@duckmind/dm-windows-x64 0.63.6 → 0.63.9
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/dm.exe +0 -0
- package/extensions/.dm-extensions.json +174 -11
- package/extensions/dm-mcp-adapter/OAUTH.md +3 -0
- package/extensions/dm-mcp-adapter/THIRD_PARTY_NOTICES.md +4 -0
- package/extensions/dm-mcp-adapter/abort.js +35 -0
- package/extensions/dm-mcp-adapter/agent-dir.js +45 -0
- package/extensions/dm-mcp-adapter/agent-plugin-loader.js +349 -0
- package/extensions/dm-mcp-adapter/app-bridge.bundle.js +5843 -0
- package/extensions/dm-mcp-adapter/cli.js +354 -0
- package/extensions/dm-mcp-adapter/commands.js +619 -0
- package/extensions/dm-mcp-adapter/config.js +1060 -0
- package/extensions/dm-mcp-adapter/consent-manager.js +60 -0
- package/extensions/dm-mcp-adapter/direct-tools.js +544 -0
- package/extensions/dm-mcp-adapter/dist/agent-dir.js +45 -0
- package/extensions/dm-mcp-adapter/dist/agent-plugin-loader.js +349 -0
- package/extensions/dm-mcp-adapter/dist/config.js +1060 -0
- package/extensions/dm-mcp-adapter/dist/mcp-bearer-store.js +311 -0
- package/extensions/dm-mcp-adapter/dist/metadata-cache.js +285 -0
- package/extensions/dm-mcp-adapter/dist/package-mcp-loader.js +144 -0
- package/extensions/dm-mcp-adapter/dist/resource-tools.js +7 -0
- package/extensions/dm-mcp-adapter/dist/types.js +247 -0
- package/extensions/dm-mcp-adapter/dist/ui-app-bridge-helpers.js +36 -0
- package/extensions/dm-mcp-adapter/dist/ui-stream-types.js +58 -0
- package/extensions/dm-mcp-adapter/dist/ui-tool-visibility.js +26 -0
- package/extensions/dm-mcp-adapter/dist/utils.js +307 -0
- package/extensions/dm-mcp-adapter/elicitation-handler.js +306 -0
- package/extensions/dm-mcp-adapter/error-signal.js +16 -0
- package/extensions/dm-mcp-adapter/errors.js +225 -0
- package/extensions/dm-mcp-adapter/failure-backoff.js +19 -0
- package/extensions/dm-mcp-adapter/glimpse-ui.js +61 -0
- package/extensions/dm-mcp-adapter/host-html-template.js +464 -0
- package/extensions/dm-mcp-adapter/index.js +1079 -0
- package/extensions/dm-mcp-adapter/init.js +624 -0
- package/extensions/dm-mcp-adapter/json-schema-validator.js +53 -0
- package/extensions/dm-mcp-adapter/lifecycle.js +385 -0
- package/extensions/dm-mcp-adapter/logger.js +115 -0
- package/extensions/dm-mcp-adapter/mcp-auth-flow.js +824 -0
- package/extensions/dm-mcp-adapter/mcp-auth.js +732 -0
- package/extensions/dm-mcp-adapter/mcp-bearer-store.js +311 -0
- package/extensions/dm-mcp-adapter/mcp-callback-server.js +388 -0
- package/extensions/dm-mcp-adapter/mcp-code.js +291 -0
- package/extensions/dm-mcp-adapter/mcp-keyring-helper.cjs +88 -0
- package/extensions/dm-mcp-adapter/mcp-oauth-provider.js +490 -0
- package/extensions/dm-mcp-adapter/mcp-output-guard.js +386 -0
- package/extensions/dm-mcp-adapter/mcp-panel.js +951 -0
- package/extensions/dm-mcp-adapter/mcp-probe.js +151 -0
- package/extensions/dm-mcp-adapter/mcp-references.js +263 -0
- package/extensions/dm-mcp-adapter/mcp-script-worker.mjs +126 -0
- package/extensions/dm-mcp-adapter/mcp-setup-panel.js +578 -0
- package/extensions/dm-mcp-adapter/mcp-status.js +80 -0
- package/extensions/dm-mcp-adapter/mcp-trace.js +215 -0
- package/extensions/dm-mcp-adapter/metadata-cache.js +292 -0
- package/extensions/dm-mcp-adapter/namespace-tools.js +155 -0
- package/extensions/dm-mcp-adapter/npx-resolver.js +465 -0
- package/extensions/dm-mcp-adapter/oauth-handler.js +17 -0
- package/extensions/dm-mcp-adapter/oauth.js +17 -0
- package/extensions/dm-mcp-adapter/onboarding-state.js +62 -0
- package/extensions/dm-mcp-adapter/package-mcp-loader.js +144 -0
- package/extensions/dm-mcp-adapter/package.json +68 -0
- package/extensions/dm-mcp-adapter/panel-keys.js +26 -0
- package/extensions/dm-mcp-adapter/prompts.js +258 -0
- package/extensions/dm-mcp-adapter/proxy-modes.js +1336 -0
- package/extensions/dm-mcp-adapter/request-headers-command.js +293 -0
- package/extensions/dm-mcp-adapter/resource-tools.js +7 -0
- package/extensions/dm-mcp-adapter/runtime-owner.js +79 -0
- package/extensions/dm-mcp-adapter/sampling-handler.js +222 -0
- package/extensions/dm-mcp-adapter/sandbox-proxy-template.js +190 -0
- package/extensions/dm-mcp-adapter/search-ranking.js +198 -0
- package/extensions/dm-mcp-adapter/server-manager.js +1258 -0
- package/extensions/dm-mcp-adapter/session-recovery.js +82 -0
- package/extensions/dm-mcp-adapter/skills/mcp-scripting/SKILL.md +39 -0
- package/extensions/dm-mcp-adapter/state.js +0 -0
- package/extensions/dm-mcp-adapter/test-runner.mjs +18 -0
- package/extensions/dm-mcp-adapter/tool-approval.js +151 -0
- package/extensions/dm-mcp-adapter/tool-metadata.js +247 -0
- package/extensions/dm-mcp-adapter/tool-registrar.js +212 -0
- package/extensions/dm-mcp-adapter/tool-result-renderer.js +355 -0
- package/extensions/dm-mcp-adapter/ts-shape.js +157 -0
- package/extensions/dm-mcp-adapter/types.js +264 -0
- package/extensions/dm-mcp-adapter/ui-app-bridge-helpers.js +36 -0
- package/extensions/dm-mcp-adapter/ui-resource-handler.js +209 -0
- package/extensions/dm-mcp-adapter/ui-server.js +815 -0
- package/extensions/dm-mcp-adapter/ui-session.js +455 -0
- package/extensions/dm-mcp-adapter/ui-stream-types.js +58 -0
- package/extensions/dm-mcp-adapter/ui-tool-visibility.js +26 -0
- package/extensions/dm-mcp-adapter/unix-socket-transport.js +83 -0
- package/extensions/dm-mcp-adapter/utils.js +307 -0
- package/package.json +13 -1
- package/extensions/dm-localllm-provider/detect.test.js +0 -1051
- package/extensions/dm-localllm-provider/index.test.js +0 -149
- package/extensions/dm-localllm-provider/keychain.test.js +0 -61
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
export const DEFAULT_MCP_OUTPUT_MAX_BYTES = 50 * 1024;
|
|
6
|
+
export const DEFAULT_MCP_OUTPUT_MAX_LINES = 2000;
|
|
7
|
+
export const DEFAULT_MCP_DETAILS_MAX_BYTES = 16 * 1024;
|
|
8
|
+
const CONTENT_SUMMARY_LIMIT = 20;
|
|
9
|
+
const KEY_PREVIEW_LIMIT = 20;
|
|
10
|
+
const KEY_MAX_BYTES = 120;
|
|
11
|
+
const STRUCTURED_CONTENT_PRESERVE_MAX_BYTES = 4 * 1024;
|
|
12
|
+
const STRUCTURED_CONTENT_FIELD_PRESERVE_MAX_BYTES = 512;
|
|
13
|
+
export function resolveMcpOutputGuardOptions(settings) {
|
|
14
|
+
const configured = settings?.outputGuard;
|
|
15
|
+
const tuning = typeof configured === "object" && configured !== null ? configured : undefined;
|
|
16
|
+
return {
|
|
17
|
+
enabled: envKillSwitch("MCP_OUTPUT_GUARD") ?? configured !== false,
|
|
18
|
+
maxBytes: positiveInt(tuning?.maxBytes) ?? DEFAULT_MCP_OUTPUT_MAX_BYTES,
|
|
19
|
+
maxLines: positiveInt(tuning?.maxLines) ?? DEFAULT_MCP_OUTPUT_MAX_LINES,
|
|
20
|
+
detailsMaxBytes: positiveInt(tuning?.detailsMaxBytes) ?? DEFAULT_MCP_DETAILS_MAX_BYTES
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export function guardedMcpDetails(guarded) {
|
|
24
|
+
return {
|
|
25
|
+
...guarded.mcpResult !== undefined ? { mcpResult: guarded.mcpResult } : {},
|
|
26
|
+
...guarded.outputGuard ? { outputGuard: guarded.outputGuard } : {}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export async function guardMcpOutput(content, options = {}) {
|
|
30
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MCP_OUTPUT_MAX_BYTES;
|
|
31
|
+
const maxLines = options.maxLines ?? DEFAULT_MCP_OUTPUT_MAX_LINES;
|
|
32
|
+
const detailsMaxBytes = options.detailsMaxBytes ?? DEFAULT_MCP_DETAILS_MAX_BYTES;
|
|
33
|
+
const prefix = options.prefix ?? "";
|
|
34
|
+
const suffix = options.suffix ?? "";
|
|
35
|
+
const normalizedContent = withEmptyTextFallback(content.length > 0 ? sanitizeContent(content) : [{ type: "text", text: options.emptyTextFallback ?? "(empty result)" }], options.emptyTextFallback);
|
|
36
|
+
if (options.enabled === false) {
|
|
37
|
+
return {
|
|
38
|
+
content: addAffixes(normalizedContent, prefix, suffix),
|
|
39
|
+
...options.rawMcpResult !== undefined ? { mcpResult: options.rawMcpResult } : {}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
const imageBlocks = normalizedContent.filter((block) => block.type === "image");
|
|
43
|
+
const textOutput = normalizedContent.filter((block) => block.type === "text").map((block) => block.text).join(`
|
|
44
|
+
`);
|
|
45
|
+
const composedOutput = `${prefix}${textOutput}${suffix}`;
|
|
46
|
+
const stats = textStats(composedOutput);
|
|
47
|
+
let guardedContent = addAffixes(normalizedContent, prefix, suffix);
|
|
48
|
+
let outputGuard;
|
|
49
|
+
if (stats.bytes > maxBytes || stats.lines > maxLines) {
|
|
50
|
+
const { path: fullOutputPath, error: writeError } = await saveArtifact("output", composedOutput);
|
|
51
|
+
const notice = formatTruncationNotice(stats, fullOutputPath, writeError);
|
|
52
|
+
const previewBudget = reserveBudget(maxBytes, maxLines, notice);
|
|
53
|
+
const preview = truncateHead(composedOutput, previewBudget.maxBytes, previewBudget.maxLines);
|
|
54
|
+
const finalText = `${preview.content}
|
|
55
|
+
|
|
56
|
+
${notice}`;
|
|
57
|
+
const finalStats = textStats(finalText);
|
|
58
|
+
guardedContent = [{ type: "text", text: finalText }, ...imageBlocks];
|
|
59
|
+
outputGuard = {
|
|
60
|
+
truncated: true,
|
|
61
|
+
originalBytes: stats.bytes,
|
|
62
|
+
returnedBytes: finalStats.bytes,
|
|
63
|
+
originalLines: stats.lines,
|
|
64
|
+
returnedLines: finalStats.lines,
|
|
65
|
+
...imageBlocks.length > 0 ? { imageBlocksPassedThrough: imageBlocks.length } : {},
|
|
66
|
+
...fullOutputPath !== undefined ? { fullOutputPath } : {},
|
|
67
|
+
...writeError !== undefined ? { writeError } : {}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
const mcpResult = options.rawMcpResult === undefined ? undefined : await boundMcpResult(options.rawMcpResult, detailsMaxBytes);
|
|
71
|
+
return {
|
|
72
|
+
content: guardedContent,
|
|
73
|
+
...outputGuard ? { outputGuard } : {},
|
|
74
|
+
...mcpResult !== undefined ? { mcpResult } : {}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function sanitizeContent(content) {
|
|
78
|
+
return content.map((block) => {
|
|
79
|
+
if (block.type !== "image")
|
|
80
|
+
return block;
|
|
81
|
+
const mimeType = typeof block.mimeType === "string" && block.mimeType.trim() ? block.mimeType.trim().slice(0, 100) : "image/png";
|
|
82
|
+
return { ...block, mimeType };
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
function withEmptyTextFallback(content, fallback) {
|
|
86
|
+
if (!fallback)
|
|
87
|
+
return content;
|
|
88
|
+
const textOutput = content.filter((block) => block.type === "text").map((block) => block.text).join(`
|
|
89
|
+
`);
|
|
90
|
+
if (textOutput)
|
|
91
|
+
return content;
|
|
92
|
+
return [{ type: "text", text: fallback }, ...content.filter((block) => block.type === "image")];
|
|
93
|
+
}
|
|
94
|
+
function addAffixes(content, prefix, suffix) {
|
|
95
|
+
if (!prefix && !suffix)
|
|
96
|
+
return content;
|
|
97
|
+
const next = [...content];
|
|
98
|
+
if (prefix) {
|
|
99
|
+
const index = next.findIndex((block) => block.type === "text");
|
|
100
|
+
const block = next[index];
|
|
101
|
+
if (block?.type === "text") {
|
|
102
|
+
next[index] = { ...block, text: `${prefix}${block.text}` };
|
|
103
|
+
} else {
|
|
104
|
+
next.unshift({ type: "text", text: prefix });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (suffix) {
|
|
108
|
+
let index = -1;
|
|
109
|
+
for (let i = next.length - 1;i >= 0; i--) {
|
|
110
|
+
if (next[i]?.type === "text") {
|
|
111
|
+
index = i;
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const block = next[index];
|
|
116
|
+
if (block?.type === "text") {
|
|
117
|
+
next[index] = { ...block, text: `${block.text}${suffix}` };
|
|
118
|
+
} else {
|
|
119
|
+
next.push({ type: "text", text: suffix });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return next;
|
|
123
|
+
}
|
|
124
|
+
function reserveBudget(maxBytes, maxLines, notice) {
|
|
125
|
+
const noticeStats = textStats(`
|
|
126
|
+
|
|
127
|
+
${notice}`);
|
|
128
|
+
return {
|
|
129
|
+
maxBytes: Math.max(0, maxBytes - noticeStats.bytes),
|
|
130
|
+
maxLines: Math.max(0, maxLines - noticeStats.lines)
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function truncateHead(text, maxBytes, maxLines) {
|
|
134
|
+
const lines = text.split(`
|
|
135
|
+
`);
|
|
136
|
+
const output = [];
|
|
137
|
+
let bytes = 0;
|
|
138
|
+
for (const line of lines) {
|
|
139
|
+
if (output.length >= maxLines)
|
|
140
|
+
break;
|
|
141
|
+
const separatorBytes = output.length > 0 ? 1 : 0;
|
|
142
|
+
const lineBytes = byteLength(line);
|
|
143
|
+
if (bytes + separatorBytes + lineBytes > maxBytes) {
|
|
144
|
+
const remaining = maxBytes - bytes - separatorBytes;
|
|
145
|
+
if (remaining > 0) {
|
|
146
|
+
output.push(truncateStringToBytes(line, remaining));
|
|
147
|
+
}
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
output.push(line);
|
|
151
|
+
bytes += separatorBytes + lineBytes;
|
|
152
|
+
}
|
|
153
|
+
const content = output.join(`
|
|
154
|
+
`);
|
|
155
|
+
const stats = textStats(content);
|
|
156
|
+
return { content, bytes: stats.bytes, lines: stats.lines };
|
|
157
|
+
}
|
|
158
|
+
function truncateStringToBytes(value, maxBytes) {
|
|
159
|
+
if (byteLength(value) <= maxBytes)
|
|
160
|
+
return value;
|
|
161
|
+
const buffer = Buffer.from(value, "utf8");
|
|
162
|
+
let end = Number.isFinite(maxBytes) ? Math.max(0, Math.floor(maxBytes)) : 0;
|
|
163
|
+
while (end > 0 && (buffer.readUInt8(end) & 192) === 128)
|
|
164
|
+
end--;
|
|
165
|
+
return buffer.subarray(0, end).toString("utf8");
|
|
166
|
+
}
|
|
167
|
+
function formatTruncationNotice(stats, fullOutputPath, writeError) {
|
|
168
|
+
const base = `[MCP text output truncated: original ${stats.lines.toLocaleString()} lines / ${formatSize(stats.bytes)}.`;
|
|
169
|
+
if (fullOutputPath) {
|
|
170
|
+
return `${base} Full text saved to: ${fullOutputPath} — use read with offset/limit or grep to inspect.]`;
|
|
171
|
+
}
|
|
172
|
+
return `${base} Full output could not be saved: ${writeError ?? "unknown error"}]`;
|
|
173
|
+
}
|
|
174
|
+
async function boundMcpResult(result, detailsMaxBytes) {
|
|
175
|
+
const raw = safeStringify(result);
|
|
176
|
+
const rawBytes = byteLength(raw);
|
|
177
|
+
if (rawBytes <= detailsMaxBytes)
|
|
178
|
+
return result;
|
|
179
|
+
const marker = { omitted: true };
|
|
180
|
+
if (byteLength(safeStringify(marker)) > detailsMaxBytes)
|
|
181
|
+
return;
|
|
182
|
+
const summary = await summarizeMcpResult(result, raw, rawBytes);
|
|
183
|
+
if (byteLength(safeStringify(summary)) <= detailsMaxBytes)
|
|
184
|
+
return summary;
|
|
185
|
+
return compactMcpResultOmission(summary, marker, detailsMaxBytes);
|
|
186
|
+
}
|
|
187
|
+
async function compactMcpResultOmission(summary, marker, maxBytes) {
|
|
188
|
+
if (summary.fullResultPath) {
|
|
189
|
+
const withPathAndSize = {
|
|
190
|
+
...marker,
|
|
191
|
+
rawResultBytes: summary.rawResultBytes,
|
|
192
|
+
fullResultPath: summary.fullResultPath
|
|
193
|
+
};
|
|
194
|
+
if (byteLength(safeStringify(withPathAndSize)) <= maxBytes)
|
|
195
|
+
return withPathAndSize;
|
|
196
|
+
const withPath = { ...marker, fullResultPath: summary.fullResultPath };
|
|
197
|
+
if (byteLength(safeStringify(withPath)) <= maxBytes)
|
|
198
|
+
return withPath;
|
|
199
|
+
await discardArtifact(summary.fullResultPath);
|
|
200
|
+
}
|
|
201
|
+
const withSize = { ...marker, rawResultBytes: summary.rawResultBytes };
|
|
202
|
+
return byteLength(safeStringify(withSize)) <= maxBytes ? withSize : marker;
|
|
203
|
+
}
|
|
204
|
+
async function summarizeMcpResult(result, raw, rawBytes) {
|
|
205
|
+
const { path: fullResultPath, error: resultWriteError } = await saveArtifact("mcp-result", raw);
|
|
206
|
+
const record = asRecord(result);
|
|
207
|
+
const content = Array.isArray(record?.content) ? record.content : [];
|
|
208
|
+
const summary = {
|
|
209
|
+
omitted: true,
|
|
210
|
+
reason: "Raw MCP result exceeded the details size limit and was replaced with this summary to keep session context bounded.",
|
|
211
|
+
isError: record?.isError === true,
|
|
212
|
+
contentBlocks: content.length,
|
|
213
|
+
contentSummary: summarizeContent(content),
|
|
214
|
+
rawResultBytes: rawBytes,
|
|
215
|
+
...fullResultPath !== undefined ? { fullResultPath } : {},
|
|
216
|
+
...resultWriteError !== undefined ? { resultWriteError } : {}
|
|
217
|
+
};
|
|
218
|
+
if (record && "structuredContent" in record) {
|
|
219
|
+
summary.structuredContent = summarizeStructuredContent(record.structuredContent);
|
|
220
|
+
}
|
|
221
|
+
if (record && "_meta" in record) {
|
|
222
|
+
summary.meta = summarizeValue(record._meta);
|
|
223
|
+
}
|
|
224
|
+
if (record) {
|
|
225
|
+
const standard = new Set(["content", "isError", "structuredContent", "_meta"]);
|
|
226
|
+
const extraFields = Object.keys(record).filter((key) => !standard.has(key)).slice(0, KEY_PREVIEW_LIMIT).map((key) => ({ key: truncateKey(key), type: typeof record[key], estimatedBytes: estimateValueBytes(record[key]), omitted: true }));
|
|
227
|
+
if (extraFields.length > 0)
|
|
228
|
+
summary.extraFields = extraFields;
|
|
229
|
+
}
|
|
230
|
+
return summary;
|
|
231
|
+
}
|
|
232
|
+
function summarizeContent(content) {
|
|
233
|
+
const summaries = content.slice(0, CONTENT_SUMMARY_LIMIT).map((block) => {
|
|
234
|
+
const record = asRecord(block);
|
|
235
|
+
if (!record)
|
|
236
|
+
return { type: typeof block, omitted: true };
|
|
237
|
+
if (record.type === "text") {
|
|
238
|
+
const text = typeof record.text === "string" ? record.text : "";
|
|
239
|
+
return { type: "text", bytes: byteLength(text), lines: textStats(text).lines, textOmitted: true };
|
|
240
|
+
}
|
|
241
|
+
if (record.type === "image") {
|
|
242
|
+
const data = typeof record.data === "string" ? record.data : "";
|
|
243
|
+
return { type: "image", mimeType: typeof record.mimeType === "string" ? record.mimeType : undefined, dataBytes: byteLength(data), dataOmitted: true };
|
|
244
|
+
}
|
|
245
|
+
return { type: typeof record.type === "string" ? record.type : "unknown", estimatedBytes: estimateValueBytes(record), omitted: true };
|
|
246
|
+
});
|
|
247
|
+
if (content.length > CONTENT_SUMMARY_LIMIT) {
|
|
248
|
+
summaries.push({ type: "omitted", count: content.length - CONTENT_SUMMARY_LIMIT });
|
|
249
|
+
}
|
|
250
|
+
return summaries;
|
|
251
|
+
}
|
|
252
|
+
function summarizeValue(value) {
|
|
253
|
+
const record = asRecord(value);
|
|
254
|
+
if (!record) {
|
|
255
|
+
return { type: value === null ? "null" : typeof value, estimatedBytes: estimateValueBytes(value), omitted: true };
|
|
256
|
+
}
|
|
257
|
+
const keys = Object.keys(record);
|
|
258
|
+
return {
|
|
259
|
+
type: Array.isArray(value) ? "array" : "object",
|
|
260
|
+
estimatedBytes: estimateValueBytes(value),
|
|
261
|
+
keyCount: keys.length,
|
|
262
|
+
keysPreview: uniqueBoundedKeys(keys.slice(0, KEY_PREVIEW_LIMIT)),
|
|
263
|
+
omitted: true
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
function summarizeStructuredContent(value) {
|
|
267
|
+
const record = asRecord(value);
|
|
268
|
+
if (!record || Array.isArray(value))
|
|
269
|
+
return summarizeValue(value);
|
|
270
|
+
const keys = Object.keys(record);
|
|
271
|
+
const entries = Object.entries(record).slice(0, KEY_PREVIEW_LIMIT);
|
|
272
|
+
const previewKeys = uniqueBoundedKeys(entries.map(([key]) => key));
|
|
273
|
+
const fields = {};
|
|
274
|
+
let preservedBytes = byteLength("{}");
|
|
275
|
+
for (const [key, field] of entries) {
|
|
276
|
+
const fieldBytes = byteLength(safeStringify(field));
|
|
277
|
+
const candidate = fieldBytes <= STRUCTURED_CONTENT_FIELD_PRESERVE_MAX_BYTES ? field : summarizeValue(field);
|
|
278
|
+
const entryBytes = serializedObjectEntryBytes(key, candidate, Object.keys(fields).length > 0);
|
|
279
|
+
if (preservedBytes + entryBytes > STRUCTURED_CONTENT_PRESERVE_MAX_BYTES)
|
|
280
|
+
continue;
|
|
281
|
+
fields[key] = candidate;
|
|
282
|
+
preservedBytes += entryBytes;
|
|
283
|
+
}
|
|
284
|
+
return {
|
|
285
|
+
preservedFields: fields,
|
|
286
|
+
summary: {
|
|
287
|
+
type: "object",
|
|
288
|
+
estimatedBytes: estimateValueBytes(value),
|
|
289
|
+
keyCount: keys.length,
|
|
290
|
+
keysPreview: previewKeys,
|
|
291
|
+
omitted: true
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
function estimateValueBytes(value, depth = 0) {
|
|
296
|
+
if (value === null || value === undefined)
|
|
297
|
+
return 0;
|
|
298
|
+
if (typeof value === "string")
|
|
299
|
+
return byteLength(value);
|
|
300
|
+
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint")
|
|
301
|
+
return byteLength(String(value));
|
|
302
|
+
const record = asRecord(value);
|
|
303
|
+
if (!record || depth >= 2)
|
|
304
|
+
return 0;
|
|
305
|
+
const values = Array.isArray(value) ? value.slice(0, KEY_PREVIEW_LIMIT) : Object.values(record).slice(0, KEY_PREVIEW_LIMIT);
|
|
306
|
+
return values.reduce((total, item) => total + estimateValueBytes(item, depth + 1), 0);
|
|
307
|
+
}
|
|
308
|
+
function truncateKey(key) {
|
|
309
|
+
if (byteLength(key) <= KEY_MAX_BYTES)
|
|
310
|
+
return key;
|
|
311
|
+
const suffix = "…";
|
|
312
|
+
return `${truncateStringToBytes(key, KEY_MAX_BYTES - byteLength(suffix))}${suffix}`;
|
|
313
|
+
}
|
|
314
|
+
function uniqueBoundedKeys(keys) {
|
|
315
|
+
const used = new Set;
|
|
316
|
+
return keys.map((key) => {
|
|
317
|
+
let candidate = truncateKey(key);
|
|
318
|
+
let ordinal = 2;
|
|
319
|
+
while (used.has(candidate)) {
|
|
320
|
+
const suffix = `~${ordinal}`;
|
|
321
|
+
candidate = `${truncateStringToBytes(key, KEY_MAX_BYTES - byteLength(suffix))}${suffix}`;
|
|
322
|
+
ordinal += 1;
|
|
323
|
+
}
|
|
324
|
+
used.add(candidate);
|
|
325
|
+
return candidate;
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
function serializedObjectEntryBytes(key, value, hasPrevious) {
|
|
329
|
+
const serialized = safeStringify({ [key]: value });
|
|
330
|
+
return Math.max(0, byteLength(serialized) - byteLength("{}")) + (hasPrevious ? 1 : 0);
|
|
331
|
+
}
|
|
332
|
+
async function saveArtifact(kind, text) {
|
|
333
|
+
try {
|
|
334
|
+
const dir = await mkdtemp(join(tmpdir(), "pi-mcp-output-"));
|
|
335
|
+
const path = join(dir, `${kind}-${randomBytes(4).toString("hex")}.txt`);
|
|
336
|
+
await writeFile(path, text, { encoding: "utf8", mode: 384 });
|
|
337
|
+
return { path };
|
|
338
|
+
} catch (error) {
|
|
339
|
+
return { error: error instanceof Error ? error.message : String(error) };
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
async function discardArtifact(path) {
|
|
343
|
+
try {
|
|
344
|
+
await rm(dirname(path), { recursive: true, force: true });
|
|
345
|
+
} catch {}
|
|
346
|
+
}
|
|
347
|
+
function asRecord(value) {
|
|
348
|
+
return typeof value === "object" && value !== null ? value : undefined;
|
|
349
|
+
}
|
|
350
|
+
function safeStringify(value) {
|
|
351
|
+
try {
|
|
352
|
+
return JSON.stringify(value);
|
|
353
|
+
} catch {
|
|
354
|
+
return String(value);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
function textStats(text) {
|
|
358
|
+
return { bytes: byteLength(text), lines: text.length === 0 ? 0 : text.split(`
|
|
359
|
+
`).length };
|
|
360
|
+
}
|
|
361
|
+
function byteLength(text) {
|
|
362
|
+
return Buffer.byteLength(text, "utf8");
|
|
363
|
+
}
|
|
364
|
+
function positiveInt(value) {
|
|
365
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
366
|
+
return;
|
|
367
|
+
const integer = Math.floor(value);
|
|
368
|
+
return integer > 0 ? integer : undefined;
|
|
369
|
+
}
|
|
370
|
+
function envKillSwitch(name) {
|
|
371
|
+
const value = process.env[name]?.trim().toLowerCase();
|
|
372
|
+
if (!value)
|
|
373
|
+
return;
|
|
374
|
+
if (["0", "false", "no", "off"].includes(value))
|
|
375
|
+
return false;
|
|
376
|
+
if (["1", "true", "yes", "on"].includes(value))
|
|
377
|
+
return true;
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
function formatSize(bytes) {
|
|
381
|
+
if (bytes < 1024)
|
|
382
|
+
return `${bytes} B`;
|
|
383
|
+
if (bytes < 1024 * 1024)
|
|
384
|
+
return `${(bytes / 1024).toFixed(1)} KiB`;
|
|
385
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
|
|
386
|
+
}
|