@tangle-network/agent-app 0.46.42 → 0.46.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/assistant/index.js +9 -8
- package/dist/assistant/index.js.map +1 -1
- package/dist/catalog/index.d.ts +1 -1
- package/dist/catalog/index.js +5 -3
- package/dist/chat-react/index.js +6 -5
- package/dist/chat-routes/gateway-adapter.d.ts +4 -2
- package/dist/chat-routes/index.js +115 -24
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/turn-routes.d.ts +20 -8
- package/dist/chat-routes/wire.d.ts +7 -1
- package/dist/chat-store/index.js +3 -2
- package/dist/chat-store/index.js.map +1 -1
- package/dist/chat-store/store.d.ts +3 -0
- package/dist/{chunk-KWXUBMXU.js → chunk-DXHUQ5NO.js} +1 -1
- package/dist/chunk-DXHUQ5NO.js.map +1 -0
- package/dist/{chunk-U2UAQTFY.js → chunk-HHCUPBYW.js} +3 -3
- package/dist/{chunk-5ZTFZBS6.js → chunk-IRYULX3R.js} +2 -2
- package/dist/{chunk-TH7L265V.js → chunk-MCYJON3F.js} +12 -5
- package/dist/chunk-MCYJON3F.js.map +1 -0
- package/dist/{chunk-Z4TPWP6A.js → chunk-MLJQYITH.js} +2 -2
- package/dist/{chunk-PZOTRGGQ.js → chunk-N55NM3W2.js} +143 -8
- package/dist/chunk-N55NM3W2.js.map +1 -0
- package/dist/{chunk-QK4IFP3E.js → chunk-P3L5HF53.js} +5 -5
- package/dist/{chunk-YNMPMW3G.js → chunk-SUO2R2ET.js} +2 -2
- package/dist/{chunk-PYDMEYWA.js → chunk-TIQKVTOD.js} +26 -9
- package/dist/chunk-TIQKVTOD.js.map +1 -0
- package/dist/{chunk-OAGD7RDM.js → chunk-UEDFSZ3E.js} +43 -16
- package/dist/chunk-UEDFSZ3E.js.map +1 -0
- package/dist/harness/index.d.ts +10 -4
- package/dist/harness/index.js +1 -1
- package/dist/{mention-editor-CBLT6LE3.js → mention-editor-Y45HQYOA.js} +3 -2
- package/dist/{mention-editor-CBLT6LE3.js.map → mention-editor-Y45HQYOA.js.map} +1 -1
- package/dist/run/index.js +1 -1
- package/dist/runtime/index.js +4 -2
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/model-catalog.d.ts +9 -1
- package/dist/sandbox/index.d.ts +33 -0
- package/dist/sandbox/index.js +4 -2
- package/dist/skills-placement/index.js +1 -1
- package/dist/studio-react/index.js +3 -2
- package/dist/studio-react/index.js.map +1 -1
- package/dist/web-react/controls.d.ts +4 -4
- package/dist/web-react/index.js +9 -8
- package/package.json +15 -13
- package/dist/chunk-KWXUBMXU.js.map +0 -1
- package/dist/chunk-OAGD7RDM.js.map +0 -1
- package/dist/chunk-PYDMEYWA.js.map +0 -1
- package/dist/chunk-PZOTRGGQ.js.map +0 -1
- package/dist/chunk-TH7L265V.js.map +0 -1
- /package/dist/{chunk-U2UAQTFY.js.map → chunk-HHCUPBYW.js.map} +0 -0
- /package/dist/{chunk-5ZTFZBS6.js.map → chunk-IRYULX3R.js.map} +0 -0
- /package/dist/{chunk-Z4TPWP6A.js.map → chunk-MLJQYITH.js.map} +0 -0
- /package/dist/{chunk-QK4IFP3E.js.map → chunk-P3L5HF53.js.map} +0 -0
- /package/dist/{chunk-YNMPMW3G.js.map → chunk-SUO2R2ET.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/web-react/mention-editor.tsx","../src/web-react/mention-list.tsx","../src/web-react/mention-serialize.ts"],"sourcesContent":["/**\n * The mention-capable rich input behind `ChatComposer`'s `mention` prop.\n *\n * The five `@tiptap/*` packages are OPTIONAL peers, and every value access to\n * them goes through `loadTiptapModules()`'s dynamic `import()` — never a\n * static named import. A bundler resolves a missing optional peer to a stub\n * module with a default export only, so a static `import { mergeAttributes }`\n * fails the CONSUMER'S build even when nothing ever renders the mention path\n * (measured against Vite 7's `__vite-optional-peer-dep` stub). The dynamic\n * form builds clean and defers the failure to the first actual editor load,\n * where it throws with the missing packages named — the same doctrine as\n * `sequences-react`'s transcription peer. Type-only imports are erased and\n * stay allowed.\n */\n\nimport type { MentionOptions } from '@tiptap/extension-mention'\nimport type { SuggestionKeyDownProps, SuggestionProps } from '@tiptap/suggestion'\nimport type * as TiptapCore from '@tiptap/core'\nimport type * as TiptapExtensionMention from '@tiptap/extension-mention'\nimport type * as TiptapReact from '@tiptap/react'\nimport type * as TiptapStarterKit from '@tiptap/starter-kit'\nimport type * as TiptapSuggestion from '@tiptap/suggestion'\nimport { useEffect, useId, useRef, useState, type ComponentType, type ReactNode } from 'react'\n\nimport { PopoverSurface } from './controls'\nimport { MENTION_PILL_CLASS } from './mention-pill'\nimport { MentionList, type MentionListHandle } from './mention-list'\nimport {\n collectMentions,\n parseMentionValue,\n serializeMentionDoc,\n type MentionDocNode,\n} from './mention-serialize'\nimport type { ComposerMentionProp, MentionItem } from './use-file-mentions'\n\n/** The loaded namespaces of the five optional peers, as one bag. */\nexport interface TiptapModules {\n core: typeof TiptapCore\n extensionMention: typeof TiptapExtensionMention\n react: typeof TiptapReact\n starterKit: typeof TiptapStarterKit\n suggestion: typeof TiptapSuggestion\n}\n\nconst PEERS_MISSING_MESSAGE =\n 'ChatComposer `mention` needs the @tiptap/* optional peers — install @tiptap/core, @tiptap/extension-mention, @tiptap/pm, @tiptap/react, @tiptap/starter-kit and @tiptap/suggestion (>=3.28.0 <4.0.0; @tiptap/suggestion also peers on @floating-ui/dom)'\n\n/** The rejection shapes bundlers produce for an UNINSTALLED module. Only\n * these get enriched with the install-set message — a transient chunk-fetch\n * failure keeps its own cause so diagnostics do not mislabel it as a missing\n * dependency. An unmatched resolution error stays unchanged, so the\n * classifier can only under-enrich. */\nconst RESOLUTION_FAILURE = /could not resolve|cannot find module|failed to resolve/i\n\n/** Resolve the optional peers, or throw naming every one of them. */\nexport async function loadTiptapModules(): Promise<TiptapModules> {\n let modules: TiptapModules\n try {\n const [core, extensionMention, react, starterKit, suggestion] = await Promise.all([\n import('@tiptap/core'),\n import('@tiptap/extension-mention'),\n import('@tiptap/react'),\n import('@tiptap/starter-kit'),\n import('@tiptap/suggestion'),\n ])\n modules = { core, extensionMention, react, starterKit, suggestion }\n } catch (error) {\n if (error instanceof Error && RESOLUTION_FAILURE.test(error.message)) {\n throw new Error(PEERS_MISSING_MESSAGE, { cause: error })\n }\n throw error\n }\n // A CommonJS-in-production bundler stubs a missing optional peer as a\n // SILENT empty namespace rather than a throwing module. Validate the\n // members the editor actually calls, so that shape still fails loud with\n // the peers named instead of as an undefined-property crash mid-render.\n if (\n typeof modules.core.mergeAttributes !== 'function' ||\n typeof modules.react.useEditor !== 'function' ||\n modules.react.EditorContent === undefined ||\n modules.extensionMention.default === undefined ||\n modules.starterKit.default === undefined ||\n typeof modules.suggestion.exitSuggestion !== 'function'\n ) {\n throw new Error(PEERS_MISSING_MESSAGE)\n }\n return modules\n}\n\nexport interface MentionEditorProps {\n value: string\n onChange: (value: string) => void\n /** Fired when Enter (no Shift, popover closed, not composing) should send. */\n onSubmit: () => void\n placeholder: string\n disabled?: boolean\n autoFocus?: boolean\n /** Pixel floor for the input box. The composer computes it from `minRows`\n * against its own line metrics, so the two input modes cannot drift. */\n minHeight: number\n /** Pixel height the input grows to before it scrolls. */\n maxHeight: number\n mention: ComposerMentionProp\n /** Basic input shown during server rendering and editor initialization. */\n fallback: ReactNode\n /** Registers a focus callback the composer wires to Cmd/Ctrl+L; called with\n * `null` on unmount so the composer never focuses a destroyed editor. */\n registerFocus?: (focus: (() => void) | null) => void\n /**\n * Clipboard files pulled off a paste. Returns true when consumed so the\n * editor suppresses its default text paste — the same funnel the textarea\n * path routes through to `onAttach`.\n */\n onPasteFiles?: (files: FileList) => boolean\n}\n\n/** Only text, hard breaks, and atomic mention pills — no marks, no formatting. */\nexport function buildComposerStarterKit(tiptap: TiptapModules) {\n return tiptap.starterKit.default.configure({\n blockquote: false,\n bold: false,\n bulletList: false,\n code: false,\n codeBlock: false,\n dropcursor: false,\n heading: false,\n horizontalRule: false,\n italic: false,\n link: false,\n listItem: false,\n listKeymap: false,\n orderedList: false,\n strike: false,\n trailingNode: false,\n underline: false,\n })\n}\n\n/**\n * The mention node: an inline atom (`inline: true, selectable: false,\n * atom: true` from `@tiptap/extension-mention`) carrying `{ id, label, kind }`,\n * rendered as a themed pill showing the label with the full id in `title`. Atom\n * means the cursor can't enter it and a single backspace removes the whole\n * thing. The `suggestion` config is supplied by the caller so the popover's\n * fetch/keyboard wiring stays in the component.\n */\nexport function buildMentionExtension(\n tiptap: TiptapModules,\n trigger: string,\n suggestion: MentionOptions['suggestion'],\n) {\n const { mergeAttributes } = tiptap.core\n return tiptap.extensionMention.default\n .extend({\n addAttributes() {\n return {\n id: {\n default: null,\n parseHTML: (element) => element.getAttribute('data-id'),\n renderHTML: (attrs) => (attrs.id ? { 'data-id': attrs.id } : {}),\n },\n label: {\n default: null,\n parseHTML: (element) => element.getAttribute('data-label'),\n renderHTML: (attrs) => (attrs.label ? { 'data-label': attrs.label } : {}),\n },\n kind: {\n default: null,\n parseHTML: (element) => element.getAttribute('data-kind'),\n renderHTML: (attrs) => (attrs.kind ? { 'data-kind': attrs.kind } : {}),\n },\n }\n },\n })\n .configure({\n HTMLAttributes: { class: MENTION_PILL_CLASS },\n renderText: ({ node }) => `${trigger}${node.attrs.id}`,\n renderHTML: ({ options, node }) => [\n 'span',\n mergeAttributes(options.HTMLAttributes, {\n title: node.attrs.id ?? undefined,\n }),\n `${trigger}${node.attrs.label ?? node.attrs.id}`,\n ],\n suggestion,\n })\n}\n\n/** Matches the composer textarea's own text treatment so the two input modes\n * render identically (`text-base leading-6`, the same padding). `outline-none`\n * is safe for the same reason as on that textarea: the composer card this\n * editor mounts into draws the keyboard indicator through `focus-within:`,\n * so a second outline inside the card would double the ring. */\nconst EDITOR_CLASS =\n 'w-full whitespace-pre-wrap break-words bg-transparent px-1.5 py-1 text-base leading-6 text-foreground outline-none'\n\n/** Trailing debounce on the suggestion fetch so a fast typist doesn't hit the\n * provider once per keystroke. Fixed rather than a prop — 100ms is well under\n * perceived latency and the monotonic `requestId` already makes any race\n * harmless, so there's no tuning knob worth exposing. */\nconst FETCH_DEBOUNCE_MS = 100\n\n/** Stable key for a mention set — order- and id-sensitive, ignores label/kind\n * so cosmetic re-fetches of the same id don't read as a change. JSON-encoded:\n * ids are workspace paths that may contain spaces, so a plain join would make\n * `[\"a b\",\"c\"]` and `[\"a\",\"b c\"]` collide and suppress a real change. */\nfunction mentionsKey(mentions: MentionItem[]): string {\n return JSON.stringify(mentions.map((item) => item.id))\n}\n\n/** `React.lazy` payload: resolve the peers, then build the component. */\nexport async function loadMentionEditor(): Promise<{\n default: ComponentType<MentionEditorProps>\n}> {\n return { default: createMentionEditor(await loadTiptapModules()) }\n}\n\n/**\n * Builds the mention-capable rich input against loaded tiptap modules. Loaded\n * lazily by `ChatComposer` so textarea-only consumers never pull TipTap into\n * their initial bundle. It preserves every textarea behavior — controlled\n * plain-text `value`, Enter to send / Shift+Enter for a newline, placeholder,\n * disabled, autofocus, file-paste routing — and adds `@`-mention pills backed\n * by an async provider.\n *\n * The suggestion list renders through `PopoverSurface` anchored to the input\n * box, like the composer's slash menu: an in-place panel is a panel the host\n * clips away (see the popover canon in AGENTS.md).\n */\nexport function createMentionEditor(tiptap: TiptapModules): ComponentType<MentionEditorProps> {\n const { EditorContent, useEditor } = tiptap.react\n const { exitSuggestion } = tiptap.suggestion\n\n return function MentionEditor({\n value,\n onChange,\n onSubmit,\n placeholder,\n disabled,\n autoFocus,\n minHeight,\n maxHeight,\n mention,\n fallback,\n registerFocus,\n onPasteFiles,\n }: MentionEditorProps) {\n const trigger = mention.trigger ?? '@'\n\n const [open, setOpen] = useState(false)\n const [query, setQuery] = useState('')\n const [items, setItems] = useState<MentionItem[]>([])\n const [loading, setLoading] = useState(false)\n const [errored, setErrored] = useState(false)\n // Mirror of the list's highlight, for `aria-activedescendant` — keyboard\n // focus never leaves the editor, so the highlighted row must be announced\n // through the editable element itself.\n const [activeIndex, setActiveIndex] = useState(0)\n const listboxId = useId()\n\n // The input box PopoverSurface anchors to, and the portaled panel itself.\n const anchorRef = useRef<HTMLDivElement>(null)\n const panelRef = useRef<HTMLDivElement>(null)\n\n // Live refs keep the once-built editor's callbacks reading current props\n // and state without rebuilding the editor (which would drop cursor +\n // content).\n const openRef = useRef(false)\n const commandRef = useRef<((item: MentionItem) => void) | null>(null)\n const listRef = useRef<MentionListHandle | null>(null)\n // Grows for the component's lifetime — one entry per distinct id the user\n // actually PICKED (or that arrived in the document as a mention node).\n // Deliberately never fed from fetch results: restore-eligibility must\n // track selection, not visibility. Uncapped; fine for a chat composer's\n // lifetime, worth an LRU only if this outlives that.\n const knownRef = useRef<Map<string, MentionItem>>(new Map())\n const requestIdRef = useRef(0)\n // Last mention-id set reported via `onMentionsChange`, so a programmatic\n // restore that lands on the same mentions doesn't re-fire the callback.\n // Seeded with the EMPTY-set key (not ''): the initial document can never\n // hold pills (`knownRef` starts empty), so the first computed key is the\n // empty set's — starting anywhere else fires a spurious `[]` callback.\n const lastMentionsKeyRef = useRef(mentionsKey([]))\n const onSubmitRef = useRef(onSubmit)\n onSubmitRef.current = onSubmit\n const onChangeRef = useRef(onChange)\n onChangeRef.current = onChange\n const onMentionsChangeRef = useRef(mention.onMentionsChange)\n onMentionsChangeRef.current = mention.onMentionsChange\n const onPasteFilesRef = useRef(onPasteFiles)\n onPasteFilesRef.current = onPasteFiles\n const fetchItemsRef = useRef(mention.fetchItems)\n fetchItemsRef.current = mention.fetchItems\n\n const editor = useEditor(\n {\n immediatelyRender: false,\n editable: !disabled,\n autofocus: autoFocus ? 'end' : false,\n content: parseMentionValue(value, knownRef.current),\n editorProps: {\n attributes: {\n class: EDITOR_CLASS,\n role: 'textbox',\n 'aria-multiline': 'true',\n 'aria-label': 'Message input',\n 'aria-haspopup': 'listbox',\n },\n handleKeyDown: (_view, event) => {\n if (event.key !== 'Enter' || event.shiftKey) return false\n // Composition (IME) commits via Enter — never send mid-composition.\n if (event.isComposing || event.keyCode === 229) return false\n // Popover open ⇒ Enter belongs to the suggestion plugin (selects).\n if (openRef.current) return false\n event.preventDefault()\n onSubmitRef.current()\n return true\n },\n handlePaste: (_view, event) => {\n const files = event.clipboardData?.files\n if (files && files.length > 0 && onPasteFilesRef.current) {\n return onPasteFilesRef.current(files)\n }\n return false\n },\n },\n onUpdate: ({ editor }) => {\n const json = editor.getJSON() as MentionDocNode\n onChangeRef.current(serializeMentionDoc(json))\n const mentions = collectMentions(json)\n for (const item of mentions) knownRef.current.set(item.id, item)\n // Report only when the mention SET changed — typing prose around an\n // unchanged pill must not re-fire the callback on every keystroke.\n const key = mentionsKey(mentions)\n if (key !== lastMentionsKeyRef.current) {\n lastMentionsKeyRef.current = key\n onMentionsChangeRef.current?.(mentions)\n }\n },\n extensions: [\n buildComposerStarterKit(tiptap),\n buildMentionExtension(tiptap, trigger, {\n char: trigger,\n allowSpaces: false,\n // Items are fetched by this component (so it can model loading and\n // error states), not by the suggestion plugin.\n items: () => [],\n command: ({ editor, range, props }) => {\n const item = props as unknown as MentionItem\n editor\n .chain()\n .focus()\n .insertContentAt(range, [\n {\n type: 'mention',\n attrs: {\n id: item.id,\n label: item.label,\n kind: item.kind ?? null,\n },\n },\n { type: 'text', text: ' ' },\n ])\n .run()\n knownRef.current.set(item.id, item)\n },\n render: () => ({\n onStart: (props: SuggestionProps) => {\n openRef.current = true\n commandRef.current = props.command\n setOpen(true)\n setQuery(props.query)\n },\n onUpdate: (props: SuggestionProps) => {\n commandRef.current = props.command\n setQuery(props.query)\n },\n onKeyDown: (props: SuggestionKeyDownProps) => {\n if (props.event.key === 'Escape') {\n exitSuggestion(props.view)\n return true\n }\n return listRef.current?.onKeyDown(props.event) ?? false\n },\n onExit: () => {\n openRef.current = false\n commandRef.current = null\n setOpen(false)\n setItems([])\n setLoading(false)\n setErrored(false)\n },\n }),\n }),\n ],\n },\n [],\n )\n\n // Fetch matches for the active query, trailing-debounced so a fast typist\n // doesn't hit the provider once per keystroke. The monotonic id still\n // drops stale responses (belt-and-suspenders against a provider that\n // resolves out of order); the debounce timer itself is cancelled by the\n // effect cleanup whenever `query` changes again before it fires.\n useEffect(() => {\n if (!open) return\n const requestId = (requestIdRef.current += 1)\n setLoading(true)\n setErrored(false)\n const timer = setTimeout(() => {\n // The provider is called INSIDE the chain so a synchronous throw lands\n // in the same `.catch` as a rejection — outside it, the exception\n // escapes the timer callback and the panel is stuck on \"Searching…\".\n Promise.resolve()\n .then(() => fetchItemsRef.current(query))\n .then((results) => {\n if (requestId !== requestIdRef.current) return\n // Results are NOT written into `knownRef`: merely appearing in a\n // suggestion list must not make an id restore-eligible, or a\n // later restore would promote prose the user typed (never picked)\n // into a structured mention. Only a pick (`command`) or a mention\n // already in the document teaches the restore path an id.\n setItems(results)\n setLoading(false)\n })\n .catch(() => {\n if (requestId !== requestIdRef.current) return\n setErrored(true)\n setLoading(false)\n })\n }, FETCH_DEBOUNCE_MS)\n return () => clearTimeout(timer)\n }, [open, query])\n\n // Programmatic `value` changes\n // re-parse into the document; `@<id>` runs come back as pills only for\n // ids already in `knownRef` at parse time. That conservatism is the\n // contract, not a gap: the serialized form cannot distinguish a PICKED\n // pill from `@text` the user simply typed (a pick is the only thing that\n // creates a mention in-session), so resolving unknown runs against the\n // provider at hydration would fabricate structured attachments from\n // plain prose. An id never fetched or inserted in this session therefore\n // stays literal text, exactly as it would have if typed. Guarded against\n // the onChange→value feedback loop by comparing the serialized form.\n //\n // `setContent` runs with `emitUpdate: false` (this is not a user edit),\n // so `onMentionsChange` — normally wired only off `onUpdate` — is fired\n // here explicitly, but only when the restored mention set actually\n // differs from the last one reported, so a restore that changes plain\n // text around unchanged mentions doesn't re-fire spuriously.\n useEffect(() => {\n if (!editor) return\n if (serializeMentionDoc(editor.getJSON() as MentionDocNode) === value) return\n const doc = parseMentionValue(value, knownRef.current)\n editor.commands.setContent(doc, { emitUpdate: false })\n const mentions = collectMentions(doc)\n const key = mentionsKey(mentions)\n if (key !== lastMentionsKeyRef.current) {\n lastMentionsKeyRef.current = key\n onMentionsChangeRef.current?.(mentions)\n }\n }, [editor, value])\n\n useEffect(() => {\n editor?.setEditable(!disabled)\n }, [editor, disabled])\n\n // Announce the popover through the editable element: focus stays in the\n // editor while ↑/↓ move the listbox highlight, so without\n // `aria-activedescendant` a screen reader hears nothing change. Set\n // imperatively — `editorProps.attributes` is fixed at editor creation.\n useEffect(() => {\n if (!editor) return\n const dom = editor.view.dom\n dom.setAttribute('aria-expanded', open ? 'true' : 'false')\n if (open) dom.setAttribute('aria-controls', listboxId)\n else dom.removeAttribute('aria-controls')\n const hasRows = open && !loading && !errored && items.length > 0\n if (hasRows) dom.setAttribute('aria-activedescendant', `${listboxId}-opt-${activeIndex}`)\n else dom.removeAttribute('aria-activedescendant')\n }, [editor, open, loading, errored, items.length, activeIndex, listboxId])\n\n useEffect(() => {\n if (!editor || !registerFocus) return\n registerFocus(() => editor.commands.focus())\n // Unregister on unmount so the composer's focus shortcut can never call\n // into a destroyed editor.\n return () => registerFocus(null)\n }, [editor, registerFocus])\n\n if (!editor) return fallback\n\n return (\n <div className=\"relative\">\n <div ref={anchorRef} className=\"overflow-y-auto\" style={{ maxHeight, minHeight }}>\n <EditorContent editor={editor} />\n {value.length === 0 && (\n <div className=\"pointer-events-none absolute left-1.5 top-1 text-base leading-6 text-muted-foreground\">\n {placeholder}\n </div>\n )}\n </div>\n\n {/* The panel's surface classes (and the consumer's `popoverClassName`)\n live on MentionList itself; the surface only places it. The outer\n scroll keeps rows reachable when the viewport cap undercuts the\n list's own max height. */}\n <PopoverSurface\n open={open}\n triggerRef={anchorRef}\n panelRef={panelRef}\n className=\"overflow-y-auto\"\n >\n <MentionList\n ref={listRef}\n id={listboxId}\n items={items}\n loading={loading}\n error={errored}\n emptyText={mention.emptyText}\n renderItem={mention.renderItem}\n onSelect={(item) => commandRef.current?.(item)}\n onActiveChange={setActiveIndex}\n className={mention.popoverClassName}\n />\n </PopoverSurface>\n </div>\n )\n }\n}\n","import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\n\nimport { joinClasses } from './class-names'\nimport type { MentionItem } from './use-file-mentions'\n\n/** Imperative surface the editor's suggestion keymap drives. */\nexport interface MentionListHandle {\n /** Returns true when the key was consumed — the editor must not also act. */\n onKeyDown: (event: KeyboardEvent) => boolean\n}\n\nexport interface MentionListProps {\n items: MentionItem[]\n loading: boolean\n error: boolean\n /** Shown when the fetch resolved to zero items. Default \"No matches\". */\n emptyText?: string\n renderItem?: (item: MentionItem) => ReactNode\n onSelect: (item: MentionItem) => void\n /** Root `role=\"listbox\"` element id; option rows derive stable ids from it\n * (`<id>-opt-<index>`) so the editor can point `aria-activedescendant` at\n * the highlighted row. */\n id?: string\n /** Fired whenever the highlight moves (keys, hover, or a result-set\n * re-home) — what keeps the editor's `aria-activedescendant` current. */\n onActiveChange?: (index: number) => void\n /** Extra classes merged onto the panel's root element, applied last so\n * they win over the component's own. */\n className?: string\n}\n\n/**\n * The mention suggestion list: a flat, keyboard-driven menu with loading,\n * empty, and error states. Selection is owned here so ↑/↓ and Enter/Tab\n * resolve against the highlighted row; every key it handles is reported\n * consumed so the composer's Enter-to-send never fires while open. The panel\n * carries its own surface classes but no positioning — the editor places it\n * through `PopoverSurface`, per the popover canon.\n */\nexport const MentionList = forwardRef<MentionListHandle, MentionListProps>(\n function MentionList(\n { items, loading, error, emptyText = 'No matches', renderItem, onSelect, id, onActiveChange, className },\n ref,\n ) {\n const [selected, setSelected] = useState(0)\n // Mirrors `selected` so the key handler reads the live index even when keys\n // arrive faster than React commits (e.g. synchronous test-driven calls).\n const selectedRef = useRef(0)\n const onActiveChangeRef = useRef(onActiveChange)\n onActiveChangeRef.current = onActiveChange\n // One entry per rendered row, so the highlight can be scrolled into view\n // from an effect (once per highlight move) instead of a ref callback\n // (which re-fires on every re-render of the row).\n const optionRefs = useRef<Array<HTMLButtonElement | null>>([])\n const move = (next: number) => {\n selectedRef.current = next\n setSelected(next)\n onActiveChangeRef.current?.(next)\n }\n\n // Keyboard navigation must keep the highlight visible inside the panel's\n // own scroll (`max-h-64 overflow-y-auto`).\n useEffect(() => {\n optionRefs.current[selected]?.scrollIntoView({ block: 'nearest' })\n }, [selected, items])\n\n // A new result set re-homes the highlight to the top.\n useEffect(() => {\n move(0)\n }, [items])\n\n useImperativeHandle(\n ref,\n () => ({\n onKeyDown(event) {\n // The handler must agree with the render: while loading or errored\n // the rows are not painted, so `items` still holding the PREVIOUS\n // query's results must not make Enter select an invisible file.\n const count = loading || error ? 0 : items.length\n switch (event.key) {\n case 'ArrowDown':\n if (count > 0) move((selectedRef.current + 1) % count)\n return true\n case 'ArrowUp':\n if (count > 0) move((selectedRef.current - 1 + count) % count)\n return true\n case 'Enter':\n // Consume even with nothing to select so the message never\n // submits while the popover is open. Clamp the index: a\n // shrunken result set re-homes the highlight in an effect, and\n // a key can arrive before that effect commits.\n if (count > 0) onSelect(items[Math.min(selectedRef.current, count - 1)]!)\n return true\n case 'Tab':\n // Tab selects only when a row exists; with nothing selectable\n // (loading, error, empty) it must fall through to normal focus\n // navigation — consuming it would trap keyboard focus.\n if (count === 0) return false\n onSelect(items[Math.min(selectedRef.current, count - 1)]!)\n return true\n default:\n return false\n }\n },\n }),\n [items, loading, error, onSelect],\n )\n\n return (\n <div\n role=\"listbox\"\n id={id}\n aria-label=\"File mentions\"\n className={joinClasses(\n 'max-h-64 min-w-[16rem] max-w-sm overflow-y-auto rounded-xl border border-border',\n 'bg-popover p-1 text-popover-foreground shadow-lg',\n className,\n )}\n >\n {loading && (\n <div className=\"flex items-center gap-2 px-2.5 py-2 text-sm text-muted-foreground\">\n <span className=\"h-3.5 w-3.5 animate-spin rounded-full border-2 border-primary border-t-transparent\" />\n Searching…\n </div>\n )}\n\n {!loading && error && (\n <div className=\"px-2.5 py-2 text-sm text-destructive\">Couldn’t load matches</div>\n )}\n\n {!loading && !error && items.length === 0 && (\n <div className=\"px-2.5 py-2 text-sm text-muted-foreground\">{emptyText}</div>\n )}\n\n {!loading &&\n !error &&\n items.map((item, index) => {\n const active = index === selected\n return (\n <button\n type=\"button\"\n key={item.id}\n id={id ? `${id}-opt-${index}` : undefined}\n role=\"option\"\n aria-selected={active}\n ref={(el) => {\n optionRefs.current[index] = el\n }}\n // Pointer down only PREVENTS the focus steal (a blur would\n // tear down the suggestion mid-select); selection happens on\n // click so mouse, touch, keyboard, and assistive-technology\n // synthesized activations all share the native path — and a\n // secondary-button press never inserts a mention.\n onMouseDown={(event) => {\n event.preventDefault()\n }}\n onClick={() => onSelect(item)}\n // Routes through the same path arrows use so the imperative\n // Enter/Tab handler (which reads `selectedRef`, not `selected`)\n // agrees with the row the pointer is over.\n onMouseEnter={() => move(index)}\n className={joinClasses(\n 'flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-sm',\n active ? 'bg-primary/10 text-foreground' : 'text-muted-foreground',\n )}\n >\n {renderItem ? (\n renderItem(item)\n ) : (\n <>\n <span className=\"truncate text-foreground\">{item.label}</span>\n {item.detail && (\n <span className=\"ml-auto truncate text-xs text-muted-foreground\">\n {item.detail}\n </span>\n )}\n </>\n )}\n </button>\n )\n })}\n </div>\n )\n },\n)\n","/**\n * Round-trip between the mention editor's document and the composer's plain\n * `value` string. A mention node serializes to `@<id>`; parsing restores a\n * pill only for ids the session already knows (fetched, inserted, or\n * restored), so unknown `@…` runs stay literal text.\n *\n * The document shape is kept structural (no TipTap import) so this round-trip\n * is unit-testable on its own and never pulls the editor chunk into a bundle.\n */\n\nimport { charAt, charBefore, PATH_CONTINUATION_CHAR, WORD_CHAR } from './mention-boundaries'\nimport type { MentionItem } from './use-file-mentions'\n\n/**\n * The subset of a TipTap/ProseMirror JSON document the mention editor\n * produces: a `doc` of paragraphs, each holding text, hard breaks, and atomic\n * mention nodes.\n */\nexport interface MentionDocNode {\n type: string\n text?: string\n attrs?: { id?: string | null; label?: string | null; kind?: string | null }\n content?: MentionDocNode[]\n}\n\nconst MENTION_TYPE = 'mention'\n\n/**\n * Plain-text serialization of the editor document. Paragraphs join with a\n * newline, hard breaks become a newline, and a mention node becomes `@<id>` —\n * the stable text form the controlled `value` carries.\n */\nexport function serializeMentionDoc(doc: MentionDocNode): string {\n return (doc.content ?? []).map(serializeBlock).join('\\n')\n}\n\nfunction serializeBlock(node: MentionDocNode): string {\n if (node.type === 'paragraph') {\n return (node.content ?? []).map(serializeInline).join('')\n }\n return ''\n}\n\nfunction serializeInline(node: MentionDocNode): string {\n if (node.type === 'text') return node.text ?? ''\n if (node.type === 'hardBreak') return '\\n'\n if (node.type === MENTION_TYPE) return `@${node.attrs?.id ?? ''}`\n return ''\n}\n\n/** Every mention node in the document, in order, as `MentionItem`s. */\nexport function collectMentions(doc: MentionDocNode): MentionItem[] {\n const out: MentionItem[] = []\n const walk = (node: MentionDocNode) => {\n if (node.type === MENTION_TYPE && node.attrs?.id) {\n out.push({\n id: node.attrs.id,\n label: node.attrs.label ?? node.attrs.id,\n kind: node.attrs.kind ?? undefined,\n })\n }\n for (const child of node.content ?? []) walk(child)\n }\n walk(doc)\n return out\n}\n\n/**\n * Parse a controlled `value` string back into an editor document. `@<id>`\n * runs that match a currently-known mention restore as atomic mention nodes;\n * every other `@…` stays literal text. Each line becomes a paragraph — a\n * deliberate asymmetry with `serializeMentionDoc`, which also flattens an\n * in-paragraph `hardBreak` to `\\n`: the string round-trips byte-identically,\n * but a restored Shift+Enter comes back as a paragraph break. The two render\n * identically under the composer's styling (no paragraph margins), so the\n * plain-text `value` contract stays the source of truth.\n */\nexport function parseMentionValue(\n value: string,\n known: Map<string, MentionItem>,\n): MentionDocNode {\n const lines = value.split('\\n')\n return {\n type: 'doc',\n content: lines.map((line) => ({\n type: 'paragraph',\n content: parseLine(line, known),\n })),\n }\n}\n\nfunction parseLine(line: string, known: Map<string, MentionItem>): MentionDocNode[] {\n const content: MentionDocNode[] = []\n let text = ''\n const flush = () => {\n if (text) {\n content.push({ type: 'text', text })\n text = ''\n }\n }\n\n let i = 0\n while (i < line.length) {\n // A word character right before the `@` means it is part of a longer\n // token (an email local part, a handle), never a mention start — the\n // same rule the transcript segmenter applies to persisted messages.\n // Read as a full code point: an astral letter's low surrogate would\n // fail WORD_CHAR and let an embedded `@` start a mention.\n const before = charBefore(line, i)\n const partOfLongerToken = before !== undefined && WORD_CHAR.test(before)\n if (line[i] === '@' && !partOfLongerToken) {\n const id = matchKnownId(line, i + 1, known)\n if (id) {\n const item = known.get(id)!\n flush()\n content.push({\n type: MENTION_TYPE,\n attrs: {\n id: item.id,\n label: item.label,\n kind: item.kind ?? null,\n },\n })\n i += 1 + id.length\n continue\n }\n }\n text += line[i]\n i += 1\n }\n flush()\n return content\n}\n\n/**\n * The longest known id that starts at `pos` and ends on a boundary: end of\n * line, or any full character (never a lone surrogate) that could not\n * continue the same path — the transcript segmenter's rule, so `@a.tsx,`\n * restores its pill while `@a.tsx.bak` never matches the shorter `a.tsx`\n * mid-filename. The scan is linear in `known.size` per `@` run on purpose:\n * `known` holds only the ids PICKED this session (a handful), never the\n * file index, so an index structure would buy nothing.\n */\nfunction matchKnownId(\n line: string,\n pos: number,\n known: Map<string, MentionItem>,\n): string | null {\n let best: string | null = null\n for (const id of known.keys()) {\n if (id.length === 0) continue\n if (best !== null && id.length <= best.length) continue\n if (!line.startsWith(id, pos)) continue\n const next = charAt(line, pos + id.length)\n if (next !== undefined && PATH_CONTINUATION_CHAR.test(next)) continue\n best = id\n }\n return best\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsBA,SAAS,aAAAA,YAAW,OAAO,UAAAC,SAAQ,YAAAC,iBAAoD;;;ACtBvF,SAAS,YAAY,WAAW,qBAAqB,QAAQ,gBAAgB;AAyHnE,SAiDQ,UAhDN,KADF;AAjFH,IAAM,cAAc;AAAA,EACzB,SAASC,aACP,EAAE,OAAO,SAAS,OAAO,YAAY,cAAc,YAAY,UAAU,IAAI,gBAAgB,UAAU,GACvG,KACA;AACA,UAAM,CAAC,UAAU,WAAW,IAAI,SAAS,CAAC;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YACb;AAAA,sBAAAA,MAAC,SAAI,KAAK,WAAW,WAAU,mBAAkB,OAAO,EAAE,WAAW,UAAU,GAC7E;AAAA,wBAAAD,KAAC,iBAAc,QAAgB;AAAA,QAC9B,MAAM,WAAW,KAChB,gBAAAA,KAAC,SAAI,WAAU,yFACZ,uBACH;AAAA,SAEJ;AAAA,MAMA,gBAAAA;AAAA,QAAC;AAAA;AAAA,UACC;AAAA,UACA,YAAY;AAAA,UACZ;AAAA,UACA,WAAU;AAAA,UAEV,0BAAAA;AAAA,YAAC;AAAA;AAAA,cACC,KAAK;AAAA,cACL,IAAI;AAAA,cACJ;AAAA,cACA;AAAA,cACA,OAAO;AAAA,cACP,WAAW,QAAQ;AAAA,cACnB,YAAY,QAAQ;AAAA,cACpB,UAAU,CAAC,SAAS,WAAW,UAAU,IAAI;AAAA,cAC7C,gBAAgB;AAAA,cAChB,WAAW,QAAQ;AAAA;AAAA,UACrB;AAAA;AAAA,MACF;AAAA,OACF;AAAA,EAEJ;AACF;","names":["useEffect","useRef","useState","MentionList","jsx","jsxs","useState","useRef","editor","useEffect"]}
|
|
1
|
+
{"version":3,"sources":["../src/web-react/mention-editor.tsx","../src/web-react/mention-list.tsx","../src/web-react/mention-serialize.ts"],"sourcesContent":["/**\n * The mention-capable rich input behind `ChatComposer`'s `mention` prop.\n *\n * The five `@tiptap/*` packages are OPTIONAL peers, and every value access to\n * them goes through `loadTiptapModules()`'s dynamic `import()` — never a\n * static named import. A bundler resolves a missing optional peer to a stub\n * module with a default export only, so a static `import { mergeAttributes }`\n * fails the CONSUMER'S build even when nothing ever renders the mention path\n * (measured against Vite 7's `__vite-optional-peer-dep` stub). The dynamic\n * form builds clean and defers the failure to the first actual editor load,\n * where it throws with the missing packages named — the same doctrine as\n * `sequences-react`'s transcription peer. Type-only imports are erased and\n * stay allowed.\n */\n\nimport type { MentionOptions } from '@tiptap/extension-mention'\nimport type { SuggestionKeyDownProps, SuggestionProps } from '@tiptap/suggestion'\nimport type * as TiptapCore from '@tiptap/core'\nimport type * as TiptapExtensionMention from '@tiptap/extension-mention'\nimport type * as TiptapReact from '@tiptap/react'\nimport type * as TiptapStarterKit from '@tiptap/starter-kit'\nimport type * as TiptapSuggestion from '@tiptap/suggestion'\nimport { useEffect, useId, useRef, useState, type ComponentType, type ReactNode } from 'react'\n\nimport { PopoverSurface } from './controls'\nimport { MENTION_PILL_CLASS } from './mention-pill'\nimport { MentionList, type MentionListHandle } from './mention-list'\nimport {\n collectMentions,\n parseMentionValue,\n serializeMentionDoc,\n type MentionDocNode,\n} from './mention-serialize'\nimport type { ComposerMentionProp, MentionItem } from './use-file-mentions'\n\n/** The loaded namespaces of the five optional peers, as one bag. */\nexport interface TiptapModules {\n core: typeof TiptapCore\n extensionMention: typeof TiptapExtensionMention\n react: typeof TiptapReact\n starterKit: typeof TiptapStarterKit\n suggestion: typeof TiptapSuggestion\n}\n\nconst PEERS_MISSING_MESSAGE =\n 'ChatComposer `mention` needs the @tiptap/* optional peers — install @tiptap/core, @tiptap/extension-mention, @tiptap/pm, @tiptap/react, @tiptap/starter-kit and @tiptap/suggestion (>=3.28.0 <4.0.0; @tiptap/suggestion also peers on @floating-ui/dom)'\n\n/** The rejection shapes bundlers produce for an UNINSTALLED module. Only\n * these get enriched with the install-set message — a transient chunk-fetch\n * failure keeps its own cause so diagnostics do not mislabel it as a missing\n * dependency. An unmatched resolution error stays unchanged, so the\n * classifier can only under-enrich. */\nconst RESOLUTION_FAILURE = /could not resolve|cannot find module|failed to resolve/i\n\n/** Resolve the optional peers, or throw naming every one of them. */\nexport async function loadTiptapModules(): Promise<TiptapModules> {\n let modules: TiptapModules\n try {\n const [core, extensionMention, react, starterKit, suggestion] = await Promise.all([\n import('@tiptap/core'),\n import('@tiptap/extension-mention'),\n import('@tiptap/react'),\n import('@tiptap/starter-kit'),\n import('@tiptap/suggestion'),\n ])\n modules = { core, extensionMention, react, starterKit, suggestion }\n } catch (error) {\n if (error instanceof Error && RESOLUTION_FAILURE.test(error.message)) {\n throw new Error(PEERS_MISSING_MESSAGE, { cause: error })\n }\n throw error\n }\n // A CommonJS-in-production bundler stubs a missing optional peer as a\n // SILENT empty namespace rather than a throwing module. Validate the\n // members the editor actually calls, so that shape still fails loud with\n // the peers named instead of as an undefined-property crash mid-render.\n if (\n typeof modules.core.mergeAttributes !== 'function' ||\n typeof modules.react.useEditor !== 'function' ||\n modules.react.EditorContent === undefined ||\n modules.extensionMention.default === undefined ||\n modules.starterKit.default === undefined ||\n typeof modules.suggestion.exitSuggestion !== 'function'\n ) {\n throw new Error(PEERS_MISSING_MESSAGE)\n }\n return modules\n}\n\nexport interface MentionEditorProps {\n value: string\n onChange: (value: string) => void\n /** Fired when Enter (no Shift, popover closed, not composing) should send. */\n onSubmit: () => void\n placeholder: string\n disabled?: boolean\n autoFocus?: boolean\n /** Pixel floor for the input box. The composer computes it from `minRows`\n * against its own line metrics, so the two input modes cannot drift. */\n minHeight: number\n /** Pixel height the input grows to before it scrolls. */\n maxHeight: number\n mention: ComposerMentionProp\n /** Basic input shown during server rendering and editor initialization. */\n fallback: ReactNode\n /** Registers a focus callback the composer wires to Cmd/Ctrl+L; called with\n * `null` on unmount so the composer never focuses a destroyed editor. */\n registerFocus?: (focus: (() => void) | null) => void\n /**\n * Clipboard files pulled off a paste. Returns true when consumed so the\n * editor suppresses its default text paste — the same funnel the textarea\n * path routes through to `onAttach`.\n */\n onPasteFiles?: (files: FileList) => boolean\n}\n\n/** Only text, hard breaks, and atomic mention pills — no marks, no formatting. */\nexport function buildComposerStarterKit(tiptap: TiptapModules) {\n return tiptap.starterKit.default.configure({\n blockquote: false,\n bold: false,\n bulletList: false,\n code: false,\n codeBlock: false,\n dropcursor: false,\n heading: false,\n horizontalRule: false,\n italic: false,\n link: false,\n listItem: false,\n listKeymap: false,\n orderedList: false,\n strike: false,\n trailingNode: false,\n underline: false,\n })\n}\n\n/**\n * The mention node: an inline atom (`inline: true, selectable: false,\n * atom: true` from `@tiptap/extension-mention`) carrying `{ id, label, kind }`,\n * rendered as a themed pill showing the label with the full id in `title`. Atom\n * means the cursor can't enter it and a single backspace removes the whole\n * thing. The `suggestion` config is supplied by the caller so the popover's\n * fetch/keyboard wiring stays in the component.\n */\nexport function buildMentionExtension(\n tiptap: TiptapModules,\n trigger: string,\n suggestion: MentionOptions['suggestion'],\n) {\n const { mergeAttributes } = tiptap.core\n return tiptap.extensionMention.default\n .extend({\n addAttributes() {\n return {\n id: {\n default: null,\n parseHTML: (element) => element.getAttribute('data-id'),\n renderHTML: (attrs) => (attrs.id ? { 'data-id': attrs.id } : {}),\n },\n label: {\n default: null,\n parseHTML: (element) => element.getAttribute('data-label'),\n renderHTML: (attrs) => (attrs.label ? { 'data-label': attrs.label } : {}),\n },\n kind: {\n default: null,\n parseHTML: (element) => element.getAttribute('data-kind'),\n renderHTML: (attrs) => (attrs.kind ? { 'data-kind': attrs.kind } : {}),\n },\n }\n },\n })\n .configure({\n HTMLAttributes: { class: MENTION_PILL_CLASS },\n renderText: ({ node }) => `${trigger}${node.attrs.id}`,\n renderHTML: ({ options, node }) => [\n 'span',\n mergeAttributes(options.HTMLAttributes, {\n title: node.attrs.id ?? undefined,\n }),\n `${trigger}${node.attrs.label ?? node.attrs.id}`,\n ],\n suggestion,\n })\n}\n\n/** Matches the composer textarea's own text treatment so the two input modes\n * render identically (`text-base leading-6`, the same padding). `outline-none`\n * is safe for the same reason as on that textarea: the composer card this\n * editor mounts into draws the keyboard indicator through `focus-within:`,\n * so a second outline inside the card would double the ring. */\nconst EDITOR_CLASS =\n 'w-full whitespace-pre-wrap break-words bg-transparent px-1.5 py-1 text-base leading-6 text-foreground outline-none'\n\n/** Trailing debounce on the suggestion fetch so a fast typist doesn't hit the\n * provider once per keystroke. Fixed rather than a prop — 100ms is well under\n * perceived latency and the monotonic `requestId` already makes any race\n * harmless, so there's no tuning knob worth exposing. */\nconst FETCH_DEBOUNCE_MS = 100\n\n/** Stable key for a mention set — order- and id-sensitive, ignores label/kind\n * so cosmetic re-fetches of the same id don't read as a change. JSON-encoded:\n * ids are workspace paths that may contain spaces, so a plain join would make\n * `[\"a b\",\"c\"]` and `[\"a\",\"b c\"]` collide and suppress a real change. */\nfunction mentionsKey(mentions: MentionItem[]): string {\n return JSON.stringify(mentions.map((item) => item.id))\n}\n\n/** `React.lazy` payload: resolve the peers, then build the component. */\nexport async function loadMentionEditor(): Promise<{\n default: ComponentType<MentionEditorProps>\n}> {\n return { default: createMentionEditor(await loadTiptapModules()) }\n}\n\n/**\n * Builds the mention-capable rich input against loaded tiptap modules. Loaded\n * lazily by `ChatComposer` so textarea-only consumers never pull TipTap into\n * their initial bundle. It preserves every textarea behavior — controlled\n * plain-text `value`, Enter to send / Shift+Enter for a newline, placeholder,\n * disabled, autofocus, file-paste routing — and adds `@`-mention pills backed\n * by an async provider.\n *\n * The suggestion list renders through `PopoverSurface` anchored to the input\n * box, like the composer's slash menu: an in-place panel is a panel the host\n * clips away (see the popover canon in AGENTS.md).\n */\nexport function createMentionEditor(tiptap: TiptapModules): ComponentType<MentionEditorProps> {\n const { EditorContent, useEditor } = tiptap.react\n const { exitSuggestion } = tiptap.suggestion\n\n return function MentionEditor({\n value,\n onChange,\n onSubmit,\n placeholder,\n disabled,\n autoFocus,\n minHeight,\n maxHeight,\n mention,\n fallback,\n registerFocus,\n onPasteFiles,\n }: MentionEditorProps) {\n const trigger = mention.trigger ?? '@'\n\n const [open, setOpen] = useState(false)\n const [query, setQuery] = useState('')\n const [items, setItems] = useState<MentionItem[]>([])\n const [loading, setLoading] = useState(false)\n const [errored, setErrored] = useState(false)\n // Mirror of the list's highlight, for `aria-activedescendant` — keyboard\n // focus never leaves the editor, so the highlighted row must be announced\n // through the editable element itself.\n const [activeIndex, setActiveIndex] = useState(0)\n const listboxId = useId()\n\n // The input box PopoverSurface anchors to, and the portaled panel itself.\n const anchorRef = useRef<HTMLDivElement>(null)\n const panelRef = useRef<HTMLDivElement>(null)\n\n // Live refs keep the once-built editor's callbacks reading current props\n // and state without rebuilding the editor (which would drop cursor +\n // content).\n const openRef = useRef(false)\n const commandRef = useRef<((item: MentionItem) => void) | null>(null)\n const listRef = useRef<MentionListHandle | null>(null)\n // Grows for the component's lifetime — one entry per distinct id the user\n // actually PICKED (or that arrived in the document as a mention node).\n // Deliberately never fed from fetch results: restore-eligibility must\n // track selection, not visibility. Uncapped; fine for a chat composer's\n // lifetime, worth an LRU only if this outlives that.\n const knownRef = useRef<Map<string, MentionItem>>(new Map())\n const requestIdRef = useRef(0)\n // Last mention-id set reported via `onMentionsChange`, so a programmatic\n // restore that lands on the same mentions doesn't re-fire the callback.\n // Seeded with the EMPTY-set key (not ''): the initial document can never\n // hold pills (`knownRef` starts empty), so the first computed key is the\n // empty set's — starting anywhere else fires a spurious `[]` callback.\n const lastMentionsKeyRef = useRef(mentionsKey([]))\n const onSubmitRef = useRef(onSubmit)\n onSubmitRef.current = onSubmit\n const onChangeRef = useRef(onChange)\n onChangeRef.current = onChange\n const onMentionsChangeRef = useRef(mention.onMentionsChange)\n onMentionsChangeRef.current = mention.onMentionsChange\n const onPasteFilesRef = useRef(onPasteFiles)\n onPasteFilesRef.current = onPasteFiles\n const fetchItemsRef = useRef(mention.fetchItems)\n fetchItemsRef.current = mention.fetchItems\n\n const editor = useEditor(\n {\n immediatelyRender: false,\n editable: !disabled,\n autofocus: autoFocus ? 'end' : false,\n content: parseMentionValue(value, knownRef.current),\n editorProps: {\n attributes: {\n class: EDITOR_CLASS,\n role: 'textbox',\n 'aria-multiline': 'true',\n 'aria-label': 'Message input',\n 'aria-haspopup': 'listbox',\n },\n handleKeyDown: (_view, event) => {\n if (event.key !== 'Enter' || event.shiftKey) return false\n // Composition (IME) commits via Enter — never send mid-composition.\n if (event.isComposing || event.keyCode === 229) return false\n // Popover open ⇒ Enter belongs to the suggestion plugin (selects).\n if (openRef.current) return false\n event.preventDefault()\n onSubmitRef.current()\n return true\n },\n handlePaste: (_view, event) => {\n const files = event.clipboardData?.files\n if (files && files.length > 0 && onPasteFilesRef.current) {\n return onPasteFilesRef.current(files)\n }\n return false\n },\n },\n onUpdate: ({ editor }) => {\n const json = editor.getJSON() as MentionDocNode\n onChangeRef.current(serializeMentionDoc(json))\n const mentions = collectMentions(json)\n for (const item of mentions) knownRef.current.set(item.id, item)\n // Report only when the mention SET changed — typing prose around an\n // unchanged pill must not re-fire the callback on every keystroke.\n const key = mentionsKey(mentions)\n if (key !== lastMentionsKeyRef.current) {\n lastMentionsKeyRef.current = key\n onMentionsChangeRef.current?.(mentions)\n }\n },\n extensions: [\n buildComposerStarterKit(tiptap),\n buildMentionExtension(tiptap, trigger, {\n char: trigger,\n allowSpaces: false,\n // Items are fetched by this component (so it can model loading and\n // error states), not by the suggestion plugin.\n items: () => [],\n command: ({ editor, range, props }) => {\n const item = props as unknown as MentionItem\n editor\n .chain()\n .focus()\n .insertContentAt(range, [\n {\n type: 'mention',\n attrs: {\n id: item.id,\n label: item.label,\n kind: item.kind ?? null,\n },\n },\n { type: 'text', text: ' ' },\n ])\n .run()\n knownRef.current.set(item.id, item)\n },\n render: () => ({\n onStart: (props: SuggestionProps) => {\n openRef.current = true\n commandRef.current = props.command\n setOpen(true)\n setQuery(props.query)\n },\n onUpdate: (props: SuggestionProps) => {\n commandRef.current = props.command\n setQuery(props.query)\n },\n onKeyDown: (props: SuggestionKeyDownProps) => {\n if (props.event.key === 'Escape') {\n exitSuggestion(props.view)\n return true\n }\n return listRef.current?.onKeyDown(props.event) ?? false\n },\n onExit: () => {\n openRef.current = false\n commandRef.current = null\n setOpen(false)\n setItems([])\n setLoading(false)\n setErrored(false)\n },\n }),\n }),\n ],\n },\n [],\n )\n\n // Fetch matches for the active query, trailing-debounced so a fast typist\n // doesn't hit the provider once per keystroke. The monotonic id still\n // drops stale responses (belt-and-suspenders against a provider that\n // resolves out of order); the debounce timer itself is cancelled by the\n // effect cleanup whenever `query` changes again before it fires.\n useEffect(() => {\n if (!open) return\n const requestId = (requestIdRef.current += 1)\n setLoading(true)\n setErrored(false)\n const timer = setTimeout(() => {\n // The provider is called INSIDE the chain so a synchronous throw lands\n // in the same `.catch` as a rejection — outside it, the exception\n // escapes the timer callback and the panel is stuck on \"Searching…\".\n Promise.resolve()\n .then(() => fetchItemsRef.current(query))\n .then((results) => {\n if (requestId !== requestIdRef.current) return\n // Results are NOT written into `knownRef`: merely appearing in a\n // suggestion list must not make an id restore-eligible, or a\n // later restore would promote prose the user typed (never picked)\n // into a structured mention. Only a pick (`command`) or a mention\n // already in the document teaches the restore path an id.\n setItems(results)\n setLoading(false)\n })\n .catch(() => {\n if (requestId !== requestIdRef.current) return\n setErrored(true)\n setLoading(false)\n })\n }, FETCH_DEBOUNCE_MS)\n return () => clearTimeout(timer)\n }, [open, query])\n\n // Programmatic `value` changes\n // re-parse into the document; `@<id>` runs come back as pills only for\n // ids already in `knownRef` at parse time. That conservatism is the\n // contract, not a gap: the serialized form cannot distinguish a PICKED\n // pill from `@text` the user simply typed (a pick is the only thing that\n // creates a mention in-session), so resolving unknown runs against the\n // provider at hydration would fabricate structured attachments from\n // plain prose. An id never fetched or inserted in this session therefore\n // stays literal text, exactly as it would have if typed. Guarded against\n // the onChange→value feedback loop by comparing the serialized form.\n //\n // `setContent` runs with `emitUpdate: false` (this is not a user edit),\n // so `onMentionsChange` — normally wired only off `onUpdate` — is fired\n // here explicitly, but only when the restored mention set actually\n // differs from the last one reported, so a restore that changes plain\n // text around unchanged mentions doesn't re-fire spuriously.\n useEffect(() => {\n if (!editor) return\n if (serializeMentionDoc(editor.getJSON() as MentionDocNode) === value) return\n const doc = parseMentionValue(value, knownRef.current)\n editor.commands.setContent(doc, { emitUpdate: false })\n const mentions = collectMentions(doc)\n const key = mentionsKey(mentions)\n if (key !== lastMentionsKeyRef.current) {\n lastMentionsKeyRef.current = key\n onMentionsChangeRef.current?.(mentions)\n }\n }, [editor, value])\n\n useEffect(() => {\n editor?.setEditable(!disabled)\n }, [editor, disabled])\n\n // Announce the popover through the editable element: focus stays in the\n // editor while ↑/↓ move the listbox highlight, so without\n // `aria-activedescendant` a screen reader hears nothing change. Set\n // imperatively — `editorProps.attributes` is fixed at editor creation.\n useEffect(() => {\n if (!editor) return\n const dom = editor.view.dom\n dom.setAttribute('aria-expanded', open ? 'true' : 'false')\n if (open) dom.setAttribute('aria-controls', listboxId)\n else dom.removeAttribute('aria-controls')\n const hasRows = open && !loading && !errored && items.length > 0\n if (hasRows) dom.setAttribute('aria-activedescendant', `${listboxId}-opt-${activeIndex}`)\n else dom.removeAttribute('aria-activedescendant')\n }, [editor, open, loading, errored, items.length, activeIndex, listboxId])\n\n useEffect(() => {\n if (!editor || !registerFocus) return\n registerFocus(() => editor.commands.focus())\n // Unregister on unmount so the composer's focus shortcut can never call\n // into a destroyed editor.\n return () => registerFocus(null)\n }, [editor, registerFocus])\n\n if (!editor) return fallback\n\n return (\n <div className=\"relative\">\n <div ref={anchorRef} className=\"overflow-y-auto\" style={{ maxHeight, minHeight }}>\n <EditorContent editor={editor} />\n {value.length === 0 && (\n <div className=\"pointer-events-none absolute left-1.5 top-1 text-base leading-6 text-muted-foreground\">\n {placeholder}\n </div>\n )}\n </div>\n\n {/* The panel's surface classes (and the consumer's `popoverClassName`)\n live on MentionList itself; the surface only places it. The outer\n scroll keeps rows reachable when the viewport cap undercuts the\n list's own max height. */}\n <PopoverSurface\n open={open}\n triggerRef={anchorRef}\n panelRef={panelRef}\n className=\"overflow-y-auto\"\n >\n <MentionList\n ref={listRef}\n id={listboxId}\n items={items}\n loading={loading}\n error={errored}\n emptyText={mention.emptyText}\n renderItem={mention.renderItem}\n onSelect={(item) => commandRef.current?.(item)}\n onActiveChange={setActiveIndex}\n className={mention.popoverClassName}\n />\n </PopoverSurface>\n </div>\n )\n }\n}\n","import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\n\nimport { joinClasses } from './class-names'\nimport type { MentionItem } from './use-file-mentions'\n\n/** Imperative surface the editor's suggestion keymap drives. */\nexport interface MentionListHandle {\n /** Returns true when the key was consumed — the editor must not also act. */\n onKeyDown: (event: KeyboardEvent) => boolean\n}\n\nexport interface MentionListProps {\n items: MentionItem[]\n loading: boolean\n error: boolean\n /** Shown when the fetch resolved to zero items. Default \"No matches\". */\n emptyText?: string\n renderItem?: (item: MentionItem) => ReactNode\n onSelect: (item: MentionItem) => void\n /** Root `role=\"listbox\"` element id; option rows derive stable ids from it\n * (`<id>-opt-<index>`) so the editor can point `aria-activedescendant` at\n * the highlighted row. */\n id?: string\n /** Fired whenever the highlight moves (keys, hover, or a result-set\n * re-home) — what keeps the editor's `aria-activedescendant` current. */\n onActiveChange?: (index: number) => void\n /** Extra classes merged onto the panel's root element, applied last so\n * they win over the component's own. */\n className?: string\n}\n\n/**\n * The mention suggestion list: a flat, keyboard-driven menu with loading,\n * empty, and error states. Selection is owned here so ↑/↓ and Enter/Tab\n * resolve against the highlighted row; every key it handles is reported\n * consumed so the composer's Enter-to-send never fires while open. The panel\n * carries its own surface classes but no positioning — the editor places it\n * through `PopoverSurface`, per the popover canon.\n */\nexport const MentionList = forwardRef<MentionListHandle, MentionListProps>(\n function MentionList(\n { items, loading, error, emptyText = 'No matches', renderItem, onSelect, id, onActiveChange, className },\n ref,\n ) {\n const [selected, setSelected] = useState(0)\n // Mirrors `selected` so the key handler reads the live index even when keys\n // arrive faster than React commits (e.g. synchronous test-driven calls).\n const selectedRef = useRef(0)\n const onActiveChangeRef = useRef(onActiveChange)\n onActiveChangeRef.current = onActiveChange\n // One entry per rendered row, so the highlight can be scrolled into view\n // from an effect (once per highlight move) instead of a ref callback\n // (which re-fires on every re-render of the row).\n const optionRefs = useRef<Array<HTMLButtonElement | null>>([])\n const move = (next: number) => {\n selectedRef.current = next\n setSelected(next)\n onActiveChangeRef.current?.(next)\n }\n\n // Keyboard navigation must keep the highlight visible inside the panel's\n // own scroll (`max-h-64 overflow-y-auto`).\n useEffect(() => {\n optionRefs.current[selected]?.scrollIntoView({ block: 'nearest' })\n }, [selected, items])\n\n // A new result set re-homes the highlight to the top.\n useEffect(() => {\n move(0)\n }, [items])\n\n useImperativeHandle(\n ref,\n () => ({\n onKeyDown(event) {\n // The handler must agree with the render: while loading or errored\n // the rows are not painted, so `items` still holding the PREVIOUS\n // query's results must not make Enter select an invisible file.\n const count = loading || error ? 0 : items.length\n switch (event.key) {\n case 'ArrowDown':\n if (count > 0) move((selectedRef.current + 1) % count)\n return true\n case 'ArrowUp':\n if (count > 0) move((selectedRef.current - 1 + count) % count)\n return true\n case 'Enter':\n // Consume even with nothing to select so the message never\n // submits while the popover is open. Clamp the index: a\n // shrunken result set re-homes the highlight in an effect, and\n // a key can arrive before that effect commits.\n if (count > 0) onSelect(items[Math.min(selectedRef.current, count - 1)]!)\n return true\n case 'Tab':\n // Tab selects only when a row exists; with nothing selectable\n // (loading, error, empty) it must fall through to normal focus\n // navigation — consuming it would trap keyboard focus.\n if (count === 0) return false\n onSelect(items[Math.min(selectedRef.current, count - 1)]!)\n return true\n default:\n return false\n }\n },\n }),\n [items, loading, error, onSelect],\n )\n\n return (\n <div\n role=\"listbox\"\n id={id}\n aria-label=\"File mentions\"\n className={joinClasses(\n 'max-h-64 min-w-[16rem] max-w-sm overflow-y-auto rounded-xl border border-border',\n 'bg-popover p-1 text-popover-foreground shadow-lg',\n className,\n )}\n >\n {loading && (\n <div className=\"flex items-center gap-2 px-2.5 py-2 text-sm text-muted-foreground\">\n <span className=\"h-3.5 w-3.5 animate-spin rounded-full border-2 border-primary border-t-transparent\" />\n Searching…\n </div>\n )}\n\n {!loading && error && (\n <div className=\"px-2.5 py-2 text-sm text-destructive\">Couldn’t load matches</div>\n )}\n\n {!loading && !error && items.length === 0 && (\n <div className=\"px-2.5 py-2 text-sm text-muted-foreground\">{emptyText}</div>\n )}\n\n {!loading &&\n !error &&\n items.map((item, index) => {\n const active = index === selected\n return (\n <button\n type=\"button\"\n key={item.id}\n id={id ? `${id}-opt-${index}` : undefined}\n role=\"option\"\n aria-selected={active}\n ref={(el) => {\n optionRefs.current[index] = el\n }}\n // Pointer down only PREVENTS the focus steal (a blur would\n // tear down the suggestion mid-select); selection happens on\n // click so mouse, touch, keyboard, and assistive-technology\n // synthesized activations all share the native path — and a\n // secondary-button press never inserts a mention.\n onMouseDown={(event) => {\n event.preventDefault()\n }}\n onClick={() => onSelect(item)}\n // Routes through the same path arrows use so the imperative\n // Enter/Tab handler (which reads `selectedRef`, not `selected`)\n // agrees with the row the pointer is over.\n onMouseEnter={() => move(index)}\n className={joinClasses(\n 'flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-sm',\n active ? 'bg-primary/10 text-foreground' : 'text-muted-foreground',\n )}\n >\n {renderItem ? (\n renderItem(item)\n ) : (\n <>\n <span className=\"truncate text-foreground\">{item.label}</span>\n {item.detail && (\n <span className=\"ml-auto truncate text-xs text-muted-foreground\">\n {item.detail}\n </span>\n )}\n </>\n )}\n </button>\n )\n })}\n </div>\n )\n },\n)\n","/**\n * Round-trip between the mention editor's document and the composer's plain\n * `value` string. A mention node serializes to `@<id>`; parsing restores a\n * pill only for ids the session already knows (fetched, inserted, or\n * restored), so unknown `@…` runs stay literal text.\n *\n * The document shape is kept structural (no TipTap import) so this round-trip\n * is unit-testable on its own and never pulls the editor chunk into a bundle.\n */\n\nimport { charAt, charBefore, PATH_CONTINUATION_CHAR, WORD_CHAR } from './mention-boundaries'\nimport type { MentionItem } from './use-file-mentions'\n\n/**\n * The subset of a TipTap/ProseMirror JSON document the mention editor\n * produces: a `doc` of paragraphs, each holding text, hard breaks, and atomic\n * mention nodes.\n */\nexport interface MentionDocNode {\n type: string\n text?: string\n attrs?: { id?: string | null; label?: string | null; kind?: string | null }\n content?: MentionDocNode[]\n}\n\nconst MENTION_TYPE = 'mention'\n\n/**\n * Plain-text serialization of the editor document. Paragraphs join with a\n * newline, hard breaks become a newline, and a mention node becomes `@<id>` —\n * the stable text form the controlled `value` carries.\n */\nexport function serializeMentionDoc(doc: MentionDocNode): string {\n return (doc.content ?? []).map(serializeBlock).join('\\n')\n}\n\nfunction serializeBlock(node: MentionDocNode): string {\n if (node.type === 'paragraph') {\n return (node.content ?? []).map(serializeInline).join('')\n }\n return ''\n}\n\nfunction serializeInline(node: MentionDocNode): string {\n if (node.type === 'text') return node.text ?? ''\n if (node.type === 'hardBreak') return '\\n'\n if (node.type === MENTION_TYPE) return `@${node.attrs?.id ?? ''}`\n return ''\n}\n\n/** Every mention node in the document, in order, as `MentionItem`s. */\nexport function collectMentions(doc: MentionDocNode): MentionItem[] {\n const out: MentionItem[] = []\n const walk = (node: MentionDocNode) => {\n if (node.type === MENTION_TYPE && node.attrs?.id) {\n out.push({\n id: node.attrs.id,\n label: node.attrs.label ?? node.attrs.id,\n kind: node.attrs.kind ?? undefined,\n })\n }\n for (const child of node.content ?? []) walk(child)\n }\n walk(doc)\n return out\n}\n\n/**\n * Parse a controlled `value` string back into an editor document. `@<id>`\n * runs that match a currently-known mention restore as atomic mention nodes;\n * every other `@…` stays literal text. Each line becomes a paragraph — a\n * deliberate asymmetry with `serializeMentionDoc`, which also flattens an\n * in-paragraph `hardBreak` to `\\n`: the string round-trips byte-identically,\n * but a restored Shift+Enter comes back as a paragraph break. The two render\n * identically under the composer's styling (no paragraph margins), so the\n * plain-text `value` contract stays the source of truth.\n */\nexport function parseMentionValue(\n value: string,\n known: Map<string, MentionItem>,\n): MentionDocNode {\n const lines = value.split('\\n')\n return {\n type: 'doc',\n content: lines.map((line) => ({\n type: 'paragraph',\n content: parseLine(line, known),\n })),\n }\n}\n\nfunction parseLine(line: string, known: Map<string, MentionItem>): MentionDocNode[] {\n const content: MentionDocNode[] = []\n let text = ''\n const flush = () => {\n if (text) {\n content.push({ type: 'text', text })\n text = ''\n }\n }\n\n let i = 0\n while (i < line.length) {\n // A word character right before the `@` means it is part of a longer\n // token (an email local part, a handle), never a mention start — the\n // same rule the transcript segmenter applies to persisted messages.\n // Read as a full code point: an astral letter's low surrogate would\n // fail WORD_CHAR and let an embedded `@` start a mention.\n const before = charBefore(line, i)\n const partOfLongerToken = before !== undefined && WORD_CHAR.test(before)\n if (line[i] === '@' && !partOfLongerToken) {\n const id = matchKnownId(line, i + 1, known)\n if (id) {\n const item = known.get(id)!\n flush()\n content.push({\n type: MENTION_TYPE,\n attrs: {\n id: item.id,\n label: item.label,\n kind: item.kind ?? null,\n },\n })\n i += 1 + id.length\n continue\n }\n }\n text += line[i]\n i += 1\n }\n flush()\n return content\n}\n\n/**\n * The longest known id that starts at `pos` and ends on a boundary: end of\n * line, or any full character (never a lone surrogate) that could not\n * continue the same path — the transcript segmenter's rule, so `@a.tsx,`\n * restores its pill while `@a.tsx.bak` never matches the shorter `a.tsx`\n * mid-filename. The scan is linear in `known.size` per `@` run on purpose:\n * `known` holds only the ids PICKED this session (a handful), never the\n * file index, so an index structure would buy nothing.\n */\nfunction matchKnownId(\n line: string,\n pos: number,\n known: Map<string, MentionItem>,\n): string | null {\n let best: string | null = null\n for (const id of known.keys()) {\n if (id.length === 0) continue\n if (best !== null && id.length <= best.length) continue\n if (!line.startsWith(id, pos)) continue\n const next = charAt(line, pos + id.length)\n if (next !== undefined && PATH_CONTINUATION_CHAR.test(next)) continue\n best = id\n }\n return best\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,SAAS,aAAAA,YAAW,OAAO,UAAAC,SAAQ,YAAAC,iBAAoD;;;ACtBvF,SAAS,YAAY,WAAW,qBAAqB,QAAQ,gBAAgB;AAyHnE,SAiDQ,UAhDN,KADF;AAjFH,IAAM,cAAc;AAAA,EACzB,SAASC,aACP,EAAE,OAAO,SAAS,OAAO,YAAY,cAAc,YAAY,UAAU,IAAI,gBAAgB,UAAU,GACvG,KACA;AACA,UAAM,CAAC,UAAU,WAAW,IAAI,SAAS,CAAC;AAG1C,UAAM,cAAc,OAAO,CAAC;AAC5B,UAAM,oBAAoB,OAAO,cAAc;AAC/C,sBAAkB,UAAU;AAI5B,UAAM,aAAa,OAAwC,CAAC,CAAC;AAC7D,UAAM,OAAO,CAAC,SAAiB;AAC7B,kBAAY,UAAU;AACt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yFACZ,uBACH;AAAA,SAEJ;AAAA,MAMA,gBAAAA;AAAA,QAAC;AAAA;AAAA,UACC;AAAA,UACA,YAAY;AAAA,UACZ;AAAA,UACA,WAAU;AAAA,UAEV,0BAAAA;AAAA,YAAC;AAAA;AAAA,cACC,KAAK;AAAA,cACL,IAAI;AAAA,cACJ;AAAA,cACA;AAAA,cACA,OAAO;AAAA,cACP,WAAW,QAAQ;AAAA,cACnB,YAAY,QAAQ;AAAA,cACpB,UAAU,CAAC,SAAS,WAAW,UAAU,IAAI;AAAA,cAC7C,gBAAgB;AAAA,cAChB,WAAW,QAAQ;AAAA;AAAA,UACrB;AAAA;AAAA,MACF;AAAA,OACF;AAAA,EAEJ;AACF;","names":["useEffect","useRef","useState","MentionList","jsx","jsxs","useState","useRef","editor","useEffect"]}
|
package/dist/run/index.js
CHANGED
package/dist/runtime/index.js
CHANGED
|
@@ -18,8 +18,9 @@ import {
|
|
|
18
18
|
buildCatalog,
|
|
19
19
|
fetchModelCatalog,
|
|
20
20
|
isChatCapableModel,
|
|
21
|
-
normalizeModelId
|
|
22
|
-
|
|
21
|
+
normalizeModelId,
|
|
22
|
+
sortModelsByFreshness
|
|
23
|
+
} from "../chunk-UEDFSZ3E.js";
|
|
23
24
|
|
|
24
25
|
// src/runtime/openai-stream.ts
|
|
25
26
|
async function* toLoopEvents(chunks) {
|
|
@@ -323,6 +324,7 @@ export {
|
|
|
323
324
|
resolveUserTangleExecutionKey,
|
|
324
325
|
resolveUserTangleExecutionKeyForUser,
|
|
325
326
|
runToolLoop as runAppToolLoop,
|
|
327
|
+
sortModelsByFreshness,
|
|
326
328
|
streamToolLoop as streamAppToolLoop,
|
|
327
329
|
tangleExecutionKeyHttpError,
|
|
328
330
|
toLoopEvents,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/openai-stream.ts","../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts","../../src/runtime/loop.ts"],"sourcesContent":["/**\n * OpenAI-compatible stream → `LoopEvent` adapter, for NON-sandbox copilots.\n *\n * `streamAppToolLoop` takes a `streamTurn` seam that yields `LoopEvent`s. A\n * sandboxed agent produces those from its container; a browser/edge copilot\n * instead calls a model directly. The Tangle Router, the tcloud SDK, and most\n * providers all speak the OpenAI Chat Completions streaming shape — so the ONE\n * reusable piece is assembling that stream (content deltas + FRAGMENTED\n * tool-call deltas) into `LoopEvent`s. That assembly is the boilerplate every\n * copilot would re-write (and get wrong — OpenAI streams tool-call arguments in\n * pieces across chunks).\n *\n * This does NOT implement an HTTP client beyond a minimal `fetch` + SSE reader\n * (browser/edge/Node-safe, zero deps). For richer transport use the tcloud SDK\n * or the Vercel AI SDK and pipe their stream through {@link toLoopEvents}.\n */\nimport type { LoopEvent, LoopMessage, LoopToolCall } from './loop'\nimport { normalizeModelId } from './model-catalog'\n\n/** Minimal OpenAI Chat Completions streaming chunk (structural — no `openai` dep). */\nexport interface OpenAIStreamChunk {\n /** The model that produced this chunk. The Tangle Router reports the DATED\n * upstream id here (`gpt-5-2025-08-07`) whether or not it substituted, so\n * this is a served-model source only after id folding — see\n * {@link OpenAICompatServedModel}. */\n model?: string\n choices?: Array<{\n delta?: {\n content?: string | null\n /** Reasoning deltas — DeepSeek/router use `reasoning_content`; some proxies use `thinking`. */\n reasoning_content?: string | null\n thinking?: string | null\n tool_calls?: Array<{\n index: number\n id?: string\n function?: { name?: string; arguments?: string }\n }>\n }\n finish_reason?: string | null\n }>\n /** Final-chunk token accounting (requires `stream_options.include_usage`). */\n usage?: {\n prompt_tokens?: number\n completion_tokens?: number\n } | null\n}\n\ninterface PartialToolCall {\n id?: string\n name: string\n args: string\n}\n\n/**\n * Map an OpenAI-compat streaming chunk iterator to `LoopEvent`s: each content\n * delta → a `text` event; tool-call deltas are accumulated by index across\n * chunks and emitted as one complete `tool_call` event when the stream finishes\n * (arguments JSON-parsed; an empty/garbled args string yields `{}` rather than\n * throwing). Works for the Tangle Router, tcloud, or any OpenAI-compat source.\n */\nexport async function* toLoopEvents(chunks: AsyncIterable<OpenAIStreamChunk>): AsyncIterable<LoopEvent> {\n const calls = new Map<number, PartialToolCall>()\n for await (const chunk of chunks) {\n // Usage rides the final chunk, which has an empty choices array — handle\n // it before the choice guard.\n if (chunk.usage?.prompt_tokens != null || chunk.usage?.completion_tokens != null) {\n yield {\n type: 'usage',\n usage: {\n promptTokens: chunk.usage.prompt_tokens ?? 0,\n completionTokens: chunk.usage.completion_tokens ?? 0,\n },\n }\n }\n const choice = chunk.choices?.[0]\n if (!choice) continue\n const content = choice.delta?.content\n if (content) yield { type: 'text', text: content }\n const reasoning = choice.delta?.reasoning_content ?? choice.delta?.thinking\n if (reasoning) yield { type: 'reasoning', text: reasoning }\n for (const tc of choice.delta?.tool_calls ?? []) {\n const cur = calls.get(tc.index) ?? { name: '', args: '' }\n if (tc.id) cur.id = tc.id\n if (tc.function?.name) cur.name += tc.function.name\n if (tc.function?.arguments) cur.args += tc.function.arguments\n calls.set(tc.index, cur)\n }\n }\n for (const [, c] of [...calls.entries()].sort((a, b) => a[0] - b[0])) {\n if (!c.name) continue\n yield { type: 'tool_call', call: { toolCallId: c.id, toolName: c.name, args: safeParse(c.args) } satisfies LoopToolCall }\n }\n}\n\nfunction safeParse(s: string): Record<string, unknown> {\n if (!s.trim()) return {}\n try {\n const v = JSON.parse(s)\n return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {}\n } catch {\n return {}\n }\n}\n\n/**\n * Which model actually served one direct-router turn.\n *\n * The router substitutes models on purpose — a quota-walled primary comes back\n * `200` answered by a different model — and says so in response headers. This\n * lane used to drop the whole `Response` after taking `.body`, so a turn\n * requested as `claude-sonnet-4-6` and answered by `openai/gpt-5` was recorded\n * by its caller as Claude: per-model quality scoring blamed the wrong model and\n * cost used the wrong price basis.\n *\n * Map this onto the shell's existing attribution contract rather than inventing\n * a second channel — `ChatTurnRouteProducer.modelAttribution()` (`/chat-routes`):\n *\n * modelAttribution: () => ({ requestedModel, servedModel, echoReceived: true })\n *\n * Leave that contract's `servedSource` unset: its union is sandbox\n * profile-resolution vocabulary with no router analogue.\n */\nexport interface OpenAICompatServedModel {\n /** The model id this turn asked for (`OpenAICompatStreamTurnOptions.model`). */\n requestedModel: string\n /** The model the router/provider reports having actually served. */\n servedModel: string\n /** Where `servedModel` was read from. The header is the router's own\n * substitution signal; the body is the backstop that survives CORS. */\n source: 'router_header' | 'response_body'\n /** True when served differs from requested after id folding. Folded, not\n * compared raw: the body reports a dated id on EVERY turn, so `!==` would\n * claim a substitution every time. */\n substituted: boolean\n /** `x-tangle-failover` `trigger=` — why the router swapped. Absent when the\n * router did not inject the substitute (a caller-supplied fallback chain\n * sets the served-model header without the failover one). */\n trigger?: string\n /** `x-tangle-failover` `degraded=`. */\n degraded?: boolean\n}\n\n/** Parse `from=…; to=…; trigger=…; degraded=…` down to the fields we report.\n * Absent/garbled segments are simply omitted — attribution is best-effort and\n * must never fail a turn that is otherwise streaming fine. */\nfunction parseFailoverHeader(raw: string | null): { trigger?: string; degraded?: boolean } {\n if (!raw) return {}\n const fields = new Map<string, string>()\n for (const segment of raw.split(';')) {\n const eq = segment.indexOf('=')\n if (eq === -1) continue\n fields.set(segment.slice(0, eq).trim().toLowerCase(), segment.slice(eq + 1).trim())\n }\n const trigger = fields.get('trigger')\n const degraded = fields.get('degraded')\n return {\n ...(trigger ? { trigger } : {}),\n ...(degraded != null ? { degraded: degraded === 'true' } : {}),\n }\n}\n\n/** Define options for configuring an OpenAI-compatible streaming chat turn including API details and tools */\nexport interface OpenAICompatStreamTurnOptions {\n /** OpenAI-compat base URL (e.g. the Tangle Router `https://router.tangle.tools/v1`). */\n baseUrl: string\n apiKey: string\n model: string\n /** OpenAI tool definitions — pass `buildAppToolOpenAITools(taxonomy)` so the\n * model can call the app tools. Omit for a tool-free copilot. */\n tools?: unknown[]\n temperature?: number\n fetchImpl?: typeof fetch\n /** Extra body fields (e.g. `max_tokens`). */\n extraBody?: Record<string, unknown>\n /**\n * Called at most ONCE per turn, as soon as the serving model is\n * determinable, with what actually answered. Never called when neither the\n * header nor the body names a model — silence means \"learned nothing\", not\n * \"nothing was substituted\".\n *\n * `streamTurn` runs once per TOOL turn, so a multi-turn `runAppToolLoop`\n * fires this once per turn; take the last for row attribution.\n */\n onServedModel?: (served: OpenAICompatServedModel) => void\n}\n\n/**\n * Build a `streamTurn` that calls an OpenAI-compatible `/chat/completions`\n * endpoint (Tangle Router / tcloud / any compat provider) with `stream: true`\n * and yields `LoopEvent`s via {@link toLoopEvents}. Browser/edge/Node-safe —\n * just `fetch` + an SSE reader. Drop straight into `streamAppToolLoop`:\n *\n * const cfg = resolveTangleModelConfig() // or { baseUrl, apiKey, model }\n * streamAppToolLoop({ streamTurn: createOpenAICompatStreamTurn({ ...cfg, tools }), executeToolCall, ... })\n */\nexport function createOpenAICompatStreamTurn(\n opts: OpenAICompatStreamTurnOptions,\n): (messages: LoopMessage[]) => AsyncIterable<LoopEvent> {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const doFetch = opts.fetchImpl ?? fetch\n return (messages) =>\n toLoopEvents(\n streamChatCompletions(doFetch, `${base}/chat/completions`, opts.apiKey, {\n model: opts.model,\n messages,\n stream: true,\n stream_options: { include_usage: true },\n ...(opts.tools && opts.tools.length > 0 ? { tools: opts.tools } : {}),\n ...(opts.temperature != null ? { temperature: opts.temperature } : {}),\n ...opts.extraBody,\n }, opts.onServedModel ? { requestedModel: opts.model, report: opts.onServedModel } : undefined),\n )\n}\n\n/** Stream + parse an OpenAI-compat SSE response into chunks. Tolerates `data:`\n * framing, multi-line buffers, and the terminal `[DONE]`. */\nasync function* streamChatCompletions(\n doFetch: typeof fetch,\n url: string,\n apiKey: string,\n body: Record<string, unknown>,\n attribution?: { requestedModel: string; report: (served: OpenAICompatServedModel) => void },\n): AsyncIterable<OpenAIStreamChunk> {\n const res = await doFetch(url, {\n method: 'POST',\n headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'text/event-stream' },\n body: JSON.stringify(body),\n })\n if (!res.ok || !res.body) {\n const text = res.body ? await res.text().catch(() => '') : ''\n const error = new Error(`OpenAI-compat stream failed (HTTP ${res.status})${text ? `: ${text.slice(0, 200)}` : ''}`)\n // Stamp the NUMERIC status. `isUpstreamUnavailable` (`/model-resolution`)\n // reads a numeric field first and prose only as a backstop, and a\n // Cloudflare EDGE 502 gives it nothing else to read: `content-type:\n // text/plain`, a body of `error code: 502`, and none of the router's own\n // `x-tangle-*` headers, because the origin never ran. Carrying the status\n // as data keeps THIS path — the browser/edge copilot lane, which calls the\n // router directly — out of the string-matching business entirely.\n Object.assign(error, { status: res.status })\n throw error\n }\n // Served-model attribution, fired at most once, as early as it is knowable.\n //\n // The header comes first because it is the router's OWN substitution signal:\n // `X-Tangle-Served-Model` is set only when the served model differs from the\n // requested one, so its presence is authoritative and it arrives before the\n // first byte of content. `X-Tangle-Failover` rides along only when the router\n // itself picked the substitute (a caller-supplied fallback chain sets the\n // former without the latter), which is why `trigger`/`degraded` are optional.\n //\n // The body is the backstop for when the header cannot reach us. In a BROWSER,\n // headers are invisible to JS unless the server lists them in\n // `Access-Control-Expose-Headers` — tangle-router#324 added both, but that\n // only helps once it is DEPLOYED, and any other OpenAI-compat endpoint\n // pointed at this client exposes nothing. The chunk `model` field is not\n // subject to CORS, so it keeps the browser lane attributable regardless.\n let reported = false\n const report = (served: OpenAICompatServedModel): void => {\n if (reported || !attribution) return\n reported = true\n attribution.report(served)\n }\n if (attribution) {\n const servedHeader = res.headers.get('x-tangle-served-model')\n if (servedHeader) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: servedHeader,\n source: 'router_header',\n substituted: normalizeModelId(servedHeader) !== normalizeModelId(attribution.requestedModel),\n ...parseFailoverHeader(res.headers.get('x-tangle-failover')),\n })\n }\n }\n const reader = res.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) continue\n const data = trimmed.slice(5).trim()\n if (data === '[DONE]') return\n let chunk: OpenAIStreamChunk\n try {\n chunk = JSON.parse(data) as OpenAIStreamChunk\n } catch {\n continue /* skip a partial/garbled SSE frame */\n }\n // Body fallback: only when the header said nothing. Fold both ids before\n // comparing — the router reports the dated upstream id (`gpt-5-2025-08-07`)\n // for a request of `openai/gpt-5` even with NO substitution, so a raw\n // `!==` would report a swap on literally every turn.\n if (attribution && !reported && chunk.model) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: chunk.model,\n source: 'response_body',\n substituted: normalizeModelId(chunk.model) !== normalizeModelId(attribution.requestedModel),\n })\n }\n yield chunk\n }\n }\n}\n","/**\n * `createCertifiedDelivery` — the delivery truck for Tangle Intelligence.\n *\n * Pulls a tenant's CERTIFIED `AgentProfile` from the deployed plane\n * (`GET /v1/profiles/:target/composed`) and applies it to the agent's resolved\n * surfaces each turn, so an approved improvement reaches the running agent with\n * NO redeploy. This is the `composeProfile` transform `createAgentRuntime`\n * accepts — opt-in per product, fail-closed, cached + refreshed.\n *\n * Profile-WIDE by design (not prompt-only): the composed profile carries every\n * promoted artifact type keyed by kind. What's folded where:\n * - `prompt-surface` + `skill` → the system prompt (via `composeCertifiedPrompt`).\n * - `tool` artifacts that carry an OpenAI tool definition → `extraTools`\n * (advertised to the model; the matching executor is supplied by the product\n * via `executeOtherTool`). Until a `tool` artifact carries a runnable def,\n * it is surfaced (see `current()`) but not advertised — advertising a tool\n * with no executor would make the model call into a dead end.\n * - `mcp` / `memory` / `rag` artifacts materialize as servers/files and deliver\n * through the SANDBOX-provisioning seam, not this in-process one. The full\n * certified profile is exposed via `current()` so that seam can consume it.\n *\n * Substrate boundary: THIS module imports `@tangle-network/agent-runtime`; the\n * `createAgentRuntime` core does not (it only consumes the generic transform).\n */\n\nimport {\n composeCertifiedPrompt,\n type CertifiedProfile,\n pullCertified,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\nconst defaultRefreshMs = 300_000\n\n/** Define configuration options for delivering certified artifacts to a specified tenant target */\nexport interface CertifiedDeliveryConfig {\n /** The tenant target whose certified artifacts to deliver (the agent id). */\n target: string\n /** Bearer for the plane. Reads `TANGLE_API_KEY` when omitted. */\n apiKey?: string\n /** Plane base URL. Reads `TANGLE_INTELLIGENCE_URL` then the public plane. */\n baseUrl?: string\n /** Min interval between certified-profile pulls. Default 5m. */\n refreshMs?: number\n /** fetch impl (tests / non-global-fetch runtimes). */\n fetchImpl?: typeof fetch\n}\n\n/** Resolve and manage certified profiles with refresh and composition capabilities */\nexport interface CertifiedDelivery {\n /** The `composeProfile` transform to pass to `createAgentRuntime`. Applies the\n * cached certified profile to the base surfaces; refreshes on the cadence. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now (ignores the refresh window). Best-effort. */\n refresh(): Promise<void>\n /** The certified profile currently in effect (null = none promoted / pull\n * failed). Lets the sandbox-provisioning seam deliver the file/server\n * artifact types this in-process seam doesn't. */\n current(): CertifiedProfile | null\n}\n\n/**\n * Build a certified-delivery transform for one agent target. Fail-closed: a pull\n * error or 404 keeps the last-known certified profile (or null), and the agent\n * runs on its base surfaces — it never breaks because Intelligence is down.\n */\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const refreshMs = config.refreshMs ?? defaultRefreshMs\n let certified: CertifiedProfile | null = null\n let lastPullAt = 0\n let inflight: Promise<void> | null = null\n\n async function refresh(force = false): Promise<void> {\n if (!force && Date.now() - lastPullAt < refreshMs) return\n if (inflight) return inflight\n inflight = (async () => {\n const outcome = await pullCertified({\n target: config.target,\n apiKey: config.apiKey,\n baseUrl: config.baseUrl,\n fetchImpl: config.fetchImpl,\n })\n lastPullAt = Date.now()\n // Only replace on a real pull; a 404/error keeps the last-known profile.\n if (outcome.succeeded) certified = outcome.value\n })()\n try {\n await inflight\n } finally {\n inflight = null\n }\n }\n\n return {\n async composeProfile(base) {\n await refresh()\n return {\n // prompt-surface + skill fold into the system prompt.\n systemPrompt: composeCertifiedPrompt(base.systemPrompt, certified),\n // Certified `tool` artifacts deliver here once they carry a runnable\n // OpenAI def + the product wires the executor; until then pass through.\n extraTools: base.extraTools,\n }\n },\n refresh: () => refresh(true),\n current: () => certified,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value into `SandboxRuntimeConfig.env` at box creation. The\n * value must be deterministic for the box's lifetime (an HMAC over the\n * workspace id, e.g. `createCapabilityToken` in ../tools), because a freshly\n * random per-request mint would never match what the box already carries.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_SEVERITY)) {\n throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`)\n }\n }\n }\n}\n","/**\n * The bounded agent tool-loop — owned by `@tangle-network/agent-runtime`.\n *\n * A model turn may emit tool calls (integration-hub actions, the app tools from\n * `../tools`, delegation). The loop streams a turn, collects the executable tool\n * calls, dispatches each, appends the results to history in OpenAI\n * function-calling shape, and re-runs so the model reads them — bounded by\n * `maxToolTurns`, a wall-clock `deadlineMs`, and a `maxCostUsd` budget.\n *\n * The history shape is the OpenAI function-calling contract: the assistant turn\n * that emitted tool calls is preserved as an `assistant` message carrying its\n * `tool_calls` array, and each result is its own `{ role: 'tool', tool_call_id,\n * content }` message keyed to the call. A strict model (Claude, and any\n * OpenAI-compatible provider that validates tool history) needs this to read its\n * own tool use back; folding results into a `user` message makes such models\n * re-issue the same call in a loop.\n *\n * The loop is substrate-owned (`runToolLoop` / `streamToolLoop`); the app\n * supplies `streamTurn` (wrapping its model endpoint) and `executeToolCall`\n * (routing to its integration + app-tool executors). The app-facing names below\n * are 1:1 aliases of the canonical symbols, kept so this package's consumers and\n * the in-package `createAgentRuntime` read against a single, stable vocabulary.\n *\n * This is the LEAF the runtime barrel and its children both import — keeping the\n * tool-loop vocabulary out of any import cycle. The barrel re-exports it.\n */\n\nexport {\n runToolLoop as runAppToolLoop,\n streamToolLoop as streamAppToolLoop,\n} from '@tangle-network/agent-runtime/tool-loop'\nexport type {\n ToolLoopCall as LoopToolCall,\n ToolLoopAssistantToolCall as LoopAssistantToolCall,\n ToolLoopMessage as LoopMessage,\n ToolLoopEvent,\n ToolLoopStopReason,\n ToolLoopResult,\n RunToolLoopOptions as AppToolLoopOptions,\n StreamToolLoopOptions as StreamAppToolLoopOptions,\n StreamToolLoopYield as StreamLoopYield,\n} from '@tangle-network/agent-runtime/tool-loop'\n\n/**\n * Events the app's OpenAI-compat stream adapter ({@link toLoopEvents}) yields.\n *\n * This is the app's own `Raw` event type for the streaming loop — the canonical\n * `streamToolLoop<Raw>` is generic over it. It widens the substrate's\n * tool-loop event with `reasoning` (DeepSeek/router `reasoning_content` /\n * `thinking` deltas, rendered as thinking sections) and `usage` (per-message\n * token accounting) — neither belongs in the substrate's loop contract, so they\n * stay here. The adapter maps each into the `streamTurn` seam; `text` and\n * `tool_call` drive the loop, `reasoning` / `usage` pass through to the UI.\n */\nexport type LoopEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | {\n type: 'tool_call'\n call: import('@tangle-network/agent-runtime/tool-loop').ToolLoopCall\n }\n | { type: 'usage'; usage: { promptTokens: number; completionTokens: number } }\n | { type: 'other'; event: unknown }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA4DA,gBAAuB,aAAa,QAAoE;AACtG,QAAM,QAAQ,oBAAI,IAA6B;AAC/C,mBAAiB,SAAS,QAAQ;AAGhC,QAAI,MAA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W,GAAG;AAC5F,YAAM,IAAI,MAAM,GAAG,KAAK,2DAA2D;AAAA,IACrF;AAAA,EACF;AACA,MAAI,QAAQ,QAAQ,QAAW;AAC7B,eAAW,CAAC,MAAM,MAAM,KAAK,OAAO,QAAQ,QAAQ,GAAG,GAAG;AACxD,UAAI,KAAK,KAAK,EAAE,WAAW,EAAG,OAAM,IAAI,MAAM,GAAG,KAAK,sCAAsC;AAC5F,UAAI,OAAO,cAAc,QAAQ;AAC/B,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,oCAAoC,KAAK,UAAW,OAAmC,SAAS,CAAC,GAAG;AAAA,MACnJ;AACA,UAAI;AACJ,UAAI;AACF,iBAAS,IAAI,IAAI,OAAO,GAAG;AAAA,MAC7B,QAAQ;AACN,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,sCAAsC,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAClH;AACA,UAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UAAU;AAC/D,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,8BAA8B,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAC1G;AAAA,IACF;AAAA,EACF;AACA,MAAI,QAAQ,gBAAgB,QAAW;AACrC,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,WAAW,GAAG;AAC9D,UAAI,EAAE,SAAS,sBAAsB;AACnC,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,GAAG,2CAA2C,KAAK,UAAU,KAAK,CAAC,GAAG;AAAA,MACjH;AAAA,IACF;AAAA,EACF;AACF;;;AC/MA;AAAA,EACiB;AAAA,EACG;AAAA,OACb;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/openai-stream.ts","../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts","../../src/runtime/loop.ts"],"sourcesContent":["/**\n * OpenAI-compatible stream → `LoopEvent` adapter, for NON-sandbox copilots.\n *\n * `streamAppToolLoop` takes a `streamTurn` seam that yields `LoopEvent`s. A\n * sandboxed agent produces those from its container; a browser/edge copilot\n * instead calls a model directly. The Tangle Router, the tcloud SDK, and most\n * providers all speak the OpenAI Chat Completions streaming shape — so the ONE\n * reusable piece is assembling that stream (content deltas + FRAGMENTED\n * tool-call deltas) into `LoopEvent`s. That assembly is the boilerplate every\n * copilot would re-write (and get wrong — OpenAI streams tool-call arguments in\n * pieces across chunks).\n *\n * This does NOT implement an HTTP client beyond a minimal `fetch` + SSE reader\n * (browser/edge/Node-safe, zero deps). For richer transport use the tcloud SDK\n * or the Vercel AI SDK and pipe their stream through {@link toLoopEvents}.\n */\nimport type { LoopEvent, LoopMessage, LoopToolCall } from './loop'\nimport { normalizeModelId } from './model-catalog'\n\n/** Minimal OpenAI Chat Completions streaming chunk (structural — no `openai` dep). */\nexport interface OpenAIStreamChunk {\n /** The model that produced this chunk. The Tangle Router reports the DATED\n * upstream id here (`gpt-5-2025-08-07`) whether or not it substituted, so\n * this is a served-model source only after id folding — see\n * {@link OpenAICompatServedModel}. */\n model?: string\n choices?: Array<{\n delta?: {\n content?: string | null\n /** Reasoning deltas — DeepSeek/router use `reasoning_content`; some proxies use `thinking`. */\n reasoning_content?: string | null\n thinking?: string | null\n tool_calls?: Array<{\n index: number\n id?: string\n function?: { name?: string; arguments?: string }\n }>\n }\n finish_reason?: string | null\n }>\n /** Final-chunk token accounting (requires `stream_options.include_usage`). */\n usage?: {\n prompt_tokens?: number\n completion_tokens?: number\n } | null\n}\n\ninterface PartialToolCall {\n id?: string\n name: string\n args: string\n}\n\n/**\n * Map an OpenAI-compat streaming chunk iterator to `LoopEvent`s: each content\n * delta → a `text` event; tool-call deltas are accumulated by index across\n * chunks and emitted as one complete `tool_call` event when the stream finishes\n * (arguments JSON-parsed; an empty/garbled args string yields `{}` rather than\n * throwing). Works for the Tangle Router, tcloud, or any OpenAI-compat source.\n */\nexport async function* toLoopEvents(chunks: AsyncIterable<OpenAIStreamChunk>): AsyncIterable<LoopEvent> {\n const calls = new Map<number, PartialToolCall>()\n for await (const chunk of chunks) {\n // Usage rides the final chunk, which has an empty choices array — handle\n // it before the choice guard.\n if (chunk.usage?.prompt_tokens != null || chunk.usage?.completion_tokens != null) {\n yield {\n type: 'usage',\n usage: {\n promptTokens: chunk.usage.prompt_tokens ?? 0,\n completionTokens: chunk.usage.completion_tokens ?? 0,\n },\n }\n }\n const choice = chunk.choices?.[0]\n if (!choice) continue\n const content = choice.delta?.content\n if (content) yield { type: 'text', text: content }\n const reasoning = choice.delta?.reasoning_content ?? choice.delta?.thinking\n if (reasoning) yield { type: 'reasoning', text: reasoning }\n for (const tc of choice.delta?.tool_calls ?? []) {\n const cur = calls.get(tc.index) ?? { name: '', args: '' }\n if (tc.id) cur.id = tc.id\n if (tc.function?.name) cur.name += tc.function.name\n if (tc.function?.arguments) cur.args += tc.function.arguments\n calls.set(tc.index, cur)\n }\n }\n for (const [, c] of [...calls.entries()].sort((a, b) => a[0] - b[0])) {\n if (!c.name) continue\n yield { type: 'tool_call', call: { toolCallId: c.id, toolName: c.name, args: safeParse(c.args) } satisfies LoopToolCall }\n }\n}\n\nfunction safeParse(s: string): Record<string, unknown> {\n if (!s.trim()) return {}\n try {\n const v = JSON.parse(s)\n return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {}\n } catch {\n return {}\n }\n}\n\n/**\n * Which model actually served one direct-router turn.\n *\n * The router substitutes models on purpose — a quota-walled primary comes back\n * `200` answered by a different model — and says so in response headers. This\n * lane used to drop the whole `Response` after taking `.body`, so a turn\n * requested as `claude-sonnet-4-6` and answered by `openai/gpt-5` was recorded\n * by its caller as Claude: per-model quality scoring blamed the wrong model and\n * cost used the wrong price basis.\n *\n * Map this onto the shell's existing attribution contract rather than inventing\n * a second channel — `ChatTurnRouteProducer.modelAttribution()` (`/chat-routes`):\n *\n * modelAttribution: () => ({ requestedModel, servedModel, echoReceived: true })\n *\n * Leave that contract's `servedSource` unset: its union is sandbox\n * profile-resolution vocabulary with no router analogue.\n */\nexport interface OpenAICompatServedModel {\n /** The model id this turn asked for (`OpenAICompatStreamTurnOptions.model`). */\n requestedModel: string\n /** The model the router/provider reports having actually served. */\n servedModel: string\n /** Where `servedModel` was read from. The header is the router's own\n * substitution signal; the body is the backstop that survives CORS. */\n source: 'router_header' | 'response_body'\n /** True when served differs from requested after id folding. Folded, not\n * compared raw: the body reports a dated id on EVERY turn, so `!==` would\n * claim a substitution every time. */\n substituted: boolean\n /** `x-tangle-failover` `trigger=` — why the router swapped. Absent when the\n * router did not inject the substitute (a caller-supplied fallback chain\n * sets the served-model header without the failover one). */\n trigger?: string\n /** `x-tangle-failover` `degraded=`. */\n degraded?: boolean\n}\n\n/** Parse `from=…; to=…; trigger=…; degraded=…` down to the fields we report.\n * Absent/garbled segments are simply omitted — attribution is best-effort and\n * must never fail a turn that is otherwise streaming fine. */\nfunction parseFailoverHeader(raw: string | null): { trigger?: string; degraded?: boolean } {\n if (!raw) return {}\n const fields = new Map<string, string>()\n for (const segment of raw.split(';')) {\n const eq = segment.indexOf('=')\n if (eq === -1) continue\n fields.set(segment.slice(0, eq).trim().toLowerCase(), segment.slice(eq + 1).trim())\n }\n const trigger = fields.get('trigger')\n const degraded = fields.get('degraded')\n return {\n ...(trigger ? { trigger } : {}),\n ...(degraded != null ? { degraded: degraded === 'true' } : {}),\n }\n}\n\n/** Define options for configuring an OpenAI-compatible streaming chat turn including API details and tools */\nexport interface OpenAICompatStreamTurnOptions {\n /** OpenAI-compat base URL (e.g. the Tangle Router `https://router.tangle.tools/v1`). */\n baseUrl: string\n apiKey: string\n model: string\n /** OpenAI tool definitions — pass `buildAppToolOpenAITools(taxonomy)` so the\n * model can call the app tools. Omit for a tool-free copilot. */\n tools?: unknown[]\n temperature?: number\n fetchImpl?: typeof fetch\n /** Extra body fields (e.g. `max_tokens`). */\n extraBody?: Record<string, unknown>\n /**\n * Called at most ONCE per turn, as soon as the serving model is\n * determinable, with what actually answered. Never called when neither the\n * header nor the body names a model — silence means \"learned nothing\", not\n * \"nothing was substituted\".\n *\n * `streamTurn` runs once per TOOL turn, so a multi-turn `runAppToolLoop`\n * fires this once per turn; take the last for row attribution.\n */\n onServedModel?: (served: OpenAICompatServedModel) => void\n}\n\n/**\n * Build a `streamTurn` that calls an OpenAI-compatible `/chat/completions`\n * endpoint (Tangle Router / tcloud / any compat provider) with `stream: true`\n * and yields `LoopEvent`s via {@link toLoopEvents}. Browser/edge/Node-safe —\n * just `fetch` + an SSE reader. Drop straight into `streamAppToolLoop`:\n *\n * const cfg = resolveTangleModelConfig() // or { baseUrl, apiKey, model }\n * streamAppToolLoop({ streamTurn: createOpenAICompatStreamTurn({ ...cfg, tools }), executeToolCall, ... })\n */\nexport function createOpenAICompatStreamTurn(\n opts: OpenAICompatStreamTurnOptions,\n): (messages: LoopMessage[]) => AsyncIterable<LoopEvent> {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const doFetch = opts.fetchImpl ?? fetch\n return (messages) =>\n toLoopEvents(\n streamChatCompletions(doFetch, `${base}/chat/completions`, opts.apiKey, {\n model: opts.model,\n messages,\n stream: true,\n stream_options: { include_usage: true },\n ...(opts.tools && opts.tools.length > 0 ? { tools: opts.tools } : {}),\n ...(opts.temperature != null ? { temperature: opts.temperature } : {}),\n ...opts.extraBody,\n }, opts.onServedModel ? { requestedModel: opts.model, report: opts.onServedModel } : undefined),\n )\n}\n\n/** Stream + parse an OpenAI-compat SSE response into chunks. Tolerates `data:`\n * framing, multi-line buffers, and the terminal `[DONE]`. */\nasync function* streamChatCompletions(\n doFetch: typeof fetch,\n url: string,\n apiKey: string,\n body: Record<string, unknown>,\n attribution?: { requestedModel: string; report: (served: OpenAICompatServedModel) => void },\n): AsyncIterable<OpenAIStreamChunk> {\n const res = await doFetch(url, {\n method: 'POST',\n headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'text/event-stream' },\n body: JSON.stringify(body),\n })\n if (!res.ok || !res.body) {\n const text = res.body ? await res.text().catch(() => '') : ''\n const error = new Error(`OpenAI-compat stream failed (HTTP ${res.status})${text ? `: ${text.slice(0, 200)}` : ''}`)\n // Stamp the NUMERIC status. `isUpstreamUnavailable` (`/model-resolution`)\n // reads a numeric field first and prose only as a backstop, and a\n // Cloudflare EDGE 502 gives it nothing else to read: `content-type:\n // text/plain`, a body of `error code: 502`, and none of the router's own\n // `x-tangle-*` headers, because the origin never ran. Carrying the status\n // as data keeps THIS path — the browser/edge copilot lane, which calls the\n // router directly — out of the string-matching business entirely.\n Object.assign(error, { status: res.status })\n throw error\n }\n // Served-model attribution, fired at most once, as early as it is knowable.\n //\n // The header comes first because it is the router's OWN substitution signal:\n // `X-Tangle-Served-Model` is set only when the served model differs from the\n // requested one, so its presence is authoritative and it arrives before the\n // first byte of content. `X-Tangle-Failover` rides along only when the router\n // itself picked the substitute (a caller-supplied fallback chain sets the\n // former without the latter), which is why `trigger`/`degraded` are optional.\n //\n // The body is the backstop for when the header cannot reach us. In a BROWSER,\n // headers are invisible to JS unless the server lists them in\n // `Access-Control-Expose-Headers` — tangle-router#324 added both, but that\n // only helps once it is DEPLOYED, and any other OpenAI-compat endpoint\n // pointed at this client exposes nothing. The chunk `model` field is not\n // subject to CORS, so it keeps the browser lane attributable regardless.\n let reported = false\n const report = (served: OpenAICompatServedModel): void => {\n if (reported || !attribution) return\n reported = true\n attribution.report(served)\n }\n if (attribution) {\n const servedHeader = res.headers.get('x-tangle-served-model')\n if (servedHeader) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: servedHeader,\n source: 'router_header',\n substituted: normalizeModelId(servedHeader) !== normalizeModelId(attribution.requestedModel),\n ...parseFailoverHeader(res.headers.get('x-tangle-failover')),\n })\n }\n }\n const reader = res.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) continue\n const data = trimmed.slice(5).trim()\n if (data === '[DONE]') return\n let chunk: OpenAIStreamChunk\n try {\n chunk = JSON.parse(data) as OpenAIStreamChunk\n } catch {\n continue /* skip a partial/garbled SSE frame */\n }\n // Body fallback: only when the header said nothing. Fold both ids before\n // comparing — the router reports the dated upstream id (`gpt-5-2025-08-07`)\n // for a request of `openai/gpt-5` even with NO substitution, so a raw\n // `!==` would report a swap on literally every turn.\n if (attribution && !reported && chunk.model) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: chunk.model,\n source: 'response_body',\n substituted: normalizeModelId(chunk.model) !== normalizeModelId(attribution.requestedModel),\n })\n }\n yield chunk\n }\n }\n}\n","/**\n * `createCertifiedDelivery` — the delivery truck for Tangle Intelligence.\n *\n * Pulls a tenant's CERTIFIED `AgentProfile` from the deployed plane\n * (`GET /v1/profiles/:target/composed`) and applies it to the agent's resolved\n * surfaces each turn, so an approved improvement reaches the running agent with\n * NO redeploy. This is the `composeProfile` transform `createAgentRuntime`\n * accepts — opt-in per product, fail-closed, cached + refreshed.\n *\n * Profile-WIDE by design (not prompt-only): the composed profile carries every\n * promoted artifact type keyed by kind. What's folded where:\n * - `prompt-surface` + `skill` → the system prompt (via `composeCertifiedPrompt`).\n * - `tool` artifacts that carry an OpenAI tool definition → `extraTools`\n * (advertised to the model; the matching executor is supplied by the product\n * via `executeOtherTool`). Until a `tool` artifact carries a runnable def,\n * it is surfaced (see `current()`) but not advertised — advertising a tool\n * with no executor would make the model call into a dead end.\n * - `mcp` / `memory` / `rag` artifacts materialize as servers/files and deliver\n * through the SANDBOX-provisioning seam, not this in-process one. The full\n * certified profile is exposed via `current()` so that seam can consume it.\n *\n * Substrate boundary: THIS module imports `@tangle-network/agent-runtime`; the\n * `createAgentRuntime` core does not (it only consumes the generic transform).\n */\n\nimport {\n composeCertifiedPrompt,\n type CertifiedProfile,\n pullCertified,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\nconst defaultRefreshMs = 300_000\n\n/** Define configuration options for delivering certified artifacts to a specified tenant target */\nexport interface CertifiedDeliveryConfig {\n /** The tenant target whose certified artifacts to deliver (the agent id). */\n target: string\n /** Bearer for the plane. Reads `TANGLE_API_KEY` when omitted. */\n apiKey?: string\n /** Plane base URL. Reads `TANGLE_INTELLIGENCE_URL` then the public plane. */\n baseUrl?: string\n /** Min interval between certified-profile pulls. Default 5m. */\n refreshMs?: number\n /** fetch impl (tests / non-global-fetch runtimes). */\n fetchImpl?: typeof fetch\n}\n\n/** Resolve and manage certified profiles with refresh and composition capabilities */\nexport interface CertifiedDelivery {\n /** The `composeProfile` transform to pass to `createAgentRuntime`. Applies the\n * cached certified profile to the base surfaces; refreshes on the cadence. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now (ignores the refresh window). Best-effort. */\n refresh(): Promise<void>\n /** The certified profile currently in effect (null = none promoted / pull\n * failed). Lets the sandbox-provisioning seam deliver the file/server\n * artifact types this in-process seam doesn't. */\n current(): CertifiedProfile | null\n}\n\n/**\n * Build a certified-delivery transform for one agent target. Fail-closed: a pull\n * error or 404 keeps the last-known certified profile (or null), and the agent\n * runs on its base surfaces — it never breaks because Intelligence is down.\n */\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const refreshMs = config.refreshMs ?? defaultRefreshMs\n let certified: CertifiedProfile | null = null\n let lastPullAt = 0\n let inflight: Promise<void> | null = null\n\n async function refresh(force = false): Promise<void> {\n if (!force && Date.now() - lastPullAt < refreshMs) return\n if (inflight) return inflight\n inflight = (async () => {\n const outcome = await pullCertified({\n target: config.target,\n apiKey: config.apiKey,\n baseUrl: config.baseUrl,\n fetchImpl: config.fetchImpl,\n })\n lastPullAt = Date.now()\n // Only replace on a real pull; a 404/error keeps the last-known profile.\n if (outcome.succeeded) certified = outcome.value\n })()\n try {\n await inflight\n } finally {\n inflight = null\n }\n }\n\n return {\n async composeProfile(base) {\n await refresh()\n return {\n // prompt-surface + skill fold into the system prompt.\n systemPrompt: composeCertifiedPrompt(base.systemPrompt, certified),\n // Certified `tool` artifacts deliver here once they carry a runnable\n // OpenAI def + the product wires the executor; until then pass through.\n extraTools: base.extraTools,\n }\n },\n refresh: () => refresh(true),\n current: () => certified,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value into `SandboxRuntimeConfig.env` at box creation. The\n * value must be deterministic for the box's lifetime (an HMAC over the\n * workspace id, e.g. `createCapabilityToken` in ../tools), because a freshly\n * random per-request mint would never match what the box already carries.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_SEVERITY)) {\n throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`)\n }\n }\n }\n}\n","/**\n * The bounded agent tool-loop — owned by `@tangle-network/agent-runtime`.\n *\n * A model turn may emit tool calls (integration-hub actions, the app tools from\n * `../tools`, delegation). The loop streams a turn, collects the executable tool\n * calls, dispatches each, appends the results to history in OpenAI\n * function-calling shape, and re-runs so the model reads them — bounded by\n * `maxToolTurns`, a wall-clock `deadlineMs`, and a `maxCostUsd` budget.\n *\n * The history shape is the OpenAI function-calling contract: the assistant turn\n * that emitted tool calls is preserved as an `assistant` message carrying its\n * `tool_calls` array, and each result is its own `{ role: 'tool', tool_call_id,\n * content }` message keyed to the call. A strict model (Claude, and any\n * OpenAI-compatible provider that validates tool history) needs this to read its\n * own tool use back; folding results into a `user` message makes such models\n * re-issue the same call in a loop.\n *\n * The loop is substrate-owned (`runToolLoop` / `streamToolLoop`); the app\n * supplies `streamTurn` (wrapping its model endpoint) and `executeToolCall`\n * (routing to its integration + app-tool executors). The app-facing names below\n * are 1:1 aliases of the canonical symbols, kept so this package's consumers and\n * the in-package `createAgentRuntime` read against a single, stable vocabulary.\n *\n * This is the LEAF the runtime barrel and its children both import — keeping the\n * tool-loop vocabulary out of any import cycle. The barrel re-exports it.\n */\n\nexport {\n runToolLoop as runAppToolLoop,\n streamToolLoop as streamAppToolLoop,\n} from '@tangle-network/agent-runtime/tool-loop'\nexport type {\n ToolLoopCall as LoopToolCall,\n ToolLoopAssistantToolCall as LoopAssistantToolCall,\n ToolLoopMessage as LoopMessage,\n ToolLoopEvent,\n ToolLoopStopReason,\n ToolLoopResult,\n RunToolLoopOptions as AppToolLoopOptions,\n StreamToolLoopOptions as StreamAppToolLoopOptions,\n StreamToolLoopYield as StreamLoopYield,\n} from '@tangle-network/agent-runtime/tool-loop'\n\n/**\n * Events the app's OpenAI-compat stream adapter ({@link toLoopEvents}) yields.\n *\n * This is the app's own `Raw` event type for the streaming loop — the canonical\n * `streamToolLoop<Raw>` is generic over it. It widens the substrate's\n * tool-loop event with `reasoning` (DeepSeek/router `reasoning_content` /\n * `thinking` deltas, rendered as thinking sections) and `usage` (per-message\n * token accounting) — neither belongs in the substrate's loop contract, so they\n * stay here. The adapter maps each into the `streamTurn` seam; `text` and\n * `tool_call` drive the loop, `reasoning` / `usage` pass through to the UI.\n */\nexport type LoopEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | {\n type: 'tool_call'\n call: import('@tangle-network/agent-runtime/tool-loop').ToolLoopCall\n }\n | { type: 'usage'; usage: { promptTokens: number; completionTokens: number } }\n | { type: 'other'; event: unknown }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,gBAAuB,aAAa,QAAoE;AACtG,QAAM,QAAQ,oBAAI,IAA6B;AAC/C,mBAAiB,SAAS,QAAQ;AAGhC,QAAI,MAAM,OAAO,iBAAiB,QAAQ,M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I,MAAM,GAAG,KAAK,2DAA2D;AAAA,IACrF;AAAA,EACF;AACA,MAAI,QAAQ,QAAQ,QAAW;AAC7B,eAAW,CAAC,MAAM,MAAM,KAAK,OAAO,QAAQ,QAAQ,GAAG,GAAG;AACxD,UAAI,KAAK,KAAK,EAAE,WAAW,EAAG,OAAM,IAAI,MAAM,GAAG,KAAK,sCAAsC;AAC5F,UAAI,OAAO,cAAc,QAAQ;AAC/B,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,oCAAoC,KAAK,UAAW,OAAmC,SAAS,CAAC,GAAG;AAAA,MACnJ;AACA,UAAI;AACJ,UAAI;AACF,iBAAS,IAAI,IAAI,OAAO,GAAG;AAAA,MAC7B,QAAQ;AACN,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,sCAAsC,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAClH;AACA,UAAI,OAAO,aAAa,WAAW,OAAO,aAAa,UAAU;AAC/D,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,IAAI,8BAA8B,KAAK,UAAU,OAAO,GAAG,CAAC,GAAG;AAAA,MAC1G;AAAA,IACF;AAAA,EACF;AACA,MAAI,QAAQ,gBAAgB,QAAW;AACrC,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,WAAW,GAAG;AAC9D,UAAI,EAAE,SAAS,sBAAsB;AACnC,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,GAAG,2CAA2C,KAAK,UAAU,KAAK,CAAC,GAAG;AAAA,MACjH;AAAA,IACF;AAAA,EACF;AACF;;;AC/MA;AAAA,EACiB;AAAA,EACG;AAAA,OACb;","names":[]}
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* duplicate canonical ones. This module turns that into a product catalogue:
|
|
10
10
|
*
|
|
11
11
|
* filter (chat-capable, routeable) → dedupe (snapshot/prefix/:free aliases)
|
|
12
|
-
* → rank (provider tier,
|
|
12
|
+
* → rank (provider tier, current generation) → feature (best model per family)
|
|
13
13
|
* → default (env override or first featured)
|
|
14
14
|
*
|
|
15
15
|
* Freshness is automatic: everything is derived from the live router response,
|
|
@@ -64,6 +64,14 @@ export interface ModelCatalog {
|
|
|
64
64
|
}
|
|
65
65
|
/** Strip provider prefix, :free suffix, and trailing date stamps. */
|
|
66
66
|
export declare function normalizeModelId(id: string): string;
|
|
67
|
+
/**
|
|
68
|
+
* Return a copy sorted for a model menu.
|
|
69
|
+
*
|
|
70
|
+
* Providers keep the shared display order. Within each provider, current
|
|
71
|
+
* generations come first across families. Stable ids win ties with previews.
|
|
72
|
+
* Callers can sort separate sections without changing `featured` or defaults.
|
|
73
|
+
*/
|
|
74
|
+
export declare function sortModelsByFreshness(models: readonly CatalogModel[]): CatalogModel[];
|
|
67
75
|
/**
|
|
68
76
|
* Can this router entry serve a text chat turn?
|
|
69
77
|
*
|
package/dist/sandbox/index.d.ts
CHANGED
|
@@ -611,6 +611,13 @@ export declare function mergeHistoryIntoParts(parts: PromptInputPart[], history?
|
|
|
611
611
|
export declare function mergeExtraMcp(appToolMcp: Record<string, AgentProfileMcpServer>, baseProfileMcp: Record<string, AgentProfileMcpServer>, extra: Record<string, AgentProfileMcpServer> | undefined): Record<string, AgentProfileMcpServer>;
|
|
612
612
|
/** Attach a specified reasoning effort level to an agent profile for a given harness */
|
|
613
613
|
export declare function attachReasoningEffort(profile: AgentProfile, harness: Harness, effort: 'auto' | ReasoningEffort | undefined): AgentProfile;
|
|
614
|
+
export interface SandboxPromptTokenLimits {
|
|
615
|
+
maxVisibleOutputTokens?: number;
|
|
616
|
+
maxReasoningTokens?: number;
|
|
617
|
+
maxTotalOutputTokens?: number;
|
|
618
|
+
}
|
|
619
|
+
/** Tighten the profile's provider-enforced token ceilings for one prompt. */
|
|
620
|
+
export declare function applyPromptTokenLimits(profile: AgentProfile, limits: SandboxPromptTokenLimits): AgentProfile;
|
|
614
621
|
/** Define options for configuring and controlling a streaming sandbox prompt session */
|
|
615
622
|
export interface StreamSandboxPromptOptions {
|
|
616
623
|
sessionId?: string;
|
|
@@ -628,6 +635,12 @@ export interface StreamSandboxPromptOptions {
|
|
|
628
635
|
}>;
|
|
629
636
|
harness?: Harness;
|
|
630
637
|
effort?: 'auto' | ReasoningEffort;
|
|
638
|
+
/** Provider-enforced visible answer ceiling for this turn. */
|
|
639
|
+
maxOutputTokens?: number;
|
|
640
|
+
/** Provider-enforced hidden reasoning ceiling for this turn. */
|
|
641
|
+
maxReasoningTokens?: number;
|
|
642
|
+
/** Provider-enforced combined answer and reasoning ceiling for this turn. */
|
|
643
|
+
maxTotalOutputTokens?: number;
|
|
631
644
|
appToolMcp?: Record<string, AgentProfileMcpServer>;
|
|
632
645
|
baseProfileMcp?: Record<string, AgentProfileMcpServer>;
|
|
633
646
|
extraMcp?: Record<string, AgentProfileMcpServer>;
|
|
@@ -660,9 +673,29 @@ export interface SandboxStreamEvent {
|
|
|
660
673
|
};
|
|
661
674
|
delta?: string;
|
|
662
675
|
finalText?: string;
|
|
676
|
+
code?: string;
|
|
677
|
+
message?: string;
|
|
678
|
+
details?: Record<string, unknown>;
|
|
663
679
|
inputRequired?: {
|
|
664
680
|
prompt?: string;
|
|
665
681
|
};
|
|
682
|
+
usage?: {
|
|
683
|
+
inputTokens?: number;
|
|
684
|
+
outputTokens?: number;
|
|
685
|
+
reasoningTokens?: number;
|
|
686
|
+
toolTokens?: number;
|
|
687
|
+
toolCallCount?: number;
|
|
688
|
+
providerCostUsd?: number;
|
|
689
|
+
budgetEnforced?: boolean;
|
|
690
|
+
};
|
|
691
|
+
tool?: {
|
|
692
|
+
name?: string;
|
|
693
|
+
inputTokens?: number;
|
|
694
|
+
outputTokens?: number;
|
|
695
|
+
};
|
|
696
|
+
reasoning?: {
|
|
697
|
+
tokens?: number;
|
|
698
|
+
};
|
|
666
699
|
};
|
|
667
700
|
}
|
|
668
701
|
/** Normalize raw sandbox events for shared agent-gateway consumers. */
|
package/dist/sandbox/index.js
CHANGED
|
@@ -27,6 +27,7 @@ import {
|
|
|
27
27
|
WORKSPACE_SANDBOX_UNRECOVERABLE,
|
|
28
28
|
WorkspaceSandboxRecoveryRequiredError,
|
|
29
29
|
adaptSandboxStream,
|
|
30
|
+
applyPromptTokenLimits,
|
|
30
31
|
assertEnvWithinLimits,
|
|
31
32
|
assertProvisionPayloadWithinCap,
|
|
32
33
|
assessWorkspaceSandboxSnapshot,
|
|
@@ -98,8 +99,8 @@ import {
|
|
|
98
99
|
workspaceSandboxRecoveryMessage,
|
|
99
100
|
workspaceSandboxRecoveryRecommendedActions,
|
|
100
101
|
writeProfileFilesToBox
|
|
101
|
-
} from "../chunk-
|
|
102
|
-
import "../chunk-
|
|
102
|
+
} from "../chunk-N55NM3W2.js";
|
|
103
|
+
import "../chunk-MCYJON3F.js";
|
|
103
104
|
import "../chunk-LWSJK546.js";
|
|
104
105
|
import "../chunk-P5PIAQVS.js";
|
|
105
106
|
import "../chunk-KBJL6LIW.js";
|
|
@@ -136,6 +137,7 @@ export {
|
|
|
136
137
|
WORKSPACE_SANDBOX_UNRECOVERABLE,
|
|
137
138
|
WorkspaceSandboxRecoveryRequiredError,
|
|
138
139
|
adaptSandboxStream,
|
|
140
|
+
applyPromptTokenLimits,
|
|
139
141
|
assertEnvWithinLimits,
|
|
140
142
|
assertProvisionPayloadWithinCap,
|
|
141
143
|
assessWorkspaceSandboxSnapshot,
|
|
@@ -38,7 +38,7 @@ import {
|
|
|
38
38
|
} from "../chunk-TY2DALJG.js";
|
|
39
39
|
import {
|
|
40
40
|
useInfiniteScroll
|
|
41
|
-
} from "../chunk-
|
|
41
|
+
} from "../chunk-MLJQYITH.js";
|
|
42
42
|
import {
|
|
43
43
|
CheckGlyph,
|
|
44
44
|
ChevronDown,
|
|
@@ -48,8 +48,9 @@ import {
|
|
|
48
48
|
PopoverSurface,
|
|
49
49
|
ProviderLogo,
|
|
50
50
|
usePopover
|
|
51
|
-
} from "../chunk-
|
|
51
|
+
} from "../chunk-TIQKVTOD.js";
|
|
52
52
|
import "../chunk-SJWIZT7B.js";
|
|
53
|
+
import "../chunk-UEDFSZ3E.js";
|
|
53
54
|
|
|
54
55
|
// src/studio-react/use-studio-generations.ts
|
|
55
56
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|