@code-yeongyu/senpi 2026.11.10-1 → 2026.11.10-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/bundle/chunks/{chunk-GPXZTSEX.js → chunk-2M54EAAY.js} +3 -3
  3. package/dist/bundle/chunks/{chunk-YPAQXRP3.js → chunk-47T6YMI2.js} +2 -2
  4. package/dist/bundle/chunks/{chunk-I5ASHSLZ.js → chunk-4JMGWVRH.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-HI5JSLG5.js → chunk-74IB3JPP.js} +2 -2
  6. package/dist/bundle/chunks/{chunk-NH7SYIGN.js → chunk-DLPV4B3R.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-Y7Z7XPUF.js → chunk-DZQA5LVN.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-2CNSCMYC.js → chunk-E5O4SP5I.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-3IYWH6RO.js → chunk-IKJCA5SH.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-H33A33M4.js → chunk-M2VJVJMK.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-L6NRDUWJ.js → chunk-OF3XVGG4.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-THYEZBUG.js → chunk-Q4G5DECT.js} +2 -2
  13. package/dist/bundle/chunks/{chunk-ARUV3US4.js → chunk-QATU6BBC.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-FAFIGBUD.js → chunk-TUEZNIBK.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-BELNOPAI.js → chunk-UOZDDYBN.js} +2 -2
  16. package/dist/bundle/chunks/{chunk-DBQBJTMF.js → chunk-VUY4BZDI.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-TGW4R7SI.js → chunk-XH24X5B2.js} +1 -1
  18. package/dist/bundle/chunks/chunk-XI6THO4F.js +2 -0
  19. package/dist/bundle/chunks/{chunk-X4XWAB3J.js → chunk-YCPURLPU.js} +38 -38
  20. package/dist/bundle/chunks/{chunk-LHEP3ACI.js → chunk-YNGEZBTP.js} +1 -1
  21. package/dist/bundle/chunks/{cli-main-VG3C2EXI.js → cli-main-Y6ALA5OI.js} +1 -1
  22. package/dist/bundle/chunks/{hand-entry-3LQKUTYS.js → hand-entry-IPDAIOGI.js} +1 -1
  23. package/dist/bundle/chunks/{host-command-CCASS7W4.js → host-command-2326GCUP.js} +1 -1
  24. package/dist/bundle/chunks/{host-lifecycle-WWC7HXQ6.js → host-lifecycle-TNHASSFJ.js} +1 -1
  25. package/dist/bundle/chunks/host-lifecycle.js +1 -1
  26. package/dist/bundle/chunks/{host-session-command-YJB2FLKU.js → host-session-command-BZYBDOIE.js} +1 -1
  27. package/dist/bundle/chunks/{host-socket-request-DMYXC56U.js → host-socket-request-QN4Q2P5E.js} +1 -1
  28. package/dist/bundle/chunks/{interactive-mode-CUN3WMUF.js → interactive-mode-LBQB7DDR.js} +1 -1
  29. package/dist/bundle/chunks/{main-P7XRC2OI.js → main-FFRFP34W.js} +1 -1
  30. package/dist/bundle/chunks/{multi-session-host-244X3P6L.js → multi-session-host-NDIHHJ2L.js} +11 -8
  31. package/dist/bundle/chunks/{package-manager-cli-UVWJOQA3.js → package-manager-cli-XCPAMOYI.js} +1 -1
  32. package/dist/bundle/chunks/{rpc-mode-G4I3HHPB.js → rpc-mode-TKNZM4PZ.js} +1 -1
  33. package/dist/bundle/chunks/{rpc-monitor-source-C6VQ3BC4.js → rpc-monitor-source-PGTDSGWP.js} +1 -1
  34. package/dist/bundle/chunks/{run-attached-tui-R3RB5P7G.js → run-attached-tui-JDUKXDI2.js} +1 -1
  35. package/dist/bundle/chunks/{schedule-command-5FG2OKSR.js → schedule-command-HF2DHABB.js} +1 -1
  36. package/dist/bundle/chunks/{session-control-endpoint-XWCFLJYC.js → session-control-endpoint-A6R6W2JQ.js} +1 -1
  37. package/dist/bundle/chunks/{session-picker-2FZSNFS7.js → session-picker-GWA4S2PO.js} +1 -1
  38. package/dist/bundle/chunks/session-worker.js +119 -116
  39. package/dist/bundle/cli.js +2 -2
  40. package/dist/bundle/host-supervisor.js +1 -1
  41. package/dist/bundle/index.js +1 -1
  42. package/dist/bundle/rpc-entry.js +1 -1
  43. package/dist/bundle/runtime-manifest.json +1 -1
  44. package/dist/core/agent-session-runtime.d.ts +2 -0
  45. package/dist/core/agent-session-runtime.js +5 -0
  46. package/dist/core/agent-session.d.ts +1 -1
  47. package/dist/core/agent-session.js +30 -10
  48. package/dist/core/extensions/builtin/config-reload/change-groups.js +6 -2
  49. package/dist/core/extensions/builtin/mcp/auth/catalog-identity.js +32 -8
  50. package/dist/core/extensions/builtin/mcp/auth/oauth-grant.d.ts +43 -0
  51. package/dist/core/extensions/builtin/mcp/auth/oauth-grant.js +196 -0
  52. package/dist/core/extensions/builtin/mcp/auth/oauth-provider.d.ts +4 -17
  53. package/dist/core/extensions/builtin/mcp/auth/oauth-provider.js +64 -75
  54. package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.d.ts +1 -1
  55. package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.js +25 -4
  56. package/dist/core/extensions/builtin/mcp/auth/oauth.js +10 -7
  57. package/dist/core/extensions/builtin/mcp/auth/token-store.d.ts +18 -0
  58. package/dist/core/extensions/builtin/mcp/auth/token-store.js +3 -0
  59. package/dist/core/extensions/builtin/mcp/catalog-cache.js +7 -6
  60. package/dist/core/extensions/builtin/mcp/catalog.js +3 -2
  61. package/dist/core/extensions/builtin/mcp/invocation.js +6 -0
  62. package/dist/core/extensions/builtin/mcp/service-register.js +16 -2
  63. package/dist/core/extensions/builtin/mcp/service-tools-changed.js +61 -54
  64. package/dist/core/extensions/builtin/mcp/startup-race.d.ts +2 -0
  65. package/dist/core/extensions/builtin/mcp/startup-race.js +25 -7
  66. package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-2.js +6 -6
  67. package/dist/core/open-timing.d.ts +2 -0
  68. package/dist/core/open-timing.js +7 -1
  69. package/dist/core/session-manager.d.ts +2 -0
  70. package/dist/core/session-manager.js +15 -1
  71. package/dist/modes/interactive/session-control-rpc-commands.d.ts +1 -1
  72. package/dist/modes/interactive/session-control-rpc-commands.js +5 -0
  73. package/dist/modes/rpc/compact-admission-validation.js +4 -1
  74. package/dist/modes/rpc/connection-handler.d.ts +2 -0
  75. package/dist/modes/rpc/connection-handler.js +10 -2
  76. package/dist/modes/rpc/custom-capability.d.ts +2 -0
  77. package/dist/modes/rpc/custom-capability.js +2 -0
  78. package/dist/modes/rpc/effect-commands.d.ts +21 -0
  79. package/dist/modes/rpc/host-capabilities.d.ts +1 -0
  80. package/dist/modes/rpc/host-capabilities.js +3 -1
  81. package/dist/modes/rpc/host-observe-request.d.ts +2 -0
  82. package/dist/modes/rpc/host-observe-request.js +6 -1
  83. package/dist/modes/rpc/host-park-ledger.d.ts +19 -0
  84. package/dist/modes/rpc/host-park-ledger.js +110 -0
  85. package/dist/modes/rpc/lifecycle-delivery.js +4 -1
  86. package/dist/modes/rpc/media-placeholders.js +1 -0
  87. package/dist/modes/rpc/method-classes-schema-host.d.ts +42 -1
  88. package/dist/modes/rpc/method-classes-schema-host.js +24 -21
  89. package/dist/modes/rpc/method-classes-schema.d.ts +42 -1
  90. package/dist/modes/rpc/method-classes-schema.js +5 -2
  91. package/dist/modes/rpc/method-classes.d.ts +2 -0
  92. package/dist/modes/rpc/method-classes.js +3 -0
  93. package/dist/modes/rpc/multi-session-host.js +1 -1
  94. package/dist/modes/rpc/rpc-host-command-types.d.ts +14 -1
  95. package/dist/modes/rpc/rpc-host-response-types.d.ts +21 -0
  96. package/dist/modes/rpc/session-attachment-gate.js +2 -0
  97. package/dist/modes/rpc/session-binding.d.ts +1 -0
  98. package/dist/modes/rpc/session-binding.js +6 -1
  99. package/dist/modes/rpc/session-connection-context.d.ts +2 -0
  100. package/dist/modes/rpc/session-connection-context.js +4 -0
  101. package/dist/modes/rpc/session-registry-attach.d.ts +2 -0
  102. package/dist/modes/rpc/session-registry-attach.js +15 -11
  103. package/dist/modes/rpc/session-registry-claims.js +2 -0
  104. package/dist/modes/rpc/session-registry-open.js +13 -7
  105. package/dist/modes/rpc/session-registry-opening.js +2 -1
  106. package/dist/modes/rpc/session-registry-types.d.ts +4 -0
  107. package/dist/modes/rpc/session-registry.d.ts +3 -0
  108. package/dist/modes/rpc/session-registry.js +27 -3
  109. package/dist/modes/rpc/session-router-close.js +1 -0
  110. package/dist/modes/rpc/session-router-context.d.ts +4 -2
  111. package/dist/modes/rpc/session-router-context.js +3 -0
  112. package/dist/modes/rpc/session-router-host-reads.js +1 -0
  113. package/dist/modes/rpc/session-router-occupancy.js +10 -1
  114. package/dist/modes/rpc/session-router-open-result.d.ts +12 -0
  115. package/dist/modes/rpc/session-router-open-result.js +63 -0
  116. package/dist/modes/rpc/session-router-open.d.ts +3 -0
  117. package/dist/modes/rpc/session-router-open.js +15 -63
  118. package/dist/modes/rpc/session-router-park.d.ts +15 -0
  119. package/dist/modes/rpc/session-router-park.js +176 -0
  120. package/dist/modes/rpc/session-router-routing.d.ts +1 -1
  121. package/dist/modes/rpc/session-router-routing.js +7 -0
  122. package/dist/modes/rpc/session-status-source.js +2 -2
  123. package/docs/engine-socket/fixtures/admission-routes/h-legacy.json +1 -1
  124. package/docs/engine-socket/fixtures/rpc-inbound-samples.json +22 -2
  125. package/docs/rpc.md +50 -0
  126. package/native/socket-secret/prebuilds/win32-arm64/senpi_socket_secret.win32-arm64.node +0 -0
  127. package/native/socket-secret/prebuilds/win32-x64/senpi_socket_secret.win32-x64.node +0 -0
  128. package/package.json +6 -6
  129. package/dist/bundle/chunks/chunk-436DNN4Z.js +0 -2
@@ -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&&registerSessionWriter(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&&current.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,4 +1,4 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
2
  import{HOST_INSTANCE_ID_ENV}from"./chunk-RUGTHELO.js";import{ProcessIdentityUnreadableError,processMatchesPidFile,readProcessStartTime}from"./chunk-O5RYI3IW.js";import{createHmac,timingSafeEqual}from"node:crypto";var RPC_AUTH_CAPABILITY="socket_auth",RPC_AUTH_HEX=/^[a-f0-9]{64}$/,RPC_LAUNCH_ID=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,RPC_LAUNCH_PROOF_RECORD="launch_proven";function launchProofRecordRefusal(id){return{...id===void 0?{}:{id},type:"response",command:RPC_LAUNCH_PROOF_RECORD,success:!1,error:"reserved_record",errorCode:"reserved_record"}}function rpcAuthProof(key,label,...parts){return createHmac("sha256",key).update([`senpi-rpc-${label}`,...parts].join(`
3
3
  `),"utf8").digest("hex")}function rpcProofMatches(expected,received){return typeof received=="string"&&RPC_AUTH_HEX.test(received)&&timingSafeEqual(Buffer.from(expected,"hex"),Buffer.from(received,"hex"))}var RpcEndpointAuthError=class extends Error{constructor(code,detail,options){super(`${code}: ${detail}`,options),this.code=code,this.name="RpcEndpointAuthError"}};function authRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}import{randomBytes,randomUUID}from"node:crypto";import{constants,unlinkSync}from"node:fs";import*as fs from"node:fs/promises";import{join}from"node:path";var MAX_KEY_RECORD_BYTES=4096;async function checkRpcKeyDirectory(path,privateKeys=!1){let checked=privateKeys?path:await fs.realpath(path),problem=keyDirectoryProblem(await fs.lstat(checked),checked,privateKeys);if(problem!==void 0)throw new RpcEndpointAuthError("unsafe_key_record",`${checked} ${problem}`)}function keyDirectoryProblem(info,path,privateKeys){if(!info.isDirectory())return"is not a directory";if(info.uid!==process.getuid?.())return"is not owned by this user";let mode=info.mode&4095;return privateKeys?mode===448?void 0:`must be mode 0700 (is 0${mode.toString(8)}); run: chmod 700 ${path}`:(mode&18)===0?void 0:`is writable by group or others; run: chmod go-w ${path}`}async function checkRpcKeyParents(root){await checkRpcKeyDirectory(root),await checkRpcKeyDirectory(join(root,"rpc"))}async function readRpcKeyRecord(root,launchId){if(!RPC_LAUNCH_ID.test(launchId))throw new RpcEndpointAuthError("unsafe_key_record",`invalid launch id under ${root}`);let path=join(root,"rpc","keys",launchId);try{await checkRpcKeyParents(root),await checkRpcKeyDirectory(join(root,"rpc","keys"),!0);let handle=await fs.open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{let info=await handle.stat();if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&4095)!==384||info.size>MAX_KEY_RECORD_BYTES)throw new RpcEndpointAuthError("unsafe_key_record",path);let record=authRecord(JSON.parse(await handle.readFile("utf8")));if(record?.version!==1||record.launch_id!==launchId||typeof record.key!="string"||!RPC_AUTH_HEX.test(record.key))throw new RpcEndpointAuthError("unsafe_key_record",path);return record}finally{await handle.close()}}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause instanceof RpcEndpointAuthError?cause:new RpcEndpointAuthError("unsafe_key_record",path,{cause})}}var RpcPublicEndpoint=class{constructor(agentDir,endpoint){this.key=randomBytes(32),this.launchId=randomUUID(),this.publication=Promise.withResolvers(),this.created=!1,this.exitCleanup=()=>{if(this.created)try{unlinkSync(this.recordPath)}catch(cause){cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"||process.stderr.write(`senpi rpc host: could not remove own endpoint key record
4
- `)}},this.agentDir=agentDir,this.endpoint=endpoint,this.recordPath=join(agentDir,"rpc","keys",this.launchId),this.ready=this.publication.promise,this.ready.catch(()=>{})}async publish(){try{await fs.mkdir(join(this.agentDir,"rpc"),{recursive:!0,mode:448}),await checkRpcKeyParents(this.agentDir);let keys=join(this.agentDir,"rpc","keys");await fs.mkdir(keys,{recursive:!0,mode:448});let directory=await fs.lstat(keys);if(!directory.isDirectory()||directory.uid!==process.getuid?.())throw new RpcEndpointAuthError("unsafe_key_record",keys);(directory.mode&4095)!==448&&await fs.chmod(keys,448),await checkRpcKeyDirectory(keys,!0);let handle=await fs.open(this.recordPath,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,384);this.created=!0,process.once("exit",this.exitCleanup);try{await handle.writeFile(JSON.stringify({version:1,launch_id:this.launchId,key:this.key.toString("hex"),pid:process.pid,process_start:await readProcessStartTime(process.pid)??null,endpoint:this.endpoint,created_at:new Date().toISOString()})),await handle.sync();let info=await handle.stat();if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&4095)!==384)throw new RpcEndpointAuthError("unsafe_key_record",this.recordPath)}finally{await handle.close()}this.publication.resolve()}catch(cause){let error=new RpcEndpointAuthError("key_publication_failed",cause instanceof RpcEndpointAuthError?cause.message:this.recordPath,{cause});throw this.publication.reject(error),error}}async dispose(){process.off("exit",this.exitCleanup),this.created&&(this.created=!1,await fs.unlink(this.recordPath).catch(cause=>{if(!(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"))throw cause}))}};async function gcRpcPublicKeys(agentDir,budget={}){let keys=join(agentDir,"rpc","keys");try{await checkRpcKeyParents(agentDir),await checkRpcKeyDirectory(keys,!0)}catch(cause){if(cause instanceof RpcEndpointAuthError||cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause}let names=await fs.readdir(keys).catch(cause=>{if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return[];throw cause}),examined=0;for(let name of names){if(Date.now()>=(budget.deadline??1/0)||examined>=(budget.maxRecords??1/0))break;if(RPC_LAUNCH_ID.test(name)){examined++;try{let record=await readRpcKeyRecord(agentDir,name);if(record===void 0||typeof record.pid!="number"||!Number.isSafeInteger(record.pid)||record.pid<=0||!(record.process_start===null||typeof record.process_start=="string")||await processMatchesPidFile({pid:record.pid,processStartTime:record.process_start}))continue;await fs.unlink(join(keys,name))}catch(cause){if(cause instanceof ProcessIdentityUnreadableError||cause instanceof RpcEndpointAuthError||cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")continue;throw cause}}}}var OBSERVE_REQUEST_FIELD="observe",ORIGIN_HOST_INSTANCE_FIELD="origin_host_instance",HOLD_HOST_FIELD="hold_host",OBSERVING_COMMANDS=new Set(["get_protocol_info","get_snapshot","list_sessions","subscribe_sessions","unsubscribe_sessions","get_effect_status","get_pending_inputs","get_subscription_limits","get_state","get_entries"]);function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record=request;return record.type==="warm"||record.type==="authenticate"||record.type===RPC_LAUNCH_PROOF_RECORD?!0:record[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record.type)}function observingHoldChange(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let record=request;if(record[OBSERVE_REQUEST_FIELD]!==!0||!OBSERVING_COMMANDS.has(record.type))return;let hold=record[HOLD_HOST_FIELD];return typeof hold=="boolean"?hold:void 0}function originHostInstance(env=process.env){let instance=env[HOST_INSTANCE_ID_ENV]?.trim();return instance||void 0}function requestOriginHostInstance(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let origin=Reflect.get(request,ORIGIN_HOST_INSTANCE_FIELD);return typeof origin=="string"&&origin.length>0?origin:void 0}export{RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RPC_LAUNCH_ID,RPC_LAUNCH_PROOF_RECORD,launchProofRecordRefusal,rpcAuthProof,rpcProofMatches,RpcEndpointAuthError,authRecord,OBSERVE_REQUEST_FIELD,ORIGIN_HOST_INSTANCE_FIELD,isObservingRequest,observingHoldChange,originHostInstance,requestOriginHostInstance,readRpcKeyRecord,RpcPublicEndpoint,gcRpcPublicKeys};
4
+ `)}},this.agentDir=agentDir,this.endpoint=endpoint,this.recordPath=join(agentDir,"rpc","keys",this.launchId),this.ready=this.publication.promise,this.ready.catch(()=>{})}async publish(){try{await fs.mkdir(join(this.agentDir,"rpc"),{recursive:!0,mode:448}),await checkRpcKeyParents(this.agentDir);let keys=join(this.agentDir,"rpc","keys");await fs.mkdir(keys,{recursive:!0,mode:448});let directory=await fs.lstat(keys);if(!directory.isDirectory()||directory.uid!==process.getuid?.())throw new RpcEndpointAuthError("unsafe_key_record",keys);(directory.mode&4095)!==448&&await fs.chmod(keys,448),await checkRpcKeyDirectory(keys,!0);let handle=await fs.open(this.recordPath,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,384);this.created=!0,process.once("exit",this.exitCleanup);try{await handle.writeFile(JSON.stringify({version:1,launch_id:this.launchId,key:this.key.toString("hex"),pid:process.pid,process_start:await readProcessStartTime(process.pid)??null,endpoint:this.endpoint,created_at:new Date().toISOString()})),await handle.sync();let info=await handle.stat();if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&4095)!==384)throw new RpcEndpointAuthError("unsafe_key_record",this.recordPath)}finally{await handle.close()}this.publication.resolve()}catch(cause){let error=new RpcEndpointAuthError("key_publication_failed",cause instanceof RpcEndpointAuthError?cause.message:this.recordPath,{cause});throw this.publication.reject(error),error}}async dispose(){process.off("exit",this.exitCleanup),this.created&&(this.created=!1,await fs.unlink(this.recordPath).catch(cause=>{if(!(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"))throw cause}))}};async function gcRpcPublicKeys(agentDir,budget={}){let keys=join(agentDir,"rpc","keys");try{await checkRpcKeyParents(agentDir),await checkRpcKeyDirectory(keys,!0)}catch(cause){if(cause instanceof RpcEndpointAuthError||cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause}let names=await fs.readdir(keys).catch(cause=>{if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return[];throw cause}),examined=0;for(let name of names){if(Date.now()>=(budget.deadline??1/0)||examined>=(budget.maxRecords??1/0))break;if(RPC_LAUNCH_ID.test(name)){examined++;try{let record=await readRpcKeyRecord(agentDir,name);if(record===void 0||typeof record.pid!="number"||!Number.isSafeInteger(record.pid)||record.pid<=0||!(record.process_start===null||typeof record.process_start=="string")||await processMatchesPidFile({pid:record.pid,processStartTime:record.process_start}))continue;await fs.unlink(join(keys,name))}catch(cause){if(cause instanceof ProcessIdentityUnreadableError||cause instanceof RpcEndpointAuthError||cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")continue;throw cause}}}}var OBSERVE_REQUEST_FIELD="observe",ORIGIN_HOST_INSTANCE_FIELD="origin_host_instance",HOLD_HOST_FIELD="hold_host",OBSERVING_COMMANDS=new Set(["get_protocol_info","get_snapshot","list_sessions","subscribe_sessions","unsubscribe_sessions","get_effect_status","get_pending_inputs","get_subscription_limits","get_state","get_entries"]);function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record=request;return record.type==="warm"||record.type==="park_session"||record.type==="authenticate"||record.type===RPC_LAUNCH_PROOF_RECORD?!0:record[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record.type)}function observingHoldChange(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let record=request;if(record[OBSERVE_REQUEST_FIELD]!==!0||!OBSERVING_COMMANDS.has(record.type))return;let hold=record[HOLD_HOST_FIELD];return typeof hold=="boolean"?hold:void 0}function originHostInstance(env=process.env){let instance=env[HOST_INSTANCE_ID_ENV]?.trim();return instance||void 0}function requestOriginHostInstance(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let origin=Reflect.get(request,ORIGIN_HOST_INSTANCE_FIELD);return typeof origin=="string"&&origin.length>0?origin:void 0}export{RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RPC_LAUNCH_ID,RPC_LAUNCH_PROOF_RECORD,launchProofRecordRefusal,rpcAuthProof,rpcProofMatches,RpcEndpointAuthError,authRecord,OBSERVE_REQUEST_FIELD,ORIGIN_HOST_INSTANCE_FIELD,isObservingRequest,observingHoldChange,originHostInstance,requestOriginHostInstance,readRpcKeyRecord,RpcPublicEndpoint,gcRpcPublicKeys};
@@ -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{appendDebugLogEntry}from"./chunk-MSDBBOB2.js";import{isRecoverableInspectorVmImportError}from"./chunk-3IYWH6RO.js";import{hasModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{isStaleExtensionContextError}from"./chunk-IHES3JES.js";function containStaleExtensionError(error,origin){if(!isStaleExtensionContextError(error))return!1;try{appendDebugLogEntry(`contained stale extension ctx (${origin})`,error.stack??error.message)}catch{}return!0}var installed=!1;function installStaleExtensionContainment(){installed||(installed=!0,process.on("uncaughtException",(error,origin)=>{containStaleExtensionError(error,origin??"uncaughtException")||hasModeCrashHandler("uncaughtException")||isRecoverableInspectorVmImportError(error,origin??"uncaughtException")||(console.error(error),process.exit(1))}))}export{containStaleExtensionError,installStaleExtensionContainment};
2
+ import{appendDebugLogEntry}from"./chunk-MSDBBOB2.js";import{isRecoverableInspectorVmImportError}from"./chunk-IKJCA5SH.js";import{hasModeCrashHandler}from"./chunk-ZFIC2DZV.js";import{isStaleExtensionContextError}from"./chunk-IHES3JES.js";function containStaleExtensionError(error,origin){if(!isStaleExtensionContextError(error))return!1;try{appendDebugLogEntry(`contained stale extension ctx (${origin})`,error.stack??error.message)}catch{}return!0}var installed=!1;function installStaleExtensionContainment(){installed||(installed=!0,process.on("uncaughtException",(error,origin)=>{containStaleExtensionError(error,origin??"uncaughtException")||hasModeCrashHandler("uncaughtException")||isRecoverableInspectorVmImportError(error,origin??"uncaughtException")||(console.error(error),process.exit(1))}))}export{containStaleExtensionError,installStaleExtensionContainment};
@@ -0,0 +1,2 @@
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{jsonNormalValue}from"./chunk-SF4MQDKZ.js";import{isBigIntObject,isBooleanObject,isNumberObject,isStringObject}from"node:util/types";function normalizeJsonValue(input){let ancestors=new Set,changed=!1,visit=(input2,key)=>{let value2=input2;if(typeof value2=="object"&&value2!==null||typeof value2=="function"||typeof value2=="bigint"){let toJSON=value2.toJSON;typeof toJSON=="function"&&(value2=toJSON.call(value2,key),changed=!0)}if(typeof value2=="object"&&value2!==null){if(isNumberObject(value2))value2=+value2,changed=!0;else if(isStringObject(value2))value2=String(value2),changed=!0;else if(isBooleanObject(value2))value2=Boolean.prototype.valueOf.call(value2),changed=!0;else if(isBigIntObject(value2))throw new TypeError("Do not know how to serialize a BigInt")}if(typeof value2=="bigint")throw new TypeError("Do not know how to serialize a BigInt");if(typeof value2=="number"){let normalized=Number.isFinite(value2)?Object.is(value2,-0)?0:value2:null;return Object.is(normalized,value2)||(changed=!0),normalized}if(typeof value2>"u"||typeof value2=="function"||typeof value2=="symbol"){changed=!0;return}if(typeof value2!="object"||value2===null)return value2;if(ancestors.has(value2))throw new TypeError("Converting circular structure to JSON");ancestors.add(value2);try{if("toJSON"in value2&&(changed=!0),Array.isArray(value2)){let array=[],length=value2.length;for(let index=0;index<length;index++){let descriptor=Object.getOwnPropertyDescriptor(value2,String(index));(!descriptor||descriptor.get)&&(changed=!0),array.push(visit(value2[index],String(index))??null)}return array}let result={},names=Object.keys(value2);(Object.getPrototypeOf(value2)!==Object.prototype||Reflect.ownKeys(value2).length!==names.length)&&(changed=!0);for(let name of names){Object.getOwnPropertyDescriptor(value2,name)?.get&&(changed=!0);let child=visit(value2[name],name);child!==void 0&&Object.defineProperty(result,name,{value:child,enumerable:!0,configurable:!0,writable:!0})}return result}finally{ancestors.delete(value2)}},value;try{value=visit(input,"")}catch(error){if(!(error instanceof RangeError))throw error;if(value=jsonNormalValue(input),value===void 0)throw new SyntaxError("JSON input has no representation");return{value,changed:!0}}if(value===void 0)throw new SyntaxError("JSON input has no representation");return{value,changed}}var MEDIA_BEARING_RECORD_TYPES=new Set(["tool_execution_end","message_start","message_end","turn_end","agent_end","entry_appended"]),MEDIA_BEARING_RESPONSE_COMMANDS=new Set(["get_messages","get_entries","get_tree","get_state","open_session","claim_session"]);function base64ByteLength(data){let padding=data.endsWith("==")?2:data.endsWith("=")?1:0;return Math.max(0,Math.floor(data.length*3/4)-padding)}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isInlineImage(value){return isPlainObject(value)&&value.type==="image"&&typeof value.data=="string"}function omitContentImages(content,toolCallId,persist){let replaced;for(let index=0;index<content.length;index++){let block=content[index];if(!isInlineImage(block))continue;replaced??=[...content];let ref={toolCallId,contentIndex:index};replaced[index]={type:"image_ref",mimeType:typeof block.mimeType=="string"?block.mimeType:"application/octet-stream",byteLength:base64ByteLength(block.data),ref,...persist?.(ref,block)}}return replaced??content}function omitToolResultImages(message,persist){let content=message.content,toolCallId=typeof message.toolCallId=="string"?message.toolCallId:"";if(!Array.isArray(content))return message;let omitted=omitContentImages(content,toolCallId,persist);return omitted===content?message:{...message,content:omitted}}function enter(value,key,persist){if(Array.isArray(value))return{key,value,index:0};if(!isPlainObject(value))return;let scrubbed=value.role==="toolResult"?omitToolResultImages(value,persist):value,entries=Object.entries(scrubbed).filter(([name,child])=>(name!=="content"||scrubbed===value)&&(isPlainObject(child)||Array.isArray(child)));return scrubbed===value?{key,value,scrubbed,entries,index:0}:{key,value,scrubbed,entries,index:0,replaced:{...scrubbed}}}function walk(root,persist){let first=enter(root,0,persist);if(!first)return root;let stack=[first],ancestors=new Set([first.value]);for(;;){let top=stack[stack.length-1];if("entries"in top?top.index<top.entries.length:top.index<top.value.length){let[key,child]="entries"in top?top.entries[top.index]:[top.index,top.value[top.index]];top.index++;let frame=enter(child,key,persist);if(!frame)continue;if(ancestors.has(frame.value))throw new TypeError("Converting circular structure to JSON");ancestors.add(frame.value),stack.push(frame);continue}stack.pop(),ancestors.delete(top.value);let result=top.replaced??top.value,parent=stack[stack.length-1];if(!parent)return result;result!==top.value&&("entries"in parent?(parent.replaced??={...parent.scrubbed})[top.key]=result:(parent.replaced??=[...parent.value])[top.key]=result)}}function omitToolExecutionEndImages(record,persist){let result=record.result;if(!isPlainObject(result)||!Array.isArray(result.content))return record;let toolCallId=typeof record.toolCallId=="string"?record.toolCallId:"",omitted=omitContentImages(result.content,toolCallId,persist);return omitted===result.content?record:{...record,result:{...result,content:omitted}}}function carriesMedia(record){return typeof record.type!="string"?!1:MEDIA_BEARING_RECORD_TYPES.has(record.type)?!0:record.type==="response"&&typeof record.command=="string"?MEDIA_BEARING_RESPONSE_COMMANDS.has(record.command):!1}function omitNormalInlineMedia(record,persist){let typed=record;if(!carriesMedia(typed))return record;let scrubbed=typed.type==="tool_execution_end"?omitToolExecutionEndImages(typed,persist):typed,walked=walk(scrubbed,persist);return walked===typed?record:walked}export{normalizeJsonValue,base64ByteLength,carriesMedia,omitNormalInlineMedia};