@code-yeongyu/senpi 2026.10.26-1 → 2026.10.26-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/bundle/chunks/{anthropic-messages-M235FJQV.js → anthropic-messages-ODSFJCXR.js} +1 -1
- package/dist/bundle/chunks/{args-FBNJOJSR.js → args-SWKJAYQD.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-YQRTQ7H6.js → azure-openai-responses-REGXS4XO.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/chunk-2XF6W6F6.js +410 -0
- package/dist/bundle/chunks/{chunk-DMFAVE5N.js → chunk-4QVORFQ2.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZXHLH4MW.js → chunk-5W3DTM2J.js} +1 -1
- package/dist/bundle/chunks/{chunk-QREKAXKX.js → chunk-6GAMRAVM.js} +5 -5
- package/dist/bundle/chunks/{chunk-MSHRIZGT.js → chunk-7IZH2KQX.js} +3 -3
- package/dist/bundle/chunks/{chunk-PH3JDRB2.js → chunk-ARSENVDY.js} +1 -1
- package/dist/bundle/chunks/{chunk-5KZH6EYQ.js → chunk-CNDPCYNT.js} +1 -1
- package/dist/bundle/chunks/{chunk-DYWIFF2Q.js → chunk-CYOHFREV.js} +1 -1
- package/dist/bundle/chunks/{chunk-3LPWILUZ.js → chunk-DNDZPKIQ.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZLIVZQDY.js → chunk-EQNUL2WB.js} +1 -1
- package/dist/bundle/chunks/{chunk-5FQMNHXV.js → chunk-ESNSRUW4.js} +1 -1
- package/dist/bundle/chunks/{chunk-LO5MYLGF.js → chunk-FQDARFHT.js} +1 -1
- package/dist/bundle/chunks/{chunk-7KOUQSBX.js → chunk-GPPOPK76.js} +3 -3
- package/dist/bundle/chunks/chunk-I2WFLKZ2.js +5 -0
- package/dist/bundle/chunks/{chunk-I7QWTWVZ.js → chunk-IHKHCWWG.js} +1 -1
- package/dist/bundle/chunks/{chunk-MY4ZD3EW.js → chunk-IY4G44MN.js} +1 -1
- package/dist/bundle/chunks/{chunk-OQ3WDMB3.js → chunk-JH7MVRNJ.js} +1 -1
- package/dist/bundle/chunks/chunk-KBSFTXAT.js +2 -0
- package/dist/bundle/chunks/{chunk-UW6M3EXY.js → chunk-KRO63T4Q.js} +1 -1
- package/dist/bundle/chunks/{chunk-J5FCH7TI.js → chunk-KTDIIF2F.js} +1 -1
- package/dist/bundle/chunks/{chunk-3WP5RFQR.js → chunk-NDNIMC5W.js} +1 -1
- package/dist/bundle/chunks/{chunk-CDQPA4FP.js → chunk-ODRGPC5S.js} +1 -1
- package/dist/bundle/chunks/{chunk-3A3XCLNH.js → chunk-PDG4XWO2.js} +1 -1
- package/dist/bundle/chunks/{chunk-QYFOHFPS.js → chunk-PPECSSWX.js} +1 -1
- package/dist/bundle/chunks/{chunk-5LWUUXMH.js → chunk-PY4ZQHTN.js} +1 -1
- package/dist/bundle/chunks/{chunk-EZP6AYW2.js → chunk-RPW3XQW3.js} +22 -22
- package/dist/bundle/chunks/{chunk-SOXQ42VS.js → chunk-RQ5JTXUC.js} +1 -1
- package/dist/bundle/chunks/{chunk-JFQUWEN7.js → chunk-TQ67PB7U.js} +2 -2
- package/dist/bundle/chunks/{chunk-6U3TBFBA.js → chunk-UJPG4ROT.js} +1 -1
- package/dist/bundle/chunks/{chunk-UDM7VO6O.js → chunk-XM36IFP3.js} +1 -1
- package/dist/bundle/chunks/{chunk-XQ45JMGN.js → chunk-Z6BREXV3.js} +1 -1
- package/dist/bundle/chunks/{chunk-ADQAPDPV.js → chunk-ZP6JJDYV.js} +1 -1
- package/dist/bundle/chunks/{cli-main-55EQA5PS.js → cli-main-Q2GA53XM.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-ZJQGIIRC.js → cloudflare-workers-ai-system-one-WDHT7BBV.js} +1 -1
- package/dist/bundle/chunks/cursor-agent.js +1 -1
- package/dist/bundle/chunks/devin-agent.js +1 -1
- package/dist/bundle/chunks/{dispatch-C2IBP5VV.js → dispatch-5R3TYAYB.js} +3 -3
- package/dist/bundle/chunks/{google-generative-ai-5G4RIQA6.js → google-generative-ai-FHYFXKLA.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-ALD4P27O.js → google-vertex-5DWE5U5K.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-PEIKGCKZ.js → help-fast-path-FETLIF3W.js} +1 -1
- package/dist/bundle/chunks/{host-command-657VCQ34.js → host-command-XEB7SHT3.js} +1 -1
- package/dist/bundle/chunks/{host-session-command-OV5XDOJK.js → host-session-command-FFN52LXJ.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-MLXSYK2H.js → interactive-mode-5DEKY3YW.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-RAE4K2XY.js → mistral-conversations-I2PI7DDF.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-774MACJU.js → multi-session-host-OPR5VBFO.js} +3 -3
- package/dist/bundle/chunks/{openai-codex-responses-3CW4R7TG.js → openai-codex-responses-WSEX6SH7.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-5UIJXQUF.js → openai-completions-YCBHTBSS.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-2BO44MRW.js → openai-responses-GXNSQF4A.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-MZHVCX2S.js → package-manager-cli-W55E3LHP.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-RF6GER4R.js → pi-messages-O6GISIRW.js} +1 -1
- package/dist/bundle/chunks/{role-ETSFSDTS.js → role-SHIZQKK4.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-ZMQB4GPO.js → rotation-stream-2PCZWNKF.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-UJXOIZCW.js → rpc-mode-IDUJTSYS.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-KA7LFFNK.js → schedule-command-B7RRSANU.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-MFWXUR7Z.js → session-control-endpoint-LMZH5JLH.js} +1 -1
- package/dist/bundle/chunks/{session-picker-BP33NRSL.js → session-picker-DTGBOXDR.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +41 -41
- package/dist/bundle/chunks/{typesafe-system-one-GNNZ5O5U.js → typesafe-system-one-XGYJJVSE.js} +1 -1
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/core/agent-session.d.ts +11 -1
- package/dist/core/agent-session.js +19 -2
- package/dist/core/extensions/builtin/compaction/index.js +7 -1
- package/dist/core/extensions/builtin/herdr/index.js +9 -5
- package/dist/core/extensions/builtin/mcp/auth/oauth-issuer.d.ts +6 -0
- package/dist/core/extensions/builtin/mcp/auth/oauth-issuer.js +25 -0
- package/dist/core/extensions/builtin/mcp/auth/oauth-provider.d.ts +3 -3
- package/dist/core/extensions/builtin/mcp/auth/oauth-provider.js +50 -19
- package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.js +4 -3
- package/dist/core/extensions/builtin/mcp/auth/oauth.js +19 -12
- package/dist/core/extensions/builtin/mcp/modern/dispatch.js +1 -0
- package/dist/core/extensions/builtin/mcp/modern/parameter-headers.d.ts +4 -1
- package/dist/core/extensions/builtin/mcp/modern/parameter-headers.js +33 -35
- package/dist/core/extensions/builtin/mcp/modern/request.js +3 -0
- package/dist/core/extensions/builtin/mcp/modern/transport.d.ts +2 -0
- package/dist/core/extensions/builtin/mcp/modern/transport.js +4 -2
- package/dist/core/extensions/builtin/terminal/extension-state.js +2 -1
- package/dist/core/extensions/builtin/vertex-model-garden/auth.d.ts +9 -0
- package/dist/core/extensions/builtin/vertex-model-garden/auth.js +17 -1
- package/dist/core/extensions/builtin/websearch/websearch/providers/google.d.ts +6 -0
- package/dist/core/extensions/builtin/websearch/websearch/providers/google.js +6 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/lifecycle-children.d.ts +3 -1
- package/dist/core/lifecycle-children.js +79 -15
- package/dist/core/lifecycle-record.js +1 -24
- package/dist/core/lifecycle-session-binding.js +2 -1
- package/dist/core/lifecycle-wait-items.d.ts +17 -0
- package/dist/core/lifecycle-wait-items.js +72 -0
- package/dist/core/model-runtime.js +6 -1
- package/dist/core/provider-api-key-auth.d.ts +6 -1
- package/dist/core/provider-api-key-auth.js +11 -4
- package/dist/core/provider-composer.d.ts +8 -1
- package/dist/core/provider-composer.js +7 -3
- package/dist/core/sdk.js +4 -1
- package/dist/core/session-activity.js +2 -0
- package/dist/core/session-lifecycle-types.d.ts +20 -4
- package/dist/core/session-lifecycle.js +35 -4
- package/dist/core/structured-session-lane.d.ts +33 -0
- package/dist/core/structured-session-lane.js +62 -0
- package/dist/core/work-custody-record.d.ts +2 -1
- package/dist/core/work-custody-record.js +2 -0
- package/dist/core/work-obligations.d.ts +1 -1
- package/dist/core/work-obligations.js +8 -2
- package/dist/modes/json-event.d.ts +79 -1
- package/dist/modes/json-event.js +79 -1
- package/dist/modes/rpc/compact-content-index.d.ts +85 -0
- package/dist/modes/rpc/compact-content-index.js +254 -0
- package/dist/modes/rpc/compact-content-store.d.ts +6 -43
- package/dist/modes/rpc/compact-content-store.js +22 -157
- package/dist/modes/rpc/compact-index-pages.d.ts +12 -0
- package/dist/modes/rpc/compact-index-pages.js +31 -0
- package/dist/modes/rpc/compact-session-state.d.ts +11 -39
- package/dist/modes/rpc/compact-session-state.js +17 -26
- package/dist/modes/rpc/compact-spool-dir.d.ts +4 -1
- package/dist/modes/rpc/compact-spool-dir.js +41 -8
- package/dist/modes/rpc/compact-spool-storage.d.ts +53 -0
- package/dist/modes/rpc/compact-spool-storage.js +162 -0
- package/dist/modes/rpc/compact-storage-io.d.ts +2 -1
- package/dist/modes/rpc/compact-storage-io.js +7 -1
- package/dist/modes/rpc/compact-transition.d.ts +41 -0
- package/dist/modes/rpc/compact-transition.js +12 -0
- package/dist/modes/rpc/connection-handler.d.ts +2 -0
- package/dist/modes/rpc/connection-handler.js +12 -6
- package/dist/modes/rpc/host-ensure-start.js +5 -3
- package/dist/modes/rpc/security-presentations.js +2 -1
- package/dist/modes/rpc/session-binding.js +10 -0
- package/dist/modes/rpc/session-event-writer.d.ts +2 -0
- package/dist/modes/rpc/session-event-writer.js +2 -0
- package/dist/modes/rpc/session-record-stream.d.ts +3 -3
- package/dist/modes/rpc/session-record-stream.js +3 -3
- package/dist/modes/rpc/session-structured-lanes.d.ts +12 -0
- package/dist/modes/rpc/session-structured-lanes.js +24 -0
- package/dist/modes/rpc/session-worker-client.js +6 -5
- package/dist/modes/rpc/structured-session-records.d.ts +12 -0
- package/dist/modes/rpc/structured-session-records.js +88 -0
- package/docs/extensions.md +7 -1
- package/docs/rpc.md +17 -2
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-GQJYNFMO.js +0 -2
- package/dist/bundle/chunks/chunk-VICDRG3J.js +0 -410
- package/dist/bundle/chunks/chunk-VL7O5PO4.js +0 -5
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv}from"./chunk-
|
|
2
|
+
import{CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv}from"./chunk-ESNSRUW4.js";import{homedir}from"node:os";try{process.cwd()}catch{let fallback=homedir();process.chdir(fallback),console.error(`the current working directory no longer exists; continuing from ${fallback}`)}import*as nodeModule from"node:module";async function enableStartupCompileCache(){let enable=nodeModule.enableCompileCache;if(typeof enable!="function")return;let args=process.argv.slice(2);if(!isPackageCommandArgv(args)&&args[0]!==CONFIG_COMMAND_ARGV&&(args.includes("--version")||args.includes("-v")))return;let scheduleWatch=!1;if(args[0]===SCHEDULE_COMMAND_ARGV&&args[1]==="run")for(let index=2;index<args.length;index++){let arg=args[index];arg==="--watch"?scheduleWatch=!0:["--exec","--poll-seconds","--timeout-seconds","--concurrency"].includes(arg??"")&&index++}if(!(isPackageCommandArgv(args)||args[0]===HOST_COMMAND_ARGV||args[0]===SCHEDULE_COMMAND_ARGV&&!scheduleWatch)){if(!scheduleWatch&&args.some(arg=>["--help","-h","--export","--list-models","--list-tips"].includes(arg)))try{let{parseArgs}=await import("./args-SWKJAYQD.js"),parsed=parseArgs(args);if(parsed.version||parsed.export||parsed.listModels!==void 0||parsed.listTips||parsed.help&&!(parsed.mode==="rpc"&&parsed.multiSession))return}catch{}try{let result=enable();result.directory!==void 0&&process.env.NODE_COMPILE_CACHE===void 0&&(process.env.NODE_COMPILE_CACHE=result.directory)}catch{}}}export{enableStartupCompileCache};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{getCurrentTools,getSystemMessageText}from"./chunk-ZXHLH4MW.js";function shortHash(str){let h1=3735928559,h2=1103547991;for(let i=0;i<str.length;i++){let ch=str.charCodeAt(i);h1=Math.imul(h1^ch,2654435761),h2=Math.imul(h2^ch,1597334677)}return h1=Math.imul(h1^h1>>>16,2246822507)^Math.imul(h2^h2>>>13,3266489909),h2=Math.imul(h2^h2>>>16,2246822507)^Math.imul(h1^h1>>>13,3266489909),(h2>>>0).toString(36)+(h1>>>0).toString(36)}var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function getGrammarToolInput(toolName,arguments_,inputProperty){let input=arguments_[inputProperty];if(typeof input!="string")throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);return input}function appendGrammarToolInputJsonDelta(buffer,inputProperty,nextInput,close){if(buffer.closed){if(close&&nextInput===buffer.input)return;throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`)}if(!nextInput.startsWith(buffer.input))throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);let inputDelta=nextInput.slice(buffer.input.length);if(!close&&inputDelta.length===0)return;let delta="";return buffer.started||(delta+=`{${JSON.stringify(inputProperty)}:"`,buffer.started=!0),delta+=JSON.stringify(inputDelta).slice(1,-1),buffer.input=nextInput,close&&(delta+='"}',buffer.closed=!0),delta}function inferGrammarInputProperty(tool){let schema=tool.parameters;if(schema.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(schema.required)||schema.required.length!==1||typeof schema.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let inputProperty=schema.required[0];if(!schema.properties?.[inputProperty])throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);if(schema.properties[inputProperty]?.type!=="string")throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);return inputProperty}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(config===!1||config?.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools){let config=tool.constrainedSampling;if(!config||config.type!=="grammar"||!supportsOpenAIGrammarTools)return;let larkDefinition=config.variants.openai_lark,regexDefinition=config.variants.openai_regex,hasLarkDefinition=typeof larkDefinition=="string"&&larkDefinition.trim().length>0,hasRegexDefinition=typeof regexDefinition=="string"&®exDefinition.trim().length>0;if(!hasLarkDefinition&&!hasRegexDefinition)throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:hasLarkDefinition?"lark":"regex",definition:hasLarkDefinition?larkDefinition:regexDefinition,inputProperty:inferGrammarInputProperty(tool)}}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`)}}function createGrammarToolInputProperties(tools,supportsOpenAIGrammarTools){let properties=new Map;for(let tool of tools??[]){let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);grammar&&properties.set(tool.name,grammar.inputProperty)}return properties}function isVideoMimeType(mimeType){return mimeType.toLowerCase().startsWith("video/")}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",NO_VIDEO_USER_PLACEHOLDER="(video omitted: model does not support video input)",NO_VIDEO_TOOL_PLACEHOLDER="(tool video omitted: model does not support video input)";function replaceMediaWithPlaceholder(content,placeholder,matches){if(!content.some(block=>block.type==="image"&&matches(block)))return content;let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"&&matches(block)){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.type==="text"&&block.text===placeholder}return result}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){let supportsImages=model.input.includes("image"),supportsVideo=model.input.includes("video");return supportsImages&&supportsVideo?messages:messages.map(msg=>{if(msg.role==="user"&&Array.isArray(msg.content)){let content=msg.content;return supportsVideo||(content=replaceMediaWithPlaceholder(content,NO_VIDEO_USER_PLACEHOLDER,b=>isVideoMimeType(b.mimeType))),supportsImages||(content=replaceImagesWithPlaceholder(content,NON_VISION_USER_IMAGE_PLACEHOLDER)),{...msg,content}}if(msg.role==="toolResult"){let content=msg.content;return supportsVideo||(content=replaceMediaWithPlaceholder(content,NO_VIDEO_TOOL_PLACEHOLDER,b=>isVideoMimeType(b.mimeType))),supportsImages||(content=replaceImagesWithPlaceholder(content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)),{...msg,content}}return msg})}function transformMessages(messages,model,normalizeToolCallId,options={}){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),imageAwareMessages=downgradeUnsupportedImages(normalizedMessages,model),preserveThinking=options.preserveThinking??!0,preserveTextSignatures=options.preserveTextSignatures??!1,preserveUnsignedThinking=options.preserveUnsignedThinking??!1,normalizeSameModelToolCallIds=options.normalizeSameModelToolCallIds??!1,transformed=imageAwareMessages.map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,hasToolCalls=assistantMsg.content.some(block=>block.type==="toolCall"),preserveProviderState=preserveThinking||hasToolCalls,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking"){if(block.redacted)return isSameModel?{...block}:[];let hasUsableSignature=typeof block.thinkingSignature=="string"&&block.thinkingSignature.trim().length>0;return isSameModel&&hasUsableSignature&&(preserveProviderState||block.thinking.trim()==="")?{...block}:!block.thinking||block.thinking.trim()===""?[]:isSameModel?preserveProviderState||preserveUnsignedThinking&&!hasUsableSignature?{...block}:[]:{type:"text",text:block.thinking}}if(block.type==="text")return isSameModel&&(preserveProviderState||preserveTextSignatures)?{...block}:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall={...toolCall};if((!isSameModel||!preserveProviderState)&&toolCall.thoughtSignature&&delete normalizedToolCall.thoughtSignature,(!isSameModel||normalizeSameModelToolCallIds)&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],toolResultsById=new Map,nextToolCallIndexById=new Map,droppedCallIds=new Set;for(let sourceIndex=0;sourceIndex<transformed.length;sourceIndex++){let message=transformed[sourceIndex];if(message.role==="toolResult"){let entries=toolResultsById.get(message.toolCallId)??[];entries.push({message,sourceIndex,consumed:!1}),toolResultsById.set(message.toolCallId,entries);continue}if(message.role==="assistant"){if(message.stopReason==="error"||message.stopReason==="aborted"){for(let block of message.content)block.type==="toolCall"&&droppedCallIds.add(block.id);continue}for(let block of message.content){if(block.type!=="toolCall")continue;let indexes=nextToolCallIndexById.get(block.id)??[];indexes.push(sourceIndex),nextToolCallIndexById.set(block.id,indexes)}}}for(let sourceIndex=0;sourceIndex<transformed.length;sourceIndex++){let message=transformed[sourceIndex];if(message.role==="toolResult"){toolResultsById.get(message.toolCallId)?.find(candidate=>candidate.sourceIndex===sourceIndex)?.consumed||(!droppedCallIds.has(message.toolCallId)||nextToolCallIndexById.has(message.toolCallId))&&result.push(message);continue}if(message.role!=="assistant"){result.push(message);continue}if(!(message.stopReason==="error"||message.stopReason==="aborted")){result.push(message);for(let block of message.content){if(block.type!=="toolCall")continue;let nextDeclarationIndex=(nextToolCallIndexById.get(block.id)??[]).find(index=>index>sourceIndex)??1/0,matchedResult=toolResultsById.get(block.id)?.find(candidate=>!candidate.consumed&&candidate.sourceIndex>sourceIndex&&candidate.sourceIndex<nextDeclarationIndex);if(matchedResult){matchedResult.consumed=!0,result.push(matchedResult.message);continue}result.push({role:"toolResult",toolCallId:block.id,toolName:block.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()})}}}return result}var CHARS_PER_TOKEN=4,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.contextUsage!==void 0?usage.contextUsage===null?0:usage.contextUsage.input+usage.contextUsage.output:usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);if(message.role==="configurationUpdate")return 0;for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:block.type==="toolCall"?chars+=block.name.length+safeJsonStringify(block.arguments).length:chars+=block.subtype.length+safeJsonStringify(block.raw).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i=0;i<messages.length;i++){let message=messages[i];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=estimateLazilyAddedToolsTokens(messages,usageInfo.index);for(let i=usageInfo.index+1;i<messages.length;i++)trailingTokens+=estimateMessageTokens(messages[i]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateLazilyAddedToolsTokens(messages,lastUsageIndex){let addedNames=new Set(messages.slice(lastUsageIndex+1).flatMap(message=>message.role==="toolResult"?message.addedToolNames??[]:[]));return addedNames.size===0?0:estimateToolsTokens(getCurrentTools(messages).filter(tool=>addedNames.has(tool.name)))}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify(tools))}export{shortHash,getJsonSchemaToolParameters,getGrammarToolInput,appendGrammarToolInputJsonDelta,resolveJsonSchemaStrictSampling,resolveGrammarConstrainedSampling,createGrammarToolInputProperties,isVideoMimeType,transformMessages,estimateTextTokens,estimateContextTokens};
|
|
2
|
+
import{getCurrentTools,getSystemMessageText}from"./chunk-5W3DTM2J.js";function shortHash(str){let h1=3735928559,h2=1103547991;for(let i=0;i<str.length;i++){let ch=str.charCodeAt(i);h1=Math.imul(h1^ch,2654435761),h2=Math.imul(h2^ch,1597334677)}return h1=Math.imul(h1^h1>>>16,2246822507)^Math.imul(h2^h2>>>13,3266489909),h2=Math.imul(h2^h2>>>16,2246822507)^Math.imul(h1^h1>>>13,3266489909),(h2>>>0).toString(36)+(h1>>>0).toString(36)}var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){if(Array.isArray(schema.items))throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");makeJsonSchemaNodeStrict(schema.items,isUnsupportedKeyword)}let isObjectSchema=schema.type==="object";if(schema.properties!==void 0&&!isObjectSchema)throw new UnsupportedStrictJsonSchemaError("properties require type object");if(!isObjectSchema)return;if(schema.additionalProperties!==void 0&&schema.additionalProperties!==!1)throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");if(schema.properties!==void 0&&!isJsonSchemaObject(schema.properties))throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");if(schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(key=>typeof key!="string")))throw new UnsupportedStrictJsonSchemaError("object required must be a string array");let properties=schema.properties??{},propertyNames=Object.keys(properties),required=new Set(Array.isArray(schema.required)?schema.required:[]);if([...required].some(key=>!propertyNames.includes(key)))throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");for(let[key,property]of Object.entries(properties))makeJsonSchemaNodeStrict(property,isUnsupportedKeyword),!required.has(key)&&!schemaAllowsNull(property)&&(properties[key]={anyOf:[property,{type:"null"}]});schema.required=propertyNames,schema.additionalProperties=!1}function makeStrictJsonSchema(schema,isUnsupportedKeyword){let cloned=structuredClone(schema);if(!isJsonSchemaObject(cloned))throw new UnsupportedStrictJsonSchemaError("root schema must have type object");if(makeJsonSchemaNodeStrict(cloned,isUnsupportedKeyword),cloned.type!=="object")throw new UnsupportedStrictJsonSchemaError("root schema must have type object");return cloned}function getJsonSchemaToolParameters(tool,strict){return strict===!0?makeStrictJsonSchema(tool.parameters):tool.parameters}function getGrammarToolInput(toolName,arguments_,inputProperty){let input=arguments_[inputProperty];if(typeof input!="string")throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);return input}function appendGrammarToolInputJsonDelta(buffer,inputProperty,nextInput,close){if(buffer.closed){if(close&&nextInput===buffer.input)return;throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`)}if(!nextInput.startsWith(buffer.input))throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);let inputDelta=nextInput.slice(buffer.input.length);if(!close&&inputDelta.length===0)return;let delta="";return buffer.started||(delta+=`{${JSON.stringify(inputProperty)}:"`,buffer.started=!0),delta+=JSON.stringify(inputDelta).slice(1,-1),buffer.input=nextInput,close&&(delta+='"}',buffer.closed=!0),delta}function inferGrammarInputProperty(tool){let schema=tool.parameters;if(schema.type!=="object")throw new Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(schema.required)||schema.required.length!==1||typeof schema.required[0]!="string")throw new Error("grammar constrained sampling requires exactly one required string property");let inputProperty=schema.required[0];if(!schema.properties?.[inputProperty])throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);if(schema.properties[inputProperty]?.type!=="string")throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);return inputProperty}function resolveJsonSchemaStrictSampling(tool,supportsStrictMode,isUnsupportedKeyword){let config=tool.constrainedSampling;if(!(config===!1||config?.type!=="json_schema")){if(supportsStrictMode)try{return makeStrictJsonSchema(tool.parameters,isUnsupportedKeyword),!0}catch(error){if(!(error instanceof UnsupportedStrictJsonSchemaError))throw error;if(config.strict!=="require")return;throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`)}if(config.strict==="require")throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools){let config=tool.constrainedSampling;if(!config||config.type!=="grammar"||!supportsOpenAIGrammarTools)return;let larkDefinition=config.variants.openai_lark,regexDefinition=config.variants.openai_regex,hasLarkDefinition=typeof larkDefinition=="string"&&larkDefinition.trim().length>0,hasRegexDefinition=typeof regexDefinition=="string"&®exDefinition.trim().length>0;if(!hasLarkDefinition&&!hasRegexDefinition)throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:hasLarkDefinition?"lark":"regex",definition:hasLarkDefinition?larkDefinition:regexDefinition,inputProperty:inferGrammarInputProperty(tool)}}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`)}}function createGrammarToolInputProperties(tools,supportsOpenAIGrammarTools){let properties=new Map;for(let tool of tools??[]){let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);grammar&&properties.set(tool.name,grammar.inputProperty)}return properties}function isVideoMimeType(mimeType){return mimeType.toLowerCase().startsWith("video/")}var NON_VISION_USER_IMAGE_PLACEHOLDER="(image omitted: model does not support images)",NON_VISION_TOOL_IMAGE_PLACEHOLDER="(tool image omitted: model does not support images)",NO_VIDEO_USER_PLACEHOLDER="(video omitted: model does not support video input)",NO_VIDEO_TOOL_PLACEHOLDER="(tool video omitted: model does not support video input)";function replaceMediaWithPlaceholder(content,placeholder,matches){if(!content.some(block=>block.type==="image"&&matches(block)))return content;let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"&&matches(block)){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.type==="text"&&block.text===placeholder}return result}function replaceImagesWithPlaceholder(content,placeholder){let result=[],previousWasPlaceholder=!1;for(let block of content){if(block.type==="image"){previousWasPlaceholder||result.push({type:"text",text:placeholder}),previousWasPlaceholder=!0;continue}result.push(block),previousWasPlaceholder=block.text===placeholder}return result}function downgradeUnsupportedImages(messages,model){let supportsImages=model.input.includes("image"),supportsVideo=model.input.includes("video");return supportsImages&&supportsVideo?messages:messages.map(msg=>{if(msg.role==="user"&&Array.isArray(msg.content)){let content=msg.content;return supportsVideo||(content=replaceMediaWithPlaceholder(content,NO_VIDEO_USER_PLACEHOLDER,b=>isVideoMimeType(b.mimeType))),supportsImages||(content=replaceImagesWithPlaceholder(content,NON_VISION_USER_IMAGE_PLACEHOLDER)),{...msg,content}}if(msg.role==="toolResult"){let content=msg.content;return supportsVideo||(content=replaceMediaWithPlaceholder(content,NO_VIDEO_TOOL_PLACEHOLDER,b=>isVideoMimeType(b.mimeType))),supportsImages||(content=replaceImagesWithPlaceholder(content,NON_VISION_TOOL_IMAGE_PLACEHOLDER)),{...msg,content}}return msg})}function transformMessages(messages,model,normalizeToolCallId,options={}){let toolCallIdMap=new Map,normalizedMessages=messages.map(msg=>msg.content==null?{...msg,content:[]}:msg),imageAwareMessages=downgradeUnsupportedImages(normalizedMessages,model),preserveThinking=options.preserveThinking??!0,preserveTextSignatures=options.preserveTextSignatures??!1,preserveUnsignedThinking=options.preserveUnsignedThinking??!1,normalizeSameModelToolCallIds=options.normalizeSameModelToolCallIds??!1,transformed=imageAwareMessages.map(msg=>{if(msg.role==="system"||msg.role==="user")return msg;if(msg.role==="toolResult"){let normalizedId=toolCallIdMap.get(msg.toolCallId);return normalizedId&&normalizedId!==msg.toolCallId?{...msg,toolCallId:normalizedId}:msg}if(msg.role==="assistant"){let assistantMsg=msg,isSameModel=assistantMsg.provider===model.provider&&assistantMsg.api===model.api&&assistantMsg.model===model.id,hasToolCalls=assistantMsg.content.some(block=>block.type==="toolCall"),preserveProviderState=preserveThinking||hasToolCalls,transformedContent=assistantMsg.content.flatMap(block=>{if(block.type==="thinking"){if(block.redacted)return isSameModel?{...block}:[];let hasUsableSignature=typeof block.thinkingSignature=="string"&&block.thinkingSignature.trim().length>0;return isSameModel&&hasUsableSignature&&(preserveProviderState||block.thinking.trim()==="")?{...block}:!block.thinking||block.thinking.trim()===""?[]:isSameModel?preserveProviderState||preserveUnsignedThinking&&!hasUsableSignature?{...block}:[]:{type:"text",text:block.thinking}}if(block.type==="text")return isSameModel&&(preserveProviderState||preserveTextSignatures)?{...block}:{type:"text",text:block.text};if(block.type==="toolCall"){let toolCall=block,normalizedToolCall={...toolCall};if((!isSameModel||!preserveProviderState)&&toolCall.thoughtSignature&&delete normalizedToolCall.thoughtSignature,(!isSameModel||normalizeSameModelToolCallIds)&&normalizeToolCallId){let normalizedId=normalizeToolCallId(toolCall.id,model,assistantMsg);normalizedId!==toolCall.id&&(toolCallIdMap.set(toolCall.id,normalizedId),normalizedToolCall={...normalizedToolCall,id:normalizedId})}return normalizedToolCall}return block});return{...assistantMsg,content:transformedContent}}return msg}),result=[],toolResultsById=new Map,nextToolCallIndexById=new Map,droppedCallIds=new Set;for(let sourceIndex=0;sourceIndex<transformed.length;sourceIndex++){let message=transformed[sourceIndex];if(message.role==="toolResult"){let entries=toolResultsById.get(message.toolCallId)??[];entries.push({message,sourceIndex,consumed:!1}),toolResultsById.set(message.toolCallId,entries);continue}if(message.role==="assistant"){if(message.stopReason==="error"||message.stopReason==="aborted"){for(let block of message.content)block.type==="toolCall"&&droppedCallIds.add(block.id);continue}for(let block of message.content){if(block.type!=="toolCall")continue;let indexes=nextToolCallIndexById.get(block.id)??[];indexes.push(sourceIndex),nextToolCallIndexById.set(block.id,indexes)}}}for(let sourceIndex=0;sourceIndex<transformed.length;sourceIndex++){let message=transformed[sourceIndex];if(message.role==="toolResult"){toolResultsById.get(message.toolCallId)?.find(candidate=>candidate.sourceIndex===sourceIndex)?.consumed||(!droppedCallIds.has(message.toolCallId)||nextToolCallIndexById.has(message.toolCallId))&&result.push(message);continue}if(message.role!=="assistant"){result.push(message);continue}if(!(message.stopReason==="error"||message.stopReason==="aborted")){result.push(message);for(let block of message.content){if(block.type!=="toolCall")continue;let nextDeclarationIndex=(nextToolCallIndexById.get(block.id)??[]).find(index=>index>sourceIndex)??1/0,matchedResult=toolResultsById.get(block.id)?.find(candidate=>!candidate.consumed&&candidate.sourceIndex>sourceIndex&&candidate.sourceIndex<nextDeclarationIndex);if(matchedResult){matchedResult.consumed=!0,result.push(matchedResult.message);continue}result.push({role:"toolResult",toolCallId:block.id,toolName:block.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()})}}}return result}var CHARS_PER_TOKEN=4,ESTIMATED_IMAGE_CHARS=4800;function calculateContextTokens(usage){return usage.contextUsage!==void 0?usage.contextUsage===null?0:usage.contextUsage.input+usage.contextUsage.output:usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function safeJsonStringify(value){try{return JSON.stringify(value)??"undefined"}catch{return"[unserializable]"}}function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)chars+=block.type==="text"?block.text.length:ESTIMATED_IMAGE_CHARS;return chars}function estimateTextTokens(text){return Math.ceil(text.length/CHARS_PER_TOKEN)}function estimateTextAndImageContentTokens(content){return Math.ceil(estimateTextAndImageContentChars(content)/CHARS_PER_TOKEN)}function estimateMessageTokens(message){let chars=0;if(message.role==="system")return estimateTextTokens(getSystemMessageText(message))+estimateToolsTokens(message.toolsAdded)+estimateToolsTokens(message.toolsRemoved);if(message.role==="user"||message.role==="toolResult")return estimateTextAndImageContentTokens(message.content);if(message.role==="configurationUpdate")return 0;for(let block of message.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:block.type==="toolCall"?chars+=block.name.length+safeJsonStringify(block.arguments).length:chars+=block.subtype.length+safeJsonStringify(block.raw).length;return Math.ceil(chars/CHARS_PER_TOKEN)}function getLastAssistantUsageInfo(messages){let latestPrefixTimestamp=Number.NEGATIVE_INFINITY,usageInfo;for(let i=0;i<messages.length;i++){let message=messages[i];if(message.role==="assistant"){let assistant=message;assistant.timestamp>=latestPrefixTimestamp&&assistant.stopReason!=="aborted"&&assistant.stopReason!=="error"&&calculateContextTokens(assistant.usage)>0&&(usageInfo={usage:assistant.usage,index:i})}latestPrefixTimestamp=Math.max(latestPrefixTimestamp,message.timestamp)}return usageInfo}function estimateContextTokens(context){let messages="messages"in context?context.messages:context,usageInfo=getLastAssistantUsageInfo(messages);if(usageInfo){let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=estimateLazilyAddedToolsTokens(messages,usageInfo.index);for(let i=usageInfo.index+1;i<messages.length;i++)trailingTokens+=estimateMessageTokens(messages[i]);return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}let tokens=0;for(let message of messages)tokens+=estimateMessageTokens(message);return{tokens,usageTokens:0,trailingTokens:tokens,lastUsageIndex:null}}function estimateLazilyAddedToolsTokens(messages,lastUsageIndex){let addedNames=new Set(messages.slice(lastUsageIndex+1).flatMap(message=>message.role==="toolResult"?message.addedToolNames??[]:[]));return addedNames.size===0?0:estimateToolsTokens(getCurrentTools(messages).filter(tool=>addedNames.has(tool.name)))}function estimateToolsTokens(tools){return!tools||tools.length===0?0:estimateTextTokens(safeJsonStringify(tools))}export{shortHash,getJsonSchemaToolParameters,getGrammarToolInput,appendGrammarToolInputJsonDelta,resolveJsonSchemaStrictSampling,resolveGrammarConstrainedSampling,createGrammarToolInputProperties,isVideoMimeType,transformMessages,estimateTextTokens,estimateContextTokens};
|