@lotics/cli 0.318.37 → 0.318.38

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/dist/src/cli.js CHANGED
@@ -233,6 +233,54 @@ var LoticsRequestError = class extends Error {
233
233
  body;
234
234
  telemetryMessage;
235
235
  };
236
+ var OutcomeUnknownError = class extends Error {
237
+ constructor(waited, request_id, cause) {
238
+ super(
239
+ `No answer from the server ${waited}, so this call cannot say whether it took effect. Read the records before running it again. Request id: ${request_id}.`,
240
+ { cause }
241
+ );
242
+ this.request_id = request_id;
243
+ this.name = "OutcomeUnknownError";
244
+ }
245
+ request_id;
246
+ error_code = "outcome_unknown";
247
+ };
248
+ var NoAnswerError = class extends Error {
249
+ constructor(waited, request_id, cause) {
250
+ super(
251
+ `No answer from ${request_id === void 0 ? "storage" : "the server"} ${waited}. This call only reads, so nothing changed.${request_id === void 0 ? "" : ` Request id: ${request_id}.`}`,
252
+ { cause }
253
+ );
254
+ this.request_id = request_id;
255
+ this.name = "NoAnswerError";
256
+ }
257
+ request_id;
258
+ };
259
+ async function fetchStorage(url2, timeoutMs, read) {
260
+ try {
261
+ return await read(await fetch(url2, timeoutMs === void 0 ? {} : { signal: AbortSignal.timeout(timeoutMs) }));
262
+ } catch (error62) {
263
+ if (error62 instanceof Error && error62.name === "TimeoutError" && timeoutMs !== void 0) {
264
+ throw new NoAnswerError(`within ${timeoutMs / 1e3}s`, void 0, error62);
265
+ }
266
+ throw error62;
267
+ }
268
+ }
269
+ var NEVER_SENT_CODES = /* @__PURE__ */ new Set([
270
+ "ENOTFOUND",
271
+ "ECONNREFUSED",
272
+ "EAI_AGAIN",
273
+ "UND_ERR_CONNECT_TIMEOUT",
274
+ "CERT_HAS_EXPIRED",
275
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
276
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
277
+ "SELF_SIGNED_CERT_IN_CHAIN",
278
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
279
+ "ERR_TLS_CERT_ALTNAME_INVALID"
280
+ ]);
281
+ function errorCode(cause) {
282
+ return typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : void 0;
283
+ }
236
284
  var WEB_APP_URL = process.env.LOTICS_WEB_URL ?? "https://lotics.ai";
237
285
  var PUBLIC_FETCH_TIMEOUT_MS = 1e4;
238
286
  async function startCliLogin(apiUrl, email3) {
@@ -285,7 +333,9 @@ var LoticsClient = class {
285
333
  workspaceId;
286
334
  /** The instance this client sends every request to. */
287
335
  baseUrl;
336
+ timeoutMs;
288
337
  constructor(options) {
338
+ this.timeoutMs = options.timeoutMs;
289
339
  this.apiKey = options.apiKey;
290
340
  this.workspaceId = options.workspaceId;
291
341
  this.baseUrl = options.apiUrl;
@@ -302,7 +352,20 @@ var LoticsClient = class {
302
352
  * logs. Every call against the API passes the id its own headers carry.
303
353
  */
304
354
  async throwResponseError(response, requestId) {
305
- const text = await response.text();
355
+ const trace = requestId === void 0 ? "" : `
356
+
357
+ Request id: ${requestId} \u2014 quote this to Lotics support.`;
358
+ let text;
359
+ try {
360
+ text = await response.text();
361
+ } catch (readError) {
362
+ throw new LoticsRequestError(
363
+ `${response.status}: the server refused with HTTP ${response.status} and its error body could not be read (${readError instanceof Error ? readError.message : String(readError)})${trace}`,
364
+ response.status,
365
+ {},
366
+ `${response.status}: ${telemetryErrorMessage(response.status, {})}${trace}`
367
+ );
368
+ }
306
369
  let body = {};
307
370
  try {
308
371
  const json2 = JSON.parse(text);
@@ -313,9 +376,6 @@ var LoticsClient = class {
313
376
  const message = typeof body.message === "string" ? body.message : unparsedAnswer(text);
314
377
  const hint = typeof body.hint === "string" ? `
315
378
  ${body.hint}` : "";
316
- const trace = requestId === void 0 ? "" : `
317
-
318
- Request id: ${requestId} \u2014 quote this to Lotics support.`;
319
379
  throw new LoticsRequestError(
320
380
  `${response.status}: ${message}${hint}${trace}`,
321
381
  response.status,
@@ -357,17 +417,54 @@ var LoticsClient = class {
357
417
  headers["x-request-id"] = newRequestId();
358
418
  return headers;
359
419
  }
360
- async request(method, path17, body) {
420
+ /**
421
+ * The one transport for every call to our API. Waits for the server's answer;
422
+ * only the client's `timeoutMs` stops the wait earlier, and a lost connection
423
+ * ends it too. Either way a call that may write could have taken effect, so
424
+ * it gets `OutcomeUnknownError`, never a plain failure; a read gets
425
+ * `NoAnswerError`, because it changed nothing. `read` turns the answer into
426
+ * the result and runs inside the wait.
427
+ */
428
+ async call(method, path17, body, read) {
361
429
  const url2 = `${this.baseUrl}${path17}`;
362
430
  const headers = this.buildHeaders();
431
+ const requestId = headers["x-request-id"];
432
+ const timeoutMs = this.timeoutMs;
433
+ const readOnly = method === "GET" || method === "HEAD";
434
+ const noAnswer = (waited, cause) => readOnly ? new NoAnswerError(waited, requestId, cause) : new OutcomeUnknownError(waited, requestId, cause);
363
435
  const init = { method, headers };
364
- if (body !== void 0) {
436
+ if (timeoutMs !== void 0) init.signal = AbortSignal.timeout(timeoutMs);
437
+ if (body?.kind === "json") {
365
438
  headers["Content-Type"] = "application/json";
366
- init.body = JSON.stringify(body);
439
+ init.body = JSON.stringify(body.value);
440
+ } else if (body?.kind === "form") {
441
+ init.body = body.value;
442
+ }
443
+ try {
444
+ const response = await fetch(url2, init);
445
+ if (!response.ok) {
446
+ if (response.status >= 500 && !response.headers.has("x-request-id")) {
447
+ throw noAnswer(`before the gateway in front of it gave up (HTTP ${response.status})`);
448
+ }
449
+ await this.throwResponseError(response, requestId);
450
+ }
451
+ return await read(response);
452
+ } catch (error62) {
453
+ if (error62 instanceof LoticsRequestError || error62 instanceof OutcomeUnknownError || error62 instanceof NoAnswerError) throw error62;
454
+ if (error62 instanceof Error && error62.name === "TimeoutError" && timeoutMs !== void 0) {
455
+ throw noAnswer(`within ${timeoutMs / 1e3}s`, error62);
456
+ }
457
+ if (error62 instanceof TypeError && error62.cause !== void 0 && !NEVER_SENT_CODES.has(errorCode(error62.cause))) {
458
+ throw noAnswer("before the connection closed", error62.cause);
459
+ }
460
+ throw error62;
367
461
  }
368
- const response = await fetch(url2, init);
369
- if (!response.ok) await this.throwResponseError(response, headers["x-request-id"]);
370
- return response.json();
462
+ }
463
+ async request(method, path17, body) {
464
+ return this.call(method, path17, body === void 0 ? void 0 : { kind: "json", value: body }, async (response) => await response.json());
465
+ }
466
+ async requestForm(method, path17, form) {
467
+ return this.call(method, path17, { kind: "form", value: form }, async (response) => await response.json());
371
468
  }
372
469
  /** `email` is null for a credential no person signs in as; `account_type` is absent from an older server. */
373
470
  /** `credential_origin` describes the CREDENTIAL this call carried, not the
@@ -426,31 +523,7 @@ var LoticsClient = class {
426
523
  return this.request("GET", `/v1/tools/${encodeURIComponent(name)}`);
427
524
  }
428
525
  async execute(tool, args, options) {
429
- const body = { tool, args, format: options?.format ?? "text" };
430
- if (options?.timeoutMs) {
431
- const controller = new AbortController();
432
- const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
433
- try {
434
- const url2 = `${this.baseUrl}/v1/tools/execute`;
435
- const headers = { ...this.buildHeaders(), "Content-Type": "application/json" };
436
- const response = await fetch(url2, {
437
- method: "POST",
438
- headers,
439
- body: JSON.stringify(body),
440
- signal: controller.signal
441
- });
442
- if (!response.ok) await this.throwResponseError(response, headers["x-request-id"]);
443
- return response.json();
444
- } catch (error62) {
445
- if (error62 instanceof Error && error62.name === "AbortError") {
446
- throw new Error(`Tool execution timed out after ${options.timeoutMs}ms`);
447
- }
448
- throw error62;
449
- } finally {
450
- clearTimeout(timeout);
451
- }
452
- }
453
- return this.request("POST", "/v1/tools/execute", body);
526
+ return this.request("POST", "/v1/tools/execute", { tool, args, format: options?.format ?? "text" });
454
527
  }
455
528
  // --- Knowledge docs ---
456
529
  /**
@@ -495,9 +568,10 @@ var LoticsClient = class {
495
568
  "GET",
496
569
  `/v1/apps/${encodeURIComponent(appId)}/versions/${encodeURIComponent(versionId)}/source`
497
570
  );
498
- const response = await fetch(url2);
499
- if (!response.ok) await this.throwResponseError(response);
500
- return Buffer.from(await response.arrayBuffer());
571
+ return fetchStorage(url2, this.timeoutMs, async (response) => {
572
+ if (!response.ok) await this.throwResponseError(response);
573
+ return Buffer.from(await response.arrayBuffer());
574
+ });
501
575
  }
502
576
  /**
503
577
  * Workspace-wide dangling-reference sweep — active app/workflow artifacts
@@ -538,20 +612,13 @@ var LoticsClient = class {
538
612
  );
539
613
  if (args.prev_version_id) formData.append("prev_version_id", args.prev_version_id);
540
614
  if (args.message) formData.append("message", args.message);
541
- const url2 = `${this.baseUrl}/v1/apps/${encodeURIComponent(args.app_id)}/versions`;
542
- const headers = this.buildHeaders();
543
- const response = await fetch(url2, { method: "POST", headers, body: formData });
544
- if (!response.ok) {
545
- await this.throwResponseError(response, headers["x-request-id"]);
546
- }
547
- return response.json();
615
+ return this.requestForm("POST", `/v1/apps/${encodeURIComponent(args.app_id)}/versions`, formData);
548
616
  }
549
617
  async downloadFile(url2, outputPath) {
550
- const response = await fetch(url2);
551
- if (!response.ok) {
552
- throw new Error(`${response.status}: Failed to download file`);
553
- }
554
- const buffer = Buffer.from(await response.arrayBuffer());
618
+ const buffer = await fetchStorage(url2, this.timeoutMs, async (response) => {
619
+ if (!response.ok) throw new Error(`${response.status}: Failed to download file`);
620
+ return Buffer.from(await response.arrayBuffer());
621
+ });
555
622
  const absolutePath = path2.resolve(outputPath);
556
623
  await fs2.promises.mkdir(path2.dirname(absolutePath), { recursive: true });
557
624
  await fs2.promises.writeFile(absolutePath, buffer);
@@ -573,20 +640,12 @@ var LoticsClient = class {
573
640
  return this.request("GET", `/v1/files${query ? `?${query}` : ""}`);
574
641
  }
575
642
  async downloadFileById(fileId, destination, options) {
576
- const signedHeaders = this.buildHeaders();
577
- const signedUrlRes = await fetch(
578
- `${this.baseUrl}/v1/files/${encodeURIComponent(fileId)}/signed_url`,
579
- { headers: signedHeaders }
580
- );
581
- if (!signedUrlRes.ok) {
582
- await this.throwResponseError(signedUrlRes, signedHeaders["x-request-id"]);
583
- }
584
- const { url: url2 } = await signedUrlRes.json();
585
- const response = await fetch(url2);
586
- if (!response.ok) await this.throwResponseError(response);
587
- const disposition = response.headers.get("content-disposition") ?? "";
643
+ const { url: url2 } = await this.request("GET", `/v1/files/${encodeURIComponent(fileId)}/signed_url`);
644
+ const { disposition, buffer } = await fetchStorage(url2, this.timeoutMs, async (response) => {
645
+ if (!response.ok) await this.throwResponseError(response);
646
+ return { disposition: response.headers.get("content-disposition") ?? "", buffer: Buffer.from(await response.arrayBuffer()) };
647
+ });
588
648
  const originalFilename = parseContentDispositionFilename(disposition) ?? fileId;
589
- const buffer = Buffer.from(await response.arrayBuffer());
590
649
  const { dir, named } = destination === void 0 ? { dir: process.cwd() } : "file" in destination ? {
591
650
  dir: path2.dirname(path2.resolve(destination.file)),
592
651
  named: path2.basename(destination.file)
@@ -635,6 +694,7 @@ var LoticsClient = class {
635
694
  files.push(...result.files);
636
695
  errors.push(...result.errors);
637
696
  } catch (error62) {
697
+ if (error62 instanceof OutcomeUnknownError) throw error62;
638
698
  const message = error62 instanceof Error ? error62.message : String(error62);
639
699
  errors.push(...sent.map((item) => ({ filename: item.filename, error: message })));
640
700
  }
@@ -656,6 +716,7 @@ var LoticsClient = class {
656
716
  try {
657
717
  files.push(await this.uploadLargeFile(item));
658
718
  } catch (error62) {
719
+ if (error62 instanceof OutcomeUnknownError) throw error62;
659
720
  errors.push({
660
721
  filename: item.filename,
661
722
  error: error62 instanceof Error ? error62.message : String(error62)
@@ -758,11 +819,7 @@ var LoticsClient = class {
758
819
  const mimeType = item.mimeType ?? getMimeType(item.filename);
759
820
  formData.append("file", new Blob([item.bytes], { type: mimeType }), item.filename);
760
821
  }
761
- const url2 = `${this.baseUrl}/v1/files`;
762
- const headers = this.buildHeaders();
763
- const response = await fetch(url2, { method: "POST", headers, body: formData });
764
- if (!response.ok) await this.throwResponseError(response, headers["x-request-id"]);
765
- return response.json();
822
+ return this.requestForm("POST", "/v1/files", formData);
766
823
  }
767
824
  };
768
825
 
@@ -1753,18 +1810,20 @@ function signedLinks(result) {
1753
1810
  }
1754
1811
  return Object.values(result).flatMap(signedLinks);
1755
1812
  }
1756
- async function saveSignedLinks(links, dir) {
1813
+ async function saveSignedLinks(links, dir, timeoutMs) {
1757
1814
  const target = path6.resolve(dir);
1758
1815
  await fs6.promises.mkdir(target, { recursive: true });
1759
1816
  const saved = [];
1760
1817
  for (const link of links) {
1761
- const response = await fetch(link.url);
1762
- if (!response.ok) {
1763
- fail(`Could not fetch ${link.filename}: HTTP ${response.status}. A link is signed for an hour; run the tool again for a new one.`);
1764
- }
1818
+ const bytes = await fetchStorage(link.url, timeoutMs, async (response) => {
1819
+ if (!response.ok) {
1820
+ fail(`Could not fetch ${link.filename}: HTTP ${response.status}. A link is signed for an hour; run the tool again for a new one.`);
1821
+ }
1822
+ return Buffer.from(await response.arrayBuffer());
1823
+ });
1765
1824
  const name = findAvailableFilename(target, path6.basename(link.filename));
1766
1825
  const file2 = path6.join(target, name);
1767
- await fs6.promises.writeFile(file2, Buffer.from(await response.arrayBuffer()));
1826
+ await fs6.promises.writeFile(file2, bytes);
1768
1827
  saved.push(file2);
1769
1828
  if (link.snapshot !== void 0) {
1770
1829
  const text = path6.join(target, findAvailableFilename(target, `${path6.parse(name).name}.txt`));
@@ -1776,7 +1835,7 @@ async function saveSignedLinks(links, dir) {
1776
1835
  }
1777
1836
 
1778
1837
  // src/version.ts
1779
- var VERSION = "0.318.37";
1838
+ var VERSION = "0.318.38";
1780
1839
 
1781
1840
  // src/timezone.ts
1782
1841
  function machineTimezone() {
@@ -1825,7 +1884,7 @@ var AGENTS_default = "# @lotics/cli \u2014 agent index\n\nThe model an agent nee
1825
1884
  var building_an_app_default = '# Building an app, end to end\n\nThe other references here describe **grammars** \u2014 what a table document or an app tree may state, what a tool takes. This\none describes the **sequence**: the order the steps go in, and why. Read it once for the shape, then\nreach for the area doc (`lotics docs`) whenever you need the detail.\n\n**The live app is the only edit surface.** Every change to an app \u2014 applying a tree, deploying a\nbuild, setting one query or workflow \u2014 mints a new version of it. To go back, apply the earlier tree\nagain (or deploy the earlier source). Nothing about an app lives in a local directory the platform\nreads back.\n\n**Going back restores the app, not the data.** A table change, and every row a workflow wrote while\nyou tried it, stay where they are. Try a write on a throwaway record.\n\n---\n\n## 1 \u2014 Two kinds of app\n\n- **An app stated as a tree** \u2014 the default, and the right one for almost every job. The tree (a\n JSON file, one per app) is a List of one table, whose rows are recognised by the\n table\'s own `records`, and the page its rows open (`pages`), with the Lists and Sheets that stand beside it at the root as peers (which a change may add at any time, each a View of its own, shown to whoever the app is shared with): its columns and filters, its Sections in the order its work\n reaches them, its Acts and the Checks that guard them (`lotics docs reference/app-tree`,\n `reference/list-node`, `reference/section-node`, `reference/act-node`, `reference/check-node`). The platform\n compiles each app and draws it with the runtime every such app shares, so how each piece looks is\n the platform\'s, one way per concept, and no prop changes it. Every write the app makes is a\n generated workflow that re-checks on the server what the tables state.\n- **A custom-code app** \u2014 your own project, for a surface the tree\'s components cannot state. Its UI\n library, components, styling, state, bundler, tests and lint are yours; it reads and writes through\n `@lotics/app-sdk` (queries, workflows, files, AI).\n\n## 2 \u2014 Clarify what is being asked, before designing it\n\n**A metric name is not a definition.** "Revenue", "in stock", "active", "overdue" \u2014 each is a\nbusiness rule the person asking owns, and the cost of guessing is a screen that is confidently\nwrong. Ask until there is no ambiguity left:\n\n- Which rows count, keyed off which field \u2014 a date, a status, a flag?\n- Does the same metric need a **different rule per table**? One table may key off a date and\n another off a status; one rule rarely covers both.\n- Snapshot or flow? "Current stock" is as-of-now; "revenue this month" is a window. They compile\n to different filters.\n- If the data cannot support the definition asked for \u2014 the field simply is not there \u2014 **say so\n and show the options.** Silently substituting a near-miss produces a number nobody can trace.\n\nThis is the step that gets skipped under time pressure, and it is the only one whose mistakes are\ninvisible in review: every later artifact is correct with respect to the wrong definition.\n\n## 3 \u2014 The data model, before any app\n\nGet this wrong and nothing above it can be precise. Each kind of thing is its own table with links into\nthe spine; attributes and evidence are fields on their owner. A single table with a `type` column\nstanding in for three kinds of thing collapses the distinctions every later query needs.\n\n**Verify real VALUES, never just that a field exists.** `lotics run query_records` a sample and\nlook at fill rates \u2014 a field that is present and empty on 90% of rows will not support the screen\nyou are about to design.\n\n**That includes imagery.** If the thing has a likeness \u2014 a product, a property, a vehicle, a\nperson \u2014 its picture is the strongest identifier a register row can carry, and an empty image field\nis a data gap to fill before you design around it: `lotics file upload`, then `update_records`.\n\n**Match on ids and option aliases, never on rendered text.** Resolve a name to its `rec_\u2026` or its option alias\nonce, at the boundary, and compare those. Treat an unresolved name as UNKNOWN, never as a wildcard.\n\n**How the tables RELATE, and one fact in one column, is `lotics docs data_model`** \u2014 read it before designing a\nschema; those decisions outlive any one app.\n\n## 4 \u2014 An app stated as a tree\n\nTables first, then apps. `set_tables` takes a list of table documents, one or many, and writes them all or\nnone; `set_app` takes one app per call. Each creates when it is given no id and edits when it is given one.\n\n```\nlotics docs reference # the keys of a table document and the app tree\'s components, with a worked example\nlotics docs design # the treatment per kind of row\nlotics run set_tables @tables.json # one call, every table: {"tables": [...]}\nlotics run set_app @orders.call.json # one app: {"body": <the App tree>} to create (add "dry_run": true to check)\nlotics app apply orders.app.json --check # the same tool from a bare tree file: what would refuse it, writing nothing\nlotics app apply orders.app.json # no app known: creates it; known: edits it to the file\nlotics app pull <app_id> # the app\'s tree, as ./<name>.app.json\n```\n\nA new workspace is built in one order: one `set_tables` call with the tables, then every `set_app`\ncall, then fixes. One call carries at most 50 tables, 200 first rows a table, and 2000 rows and 2000\ndocuments in all; a workspace of more tables is built in further calls, each naming the tables already made by\ntheir ids.\n\nA table is a document: its `fields` are keyed by alias, and a link field names the table it\npoints at by id, or by the `ref` of another table of the same call, and states `multi`. A\ntwo-way link states `pair` on one table, as `true` or as a free alias, and the partner is made on the other; a many-to-many link states both sides. A table is edited by an RFC 7396 merge patch of its document:\nwhat the patch leaves alone is left alone and `null` deletes. `dry_run` checks the call and writes\nnothing; a refusal lists everything wrong in it at once.\n\nThe App node is the app: its `name`, `description`, `icon` and `color` are props of it, and no other input of\n`set_app` states them. It names the tables and templates it uses by their aliases (an entity is a table\'s alias, a `template` a template\'s alias);\n`set_app` fills the `tables` and `templates` maps by id from them and `get_app` shows aliases (`lotics docs reference/app-node`).\nWho reads which rows is the app\'s `rows` (\xA7 Who reads which rows, below). A call that creates\nis `{"body": <the App tree>}`; one that changes a part is `{"app_id": "app_\u2026", "nodes": {"<address>": <patch>}}`,\neach address a node\'s path of keys (`get_app` prints every one), a patch a JSON merge patch of that node\'s props\nand `null` removing the node; the App\'s own props change through `body`. A call stating `base_version_id` \u2014 the\nversion you read \u2014 is refused when the app has moved on. The old body grammar (`register`, `record`, `acts`,\n`edits`) is refused with a sentence pointing here.\n\nA tree states what it means once: a statement equal to what the runtime draws anyway (a column the row already shows) is kept,\ndrawn once and noted, while a statement that conflicts is refused. A register List\'s `label` is the register\'s heading in the app\'s lists; its rows are named by the table\'s own label and singular.\n`type` may be omitted, and a Section, Side or Page\nwithout a `key` is keyed by its title\'s slug, written once and kept.\n\n`app apply` with no app known creates one from the file, named by the tree\'s `name`, and records its id and\nversion in `<file>.lotics.json` (`app pull` writes the same file), so the next apply of that file edits that\napp; `--app <app_id>` names it instead, and is refused for a file whose record names another app. A known app\nis read first and only what the file changes is sent, as a JSON merge patch (RFC 7396): a key the file drops\nis removed, a list is replaced whole, and what the file leaves alone is left alone. A file pulled at a\nversion the app has since left is refused, naming the version: pull the current tree into another path and\ncarry your edits over. Applying a tree the app already has mints nothing.\n`--check` sends the same change as `dry_run`: what would refuse the tree, the notes on it, and the permissions the\nwrite would grant and remove, writing nothing. Every write\'s answer states those permissions: the saves, adds,\nDeletes and act writes the new tree grants and removes, from the previous tree to the new one.\n\n**What the tree leaves out is drawn, never stored.** The answer shows a treatment the rows call for that the tree leaves out \u2014\nReadings over its rows, a record\'s Sections, an Act per status move, a picture where its rows hold photos\n(`lotics docs design`) \u2014 and the tree states the ones the job needs. What it states with one fix, the write places\nand says (`lotics docs reference/changing-an-app`); edit only the difference.\n\n**The tree changes after the app exists, and applying it again is how it lands.** Pull the tree, edit\nthe file, apply it; or send `nodes` for one part. An Act whose write the tree cannot say names its own `workflow`; that workflow\'s code is\nthe live one, and `lotics run set_workflow` changes it. A job no press starts \u2014 an agent or a\nservice handing the app a file or a list of rows \u2014 is a Workflow node the app declares\n(`lotics docs reference/workflow-node`): the node states what it takes and hands back, and `lotics run\nset_workflow` sets its code with `inputs` and `outputs` left out of its `on({ type: "app", ... })` header.\n\n**What a person reads and does in the app, an agent reads and does through it.** Writing the tree generates a\nquery for every List, record, child List and figure the screen reads, and a workflow for every add, edit,\nremoval and act \u2014 `lotics run get_app` lists them, and `lotics docs agent_surface` names each\nfamily and how it is called. A question the screen never asks is a Query node the app declares\n(`lotics docs reference/query-node`), beside its Workflow nodes. Both are part of the design: `lotics docs\nagent_surface`, \xA7 Declaring more.\n\n### Who reads which rows\n\nAn app runs with its owner\'s access, and the people it is shared with need the app alone, never its tables. Who of them\nreads which rows is the app\'s `rows`, one rule per table in the grammar of a table\'s `read_scope` (`lotics docs reference/read-scope`); it narrows\nthe app\'s screens, its queries and workflows called through it (`run_app_query`, `run_app_workflow`), its acts and its\nworkflow bodies alike, and a record id a caller passes is refused where the rule hides the row. State a rule only where\npeople differ; a table with none is read whole by everyone the app is shared with.\n\n| The business says | The app states |\n|---|---|\n| Everyone on the team sees every order | nothing |\n| Each rep sees only their own deals | `"rows": { "deal": { "any": [{ "field": "rep", "is": "self" }] } }` |\n| Reps see their own deals; managers see all | `"rows": { "deal": { "any": [{ "field": "rep", "is": "self" }, { "member_of": "<managers group id>" }] } }` |\n| Each branch manager sees their branch\'s orders | `"rows": { "order": { "any": [{ "through": ["branch"], "field": "manager", "is": "self" }] } }` |\n| Each employee sees only their own payslips; HR sees all | two apps: one stating `"payslip": { "any": [{ "field": "employee", "is": "self" }] }`, one for HR stating none |\n| Team leads see people, not salaries | an app that draws no salary field \u2014 what it does not show, no one reads through it |\n\nA child read under a ruled row states its own rule, through its link to the parent; only a status history inherits.\nAn admin and the app\'s owner are narrowed like anyone, and the write says so when a rule hides rows from them. Someone on a public link, signed in as no one, reads no row a `self` clause would\nchoose. An app never reads past its owner\'s own access. A table\'s own `read_scope` governs opening the table directly.\nWorking inside one row of a folder (`scope`) narrows the view, not who may read: a branch app shared with every manager\nstill states the branch rule.\n\n## 5 \u2014 A custom-code app\n\n```\nlotics app create "<name>" --custom . # registers the app and links this directory (package.json#lotics)\nlotics app deploy -m "<what changed>" # build, upload, a new version live\nlotics app pull <app_id> # the live version\'s source, on a machine without the project or after another deploy\n```\n\nThe contract, and nothing more:\n\n- `@lotics/app-sdk` is React hooks and needs React 19 (`react` and `react-dom` `^19.2`); `react-router`\n (`^7` or `^8`) only for `@lotics/app-sdk/router`. Its reference is `node_modules/@lotics/app-sdk/AGENTS.md`.\n- `lotics app deploy` writes the app\'s declarations into `.lotics/` (`app_queries.d.ts` types\n `useQuery` by its aliases; include the directory in the project\'s TypeScript config), runs\n `npm run typecheck` when the project declares it, then `npm run build`, which must write a static\n `dist/` with an `index.html`. It uploads `dist/` and the source (without `node_modules`, `dist`,\n `.git`).\n- The app is a static bundle on the app host and reaches data only through the SDK.\n\nWhat the app reads and writes is bound on the app, never in the project: `lotics run\nset_app` binds named queries (`app_bindings`), `lotics run set_workflow` a workflow body, and each mints a\nversion. `useQuery("<alias>")` and `useWorkflow("<alias>")` call them. A deploy uploads the build\nand carries every binding forward unchanged.\n\n**Named queries.** Author them as `kind: "project"` with a `filter`, naming each projected column\n(`{ "source": "amount", "output": "total" }`), so a row reads as `r.total`. Scope per-user reads with\n`is_current_member` **inside the query** \u2014 a member id passed from the client is chosen by the\ncaller. Write one `description` per alias: it is the line a chat or MCP caller chooses by.\n\n**Workflows are the only way an app writes**, and every query and workflow bound to an app is also what\nan agent reads and runs there: `lotics docs agent_surface` \xA7 Declaring more states how each is shaped for\nthat caller.\n\n## 6 \u2014 Prove it, without a screen\n\nStatic checks prove parse, types and names \u2014 they evaluate nothing. Rehearse a write first:\n\n```\nlotics run set_workflow \'{"source":"on({ type: \\"app\\", app_id: \\"app_\u2026\\", alias: \\"\u2026\\" });\\n\u2026","dry_run":true,"record_id":"rec_\u2026"}\'\n```\n\nIt walks the draft through the same engine an Act\'s preview uses, under the app\'s authority: reads are real,\nwrites and sends are said and not made, and it returns what the run would answer plus the calls it would make.\nPass `preview_inputs` for the values of a workflow that takes inputs and no row.\n\nThen run it end to end, on a throwaway record:\n\n```\nlotics run run_app_query \'{"app_id":"app_\u2026","alias":"\u2026","params":{\u2026}}\'\nlotics run run_app_workflow \'{"app_id":"app_\u2026","alias":"\u2026","inputs":{\u2026}}\'\n# exits non-zero when the run failed, so it is assertable\n```\n\nA workflow is also how an app **produces a document** \u2014 `generate_document` fills a template\nyou registered once (`lotics docs document_templates`).\n\n## 7 \u2014 Look at it, then name it\n\nLook at every app you apply, at a desktop width and at a phone\'s \u2014 every check above reads the\ndefinition, none of them the pixels \u2014 and judge each shot against the visual bar `design` opens on:\n\n```\nlotics run screenshot_app \'{"app_id":"app_\u2026"}\' -o ./shots\n# one PNG per width saved into ./shots, each with its text snapshot beside it as <name>.txt;\n# "path":"/rec_\u2026" opens a screen inside the app\n```\n\nFrom the CLI each image is a link signed for an hour, and `-o` saves it. Each shot is one screen, as a member sees it; `"screen":2` draws the next screen of\nthe content scrolling inside the app, and so on to its end, and `"full_page":true` grows one image\nto the first five screens \u2014 one or the other. Beside each image comes its `snapshot`, the screen\'s\naccessibility tree as text \u2014 read it to check labels and values without opening the picture \u2014 and,\nwhere a table left columns off at that width, `shed` names them.\n\nThe app is drawn live, as you, read-only: a screen that writes when it opens shows that write\nrefused, and `errors` lists what failed on the page. A version that looks wrong is one\n`lotics app apply` away from the one before: apply the earlier tree again.\n\nFor an app stated as a tree, `verdict` comes beside the images: what a check of that app finds now,\nbeside its rows \u2014 what the next write would refuse it for and the notes\non it. `verdict_unread` says why none was read.\n\nThe app\'s `name`, `icon`, `color` and `description` are props of the App node; an app\nstating no `color` gets the platform\'s grey tile. `lotics run set_app` with the app\'s id and a `body` patch changes them\non the app, and `lotics app pull` reads the tree back as the app holds it. The\n`description` heads the capability listing the member\'s chat agent reads on **every** turn, so a\nstanding process the app expects that agent to carry out belongs there and nowhere else.\n\n**A caller outside the team gets its own app.** Sharing an app publicly, or giving an API key\naccess to it, reaches every alias the app declares; no alias can be held back. So whatever\noutsiders may call is a SECOND app over the same tables: only the queries they may read and the\nworkflows they may run. The desk the team works in stays a separate, private app. One only a server calls is an API app: `lotics docs app_bindings` \xA7 API apps.\n';
1826
1885
 
1827
1886
  // docs/cli_reference.md
1828
- var cli_reference_default = "# @lotics/cli \u2014 CLI Command Reference\n\nPer-command syntax, flags, contracts, and gotchas for the public `lotics` CLI. Start at [AGENTS.md](../AGENTS.md) for the model this reference assumes; `lotics --help` is the authoritative, always-current verb list.\n\n| Command | What it does |\n|---|---|\n| `lotics` / `lotics --help` | Show full help: capabilities, the verb list (\xA7 COMMANDS), flags, config. `lotics <verb> --help` prints that verb's entries alone (`lotics app --help`, `lotics file download --help`); `lotics report --help` prints the report frame. |\n| `lotics auth signup <email>` | Create account + org + API key, sends magic link email. Refused on a private instance, whose people arrive by invitation; prints that creating the account accepts the Terms and Privacy Policy. Registers the new org as a profile; `--local` pins this directory to it (pointer) instead of setting the global default. |\n| `lotics auth login <email>` | Sign in an account that already exists, on a machine holding no key. **Two steps, and it does not wait for the person.** The first prints the page to open \u2014 `https://lotics.ai/cli_login/<request_id>`, also mailed \u2014 and the code that page must show, records the request, and exits 0. They sign in there if asked, check the code and press Confirm. **Then the next command that needs a credential collects the key** before it does its own work, so the second step is just re-running whatever was wanted; a command run before Confirm exits 1 naming the page and the code again, and once the 15 minutes are up it says to ask again. The handful that run WITHOUT a credential \u2014 `docs` among them \u2014 claim nothing, so one of those run after Confirm still answers as though signed out. `--wait` keeps one command instead, holding the terminal until Confirm; `--local` pins this directory to that org rather than setting the global default, and implies `--wait` (a pin names THIS directory, so only the terminal that stays in it can write one). `--json` prints `organization_id`, `workspace_id` and `organization_name` when it finishes signed in, and `request_id`, `confirm_url`, `code`, `email`, `expires_at` when it is the first step. The request's secret is never printed and the org's key never leaves the store. |\n| \u2014 | **A flag is refused on a verb that does not read it**, naming the verbs that do, before any request or credential: `--check` on `lotics run` would otherwise be parsed and ignored, and the write it was meant to stop would run. `--json`, `--workspace`, `--api-key` and `--timeout` are read by every verb. |\n| `lotics auth api-key [key]` | `whoami` \u2192 **upsert** the key's org as a profile in the global store (never overwrites). The profile records the instance the key was verified against (`LOTICS_API_URL`, default `https://api.lotics.ai`), and every later command for that org goes there. `--local` additionally pins this directory to it (pointer) instead of setting the global default. |\n| `lotics auth web` | Send a magic link email to access the web app (requires auth) |\n| `lotics auth whoami` | Print active account name, email, org, resolved workspace, the instance the credential belongs to, which **kind** of credential this machine holds (a sign-in from `auth login`, or an API key \u2014 read from the saved profile, and from the server when the profile does not say, which covers `--api-key`/`LOTICS_API_KEY` and a profile saved before the field existed; unknown only when neither can say), and the resolution **source** (flag/env/local/app-manifest/global). `--json` adds `workspace_id`, `api_url`, `credential_kind` + `source`. |\n| `lotics auth logout [<name\\|id>]` | In a pinned dir: delete the local pin. Else: remove the profile (default the active org), `--all` for every one. What happens server-side depends on which KIND of credential it is. A **sign-in** (`auth login` / `auth signup`) is revoked \u2014 logging that terminal out ends its credential rather than leaving a live one behind; a server that cannot be reached, or a credential already dead, never blocks the local forget, and one line names the org and Settings \u2192 Security \u2192 *Keys and terminals*. An **API key** (`auth api-key`) is only forgotten here \u2014 an admin issued it and it is routinely on a server and on other machines, so one terminal signing out must not kill it for everyone; the line says it is still active and names both pages, because Settings \u2192 API keys is admin-only and the credential may well be the holder's own sign-in, which they revoke themselves at Settings \u2192 Security \u2192 *Keys and terminals*. A profile saved before the kind was recorded states nothing, so the SERVER is asked (`auth whoami`) and it is revoked only if the answer is a sign-in: an older server, a credential minted before the column, and a request that fails all leave it alone. |\n| \u2014 | **A refused credential says which of three ways it is dead, and names the remedy that ends its kind.** `This credential expired.` / `was revoked.` / `belongs to a member who is no longer active in this organization.` carries `Run \\`lotics auth login <email>\\` to sign in again.` for a sign-in and `Ask an admin for a new API key (Settings \u2192 API keys).` for an issued key. A credential minted before that was recorded still gets BOTH in one sentence, because nothing on the row tells them apart \u2014 so a headless box is never sent looking for a browser alone. A key the server does not recognize at all gets one flat `Invalid or disabled API key.` \u2014 deliberately, so a guessed key learns nothing, not even that it named a row. The body carries `reason` for a script to branch on, since the code stays `unauthorized` for every 401. Changing or resetting the account's password revokes its sign-ins, never an issued key. |\n| `lotics org` | List saved orgs (profiles) from the global store with the instance each belongs to, marks active for this directory (a local pin wins over the global default). |\n| `LOTICS_ORG=<name\\|id>` | Scope every command in this shell to one saved org. **Resolved once, before any command dispatches**, so a value matching no saved credential refuses every verb with one sentence \u2014 a read, a write, and a local check that needs no credential alike \u2014 and refuses it before the first byte is written. It refuses even when a credential arrives another way, because `--api-key` / `LOTICS_API_KEY` outrank it in the precedence chain and a write must never fall through to whatever THOSE name while the variable says otherwise; when the variable resolves and a key is also given, the key decides and the command says so. The refusal lists the orgs this machine holds, so it is answerable without another command (`lotics org` is refused by the same rule). A name is whatever the credential was SAVED under \u2014 a server-side rename never moves it, and the new name resolves too, so both keep working and `lotics org` prints the pair. |\n| `lotics org use <name\\|id> [--local]` | Switch the active org by org name (case-insensitive, ambiguous \u2192 error) or id. No flag \u2192 global `active_org`; `--local` \u2192 a `.lotics/config.json` pointer in the current dir. |\n| `lotics workspace` | List workspaces in the active org, marks current with `(current)` |\n| `lotics workspace select <id>` | Set the workspace in the **active scope** \u2014 a local pin if the dir has one, else the active org's global profile. Records the workspace's NAME beside its id, which is what the `lotics \u2192 <org> / <workspace>` echo prints; `workspace list`, `workspace create`, `workspace rename` and `org use` record it too, so a target is named rather than identified. Until one command has listed it, the echo prints the id and says the name is not known yet. |\n| `lotics workspace create <name> [--timezone <Area/City>] [--currency <ISO>]` | Create a new workspace (admin only), auto-switches to it. Neither flag is defaulted from THIS machine, unlike signup: an extra workspace is routinely created by an operator for somebody else. Without `--timezone` the new workspace inherits the zone of the org's OLDEST workspace; without `--currency` it takes the org's default. Both ride the create, so the workspace is never briefly denominated in a currency nobody asked for. `--currency` takes an ISO-4217 code (case-insensitive; anything else is refused). |\n| `lotics workspace rename <name>` | Rename the **current** workspace (admin only) \u2014 the endpoint takes its target from the request's workspace, never a path id, so switch with `workspace select <id>` first and read the `lotics \u2192 <org> / <workspace>` echo before trusting it \u2014 both halves are names, and the rename moves the cached one in the same act. Carries the workspace's existing `default_currency` and `timezone` through unchanged: the endpoint takes the whole settings triple, so sending only a name would blank the other two. |\n| `lotics workspace settings [--name <n>] [--currency <ISO>] [--timezone <Area/City>]` | Change the CURRENT workspace's name, default currency or timezone \u2014 `PATCH /v1/workspace`, admin only. Only what you name changes; the endpoint takes the whole triple, so the CLI carries the two you did not. `rename` is this verb with the name alone, which is why it can never forget the other two. Both values are invisible once they are wrong: the currency decides how every money field RENDERS and the zone decides how every date BUCKETS, on a workspace whose whole purpose may be to look like the customer's own. `--json` prints the updated workspace. |\n| `lotics workspace delete <id> --yes` | Delete a workspace by id (admin only). **Soft delete** \u2014 `archived_at` is set, so it drops out of listings, can no longer be selected, and its tables/records go dark, while the data is retained and recoverable. Its **apps are cascade-archived** too \u2014 every app entry point (embedded, public link, standalone subdomain, incl. anonymous public links) stops serving. Refuses the org's **only** active workspace (400) and any workspace outside the caller's org (404). Requires `--yes` to confirm (destructive; the CLI is used non-interactively). |\n| `lotics workspace doctor` | Report workspace-wide dangling schema references via `GET /v1/workspaces/dangling-references` \u2014 every active app/workflow artifact whose prefixed schema id no longer resolves, printed as `<referent.kind> \"<name>\" (<id>) \u2192 <namespace> <id> (missing)`; healthy prints a one-line all-clear. **Exits non-zero (exit 1) on findings** so scripts can gate on it. Resolves the first workspace like every data command (runs before the global workspace resolution). Admin-only. |\n| `lotics tools` | List tools by category with descriptions |\n| `lotics tools <name>` | Full description, input JSON Schema, and the output schema where the tool answers a shape, for one tool; a workflow step says to call it from a workflow body, not `lotics run` |\n| `lotics run <tool> '<json>'` | Execute a tool (text output via toModelOutput). Args may also come from a file (`lotics run <tool> @args.json`) or stdin behind the `-` sentinel (`cat args.json \\| lotics run <tool> -`) \u2014 both bypass the OS `ARG_MAX` limit for large payloads (a knowledge-doc `content`, a bulk update). A leading `@` on the args is unambiguously a file path (JSON args start with `{`). **Stdin is asked for, never guessed.** `lotics run <tool>` with no payload runs the tool with no arguments and returns at once. `lotics report` takes the same sentinel. In PowerShell use `@file`: quotes inside an inline argument are consumed by the shell, and the CLI reports the JSON it received with its quotes gone \u2014 the error names both escapes. |\n| `lotics run <tool> --json '<json>'` | Execute a tool (full JSON output) |\n| `lotics run <tool>` \u2014 **file cells** | A file in a tool's result carries its `fil_\u2026` id and metadata and **no `url`**, on every tool and in both output modes. That is not a broken file \u2014 this surface resolves no URL for a cell. Reach the bytes with `lotics file download <file_id>`, which takes the id straight from the cell; the text output says so whenever a result carries one. |\n| \u2014 | **Every tool is invoked here, including the ones that RUN something** (`run_app_workflow`, `run_app_query`) and every one that builds: `set_tables` (a list of table documents), `set_app` (one app), `set_workflow`. A command exists only for work that touches a local file: `app apply`, `app create --custom`, `app pull`, `app deploy`. |\n| \u2014 | **An app's queries and workflows take more than their params and inputs** (`lotics docs agent_surface`). `run_app_query '{\"app_id\",\"alias\",\"params\"}'` also takes `filters` and `sort` over the query's output columns, `fields` (the columns to return), `count` with `count_by` or `count_where`, `aggregate`, `limit` (200 rows at most; 50 where none is stated) and `cursor`, and `runs` \u2014 up to 20 reads in one call, each `{\"alias\", \u2026}`, a refused one answered with its `error`; one call's rows total at most 262,144 bytes. `export: {\"key\", \u2026narrowing}` instead of the read arguments makes the file an app's Export makes (`lotics docs agent_surface`). `run_app_workflow '{\"app_id\",\"alias\",\"inputs\"}'` also takes `dry_run: true` \u2014 a rehearsal on the real inputs, nothing written or sent; the answer is what the run would return, with the reads it made under `dry_run.reads`, the calls it would make under `dry_run.writes` and the papers it rendered under `dry_run.papers` and the parts of the answer it could not say under `dry_run.unpredicted`; a workflow no dry run is offered of answers `status: \"not_previewed\"` \u2014 and `runs` \u2014 up to 50 runs in order, the first refused, failed or not previewed ending the call, an input `{\"from_run\": <index>, \"path\": \"data.<key>\"}` reading an earlier run's answer. |\n| \u2014 | **The exit code reports the WORK, not just the call \u2014 for the tool that RUNS one.** `run_app_workflow` whose envelope carries a failed `status` (`error`/`failed`/`cancelled`, or `not_previewed` \u2014 a dry run asked for and not given) exit non-zero and print `<tool> \u2192 <status>: <message>` to stderr, so `lotics run \u2026 && next-step` cannot walk past a refused run. The rule is an allowlist of FAILURE \u2014 an unrecognized status exits 0, so a status added later never turns a working script red. A parked run (`awaiting_input`) is not a failure: it is waiting for an answer and the work is still live. Only a TOP-LEVEL `status` counts; one inside the data belongs to the data. Any OTHER tool's `status` is data, and exits 0. |\n| `lotics run <tool> '<json>' -o <dir>` | Also save every **signed link** the answer carries \u2014 an object with a `url`, a `filename` and the `expires_at` its signature ends at, at any depth, such as `screenshot_app`'s images. Each is fetched into `<dir>` (created if missing) under its `filename`, taking a free spelling beside a file of that name already there, and a link's `snapshot` text is written beside it as `<name>.txt`. The written paths follow the answer on **stdout**, one per line (on stderr under `--json`, whose stdout stays the one object). A link is signed for an hour; one the store no longer serves exits non-zero. A workspace file states no `expires_at` and is left to `lotics file download`. |\n| `lotics run set_members '{\"members\": {\"<email or member id>\": {\"role\": \"member\", \"name\": \"\u2026\"}}}'` | Invite, rename, change a role, remove (`null`) or restore members; `groups` keeps the member groups in the same call. Admin only: the whole input is checked before an email is sent. A member's `lotics tools` does not list it, nor `set_workspace`. View-as is the web app's preview alone; the CLI acts as the signed-in member. |\n| `lotics run <tool> --print-created` | Report the records the call created, grouped by table, with a paste-ready `delete_records` per table and the mandatory caveat naming what cannot be auto-undone (external integrations, notifications, possible sub-workflows). Works for any tool that returns a `side_effects` block, not workflows alone. |\n| `lotics run <tool> --cleanup` | Implies `--print-created`, then runs those deletes \u2014 harvested records **only**, never files / external calls / notifications. **Not a rollback**; a rollback is structurally impossible here. A partial cleanup exits non-zero so a script cannot read it as success. |\n| `lotics file upload <file\\|dir...>` (alias `lotics upload`) \xB7 `--stdin` \xB7 `--base64` \xB7 `--url <url>` | Upload files/directories. **The transport is chosen by size and is not a flag**: under 8 MiB the file is POSTed to `/v1/files`, several such files to a request up to half that route's 100 MiB cap; at or above it the CLI takes presigned part URLs and PUTs the bytes straight to object storage, so they never pass through the API. That threshold matches the AWS CLI's own `multipart_threshold`, and the number matters less than there being nothing to choose \u2014 one verb, any size, up to the 2 GiB a workspace may store. A large upload reads one part at a time, so memory stays flat regardless of file size, and a failure part-way abandons the parts already sent rather than leaving them billable and invisible. A directory expands to its immediate files; `--as <name>` renames a single upload. **Three alternative byte sources, for a caller that never had the bytes on disk** \u2014 an attachment decoded in memory, a generated document, a signed download link \u2014 each mutually exclusive with the others and with a path argument: `--stdin` takes raw bytes on stdin, `--base64` takes base64 on stdin (the shape attachments arrive in), `--url <url>` fetches the URL first. `--stdin`/`--base64` REQUIRE `--as`, because stdin carries no filename and the mime type is derived from it; `--url` falls back to `Content-Disposition` then the URL's last path segment. `--base64` decodes STRICTLY \u2014 `Buffer.from(s, \"base64\")` silently skips invalid characters and truncates on bad padding, so a corrupted pipe would otherwise store a short file that only fails when a human opens it. The `--url` fetch happens in the CLI, not the server: the URL comes from the operator running the command, so routing it through the backend would add an SSRF surface to buy what `curl` already does. |\n| `lotics file download <file_id> [<path>]` \xB7 `-o <dir>` | (alias `lotics download`) Download a stored file: `GET /v1/files/{id}/signed_url` \u2192 fetch the presigned URL and write it where you asked. **The two spellings mean two different things, and neither is read by shape: the positional `<path>` is the FILE to write, `-o <dir>` is the DIRECTORY to save into.** That is `cp` and `curl -o`, so nothing here consults an extension. A named file is written as named, its parent created, overwriting what is there \u2014 the point of naming it is that the next command opens that exact path. A directory is created if missing and written into under the stored filename (the response's `Content-Disposition`), taking a free spelling beside a file of that name already there so a repeat download never clobbers the first; with no destination at all, that filename lands in cwd. Give the destination once \u2014 a positional and `-o` together is refused, as is a positional that names an existing directory or ends in a separator (`a directory goes in -o`). The first argument is a **file id**, so a path in that slot is refused rather than sent as an id. The written path goes to **stdout** (under `--json`, `{file_id, path, filename, stored_filename}`) and the narration to stderr, so a download pipes into whatever opens it. `lotics file download record <record_id> <field_alias> [-o <dir>]` (the field named by the alias `query_records` shows it under) spreads every file on a record's file field over a DIRECTORY \u2014 there is no single file for N files to be. |\n| `lotics file list [--limit <n>] [--cursor <token>]` | The workspace's files, newest first \u2014 id, upload time, bytes, MIME type, filename on stdout, one per line (`--json` for the object). `GET /v1/files` with no `file_ids`. A file holding the content of a knowledge doc or template you cannot use is left out. **A page, not a dump**: the store only ever grows, so the last line prints the command for the next page and `next_cursor` is null on the last one. The cursor is opaque and keyset \u2014 pass it back as given \u2014 so an upload landing mid-sweep cannot make a walk skip or repeat a row. Every other file verb takes an id, so this is the only answer to \"what is in here\" short of reading Postgres. |\n| `lotics knowledge list [--include-hidden \\| --deleted]` | `GET /v1/knowledge_docs` \u2014 a table of id, name, tags, description (`--json` for the docs). **REST, not `get_workspace` kind `knowledge`**: the tool answers what the ASSISTANT may browse, and a hidden doc is out of that corpus by definition, so a tool-backed listing could never show one and the person who hid it would have no way back to it. Hidden docs are left out unless `--include-hidden` asks; those rows are marked `(hidden)`. **`--deleted` is the one tool-backed form**: it calls `get_workspace` with `kind: \"knowledge\"` and `include_archived: true`, page by page, and prints the deleted docs you can manage (id, name, deleted time, description); it cannot be combined with `--include-hidden`. |\n| `lotics knowledge create --name <n> [--description <d>] [--tags <a,b>] (--from <file.md> \\| --content <str>)` | Read the body client-side (a file XOR an inline string \u2014 exactly one required), then call `set_knowledge` with `{ name, description, content, tags? }` and no `knowledge_doc_id`, which makes a doc (description defaults to `\"\"`). `--tags` files the doc as it is made, which is the only moment a corpus reliably gets labelled. Prints the new id to stdout. Large files ride the POST body fine. |\n| `lotics knowledge get <id> [-o <file.md>]` | `GET /v1/knowledge_docs/{id}` (`getKnowledgeDoc`) \u2192 the doc with its **hydrated `content`** (the one whole-content read for a non-sandbox client; the tool `read_knowledge` reads a line range). `-o` writes the body via `writeFileAtomic`; else the body goes to stdout. `--json` prints the full doc instead. |\n| `lotics knowledge update <id> [--from <file.md> \\| --content <str>] [--name <n>] [--description <d>] [--tags <a,b>]` | Call `set_knowledge` with a `knowledge_doc_id` and **only** the provided fields (a body from --from/--content becomes `content`; the tool diffs + CASes the content change internally, so the CLI passes no `expected_content_file_id`). `--tags` REPLACES the doc's label set \u2014 the single-doc form, where the caller is looking at one doc and can state what it should carry. At least one field required; --from and --content are mutually exclusive. |\n| `lotics knowledge tag <id...> [--add <a,b>] [--remove <c,d>]` | `PATCH /v1/knowledge_docs` with `{ knowledge_doc_ids, add_tags?, remove_tags? }` \u2014 one transaction over the whole set. A **DIFF applied to each doc's own labels**, never a replacement: the docs named on one command line carry different labels, so one array across them would strip whatever the others were filed under. Removal matches case-insensitively; adding a label a doc already carries writes nothing. Ids may be separate arguments or comma-separated. At least one of --add/--remove required. |\n| `lotics knowledge hide <id...>` / `lotics knowledge unhide <id...>` | `PATCH /v1/knowledge_docs` with `{ knowledge_doc_ids, hidden }`. Hiding takes docs out of every **listing** \u2014 the Library's list, and the corpus `get_workspace` lists and its `search` searches \u2014 while leaving IAM untouched and keeping them readable **by id** (`read_knowledge` with an id, a code run staging one, an app agent's declared set). So it can never silently break an app that depends on a doc, and unhiding costs nothing. Refuses the no-argument form rather than reading it as \"everything\". |\n| `lotics knowledge rm <id...>` | Delete docs via `set_knowledge` (`{ knowledge_doc_id, delete: true }`), one call per id: each must be a live doc you manage that no app or workflow names, and the command reports which succeeded and which failed. Sharing and history are kept. The REST execute path does not gate `needsApproval`, so this runs unattended. |\n| `lotics knowledge restore <id...>` | Bring deleted docs back via `set_knowledge` (`{ knowledge_doc_id, restore: true }`), one call per id: each must be a deleted doc you manage, and the command reports which succeeded and which failed. Refuses the no-argument form. |\n| `lotics app create <name> --custom [path]` | **A custom-code app**: creates the app (`POST /v1/apps`) and links `[path]` (default `./<name>`, made when absent) to it by writing `package.json#lotics` (the app and its workspace, which is how `app deploy` in that directory finds both) \u2014 into the project's own `package.json` when it has one, every other key kept, otherwise a `package.json` holding the link alone. Nothing else is written and nothing is installed: the project is yours. `app deploy` needs `@lotics/app-sdk` (React 19) and an `npm run build` that writes a static `dist/` with an `index.html`. A directory already linked to an app is refused before the app row exists. The app has no version until the first `lotics app deploy`. `--custom` is required: a JSON app is made by `lotics app apply` (the tool `set_app`). The SDK's reference is `node_modules/@lotics/app-sdk/AGENTS.md` once the project installs it. |\n| `lotics app pull [app_id] [path]` | **An app's live definition, pulled.** The app is read with `get_app`: its author is shown a body, a JSON **tree** (with the addresses of its nodes) pulled as that tree and a custom-code app (its identity and Query nodes) as its source; an app whose stored tree does not read in this release is pulled as it is stored, with a warning giving the reason `get_app` gives (where the stored value is not a JSON object, nothing is pulled and the reason is the error); an app that shows the caller no body (the caller does not author it, or it has no version) is refused. **A JSON app**: the tree is written as JSON to `[path]` (a directory receives `./<name>.app.json`; default `./<name>.app.json`), and the app's id and current version beside it in `<file>.lotics.json` (`{ \"app_id\": \"\u2026\", \"version_id\": \"\u2026\", \"digest\": \"\u2026\" }`, the digest being the file as the CLI last left it; a record without all three is refused by `app apply`, naming `lotics app pull`) \u2014 a custom-code project records both in `package.json#lotics`, a single file has no such place \u2014 so the next `lotics app apply <file>` edits that app, and is refused if the app has since moved past that version. An existing file is overwritten only when its `.lotics.json` names this same app and the file is unchanged since it was last pulled or applied; a file with edits, or whose record names the app but no digest, is refused, naming `--force`, which overwrites it. `--force` is a flag of `app pull` alone. `--json` prints `{workspace_id, app_id, path, outcome}`. **A custom-code app**: its live source, as a project ready to deploy on it. The target is `[path]`, else this directory when it is the app's project (or no app is named), else `./<name>`. **The app's own project is brought up to date in place** \u2014 but only when it holds no edit since the version `package.json#lotics.current_version_id` names: its source (packed as a deploy packs it) is compared with that version's archive, ignoring `.lotics/` and `package.json#lotics`, and any difference refuses the pull, naming the changed files; a pull never merges, so local work is never lost. Already at the live version is a no-op that says so. **An empty or new directory receives the source whole**; any other directory is refused. Downloads come from `GET /v1/apps/{id}/versions/{version_id}/source`. `package.json#lotics` is then set to exactly the app, its workspace and the pulled version, dropping every other key an older CLI wrote there, so the next `lotics app deploy` builds on the live version; then `.lotics/` is written (`GET /v1/apps/{id}/types`) and dependencies installed (`npm ci` with a lockfile, else `npm install`, both `--ignore-scripts`). |\n| `lotics app apply <file> [--app <app_id>] [--check] [--json]` | **A JSON app, one at a time, through the tool `set_app`.** The file is an app's tree (`lotics docs reference`: the App node with the nodes under it, its tables and templates named by alias). **No app known** (no `--app`, no `<file>.lotics.json` beside it): the file is sent as `{ \"body\": \u2026 }` to make a new app, named by the body's `name`, and the id made is printed, then recorded with its version in `<file>.lotics.json`. **An app known**: its current tree is read (`get_app`) and the **RFC 7396 merge patch** that turns it into the file is sent as `body` with the `app_id` and the version the patch was computed against as `base_version_id` \u2014 a key the file drops is `null` in the patch, a list is replaced whole, what the file leaves alone is left alone, and a tree the app already has sends nothing and says so. **A file pulled at a version the app has since left is refused** where the stored tree changed since the pull (a version that moved only for a workflow's body applies) before anything is sent, naming both versions and `lotics app pull <app_id> <path>`: pull the current tree into another path, carry the edits over, apply that file. `--app` naming an app other than the sibling file's is refused too. A write that races the apply is refused by the server, which names the app's current version. A file that sets an object key to `null` is refused naming the key, since a merge patch reads `null` as a removal. `--app` names the app, else the sibling file does; an app whose `get_app` shows no body (it is not yours) is refused, **over a stored tree that does not read in this release the file is sent whole** (`set_app` with `app_id`, the file as `body` and the version read as `base_version_id`; no merge patch is computed against a tree that does not read) where it states `\"type\": \"App\"`, and any other file is refused, naming that only a whole tree replaces it; a custom-code app takes its identity (name, description, icon, colour) and, where the file states `children`, its Query nodes, which replace every query it holds; a file stating none leaves its queries alone and no `<file>.lotics.json` records it, since an identity write makes no version \u2014 its source deploys with `app deploy`. **The file is never rewritten**: a node the tree leaves out draws as the rows call for it and is stored nowhere (`lotics docs design`). It prints what `set_app` answered and reports its `outcome`: its notes and findings, every finding at once, and the saves, adds and Deletes the write grants and removes. **`--check` sends `dry_run`** (a flag of `app apply` alone, as is `--app`) \u2014 what would refuse the tree, and what it would grant and remove \u2014 and writes nothing, the file and its sibling included; an `outcome` of `refused` exits 1. A tree the app already has, or one `set_app` answers `unchanged`, records the version the app stays at in the sibling. **To go back to an earlier version, apply the earlier tree again.** Resolves and ANNOUNCES its workspace first. `--json` prints `{workspace_id, app_id, outcome, write}`, `outcome` being `set_app`'s: `created`, `updated`, `unchanged` or `refused` (with `--check`, what it would be). |\n| `lotics app deploy [-m <message>]` | **Build this directory and upload it as a new version of the live app.** Rewrites `.lotics/` with the declarations of the app's live bindings (`GET /v1/apps/{id}/types`, replacing each file there), then runs the project's `npm run typecheck` (warned about when absent; a type error in the app's own files stops the deploy, one inside an installed package is reported and does not) and `npm run build`, tars the source (without `node_modules`, `dist`, `.git`, `*.tsbuildinfo`) and `dist/`, and posts both to `POST /v1/apps/{id}/versions` on the version `package.json#lotics.current_version_id` names, then stamps the new one there. The version carries the app's queries, workflows, agents and capabilities forward unchanged \u2014 those are written through their tools. A project with no `build` script, or whose `package.json#lotics` still declares `queries`, `workflows`, `agents` or `capabilities`, is refused before anything is built; the refusal names the tool that sets each. **A 409 because another version went live since this directory's last deploy** (a deploy from elsewhere, a rollback) prints the server's sentence and the version that is live, and names `lotics app pull`: run in this directory, it brings an unedited project up to date, and lists the files a project with edits changed, to carry over into a fresh pull. `-m` (or a bare positional) is the version's message, optional. The workspace comes from `package.json#lotics.workspace_id` unless `--workspace` / `LOTICS_WORKSPACE` names another. |\n| `lotics docs` \\| `lotics docs <area>[/<section>]` \\| `lotics docs [<area>[/<section>]] --grep <text>` | **This CLI's own references, carried inside the binary** \u2014 the model reference, this index, and every doc under `docs/` \u2014 so the doc a reader opens describes the binary answering, listed by the job a reader comes to do. Capped at ONE PAGE: a doc that does not fit prints its opening and the addresses of what it holds (`lotics docs <area>/<section>`, each section's size beside it, or a table's row names), and every address prints within a page. **A reference the binary's copy lacks, or a part of one the server serves, is read from the server's `docs` tool** with this machine's credential, after the copy's refusal \u2014 a page the server added since this binary was built, which a server refusal can cite. A name matching more than one reference, or a part missing from a guide to this CLI, is answered by the copy alone. **`--grep` searches the references the server serves** (not this CLI's own guides, which it refuses), with this machine's credential, narrowed to the area or section named: literal text unless `--regex`; a literal search that finds nothing while the pattern read as an expression matches (`a|b`) returns those lines under a note saying so, and `--literal` keeps the literal zero; with `--case-sensitive`, `--diacritic-insensitive`, `--context-lines <n>` and `--limit <n>` \u2014 the dialect the knowledge lines of `get_workspace` with `search` are read in \u2014 each hit under the address that opens its page; any of those options without `--grep` is refused. A custom-code app's SDK reference ships inside `@lotics/app-sdk` in the app's `node_modules`. |\n| `lotics upgrade` | Update this CLI in place. Runs the same installer a person would, chosen by how THIS copy arrived: an npm install upgrades through npm, a script install re-runs the script \u2014 the runtime knows which (the executable is compiled, the npm bin runs under node), so nobody has to. It downloads nothing itself; resolving a version, verifying the checksum and replacing a running executable already exist in the installers, and a second copy of that inside the binary would be a second thing to get right. Replacing the binary while it runs is safe \u2014 a rename leaves the running image mapped on unix, and on Windows the installer moves the old aside precisely because the file is in use. Already current is a no-op that says so. Needs no auth. |\n| `lotics docs reference` \\| `lotics docs reference/<section>[/\u2026]` | **The reference for tables and apps, from inside the binary** \u2014 at this CLI's version; `lotics docs` lists it under \"Build an app\", after `design`. Its first page is what the documents compose with, the working order (jobs \u2192 tables and fields \u2192 `records` \u2192 one app per job \u2192 one `set_tables` call with every table, then every `set_app` call) and the section addresses; every page of it is whole. Every key of a table document and an app body, every field `type` with the config each one needs, the option / view / inline-template shapes, `records` (how a row of a table is recognised), `write_rules`, the apps (each register, record, act and check), the row format (relative dates `@today` / `@month-start` with whole-day offsets; links as `\"<table-ref>:<row-ref>\"` or a stored record's id), the rules, the caps of one `set_tables` call, and a worked example; **Offline, no account.** |\n| `lotics report '<json>'` \\| `lotics report @report.json` | File a report with the Lotics team about what got in your way. **Covers the classes telemetry structurally cannot see**: a capability that does not exist (no command ran, so nothing was recorded), a command that exited 0 having done the wrong thing, an error whose message did not name the remedy, and anything that made authoring slower than it should be. **A frame, not a paragraph** \u2014 `{goal, actual, expected?, tried?, wanted?}`, `goal` and `actual` required, unknown keys dropped rather than refused. **No severity or category.** Ingest is inline JSON, `@file`, or `-` for stdin. A bare sentence is refused with the frame printed beside it, so the fix is one step; a bare invocation prints the frame BEFORE asking for a credential, since someone whose key will not resolve is exactly who has something to report. **Not spooled**: unlike telemetry it posts inline, prints whether it landed, and exits non-zero if it did not, echoing the report back so a failed send never loses it. Runs regardless of `LOTICS_TELEMETRY` \u2014 invoking it IS the consent that passive collection needs an opt-in for \u2014 but with telemetry off there are no recorded commands to attach, and it says so rather than implying context it does not have. Requires auth. Never paste records, file contents, or credentials. **Prints the id of each frame filed** \u2014 a filing nobody can cite cannot be answered about. The ids come from the server, so an instance that only logs the frames prints the count alone; the CLI never mints one of its own, which would hand back a token that resolves to nothing. |\n\n";
1887
+ var cli_reference_default = "# @lotics/cli \u2014 CLI Command Reference\n\nPer-command syntax, flags, contracts, and gotchas for the public `lotics` CLI. Start at [AGENTS.md](../AGENTS.md) for the model this reference assumes; `lotics --help` is the authoritative, always-current verb list.\n\n| Command | What it does |\n|---|---|\n| `lotics` / `lotics --help` | Show full help: capabilities, the verb list (\xA7 COMMANDS), flags, config. `lotics <verb> --help` prints that verb's entries alone (`lotics app --help`, `lotics file download --help`); `lotics report --help` prints the report frame. |\n| `lotics auth signup <email>` | Create account + org + API key, sends magic link email. Refused on a private instance, whose people arrive by invitation; prints that creating the account accepts the Terms and Privacy Policy. Registers the new org as a profile; `--local` pins this directory to it (pointer) instead of setting the global default. |\n| `lotics auth login <email>` | Sign in an account that already exists, on a machine holding no key. **Two steps, and it does not wait for the person.** The first prints the page to open \u2014 `https://lotics.ai/cli_login/<request_id>`, also mailed \u2014 and the code that page must show, records the request, and exits 0. They sign in there if asked, check the code and press Confirm. **Then the next command that needs a credential collects the key** before it does its own work, so the second step is just re-running whatever was wanted; a command run before Confirm exits 1 naming the page and the code again, and once the 15 minutes are up it says to ask again. The handful that run WITHOUT a credential \u2014 `docs` among them \u2014 claim nothing, so one of those run after Confirm still answers as though signed out. `--wait` keeps one command instead, holding the terminal until Confirm; `--local` pins this directory to that org rather than setting the global default, and implies `--wait` (a pin names THIS directory, so only the terminal that stays in it can write one). `--json` prints `organization_id`, `workspace_id` and `organization_name` when it finishes signed in, and `request_id`, `confirm_url`, `code`, `email`, `expires_at` when it is the first step. The request's secret is never printed and the org's key never leaves the store. |\n| \u2014 | **A flag is refused on a verb that does not read it**, naming the verbs that do, before any request or credential: `--check` on `lotics run` would otherwise be parsed and ignored, and the write it was meant to stop would run. `--json`, `--workspace`, `--api-key` and `--timeout` are read by every verb. |\n| \u2014 | **Every call a verb makes waits for the server's answer**; `--timeout <ms>` (a whole number of milliseconds from 1 to 2147483647) stops each wait early. The wait ends without an answer when `--timeout` passes or no answer arrives from the server. A read with no answer changed nothing: the command exits non-zero naming the request id. A write with no answer exits non-zero with `error_code: \"outcome_unknown\"` and the request id under `--json`, because it cannot say whether the call took effect: read before running it again. The one fetch outside this is the download from an object-storage signed URL, which carries no request id and is stopped by `--timeout` alone. Under `--json` every error is one object on stdout: `error`, with `error_code` and `request_id` where the error has them. |\n| `lotics auth api-key [key]` | `whoami` \u2192 **upsert** the key's org as a profile in the global store (never overwrites). The profile records the instance the key was verified against (`LOTICS_API_URL`, default `https://api.lotics.ai`), and every later command for that org goes there. `--local` additionally pins this directory to it (pointer) instead of setting the global default. |\n| `lotics auth web` | Send a magic link email to access the web app (requires auth) |\n| `lotics auth whoami` | Print active account name, email, org, resolved workspace, the instance the credential belongs to, which **kind** of credential this machine holds (a sign-in from `auth login`, or an API key \u2014 read from the saved profile, and from the server when the profile does not say, which covers `--api-key`/`LOTICS_API_KEY` and a profile saved before the field existed; unknown only when neither can say), and the resolution **source** (flag/env/local/app-manifest/global). `--json` adds `workspace_id`, `api_url`, `credential_kind` + `source`. |\n| `lotics auth logout [<name\\|id>]` | In a pinned dir: delete the local pin. Else: remove the profile (default the active org), `--all` for every one. What happens server-side depends on which KIND of credential it is. A **sign-in** (`auth login` / `auth signup`) is revoked \u2014 logging that terminal out ends its credential rather than leaving a live one behind; a server that cannot be reached, or a credential already dead, never blocks the local forget, and one line names the org and Settings \u2192 Security \u2192 *Keys and terminals*. An **API key** (`auth api-key`) is only forgotten here \u2014 an admin issued it and it is routinely on a server and on other machines, so one terminal signing out must not kill it for everyone; the line says it is still active and names both pages, because Settings \u2192 API keys is admin-only and the credential may well be the holder's own sign-in, which they revoke themselves at Settings \u2192 Security \u2192 *Keys and terminals*. A profile saved before the kind was recorded states nothing, so the SERVER is asked (`auth whoami`) and it is revoked only if the answer is a sign-in: an older server, a credential minted before the column, and a request that fails all leave it alone. |\n| \u2014 | **A refused credential says which of three ways it is dead, and names the remedy that ends its kind.** `This credential expired.` / `was revoked.` / `belongs to a member who is no longer active in this organization.` carries `Run \\`lotics auth login <email>\\` to sign in again.` for a sign-in and `Ask an admin for a new API key (Settings \u2192 API keys).` for an issued key. A credential minted before that was recorded still gets BOTH in one sentence, because nothing on the row tells them apart \u2014 so a headless box is never sent looking for a browser alone. A key the server does not recognize at all gets one flat `Invalid or disabled API key.` \u2014 deliberately, so a guessed key learns nothing, not even that it named a row. The body carries `reason` for a script to branch on, since the code stays `unauthorized` for every 401. Changing or resetting the account's password revokes its sign-ins, never an issued key. |\n| `lotics org` | List saved orgs (profiles) from the global store with the instance each belongs to, marks active for this directory (a local pin wins over the global default). |\n| `LOTICS_ORG=<name\\|id>` | Scope every command in this shell to one saved org. **Resolved once, before any command dispatches**, so a value matching no saved credential refuses every verb with one sentence \u2014 a read, a write, and a local check that needs no credential alike \u2014 and refuses it before the first byte is written. It refuses even when a credential arrives another way, because `--api-key` / `LOTICS_API_KEY` outrank it in the precedence chain and a write must never fall through to whatever THOSE name while the variable says otherwise; when the variable resolves and a key is also given, the key decides and the command says so. The refusal lists the orgs this machine holds, so it is answerable without another command (`lotics org` is refused by the same rule). A name is whatever the credential was SAVED under \u2014 a server-side rename never moves it, and the new name resolves too, so both keep working and `lotics org` prints the pair. |\n| `lotics org use <name\\|id> [--local]` | Switch the active org by org name (case-insensitive, ambiguous \u2192 error) or id. No flag \u2192 global `active_org`; `--local` \u2192 a `.lotics/config.json` pointer in the current dir. |\n| `lotics workspace` | List workspaces in the active org, marks current with `(current)` |\n| `lotics workspace select <id>` | Set the workspace in the **active scope** \u2014 a local pin if the dir has one, else the active org's global profile. Records the workspace's NAME beside its id, which is what the `lotics \u2192 <org> / <workspace>` echo prints; `workspace list`, `workspace create`, `workspace rename` and `org use` record it too, so a target is named rather than identified. Until one command has listed it, the echo prints the id and says the name is not known yet. |\n| `lotics workspace create <name> [--timezone <Area/City>] [--currency <ISO>]` | Create a new workspace (admin only), auto-switches to it. Neither flag is defaulted from THIS machine, unlike signup: an extra workspace is routinely created by an operator for somebody else. Without `--timezone` the new workspace inherits the zone of the org's OLDEST workspace; without `--currency` it takes the org's default. Both ride the create, so the workspace is never briefly denominated in a currency nobody asked for. `--currency` takes an ISO-4217 code (case-insensitive; anything else is refused). |\n| `lotics workspace rename <name>` | Rename the **current** workspace (admin only) \u2014 the endpoint takes its target from the request's workspace, never a path id, so switch with `workspace select <id>` first and read the `lotics \u2192 <org> / <workspace>` echo before trusting it \u2014 both halves are names, and the rename moves the cached one in the same act. Carries the workspace's existing `default_currency` and `timezone` through unchanged: the endpoint takes the whole settings triple, so sending only a name would blank the other two. |\n| `lotics workspace settings [--name <n>] [--currency <ISO>] [--timezone <Area/City>]` | Change the CURRENT workspace's name, default currency or timezone \u2014 `PATCH /v1/workspace`, admin only. Only what you name changes; the endpoint takes the whole triple, so the CLI carries the two you did not. `rename` is this verb with the name alone, which is why it can never forget the other two. Both values are invisible once they are wrong: the currency decides how every money field RENDERS and the zone decides how every date BUCKETS, on a workspace whose whole purpose may be to look like the customer's own. `--json` prints the updated workspace. |\n| `lotics workspace delete <id> --yes` | Delete a workspace by id (admin only). **Soft delete** \u2014 `archived_at` is set, so it drops out of listings, can no longer be selected, and its tables/records go dark, while the data is retained and recoverable. Its **apps are cascade-archived** too \u2014 every app entry point (embedded, public link, standalone subdomain, incl. anonymous public links) stops serving. Refuses the org's **only** active workspace (400) and any workspace outside the caller's org (404). Requires `--yes` to confirm (destructive; the CLI is used non-interactively). |\n| `lotics workspace doctor` | Report workspace-wide dangling schema references via `GET /v1/workspaces/dangling-references` \u2014 every active app/workflow artifact whose prefixed schema id no longer resolves, printed as `<referent.kind> \"<name>\" (<id>) \u2192 <namespace> <id> (missing)`; healthy prints a one-line all-clear. **Exits non-zero (exit 1) on findings** so scripts can gate on it. Resolves the first workspace like every data command (runs before the global workspace resolution). Admin-only. |\n| `lotics tools` | List tools by category with descriptions |\n| `lotics tools <name>` | Full description, input JSON Schema, and the output schema where the tool answers a shape, for one tool; a workflow step says to call it from a workflow body, not `lotics run` |\n| `lotics run <tool> '<json>'` | Execute a tool (text output via toModelOutput). Args may also come from a file (`lotics run <tool> @args.json`) or stdin behind the `-` sentinel (`cat args.json \\| lotics run <tool> -`) \u2014 both bypass the OS `ARG_MAX` limit for large payloads (a knowledge-doc `content`, a bulk update). A leading `@` on the args is unambiguously a file path (JSON args start with `{`). **Stdin is asked for, never guessed.** `lotics run <tool>` with no payload runs the tool with no arguments and returns at once. `lotics report` takes the same sentinel. In PowerShell use `@file`: quotes inside an inline argument are consumed by the shell, and the CLI reports the JSON it received with its quotes gone \u2014 the error names both escapes. |\n| `lotics run <tool> --json '<json>'` | Execute a tool (full JSON output) |\n| `lotics run <tool>` \u2014 **file cells** | A file in a tool's result carries its `fil_\u2026` id and metadata and **no `url`**, on every tool and in both output modes. That is not a broken file \u2014 this surface resolves no URL for a cell. Reach the bytes with `lotics file download <file_id>`, which takes the id straight from the cell; the text output says so whenever a result carries one. |\n| \u2014 | **Every tool is invoked here, including the ones that RUN something** (`run_app_workflow`, `run_app_query`) and every one that builds: `set_tables` (a list of table documents), `set_app` (one app), `set_workflow`. A command exists only for work that touches a local file: `app apply`, `app create --custom`, `app pull`, `app deploy`. |\n| \u2014 | **An app's queries and workflows take more than their params and inputs** (`lotics docs agent_surface`). `run_app_query '{\"app_id\",\"alias\",\"params\"}'` also takes `filters` and `sort` over the query's output columns, `fields` (the columns to return), `count` with `count_by` or `count_where`, `aggregate`, `limit` (200 rows at most; 50 where none is stated) and `cursor`, and `runs` \u2014 up to 20 reads in one call, each `{\"alias\", \u2026}`, a refused one answered with its `error`; one call's rows total at most 262,144 bytes. `export: {\"key\", \u2026narrowing}` instead of the read arguments makes the file an app's Export makes (`lotics docs agent_surface`). `run_app_workflow '{\"app_id\",\"alias\",\"inputs\"}'` also takes `dry_run: true` \u2014 a rehearsal on the real inputs, nothing written or sent; the answer is what the run would return, with the reads it made under `dry_run.reads`, the calls it would make under `dry_run.writes` and the papers it rendered under `dry_run.papers` and the parts of the answer it could not say under `dry_run.unpredicted`; a workflow no dry run is offered of answers `status: \"not_previewed\"` \u2014 and `runs` \u2014 up to 50 runs in order, the first refused, failed or not previewed ending the call, an input `{\"from_run\": <index>, \"path\": \"data.<key>\"}` reading an earlier run's answer. |\n| \u2014 | **The exit code reports the WORK, not just the call \u2014 for the tool that RUNS one.** `run_app_workflow` whose envelope carries a failed `status` (`error`/`failed`/`cancelled`, or `not_previewed` \u2014 a dry run asked for and not given) exit non-zero and print `<tool> \u2192 <status>: <message>` to stderr, so `lotics run \u2026 && next-step` cannot walk past a refused run. The rule is an allowlist of FAILURE \u2014 an unrecognized status exits 0, so a status added later never turns a working script red. A parked run (`awaiting_input`) is not a failure: it is waiting for an answer and the work is still live. Only a TOP-LEVEL `status` counts; one inside the data belongs to the data. Any OTHER tool's `status` is data, and exits 0. |\n| `lotics run <tool> '<json>' -o <dir>` | Also save every **signed link** the answer carries \u2014 an object with a `url`, a `filename` and the `expires_at` its signature ends at, at any depth, such as `screenshot_app`'s images. Each is fetched into `<dir>` (created if missing) under its `filename`, taking a free spelling beside a file of that name already there, and a link's `snapshot` text is written beside it as `<name>.txt`. The written paths follow the answer on **stdout**, one per line (on stderr under `--json`, whose stdout stays the one object). A link is signed for an hour; one the store no longer serves exits non-zero. A workspace file states no `expires_at` and is left to `lotics file download`. |\n| `lotics run set_members '{\"members\": {\"<email or member id>\": {\"role\": \"member\", \"name\": \"\u2026\"}}}'` | Invite, rename, change a role, remove (`null`) or restore members; `groups` keeps the member groups in the same call. Admin only: the whole input is checked before an email is sent. A member's `lotics tools` does not list it, nor `set_workspace`. View-as is the web app's preview alone; the CLI acts as the signed-in member. |\n| `lotics run <tool> --print-created` | Report the records the call created, grouped by table, with a paste-ready `delete_records` per table and the mandatory caveat naming what cannot be auto-undone (external integrations, notifications, possible sub-workflows). Works for any tool that returns a `side_effects` block, not workflows alone. |\n| `lotics run <tool> --cleanup` | Implies `--print-created`, then runs those deletes \u2014 harvested records **only**, never files / external calls / notifications. **Not a rollback**; a rollback is structurally impossible here. A partial cleanup exits non-zero so a script cannot read it as success. |\n| `lotics file upload <file\\|dir...>` (alias `lotics upload`) \xB7 `--stdin` \xB7 `--base64` \xB7 `--url <url>` | Upload files/directories. **The transport is chosen by size and is not a flag**: under 8 MiB the file is POSTed to `/v1/files`, several such files to a request up to half that route's 100 MiB cap; at or above it the CLI takes presigned part URLs and PUTs the bytes straight to object storage, so they never pass through the API. That threshold matches the AWS CLI's own `multipart_threshold`, and the number matters less than there being nothing to choose \u2014 one verb, any size, up to the 2 GiB a workspace may store. A large upload reads one part at a time, so memory stays flat regardless of file size, and a failure part-way abandons the parts already sent rather than leaving them billable and invisible. A directory expands to its immediate files; `--as <name>` renames a single upload. **Three alternative byte sources, for a caller that never had the bytes on disk** \u2014 an attachment decoded in memory, a generated document, a signed download link \u2014 each mutually exclusive with the others and with a path argument: `--stdin` takes raw bytes on stdin, `--base64` takes base64 on stdin (the shape attachments arrive in), `--url <url>` fetches the URL first. `--stdin`/`--base64` REQUIRE `--as`, because stdin carries no filename and the mime type is derived from it; `--url` falls back to `Content-Disposition` then the URL's last path segment. `--base64` decodes STRICTLY \u2014 `Buffer.from(s, \"base64\")` silently skips invalid characters and truncates on bad padding, so a corrupted pipe would otherwise store a short file that only fails when a human opens it. The `--url` fetch happens in the CLI, not the server: the URL comes from the operator running the command, so routing it through the backend would add an SSRF surface to buy what `curl` already does. |\n| `lotics file download <file_id> [<path>]` \xB7 `-o <dir>` | (alias `lotics download`) Download a stored file: `GET /v1/files/{id}/signed_url` \u2192 fetch the presigned URL and write it where you asked. **The two spellings mean two different things, and neither is read by shape: the positional `<path>` is the FILE to write, `-o <dir>` is the DIRECTORY to save into.** That is `cp` and `curl -o`, so nothing here consults an extension. A named file is written as named, its parent created, overwriting what is there \u2014 the point of naming it is that the next command opens that exact path. A directory is created if missing and written into under the stored filename (the response's `Content-Disposition`), taking a free spelling beside a file of that name already there so a repeat download never clobbers the first; with no destination at all, that filename lands in cwd. Give the destination once \u2014 a positional and `-o` together is refused, as is a positional that names an existing directory or ends in a separator (`a directory goes in -o`). The first argument is a **file id**, so a path in that slot is refused rather than sent as an id. The written path goes to **stdout** (under `--json`, `{file_id, path, filename, stored_filename}`) and the narration to stderr, so a download pipes into whatever opens it. `lotics file download record <record_id> <field_alias> [-o <dir>]` (the field named by the alias `query_records` shows it under) spreads every file on a record's file field over a DIRECTORY \u2014 there is no single file for N files to be. |\n| `lotics file list [--limit <n>] [--cursor <token>]` | The workspace's files, newest first \u2014 id, upload time, bytes, MIME type, filename on stdout, one per line (`--json` for the object). `GET /v1/files` with no `file_ids`. A file holding the content of a knowledge doc or template you cannot use is left out. **A page, not a dump**: the store only ever grows, so the last line prints the command for the next page and `next_cursor` is null on the last one. The cursor is opaque and keyset \u2014 pass it back as given \u2014 so an upload landing mid-sweep cannot make a walk skip or repeat a row. Every other file verb takes an id, so this is the only answer to \"what is in here\" short of reading Postgres. |\n| `lotics knowledge list [--include-hidden \\| --deleted]` | `GET /v1/knowledge_docs` \u2014 a table of id, name, tags, description (`--json` for the docs). **REST, not `get_workspace` kind `knowledge`**: the tool answers what the ASSISTANT may browse, and a hidden doc is out of that corpus by definition, so a tool-backed listing could never show one and the person who hid it would have no way back to it. Hidden docs are left out unless `--include-hidden` asks; those rows are marked `(hidden)`. **`--deleted` is the one tool-backed form**: it calls `get_workspace` with `kind: \"knowledge\"` and `include_archived: true`, page by page, and prints the deleted docs you can manage (id, name, deleted time, description); it cannot be combined with `--include-hidden`. |\n| `lotics knowledge create --name <n> [--description <d>] [--tags <a,b>] (--from <file.md> \\| --content <str>)` | Read the body client-side (a file XOR an inline string \u2014 exactly one required), then call `set_knowledge` with `{ name, description, content, tags? }` and no `knowledge_doc_id`, which makes a doc (description defaults to `\"\"`). `--tags` files the doc as it is made, which is the only moment a corpus reliably gets labelled. Prints the new id to stdout. Large files ride the POST body fine. |\n| `lotics knowledge get <id> [-o <file.md>]` | `GET /v1/knowledge_docs/{id}` (`getKnowledgeDoc`) \u2192 the doc with its **hydrated `content`** (the one whole-content read for a non-sandbox client; the tool `read_knowledge` reads a line range). `-o` writes the body via `writeFileAtomic`; else the body goes to stdout. `--json` prints the full doc instead. |\n| `lotics knowledge update <id> [--from <file.md> \\| --content <str>] [--name <n>] [--description <d>] [--tags <a,b>]` | Call `set_knowledge` with a `knowledge_doc_id` and **only** the provided fields (a body from --from/--content becomes `content`; the tool diffs + CASes the content change internally, so the CLI passes no `expected_content_file_id`). `--tags` REPLACES the doc's label set \u2014 the single-doc form, where the caller is looking at one doc and can state what it should carry. At least one field required; --from and --content are mutually exclusive. |\n| `lotics knowledge tag <id...> [--add <a,b>] [--remove <c,d>]` | `PATCH /v1/knowledge_docs` with `{ knowledge_doc_ids, add_tags?, remove_tags? }` \u2014 one transaction over the whole set. A **DIFF applied to each doc's own labels**, never a replacement: the docs named on one command line carry different labels, so one array across them would strip whatever the others were filed under. Removal matches case-insensitively; adding a label a doc already carries writes nothing. Ids may be separate arguments or comma-separated. At least one of --add/--remove required. |\n| `lotics knowledge hide <id...>` / `lotics knowledge unhide <id...>` | `PATCH /v1/knowledge_docs` with `{ knowledge_doc_ids, hidden }`. Hiding takes docs out of every **listing** \u2014 the Library's list, and the corpus `get_workspace` lists and its `search` searches \u2014 while leaving IAM untouched and keeping them readable **by id** (`read_knowledge` with an id, a code run staging one, an app agent's declared set). So it can never silently break an app that depends on a doc, and unhiding costs nothing. Refuses the no-argument form rather than reading it as \"everything\". |\n| `lotics knowledge rm <id...>` | Delete docs via `set_knowledge` (`{ knowledge_doc_id, delete: true }`), one call per id: each must be a live doc you manage that no app or workflow names, and the command reports which succeeded and which failed. Sharing and history are kept. The REST execute path does not gate `needsApproval`, so this runs unattended. |\n| `lotics knowledge restore <id...>` | Bring deleted docs back via `set_knowledge` (`{ knowledge_doc_id, restore: true }`), one call per id: each must be a deleted doc you manage, and the command reports which succeeded and which failed. Refuses the no-argument form. |\n| `lotics app create <name> --custom [path]` | **A custom-code app**: creates the app (`POST /v1/apps`) and links `[path]` (default `./<name>`, made when absent) to it by writing `package.json#lotics` (the app and its workspace, which is how `app deploy` in that directory finds both) \u2014 into the project's own `package.json` when it has one, every other key kept, otherwise a `package.json` holding the link alone. Nothing else is written and nothing is installed: the project is yours. `app deploy` needs `@lotics/app-sdk` (React 19) and an `npm run build` that writes a static `dist/` with an `index.html`. A directory already linked to an app is refused before the app row exists. The app has no version until the first `lotics app deploy`. `--custom` is required: a JSON app is made by `lotics app apply` (the tool `set_app`). The SDK's reference is `node_modules/@lotics/app-sdk/AGENTS.md` once the project installs it. |\n| `lotics app pull [app_id] [path]` | **An app's live definition, pulled.** The app is read with `get_app`: its author is shown a body, a JSON **tree** (with the addresses of its nodes) pulled as that tree and a custom-code app (its identity and Query nodes) as its source; an app whose stored tree does not read in this release is pulled as it is stored, with a warning giving the reason `get_app` gives (where the stored value is not a JSON object, nothing is pulled and the reason is the error); an app that shows the caller no body (the caller does not author it, or it has no version) is refused. **A JSON app**: the tree is written as JSON to `[path]` (a directory receives `./<name>.app.json`; default `./<name>.app.json`), and the app's id and current version beside it in `<file>.lotics.json` (`{ \"app_id\": \"\u2026\", \"version_id\": \"\u2026\", \"digest\": \"\u2026\" }`, the digest being the file as the CLI last left it; a record without all three is refused by `app apply`, naming `lotics app pull`) \u2014 a custom-code project records both in `package.json#lotics`, a single file has no such place \u2014 so the next `lotics app apply <file>` edits that app, and is refused if the app has since moved past that version. An existing file is overwritten only when its `.lotics.json` names this same app and the file is unchanged since it was last pulled or applied; a file with edits, or whose record names the app but no digest, is refused, naming `--force`, which overwrites it. `--force` is a flag of `app pull` alone. `--json` prints `{workspace_id, app_id, path, outcome}`. **A custom-code app**: its live source, as a project ready to deploy on it. The target is `[path]`, else this directory when it is the app's project (or no app is named), else `./<name>`. **The app's own project is brought up to date in place** \u2014 but only when it holds no edit since the version `package.json#lotics.current_version_id` names: its source (packed as a deploy packs it) is compared with that version's archive, ignoring `.lotics/` and `package.json#lotics`, and any difference refuses the pull, naming the changed files; a pull never merges, so local work is never lost. Already at the live version is a no-op that says so. **An empty or new directory receives the source whole**; any other directory is refused. Downloads come from `GET /v1/apps/{id}/versions/{version_id}/source`. `package.json#lotics` is then set to exactly the app, its workspace and the pulled version, dropping every other key an older CLI wrote there, so the next `lotics app deploy` builds on the live version; then `.lotics/` is written (`GET /v1/apps/{id}/types`) and dependencies installed (`npm ci` with a lockfile, else `npm install`, both `--ignore-scripts`). |\n| `lotics app apply <file> [--app <app_id>] [--check] [--json]` | **A JSON app, one at a time, through the tool `set_app`.** The file is an app's tree (`lotics docs reference`: the App node with the nodes under it, its tables and templates named by alias). **No app known** (no `--app`, no `<file>.lotics.json` beside it): the file is sent as `{ \"body\": \u2026 }` to make a new app, named by the body's `name`, and the id made is printed, then recorded with its version in `<file>.lotics.json`. **An app known**: its current tree is read (`get_app`) and the **RFC 7396 merge patch** that turns it into the file is sent as `body` with the `app_id` and the version the patch was computed against as `base_version_id` \u2014 a key the file drops is `null` in the patch, a list is replaced whole, what the file leaves alone is left alone, and a tree the app already has sends nothing and says so. **A file pulled at a version the app has since left is refused** where the stored tree changed since the pull (a version that moved only for a workflow's body applies) before anything is sent, naming both versions and `lotics app pull <app_id> <path>`: pull the current tree into another path, carry the edits over, apply that file. `--app` naming an app other than the sibling file's is refused too. A write that races the apply is refused by the server, which names the app's current version. A file that sets an object key to `null` is refused naming the key, since a merge patch reads `null` as a removal. `--app` names the app, else the sibling file does; an app whose `get_app` shows no body (it is not yours) is refused, **over a stored tree that does not read in this release the file is sent whole** (`set_app` with `app_id`, the file as `body` and the version read as `base_version_id`; no merge patch is computed against a tree that does not read) where it states `\"type\": \"App\"`, and any other file is refused, naming that only a whole tree replaces it; a custom-code app takes its identity (name, description, icon, colour) and, where the file states `children`, its Query nodes, which replace every query it holds; a file stating none leaves its queries alone and no `<file>.lotics.json` records it, since an identity write makes no version \u2014 its source deploys with `app deploy`. **The file is never rewritten**: a node the tree leaves out draws as the rows call for it and is stored nowhere (`lotics docs design`). It prints what `set_app` answered and reports its `outcome`: its notes and findings, every finding at once, and the saves, adds and Deletes the write grants and removes. **`--check` sends `dry_run`** (a flag of `app apply` alone, as is `--app`) \u2014 what would refuse the tree, and what it would grant and remove \u2014 and writes nothing, the file and its sibling included; an `outcome` of `refused` exits 1. A tree the app already has, or one `set_app` answers `unchanged`, records the version the app stays at in the sibling. **To go back to an earlier version, apply the earlier tree again.** Resolves and ANNOUNCES its workspace first. `--json` prints `{workspace_id, app_id, outcome, write}`, `outcome` being `set_app`'s: `created`, `updated`, `unchanged` or `refused` (with `--check`, what it would be). |\n| `lotics app deploy [-m <message>]` | **Build this directory and upload it as a new version of the live app.** Rewrites `.lotics/` with the declarations of the app's live bindings (`GET /v1/apps/{id}/types`, replacing each file there), then runs the project's `npm run typecheck` (warned about when absent; a type error in the app's own files stops the deploy, one inside an installed package is reported and does not) and `npm run build`, tars the source (without `node_modules`, `dist`, `.git`, `*.tsbuildinfo`) and `dist/`, and posts both to `POST /v1/apps/{id}/versions` on the version `package.json#lotics.current_version_id` names, then stamps the new one there. The version carries the app's queries, workflows, agents and capabilities forward unchanged \u2014 those are written through their tools. A project with no `build` script, or whose `package.json#lotics` still declares `queries`, `workflows`, `agents` or `capabilities`, is refused before anything is built; the refusal names the tool that sets each. **A 409 because another version went live since this directory's last deploy** (a deploy from elsewhere, a rollback) prints the server's sentence and the version that is live, and names `lotics app pull`: run in this directory, it brings an unedited project up to date, and lists the files a project with edits changed, to carry over into a fresh pull. `-m` (or a bare positional) is the version's message, optional. The workspace comes from `package.json#lotics.workspace_id` unless `--workspace` / `LOTICS_WORKSPACE` names another. |\n| `lotics docs` \\| `lotics docs <area>[/<section>]` \\| `lotics docs [<area>[/<section>]] --grep <text>` | **This CLI's own references, carried inside the binary** \u2014 the model reference, this index, and every doc under `docs/` \u2014 so the doc a reader opens describes the binary answering, listed by the job a reader comes to do. Capped at ONE PAGE: a doc that does not fit prints its opening and the addresses of what it holds (`lotics docs <area>/<section>`, each section's size beside it, or a table's row names), and every address prints within a page. **A reference the binary's copy lacks, or a part of one the server serves, is read from the server's `docs` tool** with this machine's credential, after the copy's refusal \u2014 a page the server added since this binary was built, which a server refusal can cite. A name matching more than one reference, or a part missing from a guide to this CLI, is answered by the copy alone. **`--grep` searches the references the server serves** (not this CLI's own guides, which it refuses), with this machine's credential, narrowed to the area or section named: literal text unless `--regex`; a literal search that finds nothing while the pattern read as an expression matches (`a|b`) returns those lines under a note saying so, and `--literal` keeps the literal zero; with `--case-sensitive`, `--diacritic-insensitive`, `--context-lines <n>` and `--limit <n>` \u2014 the dialect the knowledge lines of `get_workspace` with `search` are read in \u2014 each hit under the address that opens its page; any of those options without `--grep` is refused. A custom-code app's SDK reference ships inside `@lotics/app-sdk` in the app's `node_modules`. |\n| `lotics upgrade` | Update this CLI in place. Runs the same installer a person would, chosen by how THIS copy arrived: an npm install upgrades through npm, a script install re-runs the script \u2014 the runtime knows which (the executable is compiled, the npm bin runs under node), so nobody has to. It downloads nothing itself; resolving a version, verifying the checksum and replacing a running executable already exist in the installers, and a second copy of that inside the binary would be a second thing to get right. Replacing the binary while it runs is safe \u2014 a rename leaves the running image mapped on unix, and on Windows the installer moves the old aside precisely because the file is in use. Already current is a no-op that says so. Needs no auth. |\n| `lotics docs reference` \\| `lotics docs reference/<section>[/\u2026]` | **The reference for tables and apps, from inside the binary** \u2014 at this CLI's version; `lotics docs` lists it under \"Build an app\", after `design`. Its first page is what the documents compose with, the working order (jobs \u2192 tables and fields \u2192 `records` \u2192 one app per job \u2192 one `set_tables` call with every table, then every `set_app` call) and the section addresses; every page of it is whole. Every key of a table document and an app body, every field `type` with the config each one needs, the option / view / inline-template shapes, `records` (how a row of a table is recognised), `write_rules`, the apps (each register, record, act and check), the row format (relative dates `@today` / `@month-start` with whole-day offsets; links as `\"<table-ref>:<row-ref>\"` or a stored record's id), the rules, the caps of one `set_tables` call, and a worked example; **Offline, no account.** |\n| `lotics report '<json>'` \\| `lotics report @report.json` | File a report with the Lotics team about what got in your way. **Covers the classes telemetry structurally cannot see**: a capability that does not exist (no command ran, so nothing was recorded), a command that exited 0 having done the wrong thing, an error whose message did not name the remedy, and anything that made authoring slower than it should be. **A frame, not a paragraph** \u2014 `{goal, actual, expected?, tried?, wanted?}`, `goal` and `actual` required, unknown keys dropped rather than refused. **No severity or category.** Ingest is inline JSON, `@file`, or `-` for stdin. A bare sentence is refused with the frame printed beside it, so the fix is one step; a bare invocation prints the frame BEFORE asking for a credential, since someone whose key will not resolve is exactly who has something to report. **Not spooled**: unlike telemetry it posts inline, prints whether it landed, and exits non-zero if it did not, echoing the report back so a failed send never loses it. Runs regardless of `LOTICS_TELEMETRY` \u2014 invoking it IS the consent that passive collection needs an opt-in for \u2014 but with telemetry off there are no recorded commands to attach, and it says so rather than implying context it does not have. Requires auth. Never paste records, file contents, or credentials. **Prints the id of each frame filed** \u2014 a filing nobody can cite cannot be answered about. The ids come from the server, so an instance that only logs the frames prints the count alone; the CLI never mints one of its own, which would hand back a token that resolves to nothing. |\n\n";
1829
1888
 
1830
1889
  // docs/data_model.md
1831
1890
  var data_model_default = '# The data model \u2014 tables, their fields, and how they relate\n\nThe decisions here outlive any one app, and most become expensive the moment a second screen depends\non them. They stand apart from building an app on purpose: **every workspace starts with tables\nand many never get an app**, so schema design is not a chapter of app building.\n\nThe rules below share one signature. **Both sides read correctly on their own**, so nothing reports\nthe problem \u2014 no error, no empty column, no failing query. Each is found by looking for it. Then,\nunder **Fields**, what each field type takes.\n\n## One fact, one column\n\n**Read the table\'s existing fields first (`get_table`), and add nothing that stores a fact the table already\nstores.** A value written as text and the same value held as a `link` are one fact in\ntwo columns \u2014 a customer\'s city typed into a text box beside a link to the city record, a status\nword beside the select that decides it, a total beside the formula that computes it.\n\nTwo columns for one fact do not stay equal. Some writer sets only one of them, and nothing reports\nthe divergence: both rows still look correct on their own. A reader that then matches on the text\nhalf treats "Acme" and "Acme Ltd" as different records, so an import creates a duplicate every time\nit runs.\n\n- **Prefer the link, the select, or the formula.** Text is a RENDERING of a record; compose it when\n you read, rather than storing it a second time.\n- **Renaming, retyping or re-pointing the existing field beats adding another.** A field\'s key is\n stable, so a rename breaks nothing that addresses it by key.\n- **Superseding a field means DELETING it**, not leaving it beside its replacement with a\n description that says which one is real.\n- **Empty is not the same as redundant.** A field nothing fills may still be the only home for a\n real distinction \u2014 read what it MEANS before removing it.\n- **A stored field becomes required only once every row holds a value**, so it always holds one: fill the\n empty cells first, then set it. A computed field\'s flag is checked as each row is written.\n\n## One entity, one table \u2014 and the test is measurable\n\nVariation belongs in a column \u2014 a multi-select role, a kind, a stage \u2014 not in a second table. Two\ntables for one kind of thing give the same real-world entity two rows, two ids and two halves of its\nhistory, and each screen shows whichever half it happens to link to.\n\nSplit tables are often right. A supplier book beside a customer book is a normal shape, and merging\non suspicion is a large repoint bought for nothing. So do not argue it in the abstract:\n\n> **List both tables\' names and look for one that appears in both.**\n\nNone means the split is holding. One means it has broken \u2014 the usual cause is a party you begin to\ninvoice as well as buy from \u2014 and the fix is to merge before a second screen depends on the copy.\n\n## One vocabulary wherever values are COPIED between tables\n\nTwo `select` fields for one concept carry different option keys even when their labels match. Copy an option by its\nalias or label: the record tools match an option by alias or label, so a value copied by alias lands\non the option of that alias on the other field. Prefer a link to a shared reference table where the set is open or\ngrowing. Where one side holds more values than the other, the wider side must **refuse** what the narrower one cannot\nexpress rather than quietly picking the nearest value.\n\nA value read through a link or a lookup reads exactly as the same field would on its own row: an option written by its alias in\na body and read as its key, a member or a link by its id. A value a check matches\nacross tables is a link to one table: two selects never compare, and a save that compares them is refused, in a check\'s lookup too. A filter or a write on another table\'s select takes a value read from this one by its alias, else its label.\n\nA lookup reads as one flat list of the values it looks up, in a check and in every body: `first(record.x)` is the one value through a one-row link and `includes(record.x, v)` asks whether any row holds `v`; two selects never compare, so a value matched across tables is a link to one table. A single member, a single select, a number or a text reads as the value itself, and `first(...)` of one is refused when the body is saved. A rollup that adds up (a sum, a count) over no rows is 0, never empty, as `sum` over an empty list is; a min, a max or an average over no rows is empty.\n\n## A copy boundary accounts for EVERY source field\n\nEach field on the source gets a column on the destination, a deliberate drop with the reason written\ndown, or a refusal.\n\nA field with nowhere to land is data destroyed at the boundary, and it is invisible afterwards: the\ndestination is not empty and not obviously wrong \u2014 just a number that no longer agrees with where it\ncame from.\n\n## Provenance is a LINK, not a flag and not a copy\n\nA row created BY another row carries a link to it.\n\nThat link is what makes "is this the estimate or the actual", "where did this come from" and "have we\nalready imported this" answerable at all. A boolean records that something was true once; a link\nstays true, survives a rename, and lets the next write UPDATE the original instead of adding a second\nrow beside it.\n\n## Say what makes two rows the SAME row\n\nState it as the table\'s `natural_key` (`reference/write-rules`); a text key is also `unique`.\n\nAnything that imports, reconciles or de-duplicates has to decide identity, and with no declared key it falls back to\ncomparing displayed text \u2014 which is how one company arrives three times under three spellings. Name the key: a reference\nnumber, a tax id, a link plus a period. Then match on record ids and option aliases, never on rendered labels.\n\n## A stage\'s moment is a date on the row\n\nWho changed what, and when, is the platform\'s audit trail, which an agent already reads (`query_audit_logs`) under\nits own access to the table \u2014 so it is never a table of yours, and an app shows none of it: a history an app shows is\ntable-backed (`records.status.dates`, `records.status.history`, an event table an act makes).\n\nWhen the business reports, filters or prints the moment a row reached a stage (completed on, cancelled on), that\nmoment is a `date` field of the row, as `completed_at` and `canceled_at` are in SQL. State it as `records.status.dates`\n(`reference/status`): option \u2192 date. The record write path stamps it as a row is made at the option or moved into it,\nwhoever writes, so no one has to remember; a value the same write states wins, which loads past data as it happened. The\nplatform never clears a stamp: each date is when the row last entered the option, and leaving keeps it, and putting a\nchange back restamps nothing. A date range is a span, never a moment, so it is refused. It is the one way a status is\ntimed: a stage\'s `within` runs from its date, a straight-line process is one select whose options are its steps, each\ndated, and the stage is never read off a run of dates.\n\n`records.status.history` is for a business that reports on every move \u2014 moves per person, or time in a stage a row\nre-enters \u2014 and the platform appends one row per move. An event that carries facts of its own (a reason, an amount, a\nsignature, an inspection\'s findings) is its own table with those fields, made by the act that records it.\n\n## Keep derived chains shallow\n\nFormulas and rollups are computed and STORED when a row is written, and one that reads another recomputes with it. A\nrollup over a formula over a formula is paid three times on every touch, and again for every row upstream of it.\n**Depth costs more than row count**: chain depth is yours to keep down, row scanning is the platform\'s.\n\n## Fields\n\nA field is stated inside its table\'s document in a `set_tables` call, keyed by alias. A name people read (a\ntable\'s, a field\'s, an option\'s) is in the owner\'s language; an alias stays English. Every field `type`, the\nkeys each one takes (notation, defaults, options, links, formulas, rollups, lookups, copies) and a worked\nexample are in `docs path="reference/field"`; this page holds the choices around them.\n\n### Types and formats\n\n`type` is one of `text`, `number`, `date`, `boolean`, `select`, `member`,\n`link`, `files`, `formula`, `rollup`, `lookup`, `autonumber`.\n\nA URL, an email, markdown, a checkbox, a datetime, money, a quantity or a percentage is a `format`\nor a `notation` on another type, never a `type`:\n\n| Wanted | Field |\n|---|---|\n| URL or external link | `{ type: "text", format: "link" }` |\n| Email or phone | `{ type: "text" }` |\n| Markdown | `{ type: "text", format: "markdown" }` |\n| Checkbox | `{ type: "boolean" }` |\n| Money | `{ type: "number", notation: { style: "currency", currency: "USD" } }` |\n| Quantity | `{ type: "number", notation: { style: "unit", unit: "kg" } }` |\n| Percentage | `{ type: "number", notation: { style: "unit", unit: "percent" } }` |\n| Datetime | `{ type: "date", format: "datetime" }` |\n| Date range | `{ type: "date", format: "date_range" }` |\n\n### Changing a field\n\nRead the table with `get_table`, which answers its document exactly as `set_tables` takes it, then send `set_tables` with\nthe `table_id` and only what changes. The table is edited by an RFC 7396 merge patch of its document, so what the patch\nleaves alone is left alone and `null` deletes the field it names. Every key a table and a field take is in\n`docs path="reference/tables"` and `reference/field`.\n\nA table is named by its alias wherever a call names one (`table_id`, a link\'s `table`, a lookup, `records.history`), and a new table in the call is named by its `ref`, which becomes its alias. The alias is kept while the table exists, archived or not: asking for one an archived table holds is refused, offering to restore that table or to choose another alias. A filter in a table document (a rollup\'s `filter`, `options_where`, a colour\'s condition, a check\'s lookup) takes the record tools\' operators and values (`is`, `is_any_of`, `gte`, a plain date as a day). An `autonumber` field takes `next` (`"next": 232`): the number its next row gets, refused below the highest already issued.\n\n- **A list is replaced whole**, so an option cannot be nulled. To rename, recolour, add or remove an option, restate the\n field\'s whole `options` list, each option with its alias (`reference/field/select`). A rename changes the label and every\n record keeps its value; an alias left out is removed, which needs `force` while rows hold it.\n- **A number field becomes an `autonumber`** when every row holds its own whole number of 1 or more: the numbers are kept\n and the next row takes the one after the highest (a `next` must be above it). Otherwise the call is refused, saying how\n many rows are blank, repeated or not whole, with up to 5 row ids. No other type converts to or from an autonumber; add\n one as a new field, which numbers the rows already there from 1 (or from `next`) in creation order.\n- **Splitting an option is a rename plus an add.** The old option keeps its alias and takes the first part\'s label, so its\n rows and every app reference to it keep working; the second part is a new option. Rows that belong to the second part\n are then moved by a filtered `update_records`.\n- **A status history holds every option its status ever had** and follows them in the same write: an option added or renamed\n on the status is added or renamed on the history, which a call never restates. Removing an option on the status leaves it\n on the history, because the moves already written hold it. A call that changes nothing of the status\'s options leaves the\n history alone, and options only the history holds stay. Deleting a row deletes its history rows with it, and restoring\n the row restores them; they never hold a delete back.\n- A link names its table by id, or by the `ref` of another table of the same call, and states its `multi`. A two-way link\n states `pair` on one table, as `true` or as a free alias, and the platform makes the partner on the other table with the\n inverse cardinality; a many-to-many link states both sides, since the inverse of many is not decided.\n A link to its own table pairs with itself when `pair` is `true`, and with a second field of that table when `pair` names it\n (a parent and its children).\n A link already holding rows is paired the same way, with its partner stated beside it in the call: the partner is filled from\n the links the rows hold and no cell of the link is rewritten. `pair: null` lets a pair go, both fields staying one-way links\n with their values; a field that holds one row, the partner or the link itself, refuses a pair two rows would crowd, naming the rows.\n The partner may stand on a table the call does not name: `pair: "<alias>"` makes it there, or pairs the one-way link that table\n already holds under that alias, and the answer lists that table among the call\'s. Only someone who manages that table may.\n- A formula\'s `output_type` is inferred from its expression; state it only to override.\n- **A call\'s removals are judged together, on what the call leaves.** A table and the links and lookups naming it, removed in one call, pass; every reader left outside the call is named in one answer, not one per retry. An app reading a field or an option that leaves is rebuilt in the same call, and the answer (a dry run too) lists each node of its tree that changed: a column, a filter, a sort key or a field of a part that only drew the field is dropped, and an option leaves every list of options it stood in. What has no meaning without it refuses the call, naming the node: an act that sets a removed option, a part left with nothing to draw, a list that held only the removed option. An app drawing a field that is retyped, or a link pointed at another table, is rebuilt too, its tree unchanged: where the field no longer lets the tree draw what it drew, the call refuses, naming the node, and a field that became a formula, rollup, lookup or autonumber leaves the app\'s allowlist of saves. A workflow body its author wrote is never rewritten: it is checked again against the tables as the call leaves them, and the call refuses, naming the workflow, only if it no longer checks. A table\'s check or workflow that reads a retyped field or a link pointed elsewhere is judged the same way and refuses, naming it, only if it no longer holds. Deleting one field through the table\'s field route drops no node: an app whose tree draws the field refuses it, naming the node.\n- **A field something reads cannot go.** A query, a workflow, a check, an app only its owner can rebuild, or another\n table\'s formula, rollup, lookup or copy that reads the field refuses its deletion, naming the reader. Change or remove\n the reader first, or in the same call.\n- **`force` consents to losing values:** deleting a field rows hold, removing an option rows hold, and a change of type\n that does not convert every value.\n- A money formula is proven by its numbers. `query_records` with `aggregate` the affected totals before the change and after, and\n compare. A new field in a formula is tested for the value you want, never for differing from an empty cell, which reads\n `""` and differs from every option.\n- A check\'s expressions are written in the language of `workflows/table-checks`.\n- Views are written with `set_table_views`, not `set_tables`: `views` is keyed by a view\'s id (patch; `null` deletes) or a new key (create), and `order` lists view ids or new keys. `get_table` lists each view\'s id and name and returns the definitions with `views: true`.\n- A refused edit writes nothing and lists everything wrong; `dry_run` is for reading the grants it would make or deciding `force`.\n\nA worked call: add the option `cancelled` to `stage` (the whole list restated), add a check, and consent to losing\nwhat rows hold.\n\n```json5\n{\n "tables": [\n {\n "table_id": "<id of the table>",\n "fields": {\n "stage": {\n "options": [\n { "alias": "draft", "label": "Draft" },\n { "alias": "confirmed", "label": "Confirmed" },\n { "alias": "cancelled", "label": "Cancelled", "color": "red" }\n ]\n }\n },\n "checks": {\n "returns_after_leaves": {\n "on": ["create", "update"],\n "when": "!isNull(record.returns)",\n "fail_when": "record.returns < record.leaves",\n "message": "\\"Return before departure\\"",\n "field": "returns"\n }\n }\n }\n ],\n "force": true,\n "dry_run": true\n}\n```\n\nSplitting `queued` into waiting and underway is one call of the same shape:\n\n```json5\n{ "tables": [{ "table_id": "<id of the table>", "fields": { "stage": { "options": [\n { "alias": "draft", "label": "Draft" },\n { "alias": "queued", "label": "Waiting" },\n { "alias": "underway", "label": "Underway", "color": "green" }\n] } } }] }\n```\n\n`table_id` picks the table patched; `fields` merges by alias, so only `stage` changes; `checks` adds one under its alias\n(`null` removes it); `force` consents to losing values (leave it out unless rows hold a removed option); `dry_run`\nchecks and writes nothing, for reading the grants or deciding `force` before the call that writes.\n';
@@ -2261,6 +2320,10 @@ function flushPendingWarnings() {
2261
2320
  for (const text of collectedWarnings) console.error(text);
2262
2321
  collectedWarnings.length = 0;
2263
2322
  }
2323
+ function exitCli(code) {
2324
+ flushPendingWarnings();
2325
+ process.exit(code);
2326
+ }
2264
2327
 
2265
2328
  // src/docs_command.ts
2266
2329
  var TEXTS = {
@@ -2303,7 +2366,7 @@ async function docsCommand(args, server) {
2303
2366
  const own2 = ownArea(args.area);
2304
2367
  if (own2 !== void 0) {
2305
2368
  console.error(`--grep searches the references the server holds, and "${own2}" is this binary's own: read it with \`lotics docs ${own2}\`.`);
2306
- process.exit(1);
2369
+ exitCli(1);
2307
2370
  }
2308
2371
  return printAnswer(await (await server()).execute("docs", { path: args.area, ...args.search }, { format: "text" }));
2309
2372
  }
@@ -2314,7 +2377,7 @@ async function docsCommand(args, server) {
2314
2377
  }
2315
2378
  console.error(page.error);
2316
2379
  const newer = page.kind === "no_area" || page.kind === "no_part" && SERVED2.has(page.area);
2317
- if (!newer) process.exit(1);
2380
+ if (!newer) exitCli(1);
2318
2381
  note("This binary's references may predate the page; reading the server's.");
2319
2382
  printAnswer(await (await server()).execute("docs", { path: args.area }, { format: "text" }));
2320
2383
  }
@@ -2327,7 +2390,7 @@ function ownArea(path17) {
2327
2390
  function printAnswer(answer) {
2328
2391
  if (answer.error) {
2329
2392
  console.error(answer.error);
2330
- process.exit(1);
2393
+ exitCli(1);
2331
2394
  }
2332
2395
  if (answer.model_output === void 0) fail("The server's docs tool answered without its text.");
2333
2396
  process.stdout.write(`${answer.model_output.replace(/\n+$/, "")}
@@ -2747,7 +2810,7 @@ async function reportCommand(client, options) {
2747
2810
  `Could not file the report: ${error62 instanceof Error ? error62.message : String(error62)}`
2748
2811
  );
2749
2812
  echoReport(report);
2750
- process.exit(1);
2813
+ exitCli(1);
2751
2814
  }
2752
2815
  console.error(
2753
2816
  `Filed${filed > 1 ? ` ${filed} reports` : ""}${filedIds.length > 0 ? `: ${filedIds.join(", ")}` : ""}. Thank you \u2014 this is read.`
@@ -27654,6 +27717,7 @@ var AGENT_RUN_POLL = {
27654
27717
  function splitList(value) {
27655
27718
  return (value ?? "").split(",").map((part) => part.trim()).filter((part) => part !== "");
27656
27719
  }
27720
+ var MAX_TIMEOUT_MS = 2147483647;
27657
27721
  var CANONICAL_FLAG = {
27658
27722
  "-o": "--output",
27659
27723
  "-w": "--workspace",
@@ -27693,6 +27757,7 @@ function parseArgs(argv2) {
27693
27757
  const typed = [];
27694
27758
  let unknownFlag;
27695
27759
  let missingValue;
27760
+ let invalidValue;
27696
27761
  let i = 0;
27697
27762
  const takeValue = (flag, expects) => {
27698
27763
  const value = argv2[++i];
@@ -27716,9 +27781,12 @@ function parseArgs(argv2) {
27716
27781
  case "--url":
27717
27782
  flags.url = takeValue(arg, "<url>");
27718
27783
  break;
27719
- case "--timeout":
27720
- flags.timeout = parseInt(takeValue(arg, "<ms>"), 10);
27784
+ case "--timeout": {
27785
+ const value = takeValue(arg, "<ms>");
27786
+ if (/^[1-9]\d*$/.test(value) && Number(value) <= MAX_TIMEOUT_MS) flags.timeout = Number(value);
27787
+ else if (!missingValue) invalidValue ??= { flag: arg, expects: `a whole number of milliseconds from 1 to ${MAX_TIMEOUT_MS}`, value };
27721
27788
  break;
27789
+ }
27722
27790
  case "--output":
27723
27791
  case "-o":
27724
27792
  flags.output = takeValue(arg, "<path>");
@@ -27858,21 +27926,7 @@ function parseArgs(argv2) {
27858
27926
  if (matched) typed.push(CANONICAL_FLAG[arg] ?? arg);
27859
27927
  i++;
27860
27928
  }
27861
- return { command, subcommand, toolArgs, restArgs, flags, typed, unknownFlag, missingValue };
27862
- }
27863
-
27864
- // ../shared/src/screenshot_limits.ts
27865
- var MAX_SCREENSHOT_WIDTHS = 3;
27866
- var SCREENSHOT_BUDGET_MS = 3e4;
27867
- var SCREENSHOT_QUEUE_WAIT_MS = 2e4;
27868
- var SCREENSHOT_CAPTURE_MARGIN_MS = 43e3;
27869
- var SCREENSHOT_BROWSER_OPEN_MS = 49e3;
27870
- var SCREENSHOT_TRANSFER_MS = 1e4;
27871
- function screenshotRenderCeilingMs(widths) {
27872
- return widths * (SCREENSHOT_BUDGET_MS + SCREENSHOT_CAPTURE_MARGIN_MS);
27873
- }
27874
- function screenshotTimeoutMs(widths) {
27875
- return SCREENSHOT_QUEUE_WAIT_MS + SCREENSHOT_BROWSER_OPEN_MS + screenshotRenderCeilingMs(widths) + SCREENSHOT_TRANSFER_MS;
27929
+ return { command, subcommand, toolArgs, restArgs, flags, typed, unknownFlag, missingValue, invalidValue };
27876
27930
  }
27877
27931
 
27878
27932
  // src/cli_login.ts
@@ -28390,7 +28444,7 @@ ${renderCommandsHelp()}
28390
28444
 
28391
28445
  FLAGS
28392
28446
  --json Full JSON output (default is human-readable text)
28393
- --timeout <ms> Timeout for tool execution (default: 60000; screenshot_app waits for its widest request)
28447
+ --timeout <ms> Stop waiting for the server's answer after this long (default: wait for it)
28394
28448
  -o <path> download: the directory to save into; knowledge get: the file
28395
28449
  to write; run: the directory every signed link in the
28396
28450
  tool's answer is saved into
@@ -28560,14 +28614,14 @@ async function runUpgrade() {
28560
28614
  Upgrade failed (exit ${code}). Run it yourself to see why:
28561
28615
  ${cmd}`
28562
28616
  );
28563
- process.exit(1);
28617
+ exitCli(1);
28564
28618
  }
28565
28619
  }
28566
28620
  async function handleSignup(positionalEmail, flags) {
28567
28621
  const email3 = positionalEmail ?? (process.stdin.isTTY ? await prompt("Email: ") : "");
28568
28622
  if (!email3) {
28569
28623
  console.error("Email is required. Usage: lotics auth signup <email>");
28570
- process.exit(1);
28624
+ exitCli(1);
28571
28625
  }
28572
28626
  if (alreadySetUp(email3)) {
28573
28627
  console.error(
@@ -28594,7 +28648,7 @@ async function handleSignup(positionalEmail, flags) {
28594
28648
  });
28595
28649
  } catch (error62) {
28596
28650
  console.error(error62 instanceof Error ? error62.message : String(error62));
28597
- process.exit(1);
28651
+ exitCli(1);
28598
28652
  }
28599
28653
  if (outcome.kind === "email_taken") {
28600
28654
  console.error(
@@ -28602,7 +28656,7 @@ async function handleSignup(positionalEmail, flags) {
28602
28656
  Sign in on this machine: lotics auth login ${email3}
28603
28657
  Which account is saved: lotics auth whoami`
28604
28658
  );
28605
- process.exit(1);
28659
+ exitCli(1);
28606
28660
  }
28607
28661
  const { orgId, orgName } = outcome.account;
28608
28662
  console.error(`Account created. You can now use the CLI.`);
@@ -28620,7 +28674,7 @@ async function handleLogin(positionalEmail, flags) {
28620
28674
  const email3 = positionalEmail ?? (process.stdin.isTTY ? await prompt("Email: ") : "");
28621
28675
  if (!email3) {
28622
28676
  console.error("Email is required. Usage: lotics auth login <email>");
28623
- process.exit(1);
28677
+ exitCli(1);
28624
28678
  }
28625
28679
  if (!waitsForConfirm(flags)) {
28626
28680
  const pending = await startPendingLogin(email3);
@@ -28647,7 +28701,7 @@ async function handleLogin(positionalEmail, flags) {
28647
28701
  account = await awaitCliLogin(email3, flags.local ? { local: true } : {});
28648
28702
  } catch (error62) {
28649
28703
  console.error(error62 instanceof Error ? error62.message : String(error62));
28650
- process.exit(1);
28704
+ exitCli(1);
28651
28705
  }
28652
28706
  narrate(`lotics \u2192 ${account.orgName} / ${account.workspaceId}`);
28653
28707
  if (flags.json) {
@@ -28664,22 +28718,15 @@ async function handleLogin(positionalEmail, flags) {
28664
28718
  );
28665
28719
  }
28666
28720
  }
28667
- async function handleSetup(providedKey, local) {
28721
+ async function handleSetup(providedKey, local, timeoutMs) {
28668
28722
  const apiKey = providedKey ?? await prompt("Enter your API key: ");
28669
28723
  if (!apiKey) {
28670
28724
  console.error("No API key provided.");
28671
- process.exit(1);
28725
+ exitCli(1);
28672
28726
  }
28673
28727
  const apiUrl = envApiUrl();
28674
- const client = new LoticsClient({ apiKey, apiUrl });
28675
- let info;
28676
- try {
28677
- info = await client.whoami();
28678
- } catch (error62) {
28679
- const message = error62 instanceof Error ? error62.message : String(error62);
28680
- console.error(`Authentication failed: ${message}`);
28681
- process.exit(1);
28682
- }
28728
+ const client = new LoticsClient({ apiKey, apiUrl, timeoutMs });
28729
+ const info = await client.whoami();
28683
28730
  let workspaceId;
28684
28731
  let workspaceName;
28685
28732
  try {
@@ -28766,16 +28813,16 @@ async function requireClient(flags, appWorkspaceId) {
28766
28813
  const { ctx, refusal } = await resolveContextOrClaim(flags, { appWorkspaceId });
28767
28814
  if (refusal !== void 0) {
28768
28815
  console.error(refusal);
28769
- process.exit(1);
28816
+ exitCli(1);
28770
28817
  }
28771
28818
  if (!ctx) {
28772
28819
  console.error('Not authenticated. Run "lotics auth signup", "lotics auth api-key <key>", or set LOTICS_API_KEY.');
28773
- process.exit(1);
28820
+ exitCli(1);
28774
28821
  }
28775
28822
  noteScope({ org_id: ctx.orgId ?? void 0, workspace_id: ctx.workspaceId });
28776
28823
  flushSpool(ctx.apiUrl, (events) => postEvents(ctx.apiUrl, ctx.apiKey, events));
28777
28824
  return {
28778
- client: new LoticsClient({ apiKey: ctx.apiKey, apiUrl: ctx.apiUrl, workspaceId: ctx.workspaceId }),
28825
+ client: new LoticsClient({ apiKey: ctx.apiKey, apiUrl: ctx.apiUrl, workspaceId: ctx.workspaceId, timeoutMs: flags.timeout }),
28779
28826
  ctx
28780
28827
  };
28781
28828
  }
@@ -28833,17 +28880,10 @@ async function resolveWorkspace(client, ctx) {
28833
28880
  announceTarget(ctx, ctx.workspaceId, name);
28834
28881
  return;
28835
28882
  }
28836
- let workspaces;
28837
- try {
28838
- workspaces = await client.listWorkspaces();
28839
- } catch (error62) {
28840
- const message = error62 instanceof Error ? error62.message : String(error62);
28841
- console.error(`Failed to list workspaces: ${message}`);
28842
- process.exit(1);
28843
- }
28883
+ const workspaces = await client.listWorkspaces();
28844
28884
  if (workspaces.length === 0) {
28845
28885
  console.error("No workspaces found for this organization.");
28846
- process.exit(1);
28886
+ exitCli(1);
28847
28887
  }
28848
28888
  if (workspaces.length === 1) {
28849
28889
  setSelectedWorkspace(workspaces[0].id, ctx.orgId, workspaces[0].name);
@@ -28855,7 +28895,7 @@ async function resolveWorkspace(client, ctx) {
28855
28895
  console.error(" lotics workspace select <id>\n");
28856
28896
  printWorkspaceList(workspaces);
28857
28897
  console.error("");
28858
- process.exit(1);
28898
+ exitCli(1);
28859
28899
  }
28860
28900
  function resolveUploadPaths(rawPaths) {
28861
28901
  const result = [];
@@ -28879,12 +28919,17 @@ function wholeNumberFlag(flag, value, min) {
28879
28919
  const parsed = Number(value);
28880
28920
  if (value.trim() === "" || !Number.isInteger(parsed) || parsed < min) {
28881
28921
  console.error(`Invalid ${flag} "${value}" \u2014 expected ${min === 1 ? "a positive integer" : "a whole number"}.`);
28882
- process.exit(1);
28922
+ exitCli(1);
28883
28923
  }
28884
28924
  return parsed;
28885
28925
  }
28886
28926
  async function main(argv2) {
28927
+ await dispatch(argv2);
28928
+ flushPendingWarnings();
28929
+ }
28930
+ async function dispatch(argv2) {
28887
28931
  const parsed = parseArgs(argv2);
28932
+ setMachineOutput(parsed.flags.json);
28888
28933
  const { restArgs, flags } = parsed;
28889
28934
  let { command, subcommand, toolArgs } = parsed;
28890
28935
  if (parsed.unknownFlag !== void 0) {
@@ -28896,12 +28941,17 @@ async function main(argv2) {
28896
28941
  );
28897
28942
  } else if (dryRunFlag) console.error("Nothing was written. A dry run is --check: lotics app apply <file> --check");
28898
28943
  else console.error("Run 'lotics --help' for the options each command takes.");
28899
- process.exit(1);
28944
+ exitCli(1);
28900
28945
  }
28901
28946
  if (parsed.missingValue !== void 0) {
28902
28947
  const { flag, expects } = parsed.missingValue;
28903
28948
  console.error(`${flag} needs a value \u2014 write it as: ${flag} ${expects}`);
28904
- process.exit(1);
28949
+ exitCli(1);
28950
+ }
28951
+ if (parsed.invalidValue !== void 0) {
28952
+ const { flag, expects, value } = parsed.invalidValue;
28953
+ console.error(`${flag} needs ${expects} \u2014 got ${JSON.stringify(value)}`);
28954
+ exitCli(1);
28905
28955
  }
28906
28956
  if (flags.help && command === "report") {
28907
28957
  console.error(REPORT_USAGE);
@@ -28934,7 +28984,7 @@ async function main(argv2) {
28934
28984
  `--version prints this CLI's version and takes no argument; it cannot be combined with a command.
28935
28985
  The CLI version: lotics --version`
28936
28986
  );
28937
- process.exit(1);
28987
+ exitCli(1);
28938
28988
  }
28939
28989
  if (flags.version) {
28940
28990
  console.log(VERSION);
@@ -28943,7 +28993,7 @@ async function main(argv2) {
28943
28993
  const misplaced = misplacedFlag(parsed.typed, [command, subcommand].filter((word) => word !== void 0));
28944
28994
  if (misplaced !== null) {
28945
28995
  console.error(misplaced);
28946
- process.exit(1);
28996
+ exitCli(1);
28947
28997
  }
28948
28998
  const envOrg = resolveEnvOrg();
28949
28999
  if (envOrg && (flags.apiKey ?? process.env.LOTICS_API_KEY)) {
@@ -28957,12 +29007,12 @@ async function main(argv2) {
28957
29007
  const stray = Object.entries(searchOnly).find(([, given]) => given)?.[0];
28958
29008
  if (stray !== void 0) {
28959
29009
  console.error(`${stray} shapes a search \u2014 add --grep <text>.`);
28960
- process.exit(1);
29010
+ exitCli(1);
28961
29011
  }
28962
29012
  }
28963
29013
  if (flags.regex && flags.literal) {
28964
29014
  console.error("--regex and --literal read the pattern two ways \u2014 pass one.");
28965
- process.exit(1);
29015
+ exitCli(1);
28966
29016
  }
28967
29017
  const search = flags.grep === void 0 ? void 0 : {
28968
29018
  grep: flags.grep,
@@ -28988,7 +29038,7 @@ async function main(argv2) {
28988
29038
  const file2 = input2.slice(1);
28989
29039
  if (!fs17.existsSync(file2)) {
28990
29040
  console.error(`No such file: ${file2}`);
28991
- process.exit(1);
29041
+ exitCli(1);
28992
29042
  }
28993
29043
  input2 = fs17.readFileSync(file2, "utf-8");
28994
29044
  } else if (input2 === "-") {
@@ -28997,31 +29047,31 @@ async function main(argv2) {
28997
29047
  }
28998
29048
  if (input2.trim() === "") {
28999
29049
  console.error(REPORT_USAGE);
29000
- process.exit(1);
29050
+ exitCli(1);
29001
29051
  }
29002
29052
  const parsed2 = parseReport(input2, source);
29003
29053
  if ("error" in parsed2) {
29004
29054
  console.error(`${parsed2.error}
29005
29055
  `);
29006
29056
  console.error(REPORT_USAGE);
29007
- process.exit(1);
29057
+ exitCli(1);
29008
29058
  }
29009
29059
  const { ctx: reportCtx, refusal } = await resolveContextOrClaim(flags);
29010
29060
  if (refusal !== void 0) {
29011
29061
  console.error(refusal);
29012
29062
  echoReport(parsed2.report);
29013
- process.exit(1);
29063
+ exitCli(1);
29014
29064
  }
29015
29065
  if (!reportCtx) {
29016
29066
  console.error(
29017
29067
  'Not authenticated, so this could not be sent. Run "lotics auth signup", "lotics auth api-key <key>", or set LOTICS_API_KEY.'
29018
29068
  );
29019
29069
  echoReport(parsed2.report);
29020
- process.exit(1);
29070
+ exitCli(1);
29021
29071
  }
29022
29072
  noteScope({ org_id: reportCtx.orgId ?? void 0, workspace_id: reportCtx.workspaceId });
29023
29073
  await reportCommand(
29024
- new LoticsClient({ apiKey: reportCtx.apiKey, apiUrl: reportCtx.apiUrl, workspaceId: reportCtx.workspaceId }),
29074
+ new LoticsClient({ apiKey: reportCtx.apiKey, apiUrl: reportCtx.apiUrl, workspaceId: reportCtx.workspaceId, timeoutMs: flags.timeout }),
29025
29075
  {
29026
29076
  report: parsed2.report,
29027
29077
  version: VERSION,
@@ -29040,20 +29090,20 @@ async function main(argv2) {
29040
29090
  return;
29041
29091
  }
29042
29092
  if (subcommand === "api-key") {
29043
- await handleSetup(toolArgs ?? flags.apiKey, flags.local);
29093
+ await handleSetup(toolArgs ?? flags.apiKey, flags.local, flags.timeout);
29044
29094
  return;
29045
29095
  }
29046
29096
  if (subcommand === "whoami") {
29047
29097
  const { ctx: ctx2, refusal } = await resolveContextOrClaim(flags);
29048
29098
  if (refusal !== void 0) {
29049
29099
  console.error(refusal);
29050
- process.exit(1);
29100
+ exitCli(1);
29051
29101
  }
29052
29102
  if (!ctx2) {
29053
29103
  console.error('Not authenticated. Run "lotics auth signup", "lotics auth api-key <key>", or set LOTICS_API_KEY.');
29054
- process.exit(1);
29104
+ exitCli(1);
29055
29105
  }
29056
- const client2 = new LoticsClient({ apiKey: ctx2.apiKey, apiUrl: ctx2.apiUrl });
29106
+ const client2 = new LoticsClient({ apiKey: ctx2.apiKey, apiUrl: ctx2.apiUrl, timeoutMs: flags.timeout });
29057
29107
  const info = await client2.whoami();
29058
29108
  const existing = loadGlobalConfig() ?? {};
29059
29109
  if (info.email !== null) saveGlobalConfig({ ...existing, email: info.email });
@@ -29109,7 +29159,7 @@ async function main(argv2) {
29109
29159
  }
29110
29160
  if (!resolved) {
29111
29161
  console.error(toolArgs ? `No saved credential matches "${toolArgs}".` : "No active credential to remove. Pass an org name/id, or use --all.");
29112
- process.exit(1);
29162
+ exitCli(1);
29113
29163
  }
29114
29164
  const [orgId, profile] = resolved;
29115
29165
  await revokeCredential(orgId, profile);
@@ -29143,12 +29193,12 @@ async function main(argv2) {
29143
29193
  if (subcommand === "use") {
29144
29194
  if (!toolArgs) {
29145
29195
  console.error("Usage: lotics org use <name|id> [--local]");
29146
- process.exit(1);
29196
+ exitCli(1);
29147
29197
  }
29148
29198
  const resolved = resolveProfileByNameOrId(profiles, toolArgs);
29149
29199
  if (!resolved) {
29150
29200
  console.error(`No saved credential for "${toolArgs}". Run "lotics auth api-key <key>" while authenticated to that org, or "lotics org" to list.`);
29151
- process.exit(1);
29201
+ exitCli(1);
29152
29202
  }
29153
29203
  const [orgId, profile] = resolved;
29154
29204
  if (flags.local) {
@@ -29171,7 +29221,7 @@ async function main(argv2) {
29171
29221
  if (subcommand && subcommand !== "list") {
29172
29222
  console.error(`Unknown org subcommand: ${subcommand}`);
29173
29223
  console.error("Usage: lotics org [list | use <name|id> [--local]]");
29174
- process.exit(1);
29224
+ exitCli(1);
29175
29225
  }
29176
29226
  const orgIds = Object.keys(profiles);
29177
29227
  if (orgIds.length === 0) {
@@ -29208,20 +29258,20 @@ async function main(argv2) {
29208
29258
  console.error(
29209
29259
  `If Lotics genuinely cannot do this yet, say so \u2014 run \`lotics report\` for the frame.`
29210
29260
  );
29211
- process.exit(1);
29261
+ exitCli(1);
29212
29262
  }
29213
29263
  if (command === "app" && !subcommand) {
29214
29264
  console.error(`Usage:
29215
29265
  ${commandHelp(["app"])}`);
29216
29266
  console.error("Everything else about an app is a tool: lotics tools, then lotics run <tool>.");
29217
- process.exit(1);
29267
+ exitCli(1);
29218
29268
  }
29219
29269
  if (command === "run" && !subcommand) {
29220
29270
  console.error(
29221
29271
  "Usage: lotics run <tool> '<json_args>'\n lotics run <tool> @args.json (read args from a file \u2014 for large payloads)\n cat args.json | lotics run <tool> - (read args from stdin)"
29222
29272
  );
29223
29273
  console.error('Run "lotics tools" to see available tools.');
29224
- process.exit(1);
29274
+ exitCli(1);
29225
29275
  }
29226
29276
  if (command === "upload" && !subcommand && !flags.stdin && !flags.base64 && !flags.url) {
29227
29277
  console.error("Usage:");
@@ -29230,7 +29280,7 @@ ${commandHelp(["app"])}`);
29230
29280
  console.error(" lotics upload --base64 --as <name> Base64 on stdin");
29231
29281
  console.error(" lotics upload --url <url> [--as <name>]");
29232
29282
  console.error("Uploads files and returns their file_ids. Directories expand to their immediate files.");
29233
- process.exit(1);
29283
+ exitCli(1);
29234
29284
  }
29235
29285
  if (command === "download") {
29236
29286
  const args = resolveDownloadArgs({
@@ -29277,7 +29327,7 @@ ${commandHelp(["app"])}`);
29277
29327
  console.error(`Unknown file subcommand: ${subcommand}
29278
29328
  `);
29279
29329
  console.error(commandHelp(["file"]));
29280
- process.exit(1);
29330
+ exitCli(1);
29281
29331
  }
29282
29332
  const { client: client2, ctx: ctx2 } = await requireClient(flags);
29283
29333
  await resolveWorkspace(client2, ctx2);
@@ -29321,7 +29371,7 @@ ${commandHelp(["app"])}`);
29321
29371
  if (subcommand === "rename" && !settingsName) {
29322
29372
  console.error("Usage: lotics workspace rename <new name>");
29323
29373
  console.error('Renames the CURRENT workspace. Switch first with "lotics workspace select <id>".');
29324
- process.exit(1);
29374
+ exitCli(1);
29325
29375
  }
29326
29376
  if (subcommand === "settings" && settingsName === void 0 && flags.currency === void 0 && flags.timezone === void 0) {
29327
29377
  console.error(
@@ -29331,7 +29381,7 @@ ${commandHelp(["app"])}`);
29331
29381
  "Changes the CURRENT workspace. The currency decides how every money field renders and the"
29332
29382
  );
29333
29383
  console.error("zone decides how every date buckets; neither is visible once it is wrong.");
29334
- process.exit(1);
29384
+ exitCli(1);
29335
29385
  }
29336
29386
  const workspaces = await client.listWorkspaces();
29337
29387
  const currentWorkspaceId = ctx.workspaceId;
@@ -29339,7 +29389,7 @@ ${commandHelp(["app"])}`);
29339
29389
  const targetId = toolArgs;
29340
29390
  if (!targetId) {
29341
29391
  console.error("Usage: lotics workspace select <workspace_id>");
29342
- process.exit(1);
29392
+ exitCli(1);
29343
29393
  }
29344
29394
  const target = workspaces.find((ws) => ws.id === targetId);
29345
29395
  if (!target) {
@@ -29347,7 +29397,7 @@ ${commandHelp(["app"])}`);
29347
29397
 
29348
29398
  Available workspaces:`);
29349
29399
  printWorkspaceList(workspaces, currentWorkspaceId);
29350
- process.exit(1);
29400
+ exitCli(1);
29351
29401
  }
29352
29402
  sayWorkspaceSwitch(target, setSelectedWorkspace(target.id, ctx.orgId, target.name));
29353
29403
  return;
@@ -29356,7 +29406,7 @@ Available workspaces:`);
29356
29406
  const current2 = workspaces.find((ws) => ws.id === currentWorkspaceId);
29357
29407
  if (!current2) {
29358
29408
  console.error('No workspace selected. Choose one with "lotics workspace select <id>".');
29359
- process.exit(1);
29409
+ exitCli(1);
29360
29410
  }
29361
29411
  const updated = await client.updateWorkspace({
29362
29412
  name: settingsName ?? current2.name,
@@ -29377,7 +29427,7 @@ Available workspaces:`);
29377
29427
  const name = toolArgs;
29378
29428
  if (!name) {
29379
29429
  console.error("Usage: lotics workspace create <name> [--timezone <tz>] [--currency <ISO>]");
29380
- process.exit(1);
29430
+ exitCli(1);
29381
29431
  }
29382
29432
  const timezone = flags.timezone;
29383
29433
  const created = await client.createWorkspace({
@@ -29401,7 +29451,7 @@ Available workspaces:`);
29401
29451
  const targetId = toolArgs;
29402
29452
  if (!targetId) {
29403
29453
  console.error("Usage: lotics workspace delete <workspace_id> --yes");
29404
- process.exit(1);
29454
+ exitCli(1);
29405
29455
  }
29406
29456
  const target = workspaces.find((ws) => ws.id === targetId);
29407
29457
  if (!target) {
@@ -29409,12 +29459,12 @@ Available workspaces:`);
29409
29459
 
29410
29460
  Available workspaces:`);
29411
29461
  printWorkspaceList(workspaces, currentWorkspaceId);
29412
- process.exit(1);
29462
+ exitCli(1);
29413
29463
  }
29414
29464
  if (!flags.yes) {
29415
29465
  console.error(`This deletes workspace "${target.name}" (${target.id}) \u2014 every table, app, record, and template inside it becomes inaccessible (soft delete: retained and recoverable by an admin).`);
29416
29466
  console.error(`Re-run with --yes to confirm: lotics workspace delete ${target.id} --yes`);
29417
- process.exit(1);
29467
+ exitCli(1);
29418
29468
  }
29419
29469
  const deleted = await client.deleteWorkspace(target.id);
29420
29470
  if (flags.json) {
@@ -29430,7 +29480,7 @@ Available workspaces:`);
29430
29480
  if (subcommand && subcommand !== "list") {
29431
29481
  console.error(`Unknown workspace subcommand: ${subcommand}`);
29432
29482
  console.error("Usage: lotics workspace [list | select <id> | create <name> | delete <id> --yes]");
29433
- process.exit(1);
29483
+ exitCli(1);
29434
29484
  }
29435
29485
  const current = workspaces.find((ws) => ws.id === currentWorkspaceId);
29436
29486
  if (current !== void 0) cacheWorkspaceName(current.id, ctx.orgId, current.name);
@@ -29463,15 +29513,13 @@ Available workspaces:`);
29463
29513
  console.error(" A custom-code app: registered here and linked to [path] (default ./<name>)");
29464
29514
  console.error(" by package.json#lotics; the project there is yours. An app the runtime");
29465
29515
  console.error(" draws from a JSON body is made by `lotics app apply <file>`.");
29466
- process.exit(1);
29516
+ exitCli(1);
29467
29517
  }
29468
- if (flags.json) setMachineOutput(true);
29469
29518
  const created = await appCreate(client, { name, ...restArgs[0] === void 0 ? {} : { targetPath: restArgs[0] } });
29470
29519
  if (flags.json) emitJson({ workspace_id: ctx.workspaceId, ...created });
29471
29520
  return;
29472
29521
  }
29473
29522
  if (subcommand === "pull") {
29474
- if (flags.json) setMachineOutput(true);
29475
29523
  const pulled = await appPull(client, {
29476
29524
  force: flags.force,
29477
29525
  ...toolArgs === void 0 ? {} : { appId: toolArgs },
@@ -29490,23 +29538,21 @@ Available workspaces:`);
29490
29538
  console.error(" app has moved past the version the file was pulled at.");
29491
29539
  console.error(" --check sends dry_run and writes nothing. To go back, apply the earlier body");
29492
29540
  console.error(" again. Pull a body (the tool get_app): lotics app pull <app_id> [path]");
29493
- process.exit(1);
29541
+ exitCli(1);
29494
29542
  }
29495
- if (flags.json) setMachineOutput(true);
29496
29543
  const applied = await applyAppBody(client, { file: toolArgs, appId: flags.app, check: flags.check });
29497
29544
  if (flags.json) emitJson({ workspace_id: ctx.workspaceId, ...applied });
29498
29545
  return;
29499
29546
  }
29500
29547
  if (subcommand === "deploy") {
29501
29548
  const message = (flags.message ?? toolArgs)?.trim();
29502
- if (flags.json) setMachineOutput(true);
29503
29549
  const deployed = await appDeploy(client, message ? { message } : {});
29504
29550
  if (flags.json) emitJson(deployed);
29505
29551
  return;
29506
29552
  }
29507
29553
  console.error(`Unknown app subcommand: ${subcommand}`);
29508
29554
  console.error("Run 'lotics app' for usage.");
29509
- process.exit(1);
29555
+ exitCli(1);
29510
29556
  }
29511
29557
  if (command === "tools") {
29512
29558
  if (subcommand) {
@@ -29549,19 +29595,19 @@ ${JSON.stringify(info.input_schema, null, 2)}${output2}`);
29549
29595
  const sources = [flags.stdin && "--stdin", flags.base64 && "--base64", flags.url && "--url"].filter(Boolean);
29550
29596
  if (sources.length > 1) {
29551
29597
  console.error(`Pick one source: ${sources.join(", ")} were all given.`);
29552
- process.exit(1);
29598
+ exitCli(1);
29553
29599
  }
29554
29600
  let upload;
29555
29601
  if (sources.length === 1) {
29556
29602
  const positional = [subcommand, toolArgs, ...restArgs].filter((v) => v !== void 0);
29557
29603
  if (positional.length > 0) {
29558
29604
  console.error(`${sources[0]} reads the bytes itself \u2014 drop the path argument (${positional.join(", ")}).`);
29559
- process.exit(1);
29605
+ exitCli(1);
29560
29606
  }
29561
29607
  const resolved = await resolveUploadSource(String(sources[0]), flags);
29562
29608
  if ("error" in resolved) {
29563
29609
  console.error(resolved.error);
29564
- process.exit(1);
29610
+ exitCli(1);
29565
29611
  }
29566
29612
  upload = await client.uploadFileBytes([resolved]);
29567
29613
  } else {
@@ -29569,11 +29615,11 @@ ${JSON.stringify(info.input_schema, null, 2)}${output2}`);
29569
29615
  const filePaths = resolveUploadPaths(rawPaths);
29570
29616
  if (filePaths.length === 0) {
29571
29617
  console.error("No files found in the specified paths.");
29572
- process.exit(1);
29618
+ exitCli(1);
29573
29619
  }
29574
29620
  if (flags.as && filePaths.length > 1) {
29575
29621
  console.error("Cannot use --as with multiple files.");
29576
- process.exit(1);
29622
+ exitCli(1);
29577
29623
  }
29578
29624
  upload = await client.uploadFiles(filePaths, {
29579
29625
  filenames: flags.as ? [flags.as] : void 0
@@ -29581,7 +29627,7 @@ ${JSON.stringify(info.input_schema, null, 2)}${output2}`);
29581
29627
  }
29582
29628
  if (upload.files.length === 0 && upload.errors.length > 0) {
29583
29629
  console.error(`Upload failed: ${upload.errors.map((e) => `${e.filename}: ${e.error}`).join(", ")}`);
29584
- process.exit(1);
29630
+ exitCli(1);
29585
29631
  }
29586
29632
  if (flags.json) {
29587
29633
  console.log(JSON.stringify({ files: upload.files, errors: upload.errors }, null, 2));
@@ -29605,21 +29651,20 @@ ${JSON.stringify(info.input_schema, null, 2)}${output2}`);
29605
29651
  });
29606
29652
  if (ingested.kind === "error") {
29607
29653
  console.error(ingested.message);
29608
- process.exit(1);
29654
+ exitCli(1);
29609
29655
  }
29610
29656
  const args = ingested.args;
29611
29657
  noteToolArgs(args);
29612
- const timeoutMs = flags.timeout ?? (toolName === "screenshot_app" ? screenshotTimeoutMs(MAX_SCREENSHOT_WIDTHS) : 6e4);
29613
- const result = await client.execute(toolName, args, { format: "text", timeoutMs });
29658
+ const result = await client.execute(toolName, args, { format: "text" });
29614
29659
  if (result.error) {
29615
29660
  const recorded = result.message_source === "system" ? result.error : result.error_code ?? "unmarked tool error";
29616
29661
  if (flags.json) {
29617
- console.log(JSON.stringify({ error: result.error }, null, 2));
29662
+ emitJson({ error: result.error });
29618
29663
  } else {
29619
29664
  narrate(result.error);
29620
29665
  }
29621
29666
  recordFailure(recorded);
29622
- process.exit(1);
29667
+ exitCli(1);
29623
29668
  }
29624
29669
  if (flags.json) {
29625
29670
  console.log(JSON.stringify(result.result, null, 2));
@@ -29629,7 +29674,7 @@ ${JSON.stringify(info.input_schema, null, 2)}${output2}`);
29629
29674
  console.log(JSON.stringify(result.result, null, 2));
29630
29675
  }
29631
29676
  if (flags.output !== void 0) {
29632
- const saved = await saveSignedLinks(signedLinks(result.result), flags.output);
29677
+ const saved = await saveSignedLinks(signedLinks(result.result), flags.output, flags.timeout);
29633
29678
  for (const file2 of saved) (flags.json ? console.error : console.log)(file2);
29634
29679
  if (saved.length === 0) console.error("(this result carries no signed link to save; a workspace file is saved by lotics download <file_id>)");
29635
29680
  }
@@ -29649,21 +29694,31 @@ ${JSON.stringify(info.input_schema, null, 2)}${output2}`);
29649
29694
  }
29650
29695
  if (resultReportsFailure(toolName, result.result)) {
29651
29696
  console.error(`${toolName} \u2192 ${resultSummary(result.result) ?? "failed"}`);
29652
- process.exit(1);
29697
+ exitCli(1);
29653
29698
  }
29654
- if (cleanupFailed) process.exit(1);
29699
+ if (cleanupFailed) exitCli(1);
29655
29700
  return;
29656
29701
  }
29657
29702
  }
29703
+ function machineError(error62, text) {
29704
+ const error_code = error62 instanceof OutcomeUnknownError ? error62.error_code : error62 instanceof LoticsRequestError && typeof error62.body.error_code === "string" ? error62.body.error_code : void 0;
29705
+ const request_id = error62 instanceof OutcomeUnknownError || error62 instanceof NoAnswerError ? error62.request_id : void 0;
29706
+ return { error: text, ...error_code === void 0 ? {} : { error_code }, ...request_id === void 0 ? {} : { request_id } };
29707
+ }
29658
29708
  function exitOnError(error62) {
29659
29709
  flushPendingWarnings();
29660
- if (error62 instanceof Error && isCustomerWorded(error62)) {
29661
- narrate(describeCliError(error62));
29662
- recordFailure(error62.telemetryMessage);
29710
+ const text = describeCliError(error62);
29711
+ const recorded = error62 instanceof OutcomeUnknownError ? error62.error_code : error62 instanceof Error && isCustomerWorded(error62) ? error62.telemetryMessage : void 0;
29712
+ if (isMachineOutput()) {
29713
+ emitJson(machineError(error62, text));
29714
+ recordFailure(recorded ?? text);
29715
+ } else if (recorded !== void 0) {
29716
+ narrate(text);
29717
+ recordFailure(recorded);
29663
29718
  } else {
29664
- console.error(describeCliError(error62));
29719
+ console.error(text);
29665
29720
  }
29666
- process.exit(1);
29721
+ exitCli(1);
29667
29722
  }
29668
29723
 
29669
29724
  // src/cli.ts