@assistant-ui/react-ag-ui 0.0.54 → 0.0.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/index.d.ts +2 -2
  2. package/dist/index.js +2 -2
  3. package/dist/runtime/AgUiThreadRuntimeCore.d.ts +23 -2
  4. package/dist/runtime/AgUiThreadRuntimeCore.d.ts.map +1 -1
  5. package/dist/runtime/AgUiThreadRuntimeCore.js +169 -35
  6. package/dist/runtime/AgUiThreadRuntimeCore.js.map +1 -1
  7. package/dist/runtime/adapter/conversions.d.ts +13 -3
  8. package/dist/runtime/adapter/conversions.d.ts.map +1 -1
  9. package/dist/runtime/adapter/conversions.js +58 -26
  10. package/dist/runtime/adapter/conversions.js.map +1 -1
  11. package/dist/runtime/adapter/run-aggregator.d.ts +5 -1
  12. package/dist/runtime/adapter/run-aggregator.d.ts.map +1 -1
  13. package/dist/runtime/adapter/run-aggregator.js +26 -1
  14. package/dist/runtime/adapter/run-aggregator.js.map +1 -1
  15. package/dist/runtime/adapter/subscriber.d.ts +3 -0
  16. package/dist/runtime/adapter/subscriber.d.ts.map +1 -1
  17. package/dist/runtime/adapter/subscriber.js +9 -0
  18. package/dist/runtime/adapter/subscriber.js.map +1 -1
  19. package/dist/runtime/adapter/tool-approval.d.ts +56 -0
  20. package/dist/runtime/adapter/tool-approval.d.ts.map +1 -0
  21. package/dist/runtime/adapter/tool-approval.js +244 -0
  22. package/dist/runtime/adapter/tool-approval.js.map +1 -0
  23. package/dist/runtime/event-parser.d.ts.map +1 -1
  24. package/dist/runtime/event-parser.js +2 -1
  25. package/dist/runtime/event-parser.js.map +1 -1
  26. package/dist/runtime/interrupt-internals.d.ts +8 -0
  27. package/dist/runtime/interrupt-internals.d.ts.map +1 -0
  28. package/dist/runtime/interrupt-internals.js +25 -0
  29. package/dist/runtime/interrupt-internals.js.map +1 -0
  30. package/dist/useAgUiRuntime.js +3 -0
  31. package/dist/useAgUiRuntime.js.map +1 -1
  32. package/package.json +7 -7
  33. package/src/index.ts +8 -2
  34. package/src/runtime/AgUiThreadRuntimeCore.ts +314 -41
  35. package/src/runtime/adapter/conversions.content.test.ts +61 -3
  36. package/src/runtime/adapter/conversions.ts +83 -39
  37. package/src/runtime/adapter/run-aggregator.approval.test.ts +103 -0
  38. package/src/runtime/adapter/run-aggregator.ts +37 -1
  39. package/src/runtime/adapter/subscriber.ts +14 -0
  40. package/src/runtime/adapter/tool-approval.test.ts +681 -0
  41. package/src/runtime/adapter/tool-approval.ts +366 -0
  42. package/src/runtime/event-parser.ts +10 -1
  43. package/src/runtime/interrupt-internals.ts +35 -0
  44. package/src/useAgUiRuntime.approval.test.tsx +885 -0
  45. package/src/useAgUiRuntime.ts +4 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-approval.js","names":[],"sources":["../../../src/runtime/adapter/tool-approval.ts"],"sourcesContent":["import { buildResumeArray } from \"@ag-ui/client\";\nimport type {\n RespondToToolApprovalOptions,\n ThreadAssistantMessagePart,\n ToolCallMessagePart,\n} from \"@assistant-ui/core\";\nimport type { AgUiInterrupt, AgUiResumeEntry } from \"../types\";\nimport {\n readRawResponseSchema,\n withoutRawResponseSchema,\n} from \"../interrupt-internals\";\n\ntype ToolApproval = NonNullable<ToolCallMessagePart[\"approval\"]>;\n\nconst EMPTY_APPROVALS: ReadonlyMap<string, ToolApproval> = new Map();\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isString = (value: unknown) => typeof value === \"string\";\n\nconst JSON_SCHEMA_TYPES = new Set([\n \"null\",\n \"boolean\",\n \"object\",\n \"array\",\n \"number\",\n \"integer\",\n \"string\",\n]);\n\nconst isUniqueStrings = (value: unknown) =>\n Array.isArray(value) &&\n value.every(isString) &&\n new Set(value).size === value.length;\n\nconst isSchemaType = (type: unknown) =>\n (isString(type) && JSON_SCHEMA_TYPES.has(type as string)) ||\n (Array.isArray(type) &&\n type.length > 0 &&\n isUniqueStrings(type) &&\n type.every((entry) => JSON_SCHEMA_TYPES.has(entry as string)));\n\nconst acceptsType = (type: unknown, primitive: string) =>\n type === primitive ||\n (Array.isArray(type) && isSchemaType(type) && type.includes(primitive));\n\nconst acceptsObject = (type: unknown) => acceptsType(type, \"object\");\n\nconst SUB_SCHEMA_ANNOTATIONS = new Set([\n \"$schema\",\n \"$id\",\n \"title\",\n \"description\",\n]);\n\n/**\n * A field schema accepts a value of `primitive` only where nothing in it can\n * narrow past the type: an annotation carries no constraint, and an absent\n * `type` constrains nothing. Any other keyword — `const`, `enum`, `anyOf`,\n * `format` — can reject the value this seam sends, so it is not interpreted.\n */\nconst acceptsOnly = (schema: unknown, primitive: string) =>\n isPlainObject(schema) &&\n Object.entries(schema).every(([keyword, value]) =>\n keyword === \"type\"\n ? acceptsType(value, primitive)\n : SUB_SCHEMA_ANNOTATIONS.has(keyword) && isString(value),\n );\n\n/**\n * Keywords of a sub-schema whose value shape a validator reads, each paired\n * with that shape: the same shapes the top-level schema is held to, plus\n * `properties` and `items`, which carry schemas, so a malformed one nested\n * under them is as uncompilable as a malformed one at the top. A keyword this\n * seam cannot judge is left alone: unlike the top-level schema, a field the\n * seam never sends needs only to be compilable, not permissive.\n */\nconst SUB_SCHEMA_SHAPES = new Map<string, (value: unknown) => boolean>([\n [\"type\", isSchemaType],\n [\"required\", isUniqueStrings],\n ...[...SUB_SCHEMA_ANNOTATIONS].map(\n (annotation) =>\n [annotation, isString] as [string, (value: unknown) => boolean],\n ),\n [\n \"properties\",\n (value) =>\n isPlainObject(value) &&\n Object.values(value).every((schema) => isWellFormedSubSchema(schema)),\n ],\n [\"items\", (value) => isWellFormedSubSchema(value)],\n]);\n\n/**\n * A schema the server cannot compile fails the run whatever payload follows, so\n * a field this seam never sends is still checked for the shape a validator\n * reads it as. A boolean is a schema in its own right.\n */\nconst isWellFormedSubSchema = (schema: unknown): boolean =>\n typeof schema === \"boolean\" ||\n (isPlainObject(schema) &&\n Object.entries(schema).every(([keyword, value]) => {\n const holds = SUB_SCHEMA_SHAPES.get(keyword);\n return holds === undefined || holds(value);\n }));\n\n/**\n * AG-UI's own tool-approval schema declares the fields it expects under\n * `properties`, so a declaration is read where it cannot reject what the seam\n * sends: `approved` must accept a boolean and `reason` a string. A field the\n * seam never sends is unconstrained by `required` (which admits only\n * `approved`), so only its well-formedness as a sub-schema is checked — the\n * `editedArgs` of the spec's approve-with-edits shape is such a field.\n */\nconst acceptsSeamProperties = (properties: unknown) =>\n isPlainObject(properties) &&\n Object.entries(properties).every(([field, schema]) => {\n if (field === \"approved\") return acceptsOnly(schema, \"boolean\");\n if (field === \"reason\") return acceptsOnly(schema, \"string\");\n return isWellFormedSubSchema(schema);\n });\n\nconst acceptsSeamPayload = (required: unknown) =>\n Array.isArray(required) &&\n required.every((field) => field === \"approved\") &&\n new Set(required).size === required.length;\n\n/**\n * Keywords that cannot reject a payload this seam emits, each paired with the\n * check that its value is the well-formed shape the keyword is read as. A\n * keyword whose value a validator would reject as an invalid schema is not\n * decided here, because a server that compiles the schema fails the run. An\n * unlisted keyword — `additionalProperties`, `allOf`, `$ref` — makes the gate\n * bespoke rather than being interpreted. The map is keyed by\n * `Map` rather than by object property, because a schema key of `constructor`\n * or `toString` would otherwise read an `Object.prototype` member as its\n * validator and `__proto__` would read the prototype itself.\n */\nconst SEAM_SAFE_KEYWORDS = new Map<string, (value: unknown) => boolean>([\n [\"$schema\", isString],\n [\"$id\", isString],\n [\"title\", isString],\n [\"description\", isString],\n [\"type\", acceptsObject],\n [\"required\", acceptsSeamPayload],\n [\"properties\", acceptsSeamProperties],\n]);\n\n/**\n * The seam sends `{ approved }` and may add `reason`, so it may answer a\n * `responseSchema` only where acceptance of those exact payloads is established\n * by construction. AG-UI answers a resume payload its schema rejects with\n * `RunError`, and the host can always build the exact payload through the\n * bespoke interrupt hooks, so an undecidable schema is left to them. Only an\n * absent schema and a plain object of well-formed allowed keywords establish\n * that: a boolean schema (`false` rejects every payload), a malformed one, and\n * a keyword whose value is not the shape it interprets are all left bespoke.\n */\nconst isSeamAnswerable = (schema: unknown) => {\n if (schema === undefined) return true;\n if (!isPlainObject(schema)) return false;\n return Object.entries(schema).every(([keyword, value]) => {\n const accepts = SEAM_SAFE_KEYWORDS.get(keyword);\n return accepts !== undefined && accepts(value);\n });\n};\n\nconst isGate = (\n interrupt: AgUiInterrupt,\n): interrupt is AgUiInterrupt & { toolCallId: string } =>\n interrupt.reason === \"tool_call\" &&\n !!interrupt.id &&\n !!interrupt.toolCallId &&\n // A restored interrupt is untyped, so `responseSchema` may hold any persisted\n // shape; a non-object schema received live arrives on the internal carrier.\n readRawResponseSchema(interrupt) === undefined &&\n isSeamAnswerable(interrupt.responseSchema);\n\nconst isPending = (approval: ToolCallMessagePart[\"approval\"]) =>\n !!approval && approval.approved === undefined && !approval.resolution;\n\n/**\n * AG-UI binds a decision to a tool call with `reason: \"tool_call\"`;\n * `confirmation` is a free-standing yes/no and `input_required` wants structured\n * input, so both stay on the bespoke interrupt hooks, as does a `tool_call`\n * whose `responseSchema` asks for more than this seam can send. A batch mixing a\n * gate with any other interrupt projects nothing: AG-UI resumes with one\n * response per open interrupt, so a half-owned batch cannot be completed from\n * either side alone.\n *\n * The same rule covers binding. A gate naming a tool call the message does not\n * render can never be decided through this seam, so the batch it belongs to\n * could never be completed either: the decisions taken on its visible siblings\n * would sit on the message while the run waited for a response that no click\n * can produce. `boundToolCallIds` leaves such a batch bespoke instead.\n */\nexport const projectAgUiToolApprovals = (\n interrupts: readonly AgUiInterrupt[] | undefined,\n boundToolCallIds?: ReadonlySet<string>,\n): ReadonlyMap<string, ToolApproval> => {\n if (!interrupts?.length || !interrupts.every(isGate)) return EMPTY_APPROVALS;\n if (\n boundToolCallIds &&\n !interrupts.every((interrupt) => boundToolCallIds.has(interrupt.toolCallId))\n ) {\n return EMPTY_APPROVALS;\n }\n // Two gates naming one tool call would collapse into a single approval, so\n // the batch could never be completed: the surviving gate takes one decision\n // while the resume array still waits on the id that no part carries.\n const toolCallIds = interrupts.map((interrupt) => interrupt.toolCallId);\n if (new Set(toolCallIds).size !== toolCallIds.length) return EMPTY_APPROVALS;\n return new Map(\n interrupts.map((interrupt) => [interrupt.toolCallId, { id: interrupt.id }]),\n );\n};\n\n/**\n * Records a decision on the gated tool call. The decision is held on the part\n * until every gate in the batch is answered, because AG-UI resumes a run with\n * one response per open interrupt rather than one response per gate. A chosen\n * `optionId` is not recorded: the projection exposes an approval without\n * options, and core rejects an `optionId` absent from them, so no option can\n * reach this seam.\n */\nexport const withToolApprovalDecision = (\n content: readonly ThreadAssistantMessagePart[],\n { approvalId, approved, reason }: RespondToToolApprovalOptions,\n): readonly ThreadAssistantMessagePart[] => {\n let changed = false;\n const next = content.map((part) => {\n if (part.type !== \"tool-call\") return part;\n const approval = part.approval;\n if (approval?.id !== approvalId || !isPending(approval)) return part;\n changed = true;\n return {\n ...part,\n approval: {\n ...approval,\n approved,\n ...(reason !== undefined && { reason }),\n },\n };\n });\n return changed ? next : content;\n};\n\n/**\n * Maps the recorded decisions onto AG-UI resume entries, or `null` while the\n * batch is incomplete. A denial is a resolved response carrying\n * `approved: false`, not a cancellation: `cancelled` means the user abandoned\n * the interrupt without meaningful input and carries no payload, which would\n * drop the denial reason on the wire.\n */\nexport const buildToolApprovalResume = (\n content: readonly ThreadAssistantMessagePart[],\n interrupts: readonly AgUiInterrupt[],\n): AgUiResumeEntry[] | null => {\n const open = new Set(interrupts.map((interrupt) => interrupt.id));\n // Decisions accumulate in a `Map` rather than in an object literal, because an\n // interrupt id of `__proto__` would otherwise write to the prototype chain\n // instead of recording a response, and `constructor` or `toString` would\n // report themselves as answered while undecided.\n const responses = new Map<string, { status: \"resolved\"; payload: unknown }>();\n for (const part of content) {\n if (part.type !== \"tool-call\") continue;\n const approval = part.approval;\n if (!approval || approval.approved === undefined) continue;\n if (!open.has(approval.id)) continue;\n responses.set(approval.id, {\n status: \"resolved\",\n payload: {\n approved: approval.approved,\n ...(approval.reason !== undefined && { reason: approval.reason }),\n },\n });\n }\n if (interrupts.some((interrupt) => !responses.has(interrupt.id))) return null;\n // The schema is dropped rather than cast: AG-UI's own interrupt type cannot\n // express a boolean schema, and `buildResumeArray` reads only the ids.\n return buildResumeArray(\n interrupts.map((interrupt) => {\n const { responseSchema: _schema, ...rest } =\n withoutRawResponseSchema(interrupt);\n return rest;\n }),\n Object.fromEntries(responses),\n );\n};\n\nconst settle = (\n approval: ToolApproval,\n entry: AgUiResumeEntry,\n): ToolApproval | undefined => {\n // A decision this gate recorded locally but never sent is dropped rather than\n // displayed beside the settlement it contradicts: a submitted entry carries\n // the whole outcome, so no field of an earlier one may survive it.\n const {\n approved: _approved,\n reason: _reason,\n resolution: _resolution,\n ...rest\n } = approval;\n if (entry.status === \"cancelled\") {\n return { ...rest, resolution: \"cancelled\" };\n }\n const payload = entry.payload;\n if (\n typeof payload !== \"object\" ||\n payload === null ||\n typeof (payload as { approved?: unknown }).approved !== \"boolean\"\n ) {\n // The entry settles the gate with no decision. Nothing is fabricated, and a\n // decision recorded locally is dropped: the payload that went out carried\n // none, so displaying one would show what was never sent. The gate is still\n // marked terminal, because the interrupt it belonged to is closed and a\n // click on it afterwards would find nothing pending.\n return { ...rest, resolution: \"cancelled\" };\n }\n const { approved, reason } = payload as {\n approved: boolean;\n reason?: unknown;\n };\n return {\n ...rest,\n approved,\n ...(typeof reason === \"string\" && { reason }),\n };\n};\n\n/**\n * Settles every gate the submitted resume array names, so the displayed outcome\n * cannot contradict the wire. A decision recorded locally is not exempt: a gate\n * approved while the batch waited on its sibling is still cancelled when\n * `steerAway` submits a cancellation for it. A gate is shown as cancelled only\n * where its own entry is cancelled; a resolved entry supplies the decision it\n * carries, and one that carries none settles the gate with no decision rather\n * than fabricating one or keeping an unsent local decision beside it.\n *\n * A settlement always overrides an earlier one, in either direction. A resolved\n * settlement leaves no state a locally recorded decision does not also leave —\n * core's `resolution` covers only `cancelled` and `expired` — so honoring the\n * first settlement instead would mean treating an unsent local decision as\n * terminal, which is exactly what the cancellation case must override.\n */\nexport const withSettledToolApprovals = (\n content: readonly ThreadAssistantMessagePart[],\n resume: readonly AgUiResumeEntry[],\n): readonly ThreadAssistantMessagePart[] => {\n if (resume.length === 0) return content;\n const byId = new Map(resume.map((entry) => [entry.interruptId, entry]));\n let changed = false;\n const next = content.map((part) => {\n if (part.type !== \"tool-call\") return part;\n const approval = part.approval;\n if (!approval) return part;\n const entry = byId.get(approval.id);\n if (!entry) return part;\n const settled = settle(approval, entry);\n if (!settled) return part;\n changed = true;\n return { ...part, approval: settled };\n });\n return changed ? next : content;\n};\n"],"mappings":";;;AAcA,MAAM,kCAAqD,IAAI,IAAI;AAEnE,MAAM,iBAAiB,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,MAAM,YAAY,UAAmB,OAAO,UAAU;AAEtD,MAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,mBAAmB,UACvB,MAAM,QAAQ,KAAK,KACnB,MAAM,MAAM,QAAQ,KACpB,IAAI,IAAI,KAAK,CAAC,CAAC,SAAS,MAAM;AAEhC,MAAM,gBAAgB,SACnB,SAAS,IAAI,KAAK,kBAAkB,IAAI,IAAc,KACtD,MAAM,QAAQ,IAAI,KACjB,KAAK,SAAS,KACd,gBAAgB,IAAI,KACpB,KAAK,OAAO,UAAU,kBAAkB,IAAI,KAAe,CAAC;AAEhE,MAAM,eAAe,MAAe,cAClC,SAAS,aACR,MAAM,QAAQ,IAAI,KAAK,aAAa,IAAI,KAAK,KAAK,SAAS,SAAS;AAEvE,MAAM,iBAAiB,SAAkB,YAAY,MAAM,QAAQ;AAEnE,MAAM,yCAAyB,IAAI,IAAI;CACrC;CACA;CACA;CACA;AACF,CAAC;;;;;;;AAQD,MAAM,eAAe,QAAiB,cACpC,cAAc,MAAM,KACpB,OAAO,QAAQ,MAAM,CAAC,CAAC,OAA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,YAAY,EAAE,OAAO;CAC7C;AACF;;;;;;;;;;;;;;;;AAiBA,MAAa,4BACX,SACA,WAC0C;CAC1C,IAAI,OAAO,WAAW,GAAG,OAAO;CAChC,MAAM,OAAO,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC,MAAM,aAAa,KAAK,CAAC,CAAC;CACtE,IAAI,UAAU;CACd,MAAM,OAAO,QAAQ,KAAK,SAAS;EACjC,IAAI,KAAK,SAAS,aAAa,OAAO;EACtC,MAAM,WAAW,KAAK;EACtB,IAAI,CAAC,UAAU,OAAO;EACtB,MAAM,QAAQ,KAAK,IAAI,SAAS,EAAE;EAClC,IAAI,CAAC,OAAO,OAAO;EACnB,MAAM,UAAU,OAAO,UAAU,KAAK;EACtC,IAAI,CAAC,SAAS,OAAO;EACrB,UAAU;EACV,OAAO;GAAE,GAAG;GAAM,UAAU;EAAQ;CACtC,CAAC;CACD,OAAO,UAAU,OAAO;AAC1B"}
@@ -1 +1 @@
1
- {"version":3,"file":"event-parser.d.ts","names":[],"sources":["../../src/runtime/event-parser.ts"],"mappings":";;;KAIY;EACV,SAAS;;cAkEE,iBACX,gBACA,UAAU,0BACT"}
1
+ {"version":3,"file":"event-parser.d.ts","names":[],"sources":["../../src/runtime/event-parser.ts"],"mappings":";;;KAKY;EACV,SAAS;;cA0EE,iBACX,gBACA,UAAU,0BACT"}
@@ -1,4 +1,5 @@
1
1
  import { parseMcpToolCallResult } from "./mcp-tool-result.js";
2
+ import { withRawResponseSchema } from "./interrupt-internals.js";
2
3
  //#region src/runtime/event-parser.ts
3
4
  const isString = (value) => typeof value === "string";
4
5
  const isNonEmptyString = (value) => isString(value) && value.length > 0;
@@ -24,7 +25,7 @@ const parseInterrupt = (raw) => {
24
25
  if (typeof raw.expiresAt === "string") interrupt.expiresAt = raw.expiresAt;
25
26
  if (isPlainObject(raw.responseSchema)) interrupt.responseSchema = raw.responseSchema;
26
27
  if (isPlainObject(raw.metadata)) interrupt.metadata = raw.metadata;
27
- return interrupt;
28
+ return raw.responseSchema == null || isPlainObject(raw.responseSchema) ? interrupt : withRawResponseSchema(interrupt, raw.responseSchema);
28
29
  };
29
30
  const parseRunFinishedOutcome = (raw, logger) => {
30
31
  if (!isPlainObject(raw)) return void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"event-parser.js","names":[],"sources":["../../src/runtime/event-parser.ts"],"sourcesContent":["import type { AgUiEvent, AgUiInterrupt, AgUiRunFinishedOutcome } from \"./types\";\nimport type { Logger } from \"./logger\";\nimport { parseMcpToolCallResult } from \"./mcp-tool-result\";\n\nexport type ParseAgUiEventOptions = {\n logger?: Logger;\n};\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\nconst isNonEmptyString = (value: unknown): value is string =>\n isString(value) && value.length > 0;\n\nconst withOptional = <T extends object>(\n base: T,\n optionals: Record<string, unknown>,\n) => {\n const definedEntries = Object.entries(optionals).filter(\n ([, value]) => value !== undefined,\n );\n return definedEntries.length === 0\n ? base\n : ({ ...base, ...Object.fromEntries(definedEntries) } as T);\n};\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value);\n\nconst parseInterrupt = (raw: unknown): AgUiInterrupt | null => {\n if (!isPlainObject(raw)) return null;\n const id = raw.id;\n const reason = raw.reason;\n if (typeof id !== \"string\" || typeof reason !== \"string\") return null;\n const interrupt: AgUiInterrupt = { id, reason };\n if (typeof raw.message === \"string\") interrupt.message = raw.message;\n if (typeof raw.toolCallId === \"string\") interrupt.toolCallId = raw.toolCallId;\n if (typeof raw.expiresAt === \"string\") interrupt.expiresAt = raw.expiresAt;\n if (isPlainObject(raw.responseSchema))\n interrupt.responseSchema = raw.responseSchema;\n if (isPlainObject(raw.metadata)) interrupt.metadata = raw.metadata;\n return interrupt;\n};\n\nconst parseRunFinishedOutcome = (\n raw: unknown,\n logger: Logger | undefined,\n): AgUiRunFinishedOutcome | undefined => {\n if (!isPlainObject(raw)) return undefined;\n if (raw.type === \"success\") return { type: \"success\" };\n if (raw.type === \"interrupt\") {\n if (!Array.isArray(raw.interrupts)) {\n logger?.debug?.(\n \"[agui] RUN_FINISHED interrupt outcome missing interrupts array\",\n raw,\n );\n return undefined;\n }\n const parsed = raw.interrupts\n .map((entry) => parseInterrupt(entry))\n .filter((entry): entry is AgUiInterrupt => entry !== null);\n if (parsed.length === 0) {\n logger?.debug?.(\n \"[agui] RUN_FINISHED interrupt outcome has no valid interrupts\",\n raw.interrupts,\n );\n return undefined;\n }\n return { type: \"interrupt\", interrupts: parsed };\n }\n return undefined;\n};\n\nexport const parseAgUiEvent = (\n event: unknown,\n options?: ParseAgUiEventOptions,\n): AgUiEvent | null => {\n if (!event || typeof event !== \"object\") return null;\n const payload = event as Record<string, unknown>;\n const typeValue = payload.type;\n if (!isString(typeValue)) return null;\n\n const getString = (key: string) =>\n isString(payload[key]) ? (payload[key] as string) : undefined;\n\n switch (typeValue) {\n case \"RUN_STARTED\": {\n const runId = getString(\"runId\");\n return runId ? { type: \"RUN_STARTED\", runId } : null;\n }\n case \"RUN_FINISHED\": {\n const runId = getString(\"runId\");\n if (!runId) return null;\n return withOptional(\n { type: \"RUN_FINISHED\" as const, runId },\n {\n outcome: parseRunFinishedOutcome(payload.outcome, options?.logger),\n },\n );\n }\n case \"RUN_CANCELLED\": {\n const runId = getString(\"runId\");\n return withOptional({ type: \"RUN_CANCELLED\" as const }, { runId });\n }\n case \"RUN_ERROR\": {\n return withOptional(\n { type: \"RUN_ERROR\" as const },\n {\n message: getString(\"message\"),\n code: getString(\"code\"),\n },\n );\n }\n case \"TEXT_MESSAGE_START\":\n return withOptional(\n { type: \"TEXT_MESSAGE_START\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"TEXT_MESSAGE_CONTENT\": {\n const delta = getString(\"delta\");\n if (!isNonEmptyString(delta)) return null;\n return withOptional(\n { type: \"TEXT_MESSAGE_CONTENT\" as const, delta },\n { messageId: getString(\"messageId\") },\n );\n }\n case \"TEXT_MESSAGE_END\":\n return withOptional(\n { type: \"TEXT_MESSAGE_END\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"TEXT_MESSAGE_CHUNK\": {\n const delta = getString(\"delta\") ?? \"\";\n return withOptional(\n { type: \"TEXT_MESSAGE_CHUNK\" as const, delta },\n { messageId: getString(\"messageId\") },\n );\n }\n case \"THINKING_START\":\n return withOptional(\n { type: \"THINKING_START\" as const },\n { title: getString(\"title\") },\n );\n case \"THINKING_TEXT_MESSAGE_START\":\n return { type: \"THINKING_TEXT_MESSAGE_START\" };\n case \"THINKING_TEXT_MESSAGE_CONTENT\": {\n const delta = getString(\"delta\") ?? \"\";\n return { type: \"THINKING_TEXT_MESSAGE_CONTENT\", delta };\n }\n case \"THINKING_TEXT_MESSAGE_END\":\n return { type: \"THINKING_TEXT_MESSAGE_END\" };\n case \"THINKING_END\":\n return { type: \"THINKING_END\" };\n case \"REASONING_START\":\n return withOptional(\n { type: \"REASONING_START\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"REASONING_MESSAGE_START\":\n return withOptional(\n { type: \"REASONING_MESSAGE_START\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"REASONING_MESSAGE_CONTENT\": {\n const delta = getString(\"delta\") ?? \"\";\n return withOptional(\n { type: \"REASONING_MESSAGE_CONTENT\" as const, delta },\n { messageId: getString(\"messageId\") },\n );\n }\n case \"REASONING_MESSAGE_END\":\n return withOptional(\n { type: \"REASONING_MESSAGE_END\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"REASONING_ENCRYPTED_VALUE\": {\n const entityId = getString(\"entityId\");\n const encryptedValue = getString(\"encryptedValue\");\n const subtype = getString(\"subtype\");\n if (!entityId || !encryptedValue) return null;\n if (subtype !== \"message\" && subtype !== \"tool-call\") return null;\n return {\n type: \"REASONING_ENCRYPTED_VALUE\" as const,\n subtype,\n entityId,\n encryptedValue,\n };\n }\n case \"REASONING_END\":\n return withOptional(\n { type: \"REASONING_END\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"TOOL_CALL_START\": {\n const toolCallId = getString(\"toolCallId\");\n if (!toolCallId) return null;\n return withOptional(\n { type: \"TOOL_CALL_START\" as const, toolCallId },\n {\n toolCallName: getString(\"toolCallName\"),\n parentMessageId: getString(\"parentMessageId\"),\n },\n );\n }\n case \"TOOL_CALL_ARGS\": {\n const toolCallId = getString(\"toolCallId\");\n if (!toolCallId) return null;\n const delta = getString(\"delta\") ?? \"\";\n return { type: \"TOOL_CALL_ARGS\", toolCallId, delta };\n }\n case \"TOOL_CALL_END\": {\n const toolCallId = getString(\"toolCallId\");\n return toolCallId ? { type: \"TOOL_CALL_END\", toolCallId } : null;\n }\n case \"TOOL_CALL_CHUNK\":\n return withOptional(\n { type: \"TOOL_CALL_CHUNK\" as const },\n {\n toolCallId: getString(\"toolCallId\"),\n toolCallName: getString(\"toolCallName\"),\n parentMessageId: getString(\"parentMessageId\"),\n delta: getString(\"delta\"),\n },\n );\n case \"TOOL_CALL_RESULT\": {\n const toolCallId = getString(\"toolCallId\");\n if (!toolCallId) return null;\n const content = getString(\"content\") ?? \"\";\n return withOptional(\n {\n type: \"TOOL_CALL_RESULT\" as const,\n toolCallId,\n content,\n },\n {\n messageId: getString(\"messageId\"),\n role: payload.role === \"tool\" ? \"tool\" : undefined,\n mcpResult: parseMcpToolCallResult(payload, content),\n },\n );\n }\n case \"STATE_SNAPSHOT\":\n return { type: \"STATE_SNAPSHOT\", snapshot: payload.snapshot };\n case \"STATE_DELTA\":\n return {\n type: \"STATE_DELTA\",\n delta: Array.isArray(payload.delta) ? (payload.delta as any[]) : [],\n };\n case \"MESSAGES_SNAPSHOT\":\n return {\n type: \"MESSAGES_SNAPSHOT\",\n messages: Array.isArray(payload.messages)\n ? (payload.messages as any[])\n : [],\n };\n case \"ACTIVITY_SNAPSHOT\": {\n const activityType = getString(\"activityType\");\n if (!activityType || !isPlainObject(payload.content)) return null;\n return withOptional(\n {\n type: \"ACTIVITY_SNAPSHOT\" as const,\n activityType,\n content: payload.content,\n },\n {\n messageId: getString(\"messageId\"),\n replace:\n typeof payload.replace === \"boolean\" ? payload.replace : undefined,\n },\n );\n }\n case \"RAW\":\n return withOptional(\n { type: \"RAW\" as const, event: payload.event },\n { source: getString(\"source\") },\n );\n case \"CUSTOM\": {\n const name = getString(\"name\");\n if (!name) return null;\n return { type: \"CUSTOM\", name, value: payload.value };\n }\n default:\n return withOptional(\n { type: \"RAW\" as const, event: payload },\n {\n source: isString(payload.type) ? (payload.type as string) : undefined,\n },\n );\n }\n};\n"],"mappings":";;AAQA,MAAM,YAAY,UAAoC,OAAO,UAAU;AACvE,MAAM,oBAAoB,UACxB,SAAS,KAAK,KAAK,MAAM,SAAS;AAEpC,MAAM,gBACJ,MACA,cACG;CACH,MAAM,iBAAiB,OAAO,QAAQ,SAAS,CAAC,CAAC,QAC9C,GAAG,WAAW,UAAU,KAAA,CAC3B;CACA,OAAO,eAAe,WAAW,IAC7B,OACC;EAAE,GAAG;EAAM,GAAG,OAAO,YAAY,cAAc;CAAE;AACxD;AAEA,MAAM,iBAAiB,UACrB,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAE9D,MAAM,kBAAkB,QAAuC;CAC7D,IAAI,CAAC,cAAc,GAAG,GAAG,OAAO;CAChC,MAAM,KAAK,IAAI;CACf,MAAM,SAAS,IAAI;CACnB,IAAI,OAAO,OAAO,YAAY,OAAO,WAAW,UAAU,OAAO;CACjE,MAAM,YAA2B;EAAE;EAAI;CAAO;CAC9C,IAAI,OAAO,IAAI,YAAY,UAAU,UAAU,UAAU,IAAI;CAC7D,IAAI,OAAO,IAAI,eAAe,UAAU,UAAU,aAAa,IAAI;CACnE,IAAI,OAAO,IAAI,cAAc,UAAU,UAAU,YAAY,IAAI;CACjE,IAAI,cAAc,IAAI,cAAc,GAClC,UAAU,iBAAiB,IAAI;CACjC,IAAI,cAAc,IAAI,QAAQ,GAAG,UAAU,WAAW,IAAI;CAC1D,OAAO;AACT;AAEA,MAAM,2BACJ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O;GACpD,CACF;EACF;EACA,KAAK,kBACH,OAAO;GAAE,MAAM;GAAkB,UAAU,QAAQ;EAAS;EAC9D,KAAK,eACH,OAAO;GACL,MAAM;GACN,OAAO,MAAM,QAAQ,QAAQ,KAAK,IAAK,QAAQ,QAAkB,CAAC;EACpE;EACF,KAAK,qBACH,OAAO;GACL,MAAM;GACN,UAAU,MAAM,QAAQ,QAAQ,QAAQ,IACnC,QAAQ,WACT,CAAC;EACP;EACF,KAAK,qBAAqB;GACxB,MAAM,eAAe,UAAU,cAAc;GAC7C,IAAI,CAAC,gBAAgB,CAAC,cAAc,QAAQ,OAAO,GAAG,OAAO;GAC7D,OAAO,aACL;IACE,MAAM;IACN;IACA,SAAS,QAAQ;GACnB,GACA;IACE,WAAW,UAAU,WAAW;IAChC,SACE,OAAO,QAAQ,YAAY,YAAY,QAAQ,UAAU,KAAA;GAC7D,CACF;EACF;EACA,KAAK,OACH,OAAO,aACL;GAAE,MAAM;GAAgB,OAAO,QAAQ;EAAM,GAC7C,EAAE,QAAQ,UAAU,QAAQ,EAAE,CAChC;EACF,KAAK,UAAU;GACb,MAAM,OAAO,UAAU,MAAM;GAC7B,IAAI,CAAC,MAAM,OAAO;GAClB,OAAO;IAAE,MAAM;IAAU;IAAM,OAAO,QAAQ;GAAM;EACtD;EACA,SACE,OAAO,aACL;GAAE,MAAM;GAAgB,OAAO;EAAQ,GACvC,EACE,QAAQ,SAAS,QAAQ,IAAI,IAAK,QAAQ,OAAkB,KAAA,EAC9D,CACF;CACJ;AACF"}
1
+ {"version":3,"file":"event-parser.js","names":[],"sources":["../../src/runtime/event-parser.ts"],"sourcesContent":["import type { AgUiEvent, AgUiInterrupt, AgUiRunFinishedOutcome } from \"./types\";\nimport type { Logger } from \"./logger\";\nimport { parseMcpToolCallResult } from \"./mcp-tool-result\";\nimport { withRawResponseSchema } from \"./interrupt-internals\";\n\nexport type ParseAgUiEventOptions = {\n logger?: Logger;\n};\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\nconst isNonEmptyString = (value: unknown): value is string =>\n isString(value) && value.length > 0;\n\nconst withOptional = <T extends object>(\n base: T,\n optionals: Record<string, unknown>,\n) => {\n const definedEntries = Object.entries(optionals).filter(\n ([, value]) => value !== undefined,\n );\n return definedEntries.length === 0\n ? base\n : ({ ...base, ...Object.fromEntries(definedEntries) } as T);\n};\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === \"object\" && !Array.isArray(value);\n\nconst parseInterrupt = (raw: unknown): AgUiInterrupt | null => {\n if (!isPlainObject(raw)) return null;\n const id = raw.id;\n const reason = raw.reason;\n if (typeof id !== \"string\" || typeof reason !== \"string\") return null;\n const interrupt: AgUiInterrupt = { id, reason };\n if (typeof raw.message === \"string\") interrupt.message = raw.message;\n if (typeof raw.toolCallId === \"string\") interrupt.toolCallId = raw.toolCallId;\n if (typeof raw.expiresAt === \"string\") interrupt.expiresAt = raw.expiresAt;\n if (isPlainObject(raw.responseSchema))\n interrupt.responseSchema = raw.responseSchema;\n if (isPlainObject(raw.metadata)) interrupt.metadata = raw.metadata;\n // A present schema is kept whatever its shape: `false` is a JSON Schema that\n // rejects every payload, so normalizing it to absent would claim a gate no\n // decision can answer. Only an object schema fits `responseSchema`; every\n // other shape travels on the internal carrier. `null` is not a JSON Schema at\n // all, and it is what a server serializing an unset optional field sends, so\n // it reads as absent rather than as a schema nothing can satisfy.\n return raw.responseSchema == null || isPlainObject(raw.responseSchema)\n ? interrupt\n : withRawResponseSchema(interrupt, raw.responseSchema);\n};\n\nconst parseRunFinishedOutcome = (\n raw: unknown,\n logger: Logger | undefined,\n): AgUiRunFinishedOutcome | undefined => {\n if (!isPlainObject(raw)) return undefined;\n if (raw.type === \"success\") return { type: \"success\" };\n if (raw.type === \"interrupt\") {\n if (!Array.isArray(raw.interrupts)) {\n logger?.debug?.(\n \"[agui] RUN_FINISHED interrupt outcome missing interrupts array\",\n raw,\n );\n return undefined;\n }\n const parsed = raw.interrupts\n .map((entry) => parseInterrupt(entry))\n .filter((entry): entry is AgUiInterrupt => entry !== null);\n if (parsed.length === 0) {\n logger?.debug?.(\n \"[agui] RUN_FINISHED interrupt outcome has no valid interrupts\",\n raw.interrupts,\n );\n return undefined;\n }\n return { type: \"interrupt\", interrupts: parsed };\n }\n return undefined;\n};\n\nexport const parseAgUiEvent = (\n event: unknown,\n options?: ParseAgUiEventOptions,\n): AgUiEvent | null => {\n if (!event || typeof event !== \"object\") return null;\n const payload = event as Record<string, unknown>;\n const typeValue = payload.type;\n if (!isString(typeValue)) return null;\n\n const getString = (key: string) =>\n isString(payload[key]) ? (payload[key] as string) : undefined;\n\n switch (typeValue) {\n case \"RUN_STARTED\": {\n const runId = getString(\"runId\");\n return runId ? { type: \"RUN_STARTED\", runId } : null;\n }\n case \"RUN_FINISHED\": {\n const runId = getString(\"runId\");\n if (!runId) return null;\n return withOptional(\n { type: \"RUN_FINISHED\" as const, runId },\n {\n outcome: parseRunFinishedOutcome(payload.outcome, options?.logger),\n },\n );\n }\n case \"RUN_CANCELLED\": {\n const runId = getString(\"runId\");\n return withOptional({ type: \"RUN_CANCELLED\" as const }, { runId });\n }\n case \"RUN_ERROR\": {\n return withOptional(\n { type: \"RUN_ERROR\" as const },\n {\n message: getString(\"message\"),\n code: getString(\"code\"),\n },\n );\n }\n case \"TEXT_MESSAGE_START\":\n return withOptional(\n { type: \"TEXT_MESSAGE_START\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"TEXT_MESSAGE_CONTENT\": {\n const delta = getString(\"delta\");\n if (!isNonEmptyString(delta)) return null;\n return withOptional(\n { type: \"TEXT_MESSAGE_CONTENT\" as const, delta },\n { messageId: getString(\"messageId\") },\n );\n }\n case \"TEXT_MESSAGE_END\":\n return withOptional(\n { type: \"TEXT_MESSAGE_END\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"TEXT_MESSAGE_CHUNK\": {\n const delta = getString(\"delta\") ?? \"\";\n return withOptional(\n { type: \"TEXT_MESSAGE_CHUNK\" as const, delta },\n { messageId: getString(\"messageId\") },\n );\n }\n case \"THINKING_START\":\n return withOptional(\n { type: \"THINKING_START\" as const },\n { title: getString(\"title\") },\n );\n case \"THINKING_TEXT_MESSAGE_START\":\n return { type: \"THINKING_TEXT_MESSAGE_START\" };\n case \"THINKING_TEXT_MESSAGE_CONTENT\": {\n const delta = getString(\"delta\") ?? \"\";\n return { type: \"THINKING_TEXT_MESSAGE_CONTENT\", delta };\n }\n case \"THINKING_TEXT_MESSAGE_END\":\n return { type: \"THINKING_TEXT_MESSAGE_END\" };\n case \"THINKING_END\":\n return { type: \"THINKING_END\" };\n case \"REASONING_START\":\n return withOptional(\n { type: \"REASONING_START\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"REASONING_MESSAGE_START\":\n return withOptional(\n { type: \"REASONING_MESSAGE_START\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"REASONING_MESSAGE_CONTENT\": {\n const delta = getString(\"delta\") ?? \"\";\n return withOptional(\n { type: \"REASONING_MESSAGE_CONTENT\" as const, delta },\n { messageId: getString(\"messageId\") },\n );\n }\n case \"REASONING_MESSAGE_END\":\n return withOptional(\n { type: \"REASONING_MESSAGE_END\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"REASONING_ENCRYPTED_VALUE\": {\n const entityId = getString(\"entityId\");\n const encryptedValue = getString(\"encryptedValue\");\n const subtype = getString(\"subtype\");\n if (!entityId || !encryptedValue) return null;\n if (subtype !== \"message\" && subtype !== \"tool-call\") return null;\n return {\n type: \"REASONING_ENCRYPTED_VALUE\" as const,\n subtype,\n entityId,\n encryptedValue,\n };\n }\n case \"REASONING_END\":\n return withOptional(\n { type: \"REASONING_END\" as const },\n { messageId: getString(\"messageId\") },\n );\n case \"TOOL_CALL_START\": {\n const toolCallId = getString(\"toolCallId\");\n if (!toolCallId) return null;\n return withOptional(\n { type: \"TOOL_CALL_START\" as const, toolCallId },\n {\n toolCallName: getString(\"toolCallName\"),\n parentMessageId: getString(\"parentMessageId\"),\n },\n );\n }\n case \"TOOL_CALL_ARGS\": {\n const toolCallId = getString(\"toolCallId\");\n if (!toolCallId) return null;\n const delta = getString(\"delta\") ?? \"\";\n return { type: \"TOOL_CALL_ARGS\", toolCallId, delta };\n }\n case \"TOOL_CALL_END\": {\n const toolCallId = getString(\"toolCallId\");\n return toolCallId ? { type: \"TOOL_CALL_END\", toolCallId } : null;\n }\n case \"TOOL_CALL_CHUNK\":\n return withOptional(\n { type: \"TOOL_CALL_CHUNK\" as const },\n {\n toolCallId: getString(\"toolCallId\"),\n toolCallName: getString(\"toolCallName\"),\n parentMessageId: getString(\"parentMessageId\"),\n delta: getString(\"delta\"),\n },\n );\n case \"TOOL_CALL_RESULT\": {\n const toolCallId = getString(\"toolCallId\");\n if (!toolCallId) return null;\n const content = getString(\"content\") ?? \"\";\n return withOptional(\n {\n type: \"TOOL_CALL_RESULT\" as const,\n toolCallId,\n content,\n },\n {\n messageId: getString(\"messageId\"),\n role: payload.role === \"tool\" ? \"tool\" : undefined,\n mcpResult: parseMcpToolCallResult(payload, content),\n },\n );\n }\n case \"STATE_SNAPSHOT\":\n return { type: \"STATE_SNAPSHOT\", snapshot: payload.snapshot };\n case \"STATE_DELTA\":\n return {\n type: \"STATE_DELTA\",\n delta: Array.isArray(payload.delta) ? (payload.delta as any[]) : [],\n };\n case \"MESSAGES_SNAPSHOT\":\n return {\n type: \"MESSAGES_SNAPSHOT\",\n messages: Array.isArray(payload.messages)\n ? (payload.messages as any[])\n : [],\n };\n case \"ACTIVITY_SNAPSHOT\": {\n const activityType = getString(\"activityType\");\n if (!activityType || !isPlainObject(payload.content)) return null;\n return withOptional(\n {\n type: \"ACTIVITY_SNAPSHOT\" as const,\n activityType,\n content: payload.content,\n },\n {\n messageId: getString(\"messageId\"),\n replace:\n typeof payload.replace === \"boolean\" ? payload.replace : undefined,\n },\n );\n }\n case \"RAW\":\n return withOptional(\n { type: \"RAW\" as const, event: payload.event },\n { source: getString(\"source\") },\n );\n case \"CUSTOM\": {\n const name = getString(\"name\");\n if (!name) return null;\n return { type: \"CUSTOM\", name, value: payload.value };\n }\n default:\n return withOptional(\n { type: \"RAW\" as const, event: payload },\n {\n source: isString(payload.type) ? (payload.type as string) : undefined,\n },\n );\n }\n};\n"],"mappings":";;;AASA,MAAM,YAAY,UAAoC,OAAO,UAAU;AACvE,MAAM,oBAAoB,UACxB,SAAS,KAAK,KAAK,MAAM,SAAS;AAEpC,MAAM,gBACJ,MACA,cACG;CACH,MAAM,iBAAiB,OAAO,QAAQ,SAAS,CAAC,CAAC,QAC9C,GAAG,WAAW,UAAU,KAAA,CAC3B;CACA,OAAO,eAAe,WAAW,IAC7B,OACC;EAAE,GAAG;EAAM,GAAG,OAAO,YAAY,cAAc;CAAE;AACxD;AAEA,MAAM,iBAAiB,UACrB,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAE9D,MAAM,kBAAkB,QAAuC;CAC7D,IAAI,CAAC,cAAc,GAAG,GAAG,OAAO;CAChC,MAAM,KAAK,IAAI;CACf,MAAM,SAAS,IAAI;CACnB,IAAI,OAAO,OAAO,YAAY,OAAO,WAAW,UAAU,OAAO;CACjE,MAAM,YAA2B;EAAE;EAAI;CAAO;CAC9C,IAAI,OAAO,IAAI,YAAY,UAAU,UAAU,UAAU,IAAI;CAC7D,IAAI,OAAO,IAAI,eAAe,UAAU,UAAU,aAAa,IAAI;CACnE,IAAI,OAAO,IAAI,cAAc,UAAU,UAAU,YAAY,IAAI;CACjE,IAAI,cAAc,IAAI,cAAc,GAClC,UAAU,iBAAiB,IAAI;CACjC,IAAI,cAAc,IAAI,QAAQ,GAAG,UAAU,WAAW,IAAI;CAO1D,OAAO,IAAI,kBAAkB,QAAQ,cAAc,IAAI,cAAc,IACjE,YACA,sBAAsB,WAAW,IAAI,cAAc;AACzD;AAEA,MAAM,2BACJ,KACA,WACuC;CACvC,IAAI,CAAC,cAAc,GAAG,GAAG,OAAO,KAAA;CAChC,IAAI,IAAI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S;EAC9D,KAAK,eACH,OAAO;GACL,MAAM;GACN,OAAO,MAAM,QAAQ,QAAQ,KAAK,IAAK,QAAQ,QAAkB,CAAC;EACpE;EACF,KAAK,qBACH,OAAO;GACL,MAAM;GACN,UAAU,MAAM,QAAQ,QAAQ,QAAQ,IACnC,QAAQ,WACT,CAAC;EACP;EACF,KAAK,qBAAqB;GACxB,MAAM,eAAe,UAAU,cAAc;GAC7C,IAAI,CAAC,gBAAgB,CAAC,cAAc,QAAQ,OAAO,GAAG,OAAO;GAC7D,OAAO,aACL;IACE,MAAM;IACN;IACA,SAAS,QAAQ;GACnB,GACA;IACE,WAAW,UAAU,WAAW;IAChC,SACE,OAAO,QAAQ,YAAY,YAAY,QAAQ,UAAU,KAAA;GAC7D,CACF;EACF;EACA,KAAK,OACH,OAAO,aACL;GAAE,MAAM;GAAgB,OAAO,QAAQ;EAAM,GAC7C,EAAE,QAAQ,UAAU,QAAQ,EAAE,CAChC;EACF,KAAK,UAAU;GACb,MAAM,OAAO,UAAU,MAAM;GAC7B,IAAI,CAAC,MAAM,OAAO;GAClB,OAAO;IAAE,MAAM;IAAU;IAAM,OAAO,QAAQ;GAAM;EACtD;EACA,SACE,OAAO,aACL;GAAE,MAAM;GAAgB,OAAO;EAAQ,GACvC,EACE,QAAQ,SAAS,QAAQ,IAAI,IAAK,QAAQ,OAAkB,KAAA,EAC9D,CACF;CACJ;AACF"}
@@ -0,0 +1,8 @@
1
+ import { AgUiInterrupt } from "./types.js";
2
+ //#region src/runtime/interrupt-internals.d.ts
3
+ declare const withRawResponseSchema: (interrupt: AgUiInterrupt, schema: unknown) => AgUiInterrupt;
4
+ declare const readRawResponseSchema: (interrupt: AgUiInterrupt) => unknown;
5
+ declare const withoutRawResponseSchema: <T extends AgUiInterrupt>(interrupt: T) => T;
6
+ //#endregion
7
+ export { readRawResponseSchema, withRawResponseSchema, withoutRawResponseSchema };
8
+ //# sourceMappingURL=interrupt-internals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interrupt-internals.d.ts","names":[],"sources":["../../src/runtime/interrupt-internals.ts"],"mappings":";;cAca,wBACX,WAAW,eACX,oBACC;cAQU,wBAAyB,WAAW;cAGpC,2BAA4B,UAAU,eACjD,WAAW,MACV"}
@@ -0,0 +1,25 @@
1
+ //#region src/runtime/interrupt-internals.ts
2
+ /**
3
+ * Where a received `responseSchema` travels when it is not an object. JSON
4
+ * Schema allows a boolean, and `false` rejects every payload, so a schema
5
+ * `responseSchema` cannot hold still has to be distinguishable from an absent
6
+ * one. The carrier is a string key rather than a symbol so it survives the
7
+ * persistence round trip, and it stays off `AgUiInterrupt` because only the
8
+ * gate check reads it.
9
+ */
10
+ const RAW_RESPONSE_SCHEMA = "__aui_agui_responseSchemaRaw";
11
+ const withRawResponseSchema = (interrupt, schema) => {
12
+ return {
13
+ ...interrupt,
14
+ [RAW_RESPONSE_SCHEMA]: schema
15
+ };
16
+ };
17
+ const readRawResponseSchema = (interrupt) => interrupt[RAW_RESPONSE_SCHEMA];
18
+ const withoutRawResponseSchema = (interrupt) => {
19
+ const { [RAW_RESPONSE_SCHEMA]: _raw, ...rest } = interrupt;
20
+ return rest;
21
+ };
22
+ //#endregion
23
+ export { readRawResponseSchema, withRawResponseSchema, withoutRawResponseSchema };
24
+
25
+ //# sourceMappingURL=interrupt-internals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interrupt-internals.js","names":[],"sources":["../../src/runtime/interrupt-internals.ts"],"sourcesContent":["import type { AgUiInterrupt } from \"./types\";\n\n/**\n * Where a received `responseSchema` travels when it is not an object. JSON\n * Schema allows a boolean, and `false` rejects every payload, so a schema\n * `responseSchema` cannot hold still has to be distinguishable from an absent\n * one. The carrier is a string key rather than a symbol so it survives the\n * persistence round trip, and it stays off `AgUiInterrupt` because only the\n * gate check reads it.\n */\nconst RAW_RESPONSE_SCHEMA = \"__aui_agui_responseSchemaRaw\";\n\ntype RawResponseSchemaCarrier = { [RAW_RESPONSE_SCHEMA]?: unknown };\n\nexport const withRawResponseSchema = (\n interrupt: AgUiInterrupt,\n schema: unknown,\n): AgUiInterrupt => {\n const carried: AgUiInterrupt & RawResponseSchemaCarrier = {\n ...interrupt,\n [RAW_RESPONSE_SCHEMA]: schema,\n };\n return carried;\n};\n\nexport const readRawResponseSchema = (interrupt: AgUiInterrupt): unknown =>\n (interrupt as RawResponseSchemaCarrier)[RAW_RESPONSE_SCHEMA];\n\nexport const withoutRawResponseSchema = <T extends AgUiInterrupt>(\n interrupt: T,\n): T => {\n const { [RAW_RESPONSE_SCHEMA]: _raw, ...rest } = interrupt as T &\n RawResponseSchemaCarrier;\n return rest as T;\n};\n"],"mappings":";;;;;;;;;AAUA,MAAM,sBAAsB;AAI5B,MAAa,yBACX,WACA,WACkB;CAKlB,OAAO;EAHL,GAAG;GACF,sBAAsB;CAEZ;AACf;AAEA,MAAa,yBAAyB,cACnC,UAAuC;AAE1C,MAAa,4BACX,cACM;CACN,MAAM,GAAG,sBAAsB,MAAM,GAAG,SAAS;CAEjD,OAAO;AACT"}
@@ -133,6 +133,9 @@ function useAgUiRuntime(options) {
133
133
  core.cancel();
134
134
  },
135
135
  onAddToolResult: (options) => core.addToolResult(options),
136
+ onRespondToToolApproval: (options) => core.respondToToolApproval(options).catch((error) => {
137
+ core.reportError(error);
138
+ }),
136
139
  onResume: (config) => core.resume(config),
137
140
  setMessages: (messages) => core.applyExternalMessages(messages),
138
141
  onImport: (messages) => core.applyExternalMessages(messages),
@@ -1 +1 @@
1
- {"version":3,"file":"useAgUiRuntime.js","names":[],"sources":["../src/useAgUiRuntime.ts"],"sourcesContent":["\"use client\";\n\nimport {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n useExternalStoreRuntime,\n useExternalStoreSharedOptions,\n useRuntimeAdapters,\n} from \"@assistant-ui/core/react\";\nimport { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n MessageQueueController,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport type {\n AssistantRuntime,\n AppendMessage,\n ExternalStoreAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { makeLogger } from \"./runtime/logger\";\nimport type {\n AgUiInterrupt,\n AgUiResumeEntry,\n UseAgUiRuntimeOptions,\n} from \"./runtime/types\";\nimport { AgUiThreadRuntimeCore } from \"./runtime/AgUiThreadRuntimeCore\";\nimport { agUiExtras } from \"./agUiExtras\";\nimport type { QueueItemState } from \"@assistant-ui/core/store\";\n\nconst EMPTY_INTERRUPTS: readonly AgUiInterrupt[] = [];\nconst EMPTY_QUEUE_ITEMS: readonly QueueItemState[] = Object.freeze([]);\nconst subscribeNoop = () => () => {};\n\nexport type AgUiAssistantRuntime = AssistantRuntime & {\n /**\n * @deprecated Use the `useAgUiInterrupts()` hook instead. This method is kept\n * for backward compatibility and will be removed in a future major release.\n */\n unstable_getPendingInterrupts: () => readonly AgUiInterrupt[];\n /**\n * @deprecated Use the `useAgUiSubmitInterruptResponses()` hook instead. This\n * method is kept for backward compatibility and will be removed in a future\n * major release.\n */\n unstable_submitInterruptResponses: (\n responses: readonly AgUiResumeEntry[],\n ) => Promise<void>;\n};\n\nexport function useAgUiRuntime(\n options: UseAgUiRuntimeOptions,\n): AgUiAssistantRuntime {\n const logger = useMemo(() => makeLogger(options.logger), [options.logger]);\n const [_version, setVersion] = useState(0);\n const notifyUpdate = useCallback(() => setVersion((v) => v + 1), []);\n const coreRef = useRef<AgUiThreadRuntimeCore | null>(null);\n const runtimeAdapters = useRuntimeAdapters();\n\n const historyAdapter = options.adapters?.history ?? runtimeAdapters?.history;\n const threadListAdapter = options.adapters?.threadList;\n\n if (!coreRef.current) {\n coreRef.current = new AgUiThreadRuntimeCore({\n agent: options.agent,\n logger,\n showThinking: options.showThinking ?? true,\n autoCancelPendingToolCalls: options.autoCancelPendingToolCalls,\n ...(options.onError && { onError: options.onError }),\n ...(options.onCancel && { onCancel: options.onCancel }),\n ...(historyAdapter && { history: historyAdapter }),\n notifyUpdate,\n });\n }\n\n const core = coreRef.current;\n core.updateOptions({\n agent: options.agent,\n logger,\n showThinking: options.showThinking ?? true,\n autoCancelPendingToolCalls: options.autoCancelPendingToolCalls,\n ...(options.onError && { onError: options.onError }),\n ...(options.onCancel && { onCancel: options.onCancel }),\n ...(historyAdapter && { history: historyAdapter }),\n });\n\n const [toolStatuses, setToolStatuses] = useState<\n Record<string, ToolExecutionStatus>\n >({});\n\n const hasExecutingTools = Object.values(toolStatuses).some(\n (s) => s?.type === \"executing\",\n );\n const isRunning = core.isRunning() || hasExecutingTools;\n\n // The driver sends through the agent core rather than the runtime, because\n // the runtime's append routes every tail append back into this queue.\n const queueRef = useRef<MessageQueueController | null>(null);\n // Counts rendered busy edges, whether a run start or an interrupt arriving.\n // A dispatch whose count never moves was never observed as busy, so no\n // falling edge is coming to release the queue.\n const busyEdgesRef = useRef(0);\n if (options.unstable_enableMessageQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message) => {\n const controller = queueRef.current;\n const edgesAtDispatch = busyEdgesRef.current;\n // The queue drops the item before dispatching and stays busy until an\n // idle edge. An append observed as busy is released by that falling\n // edge, and releasing again here would advance the queue twice; one\n // that never runs (a pre-run rejection, or startRun false) has to be\n // released here or every later send buffers forever. An interrupt is\n // rechecked because a run that resolves without yielding to React\n // reaches here before the effect below has seen either edge.\n const releaseIfNoRun = () => {\n if (\n queueRef.current !== controller ||\n busyEdgesRef.current !== edgesAtDispatch ||\n core.getPendingInterrupts() !== null\n )\n return;\n controller?.notifyIdle();\n };\n void core.append(message).then(releaseIfNoRun, (e: unknown) => {\n releaseIfNoRun();\n logger.error?.(\"[agui] queued message failed to send\", e);\n });\n },\n });\n } else if (!options.unstable_enableMessageQueue && queueRef.current) {\n queueRef.current.clear();\n queueRef.current = null;\n }\n const queueController = options.unstable_enableMessageQueue\n ? queueRef.current\n : null;\n\n // Feeds the store memo below: the runtime core skips an adapter whose\n // identity is unchanged, so queue items have to move the store reference or\n // subscribers never see composer.queue change.\n const queueItems = useSyncExternalStore(\n queueController?.subscribe ?? subscribeNoop,\n () => queueController?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n const steerQueueItems = useSyncExternalStore(\n queueController?.subscribe ?? subscribeNoop,\n () => queueController?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // Holds the queue while client-side tools are still executing, and while an\n // interrupt is unanswered: `append` refuses a new run until it is resolved,\n // and the queue drops an item before dispatching it, so draining into that\n // refusal would lose the message instead of keeping it visible.\n const queueBusy = isRunning || core.getPendingInterrupts() !== null;\n useEffect(() => {\n if (queueBusy) {\n busyEdgesRef.current++;\n queueController?.notifyBusy();\n } else {\n queueController?.notifyIdle();\n }\n }, [queueBusy, queueController]);\n\n const threadList = useMemo(() => {\n if (!threadListAdapter) return undefined;\n\n const { onSwitchToNewThread, onSwitchToThread, ...rest } =\n threadListAdapter;\n\n return {\n ...rest,\n onSwitchToNewThread: onSwitchToNewThread\n ? async () => {\n await onSwitchToNewThread();\n core.applyExternalMessages([]);\n core.resetState();\n }\n : undefined,\n onSwitchToThread: onSwitchToThread\n ? async (threadId: string) => {\n // Clear before the thread id flips, or the old messages leak\n // into the new thread as a sibling branch.\n core.applyExternalMessages([]);\n const result = await onSwitchToThread(threadId);\n core.applyExternalMessages(result.messages);\n if (result.state !== undefined) {\n core.loadExternalState(result.state);\n } else {\n core.resetState();\n }\n if (result.unstable_resume) {\n void core.resumeInFlightRun(result.messages);\n }\n }\n : undefined,\n };\n }, [threadListAdapter, core]);\n\n const adapters = options.adapters;\n const adapterAdapters = useMemo(\n () => ({\n attachments: adapters?.attachments ?? runtimeAdapters?.attachments,\n speech: adapters?.speech,\n dictation: adapters?.dictation,\n voice: adapters?.voice,\n feedback: adapters?.feedback,\n threadList,\n }),\n [adapters, runtimeAdapters, threadList],\n );\n\n const shared = useExternalStoreSharedOptions(options);\n const store = useMemo(\n () => {\n void _version; // rerender on version change\n\n return {\n ...shared,\n isLoading: core.isLoading,\n messageRepository: core.getMessageRepository(),\n state: core.getState(),\n isRunning,\n extras: agUiExtras.provide({\n interrupts:\n core.getPendingInterrupts()?.interrupts ?? EMPTY_INTERRUPTS,\n sendA2uiAction: (action) => core.sendA2uiAction(action),\n submitInterruptResponses: (responses) =>\n core.submitInterruptResponses(responses),\n steerAway: (message, responses) => core.steerAway(message, responses),\n state: core.getState(),\n setState: (next) => core.setState(next),\n }),\n unstable_enableToolInvocations: true,\n setToolStatuses,\n onNew: (message: AppendMessage) => core.append(message),\n onEdit: (message: AppendMessage) => {\n queueController?.clear();\n return core.edit(message);\n },\n onReload: (parentId: string | null, config: { runConfig?: any }) => {\n queueController?.clear();\n return core.reload(parentId, config);\n },\n onCancel: async () => {\n queueController?.notifyCancelled();\n core.cancel();\n },\n onAddToolResult: (options) => core.addToolResult(options),\n onResume: (config) => core.resume(config),\n setMessages: (messages: readonly ThreadMessage[]) =>\n core.applyExternalMessages(messages),\n onImport: (messages: readonly ThreadMessage[]) =>\n core.applyExternalMessages(messages),\n onLoadExternalState: (state: ReadonlyJSONValue) =>\n core.loadExternalState(state),\n adapters: adapterAdapters,\n ...(queueController && { queue: queueController.adapter }),\n } satisfies ExternalStoreAdapter<ThreadMessage>;\n },\n // _version is intentionally included to trigger re-computation when core state changes via notifyUpdate\n // toolInvocations intentionally excluded: abort/resume use refs internally and work with stale captures\n [\n adapterAdapters,\n core,\n _version,\n isRunning,\n queueController,\n queueItems,\n steerQueueItems,\n shared,\n ],\n );\n\n const baseRuntime = useExternalStoreRuntime(store);\n\n const runtime = useMemo<AgUiAssistantRuntime>(() => {\n const wrapper = Object.create(baseRuntime) as AgUiAssistantRuntime;\n wrapper.unstable_getPendingInterrupts = () =>\n core.getPendingInterrupts()?.interrupts ?? [];\n wrapper.unstable_submitInterruptResponses = (responses) =>\n core.submitInterruptResponses(responses);\n return wrapper;\n }, [baseRuntime, core]);\n\n useEffect(() => {\n core.attachRuntime(runtime);\n return () => {\n core.detachRuntime();\n };\n }, [core, runtime]);\n\n useEffect(() => {\n core.__internal_load();\n }, [core]);\n\n return runtime;\n}\n"],"mappings":";;;;;;;;AAqCA,MAAM,mBAA6C,CAAC;AACpD,MAAM,oBAA+C,OAAO,OAAO,CAAC,CAAC;AACrE,MAAM,4BAA4B,CAAC;AAkBnC,SAAgB,eACd,SACsB;CACtB,MAAM,SAAS,cAAc,WAAW,QAAQ,MAAM,GAAG,CAAC,QAAQ,MAAM,CAAC;CACzE,MAAM,CAAC,UAAU,cAAc,SAAS,CAAC;CACzC,MAAM,eAAe,kBAAkB,YAAY,MAAM,IAAI,CAAC,GAAG,CAAC,CAAC;CACnE,MAAM,UAAU,OAAqC,IAAI;CACzD,MAAM,kBAAkB,mBAAmB;CAE3C,MAAM,iBAAiB,QAAQ,UAAU,WAAW,iBAAiB;CACrE,MAAM,oBAAoB,QAAQ,UAAU;CAE5C,IAAI,CAAC,QAAQ,SACX,QAAQ,UAAU,IAAI,sBAAsB;EAC1C,OAAO,QAAQ;EACf;EACA,cAAc,QAAQ,gBAAgB;EACtC,4BAA4B,QAAQ;EACpC,GAAI,QAAQ,WAAW,EAAE,SAAS,QAAQ,QAAQ;EAClD,GAAI,QAAQ,YAAY,EAAE,UAAU,QAAQ,SAAS;EACrD,GAAI,kBAAkB,EAAE,SAAS,eAAe;EAChD;CACF,CAAC;CAGH,MAAM,OAAO,QAAQ;CACrB,KAAK,cAAc;EACjB,OAAO,QAAQ;EACf;EACA,cAAc,QAAQ,gBAAgB;EACtC,4BAA4B,QAAQ;EACpC,GAAI,QAAQ,WAAW,EAAE,SAAS,QAAQ,QAAQ;EAClD,GAAI,QAAQ,YAAY,EAAE,UAAU,QAAQ,SAAS;EACrD,GAAI,kBAAkB,EAAE,SAAS,eAAe;CAClD,CAAC;CAED,MAAM,CAAC,cAAc,mBAAmB,SAEtC,CAAC,CAAC;CAEJ,M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,MAAM;GACrC;GACA,UAAU,YAAY;IACpB,iBAAiB,gBAAgB;IACjC,KAAK,OAAO;GACd;GACA,kBAAkB,YAAY,KAAK,cAAc,OAAO;GACxD,WAAW,WAAW,KAAK,OAAO,MAAM;GACxC,cAAc,aACZ,KAAK,sBAAsB,QAAQ;GACrC,WAAW,aACT,KAAK,sBAAsB,QAAQ;GACrC,sBAAsB,UACpB,KAAK,kBAAkB,KAAK;GAC9B,UAAU;GACV,GAAI,mBAAmB,EAAE,OAAO,gBAAgB,QAAQ;EAC1D;CACF,GAGA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,MAAM,cAAc,wBAAwB,KAAK;CAEjD,MAAM,UAAU,cAAoC;EAClD,MAAM,UAAU,OAAO,OAAO,WAAW;EACzC,QAAQ,sCACN,KAAK,qBAAqB,CAAC,EAAE,cAAc,CAAC;EAC9C,QAAQ,qCAAqC,cAC3C,KAAK,yBAAyB,SAAS;EACzC,OAAO;CACT,GAAG,CAAC,aAAa,IAAI,CAAC;CAEtB,gBAAgB;EACd,KAAK,cAAc,OAAO;EAC1B,aAAa;GACX,KAAK,cAAc;EACrB;CACF,GAAG,CAAC,MAAM,OAAO,CAAC;CAElB,gBAAgB;EACd,KAAK,gBAAgB;CACvB,GAAG,CAAC,IAAI,CAAC;CAET,OAAO;AACT"}
1
+ {"version":3,"file":"useAgUiRuntime.js","names":[],"sources":["../src/useAgUiRuntime.ts"],"sourcesContent":["\"use client\";\n\nimport {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n useExternalStoreRuntime,\n useExternalStoreSharedOptions,\n useRuntimeAdapters,\n} from \"@assistant-ui/core/react\";\nimport { createMessageQueue } from \"@assistant-ui/core\";\nimport type {\n MessageQueueController,\n ToolExecutionStatus,\n} from \"@assistant-ui/core\";\nimport type {\n AssistantRuntime,\n AppendMessage,\n ExternalStoreAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { makeLogger } from \"./runtime/logger\";\nimport type {\n AgUiInterrupt,\n AgUiResumeEntry,\n UseAgUiRuntimeOptions,\n} from \"./runtime/types\";\nimport { AgUiThreadRuntimeCore } from \"./runtime/AgUiThreadRuntimeCore\";\nimport { agUiExtras } from \"./agUiExtras\";\nimport type { QueueItemState } from \"@assistant-ui/core/store\";\n\nconst EMPTY_INTERRUPTS: readonly AgUiInterrupt[] = [];\nconst EMPTY_QUEUE_ITEMS: readonly QueueItemState[] = Object.freeze([]);\nconst subscribeNoop = () => () => {};\n\nexport type AgUiAssistantRuntime = AssistantRuntime & {\n /**\n * @deprecated Use the `useAgUiInterrupts()` hook instead. This method is kept\n * for backward compatibility and will be removed in a future major release.\n */\n unstable_getPendingInterrupts: () => readonly AgUiInterrupt[];\n /**\n * @deprecated Use the `useAgUiSubmitInterruptResponses()` hook instead. This\n * method is kept for backward compatibility and will be removed in a future\n * major release.\n */\n unstable_submitInterruptResponses: (\n responses: readonly AgUiResumeEntry[],\n ) => Promise<void>;\n};\n\nexport function useAgUiRuntime(\n options: UseAgUiRuntimeOptions,\n): AgUiAssistantRuntime {\n const logger = useMemo(() => makeLogger(options.logger), [options.logger]);\n const [_version, setVersion] = useState(0);\n const notifyUpdate = useCallback(() => setVersion((v) => v + 1), []);\n const coreRef = useRef<AgUiThreadRuntimeCore | null>(null);\n const runtimeAdapters = useRuntimeAdapters();\n\n const historyAdapter = options.adapters?.history ?? runtimeAdapters?.history;\n const threadListAdapter = options.adapters?.threadList;\n\n if (!coreRef.current) {\n coreRef.current = new AgUiThreadRuntimeCore({\n agent: options.agent,\n logger,\n showThinking: options.showThinking ?? true,\n autoCancelPendingToolCalls: options.autoCancelPendingToolCalls,\n ...(options.onError && { onError: options.onError }),\n ...(options.onCancel && { onCancel: options.onCancel }),\n ...(historyAdapter && { history: historyAdapter }),\n notifyUpdate,\n });\n }\n\n const core = coreRef.current;\n core.updateOptions({\n agent: options.agent,\n logger,\n showThinking: options.showThinking ?? true,\n autoCancelPendingToolCalls: options.autoCancelPendingToolCalls,\n ...(options.onError && { onError: options.onError }),\n ...(options.onCancel && { onCancel: options.onCancel }),\n ...(historyAdapter && { history: historyAdapter }),\n });\n\n const [toolStatuses, setToolStatuses] = useState<\n Record<string, ToolExecutionStatus>\n >({});\n\n const hasExecutingTools = Object.values(toolStatuses).some(\n (s) => s?.type === \"executing\",\n );\n const isRunning = core.isRunning() || hasExecutingTools;\n\n // The driver sends through the agent core rather than the runtime, because\n // the runtime's append routes every tail append back into this queue.\n const queueRef = useRef<MessageQueueController | null>(null);\n // Counts rendered busy edges, whether a run start or an interrupt arriving.\n // A dispatch whose count never moves was never observed as busy, so no\n // falling edge is coming to release the queue.\n const busyEdgesRef = useRef(0);\n if (options.unstable_enableMessageQueue && !queueRef.current) {\n queueRef.current = createMessageQueue({\n run: (message) => {\n const controller = queueRef.current;\n const edgesAtDispatch = busyEdgesRef.current;\n // The queue drops the item before dispatching and stays busy until an\n // idle edge. An append observed as busy is released by that falling\n // edge, and releasing again here would advance the queue twice; one\n // that never runs (a pre-run rejection, or startRun false) has to be\n // released here or every later send buffers forever. An interrupt is\n // rechecked because a run that resolves without yielding to React\n // reaches here before the effect below has seen either edge.\n const releaseIfNoRun = () => {\n if (\n queueRef.current !== controller ||\n busyEdgesRef.current !== edgesAtDispatch ||\n core.getPendingInterrupts() !== null\n )\n return;\n controller?.notifyIdle();\n };\n void core.append(message).then(releaseIfNoRun, (e: unknown) => {\n releaseIfNoRun();\n logger.error?.(\"[agui] queued message failed to send\", e);\n });\n },\n });\n } else if (!options.unstable_enableMessageQueue && queueRef.current) {\n queueRef.current.clear();\n queueRef.current = null;\n }\n const queueController = options.unstable_enableMessageQueue\n ? queueRef.current\n : null;\n\n // Feeds the store memo below: the runtime core skips an adapter whose\n // identity is unchanged, so queue items have to move the store reference or\n // subscribers never see composer.queue change.\n const queueItems = useSyncExternalStore(\n queueController?.subscribe ?? subscribeNoop,\n () => queueController?.adapter.items ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n const steerQueueItems = useSyncExternalStore(\n queueController?.subscribe ?? subscribeNoop,\n () => queueController?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS,\n () => EMPTY_QUEUE_ITEMS,\n );\n\n // Holds the queue while client-side tools are still executing, and while an\n // interrupt is unanswered: `append` refuses a new run until it is resolved,\n // and the queue drops an item before dispatching it, so draining into that\n // refusal would lose the message instead of keeping it visible.\n const queueBusy = isRunning || core.getPendingInterrupts() !== null;\n useEffect(() => {\n if (queueBusy) {\n busyEdgesRef.current++;\n queueController?.notifyBusy();\n } else {\n queueController?.notifyIdle();\n }\n }, [queueBusy, queueController]);\n\n const threadList = useMemo(() => {\n if (!threadListAdapter) return undefined;\n\n const { onSwitchToNewThread, onSwitchToThread, ...rest } =\n threadListAdapter;\n\n return {\n ...rest,\n onSwitchToNewThread: onSwitchToNewThread\n ? async () => {\n await onSwitchToNewThread();\n core.applyExternalMessages([]);\n core.resetState();\n }\n : undefined,\n onSwitchToThread: onSwitchToThread\n ? async (threadId: string) => {\n // Clear before the thread id flips, or the old messages leak\n // into the new thread as a sibling branch.\n core.applyExternalMessages([]);\n const result = await onSwitchToThread(threadId);\n core.applyExternalMessages(result.messages);\n if (result.state !== undefined) {\n core.loadExternalState(result.state);\n } else {\n core.resetState();\n }\n if (result.unstable_resume) {\n void core.resumeInFlightRun(result.messages);\n }\n }\n : undefined,\n };\n }, [threadListAdapter, core]);\n\n const adapters = options.adapters;\n const adapterAdapters = useMemo(\n () => ({\n attachments: adapters?.attachments ?? runtimeAdapters?.attachments,\n speech: adapters?.speech,\n dictation: adapters?.dictation,\n voice: adapters?.voice,\n feedback: adapters?.feedback,\n threadList,\n }),\n [adapters, runtimeAdapters, threadList],\n );\n\n const shared = useExternalStoreSharedOptions(options);\n const store = useMemo(\n () => {\n void _version; // rerender on version change\n\n return {\n ...shared,\n isLoading: core.isLoading,\n messageRepository: core.getMessageRepository(),\n state: core.getState(),\n isRunning,\n extras: agUiExtras.provide({\n interrupts:\n core.getPendingInterrupts()?.interrupts ?? EMPTY_INTERRUPTS,\n sendA2uiAction: (action) => core.sendA2uiAction(action),\n submitInterruptResponses: (responses) =>\n core.submitInterruptResponses(responses),\n steerAway: (message, responses) => core.steerAway(message, responses),\n state: core.getState(),\n setState: (next) => core.setState(next),\n }),\n unstable_enableToolInvocations: true,\n setToolStatuses,\n onNew: (message: AppendMessage) => core.append(message),\n onEdit: (message: AppendMessage) => {\n queueController?.clear();\n return core.edit(message);\n },\n onReload: (parentId: string | null, config: { runConfig?: any }) => {\n queueController?.clear();\n return core.reload(parentId, config);\n },\n onCancel: async () => {\n queueController?.notifyCancelled();\n core.cancel();\n },\n onAddToolResult: (options) => core.addToolResult(options),\n onRespondToToolApproval: (options) =>\n core.respondToToolApproval(options).catch((error: unknown) => {\n core.reportError(error);\n }),\n onResume: (config) => core.resume(config),\n setMessages: (messages: readonly ThreadMessage[]) =>\n core.applyExternalMessages(messages),\n onImport: (messages: readonly ThreadMessage[]) =>\n core.applyExternalMessages(messages),\n onLoadExternalState: (state: ReadonlyJSONValue) =>\n core.loadExternalState(state),\n adapters: adapterAdapters,\n ...(queueController && { queue: queueController.adapter }),\n } satisfies ExternalStoreAdapter<ThreadMessage>;\n },\n // _version is intentionally included to trigger re-computation when core state changes via notifyUpdate\n // toolInvocations intentionally excluded: abort/resume use refs internally and work with stale captures\n [\n adapterAdapters,\n core,\n _version,\n isRunning,\n queueController,\n queueItems,\n steerQueueItems,\n shared,\n ],\n );\n\n const baseRuntime = useExternalStoreRuntime(store);\n\n const runtime = useMemo<AgUiAssistantRuntime>(() => {\n const wrapper = Object.create(baseRuntime) as AgUiAssistantRuntime;\n wrapper.unstable_getPendingInterrupts = () =>\n core.getPendingInterrupts()?.interrupts ?? [];\n wrapper.unstable_submitInterruptResponses = (responses) =>\n core.submitInterruptResponses(responses);\n return wrapper;\n }, [baseRuntime, core]);\n\n useEffect(() => {\n core.attachRuntime(runtime);\n return () => {\n core.detachRuntime();\n };\n }, [core, runtime]);\n\n useEffect(() => {\n core.__internal_load();\n }, [core]);\n\n return runtime;\n}\n"],"mappings":";;;;;;;;AAqCA,MAAM,mBAA6C,CAAC;AACpD,MAAM,oBAA+C,OAAO,OAAO,CAAC,CAAC;AACrE,MAAM,4BAA4B,CAAC;AAkBnC,SAAgB,eACd,SACsB;CACtB,MAAM,SAAS,cAAc,WAAW,QAAQ,MAAM,GAAG,CAAC,QAAQ,MAAM,CAAC;CACzE,MAAM,CAAC,UAAU,cAAc,SAAS,CAAC;CACzC,MAAM,eAAe,kBAAkB,YAAY,MAAM,IAAI,CAAC,GAAG,CAAC,CAAC;CACnE,MAAM,UAAU,OAAqC,IAAI;CACzD,MAAM,kBAAkB,mBAAmB;CAE3C,MAAM,iBAAiB,QAAQ,UAAU,WAAW,iBAAiB;CACrE,MAAM,oBAAoB,QAAQ,UAAU;CAE5C,IAAI,CAAC,QAAQ,SACX,QAAQ,UAAU,IAAI,sBAAsB;EAC1C,OAAO,QAAQ;EACf;EACA,cAAc,QAAQ,gBAAgB;EACtC,4BAA4B,QAAQ;EACpC,GAAI,QAAQ,WAAW,EAAE,SAAS,QAAQ,QAAQ;EAClD,GAAI,QAAQ,YAAY,EAAE,UAAU,QAAQ,SAAS;EACrD,GAAI,kBAAkB,EAAE,SAAS,eAAe;EAChD;CACF,CAAC;CAGH,MAAM,OAAO,QAAQ;CACrB,KAAK,cAAc;EACjB,OAAO,QAAQ;EACf;EACA,cAAc,QAAQ,gBAAgB;EACtC,4BAA4B,QAAQ;EACpC,GAAI,QAAQ,WAAW,EAAE,SAAS,QAAQ,QAAQ;EAClD,GAAI,QAAQ,YAAY,EAAE,UAAU,QAAQ,SAAS;EACrD,GAAI,kBAAkB,EAAE,SAAS,eAAe;CAClD,CAAC;CAED,MAAM,CAAC,cAAc,mBAAmB,SAEtC,CAAC,CAAC;CAEJ,MAAM,oBAAoB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;GACA,UAAU,YAAY;IACpB,iBAAiB,gBAAgB;IACjC,KAAK,OAAO;GACd;GACA,kBAAkB,YAAY,KAAK,cAAc,OAAO;GACxD,0BAA0B,YACxB,KAAK,sBAAsB,OAAO,CAAC,CAAC,OAAO,UAAmB;IAC5D,KAAK,YAAY,KAAK;GACxB,CAAC;GACH,WAAW,WAAW,KAAK,OAAO,MAAM;GACxC,cAAc,aACZ,KAAK,sBAAsB,QAAQ;GACrC,WAAW,aACT,KAAK,sBAAsB,QAAQ;GACrC,sBAAsB,UACpB,KAAK,kBAAkB,KAAK;GAC9B,UAAU;GACV,GAAI,mBAAmB,EAAE,OAAO,gBAAgB,QAAQ;EAC1D;CACF,GAGA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,MAAM,cAAc,wBAAwB,KAAK;CAEjD,MAAM,UAAU,cAAoC;EAClD,MAAM,UAAU,OAAO,OAAO,WAAW;EACzC,QAAQ,sCACN,KAAK,qBAAqB,CAAC,EAAE,cAAc,CAAC;EAC9C,QAAQ,qCAAqC,cAC3C,KAAK,yBAAyB,SAAS;EACzC,OAAO;CACT,GAAG,CAAC,aAAa,IAAI,CAAC;CAEtB,gBAAgB;EACd,KAAK,cAAc,OAAO;EAC1B,aAAa;GACX,KAAK,cAAc;EACrB;CACF,GAAG,CAAC,MAAM,OAAO,CAAC;CAElB,gBAAgB;EACd,KAAK,gBAAgB;CACvB,GAAG,CAAC,IAAI,CAAC;CAET,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-ag-ui",
3
- "version": "0.0.54",
3
+ "version": "0.0.56",
4
4
  "description": "AG-UI protocol adapter for assistant-ui",
5
5
  "keywords": [
6
6
  "ag-ui",
@@ -29,11 +29,11 @@
29
29
  ],
30
30
  "sideEffects": false,
31
31
  "dependencies": {
32
- "@ag-ui/client": "^0.0.57",
33
- "@assistant-ui/core": "^0.3.13",
34
- "@assistant-ui/react-generative-ui": "^0.0.14",
35
- "@assistant-ui/store": "^0.3.9",
36
- "assistant-stream": "^0.3.36",
32
+ "@ag-ui/client": "^0.0.58",
33
+ "@assistant-ui/core": "^0.3.15",
34
+ "@assistant-ui/react-generative-ui": "^0.0.15",
35
+ "@assistant-ui/store": "^0.3.10",
36
+ "assistant-stream": "^0.3.39",
37
37
  "fast-json-patch": "^3.1.1"
38
38
  },
39
39
  "peerDependencies": {
@@ -53,7 +53,7 @@
53
53
  "react": "^19.2.8",
54
54
  "vitest": "^4.1.10",
55
55
  "zod": "^4.4.3",
56
- "@assistant-ui/x-buildutils": "0.0.22"
56
+ "@assistant-ui/x-buildutils": "0.0.23"
57
57
  },
58
58
  "publishConfig": {
59
59
  "access": "public",
package/src/index.ts CHANGED
@@ -8,8 +8,14 @@ export {
8
8
  useAgUiState,
9
9
  useAgUiSetState,
10
10
  } from "./hooks";
11
- export { fromAgUiMessages } from "./runtime/adapter/conversions";
12
- export type { FromAgUiMessagesOptions } from "./runtime/adapter/conversions";
11
+ export {
12
+ fromAgUiMessages,
13
+ toAgUiMessages,
14
+ } from "./runtime/adapter/conversions";
15
+ export type {
16
+ AgUiMessage,
17
+ FromAgUiMessagesOptions,
18
+ } from "./runtime/adapter/conversions";
13
19
  export type {
14
20
  AgUiInterrupt,
15
21
  AgUiInterruptReason,