apex-code 0.3.0 → 0.5.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 +46 -0
- package/dist/client/transcript.d.ts.map +1 -1
- package/dist/client/transcript.js +1 -1
- package/dist/client/transcript.js.map +1 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +2 -1
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/delegation/runtime.d.ts.map +1 -1
- package/dist/core/delegation/runtime.js +2 -2
- package/dist/core/delegation/runtime.js.map +1 -1
- package/dist/core/durable-state/daemon.d.ts.map +1 -1
- package/dist/core/durable-state/daemon.js +1 -1
- package/dist/core/durable-state/daemon.js.map +1 -1
- package/dist/core/extensions/types.d.ts +1 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +1 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/mcp/mcp-tool.d.ts.map +1 -1
- package/dist/core/mcp/mcp-tool.js +2 -4
- package/dist/core/mcp/mcp-tool.js.map +1 -1
- package/dist/core/mcp/oauth/authorize.d.ts.map +1 -1
- package/dist/core/mcp/oauth/authorize.js +7 -2
- package/dist/core/mcp/oauth/authorize.js.map +1 -1
- package/dist/core/mcp/runtime.d.ts +2 -2
- package/dist/core/mcp/runtime.d.ts.map +1 -1
- package/dist/core/mcp/runtime.js +8 -3
- package/dist/core/mcp/runtime.js.map +1 -1
- package/dist/core/permissions/store.d.ts +7 -2
- package/dist/core/permissions/store.d.ts.map +1 -1
- package/dist/core/permissions/store.js +6 -1
- package/dist/core/permissions/store.js.map +1 -1
- package/dist/core/project-resources.d.ts +12 -0
- package/dist/core/project-resources.d.ts.map +1 -1
- package/dist/core/project-resources.js +19 -0
- package/dist/core/project-resources.js.map +1 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +10 -1
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/resource-loader.d.ts +6 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +9 -3
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -3
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +16 -3
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +39 -16
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tools/bash.d.ts +11 -7
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +37 -46
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +2 -2
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +3 -3
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +4 -4
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +4 -4
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +4 -4
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/path-utils.d.ts +9 -0
- package/dist/core/tools/path-utils.d.ts.map +1 -1
- package/dist/core/tools/path-utils.js +235 -10
- package/dist/core/tools/path-utils.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +11 -8
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +7 -8
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/workspace/state.d.ts.map +1 -1
- package/dist/core/workspace/state.js +1 -1
- package/dist/core/workspace/state.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +3 -2
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +3 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +0 -10
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/autocomplete-source.d.ts +8 -0
- package/dist/modes/interactive/components/autocomplete-source.d.ts.map +1 -0
- package/dist/modes/interactive/components/autocomplete-source.js +23 -0
- package/dist/modes/interactive/components/autocomplete-source.js.map +1 -0
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +6 -4
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
- package/dist/modes/interactive/components/bordered-loader.js +1 -1
- package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
- package/dist/modes/interactive/components/composer-dock.d.ts +12 -0
- package/dist/modes/interactive/components/composer-dock.d.ts.map +1 -0
- package/dist/modes/interactive/components/composer-dock.js +24 -0
- package/dist/modes/interactive/components/composer-dock.js.map +1 -0
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +11 -9
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/diff.d.ts.map +1 -1
- package/dist/modes/interactive/components/diff.js +2 -2
- package/dist/modes/interactive/components/diff.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +9 -9
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-input.js +9 -5
- package/dist/modes/interactive/components/extension-input.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +11 -10
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
- package/dist/modes/interactive/components/first-time-setup.js +6 -6
- package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +8 -3
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +21 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +34 -0
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +27 -23
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +14 -18
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +7 -6
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/permission-preview.d.ts.map +1 -1
- package/dist/modes/interactive/components/permission-preview.js +3 -3
- package/dist/modes/interactive/components/permission-preview.js.map +1 -1
- package/dist/modes/interactive/components/prompt-input.d.ts +12 -0
- package/dist/modes/interactive/components/prompt-input.d.ts.map +1 -0
- package/dist/modes/interactive/components/prompt-input.js +18 -0
- package/dist/modes/interactive/components/prompt-input.js.map +1 -0
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +4 -3
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +26 -19
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +39 -6
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.js +8 -6
- package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +10 -5
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +1 -11
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +9 -38
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-panel.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-panel.js +7 -2
- package/dist/modes/interactive/components/tool-panel.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +9 -5
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/trust-selector.js +11 -11
- package/dist/modes/interactive/components/trust-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.js +2 -2
- package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +6 -3
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +7 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +65 -65
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +49 -23
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/tsconfig.json +3 -0
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +1 -1
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +22 -22
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/docs/json.md +36 -0
- package/docs/models.md +1 -1
- package/docs/settings.md +1 -1
- package/examples/extensions/gondolin/package-lock.json +3 -3
- package/examples/extensions/minimal-mode.ts +6 -6
- package/examples/extensions/sandbox/package-lock.json +4 -4
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/sdk/10-settings.ts +2 -2
- package/examples/sdk/README.md +1 -1
- package/npm-shrinkwrap.json +19 -34
- package/package.json +6 -6
- package/dist/modes/interactive/components/message-spine.d.ts +0 -14
- package/dist/modes/interactive/components/message-spine.d.ts.map +0 -1
- package/dist/modes/interactive/components/message-spine.js +0 -19
- package/dist/modes/interactive/components/message-spine.js.map +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { accessSync, closeSync, constants, existsSync, fchmodSync, fstatSync, ftruncateSync, mkdirSync, openSync, readSync, realpathSync, renameSync, statSync, unlinkSync, writeSync, } from "node:fs";
|
|
2
3
|
import { access } from "node:fs/promises";
|
|
3
4
|
import { basename, dirname, isAbsolute, join, parse, sep } from "node:path";
|
|
4
5
|
import { normalizePath, resolvePath } from "../../utils/paths.js";
|
|
@@ -19,6 +20,27 @@ export function preparePathOperation(filePath, cwd) {
|
|
|
19
20
|
return { kind: "path-new", path: { kind: "canonical-path", value: canonicalPath } };
|
|
20
21
|
}
|
|
21
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* Verify a descriptor's identity against the one captured at authorization.
|
|
25
|
+
*
|
|
26
|
+
* A zero inode is not an identity. POSIX reserves inode 0 for "no file", and Node reports 0
|
|
27
|
+
* on Windows when the file index is unavailable for the handle. Comparing two of them
|
|
28
|
+
* succeeds trivially, which would turn this check -- the only thing standing between an
|
|
29
|
+
* authorized target and one swapped underneath it -- into a no-op at exactly the moment the
|
|
30
|
+
* platform could not say what we are holding. An unverifiable target is not an authorized
|
|
31
|
+
* one, so refuse rather than proceed.
|
|
32
|
+
*
|
|
33
|
+
* The mismatched case keeps its own wording: "changed" and "could not be verified" are
|
|
34
|
+
* different facts, and an operator reading the refusal should be able to tell them apart.
|
|
35
|
+
*/
|
|
36
|
+
function verifyPreparedIdentity(subject, stats, identity) {
|
|
37
|
+
if (stats.ino === 0 || identity.inode === 0) {
|
|
38
|
+
throw new PreparedTargetChangedError(`Authorized ${subject} target identity could not be verified`);
|
|
39
|
+
}
|
|
40
|
+
if (stats.dev !== identity.device || stats.ino !== identity.inode) {
|
|
41
|
+
throw new PreparedTargetChangedError(`Authorized ${subject} target changed before execution`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
22
44
|
/**
|
|
23
45
|
* Read the authorized target through a no-follow final-component open, verifying
|
|
24
46
|
* the descriptor identity captured at authorization before any byte is returned.
|
|
@@ -38,9 +60,7 @@ export function readPreparedPath(operation, maxBytes) {
|
|
|
38
60
|
}
|
|
39
61
|
try {
|
|
40
62
|
const stats = fstatSync(fd);
|
|
41
|
-
|
|
42
|
-
throw new PreparedTargetChangedError("Authorized read target changed before execution");
|
|
43
|
-
}
|
|
63
|
+
verifyPreparedIdentity("read", stats, operation.identity);
|
|
44
64
|
const length = maxBytes === undefined ? stats.size : Math.min(stats.size, maxBytes);
|
|
45
65
|
const buffer = Buffer.alloc(length);
|
|
46
66
|
let offset = 0;
|
|
@@ -79,6 +99,143 @@ function openUnder(parent, name, flags, mode) {
|
|
|
79
99
|
return openSync(`${PROC_FD}/${parent.fd}/${name}`, flags, mode);
|
|
80
100
|
return openSync(join(parent.path, name), flags, mode);
|
|
81
101
|
}
|
|
102
|
+
function renameUnder(parent, from, to) {
|
|
103
|
+
if (useProcFd())
|
|
104
|
+
renameSync(`${PROC_FD}/${parent.fd}/${from}`, `${PROC_FD}/${parent.fd}/${to}`);
|
|
105
|
+
else
|
|
106
|
+
renameSync(join(parent.path, from), join(parent.path, to));
|
|
107
|
+
}
|
|
108
|
+
function unlinkUnder(parent, name) {
|
|
109
|
+
try {
|
|
110
|
+
if (useProcFd())
|
|
111
|
+
unlinkSync(`${PROC_FD}/${parent.fd}/${name}`);
|
|
112
|
+
else
|
|
113
|
+
unlinkSync(join(parent.path, name));
|
|
114
|
+
}
|
|
115
|
+
catch { }
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The name of the sibling a publish stages into.
|
|
119
|
+
*
|
|
120
|
+
* It carries enough of the destination to be recognizable if a crash ever strands one, and
|
|
121
|
+
* a pid and a random suffix so two publishes in one directory cannot collide. The base is
|
|
122
|
+
* truncated to fit: a destination already at the filesystem's per-component limit would
|
|
123
|
+
* otherwise produce a staging name past it, and fail a write that truncate-in-place handled.
|
|
124
|
+
* 255 is the limit on every filesystem this runs on that has one at all.
|
|
125
|
+
*/
|
|
126
|
+
function stagingName(name) {
|
|
127
|
+
const suffix = `.apex-${process.pid}-${randomUUID().slice(0, 8)}`;
|
|
128
|
+
const budget = 255 - suffix.length - 1;
|
|
129
|
+
return `.${name.slice(0, Math.max(1, budget))}${suffix}`;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Write `content` to a sibling of `name` and rename it over `name`.
|
|
133
|
+
*
|
|
134
|
+
* The rename is the publish. Until it runs, `name` still refers to the old inode with all
|
|
135
|
+
* of its old bytes, so a crash, a full disk, or a kill mid-write destroys nothing. The
|
|
136
|
+
* caller has already proved that `name` refers to the authorized target; this only decides
|
|
137
|
+
* how the bytes arrive.
|
|
138
|
+
*
|
|
139
|
+
* `mode` is the destination's, captured from the descriptor the identity check used, so a
|
|
140
|
+
* publish does not quietly reset a file's permissions to the temp file's. Ownership is not
|
|
141
|
+
* carried: a rename installs a file this process created, so a target owned by someone else
|
|
142
|
+
* and merely writable by us changes owner. That is inherent to publishing by rename and is
|
|
143
|
+
* the same trade the session store already makes.
|
|
144
|
+
*
|
|
145
|
+
* One guarantee narrows, and it is worth stating plainly rather than leaving for a reader to
|
|
146
|
+
* derive. ADR 0029's identity check still runs and still aborts on a mismatch, but it now
|
|
147
|
+
* proves the name referred to the authorized file at the moment of the check rather than at
|
|
148
|
+
* the moment of the write. Writing through the checked descriptor could not be redirected by
|
|
149
|
+
* a later swap; a rename can be, because it resolves the name again. The window is between
|
|
150
|
+
* the identity check and the rename, both anchored to the same validated parent descriptor,
|
|
151
|
+
* and exploiting it needs a local attacker placing a file at that exact name in a directory
|
|
152
|
+
* the call was already authorized to write. That is traded for crash safety, which is not a
|
|
153
|
+
* race: it is what every interrupted write did.
|
|
154
|
+
*
|
|
155
|
+
* Windows refuses a rename onto a destination another handle holds open, and an ordinary read
|
|
156
|
+
* handle is enough to trigger it. An earlier version of this comment called that an acceptable
|
|
157
|
+
* trade. Three-OS CI disproved it: the case is an editor, a watcher, or a language server with
|
|
158
|
+
* the file open, which is the common case rather than an exotic one, and failing the write
|
|
159
|
+
* there is not a trade a user opted into. It falls back to `writeInPlace` instead, so Windows
|
|
160
|
+
* gets atomic publish whenever it can and a working write when it cannot.
|
|
161
|
+
*/
|
|
162
|
+
function publishByRename(parent, name, content, mode) {
|
|
163
|
+
const temporary = stagingName(name);
|
|
164
|
+
let fd;
|
|
165
|
+
try {
|
|
166
|
+
fd = openUnder(parent, temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, mode);
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
throw new PreparedTargetChangedError("Authorized write could not stage its replacement", { cause: error });
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
writeAll(fd, content);
|
|
173
|
+
// The create mode passes through umask; the destination's mode does not.
|
|
174
|
+
fchmodSync(fd, mode);
|
|
175
|
+
closeSync(fd);
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
try {
|
|
179
|
+
closeSync(fd);
|
|
180
|
+
}
|
|
181
|
+
catch { }
|
|
182
|
+
unlinkUnder(parent, temporary);
|
|
183
|
+
throw error;
|
|
184
|
+
}
|
|
185
|
+
try {
|
|
186
|
+
renameUnder(parent, temporary, name);
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
unlinkUnder(parent, temporary);
|
|
191
|
+
if (isWindowsSharingViolation(error))
|
|
192
|
+
return false;
|
|
193
|
+
throw new PreparedTargetChangedError("Authorized write target changed before execution", { cause: error });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Windows refuses to rename onto a destination another handle holds open, and an ordinary
|
|
198
|
+
* read handle is enough. An editor, a watcher, or a language server with the file open is
|
|
199
|
+
* the common case, not an exotic one, so a rename that cannot land there has to fall back
|
|
200
|
+
* rather than fail the write.
|
|
201
|
+
*
|
|
202
|
+
* Three OS CI found this. The Linux and macOS jobs pass, because POSIX renames over an open
|
|
203
|
+
* file happily.
|
|
204
|
+
*/
|
|
205
|
+
function isWindowsSharingViolation(error) {
|
|
206
|
+
if (process.platform !== "win32")
|
|
207
|
+
return false;
|
|
208
|
+
const code = error?.code;
|
|
209
|
+
return code === "EPERM" || code === "EACCES" || code === "EBUSY";
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* The pre-rename publish, kept for the one case that cannot use a rename.
|
|
213
|
+
*
|
|
214
|
+
* This is the truncate-then-write window the rename exists to close, so it runs only when
|
|
215
|
+
* Windows has refused the rename. Crash safety is lost for that write; the alternative is
|
|
216
|
+
* refusing to write a file something else has open, which is worse and is not a trade a
|
|
217
|
+
* user opted into. The identity check is re-run against a freshly opened descriptor, so the
|
|
218
|
+
* weaker durability does not come with a weaker target guarantee.
|
|
219
|
+
*/
|
|
220
|
+
function writeInPlace(parent, name, content, identity) {
|
|
221
|
+
let fd;
|
|
222
|
+
try {
|
|
223
|
+
fd = openUnder(parent, name, constants.O_WRONLY | constants.O_NOFOLLOW);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
throw new PreparedTargetChangedError("Authorized write target changed before execution", { cause: error });
|
|
227
|
+
}
|
|
228
|
+
try {
|
|
229
|
+
if (identity) {
|
|
230
|
+
verifyPreparedIdentity("write", fstatSync(fd), identity);
|
|
231
|
+
}
|
|
232
|
+
ftruncateSync(fd, 0);
|
|
233
|
+
writeAll(fd, content);
|
|
234
|
+
}
|
|
235
|
+
finally {
|
|
236
|
+
closeSync(fd);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
82
239
|
function mkdirUnder(parent, name) {
|
|
83
240
|
if (useProcFd())
|
|
84
241
|
mkdirSync(`${PROC_FD}/${parent.fd}/${name}`);
|
|
@@ -176,19 +333,23 @@ export function writePreparedPath(operation, content) {
|
|
|
176
333
|
catch (error) {
|
|
177
334
|
throw new PreparedTargetChangedError("Authorized write target changed before execution", { cause: error });
|
|
178
335
|
}
|
|
336
|
+
let mode;
|
|
179
337
|
try {
|
|
180
338
|
const stats = fstatSync(fd);
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
}
|
|
184
|
-
ftruncateSync(fd, 0);
|
|
185
|
-
writeAll(fd, content);
|
|
339
|
+
verifyPreparedIdentity("write", stats, operation.identity);
|
|
340
|
+
mode = stats.mode & 0o7777;
|
|
186
341
|
}
|
|
187
342
|
finally {
|
|
188
343
|
closeSync(fd);
|
|
189
344
|
}
|
|
345
|
+
if (!publishByRename(parent, name, content, mode)) {
|
|
346
|
+
writeInPlace(parent, name, content, operation.identity);
|
|
347
|
+
}
|
|
190
348
|
return;
|
|
191
349
|
}
|
|
350
|
+
// The exclusive create is what proves the name was still absent, which is the whole
|
|
351
|
+
// authorization for a new-file write. It reserves the name; the rename below then
|
|
352
|
+
// replaces that empty placeholder, so the name never holds a half-written file.
|
|
192
353
|
let fd;
|
|
193
354
|
try {
|
|
194
355
|
fd = openUnder(parent, name, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
@@ -196,13 +357,77 @@ export function writePreparedPath(operation, content) {
|
|
|
196
357
|
catch (error) {
|
|
197
358
|
throw new PreparedTargetChangedError("Authorized new-file target changed before execution", { cause: error });
|
|
198
359
|
}
|
|
360
|
+
closeSync(fd);
|
|
199
361
|
try {
|
|
362
|
+
// The reservation this just created is ours, so there is no prior identity to
|
|
363
|
+
// re-check if Windows refuses the rename onto it.
|
|
364
|
+
if (!publishByRename(parent, name, content, 0o600)) {
|
|
365
|
+
writeInPlace(parent, name, content);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
unlinkUnder(parent, name);
|
|
370
|
+
throw error;
|
|
371
|
+
}
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Atomic publish for an ungated write, where no prepared operation exists to pin the target.
|
|
376
|
+
*
|
|
377
|
+
* `writePreparedPath` is the gated path and the one that matters; this is its counterpart for
|
|
378
|
+
* a tool invoked outside the permission gate, so that neither route can leave a half-written
|
|
379
|
+
* file. It makes no containment claim: with no authorization there is no authorized target to
|
|
380
|
+
* hold the write to, and the no-follow walk would have nothing to check against.
|
|
381
|
+
*/
|
|
382
|
+
export function writePathAtomically(filePath, content) {
|
|
383
|
+
const temporary = join(dirname(filePath), stagingName(basename(filePath)));
|
|
384
|
+
// Only an existing destination has a mode worth carrying. For a new file there is
|
|
385
|
+
// nothing to capture, and chmod'ing to the 0o666 open default would force past the
|
|
386
|
+
// caller's umask and publish a world-writable file, which `writeFile` never did.
|
|
387
|
+
let destinationMode;
|
|
388
|
+
try {
|
|
389
|
+
destinationMode = statSync(filePath).mode & 0o7777;
|
|
390
|
+
}
|
|
391
|
+
catch { }
|
|
392
|
+
const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, destinationMode ?? 0o666);
|
|
393
|
+
try {
|
|
394
|
+
writeAll(fd, content);
|
|
395
|
+
if (destinationMode !== undefined)
|
|
396
|
+
fchmodSync(fd, destinationMode);
|
|
397
|
+
closeSync(fd);
|
|
398
|
+
}
|
|
399
|
+
catch (error) {
|
|
400
|
+
try {
|
|
401
|
+
closeSync(fd);
|
|
402
|
+
}
|
|
403
|
+
catch { }
|
|
404
|
+
try {
|
|
405
|
+
unlinkSync(temporary);
|
|
406
|
+
}
|
|
407
|
+
catch { }
|
|
408
|
+
throw error;
|
|
409
|
+
}
|
|
410
|
+
try {
|
|
411
|
+
renameSync(temporary, filePath);
|
|
412
|
+
}
|
|
413
|
+
catch (error) {
|
|
414
|
+
try {
|
|
415
|
+
unlinkSync(temporary);
|
|
416
|
+
}
|
|
417
|
+
catch { }
|
|
418
|
+
// Same Windows sharing case as the gated path, and the same answer: a file something
|
|
419
|
+
// else has open is still a file the caller asked to write.
|
|
420
|
+
if (!isWindowsSharingViolation(error))
|
|
421
|
+
throw error;
|
|
422
|
+
const fd = openSync(filePath, constants.O_WRONLY | constants.O_CREAT, destinationMode ?? 0o666);
|
|
423
|
+
try {
|
|
424
|
+
ftruncateSync(fd, 0);
|
|
200
425
|
writeAll(fd, content);
|
|
201
426
|
}
|
|
202
427
|
finally {
|
|
203
428
|
closeSync(fd);
|
|
204
429
|
}
|
|
205
|
-
}
|
|
430
|
+
}
|
|
206
431
|
}
|
|
207
432
|
function tryMacOSScreenshotPath(filePath) {
|
|
208
433
|
return filePath.replace(/ (AM|PM)\./gi, `${NARROW_NO_BREAK_SPACE}$1.`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path-utils.js","sourceRoot":"","sources":["../../../src/core/tools/path-utils.ts"],"names":[],"mappings":"AAAA,OAA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WAAW,CAAC,CAAC,EAAE,CAAC;QACjE,OAAO,WAAW,CAAC;IACpB,CAAC;IAED,uDAAuD;IACvD,MAAM,UAAU,GAAG,aAAa,CAAC,QAAQ,CAAC,CAAC;IAC3C,IAAI,UAAU,KAAK,QAAQ,IAAI,CAAC,MAAM,UAAU,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;QAC/D,OAAO,UAAU,CAAC;IACnB,CAAC;IAED,kEAAkE;IAClE,MAAM,YAAY,GAAG,oBAAoB,CAAC,QAAQ,CAAC,CAAC;IACpD,IAAI,YAAY,KAAK,QAAQ,IAAI,CAAC,MAAM,UAAU,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC;QACnE,OAAO,YAAY,CAAC;IACrB,CAAC;IAED,wFAAuF;IACvF,MAAM,eAAe,GAAG,oBAAoB,CAAC,UAAU,CAAC,CAAC;IACzD,IAAI,eAAe,KAAK,QAAQ,IAAI,CAAC,MAAM,UAAU,CAAC,eAAe,CAAC,CAAC,EAAE,CAAC;QACzE,OAAO,eAAe,CAAC;IACxB,CAAC;IAED,OAAO,QAAQ,CAAC;AAAA,CAChB","sourcesContent":["import {\n\taccessSync,\n\tcloseSync,\n\tconstants,\n\texistsSync,\n\tfstatSync,\n\tftruncateSync,\n\tmkdirSync,\n\topenSync,\n\treadSync,\n\trealpathSync,\n\tstatSync,\n\twriteSync,\n} from \"node:fs\";\nimport { access } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, join, parse, sep } from \"node:path\";\nimport { normalizePath, resolvePath } from \"../../utils/paths.ts\";\nimport type { PreparedPathOperation } from \"../permissions/operations.ts\";\n\nconst NARROW_NO_BREAK_SPACE = \"\\u202F\";\n\nexport function preparePathOperation(filePath: string, cwd: string): PreparedPathOperation {\n\tconst canonicalPath = resolveToCwd(filePath, cwd);\n\tif (!isAbsolute(canonicalPath)) throw new Error(\"Canonical path must be absolute\");\n\ttry {\n\t\tconst stats = statSync(canonicalPath);\n\t\treturn {\n\t\t\tkind: \"path-existing\",\n\t\t\tpath: { kind: \"canonical-path\", value: canonicalPath },\n\t\t\tidentity: { device: stats.dev, inode: stats.ino },\n\t\t};\n\t} catch {\n\t\treturn { kind: \"path-new\", path: { kind: \"canonical-path\", value: canonicalPath } };\n\t}\n}\n\n/**\n * Read the authorized target through a no-follow final-component open, verifying\n * the descriptor identity captured at authorization before any byte is returned.\n * A replaced alias or an injected symlink never matches and the read aborts.\n */\nexport function readPreparedPath(operation: PreparedPathOperation, maxBytes?: number): Buffer {\n\tif (operation.kind !== \"path-existing\") {\n\t\tthrow new PreparedTargetChangedError(\"Authorized read target did not exist when permission was checked\");\n\t}\n\treturn withTargetDirectory(operation, { createMissingDirectories: false }, (parent, name) => {\n\t\tlet fd: number;\n\t\ttry {\n\t\t\tfd = openUnder(parent, name, constants.O_RDONLY | constants.O_NOFOLLOW);\n\t\t} catch (error) {\n\t\t\tthrow new PreparedTargetChangedError(\"Authorized read target changed before execution\", { cause: error });\n\t\t}\n\t\ttry {\n\t\t\tconst stats = fstatSync(fd);\n\t\t\tif (stats.dev !== operation.identity.device || stats.ino !== operation.identity.inode) {\n\t\t\t\tthrow new PreparedTargetChangedError(\"Authorized read target changed before execution\");\n\t\t\t}\n\t\t\tconst length = maxBytes === undefined ? stats.size : Math.min(stats.size, maxBytes);\n\t\t\tconst buffer = Buffer.alloc(length);\n\t\t\tlet offset = 0;\n\t\t\twhile (offset < buffer.length) {\n\t\t\t\tconst read = readSync(fd, buffer, offset, buffer.length - offset, null);\n\t\t\t\tif (read === 0) break;\n\t\t\t\toffset += read;\n\t\t\t}\n\t\t\treturn offset === buffer.length ? buffer : buffer.subarray(0, offset);\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t});\n}\n\n/** The authorized target changed between permission evaluation and execution. */\nexport class PreparedTargetChangedError extends Error {}\n\nconst PROC_FD = \"/proc/self/fd\";\nlet procFdAvailable: boolean | undefined;\n\n/** /proc lets an already-open directory fd act as the parent of the next open, so a swapped intermediate directory cannot be traversed. */\nfunction useProcFd(): boolean {\n\tif (procFdAvailable === undefined) {\n\t\ttry {\n\t\t\tprocFdAvailable = existsSync(`${PROC_FD}/self`);\n\t\t} catch {\n\t\t\tprocFdAvailable = false;\n\t\t}\n\t}\n\treturn procFdAvailable;\n}\n\ninterface OpenDirectory {\n\tfd: number;\n\t/** Fallback parent path for platforms without /proc/self/fd. */\n\tpath: string;\n}\n\nfunction openUnder(parent: OpenDirectory, name: string, flags: number, mode?: number): number {\n\tif (useProcFd()) return openSync(`${PROC_FD}/${parent.fd}/${name}`, flags, mode);\n\treturn openSync(join(parent.path, name), flags, mode);\n}\n\nfunction mkdirUnder(parent: OpenDirectory, name: string): void {\n\tif (useProcFd()) mkdirSync(`${PROC_FD}/${parent.fd}/${name}`);\n\telse mkdirSync(join(parent.path, name));\n}\n\nfunction openChildDirectory(parent: OpenDirectory, name: string): OpenDirectory {\n\tconst flags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;\n\tconst fd = openUnder(parent, name, flags);\n\tcloseSync(parent.fd);\n\treturn { fd, path: join(parent.path, name) };\n}\n\nfunction writeAll(fd: number, content: string | Buffer): void {\n\tconst buffer = typeof content === \"string\" ? Buffer.from(content, \"utf-8\") : content;\n\tlet written = 0;\n\twhile (written < buffer.length) {\n\t\twritten += writeSync(fd, buffer, written, buffer.length - written);\n\t}\n}\n\nfunction isMissingEntryError(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: unknown }).code === \"ENOENT\"\n\t);\n}\n\n/**\n * Walk every directory component of the authorized path no-follow, holding one\n * directory fd across the walk, then run the caller's final-component step against\n * that walked parent. Any intermediate that is not a real directory — a swapped\n * symlink, a removed component — aborts before the target is touched.\n */\nfunction withTargetDirectory<T>(\n\toperation: PreparedPathOperation,\n\toptions: { createMissingDirectories: boolean },\n\trun: (parent: OpenDirectory, name: string) => T,\n): T {\n\tconst root = parse(operation.path.value).root;\n\tconst components = operation.path.value\n\t\t.slice(root.length)\n\t\t.split(sep)\n\t\t.filter((component) => component.length > 0);\n\tconst name = components[components.length - 1];\n\tif (name === undefined) throw new PreparedTargetChangedError(\"Authorized path has no final component\");\n\tlet parent: OpenDirectory = { fd: openSync(root, constants.O_RDONLY | constants.O_DIRECTORY), path: root };\n\tconst closeParent = (): void => {\n\t\ttry {\n\t\t\tcloseSync(parent.fd);\n\t\t} catch {}\n\t};\n\tfor (const component of components.slice(0, -1)) {\n\t\ttry {\n\t\t\tparent = openChildDirectory(parent, component);\n\t\t} catch (error) {\n\t\t\tif (options.createMissingDirectories && isMissingEntryError(error)) {\n\t\t\t\ttry {\n\t\t\t\t\tmkdirUnder(parent, component);\n\t\t\t\t\tparent = openChildDirectory(parent, component);\n\t\t\t\t\tcontinue;\n\t\t\t\t} catch (mkdirError) {\n\t\t\t\t\tcloseParent();\n\t\t\t\t\tthrow new PreparedTargetChangedError(`Authorized write parent \"${component}\" changed before execution`, {\n\t\t\t\t\t\tcause: mkdirError,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tcloseParent();\n\t\t\tthrow new PreparedTargetChangedError(`Authorized path component \"${component}\" changed before execution`, {\n\t\t\t\tcause: error,\n\t\t\t});\n\t\t}\n\t}\n\ttry {\n\t\treturn run(parent, name);\n\t} finally {\n\t\tcloseParent();\n\t}\n}\n\n/**\n * Execute an authorized write against the prepared target.\n *\n * - `path-existing`: the final component is opened `O_NOFOLLOW`, its descriptor\n * identity is compared with the identity captured at authorization, and only\n * then is the file truncated and written through that descriptor. A swapped\n * alias, an injected symlink, or a redirected parent never matches and the\n * write aborts before any byte changes.\n * - `path-new`: missing parents are created no-follow under the walked directory\n * descriptor, and the file is created `O_CREAT | O_EXCL | O_NOFOLLOW`, so a\n * replaced parent or a pre-placed symlink is never followed.\n */\nexport function writePreparedPath(operation: PreparedPathOperation, content: string | Buffer): void {\n\twithTargetDirectory(operation, { createMissingDirectories: operation.kind === \"path-new\" }, (parent, name) => {\n\t\tif (operation.kind === \"path-existing\") {\n\t\t\tlet fd: number;\n\t\t\ttry {\n\t\t\t\tfd = openUnder(parent, name, constants.O_WRONLY | constants.O_NOFOLLOW);\n\t\t\t} catch (error) {\n\t\t\t\tthrow new PreparedTargetChangedError(\"Authorized write target changed before execution\", { cause: error });\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst stats = fstatSync(fd);\n\t\t\t\tif (stats.dev !== operation.identity.device || stats.ino !== operation.identity.inode) {\n\t\t\t\t\tthrow new PreparedTargetChangedError(\"Authorized write target changed before execution\");\n\t\t\t\t}\n\t\t\t\tftruncateSync(fd, 0);\n\t\t\t\twriteAll(fd, content);\n\t\t\t} finally {\n\t\t\t\tcloseSync(fd);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tlet fd: number;\n\t\ttry {\n\t\t\tfd = openUnder(\n\t\t\t\tparent,\n\t\t\t\tname,\n\t\t\t\tconstants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n\t\t\t\t0o600,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new PreparedTargetChangedError(\"Authorized new-file target changed before execution\", { cause: error });\n\t\t}\n\t\ttry {\n\t\t\twriteAll(fd, content);\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t});\n}\n\nfunction tryMacOSScreenshotPath(filePath: string): string {\n\treturn filePath.replace(/ (AM|PM)\\./gi, `${NARROW_NO_BREAK_SPACE}$1.`);\n}\n\nfunction tryNFDVariant(filePath: string): string {\n\t// macOS stores filenames in NFD (decomposed) form, try converting user input to NFD\n\treturn filePath.normalize(\"NFD\");\n}\n\nfunction tryCurlyQuoteVariant(filePath: string): string {\n\t// macOS uses U+2019 (right single quotation mark) in screenshot names like \"Capture d'écran\"\n\t// Users typically type U+0027 (straight apostrophe)\n\treturn filePath.replace(/'/g, \"\\u2019\");\n}\n\nfunction fileExists(filePath: string): boolean {\n\ttry {\n\t\taccessSync(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport async function pathExists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait access(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function expandPath(filePath: string): string {\n\treturn normalizePath(filePath, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n}\n\n/**\n * Resolve a path relative to the given cwd, handling ~ expansion and absolute\n * paths. The result is the single target used by both permission matching and\n * filesystem execution.\n */\nexport function resolveToCwd(filePath: string, cwd: string): string {\n\tconst requested = resolvePath(filePath, cwd, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n\ttry {\n\t\treturn realpathSync(requested);\n\t} catch {\n\t\ttry {\n\t\t\treturn joinCanonicalParent(requested);\n\t\t} catch {\n\t\t\treturn requested;\n\t\t}\n\t}\n}\n\nfunction joinCanonicalParent(requested: string): string {\n\treturn join(realpathSync(dirname(requested)), basename(requested));\n}\n\nexport function resolveReadPath(filePath: string, cwd: string): string {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (fileExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && fileExists(amPmVariant)) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && fileExists(nfdVariant)) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && fileExists(curlyVariant)) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && fileExists(nfdCurlyVariant)) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n\nexport async function resolveReadPathAsync(filePath: string, cwd: string): Promise<string> {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (await pathExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && (await pathExists(amPmVariant))) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && (await pathExists(nfdVariant))) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && (await pathExists(curlyVariant))) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && (await pathExists(nfdCurlyVariant))) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"path-utils.js","sourceRoot":"","sources":["../../../src/core/tools/path-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,UAAU,EACV,UAAU,EACV,SAAS,EACT,aAAa,EACb,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,SAAS,GACT,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,OA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loseSync,\n\tconstants,\n\texistsSync,\n\tfchmodSync,\n\tfstatSync,\n\tftruncateSync,\n\tmkdirSync,\n\topenSync,\n\treadSync,\n\trealpathSync,\n\trenameSync,\n\tstatSync,\n\tunlinkSync,\n\twriteSync,\n} from \"node:fs\";\nimport { access } from \"node:fs/promises\";\nimport { basename, dirname, isAbsolute, join, parse, sep } from \"node:path\";\nimport { normalizePath, resolvePath } from \"../../utils/paths.ts\";\nimport type { FileIdentity, PreparedPathOperation } from \"../permissions/operations.ts\";\n\nconst NARROW_NO_BREAK_SPACE = \"\\u202F\";\n\nexport function preparePathOperation(filePath: string, cwd: string): PreparedPathOperation {\n\tconst canonicalPath = resolveToCwd(filePath, cwd);\n\tif (!isAbsolute(canonicalPath)) throw new Error(\"Canonical path must be absolute\");\n\ttry {\n\t\tconst stats = statSync(canonicalPath);\n\t\treturn {\n\t\t\tkind: \"path-existing\",\n\t\t\tpath: { kind: \"canonical-path\", value: canonicalPath },\n\t\t\tidentity: { device: stats.dev, inode: stats.ino },\n\t\t};\n\t} catch {\n\t\treturn { kind: \"path-new\", path: { kind: \"canonical-path\", value: canonicalPath } };\n\t}\n}\n\n/**\n * Verify a descriptor's identity against the one captured at authorization.\n *\n * A zero inode is not an identity. POSIX reserves inode 0 for \"no file\", and Node reports 0\n * on Windows when the file index is unavailable for the handle. Comparing two of them\n * succeeds trivially, which would turn this check -- the only thing standing between an\n * authorized target and one swapped underneath it -- into a no-op at exactly the moment the\n * platform could not say what we are holding. An unverifiable target is not an authorized\n * one, so refuse rather than proceed.\n *\n * The mismatched case keeps its own wording: \"changed\" and \"could not be verified\" are\n * different facts, and an operator reading the refusal should be able to tell them apart.\n */\nfunction verifyPreparedIdentity(subject: \"read\" | \"write\", stats: Stats, identity: FileIdentity): void {\n\tif (stats.ino === 0 || identity.inode === 0) {\n\t\tthrow new PreparedTargetChangedError(`Authorized ${subject} target identity could not be verified`);\n\t}\n\tif (stats.dev !== identity.device || stats.ino !== identity.inode) {\n\t\tthrow new PreparedTargetChangedError(`Authorized ${subject} target changed before execution`);\n\t}\n}\n\n/**\n * Read the authorized target through a no-follow final-component open, verifying\n * the descriptor identity captured at authorization before any byte is returned.\n * A replaced alias or an injected symlink never matches and the read aborts.\n */\nexport function readPreparedPath(operation: PreparedPathOperation, maxBytes?: number): Buffer {\n\tif (operation.kind !== \"path-existing\") {\n\t\tthrow new PreparedTargetChangedError(\"Authorized read target did not exist when permission was checked\");\n\t}\n\treturn withTargetDirectory(operation, { createMissingDirectories: false }, (parent, name) => {\n\t\tlet fd: number;\n\t\ttry {\n\t\t\tfd = openUnder(parent, name, constants.O_RDONLY | constants.O_NOFOLLOW);\n\t\t} catch (error) {\n\t\t\tthrow new PreparedTargetChangedError(\"Authorized read target changed before execution\", { cause: error });\n\t\t}\n\t\ttry {\n\t\t\tconst stats = fstatSync(fd);\n\t\t\tverifyPreparedIdentity(\"read\", stats, operation.identity);\n\t\t\tconst length = maxBytes === undefined ? stats.size : Math.min(stats.size, maxBytes);\n\t\t\tconst buffer = Buffer.alloc(length);\n\t\t\tlet offset = 0;\n\t\t\twhile (offset < buffer.length) {\n\t\t\t\tconst read = readSync(fd, buffer, offset, buffer.length - offset, null);\n\t\t\t\tif (read === 0) break;\n\t\t\t\toffset += read;\n\t\t\t}\n\t\t\treturn offset === buffer.length ? buffer : buffer.subarray(0, offset);\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t});\n}\n\n/** The authorized target changed between permission evaluation and execution. */\nexport class PreparedTargetChangedError extends Error {}\n\nconst PROC_FD = \"/proc/self/fd\";\nlet procFdAvailable: boolean | undefined;\n\n/** /proc lets an already-open directory fd act as the parent of the next open, so a swapped intermediate directory cannot be traversed. */\nfunction useProcFd(): boolean {\n\tif (procFdAvailable === undefined) {\n\t\ttry {\n\t\t\tprocFdAvailable = existsSync(`${PROC_FD}/self`);\n\t\t} catch {\n\t\t\tprocFdAvailable = false;\n\t\t}\n\t}\n\treturn procFdAvailable;\n}\n\ninterface OpenDirectory {\n\tfd: number;\n\t/** Fallback parent path for platforms without /proc/self/fd. */\n\tpath: string;\n}\n\nfunction openUnder(parent: OpenDirectory, name: string, flags: number, mode?: number): number {\n\tif (useProcFd()) return openSync(`${PROC_FD}/${parent.fd}/${name}`, flags, mode);\n\treturn openSync(join(parent.path, name), flags, mode);\n}\n\nfunction renameUnder(parent: OpenDirectory, from: string, to: string): void {\n\tif (useProcFd()) renameSync(`${PROC_FD}/${parent.fd}/${from}`, `${PROC_FD}/${parent.fd}/${to}`);\n\telse renameSync(join(parent.path, from), join(parent.path, to));\n}\n\nfunction unlinkUnder(parent: OpenDirectory, name: string): void {\n\ttry {\n\t\tif (useProcFd()) unlinkSync(`${PROC_FD}/${parent.fd}/${name}`);\n\t\telse unlinkSync(join(parent.path, name));\n\t} catch {}\n}\n\n/**\n * The name of the sibling a publish stages into.\n *\n * It carries enough of the destination to be recognizable if a crash ever strands one, and\n * a pid and a random suffix so two publishes in one directory cannot collide. The base is\n * truncated to fit: a destination already at the filesystem's per-component limit would\n * otherwise produce a staging name past it, and fail a write that truncate-in-place handled.\n * 255 is the limit on every filesystem this runs on that has one at all.\n */\nfunction stagingName(name: string): string {\n\tconst suffix = `.apex-${process.pid}-${randomUUID().slice(0, 8)}`;\n\tconst budget = 255 - suffix.length - 1;\n\treturn `.${name.slice(0, Math.max(1, budget))}${suffix}`;\n}\n\n/**\n * Write `content` to a sibling of `name` and rename it over `name`.\n *\n * The rename is the publish. Until it runs, `name` still refers to the old inode with all\n * of its old bytes, so a crash, a full disk, or a kill mid-write destroys nothing. The\n * caller has already proved that `name` refers to the authorized target; this only decides\n * how the bytes arrive.\n *\n * `mode` is the destination's, captured from the descriptor the identity check used, so a\n * publish does not quietly reset a file's permissions to the temp file's. Ownership is not\n * carried: a rename installs a file this process created, so a target owned by someone else\n * and merely writable by us changes owner. That is inherent to publishing by rename and is\n * the same trade the session store already makes.\n *\n * One guarantee narrows, and it is worth stating plainly rather than leaving for a reader to\n * derive. ADR 0029's identity check still runs and still aborts on a mismatch, but it now\n * proves the name referred to the authorized file at the moment of the check rather than at\n * the moment of the write. Writing through the checked descriptor could not be redirected by\n * a later swap; a rename can be, because it resolves the name again. The window is between\n * the identity check and the rename, both anchored to the same validated parent descriptor,\n * and exploiting it needs a local attacker placing a file at that exact name in a directory\n * the call was already authorized to write. That is traded for crash safety, which is not a\n * race: it is what every interrupted write did.\n *\n * Windows refuses a rename onto a destination another handle holds open, and an ordinary read\n * handle is enough to trigger it. An earlier version of this comment called that an acceptable\n * trade. Three-OS CI disproved it: the case is an editor, a watcher, or a language server with\n * the file open, which is the common case rather than an exotic one, and failing the write\n * there is not a trade a user opted into. It falls back to `writeInPlace` instead, so Windows\n * gets atomic publish whenever it can and a working write when it cannot.\n */\nfunction publishByRename(parent: OpenDirectory, name: string, content: string | Buffer, mode: number): boolean {\n\tconst temporary = stagingName(name);\n\tlet fd: number;\n\ttry {\n\t\tfd = openUnder(\n\t\t\tparent,\n\t\t\ttemporary,\n\t\t\tconstants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n\t\t\tmode,\n\t\t);\n\t} catch (error) {\n\t\tthrow new PreparedTargetChangedError(\"Authorized write could not stage its replacement\", { cause: error });\n\t}\n\ttry {\n\t\twriteAll(fd, content);\n\t\t// The create mode passes through umask; the destination's mode does not.\n\t\tfchmodSync(fd, mode);\n\t\tcloseSync(fd);\n\t} catch (error) {\n\t\ttry {\n\t\t\tcloseSync(fd);\n\t\t} catch {}\n\t\tunlinkUnder(parent, temporary);\n\t\tthrow error;\n\t}\n\ttry {\n\t\trenameUnder(parent, temporary, name);\n\t\treturn true;\n\t} catch (error) {\n\t\tunlinkUnder(parent, temporary);\n\t\tif (isWindowsSharingViolation(error)) return false;\n\t\tthrow new PreparedTargetChangedError(\"Authorized write target changed before execution\", { cause: error });\n\t}\n}\n\n/**\n * Windows refuses to rename onto a destination another handle holds open, and an ordinary\n * read handle is enough. An editor, a watcher, or a language server with the file open is\n * the common case, not an exotic one, so a rename that cannot land there has to fall back\n * rather than fail the write.\n *\n * Three OS CI found this. The Linux and macOS jobs pass, because POSIX renames over an open\n * file happily.\n */\nfunction isWindowsSharingViolation(error: unknown): boolean {\n\tif (process.platform !== \"win32\") return false;\n\tconst code = (error as { code?: unknown } | null)?.code;\n\treturn code === \"EPERM\" || code === \"EACCES\" || code === \"EBUSY\";\n}\n\n/**\n * The pre-rename publish, kept for the one case that cannot use a rename.\n *\n * This is the truncate-then-write window the rename exists to close, so it runs only when\n * Windows has refused the rename. Crash safety is lost for that write; the alternative is\n * refusing to write a file something else has open, which is worse and is not a trade a\n * user opted into. The identity check is re-run against a freshly opened descriptor, so the\n * weaker durability does not come with a weaker target guarantee.\n */\nfunction writeInPlace(parent: OpenDirectory, name: string, content: string | Buffer, identity?: FileIdentity): void {\n\tlet fd: number;\n\ttry {\n\t\tfd = openUnder(parent, name, constants.O_WRONLY | constants.O_NOFOLLOW);\n\t} catch (error) {\n\t\tthrow new PreparedTargetChangedError(\"Authorized write target changed before execution\", { cause: error });\n\t}\n\ttry {\n\t\tif (identity) {\n\t\t\tverifyPreparedIdentity(\"write\", fstatSync(fd), identity);\n\t\t}\n\t\tftruncateSync(fd, 0);\n\t\twriteAll(fd, content);\n\t} finally {\n\t\tcloseSync(fd);\n\t}\n}\n\nfunction mkdirUnder(parent: OpenDirectory, name: string): void {\n\tif (useProcFd()) mkdirSync(`${PROC_FD}/${parent.fd}/${name}`);\n\telse mkdirSync(join(parent.path, name));\n}\n\nfunction openChildDirectory(parent: OpenDirectory, name: string): OpenDirectory {\n\tconst flags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;\n\tconst fd = openUnder(parent, name, flags);\n\tcloseSync(parent.fd);\n\treturn { fd, path: join(parent.path, name) };\n}\n\nfunction writeAll(fd: number, content: string | Buffer): void {\n\tconst buffer = typeof content === \"string\" ? Buffer.from(content, \"utf-8\") : content;\n\tlet written = 0;\n\twhile (written < buffer.length) {\n\t\twritten += writeSync(fd, buffer, written, buffer.length - written);\n\t}\n}\n\nfunction isMissingEntryError(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: unknown }).code === \"ENOENT\"\n\t);\n}\n\n/**\n * Walk every directory component of the authorized path no-follow, holding one\n * directory fd across the walk, then run the caller's final-component step against\n * that walked parent. Any intermediate that is not a real directory — a swapped\n * symlink, a removed component — aborts before the target is touched.\n */\nfunction withTargetDirectory<T>(\n\toperation: PreparedPathOperation,\n\toptions: { createMissingDirectories: boolean },\n\trun: (parent: OpenDirectory, name: string) => T,\n): T {\n\tconst root = parse(operation.path.value).root;\n\tconst components = operation.path.value\n\t\t.slice(root.length)\n\t\t.split(sep)\n\t\t.filter((component) => component.length > 0);\n\tconst name = components[components.length - 1];\n\tif (name === undefined) throw new PreparedTargetChangedError(\"Authorized path has no final component\");\n\tlet parent: OpenDirectory = { fd: openSync(root, constants.O_RDONLY | constants.O_DIRECTORY), path: root };\n\tconst closeParent = (): void => {\n\t\ttry {\n\t\t\tcloseSync(parent.fd);\n\t\t} catch {}\n\t};\n\tfor (const component of components.slice(0, -1)) {\n\t\ttry {\n\t\t\tparent = openChildDirectory(parent, component);\n\t\t} catch (error) {\n\t\t\tif (options.createMissingDirectories && isMissingEntryError(error)) {\n\t\t\t\ttry {\n\t\t\t\t\tmkdirUnder(parent, component);\n\t\t\t\t\tparent = openChildDirectory(parent, component);\n\t\t\t\t\tcontinue;\n\t\t\t\t} catch (mkdirError) {\n\t\t\t\t\tcloseParent();\n\t\t\t\t\tthrow new PreparedTargetChangedError(`Authorized write parent \"${component}\" changed before execution`, {\n\t\t\t\t\t\tcause: mkdirError,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tcloseParent();\n\t\t\tthrow new PreparedTargetChangedError(`Authorized path component \"${component}\" changed before execution`, {\n\t\t\t\tcause: error,\n\t\t\t});\n\t\t}\n\t}\n\ttry {\n\t\treturn run(parent, name);\n\t} finally {\n\t\tcloseParent();\n\t}\n}\n\n/**\n * Execute an authorized write against the prepared target.\n *\n * - `path-existing`: the final component is opened `O_NOFOLLOW`, its descriptor\n * identity is compared with the identity captured at authorization, and only\n * then is the file truncated and written through that descriptor. A swapped\n * alias, an injected symlink, or a redirected parent never matches and the\n * write aborts before any byte changes.\n * - `path-new`: missing parents are created no-follow under the walked directory\n * descriptor, and the file is created `O_CREAT | O_EXCL | O_NOFOLLOW`, so a\n * replaced parent or a pre-placed symlink is never followed.\n */\nexport function writePreparedPath(operation: PreparedPathOperation, content: string | Buffer): void {\n\twithTargetDirectory(operation, { createMissingDirectories: operation.kind === \"path-new\" }, (parent, name) => {\n\t\tif (operation.kind === \"path-existing\") {\n\t\t\tlet fd: number;\n\t\t\ttry {\n\t\t\t\tfd = openUnder(parent, name, constants.O_WRONLY | constants.O_NOFOLLOW);\n\t\t\t} catch (error) {\n\t\t\t\tthrow new PreparedTargetChangedError(\"Authorized write target changed before execution\", { cause: error });\n\t\t\t}\n\t\t\tlet mode: number;\n\t\t\ttry {\n\t\t\t\tconst stats = fstatSync(fd);\n\t\t\t\tverifyPreparedIdentity(\"write\", stats, operation.identity);\n\t\t\t\tmode = stats.mode & 0o7777;\n\t\t\t} finally {\n\t\t\t\tcloseSync(fd);\n\t\t\t}\n\t\t\tif (!publishByRename(parent, name, content, mode)) {\n\t\t\t\twriteInPlace(parent, name, content, operation.identity);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t// The exclusive create is what proves the name was still absent, which is the whole\n\t\t// authorization for a new-file write. It reserves the name; the rename below then\n\t\t// replaces that empty placeholder, so the name never holds a half-written file.\n\t\tlet fd: number;\n\t\ttry {\n\t\t\tfd = openUnder(\n\t\t\t\tparent,\n\t\t\t\tname,\n\t\t\t\tconstants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n\t\t\t\t0o600,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new PreparedTargetChangedError(\"Authorized new-file target changed before execution\", { cause: error });\n\t\t}\n\t\tcloseSync(fd);\n\t\ttry {\n\t\t\t// The reservation this just created is ours, so there is no prior identity to\n\t\t\t// re-check if Windows refuses the rename onto it.\n\t\t\tif (!publishByRename(parent, name, content, 0o600)) {\n\t\t\t\twriteInPlace(parent, name, content);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tunlinkUnder(parent, name);\n\t\t\tthrow error;\n\t\t}\n\t});\n}\n\n/**\n * Atomic publish for an ungated write, where no prepared operation exists to pin the target.\n *\n * `writePreparedPath` is the gated path and the one that matters; this is its counterpart for\n * a tool invoked outside the permission gate, so that neither route can leave a half-written\n * file. It makes no containment claim: with no authorization there is no authorized target to\n * hold the write to, and the no-follow walk would have nothing to check against.\n */\nexport function writePathAtomically(filePath: string, content: string | Buffer): void {\n\tconst temporary = join(dirname(filePath), stagingName(basename(filePath)));\n\t// Only an existing destination has a mode worth carrying. For a new file there is\n\t// nothing to capture, and chmod'ing to the 0o666 open default would force past the\n\t// caller's umask and publish a world-writable file, which `writeFile` never did.\n\tlet destinationMode: number | undefined;\n\ttry {\n\t\tdestinationMode = statSync(filePath).mode & 0o7777;\n\t} catch {}\n\tconst fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, destinationMode ?? 0o666);\n\ttry {\n\t\twriteAll(fd, content);\n\t\tif (destinationMode !== undefined) fchmodSync(fd, destinationMode);\n\t\tcloseSync(fd);\n\t} catch (error) {\n\t\ttry {\n\t\t\tcloseSync(fd);\n\t\t} catch {}\n\t\ttry {\n\t\t\tunlinkSync(temporary);\n\t\t} catch {}\n\t\tthrow error;\n\t}\n\ttry {\n\t\trenameSync(temporary, filePath);\n\t} catch (error) {\n\t\ttry {\n\t\t\tunlinkSync(temporary);\n\t\t} catch {}\n\t\t// Same Windows sharing case as the gated path, and the same answer: a file something\n\t\t// else has open is still a file the caller asked to write.\n\t\tif (!isWindowsSharingViolation(error)) throw error;\n\t\tconst fd = openSync(filePath, constants.O_WRONLY | constants.O_CREAT, destinationMode ?? 0o666);\n\t\ttry {\n\t\t\tftruncateSync(fd, 0);\n\t\t\twriteAll(fd, content);\n\t\t} finally {\n\t\t\tcloseSync(fd);\n\t\t}\n\t}\n}\n\nfunction tryMacOSScreenshotPath(filePath: string): string {\n\treturn filePath.replace(/ (AM|PM)\\./gi, `${NARROW_NO_BREAK_SPACE}$1.`);\n}\n\nfunction tryNFDVariant(filePath: string): string {\n\t// macOS stores filenames in NFD (decomposed) form, try converting user input to NFD\n\treturn filePath.normalize(\"NFD\");\n}\n\nfunction tryCurlyQuoteVariant(filePath: string): string {\n\t// macOS uses U+2019 (right single quotation mark) in screenshot names like \"Capture d'écran\"\n\t// Users typically type U+0027 (straight apostrophe)\n\treturn filePath.replace(/'/g, \"\\u2019\");\n}\n\nfunction fileExists(filePath: string): boolean {\n\ttry {\n\t\taccessSync(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport async function pathExists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait access(filePath, constants.F_OK);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function expandPath(filePath: string): string {\n\treturn normalizePath(filePath, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n}\n\n/**\n * Resolve a path relative to the given cwd, handling ~ expansion and absolute\n * paths. The result is the single target used by both permission matching and\n * filesystem execution.\n */\nexport function resolveToCwd(filePath: string, cwd: string): string {\n\tconst requested = resolvePath(filePath, cwd, { normalizeUnicodeSpaces: true, stripAtPrefix: true });\n\ttry {\n\t\treturn realpathSync(requested);\n\t} catch {\n\t\ttry {\n\t\t\treturn joinCanonicalParent(requested);\n\t\t} catch {\n\t\t\treturn requested;\n\t\t}\n\t}\n}\n\nfunction joinCanonicalParent(requested: string): string {\n\treturn join(realpathSync(dirname(requested)), basename(requested));\n}\n\nexport function resolveReadPath(filePath: string, cwd: string): string {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (fileExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && fileExists(amPmVariant)) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && fileExists(nfdVariant)) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && fileExists(curlyVariant)) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && fileExists(nfdCurlyVariant)) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n\nexport async function resolveReadPathAsync(filePath: string, cwd: string): Promise<string> {\n\tconst resolved = resolveToCwd(filePath, cwd);\n\n\tif (await pathExists(resolved)) {\n\t\treturn resolved;\n\t}\n\n\t// Try macOS AM/PM variant (narrow no-break space before AM/PM)\n\tconst amPmVariant = tryMacOSScreenshotPath(resolved);\n\tif (amPmVariant !== resolved && (await pathExists(amPmVariant))) {\n\t\treturn amPmVariant;\n\t}\n\n\t// Try NFD variant (macOS stores filenames in NFD form)\n\tconst nfdVariant = tryNFDVariant(resolved);\n\tif (nfdVariant !== resolved && (await pathExists(nfdVariant))) {\n\t\treturn nfdVariant;\n\t}\n\n\t// Try curly quote variant (macOS uses U+2019 in screenshot names)\n\tconst curlyVariant = tryCurlyQuoteVariant(resolved);\n\tif (curlyVariant !== resolved && (await pathExists(curlyVariant))) {\n\t\treturn curlyVariant;\n\t}\n\n\t// Try combined NFD + curly quote (for French macOS screenshots like \"Capture d'écran\")\n\tconst nfdCurlyVariant = tryCurlyQuoteVariant(nfdVariant);\n\tif (nfdCurlyVariant !== resolved && (await pathExists(nfdCurlyVariant))) {\n\t\treturn nfdCurlyVariant;\n\t}\n\n\treturn resolved;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAGtD,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAU5C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAKxD,OAAO,EAAoD,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEtH,QAAA,MAAM,UAAU;;;;EAId,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC9B;AASD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,qCAAqC;IACrC,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,+CAA+C;IAC/C,MAAM,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,sEAAsE;IACtE,mBAAmB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;CACnF;AAQD,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B;AA4ID,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,kBAAkB,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAgKpE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport type { AgentTool } from \"apex-code-agent-core\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"../../config.ts\";\nimport { keyHint, keyText } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { detectSupportedImageMimeType, detectSupportedImageMimeTypeFromFile } from \"../../utils/mime.ts\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"../../utils/paths.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { getPreparedPathOperation } from \"../permissions/operations.ts\";\nimport type { ApexToolDefinition } from \"./contract.ts\";\nimport { createPathPermissionSpec } from \"./path-permission.ts\";\nimport { readPreparedPath, resolveReadPathAsync, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport const readToolSystemPromptContribution = {\n\tsnippet: \"Read file contents\",\n\tguidelines: [\"Use read to examine files instead of cat or sed.\"],\n} as const;\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n}\n\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\n\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.override.md\", \"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise<void>;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: number; limit?: number };\n\nfunction formatReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tif (args?.offset === undefined && args?.limit === undefined) return \"\";\n\tconst startLine = args.offset ?? 1;\n\tconst endLine = args.limit !== undefined ? startLine + args.limit - 1 : \"\";\n\treturn theme.fg(\"warning\", `:${startLine}${endLine ? `-${endLine}` : \"\"}`);\n}\n\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction getNonVisionImageNote(model: Model<Api> | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\n\nfunction getPiDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\n\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\n\treturn undefined;\n}\n\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} to expand)`);\n\tif (classification.kind === \"skill\") {\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\n\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: { content: (TextContent | ImageContent)[]; details?: ReadToolDetails },\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\t_cwd: string,\n\tisError: boolean,\n): string {\n\tif (!options.expanded && !isError) {\n\t\treturn \"\";\n\t}\n\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tconst lang = !isError && rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : 10;\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - maxLines;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t}\n\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t\t} else {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n\t\t}\n\t}\n\treturn text;\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ApexToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: readToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...readToolSystemPromptContribution.guidelines],\n\t\tparameters: readSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"fs.read\"]),\n\t\t\tpermission: createPathPermissionSpec({\n\t\t\t\tcwd,\n\t\t\t\tdefaultBehavior: \"allow\",\n\t\t\t\tverb: \"Read\",\n\t\t\t\tgetPath: (params) => params.path,\n\t\t\t}),\n\t\t\tcontext: { resultRecoverable: true, deferSchema: false },\n\t\t\tevidence: { emits: new Set(), capture: () => [] },\n\t\t},\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\tinput: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?,\n\t\t) {\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst { path, offset, limit } = input;\n\t\t\t\t\t\t\tconst prepared = getPreparedPathOperation(input);\n\t\t\t\t\t\t\tconst absolutePath = prepared?.path.value ?? (await resolveReadPathAsync(path, cwd));\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tif (!prepared) await ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tconst buffer = prepared ? await readPreparedPath(prepared) : undefined;\n\t\t\t\t\t\t\t// A gated read detects the MIME type from the already-verified bytes,\n\t\t\t\t\t\t\t// so no secondary unverified pathname open happens after authorization.\n\t\t\t\t\t\t\tconst mimeType = prepared\n\t\t\t\t\t\t\t\t? detectSupportedImageMimeType(buffer!)\n\t\t\t\t\t\t\t\t: ops.detectImageMimeType\n\t\t\t\t\t\t\t\t\t? await ops.detectImageMimeType(absolutePath)\n\t\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst imageBuffer = buffer ?? (await ops.readFile(absolutePath));\n\t\t\t\t\t\t\t\tconst processed = await processImage(imageBuffer, mimeType, { autoResizeImages });\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read text content.\n\t\t\t\t\t\t\t\tconst textContent = (buffer ?? (await ops.readFile(absolutePath))).toString(\"utf-8\");\n\t\t\t\t\t\t\t\tconst allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\t// Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Offset ${offset} is beyond end of file (${allLines.length} lines total)`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet selectedContent: string;\n\t\t\t\t\t\t\t\tlet userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\t// If limit is specified by the user, honor it first. Otherwise truncateHead decides.\n\t\t\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + limit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine, endLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t\tuserLimitedLines = endLine - startLine;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Apply truncation, respecting both line and byte limits.\n\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], \"utf-8\"));\n\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\ttext.setText(\n\t\t\t\tclassification\n\t\t\t\t\t? formatCompactReadCall(classification, args, theme)\n\t\t\t\t\t: formatReadCall(args, theme, context.cwd),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../../src/core/tools/read.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAGtD,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAU5C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAKxD,OAAO,EAAoD,KAAK,gBAAgB,EAAgB,MAAM,eAAe,CAAC;AAEtH,QAAA,MAAM,UAAU;;;;EAId,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAEtD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC9B;AASD;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC9B,qCAAqC;IACrC,QAAQ,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,+CAA+C;IAC/C,MAAM,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAChD,sEAAsE;IACtE,mBAAmB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;CACnF;AAQD,MAAM,WAAW,eAAe;IAC/B,oEAAoE;IACpE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,oEAAoE;IACpE,UAAU,CAAC,EAAE,cAAc,CAAC;CAC5B;AA8ID,wBAAgB,wBAAwB,CACvC,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,eAAe,GACvB,kBAAkB,CAAC,OAAO,UAAU,EAAE,eAAe,GAAG,SAAS,CAAC,CAgKpE;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAEnG","sourcesContent":["import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport type { Api, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport type { AgentTool } from \"apex-code-agent-core\";\nimport { constants } from \"fs\";\nimport { access as fsAccess, readFile as fsReadFile } from \"fs/promises\";\nimport { type Static, Type } from \"typebox\";\nimport { getReadmePath } from \"../../config.ts\";\nimport { formatHiddenLines, keyText, previewLineCount } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getLanguageFromPath, highlightCode, type Theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { processImage } from \"../../utils/image-process.ts\";\nimport { detectSupportedImageMimeType, detectSupportedImageMimeTypeFromFile } from \"../../utils/mime.ts\";\nimport { formatPathRelativeToCwdOrAbsolute } from \"../../utils/paths.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { getPreparedPathOperation } from \"../permissions/operations.ts\";\nimport type { ApexToolDefinition } from \"./contract.ts\";\nimport { createPathPermissionSpec } from \"./path-permission.ts\";\nimport { readPreparedPath, resolveReadPathAsync, resolveToCwd } from \"./path-utils.ts\";\nimport { getTextOutput, renderToolPath, replaceTabs, str } from \"./render-utils.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateHead } from \"./truncate.ts\";\n\nconst readSchema = Type.Object({\n\tpath: Type.String({ description: \"Path to the file to read (relative or absolute)\" }),\n\toffset: Type.Optional(Type.Number({ description: \"Line number to start reading from (1-indexed)\" })),\n\tlimit: Type.Optional(Type.Number({ description: \"Maximum number of lines to read\" })),\n});\n\nexport const readToolSystemPromptContribution = {\n\tsnippet: \"Read file contents\",\n\tguidelines: [\"Use read to examine files instead of cat or sed.\"],\n} as const;\n\nexport type ReadToolInput = Static<typeof readSchema>;\n\nexport interface ReadToolDetails {\n\ttruncation?: TruncationResult;\n}\n\ninterface CompactReadClassification {\n\tkind: \"docs\" | \"resource\" | \"skill\";\n\tlabel: string;\n}\n\nconst COMPACT_RESOURCE_FILE_NAMES = new Set([\"AGENTS.override.md\", \"AGENTS.md\", \"AGENTS.MD\", \"CLAUDE.md\", \"CLAUDE.MD\"]);\n\n/**\n * Pluggable operations for the read tool.\n * Override these to delegate file reading to remote systems (for example SSH).\n */\nexport interface ReadOperations {\n\t/** Read file contents as a Buffer */\n\treadFile: (absolutePath: string) => Promise<Buffer>;\n\t/** Check if file is readable (throw if not) */\n\taccess: (absolutePath: string) => Promise<void>;\n\t/** Detect image MIME type, return null or undefined for non-images */\n\tdetectImageMimeType?: (absolutePath: string) => Promise<string | null | undefined>;\n}\n\nconst defaultReadOperations: ReadOperations = {\n\treadFile: (path) => fsReadFile(path),\n\taccess: (path) => fsAccess(path, constants.R_OK),\n\tdetectImageMimeType: detectSupportedImageMimeTypeFromFile,\n};\n\nexport interface ReadToolOptions {\n\t/** Whether to auto-resize images to 2000x2000 max. Default: true */\n\tautoResizeImages?: boolean;\n\t/** Custom operations for file reading. Default: local filesystem */\n\toperations?: ReadOperations;\n}\n\ntype ReadRenderArgs = { path?: string; file_path?: string; offset?: number; limit?: number };\n\nfunction formatReadLineRange(args: ReadRenderArgs | undefined, theme: Theme): string {\n\tif (args?.offset === undefined && args?.limit === undefined) return \"\";\n\tconst startLine = args.offset ?? 1;\n\tconst endLine = args.limit !== undefined ? startLine + args.limit - 1 : \"\";\n\treturn theme.fg(\"warning\", `:${startLine}${endLine ? `-${endLine}` : \"\"}`);\n}\n\nfunction formatReadCall(args: ReadRenderArgs | undefined, theme: Theme, cwd: string): string {\n\tconst pathDisplay = renderToolPath(str(args?.file_path ?? args?.path), theme, cwd);\n\treturn `${theme.fg(\"toolTitle\", theme.bold(\"read\"))} ${pathDisplay}${formatReadLineRange(args, theme)}`;\n}\n\nfunction trimTrailingEmptyLines(lines: string[]): string[] {\n\tlet end = lines.length;\n\twhile (end > 0 && lines[end - 1] === \"\") {\n\t\tend--;\n\t}\n\treturn lines.slice(0, end);\n}\n\nfunction getNonVisionImageNote(model: Model<Api> | undefined): string | undefined {\n\tif (!model || model.input.includes(\"image\")) {\n\t\treturn undefined;\n\t}\n\treturn \"[Current model does not support images. The image will be omitted from this request.]\";\n}\n\nfunction toPosixPath(filePath: string): string {\n\treturn filePath.split(sep).join(\"/\");\n}\n\nfunction getPiDocsClassification(absolutePath: string): CompactReadClassification | undefined {\n\tconst packageRoot = dirname(getReadmePath());\n\tconst relativePath = relative(resolvePath(packageRoot), resolvePath(absolutePath));\n\tif (\n\t\trelativePath === \"\" ||\n\t\trelativePath === \"..\" ||\n\t\trelativePath.startsWith(`..${sep}`) ||\n\t\tisAbsolute(relativePath)\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst label = toPosixPath(relativePath);\n\tif (label === \"README.md\" || label.startsWith(\"docs/\") || label.startsWith(\"examples/\")) {\n\t\treturn { kind: \"docs\", label };\n\t}\n\treturn undefined;\n}\n\nfunction getCompactReadClassification(\n\targs: ReadRenderArgs | undefined,\n\tcwd: string,\n): CompactReadClassification | undefined {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tif (!rawPath) return undefined;\n\n\tconst absolutePath = resolveToCwd(rawPath, cwd);\n\tconst fileName = basename(absolutePath);\n\tif (fileName === \"SKILL.md\") {\n\t\treturn { kind: \"skill\", label: basename(dirname(absolutePath)) || fileName };\n\t}\n\n\tconst docsClassification = getPiDocsClassification(absolutePath);\n\tif (docsClassification) return docsClassification;\n\n\tif (COMPACT_RESOURCE_FILE_NAMES.has(fileName)) {\n\t\treturn { kind: \"resource\", label: formatPathRelativeToCwdOrAbsolute(absolutePath, cwd) };\n\t}\n\n\treturn undefined;\n}\n\nfunction formatCompactReadCall(\n\tclassification: CompactReadClassification,\n\targs: ReadRenderArgs | undefined,\n\ttheme: Theme,\n): string {\n\tconst expandHint = theme.fg(\"dim\", ` (${keyText(\"app.tools.expand\")} to expand)`);\n\tif (classification.kind === \"skill\") {\n\t\treturn (\n\t\t\ttheme.fg(\"customMessageLabel\", `\\x1b[1m[skill]\\x1b[22m `) +\n\t\t\ttheme.fg(\"customMessageText\", classification.label) +\n\t\t\tformatReadLineRange(args, theme) +\n\t\t\texpandHint\n\t\t);\n\t}\n\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(`read ${classification.kind}`)) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", classification.label) +\n\t\tformatReadLineRange(args, theme) +\n\t\texpandHint\n\t);\n}\n\nfunction formatReadResult(\n\targs: ReadRenderArgs | undefined,\n\tresult: { content: (TextContent | ImageContent)[]; details?: ReadToolDetails },\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tshowImages: boolean,\n\tcwd: string,\n\tisError: boolean,\n): string {\n\tconst rawPath = str(args?.file_path ?? args?.path);\n\tconst output = getTextOutput(result, showImages);\n\tif (!options.expanded && !isError) {\n\t\t// A compact read names its expand key in the call row already.\n\t\tif (getCompactReadClassification(args, cwd)) return \"\";\n\t\treturn `\\n${formatHiddenLines(trimTrailingEmptyLines(output.split(\"\\n\")).length, \"all\")}`;\n\t}\n\n\tconst lang = !isError && rawPath ? getLanguageFromPath(rawPath) : undefined;\n\tconst renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split(\"\\n\");\n\tconst lines = trimTrailingEmptyLines(renderedLines);\n\tconst maxLines = options.expanded ? lines.length : previewLineCount(lines.length, 10);\n\tconst displayLines = lines.slice(0, maxLines);\n\tconst remaining = lines.length - displayLines.length;\n\tlet text = `\\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg(\"toolOutput\", replaceTabs(line)))).join(\"\\n\")}`;\n\tif (remaining > 0) {\n\t\ttext += `\\n${formatHiddenLines(remaining, \"more\")}`;\n\t}\n\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[First line exceeds ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines (${truncation.maxLines ?? DEFAULT_MAX_LINES} line limit)]`)}`;\n\t\t} else {\n\t\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)]`)}`;\n\t\t}\n\t}\n\treturn text;\n}\n\nexport function createReadToolDefinition(\n\tcwd: string,\n\toptions?: ReadToolOptions,\n): ApexToolDefinition<typeof readSchema, ReadToolDetails | undefined> {\n\tconst autoResizeImages = options?.autoResizeImages ?? true;\n\tconst ops = options?.operations ?? defaultReadOperations;\n\treturn {\n\t\tname: \"read\",\n\t\tlabel: \"read\",\n\t\tdescription: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,\n\t\tpromptSnippet: readToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...readToolSystemPromptContribution.guidelines],\n\t\tparameters: readSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"fs.read\"]),\n\t\t\tpermission: createPathPermissionSpec({\n\t\t\t\tcwd,\n\t\t\t\tdefaultBehavior: \"allow\",\n\t\t\t\tverb: \"Read\",\n\t\t\t\tgetPath: (params) => params.path,\n\t\t\t}),\n\t\t\tcontext: { resultRecoverable: true, deferSchema: false },\n\t\t\tevidence: { emits: new Set(), capture: () => [] },\n\t\t},\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(\n\t\t\t_toolCallId,\n\t\t\tinput: { path: string; offset?: number; limit?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t\t_onUpdate?,\n\t\t\tctx?,\n\t\t) {\n\t\t\treturn new Promise<{ content: (TextContent | ImageContent)[]; details: ReadToolDetails | undefined }>(\n\t\t\t\t(resolve, reject) => {\n\t\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlet aborted = false;\n\t\t\t\t\tconst onAbort = () => {\n\t\t\t\t\t\taborted = true;\n\t\t\t\t\t\treject(new Error(\"Operation aborted\"));\n\t\t\t\t\t};\n\t\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\t\t\t\t(async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst { path, offset, limit } = input;\n\t\t\t\t\t\t\tconst prepared = getPreparedPathOperation(input);\n\t\t\t\t\t\t\tconst absolutePath = prepared?.path.value ?? (await resolveReadPathAsync(path, cwd));\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tif (!prepared) await ops.access(absolutePath);\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tconst buffer = prepared ? await readPreparedPath(prepared) : undefined;\n\t\t\t\t\t\t\t// A gated read detects the MIME type from the already-verified bytes,\n\t\t\t\t\t\t\t// so no secondary unverified pathname open happens after authorization.\n\t\t\t\t\t\t\tconst mimeType = prepared\n\t\t\t\t\t\t\t\t? detectSupportedImageMimeType(buffer!)\n\t\t\t\t\t\t\t\t: ops.detectImageMimeType\n\t\t\t\t\t\t\t\t\t? await ops.detectImageMimeType(absolutePath)\n\t\t\t\t\t\t\t\t\t: undefined;\n\t\t\t\t\t\t\tlet content: (TextContent | ImageContent)[];\n\t\t\t\t\t\t\tlet details: ReadToolDetails | undefined;\n\t\t\t\t\t\t\tconst nonVisionImageNote = getNonVisionImageNote(ctx?.model);\n\t\t\t\t\t\t\tif (mimeType) {\n\t\t\t\t\t\t\t\t// Read image as binary.\n\t\t\t\t\t\t\t\tconst imageBuffer = buffer ?? (await ops.readFile(absolutePath));\n\t\t\t\t\t\t\t\tconst processed = await processImage(imageBuffer, mimeType, { autoResizeImages });\n\t\t\t\t\t\t\t\tif (!processed.ok) {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${mimeType}]\\n${processed.message}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: textNote }];\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tlet textNote = `Read image file [${processed.mimeType}]`;\n\t\t\t\t\t\t\t\t\tif (processed.hints.length > 0) textNote += `\\n${processed.hints.join(\"\\n\")}`;\n\t\t\t\t\t\t\t\t\tif (nonVisionImageNote) textNote += `\\n${nonVisionImageNote}`;\n\t\t\t\t\t\t\t\t\tcontent = [\n\t\t\t\t\t\t\t\t\t\t{ type: \"text\", text: textNote },\n\t\t\t\t\t\t\t\t\t\t{ type: \"image\", data: processed.data, mimeType: processed.mimeType },\n\t\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Read text content.\n\t\t\t\t\t\t\t\tconst textContent = (buffer ?? (await ops.readFile(absolutePath))).toString(\"utf-8\");\n\t\t\t\t\t\t\t\tconst allLines = textContent.split(\"\\n\");\n\t\t\t\t\t\t\t\tconst totalFileLines = allLines.length;\n\t\t\t\t\t\t\t\t// Apply offset if specified. Convert from 1-indexed input to 0-indexed array access.\n\t\t\t\t\t\t\t\tconst startLine = offset ? Math.max(0, offset - 1) : 0;\n\t\t\t\t\t\t\t\tconst startLineDisplay = startLine + 1;\n\t\t\t\t\t\t\t\t// Check if offset is out of bounds.\n\t\t\t\t\t\t\t\tif (startLine >= allLines.length) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`Offset ${offset} is beyond end of file (${allLines.length} lines total)`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tlet selectedContent: string;\n\t\t\t\t\t\t\t\tlet userLimitedLines: number | undefined;\n\t\t\t\t\t\t\t\t// If limit is specified by the user, honor it first. Otherwise truncateHead decides.\n\t\t\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\t\t\tconst endLine = Math.min(startLine + limit, allLines.length);\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine, endLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t\tuserLimitedLines = endLine - startLine;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tselectedContent = allLines.slice(startLine).join(\"\\n\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// Apply truncation, respecting both line and byte limits.\n\t\t\t\t\t\t\t\tconst truncation = truncateHead(selectedContent);\n\t\t\t\t\t\t\t\tlet outputText: string;\n\t\t\t\t\t\t\t\tif (truncation.firstLineExceedsLimit) {\n\t\t\t\t\t\t\t\t\t// First line alone exceeds the byte limit. Point the model at a bash fallback.\n\t\t\t\t\t\t\t\t\tconst firstLineSize = formatSize(Buffer.byteLength(allLines[startLine], \"utf-8\"));\n\t\t\t\t\t\t\t\t\toutputText = `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${DEFAULT_MAX_BYTES}]`;\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (truncation.truncated) {\n\t\t\t\t\t\t\t\t\t// Truncation occurred. Build an actionable continuation notice.\n\t\t\t\t\t\t\t\t\tconst endLineDisplay = startLineDisplay + truncation.outputLines - 1;\n\t\t\t\t\t\t\t\t\tconst nextOffset = endLineDisplay + 1;\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdetails = { truncation };\n\t\t\t\t\t\t\t\t} else if (userLimitedLines !== undefined && startLine + userLimitedLines < allLines.length) {\n\t\t\t\t\t\t\t\t\t// User-specified limit stopped early, but the file still has more content.\n\t\t\t\t\t\t\t\t\tconst remaining = allLines.length - (startLine + userLimitedLines);\n\t\t\t\t\t\t\t\t\tconst nextOffset = startLine + userLimitedLines + 1;\n\t\t\t\t\t\t\t\t\toutputText = `${truncation.content}\\n\\n[${remaining} more lines in file. Use offset=${nextOffset} to continue.]`;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// No truncation and no remaining user-limited content.\n\t\t\t\t\t\t\t\t\toutputText = truncation.content;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontent = [{ type: \"text\", text: outputText }];\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (aborted) return;\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tresolve({ content, details });\n\t\t\t\t\t\t} catch (error: any) {\n\t\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\t\tif (!aborted) reject(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t})();\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\tconst classification = !context.expanded ? getCompactReadClassification(args, context.cwd) : undefined;\n\t\t\ttext.setText(\n\t\t\t\tclassification\n\t\t\t\t\t? formatCompactReadCall(classification, args, theme)\n\t\t\t\t\t: formatReadCall(args, theme, context.cwd),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(\n\t\t\t\tformatReadResult(context.args, result, options, theme, context.showImages, context.cwd, context.isError),\n\t\t\t);\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createReadTool(cwd: string, options?: ReadToolOptions): AgentTool<typeof readSchema> {\n\treturn wrapToolDefinition(createReadToolDefinition(cwd, options));\n}\n"]}
|
package/dist/core/tools/read.js
CHANGED
|
@@ -4,7 +4,7 @@ import { constants } from "fs";
|
|
|
4
4
|
import { access as fsAccess, readFile as fsReadFile } from "fs/promises";
|
|
5
5
|
import { Type } from "typebox";
|
|
6
6
|
import { getReadmePath } from "../../config.js";
|
|
7
|
-
import {
|
|
7
|
+
import { formatHiddenLines, keyText, previewLineCount } from "../../modes/interactive/components/keybinding-hints.js";
|
|
8
8
|
import { getLanguageFromPath, highlightCode } from "../../modes/interactive/theme/theme.js";
|
|
9
9
|
import { processImage } from "../../utils/image-process.js";
|
|
10
10
|
import { detectSupportedImageMimeType, detectSupportedImageMimeTypeFromFile } from "../../utils/mime.js";
|
|
@@ -104,21 +104,24 @@ function formatCompactReadCall(classification, args, theme) {
|
|
|
104
104
|
formatReadLineRange(args, theme) +
|
|
105
105
|
expandHint);
|
|
106
106
|
}
|
|
107
|
-
function formatReadResult(args, result, options, theme, showImages,
|
|
108
|
-
if (!options.expanded && !isError) {
|
|
109
|
-
return "";
|
|
110
|
-
}
|
|
107
|
+
function formatReadResult(args, result, options, theme, showImages, cwd, isError) {
|
|
111
108
|
const rawPath = str(args?.file_path ?? args?.path);
|
|
112
109
|
const output = getTextOutput(result, showImages);
|
|
110
|
+
if (!options.expanded && !isError) {
|
|
111
|
+
// A compact read names its expand key in the call row already.
|
|
112
|
+
if (getCompactReadClassification(args, cwd))
|
|
113
|
+
return "";
|
|
114
|
+
return `\n${formatHiddenLines(trimTrailingEmptyLines(output.split("\n")).length, "all")}`;
|
|
115
|
+
}
|
|
113
116
|
const lang = !isError && rawPath ? getLanguageFromPath(rawPath) : undefined;
|
|
114
117
|
const renderedLines = lang ? highlightCode(replaceTabs(output), lang) : output.split("\n");
|
|
115
118
|
const lines = trimTrailingEmptyLines(renderedLines);
|
|
116
|
-
const maxLines = options.expanded ? lines.length : 10;
|
|
119
|
+
const maxLines = options.expanded ? lines.length : previewLineCount(lines.length, 10);
|
|
117
120
|
const displayLines = lines.slice(0, maxLines);
|
|
118
|
-
const remaining = lines.length -
|
|
121
|
+
const remaining = lines.length - displayLines.length;
|
|
119
122
|
let text = `\n${displayLines.map((line) => (lang ? replaceTabs(line) : theme.fg("toolOutput", replaceTabs(line)))).join("\n")}`;
|
|
120
123
|
if (remaining > 0) {
|
|
121
|
-
text +=
|
|
124
|
+
text += `\n${formatHiddenLines(remaining, "more")}`;
|
|
122
125
|
}
|
|
123
126
|
const truncation = result.details?.truncation;
|
|
124
127
|
if (truncation?.truncated) {
|