@tangle-network/agent-app 0.43.43 → 0.43.45
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-PEUBCJXF.js → chunk-7VMUOD3G.js} +79 -1
- package/dist/chunk-7VMUOD3G.js.map +1 -0
- package/dist/chunk-LCNY3DCM.js +84 -0
- package/dist/chunk-LCNY3DCM.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 +68 -5
- 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
|
@@ -5,13 +5,14 @@ export { d as ComposerAnswerDelivery, I as INTERACTION_CANCEL_EVENT, e as INTERA
|
|
|
5
5
|
import { ChatPlan } from '../plans/index.js';
|
|
6
6
|
import { InteractionData } from '@tangle-network/agent-interface';
|
|
7
7
|
export { InteractionData, InteractionOutcome, InteractionRequest } from '@tangle-network/agent-interface';
|
|
8
|
-
import {
|
|
9
|
-
export {
|
|
8
|
+
import { F as FileMention, d as ChatMentionPart } from '../parts-1_3y2JmR.js';
|
|
9
|
+
export { c as ChatMentionKind, D as ChatTurnFilePartInput, B as ChatTurnPartInput, A as ChatTurnRequestPayload, L as buildMentionPromptBlock, N as chatTurnRequestInit, O as fileMentionsToParts, P as mediaTypeForMentionPath, x as mentionInputToPart, Q as mentionKindForPath, y as mentionPartsFromMessageParts } from '../parts-1_3y2JmR.js';
|
|
10
10
|
import { S as StepAgentActivity } from '../agent-activity-C8ZG0F0M.js';
|
|
11
11
|
import { a as FlowTrace } from '../flow-types-Cb_AblZs.js';
|
|
12
12
|
export { S as SandboxTerminalConnection, a as SandboxTerminalConnectionResponse, U as UseSandboxTerminalConnectionOptions, b as UseSandboxTerminalConnectionResult, t as tabTerminalConnectionId, u as useSandboxTerminalConnection } from '../sandbox-terminal-BIIC__CP.js';
|
|
13
13
|
import { CatalogModel } from '../catalog/index.js';
|
|
14
14
|
import { Harness } from '../harness/index.js';
|
|
15
|
+
export { b as FileIndexReadyResponse, c as FileIndexResponse, d as FileIndexWarmingResponse } from '../file-index-Bn6sitKb.js';
|
|
15
16
|
|
|
16
17
|
type DurablePlanDecision = 'approved' | 'rejected';
|
|
17
18
|
/** Stable authority receipt for the follow-up turn dispatched by a plan
|
|
@@ -188,13 +189,19 @@ interface DurableChatCardsProps {
|
|
|
188
189
|
planError?: (plan: ChatPlan) => string | null;
|
|
189
190
|
onInteractionResolved?: (id: string, status: Exclude<ChatInteraction['status'], 'pending'>, answers?: InteractionAnswers) => void;
|
|
190
191
|
onLateAnswer?: (message: string) => boolean | void | Promise<boolean | void>;
|
|
192
|
+
/** Fired when the user asks the agent to re-submit an expired/withdrawn
|
|
193
|
+
* plan card as a new chat turn; receives that card's interaction. Omit to
|
|
194
|
+
* hide the affordance entirely. */
|
|
195
|
+
onReRequest?: (interaction: ChatInteraction) => boolean | void | Promise<boolean | void>;
|
|
196
|
+
/** Overrides the default re-request button label. */
|
|
197
|
+
reRequestLabel?: string;
|
|
191
198
|
renderMarkdown?: (markdown: string) => ReactNode;
|
|
192
199
|
className?: string;
|
|
193
200
|
}
|
|
194
201
|
/** Ready-to-embed canonical question/plan card lane for persisted assistant
|
|
195
202
|
* parts. Apps inject transport and styling callbacks instead of rebuilding the
|
|
196
203
|
* lifecycle/render switch. */
|
|
197
|
-
declare function DurableChatCards({ parts, canWrite, submitInteraction, decidePlan, decidingPlan, planError, onInteractionResolved, onLateAnswer, renderMarkdown, className, }: DurableChatCardsProps): react.JSX.Element | null;
|
|
204
|
+
declare function DurableChatCards({ parts, canWrite, submitInteraction, decidePlan, decidingPlan, planError, onInteractionResolved, onLateAnswer, onReRequest, reRequestLabel, renderMarkdown, className, }: DurableChatCardsProps): react.JSX.Element | null;
|
|
198
205
|
|
|
199
206
|
/**
|
|
200
207
|
* Client-side chat-stream consumption — the NDJSON parse loop every agent
|
|
@@ -409,11 +416,20 @@ interface InteractionPlanCardProps {
|
|
|
409
416
|
/** Fired when this card resolves locally (approved/rejected, or discovered
|
|
410
417
|
* expired via a 410) so the stream/route state stays in sync. */
|
|
411
418
|
onResolved?: (id: string, status: Exclude<ChatInteractionStatus, 'pending'>) => void;
|
|
419
|
+
/** Fired when the user asks the agent to re-submit an expired/withdrawn plan
|
|
420
|
+
* as a new chat turn. Receives the interaction so a callback shared across
|
|
421
|
+
* cards (e.g. via DurableChatCards) knows which plan fired. Return/resolve
|
|
422
|
+
* `false` (or throw) to report the send failed and keep the affordance
|
|
423
|
+
* retryable. Omit to hide it entirely. */
|
|
424
|
+
onReRequest?: (interaction: ChatInteraction) => boolean | void | Promise<boolean | void>;
|
|
425
|
+
/** Overrides the default re-request button label
|
|
426
|
+
* ("Ask agent to re-submit the plan" — gtm's exact current copy). */
|
|
427
|
+
reRequestLabel?: string;
|
|
412
428
|
/** Renders the plan body (markdown). Falls back to pre-wrapped plain text. */
|
|
413
429
|
renderMarkdown?: (markdown: string) => ReactNode;
|
|
414
430
|
className?: string;
|
|
415
431
|
}
|
|
416
|
-
declare function InteractionPlanCard({ interaction, canWrite, submitAnswer, onResolved, renderMarkdown, className, }: InteractionPlanCardProps): react.JSX.Element;
|
|
432
|
+
declare function InteractionPlanCard({ interaction, canWrite, submitAnswer, onResolved, onReRequest, reRequestLabel, renderMarkdown, className, }: InteractionPlanCardProps): react.JSX.Element;
|
|
417
433
|
|
|
418
434
|
interface DurablePlanCardProps {
|
|
419
435
|
plan: ChatPlan;
|
|
@@ -608,6 +624,53 @@ interface UseFileMentionsResult {
|
|
|
608
624
|
}
|
|
609
625
|
declare function useFileMentions(options: UseFileMentionsOptions): UseFileMentionsResult;
|
|
610
626
|
|
|
627
|
+
/**
|
|
628
|
+
* Transcript-side counterpart to the composer's `@`-mention primitive
|
|
629
|
+
* (sandbox-ui#184). The composer serializes a picked file into the message
|
|
630
|
+
* text as `@<path>`; this module is the exact inverse — it finds those tokens
|
|
631
|
+
* again in a PERSISTED message and splits the text so a renderer can draw a
|
|
632
|
+
* pill where the user typed one and leave the rest as prose.
|
|
633
|
+
*
|
|
634
|
+
* Pure and product-agnostic: no React, no fetch, no DOM. The only input beyond
|
|
635
|
+
* the text is the message's OWN mention parts, so one message can never render
|
|
636
|
+
* a pill for a path another message mentioned.
|
|
637
|
+
*
|
|
638
|
+
* `ChatMentionPart` and the runtime helpers `mentionInputToPart` /
|
|
639
|
+
* `mentionPartsFromMessageParts` are re-exported here from `../chat-store/parts`
|
|
640
|
+
* directly (not the `/chat-store` barrel), so a browser bundle gets the mention
|
|
641
|
+
* vocabulary and its converters without importing `/chat-store`, whose barrel
|
|
642
|
+
* pulls the drizzle peer.
|
|
643
|
+
*/
|
|
644
|
+
|
|
645
|
+
/** One run of a segmented message: literal prose, or a matched mention with
|
|
646
|
+
* the part that produced it. `text` for a mention segment is the token as it
|
|
647
|
+
* appears in the message (`@<path>`), so a renderer that ignores `part` still
|
|
648
|
+
* reproduces the original string exactly. */
|
|
649
|
+
interface MentionTextSegment {
|
|
650
|
+
type: 'text' | 'mention';
|
|
651
|
+
text: string;
|
|
652
|
+
part?: ChatMentionPart;
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Split a message's text into plain-text and mention segments by matching
|
|
656
|
+
* `@<path>` runs against that message's own mention parts.
|
|
657
|
+
*
|
|
658
|
+
* Only a part whose exact `@<path>` token appears in `content`, at a token
|
|
659
|
+
* boundary on both sides, counts as a match; everything else — including
|
|
660
|
+
* unrelated `@` text — passes through as plain text untouched. When two parts'
|
|
661
|
+
* tokens both match at the same position (one path a prefix of another), the
|
|
662
|
+
* LONGEST token wins, so nested-looking paths split at the right boundary.
|
|
663
|
+
*
|
|
664
|
+
* Returns the matched parts alongside the segments: a caller that also renders
|
|
665
|
+
* a fallback chip row can drop the chip for anything now shown inline and keep
|
|
666
|
+
* it only for mentions the text does not actually contain (a restored draft, a
|
|
667
|
+
* queued message whose text was edited).
|
|
668
|
+
*/
|
|
669
|
+
declare function segmentMentionContent(content: string, parts: ReadonlyArray<ChatMentionPart>): {
|
|
670
|
+
segments: MentionTextSegment[];
|
|
671
|
+
matched: Set<ChatMentionPart>;
|
|
672
|
+
};
|
|
673
|
+
|
|
611
674
|
/**
|
|
612
675
|
* Provider brand marks — real logo path data (simple-icons / SVG Logos, both
|
|
613
676
|
* CC0) inlined so the picker shows actual provider identity instead of
|
|
@@ -1043,4 +1106,4 @@ declare function useThinkingSeconds(active: boolean): number;
|
|
|
1043
1106
|
*/
|
|
1044
1107
|
declare function ChatMessages({ messages, models, renderMarkdown, renderExtras, durableCards, userLabel, agentLabel, loading, approval, onToolCallClick, toolRenderers, error, onRetry, renderEmpty, emptyState, header, }: ChatMessagesProps): react.JSX.Element;
|
|
1045
1108
|
|
|
1046
|
-
export { type ActivityTone, type AgentActivityPage, AgentActivityPanel, type AgentActivityPanelProps, type AgentActivityRecord, AgentSessionControls, type AgentSessionControlsProps, CatalogModel, ChatComposer, type ChatComposerProps, type ChatEmptyDoor, ChatEmptyState, type ChatEmptyStateProps, ChatInteraction, ChatInteractionField, type ChatInteractionRestoreMode, ChatInteractionStatus, type ChatMessageMetrics, type ChatMessageSegment, ChatMessages, type ChatMessagesProps, ChatSelectField, type ChatStreamCallbacks, type ChatStreamToolCall, type ChatStreamToolResult, type ChatToolCallInfo, type ChatUiMessage, type ComposerFile, type ComposerFilePart, type ComposerMentionProp, type ConsumeChatStreamResult, DEFAULT_EFFORT_LEVELS, DEFAULT_MENTION_EMPTY_TEXT, DEFAULT_MENTION_LIMIT, type DurableChatCard, DurableChatCards, type DurableChatCardsProps, type DurableInteractionAnswerSubmitterOptions, DurablePlanCard, type DurablePlanCardProps, DurablePlanClientError, type DurablePlanCurrentInput, type DurablePlanDecision, type DurablePlanDecisionClient, type DurablePlanDecisionClientOptions, type DurablePlanDecisionInput, type DurablePlanDecisionResult, type DurablePlanFollowUpReceipt, type EffortLevel, EffortPicker, type EffortPickerProps, type FieldValues, FileMention, FlowWaterfall, type FlowWaterfallProps, INDEX_REFRESH_AFTER_MS, INTERACTION_SUBMIT_TIMEOUT_MESSAGE, INTERACTION_SUBMIT_TIMEOUT_MS, InteractionActionButton, type InteractionAnswerSubmission, type InteractionAnswerSubmitterOptions, InteractionAnswers, type InteractionAttemptStore, InteractionBadge, type InteractionBadgeVariant, InteractionCancelData, InteractionPlanCard, type InteractionPlanCardProps, InteractionQuestionCard, type InteractionQuestionCardProps, InteractionRequestWire, type InteractionSubmitResult, type MentionItem, MissionActivityLane, type MissionActivityLaneProps, ModelPicker, type ModelPickerProps, type ProposalApprovalHandlers, ProviderLogo, type ProviderLogoProps, QuestionOptionList, type QuestionOptionListProps, type RestoreChatInteractionsOptions, RunDrillIn, type RunDrillInProps, SeatPaywall, type SeatPaywallProps, type SmoothRevealOptions, type StreamChatOptions, type SubmitInteractionAnswer, type ToolDetailRenderers, type ToolRunRecord, type ToolRunStep, type UseChatInteractionsOptions, type UseChatInteractionsResult, type UseDurablePlanFlowOptions, type UseDurablePlanFlowResult, type UseFileMentionsOptions, type UseFileMentionsResult, type WaterfallRow, activityTone, buildAnswerData, cancelChatInteraction, consumeChatStream, createDurableInteractionAnswerSubmitter, createDurablePlanDecisionClient, createInteractionAnswerSubmitter, createMemoryInteractionAttemptStore, createSessionInteractionAttemptStore, dispatchChatStreamLine, durableChatCardsFromParts, fieldAnswer, fieldValuesFromAnswers, formatActivityCost, formatActivityDuration, formatModelCost, formatTokensPerSecond, hasSecretField, hydrateChatInteractions, interactionStatusLabels, interactionSubmissionSignature, interactionTerminalNotes, isLateAnswerableStatus, lateAnswerMessage, mergeActivityPages, nextRevealCount, pendingApprovalOf, rankFileMentions, resolveChatInteraction, responseErrorMessage, restoreChatInteractions, streamChatTurn, terminalizePendingChatInteractions, upsertChatInteraction, useChatInteractions, useDurablePlanFlow, useFileMentions, usePending, usePopover, useSmoothText, useThinkingSeconds, waterfallLayout };
|
|
1109
|
+
export { type ActivityTone, type AgentActivityPage, AgentActivityPanel, type AgentActivityPanelProps, type AgentActivityRecord, AgentSessionControls, type AgentSessionControlsProps, CatalogModel, ChatComposer, type ChatComposerProps, type ChatEmptyDoor, ChatEmptyState, type ChatEmptyStateProps, ChatInteraction, ChatInteractionField, type ChatInteractionRestoreMode, ChatInteractionStatus, ChatMentionPart, type ChatMessageMetrics, type ChatMessageSegment, ChatMessages, type ChatMessagesProps, ChatSelectField, type ChatStreamCallbacks, type ChatStreamToolCall, type ChatStreamToolResult, type ChatToolCallInfo, type ChatUiMessage, type ComposerFile, type ComposerFilePart, type ComposerMentionProp, type ConsumeChatStreamResult, DEFAULT_EFFORT_LEVELS, DEFAULT_MENTION_EMPTY_TEXT, DEFAULT_MENTION_LIMIT, type DurableChatCard, DurableChatCards, type DurableChatCardsProps, type DurableInteractionAnswerSubmitterOptions, DurablePlanCard, type DurablePlanCardProps, DurablePlanClientError, type DurablePlanCurrentInput, type DurablePlanDecision, type DurablePlanDecisionClient, type DurablePlanDecisionClientOptions, type DurablePlanDecisionInput, type DurablePlanDecisionResult, type DurablePlanFollowUpReceipt, type EffortLevel, EffortPicker, type EffortPickerProps, type FieldValues, FileMention, FlowWaterfall, type FlowWaterfallProps, INDEX_REFRESH_AFTER_MS, INTERACTION_SUBMIT_TIMEOUT_MESSAGE, INTERACTION_SUBMIT_TIMEOUT_MS, InteractionActionButton, type InteractionAnswerSubmission, type InteractionAnswerSubmitterOptions, InteractionAnswers, type InteractionAttemptStore, InteractionBadge, type InteractionBadgeVariant, InteractionCancelData, InteractionPlanCard, type InteractionPlanCardProps, InteractionQuestionCard, type InteractionQuestionCardProps, InteractionRequestWire, type InteractionSubmitResult, type MentionItem, type MentionTextSegment, MissionActivityLane, type MissionActivityLaneProps, ModelPicker, type ModelPickerProps, type ProposalApprovalHandlers, ProviderLogo, type ProviderLogoProps, QuestionOptionList, type QuestionOptionListProps, type RestoreChatInteractionsOptions, RunDrillIn, type RunDrillInProps, SeatPaywall, type SeatPaywallProps, type SmoothRevealOptions, type StreamChatOptions, type SubmitInteractionAnswer, type ToolDetailRenderers, type ToolRunRecord, type ToolRunStep, type UseChatInteractionsOptions, type UseChatInteractionsResult, type UseDurablePlanFlowOptions, type UseDurablePlanFlowResult, type UseFileMentionsOptions, type UseFileMentionsResult, type WaterfallRow, activityTone, buildAnswerData, cancelChatInteraction, consumeChatStream, createDurableInteractionAnswerSubmitter, createDurablePlanDecisionClient, createInteractionAnswerSubmitter, createMemoryInteractionAttemptStore, createSessionInteractionAttemptStore, dispatchChatStreamLine, durableChatCardsFromParts, fieldAnswer, fieldValuesFromAnswers, formatActivityCost, formatActivityDuration, formatModelCost, formatTokensPerSecond, hasSecretField, hydrateChatInteractions, interactionStatusLabels, interactionSubmissionSignature, interactionTerminalNotes, isLateAnswerableStatus, lateAnswerMessage, mergeActivityPages, nextRevealCount, pendingApprovalOf, rankFileMentions, resolveChatInteraction, responseErrorMessage, restoreChatInteractions, segmentMentionContent, streamChatTurn, terminalizePendingChatInteractions, upsertChatInteraction, useChatInteractions, useDurablePlanFlow, useFileMentions, usePending, usePopover, useSmoothText, useThinkingSeconds, waterfallLayout };
|
package/dist/web-react/index.js
CHANGED
|
@@ -56,6 +56,7 @@ import {
|
|
|
56
56
|
resolveChatInteraction,
|
|
57
57
|
responseErrorMessage,
|
|
58
58
|
restoreChatInteractions,
|
|
59
|
+
segmentMentionContent,
|
|
59
60
|
streamChatTurn,
|
|
60
61
|
terminalizePendingChatInteractions,
|
|
61
62
|
upsertChatInteraction,
|
|
@@ -67,18 +68,22 @@ import {
|
|
|
67
68
|
useSmoothText,
|
|
68
69
|
useThinkingSeconds,
|
|
69
70
|
waterfallLayout
|
|
70
|
-
} from "../chunk-
|
|
71
|
+
} from "../chunk-7VMUOD3G.js";
|
|
71
72
|
import {
|
|
72
73
|
tabTerminalConnectionId,
|
|
73
74
|
useSandboxTerminalConnection
|
|
74
75
|
} from "../chunk-65P3HJY3.js";
|
|
76
|
+
import "../chunk-LCNY3DCM.js";
|
|
77
|
+
import "../chunk-2QI7XV2T.js";
|
|
75
78
|
import {
|
|
76
79
|
buildMentionPromptBlock,
|
|
77
80
|
chatTurnRequestInit,
|
|
78
81
|
fileMentionsToParts,
|
|
79
|
-
mediaTypeForMentionPath
|
|
80
|
-
|
|
81
|
-
|
|
82
|
+
mediaTypeForMentionPath,
|
|
83
|
+
mentionInputToPart,
|
|
84
|
+
mentionKindForPath,
|
|
85
|
+
mentionPartsFromMessageParts
|
|
86
|
+
} from "../chunk-6E2XJSCT.js";
|
|
82
87
|
import {
|
|
83
88
|
INTERACTION_CANCEL_EVENT,
|
|
84
89
|
INTERACTION_EVENT,
|
|
@@ -176,6 +181,9 @@ export {
|
|
|
176
181
|
isTerminalInteractionStatus,
|
|
177
182
|
lateAnswerMessage,
|
|
178
183
|
mediaTypeForMentionPath,
|
|
184
|
+
mentionInputToPart,
|
|
185
|
+
mentionKindForPath,
|
|
186
|
+
mentionPartsFromMessageParts,
|
|
179
187
|
mergeActivityPages,
|
|
180
188
|
nextRevealCount,
|
|
181
189
|
noticePart,
|
|
@@ -190,6 +198,7 @@ export {
|
|
|
190
198
|
resolveChatInteraction,
|
|
191
199
|
responseErrorMessage,
|
|
192
200
|
restoreChatInteractions,
|
|
201
|
+
segmentMentionContent,
|
|
193
202
|
stampInteractionAnswers,
|
|
194
203
|
streamChatTurn,
|
|
195
204
|
tabTerminalConnectionId,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-app",
|
|
3
|
-
"version": "0.43.
|
|
3
|
+
"version": "0.43.45",
|
|
4
4
|
"packageManager": "pnpm@10.33.4",
|
|
5
5
|
"description": "Application-shell framework for Tangle agent products: a bounded tool loop, the structured agent→app tool side channel, integration-hub client, per-workspace billing, and crypto — composed over the Tangle agent substrate through typed seams.",
|
|
6
6
|
"keywords": [
|
package/dist/chunk-2EO7CPL3.js
DELETED
|
@@ -1,191 +0,0 @@
|
|
|
1
|
-
// src/chat-routes/wire.ts
|
|
2
|
-
function chatTurnRequestInit(payload) {
|
|
3
|
-
return {
|
|
4
|
-
method: "POST",
|
|
5
|
-
headers: { "Content-Type": "application/json" },
|
|
6
|
-
body: JSON.stringify(payload)
|
|
7
|
-
};
|
|
8
|
-
}
|
|
9
|
-
var INLINE_PARTS_MAX_BYTES = 95e4;
|
|
10
|
-
var ChatTurnInputError = class extends Error {
|
|
11
|
-
constructor(message, status = 400, code = "INVALID_CHAT_TURN") {
|
|
12
|
-
super(message);
|
|
13
|
-
this.status = status;
|
|
14
|
-
this.code = code;
|
|
15
|
-
this.name = "ChatTurnInputError";
|
|
16
|
-
}
|
|
17
|
-
status;
|
|
18
|
-
code;
|
|
19
|
-
};
|
|
20
|
-
function partByteSize(part) {
|
|
21
|
-
let bytes = 0;
|
|
22
|
-
if (part.type === "text") return part.text.length;
|
|
23
|
-
if (part.url) bytes += part.url.length;
|
|
24
|
-
if (part.content) bytes += part.content.length;
|
|
25
|
-
if (part.path) bytes += part.path.length;
|
|
26
|
-
return bytes;
|
|
27
|
-
}
|
|
28
|
-
function promptPartsByteSize(parts) {
|
|
29
|
-
return parts.reduce((total, part) => total + partByteSize(part), 0);
|
|
30
|
-
}
|
|
31
|
-
function assertPromptPartsWithinCap(parts, maxBytes = INLINE_PARTS_MAX_BYTES) {
|
|
32
|
-
const total = promptPartsByteSize(parts);
|
|
33
|
-
if (total <= maxBytes) return;
|
|
34
|
-
const largest = [...parts].sort((a, b) => partByteSize(b) - partByteSize(a))[0];
|
|
35
|
-
const largestName = largest && largest.type !== "text" ? largest.filename ?? largest.path ?? largest.type : "text";
|
|
36
|
-
throw new ChatTurnInputError(
|
|
37
|
-
`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.`,
|
|
38
|
-
413,
|
|
39
|
-
"PROMPT_PARTS_TOO_LARGE"
|
|
40
|
-
);
|
|
41
|
-
}
|
|
42
|
-
var MENTION_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Map([
|
|
43
|
-
[".png", "image/png"],
|
|
44
|
-
[".jpg", "image/jpeg"],
|
|
45
|
-
[".jpeg", "image/jpeg"],
|
|
46
|
-
[".gif", "image/gif"],
|
|
47
|
-
[".webp", "image/webp"],
|
|
48
|
-
[".svg", "image/svg+xml"],
|
|
49
|
-
[".bmp", "image/bmp"],
|
|
50
|
-
[".heic", "image/heic"],
|
|
51
|
-
[".heif", "image/heif"],
|
|
52
|
-
[".avif", "image/avif"]
|
|
53
|
-
]);
|
|
54
|
-
function extensionOf(path) {
|
|
55
|
-
const base = path.split("/").filter(Boolean).pop() ?? path;
|
|
56
|
-
const dot = base.lastIndexOf(".");
|
|
57
|
-
return dot > 0 ? base.slice(dot).toLowerCase() : "";
|
|
58
|
-
}
|
|
59
|
-
function mediaTypeForMentionPath(path) {
|
|
60
|
-
return MENTION_IMAGE_MEDIA_TYPES.get(extensionOf(path));
|
|
61
|
-
}
|
|
62
|
-
function fileMentionsToParts(mentions, opts = {}) {
|
|
63
|
-
const resolvePath = opts.resolvePath ?? ((path) => path);
|
|
64
|
-
return mentions.map((mention) => {
|
|
65
|
-
const mediaType = mediaTypeForMentionPath(mention.path);
|
|
66
|
-
const part = {
|
|
67
|
-
type: mediaType ? "image" : "file",
|
|
68
|
-
filename: mention.name,
|
|
69
|
-
path: resolvePath(mention.path)
|
|
70
|
-
};
|
|
71
|
-
if (mediaType) part.mediaType = mediaType;
|
|
72
|
-
return part;
|
|
73
|
-
});
|
|
74
|
-
}
|
|
75
|
-
function buildMentionPromptBlock(mentions) {
|
|
76
|
-
if (mentions.length === 0) return "";
|
|
77
|
-
const lines = mentions.map((m) => `- ${m.name} (${m.path})`);
|
|
78
|
-
return `
|
|
79
|
-
|
|
80
|
-
Mentioned files \u2014 read them from these paths:
|
|
81
|
-
${lines.join("\n")}`;
|
|
82
|
-
}
|
|
83
|
-
function parseChatTurnParts(raw) {
|
|
84
|
-
if (raw === void 0 || raw === null) return [];
|
|
85
|
-
if (!Array.isArray(raw)) throw new ChatTurnInputError("parts must be an array");
|
|
86
|
-
return raw.map((entry, index) => {
|
|
87
|
-
const part = entry;
|
|
88
|
-
if (!part || typeof part !== "object") {
|
|
89
|
-
throw new ChatTurnInputError(`parts[${index}] must be an object`);
|
|
90
|
-
}
|
|
91
|
-
if (part.type !== "image" && part.type !== "file") {
|
|
92
|
-
throw new ChatTurnInputError(`parts[${index}].type must be 'image' or 'file'`);
|
|
93
|
-
}
|
|
94
|
-
for (const key of ["filename", "mediaType", "url", "path", "content"]) {
|
|
95
|
-
if (part[key] !== void 0 && typeof part[key] !== "string") {
|
|
96
|
-
throw new ChatTurnInputError(`parts[${index}].${key} must be a string`);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
if (!part.url && !part.path && !part.content) {
|
|
100
|
-
throw new ChatTurnInputError(`parts[${index}] needs a url, path, or content`);
|
|
101
|
-
}
|
|
102
|
-
return {
|
|
103
|
-
type: part.type,
|
|
104
|
-
...part.filename !== void 0 ? { filename: part.filename } : {},
|
|
105
|
-
...part.mediaType !== void 0 ? { mediaType: part.mediaType } : {},
|
|
106
|
-
...part.url !== void 0 ? { url: part.url } : {},
|
|
107
|
-
...part.path !== void 0 ? { path: part.path } : {},
|
|
108
|
-
...part.content !== void 0 ? { content: part.content } : {}
|
|
109
|
-
};
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
// src/chat-routes/file-index.ts
|
|
114
|
-
var DEFAULT_IGNORE_SEGMENTS = [
|
|
115
|
-
"node_modules",
|
|
116
|
-
"dist",
|
|
117
|
-
"build",
|
|
118
|
-
"out",
|
|
119
|
-
"coverage",
|
|
120
|
-
"target",
|
|
121
|
-
"__pycache__",
|
|
122
|
-
"venv"
|
|
123
|
-
];
|
|
124
|
-
function isIgnored(relPath, ignoreSegments) {
|
|
125
|
-
for (const segment of relPath.split("/")) {
|
|
126
|
-
if (!segment) continue;
|
|
127
|
-
if (segment.startsWith(".")) return true;
|
|
128
|
-
if (ignoreSegments.has(segment)) return true;
|
|
129
|
-
}
|
|
130
|
-
return false;
|
|
131
|
-
}
|
|
132
|
-
function relativeTo(root, path) {
|
|
133
|
-
const prefix = root.endsWith("/") ? root : `${root}/`;
|
|
134
|
-
if (path.startsWith(prefix)) return path.slice(prefix.length);
|
|
135
|
-
if (path === root) return "";
|
|
136
|
-
return path;
|
|
137
|
-
}
|
|
138
|
-
function basename(path) {
|
|
139
|
-
const segments = path.split("/").filter(Boolean);
|
|
140
|
-
return segments[segments.length - 1] ?? path;
|
|
141
|
-
}
|
|
142
|
-
function createSandboxFileIndexRoute(options) {
|
|
143
|
-
const maxDepth = options.maxDepth ?? 12;
|
|
144
|
-
const maxEntries = options.maxEntries ?? 5e3;
|
|
145
|
-
const cacheTtlSeconds = options.cacheTtlSeconds ?? 20;
|
|
146
|
-
const staticIgnore = /* @__PURE__ */ new Set([...DEFAULT_IGNORE_SEGMENTS, ...options.ignore ?? []]);
|
|
147
|
-
return async function fileIndex(request) {
|
|
148
|
-
const auth = await options.authorize({ request });
|
|
149
|
-
if (auth.status === "denied") return auth.response;
|
|
150
|
-
if (auth.status === "warming") {
|
|
151
|
-
return Response.json({ status: "warming" });
|
|
152
|
-
}
|
|
153
|
-
const cache = options.cache;
|
|
154
|
-
if (cache && auth.cacheKey) {
|
|
155
|
-
const cached = await cache.get(auth.cacheKey);
|
|
156
|
-
if (cached) return Response.json(cached);
|
|
157
|
-
}
|
|
158
|
-
const ignoreSegments = auth.ignore?.length ? /* @__PURE__ */ new Set([...staticIgnore, ...auth.ignore]) : staticIgnore;
|
|
159
|
-
const scan = await auth.fs.tree(auth.root, { maxDepth });
|
|
160
|
-
const filtered = scan.files.filter((f) => !isIgnored(relativeTo(scan.root, f.path), ignoreSegments));
|
|
161
|
-
const truncated = scan.stats.truncated || filtered.length > maxEntries;
|
|
162
|
-
const files = filtered.slice(0, maxEntries).map((f) => {
|
|
163
|
-
const path = relativeTo(scan.root, f.path);
|
|
164
|
-
const entry = { path, name: basename(path) };
|
|
165
|
-
if (typeof f.size === "number") entry.size = f.size;
|
|
166
|
-
return entry;
|
|
167
|
-
});
|
|
168
|
-
const body = {
|
|
169
|
-
status: "ready",
|
|
170
|
-
files,
|
|
171
|
-
truncated,
|
|
172
|
-
generatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
173
|
-
};
|
|
174
|
-
if (cache && auth.cacheKey) await cache.put(auth.cacheKey, body, { ttlSeconds: cacheTtlSeconds });
|
|
175
|
-
return Response.json(body);
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
export {
|
|
180
|
-
chatTurnRequestInit,
|
|
181
|
-
INLINE_PARTS_MAX_BYTES,
|
|
182
|
-
ChatTurnInputError,
|
|
183
|
-
promptPartsByteSize,
|
|
184
|
-
assertPromptPartsWithinCap,
|
|
185
|
-
mediaTypeForMentionPath,
|
|
186
|
-
fileMentionsToParts,
|
|
187
|
-
buildMentionPromptBlock,
|
|
188
|
-
parseChatTurnParts,
|
|
189
|
-
createSandboxFileIndexRoute
|
|
190
|
-
};
|
|
191
|
-
//# sourceMappingURL=chunk-2EO7CPL3.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/chat-routes/wire.ts","../src/chat-routes/file-index.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 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\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/** 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 * `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\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. */\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\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 const scan = await auth.fs.tree(auth.root, { maxDepth })\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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