@crewhaus/tool-text 0.7.0 → 0.8.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/LICENSE +201 -0
- package/NOTICE +9 -0
- package/README.md +14 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +94 -35
- package/dist/lib/entities.d.ts +2 -0
- package/dist/lib/entities.js +71 -9
- package/dist/lib/markdown.d.ts +18 -0
- package/dist/lib/markdown.js +35 -4
- package/dist/lib/normalize.d.ts +20 -1
- package/dist/lib/normalize.js +181 -17
- package/dist/lib/regex.d.ts +54 -7
- package/dist/lib/regex.js +116 -27
- package/dist/lib/similarity.d.ts +20 -1
- package/dist/lib/similarity.js +67 -15
- package/dist/lib/template.d.ts +23 -2
- package/dist/lib/template.js +36 -7
- package/package.json +11 -6
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
CHANGED
|
@@ -48,6 +48,20 @@ recognition. `TextSimilarity` is lexical, with no embeddings.
|
|
|
48
48
|
Where a deterministic first pass exists, it belongs first and the model is the
|
|
49
49
|
escalation path.
|
|
50
50
|
|
|
51
|
+
## Caller patterns
|
|
52
|
+
|
|
53
|
+
`RegexExtract`'s pattern and `RuleClassify`'s regex rules are the caller's,
|
|
54
|
+
run over the caller's text, so neither runs on the caller's thread: each call
|
|
55
|
+
runs them in one `@crewhaus/tool-safety` regex worker under a five-second
|
|
56
|
+
deadline (a synchronous `RegExp` cannot be interrupted; `a*a*a*a*b` over 400
|
|
57
|
+
characters held the whole process for 108 s). A pattern that backtracks
|
|
58
|
+
exponentially (`(a+)+`, `(\w+\s?)*`) is refused with the reason, as an invalid
|
|
59
|
+
one is. A run that cannot finish is never "no match": `RegexExtract` returns
|
|
60
|
+
the matches it found with `undetermined` and the reason, and `RuleClassify`
|
|
61
|
+
returns no label, not the default, listing the patterns it could not answer.
|
|
62
|
+
The engine giving up is detected by time, so a genuine no-match slower than
|
|
63
|
+
100 ms is reported the same way.
|
|
64
|
+
|
|
51
65
|
## Layout
|
|
52
66
|
|
|
53
67
|
`src/lib/` holds the pure functions and is where the behaviour is tested;
|
package/dist/index.d.ts
CHANGED
|
@@ -31,4 +31,11 @@ export declare const TEXT_TOOLS: ReadonlyArray<RegisteredTool>;
|
|
|
31
31
|
* parsers means two numberings, one of which is wrong. This is the same
|
|
32
32
|
* reason `@crewhaus/tool-code` exports its lockfile readers beside its tools.
|
|
33
33
|
*/
|
|
34
|
+
/**
|
|
35
|
+
* The ATX heading reader and the offset-to-line index, re-exported so a
|
|
36
|
+
* package that reports "line 12" of a Markdown file, or reads its headings,
|
|
37
|
+
* asks the same code this one does (`@crewhaus/tool-verify` does both).
|
|
38
|
+
*/
|
|
39
|
+
export { parseAtxHeading } from "./lib/markdown";
|
|
40
|
+
export { lineStarts, offsetToLineCol } from "./lib/locate";
|
|
34
41
|
export { type DiffFileStatus, type DiffLineKind, type ParsedDiff, type ParsedDiffFile, type ParsedDiffLine, type ParsedHunk, parseUnifiedDiff, } from "./lib/diff";
|
package/dist/index.js
CHANGED
|
@@ -20,8 +20,8 @@ import { estimateTokens, tokenize } from "./lib/locate";
|
|
|
20
20
|
import { compactLogLines } from "./lib/log";
|
|
21
21
|
import { codeBlocks, markdownTable as markdownTableFn, parseHeadings, renderOutline, sectionBody, } from "./lib/markdown";
|
|
22
22
|
import { glossaryReplace as glossaryReplaceFn, normalizeText as normalizeTextFn, sortLines as sortLinesFn, } from "./lib/normalize";
|
|
23
|
-
import { regexExtractAll } from "./lib/regex";
|
|
24
|
-
import { extractKeywords as extractKeywordsFn, fuzzyRank, similarity } from "./lib/similarity";
|
|
23
|
+
import { answerPatterns, regexExtractAll, regexRunContext } from "./lib/regex";
|
|
24
|
+
import { MAX_SIMILARITY_WORK, extractKeywords as extractKeywordsFn, fuzzyRank, similarity, similarityCost, } from "./lib/similarity";
|
|
25
25
|
import { classifyByRules, renderTemplateString } from "./lib/template";
|
|
26
26
|
/** Compact JSON — no indentation, since the reader is a model, not a person. */
|
|
27
27
|
const json = (value) => JSON.stringify(value);
|
|
@@ -31,6 +31,11 @@ const json = (value) => JSON.stringify(value);
|
|
|
31
31
|
* memory. Callers hitting it should narrow the input rather than raise it.
|
|
32
32
|
*/
|
|
33
33
|
const MAX_INPUT_CHARS = 2_000_000;
|
|
34
|
+
/**
|
|
35
|
+
* The most cells TextDiff's LCS table may hold: a memory bound (the table
|
|
36
|
+
* is built whole), the ceiling it has had since 0.7.0.
|
|
37
|
+
*/
|
|
38
|
+
const MAX_DIFF_CELLS = 25_000_000;
|
|
34
39
|
function assertSize(text, field) {
|
|
35
40
|
if (text.length > MAX_INPUT_CHARS) {
|
|
36
41
|
throw new Error(`${field} is ${text.length} characters, over the ${MAX_INPUT_CHARS} limit — narrow the input first`);
|
|
@@ -39,7 +44,7 @@ function assertSize(text, field) {
|
|
|
39
44
|
// ---------------------------------------------------------------------------
|
|
40
45
|
export const regexExtract = buildTool({
|
|
41
46
|
name: "RegexExtract",
|
|
42
|
-
description: "Extract every regex match from text, with named capture groups, character offsets and line numbers. Use to pull ids, versions, paths or fields out of logs and documents without reading the whole thing into context.",
|
|
47
|
+
description: "Extract every regex match from text, with named capture groups, character offsets and line numbers. Use to pull ids, versions, paths or fields out of logs and documents without reading the whole thing into context. The pattern runs under a time limit; a pattern that backtracks exponentially is refused, and a run that cannot finish says so rather than reporting the matches it found as all of them.",
|
|
43
48
|
inputSchema: z.object({
|
|
44
49
|
text: z.string().describe("the text to search"),
|
|
45
50
|
pattern: z.string().min(1).describe("a JavaScript regular expression source"),
|
|
@@ -52,28 +57,30 @@ export const regexExtract = buildTool({
|
|
|
52
57
|
}),
|
|
53
58
|
readOnly: true,
|
|
54
59
|
concurrencySafe: true,
|
|
55
|
-
execute: async (input) => {
|
|
60
|
+
execute: async (input, ctx) => {
|
|
56
61
|
assertSize(input.text, "text");
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
62
|
+
const flags = input.flags ?? "";
|
|
63
|
+
// The match runs in the regex worker under a deadline, never on this
|
|
64
|
+
// thread (C073): `a*a*a*a*b` over 400 characters held the process 108 s.
|
|
65
|
+
const result = await regexExtractAll(input.text, input.pattern, flags, input.maxMatches ?? 500, regexRunContext(ctx));
|
|
66
|
+
if (!result.ok) {
|
|
67
|
+
// An invalid or refused pattern is a caller mistake, not a crash: say why.
|
|
68
|
+
return `invalid regex /${input.pattern}/${flags}: ${result.invalid}`;
|
|
60
69
|
}
|
|
61
|
-
|
|
62
|
-
// An invalid pattern is a caller mistake, not a crash: say which part.
|
|
63
|
-
return `invalid regex /${input.pattern}/${input.flags ?? ""}: ${err.message}`;
|
|
64
|
-
}
|
|
65
|
-
if (input.valuesOnly) {
|
|
66
|
-
return json({
|
|
67
|
-
count: result.matches.length,
|
|
68
|
-
truncated: result.truncated,
|
|
69
|
-
values: result.matches.map((m) => m.match),
|
|
70
|
-
});
|
|
71
|
-
}
|
|
72
|
-
return json({
|
|
70
|
+
const head = {
|
|
73
71
|
count: result.matches.length,
|
|
74
72
|
truncated: result.truncated,
|
|
75
|
-
|
|
76
|
-
|
|
73
|
+
...(result.truncatedBy === undefined ? {} : { truncatedBy: result.truncatedBy }),
|
|
74
|
+
...(result.undetermined === undefined
|
|
75
|
+
? {}
|
|
76
|
+
: {
|
|
77
|
+
undetermined: `the pattern could not be run to the end of the text, so there may be more matches: ${result.undetermined}`,
|
|
78
|
+
}),
|
|
79
|
+
};
|
|
80
|
+
if (input.valuesOnly) {
|
|
81
|
+
return json({ ...head, values: result.matches.map((m) => m.match) });
|
|
82
|
+
}
|
|
83
|
+
return json({ ...head, matches: result.matches });
|
|
77
84
|
},
|
|
78
85
|
});
|
|
79
86
|
export const textDiff = buildTool({
|
|
@@ -101,7 +108,7 @@ export const textDiff = buildTool({
|
|
|
101
108
|
const bLines = prep(input.b);
|
|
102
109
|
// The LCS table is O(n*m) cells; refuse rather than exhaust memory.
|
|
103
110
|
const cells = (aLines.length + 1) * (bLines.length + 1);
|
|
104
|
-
if (cells >
|
|
111
|
+
if (cells > MAX_DIFF_CELLS) {
|
|
105
112
|
return `inputs too large to diff (${aLines.length} x ${bLines.length} lines) — diff a narrower region`;
|
|
106
113
|
}
|
|
107
114
|
const ops = diffLines(aLines, bLines);
|
|
@@ -310,13 +317,20 @@ export const ruleClassify = buildTool({
|
|
|
310
317
|
}),
|
|
311
318
|
readOnly: true,
|
|
312
319
|
concurrencySafe: true,
|
|
313
|
-
execute: async (input) => {
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
}
|
|
320
|
+
execute: async (input, ctx) => {
|
|
321
|
+
assertSize(input.text, "text");
|
|
322
|
+
const rules = input.rules.map((r) => ({
|
|
323
|
+
...r,
|
|
324
|
+
weight: r.weight ?? 1,
|
|
325
|
+
regex: r.regex ?? false,
|
|
326
|
+
}));
|
|
327
|
+
// Regex rules are answered in the worker, all at once, before scoring;
|
|
328
|
+
// one with no answer leaves the label undetermined, never the default.
|
|
329
|
+
const regexPatterns = rules.filter((r) => r.regex).flatMap((r) => r.patterns);
|
|
330
|
+
const answered = await answerPatterns(input.text, regexPatterns, "i", regexRunContext(ctx));
|
|
331
|
+
if (!answered.ok)
|
|
332
|
+
return `invalid rule pattern: ${answered.invalid}`;
|
|
333
|
+
return json(classifyByRules(input.text, rules, input.threshold ?? 1, input.defaultLabel ?? null, answered.answers));
|
|
320
334
|
},
|
|
321
335
|
});
|
|
322
336
|
export const normalizeText = buildTool({
|
|
@@ -421,6 +435,21 @@ export const extractEntities = buildTool({
|
|
|
421
435
|
return json(flat);
|
|
422
436
|
},
|
|
423
437
|
});
|
|
438
|
+
/**
|
|
439
|
+
* The most quadratic work one FuzzyMatch call may do, summed over its
|
|
440
|
+
* candidates, in Levenshtein cells: two single comparisons' worth, about
|
|
441
|
+
* two seconds of one thread. tool-kyc's SanctionsScreen sends up to 10,000
|
|
442
|
+
* list names per call; at the name lengths a sanctions list holds (tens of
|
|
443
|
+
* characters) that is a few million cells, far inside it.
|
|
444
|
+
*/
|
|
445
|
+
const MAX_FUZZY_WORK = 2 * MAX_SIMILARITY_WORK;
|
|
446
|
+
/** Why comparing a and b by `method` is too much work for one call, or null. */
|
|
447
|
+
function tooCostly(a, b, method) {
|
|
448
|
+
const cells = similarityCost(a, b, method);
|
|
449
|
+
if (cells <= MAX_SIMILARITY_WORK)
|
|
450
|
+
return null;
|
|
451
|
+
return `inputs too large for ${method} (${a.length} x ${b.length} characters) — use trigram or tokenJaccard, or compare a narrower region`;
|
|
452
|
+
}
|
|
424
453
|
export const fuzzyMatch = buildTool({
|
|
425
454
|
name: "FuzzyMatch",
|
|
426
455
|
description: "Rank candidate strings against a query by edit distance, Jaro-Winkler, trigram or token overlap. Use to map a typed name onto a canonical id, or to reconcile two lists, without asking a model to guess.",
|
|
@@ -433,9 +462,26 @@ export const fuzzyMatch = buildTool({
|
|
|
433
462
|
}),
|
|
434
463
|
readOnly: true,
|
|
435
464
|
concurrencySafe: true,
|
|
436
|
-
execute: async (input) =>
|
|
437
|
-
|
|
438
|
-
|
|
465
|
+
execute: async (input) => {
|
|
466
|
+
const method = input.method ?? "jaro";
|
|
467
|
+
assertSize(input.query, "query");
|
|
468
|
+
// Refused before any comparison runs, never part-way through: a ranking
|
|
469
|
+
// that silently skipped the costly candidates would read as "no match".
|
|
470
|
+
let total = 0;
|
|
471
|
+
for (const [i, candidate] of input.candidates.entries()) {
|
|
472
|
+
assertSize(candidate, `candidates[${i}]`);
|
|
473
|
+
const single = tooCostly(input.query, candidate, method);
|
|
474
|
+
if (single !== null)
|
|
475
|
+
return `candidates[${i}]: ${single}`;
|
|
476
|
+
total += similarityCost(input.query, candidate, method);
|
|
477
|
+
}
|
|
478
|
+
if (total > MAX_FUZZY_WORK) {
|
|
479
|
+
return `candidates too large for ${method}: ${input.candidates.length} comparisons against a ${input.query.length}-character query need about ${total} cells, over the ${MAX_FUZZY_WORK} one call may take — use trigram or tokenJaccard, or send fewer or shorter candidates`;
|
|
480
|
+
}
|
|
481
|
+
return json({
|
|
482
|
+
hits: fuzzyRank(input.query, input.candidates, method, input.minScore ?? 0.5, input.limit ?? 10),
|
|
483
|
+
});
|
|
484
|
+
},
|
|
439
485
|
});
|
|
440
486
|
export const textSimilarity = buildTool({
|
|
441
487
|
name: "TextSimilarity",
|
|
@@ -450,9 +496,13 @@ export const textSimilarity = buildTool({
|
|
|
450
496
|
execute: async (input) => {
|
|
451
497
|
assertSize(input.a, "a");
|
|
452
498
|
assertSize(input.b, "b");
|
|
499
|
+
const method = input.method ?? "trigram";
|
|
500
|
+
const refused = tooCostly(input.a, input.b, method);
|
|
501
|
+
if (refused !== null)
|
|
502
|
+
return refused;
|
|
453
503
|
return json({
|
|
454
|
-
score: Number(similarity(input.a, input.b,
|
|
455
|
-
method
|
|
504
|
+
score: Number(similarity(input.a, input.b, method).toFixed(6)),
|
|
505
|
+
method,
|
|
456
506
|
});
|
|
457
507
|
},
|
|
458
508
|
});
|
|
@@ -521,7 +571,9 @@ export const glossaryReplace = buildTool({
|
|
|
521
571
|
concurrencySafe: true,
|
|
522
572
|
execute: async (input) => {
|
|
523
573
|
assertSize(input.text, "text");
|
|
524
|
-
const out = glossaryReplaceFn(input.text, input.mapping, input.wholeWord ?? true, input.caseSensitive ?? false
|
|
574
|
+
const out = glossaryReplaceFn(input.text, input.mapping, input.wholeWord ?? true, input.caseSensitive ?? false,
|
|
575
|
+
// What the mapping may grow the text to: the limit for the text itself.
|
|
576
|
+
MAX_INPUT_CHARS);
|
|
525
577
|
return json({ text: out.text, replacements: out.replacements });
|
|
526
578
|
},
|
|
527
579
|
});
|
|
@@ -572,4 +624,11 @@ export const TEXT_TOOLS = Object.freeze([
|
|
|
572
624
|
* parsers means two numberings, one of which is wrong. This is the same
|
|
573
625
|
* reason `@crewhaus/tool-code` exports its lockfile readers beside its tools.
|
|
574
626
|
*/
|
|
627
|
+
/**
|
|
628
|
+
* The ATX heading reader and the offset-to-line index, re-exported so a
|
|
629
|
+
* package that reports "line 12" of a Markdown file, or reads its headings,
|
|
630
|
+
* asks the same code this one does (`@crewhaus/tool-verify` does both).
|
|
631
|
+
*/
|
|
632
|
+
export { parseAtxHeading } from "./lib/markdown";
|
|
633
|
+
export { lineStarts, offsetToLineCol } from "./lib/locate";
|
|
575
634
|
export { parseUnifiedDiff, } from "./lib/diff";
|
package/dist/lib/entities.d.ts
CHANGED
|
@@ -13,3 +13,5 @@ export type EntityHit = {
|
|
|
13
13
|
readonly line: number;
|
|
14
14
|
};
|
|
15
15
|
export declare function extractEntities(text: string, kinds: ReadonlyArray<string>, unique: boolean): Record<string, EntityHit[]>;
|
|
16
|
+
/** Every match of one kind's pattern, in order. */
|
|
17
|
+
export declare function matchesOf(text: string, kind: string, source: RegExp): Generator<RegExpExecArray>;
|
package/dist/lib/entities.js
CHANGED
|
@@ -23,27 +23,72 @@ export const ENTITY_PATTERNS = Object.freeze({
|
|
|
23
23
|
});
|
|
24
24
|
/** Every kind `extractEntities` understands, for schema + error messages. */
|
|
25
25
|
export const ENTITY_KINDS = Object.freeze(Object.keys(ENTITY_PATTERNS));
|
|
26
|
+
const LOCAL_PART = "[\\w.!#$%&'*+/=?^`{|}~-]";
|
|
27
|
+
const RUN_SCANS = Object.freeze({
|
|
28
|
+
email: {
|
|
29
|
+
candidate: new RegExp(LOCAL_PART, "g"),
|
|
30
|
+
sticky: new RegExp(ENTITY_PATTERNS["email"]?.source, "y"),
|
|
31
|
+
run: () => new RegExp(`${LOCAL_PART}+`, "y"),
|
|
32
|
+
},
|
|
33
|
+
money: {
|
|
34
|
+
// A currency symbol starts the first alternative, a digit at a word
|
|
35
|
+
// boundary the second.
|
|
36
|
+
candidate: /[$£€¥]|\b\d/g,
|
|
37
|
+
sticky: new RegExp(ENTITY_PATTERNS["money"]?.source, "y"),
|
|
38
|
+
// The first alternative cannot fail after its symbol and digit, so a
|
|
39
|
+
// failed symbol only skips itself; a failed digit skips its digit run.
|
|
40
|
+
run: (at) => (/\d/.test(at) ? /[\d,]+/y : null),
|
|
41
|
+
},
|
|
42
|
+
jwt: {
|
|
43
|
+
candidate: /\beyJ/g,
|
|
44
|
+
sticky: new RegExp(ENTITY_PATTERNS["jwt"]?.source, "y"),
|
|
45
|
+
run: () => /[A-Za-z0-9_-]+/y,
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
/** Every match of `kind` in `text`, in order: the global regex's matches, in linear time. */
|
|
49
|
+
function* scanRuns(text, scan) {
|
|
50
|
+
const candidate = new RegExp(scan.candidate.source, scan.candidate.flags);
|
|
51
|
+
const sticky = new RegExp(scan.sticky.source, scan.sticky.flags);
|
|
52
|
+
let pos = 0;
|
|
53
|
+
while (pos <= text.length) {
|
|
54
|
+
candidate.lastIndex = pos;
|
|
55
|
+
const c = candidate.exec(text);
|
|
56
|
+
if (c === null)
|
|
57
|
+
return;
|
|
58
|
+
const at = c.index;
|
|
59
|
+
sticky.lastIndex = at;
|
|
60
|
+
const m = sticky.exec(text);
|
|
61
|
+
if (m !== null && m[0].length > 0) {
|
|
62
|
+
yield m;
|
|
63
|
+
pos = at + m[0].length;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const run = scan.run(text.charAt(at));
|
|
67
|
+
let next = at + 1;
|
|
68
|
+
if (run !== null) {
|
|
69
|
+
run.lastIndex = at;
|
|
70
|
+
const r = run.exec(text);
|
|
71
|
+
if (r !== null)
|
|
72
|
+
next = Math.max(next, at + r[0].length);
|
|
73
|
+
}
|
|
74
|
+
pos = next;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
26
77
|
export function extractEntities(text, kinds, unique) {
|
|
27
78
|
const starts = lineStarts(text);
|
|
28
79
|
const out = {};
|
|
29
80
|
for (const kind of kinds) {
|
|
30
|
-
|
|
31
|
-
if (source === undefined)
|
|
81
|
+
if (!Object.hasOwn(ENTITY_PATTERNS, kind))
|
|
32
82
|
continue;
|
|
33
|
-
const
|
|
83
|
+
const source = ENTITY_PATTERNS[kind];
|
|
34
84
|
const hits = [];
|
|
35
85
|
const seen = new Set();
|
|
36
|
-
for (
|
|
37
|
-
const m = re.exec(text);
|
|
38
|
-
if (m === null)
|
|
39
|
-
break;
|
|
86
|
+
for (const m of matchesOf(text, kind, source)) {
|
|
40
87
|
const whole = m[0];
|
|
41
88
|
// Patterns with a leading-boundary group (hashtag, mention) report the
|
|
42
89
|
// capture, so the preceding space is not part of the value.
|
|
43
90
|
const value = (m[1] ?? whole);
|
|
44
91
|
const index = m.index + whole.indexOf(value);
|
|
45
|
-
if (whole.length === 0)
|
|
46
|
-
re.lastIndex += 1;
|
|
47
92
|
if (unique && seen.has(value))
|
|
48
93
|
continue;
|
|
49
94
|
seen.add(value);
|
|
@@ -54,3 +99,20 @@ export function extractEntities(text, kinds, unique) {
|
|
|
54
99
|
}
|
|
55
100
|
return out;
|
|
56
101
|
}
|
|
102
|
+
/** Every match of one kind's pattern, in order. */
|
|
103
|
+
export function* matchesOf(text, kind, source) {
|
|
104
|
+
const scan = Object.hasOwn(RUN_SCANS, kind) ? RUN_SCANS[kind] : undefined;
|
|
105
|
+
if (scan !== undefined) {
|
|
106
|
+
yield* scanRuns(text, scan);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const re = new RegExp(source.source, source.flags);
|
|
110
|
+
for (;;) {
|
|
111
|
+
const m = re.exec(text);
|
|
112
|
+
if (m === null)
|
|
113
|
+
return;
|
|
114
|
+
if (m[0].length === 0)
|
|
115
|
+
re.lastIndex += 1;
|
|
116
|
+
yield m;
|
|
117
|
+
}
|
|
118
|
+
}
|
package/dist/lib/markdown.d.ts
CHANGED
|
@@ -6,6 +6,24 @@ export type Heading = {
|
|
|
6
6
|
};
|
|
7
7
|
/** GitHub-style heading anchor: lowercase, drop punctuation, spaces to dashes. */
|
|
8
8
|
export declare function slugify(title: string): string;
|
|
9
|
+
/**
|
|
10
|
+
* One line read as an ATX heading (`## Title ##`), or null when it is not one.
|
|
11
|
+
*
|
|
12
|
+
* The opening `#` run must be followed by a space or a tab, as CommonMark
|
|
13
|
+
* says; a closing `#` run is dropped only when a space or tab precedes it
|
|
14
|
+
* (so `# C#` is titled `C#`, and `## Title ##` is titled `Title`). An empty
|
|
15
|
+
* title is not a heading.
|
|
16
|
+
*
|
|
17
|
+
* Written as one anchored, linear match plus a backward scan, because the
|
|
18
|
+
* obvious `/^(#{1,6})\s+(.+?)\s*#*\s*$/` is cubic: a heading with a few
|
|
19
|
+
* thousand spaces in it took seconds, and `\s+` let `#` on a line of its own
|
|
20
|
+
* swallow the paragraph under it as a heading. `@crewhaus/tool-verify` reads
|
|
21
|
+
* headings through this too, so the two cannot disagree about one.
|
|
22
|
+
*/
|
|
23
|
+
export declare function parseAtxHeading(line: string): {
|
|
24
|
+
depth: number;
|
|
25
|
+
title: string;
|
|
26
|
+
} | null;
|
|
9
27
|
/**
|
|
10
28
|
* Collect ATX headings, ignoring any inside a fenced code block — a
|
|
11
29
|
* `# comment` in a shell sample is not a section, and treating it as one
|
package/dist/lib/markdown.js
CHANGED
|
@@ -6,6 +6,38 @@ export function slugify(title) {
|
|
|
6
6
|
.trim()
|
|
7
7
|
.replace(/\s+/g, "-");
|
|
8
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* One line read as an ATX heading (`## Title ##`), or null when it is not one.
|
|
11
|
+
*
|
|
12
|
+
* The opening `#` run must be followed by a space or a tab, as CommonMark
|
|
13
|
+
* says; a closing `#` run is dropped only when a space or tab precedes it
|
|
14
|
+
* (so `# C#` is titled `C#`, and `## Title ##` is titled `Title`). An empty
|
|
15
|
+
* title is not a heading.
|
|
16
|
+
*
|
|
17
|
+
* Written as one anchored, linear match plus a backward scan, because the
|
|
18
|
+
* obvious `/^(#{1,6})\s+(.+?)\s*#*\s*$/` is cubic: a heading with a few
|
|
19
|
+
* thousand spaces in it took seconds, and `\s+` let `#` on a line of its own
|
|
20
|
+
* swallow the paragraph under it as a heading. `@crewhaus/tool-verify` reads
|
|
21
|
+
* headings through this too, so the two cannot disagree about one.
|
|
22
|
+
*/
|
|
23
|
+
export function parseAtxHeading(line) {
|
|
24
|
+
// `[\s\S]`, not `.`: a CRLF file's line still ends in `\r`, which `.` does
|
|
25
|
+
// not match and `trimEnd` below removes.
|
|
26
|
+
const m = /^(#{1,6})[ \t]+([\s\S]*)$/.exec(line);
|
|
27
|
+
if (m === null)
|
|
28
|
+
return null;
|
|
29
|
+
let title = m[2].trimEnd();
|
|
30
|
+
let k = title.length;
|
|
31
|
+
while (k > 0 && title.charCodeAt(k - 1) === 35 /* # */)
|
|
32
|
+
k--;
|
|
33
|
+
if (k < title.length && (k === 0 || title[k - 1] === " " || title[k - 1] === "\t")) {
|
|
34
|
+
title = title.slice(0, k).trimEnd();
|
|
35
|
+
}
|
|
36
|
+
title = title.trim();
|
|
37
|
+
if (title === "")
|
|
38
|
+
return null;
|
|
39
|
+
return { depth: m[1].length, title };
|
|
40
|
+
}
|
|
9
41
|
/**
|
|
10
42
|
* Collect ATX headings, ignoring any inside a fenced code block — a
|
|
11
43
|
* `# comment` in a shell sample is not a section, and treating it as one
|
|
@@ -32,11 +64,10 @@ export function parseHeadings(markdown) {
|
|
|
32
64
|
}
|
|
33
65
|
if (inFence)
|
|
34
66
|
continue;
|
|
35
|
-
const
|
|
36
|
-
if (
|
|
67
|
+
const heading = parseAtxHeading(line);
|
|
68
|
+
if (heading === null)
|
|
37
69
|
continue;
|
|
38
|
-
|
|
39
|
-
out.push({ depth: m[1].length, title, line: i + 1, slug: slugify(title) });
|
|
70
|
+
out.push({ ...heading, line: i + 1, slug: slugify(heading.title) });
|
|
40
71
|
}
|
|
41
72
|
return out;
|
|
42
73
|
}
|