@vercel/v0 0.0.1-alpha.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/legid@0.1.4/node_modules/legid/dist/index.js","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/ai-sdk-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/api-call-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/empty-response-body-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/get-error-message.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/invalid-argument-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/invalid-prompt-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/invalid-response-data-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/json-parse-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/load-api-key-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/load-setting-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/no-content-generated-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/no-such-model-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/too-many-embedding-values-for-call-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/type-validation-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/src/errors/unsupported-functionality-error.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-schema.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/select-parser.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/array.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/record.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/generate-id.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/secure-json-parse.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/validator.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/validate-types.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/parse-json.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/add-additional-properties-to-json-schema.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/get-relative-path.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/options.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/any.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/bigint.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/boolean.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/branded.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/catch.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/date.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/default.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/effects.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/enum.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/intersection.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/literal.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/string.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/map.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/native-enum.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/never.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/null.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/union.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/nullable.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/number.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/object.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/optional.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/pipeline.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/promise.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/set.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/tuple.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/undefined.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/unknown.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parsers/readonly.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/parse-def.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/refs.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/zod-to-json-schema.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/zod-to-json-schema/index.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/schema.ts","../../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.19_zod@4.3.5/node_modules/@ai-sdk/provider-utils/src/uint8-utils.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/prompt/data-content.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/prompt/standardize-prompt.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/prompt/message.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/types/provider-metadata.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/types/json-value.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/prompt/content-part.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/ui-message-stream/ui-message-chunks.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/ui/validate-ui-messages.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/error/no-output-specified-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/error/invalid-argument-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/error/invalid-stream-part-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/error/invalid-tool-input-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/error/no-image-generated-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/error/no-object-generated-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/error/no-output-generated-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/error/no-such-tool-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/error/tool-call-repair-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/prompt/invalid-data-content-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/prompt/invalid-message-role-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/prompt/message-conversion-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/util/download/download-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/util/retry-error.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/generate-text/generate-text.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/ui-message-stream/json-to-sse-transform-stream.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/util/fix-json.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/util/parse-partial-json.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/generate-text/stream-text.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/generate-object/generate-object.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/generate-object/stream-object.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/generate-text/output.ts","../../../node_modules/.pnpm/ai@5.0.116_zod@4.3.5/node_modules/ai/src/registry/no-such-provider-error.ts","../../shared/lib/cloud-sdk/sdk/routes/chat/create-id.tsx","../../shared/lib/constants-shared.ts","../../shared/lib/cloud-sdk/stream/isLlmError.ts","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/processor.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/pipe.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/contexts/context.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/clone.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/contexts/diff.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/contexts/patch.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/contexts/reverse.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/filters/trivial.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/filters/nested.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/filters/lcs.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/filters/arrays.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/filters/dates.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/filters/texts.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/diffpatcher.js","../../../node_modules/.pnpm/jsondiffpatch@0.6.0/node_modules/jsondiffpatch/lib/index.js","../../shared/lib/cloud-sdk/stream/diffpatch.ts","../../shared/lib/cloud-sdk/stream/stream-to-tree.ts","../../shared/lib/cloud-sdk/create-programmatic-task.tsx","../../shared/lib/cloud-sdk/sdk/routes/chat/programmatic-tasks.tsx","../../shared/lib/chat/mdx0/types.ts","../../shared/lib/chat/mdx0/helpers.ts","../../shared/lib/cloud-sdk/sdk/routes/chat/create-message.ts","../../shared/lib/cloud-sdk/sdk/routes/chat/create-pull-request.ts","../../shared/lib/cloud-sdk/sdk/routes/chat/push-to-branch.ts","../../shared/lib/cloud-sdk/sdk/routes/chat/get-deployment-status.ts","../../shared/lib/cloud-sdk/sdk/client.ts"],"names":["SALT","ALPHABET","calculateHexLength","alphabetLength","hexToCustomAlphabet","hex","decimal","result","base","remainder","generateRandomHexToken","length","array","byte","arrayBufferToHex","buffer","byteArray","sha1","text","data","hashBuffer","createId","approximateLength","salt","step","hexLength","hexToken","hexHash","hexId","tokenIndex","hashIndex","i","marker","symbol","_a","_AISDKError","name","message","cause","error","markerSymbol","AISDKError","getErrorMessage","InvalidArgumentError","argument","JSONParseError","_TypeValidationError","value","TypeValidationError","z4","ZodFirstPartyTypeKind","createIdGenerator","prefix","size","alphabet","separator","generator","chars","generateId","suspectProtoRx","suspectConstructorRx","_parse","obj","filter","next","nodes","node","key","secureJsonParse","stackTraceLimit","validatorSymbol","validator","validate","isValidator","lazyValidator","createValidator","asValidator","standardSchemaValidator","standardSchema","safeValidateTypes","schema","safeParseJSON","addAdditionalPropertiesToJsonSchema","jsonSchema","properties","property","item","getRelativePath","pathA","pathB","ignoreOverride","defaultOptions","getDefaultOptions","options","parseAnyDef","parseArrayDef","def","refs","_b","_c","res","parseDef","parseBigintDef","check","parseBooleanDef","parseBrandedDef","_def","parseCatchDef","parseDateDef","overrideDateStrategy","strategy","integerDateParser","parseDefaultDef","parseEffectsDef","parseEnumDef","isJsonSchema7AllOfType","type","parseIntersectionDef","allOf","x","mergedAllOf","nestedSchema","additionalProperties","rest","parseLiteralDef","parsedType","emojiRegex","zodPatterns","parseStringDef","addFormat","addPattern","escapeLiteralCheckValue","literal","escapeNonAlphaNumeric","ALPHA_NUMERIC","source","regex","stringifyRegExpWithFlags","flags","pattern","isEscaped","inCharGroup","inCharRange","parseRecordDef","_d","_e","_f","keyType","parseMapDef","keys","values","parseNativeEnumDef","object","actualValues","parsedTypes","parseNeverDef","parseNullDef","primitiveMappings","parseUnionDef","types","acc","uniqueTypes","a","asAnyOf","anyOf","parseNullableDef","parseNumberDef","parseObjectDef","required","shape","propName","propDef","propOptional","safeIsOptional","parsedDef","decideAdditionalProperties","parseOptionalDef","innerSchema","parsePipelineDef","b","parsePromiseDef","parseSetDef","parseTupleDef","parseUndefinedDef","parseUnknownDef","parseReadonlyDef","selectParser","typeName","_","forceResolution","seenItem","overrideResult","seenSchema","get$ref","newItem","jsonSchemaOrGetter","addMeta","postProcessResult","index","getRefs","_options","currentPath","zodToJsonSchema","definitions","main","title","combined","zod_to_json_schema_default","zod3Schema","zodSchema","useReferences","zod4Schema","isZod4Schema","schemaSymbol","isSchema","asSchema","btoa","atob","z","NoObjectGeneratedError","response","usage","finishReason","dataContentSchema","jsonValueSchema","providerMetadataSchema","textPartSchema","imagePartSchema","filePartSchema","reasoningPartSchema","toolCallPartSchema","outputSchema","toolResultPartSchema","systemModelMessageSchema","userModelMessageSchema","assistantModelMessageSchema","toolModelMessageSchema","modelMessageSchema","originalGenerateId","JsonToSseTransformStream","part","controller","uiMessageChunkSchema","fixJson","input","stack","lastValidIndex","literalStart","processValueStart","char","swapState","processAfterObjectValue","processAfterArrayValue","partialLiteral","parsePartialJson","jsonText","output_exports","__export","inputSchema","_exhaustiveCheck","context","parseResult","validationResult","uiMessagesSchema","createChatId","createMessageId","MAX_COOKIE_AGE","LLM_ERROR_PREFIX","LLM_ERROR_RETRY_SUFFIX","CONSOLE_RESIZE_COOKIE","CONSOLE_EXPANDED_COOKIE","CLI_TOKEN_EXPIRATION_MS","DEPLOYMENT_ALIAS_ERROR_MAP","PROJECT_DOMAIN_ALIAS_ERROR_MAP","ALIAS_ERROR_MAP","MAX_SQL_ATTACHMENT_SIZE","isLlmError","chunkOrMessage","returnValue","errorCategory","isRetriedLlmError","Processor","pipeArg","pipe","nextPipe","lastPipe","processor_default","Pipe","debug","msg","args","filterName","f","params","should","pipe_default","Context","child","cloneRegExp","re","regexMatch","clone","arg","cloned","DiffContext","left","right","diff_default","PatchContext","delta","patch_default","ReverseContext","reverse_default","diffFilter","patchFilter","nonNestedDelta","regexArgs","reverseFilter","collectChildrenDiffFilter","objectsDiffFilter","propertyFilter","nestedDelta","objectDelta","collectChildrenPatchFilter","collectChildrenReverseFilter","defaultMatch","array1","array2","index1","index2","lengthMatrix","match","len1","len2","y","matrix","backtrack","subsequence","valueAtMatrixAbove","valueAtMatrixLeft","get","innerContext","lcs_default","ARRAY_MOVE","arraysHaveMatchByRef","val1","val2","matchItems","value1","value2","objectHash","hash1","hash2","matchContext","commonHead","commonTail","trimmed1","trimmed2","seq","removedItems","detectMove","includeValueOnMove","removedItemsLength","indexOnArray2","isMove","removeItemIndex1","compare","toRemove","toInsert","toModify","removedOrMovedIndex","numberIndex","indexDiff","removedValue","toInsertLength","insertion","toModifyLength","modification","arrayIndex","arrayMoveDelta","arrayDelta","reverseArrayDeltaIndex","itemDelta","reverseIndex","deltaIndex","deltaItem","moveFromIndex","moveToIndex","deltaWithChildren","cachedDiffPatch","getDiffMatchPatch","instance","txt1","txt2","patch","results","minLength","diffMatchPatch","diff","textDiffDelta","textDeltaReverse","l","line","lineTmp","header","headerRegex","lineHeader","lines","lineStart","DiffPatcher","diffpatcher_default","create","jdf","original","newObj","indexes","streamToTree","reader","onError","signal","state","decoder","remainingLine","processRow","row","done","isRetried","createProgrammaticTask","getMessageRowType","extractItemOfType","content","targetType","extractFromItems","items","props","children","rowInfo","createPullRequestSchema","programmaticTasks","composeProgrammaticSchema","schemaShape","composeProgrammaticJsonSchema","maybeProgrammaticResult","createMessageStream","baseUrl","headers","chatId","messageId","programmatic","programmaticJsonSchema","messageContent","requestBody","errorBody","assistantMessageId","gitHeadBranch","gitBaseBranch","gitRepo","gitOrg","gitMeta","chunkMeta","programmaticResultYielded","streamError","stream","programmaticResult","e","CreatePullRequestInputSchema","MergeableState","CreatePullRequestResultSchema","createPullRequest","PushToBranchInputSchema","PushToBranchResultSchema","pushToBranch","GetDeploymentStatusInputSchema","DeploymentStatusSchema","GetDeploymentStatusResultSchema","getDeploymentStatus","createV0Client","token","customHeaders","getHeaders","resolvedToken","isNew"],"mappings":"AACA,IAAMA,GAAO,SAIb,IAAMC,GAAW,iEAWb,SAASC,GAAmBC,EAAgB,CAC5C,OAAO,KAAK,MAAMA,EAAiB,OAAqB,CAC5D,CAGI,SAASC,GAAoBC,EAAK,CAClC,GAAI,CAACA,EAAK,MAAO,GAEjB,IAAIC,EAAU,OAAO,KAAOD,CAAG,EAC3BE,EAAS,GACPC,EAAO,OAAOP,GAAS,MAAM,EACnC,EAAG,CACC,IAAMQ,EAAYH,EAAUE,EAC5BD,EAASN,GAAS,OAAOQ,CAAS,CAAC,EAAIF,EACvCD,EAAUA,EAAUE,QAChBF,EAAU,IAClB,OAAOC,CACX,CAoBI,SAASG,GAAuBC,EAAQ,CAGxC,IAAMC,EAAQ,IAAI,WAAW,KAAK,KAAKD,EAAS,CAAC,CAAC,EAGlD,IAFA,OAAO,gBAAgBC,CAAK,E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AS,KAAK,CACvB,CCrDO,IAAMgQ,GAAiB,CAAC,CAC7B,QAAAhC,EAAU,iBACV,MAAAiC,EACA,QAASC,CACX,IAAuB,CACrB,IAAMC,EAAa,SAA6C,CAC9D,IAAMC,EAAgB,OAAOH,GAAU,WAAa,MAAMA,EAAM,EAAIA,EACpE,MAAO,CACL,GAAGC,EACH,cAAe,UAAUE,IACzB,eAAgB,kBAClB,CACF,EAEA,MAAO,CACL,QAAS,CACP,MAAO,aACL5O,EACiE,CACjE,IAAMyM,EAAU,MAAMkC,EAAW,EAC3BjC,EAAS1M,EAAM,QAAW,MAAMoB,GAAa,EAC7CyN,EAAQ7O,EAAM,OAAS,CAACA,EAAM,OAEpC,MAAOuM,GAA4B,CACjC,MAAO,CAAE,GAAGvM,EAAO,OAAA0M,EAAQ,MAAAmC,CAAM,EACjC,QAAArC,EACA,QAAAC,CACF,CAAC,CACH,CACF,EACA,IAAK,CACH,YAAa,CACX,OAAQ,MACNzM,GACqC,CACrC,IAAMyM,EAAU,MAAMkC,EAAW,EACjC,OAAOX,GAAkB,CACvB,MAAAhO,EACA,QAAAwM,EACA,QAAAC,CACF,CAAC,CACH,CACF,EACA,OAAQ,CACN,KAAM,MAAOzM,GAA0D,CACrE,IAAMyM,EAAU,MAAMkC,EAAW,EACjC,OAAOR,GAAa,CAClB,MAAAnO,EACA,QAAAwM,EACA,QAAAC,CACF,CAAC,CACH,CACF,EACA,iBAAkB,CAChB,IAAK,MACHzM,GACuC,CACvC,IAAMyM,EAAU,MAAMkC,EAAW,EACjC,OAAOJ,GAAoB,CACzB,MAAAvO,EACA,QAAAwM,EACA,QAAAC,CACF,CAAC,CACH,CACF,CACF,CACF,CACF","sourcesContent":["// Default salt prefix for ID generation\nconst SALT = 'legid:';\n// Default length for generated IDs if not specified\nconst DEFAULT_ID_LENGTH = 10;\n// Custom alphabet for ID generation\nconst ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';\n// Calculate the conversion ratio from hex to base62\n// Math.log(62) / Math.log(16) ~= 1.48855\nconst HEX_TO_ALPHABET_RATIO = 1.48855;\n// SHA-1 is 160 bits, which is 40 hex characters. So the max length of the hex\n// ID is 80 characters (40 from token, 40 from hash).\n// 80 / 1.48855 = 54\n// Maximum length for custom alphabet IDs\nconst MAX_ID_LENGTH = 54;\n/**\n * Calculate required hex length for desired alphabet length\n */ function calculateHexLength(alphabetLength) {\n return Math.floor(alphabetLength * HEX_TO_ALPHABET_RATIO);\n}\n/**\n * Converts hex string to custom alphabet using base conversion\n */ function hexToCustomAlphabet(hex) {\n if (!hex) return '';\n // Convert hex to decimal\n let decimal = BigInt('0x' + hex);\n let result = '';\n const base = BigInt(ALPHABET.length);\n do {\n const remainder = decimal % base;\n result = ALPHABET[Number(remainder)] + result;\n decimal = decimal / base;\n }while (decimal > 0n)\n return result;\n}\n/**\n * Converts custom alphabet string back to hex using base conversion\n */ function customAlphabetToHex(customStr) {\n if (!customStr) return '';\n let decimal = 0n;\n const base = BigInt(ALPHABET.length);\n for(let i = 0; i < customStr.length; i++){\n const char = customStr[i];\n const index = ALPHABET.indexOf(char);\n if (index === -1) {\n throw new Error(`Invalid character: ${char}`);\n }\n decimal = decimal * base + BigInt(index);\n }\n // Convert decimal back to hex\n return decimal.toString(16);\n}\n/**\n * Generates a random hex token of specified length using crypto.getRandomValues\n */ function generateRandomHexToken(length) {\n // Generate enough bytes to cover the required hex length\n // Each byte produces 2 hex characters\n const array = new Uint8Array(Math.ceil(length / 2));\n crypto.getRandomValues(array);\n // Ensure that the first byte is not zero to avoid leading zeros in hex\n while(array[0] < 16){\n crypto.getRandomValues(array);\n }\n const hex = Array.from(array, (byte)=>byte.toString(16).padStart(2, '0')).join('');\n return hex.substring(0, length);\n}\n/**\n * Converts ArrayBuffer to hex string\n */ function arrayBufferToHex(buffer) {\n const byteArray = new Uint8Array(buffer);\n return Array.from(byteArray, (byte)=>byte.toString(16).padStart(2, '0')).join('');\n}\n/**\n * Computes SHA-1 hash using SubtleCrypto\n */ async function sha1(text) {\n const encoder = new TextEncoder();\n const data = encoder.encode(text);\n const hashBuffer = await crypto.subtle.digest('SHA-1', data);\n return arrayBufferToHex(hashBuffer);\n}\n/**\n * Creates a random ID\n * ID structure: chars at odd positions are from token, chars at even positions are from hash\n * Uses hex internally, converts to custom alphabet at the end\n */ async function createId({ approximateLength = DEFAULT_ID_LENGTH, salt = SALT, step = 2 } = {}) {\n if (approximateLength <= 0) {\n throw new Error('ID length must be a positive integer');\n }\n if (approximateLength > MAX_ID_LENGTH) {\n throw new Error(`ID length exceeds maximum of ${MAX_ID_LENGTH} characters`);\n }\n if (step <= 1) {\n throw new Error('Step must be at least 2');\n }\n // Calculate required hex length for the desired alphabet ID length\n let hexLength = calculateHexLength(approximateLength);\n if (step > hexLength - 1) {\n throw new Error('Step cannot be greater than the data length: ' + (hexLength - 1));\n }\n // Generate random token\n const hexToken = generateRandomHexToken(Math.ceil(hexLength * (step - 1) / step));\n // Calculate hash\n const hexHash = await sha1(salt + hexToken);\n // Create hex ID\n let hexId = '';\n let tokenIndex = 0;\n let hashIndex = 0;\n for(let i = 0; i < hexLength; i++){\n if ((i + 1) % step === 0) {\n hexId += hexHash[hashIndex++];\n } else {\n hexId += hexToken[tokenIndex++];\n }\n }\n return hexToCustomAlphabet(hexId);\n}\n/**\n * Verifies if an ID was created from the createId process\n * Converts from custom alphabet back to hex, then verifies\n */ async function verifyId(id, { salt = SALT, step = 2 } = {}) {\n if (!id || id.length > MAX_ID_LENGTH) {\n return false // Invalid ID length\n ;\n }\n try {\n // Convert custom alphabet ID back to hex without specifying expected length\n const hexId = customAlphabetToHex(id);\n let extractedHexToken = '';\n let extractedHexHash = '';\n for(let i = 0; i < hexId.length; i++){\n if ((i + 1) % step === 0) {\n extractedHexHash += hexId[i];\n } else {\n extractedHexToken += hexId[i];\n }\n }\n if (extractedHexHash.length === 0) {\n // If no hash part is extracted, it's invalid\n return false;\n }\n // Calculate expected hex value\n const expectedHexValue = await sha1(salt + extractedHexToken);\n // It must be a prefix match\n return expectedHexValue.startsWith(extractedHexHash);\n } catch (error) {\n return false;\n }\n}\n\nexport { createId, verifyId };\n","/**\n * Symbol used for identifying AI SDK Error instances.\n * Enables checking if an error is an instance of AISDKError across package versions.\n */\nconst marker = 'vercel.ai.error';\nconst symbol = Symbol.for(marker);\n\n/**\n * Custom error class for AI SDK related errors.\n * @extends Error\n */\nexport class AISDKError extends Error {\n private readonly [symbol] = true; // used in isInstance\n\n /**\n * The underlying cause of the error, if any.\n */\n readonly cause?: unknown;\n\n /**\n * Creates an AI SDK Error.\n *\n * @param {Object} params - The parameters for creating the error.\n * @param {string} params.name - The name of the error.\n * @param {string} params.message - The error message.\n * @param {unknown} [params.cause] - The underlying cause of the error.\n */\n constructor({\n name,\n message,\n cause,\n }: {\n name: string;\n message: string;\n cause?: unknown;\n }) {\n super(message);\n\n this.name = name;\n this.cause = cause;\n }\n\n /**\n * Checks if the given error is an AI SDK Error.\n * @param {unknown} error - The error to check.\n * @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n */\n static isInstance(error: unknown): error is AISDKError {\n return AISDKError.hasMarker(error, marker);\n }\n\n protected static hasMarker(error: unknown, marker: string): boolean {\n const markerSymbol = Symbol.for(marker);\n return (\n error != null &&\n typeof error === 'object' &&\n markerSymbol in error &&\n typeof error[markerSymbol] === 'boolean' &&\n error[markerSymbol] === true\n );\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_APICallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class APICallError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly url: string;\n readonly requestBodyValues: unknown;\n readonly statusCode?: number;\n\n readonly responseHeaders?: Record<string, string>;\n readonly responseBody?: string;\n\n readonly isRetryable: boolean;\n readonly data?: unknown;\n\n constructor({\n message,\n url,\n requestBodyValues,\n statusCode,\n responseHeaders,\n responseBody,\n cause,\n isRetryable = statusCode != null &&\n (statusCode === 408 || // request timeout\n statusCode === 409 || // conflict\n statusCode === 429 || // too many requests\n statusCode >= 500), // server error\n data,\n }: {\n message: string;\n url: string;\n requestBodyValues: unknown;\n statusCode?: number;\n responseHeaders?: Record<string, string>;\n responseBody?: string;\n cause?: unknown;\n isRetryable?: boolean;\n data?: unknown;\n }) {\n super({ name, message, cause });\n\n this.url = url;\n this.requestBodyValues = requestBodyValues;\n this.statusCode = statusCode;\n this.responseHeaders = responseHeaders;\n this.responseBody = responseBody;\n this.isRetryable = isRetryable;\n this.data = data;\n }\n\n static isInstance(error: unknown): error is APICallError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_EmptyResponseBodyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class EmptyResponseBodyError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n constructor({ message = 'Empty response body' }: { message?: string } = {}) {\n super({ name, message });\n }\n\n static isInstance(error: unknown): error is EmptyResponseBodyError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","export function getErrorMessage(error: unknown | undefined) {\n if (error == null) {\n return 'unknown error';\n }\n\n if (typeof error === 'string') {\n return error;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n return JSON.stringify(error);\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A function argument is invalid.\n */\nexport class InvalidArgumentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly argument: string;\n\n constructor({\n message,\n cause,\n argument,\n }: {\n argument: string;\n message: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n\n this.argument = argument;\n }\n\n static isInstance(error: unknown): error is InvalidArgumentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidPromptError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * A prompt is invalid. This error should be thrown by providers when they cannot\n * process a prompt.\n */\nexport class InvalidPromptError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly prompt: unknown;\n\n constructor({\n prompt,\n message,\n cause,\n }: {\n prompt: unknown;\n message: string;\n cause?: unknown;\n }) {\n super({ name, message: `Invalid prompt: ${message}`, cause });\n\n this.prompt = prompt;\n }\n\n static isInstance(error: unknown): error is InvalidPromptError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_InvalidResponseDataError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\n * Server returned a response with invalid data content.\n * This should be thrown by providers when they cannot parse the response from the API.\n */\nexport class InvalidResponseDataError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly data: unknown;\n\n constructor({\n data,\n message = `Invalid response data: ${JSON.stringify(data)}.`,\n }: {\n data: unknown;\n message?: string;\n }) {\n super({ name, message });\n\n this.data = data;\n }\n\n static isInstance(error: unknown): error is InvalidResponseDataError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_JSONParseError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n// TODO v5: rename to ParseError\nexport class JSONParseError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly text: string;\n\n constructor({ text, cause }: { text: string; cause: unknown }) {\n super({\n name,\n message:\n `JSON parsing failed: ` +\n `Text: ${text}.\\n` +\n `Error message: ${getErrorMessage(cause)}`,\n cause,\n });\n\n this.text = text;\n }\n\n static isInstance(error: unknown): error is JSONParseError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadAPIKeyError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadAPIKeyError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n constructor({ message }: { message: string }) {\n super({ name, message });\n }\n\n static isInstance(error: unknown): error is LoadAPIKeyError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_LoadSettingError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class LoadSettingError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n constructor({ message }: { message: string }) {\n super({ name, message });\n }\n\n static isInstance(error: unknown): error is LoadSettingError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoContentGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\nThrown when the AI provider fails to generate any content.\n */\nexport class NoContentGeneratedError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n constructor({\n message = 'No content generated.',\n }: { message?: string } = {}) {\n super({ name, message });\n }\n\n static isInstance(error: unknown): error is NoContentGeneratedError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_NoSuchModelError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchModelError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly modelId: string;\n readonly modelType:\n | 'languageModel'\n | 'textEmbeddingModel'\n | 'imageModel'\n | 'transcriptionModel'\n | 'speechModel';\n\n constructor({\n errorName = name,\n modelId,\n modelType,\n message = `No such ${modelType}: ${modelId}`,\n }: {\n errorName?: string;\n modelId: string;\n modelType:\n | 'languageModel'\n | 'textEmbeddingModel'\n | 'imageModel'\n | 'transcriptionModel'\n | 'speechModel';\n message?: string;\n }) {\n super({ name: errorName, message });\n\n this.modelId = modelId;\n this.modelType = modelType;\n }\n\n static isInstance(error: unknown): error is NoSuchModelError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_TooManyEmbeddingValuesForCallError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class TooManyEmbeddingValuesForCallError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly provider: string;\n readonly modelId: string;\n readonly maxEmbeddingsPerCall: number;\n readonly values: Array<unknown>;\n\n constructor(options: {\n provider: string;\n modelId: string;\n maxEmbeddingsPerCall: number;\n values: Array<unknown>;\n }) {\n super({\n name,\n message:\n `Too many values for a single embedding call. ` +\n `The ${options.provider} model \"${options.modelId}\" can only embed up to ` +\n `${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`,\n });\n\n this.provider = options.provider;\n this.modelId = options.modelId;\n this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n this.values = options.values;\n }\n\n static isInstance(\n error: unknown,\n ): error is TooManyEmbeddingValuesForCallError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from './ai-sdk-error';\nimport { getErrorMessage } from './get-error-message';\n\nconst name = 'AI_TypeValidationError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class TypeValidationError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly value: unknown;\n\n constructor({ value, cause }: { value: unknown; cause: unknown }) {\n super({\n name,\n message:\n `Type validation failed: ` +\n `Value: ${JSON.stringify(value)}.\\n` +\n `Error message: ${getErrorMessage(cause)}`,\n cause,\n });\n\n this.value = value;\n }\n\n static isInstance(error: unknown): error is TypeValidationError {\n return AISDKError.hasMarker(error, marker);\n }\n\n /**\n * Wraps an error into a TypeValidationError.\n * If the cause is already a TypeValidationError with the same value, it returns the cause.\n * Otherwise, it creates a new TypeValidationError.\n *\n * @param {Object} params - The parameters for wrapping the error.\n * @param {unknown} params.value - The value that failed validation.\n * @param {unknown} params.cause - The original error or cause of the validation failure.\n * @returns {TypeValidationError} A TypeValidationError instance.\n */\n static wrap({\n value,\n cause,\n }: {\n value: unknown;\n cause: unknown;\n }): TypeValidationError {\n return TypeValidationError.isInstance(cause) && cause.value === value\n ? cause\n : new TypeValidationError({ value, cause });\n }\n}\n","import { AISDKError } from './ai-sdk-error';\n\nconst name = 'AI_UnsupportedFunctionalityError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class UnsupportedFunctionalityError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly functionality: string;\n\n constructor({\n functionality,\n message = `'${functionality}' functionality not supported.`,\n }: {\n functionality: string;\n message?: string;\n }) {\n super({ name, message });\n this.functionality = functionality;\n }\n\n static isInstance(error: unknown): error is UnsupportedFunctionalityError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { JSONSchema7 } from '@ai-sdk/provider';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4';\nimport { addAdditionalPropertiesToJsonSchema } from './add-additional-properties-to-json-schema';\nimport { jsonSchema, Schema } from './schema';\nimport zodToJsonSchema from './zod-to-json-schema';\n\nexport function zod3Schema<OBJECT>(\n zodSchema: z3.Schema<OBJECT, z3.ZodTypeDef, any>,\n options?: {\n /**\n * Enables support for references in the schema.\n * This is required for recursive schemas, e.g. with `z.lazy`.\n * However, not all language models and providers support such references.\n * Defaults to `false`.\n */\n useReferences?: boolean;\n },\n): Schema<OBJECT> {\n // default to no references (to support openapi conversion for google)\n const useReferences = options?.useReferences ?? false;\n\n return jsonSchema(\n // defer json schema creation to avoid unnecessary computation when only validation is needed\n () =>\n zodToJsonSchema(zodSchema, {\n $refStrategy: useReferences ? 'root' : 'none',\n }) as JSONSchema7,\n {\n validate: async value => {\n const result = await zodSchema.safeParseAsync(value);\n return result.success\n ? { success: true, value: result.data }\n : { success: false, error: result.error };\n },\n },\n );\n}\n\nexport function zod4Schema<OBJECT>(\n zodSchema: z4.core.$ZodType<OBJECT, any>,\n options?: {\n /**\n * Enables support for references in the schema.\n * This is required for recursive schemas, e.g. with `z.lazy`.\n * However, not all language models and providers support such references.\n * Defaults to `false`.\n */\n useReferences?: boolean;\n },\n): Schema<OBJECT> {\n // default to no references (to support openapi conversion for google)\n const useReferences = options?.useReferences ?? false;\n\n return jsonSchema(\n // defer json schema creation to avoid unnecessary computation when only validation is needed\n () =>\n addAdditionalPropertiesToJsonSchema(\n z4.toJSONSchema(zodSchema, {\n target: 'draft-7',\n io: 'input',\n reused: useReferences ? 'ref' : 'inline',\n }) as JSONSchema7,\n ),\n {\n validate: async value => {\n const result = await z4.safeParseAsync(zodSchema, value);\n return result.success\n ? { success: true, value: result.data }\n : { success: false, error: result.error };\n },\n },\n );\n}\n\nexport function isZod4Schema(\n zodSchema: z4.core.$ZodType<any, any> | z3.Schema<any, z3.ZodTypeDef, any>,\n): zodSchema is z4.core.$ZodType<any, any> {\n // https://zod.dev/library-authors?id=how-to-support-zod-3-and-zod-4-simultaneously\n return '_zod' in zodSchema;\n}\n\nexport function zodSchema<OBJECT>(\n zodSchema:\n | z4.core.$ZodType<OBJECT, any>\n | z3.Schema<OBJECT, z3.ZodTypeDef, any>,\n options?: {\n /**\n * Enables support for references in the schema.\n * This is required for recursive schemas, e.g. with `z.lazy`.\n * However, not all language models and providers support such references.\n * Defaults to `false`.\n */\n useReferences?: boolean;\n },\n): Schema<OBJECT> {\n if (isZod4Schema(zodSchema)) {\n return zod4Schema(zodSchema, options);\n } else {\n return zod3Schema(zodSchema, options);\n }\n}\n","import { ZodFirstPartyTypeKind } from 'zod/v3';\nimport { parseAnyDef } from './parsers/any';\nimport { parseArrayDef } from './parsers/array';\nimport { parseBigintDef } from './parsers/bigint';\nimport { parseBooleanDef } from './parsers/boolean';\nimport { parseBrandedDef } from './parsers/branded';\nimport { parseCatchDef } from './parsers/catch';\nimport { parseDateDef } from './parsers/date';\nimport { parseDefaultDef } from './parsers/default';\nimport { parseEffectsDef } from './parsers/effects';\nimport { parseEnumDef } from './parsers/enum';\nimport { parseIntersectionDef } from './parsers/intersection';\nimport { parseLiteralDef } from './parsers/literal';\nimport { parseMapDef } from './parsers/map';\nimport { parseNativeEnumDef } from './parsers/native-enum';\nimport { parseNeverDef } from './parsers/never';\nimport { parseNullDef } from './parsers/null';\nimport { parseNullableDef } from './parsers/nullable';\nimport { parseNumberDef } from './parsers/number';\nimport { parseObjectDef } from './parsers/object';\nimport { parseOptionalDef } from './parsers/optional';\nimport { parsePipelineDef } from './parsers/pipeline';\nimport { parsePromiseDef } from './parsers/promise';\nimport { parseRecordDef } from './parsers/record';\nimport { parseSetDef } from './parsers/set';\nimport { parseStringDef } from './parsers/string';\nimport { parseTupleDef } from './parsers/tuple';\nimport { parseUndefinedDef } from './parsers/undefined';\nimport { parseUnionDef } from './parsers/union';\nimport { parseUnknownDef } from './parsers/unknown';\nimport { Refs } from './refs';\nimport { parseReadonlyDef } from './parsers/readonly';\nimport { JsonSchema7Type } from './parse-types';\n\nexport type InnerDefGetter = () => any;\n\nexport const selectParser = (\n def: any,\n typeName: ZodFirstPartyTypeKind,\n refs: Refs,\n): JsonSchema7Type | undefined | InnerDefGetter => {\n switch (typeName) {\n case ZodFirstPartyTypeKind.ZodString:\n return parseStringDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNumber:\n return parseNumberDef(def);\n case ZodFirstPartyTypeKind.ZodObject:\n return parseObjectDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBigInt:\n return parseBigintDef(def);\n case ZodFirstPartyTypeKind.ZodBoolean:\n return parseBooleanDef();\n case ZodFirstPartyTypeKind.ZodDate:\n return parseDateDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUndefined:\n return parseUndefinedDef();\n case ZodFirstPartyTypeKind.ZodNull:\n return parseNullDef();\n case ZodFirstPartyTypeKind.ZodArray:\n return parseArrayDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUnion:\n case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n return parseUnionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodIntersection:\n return parseIntersectionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodTuple:\n return parseTupleDef(def, refs);\n case ZodFirstPartyTypeKind.ZodRecord:\n return parseRecordDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLiteral:\n return parseLiteralDef(def);\n case ZodFirstPartyTypeKind.ZodEnum:\n return parseEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNativeEnum:\n return parseNativeEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNullable:\n return parseNullableDef(def, refs);\n case ZodFirstPartyTypeKind.ZodOptional:\n return parseOptionalDef(def, refs);\n case ZodFirstPartyTypeKind.ZodMap:\n return parseMapDef(def, refs);\n case ZodFirstPartyTypeKind.ZodSet:\n return parseSetDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLazy:\n return () => (def as any).getter()._def;\n case ZodFirstPartyTypeKind.ZodPromise:\n return parsePromiseDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNaN:\n case ZodFirstPartyTypeKind.ZodNever:\n return parseNeverDef();\n case ZodFirstPartyTypeKind.ZodEffects:\n return parseEffectsDef(def, refs);\n case ZodFirstPartyTypeKind.ZodAny:\n return parseAnyDef();\n case ZodFirstPartyTypeKind.ZodUnknown:\n return parseUnknownDef();\n case ZodFirstPartyTypeKind.ZodDefault:\n return parseDefaultDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBranded:\n return parseBrandedDef(def, refs);\n case ZodFirstPartyTypeKind.ZodReadonly:\n return parseReadonlyDef(def, refs);\n case ZodFirstPartyTypeKind.ZodCatch:\n return parseCatchDef(def, refs);\n case ZodFirstPartyTypeKind.ZodPipeline:\n return parsePipelineDef(def, refs);\n case ZodFirstPartyTypeKind.ZodFunction:\n case ZodFirstPartyTypeKind.ZodVoid:\n case ZodFirstPartyTypeKind.ZodSymbol:\n return undefined;\n default:\n /* c8 ignore next */\n return ((_: never) => undefined)(typeName);\n }\n};\n","import { ZodArrayDef, ZodFirstPartyTypeKind } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7ArrayType = {\n type: 'array';\n items?: JsonSchema7Type;\n minItems?: number;\n maxItems?: number;\n};\n\nexport function parseArrayDef(def: ZodArrayDef, refs: Refs) {\n const res: JsonSchema7ArrayType = {\n type: 'array',\n };\n if (\n def.type?._def &&\n def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny\n ) {\n res.items = parseDef(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items'],\n });\n }\n\n if (def.minLength) {\n res.minItems = def.minLength.value;\n }\n if (def.maxLength) {\n res.maxItems = def.maxLength.value;\n }\n if (def.exactLength) {\n res.minItems = def.exactLength.value;\n res.maxItems = def.exactLength.value;\n }\n return res;\n}\n","import {\n ZodFirstPartyTypeKind,\n ZodMapDef,\n ZodRecordDef,\n ZodTypeAny,\n} from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseBrandedDef } from './branded';\nimport { JsonSchema7EnumType } from './enum';\nimport { JsonSchema7StringType, parseStringDef } from './string';\n\ntype JsonSchema7RecordPropertyNamesType =\n | Omit<JsonSchema7StringType, 'type'>\n | Omit<JsonSchema7EnumType, 'type'>;\n\nexport type JsonSchema7RecordType = {\n type: 'object';\n additionalProperties?: JsonSchema7Type | true;\n propertyNames?: JsonSchema7RecordPropertyNamesType;\n};\n\nexport function parseRecordDef(\n def: ZodRecordDef<ZodTypeAny, ZodTypeAny> | ZodMapDef,\n refs: Refs,\n): JsonSchema7RecordType {\n const schema: JsonSchema7RecordType = {\n type: 'object',\n additionalProperties:\n parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalProperties'],\n }) ?? refs.allowedAdditionalProperties,\n };\n\n if (\n def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n def.keyType._def.checks?.length\n ) {\n const { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n\n return {\n ...schema,\n propertyNames: keyType,\n };\n } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values,\n },\n };\n } else if (\n def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded &&\n def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n def.keyType._def.type._def.checks?.length\n ) {\n const { type, ...keyType } = parseBrandedDef(\n def.keyType._def,\n refs,\n ) as JsonSchema7StringType;\n\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n\n return schema;\n}\n","import { InvalidArgumentError } from '@ai-sdk/provider';\n\n/**\nCreates an ID generator.\nThe total length of the ID is the sum of the prefix, separator, and random part length.\nNot cryptographically secure.\n\n@param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.\n@param prefix - The prefix of the ID to generate. Optional.\n@param separator - The separator between the prefix and the random part of the ID. Default: '-'.\n@param size - The size of the random part of the ID to generate. Default: 16.\n */\nexport const createIdGenerator = ({\n prefix,\n size = 16,\n alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n separator = '-',\n}: {\n prefix?: string;\n separator?: string;\n size?: number;\n alphabet?: string;\n} = {}): IdGenerator => {\n const generator = () => {\n const alphabetLength = alphabet.length;\n const chars = new Array(size);\n for (let i = 0; i < size; i++) {\n chars[i] = alphabet[(Math.random() * alphabetLength) | 0];\n }\n return chars.join('');\n };\n\n if (prefix == null) {\n return generator;\n }\n\n // check that the prefix is not part of the alphabet (otherwise prefix checking can fail randomly)\n if (alphabet.includes(separator)) {\n throw new InvalidArgumentError({\n argument: 'separator',\n message: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`,\n });\n }\n\n return () => `${prefix}${separator}${generator()}`;\n};\n\n/**\nA function that generates an ID.\n */\nexport type IdGenerator = () => string;\n\n/**\nGenerates a 16-character random string to use for IDs.\nNot cryptographically secure.\n */\nexport const generateId = createIdGenerator();\n","// Licensed under BSD-3-Clause (this file only)\n// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/index.js\n//\n// Copyright (c) Vercel, Inc. (https://vercel.com)\n// Copyright (c) 2019 The Fastify Team\n// Copyright (c) 2019, Sideway Inc, and project contributors\n// All rights reserved.\n//\n// The complete list of contributors can be found at:\n// - https://github.com/hapijs/bourne/graphs/contributors\n// - https://github.com/fastify/secure-json-parse/graphs/contributors\n// - https://github.com/vercel/ai/commits/main/packages/provider-utils/src/secure-parse-json.ts\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nconst suspectProtoRx = /\"__proto__\"\\s*:/;\nconst suspectConstructorRx = /\"constructor\"\\s*:/;\n\nfunction _parse(text: string) {\n // Parse normally\n const obj = JSON.parse(text);\n\n // Ignore null and non-objects\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (\n suspectProtoRx.test(text) === false &&\n suspectConstructorRx.test(text) === false\n ) {\n return obj;\n }\n\n // Scan result for proto keys\n return filter(obj);\n}\n\nfunction filter(obj: any) {\n let next = [obj];\n\n while (next.length) {\n const nodes = next;\n next = [];\n\n for (const node of nodes) {\n if (Object.prototype.hasOwnProperty.call(node, '__proto__')) {\n throw new SyntaxError('Object contains forbidden prototype property');\n }\n\n if (\n Object.prototype.hasOwnProperty.call(node, 'constructor') &&\n Object.prototype.hasOwnProperty.call(node.constructor, 'prototype')\n ) {\n throw new SyntaxError('Object contains forbidden prototype property');\n }\n\n for (const key in node) {\n const value = node[key];\n if (value && typeof value === 'object') {\n next.push(value);\n }\n }\n }\n }\n return obj;\n}\n\nexport function secureJsonParse(text: string) {\n const { stackTraceLimit } = Error;\n try {\n // Performance optimization, see https://github.com/fastify/secure-json-parse/pull/90\n Error.stackTraceLimit = 0;\n } catch (e) {\n // Fallback in case Error is immutable (v8 readonly)\n return _parse(text);\n }\n\n try {\n return _parse(text);\n } finally {\n Error.stackTraceLimit = stackTraceLimit;\n }\n}\n","import { TypeValidationError } from '@ai-sdk/provider';\nimport { StandardSchemaV1 } from '@standard-schema/spec';\n\n/**\n * Used to mark validator functions so we can support both Zod and custom schemas.\n */\nexport const validatorSymbol = Symbol.for('vercel.ai.validator');\n\nexport type ValidationResult<OBJECT> =\n | { success: true; value: OBJECT }\n | { success: false; error: Error };\n\nexport type Validator<OBJECT = unknown> = {\n /**\n * Used to mark validator functions so we can support both Zod and custom schemas.\n */\n [validatorSymbol]: true;\n\n /**\n * Optional. Validates that the structure of a value matches this schema,\n * and returns a typed version of the value if it does.\n */\n readonly validate?: (\n value: unknown,\n ) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;\n};\n\n/**\n * Create a validator.\n *\n * @param validate A validation function for the schema.\n */\nexport function validator<OBJECT>(\n validate?:\n | undefined\n | ((\n value: unknown,\n ) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>),\n): Validator<OBJECT> {\n return { [validatorSymbol]: true, validate };\n}\n\nexport function isValidator(value: unknown): value is Validator {\n return (\n typeof value === 'object' &&\n value !== null &&\n validatorSymbol in value &&\n value[validatorSymbol] === true &&\n 'validate' in value\n );\n}\n\n/**\n * Creates a validator with deferred creation.\n * This is important to reduce the startup time of the library\n * and to avoid initializing unused validators.\n *\n * @param createValidator A function that creates a validator.\n * @returns A function that returns a validator.\n */\nexport function lazyValidator<OBJECT>(\n createValidator: () => Validator<OBJECT>,\n): LazyValidator<OBJECT> {\n // cache the validator to avoid initializing it multiple times\n let validator: Validator<OBJECT> | undefined;\n return () => {\n if (validator == null) {\n validator = createValidator();\n }\n return validator;\n };\n}\n\nexport type LazyValidator<OBJECT> = () => Validator<OBJECT>;\n\nexport type FlexibleValidator<OBJECT> =\n | Validator<OBJECT>\n | LazyValidator<OBJECT>\n | StandardSchemaV1<unknown, OBJECT>;\n\nexport type InferValidator<SCHEMA> =\n SCHEMA extends StandardSchemaV1<unknown, infer T>\n ? T\n : SCHEMA extends LazyValidator<infer T>\n ? T\n : SCHEMA extends Validator<infer T>\n ? T\n : never;\n\nexport function asValidator<OBJECT>(\n value: FlexibleValidator<OBJECT>,\n): Validator<OBJECT> {\n return isValidator(value)\n ? value\n : typeof value === 'function'\n ? value()\n : standardSchemaValidator(value);\n}\n\nexport function standardSchemaValidator<OBJECT>(\n standardSchema: StandardSchemaV1<unknown, OBJECT>,\n): Validator<OBJECT> {\n return validator(async value => {\n const result = await standardSchema['~standard'].validate(value);\n\n return result.issues == null\n ? { success: true, value: result.value }\n : {\n success: false,\n error: new TypeValidationError({\n value,\n cause: result.issues,\n }),\n };\n });\n}\n","import { TypeValidationError } from '@ai-sdk/provider';\nimport { FlexibleValidator, asValidator } from './validator';\n\n/**\n * Validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The object to validate.\n * @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n * @returns {Promise<T>} - The typed object.\n */\nexport async function validateTypes<OBJECT>({\n value,\n schema,\n}: {\n value: unknown;\n schema: FlexibleValidator<OBJECT>;\n}): Promise<OBJECT> {\n const result = await safeValidateTypes({ value, schema });\n\n if (!result.success) {\n throw TypeValidationError.wrap({ value, cause: result.error });\n }\n\n return result.value;\n}\n\n/**\n * Safely validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The JSON object to validate.\n * @param {Validator<T>} options.schema - The schema to use for validating the JSON.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport async function safeValidateTypes<OBJECT>({\n value,\n schema,\n}: {\n value: unknown;\n schema: FlexibleValidator<OBJECT>;\n}): Promise<\n | {\n success: true;\n value: OBJECT;\n rawValue: unknown;\n }\n | {\n success: false;\n error: TypeValidationError;\n rawValue: unknown;\n }\n> {\n const validator = asValidator(schema);\n\n try {\n if (validator.validate == null) {\n return { success: true, value: value as OBJECT, rawValue: value };\n }\n\n const result = await validator.validate(value);\n\n if (result.success) {\n return { success: true, value: result.value, rawValue: value };\n }\n\n return {\n success: false,\n error: TypeValidationError.wrap({ value, cause: result.error }),\n rawValue: value,\n };\n } catch (error) {\n return {\n success: false,\n error: TypeValidationError.wrap({ value, cause: error }),\n rawValue: value,\n };\n }\n}\n","import {\n JSONParseError,\n JSONValue,\n TypeValidationError,\n} from '@ai-sdk/provider';\nimport { secureJsonParse } from './secure-json-parse';\nimport { safeValidateTypes, validateTypes } from './validate-types';\nimport { FlexibleValidator, Validator } from './validator';\n\n/**\n * Parses a JSON string into an unknown object.\n *\n * @param text - The JSON string to parse.\n * @returns {JSONValue} - The parsed JSON object.\n */\nexport async function parseJSON(options: {\n text: string;\n schema?: undefined;\n}): Promise<JSONValue>;\n/**\n * Parses a JSON string into a strongly-typed object using the provided schema.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns {Promise<T>} - The parsed object.\n */\nexport async function parseJSON<T>(options: {\n text: string;\n schema: FlexibleValidator<T>;\n}): Promise<T>;\nexport async function parseJSON<T>({\n text,\n schema,\n}: {\n text: string;\n schema?: FlexibleValidator<T>;\n}): Promise<T> {\n try {\n const value = secureJsonParse(text);\n\n if (schema == null) {\n return value;\n }\n\n return validateTypes<T>({ value, schema });\n } catch (error) {\n if (\n JSONParseError.isInstance(error) ||\n TypeValidationError.isInstance(error)\n ) {\n throw error;\n }\n\n throw new JSONParseError({ text, cause: error });\n }\n}\n\nexport type ParseResult<T> =\n | { success: true; value: T; rawValue: unknown }\n | {\n success: false;\n error: JSONParseError | TypeValidationError;\n rawValue: unknown;\n };\n\n/**\n * Safely parses a JSON string and returns the result as an object of type `unknown`.\n *\n * @param text - The JSON string to parse.\n * @returns {Promise<object>} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.\n */\nexport async function safeParseJSON(options: {\n text: string;\n schema?: undefined;\n}): Promise<ParseResult<JSONValue>>;\n/**\n * Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Validator<T>} schema - The schema to use for parsing the JSON.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport async function safeParseJSON<T>(options: {\n text: string;\n schema: FlexibleValidator<T>;\n}): Promise<ParseResult<T>>;\nexport async function safeParseJSON<T>({\n text,\n schema,\n}: {\n text: string;\n schema?: FlexibleValidator<T>;\n}): Promise<ParseResult<T>> {\n try {\n const value = secureJsonParse(text);\n\n if (schema == null) {\n return { success: true, value: value as T, rawValue: value };\n }\n\n return await safeValidateTypes<T>({ value, schema });\n } catch (error) {\n return {\n success: false,\n error: JSONParseError.isInstance(error)\n ? error\n : new JSONParseError({ text, cause: error }),\n rawValue: undefined,\n };\n }\n}\n\nexport function isParsableJson(input: string): boolean {\n try {\n secureJsonParse(input);\n return true;\n } catch {\n return false;\n }\n}\n","import { JSONSchema7 } from '@ai-sdk/provider';\n\n/**\n * Recursively adds additionalProperties: false to the JSON schema. This is necessary because some providers (e.g. OpenAI) do not support additionalProperties: true.\n */\nexport function addAdditionalPropertiesToJsonSchema(\n jsonSchema: JSONSchema7,\n): JSONSchema7 {\n if (jsonSchema.type === 'object') {\n jsonSchema.additionalProperties = false;\n const properties = jsonSchema.properties;\n if (properties != null) {\n for (const property in properties) {\n properties[property] = addAdditionalPropertiesToJsonSchema(\n properties[property] as JSONSchema7,\n );\n }\n }\n }\n if (jsonSchema.type === 'array' && jsonSchema.items != null) {\n if (Array.isArray(jsonSchema.items)) {\n jsonSchema.items = jsonSchema.items.map(item =>\n addAdditionalPropertiesToJsonSchema(item as JSONSchema7),\n );\n } else {\n jsonSchema.items = addAdditionalPropertiesToJsonSchema(\n jsonSchema.items as JSONSchema7,\n );\n }\n }\n return jsonSchema;\n}\n","export const getRelativePath = (pathA: string[], pathB: string[]) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i]) break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/');\n};\n","import { ZodSchema, ZodTypeDef } from 'zod/v3';\nimport { Refs, Seen } from './refs';\nimport { JsonSchema7Type } from './parse-types';\n\nexport type DateStrategy =\n | 'format:date-time'\n | 'format:date'\n | 'string'\n | 'integer';\n\nexport const ignoreOverride = Symbol(\n 'Let zodToJsonSchema decide on which parser to use',\n);\n\nexport type OverrideCallback = (\n def: ZodTypeDef,\n refs: Refs,\n seen: Seen | undefined,\n forceResolution?: boolean,\n) => JsonSchema7Type | undefined | typeof ignoreOverride;\n\nexport type PostProcessCallback = (\n jsonSchema: JsonSchema7Type | undefined,\n def: ZodTypeDef,\n refs: Refs,\n) => JsonSchema7Type | undefined;\n\nexport const jsonDescription: PostProcessCallback = (jsonSchema, def) => {\n if (def.description) {\n try {\n return {\n ...jsonSchema,\n ...JSON.parse(def.description),\n };\n } catch {}\n }\n\n return jsonSchema;\n};\n\nexport type Options = {\n name: string | undefined;\n $refStrategy: 'root' | 'relative' | 'none' | 'seen';\n basePath: string[];\n effectStrategy: 'input' | 'any';\n pipeStrategy: 'input' | 'output' | 'all';\n dateStrategy: DateStrategy | DateStrategy[];\n mapStrategy: 'entries' | 'record';\n removeAdditionalStrategy: 'passthrough' | 'strict';\n allowedAdditionalProperties: true | undefined;\n rejectedAdditionalProperties: false | undefined;\n strictUnions: boolean;\n definitionPath: string;\n definitions: Record<string, ZodSchema>;\n errorMessages: boolean;\n patternStrategy: 'escape' | 'preserve';\n applyRegexFlags: boolean;\n emailStrategy: 'format:email' | 'format:idn-email' | 'pattern:zod';\n base64Strategy: 'format:binary' | 'contentEncoding:base64' | 'pattern:zod';\n nameStrategy: 'ref' | 'title';\n override?: OverrideCallback;\n postProcess?: PostProcessCallback;\n};\n\nexport const defaultOptions: Options = {\n name: undefined,\n $refStrategy: 'root',\n basePath: ['#'],\n effectStrategy: 'input',\n pipeStrategy: 'all',\n dateStrategy: 'format:date-time',\n mapStrategy: 'entries',\n removeAdditionalStrategy: 'passthrough',\n allowedAdditionalProperties: true,\n rejectedAdditionalProperties: false,\n definitionPath: 'definitions',\n strictUnions: false,\n definitions: {},\n errorMessages: false,\n patternStrategy: 'escape',\n applyRegexFlags: false,\n emailStrategy: 'format:email',\n base64Strategy: 'contentEncoding:base64',\n nameStrategy: 'ref',\n};\n\nexport const getDefaultOptions = (\n options: Partial<Options> | string | undefined,\n) =>\n (typeof options === 'string'\n ? {\n ...defaultOptions,\n name: options,\n }\n : {\n ...defaultOptions,\n ...options,\n }) as Options;\n","export type JsonSchema7AnyType = { $ref?: string };\n\nexport function parseAnyDef(): JsonSchema7AnyType {\n return {};\n}\n","import { ZodBigIntDef } from 'zod/v3';\n\nexport type JsonSchema7BigintType = {\n type: 'integer';\n format: 'int64';\n minimum?: BigInt;\n exclusiveMinimum?: BigInt;\n maximum?: BigInt;\n exclusiveMaximum?: BigInt;\n multipleOf?: BigInt;\n};\n\nexport function parseBigintDef(def: ZodBigIntDef): JsonSchema7BigintType {\n const res: JsonSchema7BigintType = {\n type: 'integer',\n format: 'int64',\n };\n\n if (!def.checks) return res;\n\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n if (check.inclusive) {\n res.minimum = check.value;\n } else {\n res.exclusiveMinimum = check.value;\n }\n break;\n case 'max':\n if (check.inclusive) {\n res.maximum = check.value;\n } else {\n res.exclusiveMaximum = check.value;\n }\n\n break;\n case 'multipleOf':\n res.multipleOf = check.value;\n break;\n }\n }\n return res;\n}\n","export type JsonSchema7BooleanType = {\n type: 'boolean';\n};\n\nexport function parseBooleanDef(): JsonSchema7BooleanType {\n return { type: 'boolean' };\n}\n","import { ZodBrandedDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { Refs } from '../refs';\n\nexport function parseBrandedDef(_def: ZodBrandedDef<any>, refs: Refs) {\n return parseDef(_def.type._def, refs);\n}\n","import { ZodCatchDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { Refs } from '../refs';\n\nexport const parseCatchDef = (def: ZodCatchDef<any>, refs: Refs) => {\n return parseDef(def.innerType._def, refs);\n};\n","import { ZodDateDef } from 'zod/v3';\nimport { Refs } from '../refs';\nimport { DateStrategy } from '../options';\n\nexport type JsonSchema7DateType =\n | {\n type: 'integer' | 'string';\n format: 'unix-time' | 'date-time' | 'date';\n minimum?: number;\n maximum?: number;\n }\n | {\n anyOf: JsonSchema7DateType[];\n };\n\nexport function parseDateDef(\n def: ZodDateDef,\n refs: Refs,\n overrideDateStrategy?: DateStrategy,\n): JsonSchema7DateType {\n const strategy = overrideDateStrategy ?? refs.dateStrategy;\n\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n };\n }\n\n switch (strategy) {\n case 'string':\n case 'format:date-time':\n return {\n type: 'string',\n format: 'date-time',\n };\n case 'format:date':\n return {\n type: 'string',\n format: 'date',\n };\n case 'integer':\n return integerDateParser(def);\n }\n}\n\nconst integerDateParser = (def: ZodDateDef) => {\n const res: JsonSchema7DateType = {\n type: 'integer',\n format: 'unix-time',\n };\n\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n res.minimum = check.value;\n break;\n case 'max':\n res.maximum = check.value;\n break;\n }\n }\n\n return res;\n};\n","import { ZodDefaultDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport function parseDefaultDef(\n _def: ZodDefaultDef,\n refs: Refs,\n): JsonSchema7Type & { default: any } {\n return {\n ...parseDef(_def.innerType._def, refs),\n default: _def.defaultValue(),\n };\n}\n","import { ZodEffectsDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseAnyDef } from './any';\n\nexport function parseEffectsDef(\n _def: ZodEffectsDef,\n refs: Refs,\n): JsonSchema7Type | undefined {\n return refs.effectStrategy === 'input'\n ? parseDef(_def.schema._def, refs)\n : parseAnyDef();\n}\n","import { ZodEnumDef } from 'zod/v3';\n\nexport type JsonSchema7EnumType = {\n type: 'string';\n enum: string[];\n};\n\nexport function parseEnumDef(def: ZodEnumDef): JsonSchema7EnumType {\n return {\n type: 'string',\n enum: Array.from(def.values),\n };\n}\n","import { ZodIntersectionDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { JsonSchema7StringType } from './string';\n\nexport type JsonSchema7AllOfType = {\n allOf: JsonSchema7Type[];\n unevaluatedProperties?: boolean;\n};\n\nconst isJsonSchema7AllOfType = (\n type: JsonSchema7Type | JsonSchema7StringType,\n): type is JsonSchema7AllOfType => {\n if ('type' in type && type.type === 'string') return false;\n return 'allOf' in type;\n};\n\nexport function parseIntersectionDef(\n def: ZodIntersectionDef,\n refs: Refs,\n): JsonSchema7AllOfType | JsonSchema7Type | undefined {\n const allOf = [\n parseDef(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '0'],\n }),\n parseDef(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '1'],\n }),\n ].filter((x): x is JsonSchema7Type => !!x);\n\n const mergedAllOf: JsonSchema7Type[] = [];\n // If either of the schemas is an allOf, merge them into a single allOf\n allOf.forEach(schema => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n } else {\n let nestedSchema: JsonSchema7Type = schema;\n if (\n 'additionalProperties' in schema &&\n schema.additionalProperties === false\n ) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length ? { allOf: mergedAllOf } : undefined;\n}\n","import { ZodLiteralDef } from 'zod/v3';\n\nexport type JsonSchema7LiteralType =\n | {\n type: 'string' | 'number' | 'integer' | 'boolean';\n const: string | number | boolean;\n }\n | {\n type: 'object' | 'array';\n };\n\nexport function parseLiteralDef(def: ZodLiteralDef): JsonSchema7LiteralType {\n const parsedType = typeof def.value;\n if (\n parsedType !== 'bigint' &&\n parsedType !== 'number' &&\n parsedType !== 'boolean' &&\n parsedType !== 'string'\n ) {\n return {\n type: Array.isArray(def.value) ? 'array' : 'object',\n };\n }\n\n return {\n type: parsedType === 'bigint' ? 'integer' : parsedType,\n const: def.value,\n };\n}\n","import { ZodStringDef } from 'zod/v3';\nimport { Refs } from '../refs';\n\nlet emojiRegex: RegExp | undefined = undefined;\n\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email:\n /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === undefined) {\n emojiRegex = RegExp(\n '^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$',\n 'u',\n );\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n ipv4Cidr:\n /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n ipv6Cidr:\n /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n base64url:\n /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n} as const;\n\nexport type JsonSchema7StringType = {\n type: 'string';\n minLength?: number;\n maxLength?: number;\n format?:\n | 'email'\n | 'idn-email'\n | 'uri'\n | 'uuid'\n | 'date-time'\n | 'ipv4'\n | 'ipv6'\n | 'date'\n | 'time'\n | 'duration';\n pattern?: string;\n allOf?: {\n pattern: string;\n }[];\n anyOf?: {\n format: string;\n }[];\n contentEncoding?: string;\n};\n\nexport function parseStringDef(\n def: ZodStringDef,\n refs: Refs,\n): JsonSchema7StringType {\n const res: JsonSchema7StringType = {\n type: 'string',\n };\n\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case 'min':\n res.minLength =\n typeof res.minLength === 'number'\n ? Math.max(res.minLength, check.value)\n : check.value;\n break;\n case 'max':\n res.maxLength =\n typeof res.maxLength === 'number'\n ? Math.min(res.maxLength, check.value)\n : check.value;\n\n break;\n case 'email':\n switch (refs.emailStrategy) {\n case 'format:email':\n addFormat(res, 'email', check.message, refs);\n break;\n case 'format:idn-email':\n addFormat(res, 'idn-email', check.message, refs);\n break;\n case 'pattern:zod':\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n\n break;\n case 'url':\n addFormat(res, 'uri', check.message, refs);\n break;\n case 'uuid':\n addFormat(res, 'uuid', check.message, refs);\n break;\n case 'regex':\n addPattern(res, check.regex, check.message, refs);\n break;\n case 'cuid':\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case 'cuid2':\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case 'startsWith':\n addPattern(\n res,\n RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),\n check.message,\n refs,\n );\n break;\n case 'endsWith':\n addPattern(\n res,\n RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),\n check.message,\n refs,\n );\n break;\n case 'datetime':\n addFormat(res, 'date-time', check.message, refs);\n break;\n case 'date':\n addFormat(res, 'date', check.message, refs);\n break;\n case 'time':\n addFormat(res, 'time', check.message, refs);\n break;\n case 'duration':\n addFormat(res, 'duration', check.message, refs);\n break;\n case 'length':\n res.minLength =\n typeof res.minLength === 'number'\n ? Math.max(res.minLength, check.value)\n : check.value;\n res.maxLength =\n typeof res.maxLength === 'number'\n ? Math.min(res.maxLength, check.value)\n : check.value;\n break;\n case 'includes': {\n addPattern(\n res,\n RegExp(escapeLiteralCheckValue(check.value, refs)),\n check.message,\n refs,\n );\n break;\n }\n case 'ip': {\n if (check.version !== 'v6') {\n addFormat(res, 'ipv4', check.message, refs);\n }\n if (check.version !== 'v4') {\n addFormat(res, 'ipv6', check.message, refs);\n }\n break;\n }\n case 'base64url':\n addPattern(res, zodPatterns.base64url, check.message, refs);\n break;\n case 'jwt':\n addPattern(res, zodPatterns.jwt, check.message, refs);\n break;\n case 'cidr': {\n if (check.version !== 'v6') {\n addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n }\n if (check.version !== 'v4') {\n addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n }\n break;\n }\n case 'emoji':\n addPattern(res, zodPatterns.emoji(), check.message, refs);\n break;\n case 'ulid': {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case 'base64': {\n switch (refs.base64Strategy) {\n case 'format:binary': {\n addFormat(res, 'binary' as any, check.message, refs);\n break;\n }\n\n case 'contentEncoding:base64': {\n res.contentEncoding = 'base64';\n break;\n }\n\n case 'pattern:zod': {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case 'nanoid': {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case 'toLowerCase':\n case 'toUpperCase':\n case 'trim':\n break;\n default:\n /* c8 ignore next */\n ((_: never) => {})(check);\n }\n }\n }\n\n return res;\n}\n\nfunction escapeLiteralCheckValue(literal: string, refs: Refs): string {\n return refs.patternStrategy === 'escape'\n ? escapeNonAlphaNumeric(literal)\n : literal;\n}\n\nconst ALPHA_NUMERIC = new Set(\n 'ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789',\n);\n\nfunction escapeNonAlphaNumeric(source: string) {\n let result = '';\n\n for (let i = 0; i < source.length; i++) {\n if (!ALPHA_NUMERIC.has(source[i])) {\n result += '\\\\';\n }\n\n result += source[i];\n }\n\n return result;\n}\n\n// Adds a \"format\" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.\nfunction addFormat(\n schema: JsonSchema7StringType,\n value: Required<JsonSchema7StringType>['format'],\n message: string | undefined,\n refs: Refs,\n) {\n if (schema.format || schema.anyOf?.some(x => x.format)) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n\n if (schema.format) {\n schema.anyOf!.push({\n format: schema.format,\n });\n delete schema.format;\n }\n\n schema.anyOf!.push({\n format: value,\n ...(message &&\n refs.errorMessages && { errorMessage: { format: message } }),\n });\n } else {\n schema.format = value;\n }\n}\n\n// Adds a \"pattern\" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.\nfunction addPattern(\n schema: JsonSchema7StringType,\n regex: RegExp,\n message: string | undefined,\n refs: Refs,\n) {\n if (schema.pattern || schema.allOf?.some(x => x.pattern)) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n\n if (schema.pattern) {\n schema.allOf!.push({\n pattern: schema.pattern,\n });\n delete schema.pattern;\n }\n\n schema.allOf!.push({\n pattern: stringifyRegExpWithFlags(regex, refs),\n ...(message &&\n refs.errorMessages && { errorMessage: { pattern: message } }),\n });\n } else {\n schema.pattern = stringifyRegExpWithFlags(regex, refs);\n }\n}\n\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nfunction stringifyRegExpWithFlags(regex: RegExp, refs: Refs): string {\n if (!refs.applyRegexFlags || !regex.flags) {\n return regex.source;\n }\n\n // Currently handled flags\n const flags = {\n i: regex.flags.includes('i'), // Case-insensitive\n m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters\n s: regex.flags.includes('s'), // `.` matches newlines\n };\n\n // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = '';\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n } else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) {\n pattern += source[i];\n inCharRange = true;\n } else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n } else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n\n if (flags.m) {\n if (source[i] === '^') {\n pattern += `(^|(?<=[\\r\\n]))`;\n continue;\n } else if (source[i] === '$') {\n pattern += `($|(?=[\\r\\n]))`;\n continue;\n }\n }\n\n if (flags.s && source[i] === '.') {\n pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n continue;\n }\n\n pattern += source[i];\n if (source[i] === '\\\\') {\n isEscaped = true;\n } else if (inCharGroup && source[i] === ']') {\n inCharGroup = false;\n } else if (!inCharGroup && source[i] === '[') {\n inCharGroup = true;\n }\n }\n\n try {\n new RegExp(pattern);\n } catch {\n console.warn(\n `Could not convert regex pattern at ${refs.currentPath.join(\n '/',\n )} to a flag-independent form! Falling back to the flag-ignorant source`,\n );\n return regex.source;\n }\n\n return pattern;\n}\n","import { ZodMapDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseAnyDef } from './any';\nimport { JsonSchema7RecordType, parseRecordDef } from './record';\n\nexport type JsonSchema7MapType = {\n type: 'array';\n maxItems: 125;\n items: {\n type: 'array';\n items: [JsonSchema7Type, JsonSchema7Type];\n minItems: 2;\n maxItems: 2;\n };\n};\n\nexport function parseMapDef(\n def: ZodMapDef,\n refs: Refs,\n): JsonSchema7MapType | JsonSchema7RecordType {\n if (refs.mapStrategy === 'record') {\n return parseRecordDef(def, refs);\n }\n\n const keys =\n parseDef(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', 'items', '0'],\n }) || parseAnyDef();\n const values =\n parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', 'items', '1'],\n }) || parseAnyDef();\n return {\n type: 'array',\n maxItems: 125,\n items: {\n type: 'array',\n items: [keys, values],\n minItems: 2,\n maxItems: 2,\n },\n };\n}\n","import { ZodNativeEnumDef } from 'zod/v3';\n\nexport type JsonSchema7NativeEnumType = {\n type: 'string' | 'number' | ['string', 'number'];\n enum: (string | number)[];\n};\n\nexport function parseNativeEnumDef(\n def: ZodNativeEnumDef,\n): JsonSchema7NativeEnumType {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key: string) => {\n return typeof object[object[key]] !== 'number';\n });\n\n const actualValues = actualKeys.map((key: string) => object[key]);\n\n const parsedTypes = Array.from(\n new Set(actualValues.map((values: string | number) => typeof values)),\n );\n\n return {\n type:\n parsedTypes.length === 1\n ? parsedTypes[0] === 'string'\n ? 'string'\n : 'number'\n : ['string', 'number'],\n enum: actualValues,\n };\n}\n","import { JsonSchema7AnyType, parseAnyDef } from './any';\n\nexport type JsonSchema7NeverType = {\n not: JsonSchema7AnyType;\n};\n\nexport function parseNeverDef(): JsonSchema7NeverType | undefined {\n return { not: parseAnyDef() };\n}\n","export type JsonSchema7NullType = {\n type: 'null';\n};\n\nexport function parseNullDef(): JsonSchema7NullType {\n return {\n type: 'null',\n };\n}\n","import {\n ZodDiscriminatedUnionDef,\n ZodLiteralDef,\n ZodTypeAny,\n ZodUnionDef,\n} from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport const primitiveMappings = {\n ZodString: 'string',\n ZodNumber: 'number',\n ZodBigInt: 'integer',\n ZodBoolean: 'boolean',\n ZodNull: 'null',\n} as const;\ntype ZodPrimitive = keyof typeof primitiveMappings;\ntype JsonSchema7Primitive =\n (typeof primitiveMappings)[keyof typeof primitiveMappings];\n\nexport type JsonSchema7UnionType =\n | JsonSchema7PrimitiveUnionType\n | JsonSchema7AnyOfType;\n\ntype JsonSchema7PrimitiveUnionType =\n | {\n type: JsonSchema7Primitive | JsonSchema7Primitive[];\n }\n | {\n type: JsonSchema7Primitive | JsonSchema7Primitive[];\n enum: (string | number | bigint | boolean | null)[];\n };\n\ntype JsonSchema7AnyOfType = {\n anyOf: JsonSchema7Type[];\n};\n\nexport function parseUnionDef(\n def: ZodUnionDef | ZodDiscriminatedUnionDef<any, any>,\n refs: Refs,\n): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined {\n const options: readonly ZodTypeAny[] =\n def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n\n // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n if (\n options.every(\n x =>\n x._def.typeName in primitiveMappings &&\n (!x._def.checks || !x._def.checks.length),\n )\n ) {\n // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n\n const types = options.reduce((types: JsonSchema7Primitive[], x) => {\n const type = primitiveMappings[x._def.typeName as ZodPrimitive]; //Can be safely casted due to row 43\n return type && !types.includes(type) ? [...types, type] : types;\n }, []);\n\n return {\n type: types.length > 1 ? types : types[0],\n };\n } else if (\n options.every(x => x._def.typeName === 'ZodLiteral' && !x.description)\n ) {\n // all options literals\n\n const types = options.reduce(\n (acc: JsonSchema7Primitive[], x: { _def: ZodLiteralDef }) => {\n const type = typeof x._def.value;\n switch (type) {\n case 'string':\n case 'number':\n case 'boolean':\n return [...acc, type];\n case 'bigint':\n return [...acc, 'integer' as const];\n case 'object':\n if (x._def.value === null) return [...acc, 'null' as const];\n case 'symbol':\n case 'undefined':\n case 'function':\n default:\n return acc;\n }\n },\n [],\n );\n\n if (types.length === options.length) {\n // all the literals are primitive, as far as null can be considered primitive\n\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce(\n (acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n },\n [] as (string | number | bigint | boolean | null)[],\n ),\n };\n }\n } else if (options.every(x => x._def.typeName === 'ZodEnum')) {\n return {\n type: 'string',\n enum: options.reduce(\n (acc: string[], x) => [\n ...acc,\n ...x._def.values.filter((x: string) => !acc.includes(x)),\n ],\n [],\n ),\n };\n }\n\n return asAnyOf(def, refs);\n}\n\nconst asAnyOf = (\n def: ZodUnionDef | ZodDiscriminatedUnionDef<any, any>,\n refs: Refs,\n): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined => {\n const anyOf = (\n (def.options instanceof Map\n ? Array.from(def.options.values())\n : def.options) as any[]\n )\n .map((x, i) =>\n parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', `${i}`],\n }),\n )\n .filter(\n (x): x is JsonSchema7Type =>\n !!x &&\n (!refs.strictUnions ||\n (typeof x === 'object' && Object.keys(x).length > 0)),\n );\n\n return anyOf.length ? { anyOf } : undefined;\n};\n","import { ZodNullableDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { JsonSchema7NullType } from './null';\nimport { primitiveMappings } from './union';\n\nexport type JsonSchema7NullableType =\n | {\n anyOf: [JsonSchema7Type, JsonSchema7NullType];\n }\n | {\n type: [string, 'null'];\n };\n\nexport function parseNullableDef(\n def: ZodNullableDef,\n refs: Refs,\n): JsonSchema7NullableType | undefined {\n if (\n ['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(\n def.innerType._def.typeName,\n ) &&\n (!def.innerType._def.checks || !def.innerType._def.checks.length)\n ) {\n return {\n type: [\n primitiveMappings[\n def.innerType._def.typeName as keyof typeof primitiveMappings\n ],\n 'null',\n ],\n };\n }\n\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', '0'],\n });\n\n return base && { anyOf: [base, { type: 'null' }] };\n}\n","import { ZodNumberDef } from 'zod/v3';\n\nexport type JsonSchema7NumberType = {\n type: 'number' | 'integer';\n minimum?: number;\n exclusiveMinimum?: number;\n maximum?: number;\n exclusiveMaximum?: number;\n multipleOf?: number;\n};\n\nexport function parseNumberDef(def: ZodNumberDef): JsonSchema7NumberType {\n const res: JsonSchema7NumberType = {\n type: 'number',\n };\n\n if (!def.checks) return res;\n\n for (const check of def.checks) {\n switch (check.kind) {\n case 'int':\n res.type = 'integer';\n break;\n case 'min':\n if (check.inclusive) {\n res.minimum = check.value;\n } else {\n res.exclusiveMinimum = check.value;\n }\n break;\n case 'max':\n if (check.inclusive) {\n res.maximum = check.value;\n } else {\n res.exclusiveMaximum = check.value;\n }\n break;\n case 'multipleOf':\n res.multipleOf = check.value;\n break;\n }\n }\n return res;\n}\n","import { ZodObjectDef, ZodTypeAny } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7ObjectType = {\n type: 'object';\n properties: Record<string, JsonSchema7Type>;\n additionalProperties?: boolean | JsonSchema7Type;\n required?: string[];\n};\n\nexport function parseObjectDef(def: ZodObjectDef, refs: Refs) {\n const result: JsonSchema7ObjectType = {\n type: 'object',\n properties: {},\n };\n\n const required: string[] = [];\n\n const shape = def.shape();\n\n for (const propName in shape) {\n let propDef = shape[propName];\n\n if (propDef === undefined || propDef._def === undefined) {\n continue;\n }\n\n const propOptional = safeIsOptional(propDef);\n\n const parsedDef = parseDef(propDef._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'properties', propName],\n propertyPath: [...refs.currentPath, 'properties', propName],\n });\n\n if (parsedDef === undefined) {\n continue;\n }\n\n result.properties[propName] = parsedDef;\n\n if (!propOptional) {\n required.push(propName);\n }\n }\n\n if (required.length) {\n result.required = required;\n }\n\n const additionalProperties = decideAdditionalProperties(def, refs);\n\n if (additionalProperties !== undefined) {\n result.additionalProperties = additionalProperties;\n }\n\n return result;\n}\n\nfunction decideAdditionalProperties(def: ZodObjectDef, refs: Refs) {\n if (def.catchall._def.typeName !== 'ZodNever') {\n return parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalProperties'],\n });\n }\n\n switch (def.unknownKeys) {\n case 'passthrough':\n return refs.allowedAdditionalProperties;\n case 'strict':\n return refs.rejectedAdditionalProperties;\n case 'strip':\n return refs.removeAdditionalStrategy === 'strict'\n ? refs.allowedAdditionalProperties\n : refs.rejectedAdditionalProperties;\n }\n}\n\nfunction safeIsOptional(schema: ZodTypeAny): boolean {\n try {\n return schema.isOptional();\n } catch {\n return true;\n }\n}\n","import { ZodOptionalDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { parseAnyDef } from './any';\n\nexport const parseOptionalDef = (\n def: ZodOptionalDef,\n refs: Refs,\n): JsonSchema7Type | undefined => {\n if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n return parseDef(def.innerType._def, refs);\n }\n\n const innerSchema = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'anyOf', '1'],\n });\n\n return innerSchema\n ? { anyOf: [{ not: parseAnyDef() }, innerSchema] }\n : parseAnyDef();\n};\n","import { ZodPipelineDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\nimport { JsonSchema7AllOfType } from './intersection';\n\nexport const parsePipelineDef = (\n def: ZodPipelineDef<any, any>,\n refs: Refs,\n): JsonSchema7AllOfType | JsonSchema7Type | undefined => {\n if (refs.pipeStrategy === 'input') {\n return parseDef(def.in._def, refs);\n } else if (refs.pipeStrategy === 'output') {\n return parseDef(def.out._def, refs);\n }\n\n const a = parseDef(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', '0'],\n });\n const b = parseDef(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'],\n });\n\n return {\n allOf: [a, b].filter((x): x is JsonSchema7Type => x !== undefined),\n };\n};\n","import { ZodPromiseDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport function parsePromiseDef(\n def: ZodPromiseDef,\n refs: Refs,\n): JsonSchema7Type | undefined {\n return parseDef(def.type._def, refs);\n}\n","import { ZodSetDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7SetType = {\n type: 'array';\n uniqueItems: true;\n items?: JsonSchema7Type;\n minItems?: number;\n maxItems?: number;\n};\n\nexport function parseSetDef(def: ZodSetDef, refs: Refs): JsonSchema7SetType {\n const items = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items'],\n });\n\n const schema: JsonSchema7SetType = {\n type: 'array',\n uniqueItems: true,\n items,\n };\n\n if (def.minSize) {\n schema.minItems = def.minSize.value;\n }\n\n if (def.maxSize) {\n schema.maxItems = def.maxSize.value;\n }\n\n return schema;\n}\n","import { ZodTupleDef, ZodTupleItems, ZodTypeAny } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { JsonSchema7Type } from '../parse-types';\nimport { Refs } from '../refs';\n\nexport type JsonSchema7TupleType = {\n type: 'array';\n minItems: number;\n items: JsonSchema7Type[];\n} & (\n | {\n maxItems: number;\n }\n | {\n additionalItems?: JsonSchema7Type;\n }\n);\n\nexport function parseTupleDef(\n def: ZodTupleDef<ZodTupleItems | [], ZodTypeAny | null>,\n refs: Refs,\n): JsonSchema7TupleType {\n if (def.rest) {\n return {\n type: 'array',\n minItems: def.items.length,\n items: def.items\n .map((x, i) =>\n parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', `${i}`],\n }),\n )\n .reduce(\n (acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]),\n [],\n ),\n additionalItems: parseDef(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'additionalItems'],\n }),\n };\n } else {\n return {\n type: 'array',\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items\n .map((x, i) =>\n parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, 'items', `${i}`],\n }),\n )\n .reduce(\n (acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]),\n [],\n ),\n };\n }\n}\n","import { JsonSchema7AnyType, parseAnyDef } from './any';\n\nexport type JsonSchema7UndefinedType = {\n not: JsonSchema7AnyType;\n};\n\nexport function parseUndefinedDef(): JsonSchema7UndefinedType {\n return {\n not: parseAnyDef(),\n };\n}\n","import { JsonSchema7AnyType, parseAnyDef } from './any';\n\nexport type JsonSchema7UnknownType = JsonSchema7AnyType;\n\nexport function parseUnknownDef(): JsonSchema7UnknownType {\n return parseAnyDef();\n}\n","import { ZodReadonlyDef } from 'zod/v3';\nimport { parseDef } from '../parse-def';\nimport { Refs } from '../refs';\n\nexport const parseReadonlyDef = (def: ZodReadonlyDef<any>, refs: Refs) => {\n return parseDef(def.innerType._def, refs);\n};\n","import { ZodTypeDef } from 'zod/v3';\nimport { Refs, Seen } from './refs';\nimport { ignoreOverride } from './options';\nimport { JsonSchema7Type } from './parse-types';\nimport { selectParser } from './select-parser';\nimport { getRelativePath } from './get-relative-path';\nimport { parseAnyDef } from './parsers/any';\n\nexport function parseDef(\n def: ZodTypeDef,\n refs: Refs,\n forceResolution = false, // Forces a new schema to be instantiated even though its def has been seen. Used for improving refs in definitions. See https://github.com/StefanTerdell/zod-to-json-schema/pull/61.\n): JsonSchema7Type | undefined {\n const seenItem = refs.seen.get(def);\n\n if (refs.override) {\n const overrideResult = refs.override?.(\n def,\n refs,\n seenItem,\n forceResolution,\n );\n\n if (overrideResult !== ignoreOverride) {\n return overrideResult;\n }\n }\n\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n\n if (seenSchema !== undefined) {\n return seenSchema;\n }\n }\n\n const newItem: Seen = { def, path: refs.currentPath, jsonSchema: undefined };\n\n refs.seen.set(def, newItem);\n\n const jsonSchemaOrGetter = selectParser(def, (def as any).typeName, refs);\n\n // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive)\n const jsonSchema =\n typeof jsonSchemaOrGetter === 'function'\n ? parseDef(jsonSchemaOrGetter(), refs)\n : jsonSchemaOrGetter;\n\n if (jsonSchema) {\n addMeta(def, refs, jsonSchema);\n }\n\n if (refs.postProcess) {\n const postProcessResult = refs.postProcess(jsonSchema, def, refs);\n\n newItem.jsonSchema = jsonSchema;\n\n return postProcessResult;\n }\n\n newItem.jsonSchema = jsonSchema;\n\n return jsonSchema;\n}\n\nconst get$ref = (\n item: Seen,\n refs: Refs,\n):\n | {\n $ref: string;\n }\n | {}\n | undefined => {\n switch (refs.$refStrategy) {\n case 'root':\n return { $ref: item.path.join('/') };\n case 'relative':\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case 'none':\n case 'seen': {\n if (\n item.path.length < refs.currentPath.length &&\n item.path.every((value, index) => refs.currentPath[index] === value)\n ) {\n console.warn(\n `Recursive reference detected at ${refs.currentPath.join(\n '/',\n )}! Defaulting to any`,\n );\n\n return parseAnyDef();\n }\n\n return refs.$refStrategy === 'seen' ? parseAnyDef() : undefined;\n }\n }\n};\n\nconst addMeta = (\n def: ZodTypeDef,\n refs: Refs,\n jsonSchema: JsonSchema7Type,\n): JsonSchema7Type => {\n if (def.description) {\n jsonSchema.description = def.description;\n }\n return jsonSchema;\n};\n","import { ZodTypeDef } from 'zod/v3';\nimport { getDefaultOptions, Options } from './options';\nimport { JsonSchema7Type } from './parse-types';\n\nexport type Refs = {\n seen: Map<ZodTypeDef, Seen>;\n currentPath: string[];\n propertyPath: string[] | undefined;\n} & Options;\n\nexport type Seen = {\n def: ZodTypeDef;\n path: string[];\n jsonSchema: JsonSchema7Type | undefined;\n};\n\nexport const getRefs = (options?: string | Partial<Options>): Refs => {\n const _options = getDefaultOptions(options);\n const currentPath =\n _options.name !== undefined\n ? [..._options.basePath, _options.definitionPath, _options.name]\n : _options.basePath;\n return {\n ..._options,\n currentPath: currentPath,\n propertyPath: undefined,\n seen: new Map(\n Object.entries(_options.definitions).map(([name, def]) => [\n def._def,\n {\n def: def._def,\n path: [..._options.basePath, _options.definitionPath, name],\n // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n jsonSchema: undefined,\n },\n ]),\n ),\n };\n};\n","import { ZodSchema } from 'zod/v3';\nimport { Options } from './options';\nimport { parseDef } from './parse-def';\nimport { JsonSchema7Type } from './parse-types';\nimport { getRefs } from './refs';\nimport { parseAnyDef } from './parsers/any';\n\nconst zodToJsonSchema = (\n schema: ZodSchema<any>,\n options?: Partial<Options> | string,\n): JsonSchema7Type & {\n $schema?: string;\n definitions?: {\n [key: string]: JsonSchema7Type;\n };\n} => {\n const refs = getRefs(options);\n\n let definitions =\n typeof options === 'object' && options.definitions\n ? Object.entries(options.definitions).reduce(\n (acc: { [key: string]: JsonSchema7Type }, [name, schema]) => ({\n ...acc,\n [name]:\n parseDef(\n schema._def,\n {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n },\n true,\n ) ?? parseAnyDef(),\n }),\n {},\n )\n : undefined;\n\n const name =\n typeof options === 'string'\n ? options\n : options?.nameStrategy === 'title'\n ? undefined\n : options?.name;\n\n const main =\n parseDef(\n schema._def,\n name === undefined\n ? refs\n : {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n },\n false,\n ) ?? (parseAnyDef() as JsonSchema7Type);\n\n const title =\n typeof options === 'object' &&\n options.name !== undefined &&\n options.nameStrategy === 'title'\n ? options.name\n : undefined;\n\n if (title !== undefined) {\n main.title = title;\n }\n\n const combined: ReturnType<typeof zodToJsonSchema> =\n name === undefined\n ? definitions\n ? {\n ...main,\n [refs.definitionPath]: definitions,\n }\n : main\n : {\n $ref: [\n ...(refs.$refStrategy === 'relative' ? [] : refs.basePath),\n refs.definitionPath,\n name,\n ].join('/'),\n [refs.definitionPath]: {\n ...definitions,\n [name]: main,\n },\n };\n\n combined.$schema = 'http://json-schema.org/draft-07/schema#';\n\n return combined;\n};\n\nexport { zodToJsonSchema };\n","export * from './get-relative-path';\nexport * from './options';\nexport * from './parse-def';\nexport * from './parse-types';\nexport * from './parsers/any';\nexport * from './parsers/array';\nexport * from './parsers/bigint';\nexport * from './parsers/boolean';\nexport * from './parsers/branded';\nexport * from './parsers/catch';\nexport * from './parsers/date';\nexport * from './parsers/default';\nexport * from './parsers/effects';\nexport * from './parsers/enum';\nexport * from './parsers/intersection';\nexport * from './parsers/literal';\nexport * from './parsers/map';\nexport * from './parsers/native-enum';\nexport * from './parsers/never';\nexport * from './parsers/null';\nexport * from './parsers/nullable';\nexport * from './parsers/number';\nexport * from './parsers/object';\nexport * from './parsers/optional';\nexport * from './parsers/pipeline';\nexport * from './parsers/promise';\nexport * from './parsers/readonly';\nexport * from './parsers/record';\nexport * from './parsers/set';\nexport * from './parsers/string';\nexport * from './parsers/tuple';\nexport * from './parsers/undefined';\nexport * from './parsers/union';\nexport * from './parsers/unknown';\nexport * from './refs';\nexport * from './select-parser';\nexport * from './zod-to-json-schema';\nimport { zodToJsonSchema } from './zod-to-json-schema';\nexport default zodToJsonSchema;\n","import { JSONSchema7 } from '@ai-sdk/provider';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4';\nimport { Validator, validatorSymbol, type ValidationResult } from './validator';\nimport { zodSchema } from './zod-schema';\n\n/**\n * Used to mark schemas so we can support both Zod and custom schemas.\n */\nconst schemaSymbol = Symbol.for('vercel.ai.schema');\n\nexport type Schema<OBJECT = unknown> = Validator<OBJECT> & {\n /**\n * Used to mark schemas so we can support both Zod and custom schemas.\n */\n [schemaSymbol]: true;\n\n /**\n * Schema type for inference.\n */\n _type: OBJECT;\n\n /**\n * The JSON Schema for the schema. It is passed to the providers.\n */\n readonly jsonSchema: JSONSchema7;\n};\n\n/**\n * Creates a schema with deferred creation.\n * This is important to reduce the startup time of the library\n * and to avoid initializing unused validators.\n *\n * @param createValidator A function that creates a schema.\n * @returns A function that returns a schema.\n */\nexport function lazySchema<SCHEMA>(\n createSchema: () => Schema<SCHEMA>,\n): LazySchema<SCHEMA> {\n // cache the validator to avoid initializing it multiple times\n let schema: Schema<SCHEMA> | undefined;\n return () => {\n if (schema == null) {\n schema = createSchema();\n }\n return schema;\n };\n}\n\nexport type LazySchema<SCHEMA> = () => Schema<SCHEMA>;\n\n// Note: Zod types here exactly match the types in zod-schema.ts\n// to prevent type errors when using zod schemas with flexible schemas.\nexport type FlexibleSchema<SCHEMA> =\n | z4.core.$ZodType<SCHEMA, any>\n | z3.Schema<SCHEMA, z3.ZodTypeDef, any>\n | Schema<SCHEMA>\n | LazySchema<SCHEMA>;\n\nexport type InferSchema<SCHEMA> = SCHEMA extends z3.Schema\n ? z3.infer<SCHEMA>\n : SCHEMA extends z4.core.$ZodType\n ? z4.infer<SCHEMA>\n : SCHEMA extends LazySchema<infer T>\n ? T\n : SCHEMA extends Schema<infer T>\n ? T\n : never;\n\n/**\n * Create a schema using a JSON Schema.\n *\n * @param jsonSchema The JSON Schema for the schema.\n * @param options.validate Optional. A validation function for the schema.\n */\nexport function jsonSchema<OBJECT = unknown>(\n jsonSchema: JSONSchema7 | (() => JSONSchema7),\n {\n validate,\n }: {\n validate?: (\n value: unknown,\n ) => ValidationResult<OBJECT> | PromiseLike<ValidationResult<OBJECT>>;\n } = {},\n): Schema<OBJECT> {\n return {\n [schemaSymbol]: true,\n _type: undefined as OBJECT, // should never be used directly\n [validatorSymbol]: true,\n get jsonSchema() {\n if (typeof jsonSchema === 'function') {\n jsonSchema = jsonSchema(); // cache the function results\n }\n return jsonSchema;\n },\n validate,\n };\n}\n\nfunction isSchema(value: unknown): value is Schema {\n return (\n typeof value === 'object' &&\n value !== null &&\n schemaSymbol in value &&\n value[schemaSymbol] === true &&\n 'jsonSchema' in value &&\n 'validate' in value\n );\n}\n\nexport function asSchema<OBJECT>(\n schema: FlexibleSchema<OBJECT> | undefined,\n): Schema<OBJECT> {\n return schema == null\n ? jsonSchema({\n properties: {},\n additionalProperties: false,\n })\n : isSchema(schema)\n ? schema\n : typeof schema === 'function'\n ? schema()\n : zodSchema(schema);\n}\n","// btoa and atob need to be invoked as a function call, not as a method call.\n// Otherwise CloudFlare will throw a\n// \"TypeError: Illegal invocation: function called with incorrect this reference\"\nconst { btoa, atob } = globalThis;\n\nexport function convertBase64ToUint8Array(base64String: string) {\n const base64Url = base64String.replace(/-/g, '+').replace(/_/g, '/');\n const latin1string = atob(base64Url);\n return Uint8Array.from(latin1string, byte => byte.codePointAt(0)!);\n}\n\nexport function convertUint8ArrayToBase64(array: Uint8Array): string {\n let latin1string = '';\n\n // Note: regular for loop to support older JavaScript versions that\n // do not support for..of on Uint8Array\n for (let i = 0; i < array.length; i++) {\n latin1string += String.fromCodePoint(array[i]);\n }\n\n return btoa(latin1string);\n}\n\nexport function convertToBase64(value: string | Uint8Array): string {\n return value instanceof Uint8Array ? convertUint8ArrayToBase64(value) : value;\n}\n","import { AISDKError, LanguageModelV2DataContent } from '@ai-sdk/provider';\nimport {\n convertBase64ToUint8Array,\n convertUint8ArrayToBase64,\n DataContent,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { InvalidDataContentError } from './invalid-data-content-error';\nimport { splitDataUrl } from './split-data-url';\n\n/**\n@internal\n */\nexport const dataContentSchema: z.ZodType<DataContent> = z.union([\n z.string(),\n z.instanceof(Uint8Array),\n z.instanceof(ArrayBuffer),\n z.custom<Buffer>(\n // Buffer might not be available in some environments such as CloudFlare:\n (value: unknown): value is Buffer =>\n globalThis.Buffer?.isBuffer(value) ?? false,\n { message: 'Must be a Buffer' },\n ),\n]);\n\nexport function convertToLanguageModelV2DataContent(\n content: DataContent | URL,\n): {\n data: LanguageModelV2DataContent;\n mediaType: string | undefined;\n} {\n // Buffer & Uint8Array:\n if (content instanceof Uint8Array) {\n return { data: content, mediaType: undefined };\n }\n\n // ArrayBuffer needs conversion to Uint8Array (lightweight):\n if (content instanceof ArrayBuffer) {\n return { data: new Uint8Array(content), mediaType: undefined };\n }\n\n // Attempt to create a URL from the data. If it fails, we can assume the data\n // is not a URL and likely some other sort of data.\n if (typeof content === 'string') {\n try {\n content = new URL(content);\n } catch (error) {\n // ignored\n }\n }\n\n // Extract data from data URL:\n if (content instanceof URL && content.protocol === 'data:') {\n const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(\n content.toString(),\n );\n\n if (dataUrlMediaType == null || base64Content == null) {\n throw new AISDKError({\n name: 'InvalidDataContentError',\n message: `Invalid data URL format in content ${content.toString()}`,\n });\n }\n\n return { data: base64Content, mediaType: dataUrlMediaType };\n }\n\n return { data: content, mediaType: undefined };\n}\n\n/**\nConverts data content to a base64-encoded string.\n\n@param content - Data content to convert.\n@returns Base64-encoded string.\n*/\nexport function convertDataContentToBase64String(content: DataContent): string {\n if (typeof content === 'string') {\n return content;\n }\n\n if (content instanceof ArrayBuffer) {\n return convertUint8ArrayToBase64(new Uint8Array(content));\n }\n\n return convertUint8ArrayToBase64(content);\n}\n\n/**\nConverts data content to a Uint8Array.\n\n@param content - Data content to convert.\n@returns Uint8Array.\n */\nexport function convertDataContentToUint8Array(\n content: DataContent,\n): Uint8Array {\n if (content instanceof Uint8Array) {\n return content;\n }\n\n if (typeof content === 'string') {\n try {\n return convertBase64ToUint8Array(content);\n } catch (error) {\n throw new InvalidDataContentError({\n message:\n 'Invalid data content. Content string is not a base64-encoded media.',\n content,\n cause: error,\n });\n }\n }\n\n if (content instanceof ArrayBuffer) {\n return new Uint8Array(content);\n }\n\n throw new InvalidDataContentError({ content });\n}\n\n/**\n * Converts a Uint8Array to a string of text.\n *\n * @param uint8Array - The Uint8Array to convert.\n * @returns The converted string.\n */\nexport function convertUint8ArrayToText(uint8Array: Uint8Array): string {\n try {\n return new TextDecoder().decode(uint8Array);\n } catch (error) {\n throw new Error('Error decoding Uint8Array to text');\n }\n}\n","import { InvalidPromptError } from '@ai-sdk/provider';\nimport { ModelMessage, safeValidateTypes } from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { modelMessageSchema } from './message';\nimport { Prompt } from './prompt';\n\nexport type StandardizedPrompt = {\n /**\n * System message.\n */\n system?: string;\n\n /**\n * Messages.\n */\n messages: ModelMessage[];\n};\n\nexport async function standardizePrompt(\n prompt: Prompt,\n): Promise<StandardizedPrompt> {\n if (prompt.prompt == null && prompt.messages == null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt or messages must be defined',\n });\n }\n\n if (prompt.prompt != null && prompt.messages != null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt and messages cannot be defined at the same time',\n });\n }\n\n // validate that system is a string\n if (prompt.system != null && typeof prompt.system !== 'string') {\n throw new InvalidPromptError({\n prompt,\n message: 'system must be a string',\n });\n }\n\n let messages: ModelMessage[];\n\n if (prompt.prompt != null && typeof prompt.prompt === 'string') {\n messages = [{ role: 'user', content: prompt.prompt }];\n } else if (prompt.prompt != null && Array.isArray(prompt.prompt)) {\n messages = prompt.prompt;\n } else if (prompt.messages != null) {\n messages = prompt.messages;\n } else {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt or messages must be defined',\n });\n }\n\n if (messages.length === 0) {\n throw new InvalidPromptError({\n prompt,\n message: 'messages must not be empty',\n });\n }\n\n const validationResult = await safeValidateTypes({\n value: messages,\n schema: z.array(modelMessageSchema),\n });\n\n if (!validationResult.success) {\n throw new InvalidPromptError({\n prompt,\n message:\n 'The messages must be a ModelMessage[]. ' +\n 'If you have passed a UIMessage[], you can use convertToModelMessages to convert them.',\n cause: validationResult.error,\n });\n }\n\n return {\n messages,\n system: prompt.system,\n };\n}\n","import {\n AssistantModelMessage,\n ModelMessage,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { providerMetadataSchema } from '../types/provider-metadata';\nimport {\n filePartSchema,\n imagePartSchema,\n reasoningPartSchema,\n textPartSchema,\n toolCallPartSchema,\n toolResultPartSchema,\n} from './content-part';\n\n/**\n@deprecated Use `SystemModelMessage` instead.\n */\n// TODO remove in AI SDK 6\nexport type CoreSystemMessage = SystemModelMessage;\n\nexport const systemModelMessageSchema: z.ZodType<SystemModelMessage> = z.object(\n {\n role: z.literal('system'),\n content: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n },\n);\n\n/**\n@deprecated Use `systemModelMessageSchema` instead.\n */\n// TODO remove in AI SDK 6\nexport const coreSystemMessageSchema = systemModelMessageSchema;\n\n/**\n@deprecated Use `UserModelMessage` instead.\n */\n// TODO remove in AI SDK 6\nexport type CoreUserMessage = UserModelMessage;\n\nexport const userModelMessageSchema: z.ZodType<UserModelMessage> = z.object({\n role: z.literal('user'),\n content: z.union([\n z.string(),\n z.array(z.union([textPartSchema, imagePartSchema, filePartSchema])),\n ]),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n@deprecated Use `userModelMessageSchema` instead.\n */\n// TODO remove in AI SDK 6\nexport const coreUserMessageSchema = userModelMessageSchema;\n\n/**\n@deprecated Use `AssistantModelMessage` instead.\n */\n// TODO remove in AI SDK 6\nexport type CoreAssistantMessage = AssistantModelMessage;\n\nexport const assistantModelMessageSchema: z.ZodType<AssistantModelMessage> =\n z.object({\n role: z.literal('assistant'),\n content: z.union([\n z.string(),\n z.array(\n z.union([\n textPartSchema,\n filePartSchema,\n reasoningPartSchema,\n toolCallPartSchema,\n toolResultPartSchema,\n ]),\n ),\n ]),\n providerOptions: providerMetadataSchema.optional(),\n });\n\n/**\n@deprecated Use `assistantModelMessageSchema` instead.\n */\n// TODO remove in AI SDK 6\nexport const coreAssistantMessageSchema = assistantModelMessageSchema;\n\n/**\n@deprecated Use `ToolModelMessage` instead.\n */\n// TODO remove in AI SDK 6\nexport type CoreToolMessage = ToolModelMessage;\n\nexport const toolModelMessageSchema: z.ZodType<ToolModelMessage> = z.object({\n role: z.literal('tool'),\n content: z.array(toolResultPartSchema),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n@deprecated Use `toolModelMessageSchema` instead.\n */\n// TODO remove in AI SDK 6\nexport const coreToolMessageSchema = toolModelMessageSchema;\n\n/**\n@deprecated Use `ModelMessage` instead.\n */\n// TODO remove in AI SDK 6\nexport type CoreMessage = ModelMessage;\n\nexport const modelMessageSchema: z.ZodType<ModelMessage> = z.union([\n systemModelMessageSchema,\n userModelMessageSchema,\n assistantModelMessageSchema,\n toolModelMessageSchema,\n]);\n\n/**\n@deprecated Use `modelMessageSchema` instead.\n */\n// TODO remove in AI SDK 6\nexport const coreMessageSchema: z.ZodType<CoreMessage> = modelMessageSchema;\n","import { SharedV2ProviderMetadata } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\nimport { jsonValueSchema } from './json-value';\n\n/**\nAdditional provider-specific metadata that is returned from the provider.\n\nThis is needed to enable provider-specific functionality that can be\nfully encapsulated in the provider.\n */\nexport type ProviderMetadata = SharedV2ProviderMetadata;\n\nexport const providerMetadataSchema: z.ZodType<ProviderMetadata> = z.record(\n z.string(),\n z.record(z.string(), jsonValueSchema),\n);\n","import { JSONValue as OriginalJSONValue } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\n\nexport const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>\n z.union([\n z.null(),\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), jsonValueSchema),\n z.array(jsonValueSchema),\n ]),\n);\n\nexport type JSONValue = OriginalJSONValue;\n","import { LanguageModelV2ToolResultOutput } from '@ai-sdk/provider';\nimport {\n FilePart,\n ImagePart,\n ProviderOptions,\n ReasoningPart,\n TextPart,\n ToolResultPart,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { jsonValueSchema } from '../types/json-value';\nimport { providerMetadataSchema } from '../types/provider-metadata';\nimport { dataContentSchema } from './data-content';\n\n/**\n@internal\n */\nexport const textPartSchema: z.ZodType<TextPart> = z.object({\n type: z.literal('text'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n@internal\n */\nexport const imagePartSchema: z.ZodType<ImagePart> = z.object({\n type: z.literal('image'),\n image: z.union([dataContentSchema, z.instanceof(URL)]),\n mediaType: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n@internal\n */\nexport const filePartSchema: z.ZodType<FilePart> = z.object({\n type: z.literal('file'),\n data: z.union([dataContentSchema, z.instanceof(URL)]),\n filename: z.string().optional(),\n mediaType: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n@internal\n */\nexport const reasoningPartSchema: z.ZodType<ReasoningPart> = z.object({\n type: z.literal('reasoning'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\nTool call content part of a prompt. It contains a tool call (usually generated by the AI model).\n */\nexport interface ToolCallPart {\n type: 'tool-call';\n\n /**\nID of the tool call. This ID is used to match the tool call with the tool result.\n */\n toolCallId: string;\n\n /**\nName of the tool that is being called.\n */\n toolName: string;\n\n /**\nArguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.\n */\n input: unknown;\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n}\n\n/**\n@internal\n */\nexport const toolCallPartSchema: z.ZodType<ToolCallPart> = z.object({\n type: z.literal('tool-call'),\n toolCallId: z.string(),\n toolName: z.string(),\n input: z.unknown(),\n providerOptions: providerMetadataSchema.optional(),\n providerExecuted: z.boolean().optional(),\n}) as z.ZodType<ToolCallPart>; // necessary bc input is optional on Zod type\n\n/**\n@internal\n */\nexport const outputSchema: z.ZodType<LanguageModelV2ToolResultOutput> =\n z.discriminatedUnion('type', [\n z.object({\n type: z.literal('text'),\n value: z.string(),\n }),\n z.object({\n type: z.literal('json'),\n value: jsonValueSchema,\n }),\n z.object({\n type: z.literal('error-text'),\n value: z.string(),\n }),\n z.object({\n type: z.literal('error-json'),\n value: jsonValueSchema,\n }),\n z.object({\n type: z.literal('content'),\n value: z.array(\n z.union([\n z.object({\n type: z.literal('text'),\n text: z.string(),\n }),\n z.object({\n type: z.literal('media'),\n data: z.string(),\n mediaType: z.string(),\n }),\n ]),\n ),\n }),\n ]);\n\n/**\n@internal\n */\nexport const toolResultPartSchema: z.ZodType<ToolResultPart> = z.object({\n type: z.literal('tool-result'),\n toolCallId: z.string(),\n toolName: z.string(),\n output: outputSchema,\n providerOptions: providerMetadataSchema.optional(),\n}) as z.ZodType<ToolResultPart>; // necessary bc result is optional on Zod type\n","import { z } from 'zod/v4';\nimport {\n ProviderMetadata,\n providerMetadataSchema,\n} from '../types/provider-metadata';\nimport { FinishReason } from '../types/language-model';\nimport {\n InferUIMessageData,\n InferUIMessageMetadata,\n UIDataTypes,\n UIMessage,\n} from '../ui/ui-messages';\nimport { ValueOf } from '../util/value-of';\nimport { lazyValidator, zodSchema } from '@ai-sdk/provider-utils';\n\nexport const uiMessageChunkSchema = lazyValidator(() =>\n zodSchema(\n z.union([\n z.strictObject({\n type: z.literal('text-start'),\n id: z.string(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.strictObject({\n type: z.literal('text-delta'),\n id: z.string(),\n delta: z.string(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.strictObject({\n type: z.literal('text-end'),\n id: z.string(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.strictObject({\n type: z.literal('error'),\n errorText: z.string(),\n }),\n z.strictObject({\n type: z.literal('tool-input-start'),\n toolCallId: z.string(),\n toolName: z.string(),\n providerExecuted: z.boolean().optional(),\n dynamic: z.boolean().optional(),\n }),\n z.strictObject({\n type: z.literal('tool-input-delta'),\n toolCallId: z.string(),\n inputTextDelta: z.string(),\n }),\n z.strictObject({\n type: z.literal('tool-input-available'),\n toolCallId: z.string(),\n toolName: z.string(),\n input: z.unknown(),\n providerExecuted: z.boolean().optional(),\n providerMetadata: providerMetadataSchema.optional(),\n dynamic: z.boolean().optional(),\n }),\n z.strictObject({\n type: z.literal('tool-input-error'),\n toolCallId: z.string(),\n toolName: z.string(),\n input: z.unknown(),\n providerExecuted: z.boolean().optional(),\n providerMetadata: providerMetadataSchema.optional(),\n dynamic: z.boolean().optional(),\n errorText: z.string(),\n }),\n z.strictObject({\n type: z.literal('tool-output-available'),\n toolCallId: z.string(),\n output: z.unknown(),\n providerExecuted: z.boolean().optional(),\n dynamic: z.boolean().optional(),\n preliminary: z.boolean().optional(),\n }),\n z.strictObject({\n type: z.literal('tool-output-error'),\n toolCallId: z.string(),\n errorText: z.string(),\n providerExecuted: z.boolean().optional(),\n dynamic: z.boolean().optional(),\n }),\n z.strictObject({\n type: z.literal('reasoning-start'),\n id: z.string(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.strictObject({\n type: z.literal('reasoning-delta'),\n id: z.string(),\n delta: z.string(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.strictObject({\n type: z.literal('reasoning-end'),\n id: z.string(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.strictObject({\n type: z.literal('source-url'),\n sourceId: z.string(),\n url: z.string(),\n title: z.string().optional(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.strictObject({\n type: z.literal('source-document'),\n sourceId: z.string(),\n mediaType: z.string(),\n title: z.string(),\n filename: z.string().optional(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.strictObject({\n type: z.literal('file'),\n url: z.string(),\n mediaType: z.string(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.strictObject({\n type: z.custom<`data-${string}`>(\n (value): value is `data-${string}` =>\n typeof value === 'string' && value.startsWith('data-'),\n { message: 'Type must start with \"data-\"' },\n ),\n id: z.string().optional(),\n data: z.unknown(),\n transient: z.boolean().optional(),\n }),\n z.strictObject({\n type: z.literal('start-step'),\n }),\n z.strictObject({\n type: z.literal('finish-step'),\n }),\n z.strictObject({\n type: z.literal('start'),\n messageId: z.string().optional(),\n messageMetadata: z.unknown().optional(),\n }),\n z.strictObject({\n type: z.literal('finish'),\n finishReason: z\n .enum([\n 'stop',\n 'length',\n 'content-filter',\n 'tool-calls',\n 'error',\n 'other',\n 'unknown',\n ] as const satisfies readonly FinishReason[])\n .optional(),\n messageMetadata: z.unknown().optional(),\n }),\n z.strictObject({\n type: z.literal('abort'),\n }),\n z.strictObject({\n type: z.literal('message-metadata'),\n messageMetadata: z.unknown(),\n }),\n ]),\n ),\n);\n\nexport type DataUIMessageChunk<DATA_TYPES extends UIDataTypes> = ValueOf<{\n [NAME in keyof DATA_TYPES & string]: {\n type: `data-${NAME}`;\n id?: string;\n data: DATA_TYPES[NAME];\n transient?: boolean;\n };\n}>;\n\nexport type UIMessageChunk<\n METADATA = unknown,\n DATA_TYPES extends UIDataTypes = UIDataTypes,\n> =\n | {\n type: 'text-start';\n id: string;\n providerMetadata?: ProviderMetadata;\n }\n | {\n type: 'text-delta';\n delta: string;\n id: string;\n providerMetadata?: ProviderMetadata;\n }\n | {\n type: 'text-end';\n id: string;\n providerMetadata?: ProviderMetadata;\n }\n | {\n type: 'reasoning-start';\n id: string;\n providerMetadata?: ProviderMetadata;\n }\n | {\n type: 'reasoning-delta';\n id: string;\n delta: string;\n providerMetadata?: ProviderMetadata;\n }\n | {\n type: 'reasoning-end';\n id: string;\n providerMetadata?: ProviderMetadata;\n }\n | {\n type: 'error';\n errorText: string;\n }\n | {\n type: 'tool-input-available';\n toolCallId: string;\n toolName: string;\n input: unknown;\n providerExecuted?: boolean;\n providerMetadata?: ProviderMetadata;\n dynamic?: boolean;\n }\n | {\n type: 'tool-input-error';\n toolCallId: string;\n toolName: string;\n input: unknown;\n providerExecuted?: boolean;\n providerMetadata?: ProviderMetadata;\n dynamic?: boolean;\n errorText: string;\n }\n | {\n type: 'tool-output-available';\n toolCallId: string;\n output: unknown;\n providerExecuted?: boolean;\n dynamic?: boolean;\n preliminary?: boolean;\n }\n | {\n type: 'tool-output-error';\n toolCallId: string;\n errorText: string;\n providerExecuted?: boolean;\n dynamic?: boolean;\n }\n | {\n type: 'tool-input-start';\n toolCallId: string;\n toolName: string;\n providerExecuted?: boolean;\n dynamic?: boolean;\n }\n | {\n type: 'tool-input-delta';\n toolCallId: string;\n inputTextDelta: string;\n }\n | {\n type: 'source-url';\n sourceId: string;\n url: string;\n title?: string;\n providerMetadata?: ProviderMetadata;\n }\n | {\n type: 'source-document';\n sourceId: string;\n mediaType: string;\n title: string;\n filename?: string;\n providerMetadata?: ProviderMetadata;\n }\n | {\n type: 'file';\n url: string;\n mediaType: string;\n providerMetadata?: ProviderMetadata;\n }\n | DataUIMessageChunk<DATA_TYPES>\n | {\n type: 'start-step';\n }\n | {\n type: 'finish-step';\n }\n | {\n type: 'start';\n messageId?: string;\n messageMetadata?: METADATA;\n }\n | {\n type: 'finish';\n finishReason?: FinishReason;\n messageMetadata?: METADATA;\n }\n | {\n type: 'abort';\n }\n | {\n type: 'message-metadata';\n messageMetadata: METADATA;\n };\n\nexport function isDataUIMessageChunk(\n chunk: UIMessageChunk,\n): chunk is DataUIMessageChunk<UIDataTypes> {\n return chunk.type.startsWith('data-');\n}\n\nexport type InferUIMessageChunk<T extends UIMessage> = UIMessageChunk<\n InferUIMessageMetadata<T>,\n InferUIMessageData<T>\n>;\n","import { TypeValidationError } from '@ai-sdk/provider';\nimport {\n lazyValidator,\n StandardSchemaV1,\n Tool,\n validateTypes,\n Validator,\n zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { InvalidArgumentError } from '../error';\nimport { providerMetadataSchema } from '../types/provider-metadata';\nimport {\n DataUIPart,\n InferUIMessageData,\n InferUIMessageTools,\n ToolUIPart,\n UIMessage,\n} from './ui-messages';\n\nconst uiMessagesSchema = lazyValidator(() =>\n zodSchema(\n z\n .array(\n z.object({\n id: z.string(),\n role: z.enum(['system', 'user', 'assistant']),\n metadata: z.unknown().optional(),\n parts: z\n .array(\n z.union([\n z.object({\n type: z.literal('text'),\n text: z.string(),\n state: z.enum(['streaming', 'done']).optional(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('reasoning'),\n text: z.string(),\n state: z.enum(['streaming', 'done']).optional(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('source-url'),\n sourceId: z.string(),\n url: z.string(),\n title: z.string().optional(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('source-document'),\n sourceId: z.string(),\n mediaType: z.string(),\n title: z.string(),\n filename: z.string().optional(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('file'),\n mediaType: z.string(),\n filename: z.string().optional(),\n url: z.string(),\n providerMetadata: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('step-start'),\n }),\n z.object({\n type: z.string().startsWith('data-'),\n id: z.string().optional(),\n data: z.unknown(),\n }),\n z.object({\n type: z.literal('dynamic-tool'),\n toolName: z.string(),\n toolCallId: z.string(),\n state: z.literal('input-streaming'),\n input: z.unknown().optional(),\n providerExecuted: z.boolean().optional(),\n output: z.never().optional(),\n errorText: z.never().optional(),\n }),\n z.object({\n type: z.literal('dynamic-tool'),\n toolName: z.string(),\n toolCallId: z.string(),\n state: z.literal('input-available'),\n input: z.unknown(),\n providerExecuted: z.boolean().optional(),\n output: z.never().optional(),\n errorText: z.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('dynamic-tool'),\n toolName: z.string(),\n toolCallId: z.string(),\n state: z.literal('output-available'),\n input: z.unknown(),\n providerExecuted: z.boolean().optional(),\n output: z.unknown(),\n errorText: z.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n preliminary: z.boolean().optional(),\n }),\n z.object({\n type: z.literal('dynamic-tool'),\n toolName: z.string(),\n toolCallId: z.string(),\n state: z.literal('output-error'),\n input: z.unknown(),\n providerExecuted: z.boolean().optional(),\n output: z.never().optional(),\n errorText: z.string(),\n callProviderMetadata: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.string().startsWith('tool-'),\n toolCallId: z.string(),\n state: z.literal('input-streaming'),\n providerExecuted: z.boolean().optional(),\n input: z.unknown().optional(),\n output: z.never().optional(),\n errorText: z.never().optional(),\n approval: z.never().optional(),\n }),\n z.object({\n type: z.string().startsWith('tool-'),\n toolCallId: z.string(),\n state: z.literal('input-available'),\n providerExecuted: z.boolean().optional(),\n input: z.unknown(),\n output: z.never().optional(),\n errorText: z.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z.never().optional(),\n }),\n z.object({\n type: z.string().startsWith('tool-'),\n toolCallId: z.string(),\n state: z.literal('approval-requested'),\n input: z.unknown(),\n providerExecuted: z.boolean().optional(),\n output: z.never().optional(),\n errorText: z.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z.object({\n id: z.string(),\n approved: z.never().optional(),\n reason: z.never().optional(),\n }),\n }),\n z.object({\n type: z.string().startsWith('tool-'),\n toolCallId: z.string(),\n state: z.literal('approval-responded'),\n input: z.unknown(),\n providerExecuted: z.boolean().optional(),\n output: z.never().optional(),\n errorText: z.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z.object({\n id: z.string(),\n approved: z.boolean(),\n reason: z.string().optional(),\n }),\n }),\n z.object({\n type: z.string().startsWith('tool-'),\n toolCallId: z.string(),\n state: z.literal('output-available'),\n providerExecuted: z.boolean().optional(),\n input: z.unknown(),\n output: z.unknown(),\n errorText: z.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n preliminary: z.boolean().optional(),\n approval: z\n .object({\n id: z.string(),\n approved: z.literal(true),\n reason: z.string().optional(),\n })\n .optional(),\n }),\n z.object({\n type: z.string().startsWith('tool-'),\n toolCallId: z.string(),\n state: z.literal('output-error'),\n providerExecuted: z.boolean().optional(),\n input: z.unknown(),\n output: z.never().optional(),\n errorText: z.string(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z\n .object({\n id: z.string(),\n approved: z.literal(true),\n reason: z.string().optional(),\n })\n .optional(),\n }),\n z.object({\n type: z.string().startsWith('tool-'),\n toolCallId: z.string(),\n state: z.literal('output-denied'),\n providerExecuted: z.boolean().optional(),\n input: z.unknown(),\n output: z.never().optional(),\n errorText: z.never().optional(),\n callProviderMetadata: providerMetadataSchema.optional(),\n approval: z.object({\n id: z.string(),\n approved: z.literal(false),\n reason: z.string().optional(),\n }),\n }),\n ]),\n )\n .nonempty('Message must contain at least one part'),\n }),\n )\n .nonempty('Messages array must not be empty'),\n ),\n);\n\nexport type SafeValidateUIMessagesResult<UI_MESSAGE extends UIMessage> =\n | {\n success: true;\n data: Array<UI_MESSAGE>;\n }\n | {\n success: false;\n error: Error;\n };\n\n/**\n * Validates a list of UI messages like `validateUIMessages`,\n * but instead of throwing it returns `{ success: true, data }`\n * or `{ success: false, error }`.\n */\nexport async function safeValidateUIMessages<UI_MESSAGE extends UIMessage>({\n messages,\n metadataSchema,\n dataSchemas,\n tools,\n}: {\n messages: unknown;\n metadataSchema?:\n | Validator<UIMessage['metadata']>\n | StandardSchemaV1<unknown, UI_MESSAGE['metadata']>;\n dataSchemas?: {\n [NAME in keyof InferUIMessageData<UI_MESSAGE> & string]?:\n | Validator<InferUIMessageData<UI_MESSAGE>[NAME]>\n | StandardSchemaV1<unknown, InferUIMessageData<UI_MESSAGE>[NAME]>;\n };\n tools?: {\n [NAME in keyof InferUIMessageTools<UI_MESSAGE> & string]?: Tool<\n InferUIMessageTools<UI_MESSAGE>[NAME]['input'],\n InferUIMessageTools<UI_MESSAGE>[NAME]['output']\n >;\n };\n}): Promise<SafeValidateUIMessagesResult<UI_MESSAGE>> {\n try {\n if (messages == null) {\n return {\n success: false,\n error: new InvalidArgumentError({\n parameter: 'messages',\n value: messages,\n message: 'messages parameter must be provided',\n }),\n };\n }\n\n const validatedMessages = await validateTypes({\n value: messages,\n schema: uiMessagesSchema,\n });\n\n if (metadataSchema) {\n for (const message of validatedMessages) {\n await validateTypes({\n value: message.metadata,\n schema: metadataSchema,\n });\n }\n }\n\n if (dataSchemas) {\n for (const message of validatedMessages) {\n const dataParts = message.parts.filter(part =>\n part.type.startsWith('data-'),\n ) as DataUIPart<InferUIMessageData<UI_MESSAGE>>[];\n\n for (const dataPart of dataParts) {\n const dataName = dataPart.type.slice(5);\n const dataSchema = dataSchemas[dataName];\n\n if (!dataSchema) {\n return {\n success: false,\n error: new TypeValidationError({\n value: dataPart.data,\n cause: `No data schema found for data part ${dataName}`,\n }),\n };\n }\n\n await validateTypes({\n value: dataPart.data,\n schema: dataSchema,\n });\n }\n }\n }\n\n if (tools) {\n for (const message of validatedMessages) {\n const toolParts = message.parts.filter(part =>\n part.type.startsWith('tool-'),\n ) as ToolUIPart<InferUIMessageTools<UI_MESSAGE>>[];\n\n for (const toolPart of toolParts) {\n const toolName = toolPart.type.slice(5);\n const tool = tools[toolName];\n\n if (!tool) {\n return {\n success: false,\n error: new TypeValidationError({\n value: toolPart.input,\n cause: `No tool schema found for tool part ${toolName}`,\n }),\n };\n }\n\n if (\n toolPart.state === 'input-available' ||\n toolPart.state === 'output-available' ||\n toolPart.state === 'output-error'\n ) {\n await validateTypes({\n value: toolPart.input,\n schema: tool.inputSchema,\n });\n }\n\n if (toolPart.state === 'output-available' && tool.outputSchema) {\n await validateTypes({\n value: toolPart.output,\n schema: tool.outputSchema,\n });\n }\n }\n }\n }\n\n return {\n success: true,\n data: validatedMessages as Array<UI_MESSAGE>,\n };\n } catch (error) {\n const err = error as Error;\n\n return {\n success: false,\n error: err,\n };\n }\n}\n\n/**\n * Validates a list of UI messages.\n *\n * Metadata, data parts, and generic tool call structures are only validated if\n * the corresponding schemas are provided. Otherwise, they are assumed to be\n * valid.\n */\nexport async function validateUIMessages<UI_MESSAGE extends UIMessage>({\n messages,\n metadataSchema,\n dataSchemas,\n tools,\n}: {\n messages: unknown;\n metadataSchema?:\n | Validator<UIMessage['metadata']>\n | StandardSchemaV1<unknown, UI_MESSAGE['metadata']>;\n dataSchemas?: {\n [NAME in keyof InferUIMessageData<UI_MESSAGE> & string]?:\n | Validator<InferUIMessageData<UI_MESSAGE>[NAME]>\n | StandardSchemaV1<unknown, InferUIMessageData<UI_MESSAGE>[NAME]>;\n };\n tools?: {\n [NAME in keyof InferUIMessageTools<UI_MESSAGE> & string]?: Tool<\n InferUIMessageTools<UI_MESSAGE>[NAME]['input'],\n InferUIMessageTools<UI_MESSAGE>[NAME]['output']\n >;\n };\n}): Promise<Array<UI_MESSAGE>> {\n const response = await safeValidateUIMessages({\n messages,\n metadataSchema,\n dataSchemas,\n tools,\n });\n\n if (!response.success) throw response.error;\n\n return response.data;\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoOutputSpecifiedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\nThrown when no output type is specified and output-related methods are called.\n */\nexport class NoOutputSpecifiedError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n constructor({ message = 'No output specified.' }: { message?: string } = {}) {\n super({ name, message });\n }\n\n static isInstance(error: unknown): error is NoOutputSpecifiedError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidArgumentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly parameter: string;\n readonly value: unknown;\n\n constructor({\n parameter,\n value,\n message,\n }: {\n parameter: string;\n value: unknown;\n message: string;\n }) {\n super({\n name,\n message: `Invalid argument for parameter ${parameter}: ${message}`,\n });\n\n this.parameter = parameter;\n this.value = value;\n }\n\n static isInstance(error: unknown): error is InvalidArgumentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport { SingleRequestTextStreamPart } from '../generate-text/run-tools-transformation';\n\nconst name = 'AI_InvalidStreamPartError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidStreamPartError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly chunk: SingleRequestTextStreamPart<any>;\n\n constructor({\n chunk,\n message,\n }: {\n chunk: SingleRequestTextStreamPart<any>;\n message: string;\n }) {\n super({ name, message });\n\n this.chunk = chunk;\n }\n\n static isInstance(error: unknown): error is InvalidStreamPartError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolInputError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolInputError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolName: string;\n readonly toolInput: string;\n\n constructor({\n toolInput,\n toolName,\n cause,\n message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}`,\n }: {\n message?: string;\n toolInput: string;\n toolName: string;\n cause: unknown;\n }) {\n super({ name, message, cause });\n\n this.toolInput = toolInput;\n this.toolName = toolName;\n }\n\n static isInstance(error: unknown): error is InvalidToolInputError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport { ImageModelResponseMetadata } from '../types/image-model-response-metadata';\n\nconst name = 'AI_NoImageGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\nThrown when no image could be generated. This can have multiple causes:\n\n- The model failed to generate a response.\n- The model generated a response that could not be parsed.\n */\nexport class NoImageGeneratedError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n /**\nThe response metadata for each call.\n */\n readonly responses: Array<ImageModelResponseMetadata> | undefined;\n\n constructor({\n message = 'No image generated.',\n cause,\n responses,\n }: {\n message?: string;\n cause?: Error;\n responses?: Array<ImageModelResponseMetadata>;\n }) {\n super({ name, message, cause });\n\n this.responses = responses;\n }\n\n static isInstance(error: unknown): error is NoImageGeneratedError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport { FinishReason } from '../types/language-model';\nimport { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport { LanguageModelUsage } from '../types/usage';\n\nconst name = 'AI_NoObjectGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\nThrown when no object could be generated. This can have several causes:\n\n- The model failed to generate a response.\n- The model generated a response that could not be parsed.\n- The model generated a response that could not be validated against the schema.\n\nThe error contains the following properties:\n\n- `text`: The text that was generated by the model. This can be the raw text or the tool call text, depending on the model.\n */\nexport class NoObjectGeneratedError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n /**\n The text that was generated by the model. This can be the raw text or the tool call text, depending on the model.\n */\n readonly text: string | undefined;\n\n /**\n The response metadata.\n */\n readonly response: LanguageModelResponseMetadata | undefined;\n\n /**\n The usage of the model.\n */\n readonly usage: LanguageModelUsage | undefined;\n\n /**\n Reason why the model finished generating a response.\n */\n readonly finishReason: FinishReason | undefined;\n\n constructor({\n message = 'No object generated.',\n cause,\n text,\n response,\n usage,\n finishReason,\n }: {\n message?: string;\n cause?: Error;\n text?: string;\n response: LanguageModelResponseMetadata;\n usage: LanguageModelUsage;\n finishReason: FinishReason;\n }) {\n super({ name, message, cause });\n\n this.text = text;\n this.response = response;\n this.usage = usage;\n this.finishReason = finishReason;\n }\n\n static isInstance(error: unknown): error is NoObjectGeneratedError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoOutputGeneratedError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\n/**\nThrown when no LLM output was generated, e.g. because of errors.\n */\nexport class NoOutputGeneratedError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n constructor({\n message = 'No output generated.',\n cause,\n }: {\n message?: string;\n cause?: Error;\n } = {}) {\n super({ name, message, cause });\n }\n\n static isInstance(error: unknown): error is NoOutputGeneratedError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoSuchToolError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchToolError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolName: string;\n readonly availableTools: string[] | undefined;\n\n constructor({\n toolName,\n availableTools = undefined,\n message = `Model tried to call unavailable tool '${toolName}'. ${\n availableTools === undefined\n ? 'No tools are available.'\n : `Available tools: ${availableTools.join(', ')}.`\n }`,\n }: {\n toolName: string;\n availableTools?: string[] | undefined;\n message?: string;\n }) {\n super({ name, message });\n\n this.toolName = toolName;\n this.availableTools = availableTools;\n }\n\n static isInstance(error: unknown): error is NoSuchToolError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\nimport { InvalidToolInputError } from './invalid-tool-input-error';\nimport { NoSuchToolError } from './no-such-tool-error';\n\nconst name = 'AI_ToolCallRepairError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class ToolCallRepairError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly originalError: NoSuchToolError | InvalidToolInputError;\n\n constructor({\n cause,\n originalError,\n message = `Error repairing tool call: ${getErrorMessage(cause)}`,\n }: {\n message?: string;\n cause: unknown;\n originalError: NoSuchToolError | InvalidToolInputError;\n }) {\n super({ name, message, cause });\n this.originalError = originalError;\n }\n\n static isInstance(error: unknown): error is ToolCallRepairError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidDataContentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidDataContentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly content: unknown;\n\n constructor({\n content,\n cause,\n message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`,\n }: {\n content: unknown;\n cause?: unknown;\n message?: string;\n }) {\n super({ name, message, cause });\n\n this.content = content;\n }\n\n static isInstance(error: unknown): error is InvalidDataContentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidMessageRoleError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidMessageRoleError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly role: string;\n\n constructor({\n role,\n message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".`,\n }: {\n role: string;\n message?: string;\n }) {\n super({ name, message });\n\n this.role = role;\n }\n\n static isInstance(error: unknown): error is InvalidMessageRoleError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\nimport { UIMessage } from '../ui/ui-messages';\n\nconst name = 'AI_MessageConversionError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class MessageConversionError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly originalMessage: Omit<UIMessage, 'id'>;\n\n constructor({\n originalMessage,\n message,\n }: {\n originalMessage: Omit<UIMessage, 'id'>;\n message: string;\n }) {\n super({ name, message });\n\n this.originalMessage = originalMessage;\n }\n\n static isInstance(error: unknown): error is MessageConversionError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_DownloadError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class DownloadError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly url: string;\n readonly statusCode?: number;\n readonly statusText?: string;\n\n constructor({\n url,\n statusCode,\n statusText,\n cause,\n message = cause == null\n ? `Failed to download ${url}: ${statusCode} ${statusText}`\n : `Failed to download ${url}: ${cause}`,\n }: {\n url: string;\n statusCode?: number;\n statusText?: string;\n message?: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n\n this.url = url;\n this.statusCode = statusCode;\n this.statusText = statusText;\n }\n\n static isInstance(error: unknown): error is DownloadError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_RetryError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport type RetryErrorReason =\n | 'maxRetriesExceeded'\n | 'errorNotRetryable'\n | 'abort';\n\nexport class RetryError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n // note: property order determines debugging output\n readonly reason: RetryErrorReason;\n readonly lastError: unknown;\n readonly errors: Array<unknown>;\n\n constructor({\n message,\n reason,\n errors,\n }: {\n message: string;\n reason: RetryErrorReason;\n errors: Array<unknown>;\n }) {\n super({ name, message });\n\n this.reason = reason;\n this.errors = errors;\n\n // separate our last error to make debugging via log easier:\n this.lastError = errors[errors.length - 1];\n }\n\n static isInstance(error: unknown): error is RetryError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import {\n LanguageModelV2,\n LanguageModelV2Content,\n LanguageModelV2ToolCall,\n} from '@ai-sdk/provider';\nimport {\n createIdGenerator,\n executeTool,\n getErrorMessage,\n IdGenerator,\n ProviderOptions,\n withUserAgentSuffix,\n} from '@ai-sdk/provider-utils';\nimport { Tracer } from '@opentelemetry/api';\nimport { NoOutputSpecifiedError } from '../error/no-output-specified-error';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport { ModelMessage } from '../prompt';\nimport { CallSettings } from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { prepareCallSettings } from '../prompt/prepare-call-settings';\nimport { prepareToolsAndToolChoice } from '../prompt/prepare-tools-and-tool-choice';\nimport { Prompt } from '../prompt/prompt';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { getBaseTelemetryAttributes } from '../telemetry/get-base-telemetry-attributes';\nimport { getTracer } from '../telemetry/get-tracer';\nimport { recordErrorOnSpan, recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport { stringifyForTelemetry } from '../telemetry/stringify-for-telemetry';\nimport { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport { LanguageModel, ToolChoice } from '../types';\nimport { addLanguageModelUsage, LanguageModelUsage } from '../types/usage';\nimport { asArray } from '../util/as-array';\nimport { DownloadFunction } from '../util/download/download-function';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { ContentPart } from './content-part';\nimport { extractTextContent } from './extract-text-content';\nimport { GenerateTextResult } from './generate-text-result';\nimport { DefaultGeneratedFile } from './generated-file';\nimport { Output } from './output';\nimport { parseToolCall } from './parse-tool-call';\nimport { PrepareStepFunction } from './prepare-step';\nimport { ResponseMessage } from './response-message';\nimport { DefaultStepResult, StepResult } from './step-result';\nimport {\n isStopConditionMet,\n stepCountIs,\n StopCondition,\n} from './stop-condition';\nimport { toResponseMessages } from './to-response-messages';\nimport { TypedToolCall } from './tool-call';\nimport { ToolCallRepairFunction } from './tool-call-repair-function';\nimport { TypedToolError } from './tool-error';\nimport { ToolOutput } from './tool-output';\nimport { TypedToolResult } from './tool-result';\nimport { ToolSet } from './tool-set';\nimport { VERSION } from '../version';\n\nconst originalGenerateId = createIdGenerator({\n prefix: 'aitxt',\n size: 24,\n});\n\n/**\nCallback that is set using the `onStepFinish` option.\n\n@param stepResult - The result of the step.\n */\nexport type GenerateTextOnStepFinishCallback<TOOLS extends ToolSet> = (\n stepResult: StepResult<TOOLS>,\n) => Promise<void> | void;\n\n/**\nGenerate a text and call tools for a given prompt using a language model.\n\nThis function does not stream the output. If you want to stream the output, use `streamText` instead.\n\n@param model - The language model to use.\n\n@param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n@param toolChoice - The tool choice strategy. Default: 'auto'.\n\n@param system - A system message that will be part of the prompt.\n@param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n@param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n\n@param maxOutputTokens - Maximum number of tokens to generate.\n@param temperature - Temperature setting.\nThe value is passed through to the provider. The range depends on the provider and model.\nIt is recommended to set either `temperature` or `topP`, but not both.\n@param topP - Nucleus sampling.\nThe value is passed through to the provider. The range depends on the provider and model.\nIt is recommended to set either `temperature` or `topP`, but not both.\n@param topK - Only sample from the top K options for each subsequent token.\nUsed to remove \"long tail\" low probability responses.\nRecommended for advanced use cases only. You usually only need to use temperature.\n@param presencePenalty - Presence penalty setting.\nIt affects the likelihood of the model to repeat information that is already in the prompt.\nThe value is passed through to the provider. The range depends on the provider and model.\n@param frequencyPenalty - Frequency penalty setting.\nIt affects the likelihood of the model to repeatedly use the same words or phrases.\nThe value is passed through to the provider. The range depends on the provider and model.\n@param stopSequences - Stop sequences.\nIf set, the model will stop generating text when one of the stop sequences is generated.\n@param seed - The seed (integer) to use for random sampling.\nIf set and supported by the model, calls will generate deterministic results.\n\n@param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n@param abortSignal - An optional abort signal that can be used to cancel the call.\n@param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n\n@param experimental_generateMessageId - Generate a unique ID for each message.\n\n@param onStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps.\n\n@returns\nA result object that contains the generated text, the results of the tool calls, and additional information.\n */\nexport async function generateText<\n TOOLS extends ToolSet,\n OUTPUT = never,\n OUTPUT_PARTIAL = never,\n>({\n model: modelArg,\n tools,\n toolChoice,\n system,\n prompt,\n messages,\n maxRetries: maxRetriesArg,\n abortSignal,\n headers,\n stopWhen = stepCountIs(1),\n experimental_output: output,\n experimental_telemetry: telemetry,\n providerOptions,\n experimental_activeTools,\n activeTools = experimental_activeTools,\n experimental_prepareStep,\n prepareStep = experimental_prepareStep,\n experimental_repairToolCall: repairToolCall,\n experimental_download: download,\n experimental_context,\n _internal: {\n generateId = originalGenerateId,\n currentDate = () => new Date(),\n } = {},\n onStepFinish,\n ...settings\n}: CallSettings &\n Prompt & {\n /**\nThe language model to use.\n */\n model: LanguageModel;\n\n /**\nThe tools that the model can call. The model needs to support calling tools.\n*/\n tools?: TOOLS;\n\n /**\nThe tool choice strategy. Default: 'auto'.\n */\n toolChoice?: ToolChoice<NoInfer<TOOLS>>;\n\n /**\nCondition for stopping the generation when there are tool results in the last step.\nWhen the condition is an array, any of the conditions can be met to stop the generation.\n\n@default stepCountIs(1)\n */\n stopWhen?:\n | StopCondition<NoInfer<TOOLS>>\n | Array<StopCondition<NoInfer<TOOLS>>>;\n\n /**\nOptional telemetry configuration (experimental).\n */\n experimental_telemetry?: TelemetrySettings;\n\n /**\nAdditional provider-specific options. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n * @deprecated Use `activeTools` instead.\n */\n experimental_activeTools?: Array<keyof NoInfer<TOOLS>>;\n\n /**\nLimits the tools that are available for the model to call without\nchanging the tool call and result types in the result.\n */\n activeTools?: Array<keyof NoInfer<TOOLS>>;\n\n /**\nOptional specification for parsing structured outputs from the LLM response.\n */\n experimental_output?: Output<OUTPUT, OUTPUT_PARTIAL>;\n\n /**\nCustom download function to use for URLs.\n\nBy default, files are downloaded if the model does not support the URL for the given media type.\n */\n experimental_download?: DownloadFunction | undefined;\n\n /**\n * @deprecated Use `prepareStep` instead.\n */\n experimental_prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;\n\n /**\nOptional function that you can use to provide different settings for a step.\n */\n prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;\n\n /**\nA function that attempts to repair a tool call that failed to parse.\n */\n experimental_repairToolCall?: ToolCallRepairFunction<NoInfer<TOOLS>>;\n\n /**\n Callback that is called when each step (LLM call) is finished, including intermediate steps.\n */\n onStepFinish?: GenerateTextOnStepFinishCallback<NoInfer<TOOLS>>;\n\n /**\n * Context that is passed into tool execution.\n *\n * Experimental (can break in patch releases).\n *\n * @default undefined\n */\n experimental_context?: unknown;\n\n /**\n * Internal. For test use only. May change without notice.\n */\n _internal?: {\n generateId?: IdGenerator;\n currentDate?: () => Date;\n };\n }): Promise<GenerateTextResult<TOOLS, OUTPUT>> {\n const model = resolveLanguageModel(modelArg);\n const stopConditions = asArray(stopWhen);\n const { maxRetries, retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal,\n });\n\n const callSettings = prepareCallSettings(settings);\n\n const headersWithUserAgent = withUserAgentSuffix(\n headers ?? {},\n `ai/${VERSION}`,\n );\n\n const baseTelemetryAttributes = getBaseTelemetryAttributes({\n model,\n telemetry,\n headers: headersWithUserAgent,\n settings: { ...callSettings, maxRetries },\n });\n\n const initialPrompt = await standardizePrompt({\n system,\n prompt,\n messages,\n } as Prompt);\n\n const tracer = getTracer(telemetry);\n\n try {\n return await recordSpan({\n name: 'ai.generateText',\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: 'ai.generateText',\n telemetry,\n }),\n ...baseTelemetryAttributes,\n // model:\n 'ai.model.provider': model.provider,\n 'ai.model.id': model.modelId,\n // specific settings that only make sense on the outer level:\n 'ai.prompt': {\n input: () => JSON.stringify({ system, prompt, messages }),\n },\n },\n }),\n tracer,\n fn: async span => {\n const callSettings = prepareCallSettings(settings);\n\n let currentModelResponse: Awaited<\n ReturnType<LanguageModelV2['doGenerate']>\n > & { response: { id: string; timestamp: Date; modelId: string } };\n let clientToolCalls: Array<TypedToolCall<TOOLS>> = [];\n let clientToolOutputs: Array<ToolOutput<TOOLS>> = [];\n const responseMessages: Array<ResponseMessage> = [];\n const steps: GenerateTextResult<TOOLS, OUTPUT>['steps'] = [];\n\n do {\n const stepInputMessages = [\n ...initialPrompt.messages,\n ...responseMessages,\n ];\n\n const prepareStepResult = await prepareStep?.({\n model,\n steps,\n stepNumber: steps.length,\n messages: stepInputMessages,\n });\n\n const stepModel = resolveLanguageModel(\n prepareStepResult?.model ?? model,\n );\n\n const promptMessages = await convertToLanguageModelPrompt({\n prompt: {\n system: prepareStepResult?.system ?? initialPrompt.system,\n messages: prepareStepResult?.messages ?? stepInputMessages,\n },\n supportedUrls: await stepModel.supportedUrls,\n download,\n });\n\n const { toolChoice: stepToolChoice, tools: stepTools } =\n prepareToolsAndToolChoice({\n tools,\n toolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n activeTools: prepareStepResult?.activeTools ?? activeTools,\n });\n\n currentModelResponse = await retry(() =>\n recordSpan({\n name: 'ai.generateText.doGenerate',\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: 'ai.generateText.doGenerate',\n telemetry,\n }),\n ...baseTelemetryAttributes,\n // model:\n 'ai.model.provider': stepModel.provider,\n 'ai.model.id': stepModel.modelId,\n // prompt:\n 'ai.prompt.messages': {\n input: () => stringifyForTelemetry(promptMessages),\n },\n 'ai.prompt.tools': {\n // convert the language model level tools:\n input: () => stepTools?.map(tool => JSON.stringify(tool)),\n },\n 'ai.prompt.toolChoice': {\n input: () =>\n stepToolChoice != null\n ? JSON.stringify(stepToolChoice)\n : undefined,\n },\n\n // standardized gen-ai llm span attributes:\n 'gen_ai.system': stepModel.provider,\n 'gen_ai.request.model': stepModel.modelId,\n 'gen_ai.request.frequency_penalty': settings.frequencyPenalty,\n 'gen_ai.request.max_tokens': settings.maxOutputTokens,\n 'gen_ai.request.presence_penalty': settings.presencePenalty,\n 'gen_ai.request.stop_sequences': settings.stopSequences,\n 'gen_ai.request.temperature':\n settings.temperature ?? undefined,\n 'gen_ai.request.top_k': settings.topK,\n 'gen_ai.request.top_p': settings.topP,\n },\n }),\n tracer,\n fn: async span => {\n const result = await stepModel.doGenerate({\n ...callSettings,\n tools: stepTools,\n toolChoice: stepToolChoice,\n responseFormat: output?.responseFormat,\n prompt: promptMessages,\n providerOptions,\n abortSignal,\n headers: headersWithUserAgent,\n });\n\n // Fill in default values:\n const responseData = {\n id: result.response?.id ?? generateId(),\n timestamp: result.response?.timestamp ?? currentDate(),\n modelId: result.response?.modelId ?? stepModel.modelId,\n headers: result.response?.headers,\n body: result.response?.body,\n };\n\n // Add response information to the span:\n span.setAttributes(\n selectTelemetryAttributes({\n telemetry,\n attributes: {\n 'ai.response.finishReason': result.finishReason,\n 'ai.response.text': {\n output: () => extractTextContent(result.content),\n },\n 'ai.response.toolCalls': {\n output: () => {\n const toolCalls = asToolCalls(result.content);\n return toolCalls == null\n ? undefined\n : JSON.stringify(toolCalls);\n },\n },\n 'ai.response.id': responseData.id,\n 'ai.response.model': responseData.modelId,\n 'ai.response.timestamp':\n responseData.timestamp.toISOString(),\n 'ai.response.providerMetadata': JSON.stringify(\n result.providerMetadata,\n ),\n\n // TODO rename telemetry attributes to inputTokens and outputTokens\n 'ai.usage.promptTokens': result.usage.inputTokens,\n 'ai.usage.completionTokens': result.usage.outputTokens,\n\n // standardized gen-ai llm span attributes:\n 'gen_ai.response.finish_reasons': [result.finishReason],\n 'gen_ai.response.id': responseData.id,\n 'gen_ai.response.model': responseData.modelId,\n 'gen_ai.usage.input_tokens': result.usage.inputTokens,\n 'gen_ai.usage.output_tokens': result.usage.outputTokens,\n },\n }),\n );\n\n return { ...result, response: responseData };\n },\n }),\n );\n\n // parse tool calls:\n const stepToolCalls: TypedToolCall<TOOLS>[] = await Promise.all(\n currentModelResponse.content\n .filter(\n (part): part is LanguageModelV2ToolCall =>\n part.type === 'tool-call',\n )\n .map(toolCall =>\n parseToolCall({\n toolCall,\n tools,\n repairToolCall,\n system,\n messages: stepInputMessages,\n }),\n ),\n );\n\n // notify the tools that the tool calls are available:\n for (const toolCall of stepToolCalls) {\n if (toolCall.invalid) {\n continue; // ignore invalid tool calls\n }\n\n const tool = tools![toolCall.toolName];\n if (tool?.onInputAvailable != null) {\n await tool.onInputAvailable({\n input: toolCall.input,\n toolCallId: toolCall.toolCallId,\n messages: stepInputMessages,\n abortSignal,\n experimental_context,\n });\n }\n }\n\n // insert error tool outputs for invalid tool calls:\n // TODO AI SDK 6: invalid inputs should not require output parts\n const invalidToolCalls = stepToolCalls.filter(\n toolCall => toolCall.invalid && toolCall.dynamic,\n );\n\n clientToolOutputs = [];\n\n for (const toolCall of invalidToolCalls) {\n clientToolOutputs.push({\n type: 'tool-error',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n error: getErrorMessage(toolCall.error!),\n dynamic: true,\n });\n }\n\n // execute client tool calls:\n clientToolCalls = stepToolCalls.filter(\n toolCall => !toolCall.providerExecuted,\n );\n\n if (tools != null) {\n clientToolOutputs.push(\n ...(await executeTools({\n toolCalls: clientToolCalls.filter(\n toolCall => !toolCall.invalid,\n ),\n tools,\n tracer,\n telemetry,\n messages: stepInputMessages,\n abortSignal,\n experimental_context,\n })),\n );\n }\n\n // content:\n const stepContent = asContent({\n content: currentModelResponse.content,\n toolCalls: stepToolCalls,\n toolOutputs: clientToolOutputs,\n });\n\n // append to messages for potential next step:\n responseMessages.push(\n ...toResponseMessages({\n content: stepContent,\n tools,\n }),\n );\n\n // Add step information (after response messages are updated):\n const currentStepResult: StepResult<TOOLS> = new DefaultStepResult({\n content: stepContent,\n finishReason: currentModelResponse.finishReason,\n usage: currentModelResponse.usage,\n warnings: currentModelResponse.warnings,\n providerMetadata: currentModelResponse.providerMetadata,\n request: currentModelResponse.request ?? {},\n response: {\n ...currentModelResponse.response,\n // deep clone msgs to avoid mutating past messages in multi-step:\n messages: structuredClone(responseMessages),\n },\n });\n\n logWarnings(currentModelResponse.warnings ?? []);\n\n steps.push(currentStepResult);\n await onStepFinish?.(currentStepResult);\n } while (\n // there are tool calls:\n clientToolCalls.length > 0 &&\n // all current tool calls have outputs (incl. execution errors):\n clientToolOutputs.length === clientToolCalls.length &&\n // continue until a stop condition is met:\n !(await isStopConditionMet({ stopConditions, steps }))\n );\n\n // Add response information to the span:\n span.setAttributes(\n selectTelemetryAttributes({\n telemetry,\n attributes: {\n 'ai.response.finishReason': currentModelResponse.finishReason,\n 'ai.response.text': {\n output: () => extractTextContent(currentModelResponse.content),\n },\n 'ai.response.toolCalls': {\n output: () => {\n const toolCalls = asToolCalls(currentModelResponse.content);\n return toolCalls == null\n ? undefined\n : JSON.stringify(toolCalls);\n },\n },\n 'ai.response.providerMetadata': JSON.stringify(\n currentModelResponse.providerMetadata,\n ),\n\n // TODO rename telemetry attributes to inputTokens and outputTokens\n 'ai.usage.promptTokens': currentModelResponse.usage.inputTokens,\n 'ai.usage.completionTokens':\n currentModelResponse.usage.outputTokens,\n },\n }),\n );\n\n const lastStep = steps[steps.length - 1];\n\n // parse output only if the last step was finished with \"stop\":\n let resolvedOutput;\n if (lastStep.finishReason === 'stop') {\n resolvedOutput = await output?.parseOutput(\n { text: lastStep.text },\n {\n response: lastStep.response,\n usage: lastStep.usage,\n finishReason: lastStep.finishReason,\n },\n );\n }\n\n return new DefaultGenerateTextResult({\n steps,\n resolvedOutput,\n });\n },\n });\n } catch (error) {\n throw wrapGatewayError(error);\n }\n}\n\nasync function executeTools<TOOLS extends ToolSet>({\n toolCalls,\n tools,\n tracer,\n telemetry,\n messages,\n abortSignal,\n experimental_context,\n}: {\n toolCalls: Array<TypedToolCall<TOOLS>>;\n tools: TOOLS;\n tracer: Tracer;\n telemetry: TelemetrySettings | undefined;\n messages: ModelMessage[];\n abortSignal: AbortSignal | undefined;\n experimental_context: unknown;\n}): Promise<Array<ToolOutput<TOOLS>>> {\n const toolOutputs = await Promise.all(\n toolCalls.map(async ({ toolCallId, toolName, input }) => {\n const tool = tools[toolName];\n\n if (tool?.execute == null) {\n return undefined;\n }\n\n return recordSpan({\n name: 'ai.toolCall',\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: 'ai.toolCall',\n telemetry,\n }),\n 'ai.toolCall.name': toolName,\n 'ai.toolCall.id': toolCallId,\n 'ai.toolCall.args': {\n output: () => JSON.stringify(input),\n },\n },\n }),\n tracer,\n fn: async span => {\n try {\n const stream = executeTool({\n execute: tool.execute!.bind(tool),\n input,\n options: {\n toolCallId,\n messages,\n abortSignal,\n experimental_context,\n },\n });\n\n let output: unknown;\n for await (const part of stream) {\n if (part.type === 'final') {\n output = part.output;\n }\n }\n try {\n span.setAttributes(\n selectTelemetryAttributes({\n telemetry,\n attributes: {\n 'ai.toolCall.result': {\n output: () => JSON.stringify(output),\n },\n },\n }),\n );\n } catch (ignored) {\n // JSON stringify might fail if the result is not serializable,\n // in which case we just ignore it. In the future we might want to\n // add an optional serialize method to the tool interface and warn\n // if the result is not serializable.\n }\n\n return {\n type: 'tool-result',\n toolCallId,\n toolName,\n input,\n output,\n dynamic: tool.type === 'dynamic',\n } as TypedToolResult<TOOLS>;\n } catch (error) {\n recordErrorOnSpan(span, error);\n return {\n type: 'tool-error',\n toolCallId,\n toolName,\n input,\n error,\n dynamic: tool.type === 'dynamic',\n } as TypedToolError<TOOLS>;\n }\n },\n });\n }),\n );\n\n return toolOutputs.filter(\n (output): output is NonNullable<typeof output> => output != null,\n );\n}\n\nclass DefaultGenerateTextResult<TOOLS extends ToolSet, OUTPUT>\n implements GenerateTextResult<TOOLS, OUTPUT>\n{\n readonly steps: GenerateTextResult<TOOLS, OUTPUT>['steps'];\n\n private readonly resolvedOutput: OUTPUT;\n\n constructor(options: {\n steps: GenerateTextResult<TOOLS, OUTPUT>['steps'];\n resolvedOutput: OUTPUT;\n }) {\n this.steps = options.steps;\n this.resolvedOutput = options.resolvedOutput;\n }\n\n private get finalStep() {\n return this.steps[this.steps.length - 1];\n }\n\n get content() {\n return this.finalStep.content;\n }\n\n get text() {\n return this.finalStep.text;\n }\n\n get files() {\n return this.finalStep.files;\n }\n\n get reasoningText() {\n return this.finalStep.reasoningText;\n }\n\n get reasoning() {\n return this.finalStep.reasoning;\n }\n\n get toolCalls() {\n return this.finalStep.toolCalls;\n }\n\n get staticToolCalls() {\n return this.finalStep.staticToolCalls;\n }\n\n get dynamicToolCalls() {\n return this.finalStep.dynamicToolCalls;\n }\n\n get toolResults() {\n return this.finalStep.toolResults;\n }\n\n get staticToolResults() {\n return this.finalStep.staticToolResults;\n }\n\n get dynamicToolResults() {\n return this.finalStep.dynamicToolResults;\n }\n\n get sources() {\n return this.finalStep.sources;\n }\n\n get finishReason() {\n return this.finalStep.finishReason;\n }\n\n get warnings() {\n return this.finalStep.warnings;\n }\n\n get providerMetadata() {\n return this.finalStep.providerMetadata;\n }\n\n get response() {\n return this.finalStep.response;\n }\n\n get request() {\n return this.finalStep.request;\n }\n\n get usage() {\n return this.finalStep.usage;\n }\n\n get totalUsage() {\n return this.steps.reduce(\n (totalUsage, step) => {\n return addLanguageModelUsage(totalUsage, step.usage);\n },\n {\n inputTokens: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n reasoningTokens: undefined,\n cachedInputTokens: undefined,\n } as LanguageModelUsage,\n );\n }\n\n get experimental_output() {\n if (this.resolvedOutput == null) {\n throw new NoOutputSpecifiedError();\n }\n\n return this.resolvedOutput;\n }\n}\n\nfunction asToolCalls(content: Array<LanguageModelV2Content>) {\n const parts = content.filter(\n (part): part is LanguageModelV2ToolCall => part.type === 'tool-call',\n );\n\n if (parts.length === 0) {\n return undefined;\n }\n\n return parts.map(toolCall => ({\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n }));\n}\n\nfunction asContent<TOOLS extends ToolSet>({\n content,\n toolCalls,\n toolOutputs,\n}: {\n content: Array<LanguageModelV2Content>;\n toolCalls: Array<TypedToolCall<TOOLS>>;\n toolOutputs: Array<ToolOutput<TOOLS>>;\n}): Array<ContentPart<TOOLS>> {\n return [\n ...content.map(part => {\n switch (part.type) {\n case 'text':\n case 'reasoning':\n case 'source':\n return part;\n\n case 'file': {\n return {\n type: 'file' as const,\n file: new DefaultGeneratedFile(part),\n };\n }\n\n case 'tool-call': {\n return toolCalls.find(\n toolCall => toolCall.toolCallId === part.toolCallId,\n )!;\n }\n\n case 'tool-result': {\n const toolCall = toolCalls.find(\n toolCall => toolCall.toolCallId === part.toolCallId,\n )!;\n\n if (toolCall == null) {\n throw new Error(`Tool call ${part.toolCallId} not found.`);\n }\n\n if (part.isError) {\n return {\n type: 'tool-error' as const,\n toolCallId: part.toolCallId,\n toolName: part.toolName as keyof TOOLS & string,\n input: toolCall.input,\n error: part.result,\n providerExecuted: true,\n dynamic: toolCall.dynamic,\n } as TypedToolError<TOOLS>;\n }\n\n return {\n type: 'tool-result' as const,\n toolCallId: part.toolCallId,\n toolName: part.toolName as keyof TOOLS & string,\n input: toolCall.input,\n output: part.result,\n providerExecuted: true,\n dynamic: toolCall.dynamic,\n } as TypedToolResult<TOOLS>;\n }\n }\n }),\n ...toolOutputs,\n ];\n}\n","export class JsonToSseTransformStream extends TransformStream<unknown, string> {\n constructor() {\n super({\n transform(part, controller) {\n controller.enqueue(`data: ${JSON.stringify(part)}\\n\\n`);\n },\n flush(controller) {\n controller.enqueue('data: [DONE]\\n\\n');\n },\n });\n }\n}\n","type State =\n | 'ROOT'\n | 'FINISH'\n | 'INSIDE_STRING'\n | 'INSIDE_STRING_ESCAPE'\n | 'INSIDE_LITERAL'\n | 'INSIDE_NUMBER'\n | 'INSIDE_OBJECT_START'\n | 'INSIDE_OBJECT_KEY'\n | 'INSIDE_OBJECT_AFTER_KEY'\n | 'INSIDE_OBJECT_BEFORE_VALUE'\n | 'INSIDE_OBJECT_AFTER_VALUE'\n | 'INSIDE_OBJECT_AFTER_COMMA'\n | 'INSIDE_ARRAY_START'\n | 'INSIDE_ARRAY_AFTER_VALUE'\n | 'INSIDE_ARRAY_AFTER_COMMA';\n\n// Implemented as a scanner with additional fixing\n// that performs a single linear time scan pass over the partial JSON.\n//\n// The states should ideally match relevant states from the JSON spec:\n// https://www.json.org/json-en.html\n//\n// Please note that invalid JSON is not considered/covered, because it\n// is assumed that the resulting JSON will be processed by a standard\n// JSON parser that will detect any invalid JSON.\nexport function fixJson(input: string): string {\n const stack: State[] = ['ROOT'];\n let lastValidIndex = -1;\n let literalStart: number | null = null;\n\n function processValueStart(char: string, i: number, swapState: State) {\n {\n switch (char) {\n case '\"': {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_STRING');\n break;\n }\n\n case 'f':\n case 't':\n case 'n': {\n lastValidIndex = i;\n literalStart = i;\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_LITERAL');\n break;\n }\n\n case '-': {\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_NUMBER');\n break;\n }\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9': {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_NUMBER');\n break;\n }\n\n case '{': {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_OBJECT_START');\n break;\n }\n\n case '[': {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_ARRAY_START');\n break;\n }\n }\n }\n }\n\n function processAfterObjectValue(char: string, i: number) {\n switch (char) {\n case ',': {\n stack.pop();\n stack.push('INSIDE_OBJECT_AFTER_COMMA');\n break;\n }\n case '}': {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n }\n }\n\n function processAfterArrayValue(char: string, i: number) {\n switch (char) {\n case ',': {\n stack.pop();\n stack.push('INSIDE_ARRAY_AFTER_COMMA');\n break;\n }\n case ']': {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n }\n }\n\n for (let i = 0; i < input.length; i++) {\n const char = input[i];\n const currentState = stack[stack.length - 1];\n\n switch (currentState) {\n case 'ROOT':\n processValueStart(char, i, 'FINISH');\n break;\n\n case 'INSIDE_OBJECT_START': {\n switch (char) {\n case '\"': {\n stack.pop();\n stack.push('INSIDE_OBJECT_KEY');\n break;\n }\n case '}': {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n }\n break;\n }\n\n case 'INSIDE_OBJECT_AFTER_COMMA': {\n switch (char) {\n case '\"': {\n stack.pop();\n stack.push('INSIDE_OBJECT_KEY');\n break;\n }\n }\n break;\n }\n\n case 'INSIDE_OBJECT_KEY': {\n switch (char) {\n case '\"': {\n stack.pop();\n stack.push('INSIDE_OBJECT_AFTER_KEY');\n break;\n }\n }\n break;\n }\n\n case 'INSIDE_OBJECT_AFTER_KEY': {\n switch (char) {\n case ':': {\n stack.pop();\n stack.push('INSIDE_OBJECT_BEFORE_VALUE');\n\n break;\n }\n }\n break;\n }\n\n case 'INSIDE_OBJECT_BEFORE_VALUE': {\n processValueStart(char, i, 'INSIDE_OBJECT_AFTER_VALUE');\n break;\n }\n\n case 'INSIDE_OBJECT_AFTER_VALUE': {\n processAfterObjectValue(char, i);\n break;\n }\n\n case 'INSIDE_STRING': {\n switch (char) {\n case '\"': {\n stack.pop();\n lastValidIndex = i;\n break;\n }\n\n case '\\\\': {\n stack.push('INSIDE_STRING_ESCAPE');\n break;\n }\n\n default: {\n lastValidIndex = i;\n }\n }\n\n break;\n }\n\n case 'INSIDE_ARRAY_START': {\n switch (char) {\n case ']': {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n\n default: {\n lastValidIndex = i;\n processValueStart(char, i, 'INSIDE_ARRAY_AFTER_VALUE');\n break;\n }\n }\n break;\n }\n\n case 'INSIDE_ARRAY_AFTER_VALUE': {\n switch (char) {\n case ',': {\n stack.pop();\n stack.push('INSIDE_ARRAY_AFTER_COMMA');\n break;\n }\n\n case ']': {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n\n default: {\n lastValidIndex = i;\n break;\n }\n }\n\n break;\n }\n\n case 'INSIDE_ARRAY_AFTER_COMMA': {\n processValueStart(char, i, 'INSIDE_ARRAY_AFTER_VALUE');\n break;\n }\n\n case 'INSIDE_STRING_ESCAPE': {\n stack.pop();\n lastValidIndex = i;\n\n break;\n }\n\n case 'INSIDE_NUMBER': {\n switch (char) {\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9': {\n lastValidIndex = i;\n break;\n }\n\n case 'e':\n case 'E':\n case '-':\n case '.': {\n break;\n }\n\n case ',': {\n stack.pop();\n\n if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n processAfterArrayValue(char, i);\n }\n\n if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n processAfterObjectValue(char, i);\n }\n\n break;\n }\n\n case '}': {\n stack.pop();\n\n if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n processAfterObjectValue(char, i);\n }\n\n break;\n }\n\n case ']': {\n stack.pop();\n\n if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n processAfterArrayValue(char, i);\n }\n\n break;\n }\n\n default: {\n stack.pop();\n break;\n }\n }\n\n break;\n }\n\n case 'INSIDE_LITERAL': {\n const partialLiteral = input.substring(literalStart!, i + 1);\n\n if (\n !'false'.startsWith(partialLiteral) &&\n !'true'.startsWith(partialLiteral) &&\n !'null'.startsWith(partialLiteral)\n ) {\n stack.pop();\n\n if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n processAfterObjectValue(char, i);\n } else if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n processAfterArrayValue(char, i);\n }\n } else {\n lastValidIndex = i;\n }\n\n break;\n }\n }\n }\n\n let result = input.slice(0, lastValidIndex + 1);\n\n for (let i = stack.length - 1; i >= 0; i--) {\n const state = stack[i];\n\n switch (state) {\n case 'INSIDE_STRING': {\n result += '\"';\n break;\n }\n\n case 'INSIDE_OBJECT_KEY':\n case 'INSIDE_OBJECT_AFTER_KEY':\n case 'INSIDE_OBJECT_AFTER_COMMA':\n case 'INSIDE_OBJECT_START':\n case 'INSIDE_OBJECT_BEFORE_VALUE':\n case 'INSIDE_OBJECT_AFTER_VALUE': {\n result += '}';\n break;\n }\n\n case 'INSIDE_ARRAY_START':\n case 'INSIDE_ARRAY_AFTER_COMMA':\n case 'INSIDE_ARRAY_AFTER_VALUE': {\n result += ']';\n break;\n }\n\n case 'INSIDE_LITERAL': {\n const partialLiteral = input.substring(literalStart!, input.length);\n\n if ('true'.startsWith(partialLiteral)) {\n result += 'true'.slice(partialLiteral.length);\n } else if ('false'.startsWith(partialLiteral)) {\n result += 'false'.slice(partialLiteral.length);\n } else if ('null'.startsWith(partialLiteral)) {\n result += 'null'.slice(partialLiteral.length);\n }\n }\n }\n }\n\n return result;\n}\n","import { JSONValue } from '@ai-sdk/provider';\nimport { safeParseJSON } from '@ai-sdk/provider-utils';\nimport { fixJson } from './fix-json';\n\nexport async function parsePartialJson(jsonText: string | undefined): Promise<{\n value: JSONValue | undefined;\n state:\n | 'undefined-input'\n | 'successful-parse'\n | 'repaired-parse'\n | 'failed-parse';\n}> {\n if (jsonText === undefined) {\n return { value: undefined, state: 'undefined-input' };\n }\n\n let result = await safeParseJSON({ text: jsonText });\n\n if (result.success) {\n return { value: result.value, state: 'successful-parse' };\n }\n\n result = await safeParseJSON({ text: fixJson(jsonText) });\n\n if (result.success) {\n return { value: result.value, state: 'repaired-parse' };\n }\n\n return { value: undefined, state: 'failed-parse' };\n}\n","import {\n getErrorMessage,\n LanguageModelV2,\n LanguageModelV2CallWarning,\n} from '@ai-sdk/provider';\nimport {\n createIdGenerator,\n DelayedPromise,\n IdGenerator,\n isAbortError,\n ProviderOptions,\n} from '@ai-sdk/provider-utils';\nimport { Span } from '@opentelemetry/api';\nimport { ServerResponse } from 'node:http';\nimport { NoOutputGeneratedError } from '../error';\nimport { NoOutputSpecifiedError } from '../error/no-output-specified-error';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport { CallSettings } from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { prepareCallSettings } from '../prompt/prepare-call-settings';\nimport { prepareToolsAndToolChoice } from '../prompt/prepare-tools-and-tool-choice';\nimport { Prompt } from '../prompt/prompt';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { getBaseTelemetryAttributes } from '../telemetry/get-base-telemetry-attributes';\nimport { getTracer } from '../telemetry/get-tracer';\nimport { recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport { stringifyForTelemetry } from '../telemetry/stringify-for-telemetry';\nimport { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport { createTextStreamResponse } from '../text-stream/create-text-stream-response';\nimport { pipeTextStreamToResponse } from '../text-stream/pipe-text-stream-to-response';\nimport { LanguageModelRequestMetadata } from '../types';\nimport {\n CallWarning,\n FinishReason,\n LanguageModel,\n ToolChoice,\n} from '../types/language-model';\nimport { ProviderMetadata } from '../types/provider-metadata';\nimport { addLanguageModelUsage, LanguageModelUsage } from '../types/usage';\nimport { UIMessage } from '../ui';\nimport { createUIMessageStreamResponse } from '../ui-message-stream/create-ui-message-stream-response';\nimport { getResponseUIMessageId } from '../ui-message-stream/get-response-ui-message-id';\nimport { handleUIMessageStreamFinish } from '../ui-message-stream/handle-ui-message-stream-finish';\nimport { pipeUIMessageStreamToResponse } from '../ui-message-stream/pipe-ui-message-stream-to-response';\nimport {\n InferUIMessageChunk,\n UIMessageChunk,\n} from '../ui-message-stream/ui-message-chunks';\nimport { UIMessageStreamResponseInit } from '../ui-message-stream/ui-message-stream-response-init';\nimport { InferUIMessageData, InferUIMessageMetadata } from '../ui/ui-messages';\nimport { asArray } from '../util/as-array';\nimport {\n AsyncIterableStream,\n createAsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport { consumeStream } from '../util/consume-stream';\nimport { createStitchableStream } from '../util/create-stitchable-stream';\nimport { DownloadFunction } from '../util/download/download-function';\nimport { now as originalNow } from '../util/now';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { ContentPart } from './content-part';\nimport { Output } from './output';\nimport { PrepareStepFunction } from './prepare-step';\nimport { ResponseMessage } from './response-message';\nimport {\n runToolsTransformation,\n SingleRequestTextStreamPart,\n} from './run-tools-transformation';\nimport { DefaultStepResult, StepResult } from './step-result';\nimport {\n isStopConditionMet,\n stepCountIs,\n StopCondition,\n} from './stop-condition';\nimport {\n ConsumeStreamOptions,\n StreamTextResult,\n TextStreamPart,\n UIMessageStreamOptions,\n} from './stream-text-result';\nimport { toResponseMessages } from './to-response-messages';\nimport { TypedToolCall } from './tool-call';\nimport { ToolCallRepairFunction } from './tool-call-repair-function';\nimport { ToolOutput } from './tool-output';\nimport { ToolSet } from './tool-set';\n\nconst originalGenerateId = createIdGenerator({\n prefix: 'aitxt',\n size: 24,\n});\n\n/**\nA transformation that is applied to the stream.\n\n@param stopStream - A function that stops the source stream.\n@param tools - The tools that are accessible to and can be called by the model. The model needs to support calling tools.\n */\nexport type StreamTextTransform<TOOLS extends ToolSet> = (options: {\n tools: TOOLS; // for type inference\n stopStream: () => void;\n}) => TransformStream<TextStreamPart<TOOLS>, TextStreamPart<TOOLS>>;\n\n/**\nCallback that is set using the `onError` option.\n\n@param event - The event that is passed to the callback.\n */\nexport type StreamTextOnErrorCallback = (event: {\n error: unknown;\n}) => PromiseLike<void> | void;\n\n/**\nCallback that is set using the `onStepFinish` option.\n\n@param stepResult - The result of the step.\n */\nexport type StreamTextOnStepFinishCallback<TOOLS extends ToolSet> = (\n stepResult: StepResult<TOOLS>,\n) => PromiseLike<void> | void;\n\n/**\nCallback that is set using the `onChunk` option.\n\n@param event - The event that is passed to the callback.\n */\nexport type StreamTextOnChunkCallback<TOOLS extends ToolSet> = (event: {\n chunk: Extract<\n TextStreamPart<TOOLS>,\n {\n type:\n | 'text-delta'\n | 'reasoning-delta'\n | 'source'\n | 'tool-call'\n | 'tool-input-start'\n | 'tool-input-delta'\n | 'tool-result'\n | 'raw';\n }\n >;\n}) => PromiseLike<void> | void;\n\n/**\nCallback that is set using the `onFinish` option.\n\n@param event - The event that is passed to the callback.\n */\nexport type StreamTextOnFinishCallback<TOOLS extends ToolSet> = (\n event: StepResult<TOOLS> & {\n /**\nDetails for all steps.\n */\n readonly steps: StepResult<TOOLS>[];\n\n /**\nTotal usage for all steps. This is the sum of the usage of all steps.\n */\n readonly totalUsage: LanguageModelUsage;\n },\n) => PromiseLike<void> | void;\n\n/**\nCallback that is set using the `onAbort` option.\n\n@param event - The event that is passed to the callback.\n */\nexport type StreamTextOnAbortCallback<TOOLS extends ToolSet> = (event: {\n /**\nDetails for all previously finished steps.\n */\n readonly steps: StepResult<TOOLS>[];\n}) => PromiseLike<void> | void;\n\n/**\nGenerate a text and call tools for a given prompt using a language model.\n\nThis function streams the output. If you do not want to stream the output, use `generateText` instead.\n\n@param model - The language model to use.\n@param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n\n@param system - A system message that will be part of the prompt.\n@param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n@param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n\n@param maxOutputTokens - Maximum number of tokens to generate.\n@param temperature - Temperature setting.\nThe value is passed through to the provider. The range depends on the provider and model.\nIt is recommended to set either `temperature` or `topP`, but not both.\n@param topP - Nucleus sampling.\nThe value is passed through to the provider. The range depends on the provider and model.\nIt is recommended to set either `temperature` or `topP`, but not both.\n@param topK - Only sample from the top K options for each subsequent token.\nUsed to remove \"long tail\" low probability responses.\nRecommended for advanced use cases only. You usually only need to use temperature.\n@param presencePenalty - Presence penalty setting.\nIt affects the likelihood of the model to repeat information that is already in the prompt.\nThe value is passed through to the provider. The range depends on the provider and model.\n@param frequencyPenalty - Frequency penalty setting.\nIt affects the likelihood of the model to repeatedly use the same words or phrases.\nThe value is passed through to the provider. The range depends on the provider and model.\n@param stopSequences - Stop sequences.\nIf set, the model will stop generating text when one of the stop sequences is generated.\n@param seed - The seed (integer) to use for random sampling.\nIf set and supported by the model, calls will generate deterministic results.\n\n@param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n@param abortSignal - An optional abort signal that can be used to cancel the call.\n@param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n\n@param maxSteps - Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.\n\n@param onChunk - Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved.\n@param onError - Callback that is called when an error occurs during streaming. You can use it to log errors.\n@param onStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps.\n@param onFinish - Callback that is called when the LLM response and all request tool executions\n(for tools that have an `execute` function) are finished.\n\n@return\nA result object for accessing different stream types and additional information.\n */\nexport function streamText<\n TOOLS extends ToolSet,\n OUTPUT = never,\n PARTIAL_OUTPUT = never,\n>({\n model,\n tools,\n toolChoice,\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n headers,\n stopWhen = stepCountIs(1),\n experimental_output: output,\n experimental_telemetry: telemetry,\n prepareStep,\n providerOptions,\n experimental_activeTools,\n activeTools = experimental_activeTools,\n experimental_repairToolCall: repairToolCall,\n experimental_transform: transform,\n experimental_download: download,\n includeRawChunks = false,\n onChunk,\n onError = ({ error }) => {\n console.error(error);\n },\n onFinish,\n onAbort,\n onStepFinish,\n experimental_context,\n _internal: {\n now = originalNow,\n generateId = originalGenerateId,\n currentDate = () => new Date(),\n } = {},\n ...settings\n}: CallSettings &\n Prompt & {\n /**\nThe language model to use.\n */\n model: LanguageModel;\n\n /**\nThe tools that the model can call. The model needs to support calling tools.\n */\n tools?: TOOLS;\n\n /**\nThe tool choice strategy. Default: 'auto'.\n */\n toolChoice?: ToolChoice<TOOLS>;\n\n /**\nCondition for stopping the generation when there are tool results in the last step.\nWhen the condition is an array, any of the conditions can be met to stop the generation.\n\n@default stepCountIs(1)\n */\n stopWhen?:\n | StopCondition<NoInfer<TOOLS>>\n | Array<StopCondition<NoInfer<TOOLS>>>;\n\n /**\nOptional telemetry configuration (experimental).\n */\n experimental_telemetry?: TelemetrySettings;\n\n /**\nAdditional provider-specific options. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n * @deprecated Use `activeTools` instead.\n */\n experimental_activeTools?: Array<keyof NoInfer<TOOLS>>;\n\n /**\n Limits the tools that are available for the model to call without\n changing the tool call and result types in the result.\n */\n activeTools?: Array<keyof NoInfer<TOOLS>>;\n\n /**\nOptional specification for parsing structured outputs from the LLM response.\n */\n experimental_output?: Output<OUTPUT, PARTIAL_OUTPUT>;\n\n /**\nOptional function that you can use to provide different settings for a step.\n\n@param options - The options for the step.\n@param options.steps - The steps that have been executed so far.\n@param options.stepNumber - The number of the step that is being executed.\n@param options.model - The model that is being used.\n\n@returns An object that contains the settings for the step.\nIf you return undefined (or for undefined settings), the settings from the outer level will be used.\n */\n prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;\n\n /**\nA function that attempts to repair a tool call that failed to parse.\n */\n experimental_repairToolCall?: ToolCallRepairFunction<TOOLS>;\n\n /**\nOptional stream transformations.\nThey are applied in the order they are provided.\nThe stream transformations must maintain the stream structure for streamText to work correctly.\n */\n experimental_transform?:\n | StreamTextTransform<TOOLS>\n | Array<StreamTextTransform<TOOLS>>;\n\n /**\nCustom download function to use for URLs.\n\nBy default, files are downloaded if the model does not support the URL for the given media type.\n */\n experimental_download?: DownloadFunction | undefined;\n\n /**\nWhether to include raw chunks from the provider in the stream.\nWhen enabled, you will receive raw chunks with type 'raw' that contain the unprocessed data from the provider.\nThis allows access to cutting-edge provider features not yet wrapped by the AI SDK.\nDefaults to false.\n */\n includeRawChunks?: boolean;\n\n /**\nCallback that is called for each chunk of the stream.\nThe stream processing will pause until the callback promise is resolved.\n */\n onChunk?: StreamTextOnChunkCallback<TOOLS>;\n\n /**\nCallback that is invoked when an error occurs during streaming.\nYou can use it to log errors.\nThe stream processing will pause until the callback promise is resolved.\n */\n onError?: StreamTextOnErrorCallback;\n\n /**\nCallback that is called when the LLM response and all request tool executions\n(for tools that have an `execute` function) are finished.\n\nThe usage is the combined usage of all steps.\n */\n onFinish?: StreamTextOnFinishCallback<TOOLS>;\n\n onAbort?: StreamTextOnAbortCallback<TOOLS>;\n\n /**\nCallback that is called when each step (LLM call) is finished, including intermediate steps.\n */\n onStepFinish?: StreamTextOnStepFinishCallback<TOOLS>;\n\n /**\n * Context that is passed into tool execution.\n *\n * Experimental (can break in patch releases).\n *\n * @default undefined\n */\n experimental_context?: unknown;\n\n /**\nInternal. For test use only. May change without notice.\n */\n _internal?: {\n now?: () => number;\n generateId?: IdGenerator;\n currentDate?: () => Date;\n };\n }): StreamTextResult<TOOLS, PARTIAL_OUTPUT> {\n return new DefaultStreamTextResult<TOOLS, OUTPUT, PARTIAL_OUTPUT>({\n model: resolveLanguageModel(model),\n telemetry,\n headers,\n settings,\n maxRetries,\n abortSignal,\n system,\n prompt,\n messages,\n tools,\n toolChoice,\n transforms: asArray(transform),\n activeTools,\n repairToolCall,\n stopConditions: asArray(stopWhen),\n output,\n providerOptions,\n prepareStep,\n includeRawChunks,\n onChunk,\n onError,\n onFinish,\n onAbort,\n onStepFinish,\n now,\n currentDate,\n generateId,\n experimental_context,\n download,\n });\n}\n\ntype EnrichedStreamPart<TOOLS extends ToolSet, PARTIAL_OUTPUT> = {\n part: TextStreamPart<TOOLS>;\n partialOutput: PARTIAL_OUTPUT | undefined;\n};\n\nfunction createOutputTransformStream<\n TOOLS extends ToolSet,\n OUTPUT,\n PARTIAL_OUTPUT,\n>(\n output: Output<OUTPUT, PARTIAL_OUTPUT> | undefined,\n): TransformStream<\n TextStreamPart<TOOLS>,\n EnrichedStreamPart<TOOLS, PARTIAL_OUTPUT>\n> {\n if (!output) {\n return new TransformStream<\n TextStreamPart<TOOLS>,\n EnrichedStreamPart<TOOLS, PARTIAL_OUTPUT>\n >({\n transform(chunk, controller) {\n controller.enqueue({ part: chunk, partialOutput: undefined });\n },\n });\n }\n\n let firstTextChunkId: string | undefined = undefined;\n let text = '';\n let textChunk = '';\n let lastPublishedJson = '';\n\n function publishTextChunk({\n controller,\n partialOutput = undefined,\n }: {\n controller: TransformStreamDefaultController<\n EnrichedStreamPart<TOOLS, PARTIAL_OUTPUT>\n >;\n partialOutput?: PARTIAL_OUTPUT;\n }) {\n controller.enqueue({\n part: {\n type: 'text-delta',\n id: firstTextChunkId!,\n text: textChunk,\n },\n partialOutput,\n });\n textChunk = '';\n }\n\n return new TransformStream<\n TextStreamPart<TOOLS>,\n EnrichedStreamPart<TOOLS, PARTIAL_OUTPUT>\n >({\n async transform(chunk, controller) {\n // ensure that we publish the last text chunk before the step finish:\n if (chunk.type === 'finish-step' && textChunk.length > 0) {\n publishTextChunk({ controller });\n }\n\n if (\n chunk.type !== 'text-delta' &&\n chunk.type !== 'text-start' &&\n chunk.type !== 'text-end'\n ) {\n controller.enqueue({ part: chunk, partialOutput: undefined });\n return;\n }\n\n // we have to pick a text chunk which contains the json text\n // since we are streaming, we have to pick the first text chunk\n if (firstTextChunkId == null) {\n firstTextChunkId = chunk.id;\n } else if (chunk.id !== firstTextChunkId) {\n controller.enqueue({ part: chunk, partialOutput: undefined });\n return;\n }\n\n if (chunk.type === 'text-start') {\n controller.enqueue({ part: chunk, partialOutput: undefined });\n return;\n }\n\n if (chunk.type === 'text-end') {\n if (textChunk.length > 0) {\n publishTextChunk({ controller });\n }\n controller.enqueue({ part: chunk, partialOutput: undefined });\n return;\n }\n\n text += chunk.text;\n textChunk += chunk.text;\n\n // only publish if partial json can be parsed:\n const result = await output.parsePartial({ text });\n if (result != null) {\n // only send new json if it has changed:\n const currentJson = JSON.stringify(result.partial);\n if (currentJson !== lastPublishedJson) {\n publishTextChunk({ controller, partialOutput: result.partial });\n lastPublishedJson = currentJson;\n }\n }\n },\n });\n}\n\nclass DefaultStreamTextResult<TOOLS extends ToolSet, OUTPUT, PARTIAL_OUTPUT>\n implements StreamTextResult<TOOLS, PARTIAL_OUTPUT>\n{\n private readonly _totalUsage = new DelayedPromise<\n Awaited<StreamTextResult<TOOLS, PARTIAL_OUTPUT>['usage']>\n >();\n private readonly _finishReason = new DelayedPromise<\n Awaited<StreamTextResult<TOOLS, PARTIAL_OUTPUT>['finishReason']>\n >();\n private readonly _steps = new DelayedPromise<\n Awaited<StreamTextResult<TOOLS, PARTIAL_OUTPUT>['steps']>\n >();\n\n private readonly addStream: (\n stream: ReadableStream<TextStreamPart<TOOLS>>,\n ) => void;\n\n private readonly closeStream: () => void;\n\n private baseStream: ReadableStream<EnrichedStreamPart<TOOLS, PARTIAL_OUTPUT>>;\n\n private output: Output<OUTPUT, PARTIAL_OUTPUT> | undefined;\n\n private includeRawChunks: boolean;\n\n private tools: TOOLS | undefined;\n\n constructor({\n model,\n telemetry,\n headers,\n settings,\n maxRetries: maxRetriesArg,\n abortSignal,\n system,\n prompt,\n messages,\n tools,\n toolChoice,\n transforms,\n activeTools,\n repairToolCall,\n stopConditions,\n output,\n providerOptions,\n prepareStep,\n includeRawChunks,\n now,\n currentDate,\n generateId,\n onChunk,\n onError,\n onFinish,\n onAbort,\n onStepFinish,\n experimental_context,\n download,\n }: {\n model: LanguageModelV2;\n telemetry: TelemetrySettings | undefined;\n headers: Record<string, string | undefined> | undefined;\n settings: Omit<CallSettings, 'abortSignal' | 'headers'>;\n maxRetries: number | undefined;\n abortSignal: AbortSignal | undefined;\n system: Prompt['system'];\n prompt: Prompt['prompt'];\n messages: Prompt['messages'];\n tools: TOOLS | undefined;\n toolChoice: ToolChoice<TOOLS> | undefined;\n transforms: Array<StreamTextTransform<TOOLS>>;\n activeTools: Array<keyof TOOLS> | undefined;\n repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;\n stopConditions: Array<StopCondition<NoInfer<TOOLS>>>;\n output: Output<OUTPUT, PARTIAL_OUTPUT> | undefined;\n providerOptions: ProviderOptions | undefined;\n prepareStep: PrepareStepFunction<NoInfer<TOOLS>> | undefined;\n includeRawChunks: boolean;\n now: () => number;\n currentDate: () => Date;\n generateId: () => string;\n experimental_context: unknown;\n download: DownloadFunction | undefined;\n\n // callbacks:\n onChunk: undefined | StreamTextOnChunkCallback<TOOLS>;\n onError: StreamTextOnErrorCallback;\n onFinish: undefined | StreamTextOnFinishCallback<TOOLS>;\n onAbort: undefined | StreamTextOnAbortCallback<TOOLS>;\n onStepFinish: undefined | StreamTextOnStepFinishCallback<TOOLS>;\n }) {\n this.output = output;\n this.includeRawChunks = includeRawChunks;\n this.tools = tools;\n\n // promise to ensure that the step has been fully processed by the event processor\n // before a new step is started. This is required because the continuation condition\n // needs the updated steps to determine if another step is needed.\n let stepFinish!: DelayedPromise<void>;\n\n let recordedContent: Array<ContentPart<TOOLS>> = [];\n const recordedResponseMessages: Array<ResponseMessage> = [];\n let recordedFinishReason: FinishReason | undefined = undefined;\n let recordedTotalUsage: LanguageModelUsage | undefined = undefined;\n let recordedRequest: LanguageModelRequestMetadata = {};\n let recordedWarnings: Array<CallWarning> = [];\n const recordedSteps: StepResult<TOOLS>[] = [];\n\n let rootSpan!: Span;\n\n let activeTextContent: Record<\n string,\n {\n type: 'text';\n text: string;\n providerMetadata: ProviderMetadata | undefined;\n }\n > = {};\n\n let activeReasoningContent: Record<\n string,\n {\n type: 'reasoning';\n text: string;\n providerMetadata: ProviderMetadata | undefined;\n }\n > = {};\n\n const eventProcessor = new TransformStream<\n EnrichedStreamPart<TOOLS, PARTIAL_OUTPUT>,\n EnrichedStreamPart<TOOLS, PARTIAL_OUTPUT>\n >({\n async transform(chunk, controller) {\n controller.enqueue(chunk); // forward the chunk to the next stream\n\n const { part } = chunk;\n\n if (\n part.type === 'text-delta' ||\n part.type === 'reasoning-delta' ||\n part.type === 'source' ||\n part.type === 'tool-call' ||\n part.type === 'tool-result' ||\n part.type === 'tool-input-start' ||\n part.type === 'tool-input-delta' ||\n part.type === 'raw'\n ) {\n await onChunk?.({ chunk: part });\n }\n\n if (part.type === 'error') {\n await onError({ error: wrapGatewayError(part.error) });\n }\n\n if (part.type === 'text-start') {\n activeTextContent[part.id] = {\n type: 'text',\n text: '',\n providerMetadata: part.providerMetadata,\n };\n\n recordedContent.push(activeTextContent[part.id]);\n }\n\n if (part.type === 'text-delta') {\n const activeText = activeTextContent[part.id];\n\n if (activeText == null) {\n controller.enqueue({\n part: {\n type: 'error',\n error: `text part ${part.id} not found`,\n },\n partialOutput: undefined,\n });\n return;\n }\n\n activeText.text += part.text;\n activeText.providerMetadata =\n part.providerMetadata ?? activeText.providerMetadata;\n }\n\n if (part.type === 'text-end') {\n const activeText = activeTextContent[part.id];\n\n if (activeText == null) {\n controller.enqueue({\n part: {\n type: 'error',\n error: `text part ${part.id} not found`,\n },\n partialOutput: undefined,\n });\n return;\n }\n\n activeText.providerMetadata =\n part.providerMetadata ?? activeText.providerMetadata;\n\n delete activeTextContent[part.id];\n }\n\n if (part.type === 'reasoning-start') {\n activeReasoningContent[part.id] = {\n type: 'reasoning',\n text: '',\n providerMetadata: part.providerMetadata,\n };\n\n recordedContent.push(activeReasoningContent[part.id]);\n }\n\n if (part.type === 'reasoning-delta') {\n const activeReasoning = activeReasoningContent[part.id];\n\n if (activeReasoning == null) {\n controller.enqueue({\n part: {\n type: 'error',\n error: `reasoning part ${part.id} not found`,\n },\n partialOutput: undefined,\n });\n return;\n }\n\n activeReasoning.text += part.text;\n activeReasoning.providerMetadata =\n part.providerMetadata ?? activeReasoning.providerMetadata;\n }\n\n if (part.type === 'reasoning-end') {\n const activeReasoning = activeReasoningContent[part.id];\n\n if (activeReasoning == null) {\n controller.enqueue({\n part: {\n type: 'error',\n error: `reasoning part ${part.id} not found`,\n },\n partialOutput: undefined,\n });\n return;\n }\n\n activeReasoning.providerMetadata =\n part.providerMetadata ?? activeReasoning.providerMetadata;\n\n delete activeReasoningContent[part.id];\n }\n\n if (part.type === 'file') {\n recordedContent.push({ type: 'file', file: part.file });\n }\n\n if (part.type === 'source') {\n recordedContent.push(part);\n }\n\n if (part.type === 'tool-call') {\n recordedContent.push(part);\n }\n\n if (part.type === 'tool-result' && !part.preliminary) {\n recordedContent.push(part);\n }\n\n if (part.type === 'tool-error') {\n recordedContent.push(part);\n }\n\n if (part.type === 'start-step') {\n recordedRequest = part.request;\n recordedWarnings = part.warnings;\n }\n\n if (part.type === 'finish-step') {\n const stepMessages = toResponseMessages({\n content: recordedContent,\n tools,\n });\n\n // Add step information (after response messages are updated):\n const currentStepResult: StepResult<TOOLS> = new DefaultStepResult({\n content: recordedContent,\n finishReason: part.finishReason,\n usage: part.usage,\n warnings: recordedWarnings,\n request: recordedRequest,\n response: {\n ...part.response,\n messages: [...recordedResponseMessages, ...stepMessages],\n },\n providerMetadata: part.providerMetadata,\n });\n\n await onStepFinish?.(currentStepResult);\n\n logWarnings(recordedWarnings);\n\n recordedSteps.push(currentStepResult);\n\n recordedContent = [];\n activeReasoningContent = {};\n activeTextContent = {};\n\n recordedResponseMessages.push(...stepMessages);\n\n // resolve the promise to signal that the step has been fully processed\n // by the event processor:\n stepFinish.resolve();\n }\n\n if (part.type === 'finish') {\n recordedTotalUsage = part.totalUsage;\n recordedFinishReason = part.finishReason;\n }\n },\n\n async flush(controller) {\n try {\n if (recordedSteps.length === 0) {\n const error = new NoOutputGeneratedError({\n message: 'No output generated. Check the stream for errors.',\n });\n\n self._finishReason.reject(error);\n self._totalUsage.reject(error);\n self._steps.reject(error);\n\n return; // no steps recorded (e.g. in error scenario)\n }\n\n // derived:\n const finishReason = recordedFinishReason ?? 'unknown';\n const totalUsage = recordedTotalUsage ?? {\n inputTokens: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n };\n\n // from finish:\n self._finishReason.resolve(finishReason);\n self._totalUsage.resolve(totalUsage);\n\n // aggregate results:\n self._steps.resolve(recordedSteps);\n\n // call onFinish callback:\n const finalStep = recordedSteps[recordedSteps.length - 1];\n await onFinish?.({\n finishReason,\n totalUsage,\n usage: finalStep.usage,\n content: finalStep.content,\n text: finalStep.text,\n reasoningText: finalStep.reasoningText,\n reasoning: finalStep.reasoning,\n files: finalStep.files,\n sources: finalStep.sources,\n toolCalls: finalStep.toolCalls,\n staticToolCalls: finalStep.staticToolCalls,\n dynamicToolCalls: finalStep.dynamicToolCalls,\n toolResults: finalStep.toolResults,\n staticToolResults: finalStep.staticToolResults,\n dynamicToolResults: finalStep.dynamicToolResults,\n request: finalStep.request,\n response: finalStep.response,\n warnings: finalStep.warnings,\n providerMetadata: finalStep.providerMetadata,\n steps: recordedSteps,\n });\n\n // Add response information to the root span:\n rootSpan.setAttributes(\n selectTelemetryAttributes({\n telemetry,\n attributes: {\n 'ai.response.finishReason': finishReason,\n 'ai.response.text': { output: () => finalStep.text },\n 'ai.response.toolCalls': {\n output: () =>\n finalStep.toolCalls?.length\n ? JSON.stringify(finalStep.toolCalls)\n : undefined,\n },\n 'ai.response.providerMetadata': JSON.stringify(\n finalStep.providerMetadata,\n ),\n\n 'ai.usage.inputTokens': totalUsage.inputTokens,\n 'ai.usage.outputTokens': totalUsage.outputTokens,\n 'ai.usage.totalTokens': totalUsage.totalTokens,\n 'ai.usage.reasoningTokens': totalUsage.reasoningTokens,\n 'ai.usage.cachedInputTokens': totalUsage.cachedInputTokens,\n },\n }),\n );\n } catch (error) {\n controller.error(error);\n } finally {\n rootSpan.end();\n }\n },\n });\n\n // initialize the stitchable stream and the transformed stream:\n const stitchableStream = createStitchableStream<TextStreamPart<TOOLS>>();\n this.addStream = stitchableStream.addStream;\n this.closeStream = stitchableStream.close;\n\n // resilient stream that handles abort signals and errors:\n const reader = stitchableStream.stream.getReader();\n let stream = new ReadableStream<TextStreamPart<TOOLS>>({\n async start(controller) {\n // send start event:\n controller.enqueue({ type: 'start' });\n },\n\n async pull(controller) {\n // abort handling:\n function abort() {\n onAbort?.({ steps: recordedSteps });\n controller.enqueue({ type: 'abort' });\n controller.close();\n }\n\n try {\n const { done, value } = await reader.read();\n\n if (done) {\n controller.close();\n return;\n }\n\n if (abortSignal?.aborted) {\n abort();\n return;\n }\n\n controller.enqueue(value);\n } catch (error) {\n if (isAbortError(error) && abortSignal?.aborted) {\n abort();\n } else {\n controller.error(error);\n }\n }\n },\n\n cancel(reason) {\n return stitchableStream.stream.cancel(reason);\n },\n });\n\n // transform the stream before output parsing\n // to enable replacement of stream segments:\n for (const transform of transforms) {\n stream = stream.pipeThrough(\n transform({\n tools: tools as TOOLS,\n stopStream() {\n stitchableStream.terminate();\n },\n }),\n );\n }\n\n this.baseStream = stream\n .pipeThrough(createOutputTransformStream(output))\n .pipeThrough(eventProcessor);\n\n const { maxRetries, retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal,\n });\n\n const tracer = getTracer(telemetry);\n\n const callSettings = prepareCallSettings(settings);\n\n const baseTelemetryAttributes = getBaseTelemetryAttributes({\n model,\n telemetry,\n headers,\n settings: { ...callSettings, maxRetries },\n });\n\n const self = this;\n\n recordSpan({\n name: 'ai.streamText',\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({ operationId: 'ai.streamText', telemetry }),\n ...baseTelemetryAttributes,\n // specific settings that only make sense on the outer level:\n 'ai.prompt': {\n input: () => JSON.stringify({ system, prompt, messages }),\n },\n },\n }),\n tracer,\n endWhenDone: false,\n fn: async rootSpanArg => {\n rootSpan = rootSpanArg;\n\n async function streamStep({\n currentStep,\n responseMessages,\n usage,\n }: {\n currentStep: number;\n responseMessages: Array<ResponseMessage>;\n usage: LanguageModelUsage;\n }) {\n const includeRawChunks = self.includeRawChunks;\n\n stepFinish = new DelayedPromise<void>();\n\n const initialPrompt = await standardizePrompt({\n system,\n prompt,\n messages,\n } as Prompt);\n\n const stepInputMessages = [\n ...initialPrompt.messages,\n ...responseMessages,\n ];\n\n const prepareStepResult = await prepareStep?.({\n model,\n steps: recordedSteps,\n stepNumber: recordedSteps.length,\n messages: stepInputMessages,\n });\n\n const stepModel = resolveLanguageModel(\n prepareStepResult?.model ?? model,\n );\n\n const promptMessages = await convertToLanguageModelPrompt({\n prompt: {\n system: prepareStepResult?.system ?? initialPrompt.system,\n messages: prepareStepResult?.messages ?? stepInputMessages,\n },\n supportedUrls: await stepModel.supportedUrls,\n download,\n });\n\n const { toolChoice: stepToolChoice, tools: stepTools } =\n prepareToolsAndToolChoice({\n tools,\n toolChoice: prepareStepResult?.toolChoice ?? toolChoice,\n activeTools: prepareStepResult?.activeTools ?? activeTools,\n });\n\n const {\n result: { stream, response, request },\n doStreamSpan,\n startTimestampMs,\n } = await retry(() =>\n recordSpan({\n name: 'ai.streamText.doStream',\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: 'ai.streamText.doStream',\n telemetry,\n }),\n ...baseTelemetryAttributes,\n // model:\n 'ai.model.provider': stepModel.provider,\n 'ai.model.id': stepModel.modelId,\n // prompt:\n 'ai.prompt.messages': {\n input: () => stringifyForTelemetry(promptMessages),\n },\n 'ai.prompt.tools': {\n // convert the language model level tools:\n input: () => stepTools?.map(tool => JSON.stringify(tool)),\n },\n 'ai.prompt.toolChoice': {\n input: () =>\n stepToolChoice != null\n ? JSON.stringify(stepToolChoice)\n : undefined,\n },\n\n // standardized gen-ai llm span attributes:\n 'gen_ai.system': stepModel.provider,\n 'gen_ai.request.model': stepModel.modelId,\n 'gen_ai.request.frequency_penalty':\n callSettings.frequencyPenalty,\n 'gen_ai.request.max_tokens': callSettings.maxOutputTokens,\n 'gen_ai.request.presence_penalty':\n callSettings.presencePenalty,\n 'gen_ai.request.stop_sequences': callSettings.stopSequences,\n 'gen_ai.request.temperature': callSettings.temperature,\n 'gen_ai.request.top_k': callSettings.topK,\n 'gen_ai.request.top_p': callSettings.topP,\n },\n }),\n tracer,\n endWhenDone: false,\n fn: async doStreamSpan => {\n return {\n startTimestampMs: now(), // get before the call\n doStreamSpan,\n result: await stepModel.doStream({\n ...callSettings,\n tools: stepTools,\n toolChoice: stepToolChoice,\n responseFormat: output?.responseFormat,\n prompt: promptMessages,\n providerOptions,\n abortSignal,\n headers,\n includeRawChunks,\n }),\n };\n },\n }),\n );\n\n const streamWithToolResults = runToolsTransformation({\n tools,\n generatorStream: stream,\n tracer,\n telemetry,\n system,\n messages: stepInputMessages,\n repairToolCall,\n abortSignal,\n experimental_context,\n });\n\n const stepRequest = request ?? {};\n const stepToolCalls: TypedToolCall<TOOLS>[] = [];\n const stepToolOutputs: ToolOutput<TOOLS>[] = [];\n let warnings: LanguageModelV2CallWarning[] | undefined;\n\n const activeToolCallToolNames: Record<string, string> = {};\n\n let stepFinishReason: FinishReason = 'unknown';\n let stepUsage: LanguageModelUsage = {\n inputTokens: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n };\n let stepProviderMetadata: ProviderMetadata | undefined;\n let stepFirstChunk = true;\n let stepResponse: { id: string; timestamp: Date; modelId: string } = {\n id: generateId(),\n timestamp: currentDate(),\n modelId: model.modelId,\n };\n\n // raw text as it comes from the provider. recorded for telemetry.\n let activeText = '';\n\n self.addStream(\n streamWithToolResults.pipeThrough(\n new TransformStream<\n SingleRequestTextStreamPart<TOOLS>,\n TextStreamPart<TOOLS>\n >({\n async transform(chunk, controller): Promise<void> {\n if (chunk.type === 'stream-start') {\n warnings = chunk.warnings;\n return; // stream start chunks are sent immediately and do not count as first chunk\n }\n\n if (stepFirstChunk) {\n // Telemetry for first chunk:\n const msToFirstChunk = now() - startTimestampMs;\n\n stepFirstChunk = false;\n\n doStreamSpan.addEvent('ai.stream.firstChunk', {\n 'ai.response.msToFirstChunk': msToFirstChunk,\n });\n\n doStreamSpan.setAttributes({\n 'ai.response.msToFirstChunk': msToFirstChunk,\n });\n\n // Step start:\n controller.enqueue({\n type: 'start-step',\n request: stepRequest,\n warnings: warnings ?? [],\n });\n }\n\n const chunkType = chunk.type;\n switch (chunkType) {\n case 'text-start':\n case 'text-end': {\n controller.enqueue(chunk);\n break;\n }\n\n case 'text-delta': {\n if (chunk.delta.length > 0) {\n controller.enqueue({\n type: 'text-delta',\n id: chunk.id,\n text: chunk.delta,\n providerMetadata: chunk.providerMetadata,\n });\n activeText += chunk.delta;\n }\n break;\n }\n\n case 'reasoning-start':\n case 'reasoning-end': {\n controller.enqueue(chunk);\n break;\n }\n\n case 'reasoning-delta': {\n controller.enqueue({\n type: 'reasoning-delta',\n id: chunk.id,\n text: chunk.delta,\n providerMetadata: chunk.providerMetadata,\n });\n break;\n }\n\n case 'tool-call': {\n controller.enqueue(chunk);\n // store tool calls for onFinish callback and toolCalls promise:\n stepToolCalls.push(chunk);\n break;\n }\n\n case 'tool-result': {\n controller.enqueue(chunk);\n\n if (!chunk.preliminary) {\n stepToolOutputs.push(chunk);\n }\n\n break;\n }\n\n case 'tool-error': {\n controller.enqueue(chunk);\n stepToolOutputs.push(chunk);\n break;\n }\n\n case 'response-metadata': {\n stepResponse = {\n id: chunk.id ?? stepResponse.id,\n timestamp: chunk.timestamp ?? stepResponse.timestamp,\n modelId: chunk.modelId ?? stepResponse.modelId,\n };\n break;\n }\n\n case 'finish': {\n // Note: tool executions might not be finished yet when the finish event is emitted.\n // store usage and finish reason for promises and onFinish callback:\n stepUsage = chunk.usage;\n stepFinishReason = chunk.finishReason;\n stepProviderMetadata = chunk.providerMetadata;\n\n // Telemetry for finish event timing\n // (since tool executions can take longer and distort calculations)\n const msToFinish = now() - startTimestampMs;\n doStreamSpan.addEvent('ai.stream.finish');\n doStreamSpan.setAttributes({\n 'ai.response.msToFinish': msToFinish,\n 'ai.response.avgOutputTokensPerSecond':\n (1000 * (stepUsage.outputTokens ?? 0)) / msToFinish,\n });\n\n break;\n }\n\n case 'file': {\n controller.enqueue(chunk);\n break;\n }\n\n case 'source': {\n controller.enqueue(chunk);\n break;\n }\n\n case 'tool-input-start': {\n activeToolCallToolNames[chunk.id] = chunk.toolName;\n\n const tool = tools?.[chunk.toolName];\n if (tool?.onInputStart != null) {\n await tool.onInputStart({\n toolCallId: chunk.id,\n messages: stepInputMessages,\n abortSignal,\n experimental_context,\n });\n }\n\n controller.enqueue({\n ...chunk,\n dynamic: tool?.type === 'dynamic',\n });\n break;\n }\n\n case 'tool-input-end': {\n delete activeToolCallToolNames[chunk.id];\n controller.enqueue(chunk);\n break;\n }\n\n case 'tool-input-delta': {\n const toolName = activeToolCallToolNames[chunk.id];\n const tool = tools?.[toolName];\n\n if (tool?.onInputDelta != null) {\n await tool.onInputDelta({\n inputTextDelta: chunk.delta,\n toolCallId: chunk.id,\n messages: stepInputMessages,\n abortSignal,\n experimental_context,\n });\n }\n\n controller.enqueue(chunk);\n break;\n }\n\n case 'error': {\n controller.enqueue(chunk);\n stepFinishReason = 'error';\n break;\n }\n\n case 'raw': {\n if (includeRawChunks) {\n controller.enqueue(chunk);\n }\n break;\n }\n\n default: {\n const exhaustiveCheck: never = chunkType;\n throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);\n }\n }\n },\n\n // invoke onFinish callback and resolve toolResults promise when the stream is about to close:\n async flush(controller) {\n const stepToolCallsJson =\n stepToolCalls.length > 0\n ? JSON.stringify(stepToolCalls)\n : undefined;\n\n // record telemetry information first to ensure best effort timing\n try {\n doStreamSpan.setAttributes(\n selectTelemetryAttributes({\n telemetry,\n attributes: {\n 'ai.response.finishReason': stepFinishReason,\n 'ai.response.text': {\n output: () => activeText,\n },\n 'ai.response.toolCalls': {\n output: () => stepToolCallsJson,\n },\n 'ai.response.id': stepResponse.id,\n 'ai.response.model': stepResponse.modelId,\n 'ai.response.timestamp':\n stepResponse.timestamp.toISOString(),\n 'ai.response.providerMetadata':\n JSON.stringify(stepProviderMetadata),\n\n 'ai.usage.inputTokens': stepUsage.inputTokens,\n 'ai.usage.outputTokens': stepUsage.outputTokens,\n 'ai.usage.totalTokens': stepUsage.totalTokens,\n 'ai.usage.reasoningTokens': stepUsage.reasoningTokens,\n 'ai.usage.cachedInputTokens':\n stepUsage.cachedInputTokens,\n\n // standardized gen-ai llm span attributes:\n 'gen_ai.response.finish_reasons': [stepFinishReason],\n 'gen_ai.response.id': stepResponse.id,\n 'gen_ai.response.model': stepResponse.modelId,\n 'gen_ai.usage.input_tokens': stepUsage.inputTokens,\n 'gen_ai.usage.output_tokens': stepUsage.outputTokens,\n },\n }),\n );\n } catch (error) {\n // ignore error setting telemetry attributes\n } finally {\n // finish doStreamSpan before other operations for correct timing:\n doStreamSpan.end();\n }\n\n controller.enqueue({\n type: 'finish-step',\n finishReason: stepFinishReason,\n usage: stepUsage,\n providerMetadata: stepProviderMetadata,\n response: {\n ...stepResponse,\n headers: response?.headers,\n },\n });\n\n const combinedUsage = addLanguageModelUsage(usage, stepUsage);\n\n // wait for the step to be fully processed by the event processor\n // to ensure that the recorded steps are complete:\n await stepFinish.promise;\n\n const clientToolCalls = stepToolCalls.filter(\n toolCall => toolCall.providerExecuted !== true,\n );\n const clientToolOutputs = stepToolOutputs.filter(\n toolOutput => toolOutput.providerExecuted !== true,\n );\n\n if (\n clientToolCalls.length > 0 &&\n // all current tool calls have outputs (incl. execution errors):\n clientToolOutputs.length === clientToolCalls.length &&\n // continue until a stop condition is met:\n !(await isStopConditionMet({\n stopConditions,\n steps: recordedSteps,\n }))\n ) {\n // append to messages for the next step:\n responseMessages.push(\n ...toResponseMessages({\n content:\n // use transformed content to create the messages for the next step:\n recordedSteps[recordedSteps.length - 1].content,\n tools,\n }),\n );\n\n try {\n await streamStep({\n currentStep: currentStep + 1,\n responseMessages,\n usage: combinedUsage,\n });\n } catch (error) {\n controller.enqueue({\n type: 'error',\n error,\n });\n\n self.closeStream();\n }\n } else {\n controller.enqueue({\n type: 'finish',\n finishReason: stepFinishReason,\n totalUsage: combinedUsage,\n });\n\n self.closeStream(); // close the stitchable stream\n }\n },\n }),\n ),\n );\n }\n\n // add the initial stream to the stitchable stream\n await streamStep({\n currentStep: 0,\n responseMessages: [],\n usage: {\n inputTokens: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n },\n });\n },\n }).catch(error => {\n // add an error stream part and close the streams:\n self.addStream(\n new ReadableStream({\n start(controller) {\n controller.enqueue({ type: 'error', error });\n controller.close();\n },\n }),\n );\n self.closeStream();\n });\n }\n\n get steps() {\n // when any of the promises are accessed, the stream is consumed\n // so it resolves without needing to consume the stream separately\n this.consumeStream();\n\n return this._steps.promise;\n }\n\n private get finalStep() {\n return this.steps.then(steps => steps[steps.length - 1]);\n }\n\n get content() {\n return this.finalStep.then(step => step.content);\n }\n\n get warnings() {\n return this.finalStep.then(step => step.warnings);\n }\n\n get providerMetadata() {\n return this.finalStep.then(step => step.providerMetadata);\n }\n\n get text() {\n return this.finalStep.then(step => step.text);\n }\n\n get reasoningText() {\n return this.finalStep.then(step => step.reasoningText);\n }\n\n get reasoning() {\n return this.finalStep.then(step => step.reasoning);\n }\n\n get sources() {\n return this.finalStep.then(step => step.sources);\n }\n\n get files() {\n return this.finalStep.then(step => step.files);\n }\n\n get toolCalls() {\n return this.finalStep.then(step => step.toolCalls);\n }\n\n get staticToolCalls() {\n return this.finalStep.then(step => step.staticToolCalls);\n }\n\n get dynamicToolCalls() {\n return this.finalStep.then(step => step.dynamicToolCalls);\n }\n\n get toolResults() {\n return this.finalStep.then(step => step.toolResults);\n }\n\n get staticToolResults() {\n return this.finalStep.then(step => step.staticToolResults);\n }\n\n get dynamicToolResults() {\n return this.finalStep.then(step => step.dynamicToolResults);\n }\n\n get usage() {\n return this.finalStep.then(step => step.usage);\n }\n\n get request() {\n return this.finalStep.then(step => step.request);\n }\n\n get response() {\n return this.finalStep.then(step => step.response);\n }\n\n get totalUsage() {\n // when any of the promises are accessed, the stream is consumed\n // so it resolves without needing to consume the stream separately\n this.consumeStream();\n\n return this._totalUsage.promise;\n }\n\n get finishReason() {\n // when any of the promises are accessed, the stream is consumed\n // so it resolves without needing to consume the stream separately\n this.consumeStream();\n\n return this._finishReason.promise;\n }\n\n /**\nSplit out a new stream from the original stream.\nThe original stream is replaced to allow for further splitting,\nsince we do not know how many times the stream will be split.\n\nNote: this leads to buffering the stream content on the server.\nHowever, the LLM results are expected to be small enough to not cause issues.\n */\n private teeStream() {\n const [stream1, stream2] = this.baseStream.tee();\n this.baseStream = stream2;\n return stream1;\n }\n\n get textStream(): AsyncIterableStream<string> {\n return createAsyncIterableStream(\n this.teeStream().pipeThrough(\n new TransformStream<EnrichedStreamPart<TOOLS, PARTIAL_OUTPUT>, string>({\n transform({ part }, controller) {\n if (part.type === 'text-delta') {\n controller.enqueue(part.text);\n }\n },\n }),\n ),\n );\n }\n\n get fullStream(): AsyncIterableStream<TextStreamPart<TOOLS>> {\n return createAsyncIterableStream(\n this.teeStream().pipeThrough(\n new TransformStream<\n EnrichedStreamPart<TOOLS, PARTIAL_OUTPUT>,\n TextStreamPart<TOOLS>\n >({\n transform({ part }, controller) {\n controller.enqueue(part);\n },\n }),\n ),\n );\n }\n\n async consumeStream(options?: ConsumeStreamOptions): Promise<void> {\n try {\n await consumeStream({\n stream: this.fullStream,\n onError: options?.onError,\n });\n } catch (error) {\n options?.onError?.(error);\n }\n }\n\n get experimental_partialOutputStream(): AsyncIterableStream<PARTIAL_OUTPUT> {\n if (this.output == null) {\n throw new NoOutputSpecifiedError();\n }\n\n return createAsyncIterableStream(\n this.teeStream().pipeThrough(\n new TransformStream<\n EnrichedStreamPart<TOOLS, PARTIAL_OUTPUT>,\n PARTIAL_OUTPUT\n >({\n transform({ partialOutput }, controller) {\n if (partialOutput != null) {\n controller.enqueue(partialOutput);\n }\n },\n }),\n ),\n );\n }\n\n toUIMessageStream<UI_MESSAGE extends UIMessage>({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning = true,\n sendSources = false,\n sendStart = true,\n sendFinish = true,\n onError = getErrorMessage,\n }: UIMessageStreamOptions<UI_MESSAGE> = {}): AsyncIterableStream<\n InferUIMessageChunk<UI_MESSAGE>\n > {\n const responseMessageId =\n generateMessageId != null\n ? getResponseUIMessageId({\n originalMessages,\n responseMessageId: generateMessageId,\n })\n : undefined;\n\n const toolNamesByCallId: Record<string, string> = {};\n\n const isDynamic = (toolCallId: string) => {\n const toolName = toolNamesByCallId[toolCallId];\n const dynamic = this.tools?.[toolName]?.type === 'dynamic';\n return dynamic ? true : undefined; // only send when dynamic to reduce data transfer\n };\n\n const baseStream = this.fullStream.pipeThrough(\n new TransformStream<\n TextStreamPart<TOOLS>,\n UIMessageChunk<\n InferUIMessageMetadata<UI_MESSAGE>,\n InferUIMessageData<UI_MESSAGE>\n >\n >({\n transform: async (part, controller) => {\n const messageMetadataValue = messageMetadata?.({ part });\n\n const partType = part.type;\n switch (partType) {\n case 'text-start': {\n controller.enqueue({\n type: 'text-start',\n id: part.id,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n });\n break;\n }\n\n case 'text-delta': {\n controller.enqueue({\n type: 'text-delta',\n id: part.id,\n delta: part.text,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n });\n break;\n }\n\n case 'text-end': {\n controller.enqueue({\n type: 'text-end',\n id: part.id,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n });\n break;\n }\n\n case 'reasoning-start': {\n controller.enqueue({\n type: 'reasoning-start',\n id: part.id,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n });\n break;\n }\n\n case 'reasoning-delta': {\n if (sendReasoning) {\n controller.enqueue({\n type: 'reasoning-delta',\n id: part.id,\n delta: part.text,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n });\n }\n break;\n }\n\n case 'reasoning-end': {\n controller.enqueue({\n type: 'reasoning-end',\n id: part.id,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n });\n break;\n }\n\n case 'file': {\n controller.enqueue({\n type: 'file',\n mediaType: part.file.mediaType,\n url: `data:${part.file.mediaType};base64,${part.file.base64}`,\n });\n break;\n }\n\n case 'source': {\n if (sendSources && part.sourceType === 'url') {\n controller.enqueue({\n type: 'source-url',\n sourceId: part.id,\n url: part.url,\n title: part.title,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n });\n }\n\n if (sendSources && part.sourceType === 'document') {\n controller.enqueue({\n type: 'source-document',\n sourceId: part.id,\n mediaType: part.mediaType,\n title: part.title,\n filename: part.filename,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n });\n }\n break;\n }\n\n case 'tool-input-start': {\n toolNamesByCallId[part.id] = part.toolName;\n const dynamic = isDynamic(part.id);\n\n controller.enqueue({\n type: 'tool-input-start',\n toolCallId: part.id,\n toolName: part.toolName,\n ...(part.providerExecuted != null\n ? { providerExecuted: part.providerExecuted }\n : {}),\n ...(dynamic != null ? { dynamic } : {}),\n });\n break;\n }\n\n case 'tool-input-delta': {\n controller.enqueue({\n type: 'tool-input-delta',\n toolCallId: part.id,\n inputTextDelta: part.delta,\n });\n break;\n }\n\n case 'tool-call': {\n toolNamesByCallId[part.toolCallId] = part.toolName;\n const dynamic = isDynamic(part.toolCallId);\n\n if (part.invalid) {\n controller.enqueue({\n type: 'tool-input-error',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n ...(part.providerExecuted != null\n ? { providerExecuted: part.providerExecuted }\n : {}),\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n ...(dynamic != null ? { dynamic } : {}),\n errorText: onError(part.error),\n });\n } else {\n controller.enqueue({\n type: 'tool-input-available',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n ...(part.providerExecuted != null\n ? { providerExecuted: part.providerExecuted }\n : {}),\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n ...(dynamic != null ? { dynamic } : {}),\n });\n }\n\n break;\n }\n\n case 'tool-result': {\n const dynamic = isDynamic(part.toolCallId);\n\n controller.enqueue({\n type: 'tool-output-available',\n toolCallId: part.toolCallId,\n output: part.output,\n ...(part.providerExecuted != null\n ? { providerExecuted: part.providerExecuted }\n : {}),\n ...(part.preliminary != null\n ? { preliminary: part.preliminary }\n : {}),\n ...(dynamic != null ? { dynamic } : {}),\n });\n break;\n }\n\n case 'tool-error': {\n const dynamic = isDynamic(part.toolCallId);\n\n controller.enqueue({\n type: 'tool-output-error',\n toolCallId: part.toolCallId,\n errorText: onError(part.error),\n ...(part.providerExecuted != null\n ? { providerExecuted: part.providerExecuted }\n : {}),\n ...(dynamic != null ? { dynamic } : {}),\n });\n break;\n }\n\n case 'error': {\n controller.enqueue({\n type: 'error',\n errorText: onError(part.error),\n });\n break;\n }\n\n case 'start-step': {\n controller.enqueue({ type: 'start-step' });\n break;\n }\n\n case 'finish-step': {\n controller.enqueue({ type: 'finish-step' });\n break;\n }\n\n case 'start': {\n if (sendStart) {\n controller.enqueue({\n type: 'start',\n ...(messageMetadataValue != null\n ? { messageMetadata: messageMetadataValue }\n : {}),\n ...(responseMessageId != null\n ? { messageId: responseMessageId }\n : {}),\n });\n }\n break;\n }\n\n case 'finish': {\n if (sendFinish) {\n controller.enqueue({\n type: 'finish',\n finishReason: part.finishReason,\n ...(messageMetadataValue != null\n ? { messageMetadata: messageMetadataValue }\n : {}),\n });\n }\n break;\n }\n\n case 'abort': {\n controller.enqueue(part);\n break;\n }\n\n case 'tool-input-end': {\n break;\n }\n\n case 'raw': {\n // Raw chunks are not included in UI message streams\n // as they contain provider-specific data for developer use\n break;\n }\n\n default: {\n const exhaustiveCheck: never = partType;\n throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);\n }\n }\n\n // start and finish events already have metadata\n // so we only need to send metadata for other parts\n if (\n messageMetadataValue != null &&\n partType !== 'start' &&\n partType !== 'finish'\n ) {\n controller.enqueue({\n type: 'message-metadata',\n messageMetadata: messageMetadataValue,\n });\n }\n },\n }),\n );\n\n return createAsyncIterableStream(\n handleUIMessageStreamFinish<UI_MESSAGE>({\n stream: baseStream,\n messageId: responseMessageId ?? generateMessageId?.(),\n originalMessages,\n onFinish,\n onError,\n }),\n );\n }\n\n pipeUIMessageStreamToResponse<UI_MESSAGE extends UIMessage>(\n response: ServerResponse,\n {\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendFinish,\n sendStart,\n onError,\n ...init\n }: UIMessageStreamResponseInit & UIMessageStreamOptions<UI_MESSAGE> = {},\n ) {\n pipeUIMessageStreamToResponse({\n response,\n stream: this.toUIMessageStream({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendFinish,\n sendStart,\n onError,\n }),\n ...init,\n });\n }\n\n pipeTextStreamToResponse(response: ServerResponse, init?: ResponseInit) {\n pipeTextStreamToResponse({\n response,\n textStream: this.textStream,\n ...init,\n });\n }\n\n toUIMessageStreamResponse<UI_MESSAGE extends UIMessage>({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendFinish,\n sendStart,\n onError,\n ...init\n }: UIMessageStreamResponseInit &\n UIMessageStreamOptions<UI_MESSAGE> = {}): Response {\n return createUIMessageStreamResponse({\n stream: this.toUIMessageStream({\n originalMessages,\n generateMessageId,\n onFinish,\n messageMetadata,\n sendReasoning,\n sendSources,\n sendFinish,\n sendStart,\n onError,\n }),\n ...init,\n });\n }\n\n toTextStreamResponse(init?: ResponseInit): Response {\n return createTextStreamResponse({\n textStream: this.textStream,\n ...init,\n });\n }\n}\n","import { JSONValue } from '@ai-sdk/provider';\nimport {\n createIdGenerator,\n FlexibleSchema,\n InferSchema,\n ProviderOptions,\n withUserAgentSuffix,\n} from '@ai-sdk/provider-utils';\nimport { NoObjectGeneratedError } from '../error/no-object-generated-error';\nimport { extractReasoningContent } from '../generate-text/extract-reasoning-content';\nimport { extractTextContent } from '../generate-text/extract-text-content';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport { CallSettings } from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { prepareCallSettings } from '../prompt/prepare-call-settings';\nimport { Prompt } from '../prompt/prompt';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { getBaseTelemetryAttributes } from '../telemetry/get-base-telemetry-attributes';\nimport { getTracer } from '../telemetry/get-tracer';\nimport { recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport { stringifyForTelemetry } from '../telemetry/stringify-for-telemetry';\nimport { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport {\n CallWarning,\n FinishReason,\n LanguageModel,\n} from '../types/language-model';\nimport { LanguageModelRequestMetadata } from '../types/language-model-request-metadata';\nimport { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport { ProviderMetadata } from '../types/provider-metadata';\nimport { LanguageModelUsage } from '../types/usage';\nimport { DownloadFunction } from '../util/download/download-function';\nimport { prepareHeaders } from '../util/prepare-headers';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { VERSION } from '../version';\nimport { GenerateObjectResult } from './generate-object-result';\nimport { getOutputStrategy } from './output-strategy';\nimport { parseAndValidateObjectResultWithRepair } from './parse-and-validate-object-result';\nimport { RepairTextFunction } from './repair-text';\nimport { validateObjectGenerationInput } from './validate-object-generation-input';\n\nconst originalGenerateId = createIdGenerator({ prefix: 'aiobj', size: 24 });\n\n/**\nGenerate a structured, typed object for a given prompt and schema using a language model.\n\nThis function does not stream the output. If you want to stream the output, use `streamObject` instead.\n\n@param model - The language model to use.\n@param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n\n@param system - A system message that will be part of the prompt.\n@param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n@param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n\n@param maxOutputTokens - Maximum number of tokens to generate.\n@param temperature - Temperature setting.\nThe value is passed through to the provider. The range depends on the provider and model.\nIt is recommended to set either `temperature` or `topP`, but not both.\n@param topP - Nucleus sampling.\nThe value is passed through to the provider. The range depends on the provider and model.\nIt is recommended to set either `temperature` or `topP`, but not both.\n@param topK - Only sample from the top K options for each subsequent token.\nUsed to remove \"long tail\" low probability responses.\nRecommended for advanced use cases only. You usually only need to use temperature.\n@param presencePenalty - Presence penalty setting.\nIt affects the likelihood of the model to repeat information that is already in the prompt.\nThe value is passed through to the provider. The range depends on the provider and model.\n@param frequencyPenalty - Frequency penalty setting.\nIt affects the likelihood of the model to repeatedly use the same words or phrases.\nThe value is passed through to the provider. The range depends on the provider and model.\n@param stopSequences - Stop sequences.\nIf set, the model will stop generating text when one of the stop sequences is generated.\n@param seed - The seed (integer) to use for random sampling.\nIf set and supported by the model, calls will generate deterministic results.\n\n@param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n@param abortSignal - An optional abort signal that can be used to cancel the call.\n@param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n\n@param schema - The schema of the object that the model should generate.\n@param schemaName - Optional name of the output that should be generated.\nUsed by some providers for additional LLM guidance, e.g.\nvia tool or schema name.\n@param schemaDescription - Optional description of the output that should be generated.\nUsed by some providers for additional LLM guidance, e.g.\nvia tool or schema description.\n\n@param output - The type of the output.\n\n- 'object': The output is an object.\n- 'array': The output is an array.\n- 'enum': The output is an enum.\n- 'no-schema': The output is not a schema.\n\n@param experimental_repairText - A function that attempts to repair the raw output of the model\nto enable JSON parsing.\n\n@param experimental_telemetry - Optional telemetry configuration (experimental).\n\n@param providerOptions - Additional provider-specific options. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n\n@returns\nA result object that contains the generated object, the finish reason, the token usage, and additional information.\n */\nexport async function generateObject<\n SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<JSONValue>,\n OUTPUT extends\n | 'object'\n | 'array'\n | 'enum'\n | 'no-schema' = InferSchema<SCHEMA> extends string ? 'enum' : 'object',\n RESULT = OUTPUT extends 'array'\n ? Array<InferSchema<SCHEMA>>\n : InferSchema<SCHEMA>,\n>(\n options: Omit<CallSettings, 'stopSequences'> &\n Prompt &\n (OUTPUT extends 'enum'\n ? {\n /**\nThe enum values that the model should use.\n */\n enum: Array<RESULT>;\n output: 'enum';\n }\n : OUTPUT extends 'no-schema'\n ? {}\n : {\n /**\nThe schema of the object that the model should generate.\n */\n schema: SCHEMA;\n\n /**\nOptional name of the output that should be generated.\nUsed by some providers for additional LLM guidance, e.g.\nvia tool or schema name.\n */\n schemaName?: string;\n\n /**\nOptional description of the output that should be generated.\nUsed by some providers for additional LLM guidance, e.g.\nvia tool or schema description.\n */\n schemaDescription?: string;\n }) & {\n output?: OUTPUT;\n\n /**\n The language model to use.\n */\n model: LanguageModel;\n /**\n A function that attempts to repair the raw output of the model\n to enable JSON parsing.\n */\n experimental_repairText?: RepairTextFunction;\n\n /**\n Optional telemetry configuration (experimental).\n */\n\n experimental_telemetry?: TelemetrySettings;\n\n /**\n Custom download function to use for URLs.\n\n By default, files are downloaded if the model does not support the URL for the given media type.\n */\n experimental_download?: DownloadFunction | undefined;\n\n /**\n Additional provider-specific options. They are passed through\n to the provider from the AI SDK and enable provider-specific\n functionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n * Internal. For test use only. May change without notice.\n */\n _internal?: {\n generateId?: () => string;\n currentDate?: () => Date;\n };\n },\n): Promise<GenerateObjectResult<RESULT>> {\n const {\n model: modelArg,\n output = 'object',\n system,\n prompt,\n messages,\n maxRetries: maxRetriesArg,\n abortSignal,\n headers,\n experimental_repairText: repairText,\n experimental_telemetry: telemetry,\n experimental_download: download,\n providerOptions,\n _internal: {\n generateId = originalGenerateId,\n currentDate = () => new Date(),\n } = {},\n ...settings\n } = options;\n\n const model = resolveLanguageModel(modelArg);\n\n const enumValues = 'enum' in options ? options.enum : undefined;\n const {\n schema: inputSchema,\n schemaDescription,\n schemaName,\n } = 'schema' in options ? options : {};\n\n validateObjectGenerationInput({\n output,\n schema: inputSchema,\n schemaName,\n schemaDescription,\n enumValues,\n });\n\n const { maxRetries, retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal,\n });\n\n const outputStrategy = getOutputStrategy({\n output,\n schema: inputSchema,\n enumValues,\n });\n\n const callSettings = prepareCallSettings(settings);\n\n const headersWithUserAgent = withUserAgentSuffix(\n headers ?? {},\n `ai/${VERSION}`,\n );\n\n const baseTelemetryAttributes = getBaseTelemetryAttributes({\n model,\n telemetry,\n headers: headersWithUserAgent,\n settings: { ...callSettings, maxRetries },\n });\n\n const tracer = getTracer(telemetry);\n\n try {\n return await recordSpan({\n name: 'ai.generateObject',\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: 'ai.generateObject',\n telemetry,\n }),\n ...baseTelemetryAttributes,\n // specific settings that only make sense on the outer level:\n 'ai.prompt': {\n input: () => JSON.stringify({ system, prompt, messages }),\n },\n 'ai.schema':\n outputStrategy.jsonSchema != null\n ? { input: () => JSON.stringify(outputStrategy.jsonSchema) }\n : undefined,\n 'ai.schema.name': schemaName,\n 'ai.schema.description': schemaDescription,\n 'ai.settings.output': outputStrategy.type,\n },\n }),\n tracer,\n fn: async span => {\n let result: string;\n let finishReason: FinishReason;\n let usage: LanguageModelUsage;\n let warnings: CallWarning[] | undefined;\n let response: LanguageModelResponseMetadata;\n let request: LanguageModelRequestMetadata;\n let resultProviderMetadata: ProviderMetadata | undefined;\n let reasoning: string | undefined;\n\n const standardizedPrompt = await standardizePrompt({\n system,\n prompt,\n messages,\n } as Prompt);\n\n const promptMessages = await convertToLanguageModelPrompt({\n prompt: standardizedPrompt,\n supportedUrls: await model.supportedUrls,\n download,\n });\n\n const generateResult = await retry(() =>\n recordSpan({\n name: 'ai.generateObject.doGenerate',\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: 'ai.generateObject.doGenerate',\n telemetry,\n }),\n ...baseTelemetryAttributes,\n 'ai.prompt.messages': {\n input: () => stringifyForTelemetry(promptMessages),\n },\n\n // standardized gen-ai llm span attributes:\n 'gen_ai.system': model.provider,\n 'gen_ai.request.model': model.modelId,\n 'gen_ai.request.frequency_penalty':\n callSettings.frequencyPenalty,\n 'gen_ai.request.max_tokens': callSettings.maxOutputTokens,\n 'gen_ai.request.presence_penalty': callSettings.presencePenalty,\n 'gen_ai.request.temperature': callSettings.temperature,\n 'gen_ai.request.top_k': callSettings.topK,\n 'gen_ai.request.top_p': callSettings.topP,\n },\n }),\n tracer,\n fn: async span => {\n const result = await model.doGenerate({\n responseFormat: {\n type: 'json',\n schema: outputStrategy.jsonSchema,\n name: schemaName,\n description: schemaDescription,\n },\n ...prepareCallSettings(settings),\n prompt: promptMessages,\n providerOptions,\n abortSignal,\n headers: headersWithUserAgent,\n });\n\n const responseData = {\n id: result.response?.id ?? generateId(),\n timestamp: result.response?.timestamp ?? currentDate(),\n modelId: result.response?.modelId ?? model.modelId,\n headers: result.response?.headers,\n body: result.response?.body,\n };\n\n const text = extractTextContent(result.content);\n const reasoning = extractReasoningContent(result.content);\n\n if (text === undefined) {\n throw new NoObjectGeneratedError({\n message:\n 'No object generated: the model did not return a response.',\n response: responseData,\n usage: result.usage,\n finishReason: result.finishReason,\n });\n }\n\n // Add response information to the span:\n span.setAttributes(\n selectTelemetryAttributes({\n telemetry,\n attributes: {\n 'ai.response.finishReason': result.finishReason,\n 'ai.response.object': { output: () => text },\n 'ai.response.id': responseData.id,\n 'ai.response.model': responseData.modelId,\n 'ai.response.timestamp':\n responseData.timestamp.toISOString(),\n 'ai.response.providerMetadata': JSON.stringify(\n result.providerMetadata,\n ),\n\n // TODO rename telemetry attributes to inputTokens and outputTokens\n 'ai.usage.promptTokens': result.usage.inputTokens,\n 'ai.usage.completionTokens': result.usage.outputTokens,\n\n // standardized gen-ai llm span attributes:\n 'gen_ai.response.finish_reasons': [result.finishReason],\n 'gen_ai.response.id': responseData.id,\n 'gen_ai.response.model': responseData.modelId,\n 'gen_ai.usage.input_tokens': result.usage.inputTokens,\n 'gen_ai.usage.output_tokens': result.usage.outputTokens,\n },\n }),\n );\n\n return {\n ...result,\n objectText: text,\n reasoning,\n responseData,\n };\n },\n }),\n );\n\n result = generateResult.objectText;\n finishReason = generateResult.finishReason;\n usage = generateResult.usage;\n warnings = generateResult.warnings;\n resultProviderMetadata = generateResult.providerMetadata;\n request = generateResult.request ?? {};\n response = generateResult.responseData;\n reasoning = generateResult.reasoning;\n\n logWarnings(warnings);\n\n const object = await parseAndValidateObjectResultWithRepair(\n result,\n outputStrategy,\n repairText,\n {\n response,\n usage,\n finishReason,\n },\n );\n\n // Add response information to the span:\n span.setAttributes(\n selectTelemetryAttributes({\n telemetry,\n attributes: {\n 'ai.response.finishReason': finishReason,\n 'ai.response.object': {\n output: () => JSON.stringify(object),\n },\n 'ai.response.providerMetadata': JSON.stringify(\n resultProviderMetadata,\n ),\n\n // TODO rename telemetry attributes to inputTokens and outputTokens\n 'ai.usage.promptTokens': usage.inputTokens,\n 'ai.usage.completionTokens': usage.outputTokens,\n },\n }),\n );\n\n return new DefaultGenerateObjectResult({\n object,\n reasoning,\n finishReason,\n usage,\n warnings,\n request,\n response,\n providerMetadata: resultProviderMetadata,\n });\n },\n });\n } catch (error) {\n throw wrapGatewayError(error);\n }\n}\n\nclass DefaultGenerateObjectResult<T> implements GenerateObjectResult<T> {\n readonly object: GenerateObjectResult<T>['object'];\n readonly finishReason: GenerateObjectResult<T>['finishReason'];\n readonly usage: GenerateObjectResult<T>['usage'];\n readonly warnings: GenerateObjectResult<T>['warnings'];\n readonly providerMetadata: GenerateObjectResult<T>['providerMetadata'];\n readonly response: GenerateObjectResult<T>['response'];\n readonly request: GenerateObjectResult<T>['request'];\n readonly reasoning: GenerateObjectResult<T>['reasoning'];\n\n constructor(options: {\n object: GenerateObjectResult<T>['object'];\n finishReason: GenerateObjectResult<T>['finishReason'];\n usage: GenerateObjectResult<T>['usage'];\n warnings: GenerateObjectResult<T>['warnings'];\n providerMetadata: GenerateObjectResult<T>['providerMetadata'];\n response: GenerateObjectResult<T>['response'];\n request: GenerateObjectResult<T>['request'];\n reasoning: GenerateObjectResult<T>['reasoning'];\n }) {\n this.object = options.object;\n this.finishReason = options.finishReason;\n this.usage = options.usage;\n this.warnings = options.warnings;\n this.providerMetadata = options.providerMetadata;\n this.response = options.response;\n this.request = options.request;\n this.reasoning = options.reasoning;\n }\n\n toJsonResponse(init?: ResponseInit): Response {\n return new Response(JSON.stringify(this.object), {\n status: init?.status ?? 200,\n headers: prepareHeaders(init?.headers, {\n 'content-type': 'application/json; charset=utf-8',\n }),\n });\n }\n}\n","import {\n JSONValue,\n LanguageModelV2CallWarning,\n LanguageModelV2FinishReason,\n LanguageModelV2StreamPart,\n LanguageModelV2Usage,\n SharedV2ProviderMetadata,\n} from '@ai-sdk/provider';\nimport {\n createIdGenerator,\n DelayedPromise,\n FlexibleSchema,\n ProviderOptions,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { ServerResponse } from 'http';\nimport { logWarnings } from '../logger/log-warnings';\nimport { resolveLanguageModel } from '../model/resolve-model';\nimport { CallSettings } from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { prepareCallSettings } from '../prompt/prepare-call-settings';\nimport { Prompt } from '../prompt/prompt';\nimport { standardizePrompt } from '../prompt/standardize-prompt';\nimport { wrapGatewayError } from '../prompt/wrap-gateway-error';\nimport { assembleOperationName } from '../telemetry/assemble-operation-name';\nimport { getBaseTelemetryAttributes } from '../telemetry/get-base-telemetry-attributes';\nimport { getTracer } from '../telemetry/get-tracer';\nimport { recordSpan } from '../telemetry/record-span';\nimport { selectTelemetryAttributes } from '../telemetry/select-telemetry-attributes';\nimport { stringifyForTelemetry } from '../telemetry/stringify-for-telemetry';\nimport { TelemetrySettings } from '../telemetry/telemetry-settings';\nimport { createTextStreamResponse } from '../text-stream/create-text-stream-response';\nimport { pipeTextStreamToResponse } from '../text-stream/pipe-text-stream-to-response';\nimport {\n CallWarning,\n FinishReason,\n LanguageModel,\n} from '../types/language-model';\nimport { LanguageModelRequestMetadata } from '../types/language-model-request-metadata';\nimport { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport { ProviderMetadata } from '../types/provider-metadata';\nimport { LanguageModelUsage } from '../types/usage';\nimport { DeepPartial, isDeepEqualData, parsePartialJson } from '../util';\nimport {\n AsyncIterableStream,\n createAsyncIterableStream,\n} from '../util/async-iterable-stream';\nimport { createStitchableStream } from '../util/create-stitchable-stream';\nimport { DownloadFunction } from '../util/download/download-function';\nimport { now as originalNow } from '../util/now';\nimport { prepareRetries } from '../util/prepare-retries';\nimport { getOutputStrategy, OutputStrategy } from './output-strategy';\nimport { parseAndValidateObjectResultWithRepair } from './parse-and-validate-object-result';\nimport { RepairTextFunction } from './repair-text';\nimport { ObjectStreamPart, StreamObjectResult } from './stream-object-result';\nimport { validateObjectGenerationInput } from './validate-object-generation-input';\n\nconst originalGenerateId = createIdGenerator({ prefix: 'aiobj', size: 24 });\n\n/**\nCallback that is set using the `onError` option.\n\n@param event - The event that is passed to the callback.\n */\nexport type StreamObjectOnErrorCallback = (event: {\n error: unknown;\n}) => Promise<void> | void;\n\n/**\nCallback that is set using the `onFinish` option.\n\n@param event - The event that is passed to the callback.\n */\nexport type StreamObjectOnFinishCallback<RESULT> = (event: {\n /**\nThe token usage of the generated response.\n*/\n usage: LanguageModelUsage;\n\n /**\nThe generated object. Can be undefined if the final object does not match the schema.\n*/\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n*/\n error: unknown | undefined;\n\n /**\nResponse metadata.\n */\n response: LanguageModelResponseMetadata;\n\n /**\nWarnings from the model provider (e.g. unsupported settings).\n*/\n warnings?: CallWarning[];\n\n /**\nAdditional provider-specific metadata. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n*/\n providerMetadata: ProviderMetadata | undefined;\n}) => Promise<void> | void;\n\n/**\nGenerate a structured, typed object for a given prompt and schema using a language model.\n\nThis function streams the output. If you do not want to stream the output, use `generateObject` instead.\n\n@param model - The language model to use.\n@param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.\n\n@param system - A system message that will be part of the prompt.\n@param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.\n@param messages - A list of messages. You can either use `prompt` or `messages` but not both.\n\n@param maxOutputTokens - Maximum number of tokens to generate.\n@param temperature - Temperature setting.\nThe value is passed through to the provider. The range depends on the provider and model.\nIt is recommended to set either `temperature` or `topP`, but not both.\n@param topP - Nucleus sampling.\nThe value is passed through to the provider. The range depends on the provider and model.\nIt is recommended to set either `temperature` or `topP`, but not both.\n@param topK - Only sample from the top K options for each subsequent token.\nUsed to remove \"long tail\" low probability responses.\nRecommended for advanced use cases only. You usually only need to use temperature.\n@param presencePenalty - Presence penalty setting.\nIt affects the likelihood of the model to repeat information that is already in the prompt.\nThe value is passed through to the provider. The range depends on the provider and model.\n@param frequencyPenalty - Frequency penalty setting.\nIt affects the likelihood of the model to repeatedly use the same words or phrases.\nThe value is passed through to the provider. The range depends on the provider and model.\n@param stopSequences - Stop sequences.\nIf set, the model will stop generating text when one of the stop sequences is generated.\n@param seed - The seed (integer) to use for random sampling.\nIf set and supported by the model, calls will generate deterministic results.\n\n@param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.\n@param abortSignal - An optional abort signal that can be used to cancel the call.\n@param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.\n\n@param schema - The schema of the object that the model should generate.\n@param schemaName - Optional name of the output that should be generated.\nUsed by some providers for additional LLM guidance, e.g.\nvia tool or schema name.\n@param schemaDescription - Optional description of the output that should be generated.\nUsed by some providers for additional LLM guidance, e.g.\nvia tool or schema description.\n\n@param output - The type of the output.\n\n- 'object': The output is an object.\n- 'array': The output is an array.\n- 'enum': The output is an enum.\n- 'no-schema': The output is not a schema.\n\n@param experimental_telemetry - Optional telemetry configuration (experimental).\n\n@param providerOptions - Additional provider-specific options. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n\n@returns\nA result object for accessing the partial object stream and additional information.\n */\nexport function streamObject<\n SCHEMA extends FlexibleSchema<unknown> = FlexibleSchema<JSONValue>,\n OUTPUT extends\n | 'object'\n | 'array'\n | 'enum'\n | 'no-schema' = InferSchema<SCHEMA> extends string ? 'enum' : 'object',\n RESULT = OUTPUT extends 'array'\n ? Array<InferSchema<SCHEMA>>\n : InferSchema<SCHEMA>,\n>(\n options: Omit<CallSettings, 'stopSequences'> &\n Prompt &\n (OUTPUT extends 'enum'\n ? {\n /**\nThe enum values that the model should use.\n */\n enum: Array<RESULT>;\n output: 'enum';\n }\n : OUTPUT extends 'no-schema'\n ? {}\n : {\n /**\nThe schema of the object that the model should generate.\n */\n schema: SCHEMA;\n\n /**\nOptional name of the output that should be generated.\nUsed by some providers for additional LLM guidance, e.g.\nvia tool or schema name.\n */\n schemaName?: string;\n\n /**\nOptional description of the output that should be generated.\nUsed by some providers for additional LLM guidance, e.g.\nvia tool or schema description.\n */\n schemaDescription?: string;\n }) & {\n output?: OUTPUT;\n\n /**\nThe language model to use.\n */\n model: LanguageModel;\n\n /**\nA function that attempts to repair the raw output of the model\nto enable JSON parsing.\n */\n experimental_repairText?: RepairTextFunction;\n\n /**\nOptional telemetry configuration (experimental).\n */\n\n experimental_telemetry?: TelemetrySettings;\n\n /**\n Custom download function to use for URLs.\n\n By default, files are downloaded if the model does not support the URL for the given media type.\n */\n experimental_download?: DownloadFunction | undefined;\n\n /**\nAdditional provider-specific options. They are passed through\nto the provider from the AI SDK and enable provider-specific\nfunctionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\nCallback that is invoked when an error occurs during streaming.\nYou can use it to log errors.\nThe stream processing will pause until the callback promise is resolved.\n */\n onError?: StreamObjectOnErrorCallback;\n\n /**\nCallback that is called when the LLM response and the final object validation are finished.\n*/\n onFinish?: StreamObjectOnFinishCallback<RESULT>;\n\n /**\n * Internal. For test use only. May change without notice.\n */\n _internal?: {\n generateId?: () => string;\n currentDate?: () => Date;\n now?: () => number;\n };\n },\n): StreamObjectResult<\n OUTPUT extends 'enum'\n ? string\n : OUTPUT extends 'array'\n ? RESULT\n : DeepPartial<RESULT>,\n OUTPUT extends 'array' ? RESULT : RESULT,\n OUTPUT extends 'array'\n ? RESULT extends Array<infer U>\n ? AsyncIterableStream<U>\n : never\n : never\n> {\n const {\n model,\n output = 'object',\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n headers,\n experimental_repairText: repairText,\n experimental_telemetry: telemetry,\n experimental_download: download,\n providerOptions,\n onError = ({ error }: { error: unknown }) => {\n console.error(error);\n },\n onFinish,\n _internal: {\n generateId = originalGenerateId,\n currentDate = () => new Date(),\n now = originalNow,\n } = {},\n ...settings\n } = options;\n\n const enumValues =\n 'enum' in options && options.enum ? options.enum : undefined;\n\n const {\n schema: inputSchema,\n schemaDescription,\n schemaName,\n } = 'schema' in options ? options : {};\n\n validateObjectGenerationInput({\n output,\n schema: inputSchema,\n schemaName,\n schemaDescription,\n enumValues,\n });\n\n const outputStrategy = getOutputStrategy({\n output,\n schema: inputSchema,\n enumValues,\n });\n\n return new DefaultStreamObjectResult({\n model,\n telemetry,\n headers,\n settings,\n maxRetries,\n abortSignal,\n outputStrategy,\n system,\n prompt,\n messages,\n schemaName,\n schemaDescription,\n providerOptions,\n repairText,\n onError,\n onFinish,\n download,\n generateId,\n currentDate,\n now,\n });\n}\n\nclass DefaultStreamObjectResult<PARTIAL, RESULT, ELEMENT_STREAM>\n implements StreamObjectResult<PARTIAL, RESULT, ELEMENT_STREAM>\n{\n private readonly _object = new DelayedPromise<RESULT>();\n private readonly _usage = new DelayedPromise<LanguageModelUsage>();\n private readonly _providerMetadata = new DelayedPromise<\n ProviderMetadata | undefined\n >();\n private readonly _warnings = new DelayedPromise<CallWarning[] | undefined>();\n private readonly _request =\n new DelayedPromise<LanguageModelRequestMetadata>();\n private readonly _response =\n new DelayedPromise<LanguageModelResponseMetadata>();\n private readonly _finishReason = new DelayedPromise<FinishReason>();\n\n private readonly baseStream: ReadableStream<ObjectStreamPart<PARTIAL>>;\n\n private readonly outputStrategy: OutputStrategy<\n PARTIAL,\n RESULT,\n ELEMENT_STREAM\n >;\n\n constructor({\n model: modelArg,\n headers,\n telemetry,\n settings,\n maxRetries: maxRetriesArg,\n abortSignal,\n outputStrategy,\n system,\n prompt,\n messages,\n schemaName,\n schemaDescription,\n providerOptions,\n repairText,\n onError,\n onFinish,\n download,\n generateId,\n currentDate,\n now,\n }: {\n model: LanguageModel;\n telemetry: TelemetrySettings | undefined;\n headers: Record<string, string | undefined> | undefined;\n settings: Omit<CallSettings, 'abortSignal' | 'headers'>;\n maxRetries: number | undefined;\n abortSignal: AbortSignal | undefined;\n outputStrategy: OutputStrategy<PARTIAL, RESULT, ELEMENT_STREAM>;\n system: Prompt['system'];\n prompt: Prompt['prompt'];\n messages: Prompt['messages'];\n schemaName: string | undefined;\n schemaDescription: string | undefined;\n providerOptions: ProviderOptions | undefined;\n repairText: RepairTextFunction | undefined;\n onError: StreamObjectOnErrorCallback;\n onFinish: StreamObjectOnFinishCallback<RESULT> | undefined;\n download: DownloadFunction | undefined;\n generateId: () => string;\n currentDate: () => Date;\n now: () => number;\n }) {\n const model = resolveLanguageModel(modelArg);\n\n const { maxRetries, retry } = prepareRetries({\n maxRetries: maxRetriesArg,\n abortSignal,\n });\n\n const callSettings = prepareCallSettings(settings);\n\n const baseTelemetryAttributes = getBaseTelemetryAttributes({\n model,\n telemetry,\n headers,\n settings: { ...callSettings, maxRetries },\n });\n\n const tracer = getTracer(telemetry);\n const self = this;\n\n const stitchableStream =\n createStitchableStream<ObjectStreamPart<PARTIAL>>();\n\n const eventProcessor = new TransformStream<\n ObjectStreamPart<PARTIAL>,\n ObjectStreamPart<PARTIAL>\n >({\n transform(chunk, controller) {\n controller.enqueue(chunk);\n\n if (chunk.type === 'error') {\n onError({ error: wrapGatewayError(chunk.error) });\n }\n },\n });\n\n this.baseStream = stitchableStream.stream.pipeThrough(eventProcessor);\n\n recordSpan({\n name: 'ai.streamObject',\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: 'ai.streamObject',\n telemetry,\n }),\n ...baseTelemetryAttributes,\n // specific settings that only make sense on the outer level:\n 'ai.prompt': {\n input: () => JSON.stringify({ system, prompt, messages }),\n },\n 'ai.schema':\n outputStrategy.jsonSchema != null\n ? { input: () => JSON.stringify(outputStrategy.jsonSchema) }\n : undefined,\n 'ai.schema.name': schemaName,\n 'ai.schema.description': schemaDescription,\n 'ai.settings.output': outputStrategy.type,\n },\n }),\n tracer,\n endWhenDone: false,\n fn: async rootSpan => {\n const standardizedPrompt = await standardizePrompt({\n system,\n prompt,\n messages,\n } as Prompt);\n\n const callOptions = {\n responseFormat: {\n type: 'json' as const,\n schema: outputStrategy.jsonSchema,\n name: schemaName,\n description: schemaDescription,\n },\n ...prepareCallSettings(settings),\n prompt: await convertToLanguageModelPrompt({\n prompt: standardizedPrompt,\n supportedUrls: await model.supportedUrls,\n download,\n }),\n providerOptions,\n abortSignal,\n headers,\n includeRawChunks: false,\n };\n\n const transformer: Transformer<\n LanguageModelV2StreamPart,\n ObjectStreamInputPart\n > = {\n transform: (chunk, controller) => {\n switch (chunk.type) {\n case 'text-delta':\n controller.enqueue(chunk.delta);\n break;\n case 'response-metadata':\n case 'finish':\n case 'error':\n case 'stream-start':\n controller.enqueue(chunk);\n break;\n }\n },\n };\n\n const {\n result: { stream, response, request },\n doStreamSpan,\n startTimestampMs,\n } = await retry(() =>\n recordSpan({\n name: 'ai.streamObject.doStream',\n attributes: selectTelemetryAttributes({\n telemetry,\n attributes: {\n ...assembleOperationName({\n operationId: 'ai.streamObject.doStream',\n telemetry,\n }),\n ...baseTelemetryAttributes,\n 'ai.prompt.messages': {\n input: () => stringifyForTelemetry(callOptions.prompt),\n },\n\n // standardized gen-ai llm span attributes:\n 'gen_ai.system': model.provider,\n 'gen_ai.request.model': model.modelId,\n 'gen_ai.request.frequency_penalty':\n callSettings.frequencyPenalty,\n 'gen_ai.request.max_tokens': callSettings.maxOutputTokens,\n 'gen_ai.request.presence_penalty': callSettings.presencePenalty,\n 'gen_ai.request.temperature': callSettings.temperature,\n 'gen_ai.request.top_k': callSettings.topK,\n 'gen_ai.request.top_p': callSettings.topP,\n },\n }),\n tracer,\n endWhenDone: false,\n fn: async doStreamSpan => ({\n startTimestampMs: now(),\n doStreamSpan,\n result: await model.doStream(callOptions),\n }),\n }),\n );\n\n self._request.resolve(request ?? {});\n\n // store information for onFinish callback:\n let warnings: LanguageModelV2CallWarning[] | undefined;\n let usage: LanguageModelUsage = {\n inputTokens: undefined,\n outputTokens: undefined,\n totalTokens: undefined,\n };\n let finishReason: LanguageModelV2FinishReason | undefined;\n let providerMetadata: ProviderMetadata | undefined;\n let object: RESULT | undefined;\n let error: unknown | undefined;\n\n // pipe chunks through a transformation stream that extracts metadata:\n let accumulatedText = '';\n let textDelta = '';\n let fullResponse: {\n id: string;\n timestamp: Date;\n modelId: string;\n } = {\n id: generateId(),\n timestamp: currentDate(),\n modelId: model.modelId,\n };\n\n // Keep track of raw parse result before type validation, since e.g. Zod might\n // change the object by mapping properties.\n let latestObjectJson: JSONValue | undefined = undefined;\n let latestObject: PARTIAL | undefined = undefined;\n let isFirstChunk = true;\n let isFirstDelta = true;\n\n const transformedStream = stream\n .pipeThrough(new TransformStream(transformer))\n .pipeThrough(\n new TransformStream<\n string | ObjectStreamInputPart,\n ObjectStreamPart<PARTIAL>\n >({\n async transform(chunk, controller): Promise<void> {\n if (\n typeof chunk === 'object' &&\n chunk.type === 'stream-start'\n ) {\n warnings = chunk.warnings;\n return; // stream start chunks are sent immediately and do not count as first chunk\n }\n\n // Telemetry event for first chunk:\n if (isFirstChunk) {\n const msToFirstChunk = now() - startTimestampMs;\n\n isFirstChunk = false;\n\n doStreamSpan.addEvent('ai.stream.firstChunk', {\n 'ai.stream.msToFirstChunk': msToFirstChunk,\n });\n\n doStreamSpan.setAttributes({\n 'ai.stream.msToFirstChunk': msToFirstChunk,\n });\n }\n\n // process partial text chunks\n if (typeof chunk === 'string') {\n accumulatedText += chunk;\n textDelta += chunk;\n\n const { value: currentObjectJson, state: parseState } =\n await parsePartialJson(accumulatedText);\n\n if (\n currentObjectJson !== undefined &&\n !isDeepEqualData(latestObjectJson, currentObjectJson)\n ) {\n const validationResult =\n await outputStrategy.validatePartialResult({\n value: currentObjectJson,\n textDelta,\n latestObject,\n isFirstDelta,\n isFinalDelta: parseState === 'successful-parse',\n });\n\n if (\n validationResult.success &&\n !isDeepEqualData(\n latestObject,\n validationResult.value.partial,\n )\n ) {\n // inside inner check to correctly parse the final element in array mode:\n latestObjectJson = currentObjectJson;\n latestObject = validationResult.value.partial;\n\n controller.enqueue({\n type: 'object',\n object: latestObject,\n });\n\n controller.enqueue({\n type: 'text-delta',\n textDelta: validationResult.value.textDelta,\n });\n\n textDelta = '';\n isFirstDelta = false;\n }\n }\n\n return;\n }\n\n switch (chunk.type) {\n case 'response-metadata': {\n fullResponse = {\n id: chunk.id ?? fullResponse.id,\n timestamp: chunk.timestamp ?? fullResponse.timestamp,\n modelId: chunk.modelId ?? fullResponse.modelId,\n };\n break;\n }\n\n case 'finish': {\n // send final text delta:\n if (textDelta !== '') {\n controller.enqueue({ type: 'text-delta', textDelta });\n }\n\n // store finish reason for telemetry:\n finishReason = chunk.finishReason;\n\n // store usage and metadata for promises and onFinish callback:\n usage = chunk.usage;\n providerMetadata = chunk.providerMetadata;\n\n controller.enqueue({\n ...chunk,\n usage,\n response: fullResponse,\n });\n\n // log warnings:\n logWarnings(warnings ?? []);\n\n // resolve promises that can be resolved now:\n self._usage.resolve(usage);\n self._providerMetadata.resolve(providerMetadata);\n self._warnings.resolve(warnings);\n self._response.resolve({\n ...fullResponse,\n headers: response?.headers,\n });\n self._finishReason.resolve(finishReason ?? 'unknown');\n\n try {\n object = await parseAndValidateObjectResultWithRepair(\n accumulatedText,\n outputStrategy,\n repairText,\n {\n response: fullResponse,\n usage,\n finishReason,\n },\n );\n self._object.resolve(object);\n } catch (e) {\n error = e;\n self._object.reject(e);\n }\n break;\n }\n\n default: {\n controller.enqueue(chunk);\n break;\n }\n }\n },\n\n // invoke onFinish callback and resolve toolResults promise when the stream is about to close:\n async flush(controller) {\n try {\n const finalUsage = usage ?? {\n promptTokens: NaN,\n completionTokens: NaN,\n totalTokens: NaN,\n };\n\n doStreamSpan.setAttributes(\n selectTelemetryAttributes({\n telemetry,\n attributes: {\n 'ai.response.finishReason': finishReason,\n 'ai.response.object': {\n output: () => JSON.stringify(object),\n },\n 'ai.response.id': fullResponse.id,\n 'ai.response.model': fullResponse.modelId,\n 'ai.response.timestamp':\n fullResponse.timestamp.toISOString(),\n 'ai.response.providerMetadata':\n JSON.stringify(providerMetadata),\n\n 'ai.usage.inputTokens': finalUsage.inputTokens,\n 'ai.usage.outputTokens': finalUsage.outputTokens,\n 'ai.usage.totalTokens': finalUsage.totalTokens,\n 'ai.usage.reasoningTokens': finalUsage.reasoningTokens,\n 'ai.usage.cachedInputTokens':\n finalUsage.cachedInputTokens,\n\n // standardized gen-ai llm span attributes:\n 'gen_ai.response.finish_reasons': [finishReason],\n 'gen_ai.response.id': fullResponse.id,\n 'gen_ai.response.model': fullResponse.modelId,\n 'gen_ai.usage.input_tokens': finalUsage.inputTokens,\n 'gen_ai.usage.output_tokens': finalUsage.outputTokens,\n },\n }),\n );\n\n // finish doStreamSpan before other operations for correct timing:\n doStreamSpan.end();\n\n // Add response information to the root span:\n rootSpan.setAttributes(\n selectTelemetryAttributes({\n telemetry,\n attributes: {\n 'ai.usage.inputTokens': finalUsage.inputTokens,\n 'ai.usage.outputTokens': finalUsage.outputTokens,\n 'ai.usage.totalTokens': finalUsage.totalTokens,\n 'ai.usage.reasoningTokens': finalUsage.reasoningTokens,\n 'ai.usage.cachedInputTokens':\n finalUsage.cachedInputTokens,\n 'ai.response.object': {\n output: () => JSON.stringify(object),\n },\n 'ai.response.providerMetadata':\n JSON.stringify(providerMetadata),\n },\n }),\n );\n\n // call onFinish callback:\n await onFinish?.({\n usage: finalUsage,\n object,\n error,\n response: {\n ...fullResponse,\n headers: response?.headers,\n },\n warnings,\n providerMetadata,\n });\n } catch (error) {\n controller.enqueue({ type: 'error', error });\n } finally {\n rootSpan.end();\n }\n },\n }),\n );\n\n stitchableStream.addStream(transformedStream);\n },\n })\n .catch(error => {\n // add an empty stream with an error to break the stream:\n stitchableStream.addStream(\n new ReadableStream({\n start(controller) {\n controller.enqueue({ type: 'error', error });\n controller.close();\n },\n }),\n );\n })\n .finally(() => {\n stitchableStream.close();\n });\n\n this.outputStrategy = outputStrategy;\n }\n\n get object() {\n return this._object.promise;\n }\n\n get usage() {\n return this._usage.promise;\n }\n\n get providerMetadata() {\n return this._providerMetadata.promise;\n }\n\n get warnings() {\n return this._warnings.promise;\n }\n\n get request() {\n return this._request.promise;\n }\n\n get response() {\n return this._response.promise;\n }\n\n get finishReason() {\n return this._finishReason.promise;\n }\n\n get partialObjectStream(): AsyncIterableStream<PARTIAL> {\n return createAsyncIterableStream(\n this.baseStream.pipeThrough(\n new TransformStream<ObjectStreamPart<PARTIAL>, PARTIAL>({\n transform(chunk, controller) {\n switch (chunk.type) {\n case 'object':\n controller.enqueue(chunk.object);\n break;\n\n case 'text-delta':\n case 'finish':\n case 'error': // suppress error (use onError instead)\n break;\n\n default: {\n const _exhaustiveCheck: never = chunk;\n throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n }\n }\n },\n }),\n ),\n );\n }\n\n get elementStream(): ELEMENT_STREAM {\n return this.outputStrategy.createElementStream(this.baseStream);\n }\n\n get textStream(): AsyncIterableStream<string> {\n return createAsyncIterableStream(\n this.baseStream.pipeThrough(\n new TransformStream<ObjectStreamPart<PARTIAL>, string>({\n transform(chunk, controller) {\n switch (chunk.type) {\n case 'text-delta':\n controller.enqueue(chunk.textDelta);\n break;\n\n case 'object':\n case 'finish':\n case 'error': // suppress error (use onError instead)\n break;\n\n default: {\n const _exhaustiveCheck: never = chunk;\n throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n }\n }\n },\n }),\n ),\n );\n }\n\n get fullStream(): AsyncIterableStream<ObjectStreamPart<PARTIAL>> {\n return createAsyncIterableStream(this.baseStream);\n }\n\n pipeTextStreamToResponse(response: ServerResponse, init?: ResponseInit) {\n pipeTextStreamToResponse({\n response,\n textStream: this.textStream,\n ...init,\n });\n }\n\n toTextStreamResponse(init?: ResponseInit): Response {\n return createTextStreamResponse({\n textStream: this.textStream,\n ...init,\n });\n }\n}\n\nexport type ObjectStreamInputPart =\n | string\n | {\n type: 'stream-start';\n warnings: LanguageModelV2CallWarning[];\n }\n | {\n type: 'error';\n error: unknown;\n }\n | {\n type: 'response-metadata';\n id?: string;\n timestamp?: Date;\n modelId?: string;\n }\n | {\n type: 'finish';\n finishReason: LanguageModelV2FinishReason;\n usage: LanguageModelV2Usage;\n providerMetadata?: SharedV2ProviderMetadata;\n };\n","import { LanguageModelV2CallOptions } from '@ai-sdk/provider';\nimport {\n asSchema,\n FlexibleSchema,\n safeParseJSON,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport { NoObjectGeneratedError } from '../error/no-object-generated-error';\nimport { FinishReason } from '../types/language-model';\nimport { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';\nimport { LanguageModelUsage } from '../types/usage';\nimport { DeepPartial } from '../util/deep-partial';\nimport { parsePartialJson } from '../util/parse-partial-json';\n\nexport interface Output<OUTPUT, PARTIAL> {\n readonly type: 'object' | 'text';\n\n responseFormat: LanguageModelV2CallOptions['responseFormat'];\n\n parsePartial(options: {\n text: string;\n }): Promise<{ partial: PARTIAL } | undefined>;\n\n parseOutput(\n options: { text: string },\n context: {\n response: LanguageModelResponseMetadata;\n usage: LanguageModelUsage;\n finishReason: FinishReason;\n },\n ): Promise<OUTPUT>;\n}\n\nexport const text = (): Output<string, string> => ({\n type: 'text',\n\n responseFormat: { type: 'text' },\n\n async parsePartial({ text }: { text: string }) {\n return { partial: text };\n },\n\n async parseOutput({ text }: { text: string }) {\n return text;\n },\n});\n\nexport const object = <OUTPUT>({\n schema: inputSchema,\n}: {\n schema: FlexibleSchema<OUTPUT>;\n}): Output<OUTPUT, DeepPartial<OUTPUT>> => {\n const schema = asSchema(inputSchema);\n\n return {\n type: 'object',\n\n responseFormat: {\n type: 'json',\n schema: schema.jsonSchema,\n },\n\n async parsePartial({ text }: { text: string }) {\n const result = await parsePartialJson(text);\n\n switch (result.state) {\n case 'failed-parse':\n case 'undefined-input':\n return undefined;\n\n case 'repaired-parse':\n case 'successful-parse':\n return {\n // Note: currently no validation of partial results:\n partial: result.value as DeepPartial<OUTPUT>,\n };\n\n default: {\n const _exhaustiveCheck: never = result.state;\n throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);\n }\n }\n },\n\n async parseOutput(\n { text }: { text: string },\n context: {\n response: LanguageModelResponseMetadata;\n usage: LanguageModelUsage;\n finishReason: FinishReason;\n },\n ) {\n const parseResult = await safeParseJSON({ text });\n\n if (!parseResult.success) {\n throw new NoObjectGeneratedError({\n message: 'No object generated: could not parse the response.',\n cause: parseResult.error,\n text,\n response: context.response,\n usage: context.usage,\n finishReason: context.finishReason,\n });\n }\n\n const validationResult = await safeValidateTypes({\n value: parseResult.value,\n schema,\n });\n\n if (!validationResult.success) {\n throw new NoObjectGeneratedError({\n message: 'No object generated: response did not match schema.',\n cause: validationResult.error,\n text,\n response: context.response,\n usage: context.usage,\n finishReason: context.finishReason,\n });\n }\n\n return validationResult.value;\n },\n };\n};\n","import { AISDKError, NoSuchModelError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoSuchProviderError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchProviderError extends NoSuchModelError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly providerId: string;\n readonly availableProviders: string[];\n\n constructor({\n modelId,\n modelType,\n providerId,\n availableProviders,\n message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})`,\n }: {\n modelId: string;\n modelType:\n | 'languageModel'\n | 'textEmbeddingModel'\n | 'imageModel'\n | 'transcriptionModel'\n | 'speechModel';\n providerId: string;\n availableProviders: string[];\n message?: string;\n }) {\n super({ errorName: name, modelId, modelType, message });\n\n this.providerId = providerId;\n this.availableProviders = availableProviders;\n }\n\n static isInstance(error: unknown): error is NoSuchProviderError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { createId } from 'legid'\nimport { createIdGenerator } from 'ai'\n\nexport const createChatId = () => createId({ approximateLength: 11, step: 3 })\n\nexport const createMessageId = () => createIdGenerator({ size: 32 })()\n","// IMPORTANT: these are exposed to the client. Server-only constants should be in server-constants.ts\n\nexport const DAILY_MESSAGE_QUOTA_REACHED_ERROR = 'Daily message quota reached!'\n\n// v0_internalForceWaitingRoom\nexport const INTERNAL_WAITING_ROOM_COOKIE = 'v0_ifwr'\n\nexport const AMBASSADOR_CTA_LINK = 'https://v0ambassadorform.vercel.app'\n\nexport const FORCE_BEDROCK_CONFIG = true\n\nexport const MAX_COOKIE_AGE = Math.pow(2, 31) - 1 // max value for a 32-bit signed integer\n\nexport const PROMPT_DRAFT_COOKIE = 'prompt-draft'\nexport const SELECTED_PROJECT_ID_COOKIE = 'selected-project-id'\n\nexport const INVALID_PLAN_ERROR = 'Invalid v0 plan.'\nexport const BLOCKED_ERROR = 'You are blocked from sending messages.'\n\nexport const SCROLL_CONTAINER_ID = 'scroll-container'\nexport const SCROLL_INNER_CONTAINER_ID = 'scroll-inner-container'\n\nexport const LLM_ERROR_PREFIX = 'V0CHAT_LLM_ERROR'\nexport const LLM_ERROR_RETRY_SUFFIX = '_RETRY'\n\n// Billing\nexport const SHOW_UPGRADE_CTA_THRESHOLD_MESSAGES = 3\nexport const DAILY_MODEL_USAGE_LIMIT = 7 // daily free usage limit\nexport const SHOW_NON_DISMISSABLE_UPGRADE_CTA_THRESHOLD_DAILY_MODEL_USAGE = 2 // critical threshold for daily model usage\nexport const SHOW_DISMISSABLE_UPGRADE_CTA_THRESHOLD_DAILY_MODEL_USAGE = 4 // critical threshold for daily model usage\nexport const DISMISSED_DAILY_MODEL_USAGE_UPGRADE_CTA_COOKIE = 'chat-ddmuuc'\nexport const SHOW_UPGRADE_CTA_THRESHOLD_CREDITS = 1.0\nexport const SHOW_UPGRADE_CTA_THRESHOLD_FOR_EXPERIMENT = 11\nexport const DISMISSED_DAILY_UPGRADE_CTA_COOKIE = 'chat-dduc'\nexport const DISMISSED_GENERAL_UPGRADE_CTA_COOKIE = 'chat-dguc'\nexport const MINIMUM_CREDITS_TO_SEND_MESSAGE = 0.02\n\nexport const CONTACT_SALES_LINK =\n 'https://vercel.com/contact/sales?mode=enterprise-v0&utm_source=v0-chat&utm_campaign=v0_enterprise&utm_medium=message-limit-reached'\nexport const CONTACT_SALES_LINK_ENTERPRISE =\n 'https://vercel.com/contact/sales/v0-enterprise'\n\nexport const FILE_TREE_RESIZE_COOKIE = 'file-tree-size'\nexport const BLOCK_RESIZE_COOKIE = 'block-view-size'\n\nexport const CONSOLE_RESIZE_COOKIE = 'console-view-size'\nexport const CONSOLE_EXPANDED_COOKIE = `${CONSOLE_RESIZE_COOKIE}-expanded`\n\nexport const HIDE_COOKIE = 'HIDE_SHARE_DISCLAIMER'\nexport const ANON_SESSION_ID_COOKIE = 'anon_session_id'\nexport const SESSION_REFERER_COOKIE = 'session_referer'\n\nexport const V0_HAS_SIGNED_IN_COOKIE = 'v0-has-signed-in'\nexport const V0_DEV_APP_TRANSFER_COOKIE = 'v0-dev-app-transfer'\n\nexport const CUSTOM_INSTRUCTIONS_COOKIE_NAME = 'selectedPrompts'\n\nexport const OUTPUT_RESIZE_PUBLISHED_COOKIE = 'output-resize-published'\nexport const V0_RESIZE_PUBLISHED_COOKIE = 'v0-resize-published'\nexport const OUTPUT_RESIZE_COOKIE = 'output-resize'\n\nexport const CLI_TOKEN_EXPIRATION_TIME = '30m'\nexport const CLI_TOKEN_EXPIRATION_MS = 30 * 60 * 1000\n\nexport const MAX_CHAT_HISTORY_ITEMS = 60\nexport const MAX_CHAT_SHARED_ITEMS = 30\nexport const MAX_CHAT_FAVORITE_ITEMS = 30\n\nexport const V0_NO_OP_CODE_BLOCK_PREFIX = '[v0-no-op-code-block-prefix]'\n\nexport const CHAT_HISTORY_PAGE_SIZE = 15\nexport const BLOCK_HISTORY_PAGE_SIZE = 12\n\nexport const ChatHistoryViews = {\n All: 'all',\n My: 'my',\n} as const\n\nexport const ProjectViews = {\n All: 'all',\n My: 'my',\n} as const\n\nexport const V0_MULTI_FILE_INDICATOR_MAP = {\n 'code-project': '[V0_FILE]',\n local: '[V0_FILE_EDIT]',\n} as const\n\n// This determines the maximum number of files that can be uploaded at once\n// NOTE: Size validation happens on the server for inline image attachments.\nexport const ALLOWED_FILE_COUNT = {\n 'prompt-attachment': 10,\n 'project-source': 1000,\n}\n\nexport const FIRST_HIGHLIGHTED_LINE_ID = `first-highlighted-line`\n\n// Leaving this here to stop mass abuse but generally should not be hit.\nexport const MAX_PROJECTS_FOR_FREE_USERS = 2000\n\nconst DEPLOYMENT_ALIAS_ERROR_MAP = {\n cert_missing: 'Missing certificate',\n domain_not_found: 'Domain not found',\n cert_expired: 'Certificate expired',\n deployment_not_found: 'Deployment not found',\n gone: 'Cannot assign alias to failed deployment',\n invalid_alias: 'Invalid alias',\n deployment_not_ready: 'Deployment is not ready',\n alias_in_use: 'Alias unavailable',\n forbidden: 'Unauthorized',\n} as const\n\nconst PROJECT_DOMAIN_ALIAS_ERROR_MAP = {\n 'duplicate-team-registration': 'Domain already registered on another project',\n domain_already_in_use: 'Domain already in use',\n missing_domain_verification: 'Domain not verified',\n 'owned-on-personal-account':\n 'Domain already registered on your personal account',\n 'duplicate-user-registration': 'Domain already registered on your account',\n 'owned-on-other-team': 'Domain already registered on another team',\n domain_taken: 'Domain is unavailable',\n}\n\nexport const ALIAS_ERROR_MAP = {\n ...DEPLOYMENT_ALIAS_ERROR_MAP,\n ...PROJECT_DOMAIN_ALIAS_ERROR_MAP,\n} as const\n\nexport const DEFAULT_BLOCK_SIZE = 75 // NOTE: If you change this, also update the E2E test for it `block opens to X% by default`\nexport const DEFAULT_FILE_TREE_SIZE = 25\n\nexport const INITIAL_CONSOLE_SIZE = 33 // initially visible\nexport const INITIAL_CONSOLE_EXPANDED = false\nexport const DEFAULT_CONSOLE_SIZE = 33\nexport const CONSOLE_MIN_SIZE_PX = 100\nexport const CONSOLE_THRESHOLD_PX = 100\n\nexport const MAX_PROMPT_LENGTH_TO_ENHANCE = 1000\nexport const MIN_PROMPT_LENGTH_TO_ENHANCE = 10\n\nexport const INLINE_BLOCK_TYPES = ['inline-sql']\n\nexport const MAX_SQL_ATTACHMENT_SIZE = 3 * 1024 // 3kb\n\nexport const MAX_CUSTOM_INSTRUCTIONS_LENGTH = 2_000\nexport const MAX_CUSTOM_INSTRUCTIONS_COUNT = 10\n\nexport const MAX_ZIP_UPLOAD_SIZE_MB = 50\n\nexport const VERCEL_COMMUNITY_V0_SECTION_URL =\n 'https://community.vercel.com/c/v0/59'\n\nexport const USAGE_BLOG_URL =\n 'https://vercel.com/blog/improved-v0-pricing-5luSrdRUJsRvf1kXWoYGxh'\n\n// DO NOT REMOVE THIS CONSTANT.\n// This is a list of team IDs that have opted out of personal scopes being displayed in the UI.\nexport const PERSONAL_OPT_OUT_TEAM_IDS = [\n // Optum/UHG\n 'team_wR5a08RllTGidzk4UqvscibX', // NetraAI Core\n 'team_uDX0VNCOe5xNadsMqajBcvFi', // NetraAI Curo\n 'team_zIHyjdtagYlo3QsJ7zvpL72r', // NetraAI OBH\n 'team_fGZcZ4AXeQtKb85Fdm5bn1Td', // NetraAI UM\n 'team_WbdP9r72OCpLMW7LVeY7yOLa', // NetraAI HC\n 'team_HxtvWg98OxxsTnD3vOstnbyN', // NetraAI CM\n 'team_5GeKt7jLO7KrDcyJboNeqi1s', // NetraAI Design\n 'team_ZuYXXf77CRYR7x5NaPGCs5zM', // NetraAI Optum\n 'team_QU14kGaTfz7FzT2wRXgyAN3R', // NetraAI UHC\n]\n\nexport const PUSHER_EVENTS = {\n latestChat: {\n getChannelName: (chatId: string) => `v0-chats-${chatId}`,\n getEventName: () => 'poll-latest-chat',\n },\n} as const\n","import {\n LLM_ERROR_PREFIX,\n LLM_ERROR_RETRY_SUFFIX,\n} from '../../constants-shared'\nimport type { LLMProviderErrorCategory } from './types'\n\ninterface LlmErrorReturnValue {\n isLlmError: boolean\n isRetried: boolean\n errorCategory?: LLMProviderErrorCategory\n}\n\n/**\n * Parses stream chunk (e.g. \"V0CHAT_LLM_ERROR_RETRY:input-too-long\") or BotUIMessage to determine if it's an LLM error, and if so, extracts the error category.\n */\nexport function isLlmError(\n chunkOrMessage:\n | string\n | {\n finishReason?: string\n },\n): LlmErrorReturnValue {\n const returnValue: LlmErrorReturnValue = {\n isLlmError: false,\n isRetried: false,\n errorCategory: undefined,\n }\n\n if (typeof chunkOrMessage === 'string') {\n // Stream chunk evaluation:\n returnValue.isLlmError = chunkOrMessage.startsWith(LLM_ERROR_PREFIX)\n returnValue.isRetried = chunkOrMessage.endsWith(LLM_ERROR_RETRY_SUFFIX)\n const errorChunkArray = chunkOrMessage.split(':')\n const errorCategory = (errorChunkArray[1] ??\n 'default') as LLMProviderErrorCategory\n returnValue.errorCategory = errorCategory\n } else if (chunkOrMessage.finishReason?.includes('provider_server_error')) {\n // Bot Message evaluation:\n const isRetriedLlmError = chunkOrMessage.finishReason.startsWith(\n 'retry_provider_server_error',\n )\n const isLlmError =\n isRetriedLlmError ||\n Boolean(chunkOrMessage.finishReason.startsWith('provider_server_error'))\n returnValue.isLlmError = isLlmError\n returnValue.isRetried = isRetriedLlmError\n\n if (isLlmError) {\n const finishReasonArray = chunkOrMessage.finishReason.split(':')\n const errorCategory = (finishReasonArray[1] ??\n 'default') as LLMProviderErrorCategory\n returnValue.errorCategory = errorCategory\n }\n }\n\n return returnValue\n}\n","class Processor {\n constructor(options) {\n this.selfOptions = options || {};\n this.pipes = {};\n }\n options(options) {\n if (options) {\n this.selfOptions = options;\n }\n return this.selfOptions;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n pipe(name, pipeArg) {\n let pipe = pipeArg;\n if (typeof name === 'string') {\n if (typeof pipe === 'undefined') {\n return this.pipes[name];\n }\n else {\n this.pipes[name] = pipe;\n }\n }\n if (name && name.name) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n pipe = name;\n if (pipe.processor === this) {\n return pipe;\n }\n this.pipes[pipe.name] = pipe;\n }\n pipe.processor = this;\n return pipe;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process(input, pipe) {\n let context = input;\n context.options = this.options();\n let nextPipe = pipe || input.pipe || 'default';\n let lastPipe;\n while (nextPipe) {\n if (typeof context.nextAfterChildren !== 'undefined') {\n // children processed and coming back to parent\n context.next = context.nextAfterChildren;\n context.nextAfterChildren = null;\n }\n if (typeof nextPipe === 'string') {\n nextPipe = this.pipe(nextPipe);\n }\n nextPipe.process(context);\n lastPipe = nextPipe;\n nextPipe = null;\n if (context) {\n if (context.next) {\n context = context.next;\n nextPipe = context.pipe || lastPipe;\n }\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return context.hasResult ? context.result : undefined;\n }\n}\nexport default Processor;\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nclass Pipe {\n constructor(name) {\n this.name = name;\n this.filters = [];\n }\n process(input) {\n if (!this.processor) {\n throw new Error('add this pipe to a processor before using it');\n }\n const debug = this.debug;\n const length = this.filters.length;\n const context = input;\n for (let index = 0; index < length; index++) {\n const filter = this.filters[index];\n if (debug) {\n this.log(`filter: ${filter.filterName}`);\n }\n filter(context);\n if (typeof context === 'object' && context.exiting) {\n context.exiting = false;\n break;\n }\n }\n if (!context.next && this.resultCheck) {\n this.resultCheck(context);\n }\n }\n log(msg) {\n console.log(`[jsondiffpatch] ${this.name} pipe, ${msg}`);\n }\n append(...args) {\n this.filters.push(...args);\n return this;\n }\n prepend(...args) {\n this.filters.unshift(...args);\n return this;\n }\n indexOf(filterName) {\n if (!filterName) {\n throw new Error('a filter name is required');\n }\n for (let index = 0; index < this.filters.length; index++) {\n const filter = this.filters[index];\n if (filter.filterName === filterName) {\n return index;\n }\n }\n throw new Error(`filter not found: ${filterName}`);\n }\n list() {\n return this.filters.map((f) => f.filterName);\n }\n after(filterName, ...params) {\n const index = this.indexOf(filterName);\n this.filters.splice(index + 1, 0, ...params);\n return this;\n }\n before(filterName, ...params) {\n const index = this.indexOf(filterName);\n this.filters.splice(index, 0, ...params);\n return this;\n }\n replace(filterName, ...params) {\n const index = this.indexOf(filterName);\n this.filters.splice(index, 1, ...params);\n return this;\n }\n remove(filterName) {\n const index = this.indexOf(filterName);\n this.filters.splice(index, 1);\n return this;\n }\n clear() {\n this.filters.length = 0;\n return this;\n }\n shouldHaveResult(should) {\n if (should === false) {\n this.resultCheck = null;\n return;\n }\n if (this.resultCheck) {\n return;\n }\n this.resultCheck = (context) => {\n if (!context.hasResult) {\n console.log(context);\n const error = new Error(`${this.name} failed`);\n error.noResult = true;\n throw error;\n }\n };\n return this;\n }\n}\nexport default Pipe;\n","export default class Context {\n setResult(result) {\n this.result = result;\n this.hasResult = true;\n return this;\n }\n exit() {\n this.exiting = true;\n return this;\n }\n push(child, name) {\n child.parent = this;\n if (typeof name !== 'undefined') {\n child.childName = name;\n }\n child.root = this.root || this;\n child.options = child.options || this.options;\n if (!this.children) {\n this.children = [child];\n this.nextAfterChildren = this.next || null;\n this.next = child;\n }\n else {\n this.children[this.children.length - 1].next = child;\n this.children.push(child);\n }\n child.next = this;\n return this;\n }\n}\n","function cloneRegExp(re) {\n const regexMatch = /^\\/(.*)\\/([gimyu]*)$/.exec(re.toString());\n return new RegExp(regexMatch[1], regexMatch[2]);\n}\nexport default function clone(arg) {\n if (typeof arg !== 'object') {\n return arg;\n }\n if (arg === null) {\n return null;\n }\n if (Array.isArray(arg)) {\n return arg.map(clone);\n }\n if (arg instanceof Date) {\n return new Date(arg.getTime());\n }\n if (arg instanceof RegExp) {\n return cloneRegExp(arg);\n }\n const cloned = {};\n for (const name in arg) {\n if (Object.prototype.hasOwnProperty.call(arg, name)) {\n cloned[name] = clone(arg[name]);\n }\n }\n return cloned;\n}\n","import Context from './context.js';\nimport defaultClone from '../clone.js';\nclass DiffContext extends Context {\n constructor(left, right) {\n super();\n this.left = left;\n this.right = right;\n this.pipe = 'diff';\n }\n setResult(result) {\n if (this.options.cloneDiffValues && typeof result === 'object') {\n const clone = typeof this.options.cloneDiffValues === 'function'\n ? this.options.cloneDiffValues\n : defaultClone;\n if (typeof result[0] === 'object') {\n result[0] = clone(result[0]);\n }\n if (typeof result[1] === 'object') {\n result[1] = clone(result[1]);\n }\n }\n return super.setResult(result);\n }\n}\nexport default DiffContext;\n","import Context from './context.js';\nclass PatchContext extends Context {\n constructor(left, delta) {\n super();\n this.left = left;\n this.delta = delta;\n this.pipe = 'patch';\n }\n}\nexport default PatchContext;\n","import Context from './context.js';\nclass ReverseContext extends Context {\n constructor(delta) {\n super();\n this.delta = delta;\n this.pipe = 'reverse';\n }\n}\nexport default ReverseContext;\n","export const diffFilter = function trivialMatchesDiffFilter(context) {\n if (context.left === context.right) {\n context.setResult(undefined).exit();\n return;\n }\n if (typeof context.left === 'undefined') {\n if (typeof context.right === 'function') {\n throw new Error('functions are not supported');\n }\n context.setResult([context.right]).exit();\n return;\n }\n if (typeof context.right === 'undefined') {\n context.setResult([context.left, 0, 0]).exit();\n return;\n }\n if (typeof context.left === 'function' ||\n typeof context.right === 'function') {\n throw new Error('functions are not supported');\n }\n context.leftType = context.left === null ? 'null' : typeof context.left;\n context.rightType = context.right === null ? 'null' : typeof context.right;\n if (context.leftType !== context.rightType) {\n context.setResult([context.left, context.right]).exit();\n return;\n }\n if (context.leftType === 'boolean' || context.leftType === 'number') {\n context.setResult([context.left, context.right]).exit();\n return;\n }\n if (context.leftType === 'object') {\n context.leftIsArray = Array.isArray(context.left);\n }\n if (context.rightType === 'object') {\n context.rightIsArray = Array.isArray(context.right);\n }\n if (context.leftIsArray !== context.rightIsArray) {\n context.setResult([context.left, context.right]).exit();\n return;\n }\n if (context.left instanceof RegExp) {\n if (context.right instanceof RegExp) {\n context\n .setResult([context.left.toString(), context.right.toString()])\n .exit();\n }\n else {\n context.setResult([context.left, context.right]).exit();\n }\n }\n};\ndiffFilter.filterName = 'trivial';\nexport const patchFilter = function trivialMatchesPatchFilter(context) {\n if (typeof context.delta === 'undefined') {\n context.setResult(context.left).exit();\n return;\n }\n context.nested = !Array.isArray(context.delta);\n if (context.nested) {\n return;\n }\n const nonNestedDelta = context.delta;\n if (nonNestedDelta.length === 1) {\n context.setResult(nonNestedDelta[0]).exit();\n return;\n }\n if (nonNestedDelta.length === 2) {\n if (context.left instanceof RegExp) {\n const regexArgs = /^\\/(.*)\\/([gimyu]+)$/.exec(nonNestedDelta[1]);\n if (regexArgs) {\n context.setResult(new RegExp(regexArgs[1], regexArgs[2])).exit();\n return;\n }\n }\n context.setResult(nonNestedDelta[1]).exit();\n return;\n }\n if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {\n context.setResult(undefined).exit();\n }\n};\npatchFilter.filterName = 'trivial';\nexport const reverseFilter = function trivialReferseFilter(context) {\n if (typeof context.delta === 'undefined') {\n context.setResult(context.delta).exit();\n return;\n }\n context.nested = !Array.isArray(context.delta);\n if (context.nested) {\n return;\n }\n const nonNestedDelta = context.delta;\n if (nonNestedDelta.length === 1) {\n context.setResult([nonNestedDelta[0], 0, 0]).exit();\n return;\n }\n if (nonNestedDelta.length === 2) {\n context.setResult([nonNestedDelta[1], nonNestedDelta[0]]).exit();\n return;\n }\n if (nonNestedDelta.length === 3 && nonNestedDelta[2] === 0) {\n context.setResult([nonNestedDelta[0]]).exit();\n }\n};\nreverseFilter.filterName = 'trivial';\n","import DiffContext from '../contexts/diff.js';\nimport PatchContext from '../contexts/patch.js';\nimport ReverseContext from '../contexts/reverse.js';\nexport const collectChildrenDiffFilter = (context) => {\n if (!context || !context.children) {\n return;\n }\n const length = context.children.length;\n let child;\n let result = context.result;\n for (let index = 0; index < length; index++) {\n child = context.children[index];\n if (typeof child.result === 'undefined') {\n continue;\n }\n result = result || {};\n result[child.childName] = child.result;\n }\n if (result && context.leftIsArray) {\n result._t = 'a';\n }\n context.setResult(result).exit();\n};\ncollectChildrenDiffFilter.filterName = 'collectChildren';\nexport const objectsDiffFilter = (context) => {\n if (context.leftIsArray || context.leftType !== 'object') {\n return;\n }\n const left = context.left;\n const right = context.right;\n let name;\n let child;\n const propertyFilter = context.options.propertyFilter;\n for (name in left) {\n if (!Object.prototype.hasOwnProperty.call(left, name)) {\n continue;\n }\n if (propertyFilter && !propertyFilter(name, context)) {\n continue;\n }\n child = new DiffContext(left[name], right[name]);\n context.push(child, name);\n }\n for (name in right) {\n if (!Object.prototype.hasOwnProperty.call(right, name)) {\n continue;\n }\n if (propertyFilter && !propertyFilter(name, context)) {\n continue;\n }\n if (typeof left[name] === 'undefined') {\n child = new DiffContext(undefined, right[name]);\n context.push(child, name);\n }\n }\n if (!context.children || context.children.length === 0) {\n context.setResult(undefined).exit();\n return;\n }\n context.exit();\n};\nobjectsDiffFilter.filterName = 'objects';\nexport const patchFilter = function nestedPatchFilter(context) {\n if (!context.nested) {\n return;\n }\n const nestedDelta = context.delta;\n if (nestedDelta._t) {\n return;\n }\n const objectDelta = nestedDelta;\n let name;\n let child;\n for (name in objectDelta) {\n child = new PatchContext(context.left[name], objectDelta[name]);\n context.push(child, name);\n }\n context.exit();\n};\npatchFilter.filterName = 'objects';\nexport const collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {\n if (!context || !context.children) {\n return;\n }\n const deltaWithChildren = context.delta;\n if (deltaWithChildren._t) {\n return;\n }\n const object = context.left;\n const length = context.children.length;\n let child;\n for (let index = 0; index < length; index++) {\n child = context.children[index];\n const property = child.childName;\n if (Object.prototype.hasOwnProperty.call(context.left, property) &&\n child.result === undefined) {\n delete object[property];\n }\n else if (object[property] !== child.result) {\n object[property] = child.result;\n }\n }\n context.setResult(object).exit();\n};\ncollectChildrenPatchFilter.filterName = 'collectChildren';\nexport const reverseFilter = function nestedReverseFilter(context) {\n if (!context.nested) {\n return;\n }\n const nestedDelta = context.delta;\n if (nestedDelta._t) {\n return;\n }\n const objectDelta = context.delta;\n let name;\n let child;\n for (name in objectDelta) {\n child = new ReverseContext(objectDelta[name]);\n context.push(child, name);\n }\n context.exit();\n};\nreverseFilter.filterName = 'objects';\nexport const collectChildrenReverseFilter = (context) => {\n if (!context || !context.children) {\n return;\n }\n const deltaWithChildren = context.delta;\n if (deltaWithChildren._t) {\n return;\n }\n const length = context.children.length;\n let child;\n const delta = {};\n for (let index = 0; index < length; index++) {\n child = context.children[index];\n const property = child.childName;\n if (delta[property] !== child.result) {\n delta[property] = child.result;\n }\n }\n context.setResult(delta).exit();\n};\ncollectChildrenReverseFilter.filterName = 'collectChildren';\n","/*\n\nLCS implementation that supports arrays or strings\n\nreference: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem\n\n*/\nconst defaultMatch = function (array1, array2, index1, index2) {\n return array1[index1] === array2[index2];\n};\nconst lengthMatrix = function (array1, array2, match, context) {\n const len1 = array1.length;\n const len2 = array2.length;\n let x, y;\n // initialize empty matrix of len1+1 x len2+1\n const matrix = new Array(len1 + 1);\n for (x = 0; x < len1 + 1; x++) {\n matrix[x] = new Array(len2 + 1);\n for (y = 0; y < len2 + 1; y++) {\n matrix[x][y] = 0;\n }\n }\n matrix.match = match;\n // save sequence lengths for each coordinate\n for (x = 1; x < len1 + 1; x++) {\n for (y = 1; y < len2 + 1; y++) {\n if (match(array1, array2, x - 1, y - 1, context)) {\n matrix[x][y] = matrix[x - 1][y - 1] + 1;\n }\n else {\n matrix[x][y] = Math.max(matrix[x - 1][y], matrix[x][y - 1]);\n }\n }\n }\n return matrix;\n};\nconst backtrack = function (matrix, array1, array2, context) {\n let index1 = array1.length;\n let index2 = array2.length;\n const subsequence = {\n sequence: [],\n indices1: [],\n indices2: [],\n };\n while (index1 !== 0 && index2 !== 0) {\n const sameLetter = matrix.match(array1, array2, index1 - 1, index2 - 1, context);\n if (sameLetter) {\n subsequence.sequence.unshift(array1[index1 - 1]);\n subsequence.indices1.unshift(index1 - 1);\n subsequence.indices2.unshift(index2 - 1);\n --index1;\n --index2;\n }\n else {\n const valueAtMatrixAbove = matrix[index1][index2 - 1];\n const valueAtMatrixLeft = matrix[index1 - 1][index2];\n if (valueAtMatrixAbove > valueAtMatrixLeft) {\n --index2;\n }\n else {\n --index1;\n }\n }\n }\n return subsequence;\n};\nconst get = function (array1, array2, match, context) {\n const innerContext = context || {};\n const matrix = lengthMatrix(array1, array2, match || defaultMatch, innerContext);\n return backtrack(matrix, array1, array2, innerContext);\n};\nexport default {\n get,\n};\n","import DiffContext from '../contexts/diff.js';\nimport PatchContext from '../contexts/patch.js';\nimport ReverseContext from '../contexts/reverse.js';\nimport lcs from './lcs.js';\nconst ARRAY_MOVE = 3;\nfunction arraysHaveMatchByRef(array1, array2, len1, len2) {\n for (let index1 = 0; index1 < len1; index1++) {\n const val1 = array1[index1];\n for (let index2 = 0; index2 < len2; index2++) {\n const val2 = array2[index2];\n if (index1 !== index2 && val1 === val2) {\n return true;\n }\n }\n }\n}\nfunction matchItems(array1, array2, index1, index2, context) {\n const value1 = array1[index1];\n const value2 = array2[index2];\n if (value1 === value2) {\n return true;\n }\n if (typeof value1 !== 'object' || typeof value2 !== 'object') {\n return false;\n }\n const objectHash = context.objectHash;\n if (!objectHash) {\n // no way to match objects was provided, try match by position\n return context.matchByPosition && index1 === index2;\n }\n context.hashCache1 = context.hashCache1 || [];\n let hash1 = context.hashCache1[index1];\n if (typeof hash1 === 'undefined') {\n context.hashCache1[index1] = hash1 = objectHash(value1, index1);\n }\n if (typeof hash1 === 'undefined') {\n return false;\n }\n context.hashCache2 = context.hashCache2 || [];\n let hash2 = context.hashCache2[index2];\n if (typeof hash2 === 'undefined') {\n context.hashCache2[index2] = hash2 = objectHash(value2, index2);\n }\n if (typeof hash2 === 'undefined') {\n return false;\n }\n return hash1 === hash2;\n}\nexport const diffFilter = function arraysDiffFilter(context) {\n if (!context.leftIsArray) {\n return;\n }\n const matchContext = {\n objectHash: context.options && context.options.objectHash,\n matchByPosition: context.options && context.options.matchByPosition,\n };\n let commonHead = 0;\n let commonTail = 0;\n let index;\n let index1;\n let index2;\n const array1 = context.left;\n const array2 = context.right;\n const len1 = array1.length;\n const len2 = array2.length;\n let child;\n if (len1 > 0 &&\n len2 > 0 &&\n !matchContext.objectHash &&\n typeof matchContext.matchByPosition !== 'boolean') {\n matchContext.matchByPosition = !arraysHaveMatchByRef(array1, array2, len1, len2);\n }\n // separate common head\n while (commonHead < len1 &&\n commonHead < len2 &&\n matchItems(array1, array2, commonHead, commonHead, matchContext)) {\n index = commonHead;\n child = new DiffContext(array1[index], array2[index]);\n context.push(child, index);\n commonHead++;\n }\n // separate common tail\n while (commonTail + commonHead < len1 &&\n commonTail + commonHead < len2 &&\n matchItems(array1, array2, len1 - 1 - commonTail, len2 - 1 - commonTail, matchContext)) {\n index1 = len1 - 1 - commonTail;\n index2 = len2 - 1 - commonTail;\n child = new DiffContext(array1[index1], array2[index2]);\n context.push(child, index2);\n commonTail++;\n }\n let result;\n if (commonHead + commonTail === len1) {\n if (len1 === len2) {\n // arrays are identical\n context.setResult(undefined).exit();\n return;\n }\n // trivial case, a block (1 or more consecutive items) was added\n result = result || {\n _t: 'a',\n };\n for (index = commonHead; index < len2 - commonTail; index++) {\n result[index] = [array2[index]];\n }\n context.setResult(result).exit();\n return;\n }\n if (commonHead + commonTail === len2) {\n // trivial case, a block (1 or more consecutive items) was removed\n result = result || {\n _t: 'a',\n };\n for (index = commonHead; index < len1 - commonTail; index++) {\n result[`_${index}`] = [array1[index], 0, 0];\n }\n context.setResult(result).exit();\n return;\n }\n // reset hash cache\n delete matchContext.hashCache1;\n delete matchContext.hashCache2;\n // diff is not trivial, find the LCS (Longest Common Subsequence)\n const trimmed1 = array1.slice(commonHead, len1 - commonTail);\n const trimmed2 = array2.slice(commonHead, len2 - commonTail);\n const seq = lcs.get(trimmed1, trimmed2, matchItems, matchContext);\n const removedItems = [];\n result = result || {\n _t: 'a',\n };\n for (index = commonHead; index < len1 - commonTail; index++) {\n if (seq.indices1.indexOf(index - commonHead) < 0) {\n // removed\n result[`_${index}`] = [array1[index], 0, 0];\n removedItems.push(index);\n }\n }\n let detectMove = true;\n if (context.options &&\n context.options.arrays &&\n context.options.arrays.detectMove === false) {\n detectMove = false;\n }\n let includeValueOnMove = false;\n if (context.options &&\n context.options.arrays &&\n context.options.arrays.includeValueOnMove) {\n includeValueOnMove = true;\n }\n const removedItemsLength = removedItems.length;\n for (index = commonHead; index < len2 - commonTail; index++) {\n const indexOnArray2 = seq.indices2.indexOf(index - commonHead);\n if (indexOnArray2 < 0) {\n // added, try to match with a removed item and register as position move\n let isMove = false;\n if (detectMove && removedItemsLength > 0) {\n for (let removeItemIndex1 = 0; removeItemIndex1 < removedItemsLength; removeItemIndex1++) {\n index1 = removedItems[removeItemIndex1];\n if (matchItems(trimmed1, trimmed2, index1 - commonHead, index - commonHead, matchContext)) {\n // store position move as: [originalValue, newPosition, ARRAY_MOVE]\n result[`_${index1}`].splice(1, 2, index, ARRAY_MOVE);\n if (!includeValueOnMove) {\n // don't include moved value on diff, to save bytes\n result[`_${index1}`][0] = '';\n }\n index2 = index;\n child = new DiffContext(array1[index1], array2[index2]);\n context.push(child, index2);\n removedItems.splice(removeItemIndex1, 1);\n isMove = true;\n break;\n }\n }\n }\n if (!isMove) {\n // added\n result[index] = [array2[index]];\n }\n }\n else {\n // match, do inner diff\n index1 = seq.indices1[indexOnArray2] + commonHead;\n index2 = seq.indices2[indexOnArray2] + commonHead;\n child = new DiffContext(array1[index1], array2[index2]);\n context.push(child, index2);\n }\n }\n context.setResult(result).exit();\n};\ndiffFilter.filterName = 'arrays';\nconst compare = {\n numerically(a, b) {\n return a - b;\n },\n numericallyBy(name) {\n return (a, b) => a[name] - b[name];\n },\n};\nexport const patchFilter = function nestedPatchFilter(context) {\n if (!context.nested) {\n return;\n }\n const nestedDelta = context.delta;\n if (nestedDelta._t !== 'a') {\n return;\n }\n let index;\n let index1;\n const delta = nestedDelta;\n const array = context.left;\n // first, separate removals, insertions and modifications\n let toRemove = [];\n let toInsert = [];\n const toModify = [];\n for (index in delta) {\n if (index !== '_t') {\n if (index[0] === '_') {\n const removedOrMovedIndex = index;\n // removed item from original array\n if (delta[removedOrMovedIndex][2] === 0 ||\n delta[removedOrMovedIndex][2] === ARRAY_MOVE) {\n toRemove.push(parseInt(index.slice(1), 10));\n }\n else {\n throw new Error('only removal or move can be applied at original array indices,' +\n ` invalid diff type: ${delta[removedOrMovedIndex][2]}`);\n }\n }\n else {\n const numberIndex = index;\n if (delta[numberIndex].length === 1) {\n // added item at new array\n toInsert.push({\n index: parseInt(numberIndex, 10),\n value: delta[numberIndex][0],\n });\n }\n else {\n // modified item at new array\n toModify.push({\n index: parseInt(numberIndex, 10),\n delta: delta[numberIndex],\n });\n }\n }\n }\n }\n // remove items, in reverse order to avoid sawing our own floor\n toRemove = toRemove.sort(compare.numerically);\n for (index = toRemove.length - 1; index >= 0; index--) {\n index1 = toRemove[index];\n const indexDiff = delta[`_${index1}`];\n const removedValue = array.splice(index1, 1)[0];\n if (indexDiff[2] === ARRAY_MOVE) {\n // reinsert later\n toInsert.push({\n index: indexDiff[1],\n value: removedValue,\n });\n }\n }\n // insert items, in reverse order to avoid moving our own floor\n toInsert = toInsert.sort(compare.numericallyBy('index'));\n const toInsertLength = toInsert.length;\n for (index = 0; index < toInsertLength; index++) {\n const insertion = toInsert[index];\n array.splice(insertion.index, 0, insertion.value);\n }\n // apply modifications\n const toModifyLength = toModify.length;\n let child;\n if (toModifyLength > 0) {\n for (index = 0; index < toModifyLength; index++) {\n const modification = toModify[index];\n child = new PatchContext(array[modification.index], modification.delta);\n context.push(child, modification.index);\n }\n }\n if (!context.children) {\n context.setResult(array).exit();\n return;\n }\n context.exit();\n};\npatchFilter.filterName = 'arrays';\nexport const collectChildrenPatchFilter = function collectChildrenPatchFilter(context) {\n if (!context || !context.children) {\n return;\n }\n const deltaWithChildren = context.delta;\n if (deltaWithChildren._t !== 'a') {\n return;\n }\n const array = context.left;\n const length = context.children.length;\n let child;\n for (let index = 0; index < length; index++) {\n child = context.children[index];\n const arrayIndex = child.childName;\n array[arrayIndex] = child.result;\n }\n context.setResult(array).exit();\n};\ncollectChildrenPatchFilter.filterName = 'arraysCollectChildren';\nexport const reverseFilter = function arraysReverseFilter(context) {\n if (!context.nested) {\n const nonNestedDelta = context.delta;\n if (nonNestedDelta[2] === ARRAY_MOVE) {\n const arrayMoveDelta = nonNestedDelta;\n context.newName = `_${arrayMoveDelta[1]}`;\n context\n .setResult([\n arrayMoveDelta[0],\n parseInt(context.childName.substring(1), 10),\n ARRAY_MOVE,\n ])\n .exit();\n }\n return;\n }\n const nestedDelta = context.delta;\n if (nestedDelta._t !== 'a') {\n return;\n }\n const arrayDelta = nestedDelta;\n let name;\n let child;\n for (name in arrayDelta) {\n if (name === '_t') {\n continue;\n }\n child = new ReverseContext(arrayDelta[name]);\n context.push(child, name);\n }\n context.exit();\n};\nreverseFilter.filterName = 'arrays';\nconst reverseArrayDeltaIndex = (delta, index, itemDelta) => {\n if (typeof index === 'string' && index[0] === '_') {\n return parseInt(index.substring(1), 10);\n }\n else if (Array.isArray(itemDelta) && itemDelta[2] === 0) {\n return `_${index}`;\n }\n let reverseIndex = +index;\n for (const deltaIndex in delta) {\n const deltaItem = delta[deltaIndex];\n if (Array.isArray(deltaItem)) {\n if (deltaItem[2] === ARRAY_MOVE) {\n const moveFromIndex = parseInt(deltaIndex.substring(1), 10);\n const moveToIndex = deltaItem[1];\n if (moveToIndex === +index) {\n return moveFromIndex;\n }\n if (moveFromIndex <= reverseIndex && moveToIndex > reverseIndex) {\n reverseIndex++;\n }\n else if (moveFromIndex >= reverseIndex &&\n moveToIndex < reverseIndex) {\n reverseIndex--;\n }\n }\n else if (deltaItem[2] === 0) {\n const deleteIndex = parseInt(deltaIndex.substring(1), 10);\n if (deleteIndex <= reverseIndex) {\n reverseIndex++;\n }\n }\n else if (deltaItem.length === 1 &&\n parseInt(deltaIndex, 10) <= reverseIndex) {\n reverseIndex--;\n }\n }\n }\n return reverseIndex;\n};\nexport const collectChildrenReverseFilter = (context) => {\n if (!context || !context.children) {\n return;\n }\n const deltaWithChildren = context.delta;\n if (deltaWithChildren._t !== 'a') {\n return;\n }\n const arrayDelta = deltaWithChildren;\n const length = context.children.length;\n let child;\n const delta = {\n _t: 'a',\n };\n for (let index = 0; index < length; index++) {\n child = context.children[index];\n let name = child.newName;\n if (typeof name === 'undefined') {\n name = reverseArrayDeltaIndex(arrayDelta, child.childName, child.result);\n }\n if (delta[name] !== child.result) {\n // There's no way to type this well.\n delta[name] = child.result;\n }\n }\n context.setResult(delta).exit();\n};\ncollectChildrenReverseFilter.filterName = 'arraysCollectChildren';\n","export const diffFilter = function datesDiffFilter(context) {\n if (context.left instanceof Date) {\n if (context.right instanceof Date) {\n if (context.left.getTime() !== context.right.getTime()) {\n context.setResult([context.left, context.right]);\n }\n else {\n context.setResult(undefined);\n }\n }\n else {\n context.setResult([context.left, context.right]);\n }\n context.exit();\n }\n else if (context.right instanceof Date) {\n context.setResult([context.left, context.right]).exit();\n }\n};\ndiffFilter.filterName = 'dates';\n","const TEXT_DIFF = 2;\nconst DEFAULT_MIN_LENGTH = 60;\nlet cachedDiffPatch = null;\nfunction getDiffMatchPatch(options, required) {\n var _a;\n if (!cachedDiffPatch) {\n let instance;\n if ((_a = options === null || options === void 0 ? void 0 : options.textDiff) === null || _a === void 0 ? void 0 : _a.diffMatchPatch) {\n instance = new options.textDiff.diffMatchPatch();\n }\n else {\n if (!required) {\n return null;\n }\n const error = new Error('The diff-match-patch library was not provided. Pass the library in through the options or use the `jsondiffpatch/with-text-diffs` entry-point.');\n // eslint-disable-next-line camelcase\n error.diff_match_patch_not_found = true;\n throw error;\n }\n cachedDiffPatch = {\n diff: function (txt1, txt2) {\n return instance.patch_toText(instance.patch_make(txt1, txt2));\n },\n patch: function (txt1, patch) {\n const results = instance.patch_apply(instance.patch_fromText(patch), txt1);\n for (let i = 0; i < results[1].length; i++) {\n if (!results[1][i]) {\n const error = new Error('text patch failed');\n error.textPatchFailed = true;\n }\n }\n return results[0];\n },\n };\n }\n return cachedDiffPatch;\n}\nexport const diffFilter = function textsDiffFilter(context) {\n if (context.leftType !== 'string') {\n return;\n }\n const left = context.left;\n const right = context.right;\n const minLength = (context.options &&\n context.options.textDiff &&\n context.options.textDiff.minLength) ||\n DEFAULT_MIN_LENGTH;\n if (left.length < minLength || right.length < minLength) {\n context.setResult([left, right]).exit();\n return;\n }\n // large text, try to use a text-diff algorithm\n const diffMatchPatch = getDiffMatchPatch(context.options);\n if (!diffMatchPatch) {\n // diff-match-patch library not available,\n // fallback to regular string replace\n context.setResult([left, right]).exit();\n return;\n }\n const diff = diffMatchPatch.diff;\n context.setResult([diff(left, right), 0, TEXT_DIFF]).exit();\n};\ndiffFilter.filterName = 'texts';\nexport const patchFilter = function textsPatchFilter(context) {\n if (context.nested) {\n return;\n }\n const nonNestedDelta = context.delta;\n if (nonNestedDelta[2] !== TEXT_DIFF) {\n return;\n }\n const textDiffDelta = nonNestedDelta;\n // text-diff, use a text-patch algorithm\n const patch = getDiffMatchPatch(context.options, true).patch;\n context.setResult(patch(context.left, textDiffDelta[0])).exit();\n};\npatchFilter.filterName = 'texts';\nconst textDeltaReverse = function (delta) {\n let i;\n let l;\n let line;\n let lineTmp;\n let header = null;\n const headerRegex = /^@@ +-(\\d+),(\\d+) +\\+(\\d+),(\\d+) +@@$/;\n let lineHeader;\n const lines = delta.split('\\n');\n for (i = 0, l = lines.length; i < l; i++) {\n line = lines[i];\n const lineStart = line.slice(0, 1);\n if (lineStart === '@') {\n header = headerRegex.exec(line);\n lineHeader = i;\n // fix header\n lines[lineHeader] =\n '@@ -' +\n header[3] +\n ',' +\n header[4] +\n ' +' +\n header[1] +\n ',' +\n header[2] +\n ' @@';\n }\n else if (lineStart === '+') {\n lines[i] = '-' + lines[i].slice(1);\n if (lines[i - 1].slice(0, 1) === '+') {\n // swap lines to keep default order (-+)\n lineTmp = lines[i];\n lines[i] = lines[i - 1];\n lines[i - 1] = lineTmp;\n }\n }\n else if (lineStart === '-') {\n lines[i] = '+' + lines[i].slice(1);\n }\n }\n return lines.join('\\n');\n};\nexport const reverseFilter = function textsReverseFilter(context) {\n if (context.nested) {\n return;\n }\n const nonNestedDelta = context.delta;\n if (nonNestedDelta[2] !== TEXT_DIFF) {\n return;\n }\n const textDiffDelta = nonNestedDelta;\n // text-diff, use a text-diff algorithm\n context\n .setResult([textDeltaReverse(textDiffDelta[0]), 0, TEXT_DIFF])\n .exit();\n};\nreverseFilter.filterName = 'texts';\n","import Processor from './processor.js';\nimport Pipe from './pipe.js';\nimport DiffContext from './contexts/diff.js';\nimport PatchContext from './contexts/patch.js';\nimport ReverseContext from './contexts/reverse.js';\nimport clone from './clone.js';\nimport * as trivial from './filters/trivial.js';\nimport * as nested from './filters/nested.js';\nimport * as arrays from './filters/arrays.js';\nimport * as dates from './filters/dates.js';\nimport * as texts from './filters/texts.js';\nclass DiffPatcher {\n constructor(options) {\n this.processor = new Processor(options);\n this.processor.pipe(new Pipe('diff')\n .append(nested.collectChildrenDiffFilter, trivial.diffFilter, dates.diffFilter, texts.diffFilter, nested.objectsDiffFilter, arrays.diffFilter)\n .shouldHaveResult());\n this.processor.pipe(new Pipe('patch')\n .append(nested.collectChildrenPatchFilter, arrays.collectChildrenPatchFilter, trivial.patchFilter, texts.patchFilter, nested.patchFilter, arrays.patchFilter)\n .shouldHaveResult());\n this.processor.pipe(new Pipe('reverse')\n .append(nested.collectChildrenReverseFilter, arrays.collectChildrenReverseFilter, trivial.reverseFilter, texts.reverseFilter, nested.reverseFilter, arrays.reverseFilter)\n .shouldHaveResult());\n }\n options(options) {\n return this.processor.options(options);\n }\n diff(left, right) {\n return this.processor.process(new DiffContext(left, right));\n }\n patch(left, delta) {\n return this.processor.process(new PatchContext(left, delta));\n }\n reverse(delta) {\n return this.processor.process(new ReverseContext(delta));\n }\n unpatch(right, delta) {\n return this.patch(right, this.reverse(delta));\n }\n clone(value) {\n return clone(value);\n }\n}\nexport default DiffPatcher;\n","import DiffPatcher from './diffpatcher.js';\nimport dateReviver from './date-reviver.js';\nexport { DiffPatcher, dateReviver };\nexport function create(options) {\n return new DiffPatcher(options);\n}\nlet defaultInstance;\nexport function diff(left, right) {\n if (!defaultInstance) {\n defaultInstance = new DiffPatcher();\n }\n return defaultInstance.diff(left, right);\n}\nexport function patch(left, delta) {\n if (!defaultInstance) {\n defaultInstance = new DiffPatcher();\n }\n return defaultInstance.patch(left, delta);\n}\nexport function unpatch(right, delta) {\n if (!defaultInstance) {\n defaultInstance = new DiffPatcher();\n }\n return defaultInstance.unpatch(right, delta);\n}\nexport function reverse(delta) {\n if (!defaultInstance) {\n defaultInstance = new DiffPatcher();\n }\n return defaultInstance.reverse(delta);\n}\nexport function clone(value) {\n if (!defaultInstance) {\n defaultInstance = new DiffPatcher();\n }\n return defaultInstance.clone(value);\n}\n","import * as jsondiffpatch from 'jsondiffpatch'\n\nconst jdf = jsondiffpatch.create({})\n\nfunction isArrayStringAppend(\n delta: jsondiffpatch.Delta,\n): false | [...number[], string] {\n // Check that the delta type is 'a' (array):\n if (delta && '_t' in delta && delta._t === 'a') {\n const arrayDelta = delta as jsondiffpatch.ArrayDelta\n\n let index = -1\n let removedIndex = -1\n for (const i in arrayDelta) {\n if (i === '_t') {\n continue\n }\n // In jsondiffpatch, properties starting with an underscore in an array delta represent removed or moved elements:\n if (i.startsWith('_')) {\n removedIndex = +i.slice(1)\n continue\n }\n if (index !== -1) {\n return false\n }\n index = +i\n }\n\n if (removedIndex === -1) {\n // Nothing was removed, check if the element at index is a string append:\n const res = isArrayStringAppend(arrayDelta[index])\n if (res === false) {\n return false\n }\n return [index, ...res]\n }\n\n // https://github.com/benjamine/jsondiffpatch/blob/master/docs/deltas.md\n if (index === removedIndex) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n const deltaNew = arrayDelta[index] as jsondiffpatch.Delta\n const deltaOld = arrayDelta[`_${removedIndex}`] as jsondiffpatch.Delta\n if (\n Array.isArray(deltaNew) &&\n deltaNew.length === 1 &&\n typeof deltaNew[0] === 'string' &&\n Array.isArray(deltaOld) &&\n deltaOld.length === 3 &&\n typeof deltaOld[0] === 'string' &&\n deltaOld[1] === 0 &&\n deltaOld[2] === 0\n ) {\n const newStr = deltaNew[0]\n const oldStr = deltaOld[0]\n if (newStr.startsWith(oldStr)) {\n return [index, newStr.slice(oldStr.length)]\n }\n }\n }\n }\n return false\n}\n\nexport function diff(original: any, modified: any) {\n const delta = jdf.diff(original, modified)\n\n const maybeStringAppend = isArrayStringAppend(delta)\n if (maybeStringAppend !== false) {\n // Our customized delta - string append to a recursive array index\n return [maybeStringAppend, 9, 9]\n }\n\n return delta\n}\n\nexport function patch(original: any, delta: any) {\n if (!delta) {\n return original\n }\n\n try {\n const newObj = jdf.clone(original)\n\n // Check for our customized delta\n if (Array.isArray(delta) && delta[1] === 9 && delta[2] === 9) {\n // Get the path to the modified element\n const indexes = delta[0].slice(0, -1)\n // Get the string to be appended\n const value = delta[0].slice(-1)\n let obj = newObj as any\n for (const index of indexes) {\n if (obj === undefined || obj === null) {\n // Path doesn't exist, return original unchanged\n return original\n }\n if (typeof obj[index] === 'string') {\n obj[index] += value\n return newObj\n }\n obj = obj[index]\n }\n // If we get here and obj is a string, append to it\n if (typeof obj === 'string') {\n return original // Can't modify, return unchanged\n }\n }\n\n // If not custom delta, apply standard jsondiffpatch-ing\n jdf.patch(newObj, delta)\n return newObj\n } catch {\n // If patching fails, return original state unchanged\n return original\n }\n}\n","import type { MessageContent } from '../../chat/mdx0/types'\nimport { isLlmError } from './isLlmError'\nimport { patch } from './diffpatch'\n\nexport async function* streamToTree({\n reader,\n onError,\n signal,\n}: {\n onError: (\n error: Error,\n result: {\n finishReason:\n | `provider_server_error:${string}`\n | `retry_provider_server_error:${string}`\n },\n ) => void\n signal?: AbortSignal\n reader: ReadableStreamDefaultReader<Uint8Array<ArrayBufferLike>>\n}): AsyncGenerator<MessageContent> {\n let state: any = []\n const decoder = new TextDecoder()\n let remainingLine = ''\n\n function processRow(row: string) {\n const delta = JSON.parse(row)\n state = patch(state, delta)\n return state\n }\n\n while (true) {\n if (signal?.aborted) {\n throw new Error('Signal aborted')\n }\n\n const { done, value } = await reader.read()\n if (done) {\n break\n }\n\n const chunk =\n remainingLine +\n (value instanceof Uint8Array ? decoder.decode(value) : value)\n const lines = chunk.split('\\n')\n\n for (let i = 0; i < lines.length - 1; i++) {\n const {\n isLlmError: error,\n isRetried,\n errorCategory = 'default',\n } = isLlmError(lines[i]!)\n\n if (error) {\n return onError(new Error('LLM call error'), {\n finishReason: isRetried\n ? `retry_provider_server_error:${errorCategory}`\n : `provider_server_error:${errorCategory}`,\n })\n } else {\n yield processRow(lines[i]!)\n }\n }\n remainingLine = lines[lines.length - 1]!\n }\n\n if (remainingLine) {\n const {\n isLlmError: error,\n isRetried,\n errorCategory = 'default',\n } = isLlmError(remainingLine)\n if (error) {\n return onError(new Error('LLM call error'), {\n finishReason: isRetried\n ? `retry_provider_server_error:${errorCategory}`\n : `provider_server_error:${errorCategory}`,\n })\n } else {\n yield processRow(remainingLine)\n }\n }\n}\n","import * as z from 'zod'\n\nexport function createProgrammaticTask<\n Schema extends z.ZodType,\n Result,\n>(input: {\n schema: Schema\n handler: (input: NonNullable<z.infer<Schema>>) => Promise<Result>\n}) {\n return {\n zodSchema: input.schema,\n jsonSchema: z.toJSONSchema(input.schema),\n handler: input.handler,\n }\n}\n","import { createProgrammaticTask } from '../../../create-programmatic-task'\nimport * as z from 'zod'\nimport type { MessageContent } from '../../../../chat/mdx0/types'\nimport { extractItemOfType } from '../../../../chat/mdx0/helpers'\n\nexport const createPullRequestSchema = z.union([\n z\n .object({\n shouldCreatePullRequest: z.literal(false),\n messageResponseText: z\n .string()\n .describe(\n 'Full response to reply to the user, this will be used in the chat response.',\n ),\n })\n .describe(\n 'If no code changes were made, pass this object to skip making a PR.',\n ),\n z\n .object({\n title: z.string().min(1),\n body: z.string().min(1),\n shouldCreatePullRequest: z.literal(true),\n messageResponseText: z\n .string()\n .describe(\n 'A short message explaining the changes made, this will be sent to the user as a response.',\n ),\n })\n .describe(\n `\\\nPass this object to create a pull request on behalf of the user.\n\nYou MUST ALWAYS pass \\`shouldCreatePullRequest: true\\` after making any Edits or Writes.\nYou MUST NEVER try to create a pull request with the Bash tool or GitHub API directly. Always use this object which will ensure the PR is created correctly.\n`,\n ),\n])\n\nexport const programmaticTasks = {\n createPullRequest: createProgrammaticTask({\n schema: createPullRequestSchema,\n // eslint-disable-next-line @typescript-eslint/require-await\n handler: async (input) => input,\n }),\n} as const\n\nexport interface ProgrammaticFlags {\n shouldCreatePR?: boolean\n}\n\n/** Builds result type based on which flags are true */\nexport type ComposedProgrammaticResult<TFlags extends ProgrammaticFlags> =\n (TFlags['shouldCreatePR'] extends true\n ? { createPullRequest: z.infer<typeof createPullRequestSchema> }\n : // eslint-disable-next-line @typescript-eslint/ban-types\n {}) &\n // eslint-disable-next-line @typescript-eslint/ban-types\n {}\n\ntype ComposedSchemaReturnType<TFlags extends ProgrammaticFlags> =\n TFlags['shouldCreatePR'] extends true\n ? z.ZodObject<{ createPullRequest: typeof createPullRequestSchema }>\n : undefined\n\nexport function composeProgrammaticSchema<TFlags extends ProgrammaticFlags>(\n flags: TFlags,\n): ComposedSchemaReturnType<TFlags> {\n const schemaShape: Record<string, z.ZodType> = {}\n\n if (flags.shouldCreatePR) {\n schemaShape.createPullRequest = createPullRequestSchema\n }\n\n if (Object.keys(schemaShape).length > 0) {\n return z.object(schemaShape) as ComposedSchemaReturnType<TFlags>\n }\n\n return undefined as ComposedSchemaReturnType<TFlags>\n}\n\nexport function composeProgrammaticJsonSchema<TFlags extends ProgrammaticFlags>(\n flags: TFlags,\n): Record<string, unknown> | undefined {\n const schema = composeProgrammaticSchema(flags)\n if (schema) {\n return z.toJSONSchema(schema)\n }\n return undefined\n}\n\n/** Extracts programmatic result text from message content if present */\nexport function maybeProgrammaticResult(\n content: MessageContent,\n): string | null {\n const items = extractItemOfType(content, 'AssistantMessageContentPart')\n\n if (items?.props.part?.type === 'task-programmatic-result-v1') {\n for (const part of items.props.part.parts) {\n if (part.type === 'result') {\n return part.structuredOutput || part.text || null\n }\n }\n return null\n }\n return null\n}\n","import { AssistantMessageContentRichPart } from '../../message-content-schema'\n\nexport type MessageContentMetadata = {\n title?: string\n}\n\nexport type MessageContent = Array<\n | [0, MessageContentItem[]] // Section with content items\n | [1, MessageContentMetadata] // Section with metadata\n>\n\ntype NodeTuple1 = {\n [Node in keyof ChatMessageNode]: [Node, ChatMessageNode[Node], ...unknown[]]\n}\n\ntype NodeTuple2<Child> = {\n [Node in keyof ChatMessageNode]: [Node, ChatMessageNode[Node], ...Child[]]\n}\n\nexport type MessageContentItem =\n | NodeTuple2<string | NodeTuple2<NodeTuple1>>[keyof ChatMessageNode]\n | string\n\nconst VALID_STEP_TYPES = [\n 'add-integration',\n 'run-script',\n 'add-env-var',\n 'run-action',\n] as const\n\ntype StepType = (typeof VALID_STEP_TYPES)[number]\n\nexport type IntegrationStatus =\n | 'none'\n | 'creating_project'\n | 'linking_integration'\n | 'added_env_vars'\n | 'connected_integration'\n | 'applying_script'\n | 'applied_script'\n | 'applying_action'\n | 'completed_action'\n | 'introspecting_db'\n\nexport type StepStatus = IntegrationStatus\n\nexport type Step = {\n type: StepType\n stepName: string\n}\n\nexport type StepWithStatus = Step & {\n status: StepStatus | undefined\n}\n\nexport type ChatMessageNode = {\n text: {\n children?: string\n [key: string]: unknown\n }\n p: Record<string, unknown> & {\n children?: string\n }\n blockquote: Record<string, unknown>\n strong: Record<string, unknown> & {\n children?: string\n }\n em: Record<string, unknown>\n del: Record<string, unknown>\n h1: {\n id?: string\n children?: string\n [key: string]: unknown\n }\n h2: {\n id?: string\n children?: string\n [key: string]: unknown\n }\n h3: {\n id?: string\n children?: string\n [key: string]: unknown\n }\n h4: {\n id?: string\n children?: string\n [key: string]: unknown\n }\n h5: {\n id?: string\n children?: string\n [key: string]: unknown\n }\n h6: {\n id?: string\n children?: string\n [key: string]: unknown\n }\n ul: {\n start?: number\n children?: string\n [key: string]: unknown\n }\n ol: {\n start?: number\n children?: string\n [key: string]: unknown\n }\n li: {\n index?: number\n children?: string\n [key: string]: unknown\n }\n code: {\n lang?: string\n meta?: Record<string, unknown>\n children?: string\n [key: string]: unknown\n }\n a: {\n href: string\n children?: any\n [key: string]: unknown\n }\n img: {\n src: string\n alt?: string\n children?: string\n [key: string]: unknown\n }\n hr: Record<string, unknown>\n table: Record<string, unknown>\n tr: Record<string, unknown>\n td: Record<string, unknown>\n th: Record<string, unknown>\n thead: Record<string, unknown>\n tbody: Record<string, unknown>\n Codeblock: CodeBlock\n InlineMath: Record<string, unknown>\n Math: Record<string, unknown>\n LinearProcessFlow: Record<string, unknown>\n Steps: Record<string, unknown>\n StepsCard: {\n steps: Step[]\n children?: string\n }\n Thinking: {\n closed?: boolean\n chars?: number\n children?: Array<MessageContentItem>\n [key: string]: unknown\n }\n DevThinking: {\n closed?: boolean\n chars?: number\n children?: Array<MessageContentItem>\n [key: string]: unknown\n }\n V0Info: {\n closed?: boolean\n chars?: number\n children?: Array<MessageContentItem>\n [key: string]: unknown\n }\n Solution: Record<string, unknown>\n Quiz: Record<string, unknown>\n Spinner: {\n message?: string\n [key: string]: unknown\n }\n MathInstructions: Record<string, unknown>\n MathBlock: Record<string, unknown>\n footnoteReference: {\n label: string\n [key: string]: unknown\n }\n footnoteDefinition: Record<string, unknown>\n AddEnvironmentVariables: {\n names: string[]\n [key: string]: unknown\n }\n AddEnvironmentVariable: {\n names: string[]\n [key: string]: unknown\n }\n AddIntegration: {\n category: string\n names: string[]\n starter?: boolean\n [key: string]: unknown\n }\n OpenExternalDashboard: {\n integration: string\n [key: string]: unknown\n }\n SuggestedNextSteps: {\n options: Array<Record<string, unknown>>\n [key: string]: unknown\n }\n LoadingLighthouse: Record<string, unknown>\n AssistantMessageContentPart: {\n part: AssistantMessageContentRichPart | null\n [key: string]: unknown\n }\n Lighthouse: Record<string, unknown>\n LighthouseReport: Record<string, unknown>\n br: Record<string, unknown>\n Action: {\n name: string\n description: string\n [key: string]: unknown\n }\n Actions: Record<string, unknown>\n span: Record<string, unknown>\n}\n\nexport type NarrowedMessageContentItem<Type extends keyof ChatMessageNode> = [\n Type,\n ChatMessageNode[Type],\n ...MessageContentItem[],\n]\n\nexport type CodeBlock = {\n lang: string\n meta: Record<string, unknown>\n closed?: boolean\n blockId?: string\n remoteInfo?: Record<string, unknown>\n resultId?: string\n latestDeploymentInfo?: Record<string, unknown>\n}\n\n/**\n * @deprecated not deprecated but don't use me\n */\nexport interface MessageContext {}\n\nexport function getMessageRowType<Row extends MessageContent[number]>(\n row: Row,\n):\n | { type: 'markdown'; data: MessageContentItem[] }\n | { type: 'metadata'; data: MessageContentMetadata }\n | null {\n if (row[0] === 0) {\n return { type: 'markdown', data: row[1] }\n }\n if (row[0] === 1) {\n return { type: 'metadata', data: row[1] }\n }\n return null\n}\n","import {\n ChatMessageNode,\n MessageContent,\n MessageContentItem,\n getMessageRowType,\n} from './types'\n\nexport function extractItemOfType<T extends keyof ChatMessageNode>(\n content: MessageContent,\n targetType: T,\n) {\n function extractFromItems(items: MessageContentItem[]) {\n for (let i = items.length - 1; i >= 0; i--) {\n const item = items[i]\n if (item == null || typeof item === 'string') {\n continue\n }\n\n if (Array.isArray(item)) {\n const [type, props, ...children] = item\n\n if (type === targetType) {\n return { props: props as ChatMessageNode[T], children }\n }\n }\n }\n return null\n }\n\n if (!content) {\n return null\n }\n\n for (let i = content.length - 1; i >= 0; i--) {\n const row = content[i]!\n const rowInfo = getMessageRowType(row)\n if (rowInfo?.type === 'markdown') {\n return extractFromItems(rowInfo.data) as {\n props: ChatMessageNode[T]\n children: MessageContentItem[]\n } | null\n }\n }\n\n return null\n}\n\nexport function extractAllItemsOfType<T extends keyof ChatMessageNode>(\n content: MessageContent,\n targetType: T,\n) {\n const result: {\n props: ChatMessageNode[T]\n children: MessageContentItem[]\n }[] = []\n function extractFromItems(items: MessageContentItem[]) {\n for (const item of items) {\n if (item == null || typeof item === 'string') {\n continue\n }\n\n if (Array.isArray(item)) {\n const [type, props, ...children] = item\n\n if (type === targetType) {\n result.push({\n props: props as ChatMessageNode[T],\n children: children as MessageContentItem[],\n })\n }\n }\n }\n return null\n }\n\n if (!content) {\n return null\n }\n\n for (const row of content) {\n const rowInfo = getMessageRowType(row)\n if (rowInfo?.type === 'markdown') {\n extractFromItems(rowInfo.data)\n }\n }\n\n return result\n}\n","import { streamToTree } from '../../../stream/stream-to-tree'\nimport type { StreamEvent } from '../../stream-events'\nimport type { CreateStreamInput, MessageContentServer } from '../../schemas'\nimport {\n type ProgrammaticFlags,\n type ComposedProgrammaticResult,\n composeProgrammaticJsonSchema,\n maybeProgrammaticResult,\n} from './programmatic-tasks'\nimport { createChatId, createMessageId } from './create-id'\n\ninterface CreateMessageStreamParams<TFlags extends ProgrammaticFlags> {\n input: CreateStreamInput & TFlags & { isNew: boolean }\n baseUrl: string\n headers: Record<string, string>\n}\n\nexport async function* createMessageStream<TFlags extends ProgrammaticFlags>({\n input,\n baseUrl,\n headers,\n}: CreateMessageStreamParams<TFlags>): AsyncGenerator<\n StreamEvent<ComposedProgrammaticResult<TFlags>>\n> {\n const chatId = input.chatId ?? (await createChatId())\n const messageId = input.messageId ?? createMessageId()\n\n // Support both raw programmatic config and boolean flags\n let programmatic: { enabled: boolean; jsonSchema?: unknown } | undefined\n if (input.programmatic) {\n // Raw programmatic config passed directly (e.g., from headless mode)\n programmatic = input.programmatic\n } else {\n // Compose from boolean flags\n const programmaticJsonSchema = composeProgrammaticJsonSchema(input)\n programmatic = programmaticJsonSchema\n ? { enabled: true, jsonSchema: programmaticJsonSchema }\n : undefined\n }\n\n // Default sandbox to enabled if config is provided but enabled is not set\n if (input.sandbox && input.sandbox.enabled === undefined) {\n input.sandbox.enabled = true\n }\n\n let messageContent: MessageContentServer\n if (typeof input.message === 'string') {\n messageContent = {\n version: 1,\n parts: [{ type: 'mdx', content: input.message }],\n }\n } else {\n messageContent = {\n version: 1,\n parts: input.message,\n }\n }\n\n const requestBody: Record<string, unknown> = {\n chatId,\n messageId,\n messageContent,\n modelConfiguration: input.modelConfiguration ?? {\n modelId: 'v0-max',\n imageGenerations: true,\n },\n userMessageType: input.userMessageType ?? 'message',\n isNew: input.isNew,\n agentPermissions: input.agentPermissions ?? [\n { type: 'ALLOW_ALL_DYNAMIC_TOOLS' },\n ],\n attachments: input.attachments ?? [],\n projectId: input.projectId ?? null,\n parentId: input.parentId,\n programmatic,\n sandbox: input.sandbox,\n remote: input.remote,\n chatPrivacy: input.chatPrivacy,\n }\n\n const response = await fetch(`${baseUrl}/chat/api/chat`, {\n method: 'POST',\n headers: {\n ...headers,\n Accept: 'text/event-stream',\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestBody),\n })\n\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n } catch {\n // Ignore\n }\n console.error(\n '[createMessageStream] failed with status',\n response.status,\n errorBody ?? response.statusText,\n )\n yield {\n type: 'error',\n chatId,\n error: new Error(errorBody ?? response.statusText),\n assistantMessageId: '',\n git: null,\n }\n return\n }\n\n const assistantMessageId =\n response.headers.get('x-v0-response-message-id') ?? ''\n\n if (!assistantMessageId) {\n yield {\n type: 'error',\n error: new Error('No assistant message ID received in response headers'),\n chatId,\n assistantMessageId: '',\n git: null,\n }\n return\n }\n\n const gitHeadBranch = response.headers.get('x-v0-git-head')\n const gitBaseBranch = response.headers.get('x-v0-git-base')\n const gitRepo = response.headers.get('x-v0-git-repo')\n const gitOrg = response.headers.get('x-v0-git-org')\n\n let gitMeta = null\n if (gitHeadBranch && gitBaseBranch && gitRepo && gitOrg) {\n gitMeta = {\n head: gitHeadBranch,\n base: gitBaseBranch,\n repo: gitRepo,\n org: gitOrg,\n }\n }\n\n const chunkMeta = {\n chatId,\n assistantMessageId,\n git: gitMeta,\n }\n\n yield { ...chunkMeta, type: 'start' }\n\n const reader = response.body?.getReader()\n if (!reader) {\n yield {\n ...chunkMeta,\n type: 'error',\n error: new Error('No response body received from chat API'),\n }\n return\n }\n\n let programmaticResultYielded = false\n let streamError: Error | null = null\n\n const stream = streamToTree({\n reader,\n onError: (error, { finishReason }) => {\n streamError = new Error(`Stream error: ${finishReason}`, { cause: error })\n },\n })\n\n try {\n for await (const content of stream) {\n // Check for stream error first - stop processing immediately\n if (streamError) {\n yield {\n ...chunkMeta,\n type: 'error',\n error: streamError,\n }\n return\n }\n\n if (!programmaticResultYielded) {\n const programmaticResult = maybeProgrammaticResult(content)\n if (programmaticResult) {\n try {\n yield {\n ...chunkMeta,\n type: 'programmatic',\n result: programmaticResult as any,\n }\n programmaticResultYielded = true\n } catch (e) {\n console.error(e)\n // Failed to parse\n }\n }\n }\n\n yield {\n ...chunkMeta,\n type: 'message',\n content,\n }\n }\n\n // Check for error that occurred on final chunk\n if (streamError) {\n yield {\n ...chunkMeta,\n type: 'error',\n error: streamError,\n }\n return\n }\n\n yield {\n ...chunkMeta,\n type: 'complete',\n }\n } catch (error) {\n yield {\n ...chunkMeta,\n type: 'error',\n error: error instanceof Error ? error : new Error(String(error)),\n }\n }\n}\n","import * as z from 'zod'\n\nexport const CreatePullRequestInputSchema = z.object({\n chatId: z.string().min(1),\n content: z\n .object({\n title: z.string().min(1),\n body: z.string().min(1),\n })\n .optional(),\n pushLatestChanges: z.boolean().optional().default(true),\n})\n\nexport type CreatePullRequestInput = z.infer<\n typeof CreatePullRequestInputSchema\n>\n\nconst MergeableState = z.enum([\n 'clean',\n 'dirty',\n 'unstable',\n 'blocked',\n 'behind',\n 'unknown',\n 'draft',\n])\n\nexport const CreatePullRequestResultSchema = z.discriminatedUnion('ok', [\n z.object({\n ok: z.literal(true),\n value: z.object({\n state: z.enum(['open', 'closed', 'merged']),\n title: z.string(),\n updatedAt: z.string(),\n id: z.number(),\n avatar: z.string().nullable(),\n htmlUrl: z.string(),\n mergeableState: MergeableState.nullable(),\n head: z.string(),\n }),\n }),\n z.object({\n ok: z.literal(false),\n error: z.object({\n error: z.string(),\n statusCode: z.number(),\n errorCode: z.string(),\n }),\n }),\n])\n\nexport type CreatePullRequestResult = z.infer<\n typeof CreatePullRequestResultSchema\n>\n\ninterface CreatePullRequestParams {\n input: CreatePullRequestInput\n baseUrl: string\n headers: Record<string, string>\n}\n\nexport async function createPullRequest({\n input,\n baseUrl,\n headers,\n}: CreatePullRequestParams): Promise<CreatePullRequestResult> {\n const response = await fetch(`${baseUrl}/api/git/pull-request`, {\n method: 'POST',\n headers: {\n ...headers,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(input),\n })\n\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n } catch {\n // Ignore\n }\n throw new Error(\n `Failed to create pull request: ${response.status} ${response.statusText}${errorBody ? `\\n${errorBody}` : ''}`,\n )\n }\n\n return response.json()\n}\n","import * as z from 'zod'\n\nexport const PushToBranchInputSchema = z.object({\n chatId: z.string().min(1),\n})\n\nexport type PushToBranchInput = z.infer<typeof PushToBranchInputSchema>\n\nexport const PushToBranchResultSchema = z.discriminatedUnion('ok', [\n z.object({\n ok: z.literal(true),\n value: z.object({\n pushed: z.literal(true),\n }),\n }),\n z.object({\n ok: z.literal(false),\n error: z.object({\n error: z.string(),\n statusCode: z.number(),\n errorCode: z.string(),\n }),\n }),\n])\n\nexport type PushToBranchResult = z.infer<typeof PushToBranchResultSchema>\n\ninterface PushToBranchParams {\n input: PushToBranchInput\n baseUrl: string\n headers: Record<string, string>\n}\n\nexport async function pushToBranch({\n input,\n baseUrl,\n headers,\n}: PushToBranchParams): Promise<PushToBranchResult> {\n const response = await fetch(`${baseUrl}/api/git/push-to-branch`, {\n method: 'POST',\n headers: {\n ...headers,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(input),\n })\n\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n } catch {\n // Ignore\n }\n throw new Error(\n `Failed to push to branch: ${response.status} ${response.statusText}${errorBody ? `\\n${errorBody}` : ''}`,\n )\n }\n\n return response.json()\n}\n","import * as z from 'zod'\n\nexport const GetDeploymentStatusInputSchema = z.object({\n chatId: z.string().min(1),\n})\n\nexport type GetDeploymentStatusInput = z.infer<\n typeof GetDeploymentStatusInputSchema\n>\n\nexport const DeploymentStatusSchema = z.enum([\n 'QUEUED',\n 'BUILDING',\n 'READY',\n 'ERROR',\n 'CANCELED',\n 'INITIALIZING',\n 'NOTREADY',\n 'NOT_FOUND',\n])\n\nexport type DeploymentStatus = z.infer<typeof DeploymentStatusSchema>\n\nexport const GetDeploymentStatusResultSchema = z.discriminatedUnion('ok', [\n z.object({\n ok: z.literal(true),\n value: z.object({\n status: DeploymentStatusSchema,\n vercelProjectUrl: z.string().nullable(),\n vercelPreviewUrl: z.string().nullable(),\n vercelInspectorUrl: z.string().nullable(),\n }),\n }),\n z.object({\n ok: z.literal(false),\n error: z.object({\n error: z.string(),\n statusCode: z.number(),\n errorCode: z.string(),\n }),\n }),\n])\n\nexport type GetDeploymentStatusResult = z.infer<\n typeof GetDeploymentStatusResultSchema\n>\n\ninterface GetDeploymentStatusParams {\n input: GetDeploymentStatusInput\n baseUrl: string\n headers: Record<string, string>\n}\n\nexport async function getDeploymentStatus({\n input,\n baseUrl,\n headers,\n}: GetDeploymentStatusParams): Promise<GetDeploymentStatusResult> {\n const params = new URLSearchParams({ chatId: input.chatId })\n const response = await fetch(\n `${baseUrl}/api/git/deployment-status?${params.toString()}`,\n {\n method: 'GET',\n headers: {\n ...headers,\n 'Content-Type': 'application/json',\n },\n },\n )\n\n if (!response.ok) {\n let errorBody = ''\n try {\n errorBody = await response.text()\n } catch {\n // Ignore\n }\n throw new Error(\n `Failed to get deployment status: ${response.status} ${response.statusText}${errorBody ? `\\n${errorBody}` : ''}`,\n )\n }\n\n return response.json()\n}\n","import { createChatId } from './routes/chat/create-id'\nimport { createMessageStream } from './routes/chat/create-message'\nimport {\n createPullRequest,\n type CreatePullRequestInput,\n type CreatePullRequestResult,\n} from './routes/chat/create-pull-request'\nimport {\n pushToBranch,\n type PushToBranchInput,\n type PushToBranchResult,\n} from './routes/chat/push-to-branch'\nimport {\n getDeploymentStatus,\n type GetDeploymentStatusInput,\n type GetDeploymentStatusResult,\n} from './routes/chat/get-deployment-status'\nimport type { StreamEvent } from './stream-events'\nimport type {\n ProgrammaticFlags,\n ComposedProgrammaticResult,\n} from './routes/chat/programmatic-tasks'\nimport type { CreateStreamInput } from './schemas'\n\nexport interface V0ClientOptions {\n baseUrl?: string\n token: string | (() => Promise<string> | string)\n headers?: Record<string, string>\n}\n\nexport const createV0Client = ({\n baseUrl = 'https://v0.app',\n token,\n headers: customHeaders,\n}: V0ClientOptions) => {\n const getHeaders = async (): Promise<Record<string, string>> => {\n const resolvedToken = typeof token === 'function' ? await token() : token\n return {\n ...customHeaders,\n Authorization: `Bearer ${resolvedToken}`,\n 'Content-Type': 'application/json',\n }\n }\n\n return {\n message: {\n async *createStream<TFlags extends ProgrammaticFlags>(\n input: CreateStreamInput & TFlags,\n ): AsyncGenerator<StreamEvent<ComposedProgrammaticResult<TFlags>>> {\n const headers = await getHeaders()\n const chatId = input.chatId ?? (await createChatId())\n const isNew = input.isNew || !input.chatId\n\n yield* createMessageStream<TFlags>({\n input: { ...input, chatId, isNew },\n baseUrl,\n headers,\n })\n },\n },\n git: {\n pullRequest: {\n create: async (\n input: CreatePullRequestInput,\n ): Promise<CreatePullRequestResult> => {\n const headers = await getHeaders()\n return createPullRequest({\n input,\n baseUrl,\n headers,\n })\n },\n },\n branch: {\n push: async (input: PushToBranchInput): Promise<PushToBranchResult> => {\n const headers = await getHeaders()\n return pushToBranch({\n input,\n baseUrl,\n headers,\n })\n },\n },\n deploymentStatus: {\n get: async (\n input: GetDeploymentStatusInput,\n ): Promise<GetDeploymentStatusResult> => {\n const headers = await getHeaders()\n return getDeploymentStatus({\n input,\n baseUrl,\n headers,\n })\n },\n },\n },\n }\n}\n\nexport type { StreamEvent } from './stream-events'\nexport type {\n ProgrammaticFlags,\n ComposedProgrammaticResult,\n} from './routes/chat/programmatic-tasks'\nexport type {\n CreateStreamInput,\n RemoteConfig,\n SandboxConfig,\n MCPTool,\n} from './schemas'\nexport type {\n CreatePullRequestInput,\n CreatePullRequestResult,\n} from './routes/chat/create-pull-request'\nexport type {\n PushToBranchInput,\n PushToBranchResult,\n} from './routes/chat/push-to-branch'\nexport type {\n GetDeploymentStatusInput,\n GetDeploymentStatusResult,\n DeploymentStatus,\n} from './routes/chat/get-deployment-status'\n"]}