@linxiraos/pi-utils 1.2.1 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [1.3.1] - 2026-10-19
4
+
5
+ ### Added
6
+
7
+ - Added `readSalvageableRows()` to read the rows of a damaged SQLite table that are still readable, skipping only the damaged pages ([#15751](https://github.com/can1357/oh-my-pi/pull/15751) by [@Shadorain](https://github.com/Shadorain))
8
+
9
+ ## [1.3.0] - 2026-10-18
10
+
11
+ ### Added
12
+
13
+ - Added `sanitizeTextDeep()`, which applies `sanitizeText()` to every string in a JSON-shaped value without mutating it ([#15963](https://github.com/can1357/oh-my-pi/issues/15963))
14
+ - Exported `sqliteFileIdentity()`, so a caller holding a long-lived SQLite connection can tell when its path now names a different file (e.g. after a corrupt store was quarantined and replaced) ([#14361](https://github.com/can1357/oh-my-pi/pull/14361) by [@F0Rextasy](https://github.com/F0Rextasy))
15
+ - Added `slugify()`, the shared lowercase ASCII kebab-case helper with an optional `maxLength` ([#14283](https://github.com/can1357/oh-my-pi/pull/14283) by [@jaredlyon](https://github.com/jaredlyon))
16
+ - Added `getMnemopiEmbedRuntimeDir()` for the shared mnemopi embedding server endpoints and logs.
17
+
18
+ ### Fixed
19
+
20
+ - Fixed Windows archive extraction overwriting existing files or following existing symlinks when copying a symlink entry without symlink privileges ([#15931](https://github.com/can1357/oh-my-pi/pull/15931) by [@jchanghong023](https://github.com/jchanghong023)).
21
+ - Fixed Markdown fence info-string parsing to keep backtick-containing backtick openers as paragraph text while accepting backticks in tilde info strings and Unicode line separators in either fence's info string ([#15928](https://github.com/can1357/oh-my-pi/pull/15928) by [@jchanghong023](https://github.com/jchanghong023)).
22
+ - Fixed `parseHTML` treating `<link>` in RSS/Atom documents as an HTML void element, which dropped the URL text of RSS `<link>…</link>` ([#15954](https://github.com/can1357/oh-my-pi/issues/15954))
23
+ - Fixed an unhandled rejection when a subprocess is spawned with an already-aborted signal ([#15750](https://github.com/can1357/oh-my-pi/pull/15750) by [@harshaygadekar](https://github.com/harshaygadekar))
24
+ - Fixed `ChildProcess.kill()` silently leaving the child running when the native process handle could not be resolved or used; it now signals the child directly and escalates to SIGKILL after the grace period.
25
+
3
26
  ## [1.2.0] - 2026-10-12
4
27
 
5
28
  - Added `getNativeGrammarsDir()`, where the native addon loads downloaded tree-sitter grammars from (`~/.zeta/natives/grammars`).
@@ -8,8 +8,8 @@ no rights in third-party code, fonts, data, or marks identified below.
8
8
  PYTHON DEPENDENCY DISTRIBUTION ROLE
9
9
  ===================================
10
10
 
11
- omp-rpc has no third-party runtime dependencies. robomp declares FastAPI,
12
- Uvicorn, HTTPX, Pydantic, pydantic-settings, python-dotenv, Click, and omp-rpc
11
+ zeta-rpc has no third-party runtime dependencies. robomp declares FastAPI,
12
+ Uvicorn, HTTPX, Pydantic, pydantic-settings, python-dotenv, Click, and zeta-rpc
13
13
  as ordinary installer-resolved dependencies. The Python wheels do not vendor
14
14
  those projects; each dependency remains a separately installed distribution
15
15
  carrying its own license metadata and files. Container/system assemblers must
@@ -79,9 +79,9 @@ uutils coreutils (https://github.com/uutils/coreutils), MIT
79
79
  --------------------------------------------------------------------------------
80
80
  Covers: base32, base64, basename, cat, cksum (shared checksum machinery),
81
81
  b2sum, md5sum, sha1sum, sha224sum, sha256sum, sha384sum, sha512sum, comm, cp,
82
- cut, date, dirname, head, hostname, ln, ls, mkdir, mktemp, mv, nproc, paste,
83
- printenv, readlink, realpath, rm, seq, sort, stat, tac, tail, tee, touch, tr,
84
- truncate, uname, uniq, wc, whoami, yes.
82
+ cut, date, dirname, head, hostname, ln, ls, mkdir, mktemp, mv, nl, nproc,
83
+ paste, printenv, readlink, realpath, rm, seq, sort, stat, tac, tail, tee,
84
+ touch, tr, truncate, uname, uniq, wc, whoami, yes.
85
85
 
86
86
  Copyright (c) uutils developers
87
87
 
@@ -824,6 +824,56 @@ public licenses.
824
824
 
825
825
  Creative Commons may be contacted at creativecommons.org.
826
826
 
827
+ -------------------------------------------------------------------------------
828
+ scripts/brand/fonts/ANSI Shadow.flf, scripts/brand/fonts/mini.flf
829
+
830
+ Two FIGlet font files from the standard FIGlet font distribution — the
831
+ figlet.org font set shipped by figlet.js
832
+ (https://github.com/patorjk/figlet.js/tree/master/fonts), fetched from
833
+ figlet.js 1.8.0 — vendored so the welcome/splash brand art
834
+ (`packages/tui/src/prompt/welcome.ts`) is generated reproducibly and offline
835
+ by `bun scripts/brand/generate-logo-art.ts`. Both files are unmodified and
836
+ retain their original FIGlet headers. They are build-time inputs only: no font
837
+ file or font data is compiled into, or shipped with, a Zeta release artifact.
838
+ The fonts' own headers carry their terms:
839
+
840
+ - `ANSI Shadow.flf` — "ANSI Shadow". Author unknown ("Font Author: ?" in the
841
+ header); a TheDraw-archive font converted with the FIGlet font editor
842
+ (http://patorjk.com/figfont-editor). Distributed under the FIGlet font
843
+ license as carried by the standard FIGlet font set: free to use and
844
+ redistribute with the header intact.
845
+ - `mini.flf` — "mini" by Glenn Chappell (4/93), from figlet release 2.1
846
+ (12 Aug 1994), "Includes ISO Latin-1"; modified by Paul Burton
847
+ <solution@earthlink.net> 12/96. Header grant: "Permission is hereby given to
848
+ modify this font, as long as the modifier's name is placed on a comment
849
+ line."
850
+
851
+ FIGlet renderer — `figlet` 1.8.0 (https://github.com/patorjk/figlet.js), a
852
+ root devDependency used only to generate the art at build time; it is not
853
+ imported by any runtime bundle or shipped artifact.
854
+
855
+ MIT License
856
+
857
+ Copyright (C) 2014-present Patrick Gillespie and other contributors
858
+
859
+ Permission is hereby granted, free of charge, to any person obtaining a copy
860
+ of this software and associated documentation files (the "Software"), to deal
861
+ in the Software without restriction, including without limitation the rights
862
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
863
+ copies of the Software, and to permit persons to whom the Software is
864
+ furnished to do so, subject to the following conditions:
865
+
866
+ The above copyright notice and this permission notice shall be included in
867
+ all copies or substantial portions of the Software.
868
+
869
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
870
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
871
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
872
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
873
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
874
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
875
+ SOFTWARE.
876
+
827
877
  BUN / NPM DEPENDENCY INVENTORY
828
878
  ==============================
829
879
  This inventory is traversed from bun.lock, not from the host node_modules tree.
@@ -14,10 +14,11 @@
14
14
  /** App name (e.g. "zeta") — product-level identity: config-dir root, log file
15
15
  * names, provider attribution headers, splash wordmark. NOT the CLI command. */
16
16
  export declare const APP_NAME: string;
17
- /** CLI binary name (`npm i -g @linxiraos/zeta` installs `zetacode`, with
18
- * `zetacode` and `zeta-cli` as compatibility aliases). Every user-facing "run
19
- * this command" string and process title uses this; the bare `zeta` name
20
- * belongs to the @linxiraos/main workspace product, not this package. */
17
+ /** CLI binary name (`npm i -g @linxiraos/zeta` installs exactly one bin,
18
+ * `zetacode` — the retired `zeta-c`/`zeta-cli` aliases are gone). Every
19
+ * user-facing "run this command" string and process title uses this; the
20
+ * bare `zeta` name belongs to the @linxiraos/main workbench product, where it
21
+ * prints the suite index, not this package. */
21
22
  export declare const CLI_BIN_NAME: string;
22
23
  /** Public homepage that inference gateways (OpenRouter, Vercel AI Gateway) credit our traffic to. */
23
24
  export declare const APP_URL: string;
@@ -168,20 +169,35 @@ export declare function getPluginsNodeModules(home?: string): string;
168
169
  /** Plugin manifest (~/.zeta/plugins/package.json). */
169
170
  export declare function getPluginsPackageJson(home?: string): string;
170
171
  /**
171
- * Plugin lock file (~/.zeta/plugins/omp-plugins.lock.json).
172
- *
173
- * The on-disk filename stays upstream-compatible: it carries per-plugin runtime
174
- * state (enabled flag, version), so renaming it would reset every existing
175
- * install's plugins on upgrade. That is the reason for the compat, not a
176
- * general rule — see `document/brand-surface-rules.md`, which classifies this
177
- * surface as DUAL (read both spellings, write the Zeta one) rather than
178
- * permanently frozen.
172
+ * Zeta-named lockfile, written going forward; `PLUGINS_LOCKFILE_LEGACY` stays
173
+ * readable so a pre-rename install keeps its state (see
174
+ * `document/brand-surface-rules.md`, DUAL: read both spellings, write the Zeta
175
+ * one). Every lockfile name in the tree comes from the two constants below —
176
+ * a writer on one spelling and a reader on the other is what emptied
177
+ * `zetacode plugin list` after the loader migrated the file.
179
178
  */
180
- export declare function getPluginsLockfile(home?: string): string;
181
- /** Zeta-named lockfile, written going forward; `getPluginsLockfile` is read first. */
182
179
  export declare const PLUGINS_LOCKFILE_CANONICAL = "zeta-plugins.lock.json";
183
180
  /** Pre-rename lockfile name still produced by earlier installs. */
184
181
  export declare const PLUGINS_LOCKFILE_LEGACY = "omp-plugins.lock.json";
182
+ /**
183
+ * Plugin lock file (~/.zeta/plugins/zeta-plugins.lock.json) — the path every
184
+ * writer targets and every reader asks for first.
185
+ *
186
+ * It carries per-plugin runtime state (enabled flag, enabled features,
187
+ * version), so the rename is a migration rather than a reset: a lockfile left
188
+ * under the pre-rename name is still read (see
189
+ * {@link pluginsLockfileReadOrder}) and moved to this path on first load.
190
+ */
191
+ export declare function getPluginsLockfile(home?: string): string;
192
+ /**
193
+ * Read order for a lockfile path whose directory is a plugins root: the
194
+ * canonical name first, then the pre-rename one. Returned as absolute paths so
195
+ * a caller can hand each to `Bun.file` without re-deriving the directory.
196
+ *
197
+ * A path that is not one of the two names (a caller- or test-supplied path) is
198
+ * returned as-is and reads nothing else.
199
+ */
200
+ export declare function pluginsLockfileReadOrder(lockfilePath: string): string[];
185
201
  /**
186
202
  * Normalize a plugin id into a safe single path segment (spec §4.2): lowercased,
187
203
  * every character outside `[a-z0-9._-]` (including `/` and `\`, so scoped npm
@@ -368,6 +384,8 @@ export declare function getDebugLogPath(agentDir?: string): string;
368
384
  export declare function getSecretPlaceholderKeyPath(): string;
369
385
  /** Directory holding the per-model tiny-worker sockets and logs (~/.zeta/run/tiny; XDG default: $XDG_STATE_HOME/zeta/run/tiny). */
370
386
  export declare function getTinyWorkerRuntimeDir(): string;
387
+ /** Directory holding the per-model mnemopi embedding server endpoints and logs (~/.zeta/run/mnemopi; XDG default: $XDG_STATE_HOME/zeta/run/mnemopi). */
388
+ export declare function getMnemopiEmbedRuntimeDir(): string;
371
389
  /** Root directory containing every per-project daemon runtime scope (~/.zeta/run/daemons; XDG default: $XDG_STATE_HOME/zeta/run/daemons). */
372
390
  export declare function getDaemonRuntimeRoot(): string;
373
391
  /** Get the daemon runtime directory for a project (~/.zeta/run/daemons/<hash>; XDG default: $XDG_STATE_HOME/zeta/run/daemons/<hash>). */
@@ -48,6 +48,18 @@
48
48
  * await args.key("path").value<string>(); // "a.ts"
49
49
  * ```
50
50
  */
51
+ /**
52
+ * @internal exported for tests — monotonic count of members re-lexed by
53
+ * selecting scans: one per object member or array element a scan walked over
54
+ * on the way to the member it was asked for.
55
+ *
56
+ * Cursor resumption (see {@link ContainerIndex}) is what keeps a full
57
+ * traversal linear in the document instead of quadratic, and losing it
58
+ * changes nothing about the pulled values — only how many members get
59
+ * re-lexed. Read the live binding before and after a traversal to measure
60
+ * exactly that.
61
+ */
62
+ export declare let rescannedMembers: number;
51
63
  /** Location component in a pulled JSON path: an object member name or an array index. */
52
64
  export type PullPathSegment = string | number;
53
65
  /** JSON shape observed by a started pull. */
@@ -32,6 +32,7 @@ export { AbortError, ChildProcess, Exception, NonZeroExitError } from "./ptree.j
32
32
  export * from "./release-assets.js";
33
33
  export * from "./runtime-install.js";
34
34
  export * from "./sanitize-text.js";
35
+ export * from "./slugify.js";
35
36
  export * from "./snowflake.js";
36
37
  export * from "./sqlite.js";
37
38
  export * from "./stderr-guard.js";
@@ -26,5 +26,26 @@ export type ImageMetadata = {
26
26
  hasAlpha?: boolean;
27
27
  };
28
28
  export declare function parseImageMetadata(header: Uint8Array): ImageMetadata | null;
29
+ /** Why base64 image data is unusable; `undefined` when it is canonical and non-empty. */
30
+ export type Base64ImageDataFailure = "invalid base64 image data" | "empty image data";
31
+ /**
32
+ * Non-empty decoded bytes on success, or a validation failure reason, never both.
33
+ * Check `reason` before using `bytes`; successful base64 decoding does not establish
34
+ * that the bytes represent a supported or decodable image.
35
+ */
36
+ export type Base64ImageDecodeResult = {
37
+ bytes: Buffer;
38
+ reason?: never;
39
+ } | {
40
+ bytes?: never;
41
+ reason: Base64ImageDataFailure;
42
+ };
43
+ /**
44
+ * Validate standard base64 image data without decoding it. Padding may be omitted, but
45
+ * present padding must be canonical, the trailing bits must be zero, and the data non-empty.
46
+ */
47
+ export declare function base64ImageDataFailureReason(data: string): Base64ImageDataFailure | undefined;
48
+ /** Decode standard base64 image data under the {@link base64ImageDataFailureReason} rules. */
49
+ export declare function decodeBase64ImageData(data: string): Base64ImageDecodeResult;
29
50
  export declare function readImageMetadataSync(filePath: string, maxBytes?: number): ImageMetadata | null;
30
51
  export declare function readImageMetadata(filePath: string, maxBytes?: number): Promise<ImageMetadata | null>;
@@ -12,6 +12,17 @@
12
12
  * string after the control probe.
13
13
  */
14
14
  export declare function sanitizeText(text: string): string;
15
+ /**
16
+ * Apply {@link sanitizeText} to every string value inside a JSON-shaped value.
17
+ * Only plain objects and arrays are walked; class instances, typed arrays, and
18
+ * cyclic back-references pass through untouched. Object keys are kept as-is.
19
+ *
20
+ * Returns the input reference when nothing changed, so reference-keyed caches
21
+ * stay warm; changed containers are copied and the input is never mutated.
22
+ * The iterative walk also handles arbitrarily deep tool-result `details`
23
+ * without exhausting the TUI's call stack.
24
+ */
25
+ export declare function sanitizeTextDeep(value: unknown): unknown;
15
26
  /**
16
27
  * Escape the three XML-significant characters (`&`, `<`, `>`) in text destined
17
28
  * for an XML/markup element body. Allocation-conscious: returns the input
@@ -0,0 +1,4 @@
1
+ /** Lowercase ASCII kebab slug: [^a-z0-9]+ → "-", edge dashes trimmed; optional maxLength truncates then re-trims trailing dashes; throws RangeError unless maxLength is a non-negative integer. Returns "" when nothing survives. */
2
+ export declare function slugify(input: string, options?: {
3
+ maxLength?: number;
4
+ }): string;
@@ -1,5 +1,17 @@
1
1
  /** Shared SQLite opening, error attribution, and result-code classification for persistent stores. */
2
2
  import { Database } from "bun:sqlite";
3
+ /**
4
+ * A store's identity as `dev:ino:birthtimeMs`, `null` when the path holds no
5
+ * file, or `undefined` when the stat itself failed and no conclusion is safe.
6
+ */
7
+ export type SqliteFileIdentity = string | null | undefined;
8
+ /**
9
+ * Identity of the file currently at `dbPath`. Quarantine moves a corrupt store
10
+ * aside and recreates one at the same path, so a connection cached on the path
11
+ * alone keeps writing to the unlinked inode: callers that hold a long-lived
12
+ * handle compare this before reusing it.
13
+ */
14
+ export declare function sqliteFileIdentity(dbPath: string): SqliteFileIdentity;
3
15
  /** Controls opt-in replacement of an unrecoverably corrupt SQLite store. */
4
16
  export interface SqliteOpenOptions {
5
17
  /**
@@ -30,6 +42,17 @@ export declare function openSqliteDatabaseSync<T>(dbPath: string, initialize: (d
30
42
  export declare function annotateSqliteError(error: unknown, dbPath: string): Error;
31
43
  /** Checkpoints committed WAL frames without waiting for concurrent readers. */
32
44
  export declare function checkpointWal(db: Database): void;
45
+ /**
46
+ * Reads every row of a rowid table that SQLite can still decode, to salvage a
47
+ * damaged store. A full scan aborts at the first unreadable page, so this walks
48
+ * rowids with indexed seeks instead: when a seek hits damage it doubles its
49
+ * stride past it, then bisects back to the first rowid from which seeking
50
+ * works again, losing only rows on the damaged pages. Cross-linked pages can
51
+ * still decode rows with foreign column types, so callers validate types;
52
+ * rows returned out of rowid order count as damage. Only corruption errors are
53
+ * treated as damage; anything else is thrown.
54
+ */
55
+ export declare function readSalvageableRows<T extends object>(db: Database, table: string, columns: string): T[];
33
56
  /**
34
57
  * SQLite's busy result-code family — base `SQLITE_BUSY` plus the extended
35
58
  * variants `SQLITE_BUSY_RECOVERY` (concurrent WAL recovery), `SQLITE_BUSY_SNAPSHOT`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linxiraos/pi-utils",
3
- "version": "1.2.1",
3
+ "version": "1.3.1",
4
4
  "description": "Shared utilities for pi packages",
5
5
  "keywords": [
6
6
  "utilities",
@@ -47,14 +47,14 @@
47
47
  },
48
48
  "scripts": {
49
49
  "check": "oxlint . && oxfmt --check --no-error-on-unmatched-pattern 'src/**/*.{ts,tsx}' '{test,bench,examples,scripts}/**/*.ts' '*.ts' && bun run check:types",
50
- "check:types": "tsgo -p tsconfig.json --noEmit",
50
+ "check:types": "tsc -p tsconfig.json --noEmit",
51
51
  "lint": "oxlint .",
52
52
  "test": "bun test --parallel",
53
53
  "fix": "oxlint --fix --fix-suggestions . && bun run fmt",
54
54
  "fmt": "oxfmt --no-error-on-unmatched-pattern 'src/**/*.{ts,tsx}' '{test,bench,examples,scripts}/**/*.ts' '*.ts'"
55
55
  },
56
56
  "dependencies": {
57
- "@linxiraos/pi-natives": "1.2.1"
57
+ "@linxiraos/pi-natives": "1.3.1"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@types/bun": "1.4.3"
package/src/ar/open.ts CHANGED
@@ -234,7 +234,8 @@ export async function extractArchive(
234
234
  // privilege; skip the entry so the rest still extracts.
235
235
  const extracted = await archive.readFile(link.path).catch(() => undefined);
236
236
  if (!extracted) continue;
237
- await Bun.write(outputPath, extracted.bytes);
237
+ // Keep symlink creation's exclusive destination semantics.
238
+ await fs.writeFile(outputPath, extracted.bytes, { flag: "wx" });
238
239
  const permissions = (extracted.mode ?? 0) & 0o777;
239
240
  if (permissions) await fs.chmod(outputPath, permissions);
240
241
  }
package/src/dirs.ts CHANGED
@@ -23,10 +23,11 @@ import { isEnoent, isEnotdir } from "./fs-error";
23
23
  * names, provider attribution headers, splash wordmark. NOT the CLI command. */
24
24
  export const APP_NAME: string = "zeta";
25
25
 
26
- /** CLI binary name (`npm i -g @linxiraos/zeta` installs `zetacode`, with
27
- * `zetacode` and `zeta-cli` as compatibility aliases). Every user-facing "run
28
- * this command" string and process title uses this; the bare `zeta` name
29
- * belongs to the @linxiraos/main workspace product, not this package. */
26
+ /** CLI binary name (`npm i -g @linxiraos/zeta` installs exactly one bin,
27
+ * `zetacode` — the retired `zeta-c`/`zeta-cli` aliases are gone). Every
28
+ * user-facing "run this command" string and process title uses this; the
29
+ * bare `zeta` name belongs to the @linxiraos/main workbench product, where it
30
+ * prints the suite index, not this package. */
30
31
  export const CLI_BIN_NAME: string = "zetacode";
31
32
 
32
33
  /** Public homepage that inference gateways (OpenRouter, Vercel AI Gateway) credit our traffic to. */
@@ -701,25 +702,46 @@ export function getPluginsPackageJson(home?: string): string {
701
702
  }
702
703
 
703
704
  /**
704
- * Plugin lock file (~/.zeta/plugins/omp-plugins.lock.json).
705
- *
706
- * The on-disk filename stays upstream-compatible: it carries per-plugin runtime
707
- * state (enabled flag, version), so renaming it would reset every existing
708
- * install's plugins on upgrade. That is the reason for the compat, not a
709
- * general rule — see `document/brand-surface-rules.md`, which classifies this
710
- * surface as DUAL (read both spellings, write the Zeta one) rather than
711
- * permanently frozen.
705
+ * Zeta-named lockfile, written going forward; `PLUGINS_LOCKFILE_LEGACY` stays
706
+ * readable so a pre-rename install keeps its state (see
707
+ * `document/brand-surface-rules.md`, DUAL: read both spellings, write the Zeta
708
+ * one). Every lockfile name in the tree comes from the two constants below —
709
+ * a writer on one spelling and a reader on the other is what emptied
710
+ * `zetacode plugin list` after the loader migrated the file.
712
711
  */
713
- export function getPluginsLockfile(home?: string): string {
714
- return path.join(getPluginsDir(home), "omp-plugins.lock.json");
715
- }
716
-
717
- /** Zeta-named lockfile, written going forward; `getPluginsLockfile` is read first. */
718
712
  export const PLUGINS_LOCKFILE_CANONICAL = "zeta-plugins.lock.json";
719
713
 
720
714
  /** Pre-rename lockfile name still produced by earlier installs. */
721
715
  export const PLUGINS_LOCKFILE_LEGACY = "omp-plugins.lock.json";
722
716
 
717
+ /**
718
+ * Plugin lock file (~/.zeta/plugins/zeta-plugins.lock.json) — the path every
719
+ * writer targets and every reader asks for first.
720
+ *
721
+ * It carries per-plugin runtime state (enabled flag, enabled features,
722
+ * version), so the rename is a migration rather than a reset: a lockfile left
723
+ * under the pre-rename name is still read (see
724
+ * {@link pluginsLockfileReadOrder}) and moved to this path on first load.
725
+ */
726
+ export function getPluginsLockfile(home?: string): string {
727
+ return path.join(getPluginsDir(home), PLUGINS_LOCKFILE_CANONICAL);
728
+ }
729
+
730
+ /**
731
+ * Read order for a lockfile path whose directory is a plugins root: the
732
+ * canonical name first, then the pre-rename one. Returned as absolute paths so
733
+ * a caller can hand each to `Bun.file` without re-deriving the directory.
734
+ *
735
+ * A path that is not one of the two names (a caller- or test-supplied path) is
736
+ * returned as-is and reads nothing else.
737
+ */
738
+ export function pluginsLockfileReadOrder(lockfilePath: string): string[] {
739
+ const dir = path.dirname(lockfilePath);
740
+ const base = path.basename(lockfilePath);
741
+ if (base !== PLUGINS_LOCKFILE_CANONICAL && base !== PLUGINS_LOCKFILE_LEGACY) return [lockfilePath];
742
+ return [path.join(dir, PLUGINS_LOCKFILE_CANONICAL), path.join(dir, PLUGINS_LOCKFILE_LEGACY)];
743
+ }
744
+
723
745
  /**
724
746
  * Normalize a plugin id into a safe single path segment (spec §4.2): lowercased,
725
747
  * every character outside `[a-z0-9._-]` (including `/` and `\`, so scoped npm
@@ -1195,6 +1217,11 @@ export function getTinyWorkerRuntimeDir(): string {
1195
1217
  return dirs.rootSubdir(path.join("run", "tiny"), "state");
1196
1218
  }
1197
1219
 
1220
+ /** Directory holding the per-model mnemopi embedding server endpoints and logs (~/.zeta/run/mnemopi; XDG default: $XDG_STATE_HOME/zeta/run/mnemopi). */
1221
+ export function getMnemopiEmbedRuntimeDir(): string {
1222
+ return dirs.rootSubdir(path.join("run", "mnemopi"), "state");
1223
+ }
1224
+
1198
1225
  /** Root directory containing every per-project daemon runtime scope (~/.zeta/run/daemons; XDG default: $XDG_STATE_HOME/zeta/run/daemons). */
1199
1226
  export function getDaemonRuntimeRoot(): string {
1200
1227
  return dirs.rootSubdir(path.join("run", "daemons"), "state");
package/src/dom/parser.ts CHANGED
@@ -366,7 +366,12 @@ export function parseInto(html: string, document: Document, root: Document | Doc
366
366
  index = match ? closePattern.lastIndex : html.length;
367
367
  continue;
368
368
  }
369
- if (!VOID_ELEMENTS[parsed.name] && !(namespace === SVG_NAMESPACE && parsed.selfClosing)) {
369
+ // Feed documents follow XML rules: only an explicit `/>` closes immediately, so RSS `<link>url</link>`
370
+ // keeps its text instead of being treated as an HTML void element.
371
+ const isVoid = xmlLike
372
+ ? parsed.selfClosing
373
+ : VOID_ELEMENTS[parsed.name] || (namespace === SVG_NAMESPACE && parsed.selfClosing);
374
+ if (!isVoid) {
370
375
  stack.push(element);
371
376
  parent = element;
372
377
  }
@@ -416,7 +416,11 @@ function wrapNetworkError(error: unknown): Error {
416
416
  return new Error("Request was aborted");
417
417
  }
418
418
  if (error.message === "fetch failed" && error.cause instanceof Error) {
419
- return new Error(`Network error: ${error.cause.message}`);
419
+ // Keep the original rejection as `cause`: undici nests the errno under
420
+ // `fetch failed` (often through an AggregateError), and
421
+ // classifyNetworkCause (packages/ai/src/error/network-cause.ts) walks
422
+ // `cause`/`errors` off this error. Flattening to text alone loses it.
423
+ return new Error(`Network error: ${error.cause.message}`, { cause: error });
420
424
  }
421
425
  return error;
422
426
  }
@@ -67,6 +67,19 @@ import { parseJsonWithRepair } from "./json-parse";
67
67
  /** Maximum container nesting before a scan reports the value as pending forever. */
68
68
  const MAX_DEPTH = 128;
69
69
 
70
+ /**
71
+ * @internal exported for tests — monotonic count of members re-lexed by
72
+ * selecting scans: one per object member or array element a scan walked over
73
+ * on the way to the member it was asked for.
74
+ *
75
+ * Cursor resumption (see {@link ContainerIndex}) is what keeps a full
76
+ * traversal linear in the document instead of quadratic, and losing it
77
+ * changes nothing about the pulled values — only how many members get
78
+ * re-lexed. Read the live binding before and after a traversal to measure
79
+ * exactly that.
80
+ */
81
+ export let rescannedMembers = 0;
82
+
70
83
  /** Location component in a pulled JSON path: an object member name or an array index. */
71
84
  export type PullPathSegment = string | number;
72
85
 
@@ -326,6 +339,7 @@ function selectKey(
326
339
  lex.ws();
327
340
  if (lex.atEnd) return PENDING;
328
341
  if (key === wanted) return selectValue(lex, path, at, ended, depth + 1, slot);
342
+ rescannedMembers++;
329
343
  const skipped = scanValue(lex, ended, depth + 1);
330
344
  if (skipped.tag !== "located" || skipped.end === undefined) return PENDING;
331
345
  lex.ws();
@@ -372,6 +386,7 @@ function selectIndex(
372
386
  // biome-ignore lint/suspicious/noAssignInExpressions: parser state machine relies on the inline memoized slot
373
387
  const slot = index.elements[element] ?? (index.tail ??= { offset: lex.pos });
374
388
  if (element === wanted) return selectValue(lex, path, at, ended, depth + 1, slot);
389
+ rescannedMembers++;
375
390
  const skipped = scanValue(lex, ended, depth + 1);
376
391
  if (skipped.tag !== "located" || skipped.end === undefined) return PENDING;
377
392
  if (element === index.elements.length) {
package/src/index.ts CHANGED
@@ -32,6 +32,7 @@ export { AbortError, ChildProcess, Exception, NonZeroExitError } from "./ptree";
32
32
  export * from "./release-assets";
33
33
  export * from "./runtime-install";
34
34
  export * from "./sanitize-text";
35
+ export * from "./slugify";
35
36
  export * from "./snowflake";
36
37
  export * from "./sqlite";
37
38
  export * from "./stderr-guard";
@@ -775,7 +775,10 @@ function splitTableRow(line: string): string[] {
775
775
  }
776
776
 
777
777
  function isFence(line: string): RegExpExecArray | null {
778
- return /^ {0,3}(`{3,}|~{3,})(.*?)(?:\n|$)$/.exec(line);
778
+ // Unicode line separators may occur in the info string.
779
+ const match = /^ {0,3}(`{3,}|~{3,})([^\n]*?)(?:\n|$)$/.exec(line);
780
+ // Backtick fences cannot contain backticks in their info string.
781
+ return match && match[1]!.startsWith("`") && match[2]!.includes("`") ? null : match;
779
782
  }
780
783
  function isHeading(line: string): boolean {
781
784
  return /^ {0,3}#{1,6}(?:\s|$)/.test(line);
package/src/mime.ts CHANGED
@@ -143,6 +143,50 @@ export function parseImageMetadata(header: Uint8Array): ImageMetadata | null {
143
143
  );
144
144
  }
145
145
 
146
+ /** Why base64 image data is unusable; `undefined` when it is canonical and non-empty. */
147
+ export type Base64ImageDataFailure = "invalid base64 image data" | "empty image data";
148
+
149
+ /**
150
+ * Non-empty decoded bytes on success, or a validation failure reason, never both.
151
+ * Check `reason` before using `bytes`; successful base64 decoding does not establish
152
+ * that the bytes represent a supported or decodable image.
153
+ */
154
+ export type Base64ImageDecodeResult =
155
+ | { bytes: Buffer; reason?: never }
156
+ | { bytes?: never; reason: Base64ImageDataFailure };
157
+
158
+ const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
159
+
160
+ /**
161
+ * Validate standard base64 image data without decoding it. Padding may be omitted, but
162
+ * present padding must be canonical, the trailing bits must be zero, and the data non-empty.
163
+ */
164
+ export function base64ImageDataFailureReason(data: string): Base64ImageDataFailure | undefined {
165
+ if (data.length === 0) return "empty image data";
166
+
167
+ const match = /^([A-Za-z0-9+/]+)(={0,2})$/.exec(data);
168
+ if (!match) return "invalid base64 image data";
169
+ const encoded = match[1];
170
+ const paddingLength = match[2].length;
171
+ const remainder = encoded.length % 4;
172
+ if (remainder === 1 || (paddingLength === 1 && remainder !== 3) || (paddingLength === 2 && remainder !== 2)) {
173
+ return "invalid base64 image data";
174
+ }
175
+
176
+ const lastSextet = BASE64_ALPHABET.indexOf(encoded[encoded.length - 1]);
177
+ if ((remainder === 2 && (lastSextet & 0b1111) !== 0) || (remainder === 3 && (lastSextet & 0b11) !== 0)) {
178
+ return "invalid base64 image data";
179
+ }
180
+ return undefined;
181
+ }
182
+
183
+ /** Decode standard base64 image data under the {@link base64ImageDataFailureReason} rules. */
184
+ export function decodeBase64ImageData(data: string): Base64ImageDecodeResult {
185
+ const reason = base64ImageDataFailureReason(data);
186
+ if (reason) return { reason };
187
+ return { bytes: Buffer.from(data, "base64") };
188
+ }
189
+
146
190
  export function readImageMetadataSync(filePath: string, maxBytes = IMAGE_METADATA_HEADER_BYTES): ImageMetadata | null {
147
191
  return peekFileSync(filePath, maxBytes, parseImageMetadata);
148
192
  }
package/src/ptree.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * - Convenience helpers: captureText / execText, AbortSignal, timeouts.
8
8
  */
9
9
 
10
- import { Process } from "@linxiraos/pi-natives";
10
+ import { Process, type ProcessTerminateOptions } from "@linxiraos/pi-natives";
11
11
  import type { Spawn, Subprocess } from "bun";
12
12
 
13
13
  type InMask = "pipe" | "ignore" | Buffer | Uint8Array | null;
@@ -387,12 +387,40 @@ export class ChildProcess<In extends InMask = InMask> {
387
387
  ? { group: true }
388
388
  : undefined
389
389
  : { gracefulMs, group: this.#terminateGroup };
390
- this.#terminating = (this.#windowsRootProcess ?? Process.fromPid(this.proc.pid))
391
- ?.terminate(options)
392
- ?.catch(e => void e);
390
+ this.#terminating = this.#terminateTree(options);
393
391
  }
394
392
  }
395
393
 
394
+ /**
395
+ * Native tree termination. A native handle that cannot be resolved or used
396
+ * — the PID left the process table, or a `bun test --isolate` realm whose
397
+ * napi classes another realm superseded ("Value is not an instance of class
398
+ * `Process`") — must not leave the child running, so signal it directly.
399
+ */
400
+ #terminateTree(options: ProcessTerminateOptions | undefined): Promise<boolean | void> {
401
+ const gracefulMs = options?.gracefulMs ?? 1000;
402
+ try {
403
+ const root = this.#windowsRootProcess ?? Process.fromPid(this.proc.pid);
404
+ if (root) return root.terminate(options).catch(() => this.#signalChild(gracefulMs));
405
+ } catch {}
406
+ return this.#signalChild(gracefulMs);
407
+ }
408
+
409
+ /** SIGTERM the child (its group when it leads one), then SIGKILL if it outlives `gracefulMs`. */
410
+ async #signalChild(gracefulMs: number): Promise<void> {
411
+ const signal = (name: NodeJS.Signals) => {
412
+ try {
413
+ if (this.#terminateGroup && process.platform !== "win32") process.kill(-this.proc.pid, name);
414
+ else this.proc.kill(name);
415
+ } catch {}
416
+ };
417
+ if (gracefulMs >= 0) {
418
+ signal("SIGTERM");
419
+ await Promise.race([this.proc.exited, Bun.sleep(gracefulMs)]);
420
+ }
421
+ if (this.proc.exitCode === null && this.proc.signalCode === null) signal("SIGKILL");
422
+ }
423
+
396
424
  async #hardKillSubreaperTree(root: Process): Promise<void> {
397
425
  try {
398
426
  const deadline = Date.now() + SUBREAPER_KILL_WINDOW_MS;
@@ -415,7 +443,9 @@ export class ChildProcess<In extends InMask = InMask> {
415
443
  // ── Output helpers ───────────────────────────────────────────────────
416
444
 
417
445
  async #throwIfAborted(): Promise<void> {
418
- const exitReason = this.exitReason;
446
+ // A kill() issued before Bun reports the root's exit only records the
447
+ // reason as pending; output readers that do not wait for exit must still see it.
448
+ const exitReason = this.#exitReason ?? this.#exitReasonPending;
419
449
  if (!exitReason?.aborted) return;
420
450
  if (this.#terminating) await this.#terminating;
421
451
  throw exitReason;
@@ -561,10 +591,11 @@ export class ChildProcess<In extends InMask = InMask> {
561
591
  // ── Signal / timeout ─────────────────────────────────────────────────
562
592
 
563
593
  attachSignal(signal: AbortSignal): void {
594
+ const cleanup = this.#exited.catch(() => {});
564
595
  const onAbort = () => this.kill(new AbortError(signal.reason, "<cancelled>"));
565
596
  if (signal.aborted) return void onAbort();
566
597
  signal.addEventListener("abort", onAbort, { once: true });
567
- this.#exited.catch(() => {}).finally(() => signal.removeEventListener("abort", onAbort));
598
+ cleanup.finally(() => signal.removeEventListener("abort", onAbort));
568
599
  }
569
600
 
570
601
  #clearTimeout(): void {
@@ -12,6 +12,8 @@
12
12
  * string after the control probe.
13
13
  */
14
14
 
15
+ import { isRecord } from "./type-guards";
16
+
15
17
  const ESC_CHAR = "\x1b";
16
18
 
17
19
  // Well-formed strings only need control/ANSI detection: C0 (excl. \t \n),
@@ -37,6 +39,74 @@ function sanitizeWellFormedText(text: string): string {
37
39
  return stripped.replace(CONTROL_RE, "");
38
40
  }
39
41
 
42
+ /**
43
+ * Apply {@link sanitizeText} to every string value inside a JSON-shaped value.
44
+ * Only plain objects and arrays are walked; class instances, typed arrays, and
45
+ * cyclic back-references pass through untouched. Object keys are kept as-is.
46
+ *
47
+ * Returns the input reference when nothing changed, so reference-keyed caches
48
+ * stay warm; changed containers are copied and the input is never mutated.
49
+ * The iterative walk also handles arbitrarily deep tool-result `details`
50
+ * without exhausting the TUI's call stack.
51
+ */
52
+ export function sanitizeTextDeep(value: unknown): unknown {
53
+ if (typeof value === "string") return sanitizeText(value);
54
+ const root = sanitizerFrame(value);
55
+ if (!root) return value;
56
+ const stack: SanitizerFrame[] = [root];
57
+ const ancestors = new Set<object>([root.value]);
58
+ while (true) {
59
+ const frame = stack[stack.length - 1]!;
60
+ const length = frame.kind === "array" ? frame.value.length : frame.keys.length;
61
+ if (frame.index === length) {
62
+ const clean = frame.copy ?? frame.value;
63
+ ancestors.delete(frame.value);
64
+ stack.pop();
65
+ if (stack.length === 0) return clean;
66
+ acceptSanitizedValue(stack[stack.length - 1]!, clean);
67
+ continue;
68
+ }
69
+ const child = frame.kind === "array" ? frame.value[frame.index++] : frame.value[frame.keys[frame.index++]!];
70
+ if (typeof child === "string") {
71
+ acceptSanitizedValue(frame, sanitizeText(child));
72
+ continue;
73
+ }
74
+ if (child === null || typeof child !== "object" || ancestors.has(child)) continue;
75
+ const next = sanitizerFrame(child);
76
+ if (!next) continue;
77
+ ancestors.add(child);
78
+ stack.push(next);
79
+ }
80
+ }
81
+
82
+ type SanitizerFrame =
83
+ | { kind: "array"; value: unknown[]; index: number; copy?: unknown[] }
84
+ | { kind: "record"; value: Record<string, unknown>; keys: string[]; index: number; copy?: Record<string, unknown> };
85
+
86
+ function sanitizerFrame(value: unknown): SanitizerFrame | undefined {
87
+ if (Array.isArray(value)) return { kind: "array", value, index: 0 };
88
+ if (!isRecord(value)) return undefined;
89
+ const proto: unknown = Object.getPrototypeOf(value);
90
+ if (proto !== Object.prototype && proto !== null) return undefined;
91
+ return { kind: "record", value, keys: Object.keys(value), index: 0 };
92
+ }
93
+
94
+ function acceptSanitizedValue(frame: SanitizerFrame, clean: unknown): void {
95
+ if (frame.kind === "array") {
96
+ const index = frame.index - 1;
97
+ if (clean !== frame.value[index]) (frame.copy ??= frame.value.slice())[index] = clean;
98
+ return;
99
+ }
100
+ const key = frame.keys[frame.index - 1]!;
101
+ if (clean === frame.value[key]) return;
102
+ const copy = (frame.copy ??= { ...frame.value });
103
+ if (key === "__proto__") {
104
+ Object.defineProperty(copy, key, { value: clean, writable: true, enumerable: true, configurable: true });
105
+ } else {
106
+ copy[key] = clean;
107
+ }
108
+ }
109
+
40
110
  /**
41
111
  * Escape the three XML-significant characters (`&`, `<`, `>`) in text destined
42
112
  * for an XML/markup element body. Allocation-conscious: returns the input
package/src/slugify.ts ADDED
@@ -0,0 +1,11 @@
1
+ /** Lowercase ASCII kebab slug: [^a-z0-9]+ → "-", edge dashes trimmed; optional maxLength truncates then re-trims trailing dashes; throws RangeError unless maxLength is a non-negative integer. Returns "" when nothing survives. */
2
+ export function slugify(input: string, options?: { maxLength?: number }): string {
3
+ if (options?.maxLength !== undefined && !(Number.isInteger(options.maxLength) && options.maxLength >= 0)) {
4
+ throw new RangeError(`slugify maxLength must be a non-negative integer, got ${options.maxLength}`);
5
+ }
6
+ const slug = input
7
+ .toLowerCase()
8
+ .replace(/[^a-z0-9]+/g, "-")
9
+ .replace(/^-+|-+$/g, "");
10
+ return options?.maxLength === undefined ? slug : slug.slice(0, options.maxLength).replace(/-+$/g, "");
11
+ }
package/src/sqlite.ts CHANGED
@@ -11,7 +11,11 @@ const BUSY_MAX_ATTEMPTS = 4;
11
11
  const BUSY_BASE_DELAY_MS = 100;
12
12
  const SQLITE_STORE_SUFFIXES = ["-wal", "-shm", "-journal", ""];
13
13
 
14
- type SqliteFileIdentity = string | null | undefined;
14
+ /**
15
+ * A store's identity as `dev:ino:birthtimeMs`, `null` when the path holds no
16
+ * file, or `undefined` when the stat itself failed and no conclusion is safe.
17
+ */
18
+ export type SqliteFileIdentity = string | null | undefined;
15
19
 
16
20
  /**
17
21
  * Corrupt handles held open by in-process openers awaiting recovery, keyed by
@@ -77,7 +81,13 @@ class SqliteAttemptFailure extends Error {
77
81
  }
78
82
  }
79
83
 
80
- function sqliteFileIdentity(dbPath: string): SqliteFileIdentity {
84
+ /**
85
+ * Identity of the file currently at `dbPath`. Quarantine moves a corrupt store
86
+ * aside and recreates one at the same path, so a connection cached on the path
87
+ * alone keeps writing to the unlinked inode: callers that hold a long-lived
88
+ * handle compare this before reusing it.
89
+ */
90
+ export function sqliteFileIdentity(dbPath: string): SqliteFileIdentity {
81
91
  try {
82
92
  const stat = fs.statSync(dbPath);
83
93
  return `${stat.dev}:${stat.ino}:${stat.birthtimeMs}`;
@@ -333,6 +343,75 @@ export function checkpointWal(db: Database): void {
333
343
  db.run("PRAGMA wal_checkpoint(PASSIVE)");
334
344
  }
335
345
 
346
+ /** Damaged regions one {@link readSalvageableRows} scan skips before abandoning the rest of the table. */
347
+ const SALVAGE_MAX_DAMAGED_REGIONS = 1000;
348
+
349
+ /**
350
+ * Reads every row of a rowid table that SQLite can still decode, to salvage a
351
+ * damaged store. A full scan aborts at the first unreadable page, so this walks
352
+ * rowids with indexed seeks instead: when a seek hits damage it doubles its
353
+ * stride past it, then bisects back to the first rowid from which seeking
354
+ * works again, losing only rows on the damaged pages. Cross-linked pages can
355
+ * still decode rows with foreign column types, so callers validate types;
356
+ * rows returned out of rowid order count as damage. Only corruption errors are
357
+ * treated as damage; anything else is thrown.
358
+ */
359
+ export function readSalvageableRows<T extends object>(db: Database, table: string, columns: string): T[] {
360
+ type Row = T & { salvage_rowid: number };
361
+ using seek = db.prepare<Row, [number]>(
362
+ `SELECT rowid AS salvage_rowid, ${columns} FROM ${table} WHERE rowid > ? ORDER BY rowid LIMIT 1`,
363
+ );
364
+ using exact = db.prepare<Row, [number]>(`SELECT rowid AS salvage_rowid, ${columns} FROM ${table} WHERE rowid = ?`);
365
+ // The row found, null when there is none, or undefined when the read hit damage.
366
+ const probe = (after: number, at?: number): Row | null | undefined => {
367
+ try {
368
+ const row = at === undefined ? seek.get(after) : exact.get(at);
369
+ if (!row) return null;
370
+ const valid = Number.isSafeInteger(row.salvage_rowid) && row.salvage_rowid === (at ?? row.salvage_rowid);
371
+ return valid && row.salvage_rowid > after ? row : undefined;
372
+ } catch (error) {
373
+ if (isSqliteCorruptionError(error)) return undefined;
374
+ throw error;
375
+ }
376
+ };
377
+
378
+ const rows: T[] = [];
379
+ const keep = (row: Row): void => {
380
+ const { salvage_rowid: _, ...values } = row;
381
+ rows.push(values as unknown as T);
382
+ };
383
+ let after = Number.MIN_SAFE_INTEGER;
384
+ let damaged = 0;
385
+ while (after < Number.MAX_SAFE_INTEGER) {
386
+ const row = probe(after);
387
+ if (row === null) break;
388
+ if (row) {
389
+ keep(row);
390
+ after = row.salvage_rowid;
391
+ continue;
392
+ }
393
+ if (++damaged > SALVAGE_MAX_DAMAGED_REGIONS) break;
394
+ // An end-of-table result counts as clear: the gap below it may still hold readable rows.
395
+ let bad = after;
396
+ let clear = Number.MAX_SAFE_INTEGER;
397
+ for (let step = 1; after + step < clear; step *= 2) {
398
+ if (probe(after + step) !== undefined) clear = after + step;
399
+ else bad = after + step;
400
+ }
401
+ while (clear - bad > 1) {
402
+ const mid = bad + Math.floor((clear - bad) / 2);
403
+ if (probe(mid) === undefined) bad = mid;
404
+ else clear = mid;
405
+ }
406
+ // An interior key bounds its left subtree inclusively, so seeking past the last
407
+ // damaged rowid descends into the damage again and `clear` itself is skipped.
408
+ const boundary = probe(bad, clear);
409
+ if (boundary) keep(boundary);
410
+ after = clear;
411
+ }
412
+ return rows;
413
+ }
414
+
336
415
  /**
337
416
  * SQLite's busy result-code family — base `SQLITE_BUSY` plus the extended
338
417
  * variants `SQLITE_BUSY_RECOVERY` (concurrent WAL recovery), `SQLITE_BUSY_SNAPSHOT`,