@agent-native/core 0.49.6 → 0.49.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +6 -2
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent/types.d.ts +6 -1
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/agent/types.js.map +1 -1
- package/dist/cli/app-skill.d.ts.map +1 -1
- package/dist/cli/app-skill.js +21 -5
- package/dist/cli/app-skill.js.map +1 -1
- package/dist/cli/connect.d.ts.map +1 -1
- package/dist/cli/connect.js +46 -2
- package/dist/cli/connect.js.map +1 -1
- package/dist/cli/pr-visual-recap-workflow.d.ts +1 -1
- package/dist/cli/pr-visual-recap-workflow.d.ts.map +1 -1
- package/dist/cli/pr-visual-recap-workflow.js +1 -1
- package/dist/cli/pr-visual-recap-workflow.js.map +1 -1
- package/dist/cli/recap.d.ts +6 -11
- package/dist/cli/recap.d.ts.map +1 -1
- package/dist/cli/recap.js +14 -24
- package/dist/cli/recap.js.map +1 -1
- package/dist/client/agent-chat-adapter.d.ts.map +1 -1
- package/dist/client/agent-chat-adapter.js +30 -11
- package/dist/client/agent-chat-adapter.js.map +1 -1
- package/dist/client/blocks/library/AnnotatedCodeBlock.d.ts.map +1 -1
- package/dist/client/blocks/library/AnnotatedCodeBlock.js +20 -4
- package/dist/client/blocks/library/AnnotatedCodeBlock.js.map +1 -1
- package/dist/client/blocks/library/DiffBlock.d.ts.map +1 -1
- package/dist/client/blocks/library/DiffBlock.js +33 -9
- package/dist/client/blocks/library/DiffBlock.js.map +1 -1
- package/dist/client/blocks/library/annotation-rail.d.ts +41 -3
- package/dist/client/blocks/library/annotation-rail.d.ts.map +1 -1
- package/dist/client/blocks/library/annotation-rail.js +157 -29
- package/dist/client/blocks/library/annotation-rail.js.map +1 -1
- package/dist/client/blocks/types.d.ts +19 -0
- package/dist/client/blocks/types.d.ts.map +1 -1
- package/dist/client/blocks/types.js.map +1 -1
- package/dist/client/sse-event-processor.d.ts.map +1 -1
- package/dist/client/sse-event-processor.js +13 -12
- package/dist/client/sse-event-processor.js.map +1 -1
- package/dist/vite/client.d.ts.map +1 -1
- package/dist/vite/client.js +6 -8
- package/dist/vite/client.js.map +1 -1
- package/docs/content/pr-visual-recap.md +11 -12
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/client/blocks/types.ts"],"names":[],"mappings":"AAkXA,qEAAqE;AACrE,MAAM,UAAU,WAAW,CAAQ,IAAsB;IACvD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { FC } from \"react\";\nimport type { ZodType } from \"zod\";\n\n/**\n * Block-registry contract. A `BlockSpec` describes one document block end to end:\n * its data shape (`schema`), how it round-trips to MDX source (`mdx`), how it\n * renders read-only (`Read`) and how it is edited (`Edit`, or an auto-generated\n * schema-driven editor when omitted), where it can be placed (`placement`), and\n * metadata for menus / agent schema export.\n *\n * The registry runs ALONGSIDE existing per-block code (the plan `PlanBlockView`\n * switch + `serializeBlock`/`parseBlock`). Renderers check the registry first;\n * unregistered block types fall through to the legacy code path unchanged. The\n * MDX `tag` and attribute shape for a converted block MUST match the historical\n * encoding (e.g. `<Callout tone>…body…</Callout>`) so stored `.mdx` files still\n * parse byte-compatibly.\n */\n\n/** Where a block can be placed in a document. */\nexport type BlockPlacement = \"block\" | \"inline\";\n\n/**\n * A serialized MDX/NFM attribute value before the shared `prop()` encoder runs.\n * `prop()` decides string-vs-JSON encoding; this is just the value domain.\n */\nexport type MdxAttrValue =\n | string\n | number\n | boolean\n | unknown[]\n | Record<string, unknown>;\n\n/**\n * Type-narrowed reader over the resolved MDX attributes of a parsed block node.\n * The values are already estree/JSON-resolved by the shared attribute reader\n * (the same engine `plan-mdx.ts` uses), so a spec's `fromAttrs` never touches\n * the AST directly.\n */\nexport interface BlockAttrReader {\n string(name: string): string | undefined;\n number(name: string): number | undefined;\n bool(name: string): boolean | undefined;\n array<T = unknown>(name: string): T[] | undefined;\n object<T = unknown>(name: string): T | undefined;\n raw(name: string): unknown;\n}\n\n/**\n * Maps a block's validated data to/from its MDX component representation.\n * `tag` is the JSX component name in source (e.g. \"Callout\"). It MUST match the\n * historical name in `plan-mdx.ts` `BLOCK_COMPONENTS` / stored `.mdx` files or\n * existing plans break.\n */\nexport interface BlockMdxConfig<TData> {\n /** JSX component name in MDX source. Stable contract — never rename. */\n tag: string;\n /**\n * Encode `data` → a flat attribute bag. The registry serializer runs each\n * value through the shared `prop()` encoder (string-vs-JSON heuristic) and\n * preserves insertion order, so write the keys in the exact historical order.\n * Return `undefined` for a key (or omit it) to drop the attribute. When\n * `childrenField` is set, that field is excluded from the attribute bag.\n */\n toAttrs: (data: TData) => Record<string, MdxAttrValue | undefined>;\n /**\n * Decode resolved attributes (+ optional children markdown) → data. Must\n * tolerate missing/partial attributes for backward-compat (mirror today's\n * `?? []` / `?? \"\"` defaults).\n */\n fromAttrs: (attrs: BlockAttrReader, children: string) => TData;\n /**\n * When set, this data field is a markdown string serialized as MDX *children*\n * between the open/close tags (prose-bearing blocks: rich-text, callout)\n * rather than as a prop — so the body survives as real, inline-editable MDX\n * prose in source.\n */\n childrenField?: keyof TData & string;\n /**\n * Opt-in custom children serializer for blocks whose internals are nested MDX\n * components rather than a single markdown string (e.g. wireframe → Screen/kit\n * primitives). When present it overrides `childrenField`. `serializeChildren`\n * returns the raw inner MDX; `parseChildren` receives the child MDX AST nodes.\n */\n serializeChildren?: (data: TData) => string;\n parseChildren?: (childNodes: unknown[], idContext: string) => Partial<TData>;\n}\n\n/**\n * App-injected capabilities. Core blocks stay app-agnostic by taking these\n * rather than importing app services — mirroring `createImageExtension`'s\n * `onImageUpload` injection. Provided via `BlockRegistryProvider`.\n */\nexport interface BlockRenderContext {\n /** Markdown dialect for the auto-editor's rich-text field. */\n dialect?: \"gfm\" | \"nfm\";\n /** Resolve an asset id → displayable URL. */\n resolveAssetSrc?: (assetId: string) => string | undefined;\n /** Open the shared asset picker (returns the chosen asset). */\n pickAsset?: () => Promise<{ assetId: string; url?: string } | null>;\n /** Upload a local file, returns a hosted URL. */\n uploadFile?: (file: File) => Promise<{ url: string; assetId?: string }>;\n /** Call an app action by name (for blocks that fetch live data). */\n callAction?: (name: string, args: unknown) => Promise<unknown>;\n /** Sanitizer for HTML-bearing blocks. Provided by the app/core. */\n sanitizeHtml?: (html: string, css?: string) => string;\n /**\n * Render a markdown string with the app's read-only markdown renderer. Lets a\n * core block (whose `Read` lives in core) defer prose rendering to the app's\n * markdown reader (e.g. the plan `PlanMarkdownReader`) without importing it.\n */\n renderMarkdown?: (\n markdown: string,\n options?: { className?: string },\n ) => React.ReactNode;\n /**\n * Static capture mode: render every code/diff line annotation as a visible\n * inline overlay instead of requiring hover.\n */\n showCodeAnnotationOverlays?: boolean;\n /**\n * Render an inline, editable rich-markdown field. The auto-editor calls this\n * for a `markdown()`-tagged field so the app owns the editor wiring (collab,\n * autosave debounce, dialect) rather than core hardcoding it.\n */\n renderMarkdownEditor?: (props: {\n value: string;\n onChange: (next: string) => void;\n editable: boolean;\n blockId?: string;\n className?: string;\n ariaLabel?: string;\n }) => React.ReactNode;\n /**\n * Render an app-owned edit-by-prompt affordance (\"Describe a change…\") for a focused/editable block\n * field. Core block editors pass the current field value and nearby companion\n * fields; the host app decides how to collect the prompt and route it to the\n * agent sidebar. This keeps reusable core blocks from importing app-specific\n * popover/composer code while still exposing a generic AI edit hook.\n */\n renderAiFieldAction?: (props: BlockAiFieldActionProps) => React.ReactNode;\n /**\n * Render a nested child block through the app's own block dispatcher. Container\n * blocks whose `Read`/`Edit` live in core (e.g. tabs) call this to render each\n * child so the recursion keeps flowing through the SAME app renderer the\n * top-level document uses — registered children render via their spec, and\n * unregistered (not-yet-converted) children still fall through the app's legacy\n * switch. This is the coexistence seam: a core container never has to know\n * about app-specific child block types. Returns `null`/`undefined` when no\n * dispatcher is wired (read-only/SSR-only contexts can omit it).\n */\n renderBlock?: (props: {\n block: NestedBlock;\n /** Commit a replacement for this child block (edit mode only). */\n onChange?: (next: NestedBlock) => void;\n /** Whether the parent container is being edited. */\n editing?: boolean;\n /** Tighten embedded visuals in dense contexts (e.g. tab panes). */\n compactVisuals?: boolean;\n }) => React.ReactNode;\n /**\n * Render a nested editable block list through the host app's document editor.\n * Container blocks such as columns call this for each editable region so slash\n * commands, nested structured blocks, and ordinary prose behave like the\n * top-level document while the container still persists its normalized runtime\n * data. Source adapters may still expose a human-friendly nested MDX form\n * (for example `<Columns><Column>markdown</Column></Columns>`) and normalize it\n * into these block arrays at runtime.\n */\n renderBlocksEditor?: (props: {\n blocks: NestedBlock[];\n onChange: (blocks: NestedBlock[]) => void;\n editable: boolean;\n containerBlockId: string;\n regionId: string;\n regionLabel?: string;\n /** Tighten embedded visuals in dense regions such as tab panes. */\n compactVisuals?: boolean;\n }) => React.ReactNode;\n /**\n * Wrap a block's edit form in an app-provided \"panel\" surface (e.g. a shadcn\n * Popover anchored to the corner edit button) for `editSurface: \"panel\"`\n * blocks. Core renders the rendered `Read` view plus a corner trigger button\n * and the form, then hands them here so the app owns the overlay primitive\n * (core stays shadcn-free, mirroring `renderMarkdownEditor`). When omitted, a\n * panel-mode block falls back to inline editing. `title` is the block label.\n */\n renderEditSurface?: (props: {\n title: string;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n trigger: React.ReactNode;\n children: React.ReactNode;\n /** Compact action menus omit host block-edit chrome such as edit-by-prompt. */\n variant?: \"panel\" | \"menu\";\n /** Metadata for host-provided contextual controls such as the edit-by-prompt CTA. */\n blockId?: string;\n blockType?: string;\n blockTitle?: string;\n blockSummary?: string;\n blockData?: unknown;\n }) => React.ReactNode;\n /**\n * Submit a respondent's answers from a `question-form` / `visual-questions`\n * block back to the host. The app decides how to route the summary (e.g. send\n * to the inline agent, copy to clipboard). Core blocks call this through the\n * context so they never import app-specific submit wiring; omit it and the\n * block degrades to a no-op submit.\n */\n onQuestionFormSubmit?: (summary: string) => void;\n}\n\nexport interface BlockAiFieldActionProps {\n blockId: string;\n blockType: string;\n blockTitle?: string;\n blockSummary?: string;\n fieldLabel: string;\n fieldValue: string;\n draftScope: string;\n disabled?: boolean;\n /**\n * Human-readable instructions for the host agent prompt. Mention how to patch\n * the block and which sibling fields should be preserved.\n */\n instructions: string;\n companionFields?: Array<{\n label: string;\n value: string;\n language?: string;\n }>;\n}\n\n/**\n * The minimal shape of a nested child block passed to {@link\n * BlockRenderContext.renderBlock}. It mirrors the app's block union loosely (the\n * app casts it back to its own block type) — a discriminating `type`, a stable\n * `id`, optional heading/summary, and the type-specific `data`.\n */\nexport interface NestedBlock {\n type: string;\n id: string;\n title?: string;\n summary?: string;\n data: unknown;\n [key: string]: unknown;\n}\n\nexport interface BlockContainerRegion {\n id: string;\n label?: string;\n blocks: NestedBlock[];\n}\n\nexport interface BlockContainerSpec<TData> {\n regions: (data: TData) => BlockContainerRegion[];\n updateRegion: (data: TData, regionId: string, blocks: NestedBlock[]) => TData;\n addRegion?: (data: TData, afterRegionId?: string) => TData;\n removeRegion?: (data: TData, regionId: string) => TData;\n reorderRegion?: (\n data: TData,\n fromRegionId: string,\n toRegionId: string,\n ) => TData;\n}\n\nexport type BlockDataChangeMeta = {\n containerRegion?: {\n regionId: string;\n blocks: NestedBlock[];\n };\n};\n\n/** Props passed to a block's read-only renderer. */\nexport interface BlockReadProps<TData> {\n data: TData;\n /** Stable block id (for anchors, comment targeting, source patches). */\n blockId: string;\n /** Block heading, when present. */\n title?: string;\n /** Block trailing summary, when present. */\n summary?: string;\n /** Injected app capabilities. */\n ctx: BlockRenderContext;\n}\n\n/** Props passed to a block's editor (custom or schema-generated). */\nexport interface BlockEditProps<TData> {\n data: TData;\n onChange: (next: TData, meta?: BlockDataChangeMeta) => void;\n editable: boolean;\n blockId: string;\n title?: string;\n summary?: string;\n /** Injected app capabilities. */\n ctx: BlockRenderContext;\n}\n\nexport interface BlockSpec<TData = unknown> {\n /** Discriminator. Equals the runtime block `type`. */\n type: string;\n /** Zod schema for `data`. Drives validation AND the schema-auto-editor. */\n schema: ZodType<TData>;\n /** MDX round-trip config. */\n mdx: BlockMdxConfig<TData>;\n /** Read-only renderer (replaces a `PlanBlockView` switch branch / NodeView). */\n Read: FC<BlockReadProps<TData>>;\n /**\n * Optional editor. When omitted, the registry renders the schema-driven\n * `SchemaBlockEditor` generated from `schema`. Supply for full control\n * (wireframe canvas, diagram editor).\n */\n Edit?: FC<BlockEditProps<TData>>;\n /** Allowed placements: `[\"block\"]`, `[\"inline\"]`, or both. */\n placement: BlockPlacement[];\n /**\n * When `true`, this block's data maps to a Notion-Flavored-Markdown (NFM)\n * analog and therefore round-trips into a Notion page. Apps can derive\n * registry-backed Notion allowlists with\n * {@link BlockRegistry.notionCompatibleTypes} instead of hand-maintaining\n * per-app sets. Set it on registry-atom blocks with an NFM counterpart\n * (checklist, table); leave it `false`/undefined on dev-doc blocks\n * (api-endpoint, openapi-spec, data-model, diff, file-tree, json-explorer,\n * annotated-code, mermaid, custom-html, tabs, code-tabs) and visual/plan-only\n * blocks (wireframe, diagram). Prose blocks that aren't registry atoms\n * (rich-text, callout) carry their NFM analog through the prose path, not this\n * flag.\n */\n notionCompatible?: boolean;\n /**\n * How the block is edited in a `block`-placed document:\n * - `\"inline\"` — the `Edit`/auto-form renders in place for direct\n * manipulation of authored content (prose, checklist text, table cells,\n * code bodies). Schema-ish metadata such as tone/type, tab labels,\n * language, density, or structural settings should still be tucked behind a\n * contextual edit/settings affordance inside the custom `Edit`.\n * - `\"panel\"` — the block shows its rendered `Read` view with a corner edit\n * button that opens the `Edit`/auto-form in an app-provided panel (popover).\n * Best for config-driven blocks whose render differs from their props\n * (custom HTML, charts, any user-registered block).\n * - `\"container\"` — the block renders its `Edit` in place, and that editor\n * may call `ctx.renderBlocksEditor` for nested block regions with normal\n * slash commands and nested structured blocks.\n * Defaults to `\"inline\"` when a custom `Edit` is supplied, else `\"panel\"`\n * (auto-form blocks are property forms, ideal for a panel). The app must wire\n * `ctx.renderEditSurface` for `\"panel\"` to take effect; otherwise it falls\n * back to inline.\n */\n editSurface?: \"inline\" | \"panel\" | \"container\";\n /**\n * Optional generic contract for content-bearing container blocks. Keep this\n * runtime-oriented: it describes editable regions over normalized block arrays;\n * source formats can provide readable nested MDX adapters independently.\n */\n container?: BlockContainerSpec<TData>;\n /** Human label for menus + agent schema export. */\n label: string;\n /** Tabler icon component for UI menus (never emoji/robot/sparkle). */\n icon?: FC<{ size?: number; className?: string }>;\n /** One-line description for the agent schema export. */\n description: string;\n /** Optional default `data` factory for slash-menu insertion (an empty block). */\n empty?: () => TData;\n /**\n * Optional block-specific source-patch handlers, generalizing bespoke ops\n * like `update-custom-html`. Keyed by op name; the registry dispatches a\n * matching patch op here. Generic ops (`update-block` shallow-merge) need none.\n */\n patches?: Record<string, (data: TData, op: Record<string, unknown>) => TData>;\n}\n\n/** Identity helper for authoring a spec with full type inference. */\nexport function defineBlock<TData>(spec: BlockSpec<TData>): BlockSpec<TData> {\n return spec;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/client/blocks/types.ts"],"names":[],"mappings":"AAqYA,qEAAqE;AACrE,MAAM,UAAU,WAAW,CAAQ,IAAsB;IACvD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { FC } from \"react\";\nimport type { ZodType } from \"zod\";\n\n/**\n * Block-registry contract. A `BlockSpec` describes one document block end to end:\n * its data shape (`schema`), how it round-trips to MDX source (`mdx`), how it\n * renders read-only (`Read`) and how it is edited (`Edit`, or an auto-generated\n * schema-driven editor when omitted), where it can be placed (`placement`), and\n * metadata for menus / agent schema export.\n *\n * The registry runs ALONGSIDE existing per-block code (the plan `PlanBlockView`\n * switch + `serializeBlock`/`parseBlock`). Renderers check the registry first;\n * unregistered block types fall through to the legacy code path unchanged. The\n * MDX `tag` and attribute shape for a converted block MUST match the historical\n * encoding (e.g. `<Callout tone>…body…</Callout>`) so stored `.mdx` files still\n * parse byte-compatibly.\n */\n\n/** Where a block can be placed in a document. */\nexport type BlockPlacement = \"block\" | \"inline\";\n\n/**\n * A serialized MDX/NFM attribute value before the shared `prop()` encoder runs.\n * `prop()` decides string-vs-JSON encoding; this is just the value domain.\n */\nexport type MdxAttrValue =\n | string\n | number\n | boolean\n | unknown[]\n | Record<string, unknown>;\n\n/**\n * Type-narrowed reader over the resolved MDX attributes of a parsed block node.\n * The values are already estree/JSON-resolved by the shared attribute reader\n * (the same engine `plan-mdx.ts` uses), so a spec's `fromAttrs` never touches\n * the AST directly.\n */\nexport interface BlockAttrReader {\n string(name: string): string | undefined;\n number(name: string): number | undefined;\n bool(name: string): boolean | undefined;\n array<T = unknown>(name: string): T[] | undefined;\n object<T = unknown>(name: string): T | undefined;\n raw(name: string): unknown;\n}\n\n/**\n * Maps a block's validated data to/from its MDX component representation.\n * `tag` is the JSX component name in source (e.g. \"Callout\"). It MUST match the\n * historical name in `plan-mdx.ts` `BLOCK_COMPONENTS` / stored `.mdx` files or\n * existing plans break.\n */\nexport interface BlockMdxConfig<TData> {\n /** JSX component name in MDX source. Stable contract — never rename. */\n tag: string;\n /**\n * Encode `data` → a flat attribute bag. The registry serializer runs each\n * value through the shared `prop()` encoder (string-vs-JSON heuristic) and\n * preserves insertion order, so write the keys in the exact historical order.\n * Return `undefined` for a key (or omit it) to drop the attribute. When\n * `childrenField` is set, that field is excluded from the attribute bag.\n */\n toAttrs: (data: TData) => Record<string, MdxAttrValue | undefined>;\n /**\n * Decode resolved attributes (+ optional children markdown) → data. Must\n * tolerate missing/partial attributes for backward-compat (mirror today's\n * `?? []` / `?? \"\"` defaults).\n */\n fromAttrs: (attrs: BlockAttrReader, children: string) => TData;\n /**\n * When set, this data field is a markdown string serialized as MDX *children*\n * between the open/close tags (prose-bearing blocks: rich-text, callout)\n * rather than as a prop — so the body survives as real, inline-editable MDX\n * prose in source.\n */\n childrenField?: keyof TData & string;\n /**\n * Opt-in custom children serializer for blocks whose internals are nested MDX\n * components rather than a single markdown string (e.g. wireframe → Screen/kit\n * primitives). When present it overrides `childrenField`. `serializeChildren`\n * returns the raw inner MDX; `parseChildren` receives the child MDX AST nodes.\n */\n serializeChildren?: (data: TData) => string;\n parseChildren?: (childNodes: unknown[], idContext: string) => Partial<TData>;\n}\n\n/**\n * App-injected capabilities. Core blocks stay app-agnostic by taking these\n * rather than importing app services — mirroring `createImageExtension`'s\n * `onImageUpload` injection. Provided via `BlockRegistryProvider`.\n */\nexport interface BlockRenderContext {\n /** Markdown dialect for the auto-editor's rich-text field. */\n dialect?: \"gfm\" | \"nfm\";\n /** Resolve an asset id → displayable URL. */\n resolveAssetSrc?: (assetId: string) => string | undefined;\n /** Open the shared asset picker (returns the chosen asset). */\n pickAsset?: () => Promise<{ assetId: string; url?: string } | null>;\n /** Upload a local file, returns a hosted URL. */\n uploadFile?: (file: File) => Promise<{ url: string; assetId?: string }>;\n /** Call an app action by name (for blocks that fetch live data). */\n callAction?: (name: string, args: unknown) => Promise<unknown>;\n /** Sanitizer for HTML-bearing blocks. Provided by the app/core. */\n sanitizeHtml?: (html: string, css?: string) => string;\n /**\n * Render a markdown string with the app's read-only markdown renderer. Lets a\n * core block (whose `Read` lives in core) defer prose rendering to the app's\n * markdown reader (e.g. the plan `PlanMarkdownReader`) without importing it.\n */\n renderMarkdown?: (\n markdown: string,\n options?: { className?: string },\n ) => React.ReactNode;\n /**\n * Static capture mode: render every code/diff line annotation as a visible\n * inline overlay instead of requiring hover.\n */\n showCodeAnnotationOverlays?: boolean;\n /**\n * Optional placement policy for line-anchored code/diff annotations.\n * Hosts can keep the default right-first hover behavior, or ask annotations to\n * prefer a margin side and become persistent whenever that margin has room.\n */\n codeAnnotationLayout?: {\n /** Preferred side for hover cards when that side has a clean gutter. */\n hoverSide?: \"left\" | \"right\";\n /**\n * Final hover fallback when neither side has a clean gutter. `\"below\"` keeps\n * the legacy line-below behavior; `\"left\"`/`\"right\"` clamp the card to that\n * viewport side, even if it overlaps part of the code surface.\n */\n hoverFallbackSide?: \"left\" | \"right\" | \"below\";\n /** Show all annotation cards by default when the requested margin fits. */\n showByDefaultWhenRoom?: boolean;\n /** Margin side for persistent cards; `\"auto\"` tries hoverSide, then the other side. */\n marginSide?: \"left\" | \"right\" | \"auto\";\n };\n /**\n * Render an inline, editable rich-markdown field. The auto-editor calls this\n * for a `markdown()`-tagged field so the app owns the editor wiring (collab,\n * autosave debounce, dialect) rather than core hardcoding it.\n */\n renderMarkdownEditor?: (props: {\n value: string;\n onChange: (next: string) => void;\n editable: boolean;\n blockId?: string;\n className?: string;\n ariaLabel?: string;\n }) => React.ReactNode;\n /**\n * Render an app-owned edit-by-prompt affordance (\"Describe a change…\") for a focused/editable block\n * field. Core block editors pass the current field value and nearby companion\n * fields; the host app decides how to collect the prompt and route it to the\n * agent sidebar. This keeps reusable core blocks from importing app-specific\n * popover/composer code while still exposing a generic AI edit hook.\n */\n renderAiFieldAction?: (props: BlockAiFieldActionProps) => React.ReactNode;\n /**\n * Render a nested child block through the app's own block dispatcher. Container\n * blocks whose `Read`/`Edit` live in core (e.g. tabs) call this to render each\n * child so the recursion keeps flowing through the SAME app renderer the\n * top-level document uses — registered children render via their spec, and\n * unregistered (not-yet-converted) children still fall through the app's legacy\n * switch. This is the coexistence seam: a core container never has to know\n * about app-specific child block types. Returns `null`/`undefined` when no\n * dispatcher is wired (read-only/SSR-only contexts can omit it).\n */\n renderBlock?: (props: {\n block: NestedBlock;\n /** Commit a replacement for this child block (edit mode only). */\n onChange?: (next: NestedBlock) => void;\n /** Whether the parent container is being edited. */\n editing?: boolean;\n /** Tighten embedded visuals in dense contexts (e.g. tab panes). */\n compactVisuals?: boolean;\n }) => React.ReactNode;\n /**\n * Render a nested editable block list through the host app's document editor.\n * Container blocks such as columns call this for each editable region so slash\n * commands, nested structured blocks, and ordinary prose behave like the\n * top-level document while the container still persists its normalized runtime\n * data. Source adapters may still expose a human-friendly nested MDX form\n * (for example `<Columns><Column>markdown</Column></Columns>`) and normalize it\n * into these block arrays at runtime.\n */\n renderBlocksEditor?: (props: {\n blocks: NestedBlock[];\n onChange: (blocks: NestedBlock[]) => void;\n editable: boolean;\n containerBlockId: string;\n regionId: string;\n regionLabel?: string;\n /** Tighten embedded visuals in dense regions such as tab panes. */\n compactVisuals?: boolean;\n }) => React.ReactNode;\n /**\n * Wrap a block's edit form in an app-provided \"panel\" surface (e.g. a shadcn\n * Popover anchored to the corner edit button) for `editSurface: \"panel\"`\n * blocks. Core renders the rendered `Read` view plus a corner trigger button\n * and the form, then hands them here so the app owns the overlay primitive\n * (core stays shadcn-free, mirroring `renderMarkdownEditor`). When omitted, a\n * panel-mode block falls back to inline editing. `title` is the block label.\n */\n renderEditSurface?: (props: {\n title: string;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n trigger: React.ReactNode;\n children: React.ReactNode;\n /** Compact action menus omit host block-edit chrome such as edit-by-prompt. */\n variant?: \"panel\" | \"menu\";\n /** Metadata for host-provided contextual controls such as the edit-by-prompt CTA. */\n blockId?: string;\n blockType?: string;\n blockTitle?: string;\n blockSummary?: string;\n blockData?: unknown;\n }) => React.ReactNode;\n /**\n * Submit a respondent's answers from a `question-form` / `visual-questions`\n * block back to the host. The app decides how to route the summary (e.g. send\n * to the inline agent, copy to clipboard). Core blocks call this through the\n * context so they never import app-specific submit wiring; omit it and the\n * block degrades to a no-op submit.\n */\n onQuestionFormSubmit?: (summary: string) => void;\n}\n\nexport interface BlockAiFieldActionProps {\n blockId: string;\n blockType: string;\n blockTitle?: string;\n blockSummary?: string;\n fieldLabel: string;\n fieldValue: string;\n draftScope: string;\n disabled?: boolean;\n /**\n * Human-readable instructions for the host agent prompt. Mention how to patch\n * the block and which sibling fields should be preserved.\n */\n instructions: string;\n companionFields?: Array<{\n label: string;\n value: string;\n language?: string;\n }>;\n}\n\n/**\n * The minimal shape of a nested child block passed to {@link\n * BlockRenderContext.renderBlock}. It mirrors the app's block union loosely (the\n * app casts it back to its own block type) — a discriminating `type`, a stable\n * `id`, optional heading/summary, and the type-specific `data`.\n */\nexport interface NestedBlock {\n type: string;\n id: string;\n title?: string;\n summary?: string;\n data: unknown;\n [key: string]: unknown;\n}\n\nexport interface BlockContainerRegion {\n id: string;\n label?: string;\n blocks: NestedBlock[];\n}\n\nexport interface BlockContainerSpec<TData> {\n regions: (data: TData) => BlockContainerRegion[];\n updateRegion: (data: TData, regionId: string, blocks: NestedBlock[]) => TData;\n addRegion?: (data: TData, afterRegionId?: string) => TData;\n removeRegion?: (data: TData, regionId: string) => TData;\n reorderRegion?: (\n data: TData,\n fromRegionId: string,\n toRegionId: string,\n ) => TData;\n}\n\nexport type BlockDataChangeMeta = {\n containerRegion?: {\n regionId: string;\n blocks: NestedBlock[];\n };\n};\n\n/** Props passed to a block's read-only renderer. */\nexport interface BlockReadProps<TData> {\n data: TData;\n /** Stable block id (for anchors, comment targeting, source patches). */\n blockId: string;\n /** Block heading, when present. */\n title?: string;\n /** Block trailing summary, when present. */\n summary?: string;\n /** Injected app capabilities. */\n ctx: BlockRenderContext;\n}\n\n/** Props passed to a block's editor (custom or schema-generated). */\nexport interface BlockEditProps<TData> {\n data: TData;\n onChange: (next: TData, meta?: BlockDataChangeMeta) => void;\n editable: boolean;\n blockId: string;\n title?: string;\n summary?: string;\n /** Injected app capabilities. */\n ctx: BlockRenderContext;\n}\n\nexport interface BlockSpec<TData = unknown> {\n /** Discriminator. Equals the runtime block `type`. */\n type: string;\n /** Zod schema for `data`. Drives validation AND the schema-auto-editor. */\n schema: ZodType<TData>;\n /** MDX round-trip config. */\n mdx: BlockMdxConfig<TData>;\n /** Read-only renderer (replaces a `PlanBlockView` switch branch / NodeView). */\n Read: FC<BlockReadProps<TData>>;\n /**\n * Optional editor. When omitted, the registry renders the schema-driven\n * `SchemaBlockEditor` generated from `schema`. Supply for full control\n * (wireframe canvas, diagram editor).\n */\n Edit?: FC<BlockEditProps<TData>>;\n /** Allowed placements: `[\"block\"]`, `[\"inline\"]`, or both. */\n placement: BlockPlacement[];\n /**\n * When `true`, this block's data maps to a Notion-Flavored-Markdown (NFM)\n * analog and therefore round-trips into a Notion page. Apps can derive\n * registry-backed Notion allowlists with\n * {@link BlockRegistry.notionCompatibleTypes} instead of hand-maintaining\n * per-app sets. Set it on registry-atom blocks with an NFM counterpart\n * (checklist, table); leave it `false`/undefined on dev-doc blocks\n * (api-endpoint, openapi-spec, data-model, diff, file-tree, json-explorer,\n * annotated-code, mermaid, custom-html, tabs, code-tabs) and visual/plan-only\n * blocks (wireframe, diagram). Prose blocks that aren't registry atoms\n * (rich-text, callout) carry their NFM analog through the prose path, not this\n * flag.\n */\n notionCompatible?: boolean;\n /**\n * How the block is edited in a `block`-placed document:\n * - `\"inline\"` — the `Edit`/auto-form renders in place for direct\n * manipulation of authored content (prose, checklist text, table cells,\n * code bodies). Schema-ish metadata such as tone/type, tab labels,\n * language, density, or structural settings should still be tucked behind a\n * contextual edit/settings affordance inside the custom `Edit`.\n * - `\"panel\"` — the block shows its rendered `Read` view with a corner edit\n * button that opens the `Edit`/auto-form in an app-provided panel (popover).\n * Best for config-driven blocks whose render differs from their props\n * (custom HTML, charts, any user-registered block).\n * - `\"container\"` — the block renders its `Edit` in place, and that editor\n * may call `ctx.renderBlocksEditor` for nested block regions with normal\n * slash commands and nested structured blocks.\n * Defaults to `\"inline\"` when a custom `Edit` is supplied, else `\"panel\"`\n * (auto-form blocks are property forms, ideal for a panel). The app must wire\n * `ctx.renderEditSurface` for `\"panel\"` to take effect; otherwise it falls\n * back to inline.\n */\n editSurface?: \"inline\" | \"panel\" | \"container\";\n /**\n * Optional generic contract for content-bearing container blocks. Keep this\n * runtime-oriented: it describes editable regions over normalized block arrays;\n * source formats can provide readable nested MDX adapters independently.\n */\n container?: BlockContainerSpec<TData>;\n /** Human label for menus + agent schema export. */\n label: string;\n /** Tabler icon component for UI menus (never emoji/robot/sparkle). */\n icon?: FC<{ size?: number; className?: string }>;\n /** One-line description for the agent schema export. */\n description: string;\n /** Optional default `data` factory for slash-menu insertion (an empty block). */\n empty?: () => TData;\n /**\n * Optional block-specific source-patch handlers, generalizing bespoke ops\n * like `update-custom-html`. Keyed by op name; the registry dispatches a\n * matching patch op here. Generic ops (`update-block` shallow-merge) need none.\n */\n patches?: Record<string, (data: TData, op: Record<string, unknown>) => TData>;\n}\n\n/** Identity helper for authoring a spec with full type inference. */\nexport function defineBlock<TData>(spec: BlockSpec<TData>): BlockSpec<TData> {\n return spec;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sse-event-processor.d.ts","sourceRoot":"","sources":["../../src/client/sse-event-processor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"sse-event-processor.d.ts","sourceRoot":"","sources":["../../src/client/sse-event-processor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAK9D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAItE,MAAM,MAAM,WAAW,GACnB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IACE,IAAI,EAAE,WAAW,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,kBAAkB,CAAC;IAC5B,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC1C,CAAC;AAEN,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAA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AAK,EAAE,MAAM,GAAG,SAAS,EACzB,QAAQ,EAAE,CAAC,OAAO,EAAE,WAAW,EAAE,KAAK,IAAI,GACzC,OAAO,CAAC,IAAI,CAAC,CA0Ff"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { LLM_MISSING_CREDENTIALS_ERROR_CODE, LLM_MISSING_CREDENTIALS_MESSAGE, } from "../agent/engine/credential-errors.js";
|
|
1
2
|
import { formatChatErrorText, normalizeChatError } from "./error-format.js";
|
|
2
3
|
import { humanizeToolLabelText, runningToolLabel } from "./tool-display.js";
|
|
3
4
|
const INTERRUPTED_TOOL_RESULT = "Interrupted before this tool returned a result.";
|
|
@@ -374,18 +375,29 @@ export function processEvent(ev, content, toolCallCounter, tabId) {
|
|
|
374
375
|
return { action: "continue" };
|
|
375
376
|
}
|
|
376
377
|
if (ev.type === "missing_api_key") {
|
|
378
|
+
const errMsg = LLM_MISSING_CREDENTIALS_MESSAGE;
|
|
379
|
+
const errorCode = LLM_MISSING_CREDENTIALS_ERROR_CODE;
|
|
380
|
+
const runError = {
|
|
381
|
+
message: normalizeChatError(errMsg).message,
|
|
382
|
+
errorCode,
|
|
383
|
+
};
|
|
377
384
|
if (typeof window !== "undefined") {
|
|
378
385
|
window.dispatchEvent(new Event("agent-chat:missing-api-key"));
|
|
386
|
+
window.dispatchEvent(new CustomEvent("agent-chat:run-error", {
|
|
387
|
+
detail: { ...runError, tabId },
|
|
388
|
+
}));
|
|
379
389
|
}
|
|
390
|
+
settleInterruptedToolCalls(content);
|
|
380
391
|
content.push({
|
|
381
392
|
type: "text",
|
|
382
|
-
text:
|
|
393
|
+
text: formatChatErrorText(errMsg, undefined, errorCode),
|
|
383
394
|
});
|
|
384
395
|
return {
|
|
385
396
|
action: "missing_api_key",
|
|
386
397
|
result: {
|
|
387
398
|
content: [...content],
|
|
388
399
|
status: { type: "incomplete", reason: "error" },
|
|
400
|
+
metadata: { custom: { runError } },
|
|
389
401
|
},
|
|
390
402
|
};
|
|
391
403
|
}
|
|
@@ -453,17 +465,6 @@ export function processEvent(ev, content, toolCallCounter, tabId) {
|
|
|
453
465
|
if (typeof window !== "undefined") {
|
|
454
466
|
window.dispatchEvent(new Event("agent-chat:missing-api-key"));
|
|
455
467
|
}
|
|
456
|
-
content.push({
|
|
457
|
-
type: "text",
|
|
458
|
-
text: formatChatErrorText(errMsg, ev.upgradeUrl, ev.errorCode),
|
|
459
|
-
});
|
|
460
|
-
return {
|
|
461
|
-
action: "missing_api_key",
|
|
462
|
-
result: {
|
|
463
|
-
content: [...content],
|
|
464
|
-
status: { type: "incomplete", reason: "error" },
|
|
465
|
-
},
|
|
466
|
-
};
|
|
467
468
|
}
|
|
468
469
|
const runError = {
|
|
469
470
|
message: normalized.message,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sse-event-processor.js","sourceRoot":"","sources":["../../src/client/sse-event-processor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AA6D5E,MAAM,uBAAuB,GAC3B,iDAAiD,CAAC;AAEpD,MAAM,UAAU,0BAA0B,CACxC,OAAsB,EACtB,MAAM,GAAG,uBAAuB;IAEhC,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;QAC3B,IACE,IAAI,CAAC,IAAI,KAAK,WAAW;YACzB,IAAI,CAAC,MAAM,KAAK,SAAS;YACzB,IAAI,CAAC,QAAQ,KAAK,IAAI,EACtB,CAAC;YACD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;YACrB,OAAO,GAAG,IAAI,CAAC;QACjB,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IACvC,MAAM,CAA0B;IAChC,aAAa,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oBAAoB;QAAE,QAAQ,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IACxE,MAAM,IAAI,uBAAuB,CAAC,EAAE,MAAM,EAAE,cAAc,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import type { ChatModelRunResult } from \"@assistant-ui/react\";\nimport type { AgentMcpAppPayload } from \"../mcp-client/app-result.js\";\nimport { formatChatErrorText, normalizeChatError } from \"./error-format.js\";\nimport { humanizeToolLabelText, runningToolLabel } from \"./tool-display.js\";\n\nexport type ContentPart =\n | { type: \"text\"; text: string }\n | {\n type: \"tool-call\";\n toolCallId: string;\n toolName: string;\n argsText: string;\n args: Record<string, string>;\n result?: string;\n mcpApp?: AgentMcpAppPayload;\n activity?: boolean;\n /**\n * Structured metadata from the coding-tools executor side-channel.\n * Present only on code-agent tool calls from executors new enough to\n * emit it. The `toolKind` discriminant identifies the shape.\n */\n structuredMeta?: Record<string, unknown>;\n };\n\nexport interface SSEEvent {\n type: string;\n text?: string;\n tool?: string;\n /** Server-assigned call identifier emitted on tool_start / tool_done events. */\n id?: string;\n label?: string;\n input?: Record<string, string>;\n result?: string;\n mcpApp?: AgentMcpAppPayload;\n error?: string;\n seq?: number;\n agent?: string;\n status?: string;\n reason?: string;\n // Agent task fields\n taskId?: string;\n threadId?: string;\n description?: string;\n preview?: string;\n currentStep?: string;\n summary?: string;\n // Structured error metadata — Builder gateway sets these on quota/auth/setup\n // failures so the UI can render a CTA alongside the error text.\n errorCode?: string;\n upgradeUrl?: string;\n details?: string;\n recoverable?: boolean;\n maxIterations?: number;\n}\n\nexport type AgentAutoContinueReason =\n | \"run_timeout\"\n | \"loop_limit\"\n | \"no_progress\"\n | \"stream_ended\"\n | \"stale_run\";\n\nexport type AgentActivityTrailEntry = { label: string; tool?: string };\n\nconst INTERRUPTED_TOOL_RESULT =\n \"Interrupted before this tool returned a result.\";\n\nexport function settleInterruptedToolCalls(\n content: ContentPart[],\n result = INTERRUPTED_TOOL_RESULT,\n): boolean {\n let changed = false;\n for (const part of content) {\n if (\n part.type === \"tool-call\" &&\n part.result === undefined &&\n part.activity !== true\n ) {\n part.result = result;\n changed = true;\n }\n }\n return changed;\n}\n\nexport class AgentAutoContinueSignal extends Error {\n readonly reason: AgentAutoContinueReason;\n readonly maxIterations?: number;\n readonly activityTrail: AgentActivityTrailEntry[];\n\n constructor(options: {\n reason: AgentAutoContinueReason;\n maxIterations?: number;\n activityTrail?: AgentActivityTrailEntry[];\n }) {\n super(`Agent run needs automatic continuation: ${options.reason}`);\n this.name = \"AgentAutoContinueSignal\";\n this.reason = options.reason;\n this.maxIterations = options.maxIterations;\n this.activityTrail = options.activityTrail ?? [];\n }\n}\n\nexport const SSE_NO_PROGRESS_TIMEOUT_MS = 75_000;\n\ntype ActivityTrailEntry = AgentActivityTrailEntry;\n\nfunction findPendingToolCallIndex(\n content: ContentPart[],\n toolName: string,\n toolCallId?: string,\n): number {\n // Prefer id-based match when the event carries an id: parallel same-name\n // calls can be in flight simultaneously, and name-only matching would\n // attach a result to the wrong call.\n if (toolCallId) {\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolCallId === toolCallId &&\n part.result === undefined\n ) {\n return i;\n }\n }\n // Fall through to name-matching: the start event may have arrived before\n // the server started emitting ids (e.g. older server build), so the\n // stored toolCallId is the locally-generated \"tc_N\" value rather than the\n // server-assigned one. In that case match by name as a fallback.\n }\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === toolName &&\n part.result === undefined\n ) {\n return i;\n }\n }\n return -1;\n}\n\nfunction appendActivityTrail(\n trail: ActivityTrailEntry[],\n next: ActivityTrailEntry,\n) {\n const label = next.label.trim();\n if (!label) return;\n const tool = next.tool?.trim();\n const last = trail[trail.length - 1];\n if (last?.label === label && last.tool === tool) return;\n trail.push({ label, ...(tool ? { tool } : {}) });\n if (trail.length > 8) {\n trail.splice(0, trail.length - 8);\n }\n}\n\nasync function readChunkWithProgressTimeout(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n lastMeaningfulEventAt: number,\n): Promise<ReadableStreamReadResult<Uint8Array>> {\n const elapsed = Date.now() - lastMeaningfulEventAt;\n const timeoutMs = Math.max(0, SSE_NO_PROGRESS_TIMEOUT_MS - elapsed);\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n const readPromise = reader.read();\n // If the timeout wins and cancellation causes the pending read to reject,\n // swallow that rejection because the generator is already recovering.\n void readPromise.catch(() => {});\n\n const timeoutPromise = new Promise<\"timeout\">((resolve) => {\n timeoutId = setTimeout(() => resolve(\"timeout\"), timeoutMs);\n });\n const result = await Promise.race([readPromise, timeoutPromise]);\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (result === \"timeout\") {\n await reader.cancel(\"no_progress\").catch(() => {});\n throw new AgentAutoContinueSignal({ reason: \"no_progress\" });\n }\n return result;\n}\n\nfunction isAutoRecoverableError(ev: SSEEvent, errMsg: string): boolean {\n const code = String(ev.errorCode ?? \"\").toLowerCase();\n const msg = errMsg.toLowerCase();\n\n if (\n code === \"context_length_exceeded\" ||\n code === \"input_too_long\" ||\n code.startsWith(\"credits-limit\") ||\n code === \"billing_error\" ||\n code === \"unauthorized\" ||\n code === \"authentication_error\" ||\n code === \"permission_error\" ||\n code === \"http_401\" ||\n code === \"http_403\" ||\n code === \"rate_limit_exceeded\" ||\n code === \"gateway_not_enabled\" ||\n code === \"missing_api_key\" ||\n code === \"missing_credentials\" ||\n code === \"invalid_request_error\" ||\n code === \"request_too_large\" ||\n code === \"not_found_error\" ||\n code === \"model_not_found\" ||\n // `builder_gateway_error` is the no-detail fallback the Builder engine\n // emits when the gateway returns `{type:\"stop\",reason:\"error\"}` with no\n // explanation — almost always the upstream provider giving up (model\n // quota hit, account misconfiguration, opaque downstream failure). The\n // production-agent already retries this synchronously up to MAX_RETRIES\n // before the error escapes to the SSE stream, so by the time the client\n // sees it, retrying again with another POST /agent-chat will hit the\n // same wall. This used to send the chat into a 32-continuation runaway\n // (each turn cleared+regenerated visible content) for users hitting a\n // misbehaving Builder route. Surface the error instead.\n code === \"builder_gateway_error\"\n ) {\n return false;\n }\n\n if (\n code === \"builder_gateway_network_error\" ||\n code === \"builder_gateway_timeout\" ||\n code === \"stale_run\" ||\n code === \"timeout\" ||\n code === \"timeout_error\" ||\n code === \"http_408\" ||\n code === \"http_429\" ||\n code === \"http_500\" ||\n code === \"http_502\" ||\n code === \"http_503\" ||\n code === \"http_504\" ||\n code === \"rate_limited\" ||\n code === \"too_many_concurrent_requests\" ||\n code === \"overloaded_error\"\n ) {\n return true;\n }\n\n if (ev.recoverable === true) return true;\n\n if (msg.includes(\"daily gateway request cap\")) return false;\n\n // \"gateway error\" intentionally absent — that's the no-detail Builder\n // gateway fallback and the production-agent already retries it\n // synchronously up to MAX_RETRIES before the error escapes here. Treating\n // it as auto-recoverable on top of that produced a 32-continuation\n // runaway in production for users hitting a misbehaving Builder route.\n // (See `code === \"builder_gateway_error\"` in the not-recoverable list.)\n return (\n msg.includes(\"overloaded\") ||\n msg.includes(\"rate_limit\") ||\n msg.includes(\"too many requests\") ||\n msg.includes(\"timeout\") ||\n msg.includes(\"gateway timeout\") ||\n msg.includes(\"inactivity timeout\") ||\n msg.includes(\"socket hang up\") ||\n msg.includes(\"connection reset\") ||\n msg.includes(\"connection\") ||\n msg.includes(\"network\") ||\n msg.includes(\"stream closed\") ||\n msg.includes(\"stream ended\") ||\n msg.includes(\"temporarily unavailable\") ||\n msg.includes(\"502\") ||\n msg.includes(\"503\") ||\n msg.includes(\"504\") ||\n msg.includes(\"529\")\n );\n}\n\nfunction isMissingCredentialText(message: string, errorCode?: string): boolean {\n const code = String(errorCode ?? \"\").toLowerCase();\n const msg = message.toLowerCase();\n return (\n code === \"missing_api_key\" ||\n code === \"missing_credentials\" ||\n msg.includes(\"apikey\") ||\n msg.includes(\"authtoken\") ||\n msg.includes(\"anthropic_api_key\") ||\n msg.includes(\"missing_api_key\") ||\n msg.includes(\"missing api key\") ||\n msg.includes(\"missing credentials\") ||\n msg.includes(\"no llm provider\") ||\n msg.includes(\"llm provider is connected\")\n );\n}\n\nfunction dispatchActivityClear(tabId: string | undefined) {\n if (typeof window === \"undefined\") return;\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:activity-clear\", {\n detail: { tabId },\n }),\n );\n}\n\n/**\n * Process a single SSE event and update the content accumulator.\n * Returns: \"continue\" to keep going, \"done\" to stop, or a yield-ready result.\n */\nexport function processEvent(\n ev: SSEEvent,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n): {\n action:\n | \"continue\"\n | \"done\"\n | \"yield\"\n | \"error\"\n | \"missing_api_key\"\n | \"auto_continue\";\n result?: ChatModelRunResult;\n autoContinue?: {\n reason: AgentAutoContinueReason;\n maxIterations?: number;\n };\n} {\n if (ev.type === \"clear\") {\n // Server is retrying — discard partial text/tool output from the failed attempt\n content.length = 0;\n dispatchActivityClear(tabId);\n return { action: \"continue\" };\n }\n\n if (ev.type === \"text\") {\n const lastPart = content[content.length - 1];\n if (lastPart && lastPart.type === \"text\") {\n lastPart.text += ev.text ?? \"\";\n } else {\n content.push({ type: \"text\", text: ev.text ?? \"\" });\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"activity\") {\n const tool = ev.tool?.trim() || undefined;\n const label = humanizeToolLabelText(ev.label ?? \"Working\", tool);\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:activity\", {\n detail: {\n label,\n ...(tool ? { tool } : {}),\n tabId,\n },\n }),\n );\n }\n if (!tool) return { action: \"continue\" };\n\n const pendingToolCallIndex = findPendingToolCallIndex(content, tool);\n if (pendingToolCallIndex === -1) {\n content.push({\n type: \"tool-call\",\n toolCallId: `tc_${++toolCallCounter.value}`,\n toolName: tool,\n argsText: \"\",\n args: {},\n activity: true,\n });\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"tool_start\") {\n const args = (ev.input ?? {}) as Record<string, string>;\n const tool = ev.tool ?? \"unknown\";\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-native:tool-start\", {\n detail: { tool, input: args },\n }),\n );\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:activity\", {\n detail: {\n label: runningToolLabel(tool),\n tool,\n tabId,\n },\n }),\n );\n }\n // Pass the server-assigned id so we upgrade the pending activity card\n // using id-match when available (parallel same-name calls stay separate).\n const pendingToolCallIndex = findPendingToolCallIndex(content, tool, ev.id);\n const pendingToolCall =\n pendingToolCallIndex >= 0 ? content[pendingToolCallIndex] : undefined;\n if (\n pendingToolCall &&\n pendingToolCall.type === \"tool-call\" &&\n pendingToolCall.activity === true &&\n pendingToolCall.argsText === \"\" &&\n Object.keys(pendingToolCall.args).length === 0\n ) {\n // Upgrade the pending activity card in place. Prefer the server-assigned\n // id so the subsequent tool_done can match it precisely (parallel\n // same-name calls each carry their own id). Fall back to the\n // locally-generated id already on the card.\n content[pendingToolCallIndex] = {\n type: \"tool-call\",\n toolCallId: ev.id ?? pendingToolCall.toolCallId,\n toolName: tool,\n argsText: JSON.stringify(args),\n args,\n };\n } else {\n content.push({\n type: \"tool-call\",\n toolCallId: ev.id ?? `tc_${++toolCallCounter.value}`,\n toolName: tool,\n argsText: JSON.stringify(args),\n args,\n });\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"tool_done\") {\n // Normalize identically to tool_start (which stores `ev.tool ?? \"unknown\"`)\n // so a tool_done frame with an undefined tool name still matches its\n // pending tool-call entry instead of leaving it forever unresolved.\n const doneTool = ev.tool ?? \"unknown\";\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-native:tool-done\", {\n detail: { tool: doneTool, result: ev.result },\n }),\n );\n }\n // Use id-based lookup when available so parallel same-name tool calls\n // get their results correctly assigned; fall back to name-matching.\n const doneIdx = findPendingToolCallIndex(content, doneTool, ev.id);\n if (doneIdx >= 0) {\n const part = content[doneIdx];\n if (part.type === \"tool-call\") {\n part.result = ev.result ?? \"\";\n if (ev.mcpApp) part.mcpApp = ev.mcpApp;\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"agent_call\") {\n const agentName = ev.agent ?? \"agent\";\n if (ev.status === \"start\") {\n const toolCallId = `tc_${++toolCallCounter.value}`;\n content.push({\n type: \"tool-call\",\n toolCallId,\n toolName: `agent:${agentName}`,\n argsText: \"\",\n args: {},\n });\n } else if (ev.status === \"done\" || ev.status === \"error\") {\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === `agent:${agentName}` &&\n part.result === undefined\n ) {\n part.result = ev.status === \"error\" ? \"Error calling agent\" : \"Done\";\n break;\n }\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"agent_call_text\") {\n const agentName = ev.agent ?? \"agent\";\n // Find the in-progress agent tool-call and append streaming text to argsText\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === `agent:${agentName}` &&\n part.result === undefined\n ) {\n part.argsText += ev.text ?? \"\";\n break;\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n // ─── Agent task events (sub-agent chips) ─────────────────────────\n // These events are dispatched as CustomEvents so AgentTaskCard components\n // can listen for updates to their specific taskId.\n if (\n ev.type === \"agent_task\" ||\n ev.type === \"agent_task_update\" ||\n ev.type === \"agent_task_complete\"\n ) {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"agent-task-event\", { detail: ev }));\n }\n // Don't add to content — the agent-teams tool call handles rendering\n return { action: \"continue\" };\n }\n\n if (ev.type === \"missing_api_key\") {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(\"agent-chat:missing-api-key\"));\n }\n content.push({\n type: \"text\",\n text: \"No LLM provider is connected. Open Agent settings > LLM, then connect Builder.io or add a provider key.\",\n });\n return {\n action: \"missing_api_key\",\n result: {\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"loop_limit\") {\n const maxIterations =\n typeof ev.maxIterations === \"number\" ? ev.maxIterations : undefined;\n return {\n action: \"auto_continue\",\n autoContinue: {\n reason: \"loop_limit\",\n ...(maxIterations ? { maxIterations } : {}),\n },\n };\n }\n\n if (ev.type === \"auto_continue\") {\n const reason =\n ev.reason === \"stream_ended\" ||\n ev.reason === \"loop_limit\" ||\n ev.reason === \"no_progress\" ||\n ev.reason === \"run_timeout\"\n ? ev.reason\n : ev.errorCode === \"stream_ended\" ||\n ev.errorCode === \"loop_limit\" ||\n ev.errorCode === \"no_progress\" ||\n ev.errorCode === \"run_timeout\"\n ? ev.errorCode\n : ev.error === \"stream_ended\" ||\n ev.error === \"loop_limit\" ||\n ev.error === \"no_progress\" ||\n ev.error === \"run_timeout\"\n ? ev.error\n : ev.status === \"stream_ended\" ||\n ev.status === \"loop_limit\" ||\n ev.status === \"no_progress\" ||\n ev.status === \"run_timeout\"\n ? ev.status\n : \"run_timeout\";\n return {\n action: \"auto_continue\",\n autoContinue: {\n reason,\n ...(typeof ev.maxIterations === \"number\"\n ? { maxIterations: ev.maxIterations }\n : {}),\n },\n };\n }\n\n if (ev.type === \"error\") {\n const errMsg = ev.error ?? \"Unknown error\";\n if (\n (ev.errorCode === \"run_timeout\" && ev.recoverable) ||\n isAutoRecoverableError(ev, errMsg)\n ) {\n return {\n action: \"auto_continue\",\n autoContinue: {\n reason:\n ev.errorCode === \"stale_run\"\n ? \"stale_run\"\n : ev.errorCode === \"builder_gateway_timeout\" ||\n ev.errorCode === \"run_timeout\" ||\n errMsg.toLowerCase().includes(\"timeout\")\n ? \"run_timeout\"\n : \"stream_ended\",\n },\n };\n }\n const normalized = normalizeChatError(errMsg);\n if (isMissingCredentialText(errMsg, ev.errorCode)) {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(\"agent-chat:missing-api-key\"));\n }\n content.push({\n type: \"text\",\n text: formatChatErrorText(errMsg, ev.upgradeUrl, ev.errorCode),\n });\n return {\n action: \"missing_api_key\",\n result: {\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n } as ChatModelRunResult,\n };\n }\n const runError = {\n message: normalized.message,\n ...(normalized.details || ev.details\n ? { details: ev.details ?? normalized.details }\n : {}),\n ...(ev.errorCode ? { errorCode: ev.errorCode } : {}),\n ...(ev.recoverable ? { recoverable: ev.recoverable } : {}),\n };\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:run-error\", {\n detail: { ...runError, tabId },\n }),\n );\n }\n settleInterruptedToolCalls(content);\n content.push({\n type: \"text\",\n text: formatChatErrorText(errMsg, ev.upgradeUrl, ev.errorCode),\n });\n return {\n action: \"error\",\n result: {\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n metadata: { custom: { runError } },\n } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"done\") {\n return {\n action: \"done\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n return { action: \"continue\" };\n}\n\n/**\n * Read and process SSE events from a ReadableStream response body.\n * Yields ChatModelRunResult for each meaningful event.\n *\n * When `runId` is provided, every yielded result carries\n * `metadata.custom.runId` so the UI can expose the trace ID via\n * \"Copy Request ID\" — including mid-stream, so users can grab it before\n * the run completes (or if the run hangs / ends prematurely).\n */\nexport async function* readSSEStream(\n body: ReadableStream<Uint8Array>,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n onSeq?: (seq: number) => void,\n runId?: string | null,\n): AsyncGenerator<ChatModelRunResult> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = \"\";\n let lastMeaningfulEventAt = Date.now();\n const activityTrail: ActivityTrailEntry[] = [];\n\n const withStreamMetadata = (r: ChatModelRunResult): ChatModelRunResult => {\n if (!runId && activityTrail.length === 0) return r;\n const metadata = (r.metadata ?? {}) as Record<string, unknown>;\n const custom =\n metadata.custom && typeof metadata.custom === \"object\"\n ? (metadata.custom as Record<string, unknown>)\n : {};\n const runError =\n runId && custom.runError && typeof custom.runError === \"object\"\n ? {\n ...(custom.runError as Record<string, unknown>),\n runId,\n }\n : custom.runError;\n return {\n ...r,\n metadata: {\n ...metadata,\n custom: {\n ...custom,\n ...(runId ? { runId } : {}),\n ...(runError ? { runError } : {}),\n ...(activityTrail.length > 0\n ? { activityTrail: [...activityTrail] }\n : {}),\n },\n },\n };\n };\n\n try {\n while (true) {\n const { done, value } = await readChunkWithProgressTimeout(\n reader,\n lastMeaningfulEventAt,\n );\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n let sawDataEvent = false;\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const raw = line.slice(6).trim();\n if (!raw) continue;\n\n let ev: SSEEvent;\n try {\n ev = JSON.parse(raw);\n } catch {\n continue;\n }\n sawDataEvent = true;\n lastMeaningfulEventAt = Date.now();\n\n // Track sequence number for reconnection\n if (ev.seq !== undefined && onSeq) {\n onSeq(ev.seq);\n }\n\n if (ev.type === \"clear\") {\n activityTrail.length = 0;\n } else if (ev.type === \"activity\") {\n const tool = ev.tool?.trim() || undefined;\n appendActivityTrail(activityTrail, {\n label: humanizeToolLabelText(ev.label ?? \"Working\", tool),\n ...(tool ? { tool } : {}),\n });\n } else if (ev.type === \"tool_start\") {\n const tool = ev.tool ?? \"unknown\";\n appendActivityTrail(activityTrail, {\n label: runningToolLabel(tool),\n tool,\n });\n }\n\n const { action, result, autoContinue } = processEvent(\n ev,\n content,\n toolCallCounter,\n tabId,\n );\n\n if (result) yield withStreamMetadata(result);\n if (action === \"auto_continue\") {\n throw new AgentAutoContinueSignal(\n autoContinue\n ? { ...autoContinue, activityTrail: [...activityTrail] }\n : { reason: \"stream_ended\", activityTrail: [...activityTrail] },\n );\n }\n if (\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n return;\n }\n }\n\n if (\n !sawDataEvent &&\n Date.now() - lastMeaningfulEventAt >= SSE_NO_PROGRESS_TIMEOUT_MS\n ) {\n throw new AgentAutoContinueSignal({ reason: \"no_progress\" });\n }\n }\n } finally {\n try {\n reader.releaseLock();\n } catch {\n // The timeout path cancels the stream before unwinding; some runtimes\n // still consider the pending read active for a tick.\n }\n }\n\n // Stream ended without explicit done event. Even an empty content array is\n // abnormal here: a healthy run emits a terminal `done` event. Treat this as\n // recoverable so the adapter can first reconnect to the run, then continue\n // from durable history if the producer is gone.\n throw new AgentAutoContinueSignal({\n reason: \"stream_ended\",\n activityTrail: [...activityTrail],\n });\n}\n\n/**\n * Read raw SSE events from a ReadableStream and process them into ContentPart[].\n * Unlike readSSEStream, this doesn't yield ChatModelRunResult — it updates the\n * content array in-place and calls onUpdate for each meaningful change.\n * Designed for reconnection scenarios where we render outside assistant-ui's runtime.\n */\nexport async function readSSEStreamRaw(\n body: ReadableStream<Uint8Array>,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n onUpdate: (content: ContentPart[]) => void,\n): Promise<void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = \"\";\n let lastMeaningfulEventAt = Date.now();\n // Tracks whether the most recent content state was already pushed via\n // onUpdate inside the loop, so the post-loop flush below doesn't emit the\n // identical content a second time when the stream closes without a terminal\n // event.\n let emittedLatestContent = false;\n\n try {\n while (true) {\n const { done, value } = await readChunkWithProgressTimeout(\n reader,\n lastMeaningfulEventAt,\n );\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n\n let updated = false;\n let sawDataEvent = false;\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const raw = line.slice(6).trim();\n if (!raw) continue;\n\n let ev: SSEEvent;\n try {\n ev = JSON.parse(raw);\n } catch {\n continue;\n }\n sawDataEvent = true;\n lastMeaningfulEventAt = Date.now();\n\n const { action, autoContinue } = processEvent(\n ev,\n content,\n toolCallCounter,\n tabId,\n );\n\n if (\n action === \"yield\" ||\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n updated = true;\n }\n if (action === \"auto_continue\") {\n onUpdate([...content]);\n throw new AgentAutoContinueSignal(\n autoContinue ?? { reason: \"stream_ended\" },\n );\n }\n if (\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n onUpdate([...content]);\n return;\n }\n }\n\n if (updated) {\n onUpdate([...content]);\n emittedLatestContent = true;\n }\n if (\n !sawDataEvent &&\n Date.now() - lastMeaningfulEventAt >= SSE_NO_PROGRESS_TIMEOUT_MS\n ) {\n throw new AgentAutoContinueSignal({ reason: \"no_progress\" });\n }\n }\n } finally {\n try {\n reader.releaseLock();\n } catch {\n // See readSSEStream: cancellation may race lock release in browsers.\n }\n }\n if (content.length > 0 && !emittedLatestContent) onUpdate([...content]);\n throw new AgentAutoContinueSignal({ reason: \"stream_ended\" });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sse-event-processor.js","sourceRoot":"","sources":["../../src/client/sse-event-processor.ts"],"names":[],"mappings":"AACA,OAAO,EACL,kCAAkC,EAClC,+BAA+B,GAChC,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AA6D5E,MAAM,uBAAuB,GAC3B,iDAAiD,CAAC;AAEpD,MAAM,UAAU,0BAA0B,CACxC,OAAsB,EACtB,MAAM,GAAG,uBAAuB;IAEhC,IAAI,OAAO,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AE,CAAC;gBACZ,QAAQ,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;gBACvB,oBAAoB,GAAG,IAAI,CAAC;YAC9B,CAAC;YACD,IACE,CAAC,YAAY;gBACb,IAAI,CAAC,GAAG,EAAE,GAAG,qBAAqB,IAAI,0BAA0B,EAChE,CAAC;gBACD,MAAM,IAAI,uBAAuB,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC,CAAC;YAC/D,CAAC;QACH,CAAC;IACH,CAAC;YAAS,CAAC;QACT,IAAI,CAAC;YACH,MAAM,CAAC,WAAW,EAAE,CAAC;QACvB,CAAC;QAAC,MAAM,CAAC;YACP,qEAAqE;QACvE,CAAC;IACH,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,oBAAoB;QAAE,QAAQ,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IACxE,MAAM,IAAI,uBAAuB,CAAC,EAAE,MAAM,EAAE,cAAc,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import type { ChatModelRunResult } from \"@assistant-ui/react\";\nimport {\n LLM_MISSING_CREDENTIALS_ERROR_CODE,\n LLM_MISSING_CREDENTIALS_MESSAGE,\n} from \"../agent/engine/credential-errors.js\";\nimport type { AgentMcpAppPayload } from \"../mcp-client/app-result.js\";\nimport { formatChatErrorText, normalizeChatError } from \"./error-format.js\";\nimport { humanizeToolLabelText, runningToolLabel } from \"./tool-display.js\";\n\nexport type ContentPart =\n | { type: \"text\"; text: string }\n | {\n type: \"tool-call\";\n toolCallId: string;\n toolName: string;\n argsText: string;\n args: Record<string, string>;\n result?: string;\n mcpApp?: AgentMcpAppPayload;\n activity?: boolean;\n /**\n * Structured metadata from the coding-tools executor side-channel.\n * Present only on code-agent tool calls from executors new enough to\n * emit it. The `toolKind` discriminant identifies the shape.\n */\n structuredMeta?: Record<string, unknown>;\n };\n\nexport interface SSEEvent {\n type: string;\n text?: string;\n tool?: string;\n /** Server-assigned call identifier emitted on tool_start / tool_done events. */\n id?: string;\n label?: string;\n input?: Record<string, string>;\n result?: string;\n mcpApp?: AgentMcpAppPayload;\n error?: string;\n seq?: number;\n agent?: string;\n status?: string;\n reason?: string;\n // Agent task fields\n taskId?: string;\n threadId?: string;\n description?: string;\n preview?: string;\n currentStep?: string;\n summary?: string;\n // Structured error metadata — Builder gateway sets these on quota/auth/setup\n // failures so the UI can render a CTA alongside the error text.\n errorCode?: string;\n upgradeUrl?: string;\n details?: string;\n recoverable?: boolean;\n maxIterations?: number;\n}\n\nexport type AgentAutoContinueReason =\n | \"run_timeout\"\n | \"loop_limit\"\n | \"no_progress\"\n | \"stream_ended\"\n | \"stale_run\";\n\nexport type AgentActivityTrailEntry = { label: string; tool?: string };\n\nconst INTERRUPTED_TOOL_RESULT =\n \"Interrupted before this tool returned a result.\";\n\nexport function settleInterruptedToolCalls(\n content: ContentPart[],\n result = INTERRUPTED_TOOL_RESULT,\n): boolean {\n let changed = false;\n for (const part of content) {\n if (\n part.type === \"tool-call\" &&\n part.result === undefined &&\n part.activity !== true\n ) {\n part.result = result;\n changed = true;\n }\n }\n return changed;\n}\n\nexport class AgentAutoContinueSignal extends Error {\n readonly reason: AgentAutoContinueReason;\n readonly maxIterations?: number;\n readonly activityTrail: AgentActivityTrailEntry[];\n\n constructor(options: {\n reason: AgentAutoContinueReason;\n maxIterations?: number;\n activityTrail?: AgentActivityTrailEntry[];\n }) {\n super(`Agent run needs automatic continuation: ${options.reason}`);\n this.name = \"AgentAutoContinueSignal\";\n this.reason = options.reason;\n this.maxIterations = options.maxIterations;\n this.activityTrail = options.activityTrail ?? [];\n }\n}\n\nexport const SSE_NO_PROGRESS_TIMEOUT_MS = 75_000;\n\ntype ActivityTrailEntry = AgentActivityTrailEntry;\n\nfunction findPendingToolCallIndex(\n content: ContentPart[],\n toolName: string,\n toolCallId?: string,\n): number {\n // Prefer id-based match when the event carries an id: parallel same-name\n // calls can be in flight simultaneously, and name-only matching would\n // attach a result to the wrong call.\n if (toolCallId) {\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolCallId === toolCallId &&\n part.result === undefined\n ) {\n return i;\n }\n }\n // Fall through to name-matching: the start event may have arrived before\n // the server started emitting ids (e.g. older server build), so the\n // stored toolCallId is the locally-generated \"tc_N\" value rather than the\n // server-assigned one. In that case match by name as a fallback.\n }\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === toolName &&\n part.result === undefined\n ) {\n return i;\n }\n }\n return -1;\n}\n\nfunction appendActivityTrail(\n trail: ActivityTrailEntry[],\n next: ActivityTrailEntry,\n) {\n const label = next.label.trim();\n if (!label) return;\n const tool = next.tool?.trim();\n const last = trail[trail.length - 1];\n if (last?.label === label && last.tool === tool) return;\n trail.push({ label, ...(tool ? { tool } : {}) });\n if (trail.length > 8) {\n trail.splice(0, trail.length - 8);\n }\n}\n\nasync function readChunkWithProgressTimeout(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n lastMeaningfulEventAt: number,\n): Promise<ReadableStreamReadResult<Uint8Array>> {\n const elapsed = Date.now() - lastMeaningfulEventAt;\n const timeoutMs = Math.max(0, SSE_NO_PROGRESS_TIMEOUT_MS - elapsed);\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n const readPromise = reader.read();\n // If the timeout wins and cancellation causes the pending read to reject,\n // swallow that rejection because the generator is already recovering.\n void readPromise.catch(() => {});\n\n const timeoutPromise = new Promise<\"timeout\">((resolve) => {\n timeoutId = setTimeout(() => resolve(\"timeout\"), timeoutMs);\n });\n const result = await Promise.race([readPromise, timeoutPromise]);\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (result === \"timeout\") {\n await reader.cancel(\"no_progress\").catch(() => {});\n throw new AgentAutoContinueSignal({ reason: \"no_progress\" });\n }\n return result;\n}\n\nfunction isAutoRecoverableError(ev: SSEEvent, errMsg: string): boolean {\n const code = String(ev.errorCode ?? \"\").toLowerCase();\n const msg = errMsg.toLowerCase();\n\n if (\n code === \"context_length_exceeded\" ||\n code === \"input_too_long\" ||\n code.startsWith(\"credits-limit\") ||\n code === \"billing_error\" ||\n code === \"unauthorized\" ||\n code === \"authentication_error\" ||\n code === \"permission_error\" ||\n code === \"http_401\" ||\n code === \"http_403\" ||\n code === \"rate_limit_exceeded\" ||\n code === \"gateway_not_enabled\" ||\n code === \"missing_api_key\" ||\n code === \"missing_credentials\" ||\n code === \"invalid_request_error\" ||\n code === \"request_too_large\" ||\n code === \"not_found_error\" ||\n code === \"model_not_found\" ||\n // `builder_gateway_error` is the no-detail fallback the Builder engine\n // emits when the gateway returns `{type:\"stop\",reason:\"error\"}` with no\n // explanation — almost always the upstream provider giving up (model\n // quota hit, account misconfiguration, opaque downstream failure). The\n // production-agent already retries this synchronously up to MAX_RETRIES\n // before the error escapes to the SSE stream, so by the time the client\n // sees it, retrying again with another POST /agent-chat will hit the\n // same wall. This used to send the chat into a 32-continuation runaway\n // (each turn cleared+regenerated visible content) for users hitting a\n // misbehaving Builder route. Surface the error instead.\n code === \"builder_gateway_error\"\n ) {\n return false;\n }\n\n if (\n code === \"builder_gateway_network_error\" ||\n code === \"builder_gateway_timeout\" ||\n code === \"stale_run\" ||\n code === \"timeout\" ||\n code === \"timeout_error\" ||\n code === \"http_408\" ||\n code === \"http_429\" ||\n code === \"http_500\" ||\n code === \"http_502\" ||\n code === \"http_503\" ||\n code === \"http_504\" ||\n code === \"rate_limited\" ||\n code === \"too_many_concurrent_requests\" ||\n code === \"overloaded_error\"\n ) {\n return true;\n }\n\n if (ev.recoverable === true) return true;\n\n if (msg.includes(\"daily gateway request cap\")) return false;\n\n // \"gateway error\" intentionally absent — that's the no-detail Builder\n // gateway fallback and the production-agent already retries it\n // synchronously up to MAX_RETRIES before the error escapes here. Treating\n // it as auto-recoverable on top of that produced a 32-continuation\n // runaway in production for users hitting a misbehaving Builder route.\n // (See `code === \"builder_gateway_error\"` in the not-recoverable list.)\n return (\n msg.includes(\"overloaded\") ||\n msg.includes(\"rate_limit\") ||\n msg.includes(\"too many requests\") ||\n msg.includes(\"timeout\") ||\n msg.includes(\"gateway timeout\") ||\n msg.includes(\"inactivity timeout\") ||\n msg.includes(\"socket hang up\") ||\n msg.includes(\"connection reset\") ||\n msg.includes(\"connection\") ||\n msg.includes(\"network\") ||\n msg.includes(\"stream closed\") ||\n msg.includes(\"stream ended\") ||\n msg.includes(\"temporarily unavailable\") ||\n msg.includes(\"502\") ||\n msg.includes(\"503\") ||\n msg.includes(\"504\") ||\n msg.includes(\"529\")\n );\n}\n\nfunction isMissingCredentialText(message: string, errorCode?: string): boolean {\n const code = String(errorCode ?? \"\").toLowerCase();\n const msg = message.toLowerCase();\n return (\n code === \"missing_api_key\" ||\n code === \"missing_credentials\" ||\n msg.includes(\"apikey\") ||\n msg.includes(\"authtoken\") ||\n msg.includes(\"anthropic_api_key\") ||\n msg.includes(\"missing_api_key\") ||\n msg.includes(\"missing api key\") ||\n msg.includes(\"missing credentials\") ||\n msg.includes(\"no llm provider\") ||\n msg.includes(\"llm provider is connected\")\n );\n}\n\nfunction dispatchActivityClear(tabId: string | undefined) {\n if (typeof window === \"undefined\") return;\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:activity-clear\", {\n detail: { tabId },\n }),\n );\n}\n\n/**\n * Process a single SSE event and update the content accumulator.\n * Returns: \"continue\" to keep going, \"done\" to stop, or a yield-ready result.\n */\nexport function processEvent(\n ev: SSEEvent,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n): {\n action:\n | \"continue\"\n | \"done\"\n | \"yield\"\n | \"error\"\n | \"missing_api_key\"\n | \"auto_continue\";\n result?: ChatModelRunResult;\n autoContinue?: {\n reason: AgentAutoContinueReason;\n maxIterations?: number;\n };\n} {\n if (ev.type === \"clear\") {\n // Server is retrying — discard partial text/tool output from the failed attempt\n content.length = 0;\n dispatchActivityClear(tabId);\n return { action: \"continue\" };\n }\n\n if (ev.type === \"text\") {\n const lastPart = content[content.length - 1];\n if (lastPart && lastPart.type === \"text\") {\n lastPart.text += ev.text ?? \"\";\n } else {\n content.push({ type: \"text\", text: ev.text ?? \"\" });\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"activity\") {\n const tool = ev.tool?.trim() || undefined;\n const label = humanizeToolLabelText(ev.label ?? \"Working\", tool);\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:activity\", {\n detail: {\n label,\n ...(tool ? { tool } : {}),\n tabId,\n },\n }),\n );\n }\n if (!tool) return { action: \"continue\" };\n\n const pendingToolCallIndex = findPendingToolCallIndex(content, tool);\n if (pendingToolCallIndex === -1) {\n content.push({\n type: \"tool-call\",\n toolCallId: `tc_${++toolCallCounter.value}`,\n toolName: tool,\n argsText: \"\",\n args: {},\n activity: true,\n });\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"tool_start\") {\n const args = (ev.input ?? {}) as Record<string, string>;\n const tool = ev.tool ?? \"unknown\";\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-native:tool-start\", {\n detail: { tool, input: args },\n }),\n );\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:activity\", {\n detail: {\n label: runningToolLabel(tool),\n tool,\n tabId,\n },\n }),\n );\n }\n // Pass the server-assigned id so we upgrade the pending activity card\n // using id-match when available (parallel same-name calls stay separate).\n const pendingToolCallIndex = findPendingToolCallIndex(content, tool, ev.id);\n const pendingToolCall =\n pendingToolCallIndex >= 0 ? content[pendingToolCallIndex] : undefined;\n if (\n pendingToolCall &&\n pendingToolCall.type === \"tool-call\" &&\n pendingToolCall.activity === true &&\n pendingToolCall.argsText === \"\" &&\n Object.keys(pendingToolCall.args).length === 0\n ) {\n // Upgrade the pending activity card in place. Prefer the server-assigned\n // id so the subsequent tool_done can match it precisely (parallel\n // same-name calls each carry their own id). Fall back to the\n // locally-generated id already on the card.\n content[pendingToolCallIndex] = {\n type: \"tool-call\",\n toolCallId: ev.id ?? pendingToolCall.toolCallId,\n toolName: tool,\n argsText: JSON.stringify(args),\n args,\n };\n } else {\n content.push({\n type: \"tool-call\",\n toolCallId: ev.id ?? `tc_${++toolCallCounter.value}`,\n toolName: tool,\n argsText: JSON.stringify(args),\n args,\n });\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"tool_done\") {\n // Normalize identically to tool_start (which stores `ev.tool ?? \"unknown\"`)\n // so a tool_done frame with an undefined tool name still matches its\n // pending tool-call entry instead of leaving it forever unresolved.\n const doneTool = ev.tool ?? \"unknown\";\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-native:tool-done\", {\n detail: { tool: doneTool, result: ev.result },\n }),\n );\n }\n // Use id-based lookup when available so parallel same-name tool calls\n // get their results correctly assigned; fall back to name-matching.\n const doneIdx = findPendingToolCallIndex(content, doneTool, ev.id);\n if (doneIdx >= 0) {\n const part = content[doneIdx];\n if (part.type === \"tool-call\") {\n part.result = ev.result ?? \"\";\n if (ev.mcpApp) part.mcpApp = ev.mcpApp;\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"agent_call\") {\n const agentName = ev.agent ?? \"agent\";\n if (ev.status === \"start\") {\n const toolCallId = `tc_${++toolCallCounter.value}`;\n content.push({\n type: \"tool-call\",\n toolCallId,\n toolName: `agent:${agentName}`,\n argsText: \"\",\n args: {},\n });\n } else if (ev.status === \"done\" || ev.status === \"error\") {\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === `agent:${agentName}` &&\n part.result === undefined\n ) {\n part.result = ev.status === \"error\" ? \"Error calling agent\" : \"Done\";\n break;\n }\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"agent_call_text\") {\n const agentName = ev.agent ?? \"agent\";\n // Find the in-progress agent tool-call and append streaming text to argsText\n for (let i = content.length - 1; i >= 0; i--) {\n const part = content[i];\n if (\n part.type === \"tool-call\" &&\n part.toolName === `agent:${agentName}` &&\n part.result === undefined\n ) {\n part.argsText += ev.text ?? \"\";\n break;\n }\n }\n return {\n action: \"yield\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n // ─── Agent task events (sub-agent chips) ─────────────────────────\n // These events are dispatched as CustomEvents so AgentTaskCard components\n // can listen for updates to their specific taskId.\n if (\n ev.type === \"agent_task\" ||\n ev.type === \"agent_task_update\" ||\n ev.type === \"agent_task_complete\"\n ) {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"agent-task-event\", { detail: ev }));\n }\n // Don't add to content — the agent-teams tool call handles rendering\n return { action: \"continue\" };\n }\n\n if (ev.type === \"missing_api_key\") {\n const errMsg = LLM_MISSING_CREDENTIALS_MESSAGE;\n const errorCode = LLM_MISSING_CREDENTIALS_ERROR_CODE;\n const runError = {\n message: normalizeChatError(errMsg).message,\n errorCode,\n };\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(\"agent-chat:missing-api-key\"));\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:run-error\", {\n detail: { ...runError, tabId },\n }),\n );\n }\n settleInterruptedToolCalls(content);\n content.push({\n type: \"text\",\n text: formatChatErrorText(errMsg, undefined, errorCode),\n });\n return {\n action: \"missing_api_key\",\n result: {\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n metadata: { custom: { runError } },\n } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"loop_limit\") {\n const maxIterations =\n typeof ev.maxIterations === \"number\" ? ev.maxIterations : undefined;\n return {\n action: \"auto_continue\",\n autoContinue: {\n reason: \"loop_limit\",\n ...(maxIterations ? { maxIterations } : {}),\n },\n };\n }\n\n if (ev.type === \"auto_continue\") {\n const reason =\n ev.reason === \"stream_ended\" ||\n ev.reason === \"loop_limit\" ||\n ev.reason === \"no_progress\" ||\n ev.reason === \"run_timeout\"\n ? ev.reason\n : ev.errorCode === \"stream_ended\" ||\n ev.errorCode === \"loop_limit\" ||\n ev.errorCode === \"no_progress\" ||\n ev.errorCode === \"run_timeout\"\n ? ev.errorCode\n : ev.error === \"stream_ended\" ||\n ev.error === \"loop_limit\" ||\n ev.error === \"no_progress\" ||\n ev.error === \"run_timeout\"\n ? ev.error\n : ev.status === \"stream_ended\" ||\n ev.status === \"loop_limit\" ||\n ev.status === \"no_progress\" ||\n ev.status === \"run_timeout\"\n ? ev.status\n : \"run_timeout\";\n return {\n action: \"auto_continue\",\n autoContinue: {\n reason,\n ...(typeof ev.maxIterations === \"number\"\n ? { maxIterations: ev.maxIterations }\n : {}),\n },\n };\n }\n\n if (ev.type === \"error\") {\n const errMsg = ev.error ?? \"Unknown error\";\n if (\n (ev.errorCode === \"run_timeout\" && ev.recoverable) ||\n isAutoRecoverableError(ev, errMsg)\n ) {\n return {\n action: \"auto_continue\",\n autoContinue: {\n reason:\n ev.errorCode === \"stale_run\"\n ? \"stale_run\"\n : ev.errorCode === \"builder_gateway_timeout\" ||\n ev.errorCode === \"run_timeout\" ||\n errMsg.toLowerCase().includes(\"timeout\")\n ? \"run_timeout\"\n : \"stream_ended\",\n },\n };\n }\n const normalized = normalizeChatError(errMsg);\n if (isMissingCredentialText(errMsg, ev.errorCode)) {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new Event(\"agent-chat:missing-api-key\"));\n }\n }\n const runError = {\n message: normalized.message,\n ...(normalized.details || ev.details\n ? { details: ev.details ?? normalized.details }\n : {}),\n ...(ev.errorCode ? { errorCode: ev.errorCode } : {}),\n ...(ev.recoverable ? { recoverable: ev.recoverable } : {}),\n };\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agent-chat:run-error\", {\n detail: { ...runError, tabId },\n }),\n );\n }\n settleInterruptedToolCalls(content);\n content.push({\n type: \"text\",\n text: formatChatErrorText(errMsg, ev.upgradeUrl, ev.errorCode),\n });\n return {\n action: \"error\",\n result: {\n content: [...content],\n status: { type: \"incomplete\" as const, reason: \"error\" as const },\n metadata: { custom: { runError } },\n } as ChatModelRunResult,\n };\n }\n\n if (ev.type === \"done\") {\n return {\n action: \"done\",\n result: { content: [...content] } as ChatModelRunResult,\n };\n }\n\n return { action: \"continue\" };\n}\n\n/**\n * Read and process SSE events from a ReadableStream response body.\n * Yields ChatModelRunResult for each meaningful event.\n *\n * When `runId` is provided, every yielded result carries\n * `metadata.custom.runId` so the UI can expose the trace ID via\n * \"Copy Request ID\" — including mid-stream, so users can grab it before\n * the run completes (or if the run hangs / ends prematurely).\n */\nexport async function* readSSEStream(\n body: ReadableStream<Uint8Array>,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n onSeq?: (seq: number) => void,\n runId?: string | null,\n): AsyncGenerator<ChatModelRunResult> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = \"\";\n let lastMeaningfulEventAt = Date.now();\n const activityTrail: ActivityTrailEntry[] = [];\n\n const withStreamMetadata = (r: ChatModelRunResult): ChatModelRunResult => {\n if (!runId && activityTrail.length === 0) return r;\n const metadata = (r.metadata ?? {}) as Record<string, unknown>;\n const custom =\n metadata.custom && typeof metadata.custom === \"object\"\n ? (metadata.custom as Record<string, unknown>)\n : {};\n const runError =\n runId && custom.runError && typeof custom.runError === \"object\"\n ? {\n ...(custom.runError as Record<string, unknown>),\n runId,\n }\n : custom.runError;\n return {\n ...r,\n metadata: {\n ...metadata,\n custom: {\n ...custom,\n ...(runId ? { runId } : {}),\n ...(runError ? { runError } : {}),\n ...(activityTrail.length > 0\n ? { activityTrail: [...activityTrail] }\n : {}),\n },\n },\n };\n };\n\n try {\n while (true) {\n const { done, value } = await readChunkWithProgressTimeout(\n reader,\n lastMeaningfulEventAt,\n );\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n let sawDataEvent = false;\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const raw = line.slice(6).trim();\n if (!raw) continue;\n\n let ev: SSEEvent;\n try {\n ev = JSON.parse(raw);\n } catch {\n continue;\n }\n sawDataEvent = true;\n lastMeaningfulEventAt = Date.now();\n\n // Track sequence number for reconnection\n if (ev.seq !== undefined && onSeq) {\n onSeq(ev.seq);\n }\n\n if (ev.type === \"clear\") {\n activityTrail.length = 0;\n } else if (ev.type === \"activity\") {\n const tool = ev.tool?.trim() || undefined;\n appendActivityTrail(activityTrail, {\n label: humanizeToolLabelText(ev.label ?? \"Working\", tool),\n ...(tool ? { tool } : {}),\n });\n } else if (ev.type === \"tool_start\") {\n const tool = ev.tool ?? \"unknown\";\n appendActivityTrail(activityTrail, {\n label: runningToolLabel(tool),\n tool,\n });\n }\n\n const { action, result, autoContinue } = processEvent(\n ev,\n content,\n toolCallCounter,\n tabId,\n );\n\n if (result) yield withStreamMetadata(result);\n if (action === \"auto_continue\") {\n throw new AgentAutoContinueSignal(\n autoContinue\n ? { ...autoContinue, activityTrail: [...activityTrail] }\n : { reason: \"stream_ended\", activityTrail: [...activityTrail] },\n );\n }\n if (\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n return;\n }\n }\n\n if (\n !sawDataEvent &&\n Date.now() - lastMeaningfulEventAt >= SSE_NO_PROGRESS_TIMEOUT_MS\n ) {\n throw new AgentAutoContinueSignal({ reason: \"no_progress\" });\n }\n }\n } finally {\n try {\n reader.releaseLock();\n } catch {\n // The timeout path cancels the stream before unwinding; some runtimes\n // still consider the pending read active for a tick.\n }\n }\n\n // Stream ended without explicit done event. Even an empty content array is\n // abnormal here: a healthy run emits a terminal `done` event. Treat this as\n // recoverable so the adapter can first reconnect to the run, then continue\n // from durable history if the producer is gone.\n throw new AgentAutoContinueSignal({\n reason: \"stream_ended\",\n activityTrail: [...activityTrail],\n });\n}\n\n/**\n * Read raw SSE events from a ReadableStream and process them into ContentPart[].\n * Unlike readSSEStream, this doesn't yield ChatModelRunResult — it updates the\n * content array in-place and calls onUpdate for each meaningful change.\n * Designed for reconnection scenarios where we render outside assistant-ui's runtime.\n */\nexport async function readSSEStreamRaw(\n body: ReadableStream<Uint8Array>,\n content: ContentPart[],\n toolCallCounter: { value: number },\n tabId: string | undefined,\n onUpdate: (content: ContentPart[]) => void,\n): Promise<void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = \"\";\n let lastMeaningfulEventAt = Date.now();\n // Tracks whether the most recent content state was already pushed via\n // onUpdate inside the loop, so the post-loop flush below doesn't emit the\n // identical content a second time when the stream closes without a terminal\n // event.\n let emittedLatestContent = false;\n\n try {\n while (true) {\n const { done, value } = await readChunkWithProgressTimeout(\n reader,\n lastMeaningfulEventAt,\n );\n if (done) break;\n\n buf += decoder.decode(value, { stream: true });\n const lines = buf.split(\"\\n\");\n buf = lines.pop() ?? \"\";\n\n let updated = false;\n let sawDataEvent = false;\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue;\n const raw = line.slice(6).trim();\n if (!raw) continue;\n\n let ev: SSEEvent;\n try {\n ev = JSON.parse(raw);\n } catch {\n continue;\n }\n sawDataEvent = true;\n lastMeaningfulEventAt = Date.now();\n\n const { action, autoContinue } = processEvent(\n ev,\n content,\n toolCallCounter,\n tabId,\n );\n\n if (\n action === \"yield\" ||\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n updated = true;\n }\n if (action === \"auto_continue\") {\n onUpdate([...content]);\n throw new AgentAutoContinueSignal(\n autoContinue ?? { reason: \"stream_ended\" },\n );\n }\n if (\n action === \"done\" ||\n action === \"error\" ||\n action === \"missing_api_key\"\n ) {\n onUpdate([...content]);\n return;\n }\n }\n\n if (updated) {\n onUpdate([...content]);\n emittedLatestContent = true;\n }\n if (\n !sawDataEvent &&\n Date.now() - lastMeaningfulEventAt >= SSE_NO_PROGRESS_TIMEOUT_MS\n ) {\n throw new AgentAutoContinueSignal({ reason: \"no_progress\" });\n }\n }\n } finally {\n try {\n reader.releaseLock();\n } catch {\n // See readSSEStream: cancellation may race lock release in browsers.\n }\n }\n if (content.length > 0 && !emittedLatestContent) onUpdate([...content]);\n throw new AgentAutoContinueSignal({ reason: \"stream_ended\" });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/vite/client.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAU,UAAU,EAAE,MAAM,MAAM,CAAC;AAmB/C,OAAO,EAEL,KAAK,iCAAiC,EACvC,MAAM,kCAAkC,CAAC;AAyG1C;;;;;GAKG;AACH,iBAAS,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAgE9C;AAED;;;;;;GAMG;AACH,iBAAS,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAkCvD;AAsTD,MAAM,WAAW,YAAY;IAC3B,sGAAsG;IACtG,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,6DAA6D;IAC7D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oEAAoE;IACpE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4CAA4C;IAC5C,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,mBAAmB;IAClC,yCAAyC;IACzC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,6DAA6D;IAC7D,YAAY,CAAC,EAAE,WAAW,CAAC,WAAW,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC;IAC9E,oGAAoG;IACpG,QAAQ,CAAC,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;IAClC,8BAA8B;IAC9B,OAAO,CAAC,EAAE,GAAG,EAAE,CAAC;IAChB,iDAAiD;IACjD,KAAK,C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iCAAiC,CAAC;IAChD;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;;;;;;;;;;;;OAcG;IACH,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjD;AA+dD,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,IAAI,EAAE,MAAM,GAAG,SAAS,GACvB,MAAM,GAAG,SAAS,CAMpB;AAED,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GAAG,SAAS,GACvB,OAAO,CAWT;AAoMD;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,OAAO,GAAE,mBAAwB,GAAG,UAAU,CAiS1E;AAED,OAAO,EACL,eAAe,IAAI,gBAAgB,EACnC,mBAAmB,IAAI,oBAAoB,GAC5C,CAAC"}
|
package/dist/vite/client.js
CHANGED
|
@@ -1219,6 +1219,11 @@ export function defineConfig(options = {}) {
|
|
|
1219
1219
|
// and triggers a server restart when those files change.
|
|
1220
1220
|
noExternal: [
|
|
1221
1221
|
/^@agent-native\/core(\/.*)?$/,
|
|
1222
|
+
// Keep React Router in Vite's SSR module graph so resolve.dedupe
|
|
1223
|
+
// can force root.tsx and core's shared entry-server through the
|
|
1224
|
+
// same FrameworkContext instance.
|
|
1225
|
+
...(hasDep("react-router", cwd) ? [/^react-router(\/.*)?$/] : []),
|
|
1226
|
+
...(hasDep("react-router-dom", cwd) ? ["react-router-dom"] : []),
|
|
1222
1227
|
// Radix UI primitives are transitive deps of @agent-native/core
|
|
1223
1228
|
// (used by FeedbackButton, AgentSidebar, ShareDialog, etc.). When
|
|
1224
1229
|
// a consumer app SSRs a component that imports Radix, Node's
|
|
@@ -1238,14 +1243,7 @@ export function defineConfig(options = {}) {
|
|
|
1238
1243
|
: []),
|
|
1239
1244
|
...workspaceCoreNoExternal,
|
|
1240
1245
|
],
|
|
1241
|
-
external: [
|
|
1242
|
-
"react",
|
|
1243
|
-
"react-dom",
|
|
1244
|
-
"react-dom/server",
|
|
1245
|
-
"react-router",
|
|
1246
|
-
"react-router/dom",
|
|
1247
|
-
"react-router-dom",
|
|
1248
|
-
],
|
|
1246
|
+
external: ["react", "react-dom", "react-dom/server"],
|
|
1249
1247
|
},
|
|
1250
1248
|
plugins: [
|
|
1251
1249
|
// Stub packages from `options.ssrStubs` in the SSR bundle so they
|