@code-yeongyu/senpi 2026.10.10-10 → 2026.10.10-11

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 (133) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/bundle/chunks/{anthropic-messages-2B35OVB7.js → anthropic-messages-I4Z6VKS3.js} +1 -1
  3. package/dist/bundle/chunks/{app-server-command-CV6N7JDD.js → app-server-command-HYNHHQJH.js} +1 -1
  4. package/dist/bundle/chunks/chunk-2KZKVRVC.js +8 -0
  5. package/dist/bundle/chunks/chunk-4XSQBLXM.js +2 -0
  6. package/dist/bundle/chunks/{chunk-ZPJHS64R.js → chunk-5BRVRFJI.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-4WZF7G6N.js → chunk-B2RD7QJJ.js} +6 -6
  8. package/dist/bundle/chunks/chunk-DRVT7RIO.js +2 -0
  9. package/dist/bundle/chunks/chunk-FOGXAY3T.js +2 -0
  10. package/dist/bundle/chunks/{chunk-5AKP2VFB.js → chunk-GNZDD5BK.js} +2 -3
  11. package/dist/bundle/chunks/{chunk-ZCYTYHDN.js → chunk-IAYFQEXI.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-HKRW6HT5.js → chunk-KTRCQYDF.js} +2 -2
  13. package/dist/bundle/chunks/chunk-M4C6Z7UT.js +288 -0
  14. package/dist/bundle/chunks/chunk-ML3WDDTX.js +2505 -0
  15. package/dist/bundle/chunks/chunk-NV3IPLK6.js +9 -0
  16. package/dist/bundle/chunks/chunk-OZ2N2E6U.js +2 -0
  17. package/dist/bundle/chunks/{chunk-JRGNL6WM.js → chunk-QXREUA5F.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-QQZREV6B.js → chunk-SSH4CLHJ.js} +1 -1
  19. package/dist/bundle/chunks/chunk-TOZBUPZP.js +3 -0
  20. package/dist/bundle/chunks/chunk-WASCMT6Y.js +2 -0
  21. package/dist/bundle/chunks/chunk-YU4AYH4C.js +2 -0
  22. package/dist/bundle/chunks/chunk-ZHE7JDBG.js +6 -0
  23. package/dist/bundle/chunks/{chunk-NTH33AXY.js → chunk-ZJOYLQXK.js} +1 -1
  24. package/dist/bundle/chunks/cli-main-WTXDD6H5.js +3 -0
  25. package/dist/bundle/chunks/{help-fast-path-5P73752B.js → help-fast-path-IQAJFO2G.js} +1 -1
  26. package/dist/bundle/chunks/host-command-7YS2Y6AT.js +2 -0
  27. package/dist/bundle/chunks/{host-lifecycle-B24G65GD.js → host-lifecycle-UG7RS5EU.js} +1 -1
  28. package/dist/bundle/chunks/host-lifecycle.js +1 -1
  29. package/dist/bundle/chunks/interactive-mode-WLMPVMRU.js +2 -0
  30. package/dist/bundle/chunks/multi-session-host-4SUEFZMU.js +26 -0
  31. package/dist/bundle/chunks/{package-manager-cli-PXP63ZPT.js → package-manager-cli-XEUK2RUM.js} +1 -1
  32. package/dist/bundle/chunks/rotation-stream-JXT3JYW5.js +2 -0
  33. package/dist/bundle/chunks/rpc-mode-G3DAUZCR.js +2 -0
  34. package/dist/bundle/chunks/runtime-session-6DAEMII3.js +2 -0
  35. package/dist/bundle/chunks/{schedule-command-MGZLHARF.js → schedule-command-DGLRLVWY.js} +1 -1
  36. package/dist/bundle/chunks/session-control-endpoint-MCV37VI5.js +3 -0
  37. package/dist/bundle/chunks/session-picker-WEFWH5O4.js +2 -0
  38. package/dist/bundle/chunks/session-worker.js +387 -383
  39. package/dist/bundle/cli.js +1 -1
  40. package/dist/bundle/index.js +1 -1
  41. package/dist/bundle/rpc-entry.js +1 -1
  42. package/dist/bundle/runtime-manifest.json +1 -1
  43. package/dist/cli/session-opening.d.ts +5 -0
  44. package/dist/cli/session-opening.js +11 -0
  45. package/dist/core/agent-session.d.ts +5 -0
  46. package/dist/core/agent-session.js +46 -1
  47. package/dist/core/engine-paused.d.ts +6 -0
  48. package/dist/core/engine-paused.js +50 -0
  49. package/dist/core/extensions/builtin/goal/continuation.js +2 -0
  50. package/dist/core/extensions/builtin/goal/direct-input-lifecycle.js +3 -1
  51. package/dist/core/extensions/builtin/goal/elapsed-ticker.js +2 -0
  52. package/dist/core/extensions/builtin/goal/index.js +4 -8
  53. package/dist/core/extensions/builtin/goal/lifecycle-helpers.js +54 -13
  54. package/dist/core/extensions/builtin/goal/monitor-continuation.js +2 -1
  55. package/dist/core/extensions/builtin/goal/persistence.js +2 -0
  56. package/dist/core/extensions/builtin/goal/store.d.ts +5 -0
  57. package/dist/core/extensions/builtin/goal/store.js +44 -0
  58. package/dist/core/extensions/builtin/goal/types.d.ts +2 -0
  59. package/dist/core/extensions/builtin/mcp/service-connection.js +1 -0
  60. package/dist/core/extensions/builtin/mcp/service-types.d.ts +2 -0
  61. package/dist/core/extensions/builtin/mcp/service.js +257 -74
  62. package/dist/core/extensions/builtin/terminal/process-identity.d.ts +1 -3
  63. package/dist/core/extensions/builtin/terminal/process-identity.js +1 -7
  64. package/dist/core/extensions/builtin/terminal/process-start-probe.js +11 -7
  65. package/dist/core/extensions/builtin/ttsr/index.js +19 -0
  66. package/dist/core/foreign-session-holders.d.ts +7 -0
  67. package/dist/core/foreign-session-holders.js +63 -0
  68. package/dist/core/moved-session-cwd.d.ts +7 -0
  69. package/dist/core/moved-session-cwd.js +23 -0
  70. package/dist/core/moved-sessions.d.ts +6 -0
  71. package/dist/core/moved-sessions.js +83 -24
  72. package/dist/core/resume-target.js +3 -1
  73. package/dist/core/session-holders.d.ts +2 -1
  74. package/dist/core/session-holders.js +4 -4
  75. package/dist/core/session-manager.js +12 -10
  76. package/dist/core/webview/webview-readiness.d.ts +2 -0
  77. package/dist/core/webview/webview-readiness.js +9 -0
  78. package/dist/core/webview/webview-service.d.ts +4 -0
  79. package/dist/core/webview/webview-service.js +30 -5
  80. package/dist/main.js +14 -3
  81. package/dist/modes/app-server/daemon/process.d.ts +4 -0
  82. package/dist/modes/app-server/daemon/process.js +52 -4
  83. package/dist/modes/interactive/interactive-mode.js +7 -0
  84. package/dist/modes/rpc/connection-handler.js +3 -2
  85. package/dist/modes/rpc/custom-capability.d.ts +2 -0
  86. package/dist/modes/rpc/custom-capability.js +2 -0
  87. package/dist/modes/rpc/host-capabilities.js +3 -1
  88. package/dist/modes/rpc/host-daemon-registration.js +15 -6
  89. package/dist/modes/rpc/host-legacy.js +8 -1
  90. package/dist/modes/rpc/host-reservations.d.ts +2 -0
  91. package/dist/modes/rpc/host-reservations.js +56 -3
  92. package/dist/modes/rpc/host-supervisor-log.d.ts +1 -0
  93. package/dist/modes/rpc/host-supervisor-log.js +9 -0
  94. package/dist/modes/rpc/multi-session-host.js +8 -6
  95. package/dist/modes/rpc/rpc-mode.d.ts +3 -1
  96. package/dist/modes/rpc/rpc-mode.js +3 -1
  97. package/dist/modes/rpc/rpc-types.d.ts +3 -1
  98. package/dist/modes/rpc/rpc-types.js +2 -0
  99. package/dist/modes/rpc/session-command-router.d.ts +1 -1
  100. package/dist/modes/rpc/session-command-router.js +18 -14
  101. package/dist/modes/rpc/session-held.d.ts +8 -0
  102. package/dist/modes/rpc/session-held.js +127 -0
  103. package/dist/modes/rpc/session-registry-types.d.ts +1 -1
  104. package/dist/modes/rpc/session-registry.d.ts +2 -0
  105. package/dist/modes/rpc/session-registry.js +4 -0
  106. package/dist/modes/rpc/session-worker-client.d.ts +3 -3
  107. package/dist/modes/rpc/session-worker-client.js +24 -12
  108. package/dist/modes/rpc/worker-session-claims.d.ts +15 -0
  109. package/dist/modes/rpc/worker-session-claims.js +61 -0
  110. package/dist/modes/rpc/worker-session-registry.d.ts +4 -0
  111. package/dist/modes/rpc/worker-session-registry.js +51 -8
  112. package/dist/utils/shell.d.ts +6 -2
  113. package/dist/utils/shell.js +20 -6
  114. package/docs/rpc.md +21 -1
  115. package/docs/session-format.md +9 -0
  116. package/package.json +6 -6
  117. package/dist/bundle/chunks/chunk-6Y7VGPJB.js +0 -9
  118. package/dist/bundle/chunks/chunk-JEZWV7JW.js +0 -17
  119. package/dist/bundle/chunks/chunk-LR5EN45D.js +0 -7
  120. package/dist/bundle/chunks/chunk-MYVBK47X.js +0 -2
  121. package/dist/bundle/chunks/chunk-O6YOQUVX.js +0 -2773
  122. package/dist/bundle/chunks/chunk-TJPMB4VH.js +0 -2
  123. package/dist/bundle/chunks/chunk-U5KVIAHJ.js +0 -2
  124. package/dist/bundle/chunks/chunk-XMHO4QQN.js +0 -7
  125. package/dist/bundle/chunks/cli-main-TM4UFZVC.js +0 -3
  126. package/dist/bundle/chunks/host-command-MWQNTWFA.js +0 -2
  127. package/dist/bundle/chunks/interactive-mode-CBQW7WRK.js +0 -2
  128. package/dist/bundle/chunks/multi-session-host-4KXWGRNS.js +0 -25
  129. package/dist/bundle/chunks/rotation-stream-FQH63DMY.js +0 -2
  130. package/dist/bundle/chunks/rpc-mode-7WHJHMUP.js +0 -2
  131. package/dist/bundle/chunks/runtime-session-CWJNFRHY.js +0 -2
  132. package/dist/bundle/chunks/session-control-endpoint-OH7XV2FN.js +0 -3
  133. package/dist/bundle/chunks/session-picker-UUSW6YSU.js +0 -2
@@ -0,0 +1,288 @@
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{require_ignore}from"./chunk-YU4AYH4C.js";import{composeFoldResult}from"./chunk-BMX2U22F.js";import{AssistantMessageFrameEncoder,dropFailedAssistantTurns,getToolCallFormat,hasKimiTextToolCallRecovery,hasVisibleAssistantContent,hasVisibleText,isClassifierRefusal,isContextOverflow,isCursorExecResolved,isRecoverableLength,reduceAssistantMessageFrames,require_dist,shouldRecoverTextToolCalls,supportsAllowedToolChoice,validateToolArguments}from"./chunk-5BRVRFJI.js";import{uuidv7}from"./chunk-2VZJTDUX.js";import{getAgentDir,getBinDir}from"./chunk-463OK2Y4.js";import{typebox_exports}from"./chunk-RBCQOIAD.js";import{resolveToolNameMatch}from"./chunk-WASCMT6Y.js";import{readProviderDiagnostic,sanitizeProviderDiagnostic}from"./chunk-YOPVJDSU.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS,EMPTY_RESPONSE_ERROR,EMPTY_TOOL_USE_ERROR,FORWARDED_EMPTY_RESPONSE_ERROR,FORWARDED_EMPTY_TOOL_USE_ERROR,OAUTH_REFRESH_UNAVAILABLE_DIAGNOSTIC,contentText,createInitialSystemMessage,getCurrentTools,getToolStateChanges,isOAuthRefreshUnavailableError,isRetryableAssistantError,normalizeContext,retryAssistantCall,retryDelayMs}from"./chunk-L4HVJWIF.js";import{EventStream,createAssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{__export,__toESM}from"./chunk-IKOFCODM.js";import{createHash}from"node:crypto";import{chmodSync,mkdirSync,readFileSync,renameSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{delimiter,join}from"node:path";var EMBEDDED_ENTRY=/^(?:\/\$bunfs\/|[A-Za-z]:[\\/]~BUN[\\/])/;function isCompiledBunExecutable(main){return main!==void 0&&EMBEDDED_ENTRY.test(main)}function currentHost(){return{main:globalThis.Bun?.main,execPath:process.execPath,platform:process.platform,shimRoots:[join(getAgentDir(),"bundled-bun"),join(tmpdir(),"senpi-bundled-bun")]}}function shimFiles(execPath,platform){if(platform==="win32"){let run=extra=>`@echo off\r
3
+ set BUN_BE_BUN=1\r
4
+ "${execPath}" ${extra}%*\r
5
+ exit /b %ERRORLEVEL%\r
6
+ `;return[["bun.cmd",run("")],["bunx.cmd",run("x ")]]}let quoted=`'${execPath.replaceAll("'","'\\''")}'`;return[["bun",`#!/bin/sh
7
+ BUN_BE_BUN=1 exec ${quoted} "$@"
8
+ `],["bunx",`#!/bin/sh
9
+ BUN_BE_BUN=1 exec ${quoted} x "$@"
10
+ `]]}function writeIfChanged(path,content){let current;try{current=readFileSync(path,"utf8")}catch{}if(current!==content){let staged=`${path}.${process.pid}.tmp`;writeFileSync(staged,content,{mode:493}),renameSync(staged,path)}chmodSync(path,493)}function materialize(root,host){let dir=join(root,createHash("sha256").update(host.execPath).digest("hex").slice(0,16));try{mkdirSync(dir,{recursive:!0});for(let[name,content]of shimFiles(host.execPath,host.platform))writeIfChanged(join(dir,name),content);return dir}catch{return}}var resolved=new Map;function bundledBunDir(host=currentHost()){if(!isCompiledBunExecutable(host.main))return;let key=`${host.execPath}\0${host.shimRoots.join("\0")}`;if(!resolved.has(key)){let dir;for(let root of host.shimRoots)if(dir=materialize(root,host),dir!==void 0)break;resolved.set(key,dir)}return resolved.get(key)}function withBundledBunCommands(env,host){let dir=bundledBunDir(host);if(dir===void 0)return env;let pathKey=Object.keys(env).find(key=>key.toLowerCase()==="path")??"PATH",entries=(env[pathKey]??"").split(delimiter).filter(Boolean);return entries.includes(dir)?env:{...env,[pathKey]:[...entries,dir].join(delimiter)}}import{existsSync}from"node:fs";import{delimiter as delimiter2,join as join2}from"node:path";function ok(value2){return{ok:!0,value:value2}}function err(error){return{ok:!1,error}}function getOrThrow(result){if(!result.ok)throw result.error;return result.value}function getOrUndefined(value2){return value2??void 0}function toError(error){if(error instanceof Error)return error;if(typeof error=="string")return new Error(error);try{return new Error(JSON.stringify(error))}catch{return new Error(String(error))}}var FileError=class extends Error{constructor(code,message,path,cause){super(message,cause===void 0?void 0:{cause}),this.name="FileError",this.code=code,this.path=path,cause!==void 0&&(this.cause=cause)}},ExecutionError=class extends Error{constructor(code,message,cause){super(message,cause===void 0?void 0:{cause}),this.name="ExecutionError",this.code=code,cause!==void 0&&(this.cause=cause)}},CompactionError=class extends Error{constructor(code,message,cause){super(message,cause===void 0?void 0:{cause}),this.name="CompactionError",this.code=code,cause!==void 0&&(this.cause=cause)}},BranchSummaryError=class extends Error{constructor(code,message,cause){super(message,cause===void 0?void 0:{cause}),this.name="BranchSummaryError",this.code=code}};var DEFAULT_MAX_LINES=2e3,DEFAULT_MAX_BYTES=51200,GREP_MAX_LINE_LENGTH=500,runtimeBuffer=globalThis.Buffer,nonAsciiPattern=/[^\x00-\x7f]/;function utf8ByteLength(content){if(runtimeBuffer)return runtimeBuffer.byteLength(content,"utf8");let firstNonAscii=content.search(nonAsciiPattern);if(firstNonAscii===-1)return content.length;let bytes=firstNonAscii;for(let i=firstNonAscii;i<content.length;i++){let code=content.charCodeAt(i);if(code<=127)bytes+=1;else if(code<=2047)bytes+=2;else if(code>=55296&&code<=56319&&i+1<content.length){let next=content.charCodeAt(i+1);next>=56320&&next<=57343?(bytes+=4,i++):bytes+=3}else bytes+=3}return bytes}function splitLinesForCounting(content){if(content.length===0)return[];let lines=content.split(`
11
+ `);return content.endsWith(`
12
+ `)&&lines.pop(),lines}function replaceUnpairedSurrogates(content){let output="";for(let i=0;i<content.length;i++){let code=content.charCodeAt(i);if(code>=55296&&code<=56319){if(i+1<content.length){let next=content.charCodeAt(i+1);if(next>=56320&&next<=57343){output+=content[i]+content[i+1],i++;continue}}output+="\uFFFD"}else code>=56320&&code<=57343?output+="\uFFFD":output+=content[i]}return output}function formatSize(bytes){return bytes<1024?`${bytes}B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)}KB`:`${(bytes/(1024*1024)).toFixed(1)}MB`}function truncateHead(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=utf8ByteLength(content),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};if(utf8ByteLength(lines[0])>maxBytes)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines,totalBytes,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines";for(let i=0;i<lines.length&&i<maxLines;i++){let line=lines[i],lineBytes=utf8ByteLength(line)+(i>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";break}outputLinesArr.push(line),outputBytesCount+=lineBytes}truncatedBy!=="bytes"&&(truncatedBy=outputLinesArr.length<totalLines?"lines":"bytes");let outputContent=outputLinesArr.join(`
13
+ `),finalOutputBytes=utf8ByteLength(outputContent);return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=utf8ByteLength(content),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines",lastLinePartial=!1;for(let i=lines.length-1;i>=0&&outputLinesArr.length<maxLines;i--){let line=lines[i],lineBytes=utf8ByteLength(line)+(outputLinesArr.length>0?1:0);if(outputBytesCount+lineBytes>maxBytes){if(truncatedBy="bytes",outputLinesArr.length===0){let truncatedLine=truncateStringToBytesFromEnd(line,maxBytes);outputLinesArr.unshift(truncatedLine),outputBytesCount=utf8ByteLength(truncatedLine),lastLinePartial=!0}break}outputLinesArr.unshift(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
14
+ `),finalOutputBytes=utf8ByteLength(outputContent);return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateStringToBytesFromEnd(str,maxBytes){if(maxBytes<=0)return"";let outputBytes=0,start=str.length,needsReplacement=!1;for(let i=str.length;i>0;){let characterStart=i-1,code=str.charCodeAt(characterStart),characterBytes,unpairedSurrogate=!1;if(code>=56320&&code<=57343&&characterStart>0){let previous=str.charCodeAt(characterStart-1);previous>=55296&&previous<=56319?(characterStart--,characterBytes=4):(characterBytes=3,unpairedSurrogate=!0)}else code>=55296&&code<=57343?(characterBytes=3,unpairedSurrogate=!0):characterBytes=code<=127?1:code<=2047?2:3;if(outputBytes+characterBytes>maxBytes)break;outputBytes+=characterBytes,start=characterStart,needsReplacement||=unpairedSurrogate,i=characterStart}let output=str.slice(start);return needsReplacement?replaceUnpairedSurrogates(output):output}function truncateLine(line,maxChars=500){return line.length<=maxChars?{text:line,wasTruncated:!1}:{text:`${line.slice(0,maxChars)}... [truncated]`,wasTruncated:!0}}var OUTPUT_TARGET_BYTES_PER_SECOND=100*1024,INVALID_SHELL_OUTPUT=/[\x00-\x08\x0b-\x1f\ufff9-\ufffb]/g,textEncoder=new TextEncoder,textDecoder=new TextDecoder;function applyShellOutputUpdate(current,update){switch(update.kind){case"replace":return update.output;case"append":return{text:`${current?.text??""}${update.text}`,...update.metadata};case"slide":return{text:`${current?.text.slice(update.drop)??""}${update.text}`,...update.metadata};case"metadata":return{text:current?.text??"",...update.metadata}}}function sanitizeShellOutput(text){return text.replace(INVALID_SHELL_OUTPUT,"")}import{spawnSync}from"node:child_process";var WINDOWS_PROCESS_TREE_ROWS=`Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne $PID } | ForEach-Object {
15
+ $created = if ($_.CreationDate) { $_.CreationDate.ToFileTimeUtc() } else { 0 }
16
+ "{0} {1} {2} {3}" -f $_.ProcessId, $_.ParentProcessId, $created, $_.Name }`;function parseWindowsProcessTreeRows(stdout){let rows=[];for(let line of stdout.split(/\r?\n/u)){let[pidText,parentText,createdText,...nameParts]=line.trim().split(/\s+/u),pid=Number(pidText),parentPid=Number(parentText);!Number.isInteger(pid)||pid<=0||!Number.isInteger(parentPid)||!/^\d+$/u.test(createdText??"")||rows.push({pid,parentPid,createdAt:BigInt(createdText??"0"),name:nameParts.join(" ")})}return rows}var PROTECTED_IMAGES=new Set(["system","smss.exe","csrss.exe","wininit.exe","winlogon.exe","services.exe","lsass.exe","lsaiso.exe","svchost.exe"]);function windowsTreeKillPlan(rows,rootPid,selfPid){let byPid=new Map(rows.map(row=>[row.pid,row]));if(byPid.get(rootPid)===void 0)return{kill:[],refused:[]};let tree=new Set([rootPid]),grew=!0;for(;grew;){grew=!1;for(let row of rows){if(tree.has(row.pid)||!tree.has(row.parentPid))continue;let parent=byPid.get(row.parentPid);parent===void 0||row.createdAt<parent.createdAt||(tree.add(row.pid),grew=!0)}}let ancestors=new Set([selfPid]);for(let current=byPid.get(selfPid);current!==void 0;){let parent=byPid.get(current.parentPid);if(parent===void 0||ancestors.has(parent.pid)||parent.createdAt>current.createdAt)break;ancestors.add(parent.pid),current=parent}let refused=[...tree].map(pid=>({pid,name:byPid.get(pid)?.name??""})).filter(entry=>PROTECTED_IMAGES.has(entry.name.toLowerCase())||ancestors.has(entry.pid));return refused.length===0?{kill:[...tree],refused}:{kill:refused.some(entry=>entry.pid===rootPid)?[]:[rootPid],refused}}function listWindowsProcessRowsSync(timeoutMs){let result=spawnSync("powershell.exe",["-NoProfile","-NonInteractive","-Command",WINDOWS_PROCESS_TREE_ROWS],{encoding:"utf8",windowsHide:!0,timeout:timeoutMs,maxBuffer:16777216});if(result.error!==void 0||result.status!==0||typeof result.stdout!="string")return;let rows=parseWindowsProcessTreeRows(result.stdout);return rows.length>0?rows:void 0}function windowsTreeKillArgs(rootPid,rows,selfPid=process.pid){if(rows===void 0)return["/F","/T","/PID",String(rootPid)];let pids=windowsTreeKillPlan(rows,rootPid,selfPid).kill;return pids.length===0?[]:["/F",...pids.flatMap(pid=>["/PID",String(pid)])]}var MAX_TIMEOUT_MS=2147483647,MAX_TIMEOUT_SECONDS=MAX_TIMEOUT_MS/1e3;var SPILL_HIGH_WATER_MARK=8*1024*1024;var dist_exports={};__export(dist_exports,{AGENT_TELEMETRY_SCHEMAS:()=>AGENT_TELEMETRY_SCHEMAS,AI_TELEMETRY_SCHEMA:()=>AI_TELEMETRY_SCHEMA,Agent:()=>Agent,AgentHarness:()=>AgentHarness,BACKGROUND_CONTEXT:()=>BACKGROUND_CONTEXT,BRANCH_SUMMARY_PREFIX:()=>BRANCH_SUMMARY_PREFIX,BRANCH_SUMMARY_SUFFIX:()=>BRANCH_SUMMARY_SUFFIX,BranchSummaryError:()=>BranchSummaryError,COMPACTION_SUMMARY_PREFIX:()=>COMPACTION_SUMMARY_PREFIX,COMPACTION_SUMMARY_SUFFIX:()=>COMPACTION_SUMMARY_SUFFIX,Closed:()=>Closed,CompactionError:()=>CompactionError,DEFAULT_COMPACTION_SETTINGS:()=>DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES:()=>DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES:()=>DEFAULT_MAX_LINES,EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC:()=>EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC,ExecutionError:()=>ExecutionError,FileError:()=>FileError,GREP_MAX_LINE_LENGTH:()=>GREP_MAX_LINE_LENGTH,HARNESS_TELEMETRY_SCHEMA:()=>HARNESS_TELEMETRY_SCHEMA,HarnessClosed:()=>HarnessClosed,HarnessFault:()=>HarnessFault,InMemoryTelemetryContext:()=>InMemoryTelemetryContext,InvalidLane:()=>InvalidLane,InvalidMessage:()=>InvalidMessage,InvalidNavigation:()=>InvalidNavigation,InvalidReadSegmentsError:()=>InvalidReadSegmentsError,JSONL_STORAGE_VERSION:()=>JSONL_STORAGE_VERSION,JsonlSessionRepo:()=>JsonlSessionRepo,LaneBusy:()=>LaneBusy,MemorySessionRepo:()=>MemorySessionRepo,NOOP_TELEMETRY_CONTEXT:()=>NOOP_TELEMETRY_CONTEXT,NoActiveOperation:()=>NoActiveOperation,NoActiveRun:()=>NoActiveRun,NothingToCompact:()=>NothingToCompact,NothingToResume:()=>NothingToResume,OperationMismatch:()=>OperationMismatch,ProviderRetryWatchdogAbortError:()=>ProviderRetryWatchdogAbortError,READ_FOLDER_SELECTION:()=>READ_FOLDER_SELECTION,READ_FOLD_SETTINGS:()=>READ_FOLD_SETTINGS,Result:()=>Result,SessionBranchExistsError:()=>SessionBranchExistsError,SessionInvalidBranchError:()=>SessionInvalidBranchError,SessionInvariantError:()=>SessionInvariantError,SessionPendingAssistantMessageError:()=>SessionPendingAssistantMessageError,SessionUnknownTargetError:()=>SessionUnknownTargetError,SliceNotImplemented:()=>SliceNotImplemented,StorageBackedSession:()=>StorageBackedSession,StreamStartTimeoutError:()=>StreamStartTimeoutError,TODO_CONTEXT:()=>TODO_CONTEXT,TaggedError:()=>TaggedError,UnknownSkill:()=>UnknownSkill,UnknownTarget:()=>UnknownTarget,UnknownTemplate:()=>UnknownTemplate,agentLoop:()=>agentLoop,agentLoopContinue:()=>agentLoopContinue,appendList:()=>appendList,applyShellOutputUpdate:()=>applyShellOutputUpdate,awaitWithContext:()=>awaitWithContext,bashExecutionToText:()=>bashExecutionToText,branchTip:()=>branchTip,branchTipInventoryPrefix:()=>branchTipInventoryPrefix,buildProviderContext:()=>buildProviderContext,calculateContextTokens:()=>calculateContextTokens,collectEntriesForBranchSummary:()=>collectEntriesForBranchSummary,commitWrite:()=>commitWrite,compact:()=>compact,convertToLlm:()=>convertToLlm,createBashTool:()=>createBashTool,createBranchSummaryMessage:()=>createBranchSummaryMessage,createCompactionSummaryMessage:()=>createCompactionSummaryMessage,createContextKey:()=>createContextKey,createCustomMessage:()=>createCustomMessage,createDefaultReadSummary:()=>createDefaultReadSummary,createEditTool:()=>createEditTool,createForkSnapshot:()=>createForkSnapshot,createReadTool:()=>createReadTool,createSegmentedReadView:()=>createSegmentedReadView,createTypedSpanStarter:()=>createTypedSpanStarter,createWriteTool:()=>createWriteTool,defineTelemetrySchema:()=>defineTelemetrySchema,deleteList:()=>deleteList,deleteValue:()=>deleteValue,entryLabel:()=>entryLabel,err:()=>err,estimateContextTokens:()=>estimateContextTokens,estimateTokens:()=>estimateTokens,executeShellWithCapture:()=>executeShellWithCapture,findCutPoint:()=>findCutPoint,findTurnStartIndex:()=>findTurnStartIndex,formatPromptTemplateInvocation:()=>formatPromptTemplateInvocation,formatSize:()=>formatSize,formatSkillInvocation:()=>formatSkillInvocation,formatSkillsForSystemPrompt:()=>formatSkillsForSystemPrompt,generateBranchSummary:()=>generateBranchSummary,generateSummary:()=>generateSummary,generateSummaryWithUsage:()=>generateSummaryWithUsage,getLastAssistantUsage:()=>getLastAssistantUsage,getOrThrow:()=>getOrThrow,getOrUndefined:()=>getOrUndefined,getTelemetryContext:()=>getTelemetryContext,insertEntry:()=>insertEntry,insertUsage:()=>insertUsage,isReadSummaryPath:()=>isReadSummaryPath,laneConfig:()=>laneConfig,laneState:()=>laneState,languageForPath:()=>languageForPath,list:()=>list,loadPromptTemplates:()=>loadPromptTemplates,loadSkills:()=>loadSkills,loadSourcedPromptTemplates:()=>loadSourcedPromptTemplates,loadSourcedSkills:()=>loadSourcedSkills,matchError:()=>matchError,ok:()=>ok,operationMeta:()=>operationMeta,operationPreparation:()=>operationPreparation,operationPreparationPrefix:()=>operationPreparationPrefix,operationResult:()=>operationResult,operationScopeOf:()=>operationScopeOf,operationState:()=>operationState,operationToolArgs:()=>operationToolArgs,operationToolArgsPrefix:()=>operationToolArgsPrefix,operationToolMemo:()=>operationToolMemo,operationToolMemoPrefix:()=>operationToolMemoPrefix,parseCommandArgs:()=>parseCommandArgs,pendingAssistantFrames:()=>pendingAssistantFrames,pendingEntry:()=>pendingEntry,pendingToolOutput:()=>pendingToolOutput,pendingToolOutputPrefix:()=>pendingToolOutputPrefix,prepareAgentToolCall:()=>prepareAgentToolCall,prepareAgentToolCallArguments:()=>prepareAgentToolCallArguments,prepareBranchEntries:()=>prepareBranchEntries,prepareCompaction:()=>prepareCompaction,prepareReadFolder:()=>prepareReadFolder,prepareStorageCommit:()=>prepareStorageCommit,prepareToolArguments:()=>prepareToolArguments,projectForkCurrentStateWrite:()=>projectForkCurrentStateWrite,readSummaryEngineForPath:()=>readSummaryEngineForPath,reduceLaneSnapshot:()=>reduceLaneSnapshot,renderSegmentedReadView:()=>renderSegmentedReadView,resolveListReadOptions:()=>resolveListReadOptions,resolveToolNameAlias:()=>resolveToolNameAlias,runAgentLoop:()=>runAgentLoop,runAgentLoopContinue:()=>runAgentLoopContinue,runToolCall:()=>runToolCall,sanitizeBinaryOutput:()=>sanitizeShellOutput,selectedReadFolder:()=>selectedReadFolder,serializeConversation:()=>serializeConversation,sessionName:()=>sessionName,setDefaultStreamFn:()=>setDefaultStreamFn,setValue:()=>setValue,shouldCompact:()=>shouldCompact,startAiSpan:()=>startAiSpan,startHarnessSpan:()=>startHarnessSpan,streamProxy:()=>streamProxy,substituteArgs:()=>substituteArgs,toError:()=>toError,truncateHead:()=>truncateHead,truncateLine:()=>truncateLine,truncateTail:()=>truncateTail,utf8ByteLength:()=>utf8ByteLength,uuidv7:()=>uuidv7,validateCommittedWrites:()=>validateCommittedWrites,value:()=>value,withAbortSignal:()=>withAbortSignal,withCancel:()=>withCancel,withContextValue:()=>withContextValue,withTelemetryContext:()=>withTelemetryContext,withoutAbortSignal:()=>withoutAbortSignal});function startNoopSpan(_options,callback){try{return Promise.resolve(callback(noopTelemetrySpan))}catch(error){return Promise.reject(error)}}var noopTelemetrySpan={startSpan:startNoopSpan,addEvent:()=>{},setAttributes:()=>{},setStatus:()=>{}};Object.freeze(noopTelemetrySpan);var NOOP_TELEMETRY_CONTEXT=noopTelemetrySpan;function copyAttributeValue(value2){return Array.isArray(value2)?[...value2]:value2}function copyAttributes(attributes){let copy={};if(!attributes)return copy;for(let[name,value2]of Object.entries(attributes))value2!==void 0&&(copy[name]=copyAttributeValue(value2));return copy}function mergeAttributes(current,attributes){let merged=copyAttributes(current);for(let[name,value2]of Object.entries(attributes))value2!==void 0&&(merged[name]=copyAttributeValue(value2));return merged}function copyStatus(status){return status.status==="ok"?{status:"ok"}:status.error?{status:"error",error:{name:status.error.name,message:status.error.message}}:{status:"error"}}function automaticErrorStatus(error){try{if(error instanceof Error)return{status:"error",error:{name:error.name,message:error.message}}}catch{}return{status:"error"}}function settleSpan(state,span,failed,error){span.settled||(failed&&!span.explicitStatus&&(span.status=automaticErrorStatus(error)),span.settled=!0,span.endSequence=state.nextEndSequence++)}function createSpan(state,parent,options){let name=options.name,attributes=copyAttributes(options.attributes);return{id:state.nextSpanId++,parentId:parent?.id??null,name,attributes,events:[],status:{status:"ok"},explicitStatus:!1,settled:!1}}function startInMemorySpan(state,parent,options,callback){if(parent?.settled)return NOOP_TELEMETRY_CONTEXT.startSpan(options,callback);let recordedSpan;try{recordedSpan=createSpan(state,parent,options),state.spans.push(recordedSpan)}catch{return NOOP_TELEMETRY_CONTEXT.startSpan(options,callback)}let span={startSpan:(childOptions,childCallback)=>startInMemorySpan(state,recordedSpan,childOptions,childCallback),addEvent(name,attributes){if(!recordedSpan.settled)try{recordedSpan.events.push({name,attributes:copyAttributes(attributes)})}catch{}},setAttributes(attributes){if(!recordedSpan.settled)try{recordedSpan.attributes=mergeAttributes(recordedSpan.attributes,attributes)}catch{}},setStatus(status){if(!recordedSpan.settled)try{recordedSpan.status=copyStatus(status),recordedSpan.explicitStatus=!0}catch{}}},result;try{result=callback(span)}catch(error){return settleSpan(state,recordedSpan,!0,error),Promise.reject(error)}return Promise.resolve(result).then(value2=>(settleSpan(state,recordedSpan,!1),value2),error=>{throw settleSpan(state,recordedSpan,!0,error),error})}var InMemoryTelemetryContext=class{constructor(){this.state={spans:[],nextSpanId:1,nextEndSequence:1}}startSpan(options,callback){return startInMemorySpan(this.state,void 0,options,callback)}getSpans(){return this.state.spans.map(span=>({id:span.id,parentId:span.parentId,name:span.name,attributes:copyAttributes(span.attributes),events:span.events.map(event=>({name:event.name,attributes:copyAttributes(event.attributes)})),status:copyStatus(span.status),settled:span.settled,...span.endSequence===void 0?{}:{endSequence:span.endSequence}}))}};function defineTelemetrySchema(schema){return schema}function bindTypedSpanStarter(telemetryContext){return(name,attributes,callback)=>telemetryContext.startSpan({name,attributes},span=>callback(span,bindTypedSpanStarter(span)))}function createTypedSpanStarter(telemetryContext,_schemas){return bindTypedSpanStarter(telemetryContext)}var EMPTY_USAGE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},ProviderRetryWatchdogAbortError=class extends Error{constructor(providerCause){super(providerCause),this.providerCause=providerCause,this.name="ProviderRetryWatchdogAbortError"}},EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC="empty_tool_use_terminal_state";function demoteToolUseWithoutToolCalls(message){return message.stopReason!=="toolUse"||message.content.some(block=>block.type==="toolCall")?message:{...message,stopReason:"stop",diagnostics:[...message.diagnostics??[],{type:EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC,timestamp:Date.now(),details:{}}]}}function promoteStopWithPendingToolCalls(message){return message.stopReason!=="stop"||!message.content.some(block=>block.type==="toolCall")?message:{...message,stopReason:"toolUse"}}function shouldTerminateAssistantTurn(message){return message.stopReason==="error"||message.stopReason==="aborted"||isClassifierRefusal(message)}function isStreamIdleTimeoutError(error){return error instanceof Error&&error.name==="StreamIdleTimeoutError"}function shouldFinalizeIdleAsStop(partialMessage,providerToolResults){if(!partialMessage)return!1;let toolCalls=partialMessage.content.filter(block=>block.type==="toolCall");return toolCalls.length===0?!1:providerToolResults.length>0?!0:toolCalls.every(block=>isCursorExecResolved(block))}function createTerminalFailureAssistantMessage(model,reason,error,partialMessage){let errorMessage2=error instanceof Error?error.message:String(error),providerDiagnostic=reason==="error"?readProviderDiagnostic(error):void 0;return{role:"assistant",content:partialMessage?.content??[{type:"text",text:""}],api:partialMessage?.api??model.api,provider:partialMessage?.provider??model.provider,model:partialMessage?.model??model.id,responseModel:partialMessage?.responseModel,responseId:partialMessage?.responseId,diagnostics:reason==="error"&&isOAuthRefreshUnavailableError(error)?[...partialMessage?.diagnostics??[],{type:OAUTH_REFRESH_UNAVAILABLE_DIAGNOSTIC,timestamp:Date.now(),details:{provider:model.provider}}]:partialMessage?.diagnostics,usage:partialMessage?.usage??EMPTY_USAGE,stopReason:reason,errorMessage:errorMessage2||(reason==="aborted"?"Request was aborted":"Error"),...providerDiagnostic===void 0?{}:{providerDiagnostic},...error instanceof ProviderRetryWatchdogAbortError?{abortSource:"provider"}:{},timestamp:partialMessage?.timestamp??Date.now()}}function normalizeTerminalAssistantMessage(message,event){if(event.type==="done")return message;let errorMessage2=message.errorMessage??(event.reason==="aborted"?"Request was aborted":"Error");return message.stopReason===event.reason&&message.errorMessage===errorMessage2?message:{...message,stopReason:event.reason,errorMessage:errorMessage2}}function isEmptyStop(message){return message.stopReason==="stop"&&!hasVisibleAssistantContent(message)}function isEmptyToolUse(message){return message.stopReason==="toolUse"&&!message.content.some(block=>block.type==="toolCall")}function isMeaningfulContentEvent(event,policy){switch(event.type){case"toolcall_start":return!0;case"text_delta":return hasVisibleText(event.delta);case"text_end":return hasVisibleText(event.content);case"thinking_delta":return policy.thinkingCommits&&hasVisibleText(event.delta);case"thinking_end":return policy.thinkingCommits&&hasVisibleText(event.content);default:return!1}}function appendRetryDiagnostic(message,type="empty_assistant_response_recovery",details={retries:1}){return{...message,diagnostics:[...message.diagnostics??[],{type,timestamp:Date.now(),details}]}}function recoveryDiagnosticType(toolUse){return toolUse?"empty_tool_use_response_recovery":"empty_assistant_response_recovery"}function createEmptyResponseFailure(message,toolUse=!1){let errorMessage2=toolUse?EMPTY_TOOL_USE_ERROR:EMPTY_RESPONSE_ERROR;return{...appendRetryDiagnostic(message,recoveryDiagnosticType(toolUse)),content:[{type:"text",text:errorMessage2}],stopReason:"error",errorMessage:errorMessage2}}function createForwardedEmptyFailure(message,toolUse){return{...appendRetryDiagnostic(message,recoveryDiagnosticType(toolUse),{retries:0,forwarded:!0}),stopReason:"error",errorMessage:toolUse?FORWARDED_EMPTY_TOOL_USE_ERROR:FORWARDED_EMPTY_RESPONSE_ERROR}}function createRetryingStream(firstStream,createStream,policy){let outerStream=createAssistantMessageEventStream();return(async()=>{try{let stream=firstStream,retrying=!1;for(;;){let buffered=[],forwarding=!1,retry=!1;for await(let event of stream){if(event.type==="done"){let emptyToolUse=isEmptyToolUse(event.message);if(isEmptyStop(event.message)||emptyToolUse){if(forwarding){outerStream.push({type:"error",reason:"error",error:createForwardedEmptyFailure(event.message,emptyToolUse)}),outerStream.end();return}if(!retrying){retry=!0;break}let error=createEmptyResponseFailure(event.message,emptyToolUse);outerStream.push({type:"error",reason:"error",error}),outerStream.end();return}let terminal=retrying?{...event,message:appendRetryDiagnostic(event.message,recoveryDiagnosticType(isEmptyToolUse(event.message)))}:event;if(!forwarding)for(let pending of buffered)outerStream.push(pending);outerStream.push(terminal),outerStream.end();return}if(event.type==="error"){if(!forwarding)for(let pending of buffered)outerStream.push(pending);outerStream.push(event),outerStream.end();return}if(forwarding){outerStream.push(event);continue}if(buffered.push(event),isMeaningfulContentEvent(event,policy)){for(let pending of buffered)outerStream.push(pending);forwarding=!0}}if(!retry){outerStream.end(retrying?appendRetryDiagnostic(await stream.result()):await stream.result());return}retrying=!0,stream=await createStream()}}catch(error){outerStream.fail(error)}})(),outerStream}function withEmptyAssistantRecovery(model,streamFunction){if(!shouldRecoverTextToolCalls(model)&&getToolCallFormat(model)===void 0)return streamFunction;let policy={thinkingCommits:!hasKimiTextToolCallRecovery(model)};return async(requestedModel,context,options)=>{let createStream=()=>streamFunction(requestedModel,context,options);return createRetryingStream(await createStream(),createStream,policy)}}var defaultStreamFn;function setDefaultStreamFn(streamFn){defaultStreamFn=streamFn}function getDefaultStreamFn(){if(!defaultStreamFn)throw new Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return defaultStreamFn}function prepareToolArguments(shim,args){return shim?shim(structuredClone(args)):args}function prepareAgentToolCallArguments(tool,toolCall){return tool.prepareArguments?{...toolCall,arguments:prepareToolArguments(tool.prepareArguments,toolCall.arguments)}:toolCall}function resolveToolNameAlias(requested,available){return resolveToolNameMatch(requested,available)}function toolNameCorrectionNotice(requested,resolved2){return`[auto-corrected] no tool is named "${requested}"; ran "${resolved2}". Call tools by their exact listed name.`}async function resolveCallTool(currentContext,toolCall,config){if(toolCall.incomplete===!0)return;let exact=currentContext.tools?.find(candidate=>candidate.name===toolCall.name);if(exact)return exact;let resolved2=await config.resolveUnknownToolCall?.(toolCall.name,currentContext);if(resolved2)return resolved2;let aliasedName=resolveToolNameAlias(toolCall.name,(currentContext.tools??[]).map(candidate=>candidate.name));return currentContext.tools?.find(candidate=>candidate.name===aliasedName)}function withToolNameCorrection(result,requestedName,resolvedName){return{...result,content:[{type:"text",text:toolNameCorrectionNotice(requestedName,resolvedName),audience:"model"},...result.content??[]]}}function agentLoop(prompts,context,config,signal,streamFn){let stream=createAgentStream();return runAgentLoop(prompts,context,config,async event=>{stream.push(event)},signal,streamFn).then(messages=>{stream.end(messages)}),stream}function agentLoopContinue(context,config,signal,streamFn){if(context.messages.length===0)throw new Error("Cannot continue: no messages in context");if(context.messages[context.messages.length-1].role==="assistant")throw new Error("Cannot continue from message role: assistant");let stream=createAgentStream();return runAgentLoopContinue(context,config,async event=>{stream.push(event)},signal,streamFn).then(messages=>{stream.end(messages)}),stream}async function runAgentLoop(prompts,context,config,emit,signal,streamFn){let initialMessages=declareToolChanges(context,prompts,config.model),newMessages=[...initialMessages],currentContext={...context,messages:[...context.messages,...initialMessages]};await emit({type:"agent_start"}),await emit({type:"turn_start"});for(let message of initialMessages)await emit({type:"message_start",message}),await emit({type:"message_end",message});return await runLoop(currentContext,newMessages,config,signal,emit,streamFn??getDefaultStreamFn()),newMessages}async function runAgentLoopContinue(context,config,emit,signal,streamFn){if(context.messages.length===0)throw new Error("Cannot continue: no messages in context");if(context.messages[context.messages.length-1].role==="assistant")throw new Error("Cannot continue from message role: assistant");let newMessages=[],currentContext={...context};return await emit({type:"agent_start"}),await emit({type:"turn_start"}),await runLoop(currentContext,newMessages,config,signal,emit,streamFn??getDefaultStreamFn()),newMessages}function createAgentStream(){return new EventStream(event=>event.type==="agent_end",event=>event.type==="agent_end"?event.messages:[])}var StreamIdleTimeoutError=class extends Error{constructor(timeoutMs){super(`Idle timeout waiting for provider stream after ${timeoutMs}ms`),this.name="StreamIdleTimeoutError"}},StreamStartTimeoutError=class extends Error{constructor(timeoutMs){super(`Provider stream start timed out after ${timeoutMs}ms (raise streamStartTimeoutMs \u2014 retry.provider.streamStartTimeoutMs in senpi settings; 0 disables)`),this.name="StreamStartTimeoutError"}};async function runLoop(initialContext,newMessages,initialConfig,signal,emit,streamFunction){let currentContext=initialContext,config=initialConfig,firstTurn=!0,firstProviderRequest=!0,drainedTerminatingQueue,turnStartAlreadyEmitted=!1,explicitContinuation=!1,preparedMessages=[],refreshTerminatingQueueDrain=async()=>{!drainedTerminatingQueue||!config.restorePendingMessages||(await config.restorePendingMessages(drainedTerminatingQueue,pendingMessages),pendingMessages=await config.getSteeringMessages?.()||[],drainedTerminatingQueue=pendingMessages.length>0?"steering":void 0,pendingMessages.length===0&&(pendingMessages=await config.getFollowUpMessages?.()||[],drainedTerminatingQueue=pendingMessages.length>0?"followUp":void 0))},pendingMessages=await config.getSteeringMessages?.()||[];for(;;){let hasMoreToolCalls=!0;for(;hasMoreToolCalls||pendingMessages.length>0;){if(turnStartAlreadyEmitted?turnStartAlreadyEmitted=!1:firstTurn?firstTurn=!1:await emit({type:"turn_start"}),drainedTerminatingQueue){if(await refreshTerminatingQueueDrain(),pendingMessages.length===0&&!explicitContinuation){await emit({type:"agent_end",messages:newMessages});return}drainedTerminatingQueue=void 0}for(let message2 of declareToolChanges(currentContext,[...preparedMessages,...pendingMessages],config.model))await emit({type:"message_start",message:message2}),await emit({type:"message_end",message:message2}),currentContext.messages.push(message2),newMessages.push(message2);preparedMessages=[],pendingMessages=[];let requestUpdate=await config.prepareRequest?.({context:currentContext,model:config.model,thinkingLevel:config.reasoning??"off"},signal);requestUpdate&&(currentContext=requestUpdate.context??currentContext,config=applyLoopUpdate(config,requestUpdate));let isInitialProviderRequest=firstProviderRequest;firstProviderRequest=!1;let requestConfig=isInitialProviderRequest?{...config,timeoutMs:config.initialRequestTimeoutMs??config.timeoutMs,streamStartTimeoutMs:config.initialRequestStreamStartTimeoutMs??config.streamStartTimeoutMs}:config,streamed=await streamAssistantResponse(currentContext,requestConfig,signal,emit,withEmptyAssistantRecovery(requestConfig.model,streamFunction),isInitialProviderRequest?config.timeoutMs:requestConfig.timeoutMs),message=demoteToolUseWithoutToolCalls(promoteStopWithPendingToolCalls(streamed.message)),providerToolResults=streamed.providerToolResults;newMessages.push(message);let toolResults=[];for(let result of providerToolResults)await emit({type:"message_start",message:result}),await emit({type:"message_end",message:result}),currentContext.messages.push(result),newMessages.push(result),toolResults.push(result);if(shouldTerminateAssistantTurn(message)){await config.finishTurn?.({message,toolResults,context:currentContext,newMessages},signal),await emit({type:"turn_end",message,toolResults}),await emit({type:"agent_end",messages:newMessages});return}let toolCalls=message.content.filter(c=>c.type==="toolCall"&&!isCursorExecResolved(c));hasMoreToolCalls=!1;let toolBatchTerminated=!1;if(toolCalls.length>0){let executedToolBatch=message.stopReason==="length"?await failToolCallsFromTruncatedMessage(toolCalls,emit):await executeToolCalls(currentContext,message,config,signal,emit);toolResults.push(...executedToolBatch.messages),toolBatchTerminated=executedToolBatch.terminate,hasMoreToolCalls=!executedToolBatch.terminate;for(let result of executedToolBatch.messages)currentContext.messages.push(result),newMessages.push(result)}let nextTurnContext={message,toolResults,context:currentContext,newMessages},decision=await config.finishTurn?.(nextTurnContext,signal);if(await emit({type:"turn_end",message,toolResults}),signal?.aborted){await emit({type:"agent_end",messages:newMessages});return}if(decision?.action==="end"){await emit({type:"agent_end",messages:newMessages});return}if(explicitContinuation=decision?.action==="continue",toolBatchTerminated){if(pendingMessages=await config.getSteeringMessages?.()||[],pendingMessages.length>0&&(drainedTerminatingQueue="steering"),pendingMessages.length===0&&(pendingMessages=await config.getFollowUpMessages?.()||[],pendingMessages.length>0&&(drainedTerminatingQueue="followUp")),pendingMessages.length===0&&!explicitContinuation){await emit({type:"agent_end",messages:newMessages});return}pendingMessages.length>0&&(await emit({type:"turn_start"}),turnStartAlreadyEmitted=!0)}let nextTurnSnapshot;try{nextTurnSnapshot=await config.prepareNextTurn?.(nextTurnContext)}catch(error){throw drainedTerminatingQueue&&await config.restorePendingMessages?.(drainedTerminatingQueue,pendingMessages),error}if(nextTurnSnapshot&&(currentContext=nextTurnSnapshot.context??currentContext,preparedMessages=nextTurnSnapshot.messages??[],config=applyLoopUpdate(config,nextTurnSnapshot)),signal?.aborted){drainedTerminatingQueue&&await config.restorePendingMessages?.(drainedTerminatingQueue,pendingMessages),await emit({type:"agent_end",messages:newMessages});return}if(drainedTerminatingQueue){if(await refreshTerminatingQueueDrain(),pendingMessages.length===0&&!explicitContinuation){await emit({type:"agent_end",messages:newMessages});return}drainedTerminatingQueue=void 0}toolBatchTerminated||(pendingMessages=await config.getSteeringMessages?.()||[]),(hasMoreToolCalls||pendingMessages.length>0)&&(explicitContinuation=!1)}let followUpMessages=await config.getFollowUpMessages?.()||[];if(followUpMessages.length>0){explicitContinuation=!1,pendingMessages=followUpMessages;continue}if(explicitContinuation){explicitContinuation=!1;continue}break}await emit({type:"agent_end",messages:newMessages})}function applyLoopUpdate(config,update){return{...config,model:update.model??config.model,reasoning:update.thinkingLevel===void 0?config.reasoning:update.thinkingLevel==="off"?void 0:update.thinkingLevel,thinkingSelection:update.thinkingSelection===void 0?config.thinkingSelection:update.thinkingSelection??void 0,abortServerSideFallback:update.abortServerSideFallback??config.abortServerSideFallback}}function declareToolChanges(context,pendingMessages,model){let systemIndex=-1;for(let i=pendingMessages.length-1;i>=0;i--)if(pendingMessages[i].role==="system"){systemIndex=i;break}let pending=pendingMessages[systemIndex],baseline=pending?pendingMessages.map((message,index2)=>index2===systemIndex?withToolChanges(pending,NO_CHANGES):message):pendingMessages,declared=(providerTools(context,model).tools??[]).map(toProviderToolDeclaration),shorthand=createInitialSystemMessage(context.systemPrompt,declared),committed=shorthand?[shorthand,...context.messages,...baseline]:[...context.messages,...baseline],delta=getToolStateChanges(getCurrentTools(committed),declared),declaredByName=new Map(declared.map(tool=>[tool.name,tool])),changes={toolsAdded:delta.toolsAdded.map(tool=>declaredByName.get(tool.name)??tool),toolsRemoved:delta.toolsRemoved},unchanged=changes.toolsAdded.length===0&&changes.toolsRemoved.length===0;if(pending)return unchanged&&!pending.toolsAdded?.length&&!pending.toolsRemoved?.length?pendingMessages:baseline.map((message,index2)=>index2===systemIndex?withToolChanges(pending,changes):message);if(unchanged)return pendingMessages;let update=withToolChanges({role:"system",content:"",timestamp:Date.now()},changes),insertIndex=pendingMessages.findIndex(message=>message.role!=="system"),index=insertIndex===-1?pendingMessages.length:insertIndex;return[...pendingMessages.slice(0,index),update,...pendingMessages.slice(index)]}var NO_CHANGES={toolsAdded:[],toolsRemoved:[]};function toProviderToolDeclaration(tool){return{name:tool.name,description:tool.description,parameters:tool.parameters,...tool.freeform===void 0?{}:{freeform:tool.freeform},...tool.constrainedSampling===void 0?{}:{constrainedSampling:tool.constrainedSampling}}}function withToolChanges(message,{toolsAdded,toolsRemoved}){let{toolsAdded:_added,toolsRemoved:_removed,...rest}=message;return{...rest,...toolsAdded.length>0?{toolsAdded}:{},...toolsRemoved.length>0?{toolsRemoved}:{}}}function providerTools(context,model){let declaredTools=context.declaredTools;if(declaredTools===void 0||model===void 0||!supportsAllowedToolChoice(model))return{tools:context.tools};let activeTools=context.tools??[],declaredNames=new Set(declaredTools.map(tool=>tool.name));return{tools:[...declaredTools,...activeTools.filter(tool=>!declaredNames.has(tool.name))],activeToolNames:activeTools.map(tool=>tool.name)}}async function buildProviderContext(context,config,signal){let messages=context.messages;config.transformContext&&(messages=await config.transformContext(messages,signal));let{tools,activeToolNames}=providerTools(context,config.model);return normalizeContext({systemPrompt:context.systemPrompt,messages:await config.convertToLlm(messages),...tools===void 0?{}:{tools:tools.map(toProviderToolDeclaration)},...activeToolNames===void 0?{}:{activeToolNames}})}async function streamAssistantResponse(context,config,signal,emit,streamFunction,streamIdleTimeoutMs){let partialMessage=null,addedPartial=!1,providerToolResults=[],thinkingTiming=new Map;function propagateThinkingTiming(finalMessage){for(let timing of thinkingTiming.values())timing.endedAt===void 0&&(timing.endedAt=Date.now());for(let[contentIndex,timing]of thinkingTiming){let block=finalMessage.content[contentIndex];block?.type==="thinking"&&(block.startedAt=timing.startedAt,block.endedAt=timing.endedAt)}}let requestAbortController=new AbortController,detachCallerAbort;if(signal!==void 0)if(signal.aborted)requestAbortController.abort(signal.reason);else{let onCallerAbort=()=>requestAbortController.abort(signal.reason);signal.addEventListener("abort",onCallerAbort,{once:!0}),detachCallerAbort=()=>signal.removeEventListener("abort",onCallerAbort)}try{let llmContext=await buildProviderContext(context,config,signal),resolvedApiKey=(config.getApiKey?await config.getApiKey(config.model.provider):void 0)||config.apiKey,response=await streamFunction(config.model,llmContext,{...config,streamKind:"main",apiKey:resolvedApiKey,signal:requestAbortController.signal,...config.cursorExecHandlers?{execHandlers:typeof config.cursorExecHandlers=="function"?config.cursorExecHandlers(signal??requestAbortController.signal):config.cursorExecHandlers,onToolResult:result2=>{providerToolResults.push(result2)}}:{}}),result=async()=>Object.assign(await response.result(),{thinkingLevel:config.reasoning??"off"}),iterator=response[Symbol.asyncIterator](),eventReader=createAssistantEventReader(iterator,streamIdleTimeoutMs,requestAbortController.signal,error=>requestAbortController.abort(error),config.streamStartTimeoutMs,response);try{for(;;){let next=await eventReader.next();if(next.done)break;let event=next.value;switch(event.type){case"start":partialMessage=event.partial,context.messages.push(partialMessage),addedPartial=!0,await emit({type:"message_start",message:{...partialMessage}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":if(partialMessage){if(partialMessage=event.partial,event.type==="thinking_start"||event.type==="thinking_delta"||event.type==="thinking_end"){let timing=thinkingTiming.get(event.contentIndex);event.type==="thinking_start"&&timing===void 0&&(timing={startedAt:Date.now()},thinkingTiming.set(event.contentIndex,timing)),event.type==="thinking_end"&&timing!==void 0&&(timing.endedAt=Date.now());let block=partialMessage.content[event.contentIndex];block?.type==="thinking"&&timing!==void 0&&(block.startedAt=timing.startedAt,timing.endedAt!==void 0&&(block.endedAt=timing.endedAt))}context.messages[context.messages.length-1]=partialMessage,await emit({type:"message_update",assistantMessageEvent:event,message:{...partialMessage}})}break;case"done":case"error":{let finalMessage2=normalizeTerminalAssistantMessage(await result(),event);return propagateThinkingTiming(finalMessage2),addedPartial?context.messages[context.messages.length-1]=finalMessage2:context.messages.push(finalMessage2),addedPartial||await emit({type:"message_start",message:{...finalMessage2}}),await emit({type:"message_end",message:finalMessage2}),{message:finalMessage2,providerToolResults}}}}}finally{eventReader.dispose()}let finalMessage=await result();return propagateThinkingTiming(finalMessage),addedPartial?context.messages[context.messages.length-1]=finalMessage:(context.messages.push(finalMessage),await emit({type:"message_start",message:{...finalMessage}})),await emit({type:"message_end",message:finalMessage}),{message:finalMessage,providerToolResults}}catch(error){if(isStreamIdleTimeoutError(error)&&shouldFinalizeIdleAsStop(partialMessage,providerToolResults)){let finalMessage2={role:"assistant",content:partialMessage?.content??[{type:"text",text:""}],api:partialMessage?.api??config.model.api,provider:partialMessage?.provider??config.model.provider,model:partialMessage?.model??config.model.id,responseModel:partialMessage?.responseModel,responseId:partialMessage?.responseId,diagnostics:partialMessage?.diagnostics,usage:partialMessage?.usage??{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:partialMessage?.timestamp??Date.now()};return propagateThinkingTiming(finalMessage2),addedPartial?context.messages[context.messages.length-1]=finalMessage2:(context.messages.push(finalMessage2),await emit({type:"message_start",message:{...finalMessage2}})),await emit({type:"message_end",message:finalMessage2}),{message:finalMessage2,providerToolResults}}let finalMessage=createTerminalFailureAssistantMessage(config.model,signal?.aborted?"aborted":"error",error,partialMessage);return propagateThinkingTiming(finalMessage),addedPartial?context.messages[context.messages.length-1]=finalMessage:(context.messages.push(finalMessage),await emit({type:"message_start",message:{...finalMessage}})),await emit({type:"message_end",message:finalMessage}),{message:finalMessage,providerToolResults}}finally{requestAbortController.abort(),detachCallerAbort?.()}}var ABORTED=Symbol("aborted");function abortError(reason){return reason instanceof Error?reason:new Error("Request was aborted")}function closeAssistantIterator(iterator){Promise.resolve(iterator.return?.()).catch(()=>{})}function normalizeTimeoutMs(timeoutMs){return typeof timeoutMs=="number"&&Number.isFinite(timeoutMs)&&timeoutMs>0?timeoutMs:void 0}function createAssistantEventReader(iterator,timeoutMs,signal,onIdleTimeout,streamStartTimeoutMs,stream){let idleTimeoutMs=normalizeTimeoutMs(timeoutMs),startTimeoutMs=normalizeTimeoutMs(streamStartTimeoutMs),sawFirstEvent=!1,removeAbortListener,abortPromise;return signal!==void 0&&(signal.aborted?abortPromise=Promise.resolve(ABORTED):abortPromise=new Promise(resolve=>{let abortHandler=()=>resolve(ABORTED);signal.addEventListener("abort",abortHandler,{once:!0}),removeAbortListener=()=>signal.removeEventListener("abort",abortHandler)})),{next:async()=>{if(signal?.aborted)return closeAssistantIterator(iterator),Promise.reject(abortError(signal.reason));let useStartBound=!sawFirstEvent&&startTimeoutMs!==void 0,result=await readNextAssistantEvent(iterator,useStartBound?startTimeoutMs:idleTimeoutMs,useStartBound?ms=>new StreamStartTimeoutError(ms):ms=>new StreamIdleTimeoutError(ms),abortPromise,onIdleTimeout,stream,signal);return result.done||(sawFirstEvent=!0),result},dispose:()=>removeAbortListener?.()}}async function readNextAssistantEvent(iterator,idleTimeoutMs,makeTimeoutError,abortPromise,onIdleTimeout,stream,signal){if(idleTimeoutMs===void 0&&abortPromise===void 0)return iterator.next();let timeout,settled=!1;return new Promise((resolve,reject)=>{let settle=complete=>{settled||(settled=!0,timeout!==void 0&&clearTimeout(timeout),complete())};if(idleTimeoutMs!==void 0){let onIdleDeadline=()=>{if(stream?.hasPendingLocalWork?.()){timeout=setTimeout(onIdleDeadline,idleTimeoutMs);return}let error=makeTimeoutError(idleTimeoutMs);closeAssistantIterator(iterator),settle(()=>reject(error)),onIdleTimeout?.(error)};timeout=setTimeout(onIdleDeadline,idleTimeoutMs)}(abortPromise?Promise.race([iterator.next(),abortPromise]):iterator.next()).then(result=>{if(result===ABORTED){closeAssistantIterator(iterator),settle(()=>reject(abortError(signal?.reason)));return}settle(()=>resolve(result))},error=>settle(()=>reject(error)))})}function createIncompleteToolCallErrorMessage(toolName,errorMessage2){return errorMessage2!==void 0?`${errorMessage2}${errorMessage2.endsWith(".")?"":"."} Re-issue the tool call with complete arguments.`:`Tool call "${toolName}" was not executed: the response ended before the tool call was complete because it hit the output token limit. Re-issue the tool call with complete arguments.`}async function failToolCallsFromTruncatedMessage(toolCalls,emit){let messages=[];for(let toolCall of toolCalls){await emit({type:"tool_execution_start",toolCallId:toolCall.id,toolName:toolCall.name,args:toolCall.arguments});let finalized={toolCall,result:createErrorToolResult(createIncompleteToolCallErrorMessage(toolCall.name)),isError:!0};await emitToolExecutionEnd(finalized,emit);let toolResultMessage=createToolResultMessage(finalized);await emitToolResultMessage(toolResultMessage,emit),messages.push(toolResultMessage)}return{messages,terminate:!1}}async function executeToolCalls(currentContext,assistantMessage,config,signal,emit){let toolCalls=assistantMessage.content.filter(c=>c.type==="toolCall"&&!isCursorExecResolved(c));return config.toolExecution==="sequential"?executeToolCallsSequential(currentContext,assistantMessage,toolCalls,config,signal,emit):executeToolCallsParallel(currentContext,assistantMessage,toolCalls,config,signal,emit)}async function executeToolCallsSequential(currentContext,assistantMessage,toolCalls,config,signal,emit){let finalizedCalls=[],messages=[];for(let toolCall of toolCalls){let tool=await resolveCallTool(currentContext,toolCall,config);await emit({type:"tool_execution_start",toolCallId:toolCall.id,toolName:tool?.name??toolCall.name,args:toolCall.arguments});let preparation=await prepareToolCall(currentContext,assistantMessage,toolCall,tool,config,signal),finalized;if(preparation.kind==="immediate")finalized={toolCall:preparation.toolCall,result:preparation.result,isError:preparation.isError};else{let executed=await executePreparedToolCall(preparation,signal,emitToolExecutionUpdate(preparation.toolCall,emit));finalized=await finalizeExecutedToolCall(currentContext,assistantMessage,preparation,executed,config,signal)}await emitToolExecutionEnd(finalized,emit);let toolResultMessage=createToolResultMessage(finalized);if(await emitToolResultMessage(toolResultMessage,emit),finalizedCalls.push(finalized),messages.push(toolResultMessage),signal?.aborted)break}return{messages,terminate:shouldTerminateToolBatch(finalizedCalls)}}async function executeToolCallsParallel(currentContext,assistantMessage,toolCalls,config,signal,emit){let finalizedCalls=[],preparedCalls=[],lastSequentialCall,currentParallelWave=[];for(let toolCall of toolCalls){let tool=await resolveCallTool(currentContext,toolCall,config);await emit({type:"tool_execution_start",toolCallId:toolCall.id,toolName:tool?.name??toolCall.name,args:toolCall.arguments});let preparation=await prepareToolCall(currentContext,assistantMessage,toolCall,tool,config,signal),isSequential=isSequentialToolCall(currentContext,preparation.toolCall),dependencies=isSequential?[...lastSequentialCall?[lastSequentialCall]:[],...currentParallelWave]:lastSequentialCall?[lastSequentialCall]:[];if(preparedCalls.push({preparation,isSequential,dependencies}),isSequential?(lastSequentialCall=void 0,currentParallelWave=[]):currentParallelWave.push(Promise.resolve(void 0)),signal?.aborted)break}let previousSequential,previousWave=[];for(let{preparation,isSequential}of preparedCalls){let dependencies=isSequential?[...previousSequential?[previousSequential]:[],...previousWave]:previousSequential?[previousSequential]:[],finalizedCall=(async()=>{await Promise.all(dependencies);let finalized=signal?.aborted?{toolCall:preparation.toolCall,result:createErrorToolResult("Operation aborted"),isError:!0}:await runPreparedToolCall(currentContext,assistantMessage,preparation,config,signal,emit);return await emitToolExecutionEnd(finalized,emit),finalized})();finalizedCalls.push(finalizedCall),isSequential?(previousSequential=finalizedCall,previousWave=[]):previousWave.push(finalizedCall)}let orderedFinalizedCalls=await Promise.all(finalizedCalls),messages=[];for(let finalized of orderedFinalizedCalls){let toolResultMessage=createToolResultMessage(finalized);await emitToolResultMessage(toolResultMessage,emit),messages.push(toolResultMessage)}return{messages,terminate:shouldTerminateToolBatch(orderedFinalizedCalls)}}async function runPreparedToolCall(currentContext,assistantMessage,preparation,config,signal,emit){if(preparation.kind==="immediate")return{toolCall:preparation.toolCall,result:preparation.result,isError:preparation.isError};let executed=await executePreparedToolCall(preparation,signal,emitToolExecutionUpdate(preparation.toolCall,emit));return finalizeExecutedToolCall(currentContext,assistantMessage,preparation,executed,config,signal)}function isSequentialToolCall(currentContext,toolCall){return currentContext.tools?.find(tool=>tool.name===toolCall.name)?.executionMode==="sequential"}function shouldTerminateToolBatch(finalizedCalls){return finalizedCalls.length>0&&finalizedCalls.every(finalized=>finalized.result.terminate===!0)}function prepareAgentToolCall(tool,toolCall){let preparedToolCall=prepareAgentToolCallArguments(tool,toolCall);return{toolCall:preparedToolCall,tool,args:validateToolArguments(tool,preparedToolCall)}}async function prepareToolCall(currentContext,assistantMessage,toolCall,tool,config,signal){if(toolCall.incomplete===!0)return{kind:"immediate",toolCall,result:createErrorToolResult(createIncompleteToolCallErrorMessage(toolCall.name,toolCall.errorMessage)),isError:!0};if(!tool){let hint=config.removedToolHints?.[toolCall.name];return{kind:"immediate",toolCall,result:createErrorToolResult(hint===void 0?`Tool ${toolCall.name} not found`:`Tool ${toolCall.name} not found. ${hint}`),isError:!0}}if(tool.name!==toolCall.name){let requestedName=toolCall.name,outcome=await prepareResolvedToolCall(currentContext,assistantMessage,{...toolCall,name:tool.name},tool,config,signal);return outcome.kind==="prepared"?{...outcome,requestedName}:{...outcome,result:withToolNameCorrection(outcome.result,requestedName,tool.name)}}return prepareResolvedToolCall(currentContext,assistantMessage,toolCall,tool,config,signal)}async function prepareResolvedToolCall(currentContext,assistantMessage,toolCall,tool,config,signal){try{let preparedToolCall=prepareAgentToolCall(tool,toolCall),validatedArgs=preparedToolCall.args;if(config.beforeToolCall){let beforeResult=await config.beforeToolCall({assistantMessage,toolCall:preparedToolCall.toolCall,args:validatedArgs,context:currentContext},signal);if(signal?.aborted)return{kind:"immediate",toolCall,result:createErrorToolResult("Operation aborted"),isError:!0};if(beforeResult?.block){let result=createErrorToolResult(beforeResult.reason||"Tool execution was blocked");return beforeResult.terminate===!0&&(result.terminate=!0),{kind:"immediate",toolCall,result,isError:!0}}}return signal?.aborted?{kind:"immediate",toolCall,result:createErrorToolResult("Operation aborted"),isError:!0}:{kind:"prepared",toolCall:preparedToolCall.toolCall,tool,args:validatedArgs}}catch(error){return{kind:"immediate",toolCall,result:createErrorToolResult(error instanceof Error?error.message:String(error)),isError:!0}}}function abortReleasePromise(signal){if(signal!==void 0)return signal.aborted?Promise.resolve(ABORTED):new Promise(resolve=>{signal.addEventListener("abort",()=>resolve(ABORTED),{once:!0})})}function emitToolExecutionUpdate(toolCall,emit){return partialResult=>emit({type:"tool_execution_update",toolCallId:toolCall.id,toolName:toolCall.name,args:toolCall.arguments,partialResult})}async function runToolCall(toolCall,options){let{assistantMessage,context,signal}=options,tool=options.tools.find(candidate=>candidate.name===toolCall.name),preparation=await prepareToolCall(context,assistantMessage,toolCall,tool,options,signal);if(preparation.kind==="immediate")return{toolCall,result:preparation.result,isError:preparation.isError};let executed=await executePreparedToolCall(preparation,signal,options.onUpdate??(()=>{}));return finalizeExecutedToolCall(context,assistantMessage,preparation,executed,options,signal)}async function executePreparedToolCall(prepared,signal,onUpdate){let updateEvents=[],acceptingUpdates=!0;try{let execution=prepared.tool.execute(prepared.toolCall.id,prepared.args,signal,partialResult=>{acceptingUpdates&&updateEvents.push(Promise.resolve(onUpdate(partialResult)))}),abortRelease=abortReleasePromise(signal),settled=abortRelease?await Promise.race([execution,abortRelease]):await execution;return settled===ABORTED?(Promise.resolve(execution).catch(()=>{}),acceptingUpdates=!1,await Promise.all(updateEvents),{result:createErrorToolResult("Tool execution aborted"),isError:!0}):(acceptingUpdates=!1,await Promise.all(updateEvents),{result:settled,isError:settled.isError===!0})}catch(error){return acceptingUpdates=!1,await Promise.all(updateEvents),{result:createErrorToolResult(error instanceof Error?error.message:String(error)),isError:!0}}finally{acceptingUpdates=!1}}async function finalizeExecutedToolCall(currentContext,assistantMessage,prepared,executed,config,signal){let result=executed.result,isError=executed.isError;if(config.afterToolCall)try{let afterResult=await config.afterToolCall({assistantMessage,toolCall:prepared.toolCall,args:prepared.args,result,isError,context:currentContext},signal);if(afterResult){let structuredContent=afterResult.structuredContent??(afterResult.content?void 0:result.structuredContent);result={...result,content:afterResult.content??result.content,details:afterResult.details??result.details,usage:afterResult.usage??result.usage,terminate:afterResult.terminate??result.terminate},structuredContent===void 0?delete result.structuredContent:result.structuredContent=structuredContent,isError=afterResult.isError??isError}}catch(error){result=createErrorToolResult(error instanceof Error?error.message:String(error)),isError=!0}return prepared.requestedName!==void 0&&(result=withToolNameCorrection(result,prepared.requestedName,prepared.toolCall.name)),{toolCall:prepared.toolCall,result,isError}}function createErrorToolResult(message){return{content:[{type:"text",text:message}],details:{}}}async function emitToolExecutionEnd(finalized,emit){await emit({type:"tool_execution_end",toolCallId:finalized.toolCall.id,toolName:finalized.toolCall.name,result:finalized.result,isError:finalized.isError})}function createToolResultMessage(finalized){return{role:"toolResult",toolCallId:finalized.toolCall.id,toolName:finalized.toolCall.name,content:finalized.result.content??[],details:finalized.result.details,usage:finalized.result.usage,...finalized.result.addedToolNames?.length?{addedToolNames:finalized.result.addedToolNames}:{},isError:finalized.isError,timestamp:Date.now()}}async function emitToolResultMessage(toolResultMessage,emit){await emit({type:"message_start",message:toolResultMessage}),await emit({type:"message_end",message:toolResultMessage})}function defaultConvertToLlm(messages){return messages.filter(message=>message.role==="system"||message.role==="user"||message.role==="assistant"||message.role==="toolResult")}var EMPTY_USAGE2={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},DEFAULT_MODEL={id:"unknown",name:"unknown",api:"unknown",provider:"unknown",baseUrl:"",reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function createMutableAgentState(initialState){let tools=initialState?.tools?.slice()??[],messages=initialState?.messages?.slice()??[];return{systemPrompt:initialState?.systemPrompt??"",model:initialState?.model??DEFAULT_MODEL,thinkingLevel:initialState?.thinkingLevel??"off",reasoningBaseline:initialState?.reasoningBaseline,get tools(){return tools},set tools(nextTools){tools=nextTools.slice()},get messages(){return messages},set messages(nextMessages){messages=nextMessages.slice()},declaredTools:initialState?.declaredTools?.slice(),isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0,providerDiagnostic:void 0}}var LLM_ROLES=new Set(["user","assistant","toolResult","system"]);function isBackgroundNotice(message){return!LLM_ROLES.has(message.role)}var PendingMessageQueue=class{constructor(mode){this.messages=[],this.clearGeneration=0,this.mode=mode}enqueue(message){this.messages.push(message)}hasItems(){return this.messages.length>0}getClearGeneration(){return this.clearGeneration}peek(){if(this.mode==="all")return this.messages.slice();let first=this.messages[0];if(!first)return[];if(!isBackgroundNotice(first))return[first];let end=1;for(;end<this.messages.length&&isBackgroundNotice(this.messages[end]);)end++;return this.messages.slice(0,end)}drain(){let drained=this.peek();return this.messages=this.messages.slice(drained.length),drained}prepend(messages){this.messages=[...messages,...this.messages]}clear(){this.messages=[],this.clearGeneration++}},Agent=class{async buildProviderContext(context,signal){return buildProviderContext(context,{convertToLlm:this.convertToLlm,transformContext:this.transformContext,model:this._state.model},signal)}constructor(options){this.listeners=new Set;let runtimeOptions=options??{};this._state=createMutableAgentState(runtimeOptions.initialState),this.convertToLlm=runtimeOptions.convertToLlm??defaultConvertToLlm,this.transformContext=runtimeOptions.transformContext,this.streamFunction=runtimeOptions.streamFn??getDefaultStreamFn(),this.getApiKey=runtimeOptions.getApiKey,this.onPayload=runtimeOptions.onPayload,this.onResponse=runtimeOptions.onResponse,this.onProviderStreamEvent=runtimeOptions.onProviderStreamEvent,this.beforeToolCall=runtimeOptions.beforeToolCall,this.afterToolCall=runtimeOptions.afterToolCall,this.finishTurn=runtimeOptions.finishTurn,this.prepareRequest=runtimeOptions.prepareRequest,this.prepareNextTurn=runtimeOptions.prepareNextTurn,this.prepareNextTurnWithContext=runtimeOptions.prepareNextTurnWithContext,this.steeringQueue=new PendingMessageQueue(runtimeOptions.steeringMode??"one-at-a-time"),this.followUpQueue=new PendingMessageQueue(runtimeOptions.followUpMode??"one-at-a-time"),this.sessionId=runtimeOptions.sessionId,this.thinkingBudgets=runtimeOptions.thinkingBudgets,this.transport=runtimeOptions.transport??"auto",this.timeoutMs=runtimeOptions.timeoutMs,this.streamStartTimeoutMs=runtimeOptions.streamStartTimeoutMs,this.maxRetryDelayMs=runtimeOptions.maxRetryDelayMs,this.toolExecution=runtimeOptions.toolExecution??"parallel",this.removedToolHints=runtimeOptions.removedToolHints??{},this.resolveUnknownToolCall=runtimeOptions.resolveUnknownToolCall,this.abortServerSideFallback=runtimeOptions.abortServerSideFallback,this.cursorExecHandlers=runtimeOptions.cursorExecHandlers}subscribe(listener){return this.listeners.add(listener),()=>this.listeners.delete(listener)}get state(){return this._state}set steeringMode(mode){this.steeringQueue.mode=mode}get steeringMode(){return this.steeringQueue.mode}set followUpMode(mode){this.followUpQueue.mode=mode}get followUpMode(){return this.followUpQueue.mode}steer(message){this.steeringQueue.enqueue(message)}followUp(message){this.followUpQueue.enqueue(message)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}peekQueuedMessages(){let steering=this.steeringQueue.peek();return steering.length>0?steering:this.followUpQueue.peek()}get signal(){return this.activeRun?.abortController.signal}abort(reason){this.activeRun?.abortController.abort(reason)}suppressQueuedMessageDrain(){this.activeRun&&(this.activeRun.suppressQueuedMessageDrain=!0)}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw new Error("Agent is already processing. Wait for completion before resetting.");this._state.messages=[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this._state.providerDiagnostic=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(input,images){if(this.activeRun)throw new Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let messages=this.normalizePromptInput(input,images);await this.runPromptMessages(messages)}async continueWithQueuedMessages(options={}){if(this.activeRun)throw new Error("Agent is already processing. Wait for completion before continuing.");if(this._state.messages[this._state.messages.length-1]?.role==="assistant"){await this.continue(options);return}let queuedSteering=this.steeringQueue.drain();if(queuedSteering.length>0){await this.runPromptMessages(queuedSteering,{skipInitialSteeringPoll:!0,initialRequestTimeoutMs:options.timeoutMs,initialRequestStreamStartTimeoutMs:options.streamStartTimeoutMs});return}let queuedFollowUps=this.followUpQueue.drain();if(queuedFollowUps.length>0){await this.runPromptMessages(queuedFollowUps,{initialRequestTimeoutMs:options.timeoutMs,initialRequestStreamStartTimeoutMs:options.streamStartTimeoutMs});return}await this.continue(options)}async continue(options={}){if(this.activeRun)throw new Error("Agent is already processing. Wait for completion before continuing.");let lastMessage=this._state.messages[this._state.messages.length-1];if(!lastMessage||this._state.messages.every(message=>message.role==="system"))throw new Error("No messages to continue from");if(lastMessage.role==="assistant"){let queuedSteering=this.steeringQueue.drain();if(queuedSteering.length>0){await this.runPromptMessages(queuedSteering,{skipInitialSteeringPoll:!0,initialRequestTimeoutMs:options.timeoutMs,initialRequestStreamStartTimeoutMs:options.streamStartTimeoutMs});return}let queuedFollowUps=this.followUpQueue.drain();if(queuedFollowUps.length>0){await this.runPromptMessages(queuedFollowUps,{initialRequestTimeoutMs:options.timeoutMs,initialRequestStreamStartTimeoutMs:options.streamStartTimeoutMs});return}throw new Error("Cannot continue from message role: assistant")}await this.runContinuation(options)}normalizePromptInput(input,images){if(Array.isArray(input))return input;if(typeof input!="string")return[input];let content=[{type:"text",text:input}];return images&&images.length>0&&content.push(...images),[{role:"user",content,timestamp:Date.now()}]}async runPromptMessages(messages,options={}){await this.runWithLifecycle(async signal=>{await runAgentLoop(messages,this.createContextSnapshot(),this.createLoopConfig(options),event=>this.processEvents(event),signal,this.streamFunction)})}async runContinuation(options={}){await this.runWithLifecycle(async signal=>{await runAgentLoopContinue(this.createContextSnapshot(),this.createLoopConfig({skipInitialSteeringPoll:options.deferQueuedMessages,initialRequestTimeoutMs:options.timeoutMs,initialRequestStreamStartTimeoutMs:options.streamStartTimeoutMs}),event=>this.processEvents(event),signal,this.streamFunction)})}createContextSnapshot(){return{systemPrompt:this._state.systemPrompt,messages:this._state.messages.slice(),tools:this._state.tools.slice(),...this._state.declaredTools?{declaredTools:this._state.declaredTools.slice()}:{}}}createLoopConfig(options={}){let skipInitialSteeringPoll=options.skipInitialSteeringPoll===!0,steeringQueueGeneration=this.steeringQueue.getClearGeneration(),followUpQueueGeneration=this.followUpQueue.getClearGeneration(),finishTurn=this.finishTurn,reasoning=this._state.reasoningBaseline??this._state.thinkingLevel;return{model:this._state.model,reasoning:reasoning==="off"?void 0:reasoning,thinkingSelection:this._state.thinkingSelection,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,timeoutMs:this.timeoutMs,streamStartTimeoutMs:this.streamStartTimeoutMs,initialRequestTimeoutMs:options.initialRequestTimeoutMs,initialRequestStreamStartTimeoutMs:options.initialRequestStreamStartTimeoutMs,maxRetryDelayMs:this.maxRetryDelayMs,abortServerSideFallback:this.abortServerSideFallback,cursorExecHandlers:this.cursorExecHandlers,toolExecution:this.toolExecution,removedToolHints:this.removedToolHints,resolveUnknownToolCall:this.resolveUnknownToolCall,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:finishTurn?async(turn,signal)=>{let decision=await finishTurn(turn,signal)??void 0;return decision?.action==="end"&&this.suppressQueuedMessageDrain(),decision}:void 0,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async context=>this.prepareNextTurnWithContext?await this.prepareNextTurnWithContext(context,this.signal):await this.prepareNextTurn?.(this.signal):void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>skipInitialSteeringPoll?(skipInitialSteeringPoll=!1,[]):(steeringQueueGeneration=this.steeringQueue.getClearGeneration(),this.steeringQueue.drain()),getFollowUpMessages:async()=>(followUpQueueGeneration=this.followUpQueue.getClearGeneration(),this.followUpQueue.drain()),restorePendingMessages:(queue,messages)=>{if(queue==="steering"){if(this.steeringQueue.getClearGeneration()!==steeringQueueGeneration)return;this.steeringQueue.prepend(messages);return}this.followUpQueue.getClearGeneration()===followUpQueueGeneration&&this.followUpQueue.prepend(messages)}}}async runWithLifecycle(executor){if(this.activeRun)throw new Error("Agent is already processing.");let abortController=new AbortController,resolvePromise=()=>{},promise=new Promise(resolve=>{resolvePromise=resolve});this.activeRun={promise,resolve:resolvePromise,abortController,suppressQueuedMessageDrain:!1},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0,this._state.providerDiagnostic=void 0;try{for(await executor(abortController.signal);!abortController.signal.aborted&&!this.activeRun?.suppressQueuedMessageDrain&&this.canDrainQueuedMessagesAfterRun()&&this.hasQueuedMessages();)await this.runQueuedMessagesAfterAgentEnd(abortController.signal)}catch(error){await this.handleRunFailure(error,abortController.signal.aborted)}finally{this.finishRun()}}canDrainQueuedMessagesAfterRun(){let lastMessage=this._state.messages[this._state.messages.length-1];return lastMessage?.role!=="assistant"||lastMessage.stopReason!=="error"&&lastMessage.stopReason!=="aborted"}async runQueuedMessagesAfterAgentEnd(signal){let queuedSteering=this.steeringQueue.drain();if(queuedSteering.length>0){await runAgentLoop(queuedSteering,this.createContextSnapshot(),this.createLoopConfig({skipInitialSteeringPoll:!0}),event=>this.processEvents(event),signal,this.streamFunction);return}let queuedFollowUps=this.followUpQueue.drain();queuedFollowUps.length!==0&&await runAgentLoop(queuedFollowUps,this.createContextSnapshot(),this.createLoopConfig(),event=>this.processEvents(event),signal,this.streamFunction)}async handleRunFailure(error,aborted){let providerDiagnostic=aborted?void 0:readProviderDiagnostic(error),failureMessage={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:EMPTY_USAGE2,stopReason:aborted?"aborted":"error",errorMessage:error instanceof Error?error.message:String(error),...providerDiagnostic===void 0?{}:{providerDiagnostic},...error instanceof ProviderRetryWatchdogAbortError?{abortSource:"provider"}:{},timestamp:Date.now()};await this.processEvents({type:"message_start",message:failureMessage}),await this.processEvents({type:"message_end",message:failureMessage}),await this.processEvents({type:"turn_end",message:failureMessage,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[failureMessage]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(event){switch(event.type){case"message_start":this._state.streamingMessage=event.message;break;case"message_update":this._state.streamingMessage=event.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(event.message);break;case"tool_execution_start":{let pendingToolCalls=new Set(this._state.pendingToolCalls);pendingToolCalls.add(event.toolCallId),this._state.pendingToolCalls=pendingToolCalls;break}case"tool_execution_end":{let pendingToolCalls=new Set(this._state.pendingToolCalls);pendingToolCalls.delete(event.toolCallId),this._state.pendingToolCalls=pendingToolCalls;break}case"turn_end":event.message.role==="assistant"&&event.message.errorMessage&&(this._state.errorMessage=event.message.errorMessage,this._state.providerDiagnostic=sanitizeProviderDiagnostic(event.message.providerDiagnostic));break;case"agent_end":this._state.streamingMessage=void 0;break}let signal=this.activeRun?.abortController.signal;if(!signal)throw new Error("Agent listener invoked outside active run");for(let listener of this.listeners)await listener(event,signal)}async emitExternalEvent(event,runSignal){let activeSignal=this.activeRun?.abortController.signal;!activeSignal||runSignal&&runSignal!==activeSignal||await this.processEvents(event)}};var Result={ok(value2){return{ok:!0,value:value2}},err(error){return{ok:!1,error}},isOk(result){return result.ok},isErr(result){return!result.ok}};function TaggedError(tag){class TaggedErrorClass extends Error{constructor(props){super(props.message),this._tag=tag,this.name=tag,Object.assign(this,props)}toJSON(){let payload={};for(let key of Object.keys(this))key!=="_tag"&&(payload[key]=this[key]);return{_tag:tag,message:this.message,...payload}}static is(value2){return value2 instanceof TaggedErrorClass}}return TaggedErrorClass}var LaneBusy=class extends TaggedError("LaneBusy"){},OperationMismatch=class extends TaggedError("OperationMismatch"){},NoActiveRun=class extends TaggedError("NoActiveRun"){},NoActiveOperation=class extends TaggedError("NoActiveOperation"){},NothingToResume=class extends TaggedError("NothingToResume"){},NothingToCompact=class extends TaggedError("NothingToCompact"){},InvalidMessage=class extends TaggedError("InvalidMessage"){},InvalidNavigation=class extends TaggedError("InvalidNavigation"){},UnknownSkill=class extends TaggedError("UnknownSkill"){},UnknownTemplate=class extends TaggedError("UnknownTemplate"){},UnknownTarget=class extends TaggedError("UnknownTarget"){},InvalidLane=class extends TaggedError("InvalidLane"){},Closed=class extends TaggedError("Closed"){},HarnessFault=class extends Error{constructor(message,cause){super(message),this.name="HarnessFault",this.cause=cause}},HarnessClosed=class extends Error{constructor(){super("AgentHarness was closed while the operation was active"),this.name="HarnessClosed"}};function matchError(error,matchers){let matcher=matchers[error._tag];return matcher(error)}import{awaitWithContext,BACKGROUND_CONTEXT,createContextKey,TODO_CONTEXT,withAbortSignal,withCancel,withContextValue,withoutAbortSignal}from"@earendil-works/chord/context";var TELEMETRY_CONTEXT_KEY=createContextKey("pi.telemetryContext");function getTelemetryContext(context){return context.value(TELEMETRY_CONTEXT_KEY)??NOOP_TELEMETRY_CONTEXT}function withTelemetryContext(telemetryContext,context){return withContextValue(TELEMETRY_CONTEXT_KEY,telemetryContext,context)}var AbortRequested=class extends Error{constructor(cancellation){super("Abort requested"),this.name="AbortRequested",this.cancellation=cancellation}};function createGate(){let state={status:"open"},controller=new AbortController,check=()=>{if(state.status==="aborting")throw new AbortRequested(state.cancellation);if(state.status==="closed")throw state.error};return{gate:{admit(invoke){return check(),invoke()},signal:controller.signal},control:{beginAbort(cancellation){state.status==="open"&&(state={status:"aborting",cancellation})},signalAbort(){state.status!=="aborting"||controller.signal.aborted||controller.abort(new AbortRequested(state.cancellation))},close(error){state.status!=="closed"&&(state={status:"closed",error},controller.signal.aborted||controller.abort(error))}}}}var SliceNotImplemented=class extends Error{constructor(operation){super(`${operation} is not implemented until its later AgentHarness slice`),this.name="SliceNotImplemented"}},Drive=class{constructor(options,context){this.operationId=options.operationId,this.context=withoutAbortSignal(context),this.waitForRetry=options.waitForRetry??!1,this.deferredPermits=options.pollDeferred===!0?1:0;let resolveCompletion,rejectCompletion;this.completion=new Promise((resolve,reject)=>{resolveCompletion=resolve,rejectCompletion=reject}),this.resolveCompletion=resolveCompletion,this.rejectCompletion=rejectCompletion,this.completion.catch(()=>{});let{gate,control}=createGate();this.gate=gate,this.control=control,this.closeController=new AbortController,this.closeSignal=this.closeController.signal}settle(outcome){this.resolveCompletion(outcome)}fail(error){this.rejectCompletion(error)}beginAbort(cancellation){this.control.beginAbort(cancellation)}signalAbort(){this.control.signalAbort()}closeGate(error){this.control.close(error),this.closeSignal.aborted||this.closeController.abort(error),this.rejectCompletion(error)}};var COMPACTION_SUMMARY_PREFIX=`The conversation history before this point was compacted into the following summary:
17
+
18
+ <summary>
19
+ `,COMPACTION_SUMMARY_SUFFIX=`
20
+ </summary>`,BRANCH_SUMMARY_PREFIX=`The following is a summary of a branch that this conversation came back from:
21
+
22
+ <summary>
23
+ `,BRANCH_SUMMARY_SUFFIX="</summary>";function bashExecutionToText(msg){let text=`Ran \`${msg.command}\`
24
+ `;return msg.output?text+=`\`\`\`
25
+ ${msg.output}
26
+ \`\`\``:text+="(no output)",msg.cancelled?text+=`
27
+
28
+ (command cancelled)`:msg.exitCode!==null&&msg.exitCode!==void 0&&msg.exitCode!==0&&(text+=`
29
+
30
+ Command exited with code ${msg.exitCode}`),msg.truncated&&msg.fullOutputPath&&(text+=`
31
+
32
+ [Output truncated. Full output: ${msg.fullOutputPath}]`),text}function createBranchSummaryMessage(summary,fromId,timestamp){return{role:"branchSummary",summary,fromId,timestamp:typeof timestamp=="number"?timestamp:new Date(timestamp).getTime()}}function createCompactionSummaryMessage(summary,tokensBefore,timestamp){return{role:"compactionSummary",summary,tokensBefore,timestamp:typeof timestamp=="number"?timestamp:new Date(timestamp).getTime()}}function createCustomMessage(customType,content,display,details,timestamp){return{role:"custom",customType,content,display,details,timestamp:typeof timestamp=="number"?timestamp:new Date(timestamp).getTime()}}function convertToLlm(messages){let converted=messages.map(m=>{switch(m.role){case"bashExecution":return m.excludeFromContext?void 0:{role:"user",content:[{type:"text",text:bashExecutionToText(m)}],timestamp:m.timestamp};case"custom":return{role:"user",content:typeof m.content=="string"?[{type:"text",text:m.content}]:m.content,timestamp:m.timestamp};case"branchSummary":return{role:"user",content:[{type:"text",text:BRANCH_SUMMARY_PREFIX+m.summary+BRANCH_SUMMARY_SUFFIX}],timestamp:m.timestamp};case"compactionSummary":return{role:"user",content:[{type:"text",text:COMPACTION_SUMMARY_PREFIX+m.summary+COMPACTION_SUMMARY_SUFFIX}],timestamp:m.timestamp};case"system":case"user":case"assistant":case"toolResult":return m;default:return}}).filter(m=>m!==void 0);return dropFailedAssistantTurns(converted)}function buildContextEntries(pathEntries){let compaction,compactionIndex=-1;for(let index=pathEntries.length-1;index>=0;index--){let entry=pathEntries[index];if(entry?.type==="compaction"){compaction=entry,compactionIndex=index;break}}return compaction===void 0?[...pathEntries]:[compaction,...pathEntries.slice(compactionIndex+1)]}function isContextMessage(message){return message.role!=="assistant"||message.stopReason!=="error"&&message.stopReason!=="aborted"&&message.stopReason!=="deferred"}function sessionEntryToContextMessages(entry){switch(entry.type){case"message":return isContextMessage(entry.message)?[entry.message]:[];case"compaction":return[createCompactionSummaryMessage(entry.summary,entry.tokensBefore,entry.timestamp),...entry.retainedTail.filter(isContextMessage)];case"branch_summary":return entry.summary?[createBranchSummaryMessage(entry.summary,entry.fromId,entry.timestamp)]:[];case"custom":return[]}}async function buildSessionContext(pathEntries,options,context){options??={};let entries=buildContextEntries(pathEntries),messages=[];for(let entry of entries){if(entry.type!=="custom"){messages.push(...sessionEntryToContextMessages(entry));continue}let projector=options.entryProjectors?.[entry.customType];projector!==void 0&&messages.push(...await projector(entry,context)??[])}return messages}function emptyUsage(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function addUsage(left,right){return{input:left.input+right.input,output:left.output+right.output,cacheRead:left.cacheRead+right.cacheRead,cacheWrite:left.cacheWrite+right.cacheWrite,...left.cacheWrite1h===void 0&&right.cacheWrite1h===void 0?{}:{cacheWrite1h:(left.cacheWrite1h??0)+(right.cacheWrite1h??0)},...left.reasoning===void 0&&right.reasoning===void 0?{}:{reasoning:(left.reasoning??0)+(right.reasoning??0)},totalTokens:left.totalTokens+right.totalTokens,cost:{input:left.cost.input+right.cost.input,output:left.cost.output+right.cost.output,cacheRead:left.cost.cacheRead+right.cost.cacheRead,cacheWrite:left.cost.cacheWrite+right.cost.cacheWrite,total:left.cost.total+right.cost.total}}}function createFileOps(){return{read:new Set,written:new Set,edited:new Set}}function extractFileOpsFromMessage(message,fileOps){if(message.role==="assistant"&&!(!("content"in message)||!Array.isArray(message.content)))for(let block of message.content){if(typeof block!="object"||block===null||!("type"in block)||block.type!=="toolCall"||!("arguments"in block)||!("name"in block))continue;let args=block.arguments;if(!args)continue;let path=typeof args.path=="string"?args.path:void 0;if(path)switch(block.name){case"read":fileOps.read.add(path);break;case"write":fileOps.written.add(path);break;case"edit":fileOps.edited.add(path);break}}}function computeFileLists(fileOps){let modified=new Set([...fileOps.edited,...fileOps.written]),readOnly=[...fileOps.read].filter(f=>!modified.has(f)).sort(),modifiedFiles=[...modified].sort();return{readFiles:readOnly,modifiedFiles}}function formatFileOperations(readFiles,modifiedFiles){let sections=[];return readFiles.length>0&&sections.push(`<read-files>
33
+ ${readFiles.join(`
34
+ `)}
35
+ </read-files>`),modifiedFiles.length>0&&sections.push(`<modified-files>
36
+ ${modifiedFiles.join(`
37
+ `)}
38
+ </modified-files>`),sections.length===0?"":`
39
+
40
+ ${sections.join(`
41
+
42
+ `)}`}var TOOL_RESULT_MAX_CHARS=2e3;function safeJsonStringify(value2){try{return JSON.stringify(value2)??"undefined"}catch{return"[unserializable]"}}function truncateForSummary(text,maxChars){if(text.length<=maxChars)return text;let truncatedChars=text.length-maxChars;return`${text.slice(0,maxChars)}
43
+
44
+ [... ${truncatedChars} more characters truncated]`}function isPortableSummaryContentBlock(block){return block.type!=="providerNative"}function contentTextForSummary(content,separator=`
45
+ `){return typeof content=="string"?content:contentText(content.filter(isPortableSummaryContentBlock),separator)}function serializeConversation(messages){let parts=[];for(let msg of messages)if(msg.role==="user"){let content=contentTextForSummary(msg.content,"");content&&parts.push(`[User]: ${content}`)}else if(msg.role==="assistant"){let thinkingParts=[],toolCalls=[];for(let block of msg.content)if(block.type==="thinking")thinkingParts.push(block.thinking);else if(block.type==="toolCall"){let args=block.arguments,argsStr=Object.entries(args).map(([k,v])=>`${k}=${safeJsonStringify(v)}`).join(", ");toolCalls.push(`${block.name}(${argsStr})`)}thinkingParts.length>0&&parts.push(`[Assistant thinking]: ${thinkingParts.join(`
46
+ `)}`),msg.content.some(block=>block.type==="text")&&parts.push(`[Assistant]: ${contentTextForSummary(msg.content)}`),toolCalls.length>0&&parts.push(`[Assistant tool calls]: ${toolCalls.join("; ")}`)}else if(msg.role==="toolResult"){let content=contentTextForSummary(msg.content,"");content&&parts.push(`[Tool result]: ${truncateForSummary(content,TOOL_RESULT_MAX_CHARS)}`)}return parts.join(`
47
+
48
+ `)}function safeJsonStringify2(value2){try{return JSON.stringify(value2)??"undefined"}catch{return"[unserializable]"}}function extractFileOperations(messages,entries,prevCompactionIndex){let fileOps=createFileOps();if(prevCompactionIndex>=0){let prevCompaction=entries[prevCompactionIndex];if(typeof prevCompaction.details=="object"&&prevCompaction.details!==null&&!Array.isArray(prevCompaction.details)){if(Array.isArray(prevCompaction.details.readFiles))for(let path of prevCompaction.details.readFiles)typeof path=="string"&&fileOps.read.add(path);if(Array.isArray(prevCompaction.details.modifiedFiles))for(let path of prevCompaction.details.modifiedFiles)typeof path=="string"&&fileOps.edited.add(path)}}for(let msg of messages)extractFileOpsFromMessage(msg,fileOps);return fileOps}function getMessageFromEntry(entry){if(entry.type==="message")return entry.message;if(entry.type==="branch_summary")return createBranchSummaryMessage(entry.summary,entry.fromId,entry.timestamp);if(entry.type==="compaction")return createCompactionSummaryMessage(entry.summary,entry.tokensBefore,entry.timestamp)}function getMessageFromEntryForCompaction(entry){if(entry.type!=="compaction")return getMessageFromEntry(entry)}function createSummaryRequestOptions(options,context){return{...options,signal:context.abortSignal,telemetryContext:getTelemetryContext(context),cacheRetention:"none",sessionId:options.sessionId??uuidv7()}}async function completeSimpleWithRetries(models,model,aiContext,options,retry,callbacks,context){let requestOptions=createSummaryRequestOptions(options,context);return retryAssistantCall(()=>models.completeSimple(model,aiContext,requestOptions),retry,requestOptions.signal,callbacks)}var DEFAULT_COMPACTION_SETTINGS={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4};function calculateContextTokens(usage){return usage.totalTokens||usage.input+usage.output+usage.cacheRead+usage.cacheWrite}function getAssistantUsage(msg){if(msg.role==="assistant"&&"usage"in msg){let assistantMsg=msg;if(assistantMsg.stopReason!=="aborted"&&assistantMsg.stopReason!=="error"&&assistantMsg.usage&&calculateContextTokens(assistantMsg.usage)>0)return assistantMsg.usage}}function getLastAssistantUsage(entries){for(let i=entries.length-1;i>=0;i--){let entry=entries[i];if(entry.type==="message"){let usage=getAssistantUsage(entry.message);if(usage)return usage}}}function getLastAssistantUsageInfo(messages,counted){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(!counted.has(message))continue;let usage=getAssistantUsage(message);if(usage)return{usage,index:i}}}function estimateContextTokens(messages){let counted=new Set(dropFailedAssistantTurns(messages)),usageInfo=getLastAssistantUsageInfo(messages,counted);if(!usageInfo){let estimated=0;for(let message of messages)counted.has(message)&&(estimated+=estimateTokens(message));return{tokens:estimated,usageTokens:0,trailingTokens:estimated,lastUsageIndex:null}}let usageTokens=calculateContextTokens(usageInfo.usage),trailingTokens=0;for(let i=usageInfo.index+1;i<messages.length;i++)counted.has(messages[i])&&(trailingTokens+=estimateTokens(messages[i]));return{tokens:usageTokens+trailingTokens,usageTokens,trailingTokens,lastUsageIndex:usageInfo.index}}function shouldCompact(contextTokens,contextWindow,settings){return settings.enabled?contextTokens>contextWindow-settings.reserveTokens:!1}var ESTIMATED_IMAGE_CHARS=4800;function estimateTextAndImageContentChars(content){if(typeof content=="string")return content.length;let chars=0;for(let block of content)block.type==="text"&&block.text?chars+=block.text.length:block.type==="image"&&(chars+=ESTIMATED_IMAGE_CHARS);return chars}function estimateTokens(message){let chars=0;switch(message.role){case"user":return chars=estimateTextAndImageContentChars(message.content),Math.ceil(chars/4);case"assistant":{let assistant=message;for(let block of assistant.content)block.type==="text"?chars+=block.text.length:block.type==="thinking"?chars+=block.thinking.length:block.type==="toolCall"&&(chars+=block.name.length+safeJsonStringify2(block.arguments).length);return Math.ceil(chars/4)}case"custom":case"toolResult":return chars=estimateTextAndImageContentChars(message.content),Math.ceil(chars/4);case"bashExecution":return chars=message.command.length+message.output.length,Math.ceil(chars/4);case"branchSummary":case"compactionSummary":return chars=message.summary.length,Math.ceil(chars/4)}return 0}function findValidCutPoints(entries,startIndex,endIndex){let cutPoints=[];for(let i=startIndex;i<endIndex;i++){let entry=entries[i];switch(entry.type){case"message":{switch(entry.message.role){case"bashExecution":case"custom":case"branchSummary":case"compactionSummary":case"user":case"assistant":cutPoints.push(i);break;case"toolResult":break}break}case"compaction":case"branch_summary":case"custom":break}entry.type==="branch_summary"&&cutPoints.push(i)}return cutPoints}function findTurnStartIndex(entries,entryIndex,startIndex){for(let i=entryIndex;i>=startIndex;i--){let entry=entries[i];if(entry.type==="branch_summary")return i;if(entry.type==="message"){let role=entry.message.role;if(role==="user"||role==="bashExecution")return i}}return-1}function findCutPoint(entries,startIndex,endIndex,keepRecentTokens){let cutPoints=findValidCutPoints(entries,startIndex,endIndex);if(cutPoints.length===0)return{firstKeptEntryIndex:startIndex,turnStartIndex:-1,isSplitTurn:!1};let accumulatedTokens=0,cutIndex=cutPoints[0];for(let i=endIndex-1;i>=startIndex;i--){let entry=entries[i];if(entry.type!=="message")continue;let messageTokens=estimateTokens(entry.message);if(accumulatedTokens+=messageTokens,accumulatedTokens>=keepRecentTokens){let foundCutPoint=!1;for(let c=0;c<cutPoints.length;c++)if(cutPoints[c]>=i){cutIndex=cutPoints[c],foundCutPoint=!0;break}foundCutPoint||(cutIndex=cutPoints[cutPoints.length-1]);break}}for(;cutIndex>startIndex;){let prevEntry=entries[cutIndex-1];if(prevEntry.type==="compaction"||prevEntry.type==="message")break;cutIndex--}let cutEntry=entries[cutIndex],isUserMessage=cutEntry.type==="message"&&cutEntry.message.role==="user",turnStartIndex=isUserMessage?-1:findTurnStartIndex(entries,cutIndex,startIndex);return{firstKeptEntryIndex:cutIndex,turnStartIndex,isSplitTurn:!isUserMessage&&turnStartIndex!==-1}}var SUMMARIZATION_SYSTEM_PROMPT=`You are a context summarization assistant. Your task is to read a conversation between a user and an AI assistant, then produce a structured summary following the exact format specified.
49
+
50
+ Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`,SUMMARIZATION_PROMPT=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
51
+
52
+ Use this EXACT format:
53
+
54
+ ## Goal
55
+ [What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
56
+
57
+ ## Constraints & Preferences
58
+ - [Any constraints, preferences, or requirements mentioned by user]
59
+ - [Or "(none)" if none were mentioned]
60
+
61
+ ## Progress
62
+ ### Done
63
+ - [x] [Completed tasks/changes]
64
+
65
+ ### In Progress
66
+ - [ ] [Current work]
67
+
68
+ ### Blocked
69
+ - [Issues preventing progress, if any]
70
+
71
+ ## Key Decisions
72
+ - **[Decision]**: [Brief rationale]
73
+
74
+ ## Next Steps
75
+ 1. [Ordered list of what should happen next]
76
+
77
+ ## Critical Context
78
+ - [Any data, examples, or references needed to continue]
79
+ - [Or "(none)" if not applicable]
80
+
81
+ Keep each section concise. Preserve exact file paths, function names, and error messages.`,UPDATE_SUMMARIZATION_PROMPT=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
82
+
83
+ Update the existing structured summary with new information. RULES:
84
+ - PRESERVE all existing information from the previous summary
85
+ - ADD new progress, decisions, and context from the new messages
86
+ - UPDATE the Progress section: move items from "In Progress" to "Done" when completed
87
+ - UPDATE "Next Steps" based on what was accomplished
88
+ - PRESERVE exact file paths, function names, and error messages
89
+ - If something is no longer relevant, you may remove it
90
+
91
+ Use this EXACT format:
92
+
93
+ ## Goal
94
+ [Preserve existing goals, add new ones if the task expanded]
95
+
96
+ ## Constraints & Preferences
97
+ - [Preserve existing, add new ones discovered]
98
+
99
+ ## Progress
100
+ ### Done
101
+ - [x] [Include previously done items AND newly completed items]
102
+
103
+ ### In Progress
104
+ - [ ] [Current work - update based on progress]
105
+
106
+ ### Blocked
107
+ - [Current blockers - remove if resolved]
108
+
109
+ ## Key Decisions
110
+ - **[Decision]**: [Brief rationale] (preserve all previous, add new)
111
+
112
+ ## Next Steps
113
+ 1. [Update based on current state]
114
+
115
+ ## Critical Context
116
+ - [Preserve important context, add new if needed]
117
+
118
+ Keep each section concise. Preserve exact file paths, function names, and error messages.`;async function generateSummary(currentMessages,models,model,reserveTokens,customInstructions,previousSummary,thinkingLevel,retry,callbacks,context){let result=await generateSummaryWithUsage(currentMessages,models,model,reserveTokens,customInstructions,previousSummary,thinkingLevel,retry,callbacks,context);return result.ok?ok(result.value.text):err(result.error)}function generateSummaryWithUsage(currentMessages,models,model,reserveTokens,customInstructions,previousSummary,thinkingLevel,retry,callbacks,context){return generateSummaryWithRequest(currentMessages,{model,reserveTokens,customInstructions,previousSummary,thinkingLevel},(aiContext,options,requestContext)=>completeSimpleWithRetries(models,model,aiContext,options,retry,callbacks,requestContext),context)}async function generateSummaryWithRequest(currentMessages,options,request,context){let{model,reserveTokens,customInstructions,previousSummary,thinkingLevel}=options,maxTokens=Math.min(Math.floor(.8*reserveTokens),model.maxTokens>0?model.maxTokens:Number.POSITIVE_INFINITY),basePrompt=previousSummary?UPDATE_SUMMARIZATION_PROMPT:SUMMARIZATION_PROMPT;customInstructions&&(basePrompt=`${basePrompt}
119
+
120
+ Additional focus: ${customInstructions}`);let llmMessages=convertToLlm(currentMessages),promptText=`<conversation>
121
+ ${serializeConversation(llmMessages)}
122
+ </conversation>
123
+
124
+ `;previousSummary&&(promptText+=`<previous-summary>
125
+ ${previousSummary}
126
+ </previous-summary>
127
+
128
+ `),promptText+=basePrompt;let summarizationMessages=[{role:"user",content:[{type:"text",text:promptText}],timestamp:Date.now()}],completionOptions=model.reasoning&&thinkingLevel&&thinkingLevel!=="off"?{maxTokens,reasoning:thinkingLevel}:{maxTokens},response=await request({systemPrompt:SUMMARIZATION_SYSTEM_PROMPT,messages:summarizationMessages},createSummaryRequestOptions(completionOptions,context),context);if(response.stopReason==="aborted")return err(new CompactionError("aborted",response.errorMessage||"Summarization aborted"));if(response.stopReason==="error")return err(new CompactionError("summarization_failed",`Summarization failed: ${response.errorMessage||"Unknown error"}`));let unusable=unusableSummary(response,"Summarization");if(unusable!==void 0)return err(new CompactionError("summarization_failed",unusable));let textContent=contentTextForSummary(response.content);return ok({text:textContent,usage:response.usage})}function unusableSummary(response,label){if(response.stopReason==="length")return`${label} hit the token limit; the summary is incomplete`;if(response.content.some(block=>block.type==="toolCall"))return`${label} attempted to call a tool`;if(contentTextForSummary(response.content).trim().length===0)return`${label} produced no text`}function prepareCompaction(pathEntries,settings){if(pathEntries.length===0||pathEntries[pathEntries.length-1].type==="compaction")return ok(void 0);let prevCompactionIndex=-1;for(let i=pathEntries.length-1;i>=0;i--)if(pathEntries[i].type==="compaction"){prevCompactionIndex=i;break}let previousSummary,compactableEntries=pathEntries;if(prevCompactionIndex>=0){let prevCompaction=pathEntries[prevCompactionIndex];previousSummary=prevCompaction.summary,compactableEntries=[...prevCompaction.retainedTail.map((message,index)=>({type:"message",id:`${prevCompaction.id}:retained:${index}`,parentId:index===0?prevCompaction.id:`${prevCompaction.id}:retained:${index-1}`,seq:prevCompaction.seq,timestamp:message.timestamp,message})),...pathEntries.slice(prevCompactionIndex+1)]}let boundaryEnd=compactableEntries.length,tokensBefore=estimateCompactionPathTokens(pathEntries),cutPoint=findCutPoint(compactableEntries,0,boundaryEnd,settings.keepRecentTokens),historyEnd=cutPoint.isSplitTurn?cutPoint.turnStartIndex:cutPoint.firstKeptEntryIndex,messagesToSummarize=[];for(let i=0;i<historyEnd;i++){let msg=getMessageFromEntryForCompaction(compactableEntries[i]);msg&&messagesToSummarize.push(msg)}let turnPrefixMessages=[];if(cutPoint.isSplitTurn)for(let i=cutPoint.turnStartIndex;i<cutPoint.firstKeptEntryIndex;i++){let msg=getMessageFromEntryForCompaction(compactableEntries[i]);msg&&turnPrefixMessages.push(msg)}let retainedTail=[];for(let i=cutPoint.firstKeptEntryIndex;i<boundaryEnd;i++){let msg=getMessageFromEntryForCompaction(compactableEntries[i]);msg&&retainedTail.push(msg)}let fileOps=extractFileOperations(messagesToSummarize,pathEntries,prevCompactionIndex);if(cutPoint.isSplitTurn)for(let msg of turnPrefixMessages)extractFileOpsFromMessage(msg,fileOps);return ok({messagesToSummarize,turnPrefixMessages,retainedTail,isSplitTurn:cutPoint.isSplitTurn,tokensBefore,previousSummary,fileOps,settings})}function estimateCompactionPathTokens(pathEntries){let entries=buildContextEntries(pathEntries),boundary=0;for(let i=entries.length-1;i>=0;i--)if(entries[i].type==="compaction"){boundary=i+1;break}let since=estimateContextTokens(entries.slice(boundary).flatMap(sessionEntryToContextMessages));if(since.lastUsageIndex!==null)return since.tokens;let tokens=since.tokens;for(let message of dropFailedAssistantTurns(entries.slice(0,boundary).flatMap(sessionEntryToContextMessages)))tokens+=estimateTokens(message);return tokens}var TURN_PREFIX_SUMMARIZATION_PROMPT=`This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.
129
+
130
+ Summarize the prefix to provide context for the retained suffix:
131
+
132
+ ## Original Request
133
+ [What did the user ask for in this turn?]
134
+
135
+ ## Early Progress
136
+ - [Key decisions and work done in the prefix]
137
+
138
+ ## Context for Suffix
139
+ - [Information needed to understand the retained recent work]
140
+
141
+ Be concise. Focus on what's needed to understand the kept suffix.`;function compact(preparation,models,model,customInstructions,thinkingLevel,retry,callbacks,context){return compactWithRequest(preparation,{model,customInstructions,thinkingLevel},(aiContext,options,requestContext)=>completeSimpleWithRetries(models,model,aiContext,options,retry,callbacks,requestContext),context)}async function compactWithRequest(preparation,options,request,context){let{model,customInstructions,thinkingLevel}=options,{messagesToSummarize,turnPrefixMessages,retainedTail,isSplitTurn,tokensBefore,previousSummary,fileOps,settings}=preparation,summary,summaryUsage;if(isSplitTurn&&turnPrefixMessages.length>0){let historyText="No prior history.",historyUsage;if(messagesToSummarize.length>0){let historyResult=await generateSummaryWithRequest(messagesToSummarize,{model,reserveTokens:settings.reserveTokens,customInstructions,previousSummary,thinkingLevel},request,context);if(!historyResult.ok)return err(historyResult.error);historyText=historyResult.value.text,historyUsage=historyResult.value.usage}let turnPrefixResult=await generateTurnPrefixSummary(turnPrefixMessages,model,settings.reserveTokens,thinkingLevel,request,context);if(!turnPrefixResult.ok)return err(turnPrefixResult.error);summary=`${historyText}
142
+
143
+ ---
144
+
145
+ **Turn Context (split turn):**
146
+
147
+ ${turnPrefixResult.value.text}`,summaryUsage=historyUsage?addUsage(historyUsage,turnPrefixResult.value.usage):turnPrefixResult.value.usage}else{let summaryResult=await generateSummaryWithRequest(messagesToSummarize,{model,reserveTokens:settings.reserveTokens,customInstructions,previousSummary,thinkingLevel},request,context);if(!summaryResult.ok)return err(summaryResult.error);summary=summaryResult.value.text,summaryUsage=summaryResult.value.usage}let{readFiles,modifiedFiles}=computeFileLists(fileOps);return summary+=formatFileOperations(readFiles,modifiedFiles),ok({summary,tokensBefore,usage:summaryUsage,retainedTail,details:{readFiles,modifiedFiles}})}async function generateTurnPrefixSummary(messages,model,reserveTokens,thinkingLevel,request,context){let maxTokens=Math.min(Math.floor(.5*reserveTokens),model.maxTokens>0?model.maxTokens:Number.POSITIVE_INFINITY),llmMessages=convertToLlm(messages),summarizationMessages=[{role:"user",content:[{type:"text",text:`<conversation>
148
+ ${serializeConversation(llmMessages)}
149
+ </conversation>
150
+
151
+ ${TURN_PREFIX_SUMMARIZATION_PROMPT}`}],timestamp:Date.now()}],completionOptions=model.reasoning&&thinkingLevel&&thinkingLevel!=="off"?{maxTokens,reasoning:thinkingLevel}:{maxTokens},response=await request({systemPrompt:SUMMARIZATION_SYSTEM_PROMPT,messages:summarizationMessages},createSummaryRequestOptions(completionOptions,context),context);if(response.stopReason==="aborted")return err(new CompactionError("aborted",response.errorMessage||"Turn prefix summarization aborted"));if(response.stopReason==="error")return err(new CompactionError("summarization_failed",`Turn prefix summarization failed: ${response.errorMessage||"Unknown error"}`));let unusable=unusableSummary(response,"Turn prefix summarization");return unusable!==void 0?err(new CompactionError("summarization_failed",unusable)):ok({text:contentTextForSummary(response.content),usage:response.usage})}var DEFAULT_RETRY_POLICY={enabled:!0,maxRetries:3,baseDelayMs:1e3,maxAgentDelayMs:DEFAULT_MAX_AGENT_RETRY_DELAY_MS};function validateToolNames(tools){let names=new Set;for(let tool of tools){if(names.has(tool.name))throw new TypeError(`Duplicate tool name: ${JSON.stringify(tool.name)}`);names.add(tool.name)}}function validateRetryPolicy(policy){if(!Number.isSafeInteger(policy.maxRetries)||policy.maxRetries<0||policy.maxRetries===Number.MAX_SAFE_INTEGER||!Number.isSafeInteger(policy.baseDelayMs)||policy.baseDelayMs<0||policy.maxAgentDelayMs!==void 0&&(!Number.isSafeInteger(policy.maxAgentDelayMs)||policy.maxAgentDelayMs<0))throw new RangeError("Retry policy values must be finite non-negative safe integers")}function validateCompactionSettings(settings){if(!Number.isSafeInteger(settings.reserveTokens)||settings.reserveTokens<0||!Number.isSafeInteger(settings.keepRecentTokens)||settings.keepRecentTokens<0)throw new RangeError("Compaction token counts must be finite non-negative safe integers")}var HarnessEventBus=class{constructor(){this.listeners=new Map,this.watchListeners=new Set,this.deliveryTail=Promise.resolve()}on(type,listener){if(this.closedError!==void 0)throw this.closedError;let wrapped=(event,context)=>listener(event,context),listeners=this.listeners.get(type);return listeners===void 0&&(listeners=new Set,this.listeners.set(type,listeners)),listeners.add(wrapped),()=>listeners?.delete(wrapped)}emit(event,context){return this.emitBatch([event],context)}emitBatch(events,context){if(this.closedError!==void 0||events.length===0)return Promise.resolve();let bound=events.map(event=>{let payload=structuredClone(event);return{payload,recipients:this.snapshotRecipients(payload)}}),delivery=this.deliveryTail.then(async()=>{for(let{payload,recipients}of bound)await this.deliver(payload,recipients,!0,context)});return this.deliveryTail=delivery.catch(()=>{}),delivery}watch(snapshot,filter,_context,resnapshot){if(this.closedError!==void 0)throw this.closedError;return this.installWatcher(snapshot,filter,resnapshot)}async watchFromSnapshot(capture,filter,context){if(this.closedError!==void 0)throw this.closedError;let watcher=this.installWatcher(void 0,filter,async(captureContext,markBoundary)=>{let snapshot=await capture(captureContext);return markBoundary(),snapshot});try{return watcher.setSnapshot(await capture(context)),watcher}catch(error){throw watcher.unsubscribe(),error}}close(error){this.closedError??=error,this.deliveryTail.finally(()=>{this.listeners.clear(),this.watchListeners.clear()})}installWatcher(snapshot,filter,resnapshot){let watcher,capture=resnapshot===void 0?void 0:async context=>{let marked=!1,next=await resnapshot(context,()=>{if(marked)throw new Error("Resnapshot boundary was already marked");marked=!0,this.enqueueBarrier(()=>watcher.markResnapshotBoundary())});if(!marked)throw new Error("Resnapshot capture did not mark its boundary");return next};watcher=new BufferedEventWatcher(snapshot,capture,async(error,event,context)=>{if(event.type==="handler_error")return;let normalized=error instanceof Error?error:new Error(String(error)),lane="lane"in event&&typeof event.lane=="string"?event.lane:void 0;await this.emit({type:"handler_error",kind:"event",event:event.type,error:normalized.message,...normalized.stack===void 0?{}:{stack:normalized.stack},...lane===void 0?{}:{lane}},context)});let watchListener=(event,context)=>{filter(event)&&watcher.push(event,context)};return this.watchListeners.add(watchListener),watcher.setUnsubscribe(()=>this.watchListeners.delete(watchListener)),watcher}enqueueBarrier(barrier){let delivery=this.deliveryTail.then(barrier);this.deliveryTail=delivery.catch(()=>{})}snapshotRecipients(event){return[...this.listeners.get(event.type)??[],...this.watchListeners]}async deliver(event,recipients,reportErrors,context){for(let listener of recipients)try{await listener(structuredClone(event),context)}catch(error){if(!reportErrors||event.type==="handler_error")continue;let normalized=error instanceof Error?error:new Error(String(error)),lane="lane"in event&&typeof event.lane=="string"?event.lane:void 0,handlerError={type:"handler_error",kind:"event",event:event.type,error:normalized.message,...normalized.stack===void 0?{}:{stack:normalized.stack},...lane===void 0?{}:{lane}};await this.deliver(handlerError,this.snapshotRecipients(handlerError),!1,context)}}},BufferedEventWatcher=class{constructor(snapshot,resnapshot,onError){this.buffer=[],this.deliveryTail=Promise.resolve(),this.epoch=0,this.state="buffering",this.snapshot=snapshot,this.resnapshotCallback=resnapshot,this.onError=onError}setSnapshot(snapshot){this.snapshot=snapshot}start(listener){if(this.state!=="buffering")throw new Error("WatchHandle.start() may be called only once");this.state="started",this.listener=listener;let buffered=this.buffer;this.buffer=[];for(let bufferedEvent of buffered)this.enqueue(bufferedEvent.event,bufferedEvent.context,bufferedEvent.epoch)}async resnapshot(context){if(this.state==="unsubscribed")throw new Error("WatchHandle is unsubscribed");if(this.resnapshotCallback===void 0)throw new Error("WatchHandle does not support resnapshot");if(this.resnapshotState!==void 0)throw new Error("WatchHandle resnapshot is already in progress");let resolveReached,reached=new Promise(resolve=>{resolveReached=resolve}),resnapshotState={phase:"dropping",held:[],reached,resolveReached};this.epoch++,this.resnapshotState=resnapshotState;try{let snapshot=await this.resnapshotCallback(context);await reached,this.snapshot=snapshot,this.resnapshotState=void 0;for(let held of resnapshotState.held)this.push(held.event,held.context);return snapshot}catch(error){this.resnapshotState=void 0;for(let held of resnapshotState.held)this.push(held.event,held.context);throw error}}markResnapshotBoundary(){let resnapshot=this.resnapshotState;resnapshot===void 0||resnapshot.phase!=="dropping"||(resnapshot.phase="holding",resnapshot.resolveReached())}unsubscribe(){this.state!=="unsubscribed"&&(this.state="unsubscribed",this.buffer=[],this.listener=void 0,this.unsubscribeCallback?.(),this.unsubscribeCallback=void 0)}push(event,context){if(this.state!=="unsubscribed"&&this.resnapshotState?.phase!=="dropping"){if(this.resnapshotState?.phase==="holding"){this.resnapshotState.held.push({event,context});return}if(this.state==="buffering"){this.buffer.push({event,context,epoch:this.epoch});return}this.enqueue(event,context,this.epoch)}}setUnsubscribe(callback){this.unsubscribeCallback=callback}enqueue(event,context,epoch){let listener=this.listener;listener!==void 0&&(this.deliveryTail=this.deliveryTail.then(async()=>{this.state==="started"&&epoch===this.epoch&&await listener(event,context)}).catch(async error=>{try{await this.onError(error,event,context)}catch{}}))}};var AI_TELEMETRY_SCHEMA={version:1,spans:{"pi.ai.request":{description:"One logical request to an AI provider",parents:{kind:"any"},startAttributes:{"pi.ai.operation":{type:"string",required:!0,values:["stream","fetch_deferred","cancel_deferred","generate_images"],description:"Logical provider operation"},"pi.ai.provider":{type:"string",required:!0,description:"Selected provider id"},"pi.ai.model":{type:"string",required:!0,description:"Requested model id"},"pi.ai.api":{type:"string",required:!0,description:"Provider API id"},"pi.ai.streaming":{type:"boolean",required:!0,description:"Whether this operation returns a stream"},"pi.ai.deferred":{type:"boolean",required:!1,description:"Whether the operation requests or participates in deferred execution"}},endAttributes:{"pi.ai.response.model":{type:"string",description:"Concrete response model"},"pi.ai.response.id":{type:"string",cardinality:"high",description:"Provider response id"},"pi.ai.response.stop_reason":{type:"string",values:["stop","length","tool_use","error","aborted","deferred"],description:"Normalized terminal response reason"},"pi.ai.http.status_code":{type:"number",description:"Final HTTP status"},"pi.ai.usage.input_tokens":{type:"number",description:"Reported input tokens"},"pi.ai.usage.output_tokens":{type:"number",description:"Reported output tokens"},"pi.ai.usage.cache_read_tokens":{type:"number",description:"Reported cache-read tokens"},"pi.ai.usage.cache_write_tokens":{type:"number",description:"Reported cache-write tokens"},"pi.ai.usage.reasoning_tokens":{type:"number",description:"Reported reasoning tokens"},"pi.ai.usage.total_tokens":{type:"number",description:"Reported total tokens"},"pi.ai.usage.cost":{type:"number",description:"Reported total cost"},"pi.ai.stream.chunk_count":{type:"number",description:"Streamed update chunk count"},"pi.ai.stream.time_to_first_chunk_ms":{type:"number",description:"Elapsed milliseconds to first update chunk"},"pi.ai.error.type":{type:"string",cardinality:"low",description:"Provider or transport error class"}},status:{default:"ok",errorWhen:"The operation throws or returns an error result"}}}};function startAiSpan(name,attributes,callback,context){return getTelemetryContext(context).startSpan({name,attributes},span=>callback(span,withTelemetryContext(span,context)))}var HOOK_NAMES=["before_run","before_drive","before_run_end","transform_context","before_request","before_payload","after_response","before_tool","after_tool","before_compaction","before_navigation"],EVENT_TYPES=["run_start","run_resume","run_suspend","operation_abort","run_end","fault","handler_error","turn_start","turn_end","retry_scheduled","retry_start","retry_end","message_start","message_update","message_end","tool_start","tool_update","tool_end","entry_added","queue_update","value_update","config_update","compaction_start","compaction_end","navigation_start","navigation_end","lane_created","usage"],operationStartAttributes={"pi.session.id":{type:"string",required:!0,cardinality:"high",description:"Session id"},"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.operation.recovery":{type:"boolean",required:!0,description:"Whether this invocation resumes durable work"}},operationErrorAttributes={"pi.error.code":{type:"string",cardinality:"low",description:"Stable operation error code"},"pi.error.type":{type:"string",cardinality:"low",description:"Low-cardinality operation error class"}},HARNESS_TELEMETRY_SCHEMA={version:1,spans:{"pi.harness.run":{description:"One admitted in-process run invocation",parents:{kind:"root_or_external"},startAttributes:{...operationStartAttributes,"pi.operation.kind":{type:"string",required:!0,values:["run"],description:"Run operation kind"}},endAttributes:{"pi.operation.outcome":{type:"string",values:["completed","aborted","failed","suspended"],description:"Run invocation outcome"},...operationErrorAttributes},status:{default:"ok",errorWhen:"The run fails or throws"}},"pi.harness.compaction":{description:"One admitted in-process manual compaction invocation",parents:{kind:"root_or_external"},startAttributes:{...operationStartAttributes,"pi.operation.kind":{type:"string",required:!0,values:["compaction"],description:"Compaction operation kind"}},endAttributes:{"pi.operation.outcome":{type:"string",values:["completed","declined","aborted","failed"],description:"Compaction invocation outcome"},...operationErrorAttributes},status:{default:"ok",errorWhen:"The compaction fails or throws"}},"pi.harness.navigation":{description:"One admitted in-process navigation invocation",parents:{kind:"root_or_external"},startAttributes:{...operationStartAttributes,"pi.operation.kind":{type:"string",required:!0,values:["navigation"],description:"Navigation operation kind"}},endAttributes:{"pi.operation.outcome":{type:"string",values:["completed","declined","aborted","failed"],description:"Navigation invocation outcome"},...operationErrorAttributes},status:{default:"ok",errorWhen:"The navigation fails or throws"}},"pi.harness.checkpoint":{description:"One run checkpoint",parents:{kind:"spans",spans:["pi.harness.run"]},startAttributes:{"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.checkpoint.kind":{type:"string",required:!0,values:["normal","abort_reconcile"],description:"Checkpoint purpose"}},endAttributes:{},status:{default:"ok",errorWhen:"Checkpoint work throws"}},"pi.harness.turn":{description:"One assistant response and its tool batch",parents:{kind:"spans",spans:["pi.harness.run"]},startAttributes:{"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.turn.id":{type:"string",required:!0,cardinality:"high",description:"Invocation-local turn id"}},endAttributes:{},status:{default:"ok",errorWhen:"Turn work throws"}},"pi.harness.step":{description:"One durable retry attempt",parents:{kind:"spans",spans:["pi.harness.turn","pi.harness.checkpoint","pi.harness.compaction","pi.harness.navigation"]},startAttributes:{"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.step.kind":{type:"string",required:!0,values:["assistant","compaction","branch_summary"],description:"Retryable step kind"},"pi.step.attempt":{type:"number",required:!0,description:"One-based durable attempt number"},"pi.compaction.reason":{type:"string",required:!1,values:["manual","threshold","overflow"],description:"Compaction trigger"}},endAttributes:{"pi.step.outcome":{type:"string",values:["succeeded","retry","failed","aborted","deferred","overflow"],description:"Attempt outcome"}},status:{default:"ok",errorWhen:"The attempt retries, fails, or throws"}},"pi.harness.tool":{description:"One raw phase-2 tool execution",parents:{kind:"spans",spans:["pi.harness.turn","pi.harness.run"]},startAttributes:{"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.turn.id":{type:"string",required:!1,cardinality:"high",description:"Invocation-local live turn id"},"pi.tool.name":{type:"string",required:!0,description:"Tool name"},"pi.tool.call_id":{type:"string",required:!0,cardinality:"high",description:"Tool call id"},"pi.tool.replay":{type:"string",required:!0,values:["never","safe"],description:"Declared replay policy"},"pi.tool.recovery":{type:"boolean",required:!0,description:"Whether this is recovery execution"}},endAttributes:{"pi.tool.is_error":{type:"boolean",description:"Whether raw phase-2 execution returned an error"}},status:{default:"ok",errorWhen:"Raw phase-2 execution returns an error"}},"pi.harness.hook":{description:"One registered hook handler invocation",parents:{kind:"any"},startAttributes:{"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!1,cardinality:"high",description:"Durable operation id when accepted"},"pi.hook.name":{type:"string",required:!0,values:HOOK_NAMES,description:"Hook name"},"pi.hook.registration_id":{type:"string",required:!1,description:"Optional hook registration metadata"}},endAttributes:{"pi.hook.outcome":{type:"string",values:["completed","skipped","blocked","failed"],description:"Handler outcome"}},status:{default:"ok",errorWhen:"The handler throws"}},"pi.harness.sleep":{description:"One retry delay",parents:{kind:"spans",spans:["pi.harness.run","pi.harness.compaction","pi.harness.navigation","pi.harness.turn","pi.harness.checkpoint"]},startAttributes:{"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.sleep.delay_ms":{type:"number",required:!0,description:"Requested delay in milliseconds"}},endAttributes:{"pi.sleep.outcome":{type:"string",values:["elapsed","aborted"],description:"Delay outcome"}},status:{default:"ok",errorWhen:"Sleep work throws"}},"pi.harness.event_handler":{description:"One passive event listener invocation",parents:{kind:"any"},startAttributes:{"pi.event.type":{type:"string",required:!0,cardinality:"low",values:EVENT_TYPES,description:"Delivered harness event type"},"pi.lane.name":{type:"string",required:!1,cardinality:"high",description:"Lane name for lane-scoped events"}},endAttributes:{},status:{default:"ok",errorWhen:"The listener throws"}},"pi.session.write":{description:"One committed session transaction",parents:{kind:"any"},startAttributes:{"pi.session.id":{type:"string",required:!0,cardinality:"high",description:"Session id"},"pi.lane.name":{type:"string",required:!1,cardinality:"high",description:"Lane name when supplied by the caller"},"pi.operation.id":{type:"string",required:!1,cardinality:"high",description:"Durable operation id when supplied by the caller"},"pi.session.item_count":{type:"number",required:!0,description:"Number of writes in the transaction"},"pi.session.item_kinds":{type:"string[]",required:!0,elementValues:["entry","usage","value","list"],description:"Distinct write kinds in the transaction"}},endAttributes:{"pi.session.first_seq":{type:"number",description:"First committed sequence in the transaction"},"pi.session.last_seq":{type:"number",description:"Last committed sequence in the transaction"}},status:{default:"ok",errorWhen:"Storage rejects the transaction"}}}},AGENT_TELEMETRY_SCHEMAS=[AI_TELEMETRY_SCHEMA,HARNESS_TELEMETRY_SCHEMA];function startHarnessSpan(name,attributes,callback,context){return getTelemetryContext(context).startSpan({name,attributes},span=>callback(span,withTelemetryContext(span,context)))}var HookRegistry=class{constructor(reportError){this.registrations=new Map,this.reportError=reportError}on(name,handler,options={}){if(this.closedError!==void 0)throw this.closedError;let registrations=this.registrations.get(name)??[],registration={...options.id===void 0?{}:{id:options.id},handler:(event,context)=>handler(event,context)};return registrations.push(registration),this.registrations.set(name,registrations),()=>{let index=registrations.indexOf(registration);index!==-1&&registrations.splice(index,1)}}has(name){return(this.registrations.get(name)?.length??0)!==0}runWithGate(name,event,gate,context){return gate.admit(()=>{let admittedContext=withAbortSignal(gate.signal,context);return admittedContext.abortSignal?.throwIfAborted(),this.runAdmitted(name,event,admittedContext)})}runToolWithGate(name,event,gate,context){return gate.admit(()=>{let admittedContext=withAbortSignal(gate.signal,context);return admittedContext.abortSignal?.throwIfAborted(),name==="before_tool"?this.beforeTool(event,admittedContext):this.afterTool(event,admittedContext)})}close(error){this.closedError??=error}async runAdmitted(name,event,context){if(this.closedError!==void 0)throw this.closedError;return await this.aggregate(name,event,context)}async aggregate(name,event,context){switch(name){case"before_run":return this.beforeRun(event,context);case"before_drive":await this.invokeAllFailClosed(name,event,context);return;case"before_run_end":{let followUp;return await this.invokeAll(name,event,value2=>{let result=value2;result?.followUp!==void 0&&(followUp=result.followUp)},context),followUp===void 0?void 0:{followUp}}case"transform_context":return this.transformContext(event,context);case"before_request":return this.beforeRequest(event,context);case"before_payload":return this.beforePayload(event,context);case"after_response":return this.afterResponse(event,context);case"before_tool":return this.beforeTool(event,context);case"after_tool":return this.afterTool(event,context);case"before_compaction":return this.firstStructural(name,event,"compaction",context);case"before_navigation":return this.firstStructural(name,event,"summary",context)}}async beforeRun(event,context){let prompt=event.prompt,injected=[];for(let registration of this.registrationsFor("before_run"))try{let result=await registration.handler({...event,prompt},context);result?.messages!==void 0&&(injected=[...injected,...result.messages],prompt=[...prompt,...result.messages])}catch(error){await this.reportError(error instanceof Error?error:new Error(String(error)),"before_run",event.lane,context)}return injected.length===0?void 0:{messages:injected}}async beforeTool(event,context){let args=event.args,block;for(let registration of this.registrationsFor("before_tool"))try{let result=await this.invokeToolRegistration("before_tool",registration,{...event,args},context);if(result?.args!==void 0&&(args=result.args),result?.block!==void 0){block=result.block;break}}catch(error){let normalized=error instanceof Error?error:new Error(String(error));await this.reportError(normalized,"before_tool",event.lane,context),block={reason:normalized.message};break}return{...args===event.args?{}:{args},...block===void 0?{}:{block}}}async transformContext(event,context){let messages=event.messages,systemPrompt=event.systemPrompt;for(let registration of this.registrationsFor("transform_context"))try{let result=await registration.handler({...event,messages,systemPrompt},context);result?.messages!==void 0&&(messages=result.messages),result?.systemPrompt!==void 0&&(systemPrompt=result.systemPrompt)}catch(error){await this.reportError(error instanceof Error?error:new Error(String(error)),"transform_context",event.lane,context)}return{messages,systemPrompt}}async beforeRequest(event,context){let streamOptions=event.streamOptions,changed=!1;for(let registration of this.registrationsFor("before_request"))try{let result=await registration.handler({...event,streamOptions},context);result?.streamOptions!==void 0&&(streamOptions=applyStreamOptionsPatch(streamOptions,result.streamOptions),changed=!0)}catch(error){await this.reportError(error instanceof Error?error:new Error(String(error)),"before_request",event.lane,context)}return changed?{streamOptions:createStreamOptionsPatch(event.streamOptions,streamOptions)}:void 0}async beforePayload(event,context){let payload=event.payload;for(let registration of this.registrationsFor("before_payload"))try{let result=await registration.handler({...event,payload},context);result?.payload!==void 0&&(payload=result.payload)}catch(error){await this.reportError(error instanceof Error?error:new Error(String(error)),"before_payload",event.lane,context)}return{payload}}async afterResponse(event,context){let message=event.message;for(let registration of this.registrationsFor("after_response"))try{let result=await registration.handler({...event,message},context);result?.message!==void 0&&(message=result.message)}catch(error){await this.reportError(error instanceof Error?error:new Error(String(error)),"after_response",event.lane,context)}return{message}}async afterTool(event,context){let current={content:event.content,details:event.details,isError:event.isError,usage:event.usage},aggregate={};for(let registration of this.registrationsFor("after_tool"))try{let result=await this.invokeToolRegistration("after_tool",registration,{...event,...current},context);if(result===void 0)continue;result.content!==void 0&&(aggregate.content=result.content),result.details!==void 0&&(aggregate.details=result.details),result.isError!==void 0&&(aggregate.isError=result.isError),result.usage!==void 0&&(aggregate.usage=result.usage),result.terminate!==void 0&&(aggregate.terminate=result.terminate),current={content:result.content===void 0?current.content:result.content,details:result.details===void 0?current.details:result.details,isError:result.isError===void 0?current.isError:result.isError,usage:result.usage===void 0?current.usage:result.usage}}catch(error){await this.reportError(error instanceof Error?error:new Error(String(error)),"after_tool",event.lane,context)}return Object.keys(aggregate).length===0?void 0:aggregate}async firstStructural(name,event,resultField,context){for(let registration of this.registrationsFor(name))try{let value2=await registration.handler(event,context);if(value2==null||typeof value2!="object")continue;let result=value2;if(result.decline===!0&&result[resultField]!==void 0){await this.reportError(new Error(`${name} hook cannot return both decline and ${resultField}`),name,event.lane,context);continue}if(result.decline===!0||result[resultField]!==void 0)return value2}catch(error){await this.reportError(error instanceof Error?error:new Error(String(error)),name,event.lane,context)}}invokeToolRegistration(name,registration,event,context){return startHarnessSpan("pi.harness.hook",{"pi.lane.name":event.lane,"pi.operation.id":event.runId,"pi.hook.name":name,...registration.id===void 0?{}:{"pi.hook.registration_id":registration.id}},async(span,spanContext)=>{try{let result=await registration.handler(event,spanContext),blocked=name==="before_tool"&&result!==null&&typeof result=="object"&&"block"in result&&result.block!==void 0;return span.setAttributes({"pi.hook.outcome":blocked?"blocked":"completed"}),result}catch(error){throw span.setAttributes({"pi.hook.outcome":"failed"}),span.setStatus({status:"error"}),error}},context)}registrationsFor(name){return[...this.registrations.get(name)??[]]}async invokeAllFailClosed(name,event,context){for(let registration of this.registrationsFor(name))try{await registration.handler(event,context)}catch(error){let normalized=error instanceof Error?error:new Error(String(error));throw await this.reportError(normalized,name,event.lane,context),normalized}}async invokeAll(name,event,apply,context){for(let registration of this.registrationsFor(name))try{apply(await registration.handler(event,context))}catch(error){await this.reportError(error instanceof Error?error:new Error(String(error)),name,event.lane,context)}}};function applyStreamOptionsPatch(base,patch){let next={...base};for(let key of["transport","timeoutMs","maxRetries","maxRetryDelayMs","cacheRetention","deferred"]){if(!(key in patch))continue;let value2=patch[key];value2===void 0?delete next[key]:Object.assign(next,{[key]:value2})}if("headers"in patch)if(patch.headers===void 0)delete next.headers;else{let headers={...next.headers};for(let[key,value2]of Object.entries(patch.headers))value2===void 0?delete headers[key]:headers[key]=value2;next.headers=headers}if("metadata"in patch)if(patch.metadata===void 0)delete next.metadata;else{let metadata={...next.metadata};for(let[key,value2]of Object.entries(patch.metadata))value2===void 0?delete metadata[key]:metadata[key]=value2;next.metadata=metadata}return next}function createStreamOptionsPatch(base,value2){let patch={};for(let key of["transport","timeoutMs","maxRetries","maxRetryDelayMs","cacheRetention","deferred"])base[key]!==value2[key]&&Object.assign(patch,{[key]:value2[key]});if(base.headers!==value2.headers)if(value2.headers===void 0)patch.headers=void 0;else{let headers={};for(let key of Object.keys(base.headers??{}))key in value2.headers||(headers[key]=void 0);for(let[key,header]of Object.entries(value2.headers))base.headers?.[key]!==header&&(headers[key]=header);base.headers===void 0&&Object.keys(headers).length===0?patch.headers={}:Object.keys(headers).length!==0&&(patch.headers=headers)}if(base.metadata!==value2.metadata)if(value2.metadata===void 0)patch.metadata=void 0;else{let metadata={};for(let key of Object.keys(base.metadata??{}))key in value2.metadata||(metadata[key]=void 0);for(let[key,metadataValue]of Object.entries(value2.metadata))base.metadata?.[key]!==metadataValue&&(metadata[key]=metadataValue);base.metadata===void 0&&Object.keys(metadata).length===0?patch.metadata={}:Object.keys(metadata).length!==0&&(patch.metadata=metadata)}return patch}function insertEntry(entry){return{kind:"entry",entry}}function insertUsage(row){return{kind:"usage",row}}function commitWrite(write,seq,timestamp){switch(write.kind){case"entry":return{kind:"entry",...write.entry,seq,timestamp};case"usage":return{kind:"usage",...write.row,seq};case"value":return write.op==="set"?{kind:"value",op:"set",seq,namespace:write.namespace,key:write.key,value:write.value}:{kind:"value",op:"delete",seq,namespace:write.namespace,key:write.key};case"list":return write.op==="append"?{kind:"list",op:"append",seq,namespace:write.namespace,key:write.key,value:write.value}:{kind:"list",op:"delete",seq,namespace:write.namespace,key:write.key}}}function materializeCommittedEntry(entry,seq,timestamp){return{...entry,seq,timestamp}}function prepareStorageCommit(writes,firstSeq,timestamp){let committedWrites=writes.map((write,index)=>commitWrite(write,firstSeq+index,timestamp));return{writes:committedWrites,result:{firstSeq,seqs:committedWrites.map(write=>write.seq),timestamp}}}function validateCommittedWrites(writes,firstSeq,state){let previousSeq=firstSeq-1,transactionIds=new Set,transactionEntryIds=new Set;for(let write of writes){if(write.seq<=previousSeq)throw new Error(`Non-monotonic storage sequence: ${write.seq}`);if(previousSeq=write.seq,!(write.kind!=="entry"&&write.kind!=="usage")){if(state.hasEntryOrUsageId(write.id)||transactionIds.has(write.id))throw new Error(`Duplicate entry or usage id: ${write.id}`);if(write.kind==="entry"&&write.parentId!==null&&!state.hasEntryId(write.parentId)&&!transactionEntryIds.has(write.parentId))throw new Error(`Missing parent entry: ${write.parentId}`);transactionIds.add(write.id),write.kind==="entry"&&transactionEntryIds.add(write.id)}}}var MutationLine=class{constructor(){this.tail=Promise.resolve()}run(operation){if(this.sealedError!==void 0)return Promise.reject(this.sealedError);let result=this.tail.then(()=>{if(this.sealedError!==void 0)throw this.sealedError;return operation()});return this.tail=result.then(()=>{},()=>{}),result}seal(error){return this.sealedError??=error,this.tail}};function validateAddress(namespace,key){if(namespace.length===0)throw new TypeError("Value namespace must not be empty");if(namespace.includes("\0"))throw new TypeError("Value namespace must not contain \\u0000");if(key.includes("\0"))throw new TypeError("Value key must not contain \\u0000")}function value(namespace,key=""){return validateAddress(namespace,key),Object.freeze({namespace,key,kind:"value"})}function list(namespace,key=""){return validateAddress(namespace,key),Object.freeze({namespace,key,kind:"list"})}function setValue(address,next){return{kind:"value",op:"set",namespace:address.namespace,key:address.key,value:next}}function deleteValue(address){return{kind:"value",op:"delete",namespace:address.namespace,key:address.key}}function appendList(address,element){return{kind:"list",op:"append",namespace:address.namespace,key:address.key,value:element}}function deleteList(address){return{kind:"list",op:"delete",namespace:address.namespace,key:address.key}}function resolveListReadOptions(options={}){let requestedLimit=options.limit??1e3;if(!Number.isSafeInteger(requestedLimit)||requestedLimit<=0)throw new TypeError("List read limit must be a positive safe integer");return{...options.cursor===void 0?{}:{cursor:options.cursor},order:options.order??"asc",limit:Math.min(requestedLimit,1e4)}}var branchTip=branch=>value("pi.branch.tip",branch),branchTipInventoryPrefix=()=>value("pi.branch.tip"),laneConfig=lane=>value("pi.lane.config",lane),laneState=lane=>value("pi.lane.state",lane),operationResult=operationId=>value("pi.result",operationId),operationMeta=operationId=>value("pi.op.meta",operationId),operationState=operationId=>value("pi.op.state",operationId),operationToolArgs=(operationId,stepId,sourceIndex)=>value("pi.op.tool_args",`${operationId}:${stepId}:${sourceIndex}`),operationToolMemo=(operationId,invocationId,name)=>value("pi.op.tool_memo",`${operationId}:${invocationId}:${name}`),operationPreparation=(operationId,taskId)=>value("pi.op.preparation",`${operationId}:${taskId}`),operationToolArgsPrefix=(operationId,stepId)=>value("pi.op.tool_args",stepId===void 0?`${operationId}:`:`${operationId}:${stepId}:`),operationToolMemoPrefix=(operationId,invocationId)=>value("pi.op.tool_memo",invocationId===void 0?`${operationId}:`:`${operationId}:${invocationId}:`),operationPreparationPrefix=operationId=>value("pi.op.preparation",`${operationId}:`),pendingEntry=entryId=>value("pi.pending.entry",entryId),pendingToolOutput=(operationId,invocationId)=>value("pi.pending.tool_output",`${operationId}:${invocationId}`),pendingAssistantFrames=(operationId,responseEntryId)=>list("pi.pending.assistant_frame",`${operationId}:${responseEntryId}`),pendingToolOutputPrefix=operationId=>value("pi.pending.tool_output",`${operationId}:`),sessionName=value("pi.session.name"),entryLabel=entryId=>value("pi.entry.label",entryId);var SessionInvariantError=class extends Error{constructor(message){super(message),this.name="SessionInvariantError"}},SessionInvalidBranchError=class extends Error{constructor(branch,reason){super(`Invalid branch ${JSON.stringify(branch)}: ${reason}`),this.name="SessionInvalidBranchError",this.branch=branch,this.reason=reason}},SessionBranchExistsError=class extends Error{constructor(branch){super(`Branch already exists: ${branch}`),this.name="SessionBranchExistsError",this.branch=branch}},SessionPendingAssistantMessageError=class extends Error{constructor(){super("Cannot persist a pending assistant message"),this.name="SessionPendingAssistantMessageError"}},SessionUnknownTargetError=class extends Error{constructor(targetId){super(`Unknown target: ${targetId}`),this.name="SessionUnknownTargetError",this.targetId=targetId}},StorageBackedSessionMutation=class{constructor(storage,release){this.active=!0,this.storage=storage,this.release=release}commit(writes,context){if(this.assertActive(),this.commitResult!==void 0)return Promise.reject(new Error("SessionMutator commit already attempted"));try{for(let write of writes)if(write.kind==="entry"&&write.entry.type==="message"&&write.entry.message.role==="assistant"&&write.entry.message.stopReason==="pending")throw new SessionPendingAssistantMessageError;this.commitResult=this.storage.commit(writes,context)}catch(error){this.commitResult=Promise.reject(error)}return this.commitResult}end(_context){return this.endPromise!==void 0?this.endPromise:(this.active=!1,this.endPromise=this.settle().finally(this.release),this.endPromise)}getEntries(ids,context){return this.assertActive(),this.storage.getEntries(ids,context)}getStats(context){return this.assertActive(),this.storage.getStats(context)}getValue(address,context){return this.assertActive(),this.storage.getValue(address,context)}scanValues(prefix,context){return this.assertActive(),this.storage.scanValues(prefix,context)}readList(address,options,context){return this.assertActive(),this.storage.readList(address,options,context)}scanBranch(query,context){return this.assertActive(),this.storage.scanBranch(query,context)}settle(){return this.commitResult?.then(()=>{},()=>{})??Promise.resolve()}assertActive(){if(!this.active)throw new Error("SessionMutator cannot be used outside its mutation callback")}},StorageBackedBranch=class{constructor(name,session){this.name=name,this.session=session}getTipId(context){return this.session.getBranchTip(this.name,context)}async findEntries(query,context){query??={};let start=query.start??await this.getTipId(context);return start===null?[]:this.session.scanBranch({...query,start,order:query.order??"newestFirst"},context)}async findEntry(query,context){return query??={},(await this.findEntries({...query,limit:query.limit===void 0?1:Math.min(query.limit,1)},context))[0]}appendMessage(message,context){return this.session.appendToBranch(this.name,{type:"message",message},context)}appendCustomEntry(customType,data,context){return this.session.appendToBranch(this.name,{type:"custom",customType,...data===void 0?{}:{data}},context)}},StorageBackedSession=class{constructor(metadata,storage,options={}){this.branches=new Map,this.closedError=new Error("Session is closed"),this.state="open",this.metadata=metadata,this.idGenerator=options.idGenerator??{next:uuidv7},this.storage=storage,this.mutationLine=options.mutationLine??new MutationLine,this.onClose=options.onClose}async beginMutation(_context){this.assertOpen();let grant,rejectGrant,granted=new Promise((resolve,reject)=>{grant=resolve,rejectGrant=reject}),release,finished=new Promise(resolve=>{release=resolve});return this.mutationLine.run(async()=>{grant(new StorageBackedSessionMutation(this.storage,release)),await finished}).catch(rejectGrant),granted}async mutate(mutation,context){let mutator=await this.beginMutation(context);try{return await mutation(mutator,context)}finally{await mutator.end(context)}}async getEntries(ids,context){return this.assertOpen(),this.storage.getEntries(ids,context)}async getEntry(id,context){return(await this.getEntries([id],context)).get(id)}async getValue(address,context){return this.assertOpen(),this.storage.getValue(address,context)}async scanValues(prefix,context){return this.assertOpen(),this.storage.scanValues(prefix,context)}async readList(address,options,context){return this.assertOpen(),this.storage.readList(address,options,context)}async scanBranch(query,context){return this.assertOpen(),this.storage.scanBranch(query,context)}async getStats(context){return this.assertOpen(),this.storage.getStats(context)}async getName(context){return(await this.getValue(sessionName,context))?.value}async getLabel(targetId,context){return(await this.getValue(entryLabel(targetId),context))?.value}async findEntries(query,context){query??={},this.assertOpen();let order=query.order??"desc";if(query.cursor!==void 0){if(order==="asc"&&query.cursor.seq===Number.MAX_SAFE_INTEGER)return[];if(order==="desc"&&query.cursor.seq<=1)return[]}return this.storage.scanEntries({type:query.type,customType:query.customType,order,limit:query.limit,...query.cursor===void 0?{}:order==="asc"?{fromSeq:query.cursor.seq+1}:{toSeq:query.cursor.seq-1}},context)}async findEntry(query,context){return query??={},(await this.findEntries({...query,limit:query.limit===void 0?1:Math.min(query.limit,1)},context))[0]}async branch(name,context){if(this.assertValidBranchName(name),await this.getValue(branchTip(name),context)!==void 0)return this.getOrCreateBranchObject(name)}async createBranch(name,at,context){return this.assertOpen(),this.assertValidBranchName(name),await this.mutate(async mutator=>{if(await mutator.getValue(branchTip(name),context)!==void 0)throw new SessionBranchExistsError(name);if(at!==null&&!(await mutator.getEntries([at],context)).has(at))throw new SessionUnknownTargetError(at);await mutator.commit([setValue(branchTip(name),at)],context)},context),this.getOrCreateBranchObject(name)}setValue(address,next,context){return this.mutate(async mutator=>{await mutator.commit([setValue(address,next)],context)},context)}deleteValue(address,context){return this.mutate(async mutator=>{await mutator.commit([deleteValue(address)],context)},context)}appendList(address,element,context){return this.mutate(async mutator=>{await mutator.commit([appendList(address,element)],context)},context)}deleteList(address,context){return this.mutate(async mutator=>{await mutator.commit([deleteList(address)],context)},context)}setName(name,context){return name===void 0?this.deleteValue(sessionName,context):this.setValue(sessionName,name,context)}setLabel(targetId,label,context){let address=entryLabel(targetId);return label===void 0?this.deleteValue(address,context):this.setValue(address,label,context)}close(context){return this.closePromise!==void 0?this.closePromise:(this.state="closing",this.closePromise=this.mutationLine.seal(this.closedError).then(()=>this.storage.close(context)).finally(()=>{this.state="closed",this.onClose?.()}),this.closePromise)}async getBranchTip(name,context){let stored=await this.getValue(branchTip(name),context);if(stored===void 0)throw new SessionInvariantError(`Unknown branch: ${name}`);return stored.value}async appendToBranch(name,entry,context){if(this.assertOpen(),entry.type==="message"&&entry.message.role==="assistant"&&entry.message.stopReason==="pending")throw new SessionPendingAssistantMessageError;let id=this.idGenerator.next();return await this.mutate(async mutator=>{let tip=await mutator.getValue(branchTip(name),context);if(tip===void 0)throw new SessionInvariantError(`Unknown branch: ${name}`);await mutator.commit([insertEntry(entry.type==="message"?{id,parentId:tip.value,type:"message",message:entry.message}:{id,parentId:tip.value,type:"custom",customType:entry.customType,...entry.data===void 0?{}:{data:entry.data}}),setValue(branchTip(name),id)],context)},context),id}getOrCreateBranchObject(name){let branch=this.branches.get(name);return branch===void 0&&(branch=new StorageBackedBranch(name,this),this.branches.set(name,branch)),branch}assertValidBranchName(name){if(name.length===0)throw new SessionInvalidBranchError(name,"branch name must not be empty");if(name.includes("\0"))throw new SessionInvalidBranchError(name,"branch name must not contain \\u0000")}assertOpen(){if(this.state!=="open")throw this.closedError}};async function collectEntriesForBranchSummary(branch,session,oldTipId,targetId,context){if(!oldTipId)return{entries:[],commonAncestorId:null};let oldPath=new Set((await branch.findEntries({start:oldTipId},context)).map(entry=>entry.id)),targetPath=await branch.findEntries({start:targetId},context),commonAncestorId=null;for(let entry of targetPath)if(oldPath.has(entry.id)){commonAncestorId=entry.id;break}let entries=[],current=oldTipId;for(;current&&current!==commonAncestorId;){let entry=await session.getEntry(current,context);if(!entry)throw new Error(`Corrupt session: entry ${current} not found`);entries.push(entry),current=entry.parentId}return entries.reverse(),{entries,commonAncestorId}}function getMessageFromEntry2(entry){switch(entry.type){case"message":return entry.message.role==="toolResult"?void 0:entry.message;case"branch_summary":return createBranchSummaryMessage(entry.summary,entry.fromId,entry.timestamp);case"compaction":return createCompactionSummaryMessage(entry.summary,entry.tokensBefore,entry.timestamp);case"custom":return}}function prepareBranchEntries(entries,tokenBudget=0){let messages=[],fileOps=createFileOps(),totalTokens=0;for(let entry of entries)if(!(entry.type!=="branch_summary"||typeof entry.details!="object"||entry.details===null||Array.isArray(entry.details))){if(Array.isArray(entry.details.readFiles))for(let path of entry.details.readFiles)typeof path=="string"&&fileOps.read.add(path);if(Array.isArray(entry.details.modifiedFiles))for(let path of entry.details.modifiedFiles)typeof path=="string"&&fileOps.edited.add(path)}for(let i=entries.length-1;i>=0;i--){let entry=entries[i],message=getMessageFromEntry2(entry);if(!message)continue;extractFileOpsFromMessage(message,fileOps);let tokens=estimateTokens(message);if(tokenBudget>0&&totalTokens+tokens>tokenBudget){(entry.type==="compaction"||entry.type==="branch_summary")&&totalTokens<tokenBudget*.9&&(messages.unshift(message),totalTokens+=tokens);break}messages.unshift(message),totalTokens+=tokens}return{messages,fileOps,totalTokens}}var BRANCH_SUMMARY_PREAMBLE=`The user explored a different conversation branch before returning here.
152
+ Summary of that exploration:
153
+
154
+ `,BRANCH_SUMMARY_PROMPT=`Create a structured summary of this conversation branch for context when returning later.
155
+
156
+ Use this EXACT format:
157
+
158
+ ## Goal
159
+ [What was the user trying to accomplish in this branch?]
160
+
161
+ ## Constraints & Preferences
162
+ - [Any constraints, preferences, or requirements mentioned]
163
+ - [Or "(none)" if none were mentioned]
164
+
165
+ ## Progress
166
+ ### Done
167
+ - [x] [Completed tasks/changes]
168
+
169
+ ### In Progress
170
+ - [ ] [Work that was started but not finished]
171
+
172
+ ### Blocked
173
+ - [Issues preventing progress, if any]
174
+
175
+ ## Key Decisions
176
+ - **[Decision]**: [Brief rationale]
177
+
178
+ ## Next Steps
179
+ 1. [What should happen next to continue this work]
180
+
181
+ Keep each section concise. Preserve exact file paths, function names, and error messages.`;function generateBranchSummary(entries,options,context){let{models,model,customInstructions,replaceInstructions,reserveTokens=16384,retry,callbacks}=options,contextWindow=model.contextWindow||128e3,preparation=prepareBranchEntries(entries,contextWindow-reserveTokens);return generateBranchSummaryWithRequest(preparation,{customInstructions,replaceInstructions},(aiContext,requestOptions,requestContext)=>completeSimpleWithRetries(models,model,aiContext,requestOptions,retry,callbacks,requestContext),context)}async function generateBranchSummaryWithRequest(preparation,options,request,context){let{customInstructions,replaceInstructions}=options,{messages,fileOps}=preparation;if(messages.length===0)return ok({summary:"No content to summarize",readFiles:[],modifiedFiles:[]});let llmMessages=convertToLlm(messages),conversationText=serializeConversation(llmMessages),instructions;replaceInstructions&&customInstructions?instructions=customInstructions:customInstructions?instructions=`${BRANCH_SUMMARY_PROMPT}
182
+
183
+ Additional focus: ${customInstructions}`:instructions=BRANCH_SUMMARY_PROMPT;let summarizationMessages=[{role:"user",content:[{type:"text",text:`<conversation>
184
+ ${conversationText}
185
+ </conversation>
186
+
187
+ ${instructions}`}],timestamp:Date.now()}],response=await request({systemPrompt:SUMMARIZATION_SYSTEM_PROMPT,messages:summarizationMessages},createSummaryRequestOptions({maxTokens:2048},context),context);if(response.stopReason==="aborted")return err(new BranchSummaryError("aborted",response.errorMessage||"Branch summary aborted"));if(response.stopReason==="error")return err(new BranchSummaryError("summarization_failed",`Branch summary failed: ${response.errorMessage||"Unknown error"}`));let summary=contentTextForSummary(response.content);summary=BRANCH_SUMMARY_PREAMBLE+summary;let{readFiles,modifiedFiles}=computeFileLists(fileOps);return summary+=formatFileOperations(readFiles,modifiedFiles),ok({summary:summary||"No summary generated",usage:response.usage,readFiles,modifiedFiles})}function createErrorToolResult2(message){return{content:[{type:"text",text:message}],details:void 0}}function immediateError(toolCall,message,terminate=!1){return{kind:"immediate",toolCall,result:createErrorToolResult2(message),isError:!0,terminate}}function prepareToolCall2(call,tools){let tool=tools.find(candidate=>candidate.name===call.name);if(!tool)return immediateError(call,`Tool ${JSON.stringify(call.name)} is unavailable`);try{let preparedArguments=tool.prepareArguments?tool.prepareArguments(call.arguments):call.arguments,preparedCall=preparedArguments===call.arguments?call:{...call,arguments:preparedArguments},args=validateToolArguments(tool,preparedCall);return{toolCall:call,tool,args}}catch(error){return immediateError(call,error instanceof Error?error.message:String(error))}}function applyBeforeToolDecision(prepared,decision){if(decision?.block)return immediateError(prepared.toolCall,decision.block.reason,decision.block.terminate===!0);if(!decision?.args)return{toolCall:prepared.toolCall,tool:prepared.tool,args:prepared.args};try{let validatedArgs=validateToolArguments(prepared.tool,{...prepared.toolCall,arguments:decision.args});return{toolCall:prepared.toolCall,tool:prepared.tool,args:validatedArgs}}catch(error){return immediateError(prepared.toolCall,error instanceof Error?error.message:String(error))}}function executeToolCall(call,gate,onUpdate,toolContext,invocation,context){let acceptingUpdates=!0;return gate.admit(async()=>{let admittedContext=withAbortSignal(gate.signal,context);admittedContext.abortSignal?.throwIfAborted();try{return{result:await call.tool.execute(call.toolCall.id,call.args,(partial,options)=>{acceptingUpdates&&onUpdate(partial,options)},toolContext,invocation,admittedContext),isError:!1}}catch(error){return{result:createErrorToolResult2(error instanceof Error?error.message:String(error)),isError:!0}}finally{acceptingUpdates=!1}})}function finalizeToolCall(call,executed,patch){let result=patch?{...executed.result,content:patch.content===void 0?executed.result.content:patch.content,details:patch.details===void 0?executed.result.details:patch.details,usage:patch.usage===void 0?executed.result.usage:patch.usage,terminate:patch.terminate===void 0?executed.result.terminate:patch.terminate}:executed.result;return{toolCall:call.toolCall,result,isError:patch?.isError??executed.isError,terminate:result.terminate===!0}}function toolResultFromMessage(message,terminate){return{content:message.content,details:message.details,...message.usage===void 0?{}:{usage:message.usage},...terminate?{terminate:!0}:{}}}function createToolResultMessage2(call){return{role:"toolResult",toolCallId:call.toolCall.id,toolName:call.toolCall.name,content:call.result.content??[],...call.result.details===void 0?{}:{details:call.result.details},...call.result.usage===void 0?{}:{usage:call.result.usage},isError:call.isError,timestamp:Date.now()}}var import_yaml=__toESM(require_dist(),1);async function loadPromptTemplates(env,paths,context){let promptTemplates=[],diagnostics=[];for(let path of Array.isArray(paths)?paths:[paths]){let infoResult=await env.fileInfo(path,context);if(!infoResult.ok){infoResult.error.code!=="not_found"&&diagnostics.push({type:"warning",code:"file_info_failed",message:infoResult.error.message,path});continue}let info=infoResult.value,kind=await resolveKind(env,info,diagnostics,context);if(kind==="directory"){let result=await loadTemplatesFromDir(env,info.path,context);promptTemplates.push(...result.promptTemplates),diagnostics.push(...result.diagnostics)}else if(kind==="file"&&info.name.endsWith(".md")){let result=await loadTemplateFromFile(env,info.path,info.name,context);result.promptTemplate&&promptTemplates.push(result.promptTemplate),diagnostics.push(...result.diagnostics)}}return{promptTemplates,diagnostics}}async function loadSourcedPromptTemplates(env,inputs,mapPromptTemplate,context){let promptTemplates=[],diagnostics=[];for(let input of inputs){let result=await loadPromptTemplates(env,input.path,context);for(let promptTemplate of result.promptTemplates)promptTemplates.push({promptTemplate:mapPromptTemplate?mapPromptTemplate(promptTemplate,input.source,context):promptTemplate,source:input.source});for(let diagnostic of result.diagnostics)diagnostics.push({...diagnostic,source:input.source})}return{promptTemplates,diagnostics}}async function loadTemplatesFromDir(env,dir,context){let promptTemplates=[],diagnostics=[],entriesResult=await env.listDir(dir,context);if(!entriesResult.ok)return diagnostics.push({type:"warning",code:"list_failed",message:entriesResult.error.message,path:dir}),{promptTemplates,diagnostics};let entries=entriesResult.value;for(let entry of entries.sort((a,b)=>a.name.localeCompare(b.name))){if(await resolveKind(env,entry,diagnostics,context)!=="file"||!entry.name.endsWith(".md"))continue;let result=await loadTemplateFromFile(env,entry.path,entry.name,context);result.promptTemplate&&promptTemplates.push(result.promptTemplate),diagnostics.push(...result.diagnostics)}return{promptTemplates,diagnostics}}async function loadTemplateFromFile(env,filePath,fileName,context){let diagnostics=[],rawContent=await env.readTextFile(filePath,context);if(!rawContent.ok)return diagnostics.push({type:"warning",code:"read_failed",message:rawContent.error.message,path:filePath}),{promptTemplate:null,diagnostics};let parsed=parseFrontmatter(rawContent.value);if(!parsed.ok)return diagnostics.push({type:"warning",code:"parse_failed",message:parsed.error.message,path:filePath}),{promptTemplate:null,diagnostics};let{frontmatter,body}=parsed.value,firstLine=body.split(`
188
+ `).find(line=>line.trim()),description=typeof frontmatter.description=="string"?frontmatter.description:"";return!description&&firstLine&&(description=firstLine.slice(0,60),firstLine.length>60&&(description+="...")),{promptTemplate:{name:fileName.replace(/\.md$/i,""),description,content:body},diagnostics}}async function resolveKind(env,info,diagnostics,context){if(info.kind==="file"||info.kind==="directory")return info.kind;let canonicalPath=await env.canonicalPath(info.path,context);if(!canonicalPath.ok){canonicalPath.error.code!=="not_found"&&diagnostics.push({type:"warning",code:"file_info_failed",message:canonicalPath.error.message,path:info.path});return}let target=await env.fileInfo(canonicalPath.value,context);if(!target.ok){target.error.code!=="not_found"&&diagnostics.push({type:"warning",code:"file_info_failed",message:target.error.message,path:info.path});return}return target.value.kind==="file"||target.value.kind==="directory"?target.value.kind:void 0}function parseFrontmatter(content){try{let normalized=content.replace(/\r\n/g,`
189
+ `).replace(/\r/g,`
190
+ `);if(!normalized.startsWith("---"))return{ok:!0,value:{frontmatter:{},body:normalized}};let endIndex=normalized.indexOf(`
191
+ ---`,3);if(endIndex===-1)return{ok:!0,value:{frontmatter:{},body:normalized}};let yamlString=normalized.slice(4,endIndex),body=normalized.slice(endIndex+4).trim();return{ok:!0,value:{frontmatter:(0,import_yaml.parse)(yamlString)??{},body}}}catch(error){return{ok:!1,error:toError(error)}}}function parseCommandArgs(argsString){let args=[],current="",inQuote=null;for(let i=0;i<argsString.length;i++){let char=argsString[i];inQuote?char===inQuote?inQuote=null:current+=char:char==='"'||char==="'"?inQuote=char:char===" "||char===" "?current&&(args.push(current),current=""):current+=char}return current&&args.push(current),args}function substituteArgs(content,args){let result=content;result=result.replace(/\$(\d+)/g,(_,num)=>args[parseInt(num,10)-1]??""),result=result.replace(/\$\{@:(\d+)(?::(\d+))?\}/g,(_,startStr,lengthStr)=>{let start=parseInt(startStr,10)-1;return start<0&&(start=0),lengthStr?args.slice(start,start+parseInt(lengthStr,10)).join(" "):args.slice(start).join(" ")});let allArgs=args.join(" ");return result=result.replace(/\$ARGUMENTS/g,allArgs),result=result.replace(/\$@/g,allArgs),result}function formatPromptTemplateInvocation(template,args=[]){return substituteArgs(template.content,args)}var import_ignore=__toESM(require_ignore(),1),import_yaml2=__toESM(require_dist(),1);var MAX_NAME_LENGTH=64,MAX_DESCRIPTION_LENGTH=1024,IGNORE_FILE_NAMES=[".gitignore",".ignore",".fdignore"];function formatSkillInvocation(skill,additionalInstructions){let skillBlock=`<skill name="${skill.name}" location="${skill.filePath}">
192
+ References are relative to ${dirnameEnvPath(skill.filePath)}.
193
+
194
+ ${skill.content}
195
+ </skill>`;return additionalInstructions?`${skillBlock}
196
+
197
+ ${additionalInstructions}`:skillBlock}async function loadSkills(env,dirs,context){let skills=[],diagnostics=[];for(let dir of Array.isArray(dirs)?dirs:[dirs]){let rootInfoResult=await env.fileInfo(dir,context);if(!rootInfoResult.ok){rootInfoResult.error.code!=="not_found"&&diagnostics.push({type:"warning",code:"file_info_failed",message:rootInfoResult.error.message,path:dir});continue}let rootInfo=rootInfoResult.value;if(await resolveKind2(env,rootInfo,diagnostics,context)!=="directory")continue;let result=await loadSkillsFromDirInternal(env,rootInfo.path,!0,(0,import_ignore.default)(),rootInfo.path,context);skills.push(...result.skills),diagnostics.push(...result.diagnostics)}return{skills,diagnostics}}async function loadSourcedSkills(env,inputs,mapSkill,context){let skills=[],diagnostics=[];for(let input of inputs){let result=await loadSkills(env,input.path,context);for(let skill of result.skills)skills.push({skill:mapSkill?mapSkill(skill,input.source,context):skill,source:input.source});for(let diagnostic of result.diagnostics)diagnostics.push({...diagnostic,source:input.source})}return{skills,diagnostics}}async function loadSkillsFromDirInternal(env,dir,includeRootFiles,ignoreMatcher,rootDir,context){let skills=[],diagnostics=[],dirInfoResult=await env.fileInfo(dir,context);if(!dirInfoResult.ok)return dirInfoResult.error.code!=="not_found"&&diagnostics.push({type:"warning",code:"file_info_failed",message:dirInfoResult.error.message,path:dir}),{skills,diagnostics};let dirInfo=dirInfoResult.value;if(await resolveKind2(env,dirInfo,diagnostics,context)!=="directory")return{skills,diagnostics};await addIgnoreRules(env,ignoreMatcher,dir,rootDir,diagnostics,context);let entriesResult=await env.listDir(dir,context);if(!entriesResult.ok)return diagnostics.push({type:"warning",code:"list_failed",message:entriesResult.error.message,path:dir}),{skills,diagnostics};let entries=entriesResult.value;for(let entry of entries){if(entry.name!=="SKILL.md")continue;let fullPath=entry.path;if(await resolveKind2(env,entry,diagnostics,context)!=="file")continue;let relPath=relativeEnvPath(rootDir,fullPath);if(ignoreMatcher.ignores(relPath))continue;let result=await loadSkillFromFile(env,fullPath,dirInfo.name,context);return result.skill&&skills.push(result.skill),diagnostics.push(...result.diagnostics),{skills,diagnostics}}for(let entry of entries.sort((a,b)=>a.name.localeCompare(b.name))){if(entry.name.startsWith(".")||entry.name==="node_modules")continue;let fullPath=entry.path,kind=await resolveKind2(env,entry,diagnostics,context);if(!kind)continue;let relPath=relativeEnvPath(rootDir,fullPath),ignorePath=kind==="directory"?`${relPath}/`:relPath;if(ignoreMatcher.ignores(ignorePath))continue;if(kind==="directory"){let result2=await loadSkillsFromDirInternal(env,fullPath,!1,ignoreMatcher,rootDir,context);skills.push(...result2.skills),diagnostics.push(...result2.diagnostics);continue}if(kind!=="file"||!includeRootFiles||!entry.name.endsWith(".md"))continue;let result=await loadSkillFromFile(env,fullPath,dirInfo.name,context);result.skill&&skills.push(result.skill),diagnostics.push(...result.diagnostics)}return{skills,diagnostics}}async function addIgnoreRules(env,ig,dir,rootDir,diagnostics,context){let relativeDir=relativeEnvPath(rootDir,dir),prefix=relativeDir?`${relativeDir}/`:"";for(let filename of IGNORE_FILE_NAMES){let ignorePathResult=await env.joinPath([dir,filename],context);if(!ignorePathResult.ok){diagnostics.push({type:"warning",code:"file_info_failed",message:ignorePathResult.error.message,path:dir});continue}let ignorePath=ignorePathResult.value,info=await env.fileInfo(ignorePath,context);if(!info.ok){info.error.code!=="not_found"&&diagnostics.push({type:"warning",code:"file_info_failed",message:info.error.message,path:ignorePath});continue}if(info.value.kind!=="file")continue;let content=await env.readTextFile(ignorePath,context);if(!content.ok){diagnostics.push({type:"warning",code:"read_failed",message:content.error.message,path:ignorePath});continue}let patterns=content.value.split(/\r?\n/).map(line=>prefixIgnorePattern(line,prefix)).filter(line=>!!line);patterns.length>0&&ig.add(patterns)}}function prefixIgnorePattern(line,prefix){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#")&&!trimmed.startsWith("\\#"))return null;let pattern=line,negated=!1;pattern.startsWith("!")?(negated=!0,pattern=pattern.slice(1)):pattern.startsWith("\\!")&&(pattern=pattern.slice(1)),pattern.startsWith("/")&&(pattern=pattern.slice(1));let prefixed=prefix?`${prefix}${pattern}`:pattern;return negated?`!${prefixed}`:prefixed}async function loadSkillFromFile(env,filePath,parentDirName,context){let diagnostics=[],isDeclaredSkill=filePath.replace(/[\\/]+$/,"").split(/[\\/]/).pop()==="SKILL.md",rawContent=await env.readTextFile(filePath,context);if(!rawContent.ok)return diagnostics.push({type:"warning",code:"read_failed",message:rawContent.error.message,path:filePath}),{skill:null,diagnostics};let parsed=parseFrontmatter2(rawContent.value);if(!parsed.ok)return isDeclaredSkill&&diagnostics.push({type:"warning",code:"parse_failed",message:parsed.error.message,path:filePath}),{skill:null,diagnostics};let{frontmatter,body}=parsed.value,description=typeof frontmatter.description=="string"?frontmatter.description:void 0;if(!isDeclaredSkill&&(!description||description.trim()===""))return{skill:null,diagnostics};for(let error of validateDescription(description))diagnostics.push({type:"warning",code:"invalid_metadata",message:error,path:filePath});let name=(typeof frontmatter.name=="string"?frontmatter.name:void 0)||parentDirName;for(let error of validateName(name,parentDirName))diagnostics.push({type:"warning",code:"invalid_metadata",message:error,path:filePath});return!description||description.trim()===""?{skill:null,diagnostics}:{skill:{name,description,content:body,filePath,disableModelInvocation:frontmatter["disable-model-invocation"]===!0},diagnostics}}function validateName(name,parentDirName){let errors=[];return name!==parentDirName&&errors.push(`name "${name}" does not match parent directory "${parentDirName}"`),name.length>MAX_NAME_LENGTH&&errors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`),/^[a-z0-9-]+$/.test(name)||errors.push("name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)"),(name.startsWith("-")||name.endsWith("-"))&&errors.push("name must not start or end with a hyphen"),name.includes("--")&&errors.push("name must not contain consecutive hyphens"),errors}function validateDescription(description){let errors=[];return!description||description.trim()===""?errors.push("description is required"):description.length>MAX_DESCRIPTION_LENGTH&&errors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`),errors}function parseFrontmatter2(content){try{let normalized=content.replace(/\r\n/g,`
198
+ `).replace(/\r/g,`
199
+ `);if(!normalized.startsWith("---"))return{ok:!0,value:{frontmatter:{},body:normalized}};let endIndex=normalized.indexOf(`
200
+ ---`,3);if(endIndex===-1)return{ok:!0,value:{frontmatter:{},body:normalized}};let yamlString=normalized.slice(4,endIndex),body=normalized.slice(endIndex+4).trim();return{ok:!0,value:{frontmatter:(0,import_yaml2.parse)(yamlString)??{},body}}}catch(error){return{ok:!1,error:toError(error)}}}async function resolveKind2(env,info,diagnostics,context){if(info.kind==="file"||info.kind==="directory")return info.kind;let canonicalPath=await env.canonicalPath(info.path,context);if(!canonicalPath.ok){canonicalPath.error.code!=="not_found"&&diagnostics.push({type:"warning",code:"file_info_failed",message:canonicalPath.error.message,path:info.path});return}let target=await env.fileInfo(canonicalPath.value,context);if(!target.ok){target.error.code!=="not_found"&&diagnostics.push({type:"warning",code:"file_info_failed",message:target.error.message,path:info.path});return}return target.value.kind==="file"||target.value.kind==="directory"?target.value.kind:void 0}function dirnameEnvPath(path){let normalized=path.replace(/[\\/]+$/,""),separatorIndex=Math.max(normalized.lastIndexOf("/"),normalized.lastIndexOf("\\"));return separatorIndex===2&&normalized[1]===":"?normalized.slice(0,3):separatorIndex<=0?"/":normalized.slice(0,separatorIndex)}function relativeEnvPath(root,path){let normalizedRoot=root.replace(/\\/g,"/").replace(/\/+$/,""),normalizedPath=path.replace(/\\/g,"/").replace(/\/+$/,"");return normalizedPath===normalizedRoot?"":normalizedPath.startsWith(`${normalizedRoot}/`)?normalizedPath.slice(normalizedRoot.length+1):normalizedPath.replace(/^\/+/,"")}function operationScopeOf(state){return{control:state.control,settings:state.settings,latestAssistantEntryId:state.latestAssistantEntryId}}function chainEntries(parentId,items){return items.map(item=>{let entry={...item,parentId};return parentId=item.id,entry})}function entryLifecycleEvents(entry,lane,runId){let operation=runId===void 0?{}:{runId};return entry.type==="message"?[{type:"message_start",lane,...operation,message:entry.message},{type:"message_end",lane,...operation,message:entry.message,entryId:entry.id},{type:"entry_added",lane,entry}]:[{type:"entry_added",lane,entry}]}function committedEntryEvents(entries,commit,lane,runId,firstWriteIndex=0){return entries.flatMap((entry,index)=>entryLifecycleEvents(materializeCommittedEntry(entry,commit.seqs[firstWriteIndex+index],commit.timestamp),lane,runId))}function readBoundedEntries(lane,drive,capability){return lane.continueOperation(capability,async(state,_current,_meta,reader)=>{if(state.tipId===null)throw new SessionInvariantError("Run operation has no Branch tip");return{kind:"return",result:(await reader.scanBranch({start:state.tipId,stopAtType:"compaction",order:"newestFirst"},drive.context)).reverse()}},drive.context)}async function readBoundedContext(lane,drive,capability){let entries=await readBoundedEntries(lane,drive,capability);return entries.kind==="cancel_requested"?entries:{kind:"result",value:await buildSessionContext(entries.value,{entryProjectors:lane.readConfig().entryProjectors},drive.context)}}function readLaneQueues(reader,inbox,context){return Promise.all(inbox.map(async item=>{let stored=await reader.getValue(pendingEntry(item.entryId),context);if(stored===void 0)throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is missing its payload`);if(stored.value.type==="message")return{entryId:item.entryId,kind:item.kind,type:"message",message:stored.value.payload};if(item.kind!=="write")throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is not a message`);return{entryId:item.entryId,kind:"write",type:"custom",customType:stored.value.customType,...stored.value.payload===void 0?{}:{data:stored.value.payload}}}))}async function operationCleanupWrites(reader,operationId,state,context){let[toolArguments,toolMemos,preparations,toolOutputs]=await Promise.all([reader.scanValues(operationToolArgsPrefix(operationId),context),reader.scanValues(operationToolMemoPrefix(operationId),context),reader.scanValues(operationPreparationPrefix(operationId),context),reader.scanValues(pendingToolOutputPrefix(operationId),context)]),pendingIds=new Set;if(state.at==="tools")for(let call of state.batch.calls)call.status==="outcome_ready"&&pendingIds.add(call.resultEntryId);let frameDelete;return(state.at==="assistant.effect_pending"||state.at==="deferred.effect_pending")&&(frameDelete=deleteList(pendingAssistantFrames(operationId,state.responseEntryId))),[deleteValue(operationMeta(operationId)),deleteValue(operationState(operationId)),...toolArguments.map(({address})=>deleteValue(address)),...toolMemos.map(({address})=>deleteValue(address)),...preparations.map(({address})=>deleteValue(address)),...toolOutputs.map(({address})=>deleteValue(address)),...frameDelete===void 0?[]:[frameDelete],...[...pendingIds].map(id=>deleteValue(pendingEntry(id)))]}function operationResultRecord(meta,status,tipId,error){if(status==="failed"!=(error!==void 0))throw new SessionInvariantError("Only a failed operation result may carry an error");return{operationId:meta.operationId,kind:meta.intent.kind,status,...error===void 0?{}:{error},fromTipId:meta.sourceTipId,tipId,startedAt:meta.startedAt,endedAt:Date.now()}}function normalizedRetryPolicy(lane){let retry=lane.readConfig().retryPolicy;return{maxAttempts:retry.enabled?retry.maxRetries+1:1,baseDelayMs:retry.baseDelayMs,maxAgentDelayMs:retry.maxAgentDelayMs??DEFAULT_MAX_AGENT_RETRY_DELAY_MS}}function assistantReadyAtBoundary(lane,state,scope,triggerEntryId,overflowRecoveryUsed){let config=lane.readConfig();return{...scope,at:"assistant.ready",generationContext:{stepId:lane.session.idGenerator.next(),triggerEntryId,configuration:state.configuration,streamOptions:config.streamOptions,retryPolicy:normalizedRetryPolicy(lane),overflowRecoveryUsed},nextAttempt:1}}async function planBoundaryInbox(lane,drive,state,scope,reader,tipId,followUpWhenNoTrigger){let steer=state.inbox.filter(item=>item.kind==="steer"),selectedSteer=scope.settings.steeringMode==="all"?steer:steer.slice(0,1),selected=state.inbox.filter(item=>item.kind==="write"||selectedSteer.some(candidate=>candidate.entryId===item.entryId)),load=items=>Promise.all(items.map(async item=>{let stored=await reader.getValue(pendingEntry(item.entryId),drive.context);if(stored===void 0)throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is missing its payload`);if(item.kind!=="write"&&stored.value.type!=="message")throw new SessionInvariantError(`Queued ${item.kind} entry ${item.entryId} is not a message`);return{item,pending:stored.value}})),pending=await load(selected),projects=value2=>value2.type==="message"||lane.readConfig().entryProjectors[value2.customType]!==void 0;if(followUpWhenNoTrigger&&!pending.some(({pending:value2})=>projects(value2))){let followUp=state.inbox.filter(item=>item.kind==="followUp"),selectedFollowUp=scope.settings.followUpMode==="all"?followUp:followUp.slice(0,1);selected=[...selected,...selectedFollowUp].sort((a,b)=>state.inbox.indexOf(a)-state.inbox.indexOf(b)),pending=await load(selected)}let parentId=tipId,triggerEntryId,entries=pending.map(({item,pending:value2})=>{let entry=value2.type==="message"?{id:item.entryId,parentId,type:"message",message:value2.payload}:{id:item.entryId,parentId,type:"custom",customType:value2.customType,...value2.payload===void 0?{}:{data:value2.payload}};return parentId=item.entryId,projects(value2)&&(triggerEntryId=item.entryId),entry}),selectedIds=new Set(selected.map(item=>item.entryId)),inbox=state.inbox.filter(item=>!selectedIds.has(item.entryId)),queues=selected.length===0?void 0:await readLaneQueues(reader,inbox,drive.context);return{entries,writes:[...entries.map(entry=>insertEntry(entry)),...selected.map(item=>deleteValue(pendingEntry(item.entryId))),...entries.length===0?[]:[setValue(branchTip(lane.name),parentId)]],tipId:parentId,inbox,...triggerEntryId===void 0?{}:{triggerEntryId},...queues===void 0?{}:{queues}}}function boundaryPlacementEvents(placement,commit,firstWriteIndex,lane,runId){return[...committedEntryEvents(placement.entries,commit,lane,runId,firstWriteIndex),...placement.queues===void 0?[]:[{type:"queue_update",lane,queues:placement.queues}]]}async function finishRunBoundary(lane,drive,capability,continuation,plannedEntryIds,pendingEvents=[]){let context=await readBoundedContext(lane,drive,capability);if(context.kind==="cancel_requested")return{kind:"continue"};let hook=await lane.hooks.runWithGate("before_run_end",{lane:lane.name,runId:drive.operationId,messages:context.value},drive.gate,drive.context),followUp=hook?.followUp===void 0?void 0:{id:lane.session.idGenerator.next(),message:{role:"user",content:hook.followUp,timestamp:Date.now()}},result=await lane.continueOperation(capability,async(state,current,meta,reader)=>{let placement=await planBoundaryInbox(lane,drive,state,current,reader,state.tipId,!0);if(placement.triggerEntryId!==void 0)return{kind:"commit",writes:placement.writes,operationState:assistantReadyAtBoundary(lane,state,current,placement.triggerEntryId,!1),lane:{tipId:placement.tipId,inbox:placement.inbox},materialize:()=>({kind:"continue"}),events:commit=>[...pendingEvents,...boundaryPlacementEvents(placement,commit,0,lane.name,drive.operationId)]};if(placement.entries.length===plannedEntryIds.length&&placement.entries.every((entry,index)=>entry.id===plannedEntryIds[index])&&followUp!==void 0){let entry={id:followUp.id,parentId:placement.tipId,type:"message",message:followUp.message},entryWriteIndex=placement.writes.length;return{kind:"commit",writes:[...placement.writes,insertEntry(entry),setValue(branchTip(lane.name),followUp.id)],operationState:assistantReadyAtBoundary(lane,state,current,followUp.id,!1),lane:{tipId:followUp.id,inbox:placement.inbox},materialize:()=>({kind:"continue"}),events:commit=>[...pendingEvents,...boundaryPlacementEvents(placement,commit,0,lane.name,drive.operationId),...entryLifecycleEvents({...entry,seq:commit.seqs[entryWriteIndex],timestamp:commit.timestamp},lane.name,drive.operationId)]}}if(placement.tipId===null)throw new SessionInvariantError("Completed run has no tip");if(continuation.includeFinalAssistant&&current.latestAssistantEntryId===null)throw new SessionInvariantError("Completed run is missing its final assistant");let record=operationResultRecord(meta,"completed",placement.tipId),cleanup=await operationCleanupWrites(reader,drive.operationId,current,drive.context);return{kind:"finish",writes:[...placement.writes,...cleanup],record,lane:{tipId:placement.tipId,inbox:placement.inbox},materialize:()=>({kind:"settled",outcome:record}),events:commit=>[...pendingEvents,...boundaryPlacementEvents(placement,commit,0,lane.name,drive.operationId),{type:"run_end",lane:lane.name,runId:drive.operationId,status:"completed",fromTipId:meta.sourceTipId,tipId:placement.tipId,endedAt:record.endedAt}]}},drive.context);return result.kind==="cancel_requested"?{kind:"continue"}:result.value}function retryNotBefore(policy,attempt,now=Date.now()){let sum=now+retryDelayMs(policy,attempt);return Number.isSafeInteger(sum)?sum:Number.MAX_SAFE_INTEGER}function waitUntil(notBefore,signal){return new Promise((resolve,reject)=>{let timer,cleanup=()=>{timer!==void 0&&clearTimeout(timer),signal.removeEventListener("abort",onAbort)},onAbort=()=>{cleanup(),reject(signal.reason)},check=()=>{let remaining=notBefore-Date.now();if(remaining<=0){cleanup(),resolve();return}timer=setTimeout(check,Math.min(remaining,2147483647))};signal.addEventListener("abort",onAbort,{once:!0}),signal.aborted?onAbort():check()})}var StructuralCancelled=class extends Error{constructor(){super("Structural generation was cancelled"),this.name="StructuralCancelled"}};function durableFileOperations(fileOps){return{read:[...fileOps.read],written:[...fileOps.written],edited:[...fileOps.edited]}}function durableCompactionPreparation(preparation){return{kind:"compaction",messagesToSummarize:preparation.messagesToSummarize,turnPrefixMessages:preparation.turnPrefixMessages,retainedTail:preparation.retainedTail,isSplitTurn:preparation.isSplitTurn,tokensBefore:preparation.tokensBefore,...preparation.previousSummary===void 0?{}:{previousSummary:preparation.previousSummary},fileOps:durableFileOperations(preparation.fileOps),settings:preparation.settings}}function durableBranchPreparation(preparation){return{kind:"branch_summary",messages:preparation.messages,fileOps:durableFileOperations(preparation.fileOps),totalTokens:preparation.totalTokens}}function fileOperations(fileOps){return{read:new Set(fileOps.read),written:new Set(fileOps.written),edited:new Set(fileOps.edited)}}function compactionPreparation(preparation){return{messagesToSummarize:preparation.messagesToSummarize,turnPrefixMessages:preparation.turnPrefixMessages,retainedTail:preparation.retainedTail,isSplitTurn:preparation.isSplitTurn,tokensBefore:preparation.tokensBefore,...preparation.previousSummary===void 0?{}:{previousSummary:preparation.previousSummary},fileOps:fileOperations(preparation.fileOps),settings:preparation.settings}}function branchPreparation(preparation){return{messages:preparation.messages,fileOps:fileOperations(preparation.fileOps),totalTokens:preparation.totalTokens}}function summaryKind(task){return task.boundary.kind==="commit_navigation"?"branch_summary":"compaction"}function compactionReason(task){if(task.reason!==void 0)return task.reason;if(task.boundary.kind==="finish")return"manual";throw new SessionInvariantError(`In-run compaction task ${task.taskId} is missing its reason`)}function navigationBoundary(task){if(task.boundary.kind!=="commit_navigation")throw new SessionInvariantError(`Summary task ${task.taskId} is not a navigation`);return task.boundary}async function readStructuralPreparation(lane,drive,deciding){return lane.continueOperation(deciding,async(_state,current,_meta,reader)=>{let expected=summaryKind(current.task),stored=await reader.getValue(operationPreparation(drive.operationId,current.task.taskId),drive.context);if(stored?.value.kind!==expected)throw new SessionInvariantError(`Structural task ${current.task.taskId} is missing its ${expected} preparation`);if(current.task.boundary.kind==="commit_navigation"){let targetId=current.task.boundary.targetId;if(!(await reader.getEntries([targetId],drive.context)).has(targetId))throw new SessionInvariantError(`Navigation target ${targetId} is missing`)}return{kind:"return",result:stored.value.kind==="compaction"?compactionPreparation(stored.value):branchPreparation(stored.value)}},drive.context)}function summaryContext(lane,resultEntryId,configuration){return{resultEntryId,configuration,streamOptions:{...lane.readConfig().streamOptions,deferred:!1},retryPolicy:normalizedRetryPolicy(lane)}}function usageEvent(row,writeIndex,commit,lane){return{type:"usage",lane,row:{...row,seq:commit.seqs[writeIndex]},totals:commit.stats.usage}}function operationError(code,message,details){return{code,message,...details===void 0?{}:{details}}}async function publishStructuralOutcome(lane,drive,capability,outcome){let hookUsageId=(outcome.kind==="compaction"||outcome.kind==="branch_summary")&&outcome.fromHook&&outcome.result.usage!==void 0?lane.session.idGenerator.next():void 0,published=await lane.continueOperation(capability,async(state,current,meta,reader)=>{let expected=summaryKind(current.task),terminalCompactionEndedAt;if((outcome.kind==="compaction"||outcome.kind==="branch_summary")&&outcome.kind!==expected)throw new SessionInvariantError(`Structural ${outcome.kind} result does not match ${expected} task ${current.task.taskId}`);let writes=[],baseEvents=[],terminalTipId=state.tipId;if(hookUsageId!==void 0&&(outcome.kind==="compaction"||outcome.kind==="branch_summary")){let usage=outcome.result.usage;if(usage===void 0)throw new SessionInvariantError("Hook usage id exists without structural usage");let row={id:hookUsageId,usage,adjustment:!1},writeIndex=writes.length;writes.push(insertUsage(row)),baseEvents.push(commit=>[usageEvent(row,writeIndex,commit,lane.name)])}if(outcome.kind==="compaction"){let entry={id:outcome.resultEntryId,parentId:state.tipId,type:"compaction",summary:outcome.result.summary,retainedTail:outcome.result.retainedTail,tokensBefore:outcome.result.tokensBefore,...outcome.result.details===void 0?{}:{details:outcome.result.details},...outcome.result.usage===void 0?{}:{usage:outcome.result.usage},fromHook:outcome.fromHook},entryWriteIndex=writes.length;writes.push(insertEntry(entry),setValue(branchTip(lane.name),outcome.resultEntryId)),terminalTipId=outcome.resultEntryId,baseEvents.push(commit=>committedEntryEvents([entry],commit,lane.name,drive.operationId,entryWriteIndex))}else if(outcome.kind==="branch_summary"){let boundary2=navigationBoundary(current.task),entry={id:outcome.resultEntryId,parentId:boundary2.targetId,type:"branch_summary",fromId:meta.sourceTipId,summary:outcome.result.summary,details:{readFiles:outcome.result.readFiles,modifiedFiles:outcome.result.modifiedFiles},...outcome.result.usage===void 0?{}:{usage:outcome.result.usage},fromHook:outcome.fromHook};writes.push(setValue(branchTip(lane.name),boundary2.targetId));let entryWriteIndex=writes.length;writes.push(insertEntry(entry),setValue(branchTip(lane.name),outcome.resultEntryId)),boundary2.label!==void 0&&writes.push(setValue(entryLabel(boundary2.targetId),boundary2.label)),terminalTipId=outcome.resultEntryId,baseEvents.push(commit=>committedEntryEvents([entry],commit,lane.name,drive.operationId,entryWriteIndex))}let attempt=current.at==="summary.ready"?current.nextAttempt:current.at==="summary.effect_pending"?current.attempt:void 0;attempt!==void 0&&attempt>1&&baseEvents.push(()=>[{type:"retry_end",lane:lane.name,runId:drive.operationId,step:current.task.taskId,attempt,success:outcome.kind==="compaction"||outcome.kind==="branch_summary",...outcome.kind==="failed"?{finalError:outcome.error.message}:{}}]),outcome.kind==="compaction"&&baseEvents.push(commit=>[{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:compactionReason(current.task),status:"completed",entryId:outcome.resultEntryId,endedAt:terminalCompactionEndedAt??commit.timestamp}]);let events=commit=>baseEvents.flatMap(materialize2=>materialize2(commit));switch(current.task.boundary.kind){case"resume_checkpoint":{if(outcome.kind==="branch_summary")throw new SessionInvariantError("Run compaction boundary received a branch summary");if(outcome.kind==="compaction"||outcome.kind==="declined"&&current.task.reason==="threshold"){if(terminalTipId===null)throw new SessionInvariantError("Run compaction has no Branch tip");let continuation=current.task.boundary.resumeAfter.continuation,placement=await planBoundaryInbox(lane,drive,state,current,reader,terminalTipId,outcome.kind==="declined"&&continuation.kind==="may_finish");if(outcome.kind==="declined"&&placement.triggerEntryId===void 0&&continuation.kind==="may_finish")return{kind:"return",result:{kind:"finish_pending",entryIds:placement.entries.map(entry=>entry.id)}};let placementWriteIndex=writes.length;writes.push(...placement.writes);let operationState2;if(placement.triggerEntryId!==void 0||continuation.kind==="need_assistant"){let overflowRecoveryUsed=placement.triggerEntryId===void 0&&continuation.kind==="need_assistant"?continuation.overflowRecoveryUsed:!1;operationState2=assistantReadyAtBoundary(lane,state,current,placement.triggerEntryId??current.task.boundary.resumeAfter.triggerEntryId,overflowRecoveryUsed)}else operationState2={...operationScopeOf(current),at:"checkpoint",...current.task.boundary.resumeAfter};return{kind:"commit",writes,operationState:operationState2,lane:{tipId:placement.tipId,inbox:placement.inbox},materialize:()=>({kind:"continue"}),events:commit=>[...outcome.kind==="compaction"?events(commit):[{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:"threshold",status:"declined",endedAt:commit.timestamp}],...boundaryPlacementEvents(placement,commit,placementWriteIndex,lane.name,drive.operationId)]}}if(state.tipId===null)throw new SessionInvariantError("Failed run has no Branch tip");let error=outcome.kind==="declined"?operationError("compaction_declined","Overflow compaction was declined"):outcome.error,cleanup=await operationCleanupWrites(reader,drive.operationId,current,drive.context),record=operationResultRecord(meta,"failed",state.tipId,error),compactionEnd=outcome.kind==="declined"?{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:compactionReason(current.task),status:"declined",endedAt:record.endedAt}:{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:compactionReason(current.task),status:"failed",error:outcome.error,endedAt:record.endedAt};return{kind:"finish",writes:[...writes,...cleanup],record,materialize:()=>({kind:"settled",outcome:record}),events:commit=>[...events(commit),compactionEnd,{type:"run_end",lane:lane.name,runId:drive.operationId,status:"failed",error,fromTipId:meta.sourceTipId,tipId:state.tipId,endedAt:record.endedAt}]}}case"finish":{if(outcome.kind==="branch_summary")throw new SessionInvariantError("Compaction finish boundary received a branch summary");if(outcome.kind!=="compaction"&&state.tipId===null)throw new SessionInvariantError("Standalone compaction has no Branch tip");let error=outcome.kind==="failed"?outcome.error:void 0,status=outcome.kind==="declined"?"declined":outcome.kind==="failed"?"failed":"completed",cleanup=await operationCleanupWrites(reader,drive.operationId,current,drive.context),record=operationResultRecord(meta,status,terminalTipId,error);terminalCompactionEndedAt=record.endedAt;let compactionEnd=outcome.kind==="compaction"?void 0:outcome.kind==="declined"?{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:"manual",status:"declined",endedAt:record.endedAt}:{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:"manual",status:"failed",error:outcome.error,endedAt:record.endedAt};return{kind:"finish",writes:[...writes,...cleanup],record,...outcome.kind==="compaction"?{lane:{tipId:terminalTipId}}:{},materialize:()=>({kind:"settled",outcome:record}),events:commit=>[...events(commit),...compactionEnd===void 0?[]:[compactionEnd]]}}case"commit_navigation":{if(outcome.kind==="compaction")throw new SessionInvariantError("Navigation boundary received a compaction result");let error=outcome.kind==="failed"?outcome.error:void 0,status=outcome.kind==="declined"?"declined":outcome.kind==="failed"?"failed":"completed",cleanup=await operationCleanupWrites(reader,drive.operationId,current,drive.context),record=operationResultRecord(meta,status,terminalTipId,error),navigationEnd=outcome.kind==="branch_summary"?{type:"navigation_end",lane:lane.name,runId:drive.operationId,status:"completed",fromTipId:meta.sourceTipId,tipId:terminalTipId,endedAt:record.endedAt}:outcome.kind==="declined"?{type:"navigation_end",lane:lane.name,runId:drive.operationId,status:"declined",fromTipId:meta.sourceTipId,tipId:terminalTipId,endedAt:record.endedAt}:{type:"navigation_end",lane:lane.name,runId:drive.operationId,status:"failed",error:outcome.error,fromTipId:meta.sourceTipId,tipId:terminalTipId,endedAt:record.endedAt};return{kind:"finish",writes:[...writes,...cleanup],record,...outcome.kind==="branch_summary"?{lane:{tipId:terminalTipId}}:{},materialize:()=>({kind:"settled",outcome:record}),events:commit=>[...events(commit),navigationEnd]}}}},drive.context);if(published.kind==="cancel_requested")return{kind:"continue"};if(published.value.kind!=="finish_pending")return published.value;let boundary=capability.task.boundary;if(boundary.kind!=="resume_checkpoint"||boundary.resumeAfter.continuation.kind!=="may_finish")throw new SessionInvariantError("Structural finish mediation requires a resumable finish boundary");return finishRunBoundary(lane,drive,capability,boundary.resumeAfter.continuation,published.value.entryIds,[{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:"threshold",status:"declined",endedAt:Date.now()}])}async function publishStructuralReady(lane,drive,deciding){let resultEntryId=lane.session.idGenerator.next(),published=await lane.continueOperation(deciding,(state,current)=>{let operationState2={...operationScopeOf(current),at:"summary.ready",task:current.task,summaryContext:summaryContext(lane,resultEntryId,state.configuration),nextAttempt:1};return{kind:"commit",writes:[],operationState:operationState2,materialize:()=>({kind:"continue"})}},drive.context);return published.kind==="cancel_requested"?{kind:"continue"}:published.value}async function runStructuralDecision(lane,drive,deciding){let preparation=await readStructuralPreparation(lane,drive,deciding);if(preparation.kind==="cancel_requested")return{kind:"continue"};if(deciding.task.boundary.kind==="commit_navigation"){if(!("messages"in preparation.value))throw new SessionInvariantError("Navigation task has invalid durable preparation");let hook2=await lane.hooks.runWithGate("before_navigation",{lane:lane.name,runId:drive.operationId,targetId:deciding.task.boundary.targetId,preparation:preparation.value,...deciding.task.customInstructions===void 0?{}:{customInstructions:deciding.task.customInstructions}},drive.gate,drive.context);return hook2?.decline===!0?publishStructuralOutcome(lane,drive,deciding,{kind:"declined"}):hook2?.summary!==void 0?publishStructuralOutcome(lane,drive,deciding,{kind:"branch_summary",resultEntryId:lane.session.idGenerator.next(),result:hook2.summary,fromHook:!0}):publishStructuralReady(lane,drive,deciding)}if(!("messagesToSummarize"in preparation.value))throw new SessionInvariantError("Compaction task has invalid durable preparation");let hook=await lane.hooks.runWithGate("before_compaction",{lane:lane.name,runId:drive.operationId,reason:compactionReason(deciding.task),preparation:preparation.value,...deciding.task.customInstructions===void 0?{}:{customInstructions:deciding.task.customInstructions}},drive.gate,drive.context);return hook?.decline===!0?publishStructuralOutcome(lane,drive,deciding,{kind:"declined"}):hook?.compaction!==void 0?publishStructuralOutcome(lane,drive,deciding,{kind:"compaction",resultEntryId:lane.session.idGenerator.next(),result:hook.compaction,fromHook:!0}):publishStructuralReady(lane,drive,deciding)}function effectPendingFromReady(ready){return{...operationScopeOf(ready),at:"summary.effect_pending",task:ready.task,summaryContext:ready.summaryContext,attempt:ready.nextAttempt,usageIds:[]}}function retryWaitFromEffect(effect,errorMessage2){return{...operationScopeOf(effect),at:"summary.retry_wait",task:effect.task,summaryContext:effect.summaryContext,nextAttempt:effect.attempt+1,notBefore:retryNotBefore(effect.summaryContext.retryPolicy,effect.attempt),errorMessage:errorMessage2}}function readyFromRetryWait(retry){return{...operationScopeOf(retry),at:"summary.ready",task:retry.task,summaryContext:retry.summaryContext,nextAttempt:retry.nextAttempt}}async function publishAttemptIntent(lane,drive,ready){return lane.continueOperation(ready,(_state,current)=>{let effectPending=effectPendingFromReady(current);return{kind:"commit",writes:[],operationState:effectPending,materialize:()=>effectPending}},drive.context)}async function publishNestedRequestIntent(lane,drive,effect,index,usageId){return lane.continueOperation(effect,(_state,current)=>{let next={...current,request:{index,usageId}};return{kind:"commit",writes:[],operationState:next,materialize:()=>next}},drive.context)}async function publishNestedRequestOutcome(lane,drive,effect,usageId,response){await lane.settleOperation(effect,(_state,current)=>{let next={...current,usageIds:[...current.usageIds,usageId]};delete next.request;let row={id:usageId,usage:response.usage,adjustment:!1};return{kind:"commit",writes:[insertUsage(row)],operationState:next,materialize:()=>{},events:commit=>[usageEvent(row,0,commit,lane.name)]}},drive.context)}function requestStreamOptions(options,streamOptions,context,onPayload){return{...options,transport:streamOptions.transport,timeoutMs:streamOptions.timeoutMs,maxRetries:streamOptions.maxRetries,maxRetryDelayMs:streamOptions.maxRetryDelayMs,headers:streamOptions.headers,metadata:streamOptions.metadata,cacheRetention:"none",deferred:!1,signal:context.abortSignal,telemetryContext:getTelemetryContext(context),onPayload}}async function performStructuralAttempt(lane,drive,effect,model,preparation){let requestIndex=0,lastResponse,request=async(aiContext,options,requestContext)=>{let baseOptions={...effect.summaryContext.streamOptions,deferred:!1},beforeRequest=await lane.hooks.runWithGate("before_request",{lane:lane.name,runId:drive.operationId,model,step:summaryKind(effect.task),attempt:effect.attempt,streamOptions:baseOptions},drive.gate,requestContext).catch(async error=>{throw error instanceof AbortRequested?(await error.cancellation,new StructuralCancelled):error}),streamOptions={...beforeRequest?.streamOptions===void 0?baseOptions:applyStreamOptionsPatch(baseOptions,beforeRequest.streamOptions),deferred:!1},usageId=lane.session.idGenerator.next(),intent=await publishNestedRequestIntent(lane,drive,effect,requestIndex,usageId);if(requestIndex+=1,intent.kind==="cancel_requested")throw new StructuralCancelled;let admittedContext=withAbortSignal(drive.gate.signal,requestContext),response;try{response=await drive.gate.admit(()=>lane.models.completeSimple(model,aiContext,requestStreamOptions(options,streamOptions,admittedContext,async(payload,requestModel)=>(await lane.hooks.runWithGate("before_payload",{lane:lane.name,runId:drive.operationId,model:requestModel,payload},drive.gate,admittedContext))?.payload)))}catch(error){throw error instanceof AbortRequested?(await error.cancellation,new StructuralCancelled):error}return lastResponse=response,await publishNestedRequestOutcome(lane,drive,intent.value,usageId,response),response};try{if(summaryKind(effect.task)==="compaction"){if(!("messagesToSummarize"in preparation))throw new SessionInvariantError("Compaction summary has invalid durable preparation");let result2=await compactWithRequest(preparation,{model,customInstructions:effect.task.customInstructions,thinkingLevel:effect.summaryContext.configuration.thinkingLevel},request,drive.context);return result2.ok?{kind:"compaction",result:result2.value,retryable:lastResponse!==void 0&&isRetryableAssistantError(lastResponse)}:{kind:"error",error:operationError(result2.error.code,result2.error.message),retryable:lastResponse!==void 0&&isRetryableAssistantError(lastResponse)}}if(!("messages"in preparation))throw new SessionInvariantError("Branch summary has invalid durable preparation");let result=await generateBranchSummaryWithRequest(preparation,{customInstructions:effect.task.customInstructions},request,drive.context);return result.ok?{kind:"branch_summary",result:result.value,retryable:lastResponse!==void 0&&isRetryableAssistantError(lastResponse)}:{kind:"error",error:operationError(result.error.code,result.error.message),retryable:lastResponse!==void 0&&isRetryableAssistantError(lastResponse)}}catch(error){if(error instanceof StructuralCancelled)return{kind:"cancel_requested"};throw error}}async function readAttemptPreparation(lane,drive,ready){return lane.continueOperation(ready,async(_state,current,_meta,reader)=>{let expected=summaryKind(current.task),stored=await reader.getValue(operationPreparation(drive.operationId,current.task.taskId),drive.context);if(stored===void 0||stored.value.kind!==expected)throw new SessionInvariantError(`Structural task ${current.task.taskId} has invalid durable preparation`);return{kind:"return",result:stored.value.kind==="compaction"?compactionPreparation(stored.value):branchPreparation(stored.value)}},drive.context)}async function publishAttemptResult(lane,drive,effect,result){if(result.kind==="cancel_requested")return{kind:"continue"};if(result.kind==="compaction")return publishStructuralOutcome(lane,drive,effect,{kind:"compaction",resultEntryId:effect.summaryContext.resultEntryId,result:result.result,fromHook:!1});if(result.kind==="branch_summary")return publishStructuralOutcome(lane,drive,effect,{kind:"branch_summary",resultEntryId:effect.summaryContext.resultEntryId,result:result.result,fromHook:!1});if(result.error.code==="aborted"&&lane.state.operation.state.control.status==="running")throw new SessionInvariantError("Structural provider response is aborted while durable control is running");if(result.retryable&&effect.attempt<effect.summaryContext.retryPolicy.maxAttempts){let retryWait=retryWaitFromEffect(effect,result.error.message),published=await lane.continueOperation(effect,()=>({kind:"commit",writes:[],operationState:retryWait,materialize:()=>({kind:"continue"}),events:()=>[{type:"retry_scheduled",lane:lane.name,runId:drive.operationId,step:effect.task.taskId,attempt:retryWait.nextAttempt,maxAttempts:effect.summaryContext.retryPolicy.maxAttempts,delayMs:retryDelayMs(effect.summaryContext.retryPolicy,effect.attempt),notBefore:retryWait.notBefore,errorMessage:result.error.message}]}),drive.context);return published.kind==="cancel_requested"?{kind:"continue"}:published.value}return publishStructuralOutcome(lane,drive,effect,{kind:"failed",error:result.error})}async function runStructuralGeneration(lane,drive,ready){let preparation=await readAttemptPreparation(lane,drive,ready);if(preparation.kind==="cancel_requested")return{kind:"continue"};let identity=ready.summaryContext.configuration.model,model=lane.models.getModel(identity.provider,identity.modelId);if(model===void 0)return publishStructuralOutcome(lane,drive,ready,{kind:"failed",error:operationError("model_unavailable","The configured model is unavailable in this process",identity)});let intent=await publishAttemptIntent(lane,drive,ready);if(intent.kind==="cancel_requested")return{kind:"continue"};let result=await performStructuralAttempt(lane,drive,intent.value,model,preparation.value);return publishAttemptResult(lane,drive,intent.value,result)}async function runStructuralRetryWait(lane,drive,retry){if(Date.now()<retry.notBefore){if(!drive.waitForRetry)return{kind:"waiting",outcome:{kind:"waiting",operationId:drive.operationId,reason:"retry",notBefore:retry.notBefore}};await drive.gate.admit(()=>waitUntil(retry.notBefore,drive.gate.signal))}let published=await lane.continueOperation(retry,(_state,current)=>{let ready=readyFromRetryWait(current);return{kind:"commit",writes:[],operationState:ready,materialize:()=>({kind:"continue"}),events:()=>[{type:"retry_start",lane:lane.name,runId:drive.operationId,step:current.task.taskId,attempt:current.nextAttempt}]}},drive.context);return published.kind==="cancel_requested"?{kind:"continue"}:published.value}async function recoverStructuralGeneration(lane,drive,effect){let error=operationError("structural_interrupted","Structural summary attempt was interrupted and its external outcome is unknown");if(effect.attempt>=effect.summaryContext.retryPolicy.maxAttempts)return publishStructuralOutcome(lane,drive,effect,{kind:"failed",error});let retryWait=retryWaitFromEffect(effect,error.message),published=await lane.continueOperation(effect,()=>({kind:"commit",writes:[],operationState:retryWait,materialize:()=>({kind:"continue"}),events:()=>[{type:"retry_scheduled",lane:lane.name,runId:drive.operationId,step:effect.task.taskId,attempt:retryWait.nextAttempt,maxAttempts:effect.summaryContext.retryPolicy.maxAttempts,delayMs:retryDelayMs(effect.summaryContext.retryPolicy,effect.attempt),notBefore:retryWait.notBefore,errorMessage:error.message,recovery:!0}]}),drive.context);return published.kind==="cancel_requested"?{kind:"continue"}:published.value}function summarizesHistory(preparation){return preparation.messagesToSummarize.length>0||preparation.turnPrefixMessages.length>0}async function prepareCompactionThreshold(lane,drive,checkpoint){let settings=checkpoint.settings.compaction,identity=lane.state.configuration.model,model=lane.models.getModel(identity.provider,identity.modelId);if(!settings.enabled||model===void 0)return{kind:"result",value:void 0};let path=await readBoundedEntries(lane,drive,checkpoint);if(path.kind==="cancel_requested")return path;let triggerIndex=path.value.findIndex(entry=>entry.id===checkpoint.triggerEntryId),newestCompactionIndex=-1;for(let index=path.value.length-1;index>=0;index--)if(path.value[index].type==="compaction"){newestCompactionIndex=index;break}if(newestCompactionIndex>=triggerIndex&&newestCompactionIndex!==-1)return{kind:"result",value:void 0};if(triggerIndex===-1)throw new SessionInvariantError(`Checkpoint trigger ${checkpoint.triggerEntryId} is missing from its Branch`);let prepared=prepareCompaction(path.value,settings);if(!prepared.ok)throw prepared.error;return prepared.value===void 0||!summarizesHistory(prepared.value)||!shouldCompact(prepared.value.tokensBefore,model.contextWindow,settings)?{kind:"result",value:void 0}:{kind:"result",value:{taskId:lane.session.idGenerator.next(),preparation:durableCompactionPreparation(prepared.value)}}}async function prepareOverflowCompaction(lane,drive,generation){if(generation.generationContext.overflowRecoveryUsed||!generation.settings.compaction.enabled)return;let path=await readBoundedEntries(lane,drive,generation);if(path.kind==="cancel_requested")return;let prepared=prepareCompaction(path.value,generation.settings.compaction);if(!prepared.ok)throw prepared.error;if(!(prepared.value===void 0||!summarizesHistory(prepared.value)))return{taskId:lane.session.idGenerator.next(),preparation:durableCompactionPreparation(prepared.value)}}function commitNavigation(lane,drive,navigation){return lane.continueOperation(navigation,async(_state,current,meta,reader)=>{if(current.targetId!==null&&!(await reader.getEntries([current.targetId],drive.context)).has(current.targetId))throw new SessionInvariantError(`Navigation target ${current.targetId} is missing`);if(current.targetId===meta.sourceTipId)throw new SessionInvariantError("Navigation target must differ from its source tip");if(current.targetId===null&&current.label!==void 0)throw new SessionInvariantError("Root navigation cannot set a label");let writes=[setValue(branchTip(lane.name),current.targetId)];current.label!==void 0&&current.targetId!==null&&writes.push(setValue(entryLabel(current.targetId),current.label));let cleanup=await operationCleanupWrites(reader,drive.operationId,current,drive.context),record=operationResultRecord(meta,"completed",current.targetId);return{kind:"finish",writes:[...writes,...cleanup],record,lane:{tipId:current.targetId},materialize:()=>({kind:"settled",outcome:record}),events:()=>[{type:"navigation_end",lane:lane.name,runId:drive.operationId,status:"completed",fromTipId:meta.sourceTipId,tipId:current.targetId,endedAt:record.endedAt}]}},drive.context).then(result=>result.kind==="cancel_requested"?{kind:"continue"}:result.value)}async function startRun(lane,drive,run){let prompt=await lane.continueOperation(run,async(_state,_current,meta,reader)=>{if(meta.intent.kind!=="run")throw new SessionInvariantError("Run operation has non-run intent");let entries=await reader.getEntries(meta.intent.promptEntryIds,drive.context);return{kind:"return",result:meta.intent.promptEntryIds.map(id=>{let entry=entries.get(id);if(entry?.type!=="message")throw new SessionInvariantError(`Run prompt entry ${id} is missing its message`);return entry.message})}},drive.context);if(prompt.kind==="cancel_requested")return{kind:"continue"};let injected=(await lane.hooks.runWithGate("before_run",{lane:lane.name,runId:drive.operationId,prompt:prompt.value,resources:lane.readConfig().resources},drive.gate,drive.context))?.messages??[];for(let message of injected)if(message.role==="assistant"&&message.stopReason==="pending")throw new SessionInvariantError("before_run returned a pending assistant message");let reserved=injected.map(message=>({id:lane.session.idGenerator.next(),message})),result=await lane.continueOperation(run,(state,current)=>{let entries=chainEntries(state.tipId,reserved.map(({id,message})=>({id,type:"message",message}))),triggerEntryId=entries.at(-1)?.id??state.tipId;if(triggerEntryId===null)throw new SessionInvariantError("Run start has no trigger entry");let nextState={...operationScopeOf(current),at:"checkpoint",continuation:{kind:"need_assistant",overflowRecoveryUsed:!1},triggerEntryId};return{kind:"commit",writes:[...entries.map(entry=>insertEntry(entry)),...entries.length===0?[]:[setValue(branchTip(lane.name),triggerEntryId)]],operationState:nextState,lane:{tipId:triggerEntryId},materialize:()=>({kind:"continue"}),events:commit=>committedEntryEvents(entries,commit,lane.name,drive.operationId)}},drive.context);return result.kind==="cancel_requested"?{kind:"continue"}:result.value}async function runCheckpoint(lane,drive,run){let threshold=await prepareCompactionThreshold(lane,drive,run);if(threshold.kind==="cancel_requested")return{kind:"continue"};let planned=await lane.continueOperation(run,async(state,current,_meta,reader)=>{let placement=await planBoundaryInbox(lane,drive,state,current,reader,state.tipId,threshold.value===void 0&&current.continuation.kind==="may_finish");if(placement.triggerEntryId!==void 0)return{kind:"commit",writes:placement.writes,operationState:assistantReadyAtBoundary(lane,state,current,placement.triggerEntryId,!1),lane:{tipId:placement.tipId,inbox:placement.inbox},materialize:()=>({kind:"continue"}),events:commit=>boundaryPlacementEvents(placement,commit,0,lane.name,drive.operationId)};if(threshold.value!==void 0){let structural={...operationScopeOf(current),at:"summary.deciding",task:{taskId:threshold.value.taskId,reason:"threshold",boundary:{kind:"resume_checkpoint",resumeAfter:{continuation:current.continuation,triggerEntryId:current.triggerEntryId}}}};return{kind:"commit",writes:[...placement.writes,setValue(operationPreparation(drive.operationId,threshold.value.taskId),threshold.value.preparation)],operationState:structural,lane:{tipId:placement.tipId,inbox:placement.inbox},materialize:()=>({kind:"continue"}),events:commit=>[...boundaryPlacementEvents(placement,commit,0,lane.name,drive.operationId),{type:"compaction_start",lane:lane.name,runId:drive.operationId,reason:"threshold",startedAt:commit.timestamp}]}}return current.continuation.kind==="need_assistant"?{kind:"commit",writes:placement.writes,operationState:assistantReadyAtBoundary(lane,state,current,current.triggerEntryId,current.continuation.overflowRecoveryUsed),lane:{tipId:placement.tipId,inbox:placement.inbox},materialize:()=>({kind:"continue"}),events:commit=>boundaryPlacementEvents(placement,commit,0,lane.name,drive.operationId)}:{kind:"return",result:{kind:"finish_pending",entryIds:placement.entries.map(entry=>entry.id)}}},drive.context);if(planned.kind==="cancel_requested")return{kind:"continue"};if(planned.value.kind!=="finish_pending")return planned.value;if(run.continuation.kind!=="may_finish")throw new SessionInvariantError("Checkpoint finish mediation requires a finish continuation");return finishRunBoundary(lane,drive,run,run.continuation,planned.value.entryIds)}function createRequestOptions(config,captureMetadata,context){let options=config.streamOptions;return{transport:options.transport,timeoutMs:options.timeoutMs,maxRetries:options.maxRetries,maxRetryDelayMs:options.maxRetryDelayMs,headers:options.headers,metadata:options.metadata,cacheRetention:options.cacheRetention,deferred:options.deferred,...config.thinkingLevel==="off"?{}:{reasoning:config.thinkingLevel},signal:context.abortSignal,telemetryContext:getTelemetryContext(context),onPayload:config.beforePayload===void 0?void 0:(payload,model)=>config.beforePayload?.(payload,model,context),onResponse:response=>{captureMetadata({status:response.status,headers:response.headers})}}}function isUpdateEvent(event){return event.type!=="start"&&event.type!=="done"&&event.type!=="error"}async function consumeAssistantStream(stream,observer,afterResponse,context){let started=!1;for await(let event of stream)if(event.type==="start"){if(started)throw new Error("Assistant message stream emitted more than one start event");started=!0,await observer.start({...event.partial},event,context)}else if(isUpdateEvent(event)){if(!started)throw new Error(`Assistant message stream emitted ${event.type} before start`);await observer.update({...event.partial},event,context)}else if(event.type==="done"&&!started)throw new Error("Assistant message stream emitted done before start");let settled=await stream.result(),finalMessage=settled;if(afterResponse!==void 0)try{finalMessage=await afterResponse(settled,context)}catch(error){if(!(error instanceof AbortRequested))throw error;await error.cancellation}return await observer.end(finalMessage,context),finalMessage}async function streamHarnessAssistant(messages,config,context){let requestContext={messages:messages.slice(),systemPrompt:config.systemPrompt};config.transformContext&&(requestContext=await config.transformContext(requestContext,context));let providerMessages=await config.toProviderMessages(requestContext.messages,context),aiContext={systemPrompt:requestContext.systemPrompt,messages:providerMessages,tools:config.tools},metadata={},stream=await config.request(aiContext,createRequestOptions(config,nextMetadata=>{metadata=nextMetadata},context),context),afterResponse=config.afterResponse;return consumeAssistantStream(stream,config.observer,afterResponse===void 0?void 0:(message,afterContext)=>afterResponse(message,metadata,afterContext),context)}async function readAssistantFrames(reader,operationId,responseEntryId,context){let frames=[],cursor;for(;;){let page=await reader.readList(pendingAssistantFrames(operationId,responseEntryId),{order:"asc",limit:1e3,...cursor===void 0?{}:{cursor}},context);if(frames.push(...page.map(({value:value2})=>value2)),page.length<1e3)return frames;cursor={seq:page[page.length-1].seq}}}function openProgress(lane,drive,commitWrite2,stillOwns){let sealed=!1,latest=Promise.resolve();return{write(item){if(sealed)return;let write=lane.command(projection=>stillOwns(projection)?{kind:"commit",writes:[commitWrite2(item)],next:projection,materialize:()=>{}}:{kind:"return",result:void 0},drive.context).then(()=>{});latest=write,write.catch(()=>{})},seal(){sealed=!0},async drain(){await latest}}}function openFrameProgress(lane,drive,responseEntryId){let address=pendingAssistantFrames(drive.operationId,responseEntryId);return openProgress(lane,drive,frame=>appendList(address,frame),state=>{let run=state.operation?.state;return run===void 0?!1:(run.at==="assistant.effect_pending"||run.at==="deferred.effect_pending")&&run.responseEntryId===responseEntryId})}function openToolProgress(lane,drive,turnId,sourceIndex,invocationId){let address=pendingToolOutput(drive.operationId,invocationId);return openProgress(lane,drive,snapshot=>setValue(address,snapshot),state=>{let operation=state.operation;if(operation?.state.at!=="tools")return!1;let batch=operation.state.batch;return batch.turnId===turnId&&batch.calls.some(call=>call.sourceIndex===sourceIndex&&call.resultEntryId===invocationId&&call.status==="effect_pending")})}function openAssistantResponse(lane,drive,responseEntryId,recovery=!1){let progress=openFrameProgress(lane,drive,responseEntryId),frameEncoder=new AssistantMessageFrameEncoder,eventContext={lane:lane.name,runId:drive.operationId,...recovery?{recovery:!0}:{}},close=async()=>{progress.seal(),await progress.drain()};return{observer:{start(message,event,context){let frame=frameEncoder.encode(event);return frame!==void 0&&progress.write(frame),lane.emitBatch([{type:"message_start",...eventContext,message}],context)},update(message,event,context){let frame=frameEncoder.encode(event);return frame!==void 0&&progress.write(frame),lane.emitBatch([{type:"message_update",...eventContext,message,event,...frame===void 0?{}:{frame}}],context)},end(message,context){return lane.emitBatch([{type:"message_end",...eventContext,message,entryId:responseEntryId}],context)}},async afterResponse(message,metadata,context){return await close(),(await lane.hooks.runWithGate("after_response",{lane:lane.name,runId:drive.operationId,...metadata,message},drive.gate,context))?.message??message},close}}async function publishConfigurationFailure(lane,drive,capability,error){let result=await lane.continueOperation(capability,async(state,current,meta,reader)=>{if(state.tipId===null)throw new SessionInvariantError("Failed run has no Branch tip");let record=operationResultRecord(meta,"failed",state.tipId,error);return{kind:"finish",writes:await operationCleanupWrites(reader,drive.operationId,current,drive.context),record,materialize:()=>({kind:"settled",outcome:record}),events:()=>[{type:"run_end",lane:lane.name,runId:drive.operationId,status:"failed",error,fromTipId:meta.sourceTipId,tipId:state.tipId,endedAt:record.endedAt}]}},drive.context);return result.kind==="cancel_requested"?{kind:"continue"}:result.value}function uuidV7Timestamp(id){let timestamp=Number.parseInt(id.slice(0,8)+id.slice(9,13),16);if(!Number.isSafeInteger(timestamp))throw new SessionInvariantError(`Invalid reserved UUIDv7 ${id}`);return timestamp}function providerError(source,message){return{code:"assistant_error",message:message.errorMessage??`${source==="assistant"?"Assistant":"Deferred"} request ended with ${message.stopReason}`}}function normalizeError(message,errorMessage2){return{...message,stopReason:"error",errorMessage:errorMessage2}}function normalizeAborted(source,message){return{...message,stopReason:"aborted",errorMessage:message.errorMessage??`${source==="assistant"?"Assistant":"Deferred"} request was cancelled`}}function deferredHandleIsValid(message,generation){let handle=message.deferred,identity=generation.generationContext.configuration.model;return message.stopReason==="deferred"&&handle!==void 0&&handle.id.length!==0&&handle.provider===identity.provider&&handle.modelId===identity.modelId&&handle.api===message.api}async function publishResponse(lane,drive,intent,response,options={}){let overflow=intent.at==="assistant.effect_pending"&&(isContextOverflow(response,intent.contextWindow)||isRecoverableLength(response,intent.intendedOutputLimit)),overflowPreparation=overflow&&!intent.generationContext.overflowRecoveryUsed?await prepareOverflowCompaction(lane,drive,intent):void 0;return lane.settleOperation(intent,async(state,current,meta,reader)=>{let source=current.at==="assistant.effect_pending"?"assistant":"deferred",responseEntryId=intent.responseEntryId,configuration=current.at==="assistant.effect_pending"?current.generationContext.configuration:current.configuration,turnId=current.at==="assistant.effect_pending"?current.generationContext.stepId:`${current.stepId}:poll:${current.poll}`,scope={...operationScopeOf(current),latestAssistantEntryId:responseEntryId},committed=response,settled,failure;if(current.control.status==="cancel_requested")committed=normalizeAborted(source,response),settled={...scope,at:"checkpoint",continuation:{kind:"may_finish",includeFinalAssistant:!0},triggerEntryId:responseEntryId};else{if(response.stopReason==="aborted")throw new SessionInvariantError(`${source==="assistant"?"Assistant":"Deferred"} response is aborted while durable control is running`);if(current.at==="assistant.effect_pending"&&overflow)committed=normalizeError(response,response.errorMessage??"Assistant request exceeded the context window"),current.generationContext.overflowRecoveryUsed||overflowPreparation===void 0?failure=providerError(source,committed):settled={...scope,at:"summary.deciding",task:{taskId:overflowPreparation.taskId,reason:"overflow",boundary:{kind:"resume_checkpoint",resumeAfter:{continuation:{kind:"need_assistant",overflowRecoveryUsed:!0},triggerEntryId:current.generationContext.triggerEntryId}}}};else if(response.stopReason==="deferred")current.at==="assistant.effect_pending"?deferredHandleIsValid(response,current)?settled={...scope,at:"deferred.suspended",stepId:current.generationContext.stepId,sourceEntryId:responseEntryId,poll:0,configuration,streamOptions:current.generationContext.streamOptions}:(committed=normalizeError(response,"Provider returned an invalid deferred handle"),failure=providerError(source,committed)):settled={...scope,at:"deferred.suspended",stepId:current.stepId,sourceEntryId:responseEntryId,poll:current.poll,configuration,streamOptions:current.streamOptions};else if(response.stopReason==="error")current.at==="assistant.effect_pending"&&(options.recovery===!0||isRetryableAssistantError(response))&&current.attempt<current.generationContext.retryPolicy.maxAttempts?settled={...scope,at:"assistant.retry_wait",generationContext:current.generationContext,nextAttempt:current.attempt+1,notBefore:retryNotBefore(current.generationContext.retryPolicy,current.attempt),errorMessage:response.errorMessage??"Assistant request failed"}:failure=providerError(source,response);else{let calls=response.content.flatMap((content,sourceIndex)=>content.type==="toolCall"?[{sourceIndex}]:[]);if(calls.length!==0){let timestamp=uuidV7Timestamp(responseEntryId),planned=calls.map(({sourceIndex})=>({status:"planned",sourceIndex,resultEntryId:lane.session.idGenerator.next(timestamp)}));settled={...scope,at:"tools",batch:{assistantEntryId:responseEntryId,configuration,turnId,calls:planned}}}else response.stopReason==="toolUse"?(committed=normalizeError(response,"Provider reported tool use without any tool calls"),failure=providerError(source,committed)):settled={...scope,at:"checkpoint",continuation:{kind:"may_finish",includeFinalAssistant:!0},triggerEntryId:responseEntryId}}}let responseEntry={id:responseEntryId,parentId:state.tipId,type:"message",message:committed},usageRow={id:intent.usageId,usage:committed.usage,entryId:responseEntryId,adjustment:!1};if(settled===void 0&&failure===void 0)throw new SessionInvariantError("Response settlement has no durable disposition");let record=failure===void 0?void 0:operationResultRecord(meta,"failed",responseEntryId,failure),cleanup=record===void 0?[]:await operationCleanupWrites(reader,drive.operationId,current,drive.context),writes=[insertEntry(responseEntry),insertUsage(usageRow),setValue(branchTip(lane.name),responseEntryId),...record===void 0?[deleteList(pendingAssistantFrames(drive.operationId,responseEntryId))]:cleanup,...settled?.at==="summary.deciding"&&overflowPreparation!==void 0?[setValue(operationPreparation(drive.operationId,overflowPreparation.taskId),overflowPreparation.preparation)]:[]],materializeEntry=commit=>({...responseEntry,seq:commit.seqs[0],timestamp:commit.timestamp}),events=commit=>{let entry=materializeEntry(commit),batch=[{type:"entry_added",lane:lane.name,entry,...options},{type:"usage",lane:lane.name,row:{...usageRow,seq:commit.seqs[1]},totals:commit.stats.usage}];if(current.at==="assistant.effect_pending"){if(options.recovery!==!0&&current.attempt>1&&settled?.at!=="assistant.retry_wait"){let success=committed.stopReason!=="error"&&committed.stopReason!=="aborted";batch.push({type:"retry_end",lane:lane.name,runId:drive.operationId,step:turnId,attempt:current.attempt,success,...success?{}:{finalError:committed.errorMessage??`Assistant request ended with ${committed.stopReason}`}})}options.recovery!==!0&&settled?.at==="assistant.retry_wait"&&batch.push({type:"retry_scheduled",lane:lane.name,runId:drive.operationId,step:turnId,attempt:settled.nextAttempt,maxAttempts:settled.generationContext.retryPolicy.maxAttempts,delayMs:retryDelayMs(current.generationContext.retryPolicy,current.attempt),notBefore:settled.notBefore,errorMessage:settled.errorMessage}),options.recovery!==!0&&settled?.at!=="tools"&&settled?.at!=="assistant.retry_wait"&&batch.push({type:"turn_end",lane:lane.name,runId:drive.operationId,turnId,message:committed,toolResults:[]}),settled?.at==="summary.deciding"&&batch.push({type:"compaction_start",lane:lane.name,runId:drive.operationId,reason:"overflow",startedAt:commit.timestamp})}else settled?.at!=="tools"&&batch.push({type:"turn_end",lane:lane.name,runId:drive.operationId,turnId,message:committed,toolResults:[],...options});return(current.at==="deferred.effect_pending"||options.recovery!==!0)&&settled?.at==="deferred.suspended"&&committed.deferred!==void 0&&batch.push({type:"run_suspend",lane:lane.name,runId:drive.operationId,reason:"deferred",deferred:committed.deferred,poll:settled.poll,...current.at==="deferred.effect_pending"?options:{}}),record!==void 0&&failure!==void 0&&batch.push({type:"run_end",lane:lane.name,runId:drive.operationId,status:"failed",error:failure,fromTipId:meta.sourceTipId,tipId:responseEntryId,endedAt:record.endedAt}),batch};if(record!==void 0)return{kind:"finish",writes,record,lane:{tipId:responseEntryId},materialize:()=>({kind:"settled",outcome:record}),events};if(settled===void 0)throw new SessionInvariantError("Response settlement is missing its next state");return{kind:"commit",writes,operationState:settled,lane:{tipId:responseEntryId},materialize:()=>({kind:"continue"}),events}},drive.context)}function configurationError(identity){return{code:"model_unavailable",message:"The configured model is unavailable in this process",details:identity}}async function readDeferredSourceHandle(reader,deferred,context){let source=(await reader.getEntries([deferred.sourceEntryId],context)).get(deferred.sourceEntryId);if(source?.type!=="message"||source.message.role!=="assistant"||source.message.stopReason!=="deferred"||source.message.deferred===void 0)throw new SessionInvariantError(`Deferred source ${deferred.sourceEntryId} is missing its assistant handle`);let handle=source.message.deferred,identity=deferred.configuration.model;if(handle.id.length===0||handle.provider!==identity.provider||handle.modelId!==identity.modelId||handle.api!==source.message.api)throw new SessionInvariantError(`Deferred source ${deferred.sourceEntryId} has an invalid handle`);return handle}async function readSourceHandle(lane,drive,deferred){return lane.continueOperation(deferred,async(_state,_current,_meta,reader)=>({kind:"return",result:await readDeferredSourceHandle(reader,deferred,drive.context)}),drive.context)}async function prepareDeferredPoll(lane,drive,expected){let source=await readSourceHandle(lane,drive,expected);if(source.kind==="cancel_requested")return source;if(drive.deferredPermits===0)return{kind:"waiting",source:source.value};let identity=expected.configuration.model,model=lane.models.getModel(identity.provider,identity.modelId);if(model===void 0)return{kind:"configuration_failure"};let baseOptions={...expected.streamOptions,deferred:!1},poll=expected.at==="deferred.suspended"?expected.poll+1:expected.poll,beforeRequest=await lane.hooks.runWithGate("before_request",{lane:lane.name,runId:drive.operationId,model,step:"deferred",attempt:poll,streamOptions:baseOptions},drive.gate,drive.context);return{kind:"ready",source:source.value,model,poll,streamOptions:{...beforeRequest?.streamOptions===void 0?baseOptions:applyStreamOptionsPatch(baseOptions,beforeRequest.streamOptions),deferred:!1}}}async function publishPollIntent(lane,drive,deferred,prepared,recovery){let at=Date.now(),next={at:"deferred.effect_pending",stepId:deferred.stepId,sourceEntryId:deferred.sourceEntryId,poll:prepared.poll,responseEntryId:lane.session.idGenerator.next(at),usageId:lane.session.idGenerator.next(at),configuration:deferred.configuration,streamOptions:deferred.streamOptions};return lane.continueOperation(deferred,(_state,current)=>{let nextState={...operationScopeOf(current),...next};return{kind:"commit",writes:deferred.at==="deferred.effect_pending"?[deleteList(pendingAssistantFrames(drive.operationId,deferred.responseEntryId))]:[],operationState:nextState,materialize:()=>(drive.deferredPermits--,nextState),events:()=>[{type:"run_resume",lane:lane.name,runId:drive.operationId,...recovery?{recovery:!0}:{}},{type:"turn_start",lane:lane.name,runId:drive.operationId,turnId:`${next.stepId}:poll:${next.poll}`,...recovery?{recovery:!0}:{}}]}},drive.context)}async function performDeferredPoll(lane,drive,prepared,intent,recovery){let response=openAssistantResponse(lane,drive,intent.responseEntryId,recovery),metadata={},admitted=withAbortSignal(drive.gate.signal,drive.context),stream=drive.gate.admit(()=>lane.models.streamDeferred(prepared.model,prepared.source,{wait:0,signal:admitted.abortSignal,telemetryContext:getTelemetryContext(admitted),timeoutMs:prepared.streamOptions.timeoutMs,maxRetries:prepared.streamOptions.maxRetries,maxRetryDelayMs:prepared.streamOptions.maxRetryDelayMs,headers:prepared.streamOptions.headers,onPayload:async(payload,requestModel)=>(await lane.hooks.runWithGate("before_payload",{lane:lane.name,runId:drive.operationId,model:requestModel,payload},drive.gate,drive.context))?.payload,onResponse:response2=>{metadata={status:response2.status,headers:response2.headers}}}));try{return await consumeAssistantStream(stream,response.observer,(message,context)=>response.afterResponse(message,metadata,context),drive.context)}finally{await response.close()}}async function pollDeferred(lane,drive,expected,recovery){let prepared=await prepareDeferredPoll(lane,drive,expected);if(prepared.kind==="cancel_requested")return{kind:"continue"};if(prepared.kind==="waiting")return{kind:"waiting",outcome:{kind:"waiting",operationId:drive.operationId,reason:"deferred",deferred:prepared.source}};if(prepared.kind==="configuration_failure")return publishConfigurationFailure(lane,drive,expected,configurationError(expected.configuration.model));let intent=await publishPollIntent(lane,drive,expected,prepared,recovery);if(intent.kind==="cancel_requested")return{kind:"continue"};let response=await performDeferredPoll(lane,drive,prepared,intent.value,recovery);return publishResponse(lane,drive,intent.value,response,recovery?{recovery:!0}:{})}function runDeferredSuspended(lane,drive,deferred){return pollDeferred(lane,drive,deferred,!1)}function recoverDeferredPoll(lane,drive,deferred){return pollDeferred(lane,drive,deferred,!0)}function runDeferred(lane,drive,deferred){return deferred.at==="deferred.suspended"?runDeferredSuspended(lane,drive,deferred):recoverDeferredPoll(lane,drive,deferred)}function configurationError2(code,details){return{code,message:code==="model_unavailable"?"The configured model is unavailable in this process":"One or more configured tools are unavailable in this process",details}}async function resolveSystemPrompt(lane,context){let config=lane.readConfig();if(config.systemPrompt===void 0)return"";if(typeof config.systemPrompt=="string")return config.systemPrompt;let source=config.toolContext,toolContext=typeof source=="function"?await source(context):source;return config.systemPrompt(toolContext,context)}async function prepareGeneration(lane,drive,generation){let identity=generation.generationContext.configuration.model,model=lane.models.getModel(identity.provider,identity.modelId);if(model===void 0)return{kind:"configuration_failure",error:configurationError2("model_unavailable",identity)};let config=lane.readConfig(),toolsByName=new Map(config.tools.map(tool=>[tool.name,tool])),missingTools=generation.generationContext.configuration.activeToolNames.filter(name=>!toolsByName.has(name));if(missingTools.length!==0)return{kind:"configuration_failure",error:configurationError2("configured_tools_unavailable",{tools:missingTools})};let tools=generation.generationContext.configuration.activeToolNames.map(name=>{let tool=toolsByName.get(name);if(tool===void 0)throw new SessionInvariantError(`Configured tool ${name} disappeared during resolution`);return{name:tool.name,description:tool.description,parameters:tool.parameters,...tool.constrainedSampling===void 0?{}:{constrainedSampling:tool.constrainedSampling}}}),messages=await readBoundedContext(lane,drive,generation);if(messages.kind==="cancel_requested")return messages;let systemPrompt=await resolveSystemPrompt(lane,drive.context),beforeRequest=await lane.hooks.runWithGate("before_request",{lane:lane.name,runId:drive.operationId,model,step:"assistant",attempt:generation.nextAttempt,streamOptions:generation.generationContext.streamOptions},drive.gate,drive.context),streamOptions=beforeRequest?.streamOptions===void 0?generation.generationContext.streamOptions:applyStreamOptionsPatch(generation.generationContext.streamOptions,beforeRequest.streamOptions);return{kind:"ready",model,tools,messages:messages.value,systemPrompt,streamOptions,toProviderMessages:config.toProviderMessages}}async function publishGenerationIntent(lane,drive,ready,prepared){let at=Date.now(),pending={at:"assistant.effect_pending",generationContext:ready.generationContext,attempt:ready.nextAttempt,responseEntryId:lane.session.idGenerator.next(at),usageId:lane.session.idGenerator.next(at),intendedOutputLimit:prepared.model.maxTokens,contextWindow:prepared.model.contextWindow};return lane.continueOperation(ready,(_state,current)=>{let nextState={...operationScopeOf(current),...pending};return{kind:"commit",writes:[],operationState:nextState,materialize:()=>nextState,events:()=>ready.nextAttempt===1?[{type:"turn_start",lane:lane.name,runId:drive.operationId,turnId:ready.generationContext.stepId}]:[]}},drive.context)}async function performGeneration(lane,drive,intent,prepared){let response=openAssistantResponse(lane,drive,intent.responseEntryId);try{return await streamHarnessAssistant(prepared.messages,{model:prepared.model,systemPrompt:prepared.systemPrompt,tools:prepared.tools,thinkingLevel:intent.generationContext.configuration.thinkingLevel,streamOptions:prepared.streamOptions,transformContext:async(requestContext,context)=>{let result=await lane.hooks.runWithGate("transform_context",{lane:lane.name,runId:drive.operationId,...requestContext},drive.gate,context);return{messages:result?.messages??requestContext.messages,systemPrompt:result?.systemPrompt??requestContext.systemPrompt}},toProviderMessages:prepared.toProviderMessages,beforePayload:async(payload,requestModel,context)=>(await lane.hooks.runWithGate("before_payload",{lane:lane.name,runId:drive.operationId,model:requestModel,payload},drive.gate,context))?.payload,afterResponse:response.afterResponse,request:(aiContext,options,context)=>{let admitted=withAbortSignal(drive.gate.signal,context);return drive.gate.admit(()=>lane.models.streamSimple(prepared.model,aiContext,{...options,sessionId:`${lane.session.metadata.id}:${lane.name}`,signal:admitted.abortSignal,telemetryContext:getTelemetryContext(admitted)}))},observer:response.observer},drive.context)}finally{await response.close()}}async function runRetryWait(lane,drive,generation){if(Date.now()<generation.notBefore){if(!drive.waitForRetry)return{kind:"waiting",outcome:{kind:"waiting",operationId:drive.operationId,reason:"retry",notBefore:generation.notBefore}};await drive.gate.admit(()=>waitUntil(generation.notBefore,drive.gate.signal))}let result=await lane.continueOperation(generation,(_state,current)=>{let nextState={...operationScopeOf(current),at:"assistant.ready",generationContext:generation.generationContext,nextAttempt:generation.nextAttempt};return{kind:"commit",writes:[],operationState:nextState,materialize:()=>({kind:"continue"}),events:()=>[{type:"retry_start",lane:lane.name,runId:drive.operationId,step:generation.generationContext.stepId,attempt:generation.nextAttempt}]}},drive.context);return result.kind==="cancel_requested"?{kind:"continue"}:result.value}async function runGeneration(lane,drive,generation){if(generation.at==="assistant.retry_wait")return runRetryWait(lane,drive,generation);let prepared=await prepareGeneration(lane,drive,generation);if(prepared.kind==="configuration_failure")return publishConfigurationFailure(lane,drive,generation,prepared.error);if(prepared.kind==="cancel_requested")return{kind:"continue"};let intent=await publishGenerationIntent(lane,drive,generation,prepared);if(intent.kind==="cancel_requested")return{kind:"continue"};let response=await performGeneration(lane,drive,intent.value,prepared);return publishResponse(lane,drive,intent.value,response)}var ZERO_USAGE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function interruptedAssistantMessage(identity,partial){let warning="Assistant request was interrupted. The preceding content is the latest committed partial; newer live output may be missing and the external outcome is unknown.";return partial===void 0?{role:"assistant",content:[],api:"unknown",provider:identity.provider,model:identity.modelId,usage:ZERO_USAGE,stopReason:"error",errorMessage:warning,timestamp:Date.now()}:{...partial,usage:ZERO_USAGE,stopReason:"error",errorMessage:warning}}async function recoverAssistantGeneration(lane,drive,generation){let frames=await lane.continueOperation(generation,async(_state,_current,_meta,reader)=>({kind:"return",result:await readAssistantFrames(reader,drive.operationId,generation.responseEntryId,drive.context)}),drive.context);if(frames.kind==="cancel_requested")return{kind:"continue"};let message=interruptedAssistantMessage(generation.generationContext.configuration.model,reduceAssistantMessageFrames(frames.value));return await lane.emitBatch([{type:"message_start",lane:lane.name,runId:drive.operationId,message,recovery:!0},{type:"message_end",lane:lane.name,runId:drive.operationId,message,entryId:generation.responseEntryId,recovery:!0}],drive.context),publishResponse(lane,drive,generation,message,{recovery:!0})}async function recoverCancelledAssistantEffect(lane,drive,effect){let frames=await lane.settleOperation(effect,async(_state,_current,_meta,reader)=>({kind:"return",result:await readAssistantFrames(reader,drive.operationId,effect.responseEntryId,drive.context)}),drive.context),identity=effect.at==="assistant.effect_pending"?effect.generationContext.configuration.model:effect.configuration.model,message=interruptedAssistantMessage(identity,reduceAssistantMessageFrames(frames));return await lane.emitBatch([{type:"message_start",lane:lane.name,runId:drive.operationId,message,recovery:!0},{type:"message_end",lane:lane.name,runId:drive.operationId,message,entryId:effect.responseEntryId,recovery:!0}],drive.context),publishResponse(lane,drive,effect,message,{recovery:!0})}async function readToolBatchSource(lane,drive,batch){return lane.command(async(_state,reader)=>{let entry=(await reader.getEntries([batch.assistantEntryId],drive.context)).get(batch.assistantEntryId);if(entry?.type!=="message"||entry.message.role!=="assistant")throw new SessionInvariantError("Tool batch assistant entry is invalid");let calls=new Map;for(let call of batch.calls){let block=entry.message.content[call.sourceIndex];if(block?.type!=="toolCall")throw new SessionInvariantError(`Tool call source index ${call.sourceIndex} does not name a tool-call block`);calls.set(call.sourceIndex,block)}return{kind:"return",result:{assistant:entry.message,calls}}},drive.context)}function isToolResultMessage(value2){return typeof value2=="object"&&value2!==null&&"role"in value2&&value2.role==="toolResult"}function toolCallFor(sources,call){let source=sources.calls.get(call.sourceIndex);if(source===void 0)throw new SessionInvariantError(`Tool call source index ${call.sourceIndex} is invalid`);return source}function withToolBatch(run,batch){return{...operationScopeOf(run),at:"tools",batch}}async function readPlacement(lane,drive,sources){return lane.command(async(state,reader)=>{let operation=state.operation;if(operation?.state.at!=="tools")return{kind:"return",result:void 0};let current=operation.state.batch,first=current.calls.findIndex(call=>call.status!=="completed");if(first===-1)return{kind:"return",result:void 0};let ready=[];for(;first<current.calls.length;){let call=current.calls[first];if(call.status!=="outcome_ready")break;ready.push(call),first+=1}if(ready.length===0)return{kind:"return",result:void 0};let items=[];for(let call of ready){let stored=await reader.getValue(pendingEntry(call.resultEntryId),drive.context);if(stored?.value.type!=="message"||!isToolResultMessage(stored.value.payload))throw new SessionInvariantError(`Tool call ${call.resultEntryId} is missing its staged result`);let source=toolCallFor(sources,call);if(stored.value.payload.toolCallId!==source.id||stored.value.payload.toolName!==source.name)throw new SessionInvariantError(`Tool call ${call.resultEntryId} has a mismatched staged result`);items.push({call,message:stored.value.payload})}let turnResults;if(first===current.calls.length){let placedIds=current.calls.filter(call=>call.status==="completed").map(call=>call.resultEntryId),placed=await reader.getEntries(placedIds,drive.context),staged=new Map(items.map(item=>[item.call.resultEntryId,item.message]));turnResults=current.calls.map(call=>{let message=staged.get(call.resultEntryId)??(()=>{let entry=placed.get(call.resultEntryId);return entry?.type==="message"&&isToolResultMessage(entry.message)?entry.message:void 0})();if(message===void 0)throw new SessionInvariantError(`Completed tool call ${call.resultEntryId} is missing its result entry`);return message})}return{kind:"return",result:{items,...turnResults===void 0?{}:{turnResults}}}},drive.context)}async function commitPlacement(lane,drive,capability,read){let usageIds=read.items.map(item=>item.message.usage===void 0?void 0:lane.session.idGenerator.next());return lane.settleOperation(capability,async(state,run,_meta,reader)=>{let current=run.batch,writes=[],eventEntries=[],eventUsage=[],parentId=state.tipId;for(let[index,item]of read.items.entries()){let entry={id:item.call.resultEntryId,parentId,type:"message",message:item.message,...item.call.terminate?{terminate:!0}:{}};eventEntries.push({entry,seqIndex:writes.length}),writes.push(insertEntry(entry),deleteValue(pendingEntry(item.call.resultEntryId)));let usageId=usageIds[index];if(usageId!==void 0&&item.message.usage!==void 0){let row={id:usageId,usage:item.message.usage,entryId:item.call.resultEntryId,adjustment:!1};eventUsage.push({row,seqIndex:writes.length}),writes.push(insertUsage(row))}parentId=item.call.resultEntryId}let completedCalls=current.calls.map(call=>{let item=read.items.find(candidate=>candidate.call.sourceIndex===call.sourceIndex&&candidate.call.resultEntryId===call.resultEntryId);return item===void 0?call:{status:"completed",sourceIndex:call.sourceIndex,resultEntryId:call.resultEntryId,terminate:item.call.terminate}}),complete=completedCalls.every(call=>call.status==="completed");writes.push(setValue(branchTip(lane.name),parentId));let nextRun;if(complete){let allTerminate=completedCalls.every(call=>call.status==="completed"&&call.terminate);nextRun={...operationScopeOf(run),at:"checkpoint",continuation:allTerminate?{kind:"may_finish",includeFinalAssistant:!1}:{kind:"need_assistant",overflowRecoveryUsed:!1},triggerEntryId:parentId};let args=await reader.scanValues(operationToolArgsPrefix(drive.operationId,capability.batch.turnId),drive.context);writes.push(...args.map(({address})=>deleteValue(address)))}else nextRun=withToolBatch(run,{...current,calls:completedCalls});return{kind:"commit",writes,operationState:nextRun,lane:{tipId:parentId,configuration:state.configuration},materialize:()=>complete,events:commit=>{let events=[];for(let{entry,seqIndex}of eventEntries){events.push({type:"entry_added",lane:lane.name,entry:{...entry,seq:commit.seqs[seqIndex],timestamp:commit.timestamp}});let usage=eventUsage.find(candidate=>candidate.row.entryId===entry.id);usage!==void 0&&events.push({type:"usage",lane:lane.name,row:{...usage.row,seq:commit.seqs[usage.seqIndex]},totals:commit.stats.usage})}return events}}},drive.context)}async function materializeReady(lane,drive,capability,sources,recovery){let read=await readPlacement(lane,drive,sources);if(read===void 0)return;await lane.emitBatch(read.items.flatMap(({call,message})=>[{type:"message_start",lane:lane.name,runId:drive.operationId,message,...recovery?{recovery:!0}:{}},{type:"message_end",lane:lane.name,runId:drive.operationId,message,entryId:call.resultEntryId,...recovery?{recovery:!0}:{}}]),drive.context),await commitPlacement(lane,drive,capability,read)&&read.turnResults!==void 0&&await lane.emitBatch([{type:"turn_end",lane:lane.name,runId:drive.operationId,turnId:capability.batch.turnId,message:sources.assistant,toolResults:read.turnResults,...recovery?{recovery:!0}:{}}],drive.context)}var INTERRUPTION_MARKER="[Tool execution was interrupted. The preceding output is the latest durable progress snapshot; newer live output may be missing, and the external outcome is unknown.]",ToolInvocationEnded=class extends Error{constructor(){super("Tool invocation no longer owns its durable effect"),this.name="ToolInvocationEnded"}};function currentBatch(lane){let operation=lane.state.operation;if(operation?.state.at==="tools")return{run:operation.state,batch:operation.state.batch}}function findCall(batch,sourceIndex,resultEntryId){return batch.calls.find(call=>call.sourceIndex===sourceIndex&&call.resultEntryId===resultEntryId)}function replaceCall(batch,replacement){return{...batch,calls:batch.calls.map(call=>call.sourceIndex===replacement.sourceIndex&&call.resultEntryId===replacement.resultEntryId?replacement:call)}}function validateMemoName(name){if(name.length===0)throw new TypeError("Tool invocation memo name must not be empty");if(name.includes(":"))throw new TypeError("Tool invocation memo name must not contain ':'")}function invocationCapability(lane,drive,batch,call){let active=!0,ownsEffect=state=>{let operation=state.operation;return operation?.state.at!=="tools"?!1:findCall(operation.state.batch,call.sourceIndex,call.resultEntryId)?.status==="effect_pending"},ended=()=>new ToolInvocationEnded;return{invocation:{invocationId:call.resultEntryId,operationId:drive.operationId,turnId:batch.turnId,getMemo(name){return validateMemoName(name),active?lane.command(async(state,reader)=>ownsEffect(state)?{kind:"return",result:(await reader.getValue(operationToolMemo(drive.operationId,call.resultEntryId,name),drive.context))?.value}:{kind:"reject",error:ended()},drive.context):Promise.reject(ended())},setMemo(name,value2){return validateMemoName(name),active?lane.command(state=>{if(!ownsEffect(state))return{kind:"reject",error:ended()};let address=operationToolMemo(drive.operationId,call.resultEntryId,name);return{kind:"commit",writes:[value2===void 0?deleteValue(address):setValue(address,value2)],next:state,materialize:()=>{}}},drive.context):Promise.reject(ended())}},expire(){active=!1}}}function syntheticMessage(toolCall,content,options={}){return{role:"toolResult",toolCallId:toolCall.id,toolName:toolCall.name,content,...options.details===void 0?{}:{details:options.details},...options.usage===void 0?{}:{usage:options.usage},isError:!0,timestamp:Date.now()}}function abortedOutcome(toolCall){return{toolCall,message:syntheticMessage(toolCall,[{type:"text",text:"Tool execution was cancelled before completion."}]),terminate:!1}}function interruptedOutcome(toolCall,checkpoint){return{toolCall,message:syntheticMessage(toolCall,[...checkpoint?.content??[],{type:"text",text:INTERRUPTION_MARKER}],checkpoint===void 0?{}:{details:checkpoint.details,usage:checkpoint.usage}),terminate:!1}}function truncatedOutcome(toolCall){return{toolCall,message:syntheticMessage(toolCall,[{type:"text",text:`Tool call ${JSON.stringify(toolCall.name)} was not executed because the assistant response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`}]),terminate:!1}}function outcomeFromFinalizedCall(finalized){return{toolCall:finalized.toolCall,message:createToolResultMessage2(finalized),terminate:finalized.terminate}}async function publishToolIntent(lane,drive,run,planned,toolCall,args,replay,recovery){return lane.continueOperation(run,(_state,run2)=>{let effectPending={status:"effect_pending",sourceIndex:planned.sourceIndex,resultEntryId:planned.resultEntryId,replay};return{kind:"commit",writes:[setValue(operationToolArgs(drive.operationId,run2.batch.turnId,planned.sourceIndex),args)],operationState:withToolBatch(run2,replaceCall(run2.batch,effectPending)),materialize:()=>effectPending,events:()=>[{type:"tool_start",lane:lane.name,runId:drive.operationId,turnId:run2.batch.turnId,toolCallId:toolCall.id,toolName:toolCall.name,args,...recovery?{recovery:!0}:{}}]}},drive.context)}async function publishToolOutcome(lane,drive,capability,call,finalized,recovery){await lane.settleOperation(capability,async(_state,run,_meta,reader)=>{let{toolCall}=finalized,memos=await reader.scanValues(operationToolMemoPrefix(drive.operationId,call.resultEntryId),drive.context),durableTerminate=run.control.status==="running"&&finalized.terminate,outcome={status:"outcome_ready",sourceIndex:call.sourceIndex,resultEntryId:call.resultEntryId,terminate:durableTerminate};return{kind:"commit",writes:[setValue(pendingEntry(call.resultEntryId),{type:"message",payload:finalized.message}),deleteValue(pendingToolOutput(drive.operationId,call.resultEntryId)),...memos.map(({address})=>deleteValue(address))],operationState:withToolBatch(run,replaceCall(run.batch,outcome)),materialize:()=>{},events:()=>[...call.status==="planned"?[{type:"tool_start",lane:lane.name,runId:drive.operationId,turnId:run.batch.turnId,toolCallId:toolCall.id,toolName:toolCall.name,args:toolCall.arguments,...recovery?{recovery:!0}:{}}]:[],{type:"tool_end",lane:lane.name,runId:drive.operationId,turnId:run.batch.turnId,toolCallId:toolCall.id,toolName:toolCall.name,result:toolResultFromMessage(finalized.message,durableTerminate),isError:finalized.message.isError,terminate:durableTerminate,...recovery?{recovery:!0}:{}}]}},drive.context)}async function clearReplayCheckpoint(lane,drive,batch,call,toolCall){return lane.command(async(state,reader)=>{let stored=await reader.getValue(operationToolArgs(drive.operationId,batch.turnId,call.sourceIndex),drive.context);if(stored===void 0)throw new SessionInvariantError(`Tool call ${call.resultEntryId} is missing persisted arguments`);return{kind:"commit",writes:[deleteValue(pendingToolOutput(drive.operationId,call.resultEntryId))],next:state,materialize:()=>stored.value,events:()=>[{type:"tool_start",lane:lane.name,runId:drive.operationId,turnId:batch.turnId,toolCallId:toolCall.id,toolName:toolCall.name,args:stored.value,recovery:!0}]}},drive.context)}function readCheckpoint(lane,drive,call){return lane.command(async(_state,reader)=>({kind:"return",result:(await reader.getValue(pendingToolOutput(drive.operationId,call.resultEntryId),drive.context))?.value}),drive.context)}async function resolveToolContext(lane,drive){let source=lane.readConfig().toolContext;return typeof source=="function"?await source(drive.context):source}async function performToolInvocation(lane,drive,batch,call,cleared,toolContext,recovery){let capability=invocationCapability(lane,drive,batch,call),progress=openToolProgress(lane,drive,batch.turnId,call.sourceIndex,call.resultEntryId),latestUpdateDelivery=Promise.resolve(),publishUpdate=partial=>{latestUpdateDelivery=lane.emitBatch([{type:"tool_update",lane:lane.name,runId:drive.operationId,turnId:batch.turnId,toolCallId:cleared.toolCall.id,toolName:cleared.toolCall.name,partialResult:partial,...recovery?{recovery:!0}:{}}],drive.context),latestUpdateDelivery.catch(()=>{})},execution;try{execution=executeToolCall(cleared,drive.gate,(partial,options)=>{publishUpdate(partial),options?.checkpoint===!0&&progress.write(partial)},toolContext,capability.invocation,drive.context)}catch(error){if(capability.expire(),progress.seal(),await progress.drain(),!(error instanceof AbortRequested))throw error;return await error.cancellation,recovery?interruptedOutcome(cleared.toolCall,void 0):abortedOutcome(cleared.toolCall)}let executed=await execution.finally(()=>{capability.expire(),progress.seal()});await latestUpdateDelivery,await progress.drain();let patch;try{patch=await lane.hooks.runToolWithGate("after_tool",{lane:lane.name,runId:drive.operationId,toolCallId:cleared.toolCall.id,toolName:cleared.toolCall.name,args:cleared.args,content:executed.result.content,...executed.result.details===void 0?{}:{details:executed.result.details},isError:executed.isError,...executed.result.usage===void 0?{}:{usage:executed.result.usage}},drive.gate,drive.context)}catch(error){if(!(error instanceof AbortRequested))throw error;patch=void 0}let finalized=finalizeToolCall(cleared,executed,patch);return{toolCall:finalized.toolCall,message:createToolResultMessage2(finalized),terminate:finalized.terminate}}async function prepareToolInvocation(lane,drive,sources,call,tools){let toolCall=toolCallFor(sources,call);if(sources.assistant.stopReason==="length")return{kind:"outcome",outcome:truncatedOutcome(toolCall)};let prepared=prepareToolCall2(toolCall,tools);if("kind"in prepared)return{kind:"outcome",outcome:outcomeFromFinalizedCall(prepared)};let decision;try{decision=await lane.hooks.runToolWithGate("before_tool",{lane:lane.name,runId:drive.operationId,toolCallId:toolCall.id,toolName:toolCall.name,args:prepared.args},drive.gate,drive.context)}catch(error){if(!(error instanceof AbortRequested))throw error;return await error.cancellation,{kind:"outcome",outcome:abortedOutcome(toolCall)}}let cleared=applyBeforeToolDecision(prepared,decision);return"kind"in cleared?{kind:"outcome",outcome:outcomeFromFinalizedCall(cleared)}:{kind:"ready",cleared}}async function startToolInvocation(lane,drive,run,sources,call,tools,toolContext,recovery){let prepared=await prepareToolInvocation(lane,drive,sources,call,tools);if(prepared.kind==="outcome")return{completion:publishToolOutcome(lane,drive,run,call,prepared.outcome,recovery)};let effectPending=await publishToolIntent(lane,drive,run,call,prepared.cleared.toolCall,prepared.cleared.args,prepared.cleared.tool.replay??"never",recovery);return{completion:effectPending.kind==="cancel_requested"?publishToolOutcome(lane,drive,run,call,abortedOutcome(prepared.cleared.toolCall),recovery):performToolInvocation(lane,drive,run.batch,effectPending.value,prepared.cleared,toolContext,recovery).then(outcome=>publishToolOutcome(lane,drive,run,effectPending.value,outcome,recovery))}}async function recoverToolInvocation(lane,drive,run,sources,call,toolsByName,toolContext,cancelled){let toolCall=toolCallFor(sources,call),tool=toolsByName.get(toolCall.name);if(!cancelled&&call.replay==="safe"&&tool?.replay==="safe"){let args=await clearReplayCheckpoint(lane,drive,run.batch,call,toolCall),cleared={toolCall,tool,args};return{completion:performToolInvocation(lane,drive,run.batch,call,cleared,toolContext,!0).then(outcome=>publishToolOutcome(lane,drive,run,call,outcome,!0))}}let checkpoint=await readCheckpoint(lane,drive,call);return{completion:publishToolOutcome(lane,drive,run,call,interruptedOutcome(toolCall,checkpoint),!0)}}async function runSequential(lane,drive,run,sources,execution,recovery){let{batch}=run;for(let transition=0;transition<=batch.calls.length*2+1;transition+=1){await materializeReady(lane,drive,run,sources,recovery);let current=currentBatch(lane);if(current===void 0)return{kind:"continue"};let call=current.batch.calls.find(candidate=>candidate.status!=="completed");if(call===void 0)throw new SessionInvariantError("Tool batch remained open after every call completed");if(call.status==="outcome_ready")throw new SessionInvariantError("Ready tool outcome was not materialized");if(current.run.control.status==="cancel_requested"){let toolCall=toolCallFor(sources,call);if(call.status==="planned")await publishToolOutcome(lane,drive,current.run,call,abortedOutcome(toolCall),recovery);else{let checkpoint=await readCheckpoint(lane,drive,call);await publishToolOutcome(lane,drive,current.run,call,interruptedOutcome(toolCall,checkpoint),recovery)}continue}if(execution===void 0)throw new SessionInvariantError("Running tool batch is missing execution context");await(call.status==="planned"?await startToolInvocation(lane,drive,current.run,sources,call,execution.tools,execution.toolContext,recovery):await recoverToolInvocation(lane,drive,current.run,sources,call,execution.toolsByName,execution.toolContext,!1)).completion}throw new SessionInvariantError("Sequential tool batch exceeded its bounded transition count")}async function runParallel(lane,drive,run,sources,tools,toolsByName,toolContext,recovery){let{batch}=run,materialization=Promise.resolve(),scheduleMaterialization=()=>{let scheduled=materialization.then(()=>materializeReady(lane,drive,run,sources,recovery));return materialization=scheduled.catch(()=>{}),scheduled},jobs=[];for(let call of batch.calls){if(call.status==="completed"||call.status==="outcome_ready")continue;let job=(call.status==="planned"?await startToolInvocation(lane,drive,run,sources,call,tools,toolContext,recovery):await recoverToolInvocation(lane,drive,run,sources,call,toolsByName,toolContext,lane.state.operation.state.control.status==="cancel_requested")).completion.then(async()=>{await scheduleMaterialization()});job.catch(()=>{}),jobs.push(job)}return await Promise.all(jobs),await scheduleMaterialization(),{kind:"continue"}}async function runTools(lane,drive,run){let batch=run.batch,recovery=batch.calls.some(call=>call.status==="effect_pending"||call.status==="outcome_ready");recovery&&await lane.emitBatch([{type:"turn_start",lane:lane.name,runId:drive.operationId,turnId:batch.turnId,recovery:!0}],drive.context);let sources=await readToolBatchSource(lane,drive,batch);await materializeReady(lane,drive,run,sources,recovery);let current=currentBatch(lane);if(current===void 0)return{kind:"continue"};if(current.run.control.status==="cancel_requested")return runSequential(lane,drive,current.run,sources,void 0,recovery);let config=lane.readConfig(),active=new Set(batch.configuration.activeToolNames),tools=config.tools.filter(tool=>active.has(tool.name)),toolsByName=new Map(tools.map(tool=>[tool.name,tool])),toolContext=await resolveToolContext(lane,drive);return run.settings.toolExecution==="sequential"?runSequential(lane,drive,current.run,sources,{tools,toolsByName,toolContext},recovery):runParallel(lane,drive,current.run,sources,tools,toolsByName,toolContext,recovery)}async function cancelDeferredBestEffort(lane,drive,deferred,handle){let identity=deferred.configuration.model,model=lane.models.getModel(identity.provider,identity.modelId);if(model!==void 0)try{await lane.models.cancelDeferred(model,handle,{signal:drive.closeSignal,telemetryContext:getTelemetryContext(drive.context),timeoutMs:deferred.streamOptions.timeoutMs,maxRetries:deferred.streamOptions.maxRetries,maxRetryDelayMs:deferred.streamOptions.maxRetryDelayMs,headers:deferred.streamOptions.headers})}catch{}}async function readDeferredHandle(lane,drive,deferred){return lane.settleOperation(deferred,async(_state,_current,_meta,reader)=>({kind:"return",result:await readDeferredSourceHandle(reader,deferred,drive.context)}),drive.context)}async function publishAbortedTerminal(lane,drive,capability){return lane.settleOperation(capability,async(state,current,meta,reader)=>{if(current.control.status!=="cancel_requested")throw new SessionInvariantError("Cancellation reconciliation requires cancelled durable control");let record=operationResultRecord(meta,"aborted",state.tipId),cleanup=await operationCleanupWrites(reader,drive.operationId,current,drive.context),events=[];if(meta.intent.kind==="run"){switch(current.at){case"summary.deciding":case"summary.ready":case"summary.effect_pending":case"summary.retry_wait":if(current.task.boundary.kind!=="resume_checkpoint"||current.task.reason===void 0)throw new SessionInvariantError("Cancelled run summary has an invalid result boundary");events.push({type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:current.task.reason,status:"aborted",endedAt:record.endedAt});break;default:break}events.push({type:"run_end",lane:lane.name,runId:drive.operationId,status:"aborted",fromTipId:meta.sourceTipId,tipId:state.tipId,endedAt:record.endedAt})}else meta.intent.kind==="compaction"?events.push({type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:"manual",status:"aborted",endedAt:record.endedAt}):events.push({type:"navigation_end",lane:lane.name,runId:drive.operationId,status:"aborted",fromTipId:meta.sourceTipId,tipId:state.tipId,endedAt:record.endedAt});return{kind:"finish",writes:cleanup,record,materialize:()=>({kind:"settled",outcome:record}),events:()=>events}},drive.context)}async function reconcileOperation(lane,drive){let operation=lane.state.operation;if(operation===null||operation.meta.operationId!==drive.operationId)throw new SessionInvariantError(`Drive ${drive.operationId} has no matching operation to reconcile`);if(operation.state.control.status!=="cancel_requested")throw new SessionInvariantError(`Operation ${drive.operationId} is not cancelled`);drive.beginAbort(Promise.resolve()),drive.signalAbort();let state=operation.state;switch(state.at){case"assistant.effect_pending":return recoverCancelledAssistantEffect(lane,drive,state);case"tools":return runTools(lane,drive,state);case"deferred.suspended":{let handle=await readDeferredHandle(lane,drive,state);return await cancelDeferredBestEffort(lane,drive,state,handle),publishAbortedTerminal(lane,drive,state)}case"deferred.effect_pending":{let handle=await readDeferredHandle(lane,drive,state);return await cancelDeferredBestEffort(lane,drive,state,handle),recoverCancelledAssistantEffect(lane,drive,state)}case"starting":case"checkpoint":case"assistant.ready":case"assistant.retry_wait":case"summary.deciding":case"summary.ready":case"summary.effect_pending":case"summary.retry_wait":case"navigation.ready_to_commit":return publishAbortedTerminal(lane,drive,state)}}function currentOperation(lane,drive){let operation=lane.state.operation;if(operation===null||operation.meta.operationId!==drive.operationId)throw new SessionInvariantError(`Drive ${drive.operationId} has no matching current operation`);return operation}async function driveOperation(lane,drive){let operation=currentOperation(lane,drive);if(operation.state.control.status==="running")try{await lane.hooks.runWithGate("before_drive",{lane:lane.name,runId:drive.operationId,operation:operation.meta.intent.kind},drive.gate,drive.context)}catch(error){if(!(error instanceof AbortRequested))throw error;await error.cancellation}for(;;){operation=currentOperation(lane,drive);let state=operation.state,result;try{if(state.control.status==="cancel_requested")result=await reconcileOperation(lane,drive);else switch(state.at){case"starting":result=await startRun(lane,drive,state);break;case"checkpoint":result=await runCheckpoint(lane,drive,state);break;case"assistant.ready":case"assistant.retry_wait":result=await runGeneration(lane,drive,state);break;case"assistant.effect_pending":result=await recoverAssistantGeneration(lane,drive,state);break;case"tools":result=await runTools(lane,drive,state);break;case"deferred.suspended":case"deferred.effect_pending":result=await runDeferred(lane,drive,state);break;case"summary.deciding":result=await runStructuralDecision(lane,drive,state);break;case"summary.ready":result=await runStructuralGeneration(lane,drive,state);break;case"summary.effect_pending":result=await recoverStructuralGeneration(lane,drive,state);break;case"summary.retry_wait":result=await runStructuralRetryWait(lane,drive,state);break;case"navigation.ready_to_commit":result=await commitNavigation(lane,drive,state);break}}catch(error){if(!(error instanceof AbortRequested))throw error;await error.cancellation,result={kind:"continue"}}if(result.kind==="settled")return{kind:"settled",outcome:result.outcome};if(result.kind==="waiting")return result.outcome;let next=currentOperation(lane,drive).state;if(next===state&&next.control.status!=="cancel_requested")throw new SessionInvariantError(`Drive procedure made no progress from ${state.at}`)}}function isPromiseLike(value2){return value2===null||typeof value2!="object"&&typeof value2!="function"?!1:"then"in value2&&typeof value2.then=="function"}function inboxItems(inbox,kind){return inbox.filter(item=>item.kind===kind)}function withoutInboxItems(inbox,removed){let removedIds=new Set(removed.map(item=>item.entryId));return inbox.filter(item=>!removedIds.has(item.entryId))}function selectAcceptedInbox(inbox,steeringMode,followUpMode){let steerTaken=!1,followUpTaken=!1,selected=[],remainder=[];for(let item of inbox)item.kind==="write"||item.kind==="nextRun"||item.kind==="steer"&&(steeringMode==="all"||!steerTaken)||item.kind==="followUp"&&(followUpMode==="all"||!followUpTaken)?(selected.push(item),item.kind==="steer"&&(steerTaken=!0),item.kind==="followUp"&&(followUpTaken=!0)):remainder.push(item);return{selected,remainder}}function capturedSettings(config){return{compaction:config.compaction,steeringMode:config.steeringMode,followUpMode:config.followUpMode,toolExecution:config.toolExecution}}function durableLaneState(state,currentOperationId,inbox=state.inbox,lastOperationId=state.lastOperationId){return{currentOperationId,lastOperationId,inbox}}function pendingEntryWrite(entryId,pending){return pending.type==="message"?{id:entryId,parentId:null,type:"message",message:pending.payload}:{id:entryId,parentId:null,type:"custom",customType:pending.customType,...pending.payload===void 0?{}:{data:pending.payload}}}function capturedModel(operation){let{state}=operation;switch(state.at){case"assistant.ready":case"assistant.effect_pending":case"assistant.retry_wait":return state.generationContext.configuration.model;case"tools":return state.batch.configuration.model;case"deferred.suspended":case"deferred.effect_pending":return state.configuration.model;case"summary.ready":case"summary.effect_pending":case"summary.retry_wait":return state.summaryContext.configuration.model;default:return}}var Lane=class{constructor(name,session,models,hooks,state,onFault,emitBatch,installWatch,readConfig){this.session=session,this.models=models,this.hooks=hooks,this.name=name,this.state=state,this.onFault=onFault,this.emitBatch=emitBatch,this.installWatch=installWatch,this.config=readConfig;let resolveStateChange;this.stateChange=new Promise(resolve=>{resolveStateChange=resolve}),this.resolveStateChange=resolveStateChange}async getTipId(_context){return this.assertOpen(),this.state.tipId}async getResult(operationId,context){return this.assertOpen(),(await this.session.getValue(operationResult(operationId),context))?.value}readConfig(){return this.config()}mismatch(expected,currentOperationId,lastOperationId){return new OperationMismatch({lane:this.name,expectedOperationId:expected,...currentOperationId===null?{}:{currentOperationId},...lastOperationId===null?{}:{lastOperationId},message:`Operation ${expected} does not own lane ${JSON.stringify(this.name)}`})}async readLane(read,context){this.assertOpen();try{return await this.session.mutate(async reader=>{this.assertOpen();try{return await read(this.state,reader)}catch(error){throw this.closedError!==void 0?this.closedError:this.onFault(error,context)}},context)}catch(error){throw this.closedError!==void 0?this.closedError:error}}async command(plan,context){for(this.assertOpen();this.idleOwner!==void 0;)await awaitWithContext(Promise.race([this.idleOwner,this.stateChange]),context),this.assertOpen();let outcome;try{outcome=await this.session.mutate(async mutator=>{if(this.assertOpen(),this.idleOwner!==void 0)return{kind:"idle_blocked",owner:this.idleOwner,change:this.stateChange};try{let decision=await plan(this.state,mutator);switch(decision.kind){case"return":return{kind:"return",result:decision.result};case"reject":return{kind:"reject",error:decision.error};case"commit":{let commit=await mutator.commit(decision.writes,context);this.state=decision.next,this.signalStateChange();let result=decision.materialize(commit);if(isPromiseLike(result))throw new TypeError("Lane command materialize() must be synchronous");let events=decision.events?.(commit)??[],delivery=events.length===0?void 0:this.emitBatch(events,context);return{kind:"return",result,...delivery===void 0?{}:{delivery}}}}}catch(error){throw this.closedError!==void 0?this.closedError:this.onFault(error,context)}},context)}catch(error){throw this.closedError!==void 0?this.closedError:error}if(outcome.kind==="idle_blocked")return await awaitWithContext(Promise.race([outcome.owner,outcome.change]),context),this.assertOpen(),this.command(plan,context);if(outcome.kind==="reject")throw outcome.error;return await outcome.delivery,outcome.result}settleOperation(_capability,plan,context){return this.command(async(state,reader)=>{let operation=state.operation,decision=await plan(state,operation.state,operation.meta,reader);if(decision.kind==="commit")return{kind:"commit",writes:[...decision.writes,setValue(operationState(operation.meta.operationId),decision.operationState),...decision.lane?.inbox===void 0?[]:[setValue(laneState(this.name),durableLaneState(state,operation.meta.operationId,decision.lane.inbox))]],next:{...state,...decision.lane,operation:{meta:operation.meta,state:decision.operationState}},materialize:decision.materialize,...decision.events===void 0?{}:{events:decision.events}};if(decision.kind!=="finish")return decision;let inbox=decision.lane?.inbox??state.inbox;return{kind:"commit",writes:[...decision.writes,setValue(operationResult(operation.meta.operationId),decision.record),setValue(laneState(this.name),durableLaneState(state,null,inbox,operation.meta.operationId))],next:{...state,...decision.lane,inbox,lastOperationId:operation.meta.operationId,operation:null},materialize:decision.materialize,...decision.events===void 0?{}:{events:decision.events}}},context)}continueOperation(capability,plan,context){return this.settleOperation(capability,async(state,latest,meta,reader)=>{if(latest.control.status==="cancel_requested")return{kind:"return",result:{kind:"cancel_requested"}};let decision=await plan(state,latest,meta,reader);return decision.kind==="return"?{kind:"return",result:{kind:"result",value:decision.result}}:{...decision,materialize:commit=>({kind:"result",value:decision.materialize(commit)})}},context)}async accept(request,context){if(this.closedError instanceof HarnessClosed)return Result.err(new Closed({message:this.closedError.message}));this.assertOpen();let startedAt=Date.now(),operationId=request.operationId??this.session.idGenerator.next(startedAt),acceptanceConfig=this.readConfig();return request.kind==="compaction"?this.acceptCompaction(request,operationId,startedAt,acceptanceConfig,context):request.kind==="navigation"?this.acceptNavigation(request,operationId,startedAt,acceptanceConfig,context):this.acceptRun(request,operationId,startedAt,acceptanceConfig,context)}async acceptRun(request,operationId,startedAt,acceptanceConfig,context){let messages;switch(request.kind){case"prompt":if(typeof request.prompt!="string")messages=Array.isArray(request.prompt)?request.prompt:[request.prompt];else{let images=request.images??[];messages=request.prompt.length===0&&images.length===0?[]:[{role:"user",content:[...request.prompt.length===0?[]:[{type:"text",text:request.prompt}],...images],timestamp:startedAt}]}break;case"skill":{let skill=acceptanceConfig.resources.skills?.find(candidate=>candidate.name===request.name);if(skill===void 0)return Result.err(new UnknownSkill({name:request.name,message:`Unknown skill: ${request.name}`}));messages=[{role:"user",content:[{type:"text",text:formatSkillInvocation(skill,request.additionalInstructions)}],timestamp:startedAt}];break}case"prompt_template":{let template=acceptanceConfig.resources.promptTemplates?.find(candidate=>candidate.name===request.name);if(template===void 0)return Result.err(new UnknownTemplate({name:request.name,message:`Unknown prompt template: ${request.name}`}));let content=formatPromptTemplateInvocation(template,request.args);messages=content.length===0?[]:[{role:"user",content:[{type:"text",text:content}],timestamp:startedAt}];break}}for(let message of messages)if(message.role==="assistant"&&message.stopReason==="pending")return Result.err(new InvalidMessage({lane:this.name,reason:"pending_assistant",message:"Cannot accept a pending assistant message"}));let prompt=messages.map(message=>({id:this.session.idGenerator.next(startedAt),message}));return this.command(async(state,reader)=>{if(state.operation!==null)return{kind:"return",result:Result.err(new LaneBusy({lane:this.name,operationId:state.operation.meta.operationId,operationKind:state.operation.meta.intent.kind,message:`Lane ${JSON.stringify(this.name)} already has an active operation`}))};let{selected:selectedItems,remainder:inbox}=selectAcceptedInbox(state.inbox,acceptanceConfig.steeringMode,acceptanceConfig.followUpMode),captured=await Promise.all(selectedItems.map(async item=>{let stored=await reader.getValue(pendingEntry(item.entryId),context);if(stored===void 0)throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is missing its payload`);if(item.kind!=="write"&&stored.value.type!=="message")throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is not a message`);if(stored.value.type==="message"&&stored.value.payload.role==="assistant"&&stored.value.payload.stopReason==="pending")throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} contains a pending assistant`);return{item,pending:stored.value}})),hasCapturedConversation=selectedItems.some(item=>item.kind!=="write");if(prompt.length===0&&!hasCapturedConversation)return{kind:"return",result:Result.err(new InvalidMessage({lane:this.name,reason:"empty",message:"Acceptance must append at least one message"}))};let entries=chainEntries(state.tipId,[...captured.map(({item,pending})=>pendingEntryWrite(item.entryId,pending)),...prompt.map(({id,message})=>({id,parentId:null,type:"message",message}))]),parentId=entries[entries.length-1].id,meta={operationId,lane:this.name,sourceTipId:state.tipId,startedAt,intent:{kind:"run",promptEntryIds:prompt.map(({id})=>id)}},operationState2={at:"starting",control:{status:"running"},settings:capturedSettings(acceptanceConfig),latestAssistantEntryId:null},remainingQueues=await readLaneQueues(reader,inbox,context),next={...state,tipId:parentId,inbox,operation:{meta,state:operationState2}};return{kind:"commit",writes:[...entries.map(entry=>insertEntry(entry)),...selectedItems.map(item=>deleteValue(pendingEntry(item.entryId))),setValue(branchTip(this.name),parentId),setValue(operationMeta(operationId),meta),setValue(operationState(operationId),operationState2),setValue(laneState(this.name),durableLaneState(state,operationId,inbox))],next,materialize:()=>Result.ok({operationId,kind:"run",startedAt}),events:commit=>{let events=[{type:"run_start",runId:operationId,startedAt,lane:this.name},...committedEntryEvents(entries,commit,this.name,operationId)];return selectedItems.length>0&&events.push({type:"queue_update",queues:remainingQueues,lane:this.name}),events}}},context)}acceptCompaction(request,operationId,startedAt,acceptanceConfig,context){let taskId=this.session.idGenerator.next(startedAt);return this.command(async(state,reader)=>{if(state.operation!==null)return{kind:"return",result:Result.err(new LaneBusy({lane:this.name,operationId:state.operation.meta.operationId,operationKind:state.operation.meta.intent.kind,message:`Lane ${JSON.stringify(this.name)} already has an active operation`}))};let path=state.tipId===null?[]:(await reader.scanBranch({start:state.tipId,stopAtType:"compaction",order:"newestFirst"},context)).reverse(),prepared=prepareCompaction(path,acceptanceConfig.compaction);if(!prepared.ok)throw prepared.error;if(prepared.value===void 0)return{kind:"return",result:Result.err(new NothingToCompact({lane:this.name,message:`Lane ${JSON.stringify(this.name)} has nothing to compact`}))};let meta={operationId,lane:this.name,sourceTipId:state.tipId,startedAt,intent:{kind:"compaction",...request.customInstructions===void 0?{}:{customInstructions:request.customInstructions}}},operationState2={at:"summary.deciding",control:{status:"running"},settings:capturedSettings(acceptanceConfig),latestAssistantEntryId:null,task:{taskId,reason:"manual",...request.customInstructions===void 0?{}:{customInstructions:request.customInstructions},boundary:{kind:"finish"}}};return{kind:"commit",writes:[setValue(operationPreparation(operationId,taskId),durableCompactionPreparation(prepared.value)),setValue(operationMeta(operationId),meta),setValue(operationState(operationId),operationState2),setValue(laneState(this.name),durableLaneState(state,operationId))],next:{...state,operation:{meta,state:operationState2}},materialize:()=>Result.ok({operationId,kind:"compaction",startedAt}),events:()=>[{type:"compaction_start",lane:this.name,runId:operationId,reason:"manual",startedAt}]}},context)}async acceptNavigation(request,operationId,startedAt,acceptanceConfig,context){let taskId=this.session.idGenerator.next(startedAt),targetId=request.targetId,options=request.options??{},summarize=options.summarize??!1;for(;;){let observedTipId=this.state.tipId,preparation;if(summarize&&observedTipId!==null&&targetId!==null&&(await this.session.getEntries([targetId],context)).has(targetId)){let[oldPath,targetPath]=await Promise.all([this.session.scanBranch({start:observedTipId,order:"newestFirst"},context),this.session.scanBranch({start:targetId,order:"newestFirst"},context)]),oldIds=new Set(oldPath.map(entry=>entry.id)),commonAncestorId=targetPath.find(entry=>oldIds.has(entry.id))?.id??null;preparation=prepareBranchEntries(oldPath.slice(0,commonAncestorId===null?oldPath.length:oldPath.findIndex(entry=>entry.id===commonAncestorId)).reverse())}let accepted=await this.command(async(state,reader)=>{if(state.operation!==null)return{kind:"return",result:Result.err(new LaneBusy({lane:this.name,operationId:state.operation.meta.operationId,operationKind:state.operation.meta.intent.kind,message:`Lane ${JSON.stringify(this.name)} already has an active operation`}))};if(state.tipId!==observedTipId)return{kind:"return",result:void 0};if(targetId===state.tipId)return{kind:"return",result:Result.err(new InvalidNavigation({lane:this.name,reason:"current_tip",message:"Navigation target must differ from the current tip"}))};if(targetId===null&&options.label!==void 0)return{kind:"return",result:Result.err(new InvalidNavigation({lane:this.name,reason:"root_label",message:"Root navigation cannot set a label"}))};if(summarize&&(state.tipId===null||targetId===null))return{kind:"return",result:Result.err(new InvalidNavigation({lane:this.name,reason:state.tipId===null?"source_root":"target_root",message:"Summarized navigation requires non-root source and target entries"}))};if(targetId!==null&&!(await reader.getEntries([targetId],context)).has(targetId))return{kind:"return",result:Result.err(new UnknownTarget({targetId,message:`Unknown target: ${targetId}`}))};let intent={kind:"navigation",targetId,summarize,...options.label===void 0?{}:{label:options.label},...options.customInstructions===void 0?{}:{customInstructions:options.customInstructions}},meta={operationId,lane:this.name,sourceTipId:state.tipId,startedAt,intent},operationScope={control:{status:"running"},settings:capturedSettings(acceptanceConfig),latestAssistantEntryId:null},operationState2,writes=[];if(summarize){if(state.tipId===null||targetId===null||preparation===void 0)throw new SessionInvariantError("Validated summarized navigation is missing its preparation");writes.push(setValue(operationPreparation(operationId,taskId),durableBranchPreparation(preparation))),operationState2={...operationScope,at:"summary.deciding",task:{taskId,...options.customInstructions===void 0?{}:{customInstructions:options.customInstructions},boundary:{kind:"commit_navigation",targetId,...options.label===void 0?{}:{label:options.label}}}}}else operationState2={...operationScope,at:"navigation.ready_to_commit",targetId,...options.label===void 0?{}:{label:options.label}};return writes.push(setValue(operationMeta(operationId),meta),setValue(operationState(operationId),operationState2),setValue(laneState(this.name),durableLaneState(state,operationId))),{kind:"commit",writes,next:{...state,operation:{meta,state:operationState2}},materialize:()=>Result.ok({operationId,kind:"navigation",startedAt}),events:()=>[{type:"navigation_start",lane:this.name,runId:operationId,targetId,startedAt}]}},context);if(accepted!==void 0)return accepted}}async drive(options,context){if(this.closedError instanceof HarnessClosed)return Result.err(new Closed({message:this.closedError.message}));for(this.assertOpen();;){let claim=await this.command(async(state,reader)=>{let signal=context.abortSignal;if(signal?.aborted){let reason=signal.reason;return{kind:"reject",error:reason instanceof Error?reason:new DOMException("The operation was aborted","AbortError")}}if(state.operation?.meta.operationId===options.operationId){if(this.activeDrive===void 0){let drive=new Drive(options,context);return this.activeDrive=drive,this.signalStateChange(),{kind:"return",result:{kind:"observe",drive,installed:!0}}}return{kind:"return",result:this.activeDrive.operationId===options.operationId?{kind:"observe",drive:this.activeDrive,installed:!1}:{kind:"occupied",drive:this.activeDrive}}}let stored=await reader.getValue(operationResult(options.operationId),context);return stored===void 0?{kind:"return",result:{kind:"mismatch",error:this.mismatch(options.operationId,state.operation?.meta.operationId??null,state.lastOperationId)}}:{kind:"return",result:{kind:"settled",outcome:stored.value}}},context);if(claim.kind==="settled")return Result.ok({kind:"settled",outcome:claim.outcome});if(claim.kind==="mismatch")return Result.err(claim.error);if(claim.kind==="occupied"){await awaitWithContext(claim.drive.completion,context);continue}return claim.installed&&driveOperation(this,claim.drive).then(outcome=>{this.activeDrive===claim.drive&&(this.activeDrive=void 0,this.signalStateChange()),claim.drive.settle(outcome)},error=>{let failure=this.closedError;if(failure===void 0)try{failure=this.onFault(error,claim.drive.context)}catch(faultError){failure=faultError}this.activeDrive===claim.drive&&(this.activeDrive=void 0,this.signalStateChange()),claim.drive.fail(failure)}),Result.ok(await awaitWithContext(claim.drive.completion,context))}}async requestOperationAbort(operationId,context){if(this.closedError instanceof HarnessClosed)return Result.err(new Closed({message:this.closedError.message}));this.assertOpen();let drive=this.activeDrive?.operationId===operationId?this.activeDrive:void 0,resolveCancellation,rejectCancellation,cancellation=new Promise((resolve,reject)=>{resolveCancellation=resolve,rejectCancellation=reject});cancellation.catch(()=>{}),drive?.beginAbort(cancellation);let gateSettled=!1,settleGate=signal=>{gateSettled||(gateSettled=!0,resolveCancellation(),signal&&drive?.signalAbort())};try{let result=await this.command(async(state,reader)=>{let operation=state.operation;if(operation?.meta.operationId!==operationId)return{kind:"return",result:Result.err(this.mismatch(operationId,operation?.meta.operationId??null,state.lastOperationId))};if(operation.state.control.status==="cancel_requested")return{kind:"return",result:Result.ok({operationId,newlyRequested:!1,steer:[],followUp:[]})};let removed=state.inbox.filter(item=>item.kind==="steer"||item.kind==="followUp"),payloads=await Promise.all(removed.map(async item=>{let stored=await reader.getValue(pendingEntry(item.entryId),context);if(stored?.value.type!=="message")throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is missing its message`);return{item,message:stored.value.payload}})),steer=payloads.filter(({item})=>item.kind==="steer").map(({message})=>message),followUp=payloads.filter(({item})=>item.kind==="followUp").map(({message})=>message),removedIds=new Set(removed.map(item=>item.entryId)),inbox=state.inbox.filter(item=>!removedIds.has(item.entryId)),queues=await readLaneQueues(reader,inbox,context),operationState2={...operation.state,control:{status:"cancel_requested",requestedAt:Date.now()}};return{kind:"commit",writes:[...removed.map(item=>deleteValue(pendingEntry(item.entryId))),setValue(operationState(operationId),operationState2),setValue(laneState(this.name),durableLaneState(state,operationId,inbox))],next:{...state,inbox,operation:{meta:operation.meta,state:operationState2}},materialize:()=>(settleGate(!0),Result.ok({operationId,newlyRequested:!0,steer,followUp})),events:()=>[{type:"operation_abort",operationId,steer,followUp,lane:this.name},...removed.length===0?[]:[{type:"queue_update",queues,lane:this.name}]]}},context);return settleGate(result.ok&&result.value.newlyRequested===!1),result}catch(error){throw gateSettled||rejectCancellation(error),error}}requestAbort(operationId,context){return this.requestOperationAbort(operationId,context)}inspectExecution(context){return this.readLane(state=>{let operation=state.operation,captured=operation===null?void 0:capturedModel(operation),current=operation===null?null:{id:operation.meta.operationId,kind:operation.meta.intent.kind,status:operation.state.control.status==="cancel_requested"?"aborting":"open",startedAt:operation.meta.startedAt,...captured===void 0?{}:{capturedModel:captured}};return{lane:this.name,tipId:state.tipId,configuredModel:state.configuration.model,current,lastOperationId:state.lastOperationId}},context)}async prompt(...args){return args.length===3?this.driveRunRequest({kind:"prompt",prompt:args[0],...args[1]===void 0?{}:{images:args[1]}},args[2]):this.driveRunRequest({kind:"prompt",prompt:args[0]},args[1])}skill(name,additionalInstructions,context){return this.driveRunRequest({kind:"skill",name,...additionalInstructions===void 0?{}:{additionalInstructions}},context)}promptFromTemplate(name,args,context){return this.driveRunRequest({kind:"prompt_template",name,...args===void 0?{}:{args}},context)}async driveRunRequest(request,context){let admission=await this.accept(request,context);if(!admission.ok)switch(admission.error._tag){case"LaneBusy":case"InvalidMessage":case"UnknownSkill":case"UnknownTemplate":case"Closed":return Result.err(admission.error);default:throw this.onFault(new SessionInvariantError(`Run acceptance returned ${admission.error._tag}`),context)}let driven=await this.drive({operationId:admission.value.operationId,waitForRetry:!0},context);if(!driven.ok){if(driven.error._tag==="Closed")return Result.err(driven.error);throw this.onFault(new SessionInvariantError(`Accepted run ${admission.value.operationId} no longer matches its lane`),context)}if(driven.value.kind==="settled")return Result.ok(driven.value.outcome);if(driven.value.reason==="deferred")return Result.ok({operationId:admission.value.operationId,status:"suspended",deferred:driven.value.deferred});throw this.onFault(new SessionInvariantError(`Run ${admission.value.operationId} returned an unwaited retry`),context)}async compact(options,context){let admission=await this.accept({kind:"compaction",...options?.customInstructions===void 0?{}:{customInstructions:options.customInstructions}},context);if(!admission.ok)switch(admission.error._tag){case"LaneBusy":case"NothingToCompact":case"Closed":return Result.err(admission.error);default:throw this.onFault(new SessionInvariantError(`Compaction acceptance returned ${admission.error._tag}`),context)}let compacted=await this.driveStructuralAdmission(admission.value,context);if(!compacted.ok)return compacted;let continuation=await this.continueAfterStructural(compacted.value,context);return continuation.ok?Result.ok({compaction:compacted.value,...continuation.value===void 0?{}:{run:continuation.value}}):continuation}async navigateTree(targetId,options,context){let admission=await this.accept({kind:"navigation",targetId,...options===void 0?{}:{options}},context);if(!admission.ok)switch(admission.error._tag){case"LaneBusy":case"InvalidNavigation":case"UnknownTarget":case"Closed":return Result.err(admission.error);default:throw this.onFault(new SessionInvariantError(`Navigation acceptance returned ${admission.error._tag}`),context)}let navigated=await this.driveStructuralAdmission(admission.value,context);if(!navigated.ok)return navigated;let continuation=await this.continueAfterStructural(navigated.value,context);return continuation.ok?Result.ok({navigation:navigated.value,...continuation.value===void 0?{}:{run:continuation.value}}):continuation}async driveStructuralAdmission(admission,context){let driven=await this.drive({operationId:admission.operationId,waitForRetry:!0},context);if(!driven.ok){if(driven.error._tag==="Closed")return Result.err(driven.error);throw this.onFault(new SessionInvariantError(`Accepted ${admission.kind} ${admission.operationId} no longer matches its lane`),context)}if(driven.value.kind==="settled")return Result.ok(driven.value.outcome);throw this.onFault(new SessionInvariantError(`${admission.kind} ${admission.operationId} returned ${driven.value.reason}`),context)}async continueAfterStructural(record,context){if(record.status==="aborted")return Result.ok(void 0);let admission=await this.accept({kind:"prompt",prompt:""},context);if(!admission.ok)switch(admission.error._tag){case"InvalidMessage":case"LaneBusy":return Result.ok(void 0);case"Closed":return Result.err(admission.error);default:throw this.onFault(new SessionInvariantError(`Structural continuation acceptance returned ${admission.error._tag}`),context)}let driven=await this.drive({operationId:admission.value.operationId,waitForRetry:!0},context);if(!driven.ok){if(driven.error._tag==="Closed")return Result.err(driven.error);throw this.onFault(new SessionInvariantError(`Continuation run ${admission.value.operationId} no longer matches its lane`),context)}if(driven.value.kind==="settled")return Result.ok(driven.value.outcome);if(driven.value.reason==="deferred")return Result.ok({operationId:admission.value.operationId,status:"suspended",deferred:driven.value.deferred});throw this.onFault(new SessionInvariantError(`Continuation run ${admission.value.operationId} returned an unwaited retry`),context)}async resume(context){if(this.closedError instanceof HarnessClosed)return Result.err(new Closed({message:this.closedError.message}));this.assertOpen();let inspected=await this.command(state=>{let operation=state.operation;return operation===null?{kind:"return",result:Result.err(new NothingToResume({lane:this.name,message:`Lane ${JSON.stringify(this.name)} has no active operation to resume`}))}:{kind:"return",result:Result.ok({operationId:operation.meta.operationId})}},context);if(!inspected.ok)return inspected;let driven=await this.drive({operationId:inspected.value.operationId,pollDeferred:!0,waitForRetry:!0},context);if(!driven.ok){if(driven.error._tag==="Closed")return Result.err(driven.error);throw this.onFault(new SessionInvariantError(`Operation ${inspected.value.operationId} no longer matches its lane`),context)}if(driven.value.kind==="settled")return Result.ok(driven.value.outcome);if(driven.value.reason==="deferred")return Result.ok({operationId:inspected.value.operationId,status:"suspended",deferred:driven.value.deferred});throw this.onFault(new SessionInvariantError(`Operation ${inspected.value.operationId} returned an unwaited retry`),context)}async abort(context){if(this.closedError instanceof HarnessClosed)return Result.err(new Closed({message:this.closedError.message}));this.assertOpen();let operationId=await this.command(state=>({kind:"return",result:state.operation?.meta.operationId}),context);if(operationId===void 0)return Result.err(new NoActiveOperation({lane:this.name,message:`Lane ${JSON.stringify(this.name)} has no active operation`}));let requested=await this.requestAbort(operationId,context);if(!requested.ok)return requested.error._tag==="Closed"?Result.err(requested.error):Result.err(new NoActiveOperation({lane:this.name,message:`Lane ${JSON.stringify(this.name)} no longer has the inspected operation`}));let driven=await this.drive({operationId},context);if(!driven.ok&&driven.error._tag==="Closed")return Result.err(driven.error);if(!driven.ok)throw this.onFault(new SessionInvariantError(`Cancelled operation ${operationId} no longer matches its lane`),context);return Result.ok({operationId,steer:requested.value.steer,followUp:requested.value.followUp})}steer(message,images,context){return this.enqueue("steer",message,images,context)}followUp(message,images,context){return this.enqueue("followUp",message,images,context)}nextRun(message,images,context){return this.enqueue("nextRun",message,images,context)}async enqueue(kind,input,images,context){if(this.closedError instanceof HarnessClosed)return Result.err(new Closed({message:this.closedError.message}));this.assertOpen();let at=Date.now(),message;if(typeof input=="string"){if(input.length===0&&(images===void 0||images.length===0))return Result.err(new InvalidMessage({lane:this.name,reason:"empty",message:"Queued input must contain text or an image"}));message={role:"user",content:[...input.length===0?[]:[{type:"text",text:input}],...images??[]],timestamp:at}}else{if(input.role==="assistant"&&input.stopReason==="pending")return Result.err(new InvalidMessage({lane:this.name,reason:"pending_assistant",message:"Cannot queue a pending assistant message"}));if(images!==void 0&&images.length>0&&input.role!=="user")return Result.err(new InvalidMessage({lane:this.name,reason:"images_with_non_user",message:"Images can be added only to queued user messages"}));message=images===void 0||images.length===0||input.role!=="user"?structuredClone(input):{...structuredClone(input),content:[...typeof input.content=="string"?input.content.length===0?[]:[{type:"text",text:input.content}]:input.content,...images]}}let entryId=this.session.idGenerator.next(at);return this.command(async(state,reader)=>{let inbox=[...state.inbox,{entryId,kind}],queues=[...await readLaneQueues(reader,state.inbox,context),{entryId,kind,type:"message",message}];return{kind:"commit",writes:[setValue(pendingEntry(entryId),{type:"message",payload:message}),setValue(laneState(this.name),durableLaneState(state,state.operation?.meta.operationId??null,inbox))],next:{...state,inbox},materialize:()=>Result.ok({entryId}),events:()=>[{type:"queue_update",queues,lane:this.name}]}},context)}async cancelQueued(entryId,context){return this.closedError instanceof HarnessClosed?Result.err(new Closed({message:this.closedError.message})):(this.assertOpen(),this.command(async(state,reader)=>{let queued=state.inbox.find(item=>item.entryId===entryId);if(queued===void 0){let consumed=(await reader.getEntries([entryId],context)).has(entryId);return{kind:"return",result:Result.ok({kind:consumed?"already_consumed":"not_found"})}}if(await reader.getValue(pendingEntry(entryId),context)===void 0)throw new SessionInvariantError(`Queued ${queued.kind} entry ${entryId} is missing its payload`);let inbox=state.inbox.filter(item=>item.entryId!==entryId),queues=await readLaneQueues(reader,inbox,context);return{kind:"commit",writes:[deleteValue(pendingEntry(entryId)),setValue(laneState(this.name),durableLaneState(state,state.operation?.meta.operationId??null,inbox))],next:{...state,inbox},materialize:()=>Result.ok({kind:"cancelled"}),events:()=>[{type:"queue_update",queues,lane:this.name}]}},context))}async recordUsage(usage,options,context){return this.closedError instanceof HarnessClosed?Result.err(new Closed({message:this.closedError.message})):(this.assertOpen(),this.command(state=>{let usageId=this.session.idGenerator.next(),row={id:usageId,usage,adjustment:!0,...options?.entryId===void 0?{}:{entryId:options.entryId},...options?.details===void 0?{}:{details:options.details}};return{kind:"commit",writes:[insertUsage(row)],next:state,materialize:()=>Result.ok({usageId}),events:commit=>[{type:"usage",lane:this.name,row:{...row,seq:commit.seqs[0]},totals:commit.stats.usage}]}},context))}async waitForIdle(context){for(;;){let observation=await this.command(state=>({kind:"return",result:state.operation===null&&this.activeDrive===void 0?{kind:"idle"}:{kind:"wait",drive:this.activeDrive,change:this.stateChange}}),context);if(observation.kind==="idle")return;await awaitWithContext(observation.drive===void 0?observation.change:observation.drive.completion.then(()=>{}),context)}}async runWhenIdle(callback,context){let owner,releaseOwner;for(;;){let observation=await this.command(state=>{if(state.operation!==null||this.activeDrive!==void 0)return{kind:"return",result:{kind:"wait",drive:this.activeDrive,change:this.stateChange}};let release,claimed=new Promise(resolve=>{release=resolve});return owner=claimed,releaseOwner=release,this.idleOwner=claimed,this.signalStateChange(),{kind:"return",result:{kind:"claimed"}}},context);if(observation.kind==="claimed")break;await awaitWithContext(observation.drive===void 0?observation.change:observation.drive.completion.then(()=>{}),context)}if(owner===void 0||releaseOwner===void 0)throw this.onFault(new SessionInvariantError("Idle callback claim was not published"),context);try{this.assertOpen(),await callback(context)}finally{this.idleOwner===owner&&(this.idleOwner=void 0),releaseOwner(),this.signalStateChange()}}async getModel(_context){return this.assertOpen(),this.models.getModel(this.state.configuration.model.provider,this.state.configuration.model.modelId)}setModel(model,context){return this.setConfiguration(configuration=>({...configuration,model:{...model}}),(previous,value2)=>({type:"config_update",property:"model",previous:previous.model,value:value2.model}),context)}async getThinkingLevel(_context){return this.assertOpen(),this.state.configuration.thinkingLevel}setThinkingLevel(thinkingLevel,context){return this.setConfiguration(configuration=>({...configuration,thinkingLevel}),(previous,value2)=>({type:"config_update",property:"thinkingLevel",previous:previous.thinkingLevel,value:value2.thinkingLevel}),context)}async getActiveTools(_context){return this.assertOpen(),this.state.configuration.activeToolNames}setActiveTools(activeToolNames,context){return this.setConfiguration(configuration=>({...configuration,activeToolNames}),(previous,value2)=>({type:"config_update",property:"activeTools",previous:previous.activeToolNames,value:value2.activeToolNames}),context)}watch(context){return this.readLane(async(state,reader)=>{let watcher=this.installWatch({},event=>event.type==="usage"||!("lane"in event)||event.lane===this.name,context,(resnapshotContext,markBoundary)=>this.readLane(async(latest,latestReader)=>{let snapshot=await this.captureLaneSnapshot(latest,latestReader,resnapshotContext);return markBoundary(),snapshot},resnapshotContext));try{return watcher.snapshot=await this.captureLaneSnapshot(state,reader,context),watcher}catch(error){throw watcher.unsubscribe(),error}},context)}async captureLaneSnapshot(state,reader,context){let captured=structuredClone(state),transcript=captured.tipId===null?[]:(await reader.scanBranch({start:captured.tipId,stopAtType:"compaction",order:"newestFirst"},context)).reverse(),queues=await readLaneQueues(reader,captured.inbox,context),lastResult;if(captured.lastOperationId!==null){let stored=await reader.getValue(operationResult(captured.lastOperationId),context);if(stored===void 0)throw new SessionInvariantError(`Lane ${JSON.stringify(this.name)} is missing result ${captured.lastOperationId}`);lastResult=stored.value}let stats=await reader.getStats(context),operation=captured.operation,operationSnapshot=null;if(operation!==null){let runningTools=[],streamingMessage,retry,deferred,readStreamingMessage=async responseEntryId=>reduceAssistantMessageFrames(await readAssistantFrames(reader,operation.meta.operationId,responseEntryId,context)),state2=operation.state;switch(state2.at){case"assistant.retry_wait":retry={attempt:state2.nextAttempt,maxAttempts:state2.generationContext.retryPolicy.maxAttempts,nextAttemptAt:state2.notBefore};break;case"assistant.effect_pending":streamingMessage=await readStreamingMessage(state2.responseEntryId);break;case"deferred.suspended":case"deferred.effect_pending":{let source=(await reader.getEntries([state2.sourceEntryId],context)).get(state2.sourceEntryId);if(source?.type!=="message"||source.message.role!=="assistant"||source.message.deferred===void 0)throw new SessionInvariantError("Deferred source is missing its assistant handle");deferred={handle:source.message.deferred,poll:state2.poll},state2.at==="deferred.effect_pending"&&(streamingMessage=await readStreamingMessage(state2.responseEntryId));break}case"tools":{let{batch}=state2,assistant=(await reader.getEntries([batch.assistantEntryId],context)).get(batch.assistantEntryId);if(assistant?.type!=="message"||assistant.message.role!=="assistant")throw new SessionInvariantError("Tool batch assistant entry is invalid");for(let call of batch.calls){if(call.status==="planned"||call.status==="completed")continue;let block=assistant.message.content[call.sourceIndex];if(block?.type!=="toolCall")throw new SessionInvariantError(`Tool call source index ${call.sourceIndex} does not name a tool-call block`);let args=await reader.getValue(operationToolArgs(operation.meta.operationId,batch.turnId,call.sourceIndex),context);if(call.status==="effect_pending"){if(args===void 0)throw new SessionInvariantError(`Tool call ${block.id} is missing persisted arguments`);let checkpoint=await reader.getValue(pendingToolOutput(operation.meta.operationId,call.resultEntryId),context);runningTools.push({status:"running",toolCallId:block.id,toolName:block.name,args:args.value,...checkpoint===void 0?{}:{result:checkpoint.value}});continue}let staged=await reader.getValue(pendingEntry(call.resultEntryId),context);if(staged?.value.type!=="message"||staged.value.payload.role!=="toolResult")throw new SessionInvariantError(`Tool call ${call.resultEntryId} is missing its staged result`);if(staged.value.payload.toolCallId!==block.id||staged.value.payload.toolName!==block.name)throw new SessionInvariantError(`Tool call ${call.resultEntryId} has a mismatched staged result`);runningTools.push({status:"settled",toolCallId:block.id,toolName:block.name,args:args?.value??block.arguments,result:toolResultFromMessage(staged.value.payload,call.terminate),isError:staged.value.payload.isError})}break}case"summary.retry_wait":retry={attempt:state2.nextAttempt,maxAttempts:state2.summaryContext.retryPolicy.maxAttempts,nextAttemptAt:state2.notBefore};break;default:break}operationSnapshot={id:operation.meta.operationId,kind:operation.meta.intent.kind,startedAt:operation.meta.startedAt,fromTipId:operation.meta.sourceTipId,status:operation.state.control.status==="cancel_requested"?"aborting":"open",...retry===void 0?{}:{retry},...deferred===void 0?{}:{deferred},...streamingMessage===void 0?{}:{streamingMessage},runningTools}}return structuredClone({lane:this.name,transcript,tipId:captured.tipId,...lastResult===void 0?{}:{lastResult},configuration:captured.configuration,stats,operation:operationSnapshot,queues,faulted:this.closedError instanceof HarnessFault})}async setConfiguration(update,event,context){await this.command(state=>{let configuration=update(state.configuration);return{kind:"commit",writes:[setValue(laneConfig(this.name),configuration)],next:{...state,configuration},materialize:()=>{},events:()=>[{...event(state.configuration,configuration),lane:this.name}]}},context)}async findEntries(query,context){query??={},this.assertOpen();let start=query.start??this.state.tipId;return start===null?[]:this.session.scanBranch({...query,start,order:query.order??"newestFirst"},context)}async findEntry(query,context){return query??={},(await this.findEntries({...query,limit:query.limit===void 0?1:Math.min(query.limit,1)},context))[0]}appendMessage(message,context){return this.append({type:"message",payload:message},context)}appendCustomEntry(customType,data,context){return this.append({type:"custom",customType,...data===void 0?{}:{payload:data}},context)}append(pending,context){if(this.assertOpen(),pending.type==="message"&&pending.payload.role==="assistant"&&pending.payload.stopReason==="pending")return Promise.reject(new SessionPendingAssistantMessageError);let id=this.session.idGenerator.next();return this.command(async(state,reader)=>{if(state.operation===null){let queued=inboxItems(state.inbox,"write"),captured=await Promise.all(queued.map(async item=>{let stored=await reader.getValue(pendingEntry(item.entryId),context);if(stored===void 0)throw new SessionInvariantError(`Pending write ${item.entryId} is missing its payload`);return pendingEntryWrite(item.entryId,stored.value)})),inbox2=withoutInboxItems(state.inbox,queued),queues2=queued.length===0?void 0:await readLaneQueues(reader,inbox2,context),entries=chainEntries(state.tipId,[...captured,pendingEntryWrite(id,pending)]);return{kind:"commit",writes:[...entries.map(entry=>insertEntry(entry)),...queued.map(item=>deleteValue(pendingEntry(item.entryId))),setValue(branchTip(this.name),id),setValue(laneState(this.name),durableLaneState(state,null,inbox2))],next:{...state,tipId:id,inbox:inbox2},materialize:()=>id,events:commit=>[...committedEntryEvents(entries,commit,this.name),...queues2===void 0?[]:[{type:"queue_update",queues:queues2,lane:this.name}]]}}let operation=state.operation,inbox=[...state.inbox,{entryId:id,kind:"write"}],queues=[...await readLaneQueues(reader,state.inbox,context),pending.type==="message"?{entryId:id,kind:"write",type:"message",message:pending.payload}:{entryId:id,kind:"write",type:"custom",customType:pending.customType,...pending.payload===void 0?{}:{data:pending.payload}}];return{kind:"commit",writes:[setValue(pendingEntry(id),pending),setValue(laneState(this.name),durableLaneState(state,operation.meta.operationId,inbox))],next:{...state,inbox},materialize:()=>id,events:()=>[{type:"queue_update",queues,lane:this.name}]}},context)}seal(error){return this.closedError??=error,this.activeDrive?.closeGate(error),this.signalStateChange(),this.idleOwner??Promise.resolve()}signalStateChange(){this.resolveStateChange();let resolveStateChange;this.stateChange=new Promise(resolve=>{resolveStateChange=resolve}),this.resolveStateChange=resolveStateChange}assertOpen(){if(this.closedError!==void 0)throw this.closedError}};function isSummaryState(state){return state.at.startsWith("summary.")}function stateMatchesIntent(intent,state){return intent.kind==="compaction"?isSummaryState(state)&&state.task.boundary.kind==="finish":intent.kind==="navigation"?state.at==="navigation.ready_to_commit"?!intent.summarize&&state.targetId===intent.targetId&&state.label===intent.label:intent.summarize&&isSummaryState(state)&&state.task.boundary.kind==="commit_navigation"&&state.task.boundary.targetId===intent.targetId&&state.task.boundary.label===intent.label&&state.task.customInstructions===intent.customInstructions:state.at!=="navigation.ready_to_commit"&&(!isSummaryState(state)||state.task.boundary.kind==="resume_checkpoint")}function classifyLaneStorage(lane,values){let{tip,configuration,laneState:laneState2}=values;if(tip===void 0&&configuration===void 0&&laneState2===void 0)return{kind:"absent"};if(tip!==void 0&&configuration===void 0&&laneState2===void 0)return{kind:"branch",tip};if(tip===void 0)throw new SessionInvariantError(`Lane ${JSON.stringify(lane)} is missing branch.tip`);if(configuration===void 0)throw new SessionInvariantError(`Lane ${JSON.stringify(lane)} is missing lane.config`);if(laneState2===void 0)throw new SessionInvariantError(`Lane ${JSON.stringify(lane)} is missing lane.state`);return{kind:"lane",tip,configuration,laneState:laneState2}}async function readLaneStorage(reader,lane,context){let[tip,configuration,laneState2]=await Promise.all([reader.getValue(branchTip(lane),context),reader.getValue(laneConfig(lane),context),reader.getValue(laneState(lane),context)]);return classifyLaneStorage(lane,{tip,configuration,laneState:laneState2})}function restoreSession(session,context){return session.mutate(async reader=>{let[tips,configurations,states2]=await Promise.all([reader.scanValues(branchTipInventoryPrefix(),context),reader.scanValues(laneConfig(""),context),reader.scanValues(laneState(""),context)]),tipByLane=new Map(tips.map(value2=>[value2.address.key,value2])),configurationByLane=new Map(configurations.map(value2=>[value2.address.key,value2])),stateByLane=new Map(states2.map(value2=>[value2.address.key,value2])),names=new Set([...tipByLane.keys(),...configurationByLane.keys(),...stateByLane.keys()]),restored=new Map;for(let lane of names){let stored=classifyLaneStorage(lane,{tip:tipByLane.get(lane),configuration:configurationByLane.get(lane),laneState:stateByLane.get(lane)});stored.kind==="lane"&&restored.set(lane,await restoreLaneState(reader,lane,stored,context))}return restored},context)}async function restoreLaneState(reader,lane,stored,context){let operationId=stored.laneState.value.currentOperationId,operation=null;if(operationId!==null){let[meta,state]=await Promise.all([reader.getValue(operationMeta(operationId),context),reader.getValue(operationState(operationId),context)]);if(meta===void 0)throw new SessionInvariantError(`Operation ${operationId} is missing op.meta`);if(state===void 0)throw new SessionInvariantError(`Operation ${operationId} is missing op.state`);if(meta.value.operationId!==operationId)throw new SessionInvariantError(`Operation ${operationId} metadata names operation ${JSON.stringify(meta.value.operationId)}`);if(meta.value.lane!==lane)throw new SessionInvariantError(`Operation ${operationId} belongs to lane ${JSON.stringify(meta.value.lane)}, not ${JSON.stringify(lane)}`);if(!stateMatchesIntent(meta.value.intent,state.value))throw new SessionInvariantError(`Operation ${operationId} intent ${meta.value.intent.kind} does not match state ${state.value.at}`);operation={meta:meta.value,state:state.value}}return{tipId:stored.tip.value,configuration:stored.configuration.value,inbox:stored.laneState.value.inbox,lastOperationId:stored.laneState.value.lastOperationId,operation}}var Harness=class{constructor(options,seed,restored){this.lanesByName=new Map,this.session=options.session,this.models=options.models,this.seed=seed,this.events=new HarnessEventBus,this.hooks=new HookRegistry((error,hook,lane,context)=>this.events.emit({type:"handler_error",kind:"hook",hook,error:error.message,...error.stack===void 0?{}:{stack:error.stack},lane},context)),this.configStore={value:{tools:options.tools??[],resources:options.resources??{},streamOptions:options.streamOptions??{},retryPolicy:options.retry??DEFAULT_RETRY_POLICY,compaction:options.compaction??DEFAULT_COMPACTION_SETTINGS,steeringMode:options.steeringMode??"all",followUpMode:options.followUpMode??"all",toolExecution:options.toolExecution??"parallel",toolContext:options.toolContext,systemPrompt:options.systemPrompt,toProviderMessages:options.toProviderMessages??(messages=>convertToLlm(messages)),entryProjectors:options.entryProjectors??{}}};for(let[name,state]of restored)this.lanesByName.set(name,this.buildLane(name,state))}async lane(name,optionsOrContext,maybeContext){if(this.assertOpen(),name.length===0||name.includes("\0")){let reason=name.length===0?"lane name must not be empty":"lane name must not contain \\u0000";throw new InvalidLane({lane:name,reason,message:`Invalid lane ${JSON.stringify(name)}: ${reason}`})}let options=maybeContext===void 0?{}:optionsOrContext,context=maybeContext??optionsOrContext,lane,delivery;try{await this.session.mutate(async mutator=>{if(this.assertOpen(),lane=this.lanesByName.get(name),lane!==void 0)return;let stored=await readLaneStorage(mutator,name,context);if(stored.kind==="lane"){let restored=await restoreLaneState(mutator,name,stored,context);lane=this.buildLane(name,restored),this.lanesByName.set(name,lane);return}let tipId=stored.kind==="branch"?stored.tip.value:options.createAt??null;if(stored.kind==="absent"&&tipId!==null&&!(await mutator.getEntries([tipId],context)).has(tipId))throw new UnknownTarget({targetId:tipId,message:`Unknown target: ${tipId}`});let attachedConfiguration={model:{...this.seed.model},thinkingLevel:this.seed.thinkingLevel,activeToolNames:[...this.seed.activeToolNames]},state={tipId,configuration:attachedConfiguration,inbox:[],lastOperationId:null,operation:null},writes=[...stored.kind==="absent"?[setValue(branchTip(name),tipId)]:[],setValue(laneConfig(name),attachedConfiguration),setValue(laneState(name),{currentOperationId:null,lastOperationId:null,inbox:[]})];await mutator.commit(writes,context),lane=this.buildLane(name,state),this.lanesByName.set(name,lane),delivery=this.events.emitBatch([{type:"lane_created",lane:name,at:tipId}],context)},context)}catch(error){throw this.closedError!==void 0?this.closedError:error instanceof InvalidLane||error instanceof UnknownTarget?error:this.fault(error,context)}if(await delivery,lane===void 0)throw this.fault(new SessionInvariantError(`Lane ${JSON.stringify(name)} was not published`),context);return lane}async lanes(context){return this.assertOpen(),(await Promise.all([...this.lanesByName.values()].map(lane=>lane.inspectExecution(context)))).map(execution=>({name:execution.lane,tipId:execution.tipId,operation:execution.current}))}getName(context){return this.assertOpen(),this.session.getName(context)}async setName(name,context){this.assertOpen();let delivery;try{await this.session.mutate(async mutator=>{this.assertOpen(),await mutator.commit([name===void 0?deleteValue(sessionName):setValue(sessionName,name)],context),delivery=this.events.emitBatch([{type:"value_update",value:"session_name",name}],context)},context)}catch(error){throw this.closedError!==void 0?this.closedError:this.fault(error,context)}await delivery}getLabel(targetId,context){return this.assertOpen(),this.session.getLabel(targetId,context)}async setLabel(targetId,label,context){this.assertOpen();let delivery;try{await this.session.mutate(async mutator=>{this.assertOpen();let address=entryLabel(targetId);await mutator.commit([label===void 0?deleteValue(address):setValue(address,label)],context),delivery=this.events.emitBatch([{type:"value_update",value:"entry_label",targetId,label}],context)},context)}catch(error){throw this.closedError!==void 0?this.closedError:this.fault(error,context)}await delivery}getTools(context){return this.getConfig("tools",context)}setTools(tools,context){return validateToolNames(tools),this.setConfig("tools",tools,()=>({type:"config_update",property:"tools"}),context)}getResources(context){return this.getConfig("resources",context)}setResources(resources,context){return this.setConfig("resources",resources,()=>({type:"config_update",property:"resources"}),context)}getStreamOptions(context){return this.getConfig("streamOptions",context)}setStreamOptions(options,context){return this.setConfig("streamOptions",options,(previous,value2)=>({type:"config_update",property:"streamOptions",previous,value:value2}),context)}getRetryPolicy(context){return this.getConfig("retryPolicy",context)}setRetryPolicy(policy,context){return validateRetryPolicy(policy),this.setConfig("retryPolicy",policy,(previous,value2)=>({type:"config_update",property:"retryPolicy",previous,value:value2}),context)}getCompactionSettings(context){return this.getConfig("compaction",context)}setCompactionSettings(compaction,context){return validateCompactionSettings(compaction),this.setConfig("compaction",compaction,(previous,value2)=>({type:"config_update",property:"compactionSettings",previous,value:value2}),context)}getSteeringMode(context){return this.getConfig("steeringMode",context)}setSteeringMode(steeringMode,context){return this.setConfig("steeringMode",steeringMode,(previous,value2)=>({type:"config_update",property:"steeringMode",previous,value:value2}),context)}getFollowUpMode(context){return this.getConfig("followUpMode",context)}setFollowUpMode(followUpMode,context){return this.setConfig("followUpMode",followUpMode,(previous,value2)=>({type:"config_update",property:"followUpMode",previous,value:value2}),context)}async watchSession(_context){throw new SliceNotImplemented("watchSession")}fault(cause,context){if(this.faultError!==void 0)return this.faultError;if(this.closedError!==void 0)return this.closedError;let normalized=cause instanceof Error?cause:new Error(String(cause)),fault=new HarnessFault("AgentHarness storage or invariant fault",normalized);this.faultError=fault;for(let lane of this.lanesByName.values())lane.seal(fault);return this.hooks.close(fault),this.events.emit({type:"fault",code:"harness_fault",message:fault.message},context),this.events.close(fault),fault}close(context){if(this.closePromise!==void 0)return this.closePromise;let error=new HarnessClosed;this.closedError=error;let idleCallbacks=[...this.lanesByName.values()].map(lane=>lane.seal(error));this.hooks.close(error),this.events.close(error);let sessionClose=this.session.close(context);return this.closePromise=Promise.all([sessionClose,...idleCallbacks]).then(()=>{}),this.closePromise}buildLane(name,state){return new Lane(name,this.session,this.models,this.hooks,state,(cause,context)=>this.fault(cause,context),(events,context)=>this.events.emitBatch(events,context),(snapshot,filter,context,resnapshot)=>this.events.watch(snapshot,filter,context,resnapshot),()=>this.configStore.value)}async getConfig(key,_context){return this.assertOpen(),this.configStore.value[key]}async setConfig(key,value2,event,context){this.assertOpen();let previous=this.configStore.value[key];this.configStore.value={...this.configStore.value,[key]:value2},await this.events.emit(event(previous,value2),context)}assertOpen(){if(this.faultError!==void 0)throw this.faultError;if(this.closedError!==void 0)throw this.closedError}};async function createAgentHarness(options,context){let tools=options.tools??[];validateToolNames(tools),validateRetryPolicy(options.retry??DEFAULT_RETRY_POLICY),validateCompactionSettings(options.compaction??DEFAULT_COMPACTION_SETTINGS);let seed={model:{provider:options.model.provider,modelId:options.model.id},thinkingLevel:options.thinkingLevel??"off",activeToolNames:[...options.activeToolNames??tools.map(tool=>tool.name)]};try{let restored=await restoreSession(options.session,context),open=[...restored].flatMap(([lane,state])=>{let operation=state.operation;return operation===null?[]:[{lane,operationId:operation.meta.operationId,kind:operation.meta.intent.kind,startedAt:operation.meta.startedAt,...operation.state.control.status==="cancel_requested"?{aborting:!0}:{}}]});return{harness:new Harness(options,seed,restored),open}}catch(error){throw new HarnessFault("AgentHarness storage or invariant fault",error)}}var AgentHarness={create:createAgentHarness};function upsertTool(operation,tool){let index=operation.runningTools.findIndex(candidate=>candidate.toolCallId===tool.toolCallId);index===-1?operation.runningTools.push(tool):operation.runningTools[index]=tool}function matchingOperation(snapshot,operationId){return snapshot.operation?.id===operationId?snapshot.operation:void 0}function reduceLaneSnapshot(snapshot,event){if(!("lane"in event&&event.lane!==void 0&&event.lane!==snapshot.lane&&event.type!=="usage"))switch(event.type){case"run_start":snapshot.operation={id:event.runId,kind:"run",startedAt:event.startedAt,fromTipId:snapshot.tipId,status:"open",runningTools:[]};return;case"compaction_start":if(snapshot.operation!==null)return;snapshot.operation={id:event.runId,kind:"compaction",startedAt:event.startedAt,fromTipId:snapshot.tipId,status:"open",runningTools:[]};return;case"navigation_start":snapshot.operation={id:event.runId,kind:"navigation",startedAt:event.startedAt,fromTipId:snapshot.tipId,status:"open",runningTools:[]};return;case"operation_abort":{let operation=matchingOperation(snapshot,event.operationId);operation!==void 0&&(operation.status="aborting");return}case"run_resume":{let operation=matchingOperation(snapshot,event.runId);operation!==void 0&&delete operation.deferred;return}case"run_suspend":{let operation=matchingOperation(snapshot,event.runId);if(operation===void 0)return;delete operation.streamingMessage,operation.deferred={handle:event.deferred,poll:event.poll};return}case"retry_scheduled":{let operation=matchingOperation(snapshot,event.runId);operation!==void 0&&(operation.retry={attempt:event.attempt,maxAttempts:event.maxAttempts,nextAttemptAt:event.notBefore});return}case"retry_start":case"retry_end":{let operation=matchingOperation(snapshot,event.runId);operation!==void 0&&delete operation.retry;return}case"message_start":{if(event.runId===void 0||event.message.role!=="assistant"||event.message.stopReason!=="pending")return;let operation=matchingOperation(snapshot,event.runId);operation!==void 0&&(operation.streamingMessage=event.message);return}case"message_update":{if(event.message.role!=="assistant")return;let operation=matchingOperation(snapshot,event.runId);operation!==void 0&&(operation.streamingMessage=event.message);return}case"message_end":{if(event.runId===void 0)return;let operation=matchingOperation(snapshot,event.runId);operation!==void 0&&delete operation.streamingMessage;return}case"tool_start":{let operation=matchingOperation(snapshot,event.runId);if(operation===void 0)return;upsertTool(operation,{status:"running",toolCallId:event.toolCallId,toolName:event.toolName,args:event.args});return}case"tool_update":{let tool=matchingOperation(snapshot,event.runId)?.runningTools.find(candidate=>candidate.toolCallId===event.toolCallId);tool?.status==="running"&&(tool.result=event.partialResult);return}case"tool_end":{let operation=matchingOperation(snapshot,event.runId);if(operation===void 0)return;let index=operation.runningTools.findIndex(candidate=>candidate.toolCallId===event.toolCallId),current=operation.runningTools[index];if(current===void 0)return;operation.runningTools[index]={status:"settled",toolCallId:event.toolCallId,toolName:event.toolName,args:current.args,result:event.result,isError:event.isError};return}case"entry_added":{if(event.entry.type==="message"&&event.entry.message.role==="toolResult"){let operation=snapshot.operation;if(operation!==null){let toolCallId=event.entry.message.toolCallId,index=operation.runningTools.findIndex(candidate=>candidate.toolCallId===toolCallId);index!==-1&&operation.runningTools.splice(index,1)}}event.entry.type==="compaction"?snapshot.transcript.splice(0,snapshot.transcript.length,event.entry):snapshot.transcript.push(event.entry),snapshot.tipId=event.entry.id,event.entry.type==="message"&&(snapshot.stats.messageCount+=1);return}case"queue_update":snapshot.queues=event.queues;return;case"usage":snapshot.stats.usage=event.totals;return;case"config_update":if(!("lane"in event)||event.lane!==snapshot.lane)return;switch(event.property){case"model":snapshot.configuration.model=event.value;return;case"thinkingLevel":snapshot.configuration.thinkingLevel=event.value;return;case"activeTools":snapshot.configuration.activeToolNames=event.value;return}return;case"run_end":{let operation=matchingOperation(snapshot,event.runId);if(operation?.kind!=="run")return;let record={operationId:event.runId,kind:"run",status:event.status,...event.status==="failed"?{error:event.error}:{},fromTipId:event.fromTipId,tipId:event.tipId,startedAt:operation.startedAt,endedAt:event.endedAt};snapshot.lastResult=record,snapshot.operation=null,snapshot.tipId=event.tipId;return}case"compaction_end":{let operation=matchingOperation(snapshot,event.runId);if(operation?.kind!=="compaction")return;let record={operationId:event.runId,kind:"compaction",status:event.status,...event.status==="failed"?{error:event.error}:{},fromTipId:operation.fromTipId,tipId:snapshot.tipId,startedAt:operation.startedAt,endedAt:event.endedAt};snapshot.lastResult=record,snapshot.operation=null;return}case"navigation_end":return"rebase";case"fault":snapshot.faulted=!0;return;case"handler_error":case"turn_start":case"turn_end":case"value_update":case"lane_created":return}}function selectBranchFork(options,source){if(source.tip===void 0)throw new Error(`Unknown source branch: ${options.branch}`);let requested=options.entryId??source.tip,found=requested===null,destinationTip=null,entryId=source.tip;for(;entryId!==null;){let parentId=source.getParent(entryId);if(parentId===void 0)throw new Error(`Corrupt source branch: missing parent ${entryId}`);entryId===requested?(found=!0,destinationTip=options.position==="before"?parentId:entryId,options.position!=="before"&&source.selectEntry(entryId)):found&&source.selectEntry(entryId),entryId=parentId}if(!found)throw new Error(`Fork entry ${requested} is not on source branch ${JSON.stringify(options.branch)}`);return{scope:"branch",branch:options.branch,destinationTip}}function projectForkCurrentStateWrite(write,plan,isEntryCopied){switch(write.namespace){case"pi.session.name":return write;case"pi.entry.label":return isEntryCopied(write.key)?write:void 0;case"pi.branch.tip":return plan.scope==="tree"?write:write.key===plan.branch?{...write,value:plan.destinationTip}:void 0;case"pi.lane.config":return plan.scope==="tree"||write.key===plan.branch?write:void 0;case"pi.lane.state":return plan.scope==="tree"||write.key===plan.branch?{...write,value:{currentOperationId:null,lastOperationId:null,inbox:[]}}:void 0;case"pi.result":return}if(!(write.namespace.startsWith("pi.op.")||write.namespace.startsWith("pi.pending."))){if(write.namespace==="pi"||write.namespace.startsWith("pi."))throw new Error(`Unknown reserved fork namespace: ${write.namespace}`);return plan.scope==="tree"?write:void 0}}function storedValuesInNamespace(values,address){return values.filter(stored=>stored.address.namespace===address.namespace)}function findStoredValue(values,address){return values.find(stored=>stored.address.namespace===address.namespace&&stored.address.key===address.key)}function createForkSnapshot(source,options){let sourceEntries=new Map(source.entries.map(entry=>[entry.id,entry])),sourceTips=storedValuesInNamespace(source.scalarValues,branchTip(""));validateForkSourceSnapshot(source,sourceEntries,sourceTips,options);let{entryIds,plan}=selectForkContents(sourceEntries,sourceTips,options),entries=new Map;for(let id of entryIds)entries.set(id,sourceEntries.get(id));let scalarValues=[],nextSeq=Math.max(0,...[...entries.values()].map(entry=>entry.seq))+1;for(let stored of source.scalarValues){let projected=projectForkCurrentStateWrite({kind:"value",op:"set",seq:stored.seq,namespace:stored.address.namespace,key:stored.address.key,value:stored.value},plan,entryId=>entryIds.has(entryId));projected!==void 0&&scalarValues.push({address:value(projected.namespace,projected.key),value:projected.value,seq:nextSeq++})}return{entries,scalarValues,nextSeq}}function selectForkContents(sourceEntries,sourceTips,options){let entryIds=new Set;if(options.scope==="tree"){for(let id of sourceEntries.keys())entryIds.add(id);return{entryIds,plan:{scope:"tree"}}}let sourceTip=sourceTips.find(stored=>stored.address.key===options.branch),plan=selectBranchFork(options,{tip:sourceTip?.value,getParent:entryId=>sourceEntries.get(entryId)?.parentId,selectEntry:entryId=>entryIds.add(entryId)});return{entryIds,plan}}function validateForkSourceSnapshot(source,sourceEntries,sourceTips,options){let sourceTipKeys=new Set(sourceTips.map(stored=>stored.address.key));for(let stored of source.scalarValues)if((stored.address.namespace===laneConfig("").namespace||stored.address.namespace===laneState("").namespace)&&!sourceTipKeys.has(stored.address.key))throw new Error(`Source session branch ${JSON.stringify(stored.address.key)} is missing branch.tip`);for(let tip of sourceTips){let configuration=findStoredValue(source.scalarValues,laneConfig(tip.address.key)),state=findStoredValue(source.scalarValues,laneState(tip.address.key));if(configuration===void 0!=(state===void 0))throw new Error(`Source session branch ${JSON.stringify(tip.address.key)} has incomplete lane state`);if(options.scope==="branch"&&tip.address.key===options.branch&&configuration===void 0)throw new Error(`Source branch ${JSON.stringify(options.branch)} is not a configured AgentLane`);if((source.entriesComplete!==!1||options.scope==="tree")&&tip.value!==null&&!sourceEntries.has(tip.value))throw new Error(`Source session branch ${JSON.stringify(tip.address.key)} has an unknown tip`)}}var JSONL_STORAGE_VERSION=1;function isRecord(value2){return typeof value2=="object"&&value2!==null&&!Array.isArray(value2)}function isSafeIntegerAtLeast(value2,minimum){return Number.isSafeInteger(value2)&&value2>=minimum}function isLegacyV3SessionHeader(value2){return isRecord(value2)&&value2.type==="session"&&value2.version===3&&typeof value2.id=="string"&&typeof value2.cwd=="string"&&typeof value2.timestamp=="string"&&Number.isFinite(Date.parse(value2.timestamp))&&(value2.parentSession===void 0||typeof value2.parentSession=="string")}function isJsonlStorageHeader(value2){return isRecord(value2)&&value2.kind==="header"&&value2.v===4&&typeof value2.id=="string"&&typeof value2.cwd=="string"&&isSafeIntegerAtLeast(value2.storageVersion,1)&&isSafeIntegerAtLeast(value2.createdAt,0)&&(value2.nextSeq===void 0||isSafeIntegerAtLeast(value2.nextSeq,1))&&(value2.parentSessionId===void 0||typeof value2.parentSessionId=="string")&&(value2.legacyParentSessionPath===void 0||typeof value2.legacyParentSessionPath=="string")}function parseJsonlSessionHeader(line){let value2;try{value2=JSON.parse(line)}catch(error){return err(new Error("Invalid JSONL session header: not valid JSON",{cause:error}))}return isJsonlStorageHeader(value2)?ok({format:"v4",header:value2}):isLegacyV3SessionHeader(value2)?ok({format:"v3-legacy",header:value2}):err(new Error("Unsupported JSONL session header"))}function fileValue(result,action){if(!result.ok)throw new Error(`${action}: ${result.error.message}`,{cause:result.error});return result.value}async function readJsonlHeader(reader,path,context){let line=fileValue(await reader.readLine(context),`Failed to read JSONL storage ${path}`);if(line===void 0||!line.terminated||line.text==="")throw new Error(`Invalid JSONL storage ${path}: missing header`);let parsed=parseJsonlSessionHeader(line.text);if(!parsed.ok)throw new Error(`Invalid JSONL storage ${path}: invalid header`,{cause:parsed.error});return parsed.value}function isRecord2(value2){return typeof value2=="object"&&value2!==null&&!Array.isArray(value2)}function requireSafeInteger(value2,field,minimum){if(!Number.isSafeInteger(value2)||value2<minimum)throw new Error(`Invalid JSONL ${field}`)}function parseCommittedWrite(value2){if(!isRecord2(value2))throw new Error("Invalid JSONL transaction write");switch(requireSafeInteger(value2.seq,"write seq",1),value2.kind){case"entry":return requireSafeInteger(value2.timestamp,"entry timestamp",0),value2;case"usage":return value2;case"value":if(value2.op==="set"||value2.op==="delete")return value2;throw new Error(`Invalid JSONL value operation: ${String(value2.op)}`);case"list":if(value2.op==="append"||value2.op==="delete")return value2;throw new Error(`Invalid JSONL list operation: ${String(value2.op)}`);default:throw new Error(`Invalid JSONL write kind: ${String(value2.kind)}`)}}function parseJsonlTransaction(line){let value2;try{value2=JSON.parse(line)}catch(error){throw new Error("Invalid JSONL transaction: not valid JSON",{cause:error})}return(Array.isArray(value2)?value2:[value2]).map(parseCommittedWrite)}function serializeJsonlTransaction(writes){return JSON.stringify(writes.length===1?writes[0]:writes)}async function publishFileAtomically(fileSystem,destinationPath,context,writeContent){let tempPath=`${destinationPath}.tmp`;try{fileValue(await fileSystem.writeFile(tempPath,"",context),`Failed to stage JSONL storage ${destinationPath}`),await writeContent(async content=>{fileValue(await fileSystem.appendFile(tempPath,content,context),`Failed to append JSONL storage ${destinationPath}`)}),fileValue(await fileSystem.renameFile(tempPath,destinationPath,context),`Failed to publish JSONL storage ${destinationPath}`)}catch(error){throw await fileSystem.remove(tempPath,{force:!0},context),error}}async function publishJsonl(fileSystem,destinationPath,header,context,writeTransactions){await publishFileAtomically(fileSystem,destinationPath,context,async append=>{await append(`${JSON.stringify(header)}
201
+ `),await writeTransactions(writes=>append(`${serializeJsonlTransaction(writes)}
202
+ `))})}function physicalKey(namespace,key){return`${namespace}\0${key}`}async function readJsonlForkHeader(reader,source,context){let parsed=await readJsonlHeader(reader,source.path,context);if(parsed.format!=="v4")throw new Error(`Invalid JSONL storage ${source.path}: expected format 4 header`);let header=parsed.header;if(header.id!==source.id||header.cwd!==source.cwd)throw new Error(`Session identity does not match header: ${source.id}`);if(header.storageVersion!==1)throw new Error(`Session ${source.id} uses unsupported storage version ${header.storageVersion}`);return header}function reachesForkBoundary(writes,stopBeforeSeq){if(stopBeforeSeq===void 0||writes.length===0)return!1;let first=writes[0],last=writes.at(-1);if(first.seq>=stopBeforeSeq)return!0;if(last.seq>=stopBeforeSeq)throw new Error(`JSONL transaction crosses fork sequence boundary ${stopBeforeSeq}`);return!1}async function*readJsonlForkTransactions(reader,path,stopBeforeSeq,context){for(;;){let line=fileValue(await reader.readLine(context),`Failed to read JSONL fork source ${path}`);if(line===void 0||!line.terminated)break;let writes=parseJsonlTransaction(line.text);if(reachesForkBoundary(writes,stopBeforeSeq))break;yield writes}}var JsonlForkIndex=class{constructor(){this.currentScalarSeqs=new Map,this.branchTips=new Map,this.firstSurvivingListSeqs=new Map,this.entryParents=new Map,this.copiedEntryIds=new Set,this.laneConfigs=new Set,this.laneStates=new Set}applyEntry(id,parentId){this.entryParents.set(id,parentId)}applyWrites(writes){for(let write of writes)switch(write.kind){case"entry":this.applyEntry(write.id,write.parentId);break;case"value":{let key=physicalKey(write.namespace,write.key);write.op==="delete"?this.currentScalarSeqs.delete(key):this.currentScalarSeqs.set(key,write.seq),this.applyLaneValue(write);break}case"list":{let key=physicalKey(write.namespace,write.key);write.op==="delete"?this.firstSurvivingListSeqs.delete(key):this.firstSurvivingListSeqs.has(key)||this.firstSurvivingListSeqs.set(key,write.seq);break}case"usage":break}}applyLaneValue(write){let present=write.op==="set";switch(write.namespace){case"pi.branch.tip":present?this.branchTips.set(write.key,write.value):this.branchTips.delete(write.key);break;case"pi.lane.config":present?this.laneConfigs.add(write.key):this.laneConfigs.delete(write.key);break;case"pi.lane.state":present?this.laneStates.add(write.key):this.laneStates.delete(write.key);break}}getBranchTip(branch){return this.branchTips.get(branch)}hasCompleteLane(branch){return this.laneConfigs.has(branch)&&this.laneStates.has(branch)}getCurrentScalarSeq(namespace,key){return this.currentScalarSeqs.get(physicalKey(namespace,key))}isSurvivingListElement(namespace,key,seq){let firstSeq=this.firstSurvivingListSeqs.get(physicalKey(namespace,key));return firstSeq!==void 0&&seq>=firstSeq}getParent(entryId){return this.entryParents.get(entryId)}selectEntry(entryId){this.copiedEntryIds.add(entryId)}isEntrySelected(entryId){return this.copiedEntryIds.has(entryId)}};function selectJsonlFork(index,options){if(options.scope==="tree")return{scope:"tree"};let plan=selectBranchFork(options,{tip:index.getBranchTip(options.branch),getParent:entryId=>index.getParent(entryId),selectEntry:entryId=>index.selectEntry(entryId)});if(!index.hasCompleteLane(options.branch))throw new Error(`Source branch ${JSON.stringify(options.branch)} is not a configured AgentLane`);return plan}function projectJsonlForkWrite(write,index,plan,isEntryCopied){switch(write.kind){case"entry":return isEntryCopied(write.id)?write:void 0;case"value":return write.op!=="set"||index.getCurrentScalarSeq(write.namespace,write.key)!==write.seq?void 0:projectForkCurrentStateWrite(write,plan,isEntryCopied);case"list":return write.op!=="append"||!index.isSurvivingListElement(write.namespace,write.key,write.seq)?void 0:projectForkCurrentStateWrite(write,plan,isEntryCopied);case"usage":return}}async function indexForkInput(input,fileSystem,context){let index=new JsonlForkIndex;if(input.kind==="legacy-v3"){for(let entry of input.normalized.entryStructures())index.applyEntry(entry.id,entry.parentId);return index.applyWrites(input.normalized.values),{index,nextSeq:input.normalized.nextSeq}}let reader=fileValue(await fileSystem.openTextLineReader(input.metadata.path,context),`Failed to open JSONL fork source ${input.metadata.path}`);try{let header=await readJsonlForkHeader(reader,input.metadata,context),stopBeforeSeq=input.kind==="open"?input.nextSeq:void 0,highestCompleteSeq=0;for await(let writes of readJsonlForkTransactions(reader,input.metadata.path,stopBeforeSeq,context))index.applyWrites(writes),writes.length!==0&&(highestCompleteSeq=writes.at(-1).seq);return{index,nextSeq:input.kind==="open"?input.nextSeq:Math.max(header.nextSeq??1,highestCompleteSeq+1)}}finally{await reader.close(context)}}async function*streamForkWrites(input,fileSystem,stopBeforeSeq,isEntryCopied,context){if(input.kind==="legacy-v3"){yield*input.normalized.writes(context,isEntryCopied);return}let reader=fileValue(await fileSystem.openTextLineReader(input.metadata.path,context),`Failed to open JSONL fork source ${input.metadata.path}`);try{await readJsonlForkHeader(reader,input.metadata,context);for await(let writes of readJsonlForkTransactions(reader,input.metadata.path,stopBeforeSeq,context))yield*writes}finally{await reader.close(context)}}async function runJsonlFork(options,context){let{index,nextSeq}=await indexForkInput(options.input,options.fileSystem,context),fork=options.fork;options.input.kind==="legacy-v3"&&fork.scope==="branch"&&fork.entryId!==void 0&&(fork={...fork,entryId:options.input.normalized.translateForkEntryId(fork.entryId)});let plan=selectJsonlFork(index,fork),isEntryCopied=entryId=>plan.scope==="tree"?!0:index.isEntrySelected(entryId);await publishJsonl(options.fileSystem,options.destinationPath,{...options.destinationHeader,nextSeq},context,async append=>{let sourceWrites=streamForkWrites(options.input,options.fileSystem,nextSeq,isEntryCopied,context);for await(let write of sourceWrites){let projected=projectJsonlForkWrite(write,index,plan,isEntryCopied);projected!==void 0&&await append([projected])}})}async function resolveLegacyV3ParentSessionId(fileSystem,parentSessionPath,context){let lines=await fileSystem.readTextLines(parentSessionPath,{maxLines:1},context);if(!lines.ok||lines.value[0]===void 0)return;let parsed=parseJsonlSessionHeader(lines.value[0]);return parsed.ok?parsed.value.header.id:void 0}async function metadataFromLegacyV3Header(fileSystem,header,context){let metadata={id:header.id,createdAt:Date.parse(header.timestamp),storageVersion:1,cwd:header.cwd};if(header.parentSession!==void 0){let parentSessionId=await resolveLegacyV3ParentSessionId(fileSystem,header.parentSession,context);parentSessionId!==void 0?metadata.parentSessionId=parentSessionId:metadata.legacyParentSessionPath=header.parentSession}return metadata}async function normalizeLegacyV3Header(fileSystem,header,context){return{v:4,kind:"header",...await metadataFromLegacyV3Header(fileSystem,header,context)}}function parseLegacyV3Entry(line){let entry;try{entry=JSON.parse(line)}catch(error){throw new Error("Invalid legacy v3 JSONL record: not valid JSON",{cause:error})}let recordType=entry?.type;if(recordType!=="message"&&recordType!=="custom"&&recordType!=="custom_message"&&recordType!=="branch_summary"&&recordType!=="compaction"&&recordType!=="model_change"&&recordType!=="thinking_level_change"&&recordType!=="active_tools_change"&&recordType!=="session_info"&&recordType!=="label")throw new Error(`Unsupported legacy v3 record type: ${String(recordType)}`);return entry}function importedCustomMessage(entry){return{role:"custom",customType:entry.customType,content:entry.content,details:entry.details,display:entry.display,timestamp:Date.parse(entry.timestamp)}}function isRetainedEntry(entry){return entry.type!=="model_change"&&entry.type!=="thinking_level_change"&&entry.type!=="active_tools_change"&&entry.type!=="session_info"&&entry.type!=="label"}function createLegacyIdResolver(entries){return legacyId=>{if(legacyId===null)return null;let mappedId=entries.get(legacyId)?.mappedId;if(mappedId===void 0)throw new Error(`Missing legacy v3 entry reference: ${legacyId}`);return mappedId}}function resolveBranchSummaryFromId(resolveLegacyId,legacyFromId){return legacyFromId==="root"?null:resolveLegacyId(legacyFromId)}function projectContextMessage(entry,resolveLegacyId){switch(entry.type){case"message":return entry.message;case"custom_message":return importedCustomMessage(entry);case"branch_summary":return entry.summary?createBranchSummaryMessage(entry.summary,resolveBranchSummaryFromId(resolveLegacyId,entry.fromId),entry.timestamp):void 0;case"compaction":return createCompactionSummaryMessage(entry.summary,entry.tokensBefore,entry.timestamp);case"custom":case"model_change":case"thinking_level_change":case"active_tools_change":case"session_info":case"label":return}}function*retainedTailStructure(compaction,entriesById){let currentId=compaction.parentId;for(;currentId!==null;){let entry=entriesById.get(currentId);if(yield entry,currentId===compaction.firstKeptEntryId)return;currentId=entry.parentId}throw new Error(`Legacy v3 compaction ${compaction.id} firstKeptEntryId is not on its parent branch: ${compaction.firstKeptEntryId}`)}function normalizeRetainedEntry(entry,indexed,retainedTail,resolveLegacyId){let committedBase={kind:"entry",id:indexed.mappedId,parentId:resolveLegacyId(indexed.parentId),seq:indexed.seq,timestamp:Date.parse(entry.timestamp)};return entry.type==="message"?{...committedBase,type:"message",message:entry.message}:entry.type==="custom_message"?{...committedBase,type:"message",message:importedCustomMessage(entry)}:entry.type==="branch_summary"?{...committedBase,type:"branch_summary",fromId:resolveBranchSummaryFromId(resolveLegacyId,entry.fromId),summary:entry.summary,details:entry.details,usage:entry.usage,fromHook:entry.fromHook??!1}:entry.type==="compaction"?{...committedBase,type:"compaction",summary:entry.summary,retainedTail,tokensBefore:entry.tokensBefore,details:entry.details,usage:entry.usage,fromHook:entry.fromHook??!1}:{...committedBase,type:"custom",customType:entry.customType,data:entry.data}}function selectedConfiguration(entriesById,selectedId){let remaining=new Set(["model_change","thinking_level_change","active_tools_change"]),model,thinkingLevel,activeToolNames,currentId=selectedId;for(;currentId!==null&&remaining.size!==0;){let entry=entriesById.get(currentId);if(remaining.delete(entry.type))switch(entry.type){case"model_change":model={provider:entry.provider,modelId:entry.modelId};break;case"thinking_level_change":thinkingLevel=entry.thinkingLevel;break;case"active_tools_change":activeToolNames=[...entry.activeToolNames];break}currentId=entry.parentId}if(!(model===void 0||thinkingLevel===void 0))return{model,thinkingLevel,activeToolNames:activeToolNames??[]}}function indexLegacyV3Entry(entry,lineNumber,seq,entries){let mappedParentId=entry.parentId===null?null:entries.get(entry.parentId)?.mappedId;if(mappedParentId===void 0)throw new Error(`Legacy v3 entry ${entry.id} has a missing or forward parent at line ${lineNumber}: ${entry.parentId}`);let structure={id:entry.id,parentId:entry.parentId,mappedId:mappedParentId};if(!isRetainedEntry(entry))switch(entry.type){case"label":return{...structure,type:entry.type,targetId:entry.targetId,label:entry.label};case"model_change":return{...structure,type:entry.type,provider:entry.provider,modelId:entry.modelId};case"thinking_level_change":return{...structure,type:entry.type,thinkingLevel:entry.thinkingLevel};case"active_tools_change":return{...structure,type:entry.type,activeToolNames:entry.activeToolNames};case"session_info":return{...structure,type:entry.type}}if(entry.id===null)throw new Error("Legacy v3 entry reference has no retained ancestor: null");let retained={...structure,mappedId:uuidv7(Date.parse(entry.timestamp)),seq};switch(entry.type){case"branch_summary":return{...retained,type:entry.type,fromId:entry.fromId};case"compaction":return{...retained,type:entry.type,firstKeptEntryId:entry.firstKeptEntryId};default:return{...retained,type:entry.type}}}function legacyEntryUsage(entry){switch(entry.type){case"message":return entry.message.role==="assistant"||entry.message.role==="toolResult"?entry.message.usage:void 0;case"compaction":case"branch_summary":return entry.usage;default:return}}async function readLegacyV3Inventory(reader,context){let entries=new Map,nextSeq=1,importedUsage=emptyUsage(),name,finalId=null;for(;;){let line=fileValue(await reader.readLine(context),"Failed to read legacy v3 source");if(line===void 0||!line.terminated)break;let lineNumber=entries.size+2,entry=parseLegacyV3Entry(line.text);if(entries.has(entry.id))throw new Error(`Duplicate legacy v3 entry id: ${entry.id}`);let indexed=indexLegacyV3Entry(entry,lineNumber,nextSeq,entries);entries.set(entry.id,indexed),isRetainedEntry(indexed)&&nextSeq++,finalId=entry.id,entry.type==="session_info"&&(name=entry.name);let usage=legacyEntryUsage(entry);usage!==void 0&&(importedUsage=addUsage(importedUsage,usage))}return{entries,nextSeq,importedUsage,name,finalId}}function normalizeLegacyV3Values(inventory){let{entries,name,finalId}=inventory,resolveLegacyId=createLegacyIdResolver(entries),nextSeq=inventory.nextSeq,values=[];name&&values.push({...setValue(sessionName,name),seq:nextSeq++});let labels=new Map;for(let entry of entries.values()){if(entry.type!=="label")continue;let targetId=resolveLegacyId(entry.targetId);targetId!==null&&(entry.label?labels.set(targetId,entry.label):labels.delete(targetId))}for(let[targetId,label]of labels)values.push({...setValue(entryLabel(targetId),label),seq:nextSeq++});values.push({...setValue(branchTip("main"),resolveLegacyId(finalId)),seq:nextSeq++});let configuration=selectedConfiguration(entries,finalId);return configuration!==void 0&&(values.push({...setValue(laneConfig("main"),configuration),seq:nextSeq++}),values.push({...setValue(laneState("main"),{currentOperationId:null,lastOperationId:null,inbox:[]}),seq:nextSeq++})),values}var LegacyV3Source=class _LegacyV3Source{constructor(fileSystem,path,header,entries,importedUsage,values,nextSeq){this.fileSystem=fileSystem,this.path=path,this.header=header,this.entries=entries,this.resolveLegacyId=createLegacyIdResolver(entries),this.importedUsage=importedUsage,this.values=values,this.nextSeq=nextSeq}static async read(fileSystem,path,context){let reader=fileValue(await fileSystem.openTextLineReader(path,context),`Failed to open legacy v3 source ${path}`);try{let parsed=await readJsonlHeader(reader,path,context);if(parsed.format!=="v3-legacy")throw new Error(`Invalid legacy v3 JSONL storage ${path}: expected format 3 header`);let inventory=await readLegacyV3Inventory(reader,context),values=normalizeLegacyV3Values(inventory);return new _LegacyV3Source(fileSystem,path,await normalizeLegacyV3Header(fileSystem,parsed.header,context),inventory.entries,inventory.importedUsage,values,inventory.nextSeq+values.length)}finally{await reader.close(context)}}*entryStructures(){for(let entry of this.entries.values())isRetainedEntry(entry)&&(yield{id:entry.mappedId,parentId:this.resolveLegacyId(entry.parentId),seq:entry.seq})}translateForkEntryId(legacyId){let entry=this.entries.get(legacyId);if(entry===void 0)throw new Error(`Legacy v3 fork entry does not exist: ${legacyId}`);if(!isRetainedEntry(entry))throw new Error(`Legacy v3 fork entry is not a retained entry: ${legacyId}`);return entry.mappedId}collectRequiredTailMessageIds(isEntrySelected){let requiredIds=new Set;for(let entry of this.entries.values())if(!(entry.type!=="compaction"||!(isEntrySelected===void 0||isEntrySelected(entry.mappedId))))for(let tailEntry of retainedTailStructure(entry,this.entries))isRetainedEntry(tailEntry)&&tailEntry.type!=="custom"&&requiredIds.add(tailEntry.id);return requiredIds}async*writes(context,isEntrySelected){let requiredTailMessageIds=this.collectRequiredTailMessageIds(isEntrySelected),tailMessagesByLegacyId=new Map;for await(let{entry,indexed}of this.readCapturedEntries(context)){if(requiredTailMessageIds.has(entry.id)){let message=projectContextMessage(entry,this.resolveLegacyId);message!==void 0&&tailMessagesByLegacyId.set(entry.id,message)}if(!isRetainedEntry(indexed)||!isRetainedEntry(entry)||isEntrySelected!==void 0&&!isEntrySelected(indexed.mappedId))continue;let retainedTail=[];if(indexed.type==="compaction"){for(let ancestor of retainedTailStructure(indexed,this.entries)){let message=tailMessagesByLegacyId.get(ancestor.id);message!==void 0&&retainedTail.push(message)}retainedTail.reverse()}yield normalizeRetainedEntry(entry,indexed,retainedTail,this.resolveLegacyId)}yield*this.values}async*readCapturedEntries(context){let reader=fileValue(await this.fileSystem.openTextLineReader(this.path,context),`Failed to reopen legacy v3 source ${this.path}`);try{let parsed=await readJsonlHeader(reader,this.path,context);if(parsed.format!=="v3-legacy"||parsed.header.id!==this.header.id||parsed.header.cwd!==this.header.cwd)throw new Error("Legacy v3 source header changed");for(let indexed of this.entries.values()){let line=fileValue(await reader.readLine(context),"Failed to reread legacy v3 source");if(line===void 0||!line.terminated)throw new Error("Legacy v3 source ended before captured entries");let entry=parseLegacyV3Entry(line.text);if(entry.id!==indexed.id||entry.type!==indexed.type)throw new Error("Legacy v3 source changed");yield{entry,indexed}}}finally{await reader.close(context)}}};function physicalKey2(namespace,key){return`${namespace}\0${key}`}function compareKeys(left,right){let leftCodePoints=Array.from(left,character=>character.codePointAt(0)),rightCodePoints=Array.from(right,character=>character.codePointAt(0)),length=Math.min(leftCodePoints.length,rightCodePoints.length);for(let index=0;index<length;index++){let difference=leftCodePoints[index]-rightCodePoints[index];if(difference!==0)return difference}return leftCodePoints.length-rightCodePoints.length}var InMemoryStorageState=class _InMemoryStorageState{constructor(){this.entries=new Map,this.entriesBySeq=[],this.scalarValues=new Map,this.listValues=new Map,this.usage=new Map,this.stats={messageCount:0,usage:emptyUsage()},this.nextSeq=1}prepareCommit(writes,timestamp){let prepared=prepareStorageCommit(writes,this.nextSeq,timestamp);return this.validateCommitted(prepared.writes),prepared}validateCommitted(writes){validateCommittedWrites(writes,this.nextSeq,{hasEntryOrUsageId:id=>this.entries.has(id)||this.usage.has(id),hasEntryId:id=>this.entries.has(id)})}applyValidated(writes){for(let write of writes){switch(write.kind){case"entry":{let{kind:_kind,...entry}=write;this.entries.set(entry.id,entry),this.entriesBySeq.push(entry),entry.type==="message"&&(this.stats={...this.stats,messageCount:this.stats.messageCount+1});break}case"usage":{let{kind:_kind,...row}=write;this.usage.set(row.id,row),this.stats={...this.stats,usage:addUsage(this.stats.usage,row.usage)};break}case"value":write.op==="delete"?this.scalarValues.delete(physicalKey2(write.namespace,write.key)):this.applyValueSetOrListAppend(write);break;case"list":write.op==="delete"?this.listValues.delete(physicalKey2(write.namespace,write.key)):this.applyValueSetOrListAppend(write);break}this.nextSeq=write.seq+1}return this.stats}createFork(options){let plan=this.selectForkPlan(options),isEntryCopied=entryId=>plan.scope==="tree"?!0:plan.entryIds.has(entryId),destination=new _InMemoryStorageState,messageCount=0;for(let entry of this.entriesBySeq)isEntryCopied(entry.id)&&(destination.entries.set(entry.id,entry),destination.entriesBySeq.push(entry),entry.type==="message"&&messageCount++);destination.stats={...destination.stats,messageCount};for(let stored of this.scalarValues.values()){let projected=projectForkCurrentStateWrite({kind:"value",op:"set",seq:stored.seq,namespace:stored.address.namespace,key:stored.address.key,value:stored.value},plan,isEntryCopied);projected!==void 0&&destination.applyValueSetOrListAppend(projected)}for(let stored of this.listValues.values())for(let element of stored.elements){let projected=projectForkCurrentStateWrite({kind:"list",op:"append",seq:element.seq,namespace:stored.address.namespace,key:stored.address.key,value:element.value},plan,isEntryCopied);projected!==void 0&&destination.applyValueSetOrListAppend(projected)}return destination.nextSeq=this.nextSeq,destination}selectForkPlan(options){if(options.scope==="tree")return{scope:"tree"};let entryIds=new Set,plan=selectBranchFork(options,{tip:this.getValue(branchTip(options.branch))?.value,getParent:entryId=>this.entries.get(entryId)?.parentId,selectEntry:entryId=>entryIds.add(entryId)});if(this.getValue(laneConfig(options.branch))===void 0||this.getValue(laneState(options.branch))===void 0)throw new Error(`Source branch ${JSON.stringify(options.branch)} is not a configured AgentLane`);return{...plan,entryIds}}applyValueSetOrListAppend(write){let key=physicalKey2(write.namespace,write.key);if(write.kind==="value"){this.scalarValues.set(key,{address:value(write.namespace,write.key),value:write.value,seq:write.seq});return}let element={seq:write.seq,value:write.value},stored=this.listValues.get(key);stored===void 0?this.listValues.set(key,{address:list(write.namespace,write.key),elements:[element]}):stored.elements.push(element)}advanceNextSeq(nextSeq){if(!Number.isSafeInteger(nextSeq)||nextSeq<1)throw new Error(`Invalid storage sequence high-water mark: ${nextSeq}`);this.nextSeq=Math.max(this.nextSeq,nextSeq)}getEntries(ids){let found=new Map;for(let id of ids){let entry=this.entries.get(id);entry!==void 0&&found.set(id,entry)}return found}getValue(address){return this.scalarValues.get(physicalKey2(address.namespace,address.key))}scanValues(prefix){return[...this.scalarValues.values()].filter(stored=>stored.address.namespace===prefix.namespace&&stored.address.key.startsWith(prefix.key)).sort((left,right)=>compareKeys(left.address.key,right.address.key))}readList(address,options){let resolved2=resolveListReadOptions(options),filtered=(this.listValues.get(physicalKey2(address.namespace,address.key))?.elements??[]).filter(element=>resolved2.cursor===void 0?!0:resolved2.order==="asc"?element.seq>resolved2.cursor.seq:element.seq<resolved2.cursor.seq);return(resolved2.order==="asc"?filtered:[...filtered].reverse()).slice(0,resolved2.limit)}scanBranch(query){let start=this.entries.get(query.start);if(start===void 0)throw new Error(`Unknown branch start: ${query.start}`);let path=[],entry=start;for(;entry!==void 0&&(path.push(entry),entry.parentId!==null);)if(entry=this.entries.get(entry.parentId),entry===void 0)throw new Error("Corrupt branch: missing parent");query.order==="oldestFirst"&&path.reverse();let stopped=[];for(let candidate of path)if(stopped.push(candidate),candidate.id===query.stopAtId||candidate.type===query.stopAtType)break;let filtered=stopped.filter(candidate=>query.type===void 0||candidate.type===query.type).filter(candidate=>query.customType===void 0||candidate.customType===query.customType).filter(candidate=>query.cursor===void 0||(query.order==="oldestFirst"?candidate.seq>query.cursor.seq:candidate.seq<query.cursor.seq));return query.limit===void 0?filtered:filtered.slice(0,Math.max(0,query.limit))}scanBranchStructure(query){return this.scanBranch(query).map(entry=>({id:entry.id,parentId:entry.parentId,seq:entry.seq,timestamp:entry.timestamp,type:entry.type,...entry.customType===void 0?{}:{customType:entry.customType}}))}scanEntries(query){let limit=query.limit===void 0?Number.POSITIVE_INFINITY:Math.max(0,Math.trunc(query.limit)),entries=[],descending=query.order==="desc",index=descending?this.entriesBySeq.length-1:0;for(;index>=0&&index<this.entriesBySeq.length&&entries.length<limit;){let entry=this.entriesBySeq[index];(query.type===void 0||entry.type===query.type)&&(query.customType===void 0||entry.customType===query.customType)&&(query.fromSeq===void 0||entry.seq>=query.fromSeq)&&(query.toSeq===void 0||entry.seq<=query.toSeq)&&entries.push(entry),index+=descending?-1:1}return entries}scanUsage(query){let rows=[...this.usage.values()].filter(row=>query.fromSeq===void 0||row.seq>=query.fromSeq).filter(row=>query.toSeq===void 0||row.seq<=query.toSeq).sort((left,right)=>query.order==="desc"?right.seq-left.seq:left.seq-right.seq);return query.limit===void 0?rows:rows.slice(0,Math.max(0,query.limit))}getStats(){return this.stats}getNextSeq(){return this.nextSeq}};function splitCompleteLines(content){if(content.endsWith(`
203
+ `))return{lines:content.slice(0,-1).split(`
204
+ `),torn:!1};let lastNewline=content.lastIndexOf(`
205
+ `);return lastNewline===-1?{lines:[],torn:!0}:{lines:content.slice(0,lastNewline).split(`
206
+ `),torn:!0}}var JsonlStorage=class _JsonlStorage{constructor(options,header,backing){this.storageState=new InMemoryStorageState,this.commitQueue=Promise.resolve(),this.state="open",this.fileSystem=options.fileSystem,this.path=options.path,this.now=options.now??Date.now,this.header=header,this.backing=backing}static async create(options,header,initialWrites,context){let storage=new _JsonlStorage(options,header,{kind:"v4"}),prepared=storage.storageState.prepareCommit(initialWrites,storage.now());return await publishJsonl(options.fileSystem,options.path,header,context,async append=>{prepared.writes.length!==0&&await append(prepared.writes)}),storage.storageState.applyValidated(prepared.writes),storage}static async open(options,context){let reader=fileValue(await options.fileSystem.openTextLineReader(options.path,context),`Failed to read JSONL storage ${options.path}`),parsed=await readJsonlHeader(reader,options.path,context).finally(()=>reader.close(context));return parsed.format==="v3-legacy"?_JsonlStorage.openLegacyV3(options,context):_JsonlStorage.openV4(options,parsed.header,context)}static async openV4(options,header,context){let content=fileValue(await options.fileSystem.readTextFile(options.path,context),`Failed to read JSONL storage ${options.path}`),{lines,torn}=splitCompleteLines(content);if(header.storageVersion!==1)throw new Error(`Session ${header.id} uses unsupported storage version ${header.storageVersion}`);let storage=new _JsonlStorage(options,header,{kind:"v4"});for(let index=1;index<lines.length;index++){let line=lines[index];try{storage.replayCommitted(parseJsonlTransaction(line))}catch(error){throw new Error(`Invalid JSONL storage ${options.path}: line ${index+1}`,{cause:error})}}return header.nextSeq!==void 0&&storage.storageState.advanceNextSeq(header.nextSeq),torn&&await publishFileAtomically(options.fileSystem,options.path,context,append=>append(`${lines.join(`
207
+ `)}
208
+ `)),storage}static async openLegacyV3(options,context){let source=await LegacyV3Source.read(options.fileSystem,options.path,context),storage=new _JsonlStorage(options,{...source.header,nextSeq:source.nextSeq},{kind:"v3",source});for await(let write of source.writes(context))storage.replayCommitted([write]);return storage}replayCommitted(writes){this.storageState.validateCommitted(writes),this.storageState.applyValidated(writes)}async commit(writes,context){if(this.state!=="open")throw new Error("JsonlStorage is closed");let result=this.commitQueue.then(()=>this.applyCommit(writes,context));return this.commitQueue=result.then(()=>{},()=>{}),result}async applyCommit(writes,context){if(this.backing.kind==="v3"&&writes.length!==0)return this.upgradeLegacyV3ToV4(this.backing.source,writes,context);let prepared=this.storageState.prepareCommit(writes,this.now());prepared.writes.length!==0&&fileValue(await this.fileSystem.appendFile(this.path,`${serializeJsonlTransaction(prepared.writes)}
209
+ `,context),`Failed to append JSONL storage ${this.path}`);let stats=this.storageState.applyValidated(prepared.writes);return{...prepared.result,stats:this.withImportedUsage(stats)}}async upgradeLegacyV3ToV4(source,callerWrites,context){let timestamp=this.now(),prepared=this.storageState.prepareCommit([insertUsage({id:uuidv7(timestamp),usage:source.importedUsage,adjustment:!0,details:{source:"v3-import"}}),...callerWrites],timestamp),nextSeq=prepared.result.firstSeq+prepared.writes.length,upgradedHeader={...this.header,nextSeq};await publishJsonl(this.fileSystem,this.path,upgradedHeader,context,async append=>{for await(let write of source.writes(context))await append([write]);await append(prepared.writes)});let stats=this.storageState.applyValidated(prepared.writes);return this.backing={kind:"v4"},{...prepared.result,firstSeq:prepared.result.firstSeq+1,seqs:prepared.result.seqs.slice(1),stats}}getEntries(ids,_context){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.storageState.getEntries(ids))}getValue(address,_context){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.storageState.getValue(address))}scanValues(prefix,_context){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.storageState.scanValues(prefix))}async readList(address,options,_context){if(this.state!=="open")throw new Error("JsonlStorage is closed");return this.storageState.readList(address,options)}async scanBranch(query,_context){if(this.state!=="open")throw new Error("JsonlStorage is closed");return this.storageState.scanBranch(query)}async scanBranchStructure(query,_context){if(this.state!=="open")throw new Error("JsonlStorage is closed");return this.storageState.scanBranchStructure(query)}scanEntries(query,_context){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.storageState.scanEntries(query))}scanUsage(query,_context){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.storageState.scanUsage(query))}getStats(_context){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.withImportedUsage(this.storageState.getStats()))}withImportedUsage(stats){return this.backing.kind==="v4"?stats:{...stats,usage:this.backing.source.importedUsage}}isLegacyV3(){return this.backing.kind==="v3"}captureForkNextSeq(_context){if(this.state!=="open")return Promise.reject(new Error("JsonlStorage is closed"));let result=this.commitQueue.then(()=>this.storageState.getNextSeq());return this.commitQueue=result.then(()=>{},()=>{}),result}close(_context){return this.closePromise!==void 0?this.closePromise:(this.state="closing",this.closePromise=this.commitQueue.then(()=>{this.state="closed"}),this.closePromise)}};function metadataFromHeader(header,path,modifiedAt){return{id:header.id,createdAt:header.createdAt,storageVersion:header.storageVersion,cwd:header.cwd,path,modifiedAt,...header.parentSessionId===void 0?{}:{parentSessionId:header.parentSessionId},...header.legacyParentSessionPath===void 0?{}:{legacyParentSessionPath:header.legacyParentSessionPath}}}function sessionDirectoryName(cwd){return`--${cwd.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function sessionFileName(createdAt,id){return`${new Date(createdAt).toISOString().replace(/[:.]/g,"-")}_${encodeURIComponent(id)}.jsonl`}var JsonlSessionRepo=class{constructor(options){this.openSessions=new Map,this.pendingCreates=new Set,this.closed=!1,this.fileSystem=options.fileSystem,this.sessionsRootInput=options.sessionsRoot,this.now=options.now??Date.now}async create(options,context){this.assertOpen();let createdAt=this.now(),{cwd,id}=await this.resolveCreateDestination(options.cwd,options.id,createdAt,context),key=this.sessionKey(cwd,id);if(this.openSessions.has(key)||this.pendingCreates.has(key))throw new Error(`Session already exists: ${id}`);this.pendingCreates.add(key);let path,storage;try{path=await this.resolveNewSessionPath(cwd,createdAt,id,context);let header={v:4,kind:"header",id,storageVersion:1,createdAt,cwd,...options.parentSessionId===void 0?{}:{parentSessionId:options.parentSessionId}};storage=await JsonlStorage.create({fileSystem:this.fileSystem,path,now:this.now},header,[],context);let info=fileValue(await this.fileSystem.fileInfo(path,context),`Failed to read session ${path}`);return this.publishOpenSession(metadataFromHeader(header,path,info.mtimeMs),storage,key)}catch(error){throw await storage?.close(context).catch(()=>{}),path!==void 0&&await this.fileSystem.remove(path,{force:!0},context),error}finally{this.pendingCreates.delete(key)}}async open(metadata,context){this.assertOpen();let key=this.sessionKey(metadata.cwd,metadata.id);if(this.openSessions.has(key))throw new Error(`Session is already open: ${metadata.id}`);let storage;try{return storage=await this.loadStorage(metadata,context),this.publishOpenSession(metadata,storage,key)}catch(error){throw await storage?.close(context),error}}async list(options,context){options??={},this.assertOpen();let cwd=options.cwd===void 0?void 0:fileValue(await this.fileSystem.absolutePath(options.cwd,context),`Failed to resolve session cwd ${options.cwd}`),root=await this.root(context);if(!fileValue(await this.fileSystem.exists(root,context),`Failed to check sessions root ${root}`))return[];let directories=cwd===void 0?await this.sessionDirectories(root,context):[await this.sessionDirectory(cwd,context)],metadata=[];for(let directory of directories)metadata.push(...await this.listDirectory(directory,cwd,context));return metadata.sort((left,right)=>right.createdAt-left.createdAt||left.id.localeCompare(right.id)||left.cwd.localeCompare(right.cwd))}async delete(metadata,context){this.assertOpen();let key=this.sessionKey(metadata.cwd,metadata.id);if(this.openSessions.has(key))throw new Error(`Session is open: ${metadata.id}`);if(!fileValue(await this.fileSystem.exists(metadata.path,context),`Failed to check session ${metadata.path}`))throw new Error(`Session file does not exist: ${metadata.path}`);fileValue(await this.fileSystem.remove(metadata.path,void 0,context),`Failed to delete session ${metadata.path}`)}async fork(source,options,context){this.assertOpen();let createdAt=this.now(),cwd=source.cwd,id=options.id??uuidv7(createdAt),destinationKey=this.sessionKey(cwd,id);if(this.openSessions.has(destinationKey)||this.pendingCreates.has(destinationKey))throw new Error(`Session already exists: ${id}`);this.pendingCreates.add(destinationKey);let sourceStorage=this.openSessions.get(this.sessionKey(source.cwd,source.id)),path,storage;try{let input=await this.resolveForkInput(source,sourceStorage,context);path=await this.resolveNewSessionPath(cwd,createdAt,id,context);let header={v:4,kind:"header",id,storageVersion:1,createdAt,cwd,parentSessionId:source.id};await runJsonlFork({input,fileSystem:this.fileSystem,destinationPath:path,destinationHeader:header,fork:options},context),storage=await JsonlStorage.open({fileSystem:this.fileSystem,path,now:this.now},context);let info=fileValue(await this.fileSystem.fileInfo(path,context),`Failed to read session ${path}`);return this.publishOpenSession(metadataFromHeader(header,path,info.mtimeMs),storage,destinationKey)}catch(error){throw await storage?.close(context).catch(()=>{}),path!==void 0&&await this.fileSystem.remove(path,{force:!0},context),error}finally{this.pendingCreates.delete(destinationKey)}}close(_context){return this.closePromise!==void 0?this.closePromise:(this.closed=!0,this.closePromise=Promise.resolve(),this.closePromise)}async resolveCreateDestination(cwdInput,id,createdAt,context){let destinationId=id??uuidv7(createdAt);return{cwd:fileValue(await this.fileSystem.absolutePath(cwdInput,context),`Failed to resolve session cwd ${cwdInput}`),id:destinationId}}async listDirectory(directory,cwd,context){if(!fileValue(await this.fileSystem.exists(directory,context),`Failed to check sessions directory ${directory}`))return[];let files=fileValue(await this.fileSystem.listDir(directory,context),`Failed to list sessions directory ${directory}`).filter(file=>file.kind!=="directory"&&file.name.endsWith(".jsonl")),metadata=[];for(let file of files){let discovered=await this.readSessionMetadata(file,context);discovered!==void 0&&(cwd===void 0||discovered.cwd===cwd)&&metadata.push(discovered)}return metadata}async readSessionMetadata(file,context){let lines=fileValue(await this.fileSystem.readTextLines(file.path,{maxLines:1},context),`Failed to read session header ${file.path}`);if(lines[0]===void 0)return;let parsedHeader=parseJsonlSessionHeader(lines[0]);if(parsedHeader.ok)return parsedHeader.value.format==="v3-legacy"?{...await metadataFromLegacyV3Header(this.fileSystem,parsedHeader.value.header,context),path:file.path,modifiedAt:file.mtimeMs}:metadataFromHeader(parsedHeader.value.header,file.path,file.mtimeMs)}async sessionDirectories(root,context){return fileValue(await this.fileSystem.listDir(root,context),`Failed to list sessions root ${root}`).filter(entry=>entry.kind==="directory").map(entry=>entry.path)}async sessionDirectory(cwd,context){return fileValue(await this.fileSystem.joinPath([await this.root(context),sessionDirectoryName(cwd)],context),`Failed to resolve sessions directory for ${cwd}`)}async resolveNewSessionPath(cwd,createdAt,id,context){let directory=await this.sessionDirectory(cwd,context);return await this.assertSessionIdAvailable(directory,id,context),fileValue(await this.fileSystem.createDir(directory,void 0,context),`Failed to create sessions directory ${directory}`),fileValue(await this.fileSystem.joinPath([directory,sessionFileName(createdAt,id)],context),`Failed to resolve path for session ${id}`)}async assertSessionIdAvailable(directory,id,context){if(!fileValue(await this.fileSystem.exists(directory,context),`Failed to check sessions directory ${directory}`))return;let suffix=`_${encodeURIComponent(id)}.jsonl`;if(fileValue(await this.fileSystem.listDir(directory,context),`Failed to list sessions directory ${directory}`).some(entry=>entry.kind!=="directory"&&entry.name.endsWith(suffix)))throw new Error(`Session already exists: ${id}`)}async resolveForkInput(source,storage,context){if(storage!==void 0){if(storage.isLegacyV3())throw new Error("Cannot fork an open legacy v3 JSONL session; commit a non-empty transaction to upgrade it to format 4 first");let nextSeq=await storage.captureForkNextSeq(context);return{kind:"open",metadata:source,nextSeq}}if(await this.isLegacyV3ForkSource(source,context)){let normalized=await LegacyV3Source.read(this.fileSystem,source.path,context);if(normalized.header.id!==source.id||normalized.header.cwd!==source.cwd)throw new Error(`Session identity does not match header: ${source.id}`);return{kind:"legacy-v3",normalized}}return{kind:"closed",metadata:source}}async isLegacyV3ForkSource(source,context){let lines=fileValue(await this.fileSystem.readTextLines(source.path,{maxLines:1},context),`Failed to read session header ${source.path}`);if(lines[0]===void 0)return!1;let parsed=parseJsonlSessionHeader(lines[0]);return parsed.ok&&parsed.value.format==="v3-legacy"}publishOpenSession(metadata,storage,key){if(this.openSessions.has(key))throw new Error(`Session is already open: ${metadata.id}`);let session=new StorageBackedSession(metadata,storage,{onClose:()=>{this.openSessions.get(key)===storage&&this.openSessions.delete(key)}});return this.openSessions.set(key,storage),session}sessionKey(cwd,id){return`${cwd}\0${id}`}async loadStorage(metadata,context){if(!fileValue(await this.fileSystem.exists(metadata.path,context),`Failed to check session ${metadata.path}`))throw new Error(`Session file does not exist: ${metadata.path}`);let storage=await JsonlStorage.open({fileSystem:this.fileSystem,path:metadata.path,now:this.now},context);try{if(storage.header.id!==metadata.id||storage.header.cwd!==metadata.cwd)throw new Error(`Session identity does not match header: ${metadata.id}`);if(storage.header.storageVersion!==1)throw new Error(`Session ${metadata.id} uses unsupported storage version ${storage.header.storageVersion}`);return storage}catch(error){throw await storage.close(context),error}}root(context){return this.fileSystem.absolutePath(this.sessionsRootInput,context).then(result=>fileValue(result,`Failed to resolve sessions root ${this.sessionsRootInput}`))}assertOpen(){if(this.closed)throw new Error("JsonlSessionRepo is closed")}};var MemoryStorage=class _MemoryStorage{constructor(options={}){this.storageState=new InMemoryStorageState,this.commitQueue=Promise.resolve(),this.state="open",this.now=options.now??Date.now}async commit(writes,_context){if(this.state!=="open")throw new Error("MemoryStorage is closed");let result=this.commitQueue.then(()=>{let prepared=this.storageState.prepareCommit(writes,this.now()),stats=this.storageState.applyValidated(prepared.writes);return{...prepared.result,stats}});return this.commitQueue=result.then(()=>{},()=>{}),result}getEntries(ids,_context){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.getEntries(ids))}getValue(address,_context){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.getValue(address))}scanValues(prefix,_context){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.scanValues(prefix))}async readList(address,options,_context){if(this.state!=="open")throw new Error("MemoryStorage is closed");return this.storageState.readList(address,options)}async scanBranch(query,_context){if(this.state!=="open")throw new Error("MemoryStorage is closed");return this.storageState.scanBranch(query)}async scanBranchStructure(query,_context){if(this.state!=="open")throw new Error("MemoryStorage is closed");return this.storageState.scanBranchStructure(query)}scanEntries(query,_context){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.scanEntries(query))}scanUsage(query,_context){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.scanUsage(query))}getStats(_context){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.getStats())}fork(options){if(this.state!=="open")return Promise.reject(new Error("MemoryStorage is closed"));let result=this.commitQueue.then(()=>{let destination=new _MemoryStorage({now:this.now});return destination.storageState=this.storageState.createFork(options),destination});return this.commitQueue=result.then(()=>{},()=>{}),result}close(_context){return this.closePromise!==void 0?this.closePromise:(this.state="closing",this.closePromise=this.commitQueue.then(()=>{this.state="closed"}),this.closePromise)}},MEMORY_STORAGE_VERSION=1,MemorySessionFacade=class{constructor(session,onClose){this.admitted=new Set,this.closedError=new Error("Session is closed"),this.state="open",this.session=session,this.metadata=session.metadata,this.idGenerator=session.idGenerator,this.onClose=onClose}async beginMutation(context){let resolveFinished,finished=new Promise(resolve=>{resolveFinished=resolve});this.admitted.add(finished);let source;try{source=await this.admit(()=>this.session.beginMutation(context))}catch(error){throw this.admitted.delete(finished),resolveFinished(),error}if(this.state!=="open")throw await source.end(context),this.admitted.delete(finished),resolveFinished(),this.closedError;let ended=!1;return{commit:(writes,commitContext)=>source.commit(writes,commitContext),end:async endContext=>{try{await source.end(endContext)}finally{ended||(ended=!0,this.admitted.delete(finished),resolveFinished())}},getEntries:(ids,readContext)=>source.getEntries(ids,readContext),getStats:readContext=>source.getStats(readContext),getValue:(address,readContext)=>source.getValue(address,readContext),scanValues:(prefix,readContext)=>source.scanValues(prefix,readContext),readList:(address,options,readContext)=>source.readList(address,options,readContext),scanBranch:(query,readContext)=>source.scanBranch(query,readContext)}}mutate(mutation,context){return this.admit(()=>this.session.mutate((mutator,mutationContext)=>{if(this.state!=="open")throw this.closedError;return mutation(mutator,mutationContext)},context))}getEntries(ids,context){return this.admit(()=>this.session.getEntries(ids,context))}getEntry(id,context){return this.admit(()=>this.session.getEntry(id,context))}getValue(address,context){return this.admit(()=>this.session.getValue(address,context))}scanValues(prefix,context){return this.admit(()=>this.session.scanValues(prefix,context))}readList(address,options,context){return this.admit(()=>this.session.readList(address,options,context))}scanBranch(query,context){return this.admit(()=>this.session.scanBranch(query,context))}getStats(context){return this.admit(()=>this.session.getStats(context))}getName(context){return this.admit(()=>this.session.getName(context))}getLabel(targetId,context){return this.admit(()=>this.session.getLabel(targetId,context))}findEntries(query,context){return this.admit(()=>this.session.findEntries(query,context))}findEntry(query,context){return this.admit(()=>this.session.findEntry(query,context))}async branch(name,context){let branch=await this.admit(()=>this.session.branch(name,context));return branch===void 0?void 0:this.wrapBranch(branch)}async createBranch(name,at,context){return this.wrapBranch(await this.admit(()=>this.session.createBranch(name,at,context)))}setValue(address,next,context){return this.admit(()=>this.session.setValue(address,next,context))}deleteValue(address,context){return this.admit(()=>this.session.deleteValue(address,context))}appendList(address,element,context){return this.admit(()=>this.session.appendList(address,element,context))}deleteList(address,context){return this.admit(()=>this.session.deleteList(address,context))}setName(name,context){return this.admit(()=>this.session.setName(name,context))}setLabel(targetId,label,context){return this.admit(()=>this.session.setLabel(targetId,label,context))}close(_context){return this.closePromise!==void 0?this.closePromise:(this.state="closing",this.closePromise=Promise.allSettled([...this.admitted]).then(()=>{this.state="closed",this.onClose()}),this.closePromise)}wrapBranch(branch){return{name:branch.name,getTipId:context=>this.admit(()=>branch.getTipId(context)),findEntries:(query,context)=>this.admit(()=>branch.findEntries(query,context)),findEntry:(query,context)=>this.admit(()=>branch.findEntry(query,context)),appendMessage:(message,context)=>this.admit(()=>branch.appendMessage(message,context)),appendCustomEntry:(customType,data,context)=>this.admit(()=>branch.appendCustomEntry(customType,data,context))}}admit(operation){if(this.state!=="open")return Promise.reject(this.closedError);let result;try{result=operation()}catch(error){result=Promise.reject(error)}return this.admitted.add(result),result.then(()=>this.admitted.delete(result),()=>this.admitted.delete(result)),result}},MemorySessionRepo=class{constructor(options={}){this.sessions=new Map,this.pendingIds=new Set,this.closed=!1,this.now=options.now??Date.now}async create(options,context){this.assertOpen();let createdAt=this.now(),id=options.id??uuidv7(createdAt);this.reserveId(id);let metadata={id,createdAt,storageVersion:MEMORY_STORAGE_VERSION,...options.parentSessionId===void 0?{}:{parentSessionId:options.parentSessionId}},storage=new MemoryStorage({now:this.now}),session=new StorageBackedSession(metadata,storage);try{let record={metadata,storage,session,open:!0};return this.sessions.set(id,record),this.openRecord(record)}catch(error){throw await session.close(context),error}finally{this.pendingIds.delete(id)}}open(metadata,_context){this.assertOpen();let record=this.sessions.get(metadata.id);return record===void 0?Promise.reject(new Error(`Unknown session: ${metadata.id}`)):record.open?Promise.reject(new Error(`Session is already open: ${metadata.id}`)):(record.open=!0,Promise.resolve(this.openRecord(record)))}list(_options,_context){return this.assertOpen(),Promise.resolve([...this.sessions.values()].map(({metadata})=>metadata))}async delete(metadata,context){this.assertOpen();let record=this.sessions.get(metadata.id);if(record===void 0)throw new Error(`Unknown session: ${metadata.id}`);if(record.open)throw new Error(`Session is open: ${metadata.id}`);await record.session.close(context),this.sessions.delete(metadata.id)}async fork(source,options,_context){this.assertOpen();let sourceRecord=this.sessions.get(source.id);if(sourceRecord===void 0)throw new Error(`Unknown session: ${source.id}`);let createdAt=this.now(),id=options.id??uuidv7(createdAt);this.reserveId(id);try{let storage=await sourceRecord.storage.fork(options),metadata={id,createdAt,storageVersion:MEMORY_STORAGE_VERSION,parentSessionId:sourceRecord.metadata.id},session=new StorageBackedSession(metadata,storage),record={metadata,storage,session,open:!0};return this.sessions.set(id,record),this.openRecord(record)}finally{this.pendingIds.delete(id)}}close(context){return this.closePromise!==void 0?this.closePromise:(this.closed=!0,this.closePromise=Promise.all([...this.sessions.values()].map(({session})=>session.close(context))).then(()=>{}),this.closePromise)}openRecord(record){return new MemorySessionFacade(record.session,()=>{record.open=!1})}reserveId(id){if(this.sessions.has(id)||this.pendingIds.has(id))throw new Error(`Session already exists: ${id}`);this.pendingIds.add(id)}assertOpen(){if(this.closed)throw new Error("MemorySessionRepo is closed")}};function formatSkillsForSystemPrompt(skills){let visibleSkills=skills.filter(skill=>!skill.disableModelInvocation);if(visibleSkills.length===0)return"";let lines=["The following skills provide specialized instructions for specific tasks.","Read the full skill file when the task matches its description.","When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.","","<available_skills>"];for(let skill of visibleSkills)lines.push(" <skill>"),lines.push(` <name>${escapeXml(skill.name)}</name>`),lines.push(` <description>${escapeXml(skill.description)}</description>`),lines.push(` <location>${escapeXml(skill.filePath)}</location>`),lines.push(" </skill>");return lines.push("</available_skills>"),lines.join(`
210
+ `)}function escapeXml(value2){return value2.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var MAX_TIMEOUT_SECONDS2=2147483647/1e3,BASH_CHECKPOINT_INTERVAL_MS=2e3,bashSchema=typebox_exports.Object({command:typebox_exports.String({description:"Bash command to execute"}),timeout:typebox_exports.Optional(typebox_exports.Number({description:"Timeout in seconds (optional, no default timeout)"}))});function validateTimeout(timeout){if(timeout!==void 0){if(!Number.isFinite(timeout)||timeout<=0)throw new Error("Invalid timeout: must be a finite number of seconds");if(timeout>MAX_TIMEOUT_SECONDS2)throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS2} seconds`)}}function createBashTool(options){return{name:"bash",label:"bash",description:`Execute a bash command in the current working directory. Returns combined stdout and stderr. Output is truncated to last ${2e3} lines or ${51200/1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,parameters:bashSchema,async execute(_toolCallId,{command,timeout},onUpdate,toolContext,_invocation,context){validateTimeout(timeout);let{env}=toolContext,execution={command:options?.commandPrefix?`${options.commandPrefix}
211
+ ${command}`:command,cwd:env.cwd,env:{},inheritEnv:!0};await options?.prepare?.(execution,toolContext,context);let view,lastCheckpointAt=Date.now(),lastCheckpoint,acceptingUpdates=!0;onUpdate({content:[],details:void 0});let result=await env.exec(execution.command,{cwd:execution.cwd,env:execution.env,inheritEnv:execution.inheritEnv,timeout,capture:{limits:{maxBytes:51200,maxLines:2e3,retain:"tail"},spill:!0},onUpdate:update=>{if(!acceptingUpdates)return;view=applyShellOutputUpdate(view,update);let snapshot={content:[{type:"text",text:view.text}],details:{truncation:view.truncation.truncated?view.truncation:void 0,fullOutputPath:view.spillPath}},now=Date.now(),encoded=JSON.stringify(snapshot),checkpoint=now-lastCheckpointAt>=BASH_CHECKPOINT_INTERVAL_MS&&encoded!==lastCheckpoint;onUpdate(snapshot,checkpoint?{checkpoint:!0}:void 0),checkpoint&&(lastCheckpointAt=now,lastCheckpoint=encoded)}},context);acceptingUpdates=!1;let outputText=view?.text??"",interruptedSpillPath=result.ok?void 0:result.error.spillPath,capture=result.ok?{text:outputText,...result.value}:view!==void 0&&view.spillPath===void 0&&interruptedSpillPath!==void 0?{...view,spillPath:interruptedSpillPath}:view,details;if(capture?.truncation.truncated){details={truncation:capture.truncation,fullOutputPath:capture.spillPath};let startLine=capture.truncation.totalLines-capture.truncation.outputLines+1,endLine=capture.truncation.totalLines;if(capture.truncation.lastLinePartial){let lastLineSize=formatSize(capture.lastLineBytes??capture.truncation.outputBytes);outputText+=`
212
+
213
+ [Showing last ${formatSize(capture.truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${capture.spillPath}]`}else capture.truncation.truncatedBy==="lines"?outputText+=`
214
+
215
+ [Showing lines ${startLine}-${endLine} of ${capture.truncation.totalLines}. Full output: ${capture.spillPath}]`:outputText+=`
216
+
217
+ [Showing lines ${startLine}-${endLine} of ${capture.truncation.totalLines} (${formatSize(51200)} limit). Full output: ${capture.spillPath}]`}else interruptedSpillPath!==void 0&&(outputText+=`${outputText?`
218
+
219
+ `:""}[Full output: ${interruptedSpillPath}]`);if(!result.ok){let status=result.error.code==="timeout"?`Command timed out after ${timeout} seconds`:result.error.code==="aborted"?"Command aborted":result.error.message;throw new Error(outputText?`${outputText}
220
+
221
+ ${status}`:status,{cause:result.error})}if(result.value.exitCode!==0)throw new Error(`${outputText?`${outputText}
222
+
223
+ `:""}Command exited with code ${result.value.exitCode}`);return{content:[{type:"text",text:outputText||"(no output)"}],details}}}}var Diff=class{diff(oldStr,newStr,options={}){let callback;typeof options=="function"?(callback=options,options={}):"callback"in options&&(callback=options.callback);let oldString=this.castInput(oldStr,options),newString=this.castInput(newStr,options),oldTokens=this.removeEmpty(this.tokenize(oldString,options)),newTokens=this.removeEmpty(this.tokenize(newString,options));return this.diffWithOptionsObj(oldTokens,newTokens,options,callback)}diffWithOptionsObj(oldTokens,newTokens,options,callback){var _a;let done=value2=>{if(value2=this.postProcess(value2,options),callback){setTimeout(function(){callback(value2)},0);return}else return value2},newLen=newTokens.length,oldLen=oldTokens.length,editLength=1,maxEditLength=newLen+oldLen;options.maxEditLength!=null&&(maxEditLength=Math.min(maxEditLength,options.maxEditLength));let maxExecutionTime=(_a=options.timeout)!==null&&_a!==void 0?_a:1/0,abortAfterTimestamp=Date.now()+maxExecutionTime,bestPath=[{oldPos:-1,lastComponent:void 0}],newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens));let minDiagonalToConsider=-1/0,maxDiagonalToConsider=1/0,execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath,removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];removePath&&(bestPath[diagonalPath-1]=void 0);let canAdd=!1;if(addPath){let addPathNewPos=addPath.oldPos-diagonalPath;canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen}let canRemove=removePath&&removePath.oldPos+1<oldLen;if(!canAdd&&!canRemove){bestPath[diagonalPath]=void 0;continue}if(!canRemove||canAdd&&removePath.oldPos<addPath.oldPos?basePath=this.addToPath(addPath,!0,!1,0,options):basePath=this.addToPath(removePath,!1,!0,1,options),newPos=this.extractCommon(basePath,newTokens,oldTokens,diagonalPath,options),basePath.oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||!0;bestPath[diagonalPath]=basePath,basePath.oldPos+1>=oldLen&&(maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)),newPos+1>=newLen&&(minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1))}editLength++};if(callback)(function exec(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp)return callback(void 0);execEditLength()||exec()},0)})();else for(;editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp;){let ret=execEditLength();if(ret)return ret}}addToPath(path,added,removed,oldPosInc,options){let last=path.lastComponent;return last&&!options.oneChangePerToken&&last.added===added&&last.removed===removed?{oldPos:path.oldPos+oldPosInc,lastComponent:{count:last.count+1,added,removed,previousComponent:last.previousComponent}}:{oldPos:path.oldPos+oldPosInc,lastComponent:{count:1,added,removed,previousComponent:last}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options){let newLen=newTokens.length,oldLen=oldTokens.length,oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;for(;newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldTokens[oldPos+1],newTokens[newPos+1],options);)newPos++,oldPos++,commonCount++,options.oneChangePerToken&&(basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:!1,removed:!1});return commonCount&&!options.oneChangePerToken&&(basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:!1,removed:!1}),basePath.oldPos=oldPos,newPos}equals(left,right,options){return options.comparator?options.comparator(left,right):left===right||!!options.ignoreCase&&left.toLowerCase()===right.toLowerCase()}removeEmpty(array){let ret=[];for(let i=0;i<array.length;i++)array[i]&&ret.push(array[i]);return ret}castInput(value2,options){return value2}tokenize(value2,options){return Array.from(value2)}join(chars){return chars.join("")}postProcess(changeObjects,options){return changeObjects}get useLongestToken(){return!1}buildValues(lastComponent,newTokens,oldTokens){let components=[],nextComponent;for(;lastComponent;)components.push(lastComponent),nextComponent=lastComponent.previousComponent,delete lastComponent.previousComponent,lastComponent=nextComponent;components.reverse();let componentLen=components.length,componentPos=0,newPos=0,oldPos=0;for(;componentPos<componentLen;componentPos++){let component=components[componentPos];if(component.removed)component.value=this.join(oldTokens.slice(oldPos,oldPos+component.count)),oldPos+=component.count;else{if(!component.added&&this.useLongestToken){let value2=newTokens.slice(newPos,newPos+component.count);value2=value2.map(function(value3,i){let oldValue=oldTokens[oldPos+i];return oldValue.length>value3.length?oldValue:value3}),component.value=this.join(value2)}else component.value=this.join(newTokens.slice(newPos,newPos+component.count));newPos+=component.count,component.added||(oldPos+=component.count)}}return components}};var LineDiff=class extends Diff{constructor(){super(...arguments),this.tokenize=tokenize}equals(left,right,options){return options.ignoreWhitespace?((!options.newlineIsToken||!left.includes(`
224
+ `))&&(left=left.trim()),(!options.newlineIsToken||!right.includes(`
225
+ `))&&(right=right.trim())):options.ignoreNewlineAtEof&&!options.newlineIsToken&&(left.endsWith(`
226
+ `)&&(left=left.slice(0,-1)),right.endsWith(`
227
+ `)&&(right=right.slice(0,-1))),super.equals(left,right,options)}},lineDiff=new LineDiff;function diffLines(oldStr,newStr,options){return lineDiff.diff(oldStr,newStr,options)}function tokenize(value2,options){options.stripTrailingCr&&(value2=value2.replace(/\r\n/g,`
228
+ `));let retLines=[],linesAndNewlines=value2.split(/(\n|\r\n)/);linesAndNewlines[linesAndNewlines.length-1]||linesAndNewlines.pop();for(let i=0;i<linesAndNewlines.length;i++){let line=linesAndNewlines[i];i%2&&!options.newlineIsToken?retLines[retLines.length-1]+=line:retLines.push(line)}return retLines}function needsQuoting(s){for(let i=0;i<s.length;i++)if(s[i]<" "||s[i]>"~"||s[i]==='"'||s[i]==="\\")return!0;return!1}function quoteFileNameIfNeeded(s){if(!needsQuoting(s))return s;let result='"',bytes=new TextEncoder().encode(s),i=0;for(;i<bytes.length;){let b=bytes[i];b===7?result+="\\a":b===8?result+="\\b":b===9?result+="\\t":b===10?result+="\\n":b===11?result+="\\v":b===12?result+="\\f":b===13?result+="\\r":b===34?result+='\\"':b===92?result+="\\\\":b>=32&&b<=126?result+=String.fromCharCode(b):result+="\\"+b.toString(8).padStart(3,"0"),i++}return result+='"',result}var INCLUDE_HEADERS={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0},FILE_HEADERS_ONLY={includeIndex:!1,includeUnderline:!1,includeFileHeaders:!0};function structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options){let optionsObj;options?typeof options=="function"?optionsObj={callback:options}:optionsObj=options:optionsObj={},typeof optionsObj.context>"u"&&(optionsObj.context=4);let context=optionsObj.context;if(optionsObj.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(optionsObj.callback){let{callback}=optionsObj;diffLines(oldStr,newStr,Object.assign(Object.assign({},optionsObj),{callback:diff=>{let patch=diffLinesResultToPatch(diff);callback(patch)}}))}else return diffLinesResultToPatch(diffLines(oldStr,newStr,optionsObj));function diffLinesResultToPatch(diff){if(!diff)return;diff.push({value:"",lines:[]});function contextLines(lines){return lines.map(function(entry){return" "+entry})}let hunks=[],oldRangeStart=0,newRangeStart=0,curRange=[],oldLine=1,newLine=1;for(let i=0;i<diff.length;i++){let current=diff[i],lines=current.lines||splitLines(current.value);if(current.lines=lines,current.added||current.removed){if(!oldRangeStart){let prev=diff[i-1];oldRangeStart=oldLine,newRangeStart=newLine,prev&&(curRange=context>0?contextLines(prev.lines.slice(-context)):[],oldRangeStart-=curRange.length,newRangeStart-=curRange.length)}for(let line of lines)curRange.push((current.added?"+":"-")+line);current.added?newLine+=lines.length:oldLine+=lines.length}else{if(oldRangeStart)if(lines.length<=context*2&&i<diff.length-2)for(let line of contextLines(lines))curRange.push(line);else{let contextSize=Math.min(lines.length,context);for(let line of contextLines(lines.slice(0,contextSize)))curRange.push(line);let hunk={oldStart:oldRangeStart,oldLines:oldLine-oldRangeStart+contextSize,newStart:newRangeStart,newLines:newLine-newRangeStart+contextSize,lines:curRange};hunks.push(hunk),oldRangeStart=0,newRangeStart=0,curRange=[]}oldLine+=lines.length,newLine+=lines.length}}for(let hunk of hunks)for(let i=0;i<hunk.lines.length;i++)hunk.lines[i].endsWith(`
229
+ `)?hunk.lines[i]=hunk.lines[i].slice(0,-1):(hunk.lines.splice(i+1,0,"\"),i++);return{oldFileName,newFileName,oldHeader,newHeader,hunks}}}function formatPatch(patch,headerOptions){var _a,_b,_c,_d,_e,_f;if(headerOptions||(headerOptions=INCLUDE_HEADERS),Array.isArray(patch)){if(patch.length>1&&!headerOptions.includeFileHeaders&&!patch.every(p=>p.isGit))throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)");return patch.map(p=>formatPatch(p,headerOptions)).join(`
230
+ `)}let ret=[];if(patch.isGit){if(headerOptions=INCLUDE_HEADERS,!patch.oldFileName)throw new Error("oldFileName must be specified for Git patches");if(!patch.newFileName)throw new Error("newFileName must be specified for Git patches");let gitOldName=patch.oldFileName,gitNewName=patch.newFileName;patch.isCreate&&gitOldName==="/dev/null"?gitOldName=gitNewName.replace(/^b\//,"a/"):patch.isDelete&&gitNewName==="/dev/null"&&(gitNewName=gitOldName.replace(/^a\//,"b/")),ret.push("diff --git "+quoteFileNameIfNeeded(gitOldName)+" "+quoteFileNameIfNeeded(gitNewName)),patch.isDelete&&ret.push("deleted file mode "+((_a=patch.oldMode)!==null&&_a!==void 0?_a:"100644")),patch.isCreate&&ret.push("new file mode "+((_b=patch.newMode)!==null&&_b!==void 0?_b:"100644")),patch.oldMode&&patch.newMode&&!patch.isDelete&&!patch.isCreate&&(ret.push("old mode "+patch.oldMode),ret.push("new mode "+patch.newMode)),patch.isRename&&(ret.push("rename from "+quoteFileNameIfNeeded(((_c=patch.oldFileName)!==null&&_c!==void 0?_c:"").replace(/^a\//,""))),ret.push("rename to "+quoteFileNameIfNeeded(((_d=patch.newFileName)!==null&&_d!==void 0?_d:"").replace(/^b\//,"")))),patch.isCopy&&(ret.push("copy from "+quoteFileNameIfNeeded(((_e=patch.oldFileName)!==null&&_e!==void 0?_e:"").replace(/^a\//,""))),ret.push("copy to "+quoteFileNameIfNeeded(((_f=patch.newFileName)!==null&&_f!==void 0?_f:"").replace(/^b\//,""))))}else headerOptions.includeIndex&&patch.oldFileName==patch.newFileName&&patch.oldFileName!==void 0&&ret.push("Index: "+patch.oldFileName),headerOptions.includeUnderline&&ret.push("===================================================================");let hasHunks=patch.hunks.length>0;headerOptions.includeFileHeaders&&patch.oldFileName!==void 0&&patch.newFileName!==void 0&&(!patch.isGit||hasHunks)&&(ret.push("--- "+quoteFileNameIfNeeded(patch.oldFileName)+(patch.oldHeader?" "+patch.oldHeader:"")),ret.push("+++ "+quoteFileNameIfNeeded(patch.newFileName)+(patch.newHeader?" "+patch.newHeader:"")));for(let i=0;i<patch.hunks.length;i++){let hunk=patch.hunks[i],oldStart=hunk.oldLines===0?hunk.oldStart-1:hunk.oldStart,newStart=hunk.newLines===0?hunk.newStart-1:hunk.newStart;ret.push("@@ -"+oldStart+","+hunk.oldLines+" +"+newStart+","+hunk.newLines+" @@");for(let line of hunk.lines)ret.push(line)}return ret.join(`
231
+ `)+`
232
+ `}function createTwoFilesPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options){if(typeof options=="function"&&(options={callback:options}),options?.callback){let{callback}=options;structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,Object.assign(Object.assign({},options),{callback:patchObj=>{callback(patchObj?formatPatch(patchObj,options.headerOptions):void 0)}}))}else{let patchObj=structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options);return patchObj?formatPatch(patchObj,options?.headerOptions):void 0}}function splitLines(text){let hasTrailingNl=text.endsWith(`
233
+ `),result=text.split(`
234
+ `).map(line=>line+`
235
+ `);return hasTrailingNl?result.pop():result.push(result.pop().slice(0,-1)),result}function detectLineEnding(content){let crlfIdx=content.indexOf(`\r
236
+ `),lfIdx=content.indexOf(`
237
+ `);return lfIdx===-1||crlfIdx===-1?`
238
+ `:crlfIdx<lfIdx?`\r
239
+ `:`
240
+ `}function normalizeToLF(text){return text.replace(/\r\n/g,`
241
+ `).replace(/\r/g,`
242
+ `)}function restoreLineEndings(text,ending){return ending===`\r
243
+ `?text.replace(/\n/g,`\r
244
+ `):text}function normalizeForFuzzyMatch(text){return text.normalize("NFKC").split(`
245
+ `).map(line=>line.trimEnd()).join(`
246
+ `).replace(/[\u2018\u2019\u201A\u201B]/g,"'").replace(/[\u201C\u201D\u201E\u201F]/g,'"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g,"-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g," ")}function splitLinesWithEndings(content){return content.match(/[^\n]*\n|[^\n]+/g)??[]}function getLineSpans(content){let offset=0;return splitLinesWithEndings(content).map(line=>{let span={start:offset,end:offset+line.length};return offset=span.end,span})}function getReplacementLineRange(lines,replacement){let replacementStart=replacement.matchIndex,replacementEnd=replacement.matchIndex+replacement.matchLength,startLine=-1;for(let i=0;i<lines.length;i++){let line=lines[i];if(replacementStart>=line.start&&replacementStart<line.end){startLine=i;break}}if(startLine===-1)throw new Error("Replacement range is outside the base content.");let endLine=startLine;for(;endLine<lines.length&&lines[endLine].end<replacementEnd;)endLine++;if(endLine>=lines.length)throw new Error("Replacement range is outside the base content.");return{startLine,endLine:endLine+1}}function applyReplacements(content,replacements,offset=0){let result=content;for(let i=replacements.length-1;i>=0;i--){let replacement=replacements[i],matchIndex=replacement.matchIndex-offset;result=result.substring(0,matchIndex)+replacement.newText+result.substring(matchIndex+replacement.matchLength)}return result}function applyReplacementsPreservingUnchangedLines(originalContent,baseContent,replacements){let originalLines=splitLinesWithEndings(originalContent),baseLines=getLineSpans(baseContent);if(originalLines.length!==baseLines.length)throw new Error("Cannot preserve unchanged lines because the base content has a different line count.");let groups=[],sortedReplacements=[...replacements].sort((a,b)=>a.matchIndex-b.matchIndex);for(let replacement of sortedReplacements){let range=getReplacementLineRange(baseLines,replacement),current=groups[groups.length-1];if(current&&range.startLine<current.endLine){current.endLine=Math.max(current.endLine,range.endLine),current.replacements.push(replacement);continue}groups.push({...range,replacements:[replacement]})}let originalLineIndex=0,result="";for(let group of groups){result+=originalLines.slice(originalLineIndex,group.startLine).join("");let groupStartOffset=baseLines[group.startLine].start,groupEndOffset=baseLines[group.endLine-1].end;result+=applyReplacements(baseContent.slice(groupStartOffset,groupEndOffset),group.replacements,groupStartOffset),originalLineIndex=group.endLine}return result+=originalLines.slice(originalLineIndex).join(""),result}function fuzzyFindText(content,oldText){let exactIndex=content.indexOf(oldText);if(exactIndex!==-1)return{found:!0,index:exactIndex,matchLength:oldText.length,usedFuzzyMatch:!1,contentForReplacement:content};let fuzzyContent=normalizeForFuzzyMatch(content),fuzzyOldText=normalizeForFuzzyMatch(oldText),fuzzyIndex=fuzzyContent.indexOf(fuzzyOldText);return fuzzyIndex===-1?{found:!1,index:-1,matchLength:0,usedFuzzyMatch:!1,contentForReplacement:content}:{found:!0,index:fuzzyIndex,matchLength:fuzzyOldText.length,usedFuzzyMatch:!0,contentForReplacement:fuzzyContent}}function stripBom(content){return content.startsWith("\uFEFF")?{bom:"\uFEFF",text:content.slice(1)}:{bom:"",text:content}}function countOccurrences(content,oldText){let fuzzyContent=normalizeForFuzzyMatch(content),fuzzyOldText=normalizeForFuzzyMatch(oldText);return fuzzyContent.split(fuzzyOldText).length-1}function getNotFoundError(path,editIndex,totalEdits){return totalEdits===1?new Error(`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`):new Error(`Could not find edits[${editIndex}] in ${path}. The oldText must match exactly including all whitespace and newlines.`)}function getDuplicateError(path,editIndex,totalEdits,occurrences){return totalEdits===1?new Error(`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`):new Error(`Found ${occurrences} occurrences of edits[${editIndex}] in ${path}. Each oldText must be unique. Please provide more context to make it unique.`)}function getEmptyOldTextError(path,editIndex,totalEdits){return totalEdits===1?new Error(`oldText must not be empty in ${path}.`):new Error(`edits[${editIndex}].oldText must not be empty in ${path}.`)}function getNoChangeError(path,totalEdits){return totalEdits===1?new Error(`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`):new Error(`No changes made to ${path}. The replacements produced identical content.`)}function applyEditsToNormalizedContent(normalizedContent,edits,path){let normalizedEdits=edits.map(edit=>({oldText:normalizeToLF(edit.oldText),newText:normalizeToLF(edit.newText)}));for(let i=0;i<normalizedEdits.length;i++)if(normalizedEdits[i].oldText.length===0)throw getEmptyOldTextError(path,i,normalizedEdits.length);let usedFuzzyMatch=normalizedEdits.map(edit=>fuzzyFindText(normalizedContent,edit.oldText)).some(match=>match.usedFuzzyMatch),replacementBaseContent=usedFuzzyMatch?normalizeForFuzzyMatch(normalizedContent):normalizedContent,matchedEdits=[];for(let i=0;i<normalizedEdits.length;i++){let edit=normalizedEdits[i],matchResult=fuzzyFindText(replacementBaseContent,edit.oldText);if(!matchResult.found)throw getNotFoundError(path,i,normalizedEdits.length);let occurrences=countOccurrences(replacementBaseContent,edit.oldText);if(occurrences>1)throw getDuplicateError(path,i,normalizedEdits.length,occurrences);matchedEdits.push({editIndex:i,matchIndex:matchResult.index,matchLength:matchResult.matchLength,newText:edit.newText})}matchedEdits.sort((a,b)=>a.matchIndex-b.matchIndex);for(let i=1;i<matchedEdits.length;i++){let previous=matchedEdits[i-1],current=matchedEdits[i];if(previous.matchIndex+previous.matchLength>current.matchIndex)throw new Error(`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path}. Merge them into one edit or target disjoint regions.`)}let baseContent=normalizedContent,newContent=usedFuzzyMatch?applyReplacementsPreservingUnchangedLines(normalizedContent,replacementBaseContent,matchedEdits):applyReplacements(replacementBaseContent,matchedEdits);if(baseContent===newContent)throw getNoChangeError(path,normalizedEdits.length);return{baseContent,newContent}}function generateUnifiedPatch(path,oldContent,newContent,contextLines=4){return createTwoFilesPatch(path,path,oldContent,newContent,void 0,void 0,{context:contextLines,headerOptions:FILE_HEADERS_ONLY})}function generateDiffString(oldContent,newContent,contextLines=4){let parts=diffLines(oldContent,newContent),output=[],oldLines=oldContent.split(`
247
+ `),newLines=newContent.split(`
248
+ `),maxLineNum=Math.max(oldLines.length,newLines.length),lineNumWidth=String(maxLineNum).length,oldLineNum=1,newLineNum=1,lastWasChange=!1,firstChangedLine;for(let i=0;i<parts.length;i++){let part=parts[i],raw=part.value.split(`
249
+ `);if(raw[raw.length-1]===""&&raw.pop(),part.added||part.removed){firstChangedLine===void 0&&(firstChangedLine=newLineNum);for(let line of raw)if(part.added){let lineNum=String(newLineNum).padStart(lineNumWidth," ");output.push(`+${lineNum} ${line}`),newLineNum++}else{let lineNum=String(oldLineNum).padStart(lineNumWidth," ");output.push(`-${lineNum} ${line}`),oldLineNum++}lastWasChange=!0}else{let nextPartIsChange=i<parts.length-1&&(parts[i+1].added||parts[i+1].removed),hasLeadingChange=lastWasChange,hasTrailingChange=nextPartIsChange;if(hasLeadingChange&&hasTrailingChange)if(raw.length<=contextLines*2)for(let line of raw){let lineNum=String(oldLineNum).padStart(lineNumWidth," ");output.push(` ${lineNum} ${line}`),oldLineNum++,newLineNum++}else{let leadingLines=raw.slice(0,contextLines),trailingLines=raw.slice(raw.length-contextLines),skippedLines=raw.length-leadingLines.length-trailingLines.length;for(let line of leadingLines){let lineNum=String(oldLineNum).padStart(lineNumWidth," ");output.push(` ${lineNum} ${line}`),oldLineNum++,newLineNum++}output.push(` ${"".padStart(lineNumWidth," ")} ...`),oldLineNum+=skippedLines,newLineNum+=skippedLines;for(let line of trailingLines){let lineNum=String(oldLineNum).padStart(lineNumWidth," ");output.push(` ${lineNum} ${line}`),oldLineNum++,newLineNum++}}else if(hasLeadingChange){let shownLines=raw.slice(0,contextLines),skippedLines=raw.length-shownLines.length;for(let line of shownLines){let lineNum=String(oldLineNum).padStart(lineNumWidth," ");output.push(` ${lineNum} ${line}`),oldLineNum++,newLineNum++}skippedLines>0&&(output.push(` ${"".padStart(lineNumWidth," ")} ...`),oldLineNum+=skippedLines,newLineNum+=skippedLines)}else if(hasTrailingChange){let skippedLines=Math.max(0,raw.length-contextLines);skippedLines>0&&(output.push(` ${"".padStart(lineNumWidth," ")} ...`),oldLineNum+=skippedLines,newLineNum+=skippedLines);for(let line of raw.slice(skippedLines)){let lineNum=String(oldLineNum).padStart(lineNumWidth," ");output.push(` ${lineNum} ${line}`),oldLineNum++,newLineNum++}}else oldLineNum+=raw.length,newLineNum+=raw.length;lastWasChange=!1}}return{diff:output.join(`
250
+ `),firstChangedLine}}var states=new WeakMap;function getState(env){let state=states.get(env);return state||(state={queues:new Map,registration:Promise.resolve()},states.set(env,state)),state}async function getMutationQueueKey(env,path,context){let absolutePath=getOrThrow(await env.absolutePath(path,context));return canonicalKeyPath(env,absolutePath,context)}async function canonicalKeyPath(env,absolutePath,context){let canonicalPath=await env.canonicalPath(absolutePath,context);if(canonicalPath.ok)return canonicalPath.value;if(canonicalPath.error.code==="not_supported")return absolutePath;if(canonicalPath.error.code!=="not_found")throw canonicalPath.error;let parent=getOrThrow(await env.joinPath([absolutePath,".."],context));if(parent===absolutePath||!absolutePath.startsWith(parent))return absolutePath;let name=absolutePath.slice(parent.length+(/[/\\]$/.test(parent)?0:1));return getOrThrow(await env.joinPath([await canonicalKeyPath(env,parent,context),name],context))}async function withFileMutationQueue(env,path,fn,context){let state=getState(env),registration=state.registration.then(async()=>{let key2=await getMutationQueueKey(env,path,context),currentQueue2=state.queues.get(key2)??Promise.resolve(),releaseNext2=()=>{},nextQueue=new Promise(resolve=>{releaseNext2=resolve}),chainedQueue2=currentQueue2.then(()=>nextQueue);return state.queues.set(key2,chainedQueue2),{key:key2,currentQueue:currentQueue2,chainedQueue:chainedQueue2,releaseNext:releaseNext2}});state.registration=registration.then(()=>{},()=>{});let{key,currentQueue,chainedQueue,releaseNext}=await registration;await currentQueue;try{return await fn()}finally{releaseNext(),state.queues.get(key)===chainedQueue&&state.queues.delete(key)}}var UNICODE_SPACES=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g,NARROW_NO_BREAK_SPACE="\u202F";function normalizeToolPath(path){let normalized=path.replace(UNICODE_SPACES," ");return normalized.startsWith("@")?normalized.slice(1):normalized}async function resolveToolPath(env,path,context){return getOrThrow(await env.absolutePath(normalizeToolPath(path),context))}async function resolveReadToolPath(env,path,context){let resolved2=await resolveToolPath(env,path,context),variants=[resolved2,resolved2.replace(/ (AM|PM)\./gi,`${NARROW_NO_BREAK_SPACE}$1.`),resolved2.normalize("NFD"),resolved2.replace(/'/g,"\u2019"),resolved2.normalize("NFD").replace(/'/g,"\u2019")];for(let variant of new Set(variants))if(getOrThrow(await env.exists(variant,context)))return variant;return resolved2}var NO_CHANGE={fileMayHaveChanged:!1};async function runPostMutate(hook,input){if(!hook)return NO_CHANGE;let result;try{result=await hook(input)}catch(error){return{fileMayHaveChanged:!0,note:`postMutate hook failed: ${errorMessage(error)}`}}return{fileMayHaveChanged:result.changed,note:result.note}}function appendPostMutateNote(text,...notes){return[text,...notes.filter(note=>note!==void 0)].join(`
251
+ `)}function errorMessage(error){return error instanceof Error?error.message:String(error)}var replaceEditSchema=typebox_exports.Object({oldText:typebox_exports.String({description:"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."}),newText:typebox_exports.String({description:"Replacement text for this targeted edit."})},{}),editSchema=typebox_exports.Object({path:typebox_exports.String({description:"Path to the file to edit (relative or absolute)"}),edits:typebox_exports.Array(replaceEditSchema,{description:"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."})},{});function isSingleEditInput(value2){if(!value2||typeof value2!="object"||Array.isArray(value2))return!1;let edit=value2;return typeof edit.oldText=="string"&&typeof edit.newText=="string"}function prepareEditArguments(input){if(!input||typeof input!="object"||Array.isArray(input))return input;let args={...input};if(typeof args.edits=="string")try{let parsed=JSON.parse(args.edits);Array.isArray(parsed)?args.edits=parsed:isSingleEditInput(parsed)&&(args.edits=[parsed])}catch{}else isSingleEditInput(args.edits)&&(args.edits=[args.edits]);let legacy=args;if(typeof legacy.oldText!="string"||typeof legacy.newText!="string")return args;let edits=Array.isArray(legacy.edits)?[...legacy.edits]:[];edits.push({oldText:legacy.oldText,newText:legacy.newText});let{oldText:_oldText,newText:_newText,...rest}=legacy;return{...rest,edits}}function validateEditInput(input){if(!Array.isArray(input.edits)||input.edits.length===0)throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");return{path:input.path,edits:input.edits}}function editAccessError(path,error){return new Error(`Could not edit file: ${path}. Error code: ${error.code}.`,{cause:error})}function createEditTool(){return{name:"edit",label:"edit",description:"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.",parameters:editSchema,prepareArguments:prepareEditArguments,async execute(_toolCallId,input,_onUpdate,{env,postMutate},_invocation,context){let{path,edits}=validateEditInput(input),absolutePath=await resolveToolPath(env,path,context);return withFileMutationQueue(env,absolutePath,async()=>{if(context.abortSignal?.aborted)throw new Error("Operation aborted");let info=await env.fileInfo(absolutePath,context);if(!info.ok)throw editAccessError(path,info.error);if(info.value.kind!=="file"&&info.value.kind!=="symlink")throw new Error(`Could not edit file: ${path}. Path is not a file.`);let readResult=await env.readTextFile(absolutePath,context);if(!readResult.ok)throw editAccessError(path,readResult.error);if(context.abortSignal?.aborted)throw new Error("Operation aborted");let{bom,text:content}=stripBom(readResult.value),originalEnding=detectLineEnding(content),normalizedContent=normalizeToLF(content),{baseContent,newContent}=applyEditsToNormalizedContent(normalizedContent,edits,path);if(context.abortSignal?.aborted)throw new Error("Operation aborted");let finalContent=bom+restoreLineEndings(newContent,originalEnding),writeResult=await env.writeFile(absolutePath,finalContent,context);if(!writeResult.ok)throw editAccessError(path,writeResult.error);if(context.abortSignal?.aborted)throw new Error("Operation aborted");let outcome=await runPostMutate(postMutate,{tool:"edit",path:absolutePath,signal:context.abortSignal});if(context.abortSignal?.aborted)throw new Error("Operation aborted");let committedContent=newContent,rereadNote;if(outcome.fileMayHaveChanged){let postMutateRead=await env.readTextFile(absolutePath,context);postMutateRead.ok?committedContent=normalizeToLF(stripBom(postMutateRead.value).text):rereadNote=`postMutate left the file unreadable: ${postMutateRead.error.code}. Reported diff describes the edit before the hook ran.`}let diffResult=generateDiffString(baseContent,committedContent);return{content:[{type:"text",text:appendPostMutateNote(`Successfully replaced ${edits.length} block(s) in ${path}.`,outcome.note,rereadNote)}],details:{diff:diffResult.diff,patch:generateUnifiedPatch(path,baseContent,committedContent),firstChangedLine:diffResult.firstChangedLine}}},context)}}}var HeaderProtection=class{constructor(){this.intervals=[]}get active(){return this.pending!==void 0}get unfinished(){return this.pending!==void 0}word(word,previous,depth,line,typescript){if(this.target=void 0,typescript&&["keyof","typeof","infer","readonly","satisfies","as"].includes(word))return!1;if((word==="class"||word==="function")&&previous!=="."){if(this.pending)return!1;this.pending={kind:word,depth,startLine:line}}return!0}open(char,depth,previous,line){let header=this.pending;return char!=="{"||header?.depth!==depth||header.kind==="function"&&previous!==")"?!1:(this.protect(header.startLine,line),this.pending=void 0,this.parameters=void 0,header.kind==="class")}close(open,depth,line){this.target=open.target?open.line:void 0;let startLine=open.headerLine??open.line;open.protected&&(open.signature||open.char!=="(")&&this.protect(startLine,line),open.char==="("&&!open.call&&!open.control&&(this.parameters={depth,startLine})}punctuation(token,depth,line){let target=this.target;return this.target=void 0,token==="="&&target!==void 0&&this.protect(target,line),token===":"&&this.parameters?.depth===depth?!1:((token==="{"||token==="=>")&&this.parameters?.depth===depth?(this.protect(this.parameters.startLine,line),this.parameters=void 0):(token===";"||token==="="||token===",")&&(this.parameters=void 0),!0)}protect(startLine,endLine){this.intervals.push({startLine,endLine})}filter(ranges){return ranges.filter(range=>!this.intervals.some(header=>range.startLine<=header.endLine&&range.endLine>=header.startLine))}};var expressionKeywords=new Set(["return","throw","yield","await","case","typeof","void","delete","in","of","instanceof"]),controls=new Set(["if","while","for","switch","catch","with"]),signatureDeclarations=new Set(["type","interface","enum","namespace","module","declare"]);function isCallCallee(previous,beforeWord){return/^[A-Za-z_$][\w$]*$/.test(previous)&&!["function","async","new"].includes(previous)&&!expressionKeywords.has(previous)&&!controls.has(previous)&&[".","=",":","return","await","new"].includes(beforeWord)}function stringSpan(source,start,delimiter3){let newlines=0;for(let i=start;i<source.length;i++){if(source[i]===delimiter3)return{end:i+1,newlines};if(source[i]===`
252
+ `||source[i]==="\r")return;source[i]==="\\"&&(source[i+1]==="\r"&&source[i+2]===`
253
+ `&&i++,source[i+1]===`
254
+ `&&newlines++,i++)}}function typeArgumentsSpan(source,start){let delimiters=["<"],newlines=0;for(let i=start;i<source.length;i++){let char=source[i];if(char===`
255
+ `&&newlines++,char==='"'||char==="'"){let span=stringSpan(source,i+1,char);if(!span)return;newlines+=span.newlines,i=span.end-1}else if(char==="<"||char==="[")delimiters.push(char);else if(char===">"||char==="]"){if(delimiters.pop()!==(char===">"?"<":"["))return;if(!delimiters.length)return{end:i+1,newlines}}else if(!/[A-Za-z_$0-9\s,.?|&]/.test(char))return}}function lineCommentEnd(source,start){let end=start;for(;end<source.length&&!/[\n\r\u2028\u2029]/.test(source[end]);)end++;return end}function commentSpan(source,start){let newlines=0;for(let i=start;i<source.length;i++)if(source[i]===`
256
+ `&&newlines++,source.startsWith("*/",i))return{end:i+2,newlines}}function regexSpan(source,start){let characterClass=!1;for(let i=start;i<source.length;i++){if(source[i]===`
257
+ `||source[i]==="\r"||source[i]==="\u2028"||source[i]==="\u2029")return;if(source[i]==="\\"){if(/[\r\n\u2028\u2029]/.test(source[i+1]??""))return;i++;continue}if(source[i]==="["&&(characterClass=!0),source[i]==="]"&&(characterClass=!1),source[i]==="/"&&!characterClass){let end=i+1;for(;/[a-z]/i.test(source[end]??"");)end++;let flags=source.slice(i+1,end);return/[^dgimsuy]/.test(flags)||new Set(flags).size!==flags.length?void 0:{end,newlines:0}}}}function scanBraces(source,language,settings){let ranges=[],stack=[],headers=new HeaderProtection,fail=reason=>({status:"parse_failure",reason}),line=1,i=0,template=!1,templateDepth=0,previous="",beforeWord="",wordLine=1,valueArrow=!1,expressionEnd=!1,importClause=!1,ambiguousAngleDepth,signatureDeclaration=!1;if(source.startsWith("#!")){let end=source.indexOf(`
258
+ `);i=end<0?source.length:end}for(;i<source.length;){let char=source[i],next=source[i+1];if(char===`
259
+ `&&line++,template){if(char==="\\"){next===`
260
+ `&&line++,i+=2;continue}if(char==="`")template=!1,templateDepth--,expressionEnd=!0,previous="literal";else if(char==="$"&&next==="{"){stack.push({char:"{",line,foldable:!1,protected:!0,signature:!1,interpolation:!0,control:!1,call:!1,valueParameters:!1,declaration:!1}),template=!1,expressionEnd=!1,previous="{",i+=2;continue}i++;continue}if(/\s/.test(char)){i++;continue}if(char==="/"&&next==="/"){i=lineCommentEnd(source,i);continue}if(char==="/"&&next==="*"){let span=commentSpan(source,i+2);if(!span)return fail("unterminated_comment");span.newlines+1>=settings.minCommentLines&&templateDepth===0&&!stack.some(open=>open.protected)&&!source.startsWith("/**",i)&&!source.startsWith("/*!",i)&&ranges.push({startLine:line+1,endLine:line+span.newlines-1}),(source.startsWith("/**",i)||source.startsWith("/*!",i))&&headers.protect(line,line+span.newlines),line+=span.newlines,i=span.end;continue}if(char==='"'||char==="'"){let span=stringSpan(source,i+1,char);if(!span)return fail("unterminated_string");line+=span.newlines,i=span.end,previous="literal",expressionEnd=!0,stack.length||(importClause=!1);continue}if(char==="`"){template=!0,templateDepth++,i++;continue}if(char==="/"){if(expressionEnd===null)return fail("ambiguous_regex_literal");if(!expressionEnd){let span=regexSpan(source,i+1);if(!span)return fail("ambiguous_or_unterminated_regex");i=span.end,previous="literal",expressionEnd=!0;continue}i+=next==="="?2:1,expressionEnd=!1,previous="/";continue}if(/[A-Za-z_$]/.test(char)){let start=i++;for(;/[A-Za-z_$0-9]/.test(source[i]??"");)i++;if(beforeWord=previous,previous=source.slice(start,i),wordLine=line,!headers.word(previous,beforeWord,stack.length,line,language==="ts"))return fail("unproved_header");expressionEnd=!expressionKeywords.has(previous),language==="ts"&&signatureDeclarations.has(previous)&&(signatureDeclaration=!0),previous==="import"&&(importClause=!0),previous==="from"&&(importClause=!1);continue}if(/[0-9]/.test(char)){for(i++;/[A-Za-z_0-9.]/.test(source[i]??"");)i++;expressionEnd=!0,previous="number";continue}if(char==="{"||char==="["||char==="("){if(char==="{"&&ambiguousAngleDepth!==void 0)return fail("ambiguous_angle_syntax");if(language!=="json"&&char!=="("&&previous===","&&!stack.some(open=>open.protected)&&stack.at(-1)?.char!=="["&&!stack.at(-1)?.call)return fail("ambiguous_binding");let classBody=headers.open(char,stack.length,previous,line);if(!headers.punctuation(char,stack.length,line))return fail("unproved_header");let call=char==="("&&isCallCallee(previous,beforeWord),declaration=signatureDeclaration&&!stack.some(open=>open.declaration),signature=declaration||headers.active||stack.some(open=>open.signature)||language!=="json"&&char==="["&&stack.at(-1)?.char==="{"||importClause||["const","let","var","export","type","#","!"].includes(previous)||language!=="json"&&[":","<","&","|"].includes(previous)||language==="ts"&&previous==="=>"&&!valueArrow,protectedRange=signature||char==="("&&!call&&!(previous==="=>"&&valueArrow)||stack.some(open=>open.protected),foldable=templateDepth===0&&char!=="("&&!classBody&&!protectedRange&&(char==="{"||!expressionEnd||language==="json");stack.push({char,line,headerLine:char==="("?wordLine:line,target:char!=="("&&!expressionEnd,foldable,protected:protectedRange,signature,interpolation:!1,control:char==="("&&controls.has(previous),call,valueParameters:char==="("&&stack.at(-1)?.call===!0&&["(",","].includes(previous),declaration}),valueArrow=!1,expressionEnd=!1,previous=char,i++;continue}if(char==="}"||char==="]"||char===")"){let open=stack.pop();if(ambiguousAngleDepth!==void 0&&stack.length<ambiguousAngleDepth&&(ambiguousAngleDepth=void 0),!open||{"{":"}","[":"]","(":")"}[open.char]!==char)return fail("unbalanced_delimiters");if(open.interpolation){template=!0,i++;continue}headers.close(open,stack.length,line),open.foldable&&line-open.line-1>=settings.minBodyLines&&ranges.push({startLine:open.line+1,endLine:line-1}),valueArrow=open.valueParameters,open.declaration&&(signatureDeclaration=!1),expressionEnd=open.control?!1:char==="}"?null:!0,char==="}"&&(importClause=!1),previous=char,i++;continue}if((char==="+"||char==="-")&&next===char){previous=char+char,i+=2;continue}if(char==="<"&&language==="ts"&&expressionEnd){let span=typeArgumentsSpan(source,i+1);if(span){line+=span.newlines,i=span.end,previous=">";continue}/^\s*\{/.test(source.slice(i+1))||(ambiguousAngleDepth=stack.length)}if(char==="<"&&!expressionEnd&&/^<\/?[A-Za-z]/.test(source.slice(i)))return fail("ambiguous_angle_syntax");if(!";:,.?=><!~+-*%&|^".includes(char))return fail("unknown_token");if(char===";"&&(importClause=!1,signatureDeclaration=!1,ambiguousAngleDepth===stack.length&&(ambiguousAngleDepth=void 0)),!headers.punctuation(char==="="&&next===">"?"=>":char,stack.length,line))return fail("unproved_header");valueArrow=valueArrow&&previous===")"&&char==="="&&next===">",previous=char==="="&&next===">"?"=>":char,i+=previous==="=>"?2:1,expressionEnd=char==="."?null:!1}return template||templateDepth||stack.length||headers.unfinished?fail("unbalanced_or_unproved_header"):{status:"parsed",ranges:headers.filter(ranges)}}var READ_FOLD_SETTINGS=Object.freeze({minBodyLines:4,minCommentLines:6,minTotalLines:100,unfoldUntil:50,unfoldLimit:100});var READ_FOLDER_SELECTION=Object.freeze({head:"6da8ef1361ef73928df8685e071f2a1826d3b17e",selectionSha256:"d7c502a1597e652f584877c0004ba6cde7c9393c8661ccbc388e3661ae66a634",wasm:!0,rawReasons:Object.freeze({ts:"wasm_candidate_below_threshold",tsx:"wasm_candidate_below_threshold"}),languages:Object.freeze({ts:"raw",js:"wasm",json:"heuristic",tsx:"raw",python:"unsupported",rust:"unsupported",go:"unsupported",markdown:"prose_exempt",txt:"prose_exempt"})});function languageForPath(path){let name=path.split(/[\\/]/).pop()?.toLowerCase()??"";if(name.includes("."))switch(name.slice(name.lastIndexOf(".")+1)){case"ts":return"ts";case"js":return"js";case"json":return"json";case"tsx":return"tsx";case"py":return"python";case"rs":return"rust";case"go":return"go";case"md":case"markdown":case"mdown":case"mkd":case"mkdn":return"markdown";case"txt":return"txt";default:return}}function readSummaryEngineForPath(path){let language=languageForPath(path);return language===void 0?void 0:READ_FOLDER_SELECTION.languages[language]}function isReadSummaryPath(path){let engine=readSummaryEngineForPath(path);return engine==="heuristic"||engine==="wasm"}function fold({path,text,settings}){let language=languageForPath(path);if(!language)return{status:"unsupported",reason:"unsupported_language"};let engine=READ_FOLDER_SELECTION.languages[language];switch(engine){case"unsupported":return{status:"unsupported",reason:"unsupported_language"};case"prose_exempt":return{status:"unsupported",reason:"prose_exempt"};case"raw":case"heuristic":case"wasm":break;default:return engine}if(language!=="ts"&&language!=="js"&&language!=="json")return{status:"unsupported",reason:"unsupported_language"};if(language==="json")try{JSON.parse(text)}catch(error){if(error instanceof SyntaxError)return{status:"parse_failure",reason:"invalid_json"};throw error}return composeFoldResult(text,scanBraces(text,language,settings))}var selectedReadFolder=Object.freeze({id:"measured-brace",version:"3",fold});async function prepareReadFolder(path,folder,options={}){if(!folder||folder!==selectedReadFolder)return folder;let language=languageForPath(path);if(!language||readSummaryEngineForPath(path)!=="wasm")return folder;try{let{loadTreeSitterFolder}=await import("./engine-RCHMSSBT.js");return await loadTreeSitterFolder(language,{...options,fallback:folder})??folder}catch{return folder}}function createDefaultReadSummary(input){let{path,text,offset,limit,folder,truncated}=input;if(!folder||offset!==void 0||limit!==void 0||truncated||!isReadSummaryPath(path)||text.includes("\0")||text.split(`
261
+ `).length<READ_FOLD_SETTINGS.minTotalLines)return;let view=createSegmentedReadView({text,parsed:folder.fold({path,text,settings:READ_FOLD_SETTINGS})});switch(view.status){case"summary":return view.rendered;case"no_summary":return;default:return view}}var InvalidReadSegmentsError=class extends Error{constructor(){super("Read segments must cover the source exactly, in order, without altering kept lines"),this.code="invalid_segments"}};function validRange(range,total){return Number.isSafeInteger(range.startLine)&&Number.isSafeInteger(range.endLine)&&range.startLine>=1&&range.endLine>=range.startLine&&range.endLine<=total}function renderSegmentedReadView({text,segments}){let lines=text.split(`
262
+ `),parts=[],elidedRanges=[],cursor=1;for(let segment of segments){if(!validRange(segment,lines.length)||segment.startLine!==cursor)throw new InvalidReadSegmentsError;switch(segment.kind){case"kept":if(segment.text!==lines.slice(segment.startLine-1,segment.endLine).join(`
263
+ `))throw new InvalidReadSegmentsError;parts.push(segment.text);break;case"elided":parts.push("\u2026"),elidedRanges.push({startLine:segment.startLine,endLine:segment.endLine});break;default:throw new InvalidReadSegmentsError}cursor=segment.endLine+1}if(cursor!==lines.length+1)throw new InvalidReadSegmentsError;let rereads=elidedRanges.map(range=>({offset:range.startLine,limit:range.endLine-range.startLine+1})),footerText=rereads.length?`[Elided source: ${rereads.map(r=>`offset=${r.offset} limit=${r.limit}`).join("; ")}. Reread source before editing; markers are not source.]`:"";return footerText&&parts.push("",footerText),{text:parts.join(`
264
+ `),elidedRanges,footer:{text:footerText,rereads}}}function validHierarchy(ranges,total){let queue=[{ranges,startLine:0,endLine:total+1}];for(let i=0;i<queue.length;i++){let parent=queue[i],previous=parent.startLine;for(let range of parent.ranges){if(!validRange(range,total)||range.startLine<=previous||range.endLine>=parent.endLine)return!1;previous=range.endLine,queue.push({ranges:range.children,startLine:range.startLine,endLine:range.endLine})}}return!0}var lengthOf=range=>range.endLine-range.startLine+1;function createSegmentedReadView({text,parsed}){let raw=reason=>({status:"no_summary",reason});switch(parsed.status){case"unsupported":return raw(parsed.reason);case"parse_failure":return raw("parse_failure");case"parsed":break;default:return parsed}if(parsed.text!==text)return raw("stale_source");let lines=text.split(`
265
+ `);if(!validHierarchy(parsed.ranges,lines.length))return raw("invalid_ranges");if(lines.length<READ_FOLD_SETTINGS.minTotalLines)return raw("too_short");if(!parsed.ranges.length)return raw("no_elision");let visible=lines.length-parsed.ranges.reduce((sum,r)=>sum+lengthOf(r),0);if(visible>READ_FOLD_SETTINGS.unfoldLimit)return raw("skeleton_exceeds_budget");let selected=new Set(parsed.ranges),queue=[...parsed.ranges];for(let i=0;visible<READ_FOLD_SETTINGS.unfoldUntil&&i<queue.length;i++){let parent=queue[i],nextVisible=visible+lengthOf(parent)-parent.children.reduce((sum,r)=>sum+lengthOf(r),0);if(!(nextVisible>READ_FOLD_SETTINGS.unfoldLimit)){selected.delete(parent);for(let child of parent.children)selected.add(child);queue.push(...parent.children),visible=nextVisible}}if(visible<READ_FOLD_SETTINGS.unfoldUntil)return raw("visible_budget_unreachable");if(!selected.size)return raw("no_elision");let segments=[],cursor=1;for(let range of[...selected].sort((a,b)=>a.startLine-b.startLine))cursor<range.startLine&&segments.push({kind:"kept",startLine:cursor,endLine:range.startLine-1,text:lines.slice(cursor-1,range.startLine-1).join(`
266
+ `)}),segments.push({kind:"elided",startLine:range.startLine,endLine:range.endLine}),cursor=range.endLine+1;cursor<=lines.length&&segments.push({kind:"kept",startLine:cursor,endLine:lines.length,text:lines.slice(cursor-1).join(`
267
+ `)});let rendered=renderSegmentedReadView({text,segments}),encoder=new TextEncoder;return encoder.encode(rendered.text).length>=encoder.encode(text).length?raw("no_output_saving"):{status:"summary",segments,visibleSourceLines:visible,rendered}}var PNG_SIGNATURE=[137,80,78,71,13,10,26,10];function detectSupportedImageMimeType(buffer){if(startsWith(buffer,[255,216,255]))return buffer[3]===247?void 0:"image/jpeg";if(startsWith(buffer,PNG_SIGNATURE))return isPng(buffer)&&!isAnimatedPng(buffer)?"image/png":void 0;if(startsWithAscii(buffer,0,"GIF87a")||startsWithAscii(buffer,0,"GIF89a"))return"image/gif";if(startsWithAscii(buffer,0,"RIFF")&&startsWithAscii(buffer,8,"WEBP"))return"image/webp";if(startsWithAscii(buffer,0,"BM")&&isBmp(buffer))return"image/bmp"}function encodeBase64(bytes){let alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",output="";for(let index=0;index<bytes.length;index+=3){let first=bytes[index]??0,second=bytes[index+1],third=bytes[index+2];output+=alphabet[first>>2],output+=alphabet[(first&3)<<4|(second??0)>>4],output+=second===void 0?"=":alphabet[(second&15)<<2|(third??0)>>6],output+=third===void 0?"=":alphabet[third&63]}return output}function isPng(buffer){return buffer.length>=16&&readUint32BE(buffer,PNG_SIGNATURE.length)===13&&startsWithAscii(buffer,12,"IHDR")}function isAnimatedPng(buffer){let offset=PNG_SIGNATURE.length;for(;offset+8<=buffer.length;){let chunkLength=readUint32BE(buffer,offset),chunkTypeOffset=offset+4;if(startsWithAscii(buffer,chunkTypeOffset,"acTL"))return!0;if(startsWithAscii(buffer,chunkTypeOffset,"IDAT"))return!1;let nextOffset=offset+8+chunkLength+4;if(nextOffset<=offset||nextOffset>buffer.length)return!1;offset=nextOffset}return!1}function isBmp(buffer){if(buffer.length<26)return!1;let declaredFileSize=readUint32LE(buffer,2),pixelDataOffset=readUint32LE(buffer,10),dibHeaderSize=readUint32LE(buffer,14);if(declaredFileSize!==0&&declaredFileSize<26||pixelDataOffset<14+dibHeaderSize||declaredFileSize!==0&&pixelDataOffset>=declaredFileSize)return!1;let colorPlanes,bitsPerPixel;if(dibHeaderSize===12)colorPlanes=readUint16LE(buffer,22),bitsPerPixel=readUint16LE(buffer,24);else if(dibHeaderSize>=40&&dibHeaderSize<=124){if(buffer.length<30)return!1;colorPlanes=readUint16LE(buffer,26),bitsPerPixel=readUint16LE(buffer,28)}else return!1;return colorPlanes===1&&[1,4,8,16,24,32].includes(bitsPerPixel)}function readUint16LE(buffer,offset){return(buffer[offset]??0)+((buffer[offset+1]??0)<<8)}function readUint32BE(buffer,offset){return(buffer[offset]??0)*16777216+((buffer[offset+1]??0)<<16)+((buffer[offset+2]??0)<<8)+(buffer[offset+3]??0)}function readUint32LE(buffer,offset){return(buffer[offset]??0)+((buffer[offset+1]??0)<<8)+((buffer[offset+2]??0)<<16)+(buffer[offset+3]??0)*16777216}function startsWith(buffer,bytes){return buffer.length<bytes.length?!1:bytes.every((byte,index)=>buffer[index]===byte)}function startsWithAscii(buffer,offset,text){if(buffer.length<offset+text.length)return!1;for(let index=0;index<text.length;index++)if(buffer[offset+index]!==text.charCodeAt(index))return!1;return!0}var readSchema=typebox_exports.Object({path:typebox_exports.String({description:"Path to the file to read (relative or absolute)"}),offset:typebox_exports.Optional(typebox_exports.Number({description:"Line number to start reading from (1-indexed)"})),limit:typebox_exports.Optional(typebox_exports.Number({description:"Maximum number of lines to read"}))});function createReadTool(options={folder:selectedReadFolder}){return{name:"read",label:"read",description:`Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${2e3} lines or ${51200/1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,parameters:readSchema,async execute(_toolCallId,{path,offset,limit},_onUpdate,{env},_invocation,context){let absolutePath=await resolveReadToolPath(env,path,context),bytes=getOrThrow(await env.readBinaryFile(absolutePath,context));if(context.abortSignal?.aborted)throw new FileError("aborted","Operation aborted",absolutePath);let mimeType=detectSupportedImageMimeType(bytes);if(mimeType){if(options?.imageProcessor){let processed=await options.imageProcessor(bytes,mimeType,{autoResizeImages:options.autoResizeImages??!0},context);if(!processed.ok)return{content:[{type:"text",text:`Read image file [${mimeType}]
268
+ ${processed.message}`}],details:void 0};let hints=processed.hints.length>0?`
269
+ ${processed.hints.join(`
270
+ `)}`:"";return{content:[{type:"text",text:`Read image file [${processed.mimeType}]${hints}`},{type:"image",data:processed.data,mimeType:processed.mimeType}],details:void 0}}return mimeType==="image/bmp"?{content:[{type:"text",text:`Read image file [image/bmp]
271
+ [Image omitted: configure an imageProcessor to convert BMP images.]`}],details:void 0}:{content:[{type:"text",text:`Read image file [${mimeType}]`},{type:"image",data:encodeBase64(bytes),mimeType}],details:void 0}}let textContent=new TextDecoder().decode(bytes),allLines=textContent.split(`
272
+ `),totalFileLines=allLines.length,startLine=offset?Math.max(0,offset-1):0,startLineDisplay=startLine+1;if(startLine>=allLines.length)throw new Error(`Offset ${offset} is beyond end of file (${allLines.length} lines total)`);let selectedContent,userLimitedLines;if(limit!==void 0){let endLine=Math.min(startLine+limit,allLines.length);selectedContent=allLines.slice(startLine,endLine).join(`
273
+ `),userLimitedLines=endLine-startLine}else selectedContent=allLines.slice(startLine).join(`
274
+ `);let truncation=truncateHead(selectedContent),folder=await prepareReadFolder(absolutePath,options.folder),summary=createDefaultReadSummary({path:absolutePath,text:textContent,offset,limit,folder,truncated:truncation.truncated}),outputText,details;if(summary)outputText=summary.text;else if(truncation.firstLineExceedsLimit){let firstLineSize=formatSize(new TextEncoder().encode(allLines[startLine]).byteLength);outputText=`[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(51200)} limit. Use bash: sed -n '${startLineDisplay}p' ${path} | head -c ${51200}]`,details={truncation}}else if(truncation.truncated){let endLineDisplay=startLineDisplay+truncation.outputLines-1,nextOffset=endLineDisplay+1;outputText=truncation.content,truncation.truncatedBy==="lines"?outputText+=`
275
+
276
+ [Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`:outputText+=`
277
+
278
+ [Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(51200)} limit). Use offset=${nextOffset} to continue.]`,details={truncation}}else if(userLimitedLines!==void 0&&startLine+userLimitedLines<allLines.length){let remaining=allLines.length-(startLine+userLimitedLines),nextOffset=startLine+userLimitedLines+1;outputText=`${truncation.content}
279
+
280
+ [${remaining} more lines in file. Use offset=${nextOffset} to continue.]`}else outputText=truncation.content;return{content:[{type:"text",text:outputText}],details}}}}var writeSchema=typebox_exports.Object({path:typebox_exports.String({description:"Path to the file to write (relative or absolute)"}),content:typebox_exports.String({description:"Content to write to the file"})});function createWriteTool(){return{name:"write",label:"write",description:"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",parameters:writeSchema,async execute(_toolCallId,{path,content},_onUpdate,{env,postMutate},_invocation,context){let absolutePath=await resolveToolPath(env,path,context);return withFileMutationQueue(env,absolutePath,async()=>{if(context.abortSignal?.aborted)throw new Error("Operation aborted");if(getOrThrow(await env.writeFile(absolutePath,content,context)),context.abortSignal?.aborted)throw new Error("Operation aborted");let outcome=await runPostMutate(postMutate,{tool:"write",path:absolutePath,signal:context.abortSignal});if(context.abortSignal?.aborted)throw new Error("Operation aborted");return{content:[{type:"text",text:appendPostMutateNote(`Successfully wrote to ${path}`,outcome.note)}],details:void 0}},context)}}}function progressFrom(output){return{output:output.text,truncation:{content:output.text,...output.truncation},...output.spillPath===void 0?{}:{fullOutputPath:output.spillPath},lastLineBytes:output.lastLineBytes??0}}async function executeShellWithCapture(env,command,options,context){let output,result=await env.exec(command,{cwd:options?.cwd,env:options?.env,inheritEnv:options?.inheritEnv,timeout:options?.timeout,capture:{limits:{maxBytes:51200,maxLines:2e3,retain:"tail"},spill:!0},onUpdate:(update,updateContext)=>{let previous=output;output=applyShellOutputUpdate(output,update);let chunk=update.kind==="append"||update.kind==="slide"?update.text:update.kind==="replace"&&previous===void 0?output.text:void 0;if(chunk)return options?.onChunk?.(chunk,()=>progressFrom(output),updateContext)}},context);if(output===void 0){let{content,...truncation}=truncateTail("");output={text:content,truncation}}let progress=progressFrom(output);return result.ok?ok({...progress,exitCode:result.value.exitCode,cancelled:!1,truncated:result.value.truncation.truncated}):result.error.code==="aborted"||context.abortSignal?.aborted?ok({...progress,exitCode:void 0,cancelled:!0,truncated:progress.truncation.truncated}):options?.returnExecutionErrors?ok({...progress,exitCode:void 0,cancelled:!1,truncated:progress.truncation.truncated,executionError:result.error}):err(result.error)}var ProxyMessageEventStream=class extends EventStream{constructor(){super(event=>event.type==="done"||event.type==="error",event=>{if(event.type==="done")return event.message;if(event.type==="error")return event.error;throw new Error("Unexpected event type")})}};function buildProxyRequestOptions(options){return{temperature:options.temperature,samplingParams:options.samplingParams,maxTokens:options.maxTokens,reasoning:options.reasoning,thinkingSelection:options.thinkingSelection,cacheRetention:options.cacheRetention,sessionId:options.sessionId,headers:options.headers,metadata:options.metadata,transport:options.transport,thinkingBudgets:options.thinkingBudgets,maxRetryDelayMs:options.maxRetryDelayMs}}function streamProxy(model,context,options){let stream=new ProxyMessageEventStream;return(async()=>{let partial={role:"assistant",stopReason:"pending",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},timestamp:Date.now()},reader,abortHandler=()=>{reader&&reader.cancel("Request aborted by user").catch(()=>{})};options.signal&&options.signal.addEventListener("abort",abortHandler);try{let response=await fetch(`${options.proxyUrl}/api/stream`,{method:"POST",headers:{Authorization:`Bearer ${options.authToken}`,"Content-Type":"application/json"},body:JSON.stringify({model,context,options:buildProxyRequestOptions(options)}),signal:options.signal});if(!response.ok){let errorMessage2=`Proxy error: ${response.status} ${response.statusText}`;try{let errorData=await response.json();errorData.error&&(errorMessage2=`Proxy error: ${errorData.error}`)}catch{}throw new Error(errorMessage2)}reader=response.body.getReader();let decoder=new TextDecoder,buffer="",sawTerminalEvent=!1,processLine=line=>{if(!line.startsWith("data: "))return;let data=line.slice(6).trim();if(!data)return;let proxyEvent=JSON.parse(data),event=processProxyEvent(proxyEvent,partial);event&&((event.type==="done"||event.type==="error")&&(sawTerminalEvent=!0),stream.push(event))};for(;;){let{done,value:value2}=await reader.read();if(done)break;if(options.signal?.aborted)throw new Error("Request aborted by user");buffer+=decoder.decode(value2,{stream:!0});let lines=buffer.split(`
281
+ `);buffer=lines.pop()||"";for(let line of lines)processLine(line)}if(options.signal?.aborted)throw new Error("Request aborted by user");buffer+=decoder.decode(),buffer&&processLine(buffer),sawTerminalEvent||(partial.stopReason="error",partial.errorMessage="Connection closed by proxy server before the response completed",stream.push({type:"error",reason:"error",error:partial})),stream.end()}catch(error){let errorMessage2=error instanceof Error?error.message:String(error),reason=options.signal?.aborted?"aborted":"error";partial.stopReason=reason,partial.errorMessage=errorMessage2,stream.push({type:"error",reason,error:partial}),stream.end()}finally{options.signal&&options.signal.removeEventListener("abort",abortHandler)}})(),stream}function processProxyEvent(proxyEvent,partial){switch(proxyEvent.type){case"start":return{type:"start",partial};case"text_start":return partial.content[proxyEvent.contentIndex]={type:"text",text:""},{type:"text_start",contentIndex:proxyEvent.contentIndex,partial};case"text_delta":{let content=partial.content[proxyEvent.contentIndex];if(content?.type==="text")return content.text+=proxyEvent.delta,{type:"text_delta",contentIndex:proxyEvent.contentIndex,delta:proxyEvent.delta,partial};throw new Error("Received text_delta for non-text content")}case"text_end":{let content=partial.content[proxyEvent.contentIndex];if(content?.type==="text")return content.textSignature=proxyEvent.contentSignature,{type:"text_end",contentIndex:proxyEvent.contentIndex,content:content.text,partial};throw new Error("Received text_end for non-text content")}case"thinking_start":return partial.content[proxyEvent.contentIndex]={type:"thinking",thinking:""},{type:"thinking_start",contentIndex:proxyEvent.contentIndex,partial};case"thinking_delta":{let content=partial.content[proxyEvent.contentIndex];if(content?.type==="thinking")return content.thinking+=proxyEvent.delta,{type:"thinking_delta",contentIndex:proxyEvent.contentIndex,delta:proxyEvent.delta,partial};throw new Error("Received thinking_delta for non-thinking content")}case"thinking_end":{let content=partial.content[proxyEvent.contentIndex];if(content?.type==="thinking")return content.thinkingSignature=proxyEvent.contentSignature,{type:"thinking_end",contentIndex:proxyEvent.contentIndex,content:content.thinking,partial};throw new Error("Received thinking_end for non-thinking content")}case"toolcall_start":return partial.content[proxyEvent.contentIndex]={type:"toolCall",id:proxyEvent.id,name:proxyEvent.toolName,arguments:{},partialJson:""},{type:"toolcall_start",contentIndex:proxyEvent.contentIndex,partial};case"toolcall_delta":{let content=partial.content[proxyEvent.contentIndex];if(content?.type==="toolCall")return content.partialJson+=proxyEvent.delta,content.arguments=parseStreamingJson(content.partialJson)||{},partial.content[proxyEvent.contentIndex]={...content},{type:"toolcall_delta",contentIndex:proxyEvent.contentIndex,delta:proxyEvent.delta,partial};throw new Error("Received toolcall_delta for non-toolCall content")}case"toolcall_end":{let content=partial.content[proxyEvent.contentIndex];if(content?.type==="toolCall"){let toolCall=proxyEvent.toolCall??content;return delete toolCall.partialJson,partial.content[proxyEvent.contentIndex]=toolCall,{type:"toolcall_end",contentIndex:proxyEvent.contentIndex,toolCall,partial}}return}case"done":return partial.stopReason=proxyEvent.reason,partial.usage=proxyEvent.usage,proxyEvent.providerThinkingLevel!==void 0&&(partial.providerThinkingLevel=proxyEvent.providerThinkingLevel),{type:"done",reason:proxyEvent.reason,message:partial};case"error":return partial.stopReason=proxyEvent.reason,partial.errorMessage=proxyEvent.errorMessage,partial.usage=proxyEvent.usage,proxyEvent.providerThinkingLevel!==void 0&&(partial.providerThinkingLevel=proxyEvent.providerThinkingLevel),{type:"error",reason:proxyEvent.reason,error:partial};default:{let _exhaustiveCheck=proxyEvent;console.warn(`Unhandled proxy event type: ${proxyEvent.type}`);return}}}import{spawnSync as spawnSync2}from"child_process";var GIT_BASH_PATH_ENV="SENPI_GIT_BASH_PATH";function isLegacyWslBashPath(path){let normalized=path.replace(/\//g,"\\").toLowerCase();return/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)}function resolveShellKind(shellPath){let base=shellPath.replace(/\\/g,"/").split("/").pop()?.toLowerCase().replace(/\.exe$/,"");return base==="cmd"?"cmd":base==="powershell"||base==="pwsh"?"powershell":base==="sh"?"sh":"bash"}function getBashShellConfig(shell){return isLegacyWslBashPath(shell)?{shell,args:["-s"],commandTransport:"stdin",kind:"bash"}:{shell,args:["-c"],kind:"bash"}}function getShellConfigForPath(shellPath){let kind=resolveShellKind(shellPath);switch(kind){case"cmd":return{shell:shellPath,args:["/c"],kind};case"powershell":return{shell:shellPath,args:["-NoProfile","-Command"],kind};case"sh":return{shell:shellPath,args:["-c"],kind};default:return getBashShellConfig(shellPath)}}function findExecutableOnPath(executable){if(process.platform==="win32"){try{let result=spawnSync2("where",[executable],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch&&existsSync(firstMatch))return firstMatch}}catch{}return null}try{let result=spawnSync2("which",[executable],{encoding:"utf-8",timeout:5e3});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch)return firstMatch}}catch{}return null}function getShellConfig(customShellPath){if(customShellPath){if(existsSync(customShellPath))return getShellConfigForPath(customShellPath);throw new Error(`Custom shell path not found: ${customShellPath}`)}let gitBashOverride=process.env[GIT_BASH_PATH_ENV];if(gitBashOverride){if(existsSync(gitBashOverride))return getShellConfigForPath(gitBashOverride);throw new Error(`${GIT_BASH_PATH_ENV} points to a missing shell: ${gitBashOverride}`)}if(process.platform==="win32"){let paths=[],programFiles=process.env.ProgramFiles;programFiles&&paths.push(`${programFiles}\\Git\\bin\\bash.exe`);let programFilesX86=process.env["ProgramFiles(x86)"];programFilesX86&&paths.push(`${programFilesX86}\\Git\\bin\\bash.exe`);for(let path of paths)if(existsSync(path))return getBashShellConfig(path);let bashOnPath2=findExecutableOnPath("bash.exe");if(bashOnPath2)return getBashShellConfig(bashOnPath2);throw new Error(`No bash shell found. Options:
282
+ 1. Install Git for Windows: https://git-scm.com/download/win
283
+ 2. Add your bash to PATH (Cygwin, MSYS2, etc.)
284
+ 3. Set shellPath in settings.json
285
+
286
+ Searched Git Bash in:
287
+ ${paths.map(p=>` ${p}`).join(`
288
+ `)}`)}if(existsSync("/bin/bash"))return getBashShellConfig("/bin/bash");let bashOnPath=findExecutableOnPath("bash");return bashOnPath?getBashShellConfig(bashOnPath):{shell:"sh",args:["-c"]}}var POWERSHELL_ARGS=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];function getPowerShellConfig(){if(process.platform!=="win32")throw new Error("The powershell tool is only available on Windows.");let shell=findExecutableOnPath("pwsh.exe")??findExecutableOnPath("powershell.exe");if(!shell)throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");return{shell,args:[...POWERSHELL_ARGS]}}function getShellEnv(){let binDir=getBinDir(),pathKey=Object.keys(process.env).find(key=>key.toLowerCase()==="path")??"PATH",currentPath=process.env[pathKey]??"",updatedPath=currentPath.split(delimiter2).filter(Boolean).includes(binDir)?currentPath:[binDir,currentPath].filter(Boolean).join(delimiter2);return withBundledBunCommands({...process.env,[pathKey]:updatedPath})}function sanitizeBinaryOutput(str){return hasUnsafeDisplayCharacter(str)?str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,""):str}function hasUnsafeDisplayCharacter(str){for(let i=0;i<str.length;i++){let code=str.charCodeAt(i),isAllowedControl=code===9||code===10||code===13;if(code<=31&&!isAllowedControl||code>=65529&&code<=65531)return!0}return!1}var trackedDetachedChildren=new Map;function trackDetachedChildPid(pid){trackedDetachedChildren.set(pid,{pid,pgid:pid,leaderExited:!1})}function untrackDetachedChildPid(pid){trackedDetachedChildren.delete(pid)}function noteDetachedChildExited(pid){let entry=trackedDetachedChildren.get(pid);if(entry!==void 0){if(process.platform==="win32"||!processGroupIsAlive(entry.pgid)){trackedDetachedChildren.delete(pid);return}entry.leaderExited=!0}}function pruneTrackedDetachedChildren(){if(process.platform!=="win32")for(let[pid,entry]of trackedDetachedChildren)trackedDetachedChildIsGone(entry)&&trackedDetachedChildren.delete(pid)}function signalTargetExists(target){try{return process.kill(target,0),!0}catch(error){return error.code!=="ESRCH"}}function processGroupIsAlive(pgid){return signalTargetExists(-pgid)}function trackedDetachedChildIsGone(entry){return processGroupIsAlive(entry.pgid)?!1:entry.leaderExited||!signalTargetExists(entry.pid)}function killTrackedDetachedChildren(){if(pruneTrackedDetachedChildren(),trackedDetachedChildren.size===0)return;let rows=process.platform==="win32"?listWindowsProcesses():void 0;for(let entry of trackedDetachedChildren.values())process.platform==="win32"?killWindowsProcessTree(entry.pid,void 0,()=>rows):killTrackedDetachedGroup(entry);trackedDetachedChildren.clear()}function killTrackedDetachedGroup(entry){try{process.kill(-entry.pgid,"SIGKILL");return}catch{}if(!entry.leaderExited)try{process.kill(entry.pid,"SIGKILL")}catch{}}function windowsTaskkillCandidates(env=process.env){let systemDrive=env.SystemDrive?`${env.SystemDrive}\\`:void 0,roots=[env.SystemRoot,env.SYSTEMROOT,env.windir,systemDrive&&join2(systemDrive,"Windows")],candidates=[];for(let root of roots)if(root)for(let systemDir of["System32","Sysnative"]){let absolute=join2(root,systemDir,"taskkill.exe");!candidates.includes(absolute)&&existsSync(absolute)&&candidates.push(absolute)}return candidates.push("taskkill.exe"),candidates}function killProcessDirectly(pid){try{process.kill(pid)}catch{}}var TASKKILL_TIMEOUT_MS=5e3;function listWindowsProcesses(){return listWindowsProcessRowsSync(TASKKILL_TIMEOUT_MS)}function taskkillHandledTree(taskkillPath,killArgs){if(killArgs.length===0)return!0;try{let result=spawnSync2(taskkillPath,[...killArgs],{stdio:"ignore",windowsHide:!0,timeout:TASKKILL_TIMEOUT_MS});return result.error===void 0&&result.status!==null}catch{return!1}}function killWindowsProcessTree(pid,taskkillPaths=windowsTaskkillCandidates(),listProcesses=listWindowsProcesses){let killArgs=windowsTreeKillArgs(pid,listProcesses());for(let taskkillPath of taskkillPaths)if(taskkillHandledTree(taskkillPath,killArgs))return;killProcessDirectly(pid)}function killProcessTree(pid){if(process.platform==="win32")killWindowsProcessTree(pid);else try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}export{ProviderRetryWatchdogAbortError,EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC,setDefaultStreamFn,resolveToolNameAlias,buildProviderContext,prepareAgentToolCall,runToolCall,Agent,selectedReadFolder,prepareReadFolder,createDefaultReadSummary,dist_exports,withBundledBunCommands,getShellConfig,getPowerShellConfig,getShellEnv,sanitizeBinaryOutput,trackDetachedChildPid,untrackDetachedChildPid,noteDetachedChildExited,pruneTrackedDetachedChildren,killTrackedDetachedChildren,killWindowsProcessTree,killProcessTree};