@code-yeongyu/senpi 2026.11.13 → 2026.11.15
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 +22 -0
- package/dist/bundle/chunks/{args-H56W53X6.js → args-JWBI5LNO.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-MNN2TINI.js → azure-openai-responses-PEMLRPJ5.js} +1 -1
- package/dist/bundle/chunks/{chunk-HZQHA4PA.js → chunk-3RILB2OD.js} +1 -1
- package/dist/bundle/chunks/{chunk-Y4PFEXFN.js → chunk-5IXYN6DK.js} +1 -1
- package/dist/bundle/chunks/{chunk-BKDXY6EM.js → chunk-5NECOJNK.js} +1 -1
- package/dist/bundle/chunks/{chunk-NI2AOYP6.js → chunk-6MRUNB3Z.js} +1 -1
- package/dist/bundle/chunks/chunk-6QQL3SKM.js +2 -0
- package/dist/bundle/chunks/{chunk-I4N2OIY4.js → chunk-6QXAYNO7.js} +17 -17
- package/dist/bundle/chunks/{chunk-7T2LAWZ4.js → chunk-73HGQTJN.js} +1 -1
- package/dist/bundle/chunks/chunk-75O3CWR5.js +2 -0
- package/dist/bundle/chunks/{chunk-AZ27TE3H.js → chunk-7BX3JQ7F.js} +1 -1
- package/dist/bundle/chunks/{chunk-NDI6N4NJ.js → chunk-7CXLNKEH.js} +1 -1
- package/dist/bundle/chunks/{chunk-E6ZBTSC6.js → chunk-A3LGSX7Z.js} +1 -1
- package/dist/bundle/chunks/{chunk-7GD2EO6T.js → chunk-FYVQEZYN.js} +1 -1
- package/dist/bundle/chunks/{chunk-U4FAWC6C.js → chunk-GXPH7RN6.js} +1 -1
- package/dist/bundle/chunks/{chunk-SFACYIB6.js → chunk-IK3S2NDB.js} +1 -1
- package/dist/bundle/chunks/{chunk-V4VDIV3U.js → chunk-PWA75RQU.js} +1 -1
- package/dist/bundle/chunks/{chunk-IREUIMFE.js → chunk-PWTXZXHH.js} +1 -1
- package/dist/bundle/chunks/{chunk-KKB3K5CV.js → chunk-Q4RJ4WLE.js} +1 -1
- package/dist/bundle/chunks/chunk-QVG5SUSV.js +2 -0
- package/dist/bundle/chunks/chunk-RLIY3AUC.js +2 -0
- package/dist/bundle/chunks/{chunk-EQT4WNCW.js → chunk-TACOXP5H.js} +1 -1
- package/dist/bundle/chunks/{chunk-NXGSYUMV.js → chunk-TB6LIKVR.js} +2 -2
- package/dist/bundle/chunks/{chunk-JLCZIEBC.js → chunk-THYIV26N.js} +1 -1
- package/dist/bundle/chunks/{chunk-6FE42M54.js → chunk-VGHGM5PR.js} +1 -1
- package/dist/bundle/chunks/{chunk-CU6HUYL7.js → chunk-WAGFTIT4.js} +1 -1
- package/dist/bundle/chunks/{chunk-UYPH6RHY.js → chunk-Z4PN2MDA.js} +2 -2
- package/dist/bundle/chunks/{chunk-JJYN347Z.js → chunk-ZJUL5ODW.js} +1 -1
- package/dist/bundle/chunks/{cli-main-MY53RXU3.js → cli-main-MM2XCVYE.js} +1 -1
- package/dist/bundle/chunks/credential-accounts-RXZIUKFM.js +2 -0
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{hand-entry-AXTVMVJK.js → hand-entry-MBOPYO6I.js} +1 -1
- package/dist/bundle/chunks/{headless-host-SU5O2KZ2.js → headless-host-OEK6W65T.js} +1 -1
- package/dist/bundle/chunks/{health-write-TN7EXGLI.js → health-write-44JERGEJ.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-TFQ4HJNO.js → help-fast-path-JWHUCE4E.js} +1 -1
- package/dist/bundle/chunks/{host-command-FG56Y53E.js → host-command-O2K2WIPO.js} +1 -1
- package/dist/bundle/chunks/{host-session-command-UFEOW7EP.js → host-session-command-EWA6N4JJ.js} +1 -1
- package/dist/bundle/chunks/interactive-mode-VSZYRVYY.js +2 -0
- package/dist/bundle/chunks/{login-health-XBTIORM4.js → login-health-V4B6LSCP.js} +1 -1
- package/dist/bundle/chunks/main-VEWKRBTD.js +2 -0
- package/dist/bundle/chunks/{multi-session-host-Q6SHI22A.js → multi-session-host-HC6NR5N2.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-VRGOAFEG.js → openai-codex-responses-IFPWK7NG.js} +1 -1
- package/dist/bundle/chunks/openai-responses-2BTL5MA2.js +5 -0
- package/dist/bundle/chunks/{package-manager-cli-LILAWI3Q.js → package-manager-cli-OZ6DK6GI.js} +3 -3
- package/dist/bundle/chunks/{role-KODRTWH5.js → role-BTH5PVME.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-2KNROTYB.js → rotation-stream-ZGPXLY62.js} +1 -1
- package/dist/bundle/chunks/rpc-mode-WPF3NVBL.js +2 -0
- package/dist/bundle/chunks/{run-attached-tui-OEFHV5CZ.js → run-attached-tui-RVVYEINN.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-VO4RP2KX.js → schedule-command-6TAAG2KU.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-CCVRJHSC.js → session-control-endpoint-3FNVOKKT.js} +1 -1
- package/dist/bundle/chunks/{session-picker-VN5I2ZDI.js → session-picker-YDXDCBRL.js} +1 -1
- package/dist/bundle/chunks/session-slot-N4E4OSCX.js +2 -0
- package/dist/bundle/chunks/session-worker.js +22 -21
- package/dist/bundle/chunks/{state-store-7RVODZJU.js → state-store-I6MUHET3.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 +5 -3
- package/dist/core/agent-session.js +16 -6
- package/dist/core/credential-accounts.d.ts +5 -3
- package/dist/core/credential-accounts.js +8 -6
- package/dist/core/credential-pool/classify.js +5 -1
- package/dist/core/extensions/builtin/anthropic-subscription/content-blocks.d.ts +6 -0
- package/dist/core/extensions/builtin/anthropic-subscription/content-blocks.js +14 -0
- package/dist/core/extensions/builtin/anthropic-subscription/prompt-bridge.js +3 -1
- package/dist/core/extensions/builtin/anthropic-subscription/session-sync.js +4 -1
- package/dist/core/extensions/builtin/permission-system/index.js +5 -1
- package/dist/core/reasoning-baseline.d.ts +8 -1
- package/dist/core/reasoning-baseline.js +24 -0
- package/dist/modes/rpc/connection-handler.js +4 -0
- package/dist/modes/rpc/method-classes-schema-session.d.ts +3 -0
- package/dist/modes/rpc/method-classes-schema-session.js +6 -2
- package/dist/modes/rpc/method-classes-schema.d.ts +3 -0
- package/dist/modes/rpc/project-expected-cwd.d.ts +29 -0
- package/dist/modes/rpc/project-expected-cwd.js +45 -0
- package/dist/modes/rpc/rpc-error-types.d.ts +7 -1
- package/dist/modes/rpc/rpc-error-types.js +6 -0
- package/dist/modes/rpc/rpc-session-command-types.d.ts +3 -0
- package/dist/package-manager-cli.d.ts +14 -0
- package/dist/package-manager-cli.js +20 -4
- package/dist/utils/version-check.d.ts +10 -7
- package/dist/utils/version-check.js +24 -5
- package/docs/rpc.md +20 -7
- package/package.json +7 -7
- package/dist/bundle/chunks/chunk-GLTOBXZY.js +0 -2
- package/dist/bundle/chunks/chunk-PBUV2Z3R.js +0 -2
- package/dist/bundle/chunks/chunk-WRBOKYPS.js +0 -2
- package/dist/bundle/chunks/credential-accounts-ZB5IXHIG.js +0 -2
- package/dist/bundle/chunks/interactive-mode-PHES47E3.js +0 -2
- package/dist/bundle/chunks/main-PR4FI6HQ.js +0 -2
- package/dist/bundle/chunks/openai-responses-I7PXRWCM.js +0 -4
- package/dist/bundle/chunks/rpc-mode-CGVK4SSA.js +0 -2
- package/dist/bundle/chunks/session-slot-GHJVOSG7.js +0 -2
|
@@ -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{CONTEXT_PROVENANCE_FIELD,contextProvenanceFingerprint,getContextProvenance}from"./chunk-
|
|
2
|
+
import{CONTEXT_PROVENANCE_FIELD,contextProvenanceFingerprint,getContextProvenance}from"./chunk-PWTXZXHH.js";function isUserWord(value){return typeof value=="object"&&value!==null&&"label"in value&&typeof value.label=="string"&&"text"in value&&typeof value.text=="string"}function toolResultUserWords(message){let details=message.details;return typeof details!="object"||details===null||!("userWords"in details)?[]:Array.isArray(details.userWords)?details.userWords.filter(isUserWord):[]}function userWordBlocks(words){return words.flatMap(word=>[{type:"text",text:`[${word.label}]`},{type:"text",text:word.text}])}function appendToolResultUserWords(messages){if(!messages.some(message=>message.role==="toolResult"&&toolResultUserWords(message).length>0))return messages;let result=[],pending=[],source,flush=next=>{source&&!startsWithBlocks(next,pending)&&result.push(wordMessage(pending,source)),pending=[],source=void 0};for(let message of messages){if(message.role!=="toolResult"&&flush(message),result.push(message),message.role!=="toolResult")continue;let blocks=userWordBlocks(toolResultUserWords(message));blocks.length!==0&&(pending.push(...blocks),source=message)}return flush(void 0),result}function wordMessage(content,source){let message={role:"user",content,timestamp:source.timestamp},provenance=getContextProvenance(source);if(!provenance)return message;let{integrity,...owned}=provenance;if(!(integrity===void 0||integrity===contextProvenanceFingerprint(source)))return message;let sealed=integrity===void 0?owned:{...owned,integrity:contextProvenanceFingerprint(message)};return Object.assign(message,{[CONTEXT_PROVENANCE_FIELD]:sealed})}function startsWithBlocks(message,blocks){if(message?.role!=="user"||typeof message.content=="string")return!1;let content=message.content;return blocks.every((block,index)=>{let candidate=content[index];return candidate?.type==="text"&&candidate.text===block.text})}export{toolResultUserWords,userWordBlocks,appendToolResultUserWords};
|
|
@@ -1,5 +1,5 @@
|
|
|
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{BaseContentHash,EventLoopSlicer,TranscriptJournal,blockCallKey,captureAndCloseFileIdentity,captureFileIdentity,captureTranscriptBase,compactUpdatesEnabled,discardFailedFirstFlush,discardFailedFirstFlushAsync,loadEntriesFromFile,loadEntriesFromFileAsync,loadedContentFingerprints,loadedFileIdentities,mapInSlices,parseSessionEntryLine,readForkSource,replaceFileAtomically,sessionRecoveryCause,snapshotTranscript,terminateFinalSessionLine,truncateToLastCompleteLine}from"./chunk-WMDJMN5W.js";import{parseEntryLine,resolveMovedPath,sessionInfoName,visibleMessage}from"./chunk-GTJJ73DE.js";import{appendToolResultUserWords}from"./chunk-
|
|
2
|
+
import{BaseContentHash,EventLoopSlicer,TranscriptJournal,blockCallKey,captureAndCloseFileIdentity,captureFileIdentity,captureTranscriptBase,compactUpdatesEnabled,discardFailedFirstFlush,discardFailedFirstFlushAsync,loadEntriesFromFile,loadEntriesFromFileAsync,loadedContentFingerprints,loadedFileIdentities,mapInSlices,parseSessionEntryLine,readForkSource,replaceFileAtomically,sessionRecoveryCause,snapshotTranscript,terminateFinalSessionLine,truncateToLastCompleteLine}from"./chunk-WMDJMN5W.js";import{parseEntryLine,resolveMovedPath,sessionInfoName,visibleMessage}from"./chunk-GTJJ73DE.js";import{appendToolResultUserWords}from"./chunk-A3LGSX7Z.js";import{SessionWriteFence}from"./chunk-SOMFLLPD.js";import{appendRecordWrites,createAdmissionLine,divergenceWrite,manifestWrite,openSessionStore,openSyncSessionStore,readSessionState,rewriteRecordWrite}from"./chunk-7CXLNKEH.js";import{dropFailedAssistantTurns}from"./chunk-IK3S2NDB.js";import{hasFunctions,realmRegistry}from"./chunk-XDEZA6U6.js";import{copyContextProvenance}from"./chunk-PWTXZXHH.js";import{getCurrentSystemMessage,isModelType,lazyStream,normalizeProviderId}from"./chunk-OH5TKHW7.js";import{APP_NAME,getAgentDir,getSessionsDir,normalizePath,resolvePath}from"./chunk-SODMQEHO.js";var VIRTUAL_MODEL_API="pi-virtual",VIRTUAL_MODEL_STATE_ENTRY="pi.virtual-model-state",THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isVirtualModel(model){return model.api===VIRTUAL_MODEL_API}function findLatestResponse(messages){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(message.role==="assistant"&&message.stopReason!=="error"&&message.stopReason!=="aborted")return message}}function getBranchSelection(branch,getModel){for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId};if(entry.type==="message"&&entry.message.role==="assistant"&&!isVirtualModel(entry.message)){let response={provider:entry.message.provider,modelId:entry.message.model},change=findLastModelChange(branch,i),model=change&&getModel(change.provider,change.modelId);return change&&model&&isVirtualModel(model)?change:response}}}function findLastModelChange(branch,before){for(let i=before-1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId}}}function getVirtualModelState(branch,provider,modelId){for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type!=="custom"||entry.customType!==VIRTUAL_MODEL_STATE_ENTRY)continue;let data=entry.data;if(data?.provider===provider&&data.modelId===modelId)return data.state}}function createVirtualModel(definition){let levels=definition.thinkingLevels??["off"],thinkingLevelMap={};for(let level of THINKING_LEVELS)thinkingLevelMap[level]=levels.includes(level)?level:null;return{id:definition.id,name:definition.name,api:VIRTUAL_MODEL_API,provider:definition.provider,baseUrl:"",reasoning:levels.some(level=>level!=="off"),thinkingLevelMap,input:definition.input??["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:definition.contextWindow??0,maxTokens:definition.maxTokens??0}}function unroutedStream(model){return lazyStream(model,async()=>{throw new Error(`Virtual model ${model.provider}/${model.id} must be routed before streaming`)})}function withVirtualModels(providerId,provider,virtualModels){if(!provider)return{id:providerId,name:providerId,auth:{apiKey:{name:"Virtual model",resolve:async()=>({auth:{},source:"virtual"})}},getModels:()=>virtualModels,stream:unroutedStream,streamSimple:unroutedStream};let ids=new Set(virtualModels.map(model=>model.id)),physical=models=>models.filter(model=>!isVirtualModel(model)&&!(isModelType(model,"chat")&&ids.has(model.id))),virtual=models=>models.filter(model=>isVirtualModel(model)),{filterModels,filterAllModels}=provider;return{...provider,getModels:()=>[...physical(provider.getModels()),...virtualModels],getAllModels:()=>[...physical(provider.getAllModels?.()??provider.getModels()),...virtualModels],filterModels:(models,credential)=>{let real=physical(models);return[...filterModels?.(real,credential)??real,...virtual(models)]},filterAllModels:filterAllModels&&((models,credential)=>[...filterAllModels(physical(models),credential),...virtual(models)]),stream:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.stream(model,context,options),streamSimple:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.streamSimple(model,context,options)}}var ENVIRONMENT_CONTEXT_MESSAGE_TYPE="environment-context",CURRENT_DATE_ENV="SENPI_TEST_CURRENT_DATE";function pinnedCurrentDate(){let value=process.env[CURRENT_DATE_ENV];if(value===void 0||value==="")return;let parsed=new Date(`${value}T00:00:00.000Z`);if(!(/^\d{4}-\d{2}-\d{2}$/.test(value)&&!Number.isNaN(parsed.getTime())&&parsed.toISOString().startsWith(value)))throw new Error(`${CURRENT_DATE_ENV} must be a calendar date YYYY-MM-DD, got ${JSON.stringify(value)}`);return value}function resolveEnvironmentContext(cwd,now=new Date){return{cwd:cwd.replace(/\\/g,"/"),currentDate:pinnedCurrentDate()??now.toISOString().slice(0,10)}}function formatEnvironmentContext(context){return["<environment_context>",` <cwd>${context.cwd}</cwd>`,` <current_date>${context.currentDate}</current_date>`,"</environment_context>"].join(`
|
|
3
3
|
`)}function isEnvironmentContext(value){if(typeof value!="object"||value===null)return!1;let candidate=value;return typeof candidate.cwd=="string"&&typeof candidate.currentDate=="string"}function latestEnvironmentContext(messages){for(let index=messages.length-1;index>=0;index--){let message=messages[index];if(message.role==="custom"&&message.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&isEnvironmentContext(message.details))return message.details}}function createEnvironmentContextMessage(context,timestamp=Date.now()){return{role:"custom",customType:ENVIRONMENT_CONTEXT_MESSAGE_TYPE,content:formatEnvironmentContext(context),display:!1,details:{cwd:context.cwd,currentDate:context.currentDate},timestamp}}function environmentContextMessageIfChanged(messages,current){let latest=latestEnvironmentContext(messages);if(!(latest?.cwd===current.cwd&&latest.currentDate===current.currentDate))return createEnvironmentContextMessage(current)}function contentBlocks(content){return typeof content=="string"?[{type:"text",text:content}]:content}function foldEnvironmentContextIntoNextUserMessage(messages,environmentMessages){let folded=[];for(let index=0;index<messages.length;index++){let message=messages[index],next=messages[index+1];if(environmentMessages.has(message)&&message.role==="user"&&next?.role==="user"&&!environmentMessages.has(next)){folded.push({...next,content:[...contentBlocks(message.content),...contentBlocks(next.content)]}),index++;continue}folded.push(message)}return folded}import{createHash}from"node:crypto";var IMAGE_ELISION_PLACEHOLDER="[Image elided: an older image was removed to keep the request within the provider's size limit. Re-read the source file if you need to view it again.]",IMAGE_ID_LENGTH=12,ID_SUFFIX=new RegExp(`^ \\(image ids?: ([0-9a-f]{${IMAGE_ID_LENGTH}}(?:, [0-9a-f]{${IMAGE_ID_LENGTH}})*)\\)$`);function imageContentId(data){return createHash("sha256").update(data).digest("hex").slice(0,IMAGE_ID_LENGTH)}function elisionPlaceholder(ids){let label=ids.length===1?"id":"ids";return{type:"text",text:`${IMAGE_ELISION_PLACEHOLDER} (image ${label}: ${ids.join(", ")})`}}function elidedImageIds(text){return text.startsWith(IMAGE_ELISION_PLACEHOLDER)?ID_SUFFIX.exec(text.slice(IMAGE_ELISION_PLACEHOLDER.length))?.[1]?.split(", "):void 0}function replaceElidedImages(content,isElided){let replaced=[],pending=[],flush=()=>{pending.length>0&&replaced.push(elisionPlaceholder(pending)),pending=[]};return content.forEach((block,blockIndex)=>{if(block.type==="image"&&isElided(blockIndex)){pending.push(imageContentId(block.data));return}flush(),replaced.push(block)}),flush(),replaced}var PROVIDER_IMAGE_REJECTION_PATTERN=/does not represent a valid image|image_parse_error|invalid_image|unsupported image|could not process image|unable to process input image|image_url'?\.?[^\n]*invalid base64|expected a base64-encoded data url|image was specified using the image\/[a-z]+ media type|unsupported media type for base64 image|invalid data url for image/i;function isProviderImageRejection(errorMessage){return errorMessage!==void 0&&PROVIDER_IMAGE_REJECTION_PATTERN.test(errorMessage)}function rejectedImagePlaceholder(source){return`[Image omitted: the provider rejected this image (${source}) as invalid, so it is no longer sent with the conversation.]`}function field(message,key){return key in message?message[key]:void 0}function contentBlocks2(message){let content=field(message,"content");return Array.isArray(content)?content:[]}function toolCallSource(block){let args=block.arguments;if(typeof args!="object"||args===null)return;let record=args;for(let key of["path","file_path","filePath"]){let value=record[key];if(typeof value=="string"&&value.trim().length>0)return value}}function imageSource(message,toolCallSources){if(message.role!=="toolResult")return"an attached image";let toolCallId=field(message,"toolCallId"),known=typeof toolCallId=="string"?toolCallSources.get(toolCallId):void 0;if(known)return known;let toolName=field(message,"toolName");return typeof toolName=="string"?`${toolName} tool result`:"a tool result"}function scanRejectedImages(messages){let toolCallSources=new Map,rejections=new Map,unconfirmed=[];return messages.forEach((message,messageIndex)=>{if(message.role==="assistant"){for(let block of contentBlocks2(message)){let source=block.type==="toolCall"?toolCallSource(block):void 0;source&&typeof block.id=="string"&&toolCallSources.set(block.id,source)}let stopReason=field(message,"stopReason"),errorMessage=field(message,"errorMessage");stopReason==="error"&&isProviderImageRejection(typeof errorMessage=="string"?errorMessage:void 0)?(unconfirmed.length>0&&rejections.set(messageIndex,unconfirmed),unconfirmed=[]):stopReason!=="error"&&stopReason!=="aborted"&&(unconfirmed=[]);return}message.role!=="user"&&message.role!=="toolResult"||contentBlocks2(message).forEach((block,blockIndex)=>{block.type==="image"&&unconfirmed.push({messageIndex,blockIndex,source:imageSource(message,toolCallSources)})})}),rejections}function rejectedImageSources(messages,failedTurn){let failedIndex=messages.lastIndexOf(failedTurn);return(scanRejectedImages(messages).get(failedIndex)??[]).map(image=>image.source)}function omitProviderRejectedImages(messages){let rejected=new Map;for(let images of scanRejectedImages(messages).values())for(let image of images){let blocks=rejected.get(image.messageIndex)??new Map;blocks.set(image.blockIndex,image.source),rejected.set(image.messageIndex,blocks)}return rejected.size===0?messages:messages.map((message,messageIndex)=>{let blocks=rejected.get(messageIndex);if(!blocks)return message;let content=contentBlocks2(message).map((block,blockIndex)=>{let source=blocks.get(blockIndex);return source===void 0?block:{type:"text",text:rejectedImagePlaceholder(source)}});return{...message,content}})}var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
|
|
4
4
|
|
|
5
5
|
<summary>
|
|
@@ -1,3 +1,3 @@
|
|
|
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
2
|
import{hasModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{isStaleExtensionContextError}from"./chunk-IHES3JES.js";import{envValue}from"./chunk-SODMQEHO.js";import{format}from"node:util";var OUTPUT_DELIVERY_LIMIT_MS=3e4,nativeLog=console.log,nativeStdoutWrite=process.stdout.write;async function captureStdout(print){if(console.log!==nativeLog||process.stdout.write!==nativeStdoutWrite)return{result:await print(),output:""};let chunks=[];console.log=(...args)=>{chunks.push(`${format(...args)}
|
|
3
|
-
`)},process.stdout.write=((chunk,encodingOrCallback,callback)=>(chunks.push(typeof chunk=="string"?chunk:Buffer.from(chunk).toString()),(typeof encodingOrCallback=="function"?encodingOrCallback:callback)?.(),!0));let printed=!1;try{let result=await print();return printed=!0,{result,output:chunks.join("")}}finally{console.log=nativeLog,process.stdout.write=nativeStdoutWrite,!printed&&chunks.length>0&&process.stdout.write(chunks.join(""))}}function delivered(stream,text){return stream.destroyed||stream.writableEnded?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,OUTPUT_DELIVERY_LIMIT_MS);timer.unref();let done=()=>{clearTimeout(timer),resolve()};stream.once("error",done);try{stream.write(text,done)}catch{done()}})}async function exitAfterOutput(output="",code){await Promise.all([delivered(process.stdout,output),delivered(process.stderr,"")]),process.exit(code)}async function printThenExit(print,code){let{output}=await captureStdout(print);return exitAfterOutput(output,code)}import{close as closeInspector,url as inspectorUrl}from"node:inspector";var VM_DYNAMIC_IMPORT_CALLBACK_MISSING="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING",INSPECTOR_IMPORT_FRAME="at importModuleDynamicallyCallback (node:internal/modules/esm/",INSPECTOR_TIMEOUT_FRAME=/\bat Timeout\._onTimeout \(<anonymous>:\d+:\d+\)/,RECOVER_INSPECTOR_VM_IMPORT=envValue("RECOVER_INSPECTOR_VM_IMPORT")==="1",INSPECTOR_VM_IMPORT_WARNING="Node Inspector dynamic import is unsupported; use require() or a target-side loader. Senpi kept running.";function hasInheritedInspectorOption(){return process.execArgv.some(argument=>argument.startsWith("--inspect"))||process.env.NODE_OPTIONS?.includes("--inspect")===!0}function releaseInheritedInspectorForChild(){inspectorUrl()!==void 0&&hasInheritedInspectorOption()&&closeInspector()}function isRecoverableInspectorVmImportError(error,origin){if(!RECOVER_INSPECTOR_VM_IMPORT||origin!=="unhandledRejection")return!1;try{return inspectorUrl()===void 0||typeof error!="object"||error===null||!("code"in error)||!("stack"in error)?!1:error.code===VM_DYNAMIC_IMPORT_CALLBACK_MISSING&&typeof error.stack=="string"&&error.stack.includes(INSPECTOR_IMPORT_FRAME)&&INSPECTOR_TIMEOUT_FRAME.test(error.stack)}catch{return!1}}var earlyRecoveryCount=0,earlyRecoveryInstalled=!1;function installEarlyInspectorVmImportRecovery(){if(!RECOVER_INSPECTOR_VM_IMPORT||earlyRecoveryInstalled)return;earlyRecoveryInstalled=!0;let listener=(error,origin)=>{let otherHandlerActive=hasModeCrashHandler("uncaughtException");if(isRecoverableInspectorVmImportError(error,origin)){otherHandlerActive||earlyRecoveryCount++;return}otherHandlerActive||isStaleExtensionContextError(error)||(console.error(error),process.exit(1))};process.on("uncaughtException",listener)}function consumeEarlyInspectorVmImportRecoveries(){let count=earlyRecoveryCount;return earlyRecoveryCount=0,count}var PACKAGE_COMMAND_ARGV={install:!0,remove:!0,update:!0,list:!0},PACKAGE_COMMAND_ALIAS="uninstall",CONFIG_COMMAND_ARGV="config",HOST_COMMAND_ARGV="host",SCHEDULE_COMMAND_ARGV="schedule";function isPackageCommandArgv(args){let command=args[0]??"";return Object.hasOwn(PACKAGE_COMMAND_ARGV,command)||command===PACKAGE_COMMAND_ALIAS}async function dispatchPackageCommand(args,runtimeOptions={}){if(!isPackageCommandArgv(args))return!1;let{handlePackageCommand}=await import("./package-manager-cli-
|
|
3
|
+
`)},process.stdout.write=((chunk,encodingOrCallback,callback)=>(chunks.push(typeof chunk=="string"?chunk:Buffer.from(chunk).toString()),(typeof encodingOrCallback=="function"?encodingOrCallback:callback)?.(),!0));let printed=!1;try{let result=await print();return printed=!0,{result,output:chunks.join("")}}finally{console.log=nativeLog,process.stdout.write=nativeStdoutWrite,!printed&&chunks.length>0&&process.stdout.write(chunks.join(""))}}function delivered(stream,text){return stream.destroyed||stream.writableEnded?Promise.resolve():new Promise(resolve=>{let timer=setTimeout(resolve,OUTPUT_DELIVERY_LIMIT_MS);timer.unref();let done=()=>{clearTimeout(timer),resolve()};stream.once("error",done);try{stream.write(text,done)}catch{done()}})}async function exitAfterOutput(output="",code){await Promise.all([delivered(process.stdout,output),delivered(process.stderr,"")]),process.exit(code)}async function printThenExit(print,code){let{output}=await captureStdout(print);return exitAfterOutput(output,code)}import{close as closeInspector,url as inspectorUrl}from"node:inspector";var VM_DYNAMIC_IMPORT_CALLBACK_MISSING="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING",INSPECTOR_IMPORT_FRAME="at importModuleDynamicallyCallback (node:internal/modules/esm/",INSPECTOR_TIMEOUT_FRAME=/\bat Timeout\._onTimeout \(<anonymous>:\d+:\d+\)/,RECOVER_INSPECTOR_VM_IMPORT=envValue("RECOVER_INSPECTOR_VM_IMPORT")==="1",INSPECTOR_VM_IMPORT_WARNING="Node Inspector dynamic import is unsupported; use require() or a target-side loader. Senpi kept running.";function hasInheritedInspectorOption(){return process.execArgv.some(argument=>argument.startsWith("--inspect"))||process.env.NODE_OPTIONS?.includes("--inspect")===!0}function releaseInheritedInspectorForChild(){inspectorUrl()!==void 0&&hasInheritedInspectorOption()&&closeInspector()}function isRecoverableInspectorVmImportError(error,origin){if(!RECOVER_INSPECTOR_VM_IMPORT||origin!=="unhandledRejection")return!1;try{return inspectorUrl()===void 0||typeof error!="object"||error===null||!("code"in error)||!("stack"in error)?!1:error.code===VM_DYNAMIC_IMPORT_CALLBACK_MISSING&&typeof error.stack=="string"&&error.stack.includes(INSPECTOR_IMPORT_FRAME)&&INSPECTOR_TIMEOUT_FRAME.test(error.stack)}catch{return!1}}var earlyRecoveryCount=0,earlyRecoveryInstalled=!1;function installEarlyInspectorVmImportRecovery(){if(!RECOVER_INSPECTOR_VM_IMPORT||earlyRecoveryInstalled)return;earlyRecoveryInstalled=!0;let listener=(error,origin)=>{let otherHandlerActive=hasModeCrashHandler("uncaughtException");if(isRecoverableInspectorVmImportError(error,origin)){otherHandlerActive||earlyRecoveryCount++;return}otherHandlerActive||isStaleExtensionContextError(error)||(console.error(error),process.exit(1))};process.on("uncaughtException",listener)}function consumeEarlyInspectorVmImportRecoveries(){let count=earlyRecoveryCount;return earlyRecoveryCount=0,count}var PACKAGE_COMMAND_ARGV={install:!0,remove:!0,update:!0,list:!0},PACKAGE_COMMAND_ALIAS="uninstall",CONFIG_COMMAND_ARGV="config",HOST_COMMAND_ARGV="host",SCHEDULE_COMMAND_ARGV="schedule";function isPackageCommandArgv(args){let command=args[0]??"";return Object.hasOwn(PACKAGE_COMMAND_ARGV,command)||command===PACKAGE_COMMAND_ALIAS}async function dispatchPackageCommand(args,runtimeOptions={}){if(!isPackageCommandArgv(args))return!1;let{handlePackageCommand}=await import("./package-manager-cli-OZ6DK6GI.js");return await handlePackageCommand(args,runtimeOptions)}async function dispatchConfigCommand(args,runtimeOptions={}){if(args[0]!==CONFIG_COMMAND_ARGV)return!1;let{handleConfigCommand}=await import("./package-manager-cli-OZ6DK6GI.js");return await handleConfigCommand(args,runtimeOptions)}async function dispatchHostCommand(args){if(args[0]!==HOST_COMMAND_ARGV)return;if(args[1]==="session"){let{runHostSessionCommand}=await import("./host-session-command-EWA6N4JJ.js");return await runHostSessionCommand(args.slice(2))}let{runHostCommand}=await import("./host-command-O2K2WIPO.js");return await runHostCommand(args.slice(1))}async function dispatchScheduleCommand(args){if(args[0]!==SCHEDULE_COMMAND_ARGV)return;let{runScheduleCommand}=await import("./schedule-command-6TAAG2KU.js");return await runScheduleCommand(args.slice(1))}export{captureStdout,exitAfterOutput,printThenExit,INSPECTOR_VM_IMPORT_WARNING,hasInheritedInspectorOption,releaseInheritedInspectorForChild,isRecoverableInspectorVmImportError,installEarlyInspectorVmImportRecovery,consumeEarlyInspectorVmImportRecoveries,CONFIG_COMMAND_ARGV,HOST_COMMAND_ARGV,SCHEDULE_COMMAND_ARGV,isPackageCommandArgv,dispatchPackageCommand,dispatchConfigCommand,dispatchHostCommand,dispatchScheduleCommand};
|
|
@@ -1,5 +1,5 @@
|
|
|
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{hasFunctions,realmRegistryLookup}from"./chunk-XDEZA6U6.js";import{isOpenAIResponsesPromptCacheModel}from"./chunk-
|
|
2
|
+
import{hasFunctions,realmRegistryLookup}from"./chunk-XDEZA6U6.js";import{isOpenAIResponsesPromptCacheModel}from"./chunk-PWTXZXHH.js";import{SERVER_FALLBACK_ABORTED_DIAGNOSTIC,parseServerFallbackReceipt,withGzipRequestBodies}from"./chunk-Z6TEQEZO.js";import{getAnthropicCompat,supportsAnthropicCacheWarming}from"./chunk-ZG3MNTNX.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{contentText,createProvider,getCurrentSystemPrompt,getCurrentTools,getInitialSystemMessage,getSystemMessageText,normalizeContext}from"./chunk-OH5TKHW7.js";import{AssistantMessageEventStream,assistantEvents,carryAssistantCapture,createAssistantMessageEventStream,dropAssistantCapture,enableAssistantCapture,getAssistantCapture,pushAssistantProgress,setAssistantReader}from"./chunk-NDNQ23SK.js";import{providerHeadersToRecord}from"./chunk-PJ34QVL5.js";import{Build,Clean,Convert,Create,Decode,Default,DisableParseErrors,EnableParseErrors,Encode,Errors,HasCodec,IsArray,IsBoolean,IsInteger,IsNumber,IsObject,IsString,ParseError,Parser,arguments_exports,settings_exports,typebox_exports,value_exports}from"./chunk-MIENF2YK.js";import{__commonJS,__export,__require,__toESM}from"./chunk-IKOFCODM.js";var require_identity=__commonJS({"node_modules/yaml/dist/nodes/identity.js"(exports){"use strict";var ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE=Symbol.for("yaml.node.type"),isAlias=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===ALIAS,isDocument=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===DOC,isMap=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===MAP,isPair=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===PAIR,isScalar=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SCALAR,isSeq=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SEQ;function isCollection(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return!0}return!1}function isNode(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return!0}return!1}var hasAnchor=node=>(isScalar(node)||isCollection(node))&&!!node.anchor;exports.ALIAS=ALIAS;exports.DOC=DOC;exports.MAP=MAP;exports.NODE_TYPE=NODE_TYPE;exports.PAIR=PAIR;exports.SCALAR=SCALAR;exports.SEQ=SEQ;exports.hasAnchor=hasAnchor;exports.isAlias=isAlias;exports.isCollection=isCollection;exports.isDocument=isDocument;exports.isMap=isMap;exports.isNode=isNode;exports.isPair=isPair;exports.isScalar=isScalar;exports.isSeq=isSeq}});var require_visit=__commonJS({"node_modules/yaml/dist/visit.js"(exports){"use strict";var identity=require_identity(),BREAK=Symbol("break visit"),SKIP=Symbol("skip children"),REMOVE=Symbol("remove node");function visit(node,visitor){let visitor_=initVisitor(visitor);identity.isDocument(node)?visit_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):visit_(null,node,visitor_,Object.freeze([]))}visit.BREAK=BREAK;visit.SKIP=SKIP;visit.REMOVE=REMOVE;function visit_(key,node,visitor,path){let ctrl=callVisitor(key,node,visitor,path);if(identity.isNode(ctrl)||identity.isPair(ctrl))return replaceNode(key,path,ctrl),visit_(key,ctrl,visitor,path);if(typeof ctrl!="symbol"){if(identity.isCollection(node)){path=Object.freeze(path.concat(node));for(let i=0;i<node.items.length;++i){let ci=visit_(i,node.items[i],visitor,path);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity.isPair(node)){path=Object.freeze(path.concat(node));let ck=visit_("key",node.key,visitor,path);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=visit_("value",node.value,visitor,path);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}async function visitAsync(node,visitor){let visitor_=initVisitor(visitor);identity.isDocument(node)?await visitAsync_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):await visitAsync_(null,node,visitor_,Object.freeze([]))}visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path){let ctrl=await callVisitor(key,node,visitor,path);if(identity.isNode(ctrl)||identity.isPair(ctrl))return replaceNode(key,path,ctrl),visitAsync_(key,ctrl,visitor,path);if(typeof ctrl!="symbol"){if(identity.isCollection(node)){path=Object.freeze(path.concat(node));for(let i=0;i<node.items.length;++i){let ci=await visitAsync_(i,node.items[i],visitor,path);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity.isPair(node)){path=Object.freeze(path.concat(node));let ck=await visitAsync_("key",node.key,visitor,path);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=await visitAsync_("value",node.value,visitor,path);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}function initVisitor(visitor){return typeof visitor=="object"&&(visitor.Collection||visitor.Node||visitor.Value)?Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor):visitor}function callVisitor(key,node,visitor,path){if(typeof visitor=="function")return visitor(key,node,path);if(identity.isMap(node))return visitor.Map?.(key,node,path);if(identity.isSeq(node))return visitor.Seq?.(key,node,path);if(identity.isPair(node))return visitor.Pair?.(key,node,path);if(identity.isScalar(node))return visitor.Scalar?.(key,node,path);if(identity.isAlias(node))return visitor.Alias?.(key,node,path)}function replaceNode(key,path,node){let parent=path[path.length-1];if(identity.isCollection(parent))parent.items[key]=node;else if(identity.isPair(parent))key==="key"?parent.key=node:parent.value=node;else if(identity.isDocument(parent))parent.contents=node;else{let pt=identity.isAlias(parent)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt} parent`)}}exports.visit=visit;exports.visitAsync=visitAsync}});var require_directives=__commonJS({"node_modules/yaml/dist/doc/directives.js"(exports){"use strict";var identity=require_identity(),visit=require_visit(),escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]),Directives=class _Directives{constructor(yaml,tags){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,yaml),this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){let copy=new _Directives(this.yaml,this.tags);return copy.docStart=this.docStart,copy}atDocument(){let res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);let parts=line.trim().split(/[ \t]+/),name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2&&(onError(0,"%TAG directive should contain exactly two parts"),parts.length<2))return!1;let[handle,prefix]=parts;return this.tags[handle]=prefix,!0}case"%YAML":{if(this.yaml.explicit=!0,parts.length!==1)return onError(0,"%YAML directive should contain exactly one part"),!1;let[version]=parts;if(version==="1.1"||version==="1.2")return this.yaml.version=version,!0;{let isValid=/^\d+\.\d+$/.test(version);return onError(6,`Unsupported YAML version ${version}`,isValid),!1}}default:return onError(0,`Unknown directive ${name}`,!0),!1}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!")return onError(`Not a valid tag: ${source}`),null;if(source[1]==="<"){let verbatim=source.slice(2,-1);return verbatim==="!"||verbatim==="!!"?(onError(`Verbatim tags aren't resolved, so ${source} is invalid.`),null):(source[source.length-1]!==">"&&onError("Verbatim tags must end with a >"),verbatim)}let[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);suffix||onError(`The ${source} tag has no suffix`);let prefix=this.tags[handle];if(prefix)try{return prefix+decodeURIComponent(suffix)}catch(error){return onError(String(error)),null}return handle==="!"?source:(onError(`Could not resolve tag: ${source}`),null)}tagString(tag){for(let[handle,prefix]of Object.entries(this.tags))if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length));return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){let lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],tagEntries=Object.entries(this.tags),tagNames;if(doc&&tagEntries.length>0&&identity.isNode(doc.contents)){let tags={};visit.visit(doc.contents,(_key,node)=>{identity.isNode(node)&&node.tag&&(tags[node.tag]=!0)}),tagNames=Object.keys(tags)}else tagNames=[];for(let[handle,prefix]of tagEntries)handle==="!!"&&prefix==="tag:yaml.org,2002:"||(!doc||tagNames.some(tn=>tn.startsWith(prefix)))&&lines.push(`%TAG ${handle} ${prefix}`);return lines.join(`
|
|
3
3
|
`)}};Directives.defaultYaml={explicit:!1,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};exports.Directives=Directives}});var require_anchors=__commonJS({"node_modules/yaml/dist/doc/anchors.js"(exports){"use strict";var identity=require_identity(),visit=require_visit();function anchorIsValid(anchor){if(/[\x00-\x19\s,[\]{}]/.test(anchor)){let msg=`Anchor must not contain whitespace or control characters: ${JSON.stringify(anchor)}`;throw new Error(msg)}return!0}function anchorNames(root){let anchors=new Set;return visit.visit(root,{Value(_key,node){node.anchor&&anchors.add(node.anchor)}}),anchors}function findNewAnchor(prefix,exclude){for(let i=1;;++i){let name=`${prefix}${i}`;if(!exclude.has(name))return name}}function createNodeAnchors(doc,prefix){let aliasObjects=[],sourceObjects=new Map,prevAnchors=null;return{onAnchor:source=>{aliasObjects.push(source),prevAnchors??(prevAnchors=anchorNames(doc));let anchor=findNewAnchor(prefix,prevAnchors);return prevAnchors.add(anchor),anchor},setAnchors:()=>{for(let source of aliasObjects){let ref=sourceObjects.get(source);if(typeof ref=="object"&&ref.anchor&&(identity.isScalar(ref.node)||identity.isCollection(ref.node)))ref.node.anchor=ref.anchor;else{let error=new Error("Failed to resolve repeated object (this should not happen)");throw error.source=source,error}}},sourceObjects}}exports.anchorIsValid=anchorIsValid;exports.anchorNames=anchorNames;exports.createNodeAnchors=createNodeAnchors;exports.findNewAnchor=findNewAnchor}});var require_applyReviver=__commonJS({"node_modules/yaml/dist/doc/applyReviver.js"(exports){"use strict";function applyReviver(reviver,obj,key,val){if(val&&typeof val=="object")if(Array.isArray(val))for(let i=0,len=val.length;i<len;++i){let v0=val[i],v1=applyReviver(reviver,val,String(i),v0);v1===void 0?delete val[i]:v1!==v0&&(val[i]=v1)}else if(val instanceof Map)for(let k of Array.from(val.keys())){let v0=val.get(k),v1=applyReviver(reviver,val,k,v0);v1===void 0?val.delete(k):v1!==v0&&val.set(k,v1)}else if(val instanceof Set)for(let v0 of Array.from(val)){let v1=applyReviver(reviver,val,v0,v0);v1===void 0?val.delete(v0):v1!==v0&&(val.delete(v0),val.add(v1))}else for(let[k,v0]of Object.entries(val)){let v1=applyReviver(reviver,val,k,v0);v1===void 0?delete val[k]:v1!==v0&&(val[k]=v1)}return reviver.call(obj,key,val)}exports.applyReviver=applyReviver}});var require_toJS=__commonJS({"node_modules/yaml/dist/nodes/toJS.js"(exports){"use strict";var identity=require_identity();function toJS(value,arg,ctx){if(Array.isArray(value))return value.map((v,i)=>toJS(v,String(i),ctx));if(value&&typeof value.toJSON=="function"){if(!ctx||!identity.hasAnchor(value))return value.toJSON(arg,ctx);let data={aliasCount:0,count:1,res:void 0};ctx.anchors.set(value,data),ctx.onCreate=res2=>{data.res=res2,delete ctx.onCreate};let res=value.toJSON(arg,ctx);return ctx.onCreate&&ctx.onCreate(res),res}return typeof value=="bigint"&&!ctx?.keep?Number(value):value}exports.toJS=toJS}});var require_Node=__commonJS({"node_modules/yaml/dist/nodes/Node.js"(exports){"use strict";var applyReviver=require_applyReviver(),identity=require_identity(),toJS=require_toJS(),NodeBase=class{constructor(type){Object.defineProperty(this,identity.NODE_TYPE,{value:type})}clone(){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(copy.range=this.range.slice()),copy}toJS(doc,{mapAsMap,maxAliasCount,onAnchor,reviver}={}){if(!identity.isDocument(doc))throw new TypeError("A document argument is required");let ctx={anchors:new Map,doc,keep:!0,mapAsMap:mapAsMap===!0,mapKeyWarned:!1,maxAliasCount:typeof maxAliasCount=="number"?maxAliasCount:100},res=toJS.toJS(this,"",ctx);if(typeof onAnchor=="function")for(let{count,res:res2}of ctx.anchors.values())onAnchor(res2,count);return typeof reviver=="function"?applyReviver.applyReviver(reviver,{"":res},"",res):res}};exports.NodeBase=NodeBase}});var require_Alias=__commonJS({"node_modules/yaml/dist/nodes/Alias.js"(exports){"use strict";var anchors=require_anchors(),visit=require_visit(),identity=require_identity(),Node=require_Node(),toJS=require_toJS(),Alias=class extends Node.NodeBase{constructor(source){super(identity.ALIAS),this.source=source,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(doc,ctx){if(ctx?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let nodes;ctx?.aliasResolveCache?nodes=ctx.aliasResolveCache:(nodes=[],visit.visit(doc,{Node:(_key,node)=>{(identity.isAlias(node)||identity.hasAnchor(node))&&nodes.push(node)}}),ctx&&(ctx.aliasResolveCache=nodes));let found;for(let node of nodes){if(node===this)break;node.anchor===this.source&&(found=node)}if(found&&ctx){let{anchors:anchors2,doc:doc2,maxAliasCount}=ctx,data=anchors2.get(found);if(data||(toJS.toJS(found,null,ctx),data=anchors2.get(found)),data?.res===void 0){let msg="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(msg)}if(maxAliasCount>=0&&(data.count+=1,data.aliasCount===0&&(data.aliasCount=getAliasCount(doc2,found,anchors2)),data.count*data.aliasCount>maxAliasCount)){let msg="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(msg)}}return found}toJSON(_arg,ctx){if(!ctx)return{source:this.source};let source=this.resolve(ctx.doc,ctx);if(!source){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(msg)}return ctx.anchors.get(source).res}toString(ctx,_onComment,_onChompKeep){let src=`*${this.source}`;if(ctx){if(anchors.anchorIsValid(this.source),ctx.options.verifyAliasOrder&&!ctx.anchors.has(this.source)){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(msg)}if(ctx.implicitKey)return`${src} `}return src}};function getAliasCount(doc,node,anchors2){if(identity.isAlias(node)){let source=node.resolve(doc),anchor=anchors2&&source&&anchors2.get(source);return anchor?anchor.count*anchor.aliasCount:0}else if(identity.isCollection(node)){let count=0;for(let item of node.items){let c=getAliasCount(doc,item,anchors2);c>count&&(count=c)}return count}else if(identity.isPair(node)){let kc=getAliasCount(doc,node.key,anchors2),vc=getAliasCount(doc,node.value,anchors2);return Math.max(kc,vc)}return 1}exports.Alias=Alias}});var require_Scalar=__commonJS({"node_modules/yaml/dist/nodes/Scalar.js"(exports){"use strict";var identity=require_identity(),Node=require_Node(),toJS=require_toJS(),isScalarValue=value=>!value||typeof value!="function"&&typeof value!="object",Scalar=class extends Node.NodeBase{constructor(value){super(identity.SCALAR),this.value=value}toJSON(arg,ctx){return ctx?.keep?this.value:toJS.toJS(this.value,arg,ctx)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";exports.Scalar=Scalar;exports.isScalarValue=isScalarValue}});var require_createNode=__commonJS({"node_modules/yaml/dist/doc/createNode.js"(exports){"use strict";var Alias=require_Alias(),identity=require_identity(),Scalar=require_Scalar(),defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(value,tagName,tags){if(tagName){let match=tags.filter(t=>t.tag===tagName),tagObj=match.find(t=>!t.format)??match[0];if(!tagObj)throw new Error(`Tag ${tagName} not found`);return tagObj}return tags.find(t=>t.identify?.(value)&&!t.format)}function createNode(value,tagName,ctx){if(identity.isDocument(value)&&(value=value.contents),identity.isNode(value))return value;if(identity.isPair(value)){let map=ctx.schema[identity.MAP].createNode?.(ctx.schema,null,ctx);return map.items.push(value),map}(value instanceof String||value instanceof Number||value instanceof Boolean||typeof BigInt<"u"&&value instanceof BigInt)&&(value=value.valueOf());let{aliasDuplicateObjects,onAnchor,onTagObj,schema,sourceObjects}=ctx,ref;if(aliasDuplicateObjects&&value&&typeof value=="object"){if(ref=sourceObjects.get(value),ref)return ref.anchor??(ref.anchor=onAnchor(value)),new Alias.Alias(ref.anchor);ref={anchor:null,node:null},sourceObjects.set(value,ref)}tagName?.startsWith("!!")&&(tagName=defaultTagPrefix+tagName.slice(2));let tagObj=findTagObject(value,tagName,schema.tags);if(!tagObj){if(value&&typeof value.toJSON=="function"&&(value=value.toJSON()),!value||typeof value!="object"){let node2=new Scalar.Scalar(value);return ref&&(ref.node=node2),node2}tagObj=value instanceof Map?schema[identity.MAP]:Symbol.iterator in Object(value)?schema[identity.SEQ]:schema[identity.MAP]}onTagObj&&(onTagObj(tagObj),delete ctx.onTagObj);let node=tagObj?.createNode?tagObj.createNode(ctx.schema,value,ctx):typeof tagObj?.nodeClass?.from=="function"?tagObj.nodeClass.from(ctx.schema,value,ctx):new Scalar.Scalar(value);return tagName?node.tag=tagName:tagObj.default||(node.tag=tagObj.tag),ref&&(ref.node=node),node}exports.createNode=createNode}});var require_Collection=__commonJS({"node_modules/yaml/dist/nodes/Collection.js"(exports){"use strict";var createNode=require_createNode(),identity=require_identity(),Node=require_Node();function collectionFromPath(schema,path,value){let v=value;for(let i=path.length-1;i>=0;--i){let k=path[i];if(typeof k=="number"&&Number.isInteger(k)&&k>=0){let a=[];a[k]=v,v=a}else v=new Map([[k,v]])}return createNode.createNode(v,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema,sourceObjects:new Map})}var isEmptyPath=path=>path==null||typeof path=="object"&&!!path[Symbol.iterator]().next().done,Collection=class extends Node.NodeBase{constructor(type,schema){super(type),Object.defineProperty(this,"schema",{value:schema,configurable:!0,enumerable:!1,writable:!0})}clone(schema){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return schema&&(copy.schema=schema),copy.items=copy.items.map(it=>identity.isNode(it)||identity.isPair(it)?it.clone(schema):it),this.range&&(copy.range=this.range.slice()),copy}addIn(path,value){if(isEmptyPath(path))this.add(value);else{let[key,...rest]=path,node=this.get(key,!0);if(identity.isCollection(node))node.addIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}deleteIn(path){let[key,...rest]=path;if(rest.length===0)return this.delete(key);let node=this.get(key,!0);if(identity.isCollection(node))return node.deleteIn(rest);throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}getIn(path,keepScalar){let[key,...rest]=path,node=this.get(key,!0);return rest.length===0?!keepScalar&&identity.isScalar(node)?node.value:node:identity.isCollection(node)?node.getIn(rest,keepScalar):void 0}hasAllNullValues(allowScalar){return this.items.every(node=>{if(!identity.isPair(node))return!1;let n=node.value;return n==null||allowScalar&&identity.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(path){let[key,...rest]=path;if(rest.length===0)return this.has(key);let node=this.get(key,!0);return identity.isCollection(node)?node.hasIn(rest):!1}setIn(path,value){let[key,...rest]=path;if(rest.length===0)this.set(key,value);else{let node=this.get(key,!0);if(identity.isCollection(node))node.setIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}};exports.Collection=Collection;exports.collectionFromPath=collectionFromPath;exports.isEmptyPath=isEmptyPath}});var require_stringifyComment=__commonJS({"node_modules/yaml/dist/stringify/stringifyComment.js"(exports){"use strict";var stringifyComment=str=>str.replace(/^(?!$)(?: $)?/gm,"#");function indentComment(comment,indent){return/^\n+$/.test(comment)?comment.substring(1):indent?comment.replace(/^(?! *$)/gm,indent):comment}var lineComment=(str,indent,comment)=>str.endsWith(`
|
|
4
4
|
`)?indentComment(comment,indent):comment.includes(`
|
|
5
5
|
`)?`
|
|
@@ -1,5 +1,5 @@
|
|
|
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{DynamicBorder,getEditorTheme,keyDisplayText,keyHint,observeVisibleStderrWrites,rawKeyHint,restoreStderr,sharedMarkdownTheme,takeOverStderr,theme}from"./chunk-BKDXY6EM.js";import{usageLimitScope}from"./chunk-HKCFMDJN.js";import{userWordBlocks}from"./chunk-E6ZBTSC6.js";import{isWSL}from"./chunk-ULWRGKP2.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{appendHiddenTuiStdout}from"./chunk-EUCZC2RF.js";import{CURSOR_MARKER,Container,Editor,Input,Markdown,MouseRegion,ProcessTerminal,ScrollView,Spacer,Text,TuiAltScreen,TuiMainScreen,VStack,copyLineSources,getKeybindings,getNativeClipboard,isWarpWslSession,matchesKey,nextRenderRevision,truncateToWidth,visibleWidth}from"./chunk-4PMRUR4L.js";import{redactSensitiveOutput}from"./chunk-62OVOJPI.js";import{SERVER_FALLBACK_ABORTED_DIAGNOSTIC}from"./chunk-Z6TEQEZO.js";import{ACCOUNT_LIMIT_NEXT_STEP_LEAD,describeProviderFailureForUser,stripTurnRetrySuppressionPrefix}from"./chunk-OH5TKHW7.js";import{getDebugLogPath,stripBom}from"./chunk-SODMQEHO.js";import{typebox_exports}from"./chunk-MIENF2YK.js";var CODEX_OPTION=typebox_exports.Object({label:typebox_exports.String({description:"User-facing label (1-5 words)."}),description:typebox_exports.String({description:"One short sentence explaining impact/tradeoff if selected."})},{additionalProperties:!1}),CODEX_QUESTION=typebox_exports.Object({id:typebox_exports.String({pattern:"^[a-z][a-z0-9]*(_[a-z0-9]+)*$",description:"Stable identifier for mapping answers (snake_case)."}),header:typebox_exports.String({minLength:1,maxLength:12,description:"Short header label shown in the UI (12 or fewer chars)."}),question:typebox_exports.String({minLength:1,description:"Single-sentence prompt shown to the user."}),options:typebox_exports.Array(CODEX_OPTION,{minItems:2,maxItems:3,description:'Provide 2-3 mutually exclusive choices. Put the recommended option first and suffix its label with "(Recommended)". Do not include an "Other" option in this list; the client will add a free-form "Other" option automatically.'}),multiSelect:typebox_exports.Optional(typebox_exports.Boolean({description:"Set to true to allow the user to select multiple options instead of just one."}))},{additionalProperties:!1}),CODEX_PARAMS=typebox_exports.Object({questions:typebox_exports.Array(CODEX_QUESTION,{minItems:1,maxItems:3,description:"Questions to show the user. Prefer 1 and do not exceed 3"}),wait_for_answer:typebox_exports.Boolean({description:"Set true to pause here until the user answers; set false to keep working and receive the answer later as a user message."}),required:typebox_exports.Optional(typebox_exports.Boolean({description:"Set true when the answer decides whether you take an action (for example, which of two irreversible paths to take, or whether to proceed): with no answer, that action is not taken."}))},{additionalProperties:!1}),CLAUDE_OPTION=typebox_exports.Object({label:typebox_exports.String({description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."}),description:typebox_exports.Optional(typebox_exports.String({description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}))}),CLAUDE_QUESTION=typebox_exports.Object({question:typebox_exports.String({minLength:1,description:'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'}),header:typebox_exports.String({minLength:1,maxLength:12,description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'}),options:typebox_exports.Optional(typebox_exports.Array(CLAUDE_OPTION,{minItems:2,maxItems:4,description:"The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no Other option, that will be provided automatically."})),multiSelect:typebox_exports.Boolean({description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."})}),CLAUDE_PARAMS=typebox_exports.Object({questions:typebox_exports.Array(CLAUDE_QUESTION,{minItems:1,maxItems:4,description:"Questions to ask the user (1-4 questions)"}),waitForAnswer:typebox_exports.Boolean({description:"Set true to pause here until the user answers; set false to keep working and receive the answer later as a user message."}),required:typebox_exports.Optional(typebox_exports.Boolean({description:"Set true when the answer decides whether you take an action (for example, which of two irreversible paths to take, or whether to proceed): with no answer, that action is not taken."}))});var WAIT_FLAG_STEER_TEXT="This call omitted wait_for_answer (or waitForAnswer). Set true to pause here until the user answers, false to keep working and receive the answer later as a user message.",DEFAULT_ASK_USER_TIMEOUT_MS=1800*1e3,HEADER_MAX=12,SNAKE_CASE=/^[a-z][a-z0-9]*(_[a-z0-9]+)*$/,LIMITS={codex:{maxQuestions:3,minOptions:2,maxOptions:3,optionsRequired:!0},claude:{maxQuestions:4,minOptions:2,maxOptions:4,optionsRequired:!1}},AskUserSchemaError=class extends Error{constructor(message){super(message),this.name="AskUserSchemaError"}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readWaitFlag(variant,args){let value=args[variant==="codex"?"wait_for_answer":"waitForAnswer"];if(typeof value!="boolean")throw new AskUserSchemaError(WAIT_FLAG_STEER_TEXT);return value}function parseOptions(raw,min,max,required,requireDescription){if(raw===void 0){if(required)throw new AskUserSchemaError(`options must contain ${min} to ${max} items`);return[]}if(!Array.isArray(raw))throw new AskUserSchemaError("options must be an array");if(raw.length<min||raw.length>max)throw new AskUserSchemaError(required?`options must contain ${min} to ${max} items`:`options must contain ${min} to ${max} items when present`);let options=[];for(let item of raw){if(!isRecord(item))throw new AskUserSchemaError("each option must be an object");let label=typeof item.label=="string"?item.label.trim():"";if(label.length===0)throw new AskUserSchemaError("option label must be non-empty");let description=typeof item.description=="string"?item.description.trim():void 0;if(requireDescription&&(description===void 0||description.length===0))throw new AskUserSchemaError("option description is required");options.push(description===void 0||description.length===0?{label}:{label,description})}return options}function parseQuestion(variant,raw,index){if(!isRecord(raw))throw new AskUserSchemaError("each question must be an object");let limits=LIMITS[variant],header=typeof raw.header=="string"?raw.header.trim():"";if(header.length===0)throw new AskUserSchemaError("header must be non-empty");if(header.length>HEADER_MAX)throw new AskUserSchemaError("header must be 12 or fewer characters");let question=typeof raw.question=="string"?raw.question.trim():"";if(question.length===0)throw new AskUserSchemaError("question must be non-empty");let options=parseOptions(raw.options,limits.minOptions,limits.maxOptions,limits.optionsRequired,variant==="codex"),id;if(variant==="claude")id=`q${index+1}`;else if(id=typeof raw.id=="string"?raw.id.trim():"",!SNAKE_CASE.test(id))throw new AskUserSchemaError("id must be snake_case");let multiSelect;if(variant==="claude"){if(typeof raw.multiSelect!="boolean")throw new AskUserSchemaError("multiSelect is required");multiSelect=raw.multiSelect}else multiSelect=raw.multiSelect===!0;return{id,header,question,options,multiSelect}}function toCanonical(variant,args,options){if(!isRecord(args))throw new AskUserSchemaError(WAIT_FLAG_STEER_TEXT);let waitForAnswer=readWaitFlag(variant,args);if(args.required!==void 0&&typeof args.required!="boolean")throw new AskUserSchemaError("required must be a boolean when present");let limits=LIMITS[variant];if(!Array.isArray(args.questions)||args.questions.length<1||args.questions.length>limits.maxQuestions)throw new AskUserSchemaError(`questions must contain 1 to ${limits.maxQuestions} items`);return{requestId:options?.requestId??crypto.randomUUID(),questions:args.questions.map((question,index)=>parseQuestion(variant,question,index)),waitForAnswer,timeoutMs:options?.timeoutMs??DEFAULT_ASK_USER_TIMEOUT_MS,...args.required===!0?{required:!0}:{}}}var INLINE_WORDS={comment:text=>text,typed:(_header,text)=>text},reference=label=>`(see [${label}] below)`;function separatedWords(requestId){let words=[],place=(base,text)=>{let taken=words.filter(word=>word.label===base||word.label.startsWith(`${base} (`)).length,label=taken===0?base:`${base} (${taken+1})`;return words.push({label,text}),reference(label)};return{words,comment:text=>place(`The user's comment for question ${requestId}`,text),typed:(header,text)=>place(`The user's answer to ${header} for question ${requestId}`,text)}}function resolveUserWordReferences(text,words){return words.reduce((resolved,word)=>resolved.split(reference(word.label)).join(word.text),text)}function readUserWordBlocks(content){let texts=content.flatMap(block=>block.type==="text"?[block.text]:[]);if(texts.length%2!==0)return;let words=[];for(let index=0;index<texts.length;index+=2){let label=/^\[(.+)\]$/s.exec(texts[index]??"")?.[1],text=texts[index+1];if(label===void 0||text===void 0)return;words.push({label,text})}return words}function headerFor(id,questions){return questions.find(question=>question.id===id)?.header??id}function questionTextFor(id,questions){return questions.find(question=>question.id===id)?.question??id}function typedText(answer){if(answer.selected.length>0)return;let text=answer.text?.trim();return text===void 0||text.length===0?void 0:text}function answerBody(answer,header,words=INLINE_WORDS,offered=[]){if(!answer)return;if(answer.selected.length>0)return answer.selected.join(", ");let text=typedText(answer);if(text!==void 0)return offered.some(option=>option.label===text)?text:words.typed(header,text)}function answeredLines(response,questions,words){let lines=[],seen=new Set;for(let question of questions){let body=answerBody(response.answers[question.id],question.header,words,question.options);body!==void 0&&(lines.push(`${question.header}: ${body}`),seen.add(question.id))}for(let[id,answer]of Object.entries(response.answers)){if(seen.has(id))continue;let header=headerFor(id,questions),body=answerBody(answer,header,words);body!==void 0&&lines.push(`${header}: ${body}`)}return lines}function unansweredLine(response,questions){let unanswered=response.unanswered.map(id=>headerFor(id,questions));return unanswered.length>0?[`Unanswered: ${unanswered.join(", ")}`]:[]}var CANCELLED_BY_USER="The user cancelled the question after answering part of it.",CANCELLED_AFTER_ANSWERS="The question was cancelled after part of it was answered.";function isCancelledWithAnswersLine(line){return line===CANCELLED_BY_USER||line===CANCELLED_AFTER_ANSWERS}function showsPartialAnswers(response){return response.status!=="cancelled"||response.cancelOrigin!=="user"&&response.cancelOrigin!=="ui_failure"?!1:Object.values(response.answers).some(answer=>answerBody(answer,"")!==void 0)}function selectedBlock(prefix,selected){return selected.length===1?[`${prefix} ${selected[0]}`]:[prefix,...selected]}var GATED_NO_ANSWER="No answer: do not take the action it gates. Keep that action pending and end the turn.";function formatGatedNoAnswer(response,questions,words,cancellationReason){let lines=[cancellationReason??(response.status==="timed_out"?`The user did not answer within ${Math.round((response.autoResolvedAfterMs??DEFAULT_ASK_USER_TIMEOUT_MS)/6e4)} minutes. (\uC0AC\uC6A9\uC790\uAC00 \uB2F5\uBCC0\uC744 \uC548\uD558\uACE0 timeout \uC73C\uB85C \uC885\uB8CC\uB428)`:response.status==="cancelled"?"The user dismissed the question.":response.status==="orphaned-after-restart"?"The pending question could not be resumed after a restart.":"This session has no user attached (subagent or headless).")],selected=answeredLines(response,questions,words);return selected.length>0&&lines.push(...selectedBlock("Before going idle the user had selected (not an answer):",selected)),lines.push(GATED_NO_ANSWER),lines.join(`
|
|
2
|
+
import{DynamicBorder,getEditorTheme,keyDisplayText,keyHint,observeVisibleStderrWrites,rawKeyHint,restoreStderr,sharedMarkdownTheme,takeOverStderr,theme}from"./chunk-5NECOJNK.js";import{usageLimitScope}from"./chunk-HKCFMDJN.js";import{userWordBlocks}from"./chunk-A3LGSX7Z.js";import{isWSL}from"./chunk-ULWRGKP2.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{appendHiddenTuiStdout}from"./chunk-EUCZC2RF.js";import{CURSOR_MARKER,Container,Editor,Input,Markdown,MouseRegion,ProcessTerminal,ScrollView,Spacer,Text,TuiAltScreen,TuiMainScreen,VStack,copyLineSources,getKeybindings,getNativeClipboard,isWarpWslSession,matchesKey,nextRenderRevision,truncateToWidth,visibleWidth}from"./chunk-4PMRUR4L.js";import{redactSensitiveOutput}from"./chunk-62OVOJPI.js";import{SERVER_FALLBACK_ABORTED_DIAGNOSTIC}from"./chunk-Z6TEQEZO.js";import{ACCOUNT_LIMIT_NEXT_STEP_LEAD,describeProviderFailureForUser,stripTurnRetrySuppressionPrefix}from"./chunk-OH5TKHW7.js";import{getDebugLogPath,stripBom}from"./chunk-SODMQEHO.js";import{typebox_exports}from"./chunk-MIENF2YK.js";var CODEX_OPTION=typebox_exports.Object({label:typebox_exports.String({description:"User-facing label (1-5 words)."}),description:typebox_exports.String({description:"One short sentence explaining impact/tradeoff if selected."})},{additionalProperties:!1}),CODEX_QUESTION=typebox_exports.Object({id:typebox_exports.String({pattern:"^[a-z][a-z0-9]*(_[a-z0-9]+)*$",description:"Stable identifier for mapping answers (snake_case)."}),header:typebox_exports.String({minLength:1,maxLength:12,description:"Short header label shown in the UI (12 or fewer chars)."}),question:typebox_exports.String({minLength:1,description:"Single-sentence prompt shown to the user."}),options:typebox_exports.Array(CODEX_OPTION,{minItems:2,maxItems:3,description:'Provide 2-3 mutually exclusive choices. Put the recommended option first and suffix its label with "(Recommended)". Do not include an "Other" option in this list; the client will add a free-form "Other" option automatically.'}),multiSelect:typebox_exports.Optional(typebox_exports.Boolean({description:"Set to true to allow the user to select multiple options instead of just one."}))},{additionalProperties:!1}),CODEX_PARAMS=typebox_exports.Object({questions:typebox_exports.Array(CODEX_QUESTION,{minItems:1,maxItems:3,description:"Questions to show the user. Prefer 1 and do not exceed 3"}),wait_for_answer:typebox_exports.Boolean({description:"Set true to pause here until the user answers; set false to keep working and receive the answer later as a user message."}),required:typebox_exports.Optional(typebox_exports.Boolean({description:"Set true when the answer decides whether you take an action (for example, which of two irreversible paths to take, or whether to proceed): with no answer, that action is not taken."}))},{additionalProperties:!1}),CLAUDE_OPTION=typebox_exports.Object({label:typebox_exports.String({description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."}),description:typebox_exports.Optional(typebox_exports.String({description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}))}),CLAUDE_QUESTION=typebox_exports.Object({question:typebox_exports.String({minLength:1,description:'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'}),header:typebox_exports.String({minLength:1,maxLength:12,description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'}),options:typebox_exports.Optional(typebox_exports.Array(CLAUDE_OPTION,{minItems:2,maxItems:4,description:"The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no Other option, that will be provided automatically."})),multiSelect:typebox_exports.Boolean({description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."})}),CLAUDE_PARAMS=typebox_exports.Object({questions:typebox_exports.Array(CLAUDE_QUESTION,{minItems:1,maxItems:4,description:"Questions to ask the user (1-4 questions)"}),waitForAnswer:typebox_exports.Boolean({description:"Set true to pause here until the user answers; set false to keep working and receive the answer later as a user message."}),required:typebox_exports.Optional(typebox_exports.Boolean({description:"Set true when the answer decides whether you take an action (for example, which of two irreversible paths to take, or whether to proceed): with no answer, that action is not taken."}))});var WAIT_FLAG_STEER_TEXT="This call omitted wait_for_answer (or waitForAnswer). Set true to pause here until the user answers, false to keep working and receive the answer later as a user message.",DEFAULT_ASK_USER_TIMEOUT_MS=1800*1e3,HEADER_MAX=12,SNAKE_CASE=/^[a-z][a-z0-9]*(_[a-z0-9]+)*$/,LIMITS={codex:{maxQuestions:3,minOptions:2,maxOptions:3,optionsRequired:!0},claude:{maxQuestions:4,minOptions:2,maxOptions:4,optionsRequired:!1}},AskUserSchemaError=class extends Error{constructor(message){super(message),this.name="AskUserSchemaError"}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readWaitFlag(variant,args){let value=args[variant==="codex"?"wait_for_answer":"waitForAnswer"];if(typeof value!="boolean")throw new AskUserSchemaError(WAIT_FLAG_STEER_TEXT);return value}function parseOptions(raw,min,max,required,requireDescription){if(raw===void 0){if(required)throw new AskUserSchemaError(`options must contain ${min} to ${max} items`);return[]}if(!Array.isArray(raw))throw new AskUserSchemaError("options must be an array");if(raw.length<min||raw.length>max)throw new AskUserSchemaError(required?`options must contain ${min} to ${max} items`:`options must contain ${min} to ${max} items when present`);let options=[];for(let item of raw){if(!isRecord(item))throw new AskUserSchemaError("each option must be an object");let label=typeof item.label=="string"?item.label.trim():"";if(label.length===0)throw new AskUserSchemaError("option label must be non-empty");let description=typeof item.description=="string"?item.description.trim():void 0;if(requireDescription&&(description===void 0||description.length===0))throw new AskUserSchemaError("option description is required");options.push(description===void 0||description.length===0?{label}:{label,description})}return options}function parseQuestion(variant,raw,index){if(!isRecord(raw))throw new AskUserSchemaError("each question must be an object");let limits=LIMITS[variant],header=typeof raw.header=="string"?raw.header.trim():"";if(header.length===0)throw new AskUserSchemaError("header must be non-empty");if(header.length>HEADER_MAX)throw new AskUserSchemaError("header must be 12 or fewer characters");let question=typeof raw.question=="string"?raw.question.trim():"";if(question.length===0)throw new AskUserSchemaError("question must be non-empty");let options=parseOptions(raw.options,limits.minOptions,limits.maxOptions,limits.optionsRequired,variant==="codex"),id;if(variant==="claude")id=`q${index+1}`;else if(id=typeof raw.id=="string"?raw.id.trim():"",!SNAKE_CASE.test(id))throw new AskUserSchemaError("id must be snake_case");let multiSelect;if(variant==="claude"){if(typeof raw.multiSelect!="boolean")throw new AskUserSchemaError("multiSelect is required");multiSelect=raw.multiSelect}else multiSelect=raw.multiSelect===!0;return{id,header,question,options,multiSelect}}function toCanonical(variant,args,options){if(!isRecord(args))throw new AskUserSchemaError(WAIT_FLAG_STEER_TEXT);let waitForAnswer=readWaitFlag(variant,args);if(args.required!==void 0&&typeof args.required!="boolean")throw new AskUserSchemaError("required must be a boolean when present");let limits=LIMITS[variant];if(!Array.isArray(args.questions)||args.questions.length<1||args.questions.length>limits.maxQuestions)throw new AskUserSchemaError(`questions must contain 1 to ${limits.maxQuestions} items`);return{requestId:options?.requestId??crypto.randomUUID(),questions:args.questions.map((question,index)=>parseQuestion(variant,question,index)),waitForAnswer,timeoutMs:options?.timeoutMs??DEFAULT_ASK_USER_TIMEOUT_MS,...args.required===!0?{required:!0}:{}}}var INLINE_WORDS={comment:text=>text,typed:(_header,text)=>text},reference=label=>`(see [${label}] below)`;function separatedWords(requestId){let words=[],place=(base,text)=>{let taken=words.filter(word=>word.label===base||word.label.startsWith(`${base} (`)).length,label=taken===0?base:`${base} (${taken+1})`;return words.push({label,text}),reference(label)};return{words,comment:text=>place(`The user's comment for question ${requestId}`,text),typed:(header,text)=>place(`The user's answer to ${header} for question ${requestId}`,text)}}function resolveUserWordReferences(text,words){return words.reduce((resolved,word)=>resolved.split(reference(word.label)).join(word.text),text)}function readUserWordBlocks(content){let texts=content.flatMap(block=>block.type==="text"?[block.text]:[]);if(texts.length%2!==0)return;let words=[];for(let index=0;index<texts.length;index+=2){let label=/^\[(.+)\]$/s.exec(texts[index]??"")?.[1],text=texts[index+1];if(label===void 0||text===void 0)return;words.push({label,text})}return words}function headerFor(id,questions){return questions.find(question=>question.id===id)?.header??id}function questionTextFor(id,questions){return questions.find(question=>question.id===id)?.question??id}function typedText(answer){if(answer.selected.length>0)return;let text=answer.text?.trim();return text===void 0||text.length===0?void 0:text}function answerBody(answer,header,words=INLINE_WORDS,offered=[]){if(!answer)return;if(answer.selected.length>0)return answer.selected.join(", ");let text=typedText(answer);if(text!==void 0)return offered.some(option=>option.label===text)?text:words.typed(header,text)}function answeredLines(response,questions,words){let lines=[],seen=new Set;for(let question of questions){let body=answerBody(response.answers[question.id],question.header,words,question.options);body!==void 0&&(lines.push(`${question.header}: ${body}`),seen.add(question.id))}for(let[id,answer]of Object.entries(response.answers)){if(seen.has(id))continue;let header=headerFor(id,questions),body=answerBody(answer,header,words);body!==void 0&&lines.push(`${header}: ${body}`)}return lines}function unansweredLine(response,questions){let unanswered=response.unanswered.map(id=>headerFor(id,questions));return unanswered.length>0?[`Unanswered: ${unanswered.join(", ")}`]:[]}var CANCELLED_BY_USER="The user cancelled the question after answering part of it.",CANCELLED_AFTER_ANSWERS="The question was cancelled after part of it was answered.";function isCancelledWithAnswersLine(line){return line===CANCELLED_BY_USER||line===CANCELLED_AFTER_ANSWERS}function showsPartialAnswers(response){return response.status!=="cancelled"||response.cancelOrigin!=="user"&&response.cancelOrigin!=="ui_failure"?!1:Object.values(response.answers).some(answer=>answerBody(answer,"")!==void 0)}function selectedBlock(prefix,selected){return selected.length===1?[`${prefix} ${selected[0]}`]:[prefix,...selected]}var GATED_NO_ANSWER="No answer: do not take the action it gates. Keep that action pending and end the turn.";function formatGatedNoAnswer(response,questions,words,cancellationReason){let lines=[cancellationReason??(response.status==="timed_out"?`The user did not answer within ${Math.round((response.autoResolvedAfterMs??DEFAULT_ASK_USER_TIMEOUT_MS)/6e4)} minutes. (\uC0AC\uC6A9\uC790\uAC00 \uB2F5\uBCC0\uC744 \uC548\uD558\uACE0 timeout \uC73C\uB85C \uC885\uB8CC\uB428)`:response.status==="cancelled"?"The user dismissed the question.":response.status==="orphaned-after-restart"?"The pending question could not be resumed after a restart.":"This session has no user attached (subagent or headless).")],selected=answeredLines(response,questions,words);return selected.length>0&&lines.push(...selectedBlock("Before going idle the user had selected (not an answer):",selected)),lines.push(GATED_NO_ANSWER),lines.join(`
|
|
3
3
|
`)}function formatGatedCancellation(reason,response,requestId,questions){return formatGatedNoAnswer(response,questions,separatedWords(requestId),reason)}function formatBody(response,questions,words,required=!1){if(required&&response.status!=="answered"&&response.status!=="comment-submitted")return formatGatedNoAnswer(response,questions,words);switch(response.status){case"answered":return[...answeredLines(response,questions,words),...unansweredLine(response,questions)].join(`
|
|
4
4
|
`);case"comment-submitted":{let comment=response.comment?.trim()??"";return[`The user responded: ${comment.length>0?words.comment(comment):""}`,...answeredLines(response,questions,words),...unansweredLine(response,questions)].join(`
|
|
5
5
|
`)}case"timed_out":{let lines=[`The user did not answer within ${Math.round((response.autoResolvedAfterMs??DEFAULT_ASK_USER_TIMEOUT_MS)/6e4)} minutes. (\uC0AC\uC6A9\uC790\uAC00 \uB2F5\uBCC0\uC744 \uC548\uD558\uACE0 timeout \uC73C\uB85C \uC885\uB8CC\uB428)`],selected=answeredLines(response,questions,words);return selected.length>0&&lines.push(...selectedBlock("Before going idle the user had selected:",selected),...unansweredLine(response,questions)),lines.push("Continue the work to completion on your best judgment; do not ask this question again this turn."),lines.join(`
|
|
@@ -1,6 +1,6 @@
|
|
|
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
2
|
import{reportedCount}from"./chunk-GVSBCJFI.js";import{splitDeferredTools}from"./chunk-HK46JMSC.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{appendGrammarToolInputJsonDelta,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-UAOOH2V7.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{calculateCost,getCurrentTools,getDeclaredTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript,resolveTranscriptTools,supportsConfigurationUpdate}from"./chunk-OH5TKHW7.js";import{enableAssistantCapture,pushAssistantProgress}from"./chunk-NDNQ23SK.js";function supportsOpenAIResponsesExplicitPromptCacheMode(model){let compat=model.compat;return!compat?.siwc&&compat?.supportsExplicitPromptCacheMode===!0}function isOpenAIResponsesPromptCacheModel(model){if(model.api!=="openai-responses"||!supportsOpenAIResponsesExplicitPromptCacheMode(model))return!1;try{return new URL(model.baseUrl||"https://api.openai.com/v1").hostname==="api.openai.com"}catch{return!1}}function findPromptCacheComparisonResponseId(model,messages){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role==="assistant"&&!(message.api!==model.api||message.provider!==model.provider||message.model!==model.id)&&!(message.stopReason==="error"||message.stopReason==="aborted")&&typeof message.responseId=="string"&&message.responseId.length>0)return message.responseId.startsWith("resp")?message.responseId:void 0}}function withPromptCacheComparison(options,comparisonResponseId){return comparisonResponseId===void 0?options:{...options,comparison_response_id:comparisonResponseId}}function finiteCount(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:void 0}function parsePromptCacheDiagnostics(raw){if(typeof raw!="object"||raw===null)return;let record=raw;if(typeof record.type!="string"||record.type.length===0)return;let diagnostics={type:record.type};typeof record.reason=="string"&&(diagnostics.reason=record.reason);let cacheMissedTokens=finiteCount(record.cache_missed_tokens);cacheMissedTokens!==void 0&&(diagnostics.cacheMissedTokens=cacheMissedTokens);let comparisonReusableTokens=finiteCount(record.comparison_reusable_tokens);return comparisonReusableTokens!==void 0&&(diagnostics.comparisonReusableTokens=comparisonReusableTokens),diagnostics}var CONTEXT_PROVENANCE_FIELD="__piContextProvenance";function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function getContextProvenance(value){if(!isRecord(value))return;let provenance=value[CONTEXT_PROVENANCE_FIELD];return isRecord(provenance)?provenance:void 0}function copyContextProvenance(source,target){let provenance=getContextProvenance(source);return provenance?Object.assign(target,{[CONTEXT_PROVENANCE_FIELD]:provenance}):target}function contextProvenanceFingerprint(value){if(!isRecord(value))return;let clone={...value};return delete clone[CONTEXT_PROVENANCE_FIELD],JSON.stringify(clone)}function formatResponsesCompletionStall(graceMs){return`Provider stream stalled after the last output item: response.completed timed out after ${graceMs}ms`}var ResponsesCompletionStallError=class extends Error{constructor(graceMs){super(formatResponsesCompletionStall(graceMs)),this.name="ResponsesCompletionStallError",this.graceMs=graceMs}},GRACE_EXPIRED=Symbol("responses-completion-grace-expired");function withResponsesCompletionGrace(source,graceMs=6e4){return{[Symbol.asyncIterator](){let iterator=source[Symbol.asyncIterator](),openItems=0,sawItemDone=!1,finished=!1,observe=event=>{event.type==="response.output_item.added"?openItems++:event.type==="response.output_item.done"&&(openItems=Math.max(0,openItems-1),sawItemDone=!0)},boundedNext=async()=>{let next=iterator.next();if(!sawItemDone||openItems>0||graceMs<=0)return next;let timer,deadline=new Promise(resolve=>{timer=setTimeout(()=>resolve(GRACE_EXPIRED),graceMs)});try{let winner=await Promise.race([next,deadline]);if(winner===GRACE_EXPIRED)throw finished=!0,iterator.return?.().catch(()=>{}),new ResponsesCompletionStallError(graceMs);return winner}finally{timer!==void 0&&clearTimeout(timer)}};return{async next(){if(finished)return{done:!0,value:void 0};let result=await boundedNext();return result.done?finished=!0:observe(result.value),result},async return(value){return finished=!0,await iterator.return?.(value),{done:!0,value:void 0}},async throw(error){if(finished=!0,iterator.throw)return iterator.throw(error);throw error}}}}}function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function parseReasoningSignature(signature){if(signature)try{let parsed=JSON.parse(signature);return parsed?.type==="reasoning"?parsed:void 0}catch{return}}function convertToolResultOutput(model,content){let textResult=content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
3
|
-
`),images=content.filter(c=>c.type==="image"),hasText=textResult.length>0;if(images.length===0||!model.input.includes("image"))return sanitizeSurrogates(hasText?textResult:images.length>0?"(see attached image)":"(no tool output)");let output=[];hasText&&output.push({type:"input_text",text:sanitizeSurrogates(textResult)});for(let image of images)output.push({type:"input_image",detail:"auto",image_url:`data:${image.mimeType};base64,${image.data}`});return output}var CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL="custom",ULTRAFAST_DOCUMENTED_MODEL_IDS=new Set(["gpt-6-astra","gpt-6.1-sol"]);function isResponseCustomToolCallItem(item){return item.type==="custom_tool_call"}function isFreeformTool(tool){return tool.freeform!==void 0}function isFreeformToolName(toolName,tools){return tools?.some(tool=>tool.name===toolName&&isFreeformTool(tool))??!1}function getFreeformToolInput(argumentsValue){return typeof argumentsValue.input=="string"?argumentsValue.input:JSON.stringify(argumentsValue)}function contextProvenanceForInput(message,seal){let provenance=getContextProvenance(message);if(!provenance)return;let fingerprint=contextProvenanceFingerprint(message);if(fingerprint===void 0)return;let stored=provenance.integrity;return stored===void 0&&seal?(provenance.integrity=fingerprint,provenance):stored===fingerprint?provenance:void 0}function withContextProvenance(item,message,seal){let provenance=contextProvenanceForInput(message,seal);return provenance&&Object.defineProperty(item,CONTEXT_PROVENANCE_FIELD,{value:provenance,enumerable:!1}),item}function resolveResponsesDeferredToolsMode(compat){if(compat?.supportsAdditionalTools)return"additional-tools";if(!compat?.siwc)return compat?.supportsToolSearch?"tool-search":void 0}function resolveResponsesToolPlacement(messages,supportsToolAdditions){let transcriptTools=resolveTranscriptTools(messages,supportsToolAdditions),{deferred}=splitDeferredTools({messages:[...messages],tools:getCurrentTools(messages)},supportsToolAdditions);return{requestTools:transcriptTools.requestTools.filter(tool=>!deferred.has(tool.name)),anchorsAdditions:transcriptTools.anchorsAdditions,deferred}}function convertResponsesMessages(model,context,allowedToolCallProviders,options){let normalizedContext=resolveTranscript(context,options?.supportsMidConvoSystemMessages),messages=[],deferredToolsMode=resolveResponsesDeferredToolsMode(options),toolPlacement=resolveResponsesToolPlacement(normalizedContext.messages,deferredToolsMode!==void 0),declaredTools=getDeclaredTools(normalizedContext.messages),loadedToolNames=new Set,normalizeIdPart=part=>{let sanitized=part.replace(/[^a-zA-Z0-9_-]/g,"_");return(sanitized.length>64?sanitized.slice(0,64):sanitized).replace(/_+$/,"")},buildForeignResponsesItemId=itemId=>{let normalized=`fc_${shortHash(itemId)}`;return normalized.length>64?normalized.slice(0,64):normalized},normalizeToolCallId=(id,_targetModel,source)=>{if(!id.includes("|"))return normalizeIdPart(id);let[callId,itemId]=id.split("|"),normalizedCallId=normalizeIdPart(callId);if(itemId===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL)return`${normalizedCallId}|${CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`;if(!allowedToolCallProviders.has(model.provider))return normalizeIdPart(id);let normalizedItemId=source.provider!==model.provider||source.api!==model.api?buildForeignResponsesItemId(itemId):normalizeIdPart(itemId);return normalizedItemId.startsWith("fc_")||(normalizedItemId=normalizeIdPart(`fc_${normalizedItemId}`)),`${normalizedCallId}|${normalizedItemId}`},transformedMessages=transformMessages(normalizedContext.messages,model,normalizeToolCallId,{preserveThinking:options?.preserveThinking,preserveTextSignatures:options?.preserveTextSignatures}),appendSystemToolAdditions=(message,seed)=>{let tools=toolPlacement.anchorsAdditions?(message.toolsAdded??[]).filter(tool=>!loadedToolNames.has(tool.name)):[];if(tools.length===0)return;for(let tool of tools)loadedToolNames.add(tool.name);if(options?.supportsAdditionalTools){messages.push({type:"additional_tools",role:"developer",tools:convertResponsesTools(tools,options.toolOptions)});return}if(!options?.supportsToolSearch)return;let names=tools.map(tool=>tool.name),callId=`pi_tool_load_${shortHash(`${seed}:${names.join(",")}`)}`;messages.push({type:"tool_search_call",call_id:callId,execution:"client",status:"completed",arguments:{query:names.join(" "),limit:names.length}}),messages.push({type:"tool_search_output",call_id:callId,execution:"client",status:"completed",tools:convertResponsesTools(tools,{...options.toolOptions,toolSearchResult:!0})})},includeInitialSystemMessage=options?.includeSystemPrompt??!0,compat=model.compat,instructionRole=model.compat?.siwc||model.reasoning&&compat?.supportsDeveloperRole!==!1?"developer":"system",msgIndex=0,sourceIndex=0;for(let msg of transformedMessages){let isLeadingSystemMessage=sourceIndex++===0&&msg.role==="system";if(msg.role==="configurationUpdate"){if(!supportsConfigurationUpdate(model))continue;messages[messages.length-1]?.type==="configuration_update"?messages[messages.length-1]={type:"configuration_update",reasoning:{effort:msg.effort}}:messages.push({type:"configuration_update",reasoning:{effort:msg.effort}});continue}if(msg.role==="system"){if(isLeadingSystemMessage||appendSystemToolAdditions(msg,`system:${msgIndex}`),!isLeadingSystemMessage||includeInitialSystemMessage){let text=isLeadingSystemMessage?getSystemMessageText(msg):renderSystemMessageUpdate(msg);if(text.length>0&&isLeadingSystemMessage&&options?.systemPromptCacheBreakpoint===!0){let block={type:"input_text",text:sanitizeSurrogates(text),prompt_cache_breakpoint:{mode:"explicit"}};messages.push({role:instructionRole,content:[block]})}else text.length>0&&messages.push({role:instructionRole,content:sanitizeSurrogates(text)})}}else if(msg.role==="user")if(typeof msg.content=="string")messages.push(withContextProvenance({role:"user",content:[{type:"input_text",text:sanitizeSurrogates(msg.content)}]},msg,options?.sealContextProvenance));else{let content=msg.content.map(item=>item.type==="text"?{type:"input_text",text:sanitizeSurrogates(item.text)}:{type:"input_image",detail:"auto",image_url:`data:${item.mimeType};base64,${item.data}`});if(content.length===0)continue;messages.push(withContextProvenance({role:"user",content},msg,options?.sealContextProvenance))}else if(msg.role==="assistant"){let output=[],assistantMsg=msg,isSameProviderAndApi=assistantMsg.provider===model.provider&&assistantMsg.api===model.api,isSameModel=isSameProviderAndApi&&assistantMsg.model===model.id,isDifferentModel=isSameProviderAndApi&&assistantMsg.model!==model.id,textBlockIndex=0,pushAssistantText=(text,textSignature)=>{let parsedSignature=parseTextSignature(textSignature),fallbackMessageId=textBlockIndex===0?`msg_pi_${msgIndex}`:`msg_pi_${msgIndex}_${textBlockIndex}`;textBlockIndex++;let msgId=parsedSignature?.id;msgId?msgId.length>64&&(msgId=`msg_${shortHash(msgId)}`):msgId=fallbackMessageId,output.push({type:"message",role:"assistant",content:[{type:"output_text",text:sanitizeSurrogates(text),annotations:[]}],status:"completed",id:msgId,phase:parsedSignature?.phase})};for(let block of msg.content)if(block.type==="thinking"){let reasoningItem=parseReasoningSignature(block.thinkingSignature);reasoningItem?output.push(reasoningItem):block.thinkingSignature&&block.thinking.trim()!==""&&pushAssistantText(block.thinking)}else if(block.type==="providerNative"){let raw=block.raw;isSameModel&&block.subtype==="web_search_call"&&raw!==null&&typeof raw=="object"&&"type"in raw&&raw.type==="web_search_call"&&"id"in raw&&typeof raw.id=="string"&&"action"in raw&&"status"in raw&&(raw.status==="completed"||raw.status==="failed")&&output.push(raw)}else if(block.type==="text"){let textBlock=block;pushAssistantText(textBlock.text,textBlock.textSignature)}else if(block.type==="toolCall"){let toolCall=block,[callId,itemIdRaw]=toolCall.id.split("|"),customInputProperty=options?.grammarToolInputProperties?.get(toolCall.name),isPersistedFreeform=itemIdRaw===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL,isFreeform=isFreeformToolName(toolCall.name,declaredTools)||isPersistedFreeform,itemId=isPersistedFreeform?void 0:itemIdRaw,itemIdPrefix=customInputProperty===void 0?"fc_":"ctc_";(isDifferentModel||!itemId?.startsWith(itemIdPrefix))&&(itemId=void 0);let canReplayNamespace=isSameModel||toolPlacement.deferred.has(toolCall.name);customInputProperty!==void 0?output.push({type:"custom_tool_call",...itemId!==void 0?{id:itemId}:{},call_id:callId,name:toolCall.name,input:sanitizeSurrogates(getGrammarToolInput(toolCall.name,toolCall.arguments,customInputProperty)),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):isFreeform?output.push({type:"custom_tool_call",call_id:callId,name:toolCall.name,input:getFreeformToolInput(toolCall.arguments),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):output.push({type:"function_call",...itemId?.startsWith("fc_")?{id:itemId}:{},call_id:callId,name:toolCall.name,arguments:JSON.stringify(toolCall.arguments),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}})}if(output.length===0)continue;messages.push(...output.map(item=>withContextProvenance(item,msg,options?.sealContextProvenance)))}else if(msg.role==="toolResult"){let[callId,itemIdRaw]=msg.toolCallId.split("|"),output=convertToolResultOutput(model,msg.content),customInputProperty=options?.grammarToolInputProperties?.get(msg.toolName),isPersistedFreeform=itemIdRaw===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL;customInputProperty!==void 0?messages.push(withContextProvenance({type:"custom_tool_call_output",call_id:callId,output},msg,options?.sealContextProvenance)):isFreeformToolName(msg.toolName,declaredTools)||isPersistedFreeform?messages.push(withContextProvenance({type:"custom_tool_call_output",call_id:callId,name:msg.toolName,output},msg,options?.sealContextProvenance)):messages.push(withContextProvenance({type:"function_call_output",call_id:callId,output},msg,options?.sealContextProvenance));let deferredTools=[];for(let name of msg.addedToolNames??[]){let tool=toolPlacement.deferred.get(name);!tool||loadedToolNames.has(name)||(loadedToolNames.add(name),deferredTools.push(tool))}if(deferredTools.length>0&&deferredToolsMode==="additional-tools")messages.push(withContextProvenance({type:"additional_tools",role:"developer",tools:convertResponsesTools(deferredTools,options?.toolOptions)},msg,options?.sealContextProvenance));else if(deferredTools.length>0&&deferredToolsMode==="tool-search"){let names=deferredTools.map(tool=>tool.name),searchCallId=`pi_tool_load_${shortHash(`${msg.toolCallId}:${names.join(",")}`)}`;messages.push(withContextProvenance({type:"tool_search_call",call_id:searchCallId,execution:"client",status:"completed",arguments:{query:names.join(" "),limit:names.length}},msg,options?.sealContextProvenance)),messages.push(withContextProvenance({type:"tool_search_output",call_id:searchCallId,execution:"client",status:"completed",tools:convertResponsesTools(deferredTools,{...options?.toolOptions,toolSearchResult:!0})},msg,options?.sealContextProvenance))}}isLeadingSystemMessage||msgIndex++}return messages}function convertResponsesTools(tools,options){let defaultStrict=options?.strict===void 0?!1:options.strict,supportsStrictMode=options?.supportsStrictMode??!0,supportsOpenAIGrammarTools=options?.supportsOpenAIGrammarTools??!1;return[...tools].sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0).map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);if(grammar)return{type:"custom",name:tool.name,description:tool.description,format:{type:"grammar",syntax:grammar.format,definition:grammar.definition},...options?.toolSearchResult?{defer_loading:!0}:{}};if(tool.freeform)return{type:"custom",name:tool.name,description:tool.description,format:tool.freeform,...options?.toolSearchResult?{defer_loading:!0}:{}};let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode)??defaultStrict,functionTool={type:"function",name:tool.name,description:tool.description,parameters:getJsonSchemaToolParameters(tool,strict===!0),...options?.toolSearchResult?{defer_loading:!0}:{}};return supportsStrictMode&&(functionTool.strict=strict),functionTool})}function getCustomToolCallInput(block){let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""}function appendCustomToolCallInput(block,nextInput,close){let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta}var MAX_NATIVE_IMAGE_BASE64_CHARS=24*1024*1024;function readNativeImageGenerationCall(value){if(!(typeof value!="object"||value===null||!("type"in value)||!("status"in value))&&!(value.type!=="image_generation_call"||typeof value.status!="string"))return{type:"image_generation_call",..."id"in value&&typeof value.id=="string"?{id:value.id}:{},status:value.status,..."result"in value&&(typeof value.result=="string"||value.result===null)?{result:value.result}:{},..."revised_prompt"in value&&typeof value.revised_prompt=="string"?{revised_prompt:value.revised_prompt}:{}}}function isValidBase64(value){return value.length>0&&value.length%4===0&&/^[A-Za-z0-9+/]*={0,2}$/.test(value)}function reconcileNativeImageGenerationCall(item){return item.status!=="completed"?{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:item.status}:typeof item.result!="string"||!isValidBase64(item.result)?{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"malformed"}:{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"completed",result:item.result,...item.revised_prompt?.trim()?{revised_prompt:item.revised_prompt}:{}}}async function processResponsesStream(openaiStream,output,stream,model,options){enableAssistantCapture(stream);let sawTerminalResponseEvent=!1,nativeImageBase64Chars=0,outputSlots=new Map,reasoningBlocksById=new Map,nativeImageCharsByOutputIndex=new Map,finalizedNativeImageOutputIndexes=new Set,applyMessagePhaseStopReason=item=>{item.type==="message"&&item.phase==="final_answer"&&(output.stopReason="stop")},getSlot=(outputIndex,type)=>{let slot=outputSlots.get(outputIndex);return slot?.type===type?slot:void 0},pushToolCallDelta=(slot,delta)=>{delta!==void 0&&stream.push({type:"toolcall_delta",contentIndex:slot.contentIndex,delta,partial:output})},createSlot=(outputIndex,item)=>{if(item.type==="reasoning"){let block2={type:"thinking",thinking:""};output.content.push(block2);let slot2={type:"thinking",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"thinking_start",contentIndex:slot2.contentIndex,partial:output}),slot2}if(item.type==="message"){applyMessagePhaseStopReason(item);let block2={type:"text",text:""};output.content.push(block2);let slot2={type:"text",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"text_start",contentIndex:slot2.contentIndex,partial:output}),slot2}if(item.type==="function_call"){let block2={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:{},...item.namespace!==void 0?{namespace:item.namespace}:{},partialJson:item.arguments||""};output.content.push(block2);let slot2={type:"toolCall",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"toolcall_start",contentIndex:slot2.contentIndex,partial:output},{rawArgumentPrefix:block2.partialJson}),slot2}if(isResponseCustomToolCallItem(item)){let inputProperty=options?.grammarToolInputProperties?.get(item.name)??"input",input=item.input||"",block2={type:"toolCall",id:`${item.call_id}|${item.id??CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`,name:item.name,arguments:{[inputProperty]:input},...item.namespace!==void 0?{namespace:item.namespace}:{},customInput:{property:inputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}};output.content.push(block2);let slot2={type:"toolCall",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"toolcall_start",contentIndex:slot2.contentIndex,partial:output}),slot2}let imageItem=readNativeImageGenerationCall(item),block={type:"providerNative",subtype:item.type,raw:imageItem?reconcileNativeImageGenerationCall(imageItem):item},slot={type:"providerNative",block,contentIndex:output.content.length};return imageItem&&reconcileNativeImageSlot(outputIndex,slot,imageItem),output.content.push(block),outputSlots.set(outputIndex,slot),pushAssistantProgress(stream,{type:"message_block_state",contentIndex:slot.contentIndex,phase:"insert",block}),slot},getOrCreateSlot=(outputIndex,item)=>outputSlots.get(outputIndex)??createSlot(outputIndex,item);function scrubNativeImageResults(){for(let block of output.content){if(block.type!=="providerNative"||block.subtype!=="image_generation_call")continue;let item=readNativeImageGenerationCall(block.raw);typeof item?.result=="string"&&(block.raw={type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"malformed"})}nativeImageBase64Chars=0,nativeImageCharsByOutputIndex.clear()}function reconcileNativeImageSlot(outputIndex,slot,item){let reconciled=reconcileNativeImageGenerationCall(item),previousChars=nativeImageCharsByOutputIndex.get(outputIndex)??0,nextChars=typeof reconciled.result=="string"?reconciled.result.length:0,nextTotal=nativeImageBase64Chars-previousChars+nextChars;if(nextTotal>MAX_NATIVE_IMAGE_BASE64_CHARS)throw scrubNativeImageResults(),new Error("Native image generation results exceed the 24 MiB base64 limit");nativeImageBase64Chars=nextTotal,nextChars>0?nativeImageCharsByOutputIndex.set(outputIndex,nextChars):nativeImageCharsByOutputIndex.delete(outputIndex),slot.block.subtype="image_generation_call",slot.block.raw=reconciled}let backfillNativeImageGenerationCalls=responseOutput=>{for(let[outputIndex,outputItem]of responseOutput.entries()){if(finalizedNativeImageOutputIndexes.has(outputIndex))continue;let imageItem=readNativeImageGenerationCall(outputItem);if(!imageItem)continue;let existingSlot=getSlot(outputIndex,"providerNative"),slot=existingSlot??createSlot(outputIndex,outputItem);existingSlot&&reconcileNativeImageSlot(outputIndex,existingSlot,imageItem),slot&&pushAssistantProgress(stream,{type:"message_block_state",contentIndex:slot.contentIndex,phase:"end",block:slot.block}),outputSlots.delete(outputIndex)}},backfillReasoningSignatures=responseOutput=>{for(let item of responseOutput){if(item.type!=="reasoning"||!item.encrypted_content)continue;let block=reasoningBlocksById.get(item.id);if(!block?.thinkingSignature)continue;let storedItem=parseReasoningSignature(block.thinkingSignature);!storedItem||storedItem.encrypted_content||(block.thinkingSignature=JSON.stringify({...storedItem,encrypted_content:item.encrypted_content}))}},finalizeResponse=response=>{sawTerminalResponseEvent=!0,backfillReasoningSignatures(response.output??[]),backfillNativeImageGenerationCalls(response.output??[]),response?.id&&(output.responseId=response.id);let promptCacheDiagnostics=parsePromptCacheDiagnostics(response?.prompt_cache_diagnostics);if(promptCacheDiagnostics&&(output.promptCacheDiagnostics=promptCacheDiagnostics),response?.usage){let inputDetails=response.usage.input_tokens_details,cachedTokens=inputDetails?.cached_tokens||0,cacheWriteTokens=inputDetails?.cache_write_tokens??inputDetails?.cache_creation_tokens??0,reasoning=reportedCount(response.usage.output_tokens_details?.reasoning_tokens);output.usage={input:Math.max(0,(response.usage.input_tokens||0)-cachedTokens-cacheWriteTokens),output:response.usage.output_tokens||0,cacheRead:cachedTokens,cacheWrite:cacheWriteTokens,...reasoning===void 0?{}:{reasoning},totalTokens:response.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(calculateCost(model,output.usage),options?.applyServiceTierPricing){let serviceTier=options.resolveServiceTier?options.resolveServiceTier(response?.service_tier,options.serviceTier):response?.service_tier??options.serviceTier;options.applyServiceTierPricing(output.usage,serviceTier)}let status=response?.status,incompleteDetails=response?.incomplete_details,incompleteReason=typeof incompleteDetails?.reason=="string"?incompleteDetails.reason:void 0;output.rawStopReason=incompleteReason?`${status}.${incompleteReason}`:status;let mappedStop=mapStopReason(status,incompleteReason);output.stopReason=mappedStop.stopReason,mappedStop.errorMessage===void 0?delete output.errorMessage:output.errorMessage=mappedStop.errorMessage,output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")};for await(let event of withResponsesCompletionGrace(openaiStream))if(await options?.onProviderStreamEvent?.(event,model),event.type==="response.created")output.responseId=event.response.id;else if(event.type==="response.output_item.added")createSlot(event.output_index,event.item);else if(event.type==="response.reasoning_summary_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.reasoning_summary_part.done"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=`
|
|
3
|
+
`),images=content.filter(c=>c.type==="image"),hasText=textResult.length>0;if(images.length===0||!model.input.includes("image"))return sanitizeSurrogates(hasText?textResult:images.length>0?"(see attached image)":"(no tool output)");let output=[];hasText&&output.push({type:"input_text",text:sanitizeSurrogates(textResult)});for(let image of images)output.push({type:"input_image",detail:"auto",image_url:`data:${image.mimeType};base64,${image.data}`});return output}var CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL="custom",ULTRAFAST_DOCUMENTED_MODEL_IDS=new Set(["gpt-6-astra","gpt-6.1-sol"]);function isResponseCustomToolCallItem(item){return item.type==="custom_tool_call"}function isFreeformTool(tool){return tool.freeform!==void 0}function isFreeformToolName(toolName,tools){return tools?.some(tool=>tool.name===toolName&&isFreeformTool(tool))??!1}function getFreeformToolInput(argumentsValue){return typeof argumentsValue.input=="string"?argumentsValue.input:JSON.stringify(argumentsValue)}function contextProvenanceForInput(message,seal){let provenance=getContextProvenance(message);if(!provenance)return;let fingerprint=contextProvenanceFingerprint(message);if(fingerprint===void 0)return;let stored=provenance.integrity;return stored===void 0&&seal?(provenance.integrity=fingerprint,provenance):stored===fingerprint?provenance:void 0}function withContextProvenance(item,message,seal){let provenance=contextProvenanceForInput(message,seal);return provenance&&Object.defineProperty(item,CONTEXT_PROVENANCE_FIELD,{value:provenance,enumerable:!1}),item}function resolveResponsesDeferredToolsMode(compat){if(compat?.supportsAdditionalTools)return"additional-tools";if(!compat?.siwc)return compat?.supportsToolSearch?"tool-search":void 0}function resolveResponsesToolPlacement(messages,supportsToolAdditions){let transcriptTools=resolveTranscriptTools(messages,supportsToolAdditions),{deferred}=splitDeferredTools({messages:[...messages],tools:getCurrentTools(messages)},supportsToolAdditions);return{requestTools:transcriptTools.requestTools.filter(tool=>!deferred.has(tool.name)),anchorsAdditions:transcriptTools.anchorsAdditions,deferred}}function convertResponsesMessages(model,context,allowedToolCallProviders,options){let normalizedContext=resolveTranscript(context,options?.supportsMidConvoSystemMessages),messages=[],deferredToolsMode=resolveResponsesDeferredToolsMode(options),toolPlacement=resolveResponsesToolPlacement(normalizedContext.messages,deferredToolsMode!==void 0),declaredTools=getDeclaredTools(normalizedContext.messages),loadedToolNames=new Set,normalizeIdPart=part=>{let sanitized=part.replace(/[^a-zA-Z0-9_-]/g,"_");return(sanitized.length>64?sanitized.slice(0,64):sanitized).replace(/_+$/,"")},buildForeignResponsesItemId=itemId=>{let normalized=`fc_${shortHash(itemId)}`;return normalized.length>64?normalized.slice(0,64):normalized},normalizeToolCallId=(id,_targetModel,source)=>{if(!id.includes("|"))return normalizeIdPart(id);let[callId,itemId]=id.split("|"),normalizedCallId=normalizeIdPart(callId);if(itemId===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL)return`${normalizedCallId}|${CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`;if(!allowedToolCallProviders.has(model.provider))return normalizeIdPart(id);let normalizedItemId=source.provider!==model.provider||source.api!==model.api?buildForeignResponsesItemId(itemId):normalizeIdPart(itemId);return normalizedItemId.startsWith("fc_")||(normalizedItemId=normalizeIdPart(`fc_${normalizedItemId}`)),`${normalizedCallId}|${normalizedItemId}`},transformedMessages=transformMessages(normalizedContext.messages,model,normalizeToolCallId,{preserveThinking:options?.preserveThinking,preserveTextSignatures:options?.preserveTextSignatures}),appendSystemToolAdditions=(message,seed)=>{let tools=toolPlacement.anchorsAdditions?(message.toolsAdded??[]).filter(tool=>!loadedToolNames.has(tool.name)):[];if(tools.length===0)return;for(let tool of tools)loadedToolNames.add(tool.name);if(options?.supportsAdditionalTools){messages.push({type:"additional_tools",role:"developer",tools:convertResponsesTools(tools,options.toolOptions)});return}if(!options?.supportsToolSearch)return;let names=tools.map(tool=>tool.name),callId=`pi_tool_load_${shortHash(`${seed}:${names.join(",")}`)}`;messages.push({type:"tool_search_call",call_id:callId,execution:"client",status:"completed",arguments:{query:names.join(" "),limit:names.length}}),messages.push({type:"tool_search_output",call_id:callId,execution:"client",status:"completed",tools:convertResponsesTools(tools,{...options.toolOptions,toolSearchResult:!0})})},includeInitialSystemMessage=options?.includeSystemPrompt??!0,compat=model.compat,instructionRole=model.compat?.siwc||model.reasoning&&compat?.supportsDeveloperRole!==!1?"developer":"system",msgIndex=0,sourceIndex=0;for(let msg of transformedMessages){let isLeadingSystemMessage=sourceIndex++===0&&msg.role==="system";if(msg.role==="configurationUpdate"){if(!supportsConfigurationUpdate(model)||model.compat?.siwc)continue;messages[messages.length-1]?.type==="configuration_update"?messages[messages.length-1]={type:"configuration_update",reasoning:{effort:msg.effort}}:messages.push({type:"configuration_update",reasoning:{effort:msg.effort}});continue}if(msg.role==="system"){if(isLeadingSystemMessage||appendSystemToolAdditions(msg,`system:${msgIndex}`),!isLeadingSystemMessage||includeInitialSystemMessage){let text=isLeadingSystemMessage?getSystemMessageText(msg):renderSystemMessageUpdate(msg);if(text.length>0&&isLeadingSystemMessage&&options?.systemPromptCacheBreakpoint===!0){let block={type:"input_text",text:sanitizeSurrogates(text),prompt_cache_breakpoint:{mode:"explicit"}};messages.push({role:instructionRole,content:[block]})}else text.length>0&&messages.push({role:instructionRole,content:sanitizeSurrogates(text)})}}else if(msg.role==="user")if(typeof msg.content=="string")messages.push(withContextProvenance({role:"user",content:[{type:"input_text",text:sanitizeSurrogates(msg.content)}]},msg,options?.sealContextProvenance));else{let content=msg.content.map(item=>item.type==="text"?{type:"input_text",text:sanitizeSurrogates(item.text)}:{type:"input_image",detail:"auto",image_url:`data:${item.mimeType};base64,${item.data}`});if(content.length===0)continue;messages.push(withContextProvenance({role:"user",content},msg,options?.sealContextProvenance))}else if(msg.role==="assistant"){let output=[],assistantMsg=msg,isSameProviderAndApi=assistantMsg.provider===model.provider&&assistantMsg.api===model.api,isSameModel=isSameProviderAndApi&&assistantMsg.model===model.id,isDifferentModel=isSameProviderAndApi&&assistantMsg.model!==model.id,textBlockIndex=0,pushAssistantText=(text,textSignature)=>{let parsedSignature=parseTextSignature(textSignature),fallbackMessageId=textBlockIndex===0?`msg_pi_${msgIndex}`:`msg_pi_${msgIndex}_${textBlockIndex}`;textBlockIndex++;let msgId=parsedSignature?.id;msgId?msgId.length>64&&(msgId=`msg_${shortHash(msgId)}`):msgId=fallbackMessageId,output.push({type:"message",role:"assistant",content:[{type:"output_text",text:sanitizeSurrogates(text),annotations:[]}],status:"completed",id:msgId,phase:parsedSignature?.phase})};for(let block of msg.content)if(block.type==="thinking"){let reasoningItem=parseReasoningSignature(block.thinkingSignature);reasoningItem?output.push(reasoningItem):block.thinkingSignature&&block.thinking.trim()!==""&&pushAssistantText(block.thinking)}else if(block.type==="providerNative"){let raw=block.raw;isSameModel&&block.subtype==="web_search_call"&&raw!==null&&typeof raw=="object"&&"type"in raw&&raw.type==="web_search_call"&&"id"in raw&&typeof raw.id=="string"&&"action"in raw&&"status"in raw&&(raw.status==="completed"||raw.status==="failed")&&output.push(raw)}else if(block.type==="text"){let textBlock=block;pushAssistantText(textBlock.text,textBlock.textSignature)}else if(block.type==="toolCall"){let toolCall=block,[callId,itemIdRaw]=toolCall.id.split("|"),customInputProperty=options?.grammarToolInputProperties?.get(toolCall.name),isPersistedFreeform=itemIdRaw===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL,isFreeform=isFreeformToolName(toolCall.name,declaredTools)||isPersistedFreeform,itemId=isPersistedFreeform?void 0:itemIdRaw,itemIdPrefix=customInputProperty===void 0?"fc_":"ctc_";(isDifferentModel||!itemId?.startsWith(itemIdPrefix))&&(itemId=void 0);let canReplayNamespace=isSameModel||toolPlacement.deferred.has(toolCall.name);customInputProperty!==void 0?output.push({type:"custom_tool_call",...itemId!==void 0?{id:itemId}:{},call_id:callId,name:toolCall.name,input:sanitizeSurrogates(getGrammarToolInput(toolCall.name,toolCall.arguments,customInputProperty)),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):isFreeform?output.push({type:"custom_tool_call",call_id:callId,name:toolCall.name,input:getFreeformToolInput(toolCall.arguments),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):output.push({type:"function_call",...itemId?.startsWith("fc_")?{id:itemId}:{},call_id:callId,name:toolCall.name,arguments:JSON.stringify(toolCall.arguments),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}})}if(output.length===0)continue;messages.push(...output.map(item=>withContextProvenance(item,msg,options?.sealContextProvenance)))}else if(msg.role==="toolResult"){let[callId,itemIdRaw]=msg.toolCallId.split("|"),output=convertToolResultOutput(model,msg.content),customInputProperty=options?.grammarToolInputProperties?.get(msg.toolName),isPersistedFreeform=itemIdRaw===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL;customInputProperty!==void 0?messages.push(withContextProvenance({type:"custom_tool_call_output",call_id:callId,output},msg,options?.sealContextProvenance)):isFreeformToolName(msg.toolName,declaredTools)||isPersistedFreeform?messages.push(withContextProvenance({type:"custom_tool_call_output",call_id:callId,name:msg.toolName,output},msg,options?.sealContextProvenance)):messages.push(withContextProvenance({type:"function_call_output",call_id:callId,output},msg,options?.sealContextProvenance));let deferredTools=[];for(let name of msg.addedToolNames??[]){let tool=toolPlacement.deferred.get(name);!tool||loadedToolNames.has(name)||(loadedToolNames.add(name),deferredTools.push(tool))}if(deferredTools.length>0&&deferredToolsMode==="additional-tools")messages.push(withContextProvenance({type:"additional_tools",role:"developer",tools:convertResponsesTools(deferredTools,options?.toolOptions)},msg,options?.sealContextProvenance));else if(deferredTools.length>0&&deferredToolsMode==="tool-search"){let names=deferredTools.map(tool=>tool.name),searchCallId=`pi_tool_load_${shortHash(`${msg.toolCallId}:${names.join(",")}`)}`;messages.push(withContextProvenance({type:"tool_search_call",call_id:searchCallId,execution:"client",status:"completed",arguments:{query:names.join(" "),limit:names.length}},msg,options?.sealContextProvenance)),messages.push(withContextProvenance({type:"tool_search_output",call_id:searchCallId,execution:"client",status:"completed",tools:convertResponsesTools(deferredTools,{...options?.toolOptions,toolSearchResult:!0})},msg,options?.sealContextProvenance))}}isLeadingSystemMessage||msgIndex++}return messages}function convertResponsesTools(tools,options){let defaultStrict=options?.strict===void 0?!1:options.strict,supportsStrictMode=options?.supportsStrictMode??!0,supportsOpenAIGrammarTools=options?.supportsOpenAIGrammarTools??!1;return[...tools].sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0).map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);if(grammar)return{type:"custom",name:tool.name,description:tool.description,format:{type:"grammar",syntax:grammar.format,definition:grammar.definition},...options?.toolSearchResult?{defer_loading:!0}:{}};if(tool.freeform)return{type:"custom",name:tool.name,description:tool.description,format:tool.freeform,...options?.toolSearchResult?{defer_loading:!0}:{}};let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode)??defaultStrict,functionTool={type:"function",name:tool.name,description:tool.description,parameters:getJsonSchemaToolParameters(tool,strict===!0),...options?.toolSearchResult?{defer_loading:!0}:{}};return supportsStrictMode&&(functionTool.strict=strict),functionTool})}function getCustomToolCallInput(block){let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""}function appendCustomToolCallInput(block,nextInput,close){let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta}var MAX_NATIVE_IMAGE_BASE64_CHARS=24*1024*1024;function readNativeImageGenerationCall(value){if(!(typeof value!="object"||value===null||!("type"in value)||!("status"in value))&&!(value.type!=="image_generation_call"||typeof value.status!="string"))return{type:"image_generation_call",..."id"in value&&typeof value.id=="string"?{id:value.id}:{},status:value.status,..."result"in value&&(typeof value.result=="string"||value.result===null)?{result:value.result}:{},..."revised_prompt"in value&&typeof value.revised_prompt=="string"?{revised_prompt:value.revised_prompt}:{}}}function isValidBase64(value){return value.length>0&&value.length%4===0&&/^[A-Za-z0-9+/]*={0,2}$/.test(value)}function reconcileNativeImageGenerationCall(item){return item.status!=="completed"?{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:item.status}:typeof item.result!="string"||!isValidBase64(item.result)?{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"malformed"}:{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"completed",result:item.result,...item.revised_prompt?.trim()?{revised_prompt:item.revised_prompt}:{}}}async function processResponsesStream(openaiStream,output,stream,model,options){enableAssistantCapture(stream);let sawTerminalResponseEvent=!1,nativeImageBase64Chars=0,outputSlots=new Map,reasoningBlocksById=new Map,nativeImageCharsByOutputIndex=new Map,finalizedNativeImageOutputIndexes=new Set,applyMessagePhaseStopReason=item=>{item.type==="message"&&item.phase==="final_answer"&&(output.stopReason="stop")},getSlot=(outputIndex,type)=>{let slot=outputSlots.get(outputIndex);return slot?.type===type?slot:void 0},pushToolCallDelta=(slot,delta)=>{delta!==void 0&&stream.push({type:"toolcall_delta",contentIndex:slot.contentIndex,delta,partial:output})},createSlot=(outputIndex,item)=>{if(item.type==="reasoning"){let block2={type:"thinking",thinking:""};output.content.push(block2);let slot2={type:"thinking",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"thinking_start",contentIndex:slot2.contentIndex,partial:output}),slot2}if(item.type==="message"){applyMessagePhaseStopReason(item);let block2={type:"text",text:""};output.content.push(block2);let slot2={type:"text",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"text_start",contentIndex:slot2.contentIndex,partial:output}),slot2}if(item.type==="function_call"){let block2={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:{},...item.namespace!==void 0?{namespace:item.namespace}:{},partialJson:item.arguments||""};output.content.push(block2);let slot2={type:"toolCall",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"toolcall_start",contentIndex:slot2.contentIndex,partial:output},{rawArgumentPrefix:block2.partialJson}),slot2}if(isResponseCustomToolCallItem(item)){let inputProperty=options?.grammarToolInputProperties?.get(item.name)??"input",input=item.input||"",block2={type:"toolCall",id:`${item.call_id}|${item.id??CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`,name:item.name,arguments:{[inputProperty]:input},...item.namespace!==void 0?{namespace:item.namespace}:{},customInput:{property:inputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}};output.content.push(block2);let slot2={type:"toolCall",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"toolcall_start",contentIndex:slot2.contentIndex,partial:output}),slot2}let imageItem=readNativeImageGenerationCall(item),block={type:"providerNative",subtype:item.type,raw:imageItem?reconcileNativeImageGenerationCall(imageItem):item},slot={type:"providerNative",block,contentIndex:output.content.length};return imageItem&&reconcileNativeImageSlot(outputIndex,slot,imageItem),output.content.push(block),outputSlots.set(outputIndex,slot),pushAssistantProgress(stream,{type:"message_block_state",contentIndex:slot.contentIndex,phase:"insert",block}),slot},getOrCreateSlot=(outputIndex,item)=>outputSlots.get(outputIndex)??createSlot(outputIndex,item);function scrubNativeImageResults(){for(let block of output.content){if(block.type!=="providerNative"||block.subtype!=="image_generation_call")continue;let item=readNativeImageGenerationCall(block.raw);typeof item?.result=="string"&&(block.raw={type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"malformed"})}nativeImageBase64Chars=0,nativeImageCharsByOutputIndex.clear()}function reconcileNativeImageSlot(outputIndex,slot,item){let reconciled=reconcileNativeImageGenerationCall(item),previousChars=nativeImageCharsByOutputIndex.get(outputIndex)??0,nextChars=typeof reconciled.result=="string"?reconciled.result.length:0,nextTotal=nativeImageBase64Chars-previousChars+nextChars;if(nextTotal>MAX_NATIVE_IMAGE_BASE64_CHARS)throw scrubNativeImageResults(),new Error("Native image generation results exceed the 24 MiB base64 limit");nativeImageBase64Chars=nextTotal,nextChars>0?nativeImageCharsByOutputIndex.set(outputIndex,nextChars):nativeImageCharsByOutputIndex.delete(outputIndex),slot.block.subtype="image_generation_call",slot.block.raw=reconciled}let backfillNativeImageGenerationCalls=responseOutput=>{for(let[outputIndex,outputItem]of responseOutput.entries()){if(finalizedNativeImageOutputIndexes.has(outputIndex))continue;let imageItem=readNativeImageGenerationCall(outputItem);if(!imageItem)continue;let existingSlot=getSlot(outputIndex,"providerNative"),slot=existingSlot??createSlot(outputIndex,outputItem);existingSlot&&reconcileNativeImageSlot(outputIndex,existingSlot,imageItem),slot&&pushAssistantProgress(stream,{type:"message_block_state",contentIndex:slot.contentIndex,phase:"end",block:slot.block}),outputSlots.delete(outputIndex)}},backfillReasoningSignatures=responseOutput=>{for(let item of responseOutput){if(item.type!=="reasoning"||!item.encrypted_content)continue;let block=reasoningBlocksById.get(item.id);if(!block?.thinkingSignature)continue;let storedItem=parseReasoningSignature(block.thinkingSignature);!storedItem||storedItem.encrypted_content||(block.thinkingSignature=JSON.stringify({...storedItem,encrypted_content:item.encrypted_content}))}},finalizeResponse=response=>{sawTerminalResponseEvent=!0,backfillReasoningSignatures(response.output??[]),backfillNativeImageGenerationCalls(response.output??[]),response?.id&&(output.responseId=response.id);let promptCacheDiagnostics=parsePromptCacheDiagnostics(response?.prompt_cache_diagnostics);if(promptCacheDiagnostics&&(output.promptCacheDiagnostics=promptCacheDiagnostics),response?.usage){let inputDetails=response.usage.input_tokens_details,cachedTokens=inputDetails?.cached_tokens||0,cacheWriteTokens=inputDetails?.cache_write_tokens??inputDetails?.cache_creation_tokens??0,reasoning=reportedCount(response.usage.output_tokens_details?.reasoning_tokens);output.usage={input:Math.max(0,(response.usage.input_tokens||0)-cachedTokens-cacheWriteTokens),output:response.usage.output_tokens||0,cacheRead:cachedTokens,cacheWrite:cacheWriteTokens,...reasoning===void 0?{}:{reasoning},totalTokens:response.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(calculateCost(model,output.usage),options?.applyServiceTierPricing){let serviceTier=options.resolveServiceTier?options.resolveServiceTier(response?.service_tier,options.serviceTier):response?.service_tier??options.serviceTier;options.applyServiceTierPricing(output.usage,serviceTier)}let status=response?.status,incompleteDetails=response?.incomplete_details,incompleteReason=typeof incompleteDetails?.reason=="string"?incompleteDetails.reason:void 0;output.rawStopReason=incompleteReason?`${status}.${incompleteReason}`:status;let mappedStop=mapStopReason(status,incompleteReason);output.stopReason=mappedStop.stopReason,mappedStop.errorMessage===void 0?delete output.errorMessage:output.errorMessage=mappedStop.errorMessage,output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")};for await(let event of withResponsesCompletionGrace(openaiStream))if(await options?.onProviderStreamEvent?.(event,model),event.type==="response.created")output.responseId=event.response.id;else if(event.type==="response.output_item.added")createSlot(event.output_index,event.item);else if(event.type==="response.reasoning_summary_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.reasoning_summary_part.done"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=`
|
|
4
4
|
|
|
5
5
|
`,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:`
|
|
6
6
|
|