@crewhaus/runtime-core 0.6.0 → 0.8.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ CrewHaus Factory
2
+ Copyright 2026 Max Meier
3
+
4
+ This product includes software developed by Max Meier
5
+ (operating as StudioMax — https://studiomax.io) and contributors.
6
+
7
+ The CrewHaus name and logo are trademarks of Max Meier. See
8
+ https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
9
+ use-of-marks policy.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # @crewhaus/runtime-core
2
+
3
+ Minimal runtime imported by generated harness bundles
4
+
5
+ Part of [CrewHaus](https://github.com/crewhaus/factory). Most people install the CLI (`npm install -g crewhaus`) rather than this package.
6
+
7
+ Requires [Bun](https://bun.sh) `>=1.3.14`; plain Node is not supported.
8
+
9
+ [Source](https://github.com/crewhaus/factory/tree/main/packages/runtime-core)
@@ -168,6 +168,13 @@ export declare function percentile(values: ReadonlyArray<number>, p: number): nu
168
168
  export declare function deriveThresholds(history: ReadonlyArray<SessionMetricsSnapshot>): DerivedThresholds;
169
169
  /** Compare a session snapshot against derived thresholds; list every breach. */
170
170
  export declare function detectBreaches(snapshot: SessionMetricsSnapshot, thresholds: DerivedThresholds): Breach[];
171
+ /**
172
+ * The most bytes of history {@link readMetricsHistory} reads: the file's
173
+ * TAIL, never more. {@link MAX_METRICS_HISTORY_LINES} snapshot lines are a few
174
+ * hundred KiB; a file past this was grown by something else, and only its end
175
+ * is ever consulted.
176
+ */
177
+ export declare const MAX_METRICS_HISTORY_BYTES: number;
171
178
  /**
172
179
  * Read the persisted session history, oldest first. Torn lines are skipped.
173
180
  *
@@ -176,7 +183,10 @@ export declare function detectBreaches(snapshot: SessionMetricsSnapshot, thresho
176
183
  * an older binary that predates the cap, or a file that grew past the cap
177
184
  * some other way) is never fully materialized into memory just to derive a
178
185
  * threshold from its tail. `appendMetricsSnapshot` keeps the file itself
179
- * trimmed going forward; this is the reader's independent bound.
186
+ * trimmed going forward; this is the reader's independent bound. 0.7.1: only
187
+ * the file's last {@link MAX_METRICS_HISTORY_BYTES} are read at all, and the
188
+ * file is read contained (see {@link appendMetricsSnapshot}); a refused file
189
+ * throws rather than reading as an empty history.
180
190
  */
181
191
  export declare function readMetricsHistory(metricsDir?: string): SessionMetricsSnapshot[];
182
192
  /**
@@ -187,5 +197,11 @@ export declare function readMetricsHistory(metricsDir?: string): SessionMetricsS
187
197
  * temp-write + rename so a crash mid-trim never leaves a torn or truncated
188
198
  * file in place of the real one; a torn LINE within the kept tail is still
189
199
  * tolerated by `readMetricsHistory`.
200
+ *
201
+ * 0.7.1: both go through @crewhaus/tool-safety, rooted at `.crewhaus` (see
202
+ * {@link metricsLocation}): the append with `appendContained`, the trim with
203
+ * `writeFileSafe` (a random O_EXCL|O_NOFOLLOW temp, never the pid-derived
204
+ * `sessions.jsonl.tmp-<pid>-<ms>`). A refusal throws, naming the file and the
205
+ * reason; the watchdog logs it and still checks this session's breaches.
190
206
  */
191
207
  export declare function appendMetricsSnapshot(snapshot: SessionMetricsSnapshot, metricsDir?: string): void;
@@ -23,9 +23,10 @@
23
23
  * and appending its own snapshot JSONL); event folding, threshold derivation,
24
24
  * and breach detection are pure and unit-tested.
25
25
  */
26
- import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, } from "node:fs";
27
- import { dirname, join } from "node:path";
26
+ import { closeSync, mkdirSync, readSync } from "node:fs";
27
+ import { basename, dirname, join, resolve } from "node:path";
28
28
  import { FLOOR_BLOCKED_ROUTE_REASON as ROUTER_FLOOR_BLOCKED_ROUTE_REASON } from "@crewhaus/model-router";
29
+ import { appendContained, openForReadFd, writeFileSafe, } from "@crewhaus/tool-safety/fs";
29
30
  /** Default location of the per-session metrics history, relative to cwd. */
30
31
  export const DEFAULT_METRICS_DIR = join(".crewhaus", "metrics");
31
32
  export const METRICS_FILENAME = "sessions.jsonl";
@@ -324,6 +325,65 @@ function fmt(n) {
324
325
  return Number.isInteger(n) ? String(n) : n.toFixed(3);
325
326
  }
326
327
  // --------- snapshot persistence (the only I/O this module owns) ---------
328
+ /**
329
+ * The most bytes of history {@link readMetricsHistory} reads: the file's
330
+ * TAIL, never more. {@link MAX_METRICS_HISTORY_LINES} snapshot lines are a few
331
+ * hundred KiB; a file past this was grown by something else, and only its end
332
+ * is ever consulted.
333
+ */
334
+ export const MAX_METRICS_HISTORY_BYTES = 4 * 1024 * 1024;
335
+ /**
336
+ * Where the history lives, as a root and a path under it. 0.7.1: the root is
337
+ * the metrics directory's PARENT (the harness `.crewhaus`), so the lazily
338
+ * created `metrics/` directory is itself contained: a symlink planted at
339
+ * `.crewhaus/metrics`, or at `sessions.jsonl`, is refused instead of written
340
+ * through (a model with GitApplyPatch can plant one; the path is fixed, so it
341
+ * needs nothing else). The parent itself is the operator's, and may be a link.
342
+ */
343
+ function metricsLocation(metricsDir) {
344
+ const dir = resolve(metricsDir);
345
+ return {
346
+ root: dirname(dir),
347
+ rel: `${basename(dir)}/${METRICS_FILENAME}`,
348
+ abs: join(dir, METRICS_FILENAME),
349
+ };
350
+ }
351
+ function metricsRefusal(op, abs, failure) {
352
+ return new Error(`alert-watchdog: refusing to ${op} ${abs}: ${failure.reason} (code ${failure.code})`);
353
+ }
354
+ /**
355
+ * The last {@link MAX_METRICS_HISTORY_BYTES} of the history file, or
356
+ * undefined when there is none. A link, FIFO or directory at the name, or a
357
+ * `metrics/` directory that leads out of `.crewhaus`, is refused (thrown),
358
+ * never read.
359
+ */
360
+ function readHistoryTail(metricsDir) {
361
+ const { root, rel, abs } = metricsLocation(metricsDir);
362
+ const opened = openForReadFd(root, rel, { followLeafSymlink: false });
363
+ if (!opened.ok) {
364
+ if (opened.code === "not-found")
365
+ return undefined;
366
+ throw metricsRefusal("read", abs, opened);
367
+ }
368
+ try {
369
+ const size = opened.stats.size;
370
+ const length = Math.min(size, MAX_METRICS_HISTORY_BYTES);
371
+ const buf = Buffer.alloc(length);
372
+ let got = 0;
373
+ while (got < length) {
374
+ const n = readSync(opened.fd, buf, got, length - got, size - length + got);
375
+ if (n === 0)
376
+ break;
377
+ got += n;
378
+ }
379
+ const text = buf.subarray(0, got).toString("utf-8");
380
+ // A tail that starts mid-file starts mid-line: drop the partial line.
381
+ return length < size ? text.slice(text.indexOf("\n") + 1) : text;
382
+ }
383
+ finally {
384
+ closeSync(opened.fd);
385
+ }
386
+ }
327
387
  /**
328
388
  * Read the persisted session history, oldest first. Torn lines are skipped.
329
389
  *
@@ -332,18 +392,19 @@ function fmt(n) {
332
392
  * an older binary that predates the cap, or a file that grew past the cap
333
393
  * some other way) is never fully materialized into memory just to derive a
334
394
  * threshold from its tail. `appendMetricsSnapshot` keeps the file itself
335
- * trimmed going forward; this is the reader's independent bound.
395
+ * trimmed going forward; this is the reader's independent bound. 0.7.1: only
396
+ * the file's last {@link MAX_METRICS_HISTORY_BYTES} are read at all, and the
397
+ * file is read contained (see {@link appendMetricsSnapshot}); a refused file
398
+ * throws rather than reading as an empty history.
336
399
  */
337
400
  export function readMetricsHistory(metricsDir = DEFAULT_METRICS_DIR) {
338
- const path = join(metricsDir, METRICS_FILENAME);
339
- if (!existsSync(path))
401
+ const text = readHistoryTail(metricsDir);
402
+ if (text === undefined)
340
403
  return [];
341
404
  // Filter blank lines (incl. the trailing "" from the file's final newline)
342
405
  // BEFORE slicing to the trailing cap — slicing raw split() output would
343
406
  // waste one slot of the cap on that trailing empty entry.
344
- const lines = readFileSync(path, "utf-8")
345
- .split("\n")
346
- .filter((l) => l.trim() !== "");
407
+ const lines = text.split("\n").filter((l) => l.trim() !== "");
347
408
  const bounded = lines.slice(-MAX_METRICS_HISTORY_LINES);
348
409
  const out = [];
349
410
  for (const line of bounded) {
@@ -364,18 +425,30 @@ export function readMetricsHistory(metricsDir = DEFAULT_METRICS_DIR) {
364
425
  * temp-write + rename so a crash mid-trim never leaves a torn or truncated
365
426
  * file in place of the real one; a torn LINE within the kept tail is still
366
427
  * tolerated by `readMetricsHistory`.
428
+ *
429
+ * 0.7.1: both go through @crewhaus/tool-safety, rooted at `.crewhaus` (see
430
+ * {@link metricsLocation}): the append with `appendContained`, the trim with
431
+ * `writeFileSafe` (a random O_EXCL|O_NOFOLLOW temp, never the pid-derived
432
+ * `sessions.jsonl.tmp-<pid>-<ms>`). A refusal throws, naming the file and the
433
+ * reason; the watchdog logs it and still checks this session's breaches.
367
434
  */
368
435
  export function appendMetricsSnapshot(snapshot, metricsDir = DEFAULT_METRICS_DIR) {
369
- const path = join(metricsDir, METRICS_FILENAME);
370
- mkdirSync(dirname(path), { recursive: true });
371
- appendFileSync(path, `${JSON.stringify(snapshot)}\n`);
372
- const lines = readFileSync(path, "utf-8")
373
- .split("\n")
374
- .filter((l) => l.trim() !== "");
375
- if (lines.length <= MAX_METRICS_HISTORY_LINES)
436
+ const { root, rel, abs } = metricsLocation(metricsDir);
437
+ mkdirSync(root, { recursive: true });
438
+ const appended = appendContained(root, rel, `${JSON.stringify(snapshot)}\n`, {
439
+ createParents: true,
440
+ });
441
+ if (!appended.ok)
442
+ throw metricsRefusal("append to", abs, appended);
443
+ // Past the byte cap the reader sees only the tail, so the file is trimmed
444
+ // to the tail's last lines even when that is fewer than the line cap.
445
+ const text = readHistoryTail(metricsDir) ?? "";
446
+ const lines = text.split("\n").filter((l) => l.trim() !== "");
447
+ if (lines.length <= MAX_METRICS_HISTORY_LINES && appended.size <= MAX_METRICS_HISTORY_BYTES) {
376
448
  return;
449
+ }
377
450
  const trimmed = lines.slice(-MAX_METRICS_HISTORY_LINES);
378
- const tmpPath = `${path}.tmp-${process.pid}-${Date.now()}`;
379
- writeFileSync(tmpPath, `${trimmed.join("\n")}\n`);
380
- renameSync(tmpPath, path);
451
+ const written = writeFileSafe(root, rel, `${trimmed.join("\n")}\n`, { overwrite: true });
452
+ if (!written.ok)
453
+ throw metricsRefusal("trim", abs, written);
381
454
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The parts of a markdown line the CLI renderer styles, read without the
3
+ * regex engine.
4
+ *
5
+ * Each function returns the captures its pattern returned. The patterns
6
+ * gave back a run of whitespace one character at a time when what followed
7
+ * could not match: `(.*)$` cannot pass a `\r` (a CRLF reply) or a U+2028,
8
+ * and the fence's trailing `\s*$` cannot pass a second word. Each give-back
9
+ * re-read the rest of the line, so a model reply with a long run of spaces
10
+ * in such a line took time quadratic in it. cli-markdown-lines.test.ts
11
+ * compares every function with its pattern.
12
+ */
13
+ /** `/^(\s*)```\s*(\S*)\s*$/`: [indent, language], or null. */
14
+ export declare function fenceParts(line: string): [string, string] | null;
15
+ /** `/^(\s*)(#{1,6})\s+(.*)$/`: [indent, hashes, text], or null. */
16
+ export declare function headingParts(line: string): [string, string, string] | null;
17
+ /** `/^(\s*)[-*+]\s+(.*)$/`: [indent, text], or null. */
18
+ export declare function bulletParts(line: string): [string, string] | null;
19
+ /** `/^(\s*)(\d+)\.\s+(.*)$/`: [indent, number, text], or null. */
20
+ export declare function numberedParts(line: string): [string, string, string] | null;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The parts of a markdown line the CLI renderer styles, read without the
3
+ * regex engine.
4
+ *
5
+ * Each function returns the captures its pattern returned. The patterns
6
+ * gave back a run of whitespace one character at a time when what followed
7
+ * could not match: `(.*)$` cannot pass a `\r` (a CRLF reply) or a U+2028,
8
+ * and the fence's trailing `\s*$` cannot pass a second word. Each give-back
9
+ * re-read the rest of the line, so a model reply with a long run of spaces
10
+ * in such a line took time quadratic in it. cli-markdown-lines.test.ts
11
+ * compares every function with its pattern.
12
+ */
13
+ /** `\s`: ECMAScript WhiteSpace and LineTerminator. */
14
+ const isSpace = (code) => (code >= 0x09 && code <= 0x0d) ||
15
+ code === 0x20 ||
16
+ code === 0xa0 ||
17
+ code === 0x1680 ||
18
+ (code >= 0x2000 && code <= 0x200a) ||
19
+ code === 0x2028 ||
20
+ code === 0x2029 ||
21
+ code === 0x202f ||
22
+ code === 0x205f ||
23
+ code === 0x3000 ||
24
+ code === 0xfeff;
25
+ /** What `.` does not match. */
26
+ const isLineTerminator = (code) => code === 0x0a || code === 0x0d || code === 0x2028 || code === 0x2029;
27
+ function skipSpace(line, from) {
28
+ let at = from;
29
+ while (at < line.length && isSpace(line.charCodeAt(at)))
30
+ at++;
31
+ return at;
32
+ }
33
+ /** Whether `(.*)$` matches `line` from `from`: no line terminator after it. */
34
+ function restIsOneLine(line, from) {
35
+ for (let at = from; at < line.length; at++) {
36
+ if (isLineTerminator(line.charCodeAt(at)))
37
+ return false;
38
+ }
39
+ return true;
40
+ }
41
+ /** `/^(\s*)```\s*(\S*)\s*$/`: [indent, language], or null. */
42
+ export function fenceParts(line) {
43
+ const indent = skipSpace(line, 0);
44
+ if (!line.startsWith("```", indent))
45
+ return null;
46
+ const langStart = skipSpace(line, indent + 3);
47
+ let langEnd = langStart;
48
+ while (langEnd < line.length && !isSpace(line.charCodeAt(langEnd)))
49
+ langEnd++;
50
+ if (skipSpace(line, langEnd) !== line.length)
51
+ return null;
52
+ return [line.slice(0, indent), line.slice(langStart, langEnd)];
53
+ }
54
+ /** `/^(\s*)(#{1,6})\s+(.*)$/`: [indent, hashes, text], or null. */
55
+ export function headingParts(line) {
56
+ const indent = skipSpace(line, 0);
57
+ let hashes = indent;
58
+ while (line.charCodeAt(hashes) === 0x23 /* # */)
59
+ hashes++;
60
+ const level = hashes - indent;
61
+ if (level < 1 || level > 6)
62
+ return null;
63
+ const text = skipSpace(line, hashes);
64
+ if (text === hashes || !restIsOneLine(line, text))
65
+ return null;
66
+ return [line.slice(0, indent), line.slice(indent, hashes), line.slice(text)];
67
+ }
68
+ /** `/^(\s*)[-*+]\s+(.*)$/`: [indent, text], or null. */
69
+ export function bulletParts(line) {
70
+ const indent = skipSpace(line, 0);
71
+ const marker = line.charCodeAt(indent);
72
+ if (marker !== 0x2d /* - */ && marker !== 0x2a /* * */ && marker !== 0x2b /* + */)
73
+ return null;
74
+ const text = skipSpace(line, indent + 1);
75
+ if (text === indent + 1 || !restIsOneLine(line, text))
76
+ return null;
77
+ return [line.slice(0, indent), line.slice(text)];
78
+ }
79
+ /** `/^(\s*)(\d+)\.\s+(.*)$/`: [indent, number, text], or null. */
80
+ export function numberedParts(line) {
81
+ const indent = skipSpace(line, 0);
82
+ let digits = indent;
83
+ while (line.charCodeAt(digits) >= 0x30 && line.charCodeAt(digits) <= 0x39)
84
+ digits++;
85
+ if (digits === indent || line.charCodeAt(digits) !== 0x2e /* . */)
86
+ return null;
87
+ const text = skipSpace(line, digits + 1);
88
+ if (text === digits + 1 || !restIsOneLine(line, text))
89
+ return null;
90
+ return [line.slice(0, indent), line.slice(indent, digits), line.slice(text)];
91
+ }
@@ -25,6 +25,7 @@
25
25
  * (links pass through as plain text — terminals already
26
26
  * auto-linkify URLs).
27
27
  */
28
+ import { bulletParts, fenceParts, headingParts, numberedParts } from "./cli-markdown-lines";
28
29
  const RESET = "\x1b[0m";
29
30
  const BOLD = "\x1b[1m";
30
31
  const DIM = "\x1b[2m";
@@ -65,41 +66,42 @@ export function createCliMarkdownRenderer(opts = {}) {
65
66
  write(`${renderLine(line)}\n`);
66
67
  }
67
68
  function renderLine(line) {
68
- // Code-fence delimiter — toggles state, dims the fence itself.
69
- const fence = /^(\s*)```\s*(\S*)\s*$/.exec(line);
69
+ // Code-fence delimiter — toggles state, dims the fence itself. The line
70
+ // parts are read by cli-markdown-lines.ts, which returns what each
71
+ // pattern noted there captured, in linear time.
72
+ const fence = fenceParts(line);
70
73
  if (fence) {
71
74
  if (!inCodeFence) {
72
75
  inCodeFence = true;
73
- codeFenceLang = fence[2] ?? "";
74
- return `${fence[1] ?? ""}${DIM}${GREEN}\`\`\`${codeFenceLang}${RESET}`;
76
+ codeFenceLang = fence[1];
77
+ return `${fence[0]}${DIM}${GREEN}\`\`\`${codeFenceLang}${RESET}`;
75
78
  }
76
79
  inCodeFence = false;
77
80
  const langSuffix = codeFenceLang ? ` (${codeFenceLang})` : "";
78
81
  codeFenceLang = "";
79
- return `${fence[1] ?? ""}${DIM}${GREEN}\`\`\`${langSuffix}${RESET}`;
82
+ return `${fence[0]}${DIM}${GREEN}\`\`\`${langSuffix}${RESET}`;
80
83
  }
81
84
  if (inCodeFence) {
82
85
  // Inside a fenced block — dim everything; preserve indentation.
83
86
  return `${DIM}${line}${RESET}`;
84
87
  }
85
88
  // Headings
86
- const heading = /^(\s*)(#{1,6})\s+(.*)$/.exec(line);
89
+ const heading = headingParts(line);
87
90
  if (heading) {
88
- const indent = heading[1] ?? "";
89
- const level = (heading[2] ?? "").length;
90
- const text = heading[3] ?? "";
91
+ const [indent, hashes, text] = heading;
92
+ const level = hashes.length;
91
93
  const color = HEADING_COLORS[level] ?? BOLD;
92
94
  return `${indent}${color}${renderInline(text)}${RESET}`;
93
95
  }
94
96
  // Unordered list bullets — replace marker with a pretty bullet.
95
- const bullet = /^(\s*)[-*+]\s+(.*)$/.exec(line);
97
+ const bullet = bulletParts(line);
96
98
  if (bullet) {
97
- return `${bullet[1] ?? ""}${CYAN}•${RESET} ${renderInline(bullet[2] ?? "")}`;
99
+ return `${bullet[0]}${CYAN}•${RESET} ${renderInline(bullet[1])}`;
98
100
  }
99
101
  // Ordered list — keep the number, color it.
100
- const numbered = /^(\s*)(\d+)\.\s+(.*)$/.exec(line);
102
+ const numbered = numberedParts(line);
101
103
  if (numbered) {
102
- return `${numbered[1] ?? ""}${CYAN}${numbered[2]}.${RESET} ${renderInline(numbered[3] ?? "")}`;
104
+ return `${numbered[0]}${CYAN}${numbered[1]}.${RESET} ${renderInline(numbered[2])}`;
103
105
  }
104
106
  // Blockquote
105
107
  const quote = /^(\s*)>\s?(.*)$/.exec(line);
@@ -0,0 +1,36 @@
1
+ /**
2
+ * A top-level union of object schemas, merged into one object schema.
3
+ *
4
+ * Anthropic forbids a top-level `anyOf`, but a nested `anyOf` on an
5
+ * individual property is fine — so each property becomes the union of its
6
+ * per-branch shapes, and `required` is the intersection across branches (in
7
+ * practice the shared discriminator). The tool's own zod schema still
8
+ * validates the real input at execute time, so the looser model-facing
9
+ * schema loses no safety.
10
+ *
11
+ * The schema can be an MCP server's, up to 32 KiB of it, read at every
12
+ * `runChatLoop` setup. Each property's shapes were kept by comparing every
13
+ * new one with every one kept so far, as JSON — about 900 branches of one
14
+ * key each made 880 000 `JSON.stringify` calls — and each branch's
15
+ * `required` list was searched once per name still in the intersection.
16
+ * Both are looked up in sets now; the schema produced is the same.
17
+ */
18
+ /** The parts of a JSON Schema the union handling reads. */
19
+ export type JsonSchemaLike = {
20
+ type?: unknown;
21
+ properties?: Record<string, unknown>;
22
+ required?: unknown;
23
+ anyOf?: unknown;
24
+ oneOf?: unknown;
25
+ allOf?: unknown;
26
+ };
27
+ /**
28
+ * Merge `branches` into one object schema over `baseProps`. A property's
29
+ * shapes are told apart by their JSON, first one kept; a property with one
30
+ * shape keeps it, one with more becomes their `anyOf`.
31
+ */
32
+ export declare function flattenUnionToObject(branches: JsonSchemaLike[], baseProps: Record<string, unknown> | undefined): {
33
+ type: "object";
34
+ properties: Record<string, unknown>;
35
+ required?: string[];
36
+ };