@code-yeongyu/senpi 2026.11.10-1 → 2026.11.10-3
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 +42 -0
- package/dist/bundle/chunks/{args-77GYOPEO.js → args-HFYB6URH.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-YFZ734T3.js → azure-openai-responses-MNN2TINI.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZUQCYIRY.js → chunk-2ODGHBUD.js} +1 -1
- package/dist/bundle/chunks/{chunk-YPAQXRP3.js → chunk-47T6YMI2.js} +2 -2
- package/dist/bundle/chunks/{chunk-I5ASHSLZ.js → chunk-4JMGWVRH.js} +1 -1
- package/dist/bundle/chunks/{chunk-MSDBBOB2.js → chunk-5H43O4MA.js} +1 -1
- package/dist/bundle/chunks/{chunk-3IYWH6RO.js → chunk-6Q7Y2G5A.js} +1 -1
- package/dist/bundle/chunks/{chunk-X4XWAB3J.js → chunk-AC6MDRAE.js} +81 -81
- package/dist/bundle/chunks/{chunk-33MZJTQ3.js → chunk-B4WD5XHP.js} +1 -1
- package/dist/bundle/chunks/{chunk-V5FSENW6.js → chunk-COKX65TE.js} +1 -1
- package/dist/bundle/chunks/{chunk-LHEP3ACI.js → chunk-DEQLHN2J.js} +2 -2
- package/dist/bundle/chunks/{chunk-EJB5E2JK.js → chunk-DHAAWL2H.js} +1 -1
- package/dist/bundle/chunks/{chunk-2EJ4BGBM.js → chunk-DHORIIVQ.js} +1 -1
- package/dist/bundle/chunks/{chunk-GPXZTSEX.js → chunk-DIHIEJFV.js} +3 -3
- package/dist/bundle/chunks/{chunk-NH7SYIGN.js → chunk-DLPV4B3R.js} +1 -1
- package/dist/bundle/chunks/{chunk-RCHIMH7N.js → chunk-DQY26AX3.js} +1 -1
- package/dist/bundle/chunks/{chunk-Y7Z7XPUF.js → chunk-DZQA5LVN.js} +1 -1
- package/dist/bundle/chunks/{chunk-2CNSCMYC.js → chunk-E5O4SP5I.js} +1 -1
- package/dist/bundle/chunks/{chunk-3Q5ZENSD.js → chunk-E6ZBTSC6.js} +1 -1
- package/dist/bundle/chunks/{chunk-HI5JSLG5.js → chunk-H3VJVKUK.js} +4 -4
- package/dist/bundle/chunks/{chunk-L6NRDUWJ.js → chunk-HZDKQOWB.js} +1 -1
- package/dist/bundle/chunks/chunk-IREUIMFE.js +11 -0
- package/dist/bundle/chunks/{chunk-FAFIGBUD.js → chunk-JSD6O3RJ.js} +2 -2
- package/dist/bundle/chunks/{chunk-BELNOPAI.js → chunk-L3KVP7VJ.js} +3 -3
- package/dist/bundle/chunks/{chunk-7MN7YNO5.js → chunk-L7DGTA3L.js} +1 -1
- package/dist/bundle/chunks/{chunk-J2NGJKXL.js → chunk-LXINMDMX.js} +1 -1
- package/dist/bundle/chunks/{chunk-H33A33M4.js → chunk-M2VJVJMK.js} +1 -1
- package/dist/bundle/chunks/{chunk-ARUV3US4.js → chunk-NN7NESW2.js} +1 -1
- package/dist/bundle/chunks/{chunk-2U6HXWXS.js → chunk-NNQ34ZDW.js} +1 -1
- package/dist/bundle/chunks/chunk-NQKCJQHB.js +2 -0
- package/dist/bundle/chunks/{chunk-TGW4R7SI.js → chunk-O5WJVIEU.js} +1 -1
- package/dist/bundle/chunks/{chunk-O3FG6HML.js → chunk-PJI5GT7U.js} +1 -1
- package/dist/bundle/chunks/{chunk-BPNSOZ2C.js → chunk-QUVSIW2R.js} +1 -1
- package/dist/bundle/chunks/{chunk-WXYMAUFX.js → chunk-QX7WD3IM.js} +1 -1
- package/dist/bundle/chunks/{chunk-Y4ONXQMR.js → chunk-RGHVPUUX.js} +1 -1
- package/dist/bundle/chunks/{chunk-RYPM5BZQ.js → chunk-S7NAJQB3.js} +1 -1
- package/dist/bundle/chunks/{chunk-LT353NSF.js → chunk-T4CUD7RF.js} +1 -1
- package/dist/bundle/chunks/{chunk-J7FW7MED.js → chunk-TCZORL3V.js} +1 -1
- package/dist/bundle/chunks/{chunk-KU72IKV5.js → chunk-VGSWOLIY.js} +1 -1
- package/dist/bundle/chunks/{chunk-DBQBJTMF.js → chunk-VUY4BZDI.js} +1 -1
- package/dist/bundle/chunks/chunk-XI6THO4F.js +2 -0
- package/dist/bundle/chunks/{chunk-THYEZBUG.js → chunk-Z2C5N2LM.js} +2 -2
- package/dist/bundle/chunks/{cli-main-VG3C2EXI.js → cli-main-ZTT3N4DO.js} +1 -1
- package/dist/bundle/chunks/{credential-accounts-LVVPKFEY.js → credential-accounts-5KHVGSCY.js} +1 -1
- package/dist/bundle/chunks/{dispatch-EP35KKJ3.js → dispatch-YUYZQXRP.js} +1 -1
- package/dist/bundle/chunks/{hand-entry-3LQKUTYS.js → hand-entry-UV5XPMBF.js} +3 -3
- package/dist/bundle/chunks/{headless-host-HKGNJGYT.js → headless-host-53UMJMM6.js} +1 -1
- package/dist/bundle/chunks/{health-write-FBF74QJ7.js → health-write-JLSF5EVV.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-5SCPY3OH.js → help-fast-path-552QLMWT.js} +1 -1
- package/dist/bundle/chunks/{host-command-CCASS7W4.js → host-command-BZN7WYYV.js} +1 -1
- package/dist/bundle/chunks/{host-lifecycle-WWC7HXQ6.js → host-lifecycle-TNHASSFJ.js} +1 -1
- package/dist/bundle/chunks/host-lifecycle.js +1 -1
- package/dist/bundle/chunks/{host-session-command-YJB2FLKU.js → host-session-command-O5WYHZXH.js} +1 -1
- package/dist/bundle/chunks/{host-socket-request-DMYXC56U.js → host-socket-request-QN4Q2P5E.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-CUN3WMUF.js → interactive-mode-OCU4NDPC.js} +1 -1
- package/dist/bundle/chunks/{login-health-EVXVLHB2.js → login-health-TOSQT5RG.js} +1 -1
- package/dist/bundle/chunks/{main-P7XRC2OI.js → main-CNDP6HCF.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-244X3P6L.js → multi-session-host-ODGJAGJP.js} +11 -8
- package/dist/bundle/chunks/openai-codex-responses-VRGOAFEG.js +10 -0
- package/dist/bundle/chunks/{openai-responses-NIVBWE2H.js → openai-responses-I7PXRWCM.js} +2 -2
- package/dist/bundle/chunks/{package-manager-cli-UVWJOQA3.js → package-manager-cli-HSPUG4RJ.js} +1 -1
- package/dist/bundle/chunks/{role-HQUN4XXK.js → role-AEOLJRTP.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-F3BEMXBE.js → rotation-stream-E3FJFHXJ.js} +1 -1
- package/dist/bundle/chunks/rpc-mode-KOZPXU3U.js +2 -0
- package/dist/bundle/chunks/{rpc-monitor-source-C6VQ3BC4.js → rpc-monitor-source-PGTDSGWP.js} +1 -1
- package/dist/bundle/chunks/{run-attached-tui-R3RB5P7G.js → run-attached-tui-4AENRP7P.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-5FG2OKSR.js → schedule-command-SG44FE23.js} +1 -1
- package/dist/bundle/chunks/session-control-endpoint-5A24JYPE.js +3 -0
- package/dist/bundle/chunks/{session-picker-2FZSNFS7.js → session-picker-73YRS3GE.js} +1 -1
- package/dist/bundle/chunks/{session-slot-CZGQQCOC.js → session-slot-RH7JLO3F.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +199 -196
- package/dist/bundle/chunks/{state-store-S7QAESIF.js → state-store-IECVTYXC.js} +1 -1
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/host-supervisor.js +1 -1
- 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-runtime.d.ts +2 -0
- package/dist/core/agent-session-runtime.js +5 -0
- package/dist/core/agent-session.d.ts +13 -3
- package/dist/core/agent-session.js +89 -18
- package/dist/core/assistant-error-redaction.d.ts +9 -0
- package/dist/core/assistant-error-redaction.js +27 -0
- package/dist/core/config-reference-redaction.js +90 -10
- package/dist/core/context-files.d.ts +10 -0
- package/dist/core/context-files.js +58 -12
- package/dist/core/egress/wire.d.ts +13 -0
- package/dist/core/extensions/builtin/config-reload/change-groups.js +6 -2
- package/dist/core/extensions/builtin/mcp/auth/catalog-identity.js +32 -8
- package/dist/core/extensions/builtin/mcp/auth/oauth-grant.d.ts +43 -0
- package/dist/core/extensions/builtin/mcp/auth/oauth-grant.js +196 -0
- package/dist/core/extensions/builtin/mcp/auth/oauth-provider.d.ts +4 -17
- package/dist/core/extensions/builtin/mcp/auth/oauth-provider.js +64 -75
- package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.d.ts +1 -1
- package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.js +25 -4
- package/dist/core/extensions/builtin/mcp/auth/oauth.js +10 -7
- package/dist/core/extensions/builtin/mcp/auth/token-store.d.ts +18 -0
- package/dist/core/extensions/builtin/mcp/auth/token-store.js +3 -0
- package/dist/core/extensions/builtin/mcp/catalog-cache.js +7 -6
- package/dist/core/extensions/builtin/mcp/catalog.js +3 -2
- package/dist/core/extensions/builtin/mcp/invocation.js +6 -0
- package/dist/core/extensions/builtin/mcp/service-register.js +16 -2
- package/dist/core/extensions/builtin/mcp/service-tools-changed.js +61 -54
- package/dist/core/extensions/builtin/mcp/startup-race.d.ts +2 -0
- package/dist/core/extensions/builtin/mcp/startup-race.js +25 -7
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-2.js +6 -6
- package/dist/core/extensions/loader.js +24 -4
- package/dist/core/extensions/runner.d.ts +9 -1
- package/dist/core/extensions/runner.js +9 -4
- package/dist/core/extensions/types.d.ts +17 -3
- package/dist/core/hand/hook-advertise.d.ts +41 -0
- package/dist/core/hand/hook-advertise.js +98 -0
- package/dist/core/hand/hook-contract.d.ts +66 -0
- package/dist/core/hand/hook-contract.js +138 -0
- package/dist/core/open-timing.d.ts +2 -0
- package/dist/core/open-timing.js +7 -1
- package/dist/core/resource-loader.js +2 -0
- package/dist/core/retry-fallback/log.d.ts +7 -1
- package/dist/core/retry-fallback/log.js +82 -5
- package/dist/core/retry-fallback/model-config-error.js +2 -1
- package/dist/core/session-manager.d.ts +2 -0
- package/dist/core/session-manager.js +15 -1
- package/dist/core/settings-manager.d.ts +6 -0
- package/dist/core/settings-manager.js +8 -0
- package/dist/core/turn-origin.d.ts +19 -13
- package/dist/core/turn-origin.js +34 -30
- package/dist/core/ultrafast-lanes.d.ts +1 -0
- package/dist/core/ultrafast-lanes.js +4 -2
- package/dist/modes/interactive/components/footer.d.ts +23 -5
- package/dist/modes/interactive/components/footer.js +45 -16
- package/dist/modes/interactive/interactive-mode.js +9 -1
- package/dist/modes/interactive/session-control-rpc-commands.d.ts +1 -1
- package/dist/modes/interactive/session-control-rpc-commands.js +5 -0
- package/dist/modes/rpc/admit-external-message-command.d.ts +2 -2
- package/dist/modes/rpc/admit-external-message-command.js +2 -10
- package/dist/modes/rpc/compact-admission-validation.js +4 -1
- package/dist/modes/rpc/connection-handler.d.ts +2 -0
- package/dist/modes/rpc/connection-handler.js +20 -8
- package/dist/modes/rpc/connection-roles.d.ts +2 -0
- package/dist/modes/rpc/connection-roles.js +4 -0
- package/dist/modes/rpc/custom-capability.d.ts +4 -0
- package/dist/modes/rpc/custom-capability.js +4 -0
- package/dist/modes/rpc/delegated-drive-origin.d.ts +6 -6
- package/dist/modes/rpc/delegated-drive-origin.js +7 -8
- package/dist/modes/rpc/delegation-declaration.d.ts +2 -0
- package/dist/modes/rpc/delegation-declaration.js +5 -1
- package/dist/modes/rpc/effect-commands.d.ts +21 -0
- package/dist/modes/rpc/host-capabilities.d.ts +1 -0
- package/dist/modes/rpc/host-capabilities.js +5 -1
- package/dist/modes/rpc/host-observe-request.d.ts +2 -0
- package/dist/modes/rpc/host-observe-request.js +6 -1
- package/dist/modes/rpc/host-park-ledger.d.ts +19 -0
- package/dist/modes/rpc/host-park-ledger.js +110 -0
- package/dist/modes/rpc/lifecycle-delivery.js +4 -1
- package/dist/modes/rpc/loopless-tool-handlers.d.ts +6 -0
- package/dist/modes/rpc/loopless-tool-handlers.js +14 -1
- package/dist/modes/rpc/media-placeholders.js +1 -0
- package/dist/modes/rpc/method-classes-schema-host.d.ts +42 -1
- package/dist/modes/rpc/method-classes-schema-host.js +24 -21
- package/dist/modes/rpc/method-classes-schema.d.ts +42 -1
- package/dist/modes/rpc/method-classes-schema.js +5 -2
- package/dist/modes/rpc/method-classes.d.ts +2 -0
- package/dist/modes/rpc/method-classes.js +3 -0
- package/dist/modes/rpc/multi-session-host.js +1 -1
- package/dist/modes/rpc/rpc-host-command-types.d.ts +14 -1
- package/dist/modes/rpc/rpc-host-response-types.d.ts +21 -0
- package/dist/modes/rpc/session-attachment-gate.js +2 -0
- package/dist/modes/rpc/session-binding.d.ts +1 -0
- package/dist/modes/rpc/session-binding.js +6 -1
- package/dist/modes/rpc/session-connection-context.d.ts +2 -0
- package/dist/modes/rpc/session-connection-context.js +4 -0
- package/dist/modes/rpc/session-registry-attach.d.ts +2 -0
- package/dist/modes/rpc/session-registry-attach.js +15 -11
- package/dist/modes/rpc/session-registry-claims.js +2 -0
- package/dist/modes/rpc/session-registry-open.js +13 -7
- package/dist/modes/rpc/session-registry-opening.js +2 -1
- package/dist/modes/rpc/session-registry-types.d.ts +4 -0
- package/dist/modes/rpc/session-registry.d.ts +3 -0
- package/dist/modes/rpc/session-registry.js +27 -3
- package/dist/modes/rpc/session-router-close.js +1 -0
- package/dist/modes/rpc/session-router-context.d.ts +4 -2
- package/dist/modes/rpc/session-router-context.js +3 -0
- package/dist/modes/rpc/session-router-host-reads.js +1 -0
- package/dist/modes/rpc/session-router-occupancy.js +10 -1
- package/dist/modes/rpc/session-router-open-result.d.ts +12 -0
- package/dist/modes/rpc/session-router-open-result.js +63 -0
- package/dist/modes/rpc/session-router-open.d.ts +3 -0
- package/dist/modes/rpc/session-router-open.js +15 -63
- package/dist/modes/rpc/session-router-park.d.ts +15 -0
- package/dist/modes/rpc/session-router-park.js +176 -0
- package/dist/modes/rpc/session-router-routing.d.ts +1 -1
- package/dist/modes/rpc/session-router-routing.js +7 -0
- package/dist/modes/rpc/session-status-source.js +2 -2
- package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
- package/docs/engine-socket/fixtures/rpc-inbound-samples.json +22 -2
- package/docs/extensions.md +10 -0
- package/docs/rpc.md +50 -0
- package/docs/settings.md +1 -0
- package/docs/usage.md +1 -1
- package/native/socket-secret/prebuilds/win32-arm64/senpi_socket_secret.win32-arm64.node +0 -0
- package/native/socket-secret/prebuilds/win32-x64/senpi_socket_secret.win32-x64.node +0 -0
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-436DNN4Z.js +0 -2
- package/dist/bundle/chunks/chunk-DLAY7CIU.js +0 -2
- package/dist/bundle/chunks/chunk-XH2MWTXA.js +0 -11
- package/dist/bundle/chunks/openai-codex-responses-ABB2J43U.js +0 -10
- package/dist/bundle/chunks/rpc-mode-G4I3HHPB.js +0 -2
- package/dist/bundle/chunks/session-control-endpoint-XWCFLJYC.js +0 -3
|
@@ -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-J2I56WLK.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-J2I56WLK.js";import{parseEntryLine,resolveMovedPath,sessionInfoName,visibleMessage}from"./chunk-GTJJ73DE.js";import{appendToolResultUserWords}from"./chunk-E6ZBTSC6.js";import{SessionWriteFence}from"./chunk-SOMFLLPD.js";import{appendRecordWrites,createAdmissionLine,divergenceWrite,manifestWrite,openSessionStore,openSyncSessionStore,readSessionState,rewriteRecordWrite}from"./chunk-COKX65TE.js";import{dropFailedAssistantTurns}from"./chunk-QX7WD3IM.js";import{copyContextProvenance}from"./chunk-IREUIMFE.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>
|
|
@@ -16,7 +16,7 @@ ${msg.output}
|
|
|
16
16
|
|
|
17
17
|
Command exited with code ${msg.exitCode}`),msg.truncated&&msg.fullOutputPath&&(text+=`
|
|
18
18
|
|
|
19
|
-
[Output truncated. Full output: ${msg.fullOutputPath}]`),text}function createBranchSummaryMessage(summary,fromId,timestamp){return{role:"branchSummary",summary,fromId,timestamp:new Date(timestamp).getTime()}}function createCompactionSummaryMessage(summary,tokensBefore,timestamp,details){return{role:"compactionSummary",summary,tokensBefore,details,timestamp:new Date(timestamp).getTime()}}function createCustomMessage(customType,content,display,details,timestamp){return{role:"custom",customType,content,display,details,timestamp:new Date(timestamp).getTime()}}function convertToLlm(messages){let withContextProvenance=(source,target)=>copyContextProvenance(source,target),environmentMessages=new Set,converted=messages.map(m=>{switch(m.role){case"bashExecution":return m.excludeFromContext?void 0:withContextProvenance(m,{role:"user",content:[{type:"text",text:bashExecutionToText(m)}],timestamp:m.timestamp});case"custom":{if(isContextExcludedCustomMessage(m.customType))return;let content=typeof m.content=="string"?[{type:"text",text:m.content}]:m.content,converted2=withContextProvenance(m,{role:"user",content,timestamp:m.timestamp});return m.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&environmentMessages.add(converted2),converted2}case"branchSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:BRANCH_SUMMARY_PREFIX+m.summary+BRANCH_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"compactionSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:COMPACTION_SUMMARY_PREFIX+m.summary+COMPACTION_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"configurationUpdate":return m;case"system":case"user":case"assistant":case"toolResult":return m;default:{let _exhaustiveCheck=m;return}}}).filter(m=>m!==void 0);return foldEnvironmentContextIntoNextUserMessage(appendToolResultUserWords(dropFailedAssistantTurns(omitProviderRejectedImages(converted))),environmentMessages)}var TRANSPORT_IMAGE_BUDGET_BYTES=24*1024*1024,BLOCKED_IMAGE_PLACEHOLDER="Image reading is disabled.";function dedupeConsecutivePlaceholder(content,placeholder){return content.filter((block,index,blocks)=>!(block.type==="text"&&block.text===placeholder&&index>0&&blocks[index-1].type==="text"&&blocks[index-1].text===placeholder))}function elideOldImages(messages,options){let budgetBytes=options?.budgetBytes??TRANSPORT_IMAGE_BUDGET_BYTES,alwaysKeepNewest=options?.alwaysKeepNewest??1,maxHistoricalImages=options?.maxHistoricalImages,lastAssistantIndex=messages.findLastIndex(message=>message.role==="assistant"),images=[];messages.forEach((message,messageIndex)=>{message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||message.content.forEach((block,blockIndex)=>{block.type==="image"&&images.push({key:`${messageIndex}:${blockIndex}`,bytes:block.data.length,currentTurn:maxHistoricalImages!==void 0&&messageIndex>lastAssistantIndex})})});let imagesToElide=new Set;if(maxHistoricalImages!==void 0){let historical=images.filter(image=>!image.currentTurn),step=Math.max(1,Math.floor(maxHistoricalImages/2)),excess=historical.length-maxHistoricalImages,cutoff=excess>0?Math.ceil(excess/step)*step:0;for(let image of historical.slice(0,cutoff))imagesToElide.add(image.key)}else{let protectedKeys=new Set(images.slice(Math.max(0,images.length-alwaysKeepNewest)).map(image=>image.key)),total=images.reduce((sum,image)=>sum+image.bytes,0);if(total>budgetBytes){let step=Math.max(1,Math.floor(budgetBytes/2)),threshold=Math.ceil((total-budgetBytes)/step)*step,offset=0,elidedBytes=0,straddler;for(let image of images){let start=offset;offset+=image.bytes,!protectedKeys.has(image.key)&&(offset<=threshold?(imagesToElide.add(image.key),elidedBytes+=image.bytes):start<threshold&&straddler===void 0&&(straddler=image))}straddler!==void 0&&total-elidedBytes>budgetBytes&&imagesToElide.add(straddler.key)}}return imagesToElide.size===0?messages:messages.map((message,messageIndex)=>message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some((_block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`))?message:{...message,content:replaceElidedImages(message.content,blockIndex=>imagesToElide.has(`${messageIndex}:${blockIndex}`))})}function convertToLlmForTransport(messages,options){let converted=convertToLlm(messages);return options.blockImages?converted.map(message=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some(block=>block.type==="image"))return message;let replaced=message.content.map(block=>block.type==="image"?{type:"text",text:BLOCKED_IMAGE_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,BLOCKED_IMAGE_PLACEHOLDER)}}):elideOldImages(converted,options)}import{randomBytes,randomUUID as randomUUID4}from"crypto";import{appendFileSync,closeSync,existsSync as existsSync3,mkdirSync as mkdirSync2,openSync,readdirSync,readSync,rmSync as rmSync2,statSync,writeFileSync as writeFileSync2}from"fs";import{appendFile as appendFile2,open as open4,readdir as readdir2,rm as rm3}from"fs/promises";import{basename as basename3,join as join5,resolve as resolve4}from"path";import{StringDecoder as StringDecoder2}from"string_decoder";var OMIT_JSON_VALUE=Symbol("omit-json-value");function transformJson(value,transformString){let transformed=transformJsonValue(value,transformString,"",new WeakSet);if(transformed===OMIT_JSON_VALUE){let serialized=JSON.stringify(value);if(serialized===void 0)throw new SyntaxError("JSON-compatible value expected");return JSON.parse(serialized)}return transformed}function transformJsonValue(value,transformString,key,seen){if(typeof value=="string")return transformString(value);if(typeof value=="number")return Number.isFinite(value)?value:null;if(value===null||typeof value=="boolean")return value;if(typeof value=="bigint")throw new TypeError("Do not know how to serialize a BigInt");if(typeof value>"u"||typeof value=="function"||typeof value=="symbol")return OMIT_JSON_VALUE;if(seen.has(value))throw new TypeError("Converting circular structure to JSON");seen.add(value);let jsonValue=hasJsonSerializer(value)?value.toJSON(key):value;if(jsonValue!==value){let transformed2=transformJsonValue(jsonValue,transformString,key,seen);return seen.delete(value),transformed2}if(Array.isArray(value)){let transformed2=Array.from({length:value.length},(_item,index)=>{let item=value[index],transformedItem=transformJsonValue(item,transformString,String(index),seen);return transformedItem===OMIT_JSON_VALUE?null:transformedItem});return seen.delete(value),transformed2}let transformed={};for(let[key2,item]of Object.entries(value)){let transformedItem=transformJsonValue(item,transformString,String(key2),seen);transformedItem!==OMIT_JSON_VALUE&&Object.defineProperty(transformed,key2,{configurable:!0,enumerable:!0,value:transformedItem,writable:!0})}return seen.delete(value),transformed}function hasJsonSerializer(value){return"toJSON"in value&&typeof value.toJSON=="function"}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}function hasTextOnlyContent(content,allowString){return typeof content=="string"?allowString:Array.isArray(content)?content.every(block=>isRecord(block)&&block.type==="text"&&typeof block.text=="string"):!1}function isWellFormedImageBlock(block){return block.type==="image"&&typeof block.mimeType=="string"&&block.mimeType.startsWith("image/")&&typeof block.data=="string"&&block.data.length>0}function hasSafeToolResultContent(content){return Array.isArray(content)?content.every(block=>isRecord(block)&&(block.type==="text"&&typeof block.text=="string"||isWellFormedImageBlock(block))):!1}function isUsage(value){if(!isRecord(value)||!isRecord(value.cost))return!1;for(let field3 of["input","output","cacheRead","cacheWrite","totalTokens"])if(!isFiniteNumber(value[field3]))return!1;for(let field3 of["input","output","cacheRead","cacheWrite","total"])if(!isFiniteNumber(value.cost[field3]))return!1;return(value.cacheWrite1h===void 0||isFiniteNumber(value.cacheWrite1h))&&(value.reasoning===void 0||isFiniteNumber(value.reasoning))}var base64SignaturePattern=/^[A-Za-z0-9+/]+={0,2}$/;function isValidOpaqueSignature(sig){return typeof sig=="string"&&sig.length>0&&sig.length<=65536}function isValidProviderSignature(sig,providerIsGoogle){return isValidOpaqueSignature(sig)?!providerIsGoogle||sig.length%4===0&&base64SignaturePattern.test(sig):!1}function hasSafeAssistantContent(content,providerIsGoogle){if(!Array.isArray(content))return!1;for(let block of content){if(!isRecord(block)||typeof block.type!="string")return!1;switch(block.type){case"text":if(typeof block.text!="string"||block.textSignature!==void 0&&!isValidProviderSignature(block.textSignature,providerIsGoogle))return!1;break;case"thinking":if(typeof block.thinking!="string"||block.startedAt!==void 0&&!isFiniteNumber(block.startedAt)||block.endedAt!==void 0&&!isFiniteNumber(block.endedAt)||block.redacted!==void 0&&typeof block.redacted!="boolean"||block.thinkingSignature!==void 0&&!isValidProviderSignature(block.thinkingSignature,providerIsGoogle)||block.redacted===!0&&!isValidOpaqueSignature(block.thinkingSignature))return!1;break;case"toolCall":if(typeof block.id!="string"||typeof block.name!="string"||!isRecord(block.arguments)||block.incomplete!==void 0&&block.incomplete!==!0||block.errorMessage!==void 0&&typeof block.errorMessage!="string"||block.thoughtSignature!==void 0&&!isValidProviderSignature(block.thoughtSignature,providerIsGoogle))return!1;break;default:return!1}}return!0}function hasSafeAssistantEnvelope(message){let provider=typeof message.provider=="string"?message.provider:"",providerIsGoogle=provider==="google"||provider==="google-vertex",stopReason=message.stopReason,stopDetails=message.stopDetails,safeStopDetails=stopDetails===void 0||isRecord(stopDetails)&&(stopDetails.type==="sensitive"||stopDetails.type==="refusal"&&(stopDetails.explanation===void 0||typeof stopDetails.explanation=="string"));return typeof message.api=="string"&&typeof message.provider=="string"&&typeof message.model=="string"&&isUsage(message.usage)&&(stopReason==="pending"||stopReason==="stop"||stopReason==="length"||stopReason==="toolUse"||stopReason==="error"||stopReason==="aborted")&&safeStopDetails&&isFiniteNumber(message.timestamp)&&(message.responseModel===void 0||typeof message.responseModel=="string")&&(message.responseId===void 0||typeof message.responseId=="string")&&(message.diagnostics===void 0||Array.isArray(message.diagnostics))&&(message.errorMessage===void 0||typeof message.errorMessage=="string")&&(message.rawStopReason===void 0||typeof message.rawStopReason=="string")&&hasSafeAssistantContent(message.content,providerIsGoogle)}function hasSafeToolResultEnvelope(message){return typeof message.toolCallId=="string"&&message.toolCallId.length>0&&typeof message.toolName=="string"&&message.toolName.length>0&&hasSafeToolResultContent(message.content)&&typeof message.isError=="boolean"&&isFiniteNumber(message.timestamp)&&(message.usage===void 0||isUsage(message.usage))&&(message.addedToolNames===void 0||Array.isArray(message.addedToolNames)&&message.addedToolNames.every(name=>typeof name=="string"))}var CONFIGURATION_UPDATE_EFFORTS=new Set(["off","minimal","low","medium","high","xhigh","max"]);function hasSafeConfigurationUpdate(message){return typeof message.effort=="string"&&CONFIGURATION_UPDATE_EFFORTS.has(message.effort)&&Array.isArray(message.content)&&message.content.length===0&&isFiniteNumber(message.timestamp)}function hasUnsafeRetainedContent(messages){for(let value of messages){if(!isRecord(value)||typeof value.role!="string")return!0;switch(value.role){case"user":if(!isFiniteNumber(value.timestamp)||!hasTextOnlyContent(value.content,!0))return!0;break;case"assistant":if(!hasSafeAssistantEnvelope(value))return!0;break;case"toolResult":if(!hasSafeToolResultEnvelope(value))return!0;break;case"configurationUpdate":if(!hasSafeConfigurationUpdate(value))return!0;break;case"custom":if(typeof value.customType!="string"||typeof value.display!="boolean"||!isFiniteNumber(value.timestamp)||!hasTextOnlyContent(value.content,!0))return!0;break;case"bashExecution":if(typeof value.command!="string"||typeof value.output!="string"||value.exitCode!==void 0&&!isFiniteNumber(value.exitCode)||typeof value.cancelled!="boolean"||typeof value.truncated!="boolean"||value.fullOutputPath!==void 0&&typeof value.fullOutputPath!="string"||value.excludeFromContext!==void 0&&typeof value.excludeFromContext!="boolean"||!isFiniteNumber(value.timestamp))return!0;break;case"compactionSummary":if(typeof value.summary!="string"||!isFiniteNumber(value.tokensBefore)||!isFiniteNumber(value.timestamp))return!0;break;default:return!0}}return!1}function isSafeBoundedValue(value,seen=new Set,depth=0){if(depth>32)return!1;if(value==null)return!0;let kind=typeof value;if(kind==="string"||kind==="number"||kind==="boolean")return!0;if(kind!=="object"||seen.has(value))return!1;if(seen.add(value),Array.isArray(value)){for(let item of value)if(!isSafeBoundedValue(item,seen,depth+1))return!1;return!0}let proto=Object.getPrototypeOf(value);if(proto!==Object.prototype&&proto!==null)return!1;for(let descriptor of Object.values(Object.getOwnPropertyDescriptors(value)))if(descriptor.get!==void 0||descriptor.set!==void 0||!isSafeBoundedValue(descriptor.value,seen,depth+1))return!1;return!0}function projectRetainedMessages(messages){let omittedCalls=new Set;return messages.map(original=>{let message=original,safe=!1;try{message=transformJson(original,text2=>text2),safe=isSafeBoundedValue(message)&&!hasUnsafeRetainedContent([message])}catch{}if(message.role==="assistant"&&Array.isArray(message.content))for(let block of message.content)block?.type!=="toolCall"||typeof block.id!="string"||(safe?omittedCalls.delete(block.id):omittedCalls.add(block.id));let orphanedByOmission=message.role==="toolResult"&&omittedCalls.has(message.toolCallId);if(safe&&!orphanedByOmission)return message;let timestamp=Number.isFinite(message.timestamp)?message.timestamp:0;if(message.role==="toolResult"&&!orphanedByOmission&&typeof message.toolCallId=="string"&&message.toolCallId.length>0&&typeof message.toolName=="string"&&message.toolName.length>0)return{role:"toolResult",toolCallId:message.toolCallId,toolName:message.toolName,content:[{type:"text",text:"[tool result omitted from retained context: not replay-safe]"}],isError:!0,timestamp};let text=message.role==="user"?typeof message.content=="string"?message.content:Array.isArray(message.content)?message.content.flatMap(block=>block?.type==="text"&&typeof block.text=="string"?[block.text]:[]).join(`
|
|
19
|
+
[Output truncated. Full output: ${msg.fullOutputPath}]`),text}function createBranchSummaryMessage(summary,fromId,timestamp){return{role:"branchSummary",summary,fromId,timestamp:new Date(timestamp).getTime()}}function createCompactionSummaryMessage(summary,tokensBefore,timestamp,details){return{role:"compactionSummary",summary,tokensBefore,details,timestamp:new Date(timestamp).getTime()}}function createCustomMessage(customType,content,display,details,timestamp){return{role:"custom",customType,content,display,details,timestamp:new Date(timestamp).getTime()}}function convertToLlm(messages){let withContextProvenance=(source,target)=>copyContextProvenance(source,target),environmentMessages=new Set,converted=messages.map(m=>{switch(m.role){case"bashExecution":return m.excludeFromContext?void 0:withContextProvenance(m,{role:"user",content:[{type:"text",text:bashExecutionToText(m)}],timestamp:m.timestamp});case"custom":{if(isContextExcludedCustomMessage(m.customType))return;let content=typeof m.content=="string"?[{type:"text",text:m.content}]:m.content,converted2=withContextProvenance(m,{role:"user",content,timestamp:m.timestamp});return m.customType===ENVIRONMENT_CONTEXT_MESSAGE_TYPE&&environmentMessages.add(converted2),converted2}case"branchSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:BRANCH_SUMMARY_PREFIX+m.summary+BRANCH_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"compactionSummary":return withContextProvenance(m,{role:"user",content:[{type:"text",text:COMPACTION_SUMMARY_PREFIX+m.summary+COMPACTION_SUMMARY_SUFFIX}],timestamp:m.timestamp});case"configurationUpdate":return m;case"system":case"user":case"assistant":case"toolResult":return m;default:{let _exhaustiveCheck=m;return}}}).filter(m=>m!==void 0);return foldEnvironmentContextIntoNextUserMessage(appendToolResultUserWords(dropFailedAssistantTurns(omitProviderRejectedImages(converted))),environmentMessages)}var TRANSPORT_IMAGE_BUDGET_BYTES=24*1024*1024,BLOCKED_IMAGE_PLACEHOLDER="Image reading is disabled.";function dedupeConsecutivePlaceholder(content,placeholder){return content.filter((block,index,blocks)=>!(block.type==="text"&&block.text===placeholder&&index>0&&blocks[index-1].type==="text"&&blocks[index-1].text===placeholder))}function elideOldImages(messages,options){let budgetBytes=options?.budgetBytes??TRANSPORT_IMAGE_BUDGET_BYTES,alwaysKeepNewest=options?.alwaysKeepNewest??1,maxHistoricalImages=options?.maxHistoricalImages,lastAssistantIndex=messages.findLastIndex(message=>message.role==="assistant"),images=[];messages.forEach((message,messageIndex)=>{message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||message.content.forEach((block,blockIndex)=>{block.type==="image"&&images.push({key:`${messageIndex}:${blockIndex}`,bytes:block.data.length,currentTurn:maxHistoricalImages!==void 0&&messageIndex>lastAssistantIndex})})});let imagesToElide=new Set;if(maxHistoricalImages!==void 0){let historical=images.filter(image=>!image.currentTurn),step=Math.max(1,Math.floor(maxHistoricalImages/2)),excess=historical.length-maxHistoricalImages,cutoff=excess>0?Math.ceil(excess/step)*step:0;for(let image of historical.slice(0,cutoff))imagesToElide.add(image.key)}else{let protectedKeys=new Set(images.slice(Math.max(0,images.length-alwaysKeepNewest)).map(image=>image.key)),total=images.reduce((sum,image)=>sum+image.bytes,0);if(total>budgetBytes){let step=Math.max(1,Math.floor(budgetBytes/2)),threshold=Math.ceil((total-budgetBytes)/step)*step,offset=0,elidedBytes=0,straddler;for(let image of images){let start=offset;offset+=image.bytes,!protectedKeys.has(image.key)&&(offset<=threshold?(imagesToElide.add(image.key),elidedBytes+=image.bytes):start<threshold&&straddler===void 0&&(straddler=image))}straddler!==void 0&&total-elidedBytes>budgetBytes&&imagesToElide.add(straddler.key)}}return imagesToElide.size===0?messages:messages.map((message,messageIndex)=>message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some((_block,blockIndex)=>imagesToElide.has(`${messageIndex}:${blockIndex}`))?message:{...message,content:replaceElidedImages(message.content,blockIndex=>imagesToElide.has(`${messageIndex}:${blockIndex}`))})}function convertToLlmForTransport(messages,options){let converted=convertToLlm(messages);return options.blockImages?converted.map(message=>{if(message.role!=="user"&&message.role!=="toolResult"||!Array.isArray(message.content)||!message.content.some(block=>block.type==="image"))return message;let replaced=message.content.map(block=>block.type==="image"?{type:"text",text:BLOCKED_IMAGE_PLACEHOLDER}:block);return{...message,content:dedupeConsecutivePlaceholder(replaced,BLOCKED_IMAGE_PLACEHOLDER)}}):elideOldImages(converted,options)}import{randomBytes,randomUUID as randomUUID4}from"crypto";import{appendFileSync,closeSync,existsSync as existsSync3,mkdirSync as mkdirSync2,openSync,readdirSync,readSync,rmSync as rmSync2,statSync,writeFileSync as writeFileSync2}from"fs";import{appendFile as appendFile2,mkdir,open as open4,readdir as readdir2,rm as rm3}from"fs/promises";import{basename as basename3,join as join5,resolve as resolve4}from"path";import{StringDecoder as StringDecoder2}from"string_decoder";var OMIT_JSON_VALUE=Symbol("omit-json-value");function transformJson(value,transformString){let transformed=transformJsonValue(value,transformString,"",new WeakSet);if(transformed===OMIT_JSON_VALUE){let serialized=JSON.stringify(value);if(serialized===void 0)throw new SyntaxError("JSON-compatible value expected");return JSON.parse(serialized)}return transformed}function transformJsonValue(value,transformString,key,seen){if(typeof value=="string")return transformString(value);if(typeof value=="number")return Number.isFinite(value)?value:null;if(value===null||typeof value=="boolean")return value;if(typeof value=="bigint")throw new TypeError("Do not know how to serialize a BigInt");if(typeof value>"u"||typeof value=="function"||typeof value=="symbol")return OMIT_JSON_VALUE;if(seen.has(value))throw new TypeError("Converting circular structure to JSON");seen.add(value);let jsonValue=hasJsonSerializer(value)?value.toJSON(key):value;if(jsonValue!==value){let transformed2=transformJsonValue(jsonValue,transformString,key,seen);return seen.delete(value),transformed2}if(Array.isArray(value)){let transformed2=Array.from({length:value.length},(_item,index)=>{let item=value[index],transformedItem=transformJsonValue(item,transformString,String(index),seen);return transformedItem===OMIT_JSON_VALUE?null:transformedItem});return seen.delete(value),transformed2}let transformed={};for(let[key2,item]of Object.entries(value)){let transformedItem=transformJsonValue(item,transformString,String(key2),seen);transformedItem!==OMIT_JSON_VALUE&&Object.defineProperty(transformed,key2,{configurable:!0,enumerable:!0,value:transformedItem,writable:!0})}return seen.delete(value),transformed}function hasJsonSerializer(value){return"toJSON"in value&&typeof value.toJSON=="function"}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isFiniteNumber(value){return typeof value=="number"&&Number.isFinite(value)}function hasTextOnlyContent(content,allowString){return typeof content=="string"?allowString:Array.isArray(content)?content.every(block=>isRecord(block)&&block.type==="text"&&typeof block.text=="string"):!1}function isWellFormedImageBlock(block){return block.type==="image"&&typeof block.mimeType=="string"&&block.mimeType.startsWith("image/")&&typeof block.data=="string"&&block.data.length>0}function hasSafeToolResultContent(content){return Array.isArray(content)?content.every(block=>isRecord(block)&&(block.type==="text"&&typeof block.text=="string"||isWellFormedImageBlock(block))):!1}function isUsage(value){if(!isRecord(value)||!isRecord(value.cost))return!1;for(let field3 of["input","output","cacheRead","cacheWrite","totalTokens"])if(!isFiniteNumber(value[field3]))return!1;for(let field3 of["input","output","cacheRead","cacheWrite","total"])if(!isFiniteNumber(value.cost[field3]))return!1;return(value.cacheWrite1h===void 0||isFiniteNumber(value.cacheWrite1h))&&(value.reasoning===void 0||isFiniteNumber(value.reasoning))}var base64SignaturePattern=/^[A-Za-z0-9+/]+={0,2}$/;function isValidOpaqueSignature(sig){return typeof sig=="string"&&sig.length>0&&sig.length<=65536}function isValidProviderSignature(sig,providerIsGoogle){return isValidOpaqueSignature(sig)?!providerIsGoogle||sig.length%4===0&&base64SignaturePattern.test(sig):!1}function hasSafeAssistantContent(content,providerIsGoogle){if(!Array.isArray(content))return!1;for(let block of content){if(!isRecord(block)||typeof block.type!="string")return!1;switch(block.type){case"text":if(typeof block.text!="string"||block.textSignature!==void 0&&!isValidProviderSignature(block.textSignature,providerIsGoogle))return!1;break;case"thinking":if(typeof block.thinking!="string"||block.startedAt!==void 0&&!isFiniteNumber(block.startedAt)||block.endedAt!==void 0&&!isFiniteNumber(block.endedAt)||block.redacted!==void 0&&typeof block.redacted!="boolean"||block.thinkingSignature!==void 0&&!isValidProviderSignature(block.thinkingSignature,providerIsGoogle)||block.redacted===!0&&!isValidOpaqueSignature(block.thinkingSignature))return!1;break;case"toolCall":if(typeof block.id!="string"||typeof block.name!="string"||!isRecord(block.arguments)||block.incomplete!==void 0&&block.incomplete!==!0||block.errorMessage!==void 0&&typeof block.errorMessage!="string"||block.thoughtSignature!==void 0&&!isValidProviderSignature(block.thoughtSignature,providerIsGoogle))return!1;break;default:return!1}}return!0}function hasSafeAssistantEnvelope(message){let provider=typeof message.provider=="string"?message.provider:"",providerIsGoogle=provider==="google"||provider==="google-vertex",stopReason=message.stopReason,stopDetails=message.stopDetails,safeStopDetails=stopDetails===void 0||isRecord(stopDetails)&&(stopDetails.type==="sensitive"||stopDetails.type==="refusal"&&(stopDetails.explanation===void 0||typeof stopDetails.explanation=="string"));return typeof message.api=="string"&&typeof message.provider=="string"&&typeof message.model=="string"&&isUsage(message.usage)&&(stopReason==="pending"||stopReason==="stop"||stopReason==="length"||stopReason==="toolUse"||stopReason==="error"||stopReason==="aborted")&&safeStopDetails&&isFiniteNumber(message.timestamp)&&(message.responseModel===void 0||typeof message.responseModel=="string")&&(message.responseId===void 0||typeof message.responseId=="string")&&(message.diagnostics===void 0||Array.isArray(message.diagnostics))&&(message.errorMessage===void 0||typeof message.errorMessage=="string")&&(message.rawStopReason===void 0||typeof message.rawStopReason=="string")&&hasSafeAssistantContent(message.content,providerIsGoogle)}function hasSafeToolResultEnvelope(message){return typeof message.toolCallId=="string"&&message.toolCallId.length>0&&typeof message.toolName=="string"&&message.toolName.length>0&&hasSafeToolResultContent(message.content)&&typeof message.isError=="boolean"&&isFiniteNumber(message.timestamp)&&(message.usage===void 0||isUsage(message.usage))&&(message.addedToolNames===void 0||Array.isArray(message.addedToolNames)&&message.addedToolNames.every(name=>typeof name=="string"))}var CONFIGURATION_UPDATE_EFFORTS=new Set(["off","minimal","low","medium","high","xhigh","max"]);function hasSafeConfigurationUpdate(message){return typeof message.effort=="string"&&CONFIGURATION_UPDATE_EFFORTS.has(message.effort)&&Array.isArray(message.content)&&message.content.length===0&&isFiniteNumber(message.timestamp)}function hasUnsafeRetainedContent(messages){for(let value of messages){if(!isRecord(value)||typeof value.role!="string")return!0;switch(value.role){case"user":if(!isFiniteNumber(value.timestamp)||!hasTextOnlyContent(value.content,!0))return!0;break;case"assistant":if(!hasSafeAssistantEnvelope(value))return!0;break;case"toolResult":if(!hasSafeToolResultEnvelope(value))return!0;break;case"configurationUpdate":if(!hasSafeConfigurationUpdate(value))return!0;break;case"custom":if(typeof value.customType!="string"||typeof value.display!="boolean"||!isFiniteNumber(value.timestamp)||!hasTextOnlyContent(value.content,!0))return!0;break;case"bashExecution":if(typeof value.command!="string"||typeof value.output!="string"||value.exitCode!==void 0&&!isFiniteNumber(value.exitCode)||typeof value.cancelled!="boolean"||typeof value.truncated!="boolean"||value.fullOutputPath!==void 0&&typeof value.fullOutputPath!="string"||value.excludeFromContext!==void 0&&typeof value.excludeFromContext!="boolean"||!isFiniteNumber(value.timestamp))return!0;break;case"compactionSummary":if(typeof value.summary!="string"||!isFiniteNumber(value.tokensBefore)||!isFiniteNumber(value.timestamp))return!0;break;default:return!0}}return!1}function isSafeBoundedValue(value,seen=new Set,depth=0){if(depth>32)return!1;if(value==null)return!0;let kind=typeof value;if(kind==="string"||kind==="number"||kind==="boolean")return!0;if(kind!=="object"||seen.has(value))return!1;if(seen.add(value),Array.isArray(value)){for(let item of value)if(!isSafeBoundedValue(item,seen,depth+1))return!1;return!0}let proto=Object.getPrototypeOf(value);if(proto!==Object.prototype&&proto!==null)return!1;for(let descriptor of Object.values(Object.getOwnPropertyDescriptors(value)))if(descriptor.get!==void 0||descriptor.set!==void 0||!isSafeBoundedValue(descriptor.value,seen,depth+1))return!1;return!0}function projectRetainedMessages(messages){let omittedCalls=new Set;return messages.map(original=>{let message=original,safe=!1;try{message=transformJson(original,text2=>text2),safe=isSafeBoundedValue(message)&&!hasUnsafeRetainedContent([message])}catch{}if(message.role==="assistant"&&Array.isArray(message.content))for(let block of message.content)block?.type!=="toolCall"||typeof block.id!="string"||(safe?omittedCalls.delete(block.id):omittedCalls.add(block.id));let orphanedByOmission=message.role==="toolResult"&&omittedCalls.has(message.toolCallId);if(safe&&!orphanedByOmission)return message;let timestamp=Number.isFinite(message.timestamp)?message.timestamp:0;if(message.role==="toolResult"&&!orphanedByOmission&&typeof message.toolCallId=="string"&&message.toolCallId.length>0&&typeof message.toolName=="string"&&message.toolName.length>0)return{role:"toolResult",toolCallId:message.toolCallId,toolName:message.toolName,content:[{type:"text",text:"[tool result omitted from retained context: not replay-safe]"}],isError:!0,timestamp};let text=message.role==="user"?typeof message.content=="string"?message.content:Array.isArray(message.content)?message.content.flatMap(block=>block?.type==="text"&&typeof block.text=="string"?[block.text]:[]).join(`
|
|
20
20
|
`):"":"";return{role:"user",content:`${text?`${text}
|
|
21
21
|
`:""}[message omitted from retained context: not replay-safe]`,timestamp}})}import{randomUUID}from"node:crypto";var roleOf=entry=>entry.type==="message"?entry.message.role:void 0,partsOf=entry=>{let content=entry.type==="message"?Reflect.get(entry.message,"content"):void 0;return Array.isArray(content)?content:[]};function takeKeys(entry){let role=roleOf(entry);if(role==="assistant"){let parts=partsOf(entry).map(part=>typeof part.runtimeItemKey=="string"?part.runtimeItemKey:void 0);if(!parts.some(key2=>key2!==void 0))return;for(let part of partsOf(entry))typeof part=="object"&&part!==null&&Reflect.deleteProperty(part,"runtimeItemKey");return{parts}}if(role!=="toolResult")return;let key=Reflect.get(entry,"runtimeItemKey"),unknown=Reflect.get(entry,"callUnknown")===!0;return key!==void 0&&Reflect.deleteProperty(entry,"runtimeItemKey"),unknown&&Reflect.deleteProperty(entry,"callUnknown"),unknown?{result:{callUnknown:!0}}:typeof key=="string"?{result:{runtimeItemKey:key}}:void 0}var SessionFileCallKeys=class{constructor(){this.byEntry=new Map}clear(){this.byEntry.clear()}adopt(entries){for(let entry of entries){let keys=takeKeys(entry);keys&&"id"in entry&&this.byEntry.set(entry.id,keys)}}strip(entry){return takeKeys(entry),entry}recordAssistant(entry,owner,bridged=new Map){let prefix=owner??randomUUID(),parts=partsOf(entry).map((part,index)=>part.type==="toolCall"?bridged.get(index)??blockCallKey(prefix,index):void 0);parts.some(key=>key!==void 0)&&this.byEntry.set(entry.id,{parts})}recordResult(entry,leafId,entryOf){let id=entry.message.role==="toolResult"?entry.message.toolCallId:void 0,closed=new Set,assistant;for(let at=entryOf(leafId??"");at&&!assistant;at=at.parentId===null?void 0:entryOf(at.parentId))roleOf(at)==="assistant"?assistant=at:at.type==="message"&&at.message.role==="toolResult"&&closed.add(at.message.toolCallId);let matches=assistant?partsOf(assistant).flatMap((part,index)=>part.type==="toolCall"&&part.id===id?[index]:[]):[],open5=id!==void 0&&matches.length===1&&!closed.has(id),key=assistant&&open5?this.byEntry.get(assistant.id)?.parts?.[matches[0]??-1]:void 0;this.byEntry.set(entry.id,{result:key===void 0?{callUnknown:!0}:{runtimeItemKey:key}})}decorate(entry){let keys="id"in entry?this.byEntry.get(entry.id):void 0;if(!keys||entry.type!=="message")return entry;if(keys.result)return{...entry,...keys.result};let content=partsOf(entry).map((part,index)=>{let key=keys.parts?.[index];return key===void 0?part:{...part,runtimeItemKey:key}});return{...entry,message:{...entry.message,content}}}};function sessionCwdMatcher(resolvedCwd){let mapped=new Map;return cwd=>{if(cwd===void 0||cwd==="")return!1;if(resolvePath(cwd)===resolvedCwd)return!0;let target=mapped.get(cwd);return target===void 0&&(target=resolvePath(resolveMovedPath(cwd)),mapped.set(cwd,target)),target===resolvedCwd}}import{existsSync}from"fs";import{readdir}from"fs/promises";import{join as join2}from"path";import{stat as stat2}from"fs/promises";import{resolve}from"path";import{open}from"fs/promises";import{StringDecoder}from"string_decoder";import{execFile}from"node:child_process";var REPOSITORY_IDENTITY_ENTRY_TYPE="repository-identity",GIT_TIMEOUT_MS=5e3,COMMIT_HASH=/^[0-9a-f]{40,64}$/,GIT_LOCATION_ENV=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"]),runGit=(dir,args)=>new Promise(resolve5=>{let env=Object.fromEntries(Object.entries(process.env).filter(([name])=>!GIT_LOCATION_ENV.has(name)));execFile("git",["-C",dir,...args],{env,timeout:GIT_TIMEOUT_MS,windowsHide:!0},(error,stdout)=>{resolve5(error?void 0:stdout)})});async function readRepositoryIdentity(dir,run=runGit){let[roots,origin]=await Promise.all([run(dir,["rev-list","--max-parents=0","HEAD"]),run(dir,["config","--get","remote.origin.url"])]),rootCommits=(roots??"").split(/\s+/).filter(line=>COMMIT_HASH.test(line)).sort(),originUrl=origin?.trim()?normalizeRemoteUrl(origin):void 0;if(!(rootCommits.length===0&&originUrl===void 0))return originUrl===void 0?{rootCommits}:{rootCommits,originUrl}}function normalizeRemoteUrl(url){let trimmed=url.trim(),scpLike=/^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/.exec(trimmed);return(scpLike?`${scpLike[1]}/${scpLike[2]}`:trimmed.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").replace(/^[^@/]+@/,"").replace(/^([^/:]+):\d+\//,"$1/")).replace(/\/+$/,"").replace(/\.git$/i,"").toLowerCase()}function compareRepositoryIdentities(a,b){return a===void 0||b===void 0?"unknown":a.rootCommits.length>0&&b.rootCommits.length>0?a.rootCommits.some(commit=>b.rootCommits.includes(commit))?"same":"different":a.originUrl!==void 0&&b.originUrl!==void 0?a.originUrl===b.originUrl?"same":"different":"unknown"}function parseRepositoryIdentity(value){if(typeof value!="object"||value===null)return;let{rootCommits,originUrl}=value;if(!Array.isArray(rootCommits)||!rootCommits.every(commit=>typeof commit=="string")||originUrl!==void 0&&typeof originUrl!="string")return;let commits=rootCommits.filter(commit=>COMMIT_HASH.test(commit)).sort();if(!(commits.length===0&&originUrl===void 0))return originUrl===void 0?{rootCommits:commits}:{rootCommits:commits,originUrl}}function sameRepositoryIdentity(a,b){return a===void 0||b===void 0?a===b:a.originUrl===b.originUrl&&a.rootCommits.join(",")===b.rootCommits.join(",")}function newAccumulator(){return{header:null,name:void 0,firstUserMessage:"",messageCount:0,lastActivityTime:void 0,repositoryIdentity:void 0,texts:[]}}function accumulateLine(accumulator,line){let entry=parseEntryLine(line);if(!entry)return!0;if(!accumulator.header)return entry.type!=="session"||typeof entry.id!="string"?!1:(accumulator.header=entry,!0);if(entry.type==="custom"&&entry.customType===REPOSITORY_IDENTITY_ENTRY_TYPE)return accumulator.repositoryIdentity=parseRepositoryIdentity(entry.data)??accumulator.repositoryIdentity,!0;let infoName=sessionInfoName(entry);if(infoName!==null)return accumulator.name=infoName,!0;if(entry.type!=="message")return!0;accumulator.messageCount++;let visible=visibleMessage(entry);return!visible||(typeof visible.time=="number"&&(accumulator.lastActivityTime=Math.max(accumulator.lastActivityTime??0,visible.time)),!visible.text)||(accumulator.texts.push(visible.text),!accumulator.firstUserMessage&&visible.role==="user"&&(accumulator.firstUserMessage=visible.text)),!0}var LINE_READ_BUFFER_SIZE=1024*1024;async function readFileLines(filePath,onLine){let handle=await open(filePath,"r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(LINE_READ_BUFFER_SIZE),pending="",bytes=0,lastByte=-1,emit=line=>onLine(line.endsWith("\r")?line.slice(0,-1):line);for(;;){let{bytesRead}=await handle.read(buffer,0,buffer.length,null);if(bytesRead===0)break;bytes+=bytesRead,lastByte=buffer[bytesRead-1]??-1;let searchFrom=pending.length;pending+=decoder.write(buffer.subarray(0,bytesRead));let lineStart=0,newlineIndex=pending.indexOf(`
|
|
22
22
|
`,searchFrom);for(;newlineIndex!==-1;){if(!emit(pending.slice(lineStart,newlineIndex)))return{completed:!1,bytes,endsWithNewline:!1};lineStart=newlineIndex+1,newlineIndex=pending.indexOf(`
|
|
@@ -29,7 +29,7 @@ Command exited with code ${msg.exitCode}`),msg.truncated&&msg.fullOutputPath&&(t
|
|
|
29
29
|
`);for(let line of lines)if(line.trim())try{let entry=JSON.parse(line);entries.push(entry)}catch{}return entries}function getLatestCompactionEntry(entries){for(let i=entries.length-1;i>=0;i--)if(entries[i].type==="compaction")return entries[i];return null}function buildEntryIndex(entries,byId){if(byId)return byId;let index=new Map;for(let entry of entries)index.set(entry.id,entry);return index}function buildSessionPath(entries,leafId,byId){let index=buildEntryIndex(entries,byId),leaf;if(leafId===null)return[];if(leafId&&(leaf=index.get(leafId)),leaf??=entries[entries.length-1],!leaf)return[];let path=[],visited=new Set,current=leaf;for(;current&&!visited.has(current);)visited.add(current),path.push(current),current=current.parentId?index.get(current.parentId):void 0;return path.reverse(),path}function getSessionContextSettings(path){let thinkingLevel="off",thinkingSelection,configurationUpdate,model=null,isModelSelectionExplicit=!1,isInFallbackWindow=!1,preFallbackThinkingLevel=thinkingLevel,preFallbackThinkingSelection=thinkingSelection;for(let entry of path)if(entry.type==="thinking_level_change")thinkingLevel=entry.thinkingLevel,thinkingSelection=entry.thinkingSelection;else if(entry.type==="configuration_update")configurationUpdate={effort:entry.reasoning.effort};else if(entry.type==="model_change")entry.reason==="fallback"?(isInFallbackWindow||(preFallbackThinkingLevel=thinkingLevel,preFallbackThinkingSelection=thinkingSelection,entry.originalProvider&&entry.originalModelId&&(model={provider:normalizeProviderId(entry.originalProvider),modelId:entry.originalModelId},isModelSelectionExplicit=!0)),isInFallbackWindow=!0):entry.reason==="fallback-revert"?(isInFallbackWindow&&(thinkingLevel=preFallbackThinkingLevel,thinkingSelection=preFallbackThinkingSelection),isInFallbackWindow=!1):(isInFallbackWindow=!1,entry.provider&&entry.modelId&&(model={provider:normalizeProviderId(entry.provider),modelId:entry.modelId},isModelSelectionExplicit=!0));else if(entry.type==="message"&&entry.message.role==="assistant"&&!isInFallbackWindow&&!isVirtualModel(entry.message)){if(isModelSelectionExplicit&&model?.provider===normalizeProviderId(entry.message.provider))continue;model={provider:normalizeProviderId(entry.message.provider),modelId:entry.message.model},isModelSelectionExplicit=!1}return isInFallbackWindow&&(thinkingLevel=preFallbackThinkingLevel,thinkingSelection=preFallbackThinkingSelection),{thinkingLevel,thinkingSelection,configurationUpdate,model}}function sessionEntryToContextMessages(entry){if(entry.type==="message"){let message=entry.message;return message.role==="system"&&message.content==null?[{...message,content:""}]:(message.role==="user"||message.role==="assistant"||message.role==="toolResult")&&message.content==null?[withContextEntryId(entry.id,{...message,content:[]})]:[withContextEntryId(entry.id,message)]}if(entry.type==="configuration_update")return[withContextEntryId(entry.id,{role:"configurationUpdate",content:[],effort:entry.reasoning.effort,timestamp:new Date(entry.timestamp).getTime()})];if(entry.type==="custom_message")return[withContextEntryId(entry.id,createCustomMessage(entry.customType,entry.content??[],entry.display,entry.details,entry.timestamp))];if(entry.type==="branch_summary"&&entry.summary)return[withContextEntryId(entry.id,createBranchSummaryMessage(entry.summary,entry.fromId,entry.timestamp))];if(entry.type==="compaction"){let summary=withContextEntryId(entry.id,createCompactionSummaryMessage(entry.summary,entry.tokensBefore,entry.timestamp,entry.details));return entry.systemMessage?[withContextEntryId(entry.id,entry.systemMessage),summary]:[summary]}return[]}function buildContextEntries(entries,leafId,byId){return contextEntriesOfPath(buildSessionPath(entries,leafId,byId))}function contextEntriesOfPath(path){let compaction=null;for(let entry of path)entry.type==="compaction"&&(compaction=entry);if(!compaction)return path;let compactionIdx=path.findIndex(entry=>entry.id===compaction.id);if(compactionIdx<0)return path;let contextEntries=[compaction],foundFirstKept=!1;for(let i=0;i<compactionIdx;i++){let entry=path[i];entry.type!=="compaction"&&(entry.id===compaction.firstKeptEntryId&&(foundFirstKept=!0),foundFirstKept&&!(entry.type==="message"&&entry.message.role==="system")&&contextEntries.push(entry))}return contextEntries.push(...path.slice(compactionIdx+1)),contextEntries}function projectContextEntry(entry,edit){let messages=sessionEntryToContextMessages(entry);if(!edit)return messages;let replacement=edit.replacement;return replacement===null?[]:messages.map(message=>{if(message.role!=="user"&&message.role!=="assistant"&&message.role!=="toolResult"&&message.role!=="custom")return message;let content=(message.role==="assistant"||message.role==="toolResult")&&typeof replacement.content=="string"?[{type:"text",text:replacement.content}]:replacement.content;return withContextEntryId(entry.id,{...message,content})})}function projectSession(entries,leafId,byId,knownPath){let path=knownPath??buildSessionPath(entries,leafId,byId),settings=getSessionContextSettings(path),contextEntries=contextEntriesOfPath(path),edits=new Map;for(let entry of contextEntries)entry.type==="context_edit"&&edits.set(entry.targetId,entry);let projectedEntries=contextEntries.map((sourceEntry,index)=>({sourceEntry,messages:sourceEntry.type==="compaction"&&index>0?[]:projectContextEntry(sourceEntry,edits.get(sourceEntry.id))})),recoveryIndex=path.findLastIndex(entry=>entry.type==="compaction"&&entry.details!==null&&typeof entry.details=="object"&&"retainedMessagePolicy"in entry.details&&entry.details.retainedMessagePolicy==="omit-unsafe-v1");if(recoveryIndex>=0){let retainedIds=new Set(path.slice(0,recoveryIndex).map(entry=>entry.id)),retained=projectedEntries.filter(entry=>retainedIds.has(entry.sourceEntry.id)),repaired=projectRetainedMessages(retained.flatMap(entry=>entry.messages)),index=0;for(let entry of retained)entry.messages=entry.messages.map(()=>withContextEntryId(entry.sourceEntry.id,repaired[index++]))}return{projection:{entries:projectedEntries,messages:projectedEntries.flatMap(entry=>entry.messages),thinkingLevel:settings.thinkingLevel,model:settings.model},settings}}function buildSessionProjection(entries,leafId,byId){return projectSession(entries,leafId,byId).projection}function buildSessionContext(entries,leafId,byId){let{projection,settings}=projectSession(entries,leafId,byId),{thinkingLevel,thinkingSelection,model,configurationUpdate}=settings;return{messages:projection.messages,thinkingLevel,thinkingSelection,model,configurationUpdate}}function getDefaultSessionDirPath(cwd,agentDir=getAgentDir()){let resolvedCwd=resolvePath(cwd),resolvedAgentDir=resolvePath(agentDir),safePath=`--${resolvedCwd.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`;return join5(resolvedAgentDir,"sessions",safePath)}function getDefaultSessionDir(cwd,agentDir=getAgentDir()){let sessionDir=getDefaultSessionDirPath(cwd,agentDir);return existsSync3(sessionDir)||mkdirSync2(sessionDir,{recursive:!0}),sessionDir}var SESSION_HEADER_READ_BUFFER_SIZE=4096,MAX_SESSION_HEADER_SCAN_BYTES=1024*1024,SessionHeaderScanLimitError=class extends Error{constructor(filePath){super(`Session header exceeds ${MAX_SESSION_HEADER_SCAN_BYTES}-byte scan limit: ${filePath}`),this.name="SessionHeaderScanLimitError"}};function parseSessionHeaderCandidate(line){if(!line.trim())return;let entry=parseSessionEntryLine(line);if(entry)return entry.type!=="session"||typeof entry.id!="string"?null:entry}function readSessionHeader(filePath){let fd=openSync(filePath,"r");try{let decoder=new StringDecoder2("utf8"),buffer=Buffer.allocUnsafe(SESSION_HEADER_READ_BUFFER_SIZE),lineChunks=[],scannedBytes=0;for(;scannedBytes<MAX_SESSION_HEADER_SCAN_BYTES;){let readLength=Math.min(buffer.length,MAX_SESSION_HEADER_SCAN_BYTES-scannedBytes),bytesRead=readSync(fd,buffer,0,readLength,null);if(bytesRead===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;scannedBytes+=bytesRead;let chunk=decoder.write(buffer.subarray(0,bytesRead)),lineStart=0,newlineIndex=chunk.indexOf(`
|
|
30
30
|
`,lineStart);for(;newlineIndex!==-1;){lineChunks.push(chunk.slice(lineStart,newlineIndex));let header=parseSessionHeaderCandidate(lineChunks.join(""));if(header!==void 0)return header;lineChunks.length=0,lineStart=newlineIndex+1,newlineIndex=chunk.indexOf(`
|
|
31
31
|
`,lineStart)}lineChunks.push(chunk.slice(lineStart))}let probe=Buffer.allocUnsafe(1);if(readSync(fd,probe,0,probe.length,null)===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;throw new SessionHeaderScanLimitError(filePath)}finally{closeSync(fd)}}function readSessionHeaderForDiscovery(filePath){try{return readSessionHeader(filePath)}catch{return null}}function getSessionHeaderCwd(header){let cwd=header.cwd;return typeof cwd=="string"?cwd:void 0}function discoverOpenHeader(resolvedPath,cwdOverride){if(cwdOverride!==void 0||!existsSync3(resolvedPath))return{header:null,needsFullLoad:!1};try{return{header:readSessionHeader(resolvedPath),needsFullLoad:!1}}catch(error){if(!(error instanceof SessionHeaderScanLimitError))throw error;return{header:null,needsFullLoad:!0}}}function headerOf(entries){let firstEntry=entries?.[0];return firstEntry?.type==="session"?firstEntry:null}function openLocation(resolvedPath,sessionDir,cwdOverride,header){let headerCwd=header?getSessionHeaderCwd(header):void 0,cwd=cwdOverride??(headerCwd&&resolveMovedPath(headerCwd))??process.cwd(),dir=sessionDir?normalizePath(sessionDir):resolve4(resolvedPath,"..");return{cwd,dir}}function findMostRecentSession(sessionDir,cwd){let resolvedSessionDir=normalizePath(sessionDir),matchesCwd=cwd?sessionCwdMatcher(resolvePath(cwd)):void 0;try{let files=readdirSync(resolvedSessionDir).filter(file=>file.endsWith(".jsonl")).map(file=>join5(resolvedSessionDir,file)).map(path=>({path,mtime:statSync(path).mtimeMs})).sort((a,b)=>b.mtime-a.mtime);for(let{path}of files){let header=readSessionHeaderForDiscovery(path);if(header&&(!matchesCwd||matchesCwd(getSessionHeaderCwd(header))))return path}return null}catch{return null}}var sessionEntryLoader=loadEntriesFromFile,DEFERRED_FILE_LOAD=Symbol("deferred-session-file-load");var SETUP_ENTRY_TYPES=new Set(["session","model_change","model_change_rejected","thinking_level_change","configuration_update","label"]),LIFECYCLE_ENTRY_TYPES=new Set(["session-lifecycle","work-custody","child-lifecycle"]);function isDisposableEntry(entry){return entry.type==="custom"?entry.startupBookkeeping===!0||LIFECYCLE_ENTRY_TYPES.has(entry.customType):SETUP_ENTRY_TYPES.has(entry.type)}function isConversationEntry(entry){return entry.type==="message"&&(entry.message.role==="user"||entry.message.role==="assistant")}var SessionManager=class _SessionManager{constructor(cwd,sessionDir,sessionFile,persist,newSessionOptions,preloadedFileEntries){this.sessionId="",this.writeGuard=new SessionWriteGuard,this.writeFence=new SessionWriteFence,this.bindPending=!1,this.bindRaced=!1,this.projectionWarningListeners=new Set,this.flushed=!1,this.tailMayBeTorn=!1,this.tornTailCause="unknown",this.pendingRecoveries=[],this.fileEntries=[],this.byId=new Map,this.entryOrdersById=new Map,this.messageEntryPositions=new WeakMap,this.labelsById=new Map,this.labelTimestampsById=new Map,this.leafId=null,this.transcriptFile=new TranscriptFile,this.transcriptBytes=new WeakMap,this.capturesTranscriptBase=compactUpdatesEnabled(),this.residentStore=new ResidentStringStore,this.callKeys=new SessionFileCallKeys,this.mirrorTrimmed=!1,this.loadingFullMirror=!1,this.trimmedIds=new Set,this.idsInUse={has:id=>this.byId.has(id)||this.trimmedIds.has(id)},this.fullEntryCount=0,this.historyGeneration=0,this.verbatimFromCount=0,this.historyReductions=new HistoryReductions({generation:()=>this.historyGeneration,count:()=>this.fullEntryCount,appendedSince:count=>this._appendedSince(count),readAll:()=>this._readWholeHistory()}),this.compactEntriesCache=null,this.compactView=null,this.projectionMemo=null,this.historyView=null,this.compactLookup=null,this.mutationCount=0,this.entriesCache=null,this.branchCache=null,this.sessionNameCache=void 0,this.usageTotals={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,latestCacheHitRate:void 0},this.cwd=resolvePath(cwd),this.sessionDir=normalizePath(sessionDir),this.persist=persist,persist&®isterSessionWriter(this),persist&&this.sessionDir&&!existsSync3(this.sessionDir)&&mkdirSync2(this.sessionDir,{recursive:!0}),this.residentStore.configure({blobsDir:()=>this.persist&&this.sessionId?join5(this.sessionDir,"resident-blobs",this.sessionId):void 0}),sessionFile?preloadedFileEntries!==DEFERRED_FILE_LOAD&&this._setSessionFile(sessionFile,preloadedFileEntries,newSessionOptions):preloadedFileEntries!==DEFERRED_FILE_LOAD&&preloadedFileEntries?.length?this._loadEntries(preloadedFileEntries,newSessionOptions):this.newSession(newSessionOptions)}reloadFromDisk(){if(!this.sessionFile||!existsSync3(this.sessionFile))return;let fileEntries=loadEntriesFromFile(this.sessionFile,this.capturesTranscriptBase);if(fileEntries.length===0){if(statSync(this.sessionFile).size===0)return;throw new Error(`Session file is not a valid ${APP_NAME} session: ${this.sessionFile}`)}this._setSessionFile(this.sessionFile,fileEntries),this._journalReplace()}_loadFullMirrorFor(id){if(!(this.byId.has(id)||!this.sessionFile)){this.loadingFullMirror=!0;try{this.reloadFromDisk()}finally{this.loadingFullMirror=!1}}}setSessionFile(sessionFile){this._setSessionFile(sessionFile),this._journalReplace()}_setSessionFile(sessionFile,preloadedFileEntries,newSessionOptions){let existingFile=this._beginSessionFile(sessionFile,newSessionOptions);if(existingFile===void 0)return;let entries=preloadedFileEntries??loadEntriesFromFile(existingFile,this.capturesTranscriptBase);if(this._captureTranscriptBase(loadedFileIdentities.get(entries),entries),!this._adoptFileEntries(existingFile,entries,newSessionOptions))return;let loadedHistory=this._retainLoadedTail();this.fileEntries=this.fileEntries.map(entry=>this.residentStore.externalize(entry)),this._completeFileLoad(loadedHistory)}async _setSessionFileAsync(sessionFile,preloadedFileEntries,newSessionOptions,slicer){let existingFile=this._beginSessionFile(sessionFile,newSessionOptions);if(existingFile===void 0)return;let entries=preloadedFileEntries??await loadEntriesFromFileAsync(existingFile,slicer,this.capturesTranscriptBase);if(this._captureTranscriptBase(loadedFileIdentities.get(entries),entries),!this._adoptFileEntries(existingFile,entries,newSessionOptions))return;let loadedHistory=this._retainLoadedTail();this.fileEntries=await mapInSlices(this.fileEntries,entry=>this.residentStore.externalize(entry),slicer),this._completeFileLoad(loadedHistory),await this.transcriptFile.ready}_beginSessionFile(sessionFile,newSessionOptions){let resolvedFile=resolvePath(sessionFile);this.sessionFile!==resolvedFile&&(this.durable=void 0),this.persist&&(reserveSessionWrite(resolvedFile),this.writeFence.opened(resolvedFile));let recoveryCause=this.sessionFile===resolvedFile&&this.tailMayBeTorn?this.tornTailCause:"unknown";if(this.tailMayBeTorn=!1,this.tornTailCause="unknown",this.sessionFile=resolvedFile,this.transcriptFile.reset(),this.mirrorTrimmed=!1,this.trimmedIds.clear(),this.residentStore.clear(),this.callKeys.clear(),existsSync3(resolvedFile))return this.persist&&this._settleFinalLine(resolvedFile,recoveryCause),resolvedFile;let created=withFileNameId(resolvedFile,newSessionOptions);this._resetToNewSession(created),created?.id!==void 0&&(this._rewriteFile(),this.flushed=!0)}_adoptFileEntries(sessionFile,entries,newSessionOptions){if(entries.length===0){if(statSync(sessionFile).size>0)throw new Error(`Session file is not a valid ${APP_NAME} session: ${sessionFile}`);return this._resetToNewSession(withFileNameId(sessionFile,newSessionOptions)),this._rewriteFile(),this.flushed=!0,!1}this.fileEntries=entries,this.callKeys.adopt(entries);let header=this.fileEntries.find(e=>e.type==="session");return this.sessionId=header?.id??createSessionId(),this._releaseBlobsDirUnlessShared(),migrateToCurrentVersion(this.fileEntries)&&this.writeGuard.isWritable(this.fileEntries)&&this._rewriteFile(),!0}_completeFileLoad(loadedHistory){this._buildIndex(),this.historyGeneration++,loadedHistory!==void 0&&(this.historyView={source:this.fileEntries,length:this.fileEntries.length,entries:loadedHistory}),this.mutationCount++,this.flushed=!0,this.ownedHeaderFile=void 0}newSession(options){this.durable=void 0;let timestamp=this._resetToNewSession(options);if(this.ownedHeaderFile=void 0,this.persist){let fileTimestamp=timestamp.replace(/[:.]/g,"-"),path=join5(this.getSessionDir(),`${fileTimestamp}_${this.sessionId}.jsonl`);reserveSessionWrite(path),this.sessionFile=path}return this._journalReplace(),this.sessionFile}_resetToNewSession(options){options?.id!==void 0&&assertValidSessionId(options.id);let previousBlobsDir=this.residentStore.resolvedBlobsDir();this.sessionId=options?.id??createSessionId();let timestamp=new Date().toISOString(),header={type:"session",version:CURRENT_SESSION_VERSION,id:this.sessionId,timestamp,cwd:this.cwd,parentSession:options?.parentSession,...options?.spawnedBy?{spawnedBy:options.spawnedBy}:{}};return this.fileEntries=[header],this.callKeys.clear(),this.transcriptFile.reset(),this.transcriptBytes=new WeakMap,this.historyGeneration++,this.verbatimFromCount=0,this.mirrorTrimmed=!1,this.trimmedIds.clear(),this.fullEntryCount=0,this.residentStore.clear(),previousBlobsDir&&this._removeBlobsDir(previousBlobsDir),this.byId.clear(),this.entryOrdersById.clear(),this.messageEntryPositions=new WeakMap,this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.sessionNameCache=void 0,this.usageTotals={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,latestCacheHitRate:void 0},this.mutationCount++,this.flushed=!1,timestamp}_loadEntries(entries,options){let header=entries.find(e=>e.type==="session");header?(this.fileEntries=entries,this.callKeys.adopt(entries),this.sessionId=header.id,migrateToCurrentVersion(this.fileEntries)&&this._rewriteFile()):(this.newSession(options),this.callKeys.adopt(entries),this.fileEntries=this.fileEntries.concat(entries)),this.fileEntries=this.fileEntries.map(entry=>this.residentStore.externalize(entry)),this._buildIndex(),this.historyGeneration++,this.mutationCount++}_retainLoadedTail(){if(!this.persist||this.loadingFullMirror)return;let tail=planLoadedTail(this.fileEntries);if(tail===void 0)return;let history=this.fileEntries.filter(entry=>entry.type!=="session");this.usageTotals=emptyUsageTotals(),this.fullEntryCount=history.length;for(let entry of history)this._accumulateUsage(entry);for(let id of tail.trimmedIds)this.trimmedIds.add(id);return this.mirrorTrimmed=!0,this.fileEntries=tail.retained,this.verbatimFromCount=history.length-tail.windowLength,history}_buildIndex(){this.mirrorTrimmed||(this.verbatimFromCount=0),this.byId.clear(),this.entryOrdersById.clear(),this.messageEntryPositions=new WeakMap,this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.sessionNameCache=void 0,this.mirrorTrimmed||(this.usageTotals=emptyUsageTotals());let fullEntryCount=0;for(let[order,entry]of this.fileEntries.entries())entry.type!=="session"&&(fullEntryCount++,this.byId.set(entry.id,entry),this.entryOrdersById.set(entry.id,order),this.leafId=entry.id,this.mirrorTrimmed||this._accumulateUsage(entry),entry.type==="session_info"&&(this.sessionNameCache=entry.name?.trim()||void 0),entry.type==="label"&&(entry.label?(this.labelsById.set(entry.targetId,entry.label),this.labelTimestampsById.set(entry.targetId,entry.timestamp)):(this.labelsById.delete(entry.targetId),this.labelTimestampsById.delete(entry.targetId))));this.mirrorTrimmed||(this.fullEntryCount=fullEntryCount)}_rewriteFile(){if(!this.persist||!this.sessionFile)return;this.writeGuard.assertRewritable(this.fileEntries,this.sessionFile),this.writeFence.assertOwned(this.sessionFile),reserveSessionWrite(this.sessionFile);let durable=this.durable;if(this.bindPending&&(this.bindRaced=!0),durable&&(durable.commitRewrite(this._headerLine(),this._storedEntries(this.fileEntries)),durable.projectionStale())){durable.scheduleRepair(this.sessionFile);return}try{replaceFileAtomically(this.sessionFile,this._serializedFileEntries(),this.capturesTranscriptBase?identity=>this._captureTranscriptBase(identity,this.fileEntries):void 0)}catch(error){if(!durable)throw error;durable.projectionFailed(this.sessionFile,error);return}durable?.recordWhole(this.sessionFile)}_captureTranscriptBase(identity,entries){identity&&this.transcriptFile.capture(identity,entries,()=>{let persistence=this._transcriptPersistence();persistence?(this.transcriptJournal?.record({kind:"persisted",persistence}),entries&&this._journalReplace()):this.transcriptFile.unavailable&&this.transcriptJournal?.record({kind:"unavailable",reason:this.transcriptFile.unavailable}),this.transcriptBytes=new WeakMap})}beginTranscriptJournal(){return this.transcriptJournal=new TranscriptJournal,this._transcriptSnapshot()}drainTranscript(){return this.transcriptJournal?.drain()??[]}_journalReplace(){this.transcriptJournal?.record(...this._transcriptSnapshot())}_transcriptSnapshot(){let{base,history,unavailable}=this.transcriptFile;if(unavailable)return[{kind:"unavailable",reason:unavailable}];let unpersisted=base?this.fullEntryCount-history:this.fileEntries.length,resident=base?this.fileEntries.length-1:this.mirrorTrimmed?-1:this.fileEntries.length;return snapshotTranscript({base,unpersisted:unpersisted<=resident?this.fileEntries.slice(this.fileEntries.length-unpersisted):void 0,leafId:this.leafId,own:entry=>this._transcriptEntryBytes(entry),persistence:this._transcriptPersistence()})}_transcriptPersistence(){if(!(!this.flushed||!this.transcriptFile.identity))return{fileIdentity:this.transcriptFile.identity,count:this.fullEntryCount+1}}_transcriptEntryBytes(entry){let cached=this.transcriptBytes.get(entry);if(cached!==void 0)return cached;let bytes=JSON.stringify(this.callKeys.decorate(this.residentStore.materialize(entry)));return this.persist&&this.capturesTranscriptBase&&!this.transcriptFile.unavailable&&(!this.flushed||!this.transcriptFile.identity)&&this.transcriptBytes.set(entry,bytes),bytes}*_serializedFileEntries(){let content=this.capturesTranscriptBase?new BaseContentHash:void 0;for(let entry of this.fileEntries){let bytes=this._transcriptEntryBytes(entry);this.capturesTranscriptBase&&!this.transcriptFile.unavailable&&this.transcriptBytes.set(entry,bytes),content?.line(bytes),yield`${bytes}
|
|
32
|
-
`}content&&loadedContentFingerprints.set(this.fileEntries,content.digest())}isPersisted(){return this.persist}getCwd(){return this.cwd}getSessionDir(){return this.sessionDir}usesDefaultSessionDir(){return this.sessionDir===getDefaultSessionDirPath(this.cwd)}getSessionId(){return this.sessionId}getSessionFile(){return this.sessionFile}getOwnership(){return!this.persist||!this.sessionFile?{writable:!0}:this.writeGuard.ownership(this.fileEntries)}getResidentStore(){return this.residentStore}getResidentStoreStats(){return this.residentStore.stats()}persistHeaderNow(){if(!this.persist||!this.sessionFile||this.flushed)return this.headerWrite??this.transcriptFile.ready;let sessionFile=this.sessionFile,durable=this.durable;if(this.bindPending&&(this.bindRaced=!0),durable&&this.headerWrite===void 0)try{durable.commitRewrite(this._headerLine(),this._storedEntries(this.fileEntries))}catch(error){return Promise.reject(error)}return this.headerWrite??=(durable?this._writeHeaderAsync(sessionFile).then(()=>durable.recordWhole(sessionFile),error=>durable.projectionFailed(sessionFile,error)):this._writeHeaderAsync(sessionFile)).finally(()=>{this.headerWrite=void 0}),this.headerWrite}isTranscriptFlushed(){return this.flushed}async discardHeaderOnlyFile(){return await this.headerWrite,!this.persist||!this.sessionFile||!this.flushed||this.ownedHeaderFile!==this.sessionFile||!this.fileEntries.every(isDisposableEntry)?!1:(await rm3(this.sessionFile,{force:!0}),this.ownedHeaderFile=void 0,this.flushed=!1,this.transcriptFile.reset(),!0)}async _writeHeaderAsync(sessionFile){this.writeFence.assertOwned(sessionFile),reserveSessionWrite(sessionFile);let entries=this.fileEntries,serialize=batch=>batch.map(e=>`${this._transcriptEntryBytes(e)}
|
|
32
|
+
`}content&&loadedContentFingerprints.set(this.fileEntries,content.digest())}isPersisted(){return this.persist}async enablePersistence(){if(this.persist)return;let dir=getDefaultSessionDirPath(this.cwd);await mkdir(dir,{recursive:!0});let header=this.fileEntries[0],path=join5(dir,`${header.timestamp.replace(/[:.]/g,"-")}_${this.sessionId}.jsonl`);reserveSessionWrite(path),this.sessionDir=dir,this.sessionFile=path,this.persist=!0,registerSessionWriter(this)}getCwd(){return this.cwd}getSessionDir(){return this.sessionDir}usesDefaultSessionDir(){return this.sessionDir===getDefaultSessionDirPath(this.cwd)}getSessionId(){return this.sessionId}getSessionFile(){return this.sessionFile}getOwnership(){return!this.persist||!this.sessionFile?{writable:!0}:this.writeGuard.ownership(this.fileEntries)}getResidentStore(){return this.residentStore}getResidentStoreStats(){return this.residentStore.stats()}persistHeaderNow(){if(!this.persist||!this.sessionFile||this.flushed)return this.headerWrite??this.transcriptFile.ready;let sessionFile=this.sessionFile,durable=this.durable;if(this.bindPending&&(this.bindRaced=!0),durable&&this.headerWrite===void 0)try{durable.commitRewrite(this._headerLine(),this._storedEntries(this.fileEntries))}catch(error){return Promise.reject(error)}return this.headerWrite??=(durable?this._writeHeaderAsync(sessionFile).then(()=>durable.recordWhole(sessionFile),error=>durable.projectionFailed(sessionFile,error)):this._writeHeaderAsync(sessionFile)).finally(()=>{this.headerWrite=void 0}),this.headerWrite}isTranscriptFlushed(){return this.flushed}async discardHeaderOnlyFile(){return await this.headerWrite,!this.persist||!this.sessionFile||!this.flushed||this.ownedHeaderFile!==this.sessionFile||!this.fileEntries.every(isDisposableEntry)?!1:(await rm3(this.sessionFile,{force:!0}),this.ownedHeaderFile=void 0,this.flushed=!1,this.transcriptFile.reset(),!0)}async _writeHeaderAsync(sessionFile){this.writeFence.assertOwned(sessionFile),reserveSessionWrite(sessionFile);let entries=this.fileEntries,serialize=batch=>batch.map(e=>`${this._transcriptEntryBytes(e)}
|
|
33
33
|
`).join(""),written=0,handle=await open4(sessionFile,"wx");try{for(;written<entries.length;){let batch=entries.slice(written);written+=batch.length,await handle.writeFile(serialize(batch))}let closing=handle;for(this.capturesTranscriptBase&&this.sessionFile===sessionFile&&this.fileEntries===entries&&(this._captureTranscriptBase(captureFileIdentity(closing.fd,sessionFile)),await this.transcriptFile.ready),handle=void 0,await closing.close();written<entries.length&&this.sessionFile===sessionFile&&this.fileEntries===entries;){let batch=entries.slice(written);written+=batch.length,await appendFile2(sessionFile,serialize(batch))}}catch(error){return discardFailedFirstFlushAsync(sessionFile,handle,error)}if(this.sessionFile===sessionFile&&this.fileEntries===entries&&written===entries.length){this.flushed=!0,this.ownedHeaderFile=sessionFile,this.transcriptBytes=new WeakMap;let persistence=this.transcriptJournal&&this._transcriptPersistence();persistence&&this.transcriptJournal?.record({kind:"persisted",persistence})}}_hasConversation(){return this.fileEntries.some(isConversationEntry)}onRecovery(listener){this.recoveryListener=listener;for(let recovery of this.pendingRecoveries.splice(0))listener(recovery);return()=>{this.recoveryListener===listener&&(this.recoveryListener=void 0)}}_reportRecovery(recovery){this.recoveryListener===void 0?this.pendingRecoveries.push(recovery):this.recoveryListener(recovery)}_settleFinalLine(sessionFile,cause){let repair=terminateFinalSessionLine(sessionFile,cause);repair?.kind==="set_aside"&&this._reportRecovery(repair.recovery),repair?.kind==="deferred"&&(this.tailMayBeTorn=!0,this.tornTailCause=cause)}_persist(entry){if(!this.persist||!this.sessionFile)return;this.writeGuard.assertWritable(this.fileEntries,entry,this.sessionFile),this.writeFence.assertOwned(this.sessionFile),reserveSessionWrite(this.sessionFile);let durable=this.durable;if(this.bindPending&&(this.bindRaced=!0),this.flushed){let bound=durable?this._commitBoundAppend(durable,entry):void 0;if(durable&&bound&&durable.projectionStale())return durable.scheduleRepair(this.sessionFile),bound.line;if(this.tailMayBeTorn)try{let recovery=truncateToLastCompleteLine(this.sessionFile,this.tornTailCause);this.tailMayBeTorn=!1,recovery!==void 0&&this._reportRecovery(recovery)}catch(error){if(!durable||!bound)throw error;return durable.projectionFailed(this.sessionFile,error),bound.line}let bytes2=bound?.line??this._transcriptEntryBytes(entry);try{appendFileSync(this.sessionFile,`${bytes2}
|
|
34
34
|
`)}catch(error){if(this.tailMayBeTorn=!0,this.tornTailCause=sessionRecoveryCause(error),!durable||!bound)throw error;return durable.projectionFailed(this.sessionFile,error),bytes2}return durable&&bound&&durable.projected(this.sessionFile,bound),bytes2}let durableLifecycle=entry.type==="custom"&&LIFECYCLE_ENTRY_TYPES.has(entry.customType);if(!isConversationEntry(entry)&&!durableLifecycle&&!this._hasConversation())return;if(this.headerWrite&&durableLifecycle)throw new Error("Lifecycle append requires the pending session header write to finish");if(durable&&(durable.commitRewrite(this._headerLine(),this._storedEntries([...this.fileEntries,entry])),durable.projectionStale()))return this.flushed=!0,durable.scheduleRepair(this.sessionFile),this._transcriptEntryBytes(entry);if(this.headerWrite)return;let fd;try{fd=openSync(this.sessionFile,"wx")}catch(error){if(!durable)throw error;return this.flushed=!0,durable.projectionFailed(this.sessionFile,error),this._transcriptEntryBytes(entry)}let bytes;try{for(let e of[...this.fileEntries,entry]){let serialized=this._transcriptEntryBytes(e);writeFileSync2(fd,`${serialized}
|
|
35
35
|
`),e===entry&&(bytes=serialized)}}catch(error){durable||discardFailedFirstFlush(this.sessionFile,fd,error);let failure=error;try{discardFailedFirstFlush(this.sessionFile,fd,error)}catch(discarded){failure=discarded}return this.flushed=!0,durable.projectionFailed(this.sessionFile,failure),this._transcriptEntryBytes(entry)}return this.capturesTranscriptBase?this._captureTranscriptBase(captureAndCloseFileIdentity(fd,this.sessionFile)):closeSync(fd),this.flushed=!0,this.capturesTranscriptBase||(this.transcriptBytes=new WeakMap),!isConversationEntry(entry)&&!this._hasConversation()&&(this.ownedHeaderFile=this.sessionFile),durable?.recordWhole(this.sessionFile),bytes}_commitBoundAppend(durable,entry){let stored={key:storeKeyOf(entry.id),line:this._transcriptEntryBytes(entry)};return durable.commitAppend([stored]),stored}async bindDurableStore(binding){let sessionFile=this.sessionFile;if(!this.persist||sessionFile===void 0)throw new Error("only a persisted session with a file path can be bound to the durable store");this.bindPending=!0,this.bindRaced=!1;let opened;try{opened=await DurableSessionBinding.open(binding,sessionFile,this.sessionId,this._headerLine(),warning=>{for(let listener of this.projectionWarningListeners)listener(warning)},{beforeWrite:path=>{this.writeFence.assertOwned(path),reserveSessionWrite(path)},afterReplace:(_path,identity)=>{this.capturesTranscriptBase&&this._captureTranscriptBase(Promise.resolve(identity),this.fileEntries)}})}finally{this.bindPending=!1}if(this.sessionFile!==sessionFile)throw new Error(`the session moved to another file while it was being bound: ${sessionFile} was not bound`);let{session,reprojected}=opened;this.bindRaced?(session.commitRewrite(this._headerLine(),this._storedEntries(this.fileEntries)),reprojected&&session.markProjectionStale(sessionFile)):reprojected&&this.reloadFromDisk(),this.durable=session}settleDurableProjection(){return this.durable?.settled()??Promise.resolve()}onProjectionWarning(listener){return this.projectionWarningListeners.add(listener),()=>{this.projectionWarningListeners.delete(listener)}}_headerLine(){let header=this.fileEntries.find(entry=>entry.type==="session");if(header===void 0)throw new Error("the session has no header to bind");return this._transcriptEntryBytes(header)}_storedEntries(entries){return entries.flatMap(entry=>entry.type==="session"?[]:[{key:storeKeyOf(entry.id),line:this._transcriptEntryBytes(entry)}])}_appendEntry(entry,shareable,recoveryOwner,flow){let residentEntry=this.residentStore.externalize(entry),bytes=this._persist(residentEntry),committed=this._shareMessage(residentEntry,shareable);if(this._commitEntry(committed),this.transcriptJournal){let serialized=bytes??this._transcriptEntryBytes(residentEntry);this.persist&&!this.transcriptFile.unavailable&&(!this.flushed||!this.transcriptFile.identity)&&this.transcriptBytes.set(committed,serialized);let change=flow?.();this.transcriptJournal.record({kind:"append",id:residentEntry.id,type:residentEntry.type,parentId:residentEntry.parentId,entry:serialized,persistence:this._transcriptPersistence(),...recoveryOwner?{owningMessageId:recoveryOwner.messageId,recoveryEpoch:recoveryOwner.epoch}:{},...change?{flow:change}:{}})}}_shareMessage(residentEntry,shareable){if(shareable===void 0||residentEntry.type!=="message"||!this.residentStore.isTokenFree(residentEntry)||!isPlainJson(shareable))return residentEntry;let shared={...residentEntry,message:{...shareable}};return this.residentStore.adoptTokenFree(shared),shared}_commitEntry(residentEntry){this.fileEntries.push(residentEntry),this.byId.set(residentEntry.id,residentEntry),this.entryOrdersById.set(residentEntry.id,this.fileEntries.length-1),this.leafId=residentEntry.id,this.fullEntryCount++,this._accumulateUsage(residentEntry),this.mutationCount++}appendEntry(entry){this._appendEntry(entry);let order=this.entryOrdersById.get(entry.id);entry.type==="message"&&order!==void 0&&this.messageEntryPositions.set(entry.message,{entryId:entry.id,order}),entry.type==="session_info"&&(this.sessionNameCache=entry.name?.trim()||void 0),entry.type==="label"&&(entry.label?(this.labelsById.set(entry.targetId,entry.label),this.labelTimestampsById.set(entry.targetId,entry.timestamp)):(this.labelsById.delete(entry.targetId),this.labelTimestampsById.delete(entry.targetId)))}_materializeEntry(entry){let missingResidentString=!1,materialized=this.residentStore.materialize(entry,()=>{missingResidentString=!0});if(missingResidentString&&this.sessionFile){let persisted=loadEntriesFromFile(this.sessionFile).find(candidate=>candidate.id===entry.id);if(persisted)return this.callKeys.strip(persisted)}if(materialized.type==="message"){let order=this.entryOrdersById.get(materialized.id);order!==void 0&&this.messageEntryPositions.set(materialized.message,{entryId:materialized.id,order})}return materialized}_accumulateUsage(entry){if(entry.type!=="message"||entry.message.role!=="assistant")return;let usage=entry.message.usage;if(!usage)return;this.usageTotals.input+=usage.input,this.usageTotals.output+=usage.output,this.usageTotals.cacheRead+=usage.cacheRead,this.usageTotals.cacheWrite+=usage.cacheWrite,this.usageTotals.cost+=usage.cost?.total??0,usage.costUnknown&&(this.usageTotals.costUnknown=!0);let latestPromptTokens=usage.input+usage.cacheRead+usage.cacheWrite;this.usageTotals.latestCacheHitRate=latestPromptTokens>0?usage.cacheRead/latestPromptTokens*100:void 0}getUsageTotals(){return this.usageTotals}appendMessage(message){return this._appendMessage(message,!1)}appendOwnedMessage(message,options){return this._appendMessage(message,!0,options?.inputSource,options?.recoveryOwner,options?.bridgedCalls)}persistedEntry(entry){return this.callKeys.decorate(entry)}_appendMessage(message,owned,inputSource,recoveryOwner,bridgedCalls){let entry={type:"message",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),message,...inputSource===void 0?{}:{inputSource}};message.role==="assistant"&&this.callKeys.recordAssistant(entry,recoveryOwner?.messageId,bridgedCalls),message.role==="toolResult"&&this.callKeys.recordResult(entry,this.leafId,id=>this.byId.get(id)),this._appendEntry(entry,owned?message:void 0,recoveryOwner);let order=this.entryOrdersById.get(entry.id);return order!==void 0&&this.messageEntryPositions.set(message,{entryId:entry.id,order}),entry.id}getMessageEntryPosition(message){return this.messageEntryPositions.get(message)}getEntryOrder(entryId){return this.entryOrdersById.get(entryId)}appendThinkingLevelChange(thinkingLevel,thinkingSelection,trigger,model){let entry={type:"thinking_level_change",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),thinkingLevel,thinkingSelection,...trigger===void 0?{}:{triggerSource:trigger.source},...trigger?.actor===void 0?{}:{triggerActor:trigger.actor},...trigger?.effectId===void 0?{}:{effectId:trigger.effectId},...model===void 0?{}:{provider:model.provider,modelId:model.id}};return this._appendEntry(entry),entry.id}appendConfigurationUpdate(effort){let entry={type:"configuration_update",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),reasoning:{effort}};return this._appendEntry(entry),entry.id}appendModelChangeRejected(details){let entry={type:"model_change_rejected",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),...details};return this._appendEntry(entry),entry.id}appendModelChange(provider,modelId,reason,originalProvider,originalModelId,attribution){let entry={type:"model_change",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),provider,modelId,reason,originalProvider,originalModelId,...attribution===void 0?{}:{source:attribution.origin.source},...attribution?.origin.actor===void 0?{}:{actor:attribution.origin.actor},...attribution?.duringTurn?{duringTurn:!0}:{},...attribution?.origin.effectId===void 0?{}:{effectId:attribution.origin.effectId}};return this._appendEntry(entry),entry.id}appendUsage(kind,provider,model,usage,note){let entry={type:"usage",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),kind,provider,model,usage,...note?{note}:{}};return this._appendEntry(entry),entry}appendCompaction(summary,firstKeptEntryId,tokensBefore,details,fromHook,usage){let timestamp=new Date().toISOString(),from=this.buildSessionProjection(),systemMessage=getCurrentSystemMessage(from.messages),id=generateId(this.idsInUse),entry={type:"compaction",id,parentId:this.leafId,timestamp,summary,firstKeptEntryId:firstKeptEntryId??id,tokensBefore,details,usage,fromHook,...systemMessage?{systemMessage:{...systemMessage,timestamp:new Date(timestamp).getTime()}}:{}};return this._appendEntry(entry,void 0,void 0,()=>compactionFlow(from.entries,this.buildSessionProjection().entries)),this._trimMirrorAfterCompaction(entry),entry.id}dispose(){this.transcriptFile.reset(),unregisterSessionWriter(this),this._releaseBlobsDirUnlessShared()}_releaseBlobsDirUnlessShared(){let blobsDir=this.residentStore.resolvedBlobsDir();blobsDir&&(this.sessionFile&&hasOtherLiveSessionWriter(this.sessionFile,this)||this._removeBlobsDir(blobsDir))}_removeBlobsDir(dir){try{rmSync2(dir,{force:!0,recursive:!0})}catch{}}_trimMirrorAfterCompaction(compaction){if(!this.persist)return;let firstKeptIndex=this.fileEntries.findIndex(entry=>entry.id===compaction.firstKeptEntryId),compactionIndex=this.fileEntries.findIndex(entry=>entry.id===compaction.id);if(firstKeptIndex<0||compactionIndex<firstKeptIndex)return;let verbatimStart=this.fileEntries.length-(this.fullEntryCount-this.verbatimFromCount),header=this.fileEntries.find(entry=>entry.type==="session"),branchIds=new Set(this.getBranch().map(entry=>entry.id)),firstVerbatimIndex=Math.max(firstKeptIndex,verbatimStart);for(let i=firstVerbatimIndex;i<compactionIndex;i++)branchIds.has(this.fileEntries[i].id)||(firstVerbatimIndex=i+1);this.verbatimFromCount=this.fullEntryCount-(compactionIndex+1-firstVerbatimIndex);let retained=[...this.fileEntries.slice(0,firstKeptIndex).filter(entry=>entry.type!=="message"),...this.fileEntries.slice(firstKeptIndex,compactionIndex+1).filter(entry=>branchIds.has(entry.id))],parentId=null;for(let entry of retained)entry.type!=="session"&&(entry.parentId=parentId),parentId=entry.type==="session"?null:entry.id;let retainedIds=new Set(retained.map(entry=>entry.id));for(let entry of this.fileEntries)entry.type!=="session"&&!retainedIds.has(entry.id)&&this.trimmedIds.add(entry.id);this.residentStore.spillResident(),this.mirrorTrimmed=!0,this.fileEntries=[header,...retained].filter(entry=>entry!==void 0).map(entry=>this.residentStore.externalize(entry)),this._buildIndex(),this.mutationCount++}appendCustomEntry(customType,data,options){let entry={type:"custom",customType,data,...options?.startupBookkeeping===!0?{startupBookkeeping:!0}:{},id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(entry),entry.id}appendSessionInfo(name){let sanitizedName=name.replace(/[\r\n]+/g," ").trim(),entry={type:"session_info",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),name:sanitizedName};return this._appendEntry(entry),this.sessionNameCache=sanitizedName||void 0,entry.id}getSessionName(){return this.sessionNameCache}appendCustomMessageEntry(customType,content,display,details,options){let entry={type:"custom_message",customType,content,display,details,id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(entry,void 0,options?.recoveryOwner),entry.id}appendContextEdit(targetId,replacement){if(replacement!==null&&(typeof replacement!="object"||!("content"in replacement)||typeof replacement.content!="string"&&!Array.isArray(replacement.content)))throw new Error("Context edit replacement must be null or contain string/array content");let target=this.byId.get(targetId);if(!target)throw new Error(`Entry ${targetId} not found`);if(!this.getBranch().some(entry2=>entry2.id===targetId))throw new Error(`Entry ${targetId} is not on the active branch`);if(!(target.type==="custom_message"||target.type==="message"&&(target.message.role==="user"||target.message.role==="assistant"||target.message.role==="toolResult")))throw new Error(`Entry ${targetId} does not contribute editable model content`);let targetRole=target.type==="message"?target.message.role:"custom",normalizedReplacement=replacement!==null&&(targetRole==="assistant"||targetRole==="toolResult")&&typeof replacement.content=="string"?{content:[{type:"text",text:replacement.content}]}:replacement,entry={type:"context_edit",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),targetId,replacement:normalizedReplacement};return this._appendEntry(entry,void 0,void 0,()=>{let edited=this.getEntry(targetId);return contextEditFlow(entry,edited&&ownedFlowMessage(projectContextEntry(edited,entry)[0]))}),entry.id}getLeafId(){return this.leafId}getLeafEntry(){let entry=this.leafId?this.byId.get(this.leafId):void 0;return entry?this._materializeEntry(entry):void 0}getEntry(id){let entry=this.byId.get(id);if(entry)return this._materializeEntry(entry);if(this.mirrorTrimmed&&this.sessionFile){let persisted=this._loadFullHistoryEntries().find(candidate=>candidate.id===id);return persisted?this.residentStore.materialize(persisted):void 0}}getChildren(parentId){let children=[];for(let entry of this.byId.values())entry.parentId===parentId&&children.push(this._materializeEntry(entry));return children}getLabel(id){return this.labelsById.get(id)}appendLabelChange(targetId,label){if(!this.byId.has(targetId)&&!this.getEntries().some(entry2=>entry2.id===targetId))throw new Error(`Entry ${targetId} not found`);let entry={type:"label",id:generateId(this.idsInUse),parentId:this.leafId,timestamp:new Date().toISOString(),targetId,label};return this._appendEntry(entry),label?(this.labelsById.set(targetId,label),this.labelTimestampsById.set(targetId,entry.timestamp)):(this.labelsById.delete(targetId),this.labelTimestampsById.delete(targetId)),entry.id}getBranch(fromId){if(fromId===void 0&&this.branchCache!==null&&this.branchCache.leafId===this.leafId&&this.branchCache.mutation===this.mutationCount)return this.branchCache.entries;if(fromId===void 0){let extended=this._extendBranchCache();if(extended!==void 0)return extended}let path=[],startId=fromId??this.leafId,entriesById=this.byId;fromId!==void 0&&!entriesById.has(fromId)&&this.mirrorTrimmed&&this.sessionFile&&(entriesById=new Map(this._loadFullHistoryEntries().filter(entry=>entry.type!=="session").map(entry=>[entry.id,this.residentStore.materialize(entry)])));let current=startId?entriesById.get(startId):void 0,visited=new Set;for(;current&&!visited.has(current);)visited.add(current),path.push(current),current=current.parentId?entriesById.get(current.parentId):void 0;path.reverse();let materializedPath=(entriesById===this.byId?this._fromCompactView(path):void 0)??this._materializeEntries(path);return fromId===void 0&&(this.branchCache={leafId:this.leafId,mutation:this.mutationCount,entries:materializedPath,source:this.fileEntries}),materializedPath}getFullBranch(fromId){if(!this.mirrorTrimmed||!this.sessionFile)return this.getBranch(fromId);let byId=new Map;for(let entry of this.getEntries())byId.set(entry.id,entry);let path=[],visited=new Set,current=byId.get(fromId??this.leafId??"");for(;current&&!visited.has(current.id);)visited.add(current.id),path.push(current),current=current.parentId?byId.get(current.parentId):void 0;return path.reverse()}_extendBranchCache(){let cache2=this.branchCache;if(cache2===null||cache2.source!==this.fileEntries||cache2.leafId===null)return;let added=[],current=this.leafId?this.byId.get(this.leafId):void 0;for(;current&¤t.id!==cache2.leafId;){if(added.length>=256)return;added.push(current),current=current.parentId?this.byId.get(current.parentId):void 0}if(current===void 0)return;added.reverse();let entries=[...cache2.entries,...this._fromCompactView(added)??this._materializeEntries(added)];return this.branchCache={leafId:this.leafId,mutation:this.mutationCount,entries,source:this.fileEntries},entries}buildContextEntries(){return buildContextEntries(this._getCompactEntries(),this.leafId)}buildSessionProjection(){let{projection}=this._projectCurrent();return{...projection,messages:[...projection.messages],entries:[...projection.entries]}}_projectCurrent(){let entries=this._getCompactEntries(),memo=this.projectionMemo;if(memo?.source===entries&&memo.leafId===this.leafId)return memo.result;let path=this._extendPath(memo,entries)??buildSessionPath(entries,this.leafId),result=projectSession(entries,this.leafId,void 0,path);return this.projectionMemo={source:entries,leafId:this.leafId,path,result},result}_extendPath(memo,entries){if(!memo||memo.leafId===null||this.leafId===null)return;let previous=memo.source;if(entries.length<=previous.length||entries[previous.length-1]!==previous[previous.length-1])return;let parentId=memo.leafId,appended=[];for(let index=previous.length;index<entries.length;index++){let entry=entries[index];if(entry.parentId!==parentId)return;appended.push(entry),parentId=entry.id}if(parentId===this.leafId)return[...memo.path,...appended]}buildSessionContext(){let{projection,settings}=this._projectCurrent(),{thinkingLevel,thinkingSelection,model,configurationUpdate}=settings;return{messages:[...projection.messages],thinkingLevel,thinkingSelection,model,configurationUpdate}}hasContextMessages(){return this.hasBranchEntry(entry=>entry.type==="message"||entry.type==="custom_message"||entry.type==="compaction"||entry.type==="branch_summary"&&!!entry.summary)}hasThinkingLevelChanges(){return this.hasBranchEntry(entry=>entry.type==="thinking_level_change")}countCompactions(){let count=0;for(let entry of this.fileEntries)entry.type==="compaction"&&count++;return count}hasBranchEntry(predicate){let current=this.leafId?this.byId.get(this.leafId):void 0,visited=new Set;for(;current&&!visited.has(current);){if(predicate(current))return!0;visited.add(current),current=current.parentId?this.byId.get(current.parentId):void 0}return!1}getHeader(){let h=this.fileEntries.find(e=>e.type==="session");return h?this.residentStore.materialize(h):null}getEntries(){if(this.mirrorTrimmed&&this.sessionFile){let extended=this._extendView(this.historyView);if(extended!==void 0)return this.historyView={source:this.fileEntries,length:this.fileEntries.length,entries:extended},extended;let history=this._loadFullHistoryEntries().filter(e=>e.type!=="session").map(entry=>this.residentStore.materialize(entry));return this.historyView={source:this.fileEntries,length:this.fileEntries.length,entries:history},history}if(this.entriesCache!==null&&this.entriesCache.mutation===this.mutationCount)return this.entriesCache.entries;let materializedEntries=this._getCompactEntries();return this.entriesCache={mutation:this.mutationCount,entries:materializedEntries},materializedEntries}getEntryCount(){return this.fullEntryCount}reduceHistory(reducer){return this.historyReductions.reduce(reducer)}_appendedSince(count){if(count<this.verbatimFromCount)return;let wanted=this.fullEntryCount-count,appended=[],missing=!1;for(let index=this.fileEntries.length-1;index>=0&&appended.length<wanted;index--){let entry=this.fileEntries[index];if(entry.type==="session")break;appended.push(this.residentStore.materialize(entry,()=>{missing=!0}))}return missing||appended.length<wanted?void 0:appended.reverse()}_readWholeHistory(){if(!this.mirrorTrimmed||!this.sessionFile)return this._getCompactEntries();let held=this._extendView(this.historyView);return held!==void 0?held:this._loadFullHistoryEntries().filter(entry=>entry.type!=="session").map(entry=>this.residentStore.materialize(entry))}dropMaterializedCaches(){this.entriesCache=null,this.branchCache=null,this.compactEntriesCache=null,this.compactView=null,this.historyView=null,this.compactLookup=null,this.projectionMemo=null}holdsMaterializedHistory(){return this.historyView!==null}_extendView(view){if(view===null||view.source!==this.fileEntries||view.length>this.fileEntries.length)return;if(view.length===this.fileEntries.length)return view.entries;let missing=!1,tail=[];for(let entry of this.fileEntries.slice(view.length)){if(entry.type==="session")continue;let materialized=this.residentStore.materialize(entry,()=>{missing=!0});tail.push(materialized)}if(!missing)return this._bindMessagePositions(tail),[...view.entries,...tail]}_fromCompactView(path){let entries=this._getCompactEntries(),lookup=this.compactLookup;(lookup===null||lookup.length>entries.length||lookup.length>0&&lookup.entries[lookup.length-1]!==entries[lookup.length-1])&&(lookup={entries,length:0,map:new Map});for(let index=lookup.length;index<entries.length;index++){let entry=entries[index];lookup.map.set(entry.id,entry)}this.compactLookup={entries,length:entries.length,map:lookup.map};let shared=[];for(let entry of path){let materialized=lookup.map.get(entry.id);if(materialized===void 0||materialized.parentId!==entry.parentId)return;shared.push(materialized)}return shared}_bindMessagePositions(entries){for(let entry of entries){if(entry.type!=="message")continue;let order=this.entryOrdersById.get(entry.id);order!==void 0&&this.messageEntryPositions.set(entry.message,{entryId:entry.id,order})}}_materializeEntries(entries){return materializeSessionEntries(entries,{residentStore:this.residentStore,loadHistoryEntries:()=>this._loadFullHistoryEntries(),onMaterialized:entry=>{if(entry.type!=="message")return;let order=this.entryOrdersById.get(entry.id);order!==void 0&&this.messageEntryPositions.set(entry.message,{entryId:entry.id,order})}})}_getCompactEntries(){let extended=this._extendView(this.compactView);if(extended!==void 0)return this.compactView={source:this.fileEntries,length:this.fileEntries.length,entries:extended},extended;this.compactEntriesCache?.mutation!==this.mutationCount&&(this.compactEntriesCache={mutation:this.mutationCount,entries:this.fileEntries.filter(e=>e.type!=="session")});let entries=this.compactEntriesCache.entries,missingEntryIds=new Set;for(let entry of entries)this.residentStore.materialize(entry,()=>{missingEntryIds.add(entry.id)});if(missingEntryIds.size>0&&this.sessionFile){let persistedById=new Map(this._loadFullHistoryEntries().map(entry=>[entry.id,entry]));for(let index=0;index<entries.length;index++){let entry=entries[index];if(!missingEntryIds.has(entry.id))continue;let persisted=persistedById.get(entry.id);persisted&&(entries[index]=this.residentStore.externalize(persisted))}}let materialized=entries.map(entry=>this.residentStore.materialize(entry));return this._bindMessagePositions(materialized),this.compactView={source:this.fileEntries,length:this.fileEntries.length,entries:materialized},materialized}_loadFullHistoryEntries(){return this.sessionFile?sessionEntryLoader(this.sessionFile).map(entry=>this.callKeys.strip(entry)):this.fileEntries}getTree(){let entries=this.getEntries(),nodeMap=new Map,roots=[];for(let entry of entries){if(nodeMap.has(entry.id))continue;let label=this.labelsById.get(entry.id),labelTimestamp=this.labelTimestampsById.get(entry.id);nodeMap.set(entry.id,{entry,children:[],label,labelTimestamp})}for(let entry of entries){let node=nodeMap.get(entry.id);if(node.entry===entry)if(entry.parentId===null||entry.parentId===entry.id)roots.push(node);else{let parent=nodeMap.get(entry.parentId);parent?parent.children.push(node):roots.push(node)}}let stack=[...roots];for(;stack.length>0;){let node=stack.pop();node.children.sort((a,b)=>new Date(a.entry.timestamp).getTime()-new Date(b.entry.timestamp).getTime()),stack.push(...node.children)}return roots}branch(branchFromId){if(this._loadFullMirrorFor(branchFromId),!this.byId.has(branchFromId))throw new Error(`Entry ${branchFromId} not found`);let from=this.transcriptJournal&&this.buildSessionProjection().entries;this.leafId=branchFromId,this.mutationCount++,this.transcriptJournal?.record({kind:"leaf",leafId:branchFromId,...this._branchFlow(from)})}resetLeaf(){let from=this.transcriptJournal&&this.buildSessionProjection().entries;this.leafId=null,this.mutationCount++,this.transcriptJournal?.record({kind:"leaf",leafId:null,...this._branchFlow(from)})}branchWithSummary(branchFromId,summary,details,fromHook,usage){if(branchFromId!==null&&this._loadFullMirrorFor(branchFromId),branchFromId!==null&&!this.byId.has(branchFromId))throw new Error(`Entry ${branchFromId} not found`);let fromId=this.leafId??"root",entry={type:"branch_summary",id:generateId(this.idsInUse),parentId:branchFromId,timestamp:new Date().toISOString(),fromId,summary,details,usage,fromHook},from=this.transcriptJournal&&this.buildSessionProjection().entries;return this._appendEntry(entry,void 0,void 0,()=>this._branchFlow(from).flow),entry.id}_branchFlow(from){return from?{flow:branchFlow(from,this.buildSessionProjection().entries)}:{}}createBranchedSession(leafId){let previousSessionFile=this.sessionFile,path=this.getFullBranch(leafId);if(path.length===0)throw new Error(`Entry ${leafId} not found`);this.transcriptFile.reset(),this.transcriptBytes=new WeakMap;let pathWithoutLabels=[],replacementByLabelId=new Map,pendingLabelIds=[],pathParentId=null;for(let entry of path){if(entry.type==="label"){pendingLabelIds.push(entry.id);continue}for(let labelId of pendingLabelIds)replacementByLabelId.set(labelId,entry.id);pendingLabelIds.length=0,pathWithoutLabels.push(entry.type==="compaction"?{...entry,parentId:pathParentId,firstKeptEntryId:entry.firstKeptEntryId===entry.id?entry.id:replacementByLabelId.get(entry.firstKeptEntryId)??entry.firstKeptEntryId}:{...entry,parentId:pathParentId}),pathParentId=entry.id}let newSessionId=createSessionId(),timestamp=new Date().toISOString(),fileTimestamp=timestamp.replace(/[:.]/g,"-"),newSessionFile=join5(this.getSessionDir(),`${fileTimestamp}_${newSessionId}.jsonl`),header={type:"session",version:CURRENT_SESSION_VERSION,id:newSessionId,timestamp,cwd:this.cwd,parentSession:this.persist?previousSessionFile:void 0},pathEntryIds=new Set(pathWithoutLabels.map(e=>e.id)),labelsToWrite=[];for(let[targetId,label]of this.labelsById)pathEntryIds.has(targetId)&&labelsToWrite.push({targetId,label,timestamp:this.labelTimestampsById.get(targetId)});if(this.persist){let parentId2=pathWithoutLabels[pathWithoutLabels.length-1]?.id||null,labelEntries2=[];for(let{targetId,label,timestamp:labelTimestamp}of labelsToWrite){let labelEntry={type:"label",id:generateId(new Set(pathEntryIds)),parentId:parentId2,timestamp:labelTimestamp,targetId,label};pathEntryIds.add(labelEntry.id),labelEntries2.push(labelEntry),parentId2=labelEntry.id}reserveSessionWrite(newSessionFile);let branchedEntries2=this._materializeEntries([...pathWithoutLabels,...labelEntries2]),previousBlobsDir=this.residentStore.resolvedBlobsDir();return this.residentStore.clear(),previousBlobsDir&&this._removeBlobsDir(previousBlobsDir),this.mirrorTrimmed=!1,this.trimmedIds.clear(),this.durable=void 0,this.sessionId=newSessionId,this.sessionFile=newSessionFile,this.fileEntries=[header,...branchedEntries2.map(entry=>this.residentStore.externalize(entry))],this._buildIndex(),this.historyGeneration++,this.mutationCount++,this._hasConversation()?(this._rewriteFile(),this.flushed=!0):this.flushed=!1,this._journalReplace(),newSessionFile}let labelEntries=[],parentId=pathWithoutLabels[pathWithoutLabels.length-1]?.id||null;for(let{targetId,label,timestamp:labelTimestamp}of labelsToWrite){let labelEntry={type:"label",id:generateId(new Set([...pathEntryIds,...labelEntries.map(e=>e.id)])),parentId,timestamp:labelTimestamp,targetId,label};labelEntries.push(labelEntry),parentId=labelEntry.id}let branchedEntries=this._materializeEntries([...pathWithoutLabels,...labelEntries]);this.residentStore.clear(),this.fileEntries=[header,...branchedEntries.map(entry=>this.residentStore.externalize(entry))],this.sessionId=newSessionId,this._buildIndex(),this.historyGeneration++,this.mutationCount++,this._journalReplace()}static create(cwd,sessionDir,options){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd);return new _SessionManager(cwd,dir,void 0,!0,options)}static open(path,sessionDir,cwdOverride,options){let resolvedPath=resolvePath(path);reserveSessionWrite(resolvedPath);let discovery=discoverOpenHeader(resolvedPath,cwdOverride),preloadedFileEntries=discovery.needsFullLoad?loadEntriesFromFile(resolvedPath,compactUpdatesEnabled()):void 0,header=discovery.header??headerOf(preloadedFileEntries),{cwd,dir}=openLocation(resolvedPath,sessionDir,cwdOverride,header);return new _SessionManager(cwd,dir,resolvedPath,!0,options,preloadedFileEntries)}static async openAsync(path,sessionDir,cwdOverride,options,slicer=new EventLoopSlicer){let resolvedPath=resolvePath(path);reserveSessionWrite(resolvedPath);let discovery=discoverOpenHeader(resolvedPath,cwdOverride),preloadedFileEntries=discovery.needsFullLoad?await loadEntriesFromFileAsync(resolvedPath,slicer,compactUpdatesEnabled()):void 0,header=discovery.header??headerOf(preloadedFileEntries),{cwd,dir}=openLocation(resolvedPath,sessionDir,cwdOverride,header),manager=new _SessionManager(cwd,dir,resolvedPath,!0,options,DEFERRED_FILE_LOAD);try{await manager._setSessionFileAsync(resolvedPath,preloadedFileEntries,options,slicer)}catch(error){throw manager.dispose(),error}return manager}static continueRecent(cwd,sessionDir){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),mostRecent=_SessionManager.recentSessionFile(cwd,sessionDir);return mostRecent?new _SessionManager(cwd,dir,mostRecent,!0):new _SessionManager(cwd,dir,void 0,!0)}static recentSessionFile(cwd,sessionDir){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),filterCwd=sessionDir!==void 0&&dir!==getDefaultSessionDirPath(cwd);return findMostRecentSession(dir,filterCwd?cwd:void 0)}static inMemory(cwd=process.cwd(),options,entries){return new _SessionManager(cwd,"",void 0,!1,options,entries)}static forkFrom(sourcePath,targetCwd,sessionDir,options){let resolvedSourcePath=resolvePath(sourcePath),resolvedTargetCwd=resolvePath(targetCwd),source=readForkSource(resolvedSourcePath);if(source.kind==="empty")throw new Error(`Cannot fork: source session file is empty or has no readable entries: ${resolvedSourcePath}`);if(source.kind==="not-a-session")throw new Error(`Cannot fork: source file is not a session file (no entry has a session header or a session entry shape): ${resolvedSourcePath}`);let sourceEntries=source.entries,dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(resolvedTargetCwd);existsSync3(dir)||mkdirSync2(dir,{recursive:!0}),options?.id!==void 0&&assertValidSessionId(options.id);let newSessionId=options?.id??createSessionId(),timestamp=new Date().toISOString(),fileTimestamp=timestamp.replace(/[:.]/g,"-"),newSessionFile=join5(dir,`${fileTimestamp}_${newSessionId}.jsonl`),newHeader={type:"session",version:CURRENT_SESSION_VERSION,id:newSessionId,timestamp,cwd:resolvedTargetCwd,parentSession:resolvedSourcePath};reserveSessionWrite(newSessionFile),writeFileSync2(newSessionFile,`${JSON.stringify(newHeader)}
|
|
@@ -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-ZUQCYIRY.js";import{usageLimitScope}from"./chunk-HKCFMDJN.js";import{userWordBlocks}from"./chunk-3Q5ZENSD.js";import{isWSL}from"./chunk-4GKU755E.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{appendHiddenTuiStdout}from"./chunk-MSDBBOB2.js";import{CURSOR_MARKER,Container,Editor,Input,Markdown,MouseRegion,ProcessTerminal,ScrollView,Spacer,Text,TuiAltScreen,TuiMainScreen,VStack,getKeybindings,getNativeClipboard,isWarpWslSession,matchesKey,nextRenderRevision,truncateToWidth,visibleWidth}from"./chunk-TMXRR3N7.js";import{redactSensitiveOutput}from"./chunk-BPNSOZ2C.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-2ODGHBUD.js";import{usageLimitScope}from"./chunk-HKCFMDJN.js";import{userWordBlocks}from"./chunk-E6ZBTSC6.js";import{isWSL}from"./chunk-4GKU755E.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{appendHiddenTuiStdout}from"./chunk-5H43O4MA.js";import{CURSOR_MARKER,Container,Editor,Input,Markdown,MouseRegion,ProcessTerminal,ScrollView,Spacer,Text,TuiAltScreen,TuiMainScreen,VStack,getKeybindings,getNativeClipboard,isWarpWslSession,matchesKey,nextRenderRevision,truncateToWidth,visibleWidth}from"./chunk-TMXRR3N7.js";import{redactSensitiveOutput}from"./chunk-QUVSIW2R.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,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{usageLimitResetMs}from"./chunk-WB4BUHOH.js";import{rateLimitModelFamily}from"./chunk-NJ43NBSP.js";import{normalizeProviderError}from"./chunk-AC72EWI5.js";import{extract429RetryAfterMs,parseRetryAfterMsMarker}from"./chunk-RQFD6LG2.js";import{getOverflowPatterns}from"./chunk-WXYMAUFX.js";import{ModelsError,OAuthTokenEndpointError,PROVIDER_NOT_CONFIGURED_PREFIX,USAGE_LIMIT_EXHAUSTION,isOAuthRefreshUnavailableError}from"./chunk-OH5TKHW7.js";import{credentialPoolBlockedDiagnostic,readProviderDiagnostic}from"./chunk-JGKH3D6W.js";import{attachProviderDiagnostic,siwcRecoveryFromDiagnostic}from"./chunk-3SASTB6Y.js";function rendezvousOrder(key,slots,hasher){return[...slots].map(slot=>({slot,score:hasher(`${key}\0${slot.name}`)})).sort((left,right)=>right.score>left.score?1:right.score<left.score?-1:0).map(({slot})=>slot)}function applyAccountOrder(order,ranked){if(order===void 0||order.length===0)return[...ranked];let byName=new Map(ranked.map(slot=>[slot.name,slot])),front=[];for(let name of order){let slot=byName.get(name);slot!==void 0&&!front.includes(slot)&&front.push(slot)}return[...front,...ranked.filter(slot=>!front.includes(slot))]}function withoutOrderedAccount(credential,name){if(credential.order===void 0||!credential.order.includes(name))return credential;let order=credential.order.filter(entry=>entry!==name),next={...credential};return order.length===0?delete next.order:next.order=order,next}function isSlotBlocked(slot,now){return slot.blockReason==="auth_error"||slot.blockedUntil!==void 0&&slot.blockedUntil>now}var DEFAULT_SLOT_BLOCK_MS=6e4,MAX_SLOT_BLOCK_MS=2880*60*1e3;function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ACCOUNT_USAGE_LIMIT_TEXT=new RegExp([...USAGE_LIMIT_EXHAUSTION.markers.map(escapeRegExp),String.raw`\b(?:hit|reached)\s+your\b[^.]*?\blimit\b`,String.raw`\busage\s+limit\s+reached\b`,String.raw`\b(?:Go|Free)UsageLimitError\b`,String.raw`\bblocking_limit\b`,String.raw`\brapid_refill_breaker\b`,String.raw`\bquota\s+exceeded\b`].join("|"),"i");function isAccountUsageLimitText(text){return ACCOUNT_USAGE_LIMIT_TEXT.test(text)}var COOLDOWN_BASE_MS=DEFAULT_SLOT_BLOCK_MS,COOLDOWN_CAP_MS=MAX_SLOT_BLOCK_MS,GUESSED_BACKOFF_CAP_MS=1800*1e3,RETRY_SAME_MAX_ATTEMPTS=2,ACCOUNT_POOL_REFUSAL_NOTE="No request was sent: the account pool refused it locally.";function rateLimitCooldown(failureCount,serverHintMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS,base=policy.baseMs??COOLDOWN_BASE_MS,backoff=Math.min(cap,GUESSED_BACKOFF_CAP_MS,base*2**Math.max(0,failureCount)),floored=serverHintMs===void 0?backoff:Math.max(backoff,serverHintMs);return{cooldownMs:Math.min(cap,floored),retryAfterWasCapped:floored>cap}}function usageLimitCooldown(resetMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS;return{cooldownMs:Math.min(cap,resetMs),retryAfterWasCapped:resetMs>cap}}var INVALID_KEY_TEXT=/invalid[ _-]?(?:api[ _-]?)?key|authentication[_ ]?error|invalid x-api-key|unauthorized/i,REVOKED_TOKEN_TEXT=/invalidated (?:oauth )?token|(?<!\b(?:session|csrf|xsrf|page|pagination|continuation|cursor|sync|stream|upload|idempotency|request|nonce|state)[ _-])token(?:[ _-](?:invalidated|revoked)|\s(?:has been|was) (?:invalidated|revoked))/i,REFUSED_GRANT_CODES=new Set(["invalid_grant","refresh_token_expired","refresh_token_invalidated","refresh_token_reused","token_revoked"]),REFUSED_GRANT_TOKEN=/(?<![a-z_])(invalid_grant|refresh_token_(?:expired|invalidated|reused)|token_revoked)(?![a-z_])/,CLIENT_FAULT_CODES=new Set(["invalid_client","invalid_request","invalid_scope","unauthorized_client","unsupported_grant_type"]),NETWORK_FAULT_CODES=new Set(["ECONNRESET","ECONNREFUSED","ECONNABORTED","ETIMEDOUT","EHOSTUNREACH","EHOSTDOWN","ENETUNREACH","ENETDOWN","ENETRESET","ENOTFOUND","EAI_AGAIN","EPIPE","EADDRNOTAVAIL","ERR_SOCKET_CONNECTION_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET","UND_ERR_CLOSED","ConnectionRefused","ConnectionClosed","FailedToOpenSocket"]),AUTH_ERROR_CODES=new Set(["authentication_error","invalid_api_key","token_invalidated",...REFUSED_GRANT_CODES]),MAX_CAUSE_LINKS=16,ACCOUNT_SCOPED_403_TEXT=/account|credential|token|api[ _-]?key|organization|subscription/i,MODEL_SCOPED_REFUSAL_TEXT=[/(?:does not include(?: access to)?|not entitled to(?: use)?|no access to)[^.]{0,60}?\bmodel\b/i,/\bmodel\b.{0,80}?\b(?:is not|not|no)\b.{0,40}?\b(?:available|included|entitled|enabled|accessible)\b.{0,40}?\b(?:plan|subscription)\b/i,/(?:plan|subscription)[^.]{0,30}?\bdoes not\b[^.]{0,20}?\binclude access to\b/i],RATE_LIMIT_TEXT=/rate[ _-]?limit|too many requests|resource_exhausted/i,BILLING_TEXT=/billing|credits?[ _-]?(?:required|exhausted|balance)|insufficient[ _-]?(?:funds|quota|credit)|payment[ _-]?required|quota[ _-]?exhausted/i,OVERLOAD_TEXT=/overloaded/i,NETWORK_TEXT=/econnreset|econnrefused|etimedout|enotfound|socket hang up|fetch failed|network error|request timed out/i,WEBSOCKET_REQUEST_FAULT_TEXT=/websocket closed 100[89]\b/i,WEBSOCKET_TRANSPORT_FAULT_TEXT=/websocket (?:closed|error|connect timeout|liveness timeout)/i,FAIL_FAST_TEXT=/context[ _-]?(?:length|window)|maximum context|invalid[ _-]?model|model[ _-]?not[ _-]?found|malformed[ _-]?stream|premature[ _-]?(?:close|stream)/i,ABORT_TEXT=/\baborted?\b/i,TEMPORARY_FAULT_TEXT=/time[ds]?[ _-]?out|timed out|disconnect|reset before|connection reset|gateway|temporarily|unavailable/i;function limitFromProviderCode(error){let diagnostic=readProviderDiagnostic(error);if(diagnostic?.evidence==="structured_code")switch(diagnostic.code){case"rate_limit_exceeded":return{kind:"throttle"};case"usage_limit_reached":case"usage_not_included":return diagnostic.resetsAt===void 0?{kind:"spent"}:{kind:"spent",resetsAt:diagnostic.resetsAt};default:return}}function isAbort(error,message){return error instanceof Error&&error.name==="AbortError"?!0:ABORT_TEXT.test(message)}function failedRefresh(error){let seen=new Set;for(;typeof error=="object"&&error!==null&&!seen.has(error)&&seen.size<MAX_CAUSE_LINKS;){if(seen.add(error),error instanceof ModelsError)return error.code==="oauth"?error:void 0;error=Reflect.get(error,"cause")}}function oauthBodyErrorCode(message){let start=message.indexOf("{"),end=message.lastIndexOf("}");if(!(start<0||end<=start))try{let body=JSON.parse(message.slice(start,end+1));if(typeof body!="object"||body===null)return;let field=Reflect.get(body,"error");if(typeof field=="string")return field;if(typeof field=="object"&&field!==null){let code=Reflect.get(field,"code");return typeof code=="string"?code:void 0}return}catch{return}}function isRefusedGrant(refresh){let cause=refresh.cause;if(!(cause instanceof OAuthTokenEndpointError))return!1;let code=cause.oauthError??oauthBodyErrorCode(cause.message);return code!==void 0&&CLIENT_FAULT_CODES.has(code)?!1:cause.credentialRefused||cause.status===401?!0:code!==void 0&&REFUSED_GRANT_CODES.has(code)?[400,403,404].includes(cause.status):cause.status===400&&REFUSED_GRANT_TOKEN.test(cause.message)}function isRefreshNetworkFault(refresh,text){let seen=new Set,error=refresh.cause;for(;typeof error=="object"&&error!==null&&!seen.has(error)&&seen.size<MAX_CAUSE_LINKS;){if(seen.add(error),error instanceof OAuthTokenEndpointError)return!1;let code=Reflect.get(error,"code");if(typeof code=="string")return NETWORK_FAULT_CODES.has(code);error=Reflect.get(error,"cause")}return NETWORK_TEXT.test(text)}function hasAuthDiagnostic(error){let diagnostic=readProviderDiagnostic(error);return diagnostic===void 0?!1:diagnostic.category==="auth"||diagnostic.code!==void 0&&AUTH_ERROR_CODES.has(diagnostic.code)}function isOverflowText(text){return getOverflowPatterns().some(pattern=>pattern.test(text))}function classifyCredentialFailure(error,context={}){if(isOAuthRefreshUnavailableError(error))return{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS};let normalized=normalizeProviderError(error),text=normalized.messageCarriesBody?normalized.message:`${normalized.message} ${normalized.body??""}`,status=normalized.status,failureCount=context.failureCount??0;if(error instanceof Error&&error.name==="AbortError")return{kind:"fail_request"};switch(siwcRecoveryFromDiagnostic(readProviderDiagnostic(error))){case"usage_limit":return{kind:"failover",block:{reason:"rate_limit",usageLimit:!0,...rateLimitCooldown(failureCount,void 0,{baseMs:context.cooldownBaseMs,capMs:Math.min(context.cooldownCapMs??COOLDOWN_CAP_MS,30*6e4)})}};case"account_disabled":return{kind:"failover",block:{reason:"account_disabled"}};case"auth":return{kind:"failover",block:{reason:"auth_error"}};case"request":return{kind:"fail_request"};case"transient":return{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS};case void 0:break}if(isAbort(error,text))return{kind:"fail_request"};if(text.includes(ACCOUNT_POOL_REFUSAL_NOTE))return{kind:"fail_request"};let providerFault=status===408||status!==void 0&&status>=500&&status<600||status===void 0&&(TEMPORARY_FAULT_TEXT.test(text)||NETWORK_TEXT.test(text)||OVERLOAD_TEXT.test(text)),codedLimit=limitFromProviderCode(error),usageLimit=codedLimit!==void 0?codedLimit.kind==="spent":isAccountUsageLimitText(text)&&!isOverflowText(text),limitText=codedLimit!==void 0||RATE_LIMIT_TEXT.test(text)||usageLimit;if(text.includes(PROVIDER_NOT_CONFIGURED_PREFIX))return{kind:"failover",block:{reason:"auth_error"}};let statusFault=status===408||status===429||status!==void 0&&status>=500&&status<600,refresh=failedRefresh(error);if(refresh!==void 0)return!statusFault&&isRefusedGrant(refresh)?{kind:"failover",block:{reason:"auth_error"}}:isRefreshNetworkFault(refresh,text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"};if(!providerFault&&status!==429&&hasAuthDiagnostic(error))return{kind:"failover",block:{reason:"auth_error"}};if(status===401||!providerFault&&status!==429&&(INVALID_KEY_TEXT.test(text)||REVOKED_TOKEN_TEXT.test(text)))return{kind:"failover",block:{reason:"auth_error"}};if(status===403&&!limitText)return MODEL_SCOPED_REFUSAL_TEXT.some(pattern=>pattern.test(text))?{kind:"fail_request"}:ACCOUNT_SCOPED_403_TEXT.test(text)?{kind:"failover",block:{reason:"auth_error"}}:{kind:"fail_request"};if(status===402||!providerFault&&BILLING_TEXT.test(text))return{kind:"failover",block:{reason:"account_disabled"}};if(status===429||limitText){if(codedLimit===void 0&&MODEL_SCOPED_REFUSAL_TEXT.some(pattern=>pattern.test(text)))return{kind:"fail_request"};let nowMs=context.nowMs??Date.now(),codedResetMs=codedLimit?.kind==="spent"&&codedLimit.resetsAt!==void 0?codedLimit.resetsAt-nowMs:void 0,codedReset=codedResetMs!==void 0&&codedResetMs>0?codedResetMs:void 0,hint=codedLimit?.kind==="throttle"?parseRetryAfterMsMarker(text):codedReset??extract429RetryAfterMs({status:status??429,bodyText:text},nowMs)??(usageLimit?normalized.retryAfterMs??usageLimitResetMs(text,nowMs):void 0),modelFamily=rateLimitModelFamily(text),policy={baseMs:context.cooldownBaseMs,capMs:context.cooldownCapMs};return{kind:"failover",block:{reason:"rate_limit",...usageLimit&&hint!==void 0&&hint>0?usageLimitCooldown(hint,policy):rateLimitCooldown(failureCount,hint,policy),...modelFamily===void 0?{}:{modelFamily}}}}return isOverflowText(text)||status===400||status===404||FAIL_FAST_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_REQUEST_FAULT_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_TRANSPORT_FAULT_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===529||OVERLOAD_TEXT.test(text)||status!==void 0&&status>=500&&status<600?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===408||NETWORK_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"}}var CredentialFailoverError=class extends Error{constructor(action,original,options={}){let detail=original instanceof Error?original.message:String(original);super(detail,{cause:original}),this.name="CredentialFailoverError",this.action=action,this.original=original,this.retryAt=options.retryAt}};function isAvailable(slot,now){return!(slot.blockReason==="account_disabled"||slot.blockedUntil!==void 0&&slot.blockedUntil>now)}function coolingProbe(slots,attempted){if(attempted.size>0)return[];let soonest=slots.filter(slot=>slot.blockReason==="rate_limit"&&slot.blockedUntil!==void 0).reduce((best,slot)=>best===void 0||(slot.blockedUntil??0)<(best.blockedUntil??0)?slot:best,void 0);return soonest===void 0?[]:[soonest]}function attemptCandidates(slots,attempted,now){let available=slots.filter(slot=>!attempted.has(slot.name)&&isAvailable(slot,now));return available.length>0?available:coolingProbe(slots,attempted)}function noSlotsError(slots,now){let retryAt=soonestRetryAt(slots,now);return new CredentialFailoverError({kind:"fail_request"},new Error(noSlotsMessage(slots,now)),retryAt===void 0?{}:{retryAt})}function dueBack(epochMs){return`${localTime(epochMs)} (${new Date(epochMs).toISOString()})`}function localTime(epochMs){return new Date(epochMs).toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function noSlotsMessage(slots,now){let blocked=slots.map(slot=>{let reason=slot.blockReason??"blocked";return slot.blockedUntil!==void 0&&slot.blockedUntil>now?`${slot.name} (${reason} until ${dueBack(slot.blockedUntil)})`:reason==="account_disabled"?`${slot.name} (account_disabled until re-login)`:`${slot.name} (${reason})`}),firstBack=soonestRetryAt(slots,now),step=firstBack===void 0?"Sign in again or add a new API key for this provider, or choose another model.":`Wait until ${localTime(firstBack)}, or choose another model.`;return blocked.length===0?`No credential slots available. ${step}`:`No credential slots available: ${blocked.join(", ")}. ${step}`}function isRateLimitBlock(action){return action.kind==="failover"&&action.block.reason==="rate_limit"}var OUT_OF_POOL_REASONS=new Set(["auth_error","account_disabled"]);function limitedUntil(slots,now){let resets=[];for(let slot of slots)if(!OUT_OF_POOL_REASONS.has(slot.blockReason??"")){if(slot.blockReason!=="rate_limit"||slot.blockedUntil===void 0||slot.blockedUntil<=now)return;resets.push(slot.blockedUntil)}return resets.length===0?void 0:Math.min(...resets)}function soonestRetryAt(slots,now){let deadlines=slots.map(slot=>slot.blockedUntil).filter(value=>value!==void 0&&value>now);return deadlines.length===0?void 0:Math.min(...deadlines)}async function settle(stream){let iterator=stream[Symbol.asyncIterator]();try{await iterator.return?.(void 0)}catch{}}async function*runCredentialFailover(options){let now=options.now??Date.now,classify=options.classify??classifyCredentialFailure,attempted=new Set,retriesBySlot=new Map,lastError,lastOriginal,lastTerminalEvent,startAnnounced=!1,unsettled;try{for(;;){let slots=await options.listSlots(),candidates=attemptCandidates(slots,attempted,now());if(candidates.length===0){let limitedRetryAt=lastError===void 0||isRateLimitBlock(lastError.action)?limitedUntil(slots,now()):void 0;if(lastTerminalEvent!==void 0){yield limitedRetryAt===void 0||options.withPoolRetryAt===void 0?lastTerminalEvent:options.withPoolRetryAt(lastTerminalEvent,limitedRetryAt);return}let retryAt=soonestRetryAt(slots,now()),refusal=lastError===void 0||lastOriginal===void 0?noSlotsError(slots,now()):new CredentialFailoverError(lastError.action,lastOriginal,retryAt===void 0?{}:{retryAt});throw limitedRetryAt===void 0?refusal:attachProviderDiagnostic(refusal,credentialPoolBlockedDiagnostic(limitedRetryAt))}let slot=options.select(candidates);unsettled=slot;let committedOutput=!1,terminalEvent,attemptStream;try{attemptStream=await options.runAttempt(slot);for await(let event of attemptStream){let failure=options.errorFromEvent?.(event);if(failure!==void 0)throw terminalEvent=event,failure;if(options.isStreamStart?.(event)){if(startAnnounced)continue;startAnnounced=!0}committedOutput||=options.isCommittedOutput(event),yield event}unsettled=void 0,await options.onSuccess?.(slot);return}catch(error){attemptStream&&await settle(attemptStream);let failureCount=(slot.failureCount??0)+(retriesBySlot.get(slot.name)??0),action=classify(error,{failureCount});if(lastOriginal=error,lastTerminalEvent=terminalEvent,action.kind==="retry_same"&&!committedOutput){let used=(retriesBySlot.get(slot.name)??0)+1;if(retriesBySlot.set(slot.name,used),used<action.maxAttempts){unsettled=void 0,await options.releaseSlot?.(slot);continue}if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}if(action.kind!=="failover"){if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}unsettled=void 0,await options.persistBlock(slot,action.block),attempted.add(slot.name);let failure=new CredentialFailoverError(action,error);if(lastError=failure,await options.onRotate?.({slot,block:action.block,attempt:attempted.size,committedOutput}),committedOutput){if(terminalEvent!==void 0){yield terminalEvent;return}throw failure}}}}finally{unsettled!==void 0&&await options.releaseSlot?.(unsettled)}}function parseAccountStrategy(value,field){switch(value){case void 0:case"cache-affine":case"fill-first":case"round-robin":return value;default:throw new Error(`${field} must be "cache-affine", "fill-first", or "round-robin"`)}}function orderAccounts(accounts,ranked,accountOrder,strategy="cache-affine",offset=0){switch(strategy){case"cache-affine":return applyAccountOrder(accountOrder,ranked);case"fill-first":return applyAccountOrder(accountOrder,accounts);case"round-robin":{let ordered=applyAccountOrder(accountOrder,accounts);if(ordered.length===0)return ordered;let start=offset%ordered.length;return[...ordered.slice(start),...ordered.slice(0,start)]}default:{let unsupported=strategy;throw new Error(`Unknown account strategy: ${unsupported}`)}}}function preferHeadroom(ordered,provider,limits,now,preferredAccount){let preferred=ordered.find(account=>account.name===preferredAccount),normal=preferred===void 0?ordered:[preferred,...ordered.filter(account=>account!==preferred)],nearLimit=new Set(limits.filter(limit=>limit.provider===provider&&limit.windows.some(window=>window.usedPercent>=95&&(window.resetsAt===void 0||!(Date.parse(window.resetsAt)<=now)))).map(limit=>limit.account)),withHeadroom=normal.filter(account=>!nearLimit.has(account.name));return withHeadroom.length>0?withHeadroom:normal}export{rendezvousOrder,applyAccountOrder,withoutOrderedAccount,isSlotBlocked,MAX_SLOT_BLOCK_MS,ACCOUNT_POOL_REFUSAL_NOTE,classifyCredentialFailure,CredentialFailoverError,isAvailable,attemptCandidates,noSlotsError,runCredentialFailover,parseAccountStrategy,orderAccounts,preferHeadroom};
|
|
2
|
+
import{usageLimitResetMs}from"./chunk-WB4BUHOH.js";import{rateLimitModelFamily}from"./chunk-NJ43NBSP.js";import{normalizeProviderError}from"./chunk-AC72EWI5.js";import{extract429RetryAfterMs,parseRetryAfterMsMarker}from"./chunk-RQFD6LG2.js";import{getOverflowPatterns}from"./chunk-QX7WD3IM.js";import{ModelsError,OAuthTokenEndpointError,PROVIDER_NOT_CONFIGURED_PREFIX,USAGE_LIMIT_EXHAUSTION,isOAuthRefreshUnavailableError}from"./chunk-OH5TKHW7.js";import{credentialPoolBlockedDiagnostic,readProviderDiagnostic}from"./chunk-JGKH3D6W.js";import{attachProviderDiagnostic,siwcRecoveryFromDiagnostic}from"./chunk-3SASTB6Y.js";function rendezvousOrder(key,slots,hasher){return[...slots].map(slot=>({slot,score:hasher(`${key}\0${slot.name}`)})).sort((left,right)=>right.score>left.score?1:right.score<left.score?-1:0).map(({slot})=>slot)}function applyAccountOrder(order,ranked){if(order===void 0||order.length===0)return[...ranked];let byName=new Map(ranked.map(slot=>[slot.name,slot])),front=[];for(let name of order){let slot=byName.get(name);slot!==void 0&&!front.includes(slot)&&front.push(slot)}return[...front,...ranked.filter(slot=>!front.includes(slot))]}function withoutOrderedAccount(credential,name){if(credential.order===void 0||!credential.order.includes(name))return credential;let order=credential.order.filter(entry=>entry!==name),next={...credential};return order.length===0?delete next.order:next.order=order,next}function isSlotBlocked(slot,now){return slot.blockReason==="auth_error"||slot.blockedUntil!==void 0&&slot.blockedUntil>now}var DEFAULT_SLOT_BLOCK_MS=6e4,MAX_SLOT_BLOCK_MS=2880*60*1e3;function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ACCOUNT_USAGE_LIMIT_TEXT=new RegExp([...USAGE_LIMIT_EXHAUSTION.markers.map(escapeRegExp),String.raw`\b(?:hit|reached)\s+your\b[^.]*?\blimit\b`,String.raw`\busage\s+limit\s+reached\b`,String.raw`\b(?:Go|Free)UsageLimitError\b`,String.raw`\bblocking_limit\b`,String.raw`\brapid_refill_breaker\b`,String.raw`\bquota\s+exceeded\b`].join("|"),"i");function isAccountUsageLimitText(text){return ACCOUNT_USAGE_LIMIT_TEXT.test(text)}var COOLDOWN_BASE_MS=DEFAULT_SLOT_BLOCK_MS,COOLDOWN_CAP_MS=MAX_SLOT_BLOCK_MS,GUESSED_BACKOFF_CAP_MS=1800*1e3,RETRY_SAME_MAX_ATTEMPTS=2,ACCOUNT_POOL_REFUSAL_NOTE="No request was sent: the account pool refused it locally.";function rateLimitCooldown(failureCount,serverHintMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS,base=policy.baseMs??COOLDOWN_BASE_MS,backoff=Math.min(cap,GUESSED_BACKOFF_CAP_MS,base*2**Math.max(0,failureCount)),floored=serverHintMs===void 0?backoff:Math.max(backoff,serverHintMs);return{cooldownMs:Math.min(cap,floored),retryAfterWasCapped:floored>cap}}function usageLimitCooldown(resetMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS;return{cooldownMs:Math.min(cap,resetMs),retryAfterWasCapped:resetMs>cap}}var INVALID_KEY_TEXT=/invalid[ _-]?(?:api[ _-]?)?key|authentication[_ ]?error|invalid x-api-key|unauthorized/i,REVOKED_TOKEN_TEXT=/invalidated (?:oauth )?token|(?<!\b(?:session|csrf|xsrf|page|pagination|continuation|cursor|sync|stream|upload|idempotency|request|nonce|state)[ _-])token(?:[ _-](?:invalidated|revoked)|\s(?:has been|was) (?:invalidated|revoked))/i,REFUSED_GRANT_CODES=new Set(["invalid_grant","refresh_token_expired","refresh_token_invalidated","refresh_token_reused","token_revoked"]),REFUSED_GRANT_TOKEN=/(?<![a-z_])(invalid_grant|refresh_token_(?:expired|invalidated|reused)|token_revoked)(?![a-z_])/,CLIENT_FAULT_CODES=new Set(["invalid_client","invalid_request","invalid_scope","unauthorized_client","unsupported_grant_type"]),NETWORK_FAULT_CODES=new Set(["ECONNRESET","ECONNREFUSED","ECONNABORTED","ETIMEDOUT","EHOSTUNREACH","EHOSTDOWN","ENETUNREACH","ENETDOWN","ENETRESET","ENOTFOUND","EAI_AGAIN","EPIPE","EADDRNOTAVAIL","ERR_SOCKET_CONNECTION_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET","UND_ERR_CLOSED","ConnectionRefused","ConnectionClosed","FailedToOpenSocket"]),AUTH_ERROR_CODES=new Set(["authentication_error","invalid_api_key","token_invalidated",...REFUSED_GRANT_CODES]),MAX_CAUSE_LINKS=16,ACCOUNT_SCOPED_403_TEXT=/account|credential|token|api[ _-]?key|organization|subscription/i,MODEL_SCOPED_REFUSAL_TEXT=[/(?:does not include(?: access to)?|not entitled to(?: use)?|no access to)[^.]{0,60}?\bmodel\b/i,/\bmodel\b.{0,80}?\b(?:is not|not|no)\b.{0,40}?\b(?:available|included|entitled|enabled|accessible)\b.{0,40}?\b(?:plan|subscription)\b/i,/(?:plan|subscription)[^.]{0,30}?\bdoes not\b[^.]{0,20}?\binclude access to\b/i],RATE_LIMIT_TEXT=/rate[ _-]?limit|too many requests|resource_exhausted/i,BILLING_TEXT=/billing|credits?[ _-]?(?:required|exhausted|balance)|insufficient[ _-]?(?:funds|quota|credit)|payment[ _-]?required|quota[ _-]?exhausted/i,OVERLOAD_TEXT=/overloaded/i,NETWORK_TEXT=/econnreset|econnrefused|etimedout|enotfound|socket hang up|fetch failed|network error|request timed out/i,WEBSOCKET_REQUEST_FAULT_TEXT=/websocket closed 100[89]\b/i,WEBSOCKET_TRANSPORT_FAULT_TEXT=/websocket (?:closed|error|connect timeout|liveness timeout)/i,FAIL_FAST_TEXT=/context[ _-]?(?:length|window)|maximum context|invalid[ _-]?model|model[ _-]?not[ _-]?found|malformed[ _-]?stream|premature[ _-]?(?:close|stream)/i,ABORT_TEXT=/\baborted?\b/i,TEMPORARY_FAULT_TEXT=/time[ds]?[ _-]?out|timed out|disconnect|reset before|connection reset|gateway|temporarily|unavailable/i;function limitFromProviderCode(error){let diagnostic=readProviderDiagnostic(error);if(diagnostic?.evidence==="structured_code")switch(diagnostic.code){case"rate_limit_exceeded":return{kind:"throttle"};case"usage_limit_reached":case"usage_not_included":return diagnostic.resetsAt===void 0?{kind:"spent"}:{kind:"spent",resetsAt:diagnostic.resetsAt};default:return}}function isAbort(error,message){return error instanceof Error&&error.name==="AbortError"?!0:ABORT_TEXT.test(message)}function failedRefresh(error){let seen=new Set;for(;typeof error=="object"&&error!==null&&!seen.has(error)&&seen.size<MAX_CAUSE_LINKS;){if(seen.add(error),error instanceof ModelsError)return error.code==="oauth"?error:void 0;error=Reflect.get(error,"cause")}}function oauthBodyErrorCode(message){let start=message.indexOf("{"),end=message.lastIndexOf("}");if(!(start<0||end<=start))try{let body=JSON.parse(message.slice(start,end+1));if(typeof body!="object"||body===null)return;let field=Reflect.get(body,"error");if(typeof field=="string")return field;if(typeof field=="object"&&field!==null){let code=Reflect.get(field,"code");return typeof code=="string"?code:void 0}return}catch{return}}function isRefusedGrant(refresh){let cause=refresh.cause;if(!(cause instanceof OAuthTokenEndpointError))return!1;let code=cause.oauthError??oauthBodyErrorCode(cause.message);return code!==void 0&&CLIENT_FAULT_CODES.has(code)?!1:cause.credentialRefused||cause.status===401?!0:code!==void 0&&REFUSED_GRANT_CODES.has(code)?[400,403,404].includes(cause.status):cause.status===400&&REFUSED_GRANT_TOKEN.test(cause.message)}function isRefreshNetworkFault(refresh,text){let seen=new Set,error=refresh.cause;for(;typeof error=="object"&&error!==null&&!seen.has(error)&&seen.size<MAX_CAUSE_LINKS;){if(seen.add(error),error instanceof OAuthTokenEndpointError)return!1;let code=Reflect.get(error,"code");if(typeof code=="string")return NETWORK_FAULT_CODES.has(code);error=Reflect.get(error,"cause")}return NETWORK_TEXT.test(text)}function hasAuthDiagnostic(error){let diagnostic=readProviderDiagnostic(error);return diagnostic===void 0?!1:diagnostic.category==="auth"||diagnostic.code!==void 0&&AUTH_ERROR_CODES.has(diagnostic.code)}function isOverflowText(text){return getOverflowPatterns().some(pattern=>pattern.test(text))}function classifyCredentialFailure(error,context={}){if(isOAuthRefreshUnavailableError(error))return{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS};let normalized=normalizeProviderError(error),text=normalized.messageCarriesBody?normalized.message:`${normalized.message} ${normalized.body??""}`,status=normalized.status,failureCount=context.failureCount??0;if(error instanceof Error&&error.name==="AbortError")return{kind:"fail_request"};switch(siwcRecoveryFromDiagnostic(readProviderDiagnostic(error))){case"usage_limit":return{kind:"failover",block:{reason:"rate_limit",usageLimit:!0,...rateLimitCooldown(failureCount,void 0,{baseMs:context.cooldownBaseMs,capMs:Math.min(context.cooldownCapMs??COOLDOWN_CAP_MS,30*6e4)})}};case"account_disabled":return{kind:"failover",block:{reason:"account_disabled"}};case"auth":return{kind:"failover",block:{reason:"auth_error"}};case"request":return{kind:"fail_request"};case"transient":return{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS};case void 0:break}if(isAbort(error,text))return{kind:"fail_request"};if(text.includes(ACCOUNT_POOL_REFUSAL_NOTE))return{kind:"fail_request"};let providerFault=status===408||status!==void 0&&status>=500&&status<600||status===void 0&&(TEMPORARY_FAULT_TEXT.test(text)||NETWORK_TEXT.test(text)||OVERLOAD_TEXT.test(text)),codedLimit=limitFromProviderCode(error),usageLimit=codedLimit!==void 0?codedLimit.kind==="spent":isAccountUsageLimitText(text)&&!isOverflowText(text),limitText=codedLimit!==void 0||RATE_LIMIT_TEXT.test(text)||usageLimit;if(text.includes(PROVIDER_NOT_CONFIGURED_PREFIX))return{kind:"failover",block:{reason:"auth_error"}};let statusFault=status===408||status===429||status!==void 0&&status>=500&&status<600,refresh=failedRefresh(error);if(refresh!==void 0)return!statusFault&&isRefusedGrant(refresh)?{kind:"failover",block:{reason:"auth_error"}}:isRefreshNetworkFault(refresh,text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"};if(!providerFault&&status!==429&&hasAuthDiagnostic(error))return{kind:"failover",block:{reason:"auth_error"}};if(status===401||!providerFault&&status!==429&&(INVALID_KEY_TEXT.test(text)||REVOKED_TOKEN_TEXT.test(text)))return{kind:"failover",block:{reason:"auth_error"}};if(status===403&&!limitText)return MODEL_SCOPED_REFUSAL_TEXT.some(pattern=>pattern.test(text))?{kind:"fail_request"}:ACCOUNT_SCOPED_403_TEXT.test(text)?{kind:"failover",block:{reason:"auth_error"}}:{kind:"fail_request"};if(status===402||!providerFault&&BILLING_TEXT.test(text))return{kind:"failover",block:{reason:"account_disabled"}};if(status===429||limitText){if(codedLimit===void 0&&MODEL_SCOPED_REFUSAL_TEXT.some(pattern=>pattern.test(text)))return{kind:"fail_request"};let nowMs=context.nowMs??Date.now(),codedResetMs=codedLimit?.kind==="spent"&&codedLimit.resetsAt!==void 0?codedLimit.resetsAt-nowMs:void 0,codedReset=codedResetMs!==void 0&&codedResetMs>0?codedResetMs:void 0,hint=codedLimit?.kind==="throttle"?parseRetryAfterMsMarker(text):codedReset??extract429RetryAfterMs({status:status??429,bodyText:text},nowMs)??(usageLimit?normalized.retryAfterMs??usageLimitResetMs(text,nowMs):void 0),modelFamily=rateLimitModelFamily(text),policy={baseMs:context.cooldownBaseMs,capMs:context.cooldownCapMs};return{kind:"failover",block:{reason:"rate_limit",...usageLimit&&hint!==void 0&&hint>0?usageLimitCooldown(hint,policy):rateLimitCooldown(failureCount,hint,policy),...modelFamily===void 0?{}:{modelFamily}}}}return isOverflowText(text)||status===400||status===404||FAIL_FAST_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_REQUEST_FAULT_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_TRANSPORT_FAULT_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===529||OVERLOAD_TEXT.test(text)||status!==void 0&&status>=500&&status<600?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===408||NETWORK_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"}}var CredentialFailoverError=class extends Error{constructor(action,original,options={}){let detail=original instanceof Error?original.message:String(original);super(detail,{cause:original}),this.name="CredentialFailoverError",this.action=action,this.original=original,this.retryAt=options.retryAt}};function isAvailable(slot,now){return!(slot.blockReason==="account_disabled"||slot.blockedUntil!==void 0&&slot.blockedUntil>now)}function coolingProbe(slots,attempted){if(attempted.size>0)return[];let soonest=slots.filter(slot=>slot.blockReason==="rate_limit"&&slot.blockedUntil!==void 0).reduce((best,slot)=>best===void 0||(slot.blockedUntil??0)<(best.blockedUntil??0)?slot:best,void 0);return soonest===void 0?[]:[soonest]}function attemptCandidates(slots,attempted,now){let available=slots.filter(slot=>!attempted.has(slot.name)&&isAvailable(slot,now));return available.length>0?available:coolingProbe(slots,attempted)}function noSlotsError(slots,now){let retryAt=soonestRetryAt(slots,now);return new CredentialFailoverError({kind:"fail_request"},new Error(noSlotsMessage(slots,now)),retryAt===void 0?{}:{retryAt})}function dueBack(epochMs){return`${localTime(epochMs)} (${new Date(epochMs).toISOString()})`}function localTime(epochMs){return new Date(epochMs).toLocaleString("en-US",{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function noSlotsMessage(slots,now){let blocked=slots.map(slot=>{let reason=slot.blockReason??"blocked";return slot.blockedUntil!==void 0&&slot.blockedUntil>now?`${slot.name} (${reason} until ${dueBack(slot.blockedUntil)})`:reason==="account_disabled"?`${slot.name} (account_disabled until re-login)`:`${slot.name} (${reason})`}),firstBack=soonestRetryAt(slots,now),step=firstBack===void 0?"Sign in again or add a new API key for this provider, or choose another model.":`Wait until ${localTime(firstBack)}, or choose another model.`;return blocked.length===0?`No credential slots available. ${step}`:`No credential slots available: ${blocked.join(", ")}. ${step}`}function isRateLimitBlock(action){return action.kind==="failover"&&action.block.reason==="rate_limit"}var OUT_OF_POOL_REASONS=new Set(["auth_error","account_disabled"]);function limitedUntil(slots,now){let resets=[];for(let slot of slots)if(!OUT_OF_POOL_REASONS.has(slot.blockReason??"")){if(slot.blockReason!=="rate_limit"||slot.blockedUntil===void 0||slot.blockedUntil<=now)return;resets.push(slot.blockedUntil)}return resets.length===0?void 0:Math.min(...resets)}function soonestRetryAt(slots,now){let deadlines=slots.map(slot=>slot.blockedUntil).filter(value=>value!==void 0&&value>now);return deadlines.length===0?void 0:Math.min(...deadlines)}async function settle(stream){let iterator=stream[Symbol.asyncIterator]();try{await iterator.return?.(void 0)}catch{}}async function*runCredentialFailover(options){let now=options.now??Date.now,classify=options.classify??classifyCredentialFailure,attempted=new Set,retriesBySlot=new Map,lastError,lastOriginal,lastTerminalEvent,startAnnounced=!1,unsettled;try{for(;;){let slots=await options.listSlots(),candidates=attemptCandidates(slots,attempted,now());if(candidates.length===0){let limitedRetryAt=lastError===void 0||isRateLimitBlock(lastError.action)?limitedUntil(slots,now()):void 0;if(lastTerminalEvent!==void 0){yield limitedRetryAt===void 0||options.withPoolRetryAt===void 0?lastTerminalEvent:options.withPoolRetryAt(lastTerminalEvent,limitedRetryAt);return}let retryAt=soonestRetryAt(slots,now()),refusal=lastError===void 0||lastOriginal===void 0?noSlotsError(slots,now()):new CredentialFailoverError(lastError.action,lastOriginal,retryAt===void 0?{}:{retryAt});throw limitedRetryAt===void 0?refusal:attachProviderDiagnostic(refusal,credentialPoolBlockedDiagnostic(limitedRetryAt))}let slot=options.select(candidates);unsettled=slot;let committedOutput=!1,terminalEvent,attemptStream;try{attemptStream=await options.runAttempt(slot);for await(let event of attemptStream){let failure=options.errorFromEvent?.(event);if(failure!==void 0)throw terminalEvent=event,failure;if(options.isStreamStart?.(event)){if(startAnnounced)continue;startAnnounced=!0}committedOutput||=options.isCommittedOutput(event),yield event}unsettled=void 0,await options.onSuccess?.(slot);return}catch(error){attemptStream&&await settle(attemptStream);let failureCount=(slot.failureCount??0)+(retriesBySlot.get(slot.name)??0),action=classify(error,{failureCount});if(lastOriginal=error,lastTerminalEvent=terminalEvent,action.kind==="retry_same"&&!committedOutput){let used=(retriesBySlot.get(slot.name)??0)+1;if(retriesBySlot.set(slot.name,used),used<action.maxAttempts){unsettled=void 0,await options.releaseSlot?.(slot);continue}if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}if(action.kind!=="failover"){if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}unsettled=void 0,await options.persistBlock(slot,action.block),attempted.add(slot.name);let failure=new CredentialFailoverError(action,error);if(lastError=failure,await options.onRotate?.({slot,block:action.block,attempt:attempted.size,committedOutput}),committedOutput){if(terminalEvent!==void 0){yield terminalEvent;return}throw failure}}}}finally{unsettled!==void 0&&await options.releaseSlot?.(unsettled)}}function parseAccountStrategy(value,field){switch(value){case void 0:case"cache-affine":case"fill-first":case"round-robin":return value;default:throw new Error(`${field} must be "cache-affine", "fill-first", or "round-robin"`)}}function orderAccounts(accounts,ranked,accountOrder,strategy="cache-affine",offset=0){switch(strategy){case"cache-affine":return applyAccountOrder(accountOrder,ranked);case"fill-first":return applyAccountOrder(accountOrder,accounts);case"round-robin":{let ordered=applyAccountOrder(accountOrder,accounts);if(ordered.length===0)return ordered;let start=offset%ordered.length;return[...ordered.slice(start),...ordered.slice(0,start)]}default:{let unsupported=strategy;throw new Error(`Unknown account strategy: ${unsupported}`)}}}function preferHeadroom(ordered,provider,limits,now,preferredAccount){let preferred=ordered.find(account=>account.name===preferredAccount),normal=preferred===void 0?ordered:[preferred,...ordered.filter(account=>account!==preferred)],nearLimit=new Set(limits.filter(limit=>limit.provider===provider&&limit.windows.some(window=>window.usedPercent>=95&&(window.resetsAt===void 0||!(Date.parse(window.resetsAt)<=now)))).map(limit=>limit.account)),withHeadroom=normal.filter(account=>!nearLimit.has(account.name));return withHeadroom.length>0?withHeadroom:normal}export{rendezvousOrder,applyAccountOrder,withoutOrderedAccount,isSlotBlocked,MAX_SLOT_BLOCK_MS,ACCOUNT_POOL_REFUSAL_NOTE,classifyCredentialFailure,CredentialFailoverError,isAvailable,attemptCandidates,noSlotsError,runCredentialFailover,parseAccountStrategy,orderAccounts,preferHeadroom};
|
|
@@ -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{isAbortGraceInRange}from"./chunk-TQHNFP77.js";import{connectAuthenticatedRpcSocket,socketNeedsHandshake}from"./chunk-
|
|
2
|
+
import{isAbortGraceInRange}from"./chunk-TQHNFP77.js";import{connectAuthenticatedRpcSocket,socketNeedsHandshake}from"./chunk-E5O4SP5I.js";import{readSocketSecret,resolveSocketTransportAddress,sendSocketHandshake,socketSecretPath}from"./chunk-HW6AAS3R.js";var StreamIdleTimeoutError=class extends Error{constructor(idleTimeoutMs){super(`Summarization stream stalled: no provider events for ${idleTimeoutMs}ms; treating the request as dead`),this.name="StreamIdleTimeoutError",this.idleTimeoutMs=idleTimeoutMs}},StreamDurationBudgetError=class extends Error{constructor(maxDurationMs){super(`Summarization stream exceeded its ${maxDurationMs}ms wall-clock budget; treating the request as too slow to keep the session waiting`),this.name="StreamDurationBudgetError",this.maxDurationMs=maxDurationMs}},DEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS=3e5,DEFAULT_SUMMARIZATION_MAX_DURATION_MS=12e4,SUMMARIZATION_MAX_DURATION_PER_TOKEN_MS=2,SUMMARIZATION_MAX_DURATION_CAP_MS=18e5,SUMMARIZATION_TOTAL_BUDGET_MS=9e5;function summarizationTotalBudgetMs(attemptOverrideMs){let override=attemptOverrideMs!==void 0&&Number.isFinite(attemptOverrideMs)&&attemptOverrideMs>0?Math.min(SUMMARIZATION_MAX_DURATION_CAP_MS,attemptOverrideMs):0;return Math.max(SUMMARIZATION_TOTAL_BUDGET_MS,override)}var SummarizationTotalBudgetError=class extends Error{constructor(totalBudgetMs){super(`Compaction exceeded its ${totalBudgetMs}ms total wall-clock budget across every summarization attempt and retry`),this.name="SummarizationTotalBudgetError",this.totalBudgetMs=totalBudgetMs}};function createSummarizationDeadline(totalBudgetMs,now=Date.now){let startedMs=now(),remainingMs=()=>Math.max(0,totalBudgetMs-(now()-startedMs));return{totalBudgetMs,remainingMs,attemptBudgetMs:requestedMs=>{let remaining=remainingMs();if(remaining<=0)throw new SummarizationTotalBudgetError(totalBudgetMs);return Math.min(requestedMs,remaining)}}}function summarizationMaxDurationMs(estimatedInputTokens,overrideMs){if(overrideMs!==void 0&&Number.isFinite(overrideMs)&&overrideMs>0)return Math.min(SUMMARIZATION_MAX_DURATION_CAP_MS,overrideMs);let scaled=estimatedInputTokens*SUMMARIZATION_MAX_DURATION_PER_TOKEN_MS;return Math.min(SUMMARIZATION_MAX_DURATION_CAP_MS,Math.max(DEFAULT_SUMMARIZATION_MAX_DURATION_MS,scaled))}var IDLE_TRIP="idle-trip",BUDGET_TRIP="budget-trip",CALLER_ABORTED="caller-aborted";async function consumeStreamWithIdleTimeout(stream,options){let{idleTimeoutMs,maxDurationMs,abort,onEvent,signal,settle}=options,iterator,removeAbortListener,callerAbortPromise,budgetPromise,budgetTimer,budgetMs=0;if(maxDurationMs!==void 0){budgetMs=maxDurationMs;let{promise,resolve}=Promise.withResolvers();budgetTimer=setTimeout(()=>resolve(BUDGET_TRIP),budgetMs),budgetTimer.unref?.(),budgetPromise=promise}if(signal!==void 0&&!signal.aborted){let{promise,resolve}=Promise.withResolvers(),onAbort=()=>resolve(CALLER_ABORTED);signal.addEventListener("abort",onAbort,{once:!0}),removeAbortListener=()=>signal.removeEventListener("abort",onAbort),callerAbortPromise=promise}let settleUnderWatchdogs=async()=>{if(!settle)return;let{promise:idlePromise,resolve:resolveIdle}=Promise.withResolvers(),timer=setTimeout(()=>resolveIdle(IDLE_TRIP),idleTimeoutMs);timer.unref?.();let contenders=[settle().then(value=>({settled:value})),idlePromise];budgetPromise&&contenders.push(budgetPromise);let outcome;try{outcome=await Promise.race(contenders)}finally{clearTimeout(timer)}if(outcome===IDLE_TRIP)throw abort(),new StreamIdleTimeoutError(idleTimeoutMs);if(outcome===BUDGET_TRIP)throw abort(),new StreamDurationBudgetError(budgetMs);return outcome.settled};try{if(signal?.aborted)return await settleUnderWatchdogs();let resolvedStream;if(Symbol.asyncIterator in stream)resolvedStream=stream;else{let streamContenders=[Promise.resolve(stream)];callerAbortPromise&&streamContenders.push(callerAbortPromise),budgetPromise&&streamContenders.push(budgetPromise);let resolution=await Promise.race(streamContenders);if(resolution===BUDGET_TRIP)throw abort(),new StreamDurationBudgetError(budgetMs);if(resolution===CALLER_ABORTED)return await settleUnderWatchdogs();resolvedStream=resolution}for(iterator=resolvedStream[Symbol.asyncIterator]();;){let{promise:idlePromise,resolve:resolveIdle}=Promise.withResolvers(),timer=setTimeout(()=>resolveIdle(IDLE_TRIP),idleTimeoutMs);timer.unref?.();let contenders=[iterator.next(),idlePromise];callerAbortPromise&&contenders.push(callerAbortPromise),budgetPromise&&contenders.push(budgetPromise);let result;try{result=await Promise.race(contenders)}finally{clearTimeout(timer)}if(result===IDLE_TRIP)throw abort(),iterator?.return?.(),new StreamIdleTimeoutError(idleTimeoutMs);if(result===BUDGET_TRIP)throw abort(),iterator?.return?.(),new StreamDurationBudgetError(budgetMs);if(result===CALLER_ABORTED)return iterator?.return?.(),await settleUnderWatchdogs();if(result.done)return await settleUnderWatchdogs();onEvent?.(result.value)}}finally{removeAbortListener?.(),budgetTimer!==void 0&&clearTimeout(budgetTimer)}}import{createConnection}from"node:net";async function connectRpcClientSocket(path,options){if(!socketNeedsHandshake(path))return(await connectAuthenticatedRpcSocket(path,void 0,options)).socket;let secret=await readSocketSecret(socketSecretPath(path)),socket=createConnection(resolveSocketTransportAddress(path,process.platform,secret));return await new Promise((resolve,reject)=>{let cleanup=()=>{socket.off("connect",onConnect),socket.off("error",onError)},onConnect=()=>{cleanup(),resolve()},onError=error=>{cleanup(),reject(error)};socket.once("connect",onConnect),socket.once("error",onError)}),sendSocketHandshake(socket,secret),socket}var REQUEST_DEADLINE_MS=3e4;function requestDeadlineMs(command){return command.type!=="abort"||command.awaitIdle!==!0?REQUEST_DEADLINE_MS:command.graceMs===void 0?1e4+REQUEST_DEADLINE_MS:isAbortGraceInRange(command.graceMs)?command.graceMs+REQUEST_DEADLINE_MS:REQUEST_DEADLINE_MS}var PROMPT_COMPACTION_DEADLINE_MS=SUMMARIZATION_TOTAL_BUDGET_MS+SUMMARIZATION_MAX_DURATION_CAP_MS+REQUEST_DEADLINE_MS,PROMPT_ACK_MAX_WAIT_MS=PROMPT_COMPACTION_DEADLINE_MS+REQUEST_DEADLINE_MS,OPEN_AFTER_QUEUED_DEADLINE_MS=10*6e4,PROMPT_AFTER_QUEUED_DEADLINE_MS=5*6e4;function promptStalledMessage(){return`prompt was received by the host but not accepted within ${PROMPT_AFTER_QUEUED_DEADLINE_MS/6e4} minutes`}function openStalledMessage(position){let queued=typeof position=="number"?` at queue position ${position}`:"",minutes=OPEN_AFTER_QUEUED_DEADLINE_MS/6e4;return`open_session was accepted by the host${queued} but not answered within ${minutes} minutes`}var RpcRequestTimeoutError=class extends Error{constructor(message){super(message),this.code="rpc_request_timeout",this.name="RpcRequestTimeoutError"}};function armRequestDeadline(ms,message,expire){let timer=setTimeout(()=>expire(new RpcRequestTimeoutError(message())),ms);return{extend(nextMs,nextMessage){clearTimeout(timer),timer=setTimeout(()=>expire(new RpcRequestTimeoutError(nextMessage())),nextMs)},clear(){clearTimeout(timer)}}}export{StreamIdleTimeoutError,StreamDurationBudgetError,DEFAULT_SUMMARIZATION_IDLE_TIMEOUT_MS,DEFAULT_SUMMARIZATION_MAX_DURATION_MS,SUMMARIZATION_MAX_DURATION_PER_TOKEN_MS,SUMMARIZATION_TOTAL_BUDGET_MS,summarizationTotalBudgetMs,SummarizationTotalBudgetError,createSummarizationDeadline,summarizationMaxDurationMs,consumeStreamWithIdleTimeout,connectRpcClientSocket,REQUEST_DEADLINE_MS,requestDeadlineMs,PROMPT_COMPACTION_DEADLINE_MS,PROMPT_ACK_MAX_WAIT_MS,OPEN_AFTER_QUEUED_DEADLINE_MS,PROMPT_AFTER_QUEUED_DEADLINE_MS,promptStalledMessage,openStalledMessage,RpcRequestTimeoutError,armRequestDeadline};
|
|
@@ -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{RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_UNKNOWN_COMMAND,clientMessageIdentity}from"./chunk-3IYEGHBI.js";import{OPEN_AFTER_QUEUED_DEADLINE_MS,PROMPT_ACK_MAX_WAIT_MS,PROMPT_AFTER_QUEUED_DEADLINE_MS,PROMPT_COMPACTION_DEADLINE_MS,REQUEST_DEADLINE_MS,RpcRequestTimeoutError,armRequestDeadline,connectRpcClientSocket,openStalledMessage,promptStalledMessage,requestDeadlineMs}from"./chunk-
|
|
2
|
+
import{RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_UNKNOWN_COMMAND,clientMessageIdentity}from"./chunk-3IYEGHBI.js";import{OPEN_AFTER_QUEUED_DEADLINE_MS,PROMPT_ACK_MAX_WAIT_MS,PROMPT_AFTER_QUEUED_DEADLINE_MS,PROMPT_COMPACTION_DEADLINE_MS,REQUEST_DEADLINE_MS,RpcRequestTimeoutError,armRequestDeadline,connectRpcClientSocket,openStalledMessage,promptStalledMessage,requestDeadlineMs}from"./chunk-M2VJVJMK.js";import{DETACH_CONNECTION_CAPABILITY}from"./chunk-Z2C5N2LM.js";import{ORIGIN_HOST_INSTANCE_FIELD,originHostInstance}from"./chunk-VUY4BZDI.js";import{attachJsonlLineReader,serializeJsonLine}from"./chunk-SF4MQDKZ.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{fuzzyFilter}from"./chunk-TMXRR3N7.js";import{RecoveryRepairController}from"./chunk-EYSV6A7S.js";var COMMAND_TOKEN=/^\/[A-Za-z][A-Za-z0-9:_-]*$/,MAX_SUGGESTIONS=3,UnknownCommandError=class extends Error{constructor(command,suggestions,reason){super(formatUnknownCommandMessage(command,suggestions,reason)),this.name="UnknownCommandError",this.command=command,this.suggestions=suggestions,this.reason=reason}};function formatUnknownCommandMessage(command,suggestions,reason){if(reason==="interactive_only")return`/${command} is an interactive command and cannot be sent as a prompt.`;let hint=suggestions.length===0?"":` Did you mean ${suggestions.map(name=>`/${name}`).join(", ")}?`;return`Unknown command /${command}.${hint}`}var UNKNOWN_COMMAND_CONFIRM_HINT='Resend with "unknownCommandAsText": true to send it as text.';function unknownCommandErrorFromWire(data){if(typeof data!="object"||data===null)return;let command=Reflect.get(data,"command"),suggestions=Reflect.get(data,"suggestions"),reason=Reflect.get(data,"reason");if(typeof command!="string"||!Array.isArray(suggestions)||reason!=="unknown"&&reason!=="interactive_only")return;let names=suggestions.filter(name=>typeof name=="string");return new UnknownCommandError(command,names,reason)}function commandShapedName(text){let token=text.trim().split(/\s/,1)[0]??"";return COMMAND_TOKEN.test(token)?token.slice(1):void 0}function findUnknownCommand(text,catalog){let command=commandShapedName(text);if(command===void 0||catalog.promptCommands.has(command))return;if(catalog.interactiveCommands.has(command))return new UnknownCommandError(command,[],"interactive_only");let known=[...new Set([...catalog.promptCommands,...catalog.interactiveCommands])],suggestions=fuzzyFilter(known,command,name=>name).slice(0,MAX_SUGGESTIONS);return new UnknownCommandError(command,suggestions,"unknown")}import{existsSync}from"node:fs";function getMissingSessionCwdIssue(sessionManager,fallbackCwd){let sessionFile=sessionManager.getSessionFile();if(!sessionFile)return;let sessionCwd=sessionManager.getCwd();if(!(!sessionCwd||existsSync(sessionCwd)))return{sessionFile,sessionCwd,fallbackCwd}}function formatMissingSessionCwdError(issue){let sessionFile=issue.sessionFile?`
|
|
3
3
|
Session file: ${issue.sessionFile}`:"";return`Stored session working directory does not exist: ${issue.sessionCwd}${sessionFile}
|
|
4
4
|
Current working directory: ${issue.fallbackCwd}`}function formatMissingSessionCwdPrompt(issue){return`cwd from session file does not exist
|
|
5
5
|
${issue.sessionCwd}
|