@henlii/pidance 0.2.39 → 0.2.41

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 (85) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +9 -9
  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/_tree.segment.rsc +1 -1
  12. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  13. package/.next/server/app/_not-found.html +1 -1
  14. package/.next/server/app/_not-found.rsc +3 -3
  15. package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  16. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +3 -3
  17. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  18. package/.next/server/app/api/about/route.js +1 -1
  19. package/.next/server/app/api/agent/[id]/events/route.js +1 -1
  20. package/.next/server/app/api/agent/[id]/route.js +1 -1
  21. package/.next/server/app/api/agent/new/route.js +1 -1
  22. package/.next/server/app/api/agent/running/events/route.js +1 -1
  23. package/.next/server/app/api/agent/running/route.js +1 -1
  24. package/.next/server/app/api/agent/submissions/[submissionId]/route.js +1 -1
  25. package/.next/server/app/api/file-index/route.js +1 -1
  26. package/.next/server/app/api/files/[...path]/route.js +1 -1
  27. package/.next/server/app/api/plugins/route.js +1 -1
  28. package/.next/server/app/api/plugins/updates/route.js +2 -1
  29. package/.next/server/app/api/preferences/route.js +1 -1
  30. package/.next/server/app/api/pty/route.js +4 -3
  31. package/.next/server/app/api/sessions/[id]/archive/route.js +1 -1
  32. package/.next/server/app/api/sessions/[id]/auto-name/route.js +1 -1
  33. package/.next/server/app/api/sessions/[id]/command-entry/route.js +1 -1
  34. package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
  35. package/.next/server/app/api/sessions/[id]/entries/[entryId]/thinking/route.js +1 -1
  36. package/.next/server/app/api/sessions/[id]/export/route.js +1 -1
  37. package/.next/server/app/api/sessions/[id]/info/route.js +1 -1
  38. package/.next/server/app/api/sessions/[id]/lock/route.js +1 -1
  39. package/.next/server/app/api/sessions/[id]/outline/route.js +1 -1
  40. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  41. package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
  42. package/.next/server/app/api/sessions/[id]/tool-results/[toolCallId]/route.js +1 -1
  43. package/.next/server/app/api/sessions/route.js +1 -1
  44. package/.next/server/app/api/sessions/search/route.js +1 -1
  45. package/.next/server/app/api/subagent-runs/route.js +1 -1
  46. package/.next/server/app/index.html +1 -1
  47. package/.next/server/app/index.rsc +5 -5
  48. package/.next/server/app/index.segments/__PAGE__.segment.rsc +5 -5
  49. package/.next/server/app/index.segments/_full.segment.rsc +5 -5
  50. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  51. package/.next/server/app/page.js +13 -13
  52. package/.next/server/app/page_client-reference-manifest.js +1 -1
  53. package/.next/server/app-paths-manifest.json +9 -9
  54. package/.next/server/chunks/3557.js +1 -1
  55. package/.next/server/chunks/3908.js +1 -0
  56. package/.next/server/chunks/4127.js +1 -1
  57. package/.next/server/chunks/4511.js +1 -0
  58. package/.next/server/chunks/5274.js +1 -1
  59. package/.next/server/chunks/5277.js +1 -1
  60. package/.next/server/chunks/5304.js +2 -2
  61. package/.next/server/chunks/5420.js +1 -1
  62. package/.next/server/chunks/7594.js +5 -6
  63. package/.next/server/chunks/8443.js +1 -1
  64. package/.next/server/chunks/9032.js +1 -0
  65. package/.next/server/chunks/9460.js +2 -0
  66. package/.next/server/instrumentation.js +1 -1
  67. package/.next/server/middleware-build-manifest.js +1 -1
  68. package/.next/server/pages/404.html +1 -1
  69. package/.next/server/pages/500.html +1 -1
  70. package/.next/server/server-reference-manifest.json +1 -1
  71. package/.next/static/chunks/9780-3879ff424362f71a.js +1 -0
  72. package/.next/static/chunks/app/page-24032ecb0162638f.js +24 -0
  73. package/.next/static/css/{ea117138d33e0b37.css → 1ad5c09cc7ca816b.css} +1 -1
  74. package/README.en.md +1 -1
  75. package/README.md +1 -1
  76. package/bin/pty-manager.cjs +65 -12
  77. package/bin/pty-process.cjs +135 -0
  78. package/bin/pty-worker.js +17 -3
  79. package/package.json +1 -1
  80. package/.next/server/chunks/8359.js +0 -2
  81. package/.next/server/chunks/9935.js +0 -1
  82. package/.next/static/chunks/9780-864f35ace9287b0b.js +0 -1
  83. package/.next/static/chunks/app/page-5f78e55ff0d87ec7.js +0 -24
  84. /package/.next/static/{vD56I5OFkAr4Y9TsF1L7c → OLUuuQTRgyV-qLJoY9ONN}/_buildManifest.js +0 -0
  85. /package/.next/static/{vD56I5OFkAr4Y9TsF1L7c → OLUuuQTRgyV-qLJoY9ONN}/_ssgManifest.js +0 -0
@@ -1,2 +1,2 @@
1
- "use strict";exports.id=5304,exports.ids=[5304],exports.modules={10611:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>I});var e=c(716),f=c(75430),g=c(92783),h=c(66323),i=c(12559),j=c(69714),k=c(84127),l=c(82356),m=c(68642),n=c(93686),o=c(40673),p=c(99595),q=c(89358),r=c(16601),s=c(31360),t=c(74108),u=c(63480),v=c(33727),w=c(31119),x=c(11955),y=c(35948),z=c(58732),A=c(19228),B=c(57856),C=c(37607),D=c(36315),E=c(88876),F=a([f,n,s,t,z,A]);function G(a){return"string"==typeof a&&""!==a?a:null}function H(a){return"string"==typeof a&&a?a:void 0}[f,n,s,t,z,A]=F.then?(await F)():F;class J{static{this.PARTIAL_RENDER_MIN_INTERVAL_MS=100}static{this.RERENDER_MIN_INTERVAL_MS=100}static{this.RENDER_WIDTH_MIN=40}static{this.RENDER_WIDTH_MAX=240}static{this.RENDER_ROWS_MIN=10}static{this.RENDER_ROWS_MAX=200}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,D.Lm)(),this.renderWidth=D.Yg,this.renderRows=B.Tf,this.toolRenderStates=new Map,this.toolRenderScheduler=(0,E.w7)({minIntervalMs:J.RERENDER_MIN_INTERVAL_MS,recompute:a=>this.recomputeToolSlots(a),emit:(a,b)=>this.emitRenderedLinesUpdate(a,b)}),this.streamSnapshot=(0,j.b)(),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,g.$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()}}connectionSnapshot(){let a=this.streamSnapshot.snapshot();return this.streamRunSeq>0?{...a,streamRunSeq:this.streamRunSeq}:a}beginExtensionBinding(){}async waitForExtensionsBound(){}emit(a){for(let b of(this.streamSnapshot.remember(a),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,h._2)({limit:50});return(0,h.EE)(b,a)}catch{return!1}}hasActiveExternalWork(){return!!this.hasActiveSubagentRun()||(0,i.Vz)({sessionId:this.realSessionId,sessionFile:this.realSessionFile})}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.hasActiveExternalWork())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,k.readPidancePrefs)(this.agentDir);return!0===(0,k.ql)(a,`sessionQueueHold.${this.realSessionId}`)}setFollowUpHeld(a){try{(0,k.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,k.readPidancePrefs)(this.agentDir),b=(0,k.ql)(a,`sessionQueue.${this.realSessionId}`),c=(0,o.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)>o.ym)return console.error(`[pidance] refusing to persist follow-up queue (${b}): item media exceeds ${o.ym}`),!1;let d=this.followUpQueueRevision+1,e=(0,o.S1)(this.followUpAdmittedAttemptIds,c);try{(0,k.xP)(`sessionQueue.${this.realSessionId}`,(0,o.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,o.Ot)(this.followUpQueue).map(a=>a.path));for(let c of a)"model"!==c.role||b.has(c.path)||(0,n.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:n.Md,c=(0,n.vy)(a.path,this.agentDir);return null!==c&&c<=b}validateQueueMedia(a){if(!a?.length)return!0;if(a.length>o.ym)return!1;let b=0;for(let c of a){let a=(0,n.vy)(c.path,this.agentDir);if(null===a)return!1;let d="model"===c.role?8388608:n.Md;if(a>d||(b+=a,c.previewPath&&null===(0,n.vy)(c.previewPath,this.agentDir)))return!1}return b<=n.Lj}readQueueModelImages(a){let b=[],c=[];for(let d of(0,o.Ot)(a)){if("model"!==d.role)continue;let a=(0,n.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,o.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,o.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,n.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,n.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,n.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,o.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,o.ko)(a.text,"claimed",a.media):(0,o.ko)(a.text,"claimed"));c&&g.push((0,o.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,l="prompt";try{if(this.session.isStreaming)l="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 l="queued",this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-queued"),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:l,...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,x.K2)(b),...this.queueReceiptBase()}}finally{this.dispatchingFollowUpQueue=!1}let m=(0,o.Ot)(g);return this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-deliver")&&this.discardDeliveredModelMedia(m),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:l,...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,k.readPidancePrefs)(this.agentDir).queueFlushAsOne;this.flushingFollowUp=!0,this.followUpFlushUnits=b?[{ids:a.map(a=>a.id)}]:a.map(a=>({ids:[a.id]})),this.followUpFlushCursor=0;let c=this.followUpFlushUnits[0];setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushUnits[this.followUpFlushCursor]===c&&this.sendNextFollowUp()},0)}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,o.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),l=(0,o.Ot)(c),m=this.commitFollowUpQueue(this.followUpQueue.filter(a=>!k.has(a.id)),"deliver");m&&this.discardDeliveredModelMedia(l),this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:e,...this.queueReceiptBase()}),m||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,t.tZ)(a=>{this.trackExtensionSideEffects(a),this.emit(a)},{readComposerText:()=>(0,C.x)(this.realSessionId,this.agentDir)}),(0,D.DD)(a=>{this._alive&&this.emit({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"notify",message:a,notifyType:"warning"})}),(0,D.YJ)(()=>{(0,f.renderDiff)("+ added\n- removed\n context\n")}),(0,D.Sw)(),await a.bindExtensions({uiContext:this.extensionUi.uiContext,mode:"tui",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=H(a.method);if("setStatus"===b){let b=H(a.statusKey)??H(a.key)??"default",c=H(a.statusText)??H(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=H(a.widgetKey)??H(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,s.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(y.uG,a);this.emit({type:"message_end",entryId:e,message:(0,y.FH)(a,Date.now())})}(0,s.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&&J.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=J.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,m.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,m.PI)(this.realSessionId),this.options.onSessionListInvalidate?.(),this.realSessionFile&&(0,q.$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.hasActiveExternalWork();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,s.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})}e=this.withToolDisplayMeta(e),this.emit(this.withRenderedToolLines(e))}withToolDisplayMeta(a){if("tool_execution_start"!==a.type)return a;try{let b=this.session.extensionRunner;if("function"!=typeof b?.getToolDefinition)return a;let c="string"==typeof a.toolName?a.toolName:"";if(""===c)return a;let d=b.getToolDefinition(c);if(!d)return a;let e="string"==typeof d.label?d.label.trim():"",f=""!==e&&e!==c?e:void 0,g="self"===d.renderShell?"self":void 0;if(void 0===f&&void 0===g)return a;return{...a,...void 0!==f?{toolLabel:f}:{},...void 0!==g?{toolShell:g}:{}}}catch{return a}}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_start":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=G(a.toolCallId),d=c?this.getOrCreateToolRenderState(c):null;d&&(d.args=a.args,d.callRenderer={slot:"call",def:b});let e=this.buildToolRenderContext(a.toolCallId,a.args,{isPartial:!1,expanded:!0,isError:!1,resultSlot:!1});if(!e)return a;let f=(0,D.GD)(b,a.args,e,b=>this.updateToolRenderLastComponent(a.toolCallId,!1,b),this.renderWidth),g=d?.emittedCallLines??f;return d&&g&&(d.emittedCallLines=g),g?{...a,renderedCallLines:g}:a}case"tool_execution_update":{if(!this.shouldRenderPartialUpdate(a.toolCallId))return a;let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=G(a.toolCallId);if(!c)return a;let d=this.getOrCreateToolRenderState(c);if(!d)return a;void 0!==a.args&&(d.args=a.args),d.resultRenderer={slot:"result",def:b,result:a.partialResult,isPartial:!0,isError:!0===a.isError};let e=this.renderToolSlotsNow(c,d);if(!e||(e.callLines&&this.emitRenderedLinesUpdate(c,{callLines:e.callLines}),!e.resultLines))return a;return this.recordEmittedToolLines(c,{resultLines:e.resultLines}),{...a,renderedLines:e.resultLines}}case"tool_execution_end":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=G(a.toolCallId);if(!c)return a;let d=this.getOrCreateToolRenderState(c);if(!d)return a;let e={..."object"==typeof a.result&&null!==a.result?a.result:{content:[]},isError:!0===a.isError};d.resultRenderer={slot:"result",def:b,result:e,isPartial:!1,isError:!0===a.isError};let f=this.renderToolSlotsNow(c,d);if(!f||(f.callLines&&this.emitRenderedLinesUpdate(c,{callLines:f.callLines}),!f.resultLines))return a;return this.recordEmittedToolLines(c,{resultLines:f.resultLines}),{...a,renderedResultLines:f.resultLines}}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,D.Mf)(d,a.message,this.renderBridgeTheme,this.renderWidth);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:()=>{this.scheduleToolRerender(a)},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,args:void 0,callRenderer:void 0,resultRenderer:void 0,emittedCallLines:void 0,emittedResultLines: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)}rerenderToolLines(){this.toolRenderScheduler.flushAll([...this.toolRenderStates.keys()])}scheduleToolRerender(a){let b=G(a);b&&this.toolRenderStates.has(b)&&this.toolRenderScheduler.request(b)}recomputeToolSlots(a){let b=this.toolRenderStates.get(a);return b?this.renderToolSlotsNow(a,b):null}renderToolSlotsNow(a,b){let c=null,d=null,e=b.resultRenderer&&"result"===b.resultRenderer.slot?b.resultRenderer:void 0;if(b.callRenderer){let d=this.buildToolRenderContext(a,b.args,{isPartial:e?.isPartial===!0,expanded:!0,isError:e?.isError===!0,resultSlot:!1});d&&(c=(0,D.GD)(b.callRenderer.def,b.args,d,b=>this.updateToolRenderLastComponent(a,!1,b),this.renderWidth))}let f=b.resultRenderer;if(f&&"result"===f.slot){let e=this.buildToolRenderContext(a,b.args,{isPartial:f.isPartial,expanded:!0,isError:f.isError,resultSlot:!0});if(e&&(d=(0,D.t_)(f.def,f.result,{expanded:!0,isPartial:f.isPartial},e,b=>this.updateToolRenderLastComponent(a,!0,b),this.renderWidth)),b.lastCallComponent){let a=(0,D.hR)(b.lastCallComponent,this.renderWidth);a&&(c=a)}}return(0,E.VQ)({callLines:c,resultLines:d},{callLines:b.emittedCallLines,resultLines:b.emittedResultLines})}recordEmittedToolLines(a,b){let c=this.toolRenderStates.get(a);c&&(b.callLines&&(c.emittedCallLines=b.callLines),b.resultLines&&(c.emittedResultLines=b.resultLines))}emitRenderedLinesUpdate(a,b){this.emit({type:"rendered_lines_update",toolCallId:a,...b.callLines?{renderedCallLines:b.callLines}:{},...b.resultLines?{renderedResultLines:b.resultLines}:{}}),this.recordEmittedToolLines(a,b)}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<J.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,s.G1)(a):(0,s.Qu)(b)),d=c.getCwd()||this.options.cwd,e=this.agentDir,g=this.activeToolNames,h=async({cwd:a,agentDir:b,sessionManager:c,sessionStartEvent:d})=>{let e=(0,A._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),h={name:A.Jv,label:A.wc,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:A.Tv,async execute(a,b,c){let d=await e(b,c);return{content:[{type:"text",text:`Delivered ${d.name} to the user (entry ${d.entryId}).`}],details:d}}},i=await (0,f.createAgentSessionServices)({cwd:a,agentDir:b,resourceLoaderOptions:{appendSystemPromptOverride:A.n3,extensionFactories:[a=>a.registerTool(h)]}});for(let a of i.modelRuntime.getModels())(0,w.yu)(a);return{...await (0,f.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,f.createAgentSessionRuntime)(h,{cwd:d,agentDir:e,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()??[]),extensionTerminalInputListenerCount:this.extensionUi?.terminalInputListenerCount??0,activeCustomUi:this.extensionUi?.customSnapshot??null,extensionCapabilityNotices:this.extensionUi?.capabilityNoticeSnapshot??[]};c.queuedMessages={steering:this.hasQueueSnapshot?[...this.localQueue.steering]:[],followUp:(0,o.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,p.qF)(a):(0,p.l$)(a),c=this.session.sessionManager.appendCustomEntry(p.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,z.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(y.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,y.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,x.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,z.Nu)(c.binaryBlocks,this.agentDir),i=c.images??a.images,j=this.resolvePromptImages(i);if(j.missing.length){console.error("[pidance] prompt image missing on disk:",j.missing);let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}if(this.bashRunning&&!(0,v.D)(c.message)){let a=this.reject(c.submissionId,"bash");return this.promptReceipts.set(c.submissionId,a),a}if(d.isCompacting&&!(0,v.D)(c.message)){let a=this.queueMediaFromPromptImages(i);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,v.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,v.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:j.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,l.kP)(this.realSessionId))throw Error(l.GT);this.promptRunning=!0,this.lastStopReason=null,(0,m.NK)(this.realSessionId,Date.now()),this.notifyRunning();let k=(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,m.PI)(this.realSessionId),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq}),this.resetIdleTimer())};d.prompt(c.message,{images:j.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,s.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,x.K2)(g);if(d.isStreaming&&(0,x.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,m.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,k),k}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,u.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,w.eU)(e)),this.options.onSessionListInvalidate?.(),e}case"set_thinking_level":return d.model&&(0,w.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,x._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,x.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,x.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,x.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,x.$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_command_argument_completions":{let b="string"==typeof a.name?a.name:"",c="string"==typeof a.prefix?a.prefix:"";if(!b)return{items:[]};let e=d.extensionRunner.getRegisteredCommands().find(a=>a.invocationName===b),f=e?.getArgumentCompletions;if("function"!=typeof f)return{items:[]};try{let a=await f.call(e,c);return{items:function(a){if(!Array.isArray(a))return[];let b=[];for(let c of a){if("object"!=typeof c||null===c||"string"!=typeof c.value||""===c.value)continue;let a="string"==typeof c.label&&""!==c.label?c.label:c.value;b.push({value:c.value,label:a,..."string"==typeof c.description&&""!==c.description?{description:c.description}:{}})}return b}(a)}}catch{return{items:[]}}}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,..."function"==typeof b.getArgumentCompletions?{hasArgumentCompletions:!0}:{}});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=H(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=H(a.id),c="string"==typeof a.data?a.data:"";return b&&this.extensionUi?.inputCustom(b,c),null}case"terminal_input":{let b="string"==typeof a.data?a.data:"";return!0===a.assertFocus&&this.extensionUi?.setEditorFocus(!0,H(a.clientId)??"default"),this.extensionUi?.dispatchTerminalInput(b)??{consumed:!1}}case"editor_focus":{let b=!0===a.focused,c=H(a.clientId)??"default";return{focused:b,changed:this.extensionUi?.setEditorFocus(b,c)??!1}}case"extension_ui_mouse":{let b=H(a.id),c=a.event;return b&&c&&"object"==typeof c&&this.extensionUi?.inputCustomMouse(b,c),null}case"set_render_width":{let b="number"==typeof a.width?a.width:NaN;if(!Number.isFinite(b))return null;let c=Math.min(J.RENDER_WIDTH_MAX,Math.max(J.RENDER_WIDTH_MIN,Math.round(b)));if(c===this.renderWidth)return null;return this.renderWidth=c,this.extensionUi?.setRenderSize({width:c,rows:this.renderRows}),this.rerenderToolLines(),null}case"set_render_size":{let b="number"==typeof a.width?a.width:NaN,c="number"==typeof a.rows?a.rows:NaN;if(!Number.isFinite(b)||!Number.isFinite(c))return null;let d=Math.min(J.RENDER_WIDTH_MAX,Math.max(J.RENDER_WIDTH_MIN,Math.round(b))),e=Math.min(J.RENDER_ROWS_MAX,Math.max(J.RENDER_ROWS_MIN,Math.round(c))),f=d!==this.renderWidth;if(!f&&e===this.renderRows)return null;return this.renderWidth=d,this.renderRows=e,this.extensionUi?.setRenderSize({width:d,rows:e}),f&&this.rerenderToolLines(),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=H(a.targetId);if(!b)throw Error("targetId is required");let c=await d.navigateTree(b,{summarize:a.summarize,customInstructions:H(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,q.R3)(this.realSessionFile,a):this.realSessionFile&&(0,q.$9)(this.realSessionFile)}return this.options.onSessionListInvalidate?.(),{cancelled:c.cancelled}}case"select_leaf_exact":{let b=H(a.entryId);if(!b)throw Error("entryId is required");return await this.navigateTreeCommand("select_leaf_exact",b)}case"branch_from_assistant":{let b=H(a.assistantEntryId);if(!b)throw Error("assistantEntryId is required");return await this.navigateTreeCommand("branch_from_assistant",b)}case"create_session_from_leaf":{let b=H(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c)return await c.createSessionFromLeaf(this.sessionId,b,{handoff:()=>this.destroyExcluding(1)});throw Error("create_session_from_leaf is unavailable")}case"set_branch_label":{let b=H(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()}}async navigateTreeCommand(a,b){let c=this.session;if(this.bashRunning)throw Error("select_leaf_exact"===a?"Cannot switch branch while a shell command is running":"Cannot branch while a shell command is running");if(c.isStreaming)throw Error("Wait for the current response to finish before navigating the session tree.");if(c.isCompacting)throw Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");let d=c.sessionManager,e=(0,s.LH)(d),f="select_leaf_exact"===a?(0,r.fb)(e,b):(0,r.AM)(e,b);if("noop"===f.kind)return{cancelled:!1};let g=d.getLeafId();if(f.leafId===g)return f.clearSidecar&&this.realSessionFile&&((0,q.$9)(this.realSessionFile),this.options.onSessionListInvalidate?.()),{cancelled:!1};let h=this.options.navigationActions;if((await this.dispatchTreeNavigation({oldLeafId:g,targetLeafId:f.leafId,apply:async()=>{if(h&&this.realSessionFile){let c="select_leaf_exact"===a?h.selectLeafExact:h.branchFromAssistant;return await c.call(h,this.sessionId,b,{handoff:()=>this.destroyExcluding(1),liveWriter:{sessionManager:e,sessionFile:this.realSessionFile}})}return(0,r.h_)({sessionManager:e,sessionFile:this.realSessionFile,plan:f}),this.options.onSessionListInvalidate?.(),{cancelled:!1}}})).cancelled)return{cancelled:!0};try{await this.destroyExcluding(1)}catch{}return{cancelled:!1}}async dispatchTreeNavigation(a){let b=this.session,c=b.extensionRunner,d=new AbortController;b._branchSummaryAbortController=d;try{if(c.hasHandlers("session_before_tree")){let e=(0,f.collectEntriesForBranchSummary)(b.sessionManager,a.oldLeafId,a.targetLeafId),g=await c.emit({type:"session_before_tree",preparation:{targetId:a.targetLeafId,oldLeafId:a.oldLeafId,commonAncestorId:e.commonAncestorId,entriesToSummarize:e.entries,userWantsSummary:!1},signal:d.signal});if(g?.cancel)return{cancelled:!0}}if((await a.apply()).cancelled)return{cancelled:!0};return await c.emit({type:"session_tree",newLeafId:b.sessionManager.getLeafId(),oldLeafId:a.oldLeafId}),{cancelled:!1}}finally{b._branchSummaryAbortController=void 0}}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("Session writer is busy: a command is still in flight");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.toolRenderScheduler.dispose(),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,m.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 I(a){let b=new J(a);return await b.start(),b}d()}catch(a){d(a)}})},11955:(a,b,c)=>{c.d(b,{$3:()=>o,JT:()=>k,K2:()=>g,QT:()=>p,TJ:()=>r,_3:()=>n,in:()=>f,s:()=>q});var d=c(35948),e=c(40673);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)}}},12559:(a,b,c)=>{c.d(b,{Vz:()=>e});let d=Symbol.for("@agegr/pi-web/session-liveness/v1");function e(a){let b=function(){let a=globalThis[d];if(a)return a;let b={providers:new Map,warned:new Set};return globalThis[d]=b,b}(),c=new Set([a.sessionId,a.sessionFile].filter(a=>!!a));if(0===c.size)return!1;for(let[a,d]of b.providers)if(c.has(d.sessionId)||void 0!==d.sessionFile&&c.has(d.sessionFile))try{if(!0===d.isActive())return!0}catch(c){b.warned.has(a)||(b.warned.add(a),console.warn(`[pidance] session liveness provider 抛错,按不活跃处理: ${d.name}`,c))}return!1}},16601:(a,b,c)=>{c.d(b,{h_:()=>g,AM:()=>f,fb:()=>e});var d=c(89358);function e(a,b){if(b===a.getLeafId())return{kind:"noop"};if(b===a.getLastEntryId())return{kind:"branch",leafId:b,clearSidecar:!0};if(!a.getEntry(b))throw Error(`Entry ${b} not found`);return{kind:"branch",leafId:b,clearSidecar:!1}}function f(a,b){let c=a.getLeafId();if(!c)throw Error("Session has no leaf");let d=a.getEntry(b);if(!d)throw Error("Entry not found");if("message"!==d.type||d.message?.role!=="assistant")throw Error("Only assistant messages can be branched from");let e=function(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}(a.getBranch(c),b);return{kind:"branch",leafId:e,clearSidecar:e===a.getLastEntryId()}}function g(a){let{sessionManager:b,sessionFile:c,plan:e}=a;"noop"!==e.kind&&(c&&(e.clearSidecar?(0,d.$9)(c):(0,d.R3)(c,e.leafId)),b.branch(e.leafId))}},19228:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Jv:()=>r,Tv:()=>u,_D:()=>q,n3:()=>n,wc:()=>s});var e=c(89477),f=c(42524),g=c(86697),h=c(26238),i=c(93686),j=c(87390),k=c(69271),l=c(58732),m=a([i,j,l]);[i,j,l]=m.then?(await m)():m;let r="send_file_to_user",s="Send file to user",t="## 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===t)?a:[...a,t]}let u={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)}})},31119:(a,b,c)=>{function d(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 e(a){let b=d(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}c.d(b,{eU:()=>d,yu:()=>e})},33727:(a,b,c)=>{c.d(b,{D:()=>d});function d(a){return a.trim().startsWith("/")}},35304:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{getRegistry:()=>m,recoverFollowUpQueues:()=>r});var e=c(69453),f=c(73579),g=c(31360),h=c(84127),i=c(40673),j=c(10611),k=c(82356),l=a([e,g,j]);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(){return[...n().keys()]}[e,g,j]=l.then?(await l)():l;let t="",u=[],v=new Set,w=null;function p(){!function a(){let b=new Set(function(){let a=new Set(o());for(let[b,c]of m())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,k.AZ)(a),v.add(a);for(let a of[...v])b.has(a)||((0,k.Hl)(a),v.delete(a));if(0===b.size){w&&(clearInterval(w),w=null);return}w||(w=setInterval(()=>{a()},8e3),w.unref?.())}();let a=function(){let a=new Set(o());for(let[b,c]of m())c.isRunning()&&a.add(c.sessionId||b);return[...a]}(),b=function(){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}(),c=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(c===t)return;t=c;let d=u.filter(b=>!a.includes(b)&&!(0,f.f)(b));if(u=[...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(globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners))try{b(a)}catch{}}async function q(a,b,c,d,e){return s(a,b,c,d,e)}async function r(){let a=(0,h.readPidancePrefs)();for(let b of function(a){let b=new Set,c=a.sessionQueue;if("object"==typeof c&&null!==c&&!Array.isArray(c))for(let[a,d]of Object.entries(c))a&&(0,i.aL)(d)&&b.add(a);for(let[c,d]of Object.entries(a)){if(!c.startsWith("sessionQueue.")||!(0,i.aL)(d))continue;let a=c.slice(13);a&&b.add(a)}return[...b].filter(b=>!0!==(0,h.ql)(a,`sessionQueueHold.${b}`)&&!0!==a[`sessionQueueHold.${b}`]).sort()}(a)){let a=m().get(b);if(a?.isAlive()||(0,k.wy)(b))continue;let c=await (0,e.os)(b);if(!c)continue;let d=process.cwd();try{d=(0,g.kW)(c).getHeader()?.cwd||process.cwd()}catch{}try{await q(b,c,d)}catch(a){console.error(`[pidance] recover follow-up queue failed for ${b}:`,a)}}}async function s(a,b,c,d,f){let g=m(),h=n(),i=g.get(a);if(i?.isAlive())return{session:i,realSessionId:a};let l=h.get(a);if(l)return l;if(!(0,k.kP)(a))throw Error(k.GT);p();let o=(async()=>{try{let h=await (0,j.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>p(),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))}}),i=h.sessionId,l=h.sessionFile;return l&&(0,e.O8)(i,l),i!==a&&(0,k.kP)(i),h.onDestroy(()=>{g.get(i)===h&&g.delete(i),a!==i&&g.get(a)===h&&g.delete(a),(0,k.Hl)(i),a!==i&&(0,k.Hl)(a),p()}),g.set(i,h),h.beginExtensionBinding(),{session:h,realSessionId:i}}catch(b){throw(0,k.Hl)(a),p(),b}})().finally(()=>{h.delete(a),p()});return h.set(a,o),o}d()}catch(a){d(a)}})},35948:(a,b,c)=>{c.d(b,{FH:()=>g,Ln:()=>f,PB:()=>h,uG:()=>d});let d="pidance.binary",e=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function f(a){if("string"!=typeof a)return null;let b=a.trim().toLowerCase();return e.test(b)?b:null}function g(a,b){let c={role:"custom",customType:d,content:a.name,display:!0,details:a};return void 0!==b&&(c.timestamp=b),c}function h(a,b){let c,d=f(a.mimeType)??"application/octet-stream",e=function(a){if("string"!=typeof a)return null;let b=a.replace(/[\\/\0]/g,"_").trim();return!b||b.length>180?null:b}(a.name)??"file",g=a.path.trim(),h=Number.isSafeInteger(a.size)&&a.size>=0?a.size:0,i=a.previewPath?.trim()||void 0;return{type:"binary",version:1,kind:(c=d.toLowerCase()).startsWith("image/")?"image":c.startsWith("audio/")?"audio":c.startsWith("video/")?"video":"file",path:g,name:e,mimeType:d,size:h,...i?{previewPath:i}:{},...b?{messageEntryId:b}:{}}}},36315:(a,b,c)=>{let d;c.d(b,{Yg:()=>h,Lm:()=>y,hR:()=>C,Mf:()=>E,GD:()=>B,t_:()=>A,F$:()=>D,DD:()=>s,YJ:()=>w,Sw:()=>x});let e=JSON.parse('{"$schema":"https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json","name":"dark","vars":{"cyan":"#00d7ff","blue":"#5f87ff","green":"#b5bd68","red":"#cc6666","yellow":"#ffff00","text":"#d4d4d4","gray":"#808080","dimGray":"#666666","darkGray":"#505050","accent":"#8abeb7","selectedBg":"#3a3a4a","userMsgBg":"#343541","toolPendingBg":"#282832","toolSuccessBg":"#283228","toolErrorBg":"#3c2828","customMsgBg":"#2d2838"},"colors":{"accent":"accent","border":"blue","borderAccent":"cyan","borderMuted":"darkGray","success":"green","error":"red","warning":"yellow","muted":"gray","dim":"dimGray","text":"text","thinkingText":"gray","selectedBg":"selectedBg","scrollbarTrack":"darkGray","scrollbarThumb":"text","searchMatchBg":"selectedBg","searchMatchText":"text","userMessageBg":"userMsgBg","userMessageText":"text","customMessageBg":"customMsgBg","customMessageText":"text","customMessageLabel":"#9575cd","toolPendingBg":"toolPendingBg","toolSuccessBg":"toolSuccessBg","toolErrorBg":"toolErrorBg","toolTitle":"text","toolOutput":"gray","mdHeading":"#f0c674","mdLink":"#81a2be","mdLinkUrl":"dimGray","mdCode":"accent","mdCodeBlock":"green","mdCodeBlockBorder":"gray","mdQuote":"gray","mdQuoteBorder":"gray","mdHr":"gray","mdListBullet":"accent","toolDiffAdded":"green","toolDiffRemoved":"red","toolDiffContext":"gray","syntaxComment":"#6A9955","syntaxKeyword":"#569CD6","syntaxFunction":"#DCDCAA","syntaxVariable":"#9CDCFE","syntaxString":"#CE9178","syntaxNumber":"#B5CEA8","syntaxType":"#4EC9B0","syntaxOperator":"#D4D4D4","syntaxPunctuation":"#D4D4D4","thinkingOff":"darkGray","thinkingMinimal":"#6e6e6e","thinkingLow":"#5f87af","thinkingMedium":"#81a2be","thinkingHigh":"#b294bb","thinkingXhigh":"#d183e8","thinkingMax":"#ff5fff","bashMode":"green"},"export":{"pageBg":"#18181e","cardBg":"#1e1e24","infoBg":"#3c3728"}}');function f(a){let b=a.replace("#",""),c=Number.parseInt(3===b.length?b.split("").map(a=>a+a).join(""):b,16);return{r:c>>16&255,g:c>>8&255,b:255&c}}class g{constructor(a,b,c="truecolor",d){for(const[b,e]of(this.fgAnsiMap=new Map,this.bgAnsiMap=new Map,this.mode=c,this.name=d?.name,Object.entries({...a,thinkingMax:a.thinkingMax??a.thinkingXhigh})))this.fgAnsiMap.set(b,function(a,b){if(""===a)return"\x1b[39m";if("number"==typeof a)return`\x1b[38;5;${a}m`;if("string"==typeof a&&a.startsWith("#")){if("truecolor"===b){let{r:b,g:c,b:d}=f(a);return`\x1b[38;2;${b};${c};${d}m`}return"\x1b[38;5;7m"}throw Error(`Invalid color value: ${String(a)}`)}(e,c));for(const[a,d]of Object.entries(b))this.bgAnsiMap.set(a,function(a,b){if(""===a)return"\x1b[49m";if("number"==typeof a)return`\x1b[48;5;${a}m`;if("string"==typeof a&&a.startsWith("#")){if("truecolor"===b){let{r:b,g:c,b:d}=f(a);return`\x1b[48;2;${b};${c};${d}m`}return"\x1b[48;5;0m"}throw Error(`Invalid color value: ${String(a)}`)}(d,c))}fg(a,b){let c=this.fgAnsiMap.get(a);if(!c)throw Error(`Unknown theme color: ${a}`);return`${c}${b}\x1b[39m`}bg(a,b){let c=this.bgAnsiMap.get(a);if(!c)throw Error(`Unknown theme background color: ${a}`);return`${c}${b}\x1b[49m`}bold(a){return`\x1b[1m${a}\x1b[22m`}italic(a){return`\x1b[3m${a}\x1b[23m`}underline(a){return`\x1b[4m${a}\x1b[24m`}inverse(a){return`\x1b[7m${a}\x1b[27m`}strikethrough(a){return`\x1b[9m${a}\x1b[29m`}getFgAnsi(a){let b=this.fgAnsiMap.get(a);if(!b)throw Error(`Unknown theme color: ${a}`);return b}getBgAnsi(a){let b=this.bgAnsiMap.get(a);if(!b)throw Error(`Unknown theme background color: ${a}`);return b}getColorMode(){return this.mode}getThinkingBorderColor(a){let b={off:"thinkingOff",minimal:"thinkingMinimal",low:"thinkingLow",medium:"thinkingMedium",high:"thinkingHigh",xhigh:"thinkingXhigh",max:"thinkingMax"}[a]??"thinkingOff";return a=>this.fg(b,a)}getBashModeBorderColor(){return a=>this.fg("bashMode",a)}}let h=100,i=new Set(["selectedBg","userMessageBg","customMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg"]),j=Symbol.for("@earendil-works/pi-coding-agent:theme"),k=Symbol.for("@mariozechner/pi-coding-agent:theme"),l="Extension renderers that rely on the SDK theme helpers will not draw their themed content (for example the built-in edit tool's diff): Pidance could not hand its theme to the shared pi theme slot.",m=/Theme not initialized/i,n=!1,o=null,p=new Set,q=[],r=null;function s(a){if(r=a,a)for(let b of q.splice(0))a(b)}function t(a,b){if(!p.has(a)){if(p.add(a),console.warn(`[pidance] ${b}`),!r)return void q.push(b);try{r(b)}catch(a){console.warn("[pidance] render bridge warning sink failed:",a)}}}function u(a){let b=a instanceof Error?a.message:String(a);m.test(b)&&t("sdk-theme-uninitialized",`${l} (${b})`)}let v=null;function w(a){v=a}function x(){if(null!==o)return o;if(!v)return null;try{return v(),o=!0,!0}catch(a){return o=!1,t("sdk-theme-verify",`${l} (self-check failed: ${a instanceof Error?a.message:String(a)})`),!1}}function y(){if(void 0!==d)return d;try{let a=function(a){let b={...a.colors,thinkingMax:a.colors.thinkingMax??a.colors.thinkingXhigh},c=a.vars??{},d={},e={};for(let[a,f]of Object.entries(b)){let b=function a(b,c,d=new Set){if("number"==typeof b||""===b||b.startsWith("#"))return b;if(d.has(b))throw Error(`Circular variable reference detected: ${b}`);if(!(b in c))throw Error(`Variable reference not found: ${b}`);return d.add(b),a(c[b],c,d)}(f,c);i.has(a)?e[a]=b:d[a]=b}return new g(d,e,"truecolor",{name:a.name})}(e);d=a,function(a){if(!n){n=!0;try{let b=globalThis;b[j]=a,b[k]=a}catch(a){t("sdk-theme-install",`${l} (install failed: ${a instanceof Error?a.message:String(a)})`);return}}}(a)}catch{d=null}return d}function z(a,b=h){if(!a||"object"!=typeof a||"function"!=typeof a.render)return null;try{let c=a.render(b);if(!function(a){if(!Array.isArray(a)||0===a.length||!a.every(a=>"string"==typeof a)||a.length>500)return!1;let b=0;for(let c of a)if(c.length>4e3||(b+=c.length)>204800)return!1;return!0}(c))return null;return c}catch(a){return u(a),null}}function A(a,b,c,d,e,f=h){let g=function(a){if(!a||"object"!=typeof a)return;let b=a.renderResult??a.ln;return"function"==typeof b?b:void 0}(a);if(!g)return null;let i=y();if(!i)return null;try{let a=g(b,c,i,d);return a&&"object"==typeof a&&e?.(a),z(a,f)}catch(a){return u(a),null}}function B(a,b,c,d,e=h){let f=function(a){if(!a||"object"!=typeof a)return;let b=a.renderCall;return"function"==typeof b?b:void 0}(a);if(!f)return null;let g=y();if(!g)return null;try{let a=f(b,g,c);return a&&"object"==typeof a&&d?.(a),z(a,e)}catch(a){return u(a),null}}function C(a,b=h){return z(a,b)}function D(a,b=h){return C(a,b)}function E(a,b,c,d=h){if("function"!=typeof a||!c)return null;try{let e=a(b,{expanded:!0},c);return z(e,d)}catch(a){return u(a),null}}},37607:(a,b,c)=>{c.d(b,{x:()=>f});var d=c(89477),e=c(84127);function f(a,b){if(!a)return"";try{let c=(0,d.statSync)((0,e.m6)(b),{throwIfNoEntry:!1});if(!c||c.size>4194304)return"";return function(a,b){let c=a.drafts;if("object"!=typeof c||null===c||Array.isArray(c))return"";let d=c[b];if("object"!=typeof d||null===d||Array.isArray(d))return"";let e=d.value;return"string"==typeof e?e:""}((0,e.readPidancePrefs)(b),a)}catch(a){return console.error("[pidance] readComposerDraftText failed:",a),""}}},40673:(a,b,c)=>{function d(a){if("string"!=typeof a)return null;let b=a.trim();return/^[A-Za-z0-9_-]{1,64}$/.test(b)?b:null}function e(a){return d(a)}function f(a){if(!Array.isArray(a))return[];let b=[];for(let c of a){let a=d(c);a&&!b.includes(a)&&b.push(a)}return b.length>128?b.slice(b.length-128):b}function g(a,b){let c=[...a];for(let a of b)!a||c.includes(a)||c.push(a);return c.length>128?c.slice(c.length-128):c}c.d(b,{EP:()=>l,Kk:()=>d,Ot:()=>q,Pt:()=>o,S1:()=>g,X_:()=>p,aL:()=>m,gC:()=>n,jG:()=>k,ko:()=>i,mv:()=>e,ym:()=>h});let h=32;function i(a,b="waiting",c){let d,e={id:(d=globalThis.crypto)&&"function"==typeof d.randomUUID?d.randomUUID():`q-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,text:a,state:b};return c?.length&&(e.media=[...c]),e}function j(a,b){let c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=0x1000193*c>>>0;return`legacy-${a}-${c.toString(36)}`}function k(a){let b=Array.isArray(a)?a:a&&"object"==typeof a?a.items:void 0,c=a&&"object"==typeof a&&!Array.isArray(a)&&"number"==typeof a.revision&&Number.isFinite(a.revision)?a.revision:0,d=f(a&&"object"==typeof a&&!Array.isArray(a)?a.admittedAttemptIds:void 0);if(!Array.isArray(b))return{items:[],revision:c,admittedAttemptIds:d};let e=[];for(let a=0;a<b.length;a++){let c=function(a,b){var c;if("string"==typeof a){let c=a.trim();return c?{id:j(b,a),text:c,state:"waiting"}:null}if(!a||"object"!=typeof a||Array.isArray(a)||"string"!=typeof a.text)return null;let d=function(a){if(void 0===a)return[];if(!Array.isArray(a)||a.length>h)return null;let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))return null;let a="model"===c.role||"original"===c.role?c.role:null,d="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.mimeType?c.mimeType.trim():"",f="string"==typeof c.name?c.name.trim():"",g=c.size,h="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(!a||!d||!e||!f||"number"!=typeof g||!Number.isSafeInteger(g)||g<0||void 0!==c.previewPath&&!h)return null;b.push({role:a,path:d,name:f,mimeType:e,size:g,...h&&h!==d?{previewPath:h}:{}})}return b}(a.media);return null!==d&&(a.text.trim()||0!==d.length)?{id:"string"==typeof a.id&&a.id.trim()?a.id:j(b,a.text),text:a.text,state:"claimed"===(c=a.state)||"unknown"===c?c:"waiting",...d.length?{media:d}:{}}:null}(b[a],a);c&&e.push(c)}return{items:e,revision:c,admittedAttemptIds:d}}function l(a){let b=f(a.admittedAttemptIds);return{items:a.items.map(a=>({id:a.id,text:a.text,state:a.state,...a.media?.length?{media:a.media.map(a=>({...a}))}:{}})),revision:a.revision,...b.length?{admittedAttemptIds:b}:{}}}function m(a){return k(a).items.length>0}function n(a){return a.map(a=>a.text)}function o(a,b,c){let d=new Set(c?.inFlightIds??[]),e=Array(a.length).fill(!1),f=new Map;a.forEach((a,b)=>{f.has(a.id)||f.set(a.id,b)});let g=[];for(let c of b){if(void 0!==c.id&&d.has(c.id))continue;let b=void 0===c.id?void 0:f.get(c.id);if(void 0!==b&&!e[b]){e[b]=!0;let d=a[b],f=c.media?.length?c.media:d.media;g.push({id:d.id,text:c.text,state:d.state,...f?.length?{media:[...f]}:{}});continue}let h=-1;for(let b=0;b<a.length;b++){let d=a[b];if(!e[b]&&d.text===c.text){if(function(a,b){let c=a??[],d=b??[];return c.length===d.length&&c.every((a,b)=>a.path===d[b].path)}(d.media,c.media)){h=b;break}h<0&&(h=b)}}if(h>=0){e[h]=!0;let b=a[h],d=c.media?.length?c.media:b.media;g.push({id:b.id,text:c.text,state:b.state,...d?.length?{media:[...d]}:{}});continue}g.push(c.media?.length?i(c.text,"waiting",c.media):i(c.text,"waiting"))}return g}function p(a,b){return{text:[...n(a),...b?.trim()?[b.trim()]:[]].map(a=>a.trim()).filter(a=>a.length>0).join("\n"),media:q(a)}}function q(a){return a.flatMap(a=>a.media??[])}},57856:(a,b,c)=>{c.d(b,{TQ:()=>e,Tf:()=>d});let d=40;function e(a,b=92,c=d,f={}){let g="function"==typeof b?b:()=>b,h="function"==typeof c?c:()=>c,i=Object.freeze({render:()=>[],invalidate:()=>{},handleInput:()=>{},getText:()=>"",setText:()=>{}}),j=f.isEditorFocused,k=!1,l={terminal:Object.freeze({get columns(){return g()},get rows(){return h()},kittyProtocolActive:!1}),requestRender:a,stop(){k||(k=!0,f.onUnsupported?.("tui.stop()/start() (external editor handover)"))},start(){}};return Object.defineProperty(l,"focusedComponent",{enumerable:!0,get:()=>j?.()===!0?i:void 0}),Object.freeze(l)}},58732:(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(92783),h=c(93686),i=c(35948),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)}})},63480:(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)}},66323:(a,b,c)=>{c.d(b,{EE:()=>r,_2:()=>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={}){var b,c;let d,e,f,h,n=a.fs??o,q=a.limit??20,r=a.now?.()??Date.now(),C=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(C);if(a.isSymbolicLink()||!a.isDirectory())return t(r,!1);e=n.realpathSync(C)}catch(a){return u(a),t(r,!1)}try{f=n.readdirSync(C)}catch(a){return u(a),t(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(!v(h,c))return null;let p=function(a,b,c){let d=w(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=z(p.startedAt);if(void 0===s)return null;let t="string"==typeof p.runId&&p.runId.trim()?p.runId.trim():d,u=y(p.activityState),C=z(p.endedAt),D=z(p.lastUpdate),E="string"==typeof p.cwd?p.cwd:void 0,F="string"==typeof p.error?p.error:void 0,G=z(p.currentStep),H=z(p.chainStepCount),I=A(p.totalTokens),J=B(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=y(d.activityState);g&&(f.activityState=g),"string"==typeof d.currentTool&&(f.currentTool=d.currentTool);let h=A(d.tokens);h&&(f.tokens=h);let i=B(d.totalCost)??z(d.costUsd);void 0!==i&&(f.costUsd=i);let j=z(d.startedAt);void 0!==j&&(f.startedAt=j);let k=z(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=x(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=z(b.timestamp)??z(b.ts)??z(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=x(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!==C&&(N.endedAt=C),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,C,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 t(a,b){return{runs:[],generatedAt:a,rootAvailable:b}}function u(a){return"object"==typeof a&&null!==a&&"code"in a&&"ENOENT"===a.code}function v(a,b){let c=i().resolve(a),d=b.endsWith(i().sep)?b:b+i().sep;return c===b||c.startsWith(d)}function w(a,b,c){try{let d=a.lstatSync(b);if(d.isSymbolicLink()||!d.isFile())return null;let e=a.realpathSync(b);if(!v(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 x(a,b,c,d){let e=w(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 y(a){return"string"==typeof a&&n.has(a)?a:void 0}function z(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}function A(a){if(!a||"object"!=typeof a||Array.isArray(a))return;let b=z(a.input),c=z(a.output),d=z(a.total);if(void 0!==b&&void 0!==c&&void 0!==d)return{input:b,output:c,total:d}}function B(a){return"number"==typeof a&&Number.isFinite(a)?a:!a||"object"!=typeof a||Array.isArray(a)?void 0:z(a.costUsd)}},68642:(a,b,c)=>{c.d(b,{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)}},69271:(a,b,c)=>{c.d(b,{GO:()=>h,X:()=>j,cV:()=>i,k2:()=>k,oC:()=>l});let d={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"},e={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"},f={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},g={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function h(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function i(a){return d[h(a)]??null}function j(a){return e[h(a)]??null}function k(a){return f[h(a)]??null}function l(a){return g[h(a)]??null}},69714:(a,b,c)=>{function d(a){let b=a.toolCallId;return"string"==typeof b&&""!==b?b:null}function e(a){return Array.isArray(a)&&0!==a.length&&a.every(a=>"string"==typeof a)?a:null}function f(){let a=null,b=new Map;return{remember(c){switch(c.type){case"agent_start":case"agent_end":case"prompt_done":case"agent_settled":a=null,b.clear();return;case"message_start":case"message_update":{let b=c.message;if(!b||"user"===b.role)return;a=c;return}case"message_end":a=null;return;case"tool_execution_start":{let a=d(c);if(!a)return;b.set(a,{start:c,update:null,renderedUpdate:null,callLines:null,resultLines:null});return}case"tool_execution_update":{let a=d(c);if(!a)return;let f=b.get(a);if(!f)return;f.update=c,null!==e(c.renderedLines)&&(f.renderedUpdate=c);return}case"rendered_lines_update":{let a=d(c);if(!a)return;let f=b.get(a);if(!f)return;let g=e(c.renderedCallLines);g&&(f.callLines=g);let h=e(c.renderedResultLines);h&&(f.resultLines=h);return}case"tool_execution_end":{let a=d(c);if(!a)return;b.delete(a);return}default:return}},snapshot(){let c=[];for(let e of(a&&c.push(a),b.values())){c.push(e.callLines?{...e.start,renderedCallLines:e.callLines}:e.start);let a=e.update??e.renderedUpdate;a&&(!Object.prototype.hasOwnProperty.call(a,"renderedLines")&&e.renderedUpdate?c.push({...a,renderedLines:e.renderedUpdate.renderedLines}):c.push(a)),e.resultLines&&c.push({type:"rendered_lines_update",toolCallId:d(e.start),renderedResultLines:e.resultLines})}return{isStreaming:null!==a||b.size>0,events:c}},reset(){a=null,b.clear()}}}c.d(b,{b:()=>f})},73579:(a,b,c)=>{c.d(b,{f:()=>d});function d(a){return a.startsWith("__new__")}},74108:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{tZ:()=>k});var e=c(716),f=c(29862),g=c(57856),h=c(36315),i=a([f]);let l=new(f=(i.then?(await i)():i)[0]).KeybindingsManager(f.TUI_KEYBINDINGS);function j(a,b,c,d,f,g,h){let i=(0,e.randomUUID)();return new Promise((e,j)=>{let k,l=!1,m=()=>{a.delete(i),b.delete(i),k&&clearTimeout(k),d?.signal?.removeEventListener("abort",o)},n=a=>{l||(l=!0,m(),e(a))},o=()=>n(f);d?.signal?.addEventListener("abort",o,{once:!0}),d?.timeout&&(k=setTimeout(()=>n(f),d.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 k(a,b={}){let c,d=new Map,f=new Map,i=new Map,m=new Map,n=new Map,o=null,p=!1,q=h.Yg,r=g.Tf,s=new Set,t=new Set,u=[],v=(a,b)=>{!function(a,b,c=16){a.push(b),a.length>c&&a.splice(0,a.length-c)}(u,{id:a,message:b,notifyType:"warning"})},w=new Set,x=()=>{a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"terminalInputListeners",count:w.size})},y=new Map,z=()=>{var a=Date.now();for(let[b,c]of y)c<=a&&y.delete(b);return y.size>0},A=b=>{if(t.has(b))return;t.add(b),console.warn(`[pidance] extension UI capability not supported on web: ${b}`);let c=(0,e.randomUUID)(),d=`Extension UI "${b}" is not supported by the Pidance web client.`;v(c,d),a({type:"extension_ui_request",id:c,method:"notify",message:d,notifyType:"warning"})},B=new Map,C=a=>{let b=B.get(a);if(b){B.delete(a);try{b.dispose?.()}catch(a){console.error("[pidance] widget dispose failed:",a)}}},D=(b,c)=>{m.has(b)&&(m.delete(b),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:void 0,widgetPlacement:c}))},E={select:(b,c,e)=>j(d,f,a,e,void 0,{method:"select",title:b,options:c,timeout:e?.timeout},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),confirm:(b,c,e)=>j(d,f,a,e,!1,{method:"confirm",title:b,message:c,timeout:e?.timeout},a=>(!("cancelled"in a)||!a.cancelled)&&"confirmed"in a&&!!a.confirmed),input:(b,c,e)=>j(d,f,a,e,void 0,{method:"input",title:b,placeholder:c,timeout:e?.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,e.randomUUID)(),method:"notify",message:b,notifyType:c})},onTerminalInput:b=>(((b,c)=>{if(t.has(b))return;t.add(b);let d=`Extension UI "${b}" is limited by the Pidance web client: ${c}`;console.warn(`[pidance] ${d}`);let f=(0,e.randomUUID)();v(f,d),a({type:"extension_ui_request",id:f,method:"notify",message:d,notifyType:"warning"})})("onTerminalInput","handlers only receive keys in two narrow windows: (1) with a widget present and the composer focused and empty, Down/Left start a selection, after which arrows, j, k, Enter and Escape are routed while the selection lasts; (2) while a collapsed extension panel exists, Escape, F1-F12, Alt+<char> and Ctrl+<char> (browser-reserved chords and Ctrl+Space excluded) are routed. Ordinary typing never reaches them."),w.add(b),x(),()=>{w.delete(b)&&x()}),setStatus(b,c){c?i.set(b,c):i.delete(b),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setStatus",statusKey:b,statusText:c})},setWorkingMessage(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWorkingMessage",message:b??null})},setWorkingVisible(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWorkingVisible",visible:!!b})},setWorkingIndicator(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWorkingIndicator",frames:Array.isArray(b?.frames)?b.frames.filter(a=>"string"==typeof a):null,intervalMs:"number"==typeof b?.intervalMs?b.intervalMs:null})},setHiddenThinkingLabel(a){void 0!==a&&A("setHiddenThinkingLabel")},setWidget(b,c,d){"function"==typeof c?((b,c,d)=>{let f;C(b);let i=(0,h.Lm)();if(!i)return D(b,d);let j={requestRender:()=>{}},k=!1,l=()=>{if(k=!1,B.get(b)!==j)return;let c=(0,h.F$)(f,q);null!==c&&(m.set(b,{lines:c,placement:d}),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:c,widgetPlacement:d}))},n=(0,g.TQ)(()=>{k||B.get(b)!==j||(k=!0,queueMicrotask(l))},()=>q,()=>r,{isEditorFocused:z,onUnsupported:A});j.requestRender=n.requestRender;try{f=c(n,i)}catch(a){console.error("[pidance] widget factory failed:",a),D(b,d);return}let o=f;j.dispose="function"==typeof o?.dispose?()=>f.dispose():void 0,B.set(b,j),l()})(b,c,d?.placement):(C(b),(void 0===c||Array.isArray(c))&&(null==c?m.delete(b):m.set(b,{lines:c,placement:d?.placement}),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:c,widgetPlacement:d?.placement})))},setFooter(a){void 0!==a&&A("setFooter")},setHeader(a){void 0!==a&&A("setHeader")},setTitle(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setTitle",title:b})},async custom(b,c){let d=(0,e.randomUUID)(),f=function(a){if(!a||"object"!=typeof a||!0!==a.overlay)return null;let b=a.overlayOptions&&"object"==typeof a.overlayOptions?a.overlayOptions:{},c={anchor:"string"==typeof b.anchor?b.anchor:"center"},d=b.width;("number"==typeof d||"string"==typeof d)&&(c.width=d),"number"==typeof b.minWidth&&(c.minWidth=b.minWidth);let e=b.maxHeight;("number"==typeof e||"string"==typeof e)&&(c.maxHeight=e);let f=b.margin;if("number"==typeof f)c.margin=f;else if(f&&"object"==typeof f){let a={};for(let b of["top","right","bottom","left"])"number"==typeof f[b]&&(a[b]=f[b]);c.margin=a}return c}(c);return new Promise(e=>{let i,j=!1,k=b=>{j||(j=!0,s.delete(v),n.delete(d),o?.id===d&&(o=null),a({type:"extension_ui_request",id:d,method:"custom",closed:!0,lines:[]}),e(b))},m=[],p=!1,t=!1,u=()=>{t||(a({type:"extension_ui_request",id:d,method:"custom",lines:m,...p?{hidden:p}:{},...f?{layout:f}:{}}),o={id:d,lines:[...m],...p?{hidden:p}:{},...f?{layout:f}:{}})},v=()=>{if(j)return;let a=[];try{let b=i?.render?.(q);Array.isArray(b)&&(a=b.filter(a=>"string"==typeof a))}catch(a){console.error("[pidance] custom UI render failed:",a)}m=a,u()};n.set(d,{handleInput:a=>{if("\x03"===a)return void k(void 0);try{i?.handleInput?.(a)}catch(a){console.error("[pidance] custom UI input failed:",a)}},handleMouse:a=>{try{i?.handleMouse?.(a)}catch(a){console.error("[pidance] custom UI mouse failed:",a)}},done:k});let w=(0,g.TQ)(()=>{v()},()=>q,()=>r,{isEditorFocused:z,onUnsupported:A});s.add(v);let x=(0,h.Lm)()??E.theme;c?.onHandle?.({hide(){t||j||(t=!0,p=!0,n.delete(d),o?.id===d&&(o=null),a({type:"extension_ui_request",id:d,method:"custom",closed:!0,lines:[]}))},setHidden(a){if(!t){let b;b=!!a,p===b||(p=b,j||u())}},isHidden:()=>p,focus(){},unfocus(){},isFocused:()=>!t&&!p,getBounds:()=>void 0}),Promise.resolve().then(()=>b(w,x,l,k)).then(a=>{j||(i=a,v())}).catch(a=>{console.error("[pidance] custom UI factory failed:",a),k(void 0)})})},pasteToEditor(a){this.setEditorText(a)},setEditorText(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"set_editor_text",text:b})},getEditorText(){try{return b.readComposerText?.()??""}catch(a){return console.error("[pidance] readComposerText failed:",a),""}},editor:async(b,c)=>j(d,f,a,void 0,void 0,{method:"editor",title:b,prefill:c},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),addAutocompleteProvider(){A("addAutocompleteProvider")},setEditorComponent(a){c=a,void 0!==a&&A("setEditorComponent")},getEditorComponent:()=>c,get theme(){let a,b;return(0,h.Lm)()??(a=a=>String(a??""),b=(a,b)=>void 0===b?"":String(b),{name:void 0,sourcePath:void 0,sourceInfo:void 0,fg:b,bg:b,bold:a,dim:a,italic:a,underline:a,inverse:a,strikethrough:a,getFgAnsi:()=>"",getBgAnsi:()=>"",getColorMode:()=>"truecolor",getThinkingBorderColor:()=>a,getBashModeBorderColor:()=>a})},getAllThemes:()=>(A("getAllThemes"),[]),getTheme(){A("getTheme")},setTheme:()=>({success:!1,error:"Theme switching not supported in Web mode"}),getToolsExpanded:()=>p,setToolsExpanded(b){p=!!b,a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setToolsExpanded",toolsExpanded:p})}};return{uiContext:E,pending:d,statuses:i,widgets:m,pendingSnapshot:f,get customSnapshot(){return o},get terminalInputListenerCount(){return w.size},get capabilityNoticeSnapshot(){return u.map(a=>({...a}))},respond(a,b){let c=d.get(a);return!!c&&(c.resolve(b),!0)},inputCustom(a,b){let c=n.get(a);return!!c&&(c.handleInput(b),!0)},inputCustomMouse(a,b){let c=n.get(a);return!!c&&(c.handleMouse(b),!0)},setRenderSize(a){let b=Math.round(a.width),c=Math.round(a.rows);if(!Number.isFinite(b)||b<=0||!Number.isFinite(c)||c<=0||b===q&&c===r)return!1;for(let a of(q=b,r=c,[...s]))a();for(let a of[...B.values()])a.requestRender();return!0},dispatchTerminalInput(a){let b=a;for(let a of w){let c;try{c=a(b)}catch(a){console.error("[pidance] extension terminal input listener failed:",a);continue}if(c?.consume)return{consumed:!0,data:b};c?.data!==void 0&&(b=c.data)}return 0===b.length?{consumed:!0,data:b}:{consumed:!1,data:b}},setEditorFocus:(a,b="default")=>{let c=z();if(a?y.set(b,Date.now()+6e4):y.delete(b),c===z())return!1;for(let a of[...B.values()])a.requestRender();for(let a of[...s])a();return!0},dispose(){for(let[a,b]of(y.clear(),c=void 0,d))d.delete(a),f.delete(a),b.reject(Error("Extension UI disposed"));for(let a of n.values())a.done(void 0);for(let a of(n.clear(),o=null,w.clear(),[...B.keys()]))C(a);i.clear(),m.clear()}}}d()}catch(a){d(a)}})},82356:(a,b,c)=>{c.d(b,{AZ:()=>u,GT:()=>h,Hl:()=>v,kP:()=>t,sweepStaleRunningLeases:()=>s,wy:()=>w});var d=c(716),e=c(89477),f=c(86697),g=c(92783);let h="Session is locked by another Pidance process (writable host ownership)",i="Timed out acquiring Pidance running-lease lock";function j(a){return(0,f.join)(a,"pidance-running-leases")}function k(a,b){let c=b.replace(/[^a-zA-Z0-9._-]+/g,"_").slice(0,180);return(0,f.join)(j(a),`${c}.json`)}function l(a){if(!Number.isFinite(a)||a<=0)return!1;try{return process.kill(a,0),!0}catch(a){return"EPERM"===a.code}}function m(a){try{let b=JSON.parse((0,e.readFileSync)(a,"utf8"));if("number"!=typeof b.pid||"string"!=typeof b.sessionId||"number"!=typeof b.heartbeatAt)return null;return{pid:b.pid,sessionId:b.sessionId,heartbeatAt:b.heartbeatAt,startedAt:"number"==typeof b.startedAt?b.startedAt:b.heartbeatAt}}catch{return null}}function n(a){try{let b=JSON.parse((0,e.readFileSync)(a,"utf8"));if("number"!=typeof b.pid||"string"!=typeof b.token)return null;return{pid:b.pid,token:b.token}}catch{return null}}function o(a,b){let c=j(a);(0,e.existsSync)(c)||(0,e.mkdirSync)(c,{recursive:!0,mode:448});let g=(0,f.join)(c,".lease-lock"),h=(0,d.randomBytes)(8).toString("hex"),k=Date.now()+3e3,m=!1;for(;!m;){let a=`${g}.${process.pid}.${h}.tmp`;try{(0,e.writeFileSync)(a,JSON.stringify({pid:process.pid,token:h}),{mode:384}),(0,e.linkSync)(a,g),m=!0}catch(b){if("EEXIST"!==b.code){try{(0,e.unlinkSync)(a)}catch{}throw b}}try{(0,e.unlinkSync)(a)}catch{}if(m)break;let b=n(g);if(b&&!l(b.pid)){try{n(g)?.token===b.token&&(0,e.unlinkSync)(g)}catch{}continue}if(!b)try{Date.now()-(0,e.statSync)(g).mtimeMs>1e4&&(0,e.unlinkSync)(g)}catch{}if(Date.now()>=k)throw Error(i);!function(){let a=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(a,0,0,5)}()}try{return b()}finally{try{n(g)?.token===h&&(0,e.unlinkSync)(g)}catch{}}}function p(a){return a instanceof Error&&a.message===i}function q(a,b){let c=`${a}.${process.pid}.tmp`;(0,e.writeFileSync)(c,`${JSON.stringify(b)}
2
- `,{mode:384}),(0,e.renameSync)(c,a)}function r(a){return!!(a&&l(a.pid))}function s(a=(0,g.$M)(),b=Date.now()){try{let c,{fresh:d,removed:g}=(c=j(a),(0,e.existsSync)(c)?o(a,()=>{let a=[],d=0;for(let g of(0,e.readdirSync)(c)){if(!g.endsWith(".json"))continue;let h=(0,f.join)(c,g),i=m(h);if(!r(i)){try{(0,e.unlinkSync)(h),d+=1}catch{}continue}b-i.heartbeatAt<=2e4&&l(i.pid)&&a.push(i)}return{fresh:a,removed:d}}):{fresh:[],removed:0});return{removed:g,active:d.length,skipped:!1}}catch(a){if(p(a))return{removed:0,active:0,skipped:!0};throw a}}function t(a,b=(0,g.$M)(),c=Date.now()){if(!a)return!1;try{return o(b,()=>{let d=k(b,a),f=(0,e.existsSync)(d)?m(d):null;return!(f&&f.pid!==process.pid&&r(f))&&(q(d,{pid:process.pid,sessionId:a,heartbeatAt:c,startedAt:f&&f.pid===process.pid?f.startedAt:c}),!0)})}catch(a){if(p(a))return!1;throw a}}function u(a,b=(0,g.$M)(),c=Date.now()){if(a)try{o(b,()=>{let d=k(b,a),f=(0,e.existsSync)(d)?m(d):null;f&&f.pid!==process.pid&&r(f)||q(d,{pid:process.pid,sessionId:a,heartbeatAt:c,startedAt:f&&f.pid===process.pid?f.startedAt:c})})}catch(a){if(!p(a))throw a}}function v(a,b=(0,g.$M)()){if(a)try{o(b,()=>{let c=k(b,a),d=(0,e.existsSync)(c)?m(c):null;if(!d||d.pid===process.pid)try{(0,e.unlinkSync)(c)}catch{}})}catch(a){if(!p(a))throw a}}function w(a,b=(0,g.$M)(),c=Date.now()){if(!a)return!1;let d=(0,e.existsSync)(k(b,a))?m(k(b,a)):null;return!!d&&d.pid!==process.pid&&r(d)}},88876:(a,b,c)=>{function d(a,b){if(!b||a.length!==b.length)return!1;for(let c=0;c<a.length;c+=1)if(a[c]!==b[c])return!1;return!0}function e(a,b){let c={};return a.callLines&&!d(a.callLines,b.callLines)&&(c.callLines=a.callLines),a.resultLines&&!d(a.resultLines,b.resultLines)&&(c.resultLines=a.resultLines),c.callLines||c.resultLines?c:null}function f(a){let b=a.now??(()=>Date.now()),c=a.setTimer??((a,b)=>setTimeout(a,b)),d=a.clearTimer??(a=>{clearTimeout(a)}),e=new Map,f=!1,g=a=>{let b=e.get(a);return b||(b={rendering:!1,pending:!1,timer:null,lastRunAt:void 0},e.set(a,b)),b},h=(c,d)=>{if(d.rendering){d.pending=!0;return}d.rendering=!0,d.lastRunAt=b();try{let b=a.recompute(c);null!=b&&a.emit(c,b)}catch(b){a.onError?.(b)}finally{d.rendering=!1,d.pending&&(d.pending=!1,i(c))}},i=d=>{if(f)return;let e=g(d);if(e.rendering){e.pending=!0;return}let i=void 0===e.lastRunAt?1/0:b()-e.lastRunAt;if(i<a.minIntervalMs){if(null!==e.timer)return;e.timer=c(()=>{e.timer=null,h(d,e)},a.minIntervalMs-i);return}h(d,e)},j=a=>{if(f)return;let b=g(a);null!==b.timer&&(d(b.timer),b.timer=null),h(a,b)};return{request:i,flush:j,flushAll(a){for(let b of a)j(b)},isRendering:a=>e.get(a)?.rendering===!0,dispose(){for(let a of(f=!0,e.values()))null!==a.timer&&(d(a.timer),a.timer=null),a.pending=!1;e.clear()}}}c.d(b,{VQ:()=>e,w7:()=>f})}};
1
+ "use strict";exports.id=5304,exports.ids=[3908,5304],exports.modules={2884:(a,b,c)=>{c.d(b,{Lh:()=>q,bq:()=>r,tc:()=>n,GQ:()=>o});let d=new Set(["a","c","v","x","z","y","p","s","f","n","t","w","r","l","o"]),e=new Set(["k"]),f=["ctrl","alt","shift","super"],g=new Set([...d,"b","d","e","g","h","i","j","q","u","m"]),h=/^f([1-9]|1[0-2])$/,i=new Set(["f5","f11","f12"]),j=new Set(["0","1","2","3","4","5","6","7","8","9"]),k=new Set(["+","-","=","_"]),l=new Set(["enter","tab","space","backspace","delete","insert","clear","home","end","pageup","pagedown","up","down","left","right"]),m=new Set(["left","right","home"]);function n(a){if("string"!=typeof a)return null;let b=a.toLowerCase().split("+").map(a=>a.trim()).filter(a=>a.length>0);if(0===b.length)return null;let c=b[b.length-1];if(!c||f.includes(c))return null;let d=b.slice(0,-1);return d.some(a=>!f.includes(a))?null:[...f.filter(a=>d.includes(a)),c].join("+")}function o(a){let b=n(a);if(!b)return{available:!1,reason:"typing-conflict"};let c=b.split("+"),d=c[c.length-1],f=c.includes("ctrl"),o=c.includes("shift"),p=c.includes("alt"),q=c.includes("super");return(f||q)&&(!p&&g.has(d)||"space"===d)||p&&m.has(d)||p&&!f&&!q&&1===d.length&&d>="a"&&d<="z"||i.has(d)||(f||q)&&!p&&!o&&j.has(d)||(f||q)&&!p&&k.has(d)?{available:!1,reason:"browser-reserved"}:(f||q)&&e.has(d)||"ctrl+alt+n"===b||"escape"===d||"esc"===d?{available:!1,reason:"shell-reserved"}:h.test(d)?{available:!0}:l.has(d)?{available:!1,reason:"typing-conflict"}:f||p||q?{available:!0}:{available:!1,reason:"typing-conflict"}}let p={interrupt:"app.interrupt",clear:"app.clear",exit:"app.exit",suspend:"app.suspend",cycleThinkingLevel:"app.thinking.cycle",cycleModelForward:"app.model.cycleForward",cycleModelBackward:"app.model.cycleBackward",selectModel:"app.model.select",expandTools:"app.tools.expand",toggleThinking:"app.thinking.toggle",externalEditor:"app.editor.external",followUp:"app.message.followUp",submit:"tui.input.submit",copy:"tui.input.copy",selectConfirm:"tui.select.confirm",selectCancel:"tui.select.cancel",deleteToLineEnd:"tui.editor.deleteToLineEnd"};function q(a){let b=a.userBindings??{},c={};for(let[a,d]of Object.entries(b)){let e=function(a){if("string"==typeof a)return a.length>0?a:null;if(!Array.isArray(a))return null;let b=a.filter(a=>"string"==typeof a&&a.length>0);return b.length>0?b:null}(d);if(null===e)continue;let f=p[a]??a;f!==a&&Object.hasOwn(b,f)||(c[f]=e)}return{...a.defaults,...c}}function r(a){return a.map(a=>{let b=o(a.key);return{key:n(a.key)??a.key,description:a.description,extensionPath:a.extensionPath,...b}})}},8370:(a,b,c)=>{function d(a,b){let c=a.get(b);if(void 0===c)return null;let d=Number.parseInt(c,10);return Number.isFinite(d)&&d>0?d:null}function e(a){let b=[],c=[],e=[],f=new Map,g=null,h=0,i=(a,b,g)=>{if(g)return;f.delete(b.id);let i="100"===b.params.get("f")?"image/png":null,j=b.chunks.join("");0===j.length?e.push({lineIndex:a,reason:"empty"}):null===i?e.push({lineIndex:a,reason:"unsupported-format"}):0!==j.length&&/^[A-Za-z0-9+/]+={0,2}$/.test(j)?b.size>4194304||h+b.size>8388608?e.push({lineIndex:a,reason:"too-large"}):(h+=b.size,c.push({id:b.id,mime:i,base64:j,cols:d(b.params,"c")??1,rows:d(b.params,"r")??1,lineIndex:a})):e.push({lineIndex:a,reason:"unsupported-format"})};for(let c of(a.forEach((a,c)=>{let d="string"==typeof a?function(a){let b=a.indexOf("\x1b_G");if(-1===b)return null;let c="",d=[],e=0;for(;;){if(-1===(b=a.indexOf("\x1b_G",e))){c+=a.slice(e);break}c+=a.slice(e,b);let f=b+3,g=a.indexOf("\x1b\\",f);if(-1===g){c+=a.slice(b);break}let h=a.slice(f,g),i=h.indexOf(";"),j=-1===i?h:h.slice(0,i),k=-1===i?"":h.slice(i+1),l=new Map;for(let a of j.split(",")){let b=a.indexOf("=");-1!==b&&l.set(a.slice(0,b).trim(),a.slice(b+1).trim())}d.push({params:l,payload:k}),e=g+2}return{rest:c,sequences:d}}(a):null;if(!d)return void b.push(a);for(let a of d.sequences){let b,d=a.params.get("a"),e="1"===a.params.get("m");if("d"===d||"p"===d)continue;let h=a.params.get("i");void 0!==h?(b={id:h,params:a.params,chunks:[],size:0},f.set(b.id,b)):g?b=g:(b={id:"image",params:a.params,chunks:[],size:0},f.set(b.id,b)),a.payload.length>0&&(b.chunks.push(a.payload),b.size+=a.payload.length),"number"!=typeof b.lineIndex&&(b.lineIndex=c),g=e?b:null,i(c,b,e)}b.push(d.rest)}),f.values())){let a="number"==typeof c.lineIndex?c.lineIndex:Math.max(0,b.length-1);e.push({lineIndex:a,reason:"incomplete"})}return{lines:b,images:c,fallbacks:e}}function f(a,b){if(!a||a.length!==b.length)return!1;for(let c=0;c<a.length;c+=1){let d=a[c],e=b[c];if(d.id!==e.id||d.mime!==e.mime||d.base64!==e.base64||d.lineIndex!==e.lineIndex||d.rows!==e.rows||d.cols!==e.cols)return!1}return!0}function g(a,b){if(!a||a.length!==b.length)return!1;for(let c=0;c<a.length;c+=1)if(a[c].lineIndex!==b[c].lineIndex||a[c].reason!==b[c].reason)return!1;return!0}function h(a){if(0===a.images.length&&0===a.fallbacks.length)return a.lines;let b=[...a.lines],c=(a,c)=>{let d=b[a];void 0!==d&&(b[a]=""===d?c:`${d} ${c}`)};for(let b of a.images)c(b.lineIndex,`[image: ${b.mime}]`);for(let b of a.fallbacks)c(b.lineIndex,`[image: ${b.reason}]`);return b}c.d(b,{MN:()=>f,N5:()=>h,Rd:()=>g,Rt:()=>e})},10611:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{j1:()=>P});var e=c(716),f=c(29862),g=c(89477),h=c(86697),i=c(75430),j=c(37721),k=c(92783),l=c(51874),m=c(66323),n=c(12559),o=c(69714),p=c(84127),q=c(82356),r=c(68642),s=c(93686),t=c(40673),u=c(99595),v=c(89358),w=c(16601),x=c(31360),y=c(74108),z=c(63480),A=c(33727),B=c(2884),C=c(31119),D=c(11955),E=c(35948),F=c(58732),G=c(19228),H=c(57856),I=c(37607),J=c(26327),K=c(96476),L=c(88876),M=a([f,i,s,x,y,F,G]);[f,i,s,x,y,F,G]=M.then?(await M)():M;let Q=f.KeybindingsManager,R=f.TUI_KEYBINDINGS;(0,K.cK)(i.Theme);let S=function(a=process.cwd()){let b=a;for(let a=0;a<12;a+=1){let a=(0,h.join)(b,"node_modules","@earendil-works","pi-coding-agent"),c=!1;try{c=(0,g.statSync)((0,h.join)(a,"package.json")).isFile()}catch{c=!1}if(c)try{return(void 0)("@earendil-works/pi-tui")}catch{break}let d=(0,h.dirname)(b);if(d===b)break;b=d}return f}();function N(a){return"string"==typeof a&&""!==a?a:null}function O(a){return"string"==typeof a&&a?a:void 0}(0,K.Ph)({getImages:()=>S.getCapabilities().images,setImages:a=>{let b=S.getCapabilities();S.setCapabilities({...b,images:a})}});let T=null;class U{get renderBridgeTheme(){return(0,K.Lm)()}static{this.PARTIAL_RENDER_MIN_INTERVAL_MS=100}static{this.RERENDER_MIN_INTERVAL_MS=100}static{this.RENDER_WIDTH_MIN=40}static{this.RENDER_WIDTH_MAX=240}static{this.RENDER_ROWS_MIN=10}static{this.RENDER_ROWS_MAX=200}constructor(a){this.options=a,this.listeners=[],this.runtime=null,this.markdownChain=null,this.markdownChainRefreshing=null,this.unsubscribeMarkdownInvalidation=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.renderWidth=K.Yg,this.renderRows=H.Tf,this.toolRenderStates=new Map,this.toolRenderScheduler=(0,L.w7)({minIntervalMs:U.RERENDER_MIN_INTERVAL_MS,recompute:a=>this.recomputeToolSlots(a),emit:(a,b)=>this.emitRenderedLinesUpdate(a,b)}),this.streamSnapshot=(0,o.b)(),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,k.$M)(),this.activeToolNames=a.toolNames,this.onDestroy((0,K.Q7)(()=>this.rerenderToolLines())),(0,l.Xn)(this.agentDir)}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}getRenderWidth(){return this.renderWidth}async refreshMarkdownChain(){let a=(0,J.vF)();try{let b=this.options.markdownChainResolver??J.Em,c=await b({cwd:this.realCwd,agentDir:this.agentDir});this.markdownChain={generation:a,chain:c}}catch{this.markdownChain={generation:a,chain:null}}}currentMarkdownChain(){let a=(0,J.vF)();return this.markdownChain&&this.markdownChain.generation===a?this.markdownChain.chain:(this.markdownChainRefreshing||(this.markdownChainRefreshing=this.refreshMarkdownChain().catch(()=>{}).then(()=>{this.markdownChainRefreshing=null})),null)}withTransformedMessage(a){if("message_start"!==a.type&&"message_update"!==a.type&&"message_end"!==a.type)return a;let b=a.message;if(!b)return a;try{let c=this.currentMarkdownChain();if(!c)return a;let d=(0,J.Fz)(b,{chain:c,availableWidth:this.renderWidth,isStreaming:"message_end"!==a.type,useCache:!1});return d===b?a:{...a,message:d}}catch{return a}}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()}}connectionSnapshot(){let a=this.streamSnapshot.snapshot();return this.streamRunSeq>0?{...a,streamRunSeq:this.streamRunSeq}:a}beginExtensionBinding(){}async waitForExtensionsBound(){}emit(a){for(let b of(this.streamSnapshot.remember(a),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,m._2)({limit:50});return(0,m.EE)(b,a)}catch{return!1}}hasActiveExternalWork(){return!!this.hasActiveSubagentRun()||(0,n.Vz)({sessionId:this.realSessionId,sessionFile:this.realSessionFile})}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.hasActiveExternalWork())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,p.readPidancePrefs)(this.agentDir);return!0===(0,p.ql)(a,`sessionQueueHold.${this.realSessionId}`)}setFollowUpHeld(a){try{(0,p.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,p.readPidancePrefs)(this.agentDir),b=(0,p.ql)(a,`sessionQueue.${this.realSessionId}`),c=(0,t.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)>t.ym)return console.error(`[pidance] refusing to persist follow-up queue (${b}): item media exceeds ${t.ym}`),!1;let d=this.followUpQueueRevision+1,e=(0,t.S1)(this.followUpAdmittedAttemptIds,c);try{(0,p.xP)(`sessionQueue.${this.realSessionId}`,(0,t.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,t.Ot)(this.followUpQueue).map(a=>a.path));for(let c of a)"model"!==c.role||b.has(c.path)||(0,s.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:s.Md,c=(0,s.vy)(a.path,this.agentDir);return null!==c&&c<=b}validateQueueMedia(a){if(!a?.length)return!0;if(a.length>t.ym)return!1;let b=0;for(let c of a){let a=(0,s.vy)(c.path,this.agentDir);if(null===a)return!1;let d="model"===c.role?8388608:s.Md;if(a>d||(b+=a,c.previewPath&&null===(0,s.vy)(c.previewPath,this.agentDir)))return!1}return b<=s.Lj}readQueueModelImages(a){let b=[],c=[];for(let d of(0,t.Ot)(a)){if("model"!==d.role)continue;let a=(0,s.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,t.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,t.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,s.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,s.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,s.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,t.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,t.ko)(a.text,"claimed",a.media):(0,t.ko)(a.text,"claimed"));c&&g.push((0,t.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,l="prompt";try{if(this.session.isStreaming)l="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 l="queued",this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-queued"),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:l,...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,D.K2)(b),...this.queueReceiptBase()}}finally{this.dispatchingFollowUpQueue=!1}let m=(0,t.Ot)(g);return this.commitFollowUpQueue(this.followUpQueue.filter(a=>!i.has(a.id)),"dispatch-deliver")&&this.discardDeliveredModelMedia(m),this.emitQueueChanged(),this.resetIdleTimer(),{ok:!0,status:"accepted",action:l,...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,p.readPidancePrefs)(this.agentDir).queueFlushAsOne;this.flushingFollowUp=!0,this.followUpFlushUnits=b?[{ids:a.map(a=>a.id)}]:a.map(a=>({ids:[a.id]})),this.followUpFlushCursor=0;let c=this.followUpFlushUnits[0];setTimeout(()=>{this.flushingFollowUp&&this.followUpFlushUnits[this.followUpFlushCursor]===c&&this.sendNextFollowUp()},0)}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,t.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),l=(0,t.Ot)(c),m=this.commitFollowUpQueue(this.followUpQueue.filter(a=>!k.has(a.id)),"deliver");m&&this.discardDeliveredModelMedia(l),this.emit({type:"follow_up_flushed",sessionId:this.realSessionId,item:e,...this.queueReceiptBase()}),m||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,y.tZ)(a=>{this.trackExtensionSideEffects(a),this.emit(a)},{readComposerText:()=>(0,I.x)(this.realSessionId,this.agentDir),writeComposerDraft:a=>{(0,I.H)(this.realSessionId,a,this.agentDir)},agentDir:this.agentDir}),(0,K.DD)(a=>{this._alive&&this.emit({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"notify",message:a,notifyType:"warning"})}),(0,K.YJ)(()=>{(0,i.renderDiff)("+ added\n- removed\n context\n")}),(0,K.Sw)(),await a.bindExtensions({uiContext:this.extensionUi.uiContext,mode:"tui",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()=>{this.extensionUi?.uiContext.setHiddenThinkingLabel(),this.extensionUi?.uiContext.setFooter(void 0),this.extensionUi?.uiContext.setHeader(void 0),this.extensionUi?.resetSlotFailures(),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=O(a.method);if("setStatus"===b){let b=O(a.statusKey)??O(a.key)??"default",c=O(a.statusText)??O(a.text)??"";c?this.extensionUi?.statuses.set(b,c):this.extensionUi?.statuses.delete(b)}if("setWidget"===b){let b=O(a.widgetKey)??O(a.key)??"default",c=a.widgetLines??a.content,d=(0,j.S)(this.extensionUi?.widgets.get(b),{lines:c,images:a.widgetImages,imageFallbacks:a.widgetImageFallbacks,placement:a.widgetPlacement,interactive:a.widgetInteractive});d?this.extensionUi?.widgets.set(b,d):this.extensionUi?.widgets.delete(b)}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,x.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(E.uG,a);this.emit({type:"message_end",entryId:e,message:(0,E.FH)(a,Date.now())})}(0,x.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&&U.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=U.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,r.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,r.PI)(this.realSessionId),this.options.onSessionListInvalidate?.(),this.realSessionFile&&(0,v.$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.hasActiveExternalWork();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,x.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})}e=this.withTransformedMessage(e),e=this.withToolDisplayMeta(e),this.emit(this.withRenderedToolLines(e))}withToolDisplayMeta(a){if("tool_execution_start"!==a.type)return a;try{let b=this.session.extensionRunner;if("function"!=typeof b?.getToolDefinition)return a;let c="string"==typeof a.toolName?a.toolName:"";if(""===c)return a;let d=b.getToolDefinition(c);if(!d)return a;let e="string"==typeof d.label?d.label.trim():"",f=""!==e&&e!==c?e:void 0,g="self"===d.renderShell?"self":void 0;if(void 0===f&&void 0===g)return a;return{...a,...void 0!==f?{toolLabel:f}:{},...void 0!==g?{toolShell:g}:{}}}catch{return a}}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_start":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=N(a.toolCallId),d=c?this.getOrCreateToolRenderState(c):null;d&&(d.args=a.args,d.callRenderer={slot:"call",def:b});let e=this.buildToolRenderContext(a.toolCallId,a.args,{isPartial:!1,expanded:!0,isError:!1,resultSlot:!1});if(!e)return a;let f=(0,K.GD)(b,a.args,e,b=>this.updateToolRenderLastComponent(a.toolCallId,!1,b),this.renderWidth),g=d?.emittedCallLines??f;return d&&g&&(d.emittedCallLines=g),g?{...a,renderedCallLines:g}:a}case"tool_execution_update":{if(!this.shouldRenderPartialUpdate(a.toolCallId))return a;let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=N(a.toolCallId);if(!c)return a;let d=this.getOrCreateToolRenderState(c);if(!d)return a;void 0!==a.args&&(d.args=a.args),d.resultRenderer={slot:"result",def:b,result:a.partialResult,isPartial:!0,isError:!0===a.isError};let e=this.renderToolSlotsNow(c,d);if(!e||(e.callLines&&this.emitRenderedLinesUpdate(c,{callLines:e.callLines}),!e.resultLines))return a;return this.recordEmittedToolLines(c,{resultLines:e.resultLines}),{...a,renderedLines:e.resultLines}}case"tool_execution_end":{let b=this.getToolRenderDefinition(a.toolName);if(!b)return a;let c=N(a.toolCallId);if(!c)return a;let d=this.getOrCreateToolRenderState(c);if(!d)return a;let e={..."object"==typeof a.result&&null!==a.result?a.result:{content:[]},isError:!0===a.isError};d.resultRenderer={slot:"result",def:b,result:e,isPartial:!1,isError:!0===a.isError};let f=this.renderToolSlotsNow(c,d);if(!f||(f.callLines&&this.emitRenderedLinesUpdate(c,{callLines:f.callLines}),!f.resultLines))return a;return this.recordEmittedToolLines(c,{resultLines:f.resultLines}),{...a,renderedResultLines:f.resultLines}}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,K.Mf)(d,a.message,this.renderBridgeTheme,this.renderWidth);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:()=>{this.scheduleToolRerender(a)},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,args:void 0,callRenderer:void 0,resultRenderer:void 0,emittedCallLines:void 0,emittedResultLines: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)}rerenderToolLines(){this.toolRenderScheduler.flushAll([...this.toolRenderStates.keys()])}scheduleToolRerender(a){let b=N(a);b&&this.toolRenderStates.has(b)&&this.toolRenderScheduler.request(b)}recomputeToolSlots(a){let b=this.toolRenderStates.get(a);return b?this.renderToolSlotsNow(a,b):null}renderToolSlotsNow(a,b){let c=null,d=null,e=b.resultRenderer&&"result"===b.resultRenderer.slot?b.resultRenderer:void 0;if(b.callRenderer){let d=this.buildToolRenderContext(a,b.args,{isPartial:e?.isPartial===!0,expanded:!0,isError:e?.isError===!0,resultSlot:!1});d&&(c=(0,K.GD)(b.callRenderer.def,b.args,d,b=>this.updateToolRenderLastComponent(a,!1,b),this.renderWidth))}let f=b.resultRenderer;if(f&&"result"===f.slot){let e=this.buildToolRenderContext(a,b.args,{isPartial:f.isPartial,expanded:!0,isError:f.isError,resultSlot:!0});if(e&&(d=(0,K.t_)(f.def,f.result,{expanded:!0,isPartial:f.isPartial},e,b=>this.updateToolRenderLastComponent(a,!0,b),this.renderWidth)),b.lastCallComponent){let a=(0,K.hR)(b.lastCallComponent,this.renderWidth);a&&(c=a)}}return(0,L.VQ)({callLines:c,resultLines:d},{callLines:b.emittedCallLines,resultLines:b.emittedResultLines})}recordEmittedToolLines(a,b){let c=this.toolRenderStates.get(a);c&&(b.callLines&&(c.emittedCallLines=b.callLines),b.resultLines&&(c.emittedResultLines=b.resultLines))}emitRenderedLinesUpdate(a,b){this.emit({type:"rendered_lines_update",toolCallId:a,...b.callLines?{renderedCallLines:b.callLines}:{},...b.resultLines?{renderedResultLines:b.resultLines}:{}}),this.recordEmittedToolLines(a,b)}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<U.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;await this.refreshMarkdownChain(),this.unsubscribeMarkdownInvalidation=(0,J.Z_)(()=>{this.refreshMarkdownChain()});let c=(a=this.realSessionFile,b=this.options.cwd,a?(0,x.G1)(a):(0,x.Qu)(b)),d=c.getCwd()||this.options.cwd,e=this.agentDir,f=this.activeToolNames,g=async({cwd:a,agentDir:b,sessionManager:c,sessionStartEvent:d})=>{let e=(0,G._D)({cwd:a,agentDir:b,appendBinary:a=>this.appendBinary(a,c)}),g={name:G.Jv,label:G.wc,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:G.Tv,async execute(a,b,c){let d=await e(b,c);return{content:[{type:"text",text:`Delivered ${d.name} to the user (entry ${d.entryId}).`}],details:d}}},h=await (0,i.createAgentSessionServices)({cwd:a,agentDir:b,resourceLoaderOptions:{appendSystemPromptOverride:G.n3,extensionFactories:[a=>a.registerTool(g)]}});for(let a of h.modelRuntime.getModels())(0,C.yu)(a);return{...await (0,i.createAgentSessionFromServices)({services:h,sessionManager:c,sessionStartEvent:d,tools:f&&f.length>0?f:void 0,noTools:f&&0===f.length?"all":void 0}),services:h,diagnostics:h.diagnostics}};this.runtime=await (0,i.createAgentSessionRuntime)(g,{cwd:d,agentDir:e,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}}tuiDefaultKeybindings(){return T||(T=new Q(R,{}).getResolvedBindings()),T}effectiveKeybindings(){return(0,B.Lh)({defaults:this.tuiDefaultKeybindings(),userBindings:this.readUserKeybindings()})}resolveExtensionShortcutState(){try{let a=this.session.extensionRunner,b=a.getShortcuts({}),c=a.getShortcuts(this.effectiveKeybindings()),d=a.getShortcutDiagnostics().map(a=>({message:a.message,path:a.path})),e=[...c.values()].map(a=>{let b=String(a.shortcut);return(0,B.bq)([{key:b,description:a.description,extensionPath:a.extensionPath}])[0]}),f=new Set(e.map(a=>a.key));for(let a of b.values()){let b=(0,B.tc)(String(a.shortcut))??String(a.shortcut);f.has(b)||(f.add(b),e.push({key:b,description:a.description,extensionPath:a.extensionPath,available:!1,reason:"sdk-conflict"}))}return{entries:e,diagnostics:d}}catch(a){return console.error("[pidance] failed to resolve extension shortcuts:",a),{entries:[],diagnostics:[]}}}readUserKeybindings(){try{let a=(0,h.join)(this.agentDir,"keybindings.json");if(!(0,g.existsSync)(a))return{};let b=JSON.parse((0,g.readFileSync)(a,"utf8"));if("object"!=typeof b||null===b||Array.isArray(b))return{};return b}catch{return{}}}projectState(){let a=this.session,b=this.resolveExtensionShortcutState(),c=a.model,d={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:c?{id:c.id,provider:c.provider,modelId:c.id}:void 0,messageCount:a.messages.length,pendingMessageCount:a.pendingMessageCount,extensionStatuses:Array.from(this.extensionUi?.statuses.entries()??[],([a,b])=>({key:a,text:b})),extensionWidgets:(0,j.o)(this.extensionUi?.widgets.entries()??[]),extensionHeader:this.extensionUi?.headerLines??null,extensionFooter:this.extensionUi?.footerLines??null,extensionEditorComponent:this.extensionUi?.editorTakeoverSnapshot??null,pendingExtensionRequests:Array.from(this.extensionUi?.pendingSnapshot.values()??[]),extensionTerminalInputListenerCount:this.extensionUi?.terminalInputListenerCount??0,extensionShortcuts:b.entries,extensionShortcutDiagnostics:b.diagnostics,extensionAutocompleteProviderCount:this.extensionUi?.autocompleteProviderCount??0,extensionAutocompleteTriggerCharacters:[...this.extensionUi?.autocompleteTriggerCharacters??[]],hiddenThinkingLabel:this.extensionUi?.hiddenThinkingLabel??null,activeCustomUi:this.extensionUi?.customSnapshot??null,extensionCapabilityNotices:this.extensionUi?.capabilityNoticeSnapshot??[]};d.queuedMessages={steering:this.hasQueueSnapshot?[...this.localQueue.steering]:[],followUp:(0,t.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&&(d.contextUsage={contextWindow:b.contextWindow,percent:"number"==typeof b.percent?b.percent:null,tokens:"number"==typeof b.tokens?b.tokens:null})}catch{}return d}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,u.qF)(a):(0,u.l$)(a),c=this.session.sessionManager.appendCustomEntry(u.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,F.Nu)(e?[e]:void 0,this.agentDir)[0];if(!f)throw Error("binaryBlock is required");let g=c.appendCustomEntry(E.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,E.FH)(f,Date.now())})}catch(a){console.error("[pidance] binary message event notification failed:",a)}return{entryId:g,binary:f}}async send(a,b,c){if(!this.runtime)throw Error("SDK session is not alive");let d=a.type;"get_state"!==d&&"ensure_session"!==d&&this.releaseStartupHold(),this.activeCommandCount+=1,this.resetIdleTimer();let e=this.session;try{switch(d){case"prompt":{let c=(0,D.JT)(a),d=this.promptReceipts.get(c.submissionId);if(d)return d;let f=c.submissionId,g=this.promptInFlight.get(f);if(g)return g;let h=(0,F.Nu)(c.binaryBlocks,this.agentDir),i=c.images??a.images,j=this.resolvePromptImages(i);if(j.missing.length){console.error("[pidance] prompt image missing on disk:",j.missing);let a=this.reject(c.submissionId,"media");return this.promptReceipts.set(c.submissionId,a),a}if(this.bashRunning&&!(0,A.D)(c.message)){let a=this.reject(c.submissionId,"bash");return this.promptReceipts.set(c.submissionId,a),a}if(e.isCompacting&&!(0,A.D)(c.message)){let a=this.queueMediaFromPromptImages(i);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,A.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}if((this.promptRunning||e.isStreaming)&&"steer"!==a.streamingBehavior){if(!(0,A.D)(c.message)){let a=this.reject(c.submissionId,"busy");return this.promptReceipts.set(c.submissionId,a),a}try{await e.prompt(c.message,{images:j.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,q.kP)(this.realSessionId))throw Error(q.GT);this.promptRunning=!0,this.lastStopReason=null,(0,r.NK)(this.realSessionId,Date.now()),this.notifyRunning();let k=(async()=>{try{await new Promise((b,d)=>{let g=!1,i=()=>{e.isStreaming||e.isCompacting||this.bashRunning||this.promptRunning&&(this.promptRunning=!1,"aborted"!==this.lastStopReason&&"error"!==this.lastStopReason&&(this.lastStopReason="completed"),(0,r.PI)(this.realSessionId),this.notifyRunning(),this.emit({type:"prompt_done",streamRunSeq:this.streamRunSeq}),this.resetIdleTimer())};e.prompt(c.message,{images:j.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,x.kb)(e.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,d(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,D.K2)(g);if(e.isStreaming&&(0,D.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,r.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 d={submissionId:c.submissionId,sessionId:this.realSessionId,status:"rejected"};throw this.promptReceipts.set(f,d),g}finally{this.promptInFlight.delete(f)}})();return this.promptInFlight.set(f,k),k}case"abort":return this.lastStopReason="aborted",this.setFollowUpHeld(!0),this.promptRunning=!1,this.notifyRunning(),await e.abort(),this.notifyRunning(),null;case"get_state":return this.projectState();case"set_model":{let b=String(a.provider??""),c=String(a.modelId??""),d=(0,z.E)(e.modelRuntime,b,c);if(!d)try{d=(await e.modelRuntime.getAvailable()).find(a=>a.provider===b&&a.id===c)}catch{d=void 0}if(!d)throw Error(`Model not found: ${b}/${c}`);return await e.setModel((0,C.eU)(d)),this.options.onSessionListInvalidate?.(),d}case"set_thinking_level":return e.model&&(0,C.yu)(e.model),e.setThinkingLevel(a.level),this.options.onSessionListInvalidate?.(),null;case"compact":{let b=await e.compact("string"==typeof a.customInstructions?a.customInstructions:void 0);return this.options.onSessionListInvalidate?.(),this.notifyRunning(),this.resetIdleTimer(),b}case"steer":{let b=(0,D._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,D.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,D.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,D.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,D.$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 e.setSessionName(b),this.options.onSessionListInvalidate?.(),null}case"set_auto_compaction":return e.setAutoCompactionEnabled(!!a.enabled),null;case"set_auto_retry":return e.setAutoRetryEnabled(!!a.enabled),null;case"clear_queue":return e.clearQueue();case"get_tools":{let a=e.getAllTools(),b=new Set(e.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 e.setActiveToolsByName(b),this.activeToolNames=b,null}case"completion_suggestions":{let b=Array.isArray(a.lines)?a.lines.filter(a=>"string"==typeof a):[],d=Number(a.cursorLine),e=Number(a.cursorCol);if(!Number.isInteger(d)||!Number.isInteger(e)||0===b.length||d<0||d>=b.length||e<0||e>b[d].length)return{result:{kind:"invalid-request"}};let f=c?.signal??new AbortController().signal;return{result:this.extensionUi?await this.extensionUi.suggestCompletions({lines:b,cursorLine:d,cursorCol:e,force:!0===a.force,signal:f}):{kind:"no-provider"}}}case"completion_apply":{let b=Array.isArray(a.lines)?a.lines.filter(a=>"string"==typeof a):[],c=Number(a.cursorLine),d=Number(a.cursorCol),e=a.item,f="string"==typeof a.prefix?a.prefix:"";if(!Number.isInteger(c)||!Number.isInteger(d)||0===b.length||c<0||c>=b.length||d<0||!e||"string"!=typeof e.value||""===e.value)return{result:null};let g={value:e.value,label:"string"==typeof e.label&&""!==e.label?e.label:e.value,..."string"==typeof e.description&&""!==e.description?{description:e.description}:{}};return{result:this.extensionUi?.applyCompletion({lines:b,cursorLine:c,cursorCol:d,item:g,prefix:f})??null}}case"get_command_argument_completions":{let b="string"==typeof a.name?a.name:"",c="string"==typeof a.prefix?a.prefix:"";if(!b)return{items:[]};let d=e.extensionRunner.getRegisteredCommands().find(a=>a.invocationName===b),f=d?.getArgumentCompletions;if("function"!=typeof f)return{items:[]};try{let a=await f.call(d,c);return{items:function(a){if(!Array.isArray(a))return[];let b=[];for(let c of a){if("object"!=typeof c||null===c||"string"!=typeof c.value||""===c.value)continue;let a="string"==typeof c.label&&""!==c.label?c.label:c.value;b.push({value:c.value,label:a,..."string"==typeof c.description&&""!==c.description?{description:c.description}:{}})}return b}(a)}}catch{return{items:[]}}}case"run_extension_shortcut":{let b=(0,B.tc)(a.key);if(!b)return{ok:!1,error:"invalid-shortcut"};if(!(0,B.GQ)(b).available)return{ok:!1,error:"unavailable-shortcut"};let c=[...e.extensionRunner.getShortcuts(this.effectiveKeybindings()).entries()].find(([a])=>(0,B.tc)(String(a))===b);if(!c)return{ok:!1,error:"unknown-shortcut"};try{return await c[1].handler(e.extensionRunner.createCommandContext()),{ok:!0}}catch(a){return{ok:!1,error:a instanceof Error?a.message:String(a)}}}case"get_commands":{let a=[];for(let b of e.extensionRunner.getRegisteredCommands())a.push({name:b.invocationName,description:b.description,source:"extension",sourceInfo:b.sourceInfo,..."function"==typeof b.getArgumentCompletions?{hasArgumentCompletions:!0}:{}});for(let b of e.promptTemplates)a.push({name:b.name,description:b.description,source:"prompt_template"});try{let b=e.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 e.getSessionStats();case"bash":if(e.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 e.executeBash(String(a.command??""),void 0,{excludeFromContext:!!a.excludeFromContext})}finally{this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),this.resetIdleTimer()}case"abort_bash":return e.abortBash(),this.bashRunning=!1,this.bashCommand=null,this.notifyRunning(),null;case"abort_compaction":return e.abortCompaction(),null;case"extension_ui_response":{let b=O(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=O(a.id),c="string"==typeof a.data?a.data:"";return b&&this.extensionUi?.inputCustom(b,c),null}case"editor_component_input":{let b="string"==typeof a.data?a.data:"";if(!b)return{consumed:!1};return this.extensionUi?.dispatchEditorComponentInput(b,O(a.clientId)??void 0)??{consumed:!1}}case"editor_component_set_text":{let b=O(a.requestId)??"",c="string"==typeof a.text?a.text:"";if(!b)return{applied:!1};return{applied:this.extensionUi?.applyEditorTakeoverText(b,c)??!1}}case"editor_takeover_view":{let b=O(a.requestId)??"",c=O(a.clientId)??"";return b&&c&&this.extensionUi?.recordEditorTakeoverView(b,!0===a.shown,c),null}case"editor_takeover_dismiss":{let b=O(a.requestId)??"";if(!b)return{dismissed:!1};return{dismissed:this.extensionUi?.dismissEditorTakeover(b,O(a.clientId)??void 0)??!1}}case"terminal_input":{let b="string"==typeof a.data?a.data:"";return!0===a.assertFocus&&this.extensionUi?.setEditorFocus(!0,O(a.clientId)??"default"),this.extensionUi?.dispatchTerminalInput(b)??{consumed:!1}}case"editor_focus":{let b=!0===a.focused,c=O(a.clientId)??"default";return{focused:b,changed:this.extensionUi?.setEditorFocus(b,c)??!1}}case"custom_panel_bounds":{let b=O(a.id);return b&&this.extensionUi?.setCustomBounds(b,a.bounds),null}case"extension_ui_mouse":{let b=O(a.id),c=a.event;return b&&c&&"object"==typeof c&&this.extensionUi?.inputCustomMouse(b,c),null}case"extension_ui_widget_mouse":{let b=O(a.key),c=a.event;if(!b||!c||"object"!=typeof c)return!1;return this.extensionUi?.inputWidgetMouse(b,c)??!1}case"set_render_width":{let b="number"==typeof a.width?a.width:NaN;if(!Number.isFinite(b))return null;let c=Math.min(U.RENDER_WIDTH_MAX,Math.max(U.RENDER_WIDTH_MIN,Math.round(b)));if(c===this.renderWidth)return null;return this.renderWidth=c,this.extensionUi?.setRenderSize({width:c,rows:this.renderRows}),this.rerenderToolLines(),null}case"set_render_size":{let b="number"==typeof a.width?a.width:NaN,c="number"==typeof a.rows?a.rows:NaN;if(!Number.isFinite(b)||!Number.isFinite(c))return null;let d=Math.min(U.RENDER_WIDTH_MAX,Math.max(U.RENDER_WIDTH_MIN,Math.round(b))),e=Math.min(U.RENDER_ROWS_MAX,Math.max(U.RENDER_ROWS_MIN,Math.round(c))),f=d!==this.renderWidth;if(!f&&e===this.renderRows)return null;return this.renderWidth=d,this.renderRows=e,this.extensionUi?.setRenderSize({width:d,rows:e}),f&&this.rerenderToolLines(),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=O(a.targetId);if(!b)throw Error("targetId is required");let c=await e.navigateTree(b,{summarize:a.summarize,customInstructions:O(a.customInstructions)});if(!c.cancelled&&this.realSessionFile){e.sessionManager.getLeafId();let a=e.sessionManager.getLeafId(),b=e.sessionManager.getEntries(),c=b.at(-1)?.id;a&&c&&a!==c?(0,v.R3)(this.realSessionFile,a):this.realSessionFile&&(0,v.$9)(this.realSessionFile)}return this.options.onSessionListInvalidate?.(),{cancelled:c.cancelled}}case"select_leaf_exact":{let b=O(a.entryId);if(!b)throw Error("entryId is required");return await this.navigateTreeCommand("select_leaf_exact",b)}case"branch_from_assistant":{let b=O(a.assistantEntryId);if(!b)throw Error("assistantEntryId is required");return await this.navigateTreeCommand("branch_from_assistant",b)}case"create_session_from_leaf":{let b=O(a.entryId);if(!b)throw Error("entryId is required");let c=this.options.navigationActions;if(c)return await c.createSessionFromLeaf(this.sessionId,b,{handoff:()=>this.destroyExcluding(1)});throw Error("create_session_from_leaf is unavailable")}case"set_branch_label":{let b=O(a.targetId);if(!b)throw Error("targetId is required");let c=void 0===a.label||null===a.label?void 0:String(a.label);return e.sessionManager.appendLabelChange(b,c),this.options.onSessionListInvalidate?.(),null}case"reload":return await e.reload(),await this.rebindSession(),null;case"get_last_assistant_text":return{text:e.getLastAssistantText()};case"ensure_session":return null;default:throw Error(`Unsupported command: ${d}`)}}finally{this.activeCommandCount=Math.max(0,this.activeCommandCount-1),0===this.activeCommandCount&&this.resetIdleTimer()}}async navigateTreeCommand(a,b){let c=this.session;if(this.bashRunning)throw Error("select_leaf_exact"===a?"Cannot switch branch while a shell command is running":"Cannot branch while a shell command is running");if(c.isStreaming)throw Error("Wait for the current response to finish before navigating the session tree.");if(c.isCompacting)throw Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");let d=c.sessionManager,e=(0,x.LH)(d),f="select_leaf_exact"===a?(0,w.fb)(e,b):(0,w.AM)(e,b);if("noop"===f.kind)return{cancelled:!1};let g=d.getLeafId();if(f.leafId===g)return f.clearSidecar&&this.realSessionFile&&((0,v.$9)(this.realSessionFile),this.options.onSessionListInvalidate?.()),{cancelled:!1};let h=this.options.navigationActions;if((await this.dispatchTreeNavigation({oldLeafId:g,targetLeafId:f.leafId,apply:async()=>{if(h&&this.realSessionFile){let c="select_leaf_exact"===a?h.selectLeafExact:h.branchFromAssistant;return await c.call(h,this.sessionId,b,{handoff:()=>this.destroyExcluding(1),liveWriter:{sessionManager:e,sessionFile:this.realSessionFile}})}return(0,w.h_)({sessionManager:e,sessionFile:this.realSessionFile,plan:f}),this.options.onSessionListInvalidate?.(),{cancelled:!1}}})).cancelled)return{cancelled:!0};try{await this.destroyExcluding(1)}catch{}return{cancelled:!1}}async dispatchTreeNavigation(a){let b=this.session,c=b.extensionRunner,d=new AbortController;b._branchSummaryAbortController=d;try{if(c.hasHandlers("session_before_tree")){let e=(0,i.collectEntriesForBranchSummary)(b.sessionManager,a.oldLeafId,a.targetLeafId),f=await c.emit({type:"session_before_tree",preparation:{targetId:a.targetLeafId,oldLeafId:a.oldLeafId,commonAncestorId:e.commonAncestorId,entriesToSummarize:e.entries,userWantsSummary:!1},signal:d.signal});if(f?.cancel)return{cancelled:!0}}if((await a.apply()).cancelled)return{cancelled:!0};return await c.emit({type:"session_tree",newLeafId:b.sessionManager.getLeafId(),oldLeafId:a.oldLeafId}),{cancelled:!1}}finally{b._branchSummaryAbortController=void 0}}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("Session writer is busy: a command is still in flight");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.unsubscribeMarkdownInvalidation?.(),this.unsubscribeMarkdownInvalidation=null,this.toolRenderScheduler.dispose(),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,r.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 P(a){let b=new U(a);return await b.start(),b}d()}catch(a){d(a)}})},11955:(a,b,c)=>{c.d(b,{$3:()=>o,JT:()=>k,K2:()=>g,QT:()=>p,TJ:()=>r,_3:()=>n,in:()=>f,s:()=>q});var d=c(35948),e=c(40673);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)}}},12559:(a,b,c)=>{c.d(b,{Vz:()=>e});let d=Symbol.for("@agegr/pi-web/session-liveness/v1");function e(a){let b=function(){let a=globalThis[d];if(a)return a;let b={providers:new Map,warned:new Set};return globalThis[d]=b,b}(),c=new Set([a.sessionId,a.sessionFile].filter(a=>!!a));if(0===c.size)return!1;for(let[a,d]of b.providers)if(c.has(d.sessionId)||void 0!==d.sessionFile&&c.has(d.sessionFile))try{if(!0===d.isActive())return!0}catch(c){b.warned.has(a)||(b.warned.add(a),console.warn(`[pidance] session liveness provider 抛错,按不活跃处理: ${d.name}`,c))}return!1}},16601:(a,b,c)=>{c.d(b,{h_:()=>g,AM:()=>f,fb:()=>e});var d=c(89358);function e(a,b){if(b===a.getLeafId())return{kind:"noop"};if(b===a.getLastEntryId())return{kind:"branch",leafId:b,clearSidecar:!0};if(!a.getEntry(b))throw Error(`Entry ${b} not found`);return{kind:"branch",leafId:b,clearSidecar:!1}}function f(a,b){let c=a.getLeafId();if(!c)throw Error("Session has no leaf");let d=a.getEntry(b);if(!d)throw Error("Entry not found");if("message"!==d.type||d.message?.role!=="assistant")throw Error("Only assistant messages can be branched from");let e=function(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}(a.getBranch(c),b);return{kind:"branch",leafId:e,clearSidecar:e===a.getLastEntryId()}}function g(a){let{sessionManager:b,sessionFile:c,plan:e}=a;"noop"!==e.kind&&(c&&(e.clearSidecar?(0,d.$9)(c):(0,d.R3)(c,e.leafId)),b.branch(e.leafId))}},17992:(a,b,c)=>{function d(a){if(null==a)return{kind:"none"};if("object"!=typeof a||!Array.isArray(a.items))return{kind:"invalid"};let b="string"==typeof a.prefix?a.prefix:"",c=function(a){if(!Array.isArray(a))return[];let b=[];for(let c of a){if("object"!=typeof c||null===c||"string"!=typeof c.value||""===c.value)continue;let a="string"==typeof c.label&&""!==c.label?c.label:c.value;b.push({value:c.value,label:a,..."string"==typeof c.description&&""!==c.description?{description:c.description}:{}})}return b}(a.items);return 0===c.length?0===a.items.length?{kind:"empty"}:{kind:"invalid"}:{kind:"items",items:c,prefix:b}}function e(a){if("object"!=typeof a||null===a||!Array.isArray(a.lines)||!a.lines.every(a=>"string"==typeof a)||"number"!=typeof a.cursorLine||"number"!=typeof a.cursorCol||!Number.isFinite(a.cursorLine)||!Number.isFinite(a.cursorCol))return null;let b=Math.trunc(a.cursorLine);if(b<0||b>=a.lines.length)return null;let c=a.lines[b];return a.cursorCol<0||a.cursorCol>c.length?null:{lines:a.lines,cursorLine:b,cursorCol:Math.trunc(a.cursorCol)}}function f(a){let b={getSuggestions:()=>Promise.resolve(null),applyCompletion(a,b,c,d,e){let f=a[b]??"",g=Math.max(0,c-("string"==typeof e?e.length:0)),h=f.slice(0,g)+d.value+f.slice(c);return{lines:[...a.slice(0,b),h,...a.slice(b+1)],cursorLine:b,cursorCol:g+d.value.length}},shouldTriggerFileCompletion:()=>!0},c=[],d=0;for(let e of a){let a;try{a=e(b)}catch{d+=1;continue}if("object"!=typeof a||null===a){d+=1;continue}for(let d of(b=a).triggerCharacters??[])"string"==typeof d&&""!==d&&c.push(d)}return c.length>0&&(b.triggerCharacters=[...new Set(c)]),{provider:b,triggerCharacters:[...new Set(c)],skipped:d}}c.d(b,{Q:()=>f,ad:()=>d,xh:()=>e})},19228:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{Jv:()=>r,Tv:()=>u,_D:()=>q,n3:()=>n,wc:()=>s});var e=c(89477),f=c(42524),g=c(86697),h=c(26238),i=c(93686),j=c(87390),k=c(69271),l=c(58732),m=a([i,j,l]);[i,j,l]=m.then?(await m)():m;let r="send_file_to_user",s="Send file to user",t="## 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===t)?a:[...a,t]}let u={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)}})},26327:(a,b,c)=>{c.d(b,{vF:()=>l,Z_:()=>n,Em:()=>o,Fz:()=>r});var d=c(86697);function e(a){return"object"!=typeof a||null===a||Array.isArray(a)?null:a}async function f(a){let b=(0,d.resolve)(a.cwd),f=`${b}\0${a.agentDir?(0,d.resolve)(a.agentDir):""}`,g=(globalThis.__piPidanceLoadedExtensionsCache||(globalThis.__piPidanceLoadedExtensionsCache={entries:new Map,inFlight:new Map,generation:0}),globalThis.__piPidanceLoadedExtensionsCache);if(!a.bypassCache){let a=g.entries.get(f);if(a&&a.expiresAt>Date.now())return a.value;a&&g.entries.delete(f);let b=g.inFlight.get(f);if(b)return b}let h=(a.loaderFactory??function(a,b){return async()=>{let d=await Promise.resolve().then(c.bind(c,75430));if(!d.DefaultResourceLoader)throw Error("DefaultResourceLoader is not available");let f=new d.DefaultResourceLoader(b?{cwd:a,agentDir:b}:{cwd:a});await f.reload();let g=f.getExtensions(),h=Array.isArray(g?.extensions)?g.extensions.filter(a=>null!==e(a)):[],i=Array.isArray(g?.errors)?g.errors:[];return{extensions:h,runtime:e(g?.runtime)??{},errors:i}}})(b,a.agentDir),i=g.generation,j=Promise.resolve().then(h).then(a=>({ok:!0,value:a})).catch(a=>({ok:!1,error:a instanceof Error?a.message:String(a)})).then(b=>(a.bypassCache||g.generation!==i||g.entries.set(f,{value:b,expiresAt:Date.now()+3e4}),b)).finally(()=>{g.inFlight.get(f)===j&&g.inFlight.delete(f)});return a.bypassCache||g.inFlight.set(f,j),j}function g(a){return"object"!=typeof a||null===a||Array.isArray(a)?null:a}function h(a,b,c){let d=a;for(let a of c)try{let c=a(d,b);"string"==typeof c&&(d=c)}catch{}return d}let i=new WeakMap,j=0;function k(){return globalThis.__piPidanceMarkdownTransformerCache||(globalThis.__piPidanceMarkdownTransformerCache={entries:new Map,inFlight:new Map,generation:0}),globalThis.__piPidanceMarkdownTransformerCache}function l(){return k().generation}let m=new Set;function n(a){return m.add(a),()=>{m.delete(a)}}async function o(a){let b=`${a.cwd}\0${a.agentDir??""}`,c=k();if(!a.bypassCache){let a=c.entries.get(b);if(a&&a.expiresAt>Date.now())return a.chain;a&&c.entries.delete(b);let d=c.inFlight.get(b);if(d)return d}let d=c.generation,e=Promise.resolve().then(()=>f({cwd:a.cwd,agentDir:a.agentDir,loaderFactory:a.loaderFactory,bypassCache:a.bypassCache})).then(a=>{var b;return a.ok?0===(b=function(a){let b=[];for(let c of a){let a=g(c)?.markdownTransformer;"function"==typeof a&&b.push(a)}return b}(a.value.extensions)).length?null:{transformers:b,fingerprint:b.map(a=>{let b;return void 0!==(b=i.get(a))?b:(j+=1,i.set(a,j),j)}).join(".")}:null}).catch(()=>null).then(e=>(a.bypassCache||c.generation!==d||c.entries.set(b,{chain:e,expiresAt:Date.now()+3e4}),e)).finally(()=>{c.inFlight.get(b)===e&&c.inFlight.delete(b)});return a.bypassCache||c.inFlight.set(b,e),e}function p(a){let{chain:b,messageId:c,markdown:d,context:e}=a;if(!1===a.useCache)return h(d,e,b.transformers);let f=[b.fingerprint,c,function(a){let b=0x811c9dc5;for(let c=0;c<a.length;c+=1)b^=a.charCodeAt(c),b=Math.imul(b,0x1000193)>>>0;return b.toString(16)}(d),e.availableWidth,e.isStreaming?"1":"0",e.messageType].join("\0"),g=(globalThis.__piPidanceMarkdownTransformMemo||(globalThis.__piPidanceMarkdownTransformMemo=new Map),globalThis.__piPidanceMarkdownTransformMemo),i=g.get(f);if(void 0!==i)return i;let j=h(d,e,b.transformers);return g.size>=2e3&&g.clear(),g.set(f,j),j}function q(a,b,c){let d=g(a);if(!d)return{block:a,changed:!1};if("text"===d.type&&"string"==typeof d.text){if(""===d.text.trim())return{block:a,changed:!1};let e=p({chain:c.chain,messageId:c.messageId,markdown:d.text,context:b,useCache:c.useCache});return e===d.text?{block:a,changed:!1}:{block:{...d,text:e},changed:!0}}if("thinking"===d.type&&"string"==typeof d.thinking&&""!==d.thinking){let e=p({chain:c.chain,messageId:c.messageId,markdown:d.thinking,context:b,useCache:c.useCache});return e===d.thinking?{block:a,changed:!1}:{block:{...d,thinking:e},changed:!0}}return{block:a,changed:!1}}function r(a,b){let c=g(a),d=c?.role,e=b.messageId??"#stream",f=!1!==b.useCache;if("user"===d){let d={messageType:"user",isStreaming:!1,availableWidth:b.availableWidth},g=c?.content;if("string"==typeof g){let c=p({chain:b.chain,messageId:e,markdown:g,context:d,useCache:f});return c===g?a:{...a,content:c}}if(Array.isArray(g)){let c=!1,h=g.map(a=>{let g=q(a,d,{chain:b.chain,messageId:e,useCache:f});return g.changed&&(c=!0),g.block});return c?{...a,content:h}:a}return a}if("assistant"===d&&Array.isArray(c?.content)){let d=!1,h=c.content.map(a=>{let c=g(a),h=q(a,{messageType:c?.type==="thinking"?"assistant-thinking":"assistant",isStreaming:b.isStreaming,availableWidth:b.availableWidth},{chain:b.chain,messageId:e,useCache:f});return h.changed&&(d=!0),h.block});return d?{...a,content:h}:a}return a}},29102:(a,b,c)=>{c.d(b,{mD:()=>f,tV:()=>d,v7:()=>g});let d="unreadSessionState";function e(a){if(null===a||"object"!=typeof a||Array.isArray(a))return{};let b={};for(let[d,e]of Object.entries(a)){var c;d&&"string"==typeof(c=e)&&c.length>0&&(b[d]=e)}return b}function f(a,b=new Date().toISOString()){if(Array.isArray(a)){let c={};for(let d of a)"string"==typeof d&&d&&(c[d]=b);return{completedAt:c,readAt:{}}}return null===a||"object"!=typeof a?{completedAt:{},readAt:{}}:{completedAt:e(a.completedAt),readAt:e(a.readAt)}}function g(a,b){let c=!1,d={},e={};for(let[e,f]of Object.entries(a.completedAt)){if(!b.has(e)){c=!0;continue}d[e]=f}for(let[d,f]of Object.entries(a.readAt)){if(!b.has(d)){c=!0;continue}e[d]=f}return c?{completedAt:d,readAt:e}:a}},31119:(a,b,c)=>{function d(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 e(a){let b=d(a);if(b===a)return a;try{return a.thinkingLevelMap=b.thinkingLevelMap,a}catch{return b}}c.d(b,{eU:()=>d,yu:()=>e})},33727:(a,b,c)=>{c.d(b,{D:()=>d});function d(a){return a.trim().startsWith("/")}},33908:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{sweepStaleUnreadEntries:()=>j});var e=c(69453),f=c(84127),g=c(29102),h=a([e]);e=(h.then?(await h)():h)[0];let k=0,l=!1;function i(a){return a?Date.parse(a):NaN}async function j(a={}){let b=a.now??Date.now(),c=a.minIntervalMs??6e5;if(l||b-k<c)return{swept:[],skipped:!0};k=b,l=!0;try{let c=(0,g.mD)((0,f.readPidancePrefs)(a.agentDir)[g.tV]),d=new Set([...Object.keys(c.completedAt),...Object.keys(c.readAt)]);if(0===d.size)return{swept:[],skipped:!1};let h=await (a.listSessions??e.dQ)();if(0===h.length)return{swept:[],skipped:!0};let j=function(a){let b=new Set;for(let c of a)c.id&&!c.subagent&&b.add(c.id);return b}(h),k=b-(a.minAgeMs??3e5),l=[...d].filter(a=>!j.has(a));if(0===l.length)return{swept:[],skipped:!1};let m=[];return(0,f.ln)(b=>{let c=(0,g.mD)(b[g.tV]),d=new Set([...Object.keys(c.completedAt),...Object.keys(c.readAt)]),e=[];for(let b of l){if(e.length>=(a.maxEntries??200))break;if(!d.has(b))continue;let f=function(a,b){let c=i(a.completedAt[b]),d=i(a.readAt[b]);return Number.isNaN(c)?d:Number.isNaN(d)?c:Math.max(c,d)}(c,b);(Number.isNaN(f)||!(f>k))&&(d.delete(b),e.push(b))}if(0===e.length)return!1;let f=(0,g.v7)(c,d);return f!==c&&(b[g.tV]=f,m.push(...e),!0)},a.agentDir),{swept:m,skipped:!1}}finally{l=!1}}d()}catch(a){d(a)}})},35304:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{getRegistry:()=>o,recoverFollowUpQueues:()=>t});var e=c(69453),f=c(73579),g=c(33908),h=c(31360),i=c(84127),j=c(40673),k=c(10611),l=c(68642),m=c(82356),n=a([e,g,h,k]);function o(){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 p(){return globalThis.__piStartLocks||(globalThis.__piStartLocks=new Map),globalThis.__piStartLocks}function q(){let a=new Set((0,l.MG)().keys());for(let[b,c]of o())c.isRunning()&&a.add(c.sessionId||b);return[...a]}[e,g,h,k]=n.then?(await n)():n;let v="",w=[],x=new Set,y=null;function r(){!function a(){let b=new Set(function(){let a=new Set([...p().keys()]);for(let[b,c]of o())c.isAlive()&&a.add(c.sessionId||b);return[...a]}());for(let a of b)(0,m.AZ)(a),x.add(a);for(let a of[...x])b.has(a)||((0,m.Hl)(a),x.delete(a));if(0===b.size){y&&(clearInterval(y),y=null);return}y||(y=setInterval(()=>{a()},8e3),y.unref?.())}();let a=q(),b=function(){let a=[];for(let[b,c]of o()){let d=c.listPendingExtensionRequests();0!==d.length&&a.push({sessionId:c.sessionId||b,requests:d})}return a}(),c=q(),d=JSON.stringify({ids:[...a].sort(),pending:b.map(a=>({sessionId:a.sessionId,ids:a.requests.map(a=>a.id??null)}))});if(d===v)return;v=d;let e=w.filter(a=>!c.includes(a)&&!(0,f.f)(a));if(w=[...c],e.length>0){let a=new Date().toISOString();setTimeout(()=>{for(let b of e)try{(0,i.xP)(`unreadSessionState.completedAt.${b}`,a)}catch(a){console.error("[pidance] failed to record unread completedAt:",a)}(0,g.sweepStaleUnreadEntries)().then(a=>{a.swept.length>0&&console.log(`[pidance] 已回收 ${a.swept.length} 条不会再显示的未读条目`)}).catch(()=>void 0)},0)}for(let b of(globalThis.__piRunningListeners||(globalThis.__piRunningListeners=new Set),globalThis.__piRunningListeners))try{b(a)}catch{}}async function s(a,b,c,d,e){return u(a,b,c,d,e)}async function t(){let a=(0,i.readPidancePrefs)();for(let b of function(a){let b=new Set,c=a.sessionQueue;if("object"==typeof c&&null!==c&&!Array.isArray(c))for(let[a,d]of Object.entries(c))a&&(0,j.aL)(d)&&b.add(a);for(let[c,d]of Object.entries(a)){if(!c.startsWith("sessionQueue.")||!(0,j.aL)(d))continue;let a=c.slice(13);a&&b.add(a)}return[...b].filter(b=>!0!==(0,i.ql)(a,`sessionQueueHold.${b}`)&&!0!==a[`sessionQueueHold.${b}`]).sort()}(a)){let a=o().get(b);if(a?.isAlive()||(0,m.wy)(b))continue;let c=await (0,e.os)(b);if(!c)continue;let d=process.cwd();try{d=(0,h.kW)(c).getHeader()?.cwd||process.cwd()}catch{}try{await s(b,c,d)}catch(a){console.error(`[pidance] recover follow-up queue failed for ${b}:`,a)}}}async function u(a,b,c,d,f){let g=o(),h=p(),i=g.get(a);if(i?.isAlive())return{session:i,realSessionId:a};let j=h.get(a);if(j)return j;if(!(0,m.kP)(a))throw Error(m.GT);r();let l=(async()=>{try{let h=await (0,k.j1)({sessionId:a,sessionFile:b,cwd:c,toolNames:d,navigationActions:f,onRunningChange:()=>r(),onSessionListInvalidate:()=>(0,e.mD)(),cacheSessionPath:(a,b)=>(0,e.O8)(a,b),onSessionRekeyed:(a,b,c)=>{let d;d=o(),a!==b&&d.delete(a),d.set(b,c),a!==b&&((0,m.kP)(b),(0,m.Hl)(a))}}),i=h.sessionId,j=h.sessionFile;return j&&(0,e.O8)(i,j),i!==a&&(0,m.kP)(i),h.onDestroy(()=>{g.get(i)===h&&g.delete(i),a!==i&&g.get(a)===h&&g.delete(a),(0,m.Hl)(i),a!==i&&(0,m.Hl)(a),r()}),g.set(i,h),h.beginExtensionBinding(),{session:h,realSessionId:i}}catch(b){throw(0,m.Hl)(a),r(),b}})().finally(()=>{h.delete(a),r()});return h.set(a,l),l}d()}catch(a){d(a)}})},35948:(a,b,c)=>{c.d(b,{FH:()=>g,Ln:()=>f,PB:()=>h,uG:()=>d});let d="pidance.binary",e=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;function f(a){if("string"!=typeof a)return null;let b=a.trim().toLowerCase();return e.test(b)?b:null}function g(a,b){let c={role:"custom",customType:d,content:a.name,display:!0,details:a};return void 0!==b&&(c.timestamp=b),c}function h(a,b){let c,d=f(a.mimeType)??"application/octet-stream",e=function(a){if("string"!=typeof a)return null;let b=a.replace(/[\\/\0]/g,"_").trim();return!b||b.length>180?null:b}(a.name)??"file",g=a.path.trim(),h=Number.isSafeInteger(a.size)&&a.size>=0?a.size:0,i=a.previewPath?.trim()||void 0;return{type:"binary",version:1,kind:(c=d.toLowerCase()).startsWith("image/")?"image":c.startsWith("audio/")?"audio":c.startsWith("video/")?"video":"file",path:g,name:e,mimeType:d,size:h,...i?{previewPath:i}:{},...b?{messageEntryId:b}:{}}}},37607:(a,b,c)=>{c.d(b,{H:()=>g,x:()=>f});var d=c(89477),e=c(84127);function f(a,b){if(!a)return"";try{let c=(0,d.statSync)((0,e.m6)(b),{throwIfNoEntry:!1});if(!c||c.size>4194304)return"";return function(a,b){let c=a.drafts;if("object"!=typeof c||null===c||Array.isArray(c))return"";let d=c[b];if("object"!=typeof d||null===d||Array.isArray(d))return"";let e=d.value;return"string"==typeof e?e:""}((0,e.readPidancePrefs)(b),a)}catch(a){return console.error("[pidance] readComposerDraftText failed:",a),""}}function g(a,b,c){let d="string"==typeof b?b.trim():"";if(!a||!d)return!1;try{let b=(0,e.readPidancePrefs)(c),f=("object"!=typeof b.drafts||null===b.drafts||Array.isArray(b.drafts)?{}:b.drafts)[a],g="object"!=typeof f||null===f||Array.isArray(f)?{}:f,h="string"==typeof g.value?g.value:"";if(h.trim()===d)return!1;let i=Array.isArray(g.images)?g.images:[];return(0,e.xP)(`drafts.${a}`,{...g,value:[d,h].filter(a=>a.trim()).join("\n\n"),images:i,updatedAt:Date.now()},c),!0}catch(a){return console.error("[pidance] prependComposerDraftText failed:",a),!1}}},37721:(a,b,c)=>{function d(a,b){if(null==b.lines)return null;let c=a&&"object"==typeof a?a:{};return{lines:b.lines,images:void 0===b.images?c.images:b.images,imageFallbacks:void 0===b.imageFallbacks?c.imageFallbacks:b.imageFallbacks,placement:b.placement,interactive:!0===b.interactive}}function e(a){let b=[];for(let[c,d]of a){let a=d&&"object"==typeof d?d:null;b.push({key:c,lines:Array.isArray(a?.lines)?a.lines:[],images:Array.isArray(a?.images)?a.images:[],imageFallbacks:Array.isArray(a?.imageFallbacks)?a.imageFallbacks:[],placement:a?.placement==="belowEditor"?"belowEditor":"aboveEditor",interactive:a?.interactive===!0})}return b}c.d(b,{S:()=>d,o:()=>e})},40673:(a,b,c)=>{function d(a){if("string"!=typeof a)return null;let b=a.trim();return/^[A-Za-z0-9_-]{1,64}$/.test(b)?b:null}function e(a){return d(a)}function f(a){if(!Array.isArray(a))return[];let b=[];for(let c of a){let a=d(c);a&&!b.includes(a)&&b.push(a)}return b.length>128?b.slice(b.length-128):b}function g(a,b){let c=[...a];for(let a of b)!a||c.includes(a)||c.push(a);return c.length>128?c.slice(c.length-128):c}c.d(b,{EP:()=>l,Kk:()=>d,Ot:()=>q,Pt:()=>o,S1:()=>g,X_:()=>p,aL:()=>m,gC:()=>n,jG:()=>k,ko:()=>i,mv:()=>e,ym:()=>h});let h=32;function i(a,b="waiting",c){let d,e={id:(d=globalThis.crypto)&&"function"==typeof d.randomUUID?d.randomUUID():`q-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`,text:a,state:b};return c?.length&&(e.media=[...c]),e}function j(a,b){let c=0x811c9dc5;for(let a=0;a<b.length;a++)c^=b.charCodeAt(a),c=0x1000193*c>>>0;return`legacy-${a}-${c.toString(36)}`}function k(a){let b=Array.isArray(a)?a:a&&"object"==typeof a?a.items:void 0,c=a&&"object"==typeof a&&!Array.isArray(a)&&"number"==typeof a.revision&&Number.isFinite(a.revision)?a.revision:0,d=f(a&&"object"==typeof a&&!Array.isArray(a)?a.admittedAttemptIds:void 0);if(!Array.isArray(b))return{items:[],revision:c,admittedAttemptIds:d};let e=[];for(let a=0;a<b.length;a++){let c=function(a,b){var c;if("string"==typeof a){let c=a.trim();return c?{id:j(b,a),text:c,state:"waiting"}:null}if(!a||"object"!=typeof a||Array.isArray(a)||"string"!=typeof a.text)return null;let d=function(a){if(void 0===a)return[];if(!Array.isArray(a)||a.length>h)return null;let b=[];for(let c of a){if(!c||"object"!=typeof c||Array.isArray(c))return null;let a="model"===c.role||"original"===c.role?c.role:null,d="string"==typeof c.path?c.path.trim():"",e="string"==typeof c.mimeType?c.mimeType.trim():"",f="string"==typeof c.name?c.name.trim():"",g=c.size,h="string"==typeof c.previewPath?c.previewPath.trim():void 0;if(!a||!d||!e||!f||"number"!=typeof g||!Number.isSafeInteger(g)||g<0||void 0!==c.previewPath&&!h)return null;b.push({role:a,path:d,name:f,mimeType:e,size:g,...h&&h!==d?{previewPath:h}:{}})}return b}(a.media);return null!==d&&(a.text.trim()||0!==d.length)?{id:"string"==typeof a.id&&a.id.trim()?a.id:j(b,a.text),text:a.text,state:"claimed"===(c=a.state)||"unknown"===c?c:"waiting",...d.length?{media:d}:{}}:null}(b[a],a);c&&e.push(c)}return{items:e,revision:c,admittedAttemptIds:d}}function l(a){let b=f(a.admittedAttemptIds);return{items:a.items.map(a=>({id:a.id,text:a.text,state:a.state,...a.media?.length?{media:a.media.map(a=>({...a}))}:{}})),revision:a.revision,...b.length?{admittedAttemptIds:b}:{}}}function m(a){return k(a).items.length>0}function n(a){return a.map(a=>a.text)}function o(a,b,c){let d=new Set(c?.inFlightIds??[]),e=Array(a.length).fill(!1),f=new Map;a.forEach((a,b)=>{f.has(a.id)||f.set(a.id,b)});let g=[];for(let c of b){if(void 0!==c.id&&d.has(c.id))continue;let b=void 0===c.id?void 0:f.get(c.id);if(void 0!==b&&!e[b]){e[b]=!0;let d=a[b],f=c.media?.length?c.media:d.media;g.push({id:d.id,text:c.text,state:d.state,...f?.length?{media:[...f]}:{}});continue}let h=-1;for(let b=0;b<a.length;b++){let d=a[b];if(!e[b]&&d.text===c.text){if(function(a,b){let c=a??[],d=b??[];return c.length===d.length&&c.every((a,b)=>a.path===d[b].path)}(d.media,c.media)){h=b;break}h<0&&(h=b)}}if(h>=0){e[h]=!0;let b=a[h],d=c.media?.length?c.media:b.media;g.push({id:b.id,text:c.text,state:b.state,...d?.length?{media:[...d]}:{}});continue}g.push(c.media?.length?i(c.text,"waiting",c.media):i(c.text,"waiting"))}return g}function p(a,b){return{text:[...n(a),...b?.trim()?[b.trim()]:[]].map(a=>a.trim()).filter(a=>a.length>0).join("\n"),media:q(a)}}function q(a){return a.flatMap(a=>a.media??[])}},40678:(a,b,c)=>{c.d(b,{Z:()=>d});function d(a){return`\x1b[200~${a}\x1b[201~`}},51874:(a,b,c)=>{c.d(b,{Xn:()=>h});var d=c(84127),e=c(92783),f=c(75248);let g=!1;function h(a=(0,e.$M)()){if(!g){g=!0;try{!function(a=(0,d.readPidancePrefs)(),b=(0,e.$M)()){let c=function(a){let b=(0,d.ql)(a,"theme");if(!b||"object"!=typeof b)return null;let c=b.mode;return"dark"===c||"light"===c?c:null}(a);if(!c||(0,f.QV)()?.name===c)return;let g=(0,f.tA)(c,b);g.success||console.warn(`[pidance] could not align pi theme with shell preference: ${g.error}`)}((0,d.readPidancePrefs)(a),a)}catch(a){console.error("[pidance] failed to align pi theme with shell preference:",a)}}}},54639:(a,b,c)=>{c.d(b,{HM:()=>e,wz:()=>f});var d=c(69420);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)}},57856:(a,b,c)=>{c.d(b,{TQ:()=>e,Tf:()=>d});let d=40;function e(a,b=92,c=d,f={}){let g="function"==typeof b?b:()=>b,h="function"==typeof c?c:()=>c,i=Object.freeze({render:()=>[],invalidate:()=>{},handleInput:()=>{},getText:()=>"",setText:()=>{}}),j=f.isEditorFocused,k=!1,l={terminal:Object.freeze({get columns(){return g()},get rows(){return h()},kittyProtocolActive:!1}),requestRender:a,stop(){k||(k=!0,f.onUnsupported?.("tui.stop()/start() (external editor handover)"))},start(){}};return Object.defineProperty(l,"focusedComponent",{enumerable:!0,get:()=>j?.()===!0?i:void 0}),Object.freeze(l)}},58732:(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(92783),h=c(93686),i=c(35948),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)}})},63480:(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)}},66323:(a,b,c)=>{c.d(b,{EE:()=>r,_2:()=>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={}){var b,c;let d,e,f,h,n=a.fs??o,q=a.limit??20,r=a.now?.()??Date.now(),C=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(C);if(a.isSymbolicLink()||!a.isDirectory())return t(r,!1);e=n.realpathSync(C)}catch(a){return u(a),t(r,!1)}try{f=n.readdirSync(C)}catch(a){return u(a),t(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(!v(h,c))return null;let p=function(a,b,c){let d=w(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=z(p.startedAt);if(void 0===s)return null;let t="string"==typeof p.runId&&p.runId.trim()?p.runId.trim():d,u=y(p.activityState),C=z(p.endedAt),D=z(p.lastUpdate),E="string"==typeof p.cwd?p.cwd:void 0,F="string"==typeof p.error?p.error:void 0,G=z(p.currentStep),H=z(p.chainStepCount),I=A(p.totalTokens),J=B(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=y(d.activityState);g&&(f.activityState=g),"string"==typeof d.currentTool&&(f.currentTool=d.currentTool);let h=A(d.tokens);h&&(f.tokens=h);let i=B(d.totalCost)??z(d.costUsd);void 0!==i&&(f.costUsd=i);let j=z(d.startedAt);void 0!==j&&(f.startedAt=j);let k=z(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=x(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=z(b.timestamp)??z(b.ts)??z(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=x(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!==C&&(N.endedAt=C),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,C,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 t(a,b){return{runs:[],generatedAt:a,rootAvailable:b}}function u(a){return"object"==typeof a&&null!==a&&"code"in a&&"ENOENT"===a.code}function v(a,b){let c=i().resolve(a),d=b.endsWith(i().sep)?b:b+i().sep;return c===b||c.startsWith(d)}function w(a,b,c){try{let d=a.lstatSync(b);if(d.isSymbolicLink()||!d.isFile())return null;let e=a.realpathSync(b);if(!v(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 x(a,b,c,d){let e=w(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 y(a){return"string"==typeof a&&n.has(a)?a:void 0}function z(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}function A(a){if(!a||"object"!=typeof a||Array.isArray(a))return;let b=z(a.input),c=z(a.output),d=z(a.total);if(void 0!==b&&void 0!==c&&void 0!==d)return{input:b,output:c,total:d}}function B(a){return"number"==typeof a&&Number.isFinite(a)?a:!a||"object"!=typeof a||Array.isArray(a)?void 0:z(a.costUsd)}},68642:(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()}},69271:(a,b,c)=>{c.d(b,{GO:()=>h,X:()=>j,cV:()=>i,k2:()=>k,oC:()=>l});let d={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"},e={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"},f={mp4:"video/mp4",m4v:"video/mp4",webm:"video/webm",ogv:"video/ogg",mov:"video/quicktime",mkv:"video/x-matroska",avi:"video/x-msvideo"},g={pdf:"application/pdf",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function h(a){return(a.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function i(a){return d[h(a)]??null}function j(a){return e[h(a)]??null}function k(a){return f[h(a)]??null}function l(a){return g[h(a)]??null}},69420:(a,b,c)=>{c.d(b,{Nw:()=>d});function d(a){return a.replace(/\\/g,"/")}},69714:(a,b,c)=>{function d(a){let b=a.toolCallId;return"string"==typeof b&&""!==b?b:null}function e(a){return Array.isArray(a)&&0!==a.length&&a.every(a=>"string"==typeof a)?a:null}function f(){let a=null,b=new Map;return{remember(c){switch(c.type){case"agent_start":case"agent_end":case"prompt_done":case"agent_settled":a=null,b.clear();return;case"message_start":case"message_update":{let b=c.message;if(!b||"user"===b.role)return;a=c;return}case"message_end":a=null;return;case"tool_execution_start":{let a=d(c);if(!a)return;b.set(a,{start:c,update:null,renderedUpdate:null,callLines:null,resultLines:null});return}case"tool_execution_update":{let a=d(c);if(!a)return;let f=b.get(a);if(!f)return;f.update=c,null!==e(c.renderedLines)&&(f.renderedUpdate=c);return}case"rendered_lines_update":{let a=d(c);if(!a)return;let f=b.get(a);if(!f)return;let g=e(c.renderedCallLines);g&&(f.callLines=g);let h=e(c.renderedResultLines);h&&(f.resultLines=h);return}case"tool_execution_end":{let a=d(c);if(!a)return;b.delete(a);return}default:return}},snapshot(){let c=[];for(let e of(a&&c.push(a),b.values())){c.push(e.callLines?{...e.start,renderedCallLines:e.callLines}:e.start);let a=e.update??e.renderedUpdate;a&&(!Object.prototype.hasOwnProperty.call(a,"renderedLines")&&e.renderedUpdate?c.push({...a,renderedLines:e.renderedUpdate.renderedLines}):c.push(a)),e.resultLines&&c.push({type:"rendered_lines_update",toolCallId:d(e.start),renderedResultLines:e.resultLines})}return{isStreaming:null!==a||b.size>0,events:c}},reset(){a=null,b.clear()}}}c.d(b,{b:()=>f})},73579:(a,b,c)=>{c.d(b,{f:()=>d});function d(a){return a.startsWith("__new__")}},74108:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{tZ:()=>s});var e=c(716),f=c(29862),g=c(57856),h=c(92783),i=c(40678),j=c(94377),k=c(84127),l=c(75248),m=c(96476),n=c(8370),o=c(17992),p=a([f]);let t=new(f=(p.then?(await p)():p)[0]).KeybindingsManager(f.TUI_KEYBINDINGS);function q(){let a=a=>String(a??""),b=(a,b)=>void 0===b?"":String(b);return{name:void 0,sourcePath:void 0,sourceInfo:void 0,fg:b,bg:b,bold:a,dim:a,italic:a,underline:a,inverse:a,strikethrough:a,getFgAnsi:()=>"",getBgAnsi:()=>"",getColorMode:()=>"truecolor",getThinkingBorderColor:()=>a,getBashModeBorderColor:()=>a}}function r(a,b,c,d,f,g,h){let i=(0,e.randomUUID)();return new Promise((e,j)=>{var k;let l,m=!1,n=a=>{c({type:"extension_ui_settled",id:i,reason:a})},o=()=>{a.delete(i),b.delete(i),l&&clearTimeout(l),d?.signal?.removeEventListener("abort",q)},p=(a,b)=>{m||(m=!0,o(),n(b),e(a))},q=()=>p(f,"abort");d?.signal?.addEventListener("abort",q,{once:!0});let r=(k=d?.timeout,"number"!=typeof k||!Number.isFinite(k)||k<=0?null:Math.min(Math.floor(k),0x7fffffff)),s=null===r?null:Date.now()+r;null!==r&&(l=setTimeout(()=>p(f,"timeout"),r)),a.set(i,{resolve:a=>{try{p(h(a),"responded")}catch(a){if(m)return;m=!0,o(),n("failed"),j(a instanceof Error?a:Error(String(a)))}},reject:a=>{m||(m=!0,o(),n("disposed"),j(a))}});let t={type:"extension_ui_request",id:i,...g,...null===s?{}:{expiresAt:s}};b.set(i,t),c(t)})}function s(a,b={}){let c,d=new Map,f=new Map,p=new Map,u=new Map,v=new Map,w=null,x=!1,y=b.agentDir??(0,h.$M)(),z=b.now??Date.now,A=b.writeComposerDraft,B=null,C=null,D=m.Yg,E=g.Tf,F=new Set,G=(0,m.d)(q),H={borderColor:a=>G.fg("borderMuted",a),selectList:{selectedPrefix:a=>G.fg("accent",a),selectedText:a=>G.fg("accent",a),description:a=>G.fg("muted",a),scrollInfo:a=>G.fg("muted",a),noMatch:a=>G.fg("muted",a)}},I=(0,m.Q7)(()=>{for(let a of[...ad.values()])a.requestRender();for(let a of[...F])a();for(let a of ag)ah[a]?.requestRender()}),J=new Set,K=[],L=(a,b)=>{!function(a,b,c=16){a.push(b),a.length>c&&a.splice(0,a.length-c)}(K,{id:a,message:b,notifyType:"warning"})},M=new Set,N=a=>{let b=a;for(let a of M){let c;try{c=a(b)}catch(a){console.error("[pidance] extension terminal input listener failed:",a);continue}if(c?.consume)return{consumed:!0,data:b};c?.data!==void 0&&(b=c.data)}return 0===b.length?{consumed:!0,data:b}:{consumed:!1,data:b}},O=()=>{a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"terminalInputListeners",count:M.size})},P=[],Q=null,R=[],S=0,T=new Map,U=()=>{var a=Date.now();for(let[b,c]of T)c<=a&&T.delete(b);return T.size>0},V=b=>{if(J.has(b))return;J.add(b),console.warn(`[pidance] extension UI capability not supported on web: ${b}`);let c=(0,e.randomUUID)(),d=`Extension UI "${b}" is not supported by the Pidance web client.`;L(c,d),a({type:"extension_ui_request",id:c,method:"notify",message:d,notifyType:"warning"})},W=new Set,X=a=>{let b=a.component;if(!b)return null;try{let a=b.getExpandedText?.();if("string"==typeof a)return a;let c=b.getText?.();if("string"==typeof c)return c}catch(a){console.warn("[pidance] extension editor component getText failed:",a)}return null},Y=null,Z=new Map,$=0,_=(a,b)=>{let c=z()-25e3;return[...Z.entries()].filter(([,d])=>d.requestId===a&&d.at>=c&&(!b||d.shown)).sort((a,b)=>b[1].seq-a[1].seq).map(([a])=>a)},aa=b=>{let c=B;if(!c)return;let d=X(c);B=null,F.delete(ab);try{c.component?.dispose?.()}catch(a){console.warn("[pidance] extension editor component dispose failed:",a)}if(!b?.silent&&(a({type:"extension_ui_request",id:c.id,method:"editorComponent",closed:!0}),d)){let b=_(c.id,!0);if(0===b.length)A?.(d),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"set_editor_text",text:d,appliedToTakeover:!1});else for(let c of b)a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"set_editor_text",text:d,appliedToTakeover:!1,clientId:c})}for(let[a,b]of Z)b.requestId===c.id&&Z.delete(a)},ab=()=>{let b=B;if(!b||!b.component)return;let c=null;try{c=(0,m.Ly)(b.component,D,{allowEmpty:!0})}catch(a){console.warn("[pidance] extension editor component render failed:",a)}if(!c)return void aa();b.lines=c.lines,b.images=c.images,b.imageFallbacks=c.fallbacks;let d=!(0,n.MN)(b.publishedImages,b.images);d&&(b.publishedImages=b.images);let e=!(0,n.Rd)(b.publishedFallbacks,b.imageFallbacks);e&&(b.publishedFallbacks=b.imageFallbacks),a({type:"extension_ui_request",id:b.id,method:"editorComponent",lines:[...b.lines],...d?{images:b.images}:{},...e?{imageFallbacks:b.imageFallbacks}:{}})},ac=(a,b)=>{let c=N(a);if(c.consumed)return c;let d=c.data??a;if(0===d.length)return{consumed:!0,data:d};let e=B;if(!e?.component)return{consumed:!1,data:d};let f=Y;Y=b??null;try{e.component.handleInput?.(d)}catch(a){console.warn("[pidance] extension editor component input failed:",a)}finally{Y=f}return ab(),{consumed:!0,data:d}},ad=new Map,ae=a=>{let b=ad.get(a);if(b){ad.delete(a);try{b.dispose?.()}catch(a){console.error("[pidance] widget dispose failed:",a)}}},af=(b,c)=>{u.has(b)&&(u.delete(b),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:void 0,widgetImages:[],widgetImageFallbacks:void 0,widgetPlacement:c,widgetInteractive:!1}))},ag=["header","footer"],ah={header:null,footer:null},ai=new Set,aj={getGitBranch:()=>null,getExtensionStatuses:()=>p,getAvailableProviderCount:()=>0,onBranchChange:()=>()=>{}},ak=(b,c)=>{a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"footer"===b?"setFooter":"setHeader",lines:c})},al=b=>{if(ai.has(b))return;ai.add(b),console.warn(`[pidance] extension UI ${b} component could not be rendered`);let c=(0,e.randomUUID)(),d=`Extension UI "${b}" component could not be rendered; the slot stays hidden.`;L(c,d),a({type:"extension_ui_request",id:c,method:"notify",message:d,notifyType:"warning"})},am=a=>{let b=ah[a];if(b){ah[a]=null;try{b.dispose?.()}catch(b){console.error(`[pidance] extension ${a} dispose failed:`,b)}ak(a,null)}},an=(a,b)=>{let c;if(am(a),"function"!=typeof b||!(0,m.Lm)())return;let d={lines:null,requestRender:()=>{}},e=!1,f=()=>{if(e=!1,ah[a]!==d)return;let b=(0,m.F$)(c,D,{allowEmpty:!0});if(null===b){console.error(`[pidance] extension ${a} render failed (no render method, threw, or output invalid/over the caps)`),d.lines=null,ak(a,null),al(a);return}if(0===b.length){d.lines=null,ak(a,null);return}d.lines=b,ak(a,b)},h=(0,g.TQ)(()=>{e||ah[a]!==d||(e=!0,queueMicrotask(f))},()=>D,()=>E,{isEditorFocused:U,onUnsupported:V});d.requestRender=h.requestRender;try{c="footer"===a?b(h,G,aj):b(h,G)}catch(b){console.error(`[pidance] extension ${a} factory failed:`,b),am(a),al(a);return}let i=c;if(d.dispose="function"==typeof i?.dispose?()=>c.dispose():void 0,"header"===a&&"function"==typeof i?.setExpanded){let a=c;d.setExpanded=b=>a.setExpanded(b);try{d.setExpanded(x)}catch(a){console.error("[pidance] extension header setExpanded failed:",a)}}ah[a]=d,f()};return{uiContext:{select:(b,c,e)=>r(d,f,a,e,void 0,{method:"select",title:b,options:c},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),confirm:(b,c,e)=>r(d,f,a,e,!1,{method:"confirm",title:b,message:c},a=>(!("cancelled"in a)||!a.cancelled)&&"confirmed"in a&&!!a.confirmed),input:(b,c,e)=>r(d,f,a,e,void 0,{method:"input",title:b,placeholder:c},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,e.randomUUID)(),method:"notify",message:b,notifyType:c})},onTerminalInput:b=>(((b,c)=>{if(J.has(b))return;J.add(b);let d=`Extension UI "${b}" is limited by the Pidance web client: ${c}`;console.warn(`[pidance] ${d}`);let f=(0,e.randomUUID)();L(f,d),a({type:"extension_ui_request",id:f,method:"notify",message:d,notifyType:"warning"})})("onTerminalInput","handlers only receive keys in a few narrow windows: (1) with a widget present and the composer focused and empty, Down/Left start a selection, after which arrows, j, k, Enter and Escape are routed while the selection lasts; (2) while a collapsed extension panel exists, Escape, F1-F12, Alt+<char> and Ctrl+<char> (browser-reserved chords and Ctrl+Space excluded) are routed; (3) while a plugin panel, overlay or dialog is visible, keys that no focused field or control owns are routed to the handlers as they are (Meta chords, the browser-reserved Ctrl chords, Ctrl+Space, the shell's Ctrl+K and Tab stay with the browser). Ordinary typing in the composer never reaches them."),M.add(b),O(),()=>{M.delete(b)&&O()}),setStatus(b,c){c?p.set(b,c):p.delete(b),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setStatus",statusKey:b,statusText:c})},setWorkingMessage(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWorkingMessage",message:b??null})},setWorkingVisible(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWorkingVisible",visible:!!b})},setWorkingIndicator(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWorkingIndicator",frames:Array.isArray(b?.frames)?b.frames.filter(a=>"string"==typeof a):null,intervalMs:"number"==typeof b?.intervalMs?b.intervalMs:null})},setHiddenThinkingLabel(b){let c="string"==typeof b&&""!==b.trim()?b:null;c!==C&&(C=c,a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setHiddenThinkingLabel",label:c}))},setWidget(b,c,d){if("function"==typeof c)return void((b,c,d)=>{let f,h,i;if(ae(b),!(0,m.Lm)())return af(b,d);let j={requestRender:()=>{}},k=!1,l=!1,o=()=>{if(k=!1,ad.get(b)!==j)return;let c=(0,m.Ly)(f,D);if(null===c)return;let{lines:g,images:o,fallbacks:p}=c;u.set(b,{lines:g,images:o,imageFallbacks:p,placement:d,interactive:l});let q=!(0,n.MN)(h,o);q&&(h=o);let r=!(0,n.Rd)(i,p);r&&(i=p),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:g,widgetImages:q?o:void 0,widgetImageFallbacks:r?p:void 0,widgetPlacement:d,widgetInteractive:l})},p=(0,g.TQ)(()=>{k||ad.get(b)!==j||(k=!0,queueMicrotask(o))},()=>D,()=>E,{isEditorFocused:U,onUnsupported:V});j.requestRender=p.requestRender;try{f=c(p,G)}catch(a){console.error("[pidance] widget factory failed:",a),af(b,d);return}let q=f;j.dispose="function"==typeof q?.dispose?()=>f.dispose():void 0,(l="function"==typeof q?.handleMouse)&&(j.handleMouse=a=>{let b=f?.handleMouse;try{b?.call(f,a)}catch(a){console.error("[pidance] widget handleMouse failed:",a)}}),ad.set(b,j),o()})(b,c,d?.placement);if(ae(b),void 0===c||Array.isArray(c))if(null==c)u.delete(b),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:void 0,widgetPlacement:d?.placement,widgetInteractive:!1});else{let f=(0,n.Rt)(c);u.set(b,{lines:f.lines,images:f.images,imageFallbacks:f.fallbacks,placement:d?.placement,interactive:!1}),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setWidget",widgetKey:b,widgetLines:f.lines,...f.images.length>0?{widgetImages:f.images}:{},...f.fallbacks.length>0?{widgetImageFallbacks:f.fallbacks}:{},widgetPlacement:d?.placement,widgetInteractive:!1})}},setFooter(a){an("footer",a)},setHeader(a){an("header",a)},setTitle(b){a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setTitle",title:b})},async custom(b,c){let d=(0,e.randomUUID)(),f=function(a){if(!a||"object"!=typeof a||!0!==a.overlay)return null;let b=a.overlayOptions&&"object"==typeof a.overlayOptions?a.overlayOptions:{},c={anchor:"string"==typeof b.anchor?b.anchor:"center"},d=b.width;("number"==typeof d||"string"==typeof d)&&(c.width=d),"number"==typeof b.minWidth&&(c.minWidth=b.minWidth);let e=b.maxHeight;("number"==typeof e||"string"==typeof e)&&(c.maxHeight=e);let f=b.margin;if("number"==typeof f)c.margin=f;else if(f&&"object"==typeof f){let a={};for(let b of["top","right","bottom","left"])"number"==typeof f[b]&&(a[b]=f[b]);c.margin=a}return c}(c),h=function(a){if(!a||"object"!=typeof a||!0!==a.overlay)return!1;let b=a.overlayOptions;return"object"==typeof b&&null!==b&&!0===b.nonCapturing}(c);return new Promise(e=>{let i,j=!1,k=b=>{j||(j=!0,F.delete(B),v.delete(d),w?.id===d&&(w=null),a({type:"extension_ui_request",id:d,method:"custom",closed:!0,lines:[]}),e(b))},l=[],o=[],p=[],q=[],r=[],s=!1,u=h?"editor":"panel",x=null,y=()=>!z&&!s&&"panel"===u,z=!1,A=()=>{if(z)return;let b=!(0,n.MN)(q,o);b&&(q=o);let c=!(0,n.Rd)(r,p);c&&(r=p),a({type:"extension_ui_request",id:d,method:"custom",lines:l,...b?{images:o}:{},...c?{imageFallbacks:p}:{},focus:u,...s?{hidden:s}:{},...f?{layout:f}:{}}),w={id:d,lines:[...l],...o.length>0?{images:o}:{},...p.length>0?{imageFallbacks:p}:{},focus:u,...s?{hidden:s}:{},...f?{layout:f}:{}}},B=()=>{if(j)return;let a=[],b=[],c=[];try{let d=i?(0,m.Ly)(i,D):null;d&&(a=d.lines,b=d.images,c=d.fallbacks)}catch(a){console.error("[pidance] custom UI render failed:",a)}l=a,o=b,p=c,A()};v.set(d,{handleInput:a=>{if("\x03"===a)return void k(void 0);try{i?.handleInput?.(a)}catch(a){console.error("[pidance] custom UI input failed:",a)}},handleMouse:a=>{try{i?.handleMouse?.(a)}catch(a){console.error("[pidance] custom UI mouse failed:",a)}},done:k,setBounds:a=>!z&&!j&&(!x||x.row!==a.row||x.col!==a.col||x.width!==a.width||x.height!==a.height)&&(x=a,!0)});let C=(0,g.TQ)(()=>{B()},()=>D,()=>E,{isEditorFocused:U,onUnsupported:V});F.add(B),c?.onHandle?.({hide(){z||j||(z=!0,s=!0,v.delete(d),w?.id===d&&(w=null),a({type:"extension_ui_request",id:d,method:"custom",closed:!0,lines:[]}))},setHidden(a){if(!z){let b;b=!!a,s===b||(s=b,j||A())}},isHidden:()=>s,focus(){z||s||"panel"!==u&&(u="panel",A())},unfocus(a){y()&&(u=a&&null===a.target?"none":"editor",A())},isFocused:()=>y(),getBounds:()=>z||s||null===x?void 0:{...x}}),Promise.resolve().then(()=>b(C,G,t,k)).then(a=>{j||(i=a,B())}).catch(a=>{console.error("[pidance] custom UI factory failed:",a),k(void 0)})})},pasteToEditor(a){B?.component?ac((0,i.Z)(a)):this.setEditorText(a)},setEditorText(b){let c=B?.component,d=c?.setText,f=!1;if(c&&"function"==typeof d)try{d.call(c,b),ab(),f=!0}catch(a){console.warn("[pidance] extension editor component setText failed:",a)}a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"set_editor_text",text:b,appliedToTakeover:f})},getEditorText(){let a=B;if(a){let b=X(a);if(null!==b)return b}try{return b.readComposerText?.()??""}catch(a){return console.error("[pidance] readComposerText failed:",a),""}},editor:async(b,c)=>r(d,f,a,void 0,void 0,{method:"editor",title:b,prefill:c},a=>"cancelled"in a&&a.cancelled?void 0:"value"in a?a.value:void 0),addAutocompleteProvider(b){if("function"==typeof b){let c;P=[...P,b],Q=(c=(0,o.Q)(P)).provider,R=c.triggerCharacters,S=P.length-c.skipped,a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"autocompleteProviders",count:S,triggerCharacters:[...R]})}},setEditorComponent(d){c=d,(c=>{let d;if(aa(),"function"!=typeof c)return;let f={id:(0,e.randomUUID)(),component:null,lines:[],images:[],imageFallbacks:[],publishedImages:[],publishedFallbacks:[]};B=f;try{let a=(0,g.TQ)(()=>ab(),()=>D,()=>E,{isEditorFocused:U,onUnsupported:V});d=c(a,H,t)}catch(a){console.warn("[pidance] extension editor component factory failed:",a),aa();return}if(!d||"object"!=typeof d)return aa();let h=d;try{h.onSubmit=c=>{if(B!==f)return;let d="string"==typeof c?c:String(c??""),e=Y??_(f.id,!0)[0]??_(f.id,!1)[0]??null;if(!e){d.trim()&&b.writeComposerDraft?.(d);return}a({type:"extension_ui_request",id:f.id,method:"editorComponentSubmit",text:d,clientId:e})},h.onChange=()=>{}}catch(a){console.warn("[pidance] extension editor component onSubmit is not writable:",a)}try{let a=b.readComposerText?.()??"",c=h.setText;""!==a&&"function"==typeof c&&c.call(h,a)}catch(a){console.warn("[pidance] extension editor component setText failed:",a)}f.component=h,F.add(ab),ab()})(d)},getEditorComponent:()=>c,get theme(){return(0,m.Lm)()??q()},getAllThemes:()=>(0,l.S0)(y),getTheme:a=>(0,l.n5)(a,y),setTheme(b){let c=(0,l.tA)(b,y);if(!c.success){var d;return d=c.error??"unknown error",W.has(d)||(W.size>=16&&W.clear(),W.add(d),console.warn(`[pidance] extension setTheme rejected: ${d}`),a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"notify",message:`Extension UI theme was not applied: ${d}`,notifyType:"warning"})),{success:!1,error:c.error}}var f=c.name;if("dark"===f||"light"===f){try{(0,k.xP)("theme.mode",f,y),(0,j.Z)().publish({"theme.mode":f})}catch(a){console.error("[pidance] failed to persist shell theme preference:",a)}a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setTheme",mode:f})}return{success:!0}},getToolsExpanded:()=>x,setToolsExpanded(b){x=!!b;let c=ah.header;if(c?.setExpanded){try{c.setExpanded(x)}catch(a){console.error("[pidance] extension header setExpanded failed:",a)}c.requestRender()}a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"setToolsExpanded",toolsExpanded:x})}},pending:d,statuses:p,widgets:u,pendingSnapshot:f,get headerLines(){let a=ah.header;return a?.lines?[...a.lines]:null},get footerLines(){let a=ah.footer;return a?.lines?[...a.lines]:null},resetSlotFailures(){ai.clear()},get customSnapshot(){return w},get terminalInputListenerCount(){return M.size},get autocompleteProviderCount(){return S},get autocompleteTriggerCharacters(){return[...R]},async suggestCompletions(a){let b=Q;if(!b||0===S)return{kind:"no-provider"};try{let c=await b.getSuggestions(a.lines,a.cursorLine,a.cursorCol,{signal:a.signal,force:a.force});return(0,o.ad)(c)}catch{return{kind:"error"}}},applyCompletion(a){let b=Q;if(!b||0===S)return null;try{return(0,o.xh)(b.applyCompletion(a.lines,a.cursorLine,a.cursorCol,a.item,a.prefix))}catch{return null}},get hiddenThinkingLabel(){return C},get capabilityNoticeSnapshot(){return K.map(a=>({...a}))},respond(a,b){let c=d.get(a);return!!c&&(c.resolve(b),!0)},inputCustom(a,b){let c=v.get(a);return!!c&&(c.handleInput(b),!0)},inputCustomMouse(a,b){let c=v.get(a);return!!c&&(c.handleMouse(b),!0)},setCustomBounds(a,b){let c=function(a){if(!a||"object"!=typeof a)return null;let b=b=>{let c=a[b];return"number"==typeof c&&Number.isFinite(c)?Math.round(c):null},c=b("row"),d=b("col"),e=b("width"),f=b("height");return null===c||null===d||null===e||null===f||e<=0||f<=0||Math.abs(c)>1e4||Math.abs(d)>1e4||e>1e4||f>1e4?null:{row:c,col:d,width:e,height:f}}(b);return!!c&&(v.get(a)?.setBounds(c)??!1)},inputWidgetMouse(a,b){let c=ad.get(a);return!!c?.handleMouse&&(c.handleMouse(b),!0)},get editorTakeoverSnapshot(){let a=B;if(!a)return null;return{id:a.id,lines:[...a.lines],...a.images.length>0?{images:a.images}:{},...a.imageFallbacks.length>0?{imageFallbacks:a.imageFallbacks}:{}}},dispatchEditorComponentInput:(a,b)=>ac(a,b),recordEditorTakeoverView(a,b,c){((a,b,c)=>{if(!a||!c)return;if(Z.set(c,{requestId:a,shown:b,at:z(),seq:++$}),Z.size>64){let a=[...Z.entries()].sort((a,b)=>a[1].at-b[1].at)[0];a&&Z.delete(a[0])}let d=z()-3e5;for(let[a,b]of Z)b.at<d&&Z.delete(a)})(a,b,c)},applyEditorTakeoverText(a,b){let c=B;if(!c||c.id!==a)return!1;let d=c.component?.setText;if("function"!=typeof d)return!1;try{return d.call(c.component,b),ab(),!0}catch(a){return console.warn("[pidance] extension editor component setText failed:",a),!1}},dismissEditorTakeover(b,c){let d=B;if(!d||d.id!==b)return!1;let f=X(d);return!!f&&(a({type:"extension_ui_request",id:(0,e.randomUUID)(),method:"set_editor_text",text:f,appliedToTakeover:!1,...c?{clientId:c}:{}}),!0)},setRenderSize(a){let b=Math.round(a.width),c=Math.round(a.rows);if(!Number.isFinite(b)||b<=0||!Number.isFinite(c)||c<=0||b===D&&c===E)return!1;for(let a of(D=b,E=c,[...F]))a();for(let a of[...ad.values()])a.requestRender();for(let a of ag)ah[a]?.requestRender();return!0},dispatchTerminalInput:a=>N(a),setEditorFocus:(a,b="default")=>{let c=U();if(a?T.set(b,Date.now()+6e4):T.delete(b),c===U())return!1;for(let a of[...ad.values()])a.requestRender();for(let a of[...F])a();for(let a of Object.values(ah))a?.requestRender();return!0},dispose(){for(let[a,b]of(I(),T.clear(),c=void 0,aa({silent:!0}),d))d.delete(a),f.delete(a),b.reject(Error("Extension UI disposed"));for(let a of v.values())a.done(void 0);for(let a of(v.clear(),w=null,M.clear(),[...ad.keys()]))ae(a);for(let a of ag)am(a);p.clear(),u.clear()}}}d()}catch(a){d(a)}})},75248:(a,b,c)=>{c.d(b,{QV:()=>m,S0:()=>k,n5:()=>l,tA:()=>n});var d=c(89477),e=c(86697),f=c(92783),g=c(96476);function h(a){return"string"==typeof a&&a.length>0&&!a.includes("/")}function i(a){try{let b=(0,d.statSync)(a);if(!b.isFile()||b.size>262144)return null;return(0,g.lg)(JSON.parse((0,d.readFileSync)(a,"utf8")),a)}catch{return null}}function j(a){let b,c=(0,e.join)(a,"themes");try{if(!(0,d.existsSync)(c))return[];b=(0,d.readdirSync)(c)}catch{return[]}let f=[];for(let a of b){if(!a.endsWith(".json"))continue;let b=(0,e.join)(c,a),d=i(b);h(d?.name)&&f.push({name:d.name,path:b})}return f}function k(a=(0,f.$M)()){let b=new Set,c=[];for(let d of[...(0,g.xU)(),...j(a)])b.has(d.name)||(b.add(d.name),c.push(d));return c.sort((a,b)=>a.name.localeCompare(b.name))}function l(a,b=(0,f.$M)()){if(!h(a))return;let c=(0,g.gV)(a);if(void 0!==c)return(0,g.lg)(c)??void 0;for(let c of j(b))if(c.name===a&&c.path)return i(c.path)??void 0}function m(){return(0,g.Lm)()}function n(a,b=(0,f.$M)()){if("string"==typeof a){let c=l(a,b);return c?((0,g.G8)(c),{success:!0,name:a}):{success:!1,error:`Unknown theme: ${a}`}}return a&&"object"==typeof a&&"function"==typeof a.fg&&"function"==typeof a.bg?((0,g.G8)(a),{success:!0,name:a.name}):{success:!1,error:"Expected a theme name or a Theme instance"}}},82356:(a,b,c)=>{c.d(b,{AZ:()=>u,GT:()=>h,Hl:()=>v,kP:()=>t,sweepStaleRunningLeases:()=>s,wy:()=>w});var d=c(716),e=c(89477),f=c(86697),g=c(92783);let h="Session is locked by another Pidance process (writable host ownership)",i="Timed out acquiring Pidance running-lease lock";function j(a){return(0,f.join)(a,"pidance-running-leases")}function k(a,b){let c=b.replace(/[^a-zA-Z0-9._-]+/g,"_").slice(0,180);return(0,f.join)(j(a),`${c}.json`)}function l(a){if(!Number.isFinite(a)||a<=0)return!1;try{return process.kill(a,0),!0}catch(a){return"EPERM"===a.code}}function m(a){try{let b=JSON.parse((0,e.readFileSync)(a,"utf8"));if("number"!=typeof b.pid||"string"!=typeof b.sessionId||"number"!=typeof b.heartbeatAt)return null;return{pid:b.pid,sessionId:b.sessionId,heartbeatAt:b.heartbeatAt,startedAt:"number"==typeof b.startedAt?b.startedAt:b.heartbeatAt}}catch{return null}}function n(a){try{let b=JSON.parse((0,e.readFileSync)(a,"utf8"));if("number"!=typeof b.pid||"string"!=typeof b.token)return null;return{pid:b.pid,token:b.token}}catch{return null}}function o(a,b){let c=j(a);(0,e.existsSync)(c)||(0,e.mkdirSync)(c,{recursive:!0,mode:448});let g=(0,f.join)(c,".lease-lock"),h=(0,d.randomBytes)(8).toString("hex"),k=Date.now()+3e3,m=!1;for(;!m;){let a=`${g}.${process.pid}.${h}.tmp`;try{(0,e.writeFileSync)(a,JSON.stringify({pid:process.pid,token:h}),{mode:384}),(0,e.linkSync)(a,g),m=!0}catch(b){if("EEXIST"!==b.code){try{(0,e.unlinkSync)(a)}catch{}throw b}}try{(0,e.unlinkSync)(a)}catch{}if(m)break;let b=n(g);if(b&&!l(b.pid)){try{n(g)?.token===b.token&&(0,e.unlinkSync)(g)}catch{}continue}if(!b)try{Date.now()-(0,e.statSync)(g).mtimeMs>1e4&&(0,e.unlinkSync)(g)}catch{}if(Date.now()>=k)throw Error(i);!function(){let a=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(a,0,0,5)}()}try{return b()}finally{try{n(g)?.token===h&&(0,e.unlinkSync)(g)}catch{}}}function p(a){return a instanceof Error&&a.message===i}function q(a,b){let c=`${a}.${process.pid}.tmp`;(0,e.writeFileSync)(c,`${JSON.stringify(b)}
2
+ `,{mode:384}),(0,e.renameSync)(c,a)}function r(a){return!!(a&&l(a.pid))}function s(a=(0,g.$M)(),b=Date.now()){try{let c,{fresh:d,removed:g}=(c=j(a),(0,e.existsSync)(c)?o(a,()=>{let a=[],d=0;for(let g of(0,e.readdirSync)(c)){if(!g.endsWith(".json"))continue;let h=(0,f.join)(c,g),i=m(h);if(!r(i)){try{(0,e.unlinkSync)(h),d+=1}catch{}continue}b-i.heartbeatAt<=2e4&&l(i.pid)&&a.push(i)}return{fresh:a,removed:d}}):{fresh:[],removed:0});return{removed:g,active:d.length,skipped:!1}}catch(a){if(p(a))return{removed:0,active:0,skipped:!0};throw a}}function t(a,b=(0,g.$M)(),c=Date.now()){if(!a)return!1;try{return o(b,()=>{let d=k(b,a),f=(0,e.existsSync)(d)?m(d):null;return!(f&&f.pid!==process.pid&&r(f))&&(q(d,{pid:process.pid,sessionId:a,heartbeatAt:c,startedAt:f&&f.pid===process.pid?f.startedAt:c}),!0)})}catch(a){if(p(a))return!1;throw a}}function u(a,b=(0,g.$M)(),c=Date.now()){if(a)try{o(b,()=>{let d=k(b,a),f=(0,e.existsSync)(d)?m(d):null;f&&f.pid!==process.pid&&r(f)||q(d,{pid:process.pid,sessionId:a,heartbeatAt:c,startedAt:f&&f.pid===process.pid?f.startedAt:c})})}catch(a){if(!p(a))throw a}}function v(a,b=(0,g.$M)()){if(a)try{o(b,()=>{let c=k(b,a),d=(0,e.existsSync)(c)?m(c):null;if(!d||d.pid===process.pid)try{(0,e.unlinkSync)(c)}catch{}})}catch(a){if(!p(a))throw a}}function w(a,b=(0,g.$M)(),c=Date.now()){if(!a)return!1;let d=(0,e.existsSync)(k(b,a))?m(k(b,a)):null;return!!d&&d.pid!==process.pid&&r(d)}},87390:(a,b,c)=>{c.a(a,async(a,d)=>{try{c.d(b,{A$:()=>q,Nw:()=>j.Nw,bk:()=>p,mc:()=>o,wz:()=>k.wz});var e=c(29021),f=c(21820),g=c(33873),h=c.n(g),i=c(92783),j=c(69420),k=c(54639),l=c(93686),m=c(69453),n=a([l,m]);[l,m]=n.then?(await n)():n;async function o(){let a=Date.now(),b=globalThis.__piAllowedRootsCache;if(b&&b.expiresAt>a)return b.roots;let c=await (0,m.dQ)(),d=function(a){let b=new Set;for(let c of a)!0!==c.readOnly&&c.cwd&&b.add((0,j.Nw)(c.cwd)),!0!==c.readOnly&&c.projectRoot&&b.add((0,j.Nw)(c.projectRoot));return b}(c);try{for(let a of(0,e.readdirSync)((0,f.homedir)()))/^pi-cwd-\d{8}$/.test(a)&&d.add((0,j.Nw)(h().join((0,f.homedir)(),a)))}catch{}for(let a of(0,k.HM)())d.add(a);try{d.add((0,l.qo)((0,i.$M)()))}catch{}return globalThis.__piAllowedRootsCache={roots:d,expiresAt:a+5e3},d}function p(){return!0}function q(a,b){return!0}d()}catch(a){d(a)}})},88876:(a,b,c)=>{function d(a,b){if(!b||a.length!==b.length)return!1;for(let c=0;c<a.length;c+=1)if(a[c]!==b[c])return!1;return!0}function e(a,b){let c={};return a.callLines&&!d(a.callLines,b.callLines)&&(c.callLines=a.callLines),a.resultLines&&!d(a.resultLines,b.resultLines)&&(c.resultLines=a.resultLines),c.callLines||c.resultLines?c:null}function f(a){let b=a.now??(()=>Date.now()),c=a.setTimer??((a,b)=>setTimeout(a,b)),d=a.clearTimer??(a=>{clearTimeout(a)}),e=new Map,f=!1,g=a=>{let b=e.get(a);return b||(b={rendering:!1,pending:!1,timer:null,lastRunAt:void 0},e.set(a,b)),b},h=(c,d)=>{if(d.rendering){d.pending=!0;return}d.rendering=!0,d.lastRunAt=b();try{let b=a.recompute(c);null!=b&&a.emit(c,b)}catch(b){a.onError?.(b)}finally{d.rendering=!1,d.pending&&(d.pending=!1,i(c))}},i=d=>{if(f)return;let e=g(d);if(e.rendering){e.pending=!0;return}let i=void 0===e.lastRunAt?1/0:b()-e.lastRunAt;if(i<a.minIntervalMs){if(null!==e.timer)return;e.timer=c(()=>{e.timer=null,h(d,e)},a.minIntervalMs-i);return}h(d,e)},j=a=>{if(f)return;let b=g(a);null!==b.timer&&(d(b.timer),b.timer=null),h(a,b)};return{request:i,flush:j,flushAll(a){for(let b of a)j(b)},isRendering:a=>e.get(a)?.rendering===!0,dispose(){for(let a of(f=!0,e.values()))null!==a.timer&&(d(a.timer),a.timer=null),a.pending=!1;e.clear()}}}c.d(b,{VQ:()=>e,w7:()=>f})},93686:(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(92783),k=c(87390),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)}})},94377:(a,b,c)=>{c.d(b,{Z:()=>d});function d(){let a,b,c,d=globalThis;return d.__piPrefsBus||(a=0,b=Math.random().toString(36).slice(2)+Date.now().toString(36),c=new Set,d.__piPrefsBus={revision:()=>a,bootId:()=>b,subscribe:a=>(c.add(a),()=>{c.delete(a)}),publish(d){let e={changed:d,revision:a+=1,bootId:b,at:new Date().toISOString()};for(let a of c)try{a(e)}catch{}return e},resetForTests(){a=0,c.clear()}}),d.__piPrefsBus}},96476:(a,b,c)=>{let d;c.d(b,{Yg:()=>k,d:()=>L,lg:()=>o,gV:()=>G,xU:()=>F,Lm:()=>I,Q7:()=>K,hR:()=>Q,Mf:()=>T,Ly:()=>R,GD:()=>P,t_:()=>O,F$:()=>S,G8:()=>J,Ph:()=>m,cK:()=>j,DD:()=>x,YJ:()=>B,Sw:()=>C});let e=JSON.parse('{"$schema":"https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json","name":"dark","vars":{"cyan":"#00d7ff","blue":"#5f87ff","green":"#b5bd68","red":"#cc6666","yellow":"#ffff00","text":"#d4d4d4","gray":"#808080","dimGray":"#666666","darkGray":"#505050","accent":"#8abeb7","selectedBg":"#3a3a4a","userMsgBg":"#343541","toolPendingBg":"#282832","toolSuccessBg":"#283228","toolErrorBg":"#3c2828","customMsgBg":"#2d2838"},"colors":{"accent":"accent","border":"blue","borderAccent":"cyan","borderMuted":"darkGray","success":"green","error":"red","warning":"yellow","muted":"gray","dim":"dimGray","text":"text","thinkingText":"gray","selectedBg":"selectedBg","scrollbarTrack":"darkGray","scrollbarThumb":"text","searchMatchBg":"selectedBg","searchMatchText":"text","userMessageBg":"userMsgBg","userMessageText":"text","customMessageBg":"customMsgBg","customMessageText":"text","customMessageLabel":"#9575cd","toolPendingBg":"toolPendingBg","toolSuccessBg":"toolSuccessBg","toolErrorBg":"toolErrorBg","toolTitle":"text","toolOutput":"gray","mdHeading":"#f0c674","mdLink":"#81a2be","mdLinkUrl":"dimGray","mdCode":"accent","mdCodeBlock":"green","mdCodeBlockBorder":"gray","mdQuote":"gray","mdQuoteBorder":"gray","mdHr":"gray","mdListBullet":"accent","toolDiffAdded":"green","toolDiffRemoved":"red","toolDiffContext":"gray","syntaxComment":"#6A9955","syntaxKeyword":"#569CD6","syntaxFunction":"#DCDCAA","syntaxVariable":"#9CDCFE","syntaxString":"#CE9178","syntaxNumber":"#B5CEA8","syntaxType":"#4EC9B0","syntaxOperator":"#D4D4D4","syntaxPunctuation":"#D4D4D4","thinkingOff":"darkGray","thinkingMinimal":"#6e6e6e","thinkingLow":"#5f87af","thinkingMedium":"#81a2be","thinkingHigh":"#b294bb","thinkingXhigh":"#d183e8","thinkingMax":"#ff5fff","bashMode":"green"},"export":{"pageBg":"#18181e","cardBg":"#1e1e24","infoBg":"#3c3728"}}');var f=c(8370);let g=JSON.parse('{"$schema":"https://raw.githubusercontent.com/earendil-works/pi/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json","name":"light","vars":{"teal":"#5a8080","blue":"#547da7","green":"#588458","red":"#aa5555","yellow":"#9a7326","text":"#1f2328","mediumGray":"#6c6c6c","dimGray":"#767676","lightGray":"#b0b0b0","selectedBg":"#d0d0e0","userMsgBg":"#e8e8e8","toolPendingBg":"#e8e8f0","toolSuccessBg":"#e8f0e8","toolErrorBg":"#f0e8e8","customMsgBg":"#ede7f6"},"colors":{"accent":"teal","border":"blue","borderAccent":"teal","borderMuted":"lightGray","success":"green","error":"red","warning":"yellow","muted":"mediumGray","dim":"dimGray","text":"text","thinkingText":"mediumGray","selectedBg":"selectedBg","scrollbarTrack":"lightGray","scrollbarThumb":"text","searchMatchBg":"selectedBg","searchMatchText":"text","userMessageBg":"userMsgBg","userMessageText":"text","customMessageBg":"customMsgBg","customMessageText":"text","customMessageLabel":"#7e57c2","toolPendingBg":"toolPendingBg","toolSuccessBg":"toolSuccessBg","toolErrorBg":"toolErrorBg","toolTitle":"text","toolOutput":"mediumGray","mdHeading":"yellow","mdLink":"blue","mdLinkUrl":"dimGray","mdCode":"teal","mdCodeBlock":"green","mdCodeBlockBorder":"mediumGray","mdQuote":"mediumGray","mdQuoteBorder":"mediumGray","mdHr":"mediumGray","mdListBullet":"green","toolDiffAdded":"green","toolDiffRemoved":"red","toolDiffContext":"mediumGray","syntaxComment":"#008000","syntaxKeyword":"#0000FF","syntaxFunction":"#795E26","syntaxVariable":"#001080","syntaxString":"#A31515","syntaxNumber":"#098658","syntaxType":"#267F99","syntaxOperator":"#000000","syntaxPunctuation":"#000000","thinkingOff":"lightGray","thinkingMinimal":"#767676","thinkingLow":"blue","thinkingMedium":"teal","thinkingHigh":"#875f87","thinkingXhigh":"#8b008b","thinkingMax":"#af005f","bashMode":"green"},"export":{"pageBg":"#f8f8f8","cardBg":"#ffffff","infoBg":"#fffae6"}}'),h=null;function i(a,b,c){return`${a}${c.replace(/\r?\n/g,`${b}$&${a}`)}${b}`}function j(a){if(!a){h=null;return}h=class extends a{bold(a){return i("\x1b[1m","\x1b[22m",a)}italic(a){return i("\x1b[3m","\x1b[23m",a)}underline(a){return i("\x1b[4m","\x1b[24m",a)}inverse(a){return i("\x1b[7m","\x1b[27m",a)}strikethrough(a){return i("\x1b[9m","\x1b[29m",a)}fallbackColor(a){return a}}}let k=100,l=null;function m(a){l=a}let n=new Set(["selectedBg","searchMatchBg","userMessageBg","customMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg"]);function o(a,b){if(!h||!a||"object"!=typeof a||!a.colors||"object"!=typeof a.colors)return null;try{let c=a.vars??{},d={},e={};for(let[b,f]of Object.entries(a.colors)){let a=function a(b,c,d=new Set){if("number"==typeof b||""===b||b.startsWith("#"))return b;if(d.has(b))throw Error(`Circular variable reference detected: ${b}`);if(!(b in c))throw Error(`Variable reference not found: ${b}`);return d.add(b),a(c[b],c,d)}(f,c);n.has(b)?e[b]=a:d[b]=a}return new h(d,e,"truecolor",{name:"string"==typeof a.name?a.name:void 0,sourcePath:b})}catch{return null}}let p=Symbol.for("@earendil-works/pi-coding-agent:theme"),q=Symbol.for("@mariozechner/pi-coding-agent:theme"),r="Extension renderers that rely on the SDK theme helpers will not draw their themed content (for example the built-in edit tool's diff): Pidance could not hand its theme to the shared pi theme slot.",s=/Theme not initialized/i,t=null,u=new Set,v=[],w=null;function x(a){if(w=a,a)for(let b of v.splice(0))a(b)}function y(a,b){if(!u.has(a)){if(u.add(a),console.warn(`[pidance] ${b}`),!w)return void v.push(b);try{w(b)}catch(a){console.warn("[pidance] render bridge warning sink failed:",a)}}}function z(a){let b=a instanceof Error?a.message:String(a);s.test(b)&&y("sdk-theme-uninitialized",`${r} (${b})`)}let A=null;function B(a){A=a}function C(){if(!0===t)return!0;if(!A)return null;let a=I();if(!a)return null;D(a);try{return A(),t=!0,!0}catch(a){return y("sdk-theme-verify",`${r} (self-check failed: ${a instanceof Error?a.message:String(a)})`),!1}}function D(a){try{let b=globalThis;b[p]=a,b[q]=a}catch(a){y("sdk-theme-install",`${r} (install failed: ${a instanceof Error?a.message:String(a)})`)}}let E={dark:e,light:g};function F(){return Object.keys(E).map(a=>({name:a}))}function G(a){return E[a]}let H=new Set;function I(){if(void 0!==d)return d;if(!h)return null;let a=o(E.dark);return d=a,a&&D(a),d}function J(a){for(let b of(d=a,D(a),[...H]))try{b()}catch(a){console.error("[pidance] theme change listener failed:",a)}}function K(a){return H.add(a),()=>{H.delete(a)}}function L(a){return new Proxy({},{get(b,c){let d=I()??a?.();if(!d)return;let e=Reflect.get(d,c);return"function"==typeof e?e.bind(d):e},has(a,b){let c=I();return!!c&&Reflect.has(c,b)}})}function M(a,b=k,c){if(!a||"object"!=typeof a||"function"!=typeof a.render)return null;try{let d=function(a){let b=l;if(!b)return a();let c=b.getImages();b.setImages("kitty");try{return a()}finally{b.setImages("kitty"===c?"kitty":c??null)}}(()=>a.render(b));if(!Array.isArray(d)||!d.every(a=>"string"==typeof a))return null;let e=(0,f.Rt)(d);if(!function(a,b){if(!Array.isArray(a))return!1;if(0===a.length)return b?.allowEmpty===!0;if(!a.every(a=>"string"==typeof a)||a.length>500)return!1;let c=0;for(let b of a)if(b.length>4e3||(c+=b.length)>204800)return!1;return!0}(e.lines,c))return null;return{lines:e.lines,images:e.images,fallbacks:e.fallbacks}}catch(a){return z(a),null}}function N(a,b=k,c){let d=M(a,b,c);return d?(0,f.N5)(d):null}function O(a,b,c,d,e,g=k){let h=function(a,b,c,d,e,f=k){let g=function(a){if(!a||"object"!=typeof a)return;let b=a.renderResult??a.ln;return"function"==typeof b?b:void 0}(a);if(!g)return null;let h=I();if(!h)return null;try{let a=g(b,c,h,d);return a&&"object"==typeof a&&e?.(a),M(a,f)}catch(a){return z(a),null}}(a,b,c,d,e,g);return h?(0,f.N5)(h):null}function P(a,b,c,d,e=k){let g=function(a,b,c,d,e=k){let f=function(a){if(!a||"object"!=typeof a)return;let b=a.renderCall;return"function"==typeof b?b:void 0}(a);if(!f)return null;let g=I();if(!g)return null;try{let a=f(b,g,c);return a&&"object"==typeof a&&d?.(a),M(a,e)}catch(a){return z(a),null}}(a,b,c,d,e);return g?(0,f.N5)(g):null}function Q(a,b=k,c){return N(a,b,c)}function R(a,b=k,c){return M(a,b,c)}function S(a,b=k,c){return Q(a,b,c)}function T(a,b,c,d=k){if("function"!=typeof a||!c)return null;try{let e=a(b,{expanded:!0},c);return N(e,d)}catch(a){return z(a),null}}}};