@j0hanz/filesystem-mcp 2.3.0 → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -8
- package/dist/cli-help.d.ts.map +1 -1
- package/dist/cli-help.js +14 -41
- package/dist/cli-help.js.map +1 -1
- package/dist/cli.d.ts +0 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +14 -41
- package/dist/cli.js.map +1 -1
- package/dist/core/concurrency.d.ts +5 -17
- package/dist/core/concurrency.d.ts.map +1 -1
- package/dist/core/concurrency.js +11 -34
- package/dist/core/concurrency.js.map +1 -1
- package/dist/core/cursor.d.ts +1 -12
- package/dist/core/cursor.d.ts.map +1 -1
- package/dist/core/cursor.js +2 -12
- package/dist/core/cursor.js.map +1 -1
- package/dist/core/errors.d.ts +0 -2
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +6 -17
- package/dist/core/errors.js.map +1 -1
- package/dist/core/file-uri.d.ts +2 -2
- package/dist/core/file-uri.js +3 -3
- package/dist/core/file-uri.js.map +1 -1
- package/dist/core/fmt.d.ts +0 -10
- package/dist/core/fmt.d.ts.map +1 -1
- package/dist/core/fmt.js +1 -18
- package/dist/core/fmt.js.map +1 -1
- package/dist/core/fs.d.ts +3 -3
- package/dist/core/fs.d.ts.map +1 -1
- package/dist/core/fs.js +9 -10
- package/dist/core/fs.js.map +1 -1
- package/dist/core/glob.d.ts +1 -2
- package/dist/core/glob.d.ts.map +1 -1
- package/dist/core/glob.js +9 -20
- package/dist/core/glob.js.map +1 -1
- package/dist/core/input-required.d.ts +15 -16
- package/dist/core/input-required.d.ts.map +1 -1
- package/dist/core/input-required.js +34 -34
- package/dist/core/input-required.js.map +1 -1
- package/dist/core/observability.js +2 -2
- package/dist/core/observability.js.map +1 -1
- package/dist/core/path-completer.d.ts +6 -9
- package/dist/core/path-completer.d.ts.map +1 -1
- package/dist/core/path-completer.js +28 -55
- package/dist/core/path-completer.js.map +1 -1
- package/dist/core/path-discovery.d.ts.map +1 -1
- package/dist/core/path-discovery.js +3 -4
- package/dist/core/path-discovery.js.map +1 -1
- package/dist/core/path-utils.d.ts +28 -0
- package/dist/core/path-utils.d.ts.map +1 -1
- package/dist/core/path-utils.js +57 -2
- package/dist/core/path-utils.js.map +1 -1
- package/dist/core/path.d.ts +3 -8
- package/dist/core/path.d.ts.map +1 -1
- package/dist/core/path.js +8 -9
- package/dist/core/path.js.map +1 -1
- package/dist/core/read.d.ts +3 -22
- package/dist/core/read.d.ts.map +1 -1
- package/dist/core/read.js +46 -96
- package/dist/core/read.js.map +1 -1
- package/dist/core/schema.d.ts +8 -9
- package/dist/core/schema.d.ts.map +1 -1
- package/dist/core/schema.js +11 -14
- package/dist/core/schema.js.map +1 -1
- package/dist/core/search.d.ts +1 -1
- package/dist/core/search.d.ts.map +1 -1
- package/dist/core/search.js +3 -4
- package/dist/core/search.js.map +1 -1
- package/dist/core/sensitive.d.ts.map +1 -1
- package/dist/core/sensitive.js +4 -5
- package/dist/core/sensitive.js.map +1 -1
- package/dist/core/store.d.ts +41 -16
- package/dist/core/store.d.ts.map +1 -1
- package/dist/core/store.js +147 -82
- package/dist/core/store.js.map +1 -1
- package/dist/core/util.d.ts +3 -2
- package/dist/core/util.d.ts.map +1 -1
- package/dist/core/util.js +5 -6
- package/dist/core/util.js.map +1 -1
- package/dist/core/watcher-registry.d.ts +1 -1
- package/dist/core/watcher-registry.js +4 -4
- package/dist/core/watcher-registry.js.map +1 -1
- package/dist/index.js +5 -6
- package/dist/index.js.map +1 -1
- package/dist/instructions.js +2 -2
- package/dist/instructions.js.map +1 -1
- package/dist/prompts.js +1 -1
- package/dist/prompts.js.map +1 -1
- package/dist/resources.d.ts +11 -19
- package/dist/resources.d.ts.map +1 -1
- package/dist/resources.js +39 -59
- package/dist/resources.js.map +1 -1
- package/dist/server.d.ts +4 -5
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +8 -9
- package/dist/server.js.map +1 -1
- package/dist/tools/batch.d.ts +2 -2
- package/dist/tools/batch.js +3 -3
- package/dist/tools/batch.js.map +1 -1
- package/dist/tools/create.d.ts +1 -1
- package/dist/tools/create.js +17 -15
- package/dist/tools/create.js.map +1 -1
- package/dist/tools/define.d.ts +10 -9
- package/dist/tools/define.d.ts.map +1 -1
- package/dist/tools/define.js +26 -92
- package/dist/tools/define.js.map +1 -1
- package/dist/tools/delete.d.ts +1 -1
- package/dist/tools/delete.js +16 -13
- package/dist/tools/delete.js.map +1 -1
- package/dist/tools/diff.d.ts +1 -1
- package/dist/tools/diff.d.ts.map +1 -1
- package/dist/tools/diff.js +7 -37
- package/dist/tools/diff.js.map +1 -1
- package/dist/tools/edit.d.ts +1 -1
- package/dist/tools/edit.d.ts.map +1 -1
- package/dist/tools/edit.js +27 -26
- package/dist/tools/edit.js.map +1 -1
- package/dist/tools/find-files.d.ts +1 -1
- package/dist/tools/find-files.d.ts.map +1 -1
- package/dist/tools/find-files.js +18 -37
- package/dist/tools/find-files.js.map +1 -1
- package/dist/tools/index.d.ts +9 -10
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +13 -13
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/list-roots.d.ts +1 -1
- package/dist/tools/list-roots.js +3 -3
- package/dist/tools/list-roots.js.map +1 -1
- package/dist/tools/list.d.ts +1 -1
- package/dist/tools/list.d.ts.map +1 -1
- package/dist/tools/list.js +23 -29
- package/dist/tools/list.js.map +1 -1
- package/dist/tools/move.d.ts +1 -1
- package/dist/tools/move.js +18 -13
- package/dist/tools/move.js.map +1 -1
- package/dist/tools/patch.d.ts +1 -1
- package/dist/tools/patch.js +4 -4
- package/dist/tools/patch.js.map +1 -1
- package/dist/tools/progress.d.ts +17 -28
- package/dist/tools/progress.d.ts.map +1 -1
- package/dist/tools/progress.js +42 -94
- package/dist/tools/progress.js.map +1 -1
- package/dist/tools/read.d.ts +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +10 -12
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/replace-text.d.ts +1 -1
- package/dist/tools/replace-text.d.ts.map +1 -1
- package/dist/tools/replace-text.js +32 -49
- package/dist/tools/replace-text.js.map +1 -1
- package/dist/tools/search-text.d.ts +1 -1
- package/dist/tools/search-text.d.ts.map +1 -1
- package/dist/tools/search-text.js +19 -45
- package/dist/tools/search-text.js.map +1 -1
- package/dist/tools/stat.d.ts +1 -1
- package/dist/tools/stat.d.ts.map +1 -1
- package/dist/tools/stat.js +9 -29
- package/dist/tools/stat.js.map +1 -1
- package/dist/transport/http-policy.js +4 -4
- package/dist/transport/http-policy.js.map +1 -1
- package/dist/transport/http.d.ts +2 -2
- package/dist/transport/http.d.ts.map +1 -1
- package/dist/transport/http.js +16 -17
- package/dist/transport/http.js.map +1 -1
- package/dist/transport/shared.d.ts +2 -2
- package/dist/transport/shared.js +2 -2
- package/dist/transport/shared.js.map +1 -1
- package/dist/transport/stdio.d.ts +3 -3
- package/dist/transport/stdio.js +6 -6
- package/dist/transport/stdio.js.map +1 -1
- package/dist/transport.d.ts +2 -2
- package/dist/transport.js +2 -2
- package/dist/transport.js.map +1 -1
- package/package.json +3 -7
- package/dist/core/page-store.d.ts +0 -42
- package/dist/core/page-store.d.ts.map +0 -1
- package/dist/core/page-store.js +0 -75
- package/dist/core/page-store.js.map +0 -1
- package/dist/core/primitives.d.ts +0 -34
- package/dist/core/primitives.d.ts.map +0 -1
- package/dist/core/primitives.js +0 -63
- package/dist/core/primitives.js.map +0 -1
package/dist/tools/progress.js
CHANGED
|
@@ -1,120 +1,74 @@
|
|
|
1
|
-
import { formatUnknownErrorMessage } from
|
|
2
|
-
import { Logger } from
|
|
3
|
-
function reportDetachedError(toolName, context, error) {
|
|
4
|
-
const message = formatUnknownErrorMessage(error);
|
|
5
|
-
Logger.emit('warning', `${toolName}: ${context} failed: ${message}`);
|
|
6
|
-
}
|
|
1
|
+
import { formatUnknownErrorMessage } from "../core/errors.js";
|
|
2
|
+
import { Logger } from "../core/observability.js";
|
|
7
3
|
const DEFAULT_RATE_LIMIT_MS = 50;
|
|
4
|
+
/**
|
|
5
|
+
* One tool call's progress stream: a monotonic cursor, a tick rate limit, and
|
|
6
|
+
* the wire guard the spec requires (`progress` strictly increases per token).
|
|
7
|
+
* Terminal frames (`complete`, `fail`) always reach the wire — they carry the
|
|
8
|
+
* outcome message — so they advance past the last value instead of dropping.
|
|
9
|
+
*/
|
|
8
10
|
export class ProgressSession {
|
|
9
11
|
#label;
|
|
10
12
|
#sink;
|
|
11
13
|
#rateLimitMs;
|
|
12
14
|
#startTime;
|
|
15
|
+
#pending = new Set();
|
|
13
16
|
#cursor = 0;
|
|
14
17
|
#lastSentMs = 0;
|
|
18
|
+
#lastProgress = -1;
|
|
15
19
|
#done = false;
|
|
16
20
|
constructor(opts) {
|
|
17
21
|
this.#label = opts.label;
|
|
18
22
|
this.#sink = opts.sink;
|
|
19
23
|
this.#rateLimitMs = opts.rateLimitMs ?? DEFAULT_RATE_LIMIT_MS;
|
|
20
|
-
|
|
21
|
-
this.#
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
this.#dispatch({
|
|
25
|
-
kind: 'tick',
|
|
26
|
-
current: 0,
|
|
27
|
-
message: this.#label,
|
|
28
|
-
});
|
|
24
|
+
this.#startTime = Date.now();
|
|
25
|
+
this.#lastSentMs = this.#startTime - this.#rateLimitMs;
|
|
26
|
+
// Synthetic start tick: the wire sees 0 at session creation.
|
|
27
|
+
this.#emit('tick', 0, undefined, this.#label);
|
|
29
28
|
}
|
|
30
29
|
set(input) {
|
|
31
30
|
if (this.#done)
|
|
32
31
|
return;
|
|
33
|
-
//
|
|
34
|
-
// constructor already dispatched current: 0. A repeated or backward tick
|
|
35
|
-
// would put a duplicate value on the wire — drop it.
|
|
32
|
+
// A repeated or backward tick would put a duplicate value on the wire — drop it.
|
|
36
33
|
if (input.current <= this.#cursor)
|
|
37
34
|
return;
|
|
38
35
|
this.#cursor = input.current;
|
|
39
|
-
this.#
|
|
40
|
-
kind: 'tick',
|
|
41
|
-
current: this.#cursor,
|
|
42
|
-
...(input.total !== undefined ? { total: input.total } : {}),
|
|
43
|
-
message: input.message ?? this.#label,
|
|
44
|
-
});
|
|
36
|
+
this.#emit('tick', this.#cursor, input.total, input.message ?? this.#label);
|
|
45
37
|
}
|
|
46
38
|
complete(message) {
|
|
47
39
|
if (this.#done)
|
|
48
40
|
return;
|
|
49
41
|
this.#done = true;
|
|
50
|
-
this.#
|
|
51
|
-
kind: 'complete',
|
|
52
|
-
current: this.#cursor,
|
|
53
|
-
message,
|
|
54
|
-
});
|
|
42
|
+
this.#emit('complete', this.#cursor, undefined, message);
|
|
55
43
|
}
|
|
56
|
-
fail(
|
|
44
|
+
fail(message) {
|
|
57
45
|
if (this.#done)
|
|
58
46
|
return;
|
|
59
47
|
this.#done = true;
|
|
60
|
-
this.#
|
|
61
|
-
kind: 'fail',
|
|
62
|
-
current: this.#cursor,
|
|
63
|
-
message: message ?? this.#label,
|
|
64
|
-
error,
|
|
65
|
-
});
|
|
48
|
+
this.#emit('fail', this.#cursor, undefined, message ?? this.#label);
|
|
66
49
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
50
|
+
/** Await every notification in flight; a failed send is logged, never thrown. */
|
|
51
|
+
async flush() {
|
|
52
|
+
if (this.#pending.size > 0)
|
|
53
|
+
await Promise.allSettled([...this.#pending]);
|
|
54
|
+
}
|
|
55
|
+
#emit(kind, current, total, message) {
|
|
56
|
+
const now = Date.now();
|
|
57
|
+
if (kind === 'tick') {
|
|
58
|
+
// Widen the window after 5s of execution; a rateLimitMs of 0 (tests)
|
|
59
|
+
// stays 0 only inside the first 5s, which every test run fits in.
|
|
60
|
+
const window = now - this.#startTime > 5000 ? Math.max(this.#rateLimitMs, 250) : this.#rateLimitMs;
|
|
61
|
+
if (now - this.#lastSentMs < window)
|
|
62
|
+
return;
|
|
70
63
|
}
|
|
71
|
-
this.#lastSentMs =
|
|
64
|
+
this.#lastSentMs = now;
|
|
72
65
|
if (!this.#sink)
|
|
73
66
|
return;
|
|
74
|
-
|
|
75
|
-
this.#sink.emit(event);
|
|
76
|
-
}
|
|
77
|
-
catch (err) {
|
|
78
|
-
// A sink failure must never fail the tool call it is reporting on.
|
|
79
|
-
Logger.warn('progress sink emit failed', { eventKind: event.kind, err });
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
#shouldRateLimit(event) {
|
|
83
|
-
if (event.kind !== 'tick') {
|
|
84
|
-
return false;
|
|
85
|
-
}
|
|
86
|
-
// Widen the window after 5s of execution; a rateLimitMs of 0 (tests) stays 0
|
|
87
|
-
// only inside the first 5s, which every test run fits in.
|
|
88
|
-
const now = Date.now();
|
|
89
|
-
const effectiveRateLimit = now - this.#startTime > 5000 ? Math.max(this.#rateLimitMs, 250) : this.#rateLimitMs;
|
|
90
|
-
const elapsed = now - this.#lastSentMs;
|
|
91
|
-
return elapsed < effectiveRateLimit;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
export class McpProgressSink {
|
|
95
|
-
toolName;
|
|
96
|
-
token;
|
|
97
|
-
notify;
|
|
98
|
-
#pending = new Set();
|
|
99
|
-
#lastProgress = -1;
|
|
100
|
-
constructor(toolName, token, notify) {
|
|
101
|
-
this.toolName = toolName;
|
|
102
|
-
this.token = token;
|
|
103
|
-
this.notify = notify;
|
|
104
|
-
}
|
|
105
|
-
emit(event) {
|
|
106
|
-
let current = event.current;
|
|
107
|
-
let total = event.total;
|
|
108
|
-
if (event.kind === 'complete') {
|
|
67
|
+
if (kind === 'complete') {
|
|
109
68
|
current = total ?? current;
|
|
110
69
|
total = current;
|
|
111
70
|
}
|
|
112
|
-
if (
|
|
113
|
-
// A terminal frame carries the outcome message, so it must reach the
|
|
114
|
-
// wire. It repeats the cursor whenever the session has no `total` (there
|
|
115
|
-
// is nothing higher to report), and the spec requires progress to
|
|
116
|
-
// increase per token — so advance past the last value instead of dropping
|
|
117
|
-
// the frame.
|
|
71
|
+
if (kind !== 'tick') {
|
|
118
72
|
current = Math.max(current, this.#lastProgress + 1);
|
|
119
73
|
if (total !== undefined && total < current)
|
|
120
74
|
total = current;
|
|
@@ -123,28 +77,22 @@ export class McpProgressSink {
|
|
|
123
77
|
if (current <= this.#lastProgress)
|
|
124
78
|
return;
|
|
125
79
|
this.#lastProgress = current;
|
|
126
|
-
const
|
|
127
|
-
|
|
80
|
+
const { toolName, token, notify } = this.#sink;
|
|
81
|
+
const params = {
|
|
82
|
+
progressToken: token,
|
|
128
83
|
progress: current,
|
|
129
84
|
...(total !== undefined ? { total } : {}),
|
|
130
|
-
message
|
|
85
|
+
message,
|
|
131
86
|
};
|
|
132
|
-
const promise =
|
|
133
|
-
method: 'notifications/progress',
|
|
134
|
-
params: notificationParams,
|
|
135
|
-
})
|
|
87
|
+
const promise = notify({ method: 'notifications/progress', params })
|
|
136
88
|
.catch((error) => {
|
|
137
|
-
|
|
89
|
+
// A sink failure must never fail the tool call it is reporting on.
|
|
90
|
+
Logger.warn(`${toolName}: progressNotification failed: ${formatUnknownErrorMessage(error)}`);
|
|
138
91
|
})
|
|
139
92
|
.finally(() => {
|
|
140
93
|
this.#pending.delete(promise);
|
|
141
94
|
});
|
|
142
95
|
this.#pending.add(promise);
|
|
143
96
|
}
|
|
144
|
-
async flush() {
|
|
145
|
-
if (this.#pending.size > 0) {
|
|
146
|
-
await Promise.allSettled([...this.#pending]);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
97
|
}
|
|
150
98
|
//# sourceMappingURL=progress.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"progress.js","sourceRoot":"","sources":["../../src/tools/progress.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAElD,SAAS,mBAAmB,CAAC,QAAgB,EAAE,OAAe,EAAE,KAAc;IAC5E,MAAM,OAAO,GA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'@modelcontextprotocol/server';\n\nimport { formatUnknownErrorMessage } from '../core/errors.js';\nimport { Logger } from '../core/observability.js';\n\nfunction reportDetachedError(toolName: string, context: string, error: unknown): void {\n const message = formatUnknownErrorMessage(error);\n Logger.emit('warning', `${toolName}: ${context} failed: ${message}`);\n}\n\ntype ProgressEvent =\n | { kind: 'tick'; current: number; total?: number; message: string }\n | { kind: 'complete'; current: number; total?: number; message: string }\n | {\n kind: 'fail';\n current: number;\n total?: number;\n message: string;\n error: unknown;\n };\n\ninterface ProgressSessionOptions {\n label: string;\n sink?: McpProgressSink;\n /** Override the rate limit window. Default: 50ms. */\n rateLimitMs?: number;\n}\n\nconst DEFAULT_RATE_LIMIT_MS = 50;\n\nexport class ProgressSession {\n readonly #label: string;\n readonly #sink: McpProgressSink | undefined;\n readonly #rateLimitMs: number;\n readonly #startTime: number;\n\n #cursor = 0;\n #lastSentMs = 0;\n #done = false;\n\n constructor(opts: ProgressSessionOptions) {\n this.#label = opts.label;\n this.#sink = opts.sink;\n this.#rateLimitMs = opts.rateLimitMs ?? DEFAULT_RATE_LIMIT_MS;\n\n const now = Date.now();\n this.#startTime = now;\n this.#lastSentMs = now - this.#rateLimitMs;\n\n // Synthetic start tick — preserves today's \"fire 0 at session creation\" wire behavior.\n this.#dispatch({\n kind: 'tick',\n current: 0,\n message: this.#label,\n });\n }\n\n set(input: { current: number; total?: number; message?: string }): void {\n if (this.#done) return;\n // The spec requires `progress` to increase on every notification, and the\n // constructor already dispatched current: 0. A repeated or backward tick\n // would put a duplicate value on the wire — drop it.\n if (input.current <= this.#cursor) return;\n this.#cursor = input.current;\n this.#dispatch({\n kind: 'tick',\n current: this.#cursor,\n ...(input.total !== undefined ? { total: input.total } : {}),\n message: input.message ?? this.#label,\n });\n }\n\n complete(message: string): void {\n if (this.#done) return;\n this.#done = true;\n this.#dispatch({\n kind: 'complete',\n current: this.#cursor,\n message,\n });\n }\n\n fail(error: unknown, message?: string): void {\n if (this.#done) return;\n this.#done = true;\n this.#dispatch({\n kind: 'fail',\n current: this.#cursor,\n message: message ?? this.#label,\n error,\n });\n }\n\n #dispatch(event: ProgressEvent): void {\n if (this.#shouldRateLimit(event)) {\n return;\n }\n\n this.#lastSentMs = Date.now();\n\n if (!this.#sink) return;\n try {\n this.#sink.emit(event);\n } catch (err) {\n // A sink failure must never fail the tool call it is reporting on.\n Logger.warn('progress sink emit failed', { eventKind: event.kind, err });\n }\n }\n\n #shouldRateLimit(event: ProgressEvent): boolean {\n if (event.kind !== 'tick') {\n return false;\n }\n\n // Widen the window after 5s of execution; a rateLimitMs of 0 (tests) stays 0\n // only inside the first 5s, which every test run fits in.\n const now = Date.now();\n const effectiveRateLimit =\n now - this.#startTime > 5000 ? Math.max(this.#rateLimitMs, 250) : this.#rateLimitMs;\n\n const elapsed = now - this.#lastSentMs;\n return elapsed < effectiveRateLimit;\n }\n}\n\nexport class McpProgressSink {\n private readonly toolName: string;\n private readonly token: string | number;\n private readonly notify: (n: Notification) => Promise<void>;\n readonly #pending = new Set<Promise<void>>();\n #lastProgress = -1;\n\n constructor(\n toolName: string,\n token: string | number,\n notify: (n: Notification) => Promise<void>,\n ) {\n this.toolName = toolName;\n this.token = token;\n this.notify = notify;\n }\n\n emit(event: ProgressEvent): void {\n let current = event.current;\n let total = event.total;\n if (event.kind === 'complete') {\n current = total ?? current;\n total = current;\n }\n if (event.kind !== 'tick') {\n // A terminal frame carries the outcome message, so it must reach the\n // wire. It repeats the cursor whenever the session has no `total` (there\n // is nothing higher to report), and the spec requires progress to\n // increase per token — so advance past the last value instead of dropping\n // the frame.\n current = Math.max(current, this.#lastProgress + 1);\n if (total !== undefined && total < current) total = current;\n }\n // Spec: progress must increase on every notification for the same token.\n if (current <= this.#lastProgress) return;\n this.#lastProgress = current;\n const notificationParams: ProgressNotificationParams = {\n progressToken: this.token,\n progress: current,\n ...(total !== undefined ? { total } : {}),\n message: event.message,\n };\n const promise = this.notify({\n method: 'notifications/progress',\n params: notificationParams,\n })\n .catch((error: unknown) => {\n reportDetachedError(this.toolName, 'progressNotification', error);\n })\n .finally(() => {\n this.#pending.delete(promise);\n });\n this.#pending.add(promise);\n }\n\n async flush(): Promise<void> {\n if (this.#pending.size > 0) {\n await Promise.allSettled([...this.#pending]);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"progress.js","sourceRoot":"","sources":["../../src/tools/progress.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAiBlD,MAAM,qBAAqB,GAAG,EAAE,CAAC;AAEjC;;;;;GAKG;AACH,MAAM,OAAO,eAAe;IACjB,MAAM,CAAS;IACf,KAAK,CAA2B;IAChC,YAAY,CAAS;IACrB,UAAU,CAAS;IACnB,QAAQ,GAAG,IAAI,GAAG,EAAiB,CAAC;IAE7C,OAAO,GAAG,CAAC,CAAC;IACZ,WAAW,GAAG,CAAC,CAAC;IAChB,aAAa,GAAG,CAAC,CAAC,CAAC;IACnB,KAAK,GAAG,KAAK,CAAC;IAEd,YAAY,IAA4B;QACtC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,WAAW,IAAI,qBAAqB,CAAC;QAC9D,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAC7B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,YAAY,CAAC;QACvD,6DAA6D;QAC7D,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IAChD,CAAC;IAED,GAAG,CAAC,KAA4D;QAC9D,IAAI,IAAI,CAAC,KAAK;YAAE,OAAO;QACvB,iFAAiF;QACjF,IAAI,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C,CAAC;aACD,OAAO,CAAC,GAAG,EAAE;YACZ,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAChC,CAAC,CAAC,CAAC;QACL,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;CACF","sourcesContent":["import type { Notification, ProgressNotificationParams } from '@modelcontextprotocol/server';\n\nimport { formatUnknownErrorMessage } from '../core/errors.ts';\nimport { Logger } from '../core/observability.ts';\n\n/** Where progress frames go: the `notifications/progress` sink for one `progressToken`. */\nexport interface ProgressSink {\n toolName: string;\n token: string | number;\n notify: (n: Notification) => Promise<void>;\n}\n\ninterface ProgressSessionOptions {\n label: string;\n /** Absent when the client sent no `progressToken`; the session then only tracks state. */\n sink?: ProgressSink;\n /** Override the tick rate-limit window. Default: 50ms. */\n rateLimitMs?: number;\n}\n\nconst DEFAULT_RATE_LIMIT_MS = 50;\n\n/**\n * One tool call's progress stream: a monotonic cursor, a tick rate limit, and\n * the wire guard the spec requires (`progress` strictly increases per token).\n * Terminal frames (`complete`, `fail`) always reach the wire — they carry the\n * outcome message — so they advance past the last value instead of dropping.\n */\nexport class ProgressSession {\n readonly #label: string;\n readonly #sink: ProgressSink | undefined;\n readonly #rateLimitMs: number;\n readonly #startTime: number;\n readonly #pending = new Set<Promise<void>>();\n\n #cursor = 0;\n #lastSentMs = 0;\n #lastProgress = -1;\n #done = false;\n\n constructor(opts: ProgressSessionOptions) {\n this.#label = opts.label;\n this.#sink = opts.sink;\n this.#rateLimitMs = opts.rateLimitMs ?? DEFAULT_RATE_LIMIT_MS;\n this.#startTime = Date.now();\n this.#lastSentMs = this.#startTime - this.#rateLimitMs;\n // Synthetic start tick: the wire sees 0 at session creation.\n this.#emit('tick', 0, undefined, this.#label);\n }\n\n set(input: { current: number; total?: number; message?: string }): void {\n if (this.#done) return;\n // A repeated or backward tick would put a duplicate value on the wire — drop it.\n if (input.current <= this.#cursor) return;\n this.#cursor = input.current;\n this.#emit('tick', this.#cursor, input.total, input.message ?? this.#label);\n }\n\n complete(message: string): void {\n if (this.#done) return;\n this.#done = true;\n this.#emit('complete', this.#cursor, undefined, message);\n }\n\n fail(message?: string): void {\n if (this.#done) return;\n this.#done = true;\n this.#emit('fail', this.#cursor, undefined, message ?? this.#label);\n }\n\n /** Await every notification in flight; a failed send is logged, never thrown. */\n async flush(): Promise<void> {\n if (this.#pending.size > 0) await Promise.allSettled([...this.#pending]);\n }\n\n #emit(\n kind: 'tick' | 'complete' | 'fail',\n current: number,\n total: number | undefined,\n message: string,\n ): void {\n const now = Date.now();\n if (kind === 'tick') {\n // Widen the window after 5s of execution; a rateLimitMs of 0 (tests)\n // stays 0 only inside the first 5s, which every test run fits in.\n const window =\n now - this.#startTime > 5000 ? Math.max(this.#rateLimitMs, 250) : this.#rateLimitMs;\n if (now - this.#lastSentMs < window) return;\n }\n this.#lastSentMs = now;\n if (!this.#sink) return;\n\n if (kind === 'complete') {\n current = total ?? current;\n total = current;\n }\n if (kind !== 'tick') {\n current = Math.max(current, this.#lastProgress + 1);\n if (total !== undefined && total < current) total = current;\n }\n // Spec: progress must increase on every notification for the same token.\n if (current <= this.#lastProgress) return;\n this.#lastProgress = current;\n\n const { toolName, token, notify } = this.#sink;\n const params: ProgressNotificationParams = {\n progressToken: token,\n progress: current,\n ...(total !== undefined ? { total } : {}),\n message,\n };\n const promise = notify({ method: 'notifications/progress', params })\n .catch((error: unknown) => {\n // A sink failure must never fail the tool call it is reporting on.\n Logger.warn(\n `${toolName}: progressNotification failed: ${formatUnknownErrorMessage(error)}`,\n );\n })\n .finally(() => {\n this.#pending.delete(promise);\n });\n this.#pending.add(promise);\n }\n}\n"]}
|
package/dist/tools/read.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const READ: import("./define.
|
|
1
|
+
export declare const READ: import("./define.ts").DefinedTool;
|
|
2
2
|
//# sourceMappingURL=read.d.ts.map
|
package/dist/tools/read.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAkYA,eAAO,MAAM,IAAI,
|
|
1
|
+
{"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAkYA,eAAO,MAAM,IAAI,mCAmKf,CAAC"}
|
package/dist/tools/read.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { basename } from 'node:path';
|
|
3
3
|
import * as z from 'zod/v4';
|
|
4
|
-
import { processInParallel } from
|
|
5
|
-
import { ErrorCode } from
|
|
6
|
-
import { buildFileResourceLinkFor, buildFileResourceUri } from
|
|
7
|
-
import { detectMimeFromContent, detectMimeType } from
|
|
8
|
-
import { readFileWithStats } from
|
|
9
|
-
import { ContinuationSchema, defaultFalseBoolean, FileKind, NonNegInt, OperationSummarySchema, PerFileErrorSchema, PositiveInt, Sha256Hex, singleOrBatchAccessPaths, singleOrBatchPathsInput, validateReadRange, } from
|
|
10
|
-
import { DEFAULT_CONTINUATION_CHUNK_SIZE, DEFAULT_SEARCH_TIMEOUT_MS,
|
|
11
|
-
import { isTotalFailure, runOverPaths } from
|
|
12
|
-
import { defineTool } from
|
|
4
|
+
import { processInParallel } from "../core/concurrency.js";
|
|
5
|
+
import { ErrorCode } from "../core/errors.js";
|
|
6
|
+
import { buildFileResourceLinkFor, buildFileResourceUri } from "../core/file-uri.js";
|
|
7
|
+
import { detectMimeFromContent, detectMimeType } from "../core/mime.js";
|
|
8
|
+
import { readFileWithStats } from "../core/read.js";
|
|
9
|
+
import { ContinuationSchema, defaultFalseBoolean, FileKind, NonNegInt, OperationSummarySchema, PerFileErrorSchema, PositiveInt, Sha256Hex, singleOrBatchAccessPaths, singleOrBatchPathsInput, validateReadRange, } from "../core/schema.js";
|
|
10
|
+
import { DEFAULT_CONTINUATION_CHUNK_SIZE, DEFAULT_SEARCH_TIMEOUT_MS, getMaxTextFileSize, PARALLEL_CONCURRENCY, READ_MANY_MAX_TOTAL_BYTES, } from "../core/util.js";
|
|
11
|
+
import { isTotalFailure, runOverPaths } from "./batch.js";
|
|
12
|
+
import { defineTool } from "./define.js";
|
|
13
13
|
const rangeField = (description) => z
|
|
14
14
|
.int32()
|
|
15
15
|
.min(1, { message: 'Min: 1' })
|
|
@@ -333,9 +333,7 @@ export const READ = defineTool({
|
|
|
333
333
|
let known = new Map();
|
|
334
334
|
if (args.paths !== undefined) {
|
|
335
335
|
pathList = args.paths;
|
|
336
|
-
const
|
|
337
|
-
const maxTextFileSize = getMaxTextFileSize();
|
|
338
|
-
const budget = await collectFileBudget(pathList, defaultMaxTotalSize, maxTextFileSize, ctx);
|
|
336
|
+
const budget = await collectFileBudget(pathList, READ_MANY_MAX_TOTAL_BYTES, getMaxTextFileSize(), ctx);
|
|
339
337
|
known = budget.known;
|
|
340
338
|
skippedResults = budget.skippedResults;
|
|
341
339
|
survivors = budget.survivors;
|
package/dist/tools/read.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"read.js","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACrF,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAExE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,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U,EAAE,EAAE,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE;YACnD,IAAI;YACJ,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC;YAChC,GAAG,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC/C,CAAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { createHash } from 'node:crypto';\nimport type { Stats } from 'node:fs';\nimport { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.js';\nimport { ErrorCode } from '../core/errors.js';\nimport { buildFileResourceLinkFor, buildFileResourceUri } from '../core/file-uri.js';\nimport { detectMimeFromContent, detectMimeType } from '../core/mime.js';\nimport type { ReadFileResult, ReadSpec } from '../core/read.js';\nimport { readFileWithStats } from '../core/read.js';\nimport {\n ContinuationSchema,\n defaultFalseBoolean,\n FileKind,\n NonNegInt,\n OperationSummarySchema,\n PerFileErrorSchema,\n PositiveInt,\n Sha256Hex,\n singleOrBatchAccessPaths,\n singleOrBatchPathsInput,\n validateReadRange,\n} from '../core/schema.js';\nimport {\n DEFAULT_CONTINUATION_CHUNK_SIZE,\n DEFAULT_SEARCH_TIMEOUT_MS,\n getDefaultReadManyMaxTotalSize,\n getMaxTextFileSize,\n PARALLEL_CONCURRENCY,\n} from '../core/util.js';\nimport type { PerPathResult } from './batch.js';\nimport { isTotalFailure, runOverPaths } from './batch.js';\nimport type { ToolCtx } from './define.js';\nimport { defineTool } from './define.js';\n\nconst rangeField = (description: string) =>\n z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(description);\n\nconst readRangeFields = {\n head: rangeField('Return first N lines'),\n tail: rangeField('Return last N lines'),\n startLine: rangeField('Start line (1-indexed)'),\n endLine: rangeField('End line (1-indexed)'),\n};\n\nconst ReadFileInputSchema = singleOrBatchPathsInput({\n includeHash: defaultFalseBoolean('Include SHA-256 hash of the returned content in the response'),\n ...readRangeFields,\n})\n .superRefine((value, ctx) => {\n validateReadRange(\n {\n head: value.head,\n tail: value.tail,\n startLine: value.startLine,\n endLine: value.endLine,\n },\n ctx,\n );\n })\n // Mirror `validateReadRange` on the wire. Without this the four line params\n // published as four independent optional integers, so `{ path, head, tail }`\n // passed the advertised schema and was rejected only at call time.\n //\n // `oneOf` is restated because `.meta()` replaces the entry\n // `singleOrBatchPathsInput` set rather than merging into it — dropping it here\n // would silently un-publish the path/paths rule.\n .meta({\n // The line-param exclusivity that used to sit here as a five-branch\n // `not/anyOf` is one sentence in the description instead: validateReadRange\n // rejects every conflicting combination by name at runtime, so the wire copy\n // was paying for a second statement of a rule the model reads better in\n // prose.\n oneOf: [{ required: ['path'] }, { required: ['paths'] }],\n dependentRequired: { endLine: ['startLine'] },\n });\n\n// File bytes are NOT here: text rides the text content block, image/audio ride\n// a media block. This schema is the metadata a caller cannot recover from\n// those blocks. `readOnePath` carries the bytes internally via\n// `PerPathReadValue` and `run` drops them before the structured half goes out.\nconst ReadPerPathValueSchema = z.strictObject({\n mimeType: z.string().optional().describe('Detected MIME type (e.g. text/typescript)'),\n kind: FileKind.optional().describe('Broad file kind: text, binary, image, audio, or pdf'),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'Resource URI for externalized content (present when file is stored in resource store)',\n ),\n continuation: ContinuationSchema.optional().describe(\n 'Next-read arguments; present when content was truncated due to size limits',\n ),\n totalLines: NonNegInt.optional().describe('Total line count in the full file'),\n linesRead: NonNegInt.optional().describe('Number of lines returned in this response'),\n hasMoreLines: z\n .boolean()\n .optional()\n .describe('True when additional lines remain beyond what was returned'),\n head: PositiveInt.optional().describe('Head lines requested'),\n tail: PositiveInt.optional().describe('Tail lines requested'),\n startLine: PositiveInt.optional().describe('Start line'),\n endLine: PositiveInt.optional().describe('End line'),\n contentHash: Sha256Hex.optional().describe(\n 'SHA-256 hex digest of the returned content (present when includeHash=true)',\n ),\n});\n\nconst ReadPerPathSchema = z.strictObject({\n path: z.string().describe('Requested file path'),\n value: ReadPerPathValueSchema.optional().describe('Read result; present on success'),\n error: PerFileErrorSchema.optional().describe('Error details; present on failure'),\n});\n\nconst ReadFileOutputSchema = z.strictObject({\n results: z.array(ReadPerPathSchema).describe('Per-path results ordered to match the input paths'),\n summary: OperationSummarySchema,\n});\n\ntype ReadFileInput = z.infer<typeof ReadFileInputSchema>;\n\nconst READ_TOOL_LABEL = 'Read';\n\nfunction buildReadSpec(args: ReadFileInput, signal?: AbortSignal): ReadSpec {\n const signalPart = signal ? { signal } : {};\n const { head, tail, startLine, endLine } = args;\n\n if (head !== undefined) return { kind: 'head', lines: head, ...signalPart };\n if (tail !== undefined) return { kind: 'tail', lines: tail, ...signalPart };\n if (startLine !== undefined || endLine !== undefined) {\n return {\n kind: 'range',\n start: startLine ?? 1,\n ...(endLine !== undefined ? { end: endLine } : {}),\n ...signalPart,\n };\n }\n return { kind: 'full', ...signalPart };\n}\n\n// No `totalLines`: only `readFull` counts them and a full read never leaves\n// more behind, so a continuation cannot know the total without a second pass.\nfunction buildReadContinuation(\n result: ReadFileResult,\n requestedPath: string,\n): z.infer<typeof ContinuationSchema> | undefined {\n if (!result.hasMoreLines) return undefined;\n const linesRead = result.linesRead ?? 0;\n const nextStart = (result.startLine ?? 1) + linesRead;\n let chunkSize: number;\n if (result.head !== undefined) {\n chunkSize = result.head;\n } else if (result.startLine !== undefined && result.endLine !== undefined) {\n chunkSize = result.endLine - result.startLine + 1;\n } else {\n chunkSize = DEFAULT_CONTINUATION_CHUNK_SIZE;\n }\n const nextEnd = nextStart + chunkSize - 1;\n return {\n tool: 'read',\n args: { path: requestedPath, startLine: nextStart, endLine: nextEnd },\n hint: `More lines remain from ${String(nextStart)}. Read next chunk with these args.`,\n };\n}\n\n/**\n * The published metadata plus the bytes this call read. `content` and\n * `mediaData` exist only between `readOnePath` and the content blocks `run`\n * builds from them — they are stripped before the structured half is returned,\n * which is why they are not in `ReadPerPathValueSchema`.\n */\ntype PerPathReadValue = z.infer<typeof ReadPerPathValueSchema> & {\n content?: string;\n mediaData?: string;\n};\n\ninterface BatchFileInfo {\n index: number;\n size: number;\n validPath: string;\n stats: Stats;\n}\n\nasync function collectFileBudget(\n filePaths: readonly string[],\n maxTotalSize: number,\n maxSize: number,\n ctx: Pick<ToolCtx, 'fs' | 'signal' | 'log'>,\n): Promise<{\n skippedResults: Map<number, PerPathResult<PerPathReadValue>>;\n survivors: string[];\n known: Map<string, { validPath: string; stats: Stats }>;\n}> {\n const indexed = filePaths.map((path, index) => ({ path, index }));\n const { results } = await processInParallel(\n indexed,\n async ({ path, index }): Promise<BatchFileInfo | undefined> => {\n try {\n const out = await ctx.fs.stat(path);\n return {\n index,\n size: Math.min(out.stats.size, maxSize),\n validPath: out.validPath,\n stats: out.stats,\n };\n } catch (err: unknown) {\n ctx.log?.('debug', `collectFileBudget: stat failed for \"${path}\": ${String(err)}`, 'read');\n return undefined;\n }\n },\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n const byIndex = new Map<number, number>();\n const known = new Map<string, { validPath: string; stats: Stats }>();\n for (const { value: item } of results) {\n if (!item) continue;\n byIndex.set(item.index, item.size);\n // Keyed by the ORIGINAL requested path string (not validPath) — that's\n // what readOnePath is called with downstream, and what filePaths[i]\n // holds.\n const requestedPath = filePaths[item.index];\n if (requestedPath !== undefined) {\n known.set(requestedPath, { validPath: item.validPath, stats: item.stats });\n }\n }\n\n let total = 0;\n const skippedResults = new Map<number, PerPathResult<PerPathReadValue>>();\n const survivors: string[] = [];\n let overflowed = false;\n for (let i = 0; i < filePaths.length; i += 1) {\n const path = filePaths[i];\n if (path === undefined) continue;\n const size = byIndex.get(i);\n if (overflowed) {\n // Only files that were actually stat'd get the TOO_LARGE result; a failed\n // stat falls through to survivors so its read surfaces the real error —\n // not a misleading TOO_LARGE.\n if (size !== undefined) {\n skippedResults.set(i, {\n path,\n error: {\n code: ErrorCode.TOO_LARGE,\n message: `Skipped: combined estimated read would exceed maxTotalSize (${String(maxTotalSize)} bytes)`,\n path,\n },\n });\n } else {\n survivors.push(path);\n }\n continue;\n }\n if (size === undefined) {\n survivors.push(path);\n continue;\n }\n if (total + size > maxTotalSize) {\n overflowed = true;\n skippedResults.set(i, {\n path,\n error: {\n code: ErrorCode.TOO_LARGE,\n message: `Skipped: combined estimated read would exceed maxTotalSize (${String(maxTotalSize)} bytes)`,\n path,\n },\n });\n continue;\n }\n total += size;\n survivors.push(path);\n }\n\n return { skippedResults, survivors, known };\n}\n\nfunction buildPerPathReadValue(\n result: ReadFileResult,\n options: { includeHash?: boolean; hasResourceStore?: boolean; requestedPath: string },\n): PerPathReadValue {\n const mimeInfo = detectMimeFromContent(result.path, result.content);\n const continuation =\n result.hasMoreLines && result.readMode !== 'tail'\n ? buildReadContinuation(result, options.requestedPath)\n : undefined;\n const contentHash = options.includeHash\n ? createHash('sha256').update(result.content, 'utf-8').digest('hex')\n : undefined;\n const resourceUri = options.hasResourceStore ? buildFileResourceUri(result.path) : undefined;\n\n return {\n content: result.content,\n mimeType: mimeInfo.mimeType,\n kind: mimeInfo.kind,\n ...(continuation ? { continuation } : {}),\n ...(result.totalLines !== undefined ? { totalLines: result.totalLines } : {}),\n ...(result.linesRead !== undefined ? { linesRead: result.linesRead } : {}),\n ...(result.hasMoreLines ? { hasMoreLines: true } : {}),\n ...(result.head !== undefined ? { head: result.head } : {}),\n ...(result.tail !== undefined ? { tail: result.tail } : {}),\n ...(result.startLine !== undefined ? { startLine: result.startLine } : {}),\n ...(result.endLine !== undefined ? { endLine: result.endLine } : {}),\n ...(contentHash !== undefined ? { contentHash } : {}),\n ...(resourceUri !== undefined ? { resourceUri } : {}),\n };\n}\n\n/**\n * The two facts the model cannot act on without: that lines were dropped, and\n * the exact args to get the next chunk. Both used to live only in the structured\n * half, which no longer reaches the model. Each line is `//` prefixed and set\n * off by a blank line so it cannot be read as file bytes — do not drop either\n * guard.\n */\nfunction readTrailer(v: PerPathReadValue): string[] {\n const lines: string[] = [];\n if (v.continuation) {\n lines.push(\n `// truncated: ${v.continuation.hint} Continue: read ${JSON.stringify(v.continuation.args)}`,\n );\n } else if (v.hasMoreLines && v.linesRead !== undefined) {\n // A tail read gets no continuation — there are no args that read *backwards*\n // — so say what was shown rather than leaving the truncation silent.\n lines.push(`// truncated: showing last ${String(v.linesRead)} lines`);\n }\n if (v.contentHash !== undefined) lines.push(`// sha256: ${v.contentHash}`);\n return lines;\n}\n\nasync function readOnePath(\n filePath: string,\n args: ReadFileInput,\n ctx: ToolCtx,\n known?: { validPath: string; stats: Stats },\n): Promise<PerPathReadValue> {\n // Image/audio full read: return a media content block instead of throwing\n // INVALID_INPUT (\"Binary file detected.\"). Line-range reads are\n // text-oriented and stay rejected. `readRaw` enforces the same size cap as\n // the text path (getMaxTextFileSize), so a too-large image surfaces TOO_LARGE\n // rather than blowing memory. svg carries kind:'image' but is XML text —\n // readRaw.isBinary is false for it, so it falls through to the text path.\n const isRangeRead =\n args.head !== undefined ||\n args.tail !== undefined ||\n args.startLine !== undefined ||\n args.endLine !== undefined;\n if (!isRangeRead) {\n const mime = detectMimeType(filePath);\n if (mime.kind === 'image' || mime.kind === 'audio') {\n const raw = await ctx.fs.readRaw(filePath, { signal: ctx.signal });\n if (raw.isBinary) {\n return {\n content: `[binary ${mime.kind} content: ${String(raw.content.length)} bytes; returned as a ${mime.kind} content block]`,\n mimeType: raw.mimeType,\n kind: mime.kind,\n mediaData: raw.content.toString('base64'),\n };\n }\n }\n }\n\n const spec = buildReadSpec(args, ctx.signal);\n const result = known\n ? await readFileWithStats(filePath, known.validPath, known.stats, spec)\n : await ctx.fs.readFile(filePath, spec);\n\n return buildPerPathReadValue(result, {\n includeHash: args.includeHash,\n hasResourceStore: ctx.resourceStore !== undefined,\n // The continuation is args the caller pastes back, so it echoes the path\n // they wrote. `result.path` is the resolved absolute one — on Windows that\n // is a backslash-doubling JSON string that also spells out the server root.\n requestedPath: filePath,\n });\n}\n\nexport const READ = defineTool({\n name: 'read',\n title: 'Read File',\n description:\n 'Read one or more text files and return content. ' +\n 'Partial reads: head (first N lines), tail (last N lines), startLine/endLine (line range). ' +\n 'Batch mode: pass paths[] instead of path; line params are shared across all files. ' +\n 'head, tail, and startLine/endLine are mutually exclusive — use exactly one.',\n input: ReadFileInputSchema,\n output: ReadFileOutputSchema,\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n timeoutMs: DEFAULT_SEARCH_TIMEOUT_MS,\n defaultErrorCode: ErrorCode.NOT_FILE,\n progress: (args) => {\n const isBatch = args.paths !== undefined;\n const name = isBatch ? `${String(args.paths?.length ?? 0)} files` : basename(args.path ?? '');\n if (isBatch) {\n return { label: READ_TOOL_LABEL, subject: name };\n }\n let scope: string | undefined;\n if (args.startLine !== undefined) {\n const end = args.endLine ?? '...';\n scope = `${args.startLine}-${String(end)}`;\n } else if (args.head !== undefined) {\n scope = `head ${args.head}`;\n } else if (args.tail !== undefined) {\n scope = `tail ${args.tail}`;\n }\n return { label: READ_TOOL_LABEL, subject: name, ...(scope ? { scope } : {}) };\n },\n accessPaths: singleOrBatchAccessPaths,\n run: async (args, ctx) => {\n let pathList: string[];\n let skippedResults = new Map<number, PerPathResult<PerPathReadValue>>();\n let survivors: string[];\n let known = new Map<string, { validPath: string; stats: Stats }>();\n\n if (args.paths !== undefined) {\n pathList = args.paths;\n const defaultMaxTotalSize = getDefaultReadManyMaxTotalSize();\n const maxTextFileSize = getMaxTextFileSize();\n const budget = await collectFileBudget(pathList, defaultMaxTotalSize, maxTextFileSize, ctx);\n known = budget.known;\n skippedResults = budget.skippedResults;\n survivors = budget.survivors;\n } else {\n pathList = [args.path ?? ''];\n survivors = [...pathList];\n }\n\n const batchInput = { paths: survivors };\n\n // Every path can be budget-skipped (a single file over maxTotalSize does\n // it), and runOverPaths rejects an empty list. The per-path TOO_LARGE\n // results are already built — return those rather than failing the call.\n const batch =\n survivors.length === 0\n ? { results: [] as PerPathResult<PerPathReadValue>[] }\n : await runOverPaths<undefined, PerPathReadValue>(\n batchInput,\n ctx,\n ({ path }) => readOnePath(path, args, ctx, known.get(path)),\n { defaultErrorCode: ErrorCode.NOT_FILE },\n );\n\n const resultMap = new Map(batch.results.map((r) => [r.path, r]));\n const ordered: PerPathResult<PerPathReadValue>[] = pathList.map((path, idx) => {\n const skipped = skippedResults.get(idx);\n if (skipped) return skipped;\n const result = resultMap.get(path);\n return (\n result ?? {\n path,\n error: { code: ErrorCode.UNKNOWN, message: 'Unknown read failure' },\n }\n );\n });\n\n const failed = ordered.filter((r) => 'error' in r).length;\n const summary = {\n total: ordered.length,\n succeeded: ordered.length - failed,\n failed,\n };\n\n const resources: ContentBlock[] = [];\n for (const result of ordered) {\n if ('error' in result) continue;\n const v = result.value;\n // Image/audio full read: emit the media content block alongside the\n // structured value. The base64 lives in v.mediaData (set in readOnePath).\n if (v.mediaData && v.mimeType && (v.kind === 'image' || v.kind === 'audio')) {\n resources.push(\n v.kind === 'image'\n ? { type: 'image', data: v.mediaData, mimeType: v.mimeType }\n : { type: 'audio', data: v.mediaData, mimeType: v.mimeType },\n );\n continue;\n }\n if (!v.resourceUri || !v.content) continue;\n // `result.path` is the path as *requested*; `v.resourceUri` was built from\n // the *validated* one. Rebuilding from the request would emit a second URI\n // for the same file whenever the two differ in case — subscribe by one and\n // unsubscribe by the other and the watcher never goes away.\n resources.push(\n buildFileResourceLinkFor(\n v.resourceUri,\n basename(result.path),\n v.mimeType ?? 'application/octet-stream',\n Buffer.byteLength(v.content, 'utf8'),\n ),\n );\n }\n\n const [firstOrdered] = ordered;\n const body = (v: PerPathReadValue): string => {\n const content = v.content ?? 'read failed';\n const trailer = readTrailer(v);\n if (trailer.length === 0) return content;\n // Exactly one blank line between the bytes and the trailer, whether or not\n // the file ended in a newline.\n return `${content}${content.endsWith('\\n') ? '\\n' : '\\n\\n'}${trailer.join('\\n')}`;\n };\n const text =\n ordered.length === 1 && firstOrdered !== undefined\n ? 'error' in firstOrdered\n ? firstOrdered.error.message\n : body(firstOrdered.value)\n : ordered\n .map((r) => {\n const header = `// ${r.path}`;\n if ('value' in r) return `${header}\\n${body(r.value)}`;\n return `${header}\\n// Error: ${r.error.message}`;\n })\n .join('\\n\\n');\n\n // The bytes ship once. `text` above already carries every file's content\n // verbatim (and image/audio bytes ride the media content block), so\n // repeating them under `results[].value` doubled both the wire payload and\n // the model's token cost for every read. The structured half keeps the\n // metadata a client cannot recover from the text: paths, line counts,\n // hashes, continuations, resourceUri.\n const structuredResults = ordered.map((result) => {\n if ('error' in result) return result;\n const { content: _content, mediaData: _mediaData, ...value } = result.value;\n return { ...result, value };\n });\n\n return {\n structured: { results: structuredResults, summary },\n text,\n isError: isTotalFailure(summary),\n ...(resources.length > 0 ? { resources } : {}),\n };\n },\n});\n"]}
|
|
1
|
+
{"version":3,"file":"read.js","sourceRoot":"","sources":["../../src/tools/read.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACrF,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAExE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,QAAQ,EACR,SAAS,EACT,sBAAsB,EACtB,kBAAkB,EAClB,WAAW,EACX,SAAS,EACT,wBAAwB,EACxB,uBAAuB,EACvB,iBAAiB,GAClB,MAAM,mBAAmB,CAA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AAC;IACJ,CAAC;CACF,CAAC,CAAC","sourcesContent":["import type { ContentBlock } from '@modelcontextprotocol/server';\n\nimport { createHash } from 'node:crypto';\nimport type { Stats } from 'node:fs';\nimport { basename } from 'node:path';\n\nimport * as z from 'zod/v4';\n\nimport { processInParallel } from '../core/concurrency.ts';\nimport { ErrorCode } from '../core/errors.ts';\nimport { buildFileResourceLinkFor, buildFileResourceUri } from '../core/file-uri.ts';\nimport { detectMimeFromContent, detectMimeType } from '../core/mime.ts';\nimport type { ReadFileResult, ReadSpec } from '../core/read.ts';\nimport { readFileWithStats } from '../core/read.ts';\nimport {\n ContinuationSchema,\n defaultFalseBoolean,\n FileKind,\n NonNegInt,\n OperationSummarySchema,\n PerFileErrorSchema,\n PositiveInt,\n Sha256Hex,\n singleOrBatchAccessPaths,\n singleOrBatchPathsInput,\n validateReadRange,\n} from '../core/schema.ts';\nimport {\n DEFAULT_CONTINUATION_CHUNK_SIZE,\n DEFAULT_SEARCH_TIMEOUT_MS,\n getMaxTextFileSize,\n PARALLEL_CONCURRENCY,\n READ_MANY_MAX_TOTAL_BYTES,\n} from '../core/util.ts';\nimport type { PerPathResult } from './batch.ts';\nimport { isTotalFailure, runOverPaths } from './batch.ts';\nimport type { ToolCtx } from './define.ts';\nimport { defineTool } from './define.ts';\n\nconst rangeField = (description: string) =>\n z\n .int32()\n .min(1, { message: 'Min: 1' })\n .max(100000, { message: 'Max: 100,000' })\n .optional()\n .describe(description);\n\nconst readRangeFields = {\n head: rangeField('Return first N lines'),\n tail: rangeField('Return last N lines'),\n startLine: rangeField('Start line (1-indexed)'),\n endLine: rangeField('End line (1-indexed)'),\n};\n\nconst ReadFileInputSchema = singleOrBatchPathsInput({\n includeHash: defaultFalseBoolean('Include SHA-256 hash of the returned content in the response'),\n ...readRangeFields,\n})\n .superRefine((value, ctx) => {\n validateReadRange(\n {\n head: value.head,\n tail: value.tail,\n startLine: value.startLine,\n endLine: value.endLine,\n },\n ctx,\n );\n })\n // Mirror `validateReadRange` on the wire. Without this the four line params\n // published as four independent optional integers, so `{ path, head, tail }`\n // passed the advertised schema and was rejected only at call time.\n //\n // `oneOf` is restated because `.meta()` replaces the entry\n // `singleOrBatchPathsInput` set rather than merging into it — dropping it here\n // would silently un-publish the path/paths rule.\n .meta({\n // The line-param exclusivity that used to sit here as a five-branch\n // `not/anyOf` is one sentence in the description instead: validateReadRange\n // rejects every conflicting combination by name at runtime, so the wire copy\n // was paying for a second statement of a rule the model reads better in\n // prose.\n oneOf: [{ required: ['path'] }, { required: ['paths'] }],\n dependentRequired: { endLine: ['startLine'] },\n });\n\n// File bytes are NOT here: text rides the text content block, image/audio ride\n// a media block. This schema is the metadata a caller cannot recover from\n// those blocks. `readOnePath` carries the bytes internally via\n// `PerPathReadValue` and `run` drops them before the structured half goes out.\nconst ReadPerPathValueSchema = z.strictObject({\n mimeType: z.string().optional().describe('Detected MIME type (e.g. text/typescript)'),\n kind: FileKind.optional().describe('Broad file kind: text, binary, image, audio, or pdf'),\n resourceUri: z\n .string()\n .optional()\n .describe(\n 'Resource URI for externalized content (present when file is stored in resource store)',\n ),\n continuation: ContinuationSchema.optional().describe(\n 'Next-read arguments; present when content was truncated due to size limits',\n ),\n totalLines: NonNegInt.optional().describe('Total line count in the full file'),\n linesRead: NonNegInt.optional().describe('Number of lines returned in this response'),\n hasMoreLines: z\n .boolean()\n .optional()\n .describe('True when additional lines remain beyond what was returned'),\n head: PositiveInt.optional().describe('Head lines requested'),\n tail: PositiveInt.optional().describe('Tail lines requested'),\n startLine: PositiveInt.optional().describe('Start line'),\n endLine: PositiveInt.optional().describe('End line'),\n contentHash: Sha256Hex.optional().describe(\n 'SHA-256 hex digest of the returned content (present when includeHash=true)',\n ),\n});\n\nconst ReadPerPathSchema = z.strictObject({\n path: z.string().describe('Requested file path'),\n value: ReadPerPathValueSchema.optional().describe('Read result; present on success'),\n error: PerFileErrorSchema.optional().describe('Error details; present on failure'),\n});\n\nconst ReadFileOutputSchema = z.strictObject({\n results: z.array(ReadPerPathSchema).describe('Per-path results ordered to match the input paths'),\n summary: OperationSummarySchema,\n});\n\ntype ReadFileInput = z.infer<typeof ReadFileInputSchema>;\n\nconst READ_TOOL_LABEL = 'Read';\n\nfunction buildReadSpec(args: ReadFileInput, signal?: AbortSignal): ReadSpec {\n const signalPart = signal ? { signal } : {};\n const { head, tail, startLine, endLine } = args;\n\n if (head !== undefined) return { kind: 'head', lines: head, ...signalPart };\n if (tail !== undefined) return { kind: 'tail', lines: tail, ...signalPart };\n if (startLine !== undefined || endLine !== undefined) {\n return {\n kind: 'range',\n start: startLine ?? 1,\n ...(endLine !== undefined ? { end: endLine } : {}),\n ...signalPart,\n };\n }\n return { kind: 'full', ...signalPart };\n}\n\n// No `totalLines`: only `readFull` counts them and a full read never leaves\n// more behind, so a continuation cannot know the total without a second pass.\nfunction buildReadContinuation(\n result: ReadFileResult,\n requestedPath: string,\n): z.infer<typeof ContinuationSchema> | undefined {\n if (!result.hasMoreLines) return undefined;\n const linesRead = result.linesRead ?? 0;\n const nextStart = (result.startLine ?? 1) + linesRead;\n let chunkSize: number;\n if (result.head !== undefined) {\n chunkSize = result.head;\n } else if (result.startLine !== undefined && result.endLine !== undefined) {\n chunkSize = result.endLine - result.startLine + 1;\n } else {\n chunkSize = DEFAULT_CONTINUATION_CHUNK_SIZE;\n }\n const nextEnd = nextStart + chunkSize - 1;\n return {\n tool: 'read',\n args: { path: requestedPath, startLine: nextStart, endLine: nextEnd },\n hint: `More lines remain from ${String(nextStart)}. Read next chunk with these args.`,\n };\n}\n\n/**\n * The published metadata plus the bytes this call read. `content` and\n * `mediaData` exist only between `readOnePath` and the content blocks `run`\n * builds from them — they are stripped before the structured half is returned,\n * which is why they are not in `ReadPerPathValueSchema`.\n */\ntype PerPathReadValue = z.infer<typeof ReadPerPathValueSchema> & {\n content?: string;\n mediaData?: string;\n};\n\ninterface BatchFileInfo {\n index: number;\n size: number;\n validPath: string;\n stats: Stats;\n}\n\nasync function collectFileBudget(\n filePaths: readonly string[],\n maxTotalSize: number,\n maxSize: number,\n ctx: Pick<ToolCtx, 'fs' | 'signal' | 'log'>,\n): Promise<{\n skippedResults: Map<number, PerPathResult<PerPathReadValue>>;\n survivors: string[];\n known: Map<string, { validPath: string; stats: Stats }>;\n}> {\n const indexed = filePaths.map((path, index) => ({ path, index }));\n const { results } = await processInParallel(\n indexed,\n async ({ path, index }): Promise<BatchFileInfo | undefined> => {\n try {\n const out = await ctx.fs.stat(path);\n return {\n index,\n size: Math.min(out.stats.size, maxSize),\n validPath: out.validPath,\n stats: out.stats,\n };\n } catch (err: unknown) {\n ctx.log?.('debug', `collectFileBudget: stat failed for \"${path}\": ${String(err)}`, 'read');\n return undefined;\n }\n },\n PARALLEL_CONCURRENCY,\n ctx.signal,\n );\n\n const byIndex = new Map<number, number>();\n const known = new Map<string, { validPath: string; stats: Stats }>();\n for (const { value: item } of results) {\n if (!item) continue;\n byIndex.set(item.index, item.size);\n // Keyed by the ORIGINAL requested path string (not validPath) — that's\n // what readOnePath is called with downstream, and what filePaths[i]\n // holds.\n const requestedPath = filePaths[item.index];\n if (requestedPath !== undefined) {\n known.set(requestedPath, { validPath: item.validPath, stats: item.stats });\n }\n }\n\n let total = 0;\n const skippedResults = new Map<number, PerPathResult<PerPathReadValue>>();\n const survivors: string[] = [];\n let overflowed = false;\n for (let i = 0; i < filePaths.length; i += 1) {\n const path = filePaths[i];\n if (path === undefined) continue;\n const size = byIndex.get(i);\n if (overflowed) {\n // Only files that were actually stat'd get the TOO_LARGE result; a failed\n // stat falls through to survivors so its read surfaces the real error —\n // not a misleading TOO_LARGE.\n if (size !== undefined) {\n skippedResults.set(i, {\n path,\n error: {\n code: ErrorCode.TOO_LARGE,\n message: `Skipped: combined estimated read would exceed maxTotalSize (${String(maxTotalSize)} bytes)`,\n path,\n },\n });\n } else {\n survivors.push(path);\n }\n continue;\n }\n if (size === undefined) {\n survivors.push(path);\n continue;\n }\n if (total + size > maxTotalSize) {\n overflowed = true;\n skippedResults.set(i, {\n path,\n error: {\n code: ErrorCode.TOO_LARGE,\n message: `Skipped: combined estimated read would exceed maxTotalSize (${String(maxTotalSize)} bytes)`,\n path,\n },\n });\n continue;\n }\n total += size;\n survivors.push(path);\n }\n\n return { skippedResults, survivors, known };\n}\n\nfunction buildPerPathReadValue(\n result: ReadFileResult,\n options: { includeHash?: boolean; hasResourceStore?: boolean; requestedPath: string },\n): PerPathReadValue {\n const mimeInfo = detectMimeFromContent(result.path, result.content);\n const continuation =\n result.hasMoreLines && result.readMode !== 'tail'\n ? buildReadContinuation(result, options.requestedPath)\n : undefined;\n const contentHash = options.includeHash\n ? createHash('sha256').update(result.content, 'utf-8').digest('hex')\n : undefined;\n const resourceUri = options.hasResourceStore ? buildFileResourceUri(result.path) : undefined;\n\n return {\n content: result.content,\n mimeType: mimeInfo.mimeType,\n kind: mimeInfo.kind,\n ...(continuation ? { continuation } : {}),\n ...(result.totalLines !== undefined ? { totalLines: result.totalLines } : {}),\n ...(result.linesRead !== undefined ? { linesRead: result.linesRead } : {}),\n ...(result.hasMoreLines ? { hasMoreLines: true } : {}),\n ...(result.head !== undefined ? { head: result.head } : {}),\n ...(result.tail !== undefined ? { tail: result.tail } : {}),\n ...(result.startLine !== undefined ? { startLine: result.startLine } : {}),\n ...(result.endLine !== undefined ? { endLine: result.endLine } : {}),\n ...(contentHash !== undefined ? { contentHash } : {}),\n ...(resourceUri !== undefined ? { resourceUri } : {}),\n };\n}\n\n/**\n * The two facts the model cannot act on without: that lines were dropped, and\n * the exact args to get the next chunk. Both used to live only in the structured\n * half, which no longer reaches the model. Each line is `//` prefixed and set\n * off by a blank line so it cannot be read as file bytes — do not drop either\n * guard.\n */\nfunction readTrailer(v: PerPathReadValue): string[] {\n const lines: string[] = [];\n if (v.continuation) {\n lines.push(\n `// truncated: ${v.continuation.hint} Continue: read ${JSON.stringify(v.continuation.args)}`,\n );\n } else if (v.hasMoreLines && v.linesRead !== undefined) {\n // A tail read gets no continuation — there are no args that read *backwards*\n // — so say what was shown rather than leaving the truncation silent.\n lines.push(`// truncated: showing last ${String(v.linesRead)} lines`);\n }\n if (v.contentHash !== undefined) lines.push(`// sha256: ${v.contentHash}`);\n return lines;\n}\n\nasync function readOnePath(\n filePath: string,\n args: ReadFileInput,\n ctx: ToolCtx,\n known?: { validPath: string; stats: Stats },\n): Promise<PerPathReadValue> {\n // Image/audio full read: return a media content block instead of throwing\n // INVALID_INPUT (\"Binary file detected.\"). Line-range reads are\n // text-oriented and stay rejected. `readRaw` enforces the same size cap as\n // the text path (getMaxTextFileSize), so a too-large image surfaces TOO_LARGE\n // rather than blowing memory. svg carries kind:'image' but is XML text —\n // readRaw.isBinary is false for it, so it falls through to the text path.\n const isRangeRead =\n args.head !== undefined ||\n args.tail !== undefined ||\n args.startLine !== undefined ||\n args.endLine !== undefined;\n if (!isRangeRead) {\n const mime = detectMimeType(filePath);\n if (mime.kind === 'image' || mime.kind === 'audio') {\n const raw = await ctx.fs.readRaw(filePath, { signal: ctx.signal });\n if (raw.isBinary) {\n return {\n content: `[binary ${mime.kind} content: ${String(raw.content.length)} bytes; returned as a ${mime.kind} content block]`,\n mimeType: raw.mimeType,\n kind: mime.kind,\n mediaData: raw.content.toString('base64'),\n };\n }\n }\n }\n\n const spec = buildReadSpec(args, ctx.signal);\n const result = known\n ? await readFileWithStats(filePath, known.validPath, known.stats, spec)\n : await ctx.fs.readFile(filePath, spec);\n\n return buildPerPathReadValue(result, {\n includeHash: args.includeHash,\n hasResourceStore: ctx.resourceStore !== undefined,\n // The continuation is args the caller pastes back, so it echoes the path\n // they wrote. `result.path` is the resolved absolute one — on Windows that\n // is a backslash-doubling JSON string that also spells out the server root.\n requestedPath: filePath,\n });\n}\n\nexport const READ = defineTool({\n name: 'read',\n title: 'Read File',\n description:\n 'Read one or more text files and return content. ' +\n 'Partial reads: head (first N lines), tail (last N lines), startLine/endLine (line range). ' +\n 'Batch mode: pass paths[] instead of path; line params are shared across all files. ' +\n 'head, tail, and startLine/endLine are mutually exclusive — use exactly one.',\n input: ReadFileInputSchema,\n output: ReadFileOutputSchema,\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n destructiveHint: false,\n openWorldHint: false,\n },\n timeoutMs: DEFAULT_SEARCH_TIMEOUT_MS,\n defaultErrorCode: ErrorCode.NOT_FILE,\n progress: (args) => {\n const isBatch = args.paths !== undefined;\n const name = isBatch ? `${String(args.paths?.length ?? 0)} files` : basename(args.path ?? '');\n if (isBatch) {\n return { label: READ_TOOL_LABEL, subject: name };\n }\n let scope: string | undefined;\n if (args.startLine !== undefined) {\n const end = args.endLine ?? '...';\n scope = `${args.startLine}-${String(end)}`;\n } else if (args.head !== undefined) {\n scope = `head ${args.head}`;\n } else if (args.tail !== undefined) {\n scope = `tail ${args.tail}`;\n }\n return { label: READ_TOOL_LABEL, subject: name, ...(scope ? { scope } : {}) };\n },\n accessPaths: singleOrBatchAccessPaths,\n run: async (args, ctx) => {\n let pathList: string[];\n let skippedResults = new Map<number, PerPathResult<PerPathReadValue>>();\n let survivors: string[];\n let known = new Map<string, { validPath: string; stats: Stats }>();\n\n if (args.paths !== undefined) {\n pathList = args.paths;\n const budget = await collectFileBudget(\n pathList,\n READ_MANY_MAX_TOTAL_BYTES,\n getMaxTextFileSize(),\n ctx,\n );\n known = budget.known;\n skippedResults = budget.skippedResults;\n survivors = budget.survivors;\n } else {\n pathList = [args.path ?? ''];\n survivors = [...pathList];\n }\n\n const batchInput = { paths: survivors };\n\n // Every path can be budget-skipped (a single file over maxTotalSize does\n // it), and runOverPaths rejects an empty list. The per-path TOO_LARGE\n // results are already built — return those rather than failing the call.\n const batch =\n survivors.length === 0\n ? { results: [] as PerPathResult<PerPathReadValue>[] }\n : await runOverPaths<undefined, PerPathReadValue>(\n batchInput,\n ctx,\n ({ path }) => readOnePath(path, args, ctx, known.get(path)),\n { defaultErrorCode: ErrorCode.NOT_FILE },\n );\n\n const resultMap = new Map(batch.results.map((r) => [r.path, r]));\n const ordered: PerPathResult<PerPathReadValue>[] = pathList.map((path, idx) => {\n const skipped = skippedResults.get(idx);\n if (skipped) return skipped;\n const result = resultMap.get(path);\n return (\n result ?? {\n path,\n error: { code: ErrorCode.UNKNOWN, message: 'Unknown read failure' },\n }\n );\n });\n\n const failed = ordered.filter((r) => 'error' in r).length;\n const summary = {\n total: ordered.length,\n succeeded: ordered.length - failed,\n failed,\n };\n\n const resources: ContentBlock[] = [];\n for (const result of ordered) {\n if ('error' in result) continue;\n const v = result.value;\n // Image/audio full read: emit the media content block alongside the\n // structured value. The base64 lives in v.mediaData (set in readOnePath).\n if (v.mediaData && v.mimeType && (v.kind === 'image' || v.kind === 'audio')) {\n resources.push(\n v.kind === 'image'\n ? { type: 'image', data: v.mediaData, mimeType: v.mimeType }\n : { type: 'audio', data: v.mediaData, mimeType: v.mimeType },\n );\n continue;\n }\n if (!v.resourceUri || !v.content) continue;\n // `result.path` is the path as *requested*; `v.resourceUri` was built from\n // the *validated* one. Rebuilding from the request would emit a second URI\n // for the same file whenever the two differ in case — subscribe by one and\n // unsubscribe by the other and the watcher never goes away.\n resources.push(\n buildFileResourceLinkFor(\n v.resourceUri,\n basename(result.path),\n v.mimeType ?? 'application/octet-stream',\n Buffer.byteLength(v.content, 'utf8'),\n ),\n );\n }\n\n const [firstOrdered] = ordered;\n const body = (v: PerPathReadValue): string => {\n const content = v.content ?? 'read failed';\n const trailer = readTrailer(v);\n if (trailer.length === 0) return content;\n // Exactly one blank line between the bytes and the trailer, whether or not\n // the file ended in a newline.\n return `${content}${content.endsWith('\\n') ? '\\n' : '\\n\\n'}${trailer.join('\\n')}`;\n };\n const text =\n ordered.length === 1 && firstOrdered !== undefined\n ? 'error' in firstOrdered\n ? firstOrdered.error.message\n : body(firstOrdered.value)\n : ordered\n .map((r) => {\n const header = `// ${r.path}`;\n if ('value' in r) return `${header}\\n${body(r.value)}`;\n return `${header}\\n// Error: ${r.error.message}`;\n })\n .join('\\n\\n');\n\n // The bytes ship once. `text` above already carries every file's content\n // verbatim (and image/audio bytes ride the media content block), so\n // repeating them under `results[].value` doubled both the wire payload and\n // the model's token cost for every read. The structured half keeps the\n // metadata a client cannot recover from the text: paths, line counts,\n // hashes, continuations, resourceUri.\n const structuredResults = ordered.map((result) => {\n if ('error' in result) return result;\n const { content: _content, mediaData: _mediaData, ...value } = result.value;\n return { ...result, value };\n });\n\n return {\n structured: { results: structuredResults, summary },\n text,\n isError: isTotalFailure(summary),\n ...(resources.length > 0 ? { resources } : {}),\n };\n },\n});\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const REPLACE_TEXT: import("./define.
|
|
1
|
+
export declare const REPLACE_TEXT: import("./define.ts").DefinedTool;
|
|
2
2
|
//# sourceMappingURL=replace-text.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"replace-text.d.ts","sourceRoot":"","sources":["../../src/tools/replace-text.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"replace-text.d.ts","sourceRoot":"","sources":["../../src/tools/replace-text.ts"],"names":[],"mappings":"AA8jBA,eAAO,MAAM,YAAY,mCAyCvB,CAAC"}
|