assistant-stream 0.3.17 → 0.3.18
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/core/accumulators/AssistantMessageStream.d.ts.map +1 -1
- package/dist/core/accumulators/TimingTracker.d.ts.map +1 -1
- package/dist/core/modules/assistant-stream.d.ts.map +1 -1
- package/dist/core/object/ObjectStreamAccumulator.d.ts.map +1 -1
- package/dist/core/object/ObjectStreamResponse.js.map +1 -1
- package/dist/core/serialization/data-stream/DataStream.js.map +1 -1
- package/dist/core/serialization/ui-message-stream/UIMessageStream.js.map +1 -1
- package/dist/core/tool/ToolCallReader.d.ts +1 -1
- package/dist/core/tool/ToolCallReader.d.ts.map +1 -1
- package/dist/core/tool/ToolCallReader.js.map +1 -1
- package/dist/core/tool/ToolResponse.d.ts.map +1 -1
- package/dist/core/tool/ToolResponse.js.map +1 -1
- package/dist/core/tool/schema-utils.d.ts +7 -1
- package/dist/core/tool/schema-utils.d.ts.map +1 -1
- package/dist/core/tool/schema-utils.js +8 -2
- package/dist/core/tool/schema-utils.js.map +1 -1
- package/dist/core/tool/tool-types.d.ts +68 -3
- package/dist/core/tool/tool-types.d.ts.map +1 -1
- package/dist/core/utils/Counter.d.ts.map +1 -1
- package/dist/core/utils/withPromiseOrValue.d.ts.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/node_modules/.pnpm/@types_json-schema@7.0.15/node_modules/@types/json-schema/index.d.ts.map +1 -1
- package/dist/utils/AsyncIterableStream.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/core/object/ObjectStreamResponse.ts +4 -4
- package/src/core/serialization/data-stream/DataStream.ts +0 -1
- package/src/core/serialization/ui-message-stream/UIMessageStream.ts +0 -1
- package/src/core/tool/ToolCallReader.ts +8 -9
- package/src/core/tool/ToolResponse.ts +1 -0
- package/src/core/tool/schema-utils.test.ts +56 -0
- package/src/core/tool/schema-utils.ts +11 -1
- package/src/core/tool/tool-types.ts +89 -1
- package/src/index.ts +2 -1
- package/src/resumable/index.ts +1 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantMessageStream.d.ts","names":[],"sources":["../../../src/core/accumulators/AssistantMessageStream.ts"],"mappings":";;;;cAIa,sBAAA;EAAA,SACiB,QAAA,EAAU,cAAA,CAAe,gBAAA;cAAzB,QAAA,EAAU,cAAA,CAAe,gBAAA;EAAA,OAI9C,mBAAA,CAAoB,MAAA,EAAQ,eAAA,GAAe,sBAAA;EAM5C,eAAA,
|
|
1
|
+
{"version":3,"file":"AssistantMessageStream.d.ts","names":[],"sources":["../../../src/core/accumulators/AssistantMessageStream.ts"],"mappings":";;;;cAIa,sBAAA;EAAA,SACiB,QAAA,EAAU,cAAA,CAAe,gBAAA;cAAzB,QAAA,EAAU,cAAA,CAAe,gBAAA;EAAA,OAI9C,mBAAA,CAAoB,MAAA,EAAQ,eAAA,GAAe,sBAAA;EAM5C,eAAA,IAAmB,OAAA,CAAQ,gBAAA;EAAA,CAwBhC,MAAA,CAAO,aAAA;YAGU,OAAA,CAAQ,cAAA,CAAe,gBAAA;EAAA;EAOzC,GAAA,KAAQ,sBAAA,EAAwB,sBAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TimingTracker.d.ts","names":[],"sources":["../../../src/core/accumulators/TimingTracker.ts"],"mappings":";;;cAEa,aAAA;EAAA,QACH,gBAAA;EAAA,QACA,eAAA;EAAA,QACA,YAAA;EAAA,QACA,YAAA;;EAMR,WAAA
|
|
1
|
+
{"version":3,"file":"TimingTracker.d.ts","names":[],"sources":["../../../src/core/accumulators/TimingTracker.ts"],"mappings":";;;cAEa,aAAA;EAAA,QACH,gBAAA;EAAA,QACA,eAAA;EAAA,QACA,YAAA;EAAA,QACA,YAAA;;EAMR,WAAA;EAIA,gBAAA;EAMA,mBAAA,CAAoB,UAAA;EAIpB,SAAA,CAAU,YAAA,WAAuB,SAAA,YAAqB,sBAAsB;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assistant-stream.d.ts","names":[],"sources":["../../../src/core/modules/assistant-stream.ts"],"mappings":";;;;;;;;;KAuBK,gBAAA;EACH,UAAA;EACA,QAAA;EACA,QAAA;EACA,IAAA,GAAO,kBAAA;EACP,QAAA,GAAW,gBAAA,CAAiB,iBAAA;AAAA;;;;;;;;KAUlB,yBAAA;EAVV,oEAYA,UAAA,CAAW,SAAA,iBAZiB;EAc5B,eAAA,CAAgB,cAAA,iBAd6B;EAgB7C,YAAA,CAAa,OAAA,EAAS,UAAA,SANa;EAQnC,UAAA,CAAW,OAAA,EAAS,QAAA,SAFE;EAItB,UAAA,CAAW,OAAA,EAAS,QAAA;EAAA;;;;;;;EAQpB,WAAA,IAAe,oBAAA;EAgC0C;;;;;;EAzBzD,eAAA,CAAgB,OAAA,WAAkB,wBAAA;EAnBZ;;;;;;EA0BtB,eAAA,CAAgB,OAAA,EAAS,gBAAA,GAAmB,wBAAA,EAtBjC;EAwBX,OAAA,CAAQ,KAAA,EAAO,oBAAA;EAhBA;;;;;;EAuBf,KAAA,CAAM,MAAA,EAAQ,eAAA,SAT8B;EAW5C,KAAA;EATe;;;;;;EAgBf,YAAA,CAAa,QAAA,WAAmB,yBAAA;AAAA;;;AAAyB;AA2M3D;;;;;;iBAAgB,qBAAA,CACd,QAAA,GAAW,UAAA,EAAY,yBAAA,KAA8B,WAAA,gBACpD,eAAA;;;;;;;;iBAiCa,+BAAA,
|
|
1
|
+
{"version":3,"file":"assistant-stream.d.ts","names":[],"sources":["../../../src/core/modules/assistant-stream.ts"],"mappings":";;;;;;;;;KAuBK,gBAAA;EACH,UAAA;EACA,QAAA;EACA,QAAA;EACA,IAAA,GAAO,kBAAA;EACP,QAAA,GAAW,gBAAA,CAAiB,iBAAA;AAAA;;;;;;;;KAUlB,yBAAA;EAVV,oEAYA,UAAA,CAAW,SAAA,iBAZiB;EAc5B,eAAA,CAAgB,cAAA,iBAd6B;EAgB7C,YAAA,CAAa,OAAA,EAAS,UAAA,SANa;EAQnC,UAAA,CAAW,OAAA,EAAS,QAAA,SAFE;EAItB,UAAA,CAAW,OAAA,EAAS,QAAA;EAAA;;;;;;;EAQpB,WAAA,IAAe,oBAAA;EAgC0C;;;;;;EAzBzD,eAAA,CAAgB,OAAA,WAAkB,wBAAA;EAnBZ;;;;;;EA0BtB,eAAA,CAAgB,OAAA,EAAS,gBAAA,GAAmB,wBAAA,EAtBjC;EAwBX,OAAA,CAAQ,KAAA,EAAO,oBAAA;EAhBA;;;;;;EAuBf,KAAA,CAAM,MAAA,EAAQ,eAAA,SAT8B;EAW5C,KAAA;EATe;;;;;;EAgBf,YAAA,CAAa,QAAA,WAAmB,yBAAA;AAAA;;;AAAyB;AA2M3D;;;;;;iBAAgB,qBAAA,CACd,QAAA,GAAW,UAAA,EAAY,yBAAA,KAA8B,WAAA,gBACpD,eAAA;;;;;;;;iBAiCa,+BAAA,cAA+B,eAAA,EAAA,yBAAA;AAA/C;;;;AAA+C;AAsB/C;;AAtBA,iBAsBgB,6BAAA,CACd,QAAA,GAAW,UAAA,EAAY,yBAAA,KAA8B,WAAA,gBAAwB,QAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ObjectStreamAccumulator.d.ts","names":[],"sources":["../../../src/core/object/ObjectStreamAccumulator.ts"],"mappings":";;;;cAGa,uBAAA;EAAA,QACH,MAAA;cAEI,YAAA,GAAc,iBAAA;EAAA,IAItB,KAAA,
|
|
1
|
+
{"version":3,"file":"ObjectStreamAccumulator.d.ts","names":[],"sources":["../../../src/core/object/ObjectStreamAccumulator.ts"],"mappings":";;;;cAGa,uBAAA;EAAA,QACH,MAAA;cAEI,YAAA,GAAc,iBAAA;EAAA,IAItB,KAAA,IAAK,iBAAA;EAIT,MAAA,CAAO,GAAA,WAAc,qBAAA;EAAA,eAON,KAAA;EAAA,eAuBA,UAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ObjectStreamResponse.js","names":["#isFirstChunk"],"sources":["../../../src/core/object/ObjectStreamResponse.ts"],"sourcesContent":["import { PipeableTransformStream } from \"../utils/stream/PipeableTransformStream\";\nimport { ObjectStreamAccumulator } from \"./ObjectStreamAccumulator\";\nimport { SSEDecoder, SSEEncoder } from \"../utils/stream/SSE\";\nimport type { ObjectStreamChunk, ObjectStreamOperation } from \"./types\";\n\nexport class ObjectStreamEncoder extends PipeableTransformStream<\n ObjectStreamChunk,\n Uint8Array\n> {\n constructor() {\n super((readable) =>\n readable\n .pipeThrough(\n (() => {\n class ObjectStreamTransformer
|
|
1
|
+
{"version":3,"file":"ObjectStreamResponse.js","names":["#isFirstChunk"],"sources":["../../../src/core/object/ObjectStreamResponse.ts"],"sourcesContent":["import { PipeableTransformStream } from \"../utils/stream/PipeableTransformStream\";\nimport { ObjectStreamAccumulator } from \"./ObjectStreamAccumulator\";\nimport { SSEDecoder, SSEEncoder } from \"../utils/stream/SSE\";\nimport type { ObjectStreamChunk, ObjectStreamOperation } from \"./types\";\n\nexport class ObjectStreamEncoder extends PipeableTransformStream<\n ObjectStreamChunk,\n Uint8Array\n> {\n constructor() {\n super((readable) =>\n readable\n .pipeThrough(\n (() => {\n class ObjectStreamTransformer implements Transformer<\n ObjectStreamChunk,\n readonly ObjectStreamOperation[]\n > {\n #isFirstChunk = true;\n\n start() {\n // Nothing needed here since we initialize in the field declaration\n }\n\n transform(\n chunk: ObjectStreamChunk,\n controller: TransformStreamDefaultController<\n readonly ObjectStreamOperation[]\n >,\n ) {\n if (\n this.#isFirstChunk &&\n chunk.snapshot &&\n Object.keys(chunk.snapshot).length > 0\n ) {\n // For the first chunk, if there's an initial state that's not empty,\n // prepend a set operation for the initial state\n controller.enqueue([\n { type: \"set\", path: [], value: chunk.snapshot },\n ...chunk.operations,\n ]);\n } else {\n controller.enqueue(chunk.operations);\n }\n this.#isFirstChunk = false;\n }\n }\n return new TransformStream(new ObjectStreamTransformer());\n })(),\n )\n .pipeThrough(new SSEEncoder()),\n );\n }\n}\n\nexport class ObjectStreamDecoder extends PipeableTransformStream<\n Uint8Array<ArrayBuffer>,\n ObjectStreamChunk\n> {\n constructor() {\n const accumulator = new ObjectStreamAccumulator();\n super((readable) =>\n readable\n .pipeThrough(new SSEDecoder<readonly ObjectStreamOperation[]>())\n .pipeThrough(\n new TransformStream<\n readonly ObjectStreamOperation[],\n ObjectStreamChunk\n >({\n transform(operations, controller) {\n accumulator.append(operations);\n controller.enqueue({\n snapshot: accumulator.state,\n operations,\n });\n },\n }),\n ),\n );\n }\n}\n\nexport class ObjectStreamResponse extends Response {\n constructor(body: ReadableStream<ObjectStreamChunk>) {\n super(body.pipeThrough(new ObjectStreamEncoder()), {\n headers: new Headers({\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n \"Assistant-Stream-Format\": \"object-stream/v0\",\n }),\n });\n }\n}\n\nexport const fromObjectStreamResponse = (\n response: Response,\n): ReadableStream<ObjectStreamChunk> => {\n if (!response.ok)\n throw new Error(`Response failed, status ${response.status}`);\n if (!response.body) throw new Error(\"Response body is null\");\n if (response.headers.get(\"Content-Type\") !== \"text/event-stream\") {\n throw new Error(\"Response is not an event stream\");\n }\n if (response.headers.get(\"Assistant-Stream-Format\") !== \"object-stream/v0\") {\n throw new Error(\"Unsupported Assistant-Stream-Format header\");\n }\n return response.body.pipeThrough(new ObjectStreamDecoder());\n};\n"],"mappings":";;;;AAKA,IAAa,sBAAb,cAAyC,wBAGvC;CACA,cAAc;EACZ,OAAO,aACL,SACG,mBACQ;GACL,MAAM,wBAGJ;IACA,gBAAgB;IAEhB,QAAQ,CAER;IAEA,UACE,OACA,YAGA;KACA,IACE,KAAKA,iBACL,MAAM,YACN,OAAO,KAAK,MAAM,QAAQ,EAAE,SAAS,GAIrC,WAAW,QAAQ,CACjB;MAAE,MAAM;MAAO,MAAM,CAAC;MAAG,OAAO,MAAM;KAAS,GAC/C,GAAG,MAAM,UACX,CAAC;UAED,WAAW,QAAQ,MAAM,UAAU;KAErC,KAAKA,gBAAgB;IACvB;GACF;GACA,OAAO,IAAI,gBAAgB,IAAI,wBAAwB,CAAC;EAC1D,GAAG,CACL,EACC,YAAY,IAAI,WAAW,CAAC,CACjC;CACF;AACF;AAEA,IAAa,sBAAb,cAAyC,wBAGvC;CACA,cAAc;EACZ,MAAM,cAAc,IAAI,wBAAwB;EAChD,OAAO,aACL,SACG,YAAY,IAAI,WAA6C,CAAC,EAC9D,YACC,IAAI,gBAGF,EACA,UAAU,YAAY,YAAY;GAChC,YAAY,OAAO,UAAU;GAC7B,WAAW,QAAQ;IACjB,UAAU,YAAY;IACtB;GACF,CAAC;EACH,EACF,CAAC,CACH,CACJ;CACF;AACF;AAEA,IAAa,uBAAb,cAA0C,SAAS;CACjD,YAAY,MAAyC;EACnD,MAAM,KAAK,YAAY,IAAI,oBAAoB,CAAC,GAAG,EACjD,SAAS,IAAI,QAAQ;GACnB,gBAAgB;GAChB,iBAAiB;GACjB,YAAY;GACZ,2BAA2B;EAC7B,CAAC,EACH,CAAC;CACH;AACF;AAEA,MAAa,4BACX,aACsC;CACtC,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,2BAA2B,SAAS,QAAQ;CAC9D,IAAI,CAAC,SAAS,MAAM,MAAM,IAAI,MAAM,uBAAuB;CAC3D,IAAI,SAAS,QAAQ,IAAI,cAAc,MAAM,qBAC3C,MAAM,IAAI,MAAM,iCAAiC;CAEnD,IAAI,SAAS,QAAQ,IAAI,yBAAyB,MAAM,oBACtD,MAAM,IAAI,MAAM,4CAA4C;CAE9D,OAAO,SAAS,KAAK,YAAY,IAAI,oBAAoB,CAAC;AAC5D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DataStream.js","names":["exhaustiveCheck"],"sources":["../../../../src/core/serialization/data-stream/DataStream.ts"],"sourcesContent":["import type { AssistantStreamChunk } from \"../../AssistantStreamChunk\";\nimport type { ToolCallStreamController } from \"../../modules/tool-call\";\nimport { AssistantTransformStream } from \"../../utils/stream/AssistantTransformStream\";\nimport { PipeableTransformStream } from \"../../utils/stream/PipeableTransformStream\";\nimport { type DataStreamChunk, DataStreamStreamChunkType } from \"./chunk-types\";\nimport { LineDecoderStream } from \"../../utils/stream/LineDecoderStream\";\nimport {\n DataStreamChunkDecoder,\n DataStreamChunkEncoder,\n} from \"./serialization\";\nimport {\n type AssistantMetaStreamChunk,\n AssistantMetaTransformStream,\n} from \"../../utils/stream/AssistantMetaTransformStream\";\nimport type { TextStreamController } from \"../../modules/text\";\nimport type { AssistantStreamEncoder } from \"../../AssistantStream\";\n\nexport class DataStreamEncoder\n extends PipeableTransformStream<AssistantStreamChunk, Uint8Array<ArrayBuffer>>\n implements AssistantStreamEncoder\n{\n headers = new Headers({\n \"Content-Type\": \"text/plain; charset=utf-8\",\n \"x-vercel-ai-data-stream\": \"v1\",\n });\n\n constructor() {\n super((readable) => {\n const transform = new TransformStream<\n AssistantMetaStreamChunk,\n DataStreamChunk\n >({\n transform(chunk, controller) {\n const type = chunk.type;\n switch (type) {\n case \"part-start\": {\n const part = chunk.part;\n if (part.type === \"tool-call\") {\n const { type, ...value } = part;\n controller.enqueue({\n type: DataStreamStreamChunkType.StartToolCall,\n value,\n });\n }\n if (part.type === \"source\") {\n const { type, ...value } = part;\n controller.enqueue({\n type: DataStreamStreamChunkType.Source,\n value,\n });\n }\n if (part.type === \"data\") {\n const { type, ...value } = part;\n controller.enqueue({\n type: DataStreamStreamChunkType.AuiDataPart,\n value,\n });\n }\n break;\n }\n case \"text-delta\": {\n const part = chunk.meta;\n switch (part.type) {\n case \"text\": {\n if (part.parentId) {\n controller.enqueue({\n type: DataStreamStreamChunkType.AuiTextDelta,\n value: {\n textDelta: chunk.textDelta,\n parentId: part.parentId,\n },\n });\n } else {\n controller.enqueue({\n type: DataStreamStreamChunkType.TextDelta,\n value: chunk.textDelta,\n });\n }\n break;\n }\n case \"reasoning\": {\n if (part.parentId) {\n controller.enqueue({\n type: DataStreamStreamChunkType.AuiReasoningDelta,\n value: {\n reasoningDelta: chunk.textDelta,\n parentId: part.parentId,\n },\n });\n } else {\n controller.enqueue({\n type: DataStreamStreamChunkType.ReasoningDelta,\n value: chunk.textDelta,\n });\n }\n break;\n }\n case \"tool-call\": {\n controller.enqueue({\n type: DataStreamStreamChunkType.ToolCallArgsTextDelta,\n value: {\n toolCallId: part.toolCallId,\n argsTextDelta: chunk.textDelta,\n },\n });\n break;\n }\n default:\n throw new Error(\n `Unsupported part type for text-delta: ${part.type}`,\n );\n }\n break;\n }\n case \"result\": {\n // Only tool-call parts can have results.\n const part = chunk.meta;\n if (part.type !== \"tool-call\") {\n throw new Error(\n `Result chunk on non-tool-call part not supported: ${part.type}`,\n );\n }\n controller.enqueue({\n type: DataStreamStreamChunkType.ToolCallResult,\n value: {\n toolCallId: part.toolCallId,\n result: chunk.result,\n artifact: chunk.artifact,\n ...(chunk.isError ? { isError: chunk.isError } : {}),\n },\n });\n break;\n }\n case \"step-start\": {\n const { type, ...value } = chunk;\n controller.enqueue({\n type: DataStreamStreamChunkType.StartStep,\n value,\n });\n break;\n }\n case \"step-finish\": {\n const { type, ...value } = chunk;\n controller.enqueue({\n type: DataStreamStreamChunkType.FinishStep,\n value,\n });\n break;\n }\n case \"message-finish\": {\n const { type, ...value } = chunk;\n controller.enqueue({\n type: DataStreamStreamChunkType.FinishMessage,\n value,\n });\n break;\n }\n case \"error\": {\n controller.enqueue({\n type: DataStreamStreamChunkType.Error,\n value: chunk.error,\n });\n break;\n }\n case \"annotations\": {\n controller.enqueue({\n type: DataStreamStreamChunkType.Annotation,\n value: chunk.annotations,\n });\n break;\n }\n case \"data\": {\n controller.enqueue({\n type: DataStreamStreamChunkType.Data,\n value: chunk.data,\n });\n break;\n }\n\n case \"update-state\": {\n controller.enqueue({\n type: DataStreamStreamChunkType.AuiUpdateStateOperations,\n value: chunk.operations,\n });\n break;\n }\n\n // TODO ignore for now\n // in the future, we should create a handler that waits for text parts to finish before continuing\n case \"tool-call-args-text-finish\":\n case \"part-finish\":\n break;\n\n default: {\n const exhaustiveCheck: never = type;\n throw new Error(`Unsupported chunk type: ${exhaustiveCheck}`);\n }\n }\n },\n });\n\n return readable\n .pipeThrough(new AssistantMetaTransformStream())\n .pipeThrough(transform)\n .pipeThrough(new DataStreamChunkEncoder())\n .pipeThrough(new TextEncoderStream());\n });\n }\n}\n\nconst TOOL_CALL_ARGS_CLOSING_CHUNKS = [\n DataStreamStreamChunkType.StartToolCall,\n DataStreamStreamChunkType.ToolCall,\n DataStreamStreamChunkType.TextDelta,\n DataStreamStreamChunkType.ReasoningDelta,\n DataStreamStreamChunkType.Source,\n DataStreamStreamChunkType.Error,\n DataStreamStreamChunkType.FinishStep,\n DataStreamStreamChunkType.FinishMessage,\n DataStreamStreamChunkType.AuiTextDelta,\n DataStreamStreamChunkType.AuiReasoningDelta,\n DataStreamStreamChunkType.AuiDataPart,\n];\n\nexport class DataStreamDecoder extends PipeableTransformStream<\n Uint8Array<ArrayBuffer>,\n AssistantStreamChunk\n> {\n constructor() {\n super((readable) => {\n const toolCallControllers = new Map<string, ToolCallStreamController>();\n let activeToolCallArgsText: TextStreamController | undefined;\n const transform = new AssistantTransformStream<DataStreamChunk>({\n transform(chunk, controller) {\n const { type, value } = chunk;\n\n if (TOOL_CALL_ARGS_CLOSING_CHUNKS.includes(type)) {\n activeToolCallArgsText?.close();\n activeToolCallArgsText = undefined;\n }\n\n switch (type) {\n case DataStreamStreamChunkType.ReasoningDelta:\n controller.appendReasoning(value);\n break;\n\n case DataStreamStreamChunkType.TextDelta:\n controller.appendText(value);\n break;\n\n case DataStreamStreamChunkType.AuiTextDelta:\n controller\n .withParentId(value.parentId)\n .appendText(value.textDelta);\n break;\n\n case DataStreamStreamChunkType.AuiReasoningDelta:\n controller\n .withParentId(value.parentId)\n .appendReasoning(value.reasoningDelta);\n break;\n\n case DataStreamStreamChunkType.StartToolCall: {\n const { toolCallId, toolName, parentId } = value;\n const ctrl = parentId\n ? controller.withParentId(parentId)\n : controller;\n\n if (toolCallControllers.has(toolCallId))\n throw new Error(\n `Encountered duplicate tool call id: ${toolCallId}`,\n );\n\n const toolCallController = ctrl.addToolCallPart({\n toolCallId,\n toolName,\n });\n toolCallControllers.set(toolCallId, toolCallController);\n\n activeToolCallArgsText = toolCallController.argsText;\n break;\n }\n\n case DataStreamStreamChunkType.ToolCallArgsTextDelta: {\n const { toolCallId, argsTextDelta } = value;\n const toolCallController = toolCallControllers.get(toolCallId);\n if (!toolCallController)\n throw new Error(\n `Encountered tool call with unknown id: ${toolCallId}`,\n );\n toolCallController.argsText.append(argsTextDelta);\n break;\n }\n\n case DataStreamStreamChunkType.ToolCallResult: {\n const { toolCallId, artifact, result, isError } = value;\n const toolCallController = toolCallControllers.get(toolCallId);\n if (!toolCallController)\n throw new Error(\n `Encountered tool call result with unknown id: ${toolCallId}`,\n );\n toolCallController.setResponse({\n artifact,\n result,\n isError,\n });\n break;\n }\n\n case DataStreamStreamChunkType.ToolCall: {\n const { toolCallId, toolName, args } = value;\n\n let toolCallController = toolCallControllers.get(toolCallId);\n if (toolCallController) {\n toolCallController.argsText.close();\n } else {\n toolCallController = controller.addToolCallPart({\n toolCallId,\n toolName,\n args,\n });\n toolCallControllers.set(toolCallId, toolCallController);\n }\n break;\n }\n\n case DataStreamStreamChunkType.FinishMessage:\n controller.enqueue({\n type: \"message-finish\",\n path: [],\n ...value,\n });\n break;\n\n case DataStreamStreamChunkType.StartStep:\n controller.enqueue({\n type: \"step-start\",\n path: [],\n ...value,\n });\n break;\n\n case DataStreamStreamChunkType.FinishStep:\n controller.enqueue({\n type: \"step-finish\",\n path: [],\n ...value,\n });\n break;\n case DataStreamStreamChunkType.Data:\n controller.enqueue({\n type: \"data\",\n path: [],\n data: value,\n });\n break;\n\n case DataStreamStreamChunkType.Annotation:\n controller.enqueue({\n type: \"annotations\",\n path: [],\n annotations: value,\n });\n break;\n\n case DataStreamStreamChunkType.Source: {\n const { parentId, ...sourceData } = value;\n const ctrl = parentId\n ? controller.withParentId(parentId)\n : controller;\n ctrl.appendSource({\n type: \"source\",\n ...sourceData,\n });\n break;\n }\n\n case DataStreamStreamChunkType.Error:\n controller.enqueue({\n type: \"error\",\n path: [],\n error: value,\n });\n break;\n\n case DataStreamStreamChunkType.File:\n controller.appendFile({\n type: \"file\",\n ...value,\n });\n break;\n\n case DataStreamStreamChunkType.AuiDataPart:\n controller.appendData({\n type: \"data\",\n ...value,\n });\n break;\n\n case DataStreamStreamChunkType.AuiUpdateStateOperations:\n controller.enqueue({\n type: \"update-state\",\n path: [],\n operations: value,\n });\n break;\n\n case DataStreamStreamChunkType.ReasoningSignature:\n case DataStreamStreamChunkType.RedactedReasoning:\n // ignore these for now\n break;\n\n default: {\n const exhaustiveCheck: never = type;\n throw new Error(`unsupported chunk type: ${exhaustiveCheck}`);\n }\n }\n },\n flush() {\n activeToolCallArgsText?.close();\n activeToolCallArgsText = undefined;\n // biome-ignore lint/suspicious/useIterableCallbackReturn: forEach callback intentionally has no return\n toolCallControllers.forEach((controller) => controller.close());\n toolCallControllers.clear();\n },\n });\n\n return readable\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new LineDecoderStream())\n .pipeThrough(new DataStreamChunkDecoder())\n .pipeThrough(transform);\n });\n }\n}\n"],"mappings":";;;;;;;AAiBA,IAAa,oBAAb,cACU,wBAEV;CACE,UAAU,IAAI,QAAQ;EACpB,gBAAgB;EAChB,2BAA2B;CAC7B,CAAC;CAED,cAAc;EACZ,OAAO,aAAa;GAClB,MAAM,YAAY,IAAI,gBAGpB,EACA,UAAU,OAAO,YAAY;IAC3B,MAAM,OAAO,MAAM;IACnB,QAAQ,MAAR;KACE,KAAK,cAAc;MACjB,MAAM,OAAO,MAAM;MACnB,IAAI,KAAK,SAAS,aAAa;OAC7B,MAAM,EAAE,MAAM,GAAG,UAAU;OAC3B,WAAW,QAAQ;QACjB,MAAA;QACA;OACF,CAAC;MACH;MACA,IAAI,KAAK,SAAS,UAAU;OA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OACL,CAAC;OACD;MAEF,KAAA;OACE,WAAW,QAAQ;QACjB,MAAM;QACN,MAAM,CAAC;QACP,GAAG;OACL,CAAC;OACD;MACF,KAAA;OACE,WAAW,QAAQ;QACjB,MAAM;QACN,MAAM,CAAC;QACP,MAAM;OACR,CAAC;OACD;MAEF,KAAA;OACE,WAAW,QAAQ;QACjB,MAAM;QACN,MAAM,CAAC;QACP,aAAa;OACf,CAAC;OACD;MAEF,KAAA,KAAuC;OACrC,MAAM,EAAE,UAAU,GAAG,eAAe;OAIpC,CAHa,WACT,WAAW,aAAa,QAAQ,IAChC,YACC,aAAa;QAChB,MAAM;QACN,GAAG;OACL,CAAC;OACD;MACF;MAEA,KAAA;OACE,WAAW,QAAQ;QACjB,MAAM;QACN,MAAM,CAAC;QACP,OAAO;OACT,CAAC;OACD;MAEF,KAAA;OACE,WAAW,WAAW;QACpB,MAAM;QACN,GAAG;OACL,CAAC;OACD;MAEF,KAAA;OACE,WAAW,WAAW;QACpB,MAAM;QACN,GAAG;OACL,CAAC;OACD;MAEF,KAAA;OACE,WAAW,QAAQ;QACjB,MAAM;QACN,MAAM,CAAC;QACP,YAAY;OACd,CAAC;OACD;MAEF,KAAA;MACA,KAAA,KAEE;MAEF,SAEE,MAAM,IAAI,MAAM,2BAA2BA,MAAiB;KAEhE;IACF;IACA,QAAQ;KACN,wBAAwB,MAAM;KAC9B,yBAAyB,KAAA;KAEzB,oBAAoB,SAAS,eAAe,WAAW,MAAM,CAAC;KAC9D,oBAAoB,MAAM;IAC5B;GACF,CAAC;GAED,OAAO,SACJ,YAAY,IAAI,kBAAkB,CAAC,EACnC,YAAY,IAAI,kBAAkB,CAAC,EACnC,YAAY,IAAI,uBAAuB,CAAC,EACxC,YAAY,SAAS;EAC1B,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"DataStream.js","names":["exhaustiveCheck"],"sources":["../../../../src/core/serialization/data-stream/DataStream.ts"],"sourcesContent":["import type { AssistantStreamChunk } from \"../../AssistantStreamChunk\";\nimport type { ToolCallStreamController } from \"../../modules/tool-call\";\nimport { AssistantTransformStream } from \"../../utils/stream/AssistantTransformStream\";\nimport { PipeableTransformStream } from \"../../utils/stream/PipeableTransformStream\";\nimport { type DataStreamChunk, DataStreamStreamChunkType } from \"./chunk-types\";\nimport { LineDecoderStream } from \"../../utils/stream/LineDecoderStream\";\nimport {\n DataStreamChunkDecoder,\n DataStreamChunkEncoder,\n} from \"./serialization\";\nimport {\n type AssistantMetaStreamChunk,\n AssistantMetaTransformStream,\n} from \"../../utils/stream/AssistantMetaTransformStream\";\nimport type { TextStreamController } from \"../../modules/text\";\nimport type { AssistantStreamEncoder } from \"../../AssistantStream\";\n\nexport class DataStreamEncoder\n extends PipeableTransformStream<AssistantStreamChunk, Uint8Array<ArrayBuffer>>\n implements AssistantStreamEncoder\n{\n headers = new Headers({\n \"Content-Type\": \"text/plain; charset=utf-8\",\n \"x-vercel-ai-data-stream\": \"v1\",\n });\n\n constructor() {\n super((readable) => {\n const transform = new TransformStream<\n AssistantMetaStreamChunk,\n DataStreamChunk\n >({\n transform(chunk, controller) {\n const type = chunk.type;\n switch (type) {\n case \"part-start\": {\n const part = chunk.part;\n if (part.type === \"tool-call\") {\n const { type, ...value } = part;\n controller.enqueue({\n type: DataStreamStreamChunkType.StartToolCall,\n value,\n });\n }\n if (part.type === \"source\") {\n const { type, ...value } = part;\n controller.enqueue({\n type: DataStreamStreamChunkType.Source,\n value,\n });\n }\n if (part.type === \"data\") {\n const { type, ...value } = part;\n controller.enqueue({\n type: DataStreamStreamChunkType.AuiDataPart,\n value,\n });\n }\n break;\n }\n case \"text-delta\": {\n const part = chunk.meta;\n switch (part.type) {\n case \"text\": {\n if (part.parentId) {\n controller.enqueue({\n type: DataStreamStreamChunkType.AuiTextDelta,\n value: {\n textDelta: chunk.textDelta,\n parentId: part.parentId,\n },\n });\n } else {\n controller.enqueue({\n type: DataStreamStreamChunkType.TextDelta,\n value: chunk.textDelta,\n });\n }\n break;\n }\n case \"reasoning\": {\n if (part.parentId) {\n controller.enqueue({\n type: DataStreamStreamChunkType.AuiReasoningDelta,\n value: {\n reasoningDelta: chunk.textDelta,\n parentId: part.parentId,\n },\n });\n } else {\n controller.enqueue({\n type: DataStreamStreamChunkType.ReasoningDelta,\n value: chunk.textDelta,\n });\n }\n break;\n }\n case \"tool-call\": {\n controller.enqueue({\n type: DataStreamStreamChunkType.ToolCallArgsTextDelta,\n value: {\n toolCallId: part.toolCallId,\n argsTextDelta: chunk.textDelta,\n },\n });\n break;\n }\n default:\n throw new Error(\n `Unsupported part type for text-delta: ${part.type}`,\n );\n }\n break;\n }\n case \"result\": {\n // Only tool-call parts can have results.\n const part = chunk.meta;\n if (part.type !== \"tool-call\") {\n throw new Error(\n `Result chunk on non-tool-call part not supported: ${part.type}`,\n );\n }\n controller.enqueue({\n type: DataStreamStreamChunkType.ToolCallResult,\n value: {\n toolCallId: part.toolCallId,\n result: chunk.result,\n artifact: chunk.artifact,\n ...(chunk.isError ? { isError: chunk.isError } : {}),\n },\n });\n break;\n }\n case \"step-start\": {\n const { type, ...value } = chunk;\n controller.enqueue({\n type: DataStreamStreamChunkType.StartStep,\n value,\n });\n break;\n }\n case \"step-finish\": {\n const { type, ...value } = chunk;\n controller.enqueue({\n type: DataStreamStreamChunkType.FinishStep,\n value,\n });\n break;\n }\n case \"message-finish\": {\n const { type, ...value } = chunk;\n controller.enqueue({\n type: DataStreamStreamChunkType.FinishMessage,\n value,\n });\n break;\n }\n case \"error\": {\n controller.enqueue({\n type: DataStreamStreamChunkType.Error,\n value: chunk.error,\n });\n break;\n }\n case \"annotations\": {\n controller.enqueue({\n type: DataStreamStreamChunkType.Annotation,\n value: chunk.annotations,\n });\n break;\n }\n case \"data\": {\n controller.enqueue({\n type: DataStreamStreamChunkType.Data,\n value: chunk.data,\n });\n break;\n }\n\n case \"update-state\": {\n controller.enqueue({\n type: DataStreamStreamChunkType.AuiUpdateStateOperations,\n value: chunk.operations,\n });\n break;\n }\n\n // TODO ignore for now\n // in the future, we should create a handler that waits for text parts to finish before continuing\n case \"tool-call-args-text-finish\":\n case \"part-finish\":\n break;\n\n default: {\n const exhaustiveCheck: never = type;\n throw new Error(`Unsupported chunk type: ${exhaustiveCheck}`);\n }\n }\n },\n });\n\n return readable\n .pipeThrough(new AssistantMetaTransformStream())\n .pipeThrough(transform)\n .pipeThrough(new DataStreamChunkEncoder())\n .pipeThrough(new TextEncoderStream());\n });\n }\n}\n\nconst TOOL_CALL_ARGS_CLOSING_CHUNKS = [\n DataStreamStreamChunkType.StartToolCall,\n DataStreamStreamChunkType.ToolCall,\n DataStreamStreamChunkType.TextDelta,\n DataStreamStreamChunkType.ReasoningDelta,\n DataStreamStreamChunkType.Source,\n DataStreamStreamChunkType.Error,\n DataStreamStreamChunkType.FinishStep,\n DataStreamStreamChunkType.FinishMessage,\n DataStreamStreamChunkType.AuiTextDelta,\n DataStreamStreamChunkType.AuiReasoningDelta,\n DataStreamStreamChunkType.AuiDataPart,\n];\n\nexport class DataStreamDecoder extends PipeableTransformStream<\n Uint8Array<ArrayBuffer>,\n AssistantStreamChunk\n> {\n constructor() {\n super((readable) => {\n const toolCallControllers = new Map<string, ToolCallStreamController>();\n let activeToolCallArgsText: TextStreamController | undefined;\n const transform = new AssistantTransformStream<DataStreamChunk>({\n transform(chunk, controller) {\n const { type, value } = chunk;\n\n if (TOOL_CALL_ARGS_CLOSING_CHUNKS.includes(type)) {\n activeToolCallArgsText?.close();\n activeToolCallArgsText = undefined;\n }\n\n switch (type) {\n case DataStreamStreamChunkType.ReasoningDelta:\n controller.appendReasoning(value);\n break;\n\n case DataStreamStreamChunkType.TextDelta:\n controller.appendText(value);\n break;\n\n case DataStreamStreamChunkType.AuiTextDelta:\n controller\n .withParentId(value.parentId)\n .appendText(value.textDelta);\n break;\n\n case DataStreamStreamChunkType.AuiReasoningDelta:\n controller\n .withParentId(value.parentId)\n .appendReasoning(value.reasoningDelta);\n break;\n\n case DataStreamStreamChunkType.StartToolCall: {\n const { toolCallId, toolName, parentId } = value;\n const ctrl = parentId\n ? controller.withParentId(parentId)\n : controller;\n\n if (toolCallControllers.has(toolCallId))\n throw new Error(\n `Encountered duplicate tool call id: ${toolCallId}`,\n );\n\n const toolCallController = ctrl.addToolCallPart({\n toolCallId,\n toolName,\n });\n toolCallControllers.set(toolCallId, toolCallController);\n\n activeToolCallArgsText = toolCallController.argsText;\n break;\n }\n\n case DataStreamStreamChunkType.ToolCallArgsTextDelta: {\n const { toolCallId, argsTextDelta } = value;\n const toolCallController = toolCallControllers.get(toolCallId);\n if (!toolCallController)\n throw new Error(\n `Encountered tool call with unknown id: ${toolCallId}`,\n );\n toolCallController.argsText.append(argsTextDelta);\n break;\n }\n\n case DataStreamStreamChunkType.ToolCallResult: {\n const { toolCallId, artifact, result, isError } = value;\n const toolCallController = toolCallControllers.get(toolCallId);\n if (!toolCallController)\n throw new Error(\n `Encountered tool call result with unknown id: ${toolCallId}`,\n );\n toolCallController.setResponse({\n artifact,\n result,\n isError,\n });\n break;\n }\n\n case DataStreamStreamChunkType.ToolCall: {\n const { toolCallId, toolName, args } = value;\n\n let toolCallController = toolCallControllers.get(toolCallId);\n if (toolCallController) {\n toolCallController.argsText.close();\n } else {\n toolCallController = controller.addToolCallPart({\n toolCallId,\n toolName,\n args,\n });\n toolCallControllers.set(toolCallId, toolCallController);\n }\n break;\n }\n\n case DataStreamStreamChunkType.FinishMessage:\n controller.enqueue({\n type: \"message-finish\",\n path: [],\n ...value,\n });\n break;\n\n case DataStreamStreamChunkType.StartStep:\n controller.enqueue({\n type: \"step-start\",\n path: [],\n ...value,\n });\n break;\n\n case DataStreamStreamChunkType.FinishStep:\n controller.enqueue({\n type: \"step-finish\",\n path: [],\n ...value,\n });\n break;\n case DataStreamStreamChunkType.Data:\n controller.enqueue({\n type: \"data\",\n path: [],\n data: value,\n });\n break;\n\n case DataStreamStreamChunkType.Annotation:\n controller.enqueue({\n type: \"annotations\",\n path: [],\n annotations: value,\n });\n break;\n\n case DataStreamStreamChunkType.Source: {\n const { parentId, ...sourceData } = value;\n const ctrl = parentId\n ? controller.withParentId(parentId)\n : controller;\n ctrl.appendSource({\n type: \"source\",\n ...sourceData,\n });\n break;\n }\n\n case DataStreamStreamChunkType.Error:\n controller.enqueue({\n type: \"error\",\n path: [],\n error: value,\n });\n break;\n\n case DataStreamStreamChunkType.File:\n controller.appendFile({\n type: \"file\",\n ...value,\n });\n break;\n\n case DataStreamStreamChunkType.AuiDataPart:\n controller.appendData({\n type: \"data\",\n ...value,\n });\n break;\n\n case DataStreamStreamChunkType.AuiUpdateStateOperations:\n controller.enqueue({\n type: \"update-state\",\n path: [],\n operations: value,\n });\n break;\n\n case DataStreamStreamChunkType.ReasoningSignature:\n case DataStreamStreamChunkType.RedactedReasoning:\n // ignore these for now\n break;\n\n default: {\n const exhaustiveCheck: never = type;\n throw new Error(`unsupported chunk type: ${exhaustiveCheck}`);\n }\n }\n },\n flush() {\n activeToolCallArgsText?.close();\n activeToolCallArgsText = undefined;\n toolCallControllers.forEach((controller) => controller.close());\n toolCallControllers.clear();\n },\n });\n\n return readable\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new LineDecoderStream())\n .pipeThrough(new DataStreamChunkDecoder())\n .pipeThrough(transform);\n });\n }\n}\n"],"mappings":";;;;;;;AAiBA,IAAa,oBAAb,cACU,wBAEV;CACE,UAAU,IAAI,QAAQ;EACpB,gBAAgB;EAChB,2BAA2B;CAC7B,CAAC;CAED,cAAc;EACZ,OAAO,aAAa;GAClB,MAAM,YAAY,IAAI,gBAGpB,EACA,UAAU,OAAO,YAAY;IAC3B,MAAM,OAAO,MAAM;IACnB,QAAQ,MAAR;KACE,KAAK,cAAc;MACjB,MAAM,OAAO,MAAM;MACnB,IAAI,KAAK,SAAS,aAAa;OAC7B,MAAM,EAAE,MAAM,GAAG,UAAU;OAC3B,WAAW,QAAQ;QACjB,MAAA;QACA;OACF,CAAC;MACH;MACA,IAAI,KAAK,SAAS,UAAU;OAC1B,MAAM,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OACD;MAEF,KAAA;OACE,WAAW,QAAQ;QACjB,MAAM;QACN,MAAM,CAAC;QACP,GAAG;OACL,CAAC;OACD;MACF,KAAA;OACE,WAAW,QAAQ;QACjB,MAAM;QACN,MAAM,CAAC;QACP,MAAM;OACR,CAAC;OACD;MAEF,KAAA;OACE,WAAW,QAAQ;QACjB,MAAM;QACN,MAAM,CAAC;QACP,aAAa;OACf,CAAC;OACD;MAEF,KAAA,KAAuC;OACrC,MAAM,EAAE,UAAU,GAAG,eAAe;OAIpC,CAHa,WACT,WAAW,aAAa,QAAQ,IAChC,YACC,aAAa;QAChB,MAAM;QACN,GAAG;OACL,CAAC;OACD;MACF;MAEA,KAAA;OACE,WAAW,QAAQ;QACjB,MAAM;QACN,MAAM,CAAC;QACP,OAAO;OACT,CAAC;OACD;MAEF,KAAA;OACE,WAAW,WAAW;QACpB,MAAM;QACN,GAAG;OACL,CAAC;OACD;MAEF,KAAA;OACE,WAAW,WAAW;QACpB,MAAM;QACN,GAAG;OACL,CAAC;OACD;MAEF,KAAA;OACE,WAAW,QAAQ;QACjB,MAAM;QACN,MAAM,CAAC;QACP,YAAY;OACd,CAAC;OACD;MAEF,KAAA;MACA,KAAA,KAEE;MAEF,SAEE,MAAM,IAAI,MAAM,2BAA2BA,MAAiB;KAEhE;IACF;IACA,QAAQ;KACN,wBAAwB,MAAM;KAC9B,yBAAyB,KAAA;KACzB,oBAAoB,SAAS,eAAe,WAAW,MAAM,CAAC;KAC9D,oBAAoB,MAAM;IAC5B;GACF,CAAC;GAED,OAAO,SACJ,YAAY,IAAI,kBAAkB,CAAC,EACnC,YAAY,IAAI,kBAAkB,CAAC,EACnC,YAAY,IAAI,uBAAuB,CAAC,EACxC,YAAY,SAAS;EAC1B,CAAC;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UIMessageStream.js","names":[],"sources":["../../../../src/core/serialization/ui-message-stream/UIMessageStream.ts"],"sourcesContent":["import type { AssistantStreamChunk } from \"../../AssistantStreamChunk\";\nimport type { ToolCallStreamController } from \"../../modules/tool-call\";\nimport type { TextStreamController } from \"../../modules/text\";\nimport { AssistantTransformStream } from \"../../utils/stream/AssistantTransformStream\";\nimport { PipeableTransformStream } from \"../../utils/stream/PipeableTransformStream\";\nimport { LineDecoderStream } from \"../../utils/stream/LineDecoderStream\";\nimport type {\n UIMessageStreamChunk,\n UIMessageStreamDataChunk,\n} from \"./chunk-types\";\nimport { generateId } from \"../../utils/generateId\";\n\nexport type { UIMessageStreamChunk, UIMessageStreamDataChunk };\n\nexport type UIMessageStreamDecoderOptions = {\n onData?: (data: {\n type: string;\n name: string;\n data: unknown;\n transient?: boolean;\n }) => void;\n};\n\ntype SSEEvent = {\n event: string;\n data: string;\n id?: string | undefined;\n retry?: number | undefined;\n};\n\nclass SSEEventStream extends TransformStream<string, SSEEvent> {\n constructor() {\n let eventBuffer: Partial<SSEEvent> = {};\n let dataLines: string[] = [];\n\n super({\n start() {\n eventBuffer = {};\n dataLines = [];\n },\n transform(line, controller) {\n if (line.startsWith(\":\")) return;\n\n if (line === \"\") {\n if (dataLines.length > 0) {\n controller.enqueue({\n event: eventBuffer.event || \"message\",\n data: dataLines.join(\"\\n\"),\n id: eventBuffer.id,\n retry: eventBuffer.retry,\n });\n }\n eventBuffer = {};\n dataLines = [];\n return;\n }\n\n const [field, ...rest] = line.split(\":\");\n const value = rest.join(\":\").trimStart();\n\n switch (field) {\n case \"event\":\n eventBuffer.event = value;\n break;\n case \"data\":\n dataLines.push(value);\n break;\n case \"id\":\n eventBuffer.id = value;\n break;\n case \"retry\":\n eventBuffer.retry = Number(value);\n break;\n }\n },\n flush(controller) {\n if (dataLines.length > 0) {\n controller.enqueue({\n event: eventBuffer.event || \"message\",\n data: dataLines.join(\"\\n\"),\n id: eventBuffer.id,\n retry: eventBuffer.retry,\n });\n }\n },\n });\n }\n}\n\nconst isDataChunk = (\n chunk: UIMessageStreamChunk,\n): chunk is UIMessageStreamDataChunk => chunk.type.startsWith(\"data-\");\n\n/**\n * Decodes AI SDK v6 UI Message Stream format into AssistantStreamChunks.\n */\nexport class UIMessageStreamDecoder extends PipeableTransformStream<\n Uint8Array<ArrayBuffer>,\n AssistantStreamChunk\n> {\n constructor(options: UIMessageStreamDecoderOptions = {}) {\n super((readable) => {\n const toolCallControllers = new Map<string, ToolCallStreamController>();\n let activeToolCallArgsText: TextStreamController | undefined;\n let currentMessageId: string | undefined;\n let receivedDone = false;\n\n const transform = new AssistantTransformStream<UIMessageStreamChunk>({\n transform(chunk, controller) {\n const type = chunk.type;\n\n if (isDataChunk(chunk)) {\n const name = chunk.type.slice(5);\n\n if (options.onData) {\n options.onData({\n type: chunk.type,\n name,\n data: chunk.data,\n ...(chunk.transient !== undefined && {\n transient: chunk.transient,\n }),\n });\n }\n\n if (!chunk.transient) {\n controller.enqueue({\n type: \"data\",\n path: [],\n data: [{ name, data: chunk.data }],\n });\n }\n return;\n }\n\n switch (type) {\n case \"start\":\n currentMessageId = chunk.messageId;\n controller.enqueue({\n type: \"step-start\",\n path: [],\n messageId: chunk.messageId,\n });\n break;\n\n case \"text-start\":\n case \"text-end\":\n case \"reasoning-start\":\n case \"reasoning-end\":\n break;\n\n case \"text-delta\":\n controller.appendText(chunk.textDelta);\n break;\n\n case \"reasoning-delta\":\n controller.appendReasoning(chunk.delta);\n break;\n\n case \"source\":\n controller.appendSource({\n type: \"source\",\n sourceType: chunk.source.sourceType,\n id: chunk.source.id,\n url: chunk.source.url,\n ...(chunk.source.title && { title: chunk.source.title }),\n });\n break;\n\n case \"file\":\n controller.appendFile({\n type: \"file\",\n mimeType: chunk.file.mimeType,\n data: chunk.file.data,\n });\n break;\n\n case \"tool-call-start\": {\n activeToolCallArgsText?.close();\n activeToolCallArgsText = undefined;\n\n if (toolCallControllers.has(chunk.toolCallId)) {\n throw new Error(\n `Encountered duplicate tool call id: ${chunk.toolCallId}`,\n );\n }\n\n const toolCallController = controller.addToolCallPart({\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n });\n toolCallControllers.set(chunk.toolCallId, toolCallController);\n activeToolCallArgsText = toolCallController.argsText;\n break;\n }\n\n case \"tool-call-delta\":\n activeToolCallArgsText?.append(chunk.argsText);\n break;\n\n case \"tool-call-end\":\n activeToolCallArgsText?.close();\n activeToolCallArgsText = undefined;\n break;\n\n case \"tool-result\": {\n const toolCallController = toolCallControllers.get(\n chunk.toolCallId,\n );\n if (!toolCallController) {\n throw new Error(\n `Encountered tool result with unknown id: ${chunk.toolCallId}`,\n );\n }\n toolCallController.setResponse({\n result: chunk.result,\n isError: chunk.isError ?? false,\n ...(chunk.messages !== undefined\n ? { messages: chunk.messages }\n : {}),\n });\n break;\n }\n\n case \"start-step\":\n controller.enqueue({\n type: \"step-start\",\n path: [],\n messageId: chunk.messageId ?? currentMessageId ?? generateId(),\n });\n break;\n\n case \"finish-step\":\n controller.enqueue({\n type: \"step-finish\",\n path: [],\n finishReason: chunk.finishReason,\n usage: chunk.usage,\n isContinued: chunk.isContinued,\n });\n break;\n\n case \"finish\":\n controller.enqueue({\n type: \"message-finish\",\n path: [],\n finishReason: chunk.finishReason,\n usage: chunk.usage,\n });\n break;\n\n case \"error\":\n controller.enqueue({\n type: \"error\",\n path: [],\n error: chunk.errorText,\n });\n break;\n\n default:\n // ignore unknown types for forward compatibility\n break;\n }\n },\n flush() {\n activeToolCallArgsText?.close();\n // biome-ignore lint/suspicious/useIterableCallbackReturn: forEach callback intentionally has no return\n toolCallControllers.forEach((ctrl) => ctrl.close());\n toolCallControllers.clear();\n },\n });\n\n return readable\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new LineDecoderStream())\n .pipeThrough(new SSEEventStream())\n .pipeThrough(\n new TransformStream<SSEEvent, UIMessageStreamChunk>({\n transform(event, controller) {\n if (event.event !== \"message\") {\n throw new Error(`Unknown SSE event type: ${event.event}`);\n }\n\n if (event.data === \"[DONE]\") {\n receivedDone = true;\n controller.terminate();\n return;\n }\n\n controller.enqueue(JSON.parse(event.data));\n },\n flush() {\n if (!receivedDone) {\n throw new Error(\n \"Stream ended abruptly without receiving [DONE] marker\",\n );\n }\n },\n }),\n )\n .pipeThrough(transform);\n });\n }\n}\n"],"mappings":";;;;;AA8BA,IAAM,iBAAN,cAA6B,gBAAkC;CAC7D,cAAc;EACZ,IAAI,cAAiC,CAAC;EACtC,IAAI,YAAsB,CAAC;EAE3B,MAAM;GACJ,QAAQ;IACN,cAAc,CAAC;IACf,YAAY,CAAC;GACf;GACA,UAAU,MAAM,YAAY;IAC1B,IAAI,KAAK,WAAW,GAAG,GAAG;IAE1B,IAAI,SAAS,IAAI;KACf,IAAI,UAAU,SAAS,GACrB,WAAW,QAAQ;MACjB,OAAO,YAAY,SAAS;MAC5B,MAAM,UAAU,KAAK,IAAI;MACzB,IAAI,YAAY;MAChB,OAAO,YAAY;KACrB,CAAC;KAEH,cAAc,CAAC;KACf,YAAY,CAAC;KACb;IACF;IAEA,MAAM,CAAC,OAAO,GAAG,QAAQ,KAAK,MAAM,GAAG;IACvC,MAAM,QAAQ,KAAK,KAAK,GAAG,EAAE,UAAU;IAEvC,QAAQ,OAAR;KACE,KAAK;MACH,YAAY,QAAQ;MACpB;KACF,KAAK;MACH,UAAU,KAAK,KAAK;MACpB;KACF,KAAK;MACH,YAAY,KAAK;MACjB;KACF,KAAK;MACH,YAAY,QAAQ,OAAO,KAAK;MAChC;IACJ;GACF;GACA,MAAM,YAAY;IAChB,IAAI,UAAU,SAAS,GACrB,WAAW,QAAQ;KACjB,OAAO,YAAY,SAAS;KAC5B,MAAM,UAAU,KAAK,IAAI;KACzB,IAAI,YAAY;KAChB,OAAO,YAAY;IACrB,CAAC;GAEL;EACF,CAAC;CACH;AACF;AAEA,MAAM,eACJ,UACsC,MAAM,KAAK,WAAW,OAAO;;;;AAKrE,IAAa,yBAAb,cAA4C,wBAG1C;CACA,YAAY,UAAyC,CAAC,GAAG;EACvD,OAAO,aAAa;GAClB,MAAM,sCAAsB,IAAI,IAAsC;GACtE,IAAI;GAC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;IAClD,UAAU,OAAO,YAAY;KAC3B,IAAI,MAAM,UAAU,WAClB,MAAM,IAAI,MAAM,2BAA2B,MAAM,OAAO;KAG1D,IAAI,MAAM,SAAS,UAAU;MAC3B,eAAe;MACf,WAAW,UAAU;MACrB;KACF;KAEA,WAAW,QAAQ,KAAK,MAAM,MAAM,IAAI,CAAC;IAC3C;IACA,QAAQ;KACN,IAAI,CAAC,cACH,MAAM,IAAI,MACR,uDACF;IAEJ;GACF,CAAC,CACH,EACC,YAAY,SAAS;EAC1B,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"UIMessageStream.js","names":[],"sources":["../../../../src/core/serialization/ui-message-stream/UIMessageStream.ts"],"sourcesContent":["import type { AssistantStreamChunk } from \"../../AssistantStreamChunk\";\nimport type { ToolCallStreamController } from \"../../modules/tool-call\";\nimport type { TextStreamController } from \"../../modules/text\";\nimport { AssistantTransformStream } from \"../../utils/stream/AssistantTransformStream\";\nimport { PipeableTransformStream } from \"../../utils/stream/PipeableTransformStream\";\nimport { LineDecoderStream } from \"../../utils/stream/LineDecoderStream\";\nimport type {\n UIMessageStreamChunk,\n UIMessageStreamDataChunk,\n} from \"./chunk-types\";\nimport { generateId } from \"../../utils/generateId\";\n\nexport type { UIMessageStreamChunk, UIMessageStreamDataChunk };\n\nexport type UIMessageStreamDecoderOptions = {\n onData?: (data: {\n type: string;\n name: string;\n data: unknown;\n transient?: boolean;\n }) => void;\n};\n\ntype SSEEvent = {\n event: string;\n data: string;\n id?: string | undefined;\n retry?: number | undefined;\n};\n\nclass SSEEventStream extends TransformStream<string, SSEEvent> {\n constructor() {\n let eventBuffer: Partial<SSEEvent> = {};\n let dataLines: string[] = [];\n\n super({\n start() {\n eventBuffer = {};\n dataLines = [];\n },\n transform(line, controller) {\n if (line.startsWith(\":\")) return;\n\n if (line === \"\") {\n if (dataLines.length > 0) {\n controller.enqueue({\n event: eventBuffer.event || \"message\",\n data: dataLines.join(\"\\n\"),\n id: eventBuffer.id,\n retry: eventBuffer.retry,\n });\n }\n eventBuffer = {};\n dataLines = [];\n return;\n }\n\n const [field, ...rest] = line.split(\":\");\n const value = rest.join(\":\").trimStart();\n\n switch (field) {\n case \"event\":\n eventBuffer.event = value;\n break;\n case \"data\":\n dataLines.push(value);\n break;\n case \"id\":\n eventBuffer.id = value;\n break;\n case \"retry\":\n eventBuffer.retry = Number(value);\n break;\n }\n },\n flush(controller) {\n if (dataLines.length > 0) {\n controller.enqueue({\n event: eventBuffer.event || \"message\",\n data: dataLines.join(\"\\n\"),\n id: eventBuffer.id,\n retry: eventBuffer.retry,\n });\n }\n },\n });\n }\n}\n\nconst isDataChunk = (\n chunk: UIMessageStreamChunk,\n): chunk is UIMessageStreamDataChunk => chunk.type.startsWith(\"data-\");\n\n/**\n * Decodes AI SDK v6 UI Message Stream format into AssistantStreamChunks.\n */\nexport class UIMessageStreamDecoder extends PipeableTransformStream<\n Uint8Array<ArrayBuffer>,\n AssistantStreamChunk\n> {\n constructor(options: UIMessageStreamDecoderOptions = {}) {\n super((readable) => {\n const toolCallControllers = new Map<string, ToolCallStreamController>();\n let activeToolCallArgsText: TextStreamController | undefined;\n let currentMessageId: string | undefined;\n let receivedDone = false;\n\n const transform = new AssistantTransformStream<UIMessageStreamChunk>({\n transform(chunk, controller) {\n const type = chunk.type;\n\n if (isDataChunk(chunk)) {\n const name = chunk.type.slice(5);\n\n if (options.onData) {\n options.onData({\n type: chunk.type,\n name,\n data: chunk.data,\n ...(chunk.transient !== undefined && {\n transient: chunk.transient,\n }),\n });\n }\n\n if (!chunk.transient) {\n controller.enqueue({\n type: \"data\",\n path: [],\n data: [{ name, data: chunk.data }],\n });\n }\n return;\n }\n\n switch (type) {\n case \"start\":\n currentMessageId = chunk.messageId;\n controller.enqueue({\n type: \"step-start\",\n path: [],\n messageId: chunk.messageId,\n });\n break;\n\n case \"text-start\":\n case \"text-end\":\n case \"reasoning-start\":\n case \"reasoning-end\":\n break;\n\n case \"text-delta\":\n controller.appendText(chunk.textDelta);\n break;\n\n case \"reasoning-delta\":\n controller.appendReasoning(chunk.delta);\n break;\n\n case \"source\":\n controller.appendSource({\n type: \"source\",\n sourceType: chunk.source.sourceType,\n id: chunk.source.id,\n url: chunk.source.url,\n ...(chunk.source.title && { title: chunk.source.title }),\n });\n break;\n\n case \"file\":\n controller.appendFile({\n type: \"file\",\n mimeType: chunk.file.mimeType,\n data: chunk.file.data,\n });\n break;\n\n case \"tool-call-start\": {\n activeToolCallArgsText?.close();\n activeToolCallArgsText = undefined;\n\n if (toolCallControllers.has(chunk.toolCallId)) {\n throw new Error(\n `Encountered duplicate tool call id: ${chunk.toolCallId}`,\n );\n }\n\n const toolCallController = controller.addToolCallPart({\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n });\n toolCallControllers.set(chunk.toolCallId, toolCallController);\n activeToolCallArgsText = toolCallController.argsText;\n break;\n }\n\n case \"tool-call-delta\":\n activeToolCallArgsText?.append(chunk.argsText);\n break;\n\n case \"tool-call-end\":\n activeToolCallArgsText?.close();\n activeToolCallArgsText = undefined;\n break;\n\n case \"tool-result\": {\n const toolCallController = toolCallControllers.get(\n chunk.toolCallId,\n );\n if (!toolCallController) {\n throw new Error(\n `Encountered tool result with unknown id: ${chunk.toolCallId}`,\n );\n }\n toolCallController.setResponse({\n result: chunk.result,\n isError: chunk.isError ?? false,\n ...(chunk.messages !== undefined\n ? { messages: chunk.messages }\n : {}),\n });\n break;\n }\n\n case \"start-step\":\n controller.enqueue({\n type: \"step-start\",\n path: [],\n messageId: chunk.messageId ?? currentMessageId ?? generateId(),\n });\n break;\n\n case \"finish-step\":\n controller.enqueue({\n type: \"step-finish\",\n path: [],\n finishReason: chunk.finishReason,\n usage: chunk.usage,\n isContinued: chunk.isContinued,\n });\n break;\n\n case \"finish\":\n controller.enqueue({\n type: \"message-finish\",\n path: [],\n finishReason: chunk.finishReason,\n usage: chunk.usage,\n });\n break;\n\n case \"error\":\n controller.enqueue({\n type: \"error\",\n path: [],\n error: chunk.errorText,\n });\n break;\n\n default:\n // ignore unknown types for forward compatibility\n break;\n }\n },\n flush() {\n activeToolCallArgsText?.close();\n toolCallControllers.forEach((ctrl) => ctrl.close());\n toolCallControllers.clear();\n },\n });\n\n return readable\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new LineDecoderStream())\n .pipeThrough(new SSEEventStream())\n .pipeThrough(\n new TransformStream<SSEEvent, UIMessageStreamChunk>({\n transform(event, controller) {\n if (event.event !== \"message\") {\n throw new Error(`Unknown SSE event type: ${event.event}`);\n }\n\n if (event.data === \"[DONE]\") {\n receivedDone = true;\n controller.terminate();\n return;\n }\n\n controller.enqueue(JSON.parse(event.data));\n },\n flush() {\n if (!receivedDone) {\n throw new Error(\n \"Stream ended abruptly without receiving [DONE] marker\",\n );\n }\n },\n }),\n )\n .pipeThrough(transform);\n });\n }\n}\n"],"mappings":";;;;;AA8BA,IAAM,iBAAN,cAA6B,gBAAkC;CAC7D,cAAc;EACZ,IAAI,cAAiC,CAAC;EACtC,IAAI,YAAsB,CAAC;EAE3B,MAAM;GACJ,QAAQ;IACN,cAAc,CAAC;IACf,YAAY,CAAC;GACf;GACA,UAAU,MAAM,YAAY;IAC1B,IAAI,KAAK,WAAW,GAAG,GAAG;IAE1B,IAAI,SAAS,IAAI;KACf,IAAI,UAAU,SAAS,GACrB,WAAW,QAAQ;MACjB,OAAO,YAAY,SAAS;MAC5B,MAAM,UAAU,KAAK,IAAI;MACzB,IAAI,YAAY;MAChB,OAAO,YAAY;KACrB,CAAC;KAEH,cAAc,CAAC;KACf,YAAY,CAAC;KACb;IACF;IAEA,MAAM,CAAC,OAAO,GAAG,QAAQ,KAAK,MAAM,GAAG;IACvC,MAAM,QAAQ,KAAK,KAAK,GAAG,EAAE,UAAU;IAEvC,QAAQ,OAAR;KACE,KAAK;MACH,YAAY,QAAQ;MACpB;KACF,KAAK;MACH,UAAU,KAAK,KAAK;MACpB;KACF,KAAK;MACH,YAAY,KAAK;MACjB;KACF,KAAK;MACH,YAAY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;QACP,cAAc,MAAM;QACpB,OAAO,MAAM;OACf,CAAC;OACD;MAEF,KAAK;OACH,WAAW,QAAQ;QACjB,MAAM;QACN,MAAM,CAAC;QACP,OAAO,MAAM;OACf,CAAC;OACD;MAEF,SAEE;KACJ;IACF;IACA,QAAQ;KACN,wBAAwB,MAAM;KAC9B,oBAAoB,SAAS,SAAS,KAAK,MAAM,CAAC;KAClD,oBAAoB,MAAM;IAC5B;GACF,CAAC;GAED,OAAO,SACJ,YAAY,IAAI,kBAAkB,CAAC,EACnC,YAAY,IAAI,kBAAkB,CAAC,EACnC,YAAY,IAAI,eAAe,CAAC,EAChC,YACC,IAAI,gBAAgD;IAClD,UAAU,OAAO,YAAY;KAC3B,IAAI,MAAM,UAAU,WAClB,MAAM,IAAI,MAAM,2BAA2B,MAAM,OAAO;KAG1D,IAAI,MAAM,SAAS,UAAU;MAC3B,eAAe;MACf,WAAW,UAAU;MACrB;KACF;KAEA,WAAW,QAAQ,KAAK,MAAM,MAAM,IAAI,CAAC;IAC3C;IACA,QAAQ;KACN,IAAI,CAAC,cACH,MAAM,IAAI,MACR,uDACF;IAEJ;GACF,CAAC,CACH,EACC,YAAY,SAAS;EAC1B,CAAC;CACH;AACF"}
|
|
@@ -12,7 +12,7 @@ declare class ToolCallArgsReaderImpl<T extends ReadonlyJSONObject> implements To
|
|
|
12
12
|
private processStream;
|
|
13
13
|
get<PathT extends TypePath<T>>(...fieldPath: PathT): Promise<TypeAtPath<T, PathT>>;
|
|
14
14
|
streamValues<PathT extends TypePath<T>>(...fieldPath: PathT): AsyncIterableStream<DeepPartial<TypeAtPath<T, PathT>>>;
|
|
15
|
-
streamText<PathT extends TypePath<T>>(...fieldPath: PathT): TypeAtPath<T, PathT> extends string & infer U ? AsyncIterableStream<U> : never;
|
|
15
|
+
streamText<PathT extends TypePath<T>>(...fieldPath: PathT): TypeAtPath<T, PathT> extends string & (infer U) ? AsyncIterableStream<U> : never;
|
|
16
16
|
forEach<PathT extends TypePath<T>>(...fieldPath: PathT): TypeAtPath<T, PathT> extends Array<infer U> ? AsyncIterableStream<U> : never;
|
|
17
17
|
}
|
|
18
18
|
declare class ToolCallResponseReaderImpl<TResult extends ReadonlyJSONValue> implements ToolCallResponseReader<TResult> {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolCallReader.d.ts","names":[],"sources":["../../../src/core/tool/ToolCallReader.ts"],"mappings":";;;;;;cA0Oa,sBAAA,
|
|
1
|
+
{"version":3,"file":"ToolCallReader.d.ts","names":[],"sources":["../../../src/core/tool/ToolCallReader.ts"],"mappings":";;;;;;cA0Oa,sBAAA,WACD,kBAAA,aACC,kBAAA,CAAmB,CAAA;EAAA,QACtB,aAAA;EAAA,QACA,OAAA;EAAA,QACA,IAAA;cAEI,aAAA,EAAe,cAAA;EAAA,QAKb,aAAA;EA6Bd,GAAA,eAAkB,QAAA,CAAS,CAAA,MACtB,SAAA,EAAW,KAAA,GACb,OAAA,CAAQ,UAAA,CAAW,CAAA,EAAG,KAAA;EA4BzB,YAAA,eAA2B,QAAA,CAAS,CAAA,MAC/B,SAAA,EAAW,KAAA,GACb,mBAAA,CAAoB,WAAA,CAAY,UAAA,CAAW,CAAA,EAAG,KAAA;EA2BjD,UAAA,eAAyB,QAAA,CAAS,CAAA,MAC7B,SAAA,EAAW,KAAA,GACb,UAAA,CAAW,CAAA,EAAG,KAAA,+BACb,mBAAA,CAAoB,CAAA;EA4BxB,OAAA,eAAsB,QAAA,CAAS,CAAA,MAC1B,SAAA,EAAW,KAAA,GACb,UAAA,CAAW,CAAA,EAAG,KAAA,UAAe,KAAA,YAC5B,mBAAA,CAAoB,CAAA;AAAA;AAAA,cA6Bb,0BAAA,iBACK,iBAAA,aACL,sBAAA,CAAuB,OAAA;EAAA,iBACL,OAAA;cAAA,OAAA,EAAS,OAAA,CAAQ,YAAA,CAAa,OAAA;EAEpD,GAAA,IAAG,OAAA,CAAA,YAAA,CAAA,OAAA;AAAA;AAAA,cAKC,kBAAA,eACG,kBAAA,kBACE,iBAAA,aACL,cAAA,CAAe,KAAA,EAAO,OAAA;EAAA,SACjB,IAAA,EAAM,sBAAA,CAAuB,KAAA;EAAA,SAC7B,QAAA,EAAU,0BAAA,CAA2B,OAAA;EAAA,iBACpC,QAAA;EAAA,iBACA,OAAA;EAEV,QAAA;;EAYD,mBAAA,CAAoB,IAAA,WAAe,OAAA;EAazC,WAAA,CAAY,KAAA,EAAO,YAAA,CAAa,OAAA;EAIhC,MAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolCallReader.js","names":[],"sources":["../../../src/core/tool/ToolCallReader.ts"],"sourcesContent":["import { promiseWithResolvers } from \"../../utils/promiseWithResolvers\";\nimport {\n parsePartialJsonObject,\n getPartialJsonObjectFieldState,\n} from \"../../utils/json/parse-partial-json-object\";\nimport type {\n ToolCallArgsReader,\n ToolCallReader,\n ToolCallResponseReader,\n} from \"./tool-types\";\nimport type { DeepPartial, TypeAtPath, TypePath } from \"./type-path-utils\";\nimport type { ToolResponse } from \"./ToolResponse\";\nimport { asAsyncIterableStream } from \"../../utils/AsyncIterableStream\";\nimport type {\n AsyncIterableStream,\n ReadonlyJSONObject,\n ReadonlyJSONValue,\n} from \"../../utils\";\n\n// TODO: remove dispose\n\nfunction getField<T>(obj: T, fieldPath: (string | number)[]): unknown {\n let current: unknown = obj;\n for (const key of fieldPath) {\n if (current === undefined || current === null) {\n return undefined;\n }\n current = current[key as keyof typeof current];\n }\n return current;\n}\n\ninterface Handle {\n update(args: unknown): void;\n dispose(): void;\n}\n\nclass GetHandle<T, TValue> implements Handle {\n private resolve: (value: TValue) => void;\n private reject: (reason: unknown) => void;\n private disposed = false;\n private fieldPath: (string | number)[];\n\n constructor(\n resolve: (value: TValue) => void,\n reject: (reason: unknown) => void,\n fieldPath: (string | number)[],\n ) {\n this.resolve = resolve;\n this.reject = reject;\n this.fieldPath = fieldPath;\n }\n\n update(args: unknown): void {\n if (this.disposed) return;\n\n try {\n // Check if the field is complete\n if (\n getPartialJsonObjectFieldState(\n args as Record<string, unknown>,\n this.fieldPath,\n ) === \"complete\"\n ) {\n const value = getField(args as T, this.fieldPath);\n if (value !== undefined) {\n this.resolve(value as TValue);\n this.dispose();\n }\n }\n } catch (e) {\n this.reject(e);\n this.dispose();\n }\n }\n\n dispose(): void {\n this.disposed = true;\n }\n}\n\nclass StreamValuesHandle<T> implements Handle {\n private controller: ReadableStreamDefaultController<unknown>;\n private disposed = false;\n private fieldPath: (string | number)[];\n\n constructor(\n controller: ReadableStreamDefaultController<unknown>,\n fieldPath: (string | number)[],\n ) {\n this.controller = controller;\n this.fieldPath = fieldPath;\n }\n\n update(args: unknown): void {\n if (this.disposed) return;\n\n try {\n const value = getField(args as T, this.fieldPath);\n\n if (value !== undefined) {\n this.controller.enqueue(value);\n }\n\n // Check if the field is complete, if so close the stream\n if (\n getPartialJsonObjectFieldState(\n args as Record<string, unknown>,\n this.fieldPath,\n ) === \"complete\"\n ) {\n this.controller.close();\n this.dispose();\n }\n } catch (e) {\n this.controller.error(e);\n this.dispose();\n }\n }\n\n dispose(): void {\n this.disposed = true;\n }\n}\n\nclass StreamTextHandle<T> implements Handle {\n private controller: ReadableStreamDefaultController<unknown>;\n private disposed = false;\n private fieldPath: (string | number)[];\n private lastValue: string | undefined = undefined;\n\n constructor(\n controller: ReadableStreamDefaultController<unknown>,\n fieldPath: (string | number)[],\n ) {\n this.controller = controller;\n this.fieldPath = fieldPath;\n }\n\n update(args: unknown): void {\n if (this.disposed) return;\n\n try {\n const value = getField(args as T, this.fieldPath);\n\n if (value !== undefined && typeof value === \"string\") {\n const delta = value.substring(this.lastValue?.length || 0);\n this.lastValue = value;\n this.controller.enqueue(delta);\n }\n\n // Check if the field is complete, if so close the stream\n if (\n getPartialJsonObjectFieldState(\n args as Record<string, unknown>,\n this.fieldPath,\n ) === \"complete\"\n ) {\n this.controller.close();\n this.dispose();\n }\n } catch (e) {\n this.controller.error(e);\n this.dispose();\n }\n }\n\n dispose(): void {\n this.disposed = true;\n }\n}\n\nclass ForEachHandle<T> implements Handle {\n private controller: ReadableStreamDefaultController<unknown>;\n private disposed = false;\n private fieldPath: (string | number)[];\n private processedIndexes = new Set<number>();\n\n constructor(\n controller: ReadableStreamDefaultController<unknown>,\n fieldPath: (string | number)[],\n ) {\n this.controller = controller;\n this.fieldPath = fieldPath;\n }\n\n update(args: unknown): void {\n if (this.disposed) return;\n\n try {\n const array = getField(args as T, this.fieldPath);\n\n if (!Array.isArray(array)) {\n return;\n }\n\n // Check each array element and emit completed ones that haven't been processed\n for (let i = 0; i < array.length; i++) {\n if (!this.processedIndexes.has(i)) {\n const elementPath = [...this.fieldPath, i];\n if (\n getPartialJsonObjectFieldState(\n args as Record<string, unknown>,\n elementPath,\n ) === \"complete\"\n ) {\n this.controller.enqueue(array[i]);\n this.processedIndexes.add(i);\n }\n }\n }\n\n // Check if the entire array is complete\n if (\n getPartialJsonObjectFieldState(\n args as Record<string, unknown>,\n this.fieldPath,\n ) === \"complete\"\n ) {\n this.controller.close();\n this.dispose();\n }\n } catch (e) {\n this.controller.error(e);\n this.dispose();\n }\n }\n\n dispose(): void {\n this.disposed = true;\n }\n}\n\n// Implementation of ToolCallReader that uses stream of partial JSON\nexport class ToolCallArgsReaderImpl<T extends ReadonlyJSONObject>\n implements ToolCallArgsReader<T>\n{\n private argTextDeltas: ReadableStream<string>;\n private handles: Set<Handle> = new Set();\n private args: unknown = parsePartialJsonObject(\"\");\n\n constructor(argTextDeltas: ReadableStream<string>) {\n this.argTextDeltas = argTextDeltas;\n this.processStream();\n }\n\n private async processStream(): Promise<void> {\n try {\n let accumulatedText = \"\";\n const reader = this.argTextDeltas.getReader();\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n\n accumulatedText += value;\n const parsedArgs = parsePartialJsonObject(accumulatedText);\n\n if (parsedArgs !== undefined) {\n this.args = parsedArgs;\n // Notify all handles of the updated args\n for (const handle of this.handles) {\n handle.update(parsedArgs);\n }\n }\n }\n } catch (error) {\n console.error(\"Error processing argument stream:\", error);\n // Notify handles of the error\n for (const handle of this.handles) {\n handle.dispose();\n }\n }\n }\n\n get<PathT extends TypePath<T>>(\n ...fieldPath: PathT\n ): Promise<TypeAtPath<T, PathT>> {\n return new Promise<TypeAtPath<T, PathT>>((resolve, reject) => {\n const handle = new GetHandle<T, TypeAtPath<T, PathT>>(\n resolve,\n reject,\n fieldPath,\n );\n\n // Check if the field is already complete in current args\n if (\n this.args &&\n getPartialJsonObjectFieldState(\n this.args as Record<string, unknown>,\n fieldPath,\n ) === \"complete\"\n ) {\n const value = getField(this.args as T, fieldPath);\n if (value !== undefined) {\n resolve(value as TypeAtPath<T, PathT>);\n return;\n }\n }\n\n this.handles.add(handle);\n handle.update(this.args);\n });\n }\n\n streamValues<PathT extends TypePath<T>>(\n ...fieldPath: PathT\n ): AsyncIterableStream<DeepPartial<TypeAtPath<T, PathT>>> {\n // Use a type assertion to convert the complex TypePath to a simple array\n const simplePath = fieldPath as unknown as (string | number)[];\n\n const stream = new ReadableStream<DeepPartial<TypeAtPath<T, PathT>>>({\n start: (controller) => {\n const handle = new StreamValuesHandle<T>(controller, simplePath);\n this.handles.add(handle);\n\n // Check current args immediately\n handle.update(this.args);\n },\n cancel: () => {\n // Find and dispose the corresponding handle\n for (const handle of this.handles) {\n if (handle instanceof StreamValuesHandle) {\n handle.dispose();\n this.handles.delete(handle);\n break;\n }\n }\n },\n });\n\n return asAsyncIterableStream(stream) as any;\n }\n\n streamText<PathT extends TypePath<T>>(\n ...fieldPath: PathT\n ): TypeAtPath<T, PathT> extends string & infer U\n ? AsyncIterableStream<U>\n : never {\n // Use a type assertion to convert the complex TypePath to a simple array\n const simplePath = fieldPath as unknown as (string | number)[];\n\n const stream = new ReadableStream<unknown>({\n start: (controller) => {\n const handle = new StreamTextHandle<T>(controller, simplePath);\n this.handles.add(handle);\n\n // Check current args immediately\n handle.update(this.args);\n },\n cancel: () => {\n // Find and dispose the corresponding handle\n for (const handle of this.handles) {\n if (handle instanceof StreamTextHandle) {\n handle.dispose();\n this.handles.delete(handle);\n break;\n }\n }\n },\n });\n\n return asAsyncIterableStream(stream) as any;\n }\n\n forEach<PathT extends TypePath<T>>(\n ...fieldPath: PathT\n ): TypeAtPath<T, PathT> extends Array<infer U>\n ? AsyncIterableStream<U>\n : never {\n // Use a type assertion to convert the complex TypePath to a simple array\n const simplePath = fieldPath as unknown as (string | number)[];\n\n const stream = new ReadableStream<unknown>({\n start: (controller) => {\n const handle = new ForEachHandle<T>(controller, simplePath);\n this.handles.add(handle);\n\n // Check current args immediately\n handle.update(this.args);\n },\n cancel: () => {\n // Find and dispose the corresponding handle\n for (const handle of this.handles) {\n if (handle instanceof ForEachHandle) {\n handle.dispose();\n this.handles.delete(handle);\n break;\n }\n }\n },\n });\n\n return asAsyncIterableStream(stream) as any;\n }\n}\n\nexport class ToolCallResponseReaderImpl<TResult extends ReadonlyJSONValue>\n implements ToolCallResponseReader<TResult>\n{\n constructor(private readonly promise: Promise<ToolResponse<TResult>>) {}\n\n public get() {\n return this.promise;\n }\n}\n\nexport class ToolCallReaderImpl<\n TArgs extends ReadonlyJSONObject,\n TResult extends ReadonlyJSONValue,\n> implements ToolCallReader<TArgs, TResult>\n{\n public readonly args: ToolCallArgsReaderImpl<TArgs>;\n public readonly response: ToolCallResponseReaderImpl<TResult>;\n private readonly writable: WritableStream<string>;\n private readonly resolve: (value: ToolResponse<TResult>) => void;\n\n public argsText: string = \"\";\n\n constructor() {\n const stream = new TransformStream<string, string>();\n this.writable = stream.writable;\n this.args = new ToolCallArgsReaderImpl<TArgs>(stream.readable);\n\n const { promise, resolve } = promiseWithResolvers<ToolResponse<TResult>>();\n this.resolve = resolve;\n this.response = new ToolCallResponseReaderImpl<TResult>(promise);\n }\n\n async appendArgsTextDelta(text: string): Promise<void> {\n const writer = this.writable.getWriter();\n try {\n await writer.write(text);\n } catch (err) {\n console.warn(err);\n } finally {\n writer.releaseLock();\n }\n\n this.argsText += text;\n }\n\n setResponse(value: ToolResponse<TResult>): void {\n this.resolve(value);\n }\n\n result = {\n get: async () => {\n const response = await this.response.get();\n return response.result;\n },\n };\n}\n"],"mappings":";;;;AAqBA,SAAS,SAAY,KAAQ,WAAyC;CACpE,IAAI,UAAmB;CACvB,KAAK,MAAM,OAAO,WAAW;EAC3B,IAAI,YAAY,KAAA,KAAa,YAAY,MACvC;EAEF,UAAU,QAAQ;CACpB;CACA,OAAO;AACT;AAOA,IAAM,YAAN,MAA6C;CAC3C;CACA;CACA,WAAmB;CACnB;CAEA,YACE,SACA,QACA,WACA;EACA,KAAK,UAAU;EACf,KAAK,SAAS;EACd,KAAK,YAAY;CACnB;CAEA,OAAO,MAAqB;EAC1B,IAAI,KAAK,UAAU;EAEnB,IAAI;GAEF,IACE,+BACE,MACA,KAAK,SACP,MAAM,YACN;IACA,MAAM,QAAQ,SAAS,MAAW,KAAK,SAAS;IAChD,IAAI,UAAU,KAAA,GAAW;KACvB,KAAK,QAAQ,KAAe;KAC5B,KAAK,QAAQ;IACf;GACF;EACF,SAAS,GAAG;GACV,KAAK,OAAO,CAAC;GACb,KAAK,QAAQ;EACf;CACF;CAEA,UAAgB;EACd,KAAK,WAAW;CAClB;AACF;AAEA,IAAM,qBAAN,MAA8C;CAC5C;CACA,WAAmB;CACnB;CAEA,YACE,YACA,WACA;EACA,KAAK,aAAa;EAClB,KAAK,YAAY;CACnB;CAEA,OAAO,MAAqB;EAC1B,IAAI,KAAK,UAAU;EAEnB,IAAI;GACF,MAAM,QAAQ,SAAS,MAAW,KAAK,SAAS;GAEhD,IAAI,UAAU,KAAA,GACZ,KAAK,WAAW,QAAQ,KAAK;GAI/B,IACE,+BACE,MACA,KAAK,SACP,MAAM,YACN;IACA,KAAK,WAAW,MAAM;IACtB,KAAK,QAAQ;GACf;EACF,SAAS,GAAG;GACV,KAAK,WAAW,MAAM,CAAC;GACvB,KAAK,QAAQ;EACf;CACF;CAEA,UAAgB;EACd,KAAK,WAAW;CAClB;AACF;AAEA,IAA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SAAS,YAAY,qBAA4C;EACzE,KAAK,UAAU;EACf,KAAK,WAAW,IAAI,2BAAoC,OAAO;CACjE;CAEA,MAAM,oBAAoB,MAA6B;EACrD,MAAM,SAAS,KAAK,SAAS,UAAU;EACvC,IAAI;GACF,MAAM,OAAO,MAAM,IAAI;EACzB,SAAS,KAAK;GACZ,QAAQ,KAAK,GAAG;EAClB,UAAU;GACR,OAAO,YAAY;EACrB;EAEA,KAAK,YAAY;CACnB;CAEA,YAAY,OAAoC;EAC9C,KAAK,QAAQ,KAAK;CACpB;CAEA,SAAS,EACP,KAAK,YAAY;EAEf,QAAO,MADgB,KAAK,SAAS,IAAI,GACzB;CAClB,EACF;AACF"}
|
|
1
|
+
{"version":3,"file":"ToolCallReader.js","names":[],"sources":["../../../src/core/tool/ToolCallReader.ts"],"sourcesContent":["import { promiseWithResolvers } from \"../../utils/promiseWithResolvers\";\nimport {\n parsePartialJsonObject,\n getPartialJsonObjectFieldState,\n} from \"../../utils/json/parse-partial-json-object\";\nimport type {\n ToolCallArgsReader,\n ToolCallReader,\n ToolCallResponseReader,\n} from \"./tool-types\";\nimport type { DeepPartial, TypeAtPath, TypePath } from \"./type-path-utils\";\nimport type { ToolResponse } from \"./ToolResponse\";\nimport { asAsyncIterableStream } from \"../../utils/AsyncIterableStream\";\nimport type {\n AsyncIterableStream,\n ReadonlyJSONObject,\n ReadonlyJSONValue,\n} from \"../../utils\";\n\n// TODO: remove dispose\n\nfunction getField<T>(obj: T, fieldPath: (string | number)[]): unknown {\n let current: unknown = obj;\n for (const key of fieldPath) {\n if (current === undefined || current === null) {\n return undefined;\n }\n current = current[key as keyof typeof current];\n }\n return current;\n}\n\ninterface Handle {\n update(args: unknown): void;\n dispose(): void;\n}\n\nclass GetHandle<T, TValue> implements Handle {\n private resolve: (value: TValue) => void;\n private reject: (reason: unknown) => void;\n private disposed = false;\n private fieldPath: (string | number)[];\n\n constructor(\n resolve: (value: TValue) => void,\n reject: (reason: unknown) => void,\n fieldPath: (string | number)[],\n ) {\n this.resolve = resolve;\n this.reject = reject;\n this.fieldPath = fieldPath;\n }\n\n update(args: unknown): void {\n if (this.disposed) return;\n\n try {\n // Check if the field is complete\n if (\n getPartialJsonObjectFieldState(\n args as Record<string, unknown>,\n this.fieldPath,\n ) === \"complete\"\n ) {\n const value = getField(args as T, this.fieldPath);\n if (value !== undefined) {\n this.resolve(value as TValue);\n this.dispose();\n }\n }\n } catch (e) {\n this.reject(e);\n this.dispose();\n }\n }\n\n dispose(): void {\n this.disposed = true;\n }\n}\n\nclass StreamValuesHandle<T> implements Handle {\n private controller: ReadableStreamDefaultController<unknown>;\n private disposed = false;\n private fieldPath: (string | number)[];\n\n constructor(\n controller: ReadableStreamDefaultController<unknown>,\n fieldPath: (string | number)[],\n ) {\n this.controller = controller;\n this.fieldPath = fieldPath;\n }\n\n update(args: unknown): void {\n if (this.disposed) return;\n\n try {\n const value = getField(args as T, this.fieldPath);\n\n if (value !== undefined) {\n this.controller.enqueue(value);\n }\n\n // Check if the field is complete, if so close the stream\n if (\n getPartialJsonObjectFieldState(\n args as Record<string, unknown>,\n this.fieldPath,\n ) === \"complete\"\n ) {\n this.controller.close();\n this.dispose();\n }\n } catch (e) {\n this.controller.error(e);\n this.dispose();\n }\n }\n\n dispose(): void {\n this.disposed = true;\n }\n}\n\nclass StreamTextHandle<T> implements Handle {\n private controller: ReadableStreamDefaultController<unknown>;\n private disposed = false;\n private fieldPath: (string | number)[];\n private lastValue: string | undefined = undefined;\n\n constructor(\n controller: ReadableStreamDefaultController<unknown>,\n fieldPath: (string | number)[],\n ) {\n this.controller = controller;\n this.fieldPath = fieldPath;\n }\n\n update(args: unknown): void {\n if (this.disposed) return;\n\n try {\n const value = getField(args as T, this.fieldPath);\n\n if (value !== undefined && typeof value === \"string\") {\n const delta = value.substring(this.lastValue?.length || 0);\n this.lastValue = value;\n this.controller.enqueue(delta);\n }\n\n // Check if the field is complete, if so close the stream\n if (\n getPartialJsonObjectFieldState(\n args as Record<string, unknown>,\n this.fieldPath,\n ) === \"complete\"\n ) {\n this.controller.close();\n this.dispose();\n }\n } catch (e) {\n this.controller.error(e);\n this.dispose();\n }\n }\n\n dispose(): void {\n this.disposed = true;\n }\n}\n\nclass ForEachHandle<T> implements Handle {\n private controller: ReadableStreamDefaultController<unknown>;\n private disposed = false;\n private fieldPath: (string | number)[];\n private processedIndexes = new Set<number>();\n\n constructor(\n controller: ReadableStreamDefaultController<unknown>,\n fieldPath: (string | number)[],\n ) {\n this.controller = controller;\n this.fieldPath = fieldPath;\n }\n\n update(args: unknown): void {\n if (this.disposed) return;\n\n try {\n const array = getField(args as T, this.fieldPath);\n\n if (!Array.isArray(array)) {\n return;\n }\n\n // Check each array element and emit completed ones that haven't been processed\n for (let i = 0; i < array.length; i++) {\n if (!this.processedIndexes.has(i)) {\n const elementPath = [...this.fieldPath, i];\n if (\n getPartialJsonObjectFieldState(\n args as Record<string, unknown>,\n elementPath,\n ) === \"complete\"\n ) {\n this.controller.enqueue(array[i]);\n this.processedIndexes.add(i);\n }\n }\n }\n\n // Check if the entire array is complete\n if (\n getPartialJsonObjectFieldState(\n args as Record<string, unknown>,\n this.fieldPath,\n ) === \"complete\"\n ) {\n this.controller.close();\n this.dispose();\n }\n } catch (e) {\n this.controller.error(e);\n this.dispose();\n }\n }\n\n dispose(): void {\n this.disposed = true;\n }\n}\n\n// Implementation of ToolCallReader that uses stream of partial JSON\nexport class ToolCallArgsReaderImpl<\n T extends ReadonlyJSONObject,\n> implements ToolCallArgsReader<T> {\n private argTextDeltas: ReadableStream<string>;\n private handles: Set<Handle> = new Set();\n private args: unknown = parsePartialJsonObject(\"\");\n\n constructor(argTextDeltas: ReadableStream<string>) {\n this.argTextDeltas = argTextDeltas;\n this.processStream();\n }\n\n private async processStream(): Promise<void> {\n try {\n let accumulatedText = \"\";\n const reader = this.argTextDeltas.getReader();\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n\n accumulatedText += value;\n const parsedArgs = parsePartialJsonObject(accumulatedText);\n\n if (parsedArgs !== undefined) {\n this.args = parsedArgs;\n // Notify all handles of the updated args\n for (const handle of this.handles) {\n handle.update(parsedArgs);\n }\n }\n }\n } catch (error) {\n console.error(\"Error processing argument stream:\", error);\n // Notify handles of the error\n for (const handle of this.handles) {\n handle.dispose();\n }\n }\n }\n\n get<PathT extends TypePath<T>>(\n ...fieldPath: PathT\n ): Promise<TypeAtPath<T, PathT>> {\n return new Promise<TypeAtPath<T, PathT>>((resolve, reject) => {\n const handle = new GetHandle<T, TypeAtPath<T, PathT>>(\n resolve,\n reject,\n fieldPath,\n );\n\n // Check if the field is already complete in current args\n if (\n this.args &&\n getPartialJsonObjectFieldState(\n this.args as Record<string, unknown>,\n fieldPath,\n ) === \"complete\"\n ) {\n const value = getField(this.args as T, fieldPath);\n if (value !== undefined) {\n resolve(value as TypeAtPath<T, PathT>);\n return;\n }\n }\n\n this.handles.add(handle);\n handle.update(this.args);\n });\n }\n\n streamValues<PathT extends TypePath<T>>(\n ...fieldPath: PathT\n ): AsyncIterableStream<DeepPartial<TypeAtPath<T, PathT>>> {\n // Use a type assertion to convert the complex TypePath to a simple array\n const simplePath = fieldPath as unknown as (string | number)[];\n\n const stream = new ReadableStream<DeepPartial<TypeAtPath<T, PathT>>>({\n start: (controller) => {\n const handle = new StreamValuesHandle<T>(controller, simplePath);\n this.handles.add(handle);\n\n // Check current args immediately\n handle.update(this.args);\n },\n cancel: () => {\n // Find and dispose the corresponding handle\n for (const handle of this.handles) {\n if (handle instanceof StreamValuesHandle) {\n handle.dispose();\n this.handles.delete(handle);\n break;\n }\n }\n },\n });\n\n return asAsyncIterableStream(stream) as any;\n }\n\n streamText<PathT extends TypePath<T>>(\n ...fieldPath: PathT\n ): TypeAtPath<T, PathT> extends string & (infer U)\n ? AsyncIterableStream<U>\n : never {\n // Use a type assertion to convert the complex TypePath to a simple array\n const simplePath = fieldPath as unknown as (string | number)[];\n\n const stream = new ReadableStream<unknown>({\n start: (controller) => {\n const handle = new StreamTextHandle<T>(controller, simplePath);\n this.handles.add(handle);\n\n // Check current args immediately\n handle.update(this.args);\n },\n cancel: () => {\n // Find and dispose the corresponding handle\n for (const handle of this.handles) {\n if (handle instanceof StreamTextHandle) {\n handle.dispose();\n this.handles.delete(handle);\n break;\n }\n }\n },\n });\n\n return asAsyncIterableStream(stream) as any;\n }\n\n forEach<PathT extends TypePath<T>>(\n ...fieldPath: PathT\n ): TypeAtPath<T, PathT> extends Array<infer U>\n ? AsyncIterableStream<U>\n : never {\n // Use a type assertion to convert the complex TypePath to a simple array\n const simplePath = fieldPath as unknown as (string | number)[];\n\n const stream = new ReadableStream<unknown>({\n start: (controller) => {\n const handle = new ForEachHandle<T>(controller, simplePath);\n this.handles.add(handle);\n\n // Check current args immediately\n handle.update(this.args);\n },\n cancel: () => {\n // Find and dispose the corresponding handle\n for (const handle of this.handles) {\n if (handle instanceof ForEachHandle) {\n handle.dispose();\n this.handles.delete(handle);\n break;\n }\n }\n },\n });\n\n return asAsyncIterableStream(stream) as any;\n }\n}\n\nexport class ToolCallResponseReaderImpl<\n TResult extends ReadonlyJSONValue,\n> implements ToolCallResponseReader<TResult> {\n constructor(private readonly promise: Promise<ToolResponse<TResult>>) {}\n\n public get() {\n return this.promise;\n }\n}\n\nexport class ToolCallReaderImpl<\n TArgs extends ReadonlyJSONObject,\n TResult extends ReadonlyJSONValue,\n> implements ToolCallReader<TArgs, TResult> {\n public readonly args: ToolCallArgsReaderImpl<TArgs>;\n public readonly response: ToolCallResponseReaderImpl<TResult>;\n private readonly writable: WritableStream<string>;\n private readonly resolve: (value: ToolResponse<TResult>) => void;\n\n public argsText: string = \"\";\n\n constructor() {\n const stream = new TransformStream<string, string>();\n this.writable = stream.writable;\n this.args = new ToolCallArgsReaderImpl<TArgs>(stream.readable);\n\n const { promise, resolve } = promiseWithResolvers<ToolResponse<TResult>>();\n this.resolve = resolve;\n this.response = new ToolCallResponseReaderImpl<TResult>(promise);\n }\n\n async appendArgsTextDelta(text: string): Promise<void> {\n const writer = this.writable.getWriter();\n try {\n await writer.write(text);\n } catch (err) {\n console.warn(err);\n } finally {\n writer.releaseLock();\n }\n\n this.argsText += text;\n }\n\n setResponse(value: ToolResponse<TResult>): void {\n this.resolve(value);\n }\n\n result = {\n get: async () => {\n const response = await this.response.get();\n return response.result;\n },\n };\n}\n"],"mappings":";;;;AAqBA,SAAS,SAAY,KAAQ,WAAyC;CACpE,IAAI,UAAmB;CACvB,KAAK,MAAM,OAAO,WAAW;EAC3B,IAAI,YAAY,KAAA,KAAa,YAAY,MACvC;EAEF,UAAU,QAAQ;CACpB;CACA,OAAO;AACT;AAOA,IAAM,YAAN,MAA6C;CAC3C;CACA;CACA,WAAmB;CACnB;CAEA,YACE,SACA,QACA,WACA;EACA,KAAK,UAAU;EACf,KAAK,SAAS;EACd,KAAK,YAAY;CACnB;CAEA,OAAO,MAAqB;EAC1B,IAAI,KAAK,UAAU;EAEnB,IAAI;GAEF,IACE,+BACE,MACA,KAAK,SACP,MAAM,YACN;IACA,MAAM,QAAQ,SAAS,MAAW,KAAK,SAAS;IAChD,IAAI,UAAU,KAAA,GAAW;KACvB,KAAK,QAAQ,KAAe;KAC5B,KAAK,QAAQ;IACf;GACF;EACF,SAAS,GAAG;GACV,KAAK,OAAO,CAAC;GACb,KAAK,QAAQ;EACf;CACF;CAEA,UAAgB;EACd,KAAK,WAAW;CAClB;AACF;AAEA,IAAM,qBAAN,MAA8C;CAC5C;CACA,WAAmB;CACnB;CAEA,YACE,YACA,WACA;EACA,KAAK,aAAa;EAClB,KAAK,YAAY;CACnB;CAEA,OAAO,MAAqB;EAC1B,IAAI,KAAK,UAAU;EAEnB,IAAI;GACF,MAAM,QAAQ,SAAS,MAAW,KAAK,SAAS;GAEhD,IAAI,UAAU,KAAA,GACZ,KAAK,WAAW,QAAQ,KAAK;GAI/B,IACE,+BACE,MACA,KAAK,SACP,MAAM,YACN;IACA,KAAK,WAAW,MAAM;IACtB,KAAK,QAAQ;GACf;EACF,SAAS,GAAG;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AM,SAAS,IAAI,gBAAgC;EACnD,KAAK,WAAW,OAAO;EACvB,KAAK,OAAO,IAAI,uBAA8B,OAAO,QAAQ;EAE7D,MAAM,EAAE,SAAS,YAAY,qBAA4C;EACzE,KAAK,UAAU;EACf,KAAK,WAAW,IAAI,2BAAoC,OAAO;CACjE;CAEA,MAAM,oBAAoB,MAA6B;EACrD,MAAM,SAAS,KAAK,SAAS,UAAU;EACvC,IAAI;GACF,MAAM,OAAO,MAAM,IAAI;EACzB,SAAS,KAAK;GACZ,QAAQ,KAAK,GAAG;EAClB,UAAU;GACR,OAAO,YAAY;EACrB;EAEA,KAAK,YAAY;CACnB;CAEA,YAAY,OAAoC;EAC9C,KAAK,QAAQ,KAAK;CACpB;CAEA,SAAS,EACP,KAAK,YAAY;EAEf,QAAO,MADgB,KAAK,SAAS,IAAI,GACzB;CAClB,EACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolResponse.d.ts","names":[],"sources":["../../../src/core/tool/ToolResponse.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"ToolResponse.d.ts","names":[],"sources":["../../../src/core/tool/ToolResponse.ts"],"mappings":";;;;cAOM,oBAAA;;AAFgB;;KAOV,gBAAA;EALgD,oCAO1D,MAAA,EAAQ,OAAA;EAFE;;;;;;EASV,QAAA,GAAW,iBAAA,cAWiB;EAT5B,OAAA;EAX2B;;;;;;EAkB3B,YAAA,YAAwB,oBAAA,gBAAA;EAExB,QAAA,GAAW,iBAAA;AAAA;;AAAiB;AAmB9B;;;;;;;;;;;;;;cAAa,YAAA;EAAA,KACN,oBAAA;EAAA,SAII,QAAA,GAAW,iBAAA;EAAA,SACX,MAAA,EAAQ,OAAA;EAAA,SACR,OAAA;EAAA,SACA,YAAA,YAAwB,oBAAA;EAAA,SACxB,QAAA,GAAW,iBAAA;cAER,OAAA,EAAS,gBAAA,CAAiB,OAAA;EAAA,QAc9B,MAAA,CAAO,WAAA,EACb,GAAA,YACC,GAAA,IAAO,YAAA,CAAa,iBAAA;EApBd;;;;;;;EAAA,OAiCF,UAAA,CAAW,MAAA,QAAc,YAAA,QAAoB,YAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolResponse.js","names":[],"sources":["../../../src/core/tool/ToolResponse.ts"],"sourcesContent":["import type { ReadonlyJSONValue } from \"../../utils/json/json-value\";\nimport type {\n ToolModelContentPart,\n ToolModelOutputFunction,\n} from \"./tool-types\";\n\nconst TOOL_RESPONSE_SYMBOL = Symbol.for(\"aui.tool-response\");\n\n/**\n * Shape accepted anywhere a {@link ToolResponse} can be returned.\n */\nexport type ToolResponseLike<TResult> = {\n /** UI-visible tool result value. */\n result: TResult;\n /**\n * Optional UI-only artifact associated with the result.\n *\n * Artifacts are useful for large or structured data that should be available\n * to renderers without necessarily being sent back to the model.\n */\n artifact?: ReadonlyJSONValue | undefined;\n /** Marks the tool result as an error result. */\n isError?: boolean | undefined;\n /**\n * Explicit model-visible content to send back after the tool call.\n *\n * When omitted, assistant-ui derives model output from `result` or a tool's\n * {@link ToolModelOutputFunction}.\n */\n modelContent?: readonly ToolModelContentPart[] | undefined;\n /** Optional provider-specific message payload associated with the tool result. */\n messages?: ReadonlyJSONValue | undefined;\n};\n\n/**\n * Tool result wrapper for separating UI-visible output from model-visible\n * output.\n *\n * Return `ToolResponse` from a tool when you need to attach an artifact, mark\n * the result as an error, or control the content sent back to the model.\n *\n * @example\n * ```ts\n * return new ToolResponse({\n * result: { title: \"Report ready\" },\n * artifact: { reportId },\n * modelContent: [{ type: \"text\", text: \"The report is ready.\" }],\n * });\n * ```\n */\nexport class ToolResponse<TResult> {\n get [TOOL_RESPONSE_SYMBOL]() {\n return true;\n }\n\n readonly artifact?: ReadonlyJSONValue;\n readonly result: TResult;\n readonly isError: boolean;\n readonly modelContent?: readonly ToolModelContentPart[];\n readonly messages?: ReadonlyJSONValue;\n\n constructor(options: ToolResponseLike<TResult>) {\n if (options.artifact !== undefined) {\n this.artifact = options.artifact;\n }\n this.result = options.result;\n this.isError = options.isError ?? false;\n if (options.modelContent !== undefined) {\n this.modelContent = options.modelContent;\n }\n if (options.messages !== undefined) {\n this.messages = options.messages;\n }\n }\n\n static [Symbol.hasInstance](\n obj: unknown,\n ): obj is ToolResponse<ReadonlyJSONValue> {\n return (\n typeof obj === \"object\" && obj !== null && TOOL_RESPONSE_SYMBOL in obj\n );\n }\n\n /**\n * Converts a plain tool return value into a {@link ToolResponse}.\n *\n * Existing `ToolResponse` instances are returned unchanged. `undefined`\n * becomes the string `\"<no result>\"` so downstream protocol chunks always\n * carry a concrete result.\n */\n static toResponse(result: any | ToolResponse<any>): ToolResponse<any> {\n if (result instanceof ToolResponse) {\n return result;\n }\n return new ToolResponse({\n result: result === undefined ? \"<no result>\" : result,\n });\n }\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"ToolResponse.js","names":[],"sources":["../../../src/core/tool/ToolResponse.ts"],"sourcesContent":["import type { ReadonlyJSONValue } from \"../../utils/json/json-value\";\nimport type {\n ToolModelContentPart,\n // oxlint-disable-next-line no-unused-vars -- referenced from JSDoc {@link} below\n ToolModelOutputFunction,\n} from \"./tool-types\";\n\nconst TOOL_RESPONSE_SYMBOL = Symbol.for(\"aui.tool-response\");\n\n/**\n * Shape accepted anywhere a {@link ToolResponse} can be returned.\n */\nexport type ToolResponseLike<TResult> = {\n /** UI-visible tool result value. */\n result: TResult;\n /**\n * Optional UI-only artifact associated with the result.\n *\n * Artifacts are useful for large or structured data that should be available\n * to renderers without necessarily being sent back to the model.\n */\n artifact?: ReadonlyJSONValue | undefined;\n /** Marks the tool result as an error result. */\n isError?: boolean | undefined;\n /**\n * Explicit model-visible content to send back after the tool call.\n *\n * When omitted, assistant-ui derives model output from `result` or a tool's\n * {@link ToolModelOutputFunction}.\n */\n modelContent?: readonly ToolModelContentPart[] | undefined;\n /** Optional provider-specific message payload associated with the tool result. */\n messages?: ReadonlyJSONValue | undefined;\n};\n\n/**\n * Tool result wrapper for separating UI-visible output from model-visible\n * output.\n *\n * Return `ToolResponse` from a tool when you need to attach an artifact, mark\n * the result as an error, or control the content sent back to the model.\n *\n * @example\n * ```ts\n * return new ToolResponse({\n * result: { title: \"Report ready\" },\n * artifact: { reportId },\n * modelContent: [{ type: \"text\", text: \"The report is ready.\" }],\n * });\n * ```\n */\nexport class ToolResponse<TResult> {\n get [TOOL_RESPONSE_SYMBOL]() {\n return true;\n }\n\n readonly artifact?: ReadonlyJSONValue;\n readonly result: TResult;\n readonly isError: boolean;\n readonly modelContent?: readonly ToolModelContentPart[];\n readonly messages?: ReadonlyJSONValue;\n\n constructor(options: ToolResponseLike<TResult>) {\n if (options.artifact !== undefined) {\n this.artifact = options.artifact;\n }\n this.result = options.result;\n this.isError = options.isError ?? false;\n if (options.modelContent !== undefined) {\n this.modelContent = options.modelContent;\n }\n if (options.messages !== undefined) {\n this.messages = options.messages;\n }\n }\n\n static [Symbol.hasInstance](\n obj: unknown,\n ): obj is ToolResponse<ReadonlyJSONValue> {\n return (\n typeof obj === \"object\" && obj !== null && TOOL_RESPONSE_SYMBOL in obj\n );\n }\n\n /**\n * Converts a plain tool return value into a {@link ToolResponse}.\n *\n * Existing `ToolResponse` instances are returned unchanged. `undefined`\n * becomes the string `\"<no result>\"` so downstream protocol chunks always\n * carry a concrete result.\n */\n static toResponse(result: any | ToolResponse<any>): ToolResponse<any> {\n if (result instanceof ToolResponse) {\n return result;\n }\n return new ToolResponse({\n result: result === undefined ? \"<no result>\" : result,\n });\n }\n}\n"],"mappings":";AAOA,MAAM,uBAAuB,OAAO,IAAI,mBAAmB;;;;;;;;;;;;;;;;;AA4C3D,IAAa,eAAb,MAAa,aAAsB;CACjC,KAAK,wBAAwB;EAC3B,OAAO;CACT;CAEA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAoC;EAC9C,IAAI,QAAQ,aAAa,KAAA,GACvB,KAAK,WAAW,QAAQ;EAE1B,KAAK,SAAS,QAAQ;EACtB,KAAK,UAAU,QAAQ,WAAW;EAClC,IAAI,QAAQ,iBAAiB,KAAA,GAC3B,KAAK,eAAe,QAAQ;EAE9B,IAAI,QAAQ,aAAa,KAAA,GACvB,KAAK,WAAW,QAAQ;CAE5B;CAEA,QAAQ,OAAO,aACb,KACwC;EACxC,OACE,OAAO,QAAQ,YAAY,QAAQ,QAAQ,wBAAwB;CAEvE;;;;;;;;CASA,OAAO,WAAW,QAAoD;EACpE,IAAI,kBAAkB,cACpB,OAAO;EAET,OAAO,IAAI,aAAa,EACtB,QAAQ,WAAW,KAAA,IAAY,gBAAgB,OACjD,CAAC;CACH;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { JSONSchema7 } from "../../node_modules/.pnpm/@types_json-schema@7.0.15/node_modules/@types/json-schema/index.js";
|
|
2
|
-
import { Tool } from "./tool-types.js";
|
|
2
|
+
import { ProviderOptions, Tool } from "./tool-types.js";
|
|
3
3
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
4
4
|
|
|
5
5
|
//#region src/core/tool/schema-utils.d.ts
|
|
@@ -9,6 +9,7 @@ import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
|
9
9
|
type ToolJSONSchema = {
|
|
10
10
|
description?: string;
|
|
11
11
|
parameters: JSONSchema7;
|
|
12
|
+
providerOptions?: ProviderOptions;
|
|
12
13
|
};
|
|
13
14
|
type ToToolsJSONSchemaOptions = {
|
|
14
15
|
/**
|
|
@@ -35,6 +36,11 @@ declare function toPartialJSONSchema(schema: JSONSchema7): JSONSchema7;
|
|
|
35
36
|
/**
|
|
36
37
|
* Converts a record of tools to a record of tool definitions with JSON Schema parameters.
|
|
37
38
|
* By default, filters out disabled tools and backend tools.
|
|
39
|
+
*
|
|
40
|
+
* Entries are emitted in alphabetical order so the resulting request body is
|
|
41
|
+
* byte-identical regardless of the order in which tools were registered. This
|
|
42
|
+
* keeps provider prompt caches stable across renders that mount tools in
|
|
43
|
+
* different orders.
|
|
38
44
|
*/
|
|
39
45
|
declare function toToolsJSONSchema(tools: Record<string, Tool> | undefined, options?: ToToolsJSONSchemaOptions): Record<string, ToolJSONSchema>;
|
|
40
46
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-utils.d.ts","names":[],"sources":["../../../src/core/tool/schema-utils.ts"],"mappings":";;;;;;;AAOA;KAAY,cAAA;EACV,WAAA;EACA,UAAA,EAAY,
|
|
1
|
+
{"version":3,"file":"schema-utils.d.ts","names":[],"sources":["../../../src/core/tool/schema-utils.ts"],"mappings":";;;;;;;AAOA;KAAY,cAAA;EACV,WAAA;EACA,UAAA,EAAY,WAAA;EACZ,eAAA,GAAkB,eAAe;AAAA;AAAA,KAGvB,wBAAA;EAHV;;;AAAiC;EAQjC,MAAA,IAAU,IAAA,UAAc,IAAA,EAAM,IAAI;AAAA;;;;;;;;AAAA;AA8CpC;iBAAgB,YAAA,CACd,MAAA,EAAQ,gBAAA,GAAmB,WAAA,GAC1B,WAAA;;;;;iBA+Ca,mBAAA,CAAoB,MAAA,EAAQ,WAAA,GAAc,WAAW;;;;;;;AA/CvD;AA+Cd;;iBA+BgB,iBAAA,CACd,KAAA,EAAO,MAAA,SAAe,IAAA,eACtB,OAAA,GAAS,wBAAA,GACR,MAAA,SAAe,cAAA"}
|
|
@@ -50,13 +50,19 @@ function defaultToolFilter(_name, tool) {
|
|
|
50
50
|
/**
|
|
51
51
|
* Converts a record of tools to a record of tool definitions with JSON Schema parameters.
|
|
52
52
|
* By default, filters out disabled tools and backend tools.
|
|
53
|
+
*
|
|
54
|
+
* Entries are emitted in alphabetical order so the resulting request body is
|
|
55
|
+
* byte-identical regardless of the order in which tools were registered. This
|
|
56
|
+
* keeps provider prompt caches stable across renders that mount tools in
|
|
57
|
+
* different orders.
|
|
53
58
|
*/
|
|
54
59
|
function toToolsJSONSchema(tools, options = {}) {
|
|
55
60
|
if (!tools) return {};
|
|
56
61
|
const filter = options.filter ?? defaultToolFilter;
|
|
57
|
-
return Object.fromEntries(Object.entries(tools).filter(([name, tool]) => filter(name, tool) && tool.parameters).map(([name, tool]) => [name, {
|
|
62
|
+
return Object.fromEntries(Object.entries(tools).filter(([name, tool]) => filter(name, tool) && tool.parameters).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, tool]) => [name, {
|
|
58
63
|
...tool.description && { description: tool.description },
|
|
59
|
-
parameters: toJSONSchema(tool.parameters)
|
|
64
|
+
parameters: toJSONSchema(tool.parameters),
|
|
65
|
+
...tool.providerOptions && { providerOptions: tool.providerOptions }
|
|
60
66
|
}]));
|
|
61
67
|
}
|
|
62
68
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-utils.js","names":[],"sources":["../../../src/core/tool/schema-utils.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Tool } from \"./tool-types\";\n\n/**\n * Type for a tool definition with JSON Schema parameters.\n */\nexport type ToolJSONSchema = {\n description?: string;\n parameters: JSONSchema7;\n};\n\nexport type ToToolsJSONSchemaOptions = {\n /**\n * Filter to determine which tools to include.\n * Defaults to excluding disabled tools and backend tools.\n */\n filter?: (name: string, tool: Tool) => boolean;\n};\n\nfunction isStandardSchema(schema: unknown): schema is StandardSchemaV1 & {\n \"~standard\": StandardSchemaV1[\"~standard\"] & {\n toJSONSchema?: () => unknown;\n jsonSchema?: { input?: () => unknown; output?: () => unknown };\n };\n} {\n return (\n typeof schema === \"object\" &&\n schema !== null &&\n \"~standard\" in schema &&\n typeof (schema as StandardSchemaV1)[\"~standard\"] === \"object\"\n );\n}\n\nfunction hasToJSONSchemaMethod(\n schema: unknown,\n): schema is { toJSONSchema: () => unknown } {\n return (\n typeof schema === \"object\" &&\n schema !== null &&\n \"toJSONSchema\" in schema &&\n typeof (schema as { toJSONSchema: unknown }).toJSONSchema === \"function\"\n );\n}\n\nfunction hasToJSONMethod(schema: unknown): schema is { toJSON: () => unknown } {\n return (\n typeof schema === \"object\" &&\n schema !== null &&\n \"toJSON\" in schema &&\n typeof (schema as { toJSON: unknown }).toJSON === \"function\"\n );\n}\n\n/**\n * Converts a schema to JSONSchema7.\n * Supports:\n * - StandardSchemaV1 with ~standard.toJSONSchema (e.g., Zod v4)\n * - StandardSchemaV1 with ~standard.jsonSchema.input() (e.g., Zod v4)\n * - Objects with toJSONSchema() method (e.g., Zod v4)\n * - Objects with toJSON() method\n * - Plain JSONSchema7 objects (must have a \"type\" property)\n */\nexport function toJSONSchema(\n schema: StandardSchemaV1 | JSONSchema7,\n): JSONSchema7 {\n // StandardSchemaV1 with ~standard.toJSONSchema (e.g., Zod v4)\n if (isStandardSchema(schema)) {\n const toJSONSchemaMethod = schema[\"~standard\"].toJSONSchema;\n if (typeof toJSONSchemaMethod === \"function\") {\n return toJSONSchemaMethod() as JSONSchema7;\n }\n\n // StandardSchemaV1 with ~standard.jsonSchema.input()\n const jsonSchema = schema[\"~standard\"].jsonSchema;\n if (\n typeof jsonSchema === \"object\" &&\n jsonSchema !== null &&\n typeof jsonSchema.input === \"function\"\n ) {\n return jsonSchema.input() as JSONSchema7;\n }\n }\n\n // toJSONSchema method on the schema itself\n if (hasToJSONSchemaMethod(schema)) {\n return schema.toJSONSchema() as JSONSchema7;\n }\n\n // toJSON method on the schema\n if (hasToJSONMethod(schema)) {\n return schema.toJSON() as JSONSchema7;\n }\n\n // If it's a Standard Schema that we couldn't convert, throw a helpful error\n if (isStandardSchema(schema)) {\n throw new Error(\n \"Could not convert schema to JSON Schema. \" +\n \"The schema implements Standard Schema but does not support JSON Schema conversion. \" +\n \"If you are using Zod, please upgrade to Zod v4 (npm install zod@latest). \" +\n \"Alternatively, pass a plain JSON Schema object instead.\",\n );\n }\n\n // Already a plain JSONSchema7\n return schema as JSONSchema7;\n}\n\n/**\n * Returns a copy of the JSON Schema with `required` removed recursively,\n * making every property optional. Array item schemas are left unchanged.\n */\nexport function toPartialJSONSchema(schema: JSONSchema7): JSONSchema7 {\n const { required: _, ...result } = schema;\n\n if (result.properties) {\n result.properties = Object.fromEntries(\n Object.entries(result.properties).map(([key, prop]) => {\n if (typeof prop === \"object\" && prop !== null && !Array.isArray(prop)) {\n const p = prop as JSONSchema7;\n return [key, p.properties != null ? toPartialJSONSchema(p) : prop];\n }\n return [key, prop];\n }),\n );\n }\n\n return result;\n}\n\nfunction defaultToolFilter(_name: string, tool: Tool): boolean {\n return !tool.disabled && tool.type !== \"backend\";\n}\n\n/**\n * Converts a record of tools to a record of tool definitions with JSON Schema parameters.\n * By default, filters out disabled tools and backend tools.\n */\nexport function toToolsJSONSchema(\n tools: Record<string, Tool> | undefined,\n options: ToToolsJSONSchemaOptions = {},\n): Record<string, ToolJSONSchema> {\n if (!tools) return {};\n\n const filter = options.filter ?? defaultToolFilter;\n\n return Object.fromEntries(\n Object.entries(tools)\n .filter(([name, tool]) => filter(name, tool) && tool.parameters)\n .map(([name, tool]) => [\n name,\n {\n ...(tool.description && { description: tool.description }),\n parameters: toJSONSchema(tool.parameters!),\n },\n ]),\n );\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"schema-utils.js","names":[],"sources":["../../../src/core/tool/schema-utils.ts"],"sourcesContent":["import type { JSONSchema7 } from \"json-schema\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { ProviderOptions, Tool } from \"./tool-types\";\n\n/**\n * Type for a tool definition with JSON Schema parameters.\n */\nexport type ToolJSONSchema = {\n description?: string;\n parameters: JSONSchema7;\n providerOptions?: ProviderOptions;\n};\n\nexport type ToToolsJSONSchemaOptions = {\n /**\n * Filter to determine which tools to include.\n * Defaults to excluding disabled tools and backend tools.\n */\n filter?: (name: string, tool: Tool) => boolean;\n};\n\nfunction isStandardSchema(schema: unknown): schema is StandardSchemaV1 & {\n \"~standard\": StandardSchemaV1[\"~standard\"] & {\n toJSONSchema?: () => unknown;\n jsonSchema?: { input?: () => unknown; output?: () => unknown };\n };\n} {\n return (\n typeof schema === \"object\" &&\n schema !== null &&\n \"~standard\" in schema &&\n typeof (schema as StandardSchemaV1)[\"~standard\"] === \"object\"\n );\n}\n\nfunction hasToJSONSchemaMethod(\n schema: unknown,\n): schema is { toJSONSchema: () => unknown } {\n return (\n typeof schema === \"object\" &&\n schema !== null &&\n \"toJSONSchema\" in schema &&\n typeof (schema as { toJSONSchema: unknown }).toJSONSchema === \"function\"\n );\n}\n\nfunction hasToJSONMethod(schema: unknown): schema is { toJSON: () => unknown } {\n return (\n typeof schema === \"object\" &&\n schema !== null &&\n \"toJSON\" in schema &&\n typeof (schema as { toJSON: unknown }).toJSON === \"function\"\n );\n}\n\n/**\n * Converts a schema to JSONSchema7.\n * Supports:\n * - StandardSchemaV1 with ~standard.toJSONSchema (e.g., Zod v4)\n * - StandardSchemaV1 with ~standard.jsonSchema.input() (e.g., Zod v4)\n * - Objects with toJSONSchema() method (e.g., Zod v4)\n * - Objects with toJSON() method\n * - Plain JSONSchema7 objects (must have a \"type\" property)\n */\nexport function toJSONSchema(\n schema: StandardSchemaV1 | JSONSchema7,\n): JSONSchema7 {\n // StandardSchemaV1 with ~standard.toJSONSchema (e.g., Zod v4)\n if (isStandardSchema(schema)) {\n const toJSONSchemaMethod = schema[\"~standard\"].toJSONSchema;\n if (typeof toJSONSchemaMethod === \"function\") {\n return toJSONSchemaMethod() as JSONSchema7;\n }\n\n // StandardSchemaV1 with ~standard.jsonSchema.input()\n const jsonSchema = schema[\"~standard\"].jsonSchema;\n if (\n typeof jsonSchema === \"object\" &&\n jsonSchema !== null &&\n typeof jsonSchema.input === \"function\"\n ) {\n return jsonSchema.input() as JSONSchema7;\n }\n }\n\n // toJSONSchema method on the schema itself\n if (hasToJSONSchemaMethod(schema)) {\n return schema.toJSONSchema() as JSONSchema7;\n }\n\n // toJSON method on the schema\n if (hasToJSONMethod(schema)) {\n return schema.toJSON() as JSONSchema7;\n }\n\n // If it's a Standard Schema that we couldn't convert, throw a helpful error\n if (isStandardSchema(schema)) {\n throw new Error(\n \"Could not convert schema to JSON Schema. \" +\n \"The schema implements Standard Schema but does not support JSON Schema conversion. \" +\n \"If you are using Zod, please upgrade to Zod v4 (npm install zod@latest). \" +\n \"Alternatively, pass a plain JSON Schema object instead.\",\n );\n }\n\n // Already a plain JSONSchema7\n return schema as JSONSchema7;\n}\n\n/**\n * Returns a copy of the JSON Schema with `required` removed recursively,\n * making every property optional. Array item schemas are left unchanged.\n */\nexport function toPartialJSONSchema(schema: JSONSchema7): JSONSchema7 {\n const { required: _, ...result } = schema;\n\n if (result.properties) {\n result.properties = Object.fromEntries(\n Object.entries(result.properties).map(([key, prop]) => {\n if (typeof prop === \"object\" && prop !== null && !Array.isArray(prop)) {\n const p = prop as JSONSchema7;\n return [key, p.properties != null ? toPartialJSONSchema(p) : prop];\n }\n return [key, prop];\n }),\n );\n }\n\n return result;\n}\n\nfunction defaultToolFilter(_name: string, tool: Tool): boolean {\n return !tool.disabled && tool.type !== \"backend\";\n}\n\n/**\n * Converts a record of tools to a record of tool definitions with JSON Schema parameters.\n * By default, filters out disabled tools and backend tools.\n *\n * Entries are emitted in alphabetical order so the resulting request body is\n * byte-identical regardless of the order in which tools were registered. This\n * keeps provider prompt caches stable across renders that mount tools in\n * different orders.\n */\nexport function toToolsJSONSchema(\n tools: Record<string, Tool> | undefined,\n options: ToToolsJSONSchemaOptions = {},\n): Record<string, ToolJSONSchema> {\n if (!tools) return {};\n\n const filter = options.filter ?? defaultToolFilter;\n\n return Object.fromEntries(\n Object.entries(tools)\n .filter(([name, tool]) => filter(name, tool) && tool.parameters)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([name, tool]) => [\n name,\n {\n ...(tool.description && { description: tool.description }),\n parameters: toJSONSchema(tool.parameters!),\n ...(tool.providerOptions && {\n providerOptions: tool.providerOptions,\n }),\n },\n ]),\n );\n}\n"],"mappings":";AAqBA,SAAS,iBAAiB,QAKxB;CACA,OACE,OAAO,WAAW,YAClB,WAAW,QACX,eAAe,UACf,OAAQ,OAA4B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IAAI,CAAC,OAAO,OAAO,CAAC;CAEpB,MAAM,SAAS,QAAQ,UAAU;CAEjC,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,EACjB,QAAQ,CAAC,MAAM,UAAU,OAAO,MAAM,IAAI,KAAK,KAAK,UAAU,EAC9D,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,EAC/C,KAAK,CAAC,MAAM,UAAU,CACrB,MACA;EACE,GAAI,KAAK,eAAe,EAAE,aAAa,KAAK,YAAY;EACxD,YAAY,aAAa,KAAK,UAAW;EACzC,GAAI,KAAK,mBAAmB,EAC1B,iBAAiB,KAAK,gBACxB;CACF,CACF,CAAC,CACL;AACF"}
|
|
@@ -77,7 +77,7 @@ interface ToolCallArgsReader<TArgs extends Record<string, unknown>> {
|
|
|
77
77
|
*
|
|
78
78
|
* @param fieldPath An array of object keys or array indices.
|
|
79
79
|
*/
|
|
80
|
-
streamText<PathT extends TypePath<TArgs>>(...fieldPath: PathT): TypeAtPath<TArgs, PathT> extends string & infer U ? AsyncIterableStream<U> : never;
|
|
80
|
+
streamText<PathT extends TypePath<TArgs>>(...fieldPath: PathT): TypeAtPath<TArgs, PathT> extends string & (infer U) ? AsyncIterableStream<U> : never;
|
|
81
81
|
/**
|
|
82
82
|
* Returns a stream that will emit complete items in the array
|
|
83
83
|
* at the given path, as they are generated by the LLM.
|
|
@@ -115,11 +115,48 @@ type ToolExecutionContext = {
|
|
|
115
115
|
type ToolExecuteFunction<TArgs, TResult> = (args: TArgs, context: ToolExecutionContext) => TResult | Promise<TResult>;
|
|
116
116
|
type ToolStreamCallFunction<TArgs extends Record<string, unknown> = Record<string, unknown>, TResult = unknown> = (reader: ToolCallReader<TArgs, TResult>, context: ToolExecutionContext) => void;
|
|
117
117
|
type OnSchemaValidationErrorFunction<TResult> = ToolExecuteFunction<unknown, TResult>;
|
|
118
|
+
/**
|
|
119
|
+
* Per-provider metadata forwarded into the wire request body verbatim.
|
|
120
|
+
* assistant-ui does not interpret these values; downstream adapters (AI SDK,
|
|
121
|
+
* custom routes) pass them to the model provider as-is.
|
|
122
|
+
*
|
|
123
|
+
* The outer key is the provider name (`anthropic`, `openai`, ...); the inner
|
|
124
|
+
* object is whatever shape that provider's SDK expects under
|
|
125
|
+
* `tool.providerOptions[providerName]`. Use this to enable provider-specific
|
|
126
|
+
* tool behaviors such as Anthropic's `defer_loading`
|
|
127
|
+
* (`{ anthropic: { deferLoading: true } }`) without adding provider-aware
|
|
128
|
+
* code in assistant-ui.
|
|
129
|
+
*/
|
|
130
|
+
type ProviderOptions = Record<string, Record<string, unknown>>;
|
|
131
|
+
/**
|
|
132
|
+
* Controls how a tool call's UI is presented relative to the assistant's
|
|
133
|
+
* chain-of-thought trace.
|
|
134
|
+
*
|
|
135
|
+
* - `"inline"` — the tool call is part of the reasoning trace and is folded
|
|
136
|
+
* into the chain-of-thought grouping alongside other routine tool calls.
|
|
137
|
+
* - `"standalone"` — the tool call is surfaced on its own, outside the
|
|
138
|
+
* chain-of-thought grouping (e.g. a human-in-the-loop prompt, a generative
|
|
139
|
+
* UI surface, or an important action UI worth showing prominently).
|
|
140
|
+
*
|
|
141
|
+
* This is a client-side presentation hint only; it does not affect how the
|
|
142
|
+
* tool is exposed to or executed by the model.
|
|
143
|
+
*/
|
|
144
|
+
type ToolDisplay = "standalone" | "inline";
|
|
118
145
|
type ToolBase<TArgs extends Record<string, unknown> = Record<string, unknown>, TResult = unknown> = {
|
|
119
146
|
/**
|
|
120
147
|
* @deprecated Experimental, API may change.
|
|
121
148
|
*/
|
|
122
149
|
streamCall?: ToolStreamCallFunction<TArgs, TResult>;
|
|
150
|
+
/**
|
|
151
|
+
* How this tool's UI is presented relative to the chain-of-thought trace.
|
|
152
|
+
*
|
|
153
|
+
* Defaults to `"inline"` (folded into the chain-of-thought grouping).
|
|
154
|
+
* Set `"standalone"` to surface the tool call on its own. `human` tools are
|
|
155
|
+
* always `"standalone"` and cannot opt out.
|
|
156
|
+
*
|
|
157
|
+
* @see ToolDisplay
|
|
158
|
+
*/
|
|
159
|
+
display?: ToolDisplay;
|
|
123
160
|
};
|
|
124
161
|
type BackendTool<TArgs extends Record<string, unknown> = Record<string, unknown>, TResult = unknown> = ToolBase<TArgs, TResult> & {
|
|
125
162
|
/** Tool that is executed by the backend rather than in the browser. */type: "backend";
|
|
@@ -129,6 +166,24 @@ type BackendTool<TArgs extends Record<string, unknown> = Record<string, unknown>
|
|
|
129
166
|
execute?: undefined;
|
|
130
167
|
toModelOutput?: undefined;
|
|
131
168
|
experimental_onSchemaValidationError?: undefined;
|
|
169
|
+
providerOptions?: undefined;
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* Backend tool as *authored* (a {@link ToolDeclaration}), before the build
|
|
173
|
+
* splits it: it may declare a `description`, `parameters`, and a server-side
|
|
174
|
+
* `execute`. The canonical {@link BackendTool} keeps these `undefined` because,
|
|
175
|
+
* once split, the client never sees them and the server consumes them through a
|
|
176
|
+
* server adapter rather than the shared {@link Tool} shape.
|
|
177
|
+
*/
|
|
178
|
+
type BackendToolDeclaration<TArgs extends Record<string, unknown> = Record<string, unknown>, TResult = unknown> = ToolBase<TArgs, TResult> & {
|
|
179
|
+
type: "backend"; /** Natural-language description shown to the model when selecting tools. */
|
|
180
|
+
description?: string | undefined; /** Schema for the arguments the model must provide when calling the tool. */
|
|
181
|
+
parameters?: StandardSchemaV1<TArgs> | JSONSchema7 | undefined; /** Prevents the tool from being exposed to the model while true. */
|
|
182
|
+
disabled?: boolean; /** Executes the tool on the server after the model provides valid arguments. */
|
|
183
|
+
execute?: ToolExecuteFunction<TArgs, TResult>; /** Converts the execution result into model-visible output. */
|
|
184
|
+
toModelOutput?: ToolModelOutputFunction<TArgs, TResult>; /** Handles invalid tool arguments when schema validation fails. */
|
|
185
|
+
experimental_onSchemaValidationError?: OnSchemaValidationErrorFunction<TResult>;
|
|
186
|
+
providerOptions?: ProviderOptions;
|
|
132
187
|
};
|
|
133
188
|
type FrontendTool<TArgs extends Record<string, unknown> = Record<string, unknown>, TResult = unknown> = ToolBase<TArgs, TResult> & {
|
|
134
189
|
/** Tool that is executed in the frontend runtime. */type: "frontend"; /** Natural-language description shown to the model when selecting tools. */
|
|
@@ -138,15 +193,18 @@ type FrontendTool<TArgs extends Record<string, unknown> = Record<string, unknown
|
|
|
138
193
|
execute: ToolExecuteFunction<TArgs, TResult>; /** Converts the execution result into model-visible output. */
|
|
139
194
|
toModelOutput?: ToolModelOutputFunction<TArgs, TResult>; /** Handles invalid tool arguments when schema validation fails. */
|
|
140
195
|
experimental_onSchemaValidationError?: OnSchemaValidationErrorFunction<TResult>;
|
|
196
|
+
providerOptions?: ProviderOptions;
|
|
141
197
|
};
|
|
142
198
|
type HumanTool<TArgs extends Record<string, unknown> = Record<string, unknown>, TResult = unknown> = ToolBase<TArgs, TResult> & {
|
|
143
199
|
/** Tool that pauses the run until a user or UI supplies a result. */type: "human"; /** Natural-language description shown to the model when selecting tools. */
|
|
144
200
|
description?: string | undefined; /** Schema for the arguments the model must provide when requesting input. */
|
|
145
201
|
parameters: StandardSchemaV1<TArgs> | JSONSchema7; /** Prevents the tool from being exposed to the model while true. */
|
|
146
|
-
disabled?: boolean;
|
|
202
|
+
disabled?: boolean; /** Human tools are always surfaced standalone and cannot opt out. */
|
|
203
|
+
display?: "standalone";
|
|
147
204
|
execute?: undefined;
|
|
148
205
|
toModelOutput?: undefined;
|
|
149
206
|
experimental_onSchemaValidationError?: undefined;
|
|
207
|
+
providerOptions?: ProviderOptions;
|
|
150
208
|
};
|
|
151
209
|
/**
|
|
152
210
|
* Definition for a tool that can be exposed to the assistant model.
|
|
@@ -190,6 +248,13 @@ type HumanTool<TArgs extends Record<string, unknown> = Record<string, unknown>,
|
|
|
190
248
|
* ```
|
|
191
249
|
*/
|
|
192
250
|
type Tool<TArgs extends Record<string, unknown> = Record<string, unknown>, TResult = unknown> = FrontendTool<TArgs, TResult> | BackendTool<TArgs, TResult> | HumanTool<TArgs, TResult> | ToolWithoutType<TArgs, TResult>;
|
|
251
|
+
/**
|
|
252
|
+
* A tool as *authored* — the permissive counterpart to {@link Tool}. Unlike
|
|
253
|
+
* {@link Tool}, a `backend` entry may declare `description`, `parameters`, and a
|
|
254
|
+
* server-side `execute`. Use this for the input of authoring helpers (e.g.
|
|
255
|
+
* `defineToolkit`); the canonical {@link Tool} is the output.
|
|
256
|
+
*/
|
|
257
|
+
type ToolDeclaration<TArgs extends Record<string, unknown> = Record<string, unknown>, TResult = unknown> = FrontendTool<TArgs, TResult> | BackendToolDeclaration<TArgs, TResult> | HumanTool<TArgs, TResult> | ToolWithoutType<TArgs, TResult>;
|
|
193
258
|
/**
|
|
194
259
|
* @deprecated Use {@link Tool} with an explicit `type` field instead.
|
|
195
260
|
*/
|
|
@@ -197,5 +262,5 @@ type ToolWithoutType<TArgs extends Record<string, unknown> = Record<string, unkn
|
|
|
197
262
|
type?: undefined;
|
|
198
263
|
};
|
|
199
264
|
//#endregion
|
|
200
|
-
export { Tool, ToolCallArgsReader, ToolCallReader, ToolCallResponseReader, ToolExecuteFunction, ToolExecutionContext, ToolModelContentPart, ToolModelOutputFunction, ToolStreamCallFunction, ToolWithoutType };
|
|
265
|
+
export { ProviderOptions, Tool, ToolCallArgsReader, ToolCallReader, ToolCallResponseReader, ToolDeclaration, ToolExecuteFunction, ToolExecutionContext, ToolModelContentPart, ToolModelOutputFunction, ToolStreamCallFunction, ToolWithoutType };
|
|
201
266
|
//# sourceMappingURL=tool-types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-types.d.ts","names":[],"sources":["../../../src/core/tool/tool-types.ts"],"mappings":";;;;;;;KAMY,oBAAA;8EAGG,IAAA,UAHH;EAAA,SAKG,IAAA;AAAA;EALiB,4EASjB,IAAA;EAJA;;;;EAAA,SASA,IAAA,UAIQ;EAAA,SAFR,SAAA,UA8BH;EAAA,SA5BG,QAAA;AAAA;;;;;;;;;;;;;;;;;;;;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qId,IAAA,WApIA;EAuIA,WAAA,uBArIuB;EAuIvB,UAAA,EAAY,gBAAA,CAAiB,KAAA,IAAS,WAAA,EAvItC;EAyIA,QAAA,YAxIA;EA0IA,OAAA;EACA,OAAA;EACA,aAAA;EACA,oCAAA;EACA,eAAA,GAAkB,eAAA;AAAA;;;;;AAzIX;AAeT;;;;AAAmD;AAAmB;;;;AAetD;AAAA;;;;;;;;;;;;;;;;;;;;;;AAoBO;AAAA;;;KAmIX,IAAA,eACI,MAAA,oBAA0B,MAAA,wCAGtC,YAAA,CAAa,KAAA,EAAO,OAAA,IACpB,WAAA,CAAY,KAAA,EAAO,OAAA,IACnB,SAAA,CAAU,KAAA,EAAO,OAAA,IACjB,eAAA,CAAgB,KAAA,EAAO,OAAA;;;;;;;KAQf,eAAA,eACI,MAAA,oBAA0B,MAAA,wCAGtC,YAAA,CAAa,KAAA,EAAO,OAAA,IACpB,sBAAA,CAAuB,KAAA,EAAO,OAAA,IAC9B,SAAA,CAAU,KAAA,EAAO,OAAA,IACjB,eAAA,CAAgB,KAAA,EAAO,OAAA;;;;KAKf,eAAA,eACI,MAAA,oBAA0B,MAAA,yCAGtC,IAAA,CAAK,YAAA,CAAa,KAAA,EAAO,OAAA,aACzB,IAAA,CAAK,WAAA,CAAY,KAAA,EAAO,OAAA,aACxB,IAAA,CAAK,SAAA,CAAU,KAAA,EAAO,OAAA;EACpB,IAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Counter.d.ts","names":[],"sources":["../../../src/core/utils/Counter.ts"],"mappings":";cAAa,OAAA;EACJ,KAAA;EAEP,EAAE
|
|
1
|
+
{"version":3,"file":"Counter.d.ts","names":[],"sources":["../../../src/core/utils/Counter.ts"],"mappings":";cAAa,OAAA;EACJ,KAAA;EAEP,EAAE;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withPromiseOrValue.d.ts","names":[],"sources":["../../../src/core/utils/withPromiseOrValue.ts"],"mappings":";iBAAgB,kBAAA,
|
|
1
|
+
{"version":3,"file":"withPromiseOrValue.d.ts","names":[],"sources":["../../../src/core/utils/withPromiseOrValue.ts"],"mappings":";iBAAgB,kBAAA,IACd,QAAA,QAAgB,CAAA,GAAI,WAAA,CAAY,CAAA,GAChC,WAAA,GAAc,KAAA,EAAO,CAAA,KAAM,WAAA,eAC3B,YAAA,GAAe,KAAA,cAAmB,WAAA,gBACjC,WAAA"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TextStreamController } from "./core/modules/text.js";
|
|
2
|
-
import { Tool, ToolCallReader, ToolModelContentPart, ToolModelOutputFunction } from "./core/tool/tool-types.js";
|
|
2
|
+
import { ProviderOptions, Tool, ToolCallReader, ToolDeclaration, ToolModelContentPart, ToolModelOutputFunction } from "./core/tool/tool-types.js";
|
|
3
3
|
import { ToolResponse, ToolResponseLike } from "./core/tool/ToolResponse.js";
|
|
4
4
|
import { ToolCallStreamController } from "./core/modules/tool-call.js";
|
|
5
5
|
import { AssistantMessage, AssistantMessageTiming, DataPart } from "./core/utils/types.js";
|
|
@@ -20,4 +20,4 @@ import { UIMessageStreamDecoder, UIMessageStreamDecoderOptions } from "./core/se
|
|
|
20
20
|
import { ToolExecutionStream } from "./core/tool/ToolExecutionStream.js";
|
|
21
21
|
import { ToToolsJSONSchemaOptions, ToolJSONSchema, toJSONSchema, toPartialJSONSchema, toToolsJSONSchema } from "./core/tool/schema-utils.js";
|
|
22
22
|
import { ToolResultStreamOptions, toolResultStream, unstable_runPendingTools } from "./core/tool/toolResultStream.js";
|
|
23
|
-
export { type AssistantMessage, AssistantMessageAccumulator, AssistantMessageStream, type AssistantMessageTiming, AssistantStream, type AssistantStreamChunk, type AssistantStreamController, AssistantTransportDecoder, AssistantTransportEncoder, type DataPart, DataStreamDecoder, DataStreamEncoder, type GenericAssistantMessage, type GenericFilePart, type GenericMessage, type GenericSystemMessage, type GenericTextPart, type GenericToolCallPart, type GenericToolMessage, type GenericToolResultPart, type GenericUserMessage, type ObjectStreamChunk, ObjectStreamResponse, PlainTextDecoder, PlainTextEncoder, type TextStreamController, type ToToolsJSONSchemaOptions, type Tool, type ToolCallReader, type ToolCallStreamController, ToolExecutionStream, type ToolJSONSchema, type ToolModelContentPart, type ToolModelOutputFunction, ToolResponse, type ToolResponseLike, type ToolResultStreamOptions, type UIMessageStreamChunk, type UIMessageStreamDataChunk, UIMessageStreamDecoder, type UIMessageStreamDecoderOptions, createAssistantStream, createAssistantStreamController, createAssistantStreamResponse, createObjectStream, fromObjectStreamResponse, toGenericMessages, toJSONSchema, toPartialJSONSchema, toToolsJSONSchema, createInitialMessage as unstable_createInitialMessage, unstable_runPendingTools, toolResultStream as unstable_toolResultStream };
|
|
23
|
+
export { type AssistantMessage, AssistantMessageAccumulator, AssistantMessageStream, type AssistantMessageTiming, AssistantStream, type AssistantStreamChunk, type AssistantStreamController, AssistantTransportDecoder, AssistantTransportEncoder, type DataPart, DataStreamDecoder, DataStreamEncoder, type GenericAssistantMessage, type GenericFilePart, type GenericMessage, type GenericSystemMessage, type GenericTextPart, type GenericToolCallPart, type GenericToolMessage, type GenericToolResultPart, type GenericUserMessage, type ObjectStreamChunk, ObjectStreamResponse, PlainTextDecoder, PlainTextEncoder, type ProviderOptions, type TextStreamController, type ToToolsJSONSchemaOptions, type Tool, type ToolCallReader, type ToolCallStreamController, type ToolDeclaration, ToolExecutionStream, type ToolJSONSchema, type ToolModelContentPart, type ToolModelOutputFunction, ToolResponse, type ToolResponseLike, type ToolResultStreamOptions, type UIMessageStreamChunk, type UIMessageStreamDataChunk, UIMessageStreamDecoder, type UIMessageStreamDecoderOptions, createAssistantStream, createAssistantStreamController, createAssistantStreamResponse, createObjectStream, fromObjectStreamResponse, toGenericMessages, toJSONSchema, toPartialJSONSchema, toToolsJSONSchema, createInitialMessage as unstable_createInitialMessage, unstable_runPendingTools, toolResultStream as unstable_toolResultStream };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":["JSONSchema4Object","JSONSchema4Array","key","JSONSchema4Type","Array","id","$ref","$schema","JSONSchema4Version","title","description","default","multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","JSONSchema4","items","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","definitions","k","properties","patternProperties","dependencies","enum","type","JSONSchema4TypeName","allOf","anyOf","oneOf","not","extends","format","JSONSchema6Object","JSONSchema6Array","JSONSchema6Type","JSONSchema6","$id","JSONSchema6Version","JSONSchema6Definition","contains","propertyNames","const","JSONSchema6TypeName","examples","JSONSchema7Object","JSONSchema7Array","JSONSchema7Type","JSONSchema7","JSONSchema7Version","$comment","$defs","JSONSchema7Definition","JSONSchema7TypeName","if","then","else","contentMediaType","contentEncoding","readOnly","writeOnly","valid","errors","ValidationError","property","message","instance","schema","ValidationResult","value","result"],"sources":["../../../../../../../../../node_modules/.pnpm/@types+json-schema@7.0.15/node_modules/@types/json-schema/index.d.ts"],"x_google_ignoreList":[0],"mappings":";;;;;;;;;;KA+iBY,mBAAA;AAAA;;;;;KAaA,eAAA;AAAA,qBAIN,iBAAA,GACA,gBAAgB;AAAA;AAAA,UAIL,iBAAA;EAAA,CACZE,GAAAA,WAAc,eAAe;AAAA;AAAA;AAAA;AAAA,UAKjB,gBAAA,SAAyB,KAAK,CAAC,eAAA;;;;;;;;;;;;KAapC,kBAAA;;;;;KAMA,qBAAA,GAAwB,WAAW;AAAA,UAC9B,WAAA;EACb8C,GAAAA;EACA1C,IAAAA;EACAC,OAAAA,GAAU,kBAAA;EACVsD,QAAAA;;;;;EAMAC,KAAAA;IAAAA,CACK5D,GAAAA,WAAc,qBAAA;EAAA;;;;EAMnBkC,IAAAA,GAAO,mBAAA,GAAsB,mBAAA;EAC7BD,IAAAA,GAAO,eAAA;EACPkB,KAAAA,GAAQ,eAAA;;;;EAKRzC,UAAAA;EACAC,OAAAA;EACAC,gBAAAA;EACAC,OAAAA;EACAC,gBAAAA;;;;EAKAC,SAAAA;EACAC,SAAAA;EACAC,OAAAA;;;;EAKAG,KAAAA,GAAQ,qBAAA,GAAwB,qBAAA;EAChCF,eAAAA,GAAkB,qBAAA;EAClBG,QAAAA;EACAC,QAAAA;EACAC,WAAAA;EACA0B,QAAAA,GAAW,qBAAA;;;;EAKXzB,aAAAA;EACAC,aAAAA;EACAC,QAAAA;EACAI,UAAAA;IAAAA,CACK9B,GAAAA,WAAc,qBAAA;EAAA;EAEnB+B,iBAAAA;IAAAA,CACK/B,GAAAA,WAAc,qBAAA;EAAA;EAEnB2B,oBAAAA,GAAuB,qBAAA;EACvBK,YAAAA;IAAAA,CACKhC,GAAAA,WAAc,qBAAA;EAAA;EAEnBkD,aAAAA,GAAgB,qBAAA;;;;EAKhBa,EAAAA,GAAK,qBAAA;EACLC,IAAAA,GAAO,qBAAA;EACPC,IAAAA,GAAO,qBAAA;;;;EAKP7B,KAAAA,GAAQ,qBAAA;EACRC,KAAAA,GAAQ,qBAAA;EACRC,KAAAA,GAAQ,qBAAA;EACRC,GAAAA,GAAM,qBAAA;;;;EAKNE,MAAAA;;;;EAKAyB,gBAAAA;EACAC,eAAAA;;;;EAKAvC,WAAAA;IAAAA,CACK5B,GAAAA,WAAc,qBAAA;EAAA;;;;EAMnBO,KAAAA;EACAC,WAAAA;EACAC,OAAAA,GAAU,eAAA;EACV2D,QAAAA;EACAC,SAAAA;EACAhB,QAAAA,GAAW,eAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AsyncIterableStream.d.ts","names":[],"sources":["../../src/utils/AsyncIterableStream.ts"],"mappings":";KAAY,mBAAA,MAAyB,aAAA,CAAc,CAAA,IAAK,cAAA,CAAe,CAAA;AAAA,iBAiBvD,qBAAA,
|
|
1
|
+
{"version":3,"file":"AsyncIterableStream.d.ts","names":[],"sources":["../../src/utils/AsyncIterableStream.ts"],"mappings":";KAAY,mBAAA,MAAyB,aAAA,CAAc,CAAA,IAAK,cAAA,CAAe,CAAA;AAAA,iBAiBvD,qBAAA,IACd,MAAA,EAAQ,cAAA,CAAe,CAAA,IACtB,mBAAA,CAAoB,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "assistant-stream",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.18",
|
|
4
4
|
"description": "Streaming utilities for AI assistants",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -64,10 +64,10 @@
|
|
|
64
64
|
},
|
|
65
65
|
"devDependencies": {
|
|
66
66
|
"@types/json-schema": "^7.0.15",
|
|
67
|
-
"ioredis": "^5.
|
|
68
|
-
"redis": "^
|
|
67
|
+
"ioredis": "^5.11.0",
|
|
68
|
+
"redis": "^6.0.0",
|
|
69
69
|
"vitest": "^4.1.7",
|
|
70
|
-
"@assistant-ui/x-buildutils": "0.0.
|
|
70
|
+
"@assistant-ui/x-buildutils": "0.0.10"
|
|
71
71
|
},
|
|
72
72
|
"publishConfig": {
|
|
73
73
|
"access": "public",
|
|
@@ -12,10 +12,10 @@ export class ObjectStreamEncoder extends PipeableTransformStream<
|
|
|
12
12
|
readable
|
|
13
13
|
.pipeThrough(
|
|
14
14
|
(() => {
|
|
15
|
-
class ObjectStreamTransformer
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
{
|
|
15
|
+
class ObjectStreamTransformer implements Transformer<
|
|
16
|
+
ObjectStreamChunk,
|
|
17
|
+
readonly ObjectStreamOperation[]
|
|
18
|
+
> {
|
|
19
19
|
#isFirstChunk = true;
|
|
20
20
|
|
|
21
21
|
start() {
|
|
@@ -419,7 +419,6 @@ export class DataStreamDecoder extends PipeableTransformStream<
|
|
|
419
419
|
flush() {
|
|
420
420
|
activeToolCallArgsText?.close();
|
|
421
421
|
activeToolCallArgsText = undefined;
|
|
422
|
-
// biome-ignore lint/suspicious/useIterableCallbackReturn: forEach callback intentionally has no return
|
|
423
422
|
toolCallControllers.forEach((controller) => controller.close());
|
|
424
423
|
toolCallControllers.clear();
|
|
425
424
|
},
|
|
@@ -264,7 +264,6 @@ export class UIMessageStreamDecoder extends PipeableTransformStream<
|
|
|
264
264
|
},
|
|
265
265
|
flush() {
|
|
266
266
|
activeToolCallArgsText?.close();
|
|
267
|
-
// biome-ignore lint/suspicious/useIterableCallbackReturn: forEach callback intentionally has no return
|
|
268
267
|
toolCallControllers.forEach((ctrl) => ctrl.close());
|
|
269
268
|
toolCallControllers.clear();
|
|
270
269
|
},
|
|
@@ -232,9 +232,9 @@ class ForEachHandle<T> implements Handle {
|
|
|
232
232
|
}
|
|
233
233
|
|
|
234
234
|
// Implementation of ToolCallReader that uses stream of partial JSON
|
|
235
|
-
export class ToolCallArgsReaderImpl<
|
|
236
|
-
|
|
237
|
-
{
|
|
235
|
+
export class ToolCallArgsReaderImpl<
|
|
236
|
+
T extends ReadonlyJSONObject,
|
|
237
|
+
> implements ToolCallArgsReader<T> {
|
|
238
238
|
private argTextDeltas: ReadableStream<string>;
|
|
239
239
|
private handles: Set<Handle> = new Set();
|
|
240
240
|
private args: unknown = parsePartialJsonObject("");
|
|
@@ -334,7 +334,7 @@ export class ToolCallArgsReaderImpl<T extends ReadonlyJSONObject>
|
|
|
334
334
|
|
|
335
335
|
streamText<PathT extends TypePath<T>>(
|
|
336
336
|
...fieldPath: PathT
|
|
337
|
-
): TypeAtPath<T, PathT> extends string & infer U
|
|
337
|
+
): TypeAtPath<T, PathT> extends string & (infer U)
|
|
338
338
|
? AsyncIterableStream<U>
|
|
339
339
|
: never {
|
|
340
340
|
// Use a type assertion to convert the complex TypePath to a simple array
|
|
@@ -395,9 +395,9 @@ export class ToolCallArgsReaderImpl<T extends ReadonlyJSONObject>
|
|
|
395
395
|
}
|
|
396
396
|
}
|
|
397
397
|
|
|
398
|
-
export class ToolCallResponseReaderImpl<
|
|
399
|
-
|
|
400
|
-
{
|
|
398
|
+
export class ToolCallResponseReaderImpl<
|
|
399
|
+
TResult extends ReadonlyJSONValue,
|
|
400
|
+
> implements ToolCallResponseReader<TResult> {
|
|
401
401
|
constructor(private readonly promise: Promise<ToolResponse<TResult>>) {}
|
|
402
402
|
|
|
403
403
|
public get() {
|
|
@@ -408,8 +408,7 @@ export class ToolCallResponseReaderImpl<TResult extends ReadonlyJSONValue>
|
|
|
408
408
|
export class ToolCallReaderImpl<
|
|
409
409
|
TArgs extends ReadonlyJSONObject,
|
|
410
410
|
TResult extends ReadonlyJSONValue,
|
|
411
|
-
> implements ToolCallReader<TArgs, TResult>
|
|
412
|
-
{
|
|
411
|
+
> implements ToolCallReader<TArgs, TResult> {
|
|
413
412
|
public readonly args: ToolCallArgsReaderImpl<TArgs>;
|
|
414
413
|
public readonly response: ToolCallResponseReaderImpl<TResult>;
|
|
415
414
|
private readonly writable: WritableStream<string>;
|
|
@@ -430,6 +430,62 @@ describe("toToolsJSONSchema", () => {
|
|
|
430
430
|
properties: { converted: { type: "boolean" } },
|
|
431
431
|
});
|
|
432
432
|
});
|
|
433
|
+
|
|
434
|
+
it("forwards providerOptions verbatim when present", () => {
|
|
435
|
+
const tools: Record<string, Tool> = {
|
|
436
|
+
myTool: {
|
|
437
|
+
description: "Test",
|
|
438
|
+
parameters: { type: "object", properties: {} },
|
|
439
|
+
providerOptions: { anthropic: { deferLoading: true } },
|
|
440
|
+
},
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
const result = toToolsJSONSchema(tools);
|
|
444
|
+
expect(result.myTool).toEqual({
|
|
445
|
+
description: "Test",
|
|
446
|
+
parameters: { type: "object", properties: {} },
|
|
447
|
+
providerOptions: { anthropic: { deferLoading: true } },
|
|
448
|
+
});
|
|
449
|
+
});
|
|
450
|
+
|
|
451
|
+
it("omits providerOptions when absent", () => {
|
|
452
|
+
const tools: Record<string, Tool> = {
|
|
453
|
+
myTool: {
|
|
454
|
+
parameters: { type: "object", properties: {} },
|
|
455
|
+
},
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
const result = toToolsJSONSchema(tools);
|
|
459
|
+
expect(result.myTool).not.toHaveProperty("providerOptions");
|
|
460
|
+
});
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
describe("stable ordering", () => {
|
|
464
|
+
it("emits tool names in alphabetical order", () => {
|
|
465
|
+
const tools: Record<string, Tool> = {
|
|
466
|
+
zebra: { parameters: { type: "object", properties: {} } },
|
|
467
|
+
apple: { parameters: { type: "object", properties: {} } },
|
|
468
|
+
mango: { parameters: { type: "object", properties: {} } },
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
const result = toToolsJSONSchema(tools);
|
|
472
|
+
expect(Object.keys(result)).toEqual(["apple", "mango", "zebra"]);
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
it("produces byte-identical output regardless of insertion order", () => {
|
|
476
|
+
const a: Record<string, Tool> = {
|
|
477
|
+
zebra: { parameters: { type: "object", properties: {} } },
|
|
478
|
+
apple: { parameters: { type: "object", properties: {} } },
|
|
479
|
+
};
|
|
480
|
+
const b: Record<string, Tool> = {
|
|
481
|
+
apple: { parameters: { type: "object", properties: {} } },
|
|
482
|
+
zebra: { parameters: { type: "object", properties: {} } },
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
expect(JSON.stringify(toToolsJSONSchema(a))).toBe(
|
|
486
|
+
JSON.stringify(toToolsJSONSchema(b)),
|
|
487
|
+
);
|
|
488
|
+
});
|
|
433
489
|
});
|
|
434
490
|
|
|
435
491
|
describe("edge cases", () => {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { JSONSchema7 } from "json-schema";
|
|
2
2
|
import type { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
-
import type { Tool } from "./tool-types";
|
|
3
|
+
import type { ProviderOptions, Tool } from "./tool-types";
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Type for a tool definition with JSON Schema parameters.
|
|
@@ -8,6 +8,7 @@ import type { Tool } from "./tool-types";
|
|
|
8
8
|
export type ToolJSONSchema = {
|
|
9
9
|
description?: string;
|
|
10
10
|
parameters: JSONSchema7;
|
|
11
|
+
providerOptions?: ProviderOptions;
|
|
11
12
|
};
|
|
12
13
|
|
|
13
14
|
export type ToToolsJSONSchemaOptions = {
|
|
@@ -135,6 +136,11 @@ function defaultToolFilter(_name: string, tool: Tool): boolean {
|
|
|
135
136
|
/**
|
|
136
137
|
* Converts a record of tools to a record of tool definitions with JSON Schema parameters.
|
|
137
138
|
* By default, filters out disabled tools and backend tools.
|
|
139
|
+
*
|
|
140
|
+
* Entries are emitted in alphabetical order so the resulting request body is
|
|
141
|
+
* byte-identical regardless of the order in which tools were registered. This
|
|
142
|
+
* keeps provider prompt caches stable across renders that mount tools in
|
|
143
|
+
* different orders.
|
|
138
144
|
*/
|
|
139
145
|
export function toToolsJSONSchema(
|
|
140
146
|
tools: Record<string, Tool> | undefined,
|
|
@@ -147,11 +153,15 @@ export function toToolsJSONSchema(
|
|
|
147
153
|
return Object.fromEntries(
|
|
148
154
|
Object.entries(tools)
|
|
149
155
|
.filter(([name, tool]) => filter(name, tool) && tool.parameters)
|
|
156
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
150
157
|
.map(([name, tool]) => [
|
|
151
158
|
name,
|
|
152
159
|
{
|
|
153
160
|
...(tool.description && { description: tool.description }),
|
|
154
161
|
parameters: toJSONSchema(tool.parameters!),
|
|
162
|
+
...(tool.providerOptions && {
|
|
163
|
+
providerOptions: tool.providerOptions,
|
|
164
|
+
}),
|
|
155
165
|
},
|
|
156
166
|
]),
|
|
157
167
|
);
|
|
@@ -98,7 +98,7 @@ export interface ToolCallArgsReader<TArgs extends Record<string, unknown>> {
|
|
|
98
98
|
*/
|
|
99
99
|
streamText<PathT extends TypePath<TArgs>>(
|
|
100
100
|
...fieldPath: PathT
|
|
101
|
-
): TypeAtPath<TArgs, PathT> extends string & infer U
|
|
101
|
+
): TypeAtPath<TArgs, PathT> extends string & (infer U)
|
|
102
102
|
? AsyncIterableStream<U>
|
|
103
103
|
: never;
|
|
104
104
|
|
|
@@ -168,6 +168,35 @@ type OnSchemaValidationErrorFunction<TResult> = ToolExecuteFunction<
|
|
|
168
168
|
TResult
|
|
169
169
|
>;
|
|
170
170
|
|
|
171
|
+
/**
|
|
172
|
+
* Per-provider metadata forwarded into the wire request body verbatim.
|
|
173
|
+
* assistant-ui does not interpret these values; downstream adapters (AI SDK,
|
|
174
|
+
* custom routes) pass them to the model provider as-is.
|
|
175
|
+
*
|
|
176
|
+
* The outer key is the provider name (`anthropic`, `openai`, ...); the inner
|
|
177
|
+
* object is whatever shape that provider's SDK expects under
|
|
178
|
+
* `tool.providerOptions[providerName]`. Use this to enable provider-specific
|
|
179
|
+
* tool behaviors such as Anthropic's `defer_loading`
|
|
180
|
+
* (`{ anthropic: { deferLoading: true } }`) without adding provider-aware
|
|
181
|
+
* code in assistant-ui.
|
|
182
|
+
*/
|
|
183
|
+
export type ProviderOptions = Record<string, Record<string, unknown>>;
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Controls how a tool call's UI is presented relative to the assistant's
|
|
187
|
+
* chain-of-thought trace.
|
|
188
|
+
*
|
|
189
|
+
* - `"inline"` — the tool call is part of the reasoning trace and is folded
|
|
190
|
+
* into the chain-of-thought grouping alongside other routine tool calls.
|
|
191
|
+
* - `"standalone"` — the tool call is surfaced on its own, outside the
|
|
192
|
+
* chain-of-thought grouping (e.g. a human-in-the-loop prompt, a generative
|
|
193
|
+
* UI surface, or an important action UI worth showing prominently).
|
|
194
|
+
*
|
|
195
|
+
* This is a client-side presentation hint only; it does not affect how the
|
|
196
|
+
* tool is exposed to or executed by the model.
|
|
197
|
+
*/
|
|
198
|
+
type ToolDisplay = "standalone" | "inline";
|
|
199
|
+
|
|
171
200
|
type ToolBase<
|
|
172
201
|
TArgs extends Record<string, unknown> = Record<string, unknown>,
|
|
173
202
|
TResult = unknown,
|
|
@@ -176,6 +205,17 @@ type ToolBase<
|
|
|
176
205
|
* @deprecated Experimental, API may change.
|
|
177
206
|
*/
|
|
178
207
|
streamCall?: ToolStreamCallFunction<TArgs, TResult>;
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* How this tool's UI is presented relative to the chain-of-thought trace.
|
|
211
|
+
*
|
|
212
|
+
* Defaults to `"inline"` (folded into the chain-of-thought grouping).
|
|
213
|
+
* Set `"standalone"` to surface the tool call on its own. `human` tools are
|
|
214
|
+
* always `"standalone"` and cannot opt out.
|
|
215
|
+
*
|
|
216
|
+
* @see ToolDisplay
|
|
217
|
+
*/
|
|
218
|
+
display?: ToolDisplay;
|
|
179
219
|
};
|
|
180
220
|
|
|
181
221
|
type BackendTool<
|
|
@@ -191,6 +231,35 @@ type BackendTool<
|
|
|
191
231
|
execute?: undefined;
|
|
192
232
|
toModelOutput?: undefined;
|
|
193
233
|
experimental_onSchemaValidationError?: undefined;
|
|
234
|
+
providerOptions?: undefined;
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Backend tool as *authored* (a {@link ToolDeclaration}), before the build
|
|
239
|
+
* splits it: it may declare a `description`, `parameters`, and a server-side
|
|
240
|
+
* `execute`. The canonical {@link BackendTool} keeps these `undefined` because,
|
|
241
|
+
* once split, the client never sees them and the server consumes them through a
|
|
242
|
+
* server adapter rather than the shared {@link Tool} shape.
|
|
243
|
+
*/
|
|
244
|
+
type BackendToolDeclaration<
|
|
245
|
+
TArgs extends Record<string, unknown> = Record<string, unknown>,
|
|
246
|
+
TResult = unknown,
|
|
247
|
+
> = ToolBase<TArgs, TResult> & {
|
|
248
|
+
type: "backend";
|
|
249
|
+
|
|
250
|
+
/** Natural-language description shown to the model when selecting tools. */
|
|
251
|
+
description?: string | undefined;
|
|
252
|
+
/** Schema for the arguments the model must provide when calling the tool. */
|
|
253
|
+
parameters?: StandardSchemaV1<TArgs> | JSONSchema7 | undefined;
|
|
254
|
+
/** Prevents the tool from being exposed to the model while true. */
|
|
255
|
+
disabled?: boolean;
|
|
256
|
+
/** Executes the tool on the server after the model provides valid arguments. */
|
|
257
|
+
execute?: ToolExecuteFunction<TArgs, TResult>;
|
|
258
|
+
/** Converts the execution result into model-visible output. */
|
|
259
|
+
toModelOutput?: ToolModelOutputFunction<TArgs, TResult>;
|
|
260
|
+
/** Handles invalid tool arguments when schema validation fails. */
|
|
261
|
+
experimental_onSchemaValidationError?: OnSchemaValidationErrorFunction<TResult>;
|
|
262
|
+
providerOptions?: ProviderOptions;
|
|
194
263
|
};
|
|
195
264
|
|
|
196
265
|
type FrontendTool<
|
|
@@ -212,6 +281,7 @@ type FrontendTool<
|
|
|
212
281
|
toModelOutput?: ToolModelOutputFunction<TArgs, TResult>;
|
|
213
282
|
/** Handles invalid tool arguments when schema validation fails. */
|
|
214
283
|
experimental_onSchemaValidationError?: OnSchemaValidationErrorFunction<TResult>;
|
|
284
|
+
providerOptions?: ProviderOptions;
|
|
215
285
|
};
|
|
216
286
|
|
|
217
287
|
type HumanTool<
|
|
@@ -227,9 +297,12 @@ type HumanTool<
|
|
|
227
297
|
parameters: StandardSchemaV1<TArgs> | JSONSchema7;
|
|
228
298
|
/** Prevents the tool from being exposed to the model while true. */
|
|
229
299
|
disabled?: boolean;
|
|
300
|
+
/** Human tools are always surfaced standalone and cannot opt out. */
|
|
301
|
+
display?: "standalone";
|
|
230
302
|
execute?: undefined;
|
|
231
303
|
toModelOutput?: undefined;
|
|
232
304
|
experimental_onSchemaValidationError?: undefined;
|
|
305
|
+
providerOptions?: ProviderOptions;
|
|
233
306
|
};
|
|
234
307
|
|
|
235
308
|
/**
|
|
@@ -282,6 +355,21 @@ export type Tool<
|
|
|
282
355
|
| HumanTool<TArgs, TResult>
|
|
283
356
|
| ToolWithoutType<TArgs, TResult>;
|
|
284
357
|
|
|
358
|
+
/**
|
|
359
|
+
* A tool as *authored* — the permissive counterpart to {@link Tool}. Unlike
|
|
360
|
+
* {@link Tool}, a `backend` entry may declare `description`, `parameters`, and a
|
|
361
|
+
* server-side `execute`. Use this for the input of authoring helpers (e.g.
|
|
362
|
+
* `defineToolkit`); the canonical {@link Tool} is the output.
|
|
363
|
+
*/
|
|
364
|
+
export type ToolDeclaration<
|
|
365
|
+
TArgs extends Record<string, unknown> = Record<string, unknown>,
|
|
366
|
+
TResult = unknown,
|
|
367
|
+
> =
|
|
368
|
+
| FrontendTool<TArgs, TResult>
|
|
369
|
+
| BackendToolDeclaration<TArgs, TResult>
|
|
370
|
+
| HumanTool<TArgs, TResult>
|
|
371
|
+
| ToolWithoutType<TArgs, TResult>;
|
|
372
|
+
|
|
285
373
|
/**
|
|
286
374
|
* @deprecated Use {@link Tool} with an explicit `type` field instead.
|
|
287
375
|
*/
|
package/src/index.ts
CHANGED
|
@@ -37,12 +37,13 @@ export type {
|
|
|
37
37
|
|
|
38
38
|
export type {
|
|
39
39
|
Tool,
|
|
40
|
+
ToolDeclaration,
|
|
40
41
|
ToolModelContentPart,
|
|
41
42
|
ToolModelOutputFunction,
|
|
42
43
|
} from "./core/tool/tool-types";
|
|
43
44
|
export { ToolResponse, type ToolResponseLike } from "./core/tool/ToolResponse";
|
|
44
45
|
export { ToolExecutionStream } from "./core/tool/ToolExecutionStream";
|
|
45
|
-
export type { ToolCallReader } from "./core/tool/tool-types";
|
|
46
|
+
export type { ProviderOptions, ToolCallReader } from "./core/tool/tool-types";
|
|
46
47
|
export {
|
|
47
48
|
toolResultStream as unstable_toolResultStream,
|
|
48
49
|
unstable_runPendingTools,
|
package/src/resumable/index.ts
CHANGED
|
@@ -6,10 +6,7 @@ export type {
|
|
|
6
6
|
ResumableStreamAcquireOptions,
|
|
7
7
|
} from "./types";
|
|
8
8
|
|
|
9
|
-
export {
|
|
10
|
-
ResumableStreamError,
|
|
11
|
-
type ResumableStreamErrorCode,
|
|
12
|
-
} from "./errors";
|
|
9
|
+
export { ResumableStreamError, type ResumableStreamErrorCode } from "./errors";
|
|
13
10
|
|
|
14
11
|
export {
|
|
15
12
|
createResumableStreamContext,
|