@lotics/cli 0.98.0 → 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
@@ -64486,6 +64500,9 @@ var queryOutputColumnSchema = zod_default.object({
64486
64500
  ),
64487
64501
  source_field_key: zod_default.string().optional().describe(
64488
64502
  "Source field this column originates from. Populated alongside source_table_id for passthrough columns."
64503
+ ),
64504
+ computed: zod_default.boolean().optional().describe(
64505
+ "True when the value is DERIVED rather than a passthrough of the addressed field \u2014 a link extraction reads a field on the link TARGET, so the row's own source record is a different table. Such a column may still carry source addressing (it is what resolves labels and option sets), but that addressing is NOT a write target: writable_target is refused on a computed column and on anything that passes one through."
64489
64506
  )
64490
64507
  });
64491
64508
  var queryOutputSchemaSchema = zod_default.object({
@@ -70074,8 +70091,14 @@ async function fetchLatestNpmVersion(packageName) {
70074
70091
  return null;
70075
70092
  }
70076
70093
  }
70094
+ function toManifestAgents(agents) {
70095
+ return Object.fromEntries(
70096
+ Object.entries(agents).map(([alias, { instructions: _prose, ...typed }]) => [alias, typed])
70097
+ );
70098
+ }
70077
70099
  var WORKFLOWS_DIR = path5.join("src", "workflows");
70078
70100
  var WORKFLOW_GLOBALS_DIR = path5.join(".lotics", "workflows");
70101
+ var AGENTS_DIR = path5.join("src", "agents");
70079
70102
  var WORKFLOW_TSCONFIG_EXCLUDES = ["src/workflows", ".lotics/workflows"];
70080
70103
  var LOTICS_INCLUDE_GLOB = ".lotics/**/*";
70081
70104
  var STALE_LOTICS_INCLUDES = /* @__PURE__ */ new Set([".lotics", "./.lotics", ".lotics/"]);
@@ -70123,6 +70146,39 @@ ${envelope.prefix}${body}${envelope.suffix}
70123
70146
  `);
70124
70147
  return file2;
70125
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
+ }
70126
70182
  async function writeWorkflowFiles(client, projectDir, app_id, workflows) {
70127
70183
  const written = [];
70128
70184
  for (const [alias, declaration] of Object.entries(workflows)) {
@@ -70425,9 +70481,15 @@ function stampPulledManifest(projectDir, args) {
70425
70481
  version_number: args.version_number,
70426
70482
  workflows: args.workflows,
70427
70483
  queries: args.queries,
70428
- 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)
70429
70492
  });
70430
- writeAppDts(projectDir, { workflows: args.workflows, queries: args.queries, agents: args.agents });
70431
70493
  }
70432
70494
  async function downloadToFile(url2, destPath) {
70433
70495
  const response = await fetch(url2);
@@ -70588,6 +70650,15 @@ async function appPull(client, args) {
70588
70650
  );
70589
70651
  }
70590
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
+ }
70591
70662
  console.error(`Installing npm dependencies...`);
70592
70663
  await runNpm(["install"], targetPath);
70593
70664
  console.error(`
@@ -70949,6 +71020,40 @@ Agent "${args.alias}" run ${run.id} \u2192 ${run.status}${run.error_message ? `:
70949
71020
  );
70950
71021
  if (run.status !== "completed") process.exit(1);
70951
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
+ }
70952
71057
  async function appWorkflowSet(client, args) {
70953
71058
  const projectDir = process.cwd();
70954
71059
  const meta3 = readAppMeta(projectDir);
@@ -89375,13 +89480,184 @@ var formattingSchema = external_exports.object({
89375
89480
  superscript: external_exports.boolean().optional(),
89376
89481
  subscript: external_exports.boolean().optional(),
89377
89482
  all_caps: external_exports.boolean().optional(),
89378
- 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
+ )
89379
89491
  });
89380
89492
  var runSchema = external_exports.object({
89381
89493
  text: external_exports.string(),
89382
89494
  formatting: formattingSchema.optional()
89383
89495
  });
89384
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
+
89385
89661
  // ../ooxml/src/sections.ts
89386
89662
  var PAGE_SIZES = {
89387
89663
  letter: { w: 12240, h: 15840 },
@@ -90377,170 +90653,6 @@ async function ensureContentTypeOverride(doc, partName, contentType) {
90377
90653
  doc.zip.file("[Content_Types].xml", updated);
90378
90654
  }
90379
90655
 
90380
- // ../ooxml/src/queries.ts
90381
- function getBodyElementType(el) {
90382
- const tag = getTagName(el);
90383
- if (tag === "w:p") return "paragraph";
90384
- if (tag === "w:tbl") return "table";
90385
- return "other";
90386
- }
90387
- function extractParagraphText(el) {
90388
- const tag = getTagName(el);
90389
- if (tag !== "w:p") return "";
90390
- const parts = [];
90391
- for (const child of getChildren(el)) {
90392
- const childTag = getTagName(child);
90393
- if (childTag === "w:r") {
90394
- for (const runChild of getChildren(child)) {
90395
- if (getTagName(runChild) === "w:t") {
90396
- parts.push(getTextContent(runChild));
90397
- }
90398
- }
90399
- } else if (childTag === "w:hyperlink") {
90400
- for (const hlChild of getChildren(child)) {
90401
- if (getTagName(hlChild) === "w:r") {
90402
- for (const runChild of getChildren(hlChild)) {
90403
- if (getTagName(runChild) === "w:t") {
90404
- parts.push(getTextContent(runChild));
90405
- }
90406
- }
90407
- }
90408
- }
90409
- }
90410
- }
90411
- return parts.join("");
90412
- }
90413
- function getRunsFromParagraph(el) {
90414
- const runs = [];
90415
- for (const child of getChildren(el)) {
90416
- if (getTagName(child) !== "w:r") continue;
90417
- let text = "";
90418
- let textIdx = -1;
90419
- const children = getChildren(child);
90420
- for (let i2 = 0; i2 < children.length; i2++) {
90421
- if (getTagName(children[i2]) === "w:t") {
90422
- const tChildren = getChildren(children[i2]);
90423
- for (const tn of tChildren) {
90424
- if (typeof tn["#text"] === "string") {
90425
- text += tn["#text"];
90426
- }
90427
- }
90428
- textIdx = i2;
90429
- }
90430
- }
90431
- if (textIdx >= 0) {
90432
- runs.push({ element: child, text, textNodeIndex: textIdx });
90433
- }
90434
- }
90435
- return runs;
90436
- }
90437
- function setRunText(run, newText) {
90438
- const children = getChildren(run.element);
90439
- children[run.textNodeIndex] = {
90440
- "w:t": [{ "#text": newText }],
90441
- ":@": { "@_xml:space": "preserve" }
90442
- };
90443
- run.text = newText;
90444
- }
90445
- function computeReplacementRanges(text, query, replacement, matchType, maxReplacements, startCount) {
90446
- const ranges = [];
90447
- let count = startCount;
90448
- if (matchType === "exact") {
90449
- if (text === query && count < maxReplacements) {
90450
- ranges.push({ start: 0, end: text.length, replacement });
90451
- count++;
90452
- }
90453
- return { ranges, count };
90454
- }
90455
- if (matchType === "regex") {
90456
- const re2 = new RegExp(query, "gi");
90457
- let match2;
90458
- while (count < maxReplacements && (match2 = re2.exec(text)) !== null) {
90459
- ranges.push({ start: match2.index, end: match2.index + match2[0].length, replacement });
90460
- count++;
90461
- if (match2[0].length === 0) re2.lastIndex++;
90462
- }
90463
- return { ranges, count };
90464
- }
90465
- if (query.length === 0) return { ranges, count };
90466
- const lower2 = text.toLowerCase();
90467
- const lowerQuery = query.toLowerCase();
90468
- let searchFrom = 0;
90469
- while (count < maxReplacements) {
90470
- const idx = lower2.indexOf(lowerQuery, searchFrom);
90471
- if (idx === -1) break;
90472
- ranges.push({ start: idx, end: idx + query.length, replacement });
90473
- searchFrom = idx + query.length;
90474
- count++;
90475
- }
90476
- return { ranges, count };
90477
- }
90478
- function applyRangeReplacements(runs, ranges) {
90479
- if (ranges.length === 0) return;
90480
- const bounds = [];
90481
- let offset = 0;
90482
- for (const run of runs) {
90483
- bounds.push({ run, start: offset, end: offset + run.text.length });
90484
- offset += run.text.length;
90485
- }
90486
- const joined = runs.map((r) => r.text).join("");
90487
- const sorted = [...ranges].sort((a, b) => a.start - b.start);
90488
- for (const { run, start: runStart, end: runEnd } of bounds) {
90489
- let next = "";
90490
- let cursor = runStart;
90491
- for (const range2 of sorted) {
90492
- if (range2.end <= runStart || range2.start >= runEnd) continue;
90493
- const keepUntil = Math.min(range2.start, runEnd);
90494
- const from = Math.max(cursor, runStart);
90495
- if (keepUntil > from) next += joined.slice(from, keepUntil);
90496
- if (runStart <= range2.start && range2.start < runEnd) next += range2.replacement;
90497
- cursor = Math.max(cursor, range2.end);
90498
- }
90499
- const tail = Math.max(cursor, runStart);
90500
- if (runEnd > tail) next += joined.slice(tail, runEnd);
90501
- if (next !== run.text) setRunText(run, next);
90502
- }
90503
- }
90504
- function replaceInParagraph(el, query, replacement, matchType, maxReplacements, replacementsMade) {
90505
- if (!extractParagraphText(el)) return replacementsMade;
90506
- const runs = getRunsFromParagraph(el);
90507
- if (runs.length === 0) return replacementsMade;
90508
- const text = runs.length === 1 ? runs[0].text : runs.map((r) => r.text).join("");
90509
- const { ranges, count } = computeReplacementRanges(text, query, replacement, matchType, maxReplacements, replacementsMade);
90510
- applyRangeReplacements(runs, ranges);
90511
- return count;
90512
- }
90513
- function replaceText(bodyElements, query, replacement, matchType = "contains", maxReplacements = Infinity) {
90514
- if (matchType === "regex") {
90515
- try {
90516
- new RegExp(query);
90517
- } catch {
90518
- throw new Error(`Invalid regex pattern: ${query}`);
90519
- }
90520
- }
90521
- let replacementsMade = 0;
90522
- for (let i2 = 0; i2 < bodyElements.length && replacementsMade < maxReplacements; i2++) {
90523
- const el = bodyElements[i2];
90524
- const type = getBodyElementType(el);
90525
- if (type === "paragraph") {
90526
- replacementsMade = replaceInParagraph(el, query, replacement, matchType, maxReplacements, replacementsMade);
90527
- } else if (type === "table") {
90528
- for (const child of getChildren(el)) {
90529
- if (getTagName(child) !== "w:tr") continue;
90530
- for (const cell of getChildren(child)) {
90531
- if (getTagName(cell) !== "w:tc") continue;
90532
- for (const p of getChildren(cell)) {
90533
- if (getTagName(p) === "w:p" && replacementsMade < maxReplacements) {
90534
- replacementsMade = replaceInParagraph(p, query, replacement, matchType, maxReplacements, replacementsMade);
90535
- }
90536
- }
90537
- }
90538
- }
90539
- }
90540
- }
90541
- return replacementsMade;
90542
- }
90543
-
90544
90656
  // ../docx/src/parse/parser.ts
90545
90657
  var import_jszip2 = __toESM(require_lib4(), 1);
90546
90658
  async function parseDocx(buffer) {
@@ -91680,6 +91792,10 @@ COMMANDS
91680
91792
  (inputs: inline JSON, @file, or stdin; streams
91681
91793
  progress to stderr, reports the settled run;
91682
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)
91683
91799
  lotics app subdomain <new-subdomain> Rename the app's public <slug>.lotics.app address
91684
91800
  lotics app rename "<new name>" Rename the app's display name (launcher title)
91685
91801
  lotics app dev [path] Run the app locally with HMR (RPC forwarded to prod)
@@ -92495,6 +92611,8 @@ Available workspaces:`);
92495
92611
  console.error(" cat inputs.json | lotics app agent run <app_id> <alias> (read inputs from stdin)");
92496
92612
  console.error("Streams the run's progress to stderr; reports the settled run (structured output / text) to stdout.");
92497
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");
92498
92616
  process.exit(1);
92499
92617
  };
92500
92618
  if (action === "run") {
@@ -92522,6 +92640,16 @@ Available workspaces:`);
92522
92640
  });
92523
92641
  return;
92524
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
+ }
92525
92653
  agentUsage();
92526
92654
  }
92527
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
+
@@ -7,8 +7,8 @@ them on demand** while it works, pulling in only the lines it needs.
7
7
 
8
8
  They are deliberately **not** injected into the agent wholesale. Bulk-loading every doc into
9
9
  every request would burn the context budget and drown the signal. Instead the agent retrieves
10
- from them through a search funnel, so a 10,000-line tariff book costs nothing until a question
11
- actually touches it.
10
+ from them line by line — grep, then read — so a 10,000-line tariff book costs nothing until a
11
+ question actually touches it, and a 10MB one is no different.
12
12
 
13
13
  This is a **capability + usage** guide. For the exact input schema of any tool named here, run
14
14
  `lotics tools <tool_name>`.
@@ -34,9 +34,9 @@ This reads the body from your filesystem and creates the doc through `create_kno
34
34
  `content` from a file or stdin. Either way, `create_knowledge` takes three things:
35
35
 
36
36
  - `name` — what it is.
37
- - `description` — what the doc is **and how to retrieve from it**: its vocabulary, synonyms for
38
- colloquial terms, and what to read for detail. This is surfaced when the doc is *found*,
39
- before its content is read, so the agent knows whether to open it.
37
+ - `description` — what the doc is **and what to grep it for**: its vocabulary and the synonyms
38
+ an ambiguous query would use. Surfaced in the tree before any body is read, and truncated at
39
+ 200 characters. See *Write for grep* below.
40
40
  - `content` — Markdown.
41
41
 
42
42
  A new doc is created **owned by you, active in your own agent context, and private** — no one
@@ -61,28 +61,84 @@ So: shared + active → the agent can find and read it. Shared but deactivated
61
61
  that member's agent. This is the token economy in action — activation is how a member curates
62
62
  which rulebooks their agent carries.
63
63
 
64
- ## How an agent uses a doc — catalog, then read
64
+ ## How an agent uses a doc — ls, grep, cat
65
+
66
+ Docs are not injected wholesale. The agent works the corpus like a filesystem, and all three
67
+ verbs respect access + activation, so only docs the caller may use ever surface.
68
+
69
+ 1. **`list_knowledge`** — `ls`. The corpus as a folder tree: name, id, folder, and a truncated
70
+ description. No bodies.
71
+ 2. **`grep_knowledge`** — `grep -rn`. Substring match across every readable doc (or one doc, or
72
+ one folder), returning **doc, line number, and the matching line**. It runs inside Postgres,
73
+ so only matching lines cross the wire.
74
+ 3. **`read_knowledge`** — `cat` / `sed -n 'X,Yp'`. Read a doc whole or by line range, to see
75
+ the context around a hit.
76
+
77
+ Matching is **substring, not ranked** — there is no index and no tokenizer, which is why a
78
+ corpus in any script works and why nothing goes stale. The consequence is that the *agent*
79
+ does the narrowing: a distinctive phrase is sharply selective, a whole question matches
80
+ everything. `grep_knowledge` always reports `total_matches`, so "too broad" is visible and
81
+ cheap to fix.
82
+
83
+ ### Matching options
84
+
85
+ - **Diacritics fold by default** — `ca phe` matches `cà phê`. `diacritic_insensitive: false` matches
86
+ tone marks exactly.
87
+ - **Case folds by default**, independently of diacritics. `case_sensitive: true` matches case
88
+ exactly — useful for an acronym (`NK` vs `nk`) that a folded search would blur.
89
+ - **Whitespace is normalized on both sides.** A body converted from PDF, Word or Excel carries
90
+ non-breaking spaces, soft hyphens, zero-width marks and padded runs that nobody types into a
91
+ query; those fold to ordinary single spaces before matching, so a correct search does not return
92
+ a silent zero on text that is present. Your pattern is normalized the same way.
93
+ - **`regex: true`** treats the pattern as a POSIX regular expression: quantifiers, character
94
+ classes, alternation, anchors, and **`\y` for a word boundary**. Note `\y`, not `\b` — Postgres
95
+ spells it differently, and `\b` is rewritten for you rather than silently matching nothing.
96
+ Literal is the default on purpose: `0901.11.20` as a regex would also match `0901X11Y20`.
65
97
 
66
- Docs are not injected wholesale. The agent finds the right doc from a **catalog**, then reads
67
- only what it needs. Both steps respect access + activation, so only docs the caller may use ever
68
- surface.
69
-
70
- 1. **Catalog** — `list_knowledge` returns every usable doc as `{ id, name, description }` — no
71
- bodies. This is why the *description* carries the weight: it is what the agent reads before
72
- deciding to open a doc. Write it to sell the doc — its vocabulary, the colloquial synonyms an
73
- ambiguous query would use, and what it covers.
74
- 2. **Read** — the chat agent stages the chosen doc's content file into a code run and greps it
75
- there (the body arrives as a file to `cat`/`grep`). Over this CLI you read a body directly
76
- with `lotics knowledge get <id>`.
77
-
78
- Structure your content so a reader lands on the answer without loading the rest:
98
+ ```
99
+ grep_knowledge({ pattern: "\\yNK\\y", regex: true, case_sensitive: true })
100
+ ```
79
101
 
80
- - Organize under clear Markdown headers.
81
- - Keep each searchable unit self-contained — a section for prose, **one record per line** for
82
- dense/tabular data (a price row, a code entry) — carrying both the terms someone would search
83
- for and its answer.
84
- - Lead with the most-queried fields.
85
- - Note colloquial synonyms next to official terms, so an ambiguous query still matches.
102
+ ### What a result is bounded by
103
+
104
+ A result carries at most 40.000 characters. Matched lines are admitted first and context fills
105
+ what remains, so an answer is never dropped to make room for a neighbouring line. Anything the
106
+ budget cut is REPORTED — `chars_elided_matches` (an answer was dropped) and
107
+ `context_omitted_matches` (an answer was kept without the context you asked for) mean different
108
+ things and call for different fixes: narrow the pattern, or ask for fewer `context_lines`.
109
+ Individual lines longer than 600 characters are clipped and marked, with `read_knowledge` giving
110
+ the rest.
111
+
112
+ `total_matches` is always the true total, even when fewer are shown.
113
+
114
+ ## Write for grep — the rules that decide whether an answer is findable
115
+
116
+ Retrieval addresses **lines**. Every rule below follows from that one fact, and ignoring them
117
+ is the difference between a doc that answers and a doc that merely exists.
118
+
119
+ - **One self-contained fact per line.** A grep hit returns *that line*. For dense or tabular
120
+ data — a price row, a tariff code, a charge entry — put the whole record on one line.
121
+ - **Repeat the searchable terms on every line; headings do not carry down.** A line reading
122
+ `Rate: 15%` under a heading `Roasted coffee` will never match a search for `coffee`. Restate
123
+ the identifying terms inline, even when it reads redundantly to a human. This is the single
124
+ rule most often got wrong.
125
+ - **Keep a line under ~600 characters.** Past that the line is truncated in the agent's view
126
+ and marked as cut; the agent can still `read_knowledge` for the rest, but it costs a round
127
+ trip. Put the identifying terms early and the long tail late.
128
+ - **Put synonyms and translations on the line itself.** A bilingual row (`Cà phê, đã rang /
129
+ Coffee, roasted`) matches queries in either language for free. The same trick carries
130
+ colloquial terms next to official ones.
131
+ - **For prose, keep a rule and its exception close.** A hit returns one line, so a rule on line
132
+ 40 and its exception on line 90 can be retrieved apart. Use `context_lines` when reading, and
133
+ keep related clauses adjacent when writing.
134
+
135
+ Markdown headings are ordinary text — useful for a human and for orienting a `read_knowledge`,
136
+ but they carry no retrieval weight of their own.
137
+
138
+ **The description is the discovery hint.** It is what the agent sees in the tree before it has
139
+ read a byte of the body, so it is the only clue for *what term to grep for*. Write it to name
140
+ the doc's vocabulary — the words that actually appear inside it. Keep it to a sentence: it is
141
+ truncated at 200 characters, and a keyword-stuffed description is cut, not rewarded.
86
142
 
87
143
  ## Updating a doc — `lotics knowledge update`
88
144
 
@@ -95,8 +151,8 @@ Send only the fields you're changing. `--from` / `--content` replaces the body;
95
151
  re-reads the current content pointer and version-chains the new body — so there is no version
96
152
  token to pass from the CLI. (The chat agent may instead send an `edits` array — anchored
97
153
  replace / insert / append — for a surgical change; see `lotics tools update_knowledge`.) Refine
98
- structure as you learn what users actually ask: add the synonym that failed to match, split the
99
- section that was too coarse to read.
154
+ structure as you learn what users actually ask: add the synonym that failed to match, split a
155
+ line that was too coarse, restate a term the heading was carrying.
100
156
 
101
157
  ## Package-managed knowledge
102
158
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lotics/cli",
3
- "version": "0.98.0",
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
  ],