UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

3 lines (2 loc) • 17.6 kB
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 = () => {}; } } import{getCurrentTools,getSystemMessageText}from"./chunk-AFDUWYAX.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"&&regexDefinition.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};