@chantier/tools 0.3.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/CHANGELOG.md +13 -0
- package/LICENSE +190 -0
- package/README.md +12 -0
- package/dist/index.d.mts +48 -0
- package/dist/index.mjs +708 -0
- package/package.json +46 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes are documented in the root
|
|
4
|
+
[CHANGELOG.md](../../CHANGELOG.md).
|
|
5
|
+
|
|
6
|
+
## 0.3.0 — 2026-09-16
|
|
7
|
+
|
|
8
|
+
- grep: output modes and pagination, plus guidance in the no-match case.
|
|
9
|
+
- read: continuation notices when output is truncated.
|
|
10
|
+
- bash: output spills to a file past the size cap; working-directory control.
|
|
11
|
+
- edit: CRLF handling and a diff channel for reviewing changes.
|
|
12
|
+
|
|
13
|
+
See the root changelog for the full list.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
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
|
+
4. (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
|
+
Copyright 2026 DASHLEA × MLC
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# @chantier/tools
|
|
2
|
+
|
|
3
|
+
The seven built-in tools of the [chantier](https://github.com/mlcassociation/chantier)
|
|
4
|
+
coding agent: bash, edit, glob, grep, read, webfetch, and write. Each returns
|
|
5
|
+
model-facing prose (not stack traces) and never executes a mutation without an
|
|
6
|
+
allow decision from the permission engine.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { buildTools } from "@chantier/tools";
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
License: Apache-2.0.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { ToolDefinition } from "@chantier/core";
|
|
2
|
+
//#region src/bash.d.ts
|
|
3
|
+
export declare const bashTool: ToolDefinition;
|
|
4
|
+
//#endregion
|
|
5
|
+
//#region src/edit.d.ts
|
|
6
|
+
export declare const editTool: ToolDefinition;
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/glob.d.ts
|
|
9
|
+
export declare const globTool: ToolDefinition;
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region src/grep.d.ts
|
|
12
|
+
export declare const grepTool: ToolDefinition;
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/read.d.ts
|
|
15
|
+
export declare const readTool: ToolDefinition;
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/webfetch.d.ts
|
|
18
|
+
export declare const webfetchTool: ToolDefinition;
|
|
19
|
+
/** Naive HTML → text: drop script/style blocks, strip tags, decode common entities. */
|
|
20
|
+
export declare function htmlToText(html: string): string;
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/write.d.ts
|
|
23
|
+
export declare const writeTool: ToolDefinition;
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/common.d.ts
|
|
26
|
+
/** Model-facing tool output is capped at this many chars, with a visible note. */
|
|
27
|
+
export declare const MAX_TOOL_OUTPUT_CHARS = 40000;
|
|
28
|
+
export declare function truncateOutput(text: string, maxChars?: number): string;
|
|
29
|
+
/**
|
|
30
|
+
* Deny-first read protection, enforced inside the file tools (defense in depth,
|
|
31
|
+
* independent of permission rules): .env, .env.*, *.pem, id_rsa*, ~/.ssh/**.
|
|
32
|
+
*/
|
|
33
|
+
export declare function isDenyReadPath(resolvedPath: string): boolean;
|
|
34
|
+
export declare function denyReadMessage(resolvedPath: string): string;
|
|
35
|
+
/**
|
|
36
|
+
* Resolves a tool input path against the project cwd. Absolute paths are allowed
|
|
37
|
+
* as-is (user-specified); relative paths resolve inside cwd.
|
|
38
|
+
*/
|
|
39
|
+
export declare function resolveInCwd(cwd: string, inputPath: string): string;
|
|
40
|
+
/** Formats file text with 1-indexed line numbers, optionally windowed. */
|
|
41
|
+
export declare function formatNumbered(text: string, offset?: number, limit?: number): string;
|
|
42
|
+
/** Parses a tool input field as a string, with a model-facing prose error. */
|
|
43
|
+
export declare function requireString(input: Record<string, unknown>, field: string): string | undefined;
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region src/index.d.ts
|
|
46
|
+
/** The seven v0.1 built-in tools. */
|
|
47
|
+
export declare function buildTools(): ToolDefinition[];
|
|
48
|
+
//#endregion
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,708 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { createTwoFilesPatch } from "diff";
|
|
7
|
+
import { glob } from "tinyglobby";
|
|
8
|
+
//#region src/common.ts
|
|
9
|
+
/** Model-facing tool output is capped at this many chars, with a visible note. */
|
|
10
|
+
const MAX_TOOL_OUTPUT_CHARS = 4e4;
|
|
11
|
+
function truncateOutput(text, maxChars = MAX_TOOL_OUTPUT_CHARS) {
|
|
12
|
+
if (text.length <= maxChars) return text;
|
|
13
|
+
return `${text.slice(0, maxChars)}\n[truncated: showing first ${maxChars} of ${text.length} chars]`;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Deny-first read protection, enforced inside the file tools (defense in depth,
|
|
17
|
+
* independent of permission rules): .env, .env.*, *.pem, id_rsa*, ~/.ssh/**.
|
|
18
|
+
*/
|
|
19
|
+
function isDenyReadPath(resolvedPath) {
|
|
20
|
+
const base = path.basename(resolvedPath);
|
|
21
|
+
if (base === ".env" || base.startsWith(".env.")) return true;
|
|
22
|
+
if (base.endsWith(".pem")) return true;
|
|
23
|
+
if (base.startsWith("id_rsa")) return true;
|
|
24
|
+
const home = homedir();
|
|
25
|
+
if ((resolvedPath.startsWith("~") ? path.join(home, resolvedPath.slice(1)) : resolvedPath).split(path.sep).includes(".ssh")) return true;
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
function denyReadMessage(resolvedPath) {
|
|
29
|
+
return `Error: ${resolvedPath} is protected (deny-read list: .env, .env.*, *.pem, id_rsa*, ~/.ssh/**). This path cannot be read, listed, or searched.`;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Resolves a tool input path against the project cwd. Absolute paths are allowed
|
|
33
|
+
* as-is (user-specified); relative paths resolve inside cwd.
|
|
34
|
+
*/
|
|
35
|
+
function resolveInCwd(cwd, inputPath) {
|
|
36
|
+
return path.isAbsolute(inputPath) ? path.normalize(inputPath) : path.normalize(path.join(cwd, inputPath));
|
|
37
|
+
}
|
|
38
|
+
/** Formats file text with 1-indexed line numbers, optionally windowed. */
|
|
39
|
+
function formatNumbered(text, offset = 1, limit) {
|
|
40
|
+
const lines = text.split("\n");
|
|
41
|
+
const start = Math.max(1, offset);
|
|
42
|
+
const end = limit === void 0 ? lines.length : Math.min(lines.length, start - 1 + limit);
|
|
43
|
+
const window = lines.slice(start - 1, end);
|
|
44
|
+
const width = String(end).length;
|
|
45
|
+
return window.map((line, i) => `${String(start + i).padStart(width)}: ${line}`).join("\n");
|
|
46
|
+
}
|
|
47
|
+
/** Parses a tool input field as a string, with a model-facing prose error. */
|
|
48
|
+
function requireString(input, field) {
|
|
49
|
+
const value = input[field];
|
|
50
|
+
if (typeof value === "string") return value;
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/bash.ts
|
|
54
|
+
const DEFAULT_TIMEOUT_MS = 12e4;
|
|
55
|
+
/** Captured output beyond which the full buffer is spilled to a file instead of being truncated away. */
|
|
56
|
+
const SPILL_THRESHOLD = 14e4;
|
|
57
|
+
/** Tail length kept in the tool result when a spill happens. */
|
|
58
|
+
const SPILL_TAIL_CHARS = 1e4;
|
|
59
|
+
/**
|
|
60
|
+
* Absolute last resort: the command is killed once in-memory accumulation passes
|
|
61
|
+
* this (a runaway producer that even a spill file cannot serve within reason).
|
|
62
|
+
*/
|
|
63
|
+
const HARD_CAP_CHARS = 10485760;
|
|
64
|
+
const bashTool = {
|
|
65
|
+
name: "bash",
|
|
66
|
+
description: "Run a shell command under /bin/sh. stdout and stderr are captured and the exit code is reported. Pass `workdir` to run the command in another directory (resolved relative to the project cwd; it must already exist). Commands are killed after the timeout (default 120 s). When output exceeds the tool cap, the full output is saved to a file under <cwd>/.chantier/spill/ and only the last ~10k characters are returned with a header naming the spill file.",
|
|
67
|
+
inputSchema: {
|
|
68
|
+
type: "object",
|
|
69
|
+
properties: {
|
|
70
|
+
command: {
|
|
71
|
+
type: "string",
|
|
72
|
+
description: "Shell command to run"
|
|
73
|
+
},
|
|
74
|
+
workdir: {
|
|
75
|
+
type: "string",
|
|
76
|
+
description: "Directory to run the command in, relative to the project cwd (must exist; default: project cwd)"
|
|
77
|
+
},
|
|
78
|
+
timeoutMs: {
|
|
79
|
+
type: "number",
|
|
80
|
+
description: "Kill the command after this many milliseconds (default 120000)"
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
required: ["command"]
|
|
84
|
+
},
|
|
85
|
+
readOnly: false,
|
|
86
|
+
specifier: (input) => typeof input.command === "string" ? input.command : void 0,
|
|
87
|
+
handler: async (input, ctx) => {
|
|
88
|
+
const command = typeof input.command === "string" ? input.command : void 0;
|
|
89
|
+
if (command === void 0 || command.length === 0) return "Error: the `command` argument is required and must be a non-empty string.";
|
|
90
|
+
let runCwd = ctx.cwd;
|
|
91
|
+
const workdirInput = typeof input.workdir === "string" ? input.workdir : void 0;
|
|
92
|
+
if (workdirInput !== void 0) {
|
|
93
|
+
const resolvedWorkdir = resolveInCwd(ctx.cwd, workdirInput);
|
|
94
|
+
const info = await stat(resolvedWorkdir).catch(() => null);
|
|
95
|
+
if (info === null) return `Error: workdir ${resolvedWorkdir} does not exist. Create it first (e.g. bash: mkdir -p ${workdirInput}) or pass a directory that exists under ${ctx.cwd}.`;
|
|
96
|
+
if (!info.isDirectory()) return `Error: workdir ${resolvedWorkdir} is not a directory. Pass a directory path.`;
|
|
97
|
+
runCwd = resolvedWorkdir;
|
|
98
|
+
}
|
|
99
|
+
const timeoutMs = typeof input.timeoutMs === "number" && input.timeoutMs > 0 ? Math.floor(input.timeoutMs) : DEFAULT_TIMEOUT_MS;
|
|
100
|
+
return truncateOutput(await runShell(command, runCwd, timeoutMs, ctx.signal));
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
function runShell(command, cwd, timeoutMs, signal) {
|
|
104
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
105
|
+
const child = spawn("/bin/sh", ["-c", command], {
|
|
106
|
+
cwd,
|
|
107
|
+
signal,
|
|
108
|
+
stdio: [
|
|
109
|
+
"ignore",
|
|
110
|
+
"pipe",
|
|
111
|
+
"pipe"
|
|
112
|
+
],
|
|
113
|
+
detached: true
|
|
114
|
+
});
|
|
115
|
+
let stdout = "";
|
|
116
|
+
let stderr = "";
|
|
117
|
+
let hardCapped = false;
|
|
118
|
+
child.stdout.setEncoding("utf8");
|
|
119
|
+
child.stderr.setEncoding("utf8");
|
|
120
|
+
child.stdout.on("data", (chunk) => {
|
|
121
|
+
stdout += chunk;
|
|
122
|
+
});
|
|
123
|
+
child.stderr.on("data", (chunk) => {
|
|
124
|
+
stderr += chunk;
|
|
125
|
+
});
|
|
126
|
+
const killTree = () => {
|
|
127
|
+
try {
|
|
128
|
+
if (child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
|
|
129
|
+
else child.kill("SIGKILL");
|
|
130
|
+
} catch {
|
|
131
|
+
child.kill("SIGKILL");
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
const hardCapTimer = setInterval(() => {
|
|
135
|
+
if (stdout.length + stderr.length > HARD_CAP_CHARS) {
|
|
136
|
+
hardCapped = true;
|
|
137
|
+
killTree();
|
|
138
|
+
}
|
|
139
|
+
}, 250);
|
|
140
|
+
const timer = setTimeout(killTree, timeoutMs);
|
|
141
|
+
const finish = (result) => {
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
clearInterval(hardCapTimer);
|
|
144
|
+
resolve(result);
|
|
145
|
+
};
|
|
146
|
+
child.on("error", (error) => {
|
|
147
|
+
finish(`\nError: failed to spawn shell: ${error.message}`);
|
|
148
|
+
});
|
|
149
|
+
child.on("close", (code, signalKilled) => {
|
|
150
|
+
finalize(code, signalKilled);
|
|
151
|
+
});
|
|
152
|
+
const finalize = async (code, signalKilled) => {
|
|
153
|
+
const combined = `${stdout}${stderr.length > 0 ? (stdout.length > 0 ? "\n--- stderr ---\n" : "") + stderr : ""}`;
|
|
154
|
+
let body = combined;
|
|
155
|
+
if (combined.length > SPILL_THRESHOLD) body = await spilledBody(combined, cwd, command, hardCapped);
|
|
156
|
+
finish(`${body}${exitTail(code, signalKilled, timeoutMs)}`);
|
|
157
|
+
};
|
|
158
|
+
return promise;
|
|
159
|
+
}
|
|
160
|
+
/** Header + tail for an over-cap run; undefined spillPath falls back to a truncated body. */
|
|
161
|
+
async function spilledBody(combined, cwd, command, hardCapped) {
|
|
162
|
+
const spillPath = await writeSpillFile(combined, cwd, command);
|
|
163
|
+
if (spillPath === void 0) return `[output exceeded cap (${combined.length} chars) and the spill file could not be written]\n${combined.slice(0, MAX_TOOL_OUTPUT_CHARS)}`;
|
|
164
|
+
const tail = combined.slice(Math.max(0, combined.length - SPILL_TAIL_CHARS));
|
|
165
|
+
return `${hardCapped ? `[command killed: accumulated output passed the 10 MB in-memory cap]\n` : ""}[output exceeded cap \u2014 full output (${combined.length} chars) saved to ${spillPath}]\n${tail}`;
|
|
166
|
+
}
|
|
167
|
+
/** Writes the full captured output to <cwd>/.chantier/spill/<iso>-<sha8(command)>.txt. */
|
|
168
|
+
async function writeSpillFile(combined, cwd, command) {
|
|
169
|
+
try {
|
|
170
|
+
const spillDir = path.join(cwd, ".chantier", "spill");
|
|
171
|
+
await mkdir(spillDir, { recursive: true });
|
|
172
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
173
|
+
const hash = createHash("sha256").update(command).digest("hex").slice(0, 8);
|
|
174
|
+
const spillPath = path.join(spillDir, `${stamp}-${hash}.txt`);
|
|
175
|
+
await writeFile(spillPath, combined, "utf8");
|
|
176
|
+
return spillPath;
|
|
177
|
+
} catch {
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function exitTail(code, signalKilled, timeoutMs) {
|
|
182
|
+
if (signalKilled !== null && (signalKilled === "SIGKILL" || signalKilled === "SIGTERM")) return `\nCommand killed (signal ${signalKilled}) after ${timeoutMs} ms.`;
|
|
183
|
+
return `\nExit code: ${code === null ? `signal ${String(signalKilled)}` : `${code}${code === 1 ? ` (exit 1 \u2014 commonly means "no results" for grep/rg/diff/test; not necessarily an error)` : ""}`}`;
|
|
184
|
+
}
|
|
185
|
+
//#endregion
|
|
186
|
+
//#region src/edit.ts
|
|
187
|
+
function countOccurrences(haystack, needle) {
|
|
188
|
+
if (needle.length === 0) return 0;
|
|
189
|
+
let count = 0;
|
|
190
|
+
let index = haystack.indexOf(needle);
|
|
191
|
+
while (index !== -1) {
|
|
192
|
+
count += 1;
|
|
193
|
+
index = haystack.indexOf(needle, index + 1);
|
|
194
|
+
}
|
|
195
|
+
return count;
|
|
196
|
+
}
|
|
197
|
+
/** Dominant line ending of a file; ties and pure-LF files are treated as LF. */
|
|
198
|
+
function dominantEol(text) {
|
|
199
|
+
const crlf = countOccurrences(text, "\r\n");
|
|
200
|
+
return crlf > countOccurrences(text, "\n") - crlf ? "\r\n" : "\n";
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Applies oldString → newString on `original`. When the file is CRLF-dominant and
|
|
204
|
+
* the exact match misses, oldString's `\n` are retried as `\r\n` (models write LF);
|
|
205
|
+
* the replacement text is normalized to the file's dominant ending either way.
|
|
206
|
+
*/
|
|
207
|
+
function planEdit(original, oldString, newString, replaceAll) {
|
|
208
|
+
const crlfFile = dominantEol(original) === "\r\n";
|
|
209
|
+
let target = oldString;
|
|
210
|
+
let crlfRetry = false;
|
|
211
|
+
let matches = countOccurrences(original, oldString);
|
|
212
|
+
if (matches === 0 && crlfFile && oldString.includes("\n")) {
|
|
213
|
+
const crlfOld = oldString.replace(/\r?\n/g, "\r\n");
|
|
214
|
+
const crlfMatches = countOccurrences(original, crlfOld);
|
|
215
|
+
if (crlfMatches > 0) {
|
|
216
|
+
target = crlfOld;
|
|
217
|
+
crlfRetry = true;
|
|
218
|
+
matches = crlfMatches;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (matches === 0) {
|
|
222
|
+
const snippet = oldString.length > 200 ? `${oldString.slice(0, 200)}\u2026` : oldString;
|
|
223
|
+
return {
|
|
224
|
+
ok: false,
|
|
225
|
+
kind: "not-found",
|
|
226
|
+
error: `The match is exact (whitespace and indentation included). Read the file around your target and copy the text verbatim. You sent:\n${JSON.stringify(snippet)}`
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
if (matches > 1 && !replaceAll) return {
|
|
230
|
+
ok: false,
|
|
231
|
+
kind: "ambiguous",
|
|
232
|
+
count: matches,
|
|
233
|
+
error: "Include more surrounding context to make it unique, or pass `replaceAll: true` if every occurrence should change."
|
|
234
|
+
};
|
|
235
|
+
const normalizedNew = crlfFile ? newString.replace(/\r?\n/g, "\r\n") : newString.replace(/\r\n/g, "\n");
|
|
236
|
+
return {
|
|
237
|
+
ok: true,
|
|
238
|
+
updated: replaceAll === true ? original.split(target).join(normalizedNew) : original.replace(target, normalizedNew),
|
|
239
|
+
matchCount: matches,
|
|
240
|
+
crlfFile,
|
|
241
|
+
crlfRetry
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
/** Unified diff (a/<rel> → b/<rel>) of the planned edit, for the approval card. */
|
|
245
|
+
async function editAskDetail(input, ctx) {
|
|
246
|
+
const raw = requireString(input, "path");
|
|
247
|
+
const oldString = requireString(input, "oldString");
|
|
248
|
+
const newString = requireString(input, "newString");
|
|
249
|
+
if (raw === void 0 || oldString === void 0 || oldString.length === 0 || newString === void 0) return void 0;
|
|
250
|
+
const resolved = resolveInCwd(ctx.cwd, raw);
|
|
251
|
+
const original = await readFile(resolved, "utf8").catch(() => void 0);
|
|
252
|
+
if (original === void 0) return void 0;
|
|
253
|
+
const plan = planEdit(original, oldString, newString, input.replaceAll === true);
|
|
254
|
+
if (!plan.ok) return void 0;
|
|
255
|
+
const rel = path.relative(ctx.cwd, resolved);
|
|
256
|
+
return { diff: createTwoFilesPatch(`a/${rel}`, `b/${rel}`, original, plan.updated, void 0, void 0, { context: 3 }) };
|
|
257
|
+
}
|
|
258
|
+
const editTool = {
|
|
259
|
+
name: "edit",
|
|
260
|
+
description: "Replace an exact unique string in a file with new text. The oldString must match exactly once; if it is ambiguous, include more surrounding context or pass replaceAll: true. Read the file first. CRLF files keep their line endings: if your oldString uses \\n and misses, the tool retries it as \\r\\n.",
|
|
261
|
+
inputSchema: {
|
|
262
|
+
type: "object",
|
|
263
|
+
properties: {
|
|
264
|
+
path: {
|
|
265
|
+
type: "string",
|
|
266
|
+
description: "File path, relative to the project cwd"
|
|
267
|
+
},
|
|
268
|
+
oldString: {
|
|
269
|
+
type: "string",
|
|
270
|
+
description: "Exact text to replace (must be unique unless replaceAll)"
|
|
271
|
+
},
|
|
272
|
+
newString: {
|
|
273
|
+
type: "string",
|
|
274
|
+
description: "Replacement text"
|
|
275
|
+
},
|
|
276
|
+
replaceAll: {
|
|
277
|
+
type: "boolean",
|
|
278
|
+
description: "Replace every occurrence instead of requiring uniqueness"
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
required: [
|
|
282
|
+
"path",
|
|
283
|
+
"oldString",
|
|
284
|
+
"newString"
|
|
285
|
+
]
|
|
286
|
+
},
|
|
287
|
+
readOnly: false,
|
|
288
|
+
specifier: (input) => requireString(input, "path"),
|
|
289
|
+
askDetail: editAskDetail,
|
|
290
|
+
handler: async (input, ctx) => {
|
|
291
|
+
const raw = requireString(input, "path");
|
|
292
|
+
const oldString = requireString(input, "oldString");
|
|
293
|
+
const newString = requireString(input, "newString");
|
|
294
|
+
if (raw === void 0) return "Error: the `path` argument is required and must be a string.";
|
|
295
|
+
if (oldString === void 0 || oldString.length === 0) return "Error: the `oldString` argument is required, must be a string, and must not be empty.";
|
|
296
|
+
if (newString === void 0) return "Error: the `newString` argument is required and must be a string.";
|
|
297
|
+
const resolved = resolveInCwd(ctx.cwd, raw);
|
|
298
|
+
const existing = await stat(resolved).catch(() => null);
|
|
299
|
+
if (existing === null || !existing.isFile()) return `Error: no file at ${resolved}. Use the read tool first to confirm the exact path.`;
|
|
300
|
+
const plan = planEdit(await readFile(resolved, "utf8"), oldString, newString, input.replaceAll === true);
|
|
301
|
+
if (!plan.ok) return plan.kind === "not-found" ? `Error: oldString not found in ${resolved}. ${plan.error}` : `Error: oldString appears ${plan.count} times in ${resolved}. ${plan.error}`;
|
|
302
|
+
await writeFile(resolved, plan.updated, "utf8");
|
|
303
|
+
const changed = input.replaceAll === true ? `${plan.matchCount} occurrence(s)` : "1 occurrence";
|
|
304
|
+
const eolNote = plan.crlfFile ? plan.crlfRetry ? " (CRLF line endings preserved; oldString matched after an LF→CRLF retry)" : " (CRLF line endings preserved)" : "";
|
|
305
|
+
return truncateOutput(`Edited ${resolved}: replaced ${changed} (${oldString.length} → ${newString.length} chars)${eolNote}.`);
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
//#endregion
|
|
309
|
+
//#region src/glob.ts
|
|
310
|
+
const globTool = {
|
|
311
|
+
name: "glob",
|
|
312
|
+
description: "Find files matching a glob pattern (e.g. `src/**/*.ts`). Results are sorted lexicographically.",
|
|
313
|
+
inputSchema: {
|
|
314
|
+
type: "object",
|
|
315
|
+
properties: { pattern: {
|
|
316
|
+
type: "string",
|
|
317
|
+
description: "Glob pattern, relative to the project cwd"
|
|
318
|
+
} },
|
|
319
|
+
required: ["pattern"]
|
|
320
|
+
},
|
|
321
|
+
readOnly: true,
|
|
322
|
+
specifier: (input) => typeof input.pattern === "string" ? input.pattern : void 0,
|
|
323
|
+
handler: async (input, ctx) => {
|
|
324
|
+
const pattern = typeof input.pattern === "string" ? input.pattern : void 0;
|
|
325
|
+
if (pattern === void 0 || pattern.length === 0) return "Error: the `pattern` argument is required and must be a non-empty glob string.";
|
|
326
|
+
const rgResult = await tryRgFiles(pattern, ctx.cwd);
|
|
327
|
+
if (rgResult !== null) {
|
|
328
|
+
if (rgResult === "") return "No files match this pattern.";
|
|
329
|
+
return truncateOutput(rgResult.split("\n").sort((a, b) => a.localeCompare(b)).join("\n"));
|
|
330
|
+
}
|
|
331
|
+
const files = await glob({
|
|
332
|
+
patterns: [pattern],
|
|
333
|
+
cwd: ctx.cwd,
|
|
334
|
+
dot: true
|
|
335
|
+
});
|
|
336
|
+
if (files.length === 0) return "No files match this pattern.";
|
|
337
|
+
return truncateOutput(files.sort((a, b) => a.localeCompare(b)).join("\n"));
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
/** `rg --files -g` when ripgrep is installed; null = unavailable (fallback needed). */
|
|
341
|
+
async function tryRgFiles(pattern, cwd) {
|
|
342
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
343
|
+
const child = spawn("rg", [
|
|
344
|
+
"--files",
|
|
345
|
+
"--hidden",
|
|
346
|
+
"--no-messages",
|
|
347
|
+
"-g",
|
|
348
|
+
pattern
|
|
349
|
+
], { cwd });
|
|
350
|
+
let stdout = "";
|
|
351
|
+
child.stdout.setEncoding("utf8");
|
|
352
|
+
child.stdout.on("data", (chunk) => {
|
|
353
|
+
stdout += chunk;
|
|
354
|
+
});
|
|
355
|
+
child.on("error", () => resolve(null));
|
|
356
|
+
child.on("close", (code) => {
|
|
357
|
+
if (code === null || code !== 0 && code !== 1) resolve(null);
|
|
358
|
+
else resolve(stdout.trimEnd());
|
|
359
|
+
});
|
|
360
|
+
return promise;
|
|
361
|
+
}
|
|
362
|
+
//#endregion
|
|
363
|
+
//#region src/grep.ts
|
|
364
|
+
const MAX_LINES = 100;
|
|
365
|
+
const MAX_MATCHES_PER_FILE = 50;
|
|
366
|
+
const grepTool = {
|
|
367
|
+
name: "grep",
|
|
368
|
+
description: "Search file contents with a regular expression (case-sensitive, matches anywhere in a line). Mode `content` (default) returns `file:line:text` lines; mode `files_with_matches` returns only matching file paths. Results are capped at 100 entries unless `head_limit` is given (max per file: 50). Use `offset` + `head_limit` to page through large result sets. Pass `path` to search a subtree and `glob` to filter files (e.g. `*.ts`). Protected paths are skipped. When nothing matches, the tool suggests how to widen the search.",
|
|
369
|
+
inputSchema: {
|
|
370
|
+
type: "object",
|
|
371
|
+
properties: {
|
|
372
|
+
pattern: {
|
|
373
|
+
type: "string",
|
|
374
|
+
description: "Regular expression to search for"
|
|
375
|
+
},
|
|
376
|
+
path: {
|
|
377
|
+
type: "string",
|
|
378
|
+
description: "Directory or file to search (default: project cwd)"
|
|
379
|
+
},
|
|
380
|
+
glob: {
|
|
381
|
+
type: "string",
|
|
382
|
+
description: "File glob filter, e.g. `*.ts`"
|
|
383
|
+
},
|
|
384
|
+
mode: {
|
|
385
|
+
type: "string",
|
|
386
|
+
enum: ["content", "files_with_matches"],
|
|
387
|
+
description: "content: file:line:text lines (default). files_with_matches: matching file paths only"
|
|
388
|
+
},
|
|
389
|
+
head_limit: {
|
|
390
|
+
type: "number",
|
|
391
|
+
description: "Maximum number of entries (lines or files) to return (default 100)"
|
|
392
|
+
},
|
|
393
|
+
offset: {
|
|
394
|
+
type: "number",
|
|
395
|
+
description: "Skip the first N entries before applying head_limit"
|
|
396
|
+
}
|
|
397
|
+
},
|
|
398
|
+
required: ["pattern"]
|
|
399
|
+
},
|
|
400
|
+
readOnly: true,
|
|
401
|
+
specifier: (input) => typeof input.pattern === "string" ? input.pattern : void 0,
|
|
402
|
+
handler: async (input, ctx) => {
|
|
403
|
+
const pattern = typeof input.pattern === "string" ? input.pattern : void 0;
|
|
404
|
+
if (pattern === void 0 || pattern.length === 0) return "Error: the `pattern` argument is required and must be a non-empty regular expression.";
|
|
405
|
+
let regex;
|
|
406
|
+
try {
|
|
407
|
+
regex = new RegExp(pattern);
|
|
408
|
+
} catch (error) {
|
|
409
|
+
return `Error: invalid regular expression: ${error.message}`;
|
|
410
|
+
}
|
|
411
|
+
const modeInput = typeof input.mode === "string" ? input.mode : void 0;
|
|
412
|
+
if (modeInput !== void 0 && modeInput !== "content" && modeInput !== "files_with_matches") return "Error: mode must be \"content\" or \"files_with_matches\".";
|
|
413
|
+
const mode = modeInput === "files_with_matches" ? "files_with_matches" : "content";
|
|
414
|
+
const headLimit = typeof input.head_limit === "number" ? Math.floor(input.head_limit) : MAX_LINES;
|
|
415
|
+
if (headLimit <= 0) return "Error: head_limit must be a positive integer.";
|
|
416
|
+
const offset = typeof input.offset === "number" ? Math.floor(input.offset) : 0;
|
|
417
|
+
if (offset < 0) return "Error: offset must be a non-negative integer.";
|
|
418
|
+
const searchPath = typeof input.path === "string" ? input.path : ".";
|
|
419
|
+
const globFilter = typeof input.glob === "string" ? input.glob : void 0;
|
|
420
|
+
const entries = await tryRg(pattern, ctx.cwd, searchPath, globFilter, mode) ?? await jsFallback(regex, ctx.cwd, searchPath, globFilter, mode);
|
|
421
|
+
if (entries.length === 0) return noMatchesMessage(pattern);
|
|
422
|
+
return pageResults(entries, offset, headLimit);
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
/** Corrective prose for an empty result set; shared by the rg fast path and the JS fallback. */
|
|
426
|
+
function noMatchesMessage(pattern) {
|
|
427
|
+
return `No matches for ${JSON.stringify(pattern)}. The regex is case-sensitive and matches anywhere in a line. Try a simpler pattern, check spelling and escaping (regex metacharacters like \`.\` and \`(\` need backslashes), broaden the \`glob\` filter or drop it, or widen \`path\` to the whole project.`;
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Applies offset/head_limit pagination to an ordered result list and renders the page.
|
|
431
|
+
* Appends a continuation notice when entries remain beyond the window.
|
|
432
|
+
*/
|
|
433
|
+
function pageResults(entries, offset, headLimit) {
|
|
434
|
+
if (offset >= entries.length) {
|
|
435
|
+
const plural = entries.length === 1 ? "entry" : "entries";
|
|
436
|
+
return `Error: offset ${offset} is past the end (${entries.length} ${plural} total). Re-run with a smaller offset.`;
|
|
437
|
+
}
|
|
438
|
+
const page = entries.slice(offset, offset + headLimit);
|
|
439
|
+
const end = offset + page.length;
|
|
440
|
+
const body = page.join("\n");
|
|
441
|
+
if (end < entries.length) return truncateOutput(`${body}\n[${entries.length} entries total; showing ${offset + 1}\u2013${end}; re-run with offset=${end} for the next page]`);
|
|
442
|
+
return truncateOutput(body);
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Ripgrep fast path. Returns the raw entry lines (content mode: `file:line:text`,
|
|
446
|
+
* files mode: file paths), or null when rg is unavailable or errored (caller
|
|
447
|
+
* falls back to the JS walker). No-match (exit 1) is an empty list, not null.
|
|
448
|
+
*/
|
|
449
|
+
async function tryRg(pattern, cwd, searchPath, globFilter, mode) {
|
|
450
|
+
const { promise, resolve } = Promise.withResolvers();
|
|
451
|
+
const globArgs = globFilter === void 0 ? [] : ["--glob", globFilter];
|
|
452
|
+
const args = [
|
|
453
|
+
...mode === "content" ? [
|
|
454
|
+
"-n",
|
|
455
|
+
"--max-count",
|
|
456
|
+
String(MAX_MATCHES_PER_FILE)
|
|
457
|
+
] : ["-l"],
|
|
458
|
+
"--hidden",
|
|
459
|
+
"--no-messages",
|
|
460
|
+
...globArgs,
|
|
461
|
+
pattern,
|
|
462
|
+
searchPath
|
|
463
|
+
];
|
|
464
|
+
const child = spawn("rg", args, { cwd });
|
|
465
|
+
let stdout = "";
|
|
466
|
+
child.stdout.setEncoding("utf8");
|
|
467
|
+
child.stdout.on("data", (chunk) => {
|
|
468
|
+
stdout += chunk;
|
|
469
|
+
});
|
|
470
|
+
child.on("error", () => resolve(null));
|
|
471
|
+
child.on("close", (code) => {
|
|
472
|
+
if (code === null || code !== 0 && code !== 1) {
|
|
473
|
+
resolve(null);
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
const kept = stdout.split("\n").filter((line) => line.length > 0).filter((line) => {
|
|
477
|
+
const file = mode === "content" ? line.split(":")[0] ?? "" : line;
|
|
478
|
+
return file.length === 0 || !isDenyReadPath(path.resolve(cwd, file));
|
|
479
|
+
});
|
|
480
|
+
resolve(kept);
|
|
481
|
+
});
|
|
482
|
+
return promise;
|
|
483
|
+
}
|
|
484
|
+
/** Line-walk fallback when rg is unavailable; protected paths are skipped. */
|
|
485
|
+
async function jsFallback(regex, cwd, searchPath, globFilter, mode) {
|
|
486
|
+
const base = path.resolve(cwd, searchPath);
|
|
487
|
+
const patterns = globFilter === void 0 ? ["**/*"] : [`**/${globFilter}`, globFilter];
|
|
488
|
+
const files = await glob({
|
|
489
|
+
patterns,
|
|
490
|
+
cwd: base,
|
|
491
|
+
dot: true,
|
|
492
|
+
deep: 10
|
|
493
|
+
});
|
|
494
|
+
const entries = [];
|
|
495
|
+
for (const file of files.slice().sort((a, b) => a.localeCompare(b))) {
|
|
496
|
+
const absolute = path.join(base, file);
|
|
497
|
+
if (isDenyReadPath(absolute)) continue;
|
|
498
|
+
const content = await readFile(absolute, "utf8").catch(() => null);
|
|
499
|
+
if (content === null) continue;
|
|
500
|
+
const display = searchPath === "." ? file : path.join(searchPath, file);
|
|
501
|
+
const fileLines = content.split("\n");
|
|
502
|
+
if (mode === "files_with_matches") {
|
|
503
|
+
if (fileLines.some((line) => regex.test(line))) entries.push(display);
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
let shown = 0;
|
|
507
|
+
for (let i = 0; i < fileLines.length && shown < MAX_MATCHES_PER_FILE; i++) if (regex.test(fileLines[i] ?? "")) {
|
|
508
|
+
entries.push(`${display}:${i + 1}:${fileLines[i]}`);
|
|
509
|
+
shown += 1;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return entries;
|
|
513
|
+
}
|
|
514
|
+
//#endregion
|
|
515
|
+
//#region src/read.ts
|
|
516
|
+
const DEFAULT_LINE_LIMIT = 2e3;
|
|
517
|
+
const readTool = {
|
|
518
|
+
name: "read",
|
|
519
|
+
description: "Read a file as numbered text (1-indexed). With offset/limit you can window large files; when output is cut short the result ends with a continuation notice naming the offset to resume from. Passing a directory path lists its entries (depth 1). Protected paths (.env*, *.pem, id_rsa*, ~/.ssh) are refused.",
|
|
520
|
+
inputSchema: {
|
|
521
|
+
type: "object",
|
|
522
|
+
properties: {
|
|
523
|
+
path: {
|
|
524
|
+
type: "string",
|
|
525
|
+
description: "File or directory path, relative to the project cwd"
|
|
526
|
+
},
|
|
527
|
+
offset: {
|
|
528
|
+
type: "number",
|
|
529
|
+
description: "1-indexed first line to show"
|
|
530
|
+
},
|
|
531
|
+
limit: {
|
|
532
|
+
type: "number",
|
|
533
|
+
description: "Maximum number of lines to show"
|
|
534
|
+
}
|
|
535
|
+
},
|
|
536
|
+
required: ["path"]
|
|
537
|
+
},
|
|
538
|
+
readOnly: true,
|
|
539
|
+
specifier: (input) => requireString(input, "path"),
|
|
540
|
+
handler: async (input, ctx) => {
|
|
541
|
+
const raw = requireString(input, "path");
|
|
542
|
+
if (raw === void 0) return "Error: the `path` argument is required and must be a string.";
|
|
543
|
+
const resolved = resolveInCwd(ctx.cwd, raw);
|
|
544
|
+
if (isDenyReadPath(resolved)) return denyReadMessage(resolved);
|
|
545
|
+
const info = await stat(resolved).catch((error) => error);
|
|
546
|
+
if (info instanceof Error) {
|
|
547
|
+
if (info.code !== "ENOENT") return `Error: could not access ${resolved}: ${String(info.message)}`;
|
|
548
|
+
return missingFileMessage(resolved);
|
|
549
|
+
}
|
|
550
|
+
if (info.isDirectory()) return truncateOutput((await readdir(resolved, { withFileTypes: true })).map((entry) => entry.isDirectory() ? `${entry.name}/` : entry.name).sort((a, b) => a.localeCompare(b)).map((name) => name).join("\n"));
|
|
551
|
+
const offset = typeof input.offset === "number" ? Math.floor(input.offset) : 1;
|
|
552
|
+
const limit = typeof input.limit === "number" && input.limit > 0 ? Math.floor(input.limit) : DEFAULT_LINE_LIMIT;
|
|
553
|
+
return readFileWindow(await readFile(resolved, "utf8"), offset, limit);
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
/**
|
|
557
|
+
* Windows `text` into numbered lines and appends the continuation notice when the
|
|
558
|
+
* window (line limit or the char cap) cuts the file before its end.
|
|
559
|
+
*/
|
|
560
|
+
function readFileWindow(text, offset, limit) {
|
|
561
|
+
const total = text.split("\n").length;
|
|
562
|
+
const start = Math.max(1, offset);
|
|
563
|
+
if (start > total) return `Error: offset ${offset} is past the end of the file (${total} lines). Re-read with a smaller offset.`;
|
|
564
|
+
const end = Math.min(total, start - 1 + limit);
|
|
565
|
+
let numbered = formatNumbered(text, offset, limit);
|
|
566
|
+
let shownEnd = end;
|
|
567
|
+
if (numbered.length > 4e4) {
|
|
568
|
+
const cut = numbered.slice(0, MAX_TOOL_OUTPUT_CHARS);
|
|
569
|
+
const lastNewline = cut.lastIndexOf("\n");
|
|
570
|
+
numbered = lastNewline === -1 ? cut : cut.slice(0, lastNewline);
|
|
571
|
+
shownEnd = start - 1 + numbered.split("\n").length;
|
|
572
|
+
}
|
|
573
|
+
if (shownEnd < total) numbered += `\n[truncated \u2014 showing lines ${start}\u2013${shownEnd} of ${total}; re-read with offset=${shownEnd + 1} for the continuation]`;
|
|
574
|
+
return numbered;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Corrective prose for a missing path: list nearby files so the model can recover.
|
|
578
|
+
* Only ENOENT reaches this helper; other stat errors are reported inline.
|
|
579
|
+
*/
|
|
580
|
+
async function missingFileMessage(resolved) {
|
|
581
|
+
const dir = path.dirname(resolved);
|
|
582
|
+
let nearby = [];
|
|
583
|
+
try {
|
|
584
|
+
nearby = await glob({
|
|
585
|
+
patterns: ["*"],
|
|
586
|
+
cwd: dir,
|
|
587
|
+
dot: true,
|
|
588
|
+
deep: 1
|
|
589
|
+
});
|
|
590
|
+
} catch {
|
|
591
|
+
nearby = [];
|
|
592
|
+
}
|
|
593
|
+
const listing = nearby.slice(0, 20).sort((a, b) => a.localeCompare(b));
|
|
594
|
+
return `Error: no file or directory at ${resolved}. ${listing.length > 0 ? `Nearby files in ${path.dirname(resolved)}:\n${listing.map((name) => `- ${name}`).join("\n")}` : "The parent directory is empty or could not be listed."}`;
|
|
595
|
+
}
|
|
596
|
+
//#endregion
|
|
597
|
+
//#region src/webfetch.ts
|
|
598
|
+
const TIMEOUT_MS = 15e3;
|
|
599
|
+
const BODY_CAP_BYTES = 1e6;
|
|
600
|
+
const TEXT_RETURN_CHARS = 2e4;
|
|
601
|
+
const webfetchTool = {
|
|
602
|
+
name: "webfetch",
|
|
603
|
+
description: "Fetch a URL over HTTP(S) and return its content as plain text (HTML tags stripped, no JavaScript rendering). 15 s timeout, 1 MB body cap, first 20 000 chars returned.",
|
|
604
|
+
inputSchema: {
|
|
605
|
+
type: "object",
|
|
606
|
+
properties: { url: {
|
|
607
|
+
type: "string",
|
|
608
|
+
description: "Absolute http(s) URL to fetch"
|
|
609
|
+
} },
|
|
610
|
+
required: ["url"]
|
|
611
|
+
},
|
|
612
|
+
readOnly: true,
|
|
613
|
+
specifier: (input) => typeof input.url === "string" ? input.url : void 0,
|
|
614
|
+
handler: async (input) => {
|
|
615
|
+
const url = typeof input.url === "string" ? input.url : void 0;
|
|
616
|
+
if (url === void 0 || !URL.canParse(url)) return "Error: the `url` argument is required and must be an absolute http(s) URL.";
|
|
617
|
+
let response;
|
|
618
|
+
try {
|
|
619
|
+
response = await fetch(url, {
|
|
620
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
621
|
+
redirect: "follow"
|
|
622
|
+
});
|
|
623
|
+
} catch (error) {
|
|
624
|
+
return `Error: fetch failed for ${url}: ${error.message}`;
|
|
625
|
+
}
|
|
626
|
+
if (!response.ok) return `Error: ${url} responded with HTTP ${response.status} ${response.statusText}.`;
|
|
627
|
+
const reader = response.body?.getReader();
|
|
628
|
+
if (reader === void 0) return `Error: ${url} returned an empty body.`;
|
|
629
|
+
const decoder = new TextDecoder("utf8", { fatal: false });
|
|
630
|
+
let text = "";
|
|
631
|
+
let bytes = 0;
|
|
632
|
+
for (;;) {
|
|
633
|
+
const { done, value } = await reader.read();
|
|
634
|
+
if (done) break;
|
|
635
|
+
bytes += value.byteLength;
|
|
636
|
+
text += decoder.decode(value, { stream: true });
|
|
637
|
+
if (bytes >= BODY_CAP_BYTES) {
|
|
638
|
+
await reader.cancel();
|
|
639
|
+
text += "\n[body truncated at 1 MB]";
|
|
640
|
+
break;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
text += decoder.decode();
|
|
644
|
+
return truncateOutput(((response.headers.get("content-type") ?? "").includes("html") ? htmlToText(text) : text).slice(0, TEXT_RETURN_CHARS), TEXT_RETURN_CHARS);
|
|
645
|
+
}
|
|
646
|
+
};
|
|
647
|
+
/** Naive HTML → text: drop script/style blocks, strip tags, decode common entities. */
|
|
648
|
+
function htmlToText(html) {
|
|
649
|
+
return html.replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<!--[\s\S]*?-->/g, " ").replace(/<[^>]+>/g, " ").replace(/ /g, " ").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, "\"").replace(/�?39;/g, "'").replace(/[ \t]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
|
|
650
|
+
}
|
|
651
|
+
//#endregion
|
|
652
|
+
//#region src/write.ts
|
|
653
|
+
const writeTool = {
|
|
654
|
+
name: "write",
|
|
655
|
+
description: "Create or overwrite a file. Parent directories are created automatically. Overwriting an existing file with more than 5 lines requires `overwrite: true`.",
|
|
656
|
+
inputSchema: {
|
|
657
|
+
type: "object",
|
|
658
|
+
properties: {
|
|
659
|
+
path: {
|
|
660
|
+
type: "string",
|
|
661
|
+
description: "File path, relative to the project cwd"
|
|
662
|
+
},
|
|
663
|
+
content: {
|
|
664
|
+
type: "string",
|
|
665
|
+
description: "Full file content to write"
|
|
666
|
+
},
|
|
667
|
+
overwrite: {
|
|
668
|
+
type: "boolean",
|
|
669
|
+
description: "Set true to overwrite an existing multi-line file"
|
|
670
|
+
}
|
|
671
|
+
},
|
|
672
|
+
required: ["path", "content"]
|
|
673
|
+
},
|
|
674
|
+
readOnly: false,
|
|
675
|
+
specifier: (input) => requireString(input, "path"),
|
|
676
|
+
handler: async (input, ctx) => {
|
|
677
|
+
const raw = requireString(input, "path");
|
|
678
|
+
const content = requireString(input, "content");
|
|
679
|
+
if (raw === void 0) return "Error: the `path` argument is required and must be a string.";
|
|
680
|
+
if (content === void 0) return "Error: the `content` argument is required and must be a string.";
|
|
681
|
+
const resolved = resolveInCwd(ctx.cwd, raw);
|
|
682
|
+
if ((await stat(resolved).catch(() => null))?.isFile()) {
|
|
683
|
+
const lines = (await readFile(resolved, "utf8")).split("\n");
|
|
684
|
+
if (lines.at(-1) === "") lines.pop();
|
|
685
|
+
const lineCount = lines.length;
|
|
686
|
+
if (lineCount > 5 && input.overwrite !== true) return `Error: ${resolved} already exists (${lineCount} lines). Overwriting a multi-line file by mistake is hard to undo. If this is intentional, retry with \`overwrite: true\`. For targeted changes prefer the \`edit\` tool.`;
|
|
687
|
+
}
|
|
688
|
+
await mkdir(path.dirname(resolved), { recursive: true });
|
|
689
|
+
await writeFile(resolved, content, "utf8");
|
|
690
|
+
return truncateOutput(`Wrote ${Buffer.byteLength(content, "utf8")} bytes to ${resolved}`);
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
//#endregion
|
|
694
|
+
//#region src/index.ts
|
|
695
|
+
/** The seven v0.1 built-in tools. */
|
|
696
|
+
function buildTools() {
|
|
697
|
+
return [
|
|
698
|
+
readTool,
|
|
699
|
+
writeTool,
|
|
700
|
+
editTool,
|
|
701
|
+
bashTool,
|
|
702
|
+
globTool,
|
|
703
|
+
grepTool,
|
|
704
|
+
webfetchTool
|
|
705
|
+
];
|
|
706
|
+
}
|
|
707
|
+
//#endregion
|
|
708
|
+
export { MAX_TOOL_OUTPUT_CHARS, bashTool, buildTools, denyReadMessage, editTool, formatNumbered, globTool, grepTool, htmlToText, isDenyReadPath, readTool, requireString, resolveInCwd, truncateOutput, webfetchTool, writeTool };
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@chantier/tools",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"description": "Built-in tools (bash, edit, glob, grep, read, webfetch, write) for the chantier coding agent",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"development": "./src/index.ts",
|
|
10
|
+
"types": "./dist/index.d.mts",
|
|
11
|
+
"import": "./dist/index.mjs"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE",
|
|
18
|
+
"CHANGELOG.md"
|
|
19
|
+
],
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/mlcassociation/chantier.git"
|
|
26
|
+
},
|
|
27
|
+
"homepage": "https://github.com/mlcassociation/chantier#readme",
|
|
28
|
+
"bugs": {
|
|
29
|
+
"url": "https://github.com/mlcassociation/chantier/issues"
|
|
30
|
+
},
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=22"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "tsdown src/index.ts --format esm --dts --clean --out-dir dist",
|
|
36
|
+
"prepublishOnly": "npm run build"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@chantier/core": "^0.3.0",
|
|
40
|
+
"diff": "^8.0.4",
|
|
41
|
+
"tinyglobby": "0.2.17"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"tsdown": "0.23.0"
|
|
45
|
+
}
|
|
46
|
+
}
|