@lotics/cli 0.99.1 → 0.100.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md ADDED
@@ -0,0 +1,61 @@
1
+ # @lotics/cli — agent index
2
+
3
+ The model an agent needs before driving this CLI: which surface answers which question, what the
4
+ conventions are, and where the traps are. It deliberately does **not** list commands — `lotics --help`
5
+ is generated from the code and is the only always-current inventory.
6
+
7
+ | Read | For |
8
+ |---|---|
9
+ | `lotics --help` | The verb inventory (§ COMMANDS) and global flags. Authoritative; never stale. |
10
+ | `lotics tools` · `lotics tools <name>` | The agent tool registry and one tool's full JSON Schema. |
11
+ | [docs/cli_reference.md](./docs/cli_reference.md) | Per-command contracts, flags, exit codes, and gotchas — the detail `--help` compresses. Read it before hand-building a `set_app_*` payload: several tools REPLACE rather than patch, and a CLI verb already owns the safe assembly. |
12
+ | [docs/document_templates.md](./docs/document_templates.md) | Generating PDF/Excel/Word/email from reusable templates. |
13
+ | [docs/knowledge_docs.md](./docs/knowledge_docs.md) | Authoring the workspace facts an agent can't guess; access-vs-activation; catalog-then-stage retrieval. |
14
+ | [README.md](./README.md) | Install, auth, and worked examples. |
15
+
16
+ ## Two surfaces, and the trap between them
17
+
18
+ **`lotics tools` is not the CLI's capability list.** There are two disjoint surfaces:
19
+
20
+ - **Tools** (`lotics tools`, `lotics run <tool>`) — the *agent tool registry*: what an agent, workflow,
21
+ or automation may call. Workspace data, templates, knowledge, admin.
22
+ - **Commands** (`lotics --help` § COMMANDS) — the CLI's *own verbs*. Auth and org/workspace scoping,
23
+ file upload/download/preview, local `.xlsx`/`.docx` authoring, and the whole custom-code app loop
24
+ (scaffold, pull, deploy, codegen, dev, and running a bound workflow or agent end to end).
25
+
26
+ Several capabilities exist **only** as commands and appear nowhere in `lotics tools` — downloading a
27
+ file and running a bound app agent are the two that most often get mistaken for missing. Concluding
28
+ "the platform can't do X" from the tool list alone is a mistake; check both.
29
+
30
+ ⚠️ **`lotics <subcommand> --help` prints the generic top-level help.** It does not describe the
31
+ subcommand, so an unhelpful response there is *not* evidence the subcommand is absent. To find out
32
+ whether something exists, read `lotics --help` § COMMANDS — the whole section, not a narrow grep.
33
+
34
+ ## Conventions that hold across every command
35
+
36
+ - **Scope is resolved per invocation.** `LOTICS_ORG` / `LOTICS_WORKSPACE` (or `LOTICS_API_KEY`) scope a
37
+ single call without changing the active org or a directory pin — the safe way to touch one tenant
38
+ from a shell serving many. Every command echoes its resolved target to **stderr** (`lotics → <org> /
39
+ <workspace>`); read it back before trusting a write. Resolution precedence is in README § Organizations.
40
+ - **Large payloads bypass `ARG_MAX`** — `lotics run <tool> @args.json` or piped stdin. A leading `@` is
41
+ unambiguously a file path (JSON args start with `{`). The same ingest applies to `app workflow run`
42
+ and `app agent run`.
43
+ - **stdout is the payload, stderr is the narration.** Progress, status lines, and the target echo go to
44
+ stderr; the result goes to stdout, so piping stays clean. `--json` switches stdout from the
45
+ agent-readable summary to the full structured object.
46
+ - **Exit codes are assertable.** A command that runs remote work exits non-zero when that work failed —
47
+ `app workflow run` on `status:"error"`, `app agent run` on any settled status other than `completed`,
48
+ `workspace doctor` on findings. Scripts can gate on them.
49
+ - **Text output is the default and is built for reading**; reach for `--json` only when a field is
50
+ needed programmatically.
51
+
52
+ ## Where this CLI is not the answer
53
+
54
+ - **Authoring a binding via `app deploy`.** Deploy ships code, queries, and capabilities — it never
55
+ authors bindings. Workflow bodies go through `app workflow set`, agent instructions through
56
+ `app agent set` (both edit a file on disk that `app pull` wrote from the live row). A binding's TYPED
57
+ half — an agent's `tool_names`/`inputs`/`outputs`, a workflow's schemas — is authored by the
58
+ `set_app_*` tools. A manifest alias with no server binding only fails at the app's first call, so
59
+ deploy warns about the mismatch.
60
+ - **OAuth connections.** Attaching a connected account is web-only; the CLI can list them.
61
+ - **Anything needing a browser.** `app dev` and `file preview` shell out to a local Chrome.
package/README.md CHANGED
@@ -12,6 +12,11 @@ Lotics is an AI-powered operations platform. Through this CLI you can:
12
12
 
13
13
  ## Capability guides
14
14
 
15
+ **Driving this CLI from an agent? Start at [AGENTS.md](./AGENTS.md)** (`node_modules/@lotics/cli/AGENTS.md`)
16
+ — which surface answers which question, the conventions that hold across every command, and the traps.
17
+ Per-command contracts, flags, exit codes and gotchas are in
18
+ [docs/cli_reference.md](./docs/cli_reference.md); `lotics --help` is the always-current verb list.
19
+
15
20
  Two of the platform's primary surfaces have dedicated usage guides that ship inside this
16
21
  package (reachable at `node_modules/@lotics/cli/docs/*.md` once installed):
17
22
 
package/dist/src/cli.js CHANGED
@@ -44758,6 +44758,20 @@ var LoticsClient = class {
44758
44758
  async setAppQuery(app_id, alias, declaration) {
44759
44759
  return this.execute("set_app_query", { app_id, alias, declaration });
44760
44760
  }
44761
+ /**
44762
+ * Bind (create or replace) an app agent by alias via the `set_app_agent` tool
44763
+ * — the deploy-free authoring path for `apps.agents`, parallel to
44764
+ * `setAppWorkflow`/`setAppQuery`.
44765
+ *
44766
+ * `set_app_agent` REPLACES the whole declaration, so this takes the whole
44767
+ * declaration. `lotics app agent set` is the caller that assembles it (prose
44768
+ * from `src/agents/<alias>.md`, typed fields from the manifest) precisely so
44769
+ * no caller has to remember that a partial payload silently drops
44770
+ * `instructions`, `outputs` and the model pin.
44771
+ */
44772
+ async setAppAgent(app_id, alias, declaration) {
44773
+ return this.execute("set_app_agent", { app_id, alias, ...declaration });
44774
+ }
44761
44775
  /**
44762
44776
  * Fetch one app workflow's faithful source + bound input/output schemas via
44763
44777
  * `get_app_workflow`. `source` is the JS-subset body re-rendered from the
@@ -70077,8 +70091,14 @@ async function fetchLatestNpmVersion(packageName) {
70077
70091
  return null;
70078
70092
  }
70079
70093
  }
70094
+ function toManifestAgents(agents) {
70095
+ return Object.fromEntries(
70096
+ Object.entries(agents).map(([alias, { instructions: _prose, ...typed }]) => [alias, typed])
70097
+ );
70098
+ }
70080
70099
  var WORKFLOWS_DIR = path5.join("src", "workflows");
70081
70100
  var WORKFLOW_GLOBALS_DIR = path5.join(".lotics", "workflows");
70101
+ var AGENTS_DIR = path5.join("src", "agents");
70082
70102
  var WORKFLOW_TSCONFIG_EXCLUDES = ["src/workflows", ".lotics/workflows"];
70083
70103
  var LOTICS_INCLUDE_GLOB = ".lotics/**/*";
70084
70104
  var STALE_LOTICS_INCLUDES = /* @__PURE__ */ new Set([".lotics", "./.lotics", ".lotics/"]);
@@ -70126,6 +70146,39 @@ ${envelope.prefix}${body}${envelope.suffix}
70126
70146
  `);
70127
70147
  return file2;
70128
70148
  }
70149
+ function agentFilePath(projectDir, alias) {
70150
+ return path5.join(projectDir, AGENTS_DIR, `${alias}.md`);
70151
+ }
70152
+ function agentFileHeader(alias) {
70153
+ return `<!-- lotics: instructions for agent "${alias}".
70154
+ Pulled from the LIVE app row; edit here, then: lotics app agent set ${alias}
70155
+ The typed fields (inputs/outputs/tool_names/model_id) live in package.json#lotics.agents.${alias} -->`;
70156
+ }
70157
+ function stripAgentHeader(text) {
70158
+ return text.replace(/<!--\s*lotics:[\s\S]*?-->\n?/g, "").replace(/\n{3,}/g, "\n\n").trim();
70159
+ }
70160
+ function writeAgentFile(projectDir, alias, instructions) {
70161
+ fs4.mkdirSync(path5.join(projectDir, AGENTS_DIR), { recursive: true });
70162
+ const file2 = agentFilePath(projectDir, alias);
70163
+ fs4.writeFileSync(file2, `${agentFileHeader(alias)}
70164
+
70165
+ ${instructions.replace(/\s+$/, "")}
70166
+ `);
70167
+ return file2;
70168
+ }
70169
+ function writeAgentFiles(projectDir, agents) {
70170
+ const written = [];
70171
+ for (const [alias, declaration] of Object.entries(agents)) {
70172
+ const instructions = declaration.instructions;
70173
+ if (typeof instructions !== "string" || instructions.trim() === "") {
70174
+ console.error(`\u26A0 Skipped src/agents/${alias}.md \u2014 the live declaration carries no instructions.`);
70175
+ continue;
70176
+ }
70177
+ writeAgentFile(projectDir, alias, instructions);
70178
+ written.push(alias);
70179
+ }
70180
+ return written;
70181
+ }
70129
70182
  async function writeWorkflowFiles(client, projectDir, app_id, workflows) {
70130
70183
  const written = [];
70131
70184
  for (const [alias, declaration] of Object.entries(workflows)) {
@@ -70428,9 +70481,15 @@ function stampPulledManifest(projectDir, args) {
70428
70481
  version_number: args.version_number,
70429
70482
  workflows: args.workflows,
70430
70483
  queries: args.queries,
70431
- agents: args.agents
70484
+ // The prose is stripped here and only here: `args.agents` is the LIVE map
70485
+ // (its instructions feed `writeAgentFiles`), the manifest gets the typed half.
70486
+ agents: toManifestAgents(args.agents)
70487
+ });
70488
+ writeAppDts(projectDir, {
70489
+ workflows: args.workflows,
70490
+ queries: args.queries,
70491
+ agents: toManifestAgents(args.agents)
70432
70492
  });
70433
- writeAppDts(projectDir, { workflows: args.workflows, queries: args.queries, agents: args.agents });
70434
70493
  }
70435
70494
  async function downloadToFile(url2, destPath) {
70436
70495
  const response = await fetch(url2);
@@ -70591,6 +70650,15 @@ async function appPull(client, args) {
70591
70650
  );
70592
70651
  }
70593
70652
  }
70653
+ const agents = app.agents ?? {};
70654
+ if (Object.keys(agents).length > 0) {
70655
+ const written = writeAgentFiles(targetPath, agents);
70656
+ if (written.length > 0) {
70657
+ console.error(
70658
+ `Wrote ${written.length} agent instruction ${written.length === 1 ? "file" : "files"} to ${AGENTS_DIR}/ (${written.join(", ")})`
70659
+ );
70660
+ }
70661
+ }
70594
70662
  console.error(`Installing npm dependencies...`);
70595
70663
  await runNpm(["install"], targetPath);
70596
70664
  console.error(`
@@ -70952,6 +71020,40 @@ Agent "${args.alias}" run ${run.id} \u2192 ${run.status}${run.error_message ? `:
70952
71020
  );
70953
71021
  if (run.status !== "completed") process.exit(1);
70954
71022
  }
71023
+ async function appAgentSet(client, args) {
71024
+ const projectDir = process.cwd();
71025
+ const meta3 = readAppMeta(projectDir);
71026
+ const app = await client.getApp(meta3.app_id);
71027
+ const live = app.agents?.[args.alias];
71028
+ if (!live) {
71029
+ console.error(
71030
+ `App ${meta3.app_id} has no bound agent "${args.alias}". Bind it first (set_app_agent), then 'lotics app pull' to write its instructions.`
71031
+ );
71032
+ process.exit(1);
71033
+ }
71034
+ const file2 = agentFilePath(projectDir, args.alias);
71035
+ if (!fs4.existsSync(file2)) {
71036
+ console.error(
71037
+ `No instructions at ${path5.relative(projectDir, file2)}. Run 'lotics app pull ${meta3.app_id}' to write ${AGENTS_DIR}/${args.alias}.md, then edit it.`
71038
+ );
71039
+ process.exit(1);
71040
+ }
71041
+ const instructions = stripAgentHeader(fs4.readFileSync(file2, "utf-8"));
71042
+ if (instructions === "") {
71043
+ console.error(
71044
+ `${path5.relative(projectDir, file2)} is empty after stripping the header \u2014 refusing to push an empty prompt.`
71045
+ );
71046
+ process.exit(1);
71047
+ }
71048
+ const res = await client.setAppAgent(meta3.app_id, args.alias, { ...live, instructions });
71049
+ if (res.error) {
71050
+ console.error(`Failed to set agent "${args.alias}": ${res.error}`);
71051
+ process.exit(1);
71052
+ }
71053
+ console.error(
71054
+ `Set agent "${args.alias}" (${instructions.length} chars of instructions` + (live.model_id ? `, ${live.model_id}` : "") + `). Typed fields taken from the live row.`
71055
+ );
71056
+ }
70955
71057
  async function appWorkflowSet(client, args) {
70956
71058
  const projectDir = process.cwd();
70957
71059
  const meta3 = readAppMeta(projectDir);
@@ -89378,13 +89480,184 @@ var formattingSchema = external_exports.object({
89378
89480
  superscript: external_exports.boolean().optional(),
89379
89481
  subscript: external_exports.boolean().optional(),
89380
89482
  all_caps: external_exports.boolean().optional(),
89381
- small_caps: external_exports.boolean().optional()
89483
+ small_caps: external_exports.boolean().optional(),
89484
+ language: external_exports.object({
89485
+ value: external_exports.string().optional().describe("Latin-script proofing language, e.g. vi-VN"),
89486
+ east_asia: external_exports.string().optional(),
89487
+ bidi: external_exports.string().optional()
89488
+ }).optional().describe(
89489
+ "Proofing language (`w:lang`). Changes nothing about how the run renders \u2014 it selects the dictionary Word spell-checks it against, so a value written into a form keeps the form's own language instead of inheriting the label's"
89490
+ )
89382
89491
  });
89383
89492
  var runSchema = external_exports.object({
89384
89493
  text: external_exports.string(),
89385
89494
  formatting: formattingSchema.optional()
89386
89495
  });
89387
89496
 
89497
+ // ../ooxml/src/queries.ts
89498
+ function getBodyElementType(el) {
89499
+ const tag = getTagName(el);
89500
+ if (tag === "w:p") return "paragraph";
89501
+ if (tag === "w:tbl") return "table";
89502
+ return "other";
89503
+ }
89504
+ function extractParagraphText(el) {
89505
+ const tag = getTagName(el);
89506
+ if (tag !== "w:p") return "";
89507
+ const parts = [];
89508
+ for (const child of getChildren(el)) {
89509
+ const childTag = getTagName(child);
89510
+ if (childTag === "w:r") {
89511
+ for (const runChild of getChildren(child)) {
89512
+ if (getTagName(runChild) === "w:t") {
89513
+ parts.push(getTextContent(runChild));
89514
+ }
89515
+ }
89516
+ } else if (childTag === "w:hyperlink") {
89517
+ for (const hlChild of getChildren(child)) {
89518
+ if (getTagName(hlChild) === "w:r") {
89519
+ for (const runChild of getChildren(hlChild)) {
89520
+ if (getTagName(runChild) === "w:t") {
89521
+ parts.push(getTextContent(runChild));
89522
+ }
89523
+ }
89524
+ }
89525
+ }
89526
+ }
89527
+ }
89528
+ return parts.join("");
89529
+ }
89530
+ function getRunsFromParagraph(el) {
89531
+ const runs = [];
89532
+ for (const child of getChildren(el)) {
89533
+ if (getTagName(child) !== "w:r") continue;
89534
+ let text = "";
89535
+ let hasText = false;
89536
+ for (const grandchild of getChildren(child)) {
89537
+ if (getTagName(grandchild) !== "w:t") continue;
89538
+ hasText = true;
89539
+ for (const tn of getChildren(grandchild)) {
89540
+ if (typeof tn["#text"] === "string") text += tn["#text"];
89541
+ }
89542
+ }
89543
+ if (hasText) runs.push({ element: child, text });
89544
+ }
89545
+ return runs;
89546
+ }
89547
+ function writeRunText(runElement, newText) {
89548
+ const children = getChildren(runElement);
89549
+ const textNode = { "w:t": [{ "#text": newText }], ":@": { "@_xml:space": "preserve" } };
89550
+ const indices = children.flatMap((c, i2) => getTagName(c) === "w:t" ? [i2] : []);
89551
+ if (indices.length === 0) {
89552
+ children.push(textNode);
89553
+ return;
89554
+ }
89555
+ children[indices[0]] = textNode;
89556
+ for (let i2 = indices.length - 1; i2 >= 1; i2--) children.splice(indices[i2], 1);
89557
+ }
89558
+ function setRunText(run, newText) {
89559
+ writeRunText(run.element, newText);
89560
+ run.text = newText;
89561
+ }
89562
+ function computeReplacementRanges(text, query, replacement, matchType, maxReplacements, startCount) {
89563
+ const ranges = [];
89564
+ let count = startCount;
89565
+ if (matchType === "exact") {
89566
+ if (text === query && count < maxReplacements) {
89567
+ ranges.push({ start: 0, end: text.length, replacement });
89568
+ count++;
89569
+ }
89570
+ return { ranges, count };
89571
+ }
89572
+ if (matchType === "regex") {
89573
+ const re2 = new RegExp(query, "gi");
89574
+ let match2;
89575
+ while (count < maxReplacements && (match2 = re2.exec(text)) !== null) {
89576
+ ranges.push({ start: match2.index, end: match2.index + match2[0].length, replacement });
89577
+ count++;
89578
+ if (match2[0].length === 0) re2.lastIndex++;
89579
+ }
89580
+ return { ranges, count };
89581
+ }
89582
+ if (query.length === 0) return { ranges, count };
89583
+ const lower2 = text.toLowerCase();
89584
+ const lowerQuery = query.toLowerCase();
89585
+ let searchFrom = 0;
89586
+ while (count < maxReplacements) {
89587
+ const idx = lower2.indexOf(lowerQuery, searchFrom);
89588
+ if (idx === -1) break;
89589
+ ranges.push({ start: idx, end: idx + query.length, replacement });
89590
+ searchFrom = idx + query.length;
89591
+ count++;
89592
+ }
89593
+ return { ranges, count };
89594
+ }
89595
+ function applyRangeReplacements(runs, ranges) {
89596
+ if (ranges.length === 0) return;
89597
+ const bounds = [];
89598
+ let offset = 0;
89599
+ for (const run of runs) {
89600
+ bounds.push({ run, start: offset, end: offset + run.text.length });
89601
+ offset += run.text.length;
89602
+ }
89603
+ const joined = runs.map((r) => r.text).join("");
89604
+ const sorted = [...ranges].sort((a, b) => a.start - b.start);
89605
+ for (const { run, start: runStart, end: runEnd } of bounds) {
89606
+ let next = "";
89607
+ let cursor = runStart;
89608
+ for (const range2 of sorted) {
89609
+ if (range2.end <= runStart || range2.start >= runEnd) continue;
89610
+ const keepUntil = Math.min(range2.start, runEnd);
89611
+ const from = Math.max(cursor, runStart);
89612
+ if (keepUntil > from) next += joined.slice(from, keepUntil);
89613
+ if (runStart <= range2.start && range2.start < runEnd) next += range2.replacement;
89614
+ cursor = Math.max(cursor, range2.end);
89615
+ }
89616
+ const tail = Math.max(cursor, runStart);
89617
+ if (runEnd > tail) next += joined.slice(tail, runEnd);
89618
+ if (next !== run.text) setRunText(run, next);
89619
+ }
89620
+ }
89621
+ function replaceInParagraph(el, query, replacement, matchType, maxReplacements, replacementsMade) {
89622
+ if (!extractParagraphText(el)) return replacementsMade;
89623
+ const runs = getRunsFromParagraph(el);
89624
+ if (runs.length === 0) return replacementsMade;
89625
+ const text = runs.length === 1 ? runs[0].text : runs.map((r) => r.text).join("");
89626
+ const { ranges, count } = computeReplacementRanges(text, query, replacement, matchType, maxReplacements, replacementsMade);
89627
+ applyRangeReplacements(runs, ranges);
89628
+ return count;
89629
+ }
89630
+ function replaceText(bodyElements, query, replacement, matchType = "contains", maxReplacements = Infinity) {
89631
+ if (matchType === "regex") {
89632
+ try {
89633
+ new RegExp(query);
89634
+ } catch {
89635
+ throw new Error(`Invalid regex pattern: ${query}`);
89636
+ }
89637
+ }
89638
+ let replacementsMade = 0;
89639
+ for (let i2 = 0; i2 < bodyElements.length && replacementsMade < maxReplacements; i2++) {
89640
+ const el = bodyElements[i2];
89641
+ const type = getBodyElementType(el);
89642
+ if (type === "paragraph") {
89643
+ replacementsMade = replaceInParagraph(el, query, replacement, matchType, maxReplacements, replacementsMade);
89644
+ } else if (type === "table") {
89645
+ for (const child of getChildren(el)) {
89646
+ if (getTagName(child) !== "w:tr") continue;
89647
+ for (const cell of getChildren(child)) {
89648
+ if (getTagName(cell) !== "w:tc") continue;
89649
+ for (const p of getChildren(cell)) {
89650
+ if (getTagName(p) === "w:p" && replacementsMade < maxReplacements) {
89651
+ replacementsMade = replaceInParagraph(p, query, replacement, matchType, maxReplacements, replacementsMade);
89652
+ }
89653
+ }
89654
+ }
89655
+ }
89656
+ }
89657
+ }
89658
+ return replacementsMade;
89659
+ }
89660
+
89388
89661
  // ../ooxml/src/sections.ts
89389
89662
  var PAGE_SIZES = {
89390
89663
  letter: { w: 12240, h: 15840 },
@@ -90380,170 +90653,6 @@ async function ensureContentTypeOverride(doc, partName, contentType) {
90380
90653
  doc.zip.file("[Content_Types].xml", updated);
90381
90654
  }
90382
90655
 
90383
- // ../ooxml/src/queries.ts
90384
- function getBodyElementType(el) {
90385
- const tag = getTagName(el);
90386
- if (tag === "w:p") return "paragraph";
90387
- if (tag === "w:tbl") return "table";
90388
- return "other";
90389
- }
90390
- function extractParagraphText(el) {
90391
- const tag = getTagName(el);
90392
- if (tag !== "w:p") return "";
90393
- const parts = [];
90394
- for (const child of getChildren(el)) {
90395
- const childTag = getTagName(child);
90396
- if (childTag === "w:r") {
90397
- for (const runChild of getChildren(child)) {
90398
- if (getTagName(runChild) === "w:t") {
90399
- parts.push(getTextContent(runChild));
90400
- }
90401
- }
90402
- } else if (childTag === "w:hyperlink") {
90403
- for (const hlChild of getChildren(child)) {
90404
- if (getTagName(hlChild) === "w:r") {
90405
- for (const runChild of getChildren(hlChild)) {
90406
- if (getTagName(runChild) === "w:t") {
90407
- parts.push(getTextContent(runChild));
90408
- }
90409
- }
90410
- }
90411
- }
90412
- }
90413
- }
90414
- return parts.join("");
90415
- }
90416
- function getRunsFromParagraph(el) {
90417
- const runs = [];
90418
- for (const child of getChildren(el)) {
90419
- if (getTagName(child) !== "w:r") continue;
90420
- let text = "";
90421
- let textIdx = -1;
90422
- const children = getChildren(child);
90423
- for (let i2 = 0; i2 < children.length; i2++) {
90424
- if (getTagName(children[i2]) === "w:t") {
90425
- const tChildren = getChildren(children[i2]);
90426
- for (const tn of tChildren) {
90427
- if (typeof tn["#text"] === "string") {
90428
- text += tn["#text"];
90429
- }
90430
- }
90431
- textIdx = i2;
90432
- }
90433
- }
90434
- if (textIdx >= 0) {
90435
- runs.push({ element: child, text, textNodeIndex: textIdx });
90436
- }
90437
- }
90438
- return runs;
90439
- }
90440
- function setRunText(run, newText) {
90441
- const children = getChildren(run.element);
90442
- children[run.textNodeIndex] = {
90443
- "w:t": [{ "#text": newText }],
90444
- ":@": { "@_xml:space": "preserve" }
90445
- };
90446
- run.text = newText;
90447
- }
90448
- function computeReplacementRanges(text, query, replacement, matchType, maxReplacements, startCount) {
90449
- const ranges = [];
90450
- let count = startCount;
90451
- if (matchType === "exact") {
90452
- if (text === query && count < maxReplacements) {
90453
- ranges.push({ start: 0, end: text.length, replacement });
90454
- count++;
90455
- }
90456
- return { ranges, count };
90457
- }
90458
- if (matchType === "regex") {
90459
- const re2 = new RegExp(query, "gi");
90460
- let match2;
90461
- while (count < maxReplacements && (match2 = re2.exec(text)) !== null) {
90462
- ranges.push({ start: match2.index, end: match2.index + match2[0].length, replacement });
90463
- count++;
90464
- if (match2[0].length === 0) re2.lastIndex++;
90465
- }
90466
- return { ranges, count };
90467
- }
90468
- if (query.length === 0) return { ranges, count };
90469
- const lower2 = text.toLowerCase();
90470
- const lowerQuery = query.toLowerCase();
90471
- let searchFrom = 0;
90472
- while (count < maxReplacements) {
90473
- const idx = lower2.indexOf(lowerQuery, searchFrom);
90474
- if (idx === -1) break;
90475
- ranges.push({ start: idx, end: idx + query.length, replacement });
90476
- searchFrom = idx + query.length;
90477
- count++;
90478
- }
90479
- return { ranges, count };
90480
- }
90481
- function applyRangeReplacements(runs, ranges) {
90482
- if (ranges.length === 0) return;
90483
- const bounds = [];
90484
- let offset = 0;
90485
- for (const run of runs) {
90486
- bounds.push({ run, start: offset, end: offset + run.text.length });
90487
- offset += run.text.length;
90488
- }
90489
- const joined = runs.map((r) => r.text).join("");
90490
- const sorted = [...ranges].sort((a, b) => a.start - b.start);
90491
- for (const { run, start: runStart, end: runEnd } of bounds) {
90492
- let next = "";
90493
- let cursor = runStart;
90494
- for (const range2 of sorted) {
90495
- if (range2.end <= runStart || range2.start >= runEnd) continue;
90496
- const keepUntil = Math.min(range2.start, runEnd);
90497
- const from = Math.max(cursor, runStart);
90498
- if (keepUntil > from) next += joined.slice(from, keepUntil);
90499
- if (runStart <= range2.start && range2.start < runEnd) next += range2.replacement;
90500
- cursor = Math.max(cursor, range2.end);
90501
- }
90502
- const tail = Math.max(cursor, runStart);
90503
- if (runEnd > tail) next += joined.slice(tail, runEnd);
90504
- if (next !== run.text) setRunText(run, next);
90505
- }
90506
- }
90507
- function replaceInParagraph(el, query, replacement, matchType, maxReplacements, replacementsMade) {
90508
- if (!extractParagraphText(el)) return replacementsMade;
90509
- const runs = getRunsFromParagraph(el);
90510
- if (runs.length === 0) return replacementsMade;
90511
- const text = runs.length === 1 ? runs[0].text : runs.map((r) => r.text).join("");
90512
- const { ranges, count } = computeReplacementRanges(text, query, replacement, matchType, maxReplacements, replacementsMade);
90513
- applyRangeReplacements(runs, ranges);
90514
- return count;
90515
- }
90516
- function replaceText(bodyElements, query, replacement, matchType = "contains", maxReplacements = Infinity) {
90517
- if (matchType === "regex") {
90518
- try {
90519
- new RegExp(query);
90520
- } catch {
90521
- throw new Error(`Invalid regex pattern: ${query}`);
90522
- }
90523
- }
90524
- let replacementsMade = 0;
90525
- for (let i2 = 0; i2 < bodyElements.length && replacementsMade < maxReplacements; i2++) {
90526
- const el = bodyElements[i2];
90527
- const type = getBodyElementType(el);
90528
- if (type === "paragraph") {
90529
- replacementsMade = replaceInParagraph(el, query, replacement, matchType, maxReplacements, replacementsMade);
90530
- } else if (type === "table") {
90531
- for (const child of getChildren(el)) {
90532
- if (getTagName(child) !== "w:tr") continue;
90533
- for (const cell of getChildren(child)) {
90534
- if (getTagName(cell) !== "w:tc") continue;
90535
- for (const p of getChildren(cell)) {
90536
- if (getTagName(p) === "w:p" && replacementsMade < maxReplacements) {
90537
- replacementsMade = replaceInParagraph(p, query, replacement, matchType, maxReplacements, replacementsMade);
90538
- }
90539
- }
90540
- }
90541
- }
90542
- }
90543
- }
90544
- return replacementsMade;
90545
- }
90546
-
90547
90656
  // ../docx/src/parse/parser.ts
90548
90657
  var import_jszip2 = __toESM(require_lib4(), 1);
90549
90658
  async function parseDocx(buffer) {
@@ -91683,6 +91792,10 @@ COMMANDS
91683
91792
  (inputs: inline JSON, @file, or stdin; streams
91684
91793
  progress to stderr, reports the settled run;
91685
91794
  --session <id> continues a thread; --json)
91795
+ lotics app agent set <alias> Push the edited src/agents/<alias>.md instructions
91796
+ + the manifest's typed fields through set_app_agent
91797
+ (set_app_agent REPLACES the declaration \u2014 this
91798
+ sends it whole so nothing is silently dropped)
91686
91799
  lotics app subdomain <new-subdomain> Rename the app's public <slug>.lotics.app address
91687
91800
  lotics app rename "<new name>" Rename the app's display name (launcher title)
91688
91801
  lotics app dev [path] Run the app locally with HMR (RPC forwarded to prod)
@@ -92498,6 +92611,8 @@ Available workspaces:`);
92498
92611
  console.error(" cat inputs.json | lotics app agent run <app_id> <alias> (read inputs from stdin)");
92499
92612
  console.error("Streams the run's progress to stderr; reports the settled run (structured output / text) to stdout.");
92500
92613
  console.error("--session <id> continues an existing thread; omitted mints a fresh session per run.");
92614
+ console.error("");
92615
+ console.error(" lotics app agent set <alias> Push src/agents/<alias>.md back through set_app_agent");
92501
92616
  process.exit(1);
92502
92617
  };
92503
92618
  if (action === "run") {
@@ -92525,6 +92640,16 @@ Available workspaces:`);
92525
92640
  });
92526
92641
  return;
92527
92642
  }
92643
+ if (action === "set") {
92644
+ const alias = restArgs[0];
92645
+ if (!alias) {
92646
+ console.error("Usage: lotics app agent set <alias>");
92647
+ console.error(" Edits src/agents/<alias>.md (written by 'lotics app pull').");
92648
+ process.exit(1);
92649
+ }
92650
+ await appAgentSet(client, { alias });
92651
+ return;
92652
+ }
92528
92653
  agentUsage();
92529
92654
  }
92530
92655
  if (subcommand === "query") {
@@ -867,6 +867,24 @@ export declare class LoticsClient {
867
867
  ast: unknown;
868
868
  params?: Record<string, unknown>;
869
869
  }): Promise<ToolExecuteResult>;
870
+ /**
871
+ * Bind (create or replace) an app agent by alias via the `set_app_agent` tool
872
+ * — the deploy-free authoring path for `apps.agents`, parallel to
873
+ * `setAppWorkflow`/`setAppQuery`.
874
+ *
875
+ * `set_app_agent` REPLACES the whole declaration, so this takes the whole
876
+ * declaration. `lotics app agent set` is the caller that assembles it (prose
877
+ * from `src/agents/<alias>.md`, typed fields from the manifest) precisely so
878
+ * no caller has to remember that a partial payload silently drops
879
+ * `instructions`, `outputs` and the model pin.
880
+ */
881
+ setAppAgent(app_id: string, alias: string,
882
+ /** The WHOLE declaration. Typed loosely on purpose: the caller builds it by
883
+ * spreading the live one, so a field the server adds later is forwarded
884
+ * without this signature (or the caller) having to learn about it. */
885
+ declaration: Record<string, unknown> & {
886
+ instructions: string;
887
+ }): Promise<ToolExecuteResult>;
870
888
  /**
871
889
  * Fetch one app workflow's faithful source + bound input/output schemas via
872
890
  * `get_app_workflow`. `source` is the JS-subset body re-rendered from the
@@ -560,6 +560,24 @@ export class LoticsClient {
560
560
  async setAppQuery(app_id, alias, declaration) {
561
561
  return this.execute("set_app_query", { app_id, alias, declaration });
562
562
  }
563
+ /**
564
+ * Bind (create or replace) an app agent by alias via the `set_app_agent` tool
565
+ * — the deploy-free authoring path for `apps.agents`, parallel to
566
+ * `setAppWorkflow`/`setAppQuery`.
567
+ *
568
+ * `set_app_agent` REPLACES the whole declaration, so this takes the whole
569
+ * declaration. `lotics app agent set` is the caller that assembles it (prose
570
+ * from `src/agents/<alias>.md`, typed fields from the manifest) precisely so
571
+ * no caller has to remember that a partial payload silently drops
572
+ * `instructions`, `outputs` and the model pin.
573
+ */
574
+ async setAppAgent(app_id, alias,
575
+ /** The WHOLE declaration. Typed loosely on purpose: the caller builds it by
576
+ * spreading the live one, so a field the server adds later is forwarded
577
+ * without this signature (or the caller) having to learn about it. */
578
+ declaration) {
579
+ return this.execute("set_app_agent", { app_id, alias, ...declaration });
580
+ }
563
581
  /**
564
582
  * Fetch one app workflow's faithful source + bound input/output schemas via
565
583
  * `get_app_workflow`. `source` is the JS-subset body re-rendered from the
@@ -0,0 +1,50 @@
1
+ # @lotics/cli — CLI Command Reference
2
+
3
+ Per-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.
4
+
5
+ | Command | What it does |
6
+ |---|---|
7
+ | `lotics` / `lotics --help` | Show full help with capabilities, tool categories, workflow |
8
+ | `lotics auth signup <email>` | Create account + org + API key, sends magic link email. Registers the new org as a profile; `--local` pins this directory to it (pointer) instead of setting the global default. |
9
+ | `lotics auth api-key [key]` | `whoami` → **upsert** the key's org as a profile in the global store (never overwrites). `--local` additionally pins this directory to it (pointer) instead of setting the global default. |
10
+ | `lotics auth web` | Send a magic link email to access the web app (requires auth) |
11
+ | `lotics auth whoami` | Print active account name, email, org, resolved workspace, and the resolution **source** (flag/env/local/app-manifest/global). `--json` adds `workspace_id` + `source`. |
12
+ | `lotics auth logout [<name\|id>]` | In a pinned dir: delete the local pin. Else: remove one profile (default the active org). `--all`: wipe the global store. |
13
+ | `lotics org` | List saved orgs (profiles) from the global store, marks active for this directory (a local pin wins over the global default). |
14
+ | `lotics org use <name\|id> [--local]` | Switch the active org by org name (case-insensitive, ambiguous → error) or id. No flag → global `active_org`; `--local` → a `.lotics/config.json` pointer in the current dir. |
15
+ | `lotics workspace` | List workspaces in the active org, marks current with `(current)` |
16
+ | `lotics workspace select <id>` | Set the workspace in the **active scope** — a local pin if the dir has one, else the active org's global profile |
17
+ | `lotics workspace create <name>` | Create a new workspace (admin only), auto-switches to it. |
18
+ | `lotics workspace delete <id> --yes` | Delete a workspace by id (admin only). **Soft delete** — `archived_at` is set, so it drops out of listings and can no longer be selected (the workspace middleware resolves `x-workspace-id` through `getById`, which excludes archived rows, so its tables/records/etc. go dark), while the data is retained and recoverable. Its **apps are cascade-archived** too — every app entry point (embedded, public link, standalone subdomain) resolves its workspace from the app row via `getApp`/`getBySubdomain` (gated only on the app's own `archived_at`), bypassing the middleware, so without the cascade a deleted workspace's apps would keep serving/mutating data (incl. anonymous public links). 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). |
19
+ | `lotics workspace doctor` | Report workspace-wide dangling schema references via `GET /v1/workspaces/dangling-references` — every active app/workflow artifact whose prefixed schema id no longer resolves, printed as `<referent.kind> "<name>" (<id>) → <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. |
20
+ | `lotics tools` | List tools by category with descriptions |
21
+ | `lotics tools <name>` | Full description + JSON Schema for one tool |
22
+ | `lotics run <tool> '<json>'` | Execute a tool (text output via toModelOutput). Args may also come from a file (`lotics run <tool> @args.json`) or piped stdin (`cat args.json \| lotics run <tool>`) — 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 `{`). |
23
+ | `lotics run <tool> --json '<json>'` | Execute a tool (full JSON output) |
24
+ | `lotics upload <file\|dir...>` | Upload files/directories via multipart POST to /v1/files |
25
+ | `lotics file download <file_id> [-o <dir>]` | (alias `lotics download`) Download a stored file: `GET /v1/files/{id}/signed_url` → fetch the presigned URL, saving under the stored filename (from the response's `Content-Disposition`) into `-o` (a **DIRECTORY** — note this is distinct from `lotics file preview`'s `-o`, which is a FILE path), else cwd. `lotics file download record <record_id> <field_key>` pulls every file on a record's file field. |
26
+ | `lotics knowledge list` | List knowledge docs via the `list_knowledge` tool — a table of id, name, description (`--json` for the raw results array). |
27
+ | `lotics knowledge create --name <n> [--description <d>] (--from <file.md> \| --content <str>)` | Read the body client-side (a file XOR an inline string — exactly one required), then call `create_knowledge` with `{ name, description, content }` (description defaults to `""`). Prints the new id to stdout. Large files ride the POST body fine. |
28
+ | `lotics knowledge get <id> [-o <file.md>]` | `GET /v1/knowledge_docs/{id}` (`getKnowledgeDoc`) → the doc with its **hydrated `content`** (the one content-read path for a non-sandbox client; works for file-model AND legacy parked-column rows). `-o` writes the body via `writeFileAtomic`; else the body goes to stdout. `--json` prints the full doc instead. |
29
+ | `lotics knowledge update <id> [--from <file.md> \| --content <str>] [--name <n>] [--description <d>]` | Call `update_knowledge` with **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`). At least one field required; --from and --content are mutually exclusive. |
30
+ | `lotics knowledge rm <id>` | Archive the doc via `delete_knowledge` (`{ knowledge_doc_id }`). The REST execute path does not gate `needsApproval`, so this runs unattended. |
31
+ | `lotics app create <name> [path]` | Scaffold a Vite+React+TS custom-code app project; POST /v1/apps; npm install; vite build; upload as v1 |
32
+ | `lotics app pull <app_id> [path]` | Download source archive from R2 (presigned), extract, npm install, stamp package.json's `lotics` field. With no `[path]`: refresh the cwd IN PLACE when it's already this app's own project (its manifest `app_id` matches — the documented `cd <app> && lotics app pull` flow), else clone into an `<name>/` subdir; this avoids the stray nested `./<name>/` subdir a pull-from-inside-the-app used to drop. — `workflows` and `agents` are sourced from the live App row (NOT the archived manifest), so `set_app_workflow` / `set_app_agent` authoring survives the pull. Regenerates `.lotics/app_{workflows,queries,agents}.d.ts` so `useWorkflow` / `useQuery` / `useAgentRun` stay typed. Also writes one `src/workflows/<alias>.ts` per bound workflow (faithful body from `get_app_workflow`) and one `src/agents/<alias>.md` per bound agent (its instructions, straight off the live row) — so the prose an author actually edits lives in a file, and pull always overwrites it from live, leaving no second copy to drift. A legacy workflow alias with no rendered source, or an agent with no instructions, warns and is skipped. The stamped `lotics.agents` map carries the TYPED half only (`inputs`/`outputs`/`tool_names`/`model_id`/…) — an agent's prose lives solely in its `.md`, so there is never a second local copy to desync; a stale `instructions` left by an older CLI is inert and disappears on the next pull |
33
+ | `lotics app deploy -m <message>` | **`-m` is REQUIRED** (CLI errors without a non-empty message) — each deploy is a version row read back by `lotics app versions`, so a blank message loses the audit trail. npm run build; tar source + dist; POST /v1/apps/{id}/versions multipart. Carries code + queries + capabilities only — workflow bindings are NOT a deploy concern (`set_app_workflow` / `remove_app_workflow` own `apps.workflows`; the manifest's `workflows` map is a pulled reflection used only for `useWorkflow` codegen). Deploy DOES send the manifest's `lotics.workflows` alias KEYS (not the bindings) as `workflow_aliases`, recorded on the version row so `remove_app_workflow` can refuse to unbind an alias the served version still declares. After a successful deploy it also **warns loudly about any `lotics.workflows` / `lotics.agents` alias declared in the manifest but NOT bound on the server** (a `getApp` diff via `warnIfUnboundAliases`) — since deploy never binds them, that would otherwise throw only at the app's first `useWorkflow` / `useAgentRun` call; the warning points to `lotics app workflow set` / `set_app_agent`. Advisory only (never fails the deploy). |
34
+ | `lotics app versions [app_id]` | `GET /v1/apps/{id}/versions` — print deploy history newest-first (version number, timestamp, deployer name, build status, the `-m` message; `*` marks the currently-served version). app_id from the local manifest, or pass one to inspect any app without pulling it. Admin-only server-side (mirrors deploy + source download). Answers "what shipped, when, by whom" — e.g. whether a fix was live at an incident's time. The deploy pipeline already persisted all of this in `app_versions`; this is the read surface. Title → stderr, table → stdout (pipeable). |
35
+ | `lotics app codegen [path]` | Regenerate `.lotics/*` from the manifest + workspace schema **without a deploy**. The three `.d.ts` companions (`app_{workflows,queries,agents}.d.ts`) are always rewritten (synchronous, no network). When credentials resolve, also rewrites the **runtime** `.lotics/app_fields.ts` — **branched on whether the app is a package installation** (`getApp().package_id` set, from `generate_package_fields.ts`): a **linked/published** app emits the BINDING form (`F`/`OPT`/`ROLE` resolved from the installation's LIVE binding — via `appBinding` / the `binding` RPC — at module load through `getAppBinding()` + top-level await, so the source stays portable across every install); a **bespoke** app emits the BAKED form (`generate_app_fields.ts`) — a real `.ts` exporting `F` (table→field→`"fld_…"`) + `OPT` (table→select-field→option→`"opt_…"`) keyed by display-name aliases, for the tables the app's queries reference (+ optional `package.json#lotics.codegen.tables` allowlist). Both forms share the `F`/`OPT` shape (contract aliases derive from the same slugified display names), so a published origin's deployed source compiles unchanged. Writing the BINDING form also heals the project's vitest setup (`ensureAppVitestSetup`, folded into the same write boundary): the binding form awaits `getAppBinding()` (a network call) at module load, so without a stub `npm test` fails to collect any test that imports the app graph — the heal writes `vitest.setup.ts` (mocks only `getAppBinding`, returning an echo binding: any alias → a self-identifying `fld:test:…`/`opt:test:…`/`grp:test:…` id) if absent, and warns the one-liner to add to `vite.config.ts`'s `test.setupFiles` if the wiring is missing (TS source isn't safely munged, mirroring `ensureAppTsconfig`'s JSONC-tsconfig warn). New scaffolds ship both. Also refreshes each bound workflow's `.lotics/workflows/<alias>.globals.d.ts` + re-wraps its EXISTING `src/workflows/<alias>.ts` body in the current envelope (strips + re-wraps; never re-fetches the body, so local edits survive). A getApp / binding / schema / dts-fetch failure is non-fatal (warns, keeps the last-generated files). |
36
+ | `lotics app workflow run <alias> '<json>'` | Execute a bound app workflow end-to-end via `appWorkflow`. `app_id` comes from the local manifest; the alias must be bound (`set_app_workflow`). Inputs ingest exactly like `lotics run` (inline JSON / `@file` / stdin — bulk inputs bypass `ARG_MAX`). Prints the full `{status,message,data,files,side_effects}` JSON to stdout + a one-line summary to stderr; exits non-zero on `status:"error"` (assertable). `--print-created` (alias `--report-effects`) renders the honest post-run harvest (GAP-58): created records grouped by table, a paste-ready `lotics run delete_records …` per table, then the **mandatory caveat** naming what cannot be auto-undone (external integrations + notifications) and that sub-workflows may have run. `--cleanup` (DEFAULT OFF, implies the report) additionally runs the deletes for harvested records ONLY — never files / external / notifications. Neither is a rollback — a rollback is structurally impossible here. |
37
+ | `lotics app workflow set <alias>` | Push the edited `src/workflows/<alias>.ts` body through `set_app_workflow` (the single author of `apps.workflows`). Reads the body from disk (header + `/// <reference>` + `export {};` marker + the `__workflow` wrapper all stripped) + the typed `inputs`/`outputs` from `package.json#lotics.workflows.<alias>`; the **server** re-verifies the body and echoes the bound `outputs` (declared, else DERIVED from `return({ data })`). When the manifest declared NO `outputs`, the DERIVED echo is written back into `package.json#lotics.workflows.<alias>.outputs` (a SURGICAL write — preserves `knowledge`/`config` and every other manifest field) and that alias's types are refreshed in place, so `useWorkflow("<alias>")`'s `result.data` is typed immediately with no hand-copy and no second `lotics app codegen`; an explicitly-declared `outputs` is authoritative and never overwritten. Deploy still never authors workflows — this is a CLI convenience over the existing tool. Clear error + non-zero exit on a missing file, an alias absent from the manifest, or a verify failure. |
38
+ | `lotics app agent set <alias>` | Push the edited `src/agents/<alias>.md` instructions back through `set_app_agent` — the agent mirror of `app workflow set`, and the deploy-free authoring path for `apps.agents`. Reads the prose from disk (the `<!-- lotics: … -->` header stripped) and the typed fields (`inputs`/`outputs`/`tool_names`/`model_id`/`effort_level`/`knowledge_doc_ids`/`query_aliases`/`workflow_aliases`) from `package.json#lotics.agents.<alias>`, then sends them as ONE declaration. That assembly is the point: **`set_app_agent` REPLACES the declaration rather than patching it**, so a hand-built payload that sets one field silently drops the instructions, the output schema and the model pin — a silent, unrecoverable edit against a live prompt. Clear error + non-zero exit on a missing file, an alias absent from the manifest, or a file that is empty once the header is stripped (refusing to push an empty prompt). `app pull` writes the file; edit, then `set`. |
39
+ | `lotics app query set <alias>` | Push `package.json#lotics.queries.<alias>` (`{ ast, params? }`) to `apps.queries` through `set_app_query` — the deploy-free inner loop for named queries, the mirror of `app workflow set`. The **server** validates it exactly as a deploy does (alias identifier, workspace-only tables, resolvable fields, declared params). Note: `apps.queries` is manifest-authoritative, so the next `lotics app deploy` re-syncs the whole map from the manifest — keep the declaration in the manifest to survive. Clear error + non-zero exit on an alias absent from the manifest or a validation failure. |
40
+ | `lotics app agent run <app_id> <alias> ['<json>'\|@file\|stdin]` | Run a bound app agent end-to-end (GAP-87). A run needs no deployed UI bundle — just the app row + the bound agent declaration + member auth — so the **`app_id` is explicit** (not read from a local manifest). Inputs ingest exactly like `lotics run` (inline JSON / `@file` / stdin; empty = `{}`). Opens the run's SSE (`appAgentRunStream`), streams `text-delta` prose to **stderr** as live progress, then reports from the **settled run RECORD** (`listAgentRuns`, polled to a terminal status — the client stream can close a beat before the run settles, or drop while it runs on server-side): default prints the run's structured `output` (JSON) or final text to **stdout** + a status line to stderr; `--json` prints the full run summary to stdout. Selects THIS run by the `x-app-agent-run-id` header (ordering-independent). Exits 0 **only** when the settled status is `completed`; otherwise non-zero with the run's error surfaced. A settled run that never appears fails loudly (never a silent success). A fresh `session_id` is minted per run (self-contained); `--session <id>` continues an existing thread (prior runs become the agent's context). |
41
+ | `lotics app workflow pull` | Rewrite every `src/workflows/<alias>.ts` from the server (faithful body per bound alias via `get_app_workflow`) **+ its `.lotics/workflows/<alias>.globals.d.ts`** (via `getAppWorkflowDts`, so the body is locally typecheckable via `lotics app workflow check`) without a full `app pull` (no source archive, no npm install). A legacy alias with no rendered source warns and is skipped; a dts-fetch failure is non-fatal (body still written with the fallback wrapper, typecheck degraded). Also idempotently patches the main `tsconfig.json` `exclude` to cover `src/workflows` + `.lotics/workflows` so a pre-existing app's `npm run typecheck` never loads the bodies or the colliding per-alias globals. |
42
+ | `lotics app workflow check [alias]` | Check the editable workflow bodies locally, no auth / no network, in the **server's own order** — parse, then type-check. **Parse** runs `parseWorkflowJs` from `@lotics/shared` (the SAME module `verifyWorkflow` calls, never a second implementation — that is what let the two diverge once) over the stripped body `set` would upload, with `toolNames: undefined` (the CLI ships no tool registry, so tool-name resolution stays a server check while every shape/scope rule runs here). A body the subset rejects reports **that error alone** and skips the compiler — it never reaches the server's compiler either, so tsc's opinion of it is noise. **Type-check** then builds an **isolated** `ts.Program` per alias from exactly that alias's `{body, globals}` pair — mirroring the server, which verifies one body at a time — so the per-alias ambient `trigger` never collides and `trigger.app_workflow.inputs` is checked against the right alias (GAP-59). All aliases run in ONE node process (N programs, not N `tsc` spawns), with the SAME compile options the server uses at set-time verify (lib `es2022` with no DOM, target ES2022, strict, NodeNext, `types:[]`, skipLibCheck) and the app's OWN `typescript` (resolved from its `node_modules`, never bundled into the CLI). What the compiler sees is the **checked source**, not the file: `rewriteAccumulatorAppends` from `@lotics/shared` — the SAME transform the server applies before its set-time compile — is applied in memory, so a pulled body's canonical `out = concat(out, [item])` accumulator checks green here exactly as it saves there (compiling the raw text went red on it), and the body on disk is never rewritten. Reports `<file>:<line>:<col> - <TS####\|subset>` at the **physical** line in `src/workflows/<alias>.ts`, so an editor jump lands on the offending code (these are deliberately NOT `set`'s body-relative numbers — `set` prints no file path, so there is no format to agree with); exits non-zero if any alias fails. Green is honest but not total: `set` additionally resolves names, lints and structurally validates against the live workspace — passes that need its tables and tool schemas, so they cannot run offline, and the success line says so. A bound alias with no body file yet warns + skips; a body with no globals errors (run a pull). |
43
+ | `lotics app subdomain <new-subdomain>` | Rename the app's public `<slug>.lotics.app` address via `PUT /v1/apps/{id}/subdomain`. app_id comes from the local `package.json` manifest; the chosen slug must be a valid DNS label and free; the old address stops resolving. |
44
+ | `lotics app rename "<new name>"` | Change the app's display name (launcher/title) via the `update_app` tool. app_id comes from the local `package.json` manifest; the public address (`subdomain`) and code (`deploy`) are unchanged. |
45
+ | `lotics app dev [path] [--port=N] [--vite-port=N] [--view-as=<member_id>]` | Spawn Vite dev server + an RPC-forwarding HTTP server. The wrapper page embeds the iframe with `sandbox="allow-scripts allow-same-origin"` matching production; postMessage ops (query / workflow / members / context / upload / openExternal / urlState / agentRun) are forwarded to api.lotics.ai using the CLI's API key — file bytes move in **both** directions through the dev server's own relays, never browser↔storage (the former GAP-44): dev runs against the PROD bucket, whose CORS admits `https://*.lotics.app` and not `http://localhost:<port>`, so a direct browser transfer is blocked — no upload could complete and no preview engine (PDF/Word/Excel all FETCH the bytes) could read a file. `upload` mints a presigned URL and PUTs it **to `PUT /_upload/<file_id>`** (`dev/upload_relay.ts`) from the wrapper page — same-origin, so no preflight and no CORS — and Node forwards it on; every presigned `url`/`thumbnail_url`/`preview_url` on a **file object** in an RPC result is rewritten to **`GET /_file/<token>`** (`dev/file_relay.ts`, absolute — the iframe would resolve a relative path against Vite), which streams the bytes back with `Range` passthrough (206s intact, so PDF seeking works) and an `Access-Control-Allow-Origin` for the Vite origin (the one cross-origin hop left is OUR response to allow). Neither relay ever takes a destination from the client — it gets a `file_id`/token and transfers only to/from a URL it minted or observed itself, so there is no client-controlled target and no SSRF surface. A URL in a record's own text cell is NOT rewritten. Production is unchanged (direct-to-storage, no bytes through the API server); `openExternal` and `urlState.get/set` are handled locally (the latter read/write the wrapper page's own address bar — `set` writes in place via `replaceState` and browser back/forward broadcast a `url-state` message back, so `useUrlState` survives refresh and is shareable in the dev loop; in-app *routing* is the app's own (the iframe owns its url via `@lotics/app-sdk/router`), and the wrapper bakes the saved screen (`_loc`) into the iframe src on load so a refresh restores it, mirroring production); `agentRun` (streaming) is proxied through `POST /_agent_run`, which opens the run's SSE with the CLI key and pipes chunks back to the iframe (`stream-chunk`* → `stream-end`), so `useAgentRun` works in the dev loop just like production; `context` resolves the viewer (`member_id` from `cli/whoami` + `comments_enabled` from the local manifest) and fetches the installation's stored `config` live from the app row, so `useConfig()` renders the same values as production. `--view-as` (global flag; also `LOTICS_VIEW_AS`) threads `x-view-as-member-id` so `is_current_member` + `context` resolve to that member — **admin key only** (the server 403s a non-admin), writes stay attributed to the key owner. Hot reload via Vite; full DevTools / Playwright access via plain localhost. The dev-optimizer pre-bundle list (`optimizeDeps.include`, load-bearing for dev) is imported from `@lotics/ui/vite` (`loticsOptimizeDeps`) rather than hardcoded in the scaffold, so it tracks the installed `@lotics/ui` and can never go stale. Binds **loopback only** (`127.0.0.1`) — `/_rpc` dispatches with the developer's API key, so a socket on every interface would hand anyone on the network full read/write on the workspace. |
46
+ | `lotics ui link <component> [--ui-src <path>] [--remove]` | Dev-link `@lotics/ui` to `packages/ui/src` by inserting (or removing) a package-wide `{ find: /^@lotics\/ui\/(.+)$/, replacement: "<absUiSrc>/$1" }` alias in the app's `vite.config.ts` resolve.alias — so edits to `packages/ui/src` go live (HMR) and bundle on deploy, without a publish round-trip. **`packages/ui/src` resolution:** walk up for a monorepo checkout, else the explicit `--ui-src <abs path>` / `LOTICS_UI_SRC` env — that's how an **EXTERNAL app** (one that consumes `@lotics/ui` from npm, e.g. under `~/lotics_apps`) links the local kit; fails loud when neither resolves, or when `--ui-src` isn't a directory. No auth (local file edit). Idempotent. `component` is advisory/validation only (the alias covers every subpath). **Vite-only, by design:** the app's `tsc` still resolves `@lotics/ui` from `node_modules` (the published `.d.ts`) — the kit `src` can't be typechecked inside an app because it's RN-Web (uses `react-native-web` types the app resolves as base `react-native`), so typecheck the kit in `packages/ui` and let the finalize publish restore the app's own typecheck. Reminds to restart dev + `rm node_modules/.vite`, and to finalize (`--remove` + publish-chain bump). |
47
+ | `lotics xlsx <subcmd>` | Local .xlsx read/write/edit using the bundled `@lotics/xlsx` engine (no auth, no network). 14 named subcommands (read, write, set-cell, clear-range, merge, unmerge, add-sheet, delete-sheet, rename-sheet, insert-rows, delete-rows, insert-cols, delete-cols, set-style) + `batch` for applying multiple of the same 14 ops in a single parse/export cycle. `read` also takes `--sheet <name>` (limit output to one sheet — unknown name fails with the available list) and `--range <sheet>!<A1:G60>` (limit to a cell window; the `<sheet>!` prefix is optional when `--sheet` supplies the sheet, a single cell like `S1!B2` is a 1×1 window) to trim a large workbook's JSON — the output shape is unchanged, only the `sheets` array and each sheet's `cells` map are filtered. Atomic in-place write (temp file + rename). |
48
+ | `lotics docx <subcmd>` | Local .docx read/write/edit using the bundled `@lotics/docx` engine (OOXML round-trip surface only — no ProseMirror baggage). Subcommands: read, write, append-paragraph, insert-paragraph, delete-block, replace-text, batch. A legacy `.doc` (Word 97–2003 OLE2 binary) is detected in `loadFile` and routed through `@lotics/ooxml`'s `loadDocxFromBuffer` (which re-emits it as real OOXML) before reading — so `lotics docx read` works on a `.doc`, not just a `.docx`. Opaque blocks (tables, custom XML) preserved verbatim. Atomic in-place write. |
49
+ | `lotics file preview <file\|fil_id> [-o out.png]` | (also `lotics preview`) Render a .docx/.xlsx to a PNG using the SAME engines the frontend FilePreview uses (`@lotics/docx` `loadDocxIntoElement` / `@lotics/xlsx` `drawSpreadsheet`) — so what you see matches an operator. Accepts a **local path** OR a stored **`fil_…` id** (`isStoredFileId` — a bare id, no extension): an id is first downloaded to a temp dir via `downloadFileById` (the `signed_url` presign path — same authority as `lotics file download`), rendered, then the transient source is removed; with no `-o` the PNG lands in cwd under the stored file's base name (`defaultPreviewOutputPath`). Drives a headless Chrome over **CDP with only Node built-ins** (`WebSocket`/`fetch`/`http`/`child_process`) — zero npm deps, the CLI stays a single bundled binary. The browser render logic is a separate esbuild **browser** bundle shipped at `dist/render_page.js` (built by `build_cli.mjs`, excluded from the node `tsgo`), served over a throwaway localhost http server and screenshotted full-page. **Requires a Chrome/Chromium on the machine** — detected from `CHROME_PATH`/`LOTICS_CHROME`, then Playwright's installed chromium, then system paths — inherent to rendering these browser formats; a clear "install a browser" error otherwise. PDFs need no render (open them directly). |
50
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lotics/cli",
3
- "version": "0.99.1",
3
+ "version": "0.100.0",
4
4
  "description": "Lotics SDK and CLI for AI agents",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,6 +11,7 @@
11
11
  },
12
12
  "files": [
13
13
  "dist",
14
+ "AGENTS.md",
14
15
  "README.md",
15
16
  "docs"
16
17
  ],