@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
272 lines • 594 kB
JavaScript
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
import{AssistantMessageFrameEncoder,EMPTY_RESPONSE_ERROR,EMPTY_TOOL_USE_ERROR,TOOL_RESULT_PLACEHOLDER,dropFailedAssistantTurns,getToolCallFormat,hasKimiTextToolCallRecovery,hasVisibleAssistantContent,hasVisibleText,isClassifierRefusal,isContextOverflow,isCursorExecResolved,isRecoverableLength,reduceAssistantMessageFrames,require_dist,shouldRecoverTextToolCalls,validateToolArguments}from"./chunk-OBXBNBXE.js";import{supportsAllowedToolChoice}from"./chunk-COH5F7QV.js";import{uuidv7}from"./chunk-Y7QPP7BG.js";import{resolveToolNameMatch}from"./chunk-QTS2XGPQ.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{DEFAULT_MAX_AGENT_RETRY_DELAY_MS,FORWARDED_EMPTY_RESPONSE_ERROR,FORWARDED_EMPTY_TOOL_USE_ERROR,OAUTH_REFRESH_UNAVAILABLE_DIAGNOSTIC,contentText,createInitialSystemMessage,getCurrentTools,getToolStateChanges,isOAuthRefreshUnavailableError,isRetryableAssistantError,normalizeContext,retryAssistantCall,retryDelayMs}from"./chunk-AFDUWYAX.js";import{EventStream,assistantEvents,assistantRecords,carryAssistantCapture,createAssistantMessageEventStream,getAssistantCapture,isAssistantProgress,pushAssistantProgress,sanitizeProviderErrorMessage,subscribeAssistantCapture}from"./chunk-NDNQ23SK.js";import{readProviderDiagnostic,sanitizeProviderDiagnostic}from"./chunk-JGKH3D6W.js";import{composeFoldResult}from"./chunk-BMX2U22F.js";import{typebox_exports}from"./chunk-MIKPY3E7.js";import{__commonJS,__export,__toESM}from"./chunk-IKOFCODM.js";var require_ignore=__commonJS({"node_modules/ignore/index.js"(exports,module){function makeArray(subject){return Array.isArray(subject)?subject:[subject]}var UNDEFINED=void 0,EMPTY2="",SPACE=" ",ESCAPE="\\",REGEX_LITERAL_SPECIAL=/[.*+?()[\]{}^$|\\/]/,REGEX_TEST_BLANK_LINE=/^\uFEFF? *$/,REGEX_INVALID_TRAILING_BACKSLASH=/(?:[^\\]|^)\\$/,REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION=/^\\!/,REGEX_REPLACE_LEADING_EXCAPED_HASH=/^\\#/,REGEX_SPLITALL_CRLF=/\r?\n/g,DOUBLE_SLASH="//",SLASH_CODE=47,DOT_CODE=46,SLASH="/",TMP_KEY_IGNORE="node-ignore";typeof Symbol<"u"&&(TMP_KEY_IGNORE=Symbol.for("node-ignore"));var KEY_IGNORE=TMP_KEY_IGNORE,define=(object3,key,value2)=>(Object.defineProperty(object3,key,{value:value2}),value2),RETURN_FALSE=()=>!1,cleanRangeBackSlash=slashes=>{let{length}=slashes;return slashes.slice(0,length-length%2)},POSIX_CLASSES={alnum:"0-9A-Za-z",alpha:"A-Za-z",blank:" \\t",cntrl:"\\x00-\\x1f\\x7f",digit:"0-9",graph:"!-.0-~",lower:"a-z",print:" -.0-~",punct:"!-.:-@\\[-`{-~",space:" \\t\\n\\r",upper:"A-Z",xdigit:"0-9A-Fa-f"},CLASS_MEMBERS_TO_ESCAPE="\\]^-[",escapeMember=char=>CLASS_MEMBERS_TO_ESCAPE.indexOf(char)<0?char:ESCAPE+char,NON_SLASH="(?!\\/)",classSource=(negated,body)=>{if(negated)return`[^\\/${body}]`;let source=`[${body}]`;return new RegExp(source).test("/")?NON_SLASH+source:source},scanBracket=(pattern,start)=>{let{length}=pattern,index=start+1,negated=EMPTY2,lead=pattern[index];(lead==="!"||lead==="^")&&(negated="^",index++);let body=EMPTY2,prev=EMPTY2;for(;;){let char=pattern[index];if(char===UNDEFINED)return null;if(char===ESCAPE){let escaped=pattern[index+1];if(escaped===UNDEFINED)return null;body+=escapeMember(escaped),prev=escaped,index++}else if(char==="-"&&prev&&index+1<length&&pattern[index+1]!=="]"){index++;let to=pattern[index];to===ESCAPE&&(to=pattern[index+=1]),prev<=to&&(body+=`-${escapeMember(to)}`),prev=EMPTY2}else if(char==="["&&pattern[index+1]===":"){let nameStart=index+2,end=nameStart;for(;end<length&&pattern[end]!=="]";)end++;if(end===length)return null;if(end>nameStart&&pattern[end-1]===":"){let expanded=POSIX_CLASSES[pattern.slice(nameStart,end-1)];if(expanded===UNDEFINED)return null;body+=expanded,prev=EMPTY2,index=end}else body+=escapeMember("["),prev="[",index=nameStart-2}else body+=escapeMember(char),prev=char;if(index++,pattern[index]==="]")return{end:index,source:classSource(negated,body)}}},NEVER_MATCH="[]",PLACEHOLDER="\0",REGEX_RESTORE_PLACEHOLDER=new RegExp(`${PLACEHOLDER}(\\d+)${PLACEHOLDER}`,"g"),TRAILING_WILDCARD="\uE000",extractBrackets=pattern=>{let sources=[],hold=source=>`${PLACEHOLDER}${sources.push(source)-1}${PLACEHOLDER}`,{length}=pattern,out=EMPTY2,index=0;for(;index<length;){let char=pattern[index];if(char===ESCAPE){let escaped=pattern[index+1];escaped==="*"||escaped==="["||escaped===SPACE||escaped===ESCAPE?out+=pattern.slice(index,index+2):out+=hold(REGEX_LITERAL_SPECIAL.test(escaped)?ESCAPE+escaped:escaped),index+=2}else if(char===PLACEHOLDER)out+=hold(`[${PLACEHOLDER}]`),index++;else if(char==="["){let scanned=scanBracket(pattern,index);scanned===null?(out+=hold(NEVER_MATCH),index=length):(out+=hold(scanned.source),index=scanned.end+1)}else out+=char,index++}return{source:out,sources}},DIRECT=null,REGEX_INNER_SLASH=/\/(?!$)/,REPLACERS=[[/^\uFEFF/,()=>EMPTY2,"\uFEFF"],[/[\r\n]+$/,()=>EMPTY2],[/((?:\\\\)*?)(\\? +)$/,(_,m1,m2)=>m1+(m2.indexOf("\\")===0?SPACE:EMPTY2)],[/(\\+?) /g,(_,m1)=>{let{length}=m1;return m1.slice(0,length-length%2)+SPACE}],[/[\\$.|*+(){^]/g,match=>`\\${match}`],[/(?!\\)\?/g,()=>"[^/]","?"],[/^\//,()=>"^",SLASH],[/\//g,()=>"\\/",SLASH],[/^\^*(?:\\\*\\\*\\\/)+/,()=>"^(?:.*\\/)?","*"],[DIRECT,(source,pattern)=>!source||source[0]==="^"?source:(REGEX_INNER_SLASH.test(pattern)?"^":"(?:^|\\/)")+source],[/\\\/\\\*\\\*(?=\\\/|$)/g,(_,index,str)=>index+6<str.length?str.slice(index+6)==="\\/"?"(?:\\/[^\\/]+)+":"(?:\\/[^\\/]+)*":"\\/.+","*"],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(_,p1,p2)=>{let unescaped=p2.replace(/\\\*/g,"[^\\/]*");return p1+unescaped},"*"],[/(^|[^\\])((?:\\\\)*)\\\*$/,(match,p1,p2)=>p2.length/2%2===0?p1+p2+TRAILING_WILDCARD:match,"*"],[/\\\\\\(?=[$.|*+(){^])/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\\/g,()=>ESCAPE,ESCAPE+ESCAPE],[/\\\[([^\]/]*?)(\\*)($|\])/g,(match,range,endEscape,close)=>`\\[${range}${cleanRangeBackSlash(endEscape)}${close}`,"["],[DIRECT,source=>{let last=source[source.length-1];return!last||last===TRAILING_WILDCARD?source:last===SLASH?`${source}$`:`${source}(?=$|\\/$)`}]],REGEX_REPLACE_TRAILING_WILDCARD=/(^|\\\/)?\uE000$/,MODE_IGNORE="regex",MODE_CHECK_IGNORE="checkRegex",UNDERSCORE="_",TRAILING_WILD_CARD_REPLACERS={[MODE_IGNORE](_,p1){return`${p1?`${p1}[^/]+`:"[^/]*"}(?=$|\\/$)`},[MODE_CHECK_IGNORE](_,p1){return`${p1?`${p1}[^/]*`:"[^/]*"}(?=$|\\/$)`}},WILDCARD="[^\\/]*",pinWildcards=source=>{if(source.indexOf(WILDCARD)<0)return source;let tokens=[],{length}=source,index=0;for(;index<length;){let char=source[index];if(source.startsWith(WILDCARD,index))tokens.push({wildcard:!0}),index+=WILDCARD.length;else if(char==="["){let end=index+1;for(source[end]==="^"&&end++,source[end]==="]"&&end++;end<length&&source[end]!=="]";)end+=source[end]===ESCAPE?2:1;end++,tokens.push({single:source.slice(index,end)}),index=end}else if(char===ESCAPE)tokens.push({single:source.slice(index,index+2)}),index+=2;else if(char==="("){let depth=0,end=index;do source[end]===ESCAPE?end++:source[end]==="("?depth++:source[end]===")"&&depth--,end++;while(end<length&&depth>0);"*+?".indexOf(source[end])>=0&&end++,tokens.push({boundary:source.slice(index,end)}),index=end}else char==="^"||char==="$"?(tokens.push({boundary:char}),index++):(tokens.push({single:char}),index++)}let out=EMPTY2,run=[],flush=()=>{let lastWildcard;run.forEach((token,at)=>{token.wildcard&&(lastWildcard=at)}),run.forEach((token,at)=>{if(!token.wildcard){out+=token.single;return}out+=at===lastWildcard?WILDCARD:`(?:(?!${run[at+1].single})[^\\/])*`}),run=[]};return tokens.forEach(token=>{if(token.boundary===void 0){run.push(token);return}flush(),out+=token.boundary}),flush(),out},makeRegexPrefix=pattern=>{let{source,sources}=extractBrackets(pattern),replaced=REPLACERS.reduce((prev,[matcher,replacer,required])=>matcher===DIRECT?replacer(prev,pattern):required!==UNDEFINED&&prev.indexOf(required)<0?prev:matcher.test(prev)?prev.replace(matcher,replacer.bind(pattern)):prev,source);return sources.length?replaced.replace(REGEX_RESTORE_PLACEHOLDER,(match,index)=>sources[index]):replaced},matchesBasename=body=>{let index=body.indexOf(SLASH);return index<0||index===body.length-1},basenameOf=path=>{let end=path.length-1,index=path.lastIndexOf(SLASH,path[end]===SLASH?end-1:end);return index<0?path:path.slice(index+1)},parentOf=path=>{if(path.charCodeAt(0)===SLASH_CODE||path.indexOf(DOUBLE_SLASH)>=0){let slices=path.split(SLASH).filter(Boolean);return slices.pop(),slices.length?slices.join(SLASH)+SLASH:EMPTY2}let end=path.length-1,cut=path.lastIndexOf(SLASH,path.charCodeAt(end)===SLASH_CODE?end-1:end);return cut<0?EMPTY2:path.slice(0,cut+1)},isString2=subject=>typeof subject=="string",checkPattern=pattern=>pattern&&isString2(pattern)&&!REGEX_TEST_BLANK_LINE.test(pattern)&&!REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)&&pattern.indexOf("#")!==0,splitPattern=pattern=>pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean),IgnoreRule=class{constructor(pattern,mark,body,ignoreCase,negative,prefix){this.pattern=pattern,this.mark=mark,this.negative=negative,define(this,"body",body),define(this,"ignoreCase",ignoreCase),define(this,"regexPrefix",prefix)}get _basenameOnly(){return define(this,"_basenameOnly",matchesBasename(this.body))}get regex(){let key=UNDERSCORE+MODE_IGNORE;return this[key]?this[key]:this._make(MODE_IGNORE,key)}get checkRegex(){let key=UNDERSCORE+MODE_CHECK_IGNORE;return this[key]?this[key]:this._make(MODE_CHECK_IGNORE,key)}_make(mode,key){let str=pinWildcards(this.regexPrefix.replace(REGEX_REPLACE_TRAILING_WILDCARD,TRAILING_WILD_CARD_REPLACERS[mode])),regex=this.ignoreCase?new RegExp(str,"i"):new RegExp(str);return define(this,key,regex)}},createRule=({pattern,mark},ignoreCase)=>{let negative=!1,body=pattern;body.indexOf("!")===0&&(negative=!0,body=body.substr(1)),body=body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION,"!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH,"#");let regexPrefix=makeRegexPrefix(body);return new IgnoreRule(pattern,mark,body,ignoreCase,negative,regexPrefix)},RuleManager=class{constructor(ignoreCase){this._ignoreCase=ignoreCase,this._rules=[],this._basenameCount=0}_add(pattern){if(pattern&&pattern[KEY_IGNORE]){this._rules=this._rules.concat(pattern._rules._rules),this._basenameCount+=pattern._rules._basenameCount,this._added=!0;return}if(isString2(pattern)&&(pattern={pattern}),checkPattern(pattern.pattern)){let rule=createRule(pattern,this._ignoreCase);this._added=!0,this._rules.push(rule),matchesBasename(rule.body)&&this._basenameCount++}}add(pattern){return this._added=!1,makeArray(isString2(pattern)?splitPattern(pattern):pattern).forEach(this._add,this),this._added}test(path,checkUnignored,mode){let ignored=!1,unignored=!1,matchedRule,rules=this._rules,{length}=rules,shortcut=this._basenameCount*2>=length,basename=shortcut?basenameOf(path):path;for(let index=0;index<length;index++){let rule=rules[index],{negative}=rule;!(unignored===negative&&ignored!==unignored||negative&&!ignored&&!unignored&&!checkUnignored)&&rule[mode].test(shortcut&&rule._basenameOnly?basename:path)&&(ignored=!negative,unignored=negative,matchedRule=negative?UNDEFINED:rule)}let ret={ignored,unignored};return matchedRule&&(ret.rule=matchedRule),ret}},throwError=(message2,Ctor)=>{throw new Ctor(message2)},checkPath=(path,originalPath,doThrow)=>isString2(path)?path?checkPath.isNotRelative(path)?doThrow(`path should be a \`path.relative()\`d string, but got "${originalPath}"`,RangeError):!0:doThrow("path must not be empty",TypeError):doThrow(`path must be a string, but got \`${originalPath}\``,TypeError),isNotRelative=path=>{let first=path.charCodeAt(0);if(first===SLASH_CODE)return!0;if(first!==DOT_CODE)return!1;if(path.length===1)return!0;let second=path.charCodeAt(1);return second===SLASH_CODE?!0:second!==DOT_CODE?!1:path.length===2||path.charCodeAt(2)===SLASH_CODE};checkPath.isNotRelative=isNotRelative;checkPath.convert=p=>p;var Ignore=class{constructor({ignorecase=!0,ignoreCase=ignorecase,allowRelativePaths=!1}={}){define(this,KEY_IGNORE,!0),this._rules=new RuleManager(ignoreCase),this._strictPathCheck=!allowRelativePaths,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(pattern){return this._rules.add(pattern)&&this._initCache(),this}addPattern(pattern){return this.add(pattern)}_test(originalPath,cache,checkUnignored){let path=originalPath&&checkPath.convert(originalPath);return checkPath(path,originalPath,this._strictPathCheck?throwError:RETURN_FALSE),this._t(path,cache,checkUnignored)}checkIgnore(path){if(path.charCodeAt(path.length-1)!==SLASH_CODE)return this.test(path);let parentPath=parentOf(path);if(parentPath){let parent=this._t(parentPath,this._testCache,!0);if(parent.ignored)return parent}return this._rules.test(path,!1,MODE_CHECK_IGNORE)}_t(path,cache,checkUnignored){if(path in cache)return cache[path];let parentPath=parentOf(path),parent=parentPath?this._t(parentPath,cache,checkUnignored):UNDEFINED;return cache[path]=parent&&parent.ignored?parent:this._rules.test(path,checkUnignored,MODE_IGNORE)}ignores(path){return this._test(path,this._ignoreCache,!1).ignored}createFilter(){return path=>!this.ignores(path)}filter(paths){return makeArray(paths).filter(this.createFilter())}test(path){return this._test(path,this._testCache,!0)}},factory=options=>new Ignore(options),isPathValid=path=>checkPath(path&&checkPath.convert(path),path,RETURN_FALSE),setupWindows=()=>{let makePosix=str=>/^\\\\\?\\/.test(str)||/["<>|\u0000-\u001F]+/u.test(str)?str:str.replace(/\\/g,"/");checkPath.convert=makePosix;let REGEX_TEST_WINDOWS_PATH_ABSOLUTE=/^[a-z]:\//i;checkPath.isNotRelative=path=>REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path)||isNotRelative(path)};typeof process<"u"&&process.platform==="win32"&&setupWindows();module.exports=factory;factory.default=factory;module.exports.isPathValid=isPathValid;define(module.exports,Symbol.for("setupWindows"),setupWindows)}});var LOCAL_DEVICE_FILES=Symbol.for("senpi.device-files.local");function isLocalDeviceFiles(files){return files[LOCAL_DEVICE_FILES]===!0}var FILE_CHANNEL="file/1",FILE_CHANNEL_MAX_BYTES=8*1024*1024,DEVICE_FILE_OPS=["read","write","list","stat","rename","remove","mkdir","run"],RUN_CHANNEL="run/1",DeviceFileError=class extends Error{constructor(code,message2,detail={}){super(`${code}: ${message2}`),this.name="DeviceFileError",this.code=code,this.reason=detail.reason,this.uncertain=detail.uncertain??!1}},CODES=["not_found","not_a_file","exists","too_large","io","aborted","refused_by_grant","refused_by_policy","hand_unreachable","unsupported","interrupted","protocol"];function isDeviceFileErrorCode(value2){return typeof value2=="string"&&CODES.includes(value2)}var isRecord=value2=>typeof value2=="object"&&value2!==null;function decodeDeviceFileArgs(op,args){if(!isRecord(args)||typeof args.path!="string"||args.path.length===0)return;let path=args.path;switch(op){case"read":case"list":case"stat":case"remove":case"mkdir":return{op,path};case"write":return typeof args.data=="string"?{op,path,data:args.data,exclusive:args.exclusive===!0}:void 0;case"rename":return typeof args.to=="string"&&args.to.length>0?{op,path,to:args.to}:void 0;case"run":return decodeRunArgs(path,args);default:return}}function decodeRunArgs(path,args){let{exe,argv,env,stdin,timeoutMs,activityLock}=args;if(typeof exe!="string"||!Array.isArray(argv)||!argv.every(arg=>typeof arg=="string"))return;let environment=env??{};if(!(!isRecord(environment)||!Object.values(environment).every(value2=>typeof value2=="string"))&&!(stdin!==void 0&&typeof stdin!="string")&&!(timeoutMs!==void 0&&(typeof timeoutMs!="number"||!Number.isSafeInteger(timeoutMs)||timeoutMs<=0))&&!(activityLock!==void 0&&typeof activityLock!="boolean"))return{op:"run",path,exe,argv,env:environment,...stdin===void 0?{}:{stdin},...timeoutMs===void 0?{}:{timeoutMs},activityLock:activityLock===!0}}function encodeBase64(bytes){let binary="";for(let start=0;start<bytes.length;start+=32768)binary+=String.fromCharCode(...bytes.subarray(start,start+32768));return btoa(binary)}function decodeBase64(text){let binary=atob(text),bytes=new Uint8Array(binary.length);for(let index=0;index<binary.length;index++)bytes[index]=binary.charCodeAt(index);return bytes}function base64Length(text){let padding=text.endsWith("==")?2:text.endsWith("=")?1:0;return Math.floor(text.length*3/4)-padding}function fileOutcomeOf(details){if(!isRecord(details)||!isRecord(details.file))return;let file=details.file;if(file.ok===!0&&"value"in file)return{ok:!0,value:file.value};if(file.ok===!1&&isDeviceFileErrorCode(file.code)&&typeof file.message=="string")return{ok:!1,code:file.code,message:file.message}}var PlaneRefusedError=class extends Error{constructor(reason){super(`The brain refused this request: ${reason}`),this.name="PlaneRefusedError",this.reason=reason}},KINDS=["plane.request","plane.abort","plane.reply","plane.refused"],encoder=new TextEncoder,decoder=new TextDecoder;function encodePlaneMessage(message2){return encoder.encode(JSON.stringify(message2))}var isRecord2=value2=>typeof value2=="object"&&value2!==null,isId=value2=>typeof value2=="string"&&value2.length>0;function decodePlaneMessage(payload){let value2;try{value2=JSON.parse(decoder.decode(payload))}catch{return}if(!isRecord2(value2)||!KINDS.includes(value2.kind)||!isId(value2.parent)||!isId(value2.childRequestId))return;let address={parent:value2.parent,childRequestId:value2.childRequestId};switch(value2.kind){case"plane.request":return isId(value2.plane)&&"body"in value2?{kind:"plane.request",...address,plane:value2.plane,body:value2.body}:void 0;case"plane.abort":return{kind:"plane.abort",...address};case"plane.reply":return"body"in value2?{kind:"plane.reply",...address,body:value2.body}:void 0;default:return typeof value2.reason=="string"?{kind:"plane.refused",...address,reason:value2.reason}:void 0}}function createPlaneServer(options){let served=new Map,send=(lane,message2)=>{options.transport.send(lane,encodePlaneMessage(message2)).catch(()=>{})},serve=(lane,request)=>{let{parent,childRequestId}=request,refuse2=reason=>send(lane,{kind:"plane.refused",parent,childRequestId,reason}),parentLane=options.liveLane(parent,request.plane);if(parentLane===void 0)return refuse2("parent_terminal");if(parentLane!==lane)return refuse2("scope_lane_mismatch");let children=served.get(parent)??new Map;served.set(parent,children);let known=children.get(childRequestId);if(known!==void 0){known.answer!==void 0&&send(lane,known.answer);return}let handler=Object.hasOwn(options.planes,request.plane)?options.planes[request.plane]:void 0;if(handler===void 0)return refuse2("plane_unavailable");let entry2={controller:new AbortController};children.set(childRequestId,entry2),handler(request.body,entry2.controller.signal).then(body=>({kind:"plane.reply",parent,childRequestId,body}),error=>({kind:"plane.refused",parent,childRequestId,reason:`plane_failed: ${error instanceof Error?error.message:String(error)}`})).then(answer2=>{served.get(parent)?.get(childRequestId)===entry2&&(entry2.answer=answer2,send(lane,answer2))})};return{receive(lane,message2){message2.kind==="plane.request"?serve(lane,message2):message2.kind==="plane.abort"&&options.liveLane(message2.parent)===lane&&served.get(message2.parent)?.get(message2.childRequestId)?.controller.abort()},parentEnded(executionId){let children=served.get(executionId);served.delete(executionId);for(let entry2 of children?.values()??[])entry2.controller.abort()}}}function createPlaneClient(options){let mintId=options.mintId??(()=>crypto.randomUUID()),waiting=new Map,live=new Set;return{requestFor(parent,lane,parentSignal){return live.add(parent),(plane,body,signal)=>new Promise((resolve,reject)=>{if(!live.has(parent)||parentSignal.aborted||signal?.aborted)return reject(new PlaneRefusedError("parent_terminal"));let childRequestId=mintId(),children=waiting.get(parent)??new Map;waiting.set(parent,children);let abort=()=>{children.delete(childRequestId)&&(options.transport.send(lane,encodePlaneMessage({kind:"plane.abort",parent,childRequestId})).catch(()=>{}),reject(new Error("Operation aborted")))},release=()=>{parentSignal.removeEventListener("abort",abort),signal?.removeEventListener("abort",abort)};children.set(childRequestId,{resolve:value2=>{release(),resolve(value2)},reject:error=>{release(),reject(error)}}),parentSignal.addEventListener("abort",abort,{once:!0}),signal?.addEventListener("abort",abort,{once:!0});let request={kind:"plane.request",parent,childRequestId,plane,body};options.transport.send(lane,encodePlaneMessage(request)).catch(error=>{children.delete(childRequestId)&&(release(),reject(new PlaneRefusedError(`brain_unreachable: ${error instanceof Error?error.message:String(error)}`)))})})},receive(message2){if(message2.kind!=="plane.reply"&&message2.kind!=="plane.refused")return;let children=waiting.get(message2.parent),waiter=children?.get(message2.childRequestId);waiter!==void 0&&(children?.delete(message2.childRequestId),message2.kind==="plane.reply"?waiter.resolve(message2.body):waiter.reject(new PlaneRefusedError(message2.reason)))},parentEnded(parent){live.delete(parent);let children=waiting.get(parent);waiting.delete(parent);for(let waiter of children?.values()??[])waiter.reject(new PlaneRefusedError("parent_terminal"))}}}function fileCall(message2){return{kind:"invoke",executionId:message2.executionId,batchId:message2.executionId,index:0,scope:message2.scope,toolCallId:message2.executionId,name:`file.${message2.op}`,arguments:message2.args,...message2.epoch===void 0?{}:{epoch:message2.epoch}}}function fileResult(outcome2){return{content:[],details:{file:outcome2},isError:!outcome2.ok}}function fileRefusal(code,message2){return fileResult({ok:!1,code,message:message2})}function fileStopped(granted){return granted?fileRefusal("aborted","the operation was aborted"):fileRefusal("refused_by_grant","the grant was revoked")}var HAND_CONTROL_LANE="hand.control",RemoteProtocolError=class extends Error{constructor(message2){super(`remote_protocol: ${message2}`),this.name="RemoteProtocolError"}},TERMINAL_REASONS=["cancelled","lease_expired","hand_restarted","uncertain"],EPOCH_REFUSALS=["peer_unauthorized","epoch_fenced","epoch_step_exceeded","epoch_unsupported"],encoder2=new TextEncoder,decoder2=new TextDecoder;function encodeRemoteMessage(message2){return encoder2.encode(JSON.stringify(message2))}var isRecord3=value2=>typeof value2=="object"&&value2!==null,isString=value2=>typeof value2=="string"&&value2.length>0,isEpoch=value2=>typeof value2=="number"&&Number.isSafeInteger(value2)&&value2>=1;function decodeFloorMessage(value2){switch(value2.kind){case"floor":if(!isEpoch(value2.epoch))throw new RemoteProtocolError("malformed floor");return{kind:"floor",epoch:value2.epoch};case"floor_ack":if(!isEpoch(value2.floor))throw new RemoteProtocolError("malformed floor ack");return{kind:"floor_ack",floor:value2.floor};case"floor_refused":if(!EPOCH_REFUSALS.includes(value2.reason))throw new RemoteProtocolError("malformed floor refusal");return{kind:"floor_refused",reason:value2.reason};default:return}}function decodeRemoteMessage(payload){let value2;try{value2=JSON.parse(decoder2.decode(payload))}catch{throw new RemoteProtocolError("payload is not JSON")}if(isRecord3(value2)&&value2.kind==="hello"){let{instance,durable,ops}=value2;if(!isString(instance))throw new RemoteProtocolError("malformed hello");if(durable!==void 0&&typeof durable!="boolean")throw new RemoteProtocolError("malformed hello");if(ops!==void 0&&(!Array.isArray(ops)||!ops.every(isString)))throw new RemoteProtocolError("malformed hello");return{kind:"hello",instance,durable:durable??!0,ops:ops??[]}}let floor=isRecord3(value2)?decodeFloorMessage(value2):void 0;if(floor!==void 0)return floor;if(!isRecord3(value2)||!isString(value2.executionId))throw new RemoteProtocolError("no execution ID");if(value2.epoch!==void 0&&!isEpoch(value2.epoch))throw new RemoteProtocolError("malformed epoch");switch(value2.kind){case"invoke":{let scope=value2.scope;if(!isString(value2.batchId)||typeof value2.index!="number"||!Number.isSafeInteger(value2.index)||value2.index<0||!isRecord3(scope)||!isString(scope.id)||typeof scope.root!="string"||!isString(value2.toolCallId)||!isString(value2.name)||value2.sessionRef!==void 0&&typeof value2.sessionRef!="string"||value2.promptSurface!==void 0&&typeof value2.promptSurface!="string")throw new RemoteProtocolError("malformed invoke");return value2}case"file":{let scope=value2.scope;if(!isRecord3(scope)||!isString(scope.id)||typeof scope.root!="string"||!DEVICE_FILE_OPS.includes(value2.op)||!isRecord3(value2.args))throw new RemoteProtocolError("malformed file operation");return value2}case"abort":return value2;case"ack":return value2;case"terminal":if(!TERMINAL_REASONS.includes(value2.reason)||typeof value2.uncertain!="boolean"||typeof value2.hooksRan!="boolean")throw new RemoteProtocolError("malformed terminal outcome");return value2;case"settled":{let result=value2.result;if(!isRecord3(result)||!Array.isArray(result.content)||typeof result.isError!="boolean")throw new RemoteProtocolError("malformed result");return value2}case"refused":if(typeof value2.reason!="string")throw new RemoteProtocolError("malformed refusal");return value2;default:throw new RemoteProtocolError("unknown message kind")}}function asJson(value2){return value2===void 0?void 0:JSON.parse(JSON.stringify(value2))}function toRemoteToolResult(result){return{content:result.content??[],details:asJson(result.details),isError:result.isError===!0,...result.structuredContent===void 0?{}:{structuredContent:result.structuredContent},...result.terminate===void 0?{}:{terminate:result.terminate},...result.addedToolNames?.length?{addedToolNames:[...result.addedToolNames]}:{}}}var HAND_CAPABILITY="execute",DEFAULT_WORKSPACE="omo";function authorize(authority,scopeRoot){return authority.kind==="self"?{ok:!0,root:scopeRoot}:authority.verifier.verify(authority.peer,scopeRoot)}var SEPARATORS=/[\\/]+$/;function contains(root,child){let base=root.replace(SEPARATORS,"");if(child===base)return!0;if(!child.startsWith(base))return!1;let next=child.charAt(base.length);return next==="/"||next==="\\"}function createGrantVerifier(options){let{self,canonicalize}=options,now=options.now??Date.now,listeners=new Set,snapshot,canonical=path=>{try{return canonicalize(path)}catch{return}},workspaceOf=root=>{let best;for(let workspace of options.workspaces){let resolved=canonical(workspace.root);resolved===void 0||!contains(resolved,root)||(best===void 0||resolved.length>best.length)&&(best={label:workspace.label??"omo",length:resolved.length})}return best?.label};return{verify(peer,scopeRoot){let root=canonical(scopeRoot),workspace=root===void 0?void 0:workspaceOf(root);if(root===void 0||workspace===void 0)return{ok:!1,reason:"workspace_unknown"};if(peer===self)return{ok:!0,root};let current=snapshot;return current===void 0||now()>=current.expiresAt?{ok:!1,reason:"grant_expired"}:current.grants.some(row=>row.holder===peer&&row.target===self&&row.workspace===workspace&&row.capability===HAND_CAPABILITY)?{ok:!0,root}:{ok:!1,reason:"grant_missing"}},install(next){if(!Number.isFinite(next.rv)||!Number.isFinite(next.expiresAt))throw new Error("A grant snapshot needs a finite rv and expiresAt; the installed snapshot is kept");if(!(snapshot!==void 0&&next.rv<snapshot.rv)){snapshot=next;for(let listener of[...listeners])listener()}},onReplace(listener){return listeners.add(listener),()=>listeners.delete(listener)}}}var EPOCH_FLOOR_MAX_STEP=1,EPOCH_FLOOR_PREFIX="hand.epoch-floor:",HAND_SELF_SENDER="self";function decodeFloor(data){if(typeof data=="object"&&data!==null&&!Array.isArray(data)&&"epoch"in data&&"owner"in data){let{epoch,owner}=data;if(typeof epoch=="number"&&Number.isSafeInteger(epoch)&&epoch>=1&&typeof owner=="string")return{epoch,owner}}throw new Error("A stored epoch floor is malformed")}function createHandEpochFence(options){let{durable,ownerOf}=options,floors=new Map,ready=(async()=>{if(durable!==void 0)for(let document of await durable.store.scanDocuments(EPOCH_FLOOR_PREFIX))floors.set(document.key.slice(EPOCH_FLOOR_PREFIX.length),decodeFloor(document.data))})(),raiseNow=async(scope,epoch,sender)=>{if(ownerOf(scope)!==sender)return{kind:"refused",reason:"peer_unauthorized"};let current=floors.get(scope),floor=current?.epoch??0;if(epoch<floor)return{kind:"acked",floor};if(current!==void 0&&epoch===floor)return current.owner===sender?{kind:"acked",floor}:{kind:"refused",reason:"epoch_fenced"};if(epoch-floor>1)return{kind:"refused",reason:"epoch_step_exceeded"};let next={epoch,owner:sender};if(durable===void 0)floors.set(scope,next);else{let write={op:"put",key:`${EPOCH_FLOOR_PREFIX}${scope}`,data:{...next}};await durable.store.commit(durable.epoch,[write],()=>floors.set(scope,next))}return{kind:"acked",floor:epoch}};return{ready,async raise(scope,epoch,sender){await ready;let run=()=>raiseNow(scope,epoch,sender);return durable===void 0?run():durable.admission.admit(run)},admits(scope,epoch,sender){let floor=floors.get(scope);if(floor===void 0)return!0;let at=epoch??0;return at>floor.epoch||at===floor.epoch&&floor.owner===sender}}}async function answerFloor(fence,scope,epoch,sender){if(fence===void 0)return{kind:"floor_refused",reason:"epoch_unsupported"};let raised=await fence.raise(scope,epoch,sender);return raised.kind==="acked"?{kind:"floor_ack",floor:raised.floor}:{kind:"floor_refused",reason:raised.reason}}function createRemoteExecutor(options){let{transport,openScope,ledger,authority,fence}=options,sender=authority.kind==="peer"?authority.peer:HAND_SELF_SENDER,admits=(lane,epoch)=>fence===void 0||fence.admits(lane,epoch,sender),scopes=new Map,accepted=[],seen=new Set,running=new Map,planes=createPlaneClient({transport}),closed=!1,stopWatching=authority.kind==="peer"?authority.verifier.onReplace(()=>{for(let{controller,root}of running.values())authority.verifier.verify(authority.peer,root).ok||controller.abort()}):()=>{},reply=(lane,message2)=>{transport.send(lane,encodeRemoteMessage(message2)).catch(()=>{})},refuse2=(lane,executionId,reason)=>reply(lane,{kind:"refused",executionId,reason}),stateOf=scope=>{let known=scopes.get(scope.id);if(known!==void 0)return known.root===scope.root?known:"scope_binding_mismatch";let opened=openScope(scope);opened.catch(()=>{});let state={root:scope.root,opened,lastSequential:void 0,wave:[]};return scopes.set(scope.id,state),state},invoke=async(lane,call,file)=>{if(closed)return refuse2(lane,call.executionId,"hand_closed");if(lane!==call.scope.id)return refuse2(lane,call.executionId,"scope_lane_mismatch");let verdict=authorize(authority,call.scope.root);if(!verdict.ok)return refuse2(lane,call.executionId,verdict.reason);if(!admits(lane,call.epoch))return refuse2(lane,call.executionId,"epoch_fenced");if(ledger===void 0&&seen.has(call.executionId))return refuse2(lane,call.executionId,"duplicate_execution");seen.add(call.executionId);let state=stateOf({id:call.scope.id,root:verdict.root});if(typeof state=="string")return refuse2(lane,call.executionId,state);let scope;try{scope=await state.opened}catch(error){let reason=error instanceof Error?error.message:String(error);return refuse2(lane,call.executionId,`scope_unavailable: ${reason}`)}if(ledger!==void 0){let admission=await ledger.admit(call,()=>admits(lane,call.epoch));if(admission.kind==="reply")return reply(lane,admission.message);if(admission.kind==="in_flight")return}accepted.push(call.executionId);let controller=new AbortController;running.set(call.executionId,{controller,root:verdict.root});let sequential=file!==void 0||scope.isSequential(call.name),dependencies=sequential?[...state.lastSequential?[state.lastSequential]:[],...state.wave]:state.lastSequential?[state.lastSequential]:[],done=(async()=>{if(await Promise.allSettled(dependencies),ledger===void 0&&!admits(lane,call.epoch))return running.delete(call.executionId),refuse2(lane,call.executionId,"epoch_fenced");let result;try{if(controller.signal.aborted||!authorize(authority,call.scope.root).ok)throw new Error("The call's grant was revoked before it ran");result=file===void 0?await scope.run({toolCallId:call.toolCallId,name:call.name,arguments:call.arguments,signal:controller.signal,nested:planes.requestFor(call.executionId,lane,controller.signal),...call.promptSurface===void 0?{}:{promptSurface:call.promptSurface}}):scope.file===void 0?fileRefusal("unsupported","this hand serves no file channel"):await scope.file(file.op,call.arguments,controller.signal,planes.requestFor(call.executionId,lane,controller.signal)),file!==void 0&&controller.signal.aborted&&(result=fileStopped(authorize(authority,call.scope.root).ok))}catch(error){if(file!==void 0){let granted=authorize(authority,call.scope.root).ok;result=controller.signal.aborted||!granted?fileStopped(granted):fileRefusal("io",error instanceof Error?error.message:String(error))}else result={content:[{type:"text",text:error instanceof Error?error.message:String(error)}],details:{},isError:!0}}finally{running.delete(call.executionId),planes.parentEnded(call.executionId)}let settled=toRemoteToolResult(result);reply(lane,ledger===void 0?{kind:"settled",executionId:call.executionId,result:settled}:await ledger.settle(call,settled))})();done.catch(error=>options.onFault(error)),sequential?(state.lastSequential=done,state.wave=[]):state.wave.push(done)},ready=(async()=>{if(await fence?.ready,ledger!==void 0)for(let{lane,message:message2}of await ledger.recover())reply(lane,message2);reply(HAND_CONTROL_LANE,{kind:"hello",instance:options.instance??crypto.randomUUID(),durable:ledger!==void 0,ops:options.fileChannel===!0?[FILE_CHANNEL,RUN_CHANNEL]:[]})})();return ready.catch(error=>options.onFault(error)),transport.onFrame(async frame=>{try{await ready}catch{return}let nested=decodePlaneMessage(frame.payload);if(nested!==void 0)return planes.receive(nested);let message2;try{message2=decodeRemoteMessage(frame.payload)}catch{return}try{if(message2.kind==="invoke")await invoke(frame.lane,message2);else if(message2.kind==="floor")reply(frame.lane,await answerFloor(fence,frame.lane,message2.epoch,sender));else{if((message2.kind==="abort"||message2.kind==="ack")&&!admits(frame.lane,message2.epoch))return;message2.kind==="file"?await invoke(frame.lane,fileCall(message2),{op:message2.op}):message2.kind==="abort"?running.get(message2.executionId)?.controller.abort():message2.kind==="ack"&&await ledger?.ack(message2.executionId,()=>admits(frame.lane,message2.epoch))}}catch(error){options.onFault(error)}}),{accepted:()=>[...accepted],ready,async close(){closed=!0,stopWatching();for(let{controller}of running.values())controller.abort();let opened=await Promise.allSettled([...scopes.values()].map(state=>state.opened));scopes.clear(),await Promise.allSettled(opened.flatMap(outcome2=>outcome2.status==="fulfilled"?[outcome2.value.dispose()]:[])),transport.close()}}}var KINDS2=["hook.call","hook.hello","hook.started","hook.reply","hook.failed"],encoder3=new TextEncoder,decoder3=new TextDecoder;function encodeLoopHookMessage(message2){return encoder3.encode(JSON.stringify(message2))}var isRecord4=value2=>typeof value2=="object"&&value2!==null,isId2=value2=>typeof value2=="string"&&value2.length>0;function decodeLoopHookMessage(payload){let value2;try{value2=JSON.parse(decoder3.decode(payload))}catch{return}if(!(!isRecord4(value2)||!KINDS2.includes(value2.kind)))switch(value2.kind){case"hook.call":return isId2(value2.callId)&&isId2(value2.event)&&"payload"in value2?{kind:"hook.call",callId:value2.callId,event:value2.event,payload:value2.payload}:void 0;case"hook.hello":return isId2(value2.instance)?{kind:"hook.hello",instance:value2.instance}:void 0;case"hook.started":return isId2(value2.callId)&&isId2(value2.instance)?{kind:"hook.started",callId:value2.callId,instance:value2.instance}:void 0;case"hook.reply":return isId2(value2.callId)&&"result"in value2?{kind:"hook.reply",callId:value2.callId,result:value2.result}:void 0;default:return isId2(value2.callId)&&typeof value2.error=="string"?{kind:"hook.failed",callId:value2.callId,error:value2.error}:void 0}}function serveLoopHooks(options){let{transport,lane}=options,instance=options.instance??crypto.randomUUID(),answers=new Map,dead=!1,send=message2=>transport.send(lane,encodeLoopHookMessage(message2)),point=(at,callId)=>{if(dead)throw new Error("this hand process was stopped");try{options.onPoint?.(at,callId)}catch(error){throw dead=!0,error}},serve=async call=>{if(answers.has(call.callId)){let answer3=answers.get(call.callId);answer3!==void 0&&await send(answer3);return}point("received",call.callId),answers.set(call.callId,void 0),await send({kind:"hook.started",callId:call.callId,instance}),point("started",call.callId);let answer2;try{answer2={kind:"hook.reply",callId:call.callId,result:await options.run(call.event,call.payload)}}catch(error){answer2={kind:"hook.failed",callId:call.callId,error:error instanceof Error?error.message:String(error)}}point("ran",call.callId),answers.set(call.callId,answer2),await send(answer2),point("replied",call.callId)};return transport.onFrame(async frame=>{if(dead)return;let message2=decodeLoopHookMessage(frame.payload);if(message2?.kind==="hook.call")try{await serve(message2)}catch(error){options.onFault?.(error)}}),{ready:send({kind:"hook.hello",instance}),close(){dead=!0}}}var WAKE_RETENTION_MS=6048e5,WAKE_DROPPED_SOURCE="wake.dropped";var REFUSALS=["not_scope_hand","unknown_scope","scope_closed","not_scope_session"],isStoreObject=value2=>value2!==null&&typeof value2=="object"&&!Array.isArray(value2),isId3=value2=>typeof value2=="string"&&value2.length>0;function wakeOf(value2){if(!(!isStoreObject(value2)||!isId3(value2.eventId)||!isId3(value2.scope)||!isId3(value2.source))&&"payload"in value2)return{eventId:value2.eventId,scope:value2.scope,source:value2.source,payload:value2.payload??null}}function refusalOf(value2){if(!(!isStoreObject(value2)||typeof value2.at!="number"||typeof value2.reason!="string"))return REFUSALS.includes(value2.reason)?{reason:value2.reason,at:value2.at}:void 0}function decodeOutbox(value2){if(value2===void 0)return{record:{pending:[],drops:[],refused:{},closed:{}},malformed:[]};if(!isStoreObject(value2)||!Array.isArray(value2.pending)||!isStoreObject(value2.closed))throw new Error("corrupt wake outbox record");let malformed=[],wakes=list2=>(Array.isArray(list2)?list2:[]).flatMap(entry2=>{let wake=wakeOf(entry2);return wake===void 0&&malformed.push(entry2),wake===void 0?[]:[wake]}),refused2=Object.fromEntries(Object.entries(isStoreObject(value2.refused)?value2.refused:{}).flatMap(([eventId,entry2])=>{let refusal2=refusalOf(entry2);return refusal2===void 0?[]:[[eventId,refusal2]]})),closed=Object.fromEntries(Object.entries(value2.closed).flatMap(([scope,at])=>typeof at=="number"?[[scope,at]]:[]));return{record:{pending:wakes(value2.pending),drops:wakes(value2.drops),refused:refused2,closed},malformed}}function malformedScope(entry2){return isStoreObject(entry2)&&isId3(entry2.scope)?entry2.scope:void 0}function addDrop(drops,drop,fresh,mint){let at=drops.findLastIndex(report2=>fresh.has(report2.eventId)&&report2.scope===drop.scope&&isStoreObject(report2.payload)&&report2.payload.reason===drop.reason),previous=at===-1?void 0:drops[at];if(previous!==void 0&&isStoreObject(previous.payload)&&typeof previous.payload.count=="number"){let merged={...previous,payload:{reason:drop.reason,count:previous.payload.count+drop.count}};return drops.map((report2,index)=>index===at?merged:report2)}let eventId=mint();fresh.add(eventId);let report={eventId,scope:drop.scope,source:WAKE_DROPPED_SOURCE,payload:{reason:drop.reason,count:drop.count}};return[...drops,report]}var KIND="execution.wake-outbox",WakeOverflowError=class extends Error{constructor(wake){super(`the hand's wake outbox is full; wake ${wake.eventId} of scope ${wake.scope} was dropped (overflow)`),this.name="WakeOverflowError",this.wake=wake}},MalformedWakeError=class extends Error{constructor(entry2){super(`a malformed wake was dropped from the outbox: ${JSON.stringify(entry2)}`),this.name="MalformedWakeError",this.entry=entry2}};function createWakeOutbox(options){let{hand,store,epoch,admission,clock,limits}=options,key=`${KIND}:${JSON.stringify([hand])}`,mint=()=>`${hand}:${store.mintId()}`,fresh=new Set,decoded=async()=>decodeOutbox(await store.getDocument(key)),read=async()=>(await decoded()).record,write=async(record2,step,eventId,extra=[])=>{let data={step,eventId};await store.commit(epoch,[{op:"append",id:store.mintId(),kind:KIND,data},...extra.map(data2=>({op:"append",id:store.mintId(),kind:"execution.wake-expired",data:data2})),{op:"put",key,data:record2}],()=>{})},update=decide=>admission.admit(async()=>decide(await read())),withDrops=(record2,scope,reason,count)=>({...record2,drops:addDrop(record2.drops,{scope,reason,count},fresh,mint)}),evict=(record2,wake,reason)=>{let{[wake.eventId]:_gone,...refused2}=record2.refused,pending=record2.pending.filter(entry2=>entry2.eventId!==wake.eventId);return withDrops({...record2,pending,refused:refused2},wake.scope,reason,1)},bounded=(record2,scope)=>{if(limits===void 0)return record2;let next=record2,over=()=>next.pending.filter(wake=>wake.scope===scope).length>limits.perScope||next.pending.length>limits.total;for(;over();){let inScope=next.pending.filter(wake=>wake.scope===scope).length>limits.perScope,evictable=next.pending.find(wake=>next.refused[wake.eventId]!==void 0&&(!inScope||wake.scope===scope));if(evictable===void 0)return;next=evict(next,evictable,"refused")}return next},receipt=answer2=>update(async record2=>{if(![...record2.pending,...record2.drops].some(wake=>wake.eventId===answer2.eventId))return;if(answer2.kind==="refused"){if(answer2.reason==="unknown_scope"||record2.refused[answer2.eventId]!==void 0)return;let refusal2={reason:answer2.reason,at:clock()};await write({...record2,refused:{...record2.refused,[answer2.eventId]:refusal2}},"refused",answer2.eventId);return}let kept=wake=>wake.eventId!==answer2.eventId,{[answer2.eventId]:_settled,...refused2}=record2.refused,settled={...record2,pending:record2.pending.filter(kept),drops:record2.drops.filter(kept),refused:refused2};await write(settled,"ack",answer2.eventId)}),due=async()=>{let record2=await read();for(let report of record2.drops)fresh.delete(report.eventId);return[...record2.drops,...record2.pending].filter(wake=>record2.refused[wake.eventId]===void 0)};return{offer:wake=>update(async record2=>{let event={...wake,eventId:mint()},next=bounded({...record2,pending:[...record2.pending,event]},event.scope);if(next===void 0)throw await write(withDrops(record2,event.scope,"overflow",1),"overflow",event.eventId),new WakeOverflowError(event);return await write(next,"offer",event.eventId),event}),reoffer:async send=>{let wakes=await due();for(let wake of wakes)await receipt(await send(wake));return wakes.length},due,receipt,closeScope:scope=>update(async record2=>{record2.closed[scope]===void 0&&await write({...record2,closed:{...record2.closed,[scope]:clock()}},"close",null)}),sweep:()=>admission.admit(async()=>{let{record:record2,malformed}=await decoded(),now=clock(),lapsed=wake=>{let closedAt=record2.closed[wake.scope],refusedAt=record2.refused[wake.eventId]?.at;return closedAt!==void 0&&now>closedAt+6048e5||refusedAt!==void 0&&now>refusedAt+6048e5},expired2=record2.pending.filter(lapsed),lapsedDrops=record2.drops.filter(lapsed),held=new Set([...record2.pending,...record2.drops].map(wake=>wake.eventId)),orphans=Object.keys(record2.refused).filter(eventId=>!held.has(eventId));if(expired2.length+lapsedDrops.length+malformed.length+orphans.length===0)return[];let gone=new Set([...expired2,...lapsedDrops].map(wake=>wake.eventId).concat(orphans)),next={...record2,pending:record2.pending.filter(wake=>!gone.has(wake.eventId)),drops:record2.drops.filter(wake=>!gone.has(wake.eventId)),refused:Object.fromEntries(Object.entries(record2.refused).filter(([eventId])=>!gone.has(eventId)))};for(let wake of expired2)next=withDrops(next,wake.scope,record2.refused[wake.eventId]===void 0?"expired":"refused",1);for(let entry2 of malformed){options.onFault?.(new MalformedWakeError(entry2));let scope=malformedScope(entry2);scope!==void 0&&(next=withDrops(next,scope,"malformed",1))}return await write(next,"sweep",null,expired2.map(wake=>({reason:"wake_expired",eventId:wake.eventId,scope:wake.scope}))),expired2.map(wake=>wake.eventId)}),pending:async()=>(await read()).pending}}var HAND_WAKE_LANE="hand.wake",REFUSALS2=["not_scope_hand","unknown_scope","scope_closed","not_scope_session"],DROP_REASONS=["overflow","expired","refused","malformed","unrecorded"],encoder4=new TextEncoder,decoder4=new TextDecoder,isRecord5=value2=>typeof value2=="object"&&value2!==null&&!Array.isArray(value2),isId4=value2=>typeof value2=="string"&&value2.length>0;function encodeWakeLinkMessage(message2){return encoder4.encode(JSON.stringify(message2))}function decodeWake(value2){if(!(!isRecord5(value2)||!isId4(value2.eventId)||!isId4(value2.scope)||!isId4(value2.source)||!("payload"in value2)))return{eventId:value2.eventId,scope:value2.scope,source:value2.source,payload:value2.payload}}function decodeReceipt(value2){if(!(!isRecord5(value2)||!isId4(value2.eventId))){if(value2.kind==="ack"&&typeof value2.duplicate=="boolean")return{kind:"ack",eventId:value2.eventId,duplicate:value2.duplicate};if(value2.kind==="refused"&&REFUSALS2.includes(value2.reason))return{kind:"refused",eventId:value2.eventId,reason:value2.reason}}}function decodeDrop(value2){let{scope,reason,count,eventId}=value2;if(!isId4(scope)||!DROP_REASONS.includes(reason)||typeof count!="number"||!Number.isSafeInteger(count)||count<=0||eventId!==void 0&&!isId4(eventId))return;let drop={kind:"wake_dropped",scope,reason,count};return eventId===void 0?drop:{...drop,eventId}}function decodeWakeLinkMessage(payload){let value2;try{value2=JSON.parse(decoder4.decode(payload))}catch{return}if(isRecord5(value2))switch(value2.kind){case"wake":{let wake=decodeWake(value2.wake);return wake===void 0?void 0:{kind:"wake",wake}}case"wake_receipt":{let receipt=decodeReceipt(value2.receipt);return receipt===void 0?void 0:{kind:"wake_receipt",receipt}}case"wake_dropped":return decodeDrop(value2);case"wake_reoffer":return{kind:"wake_reoffer"};default:return}}function frameOf(wake){let{payload}=wake;if(wake.source!==WAKE_DROPPED_SOURCE||!isRecord5(payload))return{kind:"wake",wake};let{reason,count}=payload;return{kind:"wake_dropped",eventId:wake.eventId,scope:wake.scope,reason,count:Number(count)}}function createHandWakeLink(options){let{transport,outbox,onFault}=options,lane=options.lane??HAND_WAKE_LANE,closed=!1,send=message2=>closed?Promise.resolve():transport.send(lane,encodeWakeLinkMessage(message2)).catch(onFault),reoffer=async()=>{await outbox.sweep();for(let wake of await outbox.due())await send(frameOf(wake))};return transport.onFrame(async frame=>{let message2=decodeWakeLinkMessage(frame.payload);try{message2===void 0?onFault(new Error(`an undecodable frame on ${lane} was dropped`)):message2.kind==="wake_receipt"?await outbox.receipt(message2.receipt):message2.kind==="wake_reoffer"&&await reoffer()}catch(error){onFault(error)}}),{ready:reoffer().catch(onFault),async offer(wake){let event;try{event=await outbox.offer(wake)}catch(error){return error instanceof WakeOverflowError?void 0:(onFault(error),send({kind:"wake_dropped",scope:wake.scope,reason:"unrecorded",count:1}))}return send({kind:"wake",wake:event})},closeScope:scope=>outbox.closeScope(scope).catch(onFault),close(){closed=!0}}}var WakeRefusedError=class extends Error{constructor(wake,reason){super(`the brain refused wake ${wake.eventId} of scope ${wake.scope}: ${reason}`),this.name="WakeRefusedError",this.wake=wake,this.reason=reason}};function serveHandWakes(options){let{transport,inbox,hand,onFault}=options,lane=options.lane??HAND_WAKE_LANE,closed=!1,send=message2=>{closed||transport.send(lane,encodeWakeLinkMessage(message2)).catch(onFault)},commit=async wake=>{let check=wake.source===WAKE_DROPPED_SOURCE?void 0:options.check,receipt=await inbox.receive(hand,wake,check);receipt.kind==="refused"&&receipt.reason==="not_scope_session"&&onFault(new WakeRefusedError(wake,receipt.reason)),send({kind:"wake_receipt",receipt}),receipt.kind==="ack"&&!receipt.duplicate&&options.onCommitted(wake)};return transport.onFrame(async frame=>{if(closed)return;let message2=decodeWakeLinkMessage(frame.payload);try{if(message2===void 0)onFault(new Error(`an undecodable frame on ${lane} was dropped`));else if(message2.kind==="wake")await commit(message2.wake);else if(message2.kind==="wake_dropped"&&message2.eventId!==void 0){let{eventId,scope,reason,count}=message2;await commit({eventId,scope,source:WAKE_DROPPED_SOURCE,payload:{reason,count}})}else message2.kind==="wake_dropped"&&options.onDropped({scope:message2.scope,reason:message2.reason,count:message2.count})}catch(error){onFault(error)}}),{reoffer:()=>send({kind:"wake_reoffer"}),close(){closed=!0}}}var TransportClosedError=class extends Error{constructor(){super("transport closed"),this.name="TransportClosedError"}};function isReferencePacket(message2){if(typeof message2!="object"||message2===null)return!1;let{kind,lane,seq}=message2;return typeof lane!="string"||typeof seq!="number"||!Number.isSafeInteger(seq)||seq<0?!1:kind==="ack"?!0:kind==="data"&&message2.payload instanceof Uint8Array}function createReliableTransport(options){let window=options.window??32,retransmitMs=options.retransmitMs??1e3,outLanes=new Map,inLanes=new Map,order=[],ackDue=new Set,next=0,connection,writable=!1,closed=!1,handler,outLane=lane=>{let state=outLanes.get(lane);return state===void 0&&(state={nextSeq:1,acked:0,transmitted:0,outbox:new Map,waiters:[],cancelRetransmit:void 0},outLanes.set(lane,state),order.push(lane)),state},inLane=lane=>{let state=inLanes.get(lane);return state===void 0&&(state={received:0,delivered:0,busy:!1,inbox:[]},inLanes.set(lane,state)),state},admit=state=>{for(;state.nextSeq-1-state.acked<window;){let waiter=state.waiters.shift();if(waiter===void 0)return;state.outbox.set(state.nextSeq,waiter.payload),state.nextSeq+=1,waiter.resolve()}},emit=packet=>connection===void 0||!writable?!1:connection.send(packet)?!0:(writable=!1,!1),disarm=state=>{state.cancelRetransmit?.(),state.cancelRetransmit=void 0},disarmAll=()=>{for(let state of outLanes.values())disarm(state)},arm=()=>{if(connection!==void 0)for(let state of outLanes.values())state.cancelRetransmit!==void 0||state.outbox.size===0||(state.cancelRetransmit=options.clock.setTimer(()=>{state.cancelRetransmit=void 0,state.transmitted=state.acked,pump()},retransmitMs))};function pump(){if(!(connection===void 0||!writable)){for(let lane of[...ackDue]){if(!emit({kind:"ack",lane,seq:inLane(lane).delivered}))return;ackDue.delete(lane)}for(let idle=0;idle<order.length;){let lane=order[next%order.length];if(lane===void 0)return;let state=outLane(lane),seq=state.transmitted+1,payload=state.outbox.get(seq);if(payload===void 0){next+=1,idle+=1;continue}if(!emit({kind:"data",lane,seq,payload}))return;state.transmitted=seq,next+=1,idle=0}arm()}}async function deliver(state,lane){if(!(state.busy||handler===void 0)){state.busy=!0;try{for(let frame=state.inbox.shift();frame!==void 0&&!closed;frame=state.inbox.shift()){try{await handler(frame)}catch(error){options.onHandlerError(error,frame)}state.delivered+=1,ackDue.add(lane),pump()}}finally{state.busy=!1}}}let onData=packet=>{let state=inLane(packet.lane);packet.seq===state.received+1?(state.received=packet.seq,state.inbox.push({lane:packet.lane,payload:packet.payload}),deliver(state,packet.lane)):ackDue.add(packet.lane),pump()},onAck=packet=>{let state=outLanes.get(packet.lane);if(!(state===void 0||packet.seq<=state.acked||packet.seq>=state.nextSeq)){for(let seq=state.acked+1;seq<=packet.seq;seq++)state.outbox.delete(seq);state.acked=packet.seq,state.transmitted=Math.max(state.transmitted,state.acked),disarm(state),admit(state),pump()}};return{send(lane,payload){if(closed)return Promise.reject(new TransportClosedError);let state=outLane(lane);return new Promise((resolve,reject)=>{state.waiters.push({payload,resolve,reject}),admit(state),pump()})},onFrame(frameHandler){handler=frameHandler;for(let[lane,state]of inLanes)deliver(state,lane)},inFlight:lane=>{let state=outLanes.get(lane);return state===void 0?0:state.nextSeq-1-state.acked},close(){if(closed)return;closed=!0,disarmAll();for(let state of outLanes.values())for(let waiter of state.waiters.splice(0))waiter.reject(new TransportClosedError);let current=connection;connection=void 0,current?.close()},attached(newConnection){if(closed){newConnection.close();return}connection=newConnection,writable=!0;for(let state of outLanes.values())state.transmitted=state.acked;for(let[lane,state]of inLanes)state.delivered>0&&ackDue.add(lane);disarmAll(),pump()},message(message2){isReferencePacket(message2)&&(message2.kind==="data"?onData(message2):onAck(message2))},writable(){connection!==void 0&&(writable=!0,pump())},detached(){connection=void 0,writable=!1,disarmAll()}}}var dist_exports={};__export(dist_exports,{AGENT_TELEMETRY_SCHEMAS:()=>AGENT_TELEMETRY_SCHEMAS,AI_TELEMETRY_SCHEMA:()=>AI_TELEMETRY_SCHEMA,Agent:()=>Agent2,AgentHarness:()=>AgentHarness,BACKGROUND_CONTEXT:()=>BACKGROUND_CONTEXT,BRANCH_SUMMARY_PREFIX:()=>BRANCH_SUMMARY_PREFIX,BRANCH_SUMMARY_SUFFIX:()=>BRANCH_SUMMARY_SUFFIX,BatchStoreMissingError:()=>BatchStoreMissingError,BranchSummaryError:()=>BranchSummaryError,CHAIN_COUNT_LIMIT:()=>CHAIN_COUNT_LIMIT,CHAIN_ORIGIN:()=>CHAIN_ORIGIN,COMPACTION_SUMMARY_PREFIX:()=>COMPACTION_SUMMARY_PREFIX,COMPACTION_SUMMARY_SUFFIX:()=>COMPACTION_SUMMARY_SUFFIX,ChainCountLimitError:()=>ChainCountLimitError,Closed:()=>Closed,CompactionError:()=>CompactionError,DEFAULT_COMPACTION_SETTINGS:()=>DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES:()=>DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES:()=>DEFAULT_MAX_LINES,DEFAULT_WORKSPACE:()=>DEFAULT_WORKSPACE,DEVICE_FILE_OPS:()=>DEVICE_FILE_OPS,DeviceFileError:()=>DeviceFileError,EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC:()=>EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC,EPOCH_FLOOR_MAX_STEP:()=>EPOCH_FLOOR_MAX_STEP,EPOCH_FRESHNESS_MS:()=>EPOCH_FRESHNESS_MS,ExecutionError:()=>ExecutionError,FILE_CHANNEL:()=>FILE_CHANNEL,FILE_CHANNEL_MAX_BYTES:()=>FILE_CHANNEL_MAX_BYTES,FileError:()=>FileError,GREP_MAX_LINE_LENGTH:()=>GREP_MAX_LINE_LENGTH,HAND_CAPABILITY:()=>HAND_CAPABILITY,HAND_CONTROL_LANE:()=>HAND_CONTROL_LANE,HAND_SELF_SENDER:()=>HAND_SELF_SENDER,HAND_WAKE_LANE:()=>HAND_WAKE_LANE,HARNESS_TELEMETRY_SCHEMA:()=>HARNESS_TELEMETRY_SCHEMA,HELLO_WAIT_MS:()=>HELLO_WAIT_MS,HOSTED_REBUILD_DEADLINE_MS:()=>HOSTED_REBUILD_DEADLINE_MS,HarnessClosed:()=>HarnessClosed,HarnessFault:()=>HarnessFault,InMemoryTelemetryContext:()=>InMemoryTelemetryContext,InvalidLane:()=>InvalidLane,InvalidMessage:()=>InvalidMessage,InvalidNavigation:()=>InvalidNavigation,InvalidReadSegmentsError:()=>InvalidReadSegmentsError,JSONL_STORAGE_VERSION:()=>JSONL_STORAGE_VERSION,JsonlSessionRepo:()=>JsonlSessionRepo,LOCAL_DEVICE_FILES:()=>LOCAL_DEVICE_FILES,LaneBusy:()=>LaneBusy,LoopHookFailedError:()=>LoopHookFailedError,LoopHookRestartedError:()=>LoopHookRestartedError,MODEL_PLANE:()=>MODEL_PLANE,MOVE_SKEW_MS:()=>MOVE_SKEW_MS,MalformedHandWakeError:()=>MalformedHandWakeError,MalformedWakeError:()=>MalformedWakeError,MemorySessionRepo:()=>MemorySessionRepo,NOOP_TELEMETRY_CONTEXT:()=>NOOP_TELEMETRY_CONTEXT,NoActiveOperation:()=>NoActiveOperation,NoActiveRun:()=>NoActiveRun,NothingToCompact:()=>NothingToCompact,NothingToResume:()=>NothingToResume,ONE_SHOT_MODES:()=>ONE_SHOT_MODES,OperationMismatch:()=>OperationMismatch,PlaneRefusedError:()=>PlaneRefusedError,PreflightCarryMissingError:()=>PreflightCarryMissingError,ProviderRetryWatchdogAbortError:()=>ProviderRetryWatchdogAbortError,READ_FOLDER_SELECTION:()=>READ_FOLDER_SELECTION,READ_FOLD_SETTINGS:()=>READ_FOLD_SETTINGS,RUN_CHANNEL:()=>RUN_CHANNEL,RemoteProtocolError:()=>RemoteProtocolError,Result:()=>Result,SESSION_PLANE:()=>SESSION_PLANE,STREAMED_DELTA_TYPES:()=>STREAMED_DELTA_TYPES,SessionBranchExistsError:()=>SessionBranchExistsError,SessionInvalidBranchError:()=>SessionInvalidBranchError,SessionInvariantError:()=>SessionInvariantError,SessionPendingAssistantMessageError:()=>SessionPendingAssistantMessageError,SessionStoreError:()=>SessionStoreError,SessionUnknownTargetError:()=>SessionUnknownTargetError,SliceNotImplemented:()=>SliceNotImplemented,StepCommitError:()=>StepCommitError,StorageBackedSession:()=>StorageBackedSession,StreamStartTimeoutError:()=>StreamStartTimeoutError,TODO_CONTEXT:()=>TODO_CONTEXT,TaggedError:()=>TaggedError,UnknownSkill:()=>UnknownSkill,UnknownTarget:()=>UnknownTarget,UnknownTemplate:()=>UnknownTemplate,WAKE_DROPPED_SOURCE:()=>WAKE_DROPPED_SOURCE,WAKE_RETENTION_MS:()=>WAKE_RETENTION_MS,WakeRefusedError:()=>WakeRefusedError,admitChainCall:()=>admitChainCall,agentLoop:()=>agentLoop2,agentLoopContinue:()=>agentLoopContinue2,appendList:()=>appendList,appendRecordWrites:()=>appendRecordWrites,applyShellOutputUpdate:()=>applyShellOutputUpdate,authorize:()=>authorize,awaitWithContext:()=>awaitWithContext,base64Length:()=>base64Length,bashExecutionToText:()=>bashExecutionToText,branchTip:()=>branchTip,branchTipInventoryPrefix:()=>branchTipInventoryPrefix,buildProviderContext:()=>buildProviderContext,calculateContextTokens:()=>calculateContextTokens,canonicalJson:()=>canonicalJson,collectEntriesForBranchSummary:()=>collectEntriesForBranchSummary,commitWrite:()=>commitWrite,compact:()=>compact,convertToLlm:()=>convertToLlm,createAdmissionLine:()=>createAdmissionLine,createBashTool:()=>createBashTool,createBatchCoordinator:()=>createBatchCoordinator,createBranchSummaryMessage:()=>createBranchSummaryMessage,createCompactionSummaryMessage:()=>createCompactionSummaryMessage,createContextKey:()=>createContextKey,createCustomMessage:()=>createCustomMessage,createDefaultReadSummary:()=>createDefaultReadSummary,createEditTool:()=>createEditTool,createErrorToolResult:()=>createErrorToolResult,createExecutionLedger:()=>createExecutionLedger,createForkSnapshot:()=>createForkSnapshot,createGrantVerifier:()=>createGrantVerifier,createHandEpochFence:()=>createHandEpochFence,createHandLedger:()=>createHandLedger,createHandWakeLink:()=>createHandWakeLink,createInProcessNetwork:()=>createInProcessNetwork,createInternalAgentChannel:()=>createInternalAgentChannel,createLoopHookHost:()=>createLoopHookHost,createLoopToolHost:()=>createLoopToolHost,createMemoryStoreMedium:()=>createMemoryStoreMedium,createModelPlaneClient:()=>createModelPlaneClient,createPreparedToolHost:()=>createPreparedToolHost,createReadTool:()=>createReadTool,createReliableTransport:()=>createReliableTransport,createRemoteExecutor:()=>createRemoteExecutor,createRemoteToolHost:()=>createRemoteToolHost,createResponseTimingRecorder:()=>createResponseTimingRecorder,createSegmentedReadView:()=>createSegmentedReadView,createSessionPlaneClient:()=>createSessionPlaneClient,createSplitToolHost:()=>createSplitToolHost,createToolResultMessage:()=>createToolResultMessage,createTypedSpanStarter:()=>createTypedSpanStarter,createWakeInbox:()=>createWakeInbox,createWakeOutbox:()=>createWakeOutbox,createWriteTool:()=>createWriteTool,decodeBase64:()=>decodeBase64,decodeChainCount:()=>decodeChainCount,decodeDeviceFileArgs:()=>decodeDeviceFileArgs,decodeModelPlaneRequest:()=>decodeModelPlaneRequest,decodePlaneMessage:()=>decodePlaneMessage,decodeRemoteMessage:()=>decodeRemoteMessage,decodeSessionPlaneRequest:()=>decodeSessionPlaneRequest,decodeWakeLinkMessage:()=>decodeWakeLinkMessage,defineTelemetrySchema:()=>defineTelemetrySchema,deleteList:()=>deleteList,deleteValue:()=>deleteValue,deliverHandDrop:()=>deliverHandDrop,deliverHandWake:()=>deliverHandWake,divergenceWrite:()=>divergenceWrite,emitToolExecutionEnd:()=>emitToolExecutionEnd,emitToolExecutionUpdate:()=>emitToolExecutionUpdate,emitToolResultMessage:()=>emitToolResultMessage,encodeBase64:()=>encodeBase64,encodePlaneMessage:()=>encodePlaneMessage,encodeRemoteMessage:()=>encodeRemoteMessage,encodeWakeLinkMessage:()=>encodeWakeLinkMessage,entryLabel:()=>entryLabel,err:()=>err,estimateContextTokens:()=>estimateContextTokens,estimateTokens:()=>estimateTokens,executeShellWithCapture:()=>executeShellWithCapture,fileOutcomeOf:()=>fileOutcomeOf,fileRefusal:()=>fileRefusal,fileResult:()=>fileResult,findCutPoint:()=>findCutPoint,findTurnStartIndex:()=>findTurnStartIndex,formatPromptTemplateInvocation:()=>formatPromptTemplateInvocation,formatSize:()=>formatSize,formatSkillInvocation:()=>formatSkillInvocation,formatSkillsForSystemPrompt:()=>formatSkillsForSystemPrompt,generateBranchSummary:()=>generateBranchSummary,generateSummary:()=>generateSummary,generateSummaryWithUsage:()=>generateSummaryWithUsage,getLastAssistantUsage:()=>getLastAssistantUsage,getOrThrow:()=>getOrThrow,getOrUndefined:()=>getOrUndefined,getSessionCwd:()=>getSessionCwd,getTelemetryContext:()=>getTelemetryContext,insertEntry:()=>insertEntry,insertUsage:()=>insertUsage,isLocalDeviceFiles:()=>isLocalDeviceFiles,isReadSummaryPath:()=>isReadSummaryPath,isStepCommitError:()=>isStepCommitError,laneConfig:()=>laneConfig,laneState:()=>laneState,languageForPath:()=>languageForPath,list:()=>list,loadPromptTemplates:()=>loadPromptTemplates,loadSkills:()=>loadSkills,loadSourcedPromptTemplates:()=>loadSourcedPromptTemplates,loadSourcedSkills:()=>loadSourcedSkills,localEndpoint:()=>localEndpoint,loopSideToolNames:()=>loopSideToolNames,manifestWrite:()=>manifestWrite,matchError:()=>matchError,nextChainCount:()=>nextChainCount,noPreflightCarry:()=>noPreflightCarry,ok:()=>ok,openMemoryBatchStore:()=>openMemoryBatchStore,openMemoryStore:()=>openMemoryStore,openSessionStore:()=>openSessionStore,openSyncSessionStore:()=>openSyncSessionStore,operationMeta:()=>operationMeta,operationPreparation:()=>operationPreparation,operationPreparationPrefix:()=>operationPreparationPrefix,operationResult:()=>operationResult,operationScopeOf:()=>operationScopeOf,operationState:()=>operationState,operationToolArgs:()=>operationToolArgs,operationToolArgsPrefix:()=>operationToolArgsPrefix,operationToolMemo:()=>operationToolMemo,operationToolMemoPrefix:()=>operationToolMemoPrefix,parseCommandArgs:()=>parseCommandArgs,parseHandWake:()=>parseHandWake,pendingAssistantFrames:()=>pendingAssistantFrames,pendingEntry:()=>pendingEntry,pendingToolOutput:()=>pendingToolOutput,pendingToolOutputPrefix:()=>pendingToolOutputPrefix,prepareAgentToolCall:()=>prepareAgentToolCall,prepareAgentToolCallArguments:()=>prepareAgentToolCallArguments,prepareBranchEntries:()=>prepareBranchEntries,prepareCompaction:()=>prepareCompaction,prepareReadFolder:()=>prepareReadFolder,prepareStorageCommit:()=>prepareStorageCommit,prepareToolArguments:()=>prepareToolArguments,projectForkCurrentStateWrite:()=>projectForkCurrentStateWrite,readSessionState:()=>readSessionState,readSummaryEngineForPath:()=>readSummaryEngineForPath,reasonedBeforeFirstDelta:()=>reasonedBeforeFirstDelta,reduceLaneSnapshot:()=>reduceLaneSnapshot,renderSegmentedReadView:()=>renderSegmentedReadView,resolveListReadOptions:()=>resolveListReadOptions,resolveToolNameAlias:()=>resolveToolNameAlias,rewriteRecordWrite:()=>rewriteRecordWrite,runAgentLoop:()=>runAgentLoop2,runAgentLoopContinue:()=>runAgentLoopContinue2,runToolCall:()=>runToolCall,sanitizeBinaryOutput:()=>sanitizeShellOutput,scopeSessionCheck:()=>scopeSessionCheck,selectedReadFolder:()=>selectedReadFolder,serializeConversation:()=>serializeConversation,serveHandWakes:()=>serveHandWakes,serveLoopHooks:()=>serveLoopHooks,serveModelPlane:()=>serveModelPlane,serveSessionPlane:()=>serveSessionPlane,sessionName:()=>sessionName,setDefaultStreamFn:()=>setDefaultStreamFn,setValue:()=>setValue,shouldCompact:()=>shouldCompact,shouldTerminateToolBatch:()=>shouldTerminateToolBatch,startAiSpan:()=>startAiSpan,startHarnessSpan:()=>startHarnessSpan,streamProxy:()=>streamProxy,substituteArgs:()=>substituteArgs,toError:()=>toError,toStoreValue:()=>toStoreValue,truncateHead:()=>truncateHead,truncateLine:()=>truncateLine,truncateTail:()=>truncateTail,utf8ByteLength:()=>utf8ByteLength,uuidv7:()=>uuidv7,validateCommittedWrites:()=>validateCommittedWrites,value:()=>value,withAbortSignal:()=>withAbortSignal,withCancel:()=>withCancel,withContextValue:()=>withContextValue,withSessionCwd:()=>withSessionCwd,withTelemetryContext:()=>withTelemetryContext,withToolNameCorrection:()=>withToolNameCorrection,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 copy2={};if(!attributes)return copy2;for(let[name,value2]of Object.entries(attributes))value2!==void 0&&(copy2[name]=copyAttributeValue(value2));return copy2}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(message2){return message2.stopReason!=="toolUse"||message2.content.some(block=>block.type==="toolCall")?message2:{...message2,stopReason:"stop",diagnostics:[...message2.diagnostics??[],{type:EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC,timestamp:Date.now(),details:{}}]}}function promoteStopWithPendingToolCalls(message2){return message2.stopReason!=="stop"||!message2.content.some(block=>block.type==="toolCall")?message2:{...message2,stopReason:"toolUse"}}function settleStopReason(message2){return demoteToolUseWithoutToolCalls(promoteStopWithPendingToolCalls(message2))}function shouldTerminateAssistantTurn(message2){return message2.stopReason==="error"||message2.stopReason==="aborted"||isClassifierRefusal(message2)}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,message2={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()};return sanitizeProviderErrorMessage(message2),message2}function normalizeTerminalAssistantMessage(message2,event){if(event.type==="done")return message2;let errorMessage2=message2.errorMessage??(event.reason==="aborted"?"Request was aborted":"Error");return message2.stopReason===event.reason&&message2.errorMessage===errorMessage2?message2:{...message2,stopReason:event.reason,errorMessage:errorMessage2}}var STREAMED_DELTA_TYPES=new Set(["text_delta","thinking_delta","toolcall_delta"]);function reasonedBeforeFirstDelta(message2,thinkingStreamed){return(message2.usage?.reasoning??0)>0?!0:thinkingStreamed?!1:message2.content?.some(block=>block.type==="thinking")??!1}function createResponseTimingRecorder(){let requestedAt,startedMs,firstDeltaMs,lastDeltaMs,firstTokenAt,lastTokenAt,thinkingStreamed=!1;return{requested(){requestedAt=Date.now()},started(){startedMs??=performance.now()},observe(event){if(!STREAMED_DELTA_TYPES.has(event.type))return;let now=performance.now(),at=Date.now();event.type==="thinking_delta"&&(thinkingStreamed=!0),firstDeltaMs??=now,firstTokenAt??=at,lastDeltaMs=now,lastTokenAt=at},stamp(message2){if(requestedAt===void 0)return;let windowStart=reasonedBeforeFirstDelta(message2,thinkingStreamed)?startedMs:firstDeltaMs,generationMs=windowStart!==void 0&&lastDeltaMs!==void 0&&lastDeltaMs>windowStart?Math.round(lastDeltaMs-windowStart):void 0;message2.timing={requestedAt,...firstTokenAt===void 0?{}:{firstTokenAt},...lastTokenAt===void 0?{}:{lastTokenAt},endedAt:Math.max(Date.now(),lastTokenAt??requestedAt),...generationMs===void 0?{}:{generationMs}}}}}var internalProgressSink=Symbol("internalProgressSink"),channels=new WeakMap;function createInternalAgentChannel(){let state={sequence:0,listeners:new Set},releaseCapture,channel=Object.freeze({subscribe(listener){return state.listeners.add(listener),releaseCapture??=subscribeAssistantCapture(),()=>{state.listeners.delete(listener),state.listeners.size===0&&(releaseCapture?.(),releaseCapture=void 0)}}});return channels.set(channel,state),channel}function internalLoopSink(channel){return!channel||!channels.get(channel)?.listeners.size?{}:{[internalProgressSink]:progress2=>dispatchInternalAgent(channel,{progress:progress2})}}function dispatchInternalAgent(channel,event){let state=channel&&channels.get(channel);if(!state?.listeners.size)return;let record2=Object.freeze({...event,sequence:++state.sequence});return(async()=>{for(let listener of state.listeners)await listener(record2)})()}function isEmptyStop(message2){return message2.stopReason==="stop"&&!hasVisibleAssistantContent(message2)}function isEmptyToolUse(message2){return message2.stopReason==="toolUse"&&!message2.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(message2,type="empty_assistant_response_recovery",details={retries:1}){return{...message2,diagnostics:[...message2.diagnostics??[],{type,timestamp:Date.now(),details}]}}function recoveryDiagnosticType(toolUse){return toolUse?"empty_tool_use_response_recovery":"empty_assistant_response_recovery"}function createEmptyResponseFailure(message2,toolUse=!1){let errorMessage2=toolUse?EMPTY_TOOL_USE_ERROR:EMPTY_RESPONSE_ERROR;return{...appendRetryDiagnostic(message2,recoveryDiagnosticType(toolUse)),content:[{type:"text",text:errorMessage2}],stopReason:"error",errorMessage:errorMessage2}}function createForwardedEmptyFailure(message2,toolUse){return{...appendRetryDiagnostic(message2,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(),forward=entry2=>{"event"in entry2?outerStream.push(entry2.event):pushAssistantProgress(outerStream,entry2.progress)},replaced=(source,error)=>carryAssistantCapture(source,{type:"error",reason:"error",error},error);return(async()=>{try{let stream=firstStream,retrying=!1;for(;;){let buffered=[],forwarding=!1,retry=!1,events=assistantEvents(stream,progress2=>{forwarding?pushAssistantProgress(outerStream,progress2):buffered.push({progress:progress2})});for await(let event of events){if(event.type==="done"){let emptyToolUse=isEmptyToolUse(event.message);if(isEmptyStop(event.message)||emptyToolUse){if(forwarding){outerStream.push(replaced(event,createForwardedEmptyFailure(event.message,emptyToolUse))),outerStream.end();return}if(!retrying){retry=!0;break}outerStream.push(replaced(event,createEmptyResponseFailure(event.message,emptyToolUse))),outerStream.end();return}let message2=retrying?appendRetryDiagnostic(event.message,recoveryDiagnosticType(isEmptyToolUse(event.message))):event.message,terminal2=retrying?carryAssistantCapture(event,{...event,message:message2},message2):event;if(!forwarding)for(let pending of buffered)forward(pending);outerStream.push(terminal2),outerStream.end();return}if(event.type==="error"){if(!forwarding)for(let pending of buffered)forward(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)forward(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}var StreamKeepAliveTimeoutError=class extends Error{constructor(timeoutMs){super(`Provider stream sent only keep-alives and timed out after ${timeoutMs}ms (raise streamKeepAliveTimeoutMs: retry.provider.keepAliveTimeoutMs in senpi settings; 0 disables)`),this.name="StreamKeepAliveTimeoutError"}};function createTransportLiveness(keepAliveTimeoutMs){let lastActivityAt,contentSilenceSince=Date.now();return{noteActivity:()=>{lastActivityAt=Date.now()},contentArrived:()=>{contentSilenceSince=Date.now()},onSilenceDeadline:windowMs=>{let now=Date.now();if(lastActivityAt===void 0||now-lastActivityAt>=windowMs)return{kind:"expire"};let delayMs=windowMs-(now-lastActivityAt);if(keepAliveTimeoutMs===void 0)return{kind:"extend",delayMs};let keepAliveLeftMs=keepAliveTimeoutMs-(now-contentSilenceSince);return keepAliveLeftMs<=0?{kind:"keep-alive-exhausted",error:new StreamKeepAliveTimeoutError(keepAliveTimeoutMs)}:{kind:"extend",delayMs:Math.max(1,Math.min(delayMs,keepAliveLeftMs))}}}}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,resolved){return`[auto-corrected] no tool is named "${requested}"; ran "${resolved}". Call tools by their exact listed name.`}function withToolNameCorrection(result,requestedName,resolvedName){return{...result,content:[{type:"text",text:toolNameCorrectionNotice(requestedName,resolvedName),audience:"model"},...result.content??[]]}}function createErrorToolResult(message2){return{content:[{type:"text",text:message2}],details:{}}}function emitToolExecutionUpdate(toolCall,emit){return partialResult=>emit({type:"tool_execution_update",toolCallId:toolCall.id,toolName:toolCall.name,args:toolCall.arguments,partialResult})}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 shouldTerminateToolBatch(finalizedCalls){return finalizedCalls.length>0&&finalizedCalls.every(finalized=>finalized.result.terminate===!0)}function createAdmissionLine(){let tail=Promise.resolve();return{admit(mutation){let run=tail.then(()=>mutation());return tail=run.then(()=>{},()=>{}),run}}}function object(value2){return value2!==null&&typeof value2=="object"&&!Array.isArray(value2)}function strings(value2,keys){return keys.every(key=>typeof value2[key]=="string")}function numbers(value2,keys){return keys.every(key=>typeof value2[key]=="number"&&Number.isFinite(value2[key]))}function terminal(value2){return!object(value2)||typeof value2.hooksRan!="boolean"||typeof value2.uncertain!="boolean"?!1:value2.reason==="result"||value2.reason==="blocked"?value2.value!==void 0:["cancelled","lease_expired","hand_restarted","uncertain"].includes(String(value2.reason))}function manifestCall(value2){return object(value2)&&strings(value2,["executionId","executor","name","requestDigest"])&&numbers(value2,["sourceIndex","wave"])&&typeof value2.sequential=="boolean"&&value2.args!==void 0&&Array.isArray(value2.dependsOn)&&value2.dependsOn.every(dependency=>typeof dependency=="number")}function manifest(value2){return object(value2)&&strings(value2,["batchId","scope","workspace","issuer","manifestDigest"])&&numbers(value2,["generation","admittedAt","leaseUntil"])&&Array.isArray(value2.calls)&&value2.calls.every(manifestCall)}function prepareReply(value2){if(!object(value2))return!1;switch(value2.kind){case"prepared":case"prepared_awaiting_consent":return typeof value2.frozenDigest=="string";case"blocked":return value2.result!==void 0;case"batch_abort":return!0;case"settled":return terminal(value2.outcome);default:return!1}}function callOutcome(value2){if(!object(value2))return!1;switch(value2.kind){case"result":return value2.value!==void 0;case"blocked":return value2.result!==void 0;case"not_run":return value2.cause==="batch_abort"||value2.cause==="interrupted_preparation";case"interrupted":return typeof value2.reason=="string"&&typeof value2.uncertain=="boolean";default:return!1}}function consentRecord(value2){return object(value2)&&(value2.gate==="raw"||value2.gate==="frozen")&&typeof value2.digest=="string"&&(value2.answer==="approved"||value2.answer==="denied"||value2.answer==="expired")}function record(value2){if(!object(value2)||!manifest(value2.manifest))return!1;let size=value2.manifest.calls.length,{prepares,released,outcomes,decision,consents}=value2;return(consents===void 0||Array.isArray(consents)&&consents.length===size&&consents.every(entry2=>entry2===null||consentRecord(entry2)))&&(decision===null||decision==="RELEASE"||decision==="ABORT")&&Array.isArray(prepares)&&prepares.length===size&&prepares.every(reply=>reply===null||prepareReply(reply))&&Array.isArray(released)&&released.length===size&&released.every(mark=>typeof mark=="boolean")&&Array.isArray(outcomes)&&outcomes.length===size&&outcomes.every(outcome2=>outcome2===null||callOutcome(outcome2))}var BatchRecordCorruptError=class extends Error{constructor(){super("invalid durable batch record"),this.name="BatchRecordCorruptError"}};function decodeBatchRecord(value2){if(!record(value2))throw new BatchRecordCorruptError;return value2}var denied=(gate,answer2)=>({kind:"blocked",result:{reason:"consent_denied",gate,answer:answer2}}),lost={reason:"uncertain",hooksRan:!0,uncertain:!0},expired={reason:"lease_expired",hooksRan:!0,uncertain:!0};async function answer(step,gate,digest){let{recorded}=step;if(recorded!==null&&recorded.gate===gate&&recorded.digest===digest)return recorded.answer;let given=await step.consent.approve({...step.ref,gate,digest,name:step.call.name,leaseUntil:step.leaseUntil});return await step.record({gate,digest,answer:given}),given}async function gateRawCall(step){let{call}=step;if(!step.consent.needsConsent({name:call.name,args:call.args}))return{};let given=await answer(step,"raw",call.requestDigest);return given==="approved"?{authorizedDigest:call.requestDigest}:{blocked:denied("raw",given)}}async function resolveFrozenConsent(step,frozenDigest){let given=await answer(step,"frozen",frozenDigest);if(given==="denied")return await step.executor.abort(step.ref),denied("frozen",given);if(given==="expired")return{kind:"settled",outcome:expired};let reply=await consentOn(step.executor,step.ref,frozenDigest);return reply.kind==="prepared"?{kind:"prepared",frozenDigest}:reply.kind==="unknown_execution"?{kind:"settled",outcome:lost}:{kind:"settled",outcome:reply.outcome}}function consentOn(executor,ref,frozenDigest){if(executor.consent===void 0)throw new Error(`executor answered prepared_awaiting_consent for ${ref.executionId} but cannot take consent`);return executor.consent(ref,frozenDigest)}function canonicalJson(value2){return Array.isArray(value2)?`[${value2.map(canonicalJson).join(",")}]`:value2!==null&&typeof value2=="object"?`{${Object.entries(value2).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([key,inner])=>`${JSON.stringify(key)}:${canonicalJson(inner)}`).join(",")}}`:JSON.stringify(value2)}async function canonicalDigest(value2){let bytes=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(canonicalJson(value2)));return Array.from(new Uint8Array(bytes),byte=>byte.toString(16).padStart(2,"0")).join("")}function batchDependencies(calls){let result=[],previousSequential,parallelSince=[];for(let[index,call]of calls.entries()){let anchor=previousSequential===void 0?[]:[previousSequential],dependsOn=call.sequential?[...anchor,...parallelSince]:anchor,wave=Math.max(-1,...dependsOn.map(dependency=>result[dependency]?.wave??-1))+1;result.push({dependsOn,wave}),call.sequential?(previousSequential=index,parallelSince=[]):parallelSince.push(index)}return result}async function buildBatchManifest(issuer,plan){let dependencies=batchDependencies(plan.calls),calls=[];for(let[sourceIndex,call]of plan.calls.entries()){let placement=dependencies[sourceIndex]??{dependsOn:[],wave:0};calls.push({...call,sourceIndex,dependsOn:placement.dependsOn,wave:placement.wave,requestDigest:await canonicalDigest({name:call.name,args:call.args})})}let{calls:_calls,...header}=plan;return{...header,issuer,calls,manifestDigest:await canonicalDigest({...header,issuer,calls})}}function abortCause(reply){if(reply.kind==="batch_abort")return"batch_abort";if(reply.kind==="settled"&&reply.outcome.reason!=="result")return"interrupted_preparation"}function finished(calls,outcomes,index){let done=new Map,visit=at=>{let known=done.get(at);if(known!==void 0)return known;let result=outcomes[at]!==null&&(calls[at]?.dependsOn??[]).every(dependency=>visit(dependency));return done.set(at,result),result};return visit(index)}function settledOutcome(reply){if(reply.kind==="unknown_execution")return{kind:"interrupted",reason:"unknown_execution",uncertain:!0};let{outcome:outcome2}=reply;switch(outcome2.reason){case"result":return{kind:"result",value:outcome2.value};case"blocked":return{kind:"blocked",result:outcome2.value};default:return{kind:"interrupted",reason:outcome2.reason,uncertain:outcome2.uncertain}}}var PREFIX="execution.batch:",keyOf=(issuer,batchId)=>`${PREFIX}${JSON.stringify([issuer,batchId])}`,BatchManifestConflictError=class extends Error{constructor(batchId){super(`batch ${batchId} already has a different durable manifest`),this.name="BatchManifestConflictError"}},replace=(items,index,value2)=>items.map((item,at)=>at===index?value2:item);function createBatchCoordinator(options){let{issuer,store,epoch,admission,executor,consent}=options,read=async batchId=>{let value2=await store.getDocument(keyOf(issuer,batchId));return value2===void 0?void 0:decodeBatchRecord(value2)};return{read,run:async plan=>{let manifest2=await buildBatchManifest(issuer,plan),key=keyOf(issuer,plan.batchId),record2=await read(plan.batchId),persist=async(next,step,call)=>{let data={batchId:plan.batchId,step,executionId:call?.executionId??null};await admission.admit(()=>store.commit(epoch,[{op:"append",id:store.mintId(),kind:"execution.batch",data},{op:"put",key,data:next}],()=>{})),record2=next},current=()=>{if(record2===void 0)throw new Error(`batch ${plan.batchId} has no durable record`);return record2},ref=call=>({issuer,executionId:call.executionId,generation:manifest2.generation}),settle2=async(call,outcome2)=>persist({...current(),outcomes:replace(current().outcomes,call.sourceIndex,outcome2)},"outcome",call);if(record2===void 0){let empty=manifest2.calls.map(()=>null);await persist({manifest:manifest2,prepares:empty,decision:null,released:manifest2.calls.map(()=>!1),outcomes:empty},"manifest")}else if(record2.manifest.manifestDigest!==manifest2.manifestDigest)throw new BatchManifestConflictError(plan.batchId);let consentStep=(gate,call)=>({consent:gate,executor:executor(call.executor),ref:ref(call),call,leaseUntil:manifest2.leaseUntil,recorded:current().consents?.[call.sourceIndex]??null,record:answered=>persist({...current(),consents:replace(current().consents??manifest2.calls.map(()=>null),call.sourceIndex,answered)},"consent",call)}),setPrepare=(call,reply)=>persist({...current(),prepares:replace(current().prepares,call.sourceIndex,reply)},"prepare",call);if(current().decision===null){for(let call of manifest2.calls){let reply=current().prepares[call.sourceIndex]??null,gate=reply===null&&consent!==void 0?await gateRawCall(consentStep(consent,call)):{};if(reply===null&&"blocked"in gate?(reply=gate.blocked,await setPrepare(call,reply)):reply===null&&(reply=await executor(call.executor).prepare({..."authorizedDigest"in gate&&gate.authorizedDigest!==void 0?{authorizedDigest:gate.authorizedDigest}:{},...ref(call),batchId:manifest2.batchId,manifestDigest:manifest2.manifestDigest,scope:manifest2.scope,workspace:manifest2.workspace,admittedAt:manifest2.admittedAt,leaseUntil:manifest2.leaseUntil,requestDigest:call.requestDigest,call:{name:call.name,args:call.args}}),await setPrepare(call,reply)),abortCause(reply)!==void 0)break}for(let call of manifest2.calls){if(current().prepares.some(reply2=>reply2!==null&&abortCause(reply2)!==void 0))break;let reply=current().prepares[call.sourceIndex]??null;if(reply?.kind==="prepared_awaiting_consent"){if(consent===void 0)throw new Error(`batch ${plan.batchId}: a call awaits consent but none is configured`);await setPrepare(call,await resolveFrozenConsent(consentStep(consent,call),reply.frozenDigest))}}let aborted=current().prepares.some(reply=>reply!==null&&abortCause(reply)!==void 0);await persist({...current(),decision:aborted?"ABORT":"RELEASE"},"decision")}let cause=current().prepares.map(reply=>reply===null?void 0:abortCause(reply)).find(found=>found!==void 0)??"batch_abort";for(let call of manifest2.calls){if(current().outcomes[call.sourceIndex]!==null)continue;let reply=current().prepares[call.sourceIndex]??null;reply?.kind==="settled"?await settle2(call,settledOutcome(reply)):reply?.kind==="blocked"?(await executor(call.executor).abort(ref(call)),await settle2(call,{kind:"blocked",result:reply.result})):current().decision==="ABORT"&&(reply!==null&&await executor(call.executor).abort(ref(call)),await settle2(call,{kind:"not_run",cause}))}let inflight=new Map;for(;;){for(let call2 of manifest2.calls){let index=call2.sourceIndex;if(!(current().outcomes[index]!==null||inflight.has(index))){if(!current().released[index]){if(!call2.dependsOn.every(dependency=>finished(manifest2.calls,current().outcomes,dependency)))continue;await persist({...current(),released:replace(current().released,index,!0)},"release",call2)}inflight.set(index,executor(call2.executor).release(ref(call2)).then(reply=>({index,ok:!0,reply}),error=>({index,ok:!1,error})))}}if(inflight.size===0)break;let settled=await Promise.race(inflight.values());if(inflight.delete(settled.index),!settled.ok)throw settled.error;let call=manifest2.calls[settled.index];call!==void 0&&await settle2(call,settledOutcome(settled.reply))}let{decision,outcomes}=current(),final=outcomes.filter(outcome2=>outcome2!==null);if(decision===null||final.length!==outcomes.length)throw new Error(`batch ${plan.batchId} ended with an unsettled call`);return{decision,outcomes:final}}}}function object2(value2){return value2!==null&&typeof value2=="object"&&!Array.isArray(value2)}function frozen(value2){return object2(value2)&&typeof value2.name=="string"&&typeof value2.digest=="string"&&value2.args!==void 0}function outcome(value2){if(!object2(value2)||typeof value2.hooksRan!="boolean"||typeof value2.uncertain!="boolean")return!1;switch(value2.reason){case"result":case"blocked":return value2.value!==void 0&&value2.uncertain===!1;case"cancelled":case"lease_expired":case"hand_restarted":case"uncertain":return!0;default:return!1}}function progress(value2){if(!object2(value2))return!1;switch(value2.state){case"admitted":case"preparing":case"acked":return!0;case"prepared":case"prepared_awaiting_consent":case"released":case"dispatched":return frozen(value2.call);case"reconciling":return frozen(value2.call)&&typeof value2.until=="number"&&Number.isFinite(value2.until);case"settled":return outcome(value2.outcome);default:return!1}}function entry(value2){return object2(value2)&&["issuer","commandId","executor","workspace","scope","requestDigest"].every(key=>typeof value2[key]=="string")&&["generation","admittedAt","leaseUntil","initialLeaseUntil","renewSeq"].every(key=>typeof value2[key]=="number"&&Number.isFinite(value2[key]))&&typeof value2.reconcilable=="boolean"&&typeof value2.effectPossible=="boolean"&&typeof value2.bodyDispatched=="boolean"&&progress(value2.progress)}var ExecutionLedgerCorruptError=class extends Error{constructor(){super("invalid durable execution ledger row"),this.name="ExecutionLedgerCorruptError"}};function decodeExecution(value2){if(!entry(value2))throw new ExecutionLedgerCorruptError;return value2}var refused=reason=>({status:"refused",reason}),replayed=entry2=>entry2.progress.state==="acked"?{status:"result_expired"}:{status:"replayed",entry:entry2},applied=entry2=>({status:"applied",entry:entry2});var advance=(entry2,progress2)=>applied({...entry2,progress:progress2}),settle=(entry2,reason)=>advance(entry2,{state:"settled",outcome:{reason,hooksRan:entry2.effectPossible,uncertain:entry2.effectPossible||entry2.bodyDispatched}});function authorized(entry2,{actor,event}){switch(event.kind){case"cancel":return actor.id===entry2.issuer||actor.approvedWorkspace===entry2.workspace;case"consent":case"release":case"abort":case"ack":case"renew":return actor.id===entry2.issuer;case"prepare":case"effect":case"freeze":case"block":case"dispatch":case"result":case"expire":case"restart":return actor.id===entry2.executor}}function recover(entry2,now){switch(entry2.progress.state){case"admitted":case"preparing":return settle(entry2,"hand_restarted");case"dispatched":return entry2.reconcilable?advance(entry2,{state:"reconciling",call:entry2.progress.call,until:Math.min(entry2.leaseUntil,now+3e4)}):settle(entry2,"hand_restarted");case"reconciling":return now>=entry2.progress.until?settle(entry2,"hand_restarted"):replayed(entry2);case"prepared":case"prepared_awaiting_consent":case"released":case"settled":case"acked":return replayed(entry2)}}function transitionExecution(entry2,command){let{event,now}=command;if(command.generation!==entry2.generation)return refused("stale_generation");if(!authorized(entry2,command))return refused("unauthorized");if(!Number.isFinite(now)||now<entry2.admittedAt)return refused("invalid_time");let progress2=entry2.progress;if(progress2.state==="acked")return event.kind==="ack"?{status:"replayed",entry:entry2}:{status:"result_expired"};if(progress2.state==="settled")switch(event.kind){case"ack":return advance(entry2,{state:"acked"});case"release":case"abort":case"consent":return refused("terminal");default:return replayed(entry2)}if(now>=entry2.leaseUntil)return settle(entry2,"lease_expired");if(progress2.state==="reconciling"&&now>=progress2.until)return settle(entry2,"hand_restarted");switch(event.kind){case"prepare":return progress2.state==="admitted"?advance(entry2,{state:"preparing"}):replayed(entry2);case"effect":return entry2.effectPossible?replayed(entry2):progress2.state==="preparing"?applied({...entry2,effectPossible:!0}):refused("invalid_transition");case"freeze":return progress2.state==="preparing"&&entry2.effectPossible?advance(entry2,{state:event.awaitingConsent?"prepared_awaiting_consent":"prepared",call:event.call}):"call"in progress2&&progress2.call.digest===event.call.digest?replayed(entry2):refused("invalid_transition");case"block":return progress2.state==="preparing"?advance(entry2,{state:"settled",outcome:{reason:"blocked",value:event.value,hooksRan:entry2.effectPossible,uncertain:!1}}):refused("invalid_transition");case"consent":return progress2.state==="prepared_awaiting_consent"?advance(entry2,{state:"prepared",call:progress2.call}):refused("invalid_transition");case"release":return progress2.state==="prepared"?advance(entry2,{state:"released",call:progress2.call}):progress2.state==="released"||entry2.bodyDispatched?replayed(entry2):refused("invalid_transition");case"dispatch":return entry2.bodyDispatched?replayed(entry2):progress2.state==="released"?applied({...entry2,bodyDispatched:!0,progress:{state:"dispatched",call:progress2.call}}):refused("invalid_transition");case"result":return progress2.state!=="dispatched"&&progress2.state!=="reconciling"?refused("invalid_transition"):advance(entry2,{state:"settled",outcome:{reason:"result",value:event.value,hooksRan:entry2.effectPossible,uncertain:!1}});case"cancel":return settle(entry2,"cancelled");case"abort":return entry2.bodyDispatched?refused("invalid_transition"):settle(entry2,"cancelled");case"ack":return refused("invalid_transition");case"renew":return event.seq<=entry2.renewSeq?replayed(entry2):!Number.isSafeInteger(event.seq)||!Number.isFinite(event.leaseUntil)||event.leaseUntil<=entry2.leaseUntil||event.leaseUntil>entry2.admittedAt+864e5?refused("invalid_renewal"):applied({...entry2,renewSeq:event.seq,leaseUntil:event.leaseUntil});case"expire":return replayed(entry2);case"restart":return recover(entry2,now)}}var PREFIX2="execution.ledger:",keyOf2=({issuer,commandId})=>`${PREFIX2}${JSON.stringify([issuer,commandId])}`;function createExecutionLedger(options){let{store,epoch,admission}=options,read=async key=>{let value2=await store.getDocument(keyOf2(key));return value2===void 0?void 0:decodeExecution(value2)},persist=async(entry2,event,audit=!1)=>{let writes=[{op:"append",id:store.mintId(),kind:audit?"execution.audit":"execution.transition",data:{issuer:entry2.issuer,commandId:entry2.commandId,generation:entry2.generation,event,state:entry2.progress.state}}];audit||writes.push({op:"put",key:keyOf2(entry2),data:entry2}),await store.commit(epoch,writes,()=>{})},apply=(command,guard)=>admission.admit(async()=>{let refusal2=guard?.();if(refusal2!==void 0)return refused(refusal2);let entry2=await read(command.key);if(entry2===void 0)return refused("not_found");let reply=transitionExecution(entry2,command);return reply.status==="applied"?await persist(reply.entry,command.event.kind):reply.status==="replayed"&&entry2.progress.state==="settled"&&(command.event.kind==="result"||command.event.kind==="cancel")&&await persist(entry2,command.event.kind,!0),reply});return{read,apply,admit:(input,guard)=>admission.admit(async()=>{let refusal2=guard?.();if(refusal2!==void 0)return refused(refusal2);let prior=await read(input);if(prior!==void 0)return prior.executor===input.executor&&prior.workspace===input.workspace&&prior.scope===input.scope&&prior.generation===input.generation&&prior.requestDigest===input.requestDigest&&prior.admittedAt===input.admittedAt&&prior.initialLeaseUntil===input.leaseUntil&&prior.reconcilable===input.reconcilable?replayed(prior):refused("identity_conflict");if(![input.issuer,input.commandId,input.executor,input.workspace,input.scope,input.requestDigest].every(Boolean)||!Number.isSafeInteger(input.generation)||input.generation<1||!Number.isFinite(input.admittedAt)||!Number.isFinite(input.leaseUntil)||input.leaseUntil<=input.admittedAt||input.leaseUntil>input.admittedAt+864e5)return refused("invalid_admission");let entry2={...input,initialLeaseUntil:input.leaseUntil,renewSeq:0,effectPossible:!1,bodyDispatched:!1,progress:{state:"admitted"}};return await persist(entry2,"admit"),applied(entry2)}),scan:async()=>(await store.scanDocuments(PREFIX2)).map(document=>decodeExecution(document.data)),recover:async now=>{for(let document of await store.scanDocuments(PREFIX2)){let entry2=decodeExecution(document.data);await apply({key:entry2,generation:entry2.generation,actor:{id:entry2.executor},now,event:{kind:"restart"}})}}}}function errorResult(message2){return{content:[{type:"text",text:message2}],details:{}}}function messageOf(error){return error instanceof Error?error.message:String(error)}var ABORTED=Symbol("aborted");async function runBody(body,signal,onUpdate){let updates=[],accepting=!0;try{let execution=body.tool.execute(body.toolCall.id,body.args,signal,partial=>{accepting&&updates.push(Promise.resolve(onUpdate(partial)))}),aborted=signal===void 0?void 0:new Promise(resolve=>{signal.aborted?resolve(ABORTED):signal.addEventListener("abort",()=>resolve(ABORTED),{once:!0})}),settled=aborted?await Promise.race([execution,aborted]):await execution;return accepting=!1,await Promise.all(updates),settled===ABORTED?(Promise.resolve(execution).catch(()=>{}),{result:errorResult("Tool execution aborted"),isError:!0}):{result:settled,isError:settled.isError===!0}}catch(error){return accepting=!1,await Promise.all(updates),{result:errorResult(messageOf(error)),isError:!0}}}async function finalizeBody(body,executed,pipeline,signal){let{result,isError}=executed;try{let after=await pipeline.afterToolCall({assistantMessage:body.assistantMessage,toolCall:body.toolCall,args:body.args,result,isError,context:body.context},signal);if(!after)return executed;let structuredContent=after.structuredContent??(after.content?void 0:result.structuredContent),merged={...result,content:after.content??result.content,details:after.details??result.details,usage:after.usage??result.usage,terminate:after.terminate??result.terminate};return structuredContent===void 0?delete merged.structuredContent:merged.structuredContent=structuredContent,{result:merged,isError:after.isError??isError}}catch(error){return{result:errorResult(messageOf(error)),isError:!0}}}function toStoreValue(value2){let json=JSON.stringify(value2);return json===void 0?null:JSON.parse(json)}async function freezeCall(name,args){let frozenArgs=toStoreValue(args);return{name,args:frozenArgs,digest:await canonicalDigest({name,args:frozenArgs})}}function resultValue(result,isError,requestedName){return toStoreValue({content:result.content??[],isError,requestedName})}function recordedResult(outcome2,requestedName){try{return{...outcome2,value:resultValue(outcome2.result,outcome2.isError,requestedName)}}catch(error){let result=errorResult(`Tool result content is not JSON: ${messageOf(error)}`);return{result,isError:!0,value:resultValue(result,!0,requestedName)}}}function stoppedValue(reply){let text=(reply.result.content??[]).map(part=>part.type==="text"?part.text:"").join(""),requestedName=reply.kind==="blocked"?reply.requestedName:void 0;return toStoreValue({kind:reply.kind,text,terminate:reply.result.terminate===!0,requestedName})}function isRecord6(value2){return value2!==null&&typeof value2=="object"&&!Array.isArray(value2)}function stoppedReply(value2){if(!isRecord6(value2))return;let{kind,text,terminate,requestedName}=value2;if(typeof text!="string"||typeof terminate!="boolean")return;let result=errorResult(text);if(terminate&&(result.terminate=!0),kind==="batch_abort")return{kind,result};if(kind==="blocked")return typeof requestedName=="string"?{kind,result,requestedName}:{kind,result}}var keyId=({issuer,commandId})=>JSON.stringify([issuer,commandId]),keyOf3=request=>({issuer:request.issuer,commandId:request.commandId??request.call.id});function refusal(reply){return{kind:"refused",reason:reply.status==="refused"?reply.reason:reply.status}}function incompleteMessage(name,errorMessage2){return errorMessage2!==void 0?`${errorMessage2}${errorMessage2.endsWith(".")?"":"."} Re-issue the tool call with complete arguments.`:`Tool call "${name}" 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.`}function fromRow(entry2){let progress2=entry2.progress;if(progress2.state==="prepared_awaiting_consent")return{kind:"prepared_awaiting_consent",call:progress2.call};if("call"in progress2)return{kind:"prepared",call:progress2.call};if(progress2.state!=="settled")return{kind:"refused",reason:progress2.state};let outcome2=progress2.outcome;return outcome2.reason!=="blocked"?{kind:"refused",reason:"terminal"}:stoppedReply(outcome2.value)??{kind:"refused",reason:"corrupt_blocked_outcome"}}function createPreparedExecutor(options){let{ledger,executor,pipeline}=options,clock=options.clock??Date.now,preparations=new Map,bodies=new Map,releases=new Map,step=(key,generation,event)=>ledger.apply({key,generation,actor:{id:executor},now:clock(),event});async function stop(key,generation,reply){let recorded=await step(key,generation,{kind:"block",value:stoppedValue(reply)});return recorded.status==="applied"?reply:recorded.status==="replayed"?fromRow(recorded.entry):refusal(recorded)}async function prepareOnce(request,requestDigest){let{call,generation,signal}=request,key=keyOf3(request),admitted=await ledger.admit({...key,executor,workspace:request.workspace,scope:request.scope,generation,requestDigest,admittedAt:request.admittedAt,leaseUntil:request.leaseUntil,reconcilable:request.reconcilable??!1});if(admitted.status==="replayed")return fromRow(admitted.entry);if(admitted.status!=="applied")return refusal(admitted);let preparing=await step(key,generation,{kind:"prepare"});if(preparing.status!=="applied")return refusal(preparing);if(call.incomplete===!0)return stop(key,generation,{kind:"blocked",result:errorResult(incompleteMessage(call.name,call.errorMessage))});let effect=await step(key,generation,{kind:"effect"});if(effect.status!=="applied")return refusal(effect);let tool;try{tool=await pipeline.resolve(call,request.context)}catch(error){return stop(key,generation,{kind:"blocked",result:errorResult(messageOf(error))})}if(!tool){let hint=pipeline.removedToolHint(call.name),text=hint===void 0?`Tool ${call.name} not found`:`Tool ${call.name} not found. ${hint}`;return stop(key,generation,{kind:"blocked",result:errorResult(text)})}let requestedName=tool.name===call.name?void 0:call.name,named=requestedName===void 0?{}:{requestedName};try{let prepared=prepareAgentToolCall(tool,requestedName===void 0?call:{...call,name:tool.name}),before=await pipeline.beforeToolCall({assistantMessage:request.assistantMessage,toolCall:prepared.toolCall,args:prepared.args,context:request.context},signal);if(signal?.aborted)return stop(key,generation,{kind:"batch_abort",result:errorResult("Operation aborted")});if(before?.block){let result=errorResult(before.reason||"Tool execution was blocked");return before.terminate===!0&&(result.terminate=!0),stop(key,generation,{kind:"blocked",result,...named})}let frozen2=await freezeCall(tool.name,prepared.args),covered=request.authorizedDigest===requestDigest&&(await freezeCall(call.name,toStoreValue(call.arguments))).digest===frozen2.digest,awaitingConsent=options.consent!==void 0&&!covered&&options.consent.needsConsent({name:frozen2.name,args:frozen2.args}),freeze=await step(key,generation,{kind:"freeze",call:frozen2,awaitingConsent});return freeze.status!=="applied"?refusal(freeze):(pipeline.afterFreeze(prepared.args,frozen2.args),bodies.set(keyId(key),{...named,tool,toolCall:prepared.toolCall,args:frozen2.args,assistantMessage:request.assistantMessage,context:request.context}),{kind:awaitingConsent?"prepared_awaiting_consent":"prepared",call:frozen2,...named})}catch(error){return stop(key,generation,{kind:"blocked",result:errorResult(messageOf(error)),...named})}}async function terminalRow(key){let entry2=await ledger.read(key);if(entry2===void 0)return{kind:"refused",reason:"not_found"};let progress2=entry2.progress;return progress2.state==="settled"&&progress2.outcome.reason==="blocked"?{kind:"refused",reason:"blocked"}:{kind:"replayed",entry:entry2}}async function runReleased(request,body){let{key,generation,signal}=request,dispatched=await step(key,generation,{kind:"dispatch"});if(dispatched.status==="replayed")return{kind:"replayed",entry:dispatched.entry};if(dispatched.status!=="applied"||dispatched.entry.progress.state!=="dispatched")return refusal(dispatched);let executed=await runBody(body,signal,request.onUpdateFor?.(body.toolCall)??request.onUpdate??(()=>{})),{result,isError,value:value2}=recordedResult(await finalizeBody(body,executed,pipeline,signal),body.requestedName),recorded=await step(key,generation,{kind:"result",value:value2});for(let memo of[bodies,preparations,releases])memo.delete(keyId(key));if(recorded.status==="replayed")return{kind:"replayed",entry:recorded.entry};if(recorded.status!=="applied")return refusal(recorded);let named=body.requestedName===void 0?{}:{requestedName:body.requestedName};return{kind:"settled",toolCall:body.toolCall,result,isError,...named}}async function release(request){let{key,generation}=request,released=await ledger.apply({key,generation,actor:request.actor,now:clock(),event:{kind:"release"}});if(released.status==="refused")return released.reason==="terminal"?terminalRow(key):refusal(released);if(released.status==="result_expired")return refusal(released);let id=keyId(key),pending=releases.get(id);if(pending!==void 0)return pending;let body=bodies.get(id);if(body===void 0)return{kind:"refused",reason:"not_prepared"};if(request.signal?.aborted)return{kind:"aborted",result:errorResult("Operation aborted")};let reply=runReleased(request,body);return releases.set(id,reply),reply.catch(()=>releases.get(id)===reply&&releases.delete(id)),reply}async function consent(request){let entry2=await ledger.read(request.key);if(entry2===void 0)return{kind:"refused",reason:"not_found"};if("call"in entry2.progress&&entry2.progress.call.digest!==request.frozenDigest)return{kind:"refused",reason:"frozen_digest_mismatch"};let reply=await ledger.apply({key:request.key,generation:request.generation,actor:request.actor,now:clock(),event:{kind:"consent"}});if(reply.status==="applied"&&reply.entry.progress.state==="prepared")return{kind:"prepared"};if(reply.status==="refused"&&reply.reason==="invalid_transition"&&entry2.progress.state==="prepared")return{kind:"prepared"};if(reply.status==="applied"||reply.status==="replayed")return{kind:"replayed",entry:reply.entry};if(reply.status==="refused"&&reply.reason==="terminal"){let terminal2=await ledger.read(request.key);return terminal2===void 0?{kind:"refused",reason:"not_found"}:{kind:"replayed",entry:terminal2}}return refusal(reply)}return{consent,prepare:async request=>{let{name,arguments:args,incomplete,errorMessage:errorMessage2}=request.call,requestDigest=await canonicalDigest(toStoreValue({name,args,incomplete,errorMessage:errorMessage2})),admission=JSON.stringify([request.generation,request.workspace,request.scope,requestDigest,request.admittedAt,request.leaseUntil,request.reconcilable??!1]),id=keyId(keyOf3(request)),pending=preparations.get(id);if(pending!==void 0&&pending.admission===admission)return pending.reply;if(pending!==void 0)return{kind:"refused",reason:"identity_conflict"};let reply=prepareOnce(request,requestDigest);preparations.set(id,{admission,reply});let forget=()=>preparations.get(id)?.reply===reply&&preparations.delete(id);return reply.then(settled=>settled.kind==="prepared"||settled.kind==="prepared_awaiting_consent"||forget(),forget),reply},release}}function agentPreparationPipeline(agent){return{resolve:async(call,context)=>{let tools=context.tools??[],exact=tools.find(tool=>tool.name===call.name);if(exact)return exact;let resolved=await agent.resolveUnknownToolCall?.(call.name,context);if(resolved)return resolved;let aliased=resolveToolNameAlias(call.name,tools.map(tool=>tool.name));return tools.find(tool=>tool.name===aliased)},beforeToolCall:async(context,signal)=>agent.beforeToolCall?.(context,signal),afterToolCall:async(context,signal)=>agent.afterToolCall?.(context,signal),removedToolHint:name=>agent.removedToolHints?.[name],afterFreeze:(prepared,frozen2)=>agent.afterToolFreeze(prepared,frozen2)}}var ISSUER="loop",EXECUTOR="local",LEASE_MS=1440*60*1e3,NO_WORKSPACE="in-process";function isSequential(context,name){let tools=context.tools??[],named=resolveToolNameAlias(name,tools.map(tool2=>tool2.name));return(tools.find(candidate=>candidate.name===name)??tools.find(candidate=>candidate.name===named))?.executionMode==="sequential"}async function runPreparedBatch(request){let{source,calls,context,assistantMessage,emit,signal}=request,store=request.openStore();await store.claim(0,1);let admission=createAdmissionLine(),base=agentPreparationPipeline(source),resolved=new Map,prepared=createPreparedExecutor({ledger:createExecutionLedger({store,epoch:1,admission}),executor:EXECUTOR,pipeline:{...base,resolve:async call=>resolved.get(call)}}),executionIdOf=index=>String(index),byExecution=new Map(calls.map((call,index)=>[executionIdOf(index),call])),renamed=new Map,named=(id,call)=>renamed.get(id)??call,callOf=id=>{let call=byExecution.get(id);if(call===void 0)throw new Error(`prepared pipeline: unknown execution ${id}`);return call},started=new Set,pending=new Map,finalized=new Map,finish=async(id,outcome2)=>{finalized.set(id,outcome2),await emitToolExecutionEnd(outcome2,emit)},aborted=call=>({toolCall:call,result:createErrorToolResult("Operation aborted"),isError:!0}),endpoint={prepare:async ref=>{let id=ref.executionId,call=callOf(id);if(signal?.aborted&&started.size>0)return{kind:"batch_abort"};let tool=call.incomplete===!0?void 0:await base.resolve(call,context);resolved.set(call,tool),tool!==void 0&&tool.name!==call.name&&renamed.set(id,{...call,name:tool.name}),await emit({type:"tool_execution_start",toolCallId:call.id,toolName:tool?.name??call.name,args:call.arguments}),started.add(id);let reply=await prepared.prepare({issuer:ISSUER,commandId:id,generation:ref.generation,workspace:ref.workspace,scope:ref.scope,call,assistantMessage,context,admittedAt:ref.admittedAt,leaseUntil:ref.leaseUntil,...signal===void 0?{}:{signal}});if(signal?.aborted)return pending.set(id,aborted(named(id,call))),{kind:"batch_abort"};if(reply.kind==="prepared")return{kind:"prepared",frozenDigest:reply.call.digest};if(reply.kind==="prepared_awaiting_consent")return{kind:"prepared_awaiting_consent",frozenDigest:reply.call.digest};if(reply.kind==="refused")throw new Error(`prepared pipeline refused call ${call.id} (execution ${id}): ${reply.reason}`);let result=reply.kind==="blocked"&&reply.requestedName!==void 0&&tool!==void 0?withToolNameCorrection(reply.result,reply.requestedName,tool.name):reply.result;pending.set(id,{toolCall:named(id,call),result,isError:!0});let value2=toStoreValue({content:result.content??[]});return reply.kind==="blocked"?{kind:"blocked",result:value2}:{kind:"batch_abort"}},release:async ref=>{let id=ref.executionId,call=callOf(id),reply=await prepared.release({key:{issuer:ISSUER,commandId:id},generation:ref.generation,actor:{id:ISSUER},onUpdateFor:toolCall=>emitToolExecutionUpdate(toolCall,emit),...signal===void 0?{}:{signal}});if(reply.kind==="settled"){let result=reply.requestedName===void 0?reply.result:withToolNameCorrection(reply.result,reply.requestedName,reply.toolCall.name);return await finish(id,{toolCall:reply.toolCall,result,isError:reply.isError}),{kind:"settled",outcome:{reason:"result",value:toStoreValue(result.content??[]),hooksRan:!0,uncertain:!1}}}if(reply.kind!=="aborted")throw new Error(`prepared pipeline: release ${reply.kind} for call ${call.id} (execution ${id})`);return await finish(id,signal?.aborted?aborted(named(id,call)):{toolCall:named(id,call),result:reply.result,isError:!0}),{kind:"settled",outcome:{reason:"cancelled",hooksRan:!0,uncertain:!1}}},abort:async ref=>{let id=ref.executionId,call=callOf(id);return started.has(id)&&await finish(id,signal?.aborted?aborted(named(id,call)):pending.get(id)??aborted(named(id,call))),{kind:"settled",outcome:{reason:"cancelled",hooksRan:!1,uncertain:!1}}}},now=Date.now(),plan={batchId:crypto.randomUUID(),scope:request.scope.id,workspace:request.scope.root===""?NO_WORKSPACE:request.scope.root,generation:1,admittedAt:now,leaseUntil:now+LEASE_MS,calls:calls.map((call,index)=>({executionId:executionIdOf(index),executor:EXECUTOR,name:call.name,args:toStoreValue(call.arguments),sequential:isSequential(context,call.name)}))};return await createBatchCoordinator({issuer:ISSUER,store,epoch:1,admission,executor:()=>endpoint}).run(plan),calls.flatMap((_call,index)=>{let id=executionIdOf(index),outcome2=finalized.get(id);return started.has(id)&&outcome2!==void 0?[outcome2]:[]})}function createPreparedToolHost(source,openStore){return{async execute(call,options){let{emit,signal,recordWitness,local:local2}=options;if(local2===void 0)throw new Error("the prepared pipeline runs only in the loop's own process");if(recordWitness)for(let raw of call.calls){let pending=recordWitness({pipeline:"prepared",toolCallId:raw.id});pending&&await pending}let batch=calls=>runPreparedBatch({source,openStore,calls,scope:call.scope,context:local2.context,assistantMessage:local2.assistantMessage,emit,...signal===void 0?{}:{signal}}),outcomes=[],messages=[],report=async finished2=>{for(let outcome2 of finished2){let message2=createToolResultMessage(outcome2);await emitToolResultMessage(message2,emit),outcomes.push(outcome2),messages.push(message2)}};if(call.mode==="sequential"){for(let raw of call.calls)if(await report(await batch([raw])),signal?.aborted)break}else await report(await batch(call.calls));return{messages,terminate:shouldTerminateToolBatch(outcomes)}}}}var BatchStoreMissingError=class extends Error{constructor(){super("agent loop: no batchStoreFactory configured for the prepared pipeline; pass one (or a toolHost)"),this.code="batch_store_missing",this.name="BatchStoreMissingError"}},PreflightCarryMissingError=class extends Error{constructor(){super("agent loop: no afterToolFreeze configured for the prepared pipeline; pass one (or a toolHost)"),this.code="preflight_carry_missing",this.name="PreflightCarryMissingError"}};function noPreflightCarry(_prepared,_frozen){}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 message2 of initialMessages)await emit({type:"message_start",message:message2}),await emit({type:"message_end",message:message2});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: 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,executionScope:initialConfig.executionScope??{id:crypto.randomUUID(),root:""}},firstTurn=!0,firstProviderRequest=!0,drainedTerminatingQueue,turnStartAlreadyEmitted=!1,explicitContinuation=!1,preparedMessages=[],pendingSource="steering",drainSteering=async()=>(pendingSource="steering",await config.getSteeringMessages?.()||[]),drainFollowUp=async()=>(pendingSource="followUp",await config.getFollowUpMessages?.()||[]),refreshTerminatingQueueDrain=async()=>{!drainedTerminatingQueue||!config.restorePendingMessages||(await config.restorePendingMessages(drainedTerminatingQueue,pendingMessages),pendingMessages=await drainSteering(),drainedTerminatingQueue=pendingMessages.length>0?"steering":void 0,pendingMessages.length===0&&(pendingMessages=await drainFollowUp(),drainedTerminatingQueue=pendingMessages.length>0?"followUp":void 0))},pendingMessages=await drainSteering();for(pendingMessages.length===0&&config.takeFollowUpsAtStart&&(pendingMessages=await drainFollowUp());;){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}if(pendingMessages.length>0&&config.commitQueuedConsumption)try{await config.commitQueuedConsumption(pendingSource,pendingMessages)}catch(error){throw await config.restorePendingMessages?.(pendingSource,pendingMessages),error}for(let message3 of declareToolChanges(currentContext,[...preparedMessages,...pendingMessages],config.model))await emit({type:"message_start",message:message3}),await emit({type:"message_end",message:message3}),currentContext.messages.push(message3),newMessages.push(message3);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),message2=streamed.message,providerToolResults=streamed.providerToolResults;newMessages.push(message2);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(config.commitStep&&await config.commitStep({message:message2,providerToolResults}),shouldTerminateAssistantTurn(message2)){await config.finishTurn?.({message:message2,toolResults,context:currentContext,newMessages},signal),await emit({type:"turn_end",message:message2,toolResults}),await emit({type:"agent_end",messages:newMessages});return}let toolCalls=message2.content.filter(c=>c.type==="toolCall"&&!isCursorExecResolved(c));hasMoreToolCalls=!1;let toolBatchTerminated=!1;if(toolCalls.length>0){let executedToolBatch=message2.stopReason==="length"?await failToolCallsFromTruncatedMessage(toolCalls,emit):await executeToolCalls(currentContext,message2,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:message2,toolResults,context:currentContext,newMessages},decision=await config.finishTurn?.(nextTurnContext,signal);if(await emit({type:"turn_end",message:message2,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 drainSteering(),pendingMessages.length>0&&(drainedTerminatingQueue="steering"),pendingMessages.length===0&&(pendingMessages=await drainFollowUp(),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 drainSteering()),(hasMoreToolCalls||pendingMessages.length>0)&&(explicitContinuation=!1)}let followUpMessages=await drainFollowUp();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((message2,index2)=>index2===systemIndex?withToolChanges(pending,NO_CHANGES):message2):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((message2,index2)=>index2===systemIndex?withToolChanges(pending,changes):message2);if(unchanged)return pendingMessages;let update=withToolChanges({role:"system",content:"",timestamp:Date.now()},changes),insertIndex=pendingMessages.findIndex(message2=>message2.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(message2,{toolsAdded,toolsRemoved}){let{toolsAdded:_added,toolsRemoved:_removed,...rest}=message2;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,...context.systemPromptStablePrefix===void 0?{}:{systemPromptStablePrefix:context.systemPromptStablePrefix},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,responseTiming=createResponseTimingRecorder();function stampTiming(finalMessage){responseTiming.stamp(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,liveness=createTransportLiveness(normalizeTimeoutMs(config.streamKeepAliveTimeoutMs)),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 preStream=createPreStreamBound(normalizeTimeoutMs(config.streamStartTimeoutMs),normalizeTimeoutMs(streamIdleTimeoutMs),requestAbortController),llmContext=await preStream.run(buildProviderContext(context,config,requestAbortController.signal)),resolvedApiKey=(config.getApiKey?await preStream.run(config.getApiKey(config.model.provider)):void 0)||config.apiKey;responseTiming.requested();let response=await preStream.run(streamFunction(config.model,llmContext,{...config,streamKind:"main",apiKey:resolvedApiKey,signal:requestAbortController.signal,onTransportActivity:()=>{liveness.noteActivity(),config.onTransportActivity?.()},...config.cursorExecHandlers?{execHandlers:typeof config.cursorExecHandlers=="function"?config.cursorExecHandlers(signal??requestAbortController.signal):config.cursorExecHandlers,onToolResult:result2=>{providerToolResults.push(result2)}}:{}}),late=>{typeof late?.[Symbol.asyncIterator]=="function"&&closeAssistantIterator(late[Symbol.asyncIterator]())}),result=async()=>Object.assign(await response.result(),{thinkingLevel:config.reasoning??"off"}),sink=config[internalProgressSink],iterator=(sink?assistantRecords(response):response)[Symbol.asyncIterator](),eventReader=createAssistantEventReader(iterator,streamIdleTimeoutMs,requestAbortController.signal,error=>requestAbortController.abort(error),preStream.remainingStartMs(),response,normalizeTimeoutMs(config.streamStartTimeoutMs),liveness);try{for(;;){let next=await eventReader.next();if(next.done)break;let event=next.value;if(isAssistantProgress(event)){await sink?.(event);continue}switch(event.type){case"start":responseTiming.started(),partialMessage=event.partial,context.messages.push(partialMessage),addedPartial=!0,await emit(carryAssistantCapture(event,{type:"message_start",message:{...partialMessage},streaming:!0}));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){partialMessage=event.partial,responseTiming.observe(event);let timingProgress;if(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),getAssistantCapture(event)&&event.type!=="thinking_delta"&&(timingProgress=Object.freeze({type:"message_block_metadata",contentIndex:event.contentIndex,...timing})))}context.messages[context.messages.length-1]=partialMessage,await emit(carryAssistantCapture(event,{type:"message_update",assistantMessageEvent:event,message:{...partialMessage}})),timingProgress&&await sink?.(timingProgress)}break;case"done":case"error":{let finalMessage2=settleStopReason(normalizeTerminalAssistantMessage(await result(),event));return stampTiming(finalMessage2),addedPartial?context.messages[context.messages.length-1]=finalMessage2:context.messages.push(finalMessage2),addedPartial||await emit(carryAssistantCapture(event,{type:"message_start",message:{...finalMessage2}},finalMessage2)),await emit(carryAssistantCapture(event,{type:"message_end",message:finalMessage2},finalMessage2)),{message:finalMessage2,providerToolResults}}}}}finally{eventReader.dispose()}let finalMessage=settleStopReason(await result());return stampTiming(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=settleStopReason({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 stampTiming(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 callerAbortedPastBound=signal?.aborted===!0&&(error instanceof StreamStartTimeoutError||error instanceof StreamKeepAliveTimeoutError||isStreamIdleTimeoutError(error)||error===signal.reason),finalMessage=createTerminalFailureAssistantMessage(config.model,signal?.aborted?"aborted":"error",callerAbortedPastBound?abortError(signal.reason):error,partialMessage);return stampTiming(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 ABORTED2=Symbol("aborted"),MAX_ABORT_REASON_CHARS=500;function abortError(reason){if(reason instanceof Error)return reason;let text=abortReasonText(reason);if(text===void 0)return new Error("Request was aborted");let characters=Array.from(text);return new Error(characters.length>MAX_ABORT_REASON_CHARS?`${characters.slice(0,MAX_ABORT_REASON_CHARS).join("")}\u2026`:text)}function abortReasonText(reason){let text=typeof reason=="string"?reason:typeof reason=="object"&&reason!==null&&"message"in reason&&typeof reason.message=="string"?reason.message:void 0;return text!==void 0&&text.trim()!==""?text:void 0}function closeAssistantIterator(iterator){Promise.resolve(iterator.return?.()).catch(()=>{})}function createPreStreamBound(startTimeoutMs,idleTimeoutMs,request){let startedAt=Date.now(),remaining=()=>startTimeoutMs===void 0?idleTimeoutMs:Math.max(0,startTimeoutMs-(Date.now()-startedAt)),timeoutError=()=>startTimeoutMs===void 0?new StreamIdleTimeoutError(idleTimeoutMs??0):new StreamStartTimeoutError(startTimeoutMs);return{run(work,discardLate){let budget=remaining();return budget===void 0?Promise.resolve(work):new Promise((resolve,reject)=>{let timer,settled=!1,finish=complete=>{settled||(settled=!0,timer!==void 0&&clearTimeout(timer),complete())};Promise.resolve(work).then(value2=>{if(settled){try{discardLate?.(value2)}catch{}return}finish(()=>resolve(value2))},error=>finish(()=>reject(error))),timer=setTimeout(()=>{let error=timeoutError();finish(()=>reject(error)),request.abort(error)},budget)})},remainingStartMs:()=>startTimeoutMs===void 0?void 0:Math.max(1,remaining()??1)}}function normalizeTimeoutMs(timeoutMs){return typeof timeoutMs=="number"&&Number.isFinite(timeoutMs)&&timeoutMs>0?timeoutMs:void 0}function createAssistantEventReader(iterator,timeoutMs,signal,onIdleTimeout,streamStartTimeoutMs,stream,configuredStartTimeoutMs,liveness){let idleTimeoutMs=normalizeTimeoutMs(timeoutMs),startTimeoutMs=normalizeTimeoutMs(streamStartTimeoutMs),reportedStartTimeoutMs=configuredStartTimeoutMs??startTimeoutMs,sawFirstEvent=!1,silentMs=0,removeAbortListener,abortPromise;return signal!==void 0&&(signal.aborted?abortPromise=Promise.resolve(ABORTED2):abortPromise=new Promise(resolve=>{let abortHandler=()=>resolve(ABORTED2);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,readTimeoutMs=useStartBound?startTimeoutMs:idleTimeoutMs,makeTimeoutError=useStartBound?ms=>new StreamStartTimeoutError(reportedStartTimeoutMs??ms):ms=>new StreamIdleTimeoutError(idleTimeoutMs??ms),readStartedAt=Date.now(),windowMs=useStartBound?reportedStartTimeoutMs??startTimeoutMs:idleTimeoutMs,result=await readNextAssistantEvent(iterator,readTimeoutMs===void 0?void 0:Math.max(1,readTimeoutMs-silentMs),makeTimeoutError,abortPromise,onIdleTimeout,stream,signal,liveness&&windowMs!==void 0?{liveness,windowMs}:void 0);return!result.done&&isAssistantProgress(result.value)?silentMs+=Date.now()-readStartedAt:(silentMs=0,result.done||(sawFirstEvent=!0,liveness?.contentArrived())),result},dispose:()=>removeAbortListener?.()}}async function readNextAssistantEvent(iterator,idleTimeoutMs,makeTimeoutError,abortPromise,onIdleTimeout,stream,signal,keepAlive){if(idleTimeoutMs===void 0&&abortPromise===void 0)return iterator.next();let timeout,settled=!1;return new Promise((resolve,reject)=>{let settle2=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 verdict=keepAlive?.liveness.onSilenceDeadline(keepAlive.windowMs);if(verdict?.kind==="extend"){timeout=setTimeout(onIdleDeadline,verdict.delayMs);return}let error=verdict?.kind==="keep-alive-exhausted"?verdict.error:makeTimeoutError(idleTimeoutMs);closeAssistantIterator(iterator),settle2(()=>reject(error)),onIdleTimeout?.(error)};timeout=setTimeout(onIdleDeadline,idleTimeoutMs)}(abortPromise?Promise.race([iterator.next(),abortPromise]):iterator.next()).then(result=>{if(result===ABORTED2){closeAssistantIterator(iterator),settle2(()=>reject(abortError(signal?.reason)));return}settle2(()=>resolve(result))},error=>settle2(()=>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.toolHost??defaultToolHost()).execute({scope:config.executionScope??{id:crypto.randomUUID(),root:""},calls:toolCalls,mode:config.toolExecution??"parallel"},{signal,emit,recordWitness:config.onExecutionPipeline,local:{context:currentContext,assistantMessage}});function defaultToolHost(){if(config.batchStoreFactory===void 0)throw new BatchStoreMissingError;let afterToolFreeze=config.afterToolFreeze;if(afterToolFreeze===void 0)throw new PreflightCarryMissingError;return createPreparedToolHost({...config,afterToolFreeze},config.batchStoreFactory)}}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,outcome2=await prepareResolvedToolCall(currentContext,assistantMessage,{...toolCall,name:tool.name},tool,config,signal);return outcome2.kind==="prepared"?{...outcome2,requestedName}:{...outcome2,result:withToolNameCorrection(outcome2.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(ABORTED2):new Promise(resolve=>{signal.addEventListener("abort",()=>resolve(ABORTED2),{once:!0})})}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===ABORTED2?(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}}var localFailures=new WeakSet;function isLocalFailure(error){return typeof error=="object"&&error!==null&&localFailures.has(error)}async function local(work){try{return await work()}catch(error){throw typeof error=="object"&&error!==null&&localFailures.add(error),error}}function localFailurePort(port){return{claim:(queue,drain)=>local(()=>port.claim(queue,drain)),release:(queue,messages,giveBack)=>local(()=>port.release(queue,messages,giveBack)),commitConsumption:(queue,messages)=>local(()=>port.commitConsumption(queue,messages))}}function defaultConvertToLlm(messages){return messages.filter(message2=>message2.role==="system"||message2.role==="user"||message2.role==="assistant"||message2.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??"",systemPromptStablePrefix:initialState?.systemPromptStablePrefix,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(message2){return!LLM_ROLES.has(message2.role)}var PendingMessageQueue=class{constructor(mode){this.messages=[],this.clearGeneration=0,this.mode=mode}enqueue(message2){this.messages.push(message2)}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)}all(){return this.messages.slice()}drain(){let drained=this.peek();return this.messages=this.messages.slice(drained.length),drained}prepend(messages){this.messages=[...messages,...this.messages]}remove(message2){let index=this.messages.indexOf(message2);return index===-1?!1:(this.messages.splice(index,1),!0)}replace(message2,next){let index=this.messages.indexOf(message2);return index===-1?!1:(this.messages[index]=next,!0)}clear(){this.messages=[],this.clearGeneration++}},Agent=class{#internalChannel;async buildProviderContext(context,signal){return buildProviderContext(context,{convertToLlm:this.convertToLlm,transformContext:this.transformContext,model:this._state.model},signal)}constructor(options){this.listeners=new Set,this.followUpsParked=!1;let runtimeOptions=options??{};this.#internalChannel=runtimeOptions.internalChannel,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.queuedInputPort=runtimeOptions.queuedInputPort,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.streamKeepAliveTimeoutMs=runtimeOptions.streamKeepAliveTimeoutMs,this.maxRetryDelayMs=runtimeOptions.maxRetryDelayMs,this.toolExecution=runtimeOptions.toolExecution??"parallel",this.toolHost=runtimeOptions.toolHost,this.batchStoreFactory=runtimeOptions.batchStoreFactory,this.afterToolFreeze=runtimeOptions.afterToolFreeze,this.executionScope=runtimeOptions.executionScope??{id:crypto.randomUUID(),root:""},this.commitStep=runtimeOptions.commitStep,this.onExecutionPipeline=runtimeOptions.onExecutionPipeline,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(message2){this.steeringQueue.enqueue(message2)}followUp(message2){this.followUpQueue.enqueue(message2)}removeQueuedMessage(message2){return this.steeringQueue.remove(message2)||this.followUpQueue.remove(message2)}replaceQueuedMessage(message2,next){return this.steeringQueue.replace(message2,next)||this.followUpQueue.replace(message2,next)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}peekQueuedMessages(options){if(options?.all)return[...this.steeringQueue.all(),...this.followUpQueue.all()];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}if(this.steeringQueue.hasItems()){await this.runQueuedMessages("steering",{skipInitialSteeringPoll:!0,initialRequestTimeoutMs:options.timeoutMs,initialRequestStreamStartTimeoutMs:options.streamStartTimeoutMs});return}if(this.followUpQueue.hasItems()){await this.runQueuedMessages("followUp",{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(message2=>message2.role==="system"))throw new Error("No messages to continue from");if(lastMessage.role==="assistant"){if(this.steeringQueue.hasItems()){await this.runQueuedMessages("steering",{skipInitialSteeringPoll:!0,initialRequestTimeoutMs:options.timeoutMs,initialRequestStreamStartTimeoutMs:options.streamStartTimeoutMs});return}if(this.followUpQueue.hasItems()){await this.runQueuedMessages("followUp",{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 content2=[{type:"text",text:input}];return images&&images.length>0&&content2.push(...images),[{role:"user",content:content2,timestamp:Date.now()}]}async runPromptMessages(messages,options={}){await this.runWithLifecycle(async signal=>{await runAgentLoop(messages,this.createContextSnapshot(),this.createLoopConfig({...options,takeParkedFollowUps:!0}),event=>this.processEvents(event),signal,this.streamFunction)})}async runQueuedMessages(queue,options){let pendingQueue=queue==="steering"?this.steeringQueue:this.followUpQueue,port=this.queuedInputPort;if(this.followUpsParked=!1,!port){await this.runPromptMessages(pendingQueue.drain(),options);return}await this.runWithLifecycle(async signal=>{let messages=await this.takeQueuedMessages(queue);messages.length!==0&&await runAgentLoop(messages,this.createContextSnapshot(),this.createLoopConfig(options),event=>this.processEvents(event),signal,this.streamFunction)})}async takeQueuedMessages(queue){let pendingQueue=queue==="steering"?this.steeringQueue:this.followUpQueue,port=this.queuedInputPort&&localFailurePort(this.queuedInputPort);if(!port)return pendingQueue.drain();let generation=pendingQueue.getClearGeneration(),messages=await port.claim(queue,()=>(generation=pendingQueue.getClearGeneration(),pendingQueue.drain()));if(messages.length===0)return messages;try{await port.commitConsumption(queue,messages)}catch(error){throw await port.release(queue,messages,this.giveBack(queue,messages,generation)),error}return messages}giveBack(queue,messages,generation){let pendingQueue=queue==="steering"?this.steeringQueue:this.followUpQueue,restorable=()=>pendingQueue.getClearGeneration()===generation;return{restorable,restore:()=>restorable()?(pendingQueue.prepend(messages),!0):!1}}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,...this._state.systemPromptStablePrefix===void 0?{}:{systemPromptStablePrefix:this._state.systemPromptStablePrefix},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,takeFollowUpsAtStart=options.takeParkedFollowUps===!0&&this.followUpsParked;takeFollowUpsAtStart&&(this.followUpsParked=!1);let steeringQueueGeneration=this.steeringQueue.getClearGeneration(),followUpQueueGeneration=this.followUpQueue.getClearGeneration(),finishTurn=this.finishTurn,queuedInputPort=this.queuedInputPort&&localFailurePort(this.queuedInputPort),giveBack=(queue,messages)=>this.giveBack(queue,messages,queue==="steering"?steeringQueueGeneration:followUpQueueGeneration),reasoning=this._state.reasoningBaseline??this._state.thinkingLevel;return{...internalLoopSink(this.#internalChannel),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,streamKeepAliveTimeoutMs:this.streamKeepAliveTimeoutMs,initialRequestTimeoutMs:options.initialRequestTimeoutMs,initialRequestStreamStartTimeoutMs:options.initialRequestStreamStartTimeoutMs,maxRetryDelayMs:this.maxRetryDelayMs,abortServerSideFallback:this.abortServerSideFallback,cursorExecHandlers:this.cursorExecHandlers,toolExecution:this.toolExecution,toolHost:this.toolHost,batchStoreFactory:this.batchStoreFactory,afterToolFreeze:this.afterToolFreeze,executionScope:this.getExecutionScope?.()??this.executionScope,...this.commitStep?{commitStep:this.commitStep}:{},onExecutionPipeline:this.onExecutionPipeline,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()=>{if(skipInitialSteeringPoll)return skipInitialSteeringPoll=!1,[];let drain=()=>(steeringQueueGeneration=this.steeringQueue.getClearGeneration(),this.steeringQueue.drain());return queuedInputPort?queuedInputPort.claim("steering",drain):drain()},takeFollowUpsAtStart,getFollowUpMessages:async()=>{let drain=()=>(followUpQueueGeneration=this.followUpQueue.getClearGeneration(),this.followUpQueue.drain());return queuedInputPort?queuedInputPort.claim("followUp",drain):drain()},commitQueuedConsumption:queuedInputPort?(queue,messages)=>queuedInputPort.commitConsumption(queue,messages):void 0,restorePendingMessages:async(queue,messages)=>{queuedInputPort?await queuedInputPort.release(queue,messages,giveBack(queue,messages)):giveBack(queue,messages).restore()}}}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);this.followUpsParked=!abortController.signal.aborted&&this.followUpQueue.hasItems()&&this.lastAssistantStopReason()==="error"}catch(error){await this.handleRunFailure(error,abortController.signal.aborted)}finally{this.finishRun()}}lastAssistantStopReason(){let lastMessage=this._state.messages.at(-1);return lastMessage?.role==="assistant"?lastMessage.stopReason:void 0}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.hasItems()?await this.takeQueuedMessages("steering"):[];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.hasItems()?await this.takeQueuedMessages("followUp"):[];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"}:{},...!aborted&&isLocalFailure(error)?{failureSource:"local"}:{},timestamp:Date.now()};sanitizeProviderErrorMessage(failureMessage),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");let internal=dispatchInternalAgent(this.#internalChannel,{event});internal&&await internal;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 HOSTED_REBUILD_DEADLINE_MS=5e3,EPOCH_FRESHNESS_MS=5e3,MOVE_SKEW_MS=2e3;var STEP_COMMIT_BRAND=Symbol.for("senpi.StepCommitError"),StepCommitError=class extends Error{constructor(stepId,code,options){super(`step commit failed: ${code}`,options),this.name="StepCommitError",this.stepId=stepId,this.code=code,Object.defineProperty(this,STEP_COMMIT_BRAND,{value:!0,enumerable:!1,writable:!1})}};function isStepCommitError(value2){return typeof value2=="object"&&value2!==null&&Reflect.get(value2,STEP_COMMIT_BRAND)===!0}var DurableStoreError=class extends Error{constructor(code,message2){super(message2),this.name="DurableStoreError",this.code=code}};function createMemoryStoreMedium(){return{current:{epoch:0,records:[],documents:new Map}}}var copy=value2=>structuredClone(value2),copyRecord=record2=>({...record2,data:copy(record2.data)}),isList=value2=>Array.isArray(value2);function sameValue(a,b){if(a===void 0||b===void 0||a===null||b===null||typeof a!="object"||typeof b!="object")return a===b;if(isList(a)||isList(b))return isList(a)&&isList(b)&&a.length===b.length&&a.every((item,index)=>sameValue(item,b[index]));let keys=Object.keys(a);return keys.length===Object.keys(b).length&&keys.every(key=>Object.hasOwn(b,key)&&sameValue(a[key],b[key]))}var sameRecord=(a,b)=>b!==void 0&&a.seq===b.seq&&a.id===b.id&&a.kind===b.kind&&sameValue(a.data,b.data);function requireOwner(state,epoch){if(state.epoch===0)throw new DurableStoreError("unclaimed","the store has no owner; claim it first");if(epoch!==state.epoch)throw new DurableStoreError("stale-epoch",`epoch ${epoch} is not the owner epoch ${state.epoch}`)}function importedTail(state,snapshot){let ids=new Set,wellFormed=snapshot.head===snapshot.records.length&&snapshot.records.every((record2,index)=>record2.seq===index+1&&!ids.has(record2.id)&&ids.add(record2.id)),extendsLog=state.records.length<=snapshot.records.length&&state.records.every((record2,index)=>sameRecord(record2,snapshot.records[index]));if(!wellFormed||!extendsLog)throw new DurableStoreError("import-conflict","the snapshot's log does not extend this store's log");return snapshot.records.slice(state.records.length)}function scan(records,query){let matching=records.filter(record2=>(query.fromSeq===void 0||record2.seq>=query.fromSeq)&&(query.toSeq===void 0||record2.seq<=query.toSeq)&&(query.kind===void 0||record2.kind===query.kind)),ordered=query.order==="desc"?matching.reverse():matching;return(query.limit===void 0?ordered:ordered.slice(0,query.limit)).map(copyRecord)}var documentsOf=(state,prefix)=>[...state.documents].filter(([key])=>key.startsWith(prefix)).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([key,data])=>({key,data:copy(data)}));function openMemoryStore(medium,options={}){let point=at=>options.onWritePoint?.(at),commitSync=(epoch,writes,adopt)=>{point({op:"commit",at:"before"});let state=medium.current;requireOwner(state,epoch);let records=[...state.records],ids=new Set(records.map(record2=>record2.id)),documents=new Map(state.documents),seqs=[];writes.forEach((write,index)=>{switch(point({op:"commit",at:"write",index}),write.op){case"append":{if(ids.has(write.id))throw new DurableStoreError("duplicate-record-id",`record ${write.id} exists`);ids.add(write.id);let seq=records.length+1;records.push({seq,id:write.id,kind:write.kind,data:copy(write.data)}),seqs.push(seq);break}case"put":documents.set(write.key,copy(write.data));break;case"delete":documents.delete(write.key);break}}),medium.current={epoch:state.epoch,records,documents},point({op:"commit",at:"durable"});let result={seqs,head:records.length};return adopt(result),result};return{readEpoch:async()=>medium.current.epoch,readHead:async()=>medium.current.records.length,async claim(expectedEpoch,nextEpoch){point({op:"claim",at:"before"});let state=medium.current;if(!Number.isSafeInteger(nextEpoch)||nextEpoch!==expectedEpoch+1)throw new DurableStoreError("invalid-claim",`a claim must raise the epoch to exactly ${expectedEpoch+1}`);if(state.epoch!==expectedEpoch)throw new DurableStoreError("stale-epoch",`expected epoch ${expectedEpoch}, the owner epoch is ${state.epoch}`);medium.current={...state,epoch:nextEpoch},point({op:"claim",at:"durable"})},commit:async(epoch,writes,adopt)=>commitSync(epoch,writes,adopt),commitSync,mintId:()=>crypto.randomUUID(),scanRecords:async(query={})=>scan(medium.current.records,query),getDocument:async key=>{let data=medium.current.documents.get(key);return data===void 0?void 0:copy(data)},scanDocuments:async prefix=>documentsOf(medium.current,prefix),exportSnapshot:async()=>{let state=medium.current;return{epoch:state.epoch,head:state.records.length,records:state.records.map(copyRecord),documents:documentsOf(state,"")}},async importSnapshot(epoch,snapshot){point({op:"import",at:"before"});let state=medium.current;if(requireOwner(state,epoch),epoch<=snapshot.epoch)throw new DurableStoreError("invalid-claim",`epoch ${epoch} is not above the source epoch ${snapshot.epoch}`);let records=[...state.records],documents=new Map,index=0;for(let record2 of importedTail(state,snapshot))point({op:"import",at:"write",index:index++}),records.push(copyRecord(record2));for(let document of snapshot.documents)point({op:"import",at:"write",index:index++}),documents.set(document.key,copy(document.data));medium.current={epoch:state.epoch,records,documents},point({op:"import",at:"durable"})}}}var openMemoryBatchStore=()=>openMemoryStore(createMemoryStoreMedium());function withBatchStore(config){return{...config,batchStoreFactory:config.batchStoreFactory??openMemoryBatchStore,afterToolFreeze:config.afterToolFreeze??noPreflightCarry}}var Agent2=class extends Agent{constructor(options){super(withBatchStore(options))}},agentLoop2=(prompts,context,config,signal,streamFn)=>agentLoop(prompts,context,withBatchStore(config),signal,streamFn),agentLoopContinue2=(context,config,signal,streamFn)=>agentLoopContinue(context,withBatchStore(config),signal,streamFn),runAgentLoop2=(prompts,context,config,emit,signal,streamFn)=>runAgentLoop(prompts,context,withBatchStore(config),emit,signal,streamFn),runAgentLoopContinue2=(context,config,emit,signal,streamFn)=>runAgentLoopContinue(context,withBatchStore(config),emit,signal,streamFn);function outcomeOf(entry2){let executionId=entry2.commandId;if(entry2.progress.state==="acked")return{kind:"refused",executionId,reason:"result_expired"};if(entry2.progress.state!=="settled")return;let{outcome:outcome2}=entry2.progress;if(outcome2.reason==="result"){let result=JSON.parse(String(outcome2.value));return{kind:"settled",executionId,result}}return outcome2.reason==="blocked"?{kind:"refused",executionId,reason:"foreign_outcome"}:{kind:"terminal",executionId,reason:outcome2.reason,uncertain:outcome2.uncertain,hooksRan:outcome2.hooksRan}}function asStoreValue(value2){return value2===void 0?null:JSON.parse(JSON.stringify(value2))}function createHandLedger(options){let{ledger,executor,issuer,workspace,now,leaseMs}=options,keyOf4=executionId=>({issuer,commandId:executionId}),apply=(executionId,event,actor,guard)=>ledger.apply({key:keyOf4(executionId),generation:1,actor:{id:actor},now:now(),event},guard),recovered,fencedBy=admits=>admits===void 0?void 0:()=>admits()?void 0:"epoch_fenced",owned=new Set,replyFrom=(reply,executionId)=>reply.status==="refused"?{kind:"refused",executionId,reason:reply.reason}:reply.status==="result_expired"?{kind:"refused",executionId,reason:"result_expired"}:outcomeOf(reply.entry)??{kind:"refused",executionId,reason:"not_settled"},admitNew=(invoke,digest,guard)=>{let admittedAt=now();return ledger.admit({issuer,commandId:invoke.executionId,executor,workspace,scope:invoke.scope.id,generation:1,requestDigest:digest,admittedAt,leaseUntil:admittedAt+leaseMs,reconcilable:!1},guard)},fenced=async executionId=>(await ledger.read(keyOf4(executionId))!==void 0&&await apply(executionId,{kind:"cancel"},issuer),{kind:"reply",message:{kind:"refused",executionId,reason:"epoch_fenced"}}),advance2=async(invoke,guard)=>{let{executionId}=invoke,isFenced=reply=>reply.status==="refused"&&reply.reason==="epoch_fenced",args=asStoreValue(invoke.arguments),frozen2={name:invoke.name,args,digest:JSON.stringify([invoke.name,args])},prior=await ledger.read(keyOf4(executionId));if(prior!==void 0&&(prior.requestDigest!==frozen2.digest||prior.scope!==invoke.scope.id))return{kind:"reply",message:{kind:"refused",executionId,reason:"identity_conflict"}};let settled=prior===void 0?void 0:outcomeOf(prior);if(settled!==void 0)return{kind:"reply",message:settled};let fromStart=[()=>admitNew(invoke,frozen2.digest,guard),()=>apply(executionId,{kind:"prepare"},executor,guard),()=>apply(executionId,{kind:"effect"},executor,guard),()=>apply(executionId,{kind:"freeze",call:frozen2,awaitingConsent:!1},executor,guard)],state=prior?.progress.state,steps=state===void 0?fromStart:state==="prepared"||state==="released"?[]:void 0;if(steps===void 0)return{kind:"in_flight"};for(let step of[...steps,()=>apply(executionId,{kind:"release"},issuer,guard)]){let reply=await step();if(isFenced(reply))return fenced(executionId);if(!(reply.status==="replayed"&&reply.entry.progress.state!=="settled")&&(reply.status!=="applied"||reply.entry.progress.state==="settled"))return{kind:"reply",message:replyFrom(reply,executionId)}}let dispatched=await apply(executionId,{kind:"dispatch"},executor,guard);return isFenced(dispatched)?fenced(executionId):dispatched.status==="applied"&&dispatched.entry.progress.state==="dispatched"?{kind:"run"}:dispatched.status==="replayed"&&dispatched.entry.progress.state!=="settled"?{kind:"in_flight"}:{kind:"reply",message:replyFrom(dispatched,executionId)}};return{async admit(invoke,admits){let{executionId}=invoke;if(owned.has(executionId))return{kind:"in_flight"};owned.add(executionId);let admission=await advance2(invoke,fencedBy(admits)).catch(error=>{throw owned.delete(executionId),error});return admission.kind!=="run"&&owned.delete(executionId),admission},async settle(invoke,result){try{let reply=await apply(invoke.executionId,{kind:"result",value:JSON.stringify(result)},executor);return replyFrom(reply,invoke.executionId)}finally{owned.delete(invoke.executionId)}},async ack(executionId,admits){await apply(executionId,{kind:"ack"},issuer,fencedBy(admits))},async recover(){return recovered!==void 0?recovered.then(()=>[]):(recovered=ledger.recover(now()),await recovered,(await ledger.scan()).flatMap(entry2=>{let message2=entry2.progress.state==="settled"?outcomeOf(entry2):void 0;return message2===void 0?[]:[{lane:entry2.scope,message:message2}]}))}}}var SessionStoreError=class extends Error{constructor(code,message2){super(message2),this.name="SessionStoreError",this.code=code}},SESSION="session-import/session/",DIVERGENCE="session-import/divergence/",sessionManifestKey=id=>SESSION+encodeURIComponent(id),divergenceKey=id=>DIVERGENCE+encodeURIComponent(id),sessionRecordKind=id=>`session/${encodeURIComponent(id)}`,isRecord7=value2=>typeof value2=="object"&&value2!==null&&!Array.isArray(value2);function readEntry(id,value2){if(isRecord7(value2)&&typeof value2.key=="string"&&typeof value2.line=="string")return{key:value2.key,line:value2.line};throw new SessionStoreError("corrupt-session",`session ${id} holds an unreadable entry record`)}async function readSessionState(store,id){let manifest2=await store.getDocument(sessionManifestKey(id));if(manifest2===void 0)return;if(!isRecord7(manifest2)||!isRecord7(manifest2.header))throw new SessionStoreError("corrupt-session",`session ${id} has no readable manifest`);if("entryIds"in manifest2)throw new SessionStoreError("corrupt-session",`session ${id} is stored in the layout before the record log; re-import it from its JSONL file`);let header=manifest2.header,entries=[],held=new Set,rewrites=0;for(let record2 of await store.scanRecords({kind:sessionRecordKind(id),order:"asc"})){let data=record2.data;if(isRecord7(data)&&data.op==="rewrite"&&isRecord7(data.header)&&Array.isArray(data.entries))header=data.header,entries=data.entries.map(entry2=>readEntry(id,entry2)),held=new Set(entries.map(entry2=>entry2.key)),rewrites++;else if(isRecord7(data)&&data.op==="append"){let entry2=readEntry(id,data);if(held.has(entry2.key))continue;held.add(entry2.key),entries.push(entry2)}else throw new SessionStoreError("corrupt-session",`session ${id} holds an unreadable record ${record2.seq}`)}let divergence=await store.getDocument(divergenceKey(id))??null;return{id,header,entries,divergence,rewrites}}var manifestWrite=(id,header)=>({op:"put",key:sessionManifestKey(id),data:{id,header}}),divergenceWrite=(id,divergence)=>({op:"put",key:divergenceKey(id),data:divergence}),appendRecordWrites=(id,rewrites,added)=>added.map(entry2=>({op:"append",id:`${sessionRecordKind(id)}/${rewrites}/${encodeURIComponent(entry2.key)}`,kind:sessionRecordKind(id),data:{op:"append",key:entry2.key,line:entry2.line}})),rewriteRecordWrite=(store,id,header,entries)=>({op:"append",id:store.mintId(),kind:sessionRecordKind(id),data:{op:"rewrite",header,entries:entries.map(entry2=>({key:entry2.key,line:entry2.line}))}});function refuseRepeats(id,entries,held,what){let seen=new Set(held);for(let entry2 of entries){if(seen.has(entry2.key))throw new SessionStoreError("duplicate-entry",`${what} ${id} repeats ${entry2.key}`);seen.add(entry2.key)}}function planAppend(state,held,added){refuseRepeats(state.id,added,state.entries.map(entry2=>entry2.key),"session");let next={...state,entries:[...state.entries,...added]};return{writes:[...held?[]:[manifestWrite(state.id,state.header)],...appendRecordWrites(state.id,state.rewrites,added)],next}}function planRewrite(store,state,held,header,entries){refuseRepeats(state.id,entries,[],"rewrite of");let next={...state,header,entries:[...entries],rewrites:state.rewrites+1};return{writes:[...held?[]:[manifestWrite(state.id,header)],rewriteRecordWrite(store,state.id,header,entries)],next}}function asDuplicateEntry(id,error){return error instanceof DurableStoreError&&error.code==="duplicate-record-id"?new SessionStoreError("duplicate-entry",`session ${id} already holds an entry this write repeats`):error}var stored=({id,header,entries})=>({id,header,entries});async function openState(store,id,header){let read=await readSessionState(store,id);return read===void 0?{state:{id,header,entries:[],divergence:null,rewrites:0},held:!1}:{state:read,held:!0}}function openSessionStore(store,epoch){return{load:async id=>{let state=await readSessionState(store,id);return state===void 0?void 0:stored(state)},open:async(id,header)=>{let{state,held}=await openState(store,id,header),tail=Promise.resolve(),enqueue=plan=>{let run=tail.then(async()=>{let next=plan();await store.commit(epoch,next.writes,()=>{}).catch(error=>{throw asDuplicateEntry(id,error)}),state=next.next,held=!0});return tail=run.catch(()=>{}),run};return{header:()=>state.header,entries:()=>state.entries,append:entries=>enqueue(()=>planAppend(state,held,entries)),rewrite:(header2,entries)=>enqueue(()=>planRewrite(store,state,held,header2,entries))}}}}function openSyncSessionStore(store,epoch){return{load:openSessionStore(store,epoch).load,open:async(id,header)=>{let{state,held}=await openState(store,id,header),commit=plan=>{try{store.commitSync(epoch,plan.writes,()=>{})}catch(error){throw asDuplicateEntry(id,error)}state=plan.next,held=!0};return{header:()=>state.header,entries:()=>state.entries,appendSync:entries=>commit(planAppend(state,held,entries)),rewriteSync:(header2,entries)=>commit(planRewrite(store,state,held,header2,entries))}}}}var HELLO_WAIT_MS=5e3,GRANT_REFUSALS=new Set(["grant_missing","grant_expired","workspace_unknown","capability_missing"]);function refusalError(reason){return GRANT_REFUSALS.has(reason)?new DeviceFileError("refused_by_grant",reason):reason==="epoch_fenced"?new DeviceFileError("refused_by_policy",reason):reason==="hand_closed"||reason.startsWith("scope_unavailable")?new DeviceFileError("hand_unreachable",reason):new DeviceFileError("protocol",reason)}function valueOf(reply){switch(reply.kind){case"settled":{let outcome2=fileOutcomeOf(reply.result.details);if(outcome2===void 0)throw new DeviceFileError("protocol","the hand sent no file outcome");if(!outcome2.ok)throw new DeviceFileError(outcome2.code,outcome2.message);return outcome2.value}case"terminal":{let{reason,uncertain}=reply.terminal;throw new DeviceFileError("interrupted",`the operation ended without an outcome (${reason})`,{reason,uncertain})}case"refused":throw refusalError(reply.reason);case"aborted":throw new DeviceFileError("aborted","the operation was aborted");case"unreachable":throw new DeviceFileError("hand_unreachable",reply.reason);case"closed":throw reply.sent?new DeviceFileError("interrupted","the hand link closed before the operation settled (hand_restarted)",{reason:"hand_restarted",uncertain:!0}):new DeviceFileError("hand_unreachable","the hand link was closed");case"epoch_refused":throw new DeviceFileError("refused_by_policy",`epoch: ${reply.reason}`)}}function createRemoteDeviceFiles(link,scope,mintId){let call=async(op,args,signal,channel=FILE_CHANNEL)=>{let hello=await link.hello(HELLO_WAIT_MS,signal);if(signal?.aborted)throw new DeviceFileError("aborted","the operation was aborted");if(hello===void 0||!hello.ops.includes(channel))throw new DeviceFileError("unsupported",`the hand serves no ${channel} channel`);return valueOf(await link.dispatch({kind:"file",executionId:mintId(),scope,op,args},signal))};return{read:async(path,options)=>{let value2=await call("read",{path},options?.signal);if(typeof value2!="string")throw new DeviceFileError("protocol","malformed read outcome");return decodeBase64(value2)},write:async(path,data,options)=>{if(data.byteLength>FILE_CHANNEL_MAX_BYTES)throw new DeviceFileError("too_large",path);let exclusive=options?.exclusive===!0;await call("write",{path,data:encodeBase64(data),exclusive},options?.signal)},list:async(path,options)=>{let value2=await call("list",{path},options?.signal);if(!Array.isArray(value2)||!value2.every(entry2=>typeof entry2=="string"))throw new DeviceFileError("protocol","malformed list outcome");return value2},stat:async(path,options)=>await call("stat",{path},options?.signal),rename:async(from,to,options)=>{await call("rename",{path:from,to},options?.signal)},remove:async(path,options)=>{await call("remove",{path},options?.signal)},mkdir:async(path,options)=>{await call("mkdir",{path},options?.signal)},run:async(request,options)=>{if(request.stdin!==void 0&&request.stdin.byteLength>FILE_CHANNEL_MAX_BYTES)throw new DeviceFileError("too_large","stdin");let args={path:request.cwd,exe:request.exe,argv:[...request.argv],env:{...request.env},...request.stdin===void 0?{}:{stdin:encodeBase64(request.stdin)},...request.timeoutMs===void 0?{}:{timeoutMs:request.timeoutMs},activityLock:request.activityLock===!0},value2=await call("run",args,options?.signal,RUN_CHANNEL);if(typeof value2!="object"||value2===null||Array.isArray(value2))throw new DeviceFileError("protocol","malformed run outcome");let{code,signal,stdout,stderr}=value2;if(typeof stdout!="string"||typeof stderr!="string")throw new DeviceFileError("protocol","malformed run outcome");return{code:typeof code=="number"?code:null,signal:typeof signal=="string"?signal:null,stdout:decodeBase64(stdout),stderr}}}}var MODEL_PLANE="model",REASONING=["minimal","low","medium","high","xhigh","max"],isRecord8=value2=>typeof value2=="object"&&value2!==null;function refuse(detail){throw new PlaneRefusedError(`malformed_request: ${detail}`)}function decodeModel(value2){if(value2!==void 0)return(!isRecord8(value2)||typeof value2.provider!="string"||typeof value2.id!="string")&&refuse("model"),{provider:value2.provider,id:value2.id}}function decodeContext(value2){return(!isRecord8(value2)||!Array.isArray(value2.messages))&&refuse("context"),value2.systemPrompt!==void 0&&typeof value2.systemPrompt!="string"&&refuse("systemPrompt"),value2.tools!==void 0&&!Array.isArray(value2.tools)&&refuse("tools"),{...value2.systemPrompt===void 0?{}:{systemPrompt:value2.systemPrompt},messages:value2.messages,...value2.tools===void 0?{}:{tools:value2.tools}}}function decodeOptions(value2){if(value2===void 0)return;isRecord8(value2)||refuse("options");let{maxTokens,temperature,reasoning}=value2;return maxTokens!==void 0&&(typeof maxTokens!="number"||!Number.isSafeInteger(maxTokens)||maxTokens<=0)&&refuse("maxTokens"),temperature!==void 0&&(typeof temperature!="number"||!Number.isFinite(temperature))&&refuse("temperature"),reasoning!==void 0&&!REASONING.includes(reasoning)&&refuse("reasoning"),{...maxTokens===void 0?{}:{maxTokens},...temperature===void 0?{}:{temperature},...reasoning===void 0?{}:{reasoning}}}function decodeModelPlaneRequest(body){isRecord8(body)||refuse("body");let model=decodeModel(body.model),options=decodeOptions(body.options);return{...model===void 0?{}:{model},context:decodeContext(body.context),...options===void 0?{}:{options}}}function serveModelPlane(complete){return async(body,signal)=>{let message2=await complete(decodeModelPlaneRequest(body),signal);return JSON.parse(JSON.stringify(message2))}}function createModelPlaneClient(nested){return{async complete(request,signal){let reply=await nested(MODEL_PLANE,JSON.parse(JSON.stringify(request)),signal);if(!isRecord8(reply)||reply.role!=="assistant"||!Array.isArray(reply.content))throw new PlaneRefusedError("malformed_reply");return reply}}}var SESSION_PLANE="session",isRecord9=value2=>typeof value2=="object"&&value2!==null&&!Array.isArray(value2);function decodeSessionPlaneRequest(body){if(!isRecord9(body)||typeof body.tool!="string"||body.tool.length===0)throw new PlaneRefusedError("malformed_request: tool");if(!isRecord9(body.arguments))throw new PlaneRefusedError("malformed_request: arguments");return{tool:body.tool,arguments:body.arguments}}function loopSideToolNames(tools){let names=new Set;for(let tool of tools)tool.runs==="brain"&&names.add(tool.name);return names}function serveSessionPlane(options){return async(body,signal)=>{let request=decodeSessionPlaneRequest(body);if(!options.loopSide.has(request.tool))throw new Error(`not_loop_side: ${request.tool}`);let result=await options.run(request,signal);return JSON.parse(JSON.stringify(result))}}function createSessionPlaneClient(nested){return{async call(request,signal){let reply=await nested(SESSION_PLANE,JSON.parse(JSON.stringify(request)),signal);if(!isRecord9(reply)||!Array.isArray(reply.content))throw new PlaneRefusedError("malformed_reply");return reply}}}function createLoopToolHost(agent){return{execute(call,options){let{batchStoreFactory,afterToolFreeze}=agent;if(batchStoreFactory===void 0)throw new BatchStoreMissingError;if(afterToolFreeze===void 0)throw new PreflightCarryMissingError;return createPreparedToolHost({...pick(agent),afterToolFreeze},batchStoreFactory).execute(call,options)}}}function pick(agent){return{resolveUnknownToolCall:agent.resolveUnknownToolCall,beforeToolCall:agent.beforeToolCall,afterToolCall:agent.afterToolCall,removedToolHints:agent.removedToolHints}}function stagesOf(calls,sideOf,isSequential2,parallel){let stages=[],segments=[],owner=[],open=!1;for(let call of calls){let side=sideOf(call),barrier=parallel&&isSequential2(call),stage=stages.at(-1);open&&!barrier&&stage!==void 0&&(parallel||stage[0]?.side===side)||stages.push([]);let current=stages.at(-1)??[],segment=current.find(entry2=>entry2.side===side);segment===void 0&&(segment={side,calls:[]},current.push(segment),segments.push(segment)),segment.calls.push(call),owner.push(segments.indexOf(segment)),open=!barrier}return{stages,segments,owner}}function queueBy(items,idOf){let queues=new Map;for(let item of items){let queue=queues.get(idOf(item))??[];queue.push(item),queues.set(idOf(item),queue)}return queues}function holdingResults(emit,held){return event=>{if(event.type!=="message_start"&&event.type!=="message_end"||event.message.role!=="toolResult")return emit(event);let{toolCallId}=event.message,open=event.type==="message_end"?held.findLast(entry2=>entry2.toolCallId===toolCallId):void 0;open!==void 0&&open.events.at(-1)?.type==="message_start"?open.events.push(event):held.push({toolCallId,events:[event]})}}function createSplitToolHost(options){let sideOf=call=>options.loopSide(call.name)?"loop":"hand",isSequential2=call=>options.isSequential(call.name),hostOf=side=>side==="loop"?options.loop:options.hand;return{async execute(call,hostOptions){let parallel=call.mode==="parallel",{stages,segments,owner}=stagesOf(call.calls,sideOf,isSequential2,parallel),[only]=segments;if(segments.every(segment=>segment.side===only?.side))return hostOf(only?.side??"hand").execute(call,hostOptions);let held=segments.map(()=>[]),run=async segment=>{let index=segments.indexOf(segment);results[index]=await hostOf(segment.side).execute({...call,calls:segment.calls},parallel?{...hostOptions,emit:holdingResults(hostOptions.emit,held[index]??[])}:hostOptions)},results=segments.map(()=>{});for(let stage of stages)if(await Promise.all(stage.map(run)),hostOptions.signal?.aborted)break;let messages=results.map(result=>queueBy(result?.messages??[],message2=>message2.toolCallId)),events=held.map(entries=>queueBy(entries,entry2=>entry2.toolCallId)),ordered=[];for(let[index,raw]of call.calls.entries()){let segment=owner[index]??-1;for(let event of events[segment]?.get(raw.id)?.shift()?.events??[])await hostOptions.emit(event);let message2=messages[segment]?.get(raw.id)?.shift();message2!==void 0&&ordered.push(message2)}let ran=results.filter(result=>(result?.messages.length??0)>0);return{messages:ordered,terminate:ran.length>0&&ran.every(result=>result.terminate)}}}}var CHAIN_COUNT_LIMIT="chain_count_limit",CHAIN_ORIGIN=0,ChainCountLimitError=class extends Error{constructor(count,limit){super(`This thread call would be hop ${count} of its chain; your thread chain count limit is ${limit}.`),this.reason=CHAIN_COUNT_LIMIT,this.name="ChainCountLimitError",this.count=count,this.limit=limit}},isCount=value2=>typeof value2=="number"&&Number.isSafeInteger(value2)&&value2>=0;function nextChainCount(sessionCount){if(!isCount(sessionCount))throw new TypeError(`not a chain count: ${String(sessionCount)}`);return sessionCount+1}function decodeChainCount(value2){if(value2===void 0)return nextChainCount(0);if(!isCount(value2)||value2===0)throw new TypeError(`malformed chain count: ${JSON.stringify(value2)}`);return value2}function admitChainCall(count,readLimit){let limit=readLimit();if(limit!==void 0&&count>limit)throw new ChainCountLimitError(count,limit);return count}var LoopHookFailedError=class extends Error{constructor(message2){super(message2),this.name="LoopHookFailedError"}},LoopHookRestartedError=class extends Error{constructor(event){super(`The user's machine restarted while it ran the ${event} hooks; they were not run again and may have run.`),this.uncertain=!0,this.name="LoopHookRestartedError"}};function createLoopHookHost(options){let{transport,lane}=options,mintId=options.mintId??(()=>crypto.randomUUID()),pending=new Map,closed=!1,send=call=>{transport.send(lane,encodeLoopHookMessage(call)).catch(error=>{let reason=error instanceof Error?error.message:String(error);settle2(call.callId,waiter=>waiter.reject(new Error(`The link to the user's machine closed: ${reason}`)))})},settle2=(callId,finish)=>{let waiter=pending.get(callId);waiter!==void 0&&(pending.delete(callId),finish(waiter))};return transport.onFrame(frame=>{let message2=decodeLoopHookMessage(frame.payload);if(message2!==void 0)switch(message2.kind){case"hook.started":{let waiter=pending.get(message2.callId);waiter!==void 0&&(waiter.startedBy=message2.instance);return}case"hook.reply":return settle2(message2.callId,waiter=>waiter.resolve(message2.result));case"hook.failed":return settle2(message2.callId,waiter=>waiter.reject(new LoopHookFailedError(message2.error)));case"hook.hello":for(let waiter of[...pending.values()])waiter.startedBy===void 0?send(waiter.call):waiter.startedBy!==message2.instance&&settle2(waiter.call.callId,stale=>stale.reject(new LoopHookRestartedError(stale.call.event)));return;case"hook.call":return}}),{run(event,payload,signal){if(closed)return Promise.reject(new Error("The loop-hook link is closed"));if(signal?.aborted)return Promise.reject(new Error("Operation aborted"));let call={kind:"hook.call",callId:mintId(),event,payload},result=new Promise((resolve,reject)=>{pending.set(call.callId,{call,resolve,reject})}),onAbort=()=>settle2(call.callId,waiter=>waiter.reject(new Error("Operation aborted")));return signal?.addEventListener("abort",onAbort,{once:!0}),result.then(()=>signal?.removeEventListener("abort",onAbort),()=>signal?.removeEventListener("abort",onAbort)),send(call),result},waiting:()=>[...pending.keys()],close(){closed=!0;for(let callId of[...pending.keys()])settle2(callId,waiter=>waiter.reject(new Error("The loop-hook link was closed before the hooks ran")));transport.close()}}}var ONE_SHOT_MODES=new Set(["print","json"]),MalformedHandWakeError=class extends Error{constructor(eventId,what){super(`malformed hand wake ${eventId}: ${what}`),this.name="MalformedHandWakeError",this.eventId=eventId}},isObject=value2=>value2!=null&&typeof value2=="object"&&!Array.isArray(value2),isOneOf=(value2,allowed)=>typeof value2=="string"&&allowed.includes(value2),DELIVER_AS=["steer","followUp","nextTurn"],USER_DELIVER_AS=["steer","followUp"],NOTICE_TYPES=["info","warning","error"],isContentPart=value2=>isObject(value2)&&(value2.type==="text"&&typeof value2.text=="string"||value2.type==="image"&&typeof value2.data=="string"&&typeof value2.mimeType=="string");function content(value2){if(typeof value2=="string"||Array.isArray(value2)&&value2.every(isContentPart))return value2}function message(value2){if(!isObject(value2)||typeof value2.customType!="string"||typeof value2.display!="boolean")return;let body=content(value2.content);if(body!==void 0)return{customType:value2.customType,content:body,display:value2.display,...value2.details===void 0?{}:{details:value2.details}}}function optionsOf(value2,fields){if(value2===void 0)return;if(!isObject(value2))return null;let out={};for(let[name,valid]of Object.entries(fields)){let field=value2[name];if(field!==void 0){if(!valid(field))return null;out[name]=field}}return out}function parseHandWake(wake){let fail=what=>{throw new MalformedHandWakeError(wake.eventId,what)},payload=isObject(wake.payload)?wake.payload:fail("payload"),{sessionId}=payload;if(sessionId!==void 0&&typeof sessionId!="string")return fail("sessionId");let session=typeof sessionId=="string"?{sessionId}:{};switch(wake.source){case"message":{let options=optionsOf(payload.options,{triggerTurn:v=>typeof v=="boolean",deliverAs:v=>isOneOf(v,DELIVER_AS)});if(options===null)return fail("message options");let body=message(payload.message)??fail("message");return{...session,kind:"message",message:body,...options===void 0?{}:{options}}}case"user_message":{let options=optionsOf(payload.options,{deliverAs:v=>isOneOf(v,USER_DELIVER_AS),expandPromptTemplates:v=>typeof v=="boolean"});if(options===null)return fail("user message options");let body=content(payload.content)??fail("user message content");return{...session,kind:"user_message",content:body,...options===void 0?{}:{options}}}case"entry":{let customType=typeof payload.customType=="string"?payload.customType:fail("entry customType");return{...session,kind:"entry",customType,...payload.data===void 0?{}:{data:payload.data}}}case"notice":{let notice=typeof payload.message=="string"?payload.message:fail("notice"),{type}=payload;return type!==void 0&&!isOneOf(type,NOTICE_TYPES)?fail("notice type"):{...session,kind:"notice",message:notice,...isOneOf(type,NOTICE_TYPES)?{type}:{}}}case WAKE_DROPPED_SOURCE:{let{reason,count}=payload;return typeof reason!="string"||typeof count!="number"?fail("drop report"):{kind:"dropped",reason,count}}default:return fail(`source ${wake.source}`)}}function mayStartTurn(session){let context=session.context();return context!==void 0&&!ONE_SHOT_MODES.has(context.mode)&&context.model!==void 0}var dropNotice=(count,reason)=>`${count} late result${count===1?"":"s"} from work on the user's machine never arrived (${reason}).`;function deliverHandWake(wake,session){let delivery=parseHandWake(wake);switch(delivery.kind){case"message":return delivery.options?.triggerTurn===!0&&!mayStartTurn(session)?"skipped":(session.sendMessage(delivery.message,delivery.options),"delivered");case"user_message":return mayStartTurn(session)?(session.sendUserMessage(delivery.content,delivery.options),"delivered"):"skipped";case"entry":return session.appendEntry(delivery.customType,delivery.data),"delivered";case"notice":return session.notify(delivery.message,delivery.type),"delivered";case"dropped":return session.notify(dropNotice(delivery.count,delivery.reason),"warning"),"delivered"}}function deliverHandDrop(drop,session){session.notify(dropNotice(drop.count,drop.reason),"warning")}function scopeSessionCheck(sessionsOf){return wake=>{let sessionId=isObject(wake.payload)?wake.payload.sessionId:void 0;if(sessionId===void 0)return;let sessions=sessionsOf(wake.scope);return sessions===void 0?"unknown_scope":typeof sessionId=="string"&&sessions.has(sessionId)?void 0:"not_scope_session"}}var KIND2="execution.wake-inbox",withFailures=(record2,failures)=>{let{failures:_previous,...rest}=record2;return Object.keys(failures).length===0?rest:{...rest,failures}},EMPTY={seen:{},pending:[],closed:{}};function decode(value2){if(value2===void 0)return EMPTY;if(isStoreObject(value2)&&isStoreObject(value2.seen)&&Array.isArray(value2.pending)&&isStoreObject(value2.closed))return value2;throw new Error("corrupt wake inbox record")}function createWakeInbox(options){let{issuer,store,epoch,admission,clock,owner}=options,key=`${KIND2}:${JSON.stringify([issuer])}`,read=async()=>decode(await store.getDocument(key)),write=async(record2,step,eventId)=>{await store.commit(epoch,[{op:"append",id:store.mintId(),kind:KIND2,data:{step,executionId:eventId}},{op:"put",key,data:record2}],()=>{})},update=decide=>admission.admit(async()=>decide(await read())),maxAttempts=options.maxAttempts??3,take=(wake,step)=>update(async record2=>{if(!record2.pending.some(entry2=>entry2.eventId===wake.eventId))return;let pending=record2.pending.filter(entry2=>entry2.eventId!==wake.eventId),{[wake.eventId]:_counted,...failures}=record2.failures??{};await write(withFailures({...record2,pending},failures),step,wake.eventId)}),failed=async(wake,error,report)=>{let attempts=((await read()).failures?.[wake.eventId]??0)+1,poisoned=attempts>=maxAttempts;poisoned?await take(wake,"poison"):await update(async record2=>{let failures={...record2.failures,[wake.eventId]:attempts};await write(withFailures(record2,failures),"failed",wake.eventId)}),report({wake,error,attempts,poisoned})},draining=Promise.resolve(),drainOnce=async consume=>{let taken=0;for(let wake of(await read()).pending){try{await consume(wake)}catch(error){let report=options.onUndeliverable;if(report===void 0)throw error;await failed(wake,error,report);continue}await take(wake,"take"),taken+=1}return taken};return{read,receive:(sender,wake,check)=>update(async record2=>{let seen=record2.seen[wake.scope]??[];if(seen.includes(wake.eventId))return{kind:"ack",eventId:wake.eventId,duplicate:!0};if(record2.closed[wake.scope]!==void 0)return{kind:"refused",eventId:wake.eventId,reason:"scope_closed"};let bound=owner(wake.scope);if(bound===void 0)return{kind:"refused",eventId:wake.eventId,reason:"unknown_scope"};if(bound!==sender)return{kind:"refused",eventId:wake.eventId,reason:"not_scope_hand"};let refusal2=check?.(wake);return refusal2!==void 0?{kind:"refused",eventId:wake.eventId,reason:refusal2}:(await write({...record2,seen:{...record2.seen,[wake.scope]:[...seen,wake.eventId]},pending:[...record2.pending,wake]},"commit",wake.eventId),{kind:"ack",eventId:wake.eventId,duplicate:!1})}),drain:consume=>{let run=draining.then(()=>drainOnce(consume));return draining=run.catch(()=>{}),run},closeScope:scope=>update(async record2=>{record2.closed[scope]===void 0&&await write({...record2,closed:{...record2.closed,[scope]:clock()}},"close",null)}),sweep:()=>update(async record2=>{let now=clock(),gone=Object.entries(record2.closed).filter(([scope,closedAt])=>now>closedAt+6048e5&&record2.seen[scope]!==void 0).map(([scope])=>scope);if(gone.length===0)return[];let drop=new Set(gone);return await write({...record2,seen:Object.fromEntries(Object.entries(record2.seen).filter(([scope])=>!drop.has(scope)))},"sweep",null),gone})}}function createEpochGate(epoch,send){let lanes=new Map,decide=(state,refusal2)=>{state.verdict={refusal:refusal2},state.decided.resolve(refusal2)},ask=(lane,state)=>{state.verdict!==void 0&&(state.verdict=void 0,state.decided=Promise.withResolvers());let asked=state.decided;send(lane,{kind:"floor",epoch}).catch(error=>{let reason=error instanceof Error?error.message:String(error);state.decided===asked&&state.verdict===void 0&&decide(state,`hand_unreachable: ${reason}`)})};return{open(lane){let known=lanes.get(lane);if(known!==void 0)return known.verdict===void 0?known.decided.promise:Promise.resolve(known.verdict.refusal);let state={decided:Promise.withResolvers(),verdict:void 0};return lanes.set(lane,state),ask(lane,state),state.decided.promise},answer(lane,message2){let state=lanes.get(lane);if(!(state===void 0||state.verdict!==void 0)){if(message2.kind==="floor_refused")return decide(state,message2.reason);if(message2.floor===epoch)return decide(state,void 0);decide(state,message2.floor>epoch?"epoch_superseded":"epoch_floor_mismatch")}},resend(){for(let[lane,state]of lanes)state.verdict?.refusal===void 0&&ask(lane,state)}}}function createHandLink(transport,planeHandlers={},filePlanes=[],epoch){let pending=new Map,closed=!1,stamp=epoch===void 0?{}:{epoch},sent=new Set,planes=createPlaneServer({transport,planes:planeHandlers,liveLane:(executionId,plane)=>{let waiting=pending.get(executionId)?.message;if(waiting?.kind==="invoke"||waiting?.kind==="file"&&(plane===void 0||filePlanes.includes(plane)))return waiting.scope.id}}),announced,waitedOut=!1,helloWaiters=new Set,settle2=(executionId,reply)=>{let waiter=pending.get(executionId);waiter!==void 0&&(pending.delete(executionId),sent.delete(executionId),planes.parentEnded(executionId),waiter.resolve(reply))},send=(lane,message2)=>transport.send(lane,encodeRemoteMessage(message2)),gate=epoch===void 0?void 0:createEpochGate(epoch,(lane,floor)=>send(lane,floor)),whenOpen=(lane,executionId,go)=>{if(gate===void 0)return go();gate.open(lane).then(refusal2=>{if(pending.has(executionId)){if(refusal2===void 0)return go();settle2(executionId,{kind:"epoch_refused",reason:refusal2})}})};return transport.onFrame(frame=>{if(closed)return;let nested=decodePlaneMessage(frame.payload);if(nested!==void 0)return planes.receive(frame.lane,nested);let message2;try{message2=decodeRemoteMessage(frame.payload)}catch{return}let ack=executionId=>{send(frame.lane,{kind:"ack",executionId,...stamp}).catch(()=>{})};if(message2.kind==="hello"){announced=message2;for(let waiter of[...helloWaiters])waiter(message2);if(gate?.resend(),message2.durable)for(let{message:waiting}of pending.values())sent.has(waiting.executionId)&&whenOpen(waiting.scope.id,waiting.executionId,()=>{send(waiting.scope.id,waiting).catch(()=>{})});return}if(message2.kind==="floor_ack"||message2.kind==="floor_refused")return gate?.answer(frame.lane,message2);message2.kind==="settled"?(settle2(message2.executionId,{kind:"settled",result:message2.result}),ack(message2.executionId)):message2.kind==="terminal"?(settle2(message2.executionId,{kind:"terminal",terminal:message2}),ack(message2.executionId)):message2.kind==="refused"&&settle2(message2.executionId,{kind:"refused",reason:message2.reason})}),{dispatch(unstamped,signal){let message2={...unstamped,...stamp},{executionId}=message2,replied=new Promise(resolve=>{pending.set(executionId,{message:message2,resolve})});if(closed)return settle2(executionId,{kind:"closed",sent:!1}),replied;if(signal?.aborted)return settle2(executionId,{kind:"aborted",sent:!1}),replied;let onAbort=()=>{if(!pending.has(executionId))return;let reached=sent.has(executionId);reached&&send(message2.scope.id,{kind:"abort",executionId,...stamp}).catch(()=>{}),settle2(executionId,{kind:"aborted",sent:reached})};return signal?.addEventListener("abort",onAbort,{once:!0}),replied.then(()=>signal?.removeEventListener("abort",onAbort)),whenOpen(message2.scope.id,executionId,()=>{sent.add(executionId),send(message2.scope.id,message2).catch(error=>{settle2(executionId,{kind:"unreachable",reason:error instanceof Error?error.message:String(error)})})}),replied},hello(ms,signal){return announced!==void 0||waitedOut||signal?.aborted?Promise.resolve(announced):new Promise(resolve=>{let done=hello=>{clearTimeout(timer),helloWaiters.delete(done),signal?.removeEventListener("abort",onAbort),resolve(hello)},onAbort=()=>done(void 0),timer=setTimeout(()=>{waitedOut=!0,done(void 0)},ms);helloWaiters.add(done),signal?.addEventListener("abort",onAbort,{once:!0})})},close(){closed=!0;for(let executionId of[...pending.keys()])settle2(executionId,{kind:"closed",sent:sent.has(executionId)});transport.close()}}}function errorResult2(text){return{content:[{type:"text",text}],details:{},isError:!0}}function terminalResult(placement,terminal2){if(placement==="split-local")return{content:[{type:"text",text:TOOL_RESULT_PLACEHOLDER}],details:{},isError:!1};let{reason,uncertain,hooksRan}=terminal2;return{content:[{type:"text",text:`The tool call ended without a result (${reason}) and was not run again. ${uncertain?"Its effects are uncertain.":"It had no effect."}`}],details:{outcome:reason,uncertain,hooksRan},isError:!0}}function createRemoteToolHost(options){let mintId=options.mintId??(()=>crypto.randomUUID()),link=createHandLink(options.transport,options.planes??{},options.filePlanes??[],options.epoch),resultOf=reply=>{switch(reply.kind){case"settled":return reply.result;case"terminal":return terminalResult(options.placement,reply.terminal);case"refused":return errorResult2(`The hand refused this tool call: ${reply.reason}`);case"aborted":return errorResult2(reply.sent?"Tool execution aborted":"Operation aborted");case"unreachable":return errorResult2(`The hand is unreachable: ${reply.reason}`);case"closed":return terminalResult(options.placement,reply.sent?{reason:"hand_restarted",uncertain:!0,hooksRan:!0}:{reason:"cancelled",uncertain:!1,hooksRan:!1});case"epoch_refused":return errorResult2(`The hand refused this session's epoch: ${reply.reason}`)}},dispatch=(invoke,signal)=>({settled:link.dispatch(invoke,signal).then(resultOf)});return{async execute(call,hostOptions){let{emit,signal}=hostOptions,batchId=mintId(),promptSurface=options.promptSurface?.(),invokeOf=(raw,index)=>({kind:"invoke",executionId:mintId(),batchId,index,scope:call.scope,toolCallId:raw.id,name:raw.name,arguments:raw.arguments,...options.sessionRef===void 0?{}:{sessionRef:options.sessionRef},...promptSurface===void 0?{}:{promptSurface}}),finish=async(raw,result)=>(await emit({type:"tool_execution_end",toolCallId:raw.id,toolName:raw.name,result,isError:result.isError}),result),outcomes=[];for(let[index,raw]of call.calls.entries()){await emit({type:"tool_execution_start",toolCallId:raw.id,toolName:raw.name,args:raw.arguments});let outcome2=dispatch(invokeOf(raw,index),signal).settled.then(result=>finish(raw,result));if(outcomes.push(outcome2),call.mode==="sequential"&&(await outcome2,signal?.aborted))break}let results=await Promise.all(outcomes),messages=[];for(let[index,result]of results.entries()){let raw=call.calls[index];if(raw===void 0)continue;let message2={role:"toolResult",toolCallId:raw.id,toolName:raw.name,content:result.content,details:result.details,...result.addedToolNames?.length?{addedToolNames:[...result.addedToolNames]}:{},isError:result.isError,timestamp:Date.now()};await emit({type:"message_start",message:message2}),await emit({type:"message_end",message:message2}),messages.push(message2)}return{messages,terminate:results.length>0&&results.every(result=>result.terminate===!0)}},deviceFiles:scope=>createRemoteDeviceFiles(link,scope,mintId),close:()=>link.close()}}var PIPE_PREFIX="\\\\.\\pipe\\";function localEndpoint(platform,name,socketDir){if(name.length===0||/[\\/]/.test(name))throw new RangeError(`local endpoint: a name must be non-empty with no path separator, got ${JSON.stringify(name)}`);if(platform==="win32"){let address=`${PIPE_PREFIX}${name}`;if(address.length>256)throw new RangeError("local endpoint: a pipe name is at most 256 characters");return{kind:"named-pipe",address}}return{kind:"unix-socket",address:`${socketDir.replace(/\/+$/,"")}/${name}.sock`,mode:384}}function endpointKey(endpoint){return endpoint.kind==="named-pipe"?endpoint.address.toUpperCase():endpoint.address}function createLink(a,b,schedule){let generation=0,up=!1,drop=()=>{up&&(up=!1,generation+=1,a.detached(),b.detached())},half=(to,at)=>({send:message2=>(schedule(()=>{up&&generation===at&&to.message(message2)}),!0),close:()=>{generation===at&&drop()}});return{connect(){up||(up=!0,generation+=1,a.attached(half(b,generation)),b.attached(half(a,generation)))},drop,get connected(){return up}}}function createInProcessNetwork(options={}){let schedule=options.schedule??queueMicrotask,listeners=new Map;return{listen(endpoint,side){let key=endpointKey(endpoint);if(listeners.has(key))throw new Error(`in-process carrier: ${endpoint.address} already has a listener`);return listeners.set(key,{side,dialed:!1}),()=>{listeners.delete(key)}},dial(endpoint,side){let listener=listeners.get(endpointKey(endpoint));if(listener===void 0)throw new Error(`in-process carrier: no listener at ${endpoint.address}`);if(listener.dialed)throw new Error(`in-process carrier: ${endpoint.address} is already dialed`);return listener.dialed=!0,createLink(side,listener.side,schedule)}}}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(message2,cause){super(message2),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"),SESSION_CWD_CONTEXT_KEY=createContextKey("pi.sessionCwd");function getSessionCwd(context){return context.value(SESSION_CWD_CONTEXT_KEY)}function withSessionCwd(cwd,context){return cwd===void 0?context:withContextValue(SESSION_CWD_CONTEXT_KEY,cwd,context)}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(outcome2){this.resolveCompletion(outcome2)}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:
<summary>
`,COMPACTION_SUMMARY_SUFFIX=`
</summary>`,BRANCH_SUMMARY_PREFIX=`The following is a summary of a branch that this conversation came back from:
<summary>
`,BRANCH_SUMMARY_SUFFIX="</summary>";function bashExecutionToText(msg){let text=`Ran \`${msg.command}\`
`;return msg.output?text+=`\`\`\`
${msg.output}
\`\`\``:text+="(no output)",msg.cancelled?text+=`
(command cancelled)`:msg.exitCode!==null&&msg.exitCode!==void 0&&msg.exitCode!==0&&(text+=`
Command exited with code ${msg.exitCode}`),msg.truncated&&msg.fullOutputPath&&(text+=`
[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,content2,display,details,timestamp){return{role:"custom",customType,content:content2,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 entry2=pathEntries[index];if(entry2?.type==="compaction"){compaction=entry2,compactionIndex=index;break}}return compaction===void 0?[...pathEntries]:[compaction,...pathEntries.slice(compactionIndex+1)]}function isContextMessage(message2){return message2.role!=="assistant"||message2.stopReason!=="error"&&message2.stopReason!=="aborted"&&message2.stopReason!=="deferred"}function sessionEntryToContextMessages(entry2){switch(entry2.type){case"message":return isContextMessage(entry2.message)?[entry2.message]:[];case"compaction":return[createCompactionSummaryMessage(entry2.summary,entry2.tokensBefore,entry2.timestamp),...entry2.retainedTail.filter(isContextMessage)];case"branch_summary":return entry2.summary?[createBranchSummaryMessage(entry2.summary,entry2.fromId,entry2.timestamp)]:[];case"custom":return[]}}async function buildSessionContext(pathEntries,options,context){options??={};let entries=buildContextEntries(pathEntries),messages=[];for(let entry2 of entries){if(entry2.type!=="custom"){messages.push(...sessionEntryToContextMessages(entry2));continue}let projector=options.entryProjectors?.[entry2.customType];projector!==void 0&&messages.push(...await projector(entry2,context)??[])}return messages}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,message2,path,cause){super(message2,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,message2,cause){super(message2,cause===void 0?void 0:{cause}),this.name="ExecutionError",this.code=code,cause!==void 0&&(this.cause=cause)}},CompactionError=class extends Error{constructor(code,message2,cause){super(message2,cause===void 0?void 0:{cause}),this.name="CompactionError",this.code=code,cause!==void 0&&(this.cause=cause)}},BranchSummaryError=class extends Error{constructor(code,message2,cause){super(message2,cause===void 0?void 0:{cause}),this.name="BranchSummaryError",this.code=code}};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},...left.costUnknown||right.costUnknown?{costUnknown:!0}:{}}}function createFileOps(){return{read:new Set,written:new Set,edited:new Set}}function extractFileOpsFromMessage(message2,fileOps){if(message2.role==="assistant"&&!(!("content"in message2)||!Array.isArray(message2.content)))for(let block of message2.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&§ions.push(`<read-files>
${readFiles.join(`
`)}
</read-files>`),modifiedFiles.length>0&§ions.push(`<modified-files>
${modifiedFiles.join(`
`)}
</modified-files>`),sections.length===0?"":`
${sections.join(`
`)}`}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)}
[... ${truncatedChars} more characters truncated]`}function isPortableSummaryContentBlock(block){return block.type!=="providerNative"}function contentTextForSummary(content2,separator=`
`){return typeof content2=="string"?content2:contentText(content2.filter(isPortableSummaryContentBlock),separator)}function serializeConversation(messages){let parts=[];for(let msg of messages)if(msg.role==="user"){let content2=contentTextForSummary(msg.content,"");content2&&parts.push(`[User]: ${content2}`)}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(`
`)}`),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 content2=contentTextForSummary(msg.content,"");content2&&parts.push(`[Tool result]: ${truncateForSummary(content2,TOOL_RESULT_MAX_CHARS)}`)}return parts.join(`
`)}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(entry2){if(entry2.type==="message")return entry2.message;if(entry2.type==="branch_summary")return createBranchSummaryMessage(entry2.summary,entry2.fromId,entry2.timestamp);if(entry2.type==="compaction")return createCompactionSummaryMessage(entry2.summary,entry2.tokensBefore,entry2.timestamp)}function getMessageFromEntryForCompaction(entry2){if(entry2.type!=="compaction")return getMessageFromEntry(entry2)}function createSummaryRequestOptions(options,context){let cwd=options.cwd??getSessionCwd(context);return{...options,...cwd===void 0?{}:{cwd},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.contextUsage!==void 0?usage.contextUsage===null?0:usage.contextUsage.input+usage.contextUsage.output: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 entry2=entries[i];if(entry2.type==="message"){let usage=getAssistantUsage(entry2.message);if(usage)return usage}}}function getLastAssistantUsageInfo(messages,counted){for(let i=messages.length-1;i>=0;i--){let message2=messages[i];if(!counted.has(message2))continue;let usage=getAssistantUsage(message2);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 message2 of messages)counted.has(message2)&&(estimated+=estimateTokens(message2));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(content2){if(typeof content2=="string")return content2.length;let chars=0;for(let block of content2)block.type==="text"&&block.text?chars+=block.text.length:block.type==="image"&&(chars+=ESTIMATED_IMAGE_CHARS);return chars}function estimateTokens(message2){let chars=0;switch(message2.role){case"user":return chars=estimateTextAndImageContentChars(message2.content),Math.ceil(chars/4);case"assistant":{let assistant=message2;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(message2.content),Math.ceil(chars/4);case"bashExecution":return chars=message2.command.length+message2.output.length,Math.ceil(chars/4);case"branchSummary":case"compactionSummary":return chars=message2.summary.length,Math.ceil(chars/4)}return 0}function findValidCutPoints(entries,startIndex,endIndex){let cutPoints=[];for(let i=startIndex;i<endIndex;i++){let entry2=entries[i];switch(entry2.type){case"message":{switch(entry2.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}entry2.type==="branch_summary"&&cutPoints.push(i)}return cutPoints}function findTurnStartIndex(entries,entryIndex,startIndex){for(let i=entryIndex;i>=startIndex;i--){let entry2=entries[i];if(entry2.type==="branch_summary")return i;if(entry2.type==="message"){let role=entry2.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 entry2=entries[i];if(entry2.type!=="message")continue;let messageTokens=estimateTokens(entry2.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.
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.
Use this EXACT format:
## Goal
[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
## Constraints & Preferences
- [Any constraints, preferences, or requirements mentioned by user]
- [Or "(none)" if none were mentioned]
## Progress
### Done
- [x] [Completed tasks/changes]
### In Progress
- [ ] [Current work]
### Blocked
- [Issues preventing progress, if any]
## Key Decisions
- **[Decision]**: [Brief rationale]
## Next Steps
1. [Ordered list of what should happen next]
## Critical Context
- [Any data, examples, or references needed to continue]
- [Or "(none)" if not applicable]
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.
Update the existing structured summary with new information. RULES:
- PRESERVE all existing information from the previous summary
- ADD new progress, decisions, and context from the new messages
- UPDATE the Progress section: move items from "In Progress" to "Done" when completed
- UPDATE "Next Steps" based on what was accomplished
- PRESERVE exact file paths, function names, and error messages
- If something is no longer relevant, you may remove it
Use this EXACT format:
## Goal
[Preserve existing goals, add new ones if the task expanded]
## Constraints & Preferences
- [Preserve existing, add new ones discovered]
## Progress
### Done
- [x] [Include previously done items AND newly completed items]
### In Progress
- [ ] [Current work - update based on progress]
### Blocked
- [Current blockers - remove if resolved]
## Key Decisions
- **[Decision]**: [Brief rationale] (preserve all previous, add new)
## Next Steps
1. [Update based on current state]
## Critical Context
- [Preserve important context, add new if needed]
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}
Additional focus: ${customInstructions}`);let llmMessages=convertToLlm(currentMessages),promptText=`<conversation>
${serializeConversation(llmMessages)}
</conversation>
`;previousSummary&&(promptText+=`<previous-summary>
${previousSummary}
</previous-summary>
`),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((message2,index)=>({type:"message",id:`${prevCompaction.id}:retained:${index}`,parentId:index===0?prevCompaction.id:`${prevCompaction.id}:retained:${index-1}`,seq:prevCompaction.seq,timestamp:message2.timestamp,message:message2})),...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 message2 of dropFailedAssistantTurns(entries.slice(0,boundary).flatMap(sessionEntryToContextMessages)))tokens+=estimateTokens(message2);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.
Summarize the prefix to provide context for the retained suffix:
## Original Request
[What did the user ask for in this turn?]
## Early Progress
- [Key decisions and work done in the prefix]
## Context for Suffix
- [Information needed to understand the retained recent work]
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}
---
**Turn Context (split turn):**
${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>
${serializeConversation(llmMessages)}
</conversation>
${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&®istrations.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 message2=event.message;for(let registration of this.registrationsFor("after_response"))try{let result=await registration.handler({...event,message:message2},context);result?.message!==void 0&&(message2=result.message)}catch(error){await this.reportError(error instanceof Error?error:new Error(String(error)),"after_response",event.lane,context)}return{message:message2}}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(entry2){return{kind:"entry",entry:entry2}}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(entry2,seq,timestamp){return{...entry2,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(message2){super(message2),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(message2,context){return this.session.appendToBranch(this.name,{type:"message",message:message2},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,finished2=new Promise(resolve=>{release=resolve});return this.mutationLine.run(async()=>{grant(new StorageBackedSessionMutation(this.storage,release)),await finished2}).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 stored2=await this.getValue(branchTip(name),context);if(stored2===void 0)throw new SessionInvariantError(`Unknown branch: ${name}`);return stored2.value}async appendToBranch(name,entry2,context){if(this.assertOpen(),entry2.type==="message"&&entry2.message.role==="assistant"&&entry2.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(entry2.type==="message"?{id,parentId:tip.value,type:"message",message:entry2.message}:{id,parentId:tip.value,type:"custom",customType:entry2.customType,...entry2.data===void 0?{}:{data:entry2.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(entry2=>entry2.id)),targetPath=await branch.findEntries({start:targetId},context),commonAncestorId=null;for(let entry2 of targetPath)if(oldPath.has(entry2.id)){commonAncestorId=entry2.id;break}let entries=[],current=oldTipId;for(;current&¤t!==commonAncestorId;){let entry2=await session.getEntry(current,context);if(!entry2)throw new Error(`Corrupt session: entry ${current} not found`);entries.push(entry2),current=entry2.parentId}return entries.reverse(),{entries,commonAncestorId}}function getMessageFromEntry2(entry2){switch(entry2.type){case"message":return entry2.message.role==="toolResult"?void 0:entry2.message;case"branch_summary":return createBranchSummaryMessage(entry2.summary,entry2.fromId,entry2.timestamp);case"compaction":return createCompactionSummaryMessage(entry2.summary,entry2.tokensBefore,entry2.timestamp);case"custom":return}}function prepareBranchEntries(entries,tokenBudget=0){let messages=[],fileOps=createFileOps(),totalTokens=0;for(let entry2 of entries)if(!(entry2.type!=="branch_summary"||typeof entry2.details!="object"||entry2.details===null||Array.isArray(entry2.details))){if(Array.isArray(entry2.details.readFiles))for(let path of entry2.details.readFiles)typeof path=="string"&&fileOps.read.add(path);if(Array.isArray(entry2.details.modifiedFiles))for(let path of entry2.details.modifiedFiles)typeof path=="string"&&fileOps.edited.add(path)}for(let i=entries.length-1;i>=0;i--){let entry2=entries[i],message2=getMessageFromEntry2(entry2);if(!message2)continue;extractFileOpsFromMessage(message2,fileOps);let tokens=estimateTokens(message2);if(tokenBudget>0&&totalTokens+tokens>tokenBudget){(entry2.type==="compaction"||entry2.type==="branch_summary")&&totalTokens<tokenBudget*.9&&(messages.unshift(message2),totalTokens+=tokens);break}messages.unshift(message2),totalTokens+=tokens}return{messages,fileOps,totalTokens}}var BRANCH_SUMMARY_PREAMBLE=`The user explored a different conversation branch before returning here.
Summary of that exploration:
`,BRANCH_SUMMARY_PROMPT=`Create a structured summary of this conversation branch for context when returning later.
Use this EXACT format:
## Goal
[What was the user trying to accomplish in this branch?]
## Constraints & Preferences
- [Any constraints, preferences, or requirements mentioned]
- [Or "(none)" if none were mentioned]
## Progress
### Done
- [x] [Completed tasks/changes]
### In Progress
- [ ] [Work that was started but not finished]
### Blocked
- [Issues preventing progress, if any]
## Key Decisions
- **[Decision]**: [Brief rationale]
## Next Steps
1. [What should happen next to continue this work]
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}
Additional focus: ${customInstructions}`:instructions=BRANCH_SUMMARY_PROMPT;let summarizationMessages=[{role:"user",content:[{type:"text",text:`<conversation>
${conversationText}
</conversation>
${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})}var CLEARED_ARGUMENTS=typebox_exports.Unknown();function issuingMessage(toolCall){return{role:"assistant",content:[toolCall],api:"agent-harness",provider:"agent-harness",model:"agent-harness",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"toolUse",timestamp:Date.now()}}async function runOnPreparedToolHost(toolCall,scopeId,recordWitness,run){let settled,body={name:toolCall.name,label:toolCall.name,description:toolCall.name,parameters:CLEARED_ARGUMENTS,execute:async()=>{let{outcome:outcome2,result}=await run();return settled={outcome:outcome2},result}};if(await createPreparedToolHost({afterToolFreeze:noPreflightCarry,removedToolHints:{}},openMemoryBatchStore).execute({scope:{id:scopeId,root:""},calls:[toolCall],mode:"sequential"},{emit:()=>{},...recordWitness===void 0?{}:{recordWitness},local:{context:{systemPrompt:"",messages:[],tools:[body]},assistantMessage:issuingMessage(toolCall)}}),settled===void 0)throw new Error(`agent harness: the prepared host ran no body for ${toolCall.name}`);return settled.outcome}function createErrorToolResult2(message2){return{content:[{type:"text",text:message2}],details:void 0}}function unrecordableArguments(args){try{toStoreValue(args);return}catch(error){return`Tool arguments are not JSON: ${error instanceof Error?error.message:String(error)}`}}function immediateError(toolCall,message2,terminate=!1){return{kind:"immediate",toolCall,result:createErrorToolResult2(message2),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,recordWitness){let acceptingUpdates=!0;return gate.admit(async()=>{let admittedContext=withAbortSignal(gate.signal,context);admittedContext.abortSignal?.throwIfAborted();let unrecordable=unrecordableArguments(call.args);if(unrecordable!==void 0)return{result:createErrorToolResult2(unrecordable),isError:!0};let toolCall={type:"toolCall",id:call.toolCall.id,name:call.toolCall.name,arguments:call.args};return runOnPreparedToolHost(toolCall,invocation.invocationId,recordWitness,async()=>{let executed;try{executed={result:await call.tool.execute(call.toolCall.id,call.args,(partial,options)=>{acceptingUpdates&&onUpdate(partial,options)},toolContext,invocation,admittedContext),isError:!1}}catch(error){executed={result:createErrorToolResult2(error instanceof Error?error.message:String(error)),isError:!0}}finally{acceptingUpdates=!1}return{outcome:executed,result:executed.result}})})}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(message2,terminate){return{content:message2.content,details:message2.details,...message2.usage===void 0?{}:{usage:message2.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 entry2 of entries.sort((a,b)=>a.name.localeCompare(b.name))){if(await resolveKind(env,entry2,diagnostics,context)!=="file"||!entry2.name.endsWith(".md"))continue;let result=await loadTemplateFromFile(env,entry2.path,entry2.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(`
`).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(content2){try{let normalized=content2.replace(/\r\n/g,`
`).replace(/\r/g,`
`);if(!normalized.startsWith("---"))return{ok:!0,value:{frontmatter:{},body:normalized}};let endIndex=normalized.indexOf(`
---`,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(content2,args){let result=content2;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}">
References are relative to ${dirnameEnvPath(skill.filePath)}.
${skill.content}
</skill>`;return additionalInstructions?`${skillBlock}
${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 entry2 of entries){if(entry2.name!=="SKILL.md")continue;let fullPath=entry2.path;if(await resolveKind2(env,entry2,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 entry2 of entries.sort((a,b)=>a.name.localeCompare(b.name))){if(entry2.name.startsWith(".")||entry2.name==="node_modules")continue;let fullPath=entry2.path,kind=await resolveKind2(env,entry2,diagnostics,context);if(!kind)continue;let isLink=entry2.kind==="symlink",relPath=relativeEnvPath(rootDir,fullPath),ignorePath=kind==="directory"?`${relPath}/`:relPath;if(!isLink&&ignoreMatcher.ignores(ignorePath))continue;if(kind==="directory"){let result2=await loadSkillsFromDirInternal(env,fullPath,!1,isLink?(0,import_ignore.default)():ignoreMatcher,rootDir,context);skills.push(...result2.skills),diagnostics.push(...result2.diagnostics);continue}if(kind!=="file"||!includeRootFiles||!entry2.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 content2=await env.readTextFile(ignorePath,context);if(!content2.ok){diagnostics.push({type:"warning",code:"read_failed",message:content2.error.message,path:ignorePath});continue}let patterns=content2.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(content2){try{let normalized=content2.replace(/\r\n/g,`
`).replace(/\r/g,`
`);if(!normalized.startsWith("---"))return{ok:!0,value:{frontmatter:{},body:normalized}};let endIndex=normalized.indexOf(`
---`,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 entry2={...item,parentId};return parentId=item.id,entry2})}function entryLifecycleEvents(entry2,lane,runId){let operation=runId===void 0?{}:{runId};return entry2.type==="message"?[{type:"message_start",lane,...operation,message:entry2.message},{type:"message_end",lane,...operation,message:entry2.message,entryId:entry2.id},{type:"entry_added",lane,entry:entry2}]:[{type:"entry_added",lane,entry:entry2}]}function committedEntryEvents(entries,commit,lane,runId,firstWriteIndex=0){return entries.flatMap((entry2,index)=>entryLifecycleEvents(materializeCommittedEntry(entry2,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 stored2=await reader.getValue(pendingEntry(item.entryId),context);if(stored2===void 0)throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is missing its payload`);if(stored2.value.type==="message")return{entryId:item.entryId,kind:item.kind,type:"message",message:stored2.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:stored2.value.customType,...stored2.value.payload===void 0?{}:{data:stored2.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 stored2=await reader.getValue(pendingEntry(item.entryId),drive.context);if(stored2===void 0)throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is missing its payload`);if(item.kind!=="write"&&stored2.value.type!=="message")throw new SessionInvariantError(`Queued ${item.kind} entry ${item.entryId} is not a message`);return{item,pending:stored2.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 entry2=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),entry2}),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(entry2=>insertEntry(entry2)),...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((entry2,index)=>entry2.id===plannedEntryIds[index])&&followUp!==void 0){let entry2={id:followUp.id,parentId:placement.tipId,type:"message",message:followUp.message},entryWriteIndex=placement.writes.length;return{kind:"commit",writes:[...placement.writes,insertEntry(entry2),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({...entry2,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&¤t.latestAssistantEntryId===null)throw new SessionInvariantError("Completed run is missing its final assistant");let record2=operationResultRecord(meta,"completed",placement.tipId),cleanup=await operationCleanupWrites(reader,drive.operationId,current,drive.context);return{kind:"finish",writes:[...placement.writes,...cleanup],record:record2,lane:{tipId:placement.tipId,inbox:placement.inbox},materialize:()=>({kind:"settled",outcome:record2}),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:record2.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),stored2=await reader.getValue(operationPreparation(drive.operationId,current.task.taskId),drive.context);if(stored2?.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:stored2.value.kind==="compaction"?compactionPreparation(stored2.value):branchPreparation(stored2.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,message2,details){return{code,message:message2,...details===void 0?{}:{details}}}async function publishStructuralOutcome(lane,drive,capability,outcome2){let hookUsageId=(outcome2.kind==="compaction"||outcome2.kind==="branch_summary")&&outcome2.fromHook&&outcome2.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((outcome2.kind==="compaction"||outcome2.kind==="branch_summary")&&outcome2.kind!==expected)throw new SessionInvariantError(`Structural ${outcome2.kind} result does not match ${expected} task ${current.task.taskId}`);let writes=[],baseEvents=[],terminalTipId=state.tipId;if(hookUsageId!==void 0&&(outcome2.kind==="compaction"||outcome2.kind==="branch_summary")){let usage=outcome2.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(outcome2.kind==="compaction"){let entry2={id:outcome2.resultEntryId,parentId:state.tipId,type:"compaction",summary:outcome2.result.summary,retainedTail:outcome2.result.retainedTail,tokensBefore:outcome2.result.tokensBefore,...outcome2.result.details===void 0?{}:{details:outcome2.result.details},...outcome2.result.usage===void 0?{}:{usage:outcome2.result.usage},fromHook:outcome2.fromHook},entryWriteIndex=writes.length;writes.push(insertEntry(entry2),setValue(branchTip(lane.name),outcome2.resultEntryId)),terminalTipId=outcome2.resultEntryId,baseEvents.push(commit=>committedEntryEvents([entry2],commit,lane.name,drive.operationId,entryWriteIndex))}else if(outcome2.kind==="branch_summary"){let boundary2=navigationBoundary(current.task),entry2={id:outcome2.resultEntryId,parentId:boundary2.targetId,type:"branch_summary",fromId:meta.sourceTipId,summary:outcome2.result.summary,details:{readFiles:outcome2.result.readFiles,modifiedFiles:outcome2.result.modifiedFiles},...outcome2.result.usage===void 0?{}:{usage:outcome2.result.usage},fromHook:outcome2.fromHook};writes.push(setValue(branchTip(lane.name),boundary2.targetId));let entryWriteIndex=writes.length;writes.push(insertEntry(entry2),setValue(branchTip(lane.name),outcome2.resultEntryId)),boundary2.label!==void 0&&writes.push(setValue(entryLabel(boundary2.targetId),boundary2.label)),terminalTipId=outcome2.resultEntryId,baseEvents.push(commit=>committedEntryEvents([entry2],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:outcome2.kind==="compaction"||outcome2.kind==="branch_summary",...outcome2.kind==="failed"?{finalError:outcome2.error.message}:{}}]),outcome2.kind==="compaction"&&baseEvents.push(commit=>[{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:compactionReason(current.task),status:"completed",entryId:outcome2.resultEntryId,endedAt:terminalCompactionEndedAt??commit.timestamp}]);let events=commit=>baseEvents.flatMap(materialize=>materialize(commit));switch(current.task.boundary.kind){case"resume_checkpoint":{if(outcome2.kind==="branch_summary")throw new SessionInvariantError("Run compaction boundary received a branch summary");if(outcome2.kind==="compaction"||outcome2.kind==="declined"&¤t.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,outcome2.kind==="declined"&&continuation.kind==="may_finish");if(outcome2.kind==="declined"&&placement.triggerEntryId===void 0&&continuation.kind==="may_finish")return{kind:"return",result:{kind:"finish_pending",entryIds:placement.entries.map(entry2=>entry2.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=>[...outcome2.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=outcome2.kind==="declined"?operationError("compaction_declined","Overflow compaction was declined"):outcome2.error,cleanup=await operationCleanupWrites(reader,drive.operationId,current,drive.context),record2=operationResultRecord(meta,"failed",state.tipId,error),compactionEnd=outcome2.kind==="declined"?{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:compactionReason(current.task),status:"declined",endedAt:record2.endedAt}:{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:compactionReason(current.task),status:"failed",error:outcome2.error,endedAt:record2.endedAt};return{kind:"finish",writes:[...writes,...cleanup],record:record2,materialize:()=>({kind:"settled",outcome:record2}),events:commit=>[...events(commit),compactionEnd,{type:"run_end",lane:lane.name,runId:drive.operationId,status:"failed",error,fromTipId:meta.sourceTipId,tipId:state.tipId,endedAt:record2.endedAt}]}}case"finish":{if(outcome2.kind==="branch_summary")throw new SessionInvariantError("Compaction finish boundary received a branch summary");if(outcome2.kind!=="compaction"&&state.tipId===null)throw new SessionInvariantError("Standalone compaction has no Branch tip");let error=outcome2.kind==="failed"?outcome2.error:void 0,status=outcome2.kind==="declined"?"declined":outcome2.kind==="failed"?"failed":"completed",cleanup=await operationCleanupWrites(reader,drive.operationId,current,drive.context),record2=operationResultRecord(meta,status,terminalTipId,error);terminalCompactionEndedAt=record2.endedAt;let compactionEnd=outcome2.kind==="compaction"?void 0:outcome2.kind==="declined"?{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:"manual",status:"declined",endedAt:record2.endedAt}:{type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:"manual",status:"failed",error:outcome2.error,endedAt:record2.endedAt};return{kind:"finish",writes:[...writes,...cleanup],record:record2,...outcome2.kind==="compaction"?{lane:{tipId:terminalTipId}}:{},materialize:()=>({kind:"settled",outcome:record2}),events:commit=>[...events(commit),...compactionEnd===void 0?[]:[compactionEnd]]}}case"commit_navigation":{if(outcome2.kind==="compaction")throw new SessionInvariantError("Navigation boundary received a compaction result");let error=outcome2.kind==="failed"?outcome2.error:void 0,status=outcome2.kind==="declined"?"declined":outcome2.kind==="failed"?"failed":"completed",cleanup=await operationCleanupWrites(reader,drive.operationId,current,drive.context),record2=operationResultRecord(meta,status,terminalTipId,error),navigationEnd=outcome2.kind==="branch_summary"?{type:"navigation_end",lane:lane.name,runId:drive.operationId,status:"completed",fromTipId:meta.sourceTipId,tipId:terminalTipId,endedAt:record2.endedAt}:outcome2.kind==="declined"?{type:"navigation_end",lane:lane.name,runId:drive.operationId,status:"declined",fromTipId:meta.sourceTipId,tipId:terminalTipId,endedAt:record2.endedAt}:{type:"navigation_end",lane:lane.name,runId:drive.operationId,status:"failed",error:outcome2.error,fromTipId:meta.sourceTipId,tipId:terminalTipId,endedAt:record2.endedAt};return{kind:"finish",writes:[...writes,...cleanup],record:record2,...outcome2.kind==="branch_summary"?{lane:{tipId:terminalTipId}}:{},materialize:()=>({kind:"settled",outcome:record2}),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},summaryContext2=withSessionCwd(lane.session.metadata.cwd,drive.context);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,summaryContext2);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,summaryContext2);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),stored2=await reader.getValue(operationPreparation(drive.operationId,current.task.taskId),drive.context);if(stored2===void 0||stored2.value.kind!==expected)throw new SessionInvariantError(`Structural task ${current.task.taskId} has invalid durable preparation`);return{kind:"return",result:stored2.value.kind==="compaction"?compactionPreparation(stored2.value):branchPreparation(stored2.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(entry2=>entry2.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&¤t.label!==void 0)throw new SessionInvariantError("Root navigation cannot set a label");let writes=[setValue(branchTip(lane.name),current.targetId)];current.label!==void 0&¤t.targetId!==null&&writes.push(setValue(entryLabel(current.targetId),current.label));let cleanup=await operationCleanupWrites(reader,drive.operationId,current,drive.context),record2=operationResultRecord(meta,"completed",current.targetId);return{kind:"finish",writes:[...writes,...cleanup],record:record2,lane:{tipId:current.targetId},materialize:()=>({kind:"settled",outcome:record2}),events:()=>[{type:"navigation_end",lane:lane.name,runId:drive.operationId,status:"completed",fromTipId:meta.sourceTipId,tipId:current.targetId,endedAt:record2.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 entry2=entries.get(id);if(entry2?.type!=="message")throw new SessionInvariantError(`Run prompt entry ${id} is missing its message`);return entry2.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 message2 of injected)if(message2.role==="assistant"&&message2.stopReason==="pending")throw new SessionInvariantError("before_run returned a pending assistant message");let reserved=injected.map(message2=>({id:lane.session.idGenerator.next(),message:message2})),result=await lane.continueOperation(run,(state,current)=>{let entries=chainEntries(state.tipId,reserved.map(({id,message:message2})=>({id,type:"message",message:message2}))),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(entry2=>insertEntry(entry2)),...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&¤t.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(entry2=>entry2.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:(message2,afterContext)=>afterResponse(message2,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 progress2=openFrameProgress(lane,drive,responseEntryId),frameEncoder=new AssistantMessageFrameEncoder,eventContext={lane:lane.name,runId:drive.operationId,...recovery?{recovery:!0}:{}},close=async()=>{progress2.seal(),await progress2.drain()};return{observer:{start(message2,event,context){let frame=frameEncoder.encode(event);return frame!==void 0&&progress2.write(frame),lane.emitBatch([{type:"message_start",...eventContext,message:message2}],context)},update(message2,event,context){let frame=frameEncoder.encode(event);return frame!==void 0&&progress2.write(frame),lane.emitBatch([{type:"message_update",...eventContext,message:message2,event,...frame===void 0?{}:{frame}}],context)},end(message2,context){return lane.emitBatch([{type:"message_end",...eventContext,message:message2,entryId:responseEntryId}],context)}},async afterResponse(message2,metadata,context){return await close(),(await lane.hooks.runWithGate("after_response",{lane:lane.name,runId:drive.operationId,...metadata,message:message2},drive.gate,context))?.message??message2},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 record2=operationResultRecord(meta,"failed",state.tipId,error);return{kind:"finish",writes:await operationCleanupWrites(reader,drive.operationId,current,drive.context),record:record2,materialize:()=>({kind:"settled",outcome:record2}),events:()=>[{type:"run_end",lane:lane.name,runId:drive.operationId,status:"failed",error,fromTipId:meta.sourceTipId,tipId:state.tipId,endedAt:record2.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,message2){return{code:"assistant_error",message:message2.errorMessage??`${source==="assistant"?"Assistant":"Deferred"} request ended with ${message2.stopReason}`}}function normalizeError(message2,errorMessage2){return{...message2,stopReason:"error",errorMessage:errorMessage2}}function normalizeAborted(source,message2){return{...message2,stopReason:"aborted",errorMessage:message2.errorMessage??`${source==="assistant"?"Assistant":"Deferred"} request was cancelled`}}function deferredHandleIsValid(message2,generation){let handle=message2.deferred,identity=generation.generationContext.configuration.model;return message2.stopReason==="deferred"&&handle!==void 0&&handle.id.length!==0&&handle.provider===identity.provider&&handle.modelId===identity.modelId&&handle.api===message2.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))&¤t.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((content2,sourceIndex)=>content2.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 record2=failure===void 0?void 0:operationResultRecord(meta,"failed",responseEntryId,failure),cleanup=record2===void 0?[]:await operationCleanupWrites(reader,drive.operationId,current,drive.context),writes=[insertEntry(responseEntry),insertUsage(usageRow),setValue(branchTip(lane.name),responseEntryId),...record2===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 entry2=materializeEntry(commit),batch=[{type:"entry_added",lane:lane.name,entry:entry2,...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&¤t.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:{}}),record2!==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:record2.endedAt}),batch};if(record2!==void 0)return{kind:"finish",writes,record:record2,lane:{tipId:responseEntryId},materialize:()=>({kind:"settled",outcome:record2}),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,(message2,context)=>response.afterResponse(message2,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,...lane.session.metadata.cwd===void 0?{}:{cwd:lane.session.metadata.cwd},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 message2=interruptedAssistantMessage(generation.generationContext.configuration.model,reduceAssistantMessageFrames(frames.value));return await lane.emitBatch([{type:"message_start",lane:lane.name,runId:drive.operationId,message:message2,recovery:!0},{type:"message_end",lane:lane.name,runId:drive.operationId,message:message2,entryId:generation.responseEntryId,recovery:!0}],drive.context),publishResponse(lane,drive,generation,message2,{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,message2=interruptedAssistantMessage(identity,reduceAssistantMessageFrames(frames));return await lane.emitBatch([{type:"message_start",lane:lane.name,runId:drive.operationId,message:message2,recovery:!0},{type:"message_end",lane:lane.name,runId:drive.operationId,message:message2,entryId:effect.responseEntryId,recovery:!0}],drive.context),publishResponse(lane,drive,effect,message2,{recovery:!0})}async function readToolBatchSource(lane,drive,batch){return lane.command(async(_state,reader)=>{let entry2=(await reader.getEntries([batch.assistantEntryId],drive.context)).get(batch.assistantEntryId);if(entry2?.type!=="message"||entry2.message.role!=="assistant")throw new SessionInvariantError("Tool batch assistant entry is invalid");let calls=new Map;for(let call of batch.calls){let block=entry2.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:entry2.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 stored2=await reader.getValue(pendingEntry(call.resultEntryId),drive.context);if(stored2?.value.type!=="message"||!isToolResultMessage(stored2.value.payload))throw new SessionInvariantError(`Tool call ${call.resultEntryId} is missing its staged result`);let source=toolCallFor(sources,call);if(stored2.value.payload.toolCallId!==source.id||stored2.value.payload.toolName!==source.name)throw new SessionInvariantError(`Tool call ${call.resultEntryId} has a mismatched staged result`);items.push({call,message:stored2.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 message2=staged.get(call.resultEntryId)??(()=>{let entry2=placed.get(call.resultEntryId);return entry2?.type==="message"&&isToolResultMessage(entry2.message)?entry2.message:void 0})();if(message2===void 0)throw new SessionInvariantError(`Completed tool call ${call.resultEntryId} is missing its result entry`);return message2})}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 entry2={id:item.call.resultEntryId,parentId,type:"message",message:item.message,...item.call.terminate?{terminate:!0}:{}};eventEntries.push({entry:entry2,seqIndex:writes.length}),writes.push(insertEntry(entry2),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:entry2,seqIndex}of eventEntries){events.push({type:"entry_added",lane:lane.name,entry:{...entry2,seq:commit.seqs[seqIndex],timestamp:commit.timestamp}});let usage=eventUsage.find(candidate=>candidate.row.entryId===entry2.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:message2})=>[{type:"message_start",lane:lane.name,runId:drive.operationId,message:message2,...recovery?{recovery:!0}:{}},{type:"message_end",lane:lane.name,runId:drive.operationId,message:message2,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,content2,options={}){return{role:"toolResult",toolCallId:toolCall.id,toolName:toolCall.name,content:content2,...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,outcome2={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,outcome2)),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 stored2=await reader.getValue(operationToolArgs(drive.operationId,batch.turnId,call.sourceIndex),drive.context);if(stored2===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:()=>stored2.value,events:()=>[{type:"tool_start",lane:lane.name,runId:drive.operationId,turnId:batch.turnId,toolCallId:toolCall.id,toolName:toolCall.name,args:stored2.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),progress2=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&&progress2.write(partial)},toolContext,capability.invocation,drive.context,lane.readConfig().onExecutionPipeline)}catch(error){if(capability.expire(),progress2.seal(),await progress2.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(),progress2.seal()});await latestUpdateDelivery,await progress2.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(outcome2=>publishToolOutcome(lane,drive,run,effectPending.value,outcome2,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(outcome2=>publishToolOutcome(lane,drive,run,call,outcome2,!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 record2=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:record2.endedAt});break;default:break}events.push({type:"run_end",lane:lane.name,runId:drive.operationId,status:"aborted",fromTipId:meta.sourceTipId,tipId:state.tipId,endedAt:record2.endedAt})}else meta.intent.kind==="compaction"?events.push({type:"compaction_end",lane:lane.name,runId:drive.operationId,reason:"manual",status:"aborted",endedAt:record2.endedAt}):events.push({type:"navigation_end",lane:lane.name,runId:drive.operationId,status:"aborted",fromTipId:meta.sourceTipId,tipId:state.tipId,endedAt:record2.endedAt});return{kind:"finish",writes:cleanup,record:record2,materialize:()=>({kind:"settled",outcome:record2}),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 outcome2;try{outcome2=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(outcome2.kind==="idle_blocked")return await awaitWithContext(Promise.race([outcome2.owner,outcome2.change]),context),this.assertOpen(),this.command(plan,context);if(outcome2.kind==="reject")throw outcome2.error;return await outcome2.delivery,outcome2.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 content2=formatPromptTemplateInvocation(template,request.args);messages=content2.length===0?[]:[{role:"user",content:[{type:"text",text:content2}],timestamp:startedAt}];break}}for(let message2 of messages)if(message2.role==="assistant"&&message2.stopReason==="pending")return Result.err(new InvalidMessage({lane:this.name,reason:"pending_assistant",message:"Cannot accept a pending assistant message"}));let prompt=messages.map(message2=>({id:this.session.idGenerator.next(startedAt),message:message2}));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 stored2=await reader.getValue(pendingEntry(item.entryId),context);if(stored2===void 0)throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is missing its payload`);if(item.kind!=="write"&&stored2.value.type!=="message")throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is not a message`);if(stored2.value.type==="message"&&stored2.value.payload.role==="assistant"&&stored2.value.payload.stopReason==="pending")throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} contains a pending assistant`);return{item,pending:stored2.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:message2})=>({id,parentId:null,type:"message",message:message2}))]),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(entry2=>insertEntry(entry2)),...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(entry2=>entry2.id)),commonAncestorId=targetPath.find(entry2=>oldIds.has(entry2.id))?.id??null;preparation=prepareBranchEntries(oldPath.slice(0,commonAncestorId===null?oldPath.length:oldPath.findIndex(entry2=>entry2.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 stored2=await reader.getValue(operationResult(options.operationId),context);return stored2===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:stored2.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(outcome2=>{this.activeDrive===claim.drive&&(this.activeDrive=void 0,this.signalStateChange()),claim.drive.settle(outcome2)},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 stored2=await reader.getValue(pendingEntry(item.entryId),context);if(stored2?.value.type!=="message")throw new SessionInvariantError(`Pending ${item.kind} entry ${item.entryId} is missing its message`);return{item,message:stored2.value.payload}})),steer=payloads.filter(({item})=>item.kind==="steer").map(({message:message2})=>message2),followUp=payloads.filter(({item})=>item.kind==="followUp").map(({message:message2})=>message2),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(record2,context){if(record2.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(message2,images,context){return this.enqueue("steer",message2,images,context)}followUp(message2,images,context){return this.enqueue("followUp",message2,images,context)}nextRun(message2,images,context){return this.enqueue("nextRun",message2,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(),message2;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"}));message2={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"}));message2=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:message2}];return{kind:"commit",writes:[setValue(pendingEntry(entryId),{type:"message",payload:message2}),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 stored2=await reader.getValue(operationResult(captured.lastOperationId),context);if(stored2===void 0)throw new SessionInvariantError(`Lane ${JSON.stringify(this.name)} is missing result ${captured.lastOperationId}`);lastResult=stored2.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(message2,context){return this.append({type:"message",payload:message2},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 stored2=await reader.getValue(pendingEntry(item.entryId),context);if(stored2===void 0)throw new SessionInvariantError(`Pending write ${item.entryId} is missing its payload`);return pendingEntryWrite(item.entryId,stored2.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(entry2=>insertEntry(entry2)),...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 stored2=classifyLaneStorage(lane,{tip:tipByLane.get(lane),configuration:configurationByLane.get(lane),laneState:stateByLane.get(lane)});stored2.kind==="lane"&&restored.set(lane,await restoreLaneState(reader,lane,stored2,context))}return restored},context)}async function restoreLaneState(reader,lane,stored2,context){let operationId=stored2.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:stored2.tip.value,configuration:stored2.configuration.value,inbox:stored2.laneState.value.inbox,lastOperationId:stored2.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??{},...options.onExecutionPipeline===void 0?{}:{onExecutionPipeline:options.onExecutionPipeline}}};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 stored2=await readLaneStorage(mutator,name,context);if(stored2.kind==="lane"){let restored=await restoreLaneState(mutator,name,stored2,context);lane=this.buildLane(name,restored),this.lanesByName.set(name,lane);return}let tipId=stored2.kind==="branch"?stored2.tip.value:options.createAt??null;if(stored2.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=[...stored2.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 record2={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=record2,snapshot.operation=null,snapshot.tipId=event.tipId;return}case"compaction_end":{let operation=matchingOperation(snapshot,event.runId);if(operation?.kind!=="compaction")return;let record2={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=record2,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(stored2=>stored2.address.namespace===address.namespace)}function findStoredValue(values,address){return values.find(stored2=>stored2.address.namespace===address.namespace&&stored2.address.key===address.key)}function createForkSnapshot(source,options){let sourceEntries=new Map(source.entries.map(entry2=>[entry2.id,entry2])),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(entry2=>entry2.seq))+1;for(let stored2 of source.scalarValues){let projected=projectForkCurrentStateWrite({kind:"value",op:"set",seq:stored2.seq,namespace:stored2.address.namespace,key:stored2.address.key,value:stored2.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(stored2=>stored2.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(stored2=>stored2.address.key));for(let stored2 of source.scalarValues)if((stored2.address.namespace===laneConfig("").namespace||stored2.address.namespace===laneState("").namespace)&&!sourceTipKeys.has(stored2.address.key))throw new Error(`Source session branch ${JSON.stringify(stored2.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 isRecord10(value2){return typeof value2=="object"&&value2!==null&&!Array.isArray(value2)}function isSafeIntegerAtLeast(value2,minimum){return Number.isSafeInteger(value2)&&value2>=minimum}function isLegacyV3SessionHeader(value2){return isRecord10(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 isRecord10(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 isRecord11(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(!isRecord11(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 content2=>{fileValue(await fileSystem.appendFile(tempPath,content2,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)}
`),await writeTransactions(writes=>append(`${serializeJsonlTransaction(writes)}
`))})}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 entry2 of input.normalized.entryStructures())index.applyEntry(entry2.id,entry2.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 entry2;try{entry2=JSON.parse(line)}catch(error){throw new Error("Invalid legacy v3 JSONL record: not valid JSON",{cause:error})}let recordType=entry2?.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 entry2}function importedCustomMessage(entry2){return{role:"custom",customType:entry2.customType,content:entry2.content,details:entry2.details,display:entry2.display,timestamp:Date.parse(entry2.timestamp)}}function isRetainedEntry(entry2){return entry2.type!=="model_change"&&entry2.type!=="thinking_level_change"&&entry2.type!=="active_tools_change"&&entry2.type!=="session_info"&&entry2.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(entry2,resolveLegacyId){switch(entry2.type){case"message":return entry2.message;case"custom_message":return importedCustomMessage(entry2);case"branch_summary":return entry2.summary?createBranchSummaryMessage(entry2.summary,resolveBranchSummaryFromId(resolveLegacyId,entry2.fromId),entry2.timestamp):void 0;case"compaction":return createCompactionSummaryMessage(entry2.summary,entry2.tokensBefore,entry2.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 entry2=entriesById.get(currentId);if(yield entry2,currentId===compaction.firstKeptEntryId)return;currentId=entry2.parentId}throw new Error(`Legacy v3 compaction ${compaction.id} firstKeptEntryId is not on its parent branch: ${compaction.firstKeptEntryId}`)}function normalizeRetainedEntry(entry2,indexed,retainedTail,resolveLegacyId){let committedBase={kind:"entry",id:indexed.mappedId,parentId:resolveLegacyId(indexed.parentId),seq:indexed.seq,timestamp:Date.parse(entry2.timestamp)};return entry2.type==="message"?{...committedBase,type:"message",message:entry2.message}:entry2.type==="custom_message"?{...committedBase,type:"message",message:importedCustomMessage(entry2)}:entry2.type==="branch_summary"?{...committedBase,type:"branch_summary",fromId:resolveBranchSummaryFromId(resolveLegacyId,entry2.fromId),summary:entry2.summary,details:entry2.details,usage:entry2.usage,fromHook:entry2.fromHook??!1}:entry2.type==="compaction"?{...committedBase,type:"compaction",summary:entry2.summary,retainedTail,tokensBefore:entry2.tokensBefore,details:entry2.details,usage:entry2.usage,fromHook:entry2.fromHook??!1}:{...committedBase,type:"custom",customType:entry2.customType,data:entry2.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 entry2=entriesById.get(currentId);if(remaining.delete(entry2.type))switch(entry2.type){case"model_change":model={provider:entry2.provider,modelId:entry2.modelId};break;case"thinking_level_change":thinkingLevel=entry2.thinkingLevel;break;case"active_tools_change":activeToolNames=[...entry2.activeToolNames];break}currentId=entry2.parentId}if(!(model===void 0||thinkingLevel===void 0))return{model,thinkingLevel,activeToolNames:activeToolNames??[]}}function indexLegacyV3Entry(entry2,lineNumber,seq,entries){let mappedParentId=entry2.parentId===null?null:entries.get(entry2.parentId)?.mappedId;if(mappedParentId===void 0)throw new Error(`Legacy v3 entry ${entry2.id} has a missing or forward parent at line ${lineNumber}: ${entry2.parentId}`);let structure={id:entry2.id,parentId:entry2.parentId,mappedId:mappedParentId};if(!isRetainedEntry(entry2))switch(entry2.type){case"label":return{...structure,type:entry2.type,targetId:entry2.targetId,label:entry2.label};case"model_change":return{...structure,type:entry2.type,provider:entry2.provider,modelId:entry2.modelId};case"thinking_level_change":return{...structure,type:entry2.type,thinkingLevel:entry2.thinkingLevel};case"active_tools_change":return{...structure,type:entry2.type,activeToolNames:entry2.activeToolNames};case"session_info":return{...structure,type:entry2.type}}if(entry2.id===null)throw new Error("Legacy v3 entry reference has no retained ancestor: null");let retained={...structure,mappedId:uuidv7(Date.parse(entry2.timestamp)),seq};switch(entry2.type){case"branch_summary":return{...retained,type:entry2.type,fromId:entry2.fromId};case"compaction":return{...retained,type:entry2.type,firstKeptEntryId:entry2.firstKeptEntryId};default:return{...retained,type:entry2.type}}}function legacyEntryUsage(entry2){switch(entry2.type){case"message":return entry2.message.role==="assistant"||entry2.message.role==="toolResult"?entry2.message.usage:void 0;case"compaction":case"branch_summary":return entry2.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,entry2=parseLegacyV3Entry(line.text);if(entries.has(entry2.id))throw new Error(`Duplicate legacy v3 entry id: ${entry2.id}`);let indexed=indexLegacyV3Entry(entry2,lineNumber,nextSeq,entries);entries.set(entry2.id,indexed),isRetainedEntry(indexed)&&nextSeq++,finalId=entry2.id,entry2.type==="session_info"&&(name=entry2.name);let usage=legacyEntryUsage(entry2);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 entry2 of entries.values()){if(entry2.type!=="label")continue;let targetId=resolveLegacyId(entry2.targetId);targetId!==null&&(entry2.label?labels.set(targetId,entry2.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 entry2 of this.entries.values())isRetainedEntry(entry2)&&(yield{id:entry2.mappedId,parentId:this.resolveLegacyId(entry2.parentId),seq:entry2.seq})}translateForkEntryId(legacyId){let entry2=this.entries.get(legacyId);if(entry2===void 0)throw new Error(`Legacy v3 fork entry does not exist: ${legacyId}`);if(!isRetainedEntry(entry2))throw new Error(`Legacy v3 fork entry is not a retained entry: ${legacyId}`);return entry2.mappedId}collectRequiredTailMessageIds(isEntrySelected){let requiredIds=new Set;for(let entry2 of this.entries.values())if(!(entry2.type!=="compaction"||!(isEntrySelected===void 0||isEntrySelected(entry2.mappedId))))for(let tailEntry of retainedTailStructure(entry2,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:entry2,indexed}of this.readCapturedEntries(context)){if(requiredTailMessageIds.has(entry2.id)){let message2=projectContextMessage(entry2,this.resolveLegacyId);message2!==void 0&&tailMessagesByLegacyId.set(entry2.id,message2)}if(!isRetainedEntry(indexed)||!isRetainedEntry(entry2)||isEntrySelected!==void 0&&!isEntrySelected(indexed.mappedId))continue;let retainedTail=[];if(indexed.type==="compaction"){for(let ancestor of retainedTailStructure(indexed,this.entries)){let message2=tailMessagesByLegacyId.get(ancestor.id);message2!==void 0&&retainedTail.push(message2)}retainedTail.reverse()}yield normalizeRetainedEntry(entry2,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 entry2=parseLegacyV3Entry(line.text);if(entry2.id!==indexed.id||entry2.type!==indexed.type)throw new Error("Legacy v3 source changed");yield{entry:entry2,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,...entry2}=write;this.entries.set(entry2.id,entry2),this.entriesBySeq.push(entry2),entry2.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 entry2 of this.entriesBySeq)isEntryCopied(entry2.id)&&(destination.entries.set(entry2.id,entry2),destination.entriesBySeq.push(entry2),entry2.type==="message"&&messageCount++);destination.stats={...destination.stats,messageCount};for(let stored2 of this.scalarValues.values()){let projected=projectForkCurrentStateWrite({kind:"value",op:"set",seq:stored2.seq,namespace:stored2.address.namespace,key:stored2.address.key,value:stored2.value},plan,isEntryCopied);projected!==void 0&&destination.applyValueSetOrListAppend(projected)}for(let stored2 of this.listValues.values())for(let element of stored2.elements){let projected=projectForkCurrentStateWrite({kind:"list",op:"append",seq:element.seq,namespace:stored2.address.namespace,key:stored2.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},stored2=this.listValues.get(key);stored2===void 0?this.listValues.set(key,{address:list(write.namespace,write.key),elements:[element]}):stored2.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 entry2=this.entries.get(id);entry2!==void 0&&found.set(id,entry2)}return found}getValue(address){return this.scalarValues.get(physicalKey2(address.namespace,address.key))}scanValues(prefix){return[...this.scalarValues.values()].filter(stored2=>stored2.address.namespace===prefix.namespace&&stored2.address.key.startsWith(prefix.key)).sort((left,right)=>compareKeys(left.address.key,right.address.key))}readList(address,options){let resolved=resolveListReadOptions(options),filtered=(this.listValues.get(physicalKey2(address.namespace,address.key))?.elements??[]).filter(element=>resolved.cursor===void 0?!0:resolved.order==="asc"?element.seq>resolved.cursor.seq:element.seq<resolved.cursor.seq);return(resolved.order==="asc"?filtered:[...filtered].reverse()).slice(0,resolved.limit)}scanBranch(query){let start=this.entries.get(query.start);if(start===void 0)throw new Error(`Unknown branch start: ${query.start}`);let path=[],entry2=start;for(;entry2!==void 0&&(path.push(entry2),entry2.parentId!==null);)if(entry2=this.entries.get(entry2.parentId),entry2===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(entry2=>({id:entry2.id,parentId:entry2.parentId,seq:entry2.seq,timestamp:entry2.timestamp,type:entry2.type,...entry2.customType===void 0?{}:{customType:entry2.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 entry2=this.entriesBySeq[index];(query.type===void 0||entry2.type===query.type)&&(query.customType===void 0||entry2.customType===query.customType)&&(query.fromSeq===void 0||entry2.seq>=query.fromSeq)&&(query.toSeq===void 0||entry2.seq<=query.toSeq)&&entries.push(entry2),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(content2){if(content2.endsWith(`
`))return{lines:content2.slice(0,-1).split(`
`),torn:!1};let lastNewline=content2.lastIndexOf(`
`);return lastNewline===-1?{lines:[],torn:!0}:{lines:content2.slice(0,lastNewline).split(`
`),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 content2=fileValue(await options.fileSystem.readTextFile(options.path,context),`Failed to read JSONL storage ${options.path}`),{lines,torn}=splitCompleteLines(content2);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(`
`)}
`)),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)}
`,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(entry2=>entry2.kind==="directory").map(entry2=>entry2.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(entry2=>entry2.kind!=="directory"&&entry2.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,finished2=new Promise(resolve=>{resolveFinished=resolve});this.admitted.add(finished2);let source;try{source=await this.admit(()=>this.session.beginMutation(context))}catch(error){throw this.admitted.delete(finished2),resolveFinished(),error}if(this.state!=="open")throw await source.end(context),this.admitted.delete(finished2),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(finished2),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:(message2,context)=>this.admit(()=>branch.appendMessage(message2,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 record2={metadata,storage,session,open:!0};return this.sessions.set(id,record2),this.openRecord(record2)}catch(error){throw await session.close(context),error}finally{this.pendingIds.delete(id)}}open(metadata,_context){this.assertOpen();let record2=this.sessions.get(metadata.id);return record2===void 0?Promise.reject(new Error(`Unknown session: ${metadata.id}`)):record2.open?Promise.reject(new Error(`Session is already open: ${metadata.id}`)):(record2.open=!0,Promise.resolve(this.openRecord(record2)))}list(_options,_context){return this.assertOpen(),Promise.resolve([...this.sessions.values()].map(({metadata})=>metadata))}async delete(metadata,context){this.assertOpen();let record2=this.sessions.get(metadata.id);if(record2===void 0)throw new Error(`Unknown session: ${metadata.id}`);if(record2.open)throw new Error(`Session is open: ${metadata.id}`);await record2.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),record2={metadata,storage,session,open:!0};return this.sessions.set(id,record2),this.openRecord(record2)}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(record2){return new MemorySessionFacade(record2.session,()=>{record2.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(`
`)}function escapeXml(value2){return value2.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var DEFAULT_MAX_LINES=2e3,DEFAULT_MAX_BYTES=51200,GREP_MAX_LINE_LENGTH=500,runtimeBuffer=globalThis.Buffer,nonAsciiPattern=/[^\x00-\x7f]/;function utf8ByteLength(content2){if(runtimeBuffer)return runtimeBuffer.byteLength(content2,"utf8");let firstNonAscii=content2.search(nonAsciiPattern);if(firstNonAscii===-1)return content2.length;let bytes=firstNonAscii;for(let i=firstNonAscii;i<content2.length;i++){let code=content2.charCodeAt(i);if(code<=127)bytes+=1;else if(code<=2047)bytes+=2;else if(code>=55296&&code<=56319&&i+1<content2.length){let next=content2.charCodeAt(i+1);next>=56320&&next<=57343?(bytes+=4,i++):bytes+=3}else bytes+=3}return bytes}function splitLinesForCounting(content2){if(content2.length===0)return[];let lines=content2.split(`
`);return content2.endsWith(`
`)&&lines.pop(),lines}function replaceUnpairedSurrogates(content2){let output="";for(let i=0;i<content2.length;i++){let code=content2.charCodeAt(i);if(code>=55296&&code<=56319){if(i+1<content2.length){let next=content2.charCodeAt(i+1);if(next>=56320&&next<=57343){output+=content2[i]+content2[i+1],i++;continue}}output+="\uFFFD"}else code>=56320&&code<=57343?output+="\uFFFD":output+=content2[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(content2,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=utf8ByteLength(content2),lines=splitLinesForCounting(content2),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content:content2,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(`
`),finalOutputBytes=utf8ByteLength(outputContent);return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content2,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=utf8ByteLength(content2),lines=splitLinesForCounting(content2),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content:content2,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(`
`),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,"")}var MAX_TIMEOUT_SECONDS=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_SECONDS)throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} 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}
${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+=`
[Showing last ${formatSize(capture.truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${capture.spillPath}]`}else capture.truncation.truncatedBy==="lines"?outputText+=`
[Showing lines ${startLine}-${endLine} of ${capture.truncation.totalLines}. Full output: ${capture.spillPath}]`:outputText+=`
[Showing lines ${startLine}-${endLine} of ${capture.truncation.totalLines} (${formatSize(51200)} limit). Full output: ${capture.spillPath}]`}else interruptedSpillPath!==void 0&&(outputText+=`${outputText?`
`:""}[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}
${status}`:status,{cause:result.error})}if(result.value.exitCode!==0)throw new Error(`${outputText?`${outputText}
`:""}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(`
`))&&(left=left.trim()),(!options.newlineIsToken||!right.includes(`
`))&&(right=right.trim())):options.ignoreNewlineAtEof&&!options.newlineIsToken&&(left.endsWith(`
`)&&(left=left.slice(0,-1)),right.endsWith(`
`)&&(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,`
`));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(entry2){return" "+entry2})}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(`
`)?hunk.lines[i]=hunk.lines[i].slice(0,-1):(hunk.lines.splice(i+1,0,"\\ No newline at end of file"),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(`
`)}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(`
`)+`
`}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(`
`),result=text.split(`
`).map(line=>line+`
`);return hasTrailingNl?result.pop():result.push(result.pop().slice(0,-1)),result}function detectLineEnding(content2){let crlfIdx=content2.indexOf(`\r
`),lfIdx=content2.indexOf(`
`);return lfIdx===-1||crlfIdx===-1?`
`:crlfIdx<lfIdx?`\r
`:`
`}function normalizeToLF(text){return text.replace(/\r\n/g,`
`).replace(/\r/g,`
`)}function restoreLineEndings(text,ending){return ending===`\r
`?text.replace(/\n/g,`\r
`):text}function normalizeForFuzzyMatch(text){return text.normalize("NFKC").split(`
`).map(line=>line.trimEnd()).join(`
`).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(content2){return content2.match(/[^\n]*\n|[^\n]+/g)??[]}function getLineSpans(content2){let offset=0;return splitLinesWithEndings(content2).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(content2,replacements,offset=0){let result=content2;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(content2,oldText){let exactIndex=content2.indexOf(oldText);if(exactIndex!==-1)return{found:!0,index:exactIndex,matchLength:oldText.length,usedFuzzyMatch:!1,contentForReplacement:content2};let fuzzyContent=normalizeForFuzzyMatch(content2),fuzzyOldText=normalizeForFuzzyMatch(oldText),fuzzyIndex=fuzzyContent.indexOf(fuzzyOldText);return fuzzyIndex===-1?{found:!1,index:-1,matchLength:0,usedFuzzyMatch:!1,contentForReplacement:content2}:{found:!0,index:fuzzyIndex,matchLength:fuzzyOldText.length,usedFuzzyMatch:!0,contentForReplacement:fuzzyContent}}function stripBom(content2){return content2.startsWith("\uFEFF")?{bom:"\uFEFF",text:content2.slice(1)}:{bom:"",text:content2}}function countOccurrences(content2,oldText){let fuzzyContent=normalizeForFuzzyMatch(content2),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(`
`),newLines=newContent.split(`
`),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(`
`);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(`
`),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 resolved=await resolveToolPath(env,path,context),variants=[resolved,resolved.replace(/ (AM|PM)\./gi,`${NARROW_NO_BREAK_SPACE}$1.`),resolved.normalize("NFD"),resolved.replace(/'/g,"\u2019"),resolved.normalize("NFD").replace(/'/g,"\u2019")];for(let variant of new Set(variants))if(getOrThrow(await env.exists(variant,context)))return variant;return resolved}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(`
`)}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:content2}=stripBom(readResult.value),originalEnding=detectLineEnding(content2),normalizedContent=normalizeToLF(content2),{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 outcome2=await runPostMutate(postMutate,{tool:"edit",path:absolutePath,signal:context.abortSignal});if(context.abortSignal?.aborted)throw new Error("Operation aborted");let committedContent=newContent,rereadNote;if(outcome2.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}.`,outcome2.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,delimiter){let newlines=0;for(let i=start;i<source.length;i++){if(source[i]===delimiter)return{end:i+1,newlines};if(source[i]===`
`||source[i]==="\r")return;source[i]==="\\"&&(source[i+1]==="\r"&&source[i+2]===`
`&&i++,source[i+1]===`
`&&newlines++,i++)}}function typeArgumentsSpan(source,start){let delimiters=["<"],newlines=0;for(let i=start;i<source.length;i++){let char=source[i];if(char===`
`&&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]===`
`&&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]===`
`||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(`
`);i=end<0?source.length:end}for(;i<source.length;){let char=source[i],next=source[i+1];if(char===`
`&&line++,template){if(char==="\\"){next===`
`&&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:"dd4b1fa66ed151e330cd7efaf7ca649d244257d52e2a79422e868da60c0edd8b",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-KXFMX52K.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(`
`).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(`
`),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(`
`))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(`
`),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(`
`);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(`
`)}),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(`
`)});let rendered=renderSegmentedReadView({text,segments}),encoder5=new TextEncoder;return encoder5.encode(rendered.text).length>=encoder5.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 encodeBase642(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 only when an imageProcessor is configured). 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. A .js or .json file of 100+ lines read without offset/limit may come back folded: bodies are replaced by markers and a footer lists the offset/limit ranges to reread; markers are not source, so reread those ranges before quoting or editing them.`,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}]
${processed.message}`}],details:void 0};let hints=processed.hints.length>0?`
${processed.hints.join(`
`)}`:"";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]
[Image omitted: configure an imageProcessor to convert BMP images.]`}],details:void 0}:{content:[{type:"text",text:`Read image file [${mimeType}]`},{type:"image",data:encodeBase642(bytes),mimeType}],details:void 0}}let textContent=new TextDecoder().decode(bytes),allLines=textContent.split(`
`),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(`
`),userLimitedLines=endLine-startLine}else selectedContent=allLines.slice(startLine).join(`
`);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+=`
[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue.]`:outputText+=`
[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}
[${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:content2},_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,content2,context)),context.abortSignal?.aborted)throw new Error("Operation aborted");let outcome2=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}`,outcome2.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:content2,...truncation}=truncateTail("");output={text:content2,truncation}}let progress2=progressFrom(output);return result.ok?ok({...progress2,exitCode:result.value.exitCode,cancelled:!1,truncated:result.value.truncation.truncated}):result.error.code==="aborted"||context.abortSignal?.aborted?ok({...progress2,exitCode:void 0,cancelled:!0,truncated:progress2.truncation.truncated}):options?.returnExecutionErrors?ok({...progress2,exitCode:void 0,cancelled:!1,truncated:progress2.truncation.truncated,executionError:result.error}):err(result.error)}function setRawArguments(partial,contentIndex,content2,raw){content2.partialJson=raw,content2.arguments=parseStreamingJson(raw)||{},partial.content[contentIndex]={...content2}}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 content2=partial.content[proxyEvent.contentIndex];if(content2?.type==="text")return content2.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 content2=partial.content[proxyEvent.contentIndex];if(content2?.type==="text")return content2.textSignature=proxyEvent.contentSignature,{type:"text_end",contentIndex:proxyEvent.contentIndex,content:content2.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 content2=partial.content[proxyEvent.contentIndex];if(content2?.type==="thinking")return content2.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 content2=partial.content[proxyEvent.contentIndex];if(content2?.type==="thinking")return content2.thinkingSignature=proxyEvent.contentSignature,{type:"thinking_end",contentIndex:proxyEvent.contentIndex,content:content2.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 content2=partial.content[proxyEvent.contentIndex];if(content2?.type==="toolCall"){let raw=content2.partialJson+proxyEvent.delta;return setRawArguments(partial,proxyEvent.contentIndex,content2,raw),{type:"toolcall_delta",contentIndex:proxyEvent.contentIndex,delta:proxyEvent.delta,partial}}throw new Error("Received toolcall_delta for non-toolCall content")}case"message_tool_arguments_reset":{let content2=partial.content[proxyEvent.contentIndex];if(content2?.type!=="toolCall")throw new Error("Received message_tool_arguments_reset for non-toolCall content");setRawArguments(partial,proxyEvent.contentIndex,content2,proxyEvent.rawArgumentPrefix);return}case"toolcall_end":{let content2=partial.content[proxyEvent.contentIndex];if(content2?.type==="toolCall"){let toolCall=proxyEvent.toolCall??content2;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}}}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 decoder5=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+=decoder5.decode(value2,{stream:!0});let lines=buffer.split(`
`);buffer=lines.pop()||"";for(let line of lines)processLine(line)}if(options.signal?.aborted)throw new Error("Request aborted by user");buffer+=decoder5.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}export{LOCAL_DEVICE_FILES,FILE_CHANNEL_MAX_BYTES,DeviceFileError,decodeDeviceFileArgs,encodeBase64,decodeBase64,base64Length,ProviderRetryWatchdogAbortError,EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC,STREAMED_DELTA_TYPES,reasonedBeforeFirstDelta,createInternalAgentChannel,setDefaultStreamFn,resolveToolNameAlias,createAdmissionLine,toStoreValue,createPreparedToolHost,BatchStoreMissingError,buildProviderContext,prepareAgentToolCall,runToolCall,createMemoryStoreMedium,openMemoryStore,Agent2 as Agent,fileResult,fileRefusal,createRemoteExecutor,readSessionState,manifestWrite,divergenceWrite,appendRecordWrites,rewriteRecordWrite,openSessionStore,openSyncSessionStore,CHAIN_COUNT_LIMIT,ChainCountLimitError,admitChainCall,serveLoopHooks,createWakeOutbox,HAND_WAKE_LANE,createHandWakeLink,createRemoteToolHost,createReliableTransport,require_ignore,selectedReadFolder,prepareReadFolder,createDefaultReadSummary,dist_exports};