@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
3 lines (2 loc) • 5.33 kB
JavaScript
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 = () => {}; } }
var forcedToolChoiceRefusals=new Set;function isRecord(value){return typeof value=="object"&&value!==null}function extractHttpStatus(error){if(!isRecord(error))return;let status=error.status;if(typeof status=="number")return status;let response=error.response;if(isRecord(response)&&typeof response.status=="number")return response.status}function errorMessage(error){return error instanceof Error?error.message:typeof error=="string"?error:String(error)}var IN_BAND_BEFORE_CONTENT=Symbol.for("senpi.forcedToolChoice.inBandBeforeContent");function isInBandBeforeContent(error){return isRecord(error)&&error[IN_BAND_BEFORE_CONTENT]===!0}function markInBandBeforeContent(error){let marked=isRecord(error)?error:new Error(errorMessage(error));try{Object.defineProperty(marked,IN_BAND_BEFORE_CONTENT,{value:!0})}catch{}return marked}function isRequestRefusal(error){let status=extractHttpStatus(error);return status===400||status===void 0&&isInBandBeforeContent(error)}async function primeStreamUntilContent(stream,hasContent,maxBuffered=64){let iterator=stream[Symbol.asyncIterator](),buffered=[],ended=!1;try{for(;buffered.length<maxBuffered;){let next=await iterator.next();if(next.done){ended=!0;break}if(buffered.push(next.value),hasContent(next.value))break}}catch(error){throw markInBandBeforeContent(error)}return{async*[Symbol.asyncIterator](){try{if(yield*buffered,ended)return;for(;;){let next=await iterator.next();if(next.done)return;yield next.value}}finally{ended||await iterator.return?.()}}}}function isForcedToolChoiceUnsupportedError(error,sentForcedToolChoice){if(!sentForcedToolChoice||!isRequestRefusal(error))return!1;let message=errorMessage(error);return/tool[_\s-]?choices?\b.*?(not\s+(?:currently\s+)?compatible|incompatible|not\s+(?:currently\s+)?supported|unsupported)/is.test(message)||/forces?\s+tool\s+use.*?(not\s+(?:currently\s+)?compatible|incompatible|not\s+(?:currently\s+)?supported|unsupported)/is.test(message)||/does\s+not\s+support\s+(?:forced|this|the)\s+tool[_\s-]?choices?/is.test(message)||/\bonly\s+[`"]*auto(?:matic)?[`"]*\s.{0,40}?tool[_\s-]?choice/is.test(message)||/thinking\s+may\s+not\s+be\s+enabled\s+when\s+tool[_\s-]?choice\s+forces\s+tool\s+use/is.test(message)||/tool[_\s-]?choice\s+cannot\s+force\s+tool\s+use/is.test(message)}function forcedToolName(toolChoice){if(!isRecord(toolChoice))return;let named=isRecord(toolChoice.function)?toolChoice.function.name:toolChoice.name;return typeof named=="string"&&named.length>0?named:void 0}function toolNames(tools){return Array.isArray(tools)?tools.map(tool=>{if(!isRecord(tool))return;let named=isRecord(tool.function)?tool.function.name:tool.name;return typeof named=="string"?named:void 0}):[]}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function refusalNamesForcedTool(error,params){if(!isRequestRefusal(error))return!1;let name=forcedToolName(params.tool_choice);if(name===void 0)return!1;let message=errorMessage(error),index=toolNames(params.tools).indexOf(name);return index>=0&&new RegExp(`\\btools(?:\\.${index}|\\[${index}\\])(?!\\d)`).test(message)?!0:new RegExp(`['"\`]${escapeRegExp(name)}['"\`]`).test(message)}function omitToolChoiceParam(params){let nextParams={...params};return delete nextParams.tool_choice,nextParams}function refusalKey(target){return JSON.stringify([target.api,target.provider,target.baseUrl,target.id])}function hasRefusedForcedToolChoice(target){return forcedToolChoiceRefusals.has(refusalKey(target))}async function sendWithForcedToolChoiceFallback(request){let forced=request.isForced(request.params.tool_choice);if(forced&&(!request.acceptsForcedToolChoice||hasRefusedForcedToolChoice(request.target))){let params=omitToolChoiceParam(request.params);return{params,result:await request.send(params)}}try{return{params:request.params,result:await request.send(request.params)}}catch(error){if(!isForcedToolChoiceUnsupportedError(error,forced)&&!(forced&&refusalNamesForcedTool(error,request.params)))throw error;let params=omitToolChoiceParam(request.params),result=await request.send(params);return/thinking/i.test(errorMessage(error))||forcedToolChoiceRefusals.add(refusalKey(request.target)),{params,result}}}var GITHUB_COPILOT_REJECTED_TOKEN_STATUSES=[401,403];function inferCopilotInitiator(messages){let last=messages[messages.length-1];return last&&last.role!=="user"?"agent":"user"}function hasCopilotVisionInput(messages){return messages.some(msg=>msg.role==="user"&&Array.isArray(msg.content)?msg.content.some(c=>c.type==="image"):msg.role==="toolResult"&&Array.isArray(msg.content)?msg.content.some(c=>c.type==="image"):!1)}function buildCopilotDynamicHeaders(params){let headers={"X-Initiator":inferCopilotInitiator(params.messages),"Openai-Intent":"conversation-edits"};return params.hasImages&&(headers["Copilot-Vision-Request"]="true"),headers}export{isRequestRefusal,primeStreamUntilContent,hasRefusedForcedToolChoice,sendWithForcedToolChoiceFallback,GITHUB_COPILOT_REJECTED_TOKEN_STATUSES,hasCopilotVisionInput,buildCopilotDynamicHeaders};