@milaboratories/pl-mcp-server 53.0.0 → 54.0.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/README.md +36 -2
- package/dist/instructions.cjs +3 -2
- package/dist/instructions.cjs.map +1 -1
- package/dist/instructions.js +3 -2
- package/dist/instructions.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/project-holds.cjs +72 -0
- package/dist/project-holds.cjs.map +1 -0
- package/dist/project-holds.js +72 -0
- package/dist/project-holds.js.map +1 -0
- package/dist/server-log.cjs +373 -0
- package/dist/server-log.cjs.map +1 -0
- package/dist/server-log.js +371 -0
- package/dist/server-log.js.map +1 -0
- package/dist/server.cjs +77 -22
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +31 -7
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +77 -23
- package/dist/server.js.map +1 -1
- package/dist/tools/await.cjs +59 -60
- package/dist/tools/await.cjs.map +1 -1
- package/dist/tools/await.js +60 -61
- package/dist/tools/await.js.map +1 -1
- package/dist/tools/block-action-context.cjs +11 -9
- package/dist/tools/block-action-context.cjs.map +1 -1
- package/dist/tools/block-action-context.js +11 -9
- package/dist/tools/block-action-context.js.map +1 -1
- package/dist/tools/block-params.cjs +4 -3
- package/dist/tools/block-params.cjs.map +1 -1
- package/dist/tools/block-params.js +4 -3
- package/dist/tools/block-params.js.map +1 -1
- package/dist/tools/block-state.cjs +46 -41
- package/dist/tools/block-state.cjs.map +1 -1
- package/dist/tools/block-state.js +47 -42
- package/dist/tools/block-state.js.map +1 -1
- package/dist/tools/blocks.cjs +30 -20
- package/dist/tools/blocks.cjs.map +1 -1
- package/dist/tools/blocks.js +30 -20
- package/dist/tools/blocks.js.map +1 -1
- package/dist/tools/connection.cjs.map +1 -1
- package/dist/tools/connection.js.map +1 -1
- package/dist/tools/data-query.cjs +111 -80
- package/dist/tools/data-query.cjs.map +1 -1
- package/dist/tools/data-query.js +114 -83
- package/dist/tools/data-query.js.map +1 -1
- package/dist/tools/ids.cjs +16 -0
- package/dist/tools/ids.cjs.map +1 -1
- package/dist/tools/ids.js +13 -1
- package/dist/tools/ids.js.map +1 -1
- package/dist/tools/logs.cjs +28 -26
- package/dist/tools/logs.cjs.map +1 -1
- package/dist/tools/logs.js +28 -26
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/ping.cjs.map +1 -1
- package/dist/tools/ping.js.map +1 -1
- package/dist/tools/projects.cjs +10 -27
- package/dist/tools/projects.cjs.map +1 -1
- package/dist/tools/projects.js +11 -28
- package/dist/tools/projects.js.map +1 -1
- package/dist/tools/sandbox.cjs +110 -8
- package/dist/tools/sandbox.cjs.map +1 -1
- package/dist/tools/sandbox.js +107 -9
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/screenshot.cjs +9 -1
- package/dist/tools/screenshot.cjs.map +1 -1
- package/dist/tools/screenshot.js +9 -1
- package/dist/tools/screenshot.js.map +1 -1
- package/dist/tools/types.cjs +29 -0
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js +27 -1
- package/dist/tools/types.js.map +1 -1
- package/dist/tools/ui-interaction.cjs.map +1 -1
- package/dist/tools/ui-interaction.js.map +1 -1
- package/package.json +6 -5
- package/src/instructions.ts +3 -2
- package/src/project-holds.test.ts +183 -0
- package/src/project-holds.ts +105 -0
- package/src/server-log.test.ts +871 -0
- package/src/server-log.ts +504 -0
- package/src/server.logging.test.ts +383 -0
- package/src/server.request-failure.test.ts +49 -0
- package/src/server.test.ts +15 -5
- package/src/server.ts +111 -26
- package/src/test/recording-logger.ts +33 -0
- package/src/tools/await.ts +96 -98
- package/src/tools/block-action-context.ts +16 -16
- package/src/tools/block-params.ts +6 -6
- package/src/tools/block-state.ts +61 -60
- package/src/tools/blocks.ts +49 -40
- package/src/tools/connection.ts +2 -3
- package/src/tools/data-query.ts +151 -108
- package/src/tools/ids.ts +22 -1
- package/src/tools/logs.ts +43 -43
- package/src/tools/ping.ts +2 -3
- package/src/tools/projects.ts +22 -45
- package/src/tools/sandbox.test.ts +183 -0
- package/src/tools/sandbox.ts +126 -10
- package/src/tools/screenshot.ts +15 -4
- package/src/tools/types.test.ts +4 -3
- package/src/tools/types.ts +73 -3
- package/src/tools/ui-interaction.ts +2 -3
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
import type { MiLogger } from "@milaboratories/helpers";
|
|
2
|
+
import type { ProjectId } from "@milaboratories/pl-model-common";
|
|
3
|
+
import { inspect } from "node:util";
|
|
4
|
+
import type { McpInstanceId } from "./server";
|
|
5
|
+
import type { ToolRegistrar } from "./tools/types";
|
|
6
|
+
import { isTimedOutResult } from "./tools/types";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A call taking longer than this many milliseconds is reported as slow, unless its tool is one of
|
|
10
|
+
* {@link WAITING_TOOLS}.
|
|
11
|
+
*/
|
|
12
|
+
export const SLOW_CALL_MS = 5000;
|
|
13
|
+
|
|
14
|
+
/** Tools whose job is to wait: a long call of one of these is not reported as slow. */
|
|
15
|
+
const WAITING_TOOLS: ReadonlySet<string> = new Set(["await_block_done"]);
|
|
16
|
+
|
|
17
|
+
/** Longest id written to a line; a longer one is cut, so that a line stays a line. */
|
|
18
|
+
const MAX_ID_LENGTH = 200;
|
|
19
|
+
|
|
20
|
+
/** Longest error summary written to the first line of a failure; the whole text follows it. */
|
|
21
|
+
const MAX_SUMMARY_LENGTH = 300;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* How deep an error is written: each error of a `cause` chain is one level, and so is each nested
|
|
25
|
+
* object in a property of an error. What lies deeper is written as its class only (`[Error]`).
|
|
26
|
+
*/
|
|
27
|
+
const MAX_ERROR_DEPTH = 6;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Top-level arguments whose values are secrets, by key name: their values are removed from the
|
|
31
|
+
* text of a failure like the secret of the server. `password` (of `connect_to_server`) is the one
|
|
32
|
+
* such argument a tool has now; the others are the names a credential would get. Block data is not
|
|
33
|
+
* searched: like the rest of the application's log, this one may quote it.
|
|
34
|
+
*/
|
|
35
|
+
const SECRET_ARGUMENTS: ReadonlySet<string> = new Set(["password", "token", "secret", "apiKey"]);
|
|
36
|
+
|
|
37
|
+
/** What replaces a secret in a line. */
|
|
38
|
+
const SECRET_MARK = "<secret>";
|
|
39
|
+
|
|
40
|
+
/** A value that needs no quotes to stay one `key=value` token. */
|
|
41
|
+
const BARE_VALUE = /^[A-Za-z0-9_.:#+\-/@,]+$/;
|
|
42
|
+
|
|
43
|
+
/** How a tool call ended. */
|
|
44
|
+
export type CallOutcome =
|
|
45
|
+
/** The handler returned a result. */
|
|
46
|
+
| "ok"
|
|
47
|
+
/** The handler returned a result with `isError: true`. */
|
|
48
|
+
| "error"
|
|
49
|
+
/** The handler threw. */
|
|
50
|
+
| "thrown";
|
|
51
|
+
|
|
52
|
+
/** The counters of one backend client, read at a moment. */
|
|
53
|
+
export type TxCounters = {
|
|
54
|
+
/** The client the counters belong to: numbers of two clients are not compared. */
|
|
55
|
+
client: object;
|
|
56
|
+
/** Write transactions that failed to commit because of a conflict and were retried, so far. */
|
|
57
|
+
conflicts: number;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/** What a {@link ServerLog} is made of. */
|
|
61
|
+
export type ServerLogOptions = {
|
|
62
|
+
/** Where the lines go. */
|
|
63
|
+
logger: MiLogger;
|
|
64
|
+
/** Id of the server instance, the first part of every call id: `mcp-<8 hex>`. */
|
|
65
|
+
instanceId: McpInstanceId;
|
|
66
|
+
/** Reads the counters of the connected backend client; `undefined` when there is none. */
|
|
67
|
+
txCounters?: () => TxCounters | undefined;
|
|
68
|
+
/** Strings that must not reach the log. An occurrence in a line is replaced with `<secret>`. */
|
|
69
|
+
secrets?: readonly string[];
|
|
70
|
+
/** See {@link SLOW_CALL_MS}. */
|
|
71
|
+
slowCallMs?: number;
|
|
72
|
+
/** Clock in milliseconds; only differences are used. */
|
|
73
|
+
now?: () => number;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/** What is known about a call when it starts. */
|
|
77
|
+
type StartedCall = {
|
|
78
|
+
id: string;
|
|
79
|
+
/**
|
|
80
|
+
* The arguments, as the handler got them. They are not written: they are read only to find the
|
|
81
|
+
* values of secret arguments (see {@link SECRET_ARGUMENTS}), and only when the call failed.
|
|
82
|
+
*/
|
|
83
|
+
args: unknown;
|
|
84
|
+
tool: string;
|
|
85
|
+
/** Other calls that were being served when this one started. */
|
|
86
|
+
inFlight: number;
|
|
87
|
+
startedAt: number | undefined;
|
|
88
|
+
projectId: string | undefined;
|
|
89
|
+
blockId: string | undefined;
|
|
90
|
+
argsBytes: number | undefined;
|
|
91
|
+
argKeys: string[] | undefined;
|
|
92
|
+
tx: TxCounters | undefined;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/** How a handler finished. */
|
|
96
|
+
type Finish = { thrown: false; result: unknown } | { thrown: true; error: unknown };
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Writes what the MCP server does to a logger: one line per tool call, more for a call that
|
|
100
|
+
* failed, was slow or ran out of time, and lines for the server's start, stop and the failures
|
|
101
|
+
* that happen outside tool handlers.
|
|
102
|
+
*
|
|
103
|
+
* Two rules hold for everything here. No secret is ever written: neither the secret of the server
|
|
104
|
+
* nor the value of a secret argument (see {@link SECRET_ARGUMENTS}); each is replaced with
|
|
105
|
+
* `<secret>`. The line of a call holds of its arguments only sizes, the names of the top-level
|
|
106
|
+
* ones and the project and block ids; the line of a failure holds the error as it is, which can
|
|
107
|
+
* quote other arguments and data, as the rest of the application's log does. And nothing here
|
|
108
|
+
* throws: a logger that fails, or a value that cannot be measured, costs a line or a field, never
|
|
109
|
+
* the call.
|
|
110
|
+
*/
|
|
111
|
+
export class ServerLog {
|
|
112
|
+
private readonly logger: MiLogger;
|
|
113
|
+
private readonly instanceId: McpInstanceId;
|
|
114
|
+
private readonly txCounters: () => TxCounters | undefined;
|
|
115
|
+
/** Removes the secrets from a text; for the lines and fields that are not about a call's arguments. */
|
|
116
|
+
private readonly secrets: Redactor;
|
|
117
|
+
private readonly slowCallMs: number;
|
|
118
|
+
private readonly now: () => number;
|
|
119
|
+
|
|
120
|
+
/** Calls started so far; the number of the last one. */
|
|
121
|
+
private calls = 0;
|
|
122
|
+
/** Calls being served now. */
|
|
123
|
+
private inFlight = 0;
|
|
124
|
+
|
|
125
|
+
constructor(options: ServerLogOptions) {
|
|
126
|
+
this.logger = options.logger;
|
|
127
|
+
this.instanceId = options.instanceId;
|
|
128
|
+
this.txCounters = options.txCounters ?? (() => undefined);
|
|
129
|
+
this.secrets = new Redactor(options.secrets ?? []);
|
|
130
|
+
this.slowCallMs = options.slowCallMs ?? SLOW_CALL_MS;
|
|
131
|
+
this.now = options.now ?? (() => performance.now());
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Returns a registrar that registers tools with `target` and logs every call of them.
|
|
136
|
+
*
|
|
137
|
+
* The handler itself is left as given: the logging goes around the function the SDK calls to run
|
|
138
|
+
* the tool (`RegisteredTool.executor`), which receives the arguments after validation. The SDK
|
|
139
|
+
* makes that function anew when a tool's handler or input schema is replaced with
|
|
140
|
+
* `RegisteredTool.update`, which would drop the logging; no tool of this server does that.
|
|
141
|
+
*/
|
|
142
|
+
registrar(target: ToolRegistrar): ToolRegistrar {
|
|
143
|
+
return {
|
|
144
|
+
registerTool: (name, config, cb) => {
|
|
145
|
+
const tool = target.registerTool(name, config, cb);
|
|
146
|
+
const execute = tool.executor;
|
|
147
|
+
tool.executor = (args, ctx) => this.run(name, args, () => execute(args, ctx));
|
|
148
|
+
return tool;
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Runs one tool call and logs how it went. Returns what `execute` returns and throws what it
|
|
155
|
+
* throws, whatever happens to the logging.
|
|
156
|
+
*/
|
|
157
|
+
async run<T>(tool: string, args: unknown, execute: () => Promise<T>): Promise<T> {
|
|
158
|
+
const call = this.begin(tool, args);
|
|
159
|
+
let result: T;
|
|
160
|
+
try {
|
|
161
|
+
result = await execute();
|
|
162
|
+
} catch (error: unknown) {
|
|
163
|
+
this.finish(call, { thrown: true, error });
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
this.finish(call, { thrown: false, result });
|
|
167
|
+
return result;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** The server listens on `port`. */
|
|
171
|
+
serverStarted(port: number, version: string): void {
|
|
172
|
+
this.write(
|
|
173
|
+
"info",
|
|
174
|
+
() =>
|
|
175
|
+
`mcp-server-start ${fields({
|
|
176
|
+
id: this.instanceId,
|
|
177
|
+
port,
|
|
178
|
+
url: `http://127.0.0.1:${port}/<secret>/mcp`,
|
|
179
|
+
version,
|
|
180
|
+
})}`,
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The server no longer listens on `port`. */
|
|
185
|
+
serverStopped(port: number): void {
|
|
186
|
+
this.write(
|
|
187
|
+
"info",
|
|
188
|
+
() =>
|
|
189
|
+
`mcp-server-stop ${fields({
|
|
190
|
+
id: this.instanceId,
|
|
191
|
+
port,
|
|
192
|
+
calls: this.calls,
|
|
193
|
+
inflight: this.inFlight,
|
|
194
|
+
})}`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The server gave back its hold on a project it had kept loaded between calls. */
|
|
199
|
+
projectReleased(projectId: ProjectId, reason: string): void {
|
|
200
|
+
this.write(
|
|
201
|
+
"info",
|
|
202
|
+
() => `mcp-project-release ${fields({ id: this.instanceId, project: projectId, reason })}`,
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* An HTTP request failed outside the MCP handler. `status` is what it is answered with, absent
|
|
208
|
+
* when the answer had already begun.
|
|
209
|
+
*/
|
|
210
|
+
requestFailed(method: string | undefined, status: number | undefined, error: unknown): void {
|
|
211
|
+
this.write(
|
|
212
|
+
"error",
|
|
213
|
+
() =>
|
|
214
|
+
`mcp-request-failed ${fields({
|
|
215
|
+
id: this.instanceId,
|
|
216
|
+
method,
|
|
217
|
+
status,
|
|
218
|
+
error: summary(this.secrets.redact(errorMessage(error))),
|
|
219
|
+
})}\n${this.secrets.redact(errorText(error))}`,
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** The MCP handler reported an error that no tool call accounts for. */
|
|
224
|
+
sdkError(error: unknown): void {
|
|
225
|
+
this.write(
|
|
226
|
+
"error",
|
|
227
|
+
() =>
|
|
228
|
+
`mcp-sdk-error ${fields({
|
|
229
|
+
id: this.instanceId,
|
|
230
|
+
error: summary(this.secrets.redact(errorMessage(error))),
|
|
231
|
+
})}\n${this.secrets.redact(errorText(error))}`,
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private begin(tool: string, args: unknown): StartedCall {
|
|
236
|
+
const call: StartedCall = {
|
|
237
|
+
id: `${this.instanceId}#${++this.calls}`,
|
|
238
|
+
args,
|
|
239
|
+
tool,
|
|
240
|
+
inFlight: this.inFlight++,
|
|
241
|
+
startedAt: undefined,
|
|
242
|
+
projectId: undefined,
|
|
243
|
+
blockId: undefined,
|
|
244
|
+
argsBytes: undefined,
|
|
245
|
+
argKeys: undefined,
|
|
246
|
+
tx: undefined,
|
|
247
|
+
};
|
|
248
|
+
attempt(() => {
|
|
249
|
+
call.projectId = stringProperty(args, "projectId");
|
|
250
|
+
call.blockId = stringProperty(args, "blockId");
|
|
251
|
+
call.argKeys = isRecord(args) ? Object.keys(args) : [];
|
|
252
|
+
call.argsBytes = jsonBytes(args);
|
|
253
|
+
});
|
|
254
|
+
attempt(() => {
|
|
255
|
+
call.tx = this.txCounters();
|
|
256
|
+
});
|
|
257
|
+
attempt(() => {
|
|
258
|
+
call.startedAt = this.now();
|
|
259
|
+
});
|
|
260
|
+
return call;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
private finish(call: StartedCall, finish: Finish): void {
|
|
264
|
+
this.inFlight--;
|
|
265
|
+
|
|
266
|
+
const ms = attempt(() =>
|
|
267
|
+
call.startedAt === undefined ? undefined : Math.round(this.now() - call.startedAt),
|
|
268
|
+
);
|
|
269
|
+
const failure = attempt(() => failureOf(finish));
|
|
270
|
+
const outcome: CallOutcome = finish.thrown ? "thrown" : failure === undefined ? "ok" : "error";
|
|
271
|
+
// A secret is removed before an id is cut, so that no part of it is left.
|
|
272
|
+
const subject = {
|
|
273
|
+
call: call.id,
|
|
274
|
+
tool: call.tool,
|
|
275
|
+
project: attempt(() => cut(this.secrets.redact(call.projectId))),
|
|
276
|
+
block: attempt(() => cut(this.secrets.redact(call.blockId))),
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
this.write("info", () => {
|
|
280
|
+
const before = call.tx;
|
|
281
|
+
const after = before === undefined ? undefined : attempt(() => this.txCounters());
|
|
282
|
+
return `mcp-call ${fields({
|
|
283
|
+
...subject,
|
|
284
|
+
argsBytes: call.argsBytes,
|
|
285
|
+
ms,
|
|
286
|
+
outcome,
|
|
287
|
+
// Nothing was returned by a handler that threw.
|
|
288
|
+
resultBytes: finish.thrown ? 0 : attempt(() => contentBytes(finish.result)),
|
|
289
|
+
inflight: call.inFlight,
|
|
290
|
+
// Counted on the backend client, so every call in flight at the time gets the same number.
|
|
291
|
+
txConflictsDuring:
|
|
292
|
+
before !== undefined && after !== undefined && before.client === after.client
|
|
293
|
+
? after.conflicts - before.conflicts
|
|
294
|
+
: undefined,
|
|
295
|
+
})}`;
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
if (outcome !== "ok")
|
|
299
|
+
this.write("error", () => {
|
|
300
|
+
// Secrets are removed from the whole texts, before any is cut: a secret cut in two would
|
|
301
|
+
// no longer be found.
|
|
302
|
+
const secrets = this.secrets.with(secretArgumentValues(call.args));
|
|
303
|
+
const text = secrets.redact(failure ?? "");
|
|
304
|
+
const message = finish.thrown ? secrets.redact(errorMessage(finish.error)) : text;
|
|
305
|
+
return `mcp-call-failed ${fields({
|
|
306
|
+
...subject,
|
|
307
|
+
outcome,
|
|
308
|
+
argKeys: (call.argKeys ?? []).join(","),
|
|
309
|
+
error: summary(message),
|
|
310
|
+
})}\n${text}`;
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
if (!finish.thrown && attempt(() => isTimedOutResult(finish.result)) === true)
|
|
314
|
+
this.write("warn", () => `mcp-call-timeout ${fields({ ...subject, ms })}`);
|
|
315
|
+
|
|
316
|
+
if (ms !== undefined && ms > this.slowCallMs && !WAITING_TOOLS.has(call.tool))
|
|
317
|
+
this.write(
|
|
318
|
+
"warn",
|
|
319
|
+
() => `mcp-call-slow ${fields({ ...subject, ms, thresholdMs: this.slowCallMs })}`,
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Writes one line, built by `line`. Neither building it nor the logger can make this throw, and a
|
|
325
|
+
* logger that returns a promise cannot make it reject unhandled.
|
|
326
|
+
*/
|
|
327
|
+
private write(level: "info" | "warn" | "error", line: () => string): void {
|
|
328
|
+
try {
|
|
329
|
+
// The texts in a line were redacted before they were cut; this pass over the whole line is
|
|
330
|
+
// for anything that still holds a secret.
|
|
331
|
+
const returned: unknown = this.logger[level](this.secrets.redact(line()));
|
|
332
|
+
if (isThenable(returned)) void returned.then(undefined, () => {});
|
|
333
|
+
} catch {
|
|
334
|
+
// A line is lost. The call it describes must not be.
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Runs `fn`; a failure gives `undefined`. For the measurements a line can do without. */
|
|
340
|
+
function attempt<T>(fn: () => T): T | undefined {
|
|
341
|
+
try {
|
|
342
|
+
return fn();
|
|
343
|
+
} catch {
|
|
344
|
+
return undefined;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function isThenable(value: unknown): value is PromiseLike<unknown> {
|
|
349
|
+
return (
|
|
350
|
+
(typeof value === "object" || typeof value === "function") &&
|
|
351
|
+
value !== null &&
|
|
352
|
+
"then" in value &&
|
|
353
|
+
typeof value.then === "function"
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
358
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function stringProperty(value: unknown, key: string): string | undefined {
|
|
362
|
+
if (!isRecord(value)) return undefined;
|
|
363
|
+
const property = value[key];
|
|
364
|
+
return typeof property === "string" ? property : undefined;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Size of `value` written as JSON, in bytes of UTF-8; 0 for a value JSON has no form for. */
|
|
368
|
+
function jsonBytes(value: unknown): number {
|
|
369
|
+
const json: string | undefined = JSON.stringify(value);
|
|
370
|
+
return json === undefined ? 0 : Buffer.byteLength(json);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Size of what a tool result carries to the agent: the UTF-8 bytes of its texts plus the length of
|
|
375
|
+
* its base64 data (images, audio, binary resources) as sent. It is the size of the content, not of
|
|
376
|
+
* the JSON the result is sent as: the envelope, the escaping and `structuredContent` are not
|
|
377
|
+
* counted, and the result is not serialized again to measure it. `undefined` for a value that is
|
|
378
|
+
* not a tool result.
|
|
379
|
+
*/
|
|
380
|
+
function contentBytes(result: unknown): number | undefined {
|
|
381
|
+
if (!isRecord(result) || !Array.isArray(result.content)) return undefined;
|
|
382
|
+
const textBytes = (text: string | undefined) =>
|
|
383
|
+
text === undefined ? 0 : Buffer.byteLength(text);
|
|
384
|
+
const dataLength = (data: string | undefined) => data?.length ?? 0;
|
|
385
|
+
let bytes = 0;
|
|
386
|
+
for (const item of result.content) {
|
|
387
|
+
const resource = isRecord(item) ? item.resource : undefined;
|
|
388
|
+
bytes +=
|
|
389
|
+
textBytes(stringProperty(item, "text")) +
|
|
390
|
+
dataLength(stringProperty(item, "data")) +
|
|
391
|
+
textBytes(stringProperty(resource, "text")) +
|
|
392
|
+
dataLength(stringProperty(resource, "blob"));
|
|
393
|
+
}
|
|
394
|
+
return bytes;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** The values of the secret arguments of a call (see {@link SECRET_ARGUMENTS}) that are strings. */
|
|
398
|
+
function secretArgumentValues(args: unknown): string[] {
|
|
399
|
+
if (!isRecord(args)) return [];
|
|
400
|
+
return Object.entries(args)
|
|
401
|
+
.filter(([key]) => SECRET_ARGUMENTS.has(key))
|
|
402
|
+
.map(([, value]) => value)
|
|
403
|
+
.filter((value) => typeof value === "string");
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Replaces each of a few strings in a text with `<secret>`, the longest first, so a secret that
|
|
408
|
+
* contains another is replaced whole. A secret is also found in the escaped forms it takes in a
|
|
409
|
+
* formatted text: inside a JSON string and inside a string written by `util.inspect` (the
|
|
410
|
+
* properties of an error), where a backslash or a quote is written with a backslash.
|
|
411
|
+
*/
|
|
412
|
+
class Redactor {
|
|
413
|
+
/** The secrets as given. */
|
|
414
|
+
private readonly given: readonly string[];
|
|
415
|
+
/** Every form of every secret, the longest first. */
|
|
416
|
+
private readonly forms: readonly string[];
|
|
417
|
+
|
|
418
|
+
constructor(secrets: Iterable<string>) {
|
|
419
|
+
this.given = [...new Set(secrets)].filter((secret) => secret.length > 0);
|
|
420
|
+
this.forms = [...new Set(this.given.flatMap(escapedForms))].sort((a, b) => b.length - a.length);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** A redactor that removes `more` as well. */
|
|
424
|
+
with(more: Iterable<string>): Redactor {
|
|
425
|
+
return new Redactor([...this.given, ...more]);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
redact(text: string): string;
|
|
429
|
+
redact(text: string | undefined): string | undefined;
|
|
430
|
+
redact(text: string | undefined): string | undefined {
|
|
431
|
+
if (text === undefined) return text;
|
|
432
|
+
let redacted = text;
|
|
433
|
+
for (const form of this.forms) redacted = redacted.replaceAll(form, SECRET_MARK);
|
|
434
|
+
return redacted;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** A secret as it is, and as it is written inside a JSON string and by `util.inspect`. */
|
|
439
|
+
function escapedForms(secret: string): string[] {
|
|
440
|
+
return [secret, JSON.stringify(secret).slice(1, -1), inspect(secret).slice(1, -1)];
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function cut(id: string | undefined): string | undefined {
|
|
444
|
+
if (id === undefined || id.length <= MAX_ID_LENGTH) return id;
|
|
445
|
+
return `${id.slice(0, MAX_ID_LENGTH)}…`;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** The first line of `text`, cut to a length that fits the first line of a log entry. */
|
|
449
|
+
function summary(text: string): string {
|
|
450
|
+
const firstLine = text.split("\n", 1)[0] ?? "";
|
|
451
|
+
return firstLine.length <= MAX_SUMMARY_LENGTH
|
|
452
|
+
? firstLine
|
|
453
|
+
: `${firstLine.slice(0, MAX_SUMMARY_LENGTH)}…`;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Writes fields as `key=value` separated by spaces, in the order given, leaving out the undefined
|
|
458
|
+
* ones. A value with a space, a quote or anything else outside {@link BARE_VALUE} is written as a
|
|
459
|
+
* JSON string, so a line never breaks and a field never runs into the next one.
|
|
460
|
+
*/
|
|
461
|
+
export function fields(values: Record<string, string | number | undefined>): string {
|
|
462
|
+
const parts: string[] = [];
|
|
463
|
+
for (const [key, value] of Object.entries(values)) {
|
|
464
|
+
if (value === undefined) continue;
|
|
465
|
+
const text = String(value);
|
|
466
|
+
parts.push(`${key}=${BARE_VALUE.test(text) ? text : JSON.stringify(text)}`);
|
|
467
|
+
}
|
|
468
|
+
return parts.join(" ");
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* The text of a failed call: of a thrown error, the error with its causes (see {@link errorText});
|
|
473
|
+
* of a result with `isError: true`, its text as the handler wrote it. `undefined` for a call that
|
|
474
|
+
* succeeded.
|
|
475
|
+
*/
|
|
476
|
+
function failureOf(finish: Finish): string | undefined {
|
|
477
|
+
if (finish.thrown) return errorText(finish.error);
|
|
478
|
+
const result = finish.result;
|
|
479
|
+
if (!isRecord(result) || result.isError !== true) return undefined;
|
|
480
|
+
const content = Array.isArray(result.content) ? result.content : [];
|
|
481
|
+
return content
|
|
482
|
+
.map((item: unknown) => stringProperty(item, "text"))
|
|
483
|
+
.filter((text) => text !== undefined)
|
|
484
|
+
.join("\n");
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function errorMessage(error: unknown): string {
|
|
488
|
+
if (error instanceof Error) return error.message;
|
|
489
|
+
return typeof error === "string" ? error : describeValue(error);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function describeValue(value: unknown): string {
|
|
493
|
+
return attempt(() => JSON.stringify(value)) ?? String(value);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Writes an error with everything a reader needs to find where it came from, as Node writes it:
|
|
498
|
+
* the stack of the error, its other properties and every error of its `cause` chain with its
|
|
499
|
+
* stack, up to {@link MAX_ERROR_DEPTH}. A thrown string is written as it is.
|
|
500
|
+
*/
|
|
501
|
+
function errorText(error: unknown): string {
|
|
502
|
+
if (typeof error === "string") return error;
|
|
503
|
+
return attempt(() => inspect(error, { colors: false, depth: MAX_ERROR_DEPTH })) ?? String(error);
|
|
504
|
+
}
|