@tangle-network/agent-app 4.0.36 → 4.0.38

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.
Files changed (53) hide show
  1. package/dist/assistant/index.js +5 -5
  2. package/dist/chat-react/index.js +3 -3
  3. package/dist/chat-routes/index.js +16 -8
  4. package/dist/chat-routes/index.js.map +1 -1
  5. package/dist/chat-routes/turn-event-stream.d.ts +10 -1
  6. package/dist/chat-routes/turn-execution.d.ts +34 -3
  7. package/dist/chat-routes/turn-intent.d.ts +5 -0
  8. package/dist/chat-routes/turn-progress.d.ts +25 -1
  9. package/dist/chat-routes/turn-route-contracts.d.ts +31 -2
  10. package/dist/chat-routes/turn-settlement.d.ts +23 -0
  11. package/dist/chat-store/index.js +2 -2
  12. package/dist/{chunk-NAMSFODC.js → chunk-4YBNKXUE.js} +54 -4
  13. package/dist/chunk-4YBNKXUE.js.map +1 -0
  14. package/dist/{chunk-K2JPSXKI.js → chunk-6YLVFV3F.js} +39 -3
  15. package/dist/chunk-6YLVFV3F.js.map +1 -0
  16. package/dist/{chunk-23YED7HQ.js → chunk-77UNTK66.js} +355 -288
  17. package/dist/chunk-77UNTK66.js.map +1 -0
  18. package/dist/{chunk-KPCNNFBO.js → chunk-AOSQ5JCO.js} +41 -2
  19. package/dist/{chunk-KPCNNFBO.js.map → chunk-AOSQ5JCO.js.map} +1 -1
  20. package/dist/{chunk-GOKFD7ZZ.js → chunk-BMRKOPL6.js} +2 -2
  21. package/dist/{chunk-7VJCMEEE.js → chunk-DPD7LY3T.js} +11 -6
  22. package/dist/chunk-DPD7LY3T.js.map +1 -0
  23. package/dist/{chunk-MQCAO5VW.js → chunk-MGW25KMR.js} +3 -3
  24. package/dist/{chunk-IAK227OO.js → chunk-Q7NELHRU.js} +2 -2
  25. package/dist/{chunk-4YZKDWMB.js → chunk-SADNHPAY.js} +2 -2
  26. package/dist/{chunk-E633CJFH.js → chunk-WAOZF4EL.js} +14 -9
  27. package/dist/chunk-WAOZF4EL.js.map +1 -0
  28. package/dist/operator/index.js +2 -2
  29. package/dist/preset-cloudflare/index.js +5 -5
  30. package/dist/public-consultation/index.d.ts +1 -1
  31. package/dist/public-consultation/index.js +6 -6
  32. package/dist/sandbox/index.js +3 -3
  33. package/dist/turn-stream/cancellation.d.ts +16 -0
  34. package/dist/turn-stream/core.d.ts +4 -0
  35. package/dist/turn-stream/do.d.ts +4 -2
  36. package/dist/turn-stream/hosted-turn.d.ts +20 -0
  37. package/dist/turn-stream/index.js +122 -5
  38. package/dist/turn-stream/index.js.map +1 -1
  39. package/dist/web-react/chat-composer-types.d.ts +10 -6
  40. package/dist/web-react/chat-composer.d.ts +3 -2
  41. package/dist/web-react/chat-stream.d.ts +4 -2
  42. package/dist/web-react/index.js +13 -5
  43. package/dist/web-react/use-composer-send.d.ts +3 -3
  44. package/package.json +1 -1
  45. package/dist/chunk-23YED7HQ.js.map +0 -1
  46. package/dist/chunk-7VJCMEEE.js.map +0 -1
  47. package/dist/chunk-E633CJFH.js.map +0 -1
  48. package/dist/chunk-K2JPSXKI.js.map +0 -1
  49. package/dist/chunk-NAMSFODC.js.map +0 -1
  50. /package/dist/{chunk-GOKFD7ZZ.js.map → chunk-BMRKOPL6.js.map} +0 -0
  51. /package/dist/{chunk-MQCAO5VW.js.map → chunk-MGW25KMR.js.map} +0 -0
  52. /package/dist/{chunk-IAK227OO.js.map → chunk-Q7NELHRU.js.map} +0 -0
  53. /package/dist/{chunk-4YZKDWMB.js.map → chunk-SADNHPAY.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/web-react/use-dictation.ts","../src/web-react/lazy-load-boundary.tsx","../src/web-react/chat-composer.tsx","../src/web-react/use-composer-commands.ts","../src/web-react/use-composer-file-intake.ts","../src/web-react/use-composer-send.ts","../src/web-react/composer-glyphs.tsx","../src/web-react/use-composer-attachments.ts","../src/web-react/composer-mode-controls.tsx","../src/web-react/entry-composer.tsx"],"sourcesContent":["/**\n * `useDictation` — the capture half of composer dictation.\n *\n * Dictation splits at a clean seam: the browser owns capture (`getUserMedia` +\n * `MediaRecorder`), the host owns what the audio MEANS (transcription —\n * `sequences-react`'s Whisper provider — or a straight upload). This hook is\n * the capture half and nothing else: it asks for the mic, records, ticks whole\n * seconds while it does, and hands the assembled `Blob` to the host's\n * `onDictate`. A hook rather than composer-private code, because a host whose\n * composer is fully composed (hotkey, push-to-talk) needs the same capture\n * without re-deriving it.\n *\n * The rules the implementation exists to hold:\n *\n * - **Unsupported is a render signal, not an exception.** A browser without\n * `MediaRecorder`/`getUserMedia` gets `supported: false`, and the composer\n * renders no dead button. `start()` stays a no-op rather than throwing, so\n * a host that wired it to a hotkey cannot crash on such a browser.\n * - **The mic is released the moment recording ends.** Tracks are stopped in\n * every exit — stop, error, cancel-during-prompt, unmount. A red dot the\n * browser keeps showing after the composer says \"idle\" is the failure this\n * is written against.\n * - **A denied prompt is a message, not a crash.** `NotAllowedError` and a\n * missing device are reported through `onError` as words the composer can\n * show; the hook returns to idle.\n * - **Unmount discards.** A composer that unmounts mid-recording delivers\n * nothing: the host it would have called has moved on, and an arriving\n * transcript would land in a conversation the user left.\n * - **Duration is measured, not counted.** `durationSeconds` comes off the\n * clock at stop; the one-second ticker drives only the visible elapsed\n * display, so a throttled timer never falsifies the delivered figure.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\n/** The audio a finished recording hands to the host. */\nexport interface DictationAudio {\n /** The assembled recording, typed with the MIME the recorder actually used. */\n readonly blob: Blob\n /** `blob.type`, surfaced so a host can switch on it without touching the blob. */\n readonly mimeType: string\n /** Clock-measured whole seconds between start and stop. */\n readonly durationSeconds: number\n}\n\nexport interface UseDictationOptions {\n /** The host callback: receive the recording. Transcription is the host's. */\n onDictate: (audio: DictationAudio) => void\n /** Capture failures in words (\"Microphone access was denied…\"). Optional —\n * the composer shows its own notice either way; this is for hosts that log. */\n onError?: (message: string) => void\n}\n\nexport interface DictationControls {\n /** Whether this browser can record at all. When false, render no affordance. */\n readonly supported: boolean\n readonly recording: boolean\n /** Whole seconds since the current recording started; drives the indicator. */\n readonly elapsedSeconds: number\n /** Ask for the mic and start. A no-op while a recording or a prompt is open. */\n readonly start: () => void\n /** Stop and deliver. Cancels a still-pending permission prompt instead. */\n readonly stop: () => void\n}\n\n/** Preference order: opus-in-webm first, Safari's mp4 last, UA default if none. */\nconst PREFERRED_MIME_TYPES = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4'] as const\n\n/** The mime to ask the recorder for, or `undefined` to take the UA default. */\nexport function pickDictationMimeType(): string | undefined {\n if (typeof MediaRecorder === 'undefined' || typeof MediaRecorder.isTypeSupported !== 'function') {\n return undefined\n }\n for (const type of PREFERRED_MIME_TYPES) {\n if (MediaRecorder.isTypeSupported(type)) return type\n }\n return undefined\n}\n\n/** Capture support is a property of the browser, so it is read once per mount. */\nfunction detectDictationSupport(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n typeof navigator.mediaDevices?.getUserMedia === 'function' &&\n typeof MediaRecorder !== 'undefined'\n )\n}\n\n/** The failure as a sentence. The denied prompt is the common case and the one\n * whose generic name (\"NotAllowedError\") says nothing to a reader. */\nexport function dictationErrorMessage(error: unknown): string {\n if (error instanceof DOMException) {\n if (error.name === 'NotAllowedError') return 'Microphone access was denied — allow it in the browser to dictate.'\n if (error.name === 'NotFoundError') return 'No microphone found on this device.'\n }\n return 'Could not start recording.'\n}\n\n/** `0:00`, `0:09`, `1:05`, `60:00` — minutes unbounded, seconds always two digits. */\nexport function formatDictationElapsed(totalSeconds: number): string {\n const safe = Number.isFinite(totalSeconds) && totalSeconds > 0 ? Math.floor(totalSeconds) : 0\n const minutes = Math.floor(safe / 60)\n const seconds = safe % 60\n return `${minutes}:${String(seconds).padStart(2, '0')}`\n}\n\n/** One capture's mutable internals, kept in a ref: they move with recorder\n * events, not with renders. */\ninterface DictationSession {\n readonly stream: MediaStream\n readonly recorder: MediaRecorder\n readonly chunks: Blob[]\n readonly mimeType: string\n readonly startedAt: number\n /** Set when the capture must deliver nothing (unmount, recorder failure). */\n cancelled: boolean\n}\n\n/** Release the mic. Idempotent — every exit path ends here. */\nfunction releaseStream(stream: MediaStream): void {\n for (const track of stream.getTracks()) track.stop()\n}\n\nexport function useDictation({ onDictate, onError }: UseDictationOptions): DictationControls {\n const [supported] = useState(detectDictationSupport)\n const [recording, setRecording] = useState(false)\n const [elapsedSeconds, setElapsedSeconds] = useState(0)\n\n const sessionRef = useRef<DictationSession | null>(null)\n /** Cancels a start whose getUserMedia has not resolved yet. */\n const cancelPendingStartRef = useRef<(() => void) | null>(null)\n // The recorder's event handlers fire outside React's render, so they read the\n // LATEST callbacks — a re-rendered host must not have its audio delivered to\n // the props the recording started with.\n const callbacksRef = useRef({ onDictate, onError })\n callbacksRef.current = { onDictate, onError }\n\n // The visible elapsed ticker. Follows `recording`; reset on each start so a\n // reused composer never opens at the previous capture's stale count.\n useEffect(() => {\n if (!recording) return\n setElapsedSeconds(0)\n const id = setInterval(() => setElapsedSeconds((s) => s + 1), 1000)\n return () => clearInterval(id)\n }, [recording])\n\n /** End the session: release the mic, reset state. Delivery is onstop's job. */\n const teardown = useCallback((cancelled: boolean) => {\n const session = sessionRef.current\n if (session === null) return\n session.cancelled = session.cancelled || cancelled\n sessionRef.current = null\n releaseStream(session.stream)\n setRecording(false)\n }, [])\n\n const stop = useCallback(() => {\n // A stop while the permission prompt is still open cancels the start: when\n // the stream arrives it is released unused, and nothing ever records.\n cancelPendingStartRef.current?.()\n cancelPendingStartRef.current = null\n const session = sessionRef.current\n if (session === null || session.cancelled) return\n // stop() flushes the buffered chunk (dataavailable) and THEN fires stop —\n // the blob is assembled in onstop, so a stop mid-chunk loses nothing.\n if (session.recorder.state !== 'inactive') session.recorder.stop()\n }, [])\n\n const start = useCallback(() => {\n if (!supported) return\n if (sessionRef.current !== null || cancelPendingStartRef.current !== null) return\n\n let pendingCancelled = false\n cancelPendingStartRef.current = () => {\n pendingCancelled = true\n }\n\n navigator.mediaDevices.getUserMedia({ audio: true }).then(\n (stream) => {\n cancelPendingStartRef.current = null\n if (pendingCancelled) {\n releaseStream(stream)\n return\n }\n const mimeType = pickDictationMimeType()\n const recorder = new MediaRecorder(stream, mimeType === undefined ? undefined : { mimeType })\n const session: DictationSession = {\n stream,\n recorder,\n chunks: [],\n mimeType: recorder.mimeType || mimeType || '',\n startedAt: Date.now(),\n cancelled: false,\n }\n sessionRef.current = session\n\n recorder.ondataavailable = (event) => {\n if (event.data.size > 0) session.chunks.push(event.data)\n }\n\n recorder.onstop = () => {\n teardown(session.cancelled)\n if (session.cancelled) return\n const blob = new Blob(session.chunks, { type: session.mimeType })\n if (blob.size === 0) {\n // A tap on/off can produce no bytes at all. Handing the host a\n // 0-byte blob reads as a recording that happened; it did not.\n callbacksRef.current.onError?.('Nothing was recorded.')\n return\n }\n const durationSeconds = Math.max(0, Math.round((Date.now() - session.startedAt) / 1000))\n callbacksRef.current.onDictate({ blob, mimeType: session.mimeType, durationSeconds })\n }\n\n recorder.onerror = () => {\n // The capture is dead; what matters is that the mic is released and\n // the hook is not wedged — the next start builds a fresh session.\n teardown(true)\n callbacksRef.current.onError?.('Recording stopped unexpectedly.')\n }\n\n recorder.start()\n setRecording(true)\n },\n (error: unknown) => {\n cancelPendingStartRef.current = null\n if (pendingCancelled) return\n callbacksRef.current.onError?.(dictationErrorMessage(error))\n },\n )\n }, [supported, teardown])\n\n // Unmount mid-recording discards the capture: mark it cancelled so onstop\n // delivers nothing, then stop the recorder to flush its events, and release\n // the mic whether or not those events ever fire.\n useEffect(\n () => () => {\n cancelPendingStartRef.current?.()\n cancelPendingStartRef.current = null\n const session = sessionRef.current\n if (session === null) return\n session.cancelled = true\n sessionRef.current = null\n try {\n if (session.recorder.state !== 'inactive') session.recorder.stop()\n } finally {\n releaseStream(session.stream)\n }\n },\n [],\n )\n\n return { supported, recording, elapsedSeconds, start, stop }\n}\n","import { Component, createElement, lazy, useEffect, useState, type ComponentType, type ReactElement, type ReactNode } from 'react'\n\ninterface LazyLoadBoundaryProps {\n children: ReactNode\n renderFailure: (error: unknown) => ReactNode\n}\n\n/** Keep a failed lazy import inside the surface that requested it. */\nexport class LazyLoadBoundary extends Component<LazyLoadBoundaryProps, { failed: boolean; error: unknown }> {\n state = { failed: false, error: null as unknown }\n\n static getDerivedStateFromError(error: unknown) {\n return { failed: true, error }\n }\n\n render() {\n if (this.state.failed) return this.props.renderFailure(this.state.error)\n return this.props.children\n }\n}\n\nconst ROUTE_RELOAD_KEY = 'agent-app:route-chunk-reload-at'\nconst ROUTE_RELOAD_WINDOW_MS = 60_000\nconst ROUTE_RELOAD_PARAM = '__agent_app_route_reload'\nconst CHUNK_LOAD_FAILURE =\n /failed to fetch dynamically imported module|error loading dynamically imported module|importing a module script failed|loading chunk .* failed|failed to load module script/i\n\n/** A stale deployed HTML page can reference a chunk removed by the next deploy. */\nfunction isChunkLoadFailure(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false\n const candidate = error as { name?: unknown; message?: unknown }\n return candidate.name === 'ChunkLoadError' ||\n (typeof candidate.message === 'string' && CHUNK_LOAD_FAILURE.test(candidate.message))\n}\n\nfunction loadFreshDocument(): void {\n const url = new URL(window.location.href)\n url.searchParams.set(ROUTE_RELOAD_PARAM, Date.now().toString(36))\n window.location.replace(url.toString())\n}\n\nfunction RouteLoadFailure({ error, autoReloadOnChunkError }: { error: unknown; autoReloadOnChunkError: boolean }) {\n useEffect(() => {\n if (!autoReloadOnChunkError || !isChunkLoadFailure(error) || typeof window === 'undefined') return\n try {\n const lastReload = Number(window.sessionStorage.getItem(ROUTE_RELOAD_KEY) ?? 0)\n const elapsed = Date.now() - lastReload\n if (lastReload > 0 && elapsed >= 0 && elapsed < ROUTE_RELOAD_WINDOW_MS) return\n window.sessionStorage.setItem(ROUTE_RELOAD_KEY, String(Date.now()))\n loadFreshDocument()\n } catch {\n // Storage may be disabled. The visible reload action remains available.\n }\n }, [error, autoReloadOnChunkError])\n\n return (\n <div role=\"alert\" className=\"rounded-xl border border-border bg-card p-5 text-foreground\">\n <p className=\"font-medium\">This page couldn’t load.</p>\n <p className=\"mt-1 text-sm text-muted-foreground\">Reload to try again.</p>\n <button\n type=\"button\"\n className=\"mt-4 rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n onClick={loadFreshDocument}\n >\n Reload page\n </button>\n </div>\n )\n}\n\nexport interface RouteChunkBoundaryProps {\n children: ReactNode\n /** Enable only where a reload cannot discard unsaved work. Default: false. */\n autoReloadOnChunkError?: boolean\n}\n\n/** Wrap a lazy route and its Suspense fallback; recovery requests a fresh document URL. */\nexport function RouteChunkBoundary({ children, autoReloadOnChunkError = false }: RouteChunkBoundaryProps) {\n useEffect(() => {\n const url = new URL(window.location.href)\n if (!url.searchParams.has(ROUTE_RELOAD_PARAM)) return\n url.searchParams.delete(ROUTE_RELOAD_PARAM)\n window.history.replaceState(window.history.state, '', url)\n }, [])\n return (\n <LazyLoadBoundary renderFailure={(error) => <RouteLoadFailure error={error} autoReloadOnChunkError={autoReloadOnChunkError} />}>\n {children}\n </LazyLoadBoundary>\n )\n}\n\n/**\n * A lazily loaded route that renders synchronously once its module has loaded.\n *\n * `React.lazy` calls its loader only on first render, so even an already\n * downloaded chunk suspends once, and React holds that Suspense retry for its\n * ~300 ms fallback throttle. Hospitality measured 305 ms before the first data\n * read on every first visit to a lazy route, with the chunk already cached.\n * Each mount decides once which component it renders, so a route mounted\n * before its module arrived keeps its state when it re-renders later.\n */\nexport type LazyRoute<P extends object> = ((props: P) => ReactElement) & { preload: () => Promise<void> }\n\nexport function lazyRoute<P extends object>(load: () => Promise<ComponentType<P>>): LazyRoute<P> {\n let loaded: ComponentType<P> | null = null\n let pending: Promise<ComponentType<P>> | null = null\n const start = () => (pending ??= load().then(\n (component) => (loaded = component),\n (error: unknown) => { pending = null; throw error },\n ))\n const Lazy = lazy(() => start().then((component) => ({ default: component })))\n function Route(props: P) {\n const [Ready] = useState(() => loaded)\n return Ready ? createElement(Ready, props) : createElement(Lazy as unknown as ComponentType<P>, props)\n }\n return Object.assign(Route, { preload: () => start().then(() => undefined) })\n}\n\n/** Load routes while the browser is idle (at most `timeoutMs` later), so a first visit waits only on its data. */\nexport function preloadWhenIdle(routes: ReadonlyArray<{ preload: () => Promise<void> }>, timeoutMs = 3000): () => void {\n const run = () => { for (const route of routes) void route.preload().catch(() => { /* The route's boundary reports a failed load when it renders. */ }) }\n if (typeof requestIdleCallback === 'function') {\n const handle = requestIdleCallback(run, { timeout: timeoutMs })\n return () => cancelIdleCallback(handle)\n }\n const handle = setTimeout(run, Math.min(timeoutMs, 1000))\n return () => clearTimeout(handle)\n}\n","/**\n * ChatComposer — the shared message input every agent app used to hand-roll:\n * an auto-resizing textarea (Enter sends, Shift+Enter inserts a newline), an\n * opt-in attach + drag-and-drop + clipboard-paste surface with pending-file\n * chips, an opt-in `@`-mention mode (`mention`) that swaps the textarea for a\n * lazily loaded rich input with atomic mention pills, a streaming Stop/Send\n * toggle, a slot for inline controls (model picker, reasoning effort), and a\n * Cmd/Ctrl+L focus shortcut.\n *\n * Files arrive by three routes — the picker dialog, a drop, and a paste — and\n * all three funnel through `accept` (`./composer-file-accept`) before they\n * reach `onAttach`, so a type the picker will not offer cannot get in by\n * another route. What `accept` refuses goes to `onRejectFiles` with a reason;\n * without that prop a refusal is silent, which is what the native picker also\n * does. Size and count limits stay the host's job — `useComposerAttachments`\n * owns them, because they depend on what is already staged.\n *\n * A REJECTED send never destroys the draft. The input clears optimistically —\n * the composer stays editable while a turn streams precisely so the next\n * message can be typed against a live answer, and holding the sent text in the\n * box until the server confirms would put the clear on a collision course with\n * that typing. So the clear happens immediately and the draft is held until the\n * send is known to have landed: a handler that throws, rejects, or returns\n * `{ ok: false }` puts the exact bytes back with the caret where it was, names\n * the reason, and reports `onSendFailed` so the host can restore the\n * attachments it consumed. If the user has already typed a replacement, the\n * unsent text is shown in the notice with its own Retry instead of overwriting\n * what they typed — neither draft is ever destroyed.\n *\n * Styling contract matches the rest of `web-react`: Tailwind over the shared\n * design tokens (`bg-card`, `border-border`, `text-foreground`, `bg-primary`, …)\n * and inline-SVG glyphs. It defines NO `--chat-*` / `--brand-*` custom\n * properties, so it themes correctly in any shell that provides the standard\n * tokens — the input renders on-palette instead of collapsing to unstyled\n * fallbacks when a host hasn't defined a private chat-token set.\n */\n\nimport {\n lazy,\n Suspense,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n type KeyboardEvent,\n} from 'react'\n\nimport { focusFieldWithin } from '@tangle-network/ui/utils'\n\nimport { OVERLAY_SHADOW, POPOVER_OPTION_FOCUS, PopoverSurface } from './controls'\nimport { formatDictationElapsed, useDictation, type DictationAudio } from './use-dictation'\nimport { LazyLoadBoundary } from './lazy-load-boundary'\nimport { useWorkspacePrewarmHandle } from './workspace-prewarm'\nimport { useComposerCommands } from './use-composer-commands'\nimport { useComposerFileIntake } from './use-composer-file-intake'\nimport { useComposerSend } from './use-composer-send'\nimport { SendGlyph, StopGlyph, ArrowUpGlyph, PaperclipGlyph, FolderGlyph, CloseGlyph, RetryGlyph, UploadGlyph, MicGlyph } from './composer-glyphs'\nimport type { ChatComposerProps } from './chat-composer-types'\n\n\n/**\n * The TipTap editor is a lazy chunk: only consumers that pass `mention` pull\n * the editor stack into their bundle, and only when the mention path renders.\n * The `@tiptap/*` packages behind it are OPTIONAL peers reached only\n * through `loadMentionEditor`'s dynamic imports — a bundler replaces a missing\n * one with a runtime-throwing stub, so a consumer without them still builds.\n */\nfunction createLazyMentionEditor() {\n return lazy(() => import('./mention-editor').then((m) => m.loadMentionEditor()))\n}\n\n/** The focus-shortcut hint names the platform's modifier: Cmd on Apple,\n * Ctrl everywhere else (the handler itself listens for both). SSR-safe —\n * defaults to Ctrl when there's no navigator to ask. */\nconst IS_APPLE_PLATFORM =\n typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/i.test(navigator.platform)\n\n\nexport * from './chat-composer-types'\n\nconst DEFAULT_MAX_HEIGHT = 168\n\n/** The input's own `leading-6` line box and its `py-1` padding, in pixels. The\n * `minRows` floor is computed from them so the CSS floor and the `rows`\n * attribute cannot drift apart at a row count other than the default. */\nconst LINE_HEIGHT = 24\nconst TEXTAREA_PADDING_Y = 8\n\nconst DEFAULT_SEND_FAILURE = \"Message not sent. Your draft is still here — try again.\"\nfunction useChatComposerViewState({\n onSend,\n onSendParts,\n onSendFailed,\n sendFailureMessage = DEFAULT_SEND_FAILURE,\n onCancel,\n isStreaming = false,\n disabled = false,\n sendDisabled = false,\n placeholder = 'Message the agent…',\n value,\n onValueChange,\n initialValue,\n seed,\n onSeedApplied,\n controls,\n controlsPlacement = 'inline',\n onAttach,\n onAttachFolder,\n pendingFiles = [],\n onRemoveFile,\n onRetryFile,\n accept,\n onRejectFiles,\n dropTitle = 'Drop files to add context',\n dropDescription = 'They attach to your next message.',\n contextItems = [],\n canSubmitAttachmentsOnly = false,\n attachmentsNotReadyMessage,\n canSubmitWhileBusy = false,\n autoFocus,\n minRows = 2,\n maxHeight = DEFAULT_MAX_HEIGHT,\n trailing,\n mention,\n slashCommands,\n eligibleSkills = [],\n selectedSkillId,\n onSelectedSkillChange,\n onDictate,\n onDictateError,\n\n focusShortcut = true,\n onFocusWithin,\n floating = false,\n sendLabel = 'Send',\n sendVariant = 'pill',\n sendTone = 'contrast',\n className,\n}: ChatComposerProps) {\n const shellPrewarm = useWorkspacePrewarmHandle()\n const focusWithin = onFocusWithin ?? shellPrewarm?.reassert\n const isControlled = value !== undefined\n const [internal, setInternal] = useState(initialValue ?? '')\n const text = isControlled ? value : internal\n const MentionEditor = useMemo(createLazyMentionEditor, [])\n // A send outcome arrives after the render that dispatched it, so the restore\n // decision must read the LIVE draft, not the one captured in that closure.\n const textRef = useRef(text)\n textRef.current = text\n\n const textareaRef = useRef<HTMLTextAreaElement>(null)\n // Set by the mention editor so autofocus-independent focus paths (the\n // Cmd/Ctrl+L shortcut) reach it in the rich path, where `textareaRef` stays\n // null. The editor registers `null` on unmount, so the shortcut can never\n // call into a destroyed editor.\n const richFocusRef = useRef<(() => void) | null>(null)\n // Stable identity so the mention editor's registration effect only reruns\n // when the editor instance itself changes, not on every parent render.\n const registerRichFocus = useCallback((focus: (() => void) | null) => {\n richFocusRef.current = focus\n }, [])\n const { fileInputRef, folderInputRef, dragOver, handleFileChange, handleFolderChange, handlePaste, ingestPastedFiles, handleDragEnter, handleDragLeave, handleDragOver, handleDrop } = useComposerFileIntake({ onAttach, onAttachFolder, accept, onRejectFiles, pendingFiles })\n\n const setText = useCallback(\n (next: string) => {\n if (!isControlled) setInternal(next)\n onValueChange?.(next)\n },\n [isControlled, onValueChange],\n )\n\n // Dictation: capture only. The hook reports every failure in words; the\n // composer shows them in its own dismissible notice (the same shape as a\n // rejected send) AND forwards them for hosts that log.\n const [dictateError, setDictateError] = useState<string | null>(null)\n const handleDictated = useCallback(\n (audio: DictationAudio) => {\n setDictateError(null)\n onDictate?.(audio)\n },\n [onDictate],\n )\n const handleDictateError = useCallback(\n (message: string) => {\n setDictateError(message)\n onDictateError?.(message)\n },\n [onDictateError],\n )\n const dictation = useDictation({ onDictate: handleDictated, onError: handleDictateError })\n\n // Keep the textarea height in sync with the content for BOTH typed and\n // external (controlled) value changes — one effect covers both paths. It also\n // reruns when the bounds move: `rows` is what `scrollHeight` resolves the\n // measurement against, so a changed `minRows` that did not re-measure would\n // strand the previous inline height.\n useEffect(() => {\n const el = textareaRef.current\n if (!el) return\n el.style.height = 'auto'\n el.style.height = `${Math.min(el.scrollHeight, maxHeight)}px`\n }, [text, maxHeight, minRows])\n\n // Adopt a one-shot seed. Applies only when the `seed` PROP transitions to a\n // new string (host sets it → consumed here → host clears it via\n // onSeedApplied), so an unstable callback identity re-running this effect\n // can never re-apply a still-set seed over the user's typing. Like\n // `initialValue`, the seed is honored ONLY in uncontrolled mode — a\n // controlled host drives its own `value` (which would shadow `setText`), so\n // it seeds by updating that state itself.\n const prevSeedRef = useRef<string | null>(null)\n const pendingCaretRef = useRef<string | null>(null)\n useEffect(() => {\n const prev = prevSeedRef.current\n prevSeedRef.current = seed ?? null\n if (seed == null || seed === prev || isControlled) return\n setText(seed)\n onSeedApplied?.()\n const el = textareaRef.current\n if (el && el.value === seed) {\n // The DOM already shows the seed — setText was a no-op (the user had\n // typed the exact string), so no re-render is coming and the [text]\n // effect below won't fire. Position the caret now instead of leaving a\n // stranded pendingCaretRef.\n el.focus()\n el.setSelectionRange(seed.length, seed.length)\n } else {\n // Defer caret positioning until the seeded value renders (see below).\n pendingCaretRef.current = seed\n }\n }, [seed, setText, onSeedApplied, isControlled])\n\n // Focus + caret-to-end AFTER the seeded value has rendered into the DOM —\n // setSelectionRange in the applying effect would run against the pre-render\n // value and clamp the caret to the old text's length.\n useEffect(() => {\n if (pendingCaretRef.current == null || pendingCaretRef.current !== text)\n return\n pendingCaretRef.current = null\n const el = textareaRef.current\n if (!el) return\n el.focus()\n el.setSelectionRange(text.length, text.length)\n }, [text])\n\n // A ready file counts as sendable content even without a `part`: store-backed\n // attachments (`useComposerAttachments`) carry no prompt part — their\n // references ride the turn body's `attachments` field — but a file-only\n // message must still be sendable. `canSubmitAttachmentsOnly` widens that to a\n // file of ANY status, so an in-flight upload leaves the control live and the\n // host's handler decides what to do about it.\n const sendableFiles = canSubmitAttachmentsOnly\n ? pendingFiles\n : pendingFiles.filter((f) => f.status === 'ready')\n const hasSendable = text.trim().length > 0 || sendableFiles.length > 0 || Boolean(selectedSkillId)\n // Streaming blocks a send unless the host queues turns. The button still\n // shows Stop while streaming, so `canSubmitWhileBusy` opens Enter, not a\n // second visible control.\n const sendBlockedByStream = isStreaming && !canSubmitWhileBusy\n const canSend = hasSendable && !sendBlockedByStream && !disabled && !sendDisabled\n\n const { failedSend, setFailedSend, send, retryFailedSend } = useComposerSend({ text, textRef, textareaRef, setText, pendingFiles, sendFailureMessage, sendBlockedByStream, disabled, sendDisabled, canSubmitAttachmentsOnly, onSend, onSendParts, onSendFailed, attachmentsNotReadyMessage, selectedSkillId })\n\n // Cmd/Ctrl+L focuses the composer from anywhere — the shortcut the hint\n // advertises. Scoped to when the shortcut is enabled and not disabled.\n // Depends on mention PRESENCE, not identity: hosts build the prop object\n // inline per render, and only the mode switch changes which input to focus.\n const mentionEnabled = mention != null\n useEffect(() => {\n if (!focusShortcut || disabled) return\n function onKeyDown(e: globalThis.KeyboardEvent) {\n if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'l') {\n if (mentionEnabled) {\n const focus = richFocusRef.current\n e.preventDefault()\n if (focus) focus()\n else textareaRef.current?.focus()\n } else {\n e.preventDefault()\n textareaRef.current?.focus()\n }\n }\n }\n document.addEventListener('keydown', onKeyDown)\n return () => document.removeEventListener('keydown', onKeyDown)\n }, [focusShortcut, disabled, mentionEnabled])\n\n const { cardRef, slashPanelRef, slashListId, setMentionSuggestionOpen, slashActiveIndex, slashOpen, slashFiltered, skillQuery, hasSkills, setSlashActive, pickSlash, handleSlashKeyDown } = useComposerCommands({ text, textRef, setText, mention, slashCommands, eligibleSkills, onSelectedSkillChange })\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n // Respect IME composition — Enter commits the candidate, it doesn't send.\n if (e.nativeEvent.isComposing) return\n if (handleSlashKeyDown(e)) return\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault()\n send()\n }\n }\n\n const folderChips = pendingFiles.filter((f) => f.kind === 'folder')\n const fileChips = pendingFiles.filter((f) => f.kind !== 'folder')\n // `above` is the only placement that takes controls OUT of the card, so it is\n // the only one matched exactly; everything else falls to inline. That keeps a\n // retired value (this prop used to accept `footer` for the same placement) or a\n // typo rendering the controls somewhere rather than nowhere — dropping them\n // silently is the one outcome with no recovery for the reader.\n const showAbove = controls != null && controlsPlacement === 'above'\n const showInline = controls != null && !showAbove\n\n // One floor for both input modes, so the mention editor and the textarea\n // cannot disagree about the empty-composer height.\n const inputMinHeight = minRows * LINE_HEIGHT + TEXTAREA_PADDING_Y\n // Keep one basic input for textarea mode and the rich editor's loading\n // state. A slow or hung lazy chunk must not leave a visible dead composer.\n // The controlled draft transfers into the rich editor when it loads.\n // Both render sites stay inside the card's `focusFieldWithin` indicator.\n const textareaInput = (\n <textarea\n ref={textareaRef}\n value={text}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={handleKeyDown}\n onPaste={onAttach ? handlePaste : undefined}\n placeholder={placeholder}\n disabled={disabled}\n autoFocus={autoFocus}\n rows={minRows}\n style={{ minHeight: inputMinHeight, maxHeight }}\n aria-label=\"Message input\"\n data-composer-input\n className=\"w-full resize-none bg-transparent px-1.5 py-1 text-base leading-6 text-foreground placeholder:text-muted-foreground disabled:opacity-50\"\n />\n )\n return { className, focusWithin, onAttach, handleDragEnter, handleDragLeave, handleDragOver,\n handleDrop, dragOver, dropTitle, dropDescription, showAbove, controls, dictateError,\n setDictateError, failedSend, setFailedSend, retryFailedSend, sendBlockedByStream, disabled,\n selectedSkillId, eligibleSkills, onSelectedSkillChange, contextItems, pendingFiles, folderChips,\n fileChips, onRetryFile, onRemoveFile, cardRef, floating, mention, textareaInput, MentionEditor,\n text, setText, send, placeholder, autoFocus, inputMinHeight, maxHeight, registerRichFocus,\n handleSlashKeyDown, setMentionSuggestionOpen, slashOpen, slashListId, slashFiltered,\n slashActiveIndex, ingestPastedFiles, fileInputRef, accept, handleFileChange, onAttachFolder,\n folderInputRef, handleFolderChange, showInline, trailing, onDictate, dictation, isStreaming,\n sendVariant, onCancel, canSend, sendLabel, sendTone, textareaRef, slashPanelRef, skillQuery,\n hasSkills, setSlashActive, pickSlash, focusShortcut }\n}\n\ntype ChatComposerViewState = ReturnType<typeof useChatComposerViewState>\n\nexport function ChatComposer(props: ChatComposerProps) {\n const view = useChatComposerViewState(props)\n return <ChatComposerView {...view} />\n}\n\nfunction ChatComposerView({ className, focusWithin, onAttach, handleDragEnter, handleDragLeave,\n handleDragOver, handleDrop, dragOver, dropTitle, dropDescription, showAbove, controls,\n dictateError, setDictateError, failedSend, setFailedSend, retryFailedSend, sendBlockedByStream,\n disabled, selectedSkillId, eligibleSkills, onSelectedSkillChange, contextItems, pendingFiles,\n folderChips, fileChips, onRetryFile, onRemoveFile, cardRef, floating, mention, textareaInput,\n MentionEditor, text, setText, send, placeholder, autoFocus, inputMinHeight, maxHeight,\n registerRichFocus, handleSlashKeyDown, setMentionSuggestionOpen, slashOpen, slashListId,\n slashFiltered, slashActiveIndex, ingestPastedFiles, fileInputRef, accept, handleFileChange,\n onAttachFolder, folderInputRef, handleFolderChange, showInline, trailing, onDictate, dictation,\n isStreaming, sendVariant, onCancel, canSend, sendLabel, sendTone, textareaRef, slashPanelRef,\n skillQuery, hasSkills, setSlashActive, pickSlash, focusShortcut }: ChatComposerViewState) {\n return ((\n <div\n className={`relative ${className ?? ''}`}\n onFocus={focusWithin}\n onDragEnter={onAttach ? handleDragEnter : undefined}\n onDragLeave={onAttach ? handleDragLeave : undefined}\n onDragOver={onAttach ? handleDragOver : undefined}\n onDrop={onAttach ? handleDrop : undefined}\n >\n {dragOver && (\n <div className=\"pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-2xl border-2 border-dashed border-primary/50 bg-card\">\n <div className=\"text-center\">\n <span className=\"mx-auto mb-2 flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary\">\n <UploadGlyph className=\"h-5 w-5\" />\n </span>\n <p className=\"text-sm font-semibold text-foreground\">{dropTitle}</p>\n <p className=\"mt-0.5 text-xs text-muted-foreground\">{dropDescription}</p>\n </div>\n </div>\n )}\n\n {showAbove && <div className=\"mb-1.5 flex flex-wrap items-center gap-1.5 px-1\">{controls}</div>}\n\n {dictateError && (\n <div\n role=\"alert\"\n data-testid=\"composer-dictate-error\"\n className=\"mb-2 flex items-start gap-2 rounded-xl border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive\"\n >\n <span className=\"min-w-0 flex-1\">{dictateError}</span>\n <button\n type=\"button\"\n aria-label=\"Dismiss dictation error\"\n onClick={() => setDictateError(null)}\n className=\"shrink-0 font-medium underline-offset-2 hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50\"\n >\n Dismiss\n </button>\n </div>\n )}\n\n {failedSend && (\n <div\n role=\"alert\"\n data-testid=\"composer-send-error\"\n className=\"mb-2 rounded-xl border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive\"\n >\n <div className=\"flex items-start gap-2\">\n <span className=\"min-w-0 flex-1\">{failedSend.message}</span>\n <button\n type=\"button\"\n aria-label=\"Dismiss send error\"\n onClick={() => setFailedSend(null)}\n className=\"shrink-0 font-medium underline-offset-2 hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50\"\n >\n Dismiss\n </button>\n </div>\n {/* The draft is only held here when it could NOT go back in the box —\n the user typed a replacement. Showing the bytes is what makes the\n message recoverable by hand even if Retry keeps failing. */}\n {!failedSend.restored && (\n <div className=\"mt-1.5\">\n <p\n data-testid=\"composer-unsent-draft\"\n className=\"max-h-20 overflow-y-auto whitespace-pre-wrap rounded-lg border border-destructive/30 bg-card px-2 py-1 text-foreground\"\n >\n {failedSend.text}\n </p>\n <button\n type=\"button\"\n aria-label=\"Retry sending the unsent message\"\n onClick={retryFailedSend}\n disabled={sendBlockedByStream || disabled}\n className=\"mt-1.5 font-medium underline-offset-2 hover:underline disabled:cursor-not-allowed disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50\"\n >\n Retry\n </button>\n </div>\n )}\n </div>\n )}\n\n {selectedSkillId && (\n <div aria-label=\"Selected skill\" className=\"mb-2 flex min-w-0 flex-wrap gap-1.5\">\n <span className=\"inline-flex min-w-0 max-w-full items-center gap-1.5 rounded-md border border-primary/30 bg-primary/10 px-2.5 py-1 text-xs text-primary\">\n <span className=\"min-w-0 truncate\">Skill: {eligibleSkills.find((skill) => skill.id === selectedSkillId)?.name ?? selectedSkillId}</span>\n {onSelectedSkillChange && (\n <button\n type=\"button\"\n aria-label=\"Remove selected skill\"\n onClick={() => onSelectedSkillChange(null)}\n className=\"shrink-0 rounded p-0.5 text-primary/70 transition hover:text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <CloseGlyph className=\"h-3 w-3\" />\n </button>\n )}\n </span>\n </div>\n )}\n\n {contextItems.length > 0 && (\n <div aria-label=\"Message context\" className=\"mb-2 flex min-w-0 flex-wrap gap-1.5\">\n {contextItems.map((item) => (\n <span\n key={item.id}\n className=\"inline-flex min-w-0 max-w-full items-center gap-1.5 rounded-md border border-primary/30 bg-primary/10 px-2.5 py-1 text-xs text-primary\"\n >\n {item.icon && (\n <span className=\"shrink-0\" aria-hidden>\n {item.icon}\n </span>\n )}\n <span className=\"min-w-0 truncate\">{item.label}</span>\n {item.onRemove && (\n <button\n type=\"button\"\n aria-label={`Remove context ${item.label}`}\n onClick={item.onRemove}\n className=\"shrink-0 rounded p-0.5 text-primary/70 transition hover:text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <CloseGlyph className=\"h-3 w-3\" />\n </button>\n )}\n </span>\n ))}\n </div>\n )}\n\n {pendingFiles.length > 0 && (\n <ComposerPendingFileChips folderChips={folderChips} fileChips={fileChips} onRetryFile={onRetryFile} onRemoveFile={onRemoveFile} />\n )}\n\n {/* Two rows inside one card: the message gets the full width, and every\n affordance that acts on it — attach, the controls slot, send — sits on\n its own row beneath. A single row would make the textarea share its\n line with the buttons, which is what squeezed the input and pushed the\n controls out of the card in the first place. */}\n {/* `focusFieldWithin` makes the card a field: with brand's interaction\n tokens it carries the well fill (`--well`), field border, hover glow\n and focus ring. Under a brand without the ladder, tokens.css sets\n `--well` to the card color. */}\n <ComposerInputCard cardRef={cardRef} floating={floating} mention={mention}\n textareaInput={textareaInput} MentionEditor={MentionEditor} text={text} setText={setText}\n send={send} placeholder={placeholder} disabled={disabled} autoFocus={autoFocus}\n inputMinHeight={inputMinHeight} maxHeight={maxHeight} registerRichFocus={registerRichFocus}\n handleSlashKeyDown={handleSlashKeyDown} setMentionSuggestionOpen={setMentionSuggestionOpen}\n slashOpen={slashOpen} slashListId={slashListId} slashFiltered={slashFiltered}\n slashActiveIndex={slashActiveIndex} onAttach={onAttach} ingestPastedFiles={ingestPastedFiles}\n fileInputRef={fileInputRef} accept={accept} handleFileChange={handleFileChange}\n onAttachFolder={onAttachFolder} folderInputRef={folderInputRef}\n handleFolderChange={handleFolderChange} showInline={showInline} controls={controls}\n trailing={trailing} onDictate={onDictate} dictation={dictation} isStreaming={isStreaming}\n sendVariant={sendVariant} onCancel={onCancel} canSend={canSend} sendLabel={sendLabel} sendTone={sendTone} />\n\n {/* The slash menu ports through PopoverSurface like every canonical\n popover: the composer docks inside horizontally scrolling rails, and\n an in-place panel there is a panel the host clips away. It anchors\n to the current input card and opens above. Focus never leaves the input —\n rows are mousedown-swallowed so a click can't blur it. */}\n <PopoverSurface\n open={slashOpen}\n id={slashListId}\n role=\"listbox\"\n triggerRef={mention ? cardRef : textareaRef}\n panelRef={slashPanelRef}\n className={`w-80 overflow-y-auto rounded-xl border border-card-edge bg-popover p-1 ${OVERLAY_SHADOW}`}\n >\n <div className=\"max-h-80 overflow-y-auto overscroll-contain\">\n {slashFiltered.length === 0 && (\n <div className=\"px-3 py-4 text-center text-sm text-muted-foreground\">\n {skillQuery !== undefined ? 'No matching skills' : hasSkills ? 'No matching commands or skills' : 'No matching commands'}\n </div>\n )}\n {slashFiltered.map((item, index) => (\n <button\n key={item.id}\n type=\"button\"\n role=\"option\"\n aria-selected={index === slashActiveIndex}\n id={`${slashListId}-${index}`}\n onMouseDown={(e) => e.preventDefault()}\n onMouseMove={() => setSlashActive(index)}\n onClick={() => pickSlash(item.id)}\n className={`flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-left text-sm transition ${POPOVER_OPTION_FOCUS} ${\n index === slashActiveIndex ? 'bg-accent' : 'hover:bg-accent'\n }`}\n >\n <span className=\"shrink-0 font-medium text-foreground\">{item.label}</span>\n <span className=\"truncate text-xs text-muted-foreground\">{item.description}</span>\n </button>\n ))}\n </div>\n </PopoverSurface>\n\n {focusShortcut && (\n // A touch screen has no keyboard to press the shortcut on.\n <div className=\"mt-1.5 flex justify-end px-1 [@media(pointer:coarse)]:hidden\">\n <span className=\"text-xs text-muted-foreground\">\n <kbd className=\"rounded border border-border bg-background px-1 py-0.5 text-xs\">{IS_APPLE_PLATFORM ? 'Cmd' : 'Ctrl'}</kbd>\n <kbd className=\"ml-0.5 rounded border border-border bg-background px-1 py-0.5 text-xs\">L</kbd>\n <span className=\"ml-1\">to focus</span>\n </span>\n </div>\n )}\n </div>\n ))\n}\n\nfunction ComposerPendingFileChips({ folderChips, fileChips, onRetryFile,\n onRemoveFile }: Pick<ChatComposerViewState, \"folderChips\" | \"fileChips\" | \"onRetryFile\" | \"onRemoveFile\">) {\n return (<div className=\"mb-2 flex flex-wrap gap-1.5\">\n {[...folderChips, ...fileChips].map((f) => {\n const isError = f.status === 'error'\n return (\n <span\n key={f.id}\n title={isError ? f.errorMessage : undefined}\n className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs ${\n isError\n ? 'border-destructive/40 text-destructive'\n : 'border-border bg-secondary text-foreground'\n } ${f.status === 'pending' ? 'opacity-60' : ''}`}\n >\n {/* A thumbnail identifies a pasted screenshot that the\n auto-generated name cannot. Folders never have one. */}\n {f.kind !== 'folder' && f.previewUrl ? (\n <img src={f.previewUrl} alt=\"\" className=\"h-8 w-8 shrink-0 rounded object-cover\" />\n ) : f.kind === 'folder' ? (\n <FolderGlyph className=\"h-3 w-3 shrink-0\" />\n ) : (\n <PaperclipGlyph className=\"h-3 w-3 shrink-0\" />\n )}\n <span className=\"max-w-[150px] truncate\">{f.name}</span>\n {f.fileCount !== undefined && <span className=\"text-muted-foreground\">({f.fileCount})</span>}\n {f.status === 'uploading' && (\n <span className=\"h-3 w-3 animate-spin rounded-full border-2 border-primary border-t-transparent\" />\n )}\n {isError && f.errorMessage && (\n <span className=\"max-w-[150px] truncate text-destructive/80\">{f.errorMessage}</span>\n )}\n {isError && onRetryFile && (\n <button\n type=\"button\"\n aria-label={`Retry upload ${f.name}`}\n onClick={() => onRetryFile(f.id)}\n className=\"rounded p-0.5 text-muted-foreground transition hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <RetryGlyph className=\"h-3 w-3\" />\n </button>\n )}\n {onRemoveFile && (\n <button\n type=\"button\"\n aria-label={`Remove ${f.name}`}\n onClick={() => onRemoveFile(f.id)}\n className=\"rounded p-0.5 text-muted-foreground transition hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <CloseGlyph className=\"h-3 w-3\" />\n </button>\n )}\n </span>\n )\n })}\n </div>)\n}\n\nfunction ComposerInputCard({ cardRef, floating, mention, textareaInput, MentionEditor, text,\n setText, send, placeholder, disabled, autoFocus, inputMinHeight, maxHeight, registerRichFocus,\n handleSlashKeyDown, setMentionSuggestionOpen, slashOpen, slashListId, slashFiltered,\n slashActiveIndex, onAttach, ingestPastedFiles, fileInputRef, accept, handleFileChange,\n onAttachFolder, folderInputRef, handleFolderChange, showInline, controls, trailing, onDictate,\n dictation, isStreaming, sendVariant, onCancel, canSend, sendLabel,\n sendTone }: Pick<ChatComposerViewState, \"cardRef\" | \"floating\" | \"mention\" | \"textareaInput\" | \"MentionEditor\" | \"text\" | \"setText\" | \"send\" | \"placeholder\" | \"disabled\" | \"autoFocus\" | \"inputMinHeight\" | \"maxHeight\" | \"registerRichFocus\" | \"handleSlashKeyDown\" | \"setMentionSuggestionOpen\" | \"slashOpen\" | \"slashListId\" | \"slashFiltered\" | \"slashActiveIndex\" | \"onAttach\" | \"ingestPastedFiles\" | \"fileInputRef\" | \"accept\" | \"handleFileChange\" | \"onAttachFolder\" | \"folderInputRef\" | \"handleFolderChange\" | \"showInline\" | \"controls\" | \"trailing\" | \"onDictate\" | \"dictation\" | \"isStreaming\" | \"sendVariant\" | \"onCancel\" | \"canSend\" | \"sendLabel\" | \"sendTone\">) {\n return (<div\n ref={cardRef}\n data-testid=\"composer-card\"\n className={`flex flex-col gap-1.5 rounded-2xl border bg-[var(--well,var(--color-card))] px-3 py-2.5 ${focusFieldWithin} ${\n floating ? 'shadow-raised' : ''\n }`}\n >\n {mention ? (\n // The basic textarea stays usable through download, initialization,\n // and failure.\n <LazyLoadBoundary renderFailure={() => (\n <>\n {textareaInput}\n <div\n role=\"alert\"\n className=\"rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-xs text-destructive\"\n >\n Mentions are unavailable. You can still send.\n </div>\n </>\n )}>\n <Suspense fallback={textareaInput}>\n <MentionEditor\n value={text}\n onChange={setText}\n onSubmit={send}\n placeholder={placeholder}\n disabled={disabled}\n autoFocus={autoFocus}\n minHeight={inputMinHeight}\n maxHeight={maxHeight}\n mention={mention}\n fallback={textareaInput}\n registerFocus={registerRichFocus}\n onComposerKeyDown={handleSlashKeyDown}\n onMentionMenuOpenChange={setMentionSuggestionOpen}\n slashListId={slashOpen ? slashListId : undefined}\n slashActiveId={slashFiltered[slashActiveIndex] ? `${slashListId}-${slashActiveIndex}` : undefined}\n onPasteFiles={onAttach ? ingestPastedFiles : undefined}\n />\n </Suspense>\n </LazyLoadBoundary>\n ) : (\n // The card is the field (`focusFieldWithin`: well fill, field border,\n // hover glow, focus ring), so tokens.css clears the transparent\n // input's own outline (`[data-composer-input]:focus-visible`).\n textareaInput\n )}\n\n {/* The row wraps rather than overlaps. The controls slot never shrinks\n below its widest control (`min-w-min`), so when the controls and the\n actions group cannot share one line the actions group moves to its\n own line, right-aligned, instead of being drawn over a squeezed\n control. With `min-w-0` here a single Plan chip was compressed to\n nothing at 390px and painted underneath a trailing model picker. */}\n <div className=\"flex flex-wrap items-end gap-2\">\n {onAttach && (\n <>\n <button\n type=\"button\"\n onClick={() => fileInputRef.current?.click()}\n disabled={disabled}\n aria-label=\"Attach files\"\n title=\"Attach files\"\n className=\"shrink-0 rounded-lg p-2 text-muted-foreground transition hover:bg-accent hover:text-foreground disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <PaperclipGlyph className=\"h-4 w-4\" />\n </button>\n <input ref={fileInputRef} type=\"file\" multiple className=\"hidden\" accept={accept} onChange={handleFileChange} />\n </>\n )}\n {onAttachFolder && (\n <>\n <button\n type=\"button\"\n onClick={() => folderInputRef.current?.click()}\n disabled={disabled}\n aria-label=\"Attach folder\"\n title=\"Attach folder\"\n className=\"shrink-0 rounded-lg p-2 text-muted-foreground transition hover:bg-accent hover:text-foreground disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <FolderGlyph className=\"h-4 w-4\" />\n </button>\n {/* webkitdirectory is non-standard but widely supported for folder picks. */}\n <input\n ref={folderInputRef}\n type=\"file\"\n multiple\n className=\"hidden\"\n onChange={handleFolderChange}\n {...({ webkitdirectory: '' } as Record<string, string>)}\n />\n </>\n )}\n\n {/* The controls take the row's slack and wrap onto a second line when\n a long picker set outgrows it. This slot must never establish an\n overflow box: a control owns its popover (ModelPicker, EffortPicker)\n and anchors it absolutely to itself, so a scroll/clip box here traps\n a 400px-tall list inside a ~34px row — the list renders and is never\n visible — and the scroll offset that comes with it cuts the trigger's\n own left edge. Growing a second line is the cost of controls that\n stay operable. Rendered even when empty so Send stays right-aligned. */}\n <div\n data-testid=\"composer-controls\"\n className=\"flex min-w-min flex-1 flex-wrap items-center gap-1.5\"\n >\n {showInline && controls}\n </div>\n\n {/* Trailing content is the controls slot's SIBLING, not its content:\n the slot is where a picker set is allowed to wrap, and a meter or\n a status line put inside it would be pushed onto the second line\n by the very pickers it reports on. Trailing content, dictation\n and Send travel together as one group: when the row wraps they\n move to the next line right-aligned, so Send never lands alone at\n the start of a line. The group wraps inside itself too: when a\n trailing picker and Send cannot share even their own line (a\n 320px phone), Send drops below the picker, right-aligned, instead\n of being drawn over it. */}\n <div data-testid=\"composer-actions\" className=\"ml-auto flex min-w-0 max-w-full flex-wrap items-end justify-end gap-2\">\n {trailing && (\n <div data-testid=\"composer-trailing\" className=\"flex min-w-0 flex-wrap items-center justify-end gap-1.5\">\n {trailing}\n </div>\n )}\n {/* Dictation sits beside Send: it produces input, like typing. The\n button renders only when the host takes audio AND the browser can\n record — a dead mic is worse than no mic. While recording, the\n elapsed seconds (not the pulsing dot, which reduced motion\n collapses) are the signal, and the stop control is never\n disabled: a `disabled` flip mid-capture must not strand the mic. */}\n {onDictate && dictation.supported ? (\n dictation.recording ? (\n <div className=\"flex shrink-0 items-center gap-1.5\">\n <span aria-hidden=\"true\" className=\"h-2 w-2 animate-pulse rounded-full bg-destructive\" />\n <span\n aria-hidden=\"true\"\n data-testid=\"composer-dictate-elapsed\"\n className=\"text-xs tabular-nums text-muted-foreground\"\n >\n {formatDictationElapsed(dictation.elapsedSeconds)}\n </span>\n <span role=\"status\" className=\"sr-only\">\n Recording\n </span>\n <button\n type=\"button\"\n onClick={dictation.stop}\n aria-label=\"Stop dictation\"\n title=\"Stop dictation\"\n className=\"shrink-0 rounded-lg p-2 text-destructive transition hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <StopGlyph className=\"h-4 w-4\" />\n </button>\n </div>\n ) : (\n <button\n type=\"button\"\n onClick={dictation.start}\n disabled={disabled}\n aria-label=\"Dictate message\"\n title=\"Dictate message\"\n className=\"shrink-0 rounded-lg p-2 text-muted-foreground transition hover:bg-accent hover:text-foreground disabled:opacity-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <MicGlyph className=\"h-4 w-4\" />\n </button>\n )\n ) : null}\n\n {isStreaming ? (\n sendVariant === 'icon' ? (\n <button\n type=\"button\"\n onClick={onCancel}\n aria-label=\"Stop response\"\n title=\"Stop\"\n className=\"inline-flex size-[var(--control-height-sm,2rem)] shrink-0 items-center justify-center rounded-full border border-border bg-transparent text-foreground transition hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n >\n <StopGlyph className=\"h-3 w-3\" />\n </button>\n ) : (\n <button\n type=\"button\"\n onClick={onCancel}\n aria-label=\"Stop response\"\n className=\"inline-flex h-[var(--control-height-sm,2rem)] shrink-0 items-center gap-1.5 rounded-full bg-destructive/15 px-3.5 text-sm font-medium text-destructive transition hover:bg-destructive/25 focus:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50\"\n >\n <StopGlyph className=\"h-3.5 w-3.5\" />\n <span>Stop</span>\n </button>\n )\n ) : sendVariant === 'icon' ? (\n <button\n type=\"button\"\n onClick={send}\n disabled={!canSend}\n aria-label={sendLabel}\n title={sendLabel}\n className={`inline-flex size-[var(--control-height-sm,2rem)] shrink-0 items-center justify-center rounded-full ${sendTone === 'primary' ? 'bg-primary text-primary-foreground' : 'bg-foreground text-background'} transition ${sendTone === 'primary' ? 'hover:bg-primary/90' : 'hover:opacity-90'} disabled:cursor-not-allowed disabled:opacity-40 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-card`}\n >\n <ArrowUpGlyph className=\"h-4 w-4\" />\n </button>\n ) : (\n <button\n type=\"button\"\n onClick={send}\n disabled={!canSend}\n aria-label={sendLabel}\n className=\"inline-flex h-[var(--control-height-sm,2rem)] shrink-0 items-center gap-1.5 rounded-full bg-primary px-3.5 text-sm font-medium text-primary-foreground shadow-sm transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-40 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-card\"\n >\n <SendGlyph className=\"h-3.5 w-3.5\" />\n <span>{sendLabel}</span>\n </button>\n )}\n </div>\n </div>\n </div>)\n}\n","/** Slash-command and skill selection for plain and rich composer inputs. */\nimport { useCallback, useEffect, useId, useMemo, useRef, useState, type RefObject } from 'react'\nimport { filterCommandPaletteItems, type CommandPaletteItem } from '../session-shell/index'\nimport type { ChatComposerProps } from './chat-composer-types'\n\ntype ComposerCommandsOptions = Pick<ChatComposerProps, 'mention' | 'slashCommands' | 'onSelectedSkillChange'> & {\n text: string\n textRef: RefObject<string>\n setText: (next: string) => void\n eligibleSkills: NonNullable<ChatComposerProps['eligibleSkills']>\n}\n\nexport function useComposerCommands({ text, textRef, setText, mention, slashCommands, eligibleSkills, onSelectedSkillChange }: ComposerCommandsOptions) {\n // ── '/' commands ─────────────────────────────────────────────────────────\n // General commands exist only while the WHOLE draft is one leading slash\n // token (`/`, `/mod`); `/skill <query>` also searches eligible skills. Esc\n // or an outside click dismisses for the CURRENT token only, so continued\n // typing reopens the menu instead of leaving it permanently suppressed.\n const slashPanelRef = useRef<HTMLDivElement>(null)\n const cardRef = useRef<HTMLDivElement>(null)\n const slashListId = useId()\n const [mentionSuggestionOpen, setMentionSuggestionOpen] = useState(false)\n const [slashActive, setSlashActive] = useState(0)\n const [slashDismissedFor, setSlashDismissedFor] = useState<string | null>(null)\n // General commands retain their textarea-only contract. Eligible skills\n // deliberately share the menu in both input modes; the rich input forwards\n // its keyboard events below. `/skill <query>` filters only skills.\n const hasSkills = Boolean(onSelectedSkillChange && eligibleSkills.length > 0)\n const commandToken = !mention && slashCommands?.length ? /^\\/(\\S*)$/.exec(text)?.[1] : undefined\n const skillToken = hasSkills ? /^\\/(\\S*)$/.exec(text)?.[1] : undefined\n const skillInvocation = hasSkills ? /^\\/skill(?:\\s+(.*))?$/i.exec(text) : null\n const skillQuery = skillInvocation ? (skillInvocation[1] ?? '') : undefined\n const slashToken = skillQuery ?? skillToken ?? commandToken\n const slashOpen = slashToken !== undefined && text !== slashDismissedFor && !mentionSuggestionOpen\n const slashItems = useMemo<CommandPaletteItem[]>(\n () => [\n ...(!mention ? slashCommands ?? [] : []).map((command) => ({\n id: `command:${command.name}`,\n group: 'Commands',\n label: `/${command.name}`,\n description: command.description,\n keywords: [command.name, command.description],\n })),\n ...(onSelectedSkillChange ? eligibleSkills : []).map((skill) => ({\n id: `skill:${skill.id}`,\n group: 'Skills',\n label: `/skill ${skill.name}`,\n description: skill.description,\n keywords: [skill.id, skill.name, skill.description],\n })),\n ],\n [slashCommands, mention, eligibleSkills, onSelectedSkillChange],\n )\n const slashFiltered = useMemo(\n () => {\n if (slashToken === undefined) return []\n const items = skillQuery !== undefined ? slashItems.filter((item) => item.group === 'Skills') : slashItems\n return filterCommandPaletteItems(items, slashToken)\n },\n [slashItems, slashToken, skillQuery],\n )\n const slashActiveIndex = slashFiltered.length === 0 ? 0 : Math.min(slashActive, slashFiltered.length - 1)\n\n useEffect(() => {\n setSlashActive(0)\n }, [slashToken])\n\n useEffect(() => {\n if (!slashOpen) return\n document\n .getElementById(`${slashListId}-${slashActiveIndex}`)\n ?.scrollIntoView?.({ block: 'nearest' })\n }, [slashOpen, slashActiveIndex, slashListId])\n\n useEffect(() => {\n if (!slashOpen) return\n function onMouseDown(e: MouseEvent) {\n const target = e.target as Node\n if (cardRef.current?.contains(target)) return\n if (slashPanelRef.current?.contains(target)) return\n setSlashDismissedFor(textRef.current)\n }\n document.addEventListener('mousedown', onMouseDown)\n return () => document.removeEventListener('mousedown', onMouseDown)\n }, [slashOpen])\n\n const pickSlash = useCallback(\n (id: string) => {\n // A pick consumes the current slash invocation: clear the box, then\n // report a typed skill or run the host's general command.\n setText('')\n setSlashDismissedFor(null)\n if (id.startsWith('skill:')) {\n const skill = eligibleSkills.find((item) => item.id === id.slice('skill:'.length))\n if (skill) onSelectedSkillChange?.(skill)\n } else if (id.startsWith('command:')) {\n slashCommands?.find((command) => command.name === id.slice('command:'.length))?.run()\n }\n },\n [slashCommands, eligibleSkills, onSelectedSkillChange, setText],\n )\n\n const handleSlashKeyDown = (e: Pick<globalThis.KeyboardEvent, 'key' | 'shiftKey' | 'preventDefault'>): boolean => {\n if (slashOpen) {\n if (e.key === 'ArrowDown') {\n e.preventDefault()\n if (slashFiltered.length > 0) setSlashActive((slashActiveIndex + 1) % slashFiltered.length)\n return true\n }\n if (e.key === 'ArrowUp') {\n e.preventDefault()\n if (slashFiltered.length > 0)\n setSlashActive((slashActiveIndex - 1 + slashFiltered.length) % slashFiltered.length)\n return true\n }\n if ((e.key === 'Enter' && !e.shiftKey) || e.key === 'Tab') {\n const item = slashFiltered[slashActiveIndex]\n if (item) {\n e.preventDefault()\n pickSlash(item.id)\n return true\n }\n // No command matched — fall through and let Enter send the raw text.\n }\n if (e.key === 'Escape') {\n e.preventDefault()\n setSlashDismissedFor(text)\n return true\n }\n }\n return false\n }\n\n return { cardRef, slashPanelRef, slashListId, setMentionSuggestionOpen, slashActiveIndex, slashOpen, slashFiltered, skillQuery, hasSkills, setSlashActive, pickSlash, handleSlashKeyDown }\n}\n","/** One accepted-file path for file pickers, clipboard pastes, and drops. */\nimport { useCallback, useRef, useState, type ChangeEvent, type ClipboardEvent, type DragEvent } from 'react'\nimport { filterAcceptedFiles, renamePastedImages } from './composer-file-accept'\nimport type { ChatComposerProps } from './chat-composer-types'\n\ntype ComposerFileIntakeOptions = Pick<ChatComposerProps, 'onAttach' | 'onAttachFolder' | 'accept' | 'onRejectFiles'> & {\n pendingFiles: NonNullable<ChatComposerProps['pendingFiles']>\n}\n\nexport function useComposerFileIntake({ onAttach, onAttachFolder, accept, onRejectFiles, pendingFiles }: ComposerFileIntakeOptions) {\n const fileInputRef = useRef<HTMLInputElement>(null)\n const folderInputRef = useRef<HTMLInputElement>(null)\n const [dragOver, setDragOver] = useState(false)\n const dragDepth = useRef(0)\n // Counts every clipboard image this composer has renamed, so two pastes of\n // the same bitmap do not both arrive as `image.png`.\n const pastedImageCount = useRef(0)\n\n // Every route a file can arrive by ends here: apply `accept`, report what it\n // removed, and hand `onAttach` only what passed. A batch the filter left\n // untouched is forwarded as the browser's own `FileList`; one it changed is\n // rebuilt, since `onAttach` takes a `FileList` and only a `DataTransfer` can\n // produce one.\n const deliverFiles = useCallback(\n (files: File[], original: FileList) => {\n if (!onAttach || files.length === 0) return\n const { accepted, rejected } = filterAcceptedFiles(files, accept)\n if (rejected.length > 0) onRejectFiles?.(rejected)\n if (accepted.length === 0) return\n const unchanged =\n accepted.length === original.length && accepted.every((file, i) => file === original[i])\n if (unchanged) {\n onAttach(original)\n return\n }\n const transfer = new DataTransfer()\n for (const file of accepted) transfer.items.add(file)\n onAttach(transfer.files)\n },\n [onAttach, onRejectFiles, accept],\n )\n\n const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {\n // Re-filter: a picker dialog lets the user override `accept` with\n // \"All Files\", so the attribute alone does not hold the gate.\n if (e.target.files?.length) deliverFiles(Array.from(e.target.files), e.target.files)\n e.target.value = ''\n }\n\n // One paste core for both input modes. Returns true when files were the\n // payload — the caller then suppresses the default text paste even when\n // every file is refused, so a rejection never half-pastes stray text.\n // The staged names go in alongside the count: the queue is the host's and\n // can outlive this mount, so the count alone could hand the next paste a\n // name the queue already holds.\n const ingestPastedFiles = (clipboardFiles: FileList): boolean => {\n if (!onAttach || clipboardFiles.length === 0) return false\n const { files, nextIndex } = renamePastedImages(\n Array.from(clipboardFiles),\n pastedImageCount.current,\n pendingFiles.map((f) => f.name),\n )\n pastedImageCount.current = nextIndex\n deliverFiles(files, clipboardFiles)\n return true\n }\n\n const handlePaste = (e: ClipboardEvent<HTMLTextAreaElement>) => {\n const clipboardFiles = e.clipboardData?.files\n if (!clipboardFiles || clipboardFiles.length === 0) return\n if (ingestPastedFiles(clipboardFiles)) e.preventDefault()\n }\n\n const handleFolderChange = (e: ChangeEvent<HTMLInputElement>) => {\n if (e.target.files?.length) (onAttachFolder ?? onAttach)?.(e.target.files)\n e.target.value = ''\n }\n\n const handleDragEnter = useCallback((e: DragEvent) => {\n e.preventDefault()\n e.stopPropagation()\n dragDepth.current++\n if (e.dataTransfer?.types.includes('Files')) setDragOver(true)\n }, [])\n\n const handleDragLeave = useCallback((e: DragEvent) => {\n e.preventDefault()\n e.stopPropagation()\n dragDepth.current--\n if (dragDepth.current <= 0) {\n dragDepth.current = 0\n setDragOver(false)\n }\n }, [])\n\n const handleDragOver = useCallback((e: DragEvent) => {\n e.preventDefault()\n e.stopPropagation()\n if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'\n }, [])\n\n const handleDrop = useCallback(\n (e: DragEvent) => {\n e.preventDefault()\n e.stopPropagation()\n dragDepth.current = 0\n setDragOver(false)\n const files = e.dataTransfer?.files\n if (files?.length) deliverFiles(Array.from(files), files)\n },\n [deliverFiles],\n )\n\n return { fileInputRef, folderInputRef, dragOver, handleFileChange, handleFolderChange, handlePaste, ingestPastedFiles, handleDragEnter, handleDragLeave, handleDragOver, handleDrop }\n}\n","/** Optimistic send admission, rejected-draft recovery, and explicit retry. */\nimport { useCallback, useEffect, useRef, useState, type RefObject } from 'react'\nimport type { ChatComposerProps, ComposerFilePart, ComposerSendOutcome, ComposerSendRejected, ComposerSendResult } from './chat-composer-types'\n\n/** A rejection the handler reported by value rather than by throwing. */\nfunction isRejectedOutcome(outcome: ComposerSendOutcome): outcome is ComposerSendRejected {\n return typeof outcome === 'object' && outcome !== null && outcome.ok === false\n}\n\nfunction isPromise(value: ComposerSendResult): value is Promise<ComposerSendOutcome> {\n return typeof (value as Promise<ComposerSendOutcome> | undefined)?.then === 'function'\n}\n\n/** The reason to show. A rejection's own `error` string wins; then an Error's\n * message; else the caller's copy — never an empty notice. */\nfunction sendFailureText(error: unknown, fallback: string): string {\n if (typeof error === 'object' && error !== null && 'ok' in error) {\n const named = (error as ComposerSendRejected).error\n if (typeof named === 'string' && named.trim() !== '') return named\n return fallback\n }\n if (typeof error === 'string' && error.trim() !== '') return error\n if (error instanceof Error && error.message.trim() !== '') return error.message\n return fallback\n}\n\ninterface FailedSend {\n message: string\n /** The user's exact draft, untrimmed — what a restore puts back. */\n text: string\n /** The trimmed form the handler was called with, so Retry sends the same\n * bytes the rejected attempt did. */\n trimmed: string\n parts: ComposerFilePart[]\n restored: boolean\n}\n\ntype ComposerSendOptions = Pick<ChatComposerProps, 'onSend' | 'onSendParts' | 'onSendFailed' | 'attachmentsNotReadyMessage' | 'selectedSkillId'> & {\n text: string\n textRef: { current: string }\n textareaRef: RefObject<HTMLTextAreaElement | null>\n setText: (next: string) => void\n pendingFiles: NonNullable<ChatComposerProps['pendingFiles']>\n sendFailureMessage: string\n sendBlockedByStream: boolean\n disabled: boolean\n sendDisabled: boolean\n canSubmitAttachmentsOnly: boolean\n}\n\nexport function useComposerSend({ text, textRef, textareaRef, setText, pendingFiles, sendFailureMessage, sendBlockedByStream, disabled, sendDisabled, canSubmitAttachmentsOnly, onSend, onSendParts, onSendFailed, attachmentsNotReadyMessage, selectedSkillId }: ComposerSendOptions) {\n // A restored draft gets the caret back where the user left it — same\n // post-render rule as the seed above, but to the recorded offsets rather than\n // to the end, so a failed send returns the user to the word they were on.\n const restoreCaretRef = useRef<{ text: string; start: number; end: number } | null>(null)\n useEffect(() => {\n const pending = restoreCaretRef.current\n if (!pending || pending.text !== text) return\n restoreCaretRef.current = null\n const el = textareaRef.current\n if (!el) return\n el.focus()\n const start = Math.min(pending.start, text.length)\n const end = Math.min(pending.end, text.length)\n el.setSelectionRange(start, end)\n }, [text])\n\n const [failedSend, setFailedSend] = useState<FailedSend | null>(null)\n\n // The draft comes back only when the box is still empty. If the user typed a\n // replacement while the send was in flight, overwriting it would trade one\n // lost message for another — the unsent text is held in the notice instead,\n // where Retry can send it without touching what they typed.\n const failSend = useCallback(\n (error: unknown, draft: string, trimmed: string, parts: ComposerFilePart[], caret: { start: number; end: number }) => {\n const message = sendFailureText(error, sendFailureMessage)\n const restored = textRef.current === ''\n if (restored) {\n const el = textareaRef.current\n setText(draft)\n if (el && el.value === draft) {\n // A handler that rejected SYNCHRONOUSLY did so inside the same event\n // as the clear, so React collapses clear+restore into no state change\n // at all — no re-render is coming and the effect below will never\n // fire. Place the caret now rather than stranding the pending ref.\n el.focus()\n el.setSelectionRange(Math.min(caret.start, draft.length), Math.min(caret.end, draft.length))\n } else {\n restoreCaretRef.current = { text: draft, start: caret.start, end: caret.end }\n }\n }\n setFailedSend({ message, text: draft, trimmed, parts, restored })\n onSendFailed?.({ message, text: draft, parts, error, restored })\n },\n [onSendFailed, sendFailureMessage, setText],\n )\n\n // Hand the message to the host and watch the outcome. The input has already\n // been cleared by the caller — this only decides whether it comes back.\n const dispatchSend = useCallback(\n (draft: string, trimmed: string, parts: ComposerFilePart[], caret: { start: number; end: number }) => {\n let outcome: ComposerSendResult\n try {\n outcome = onSendParts ? onSendParts(trimmed, parts) : onSend?.(trimmed)\n } catch (error) {\n failSend(error, draft, trimmed, parts, caret)\n return\n }\n if (isPromise(outcome)) {\n void outcome.then(\n (settled) => {\n if (isRejectedOutcome(settled)) failSend(settled, draft, trimmed, parts, caret)\n },\n (error: unknown) => failSend(error, draft, trimmed, parts, caret),\n )\n return\n }\n if (isRejectedOutcome(outcome)) failSend(outcome, draft, trimmed, parts, caret)\n },\n [onSend, onSendParts, failSend],\n )\n\n const send = useCallback(() => {\n const trimmed = text.trim()\n if (sendBlockedByStream || disabled || sendDisabled) return\n const readyFiles = pendingFiles.filter((f) => f.status === 'ready')\n const sendable = canSubmitAttachmentsOnly ? pendingFiles : readyFiles\n if (!trimmed && sendable.length === 0 && !selectedSkillId) return\n // `canSubmitAttachmentsOnly` keeps the control live while a file is staged,\n // but a turn carrying no text and no file the host can deliver must not go\n // out: it would arrive empty and the attachment would be lost. Refuse it\n // here and say why, rather than dispatching and trusting every host to\n // re-derive the same check.\n if (!trimmed && readyFiles.length === 0 && pendingFiles.length > 0) {\n const message =\n attachmentsNotReadyMessage ??\n (pendingFiles.some((f) => f.status === 'error')\n ? 'Retry or remove the failed attachment before sending.'\n : 'Wait for the attachment to finish uploading.')\n setFailedSend({ message, text: '', trimmed: '', parts: [], restored: true })\n return\n }\n // Only a parts-aware send carries parts; `onSend`'s files travel through the\n // host's own `pendingFiles`, so its failure payload names none. Parts come\n // from READY files whatever `canSubmitAttachmentsOnly` says — an unfinished\n // upload has no part to send.\n const parts = onSendParts\n ? readyFiles.filter((f) => f.part).map((f) => f.part as ComposerFilePart)\n : []\n const el = textareaRef.current\n const caret = { start: el?.selectionStart ?? text.length, end: el?.selectionEnd ?? text.length }\n setFailedSend(null)\n setText('')\n textRef.current = ''\n dispatchSend(text, trimmed, parts, caret)\n }, [\n text,\n sendBlockedByStream,\n disabled,\n sendDisabled,\n canSubmitAttachmentsOnly,\n attachmentsNotReadyMessage,\n onSendParts,\n pendingFiles,\n selectedSkillId,\n setText,\n dispatchSend,\n ])\n\n // Re-send the message the notice is holding. Reached only when the draft was\n // NOT restored (the restored path leaves the text in the box, where Send is\n // the affordance), so it never competes with the primary control.\n const retryFailedSend = useCallback(() => {\n const failure = failedSend\n if (!failure || sendBlockedByStream || disabled || sendDisabled) return\n setFailedSend(null)\n const caret = { start: failure.text.length, end: failure.text.length }\n dispatchSend(failure.text, failure.trimmed, failure.parts, caret)\n }, [failedSend, sendBlockedByStream, disabled, sendDisabled, dispatchSend])\n\n return { failedSend, setFailedSend, send, retryFailedSend }\n}\n","/** Inline action glyphs for the message composer. */\nexport function SendGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z\" />\n </svg>\n )\n}\n\nexport function StopGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"currentColor\" aria-hidden>\n <rect x=\"6\" y=\"6\" width=\"12\" height=\"12\" rx=\"2\" />\n </svg>\n )\n}\n\nexport function ArrowUpGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M12 19V5M5 12l7-7 7 7\" />\n </svg>\n )\n}\n\nexport function PaperclipGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48\" />\n </svg>\n )\n}\n\nexport function FolderGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z\" />\n <path d=\"M12 10v6m-3-3h6\" />\n </svg>\n )\n}\n\nexport function CloseGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" aria-hidden>\n <path d=\"M18 6 6 18M6 6l12 12\" />\n </svg>\n )\n}\n\nexport function RetryGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\" />\n <path d=\"M3 3v5h5\" />\n </svg>\n )\n}\n\nexport function UploadGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12\" />\n </svg>\n )\n}\n\nexport function MicGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <rect x=\"9\" y=\"2\" width=\"6\" height=\"12\" rx=\"3\" />\n <path d=\"M5 10v1a7 7 0 0 0 14 0v-1M12 18v4\" />\n </svg>\n )\n}\n","/**\n * `useComposerAttachments` — the composer's staged-upload lifecycle: validate\n * selected/dropped/pasted files against the shared limits (the SAME\n * `sniffBinary`/`checkAttachmentType`/size-cap vocabulary the store-backed\n * upload route enforces server-side, `../chat-routes/attachment-validation`\n * + `../chat-routes/binary-sniff`), upload each accepted file with one POST\n * request per file (so a single failure never poisons the batch), and track\n * every file's status so a host composer can render chips and gate sending.\n *\n * Ported from gtm-agent's `src/components/composer-attachments.tsx`\n * (gtm#584/#592/#593 hardened the sniff gate and batch semantics this leans\n * on), de-gtm-ified:\n * - the hardcoded `/api/vault/upload?workspaceId=` URL becomes\n * `uploadUrl`/`buildUploadRequest` (the latter wins — it hands back both\n * the URL and a `RequestInit` override, e.g. an auth header);\n * - `sonner` toasts become `onReject` (client pre-validation, never hits the\n * network) and `onError` (a request that reached the server and failed);\n * - the `accept`-string gate comes from `./composer-file-accept`, the one\n * matcher `ChatComposer` also funnels its picker/drop/paste ingress\n * through, so both ends of the staging path admit the same files;\n * - the response is expected to be `{ files: ChatAttachmentInput[] }` (full\n * server-authoritative descriptors — size/mediaType/kind — not gtm's\n * `{path, name}`), so `references` is a verbatim pass-through with no\n * client recompute;\n * - `workspaceId`'s truthiness gate becomes `enabled` (default `true`).\n *\n * Import-free beyond React + the browser-safe `/chat-routes` validation core:\n * this module ships through `/web-react` into client bundles\n * (`tests/browser-safe-subpaths.test.ts` walks the graph), so nothing here\n * may reach a Node builtin, `sandbox-ui`, or an engine package.\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { ChatAttachmentInput, ChatAttachmentKind } from './chat-stream'\nimport type { ComposerFile } from './chat-composer'\nimport { acceptRejectionReason, isAcceptedFileType } from './composer-file-accept'\nimport {\n ALLOWED_ATTACHMENT_SNIFFED_MIMES,\n ATTACHMENT_ACCEPT,\n ATTACHMENT_MAX_COUNT,\n MAX_ATTACHMENT_TOTAL_BYTES,\n MAX_BINARY_ATTACHMENT_BYTES,\n MAX_TEXT_ATTACHMENT_BYTES,\n attachmentSizeErrorMessage,\n attachmentTotalSizeErrorMessage,\n checkAttachmentType,\n sanitizeAttachmentFileName,\n} from '../chat-routes/attachment-validation'\nimport { sniffBinary } from '../chat-routes/binary-sniff'\n\n// The gate's defaults, so a host widening its composer gate starts from the\n// route's own values instead of a copy.\nexport {\n ALLOWED_ATTACHMENT_SNIFFED_MIMES,\n ATTACHMENT_ACCEPT,\n OOXML_SNIFFED_MIMES,\n} from '../chat-routes/attachment-validation'\n\n/** One staged file and its upload lifecycle. `file` is retained so a failed\n * upload can be retried without re-selecting; `previewUrl` is an object URL\n * for image thumbnails and must be revoked when the entry leaves the queue.\n * `reference` is the server's authoritative descriptor once the upload\n * lands — stored verbatim, never recomputed client-side. */\ninterface StagedAttachment {\n id: string\n file: File\n name: string\n size: number\n status: 'pending' | 'uploading' | 'ready' | 'error'\n reference?: ChatAttachmentInput\n previewUrl?: string\n errorMessage?: string\n}\n\n/** Define options for configuring file upload behavior and handling in a composer component */\nexport interface UseComposerAttachmentsOptions {\n /** Simple upload target: every file POSTs here. Ignored when\n * `buildUploadRequest` is provided. */\n uploadUrl?: string\n /** Full request-building seam (auth headers, per-file routing, …) — wins\n * over `uploadUrl` when both are set. */\n buildUploadRequest?: (args: { file: File; name: string; form: FormData }) => {\n url: string\n init?: Omit<RequestInit, 'body' | 'signal'>\n }\n /** Client pre-validation rejections — a file that never reaches the\n * network (bad type, over a size cap, over count, disallowed kind). */\n onReject?: (reason: string, file?: File) => void\n /** A file that reached the upload endpoint and failed (HTTP error,\n * transport error, malformed response). */\n onError?: (reason: string) => void\n limits?: {\n maxCount?: number\n maxBinaryBytes?: number\n /** Binary ceilings keyed by the content-sniffed mime, as the upload\n * route's `limits.maxBytesBySniffedMime`. */\n maxBytesBySniffedMime?: ReadonlyMap<string, number>\n maxTextBytes?: number\n maxTotalBytes?: number\n }\n /** Sniffed-mime allowlist, as the upload route's `allowedSniffedMimes`.\n * Default {@link ALLOWED_ATTACHMENT_SNIFFED_MIMES}. */\n allowedSniffedMimes?: ReadonlySet<string>\n /** How each file travels. `'form'` (default) posts multipart form data.\n * `'raw'` posts the file itself as the body, named by a `filename`\n * query parameter with its size in `X-Upload-Length`, which\n * `createAttachmentUploadRoute` streams to the store without holding the\n * file whole. */\n uploadBody?: 'form' | 'raw'\n /** Attachment kinds accepted, checked against the sniffed content's\n * mime. Default: both (`['image', 'file']` — i.e. no restriction). */\n allowedKinds?: ChatAttachmentKind[]\n /** `<input accept>`-style gate for the file picker/drop/paste path.\n * Default {@link ATTACHMENT_ACCEPT}. */\n accept?: string\n /** When `false`, `addFiles` rejects every call via `onReject` (and\n * `blockReason` explains why) instead of staging anything — the\n * replacement for gtm's `workspaceId`-truthiness gate (e.g. no workspace\n * loaded yet). Default `true`. */\n enabled?: boolean\n}\n\n/** Provide staged file chips, ready attachments, and methods to add, retry, or drop composer files */\nexport interface UseComposerAttachmentsResult {\n /** Chip models for `ChatComposer`'s `pendingFiles` prop, one per staged\n * file — `kind` is always `'file'` (agent-app's `ComposerFile.kind`\n * discriminates file-vs-folder chips, not attachment media type). */\n composerFiles: ComposerFile[]\n /** Ready-to-send attachment descriptors — only files whose upload\n * succeeded, straight from the server's response (no recompute). Feed\n * this into `ChatTurnRequestPayload.attachments`. */\n references: ChatAttachmentInput[]\n /** Validate + stage + upload the given files, one request per file. */\n addFiles: (files: File[] | FileList) => Promise<void>\n /** Re-upload a failed entry using its retained `File`. */\n retry: (id: string) => void\n /** Drop one staged entry, aborting its upload and revoking its preview. */\n removeAttachment: (id: string) => void\n /** Forget every staged entry (call after a successful send). */\n clear: () => void\n /** True while any file is still pending or uploading. */\n hasPending: boolean\n /** True while any file failed to upload. */\n hasError: boolean\n /** Why a send is blocked, or `null` when the queue is clean. */\n blockReason: string | null\n}\n\nfunction newId(): string {\n const cryptoObject = globalThis.crypto\n if (typeof cryptoObject?.randomUUID === 'function') return cryptoObject.randomUUID()\n return `att-${Date.now()}-${Math.random().toString(36).slice(2)}`\n}\n\n/** Suffix a name (`report.pdf` → `report-2.pdf`) until it's unused. The\n * server writes to a name-derived store path, so identical names would\n * overwrite. The suffix stays inside the store-path charset (see\n * `sanitizeAttachmentFileName`). Ported byte-for-byte from gtm's\n * `dedupeName`. */\nfunction dedupeName(name: string, taken: Set<string>): string {\n if (!taken.has(name)) return name\n const dot = name.lastIndexOf('.')\n const base = dot > 0 ? name.slice(0, dot) : name\n const ext = dot > 0 ? name.slice(dot) : ''\n let n = 2\n let candidate = `${base}-${n}${ext}`\n while (taken.has(candidate)) {\n n += 1\n candidate = `${base}-${n}${ext}`\n }\n return candidate\n}\n\n/** `image/*` → `'image'`, everything else → `'file'`. Deliberately\n * reimplemented here (not imported from `../chat-store/parts`, which pulls\n * the drizzle-adjacent `/chat-store` barrel): this module must stay reachable\n * from a browser bundle with only the `/chat-routes` validation core as a\n * dependency. */\nfunction kindForMime(mime: string): ChatAttachmentKind {\n return mime.startsWith('image/') ? 'image' : 'file'\n}\n\n/** Pull a human-readable message out of the upload endpoint's error body.\n * Ported from gtm's `parseUploadError`: handles both `{ error: string }`\n * (size/count/access errors) and `{ error: { message } }` (the\n * `createAttachmentUploadRoute` envelope, `{error:{code,message,path?}}`). */\nasync function parseUploadError(res: Response): Promise<string> {\n const detail = await res.json().catch(() => null)\n if (detail && typeof detail === 'object' && 'error' in detail) {\n const error = (detail as { error: unknown }).error\n if (typeof error === 'string' && error) return error\n if (error && typeof error === 'object' && 'message' in error) {\n const message = (error as { message: unknown }).message\n if (typeof message === 'string' && message) return message\n }\n }\n return `Upload failed (${res.status})`\n}\n\n/** Shown when neither `uploadUrl` nor `buildUploadRequest` is configured\n * while `enabled` — a product wiring bug, not a user-facing rejection, so it\n * lands each affected entry in `error` (with `onError`) rather than blocking\n * `addFiles` outright via `onReject`: the files still stage and can be\n * retried once the product fixes its config, instead of silently vanishing. */\nconst NO_UPLOAD_TARGET_MESSAGE = 'No upload destination configured (pass uploadUrl or buildUploadRequest)'\n\n/** The upload URL with the raw upload's `filename` query parameter set. */\nfunction withFilename(url: string, name: string): string {\n const [base, hash] = url.split('#', 2) as [string, string | undefined]\n const separator = base.includes('?') ? '&' : '?'\n return `${base}${separator}filename=${encodeURIComponent(name)}${hash === undefined ? '' : `#${hash}`}`\n}\n\n/** A raw upload's headers: the host's own, plus the declared size the route\n * needs before it reads the body. */\nfunction rawUploadHeaders(init: HeadersInit | undefined, size: number): Headers {\n const headers = new Headers(init)\n headers.set('Content-Type', 'application/octet-stream')\n headers.set('X-Upload-Length', String(size))\n return headers\n}\n\n/**\n * Owns the composer's attachment lifecycle: validate selected/dropped/pasted\n * files against the shared limits, upload each accepted file to the\n * product's store (one request per file), and track every file's status so\n * the composer can render chips and gate sending.\n *\n * Failures surface loud — a rejected file calls `onReject` and is never\n * uploaded; a failed upload calls `onError` and leaves an error chip the user\n * can retry or remove. `references` only ever contains files whose upload the\n * server actually confirmed.\n */\nexport function useComposerAttachments(\n options: UseComposerAttachmentsOptions,\n): UseComposerAttachmentsResult {\n // Latest options, read from inside stable callbacks — avoids re-creating\n // `addFiles`/`upload` (and therefore breaking referential stability for\n // effects a host might hang off them) every time a caller passes a fresh\n // options object literal.\n const optionsRef = useRef(options)\n optionsRef.current = options\n\n const [staged, setStagedState] = useState<StagedAttachment[]>([])\n // Mirror of `staged` kept in lockstep so dedupe/aggregate-cap/abort read\n // current values synchronously (setState callbacks alone can't answer\n // \"what's staged right now\" mid-validation).\n const stagedRef = useRef<StagedAttachment[]>([])\n const controllersRef = useRef<Map<string, AbortController>>(new Map())\n\n // Post-unmount calls reduce to a React no-op setState; the refs they touch\n // die with the instance.\n const setStaged = useCallback(\n (updater: StagedAttachment[] | ((prev: StagedAttachment[]) => StagedAttachment[])) => {\n const next =\n typeof updater === 'function'\n ? (updater as (prev: StagedAttachment[]) => StagedAttachment[])(stagedRef.current)\n : updater\n stagedRef.current = next\n setStagedState(next)\n },\n [],\n )\n\n const upload = useCallback(\n (id: string, file: File, name: string) => uploadComposerAttachment(id, file, name, { optionsRef, setStaged, controllersRef }),\n [setStaged],\n )\n\n const addFiles = useCallback(\n async (files: File[] | FileList) => {\n const opts = optionsRef.current\n const enabled = opts.enabled ?? true\n if (!enabled) {\n opts.onReject?.('Attachments are disabled')\n return\n }\n\n const accept = opts.accept ?? ATTACHMENT_ACCEPT\n const maxCount = opts.limits?.maxCount ?? ATTACHMENT_MAX_COUNT\n const maxBinaryBytes = opts.limits?.maxBinaryBytes ?? MAX_BINARY_ATTACHMENT_BYTES\n const maxTextBytes = opts.limits?.maxTextBytes ?? MAX_TEXT_ATTACHMENT_BYTES\n const maxTotalBytes = opts.limits?.maxTotalBytes ?? MAX_ATTACHMENT_TOTAL_BYTES\n const maxBytesBySniffedMime = opts.limits?.maxBytesBySniffedMime\n const allowedSniffedMimes = opts.allowedSniffedMimes ?? ALLOWED_ATTACHMENT_SNIFFED_MIMES\n const allowedKinds = opts.allowedKinds ?? (['image', 'file'] as ChatAttachmentKind[])\n\n const list = Array.isArray(files) ? files : Array.from(files)\n\n // Pass 1: accept-list, then count cap — accept first, and the count\n // checked against what is already staged plus what this batch has taken.\n const currentCount = stagedRef.current.length\n const countAccepted: File[] = []\n for (const file of list) {\n if (!isAcceptedFileType(file, accept)) {\n opts.onReject?.(acceptRejectionReason(file, accept), file)\n continue\n }\n if (currentCount + countAccepted.length >= maxCount) {\n opts.onReject?.(`\"${file.name}\" was not added — the ${maxCount}-file limit is already reached.`, file)\n continue\n }\n countAccepted.push(file)\n }\n\n // Pass 2: real content sniff + type gate + per-kind size cap +\n // allowed-kinds gate — the SAME checks the server enforces, so a\n // rejection never differs depending on which side classified the bytes\n // first. Nothing here ever reaches the network.\n const sizeAccepted: File[] = []\n for (const file of countAccepted) {\n const bytes = new Uint8Array(await file.arrayBuffer())\n const sniff = sniffBinary(bytes)\n const typeCheck = checkAttachmentType(file.name, sniff, allowedSniffedMimes)\n if (!typeCheck.succeeded) {\n opts.onReject?.(typeCheck.message, file)\n continue\n }\n const limit = !sniff.binary\n ? maxTextBytes\n : (sniff.mime ? maxBytesBySniffedMime?.get(sniff.mime) : undefined) ?? maxBinaryBytes\n if (file.size > limit) {\n opts.onReject?.(attachmentSizeErrorMessage(file.name, file.size, limit), file)\n continue\n }\n const mediaType = sniff.mime ?? file.type ?? ''\n const kind = kindForMime(mediaType)\n if (!allowedKinds.includes(kind)) {\n opts.onReject?.(`\"${file.name}\" is a ${kind} attachment, which isn't accepted here`, file)\n continue\n }\n sizeAccepted.push(file)\n }\n\n // Pass 3: running aggregate cap across this batch + everything already\n // staged (any status) — a partial batch can still land.\n const accepted: File[] = []\n let totalBytes = stagedRef.current.reduce((total, s) => total + s.size, 0)\n for (const file of sizeAccepted) {\n const nextTotalBytes = totalBytes + file.size\n if (nextTotalBytes > maxTotalBytes) {\n opts.onReject?.(attachmentTotalSizeErrorMessage(nextTotalBytes, maxTotalBytes), file)\n continue\n }\n accepted.push(file)\n totalBytes = nextTotalBytes\n }\n if (accepted.length === 0) return\n\n // Stage under the name the server will actually store, so the chip and\n // the message's attachment references never diverge.\n const taken = new Set(stagedRef.current.map((s) => s.name))\n const entries: StagedAttachment[] = accepted.map((file) => {\n const name = dedupeName(sanitizeAttachmentFileName(file.name), taken)\n taken.add(name)\n return {\n id: newId(),\n file,\n name,\n size: file.size,\n status: 'pending',\n previewUrl: file.type.startsWith('image/') ? URL.createObjectURL(file) : undefined,\n }\n })\n setStaged((prev) => [...prev, ...entries])\n for (const entry of entries) void upload(entry.id, entry.file, entry.name)\n },\n [setStaged, upload],\n )\n\n const retry = useCallback(\n (id: string) => {\n const entry = stagedRef.current.find((s) => s.id === id)\n if (!entry) return\n void upload(entry.id, entry.file, entry.name)\n },\n [upload],\n )\n\n const removeAttachment = useCallback(\n (id: string) => {\n controllersRef.current.get(id)?.abort()\n controllersRef.current.delete(id)\n const entry = stagedRef.current.find((s) => s.id === id)\n if (entry?.previewUrl) URL.revokeObjectURL(entry.previewUrl)\n setStaged((prev) => prev.filter((s) => s.id !== id))\n },\n [setStaged],\n )\n\n const clear = useCallback(() => {\n for (const controller of controllersRef.current.values()) controller.abort()\n controllersRef.current.clear()\n for (const entry of stagedRef.current) {\n if (entry.previewUrl) URL.revokeObjectURL(entry.previewUrl)\n }\n setStaged([])\n }, [setStaged])\n\n useEffect(\n () => () => {\n for (const controller of controllersRef.current.values()) controller.abort()\n controllersRef.current.clear()\n for (const entry of stagedRef.current) {\n if (entry.previewUrl) URL.revokeObjectURL(entry.previewUrl)\n }\n },\n [],\n )\n\n // `previewUrl` and `errorMessage` travel with the chip model. This hook is\n // the only place that knows either one — it mints the object URL and holds\n // the upload's failure text — so a projection that dropped them left the\n // composer rendering a red chip with no reason on it and no thumbnail for a\n // staged image.\n const composerFiles = useMemo<ComposerFile[]>(\n () =>\n staged.map((s) => ({\n id: s.id,\n name: s.name,\n size: s.size,\n kind: 'file' as const,\n status: s.status,\n previewUrl: s.previewUrl,\n errorMessage: s.errorMessage,\n })),\n [staged],\n )\n\n const references = useMemo<ChatAttachmentInput[]>(\n () =>\n staged\n .filter((s): s is StagedAttachment & { reference: ChatAttachmentInput } => s.status === 'ready' && !!s.reference)\n .map((s) => s.reference),\n [staged],\n )\n\n const hasPending = useMemo(\n () => staged.some((s) => s.status === 'pending' || s.status === 'uploading'),\n [staged],\n )\n const hasError = useMemo(() => staged.some((s) => s.status === 'error'), [staged])\n const enabled = options.enabled ?? true\n const blockReason = !enabled\n ? 'Attachments are disabled'\n : hasPending\n ? 'Attachments are still uploading'\n : hasError\n ? 'Remove failed attachments to send'\n : null\n\n return {\n composerFiles,\n references,\n addFiles,\n retry,\n removeAttachment,\n clear,\n hasPending,\n hasError,\n blockReason,\n }\n}\n\n\nasync function uploadComposerAttachment(id: string, file: File, name: string, { optionsRef,\n setStaged, controllersRef }: { optionsRef: { current: UseComposerAttachmentsOptions };\n setStaged: (updater: StagedAttachment[] | ((prev: StagedAttachment[]) => StagedAttachment[])) => void;\n controllersRef: { current: Map<string, AbortController> } }) {\n const opts = optionsRef.current\n setStaged((prev) =>\n prev.map((s) => (s.id === id ? { ...s, status: 'uploading', errorMessage: undefined } : s)),\n )\n const controller = new AbortController()\n controllersRef.current.set(id, controller)\n const form = new FormData()\n form.append('file', file, name)\n\n const request = opts.buildUploadRequest\n ? opts.buildUploadRequest({ file, name, form })\n : opts.uploadUrl\n ? { url: opts.uploadUrl }\n : null\n\n if (!request) {\n setStaged((prev) =>\n prev.map((s) =>\n s.id === id ? { ...s, status: 'error', errorMessage: NO_UPLOAD_TARGET_MESSAGE } : s,\n ),\n )\n opts.onError?.(NO_UPLOAD_TARGET_MESSAGE)\n controllersRef.current.delete(id)\n return\n }\n\n try {\n const res = opts.uploadBody === 'raw'\n ? await fetch(withFilename(request.url, name), {\n method: 'POST',\n credentials: 'same-origin',\n ...request.init,\n headers: rawUploadHeaders(request.init?.headers, file.size),\n body: file,\n signal: controller.signal,\n })\n : await fetch(request.url, {\n method: 'POST',\n credentials: 'same-origin',\n ...request.init,\n body: form,\n signal: controller.signal,\n })\n if (!res.ok) {\n const message = await parseUploadError(res)\n setStaged((prev) =>\n prev.map((s) => (s.id === id ? { ...s, status: 'error', errorMessage: message } : s)),\n )\n opts.onError?.(message)\n return\n }\n const data = (await res.json()) as { files?: ChatAttachmentInput[] }\n const uploaded = data.files?.[0]\n if (!uploaded) {\n const message = 'Upload returned no file'\n setStaged((prev) =>\n prev.map((s) => (s.id === id ? { ...s, status: 'error', errorMessage: message } : s)),\n )\n opts.onError?.(message)\n return\n }\n setStaged((prev) =>\n prev.map((s) => (s.id === id ? { ...s, status: 'ready', reference: uploaded } : s)),\n )\n } catch (err) {\n if ((err as Error).name === 'AbortError') return // silent removal — see removeAttachment/clear\n const message =\n err instanceof Error && err.message ? err.message : 'Upload failed — check your connection'\n setStaged((prev) =>\n prev.map((s) => (s.id === id ? { ...s, status: 'error', errorMessage: message } : s)),\n )\n opts.onError?.(message)\n } finally {\n controllersRef.current.delete(id)\n }\n }\n","import { joinClasses } from './class-names'\n\n/**\n * The plan-mode toggle state an entry surface docks beside the composer. The\n * agent-identity pickers (model / harness / effort) speak the canonical\n * `AgentSessionControls` vocabulary — see \"UI chrome ownership (picker\n * canon)\" in AGENTS.md.\n */\nexport interface ComposerPlanModeSelection {\n enabled: boolean\n setEnabled: (next: boolean) => void\n saving?: boolean\n}\n\nexport interface ComposerModeControlsProps {\n /**\n * Plan-approval mode. Products pass it only when the selected backend can\n * propose a plan and wait for approval; omitted means nothing renders.\n */\n planMode?: ComposerPlanModeSelection\n}\n\n/** Checklist glyph, inline like every `/web-react` glyph — an icon-library\n * import here would turn that optional peer into a build-time requirement\n * for every consumer of the default surface. */\nfunction ListChecksGlyph({ className }: { className?: string }) {\n return (\n <svg className={className} viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n <path d=\"m3 17 2 2 4-4M3 7l2 2 4-4M13 6h8M13 12h8M13 18h8\" />\n </svg>\n )\n}\n\n/**\n * The shared plan-mode toggle for the left side of an agent composer.\n * Plan mode is a behavioral switch, not part of the profile/backend/model/\n * thinking identity controls on the right.\n */\nexport function ComposerModeControls({ planMode }: ComposerModeControlsProps) {\n if (!planMode) return null\n\n return (\n <button\n type=\"button\"\n aria-pressed={planMode.enabled}\n disabled={planMode.saving}\n onClick={() => planMode.setEnabled(!planMode.enabled)}\n title=\"Plan mode: the agent proposes a plan you approve before it executes\"\n className={joinClasses(\n // Inset ring: this chip sits in a composer row that clips its overflow,\n // so an outward ring loses three of its four sides. Only the offset is\n // overridden — width and colour stay with the tokens.\n 'inline-flex h-[var(--control-height-sm,2rem)] items-center gap-1 rounded-full border px-2.5 text-sm transition-colors focus-visible:[outline-offset:-2px]',\n planMode.enabled\n ? 'border-primary/50 bg-primary/10 text-primary'\n : 'border-border bg-transparent text-muted-foreground hover:text-foreground',\n planMode.saving && 'opacity-60',\n )}\n >\n <ListChecksGlyph className=\"h-3.5 w-3.5\" />\n Plan\n </button>\n )\n}\n","import { useState, type ReactNode } from 'react'\nimport { ChatComposer } from './chat-composer'\nimport { ATTACHMENT_ACCEPT, useComposerAttachments } from './use-composer-attachments'\nimport type { ComposerFileRejection } from './composer-file-accept'\nimport type { UseFileMentionsResult } from './use-file-mentions'\nimport type { ChatAttachmentInput, ChatMention } from '../chat-routes/wire'\nimport {\n AgentSessionControls,\n type AgentSessionControlsProps,\n} from './agent-session-controls'\nimport { ComposerModeControls, type ComposerPlanModeSelection } from './composer-mode-controls'\n\nexport interface EntryComposerProps {\n /** The one line above the input. Domain copy — always a product parameter. */\n heading?: ReactNode\n /** Optional supporting line under the heading. */\n subheading?: ReactNode\n placeholder?: string\n initialValue?: string\n sendLabel?: string\n disabled?: boolean\n /**\n * Agent identity (backend/model/effort). Pass it and the control row renders;\n * omit it and the composer ships without one. Omitting is a real choice for a\n * surface with nothing to choose — it should never be an oversight, which is\n * why this is one prop rather than a free-form slot a caller can forget.\n *\n * This is the CANONICAL picker cluster: `AgentSessionControls` from\n * `/web-react` (its model menu IS the canonical `ModelPicker`). The legacy\n * sandbox-ui adapter that used to back this prop was removed; the props\n * mapping for migrating a stored selection lives in\n * `docs/ui-picker-canon.md`.\n */\n agent?: AgentSessionControlsProps\n /**\n * Product-specific behavioral controls docked on the LEFT. A mode is an\n * on/off switch, not a value picker, so it sits apart from agent identity.\n * For the standard plan-approval control, prefer `planMode`.\n */\n modes?: ReactNode\n /**\n * Standard plan-approval mode. Pass only when the selected backend supports\n * it; omitted means the control is not rendered.\n */\n planMode?: ComposerPlanModeSelection\n /**\n * Upload endpoint for staged attachments. Omit and the attach affordance is\n * hidden — a composer with no place to put a file must not offer one.\n */\n uploadUrl?: string\n accept?: string\n onAttachmentError?: (reason: string) => void\n /** Files rejected by this composer's attachment policy. */\n onRejectFiles?: (rejections: ComposerFileRejection[]) => void\n /**\n * `@`-file mentions. The hook itself is shared (`useFileMentions`), but the\n * cold-box policy around it — whether pressing `@` is worth starting a\n * sandbox — is a per-surface product call, so the result is injected rather\n * than created here.\n */\n mentions?: UseFileMentionsResult\n mentionPopoverClassName?: string\n /** Rendered under the composer: suggestion pills, an onboarding nudge, a\n * disclaimer. All domain copy. */\n footer?: ReactNode\n /** Block submit until a persisted selection has resolved against the catalog,\n * so the first turn cannot go out under the wrong model. Defaults to true. */\n ready?: boolean\n onSubmit: (\n prompt: string,\n attachments: ChatAttachmentInput[],\n mentions: ChatMention[],\n ) => void\n className?: string\n composerClassName?: string\n /** Max width of the centered column. Defaults to the fleet's 820px. */\n maxWidth?: number\n}\n\n/**\n * `EntryComposer` — the centered \"what do you want to work on?\" surface a\n * product shows before a conversation exists (a new thread, an empty session,\n * a workspace overview).\n *\n * It exists because three products each grew their own, and they drifted into\n * three different capability sets rather than three different looks: one lost\n * the attach button, one lost the model and effort pickers entirely, one\n * hand-rolled a `<textarea>` and wired pickers from three separate packages\n * into one row. The composer, the pickers, the attachment queue and the mention\n * index were all ALREADY shared — what was not shared was the assembly, so\n * every product re-derived which controls an entry surface gets, and each\n * re-derivation dropped a different one.\n *\n * Mechanism lives here: layout, the attachment queue, the mention wiring, the\n * submit gate (nothing sends while an upload is pending or failed, or before\n * the model selection has resolved). Domain stays a parameter: `heading`,\n * `placeholder`, `footer` (suggestion pills, disclaimers) and the selections\n * themselves.\n *\n * The input is `ChatComposer` — the same component a docked in-thread\n * composer renders directly; this assembly adds only the hero layout around\n * it.\n */\nexport function EntryComposer({\n heading,\n subheading,\n placeholder,\n initialValue = '',\n sendLabel,\n disabled,\n agent,\n modes,\n planMode,\n uploadUrl,\n accept = ATTACHMENT_ACCEPT,\n onAttachmentError,\n onRejectFiles,\n mentions,\n mentionPopoverClassName,\n footer,\n ready = true,\n onSubmit,\n className,\n composerClassName,\n maxWidth = 820,\n}: EntryComposerProps) {\n const [value, setValue] = useState(initialValue)\n const attachments = useComposerAttachments({\n uploadUrl,\n enabled: !!uploadUrl,\n onReject: onAttachmentError,\n onError: onAttachmentError,\n })\n\n function submit(prompt: string) {\n if (!ready || disabled) return\n const next = prompt.trim()\n // A pending or failed upload must not send: the turn would reference an\n // attachment the store does not have. Surface why rather than no-op'ing.\n if (attachments.hasPending || attachments.hasError) {\n if (attachments.blockReason) onAttachmentError?.(attachments.blockReason)\n return\n }\n if (!next && attachments.references.length === 0) return\n onSubmit(next, attachments.references, mentions?.mentions ?? [])\n setValue('')\n attachments.clear()\n mentions?.clearMentions()\n }\n\n return (\n <div\n className={\n className ??\n 'relative flex min-h-0 flex-1 flex-col items-center overflow-y-auto bg-background px-5 py-8'\n }\n >\n <div className=\"my-auto w-full shrink-0\" style={{ maxWidth }}>\n {heading ? (\n <h2 className=\"mb-4 text-center text-[1.75rem] font-medium tracking-tight text-foreground\">\n {heading}\n </h2>\n ) : null}\n {subheading ? (\n <p className=\"mx-auto mb-9 max-w-md text-center text-sm leading-relaxed text-muted-foreground\">\n {subheading}\n </p>\n ) : (\n heading ? <div className=\"mb-7\" /> : null\n )}\n <ChatComposer\n className={composerClassName ?? 'vt-composer'}\n value={value}\n onValueChange={setValue}\n onSend={(message) => submit(message)}\n placeholder={placeholder}\n sendLabel={sendLabel}\n // The circular arrow AgentComposer shipped and the agent-app canon\n // for new surfaces.\n sendVariant=\"icon\"\n disabled={disabled}\n sendDisabled={!ready}\n autoFocus\n // A hero composer autofocuses on mount, so the Cmd/Ctrl+L hint\n // would advertise a shortcut to the input the user is already in.\n focusShortcut={false}\n canSubmitAttachmentsOnly\n accept={accept}\n pendingFiles={attachments.composerFiles}\n onAttach={uploadUrl ? (files) => void attachments.addFiles(files) : undefined}\n onRejectFiles={onRejectFiles}\n onRemoveFile={attachments.removeAttachment}\n onRetryFile={attachments.retry}\n mention={\n mentions\n ? {\n ...mentions.mention,\n // Sidebar tone + hairline so the popover reads as app chrome\n // (the same treatment the picker menus get) instead of the\n // brighter overlay tone the component defaults to.\n popoverClassName:\n mentionPopoverClassName ??\n 'bg-surface-container-low border-[var(--md3-outline-variant)]',\n }\n : undefined\n }\n controls={modes ?? <ComposerModeControls planMode={planMode} />}\n trailing={\n agent ? <AgentSessionControls {...agent} /> : undefined\n }\n />\n {footer ? <div className=\"mt-7\">{footer}</div> : null}\n </div>\n </div>\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAiCzD,IAAM,uBAAuB,CAAC,0BAA0B,cAAc,WAAW;AAG1E,SAAS,wBAA4C;AAC1D,MAAI,OAAO,kBAAkB,eAAe,OAAO,cAAc,oBAAoB,YAAY;AAC/F,WAAO;AAAA,EACT;AACA,aAAW,QAAQ,sBAAsB;AACvC,QAAI,cAAc,gBAAgB,IAAI,EAAG,QAAO;AAAA,EAClD;AACA,SAAO;AACT;AAGA,SAAS,yBAAkC;AACzC,SACE,OAAO,cAAc,eACrB,OAAO,UAAU,cAAc,iBAAiB,cAChD,OAAO,kBAAkB;AAE7B;AAIO,SAAS,sBAAsB,OAAwB;AAC5D,MAAI,iBAAiB,cAAc;AACjC,QAAI,MAAM,SAAS,kBAAmB,QAAO;AAC7C,QAAI,MAAM,SAAS,gBAAiB,QAAO;AAAA,EAC7C;AACA,SAAO;AACT;AAGO,SAAS,uBAAuB,cAA8B;AACnE,QAAM,OAAO,OAAO,SAAS,YAAY,KAAK,eAAe,IAAI,KAAK,MAAM,YAAY,IAAI;AAC5F,QAAM,UAAU,KAAK,MAAM,OAAO,EAAE;AACpC,QAAM,UAAU,OAAO;AACvB,SAAO,GAAG,OAAO,IAAI,OAAO,OAAO,EAAE,SAAS,GAAG,GAAG,CAAC;AACvD;AAeA,SAAS,cAAc,QAA2B;AAChD,aAAW,SAAS,OAAO,UAAU,EAAG,OAAM,KAAK;AACrD;AAEO,SAAS,aAAa,EAAE,WAAW,QAAQ,GAA2C;AAC3F,QA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;AAAA,MACC,WACE,aACA;AAAA,MAGF,0BAAAC,MAAC,SAAI,WAAU,2BAA0B,OAAO,EAAE,SAAS,GACxD;AAAA,kBACC,gBAAAD,KAAC,QAAG,WAAU,8EACX,mBACH,IACE;AAAA,QACH,aACC,gBAAAA,KAAC,OAAE,WAAU,mFACV,sBACH,IAEA,UAAU,gBAAAA,KAAC,SAAI,WAAU,QAAO,IAAK;AAAA,QAEvC,gBAAAA;AAAA,UAAC;AAAA;AAAA,YACC,WAAW,qBAAqB;AAAA,YAChC;AAAA,YACA,eAAe;AAAA,YACf,QAAQ,CAAC,YAAY,OAAO,OAAO;AAAA,YACnC;AAAA,YACA;AAAA,YAGA,aAAY;AAAA,YACZ;AAAA,YACA,cAAc,CAAC;AAAA,YACf,WAAS;AAAA,YAGT,eAAe;AAAA,YACf,0BAAwB;AAAA,YACxB;AAAA,YACA,cAAc,YAAY;AAAA,YAC1B,UAAU,YAAY,CAAC,UAAU,KAAK,YAAY,SAAS,KAAK,IAAI;AAAA,YACpE;AAAA,YACA,cAAc,YAAY;AAAA,YAC1B,aAAa,YAAY;AAAA,YACzB,SACE,WACI;AAAA,cACE,GAAG,SAAS;AAAA;AAAA;AAAA;AAAA,cAIZ,kBACE,2BACA;AAAA,YACJ,IACA;AAAA,YAEN,UAAU,SAAS,gBAAAA,KAAC,wBAAqB,UAAoB;AAAA,YAC7D,UACE,QAAQ,gBAAAA,KAAC,wBAAsB,GAAG,OAAO,IAAK;AAAA;AAAA,QAElD;AAAA,QACC,SAAS,gBAAAA,KAAC,SAAI,WAAU,QAAQ,kBAAO,IAAS;AAAA,SACnD;AAAA;AAAA,EACF;AAEJ;","names":["useEffect","useState","handle","lazy","useCallback","useEffect","useMemo","useRef","useState","useCallback","useEffect","useRef","useState","useRef","useState","useEffect","useCallback","useCallback","useRef","useState","useRef","useState","useCallback","useCallback","useEffect","useRef","useState","jsx","jsxs","jsx","jsxs","lazy","useState","useMemo","useRef","useCallback","useEffect","useCallback","useEffect","useMemo","useRef","useState","useRef","useState","useCallback","enabled","useEffect","useMemo","jsx","jsxs","useState","jsx","jsxs","useState"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/chat-routes/turn-progress.ts","../src/chat-routes/wire.ts"],"sourcesContent":["/**\n * Turn progress: the real stage a chat turn is in, on the turn stream.\n *\n * A turn can spend seconds before its first answer token: authorization, the\n * conversation load, the single-flight lock, the product's pre-turn work, a\n * sandbox, the harness and the model's first token. `session.run.phase` events\n * name those stages as they happen, so a chat shows where the turn is instead\n * of a spinner.\n *\n * A client that sends {@link TURN_PROGRESS_HEADER} gets the response stream as\n * soon as the route has parsed the body and `authorize` has admitted the\n * caller. Authorization never runs inside the stream: every refusal it makes\n * (400, 401, 402, 403, 404, 429) is a plain HTTP response, so an unadmitted\n * caller sees no stage, holds no stream and starts no work. After admission,\n * anything the route answers with a non-stream response (a held lock's 409, a\n * gate's own response, a handoff, a failure) arrives as one\n * {@link TURN_RESPONSE_EVENT} carrying that response's status, headers and\n * body, and {@link settleTurnResponse} turns it back into the `Response` the\n * caller already handles. A client that does not send the header gets exactly\n * the responses it got before.\n *\n * Product work that only an admitted turn may do (resolving its profile and\n * model, any write) belongs in `prepareTurn`, which runs after admission and,\n * on a progress-first stream, inside it with its own named stages.\n * `tests/chat-routes/authorize-before-stream.test.ts` is the gate that keeps\n * every shared route behind its `authorize`.\n *\n * Browser-safe and import-free: the server route and the web client share it.\n */\n\n/** Request header that asks for a progress-first turn stream. */\nexport const TURN_PROGRESS_HEADER = 'x-turn-progress'\n/** The only value of {@link TURN_PROGRESS_HEADER}. The route echoes it on a progress-first response. */\nexport const TURN_PROGRESS_FIRST = 'first'\n\n/** Stream event naming the turn's current stage. Non-terminal and never turn content. */\nexport const TURN_PHASE_EVENT = 'session.run.phase'\n\n/**\n * Stages the shared route emits before the producer runs. Products add their\n * own (a sandbox product emits `provisioning`, `starting`,\n * `awaiting-first-token`).\n * - `accepted`: the caller is admitted; the conversation and the lock are loading.\n * - `preparing`: the turn holds its lock; the product's pre-turn work is running.\n */\nexport type TurnRoutePhase = 'accepted' | 'preparing'\n\n/** The data of a {@link TURN_PHASE_EVENT}. */\nexport type TurnPhaseData = {\n /** Stage id: a {@link TurnRoutePhase} or a product's own stage. */\n phase: string\n /** Text the client shows verbatim. */\n message: string\n /** A keepalive for the current stage rather than a new stage. */\n heartbeat?: boolean\n /** Milliseconds since the current wait began. */\n elapsedMs?: number\n /** Milliseconds since the server received the request. */\n sinceRequestMs?: number\n}\n\n/** A {@link TURN_PHASE_EVENT} as it crosses the wire. */\nexport type TurnPhaseEvent = { type: typeof TURN_PHASE_EVENT; data: TurnPhaseData }\n\n/** Default text for the route's own stages. Products override it through `createChatTurnRoutes({ progressMessages })`. */\nexport const TURN_ROUTE_PHASE_MESSAGES: Record<TurnRoutePhase, string> = {\n accepted: 'Loading your conversation…',\n preparing: 'Preparing the agent…',\n}\n\n/** Build a {@link TURN_PHASE_EVENT}. */\nexport function buildTurnPhaseEvent(\n phase: string,\n message: string,\n opts: { heartbeat?: boolean; elapsedMs?: number; sinceRequestMs?: number } = {},\n): TurnPhaseEvent {\n return {\n type: TURN_PHASE_EVENT,\n data: {\n phase,\n message,\n ...(opts.heartbeat ? { heartbeat: true } : {}),\n ...(typeof opts.elapsedMs === 'number' ? { elapsedMs: opts.elapsedMs } : {}),\n ...(typeof opts.sinceRequestMs === 'number' ? { sinceRequestMs: opts.sinceRequestMs } : {}),\n },\n }\n}\n\n/** True for a {@link TURN_PHASE_EVENT} with a usable `phase` and `message`. */\nexport function isTurnPhaseEvent(event: unknown): event is TurnPhaseEvent {\n if (!event || typeof event !== 'object') return false\n const candidate = event as { type?: unknown; data?: { phase?: unknown; message?: unknown } }\n return candidate.type === TURN_PHASE_EVENT\n && typeof candidate.data?.phase === 'string'\n && typeof candidate.data?.message === 'string'\n}\n\n/**\n * Stream event carrying the turn's intent line: one plain sentence, written by\n * a fast model call at admission, saying what the agent is about to do (\"Looking\n * at your three competitors' pricing pages, then I'll draft the comparison.\").\n * A client shows it as a labeled status line, never as the answer, until the\n * turn's first answer text replaces it. It narrates intent; it never answers\n * or acts. Non-terminal and never turn content; at most one per turn.\n */\nexport const TURN_INTENT_EVENT = 'session.run.intent'\n\n/** The data of a {@link TURN_INTENT_EVENT}. */\nexport type TurnIntentData = {\n /** The sentence, shown verbatim. */\n text: string\n /** Milliseconds since the server received the request. */\n sinceRequestMs?: number\n}\n\n/** A {@link TURN_INTENT_EVENT} as it crosses the wire. */\nexport type TurnIntentEvent = { type: typeof TURN_INTENT_EVENT; data: TurnIntentData }\n\n/** True for a {@link TURN_INTENT_EVENT} with non-empty text. */\nexport function isTurnIntentEvent(event: unknown): event is TurnIntentEvent {\n if (!event || typeof event !== 'object') return false\n const candidate = event as { type?: unknown; data?: { text?: unknown } }\n return candidate.type === TURN_INTENT_EVENT\n && typeof candidate.data?.text === 'string'\n && candidate.data.text.trim().length > 0\n}\n\n/** Terminal event of a progress-first stream that ended without a turn: the response the route returned instead. */\nexport const TURN_RESPONSE_EVENT = 'turn.response'\n\n/** The data of a {@link TURN_RESPONSE_EVENT}. */\nexport type TurnResponseData = {\n status: number\n /** Response headers other than `set-cookie` and framing headers. */\n headers: Record<string, string>\n body: string\n}\n\n/** Headers a {@link TURN_RESPONSE_EVENT} cannot carry: cookies cannot be set after the stream opened, and framing belongs to the outer response. */\nconst UNCARRIED_HEADERS = new Set(['set-cookie', 'content-length', 'content-encoding', 'transfer-encoding', 'connection'])\n\n/** Error code {@link settleTurnResponse} reports when a progress-first stream closes before the turn started. */\nexport const TURN_STREAM_LOST_CODE = 'turn_stream_lost'\n\n/** Serialize a non-stream response for a {@link TURN_RESPONSE_EVENT}. */\nexport async function turnResponseEventFor(response: Response): Promise<{ type: typeof TURN_RESPONSE_EVENT; data: TurnResponseData }> {\n const headers: Record<string, string> = {}\n response.headers.forEach((value, key) => {\n if (!UNCARRIED_HEADERS.has(key.toLowerCase())) headers[key.toLowerCase()] = value\n })\n return { type: TURN_RESPONSE_EVENT, data: { status: response.status, headers, body: await response.text() } }\n}\n\n/**\n * Settle a turn response for a client that sent {@link TURN_PROGRESS_HEADER}.\n *\n * Reads the stream's leading progress events, handing each to `onPhase` (and an\n * intent line to `onIntent`, or dropping it when there is none), until the\n * first other event. A {@link TURN_RESPONSE_EVENT} resolves to a `Response`\n * with the original status, headers and body, so the caller's existing error\n * handling runs unchanged. Any other event resolves to a `Response` whose body\n * starts at that event and continues with the rest of the stream. A response\n * that is not progress-first is returned as it is.\n */\nexport async function settleTurnResponse(\n response: Response,\n onPhase: (phase: TurnPhaseData) => void,\n onIntent?: (intent: TurnIntentData) => void,\n): Promise<Response> {\n if (response.headers.get(TURN_PROGRESS_HEADER) !== TURN_PROGRESS_FIRST || !response.body) return response\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n const encoder = new TextEncoder()\n let buffer = ''\n let ended = false\n for (;;) {\n let newline = buffer.indexOf('\\n')\n while (newline < 0) {\n if (ended) {\n // The stream closed inside the progress prefix: the turn never started.\n return Response.json(\n { error: 'The connection closed before the turn started. Try again.', code: TURN_STREAM_LOST_CODE },\n { status: 502 },\n )\n }\n const { done, value } = await reader.read()\n if (done) {\n ended = true\n buffer += decoder.decode()\n // A final line without its newline is still a line.\n if (buffer.trim()) buffer += '\\n'\n } else {\n buffer += decoder.decode(value, { stream: true })\n }\n newline = buffer.indexOf('\\n')\n }\n const line = buffer.slice(0, newline).trim()\n if (!line) {\n buffer = buffer.slice(newline + 1)\n continue\n }\n let event: unknown\n try {\n event = JSON.parse(line)\n } catch {\n event = null\n }\n if (isTurnPhaseEvent(event)) {\n buffer = buffer.slice(newline + 1)\n onPhase(event.data)\n continue\n }\n // An intent line is progress too: a response the route answers after it\n // (a held lock's 409) still settles with its own status.\n if (isTurnIntentEvent(event)) {\n buffer = buffer.slice(newline + 1)\n onIntent?.(event.data)\n continue\n }\n const answered = event as { type?: unknown; data?: Partial<TurnResponseData> } | null\n if (answered?.type === TURN_RESPONSE_EVENT && typeof answered.data?.status === 'number') {\n await reader.cancel().catch(() => {})\n return new Response(answered.data.status === 204 || answered.data.status === 304 ? null : String(answered.data.body ?? ''), {\n status: answered.data.status,\n headers: answered.data.headers ?? {},\n })\n }\n return streamFrom(reader, buffer, encoder, response)\n }\n}\n\n/** The rest of a progress-first stream, starting with bytes already read. */\nfunction streamFrom(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n pending: string,\n encoder: TextEncoder,\n original: Response,\n): Response {\n let first = pending\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n if (first) {\n controller.enqueue(encoder.encode(first))\n first = ''\n return\n }\n const { done, value } = await reader.read()\n if (done) controller.close()\n else controller.enqueue(value)\n },\n cancel(reason) {\n return reader.cancel(reason)\n },\n })\n return new Response(body, { status: original.status, headers: original.headers })\n}\n","import { isWorkspaceFileExportable } from '../web/file-export'\nimport { TURN_PROGRESS_FIRST, TURN_PROGRESS_HEADER } from './turn-progress'\nimport type { ReasoningEffort } from '@tangle-network/agent-interface'\n\n/**\n * Wire contract between the chat client (composer + `streamChatTurn`) and the\n * assembled server vertical (`createChatTurnRoutes`). This module must remain\n * browser-safe: `/web-react` re-exports these types into browser bundles, so\n * imports must not reach a Node builtin or an engine package.\n *\n * The client part shape permits an absolute file path until the server converts\n * it to the URL required by the sandbox SDK. It is derived here, not imported,\n * 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}\n\n/** Resolve input as either a text part or a file part of a chat turn */\nexport type ChatTurnPartInput = ChatTurnTextPartInput | ChatTurnFilePartInput\n\n/** A chat turn's automatic sentinel plus the canonical agent reasoning levels. */\nexport type ChatReasoningEffort = 'auto' | ReasoningEffort\n\n// ── producer stream vocabulary ───────────────────────────────────────────────\n\n/** Represent a text event produced by a source with a fixed type and associated text content */\nexport interface ProducerTextEvent {\n type: 'text'\n text: string\n}\n\n/** Define an event representing reasoning output with a fixed type and associated text */\nexport interface ProducerReasoningEvent {\n type: 'reasoning'\n text: string\n}\n\n/** Represent an event triggered by a producer tool call with its identifier, name, and arguments */\nexport interface ProducerToolCallEvent {\n type: 'tool_call'\n call: {\n toolCallId: string\n toolName: string\n args: Record<string, unknown>\n }\n}\n\n/** Describe the structure of an event representing the result of a producer tool call */\nexport interface ProducerToolResultEvent {\n type: 'tool_result'\n toolCallId: string\n toolName: string\n outcome: {\n ok: boolean\n result?: unknown\n message?: string\n /** Typed reason for a failed call, when the producer knows it. */\n code?: string\n }\n}\n\n/** Describe cumulative provider usage reported by a producer. */\nexport interface ProducerUsageEvent {\n type: 'usage'\n usage: {\n promptTokens: number\n completionTokens: number\n /** Prompt tokens the provider served from its prompt cache. */\n cachedPromptTokens?: number\n reasoningTokens?: number\n toolTokens?: number\n toolCallCount?: number\n providerCostUsd?: number\n /** Present only when the provider enforced the complete execution budget. */\n budgetEnforced?: boolean\n }\n}\n\n/** Define the structure for a producer notice event with type, id, kind, and text fields */\nexport interface ProducerNoticeEvent {\n type: 'notice'\n id: string\n /** Kept inline with `/interactions`' `NoticeKind` so this file stays import-free. */\n noticeKind: 'warning' | 'auto-declined' | 'error'\n text: string\n /** Typed reason, on an `error` notice. */\n code?: string\n /** The failure's redacted cause chain, persisted with the notice and not rendered. */\n detail?: string\n}\n\n/** Represent an error event emitted by a producer containing message, code, and optional details */\nexport interface ProducerErrorEvent {\n type: 'error'\n data: {\n message: string\n code?: string\n details?: Record<string, unknown>\n }\n}\n\n/** Stable raw lifecycle/interaction/plan/route events forwarded unchanged. */\nexport type ProducerPassthroughEventType =\n | 'turn'\n | 'metadata'\n | 'interaction'\n | 'interaction.cancel'\n | 'plan.submitted'\n | 'done'\n | 'warning'\n /** A tool's typed side event while it runs (`data`: toolCallId, toolName, kind, data, at). */\n | 'tool.event'\n | 'session.run.started'\n | 'session.run.completed'\n | 'session.run.failed'\n | 'turn_status'\n\n/** Define an event carrying passthrough data with flexible properties for producer communication */\nexport interface ProducerPassthroughEvent {\n type: ProducerPassthroughEventType\n data?: Record<string, unknown>\n /** Route markers and raw passthroughs may carry `turnId`, `status`, `seq`, etc. */\n [key: string]: unknown\n}\n\n/** Represent events emitted by a producer during its operation for processing and handling */\nexport type ProducerWireEvent =\n | ProducerTextEvent\n | ProducerReasoningEvent\n | ProducerToolCallEvent\n | ProducerToolResultEvent\n | ProducerUsageEvent\n | ProducerNoticeEvent\n | ProducerErrorEvent\n | ProducerPassthroughEvent\n\n/** The image/file split an attachment is rendered and persisted under — the\n * same discriminant as {@link ChatMentionKind}, but a distinct name because an\n * attachment carries content the product uploaded (`ChatAttachmentInput`)\n * while a mention points at a file the box already has. Defined HERE (the\n * import-free layer) so `ChatAttachmentInput` can reference it and the client\n * composer imports it without pulling the persisted-part vocabulary;\n * `/chat-store`'s parts module re-exports it alongside the attachment helpers. */\nexport type ChatAttachmentKind = 'image' | 'file'\n\n/** `POST` turn-body entry describing a file already uploaded to the product's\n * store (vault/object-store) — distinct from an inline {@link\n * ChatTurnFilePartInput} (which carries bytes) and from a {@link FileMention}\n * (a sandbox path the box already holds). The route resolves this field with\n * {@link resolveChatAttachments}: every path is re-validated and every size is\n * re-derived from the stored body, so nothing here is trusted as sent. */\nexport interface ChatAttachmentInput {\n path: string\n name: string\n size: number\n mediaType: string\n kind: ChatAttachmentKind\n}\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?: ChatMention[]\n /** Files uploaded to the product's store ahead of the turn — path\n * references, NOT inline bytes (those ride `parts`). Validated and\n * size-re-derived by {@link resolveChatAttachments} into persistable\n * attachment parts; a product whose `parts` field is spoken for by inline\n * uploads still sends store-backed files here. */\n attachments?: ChatAttachmentInput[]\n model?: string\n effort?: ChatReasoningEffort\n harness?: string\n /** Client-generated idempotency key for the logical turn (retry-safe). */\n turnId?: string\n /** New token for a deliberate retry; reuse it for transport retries of that attempt. */\n retryAttemptId?: 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(\n payload: ChatTurnRequestPayload,\n options: { progressFirst?: boolean } = {},\n): RequestInit {\n return {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n // Ask for a progress-first stream (`./turn-progress`); settle the response with `settleTurnResponse`.\n ...(options.progressFirst ? { [TURN_PROGRESS_HEADER]: TURN_PROGRESS_FIRST } : {}),\n },\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\n/** Define the maximum byte size allowed for inline parts in data processing */\nexport const INLINE_PARTS_MAX_BYTES = 950_000\n\n// ── dispatch (parts[]) budget vocabulary ────────────────────────────────────\n//\n// The default caps `buildDispatchParts` sizes an attachment/mention dispatch\n// against — the sidecar/proxy limits an assembled `parts` array crosses, one\n// step past `INLINE_PARTS_MAX_BYTES` (which gates the raw turn BODY). Grouped\n// here, in the import-free layer, so the numbers are one overridable\n// vocabulary the client can read and a product can tune per call rather than\n// constants buried in the server module. NOTE: these model sidecar/proxy caps,\n// not a product's MIME accept-list or vault bucketing — those are DOMAIN\n// values the product supplies, never defaulted here.\n\n/** Hard cap on the whole `/prompt` request body as it crosses the sandbox\n * proxy — smaller in practice than a raw-file write cap because a dispatch\n * carries several inline parts plus the flattened history in one request. */\nexport const DISPATCH_REQUEST_MAX_BYTES = 1024 * 1024\n\n/** Bytes reserved off the top of {@link DISPATCH_REQUEST_MAX_BYTES} for the\n * JSON structure around the parts array (keys, delimiters, per-part\n * `type`/`filename`/`mediaType` fields) that {@link base64WireLen} does not\n * account for — keeps the inline budget off the exact proxy cap where one\n * stray byte trips the 413. */\nexport const DISPATCH_STRUCTURAL_RESERVE_BYTES = 64 * 1024\n\n/** Sidecar's hard cap on the `parts` array of one prompt request — a dispatch\n * must never assemble more parts than this or the whole turn 400s. */\nexport const DISPATCH_MAX_PARTS = 64\n\n/** Product-side cap on media parts per dispatch (current turn + carried\n * history), well under {@link DISPATCH_MAX_PARTS}. History trimming that keeps\n * a transcript's native media under this is a PRODUCT concern (the pointer\n * block keeps trimmed media reachable); `buildDispatchParts` enforces only the\n * total {@link DISPATCH_MAX_PARTS} cap. */\nexport const DISPATCH_MAX_MEDIA_PARTS = 24\n\n/** Size a base64-encoded string occupies on the wire given the raw\n * (pre-encoding) byte length: base64 packs 3 raw bytes into 4 output\n * characters, rounded up to the next multiple of 4. */\nexport function base64WireLen(byteLen: number): number {\n return Math.ceil(byteLen / 3) * 4\n}\n\n/**\n * Render a raw byte count as a human-readable size (`512B`, `3KB`, `12MB\n * 500KB`). Ported EXACTLY from gtm-agent's `attachment-limits.ts` — byte-\n * identical implementation, not a reinterpretation — so `resolve-attachments`'s\n * and `promote-file-part`'s error strings match gtm's wording verbatim. Lives\n * in the import-free wire layer (not `resolve-attachments.ts` alone) because\n * BOTH the aggregate-cap message here and the per-file oversize message in\n * `promote-file-part.ts` need it; a browser composer wanting the same\n * formatting for a client-side pre-check can also import it with no engine\n * pulled in.\n */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes}B`\n if (bytes >= 1024 * 1024) {\n const megabytes = Math.floor(bytes / (1024 * 1024))\n const remainder = bytes % (1024 * 1024)\n return remainder === 0 ? `${megabytes}MB` : `${megabytes}MB ${formatBytes(remainder)}`\n }\n return `${Math.round(bytes / 1024)}KB`\n}\n\n/** Represent errors for invalid chat turn inputs with status and code properties */\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.path) bytes += part.path.length\n return bytes\n}\n\n/** Calculate the total byte size of an array of chat turn parts */\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\n/** An agent mention from the composer's `@`-picker: a workspace agent the\n * turn is addressed to. `handle` is the `@`-token identity (the pill's\n * `MentionItem.id`, what the message text carries as `@<handle>`);\n * `agentId` is the stable profile id, so a renamed agent still resolves from\n * an old message. A file mention has no `kind`; this one always does. */\nexport interface AgentMention {\n kind: 'agent'\n agentId: string\n handle: string\n name: string\n}\n\n/** Everything the composer can `@`: a file in the box or an agent in the workspace. */\nexport type ChatMention = FileMention | AgentMention\n\nexport function isAgentMention(mention: ChatMention): mention is AgentMention {\n return (mention as AgentMention).kind === 'agent'\n}\n\n/** The file mentions of a validated list, for the seams that read the box. */\nexport function fileMentionsOf(mentions: readonly ChatMention[]): FileMention[] {\n return mentions.filter((mention): mention is FileMention => !isAgentMention(mention))\n}\n\n/** The agent mentions of a validated list, in mention order: the turn's responders. */\nexport function agentMentionsOf(mentions: readonly ChatMention[]): AgentMention[] {\n return mentions.filter(isAgentMention)\n}\n\n/** A handle is what a person types after `@`: lowercase letters, digits and\n * hyphens, as `normalizeProfileName` in `/agent-profiles` spells a name. */\nexport const AGENT_HANDLE_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/\n\n/** The handle a profile name gets: lowercase, runs of anything else become one\n * hyphen, no leading or trailing hyphen, at most 63 characters. \"Research\n * Lead\" is `research-lead`. One spelling for the composer, the route and the\n * rail, so a product never derives its own. An empty result (a name with no\n * letters or digits) is `agent`. */\nexport function agentHandle(name: string): string {\n const handle = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 63).replace(/-+$/, '')\n return handle || 'agent'\n}\nconst AGENT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/\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' | 'agent'\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\n/** Define options to resolve mention paths when converting file mentions to parts */\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 ChatMention[],\n opts: FileMentionsToPartsOptions = {},\n): ChatTurnFilePartInput[] {\n const resolvePath = opts.resolvePath ?? ((path: string) => path)\n // An agent mention addresses a responder; it points at nothing in the box.\n return fileMentionsOf(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'> | AgentMention)[],\n): string {\n const files = mentions.filter((m): m is Pick<FileMention, 'name' | 'path'> => (m as AgentMention).kind !== 'agent')\n if (files.length === 0) return ''\n const lines = files.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\n/** Represent the result of a sandbox mention path check indicating success or failure with an error message */\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 if (!isWorkspaceFileExportable(record.path as string)) {\n throw new ChatTurnInputError(`mentions[${index}]: file is not exportable`)\n }\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 */\n/** The validated, deduped mention list off the wire: files by path, agents\n * by id, in the order typed. One cap covers both kinds. */\nexport function parseMentions(raw: unknown): ChatMention[] {\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: ChatMention[] = []\n const seen = new Set<string>()\n for (let index = 0; index < raw.length; index += 1) {\n const entry = raw[index] as Record<string, unknown> | null\n const mention = entry && typeof entry === 'object' && entry.kind === 'agent'\n ? parseAgentMention(entry, index)\n : parseFileMention(raw[index], index)\n const key = isAgentMention(mention) ? `agent:${mention.agentId}` : `file:${mention.path}`\n if (seen.has(key)) continue\n seen.add(key)\n mentions.push(mention)\n }\n return mentions\n}\n\n/** The file mentions of the wire list; agent mentions are validated and set aside. */\nexport function parseFileMentions(raw: unknown): FileMention[] {\n return fileMentionsOf(parseMentions(raw))\n}\n\nfunction parseAgentMention(record: Record<string, unknown>, index: number): AgentMention {\n const agentId = record.agentId\n if (typeof agentId !== 'string' || !AGENT_ID_PATTERN.test(agentId)) {\n throw new ChatTurnInputError(`mentions[${index}].agentId must be 1–128 letters, digits, dots, colons, underscores or hyphens`)\n }\n const handle = record.handle\n if (typeof handle !== 'string' || !AGENT_HANDLE_PATTERN.test(handle)) {\n throw new ChatTurnInputError(`mentions[${index}].handle must be lowercase letters, digits and hyphens`)\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 return { kind: 'agent', agentId, handle, name: name.trim() }\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'] 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.content !== undefined) {\n throw new ChatTurnInputError(`parts[${index}].content is not supported; provide a url or path`)\n }\n\n const url = typeof part.url === 'string' && part.url.length > 0 ? part.url : undefined\n const path = typeof part.path === 'string' && part.path.length > 0 ? part.path : undefined\n if (Boolean(url) === Boolean(path)) {\n throw new ChatTurnInputError(`parts[${index}] requires exactly one url or path`)\n }\n if (path && !path.startsWith('/')) {\n throw new ChatTurnInputError(`parts[${index}].path must be absolute`)\n }\n\n const filename = typeof part.filename === 'string' ? part.filename.trim() : undefined\n if (part.type === 'file' && !filename) {\n throw new ChatTurnInputError(`parts[${index}].filename is required for file parts`)\n }\n return {\n type: part.type,\n ...(filename ? { filename } : {}),\n ...(part.mediaType !== undefined ? { mediaType: part.mediaType as string } : {}),\n ...(url ? { url } : { path: path! }),\n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