@henlii/pidance 0.2.34 → 0.2.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +12 -12
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.json +1 -1
  6. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  7. package/.next/server/app/_global-error.html +1 -1
  8. package/.next/server/app/_global-error.rsc +1 -1
  9. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  15. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  16. package/.next/server/app/_not-found.html +1 -1
  17. package/.next/server/app/_not-found.rsc +3 -3
  18. package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  19. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  20. package/.next/server/app/_not-found.segments/_index.segment.rsc +3 -3
  21. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  22. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  23. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  24. package/.next/server/app/api/about/route.js +1 -1
  25. package/.next/server/app/api/agent/running/events/route.js +2 -2
  26. package/.next/server/app/api/auth/ui-sessions/[id]/route.js +1 -1
  27. package/.next/server/app/api/cwd/browse/route.js +1 -1
  28. package/.next/server/app/api/cwd/create/route.js +1 -1
  29. package/.next/server/app/api/cwd/validate/route.js +1 -1
  30. package/.next/server/app/api/file-index/route.js +1 -1
  31. package/.next/server/app/api/preferences/route.js +1 -1
  32. package/.next/server/app/index.html +1 -1
  33. package/.next/server/app/index.rsc +5 -5
  34. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  35. package/.next/server/app/index.segments/_full.segment.rsc +5 -5
  36. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  37. package/.next/server/app/index.segments/_index.segment.rsc +3 -3
  38. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  39. package/.next/server/app/page.js +13 -13
  40. package/.next/server/app/page_client-reference-manifest.js +1 -1
  41. package/.next/server/app-paths-manifest.json +12 -12
  42. package/.next/server/chunks/188.js +1 -1
  43. package/.next/server/chunks/329.js +1 -1
  44. package/.next/server/chunks/5274.js +1 -1
  45. package/.next/server/chunks/5277.js +1 -0
  46. package/.next/server/chunks/5304.js +1 -1
  47. package/.next/server/chunks/7594.js +3 -3
  48. package/.next/server/middleware-build-manifest.js +1 -1
  49. package/.next/server/middleware.js +1 -1
  50. package/.next/server/pages/404.html +1 -1
  51. package/.next/server/pages/500.html +1 -1
  52. package/.next/server/server-reference-manifest.json +1 -1
  53. package/.next/static/chunks/9780-c67eb25abbe3f7ca.js +1 -0
  54. package/.next/static/chunks/app/page-97814abcbd0a4b8a.js +24 -0
  55. package/.next/static/css/{2c5193dd12bf5ffb.css → 08aa26cccb5c0841.css} +1 -1
  56. package/README.en.md +1 -1
  57. package/README.md +1 -1
  58. package/package.json +3 -2
  59. package/.next/static/chunks/9780-10c5b784a91324f0.js +0 -1
  60. package/.next/static/chunks/app/page-61e09e843c0fdee8.js +0 -24
  61. /package/.next/static/{Xz9XxhYAztXJctQiqfonK → vxME07oDyWZkmnuAO8nbl}/_buildManifest.js +0 -0
  62. /package/.next/static/{Xz9XxhYAztXJctQiqfonK → vxME07oDyWZkmnuAO8nbl}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- "use strict";exports.id=7594,exports.ids=[7594],exports.modules={1060:(a,b,c)=>{c.d(b,{Ac:()=>n,GO:()=>i,X:()=>k,_4:()=>d,cV:()=>j,k2:()=>l,oC:()=>m});let d=262144,e={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},f={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},g={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},h={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function i(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function j(a){return e[i(a)]??null}function k(a){return f[i(a)]??null}function l(a){return g[i(a)]??null}function m(a){return h[i(a)]??null}function n(a){let b=i(a);return"pdf"===b||"docx"===b?b:null}},2416:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>A,v7:()=>B});var e=c(75430),f=c(60396),g=c(35768),h=c(68524),i=c(89953),j=c(5815),k=c(69835),l=c(99014),m=c(85664),n=c(65107),o=c(95237),p=c(38195),q=c(62693),r=c(23828),s=c(31524),t=c(52960),u=c(13737),v=c(60185),w=c(28121),x=c(87538),y=a([e,k,o,v,w]);[e,k,o,v,w]=y.then?(await y)():y;let B="Session writer is busy: a command is still in flight";function z(a){return"string"==typeof a&&a?a:void 0}class C{static{this.PARTIAL_RENDER_MIN_INTERVAL_MS=100}constructor(a){this.options=a,this.listeners=[],this.runtime=null,this.unsubscribe=null,this.extensionUi=null,this.idleTimer=null,this.startupHoldTimer=null,this.startupHold=!0,this.activeCommandCount=0,this.destroyCallbacks=new Set,this.pendingDestroys=new Map,this._alive=!0,this.promptRunning=!1,this.streamRunSeq=0,this.lastStopReason=null,this.followUpQueue=[],this.followUpQueueRevision=0,this.followUpQueueHydrated=!1,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,this.internalPromptTicket=Symbol("pidance internal follow-up prompt"),this.followUpFlushBlocked=!1,this.dispatchingFollowUpQueue=!1,this.commandReceipts=new Map,this.bashRunning=!1,this.bashCommand=null,this.localQueue={steering:[],followUp:[]},this.turnMetrics={startedAt:0,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},this.promptReceipts=new Map,this.promptInFlight=new Map,this.steerFlights=new Map,this.pendingBinaryBatches=[],this.destroyPromise=null,this.hasQueueSnapshot=!1,this.renderBridgeTheme=(0,x.Lm)(),this.toolRenderStates=new Map,this.followUpAdmittedAttemptIds=[],this.realSessionId=a.sessionId,this.realSessionFile=a.sessionFile,this.idleTimeoutMs=a.idleTimeoutMs??3e4,this.destroyWaitMs=a.destroyWaitMs??5e3,this.agentDir=a.agentDir??(0,f.$M)(),this.activeToolNames=a.toolNames}get sessionId(){return this.realSessionId}get sessionFile(){return this.realSessionFile}listPendingExtensionRequests(){return Array.from(this.extensionUi?.pendingSnapshot.values()??[])}get inner(){let a=this.runtime?.session;if(a)return{sessionManager:a.sessionManager}}isAlive(){return this._alive&&null!==this.runtime}isRunning(){if(!this._alive||!this.runtime)return!1;let a=this.runtime.session;return this.promptRunning||this.bashRunning||a.isStreaming||a.isCompacting}async runSteerCommand(a){let b=this.session;if(this.bashRunning){let b=this.reject(a.submissionId,"bash");return this.commandReceipts.set(a.submissionId,b),b}if(b.isCompacting&&!b.isStreaming&&!this.promptRunning){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"compacting");return this.commandReceipts.set(a.submissionId,c),c}let c=this.resolvePromptImages(a.images);if(c.missing.length){console.error("[pidance] steer image missing on disk:",c.missing);let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}if(!this.isRunning()&&!this.flushingFollowUp){let b=await this.send({type:"prompt",message:a.message,images:a.images,streamingBehavior:"steer"}),c={...b,submissionId:a.submissionId,action:"accepted"===b.status?"prompt":"queued"};return this.commandReceipts.set(a.submissionId,c),c}if(!b.isStreaming){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"busy");return this.commandReceipts.set(a.submissionId,c),c}await b.steer(a.message,c.images);let d={submissionId:a.submissionId,sessionId:this.realSessionId,status:"accepted",action:"steer"};return this.commandReceipts.set(a.submissionId,d),d}onDestroy(a){return this.destroyCallbacks.add(a),()=>{this.destroyCallbacks.delete(a)}}onEvent(a){let b=0===this.listeners.length;return this.listeners.push(a),b&&this.resetIdleTimer(),()=>{let b=this.listeners.length>0;this.listeners=this.listeners.filter(b=>b!==a),b&&0===this.listeners.length&&this.resetIdleTimer()}}beginExtensionBinding(){}async waitForExtensionsBound(){}emit(a){for(let b of this.listeners)try{b(a)}catch(a){console.error("[pidance] sdk host listener error:",a)}}notifyRunning(){this.options.onRunningChange?.()}hasActiveSubagentRun(){let a=this.realSessionFile;if(!a)return!1;try{let{runs:b}=(0,g._2)({limit:50});return(0,g.EE)(b,a)}catch{return!1}}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!this._alive||!this.runtime||this.startupHold||this.isRunning()||this.flushingFollowUp)return;if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();if(this.listeners.length>0)return;let a=this.idleTimeoutMs;this.idleTimer=setTimeout(()=>{if(this.idleTimer=null,!this.isRunning()&&!this.flushingFollowUp){if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();if(!(this.listeners.length>0)){if(this.hasActiveSubagentRun())return void this.resetIdleTimer();this.destroyAsync().catch(()=>{})}}},a)}releaseStartupHold(){this.startupHold&&(this.startupHold=!1,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null)}isSettled(){return!!this.runtime&&!!this._alive&&!this.isRunning()}isFollowUpHeld(){let a=(0,h.rV)(this.agentDir);return!0===(0,h.ql)(a,`sessionQueueHold.${this.realSessionId}`)}setFollowUpHeld(a){try{(0,h.xP)(`sessionQueueHold.${this.realSessionId}`,!!a||null,this.agentDir)}catch(b){console.error("[pidance] failed to persist follow-up hold:",b),this.emit({type:"follow_up_flush_error",errorMessage:a?"failed to persist follow-up hold; the queue may flush automatically":"failed to clear follow-up hold; the queue may stay held",...this.queueReceiptBase()})}}hydrateFollowUpQueue(){if(this.followUpQueueHydrated)return;this.followUpQueueHydrated=!0;let a=(0,h.rV)(this.agentDir),b=(0,h.ql)(a,`sessionQueue.${this.realSessionId}`),c=(0,l.jG)(b);this.followUpQueue=c.items.map(a=>"claimed"===a.state?{...a,state:"unknown"}:a),this.followUpQueueRevision=c.revision,this.followUpAdmittedAttemptIds=c.admittedAttemptIds,this.followUpQueue=this.followUpQueue.map(a=>{if(!a.media?.length)return a;let b=a.media.filter(a=>this.isQueueMediaRefAlive(a));return b.length===a.media.length?a:{...b.length?{...a,media:b}:{text:a.text,id:a.id,state:a.state},state:"unknown"}})}waitingFollowUp(){return this.followUpQueue.filter(a=>"waiting"===a.state)}hasWaitingFollowUp(){return this.followUpQueue.some(a=>"waiting"===a.state)}visibleFollowUp(){return this.followUpQueue.filter(a=>"claimed"!==a.state)}inFlightFollowUpTexts(){return this.followUpQueue.filter(a=>"claimed"===a.state).map(a=>a.text)}commitFollowUpQueue(a,b,c=[]){for(let c of a)if((c.media?.length??0)>l.ym)return console.error(`[pidance] refusing to persist follow-up queue (${b}): item media exceeds ${l.ym}`),!1;let d=this.followUpQueueRevision+1,e=(0,l.S1)(this.followUpAdmittedAttemptIds,c);try{(0,h.xP)(`sessionQueue.${this.realSessionId}`,(0,l.EP)({items:a,revision:d,admittedAttemptIds:e}),this.agentDir)}catch(a){return console.error(`[pidance] failed to persist follow-up queue (${b}):`,a),!1}return this.followUpQueue=a,this.followUpQueueRevision=d,this.followUpAdmittedAttemptIds=e,this.followUpFlushBlocked=!1,!0}discardDeliveredModelMedia(a){let b=new Set((0,l.Ot)(this.followUpQueue).map(a=>a.path));for(let c of a)"model"!==c.role||b.has(c.path)||(0,k.fm)(c.path,this.agentDir)}withFollowUpState(a,b){let c=new Set(a);return this.followUpQueue.map(a=>c.has(a.id)?{...a,state:b}:a)}queueReceiptBase(){return{revision:this.followUpQueueRevision,items:this.visibleFollowUp(),inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}reject(a,b){return{submissionId:a,sessionId:this.realSessionId,status:"rejected",reason:b}}isQueueMediaRefAlive(a){let b="model"===a.role?8388608:k.Md,c=(0,k.vy)(a.path,this.agentDir);return null!==c&&c<=b}validateQueueMedia(a){if(!a?.length)return!0;if(a.length>l.ym)return!1;let b=0;for(let c of a){let a=(0,k.vy)(c.path,this.agentDir);if(null===a)return!1;let d="model"===c.role?8388608:k.Md;if(a>d||(b+=a,c.previewPath&&null===(0,k.vy)(c.previewPath,this.agentDir)))return!1}return b<=k.Lj}readQueueModelImages(a){let b=[],c=[];for(let d of(0,l.Ot)(a)){if("model"!==d.role)continue;let a=(0,k.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b,missing:c}}queueBinaryBlocks(a){return(0,l.Ot)(a).filter(a=>"original"===a.role).map(a=>({path:a.path,name:a.name,mimeType:a.mimeType,size:a.size,...a.previewPath?{previewPath:a.previewPath}:{}}))}writeFollowUpQueue(a,b){if(null!==b&&b!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};for(let b of a)if(!this.validateQueueMedia(b.media))return{ok:!1,persist:!0,...this.queueReceiptBase()};let c=this.followUpQueue.filter(a=>"claimed"===a.state),d=this.followUpQueue.filter(a=>"claimed"!==a.state),e=[...c,...(0,l.Pt)(d,a,{inFlightIds:c.map(a=>a.id)})];return this.commitFollowUpQueue(e,"set",a.map(a=>a.attemptId))?{ok:!0,...this.queueReceiptBase()}:{ok:!1,persist:!0,...this.queueReceiptBase()}}recallFollowUpQueue(a){let b=[],c=[];for(let d of a){let a=this.followUpQueue.find(a=>a.id===d);if(!a){c.push({id:d,reason:"missing"});continue}if("claimed"===a.state){c.push({id:d,reason:"claimed"});continue}b.push(a)}if(!b.length)return{ok:!0,...this.queueReceiptBase(),recalled:[],skipped:c};let d=new Set(b.map(a=>a.id)),e=this.followUpQueue.filter(a=>!d.has(a.id));return this.commitFollowUpQueue(e,"recall")?(this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,...this.queueReceiptBase(),recalled:b,skipped:c}):{ok:!1,persist:!0,...this.queueReceiptBase(),recalled:[],skipped:c}}enqueuePayloads(a,b,c){let d=this.writeFollowUpQueue([...this.visibleFollowUp().map(a=>({text:a.text})),...b],null);return d.ok?(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer(),{submissionId:a,sessionId:this.realSessionId,status:"queued",action:"queued",...c?{reason:c}:{},queue:{items:d.items,inFlight:d.inFlight,revision:d.revision,admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}):this.reject(a,"error")}queueMediaFromPromptImages(a){if(!a?.length)return{media:void 0,ok:!0};let b=[];for(let[c,d]of a.entries()){let a;if("ref"===d.type){let a=(0,k.vy)(d.path,this.agentDir);if(null===a||a>8388608)return{media:void 0,ok:!1};b.push({role:"model",path:d.path,name:d.path.split(/[\\/]/).pop()??`image-${c}`,mimeType:d.mimeType,size:a});continue}try{a=(0,k.ki)(`prompt-image-${c}.${function(a){let b=a.split(";")[0].trim().toLowerCase();return"image/jpeg"===b?"jpg":"image/svg+xml"===b?"svg":b.startsWith("image/")?b.slice(6).replace(/[^a-z0-9]/g,"")||"png":"bin"}(d.mimeType)}`,Buffer.from(d.data,"base64"),this.agentDir)}catch(a){return console.error("[pidance] inline prompt image could not be stored:",a),{media:void 0,ok:!1}}b.push({role:"model",path:a.path,name:a.name,mimeType:d.mimeType,size:a.size})}return{media:b,ok:!0}}resolvePromptImages(a){if(!a?.length)return{images:void 0,missing:[]};let b=[],c=[];for(let d of a){if("ref"!==d.type){b.push(d);continue}let a=(0,k.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b.length?b:void 0,missing:c}}async dispatchFollowUpQueue(a){if(this.bashRunning)return{ok:!1,status:"rejected",reason:"bash",...this.queueReceiptBase()};if(this.session.isCompacting)return{ok:!1,status:"rejected",reason:"compacting",...this.queueReceiptBase()};if(this.flushingFollowUp||this.dispatchingFollowUpQueue)return{ok:!1,conflict:!0,reason:"in-flight",...this.queueReceiptBase()};if(null!==a.expectedRevision&&a.expectedRevision!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};let b=this.waitingFollowUp(),c=a.extra?.trim();if(0===b.length&&!c)return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};let{text:d}=(0,l.X_)(b,c),e=this.readQueueModelImages(b);if(e.missing.length)return console.error("[pidance] queued media missing, dispatch rejected:",e.missing),{ok:!1,status:"rejected",reason:"media",...this.queueReceiptBase()};let f=this.queueBinaryBlocks(b),g=b.map(a=>a.media?.length?(0,l.ko)(a.text,"claimed",a.media):(0,l.ko)(a.text,"claimed"));c&&g.push((0,l.ko)(c,"claimed"));let h=g.map(a=>a.id),i=new Set(h),j=[...this.followUpQueue.filter(a=>"waiting"!==a.state),...g];if(!this.commitFollowUpQueue(j,"dispatch-claim",[a.extraAttemptId]))return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};this.dispatchingFollowUpQueue=!0,this.emitQueueChanged();let k=e.images.length?e.images:void 0,m="prompt";try{if(this.session.isStreaming)m="steer",await this.session.steer(d,k);else{let a=await this.send({type:"prompt",message:d,...k?.length?{images:k}:{},...f.length?{binaryBlocks:f}:{},streamingBehavior:"steer"},this.internalPromptTicket);if(a?.status==="queued")return m="queued",this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-queued"),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:m,...this.queueReceiptBase()};if(a?.status!=="accepted")return this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release"),this.emitQueueChanged(),{ok:!1,status:"rejected",reason:a?.reason??"error",...this.queueReceiptBase()}}}catch(b){let a=this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release");return this.emitQueueChanged(),a||this.emit({type:"follow_up_flush_error",errorMessage:"dispatch rejected and the claim could not be released; it stays claimed for the user to inspect",...this.queueReceiptBase()}),{ok:!1,status:"rejected",reason:(0,t.K2)(b),...this.queueReceiptBase()}}finally{this.dispatchingFollowUpQueue=!1}let n=(0,l.Ot)(g);return this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-deliver")&&this.discardDeliveredModelMedia(n),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:m,...this.queueReceiptBase()}}scheduleFollowUpFlush(){if(!this._alive||!this.runtime||this.flushingFollowUp||this.followUpFlushBlocked||this.isFollowUpHeld()||this.dispatchingFollowUpQueue||!this.isSettled())return;let a=this.waitingFollowUp();if(0===a.length)return;let b=!0===(0,h.rV)(this.agentDir).queueFlushAsOne;this.flushingFollowUp=!0,this.followUpFlushUnits=b?[{ids:a.map(a=>a.id)}]:a.map(a=>({ids:[a.id]})),this.followUpFlushCursor=0,this.sendNextFollowUp()}emitQueueChanged(){let a=this.queueReceiptBase();this.emit({type:"follow_up_queue_changed",sessionId:this.realSessionId,items:a.items,revision:a.revision,inFlight:a.inFlight,admittedAttemptIds:a.admittedAttemptIds})}async sendNextFollowUp(){if(this.followUpSending||!this.flushingFollowUp)return;if(this.isFollowUpHeld())return void this.abortFollowUpFlush();let a=this.followUpFlushUnits[this.followUpFlushCursor];if(void 0===a)return void this.finishFollowUpFlush();if(!this.isSettled())return void setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushUnits[this.followUpFlushCursor]===a&&this.sendNextFollowUp()},80);this.followUpSending=!0;try{await this.deliverFollowUpUnit(a)}finally{this.followUpSending=!1}this.flushingFollowUp&&(this.followUpFlushCursor+=1,this.followUpFlushCursor>=this.followUpFlushUnits.length?this.finishFollowUpFlush():this.sendNextFollowUp())}async deliverFollowUpUnit(a){let b=new Set(a.ids),c=this.followUpQueue.filter(a=>b.has(a.id)&&"waiting"===a.state);if(0===c.length)return void this.emitQueueChanged();let d=c.map(a=>a.id),e=(0,l.X_)(c).text,{images:f,missing:g}=this.readQueueModelImages(c),h=this.queueBinaryBlocks(c);if(g.length){console.error("[pidance] queued image missing, delivery blocked:",g),this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"queued image is missing; delivery blocked",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}let i=f.length?f:void 0;if(this.session.isCompacting||this.bashRunning){this.emit({type:"follow_up_flush_error",errorMessage:this.session.isCompacting?"follow-up delivery deferred while compaction is running":"follow-up delivery deferred while a shell command is running",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}if(!this.commitFollowUpQueue(this.withFollowUpState(d,"claimed"),"claim")){this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"failed to persist follow-up queue before delivery",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}this.emitQueueChanged();let j=null;try{j=await this.send({type:"prompt",message:e,...i?{images:i}:{},...h.length?{binaryBlocks:h}:{}},this.internalPromptTicket)}catch(c){let a=c instanceof Error?c.message:String(c),b=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:a,...this.queueReceiptBase()}),this.abortFollowUpFlush(),b&&this.emitQueueChanged();return}if(j?.status==="queued"){this.commitFollowUpQueue(this.followUpQueue.filter(a=>!new Set(d).has(a.id)),"deliver-queued"),this.emitQueueChanged(),this.abortFollowUpFlush();return}if(j&&"accepted"!==j.status){let a=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:`follow-up prompt rejected: ${j.reason??"unknown"}`,...this.queueReceiptBase()}),this.abortFollowUpFlush(),a&&this.emitQueueChanged();return}let k=new Set(d),m=(0,l.Ot)(c),n=this.commitFollowUpQueue(this.followUpQueue.filter(a=>!k.has(a.id)),"deliver");n&&this.discardDeliveredModelMedia(m),this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:e,...this.queueReceiptBase()}),n||this.emit({type:"follow_up_flush_error",errorMessage:"follow-up delivered but queue removal was not persisted",...this.queueReceiptBase()}),this.emitQueueChanged()}abortFollowUpFlush(){this.flushingFollowUp&&(this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer())}finishFollowUpFlush(){this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.scheduleFollowUpFlush()}get session(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.session}get services(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.services}syncIdentityFromSession(){let a=this.session,b=a.sessionId||this.realSessionId,c=a.sessionFile||this.realSessionFile,d=this.realSessionId;this.realSessionId=b,this.realSessionFile=c,c&&this.options.cacheSessionPath?.(b,c),d!==b&&this.options.onSessionRekeyed?.(d,b,this)}async rebindSession(){let a=this.session;this.extensionUi?.dispose(),this.extensionUi=(0,p.t)(a=>{this.trackExtensionSideEffects(a),this.emit(a)}),await a.bindExtensions({uiContext:this.extensionUi.uiContext,mode:"rpc",commandContextActions:{waitForIdle:()=>a.waitForIdle(),newSession:async a=>{let b=await this.runtime.newSession(a);return b.cancelled||await this.rebindSession(),b},fork:async(a,b)=>{let c=await this.runtime.fork(a,b);return c.cancelled||await this.rebindSession(),{cancelled:c.cancelled}},navigateTree:async(b,c)=>({cancelled:(await a.navigateTree(b,{summarize:c?.summarize,customInstructions:c?.customInstructions,replaceInstructions:c?.replaceInstructions,label:c?.label})).cancelled}),switchSession:async(a,b)=>{let c=await this.runtime.switchSession(a,b);return c.cancelled||await this.rebindSession(),c},reload:async()=>{await a.reload()}},onError:a=>{this.setFollowUpHeld(!0),this.emit({type:"extension_error",extensionPath:a.extensionPath,event:a.event,error:a.error})}}),this.unsubscribe?.(),this.unsubscribe=a.subscribe(a=>{this.resetIdleTimer(),this.handleSessionEvent(a)}),this.syncIdentityFromSession()}trackExtensionSideEffects(a){if("extension_ui_request"!==a.type)return;let b=z(a.method);if("setStatus"===b){let b=z(a.statusKey)??z(a.key)??"default",c=z(a.statusText)??z(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=z(a.widgetKey)??z(a.key)??"default",c=a.widgetLines??a.content;null==c?this.extensionUi?.widgets.delete(b):this.extensionUi?.widgets.set(b,{lines:c,placement:a.widgetPlacement})}this.notifyRunning()}maybeAutoNameSession(){try{let a=this.session?.sessionManager;if(!a||a.getSessionName())return;let b=(a.buildSessionContext().messages??[]).find(a=>"user"===a.role),c=function(a){let b="";"string"==typeof a?b=a:Array.isArray(a)&&(b=a.filter(a=>"object"==typeof a&&null!==a&&"text"===a.type&&"string"==typeof a.text).map(a=>a.text).join("\n"));let c=b.replace(/\s+/g," ").trim();if(c)return c.length>60?`${c.slice(0,60)}…`:c}(b?.content);c&&a.appendSessionInfo(c)}catch{}}readStopReasonFromAgentEnd(a){let b=a.messages;if(!Array.isArray(b))return null;for(let a=b.length-1;a>=0;a--){let c=b[a],d=c?.message?.stopReason??c?.stopReason;if("string"==typeof d){if("aborted"===d)return"aborted";if("error"===d||"prompt_error"===d)return"error";return"completed"}}return null}removePendingBinaryBatch(a){this.pendingBinaryBatches=this.pendingBinaryBatches.filter(b=>b.submissionId!==a)}persistPendingBinaryBlocks(a){if(0!==a.length)try{let b=this.session.sessionManager;(0,o.kb)(b);let c=b.getEntries(),d=[...c].reverse().find(a=>"message"===a.type&&a.message?.role==="user"&&"string"==typeof a.id)?.id||b.getLeafId()||void 0;for(let c of a){let a=d?{...c,messageEntryId:d}:c,e=b.appendCustomEntry(u.uG,a);this.emit({type:"message_end",entryId:e,message:(0,u.FH)(a,Date.now())})}(0,o.kb)(b),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] persist binary message failed:",a)}}static hasRenderableContent(a){if(!a)return!1;let b=a.content;return"string"==typeof b?b.length>0:Array.isArray(b)&&b.length>0}static outputTokensOf(a){let b=a?.usage?.output;return"number"==typeof b&&Number.isFinite(b)&&b>=0?b:null}accumulateTurnMetrics(a){let b=Date.now();if("agent_start"===a.type)return this.turnMetrics={startedAt:b,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},!0;if("message_start"===a.type||"message_update"===a.type){let c=a.message;if(c?.role==="user")return!1;if(null===this.turnMetrics.firstTokenAt&&C.hasRenderableContent(c)){this.turnMetrics.firstTokenAt=b;let a=null===this.turnMetrics.ttftMs;return a&&this.turnMetrics.startedAt>0&&b>=this.turnMetrics.startedAt&&(this.turnMetrics.ttftMs=b-this.turnMetrics.startedAt),a}return!1}if("message_end"===a.type){let c=a.message;if(c?.role!=="assistant")return!1;let d=null===this.turnMetrics.firstTokenAt?null:Math.max(0,b-this.turnMetrics.firstTokenAt);this.turnMetrics.firstTokenAt=null;let e=C.outputTokensOf(c);if(null!==d&&null!==e)return this.turnMetrics.decodeMs+=d,this.turnMetrics.outputTokens+=e,this.turnMetrics.sampled=!0,!0}return!1}projectTurnMetrics(){let a={};return null!==this.turnMetrics.ttftMs&&this.turnMetrics.startedAt>0&&(a.ttftMs=this.turnMetrics.ttftMs),this.turnMetrics.sampled&&this.turnMetrics.decodeMs>0&&(a.tokensPerSecond=this.turnMetrics.outputTokens/(this.turnMetrics.decodeMs/1e3)),a}handleSessionEvent(a){let b=this.accumulateTurnMetrics(a),c="agent_start"===a.type?++this.streamRunSeq:this.streamRunSeq;switch(a.type){case"agent_start":this.promptRunning=!0,(0,j.NK)(this.realSessionId,Date.now()),this.notifyRunning();break;case"agent_end":this.promptRunning=!1,this.lastStopReason=this.readStopReasonFromAgentEnd(a)??this.lastStopReason??"completed",("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.setFollowUpHeld(!0),(0,j.PI)(this.realSessionId),this.options.onSessionListInvalidate?.(),this.realSessionFile&&(0,n.$9)(this.realSessionFile),this.maybeAutoNameSession(),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});break;case"agent_settled":this.promptRunning=!1,this.notifyRunning(),"completed"===this.lastStopReason?this.flushingFollowUp?this.sendNextFollowUp():this.scheduleFollowUpFlush():this.flushingFollowUp&&("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.abortFollowUpFlush();let d="agent_settled"===a.type&&!this.flushingFollowUp&&(!this.hasWaitingFollowUp()||this.isFollowUpHeld())&&!this.hasActiveSubagentRun();this.resetIdleTimer(),d&&this.destroyAsync().catch(()=>{});break;case"compaction_start":case"auto_compaction_start":this.notifyRunning();break;case"compaction_end":case"auto_compaction_end":this.notifyRunning(),!0!==a.aborted&&!a.errorMessage&&this.isSettled()&&this.scheduleFollowUpFlush(),this.resetIdleTimer();break;case"message_end":{let b=a.message;if(b?.role==="user"){let a=this.pendingBinaryBatches.shift();setImmediate(()=>{try{(0,o.kb)(this.session.sessionManager),this.syncIdentityFromSession(),this.persistPendingBinaryBlocks(a?.blocks??[]),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] materialize after user message failed:",a)}})}break}case"queue_update":{let b=Array.isArray(a.steering)?a.steering.filter(a=>"string"==typeof a):[],c=Array.isArray(a.followUp)?a.followUp.filter(a=>"string"==typeof a):[];this.localQueue={steering:b,followUp:c},this.hasQueueSnapshot=!0}}let e=c>0?{...a,streamRunSeq:c}:a;if(b){let a=this.projectTurnMetrics();(void 0!==a.ttftMs||void 0!==a.tokensPerSecond)&&(e={...e,turnMetrics:a})}let f="message_end"===a.type&&a.message?.role==="assistant";if("agent_end"===a.type||f){let a=this.contextUsageSnapshot();a&&(e={...e,contextUsage:a})}this.emit(this.withRenderedToolLines(e))}contextUsageSnapshot(){try{let a=this.session.getContextUsage();if(a&&"number"==typeof a.contextWindow&&a.contextWindow>0)return{contextWindow:a.contextWindow,percent:"number"==typeof a.percent?a.percent:null,tokens:"number"==typeof a.tokens?a.tokens:null}}catch{}}withRenderedToolLines(a){try{if(!this.renderBridgeTheme)return a;switch(a.type){case"tool_execution_update":{if(!this.shouldRenderPartialUpdate(a.toolCallId))return a;let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.args??a.input,{isPartial:!0,expanded:!0,isError:!0===a.isError,resultSlot:!0});if(!c)return a;let d=(0,x.t_)(b,a.partialResult,{expanded:!0,isPartial:!0},c,b=>this.updateToolRenderLastComponent(a.toolCallId,!0,b));return d?{...a,renderedLines:d}:a}case"tool_call":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.input,{isPartial:!1,expanded:!0,isError:!1,resultSlot:!1});if(!c)return a;let d=(0,x.GD)(b,a.input,c,b=>this.updateToolRenderLastComponent(a.toolCallId,!1,b));return d?{...a,renderedCallLines:d}:a}case"tool_result":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.args??a.input,{isPartial:!1,expanded:!0,isError:!0===a.isError,resultSlot:!0});if(!c)return a;let d=(0,x.t_)(b,{content:a.content,details:a.details,isError:!0===a.isError,...void 0!==a.usage?{usage:a.usage}:{}},{expanded:!0,isPartial:!1},c,b=>this.updateToolRenderLastComponent(a.toolCallId,!0,b));return d?{...a,renderedResultLines:d}:a}case"message_start":case"message_end":{let b=a.message;if(b?.role!=="custom"||"string"!=typeof b.customType||""===b.customType)return a;let c=this.session.extensionRunner,d="function"==typeof c?.getMessageRenderer?c.getMessageRenderer(b.customType):void 0,e=(0,x.Mf)(d,a.message,this.renderBridgeTheme);return e?{...a,renderedLines:e}:a}default:return a}}catch{return a}}getToolRenderDefinition(a){if("string"==typeof a&&""!==a)try{return this.session.getToolDefinition(a)}catch{return}}buildToolRenderContext(a,b,c){let d=this.getOrCreateToolRenderState(a);return d?{args:b,toolCallId:a,invalidate:()=>{},lastComponent:c.resultSlot?d.lastResultComponent:d.lastCallComponent,state:d.state,cwd:this.realCwd,executionStarted:!0,argsComplete:!0,isPartial:c.isPartial,expanded:c.expanded,showImages:!1,isError:c.isError}:null}getOrCreateToolRenderState(a){if("string"!=typeof a||""===a)return null;let b=this.toolRenderStates.get(a);return b||(b={state:{},lastCallComponent:void 0,lastResultComponent:void 0,lastPartialRenderAt:void 0},this.toolRenderStates.set(a,b)),b}updateToolRenderLastComponent(a,b,c){if("string"!=typeof a||""===a)return;let d=this.toolRenderStates.get(a);d&&(b?d.lastResultComponent=c:d.lastCallComponent=c)}shouldRenderPartialUpdate(a){if("string"!=typeof a||""===a)return!0;let b=Date.now(),c=this.getOrCreateToolRenderState(a);return!c||(void 0===c.lastPartialRenderAt||!(b-c.lastPartialRenderAt<C.PARTIAL_RENDER_MIN_INTERVAL_MS))&&(c.lastPartialRenderAt=b,!0)}get realCwd(){try{return this.session.sessionManager.getHeader()?.cwd||this.options.cwd}catch{return this.options.cwd}}async start(){try{var a,b;let c=(a=this.realSessionFile,b=this.options.cwd,a?(0,o.G1)(a):(0,o.Qu)(b)),d=c.getCwd()||this.options.cwd,f=this.agentDir,g=this.activeToolNames,h=async({cwd:a,agentDir:b,sessionManager:c,sessionStartEvent:d})=>{let f=(0,w._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),h={name:w.Jv,label:"Send file to user",description:"Publish an agent-created project file as a user-visible attachment with preview/download support.",promptSnippet:"deliver a generated file to the user as a downloadable attachment",promptGuidelines:["When the user needs a generated file, call send_file_to_user; do not only print a local path or paste Base64.","Only report a file as delivered after send_file_to_user returns successfully."],parameters:w.Tv,async execute(a,b,c){let d=await f(b,c);return{content:[{type:"text",text:`Delivered ${d.name} to the user (entry ${d.entryId}).`}],details:d}}},i=await (0,e.createAgentSessionServices)({cwd:a,agentDir:b,resourceLoaderOptions:{appendSystemPromptOverride:w.n3,extensionFactories:[a=>a.registerTool(h)]}});for(let a of i.modelRuntime.getModels())(0,s.yu)(a);return{...await (0,e.createAgentSessionFromServices)({services:i,sessionManager:c,sessionStartEvent:d,tools:g&&g.length>0?g:void 0,noTools:g&&0===g.length?"all":void 0}),services:i,diagnostics:i.diagnostics}};this.runtime=await (0,e.createAgentSessionRuntime)(h,{cwd:d,agentDir:f,sessionManager:c}),this.runtime.setRebindSession(async()=>{await this.rebindSession()}),this.runtime.setBeforeSessionInvalidate(()=>{this.extensionUi?.dispose(),this.unsubscribe?.(),this.unsubscribe=null}),await this.rebindSession(),this.syncIdentityFromSession(),this.hydrateFollowUpQueue(),this.startupHoldTimer=setTimeout(()=>{this.startupHoldTimer=null,this.startupHold=!1,this.resetIdleTimer()},15e3),this.startupHoldTimer.unref?.(),this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.isSettled()&&this.scheduleFollowUpFlush()}catch(a){throw await this.destroyAsync(),a}}projectState(){let a=this.session,b=a.model,c={stateSources:{rpcGetState:!1,sdkSession:!0,sessionStats:!0,localQueue:!0,localExtensionUi:!0},sessionId:this.realSessionId,sessionFile:this.realSessionFile,sessionName:a.sessionName,isStreaming:a.isStreaming,isCompacting:a.isCompacting,isPromptRunning:this.promptRunning,lastStopReason:this.lastStopReason,isBashRunning:this.bashRunning,turnMetrics:this.projectTurnMetrics(),pendingBash:this.bashCommand,autoCompactionEnabled:a.autoCompactionEnabled,steeringMode:a.steeringMode,followUpMode:a.followUpMode,thinkingLevel:a.thinkingLevel,systemPrompt:a.systemPrompt??"",model:b?{id:b.id,provider:b.provider,modelId:b.id}:void 0,messageCount:a.messages.length,pendingMessageCount:a.pendingMessageCount,extensionStatuses:Array.from(this.extensionUi?.statuses.entries()??[],([a,b])=>({key:a,text:b})),extensionWidgets:Array.from(this.extensionUi?.widgets.entries()??[],([a,b])=>({key:a,lines:Array.isArray(b?.lines)?b.lines:[],placement:b?.placement==="belowEditor"?"belowEditor":"aboveEditor"})),pendingExtensionRequests:Array.from(this.extensionUi?.pendingSnapshot.values()??[]),activeCustomUi:this.extensionUi?.customSnapshot??null};c.queuedMessages={steering:this.hasQueueSnapshot?[...this.localQueue.steering]:[],followUp:(0,l.gC)(this.visibleFollowUp()),followUpItems:this.visibleFollowUp(),followUpRevision:this.followUpQueueRevision,inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]};try{let b=a.getContextUsage();b&&"number"==typeof b.contextWindow&&b.contextWindow>0&&(c.contextUsage={contextWindow:b.contextWindow,percent:"number"==typeof b.percent?b.percent:null,tokens:"number"==typeof b.tokens?b.tokens:null})}catch{}return c}appendActivity(a){if(!this.runtime)throw Error("Cannot append activity: session not alive");let b=a&&"object"==typeof a&&"type"in a&&"append_activity"===a.type?(0,m.qF)(a):(0,m.l$)(a),c=this.session.sessionManager.appendCustomEntry(m.cP,b);return this.options.onSessionListInvalidate?.(),{entryId:c,activity:b}}appendBinary(a,b){if(!this._alive||!this.runtime||this.destroyPromise)throw Error("Cannot append binary message: session not alive");let c=this.session.sessionManager;if(b&&c!==b)throw Error("Cannot publish file after the session changed");let d=a&&"object"==typeof a&&!Array.isArray(a)?a:{},e="append_binary"===d.type?d.binaryBlock:a,f=(0,v.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(u.uG,f);try{this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] binary message list notification failed:",a)}try{this.emit({type:"message_end",entryId:g,message:(0,u.FH)(f,Date.now())})}catch(a){console.error("[pidance] binary message event notification failed:",a)}return{entryId:g,binary:f}}async send(a,b){if(!this.runtime)throw Error("SDK session is not alive");let c=a.type;"get_state"!==c&&"ensure_session"!==c&&this.releaseStartupHold(),this.activeCommandCount+=1,this.resetIdleTimer();let d=this.session;try{switch(c){case"prompt":{let c=(0,t.JT)(a),e=this.promptReceipts.get(c.submissionId);if(e)return e;let f=c.submissionId,g=this.promptInFlight.get(f);if(g)return g;let h=(0,v.Nu)(c.binaryBlocks,this.agentDir),k=c.images??a.images,l=this.resolvePromptImages(k);if(l.missing.length){console.error("[pidance] prompt image missing on disk:",l.missing);let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}if(this.bashRunning&&!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"bash");return this.promptReceipts.set(c.submissionId,a),a}if(d.isCompacting&&!(0,r.D)(c.message)){let a=this.queueMediaFromPromptImages(k);if(!a.ok){let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}let b=this.enqueuePayloads(c.submissionId,[{text:c.message,...a.media?.length?{media:a.media}:{}}],"compacting");return this.promptReceipts.set(c.submissionId,b),this.options.onSessionListInvalidate?.(),b}if(this.flushingFollowUp&&b!==this.internalPromptTicket&&!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}if((this.promptRunning||d.isStreaming)&&"steer"!==a.streamingBehavior){if(!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}try{await d.prompt(c.message,{images:l.images,source:"rpc"});let a={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(c.submissionId,a),a}catch{let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}}if(!(0,i.kP)(this.realSessionId))throw Error(i.GT);this.promptRunning=!0,this.lastStopReason=null,(0,j.NK)(this.realSessionId,Date.now()),this.notifyRunning();let m=(async()=>{try{await new Promise((b,e)=>{let g=!1,i=()=>{d.isStreaming||d.isCompacting||this.bashRunning||this.promptRunning&&(this.promptRunning=!1,"aborted"!==this.lastStopReason&&"error"!==this.lastStopReason&&(this.lastStopReason="completed"),(0,j.PI)(this.realSessionId),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq}),this.resetIdleTimer())};d.prompt(c.message,{images:l.images,streamingBehavior:a.streamingBehavior,source:"rpc",preflightResult:a=>{a&&(g=!0,h.length>0&&this.pendingBinaryBatches.push({submissionId:f,blocks:h}),this.syncIdentityFromSession(),this.setFollowUpHeld(!1),this.options.onSessionListInvalidate?.(),b())}}).then(()=>{if(!g){g=!0;try{(0,o.kb)(d.sessionManager)}catch(a){console.error("[pidance] materialize after prompt failed:",a)}this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.(),b()}i()}).catch(a=>{"aborted"!==this.lastStopReason&&(this.lastStopReason="error"),this.setFollowUpHeld(!0),i(),g||(g=!0,e(a))})});let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(f,b),b}catch(g){this.removePendingBinaryBatch(f);let a=(0,t.K2)(g);if(d.isStreaming&&(0,t.in)(a)){let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected",reason:a};return this.promptReceipts.set(f,b),b}this.promptRunning=!1,this.lastStopReason="aborted"===this.lastStopReason?"aborted":"error",this.setFollowUpHeld(!0),(0,j.PI)(this.realSessionId),this.notifyRunning();let b=g instanceof Error?g.message:String(g);this.emit({type:"prompt_error",errorMessage:b}),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});let e={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected"};throw this.promptReceipts.set(f,e),g}finally{this.promptInFlight.delete(f)}})();return this.promptInFlight.set(f,m),m}case"abort":return this.lastStopReason="aborted",this.setFollowUpHeld(!0),this.promptRunning=!1,this.notifyRunning(),await d.abort(),this.notifyRunning(),null;case"get_state":return this.projectState();case"set_model":{let b=String(a.provider??""),c=String(a.modelId??""),e=(0,q.E)(d.modelRuntime,b,c);if(!e)try{e=(await d.modelRuntime.getAvailable()).find(a=>a.provider===b&&a.id===c)}catch{e=void 0}if(!e)throw Error(`Model not found: ${b}/${c}`);return await d.setModel((0,s.eU)(e)),this.options.onSessionListInvalidate?.(),e}case"set_thinking_level":return d.model&&(0,s.yu)(d.model),d.setThinkingLevel(a.level),this.options.onSessionListInvalidate?.(),null;case"compact":{let b=await d.compact("string"==typeof a.customInstructions?a.customInstructions:void 0);return this.options.onSessionListInvalidate?.(),this.notifyRunning(),this.resetIdleTimer(),b}case"steer":{let b=(0,t._3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.steerFlights.get(b.submissionId);if(d)return d;let e=this.runSteerCommand(b);this.steerFlights.set(b.submissionId,e);try{return await e}finally{this.steerFlights.get(b.submissionId)===e&&this.steerFlights.delete(b.submissionId)}}case"dispatch_follow_up_queue":{let b=(0,t.s)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=await this.dispatchFollowUpQueue(b);return this.commandReceipts.set(b.submissionId,d),d}case"recall_follow_up_queue":{let b=(0,t.TJ)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.recallFollowUpQueue(b.itemIds);return this.commandReceipts.set(b.submissionId,d),d}case"set_follow_up_queue":{let b=(0,t.QT)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.writeFollowUpQueue(b.items,b.expectedRevision);return this.commandReceipts.set(b.submissionId,d),d.ok&&(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer()),d}case"follow_up":{let b=(0,t.$3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.queueMediaFromPromptImages(b.images),e=this.bashRunning?this.reject(b.submissionId,"bash"):d.ok?b.message.trim()||d.media?.length?this.enqueuePayloads(b.submissionId,[{text:b.message,...d.media?.length?{media:d.media}:{}}]):this.reject(b.submissionId,"error"):this.reject(b.submissionId,"media");return this.commandReceipts.set(b.submissionId,e),e}case"set_session_name":{let b=String(a.name??"").trim();if(!b)throw Error("Session name cannot be empty");return d.setSessionName(b),this.options.onSessionListInvalidate?.(),null}case"set_auto_compaction":return d.setAutoCompactionEnabled(!!a.enabled),null;case"set_auto_retry":return d.setAutoRetryEnabled(!!a.enabled),null;case"clear_queue":return d.clearQueue();case"get_tools":{let a=d.getAllTools(),b=new Set(d.getActiveToolNames());return{source:"sdk",tools:a.map(a=>({name:a.name,description:a.description??"",active:b.has(a.name)}))}}case"set_tools":{let b=Array.isArray(a.tools)?a.tools.filter(a=>"string"==typeof a):[];return d.setActiveToolsByName(b),this.activeToolNames=b,null}case"get_commands":{let a=[];for(let b of d.extensionRunner.getRegisteredCommands())a.push({name:b.invocationName,description:b.description,source:"extension",sourceInfo:b.sourceInfo});for(let b of d.promptTemplates)a.push({name:b.name,description:b.description,source:"prompt_template"});try{let b=d.resourceLoader?.getSkills?.();for(let c of b?.skills??[])a.push({name:`skill:${c.name}`,description:c.description,source:"skill",sourceInfo:c.sourceInfo})}catch{}return{commands:a}}case"get_session_stats":return d.getSessionStats();case"bash":if(d.isStreaming)throw Error("Cannot run bash while agent is streaming");this.bashRunning=!0,this.bashCommand={command:String(a.command??""),excludeFromContext:!!a.excludeFromContext,startedAt:Date.now()},this.notifyRunning();try{return await d.executeBash(String(a.command??""),void 0,{excludeFromContext:!!a.excludeFromContext})}finally{this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),this.resetIdleTimer()}case"abort_bash":return d.abortBash(),this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),null;case"abort_compaction":return d.abortCompaction(),null;case"extension_ui_response":{let b=z(a.id);if(!b)throw Error("extension_ui_response requires id");let c={...a};return delete c.type,delete c.id,!this.extensionUi?.respond(b,c),this.notifyRunning(),null}case"extension_ui_input":{let b=z(a.id),c="string"==typeof a.data?a.data:"";return b&&this.extensionUi?.inputCustom(b,c),null}case"append_activity":return this.appendActivity(a);case"append_binary":return this.appendBinary(a);case"fork":{if(this.bashRunning)throw Error("Cannot fork while a shell command is running");let b=String(a.entryId??"");if(!b)throw Error("entryId is required");let c=await this.runtime.fork(b);return c.cancelled||(await this.rebindSession(),this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.()),{cancelled:c.cancelled,newSessionId:c.cancelled?void 0:this.realSessionId,text:c.selectedText}}case"navigate_tree":{if(this.bashRunning)throw Error("Cannot navigate while a shell command is running");let b=z(a.targetId);if(!b)throw Error("targetId is required");let c=await d.navigateTree(b,{summarize:a.summarize,customInstructions:z(a.customInstructions)});if(!c.cancelled&&this.realSessionFile){d.sessionManager.getLeafId();let a=d.sessionManager.getLeafId(),b=d.sessionManager.getEntries(),c=b.at(-1)?.id;a&&c&&a!==c?(0,n.R3)(this.realSessionFile,a):this.realSessionFile&&(0,n.$9)(this.realSessionFile)}return this.options.onSessionListInvalidate?.(),{cancelled:c.cancelled}}case"select_leaf_exact":{let b=z(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.selectLeafExact(this.sessionId,b,a)}let e=await d.navigateTree(b,{summarize:!1});if(!e.cancelled&&this.realSessionFile){let a=d.sessionManager.getLeafId(),b=d.sessionManager.getEntries().at(-1)?.id;a&&b&&a!==b?(0,n.R3)(this.realSessionFile,a):(0,n.$9)(this.realSessionFile)}return{cancelled:e.cancelled}}case"branch_from_assistant":{let b=z(a.assistantEntryId);if(!b)throw Error("assistantEntryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.branchFromAssistant(this.sessionId,b,a)}throw Error("branch_from_assistant is unavailable")}case"create_session_from_leaf":{let b=z(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.createSessionFromLeaf(this.sessionId,b,a)}throw Error("create_session_from_leaf is unavailable")}case"set_branch_label":{let b=z(a.targetId);if(!b)throw Error("targetId is required");let c=void 0===a.label||null===a.label?void 0:String(a.label);return d.sessionManager.appendLabelChange(b,c),this.options.onSessionListInvalidate?.(),null}case"reload":return await d.reload(),await this.rebindSession(),null;case"get_last_assistant_text":return{text:d.getLastAssistantText()};case"ensure_session":return null;default:throw Error(`Unsupported command: ${c}`)}}finally{this.activeCommandCount=Math.max(0,this.activeCommandCount-1),0===this.activeCommandCount&&this.resetIdleTimer()}}destroy(){this.destroyAsync().catch(()=>{})}async destroyAsync(){return this.destroyExcluding(0)}destroyExcluding(a){if(this.destroyPromise)return this.destroyPromise;if(!this._alive&&!this.runtime)return Promise.resolve();if(this.activeCommandCount-a>0){let b=this.pendingDestroys.get(a);return b||(b=this.destroyWhenCommandsSettle(a),this.pendingDestroys.set(a,b)),b}return this.beginDispose()}destroyWhenCommandsSettle(a){let b=(async()=>{let b=Date.now()+this.destroyWaitMs;for(;this.activeCommandCount-a>0;){if(Date.now()>=b)throw Error(B);await new Promise(a=>{let b=setTimeout(a,25);b.unref?.()})}return this.beginDispose()})().finally(()=>{this.pendingDestroys.get(a)===b&&this.pendingDestroys.delete(a)});return b}beginDispose(){return this.destroyPromise||(this._alive=!1,this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null,this.startupHold=!1,this.destroyPromise=(async()=>{this.unsubscribe?.(),this.unsubscribe=null,this.extensionUi?.dispose(),this.extensionUi=null;let a=this.runtime;if(this.runtime=null,a)try{await a.dispose()}catch(a){console.error("[pidance] sdk runtime dispose error:",a)}for(let a of(this.promptRunning=!1,this.bashRunning=!1,this.bashCommand=null,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,(0,j.PI)(this.realSessionId),[...this.destroyCallbacks]))try{a()}catch(a){console.error("[pidance] sdk host destroy listener error:",a)}this.destroyCallbacks.clear(),this.notifyRunning()})()),this.destroyPromise}}async function A(a){let b=new C(a);return await b.start(),b}d()}catch(a){d(a)}})},5815:(a,b,c)=>{c.d(b,{MG:()=>h,NK:()=>f,PI:()=>g});let d="__piRunningStartedAt";function e(){let a=globalThis;return d in a&&a[d]instanceof Map||(a[d]=new Map),a[d]}function f(a,b){let c=e();c.has(a)||c.set(a,b)}function g(a){e().delete(a)}function h(){return e()}},23828:(a,b,c)=>{c.d(b,{D:()=>d});function d(a){return a.trim().startsWith("/")}},25252:(a,b,c)=>{c.d(b,{HM:()=>e,wz:()=>f});var d=c(50593);function e(){return globalThis.__piAdditionalAllowedRoots||(globalThis.__piAdditionalAllowedRoots=new Set),globalThis.__piAdditionalAllowedRoots}function f(a){if(!a)return;let b=(0,d.Nw)(a);e().add(b),globalThis.__piAllowedRootsCache?.roots.add(b)}},26773:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>u,A4:()=>m,DU:()=>o,EM:()=>r,Fn:()=>t,HG:()=>q,OF:()=>w});var e=c(40402),f=c(95237);c(68524);var g=c(2416),h=c(5815),i=c(89953),j=a([e,f,g]);function k(){if(!globalThis.__piSessions){globalThis.__piSessions=new Map;let a=()=>{globalThis.__piSessions?.forEach(a=>a.destroy())};process.once("exit",a),process.once("SIGINT",a),process.once("SIGTERM",a)}return globalThis.__piSessions}function l(){return globalThis.__piStartLocks||(globalThis.__piStartLocks=new Map),globalThis.__piStartLocks}function m(a){return k().get(a)}function n(){return[...l().keys()]}async function o(a){let b=l().get(a);if(!b)return null;try{return(await b).realSessionId}catch{return null}}function p(){let a=new Set(n());for(let[b,c]of k())c.isRunning()&&a.add(c.sessionId||b);return[...a]}function q(){return p()}[e,f,g]=j.then?(await j)():j;let y=new Map;function r(a,b=Date.now()){let c={},d=(0,h.MG)(),e=p(),f=new Set(e);for(let a of e){let e=d.get(a)??y.get(a)??b;y.set(a,e),c[a]=e}for(let a of[...y.keys()])f.has(a)||y.delete(a);return c}function s(){return globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners}function t(a){let b=s();return b.add(a),()=>{b.delete(a)}}function u(){let a=[];for(let[b,c]of k()){let d=c.listPendingExtensionRequests();0!==d.length&&a.push({sessionId:c.sessionId||b,requests:d})}return a}let z="",A=new Set,B=null;function v(){!function a(){let b=new Set(function(){let a=new Set(n());for(let[b,c]of k())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,i.AZ)(a),A.add(a);for(let a of[...A])b.has(a)||((0,i.Hl)(a),A.delete(a));if(0===b.size){B&&(clearInterval(B),B=null);return}B||(B=setInterval(()=>{a()},8e3),B.unref?.())}();let a=q(),b=u(),c=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(c!==z)for(let b of(z=c,s()))try{b(a)}catch{}}async function w(a,b,c,d,e){return x(a,b,c,d,e)}async function x(a,b,c,d,f){let h=k(),j=l(),m=h.get(a);if(m?.isAlive())return{session:m,realSessionId:a};let n=j.get(a);if(n)return n;if(!(0,i.kP)(a))throw Error(i.GT);v();let o=(async()=>{try{let j=await (0,g.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>v(),onSessionListInvalidate:()=>(0,e.mD)(),cacheSessionPath:(a,b)=>(0,e.O8)(a,b),onSessionRekeyed:(a,b,c)=>{let d;d=k(),a!==b&&d.delete(a),d.set(b,c),a!==b&&((0,i.kP)(b),(0,i.Hl)(a))}}),l=j.sessionId,m=j.sessionFile;return m&&(0,e.O8)(l,m),l!==a&&(0,i.kP)(l),j.onDestroy(()=>{h.get(l)===j&&h.delete(l),a!==l&&h.get(a)===j&&h.delete(a),(0,i.Hl)(l),a!==l&&(0,i.Hl)(a),v()}),h.set(l,j),j.beginExtensionBinding(),{session:j,realSessionId:l}}catch(b){throw(0,i.Hl)(a),v(),b}})().finally(()=>{j.delete(a),v()});return j.set(a,o),o}d()}catch(a){d(a)}})},28121:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Jv:()=>r,Tv:()=>t,_D:()=>q,n3:()=>n});var e=c(89477),f=c(42524),g=c(86697),h=c(26238),i=c(69835),j=c(80547),k=c(1060),l=c(60185),m=a([i,j,l]);[i,j,l]=m.then?(await m)():m;let r="send_file_to_user",s="## Pidance file delivery\nWhen the `send_file_to_user` tool is available and you create a file that the user needs to view, download, or play, call it instead of only printing a local path or embedding Base64. The tool publishes a user-visible attachment message: images keep the original for preview and download, audio/video follow the UI playback size policy, and other files get a download card. Only claim that a file was sent after the tool returns success.";function n(a){return a.some(a=>a===s)?a:[...a,s]}let t={type:"object",additionalProperties:!1,properties:{path:{type:"string",description:"Absolute or current-project-relative path of the file to deliver."},name:{type:"string",description:"Optional filename shown to the user; the source basename is used by default."}},required:["path"]};function o(a){if(a?.aborted)throw a.reason instanceof Error?a.reason:Error("file delivery aborted")}async function p(a,b){let c,d;if("string"!=typeof a||!a.trim())throw Error("path is required");let f=(0,g.resolve)(b,a.trim()),h=(0,j.bk)()?null:await (0,j.mc)();if(h&&!(0,j.A$)(f,h))throw Error("file path is not allowed");try{c=(0,e.lstatSync)(f)}catch{throw Error("file not found")}if(c.isSymbolicLink())throw Error("symbolic-link sources are not allowed");if(!c.isFile())throw Error("path must be a regular file");try{d=(0,e.realpathSync)(f)}catch{throw Error("file path could not be resolved")}if(h&&!(0,j.A$)(d,h))throw Error("file path is not allowed");return{path:d,stat:c}}function q(a){return async function(b,c){let d;o(c);let j=await p(b.path,a.cwd),m=j.path,n="string"==typeof b.name&&b.name.trim()?b.name.trim():(0,g.basename)(m),q="number"==typeof e.constants.O_NOFOLLOW?e.constants.O_NOFOLLOW:0,r="number"==typeof e.constants.O_NONBLOCK?e.constants.O_NONBLOCK:0,s=await (0,f.open)(m,e.constants.O_RDONLY|q|r);try{let b=await s.stat();if(!b.isFile())throw Error("path must be a regular file");if(0!==j.stat.dev&&0!==j.stat.ino&&(b.dev!==j.stat.dev||b.ino!==j.stat.ino))throw Error("file changed during open");if(b.size>i.Gt)throw Error(`file exceeds ${i.Gt} bytes`);o(c);let f=(0,e.createReadStream)("",{fd:s.fd,autoClose:!1,signal:c});d=await (0,i.xd)(n,h.Readable.toWeb(f),a.agentDir,i.Gt),o(c);let g=(0,l.iU)({path:d.path,name:d.name,mimeType:(0,k.cV)(m)??(0,k.X)(m)??(0,k.k2)(m)??(0,k.oC)(m)??({txt:"text/plain",md:"text/markdown",json:"application/json",csv:"text/csv",html:"text/html",xml:"application/xml",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar"})[(0,k.GO)(m)]??"application/octet-stream",size:d.size},a.agentDir),{entryId:p}=a.appendBinary(g);return d=void 0,{entryId:p,name:g.name,size:g.size}}finally{if(await s.close().catch(()=>{}),d)try{(0,e.unlinkSync)(d.path)}catch{}}}}d()}catch(a){d(a)}})},31524:(a,b,c)=>{c.d(b,{Ut:()=>e,eU:()=>f,yu:()=>g});let d=["off","minimal","low","medium","high","xhigh","max"];function e(a,b){return a?d.filter(a=>b?.[a]!==null):["off"]}function f(a){if(!a.reasoning)return a;let b=a.thinkingLevelMap,c={...b??{}},d=!1;for(let a of["xhigh","max"])Object.prototype.hasOwnProperty.call(c,a)&&void 0!==c[a]||(c[a]=a,d=!0);return!d&&b?a:{...a,thinkingLevelMap:c}}function g(a){let b=f(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}},35768:(a,b,c)=>{c.d(b,{EE:()=>r,_2:()=>t,gd:()=>E,st:()=>s});var d=c(89477),e=c.n(d),f=c(62228),g=c.n(f),h=c(86697),i=c.n(h);let j=/^[A-Za-z0-9_-]{1,128}$/,k=/^output-\d+\.log$/,l=new Set(["queued","running","complete","failed","paused","stopped"]),m=new Set(["single","parallel","chain"]),n=new Set(["active_long_running","needs_attention"]),o={readdirSync:a=>e().readdirSync(a),lstatSync:a=>e().lstatSync(a),realpathSync:a=>e().realpathSync(a),readFileSync:(a,b)=>e().readFileSync(a,b),openSync:(a,b)=>e().openSync(a,b),readSync:(a,b,c,d,f)=>e().readSync(a,b,c,d,f),closeSync:a=>e().closeSync(a),fstatSync:a=>e().fstatSync(a),constants:e().constants};function p(a){return a.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}let q=new Set(["running","queued","paused"]);function r(a,b,c=Date.now(),d=9e5){let e="string"==typeof b?b:"";if(!e.endsWith(".jsonl"))return!1;let f=e.slice(0,-6),g=a=>{if("string"!=typeof a||!a||!a.startsWith(f))return!1;let b=a.charAt(f.length);return"/"===b||"\\"===b};for(let b of a??[]){if(!b||"object"!=typeof b||!q.has(b.state))continue;let a=b.lastUpdate??b.startedAt;if("number"!=typeof a||!(c-a>d)){for(let a of b.steps??[])if(g(a?.sessionFile))return!0}}return!1}function s(a){if(null==a||""===a)return 20;if(!/^\d+$/.test(a))return null;let b=Number(a);return!Number.isInteger(b)||b<1||b>50?null:b}function t(a={}){var b,c;let d,e,f,h,n=a.fs??o,q=a.limit??20,r=a.now?.()??Date.now(),s=a.root??(b=a.scope,h=b?.tmpdir?.()??g().tmpdir(),i().join(h,`pi-subagents-${function(a){let b=a?.env??process.env,c=a&&Object.hasOwn(a,"getuid")?a.getuid:process.getuid?.bind(process);if("function"==typeof c)return`uid-${c()}`;for(let a of["USERNAME","USER","LOGNAME"]){let c=b[a];if(c)return`user-${p(c)}`}let d=a&&Object.hasOwn(a,"userInfo")?a.userInfo:g().userInfo;try{let a=d?.().username;if(a)return`user-${p(a)}`}catch{}let e=b.USERPROFILE??b.HOME;if(e)return`home-${p(e)}`;let f=a&&Object.hasOwn(a,"homedir")?a.homedir:g().homedir;try{let a=f?.();if(a)return`home-${p(a)}`}catch{}return"shared"}(b)}`,"async-subagent-runs"));try{let a=n.lstatSync(s);if(a.isSymbolicLink()||!a.isDirectory())return u(r,!1);e=n.realpathSync(s)}catch(a){return v(a),u(r,!1)}try{f=n.readdirSync(s)}catch(a){return v(a),u(r,!1)}f.length>256&&(f=f.slice(0,256));let D=[];for(let a of f)if(j.test(a))try{let b=function(a,b,c,d){var e,f;let g,h,j,n,o=i().join(b,d);try{g=a.lstatSync(o)}catch{return null}if(g.isSymbolicLink()||!g.isDirectory())return null;try{h=a.realpathSync(o)}catch{return null}if(!w(h,c))return null;let p=function(a,b,c){let d=x(a,b,c);if(!d)return null;let{fd:e,size:f}=d;try{if(f<=0||f>2097152)return null;let b=Buffer.alloc(f),c=0;for(;c<f;){let d=a.readSync(e,b,c,f-c,c);if(0===d)break;c+=d}let d=b.subarray(0,c).toString("utf8"),g=JSON.parse(d);if(!g||"object"!=typeof g||Array.isArray(g))return null;return g}catch{return null}finally{try{a.closeSync(e)}catch{}}}(a,i().join(o,"status.json"),c);if(!p)return null;let q=(e=p.state,"string"==typeof e&&l.has(e)?e:void 0);if(!q)return null;let r=(f=p.mode,("string"==typeof f&&m.has(f)?f:void 0)??"single"),s=A(p.startedAt);if(void 0===s)return null;let t="string"==typeof p.runId&&p.runId.trim()?p.runId.trim():d,u=z(p.activityState),v=A(p.endedAt),D=A(p.lastUpdate),E="string"==typeof p.cwd?p.cwd:void 0,F="string"==typeof p.error?p.error:void 0,G=A(p.currentStep),H=A(p.chainStepCount),I=B(p.totalTokens),J=C(p.totalCost),K=function(a){if(!Array.isArray(a))return[];let b=[];for(let c=0;c<a.length;c+=1){let d=a[c];if(!d||"object"!=typeof d||Array.isArray(d)){b.push({index:c,agent:"unknown",status:"unknown"});continue}let e="string"==typeof d.agent&&d.agent?d.agent:"unknown",f={index:c,agent:e,status:"string"==typeof d.status&&d.status?d.status:"unknown"};"string"==typeof d.label&&(f.label=d.label),"string"==typeof d.model&&(f.model=d.model),"string"==typeof d.sessionFile&&(f.sessionFile=d.sessionFile),"string"==typeof d.error&&(f.error=d.error);let g=z(d.activityState);g&&(f.activityState=g),"string"==typeof d.currentTool&&(f.currentTool=d.currentTool);let h=B(d.tokens);h&&(f.tokens=h);let i=C(d.totalCost)??A(d.costUsd);void 0!==i&&(f.costUsd=i);let j=A(d.startedAt);void 0!==j&&(f.startedAt=j);let k=A(d.endedAt);void 0!==k&&(f.endedAt=k),Array.isArray(d.recentOutput)&&(f.recentOutput=function(a){let b=[];for(let c of a){if(b.length>=8)break;"string"==typeof c&&b.push(c.length>200?c.slice(0,200):c)}return b}(d.recentOutput)),b.push(f)}return b}(p.steps),L=function(a,b,c){let d=y(a,b,c,65536);if(!d||!d.text)return[];let e=d.text;if(d.truncated){let a=e.indexOf("\n");a>=0&&(e=e.slice(a+1))}let f=e.split(/\r?\n/).filter(a=>a.trim().length>0),g=[];for(let a=f.length-1;a>=0&&g.length<20;a-=1)try{let b=JSON.parse(f[a]);if(!b||"object"!=typeof b||Array.isArray(b))continue;let c="string"==typeof b.type?b.type:void 0;if(!c)continue;let d={type:c},e=A(b.timestamp)??A(b.ts)??A(b.time);void 0!==e&&(d.timestamp=e);let h="string"==typeof b.message?b.message:"string"==typeof b.error?b.error:void 0;void 0!==h&&(d.message=h.length>200?h.slice(0,200):h),g.push(d)}catch{}return g.reverse(),g}(a,i().join(o,"events.jsonl"),c),M=function(a,b){if("string"!=typeof a||!a.trim())return null;let c=i().basename(a.trim());return k.test(c)?{absPath:i().join(b,c)}:null}(p.outputFile,o);if(M){let b=y(a,M.absPath,c,32768);if(b){let a=b.text;if(b.truncated){let b=a.indexOf("\n");b>=0&&(a=a.slice(b+1))}j=a,n=b.truncated}}let N={id:t,state:q,mode:r,startedAt:s,steps:K,recentEvents:L};return u&&(N.activityState=u),void 0!==v&&(N.endedAt=v),void 0!==D&&(N.lastUpdate=D),void 0!==E&&(N.cwd=E),void 0!==F&&(N.error=F),void 0!==G&&(N.currentStep=G),void 0!==H&&(N.chainStepCount=H),I&&(N.totalTokens=I),void 0!==J&&(N.totalCostUsd=J),void 0!==j&&(N.outputTail=j),void 0!==n&&(N.outputTruncated=n),N}(n,s,e,a);b&&D.push(b)}catch{}return{runs:(c=D,d=a=>{switch(a){case"running":return 0;case"queued":return 1;case"failed":case"stopped":case"paused":return 2;case"complete":return 3;default:return 4}},[...c].sort((a,b)=>{let c=d(a.state)-d(b.state);if(0!==c)return c;let e=a.lastUpdate??a.endedAt??a.startedAt;return(b.lastUpdate??b.endedAt??b.startedAt)-e})).slice(0,Math.min(q,50)),generatedAt:r,rootAvailable:!0}}function u(a,b){return{runs:[],generatedAt:a,rootAvailable:b}}function v(a){return"object"==typeof a&&null!==a&&"code"in a&&"ENOENT"===a.code}function w(a,b){let c=i().resolve(a),d=b.endsWith(i().sep)?b:b+i().sep;return c===b||c.startsWith(d)}function x(a,b,c){try{let d=a.lstatSync(b);if(d.isSymbolicLink()||!d.isFile())return null;let e=a.realpathSync(b);if(!w(e,c))return null;let f="number"==typeof a.constants.O_NOFOLLOW?a.constants.O_NOFOLLOW:0,g=a.openSync(b,a.constants.O_RDONLY|f);try{let c=a.fstatSync?a.fstatSync(g):a.lstatSync(b);if(!c.isFile())return a.closeSync(g),null;return{fd:g,size:c.size}}catch{try{a.closeSync(g)}catch{}return null}}catch{return null}}function y(a,b,c,d){let e=x(a,b,c);if(!e)return null;let{fd:f,size:g}=e;try{if(0===g)return{text:"",truncated:!1,size:0};let b=Math.min(d,g),c=Math.max(0,g-b),e=Buffer.alloc(b),h=0;for(;h<b;){let d=a.readSync(f,e,h,b-h,c+h);if(0===d)break;h+=d}return{text:e.subarray(0,h).toString("utf8"),truncated:g>d,size:g}}finally{try{a.closeSync(f)}catch{}}}function z(a){return"string"==typeof a&&n.has(a)?a:void 0}function A(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}function B(a){if(!a||"object"!=typeof a||Array.isArray(a))return;let b=A(a.input),c=A(a.output),d=A(a.total);if(void 0!==b&&void 0!==c&&void 0!==d)return{input:b,output:c,total:d}}function C(a){return"number"==typeof a&&Number.isFinite(a)?a:!a||"object"!=typeof a||Array.isArray(a)?void 0:A(a.costUsd)}function D(a){let b=a.trim();if(!b)return"";let c=/^[a-zA-Z]:[\\/]/.test(b)||b.startsWith("\\\\")||b.startsWith("//"),d=c?i().win32:i().posix,e=c?b.replace(/\//g,"\\"):b.replace(/\\/g,"/"),f=d.normalize(e);return c?f.toLowerCase():f}function E(a,b){let c=new Map;for(let a of b){if(!0!==a.readOnly||"string"!=typeof a.id||!a.id||"string"!=typeof a.path||!a.path)continue;let b=D(a.path);b&&(c.has(b)||c.set(b,a.id))}let d=a.runs.map(a=>{let b=!1,d=a.steps.map(a=>{if(!a.sessionFile)return a;let d=D(a.sessionFile),e=d?c.get(d):void 0;if(!e){if(void 0===a.sessionId)return a;let c={...a};return delete c.sessionId,b=!0,c}return a.sessionId===e?a:(b=!0,{...a,sessionId:e})});return b?{...a,steps:d}:a}),e=!1;for(let b=0;b<d.length;b+=1)if(d[b]!==a.runs[b]){e=!0;break}return e?{...a,runs:d}:a}},37594:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{C9:()=>L,DQ:()=>K,Md:()=>I,Wl:()=>J,Yz:()=>H,mB:()=>P});var e=c(29021),f=c(716),g=c(33873),h=c(80547),i=c(91898),j=c(60396),k=c(95237),l=c(52960),m=c(79495),n=c(81879),o=c(46935),p=c(31514),q=c(65107),r=c(56429),s=c(40402),t=c(85664),u=c(15461),v=c(76817),w=c(86226),x=c(68524),y=c(89953),z=c(50955),A=c(40239),B=c(5815),C=c(99911),D=c(26773),E=c(2416),F=c(68816),G=a([h,i,k,n,r,s,D,E]);[h,i,k,n,r,s,D,E]=G.then?(await G)():G;let K="Subagent sessions are read-only";class L extends Error{constructor(){super(K)}toString(){return this.message}}async function H(a,b){if(await b(a))throw new L}function I(a){let b=a instanceof Error?a.message:String(a);return a instanceof L||b===K?403:b.includes("Session not found")?404:(0,y.wE)(a)||b===y.GT||b===E.v7||"Session is being deleted"===b||b.includes("closed while its title")?409:500}function J(a){let b=a instanceof Error?a.message:String(a);return"cwd is required"===b||b.startsWith("Directory does not exist:")?400:I(a)}let M="Submission was cancelled",N={listAllSessions:s.dQ,resolveSessionPath:s.os,getRpcSession:r.A4,waitForSessionStart:r.DU,startRpcSession:r.OF,getRunningRpcSessionIds:r.HG,listPendingExtensionUi:r.$k,subscribeRunningSessions:r.Fn,allowFileRoot:h.wz,invalidateSessionListCache:s.mD,openSessionCwd:a=>(0,k.kW)(a).getHeader()?.cwd??process.cwd(),openSessionManager:a=>(0,s.Zx)({filePath:a}),openSessionView:k.kW,reparentSessionFile:k.i5,existsSync:e.existsSync,now:()=>Date.now(),archiveFs:A.Iq},O=["systemPrompt"],P=function(a={}){let b={...N,...a},c=(0,A.Ki)({fs:b.archiveFs,agentDir:b.archiveAgentDir,resolveSessionPath:b.resolveSessionPath,readSessionHeader:s.eP,isReadOnly:async a=>{let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},isRunning:a=>b.getRunningRpcSessionIds().includes(a),getSessionInfo:async a=>(await b.listAllSessions()).find(b=>b.id===a)??null,invalidateSessionListCache:b.invalidateSessionListCache,now:()=>new Date(b.now()).toISOString()}),d=()=>(0,A.$T)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)()),h=new Map,r=new Map,E=a=>{if(r.set(a.submissionId,{info:a,cancelRequested:!1,cancelApplied:!1}),!(r.size<=500))for(let[b,c]of r){if(r.size<=500)break;b!==a.submissionId&&"completed"===c.info.status&&r.delete(b)}},G=async a=>{let c=b.getRpcSession(a);if(c){if("function"==typeof c.destroyAsync)return void await c.destroyAsync();c.isAlive()&&c.destroy()}},I=async(a,b)=>{if(!(0,y.kP)(a))throw Error(y.GT);try{return await b()}finally{(0,y.Hl)(a)}},J=async(a,b,c)=>(c?await c():await G(a),I(a,b)),K={async listSessions(){let a=await b.listAllSessions(),{active:c,archived:e}=(0,A.uD)(a,d());return{sessions:c,archivedSessions:e,archivedCount:e.length,runningSessionIds:b.getRunningRpcSessionIds()}},async listArchivedSessions(){let a=await b.listAllSessions();return(0,A.uD)(a,d()).archived},async listActiveSessions(){let a=await b.listAllSessions();return(0,A.uD)(a,d()).active},listAllSessions:async()=>b.listAllSessions(),async isArchived(a){let c=await b.listAllSessions();return(0,A.YV)(c,d()).has(a)},archiveSession:async a=>c.archiveSession(a),restoreSession:async a=>c.restoreSession(a),archiveSessions:async a=>c.archiveSessions(a),restoreSessions:async a=>c.restoreSessions(a),removeArchiveRecordAfterPermanentDelete(a){(0,A.rQ)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)(),a)},resolvePath:a=>b.resolveSessionPath(a),getSessionInfo:async a=>a&&"string"==typeof a?(await b.listAllSessions()).find(b=>b.id===a)??null:null,async isReadOnly(a){let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},async getReadView(a){let c=await b.resolveSessionPath(a);if(!c)return null;let d=b.getRpcSession(a),e=d?.inner;return d?.isAlive()&&e?.sessionManager?{source:"live",filePath:c,manager:e.sessionManager}:{source:"disk",filePath:c,manager:b.openSessionManager(c)}},getLive(a){let c=b.getRpcSession(a);return c?.isAlive()?c:void 0},getLiveSession:a=>K.getLive(a),isLive:a=>!!K.getLive(a),async ensureLive(a){if(await H(a,K.isReadOnly),h.has(a))throw Error("Session is being deleted");let c=K.getLive(a);if(c)return c;if((0,y.wy)(a))throw Error(y.GT);let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=b.openSessionCwd(d),{session:f}=await b.startRpcSession(a,d,e,void 0,L);return f},destroy(a){b.getRpcSession(a)?.destroy()},async destroyAsync(a){let c=b.getRpcSession(a);c&&("function"==typeof c.destroyAsync?await c.destroyAsync():c.destroy())},deleteSession(a){let c=h.get(a);if(c)return c;let d=(async()=>{await H(a,K.isReadOnly);let c=await b.waitForSessionStart?.(a)??a,d=await b.resolveSessionPath(a);if(!d){try{(0,x.xP)(`sessionQueue.${a}`,null),(0,x.xP)(`sessionQueueHold.${a}`,null)}catch(a){console.error("[pidance] failed to clear queue prefs after missing delete:",a)}return(0,s.BR)(a),b.invalidateSessionListCache(),K.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:0}}if((0,y.wy)(a)||(0,y.wy)(c))throw Error(y.GT);let f=(0,s.eP)(d)?.parentSession,h=(0,s.eP)(d)?.id===a?(0,z.ku)(d,a):[],j=b.getRpcSession(c)??b.getRpcSession(a),k=b.getRunningRpcSessionIds();if(j?.isAlive?.()&&(k.includes(a)||k.includes(c)))try{await j.send({type:"abort"})}catch(a){console.error("[pidance] abort before delete failed:",a)}return await K.destroyAsync(j?.sessionId??c),I(j?.sessionId??c,async()=>{let c=d.replace(/\\/g,"/").split("/").slice(0,-1).join("/");try{for(let a of(0,e.readdirSync)(c).filter(a=>a.endsWith(".jsonl")&&(0,g.join)(c,a)!==d)){let e=(0,g.join)(c,a);try{let a=(0,s.eP)(e);a?.type==="session"&&a.parentSession===d&&(a.id?(await b.waitForSessionStart?.(a.id),await J(a.id,()=>{b.reparentSessionFile(e,f)})):b.reparentSessionFile(e,f))}catch{}}}catch{}try{(0,e.unlinkSync)(d)}catch(a){if("ENOENT"!==a.code)throw a}(0,q.$9)(d);let j=(0,g.resolve)(d.slice(0,-6)),k=(0,z.uq)(h,j,s.BR);try{(0,x.xP)(`sessionQueue.${a}`,null),(0,x.xP)(`sessionQueueHold.${a}`,null)}catch(a){console.error("[pidance] failed to clear queue prefs after delete:",a)}try{(0,i.Fx)()}catch(a){console.error("[pidance] failed to sweep attachments:",a)}return(0,s.BR)(a),b.invalidateSessionListCache(),K.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:k}})})();return h.set(a,d),d.finally(()=>{h.get(a)===d&&h.delete(a)})},async start(a,c,d,e){if(await H(a,K.isReadOnly),h.has(a))throw Error("Session is being deleted");return b.startRpcSession(a,c,d,e,L)},send:async(a,b)=>(await K.ensureLive(a)).send(b),async submitPrompt(a,b){await H(a,K.isReadOnly);let c=(0,l.JT)(b);try{let b=await K.send(a,c);if(b&&"object"==typeof b&&b.status)return b;return{submissionId:c.submissionId,sessionId:a,status:"rejected",reason:"error"}}catch(b){if((0,y.wE)(b))throw b;return{submissionId:c.submissionId,sessionId:a,status:"rejected",reason:(0,l.K2)(b)}}},async getAgentState(a,b){if(await K.isReadOnly(a))return{live:!1,activeRun:!1,readOnly:!0};let c=K.getLive(a);if(!c)return{live:!1,activeRun:!1,...(0,y.wy)(a)?{lockedByOther:!0}:{}};let d=await c.send({type:"get_state"}),e="function"==typeof c.isRunning?!!c.isRunning():!!(d&&(d.isStreaming||d.isPromptRunning||d.isCompacting||d.isBashRunning));return{live:!0,activeRun:e,lockedByOther:!1,state:function(a,b){if(!b?.light||!a||"object"!=typeof a||Array.isArray(a))return a;let c={...a};for(let a of O)delete c[a];return c}(d,b)}},async renameSession(a,c){await H(a,K.isReadOnly);let d=c.trim();if(!d)throw Error("name is required");let e=K.getLive(a);if(e?.isAlive()){await e.send({type:"set_session_name",name:d}),b.invalidateSessionListCache();return}let f=await b.resolveSessionPath(a);if(!f)throw Error("Session not found");await J(a,()=>{b.openSessionView(f).appendSessionInfo(d),b.invalidateSessionListCache()})},async autoNameSession(a){await H(a,K.isReadOnly);let b=await K.ensureLive(a);await b.waitUntilReady?.();let c=await K.getNavigationSnapshot(a);if(!c)throw Error("Session not found");let d=c.context.messages??[],e=(0,m.CL)(),f=await (0,m.K)({messages:d,provider:e.provider,modelId:e.modelId,baseUrl:e.baseUrl,api:e.api,apiKey:e.apiKey,headers:e.headers});if(!b.isAlive())throw Error("The session was closed while its title was being generated. Please try again.");try{await b.send({type:"set_session_name",name:f.title})}catch{await K.destroyAsync(a),await K.renameSession(a,f.title)}return{title:f.title,usage:f.usage??null}},async exportSession(a,c){let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");return(0,n.by)(d,c)},async getNavigationSnapshot(a,c={}){let d=await K.getReadView(a);if(!d)return null;let{filePath:e,manager:f}=d,{leafId:g,tree:h,context:i,header:j,sessionName:k}=(0,s.jK)(f,c),l=j?.parentSession?await (0,s.u1)(j.parentSession):void 0,m=(await b.listAllSessions()).find(b=>b.id===a),n=j?{path:e,id:j.id,cwd:j.cwd??"",name:k,created:j.timestamp,modified:j.timestamp,messageCount:i.totalMessageCount??i.messages.length,firstMessage:m?.firstMessage??"(no messages)",parentSessionId:l,...m?.subagent?{subagent:m.subagent,readOnly:!0}:{}}:null;return{filePath:e,leafId:g,tree:h,context:i,header:j,sessionName:k,parentSessionId:l,info:n}},async getUserMessageOutline(a){let b=await K.getReadView(a);if(!b)return[];let c=b.manager,d=c.getEntries?.()??[],e=(0,s.CM)(d,c.getLeafId());return(0,C.Xm)((0,s.tY)(d,e))},async getContextPage(a,b){let c,d=await K.getReadView(a);if(!d)return{context:null};let e=d.manager,f=e.getEntries?.()??[],g=(0,s.Uv)(f,b.leafId,{deferThinking:b.deferThinking,deferToolResultImages:b.deferToolResultImages}),h=b.limit;if(b.around){let a=(0,o.PV)(g,b.around,h??o._w,{toEnd:!0===b.aroundToEnd});if(!a)return{context:null,notFound:b.around};c=a}else c=b.after?(0,o.WP)(g,b.after,h??o._w):b.before?(0,o.tr)(g,b.before,h??o._w):null!==h?(0,o.G1)(g,h):{...g,hasMoreBefore:!1,totalMessageCount:g.messages.length};return{context:c}},async getEntryThinking(a,b,c){let d=await K.getReadView(a);if(!d)return null;let e=d.manager.getEntries().find(a=>a.id===b);if(!e||"message"!==e.type||e.message?.role!=="assistant")return null;let f=e.message.content?.[c];return f&&(0,p.mv)(f.type)?{thinking:(0,p.Ux)(f)}:null},async getToolResultDetails(a,b){let c=await K.getReadView(a);if(!c)return null;let d=c.manager.getEntries().find(a=>"message"===a.type&&a.message?.role==="toolResult"&&a.message.toolCallId===b);return d?{details:d.message?.details??null,content:Array.isArray(d.message?.content)?d.message.content:[]}:null},async appendActivity(a,c){await H(a,K.isReadOnly);let d=K.getLive(a),e=!!d?.inner?.sessionManager,f=d?.appendActivity;return d?.isAlive()&&e&&"function"==typeof f?await f.call(d,c):await J(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,t.l$)(c),f=b.openSessionView(d).appendCustomEntry(t.cP,e);return b.invalidateSessionListCache(),{entryId:f,activity:e}})},appendCommandEntry:async(a,c)=>(await H(a,K.isReadOnly),await J(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,u.fc)(c);if(!e.command)throw Error("command is required");let f=b.openSessionView(d).appendCustomEntry(u.OE,e);return b.invalidateSessionListCache(),{entryId:f,data:e}})),async createNew({cwd:a,command:c}){let d;if(!a||"string"!=typeof a)throw Error("cwd is required");if(!b.existsSync(a))throw Error(`Directory does not exist: ${a}`);let{provider:e,modelId:g,toolNames:h,thinkingLevel:i,...j}=c,l="string"==typeof j.submissionId?j.submissionId:void 0,m=(d="string"==typeof j.message?j.message:"",`${a}\u0000${d}`);if(l){let a=r.get(l);if(a){if(a.info.fingerprint&&a.info.fingerprint!==m)throw a.info.status="conflict",Error("Submission conflict: this submissionId was already used with different content");if(a.cancelRequested)throw a.info.status="cancelled",Error(M);if(a.info.sessionId)return{sessionId:a.info.sessionId,data:null}}E({submissionId:l,status:"pending",fingerprint:m})}let n=`__new__${(0,f.randomUUID)()}`,{session:o,realSessionId:p}=await b.startRpcSession(n,"",a,h,L),q=l?r.get(l):void 0,s=q?.cancelRequested===!0;q&&(q.info.sessionId=p,q.info.status=s?"cancelled":"starting"),b.allowFileRoot(a),b.invalidateSessionListCache();try{if(s||(e&&g&&await o.send({type:"set_model",provider:e,modelId:g}),i&&await o.send({type:"set_thinking_level",level:i}),l&&r.get(l)?.cancelRequested))throw await K.destroyAsync(p),Error(M)}catch(a){throw q&&(q.info.error=a instanceof Error?a.message:String(a)),a}if("ensure_session"===j.type){try{let a=o.inner,b=a?.sessionManager;b&&"function"==typeof b.getSessionFile&&(0,k.kb)(b)}catch(a){console.error("[pidance] materialize ensure_session failed:",a)}return{sessionId:p,data:null}}let t=await o.send(j);return q&&(q.info.status="accepted",q.info.sessionId=p),{sessionId:p,data:t}},getSubmission(a){let b=r.get(a);return b?{...b.info}:null},cancelSubmission(a){let c=r.get(a);if(!c)return E({submissionId:a,status:"cancelled"}),r.get(a).cancelRequested=!0,Promise.resolve({submissionId:a,status:"pending"});c.cancelRequested=!0;let d=c.info.sessionId;if(!d)return c.info.status="cancelled",Promise.resolve({submissionId:a,status:"pending"});if(c.cancelApplied)return Promise.resolve({submissionId:a,status:"confirmed"});c.cancelApplied=!0,c.info.status="cancelled";let e=b.getRpcSession(d);return e?.isAlive()?(async()=>{try{await e.send({type:"abort"})}catch(a){console.error("[pidance] cancel submission abort failed:",a)}return{submissionId:a,status:"confirmed"}})():Promise.resolve({submissionId:a,status:"confirmed"})},getRunningIds:()=>b.getRunningRpcSessionIds(),getRunningStartedAt(){let a=new Set(b.getRunningRpcSessionIds()),c={};for(let[b,d]of(0,B.MG)())a.has(b)&&(c[b]=d);for(let[b,d]of Object.entries((0,D.EM)()))!a.has(b)||b in c||(c[b]=d);return c},async searchFulltext(a,c={}){let d=await (0,F.s)(a,{limits:void 0!==c.maxHits?{maxHits:c.maxHits}:void 0}),e=c.scope??"active";if("all"===e)return d;let f=await b.listAllSessions(),g=(0,A.$T)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)()),h=(0,A.mT)(d.sessionIds,f,g,e);return{...d,sessionIds:d.sessionIds.filter(a=>h.has(a)),hits:d.hits.filter(a=>h.has(a.sessionId))}},listPendingExtensionUi:()=>b.listPendingExtensionUi(),subscribeRunning:a=>b.subscribeRunningSessions(a),async selectLeafExact(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let f=c.trim(),g=b.getRpcSession(a);if(g?.isAlive?.()&&g.inner?.isBashRunning)throw Error("Cannot switch branch while a shell command is running");return e=async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=b.openSessionView(c),e=d.getLeafId();if(f===e)return{cancelled:!1};if(f===d.getLastEntryId())return(0,q.$9)(c),{cancelled:!1};if(!d.getEntry(f))throw Error(`Entry ${f} not found`);try{return d.branch(f),(0,q.R3)(c,f),{cancelled:!1}}finally{b.invalidateSessionListCache()}},J(a,e,d)},async branchFromAssistant(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("assistantEntryId is required");let f=c.trim(),g=b.getRpcSession(a);if(g?.isAlive?.()&&g.inner?.isBashRunning)throw Error("Cannot branch while a shell command is running");return e=async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=b.openSessionView(c),e=d.getLeafId();if(!e)throw Error("Session has no leaf");let g=d.getBranch(e),h=d.getEntry(f);if(!h)throw Error("Entry not found");if("message"!==h.type||h.message?.role!=="assistant")throw Error("Only assistant messages can be branched from");let i=(0,v.wo)(g,f);try{return d.branch(i),i===d.getLastEntryId()?(0,q.$9)(c):(0,q.R3)(c,i),{cancelled:!1}}finally{b.invalidateSessionListCache()}},J(a,e,d)},async createSessionFromLeaf(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let f=c.trim(),g=b.getRpcSession(a),h=g?.inner;return e=async()=>{let c=(h?.sessionFile||g?.sessionFile)??await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=(0,k.kW)(c),e=d.getEntry(f);if(!e)throw Error("Invalid entry ID");let i=f;if("message"===e.type&&e.message?.role==="assistant"){let a=d.getLeafId();if(!a)throw Error("Session has no leaf");let b=d.getBranch(a);i=(0,v.wo)(b,f)}let j=d.getSessionDir(),l=(0,k.G1)(c,j),m=l.createBranchedSession(i);if(!m)throw Error("Failed to create session");(0,k.kb)(l);let n=(0,k.kW)(m,j),o=n.getSessionId();(0,s.O8)(o,m),b.invalidateSessionListCache();let p=h?.model;return p&&(0,w.yN)(n.getEntries().some(a=>"model_change"===a.type),{provider:p.provider,modelId:p.id})&&n.appendModelChange(p.provider,p.id),{cancelled:!1,newSessionId:o}},J(a,e,d)}},L={selectLeafExact:(a,b,c)=>K.selectLeafExact(a,b,c),branchFromAssistant:(a,b,c)=>K.branchFromAssistant(a,b,c),createSessionFromLeaf:(a,b,c)=>K.createSessionFromLeaf(a,b,c)};return K}();d()}catch(a){d(a)}})},38195:(a,b,c)=>{c.d(b,{t:()=>g});var d=c(716),e=c(87538);function f(a,b,c,e,f,g,h){let i=(0,d.randomUUID)();return new Promise((d,j)=>{let k,l=!1,m=()=>{a.delete(i),b.delete(i),k&&clearTimeout(k),e?.signal?.removeEventListener("abort",o)},n=a=>{l||(l=!0,m(),d(a))},o=()=>n(f);e?.signal?.addEventListener("abort",o,{once:!0}),e?.timeout&&(k=setTimeout(()=>n(f),e.timeout)),a.set(i,{resolve:a=>{try{n(h(a))}catch(a){if(l)return;l=!0,m(),j(a instanceof Error?a:Error(String(a)))}},reject:a=>{l||(l=!0,m(),j(a))}});let p={type:"extension_ui_request",id:i,...g};b.set(i,p),c(p)})}function g(a){let b=new Map,c=new Map,g=new Map,h=new Map,i=new Map,j=null,k={select:(d,e,g)=>f(b,c,a,g,void 0,{method:"select",title:d,options:e,timeout:g?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),confirm:(d,e,g)=>f(b,c,a,g,!1,{method:"confirm",title:d,message:e,timeout:g?.timeout},a=>(!("cancelled"in a)||!a.cancelled)&&"confirmed"in a&&!!a.confirmed),input:(d,e,g)=>f(b,c,a,g,void 0,{method:"input",title:d,placeholder:e,timeout:g?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),notify(b,c){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"notify",message:b,notifyType:c})},onTerminalInput:()=>()=>{},setStatus(b,c){c?g.set(b,c):g.delete(b),a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setStatus",statusKey:b,statusText:c})},setWorkingMessage(){},setWorkingVisible(){},setWorkingIndicator(){},setHiddenThinkingLabel(){},setWidget(b,c,f){if("function"==typeof c){let a=(0,e.tU)(c,(0,e.Lm)());if(null===a)return;c=a}(void 0===c||Array.isArray(c))&&(null==c?h.delete(b):h.set(b,{lines:c,placement:f?.placement}),a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:c,widgetPlacement:f?.placement}))},setFooter(){},setHeader(){},setTitle(b){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setTitle",title:b})},async custom(b){let c=(0,d.randomUUID)();return new Promise(d=>{let f,g=!1,h=b=>{g||(g=!0,i.delete(c),j?.id===c&&(j=null),a({type:"extension_ui_request",id:c,method:"custom",closed:!0,lines:[]}),d(b))},l=()=>{if(g)return;let b=[];try{let a=f?.render?.(92);Array.isArray(a)&&(b=a.filter(a=>"string"==typeof a))}catch(a){console.error("[pidance] custom UI render failed:",a)}a({type:"extension_ui_request",id:c,method:"custom",lines:b}),j={id:c,lines:[...b]}};i.set(c,{handleInput:a=>{if("\x03"===a)return void h(void 0);try{f?.handleInput?.(a)}catch(a){console.error("[pidance] custom UI input failed:",a)}},done:h});let m=function(a,b=92,c=40){return Object.freeze({terminal:Object.freeze({columns:b,rows:c,kittyProtocolActive:!1}),requestRender:a})}(()=>{l()},92,40),n=(0,e.Lm)()??k.theme;Promise.resolve().then(()=>b(m,n,{},h)).then(a=>{g||(f=a,l())}).catch(a=>{console.error("[pidance] custom UI factory failed:",a),h(void 0)})})},pasteToEditor(a){this.setEditorText(a)},setEditorText(b){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"set_editor_text",text:b})},getEditorText:()=>"",editor:async(d,e)=>f(b,c,a,void 0,void 0,{method:"editor",title:d,prefill:e},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){let a=a=>String(a??""),b=(a,b)=>void 0===b?"":String(b);return new Proxy({fg:b,bg:b,bold:a,dim:a,italic:a},{get:(b,c)=>c in b?b[c]:"then"!==c?a:void 0})},getAllThemes:()=>[],getTheme(){},setTheme:()=>({success:!1,error:"Theme switching not supported in Web mode"}),getToolsExpanded:()=>!1,setToolsExpanded(){}};return{uiContext:k,pending:b,statuses:g,widgets:h,pendingSnapshot:c,get customSnapshot(){return j},respond(a,c){let d=b.get(a);return!!d&&(d.resolve(c),!0)},inputCustom(a,b){let c=i.get(a);return!!c&&(c.handleInput(b),!0)},dispose(){for(let[a,d]of b)b.delete(a),c.delete(a),d.reject(Error("Extension UI disposed"));for(let a of i.values())a.done(void 0);i.clear(),j=null,g.clear(),h.clear()}}}},40239:(a,b,c)=>{c.d(b,{$T:()=>m,Iq:()=>g,J3:()=>t,Ki:()=>u,YV:()=>q,mT:()=>r,rQ:()=>p,uD:()=>s});var d=c(29021),e=c(33873),f=c(60396);let g={existsSync:d.existsSync,lstatSync:d.lstatSync,mkdirSync:d.mkdirSync,readFileSync:(a,b)=>(0,d.readFileSync)(a,b),writeFileSync:(a,b,c)=>(0,d.writeFileSync)(a,b,c),renameSync:d.renameSync,unlinkSync:d.unlinkSync,readdirSync:d.readdirSync};function h(a=(0,f.$M)()){return(0,e.join)(a,"pidance-archive")}function i(a){return"string"!=typeof a||a.length<8||a.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(a)?null:`${a}.json`}function j(a,b){try{let c=h(b);if(!a.existsSync(c))return null;let d=a.lstatSync(c);if(d.isSymbolicLink()||!d.isDirectory())return null;return c}catch{return null}}function k(a){return"object"==typeof a&&null!==a&&!(1!==a.version||"string"!=typeof a.sessionId||0===a.sessionId.length||"string"!=typeof a.sessionPath||0===a.sessionPath.length||"string"!=typeof a.archivedAt||Number.isNaN(Date.parse(a.archivedAt)))}function l(a,b,c){let d=i(c);if(!d)return null;let f=j(a,b);if(!f)return null;let g=(0,e.join)(f,d);try{if(!a.existsSync(g)||a.lstatSync(g).isSymbolicLink())return null;let b=a.readFileSync(g,"utf8");if(b.length>65536)return null;let d=JSON.parse(b);if(!k(d)||d.sessionId!==c)return null;return d}catch{return null}}function m(a,b){let c=globalThis.__piArchiveRecordsCache;if(c&&Date.now()-c.ts<5e3)return c.records;let d=j(a,b),e=[];if(d){let c=[];try{c=a.readdirSync(d)}catch{c=[]}for(let d of c){let c=function(a){if("string"!=typeof a||!a.endsWith(".json"))return null;let b=a.slice(0,-5);return b.length<8||b.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(b)?null:b}(d);if(!c)continue;let f=l(a,b,c);f&&e.push(f)}}return globalThis.__piArchiveRecordsCache={records:e,ts:Date.now()},e}function n(){globalThis.__piArchiveRecordsCache=void 0}function o(a,b,c){let d=i(c);if(!d)return!1;let f=j(a,b);if(!f)return!1;let g=(0,e.join)(f,d);try{if(!a.existsSync(g))return!1;return a.unlinkSync(g),n(),!a.existsSync(g)}catch{return!1}}function p(a,b,c){o(a,b,c)}function q(a,b){let c=new Map;for(let a of b)c.set(a.sessionId,a);let d=new Set;for(let b of a){let a=c.get(b.id);a&&a.sessionPath===b.path&&d.add(b.id)}return d}function r(a,b,c,d){let e=q(b,c),f=new Set;for(let b of a){let a=e.has(b);("active"===d?!a:a)&&f.add(b)}return f}function s(a,b){let c=q(a,b),d=new Map;for(let a of b)d.set(a.sessionId,a);let e=[],f=[];for(let b of a)if(c.has(b.id)){let a=d.get(b.id);f.push({...b,archivedAt:a?a.archivedAt:void 0})}else e.push(b);return{active:e,archived:f}}class t extends Error{constructor(){super("Session is running; cannot archive while active")}toString(){return this.message}}function u(a){let b=a.fs??g,c=()=>a.agentDir?.()??(0,f.$M)(),d=async d=>{if(await a.isReadOnly(d))throw Error("Subagent sessions are read-only");if(a.isRunning(d))throw new t;let f=await a.resolveSessionPath(d);if(!f)throw Error("Session not found");let g=a.readSessionHeader(f);if(!g||g.id!==d)throw Error("Session header id mismatch");let j={version:1,sessionId:d,sessionPath:f,archivedAt:a.now()};return!function(a,b,c){let d=i(c.sessionId);if(!d)throw Error("Invalid session id");if(!k(c))throw Error("Invalid archive record");let f=function(a,b){let c=h(b);try{a.existsSync(c)||a.mkdirSync(c,{recursive:!0});let b=a.lstatSync(c);if(b.isSymbolicLink()||!b.isDirectory())return null;return c}catch{return null}}(a,b);if(!f)throw Error("Archive directory unavailable");let g=(0,e.join)(f,d),j=(0,e.join)(f,`.${d}.${process.pid}.${Date.now().toString(36)}.tmp`);try{a.writeFileSync(j,JSON.stringify(c),{encoding:"utf8",flag:"wx"}),a.renameSync(j,g),n()}catch(b){try{a.existsSync(j)&&a.unlinkSync(j)}catch{}throw b}}(b,c(),j),a.invalidateSessionListCache(),j.archivedAt},j=async d=>{if(null===l(b,c(),d))throw Error("Session is not archived");if(!await a.resolveSessionPath(d))throw Error("Session not found");if(!o(b,c(),d))throw Error("Failed to remove archive record");return a.invalidateSessionListCache(),a.getSessionInfo(d)},m=async a=>{let b=[],c=[];for(let e of a)try{await d(e),b.push(e)}catch(a){c.push({id:e,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}},p=async a=>{let b=[],c=[];for(let d of a)try{await j(d),b.push(d)}catch(a){c.push({id:d,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}};return{archiveSession:d,restoreSession:j,archiveSessions:m,restoreSessions:p}}},46935:(a,b,c)=>{c.d(b,{G1:()=>h,NN:()=>g,PV:()=>i,Uf:()=>d,WP:()=>j,_w:()=>e,tr:()=>k});let d=80,e=80;function f(a,b){return"number"==typeof a&&Number.isFinite(a)?Math.max(1,Math.min(Math.floor(a),500)):b}function g(a,b=d){let c=a.get("limit")??a.get("tail");if(null===c||""===c)return null;let e=Number(c);return!Number.isFinite(e)||e<=0?b:f(e,b)}function h(a,b=d){let c=a.messages.length,e=f(b,d);if(c<=e)return{...a,hasMoreBefore:!1,hasMoreAfter:!1,totalMessageCount:c};let g=c-e;return{messages:a.messages.slice(g),entryIds:a.entryIds.slice(g),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:!1,totalMessageCount:c}}function i(a,b,c=e,d={}){let g=a.messages.length,h=a.entryIds.indexOf(b);if(h<0)return null;let j=f(c,e),k=Math.max(0,h-Math.max(1,Math.floor(j/2))),l=d.toEnd?g:Math.min(g,k+j);return{messages:a.messages.slice(k,l),entryIds:a.entryIds.slice(k,l),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:k>0,hasMoreAfter:l<g,totalMessageCount:g}}function j(a,b,c=e){let d=a.messages.length,g=a.entryIds.indexOf(b);if(g<0||g>=d-1)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:!1,totalMessageCount:d};let h=Math.min(d,g+1+f(c,e));return{messages:a.messages.slice(g+1,h),entryIds:a.entryIds.slice(g+1,h),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:h<d,totalMessageCount:d}}function k(a,b,c=e){let d=a.messages.length,g=a.entryIds.indexOf(b);if(g<=0)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!1,hasMoreAfter:!1,totalMessageCount:d};let h=Math.max(0,g-f(c,e));return{messages:a.messages.slice(h,g),entryIds:a.entryIds.slice(h,g),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:h>0,hasMoreAfter:!0,totalMessageCount:d}}},52960:(a,b,c)=>{c.d(b,{$3:()=>o,D_:()=>s,JT:()=>k,K2:()=>g,QR:()=>t,QT:()=>p,TJ:()=>r,_3:()=>n,in:()=>f,s:()=>q});var d=c(13737),e=c(99014);function f(a){return"busy"===a||"compacting"===a||"bash"===a}function g(a){let b=a instanceof Error?a.message:String(a);return/already processing|already running|streamingBehavior/i.test(b)?"busy":/shell command is running/i.test(b)?"bash":/compaction/i.test(b)?"compacting":/cannot be queued|Extension command/i.test(b)?"extension":/no (valid )?model|model not found|未选择模型/i.test(b)?"model":/401|403|unauthor|api key|authentication|permission denied/i.test(b)?"auth":/running lease|locked by another|another process/i.test(b)?"locked":"error"}function h(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`sub-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function i(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("images must be an array");let b=[];for(let c of a){if(!c||"object"!=typeof c)throw Error("invalid image");if("ref"===c.type){let a="string"==typeof c.path?c.path.trim():"",e=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!a||!e?.startsWith("image/"))throw Error("invalid image");b.push({type:"ref",path:a,mimeType:e});continue}let a="string"==typeof c.data?c.data:void 0,e="string"==typeof c.mimeType?c.mimeType:"string"==typeof c.mime_type?c.mime_type:void 0,f=(0,d.Ln)(e);if(!a||!f?.startsWith("image/"))throw Error("invalid image");if(a.length>4194304)throw Error("invalid image: payload too large");b.push({type:"image",data:a,mimeType:f})}return b}function j(a){if("string"!=typeof a.message)throw Error("message is required");return a.message}function k(a,b=h){return{type:"prompt",message:j(a),submissionId:"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b(),images:i(a.images),binaryBlocks:function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("binaryBlocks must be an array");if(a.length>32)throw Error("too many binary blocks");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid binary block");let a="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.name?c.name.trim():"",f=(0,d.Ln)(c.mimeType),g=c.size,h=void 0===c.previewPath?void 0:"string"==typeof c.previewPath?c.previewPath.trim():null;if(!a||!e||!f||!Number.isSafeInteger(g)||g<0||null===h)throw Error("invalid binary block");b.push({path:a,name:e,mimeType:f,size:g,...h?{previewPath:h}:{}})}return b}(a.binaryBlocks)}}function l(a,b){return"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b()}function m(a){if(null==a)return null;if("number"!=typeof a||!Number.isFinite(a)||a<0)throw Error("expectedRevision must be a non-negative number");return a}function n(a,b=h){return{type:"steer",message:j(a),submissionId:l(a,b),images:i(a.images)}}function o(a,b=h){return{type:"follow_up",message:j(a),submissionId:l(a,b),images:i(a.images)}}function p(a,b=h){if(void 0!==a.items&&!Array.isArray(a.items))throw Error("items must be an array");let c=[];for(let b of Array.isArray(a.items)?a.items:[]){let a,f;if("string"==typeof b){if(!b.trim())throw Error("items must not contain empty text");c.push({text:b});continue}if(!b||"object"!=typeof b||Array.isArray(b)||"string"!=typeof b.text)throw Error("items must be strings or { text, media? } objects");let g=function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("invalid queue media");if(0===a.length)return;if(a.length>e.ym)throw Error("invalid queue media: too many refs");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid queue media");let a="model"===c.role||"original"===c.role?c.role:null,e="string"==typeof c.path?c.path.trim():"";if(!a||!e)throw Error("invalid queue media");let f=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!f||"model"===a&&!f.startsWith("image/"))throw Error("invalid queue media");let g="string"==typeof c.name&&c.name.trim()?c.name.trim():"",h=c.size;if(!g||"number"!=typeof h||!Number.isSafeInteger(h)||h<0)throw Error("invalid queue media");let i="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(void 0!==c.previewPath&&!i)throw Error("invalid queue media");b.push({role:a,path:e,name:g,mimeType:f,size:h,...i&&i!==e?{previewPath:i}:{}})}return b.length?b:void 0}(b.media);if(!b.text.trim()&&!g?.length)throw Error("items must not be empty");if(void 0!==b.attemptId&&!(a=(0,e.Kk)(b.attemptId)??void 0))throw Error("invalid item attemptId");if(void 0!==b.id&&!(f=(0,e.mv)(b.id)??void 0))throw Error("invalid item id");c.push({text:b.text,...g?{media:g}:{},...a?{attemptId:a}:{},...f?{id:f}:{}})}return{type:"set_follow_up_queue",items:c,expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function q(a,b=h){let c,d="string"==typeof a.extra?a.extra:void 0;if(void 0!==a.extraAttemptId&&!(c=(0,e.Kk)(a.extraAttemptId)??void 0))throw Error("invalid extraAttemptId");return{type:"dispatch_follow_up_queue",...void 0!==d?{extra:d}:{},...c?{extraAttemptId:c}:{},expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function r(a,b=h){if(!Array.isArray(a.itemIds))throw Error("itemIds must be an array");if(0===a.itemIds.length)throw Error("itemIds must not be empty");if(a.itemIds.length>256)throw Error("too many itemIds");let c=[];for(let b of a.itemIds){let a="string"==typeof b?b.trim():"";if(!a)throw Error("invalid itemId");c.includes(a)||c.push(a)}return{type:"recall_follow_up_queue",itemIds:c,submissionId:l(a,b)}}function s(a){return"prompt"===a||"abort"===a||"steer"===a||"follow_up"===a||"set_follow_up_queue"===a||"dispatch_follow_up_queue"===a||"recall_follow_up_queue"===a}function t(a,b=h){if(!a||"object"!=typeof a||Array.isArray(a))throw Error("command is required");let c=a.type;if("prompt"===c)return k(a,b);if("abort"===c)return{type:"abort"};if("steer"===c)return n(a,b);if("follow_up"===c)return o(a,b);if("set_follow_up_queue"===c)return p(a,b);if("dispatch_follow_up_queue"===c)return q(a,b);if("recall_follow_up_queue"===c)return r(a,b);throw Error(`Unsupported message command: ${String(c)}`)}},53023:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Uj:()=>j});var e=c(85664),f=c(93127),g=c(95237),h=a([f,g]);function i(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}[f,g]=h.then?(await h)():h;let k=`
1
+ "use strict";exports.id=7594,exports.ids=[7594],exports.modules={1060:(a,b,c)=>{c.d(b,{Ac:()=>n,GO:()=>i,X:()=>k,_4:()=>d,cV:()=>j,k2:()=>l,oC:()=>m});let d=262144,e={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},f={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm"},g={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},h={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function i(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function j(a){return e[i(a)]??null}function k(a){return f[i(a)]??null}function l(a){return g[i(a)]??null}function m(a){return h[i(a)]??null}function n(a){let b=i(a);return"pdf"===b||"docx"===b?b:null}},2416:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>A,v7:()=>B});var e=c(75430),f=c(60396),g=c(35768),h=c(68524),i=c(89953),j=c(5815),k=c(69835),l=c(99014),m=c(85664),n=c(65107),o=c(95237),p=c(38195),q=c(62693),r=c(23828),s=c(31524),t=c(52960),u=c(13737),v=c(60185),w=c(28121),x=c(87538),y=a([e,k,o,v,w]);[e,k,o,v,w]=y.then?(await y)():y;let B="Session writer is busy: a command is still in flight";function z(a){return"string"==typeof a&&a?a:void 0}class C{static{this.PARTIAL_RENDER_MIN_INTERVAL_MS=100}constructor(a){this.options=a,this.listeners=[],this.runtime=null,this.unsubscribe=null,this.extensionUi=null,this.idleTimer=null,this.startupHoldTimer=null,this.startupHold=!0,this.activeCommandCount=0,this.destroyCallbacks=new Set,this.pendingDestroys=new Map,this._alive=!0,this.promptRunning=!1,this.streamRunSeq=0,this.lastStopReason=null,this.followUpQueue=[],this.followUpQueueRevision=0,this.followUpQueueHydrated=!1,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,this.internalPromptTicket=Symbol("pidance internal follow-up prompt"),this.followUpFlushBlocked=!1,this.dispatchingFollowUpQueue=!1,this.commandReceipts=new Map,this.bashRunning=!1,this.bashCommand=null,this.localQueue={steering:[],followUp:[]},this.turnMetrics={startedAt:0,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},this.promptReceipts=new Map,this.promptInFlight=new Map,this.steerFlights=new Map,this.pendingBinaryBatches=[],this.destroyPromise=null,this.hasQueueSnapshot=!1,this.renderBridgeTheme=(0,x.Lm)(),this.toolRenderStates=new Map,this.followUpAdmittedAttemptIds=[],this.realSessionId=a.sessionId,this.realSessionFile=a.sessionFile,this.idleTimeoutMs=a.idleTimeoutMs??3e4,this.destroyWaitMs=a.destroyWaitMs??5e3,this.agentDir=a.agentDir??(0,f.$M)(),this.activeToolNames=a.toolNames}get sessionId(){return this.realSessionId}get sessionFile(){return this.realSessionFile}listPendingExtensionRequests(){return Array.from(this.extensionUi?.pendingSnapshot.values()??[])}get inner(){let a=this.runtime?.session;if(a)return{sessionManager:a.sessionManager}}isAlive(){return this._alive&&null!==this.runtime}isRunning(){if(!this._alive||!this.runtime)return!1;let a=this.runtime.session;return this.promptRunning||this.bashRunning||a.isStreaming||a.isCompacting}async runSteerCommand(a){let b=this.session;if(this.bashRunning){let b=this.reject(a.submissionId,"bash");return this.commandReceipts.set(a.submissionId,b),b}if(b.isCompacting&&!b.isStreaming&&!this.promptRunning){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"compacting");return this.commandReceipts.set(a.submissionId,c),c}let c=this.resolvePromptImages(a.images);if(c.missing.length){console.error("[pidance] steer image missing on disk:",c.missing);let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}if(!this.isRunning()&&!this.flushingFollowUp){let b=await this.send({type:"prompt",message:a.message,images:a.images,streamingBehavior:"steer"}),c={...b,submissionId:a.submissionId,action:"accepted"===b.status?"prompt":"queued"};return this.commandReceipts.set(a.submissionId,c),c}if(!b.isStreaming){let b=this.queueMediaFromPromptImages(a.images);if(!b.ok){let b=this.reject(a.submissionId,"media");return this.commandReceipts.set(a.submissionId,b),b}let c=this.enqueuePayloads(a.submissionId,[{text:a.message,...b.media?.length?{media:b.media}:{}}],"busy");return this.commandReceipts.set(a.submissionId,c),c}await b.steer(a.message,c.images);let d={submissionId:a.submissionId,sessionId:this.realSessionId,status:"accepted",action:"steer"};return this.commandReceipts.set(a.submissionId,d),d}onDestroy(a){return this.destroyCallbacks.add(a),()=>{this.destroyCallbacks.delete(a)}}onEvent(a){let b=0===this.listeners.length;return this.listeners.push(a),b&&this.resetIdleTimer(),()=>{let b=this.listeners.length>0;this.listeners=this.listeners.filter(b=>b!==a),b&&0===this.listeners.length&&this.resetIdleTimer()}}beginExtensionBinding(){}async waitForExtensionsBound(){}emit(a){for(let b of this.listeners)try{b(a)}catch(a){console.error("[pidance] sdk host listener error:",a)}}notifyRunning(){this.options.onRunningChange?.()}hasActiveSubagentRun(){let a=this.realSessionFile;if(!a)return!1;try{let{runs:b}=(0,g._2)({limit:50});return(0,g.EE)(b,a)}catch{return!1}}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,!this._alive||!this.runtime||this.startupHold||this.isRunning()||this.flushingFollowUp)return;if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();if(this.listeners.length>0)return;let a=this.idleTimeoutMs;this.idleTimer=setTimeout(()=>{if(this.idleTimer=null,!this.isRunning()&&!this.flushingFollowUp){if(this.hasWaitingFollowUp()&&!this.isFollowUpHeld())return void this.scheduleFollowUpFlush();if(!(this.listeners.length>0)){if(this.hasActiveSubagentRun())return void this.resetIdleTimer();this.destroyAsync().catch(()=>{})}}},a)}releaseStartupHold(){this.startupHold&&(this.startupHold=!1,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null)}isSettled(){return!!this.runtime&&!!this._alive&&!this.isRunning()}isFollowUpHeld(){let a=(0,h.rV)(this.agentDir);return!0===(0,h.ql)(a,`sessionQueueHold.${this.realSessionId}`)}setFollowUpHeld(a){try{(0,h.xP)(`sessionQueueHold.${this.realSessionId}`,!!a||null,this.agentDir)}catch(b){console.error("[pidance] failed to persist follow-up hold:",b),this.emit({type:"follow_up_flush_error",errorMessage:a?"failed to persist follow-up hold; the queue may flush automatically":"failed to clear follow-up hold; the queue may stay held",...this.queueReceiptBase()})}}hydrateFollowUpQueue(){if(this.followUpQueueHydrated)return;this.followUpQueueHydrated=!0;let a=(0,h.rV)(this.agentDir),b=(0,h.ql)(a,`sessionQueue.${this.realSessionId}`),c=(0,l.jG)(b);this.followUpQueue=c.items.map(a=>"claimed"===a.state?{...a,state:"unknown"}:a),this.followUpQueueRevision=c.revision,this.followUpAdmittedAttemptIds=c.admittedAttemptIds,this.followUpQueue=this.followUpQueue.map(a=>{if(!a.media?.length)return a;let b=a.media.filter(a=>this.isQueueMediaRefAlive(a));return b.length===a.media.length?a:{...b.length?{...a,media:b}:{text:a.text,id:a.id,state:a.state},state:"unknown"}})}waitingFollowUp(){return this.followUpQueue.filter(a=>"waiting"===a.state)}hasWaitingFollowUp(){return this.followUpQueue.some(a=>"waiting"===a.state)}visibleFollowUp(){return this.followUpQueue.filter(a=>"claimed"!==a.state)}inFlightFollowUpTexts(){return this.followUpQueue.filter(a=>"claimed"===a.state).map(a=>a.text)}commitFollowUpQueue(a,b,c=[]){for(let c of a)if((c.media?.length??0)>l.ym)return console.error(`[pidance] refusing to persist follow-up queue (${b}): item media exceeds ${l.ym}`),!1;let d=this.followUpQueueRevision+1,e=(0,l.S1)(this.followUpAdmittedAttemptIds,c);try{(0,h.xP)(`sessionQueue.${this.realSessionId}`,(0,l.EP)({items:a,revision:d,admittedAttemptIds:e}),this.agentDir)}catch(a){return console.error(`[pidance] failed to persist follow-up queue (${b}):`,a),!1}return this.followUpQueue=a,this.followUpQueueRevision=d,this.followUpAdmittedAttemptIds=e,this.followUpFlushBlocked=!1,!0}discardDeliveredModelMedia(a){let b=new Set((0,l.Ot)(this.followUpQueue).map(a=>a.path));for(let c of a)"model"!==c.role||b.has(c.path)||(0,k.fm)(c.path,this.agentDir)}withFollowUpState(a,b){let c=new Set(a);return this.followUpQueue.map(a=>c.has(a.id)?{...a,state:b}:a)}queueReceiptBase(){return{revision:this.followUpQueueRevision,items:this.visibleFollowUp(),inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}reject(a,b){return{submissionId:a,sessionId:this.realSessionId,status:"rejected",reason:b}}isQueueMediaRefAlive(a){let b="model"===a.role?8388608:k.Md,c=(0,k.vy)(a.path,this.agentDir);return null!==c&&c<=b}validateQueueMedia(a){if(!a?.length)return!0;if(a.length>l.ym)return!1;let b=0;for(let c of a){let a=(0,k.vy)(c.path,this.agentDir);if(null===a)return!1;let d="model"===c.role?8388608:k.Md;if(a>d||(b+=a,c.previewPath&&null===(0,k.vy)(c.previewPath,this.agentDir)))return!1}return b<=k.Lj}readQueueModelImages(a){let b=[],c=[];for(let d of(0,l.Ot)(a)){if("model"!==d.role)continue;let a=(0,k.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b,missing:c}}queueBinaryBlocks(a){return(0,l.Ot)(a).filter(a=>"original"===a.role).map(a=>({path:a.path,name:a.name,mimeType:a.mimeType,size:a.size,...a.previewPath?{previewPath:a.previewPath}:{}}))}writeFollowUpQueue(a,b){if(null!==b&&b!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};for(let b of a)if(!this.validateQueueMedia(b.media))return{ok:!1,persist:!0,...this.queueReceiptBase()};let c=this.followUpQueue.filter(a=>"claimed"===a.state),d=this.followUpQueue.filter(a=>"claimed"!==a.state),e=[...c,...(0,l.Pt)(d,a,{inFlightIds:c.map(a=>a.id)})];return this.commitFollowUpQueue(e,"set",a.map(a=>a.attemptId))?{ok:!0,...this.queueReceiptBase()}:{ok:!1,persist:!0,...this.queueReceiptBase()}}recallFollowUpQueue(a){let b=[],c=[];for(let d of a){let a=this.followUpQueue.find(a=>a.id===d);if(!a){c.push({id:d,reason:"missing"});continue}if("claimed"===a.state){c.push({id:d,reason:"claimed"});continue}b.push(a)}if(!b.length)return{ok:!0,...this.queueReceiptBase(),recalled:[],skipped:c};let d=new Set(b.map(a=>a.id)),e=this.followUpQueue.filter(a=>!d.has(a.id));return this.commitFollowUpQueue(e,"recall")?(this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,...this.queueReceiptBase(),recalled:b,skipped:c}):{ok:!1,persist:!0,...this.queueReceiptBase(),recalled:[],skipped:c}}enqueuePayloads(a,b,c){let d=this.writeFollowUpQueue([...this.visibleFollowUp().map(a=>({text:a.text})),...b],null);return d.ok?(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer(),{submissionId:a,sessionId:this.realSessionId,status:"queued",action:"queued",...c?{reason:c}:{},queue:{items:d.items,inFlight:d.inFlight,revision:d.revision,admittedAttemptIds:[...this.followUpAdmittedAttemptIds]}}):this.reject(a,"error")}queueMediaFromPromptImages(a){if(!a?.length)return{media:void 0,ok:!0};let b=[];for(let[c,d]of a.entries()){let a;if("ref"===d.type){let a=(0,k.vy)(d.path,this.agentDir);if(null===a||a>8388608)return{media:void 0,ok:!1};b.push({role:"model",path:d.path,name:d.path.split(/[\\/]/).pop()??`image-${c}`,mimeType:d.mimeType,size:a});continue}try{a=(0,k.ki)(`prompt-image-${c}.${function(a){let b=a.split(";")[0].trim().toLowerCase();return"image/jpeg"===b?"jpg":"image/svg+xml"===b?"svg":b.startsWith("image/")?b.slice(6).replace(/[^a-z0-9]/g,"")||"png":"bin"}(d.mimeType)}`,Buffer.from(d.data,"base64"),this.agentDir)}catch(a){return console.error("[pidance] inline prompt image could not be stored:",a),{media:void 0,ok:!1}}b.push({role:"model",path:a.path,name:a.name,mimeType:d.mimeType,size:a.size})}return{media:b,ok:!0}}resolvePromptImages(a){if(!a?.length)return{images:void 0,missing:[]};let b=[],c=[];for(let d of a){if("ref"!==d.type){b.push(d);continue}let a=(0,k.fb)(d.path,this.agentDir,8388608);if(!a){c.push(d.path);continue}b.push({type:"image",data:a,mimeType:d.mimeType})}return{images:b.length?b:void 0,missing:c}}async dispatchFollowUpQueue(a){if(this.bashRunning)return{ok:!1,status:"rejected",reason:"bash",...this.queueReceiptBase()};if(this.session.isCompacting)return{ok:!1,status:"rejected",reason:"compacting",...this.queueReceiptBase()};if(this.flushingFollowUp||this.dispatchingFollowUpQueue)return{ok:!1,conflict:!0,reason:"in-flight",...this.queueReceiptBase()};if(null!==a.expectedRevision&&a.expectedRevision!==this.followUpQueueRevision)return{ok:!1,conflict:!0,reason:"revision",...this.queueReceiptBase()};let b=this.waitingFollowUp(),c=a.extra?.trim();if(0===b.length&&!c)return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};let{text:d}=(0,l.X_)(b,c),e=this.readQueueModelImages(b);if(e.missing.length)return console.error("[pidance] queued media missing, dispatch rejected:",e.missing),{ok:!1,status:"rejected",reason:"media",...this.queueReceiptBase()};let f=this.queueBinaryBlocks(b),g=b.map(a=>a.media?.length?(0,l.ko)(a.text,"claimed",a.media):(0,l.ko)(a.text,"claimed"));c&&g.push((0,l.ko)(c,"claimed"));let h=g.map(a=>a.id),i=new Set(h),j=[...this.followUpQueue.filter(a=>"waiting"!==a.state),...g];if(!this.commitFollowUpQueue(j,"dispatch-claim",[a.extraAttemptId]))return{ok:!1,status:"rejected",reason:"error",...this.queueReceiptBase()};this.dispatchingFollowUpQueue=!0,this.emitQueueChanged();let k=e.images.length?e.images:void 0,m="prompt";try{if(this.session.isStreaming)m="steer",await this.session.steer(d,k);else{let a=await this.send({type:"prompt",message:d,...k?.length?{images:k}:{},...f.length?{binaryBlocks:f}:{},streamingBehavior:"steer"},this.internalPromptTicket);if(a?.status==="queued")return m="queued",this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-queued"),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:m,...this.queueReceiptBase()};if(a?.status!=="accepted")return this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release"),this.emitQueueChanged(),{ok:!1,status:"rejected",reason:a?.reason??"error",...this.queueReceiptBase()}}}catch(b){let a=this.commitFollowUpQueue(this.withFollowUpState(h,"waiting"),"dispatch-release");return this.emitQueueChanged(),a||this.emit({type:"follow_up_flush_error",errorMessage:"dispatch rejected and the claim could not be released; it stays claimed for the user to inspect",...this.queueReceiptBase()}),{ok:!1,status:"rejected",reason:(0,t.K2)(b),...this.queueReceiptBase()}}finally{this.dispatchingFollowUpQueue=!1}let n=(0,l.Ot)(g);return this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-deliver")&&this.discardDeliveredModelMedia(n),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:m,...this.queueReceiptBase()}}scheduleFollowUpFlush(){if(!this._alive||!this.runtime||this.flushingFollowUp||this.followUpFlushBlocked||this.isFollowUpHeld()||this.dispatchingFollowUpQueue||!this.isSettled())return;let a=this.waitingFollowUp();if(0===a.length)return;let b=!0===(0,h.rV)(this.agentDir).queueFlushAsOne;this.flushingFollowUp=!0,this.followUpFlushUnits=b?[{ids:a.map(a=>a.id)}]:a.map(a=>({ids:[a.id]})),this.followUpFlushCursor=0,this.sendNextFollowUp()}emitQueueChanged(){let a=this.queueReceiptBase();this.emit({type:"follow_up_queue_changed",sessionId:this.realSessionId,items:a.items,revision:a.revision,inFlight:a.inFlight,admittedAttemptIds:a.admittedAttemptIds})}async sendNextFollowUp(){if(this.followUpSending||!this.flushingFollowUp)return;if(this.isFollowUpHeld())return void this.abortFollowUpFlush();let a=this.followUpFlushUnits[this.followUpFlushCursor];if(void 0===a)return void this.finishFollowUpFlush();if(!this.isSettled())return void setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushUnits[this.followUpFlushCursor]===a&&this.sendNextFollowUp()},80);this.followUpSending=!0;try{await this.deliverFollowUpUnit(a)}finally{this.followUpSending=!1}this.flushingFollowUp&&(this.followUpFlushCursor+=1,this.followUpFlushCursor>=this.followUpFlushUnits.length?this.finishFollowUpFlush():this.sendNextFollowUp())}async deliverFollowUpUnit(a){let b=new Set(a.ids),c=this.followUpQueue.filter(a=>b.has(a.id)&&"waiting"===a.state);if(0===c.length)return void this.emitQueueChanged();let d=c.map(a=>a.id),e=(0,l.X_)(c).text,{images:f,missing:g}=this.readQueueModelImages(c),h=this.queueBinaryBlocks(c);if(g.length){console.error("[pidance] queued image missing, delivery blocked:",g),this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"queued image is missing; delivery blocked",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}let i=f.length?f:void 0;if(this.session.isCompacting||this.bashRunning){this.emit({type:"follow_up_flush_error",errorMessage:this.session.isCompacting?"follow-up delivery deferred while compaction is running":"follow-up delivery deferred while a shell command is running",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}if(!this.commitFollowUpQueue(this.withFollowUpState(d,"claimed"),"claim")){this.followUpFlushBlocked=!0,this.emit({type:"follow_up_flush_error",errorMessage:"failed to persist follow-up queue before delivery",...this.queueReceiptBase()}),this.abortFollowUpFlush();return}this.emitQueueChanged();let j=null;try{j=await this.send({type:"prompt",message:e,...i?{images:i}:{},...h.length?{binaryBlocks:h}:{}},this.internalPromptTicket)}catch(c){let a=c instanceof Error?c.message:String(c),b=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:a,...this.queueReceiptBase()}),this.abortFollowUpFlush(),b&&this.emitQueueChanged();return}if(j?.status==="queued"){this.commitFollowUpQueue(this.followUpQueue.filter(a=>!new Set(d).has(a.id)),"deliver-queued"),this.emitQueueChanged(),this.abortFollowUpFlush();return}if(j&&"accepted"!==j.status){let a=this.commitFollowUpQueue(this.withFollowUpState(d,"waiting"),"release");this.emit({type:"follow_up_flush_error",errorMessage:`follow-up prompt rejected: ${j.reason??"unknown"}`,...this.queueReceiptBase()}),this.abortFollowUpFlush(),a&&this.emitQueueChanged();return}let k=new Set(d),m=(0,l.Ot)(c),n=this.commitFollowUpQueue(this.followUpQueue.filter(a=>!k.has(a.id)),"deliver");n&&this.discardDeliveredModelMedia(m),this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:e,...this.queueReceiptBase()}),n||this.emit({type:"follow_up_flush_error",errorMessage:"follow-up delivered but queue removal was not persisted",...this.queueReceiptBase()}),this.emitQueueChanged()}abortFollowUpFlush(){this.flushingFollowUp&&(this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer())}finishFollowUpFlush(){this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.scheduleFollowUpFlush()}get session(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.session}get services(){if(!this.runtime)throw Error("SDK session is not alive");return this.runtime.services}syncIdentityFromSession(){let a=this.session,b=a.sessionId||this.realSessionId,c=a.sessionFile||this.realSessionFile,d=this.realSessionId;this.realSessionId=b,this.realSessionFile=c,c&&this.options.cacheSessionPath?.(b,c),d!==b&&this.options.onSessionRekeyed?.(d,b,this)}async rebindSession(){let a=this.session;this.extensionUi?.dispose(),this.extensionUi=(0,p.t)(a=>{this.trackExtensionSideEffects(a),this.emit(a)}),await a.bindExtensions({uiContext:this.extensionUi.uiContext,mode:"rpc",commandContextActions:{waitForIdle:()=>a.waitForIdle(),newSession:async a=>{let b=await this.runtime.newSession(a);return b.cancelled||await this.rebindSession(),b},fork:async(a,b)=>{let c=await this.runtime.fork(a,b);return c.cancelled||await this.rebindSession(),{cancelled:c.cancelled}},navigateTree:async(b,c)=>({cancelled:(await a.navigateTree(b,{summarize:c?.summarize,customInstructions:c?.customInstructions,replaceInstructions:c?.replaceInstructions,label:c?.label})).cancelled}),switchSession:async(a,b)=>{let c=await this.runtime.switchSession(a,b);return c.cancelled||await this.rebindSession(),c},reload:async()=>{await a.reload()}},onError:a=>{this.setFollowUpHeld(!0),this.emit({type:"extension_error",extensionPath:a.extensionPath,event:a.event,error:a.error})}}),this.unsubscribe?.(),this.unsubscribe=a.subscribe(a=>{this.resetIdleTimer(),this.handleSessionEvent(a)}),this.syncIdentityFromSession()}trackExtensionSideEffects(a){if("extension_ui_request"!==a.type)return;let b=z(a.method);if("setStatus"===b){let b=z(a.statusKey)??z(a.key)??"default",c=z(a.statusText)??z(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=z(a.widgetKey)??z(a.key)??"default",c=a.widgetLines??a.content;null==c?this.extensionUi?.widgets.delete(b):this.extensionUi?.widgets.set(b,{lines:c,placement:a.widgetPlacement})}this.notifyRunning()}maybeAutoNameSession(){try{let a=this.session?.sessionManager;if(!a||a.getSessionName())return;let b=(a.buildSessionContext().messages??[]).find(a=>"user"===a.role),c=function(a){let b="";"string"==typeof a?b=a:Array.isArray(a)&&(b=a.filter(a=>"object"==typeof a&&null!==a&&"text"===a.type&&"string"==typeof a.text).map(a=>a.text).join("\n"));let c=b.replace(/\s+/g," ").trim();if(c)return c.length>60?`${c.slice(0,60)}…`:c}(b?.content);c&&a.appendSessionInfo(c)}catch{}}readStopReasonFromAgentEnd(a){let b=a.messages;if(!Array.isArray(b))return null;for(let a=b.length-1;a>=0;a--){let c=b[a],d=c?.message?.stopReason??c?.stopReason;if("string"==typeof d){if("aborted"===d)return"aborted";if("error"===d||"prompt_error"===d)return"error";return"completed"}}return null}removePendingBinaryBatch(a){this.pendingBinaryBatches=this.pendingBinaryBatches.filter(b=>b.submissionId!==a)}persistPendingBinaryBlocks(a){if(0!==a.length)try{let b=this.session.sessionManager;(0,o.kb)(b);let c=b.getEntries(),d=[...c].reverse().find(a=>"message"===a.type&&a.message?.role==="user"&&"string"==typeof a.id)?.id||b.getLeafId()||void 0;for(let c of a){let a=d?{...c,messageEntryId:d}:c,e=b.appendCustomEntry(u.uG,a);this.emit({type:"message_end",entryId:e,message:(0,u.FH)(a,Date.now())})}(0,o.kb)(b),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] persist binary message failed:",a)}}static hasRenderableContent(a){if(!a)return!1;let b=a.content;return"string"==typeof b?b.length>0:Array.isArray(b)&&b.length>0}static outputTokensOf(a){let b=a?.usage?.output;return"number"==typeof b&&Number.isFinite(b)&&b>=0?b:null}accumulateTurnMetrics(a){let b=Date.now();if("agent_start"===a.type)return this.turnMetrics={startedAt:b,firstTokenAt:null,ttftMs:null,decodeMs:0,outputTokens:0,sampled:!1},!0;if("message_start"===a.type||"message_update"===a.type){let c=a.message;if(c?.role==="user")return!1;if(null===this.turnMetrics.firstTokenAt&&C.hasRenderableContent(c)){this.turnMetrics.firstTokenAt=b;let a=null===this.turnMetrics.ttftMs;return a&&this.turnMetrics.startedAt>0&&b>=this.turnMetrics.startedAt&&(this.turnMetrics.ttftMs=b-this.turnMetrics.startedAt),a}return!1}if("message_end"===a.type){let c=a.message;if(c?.role!=="assistant")return!1;let d=null===this.turnMetrics.firstTokenAt?null:Math.max(0,b-this.turnMetrics.firstTokenAt);this.turnMetrics.firstTokenAt=null;let e=C.outputTokensOf(c);if(null!==d&&null!==e)return this.turnMetrics.decodeMs+=d,this.turnMetrics.outputTokens+=e,this.turnMetrics.sampled=!0,!0}return!1}projectTurnMetrics(){let a={};return null!==this.turnMetrics.ttftMs&&this.turnMetrics.startedAt>0&&(a.ttftMs=this.turnMetrics.ttftMs),this.turnMetrics.sampled&&this.turnMetrics.decodeMs>0&&(a.tokensPerSecond=this.turnMetrics.outputTokens/(this.turnMetrics.decodeMs/1e3)),a}handleSessionEvent(a){let b=this.accumulateTurnMetrics(a),c="agent_start"===a.type?++this.streamRunSeq:this.streamRunSeq;switch(a.type){case"agent_start":this.promptRunning=!0,(0,j.NK)(this.realSessionId,Date.now()),this.notifyRunning();break;case"agent_end":this.promptRunning=!1,this.lastStopReason=this.readStopReasonFromAgentEnd(a)??this.lastStopReason??"completed",("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.setFollowUpHeld(!0),(0,j.PI)(this.realSessionId),this.options.onSessionListInvalidate?.(),this.realSessionFile&&(0,n.$9)(this.realSessionFile),this.maybeAutoNameSession(),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});break;case"agent_settled":this.promptRunning=!1,this.notifyRunning(),"completed"===this.lastStopReason?this.flushingFollowUp?this.sendNextFollowUp():this.scheduleFollowUpFlush():this.flushingFollowUp&&("aborted"===this.lastStopReason||"error"===this.lastStopReason)&&this.abortFollowUpFlush();let d="agent_settled"===a.type&&!this.flushingFollowUp&&(!this.hasWaitingFollowUp()||this.isFollowUpHeld())&&!this.hasActiveSubagentRun();this.resetIdleTimer(),d&&this.destroyAsync().catch(()=>{});break;case"compaction_start":case"auto_compaction_start":this.notifyRunning();break;case"compaction_end":case"auto_compaction_end":this.notifyRunning(),!0!==a.aborted&&!a.errorMessage&&this.isSettled()&&this.scheduleFollowUpFlush(),this.resetIdleTimer();break;case"message_end":{let b=a.message;if(b?.role==="user"){let a=this.pendingBinaryBatches.shift();setImmediate(()=>{try{(0,o.kb)(this.session.sessionManager),this.syncIdentityFromSession(),this.persistPendingBinaryBlocks(a?.blocks??[]),this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] materialize after user message failed:",a)}})}break}case"queue_update":{let b=Array.isArray(a.steering)?a.steering.filter(a=>"string"==typeof a):[],c=Array.isArray(a.followUp)?a.followUp.filter(a=>"string"==typeof a):[];this.localQueue={steering:b,followUp:c},this.hasQueueSnapshot=!0}}let e=c>0?{...a,streamRunSeq:c}:a;if(b){let a=this.projectTurnMetrics();(void 0!==a.ttftMs||void 0!==a.tokensPerSecond)&&(e={...e,turnMetrics:a})}let f="message_end"===a.type&&a.message?.role==="assistant";if("agent_end"===a.type||f){let a=this.contextUsageSnapshot();a&&(e={...e,contextUsage:a})}this.emit(this.withRenderedToolLines(e))}contextUsageSnapshot(){try{let a=this.session.getContextUsage();if(a&&"number"==typeof a.contextWindow&&a.contextWindow>0)return{contextWindow:a.contextWindow,percent:"number"==typeof a.percent?a.percent:null,tokens:"number"==typeof a.tokens?a.tokens:null}}catch{}}withRenderedToolLines(a){try{if(!this.renderBridgeTheme)return a;switch(a.type){case"tool_execution_update":{if(!this.shouldRenderPartialUpdate(a.toolCallId))return a;let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.args??a.input,{isPartial:!0,expanded:!0,isError:!0===a.isError,resultSlot:!0});if(!c)return a;let d=(0,x.t_)(b,a.partialResult,{expanded:!0,isPartial:!0},c,b=>this.updateToolRenderLastComponent(a.toolCallId,!0,b));return d?{...a,renderedLines:d}:a}case"tool_call":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.input,{isPartial:!1,expanded:!0,isError:!1,resultSlot:!1});if(!c)return a;let d=(0,x.GD)(b,a.input,c,b=>this.updateToolRenderLastComponent(a.toolCallId,!1,b));return d?{...a,renderedCallLines:d}:a}case"tool_result":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=this.buildToolRenderContext(a.toolCallId,a.args??a.input,{isPartial:!1,expanded:!0,isError:!0===a.isError,resultSlot:!0});if(!c)return a;let d=(0,x.t_)(b,{content:a.content,details:a.details,isError:!0===a.isError,...void 0!==a.usage?{usage:a.usage}:{}},{expanded:!0,isPartial:!1},c,b=>this.updateToolRenderLastComponent(a.toolCallId,!0,b));return d?{...a,renderedResultLines:d}:a}case"message_start":case"message_end":{let b=a.message;if(b?.role!=="custom"||"string"!=typeof b.customType||""===b.customType)return a;let c=this.session.extensionRunner,d="function"==typeof c?.getMessageRenderer?c.getMessageRenderer(b.customType):void 0,e=(0,x.Mf)(d,a.message,this.renderBridgeTheme);return e?{...a,renderedLines:e}:a}default:return a}}catch{return a}}getToolRenderDefinition(a){if("string"==typeof a&&""!==a)try{return this.session.getToolDefinition(a)}catch{return}}buildToolRenderContext(a,b,c){let d=this.getOrCreateToolRenderState(a);return d?{args:b,toolCallId:a,invalidate:()=>{},lastComponent:c.resultSlot?d.lastResultComponent:d.lastCallComponent,state:d.state,cwd:this.realCwd,executionStarted:!0,argsComplete:!0,isPartial:c.isPartial,expanded:c.expanded,showImages:!1,isError:c.isError}:null}getOrCreateToolRenderState(a){if("string"!=typeof a||""===a)return null;let b=this.toolRenderStates.get(a);return b||(b={state:{},lastCallComponent:void 0,lastResultComponent:void 0,lastPartialRenderAt:void 0},this.toolRenderStates.set(a,b)),b}updateToolRenderLastComponent(a,b,c){if("string"!=typeof a||""===a)return;let d=this.toolRenderStates.get(a);d&&(b?d.lastResultComponent=c:d.lastCallComponent=c)}shouldRenderPartialUpdate(a){if("string"!=typeof a||""===a)return!0;let b=Date.now(),c=this.getOrCreateToolRenderState(a);return!c||(void 0===c.lastPartialRenderAt||!(b-c.lastPartialRenderAt<C.PARTIAL_RENDER_MIN_INTERVAL_MS))&&(c.lastPartialRenderAt=b,!0)}get realCwd(){try{return this.session.sessionManager.getHeader()?.cwd||this.options.cwd}catch{return this.options.cwd}}async start(){try{var a,b;let c=(a=this.realSessionFile,b=this.options.cwd,a?(0,o.G1)(a):(0,o.Qu)(b)),d=c.getCwd()||this.options.cwd,f=this.agentDir,g=this.activeToolNames,h=async({cwd:a,agentDir:b,sessionManager:c,sessionStartEvent:d})=>{let f=(0,w._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),h={name:w.Jv,label:"Send file to user",description:"Publish an agent-created project file as a user-visible attachment with preview/download support.",promptSnippet:"deliver a generated file to the user as a downloadable attachment",promptGuidelines:["When the user needs a generated file, call send_file_to_user; do not only print a local path or paste Base64.","Only report a file as delivered after send_file_to_user returns successfully."],parameters:w.Tv,async execute(a,b,c){let d=await f(b,c);return{content:[{type:"text",text:`Delivered ${d.name} to the user (entry ${d.entryId}).`}],details:d}}},i=await (0,e.createAgentSessionServices)({cwd:a,agentDir:b,resourceLoaderOptions:{appendSystemPromptOverride:w.n3,extensionFactories:[a=>a.registerTool(h)]}});for(let a of i.modelRuntime.getModels())(0,s.yu)(a);return{...await (0,e.createAgentSessionFromServices)({services:i,sessionManager:c,sessionStartEvent:d,tools:g&&g.length>0?g:void 0,noTools:g&&0===g.length?"all":void 0}),services:i,diagnostics:i.diagnostics}};this.runtime=await (0,e.createAgentSessionRuntime)(h,{cwd:d,agentDir:f,sessionManager:c}),this.runtime.setRebindSession(async()=>{await this.rebindSession()}),this.runtime.setBeforeSessionInvalidate(()=>{this.extensionUi?.dispose(),this.unsubscribe?.(),this.unsubscribe=null}),await this.rebindSession(),this.syncIdentityFromSession(),this.hydrateFollowUpQueue(),this.startupHoldTimer=setTimeout(()=>{this.startupHoldTimer=null,this.startupHold=!1,this.resetIdleTimer()},15e3),this.startupHoldTimer.unref?.(),this.resetIdleTimer(),this.hasWaitingFollowUp()&&!this.isFollowUpHeld()&&this.isSettled()&&this.scheduleFollowUpFlush()}catch(a){throw await this.destroyAsync(),a}}projectState(){let a=this.session,b=a.model,c={stateSources:{rpcGetState:!1,sdkSession:!0,sessionStats:!0,localQueue:!0,localExtensionUi:!0},sessionId:this.realSessionId,sessionFile:this.realSessionFile,sessionName:a.sessionName,isStreaming:a.isStreaming,isCompacting:a.isCompacting,isPromptRunning:this.promptRunning,lastStopReason:this.lastStopReason,isBashRunning:this.bashRunning,turnMetrics:this.projectTurnMetrics(),pendingBash:this.bashCommand,autoCompactionEnabled:a.autoCompactionEnabled,steeringMode:a.steeringMode,followUpMode:a.followUpMode,thinkingLevel:a.thinkingLevel,systemPrompt:a.systemPrompt??"",model:b?{id:b.id,provider:b.provider,modelId:b.id}:void 0,messageCount:a.messages.length,pendingMessageCount:a.pendingMessageCount,extensionStatuses:Array.from(this.extensionUi?.statuses.entries()??[],([a,b])=>({key:a,text:b})),extensionWidgets:Array.from(this.extensionUi?.widgets.entries()??[],([a,b])=>({key:a,lines:Array.isArray(b?.lines)?b.lines:[],placement:b?.placement==="belowEditor"?"belowEditor":"aboveEditor"})),pendingExtensionRequests:Array.from(this.extensionUi?.pendingSnapshot.values()??[]),activeCustomUi:this.extensionUi?.customSnapshot??null};c.queuedMessages={steering:this.hasQueueSnapshot?[...this.localQueue.steering]:[],followUp:(0,l.gC)(this.visibleFollowUp()),followUpItems:this.visibleFollowUp(),followUpRevision:this.followUpQueueRevision,inFlight:this.inFlightFollowUpTexts(),admittedAttemptIds:[...this.followUpAdmittedAttemptIds]};try{let b=a.getContextUsage();b&&"number"==typeof b.contextWindow&&b.contextWindow>0&&(c.contextUsage={contextWindow:b.contextWindow,percent:"number"==typeof b.percent?b.percent:null,tokens:"number"==typeof b.tokens?b.tokens:null})}catch{}return c}appendActivity(a){if(!this.runtime)throw Error("Cannot append activity: session not alive");let b=a&&"object"==typeof a&&"type"in a&&"append_activity"===a.type?(0,m.qF)(a):(0,m.l$)(a),c=this.session.sessionManager.appendCustomEntry(m.cP,b);return this.options.onSessionListInvalidate?.(),{entryId:c,activity:b}}appendBinary(a,b){if(!this._alive||!this.runtime||this.destroyPromise)throw Error("Cannot append binary message: session not alive");let c=this.session.sessionManager;if(b&&c!==b)throw Error("Cannot publish file after the session changed");let d=a&&"object"==typeof a&&!Array.isArray(a)?a:{},e="append_binary"===d.type?d.binaryBlock:a,f=(0,v.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(u.uG,f);try{this.options.onSessionListInvalidate?.()}catch(a){console.error("[pidance] binary message list notification failed:",a)}try{this.emit({type:"message_end",entryId:g,message:(0,u.FH)(f,Date.now())})}catch(a){console.error("[pidance] binary message event notification failed:",a)}return{entryId:g,binary:f}}async send(a,b){if(!this.runtime)throw Error("SDK session is not alive");let c=a.type;"get_state"!==c&&"ensure_session"!==c&&this.releaseStartupHold(),this.activeCommandCount+=1,this.resetIdleTimer();let d=this.session;try{switch(c){case"prompt":{let c=(0,t.JT)(a),e=this.promptReceipts.get(c.submissionId);if(e)return e;let f=c.submissionId,g=this.promptInFlight.get(f);if(g)return g;let h=(0,v.Nu)(c.binaryBlocks,this.agentDir),k=c.images??a.images,l=this.resolvePromptImages(k);if(l.missing.length){console.error("[pidance] prompt image missing on disk:",l.missing);let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}if(this.bashRunning&&!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"bash");return this.promptReceipts.set(c.submissionId,a),a}if(d.isCompacting&&!(0,r.D)(c.message)){let a=this.queueMediaFromPromptImages(k);if(!a.ok){let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}let b=this.enqueuePayloads(c.submissionId,[{text:c.message,...a.media?.length?{media:a.media}:{}}],"compacting");return this.promptReceipts.set(c.submissionId,b),this.options.onSessionListInvalidate?.(),b}if(this.flushingFollowUp&&b!==this.internalPromptTicket&&!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}if((this.promptRunning||d.isStreaming)&&"steer"!==a.streamingBehavior){if(!(0,r.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}try{await d.prompt(c.message,{images:l.images,source:"rpc"});let a={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(c.submissionId,a),a}catch{let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}}if(!(0,i.kP)(this.realSessionId))throw Error(i.GT);this.promptRunning=!0,this.lastStopReason=null,(0,j.NK)(this.realSessionId,Date.now()),this.notifyRunning();let m=(async()=>{try{await new Promise((b,e)=>{let g=!1,i=()=>{d.isStreaming||d.isCompacting||this.bashRunning||this.promptRunning&&(this.promptRunning=!1,"aborted"!==this.lastStopReason&&"error"!==this.lastStopReason&&(this.lastStopReason="completed"),(0,j.PI)(this.realSessionId),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq}),this.resetIdleTimer())};d.prompt(c.message,{images:l.images,streamingBehavior:a.streamingBehavior,source:"rpc",preflightResult:a=>{a&&(g=!0,h.length>0&&this.pendingBinaryBatches.push({submissionId:f,blocks:h}),this.syncIdentityFromSession(),this.setFollowUpHeld(!1),this.options.onSessionListInvalidate?.(),b())}}).then(()=>{if(!g){g=!0;try{(0,o.kb)(d.sessionManager)}catch(a){console.error("[pidance] materialize after prompt failed:",a)}this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.(),b()}i()}).catch(a=>{"aborted"!==this.lastStopReason&&(this.lastStopReason="error"),this.setFollowUpHeld(!0),i(),g||(g=!0,e(a))})});let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"accepted"};return this.promptReceipts.set(f,b),b}catch(g){this.removePendingBinaryBatch(f);let a=(0,t.K2)(g);if(d.isStreaming&&(0,t.in)(a)){let b={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected",reason:a};return this.promptReceipts.set(f,b),b}this.promptRunning=!1,this.lastStopReason="aborted"===this.lastStopReason?"aborted":"error",this.setFollowUpHeld(!0),(0,j.PI)(this.realSessionId),this.notifyRunning();let b=g instanceof Error?g.message:String(g);this.emit({type:"prompt_error",errorMessage:b}),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq});let e={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected"};throw this.promptReceipts.set(f,e),g}finally{this.promptInFlight.delete(f)}})();return this.promptInFlight.set(f,m),m}case"abort":return this.lastStopReason="aborted",this.setFollowUpHeld(!0),this.promptRunning=!1,this.notifyRunning(),await d.abort(),this.notifyRunning(),null;case"get_state":return this.projectState();case"set_model":{let b=String(a.provider??""),c=String(a.modelId??""),e=(0,q.E)(d.modelRuntime,b,c);if(!e)try{e=(await d.modelRuntime.getAvailable()).find(a=>a.provider===b&&a.id===c)}catch{e=void 0}if(!e)throw Error(`Model not found: ${b}/${c}`);return await d.setModel((0,s.eU)(e)),this.options.onSessionListInvalidate?.(),e}case"set_thinking_level":return d.model&&(0,s.yu)(d.model),d.setThinkingLevel(a.level),this.options.onSessionListInvalidate?.(),null;case"compact":{let b=await d.compact("string"==typeof a.customInstructions?a.customInstructions:void 0);return this.options.onSessionListInvalidate?.(),this.notifyRunning(),this.resetIdleTimer(),b}case"steer":{let b=(0,t._3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.steerFlights.get(b.submissionId);if(d)return d;let e=this.runSteerCommand(b);this.steerFlights.set(b.submissionId,e);try{return await e}finally{this.steerFlights.get(b.submissionId)===e&&this.steerFlights.delete(b.submissionId)}}case"dispatch_follow_up_queue":{let b=(0,t.s)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=await this.dispatchFollowUpQueue(b);return this.commandReceipts.set(b.submissionId,d),d}case"recall_follow_up_queue":{let b=(0,t.TJ)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.recallFollowUpQueue(b.itemIds);return this.commandReceipts.set(b.submissionId,d),d}case"set_follow_up_queue":{let b=(0,t.QT)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.writeFollowUpQueue(b.items,b.expectedRevision);return this.commandReceipts.set(b.submissionId,d),d.ok&&(this.emitQueueChanged(),this.isSettled()&&this.hasWaitingFollowUp()&&this.scheduleFollowUpFlush(),this.resetIdleTimer()),d}case"follow_up":{let b=(0,t.$3)(a),c=this.commandReceipts.get(b.submissionId);if(c)return c;let d=this.queueMediaFromPromptImages(b.images),e=this.bashRunning?this.reject(b.submissionId,"bash"):d.ok?b.message.trim()||d.media?.length?this.enqueuePayloads(b.submissionId,[{text:b.message,...d.media?.length?{media:d.media}:{}}]):this.reject(b.submissionId,"error"):this.reject(b.submissionId,"media");return this.commandReceipts.set(b.submissionId,e),e}case"set_session_name":{let b=String(a.name??"").trim();if(!b)throw Error("Session name cannot be empty");return d.setSessionName(b),this.options.onSessionListInvalidate?.(),null}case"set_auto_compaction":return d.setAutoCompactionEnabled(!!a.enabled),null;case"set_auto_retry":return d.setAutoRetryEnabled(!!a.enabled),null;case"clear_queue":return d.clearQueue();case"get_tools":{let a=d.getAllTools(),b=new Set(d.getActiveToolNames());return{source:"sdk",tools:a.map(a=>({name:a.name,description:a.description??"",active:b.has(a.name)}))}}case"set_tools":{let b=Array.isArray(a.tools)?a.tools.filter(a=>"string"==typeof a):[];return d.setActiveToolsByName(b),this.activeToolNames=b,null}case"get_commands":{let a=[];for(let b of d.extensionRunner.getRegisteredCommands())a.push({name:b.invocationName,description:b.description,source:"extension",sourceInfo:b.sourceInfo});for(let b of d.promptTemplates)a.push({name:b.name,description:b.description,source:"prompt_template"});try{let b=d.resourceLoader?.getSkills?.();for(let c of b?.skills??[])a.push({name:`skill:${c.name}`,description:c.description,source:"skill",sourceInfo:c.sourceInfo})}catch{}return{commands:a}}case"get_session_stats":return d.getSessionStats();case"bash":if(d.isStreaming)throw Error("Cannot run bash while agent is streaming");this.bashRunning=!0,this.bashCommand={command:String(a.command??""),excludeFromContext:!!a.excludeFromContext,startedAt:Date.now()},this.notifyRunning();try{return await d.executeBash(String(a.command??""),void 0,{excludeFromContext:!!a.excludeFromContext})}finally{this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),this.resetIdleTimer()}case"abort_bash":return d.abortBash(),this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),null;case"abort_compaction":return d.abortCompaction(),null;case"extension_ui_response":{let b=z(a.id);if(!b)throw Error("extension_ui_response requires id");let c={...a};return delete c.type,delete c.id,!this.extensionUi?.respond(b,c),this.notifyRunning(),null}case"extension_ui_input":{let b=z(a.id),c="string"==typeof a.data?a.data:"";return b&&this.extensionUi?.inputCustom(b,c),null}case"append_activity":return this.appendActivity(a);case"append_binary":return this.appendBinary(a);case"fork":{if(this.bashRunning)throw Error("Cannot fork while a shell command is running");let b=String(a.entryId??"");if(!b)throw Error("entryId is required");let c=await this.runtime.fork(b);return c.cancelled||(await this.rebindSession(),this.syncIdentityFromSession(),this.options.onSessionListInvalidate?.()),{cancelled:c.cancelled,newSessionId:c.cancelled?void 0:this.realSessionId,text:c.selectedText}}case"navigate_tree":{if(this.bashRunning)throw Error("Cannot navigate while a shell command is running");let b=z(a.targetId);if(!b)throw Error("targetId is required");let c=await d.navigateTree(b,{summarize:a.summarize,customInstructions:z(a.customInstructions)});if(!c.cancelled&&this.realSessionFile){d.sessionManager.getLeafId();let a=d.sessionManager.getLeafId(),b=d.sessionManager.getEntries(),c=b.at(-1)?.id;a&&c&&a!==c?(0,n.R3)(this.realSessionFile,a):this.realSessionFile&&(0,n.$9)(this.realSessionFile)}return this.options.onSessionListInvalidate?.(),{cancelled:c.cancelled}}case"select_leaf_exact":{let b=z(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.selectLeafExact(this.sessionId,b,a)}let e=await d.navigateTree(b,{summarize:!1});if(!e.cancelled&&this.realSessionFile){let a=d.sessionManager.getLeafId(),b=d.sessionManager.getEntries().at(-1)?.id;a&&b&&a!==b?(0,n.R3)(this.realSessionFile,a):(0,n.$9)(this.realSessionFile)}return{cancelled:e.cancelled}}case"branch_from_assistant":{let b=z(a.assistantEntryId);if(!b)throw Error("assistantEntryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.branchFromAssistant(this.sessionId,b,a)}throw Error("branch_from_assistant is unavailable")}case"create_session_from_leaf":{let b=z(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c){let a=()=>this.destroyExcluding(1);return await c.createSessionFromLeaf(this.sessionId,b,a)}throw Error("create_session_from_leaf is unavailable")}case"set_branch_label":{let b=z(a.targetId);if(!b)throw Error("targetId is required");let c=void 0===a.label||null===a.label?void 0:String(a.label);return d.sessionManager.appendLabelChange(b,c),this.options.onSessionListInvalidate?.(),null}case"reload":return await d.reload(),await this.rebindSession(),null;case"get_last_assistant_text":return{text:d.getLastAssistantText()};case"ensure_session":return null;default:throw Error(`Unsupported command: ${c}`)}}finally{this.activeCommandCount=Math.max(0,this.activeCommandCount-1),0===this.activeCommandCount&&this.resetIdleTimer()}}destroy(){this.destroyAsync().catch(()=>{})}async destroyAsync(){return this.destroyExcluding(0)}destroyExcluding(a){if(this.destroyPromise)return this.destroyPromise;if(!this._alive&&!this.runtime)return Promise.resolve();if(this.activeCommandCount-a>0){let b=this.pendingDestroys.get(a);return b||(b=this.destroyWhenCommandsSettle(a),this.pendingDestroys.set(a,b)),b}return this.beginDispose()}destroyWhenCommandsSettle(a){let b=(async()=>{let b=Date.now()+this.destroyWaitMs;for(;this.activeCommandCount-a>0;){if(Date.now()>=b)throw Error(B);await new Promise(a=>{let b=setTimeout(a,25);b.unref?.()})}return this.beginDispose()})().finally(()=>{this.pendingDestroys.get(a)===b&&this.pendingDestroys.delete(a)});return b}beginDispose(){return this.destroyPromise||(this._alive=!1,this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=null,this.startupHoldTimer&&clearTimeout(this.startupHoldTimer),this.startupHoldTimer=null,this.startupHold=!1,this.destroyPromise=(async()=>{this.unsubscribe?.(),this.unsubscribe=null,this.extensionUi?.dispose(),this.extensionUi=null;let a=this.runtime;if(this.runtime=null,a)try{await a.dispose()}catch(a){console.error("[pidance] sdk runtime dispose error:",a)}for(let a of(this.promptRunning=!1,this.bashRunning=!1,this.bashCommand=null,this.flushingFollowUp=!1,this.followUpFlushUnits=[],this.followUpFlushCursor=0,this.followUpSending=!1,(0,j.PI)(this.realSessionId),[...this.destroyCallbacks]))try{a()}catch(a){console.error("[pidance] sdk host destroy listener error:",a)}this.destroyCallbacks.clear(),this.notifyRunning()})()),this.destroyPromise}}async function A(a){let b=new C(a);return await b.start(),b}d()}catch(a){d(a)}})},5815:(a,b,c)=>{c.d(b,{MG:()=>h,NK:()=>f,PI:()=>g});let d="__piRunningStartedAt";function e(){let a=globalThis;return d in a&&a[d]instanceof Map||(a[d]=new Map),a[d]}function f(a,b){let c=e();c.has(a)||c.set(a,b)}function g(a){e().delete(a)}function h(){return e()}},6032:(a,b,c)=>{c.d(b,{Y:()=>d,f:()=>e});let d="__new__";function e(a){return a.startsWith(d)}},23828:(a,b,c)=>{c.d(b,{D:()=>d});function d(a){return a.trim().startsWith("/")}},25252:(a,b,c)=>{c.d(b,{HM:()=>e,wz:()=>f});var d=c(50593);function e(){return globalThis.__piAdditionalAllowedRoots||(globalThis.__piAdditionalAllowedRoots=new Set),globalThis.__piAdditionalAllowedRoots}function f(a){if(!a)return;let b=(0,d.Nw)(a);e().add(b),globalThis.__piAllowedRootsCache?.roots.add(b)}},26773:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>w,A4:()=>o,DU:()=>q,EM:()=>t,Fn:()=>v,HG:()=>s,OF:()=>y,YZ:()=>f.Y});var e=c(40402),f=c(6032),g=c(95237),h=c(68524),i=c(2416),j=c(5815),k=c(89953),l=a([e,g,i]);function m(){if(!globalThis.__piSessions){globalThis.__piSessions=new Map;let a=()=>{globalThis.__piSessions?.forEach(a=>a.destroy())};process.once("exit",a),process.once("SIGINT",a),process.once("SIGTERM",a)}return globalThis.__piSessions}function n(){return globalThis.__piStartLocks||(globalThis.__piStartLocks=new Map),globalThis.__piStartLocks}function o(a){return m().get(a)}function p(){return[...n().keys()]}async function q(a){let b=n().get(a);if(!b)return null;try{return(await b).realSessionId}catch{return null}}function r(){let a=new Set(p());for(let[b,c]of m())c.isRunning()&&a.add(c.sessionId||b);return[...a]}function s(){return r()}[e,g,i]=l.then?(await l)():l;let A=new Map;function t(a,b=Date.now()){let c={},d=(0,j.MG)(),e=r(),f=new Set(e);for(let a of e){let e=d.get(a)??A.get(a)??b;A.set(a,e),c[a]=e}for(let a of[...A.keys()])f.has(a)||A.delete(a);return c}function u(){return globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners}function v(a){let b=u();return b.add(a),()=>{b.delete(a)}}function w(){let a=[];for(let[b,c]of m()){let d=c.listPendingExtensionRequests();0!==d.length&&a.push({sessionId:c.sessionId||b,requests:d})}return a}let B="",C=[],D=new Set,E=null;function x(){!function a(){let b=new Set(function(){let a=new Set(p());for(let[b,c]of m())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,k.AZ)(a),D.add(a);for(let a of[...D])b.has(a)||((0,k.Hl)(a),D.delete(a));if(0===b.size){E&&(clearInterval(E),E=null);return}E||(E=setInterval(()=>{a()},8e3),E.unref?.())}();let a=s(),b=w(),c=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(c===B)return;B=c;let d=C.filter(b=>!a.includes(b)&&!(0,f.f)(b));if(C=[...a],d.length>0){let a=new Date().toISOString();setTimeout(()=>{for(let b of d)try{(0,h.xP)(`unreadSessionState.completedAt.${b}`,a)}catch(a){console.error("[pidance] failed to record unread completedAt:",a)}},0)}for(let b of u())try{b(a)}catch{}}async function y(a,b,c,d,e){return z(a,b,c,d,e)}async function z(a,b,c,d,f){let g=m(),h=n(),j=g.get(a);if(j?.isAlive())return{session:j,realSessionId:a};let l=h.get(a);if(l)return l;if(!(0,k.kP)(a))throw Error(k.GT);x();let o=(async()=>{try{let h=await (0,i.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>x(),onSessionListInvalidate:()=>(0,e.mD)(),cacheSessionPath:(a,b)=>(0,e.O8)(a,b),onSessionRekeyed:(a,b,c)=>{let d;d=m(),a!==b&&d.delete(a),d.set(b,c),a!==b&&((0,k.kP)(b),(0,k.Hl)(a))}}),j=h.sessionId,l=h.sessionFile;return l&&(0,e.O8)(j,l),j!==a&&(0,k.kP)(j),h.onDestroy(()=>{g.get(j)===h&&g.delete(j),a!==j&&g.get(a)===h&&g.delete(a),(0,k.Hl)(j),a!==j&&(0,k.Hl)(a),x()}),g.set(j,h),h.beginExtensionBinding(),{session:h,realSessionId:j}}catch(b){throw(0,k.Hl)(a),x(),b}})().finally(()=>{h.delete(a),x()});return h.set(a,o),o}d()}catch(a){d(a)}})},28121:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Jv:()=>r,Tv:()=>t,_D:()=>q,n3:()=>n});var e=c(89477),f=c(42524),g=c(86697),h=c(26238),i=c(69835),j=c(80547),k=c(1060),l=c(60185),m=a([i,j,l]);[i,j,l]=m.then?(await m)():m;let r="send_file_to_user",s="## Pidance file delivery\nWhen the `send_file_to_user` tool is available and you create a file that the user needs to view, download, or play, call it instead of only printing a local path or embedding Base64. The tool publishes a user-visible attachment message: images keep the original for preview and download, audio/video follow the UI playback size policy, and other files get a download card. Only claim that a file was sent after the tool returns success.";function n(a){return a.some(a=>a===s)?a:[...a,s]}let t={type:"object",additionalProperties:!1,properties:{path:{type:"string",description:"Absolute or current-project-relative path of the file to deliver."},name:{type:"string",description:"Optional filename shown to the user; the source basename is used by default."}},required:["path"]};function o(a){if(a?.aborted)throw a.reason instanceof Error?a.reason:Error("file delivery aborted")}async function p(a,b){let c,d;if("string"!=typeof a||!a.trim())throw Error("path is required");let f=(0,g.resolve)(b,a.trim()),h=(0,j.bk)()?null:await (0,j.mc)();if(h&&!(0,j.A$)(f,h))throw Error("file path is not allowed");try{c=(0,e.lstatSync)(f)}catch{throw Error("file not found")}if(c.isSymbolicLink())throw Error("symbolic-link sources are not allowed");if(!c.isFile())throw Error("path must be a regular file");try{d=(0,e.realpathSync)(f)}catch{throw Error("file path could not be resolved")}if(h&&!(0,j.A$)(d,h))throw Error("file path is not allowed");return{path:d,stat:c}}function q(a){return async function(b,c){let d;o(c);let j=await p(b.path,a.cwd),m=j.path,n="string"==typeof b.name&&b.name.trim()?b.name.trim():(0,g.basename)(m),q="number"==typeof e.constants.O_NOFOLLOW?e.constants.O_NOFOLLOW:0,r="number"==typeof e.constants.O_NONBLOCK?e.constants.O_NONBLOCK:0,s=await (0,f.open)(m,e.constants.O_RDONLY|q|r);try{let b=await s.stat();if(!b.isFile())throw Error("path must be a regular file");if(0!==j.stat.dev&&0!==j.stat.ino&&(b.dev!==j.stat.dev||b.ino!==j.stat.ino))throw Error("file changed during open");if(b.size>i.Gt)throw Error(`file exceeds ${i.Gt} bytes`);o(c);let f=(0,e.createReadStream)("",{fd:s.fd,autoClose:!1,signal:c});d=await (0,i.xd)(n,h.Readable.toWeb(f),a.agentDir,i.Gt),o(c);let g=(0,l.iU)({path:d.path,name:d.name,mimeType:(0,k.cV)(m)??(0,k.X)(m)??(0,k.k2)(m)??(0,k.oC)(m)??({txt:"text/plain",md:"text/markdown",json:"application/json",csv:"text/csv",html:"text/html",xml:"application/xml",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar"})[(0,k.GO)(m)]??"application/octet-stream",size:d.size},a.agentDir),{entryId:p}=a.appendBinary(g);return d=void 0,{entryId:p,name:g.name,size:g.size}}finally{if(await s.close().catch(()=>{}),d)try{(0,e.unlinkSync)(d.path)}catch{}}}}d()}catch(a){d(a)}})},31524:(a,b,c)=>{c.d(b,{Ut:()=>e,eU:()=>f,yu:()=>g});let d=["off","minimal","low","medium","high","xhigh","max"];function e(a,b){return a?d.filter(a=>b?.[a]!==null):["off"]}function f(a){if(!a.reasoning)return a;let b=a.thinkingLevelMap,c={...b??{}},d=!1;for(let a of["xhigh","max"])Object.prototype.hasOwnProperty.call(c,a)&&void 0!==c[a]||(c[a]=a,d=!0);return!d&&b?a:{...a,thinkingLevelMap:c}}function g(a){let b=f(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}},35768:(a,b,c)=>{c.d(b,{EE:()=>r,_2:()=>t,gd:()=>E,st:()=>s});var d=c(89477),e=c.n(d),f=c(62228),g=c.n(f),h=c(86697),i=c.n(h);let j=/^[A-Za-z0-9_-]{1,128}$/,k=/^output-\d+\.log$/,l=new Set(["queued","running","complete","failed","paused","stopped"]),m=new Set(["single","parallel","chain"]),n=new Set(["active_long_running","needs_attention"]),o={readdirSync:a=>e().readdirSync(a),lstatSync:a=>e().lstatSync(a),realpathSync:a=>e().realpathSync(a),readFileSync:(a,b)=>e().readFileSync(a,b),openSync:(a,b)=>e().openSync(a,b),readSync:(a,b,c,d,f)=>e().readSync(a,b,c,d,f),closeSync:a=>e().closeSync(a),fstatSync:a=>e().fstatSync(a),constants:e().constants};function p(a){return a.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"unknown"}let q=new Set(["running","queued","paused"]);function r(a,b,c=Date.now(),d=9e5){let e="string"==typeof b?b:"";if(!e.endsWith(".jsonl"))return!1;let f=e.slice(0,-6),g=a=>{if("string"!=typeof a||!a||!a.startsWith(f))return!1;let b=a.charAt(f.length);return"/"===b||"\\"===b};for(let b of a??[]){if(!b||"object"!=typeof b||!q.has(b.state))continue;let a=b.lastUpdate??b.startedAt;if("number"!=typeof a||!(c-a>d)){for(let a of b.steps??[])if(g(a?.sessionFile))return!0}}return!1}function s(a){if(null==a||""===a)return 20;if(!/^\d+$/.test(a))return null;let b=Number(a);return!Number.isInteger(b)||b<1||b>50?null:b}function t(a={}){var b,c;let d,e,f,h,n=a.fs??o,q=a.limit??20,r=a.now?.()??Date.now(),s=a.root??(b=a.scope,h=b?.tmpdir?.()??g().tmpdir(),i().join(h,`pi-subagents-${function(a){let b=a?.env??process.env,c=a&&Object.hasOwn(a,"getuid")?a.getuid:process.getuid?.bind(process);if("function"==typeof c)return`uid-${c()}`;for(let a of["USERNAME","USER","LOGNAME"]){let c=b[a];if(c)return`user-${p(c)}`}let d=a&&Object.hasOwn(a,"userInfo")?a.userInfo:g().userInfo;try{let a=d?.().username;if(a)return`user-${p(a)}`}catch{}let e=b.USERPROFILE??b.HOME;if(e)return`home-${p(e)}`;let f=a&&Object.hasOwn(a,"homedir")?a.homedir:g().homedir;try{let a=f?.();if(a)return`home-${p(a)}`}catch{}return"shared"}(b)}`,"async-subagent-runs"));try{let a=n.lstatSync(s);if(a.isSymbolicLink()||!a.isDirectory())return u(r,!1);e=n.realpathSync(s)}catch(a){return v(a),u(r,!1)}try{f=n.readdirSync(s)}catch(a){return v(a),u(r,!1)}f.length>256&&(f=f.slice(0,256));let D=[];for(let a of f)if(j.test(a))try{let b=function(a,b,c,d){var e,f;let g,h,j,n,o=i().join(b,d);try{g=a.lstatSync(o)}catch{return null}if(g.isSymbolicLink()||!g.isDirectory())return null;try{h=a.realpathSync(o)}catch{return null}if(!w(h,c))return null;let p=function(a,b,c){let d=x(a,b,c);if(!d)return null;let{fd:e,size:f}=d;try{if(f<=0||f>2097152)return null;let b=Buffer.alloc(f),c=0;for(;c<f;){let d=a.readSync(e,b,c,f-c,c);if(0===d)break;c+=d}let d=b.subarray(0,c).toString("utf8"),g=JSON.parse(d);if(!g||"object"!=typeof g||Array.isArray(g))return null;return g}catch{return null}finally{try{a.closeSync(e)}catch{}}}(a,i().join(o,"status.json"),c);if(!p)return null;let q=(e=p.state,"string"==typeof e&&l.has(e)?e:void 0);if(!q)return null;let r=(f=p.mode,("string"==typeof f&&m.has(f)?f:void 0)??"single"),s=A(p.startedAt);if(void 0===s)return null;let t="string"==typeof p.runId&&p.runId.trim()?p.runId.trim():d,u=z(p.activityState),v=A(p.endedAt),D=A(p.lastUpdate),E="string"==typeof p.cwd?p.cwd:void 0,F="string"==typeof p.error?p.error:void 0,G=A(p.currentStep),H=A(p.chainStepCount),I=B(p.totalTokens),J=C(p.totalCost),K=function(a){if(!Array.isArray(a))return[];let b=[];for(let c=0;c<a.length;c+=1){let d=a[c];if(!d||"object"!=typeof d||Array.isArray(d)){b.push({index:c,agent:"unknown",status:"unknown"});continue}let e="string"==typeof d.agent&&d.agent?d.agent:"unknown",f={index:c,agent:e,status:"string"==typeof d.status&&d.status?d.status:"unknown"};"string"==typeof d.label&&(f.label=d.label),"string"==typeof d.model&&(f.model=d.model),"string"==typeof d.sessionFile&&(f.sessionFile=d.sessionFile),"string"==typeof d.error&&(f.error=d.error);let g=z(d.activityState);g&&(f.activityState=g),"string"==typeof d.currentTool&&(f.currentTool=d.currentTool);let h=B(d.tokens);h&&(f.tokens=h);let i=C(d.totalCost)??A(d.costUsd);void 0!==i&&(f.costUsd=i);let j=A(d.startedAt);void 0!==j&&(f.startedAt=j);let k=A(d.endedAt);void 0!==k&&(f.endedAt=k),Array.isArray(d.recentOutput)&&(f.recentOutput=function(a){let b=[];for(let c of a){if(b.length>=8)break;"string"==typeof c&&b.push(c.length>200?c.slice(0,200):c)}return b}(d.recentOutput)),b.push(f)}return b}(p.steps),L=function(a,b,c){let d=y(a,b,c,65536);if(!d||!d.text)return[];let e=d.text;if(d.truncated){let a=e.indexOf("\n");a>=0&&(e=e.slice(a+1))}let f=e.split(/\r?\n/).filter(a=>a.trim().length>0),g=[];for(let a=f.length-1;a>=0&&g.length<20;a-=1)try{let b=JSON.parse(f[a]);if(!b||"object"!=typeof b||Array.isArray(b))continue;let c="string"==typeof b.type?b.type:void 0;if(!c)continue;let d={type:c},e=A(b.timestamp)??A(b.ts)??A(b.time);void 0!==e&&(d.timestamp=e);let h="string"==typeof b.message?b.message:"string"==typeof b.error?b.error:void 0;void 0!==h&&(d.message=h.length>200?h.slice(0,200):h),g.push(d)}catch{}return g.reverse(),g}(a,i().join(o,"events.jsonl"),c),M=function(a,b){if("string"!=typeof a||!a.trim())return null;let c=i().basename(a.trim());return k.test(c)?{absPath:i().join(b,c)}:null}(p.outputFile,o);if(M){let b=y(a,M.absPath,c,32768);if(b){let a=b.text;if(b.truncated){let b=a.indexOf("\n");b>=0&&(a=a.slice(b+1))}j=a,n=b.truncated}}let N={id:t,state:q,mode:r,startedAt:s,steps:K,recentEvents:L};return u&&(N.activityState=u),void 0!==v&&(N.endedAt=v),void 0!==D&&(N.lastUpdate=D),void 0!==E&&(N.cwd=E),void 0!==F&&(N.error=F),void 0!==G&&(N.currentStep=G),void 0!==H&&(N.chainStepCount=H),I&&(N.totalTokens=I),void 0!==J&&(N.totalCostUsd=J),void 0!==j&&(N.outputTail=j),void 0!==n&&(N.outputTruncated=n),N}(n,s,e,a);b&&D.push(b)}catch{}return{runs:(c=D,d=a=>{switch(a){case"running":return 0;case"queued":return 1;case"failed":case"stopped":case"paused":return 2;case"complete":return 3;default:return 4}},[...c].sort((a,b)=>{let c=d(a.state)-d(b.state);if(0!==c)return c;let e=a.lastUpdate??a.endedAt??a.startedAt;return(b.lastUpdate??b.endedAt??b.startedAt)-e})).slice(0,Math.min(q,50)),generatedAt:r,rootAvailable:!0}}function u(a,b){return{runs:[],generatedAt:a,rootAvailable:b}}function v(a){return"object"==typeof a&&null!==a&&"code"in a&&"ENOENT"===a.code}function w(a,b){let c=i().resolve(a),d=b.endsWith(i().sep)?b:b+i().sep;return c===b||c.startsWith(d)}function x(a,b,c){try{let d=a.lstatSync(b);if(d.isSymbolicLink()||!d.isFile())return null;let e=a.realpathSync(b);if(!w(e,c))return null;let f="number"==typeof a.constants.O_NOFOLLOW?a.constants.O_NOFOLLOW:0,g=a.openSync(b,a.constants.O_RDONLY|f);try{let c=a.fstatSync?a.fstatSync(g):a.lstatSync(b);if(!c.isFile())return a.closeSync(g),null;return{fd:g,size:c.size}}catch{try{a.closeSync(g)}catch{}return null}}catch{return null}}function y(a,b,c,d){let e=x(a,b,c);if(!e)return null;let{fd:f,size:g}=e;try{if(0===g)return{text:"",truncated:!1,size:0};let b=Math.min(d,g),c=Math.max(0,g-b),e=Buffer.alloc(b),h=0;for(;h<b;){let d=a.readSync(f,e,h,b-h,c+h);if(0===d)break;h+=d}return{text:e.subarray(0,h).toString("utf8"),truncated:g>d,size:g}}finally{try{a.closeSync(f)}catch{}}}function z(a){return"string"==typeof a&&n.has(a)?a:void 0}function A(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}function B(a){if(!a||"object"!=typeof a||Array.isArray(a))return;let b=A(a.input),c=A(a.output),d=A(a.total);if(void 0!==b&&void 0!==c&&void 0!==d)return{input:b,output:c,total:d}}function C(a){return"number"==typeof a&&Number.isFinite(a)?a:!a||"object"!=typeof a||Array.isArray(a)?void 0:A(a.costUsd)}function D(a){let b=a.trim();if(!b)return"";let c=/^[a-zA-Z]:[\\/]/.test(b)||b.startsWith("\\\\")||b.startsWith("//"),d=c?i().win32:i().posix,e=c?b.replace(/\//g,"\\"):b.replace(/\\/g,"/"),f=d.normalize(e);return c?f.toLowerCase():f}function E(a,b){let c=new Map;for(let a of b){if(!0!==a.readOnly||"string"!=typeof a.id||!a.id||"string"!=typeof a.path||!a.path)continue;let b=D(a.path);b&&(c.has(b)||c.set(b,a.id))}let d=a.runs.map(a=>{let b=!1,d=a.steps.map(a=>{if(!a.sessionFile)return a;let d=D(a.sessionFile),e=d?c.get(d):void 0;if(!e){if(void 0===a.sessionId)return a;let c={...a};return delete c.sessionId,b=!0,c}return a.sessionId===e?a:(b=!0,{...a,sessionId:e})});return b?{...a,steps:d}:a}),e=!1;for(let b=0;b<d.length;b+=1)if(d[b]!==a.runs[b]){e=!0;break}return e?{...a,runs:d}:a}},37594:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{C9:()=>M,DQ:()=>L,Md:()=>I,Wl:()=>J,Yz:()=>H,mB:()=>Q});var e=c(29021),f=c(716),g=c(33873),h=c(80547),i=c(91898),j=c(60396),k=c(95237),l=c(52960),m=c(79495),n=c(81879),o=c(46935),p=c(31514),q=c(65107),r=c(56429),s=c(40402),t=c(85664),u=c(15461),v=c(76817),w=c(86226),x=c(68524),y=c(89953),z=c(50955),A=c(40239),B=c(5815),C=c(99911),D=c(26773),E=c(2416),F=c(68816),G=a([h,i,k,n,r,s,D,E]);[h,i,k,n,r,s,D,E]=G.then?(await G)():G;let L="Subagent sessions are read-only";class M extends Error{constructor(){super(L)}toString(){return this.message}}async function H(a,b){if(await b(a))throw new M}function I(a){let b=a instanceof Error?a.message:String(a);return a instanceof M||b===L?403:b.includes("Session not found")?404:(0,y.wE)(a)||b===y.GT||b===E.v7||"Session is being deleted"===b||b.includes("closed while its title")?409:500}function J(a){let b=a instanceof Error?a.message:String(a);return"cwd is required"===b||b.startsWith("Directory does not exist:")?400:I(a)}let N="Submission was cancelled",O={listAllSessions:s.dQ,resolveSessionPath:s.os,getRpcSession:r.A4,waitForSessionStart:r.DU,startRpcSession:r.OF,getRunningRpcSessionIds:r.HG,listPendingExtensionUi:r.$k,subscribeRunningSessions:r.Fn,allowFileRoot:h.wz,invalidateSessionListCache:s.mD,openSessionCwd:a=>(0,k.kW)(a).getHeader()?.cwd??process.cwd(),openSessionManager:a=>(0,s.Zx)({filePath:a}),openSessionView:k.kW,reparentSessionFile:k.i5,existsSync:e.existsSync,now:()=>Date.now(),archiveFs:A.Iq},P=["systemPrompt"];function K(a){(0,x.xP)(`sessionQueue.${a}`,null),(0,x.xP)(`sessionQueueHold.${a}`,null);let b=(0,x.rV)().unreadSessionState;b&&"object"==typeof b&&!Array.isArray(b)&&(b.completedAt&&"object"==typeof b.completedAt&&(0,x.xP)(`unreadSessionState.completedAt.${a}`,null),b.readAt&&"object"==typeof b.readAt&&(0,x.xP)(`unreadSessionState.readAt.${a}`,null))}let Q=function(a={}){let b={...O,...a},c=(0,A.Ki)({fs:b.archiveFs,agentDir:b.archiveAgentDir,resolveSessionPath:b.resolveSessionPath,readSessionHeader:s.eP,isReadOnly:async a=>{let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},isRunning:a=>b.getRunningRpcSessionIds().includes(a),getSessionInfo:async a=>(await b.listAllSessions()).find(b=>b.id===a)??null,invalidateSessionListCache:b.invalidateSessionListCache,now:()=>new Date(b.now()).toISOString()}),d=()=>(0,A.$T)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)()),h=new Map,r=new Map,x=a=>{if(r.set(a.submissionId,{info:a,cancelRequested:!1,cancelApplied:!1}),!(r.size<=500))for(let[b,c]of r){if(r.size<=500)break;b!==a.submissionId&&"completed"===c.info.status&&r.delete(b)}},E=async a=>{let c=b.getRpcSession(a);if(c){if("function"==typeof c.destroyAsync)return void await c.destroyAsync();c.isAlive()&&c.destroy()}},G=async(a,b)=>{if(!(0,y.kP)(a))throw Error(y.GT);try{return await b()}finally{(0,y.Hl)(a)}},I=async(a,b,c)=>(c?await c():await E(a),G(a,b)),J={async listSessions(){let a=await b.listAllSessions(),{active:c,archived:e}=(0,A.uD)(a,d());return{sessions:c,archivedSessions:e,archivedCount:e.length,runningSessionIds:b.getRunningRpcSessionIds()}},async listArchivedSessions(){let a=await b.listAllSessions();return(0,A.uD)(a,d()).archived},async listActiveSessions(){let a=await b.listAllSessions();return(0,A.uD)(a,d()).active},listAllSessions:async()=>b.listAllSessions(),async isArchived(a){let c=await b.listAllSessions();return(0,A.YV)(c,d()).has(a)},archiveSession:async a=>c.archiveSession(a),restoreSession:async a=>c.restoreSession(a),archiveSessions:async a=>c.archiveSessions(a),restoreSessions:async a=>c.restoreSessions(a),removeArchiveRecordAfterPermanentDelete(a){(0,A.rQ)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)(),a)},resolvePath:a=>b.resolveSessionPath(a),getSessionInfo:async a=>a&&"string"==typeof a?(await b.listAllSessions()).find(b=>b.id===a)??null:null,async isReadOnly(a){let c=(await b.listAllSessions()).find(b=>b.id===a);return c?.readOnly===!0},async getReadView(a){let c=await b.resolveSessionPath(a);if(!c)return null;let d=b.getRpcSession(a),e=d?.inner;return d?.isAlive()&&e?.sessionManager?{source:"live",filePath:c,manager:e.sessionManager}:{source:"disk",filePath:c,manager:b.openSessionManager(c)}},getLive(a){let c=b.getRpcSession(a);return c?.isAlive()?c:void 0},getLiveSession:a=>J.getLive(a),isLive:a=>!!J.getLive(a),async ensureLive(a){if(await H(a,J.isReadOnly),h.has(a))throw Error("Session is being deleted");let c=J.getLive(a);if(c)return c;if((0,y.wy)(a))throw Error(y.GT);let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=b.openSessionCwd(d),{session:f}=await b.startRpcSession(a,d,e,void 0,L);return f},destroy(a){b.getRpcSession(a)?.destroy()},async destroyAsync(a){let c=b.getRpcSession(a);c&&("function"==typeof c.destroyAsync?await c.destroyAsync():c.destroy())},deleteSession(a){let c=h.get(a);if(c)return c;let d=(async()=>{await H(a,J.isReadOnly);let c=await b.waitForSessionStart?.(a)??a,d=await b.resolveSessionPath(a);if(!d){try{K(a)}catch(a){console.error("[pidance] failed to clear queue prefs after missing delete:",a)}return(0,s.BR)(a),b.invalidateSessionListCache(),J.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:0}}if((0,y.wy)(a)||(0,y.wy)(c))throw Error(y.GT);let f=(0,s.eP)(d)?.parentSession,h=(0,s.eP)(d)?.id===a?(0,z.ku)(d,a):[],j=b.getRpcSession(c)??b.getRpcSession(a),k=b.getRunningRpcSessionIds();if(j?.isAlive?.()&&(k.includes(a)||k.includes(c)))try{await j.send({type:"abort"})}catch(a){console.error("[pidance] abort before delete failed:",a)}return await J.destroyAsync(j?.sessionId??c),G(j?.sessionId??c,async()=>{let c=d.replace(/\\/g,"/").split("/").slice(0,-1).join("/");try{for(let a of(0,e.readdirSync)(c).filter(a=>a.endsWith(".jsonl")&&(0,g.join)(c,a)!==d)){let e=(0,g.join)(c,a);try{let a=(0,s.eP)(e);a?.type==="session"&&a.parentSession===d&&(a.id?(await b.waitForSessionStart?.(a.id),await I(a.id,()=>{b.reparentSessionFile(e,f)})):b.reparentSessionFile(e,f))}catch{}}}catch{}try{(0,e.unlinkSync)(d)}catch(a){if("ENOENT"!==a.code)throw a}(0,q.$9)(d);let j=(0,g.resolve)(d.slice(0,-6)),k=(0,z.uq)(h,j,s.BR);try{K(a)}catch(a){console.error("[pidance] failed to clear queue prefs after delete:",a)}try{(0,i.Fx)()}catch(a){console.error("[pidance] failed to sweep attachments:",a)}return(0,s.BR)(a),b.invalidateSessionListCache(),J.removeArchiveRecordAfterPermanentDelete(a),{skippedSubagents:k}})})();return h.set(a,d),d.finally(()=>{h.get(a)===d&&h.delete(a)})},async start(a,c,d,e){if(await H(a,J.isReadOnly),h.has(a))throw Error("Session is being deleted");return b.startRpcSession(a,c,d,e,L)},send:async(a,b)=>(await J.ensureLive(a)).send(b),async submitPrompt(a,b){await H(a,J.isReadOnly);let c=(0,l.JT)(b);try{let b=await J.send(a,c);if(b&&"object"==typeof b&&b.status)return b;return{submissionId:c.submissionId,sessionId:a,status:"rejected",reason:"error"}}catch(b){if((0,y.wE)(b))throw b;return{submissionId:c.submissionId,sessionId:a,status:"rejected",reason:(0,l.K2)(b)}}},async getAgentState(a,b){if(await J.isReadOnly(a))return{live:!1,activeRun:!1,readOnly:!0};let c=J.getLive(a);if(!c)return{live:!1,activeRun:!1,...(0,y.wy)(a)?{lockedByOther:!0}:{}};let d=await c.send({type:"get_state"}),e="function"==typeof c.isRunning?!!c.isRunning():!!(d&&(d.isStreaming||d.isPromptRunning||d.isCompacting||d.isBashRunning));return{live:!0,activeRun:e,lockedByOther:!1,state:function(a,b){if(!b?.light||!a||"object"!=typeof a||Array.isArray(a))return a;let c={...a};for(let a of P)delete c[a];return c}(d,b)}},async renameSession(a,c){await H(a,J.isReadOnly);let d=c.trim();if(!d)throw Error("name is required");let e=J.getLive(a);if(e?.isAlive()){await e.send({type:"set_session_name",name:d}),b.invalidateSessionListCache();return}let f=await b.resolveSessionPath(a);if(!f)throw Error("Session not found");await I(a,()=>{b.openSessionView(f).appendSessionInfo(d),b.invalidateSessionListCache()})},async autoNameSession(a){await H(a,J.isReadOnly);let b=await J.ensureLive(a);await b.waitUntilReady?.();let c=await J.getNavigationSnapshot(a);if(!c)throw Error("Session not found");let d=c.context.messages??[],e=(0,m.CL)(),f=await (0,m.K)({messages:d,provider:e.provider,modelId:e.modelId,baseUrl:e.baseUrl,api:e.api,apiKey:e.apiKey,headers:e.headers});if(!b.isAlive())throw Error("The session was closed while its title was being generated. Please try again.");try{await b.send({type:"set_session_name",name:f.title})}catch{await J.destroyAsync(a),await J.renameSession(a,f.title)}return{title:f.title,usage:f.usage??null}},async exportSession(a,c){let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");return(0,n.by)(d,c)},async getNavigationSnapshot(a,c={}){let d=await J.getReadView(a);if(!d)return null;let{filePath:e,manager:f}=d,{leafId:g,tree:h,context:i,header:j,sessionName:k}=(0,s.jK)(f,c),l=j?.parentSession?await (0,s.u1)(j.parentSession):void 0,m=(await b.listAllSessions()).find(b=>b.id===a),n=j?{path:e,id:j.id,cwd:j.cwd??"",name:k,created:j.timestamp,modified:j.timestamp,messageCount:i.totalMessageCount??i.messages.length,firstMessage:m?.firstMessage??"(no messages)",parentSessionId:l,...m?.subagent?{subagent:m.subagent,readOnly:!0}:{}}:null;return{filePath:e,leafId:g,tree:h,context:i,header:j,sessionName:k,parentSessionId:l,info:n}},async getUserMessageOutline(a){let b=await J.getReadView(a);if(!b)return[];let c=b.manager,d=c.getEntries?.()??[],e=(0,s.CM)(d,c.getLeafId());return(0,C.Xm)((0,s.tY)(d,e))},async getContextPage(a,b){let c,d=await J.getReadView(a);if(!d)return{context:null};let e=d.manager,f=e.getEntries?.()??[],g=(0,s.Uv)(f,b.leafId,{deferThinking:b.deferThinking,deferToolResultImages:b.deferToolResultImages}),h=b.limit;if(b.around){let a=(0,o.PV)(g,b.around,h??o._w,{toEnd:!0===b.aroundToEnd});if(!a)return{context:null,notFound:b.around};c=a}else c=b.after?(0,o.WP)(g,b.after,h??o._w):b.before?(0,o.tr)(g,b.before,h??o._w):null!==h?(0,o.G1)(g,h):{...g,hasMoreBefore:!1,totalMessageCount:g.messages.length};return{context:c}},async getEntryThinking(a,b,c){let d=await J.getReadView(a);if(!d)return null;let e=d.manager.getEntries().find(a=>a.id===b);if(!e||"message"!==e.type||e.message?.role!=="assistant")return null;let f=e.message.content?.[c];return f&&(0,p.mv)(f.type)?{thinking:(0,p.Ux)(f)}:null},async getToolResultDetails(a,b){let c=await J.getReadView(a);if(!c)return null;let d=c.manager.getEntries().find(a=>"message"===a.type&&a.message?.role==="toolResult"&&a.message.toolCallId===b);return d?{details:d.message?.details??null,content:Array.isArray(d.message?.content)?d.message.content:[]}:null},async appendActivity(a,c){await H(a,J.isReadOnly);let d=J.getLive(a),e=!!d?.inner?.sessionManager,f=d?.appendActivity;return d?.isAlive()&&e&&"function"==typeof f?await f.call(d,c):await I(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,t.l$)(c),f=b.openSessionView(d).appendCustomEntry(t.cP,e);return b.invalidateSessionListCache(),{entryId:f,activity:e}})},appendCommandEntry:async(a,c)=>(await H(a,J.isReadOnly),await I(a,async()=>{let d=await b.resolveSessionPath(a);if(!d)throw Error("Session not found");let e=(0,u.fc)(c);if(!e.command)throw Error("command is required");let f=b.openSessionView(d).appendCustomEntry(u.OE,e);return b.invalidateSessionListCache(),{entryId:f,data:e}})),async createNew({cwd:a,command:c}){let d;if(!a||"string"!=typeof a)throw Error("cwd is required");if(!b.existsSync(a))throw Error(`Directory does not exist: ${a}`);let{provider:e,modelId:g,toolNames:h,thinkingLevel:i,...j}=c,l="string"==typeof j.submissionId?j.submissionId:void 0,m=(d="string"==typeof j.message?j.message:"",`${a}\u0000${d}`);if(l){let a=r.get(l);if(a){if(a.info.fingerprint&&a.info.fingerprint!==m)throw a.info.status="conflict",Error("Submission conflict: this submissionId was already used with different content");if(a.cancelRequested)throw a.info.status="cancelled",Error(N);if(a.info.sessionId)return{sessionId:a.info.sessionId,data:null}}x({submissionId:l,status:"pending",fingerprint:m})}let n=`${D.YZ}${(0,f.randomUUID)()}`,{session:o,realSessionId:p}=await b.startRpcSession(n,"",a,h,L),q=l?r.get(l):void 0,s=q?.cancelRequested===!0;q&&(q.info.sessionId=p,q.info.status=s?"cancelled":"starting"),b.allowFileRoot(a),b.invalidateSessionListCache();try{if(s||(e&&g&&await o.send({type:"set_model",provider:e,modelId:g}),i&&await o.send({type:"set_thinking_level",level:i}),l&&r.get(l)?.cancelRequested))throw await J.destroyAsync(p),Error(N)}catch(a){throw q&&(q.info.error=a instanceof Error?a.message:String(a)),a}if("ensure_session"===j.type){try{let a=o.inner,b=a?.sessionManager;b&&"function"==typeof b.getSessionFile&&(0,k.kb)(b)}catch(a){console.error("[pidance] materialize ensure_session failed:",a)}return{sessionId:p,data:null}}let t=await o.send(j);return q&&(q.info.status="accepted",q.info.sessionId=p),{sessionId:p,data:t}},getSubmission(a){let b=r.get(a);return b?{...b.info}:null},cancelSubmission(a){let c=r.get(a);if(!c)return x({submissionId:a,status:"cancelled"}),r.get(a).cancelRequested=!0,Promise.resolve({submissionId:a,status:"pending"});c.cancelRequested=!0;let d=c.info.sessionId;if(!d)return c.info.status="cancelled",Promise.resolve({submissionId:a,status:"pending"});if(c.cancelApplied)return Promise.resolve({submissionId:a,status:"confirmed"});c.cancelApplied=!0,c.info.status="cancelled";let e=b.getRpcSession(d);return e?.isAlive()?(async()=>{try{await e.send({type:"abort"})}catch(a){console.error("[pidance] cancel submission abort failed:",a)}return{submissionId:a,status:"confirmed"}})():Promise.resolve({submissionId:a,status:"confirmed"})},getRunningIds:()=>b.getRunningRpcSessionIds(),getRunningStartedAt(){let a=new Set(b.getRunningRpcSessionIds()),c={};for(let[b,d]of(0,B.MG)())a.has(b)&&(c[b]=d);for(let[b,d]of Object.entries((0,D.EM)()))!a.has(b)||b in c||(c[b]=d);return c},async searchFulltext(a,c={}){let d=await (0,F.s)(a,{limits:void 0!==c.maxHits?{maxHits:c.maxHits}:void 0}),e=c.scope??"active";if("all"===e)return d;let f=await b.listAllSessions(),g=(0,A.$T)(b.archiveFs??A.Iq,b.archiveAgentDir?.()??(0,j.$M)()),h=(0,A.mT)(d.sessionIds,f,g,e);return{...d,sessionIds:d.sessionIds.filter(a=>h.has(a)),hits:d.hits.filter(a=>h.has(a.sessionId))}},listPendingExtensionUi:()=>b.listPendingExtensionUi(),subscribeRunning:a=>b.subscribeRunningSessions(a),async selectLeafExact(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let f=c.trim(),g=b.getRpcSession(a);if(g?.isAlive?.()&&g.inner?.isBashRunning)throw Error("Cannot switch branch while a shell command is running");return e=async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=b.openSessionView(c),e=d.getLeafId();if(f===e)return{cancelled:!1};if(f===d.getLastEntryId())return(0,q.$9)(c),{cancelled:!1};if(!d.getEntry(f))throw Error(`Entry ${f} not found`);try{return d.branch(f),(0,q.R3)(c,f),{cancelled:!1}}finally{b.invalidateSessionListCache()}},I(a,e,d)},async branchFromAssistant(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("assistantEntryId is required");let f=c.trim(),g=b.getRpcSession(a);if(g?.isAlive?.()&&g.inner?.isBashRunning)throw Error("Cannot branch while a shell command is running");return e=async()=>{let c=await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=b.openSessionView(c),e=d.getLeafId();if(!e)throw Error("Session has no leaf");let g=d.getBranch(e),h=d.getEntry(f);if(!h)throw Error("Entry not found");if("message"!==h.type||h.message?.role!=="assistant")throw Error("Only assistant messages can be branched from");let i=(0,v.wo)(g,f);try{return d.branch(i),i===d.getLastEntryId()?(0,q.$9)(c):(0,q.R3)(c,i),{cancelled:!1}}finally{b.invalidateSessionListCache()}},I(a,e,d)},async createSessionFromLeaf(a,c,d){let e;if("string"!=typeof c||""===c.trim())throw Error("entryId is required");let f=c.trim(),g=b.getRpcSession(a),h=g?.inner;return e=async()=>{let c=(h?.sessionFile||g?.sessionFile)??await b.resolveSessionPath(a);if(!c)throw Error("Session not found");let d=(0,k.kW)(c),e=d.getEntry(f);if(!e)throw Error("Invalid entry ID");let i=f;if("message"===e.type&&e.message?.role==="assistant"){let a=d.getLeafId();if(!a)throw Error("Session has no leaf");let b=d.getBranch(a);i=(0,v.wo)(b,f)}let j=d.getSessionDir(),l=(0,k.G1)(c,j),m=l.createBranchedSession(i);if(!m)throw Error("Failed to create session");(0,k.kb)(l);let n=(0,k.kW)(m,j),o=n.getSessionId();(0,s.O8)(o,m),b.invalidateSessionListCache();let p=h?.model;return p&&(0,w.yN)(n.getEntries().some(a=>"model_change"===a.type),{provider:p.provider,modelId:p.id})&&n.appendModelChange(p.provider,p.id),{cancelled:!1,newSessionId:o}},I(a,e,d)}},L={selectLeafExact:(a,b,c)=>J.selectLeafExact(a,b,c),branchFromAssistant:(a,b,c)=>J.branchFromAssistant(a,b,c),createSessionFromLeaf:(a,b,c)=>J.createSessionFromLeaf(a,b,c)};return J}();d()}catch(a){d(a)}})},38195:(a,b,c)=>{c.d(b,{t:()=>g});var d=c(716),e=c(87538);function f(a,b,c,e,f,g,h){let i=(0,d.randomUUID)();return new Promise((d,j)=>{let k,l=!1,m=()=>{a.delete(i),b.delete(i),k&&clearTimeout(k),e?.signal?.removeEventListener("abort",o)},n=a=>{l||(l=!0,m(),d(a))},o=()=>n(f);e?.signal?.addEventListener("abort",o,{once:!0}),e?.timeout&&(k=setTimeout(()=>n(f),e.timeout)),a.set(i,{resolve:a=>{try{n(h(a))}catch(a){if(l)return;l=!0,m(),j(a instanceof Error?a:Error(String(a)))}},reject:a=>{l||(l=!0,m(),j(a))}});let p={type:"extension_ui_request",id:i,...g};b.set(i,p),c(p)})}function g(a){let b=new Map,c=new Map,g=new Map,h=new Map,i=new Map,j=null,k={select:(d,e,g)=>f(b,c,a,g,void 0,{method:"select",title:d,options:e,timeout:g?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),confirm:(d,e,g)=>f(b,c,a,g,!1,{method:"confirm",title:d,message:e,timeout:g?.timeout},a=>(!("cancelled"in a)||!a.cancelled)&&"confirmed"in a&&!!a.confirmed),input:(d,e,g)=>f(b,c,a,g,void 0,{method:"input",title:d,placeholder:e,timeout:g?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),notify(b,c){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"notify",message:b,notifyType:c})},onTerminalInput:()=>()=>{},setStatus(b,c){c?g.set(b,c):g.delete(b),a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setStatus",statusKey:b,statusText:c})},setWorkingMessage(){},setWorkingVisible(){},setWorkingIndicator(){},setHiddenThinkingLabel(){},setWidget(b,c,f){if("function"==typeof c){let a=(0,e.tU)(c,(0,e.Lm)());if(null===a)return;c=a}(void 0===c||Array.isArray(c))&&(null==c?h.delete(b):h.set(b,{lines:c,placement:f?.placement}),a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:c,widgetPlacement:f?.placement}))},setFooter(){},setHeader(){},setTitle(b){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"setTitle",title:b})},async custom(b){let c=(0,d.randomUUID)();return new Promise(d=>{let f,g=!1,h=b=>{g||(g=!0,i.delete(c),j?.id===c&&(j=null),a({type:"extension_ui_request",id:c,method:"custom",closed:!0,lines:[]}),d(b))},l=()=>{if(g)return;let b=[];try{let a=f?.render?.(92);Array.isArray(a)&&(b=a.filter(a=>"string"==typeof a))}catch(a){console.error("[pidance] custom UI render failed:",a)}a({type:"extension_ui_request",id:c,method:"custom",lines:b}),j={id:c,lines:[...b]}};i.set(c,{handleInput:a=>{if("\x03"===a)return void h(void 0);try{f?.handleInput?.(a)}catch(a){console.error("[pidance] custom UI input failed:",a)}},done:h});let m=function(a,b=92,c=40){return Object.freeze({terminal:Object.freeze({columns:b,rows:c,kittyProtocolActive:!1}),requestRender:a})}(()=>{l()},92,40),n=(0,e.Lm)()??k.theme;Promise.resolve().then(()=>b(m,n,{},h)).then(a=>{g||(f=a,l())}).catch(a=>{console.error("[pidance] custom UI factory failed:",a),h(void 0)})})},pasteToEditor(a){this.setEditorText(a)},setEditorText(b){a({type:"extension_ui_request",id:(0,d.randomUUID)(),method:"set_editor_text",text:b})},getEditorText:()=>"",editor:async(d,e)=>f(b,c,a,void 0,void 0,{method:"editor",title:d,prefill:e},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){let a=a=>String(a??""),b=(a,b)=>void 0===b?"":String(b);return new Proxy({fg:b,bg:b,bold:a,dim:a,italic:a},{get:(b,c)=>c in b?b[c]:"then"!==c?a:void 0})},getAllThemes:()=>[],getTheme(){},setTheme:()=>({success:!1,error:"Theme switching not supported in Web mode"}),getToolsExpanded:()=>!1,setToolsExpanded(){}};return{uiContext:k,pending:b,statuses:g,widgets:h,pendingSnapshot:c,get customSnapshot(){return j},respond(a,c){let d=b.get(a);return!!d&&(d.resolve(c),!0)},inputCustom(a,b){let c=i.get(a);return!!c&&(c.handleInput(b),!0)},dispose(){for(let[a,d]of b)b.delete(a),c.delete(a),d.reject(Error("Extension UI disposed"));for(let a of i.values())a.done(void 0);i.clear(),j=null,g.clear(),h.clear()}}}},40239:(a,b,c)=>{c.d(b,{$T:()=>m,Iq:()=>g,J3:()=>t,Ki:()=>u,YV:()=>q,mT:()=>r,rQ:()=>p,uD:()=>s});var d=c(29021),e=c(33873),f=c(60396);let g={existsSync:d.existsSync,lstatSync:d.lstatSync,mkdirSync:d.mkdirSync,readFileSync:(a,b)=>(0,d.readFileSync)(a,b),writeFileSync:(a,b,c)=>(0,d.writeFileSync)(a,b,c),renameSync:d.renameSync,unlinkSync:d.unlinkSync,readdirSync:d.readdirSync};function h(a=(0,f.$M)()){return(0,e.join)(a,"pidance-archive")}function i(a){return"string"!=typeof a||a.length<8||a.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(a)?null:`${a}.json`}function j(a,b){try{let c=h(b);if(!a.existsSync(c))return null;let d=a.lstatSync(c);if(d.isSymbolicLink()||!d.isDirectory())return null;return c}catch{return null}}function k(a){return"object"==typeof a&&null!==a&&!(1!==a.version||"string"!=typeof a.sessionId||0===a.sessionId.length||"string"!=typeof a.sessionPath||0===a.sessionPath.length||"string"!=typeof a.archivedAt||Number.isNaN(Date.parse(a.archivedAt)))}function l(a,b,c){let d=i(c);if(!d)return null;let f=j(a,b);if(!f)return null;let g=(0,e.join)(f,d);try{if(!a.existsSync(g)||a.lstatSync(g).isSymbolicLink())return null;let b=a.readFileSync(g,"utf8");if(b.length>65536)return null;let d=JSON.parse(b);if(!k(d)||d.sessionId!==c)return null;return d}catch{return null}}function m(a,b){let c=globalThis.__piArchiveRecordsCache;if(c&&Date.now()-c.ts<5e3)return c.records;let d=j(a,b),e=[];if(d){let c=[];try{c=a.readdirSync(d)}catch{c=[]}for(let d of c){let c=function(a){if("string"!=typeof a||!a.endsWith(".json"))return null;let b=a.slice(0,-5);return b.length<8||b.length>64||!/^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/.test(b)?null:b}(d);if(!c)continue;let f=l(a,b,c);f&&e.push(f)}}return globalThis.__piArchiveRecordsCache={records:e,ts:Date.now()},e}function n(){globalThis.__piArchiveRecordsCache=void 0}function o(a,b,c){let d=i(c);if(!d)return!1;let f=j(a,b);if(!f)return!1;let g=(0,e.join)(f,d);try{if(!a.existsSync(g))return!1;return a.unlinkSync(g),n(),!a.existsSync(g)}catch{return!1}}function p(a,b,c){o(a,b,c)}function q(a,b){let c=new Map;for(let a of b)c.set(a.sessionId,a);let d=new Set;for(let b of a){let a=c.get(b.id);a&&a.sessionPath===b.path&&d.add(b.id)}return d}function r(a,b,c,d){let e=q(b,c),f=new Set;for(let b of a){let a=e.has(b);("active"===d?!a:a)&&f.add(b)}return f}function s(a,b){let c=q(a,b),d=new Map;for(let a of b)d.set(a.sessionId,a);let e=[],f=[];for(let b of a)if(c.has(b.id)){let a=d.get(b.id);f.push({...b,archivedAt:a?a.archivedAt:void 0})}else e.push(b);return{active:e,archived:f}}class t extends Error{constructor(){super("Session is running; cannot archive while active")}toString(){return this.message}}function u(a){let b=a.fs??g,c=()=>a.agentDir?.()??(0,f.$M)(),d=async d=>{if(await a.isReadOnly(d))throw Error("Subagent sessions are read-only");if(a.isRunning(d))throw new t;let f=await a.resolveSessionPath(d);if(!f)throw Error("Session not found");let g=a.readSessionHeader(f);if(!g||g.id!==d)throw Error("Session header id mismatch");let j={version:1,sessionId:d,sessionPath:f,archivedAt:a.now()};return!function(a,b,c){let d=i(c.sessionId);if(!d)throw Error("Invalid session id");if(!k(c))throw Error("Invalid archive record");let f=function(a,b){let c=h(b);try{a.existsSync(c)||a.mkdirSync(c,{recursive:!0});let b=a.lstatSync(c);if(b.isSymbolicLink()||!b.isDirectory())return null;return c}catch{return null}}(a,b);if(!f)throw Error("Archive directory unavailable");let g=(0,e.join)(f,d),j=(0,e.join)(f,`.${d}.${process.pid}.${Date.now().toString(36)}.tmp`);try{a.writeFileSync(j,JSON.stringify(c),{encoding:"utf8",flag:"wx"}),a.renameSync(j,g),n()}catch(b){try{a.existsSync(j)&&a.unlinkSync(j)}catch{}throw b}}(b,c(),j),a.invalidateSessionListCache(),j.archivedAt},j=async d=>{if(null===l(b,c(),d))throw Error("Session is not archived");if(!await a.resolveSessionPath(d))throw Error("Session not found");if(!o(b,c(),d))throw Error("Failed to remove archive record");return a.invalidateSessionListCache(),a.getSessionInfo(d)},m=async a=>{let b=[],c=[];for(let e of a)try{await d(e),b.push(e)}catch(a){c.push({id:e,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}},p=async a=>{let b=[],c=[];for(let d of a)try{await j(d),b.push(d)}catch(a){c.push({id:d,error:a instanceof Error?a.message:String(a)})}return{succeededIds:b,failed:c}};return{archiveSession:d,restoreSession:j,archiveSessions:m,restoreSessions:p}}},46935:(a,b,c)=>{c.d(b,{G1:()=>h,NN:()=>g,PV:()=>i,Uf:()=>d,WP:()=>j,_w:()=>e,tr:()=>k});let d=80,e=80;function f(a,b){return"number"==typeof a&&Number.isFinite(a)?Math.max(1,Math.min(Math.floor(a),500)):b}function g(a,b=d){let c=a.get("limit")??a.get("tail");if(null===c||""===c)return null;let e=Number(c);return!Number.isFinite(e)||e<=0?b:f(e,b)}function h(a,b=d){let c=a.messages.length,e=f(b,d);if(c<=e)return{...a,hasMoreBefore:!1,hasMoreAfter:!1,totalMessageCount:c};let g=c-e;return{messages:a.messages.slice(g),entryIds:a.entryIds.slice(g),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:!1,totalMessageCount:c}}function i(a,b,c=e,d={}){let g=a.messages.length,h=a.entryIds.indexOf(b);if(h<0)return null;let j=f(c,e),k=Math.max(0,h-Math.max(1,Math.floor(j/2))),l=d.toEnd?g:Math.min(g,k+j);return{messages:a.messages.slice(k,l),entryIds:a.entryIds.slice(k,l),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:k>0,hasMoreAfter:l<g,totalMessageCount:g}}function j(a,b,c=e){let d=a.messages.length,g=a.entryIds.indexOf(b);if(g<0||g>=d-1)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:!1,totalMessageCount:d};let h=Math.min(d,g+1+f(c,e));return{messages:a.messages.slice(g+1,h),entryIds:a.entryIds.slice(g+1,h),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!0,hasMoreAfter:h<d,totalMessageCount:d}}function k(a,b,c=e){let d=a.messages.length,g=a.entryIds.indexOf(b);if(g<=0)return{messages:[],entryIds:[],thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:!1,hasMoreAfter:!1,totalMessageCount:d};let h=Math.max(0,g-f(c,e));return{messages:a.messages.slice(h,g),entryIds:a.entryIds.slice(h,g),thinkingLevel:a.thinkingLevel,model:a.model,hasMoreBefore:h>0,hasMoreAfter:!0,totalMessageCount:d}}},52960:(a,b,c)=>{c.d(b,{$3:()=>o,D_:()=>s,JT:()=>k,K2:()=>g,QR:()=>t,QT:()=>p,TJ:()=>r,_3:()=>n,in:()=>f,s:()=>q});var d=c(13737),e=c(99014);function f(a){return"busy"===a||"compacting"===a||"bash"===a}function g(a){let b=a instanceof Error?a.message:String(a);return/already processing|already running|streamingBehavior/i.test(b)?"busy":/shell command is running/i.test(b)?"bash":/compaction/i.test(b)?"compacting":/cannot be queued|Extension command/i.test(b)?"extension":/no (valid )?model|model not found|未选择模型/i.test(b)?"model":/401|403|unauthor|api key|authentication|permission denied/i.test(b)?"auth":/running lease|locked by another|another process/i.test(b)?"locked":"error"}function h(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`sub-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function i(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("images must be an array");let b=[];for(let c of a){if(!c||"object"!=typeof c)throw Error("invalid image");if("ref"===c.type){let a="string"==typeof c.path?c.path.trim():"",e=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!a||!e?.startsWith("image/"))throw Error("invalid image");b.push({type:"ref",path:a,mimeType:e});continue}let a="string"==typeof c.data?c.data:void 0,e="string"==typeof c.mimeType?c.mimeType:"string"==typeof c.mime_type?c.mime_type:void 0,f=(0,d.Ln)(e);if(!a||!f?.startsWith("image/"))throw Error("invalid image");if(a.length>4194304)throw Error("invalid image: payload too large");b.push({type:"image",data:a,mimeType:f})}return b}function j(a){if("string"!=typeof a.message)throw Error("message is required");return a.message}function k(a,b=h){return{type:"prompt",message:j(a),submissionId:"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b(),images:i(a.images),binaryBlocks:function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("binaryBlocks must be an array");if(a.length>32)throw Error("too many binary blocks");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid binary block");let a="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.name?c.name.trim():"",f=(0,d.Ln)(c.mimeType),g=c.size,h=void 0===c.previewPath?void 0:"string"==typeof c.previewPath?c.previewPath.trim():null;if(!a||!e||!f||!Number.isSafeInteger(g)||g<0||null===h)throw Error("invalid binary block");b.push({path:a,name:e,mimeType:f,size:g,...h?{previewPath:h}:{}})}return b}(a.binaryBlocks)}}function l(a,b){return"string"==typeof a.submissionId&&a.submissionId.trim()?a.submissionId.trim():b()}function m(a){if(null==a)return null;if("number"!=typeof a||!Number.isFinite(a)||a<0)throw Error("expectedRevision must be a non-negative number");return a}function n(a,b=h){return{type:"steer",message:j(a),submissionId:l(a,b),images:i(a.images)}}function o(a,b=h){return{type:"follow_up",message:j(a),submissionId:l(a,b),images:i(a.images)}}function p(a,b=h){if(void 0!==a.items&&!Array.isArray(a.items))throw Error("items must be an array");let c=[];for(let b of Array.isArray(a.items)?a.items:[]){let a,f;if("string"==typeof b){if(!b.trim())throw Error("items must not contain empty text");c.push({text:b});continue}if(!b||"object"!=typeof b||Array.isArray(b)||"string"!=typeof b.text)throw Error("items must be strings or { text, media? } objects");let g=function(a){if(void 0===a)return;if(!Array.isArray(a))throw Error("invalid queue media");if(0===a.length)return;if(a.length>e.ym)throw Error("invalid queue media: too many refs");let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))throw Error("invalid queue media");let a="model"===c.role||"original"===c.role?c.role:null,e="string"==typeof c.path?c.path.trim():"";if(!a||!e)throw Error("invalid queue media");let f=(0,d.Ln)("string"==typeof c.mimeType?c.mimeType:void 0);if(!f||"model"===a&&!f.startsWith("image/"))throw Error("invalid queue media");let g="string"==typeof c.name&&c.name.trim()?c.name.trim():"",h=c.size;if(!g||"number"!=typeof h||!Number.isSafeInteger(h)||h<0)throw Error("invalid queue media");let i="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(void 0!==c.previewPath&&!i)throw Error("invalid queue media");b.push({role:a,path:e,name:g,mimeType:f,size:h,...i&&i!==e?{previewPath:i}:{}})}return b.length?b:void 0}(b.media);if(!b.text.trim()&&!g?.length)throw Error("items must not be empty");if(void 0!==b.attemptId&&!(a=(0,e.Kk)(b.attemptId)??void 0))throw Error("invalid item attemptId");if(void 0!==b.id&&!(f=(0,e.mv)(b.id)??void 0))throw Error("invalid item id");c.push({text:b.text,...g?{media:g}:{},...a?{attemptId:a}:{},...f?{id:f}:{}})}return{type:"set_follow_up_queue",items:c,expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function q(a,b=h){let c,d="string"==typeof a.extra?a.extra:void 0;if(void 0!==a.extraAttemptId&&!(c=(0,e.Kk)(a.extraAttemptId)??void 0))throw Error("invalid extraAttemptId");return{type:"dispatch_follow_up_queue",...void 0!==d?{extra:d}:{},...c?{extraAttemptId:c}:{},expectedRevision:m(a.expectedRevision),submissionId:l(a,b)}}function r(a,b=h){if(!Array.isArray(a.itemIds))throw Error("itemIds must be an array");if(0===a.itemIds.length)throw Error("itemIds must not be empty");if(a.itemIds.length>256)throw Error("too many itemIds");let c=[];for(let b of a.itemIds){let a="string"==typeof b?b.trim():"";if(!a)throw Error("invalid itemId");c.includes(a)||c.push(a)}return{type:"recall_follow_up_queue",itemIds:c,submissionId:l(a,b)}}function s(a){return"prompt"===a||"abort"===a||"steer"===a||"follow_up"===a||"set_follow_up_queue"===a||"dispatch_follow_up_queue"===a||"recall_follow_up_queue"===a}function t(a,b=h){if(!a||"object"!=typeof a||Array.isArray(a))throw Error("command is required");let c=a.type;if("prompt"===c)return k(a,b);if("abort"===c)return{type:"abort"};if("steer"===c)return n(a,b);if("follow_up"===c)return o(a,b);if("set_follow_up_queue"===c)return p(a,b);if("dispatch_follow_up_queue"===c)return q(a,b);if("recall_follow_up_queue"===c)return r(a,b);throw Error(`Unsupported message command: ${String(c)}`)}},53023:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Uj:()=>j});var e=c(85664),f=c(93127),g=c(95237),h=a([f,g]);function i(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}[f,g]=h.then?(await h)():h;let k=`
2
2
  .pidance-activity{margin:1.5rem 0;padding:1rem 1.25rem;border:1px solid #ccc;border-radius:8px;background:#fafafa;color:#222;font-family:system-ui,-apple-system,Segoe UI,sans-serif;font-size:14px;line-height:1.45}
3
3
  .pidance-activity h2{margin:0 0 0.75rem;font-size:1.1rem;font-weight:600}
4
4
  .pidance-activity-card{margin:0.75rem 0;padding:0.75rem 1rem;border:1px solid #ddd;border-radius:6px;background:#fff}
@@ -10,7 +10,7 @@
10
10
  .pidance-activity-kind{display:inline-block;padding:0.1rem 0.45rem;border-radius:4px;background:#eee;font-weight:600;text-transform:uppercase;letter-spacing:0.03em;font-size:11px}
11
11
  .pidance-activity-card h3{margin:0 0 0.5rem;font-size:1rem;font-weight:600;word-break:break-word}
12
12
  .pidance-activity-content{margin:0;padding:0.5rem 0.65rem;border-radius:4px;background:#f5f5f5;color:#111;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px;white-space:pre-wrap;word-break:break-word;overflow-x:auto}
13
- `.trim();function j(a,b,c={}){let d=(0,g.kW)(b);return function(a,b,c={}){let d=function(a,b={}){let c=b.leafId,d="string"==typeof c&&c.length>0?c:void 0;if(void 0!==d&&!a.getEntry(d))throw new f.Zq(`Invalid leafId: ${d}`);let g=void 0!==d?a.getBranch(d):a.getBranch(),h=[];for(let a of g){if(!(0,e.o7)(a))continue;let b=(0,e.p_)(a.data);if(!b)continue;let c={entryId:a.id,activity:b};"string"==typeof a.timestamp&&a.timestamp.length>0&&(c.timestamp=a.timestamp),h.push(c)}return h}(b,c),g=function(a){if(0===a.length)return"";let b=a.map(a=>{let{activity:b,entryId:c,timestamp:d}=a,e=i(b.kind),f=i(b.title),g=i(b.content),h=[`<span class="pidance-activity-kind">${e}</span>`];return void 0!==d&&h.push(`<time datetime="${i(d)}">${i(d)}</time>`),void 0!==b.source&&h.push(`<span class="pidance-activity-source">source: ${i(b.source)}</span>`),void 0!==b.requestId&&h.push(`<span class="pidance-activity-request-id">requestId: ${i(b.requestId)}</span>`),`<article class="pidance-activity-card" data-kind="${e}" data-entry-id="${i(c)}"><div class="pidance-activity-meta">${h.join("")}</div><h3>${f}</h3><pre class="pidance-activity-content">${g}</pre></article>`}).join("\n");return['<section class="pidance-activity" id="pidance-session-activity" aria-label="Session activity">',`<style>${k}</style>`,"<h2>Session activity</h2>",b,"</section>"].join("\n")}(d);return function(a,b){let c;if(0===b.length)return a;let d=/<\/body\s*>/i.exec(a);if(!d||void 0===d.index)return`${a}${b}`;let e=d.index,f=d[0],g=/<\/body\s*>/gi;for(;null!==(c=g.exec(a));)e=c.index,f=c[0];return a.slice(0,e)+b+"\n"+f+a.slice(e+f.length)}(a,g)}(a,d,c)}d()}catch(a){d(a)}})},56429:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>e.$k,A4:()=>e.A4,DU:()=>e.DU,Fn:()=>e.Fn,HG:()=>e.HG,OF:()=>e.OF});var e=c(26773),f=a([e]);e=(f.then?(await f)():f)[0],d()}catch(a){d(a)}})},60185:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Nu:()=>m,iU:()=>l});var e=c(89477),f=c(86697),g=c(60396),h=c(69835),i=c(13737),j=a([h]);h=(j.then?(await j)():j)[0];class n extends Error{constructor(a){super(a),this.name="BinaryMessageError"}}function k(a,b){let c,d,g=(0,e.realpathSync)((0,h.eq)(b));try{c=(0,e.realpathSync)((0,f.resolve)(a))}catch{throw new n("binary media file not found")}let i=(0,f.relative)(g,c);if(!i||".."===i||i.startsWith(`..${f.sep}`)||(0,f.isAbsolute)(i))throw new n("binary media path is not allowed");try{d=(0,e.statSync)(c)}catch{throw new n("binary media file not found")}if(!d.isFile())throw new n("binary media must be a file");return{path:c.replace(/\\/g,"/"),size:d.size}}function l(a,b=(0,g.$M)(),c){if(!a||"object"!=typeof a||"string"!=typeof a.name||!a.name.trim()||"string"!=typeof a.path||!a.path.trim())throw new n("invalid binary block");let d=(0,i.Ln)(a.mimeType);if(!d)throw new n("invalid binary MIME type");let e=(0,h.uF)(a.name);if(!e)throw new n("binary file name is required");let f=k(a.path,b),j=a.previewPath?k(a.previewPath,b):void 0;return(0,i.PB)({path:f.path,name:e,mimeType:d,size:f.size,...j?{previewPath:j.path}:{}},c)}function m(a,b=(0,g.$M)()){if(!a||0===a.length)return[];if(a.length>32)throw new n("too many binary blocks");return a.map(a=>l(a,b))}d()}catch(a){d(a)}})},62693:(a,b,c)=>{c.d(b,{E:()=>d});function d(a,b,c){let d=a.getModel?.(b,c);return d||a.getAvailableSnapshot?.().find(a=>a.provider===b&&a.id===c)}},68524:(a,b,c)=>{c.d(b,{Nj:()=>n,UQ:()=>h,m6:()=>g,ql:()=>l,rU:()=>o,rV:()=>i,xP:()=>m});var d=c(89477),e=c(86697),f=c(60396);function g(a=(0,f.$M)()){return(0,e.join)(a,"pidance-preferences.json")}function h(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function i(a=(0,f.$M)()){let b=g(a);if(!(0,d.existsSync)(b))return{};try{let a=JSON.parse((0,d.readFileSync)(b,"utf8"));return h(a)?a:{}}catch{return{}}}function j(a,b){let c=g(a),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let h=`${c}.lock`,i=Date.now()+15e3,j=null;for(;null===j;)try{j=(0,d.openSync)(h,"wx",384)}catch(a){if("EEXIST"!==a.code)throw a;try{Date.now()-(0,d.statSync)(h).mtimeMs>6e4&&(0,d.unlinkSync)(h)}catch{}if(Date.now()>=i)throw Error("Timed out acquiring Pidance preferences lock");!function(){let a=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(a,0,0,10)}()}try{return b()}finally{(0,d.closeSync)(j);try{(0,d.unlinkSync)(h)}catch{}}}function k(a,b){let c=g(b),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let h=`${c}.${process.pid}.${Date.now()}.tmp`;try{(0,d.writeFileSync)(h,JSON.stringify(a,null,2),{flag:"wx",mode:384}),(0,d.renameSync)(h,c)}catch(a){try{(0,d.unlinkSync)(h)}catch{}throw a}}function l(a,b){let c=b.split("."),d=a;for(let a of c){if("object"!=typeof d||null===d)return;d=d[a]}return d}function m(a,b,c=(0,f.$M)()){j(c,()=>{let d=i(c);!function(a,b,c){let d=b.split("."),e=a;for(let a=0;a<d.length-1;a++){let b=d[a],c=e[b];("object"!=typeof c||null===c||Array.isArray(c))&&(e[b]={}),e=e[b]}let f=d[d.length-1];null==c?delete e[f]:e[f]=c}(d,a,b),k(d,c)})}function n(a){let b={},c=[];for(let[d,e]of Object.entries(a)){if("sessionQueue"===d||d.startsWith("sessionQueue.")){c.push(d);continue}b[d]=e}return{patch:b,dropped:c}}function o(a,b=(0,f.$M)()){return j(b,()=>{let c=function(a,b){let c={...a};for(let[a,d]of Object.entries(b))if(null===d)delete c[a];else if(h(d)&&h(c[a])){let b={...c[a]};for(let[a,c]of Object.entries(d))null===c?delete b[a]:b[a]=c;c[a]=b}else c[a]=d;return c}(i(b),a);return k(c,b),c})}},68816:(a,b,c)=>{c.d(b,{s:()=>q});var d=c(89477),e=c(25680),f=c(86697),g=c(60396);let h={maxHits:40,maxFiles:120,maxBytesPerFile:2097152,maxTotalBytes:0x2000000,snippetRadius:48},i=/\b(OR|AND|NOT|NEAR)\b/,j=/"([^"]*)"|(\S+)/g,k=new Set(["and","or","not","near"]);function l(a,b,c=h.snippetRadius){let d=a.replace(/\s+/g," ").trim();if(!d)return"";let e=b.trim();if(!e)return d.slice(0,2*c);let f=d.toLowerCase().indexOf(e.toLowerCase());if(f<0)return d.length>2*c?`${d.slice(0,2*c)}…`:d;let g=Math.max(0,f-c),i=Math.min(d.length,f+e.length+c),j=g>0?"…":"",k=i<d.length?"…":"";return`${j}${d.slice(g,i)}${k}`}function m(a,b){if(!b(a))return!1;try{return(0,d.statSync)(a).isFile()&&(0,d.statSync)(a).size>0}catch{return!1}}function n(a){let b=function(){try{let a=c(79868);if("function"==typeof a?.DatabaseSync)return a.DatabaseSync}catch{}try{let{createRequire:a}=c(55822),b=a(__filename)("node:sqlite");if("function"==typeof b?.DatabaseSync)return b.DatabaseSync}catch{}return null}();if(!b)return null;let d=a.replace(/\\/g,"/"),e=`file:${d}?mode=ro&immutable=1`;try{return new b(e,{readOnly:!0})}catch{}try{return new b(a,{readOnly:!0})}catch{return null}}async function o(a,b,c=h){let f,g=b.trim().toLowerCase();if(!g)return[];let i=0;try{i=(0,d.statSync)(a).size}catch{return[]}if(i<=0||i>c.maxBytesPerFile)return[];let j=[],k=(f=(a.replace(/\\/g,"/").split("/").pop()??"").match(/_([0-9a-fA-F-]{8,})\.jsonl$/),f?.[1]??null),m=0,n=(0,d.createReadStream)(a,{encoding:"utf8"}),p=(0,e.createInterface)({input:n,crlfDelay:1/0});try{for await(let a of p){if((m+=Buffer.byteLength(a,"utf8")+1)>c.maxBytesPerFile)break;let d=function(a){let b,c=a.trim();if(!c||"{"!==c[0])return null;try{b=JSON.parse(c)}catch{return null}if(!b||"object"!=typeof b)return null;let d=b;if("session"===d.type&&"string"==typeof d.id)return{sessionId:d.id,text:""};if("message"!==d.type)return null;let e=d.message;if(!e||"object"!=typeof e)return null;let f="string"==typeof e.role?e.role:void 0;if("user"!==f&&"assistant"!==f&&"system"!==f)return null;let g=function(a){if("string"==typeof a)return a;if(!Array.isArray(a))return"";let b=[];for(let c of a){if("string"==typeof c){b.push(c);continue}c&&"object"==typeof c&&("string"==typeof c.text?b.push(c.text):"string"==typeof c.content?b.push(c.content):"string"==typeof c.thinking&&b.push(c.thinking))}return b.join("\n").trim()}(e.content);return g?{messageId:"string"==typeof d.id?d.id:void 0,role:f,timestamp:"string"==typeof d.timestamp?d.timestamp:"string"==typeof e.timestamp?e.timestamp:void 0,text:g}:null}(a);if(d){if(d.sessionId){k=d.sessionId;continue}k&&d.text.toLowerCase().includes(g)&&j.push({sessionId:k,role:d.role,snippet:l(d.text,b,c.snippetRadius),timestamp:d.timestamp??"",messageId:d.messageId})}}}catch{}finally{p.close(),n.destroy()}return j}function p(a){let b=new Set,c=[];for(let d of a)b.has(d.sessionId)||(b.add(d.sessionId),c.push(d.sessionId));return c}async function q(a,b={}){let c=a.trim(),e={...h,...b.limits},r={...{getAgentDir:g.$M,resolveHermesDbPath:a=>(function(a,b=d.existsSync){let c=(0,f.join)(a,"hermes-memory-config.json");if(b(c))try{let h=JSON.parse((0,d.readFileSync)(c,"utf8"));if("string"==typeof h.memoryDir&&h.memoryDir.trim()){var e,g;let c=(e=h.memoryDir.trim(),g=a,"~"===e?process.env.HOME??g:e.startsWith("~/")||e.startsWith("~\\")?(0,f.join)(process.env.HOME??g,e.slice(2)):e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)?e:(0,f.join)(g,e)),d=(0,f.join)(c,"sessions.db");if(b(d)&&m(d,b))return d}}catch{}for(let c of[(0,f.join)(a,"pi-hermes-memory","sessions.db"),(0,f.join)(a,"memory","sessions.db")])if(b(c)&&m(c,b))return c;return null})(a),openSqliteReadonly:n,listJsonlFiles:a=>(function(a,b){if(!(0,d.existsSync)(a))return[];let c=[],e=a=>{let g;if(!(c.length>=b)){try{g=(0,d.readdirSync)(a,{withFileTypes:!0})}catch{return}for(let d of(g.sort((a,b)=>b.name.localeCompare(a.name)),g)){if(c.length>=b)return;let g=(0,f.join)(a,d.name);if(d.isDirectory()){e(g);continue}d.isFile()&&d.name.endsWith(".jsonl")&&c.push(g)}}};return e(a),c})(a,h.maxFiles),scanJsonlFile:o,existsSync:d.existsSync},...b.deps};if(!c)return{query:"",source:"none",hits:[],sessionIds:[]};let s=r.getAgentDir(),t=r.resolveHermesDbPath(s);if(t){let a=r.openSqliteReadonly(t);if(a)try{let b=function(a,b,c){let d=d=>{let e=`
13
+ `.trim();function j(a,b,c={}){let d=(0,g.kW)(b);return function(a,b,c={}){let d=function(a,b={}){let c=b.leafId,d="string"==typeof c&&c.length>0?c:void 0;if(void 0!==d&&!a.getEntry(d))throw new f.Zq(`Invalid leafId: ${d}`);let g=void 0!==d?a.getBranch(d):a.getBranch(),h=[];for(let a of g){if(!(0,e.o7)(a))continue;let b=(0,e.p_)(a.data);if(!b)continue;let c={entryId:a.id,activity:b};"string"==typeof a.timestamp&&a.timestamp.length>0&&(c.timestamp=a.timestamp),h.push(c)}return h}(b,c),g=function(a){if(0===a.length)return"";let b=a.map(a=>{let{activity:b,entryId:c,timestamp:d}=a,e=i(b.kind),f=i(b.title),g=i(b.content),h=[`<span class="pidance-activity-kind">${e}</span>`];return void 0!==d&&h.push(`<time datetime="${i(d)}">${i(d)}</time>`),void 0!==b.source&&h.push(`<span class="pidance-activity-source">source: ${i(b.source)}</span>`),void 0!==b.requestId&&h.push(`<span class="pidance-activity-request-id">requestId: ${i(b.requestId)}</span>`),`<article class="pidance-activity-card" data-kind="${e}" data-entry-id="${i(c)}"><div class="pidance-activity-meta">${h.join("")}</div><h3>${f}</h3><pre class="pidance-activity-content">${g}</pre></article>`}).join("\n");return['<section class="pidance-activity" id="pidance-session-activity" aria-label="Session activity">',`<style>${k}</style>`,"<h2>Session activity</h2>",b,"</section>"].join("\n")}(d);return function(a,b){let c;if(0===b.length)return a;let d=/<\/body\s*>/i.exec(a);if(!d||void 0===d.index)return`${a}${b}`;let e=d.index,f=d[0],g=/<\/body\s*>/gi;for(;null!==(c=g.exec(a));)e=c.index,f=c[0];return a.slice(0,e)+b+"\n"+f+a.slice(e+f.length)}(a,g)}(a,d,c)}d()}catch(a){d(a)}})},56429:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$k:()=>e.$k,A4:()=>e.A4,DU:()=>e.DU,Fn:()=>e.Fn,HG:()=>e.HG,OF:()=>e.OF});var e=c(26773),f=a([e]);e=(f.then?(await f)():f)[0],d()}catch(a){d(a)}})},60185:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Nu:()=>m,iU:()=>l});var e=c(89477),f=c(86697),g=c(60396),h=c(69835),i=c(13737),j=a([h]);h=(j.then?(await j)():j)[0];class n extends Error{constructor(a){super(a),this.name="BinaryMessageError"}}function k(a,b){let c,d,g=(0,e.realpathSync)((0,h.eq)(b));try{c=(0,e.realpathSync)((0,f.resolve)(a))}catch{throw new n("binary media file not found")}let i=(0,f.relative)(g,c);if(!i||".."===i||i.startsWith(`..${f.sep}`)||(0,f.isAbsolute)(i))throw new n("binary media path is not allowed");try{d=(0,e.statSync)(c)}catch{throw new n("binary media file not found")}if(!d.isFile())throw new n("binary media must be a file");return{path:c.replace(/\\/g,"/"),size:d.size}}function l(a,b=(0,g.$M)(),c){if(!a||"object"!=typeof a||"string"!=typeof a.name||!a.name.trim()||"string"!=typeof a.path||!a.path.trim())throw new n("invalid binary block");let d=(0,i.Ln)(a.mimeType);if(!d)throw new n("invalid binary MIME type");let e=(0,h.uF)(a.name);if(!e)throw new n("binary file name is required");let f=k(a.path,b),j=a.previewPath?k(a.previewPath,b):void 0;return(0,i.PB)({path:f.path,name:e,mimeType:d,size:f.size,...j?{previewPath:j.path}:{}},c)}function m(a,b=(0,g.$M)()){if(!a||0===a.length)return[];if(a.length>32)throw new n("too many binary blocks");return a.map(a=>l(a,b))}d()}catch(a){d(a)}})},62693:(a,b,c)=>{c.d(b,{E:()=>d});function d(a,b,c){let d=a.getModel?.(b,c);return d||a.getAvailableSnapshot?.().find(a=>a.provider===b&&a.id===c)}},68524:(a,b,c)=>{c.d(b,{Gc:()=>q,Nj:()=>p,UQ:()=>i,fN:()=>r,m6:()=>h,ql:()=>n,rV:()=>j,xP:()=>o});var d=c(89477),e=c(86697),f=c(60396),g=c(75052);function h(a=(0,f.$M)()){return(0,e.join)(a,"pidance-preferences.json")}function i(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function j(a=(0,f.$M)()){let b=h(a);if(!(0,d.existsSync)(b))return{};try{let a=JSON.parse((0,d.readFileSync)(b,"utf8"));return i(a)?a:{}}catch{return{}}}function k(a,b){let c=h(a),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let g=`${c}.lock`,i=Date.now()+15e3,j=null;for(;null===j;)try{j=(0,d.openSync)(g,"wx",384)}catch(a){if("EEXIST"!==a.code)throw a;try{Date.now()-(0,d.statSync)(g).mtimeMs>6e4&&(0,d.unlinkSync)(g)}catch{}if(Date.now()>=i)throw Error("Timed out acquiring Pidance preferences lock");!function(){let a=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(a,0,0,10)}()}try{return b()}finally{(0,d.closeSync)(j);try{(0,d.unlinkSync)(g)}catch{}}}function l(a,b){let c=h(b),f=(0,e.dirname)(c);(0,d.existsSync)(f)||(0,d.mkdirSync)(f,{recursive:!0,mode:448});let g=`${c}.${process.pid}.${Date.now()}.tmp`;try{(0,d.writeFileSync)(g,JSON.stringify(a,null,2),{flag:"wx",mode:384}),(0,d.renameSync)(g,c)}catch(a){try{(0,d.unlinkSync)(g)}catch{}throw a}}function m(a,b){let c=b.split("."),d=a;for(let a of c){if("object"!=typeof d||null===d)return;d=d[a]}return d}function n(a,b){return m(a,b)}function o(a,b,c=(0,f.$M)()){k(c,()=>{let d=j(c);!function(a,b,c){let d=b.split("."),e=a;for(let a=0;a<d.length-1;a++){let b=d[a],c=e[b];("object"!=typeof c||null===c||Array.isArray(c))&&(e[b]={}),e=e[b]}let f=d[d.length-1];null==c?delete e[f]:e[f]=c}(d,a,b),l(d,c)})}function p(a){let b={},c=[];for(let[d,e]of Object.entries(a)){if("sessionQueue"===d||d.startsWith("sessionQueue.")){c.push(d);continue}b[d]=e}return{patch:b,dropped:c}}function q(a,b=(0,f.$M)()){return k(b,()=>{let c=j(b),d=function(a,b){let c={...a};for(let[a,d]of Object.entries(b))if(null===d)delete c[a];else if(i(d)&&i(c[a])){let b={...c[a]};for(let[a,c]of Object.entries(d))null===c?delete b[a]:b[a]=c;c[a]=b}else c[a]=d;return c}(c,a),e=function(a,b,c){let d={};for(let[e,f]of Object.entries(b)){let b=a[e],g=c[e];if(i(f)&&i(b)){for(let a of Object.keys(f)){let c=`${e}.${a}`,f=b[a],h=i(g)?g[a]:void 0;JSON.stringify(f)!==JSON.stringify(h)&&(d[c]=h??null)}continue}JSON.stringify(b)!==JSON.stringify(g)&&(d[e]=g??null)}return d}(c,a,d);return Object.keys(e).length>0&&l(d,b),e})}function r(a,b=(0,f.$M)()){return k(b,()=>{let c=j(b),d=(0,g.W)(c,a);if(0===d.length)return{};l(c,b);let e={};for(let a of d)e[a]=m(c,a)??null;return e})}},68816:(a,b,c)=>{c.d(b,{s:()=>q});var d=c(89477),e=c(25680),f=c(86697),g=c(60396);let h={maxHits:40,maxFiles:120,maxBytesPerFile:2097152,maxTotalBytes:0x2000000,snippetRadius:48},i=/\b(OR|AND|NOT|NEAR)\b/,j=/"([^"]*)"|(\S+)/g,k=new Set(["and","or","not","near"]);function l(a,b,c=h.snippetRadius){let d=a.replace(/\s+/g," ").trim();if(!d)return"";let e=b.trim();if(!e)return d.slice(0,2*c);let f=d.toLowerCase().indexOf(e.toLowerCase());if(f<0)return d.length>2*c?`${d.slice(0,2*c)}…`:d;let g=Math.max(0,f-c),i=Math.min(d.length,f+e.length+c),j=g>0?"…":"",k=i<d.length?"…":"";return`${j}${d.slice(g,i)}${k}`}function m(a,b){if(!b(a))return!1;try{return(0,d.statSync)(a).isFile()&&(0,d.statSync)(a).size>0}catch{return!1}}function n(a){let b=function(){try{let a=c(79868);if("function"==typeof a?.DatabaseSync)return a.DatabaseSync}catch{}try{let{createRequire:a}=c(55822),b=a(__filename)("node:sqlite");if("function"==typeof b?.DatabaseSync)return b.DatabaseSync}catch{}return null}();if(!b)return null;let d=a.replace(/\\/g,"/"),e=`file:${d}?mode=ro&immutable=1`;try{return new b(e,{readOnly:!0})}catch{}try{return new b(a,{readOnly:!0})}catch{return null}}async function o(a,b,c=h){let f,g=b.trim().toLowerCase();if(!g)return[];let i=0;try{i=(0,d.statSync)(a).size}catch{return[]}if(i<=0||i>c.maxBytesPerFile)return[];let j=[],k=(f=(a.replace(/\\/g,"/").split("/").pop()??"").match(/_([0-9a-fA-F-]{8,})\.jsonl$/),f?.[1]??null),m=0,n=(0,d.createReadStream)(a,{encoding:"utf8"}),p=(0,e.createInterface)({input:n,crlfDelay:1/0});try{for await(let a of p){if((m+=Buffer.byteLength(a,"utf8")+1)>c.maxBytesPerFile)break;let d=function(a){let b,c=a.trim();if(!c||"{"!==c[0])return null;try{b=JSON.parse(c)}catch{return null}if(!b||"object"!=typeof b)return null;let d=b;if("session"===d.type&&"string"==typeof d.id)return{sessionId:d.id,text:""};if("message"!==d.type)return null;let e=d.message;if(!e||"object"!=typeof e)return null;let f="string"==typeof e.role?e.role:void 0;if("user"!==f&&"assistant"!==f&&"system"!==f)return null;let g=function(a){if("string"==typeof a)return a;if(!Array.isArray(a))return"";let b=[];for(let c of a){if("string"==typeof c){b.push(c);continue}c&&"object"==typeof c&&("string"==typeof c.text?b.push(c.text):"string"==typeof c.content?b.push(c.content):"string"==typeof c.thinking&&b.push(c.thinking))}return b.join("\n").trim()}(e.content);return g?{messageId:"string"==typeof d.id?d.id:void 0,role:f,timestamp:"string"==typeof d.timestamp?d.timestamp:"string"==typeof e.timestamp?e.timestamp:void 0,text:g}:null}(a);if(d){if(d.sessionId){k=d.sessionId;continue}k&&d.text.toLowerCase().includes(g)&&j.push({sessionId:k,role:d.role,snippet:l(d.text,b,c.snippetRadius),timestamp:d.timestamp??"",messageId:d.messageId})}}}catch{}finally{p.close(),n.destroy()}return j}function p(a){let b=new Set,c=[];for(let d of a)b.has(d.sessionId)||(b.add(d.sessionId),c.push(d.sessionId));return c}async function q(a,b={}){let c=a.trim(),e={...h,...b.limits},r={...{getAgentDir:g.$M,resolveHermesDbPath:a=>(function(a,b=d.existsSync){let c=(0,f.join)(a,"hermes-memory-config.json");if(b(c))try{let h=JSON.parse((0,d.readFileSync)(c,"utf8"));if("string"==typeof h.memoryDir&&h.memoryDir.trim()){var e,g;let c=(e=h.memoryDir.trim(),g=a,"~"===e?process.env.HOME??g:e.startsWith("~/")||e.startsWith("~\\")?(0,f.join)(process.env.HOME??g,e.slice(2)):e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)?e:(0,f.join)(g,e)),d=(0,f.join)(c,"sessions.db");if(b(d)&&m(d,b))return d}}catch{}for(let c of[(0,f.join)(a,"pi-hermes-memory","sessions.db"),(0,f.join)(a,"memory","sessions.db")])if(b(c)&&m(c,b))return c;return null})(a),openSqliteReadonly:n,listJsonlFiles:a=>(function(a,b){if(!(0,d.existsSync)(a))return[];let c=[],e=a=>{let g;if(!(c.length>=b)){try{g=(0,d.readdirSync)(a,{withFileTypes:!0})}catch{return}for(let d of(g.sort((a,b)=>b.name.localeCompare(a.name)),g)){if(c.length>=b)return;let g=(0,f.join)(a,d.name);if(d.isDirectory()){e(g);continue}d.isFile()&&d.name.endsWith(".jsonl")&&c.push(g)}}};return e(a),c})(a,h.maxFiles),scanJsonlFile:o,existsSync:d.existsSync},...b.deps};if(!c)return{query:"",source:"none",hits:[],sessionIds:[]};let s=r.getAgentDir(),t=r.resolveHermesDbPath(s);if(t){let a=r.openSqliteReadonly(t);if(a)try{let b=function(a,b,c){let d=d=>{let e=`
14
14
  SELECT
15
15
  m.session_id AS session_id,
16
16
  m.role AS role,
@@ -35,7 +35,7 @@
35
35
  WHERE m.content LIKE ? ESCAPE '\\'
36
36
  ORDER BY m.timestamp DESC
37
37
  LIMIT ?
38
- `,e=`%${b.trim().replace(/[\\%_]/g,"\\$&")}%`;return a.prepare(d).all(e,c).filter(a=>"string"==typeof a.session_id&&a.session_id).map(a=>({sessionId:a.session_id,role:"string"==typeof a.role?a.role:void 0,snippet:l(String(a.content??""),b),timestamp:"string"==typeof a.timestamp?a.timestamp:"",messageId:"string"==typeof a.message_id?a.message_id:void 0}))}catch{return[]}}(a,c,e.maxHits);return{query:c,source:"fts",hits:b,sessionIds:p(b)}}catch{}finally{try{a.close()}catch{}}}let u=(0,f.join)(s,"sessions");if(!r.existsSync(u))return{query:c,source:"jsonl",hits:[],sessionIds:[]};let v=r.listJsonlFiles(u).slice(0,e.maxFiles),w=[],x=0;for(let a of v){if(w.length>=e.maxHits)break;let b=0;try{b=(0,d.statSync)(a).size}catch{continue}if(!(b<=0)){if(x+b>e.maxTotalBytes)break;for(let d of(x+=b,await r.scanJsonlFile(a,c,e)))if(w.push(d),w.length>=e.maxHits)break}}return w.sort((a,b)=>(b.timestamp||"").localeCompare(a.timestamp||"")),{query:c,source:"jsonl",hits:w.slice(0,e.maxHits),sessionIds:p(w)}}},69835:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$t:()=>w,Gt:()=>z,Lj:()=>y,Md:()=>x,eq:()=>n,fb:()=>u,fm:()=>v,ki:()=>r,qo:()=>m,uF:()=>o,vy:()=>t,xd:()=>q});var e=c(29021),f=c(33873),g=c(55511),h=c(27910),i=c(77725),j=c(60396),k=c(80547),l=a([k]);k=(l.then?(await l)():l)[0];let x=0x1900000,y=0x6400000,z=0x20000000;function m(a=(0,j.$M)()){return(0,k.Nw)((0,f.join)(a,"pidance-attachments"))}function n(a=(0,j.$M)()){let b=m(a);return(0,e.existsSync)(b)||(0,e.mkdirSync)(b,{recursive:!0,mode:448}),(0,k.wz)(b),b}function o(a){let b=(a.replace(/\\/g,"/").split("/").pop()??"file").replace(/\0/g,"").replace(/^\.+/,"").trim()||"file";if(b.length<=180)return b;let c=b.lastIndexOf(".");if(c>0&&b.length-c<=20){let a=b.slice(c);return b.slice(0,180-a.length)+a}return b.slice(0,180)}function p(a,b=Date.now()){let c=o(a),d=new Date(b).toISOString().replace(/[:.]/g,"-"),e=(0,g.randomUUID)().slice(0,8);return`${d}_${e}_${c}`}async function q(a,b,c=(0,j.$M)(),d=z){let l=n(c),m=p(a),r=(0,f.join)(l,m),s=(0,f.join)(l,`.${m}.${(0,g.randomUUID)()}.tmp`),t=0,u=new h.Transform({transform(a,b,c){let e=Buffer.isBuffer(a)?a:Buffer.from(a);(t+=e.length)>d?c(Error(`message media exceeds ${d} bytes`)):c(null,e)}});try{await (0,i.pipeline)(h.Readable.fromWeb(b),u,(0,e.createWriteStream)(s,{flags:"wx",mode:384})),(0,e.renameSync)(s,r)}catch(a){try{(0,e.unlinkSync)(s)}catch{}throw a}return{path:(0,k.Nw)(r),name:o(a),storedName:m,size:t}}function r(a,b,c=(0,j.$M)()){let d=n(c),g=p(a),h=(0,f.join)(d,g);return(0,e.writeFileSync)(h,b,{flag:"wx",mode:384}),{path:(0,k.Nw)(h),name:o(a),storedName:g,size:b.length}}function s(a,b,c){let d=a.trim();if(!d)return null;try{let a=(0,k.Nw)((0,e.realpathSync)(n(b))),f=(0,k.Nw)((0,e.realpathSync)(d));if(f!==a&&!f.startsWith(`${a}/`)||!(0,e.statSync)(f).isFile())return null;return c(f)}catch{return null}}function t(a,b=(0,j.$M)()){return s(a,b,a=>(0,e.statSync)(a).size)}function u(a,b=(0,j.$M)(),c=0x1900000){return s(a,b,a=>(0,e.statSync)(a).size>c?null:(0,e.readFileSync)(a).toString("base64"))}function v(a,b=(0,j.$M)()){return s(a,b,a=>{try{return(0,e.unlinkSync)(a),!0}catch{return!1}})??!1}function w(a=(0,j.$M)()){let b=[];return function a(b,c){for(let d of(()=>{try{return(0,e.readdirSync)(b,{withFileTypes:!0})}catch{return[]}})()){let g=(0,f.join)(b,d.name);if(d.isDirectory()){a(g,c);continue}if(d.isFile())try{let a=(0,e.statSync)(g);c.push({path:(0,k.Nw)(g),size:a.size,mtimeMs:a.mtimeMs})}catch{}}}(m(a),b),b}d()}catch(a){d(a)}})},76817:(a,b,c)=>{c.d(b,{wo:()=>d});function d(a,b){let c=a.findIndex(a=>a.id===b);if(-1===c)return b;let d=b;for(let b=c+1;b<a.length;b+=1){let c=a[b];if("message"===c.type&&c.message?.role==="user")break;d=c.id}return d}},79495:(a,b,c)=>{c.d(b,{CL:()=>n,K:()=>k});var d=c(89477),e=c(60396),f=c(92395);let g=`Create a concise title for this session based on the conversation above.
38
+ `,e=`%${b.trim().replace(/[\\%_]/g,"\\$&")}%`;return a.prepare(d).all(e,c).filter(a=>"string"==typeof a.session_id&&a.session_id).map(a=>({sessionId:a.session_id,role:"string"==typeof a.role?a.role:void 0,snippet:l(String(a.content??""),b),timestamp:"string"==typeof a.timestamp?a.timestamp:"",messageId:"string"==typeof a.message_id?a.message_id:void 0}))}catch{return[]}}(a,c,e.maxHits);return{query:c,source:"fts",hits:b,sessionIds:p(b)}}catch{}finally{try{a.close()}catch{}}}let u=(0,f.join)(s,"sessions");if(!r.existsSync(u))return{query:c,source:"jsonl",hits:[],sessionIds:[]};let v=r.listJsonlFiles(u).slice(0,e.maxFiles),w=[],x=0;for(let a of v){if(w.length>=e.maxHits)break;let b=0;try{b=(0,d.statSync)(a).size}catch{continue}if(!(b<=0)){if(x+b>e.maxTotalBytes)break;for(let d of(x+=b,await r.scanJsonlFile(a,c,e)))if(w.push(d),w.length>=e.maxHits)break}}return w.sort((a,b)=>(b.timestamp||"").localeCompare(a.timestamp||"")),{query:c,source:"jsonl",hits:w.slice(0,e.maxHits),sessionIds:p(w)}}},69835:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{$t:()=>w,Gt:()=>z,Lj:()=>y,Md:()=>x,eq:()=>n,fb:()=>u,fm:()=>v,ki:()=>r,qo:()=>m,uF:()=>o,vy:()=>t,xd:()=>q});var e=c(29021),f=c(33873),g=c(55511),h=c(27910),i=c(77725),j=c(60396),k=c(80547),l=a([k]);k=(l.then?(await l)():l)[0];let x=0x1900000,y=0x6400000,z=0x20000000;function m(a=(0,j.$M)()){return(0,k.Nw)((0,f.join)(a,"pidance-attachments"))}function n(a=(0,j.$M)()){let b=m(a);return(0,e.existsSync)(b)||(0,e.mkdirSync)(b,{recursive:!0,mode:448}),(0,k.wz)(b),b}function o(a){let b=(a.replace(/\\/g,"/").split("/").pop()??"file").replace(/\0/g,"").replace(/^\.+/,"").trim()||"file";if(b.length<=180)return b;let c=b.lastIndexOf(".");if(c>0&&b.length-c<=20){let a=b.slice(c);return b.slice(0,180-a.length)+a}return b.slice(0,180)}function p(a,b=Date.now()){let c=o(a),d=new Date(b).toISOString().replace(/[:.]/g,"-"),e=(0,g.randomUUID)().slice(0,8);return`${d}_${e}_${c}`}async function q(a,b,c=(0,j.$M)(),d=z){let l=n(c),m=p(a),r=(0,f.join)(l,m),s=(0,f.join)(l,`.${m}.${(0,g.randomUUID)()}.tmp`),t=0,u=new h.Transform({transform(a,b,c){let e=Buffer.isBuffer(a)?a:Buffer.from(a);(t+=e.length)>d?c(Error(`message media exceeds ${d} bytes`)):c(null,e)}});try{await (0,i.pipeline)(h.Readable.fromWeb(b),u,(0,e.createWriteStream)(s,{flags:"wx",mode:384})),(0,e.renameSync)(s,r)}catch(a){try{(0,e.unlinkSync)(s)}catch{}throw a}return{path:(0,k.Nw)(r),name:o(a),storedName:m,size:t}}function r(a,b,c=(0,j.$M)()){let d=n(c),g=p(a),h=(0,f.join)(d,g);return(0,e.writeFileSync)(h,b,{flag:"wx",mode:384}),{path:(0,k.Nw)(h),name:o(a),storedName:g,size:b.length}}function s(a,b,c){let d=a.trim();if(!d)return null;try{let a=(0,k.Nw)((0,e.realpathSync)(n(b))),f=(0,k.Nw)((0,e.realpathSync)(d));if(f!==a&&!f.startsWith(`${a}/`)||!(0,e.statSync)(f).isFile())return null;return c(f)}catch{return null}}function t(a,b=(0,j.$M)()){return s(a,b,a=>(0,e.statSync)(a).size)}function u(a,b=(0,j.$M)(),c=0x1900000){return s(a,b,a=>(0,e.statSync)(a).size>c?null:(0,e.readFileSync)(a).toString("base64"))}function v(a,b=(0,j.$M)()){return s(a,b,a=>{try{return(0,e.unlinkSync)(a),!0}catch{return!1}})??!1}function w(a=(0,j.$M)()){let b=[];return function a(b,c){for(let d of(()=>{try{return(0,e.readdirSync)(b,{withFileTypes:!0})}catch{return[]}})()){let g=(0,f.join)(b,d.name);if(d.isDirectory()){a(g,c);continue}if(d.isFile())try{let a=(0,e.statSync)(g);c.push({path:(0,k.Nw)(g),size:a.size,mtimeMs:a.mtimeMs})}catch{}}}(m(a),b),b}d()}catch(a){d(a)}})},75052:(a,b,c)=>{function d(a){return"object"==typeof a&&null!==a&&!Array.isArray(a)}function e(a,b){let c=b.split("."),e=a;for(let a=0;a<c.length-1;a+=1){let b=c[a],f=e[b];if(!d(f)){let a={};e[b]=a,e=a;continue}e=f}let f=c[c.length-1];return{container:e,last:f,existed:Object.prototype.hasOwnProperty.call(e,f)}}function f(a){return!(!a||"string"!=typeof a.key||0===a.key.length||"sessionQueue"===a.key||a.key.startsWith("sessionQueue."))&&("add"===a.op||"remove"===a.op?"sidebarUi.projectRoots"===a.key||"sidebarUi.pinnedSessionIds"===a.key||"sidebarUi.ungroupedSessionIds"===a.key||"sidebarUi.collapsedProjectRoots"===a.key:"set"===a.op)}function g(a,b){let c=[],g=a=>{c.includes(a)||c.push(a)};for(let c of b){if(!f(c))continue;if("set"===c.op){let{container:b,last:d,existed:f}=e(a,c.key);if(null===c.value||void 0===c.value){if(!f)continue;delete b[d],g(c.key);continue}if(JSON.stringify(b[d])===JSON.stringify(c.value))continue;b[d]=c.value,g(c.key);continue}let b=function(a,b){let c=a;for(let a of b.split(".")){if(!d(c))return;c=c[a]}return c}(a,c.key),h=Array.isArray(b)?b.filter(a=>!0):[],i=c.value;if("string"!=typeof i||0===i.length)continue;if("add"===c.op){if(h.includes(i))continue;h.push(i)}else{if(!h.includes(i))continue;let a=h.filter(a=>a!==i);h.length=0,h.push(...a)}let{container:j,last:k}=e(a,c.key);j[k]=h,g(c.key)}return c}c.d(b,{F:()=>f,W:()=>g})},76817:(a,b,c)=>{c.d(b,{wo:()=>d});function d(a,b){let c=a.findIndex(a=>a.id===b);if(-1===c)return b;let d=b;for(let b=c+1;b<a.length;b+=1){let c=a[b];if("message"===c.type&&c.message?.role==="user")break;d=c.id}return d}},79495:(a,b,c)=>{c.d(b,{CL:()=>n,K:()=>k});var d=c(89477),e=c(60396),f=c(92395);let g=`Create a concise title for this session based on the conversation above.
39
39
 
40
40
  Requirements:
41
41
  - Match the primary language used by the user.