@tangle-network/agent-app 0.43.43 → 0.43.44
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/dist/assistant/index.d.ts +2 -1
- package/dist/assistant/index.js +3 -2
- package/dist/assistant/index.js.map +1 -1
- package/dist/chat-routes/index.d.ts +152 -4
- package/dist/chat-routes/index.js +134 -20
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-store/index.d.ts +2 -2
- package/dist/chat-store/index.js +7 -1
- package/dist/chat-store/index.js.map +1 -1
- package/dist/{chunk-5GWXCSLQ.js → chunk-5RJNEEO2.js} +86 -5
- package/dist/chunk-5RJNEEO2.js.map +1 -0
- package/dist/chunk-6E2XJSCT.js +298 -0
- package/dist/chunk-6E2XJSCT.js.map +1 -0
- package/dist/chunk-LCNY3DCM.js +84 -0
- package/dist/chunk-LCNY3DCM.js.map +1 -0
- package/dist/{chunk-PEUBCJXF.js → chunk-Q4EU6MGU.js} +44 -1
- package/dist/chunk-Q4EU6MGU.js.map +1 -0
- package/dist/file-index-Bn6sitKb.d.ts +114 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +16 -2
- package/dist/parts-1_3y2JmR.d.ts +368 -0
- package/dist/sandbox/index.d.ts +111 -2
- package/dist/sandbox/index.js +9 -1
- package/dist/web-react/index.d.ts +51 -3
- package/dist/web-react/index.js +13 -4
- package/package.json +1 -1
- package/dist/chunk-2EO7CPL3.js +0 -191
- package/dist/chunk-2EO7CPL3.js.map +0 -1
- package/dist/chunk-5GWXCSLQ.js.map +0 -1
- package/dist/chunk-I2ATYB7R.js +0 -78
- package/dist/chunk-I2ATYB7R.js.map +0 -1
- package/dist/chunk-PEUBCJXF.js.map +0 -1
- package/dist/file-index-Bw_IQE_G.d.ts +0 -194
- package/dist/parts-DjX0RRTS.d.ts +0 -182
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import {
|
|
2
|
+
persistedPartToInteraction
|
|
3
|
+
} from "./chunk-XAWFPMAR.js";
|
|
4
|
+
import {
|
|
5
|
+
persistedPartToPlan,
|
|
6
|
+
planToPersistedPart
|
|
7
|
+
} from "./chunk-SIXYZ2FB.js";
|
|
8
|
+
|
|
9
|
+
// src/chat-routes/wire.ts
|
|
10
|
+
function chatTurnRequestInit(payload) {
|
|
11
|
+
return {
|
|
12
|
+
method: "POST",
|
|
13
|
+
headers: { "Content-Type": "application/json" },
|
|
14
|
+
body: JSON.stringify(payload)
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
var INLINE_PARTS_MAX_BYTES = 95e4;
|
|
18
|
+
var ChatTurnInputError = class extends Error {
|
|
19
|
+
constructor(message, status = 400, code = "INVALID_CHAT_TURN") {
|
|
20
|
+
super(message);
|
|
21
|
+
this.status = status;
|
|
22
|
+
this.code = code;
|
|
23
|
+
this.name = "ChatTurnInputError";
|
|
24
|
+
}
|
|
25
|
+
status;
|
|
26
|
+
code;
|
|
27
|
+
};
|
|
28
|
+
function partByteSize(part) {
|
|
29
|
+
let bytes = 0;
|
|
30
|
+
if (part.type === "text") return part.text.length;
|
|
31
|
+
if (part.url) bytes += part.url.length;
|
|
32
|
+
if (part.content) bytes += part.content.length;
|
|
33
|
+
if (part.path) bytes += part.path.length;
|
|
34
|
+
return bytes;
|
|
35
|
+
}
|
|
36
|
+
function promptPartsByteSize(parts) {
|
|
37
|
+
return parts.reduce((total, part) => total + partByteSize(part), 0);
|
|
38
|
+
}
|
|
39
|
+
function assertPromptPartsWithinCap(parts, maxBytes = INLINE_PARTS_MAX_BYTES) {
|
|
40
|
+
const total = promptPartsByteSize(parts);
|
|
41
|
+
if (total <= maxBytes) return;
|
|
42
|
+
const largest = [...parts].sort((a, b) => partByteSize(b) - partByteSize(a))[0];
|
|
43
|
+
const largestName = largest && largest.type !== "text" ? largest.filename ?? largest.path ?? largest.type : "text";
|
|
44
|
+
throw new ChatTurnInputError(
|
|
45
|
+
`Inline prompt parts total ${total}B, over the ${maxBytes}B budget (largest: ${largestName}, ${largest ? partByteSize(largest) : 0}B). Upload large files through the upload route so they travel as sandbox path references.`,
|
|
46
|
+
413,
|
|
47
|
+
"PROMPT_PARTS_TOO_LARGE"
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
var MENTION_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Map([
|
|
51
|
+
[".png", "image/png"],
|
|
52
|
+
[".jpg", "image/jpeg"],
|
|
53
|
+
[".jpeg", "image/jpeg"],
|
|
54
|
+
[".gif", "image/gif"],
|
|
55
|
+
[".webp", "image/webp"],
|
|
56
|
+
[".svg", "image/svg+xml"],
|
|
57
|
+
[".bmp", "image/bmp"],
|
|
58
|
+
[".heic", "image/heic"],
|
|
59
|
+
[".heif", "image/heif"],
|
|
60
|
+
[".avif", "image/avif"]
|
|
61
|
+
]);
|
|
62
|
+
function extensionOf(path) {
|
|
63
|
+
const base = path.split("/").filter(Boolean).pop() ?? path;
|
|
64
|
+
const dot = base.lastIndexOf(".");
|
|
65
|
+
return dot > 0 ? base.slice(dot).toLowerCase() : "";
|
|
66
|
+
}
|
|
67
|
+
function mediaTypeForMentionPath(path) {
|
|
68
|
+
return MENTION_IMAGE_MEDIA_TYPES.get(extensionOf(path));
|
|
69
|
+
}
|
|
70
|
+
function mentionKindForPath(path) {
|
|
71
|
+
return mediaTypeForMentionPath(path) ? "image" : "file";
|
|
72
|
+
}
|
|
73
|
+
function fileMentionsToParts(mentions, opts = {}) {
|
|
74
|
+
const resolvePath = opts.resolvePath ?? ((path) => path);
|
|
75
|
+
return mentions.map((mention) => {
|
|
76
|
+
const mediaType = mediaTypeForMentionPath(mention.path);
|
|
77
|
+
const part = {
|
|
78
|
+
type: mediaType ? "image" : "file",
|
|
79
|
+
filename: mention.name,
|
|
80
|
+
path: resolvePath(mention.path)
|
|
81
|
+
};
|
|
82
|
+
if (mediaType) part.mediaType = mediaType;
|
|
83
|
+
return part;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function buildMentionPromptBlock(mentions) {
|
|
87
|
+
if (mentions.length === 0) return "";
|
|
88
|
+
const lines = mentions.map((m) => `- ${m.name} (${m.path})`);
|
|
89
|
+
return `
|
|
90
|
+
|
|
91
|
+
Mentioned files \u2014 read them from these paths:
|
|
92
|
+
${lines.join("\n")}`;
|
|
93
|
+
}
|
|
94
|
+
var MENTION_MAX_COUNT = 16;
|
|
95
|
+
var MAX_MENTION_NAME_LENGTH = 256;
|
|
96
|
+
var MAX_MENTION_PATH_LENGTH = 1024;
|
|
97
|
+
function validateSandboxMentionPath(path) {
|
|
98
|
+
if (typeof path !== "string" || path.length === 0) {
|
|
99
|
+
return { succeeded: false, error: "mention path must be a non-empty string" };
|
|
100
|
+
}
|
|
101
|
+
if (path.length > MAX_MENTION_PATH_LENGTH) {
|
|
102
|
+
return { succeeded: false, error: `mention path must not exceed ${MAX_MENTION_PATH_LENGTH} characters` };
|
|
103
|
+
}
|
|
104
|
+
if (path.includes("\0")) {
|
|
105
|
+
return { succeeded: false, error: "mention path must not contain null bytes" };
|
|
106
|
+
}
|
|
107
|
+
if (path.includes("\\")) {
|
|
108
|
+
return { succeeded: false, error: "mention path must not contain backslashes" };
|
|
109
|
+
}
|
|
110
|
+
if (path.startsWith("/")) {
|
|
111
|
+
return { succeeded: false, error: "mention path must be workspace-relative, not absolute" };
|
|
112
|
+
}
|
|
113
|
+
if (path.split("/").some((segment) => segment === "..")) {
|
|
114
|
+
return { succeeded: false, error: 'mention path must not contain ".." segments' };
|
|
115
|
+
}
|
|
116
|
+
return { succeeded: true };
|
|
117
|
+
}
|
|
118
|
+
function parseFileMention(value, index) {
|
|
119
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
120
|
+
throw new ChatTurnInputError(`mentions[${index}] must be an object`);
|
|
121
|
+
}
|
|
122
|
+
const record = value;
|
|
123
|
+
const pathCheck = validateSandboxMentionPath(record.path);
|
|
124
|
+
if (!pathCheck.succeeded) throw new ChatTurnInputError(`mentions[${index}]: ${pathCheck.error}`);
|
|
125
|
+
const name = record.name;
|
|
126
|
+
if (typeof name !== "string" || !name.trim()) {
|
|
127
|
+
throw new ChatTurnInputError(`mentions[${index}].name must be a non-empty string`);
|
|
128
|
+
}
|
|
129
|
+
if (name.length > MAX_MENTION_NAME_LENGTH) {
|
|
130
|
+
throw new ChatTurnInputError(`mentions[${index}].name must not exceed ${MAX_MENTION_NAME_LENGTH} characters`);
|
|
131
|
+
}
|
|
132
|
+
const size = record.size;
|
|
133
|
+
if (size !== void 0) {
|
|
134
|
+
if (typeof size !== "number" || !Number.isFinite(size)) {
|
|
135
|
+
throw new ChatTurnInputError(`mentions[${index}].size must be a finite number`);
|
|
136
|
+
}
|
|
137
|
+
if (size < 0) {
|
|
138
|
+
throw new ChatTurnInputError(`mentions[${index}].size must not be negative`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return { path: record.path, name, ...typeof size === "number" ? { size } : {} };
|
|
142
|
+
}
|
|
143
|
+
function parseFileMentions(raw) {
|
|
144
|
+
if (raw === void 0 || raw === null) return [];
|
|
145
|
+
if (!Array.isArray(raw)) throw new ChatTurnInputError("mentions must be an array");
|
|
146
|
+
if (raw.length > MENTION_MAX_COUNT) {
|
|
147
|
+
throw new ChatTurnInputError(`mentions must not exceed ${MENTION_MAX_COUNT} entries`);
|
|
148
|
+
}
|
|
149
|
+
const mentions = [];
|
|
150
|
+
const seenPaths = /* @__PURE__ */ new Set();
|
|
151
|
+
for (let index = 0; index < raw.length; index += 1) {
|
|
152
|
+
const mention = parseFileMention(raw[index], index);
|
|
153
|
+
if (seenPaths.has(mention.path)) continue;
|
|
154
|
+
seenPaths.add(mention.path);
|
|
155
|
+
mentions.push(mention);
|
|
156
|
+
}
|
|
157
|
+
return mentions;
|
|
158
|
+
}
|
|
159
|
+
function parseChatTurnParts(raw) {
|
|
160
|
+
if (raw === void 0 || raw === null) return [];
|
|
161
|
+
if (!Array.isArray(raw)) throw new ChatTurnInputError("parts must be an array");
|
|
162
|
+
return raw.map((entry, index) => {
|
|
163
|
+
const part = entry;
|
|
164
|
+
if (!part || typeof part !== "object") {
|
|
165
|
+
throw new ChatTurnInputError(`parts[${index}] must be an object`);
|
|
166
|
+
}
|
|
167
|
+
if (part.type !== "image" && part.type !== "file") {
|
|
168
|
+
throw new ChatTurnInputError(`parts[${index}].type must be 'image' or 'file'`);
|
|
169
|
+
}
|
|
170
|
+
for (const key of ["filename", "mediaType", "url", "path", "content"]) {
|
|
171
|
+
if (part[key] !== void 0 && typeof part[key] !== "string") {
|
|
172
|
+
throw new ChatTurnInputError(`parts[${index}].${key} must be a string`);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (!part.url && !part.path && !part.content) {
|
|
176
|
+
throw new ChatTurnInputError(`parts[${index}] needs a url, path, or content`);
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
type: part.type,
|
|
180
|
+
...part.filename !== void 0 ? { filename: part.filename } : {},
|
|
181
|
+
...part.mediaType !== void 0 ? { mediaType: part.mediaType } : {},
|
|
182
|
+
...part.url !== void 0 ? { url: part.url } : {},
|
|
183
|
+
...part.path !== void 0 ? { path: part.path } : {},
|
|
184
|
+
...part.content !== void 0 ? { content: part.content } : {}
|
|
185
|
+
};
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// src/chat-store/parts.ts
|
|
190
|
+
function toChatMessageParts(parts) {
|
|
191
|
+
const out = [];
|
|
192
|
+
for (const part of parts) {
|
|
193
|
+
const typed = toChatMessagePart(part);
|
|
194
|
+
if (typed) out.push(typed);
|
|
195
|
+
}
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
var str = (value) => typeof value === "string";
|
|
199
|
+
function toChatMessagePart(part) {
|
|
200
|
+
if (!part || typeof part !== "object") return null;
|
|
201
|
+
const type = part.type;
|
|
202
|
+
switch (type) {
|
|
203
|
+
case "text":
|
|
204
|
+
case "reasoning":
|
|
205
|
+
return str(part.text) ? part : null;
|
|
206
|
+
case "tool":
|
|
207
|
+
return str(part.id) && str(part.tool) && part.state && typeof part.state === "object" ? part : null;
|
|
208
|
+
case "file":
|
|
209
|
+
case "image":
|
|
210
|
+
return part;
|
|
211
|
+
case "subtask":
|
|
212
|
+
return str(part.prompt) && str(part.description) && str(part.agent) ? part : null;
|
|
213
|
+
case "step-start":
|
|
214
|
+
return { type: "step-start" };
|
|
215
|
+
case "step-finish":
|
|
216
|
+
return part;
|
|
217
|
+
case "interaction":
|
|
218
|
+
return persistedPartToInteraction(part) ? part : null;
|
|
219
|
+
case "notice":
|
|
220
|
+
return str(part.id) && str(part.noticeKind) && str(part.text) ? part : null;
|
|
221
|
+
case "plan": {
|
|
222
|
+
const plan = persistedPartToPlan(part);
|
|
223
|
+
return plan ? { ...part, ...planToPersistedPart(plan) } : null;
|
|
224
|
+
}
|
|
225
|
+
case "mention":
|
|
226
|
+
return isChatMentionPart(part) ? part : null;
|
|
227
|
+
case void 0:
|
|
228
|
+
return null;
|
|
229
|
+
default: {
|
|
230
|
+
const _exhaustive = type;
|
|
231
|
+
void _exhaustive;
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function isChatToolPart(part) {
|
|
237
|
+
return part.type === "tool";
|
|
238
|
+
}
|
|
239
|
+
function isChatTextPart(part) {
|
|
240
|
+
return part.type === "text";
|
|
241
|
+
}
|
|
242
|
+
function isChatInteractionPart(part) {
|
|
243
|
+
return part.type === "interaction";
|
|
244
|
+
}
|
|
245
|
+
function isChatPlanPart(part) {
|
|
246
|
+
return part.type === "plan";
|
|
247
|
+
}
|
|
248
|
+
function isChatStepFinishPart(part) {
|
|
249
|
+
return part.type === "step-finish";
|
|
250
|
+
}
|
|
251
|
+
function isChatMentionPart(part) {
|
|
252
|
+
if (!part || typeof part !== "object") return false;
|
|
253
|
+
const record = part;
|
|
254
|
+
if (record.size !== void 0 && (typeof record.size !== "number" || !Number.isFinite(record.size))) {
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
return record.type === "mention" && typeof record.path === "string" && record.path.length > 0 && typeof record.name === "string" && record.name.trim().length > 0 && (record.mentionKind === "image" || record.mentionKind === "file");
|
|
258
|
+
}
|
|
259
|
+
function mentionPartsFromMessageParts(parts) {
|
|
260
|
+
if (!parts) return [];
|
|
261
|
+
return parts.filter(isChatMentionPart);
|
|
262
|
+
}
|
|
263
|
+
function mentionInputToPart(input) {
|
|
264
|
+
const part = {
|
|
265
|
+
type: "mention",
|
|
266
|
+
mentionKind: mentionKindForPath(input.path),
|
|
267
|
+
path: input.path,
|
|
268
|
+
name: input.name
|
|
269
|
+
};
|
|
270
|
+
if (typeof input.size === "number" && Number.isFinite(input.size)) part.size = input.size;
|
|
271
|
+
return part;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export {
|
|
275
|
+
chatTurnRequestInit,
|
|
276
|
+
INLINE_PARTS_MAX_BYTES,
|
|
277
|
+
ChatTurnInputError,
|
|
278
|
+
promptPartsByteSize,
|
|
279
|
+
assertPromptPartsWithinCap,
|
|
280
|
+
mediaTypeForMentionPath,
|
|
281
|
+
mentionKindForPath,
|
|
282
|
+
fileMentionsToParts,
|
|
283
|
+
buildMentionPromptBlock,
|
|
284
|
+
MENTION_MAX_COUNT,
|
|
285
|
+
validateSandboxMentionPath,
|
|
286
|
+
parseFileMentions,
|
|
287
|
+
parseChatTurnParts,
|
|
288
|
+
toChatMessageParts,
|
|
289
|
+
isChatToolPart,
|
|
290
|
+
isChatTextPart,
|
|
291
|
+
isChatInteractionPart,
|
|
292
|
+
isChatPlanPart,
|
|
293
|
+
isChatStepFinishPart,
|
|
294
|
+
isChatMentionPart,
|
|
295
|
+
mentionPartsFromMessageParts,
|
|
296
|
+
mentionInputToPart
|
|
297
|
+
};
|
|
298
|
+
//# sourceMappingURL=chunk-6E2XJSCT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/chat-routes/wire.ts","../src/chat-store/parts.ts"],"sourcesContent":["/**\n * Wire contract between the chat client (composer + `streamChatTurn`) and the\n * assembled server vertical (`createChatTurnRoutes`). Import-free on purpose:\n * `/web-react` re-exports these types into browser bundles, so nothing here may\n * reach a Node builtin or an engine package.\n *\n * The part shape mirrors the sandbox SDK's `PromptInputPart` structurally\n * (text | image | file with filename/mediaType/url/path/content) — derived\n * here, not imported, so the client bundle never touches the SDK.\n */\n\nexport interface ChatTurnTextPartInput {\n type: 'text'\n text: string\n}\n\n/** A non-text prompt part the upload route hands back and the client echoes\n * on send. `url` carries an inline `data:` URI for small files; `path` is a\n * sandbox workspace reference for large ones (the >1 MiB gateway body cap\n * makes the two-step upload mandatory). */\nexport interface ChatTurnFilePartInput {\n type: 'image' | 'file'\n filename?: string\n mediaType?: string\n url?: string\n path?: string\n content?: string\n}\n\nexport type ChatTurnPartInput = ChatTurnTextPartInput | ChatTurnFilePartInput\n\n/** POST body for the turn route. `content` may be empty when `parts` carry the\n * message (an image-only send). Product routing fields (workspaceId etc.) ride\n * alongside and are read by the product's `authorize` seam. */\nexport interface ChatTurnRequestPayload {\n threadId: string\n content?: string\n /** Non-text parts from the upload route, echoed back verbatim. */\n parts?: ChatTurnFilePartInput[]\n /** `@`-picked file mentions for this turn — path references into the\n * workspace sandbox, NOT uploads, so they travel in their own field rather\n * than as `parts` entries. A product whose `parts` field is already spoken\n * for (an attachment sentinel) can still send mentions, and mentions\n * persist as their own `ChatMentionPart`s so a retry rebuilds them. The\n * route validates this field with {@link parseFileMentions} and replaces it\n * on the payload with the validated, deduped list. */\n mentions?: FileMention[]\n model?: string\n effort?: 'auto' | 'low' | 'medium' | 'high'\n harness?: string\n /** Client-generated idempotency key for the logical turn (retry-safe). */\n turnId?: string\n [key: string]: unknown\n}\n\n/** `fetch` init for the turn route — the one place the client wire shape is\n * serialized, so composer glue and products never drift from the server's\n * parser. */\nexport function chatTurnRequestInit(payload: ChatTurnRequestPayload): RequestInit {\n return {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n }\n}\n\n// ── inline-part byte budget ─────────────────────────────────────────────────\n//\n// The sandbox gateway caps request bodies at 1 MiB; a turn body whose inline\n// `data:` parts exceed it dies at the gateway with an opaque 413. Enforce the\n// budget at the route boundary instead, with headroom for the JSON envelope\n// (same fail-loud-at-the-choke-point style as /sandbox's provision-payload and\n// env-size gates).\n\nexport const INLINE_PARTS_MAX_BYTES = 950_000\n\nexport class ChatTurnInputError extends Error {\n constructor(message: string, readonly status = 400, readonly code = 'INVALID_CHAT_TURN') {\n super(message)\n this.name = 'ChatTurnInputError'\n }\n}\n\nfunction partByteSize(part: ChatTurnPartInput): number {\n let bytes = 0\n if (part.type === 'text') return part.text.length\n if (part.url) bytes += part.url.length\n if (part.content) bytes += part.content.length\n if (part.path) bytes += part.path.length\n return bytes\n}\n\nexport function promptPartsByteSize(parts: ChatTurnPartInput[]): number {\n return parts.reduce((total, part) => total + partByteSize(part), 0)\n}\n\n/** Throws `ChatTurnInputError` (413) when the parts' inline payload would blow\n * the gateway cap. Path-ref parts are tiny by construction and always pass. */\nexport function assertPromptPartsWithinCap(\n parts: ChatTurnPartInput[],\n maxBytes = INLINE_PARTS_MAX_BYTES,\n): void {\n const total = promptPartsByteSize(parts)\n if (total <= maxBytes) return\n const largest = [...parts].sort((a, b) => partByteSize(b) - partByteSize(a))[0]\n const largestName = largest && largest.type !== 'text' ? largest.filename ?? largest.path ?? largest.type : 'text'\n throw new ChatTurnInputError(\n `Inline prompt parts total ${total}B, over the ${maxBytes}B budget (largest: ${largestName}, ${largest ? partByteSize(largest) : 0}B). ` +\n 'Upload large files through the upload route so they travel as sandbox path references.',\n 413,\n 'PROMPT_PARTS_TOO_LARGE',\n )\n}\n\n// ── file mentions ────────────────────────────────────────────────────────\n//\n// A file mention (`@`-picked in the composer, sandbox-ui#184) is a path\n// reference into the workspace sandbox — no byte upload. These helpers turn\n// a resolved mention list into wire parts and the prompt pointer block that\n// tells the agent where to read them from.\n\n/** A file mention resolved from the composer's `@`-picker: the\n * workspace-relative path plus enough metadata to build a prompt part and\n * pointer text. `path` is the canonical identity — the mention pill's\n * `MentionItem.id` for the file kind (`/web-react`'s `useFileMentions`). */\nexport interface FileMention {\n path: string\n name: string\n size?: number\n}\n\nconst MENTION_IMAGE_MEDIA_TYPES: ReadonlyMap<string, string> = new Map([\n ['.png', 'image/png'],\n ['.jpg', 'image/jpeg'],\n ['.jpeg', 'image/jpeg'],\n ['.gif', 'image/gif'],\n ['.webp', 'image/webp'],\n ['.svg', 'image/svg+xml'],\n ['.bmp', 'image/bmp'],\n ['.heic', 'image/heic'],\n ['.heif', 'image/heif'],\n ['.avif', 'image/avif'],\n])\n\nfunction extensionOf(path: string): string {\n const base = path.split('/').filter(Boolean).pop() ?? path\n const dot = base.lastIndexOf('.')\n return dot > 0 ? base.slice(dot).toLowerCase() : ''\n}\n\n/** The `image/*` mime for a mention path by extension, or `undefined` for\n * anything not in the known image set (dispatched as `type: 'file'`). */\nexport function mediaTypeForMentionPath(path: string): string | undefined {\n return MENTION_IMAGE_MEDIA_TYPES.get(extensionOf(path))\n}\n\n/** The image/file split a mention is rendered and persisted under — the\n * composer pill's icon, the dispatched part's `type`, and\n * `ChatMentionPart.mentionKind` are all this one value. */\nexport type ChatMentionKind = 'image' | 'file'\n\n/** `image` when the path's extension is in the known image set (the same table\n * {@link mediaTypeForMentionPath} reads), `file` otherwise. Exported so a\n * client that needs only the discriminant — a pill icon, a persisted part's\n * `mentionKind` — never re-declares the extension table; two frozen copies of\n * one mime table is how one gains a format and the other doesn't. */\nexport function mentionKindForPath(path: string): ChatMentionKind {\n return mediaTypeForMentionPath(path) ? 'image' : 'file'\n}\n\nexport interface FileMentionsToPartsOptions {\n /** Resolve a mention's workspace-relative path to the absolute path the\n * dispatched part should carry (e.g. a host prefixing the in-box vault\n * root). Default: identity — the path travels unchanged. */\n resolvePath?: (path: string) => string\n}\n\n/** Maps resolved file mentions to path-only `ChatTurnFilePartInput`s —\n * `image` vs `file` by extension, and always a `path`, never a `url` (the\n * url/path XOR invariant: a mention is a sandbox path reference, never\n * inline bytes). */\nexport function fileMentionsToParts(\n mentions: readonly FileMention[],\n opts: FileMentionsToPartsOptions = {},\n): ChatTurnFilePartInput[] {\n const resolvePath = opts.resolvePath ?? ((path: string) => path)\n return mentions.map((mention) => {\n const mediaType = mediaTypeForMentionPath(mention.path)\n const part: ChatTurnFilePartInput = {\n type: mediaType ? 'image' : 'file',\n filename: mention.name,\n path: resolvePath(mention.path),\n }\n if (mediaType) part.mediaType = mediaType\n return part\n })\n}\n\n/** The agent-facing pointer block appended to the dispatched prompt — never\n * persisted in message `content`. Empty array → `''` so callers can append\n * unconditionally. This is the sole producer of that text: the current\n * turn's dispatch and any history projection built from the same mention\n * list both route through here, so the two can't drift apart. */\nexport function buildMentionPromptBlock(\n mentions: readonly Pick<FileMention, 'name' | 'path'>[],\n): string {\n if (mentions.length === 0) return ''\n const lines = mentions.map((m) => `- ${m.name} (${m.path})`)\n return `\\n\\nMentioned files — read them from these paths:\\n${lines.join('\\n')}`\n}\n\n// ── mention validation ───────────────────────────────────────────────────\n//\n// This package owns BOTH ends of the mention path contract — it emits paths\n// from `createSandboxFileIndexRoute` and consumes them in `fileMentionsToParts`\n// / `buildMentionPromptBlock` — so the validation belongs here rather than in\n// each app that wires the pair up. A mention names a file that already exists\n// in the sandbox, so validation is a pure path/charset/count check with no\n// I/O: existence is proven later, when the agent reads the path and the turn\n// fails loudly if it is gone.\n\n/** Hard cap on mentions per turn. Bounds the prompt pointer block, the\n * persisted parts, and whatever media budget a dispatch draws from them. */\nexport const MENTION_MAX_COUNT = 16\n\n/** Longest mention display name accepted — bounds the pointer-block text and\n * the transcript pill label. */\nconst MAX_MENTION_NAME_LENGTH = 256\n/** Longest mention path accepted. */\nconst MAX_MENTION_PATH_LENGTH = 1024\n\nexport type SandboxMentionPathCheck =\n | { succeeded: true }\n | { succeeded: false; error: string }\n\n/**\n * Validate a workspace-relative sandbox mention path. Rejects traversal (a\n * `..` path segment), absolute paths (leading `/`), backslashes, and null\n * bytes — the four ways a path picked in a client can escape the root the\n * index route scanned.\n *\n * Spaces and unicode are deliberately ALLOWED: in-box filenames are arbitrary,\n * and an ASCII-only charset would silently drop real files from a feature\n * whose whole job is naming them.\n */\nexport function validateSandboxMentionPath(path: unknown): SandboxMentionPathCheck {\n if (typeof path !== 'string' || path.length === 0) {\n return { succeeded: false, error: 'mention path must be a non-empty string' }\n }\n if (path.length > MAX_MENTION_PATH_LENGTH) {\n return { succeeded: false, error: `mention path must not exceed ${MAX_MENTION_PATH_LENGTH} characters` }\n }\n if (path.includes('\\0')) {\n return { succeeded: false, error: 'mention path must not contain null bytes' }\n }\n if (path.includes('\\\\')) {\n return { succeeded: false, error: 'mention path must not contain backslashes' }\n }\n if (path.startsWith('/')) {\n return { succeeded: false, error: 'mention path must be workspace-relative, not absolute' }\n }\n if (path.split('/').some((segment) => segment === '..')) {\n return { succeeded: false, error: 'mention path must not contain \"..\" segments' }\n }\n return { succeeded: true }\n}\n\nfunction parseFileMention(value: unknown, index: number): FileMention {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ChatTurnInputError(`mentions[${index}] must be an object`)\n }\n const record = value as Record<string, unknown>\n\n const pathCheck = validateSandboxMentionPath(record.path)\n if (!pathCheck.succeeded) throw new ChatTurnInputError(`mentions[${index}]: ${pathCheck.error}`)\n\n const name = record.name\n if (typeof name !== 'string' || !name.trim()) {\n throw new ChatTurnInputError(`mentions[${index}].name must be a non-empty string`)\n }\n if (name.length > MAX_MENTION_NAME_LENGTH) {\n throw new ChatTurnInputError(`mentions[${index}].name must not exceed ${MAX_MENTION_NAME_LENGTH} characters`)\n }\n\n const size = record.size\n if (size !== undefined) {\n if (typeof size !== 'number' || !Number.isFinite(size)) {\n throw new ChatTurnInputError(`mentions[${index}].size must be a finite number`)\n }\n if (size < 0) {\n throw new ChatTurnInputError(`mentions[${index}].size must not be negative`)\n }\n }\n\n return { path: record.path as string, name, ...(typeof size === 'number' ? { size } : {}) }\n}\n\n/**\n * Validates the untyped `mentions` array off the wire, mirroring\n * {@link parseChatTurnParts}: the typed list, or `ChatTurnInputError` (400)\n * naming the offending entry. Never sanitizes-and-continues — a traversal path\n * is a rejected request, not a trimmed one.\n *\n * A path repeated within one turn is deduped to its first occurrence rather\n * than rejected: mentioning the same file twice is plausible user input, not\n * an attack.\n */\nexport function parseFileMentions(raw: unknown): FileMention[] {\n if (raw === undefined || raw === null) return []\n if (!Array.isArray(raw)) throw new ChatTurnInputError('mentions must be an array')\n if (raw.length > MENTION_MAX_COUNT) {\n throw new ChatTurnInputError(`mentions must not exceed ${MENTION_MAX_COUNT} entries`)\n }\n\n const mentions: FileMention[] = []\n const seenPaths = new Set<string>()\n for (let index = 0; index < raw.length; index += 1) {\n const mention = parseFileMention(raw[index], index)\n if (seenPaths.has(mention.path)) continue\n seenPaths.add(mention.path)\n mentions.push(mention)\n }\n return mentions\n}\n\n/** Validates the untyped `parts` array off the wire. Returns the typed parts\n * or throws `ChatTurnInputError` (400) naming the offending entry. */\nexport function parseChatTurnParts(raw: unknown): ChatTurnFilePartInput[] {\n if (raw === undefined || raw === null) return []\n if (!Array.isArray(raw)) throw new ChatTurnInputError('parts must be an array')\n return raw.map((entry, index) => {\n const part = entry as Record<string, unknown> | null\n if (!part || typeof part !== 'object') {\n throw new ChatTurnInputError(`parts[${index}] must be an object`)\n }\n if (part.type !== 'image' && part.type !== 'file') {\n throw new ChatTurnInputError(`parts[${index}].type must be 'image' or 'file'`)\n }\n for (const key of ['filename', 'mediaType', 'url', 'path', 'content'] as const) {\n if (part[key] !== undefined && typeof part[key] !== 'string') {\n throw new ChatTurnInputError(`parts[${index}].${key} must be a string`)\n }\n }\n if (!part.url && !part.path && !part.content) {\n throw new ChatTurnInputError(`parts[${index}] needs a url, path, or content`)\n }\n return {\n type: part.type,\n ...(part.filename !== undefined ? { filename: part.filename as string } : {}),\n ...(part.mediaType !== undefined ? { mediaType: part.mediaType as string } : {}),\n ...(part.url !== undefined ? { url: part.url as string } : {}),\n ...(part.path !== undefined ? { path: part.path as string } : {}),\n ...(part.content !== undefined ? { content: part.content as string } : {}),\n }\n })\n}\n","/**\n * The stored shape of `message.parts` — one typed vocabulary for every part a\n * product persists into a chat transcript. NOT an ad-hoc union reverse-\n * engineered from product schemas; each member is matched field-for-field to\n * its canonical source:\n *\n * - `text` / `reasoning` / `tool`: the persisted projection `/stream`'s\n * `normalizePersistedPart` produces from the harness lane's\n * `message.part.updated` events (ADC sidecar\n * `apps/sidecar/src/events/session-events.ts:56` wraps the canonical part in\n * an `{id, sessionID, messageID}` envelope; the projection strips the\n * session/message ids and keeps the per-segment part id).\n * - `file` / `image` / `step-start` / `step-finish`: the sidecar's canonical\n * `MessagePartSchema` members (ADC\n * `apps/sidecar/src/schemas/agent-schemas.ts:50-154`); `step-finish` carries\n * the harness's per-step usage receipt — tokens\n * `{total, input, output, reasoning, cache{write, read}}` + `cost` — which is\n * also the shape the message-level token/cost columns mirror.\n * - `subtask`: `@tangle-network/agent-interface`'s `SubtaskPart` (a spawned\n * sub-agent task).\n * - `interaction` / `notice`: the persisted-part codecs in\n * `/web-react`'s chat-interactions contract (`interactionToPersistedPart`,\n * `noticePart`) — type-only imports, one source of truth for their statuses\n * and field shapes.\n * - `plan`: the durable-plan projection in `/plans`, derived from the sandbox\n * SDK's authoritative plan lifecycle.\n * - `mention`: an `@`-picked reference to a file that already lives in the\n * workspace sandbox (`FileMention` in `/chat-routes`'s wire contract, plus\n * the image/file discriminant). Neither transport lane produces it — the\n * turn route persists it from the request's `mentions` field — but it is a\n * part a product persists into a transcript, so it belongs in this\n * vocabulary rather than in a parallel one.\n *\n * `@tangle-network/agent-interface` exports the canonical wire `Part` union,\n * but its `PartBase` requires the `sessionID`/`messageID` stream envelope that\n * is deliberately NOT persisted, so the stored union is defined here as the\n * envelope-free projection (a type-level coverage check against the peer's\n * `Part['type']` lives in the tests). Contribute-down candidate: if\n * agent-interface grows envelope-free persisted-part types, re-export them\n * here and delete these definitions.\n *\n * Two transport lanes serialize into this SAME stored shape:\n * - harness lane: canonical `message.part.updated` parts, merged/normalized by\n * `/stream` (`mergePersistedPart`, `finalizeAssistantParts`);\n * - router/openai-compat lane: `text_delta`/`tool_call` stream events are\n * mapped INTO canonical part events first (`/runtime`'s `toLoopEvents` +\n * `/stream`'s `normalizeToolEvent`) and then persisted identically — the\n * store never sees a router-specific shape.\n */\n\nimport type { Part as HarnessWirePart } from '@tangle-network/agent-interface'\nimport type {\n ChatInteractionField,\n ChatInteractionStatus,\n InteractionAnswers,\n InteractionPersistedPart,\n NoticeKind,\n NoticePersistedPart,\n} from '../web-react/chat-interactions'\nimport { persistedPartToInteraction } from '../interactions/contract'\nimport {\n persistedPartToPlan,\n planToPersistedPart,\n type ChatPlanPersistedPart,\n} from '../plans/index'\n// `./wire` is import-free by construction, so this edge costs the store\n// nothing and keeps ONE image-extension table for the whole mention layer.\nimport { mentionKindForPath, type ChatMentionKind, type FileMention } from '../chat-routes/wire'\n\nexport type { ChatMentionKind }\n\n/** Start/end wall-clock millis, as normalized by `/stream`'s `normalizeTime`. */\nexport interface ChatPartTime {\n start?: number\n end?: number\n}\n\n/** `id` is the harness's per-segment identity; absent on legacy/router parts,\n * which collapse to a single logical text stream. Never invented client-side. */\nexport interface ChatTextPart {\n type: 'text'\n text: string\n id?: string\n}\n\nexport interface ChatReasoningPart {\n type: 'reasoning'\n text: string\n id?: string\n time?: ChatPartTime\n}\n\n/** Superset of the sidecar's status enum (`pending|running|completed|failed`)\n * and agent-interface's `ToolState` statuses; `error` is the persisted\n * terminal form `/stream`'s `normalizePersistedPart` settles on. */\nexport type ChatToolStatus = 'pending' | 'running' | 'completed' | 'error' | 'failed'\n\nexport interface ChatToolState {\n status: ChatToolStatus\n input?: unknown\n output?: unknown\n error?: string\n title?: string\n metadata?: Record<string, unknown>\n time?: ChatPartTime\n}\n\nexport interface ChatToolPart {\n type: 'tool'\n id: string\n tool: string\n callID?: string\n state: ChatToolState\n}\n\n/** Union of the sidecar's legacy (path-based) and AI-SDK (url-based) file\n * shapes; response-side every field besides `type` is optional. */\nexport interface ChatFilePart {\n type: 'file'\n id?: string\n filename?: string\n mediaType?: string\n url?: string\n path?: string\n content?: string\n}\n\nexport interface ChatImagePart {\n type: 'image'\n filename?: string\n mediaType?: string\n url?: string\n path?: string\n}\n\nexport interface ChatSubtaskPart {\n type: 'subtask'\n prompt: string\n description: string\n agent: string\n id?: string\n}\n\n/** OpenCode step-boundary marker — no renderable text; preserved so mappers\n * never coerce it into a \"[object Object]\" text part. */\nexport interface ChatStepStartPart {\n type: 'step-start'\n}\n\n/** Per-step usage receipt as the harness reports it (sidecar\n * `StepFinishPartSchema`). The message-level token/cost columns are this\n * shape flattened. */\nexport interface ChatUsageTokens {\n total?: number\n input?: number\n output?: number\n reasoning?: number\n cache?: {\n write?: number\n read?: number\n }\n}\n\nexport interface ChatStepFinishPart {\n type: 'step-finish'\n reason?: string\n tokens?: ChatUsageTokens\n cost?: number\n}\n\n/** Persisted human-in-the-loop ask — byte-matches\n * `interactionToPersistedPart` in `/web-react`'s chat-interactions contract. */\nexport interface ChatInteractionPart {\n type: 'interaction'\n id: string\n kind: string\n title: string\n body?: string\n answerSpec: { fields: ChatInteractionField[] }\n status: ChatInteractionStatus\n answers?: InteractionAnswers\n cancelReason?: string\n}\n\nexport type ChatPlanPart = ChatPlanPersistedPart\n\n/** Persisted one-line transcript notice — byte-matches `noticePart` in\n * `/web-react`'s chat-interactions contract. */\nexport interface ChatNoticePart {\n type: 'notice'\n id: string\n noticeKind: NoticeKind\n text: string\n}\n\n/**\n * A file the user `@`-mentioned on this turn: a workspace-relative path into\n * the sandbox, never bytes. `type: 'mention'` is its own discriminant\n * precisely so it does NOT collide with the `file`/`image` attachment parts —\n * an attachment carries content the product uploaded, a mention points at\n * something the box already has, and a transcript renders them differently\n * (an inline pill, not an attachment card).\n *\n * `path` is the identity: mentioning one file twice in a turn folds to one\n * part. `turnId` is optional and set by products that rebuild a turn's\n * mentions on retry.\n */\nexport interface ChatMentionPart {\n type: 'mention'\n mentionKind: ChatMentionKind\n path: string\n name: string\n size?: number\n turnId?: string\n}\n\n// The \"byte-matches\" claims above, enforced at compile time: the interaction\n// contract's codec output types and the stored part types must stay mutually\n// assignable, so a codec field added on one side without the other fails here.\ntype MutuallyAssignable<A extends B, B> = A\ntype _CodecEmitsStorableInteractionPart = MutuallyAssignable<InteractionPersistedPart, ChatInteractionPart>\ntype _StoredInteractionPartFeedsCodec = MutuallyAssignable<ChatInteractionPart, InteractionPersistedPart>\ntype _CodecEmitsStorableNoticePart = MutuallyAssignable<NoticePersistedPart, ChatNoticePart>\ntype _StoredNoticePartFeedsCodec = MutuallyAssignable<ChatNoticePart, NoticePersistedPart>\ntype _CodecEmitsStorablePlanPart = MutuallyAssignable<ChatPlanPersistedPart, ChatPlanPart>\ntype _StoredPlanPartFeedsCodec = MutuallyAssignable<ChatPlanPart, ChatPlanPersistedPart>\n\nexport type ChatMessagePart =\n | ChatTextPart\n | ChatReasoningPart\n | ChatToolPart\n | ChatFilePart\n | ChatImagePart\n | ChatSubtaskPart\n | ChatStepStartPart\n | ChatStepFinishPart\n | ChatInteractionPart\n | ChatNoticePart\n | ChatPlanPart\n | ChatMentionPart\n\n/** Every canonical harness wire-part kind must be storable — compile-time\n * guarantee that a new agent-interface part kind cannot silently fall out of\n * the persisted vocabulary. */\nexport type StorableHarnessPartKind = HarnessWirePart['type'] & ChatMessagePart['type']\n\n/**\n * The typed projection at the `/stream` → `/chat-store` boundary. The stream\n * normalizers (`normalizePersistedPart`/`mergePersistedPart`/\n * `finalizeAssistantParts`) deliberately produce untyped `JsonRecord`s — they\n * normalize wire shapes and do not own the stored vocabulary. THIS module\n * owns it, so this is where rows gain the `ChatMessagePart` type: each entry\n * is validated against its kind's required fields and narrowed, junk is\n * dropped, and — enforced by the exhaustiveness check below — no storable\n * kind can silently fall out (the step-finish/interaction trap).\n */\nexport function toChatMessageParts(parts: Array<Record<string, unknown>>): ChatMessagePart[] {\n const out: ChatMessagePart[] = []\n for (const part of parts) {\n const typed = toChatMessagePart(part)\n if (typed) out.push(typed)\n }\n return out\n}\n\nconst str = (value: unknown): value is string => typeof value === 'string'\n\nfunction toChatMessagePart(part: Record<string, unknown>): ChatMessagePart | null {\n if (!part || typeof part !== 'object') return null\n const type = part.type as ChatMessagePart['type'] | undefined\n switch (type) {\n case 'text':\n case 'reasoning':\n return str(part.text) ? (part as unknown as ChatTextPart | ChatReasoningPart) : null\n case 'tool':\n return str(part.id) && str(part.tool) && part.state && typeof part.state === 'object'\n ? (part as unknown as ChatToolPart)\n : null\n case 'file':\n case 'image':\n return part as unknown as ChatFilePart | ChatImagePart\n case 'subtask':\n return str(part.prompt) && str(part.description) && str(part.agent)\n ? (part as unknown as ChatSubtaskPart)\n : null\n case 'step-start':\n return { type: 'step-start' }\n case 'step-finish':\n return part as unknown as ChatStepFinishPart\n case 'interaction':\n return persistedPartToInteraction(part) ? (part as unknown as ChatInteractionPart) : null\n case 'notice':\n return str(part.id) && str(part.noticeKind) && str(part.text)\n ? (part as unknown as ChatNoticePart)\n : null\n case 'plan': {\n const plan = persistedPartToPlan(part)\n return plan ? ({ ...part, ...planToPersistedPart(plan) } as ChatPlanPart) : null\n }\n case 'mention':\n return isChatMentionPart(part) ? part : null\n case undefined:\n return null\n default: {\n // Compile-time exhaustiveness: a new ChatMessagePart kind that is not\n // handled above makes `type` non-never here and this line fails.\n const _exhaustive: never = type\n void _exhaustive\n return null\n }\n }\n}\n\nexport function isChatToolPart(part: ChatMessagePart): part is ChatToolPart {\n return part.type === 'tool'\n}\n\nexport function isChatTextPart(part: ChatMessagePart): part is ChatTextPart {\n return part.type === 'text'\n}\n\nexport function isChatInteractionPart(part: ChatMessagePart): part is ChatInteractionPart {\n return part.type === 'interaction'\n}\n\nexport function isChatPlanPart(part: ChatMessagePart): part is ChatPlanPart {\n return part.type === 'plan'\n}\n\nexport function isChatStepFinishPart(part: ChatMessagePart): part is ChatStepFinishPart {\n return part.type === 'step-finish'\n}\n\n/** Widened to `unknown` — unlike its siblings this guard also runs over raw\n * untyped stored rows (a transcript renderer reads `message.parts` before the\n * typed projection), which is exactly what {@link mentionPartsFromMessageParts}\n * needs. `path` and `name` carry the pill; a row missing either is unrenderable.\n *\n * Mirrors the write contract exactly (`parseFileMention` in `/chat-routes`,\n * then {@link mentionInputToPart}): a blank `name` is rejected there and so is\n * rejected here, and `size` — optional, but typed `number` once present — is\n * type-checked so `'12'` or `null` cannot ride through the guard wearing a\n * type it does not have. Negative sizes are NOT re-rejected: the wire screens\n * them, `mentionInputToPart` trusts its input, and a read guard stricter than\n * what the writer can emit would drop rows it produced itself. */\nexport function isChatMentionPart(part: unknown): part is ChatMentionPart {\n if (!part || typeof part !== 'object') return false\n const record = part as Record<string, unknown>\n if (record.size !== undefined && (typeof record.size !== 'number' || !Number.isFinite(record.size))) {\n return false\n }\n return (\n record.type === 'mention' &&\n typeof record.path === 'string' &&\n record.path.length > 0 &&\n typeof record.name === 'string' &&\n record.name.trim().length > 0 &&\n (record.mentionKind === 'image' || record.mentionKind === 'file')\n )\n}\n\n/** Every mention part on one message, in stored order. The projection a\n * transcript renderer runs before deciding which mentions the message text\n * already shows inline (see `segmentMentionContent` in `/web-react`). */\nexport function mentionPartsFromMessageParts(\n parts: ReadonlyArray<Record<string, unknown>> | ReadonlyArray<ChatMessagePart> | null | undefined,\n): ChatMentionPart[] {\n if (!parts) return []\n return (parts as ReadonlyArray<unknown>).filter(isChatMentionPart)\n}\n\n/** A validated wire mention (`parseFileMentions` in `/chat-routes`) as the\n * part the turn route persists. An absent/non-finite `size` is DROPPED rather\n * than stored as `undefined`, so a stored row never carries a key that means\n * nothing. */\nexport function mentionInputToPart(input: FileMention): ChatMentionPart {\n const part: ChatMentionPart = {\n type: 'mention',\n mentionKind: mentionKindForPath(input.path),\n path: input.path,\n name: input.name,\n }\n if (typeof input.size === 'number' && Number.isFinite(input.size)) part.size = input.size\n return part\n}\n"],"mappings":";;;;;;;;;AA0DO,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U,QAAO;AAC9C,QAAM,SAAS;AACf,MAAI,OAAO,SAAS,WAAc,OAAO,OAAO,SAAS,YAAY,CAAC,OAAO,SAAS,OAAO,IAAI,IAAI;AACnG,WAAO;AAAA,EACT;AACA,SACE,OAAO,SAAS,aAChB,OAAO,OAAO,SAAS,YACvB,OAAO,KAAK,SAAS,KACrB,OAAO,OAAO,SAAS,YACvB,OAAO,KAAK,KAAK,EAAE,SAAS,MAC3B,OAAO,gBAAgB,WAAW,OAAO,gBAAgB;AAE9D;AAKO,SAAS,6BACd,OACmB;AACnB,MAAI,CAAC,MAAO,QAAO,CAAC;AACpB,SAAQ,MAAiC,OAAO,iBAAiB;AACnE;AAMO,SAAS,mBAAmB,OAAqC;AACtE,QAAM,OAAwB;AAAA,IAC5B,MAAM;AAAA,IACN,aAAa,mBAAmB,MAAM,IAAI;AAAA,IAC1C,MAAM,MAAM;AAAA,IACZ,MAAM,MAAM;AAAA,EACd;AACA,MAAI,OAAO,MAAM,SAAS,YAAY,OAAO,SAAS,MAAM,IAAI,EAAG,MAAK,OAAO,MAAM;AACrF,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// src/chat-routes/file-index.ts
|
|
2
|
+
var DEFAULT_IGNORE_SEGMENTS = [
|
|
3
|
+
"node_modules",
|
|
4
|
+
"dist",
|
|
5
|
+
"build",
|
|
6
|
+
"out",
|
|
7
|
+
"coverage",
|
|
8
|
+
"target",
|
|
9
|
+
"__pycache__",
|
|
10
|
+
"venv"
|
|
11
|
+
];
|
|
12
|
+
function isIgnored(relPath, ignoreSegments) {
|
|
13
|
+
for (const segment of relPath.split("/")) {
|
|
14
|
+
if (!segment) continue;
|
|
15
|
+
if (segment.startsWith(".")) return true;
|
|
16
|
+
if (ignoreSegments.has(segment)) return true;
|
|
17
|
+
}
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
function relativeTo(root, path) {
|
|
21
|
+
const prefix = root.endsWith("/") ? root : `${root}/`;
|
|
22
|
+
if (path.startsWith(prefix)) return path.slice(prefix.length);
|
|
23
|
+
if (path === root) return "";
|
|
24
|
+
return path;
|
|
25
|
+
}
|
|
26
|
+
function basename(path) {
|
|
27
|
+
const segments = path.split("/").filter(Boolean);
|
|
28
|
+
return segments[segments.length - 1] ?? path;
|
|
29
|
+
}
|
|
30
|
+
function isMissingRootError(err, root) {
|
|
31
|
+
if (!(err instanceof Error)) return false;
|
|
32
|
+
if (err.code !== "VALIDATION_ERROR") return false;
|
|
33
|
+
return /ENOENT/.test(err.message) && /no such file or directory/.test(err.message) && new RegExp(`\\blstat '${escapeRegExp(root)}'`).test(err.message);
|
|
34
|
+
}
|
|
35
|
+
function escapeRegExp(value) {
|
|
36
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
37
|
+
}
|
|
38
|
+
function createSandboxFileIndexRoute(options) {
|
|
39
|
+
const maxDepth = options.maxDepth ?? 12;
|
|
40
|
+
const maxEntries = options.maxEntries ?? 5e3;
|
|
41
|
+
const cacheTtlSeconds = options.cacheTtlSeconds ?? 20;
|
|
42
|
+
const staticIgnore = /* @__PURE__ */ new Set([...DEFAULT_IGNORE_SEGMENTS, ...options.ignore ?? []]);
|
|
43
|
+
return async function fileIndex(request) {
|
|
44
|
+
const auth = await options.authorize({ request });
|
|
45
|
+
if (auth.status === "denied") return auth.response;
|
|
46
|
+
if (auth.status === "warming") {
|
|
47
|
+
return Response.json({ status: "warming" });
|
|
48
|
+
}
|
|
49
|
+
const cache = options.cache;
|
|
50
|
+
if (cache && auth.cacheKey) {
|
|
51
|
+
const cached = await cache.get(auth.cacheKey);
|
|
52
|
+
if (cached) return Response.json(cached);
|
|
53
|
+
}
|
|
54
|
+
const ignoreSegments = auth.ignore?.length ? /* @__PURE__ */ new Set([...staticIgnore, ...auth.ignore]) : staticIgnore;
|
|
55
|
+
let scan;
|
|
56
|
+
try {
|
|
57
|
+
scan = await auth.fs.tree(auth.root, { maxDepth });
|
|
58
|
+
} catch (err) {
|
|
59
|
+
if (!isMissingRootError(err, auth.root)) throw err;
|
|
60
|
+
return Response.json({ status: "warming" });
|
|
61
|
+
}
|
|
62
|
+
const filtered = scan.files.filter((f) => !isIgnored(relativeTo(scan.root, f.path), ignoreSegments));
|
|
63
|
+
const truncated = scan.stats.truncated || filtered.length > maxEntries;
|
|
64
|
+
const files = filtered.slice(0, maxEntries).map((f) => {
|
|
65
|
+
const path = relativeTo(scan.root, f.path);
|
|
66
|
+
const entry = { path, name: basename(path) };
|
|
67
|
+
if (typeof f.size === "number") entry.size = f.size;
|
|
68
|
+
return entry;
|
|
69
|
+
});
|
|
70
|
+
const body = {
|
|
71
|
+
status: "ready",
|
|
72
|
+
files,
|
|
73
|
+
truncated,
|
|
74
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
75
|
+
};
|
|
76
|
+
if (cache && auth.cacheKey) await cache.put(auth.cacheKey, body, { ttlSeconds: cacheTtlSeconds });
|
|
77
|
+
return Response.json(body);
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export {
|
|
82
|
+
createSandboxFileIndexRoute
|
|
83
|
+
};
|
|
84
|
+
//# sourceMappingURL=chunk-LCNY3DCM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/chat-routes/file-index.ts"],"sourcesContent":["/**\n * `createSandboxFileIndexRoute` — server side of `@`-file-mentions\n * (companion to sandbox-ui#184's composer mention primitive). Serves a flat,\n * ignore-filtered listing of the workspace sandbox so `useFileMentions`\n * (`/web-react`) can filter it client-side without a round trip per\n * keystroke.\n *\n * Same seam style as `createUploadRoute`: `authorize({ request })` resolves a\n * structural `{ tree(path, opts) }` handle (the shape of the sandbox SDK's\n * `box.fs.tree`) — no SDK import here. `authorize` also carries the\n * cold-box signal: a sandbox that isn't running yet answers `{ status:\n * 'warming' }` directly, never provisions-and-waits inside this route.\n *\n * A box can also be running with its workspace root not yet materialised, which\n * `authorize` cannot see; the route recognises that one signal off `fs.tree`\n * and answers `warming` too, so every consumer gets the retry-and-wait state\n * instead of a 500. Every other `tree()` failure propagates.\n */\n\nimport type { FileMention } from './wire'\n\n/** One entry from a structural `tree()` scan. Mirrors the sandbox SDK's\n * `FileTreeFile` (`path`, `size`, `mtime`) — `mtime` is unused here so it's\n * omitted from the structural match. */\nexport interface SandboxTreeFile {\n path: string\n size: number\n}\n\n/** Structural match of the sandbox SDK's `box.fs.tree` result shape\n * (`FileTreeResult`). `stats.truncated` is the only stat this route reads;\n * the rest ride through unread on the real SDK type. */\nexport interface SandboxTreeResult {\n root: string\n files: SandboxTreeFile[]\n stats: { truncated: boolean }\n}\n\n/** Structural match of the sandbox SDK's `box.fs` tree surface. */\nexport interface SandboxFileTreeSource {\n tree(path: string, options?: { maxDepth?: number }): Promise<SandboxTreeResult>\n}\n\nexport interface FileIndexReadyResponse {\n status: 'ready'\n /** Workspace-relative entries. Same shape as `FileMention` (`./wire`) so a\n * client can hand a response entry straight to `fileMentionsToParts` /\n * `buildMentionPromptBlock` without remapping. */\n files: FileMention[]\n /** True when either the underlying scan truncated (SDK-side cap) or this\n * route's own `maxEntries` cap trimmed the filtered list. The client\n * should show \"showing first N files\" rather than imply completeness. */\n truncated: boolean\n generatedAt: string\n}\n\n/** Cold-box answer: no provisioning happened, no files were scanned. The\n * client shows a warming state and retries — this route never blocks on a\n * box coming up. Two situations produce it: `authorize` reporting a box that\n * is not running, and a running box whose workspace root does not exist yet\n * (see `isMissingRootError`). */\nexport interface FileIndexWarmingResponse {\n status: 'warming'\n}\n\nexport type FileIndexResponse = FileIndexReadyResponse | FileIndexWarmingResponse\n\n/** Short-TTL cache seam so repeat popover opens in the same session don't\n * re-scan the workspace. Host-provided (e.g. a KV binding); `key` is\n * whatever `authorize` returns as `cacheKey` — this route treats it opaquely. */\nexport interface FileIndexCache {\n get(key: string): Promise<FileIndexReadyResponse | null> | FileIndexReadyResponse | null\n put(key: string, value: FileIndexReadyResponse, options?: { ttlSeconds?: number }): Promise<void> | void\n}\n\nexport type FileIndexAuthorization =\n | {\n status: 'ready'\n /** Structural sandbox `fs` handle, usually `ensureWorkspaceSandbox(...)` → `box.fs`. */\n fs: SandboxFileTreeSource\n /** Workspace root to index (e.g. `/home/agent`). */\n root: string\n /** Extra ignore segments for this request, merged with the route's\n * defaults + `CreateSandboxFileIndexRouteOptions.ignore`. */\n ignore?: string[]\n /** Opaque cache key for the optional cache seam. Omit to skip caching\n * for this request (e.g. a workspace the host chooses not to cache). */\n cacheKey?: string\n }\n | { status: 'warming' }\n | { status: 'denied'; response: Response }\n\nexport interface CreateSandboxFileIndexRouteOptions {\n /** Authenticate the caller, resolve the sandbox `fs` handle, and signal a\n * cold box — never provisions or waits. */\n authorize(args: { request: Request }): Promise<FileIndexAuthorization>\n /** Extra ignore segments beyond the route's defaults (node_modules, .git,\n * dotfiles/dot-dirs, common build dirs). Matched as exact path-segment\n * names, same rule as the defaults. */\n ignore?: string[]\n /** Passed to `fs.tree` as `options.maxDepth`. Default 12. */\n maxDepth?: number\n /** Hard cap on entries returned after filtering. Default 5000. */\n maxEntries?: number\n /** Optional host-provided cache seam. */\n cache?: FileIndexCache\n /** Cache TTL in seconds when `cache` is set. Default 20. */\n cacheTtlSeconds?: number\n}\n\n/** Segment names ignored anywhere in a path, beyond the generic dotfile rule\n * below. Intentionally small and language/framework-agnostic — callers\n * extend it via `ignore` for anything domain-specific (e.g. a vault's\n * `uploads` dir). */\nconst DEFAULT_IGNORE_SEGMENTS = [\n 'node_modules',\n 'dist',\n 'build',\n 'out',\n 'coverage',\n 'target',\n '__pycache__',\n 'venv',\n]\n\n/** A path segment starting with `.` (`.git`, `.env`, `.next`, `.cache`, …) is\n * always ignored — this single rule covers most dot-prefixed VCS/tooling\n * dirs and dotfiles without enumerating them. */\nfunction isIgnored(relPath: string, ignoreSegments: ReadonlySet<string>): boolean {\n for (const segment of relPath.split('/')) {\n if (!segment) continue\n if (segment.startsWith('.')) return true\n if (ignoreSegments.has(segment)) return true\n }\n return false\n}\n\n/** Strips the tree result's echoed `root` prefix so entries are always\n * workspace-relative, whichever convention the structural `fs.tree` uses\n * (root-relative already, or root-prefixed). */\nfunction relativeTo(root: string, path: string): string {\n const prefix = root.endsWith('/') ? root : `${root}/`\n if (path.startsWith(prefix)) return path.slice(prefix.length)\n if (path === root) return ''\n return path\n}\n\nfunction basename(path: string): string {\n const segments = path.split('/').filter(Boolean)\n return segments[segments.length - 1] ?? path\n}\n\n/**\n * A box can answer `running` before it has materialised the workspace root —\n * `authorize` has already committed to `ready` by then, so `fs.tree` is the\n * first thing to notice, and it rejects with the sandbox SDK's\n * `ValidationError` wrapping a box-side `ENOENT … lstat` on the root. That is\n * the SAME \"not usable yet\" state `authorize` collapses onto `warming` for an\n * absent or stopped box, just discovered one step later, so it gets the same\n * answer instead of escaping as a 500.\n *\n * Matched STRUCTURALLY, not with `instanceof`: importing the SDK's error class\n * would make `@tangle-network/sandbox` a hard dependency of a route factory\n * whose entire `fs` seam is structural (`SandboxFileTreeSource`), and would\n * break any host feeding it a non-SDK handle.\n *\n * Deliberately narrow — the error code, `ENOENT`, the ENOENT message text, AND\n * the failing syscall's own operand all have to line up. A permission error, a\n * timeout, an auth failure, or an ENOENT on some other path inside the tree is\n * a real failure and still surfaces.\n *\n * The operand is matched as the quoted `lstat '<root>'` clause rather than by\n * substring, because the root is a PREFIX of everything under it: a plain\n * `includes(root)` would also swallow an ENOENT on `<root>/gone/x.md`, and on\n * a prefix sibling like `/home/agent-old/...`.\n */\nfunction isMissingRootError(err: unknown, root: string): boolean {\n if (!(err instanceof Error)) return false\n if ((err as { code?: unknown }).code !== 'VALIDATION_ERROR') return false\n return (\n /ENOENT/.test(err.message) &&\n /no such file or directory/.test(err.message) &&\n new RegExp(`\\\\blstat '${escapeRegExp(root)}'`).test(err.message)\n )\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nexport function createSandboxFileIndexRoute(\n options: CreateSandboxFileIndexRouteOptions,\n): (request: Request) => Promise<Response> {\n const maxDepth = options.maxDepth ?? 12\n const maxEntries = options.maxEntries ?? 5000\n const cacheTtlSeconds = options.cacheTtlSeconds ?? 20\n const staticIgnore = new Set([...DEFAULT_IGNORE_SEGMENTS, ...(options.ignore ?? [])])\n\n return async function fileIndex(request: Request): Promise<Response> {\n const auth = await options.authorize({ request })\n if (auth.status === 'denied') return auth.response\n if (auth.status === 'warming') {\n return Response.json({ status: 'warming' } satisfies FileIndexWarmingResponse)\n }\n\n const cache = options.cache\n if (cache && auth.cacheKey) {\n const cached = await cache.get(auth.cacheKey)\n if (cached) return Response.json(cached)\n }\n\n const ignoreSegments = auth.ignore?.length\n ? new Set([...staticIgnore, ...auth.ignore])\n : staticIgnore\n\n let scan: SandboxTreeResult\n try {\n scan = await auth.fs.tree(auth.root, { maxDepth })\n } catch (err) {\n if (!isMissingRootError(err, auth.root)) throw err\n return Response.json({ status: 'warming' } satisfies FileIndexWarmingResponse)\n }\n const filtered = scan.files.filter((f) => !isIgnored(relativeTo(scan.root, f.path), ignoreSegments))\n const truncated = scan.stats.truncated || filtered.length > maxEntries\n const files: FileMention[] = filtered.slice(0, maxEntries).map((f) => {\n const path = relativeTo(scan.root, f.path)\n const entry: FileMention = { path, name: basename(path) }\n if (typeof f.size === 'number') entry.size = f.size\n return entry\n })\n\n const body: FileIndexReadyResponse = {\n status: 'ready',\n files,\n truncated,\n generatedAt: new Date().toISOString(),\n }\n\n if (cache && auth.cacheKey) await cache.put(auth.cacheKey, body, { ttlSeconds: cacheTtlSeconds })\n\n return Response.json(body)\n }\n}\n"],"mappings":";AAkHA,IAAM,0BAA0B;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAKA,SAAS,UAAU,SAAiB,gBAA8C;AAChF,aAAW,WAAW,QAAQ,MAAM,GAAG,GAAG;AACxC,QAAI,CAAC,QAAS;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ions, clearMentions, refresh };
|
|
2090
2090
|
}
|
|
2091
2091
|
|
|
2092
|
+
// src/web-react/chat-mentions.ts
|
|
2093
|
+
var PATH_CONTINUATION_CHAR = /[\p{L}\p{N}._\-/]/u;
|
|
2094
|
+
var WORD_CHAR = /[\p{L}\p{N}]/u;
|
|
2095
|
+
function segmentMentionContent(content, parts) {
|
|
2096
|
+
const matched = /* @__PURE__ */ new Set();
|
|
2097
|
+
if (!content) return { segments: [], matched };
|
|
2098
|
+
if (parts.length === 0) return { segments: [{ type: "text", text: content }], matched };
|
|
2099
|
+
const candidates = parts.map((part) => ({ part, token: `@${part.path}` })).sort((a, b) => b.token.length - a.token.length);
|
|
2100
|
+
const segments = [];
|
|
2101
|
+
let cursor = 0;
|
|
2102
|
+
let textStart = 0;
|
|
2103
|
+
while (cursor < content.length) {
|
|
2104
|
+
if (content[cursor] !== "@") {
|
|
2105
|
+
cursor += 1;
|
|
2106
|
+
continue;
|
|
2107
|
+
}
|
|
2108
|
+
const prevChar = cursor > 0 ? content[cursor - 1] : void 0;
|
|
2109
|
+
if (prevChar && WORD_CHAR.test(prevChar)) {
|
|
2110
|
+
cursor += 1;
|
|
2111
|
+
continue;
|
|
2112
|
+
}
|
|
2113
|
+
const candidate = candidates.find(({ token }) => content.startsWith(token, cursor));
|
|
2114
|
+
if (!candidate) {
|
|
2115
|
+
cursor += 1;
|
|
2116
|
+
continue;
|
|
2117
|
+
}
|
|
2118
|
+
const endIdx = cursor + candidate.token.length;
|
|
2119
|
+
const nextChar = endIdx < content.length ? content[endIdx] : void 0;
|
|
2120
|
+
if (nextChar && PATH_CONTINUATION_CHAR.test(nextChar)) {
|
|
2121
|
+
cursor += 1;
|
|
2122
|
+
continue;
|
|
2123
|
+
}
|
|
2124
|
+
if (cursor > textStart) segments.push({ type: "text", text: content.slice(textStart, cursor) });
|
|
2125
|
+
segments.push({ type: "mention", text: candidate.token, part: candidate.part });
|
|
2126
|
+
matched.add(candidate.part);
|
|
2127
|
+
cursor = endIdx;
|
|
2128
|
+
textStart = cursor;
|
|
2129
|
+
}
|
|
2130
|
+
if (textStart < content.length) segments.push({ type: "text", text: content.slice(textStart) });
|
|
2131
|
+
return { segments, matched };
|
|
2132
|
+
}
|
|
2133
|
+
|
|
2092
2134
|
// src/web-react/mission-activity.tsx
|
|
2093
2135
|
import { useCallback as useCallback5, useEffect as useEffect7, useState as useState10 } from "react";
|
|
2094
2136
|
import { Fragment as Fragment4, jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
|
|
@@ -3298,6 +3340,7 @@ export {
|
|
|
3298
3340
|
INDEX_REFRESH_AFTER_MS,
|
|
3299
3341
|
DEFAULT_MENTION_EMPTY_TEXT,
|
|
3300
3342
|
useFileMentions,
|
|
3343
|
+
segmentMentionContent,
|
|
3301
3344
|
activityTone,
|
|
3302
3345
|
formatActivityCost,
|
|
3303
3346
|
formatActivityDuration,
|
|
@@ -3316,4 +3359,4 @@ export {
|
|
|
3316
3359
|
useThinkingSeconds,
|
|
3317
3360
|
ChatMessages
|
|
3318
3361
|
};
|
|
3319
|
-
//# sourceMappingURL=chunk-
|
|
3362
|
+
//# sourceMappingURL=chunk-Q4EU6MGU.js.map
|