@lotics/cli 0.114.0 → 0.123.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.
@@ -150,6 +150,14 @@ export declare class LoticsClient {
150
150
  readonly baseUrl: string;
151
151
  constructor(options: LoticsClientOptions);
152
152
  private throwResponseError;
153
+ /**
154
+ * The backend's `log()` middleware registers `user-agent` and
155
+ * `x-posthog-session-id` onto the per-request Logger, so they ride EVERY log
156
+ * line that request emits — the validation 400, the tool error, the timing.
157
+ * Sending them is therefore the whole of the correlation work: it turns an
158
+ * anonymous API-key request into "`app workflow set`, from cli 0.117.0, the
159
+ * fourth command of this session".
160
+ */
153
161
  private buildHeaders;
154
162
  private request;
155
163
  whoami(): Promise<{
@@ -855,6 +863,10 @@ export declare class LoticsClient {
855
863
  outputs?: Record<string, unknown>;
856
864
  name?: string;
857
865
  description?: string;
866
+ /** The `body_sha` this push was built on. Makes the write conditional: the
867
+ * server refuses it when the live body has moved since, rather than
868
+ * letting a stale copy overwrite an edit its author never saw. */
869
+ expected_body_sha?: string;
858
870
  }): Promise<ToolExecuteResult>;
859
871
  /**
860
872
  * Bind (create or replace) an app query by alias via the `set_app_query` tool
@@ -868,7 +880,9 @@ export declare class LoticsClient {
868
880
  ast: unknown;
869
881
  params?: Record<string, unknown>;
870
882
  description?: string;
871
- }): Promise<ToolExecuteResult>;
883
+ },
884
+ /** The fingerprint this edit was based on — makes the write conditional. */
885
+ expected_sha?: string): Promise<ToolExecuteResult>;
872
886
  /**
873
887
  * Bind (create or replace) an app agent by alias via the `set_app_agent` tool
874
888
  * — the deploy-free authoring path for `apps.agents`, parallel to
@@ -1036,6 +1050,7 @@ export declare class LoticsClient {
1036
1050
  * (empty array when none declared).
1037
1051
  */
1038
1052
  workflow_aliases?: string[];
1053
+ agent_aliases?: string[];
1039
1054
  query_aliases?: string[];
1040
1055
  }): Promise<{
1041
1056
  version_id: string;
@@ -1,6 +1,7 @@
1
1
  import { transportErrorMessage } from "@lotics/shared/transport_error";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
+ import { getInvocation } from "./invocation.js";
4
5
  function findAvailableFilename(dir, filename, reserved) {
5
6
  // `reserved` tracks absolute paths claimed by in-flight downloads in the same
6
7
  // batch — required for parallel callers because the file may not be on disk
@@ -75,9 +76,21 @@ export class LoticsClient {
75
76
  }
76
77
  throw new Error(`${response.status}: ${message}`);
77
78
  }
79
+ /**
80
+ * The backend's `log()` middleware registers `user-agent` and
81
+ * `x-posthog-session-id` onto the per-request Logger, so they ride EVERY log
82
+ * line that request emits — the validation 400, the tool error, the timing.
83
+ * Sending them is therefore the whole of the correlation work: it turns an
84
+ * anonymous API-key request into "`app workflow set`, from cli 0.117.0, the
85
+ * fourth command of this session".
86
+ */
78
87
  buildHeaders() {
88
+ const invocation = getInvocation();
79
89
  const headers = {
80
90
  "Authorization": `Bearer ${this.apiKey}`,
91
+ // Unversioned when the SDK is used as a library — there is no CLI process
92
+ // whose version to name, and a wrong one is worse than none.
93
+ "user-agent": invocation?.userAgent ?? "lotics-cli",
81
94
  };
82
95
  if (this.workspaceId) {
83
96
  headers["x-workspace-id"] = this.workspaceId;
@@ -85,6 +98,12 @@ export class LoticsClient {
85
98
  if (this.viewAsMemberId) {
86
99
  headers["x-view-as-member-id"] = this.viewAsMemberId;
87
100
  }
101
+ if (invocation) {
102
+ headers["x-lotics-cli-command"] = invocation.command;
103
+ if (invocation.session !== null) {
104
+ headers["x-posthog-session-id"] = invocation.session;
105
+ }
106
+ }
88
107
  return headers;
89
108
  }
90
109
  async request(method, path, body) {
@@ -547,6 +566,7 @@ export class LoticsClient {
547
566
  ...(body.outputs ? { outputs: body.outputs } : {}),
548
567
  ...(body.name ? { name: body.name } : {}),
549
568
  ...(body.description ? { description: body.description } : {}),
569
+ ...(body.expected_body_sha ? { expected_body_sha: body.expected_body_sha } : {}),
550
570
  });
551
571
  }
552
572
  /**
@@ -557,8 +577,15 @@ export class LoticsClient {
557
577
  * deploy validates the manifest. Note: `apps.queries` is manifest-authoritative,
558
578
  * so the next `lotics app deploy` overwrites this from the manifest.
559
579
  */
560
- async setAppQuery(app_id, alias, declaration) {
561
- return this.execute("set_app_query", { app_id, alias, declaration });
580
+ async setAppQuery(app_id, alias, declaration,
581
+ /** The fingerprint this edit was based on — makes the write conditional. */
582
+ expected_sha) {
583
+ return this.execute("set_app_query", {
584
+ app_id,
585
+ alias,
586
+ declaration,
587
+ ...(expected_sha ? { expected_sha } : {}),
588
+ });
562
589
  }
563
590
  /**
564
591
  * Bind (create or replace) an app agent by alias via the `set_app_agent` tool
@@ -723,6 +750,7 @@ export class LoticsClient {
723
750
  // server records what the served version calls — the remove_app_workflow
724
751
  // guard reads this back. These are the manifest KEYS only, never bindings.
725
752
  formData.append("workflow_aliases", JSON.stringify(args.workflow_aliases ?? []));
753
+ formData.append("agent_aliases", JSON.stringify(args.agent_aliases ?? []));
726
754
  formData.append("query_aliases", JSON.stringify(args.query_aliases ?? []));
727
755
  const url = `${this.baseUrl}/v1/apps/${encodeURIComponent(args.app_id)}/versions`;
728
756
  const response = await fetch(url, {
@@ -0,0 +1,51 @@
1
+ /** Enabled by an explicit `LOTICS_TELEMETRY=1`. Anything else, including unset, is off. */
2
+ export declare function telemetryEnabled(env?: NodeJS.ProcessEnv): boolean;
3
+ /**
4
+ * The verb path of an invocation — `app.workflow.set`, `run.query_records` —
5
+ * from the raw argv positionals.
6
+ *
7
+ * Positionals stop at the first token that is a flag, a JSON blob, an `@file`,
8
+ * or an identifier: the point of the header is to name the COMMAND, and a table
9
+ * id or a record payload past that point is customer data that has no business
10
+ * in a request header. `run` keeps one extra token because the tool name IS the
11
+ * verb there — `run` alone would collapse ~90 distinct operations into one label.
12
+ */
13
+ export declare function commandPath(argv: readonly string[]): string;
14
+ /** `lotics-cli/0.117.0 node/v22.1.0 linux` — enough to correlate a failure with a stale CLI. */
15
+ export declare function userAgent(version: string): string;
16
+ /**
17
+ * The command + session of the running CLI process, set once by `cli.ts` before
18
+ * dispatch and read by `LoticsClient.buildHeaders`.
19
+ *
20
+ * Process-scoped ambient state, which is a cost — but the alternative is
21
+ * threading two strings through the ~20 places a client is constructed, and the
22
+ * facts are genuinely process-wide (there is one command per invocation). It is
23
+ * write-once at startup and read-only after, so nothing downstream has to track
24
+ * when it changes.
25
+ *
26
+ * Unset is the LIBRARY case: `@lotics/cli` also exports `LoticsClient`, where
27
+ * `process.argv` belongs to someone else's program and would name a command that
28
+ * was never run. Absent beats wrong, so the header is simply omitted.
29
+ */
30
+ type Invocation = {
31
+ command: string;
32
+ session: string | null;
33
+ userAgent: string;
34
+ };
35
+ /**
36
+ * `version` is passed in rather than imported: `version.ts` resolves
37
+ * `package.json` relative to its own module URL, which only holds from `dist/`,
38
+ * so importing it into `client.ts` would make the library entry unloadable from
39
+ * source. The bin already reads it correctly; the client just relays it.
40
+ */
41
+ export declare function setInvocation(command: string, session: string | null, version: string): void;
42
+ export declare function getInvocation(): Invocation | null;
43
+ /** Back to the library state (no CLI process). Exists for tests. */
44
+ export declare function resetInvocation(): void;
45
+ export declare function sessionStorePath(): string;
46
+ /**
47
+ * The current session id, or null when telemetry is off. `now` is injected so the
48
+ * idle-gap boundary is testable without a clock.
49
+ */
50
+ export declare function sessionId(now?: number, env?: NodeJS.ProcessEnv): string | null;
51
+ export {};
@@ -0,0 +1,142 @@
1
+ /**
2
+ * What this process was asked to do, and which run of a sitting it belongs to —
3
+ * the two facts that make a server log line attributable to a CLI invocation.
4
+ *
5
+ * Today a CLI request is indistinguishable from any other API-key request: the
6
+ * backend's `log()` middleware registers `user_agent` and `$session_id` onto
7
+ * every log line of a request, and the CLI sent neither. So a 400 in PostHog
8
+ * names an endpoint and nothing about the command that produced it, and nothing
9
+ * links it to the twelve invocations that preceded it — which is the whole
10
+ * question when an agent is stuck in a retry loop.
11
+ *
12
+ * Split by sensitivity, deliberately:
13
+ * - the VERSION and the COMMAND describe the request that is already being
14
+ * made (the endpoint mostly implies the verb anyway) and always ride;
15
+ * - the SESSION id is a cross-request correlator, so it rides only under
16
+ * `LOTICS_TELEMETRY=1`. Opt-out would be the industry default; this package
17
+ * publishes to npm and runs on customers' machines, so it is opt-in.
18
+ */
19
+ import fs from "node:fs";
20
+ import os from "node:os";
21
+ import path from "node:path";
22
+ /** Enabled by an explicit `LOTICS_TELEMETRY=1`. Anything else, including unset, is off. */
23
+ export function telemetryEnabled(env = process.env) {
24
+ return env.LOTICS_TELEMETRY === "1";
25
+ }
26
+ /**
27
+ * The verb path of an invocation — `app.workflow.set`, `run.query_records` —
28
+ * from the raw argv positionals.
29
+ *
30
+ * Positionals stop at the first token that is a flag, a JSON blob, an `@file`,
31
+ * or an identifier: the point of the header is to name the COMMAND, and a table
32
+ * id or a record payload past that point is customer data that has no business
33
+ * in a request header. `run` keeps one extra token because the tool name IS the
34
+ * verb there — `run` alone would collapse ~90 distinct operations into one label.
35
+ */
36
+ export function commandPath(argv) {
37
+ const parts = [];
38
+ for (const raw of argv) {
39
+ if (parts.length >= 3)
40
+ break;
41
+ if (raw.startsWith("-") || raw.startsWith("@") || raw.startsWith("{"))
42
+ break;
43
+ if (raw.includes("/") || raw.includes("."))
44
+ break;
45
+ if (!/^[a-z][a-z0-9_-]*$/i.test(raw))
46
+ break;
47
+ if (isResourceId(raw))
48
+ break;
49
+ parts.push(raw);
50
+ }
51
+ return parts.length > 0 ? parts.join(".") : "unknown";
52
+ }
53
+ /**
54
+ * A Lotics resource id (`app_Gw6rs95ZYKQs`, `tbl_1KxO3W08g75o`) as opposed to a
55
+ * snake_case tool name (`query_records`, `grep_knowledge`).
56
+ *
57
+ * Both are `<word>_<word>`, so prefix-and-underscore alone is not the tell — it
58
+ * rejected half the tool registry. The discriminator is the SUFFIX: an id's is a
59
+ * long base62 blob, which always carries an uppercase letter or a digit; a tool
60
+ * name's second word is an English word in lowercase. Requiring both (a short
61
+ * prefix with a long mixed-case suffix, and no second underscore) leaves
62
+ * `set_app_workflow` and `aggregate_records` on the verb side where they belong.
63
+ */
64
+ function isResourceId(token) {
65
+ const match = /^[a-z]{2,5}_([A-Za-z0-9]{8,})$/.exec(token);
66
+ return match !== null && /[A-Z0-9]/.test(match[1]);
67
+ }
68
+ /** `lotics-cli/0.117.0 node/v22.1.0 linux` — enough to correlate a failure with a stale CLI. */
69
+ export function userAgent(version) {
70
+ return `lotics-cli/${version} node/${process.version} ${os.platform()}`;
71
+ }
72
+ let invocation = null;
73
+ /**
74
+ * `version` is passed in rather than imported: `version.ts` resolves
75
+ * `package.json` relative to its own module URL, which only holds from `dist/`,
76
+ * so importing it into `client.ts` would make the library entry unloadable from
77
+ * source. The bin already reads it correctly; the client just relays it.
78
+ */
79
+ export function setInvocation(command, session, version) {
80
+ invocation = { command, session, userAgent: userAgent(version) };
81
+ }
82
+ export function getInvocation() {
83
+ return invocation;
84
+ }
85
+ /** Back to the library state (no CLI process). Exists for tests. */
86
+ export function resetInvocation() {
87
+ invocation = null;
88
+ }
89
+ /**
90
+ * A sitting of the CLI, as one id shared by every invocation in it.
91
+ *
92
+ * Under an agent harness that already has a session concept, adopt it — the ids
93
+ * then line up with the harness's own transcript, which is the difference between
94
+ * "these 40 commands are related" and "these 40 commands ARE that conversation".
95
+ * Otherwise sessionize the way web analytics does: reuse the stored id while
96
+ * invocations keep arriving, mint a new one after an idle gap.
97
+ */
98
+ const IDLE_GAP_MS = 30 * 60 * 1000;
99
+ export function sessionStorePath() {
100
+ return path.join(os.homedir(), ".lotics", "session.json");
101
+ }
102
+ function readSession(file) {
103
+ try {
104
+ const parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
105
+ if (typeof parsed !== "object" || parsed === null)
106
+ return null;
107
+ const { id, last_seen } = parsed;
108
+ if (typeof id !== "string" || typeof last_seen !== "number")
109
+ return null;
110
+ return { id, last_seen };
111
+ }
112
+ catch {
113
+ // Absent, unreadable, or corrupt — all mean "no session to continue", and a
114
+ // telemetry id is never worth failing a command over.
115
+ return null;
116
+ }
117
+ }
118
+ /**
119
+ * The current session id, or null when telemetry is off. `now` is injected so the
120
+ * idle-gap boundary is testable without a clock.
121
+ */
122
+ export function sessionId(now = Date.now(), env = process.env) {
123
+ if (!telemetryEnabled(env))
124
+ return null;
125
+ const harnessSession = env.CLAUDE_CODE_SESSION_ID;
126
+ if (harnessSession !== undefined && harnessSession !== "")
127
+ return harnessSession;
128
+ const file = sessionStorePath();
129
+ const stored = readSession(file);
130
+ const id = stored !== null && now - stored.last_seen < IDLE_GAP_MS
131
+ ? stored.id
132
+ : `cli_${now.toString(36)}${Math.random().toString(36).slice(2, 10)}`;
133
+ try {
134
+ fs.mkdirSync(path.dirname(file), { recursive: true });
135
+ fs.writeFileSync(file, JSON.stringify({ id, last_seen: now }), { mode: 0o600 });
136
+ }
137
+ catch {
138
+ // A read-only home still gets a usable id for this process; only the
139
+ // continuity across invocations is lost.
140
+ }
141
+ return id;
142
+ }
@@ -45,7 +45,7 @@ Per-command syntax, flags, contracts, and gotchas for the public `lotics` CLI. S
45
45
  | `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. |
46
46
  | `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: 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. |
47
47
  | `LOTICS_UI_SRC=<abs path to packages/ui/src>` (env, not a command) | Dev-link `@lotics/ui` to a monorepo checkout for the length of ONE command, **for every tool at once**. The app's `vite.config.ts` gets its whole `resolve` block from the kit (`resolve: loticsResolve()` — `@lotics/ui/vite`), which reads the variable at call time and adds the `@lotics/ui/*` → working-copy alias, so kit edits go live under `lotics app dev` (HMR) and bundle under `lotics app deploy`. In the same breath, every command that regenerates types (`create`/`pull`/`dev`/`deploy`/`codegen`, all via `writeAppDts`) writes **`.lotics/tsconfig.link.json`** — the matching `paths`, which the app's `tsconfig.json` `extends` — so `tsc`, vitest, eslint and your EDITOR resolve the same copy Vite does. Unset ⇒ every one of them goes back to `node_modules`, and the generated file is rewritten inert. **Why `paths` and not `npm link`:** the kit ships un-built `.tsx`, so a kit file outside `node_modules` resolves its OWN `react`/`react-native` from the monorepo — two copies in one program and every shared type stops matching ("Two different types with this name exist, but they are unrelated"). The generated file therefore also pins every peer @lotics/ui declares to the APP's copy, types-package first (`react` → `@types/react`; pinning the runtime package instead strands tsc on a `.js` with no declarations). The pin set is derived from the installed kit's `peerDependencies`, so it tracks the kit rather than rotting. **Nothing hand-written is touched** — the generated file lives in `.lotics/` (the CLI's own dir) and no config is edited by regex, which is what the deleted `lotics ui link` did when it twice destroyed the load-bearing `react-native` alias along with the array's closing bracket. Identical for a monorepo app and an EXTERNAL one (e.g. `~/lotics_apps`). `app deploy` still warns whenever the variable is set — that the bundle carries kit code from your working copy, or that the app's config predates `loticsResolve()` and never reads it, so the PUBLISHED kit is going out. An app whose `tsconfig.json` already `extends` something else is told rather than rewritten: add `./.lotics/tsconfig.link.json` to the array yourself. |
48
- | `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. **`read` reports formatting back, so a generated file is verifiable through this path** rather than by unzipping OOXML: each cell carries `numFmt` when the file gave it one, and `--with-format` adds the resolved `style`. The asymmetry is deliberate — a parsed cell's style is *never* absent (every cell resolves to at least a font — size, name, colour), so emitting it by default would put three noise keys on every plain cell and make “is this styled?” unanswerable by presence; `numFmt` is genuinely absent on an unformatted cell, so it needs no flag. **`write` takes sheet-level `colWidths` (`{"A":34}`) and `rowHeights` (`{"1":44}`)** — without them every column is the default width and a human-facing workbook is unreadable no matter what the cells say. Both are written *pinned* (`customWidth`/`customHeight`), so Excel does not auto-fit them away, and both apply to a row/column that holds no cells (a spacer row's height survives). Keys are a bare column letter and a bare row number, bounded by Excel's grid (`A`…`XFD`, `1`…`1048576`): a key outside it, or a cell ref like `A1` where a column letter belongs, is **rejected** rather than resolved to something adjacent — past the grid the reference is written into the file verbatim, addressing a cell that cannot exist. Unknown **sheet** properties are rejected on the same terms as unknown cell properties — a silently-ignored `columnWidths` typo is a file that looks written and is not. Atomic in-place write (temp file + rename). |
48
+ | `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. **`read` reports formatting back, so a generated file is verifiable through this path** rather than by unzipping OOXML: each cell carries `numFmt` when the file gave it one, and `--with-format` adds the resolved `style`. The asymmetry is deliberate — a parsed cell's style is *never* absent (every cell resolves to at least a font — size, name, colour), so emitting it by default would put three noise keys on every plain cell and make “is this styled?” unanswerable by presence; `numFmt` is genuinely absent on an unformatted cell, so it needs no flag. **`write` takes sheet-level `colWidths` (`{"A":34}`) and `rowHeights` (`{"1":44}`)** — without them every column is the default width and a human-facing workbook is unreadable no matter what the cells say. Both are written *pinned* (`customWidth`/`customHeight`), so Excel does not auto-fit them away, and both apply to a row/column that holds no cells (a spacer row's height survives). Keys are a bare column letter and a bare row number, bounded by Excel's grid (`A`…`XFD`, `1`…`1048576`): a key outside it, or a cell ref like `A1` where a column letter belongs, is **rejected** rather than resolved to something adjacent — past the grid the reference is written into the file verbatim, addressing a cell that cannot exist. Unknown **sheet** properties are rejected on the same terms as unknown cell properties — a silently-ignored `columnWidths` typo is a file that looks written and is not. A subcommand whose trailing args are ALL flags (`xlsx read`, `docx read`, `docx append-paragraph`/`insert-paragraph`/`delete-block`) **rejects a `--flag` it does not know** — `parseArgs` files an unrecognised token as a positional, so a mistyped flag would otherwise arrive as inert text and the command would report success without it (`--with-formats` then reads as proof the file carries no styles). Subcommands whose trailing arg is CONTENT (`xlsx set-cell`, `docx replace-text`) are deliberately exempt from the FLAG check: a value may legitimately begin with `--`, and there a typo is indistinguishable from data. They are covered instead by arity — **every fixed-shape subcommand refuses an argument past the last one it reads**, whatever it looks like, because the likeliest source is a flag the caller believes exists and these commands write in place (`xlsx delete-rows f.xlsx S1 5 3 --dry-run` deleted three rows and reported success). Arity rather than a leading `--` is the discriminator, since a sheet name may legitimately begin with one. Every subcommand that can introduce a formula (`write`, `set-cell`, `batch`) **evaluates it and writes the cached value**, so a generated formula does not read back blank: Excel and Sheets recalculate on open, but parsers — including this CLI's `read` and the rest of the platform — take the cached `<v>`. A formula the engine cannot evaluate still gets written, with a stderr warning naming the cells, rather than silently leaving a hole where a number belongs. Atomic in-place write (temp file + rename). |
49
49
  | `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. **`replace-text` matches across run boundaries** — Word splits a run at every formatting change, so a `{{marker}}` routinely lands split — and reads straight THROUGH marks that occupy no place in the sentence (`w:proofErr`, `w:footnoteReference`, endnote/comment refs + ranges, `w:bookmarkStart`/`End`, `w:lastRenderedPageBreak`). `w:proofErr` is the one that decides whether this works in practice — Word brackets every word its dictionary rejects, so on non-English text it lands between nearly every pair of runs. It still refuses to join across anything that occupies space in the text — `w:br`, `w:tab`, `w:sym`, a drawing, or any tag not on that allowlist — because the joined string does not represent the glyph and a match there would rewrite text the caller never saw. The SAME rule applies inside a table cell as outside it — both run one `replaceInParagraph` over paragraphs found at any depth, so a marker split by a line break is refused in both rather than rewritten in the cell and skipped in the body under a success message. Zero matches is always a hard error, never a silent no-op, and when the words ARE on the page the error names the block and the splitting mark (`The text IS present at block 1, split by w:br …`) rather than claiming the text is absent. |
50
50
  | `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). |
51
51
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lotics/cli",
3
- "version": "0.114.0",
3
+ "version": "0.123.0",
4
4
  "description": "Lotics SDK and CLI for AI agents",
5
5
  "type": "module",
6
6
  "bin": {