@chainingintention/pi-web-cn 2.202610.1 → 2.202610.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J a
4
4
 
5
5
  `)})}function At(e,t){return e.filter(e=>e.target!==`display`).filter(e=>e.visible?.(t)??!0).map(e=>({action:e,enabled:e.enabled?.(t)??!0,ariaLabel:e.ariaLabel?.(t)??e.title}))}function jt(e,t){return e.filter(e=>e.target===`display`).filter(e=>e.visible?.(t)??!0).map(e=>({action:e,enabled:e.enabled?.(t)??!0,ariaLabel:e.ariaLabel?.(t)??e.title}))}var Mt=class{constructor(){this.inputs=``,this.actions=[],this.messages=new WeakMap}get(e,t,n,r=e,i=!0){let a=JSON.stringify([n.machine,n.session]);(a!==this.inputs||t.length!==this.actions.length||t.some((e,t)=>e!==this.actions[t]))&&(this.inputs=a,this.actions=t,this.messages=new WeakMap);let o=kt(r),s=JSON.stringify([o.role,o.text,i]),c=this.messages.get(e)??new Map,l=c.get(s);if(l!==void 0)return l;let u=i?Ot(e,r.role):void 0,d=t.flatMap(e=>e.target===`display`?jt([e],{...n,message:o}):u===void 0?[]:At([e],{...n,message:u}));return c.set(s,d),this.messages.set(e,c),d}};function Nt(e){let t=e.attachmentCount??0;return t>0?t===1?n(`client.queuedMessageActions.attachment`,`1 attachment`):n(`client.queuedMessageActions.attachments`,`{count} attachments`,{count:t}):e.hasAttachments===!0?n(`client.queuedMessageActions.attachmentsUnknown`,`Attachments`):void 0}function Pt(e,t){let r=e[t],i=r?.hasAttachments===!0||(r?.attachmentCount??0)>0,a=i?n(`client.queuedMessageActions.recallAttachments`,`Recall this message? Only its text will return to the composer. Its attachments will be lost.`):n(`client.queuedMessageActions.recall`,`Recall this message?`),o=e.slice(t+1);if(o.length===0)return i?a:void 0;let s=o.filter(e=>e.kind===`steer`).length,c=o.length-s,l=[s===0?void 0:s===1?n(`client.queuedMessageActions.laterSteer`,`1 later steer`):n(`client.queuedMessageActions.laterSteers`,`{count} later steers`,{count:s}),c===0?void 0:c===1?n(`client.queuedMessageActions.queuedFollowUp`,`1 queued follow-up`):n(`client.queuedMessageActions.queuedFollowUps`,`{count} queued follow-ups`,{count:c})].filter(e=>e!==void 0);return`${a}\n\n${n(`client.queuedMessageActions.removesLater`,`This will also remove {messages}.`,{messages:l.join(n(`client.queuedMessageActions.and`,` and `))})}`}var Ft=Object.freeze({presentation:`code`,overflow:`scroll`,copy:!0,previews:!0}),It=Object.freeze({presentation:`plain`,overflow:`wrap`,copy:!1,previews:!1}),Lt=Object.freeze({rememberPosition:!0,followTail:!0,automaticHistory:!0,anchorPrepends:!0,loadImages:!0,codeBlocks:Object.freeze({...It,presentation:`code`,overflow:`scroll`,copy:!0,previews:!0}),rememberDisclosures:!0,visualEffects:!0});function Rt(e,t){let n=[];for(let r of e){let e=t[r.id]?.deprecatedAgentInputs;e!==void 0&&e.length!==0&&n.push({machineId:r.id,machineName:r.name,inputs:e})}return n}function zt(e){let t=e.inputs.map(e=>{let t=e.source===`config`?n(`ui.main.cfe35469e36d`,`Config setting {arg0}`,{arg0:e.name}):n(`ui.main.0d4a3f015cec`,`Environment variable {arg0}`,{arg0:e.name});return e.replacement===void 0?n(`ui.main.ccb652119f1a`,`{arg0} is deprecated with no replacement; remove it manually (local compatibility remains temporarily)`,{arg0:t}):n(`ui.main.22fa6c3b8983`,`{arg0} is deprecated; use {arg1} instead`,{arg0:t,arg1:e.replacement})}).join(`;`);return n(`ui.main.92bd6d097e1f`,`{arg0}: {arg1}. Support for deprecated agent configuration inputs will be removed in a future release.`,{arg0:e.machineName,arg1:t})}function Bt(e){return e.length===0?null:b`<div class="deprecation-notice" role="alert">
6
6
  ${e.map(e=>b`<p class="deprecation-notice-text">${zt(e)}</p>`)}
7
- </div>`}var C=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},Vt={attribute:!0,type:String,converter:ce,reflect:!1,hasChanged:e},Ht=(e=Vt,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function w(e){return(t,n)=>typeof n==`object`?Ht(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function T(e){return w({...e,state:!0,attribute:!1})}var Ut=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function E(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return Ut(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return Ut(n,r,{get(){return a(this)}})}}var Wt={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},Gt=e=>(...t)=>({_$litDirective$:e,values:t}),Kt=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},qt={},Jt=Gt(class extends Kt{constructor(){super(...arguments),this.ot=qt}render(e,t){return t()}update(e,[t,n]){if(Array.isArray(t)){if(Array.isArray(this.ot)&&this.ot.length===t.length&&t.every((e,t)=>e===this.ot[t]))return u}else if(this.ot===t)return u;return this.ot=Array.isArray(t)?Array.from(t):t,this.render(t,n)}}),Yt=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Xt(e){return Yt.some(t=>t===e)}function Zt(e){return e===void 0||e===``?`off`:e}function Qt(e,t=c(`en`,{})){let n=Zt(e),r={off:t(`thinking.label.off`,`Off`),minimal:t(`thinking.label.minimal`,`Minimal`),low:t(`thinking.label.low`,`Low`),medium:t(`thinking.label.medium`,`Medium`),high:t(`thinking.label.high`,`High`),xhigh:t(`thinking.label.xhigh`,`Extra high`),max:t(`thinking.label.max`,`Maximum`)};return Xt(n)?r[n]??n:n}function $t(e,t=c(`en`,{})){switch(e){case`off`:return t(`thinking.description.off`,`No reasoning`);case`minimal`:return t(`thinking.description.minimal`,`Minimal reasoning (about 1k tokens)`);case`low`:return t(`thinking.description.low`,`Light reasoning (about 2k tokens)`);case`medium`:return t(`thinking.description.medium`,`Moderate reasoning (about 8k tokens)`);case`high`:return t(`thinking.description.high`,`Deep reasoning (about 16k tokens)`);case`xhigh`:return t(`thinking.description.xhigh`,`Extra high reasoning (about 32k tokens)`);case`max`:return t(`thinking.description.max`,`Maximum reasoning (about 64k tokens)`);default:return}}function en(e,t){let n=t.length>=2?t:Yt,r=n.length-1,i=Zt(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}function tn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nn(e){if(!tn(e))throw new te(`server.main.b5b69396302e`,`Invalid session defaults`);let t=e,n={};for(let e of[`defaultProvider`,`defaultModel`]){let r=t[e];if(r!==void 0){if(typeof r!=`string`)throw new te(`server.main.d20dbeed752b`,`Invalid {arg0}`,{arg0:e});n[e]=r}}let r=t.defaultThinkingLevel;if(r!==void 0){if(typeof r!=`string`||!Xt(r))throw new te(`server.main.e937d7ab07c7`,`Invalid defaultThinkingLevel`);n.defaultThinkingLevel=r}return n}var rn=class extends Error{constructor(e,t,n={}){super(e,n),this.status=t,this.name=`HttpRequestError`}},an=class extends Error{constructor(e,t={}){super(e,t),this.name=`NetworkRequestError`}},on=fe();function sn(e){on=e}function cn(e){return y(Ce(e,void 0,on))}async function D(e,t,n){let r=new Headers(n?.headers);n?.body!==void 0&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=on,a=cn(e),o=await un(()=>fetch(a,{...n,headers:r}),n?.signal);if(!o.ok)throw new rn(dn(await o.json().catch(()=>({})))??o.statusText,o.status);return ye(i),t(await un(()=>o.json(),n?.signal))}async function ln(e,t){let n=on,r=cn(e),i=await un(()=>fetch(r));if(i.status===204)ye(n);else if(i.status!==404){if(!i.ok)throw new rn(dn(await i.json().catch(()=>({})))??i.statusText,i.status);return ye(n),t(await un(()=>i.json()))}}async function un(e,t){try{return await e()}catch(e){throw e instanceof TypeError&&e.name!==`AbortError`&&t?.aborted!==!0?new an(e.message,{cause:e}):e}}function dn(e){if(fn(e))return typeof e.error==`string`?e.error:void 0}function fn(e){return typeof e==`object`&&!!e}var pn=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function mn(e){if(!hn(e))return;let t=e,n=t.themeId,r=t.auto;if(typeof n==`string`&&pn.test(n)&&typeof r==`boolean`)return{themeId:n,auto:r}}function hn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gn(e,t){let n=mn(e);if(n===void 0)throw new te(`configError.defaultTheme.invalid`,`PI WEB config defaultTheme must contain a qualified themeId and a boolean auto: {source}`,{source:t});return n}function _n(e,t){if(e!==`steer`&&e!==`followUp`)throw new te(`configError.defaultStreamingBehavior.invalid`,`PI WEB config defaultStreamingBehavior must be steer or followUp: {source}`,{source:t});return e}function vn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yn(e,t){if(!vn(e))throw new te(`configError.sessionNaming.object`,`PI WEB config sessionNaming must be an object: {source}`,{source:t});let n=Object.keys(e).find(e=>e!==`model`&&e!==`maxTokens`&&e!==`thinkingLevel`&&e!==`timeoutMs`);if(n!==void 0)throw new te(`configError.sessionNaming.unknownKey`,`PI WEB config sessionNaming has unknown key {key}: {source}`,{key:JSON.stringify(n),source:t});let r=e.model,i=e.maxTokens,a=e.thinkingLevel,o=e.timeoutMs;if(r!==void 0&&(typeof r!=`string`||!/^[^/\s]+\/\S+$/.test(r)))throw new te(`configError.sessionNaming.model`,`PI WEB config sessionNaming.model must be an exact provider/model-id with non-empty parts: {source}`,{source:t});if(i!==void 0&&(typeof i!=`number`||!Number.isSafeInteger(i)||i<=0))throw new te(`configError.sessionNaming.maxTokens`,`PI WEB config sessionNaming.maxTokens must be a positive safe integer: {source}`,{source:t});if(a!==void 0&&(typeof a!=`string`||!Xt(a)))throw new te(`configError.sessionNaming.thinkingLevel`,`PI WEB config sessionNaming.thinkingLevel must be a known thinking level: {source}`,{source:t});if(o!==void 0&&(typeof o!=`number`||!Number.isInteger(o)||o<1||o>2147483647))throw new te(`configError.sessionNaming.timeoutMs`,`PI WEB config sessionNaming.timeoutMs must be an integer from 1 to 2147483647: {source}`,{source:t});return{...r===void 0?{}:{model:r},...i===void 0?{}:{maxTokens:i},...a===void 0?{}:{thinkingLevel:a},...o===void 0?{}:{timeoutMs:o}}}function bn(e,t){if(!vn(e))throw new te(`configError.sessionArchive.object`,`PI WEB config sessionArchive must be an object: {source}`,{source:t});let n=Object.keys(e).find(e=>e!==`directory`);if(n!==void 0)throw new te(`configError.sessionArchive.unknownKey`,`PI WEB config sessionArchive has unknown key {key}: {source}`,{key:JSON.stringify(n),source:t});let r=e.directory;if(r===void 0)return{};if(typeof r!=`string`||r.trim()===``||r.includes(`\0`))throw new te(`configError.sessionArchive.directory`,`PI WEB config sessionArchive.directory must be a non-empty path: {source}`,{source:t});return{directory:r}}var xn=new Set([`schemaVersion`,`dir`]);function Sn(e){if(!Tn(e)||Object.keys(e).some(e=>!xn.has(e)))return;let t=e.schemaVersion,n=e.dir;if(t===2&&typeof n==`string`&&Cn(n))return Object.freeze({schemaVersion:2,dir:n})}function Cn(e){if(e===``||e!==e.trim()||wn(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function wn(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Tn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var En=Object.values(m),Dn=new Set(En);m.sessionsDeleteArchived,m.sessionsBulkMutations,m.sessionsCleanup,m.sessionsReload,m.sessionsClearQueue,m.sessionsQueueMessageActions,m.sessionsPersistedState,m.sessionsNotifications,m.sessionsUnread,m.sessionsAskUser,m.promptAttachments,m.workspaceFileSuggestions,m.piPackagesManage,m.selectedMachineSettings,m.agentProfileConfig,m.pluginLifecycle,m.sessionsDeleteArchived,m.sessionsBulkMutations,m.sessionsCleanup,m.sessionsReload,m.sessionsClearQueue,m.sessionsQueueMessageActions,m.sessionsPersistedState,m.sessionsNotifications,m.sessionsUnread,m.sessionsAskUser,m.promptAttachments,m.sessionsDeleteArchived,m.sessionsBulkMutations,m.sessionsCleanup,m.sessionsReload,m.sessionsClearQueue,m.sessionsQueueMessageActions,m.sessionsPersistedState,m.sessionsNotifications,m.sessionsUnread,m.sessionsAskUser,m.promptAttachments,m.workspaceFileSuggestions,m.piPackagesManage,m.selectedMachineSettings,m.agentProfileConfig,m.pluginLifecycle;function On(e){return typeof e==`string`&&Dn.has(e)}function kn(e,t){return e?.capabilities?.includes(t)===!0}function An(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e.filter(On)}function jn(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!Mn(n))continue;let e=n.source,r=n.name,i=n.replacement;(e===`environment`||e===`config`)&&typeof r==`string`&&r!==``&&(i===void 0||typeof i==`string`&&i!==``)&&t.push({source:e,name:r,...i===void 0?{}:{replacement:i}})}return t}function Mn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Nn=[`projectId`,`workspaceId`,`sessionId`];function Pn(e,t){if(!In(e))throw Error(`${t} must be an object`);let n=!1;for(let r in e)if(Object.hasOwn(e,r)&&(n=!0,!Fn(r)))throw Error(`Unsupported ${t} field: ${r}`);if(!n)throw Error(`${t} must contain at least one of projectId, workspaceId, or sessionId`);let r={};for(let n of Nn){if(!Object.hasOwn(e,n))continue;let i=e[n];if(typeof i!=`string`||i.length>512||i.trim()===``)throw Error(`${t} ${n} must be a non-empty string of at most 512 characters`);r[n]=i}if(r.projectId!==void 0)return Object.freeze({...r,projectId:r.projectId});if(r.workspaceId!==void 0)return Object.freeze({...r,workspaceId:r.workspaceId});if(r.sessionId!==void 0)return Object.freeze({...r,sessionId:r.sessionId});throw Error(`${t} must contain at least one visibility selector`)}function Fn(e){return Nn.some(t=>t===e)}function In(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var Ln={working:`core:working`,terminal:`core:terminal`,unread:`core:unread`};function Rn(e){if(!Vn(e))return;let t=e.epochId,n=e.revision,r=e.generatedAt,i=zn(e.machine),a=zn(e.unattributed),o=Bn(e.projects),s=Bn(e.workspaces);if(typeof t!=`string`||t===``||typeof n!=`number`||!Number.isFinite(n)||typeof r!=`string`||r===``||i===void 0||a===void 0||o===void 0||s===void 0)return;let c={epochId:t,revision:n,machine:i,projects:o,workspaces:s,unattributed:a,generatedAt:r};if(Object.hasOwn(e,`sessions`)){let t=Bn(e.sessions,!0);if(t===void 0)return;c.sessions=t}return c}function zn(e){if(!Vn(e))return;let t=new Map;for(let[n,r]of Object.entries(e))typeof r==`boolean`&&t.set(n,r);return Object.fromEntries(t)}function Bn(e,t=!1){if(!Vn(e))return;let n=new Map;for(let[r,i]of Object.entries(e)){let e=zn(i);if(e===void 0&&t)return;e!==void 0&&n.set(r,e)}return Object.fromEntries(n)}function Vn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Hn=Object.freeze({showSafeStart:`pi-web plugins safe-start show`,bundledOnly:`pi-web plugins safe-start set bundled-only --restart`,noServerPlugins:`pi-web plugins safe-start set none --restart`,clearSafeStart:`pi-web plugins safe-start clear --restart`});function Un(e){if(!i(e))throw Error(`Invalid PI WEB plugin id: ${e}`);return`pi-web plugins disable ${e} --restart`}function Wn(e){return typeof e==`object`&&!!e}function O(e){if(!Wn(e))throw Error(`Expected object response`);return e}function k(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function A(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function Gn(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function j(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function M(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function Kn(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e.map(e=>{if(typeof e==`object`&&e&&`entryId`in e&&e.entryId!==void 0&&typeof e.entryId!=`string`)throw Error(`Expected string field: entryId`);return e})}function qn(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function Jn(e){let t=O(e),n=t.leafId;if(n!=null&&typeof n!=`string`)throw Error(`Expected optional string|null field: leafId`);return{messages:Kn(t.messages),start:Gn(t,`start`),total:Gn(t,`total`),...N(`leafId`,n)}}function Yn(e){let t=O(e);return M(Xn)(t.machines)}function Xn(e){let t=O(e),n=er(t,`kind`),r=A(t,`baseUrl`),i=tr(t,`status`),a=A(t,`statusMessage`);return{id:k(t,`id`),name:k(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:k(t,`createdAt`),updatedAt:k(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function Zn(e){let t=O(e),n=tr(t,`status`),r=A(t,`error`);return{machineId:k(t,`machineId`),ok:j(t,`ok`),checkedAt:k(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:uo(t.web)},...t.sessiond===void 0?{}:{sessiond:uo(t.sessiond)},...r===void 0?{}:{error:r}}}function Qn(e){let t=O(e),n=A(t,`error`);return{machineId:k(t,`machineId`),ok:j(t,`ok`),checkedAt:k(t,`checkedAt`),...N(`packageName`,A(t,`packageName`)),...N(`generatedAt`,A(t,`generatedAt`)),...t.components===void 0?{}:{components:co(t.components)},...t.capabilities===void 0?{}:{capabilities:_o(t.capabilities)},...t.deprecatedAgentInputs===void 0?{}:{deprecatedAgentInputs:$n(t.deprecatedAgentInputs)},...n===void 0?{}:{error:n}}}function $n(e){let t=jn(e);if(t===void 0)throw Error(`Invalid PI WEB deprecated agent inputs`);return t}function er(e,t){let n=k(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function tr(e,t){let n=A(e,t);if(n!==void 0){if(n!==`unknown`&&n!==`online`&&n!==`offline`&&n!==`error`)throw Error(`Expected machine status field: ${t}`);return n}}function nr(e){let t=O(e);return{id:k(t,`id`),name:k(t,`name`),path:k(t,`path`),createdAt:k(t,`createdAt`)}}function rr(e){let t=O(e);return Object.freeze({id:k(t,`id`),projectId:k(t,`projectId`),path:k(t,`path`),label:k(t,`label`),isMain:j(t,`isMain`),...N(`branch`,A(t,`branch`)),...N(`isGitRepo`,Ho(t,`isGitRepo`)),...N(`isGitWorktree`,Ho(t,`isGitWorktree`)),...N(`provider`,lr(t.provider)),...N(`removal`,ur(t.removal)),effectiveConfig:pr(t.effectiveConfig)})}function ir(e){let t=O(e),n=ar(t.status),r=k(t,`projectId`),i=A(t,`ownerPluginId`);if(n===`provider`&&i===void 0)throw Error(`Provider workspace resolution is missing ownerPluginId`);if(n===`folder`&&i!==void 0)throw Error(`Folder workspace resolution must not include ownerPluginId`);let a=M(rr)(t.workspaces);if(a.length===0||a.some(e=>e.projectId!==r))throw Error(`Workspace resolution contains invalid project workspaces`);let o=M(or)(t.diagnostics);return Object.freeze({status:n,projectId:r,...i===void 0?{}:{ownerPluginId:i},workspaces:Object.freeze(a),diagnostics:Object.freeze(o)})}function ar(e){if(e===`provider`||e===`folder`||e===`degraded`)return e;throw Error(`Invalid workspace provider resolution status`)}function or(e){let t=O(e),n=A(t,`pluginId`),r=t.pluginIds===void 0?void 0:qn(t.pluginIds,`pluginIds`);return Object.freeze({code:sr(t.code),message:k(t,`message`),tier:cr(t.tier),...n===void 0?{}:{pluginId:n},...r===void 0?{}:{pluginIds:Object.freeze(r)}})}function sr(e){if(e===`probe-failed`||e===`claim-conflict`||e===`list-failed`)return e;throw Error(`Invalid workspace provider diagnostic code`)}function cr(e){if(e===`primary`||e===`fallback`)return e;throw Error(`Invalid workspace provider diagnostic tier`)}function lr(e){if(e===void 0)return;if(!Wn(e)||Array.isArray(e))throw Error(`Invalid workspace provider field`);let t=e.capabilities;if(!Wn(t)||Array.isArray(t))throw Error(`Invalid workspace provider capabilities field`);let n=e.metadata;return Object.freeze({pluginId:k(e,`pluginId`),capabilities:Object.freeze({remove:j(t,`remove`),...N(`request`,Ho(t,`request`))}),...N(`metadata`,n===void 0?void 0:dr(n,`workspace provider metadata`))})}function ur(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid workspace removal field`);return Object.freeze({actionLabel:wi(e,`actionLabel`),confirmation:wi(e,`confirmation`),precondition:wi(e,`precondition`)})}}function dr(e,t){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid ${t} field`);return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,n])=>[e,fr(n,t)])))}function fr(e,t){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(Array.isArray(e))return Object.freeze(e.map(e=>fr(e,t)));if(Wn(e))return dr(e,t);throw Error(`Invalid ${t} field`)}function pr(e){if(!Wn(e)||Array.isArray(e))throw Error(`Expected workspace effectiveConfig field`);let t=Na(e.uploads),n=Pa(e.attachments);return Object.freeze({...N(`uploads`,t===void 0?void 0:Object.freeze({...t})),...N(`attachments`,n===void 0?void 0:Object.freeze({...n}))})}function mr(e){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid session metadata field`);return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,dr(t,`session metadata namespace`)])))}function hr(e){let t=O(e),n=A(t,`name`),r=t.metadata===void 0?void 0:mr(t.metadata),i=io(t.persisted,`persisted`),a=A(t,`parentSessionPath`),o=A(t,`archivedAt`);return{id:k(t,`id`),path:k(t,`path`),cwd:k(t,`cwd`),...i===void 0?{}:{persisted:i},...n===void 0?{}:{name:n},...r===void 0?{}:{metadata:r},created:k(t,`created`),modified:k(t,`modified`),messageCount:Gn(t,`messageCount`),firstMessage:k(t,`firstMessage`),...a===void 0?{}:{parentSessionPath:a},...N(`agentSubsession`,Ho(t,`agentSubsession`)),...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function gr(e){let t=O(e);return{configured:j(t,`configured`),authenticated:j(t,`authenticated`)}}function _r(e){return{path:k(O(e),`path`)}}function vr(e){let t=O(e);if(t.deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0,path:k(t,`path`)}}function yr(e){return{sessionIds:qn(O(e).sessionIds,`sessionIds`)}}function br(e){return{pinned:j(O(e),`pinned`)}}function xr(e){let t=O(e);return{results:M(Sr)(t.results),matchCount:Gn(t,`matchCount`),truncated:j(t,`truncated`)}}function Sr(e){let t=O(e);return{session:hr(t.session),matches:M(Cr)(t.matches)}}function Cr(e){let t=O(e),n=k(t,`role`);if(n!==`user`&&n!==`assistant`)throw Error(`Invalid session content search role`);return{messageIndex:Gn(t,`messageIndex`),role:n,excerpts:M(wr)(t.excerpts),occurrenceCount:Gn(t,`occurrenceCount`)}}function wr(e){let t=O(e);return{text:k(t,`text`),matchRanges:M(e=>{let t=O(e);return{start:Gn(t,`start`),length:Gn(t,`length`)}})(t.matchRanges)}}function Tr(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function Er(e){if(e!==void 0)return{id:k(O(e),`id`)}}function Dr(e){let t=O(e),n=Er(t.dismiss);return{severity:Tr(t.severity),message:k(t,`message`),...N(`source`,A(t,`source`)),...N(`path`,A(t,`path`)),...n===void 0?{}:{dismiss:n}}}function Or(e){let t=`Recently active in another PI-WEB instance. Avoid working on this session in both instances at once.`;return e.severity===`info`&&e.source===`PI-WEB`&&(e.message===t||e.message===n(`ui.sessionActivity.message`,t))}function kr(e){let n=O(e);return{value:ai(n,`value`,128),label:ai(n,`label`,t),...N(`detail`,oi(n,`detail`,t))}}function Ar(e){let n=O(e),r=Si(n.options,kr,12,`options`);Ir(r.map(e=>e.value),`ask option value`),io(n.allowOther,`allowOther`);let i=io(n.multiple,`multiple`);return{id:ai(n,`id`,128),question:ai(n,`question`,t),...N(`detail`,oi(n,`detail`,t)),options:r,allowOther:!0,...i===void 0?{}:{multiple:i}}}function jr(e){let t=O(e),n=Si(t.questions,Ar,20,`questions`);if(n.length===0)throw Error(`Ask has no questions`);return Ir(n.map(e=>e.id),`ask question id`),{askId:ai(t,`askId`,128),askedAt:wi(t,`askedAt`),questions:n}}function Mr(e){if(e!==`submitted`&&e!==`superseded`&&e!==`cancelled`)throw Error(`Invalid ask close reason`);return e}function Nr(e){let t=O(e),n=Ar(t.question),r=Si(t.values,Ci,12,`values`),i=new Set(n.options.map(e=>e.value));if(r.some(e=>!i.has(e)))throw Error(`Ask answer selected an option the question never offered`);let a=oi(t,`otherText`,me),o=j(t,`answered`);if(o!==(r.length>0||a!==void 0))throw Error(`Ask answer contradicts its answered flag`);return{question:n,answered:o,values:r,...a===void 0?{}:{otherText:a}}}function Pr(e){let t=O(e),n=Si(t.questions,Nr,20,`questions`),r=Ti(t,`answeredCount`),i=qn(t.unansweredIds,`unansweredIds`),a=n.filter(e=>!e.answered).map(e=>e.question.id);if(r!==n.length-a.length)throw Error(`Ask outcome answered count mismatch`);if(i.length!==a.length||i.some((e,t)=>e!==a[t]))throw Error(`Ask outcome unanswered ids mismatch`);return{askId:ai(t,`askId`,128),reason:Mr(t.reason),askedAt:wi(t,`askedAt`),closedAt:wi(t,`closedAt`),questions:n,answeredCount:r,unansweredIds:i,summary:wi(t,`summary`)}}function Fr(e){let t=O(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid dialog close result`);let r=t.outcome===void 0?void 0:Gr(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Dialog close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:qr(t.sessionStatus)}}function Ir(e,t){if(new Set(e).size!==e.length)throw Error(`Duplicate ${t}`)}function Lr(e){if(e!==`confirm`&&e!==`select`&&e!==`input`)throw Error(`Invalid extension dialog kind`);return e}function Rr(e){if(e!==`answered`&&e!==`cancelled`&&e!==`timeout`&&e!==`aborted`&&e!==`session-ended`)throw Error(`Invalid extension dialog close reason`);return e}function zr(e){if(typeof e==`boolean`||typeof e==`string`&&e.length<=4e3)return e;throw Error(`Invalid extension dialog answer`)}function Br(e){let t=Ci(e);if(t.length>1e3)throw Error(`String field exceeds limit: option`);return t}function Vr(e){let t=O(e),n=Lr(t.kind),r=t.options===void 0?void 0:Si(t.options,Br,24,`options`);if(r!==void 0&&Ir(r,`dialog option`),n===`select`&&(r===void 0||r.length===0))throw Error(`Select dialog has no options`);return{dialogId:ai(t,`dialogId`,128),kind:n,title:ai(t,`title`,p),...N(`message`,oi(t,`message`,p)),...r===void 0?{}:{options:r},...N(`placeholder`,oi(t,`placeholder`,p)),askedAt:wi(t,`askedAt`),...N(`timeoutAt`,Kr(t,`timeoutAt`)),runScoped:j(t,`runScoped`)}}function Hr(e){if(e===void 0)return{};let t=M(Vr)(e);return Ir(t.map(e=>e.dialogId),`dialog id`),{pendingDialogs:t}}function Ur(e){let t=O(e);if(t.type!==`dialog.opened`)throw Error(`Invalid dialog opened event type`);return{type:`dialog.opened`,dialog:Vr(t.dialog)}}function Wr(e){let t=O(e);if(t.type!==`dialog.closed`)throw Error(`Invalid dialog closed event type`);let n=Rr(t.reason),r=t.answer===void 0?void 0:zr(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog closed event answer mismatch`);return{type:`dialog.closed`,dialogId:ai(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r}}}function Gr(e){let t=O(e),n=Rr(t.reason),r=t.answer===void 0?void 0:zr(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog outcome answer mismatch`);return{dialogId:ai(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r},askedAt:wi(t,`askedAt`),closedAt:wi(t,`closedAt`)}}function Kr(e,t){let n=A(e,t);if(n!==void 0){if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}}function qr(e){let t=O(e),n=t.warnings===void 0?void 0:M(Dr)(t.warnings),r=io(t.recentlyActiveElsewhere,`recentlyActiveElsewhere`);return{sessionId:k(t,`sessionId`),...N(`persisted`,io(t.persisted,`persisted`)),recentlyActiveElsewhere:r??n?.some(Or)??!1,isStreaming:j(t,`isStreaming`),isCompacting:j(t,`isCompacting`),isBashRunning:j(t,`isBashRunning`),pendingMessageCount:Gn(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:M(Ri)(t.queuedMessages),...N(`queueMessageActionsUnavailable`,A(t,`queueMessageActionsUnavailable`)),...N(`messageCount`,Uo(t,`messageCount`)),tokens:zi(t.tokens),cost:Gn(t,`cost`),...Vi(t.model),...ca(t.contextUsage),...N(`thinkingLevel`,A(t,`thinkingLevel`)),...N(`warnings`,n?.filter(e=>!Or(e))),...Hr(t.pendingDialogs),...N(`suggestedInput`,A(t,`suggestedInput`))}}function Jr(e){let t=O(e);return{seq:Gn(t,`seq`),partial:t.partial??null}}function Yr(e){let t=O(e);if(t.partial===void 0)throw Error(`Expected field: partial`);return{page:Jn(t.page),status:qr(t.status),seq:Ti(t,`seq`),partial:t.partial}}function Xr(e){let t=O(e),n=Ti(t,`catalogRevision`),r=Si(t.sessions,ni,f,`sessions`);if(ri(r),ii(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:ai(t,`catalogId`,512),catalogRevision:n,sessions:r}}function Zr(e){let t=O(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=ai(t,`sessionId`,512),r=ai(t,`cwd`,l),i=si(t,`catalogRevision`),a=t.unread===null?null:ni(t.unread);if(a!==null&&(a.sessionId!==n||a.cwd!==r))throw Error(`Session unread event identity mismatch`);if(a!==null&&a.completionOrder>i)throw Error(`Session unread completion order exceeds catalog revision`);return{type:`sessions.unread`,catalogId:ai(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function Qr(e){let t=O(e);if(t.type!==`session.startup`)throw Error(`Invalid session startup event type`);let n=A(t,`startupToken`);if(n===``)throw Error(`Expected non-empty string field: startupToken`);return{type:`session.startup`,...N(`startupToken`,n),activity:$r(t.activity)}}function $r(e){let t=O(e);return{sessionId:wi(t,`sessionId`),phase:ti(t,`phase`),label:wi(t,`label`),...N(`detail`,A(t,`detail`)),at:wi(t,`at`),...N(`startup`,ei(t))}}function ei(e){let t=e.startup;if(t!==void 0){if(typeof t!=`boolean`)throw Error(`Expected optional boolean field: startup`);return t}}function ti(e,t){let n=k(e,t);if(n!==`active`&&n!==`idle`&&n!==`error`)throw Error(`Expected session activity phase field: ${t}`);return n}function ni(e){let t=O(e),n=ai(t,`completedAt`,64),r=new Date(n);if(!Number.isFinite(r.getTime())||r.toISOString()!==n)throw Error(`Invalid canonical session unread completion time`);let i=t.messageRange===void 0?void 0:O(t.messageRange),a;if(i!==void 0){let e=Ti(i,`start`),t=Ti(i,`end`),n=i.leafId;if(t<e||n!==null&&typeof n!=`string`)throw Error(`Invalid unread message range`);a={start:e,end:t,leafId:n}}return{sessionId:ai(t,`sessionId`,512),cwd:ai(t,`cwd`,l),completionOrder:si(t,`completionOrder`),completedAt:n,...a===void 0?{}:{messageRange:a}}}function ri(e){let t=e.map(e=>JSON.stringify([e.sessionId,e.cwd]));if(new Set(t).size!==t.length)throw Error(`Duplicate session unread identity`);let n=e.map(e=>e.completionOrder);if(new Set(n).size!==n.length)throw Error(`Duplicate session unread completion order`)}function ii(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.completionOrder<=r.completionOrder)throw Error(`Session unread summaries are not newest-first`)}}function ai(e,t,n){let r=wi(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function oi(e,t,n){let r=A(e,t);if(r!==void 0){if(r===``)throw Error(`Expected non-empty string field: ${t}`);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}}function si(e,t){let n=Ti(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function ci(e){let t=O(e),n=hi(t.summary),r=Si(t.notifications,gi,100,`notifications`);if(Ei(r),Di(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==ki(r))throw Error(`Notification snapshot severity mismatch`);let i=_i(t.dismissThrough),a=r[0]?.order??0;if(i.order!==a)throw Error(`Notification snapshot dismiss cutoff mismatch`);if(i.overflowWatermark<n.discardedCount)throw Error(`Notification snapshot overflow cutoff mismatch`);return{daemonInstanceId:wi(t,`daemonInstanceId`),catalogRevision:Ti(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function li(e){let t=O(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=hi(t.summary),r=_i(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=vi(t.delta);if(i.kind===`cleared`&&!Oi(n))throw Error(`Notification clear event summary mismatch`);if(i.kind===`added`&&n.retainedCount===0)throw Error(`Notification add event summary mismatch`);return{type:`notifications.inbox`,daemonInstanceId:wi(t,`daemonInstanceId`),catalogRevision:Ti(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function ui(e){let t=O(e),n=M(pi)(t.notices),r=n.map(e=>e.id);if(new Set(r).size!==r.length)throw Error(`Duplicate server notice id`);return{daemonInstanceId:wi(t,`daemonInstanceId`),revision:Ti(t,`revision`),notices:n}}function di(e){let t=O(e);if(t.type!==`notices.updated`)throw Error(`Invalid server notice event type`);return{type:`notices.updated`,snapshot:ui(t.snapshot)}}function fi(e){let t=O(e);if(t.type!==`models.changed`)throw Error(`Invalid model scope event type`);return{type:`models.changed`,revision:Ti(t,`revision`)}}function pi(e){let t=O(e),n=wi(t,`createdAt`);if(!Number.isFinite(Date.parse(n)))throw Error(`Invalid server notice creation time`);let r=A(t,`source`),i=t.context===void 0?void 0:dr(t.context,`server notice context`),a=t.scope===void 0?void 0:Pn(t.scope,`server notice scope`);return{id:wi(t,`id`),severity:mi(t.severity),message:k(t,`message`),createdAt:n,...N(`source`,r),...N(`scope`,a),...N(`context`,i)}}function mi(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid server notice severity`);return e}function hi(e){let t=O(e),n=Ti(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=Ti(t,`discardedCount`),i=bi(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:wi(t,`sessionId`),cwd:wi(t,`cwd`),inboxRevision:Ti(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function gi(e){let t=O(e),n=k(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=k(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=Ti(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:wi(t,`id`),message:n,truncated:j(t,`truncated`),severity:yi(t.severity),receivedAt:r,order:i}}function _i(e){let t=O(e);return{order:Ti(t,`order`),overflowWatermark:Ti(t,`overflowWatermark`)}}function vi(e){let t=O(e);switch(t.kind){case`added`:{let e=A(t,`evictedNotificationId`);return{kind:`added`,notification:gi(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=Si(t.notificationIds,Ci,100,`notificationIds`);if(new Set(e).size!==e.length)throw Error(`Duplicate dismissed notification id`);return{kind:`dismissed`,notificationIds:e}}case`cleared`:return{kind:`cleared`,reason:xi(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function yi(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function bi(e){return e===void 0?void 0:yi(e)}function xi(e){switch(e){case`runtime-close`:case`archive`:case`delete`:case`restore`:case`archive-reconcile`:case`replacement`:case`initialization-failed`:case`service-dispose`:return e;default:throw Error(`Invalid notification clear reason`)}}function Si(e,t,n,r){if(!Array.isArray(e))throw Error(`Expected array field: ${r}`);if(e.length>n)throw Error(`Array field exceeds limit: ${r}`);return e.map(t)}function Ci(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function wi(e,t){let n=k(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function Ti(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Expected non-negative safe integer field: ${t}`);return n}function Ei(e){if(new Set(e.map(e=>e.id)).size!==e.length)throw Error(`Duplicate notification id`);if(new Set(e.map(e=>e.order)).size!==e.length)throw Error(`Duplicate notification order`)}function Di(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.order<=r.order)throw Error(`Notifications are not newest-first`)}}function Oi(e){return e.retainedCount===0&&e.discardedCount===0}function ki(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function Ai(e){let t=O(e),n=t.skippedBusySessionIds===void 0?void 0:qn(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:k(t,`generatedAt`),thresholds:Fi(t.thresholds),projects:M(Ii)(t.projects),totals:Li(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function ji(e){let t=O(e);return{...Ai(t),archivedSessionIds:qn(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:qn(t.deletedSessionIds,`deletedSessionIds`)}}function Mi(e){let t=O(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:qn(t.archivedSessionIds,`archivedSessionIds`),failures:M(Pi)(t.failures),generatedAt:k(t,`generatedAt`)}}function Ni(e){let t=O(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:qn(t.deletedSessionIds,`deletedSessionIds`),failures:M(Pi)(t.failures),generatedAt:k(t,`generatedAt`)}}function Pi(e){let t=O(e);return{sessionId:k(t,`sessionId`),error:k(t,`error`)}}function Fi(e){let t=O(e);return{...N(`archiveIdleDays`,Uo(t,`archiveIdleDays`)),...N(`deleteArchivedDays`,Uo(t,`deleteArchivedDays`))}}function Ii(e){let t=O(e);return{cwd:k(t,`cwd`),archiveCount:Gn(t,`archiveCount`),deleteCount:Gn(t,`deleteCount`)}}function Li(e){let t=O(e);return{archiveCount:Gn(t,`archiveCount`),deleteCount:Gn(t,`deleteCount`)}}function Ri(e){let t=O(e),n=k(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:k(t,`text`),...N(`hasAttachments`,Ho(t,`hasAttachments`)),...N(`attachmentCount`,t.attachmentCount===void 0?void 0:Ti(t,`attachmentCount`))}}function zi(e){let t=O(e);return{input:Gn(t,`input`),output:Gn(t,`output`),cacheRead:Gn(t,`cacheRead`),cacheWrite:Gn(t,`cacheWrite`),total:Gn(t,`total`)}}function Bi(e){let t=O(e);return{...N(`provider`,A(t,`provider`)),...N(`id`,A(t,`id`)),...N(`name`,A(t,`name`)),...N(`contextWindow`,Uo(t,`contextWindow`)),...N(`reasoning`,t.reasoning)}}function Vi(e){return e===void 0?{}:{model:Bi(e)}}function Hi(e){let t=O(e);return{models:M(Bi)(t.models)}}function Ui(e){let t=O(e);return{provider:k(t,`provider`),id:k(t,`id`),...N(`name`,A(t,`name`)),...N(`contextWindow`,Uo(t,`contextWindow`)),...N(`reasoning`,t.reasoning),enabled:j(t,`enabled`),...N(`editable`,Ho(t,`editable`)),...N(`catalogIndex`,t.catalogIndex===void 0?void 0:Ti(t,`catalogIndex`))}}function Wi(e){let t=O(e);return{models:M(Ui)(t.models)}}function Gi(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Ki(e){let t=O(e);return{levels:M(Gi)(t.levels)}}function qi(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Ji(e){if(e!==`stored`&&e!==`runtime`&&e!==`environment`&&e!==`fallback`&&e!==`models_json_key`&&e!==`models_json_command`)throw Error(`Invalid auth status source`);return e}function Yi(e){let t=O(e),n=t.source===void 0?void 0:Ji(t.source);return{configured:j(t,`configured`),...N(`source`,n),...N(`label`,A(t,`label`))}}function Xi(e){let t=O(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:k(t,`id`),name:k(t,`name`),authType:qi(t.authType),status:Yi(t.status),...n===void 0?{}:{loginFlow:n}}}function Zi(e){let t=O(e);return{providers:M(Xi)(t.providers)}}function Qi(e){let t=O(e);return{servers:M(e=>{let t=O(e);return{name:k(t,`name`),...N(`description`,A(t,`description`))}})(t.servers)}}function $i(e){let t=O(e),n=t.target;if(n!==void 0&&n!==`mcp`)throw Error(`Invalid login flow target`);let r=t.mcpMode;if(r!==void 0&&r!==`login`&&r!==`logout`)throw Error(`Invalid MCP authentication mode`);let i={flowId:k(t,`flowId`),providerId:k(t,`providerId`),providerName:k(t,`providerName`),...n===void 0?{}:{target:n},...r===void 0?{}:{mcpMode:r},...N(`cancelRequested`,Ho(t,`cancelRequested`)),status:ea(t.status),progress:M(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...N(`error`,A(t,`error`)),...N(`auth`,ta(t.auth)),...N(`prompt`,ra(t.prompt)),...N(`select`,aa(t.select)),...N(`info`,oa(t.info))};if(i.target===`mcp`&&i.auth!==void 0){let e=new URL(i.auth.url);if(e.protocol!==`https:`&&e.protocol!==`http:`)throw Error(`Invalid MCP authorization URL`)}return i}function ea(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function ta(e){if(e===void 0)return;let t=O(e);return{url:k(t,`url`),...N(`instructions`,A(t,`instructions`)),...N(`deviceCode`,na(t.deviceCode))}}function na(e){if(e===void 0)return;let t=O(e);return{userCode:k(t,`userCode`),...N(`intervalSeconds`,Uo(t,`intervalSeconds`)),...N(`expiresInSeconds`,Uo(t,`expiresInSeconds`))}}function ra(e){if(e===void 0)return;let t=O(e),n=A(t,`kind`);if(n!==void 0&&n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0&&n!==void 0?n===`manual`?`manual_code`:`text`:ia(t.promptType);return{requestId:k(t,`requestId`),message:k(t,`message`),...N(`kind`,n),promptType:r,...N(`placeholder`,A(t,`placeholder`)),...N(`allowEmpty`,Ho(t,`allowEmpty`))}}function ia(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function aa(e){if(e===void 0)return;let t=O(e);return{requestId:k(t,`requestId`),message:k(t,`message`),options:M(ko)(t.options)}}function oa(e){if(e!==void 0)return M(e=>{let t=O(e);return{message:k(t,`message`),...N(`links`,t.links===void 0?void 0:M(sa)(t.links))}})(e)}function sa(e){let t=O(e);return{url:k(t,`url`),...N(`label`,A(t,`label`))}}function ca(e){if(e===void 0)return{};let t=O(e);return{contextUsage:{tokens:Wo(t,`tokens`),contextWindow:Gn(t,`contextWindow`),percent:Wo(t,`percent`)}}}function la(e){let t=O(e),n=k(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:k(t,`name`),source:n,...N(`description`,A(t,`description`)),...N(`argumentHint`,A(t,`argumentHint`))}}function ua(e){let t=O(e),n=k(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:k(t,`path`),kind:n}}function da(e){let t=O(e);return{path:k(t,`path`),entries:M(ma)(t.entries),scannedAt:k(t,`scannedAt`),truncated:j(t,`truncated`)}}function fa(e){let t=O(e);return{results:M(pa)(t.results)}}function pa(e){let t=O(e),n=k(t,`path`),r=t.tree,i=t.error;if(r===void 0==(i===void 0))throw Error(`File tree batch result must contain exactly one of tree or error`);return r===void 0?{path:n,error:k(t,`error`)}:{path:n,tree:da(r)}}function ma(e){let t=O(e),n=k(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:k(t,`name`),path:k(t,`path`),type:n,...N(`size`,Uo(t,`size`)),...N(`modifiedAt`,A(t,`modifiedAt`))}}function ha(e){let t=O(e),n=k(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:k(t,`path`),...N(`language`,A(t,`language`)),...N(`mediaType`,ya(t.mediaType)),...N(`mimeType`,A(t,`mimeType`)),encoding:n,size:Gn(t,`size`),modifiedAt:k(t,`modifiedAt`),content:k(t,`content`),truncated:j(t,`truncated`),binary:j(t,`binary`)}}function ga(e){let t=O(e);return{path:k(t,`path`),size:Gn(t,`size`),modifiedAt:k(t,`modifiedAt`),created:j(t,`created`)}}function _a(e){let t=O(e);return{path:k(t,`path`),existed:j(t,`existed`)}}function va(e){let t=O(e);return{fromPath:k(t,`fromPath`),toPath:k(t,`toPath`),size:Gn(t,`size`),modifiedAt:k(t,`modifiedAt`)}}function ya(e){if(e!==void 0){if(e!==`image`&&e!==`html`&&e!==`pdf`&&e!==`markdown`)throw Error(`Invalid file media type`);return e}}function ba(e){let t=O(e);return{id:k(t,`id`),cwd:k(t,`cwd`),name:k(t,`name`),createdAt:k(t,`createdAt`),exited:j(t,`exited`),...N(`exitCode`,Uo(t,`exitCode`)),...N(`commandRunId`,A(t,`commandRunId`))}}function xa(e){let t=O(e);return{id:k(t,`id`),origin:k(t,`origin`),projectId:k(t,`projectId`),workspaceId:k(t,`workspaceId`),terminalId:k(t,`terminalId`),title:k(t,`title`),command:k(t,`command`),status:Sa(t.status),...N(`exitCode`,Uo(t,`exitCode`)),createdAt:k(t,`createdAt`),...N(`startedAt`,A(t,`startedAt`)),...N(`completedAt`,A(t,`completedAt`)),metadata:Ca(t.metadata,`metadata`)}}function Sa(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function Ca(e,t){let n=O(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected string record field: ${t}.${e}`);return[e,n]}))}function wa(e){let t=O(e);return{cwd:k(t,`cwd`),hasSessionActivity:j(t,`hasSessionActivity`),hasTerminalActivity:j(t,`hasTerminalActivity`),updatedAt:k(t,`updatedAt`)}}function Ta(e){let t=O(e);return{workspaces:M(wa)(t.workspaces),generatedAt:k(t,`generatedAt`)}}function Ea(e){let t=Rn(e);if(t===void 0)throw Error(`Expected machine status snapshot`);return t}function Da(e){let t=O(e);return{path:k(t,`path`),exists:j(t,`exists`),config:Oa(t.config),effectiveConfig:Oa(t.effectiveConfig),envOverrides:za(t.envOverrides)}}function Oa(e){let t=O(e);return{...N(`host`,A(t,`host`)),...N(`port`,Uo(t,`port`)),...N(`allowedHosts`,Aa(t.allowedHosts)),...N(`shortcuts`,La(t.shortcuts)),...N(`defaultTheme`,t.defaultTheme===void 0?void 0:gn(t.defaultTheme,`response`)),...N(`defaultStreamingBehavior`,t.defaultStreamingBehavior===void 0?void 0:_n(t.defaultStreamingBehavior,`response`)),...N(`plugins`,Ra(t.plugins)),...N(`pathAccess`,ja(t.pathAccess)),...N(`uploads`,Na(t.uploads)),...N(`attachments`,Pa(t.attachments)),...N(`maxUploadBytes`,Uo(t,`maxUploadBytes`)),...N(`agent`,ka(t.agent)),...N(`spawnSessions`,Ho(t,`spawnSessions`)),...N(`subsessions`,Ho(t,`subsessions`)),...N(`askUser`,Ho(t,`askUser`)),...N(`sessionNaming`,t.sessionNaming===void 0?void 0:yn(t.sessionNaming,`response`)),...N(`sessionArchive`,t.sessionArchive===void 0?void 0:bn(t.sessionArchive,`response`))}}function ka(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid PI WEB agent field`);return{...N(`command`,A(e,`command`)),...N(`dir`,A(e,`dir`))}}}function Aa(e){if(e!==void 0){if(e===!0)return!0;if(Fa(e))return e;throw Error(`Invalid PI WEB allowedHosts field`)}}function ja(e){if(e===void 0)return;if(!Wn(e))throw Error(`Invalid PI WEB pathAccess field`);let t=e.allowedPaths;return{...N(`allowedPaths`,Ma(t,`pathAccess.allowedPaths`))}}function Ma(e,t){if(e!==void 0){if(Ia(e))return e;throw Error(`Invalid PI WEB ${t} field`)}}function Na(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid PI WEB uploads field`);return{...N(`defaultFolder`,A(e,`defaultFolder`))}}}function Pa(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid PI WEB attachments field`);return{...N(`defaultFolder`,A(e,`defaultFolder`))}}}function Fa(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Ia(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function La(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid PI WEB shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEB shortcut field`);return[e,t]}))}}function Ra(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid PI WEB plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!Wn(t)||Array.isArray(t))throw Error(`Invalid PI WEB plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEB plugin enabled field`);let r=t.settings;if(r!==void 0&&(!Wn(r)||Array.isArray(r)))throw Error(`Invalid PI WEB plugin settings field`);return[e,t]}))}}function za(e){let t=O(e);return{host:j(t,`host`),port:j(t,`port`),allowedHosts:j(t,`allowedHosts`),spawnSessions:j(t,`spawnSessions`),subsessions:j(t,`subsessions`),askUser:j(t,`askUser`),agentCommand:Ho(t,`agentCommand`)??!1,agentDir:Ho(t,`agentDir`)??!1,...Ba(t),agentSessionDir:Ho(t,`agentSessionDir`)??!1}}function Ba(e){let t=e.agentDirSource;if(t===void 0)return{};if(t!==`pi-web`&&t!==`pi-compatibility`)throw Error(`Invalid PI WEB agentDirSource field`);return{agentDirSource:t}}function Va(e){let t=O(e);return{packages:M(Ua)(t.packages),...N(`installableKnownPackages`,Wa(t.installableKnownPackages))}}function Ha(e){let t=O(e),n=A(t,`source`),r=t.scope===void 0?void 0:Ka(t.scope),i=io(t.removed,`removed`);return{action:qa(t.action),...N(`source`,n),...N(`scope`,r),...N(`removed`,i),packages:M(Ua)(t.packages),...N(`installableKnownPackages`,Wa(t.installableKnownPackages))}}function Ua(e){let t=O(e);return{source:k(t,`source`),scope:Ka(t.scope),filtered:j(t,`filtered`),...N(`installedPath`,A(t,`installedPath`))}}function Wa(e){return e===void 0?void 0:M(Ga)(e)}function Ga(e){let t=O(e);return{id:k(t,`id`),label:k(t,`label`),description:k(t,`description`),source:k(t,`source`)}}function Ka(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function qa(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Ja(e){let t=O(e),r=M(Ya)(t.plugins);if(t.lifecycleVersion===void 0)return{lifecycleVersion:2,plugins:r,diagnostics:[],serverRuntime:{status:`incompatible`,terminalMode:`required`,restartRequired:!1,message:n(`ui.main.fe09b19a1f40`,`PI WEB does not support plugin lifecycle diagnostics. Update and restart PI WEB, then try again.`),recovery:to()}};if(t.lifecycleVersion!==2)throw Error(`Unsupported PI WEB plugin lifecycle version`);return{lifecycleVersion:2,plugins:r,diagnostics:M(Qa)(t.diagnostics),serverRuntime:$a(t.serverRuntime)}}function Ya(e){let t=O(e),n=k(t,`id`),r=t.server===void 0?void 0:Xa(t.server,n),i=A(t,`backendRevision`),a=no(t.pairedRequestVersion),o=no(t.pairedChannelVersion);if((a!==void 0||o!==void 0)&&i===void 0)throw Error(`Invalid PI WEB plugin paired capability`);let s=io(t.required,`required`);if(s===!1)throw Error(`Invalid PI WEB required plugin marker`);return{id:n,...s===!0?{required:!0}:{},...N(`module`,A(t,`module`)),...i===void 0?{}:{backendRevision:i},...a===void 0?{}:{pairedRequestVersion:a},...o===void 0?{}:{pairedChannelVersion:o},source:k(t,`source`),scope:ro(t.scope),machineSpecific:io(t.machineSpecific,`machineSpecific`)??!1,enabled:j(t,`enabled`),discovered:io(t.discovered,`discovered`)??!0,conflict:io(t.conflict,`conflict`)??!1,...r===void 0?{}:{server:r}}}function Xa(e,t){let n=O(e),r=n.state,i=n.phase;if(r!==`active`&&r!==`failed`&&r!==`incompatible`&&r!==`disabled`&&r!==`missing`&&r!==`unknown`)throw Error(`Invalid PI WEB server plugin state`);if(i!==void 0&&i!==`import`&&i!==`activate`&&i!==`validate`&&i!==`start`&&i!==`health`&&i!==`dispose`)throw Error(`Invalid PI WEB server plugin phase`);let a=n.health===void 0?void 0:Za(n.health),o=k(n,`disableCommand`);if(o!==Un(t))throw Error(`Invalid PI WEB server plugin recovery command`);return{state:r,...N(`desiredRevision`,A(n,`desiredRevision`)),...N(`activeRevision`,A(n,`activeRevision`)),...i===void 0?{}:{phase:i},...N(`message`,A(n,`message`)),...a===void 0?{}:{health:a},staleRevision:j(n,`staleRevision`),restartRequired:j(n,`restartRequired`),disableCommand:o}}function Za(e){let t=O(e),n=t.status;if(n!==`healthy`&&n!==`degraded`&&n!==`unhealthy`)throw Error(`Invalid PI WEB server plugin health status`);return{status:n,...N(`message`,A(t,`message`))}}function Qa(e){let t=O(e),n=t.kind,r=t.snapshot;if(n!==`conflict`&&n!==`discovery`)throw Error(`Invalid PI WEB plugin diagnostic kind`);if(r!==`desired`&&r!==`active`)throw Error(`Invalid PI WEB plugin diagnostic snapshot`);return{kind:n,snapshot:r,source:k(t,`source`),message:k(t,`message`),...N(`pluginId`,A(t,`pluginId`))}}function $a(e){let t=O(e),n=t.status,r=t.terminalMode,i=t.safeStart,a=t.desiredSafeStart;if(n!==`available`&&n!==`unavailable`&&n!==`incompatible`)throw Error(`Invalid PI WEB server-plugin runtime status`);if(r!==`required`&&r!==`recovery-disabled`)throw Error(`Invalid PI WEB Terminal plugin mode`);if(i!==void 0&&i!==`bundled-only`&&i!==`none`)throw Error(`Invalid PI WEB server-plugin safe-start state`);if(a!==void 0&&a!==`off`&&a!==`bundled-only`&&a!==`none`)throw Error(`Invalid desired PI WEB server-plugin safe-start state`);if(n!==`available`&&r===`recovery-disabled`)throw Error(`Unavailable PI WEB runtime cannot declare Terminal recovery mode`);if(i===`none`!=(r===`recovery-disabled`)&&n===`available`)throw Error(`PI WEB Terminal plugin mode does not match safe start`);return{status:n,terminalMode:r,...i===void 0?{}:{safeStart:i},...a===void 0?{}:{desiredSafeStart:a},restartRequired:j(t,`restartRequired`),...N(`message`,A(t,`message`)),recovery:eo(t.recovery)}}function eo(e){let t=O(e),n={showSafeStart:k(t,`showSafeStart`),bundledOnly:k(t,`bundledOnly`),noServerPlugins:k(t,`noServerPlugins`),clearSafeStart:k(t,`clearSafeStart`)};if(n.showSafeStart!==Hn.showSafeStart||n.bundledOnly!==Hn.bundledOnly||n.noServerPlugins!==Hn.noServerPlugins||n.clearSafeStart!==Hn.clearSafeStart)throw Error(`Invalid PI WEB server plugin recovery commands`);return n}function to(){return{...Hn}}function no(e){if(e!==void 0){if(e!==1)throw Error(`Invalid PI WEB plugin paired capability version`);return 1}}function ro(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEB plugin scope`);return e}function io(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function ao(e){let t=O(e);return{packageName:k(t,`packageName`),generatedAt:k(t,`generatedAt`),components:so(t.components),release:po(t.release),commands:mo(t.commands),messages:M(ho)(t.messages)}}function oo(e){let t=O(e);return{packageName:k(t,`packageName`),generatedAt:k(t,`generatedAt`),components:co(t.components),capabilities:_o(t.capabilities)}}function so(e){let t=O(e);return{web:uo(t.web),sessiond:uo(t.sessiond)}}function co(e){let t=O(e);return{web:lo(t.web),sessiond:lo(t.sessiond)}}function lo(e){let t=O(e),n=go(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:Sn(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:k(t,`label`),...N(`runtimeVersion`,A(t,`runtimeVersion`)),...N(`piVersion`,A(t,`piVersion`)),available:j(t,`available`),capabilities:_o(t.capabilities),...N(`activeAgentProfile`,i),...N(`deprecatedAgentInputs`,jn(t.deprecatedAgentInputs)),...N(`error`,A(t,`error`))}}function uo(e){let t=O(e);return{component:go(t.component),label:k(t,`label`),...N(`runtimeVersion`,A(t,`runtimeVersion`)),...N(`installedVersion`,A(t,`installedVersion`)),...N(`piVersion`,A(t,`piVersion`)),stale:j(t,`stale`),available:j(t,`available`),...N(`installation`,fo(t.installation)),...N(`error`,A(t,`error`))}}function fo(e){if(e===void 0)return;let t=O(e),n=k(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEB installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEB installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEB Docker mode`);return{kind:n,...N(`path`,A(t,`path`)),...N(`source`,A(t,`source`)),...r===void 0?{}:{scope:r},...N(`npmRoot`,A(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function po(e){let t=O(e);return{packageName:k(t,`packageName`),...N(`latestVersion`,A(t,`latestVersion`)),updateAvailable:j(t,`updateAvailable`),...N(`checkedAt`,A(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...N(`error`,A(t,`error`))}}function mo(e){let t=O(e);return{...N(`update`,A(t,`update`)),...N(`restart`,A(t,`restart`)),...N(`restartWeb`,A(t,`restartWeb`)),...N(`restartSessiond`,A(t,`restartSessiond`)),...N(`status`,A(t,`status`))}}function ho(e){let t=O(e);return{id:k(t,`id`),severity:vo(t.severity),title:k(t,`title`),body:k(t,`body`),...N(`command`,A(t,`command`))}}function go(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEB service component`);return e}function _o(e){let t=An(e);if(t===void 0)throw Error(`Invalid PI WEB capabilities`);return t}function vo(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEB status severity`);return e}function yo(e){let t=O(e),n=k(t,`type`);if(n===`unsupported`)return{type:n,message:k(t,`message`)};if(n===`select`)return{type:n,requestId:k(t,`requestId`),title:k(t,`title`),options:M(ko)(t.options)};if(n===`tree`)return{type:n,tree:bo(t.tree)};if(n===`done`)return{type:n,...N(`message`,A(t,`message`)),...Ao(t.session),...N(`promptDraft`,A(t,`promptDraft`))};throw Error(`Invalid command result type`)}function bo(e){let t=O(e),n=M(xo)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=Eo(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:Oo(t.activePathIds,`activePathIds`)}}function xo(e){let t=O(e);return{id:Do(t,`id`),parentId:Eo(t,`parentId`),kind:So(t.kind),summary:k(t,`summary`),...N(`timestamp`,A(t,`timestamp`)),...N(`label`,A(t,`label`))}}function So(e){switch(e){case`user`:case`assistant`:case`tool-result`:case`bash`:case`custom-message`:case`compaction`:case`branch-summary`:case`model-change`:case`thinking-level-change`:case`session-info`:case`label`:case`custom`:case`other`:return e;default:throw Error(`Invalid session tree node kind`)}}function Co(e){let t=O(e),n=j(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){To(t,`editorText`,`session tree cancellation result`);let e=t.aborted;if(e!==void 0&&typeof e!=`boolean`)throw Error(`Expected optional boolean field: aborted`);return{cancelled:n,...e===void 0?{}:{aborted:e}}}return To(t,`aborted`,`session tree navigation result`),{cancelled:n,...N(`editorText`,A(t,`editorText`))}}function wo(e){let t=O(e),n=j(t,`cancelled`);return n?(To(t,`session`,`session tree fork cancellation result`),To(t,`promptDraft`,`session tree fork cancellation result`),{cancelled:n}):{cancelled:n,session:hr(t.session),...N(`promptDraft`,A(t,`promptDraft`))}}function To(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function Eo(e,t){let n=e[t];if(n!==null&&typeof n!=`string`)throw Error(`Expected string or null field: ${t}`);if(typeof n==`string`&&n.trim()===``)throw Error(`Expected non-blank string or null field: ${t}`);return n}function Do(e,t){let n=k(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function Oo(e,t){let n=qn(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function ko(e){let t=O(e);return{value:k(t,`value`),label:k(t,`label`),...N(`description`,A(t,`description`))}}function Ao(e){return e===void 0?{}:{session:hr(e)}}function jo(e){if(O(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function Mo(e){let t=O(e);return M(No)(t.attachments)}function No(e){let t=O(e);return{path:k(t,`path`),mimeType:k(t,`mimeType`),size:Gn(t,`size`)}}function Po(e){if(O(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function Fo(e){if(O(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function Io(e){if(O(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function Lo(e){let t=O(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:qn(t.sessionIds,`sessionIds`),r=Uo(t,`archivedCount`),i=Uo(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function Ro(e){if(O(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function zo(e){if(O(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function Bo(e){if(O(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function Vo(e){if(O(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function Ho(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEB ${t} field`);return n}}function Uo(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function Wo(e,t){let n=e[t];if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected number|null field: ${t}`);return n}function N(e,t){return t===void 0?{}:{[e]:t}}function Go(e){let t=O(e);switch(t.type){case`message.append`:return{type:`message.append`,message:qo(t,`message`)};case`assistant.start`:return{type:`assistant.start`,message:qo(t,`message`)};case`assistant.delta`:return{type:`assistant.delta`,text:k(t,`text`),...N(`streamId`,A(t,`streamId`))};case`assistant.thinking.delta`:return{type:`assistant.thinking.delta`,text:k(t,`text`),...N(`streamId`,A(t,`streamId`))};case`tool.start`:return{type:`tool.start`,toolName:k(t,`toolName`),toolCallId:k(t,`toolCallId`),summary:k(t,`summary`),...N(`args`,t.args)};case`tool.update`:return{type:`tool.update`,toolName:k(t,`toolName`),toolCallId:k(t,`toolCallId`),text:k(t,`text`),...N(`content`,t.content),...N(`details`,t.details)};case`tool.end`:return{type:`tool.end`,toolName:k(t,`toolName`),toolCallId:k(t,`toolCallId`),text:k(t,`text`),isError:j(t,`isError`),...N(`content`,t.content),...N(`details`,t.details)};case`shell.start`:return{type:`shell.start`,command:k(t,`command`),...N(`excludeFromContext`,io(t.excludeFromContext,`excludeFromContext`))};case`shell.chunk`:return{type:`shell.chunk`,chunk:k(t,`chunk`)};case`shell.end`:return{type:`shell.end`,...N(`output`,A(t,`output`)),...N(`exitCode`,Jo(t,`exitCode`)),...N(`cancelled`,io(t.cancelled,`cancelled`)),...N(`truncated`,io(t.truncated,`truncated`)),...N(`fullOutputPath`,A(t,`fullOutputPath`)),...N(`isError`,io(t.isError,`isError`))};case`agent.start`:return{type:`agent.start`};case`agent.end`:return{type:`agent.end`};case`message.end`:return{type:`message.end`,...N(`message`,t.message)};case`status.update`:return{type:`status.update`,status:qr(t.status)};case`activity.update`:return{type:`activity.update`,activity:$r(t.activity)};case`command.output`:return Yo(t);case`session.error`:return{type:`session.error`,message:k(t,`message`)};case`session.diagnostic`:return{type:`session.diagnostic`,message:k(t,`message`)};case`session.name`:return Xo(t);case`session.created`:return{type:`session.created`,session:hr(t.session)};case`session.tree.changed`:return{type:`session.tree.changed`};case`pi.event`:return{type:`pi.event`,eventType:k(t,`eventType`)};default:throw Error(`Unsupported session stream event type`)}}function Ko(e){let t=O(e);switch(t.type){case`status.update`:return{type:`status.update`,status:qr(t.status)};case`activity.update`:return{type:`activity.update`,activity:$r(t.activity)};case`session.name`:return Xo(t);case`session.created`:return{type:`session.created`,session:hr(t.session)};case`models.changed`:return fi(t);case`workspaces.changed`:return{type:`workspaces.changed`,projectId:wi(t,`projectId`)};case`notices.updated`:return di(t);case`machine.status`:return{type:`machine.status`,status:Ea(t.status)};default:throw Error(`Unsupported realtime stream event type`)}}function qo(e,t){let n=e[t];if(n===void 0)throw Error(`Expected field: ${t}`);return n}function Jo(e,t){let n=e[t];if(n!==void 0){if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected optional number|null field: ${t}`);return n}}function Yo(e){let t=k(e,`level`);if(t!==`info`&&t!==`success`&&t!==`error`)throw Error(`Invalid command output level`);return{type:`command.output`,level:t,message:k(e,`message`),...N(`notificationId`,A(e,`notificationId`))}}function Xo(e){return{type:`session.name`,sessionId:wi(e,`sessionId`),...N(`name`,A(e,`name`))}}function Zo(e){let t=O(e),n=t.decision;if(n!==!0&&n!==!1&&n!==null)throw Error(`Invalid workspace trust decision`);return{path:k(t,`path`),decision:n,trusted:j(t,`trusted`)}}function Qo(e,t){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0&&typeof t==`number`&&Number.isSafeInteger(t)&&t>0?{width:e,height:t}:void 0}var $o=`reference`;function es(e){return typeof e==`string`&&/^[0-9a-f]{64}$/u.test(e)}function ts(e,t,n,r){let i=new URLSearchParams({cwd:e.cwd});return n?.limit!==void 0&&i.set(`limit`,String(n.limit)),n?.before!==void 0&&i.set(`before`,String(n.before)),i.set(`media`,$o),`api/machines/${encodeURIComponent(r)}/sessions/${encodeURIComponent(e.id)}/${t}?${i.toString()}`}function ns(e,t,n=`local`){return ts(e,`messages`,t,n)}function rs(e,t,n=`local`){return ts(e,`transcript-snapshot`,t,n)}function is(e,t=`local`){return ts(e,`stream-snapshot`,void 0,t)}function as(e,t=`local`){return ts(e,`events`,void 0,t)}function os(e,t,n=`local`){let r=new URLSearchParams({cwd:e.cwd}),i=`api/machines/${encodeURIComponent(n)}/sessions/${encodeURIComponent(e.id)}/media/${encodeURIComponent(t)}?${r.toString()}`,a=y(i);return new URL(Ce(a),a).href}function ss(e,t,n,r){let i=new URLSearchParams({path:n});r?.createDirs===!1&&i.set(`createDirs`,`false`),r?.overwrite===!1&&i.set(`overwrite`,`false`);let a=`api/machines/${encodeURIComponent(r?.machineId??`local`)}`;return y(Ce(`${a}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`))}function cs(e,t,n,r){let i=new URLSearchParams;i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),r?.download===!0&&i.set(`download`,`1`);let a=`api/machines/${encodeURIComponent(r?.machineId??`local`)}`;return Ce(`${a}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}function ls(e,t,n,r){return y(cs(e,t,n,r))}function us(e,t,n,r){return ls(e,t,n,{...r,download:!0})}var P=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`,ds={projectTrust:(e,t=`local`)=>D(`${P(t)}/projects/trust?${new URLSearchParams({path:e})}`,Zo),workspaceTrust:(e,t,n=`local`)=>D(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/trust`,Zo),setWorkspaceTrust:(e,t,n,r=`local`)=>D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/trust`,Zo,{method:`PUT`,body:JSON.stringify({trusted:n})})};function fs(e,t=`local`){return`${P(t)}/sessions/${encodeURIComponent(e.id)}`}function F(e,t,n=`local`){return`${fs(e,n)}/${t}`}function ps(e,t,n=`local`){return`${F(e,t,n)}${hs(e)}`}function ms(e,t=`local`,n){return`${fs(e,t)}${hs(e,n===void 0?{}:{scopeProjectId:n})}`}function hs(e,t={}){return`?${new URLSearchParams({cwd:e.cwd,...t}).toString()}`}function I(e,t={}){return JSON.stringify({cwd:e.cwd,...t})}function gs(e,t){let n={sessions:e.map(({id:e,cwd:t})=>({id:e,cwd:t})),...t===void 0?{}:{scopeProjectId:t}};return JSON.stringify(n)}function _s(e,t){let n=new URLSearchParams;t.projectId!==void 0&&n.set(`projectId`,t.projectId);let r=n.toString();return`${P(t.machineId)}/auth/${e}${r===``?``:`?${r}`}`}function vs(e){return e===`local`?`api/pi-web/status`:`${P(e)}/pi-web/status`}var ys={piWebStatus:(e=`local`)=>D(vs(e),ao),checkForUpdates:(e=`local`)=>D(`${vs(e)}?refresh=1`,ao,{cache:`no-store`}),piWebRuntime:()=>D(`api/pi-web/runtime`,oo)},bs={machines:()=>D(`api/machines`,Yn),addMachine:e=>D(`api/machines`,Xn,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>D(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>D(`api/machines/${encodeURIComponent(e)}/health`,Zn),runtime:(e,t=!1)=>D(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,Qn,t?{cache:`no-store`}:{})};function xs(e){return e===void 0?`api/config`:`${P(e)}/config`}function Ss(e){return e===void 0?`api/plugins`:`${P(e)}/plugins`}var Cs={namingModels:e=>{let t=new URLSearchParams;e.projectId!==void 0&&t.set(`projectId`,e.projectId);let n=t.toString();return D(`${P(e.machineId)}/models${n===``?``:`?${n}`}`,Hi)},config:e=>D(xs(e),Da),saveConfig:(e,t)=>D(xs(t),Da,{method:`PUT`,body:JSON.stringify({config:e})})},ws={status:()=>D(`api/normal-auth/status`,gr),setup:e=>D(`api/normal-auth/setup`,jo,{method:`POST`,body:JSON.stringify({password:e})}),login:e=>D(`api/normal-auth/login`,jo,{method:`POST`,body:JSON.stringify({password:e})}),changePassword:(e,t)=>D(`api/normal-auth/change-password`,jo,{method:`POST`,body:JSON.stringify({currentPassword:e,newPassword:t})})},Ts={plugins:e=>D(Ss(e),Ja)};function Es(e=``,t){let n=t===void 0?`api/pi-packages`:`${P(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var Ds={packages:e=>D(Es(``,e),Va),install:(e,t)=>{let n={source:e};return D(Es(`install`,t),Ha,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return D(Es(`remove`,n),Ha,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return D(Es(`update`,t),Ha,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}},Os={workspaceActivity:(e=`local`)=>D(`${P(e)}/activity`,Ta)},ks={machineStatus:(e=`local`)=>D(`${P(e)}/status`,Ea)},As={snapshot:(e=`local`)=>D(`${P(e)}/notices`,ui,{cache:`no-store`}),dismiss:(e,t,n)=>{let r={daemonInstanceId:t,noticeId:n};return D(`${P(e)}/notices/dismiss`,ui,{method:`POST`,body:JSON.stringify(r)})}},js={projects:(e=`local`)=>D(`${P(e)}/projects`,M(nr)),addProject:(e,t,n,r=`local`)=>D(`${P(r)}/projects`,nr,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>D(`${P(t)}/projects/${encodeURIComponent(e)}`,Po,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>D(`${P(t)}/project-directories?q=${encodeURIComponent(e)}`,M(ua))};function Ms(e,t,n,r,i,a=`local`){let o=new URLSearchParams({path:n});i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!1&&o.set(`overwrite`,`false`);let s=r instanceof Uint8Array,c=s?new Uint8Array(r):new TextEncoder().encode(r);return D(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,ga,{method:`PUT`,body:c,headers:{"Content-Type":s?`application/octet-stream`:`text/plain`}})}function Ns(e,t=`local`,n){return D(`${P(t)}/projects/${encodeURIComponent(e)}/workspaces`,t=>{let n=ir(t);if(n.projectId!==e)throw Error(`Workspace resolution project does not match request`);return n},n?.signal===void 0?void 0:{signal:n.signal})}var Ps={workspaceResolution:Ns,workspaces:async(e,t=`local`,n)=>fe()===`management`?D(`${P(t)}/projects/${encodeURIComponent(e)}/workspaces`,M(rr),n?.signal===void 0?void 0:{signal:n.signal}):[...(await Ns(e,t,n)).workspaces],deleteWorkspace:(e,t,n,r=`local`)=>{let i={precondition:n};return D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,e=>e,{method:`DELETE`,body:JSON.stringify(i)})},workspaceTree:(e,t,n=``,r=`local`,i)=>D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,da,i),workspaceTreeBatch:(e,t,n,r=`local`)=>{let i={paths:[...n]};return D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree/batch`,fa,{method:`POST`,body:JSON.stringify(i)})},workspaceFile:(e,t,n,r=`local`,i)=>D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,ha,i),optionalWorkspaceFile:(e,t,n,r=`local`)=>ln(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}&optional=true`,ha),createWorkspaceFile:(e,t,n,r=`local`)=>Ms(e,t,n,new Uint8Array,void 0,r),writeWorkspaceFile:Ms,deleteWorkspaceFile:(e,t,n,r=`local`)=>{let i=new URLSearchParams({path:n});return D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,_a,{method:`DELETE`})},moveWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({fromPath:n,toPath:r});return i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!0&&o.set(`overwrite`,`true`),D(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,va,{method:`POST`})},createWorkspaceDirectory:(e,t,n,r=`local`)=>D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,_r,{method:`POST`,body:JSON.stringify({path:n})}),moveWorkspaceDirectory:(e,t,n,r,i=`local`)=>D(`${P(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,_r,{method:`PATCH`,body:JSON.stringify({fromPath:n,toPath:r})}),deleteWorkspaceDirectory:(e,t,n,r=`local`)=>D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(n)}`,vr,{method:`DELETE`}),downloadWorkspaceFile:(e,t,n,r=`local`)=>Us(e,t,n,r)},Fs={sessions:(e,t=`local`,n)=>D(`${P(t)}/sessions?cwd=${encodeURIComponent(e)}`,M(hr),n?.signal===void 0?void 0:{signal:n.signal}),search:(e,t,n=`local`)=>D(`${P(n)}/sessions/search?${new URLSearchParams({cwd:e,q:t}).toString()}`,M(hr)),searchContent:(e,t,n=`local`)=>D(`${P(n)}/sessions/search-content?${new URLSearchParams({cwd:e,q:t}).toString()}`,xr),pinned:(e,t=`local`)=>D(`${P(t)}/sessions/pins?cwd=${encodeURIComponent(e)}`,yr),pin:(e,t=`local`)=>D(`${fs(e,t)}/pin`,br,{method:`PUT`,body:I(e)}),unpin:(e,t=`local`)=>D(`${fs(e,t)}/pin${hs(e)}`,br,{method:`DELETE`}),unreadCatalog:(e=`local`)=>D(`${P(e)}/sessions/unread`,Xr,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return D(F(e,`unread/acknowledge`,r),Xr,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>D(ps(e,`notifications`,t),ci),dismissNotification:(e,t,n,r=`local`)=>D(F(e,`notifications/dismiss`,r),ci,{method:`POST`,body:I(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>D(F(e,`notifications/dismiss-all`,r),ci,{method:`POST`,body:I(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>D(`${P(t)}/sessions`,hr,{method:`POST`,body:JSON.stringify(n===void 0?{cwd:e}:{cwd:e,startupToken:n})}),cleanupPreview:(e,t=`local`)=>D(`${P(t)}/sessions/cleanup/preview`,Ai,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>D(`${P(t)}/sessions/cleanup`,ji,{method:`POST`,body:JSON.stringify(e)}),archiveMany:(e,t=`local`,n)=>D(`${P(t)}/sessions/bulk/archive`,Mi,{method:`POST`,body:gs(e,n)}),deleteArchivedMany:(e,t=`local`,n)=>D(`${P(t)}/sessions/bulk/delete-archived`,Ni,{method:`POST`,body:gs(e,n)}),messages:(e,t,n=`local`)=>D(ns(e,t,n),Jn),status:(e,t=`local`)=>D(ps(e,`status`,t),qr),streamSnapshot:(e,t=`local`)=>D(is(e,t),Jr),transcriptSnapshot:(e,t,n=`local`)=>D(rs(e,t,n),Yr),models:(e,t=`local`)=>D(ps(e,`models`,t),Hi),modelCatalog:(e,t=`local`)=>D(ps(e,`models/catalog`,t),Wi),setModelEnabled:(e,t,n,r,i=`local`)=>D(F(e,`models/enabled`,i),Wi,{method:`POST`,body:I(e,{provider:t,modelId:n,enabled:r})}),setModelScope:(e,t,n=`local`)=>D(F(e,`models/scope`,n),Wi,{method:`POST`,body:I(e,{mode:t})}),setModel:(e,t,n,r=`local`)=>D(F(e,`model`,r),qr,{method:`POST`,body:I(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>D(F(e,`model/cycle`,n),qr,{method:`POST`,body:I(e,{direction:t})}),getSessionDefaults:(e,t=`local`)=>D(ps(e,`defaults`,t),nn),setSessionDefaults:(e,t,n=`local`)=>D(F(e,`defaults`,n),nn,{method:`POST`,body:I(e,{...t})}),thinkingLevels:(e,t=`local`)=>D(ps(e,`thinking-levels`,t),Ki),setThinkingLevel:(e,t,n=`local`)=>D(F(e,`thinking-level`,n),qr,{method:`POST`,body:I(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>D(F(e,`thinking-level/cycle`,t),qr,{method:`POST`,body:I(e)}),commands:(e,t=`local`)=>D(ps(e,`commands`,t),M(la)),prompt:(e,t,n,r=`local`,i)=>D(F(e,`prompt`,r),jo,{method:`POST`,body:I(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>D(F(e,`attachments`,n),Mo,{method:`POST`,body:I(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>D(F(e,`shell`,n),jo,{method:`POST`,body:I(e,{text:t})}),runCommand:(e,t,n=`local`)=>D(F(e,`commands/run`,n),yo,{method:`POST`,body:I(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>D(F(e,`commands/respond`,r),yo,{method:`POST`,body:I(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>D(F(e,`tree/navigate`,n),Co,{method:`POST`,body:I(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary,...t.retainCheckpoint===void 0?{}:{retainCheckpoint:t.retainCheckpoint}})}),forkTree:(e,t,n=`local`)=>zs(e,t,n),abort:(e,t=`local`)=>D(F(e,`abort`,t),Fo,{method:`POST`,body:I(e)}),stop:(e,t=`local`)=>D(F(e,`stop`,t),Io,{method:`POST`,body:I(e)}),archive:(e,t=`local`,n)=>D(F(e,`archive`,t),Lo,{method:`POST`,body:I(e,n===void 0?{}:{scopeProjectId:n})}),archiveWithDescendants:(e,t=`local`,n)=>D(F(e,`archive-tree`,t),Lo,{method:`POST`,body:I(e,n===void 0?{}:{scopeProjectId:n})}),restore:(e,t=`local`,n)=>D(F(e,`restore`,t),Ro,{method:`POST`,body:I(e,n===void 0?{}:{scopeProjectId:n})}),deleteArchived:(e,t=`local`,n)=>D(ms(e,t,n),zo,{method:`DELETE`}),detachParent:(e,t=`local`)=>D(F(e,`detach-parent`,t),Bo,{method:`POST`,body:I(e)}),reloadSession:(e,t=`local`)=>D(F(e,`reload`,t),Vo,{method:`POST`,body:I(e)}),clearQueue:(e,t=`local`)=>D(F(e,`queue/clear`,t),qr,{method:`POST`,body:I(e)}),mutateQueuedMessage:(e,t,n=`local`)=>D(F(e,`queue/message`,n),qr,{method:`POST`,body:I(e,{...t})}),dismissWarning:(e,t,n=`local`)=>D(F(e,`warnings/dismiss`,n),qr,{method:`POST`,body:I(e,{dismissId:t})}),submitAsk:(e,t,n,r=`local`)=>D(F(e,`ask/submit`,r),qr,{method:`POST`,body:I(e,{askId:t,answers:n.answers})}),cancelAsk:(e,t,n=`local`)=>D(F(e,`ask/cancel`,n),qr,{method:`POST`,body:I(e,{askId:t})}),answerDialog:(e,t,n,r=`local`)=>D(F(e,`dialogs/answer`,r),Fr,{method:`POST`,body:I(e,{dialogId:t,value:n})}),cancelDialog:(e,t,n=`local`)=>D(F(e,`dialogs/cancel`,n),Fr,{method:`POST`,body:I(e,{dialogId:t})}),authProviders:e=>{let t=new URLSearchParams;e.mode!==void 0&&t.set(`mode`,e.mode),e.authType!==void 0&&t.set(`authType`,e.authType),e.projectId!==void 0&&t.set(`projectId`,e.projectId);let n=t.toString();return D(`${P(e.machineId)}/auth/providers${n===``?``:`?${n}`}`,Zi)},saveApiKey:(e,t,n)=>D(_s(`api-key`,n),jo,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t)=>D(_s(`api-key/interactive`,t),$i,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t)=>D(_s(`logout`,t),jo,{method:`POST`,body:JSON.stringify({providerId:e})}),mcpAuthServers:(e,t=`local`)=>D(ps(e,`mcp/auth/servers`,t),Qi),startMcpAuth:(e,t,n=`local`,r)=>D(F(e,`mcp/auth`,n),$i,{method:`POST`,body:I(e,{mode:t,...r===void 0?{}:{serverName:r}})}),mcpAuthFlow:(e,t=`local`)=>D(`${P(t)}/auth/mcp/${encodeURIComponent(e)}`,$i),respondMcpAuthFlow:(e,t,n,r=`local`)=>D(`${P(r)}/auth/mcp/${encodeURIComponent(e)}/respond`,$i,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelMcpAuthFlow:(e,t=`local`)=>D(`${P(t)}/auth/mcp/${encodeURIComponent(e)}/cancel`,$i,{method:`POST`}),startOAuthLogin:(e,t)=>D(_s(`oauth`,t),$i,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t)=>D(_s(`oauth/${encodeURIComponent(e)}`,t),$i),respondOAuthFlow:(e,t,n,r)=>D(_s(`oauth/${encodeURIComponent(e)}/respond`,r),$i,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t)=>D(_s(`oauth/${encodeURIComponent(e)}/cancel`,t),$i,{method:`POST`})},Is={runTerminalCommand:(e,t,n=`local`)=>D(`${P(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,xa,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`,n)=>D(`${P(t)}/terminal-command-runs${Vs(e)}`,M(xa),n?.signal===void 0?void 0:{signal:n.signal}),getCommandRun:(e,t=`local`)=>Ls(e,t),cancelCommandRun:(e,t=`local`)=>D(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,xa,{method:`POST`})};async function Ls(e,t){return ln(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}`,xa)}var Rs=class extends Error{constructor(){super(n(`ui.main.8501d1e756a4`,`Fork from the session tree is unavailable. Restart the session daemon to enable it.`)),this.name=`SessionTreeForkUnavailableError`}};async function zs(e,t,n){let r=await fetch(cn(F(e,`tree/fork`,n)),{method:`POST`,headers:{"content-type":`application/json`},body:I(e,{entryId:t.entryId,expectedLeafId:t.expectedLeafId,...t.retainCheckpoint===void 0?{}:{retainCheckpoint:t.retainCheckpoint}})});if(!r.ok){let e=await r.json().catch(()=>({}));throw Bs(r.status,e)?new Rs:Error(Hs(e)??r.statusText)}return wo(await r.json())}function Bs(e,t){if(e!==404||!Ws(t)||t.statusCode!==404||t.error!==`Not Found`)return!1;let n=t.message;return typeof n==`string`&&/^Route POST:.*\/tree\/fork not found$/i.test(n)}function Vs(e){if(e===void 0)return``;let t=new URLSearchParams;e.projectId!==void 0&&t.set(`projectId`,e.projectId),e.workspaceId!==void 0&&t.set(`workspaceId`,e.workspaceId),e.terminalId!==void 0&&t.set(`terminalId`,e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set(`statuses`,e.statuses.join(`,`)),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set(`metadata`,JSON.stringify(e.metadata));let n=t.toString();return n===``?``:`?${n}`}function Hs(e){if(!Ws(e))return;let t=e.error;return typeof t==`string`?t:void 0}async function Us(e,t,n,r){let i=await fetch(us(e,t,n,{machineId:r}));if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(Hs(e)??i.statusText)}let a=await i.blob(),o=URL.createObjectURL(a),s=document.createElement(`a`);s.href=o;let c=n.split(`/`).pop();s.download=c===void 0||c===``?`download`:c,document.body.append(s),s.click(),s.remove(),URL.revokeObjectURL(o)}function Ws(e){return typeof e==`object`&&!!e}var Gs={files:(e,t,n={})=>{let r=typeof t==`string`,i=r?e:``,a=r?t:e,o=r?n:t,s=new URLSearchParams({q:a});if(o.kind!==void 0&&s.set(`kind`,o.kind),o.mode!==void 0&&s.set(`mode`,o.mode),o.scope!==void 0&&s.set(`scope`,o.scope),(!r||o.workspaceScoped===!0)&&o.projectId!==void 0&&o.workspaceId!==void 0)return D(`${P(o.machineId)}/projects/${encodeURIComponent(o.projectId)}/workspaces/${encodeURIComponent(o.workspaceId)}/files?${s.toString()}`,M(ua),{signal:o.signal??null});if(!r)throw Error(`File suggestions require a project and workspace`);return s.set(`cwd`,i),D(`${P(o.machineId)}/files?${s.toString()}`,M(ua),{signal:o.signal??null})}},Ks={...ys,...bs,...As,...Cs,...ws,...Ts,...Ds,...Os,...ks,...js,...ds,...Ps,...Fs,...Gs,...Is};function qs(e,t=`local`,n=fe()){let r=typeof e==`string`?`${Ys(t)}/sessions/${encodeURIComponent(e)}/events`:as(e,t),i=se(r,void 0,n);return new WebSocket(ne(i))}function Js(e=`local`,t=fe()){let n=se(`${Ys(e)}/events`,void 0,t);return new WebSocket(ne(n))}function Ys(e){return`api/machines/${encodeURIComponent(e)}`}var Xs=`.pi-web/uploads`,Zs=class extends Error{constructor(e=n(`client.workspaceUploads.workspace.upload.cancelled.ac6723`,`Workspace upload cancelled`)){super(e),this.name=`WorkspaceUploadCancelledError`}};function Qs(e){return e?.uploads?.defaultFolder??`.pi-web/uploads`}function $s(e,t){return e?.uploads?.defaultFolder??t}function ec(e,t){let r=ac(e,n(`client.workspaceUploads.upload.destination.874cbb`,`Upload destination`),{allowEmpty:!0}),i=ac(t,n(`client.workspaceUploads.upload.filename.9252dd`,`Upload filename`),{allowEmpty:!1});return r===``?i:`${r}/${i}`}function tc(e,t,r,i={}){let a=i.xhrFactory?.()??new XMLHttpRequest,o=!1,s=!1;return{promise:new Promise((c,l)=>{let u=e=>{o||(o=!0,l(e))},d=e=>{o||(o=!0,c(e))};a.open(`PUT`,ss(e,t,r.path,nc(i)),!0),a.responseType=`json`,a.setRequestHeader(`Content-Type`,(r.contentType??r.file.type)||`application/octet-stream`),a.upload.onprogress=e=>{i.onProgress?.(rc(e,r.file.size))},a.onload=()=>{if(a.status>=200&&a.status<300)try{i.onProgress?.({loaded:r.file.size,total:r.file.size,percent:1,lengthComputable:!0}),d(ga(sc(a)))}catch(e){u(e instanceof Error?e:Error(String(e)))}else u(Error(cc(a)))},a.onerror=()=>{u(Error(n(`client.workspaceUploads.workspace.upload.failed.a87e6b`,`Workspace upload failed`)))},a.onabort=()=>{u(new Zs(s?void 0:n(`client.workspaceUploads.workspace.upload.aborted.58a455`,`Workspace upload aborted`)))},a.send(r.file)}),cancel:()=>{o||(s=!0,a.abort())}}}function nc(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function rc(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:ic(e.loaded,n),lengthComputable:e.lengthComputable}}function ic(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function ac(e,t,r){let i=e.trim();if(i===``){if(r.allowEmpty)return``;throw Error(n(`client.workspaceUploads.must.not.be.empty.b22cd8`,`{value1} must not be empty`,{value1:t}))}if(oc(i))throw Error(n(`client.workspaceUploads.must.be.a.workspace.relative.path.79fcd6`,`{value1} must be a workspace-relative path`,{value1:t}));let a=i.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(a.length===0){if(r.allowEmpty)return``;throw Error(n(`client.workspaceUploads.must.not.be.empty.b22cd8`,`{value1} must not be empty`,{value1:t}))}if(a.some(e=>e===`..`))throw Error(n(`client.workspaceUploads.must.not.contain.path.traversal.dac533`,`{value1} must not contain path traversal`,{value1:t}));return a.join(`/`)}function oc(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function sc(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function cc(e){let t=lc(e);return uc(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function lc(e){try{return sc(e)}catch{return}}function uc(e){return typeof e==`object`&&!!e}var dc=`.pi-web/attachments`;function fc(e){return e?.attachments?.defaultFolder??`.pi-web/attachments`}function pc(e,t){return e?.attachments?.defaultFolder??t}function mc(e,t){return bc(e,t)}function hc(e,t,n){let r=mc(e,t);return n===void 0?cn(r):y(Ce(r),n)}function gc(e,t){let n=mc(e,t),r=n.lastIndexOf(`/`);return`${n.slice(0,r)}/channels${n.slice(r)}`}function _c(e,t,n){let r=se(gc(e,t),void 0,fe());return n===void 0?ne(r):ne(r,n)}function vc(e,t,n,r={}){return Sc(e,t,n,r,hc)}function yc(e,t,n,i,a=e=>new WebSocket(e)){if(i.signal?.aborted===!0)return Promise.reject(Dc(i.signal));let o=De(e.backendRevision,n,xc(e)),s=_c(e,t),c;try{c=a(s)}catch(e){return Promise.reject(Error(`Plugin backend channel unavailable: ${Oc(e)}`,{cause:e}))}let l=!1,u=!1,d=0,f,p=()=>void 0,m=new Promise(e=>{p=e}),h=Object.freeze({closed:m,send(e){if(!l||u||c.readyState!==1)throw Error(`Plugin backend channel is not open`);let t=r(e),n=ee(t);if(c.bufferedAmount===0&&(d=0),d>=128||c.bufferedAmount+n>1048576){let e=Error(`Plugin backend channel browser queue limit was exceeded`);throw f=Object.freeze({code:`queue-overflow`,message:e.message}),wc(c,`Channel queue overflow`),e}try{c.send(t),d+=1}catch(e){throw f=Object.freeze({code:`send-failed`,message:Oc(e)}),wc(c,`Channel send failed`),e}},close(e=`Channel closed`){wc(c,oe(e))}});return new Promise((e,t)=>{let n=setTimeout(()=>{let e=Error(`Plugin backend channel open timed out after ${String(Te)}ms`);f=Object.freeze({code:`open-timeout`,message:e.message}),t(e),wc(c,`Channel open timed out`)},Te),r=()=>{let e=i.signal;if(e===void 0)return;let n=Dc(e);l||t(n),f=Object.freeze({code:`cancelled`,message:n.message}),wc(c,`Channel cancelled`)};i.signal?.addEventListener(`abort`,r,{once:!0}),c.addEventListener(`open`,()=>{try{c.send(o)}catch(e){t(Error(`Plugin backend channel unavailable: ${Oc(e)}`,{cause:e})),wc(c,`Channel open failed`)}}),c.addEventListener(`message`,r=>{try{if(typeof r.data!=`string`)throw Error(`Plugin backend channels accept text JSON frames only`);let a=Ee(r.data);if(a.kind===`ready`){if(l)throw Error(`Plugin backend channel sent more than one ready envelope`);l=!0,clearTimeout(n),e(h);return}if(a.kind===`error`){f=Object.freeze({code:a.code,message:a.message}),l||t(Error(a.message)),wc(c,`Channel failed`);return}if(!l)throw Error(`Plugin backend channel sent data before ready`);i.onData(a.data)}catch(e){f=Object.freeze({code:`protocol-error`,message:Oc(e)}),l||t(e instanceof Error?e:Error(String(e))),wc(c,`Channel protocol error`)}}),c.addEventListener(`error`,()=>{f??=Object.freeze({code:`transport-error`,message:`Plugin backend channel transport failed`}),l||t(Error(`Plugin backend channel unavailable`)),wc(c,`Channel transport error`)}),c.addEventListener(`close`,e=>{if(u)return;u=!0,clearTimeout(n),i.signal?.removeEventListener(`abort`,r),l||t(Error(f?.message??`Plugin backend channel closed before ready (${String(e.code)})`));let a=f??(e.code===1e3?void 0:Object.freeze({code:`channel-closed`,message:e.reason||`Plugin backend channel closed with code ${String(e.code)}`}));p(Object.freeze({code:e.code,reason:e.reason,wasClean:e.wasClean,...a===void 0?{}:{error:a}}))})})}function bc(e,t){if(!i(e.pluginId))throw Error(`Invalid PI WEB plugin id: ${e.pluginId}`);if(e.machineId===``)throw Error(`Machine id is required`);if(e.projectId===``)throw Error(`Project id is required`);if(e.workspaceId===``)throw Error(`Workspace id is required`);if(e.workspaceId!==void 0&&e.projectId===void 0)throw Error(`Workspace scope requires a project id`);ke(e,xc(e));let n=Oe(t);return`${e.machineId===`local`?`api`:`api/machines/${encodeURIComponent(e.machineId)}`}${ue({...e,operation:n})}`}function xc(e){return e.scope===void 0?{}:{scope:e.scope,...e.projectId===void 0?{}:{projectId:e.projectId},...e.workspaceId===void 0?{}:{workspaceId:e.workspaceId}}}async function Sc(e,t,n,r,i){let a=v(e.backendRevision),o=de(n,`Plugin backend request input`),s=JSON.stringify({revision:a,input:o,...xc(e)});if(ee(s)>266240)throw Error(`Plugin backend request exceeds the ${String(le)} byte wire limit`);let c;try{c=await fetch(i(e,t),{method:`POST`,headers:{"content-type":`application/json`},body:s,...r.signal===void 0?{}:{signal:r.signal}})}catch(e){throw r.signal?.aborted===!0?Dc(r.signal):Error(`Plugin backend request unavailable: ${Oc(e)}`,{cause:e})}let l=await Cc(c);if(!c.ok)throw Error(Ec(l)??`Plugin backend request returned HTTP ${String(c.status)}`);return ie(l,`Plugin backend response`,ge)}async function Cc(e){let t=e.headers.get(`content-length`);if(t!==null&&/^\d+$/u.test(t)&&Number(t)>8392704)throw await e.body?.cancel(),Error(`Plugin backend response exceeds the ${String(be)} byte wire limit`);if(e.body===null){let t=await e.text();if(ee(t)>8392704)throw Tc();return t}let n=e.body.getReader(),r=new TextDecoder,i=0,a=``;try{let e=await n.read();for(;!e.done;){if(i+=e.value.byteLength,i>8392704)throw await n.cancel(),Tc();a+=r.decode(e.value,{stream:!0}),e=await n.read()}return a+r.decode()}finally{n.releaseLock()}}function wc(e,t){if(e.readyState===0||e.readyState===1)try{e.close(1e3,oe(t))}catch{e.close()}}function Tc(){return Error(`Plugin backend response exceeds the ${String(be)} byte wire limit`)}function Ec(e){try{let t=JSON.parse(e);return kc(t)&&typeof t.error==`string`?t.error:void 0}catch{return}}function Dc(e){let t=e.reason;return t instanceof Error?t:new DOMException(`Plugin backend request cancelled`,`AbortError`)}function Oc(e){return e instanceof Error?e.message:String(e)}function kc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ac(){return{sessions:[],pinnedSessionIds:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,clientQueuedSessionMessages:{},startingSessionCount:0,selectedNotificationInbox:void 0,treeDialog:void 0,error:``}}function jc(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},machineStatusSnapshots:{},projects:[],workspaces:[],sessions:[],pinnedSessionIds:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,pendingTreeActions:[],treeDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:void 0,mainView:`chat`,piWebStatus:void 0,browserErrors:{},error:``}}function Mc(e){return{kind:`machine`,machineId:e}}function Nc(e,t){return{kind:`project`,machineId:e,projectId:t}}function Pc(e,t,n){return{kind:`workspace`,machineId:e,projectId:t,workspaceId:n}}function Fc(e,t,n={}){return{kind:`session`,machineId:e,sessionId:t,...n.cwd===void 0?{}:{cwd:n.cwd},...n.projectId===void 0?{}:{projectId:n.projectId},...n.workspaceId===void 0?{}:{workspaceId:n.workspaceId}}}function Ic(e){switch(e.kind){case`global`:return`global`;case`machine`:return JSON.stringify([e.kind,e.machineId]);case`project`:return JSON.stringify([e.kind,e.machineId,e.projectId]);case`workspace`:return JSON.stringify([e.kind,e.machineId,e.projectId,e.workspaceId]);case`session`:return JSON.stringify([e.kind,e.machineId,e.sessionId,e.cwd,e.projectId,e.workspaceId])}}function Lc(e,t,n,r){return{...e,[Ic(t)]:{scope:t,message:n,...r===void 0?{}:{recovery:r}}}}function Rc(e,t,n){let r=Ic(t),i=e[r];return i===void 0||n!==void 0&&i.message!==n?e:Object.fromEntries(Object.entries(e).filter(([e])=>e!==r))}function zc(e,t){let n=Object.fromEntries(Object.entries(e).filter(([,e])=>!Gc(e.scope,t)));return Object.keys(n).length===Object.keys(e).length?e:n}function Bc(e){let t=e.selectedSession;return{machineId:e.selectedMachine?.id??`local`,...e.selectedProject===void 0?{}:{projectId:e.selectedProject.id},...e.selectedWorkspace===void 0?{}:{workspaceId:e.selectedWorkspace.id},...t===void 0?{}:{sessionId:t.id,cwd:t.cwd}}}function Vc(e,t){return Object.values(e).filter(e=>Uc(e.scope,t)).sort((e,t)=>Wc(e.scope)-Wc(t.scope)||Ic(e.scope).localeCompare(Ic(t.scope)))}var Hc=class{constructor(e,t){this.getState=e,this.setState=t}report(e,t,n){this.setState({browserErrors:Lc(this.getState().browserErrors,e,t,n)})}captureRecovery(e,t){let n=this.getState().browserErrors[Ic(e)];return n?.recovery===t?n:void 0}clearRecovered(e){e?.recovery!==void 0&&this.getState().browserErrors[Ic(e.scope)]===e&&this.clear(e.scope)}clear(e,t){let n=this.getState().browserErrors,r=Rc(n,e,t);r!==n&&this.setState({browserErrors:r})}discard(e){let t=zc(this.getState().browserErrors,e);t!==this.getState().browserErrors&&this.setState({browserErrors:t})}};function Uc(e,t){return e.kind===`global`?!0:e.machineId===t.machineId?e.kind===`machine`?!0:e.kind===`project`?e.projectId===t.projectId:e.kind===`workspace`?e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.sessionId===t.sessionId&&(e.cwd===void 0||e.cwd===t.cwd)&&(e.projectId===void 0||e.projectId===t.projectId)&&(e.workspaceId===void 0||e.workspaceId===t.workspaceId):!1}function Wc(e){switch(e.kind){case`global`:return 0;case`machine`:return 1;case`project`:return 2;case`workspace`:return 3;case`session`:return 4}}function Gc(e,t){return t.kind===`global`?!0:e.kind===`global`||e.machineId!==t.machineId?!1:t.kind===`machine`?!0:t.kind===`project`?e.kind!==`machine`&&e.projectId===t.projectId:t.kind===`workspace`?e.kind===`workspace`?e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.kind===`session`&&e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.kind===`session`&&e.sessionId===t.sessionId&&(t.cwd===void 0||e.cwd===t.cwd)}function Kc(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}var qc=`workspace.delete`,Jc=`pi.operation`,Yc=`target.workspaceId`;function Xc(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function Zc(e,t){return t[e.path]}function Qc(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function $c(e,t,n){return nl(rl(e,t,n))}function el(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function tl(e){return nl(Object.values(e??{}))}function nl(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function rl(e,t,n){return Object.values(n).filter(n=>el(e,t,n.cwd))}function il(e,t){return`${e}:${t}`}function L(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var al=class{constructor(e=0){if(this.debounceMs=e,this.pendingByKey=new Map,!Number.isInteger(e)||e<0)throw Error(`debounceMs must be a non-negative integer`)}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.phase===`running`?n.trailing=!0:this.rescheduleDebounce(n),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,phase:`debouncing`,trailing:!1,debounceTimer:void 0,finishDebounce:void 0};return r.promise=Promise.resolve().then(async()=>{let t,n;do{r.trailing=!1,r.phase=`debouncing`,this.debounceMs>0&&await this.waitForDebounce(r),r.phase=`running`;let e=r.latestRefresh;n=!1;try{await e()}catch(e){t=e,n=!0}}while(this.hasTrailingRequest(r));if(this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e),n)throw t}).finally(()=>{this.cancelDebounce(r),this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}waitForDebounce(e){return new Promise(t=>{e.finishDebounce=t,this.rescheduleDebounce(e)})}rescheduleDebounce(e){e.finishDebounce!==void 0&&(e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=globalThis.setTimeout(()=>{let t=e.finishDebounce;e.debounceTimer=void 0,e.finishDebounce=void 0,e.phase=`running`,t?.()},this.debounceMs))}cancelDebounce(e){e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=void 0,e.finishDebounce=void 0}},ol=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new al,this.api=n.api??Os,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,sl(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=R(this.getState())){let n=this.getState(),r=R(n)===t,i=cl(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...R(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function sl(e){let t={};for(let n of e.workspaces)Xc(n)&&(t[n.cwd]=n);return t}function cl(e,t){let n={...e};return Xc(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var ll=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??Ks,this.pollIntervalMs=r.pollIntervalMs??1e3,this.scope=r.scope,this.browserErrors=new Hc(e,t)}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=pl(e);return t!==void 0&&(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){this.advanceAuthOperation();let t=this.captureTarget();t!==void 0&&(e!==void 0&&e!==``?await this.openLoginProvider(e,t):this.setState({authDialog:{step:`method`,target:t}}))}async openMcpAuth(e,t,r){let i=this.getState(),a=r?.session??(i.selectedSession?.archived===!0?void 0:i.selectedSession),o=r?.machineId??R(i);if(a===void 0){this.browserErrors.report(Mc(o),n(`ui.mcp.selectSession`,`Select a session to authenticate MCP servers.`));return}let s=this.advanceAuthOperation(),c={machineId:o},l={id:a.id,cwd:a.cwd};this.setState({authDialog:{step:`starting`,target:c,mcpSession:l,title:e===`login`?n(`ui.mcp.signInTitle`,`Sign in to an MCP server`):n(`ui.mcp.signOutTitle`,`Sign out of an MCP server`)}}),await this.startFlow(()=>t===void 0?this.api.startMcpAuth(l,e,o):this.api.startMcpAuth(l,e,o,t),c,s,l)}async chooseLoginMethod(e){let t=this.getState().authDialog;if(t?.step!==`method`)return;let n=this.oauthOperationGeneration;try{let{providers:r}=await this.api.authProviders({mode:`login`,authType:e,...dl(t.target)});if(n!==this.oauthOperationGeneration||this.getState().authDialog!==t)return;this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:r,target:t.target}})}catch(e){if(n!==this.oauthOperationGeneration||this.getState().authDialog!==t)return;this.browserErrors.report(Mc(t.target.machineId),String(e))}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startOAuth(r,n.target):this.setState({authDialog:{step:`apiKey`,provider:r,value:``,target:n.target}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:n(`ui.shared.daf147632ea6`,`API key is required`)}});return}let r={...e};delete r.error,this.setState({authDialog:{...r,saving:!0}});let i=this.oauthOperationGeneration;try{let n=e.target;if(await this.api.saveApiKey(e.provider.id,t,n),i!==this.oauthOperationGeneration)return;this.closeDialog(),this.refreshStatus(n)}catch(t){if(i!==this.oauthOperationGeneration)return;this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){let t=this.advanceAuthOperation(),r=this.captureTarget();if(r!==void 0)try{let{providers:i}=await this.api.authProviders({mode:`logout`,...dl(r)});if(t!==this.oauthOperationGeneration)return;if(e!==void 0&&e!==``){let t=i.find(t=>t.id===e);t===void 0?this.browserErrors.report(Mc(r.machineId),n(`client.authController.no.saved.credentials.for.cc5494`,`No saved credentials for {value1}`,{value1:e})):await this.logoutProviderForTarget(t.id,r);return}this.setState({authDialog:{step:`logout`,providers:i,target:r}})}catch(e){if(t!==this.oauthOperationGeneration)return;this.browserErrors.report(Mc(r.machineId),String(e))}}async logoutProvider(e){let t=this.getState().authDialog;t?.step===`logout`&&t.providers.find(t=>t.id===e)!==void 0&&await this.logoutProviderForTarget(e,t.target)}async logoutProviderForTarget(e,t){let n=this.advanceAuthOperation();try{if(await this.api.logoutProvider(e,t),n!==this.oauthOperationGeneration)return;this.closeDialog(),this.refreshStatus(t)}catch(e){if(n!==this.oauthOperationGeneration)return;this.browserErrors.report(Mc(t.machineId),String(e))}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId;if(this.inFlightResponse?.generation===r&&this.inFlightResponse.flowId===i&&this.inFlightResponse.requestId===a)return;let o={generation:r,flowId:i,requestId:a};this.inFlightResponse=o;let s=e??t.inputValue??``,c={...t};delete c.error,this.setState({authDialog:{...c,responding:!0}});try{let e=t.flow.target===`mcp`?await this.api.respondMcpAuthFlow(i,a,s,t.target.machineId):await this.api.respondOAuthFlow(i,a,s,t.target),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||!ul(n.target,t.target)||fl(n.flow)!==a)return;this.updateOAuthFlow(e,t.target)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||fl(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}finally{this.inFlightResponse===o&&(this.inFlightResponse=void 0)}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.target;if(e.flow.target===`mcp`){if(e.flow.status!==`running`){this.closeDialog();return}if(e.flow.cancelRequested===!0)return;let r=this.advanceAuthOperation();this.setState({authDialog:{...e,flow:{...e.flow,cancelRequested:!0}}});try{let e=await this.api.cancelMcpAuthFlow(t,n.machineId);this.currentOAuthDialog(r,t)!==void 0&&(this.updateOAuthFlow(e,n),e.status===`running`&&this.startPolling(t,n))}catch(e){let i=this.currentOAuthDialog(r,t);i!==void 0&&(this.setState({authDialog:{...i,flow:{...i.flow,cancelRequested:!1},error:String(e)}}),this.startPolling(t,n))}}else{this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}}closeDialog(){this.advanceAuthOperation(),this.setState({authDialog:void 0})}async openLoginProvider(e,t){let r=this.oauthOperationGeneration;try{let{providers:i}=await this.api.authProviders({mode:`login`,...dl(t)});if(r!==this.oauthOperationGeneration)return;let a=i.filter(t=>t.id===e);if(a.length===0){this.browserErrors.report(Mc(t.machineId),n(`client.authController.authentication.provider.not.found.a59b6e`,`Authentication provider not found: {value1}`,{value1:e}));return}if(a.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:a,target:t}});return}let o=a[0];if(o===void 0)return;o.authType===`oauth`||o.loginFlow===`interactive`?await this.startOAuth(o,t):this.setState({authDialog:{step:`apiKey`,provider:o,value:``,target:t}})}catch(e){if(r!==this.oauthOperationGeneration)return;this.browserErrors.report(Mc(t.machineId),String(e))}}async startOAuth(e,t){let n=this.advanceAuthOperation();await this.startFlow(()=>e.authType===`oauth`?this.api.startOAuthLogin(e.id,t):this.api.startInteractiveApiKeyLogin(e.id,t),t,n)}async startFlow(e,t,n,r){if(n===this.oauthOperationGeneration)try{let i=await e();if(n!==this.oauthOperationGeneration){if(i.status===`running`)try{i.target===`mcp`?await this.api.cancelMcpAuthFlow(i.flowId,t.machineId):await this.api.cancelOAuthFlow(i.flowId,t)}catch{}return}this.updateOAuthFlow(i,t,r),i.status===`running`&&this.startPolling(i.flowId,t)}catch(e){if(n!==this.oauthOperationGeneration)return;let r=this.getState().authDialog;r?.step===`starting`?this.setState({authDialog:{...r,error:String(e)}}):this.browserErrors.report(Mc(t.machineId),String(e))}}updateOAuthFlow(e,t,n){let r=this.getState().authDialog;if(n??=e.target===`mcp`&&(r?.step===`oauth`||r?.step===`starting`)?r.mcpSession:void 0,e.status===`complete`&&e.target!==`mcp`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}e.status!==`running`&&(this.oauthOperationGeneration+=1,this.stopPolling(),e.target===`mcp`&&n!==void 0&&this.refreshMcpStatus(t.machineId,n));let i=r?.step===`oauth`&&r.flow.flowId===e.flowId?r.inputValue??``:``,a=r?.step===`oauth`?fl(r.flow):void 0,o=fl(e),s=a!==void 0&&a===o,c=s?i:``,l=s&&r?.step===`oauth`?r.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,inputValue:c,responding:l,target:t,...n===void 0?{}:{mcpSession:n}}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i===void 0||!ul(i.target,t)){this.stopPolling();return}let a=fl(i.flow);try{let o=i.flow.target===`mcp`?await this.api.mcpAuthFlow(e,i.target.machineId):await this.api.oauthFlow(e,i.target),s=this.currentOAuthDialog(n,e);if(o.flowId!==e||r!==this.pollGeneration||s===void 0||!ul(s.target,t)||fl(s.flow)!==a)return;this.updateOAuthFlow(o,i.target)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o===void 0||!ul(o.target,t)||fl(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}advanceAuthOperation(){return this.oauthOperationGeneration+=1,this.stopPolling(),this.oauthOperationGeneration}async refreshStatus(e){let t=this.selectedSessionForMachine(e.machineId);if(t!==void 0&&this.targetStillSelected(e))try{let n=await this.api.status(t,e.machineId),r=this.selectedSessionForMachine(e.machineId);if(!this.targetStillSelected(e)||r?.id!==t.id||r.cwd!==t.cwd)return;this.applyStatus(n)}catch{}}async refreshMcpStatus(e,t){let n=()=>{let n=this.selectedSessionForMachine(e);return n?.id===t.id&&n.cwd===t.cwd};if(n())try{let r=await this.api.status(t,e);n()&&this.applyStatus(r)}catch{}}selectedSessionForMachine(e){let t=this.getState();if(R(t)!==e)return;let n=t.selectedSession;if(n!==void 0&&n.archived!==!0)return n}captureTarget(){let e=this.getState(),t=e.selectedMachine,r={machineId:R(e),...t?.kind===void 0?{}:{machineKind:t.kind}};if(this.scope===`management`)return r;let i=e.selectedProject;if(i===void 0)this.browserErrors.report(Mc(r.machineId),n(`client.authController.select.a.project.before.configuring.provider.authentication.a2a76e`,`Select a project before configuring provider authentication.`));else return{...r,projectId:i.id,projectName:i.name}}targetStillSelected(e){return R(this.getState())===e.machineId?e.projectId===void 0||this.getState().selectedProject?.id===e.projectId:!1}};function ul(e,t){return e.machineId===t.machineId&&e.projectId===t.projectId}function dl(e){return e.projectId===void 0?{machineId:e.machineId}:{machineId:e.machineId,projectId:e.projectId,...e.projectName===void 0?{}:{projectName:e.projectName}}}function fl(e){return e.prompt?.requestId??e.select?.requestId}function pl(e){let t=e.trim(),n=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(n===null)return;let r=n[1];if(r!==`login`&&r!==`logout`)return;let i=n[2];return i===void 0||i===``?{command:r}:{command:r,providerId:i}}var ml=class{constructor(e,t,n,r,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.projects=r,this.runtimeRefreshSeqByMachine=new Map,this.navigateToMachine=i.navigateToMachine,this.captureNavigation=i.captureNavigation,this.browserErrors=new Hc(e,t)}async loadMachines(e){this.setState({error:``,isLoadingMachines:!0});try{let t=await Ks.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));for(let e of Object.values(this.getState().browserErrors))e.scope.kind!==`global`&&!r.has(e.scope.machineId)&&this.browserErrors.discard(Mc(e.scope.machineId));return this.setState({machines:t,selectedMachine:n,machineActivities:gl(this.getState().machineActivities,r),machineRuntimes:gl(this.getState().machineRuntimes,r),machineStatusSnapshots:gl(this.getState().machineStatusSnapshots,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t),!0}catch(t){return this.setState({error:String(t)}),this.browserErrors.report(Mc(e??`local`),String(t)),!1}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,workspaceResolution:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},...Ac()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){let t=_l(this.getState(),this.captureNavigation);this.setState({error:``});try{let n=await Ks.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==n.id),n]}),this.navigateToMachine===void 0?await this.selectMachine(n):await this.navigateToMachine(n,{expected:t}),n}catch(e){this.setState({error:String(e)});return}}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`)this.browserErrors.report(Mc(e.id),n(`client.machineController.cannot.remove.the.local.machine.9e88e1`,`Cannot remove the local machine.`));else try{await Ks.deleteMachine(e.id);let n=this.getState().machines.filter(t=>t.id!==e.id),r=n.find(e=>e.id===`local`)??n[0];if(this.browserErrors.discard(Mc(e.id)),this.setState({machines:n,machineStatuses:hl(this.getState().machineStatuses,e.id),machineRuntimes:hl(this.getState().machineRuntimes,e.id),machineActivities:hl(this.getState().machineActivities,e.id),machineStatusSnapshots:hl(this.getState().machineStatusSnapshots,e.id)}),this.getState().selectedMachine?.id===e.id&&r!==void 0){if(t.selectFallback===!1)return r;let e=_l(this.getState(),this.captureNavigation);return this.navigateToMachine===void 0?await this.selectMachine(r):await this.navigateToMachine(r,{expected:e}),r}return}catch(t){this.browserErrors.report(Mc(e.id),String(t));return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await Ks.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(t){this.browserErrors.report(Mc(e),String(t));return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await Ks.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.browserErrors.report(Mc(e),String(n));return}}async selectInitialMachine(e,t){let r=e.find(e=>e.id===(t??`local`));if(r===void 0)return this.localMachine(e);if(r.kind!==`remote`)return r;let i=await this.safeRemoteHealth(r);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i.ok||this.browserErrors.report(Mc(r.id),n(`ui.piWebApp.isUnavailableReconnecting`,`{machineName} is unavailable. Reconnecting…`,{machineName:r.name})),r}async safeRemoteHealth(e){try{return await Ks.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>Ks.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>Ks.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function hl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function gl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}function _l(e,t){return t?.()??{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}var vl=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new al,this.api=n.api??ks}refresh(e){return this.refreshes.request(e,async()=>{let t=this.getState().machineStatusSnapshots[e],n=await this.api.machineStatus(e),r=this.getState().machineStatusSnapshots[e];(r===t||r===void 0||r.epochId===n.epochId)&&this.apply(e,n)})}apply(e,t){let n=this.getState().machineStatusSnapshots;yl(n[e],t)&&this.setState({machineStatusSnapshots:{...n,[e]:t}})}};function yl(e,t){return e===void 0||e.epochId!==t.epochId||t.revision>e.revision}function bl(e){switch(e.kind){case`projects`:return JSON.stringify([e.kind,e.machineId]);case`workspaces`:return JSON.stringify([e.kind,e.machineId,e.projectId]);case`sessionPins`:return JSON.stringify([e.kind,e.machineId,e.projectId,e.workspaceId])}}var xl=class{constructor(e,t={}){this.port=e,this.options=t,this.states=new Map}ids(e){return[...this.state(e).snapshot?.ids??[]]}pending(e){return this.state(e).pending>0}ensure(e){let t=this.state(e);if(t.ensuring)return t.ensuring;if(t.snapshot)return Promise.resolve();let n=this.load(e);return t.ensuring=n,n.finally(()=>{t.ensuring=void 0}).catch(()=>void 0),n}load(e){return e={...e},this.enqueue(e,async t=>{t.snapshot=await this.port.load(e)})}mutate(e,t){return e={...e},this.enqueue(e,async n=>{n.snapshot??=await this.port.load(e);let r=n.snapshot,i=[...t([...r.ids])];if(!(i.length===r.ids.length&&i.every((e,t)=>e===r.ids[t])))try{n.snapshot=await this.port.save(e,i,r.revision)}catch(t){n.snapshot=void 0;try{n.snapshot=await this.port.load(e)}catch(t){this.options.onError?.(e,t)}throw t}})}state(e){let t=bl(e),n=this.states.get(t);return n||(n={snapshot:void 0,tail:Promise.resolve(),ensuring:void 0,pending:0},this.states.set(t,n)),n}enqueue(e,t){e={...e};let n=this.state(e);n.pending++,this.options.onChange?.(e);let r=n.tail.then(async()=>{try{await t(n)}catch(t){throw this.options.onError?.(e,t),t}finally{n.pending--,this.options.onChange?.(e)}});return n.tail=r.catch(()=>void 0),r}};function Sl(e){let t=`api/machines/${encodeURIComponent(e.machineId)}/navigation/projects`;switch(e.kind){case`projects`:return t;case`workspaces`:return`${t}/${encodeURIComponent(e.projectId)}/workspaces`;case`sessionPins`:return`${t}/${encodeURIComponent(e.projectId)}/workspaces/${encodeURIComponent(e.workspaceId)}/session-pins`}}function Cl(e){if(!wl(e))throw Error(`Invalid navigation order response`);let t=e.ids,n=e.revision;if(!Array.isArray(t)||!t.every(e=>typeof e==`string`&&e.trim()!==``)||new Set(t).size!==t.length||typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Invalid navigation order response: ids and revision are required`);return{ids:[...t],revision:n}}function wl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Tl={load:e=>D(Sl(e),Cl,{cache:`no-store`}),save:(e,t,n)=>{let r={ids:[...t],revision:n};return D(Sl(e),Cl,{method:`PUT`,body:JSON.stringify(r)})}};function El(e,t){let n=new Map;for(let e of t)n.has(e)||n.set(e,n.size);return[...e].sort((e,t)=>(n.get(e.id)??1/0)-(n.get(t.id)??1/0))}function Dl(e,t,n,r,i){let a=[...new Set([...e,...t])];if(n===r||!t.includes(n)||!t.includes(r))return a;let o=a.filter(e=>e!==n),s=o.indexOf(r);return o.splice(s+ +(i===`after`),0,n),o}var Ol=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.loadErrors=new Map,this.api=r.api??Ks,this.onProjectsApplied=r.onProjectsApplied,this.navigateToProject=r.navigateToProject,this.captureNavigation=r.captureNavigation,this.browserErrors=new Hc(e,t)}async loadProjects(){let e=R(this.getState());this.loadErrors.delete(e),this.setState({isLoadingProjects:!0});try{let t=await this.api.projects(e);if(R(this.getState())!==e)return;let n=new Set(t.map(e=>e.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>n.has(e)));this.setState({projects:t,workspacesByProjectId:r}),this.onProjectsApplied?.(e)}catch(t){this.loadErrors.set(e,String(t)),this.browserErrors.report(Mc(e),String(t))}finally{R(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t,n){if(e.trim()===``)return;let r=R(this.getState()),i=kl(this.getState(),this.captureNavigation),a;try{a=await this.api.addProject(e.trim(),void 0,t,r)}catch(e){this.browserErrors.report(Mc(r),String(e));return}try{if(R(this.getState())===r){let e=this.getState().projects;this.setState({projects:[...e.filter(e=>e.id!==a.id),a],projectDialogOpen:!1}),this.onProjectsApplied?.(r)}if(n?.changed===!0&&await this.applyTrustChoice(a,n.trusted,r),R(this.getState())!==r)return;this.navigateToProject===void 0?await this.workspaces.selectProject(a):await this.navigateToProject(a,{expected:i})}catch(e){this.browserErrors.report(Nc(r,a.id),String(e))}}async applyTrustChoice(e,t,r){let i=(await(this.api.workspaces??Ks.workspaces)(e.id,r)).find(t=>t.projectId===e.id&&t.isMain);if(i===void 0)throw Error(n(`ui.main.7800af593e97`,`Could not save trust choice for project {arg0}: the primary workspace is unavailable`,{arg0:e.id}));await(this.api.setWorkspaceTrust??Ks.setWorkspaceTrust)(e.id,i.id,t,r)}async closeProject(e){let t=R(this.getState());try{if(await this.api.closeProject(e,t),R(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();if(this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id!==e)return;let r=kl(this.getState(),this.captureNavigation);this.navigateToProject===void 0?this.workspaces.clearSelection():await this.navigateToProject(void 0,{expected:r})}catch(n){this.browserErrors.report(Nc(t,e),String(n))}}};function kl(e,t){return t?.()??{machineId:R(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}var Al=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??Ps,this.onError=n.onError}handleActivityApplied(e){return R(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return R(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(R(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!jl(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=await this.api.workspaces(t.id,e.machineId);this.applyProjectWorkspaces(e,t,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!jl(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(R(this.getState()))}applyProjectWorkspaces(e,t,n){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let r=this.getState();r.projects.find(e=>e.id===t.id)?.path===t.path&&r.workspacesByProjectId[t.id]===t.startingWorkspaces&&this.setState({workspacesByProjectId:{...r.workspacesByProjectId,[t.id]:n}})}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&R(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(Xc).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function jl(e,t,n){return e.some(e=>el(e,t[e.id]??[],n))}var Ml=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??ys,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=R(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebStatus(e);this.isCurrent(e,t)&&this.setState({piWebStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=R(this.getState()),t=this.pendingUpdateCheck;if(t?.machineId===e)return t.promise;let n=++this.requestSequence,r=this.api.checkForUpdates(e).then(t=>{this.isCurrent(e,n)&&(this.setState({piWebStatus:t}),Nl(t))}).catch(t=>{if(this.isCurrent(e,n))throw t}).finally(()=>{this.pendingUpdateCheck?.requestSequence===n&&(this.pendingUpdateCheck=void 0)});return this.pendingUpdateCheck={machineId:e,requestSequence:n,promise:r},r}isCurrent(e,t){return R(this.getState())===e&&t===this.requestSequence}};function Nl(e){if(e.release.error!==void 0)throw Error(n(`client.piWebStatusController.pi.web.update.check.failed.495ae6`,`PI WEB update check failed: {value1}`,{value1:e.release.error}));if(e.release.skipped===!0)throw Error(n(`client.piWebStatusController.pi.web.update.check.skipped.because.remote.checks.are.disabled.by.offl.e9da2f`,`PI WEB update check skipped because remote checks are disabled by offline or version-check settings`))}function Pl(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}var Fl=`pi-web:cached-new-sessions:v1`,Il=`browserCachedNew`,Ll=`local`;function Rl(e,t=Ll,n=Pl()){if(e.messageCount!==0||e.archived===!0)return;let r=Wl(n).filter(n=>n.id!==e.id||n.machineId!==t);Gl([zl(e,t),...r],n)}function zl(e,t=Ll){return{...e,browserCachedNew:!0,machineId:t}}function Bl(e,t=Ll,n=Pl()){Gl(Wl(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Vl(e,t,n=Ll,r=Pl()){let i=new Set(t.map(e=>e.id)),a=Wl(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&Gl(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Hl(e){return e!==void 0&&ql(e)&&e.browserCachedNew===!0}function Ul(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},...e.agentSubsession===!0?{agentSubsession:!0}:{},...`machineId`in e&&typeof e.machineId==`string`?{machineId:e.machineId}:{machineId:Ll},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Wl(e=Pl()){try{let t=e?.getItem(Fl);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Kl(e)):[]}catch{return[]}}function Gl(e,t=Pl()){try{e.length===0?t?.removeItem(Fl):t?.setItem(Fl,JSON.stringify(e))}catch{}}function Kl(e){if(!Jl(e))return[];let t=Yl(e,`id`),n=Yl(e,`path`),r=Yl(e,`cwd`),i=Yl(e,`created`),a=Yl(e,`modified`),o=Yl(e,`firstMessage`),s=Zl(e,`messageCount`);if(t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s!==0)return[];let c=Xl(e,`name`),l=Xl(e,`parentSessionPath`),u=Xl(e,`machineId`)??Ll;return[{id:t,path:n,cwd:r,...c===void 0?{}:{name:c},created:i,modified:a,messageCount:s,firstMessage:o,...l===void 0?{}:{parentSessionPath:l},...e.agentSubsession===!0?{agentSubsession:!0}:{},machineId:u,browserCachedNew:!0}]}function ql(e){return Il in e}function Jl(e){return typeof e==`object`&&!!e}function Yl(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Xl(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function Zl(e,t){let n=e[t];return typeof n==`number`?n:void 0}function Ql(e,t){let n=[];return e.forEach((e,r)=>{let i=ru(e);i.every(e=>e.parts.length===0)&&z(e,`role`)!==void 0&&n.at(-1)?.parts.at(-1)?.type===`askUserQuestion`&&(i=[{...i[0]??eu({role:pu(z(e,`role`)),parts:[]},e),parts:[{type:`empty`}]}]),n.push(...i.map(e=>t===void 0?e:{...e,transcriptIndex:t+r}))}),Su(n).filter(e=>e.parts.length>0)}function $l(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function eu(e,t){let n=lu(t),r=z(t,`entryId`),i=z(t,`streamId`);return n===void 0&&r===void 0&&i===void 0?e:{...e,...i===void 0?{}:{streamId:i},...n===void 0?{}:{meta:n},...r===void 0||r===``?{}:{entryId:r}}}function tu(e,t,n){if(n===``)return e;let r=e.at(-1),i=r?.parts.at(-1);return r?.role===t&&i?.type===`text`?[...e.slice(0,-1),{...r,parts:[...r.parts.slice(0,-1),{type:`text`,text:i.text+n}]}]:r?.role===t?[...e.slice(0,-1),{...r,parts:[...r.parts,{type:`text`,text:n}]}]:[...e,$l(t,n)]}function nu(e,t){if(t===``)return e;let n=e.at(-1),r=n?.parts.at(-1);return n?.role===`assistant`&&r?.type===`thinking`?[...e.slice(0,-1),{...n,parts:[...n.parts.slice(0,-1),{type:`thinking`,text:r.text+t}]}]:n?.role===`assistant`?[...e.slice(0,-1),{...n,parts:[...n.parts,{type:`thinking`,text:t}]}]:[...e,{role:`assistant`,parts:[{type:`thinking`,text:t}]}]}function ru(e){if(au(e))return e.parts.some(e=>z(e,`type`)===`image`)?[{...e,parts:e.parts.flatMap(e=>z(e,`type`)===`image`?hu(e):[e])}]:[e];if(z(e,`role`)===`bashExecution`)return[eu(fu(e),e)];let t=z(e,`role`),n=pu(t),r=mu(Au(e,`content`),e),i=t===`toolResult`?vu(z(e,`toolName`)??``,Au(e,`details`)):void 0,a=t===`toolResult`?_u(z(e,`toolName`)??``,Au(e,`details`),ju(e,`isError`)===!0):void 0,o=[...t===`toolResult`&&!r.some(e=>e.type===`toolResult`)?[bu(r.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
7
+ </div>`}var C=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},Vt={attribute:!0,type:String,converter:ce,reflect:!1,hasChanged:e},Ht=(e=Vt,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function w(e){return(t,n)=>typeof n==`object`?Ht(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function T(e){return w({...e,state:!0,attribute:!1})}var Ut=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function E(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return Ut(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return Ut(n,r,{get(){return a(this)}})}}var Wt={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},Gt=e=>(...t)=>({_$litDirective$:e,values:t}),Kt=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},qt={},Jt=Gt(class extends Kt{constructor(){super(...arguments),this.ot=qt}render(e,t){return t()}update(e,[t,n]){if(Array.isArray(t)){if(Array.isArray(this.ot)&&this.ot.length===t.length&&t.every((e,t)=>e===this.ot[t]))return u}else if(this.ot===t)return u;return this.ot=Array.isArray(t)?Array.from(t):t,this.render(t,n)}}),Yt=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Xt(e){return Yt.some(t=>t===e)}function Zt(e){return e===void 0||e===``?`off`:e}function Qt(e,t=c(`en`,{})){let n=Zt(e),r={off:t(`thinking.label.off`,`Off`),minimal:t(`thinking.label.minimal`,`Minimal`),low:t(`thinking.label.low`,`Low`),medium:t(`thinking.label.medium`,`Medium`),high:t(`thinking.label.high`,`High`),xhigh:t(`thinking.label.xhigh`,`Extra high`),max:t(`thinking.label.max`,`Maximum`)};return Xt(n)?r[n]??n:n}function $t(e,t=c(`en`,{})){switch(e){case`off`:return t(`thinking.description.off`,`No reasoning`);case`minimal`:return t(`thinking.description.minimal`,`Minimal reasoning (about 1k tokens)`);case`low`:return t(`thinking.description.low`,`Light reasoning (about 2k tokens)`);case`medium`:return t(`thinking.description.medium`,`Moderate reasoning (about 8k tokens)`);case`high`:return t(`thinking.description.high`,`Deep reasoning (about 16k tokens)`);case`xhigh`:return t(`thinking.description.xhigh`,`Extra high reasoning (about 32k tokens)`);case`max`:return t(`thinking.description.max`,`Maximum reasoning (about 64k tokens)`);default:return}}function en(e,t){let n=t.length>=2?t:Yt,r=n.length-1,i=Zt(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}function tn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nn(e){if(!tn(e))throw new te(`server.main.b5b69396302e`,`Invalid session defaults`);let t=e,n={};for(let e of[`defaultProvider`,`defaultModel`]){let r=t[e];if(r!==void 0){if(typeof r!=`string`)throw new te(`server.main.d20dbeed752b`,`Invalid {arg0}`,{arg0:e});n[e]=r}}let r=t.defaultThinkingLevel;if(r!==void 0){if(typeof r!=`string`||!Xt(r))throw new te(`server.main.e937d7ab07c7`,`Invalid defaultThinkingLevel`);n.defaultThinkingLevel=r}return n}var rn=class extends Error{constructor(e,t,n={}){super(e,n),this.status=t,this.name=`HttpRequestError`}},an=class extends Error{constructor(e,t={}){super(e,t),this.name=`NetworkRequestError`}},on=fe();function sn(e){on=e}function cn(e){return y(Ce(e,void 0,on))}async function D(e,t,n){let r=new Headers(n?.headers);n?.body!==void 0&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=on,a=cn(e),o=await un(()=>fetch(a,{...n,headers:r}),n?.signal);if(!o.ok)throw new rn(dn(await o.json().catch(()=>({})))??o.statusText,o.status);return ye(i),t(await un(()=>o.json(),n?.signal))}async function ln(e,t){let n=on,r=cn(e),i=await un(()=>fetch(r));if(i.status===204)ye(n);else if(i.status!==404){if(!i.ok)throw new rn(dn(await i.json().catch(()=>({})))??i.statusText,i.status);return ye(n),t(await un(()=>i.json()))}}async function un(e,t){try{return await e()}catch(e){throw e instanceof TypeError&&e.name!==`AbortError`&&t?.aborted!==!0?new an(e.message,{cause:e}):e}}function dn(e){if(fn(e))return typeof e.error==`string`?e.error:void 0}function fn(e){return typeof e==`object`&&!!e}var pn=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function mn(e){if(!hn(e))return;let t=e,n=t.themeId,r=t.auto;if(typeof n==`string`&&pn.test(n)&&typeof r==`boolean`)return{themeId:n,auto:r}}function hn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gn(e,t){let n=mn(e);if(n===void 0)throw new te(`configError.defaultTheme.invalid`,`PI WEB config defaultTheme must contain a qualified themeId and a boolean auto: {source}`,{source:t});return n}function _n(e,t){if(e!==`steer`&&e!==`followUp`)throw new te(`configError.defaultStreamingBehavior.invalid`,`PI WEB config defaultStreamingBehavior must be steer or followUp: {source}`,{source:t});return e}function vn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function yn(e,t){if(!vn(e))throw new te(`configError.sessionNaming.object`,`PI WEB config sessionNaming must be an object: {source}`,{source:t});let n=Object.keys(e).find(e=>e!==`model`&&e!==`maxTokens`&&e!==`thinkingLevel`&&e!==`timeoutMs`);if(n!==void 0)throw new te(`configError.sessionNaming.unknownKey`,`PI WEB config sessionNaming has unknown key {key}: {source}`,{key:JSON.stringify(n),source:t});let r=e.model,i=e.maxTokens,a=e.thinkingLevel,o=e.timeoutMs;if(r!==void 0&&(typeof r!=`string`||!/^[^/\s]+\/\S+$/.test(r)))throw new te(`configError.sessionNaming.model`,`PI WEB config sessionNaming.model must be an exact provider/model-id with non-empty parts: {source}`,{source:t});if(i!==void 0&&(typeof i!=`number`||!Number.isSafeInteger(i)||i<=0))throw new te(`configError.sessionNaming.maxTokens`,`PI WEB config sessionNaming.maxTokens must be a positive safe integer: {source}`,{source:t});if(a!==void 0&&(typeof a!=`string`||!Xt(a)))throw new te(`configError.sessionNaming.thinkingLevel`,`PI WEB config sessionNaming.thinkingLevel must be a known thinking level: {source}`,{source:t});if(o!==void 0&&(typeof o!=`number`||!Number.isInteger(o)||o<1||o>2147483647))throw new te(`configError.sessionNaming.timeoutMs`,`PI WEB config sessionNaming.timeoutMs must be an integer from 1 to 2147483647: {source}`,{source:t});return{...r===void 0?{}:{model:r},...i===void 0?{}:{maxTokens:i},...a===void 0?{}:{thinkingLevel:a},...o===void 0?{}:{timeoutMs:o}}}function bn(e,t){if(!vn(e))throw new te(`configError.sessionArchive.object`,`PI WEB config sessionArchive must be an object: {source}`,{source:t});let n=Object.keys(e).find(e=>e!==`directory`);if(n!==void 0)throw new te(`configError.sessionArchive.unknownKey`,`PI WEB config sessionArchive has unknown key {key}: {source}`,{key:JSON.stringify(n),source:t});let r=e.directory;if(r===void 0)return{};if(typeof r!=`string`||r.trim()===``||r.includes(`\0`))throw new te(`configError.sessionArchive.directory`,`PI WEB config sessionArchive.directory must be a non-empty path: {source}`,{source:t});return{directory:r}}var xn=new Set([`schemaVersion`,`dir`]);function Sn(e){if(!Tn(e)||Object.keys(e).some(e=>!xn.has(e)))return;let t=e.schemaVersion,n=e.dir;if(t===2&&typeof n==`string`&&Cn(n))return Object.freeze({schemaVersion:2,dir:n})}function Cn(e){if(e===``||e!==e.trim()||wn(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function wn(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Tn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var En=Object.values(m),Dn=new Set(En);m.sessionsDeleteArchived,m.sessionsBulkMutations,m.sessionsCleanup,m.sessionsReload,m.sessionsClearQueue,m.sessionsQueueMessageActions,m.sessionsPersistedState,m.sessionsNotifications,m.sessionsUnread,m.sessionsAskUser,m.promptAttachments,m.workspaceFileSuggestions,m.piPackagesManage,m.selectedMachineSettings,m.agentProfileConfig,m.pluginLifecycle,m.sessionsDeleteArchived,m.sessionsBulkMutations,m.sessionsCleanup,m.sessionsReload,m.sessionsClearQueue,m.sessionsQueueMessageActions,m.sessionsPersistedState,m.sessionsNotifications,m.sessionsUnread,m.sessionsAskUser,m.promptAttachments,m.sessionsDeleteArchived,m.sessionsBulkMutations,m.sessionsCleanup,m.sessionsReload,m.sessionsClearQueue,m.sessionsQueueMessageActions,m.sessionsPersistedState,m.sessionsNotifications,m.sessionsUnread,m.sessionsAskUser,m.promptAttachments,m.workspaceFileSuggestions,m.piPackagesManage,m.selectedMachineSettings,m.agentProfileConfig,m.pluginLifecycle;function On(e){return typeof e==`string`&&Dn.has(e)}function kn(e,t){return e?.capabilities?.includes(t)===!0}function An(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e.filter(On)}function jn(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!Mn(n))continue;let e=n.source,r=n.name,i=n.replacement;(e===`environment`||e===`config`)&&typeof r==`string`&&r!==``&&(i===void 0||typeof i==`string`&&i!==``)&&t.push({source:e,name:r,...i===void 0?{}:{replacement:i}})}return t}function Mn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Nn=[`projectId`,`workspaceId`,`sessionId`];function Pn(e,t){if(!In(e))throw Error(`${t} must be an object`);let n=!1;for(let r in e)if(Object.hasOwn(e,r)&&(n=!0,!Fn(r)))throw Error(`Unsupported ${t} field: ${r}`);if(!n)throw Error(`${t} must contain at least one of projectId, workspaceId, or sessionId`);let r={};for(let n of Nn){if(!Object.hasOwn(e,n))continue;let i=e[n];if(typeof i!=`string`||i.length>512||i.trim()===``)throw Error(`${t} ${n} must be a non-empty string of at most 512 characters`);r[n]=i}if(r.projectId!==void 0)return Object.freeze({...r,projectId:r.projectId});if(r.workspaceId!==void 0)return Object.freeze({...r,workspaceId:r.workspaceId});if(r.sessionId!==void 0)return Object.freeze({...r,sessionId:r.sessionId});throw Error(`${t} must contain at least one visibility selector`)}function Fn(e){return Nn.some(t=>t===e)}function In(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var Ln={working:`core:working`,terminal:`core:terminal`,unread:`core:unread`};function Rn(e){if(!Vn(e))return;let t=e.epochId,n=e.revision,r=e.generatedAt,i=zn(e.machine),a=zn(e.unattributed),o=Bn(e.projects),s=Bn(e.workspaces);if(typeof t!=`string`||t===``||typeof n!=`number`||!Number.isFinite(n)||typeof r!=`string`||r===``||i===void 0||a===void 0||o===void 0||s===void 0)return;let c={epochId:t,revision:n,machine:i,projects:o,workspaces:s,unattributed:a,generatedAt:r};if(Object.hasOwn(e,`sessions`)){let t=Bn(e.sessions,!0);if(t===void 0)return;c.sessions=t}return c}function zn(e){if(!Vn(e))return;let t=new Map;for(let[n,r]of Object.entries(e))typeof r==`boolean`&&t.set(n,r);return Object.fromEntries(t)}function Bn(e,t=!1){if(!Vn(e))return;let n=new Map;for(let[r,i]of Object.entries(e)){let e=zn(i);if(e===void 0&&t)return;e!==void 0&&n.set(r,e)}return Object.fromEntries(n)}function Vn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Hn=Object.freeze({showSafeStart:`pi-web plugins safe-start show`,bundledOnly:`pi-web plugins safe-start set bundled-only --restart`,noServerPlugins:`pi-web plugins safe-start set none --restart`,clearSafeStart:`pi-web plugins safe-start clear --restart`});function Un(e){if(!i(e))throw Error(`Invalid PI WEB plugin id: ${e}`);return`pi-web plugins disable ${e} --restart`}function Wn(e){return typeof e==`object`&&!!e}function O(e){if(!Wn(e))throw Error(`Expected object response`);return e}function k(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function A(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function Gn(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function j(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function M(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function Kn(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e.map(e=>{if(typeof e==`object`&&e&&`entryId`in e&&e.entryId!==void 0&&typeof e.entryId!=`string`)throw Error(`Expected string field: entryId`);return e})}function qn(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function Jn(e){let t=O(e),n=t.leafId;if(n!=null&&typeof n!=`string`)throw Error(`Expected optional string|null field: leafId`);return{messages:Kn(t.messages),start:Gn(t,`start`),total:Gn(t,`total`),...N(`leafId`,n)}}function Yn(e){let t=O(e);return M(Xn)(t.machines)}function Xn(e){let t=O(e),n=er(t,`kind`),r=A(t,`baseUrl`),i=tr(t,`status`),a=A(t,`statusMessage`);return{id:k(t,`id`),name:k(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:k(t,`createdAt`),updatedAt:k(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function Zn(e){let t=O(e),n=tr(t,`status`),r=A(t,`error`);return{machineId:k(t,`machineId`),ok:j(t,`ok`),checkedAt:k(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:uo(t.web)},...t.sessiond===void 0?{}:{sessiond:uo(t.sessiond)},...r===void 0?{}:{error:r}}}function Qn(e){let t=O(e),n=A(t,`error`);return{machineId:k(t,`machineId`),ok:j(t,`ok`),checkedAt:k(t,`checkedAt`),...N(`packageName`,A(t,`packageName`)),...N(`generatedAt`,A(t,`generatedAt`)),...t.components===void 0?{}:{components:co(t.components)},...t.capabilities===void 0?{}:{capabilities:_o(t.capabilities)},...t.deprecatedAgentInputs===void 0?{}:{deprecatedAgentInputs:$n(t.deprecatedAgentInputs)},...n===void 0?{}:{error:n}}}function $n(e){let t=jn(e);if(t===void 0)throw Error(`Invalid PI WEB deprecated agent inputs`);return t}function er(e,t){let n=k(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function tr(e,t){let n=A(e,t);if(n!==void 0){if(n!==`unknown`&&n!==`online`&&n!==`offline`&&n!==`error`)throw Error(`Expected machine status field: ${t}`);return n}}function nr(e){let t=O(e);return{id:k(t,`id`),name:k(t,`name`),path:k(t,`path`),createdAt:k(t,`createdAt`)}}function rr(e){let t=O(e);return Object.freeze({id:k(t,`id`),projectId:k(t,`projectId`),path:k(t,`path`),label:k(t,`label`),isMain:j(t,`isMain`),...N(`branch`,A(t,`branch`)),...N(`isGitRepo`,Ho(t,`isGitRepo`)),...N(`isGitWorktree`,Ho(t,`isGitWorktree`)),...N(`provider`,lr(t.provider)),...N(`removal`,ur(t.removal)),effectiveConfig:pr(t.effectiveConfig)})}function ir(e){let t=O(e),n=ar(t.status),r=k(t,`projectId`),i=A(t,`ownerPluginId`);if(n===`provider`&&i===void 0)throw Error(`Provider workspace resolution is missing ownerPluginId`);if(n===`folder`&&i!==void 0)throw Error(`Folder workspace resolution must not include ownerPluginId`);let a=M(rr)(t.workspaces);if(a.length===0||a.some(e=>e.projectId!==r))throw Error(`Workspace resolution contains invalid project workspaces`);let o=M(or)(t.diagnostics);return Object.freeze({status:n,projectId:r,...i===void 0?{}:{ownerPluginId:i},workspaces:Object.freeze(a),diagnostics:Object.freeze(o)})}function ar(e){if(e===`provider`||e===`folder`||e===`degraded`)return e;throw Error(`Invalid workspace provider resolution status`)}function or(e){let t=O(e),n=A(t,`pluginId`),r=t.pluginIds===void 0?void 0:qn(t.pluginIds,`pluginIds`);return Object.freeze({code:sr(t.code),message:k(t,`message`),tier:cr(t.tier),...n===void 0?{}:{pluginId:n},...r===void 0?{}:{pluginIds:Object.freeze(r)}})}function sr(e){if(e===`probe-failed`||e===`claim-conflict`||e===`list-failed`)return e;throw Error(`Invalid workspace provider diagnostic code`)}function cr(e){if(e===`primary`||e===`fallback`)return e;throw Error(`Invalid workspace provider diagnostic tier`)}function lr(e){if(e===void 0)return;if(!Wn(e)||Array.isArray(e))throw Error(`Invalid workspace provider field`);let t=e.capabilities;if(!Wn(t)||Array.isArray(t))throw Error(`Invalid workspace provider capabilities field`);let n=e.metadata;return Object.freeze({pluginId:k(e,`pluginId`),capabilities:Object.freeze({remove:j(t,`remove`),...N(`request`,Ho(t,`request`))}),...N(`metadata`,n===void 0?void 0:dr(n,`workspace provider metadata`))})}function ur(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid workspace removal field`);return Object.freeze({actionLabel:wi(e,`actionLabel`),confirmation:wi(e,`confirmation`),precondition:wi(e,`precondition`)})}}function dr(e,t){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid ${t} field`);return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,n])=>[e,fr(n,t)])))}function fr(e,t){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(Array.isArray(e))return Object.freeze(e.map(e=>fr(e,t)));if(Wn(e))return dr(e,t);throw Error(`Invalid ${t} field`)}function pr(e){if(!Wn(e)||Array.isArray(e))throw Error(`Expected workspace effectiveConfig field`);let t=Na(e.uploads),n=Pa(e.attachments);return Object.freeze({...N(`uploads`,t===void 0?void 0:Object.freeze({...t})),...N(`attachments`,n===void 0?void 0:Object.freeze({...n}))})}function mr(e){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid session metadata field`);return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,dr(t,`session metadata namespace`)])))}function hr(e){let t=O(e),n=A(t,`name`),r=t.metadata===void 0?void 0:mr(t.metadata),i=io(t.persisted,`persisted`),a=A(t,`parentSessionPath`),o=A(t,`archivedAt`);return{id:k(t,`id`),path:k(t,`path`),cwd:k(t,`cwd`),...i===void 0?{}:{persisted:i},...n===void 0?{}:{name:n},...r===void 0?{}:{metadata:r},created:k(t,`created`),modified:k(t,`modified`),messageCount:Gn(t,`messageCount`),firstMessage:k(t,`firstMessage`),...a===void 0?{}:{parentSessionPath:a},...N(`agentSubsession`,Ho(t,`agentSubsession`)),...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function gr(e){let t=O(e);return{configured:j(t,`configured`),authenticated:j(t,`authenticated`)}}function _r(e){return{path:k(O(e),`path`)}}function vr(e){let t=O(e);if(t.deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0,path:k(t,`path`)}}function yr(e){return{sessionIds:qn(O(e).sessionIds,`sessionIds`)}}function br(e){return{pinned:j(O(e),`pinned`)}}function xr(e){let t=O(e);return{results:M(Sr)(t.results),matchCount:Gn(t,`matchCount`),truncated:j(t,`truncated`)}}function Sr(e){let t=O(e);return{session:hr(t.session),matches:M(Cr)(t.matches)}}function Cr(e){let t=O(e),n=k(t,`role`);if(n!==`user`&&n!==`assistant`)throw Error(`Invalid session content search role`);return{messageIndex:Gn(t,`messageIndex`),role:n,excerpts:M(wr)(t.excerpts),occurrenceCount:Gn(t,`occurrenceCount`)}}function wr(e){let t=O(e);return{text:k(t,`text`),matchRanges:M(e=>{let t=O(e);return{start:Gn(t,`start`),length:Gn(t,`length`)}})(t.matchRanges)}}function Tr(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function Er(e){if(e!==void 0)return{id:k(O(e),`id`)}}function Dr(e){let t=O(e),n=Er(t.dismiss);return{severity:Tr(t.severity),message:k(t,`message`),...N(`source`,A(t,`source`)),...N(`path`,A(t,`path`)),...n===void 0?{}:{dismiss:n}}}function Or(e){let t=`Recently active in another PI-WEB instance. Avoid working on this session in both instances at once.`;return e.severity===`info`&&e.source===`PI-WEB`&&(e.message===t||e.message===n(`ui.sessionActivity.message`,t))}function kr(e){let n=O(e);return{value:ai(n,`value`,128),label:ai(n,`label`,t),...N(`detail`,oi(n,`detail`,t))}}function Ar(e){let n=O(e),r=Si(n.options,kr,12,`options`);Ir(r.map(e=>e.value),`ask option value`),io(n.allowOther,`allowOther`);let i=io(n.multiple,`multiple`);return{id:ai(n,`id`,128),question:ai(n,`question`,t),...N(`detail`,oi(n,`detail`,t)),options:r,allowOther:!0,...i===void 0?{}:{multiple:i}}}function jr(e){let t=O(e),n=Si(t.questions,Ar,20,`questions`);if(n.length===0)throw Error(`Ask has no questions`);return Ir(n.map(e=>e.id),`ask question id`),{askId:ai(t,`askId`,128),askedAt:wi(t,`askedAt`),questions:n}}function Mr(e){if(e!==`submitted`&&e!==`superseded`&&e!==`cancelled`)throw Error(`Invalid ask close reason`);return e}function Nr(e){let t=O(e),n=Ar(t.question),r=Si(t.values,Ci,12,`values`),i=new Set(n.options.map(e=>e.value));if(r.some(e=>!i.has(e)))throw Error(`Ask answer selected an option the question never offered`);let a=oi(t,`otherText`,me),o=j(t,`answered`);if(o!==(r.length>0||a!==void 0))throw Error(`Ask answer contradicts its answered flag`);return{question:n,answered:o,values:r,...a===void 0?{}:{otherText:a}}}function Pr(e){let t=O(e),n=Si(t.questions,Nr,20,`questions`),r=Ti(t,`answeredCount`),i=qn(t.unansweredIds,`unansweredIds`),a=n.filter(e=>!e.answered).map(e=>e.question.id);if(r!==n.length-a.length)throw Error(`Ask outcome answered count mismatch`);if(i.length!==a.length||i.some((e,t)=>e!==a[t]))throw Error(`Ask outcome unanswered ids mismatch`);return{askId:ai(t,`askId`,128),reason:Mr(t.reason),askedAt:wi(t,`askedAt`),closedAt:wi(t,`closedAt`),questions:n,answeredCount:r,unansweredIds:i,summary:wi(t,`summary`)}}function Fr(e){let t=O(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid dialog close result`);let r=t.outcome===void 0?void 0:Gr(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Dialog close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:qr(t.sessionStatus)}}function Ir(e,t){if(new Set(e).size!==e.length)throw Error(`Duplicate ${t}`)}function Lr(e){if(e!==`confirm`&&e!==`select`&&e!==`input`)throw Error(`Invalid extension dialog kind`);return e}function Rr(e){if(e!==`answered`&&e!==`cancelled`&&e!==`timeout`&&e!==`aborted`&&e!==`session-ended`)throw Error(`Invalid extension dialog close reason`);return e}function zr(e){if(typeof e==`boolean`||typeof e==`string`&&e.length<=4e3)return e;throw Error(`Invalid extension dialog answer`)}function Br(e){let t=Ci(e);if(t.length>1e3)throw Error(`String field exceeds limit: option`);return t}function Vr(e){let t=O(e),n=Lr(t.kind),r=t.options===void 0?void 0:Si(t.options,Br,24,`options`);if(r!==void 0&&Ir(r,`dialog option`),n===`select`&&(r===void 0||r.length===0))throw Error(`Select dialog has no options`);return{dialogId:ai(t,`dialogId`,128),kind:n,title:ai(t,`title`,p),...N(`message`,oi(t,`message`,p)),...r===void 0?{}:{options:r},...N(`placeholder`,oi(t,`placeholder`,p)),askedAt:wi(t,`askedAt`),...N(`timeoutAt`,Kr(t,`timeoutAt`)),runScoped:j(t,`runScoped`)}}function Hr(e){if(e===void 0)return{};let t=M(Vr)(e);return Ir(t.map(e=>e.dialogId),`dialog id`),{pendingDialogs:t}}function Ur(e){let t=O(e);if(t.type!==`dialog.opened`)throw Error(`Invalid dialog opened event type`);return{type:`dialog.opened`,dialog:Vr(t.dialog)}}function Wr(e){let t=O(e);if(t.type!==`dialog.closed`)throw Error(`Invalid dialog closed event type`);let n=Rr(t.reason),r=t.answer===void 0?void 0:zr(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog closed event answer mismatch`);return{type:`dialog.closed`,dialogId:ai(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r}}}function Gr(e){let t=O(e),n=Rr(t.reason),r=t.answer===void 0?void 0:zr(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog outcome answer mismatch`);return{dialogId:ai(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r},askedAt:wi(t,`askedAt`),closedAt:wi(t,`closedAt`)}}function Kr(e,t){let n=A(e,t);if(n!==void 0){if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}}function qr(e){let t=O(e),n=t.warnings===void 0?void 0:M(Dr)(t.warnings),r=io(t.recentlyActiveElsewhere,`recentlyActiveElsewhere`);return{sessionId:k(t,`sessionId`),...N(`persisted`,io(t.persisted,`persisted`)),recentlyActiveElsewhere:r??n?.some(Or)??!1,isStreaming:j(t,`isStreaming`),isCompacting:j(t,`isCompacting`),isBashRunning:j(t,`isBashRunning`),pendingMessageCount:Gn(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:M(Ri)(t.queuedMessages),...N(`queueMessageActionsUnavailable`,A(t,`queueMessageActionsUnavailable`)),...N(`messageCount`,Uo(t,`messageCount`)),tokens:zi(t.tokens),cost:Gn(t,`cost`),...Vi(t.model),...ca(t.contextUsage),...N(`thinkingLevel`,A(t,`thinkingLevel`)),...N(`warnings`,n?.filter(e=>!Or(e))),...Hr(t.pendingDialogs),...N(`suggestedInput`,A(t,`suggestedInput`))}}function Jr(e){let t=O(e);return{seq:Gn(t,`seq`),partial:t.partial??null}}function Yr(e){let t=O(e);if(t.partial===void 0)throw Error(`Expected field: partial`);return{page:Jn(t.page),status:qr(t.status),seq:Ti(t,`seq`),partial:t.partial}}function Xr(e){let t=O(e),n=Ti(t,`catalogRevision`),r=Si(t.sessions,ni,f,`sessions`);if(ri(r),ii(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:ai(t,`catalogId`,512),catalogRevision:n,sessions:r}}function Zr(e){let t=O(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=ai(t,`sessionId`,512),r=ai(t,`cwd`,l),i=si(t,`catalogRevision`),a=t.unread===null?null:ni(t.unread);if(a!==null&&(a.sessionId!==n||a.cwd!==r))throw Error(`Session unread event identity mismatch`);if(a!==null&&a.completionOrder>i)throw Error(`Session unread completion order exceeds catalog revision`);return{type:`sessions.unread`,catalogId:ai(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function Qr(e){let t=O(e);if(t.type!==`session.startup`)throw Error(`Invalid session startup event type`);let n=A(t,`startupToken`);if(n===``)throw Error(`Expected non-empty string field: startupToken`);return{type:`session.startup`,...N(`startupToken`,n),activity:$r(t.activity)}}function $r(e){let t=O(e);return{sessionId:wi(t,`sessionId`),phase:ti(t,`phase`),label:wi(t,`label`),...N(`detail`,A(t,`detail`)),at:wi(t,`at`),...N(`startup`,ei(t))}}function ei(e){let t=e.startup;if(t!==void 0){if(typeof t!=`boolean`)throw Error(`Expected optional boolean field: startup`);return t}}function ti(e,t){let n=k(e,t);if(n!==`active`&&n!==`idle`&&n!==`error`)throw Error(`Expected session activity phase field: ${t}`);return n}function ni(e){let t=O(e),n=ai(t,`completedAt`,64),r=new Date(n);if(!Number.isFinite(r.getTime())||r.toISOString()!==n)throw Error(`Invalid canonical session unread completion time`);let i=t.messageRange===void 0?void 0:O(t.messageRange),a;if(i!==void 0){let e=Ti(i,`start`),t=Ti(i,`end`),n=i.leafId;if(t<e||n!==null&&typeof n!=`string`)throw Error(`Invalid unread message range`);a={start:e,end:t,leafId:n}}return{sessionId:ai(t,`sessionId`,512),cwd:ai(t,`cwd`,l),completionOrder:si(t,`completionOrder`),completedAt:n,...a===void 0?{}:{messageRange:a}}}function ri(e){let t=e.map(e=>JSON.stringify([e.sessionId,e.cwd]));if(new Set(t).size!==t.length)throw Error(`Duplicate session unread identity`);let n=e.map(e=>e.completionOrder);if(new Set(n).size!==n.length)throw Error(`Duplicate session unread completion order`)}function ii(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.completionOrder<=r.completionOrder)throw Error(`Session unread summaries are not newest-first`)}}function ai(e,t,n){let r=wi(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function oi(e,t,n){let r=A(e,t);if(r!==void 0){if(r===``)throw Error(`Expected non-empty string field: ${t}`);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}}function si(e,t){let n=Ti(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function ci(e){let t=O(e),n=hi(t.summary),r=Si(t.notifications,gi,100,`notifications`);if(Ei(r),Di(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==ki(r))throw Error(`Notification snapshot severity mismatch`);let i=_i(t.dismissThrough),a=r[0]?.order??0;if(i.order!==a)throw Error(`Notification snapshot dismiss cutoff mismatch`);if(i.overflowWatermark<n.discardedCount)throw Error(`Notification snapshot overflow cutoff mismatch`);return{daemonInstanceId:wi(t,`daemonInstanceId`),catalogRevision:Ti(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function li(e){let t=O(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=hi(t.summary),r=_i(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=vi(t.delta);if(i.kind===`cleared`&&!Oi(n))throw Error(`Notification clear event summary mismatch`);if(i.kind===`added`&&n.retainedCount===0)throw Error(`Notification add event summary mismatch`);return{type:`notifications.inbox`,daemonInstanceId:wi(t,`daemonInstanceId`),catalogRevision:Ti(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function ui(e){let t=O(e),n=M(pi)(t.notices),r=n.map(e=>e.id);if(new Set(r).size!==r.length)throw Error(`Duplicate server notice id`);return{daemonInstanceId:wi(t,`daemonInstanceId`),revision:Ti(t,`revision`),notices:n}}function di(e){let t=O(e);if(t.type!==`notices.updated`)throw Error(`Invalid server notice event type`);return{type:`notices.updated`,snapshot:ui(t.snapshot)}}function fi(e){let t=O(e);if(t.type!==`models.changed`)throw Error(`Invalid model scope event type`);return{type:`models.changed`,revision:Ti(t,`revision`)}}function pi(e){let t=O(e),n=wi(t,`createdAt`);if(!Number.isFinite(Date.parse(n)))throw Error(`Invalid server notice creation time`);let r=A(t,`source`),i=t.context===void 0?void 0:dr(t.context,`server notice context`),a=t.scope===void 0?void 0:Pn(t.scope,`server notice scope`);return{id:wi(t,`id`),severity:mi(t.severity),message:k(t,`message`),createdAt:n,...N(`source`,r),...N(`scope`,a),...N(`context`,i)}}function mi(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid server notice severity`);return e}function hi(e){let t=O(e),n=Ti(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=Ti(t,`discardedCount`),i=bi(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:wi(t,`sessionId`),cwd:wi(t,`cwd`),inboxRevision:Ti(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function gi(e){let t=O(e),n=k(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=k(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=Ti(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:wi(t,`id`),message:n,truncated:j(t,`truncated`),severity:yi(t.severity),receivedAt:r,order:i}}function _i(e){let t=O(e);return{order:Ti(t,`order`),overflowWatermark:Ti(t,`overflowWatermark`)}}function vi(e){let t=O(e);switch(t.kind){case`added`:{let e=A(t,`evictedNotificationId`);return{kind:`added`,notification:gi(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=Si(t.notificationIds,Ci,100,`notificationIds`);if(new Set(e).size!==e.length)throw Error(`Duplicate dismissed notification id`);return{kind:`dismissed`,notificationIds:e}}case`cleared`:return{kind:`cleared`,reason:xi(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function yi(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function bi(e){return e===void 0?void 0:yi(e)}function xi(e){switch(e){case`runtime-close`:case`archive`:case`delete`:case`restore`:case`archive-reconcile`:case`replacement`:case`initialization-failed`:case`service-dispose`:return e;default:throw Error(`Invalid notification clear reason`)}}function Si(e,t,n,r){if(!Array.isArray(e))throw Error(`Expected array field: ${r}`);if(e.length>n)throw Error(`Array field exceeds limit: ${r}`);return e.map(t)}function Ci(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function wi(e,t){let n=k(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function Ti(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Expected non-negative safe integer field: ${t}`);return n}function Ei(e){if(new Set(e.map(e=>e.id)).size!==e.length)throw Error(`Duplicate notification id`);if(new Set(e.map(e=>e.order)).size!==e.length)throw Error(`Duplicate notification order`)}function Di(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.order<=r.order)throw Error(`Notifications are not newest-first`)}}function Oi(e){return e.retainedCount===0&&e.discardedCount===0}function ki(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function Ai(e){let t=O(e),n=t.skippedBusySessionIds===void 0?void 0:qn(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:k(t,`generatedAt`),thresholds:Fi(t.thresholds),projects:M(Ii)(t.projects),totals:Li(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function ji(e){let t=O(e);return{...Ai(t),archivedSessionIds:qn(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:qn(t.deletedSessionIds,`deletedSessionIds`)}}function Mi(e){let t=O(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:qn(t.archivedSessionIds,`archivedSessionIds`),failures:M(Pi)(t.failures),generatedAt:k(t,`generatedAt`)}}function Ni(e){let t=O(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:qn(t.deletedSessionIds,`deletedSessionIds`),failures:M(Pi)(t.failures),generatedAt:k(t,`generatedAt`)}}function Pi(e){let t=O(e);return{sessionId:k(t,`sessionId`),error:k(t,`error`)}}function Fi(e){let t=O(e);return{...N(`archiveIdleDays`,Uo(t,`archiveIdleDays`)),...N(`deleteArchivedDays`,Uo(t,`deleteArchivedDays`))}}function Ii(e){let t=O(e);return{cwd:k(t,`cwd`),archiveCount:Gn(t,`archiveCount`),deleteCount:Gn(t,`deleteCount`)}}function Li(e){let t=O(e);return{archiveCount:Gn(t,`archiveCount`),deleteCount:Gn(t,`deleteCount`)}}function Ri(e){let t=O(e),n=k(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:k(t,`text`),...N(`hasAttachments`,Ho(t,`hasAttachments`)),...N(`attachmentCount`,t.attachmentCount===void 0?void 0:Ti(t,`attachmentCount`))}}function zi(e){let t=O(e);return{input:Gn(t,`input`),output:Gn(t,`output`),cacheRead:Gn(t,`cacheRead`),cacheWrite:Gn(t,`cacheWrite`),total:Gn(t,`total`)}}function Bi(e){let t=O(e);return{...N(`provider`,A(t,`provider`)),...N(`id`,A(t,`id`)),...N(`name`,A(t,`name`)),...N(`contextWindow`,Uo(t,`contextWindow`)),...N(`reasoning`,t.reasoning)}}function Vi(e){return e===void 0?{}:{model:Bi(e)}}function Hi(e){let t=O(e);return{models:M(Bi)(t.models)}}function Ui(e){let t=O(e);return{provider:k(t,`provider`),id:k(t,`id`),...N(`name`,A(t,`name`)),...N(`contextWindow`,Uo(t,`contextWindow`)),...N(`reasoning`,t.reasoning),enabled:j(t,`enabled`),...N(`editable`,Ho(t,`editable`)),...N(`catalogIndex`,t.catalogIndex===void 0?void 0:Ti(t,`catalogIndex`))}}function Wi(e){let t=O(e);return{models:M(Ui)(t.models)}}function Gi(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Ki(e){let t=O(e);return{levels:M(Gi)(t.levels)}}function qi(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Ji(e){if(e!==`stored`&&e!==`runtime`&&e!==`environment`&&e!==`fallback`&&e!==`models_json_key`&&e!==`models_json_command`)throw Error(`Invalid auth status source`);return e}function Yi(e){let t=O(e),n=t.source===void 0?void 0:Ji(t.source);return{configured:j(t,`configured`),...N(`source`,n),...N(`label`,A(t,`label`))}}function Xi(e){let t=O(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:k(t,`id`),name:k(t,`name`),authType:qi(t.authType),status:Yi(t.status),...n===void 0?{}:{loginFlow:n}}}function Zi(e){let t=O(e);return{providers:M(Xi)(t.providers)}}function Qi(e){let t=O(e);return{servers:M(e=>{let t=O(e);return{name:k(t,`name`),...N(`description`,A(t,`description`))}})(t.servers)}}function $i(e){let t=O(e),n=t.target;if(n!==void 0&&n!==`mcp`)throw Error(`Invalid login flow target`);let r=t.mcpMode;if(r!==void 0&&r!==`login`&&r!==`logout`)throw Error(`Invalid MCP authentication mode`);let i={flowId:k(t,`flowId`),providerId:k(t,`providerId`),providerName:k(t,`providerName`),...n===void 0?{}:{target:n},...r===void 0?{}:{mcpMode:r},...N(`cancelRequested`,Ho(t,`cancelRequested`)),status:ea(t.status),progress:M(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...N(`error`,A(t,`error`)),...N(`auth`,ta(t.auth)),...N(`prompt`,ra(t.prompt)),...N(`select`,aa(t.select)),...N(`info`,oa(t.info))};if(i.target===`mcp`&&i.auth!==void 0){let e=new URL(i.auth.url);if(e.protocol!==`https:`&&e.protocol!==`http:`)throw Error(`Invalid MCP authorization URL`)}return i}function ea(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function ta(e){if(e===void 0)return;let t=O(e);return{url:k(t,`url`),...N(`instructions`,A(t,`instructions`)),...N(`deviceCode`,na(t.deviceCode))}}function na(e){if(e===void 0)return;let t=O(e);return{userCode:k(t,`userCode`),...N(`intervalSeconds`,Uo(t,`intervalSeconds`)),...N(`expiresInSeconds`,Uo(t,`expiresInSeconds`))}}function ra(e){if(e===void 0)return;let t=O(e),n=A(t,`kind`);if(n!==void 0&&n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0&&n!==void 0?n===`manual`?`manual_code`:`text`:ia(t.promptType);return{requestId:k(t,`requestId`),message:k(t,`message`),...N(`kind`,n),promptType:r,...N(`placeholder`,A(t,`placeholder`)),...N(`allowEmpty`,Ho(t,`allowEmpty`))}}function ia(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function aa(e){if(e===void 0)return;let t=O(e);return{requestId:k(t,`requestId`),message:k(t,`message`),options:M(ko)(t.options)}}function oa(e){if(e!==void 0)return M(e=>{let t=O(e);return{message:k(t,`message`),...N(`links`,t.links===void 0?void 0:M(sa)(t.links))}})(e)}function sa(e){let t=O(e);return{url:k(t,`url`),...N(`label`,A(t,`label`))}}function ca(e){if(e===void 0)return{};let t=O(e);return{contextUsage:{tokens:Wo(t,`tokens`),contextWindow:Gn(t,`contextWindow`),percent:Wo(t,`percent`)}}}function la(e){let t=O(e),n=k(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:k(t,`name`),source:n,...N(`description`,A(t,`description`)),...N(`argumentHint`,A(t,`argumentHint`))}}function ua(e){let t=O(e),n=k(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:k(t,`path`),kind:n}}function da(e){let t=O(e);return{path:k(t,`path`),entries:M(ma)(t.entries),scannedAt:k(t,`scannedAt`),truncated:j(t,`truncated`)}}function fa(e){let t=O(e);return{results:M(pa)(t.results)}}function pa(e){let t=O(e),n=k(t,`path`),r=t.tree,i=t.error;if(r===void 0==(i===void 0))throw Error(`File tree batch result must contain exactly one of tree or error`);return r===void 0?{path:n,error:k(t,`error`)}:{path:n,tree:da(r)}}function ma(e){let t=O(e),n=k(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:k(t,`name`),path:k(t,`path`),type:n,...N(`size`,Uo(t,`size`)),...N(`modifiedAt`,A(t,`modifiedAt`))}}function ha(e){let t=O(e),n=k(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:k(t,`path`),...N(`language`,A(t,`language`)),...N(`mediaType`,ya(t.mediaType)),...N(`mimeType`,A(t,`mimeType`)),encoding:n,size:Gn(t,`size`),modifiedAt:k(t,`modifiedAt`),content:k(t,`content`),truncated:j(t,`truncated`),binary:j(t,`binary`)}}function ga(e){let t=O(e);return{path:k(t,`path`),size:Gn(t,`size`),modifiedAt:k(t,`modifiedAt`),created:j(t,`created`)}}function _a(e){let t=O(e);return{path:k(t,`path`),existed:j(t,`existed`)}}function va(e){let t=O(e);return{fromPath:k(t,`fromPath`),toPath:k(t,`toPath`),size:Gn(t,`size`),modifiedAt:k(t,`modifiedAt`)}}function ya(e){if(e!==void 0){if(e!==`image`&&e!==`html`&&e!==`pdf`&&e!==`markdown`)throw Error(`Invalid file media type`);return e}}function ba(e){let t=O(e);return{id:k(t,`id`),cwd:k(t,`cwd`),name:k(t,`name`),createdAt:k(t,`createdAt`),exited:j(t,`exited`),...N(`exitCode`,Uo(t,`exitCode`)),...N(`commandRunId`,A(t,`commandRunId`))}}function xa(e){let t=O(e);return{id:k(t,`id`),origin:k(t,`origin`),projectId:k(t,`projectId`),workspaceId:k(t,`workspaceId`),terminalId:k(t,`terminalId`),title:k(t,`title`),command:k(t,`command`),status:Sa(t.status),...N(`exitCode`,Uo(t,`exitCode`)),createdAt:k(t,`createdAt`),...N(`startedAt`,A(t,`startedAt`)),...N(`completedAt`,A(t,`completedAt`)),metadata:Ca(t.metadata,`metadata`)}}function Sa(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function Ca(e,t){let n=O(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected string record field: ${t}.${e}`);return[e,n]}))}function wa(e){let t=O(e);return{cwd:k(t,`cwd`),hasSessionActivity:j(t,`hasSessionActivity`),hasTerminalActivity:j(t,`hasTerminalActivity`),updatedAt:k(t,`updatedAt`)}}function Ta(e){let t=O(e);return{workspaces:M(wa)(t.workspaces),generatedAt:k(t,`generatedAt`)}}function Ea(e){let t=Rn(e);if(t===void 0)throw Error(`Expected machine status snapshot`);return t}function Da(e){let t=O(e);return{path:k(t,`path`),exists:j(t,`exists`),config:Oa(t.config),effectiveConfig:Oa(t.effectiveConfig),envOverrides:za(t.envOverrides)}}function Oa(e){let t=O(e);return{...N(`host`,A(t,`host`)),...N(`port`,Uo(t,`port`)),...N(`allowedHosts`,Aa(t.allowedHosts)),...N(`shortcuts`,La(t.shortcuts)),...N(`defaultTheme`,t.defaultTheme===void 0?void 0:gn(t.defaultTheme,`response`)),...N(`defaultStreamingBehavior`,t.defaultStreamingBehavior===void 0?void 0:_n(t.defaultStreamingBehavior,`response`)),...N(`plugins`,Ra(t.plugins)),...N(`pathAccess`,ja(t.pathAccess)),...N(`uploads`,Na(t.uploads)),...N(`attachments`,Pa(t.attachments)),...N(`maxUploadBytes`,Uo(t,`maxUploadBytes`)),...N(`agent`,ka(t.agent)),...N(`spawnSessions`,Ho(t,`spawnSessions`)),...N(`subsessions`,Ho(t,`subsessions`)),...N(`askUser`,Ho(t,`askUser`)),...N(`sessionNaming`,t.sessionNaming===void 0?void 0:yn(t.sessionNaming,`response`)),...N(`sessionArchive`,t.sessionArchive===void 0?void 0:bn(t.sessionArchive,`response`))}}function ka(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid PI WEB agent field`);return{...N(`command`,A(e,`command`)),...N(`dir`,A(e,`dir`))}}}function Aa(e){if(e!==void 0){if(e===!0)return!0;if(Fa(e))return e;throw Error(`Invalid PI WEB allowedHosts field`)}}function ja(e){if(e===void 0)return;if(!Wn(e))throw Error(`Invalid PI WEB pathAccess field`);let t=e.allowedPaths;return{...N(`allowedPaths`,Ma(t,`pathAccess.allowedPaths`))}}function Ma(e,t){if(e!==void 0){if(Ia(e))return e;throw Error(`Invalid PI WEB ${t} field`)}}function Na(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid PI WEB uploads field`);return{...N(`defaultFolder`,A(e,`defaultFolder`))}}}function Pa(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid PI WEB attachments field`);return{...N(`defaultFolder`,A(e,`defaultFolder`))}}}function Fa(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Ia(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function La(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid PI WEB shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEB shortcut field`);return[e,t]}))}}function Ra(e){if(e!==void 0){if(!Wn(e)||Array.isArray(e))throw Error(`Invalid PI WEB plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!Wn(t)||Array.isArray(t))throw Error(`Invalid PI WEB plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEB plugin enabled field`);let r=t.settings;if(r!==void 0&&(!Wn(r)||Array.isArray(r)))throw Error(`Invalid PI WEB plugin settings field`);return[e,t]}))}}function za(e){let t=O(e);return{host:j(t,`host`),port:j(t,`port`),allowedHosts:j(t,`allowedHosts`),spawnSessions:j(t,`spawnSessions`),subsessions:j(t,`subsessions`),askUser:j(t,`askUser`),agentCommand:Ho(t,`agentCommand`)??!1,agentDir:Ho(t,`agentDir`)??!1,...Ba(t),agentSessionDir:Ho(t,`agentSessionDir`)??!1}}function Ba(e){let t=e.agentDirSource;if(t===void 0)return{};if(t!==`pi-web`&&t!==`pi-compatibility`)throw Error(`Invalid PI WEB agentDirSource field`);return{agentDirSource:t}}function Va(e){let t=O(e);return{packages:M(Ua)(t.packages),...N(`installableKnownPackages`,Wa(t.installableKnownPackages))}}function Ha(e){let t=O(e),n=A(t,`source`),r=t.scope===void 0?void 0:Ka(t.scope),i=io(t.removed,`removed`);return{action:qa(t.action),...N(`source`,n),...N(`scope`,r),...N(`removed`,i),packages:M(Ua)(t.packages),...N(`installableKnownPackages`,Wa(t.installableKnownPackages))}}function Ua(e){let t=O(e);return{source:k(t,`source`),scope:Ka(t.scope),filtered:j(t,`filtered`),...N(`installedPath`,A(t,`installedPath`))}}function Wa(e){return e===void 0?void 0:M(Ga)(e)}function Ga(e){let t=O(e);return{id:k(t,`id`),label:k(t,`label`),description:k(t,`description`),source:k(t,`source`)}}function Ka(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function qa(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Ja(e){let t=O(e),r=M(Ya)(t.plugins);if(t.lifecycleVersion===void 0)return{lifecycleVersion:2,plugins:r,diagnostics:[],serverRuntime:{status:`incompatible`,terminalMode:`required`,restartRequired:!1,message:n(`ui.main.fe09b19a1f40`,`PI WEB does not support plugin lifecycle diagnostics. Update and restart PI WEB, then try again.`),recovery:to()}};if(t.lifecycleVersion!==2)throw Error(`Unsupported PI WEB plugin lifecycle version`);return{lifecycleVersion:2,plugins:r,diagnostics:M(Qa)(t.diagnostics),serverRuntime:$a(t.serverRuntime)}}function Ya(e){let t=O(e),n=k(t,`id`),r=t.server===void 0?void 0:Xa(t.server,n),i=A(t,`backendRevision`),a=no(t.pairedRequestVersion),o=no(t.pairedChannelVersion);if((a!==void 0||o!==void 0)&&i===void 0)throw Error(`Invalid PI WEB plugin paired capability`);let s=io(t.required,`required`);if(s===!1)throw Error(`Invalid PI WEB required plugin marker`);return{id:n,...s===!0?{required:!0}:{},...N(`module`,A(t,`module`)),...i===void 0?{}:{backendRevision:i},...a===void 0?{}:{pairedRequestVersion:a},...o===void 0?{}:{pairedChannelVersion:o},source:k(t,`source`),scope:ro(t.scope),machineSpecific:io(t.machineSpecific,`machineSpecific`)??!1,enabled:j(t,`enabled`),discovered:io(t.discovered,`discovered`)??!0,conflict:io(t.conflict,`conflict`)??!1,...r===void 0?{}:{server:r}}}function Xa(e,t){let n=O(e),r=n.state,i=n.phase;if(r!==`active`&&r!==`failed`&&r!==`incompatible`&&r!==`disabled`&&r!==`missing`&&r!==`unknown`)throw Error(`Invalid PI WEB server plugin state`);if(i!==void 0&&i!==`import`&&i!==`activate`&&i!==`validate`&&i!==`start`&&i!==`health`&&i!==`dispose`)throw Error(`Invalid PI WEB server plugin phase`);let a=n.health===void 0?void 0:Za(n.health),o=k(n,`disableCommand`);if(o!==Un(t))throw Error(`Invalid PI WEB server plugin recovery command`);return{state:r,...N(`desiredRevision`,A(n,`desiredRevision`)),...N(`activeRevision`,A(n,`activeRevision`)),...i===void 0?{}:{phase:i},...N(`message`,A(n,`message`)),...a===void 0?{}:{health:a},staleRevision:j(n,`staleRevision`),restartRequired:j(n,`restartRequired`),disableCommand:o}}function Za(e){let t=O(e),n=t.status;if(n!==`healthy`&&n!==`degraded`&&n!==`unhealthy`)throw Error(`Invalid PI WEB server plugin health status`);return{status:n,...N(`message`,A(t,`message`))}}function Qa(e){let t=O(e),n=t.kind,r=t.snapshot;if(n!==`conflict`&&n!==`discovery`)throw Error(`Invalid PI WEB plugin diagnostic kind`);if(r!==`desired`&&r!==`active`)throw Error(`Invalid PI WEB plugin diagnostic snapshot`);return{kind:n,snapshot:r,source:k(t,`source`),message:k(t,`message`),...N(`pluginId`,A(t,`pluginId`))}}function $a(e){let t=O(e),n=t.status,r=t.terminalMode,i=t.safeStart,a=t.desiredSafeStart;if(n!==`available`&&n!==`unavailable`&&n!==`incompatible`)throw Error(`Invalid PI WEB server-plugin runtime status`);if(r!==`required`&&r!==`recovery-disabled`)throw Error(`Invalid PI WEB Terminal plugin mode`);if(i!==void 0&&i!==`bundled-only`&&i!==`none`)throw Error(`Invalid PI WEB server-plugin safe-start state`);if(a!==void 0&&a!==`off`&&a!==`bundled-only`&&a!==`none`)throw Error(`Invalid desired PI WEB server-plugin safe-start state`);if(n!==`available`&&r===`recovery-disabled`)throw Error(`Unavailable PI WEB runtime cannot declare Terminal recovery mode`);if(i===`none`!=(r===`recovery-disabled`)&&n===`available`)throw Error(`PI WEB Terminal plugin mode does not match safe start`);return{status:n,terminalMode:r,...i===void 0?{}:{safeStart:i},...a===void 0?{}:{desiredSafeStart:a},restartRequired:j(t,`restartRequired`),...N(`message`,A(t,`message`)),recovery:eo(t.recovery)}}function eo(e){let t=O(e),n={showSafeStart:k(t,`showSafeStart`),bundledOnly:k(t,`bundledOnly`),noServerPlugins:k(t,`noServerPlugins`),clearSafeStart:k(t,`clearSafeStart`)};if(n.showSafeStart!==Hn.showSafeStart||n.bundledOnly!==Hn.bundledOnly||n.noServerPlugins!==Hn.noServerPlugins||n.clearSafeStart!==Hn.clearSafeStart)throw Error(`Invalid PI WEB server plugin recovery commands`);return n}function to(){return{...Hn}}function no(e){if(e!==void 0){if(e!==1)throw Error(`Invalid PI WEB plugin paired capability version`);return 1}}function ro(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEB plugin scope`);return e}function io(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function ao(e){let t=O(e);return{packageName:k(t,`packageName`),generatedAt:k(t,`generatedAt`),components:so(t.components),release:po(t.release),commands:mo(t.commands),messages:M(ho)(t.messages)}}function oo(e){let t=O(e);return{packageName:k(t,`packageName`),generatedAt:k(t,`generatedAt`),components:co(t.components),capabilities:_o(t.capabilities)}}function so(e){let t=O(e);return{web:uo(t.web),sessiond:uo(t.sessiond)}}function co(e){let t=O(e);return{web:lo(t.web),sessiond:lo(t.sessiond)}}function lo(e){let t=O(e),n=go(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:Sn(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:k(t,`label`),...N(`runtimeVersion`,A(t,`runtimeVersion`)),...N(`piVersion`,A(t,`piVersion`)),available:j(t,`available`),capabilities:_o(t.capabilities),...N(`activeAgentProfile`,i),...N(`deprecatedAgentInputs`,jn(t.deprecatedAgentInputs)),...N(`error`,A(t,`error`))}}function uo(e){let t=O(e);return{component:go(t.component),label:k(t,`label`),...N(`runtimeVersion`,A(t,`runtimeVersion`)),...N(`installedVersion`,A(t,`installedVersion`)),...N(`piVersion`,A(t,`piVersion`)),stale:j(t,`stale`),available:j(t,`available`),...N(`installation`,fo(t.installation)),...N(`error`,A(t,`error`))}}function fo(e){if(e===void 0)return;let t=O(e),n=k(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEB installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEB installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEB Docker mode`);return{kind:n,...N(`path`,A(t,`path`)),...N(`source`,A(t,`source`)),...r===void 0?{}:{scope:r},...N(`npmRoot`,A(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function po(e){let t=O(e);return{packageName:k(t,`packageName`),...N(`latestVersion`,A(t,`latestVersion`)),updateAvailable:j(t,`updateAvailable`),...N(`checkedAt`,A(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...N(`error`,A(t,`error`))}}function mo(e){let t=O(e);return{...N(`update`,A(t,`update`)),...N(`restart`,A(t,`restart`)),...N(`restartWeb`,A(t,`restartWeb`)),...N(`restartSessiond`,A(t,`restartSessiond`)),...N(`status`,A(t,`status`))}}function ho(e){let t=O(e);return{id:k(t,`id`),severity:vo(t.severity),title:k(t,`title`),body:k(t,`body`),...N(`command`,A(t,`command`))}}function go(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEB service component`);return e}function _o(e){let t=An(e);if(t===void 0)throw Error(`Invalid PI WEB capabilities`);return t}function vo(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEB status severity`);return e}function yo(e){let t=O(e),n=k(t,`type`);if(n===`unsupported`)return{type:n,message:k(t,`message`)};if(n===`select`)return{type:n,requestId:k(t,`requestId`),title:k(t,`title`),options:M(ko)(t.options)};if(n===`tree`)return{type:n,tree:bo(t.tree)};if(n===`done`)return{type:n,...N(`message`,A(t,`message`)),...Ao(t.session),...N(`promptDraft`,A(t,`promptDraft`))};throw Error(`Invalid command result type`)}function bo(e){let t=O(e),n=M(xo)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=Eo(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:Oo(t.activePathIds,`activePathIds`)}}function xo(e){let t=O(e);return{id:Do(t,`id`),parentId:Eo(t,`parentId`),kind:So(t.kind),summary:k(t,`summary`),...N(`timestamp`,A(t,`timestamp`)),...N(`label`,A(t,`label`))}}function So(e){switch(e){case`user`:case`assistant`:case`tool-result`:case`bash`:case`custom-message`:case`compaction`:case`branch-summary`:case`model-change`:case`thinking-level-change`:case`session-info`:case`label`:case`custom`:case`other`:return e;default:throw Error(`Invalid session tree node kind`)}}function Co(e){let t=O(e),n=j(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){To(t,`editorText`,`session tree cancellation result`);let e=t.aborted;if(e!==void 0&&typeof e!=`boolean`)throw Error(`Expected optional boolean field: aborted`);return{cancelled:n,...e===void 0?{}:{aborted:e}}}return To(t,`aborted`,`session tree navigation result`),{cancelled:n,...N(`editorText`,A(t,`editorText`))}}function wo(e){let t=O(e),n=j(t,`cancelled`);return n?(To(t,`session`,`session tree fork cancellation result`),To(t,`promptDraft`,`session tree fork cancellation result`),{cancelled:n}):{cancelled:n,session:hr(t.session),...N(`promptDraft`,A(t,`promptDraft`))}}function To(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function Eo(e,t){let n=e[t];if(n!==null&&typeof n!=`string`)throw Error(`Expected string or null field: ${t}`);if(typeof n==`string`&&n.trim()===``)throw Error(`Expected non-blank string or null field: ${t}`);return n}function Do(e,t){let n=k(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function Oo(e,t){let n=qn(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function ko(e){let t=O(e);return{value:k(t,`value`),label:k(t,`label`),...N(`description`,A(t,`description`))}}function Ao(e){return e===void 0?{}:{session:hr(e)}}function jo(e){if(O(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function Mo(e){let t=O(e);return M(No)(t.attachments)}function No(e){let t=O(e);return{path:k(t,`path`),mimeType:k(t,`mimeType`),size:Gn(t,`size`)}}function Po(e){if(O(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function Fo(e){if(O(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function Io(e){if(O(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function Lo(e){let t=O(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:qn(t.sessionIds,`sessionIds`),r=Uo(t,`archivedCount`),i=Uo(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function Ro(e){if(O(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function zo(e){if(O(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function Bo(e){if(O(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function Vo(e){if(O(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function Ho(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEB ${t} field`);return n}}function Uo(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function Wo(e,t){let n=e[t];if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected number|null field: ${t}`);return n}function N(e,t){return t===void 0?{}:{[e]:t}}function Go(e){let t=O(e);switch(t.type){case`message.append`:return{type:`message.append`,message:qo(t,`message`)};case`assistant.start`:return{type:`assistant.start`,message:qo(t,`message`)};case`assistant.delta`:return{type:`assistant.delta`,text:k(t,`text`),...N(`streamId`,A(t,`streamId`))};case`assistant.thinking.delta`:return{type:`assistant.thinking.delta`,text:k(t,`text`),...N(`streamId`,A(t,`streamId`))};case`tool.start`:return{type:`tool.start`,toolName:k(t,`toolName`),toolCallId:k(t,`toolCallId`),summary:k(t,`summary`),...N(`args`,t.args)};case`tool.update`:return{type:`tool.update`,toolName:k(t,`toolName`),toolCallId:k(t,`toolCallId`),text:k(t,`text`),...N(`content`,t.content),...N(`details`,t.details)};case`tool.end`:return{type:`tool.end`,toolName:k(t,`toolName`),toolCallId:k(t,`toolCallId`),text:k(t,`text`),isError:j(t,`isError`),...N(`content`,t.content),...N(`details`,t.details)};case`shell.start`:return{type:`shell.start`,command:k(t,`command`),...N(`excludeFromContext`,io(t.excludeFromContext,`excludeFromContext`))};case`shell.chunk`:return{type:`shell.chunk`,chunk:k(t,`chunk`)};case`shell.end`:return{type:`shell.end`,...N(`output`,A(t,`output`)),...N(`exitCode`,Jo(t,`exitCode`)),...N(`cancelled`,io(t.cancelled,`cancelled`)),...N(`truncated`,io(t.truncated,`truncated`)),...N(`fullOutputPath`,A(t,`fullOutputPath`)),...N(`isError`,io(t.isError,`isError`))};case`agent.start`:return{type:`agent.start`};case`agent.end`:return{type:`agent.end`};case`message.end`:return{type:`message.end`,...N(`message`,t.message)};case`status.update`:return{type:`status.update`,status:qr(t.status)};case`activity.update`:return{type:`activity.update`,activity:$r(t.activity)};case`command.output`:return Yo(t);case`session.error`:return{type:`session.error`,message:k(t,`message`)};case`session.diagnostic`:return{type:`session.diagnostic`,message:k(t,`message`)};case`session.name`:return Xo(t);case`session.created`:return{type:`session.created`,session:hr(t.session)};case`session.tree.changed`:return{type:`session.tree.changed`};case`pi.event`:return{type:`pi.event`,eventType:k(t,`eventType`)};default:throw Error(`Unsupported session stream event type`)}}function Ko(e){let t=O(e);switch(t.type){case`status.update`:return{type:`status.update`,status:qr(t.status)};case`activity.update`:return{type:`activity.update`,activity:$r(t.activity)};case`session.name`:return Xo(t);case`session.created`:return{type:`session.created`,session:hr(t.session)};case`models.changed`:return fi(t);case`workspaces.changed`:return{type:`workspaces.changed`,projectId:wi(t,`projectId`)};case`notices.updated`:return di(t);case`machine.status`:return{type:`machine.status`,status:Ea(t.status)};default:throw Error(`Unsupported realtime stream event type`)}}function qo(e,t){let n=e[t];if(n===void 0)throw Error(`Expected field: ${t}`);return n}function Jo(e,t){let n=e[t];if(n!==void 0){if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected optional number|null field: ${t}`);return n}}function Yo(e){let t=k(e,`level`);if(t!==`info`&&t!==`success`&&t!==`error`)throw Error(`Invalid command output level`);return{type:`command.output`,level:t,message:k(e,`message`),...N(`notificationId`,A(e,`notificationId`))}}function Xo(e){return{type:`session.name`,sessionId:wi(e,`sessionId`),...N(`name`,A(e,`name`))}}function Zo(e){let t=O(e),n=t.decision;if(n!==!0&&n!==!1&&n!==null)throw Error(`Invalid workspace trust decision`);return{path:k(t,`path`),decision:n,trusted:j(t,`trusted`)}}function Qo(e,t){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0&&typeof t==`number`&&Number.isSafeInteger(t)&&t>0?{width:e,height:t}:void 0}var $o=`reference`;function es(e){return typeof e==`string`&&/^[0-9a-f]{64}$/u.test(e)}function ts(e,t,n,r){let i=new URLSearchParams({cwd:e.cwd});return n?.limit!==void 0&&i.set(`limit`,String(n.limit)),n?.before!==void 0&&i.set(`before`,String(n.before)),i.set(`media`,$o),`api/machines/${encodeURIComponent(r)}/sessions/${encodeURIComponent(e.id)}/${t}?${i.toString()}`}function ns(e,t,n=`local`){return ts(e,`messages`,t,n)}function rs(e,t,n=`local`){return ts(e,`transcript-snapshot`,t,n)}function is(e,t=`local`){return ts(e,`stream-snapshot`,void 0,t)}function as(e,t=`local`){return ts(e,`events`,void 0,t)}function os(e,t,n=`local`){let r=new URLSearchParams({cwd:e.cwd}),i=`api/machines/${encodeURIComponent(n)}/sessions/${encodeURIComponent(e.id)}/media/${encodeURIComponent(t)}?${r.toString()}`,a=y(i);return new URL(Ce(a),a).href}function ss(e,t,n,r){let i=new URLSearchParams({path:n});r?.createDirs===!1&&i.set(`createDirs`,`false`),r?.overwrite===!1&&i.set(`overwrite`,`false`);let a=`api/machines/${encodeURIComponent(r?.machineId??`local`)}`;return y(Ce(`${a}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`))}function cs(e,t,n,r){let i=new URLSearchParams;i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),r?.download===!0&&i.set(`download`,`1`);let a=`api/machines/${encodeURIComponent(r?.machineId??`local`)}`;return Ce(`${a}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}function ls(e,t,n,r){return y(cs(e,t,n,r))}function us(e,t,n,r){return ls(e,t,n,{...r,download:!0})}var P=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`,ds={projectTrust:(e,t=`local`)=>D(`${P(t)}/projects/trust?${new URLSearchParams({path:e})}`,Zo),workspaceTrust:(e,t,n=`local`)=>D(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/trust`,Zo),setWorkspaceTrust:(e,t,n,r=`local`)=>D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/trust`,Zo,{method:`PUT`,body:JSON.stringify({trusted:n})})};function fs(e,t=`local`){return`${P(t)}/sessions/${encodeURIComponent(e.id)}`}function F(e,t,n=`local`){return`${fs(e,n)}/${t}`}function ps(e,t,n=`local`){return`${F(e,t,n)}${hs(e)}`}function ms(e,t=`local`,n){return`${fs(e,t)}${hs(e,n===void 0?{}:{scopeProjectId:n})}`}function hs(e,t={}){return`?${new URLSearchParams({cwd:e.cwd,...t}).toString()}`}function I(e,t={}){return JSON.stringify({cwd:e.cwd,...t})}function gs(e,t){let n={sessions:e.map(({id:e,cwd:t})=>({id:e,cwd:t})),...t===void 0?{}:{scopeProjectId:t}};return JSON.stringify(n)}function _s(e,t){let n=new URLSearchParams;t.projectId!==void 0&&n.set(`projectId`,t.projectId);let r=n.toString();return`${P(t.machineId)}/auth/${e}${r===``?``:`?${r}`}`}function vs(e){return e===`local`?`api/pi-web/status`:`${P(e)}/pi-web/status`}var ys={piWebStatus:(e=`local`)=>D(vs(e),ao),checkForUpdates:(e=`local`)=>D(`${vs(e)}?refresh=1`,ao,{cache:`no-store`}),piWebRuntime:()=>D(`api/pi-web/runtime`,oo)},bs={machines:()=>D(`api/machines`,Yn),addMachine:e=>D(`api/machines`,Xn,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>D(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>D(`api/machines/${encodeURIComponent(e)}/health`,Zn),runtime:(e,t=!1)=>D(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,Qn,t?{cache:`no-store`}:{})};function xs(e){return e===void 0?`api/config`:`${P(e)}/config`}function Ss(e){return e===void 0?`api/plugins`:`${P(e)}/plugins`}var Cs={namingModels:e=>{let t=new URLSearchParams;e.projectId!==void 0&&t.set(`projectId`,e.projectId);let n=t.toString();return D(`${P(e.machineId)}/models${n===``?``:`?${n}`}`,Hi)},config:e=>D(xs(e),Da),saveConfig:(e,t)=>D(xs(t),Da,{method:`PUT`,body:JSON.stringify({config:e})})},ws={status:()=>D(`api/normal-auth/status`,gr),setup:e=>D(`api/normal-auth/setup`,jo,{method:`POST`,body:JSON.stringify({password:e})}),login:e=>D(`api/normal-auth/login`,jo,{method:`POST`,body:JSON.stringify({password:e})}),changePassword:(e,t)=>D(`api/normal-auth/change-password`,jo,{method:`POST`,body:JSON.stringify({currentPassword:e,newPassword:t})})},Ts={plugins:e=>D(Ss(e),Ja)};function Es(e=``,t){let n=t===void 0?`api/pi-packages`:`${P(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var Ds={packages:e=>D(Es(``,e),Va),install:(e,t)=>{let n={source:e};return D(Es(`install`,t),Ha,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return D(Es(`remove`,n),Ha,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return D(Es(`update`,t),Ha,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}},Os={workspaceActivity:(e=`local`)=>D(`${P(e)}/activity`,Ta)},ks={machineStatus:(e=`local`)=>D(`${P(e)}/status`,Ea)},As={snapshot:(e=`local`)=>D(`${P(e)}/notices`,ui,{cache:`no-store`}),dismiss:(e,t,n)=>{let r={daemonInstanceId:t,noticeId:n};return D(`${P(e)}/notices/dismiss`,ui,{method:`POST`,body:JSON.stringify(r)})}},js={projects:(e=`local`)=>D(`${P(e)}/projects`,M(nr)),addProject:(e,t,n,r=`local`)=>D(`${P(r)}/projects`,nr,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>D(`${P(t)}/projects/${encodeURIComponent(e)}`,Po,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>D(`${P(t)}/project-directories?q=${encodeURIComponent(e)}`,M(ua))};function Ms(e,t,n,r,i,a=`local`){let o=new URLSearchParams({path:n});i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!1&&o.set(`overwrite`,`false`);let s=r instanceof Uint8Array,c=s?new Uint8Array(r):new TextEncoder().encode(r);return D(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,ga,{method:`PUT`,body:c,headers:{"Content-Type":s?`application/octet-stream`:`text/plain`}})}function Ns(e,t=`local`,n){return D(`${P(t)}/projects/${encodeURIComponent(e)}/workspaces`,t=>{let n=ir(t);if(n.projectId!==e)throw Error(`Workspace resolution project does not match request`);return n},n?.signal===void 0?void 0:{signal:n.signal})}var Ps={workspaceResolution:Ns,workspaces:async(e,t=`local`,n)=>fe()===`management`?D(`${P(t)}/projects/${encodeURIComponent(e)}/workspaces`,M(rr),n?.signal===void 0?void 0:{signal:n.signal}):[...(await Ns(e,t,n)).workspaces],deleteWorkspace:(e,t,n,r=`local`)=>{let i={precondition:n};return D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,e=>e,{method:`DELETE`,body:JSON.stringify(i)})},workspaceTree:(e,t,n=``,r=`local`,i)=>D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,da,i),workspaceTreeBatch:(e,t,n,r=`local`)=>{let i={paths:[...n]};return D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree/batch`,fa,{method:`POST`,body:JSON.stringify(i)})},workspaceFile:(e,t,n,r=`local`,i)=>D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,ha,i),optionalWorkspaceFile:(e,t,n,r=`local`)=>ln(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}&optional=true`,ha),createWorkspaceFile:(e,t,n,r=`local`)=>Ms(e,t,n,new Uint8Array,void 0,r),writeWorkspaceFile:Ms,deleteWorkspaceFile:(e,t,n,r=`local`)=>{let i=new URLSearchParams({path:n});return D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,_a,{method:`DELETE`})},moveWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({fromPath:n,toPath:r});return i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!0&&o.set(`overwrite`,`true`),D(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,va,{method:`POST`})},createWorkspaceDirectory:(e,t,n,r=`local`)=>D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,_r,{method:`POST`,body:JSON.stringify({path:n})}),moveWorkspaceDirectory:(e,t,n,r,i=`local`)=>D(`${P(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,_r,{method:`PATCH`,body:JSON.stringify({fromPath:n,toPath:r})}),deleteWorkspaceDirectory:(e,t,n,r=`local`)=>D(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(n)}`,vr,{method:`DELETE`}),downloadWorkspaceFile:(e,t,n,r=`local`)=>Us(e,t,n,r)},Fs={sessions:(e,t=`local`,n)=>D(`${P(t)}/sessions?cwd=${encodeURIComponent(e)}`,M(hr),n?.signal===void 0?void 0:{signal:n.signal}),search:(e,t,n=`local`)=>D(`${P(n)}/sessions/search?${new URLSearchParams({cwd:e,q:t}).toString()}`,M(hr)),searchContent:(e,t,n=`local`)=>D(`${P(n)}/sessions/search-content?${new URLSearchParams({cwd:e,q:t}).toString()}`,xr),pinned:(e,t=`local`)=>D(`${P(t)}/sessions/pins?cwd=${encodeURIComponent(e)}`,yr),pin:(e,t=`local`)=>D(`${fs(e,t)}/pin`,br,{method:`PUT`,body:I(e)}),unpin:(e,t=`local`)=>D(`${fs(e,t)}/pin${hs(e)}`,br,{method:`DELETE`}),unreadCatalog:(e=`local`)=>D(`${P(e)}/sessions/unread`,Xr,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return D(F(e,`unread/acknowledge`,r),Xr,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>D(ps(e,`notifications`,t),ci),dismissNotification:(e,t,n,r=`local`)=>D(F(e,`notifications/dismiss`,r),ci,{method:`POST`,body:I(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>D(F(e,`notifications/dismiss-all`,r),ci,{method:`POST`,body:I(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>D(`${P(t)}/sessions`,hr,{method:`POST`,body:JSON.stringify(n===void 0?{cwd:e}:{cwd:e,startupToken:n})}),cleanupPreview:(e,t=`local`)=>D(`${P(t)}/sessions/cleanup/preview`,Ai,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>D(`${P(t)}/sessions/cleanup`,ji,{method:`POST`,body:JSON.stringify(e)}),archiveMany:(e,t=`local`,n)=>D(`${P(t)}/sessions/bulk/archive`,Mi,{method:`POST`,body:gs(e,n)}),deleteArchivedMany:(e,t=`local`,n)=>D(`${P(t)}/sessions/bulk/delete-archived`,Ni,{method:`POST`,body:gs(e,n)}),messages:(e,t,n=`local`)=>D(ns(e,t,n),Jn),status:(e,t=`local`)=>D(ps(e,`status`,t),qr),streamSnapshot:(e,t=`local`)=>D(is(e,t),Jr),transcriptSnapshot:(e,t,n=`local`)=>D(rs(e,t,n),Yr),models:(e,t=`local`)=>D(ps(e,`models`,t),Hi),modelCatalog:(e,t=`local`)=>D(ps(e,`models/catalog`,t),Wi),setModelEnabled:(e,t,n,r,i=`local`)=>D(F(e,`models/enabled`,i),Wi,{method:`POST`,body:I(e,{provider:t,modelId:n,enabled:r})}),setModelScope:(e,t,n=`local`)=>D(F(e,`models/scope`,n),Wi,{method:`POST`,body:I(e,{mode:t})}),setModel:(e,t,n,r=`local`)=>D(F(e,`model`,r),qr,{method:`POST`,body:I(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>D(F(e,`model/cycle`,n),qr,{method:`POST`,body:I(e,{direction:t})}),getSessionDefaults:(e,t=`local`)=>D(ps(e,`defaults`,t),nn),setSessionDefaults:(e,t,n=`local`)=>D(F(e,`defaults`,n),nn,{method:`POST`,body:I(e,{...t})}),thinkingLevels:(e,t=`local`)=>D(ps(e,`thinking-levels`,t),Ki),setThinkingLevel:(e,t,n=`local`)=>D(F(e,`thinking-level`,n),qr,{method:`POST`,body:I(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>D(F(e,`thinking-level/cycle`,t),qr,{method:`POST`,body:I(e)}),commands:(e,t=`local`)=>D(ps(e,`commands`,t),M(la)),prompt:(e,t,n,r=`local`,i)=>D(F(e,`prompt`,r),jo,{method:`POST`,body:I(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>D(F(e,`attachments`,n),Mo,{method:`POST`,body:I(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>D(F(e,`shell`,n),jo,{method:`POST`,body:I(e,{text:t})}),runCommand:(e,t,n=`local`)=>D(F(e,`commands/run`,n),yo,{method:`POST`,body:I(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>D(F(e,`commands/respond`,r),yo,{method:`POST`,body:I(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>D(F(e,`tree/navigate`,n),Co,{method:`POST`,body:I(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary,...t.retainCheckpoint===void 0?{}:{retainCheckpoint:t.retainCheckpoint}})}),forkTree:(e,t,n=`local`)=>zs(e,t,n),abort:(e,t=`local`)=>D(F(e,`abort`,t),Fo,{method:`POST`,body:I(e)}),stop:(e,t=`local`)=>D(F(e,`stop`,t),Io,{method:`POST`,body:I(e)}),archive:(e,t=`local`,n)=>D(F(e,`archive`,t),Lo,{method:`POST`,body:I(e,n===void 0?{}:{scopeProjectId:n})}),archiveWithDescendants:(e,t=`local`,n)=>D(F(e,`archive-tree`,t),Lo,{method:`POST`,body:I(e,n===void 0?{}:{scopeProjectId:n})}),restore:(e,t=`local`,n)=>D(F(e,`restore`,t),Ro,{method:`POST`,body:I(e,n===void 0?{}:{scopeProjectId:n})}),deleteArchived:(e,t=`local`,n)=>D(ms(e,t,n),zo,{method:`DELETE`}),detachParent:(e,t=`local`)=>D(F(e,`detach-parent`,t),Bo,{method:`POST`,body:I(e)}),reloadSession:(e,t=`local`)=>D(F(e,`reload`,t),Vo,{method:`POST`,body:I(e)}),clearQueue:(e,t=`local`)=>D(F(e,`queue/clear`,t),qr,{method:`POST`,body:I(e)}),mutateQueuedMessage:(e,t,n=`local`)=>D(F(e,`queue/message`,n),qr,{method:`POST`,body:I(e,{...t})}),dismissWarning:(e,t,n=`local`)=>D(F(e,`warnings/dismiss`,n),qr,{method:`POST`,body:I(e,{dismissId:t})}),submitAsk:(e,t,n,r=`local`)=>D(F(e,`ask/submit`,r),qr,{method:`POST`,body:I(e,{askId:t,answers:n.answers})}),cancelAsk:(e,t,n=`local`)=>D(F(e,`ask/cancel`,n),qr,{method:`POST`,body:I(e,{askId:t})}),answerDialog:(e,t,n,r=`local`)=>D(F(e,`dialogs/answer`,r),Fr,{method:`POST`,body:I(e,{dialogId:t,value:n})}),cancelDialog:(e,t,n=`local`)=>D(F(e,`dialogs/cancel`,n),Fr,{method:`POST`,body:I(e,{dialogId:t})}),authProviders:e=>{let t=new URLSearchParams;e.mode!==void 0&&t.set(`mode`,e.mode),e.authType!==void 0&&t.set(`authType`,e.authType),e.projectId!==void 0&&t.set(`projectId`,e.projectId);let n=t.toString();return D(`${P(e.machineId)}/auth/providers${n===``?``:`?${n}`}`,Zi)},saveApiKey:(e,t,n)=>D(_s(`api-key`,n),jo,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t)=>D(_s(`api-key/interactive`,t),$i,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t)=>D(_s(`logout`,t),jo,{method:`POST`,body:JSON.stringify({providerId:e})}),mcpAuthServers:(e,t=`local`)=>D(ps(e,`mcp/auth/servers`,t),Qi),startMcpAuth:(e,t,n=`local`,r)=>D(F(e,`mcp/auth`,n),$i,{method:`POST`,body:I(e,{mode:t,...r===void 0?{}:{serverName:r}})}),mcpAuthFlow:(e,t=`local`)=>D(`${P(t)}/auth/mcp/${encodeURIComponent(e)}`,$i),respondMcpAuthFlow:(e,t,n,r=`local`)=>D(`${P(r)}/auth/mcp/${encodeURIComponent(e)}/respond`,$i,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelMcpAuthFlow:(e,t=`local`)=>D(`${P(t)}/auth/mcp/${encodeURIComponent(e)}/cancel`,$i,{method:`POST`}),startOAuthLogin:(e,t)=>D(_s(`oauth`,t),$i,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t)=>D(_s(`oauth/${encodeURIComponent(e)}`,t),$i),respondOAuthFlow:(e,t,n,r)=>D(_s(`oauth/${encodeURIComponent(e)}/respond`,r),$i,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t)=>D(_s(`oauth/${encodeURIComponent(e)}/cancel`,t),$i,{method:`POST`})},Is={runTerminalCommand:(e,t,n=`local`)=>D(`${P(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,xa,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`,n)=>D(`${P(t)}/terminal-command-runs${Vs(e)}`,M(xa),n?.signal===void 0?void 0:{signal:n.signal}),getCommandRun:(e,t=`local`)=>Ls(e,t),cancelCommandRun:(e,t=`local`)=>D(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,xa,{method:`POST`})};async function Ls(e,t){return ln(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}`,xa)}var Rs=class extends Error{constructor(){super(n(`ui.main.8501d1e756a4`,`Fork from the session tree is unavailable. Restart the session daemon to enable it.`)),this.name=`SessionTreeForkUnavailableError`}};async function zs(e,t,n){let r=await fetch(cn(F(e,`tree/fork`,n)),{method:`POST`,headers:{"content-type":`application/json`},body:I(e,{entryId:t.entryId,expectedLeafId:t.expectedLeafId,...t.retainCheckpoint===void 0?{}:{retainCheckpoint:t.retainCheckpoint}})});if(!r.ok){let e=await r.json().catch(()=>({}));throw Bs(r.status,e)?new Rs:Error(Hs(e)??r.statusText)}return wo(await r.json())}function Bs(e,t){if(e!==404||!Ws(t)||t.statusCode!==404||t.error!==`Not Found`)return!1;let n=t.message;return typeof n==`string`&&/^Route POST:.*\/tree\/fork not found$/i.test(n)}function Vs(e){if(e===void 0)return``;let t=new URLSearchParams;e.projectId!==void 0&&t.set(`projectId`,e.projectId),e.workspaceId!==void 0&&t.set(`workspaceId`,e.workspaceId),e.terminalId!==void 0&&t.set(`terminalId`,e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set(`statuses`,e.statuses.join(`,`)),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set(`metadata`,JSON.stringify(e.metadata));let n=t.toString();return n===``?``:`?${n}`}function Hs(e){if(!Ws(e))return;let t=e.error;return typeof t==`string`?t:void 0}async function Us(e,t,n,r){let i=await fetch(us(e,t,n,{machineId:r}));if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(Hs(e)??i.statusText)}let a=await i.blob(),o=URL.createObjectURL(a),s=document.createElement(`a`);s.href=o;let c=n.split(`/`).pop();s.download=c===void 0||c===``?`download`:c,document.body.append(s),s.click(),s.remove(),URL.revokeObjectURL(o)}function Ws(e){return typeof e==`object`&&!!e}var Gs={files:(e,t,n={})=>{let r=typeof t==`string`,i=r?e:``,a=r?t:e,o=r?n:t,s=new URLSearchParams({q:a});if(o.kind!==void 0&&s.set(`kind`,o.kind),o.mode!==void 0&&s.set(`mode`,o.mode),o.scope!==void 0&&s.set(`scope`,o.scope),(!r||o.workspaceScoped===!0)&&o.projectId!==void 0&&o.workspaceId!==void 0)return D(`${P(o.machineId)}/projects/${encodeURIComponent(o.projectId)}/workspaces/${encodeURIComponent(o.workspaceId)}/files?${s.toString()}`,M(ua),{signal:o.signal??null});if(!r)throw Error(`File suggestions require a project and workspace`);return s.set(`cwd`,i),D(`${P(o.machineId)}/files?${s.toString()}`,M(ua),{signal:o.signal??null})}},Ks={...ys,...bs,...As,...Cs,...ws,...Ts,...Ds,...Os,...ks,...js,...ds,...Ps,...Fs,...Gs,...Is};function qs(e,t=`local`,n=fe()){let r=typeof e==`string`?`${Ys(t)}/sessions/${encodeURIComponent(e)}/events`:as(e,t),i=se(r,void 0,n);return new WebSocket(ne(i))}function Js(e=`local`,t=fe()){let n=se(`${Ys(e)}/events`,void 0,t);return new WebSocket(ne(n))}function Ys(e){return`api/machines/${encodeURIComponent(e)}`}var Xs=`.pi-web/uploads`,Zs=class extends Error{constructor(e=n(`client.workspaceUploads.workspace.upload.cancelled.ac6723`,`Workspace upload cancelled`)){super(e),this.name=`WorkspaceUploadCancelledError`}};function Qs(e){return e?.uploads?.defaultFolder??`.pi-web/uploads`}function $s(e,t){return e?.uploads?.defaultFolder??t}function ec(e,t){let r=ac(e,n(`client.workspaceUploads.upload.destination.874cbb`,`Upload destination`),{allowEmpty:!0}),i=ac(t,n(`client.workspaceUploads.upload.filename.9252dd`,`Upload filename`),{allowEmpty:!1});return r===``?i:`${r}/${i}`}function tc(e,t,r,i={}){let a=i.xhrFactory?.()??new XMLHttpRequest,o=!1,s=!1;return{promise:new Promise((c,l)=>{let u=e=>{o||(o=!0,l(e))},d=e=>{o||(o=!0,c(e))};a.open(`PUT`,ss(e,t,r.path,nc(i)),!0),a.responseType=`json`,a.setRequestHeader(`Content-Type`,(r.contentType??r.file.type)||`application/octet-stream`),a.upload.onprogress=e=>{i.onProgress?.(rc(e,r.file.size))},a.onload=()=>{if(a.status>=200&&a.status<300)try{i.onProgress?.({loaded:r.file.size,total:r.file.size,percent:1,lengthComputable:!0}),d(ga(sc(a)))}catch(e){u(e instanceof Error?e:Error(String(e)))}else u(Error(cc(a)))},a.onerror=()=>{u(Error(n(`client.workspaceUploads.workspace.upload.failed.a87e6b`,`Workspace upload failed`)))},a.onabort=()=>{u(new Zs(s?void 0:n(`client.workspaceUploads.workspace.upload.aborted.58a455`,`Workspace upload aborted`)))},a.send(r.file)}),cancel:()=>{o||(s=!0,a.abort())}}}function nc(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function rc(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:ic(e.loaded,n),lengthComputable:e.lengthComputable}}function ic(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function ac(e,t,r){let i=e.trim();if(i===``){if(r.allowEmpty)return``;throw Error(n(`client.workspaceUploads.must.not.be.empty.b22cd8`,`{value1} must not be empty`,{value1:t}))}if(oc(i))throw Error(n(`client.workspaceUploads.must.be.a.workspace.relative.path.79fcd6`,`{value1} must be a workspace-relative path`,{value1:t}));let a=i.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(a.length===0){if(r.allowEmpty)return``;throw Error(n(`client.workspaceUploads.must.not.be.empty.b22cd8`,`{value1} must not be empty`,{value1:t}))}if(a.some(e=>e===`..`))throw Error(n(`client.workspaceUploads.must.not.contain.path.traversal.dac533`,`{value1} must not contain path traversal`,{value1:t}));return a.join(`/`)}function oc(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function sc(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function cc(e){let t=lc(e);return uc(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function lc(e){try{return sc(e)}catch{return}}function uc(e){return typeof e==`object`&&!!e}var dc=`.pi-web/attachments`;function fc(e){return e?.attachments?.defaultFolder??`.pi-web/attachments`}function pc(e,t){return e?.attachments?.defaultFolder??t}function mc(e,t){return bc(e,t)}function hc(e,t,n){let r=mc(e,t);return n===void 0?cn(r):y(Ce(r),n)}function gc(e,t){let n=mc(e,t),r=n.lastIndexOf(`/`);return`${n.slice(0,r)}/channels${n.slice(r)}`}function _c(e,t,n){let r=se(gc(e,t),void 0,fe());return n===void 0?ne(r):ne(r,n)}function vc(e,t,n,r={}){return Sc(e,t,n,r,hc)}function yc(e,t,n,i,a=e=>new WebSocket(e)){if(i.signal?.aborted===!0)return Promise.reject(Dc(i.signal));let o=De(e.backendRevision,n,xc(e)),s=_c(e,t),c;try{c=a(s)}catch(e){return Promise.reject(Error(`Plugin backend channel unavailable: ${Oc(e)}`,{cause:e}))}let l=!1,u=!1,d=0,f,p=()=>void 0,m=new Promise(e=>{p=e}),h=Object.freeze({closed:m,send(e){if(!l||u||c.readyState!==1)throw Error(`Plugin backend channel is not open`);let t=r(e),n=ee(t);if(c.bufferedAmount===0&&(d=0),d>=128||c.bufferedAmount+n>1048576){let e=Error(`Plugin backend channel browser queue limit was exceeded`);throw f=Object.freeze({code:`queue-overflow`,message:e.message}),wc(c,`Channel queue overflow`),e}try{c.send(t),d+=1}catch(e){throw f=Object.freeze({code:`send-failed`,message:Oc(e)}),wc(c,`Channel send failed`),e}},close(e=`Channel closed`){wc(c,oe(e))}});return new Promise((e,t)=>{let n=setTimeout(()=>{let e=Error(`Plugin backend channel open timed out after ${String(Te)}ms`);f=Object.freeze({code:`open-timeout`,message:e.message}),t(e),wc(c,`Channel open timed out`)},Te),r=()=>{let e=i.signal;if(e===void 0)return;let n=Dc(e);l||t(n),f=Object.freeze({code:`cancelled`,message:n.message}),wc(c,`Channel cancelled`)};i.signal?.addEventListener(`abort`,r,{once:!0}),c.addEventListener(`open`,()=>{try{c.send(o)}catch(e){t(Error(`Plugin backend channel unavailable: ${Oc(e)}`,{cause:e})),wc(c,`Channel open failed`)}}),c.addEventListener(`message`,r=>{try{if(typeof r.data!=`string`)throw Error(`Plugin backend channels accept text JSON frames only`);let a=Ee(r.data);if(a.kind===`ready`){if(l)throw Error(`Plugin backend channel sent more than one ready envelope`);l=!0,clearTimeout(n),e(h);return}if(a.kind===`error`){f=Object.freeze({code:a.code,message:a.message}),l||t(Error(a.message)),wc(c,`Channel failed`);return}if(!l)throw Error(`Plugin backend channel sent data before ready`);i.onData(a.data)}catch(e){f=Object.freeze({code:`protocol-error`,message:Oc(e)}),l||t(e instanceof Error?e:Error(String(e))),wc(c,`Channel protocol error`)}}),c.addEventListener(`error`,()=>{f??=Object.freeze({code:`transport-error`,message:`Plugin backend channel transport failed`}),l||t(Error(`Plugin backend channel unavailable`)),wc(c,`Channel transport error`)}),c.addEventListener(`close`,e=>{if(u)return;u=!0,clearTimeout(n),i.signal?.removeEventListener(`abort`,r),l||t(Error(f?.message??`Plugin backend channel closed before ready (${String(e.code)})`));let a=f??(e.code===1e3?void 0:Object.freeze({code:`channel-closed`,message:e.reason||`Plugin backend channel closed with code ${String(e.code)}`}));p(Object.freeze({code:e.code,reason:e.reason,wasClean:e.wasClean,...a===void 0?{}:{error:a}}))})})}function bc(e,t){if(!i(e.pluginId))throw Error(`Invalid PI WEB plugin id: ${e.pluginId}`);if(e.machineId===``)throw Error(`Machine id is required`);if(e.projectId===``)throw Error(`Project id is required`);if(e.workspaceId===``)throw Error(`Workspace id is required`);if(e.workspaceId!==void 0&&e.projectId===void 0)throw Error(`Workspace scope requires a project id`);ke(e,xc(e));let n=Oe(t);return`${e.machineId===`local`?`api`:`api/machines/${encodeURIComponent(e.machineId)}`}${ue({...e,operation:n})}`}function xc(e){return e.scope===void 0?{}:{scope:e.scope,...e.projectId===void 0?{}:{projectId:e.projectId},...e.workspaceId===void 0?{}:{workspaceId:e.workspaceId}}}async function Sc(e,t,n,r,i){let a=v(e.backendRevision),o=de(n,`Plugin backend request input`),s=JSON.stringify({revision:a,input:o,...xc(e)});if(ee(s)>266240)throw Error(`Plugin backend request exceeds the ${String(le)} byte wire limit`);let c;try{c=await fetch(i(e,t),{method:`POST`,headers:{"content-type":`application/json`},body:s,...r.signal===void 0?{}:{signal:r.signal}})}catch(e){throw r.signal?.aborted===!0?Dc(r.signal):Error(`Plugin backend request unavailable: ${Oc(e)}`,{cause:e})}let l=await Cc(c);if(!c.ok)throw Error(Ec(l)??`Plugin backend request returned HTTP ${String(c.status)}`);return ie(l,`Plugin backend response`,ge)}async function Cc(e){let t=e.headers.get(`content-length`);if(t!==null&&/^\d+$/u.test(t)&&Number(t)>8392704)throw await e.body?.cancel(),Error(`Plugin backend response exceeds the ${String(be)} byte wire limit`);if(e.body===null){let t=await e.text();if(ee(t)>8392704)throw Tc();return t}let n=e.body.getReader(),r=new TextDecoder,i=0,a=``;try{let e=await n.read();for(;!e.done;){if(i+=e.value.byteLength,i>8392704)throw await n.cancel(),Tc();a+=r.decode(e.value,{stream:!0}),e=await n.read()}return a+r.decode()}finally{n.releaseLock()}}function wc(e,t){if(e.readyState===0||e.readyState===1)try{e.close(1e3,oe(t))}catch{e.close()}}function Tc(){return Error(`Plugin backend response exceeds the ${String(be)} byte wire limit`)}function Ec(e){try{let t=JSON.parse(e);return kc(t)&&typeof t.error==`string`?t.error:void 0}catch{return}}function Dc(e){let t=e.reason;return t instanceof Error?t:new DOMException(`Plugin backend request cancelled`,`AbortError`)}function Oc(e){return e instanceof Error?e.message:String(e)}function kc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ac(){return{sessions:[],pinnedSessionIds:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,clientQueuedSessionMessages:{},startingSessionCount:0,selectedNotificationInbox:void 0,treeDialog:void 0,error:``}}function jc(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},machineStatusSnapshots:{},projects:[],workspaces:[],sessions:[],pinnedSessionIds:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,pendingTreeActions:[],treeDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:void 0,mainView:`chat`,piWebStatus:void 0,browserErrors:{},error:``}}function Mc(e){return{kind:`machine`,machineId:e}}function Nc(e,t){return{kind:`project`,machineId:e,projectId:t}}function Pc(e,t,n){return{kind:`workspace`,machineId:e,projectId:t,workspaceId:n}}function Fc(e,t,n={}){return{kind:`session`,machineId:e,sessionId:t,...n.cwd===void 0?{}:{cwd:n.cwd},...n.projectId===void 0?{}:{projectId:n.projectId},...n.workspaceId===void 0?{}:{workspaceId:n.workspaceId}}}function Ic(e){switch(e.kind){case`global`:return`global`;case`machine`:return JSON.stringify([e.kind,e.machineId]);case`project`:return JSON.stringify([e.kind,e.machineId,e.projectId]);case`workspace`:return JSON.stringify([e.kind,e.machineId,e.projectId,e.workspaceId]);case`session`:return JSON.stringify([e.kind,e.machineId,e.sessionId,e.cwd,e.projectId,e.workspaceId])}}function Lc(e,t,n,r){return{...e,[Ic(t)]:{scope:t,message:n,...r===void 0?{}:{recovery:r}}}}function Rc(e,t,n){let r=Ic(t),i=e[r];return i===void 0||n!==void 0&&i.message!==n?e:Object.fromEntries(Object.entries(e).filter(([e])=>e!==r))}function zc(e,t){let n=Object.fromEntries(Object.entries(e).filter(([,e])=>!Gc(e.scope,t)));return Object.keys(n).length===Object.keys(e).length?e:n}function Bc(e){let t=e.selectedSession;return{machineId:e.selectedMachine?.id??`local`,...e.selectedProject===void 0?{}:{projectId:e.selectedProject.id},...e.selectedWorkspace===void 0?{}:{workspaceId:e.selectedWorkspace.id},...t===void 0?{}:{sessionId:t.id,cwd:t.cwd}}}function Vc(e,t){return Object.values(e).filter(e=>Uc(e.scope,t)).sort((e,t)=>Wc(e.scope)-Wc(t.scope)||Ic(e.scope).localeCompare(Ic(t.scope)))}var Hc=class{constructor(e,t){this.getState=e,this.setState=t}report(e,t,n){this.setState({browserErrors:Lc(this.getState().browserErrors,e,t,n)})}captureRecovery(e,t){let n=this.getState().browserErrors[Ic(e)];return n?.recovery===t?n:void 0}clearRecovered(e){e?.recovery!==void 0&&this.getState().browserErrors[Ic(e.scope)]===e&&this.clear(e.scope)}clear(e,t){let n=this.getState().browserErrors,r=Rc(n,e,t);r!==n&&this.setState({browserErrors:r})}discard(e){let t=zc(this.getState().browserErrors,e);t!==this.getState().browserErrors&&this.setState({browserErrors:t})}};function Uc(e,t){return e.kind===`global`?!0:e.machineId===t.machineId?e.kind===`machine`?!0:e.kind===`project`?e.projectId===t.projectId:e.kind===`workspace`?e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.sessionId===t.sessionId&&(e.cwd===void 0||e.cwd===t.cwd)&&(e.projectId===void 0||e.projectId===t.projectId)&&(e.workspaceId===void 0||e.workspaceId===t.workspaceId):!1}function Wc(e){switch(e.kind){case`global`:return 0;case`machine`:return 1;case`project`:return 2;case`workspace`:return 3;case`session`:return 4}}function Gc(e,t){return t.kind===`global`?!0:e.kind===`global`||e.machineId!==t.machineId?!1:t.kind===`machine`?!0:t.kind===`project`?e.kind!==`machine`&&e.projectId===t.projectId:t.kind===`workspace`?e.kind===`workspace`?e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.kind===`session`&&e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.kind===`session`&&e.sessionId===t.sessionId&&(t.cwd===void 0||e.cwd===t.cwd)}function Kc(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}var qc=`workspace.delete`,Jc=`pi.operation`,Yc=`target.workspaceId`;function Xc(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function Zc(e,t){return t[e.path]}function Qc(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function $c(e,t,n){return nl(rl(e,t,n))}function el(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function tl(e){return nl(Object.values(e??{}))}function nl(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function rl(e,t,n){return Object.values(n).filter(n=>el(e,t,n.cwd))}function il(e,t){return`${e}:${t}`}function L(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var al=class{constructor(e=0){if(this.debounceMs=e,this.pendingByKey=new Map,!Number.isInteger(e)||e<0)throw Error(`debounceMs must be a non-negative integer`)}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.phase===`running`?n.trailing=!0:this.rescheduleDebounce(n),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,phase:`debouncing`,trailing:!1,debounceTimer:void 0,finishDebounce:void 0};return r.promise=Promise.resolve().then(async()=>{let t,n;do{r.trailing=!1,r.phase=`debouncing`,this.debounceMs>0&&await this.waitForDebounce(r),r.phase=`running`;let e=r.latestRefresh;n=!1;try{await e()}catch(e){t=e,n=!0}}while(this.hasTrailingRequest(r));if(this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e),n)throw t}).finally(()=>{this.cancelDebounce(r),this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}waitForDebounce(e){return new Promise(t=>{e.finishDebounce=t,this.rescheduleDebounce(e)})}rescheduleDebounce(e){e.finishDebounce!==void 0&&(e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=globalThis.setTimeout(()=>{let t=e.finishDebounce;e.debounceTimer=void 0,e.finishDebounce=void 0,e.phase=`running`,t?.()},this.debounceMs))}cancelDebounce(e){e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=void 0,e.finishDebounce=void 0}},ol=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new al,this.api=n.api??Os,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,sl(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=R(this.getState())){let n=this.getState(),r=R(n)===t,i=cl(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...R(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function sl(e){let t={};for(let n of e.workspaces)Xc(n)&&(t[n.cwd]=n);return t}function cl(e,t){let n={...e};return Xc(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var ll=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??Ks,this.pollIntervalMs=r.pollIntervalMs??1e3,this.scope=r.scope,this.browserErrors=new Hc(e,t)}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=pl(e);return t!==void 0&&(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){this.advanceAuthOperation();let t=this.captureTarget();t!==void 0&&(e!==void 0&&e!==``?await this.openLoginProvider(e,t):this.setState({authDialog:{step:`method`,target:t}}))}async openMcpAuth(e,t,r){let i=this.getState(),a=r?.session??(i.selectedSession?.archived===!0?void 0:i.selectedSession),o=r?.machineId??R(i);if(a===void 0){this.browserErrors.report(Mc(o),n(`ui.mcp.selectSession`,`Select a session to authenticate MCP servers.`));return}let s=this.advanceAuthOperation(),c={machineId:o},l={id:a.id,cwd:a.cwd};this.setState({authDialog:{step:`starting`,target:c,mcpSession:l,title:e===`login`?n(`ui.mcp.signInTitle`,`Sign in to an MCP server`):n(`ui.mcp.signOutTitle`,`Sign out of an MCP server`)}}),await this.startFlow(()=>t===void 0?this.api.startMcpAuth(l,e,o):this.api.startMcpAuth(l,e,o,t),c,s,l)}async chooseLoginMethod(e){let t=this.getState().authDialog;if(t?.step!==`method`)return;let n=this.oauthOperationGeneration;try{let{providers:r}=await this.api.authProviders({mode:`login`,authType:e,...dl(t.target)});if(n!==this.oauthOperationGeneration||this.getState().authDialog!==t)return;this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:r,target:t.target}})}catch(e){if(n!==this.oauthOperationGeneration||this.getState().authDialog!==t)return;this.browserErrors.report(Mc(t.target.machineId),String(e))}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startOAuth(r,n.target):this.setState({authDialog:{step:`apiKey`,provider:r,value:``,target:n.target}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:n(`ui.shared.daf147632ea6`,`API key is required`)}});return}let r={...e};delete r.error,this.setState({authDialog:{...r,saving:!0}});let i=this.oauthOperationGeneration;try{let n=e.target;if(await this.api.saveApiKey(e.provider.id,t,n),i!==this.oauthOperationGeneration)return;this.closeDialog(),this.refreshStatus(n)}catch(t){if(i!==this.oauthOperationGeneration)return;this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){let t=this.advanceAuthOperation(),r=this.captureTarget();if(r!==void 0)try{let{providers:i}=await this.api.authProviders({mode:`logout`,...dl(r)});if(t!==this.oauthOperationGeneration)return;if(e!==void 0&&e!==``){let t=i.find(t=>t.id===e);t===void 0?this.browserErrors.report(Mc(r.machineId),n(`client.authController.no.saved.credentials.for.cc5494`,`No saved credentials for {value1}`,{value1:e})):await this.logoutProviderForTarget(t.id,r);return}this.setState({authDialog:{step:`logout`,providers:i,target:r}})}catch(e){if(t!==this.oauthOperationGeneration)return;this.browserErrors.report(Mc(r.machineId),String(e))}}async logoutProvider(e){let t=this.getState().authDialog;t?.step===`logout`&&t.providers.find(t=>t.id===e)!==void 0&&await this.logoutProviderForTarget(e,t.target)}async logoutProviderForTarget(e,t){let n=this.advanceAuthOperation();try{if(await this.api.logoutProvider(e,t),n!==this.oauthOperationGeneration)return;this.closeDialog(),this.refreshStatus(t)}catch(e){if(n!==this.oauthOperationGeneration)return;this.browserErrors.report(Mc(t.machineId),String(e))}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId;if(this.inFlightResponse?.generation===r&&this.inFlightResponse.flowId===i&&this.inFlightResponse.requestId===a)return;let o={generation:r,flowId:i,requestId:a};this.inFlightResponse=o;let s=e??t.inputValue??``,c={...t};delete c.error,this.setState({authDialog:{...c,responding:!0}});try{let e=t.flow.target===`mcp`?await this.api.respondMcpAuthFlow(i,a,s,t.target.machineId):await this.api.respondOAuthFlow(i,a,s,t.target),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||!ul(n.target,t.target)||fl(n.flow)!==a)return;this.updateOAuthFlow(e,t.target)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||fl(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}finally{this.inFlightResponse===o&&(this.inFlightResponse=void 0)}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.target;if(e.flow.target===`mcp`){if(e.flow.status!==`running`){this.closeDialog();return}if(e.flow.cancelRequested===!0)return;let r=this.advanceAuthOperation();this.setState({authDialog:{...e,flow:{...e.flow,cancelRequested:!0}}});try{let e=await this.api.cancelMcpAuthFlow(t,n.machineId);this.currentOAuthDialog(r,t)!==void 0&&(this.updateOAuthFlow(e,n),e.status===`running`&&this.startPolling(t,n))}catch(e){let i=this.currentOAuthDialog(r,t);i!==void 0&&(this.setState({authDialog:{...i,flow:{...i.flow,cancelRequested:!1},error:String(e)}}),this.startPolling(t,n))}}else{this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}}closeDialog(){this.advanceAuthOperation(),this.setState({authDialog:void 0})}async openLoginProvider(e,t){let r=this.oauthOperationGeneration;try{let{providers:i}=await this.api.authProviders({mode:`login`,...dl(t)});if(r!==this.oauthOperationGeneration)return;let a=i.filter(t=>t.id===e);if(a.length===0){this.browserErrors.report(Mc(t.machineId),n(`client.authController.authentication.provider.not.found.a59b6e`,`Authentication provider not found: {value1}`,{value1:e}));return}if(a.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:a,target:t}});return}let o=a[0];if(o===void 0)return;o.authType===`oauth`||o.loginFlow===`interactive`?await this.startOAuth(o,t):this.setState({authDialog:{step:`apiKey`,provider:o,value:``,target:t}})}catch(e){if(r!==this.oauthOperationGeneration)return;this.browserErrors.report(Mc(t.machineId),String(e))}}async startOAuth(e,t){let n=this.advanceAuthOperation();await this.startFlow(()=>e.authType===`oauth`?this.api.startOAuthLogin(e.id,t):this.api.startInteractiveApiKeyLogin(e.id,t),t,n)}async startFlow(e,t,n,r){if(n===this.oauthOperationGeneration)try{let i=await e();if(n!==this.oauthOperationGeneration){if(i.status===`running`)try{i.target===`mcp`?await this.api.cancelMcpAuthFlow(i.flowId,t.machineId):await this.api.cancelOAuthFlow(i.flowId,t)}catch{}return}this.updateOAuthFlow(i,t,r),i.status===`running`&&this.startPolling(i.flowId,t)}catch(e){if(n!==this.oauthOperationGeneration)return;let r=this.getState().authDialog;r?.step===`starting`?this.setState({authDialog:{...r,error:String(e)}}):this.browserErrors.report(Mc(t.machineId),String(e))}}updateOAuthFlow(e,t,n){let r=this.getState().authDialog;if(n??=e.target===`mcp`&&(r?.step===`oauth`||r?.step===`starting`)?r.mcpSession:void 0,e.status===`complete`&&e.target!==`mcp`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}e.status!==`running`&&(this.oauthOperationGeneration+=1,this.stopPolling(),e.target===`mcp`&&n!==void 0&&this.refreshMcpStatus(t.machineId,n));let i=r?.step===`oauth`&&r.flow.flowId===e.flowId?r.inputValue??``:``,a=r?.step===`oauth`?fl(r.flow):void 0,o=fl(e),s=a!==void 0&&a===o,c=s?i:``,l=s&&r?.step===`oauth`?r.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,inputValue:c,responding:l,target:t,...n===void 0?{}:{mcpSession:n}}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i===void 0||!ul(i.target,t)){this.stopPolling();return}let a=fl(i.flow);try{let o=i.flow.target===`mcp`?await this.api.mcpAuthFlow(e,i.target.machineId):await this.api.oauthFlow(e,i.target),s=this.currentOAuthDialog(n,e);if(o.flowId!==e||r!==this.pollGeneration||s===void 0||!ul(s.target,t)||fl(s.flow)!==a)return;this.updateOAuthFlow(o,i.target)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o===void 0||!ul(o.target,t)||fl(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}advanceAuthOperation(){return this.oauthOperationGeneration+=1,this.stopPolling(),this.oauthOperationGeneration}async refreshStatus(e){let t=this.selectedSessionForMachine(e.machineId);if(t!==void 0&&this.targetStillSelected(e))try{let n=await this.api.status(t,e.machineId),r=this.selectedSessionForMachine(e.machineId);if(!this.targetStillSelected(e)||r?.id!==t.id||r.cwd!==t.cwd)return;this.applyStatus(n)}catch{}}async refreshMcpStatus(e,t){let n=()=>{let n=this.selectedSessionForMachine(e);return n?.id===t.id&&n.cwd===t.cwd};if(n())try{let r=await this.api.status(t,e);n()&&this.applyStatus(r)}catch{}}selectedSessionForMachine(e){let t=this.getState();if(R(t)!==e)return;let n=t.selectedSession;if(n!==void 0&&n.archived!==!0)return n}captureTarget(){let e=this.getState(),t=e.selectedMachine,r={machineId:R(e),...t?.kind===void 0?{}:{machineKind:t.kind}};if(this.scope===`management`)return r;let i=e.selectedProject;if(i===void 0)this.browserErrors.report(Mc(r.machineId),n(`client.authController.select.a.project.before.configuring.provider.authentication.a2a76e`,`Select a project before configuring provider authentication.`));else return{...r,projectId:i.id,projectName:i.name}}targetStillSelected(e){return R(this.getState())===e.machineId?e.projectId===void 0||this.getState().selectedProject?.id===e.projectId:!1}};function ul(e,t){return e.machineId===t.machineId&&e.projectId===t.projectId}function dl(e){return e.projectId===void 0?{machineId:e.machineId}:{machineId:e.machineId,projectId:e.projectId,...e.projectName===void 0?{}:{projectName:e.projectName}}}function fl(e){return e.prompt?.requestId??e.select?.requestId}function pl(e){let t=e.trim(),n=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(n===null)return;let r=n[1];if(r!==`login`&&r!==`logout`)return;let i=n[2];return i===void 0||i===``?{command:r}:{command:r,providerId:i}}var ml=class{constructor(e,t,n,r,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.projects=r,this.runtimeRefreshSeqByMachine=new Map,this.navigateToMachine=i.navigateToMachine,this.captureNavigation=i.captureNavigation,this.browserErrors=new Hc(e,t)}async loadMachines(e){this.setState({error:``,isLoadingMachines:!0});try{let t=await Ks.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));for(let e of Object.values(this.getState().browserErrors))e.scope.kind!==`global`&&!r.has(e.scope.machineId)&&this.browserErrors.discard(Mc(e.scope.machineId));return this.setState({machines:t,selectedMachine:n,machineActivities:gl(this.getState().machineActivities,r),machineRuntimes:gl(this.getState().machineRuntimes,r),machineStatusSnapshots:gl(this.getState().machineStatusSnapshots,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t),!0}catch(t){return this.setState({error:String(t)}),this.browserErrors.report(Mc(e??`local`),String(t)),!1}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,workspaceResolution:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},...Ac()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){let t=_l(this.getState(),this.captureNavigation);this.setState({error:``});try{let n=await Ks.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==n.id),n]}),this.navigateToMachine===void 0?await this.selectMachine(n):await this.navigateToMachine(n,{expected:t}),n}catch(e){this.setState({error:String(e)});return}}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`)this.browserErrors.report(Mc(e.id),n(`client.machineController.cannot.remove.the.local.machine.9e88e1`,`Cannot remove the local machine.`));else try{await Ks.deleteMachine(e.id);let n=this.getState().machines.filter(t=>t.id!==e.id),r=n.find(e=>e.id===`local`)??n[0];if(this.browserErrors.discard(Mc(e.id)),this.setState({machines:n,machineStatuses:hl(this.getState().machineStatuses,e.id),machineRuntimes:hl(this.getState().machineRuntimes,e.id),machineActivities:hl(this.getState().machineActivities,e.id),machineStatusSnapshots:hl(this.getState().machineStatusSnapshots,e.id)}),this.getState().selectedMachine?.id===e.id&&r!==void 0){if(t.selectFallback===!1)return r;let e=_l(this.getState(),this.captureNavigation);return this.navigateToMachine===void 0?await this.selectMachine(r):await this.navigateToMachine(r,{expected:e}),r}return}catch(t){this.browserErrors.report(Mc(e.id),String(t));return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await Ks.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(t){this.browserErrors.report(Mc(e),String(t));return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await Ks.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.browserErrors.report(Mc(e),String(n));return}}async selectInitialMachine(e,t){let r=e.find(e=>e.id===(t??`local`));if(r===void 0)return this.localMachine(e);if(r.kind!==`remote`)return r;let i=await this.safeRemoteHealth(r);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i.ok||this.browserErrors.report(Mc(r.id),n(`ui.piWebApp.isUnavailableReconnecting`,`{machineName} is unavailable. Reconnecting…`,{machineName:r.name})),r}async safeRemoteHealth(e){try{return await Ks.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>Ks.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>Ks.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function hl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function gl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}function _l(e,t){return t?.()??{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}var vl=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new al,this.api=n.api??ks}refresh(e){return this.refreshes.request(e,async()=>{let t=this.getState().machineStatusSnapshots[e],n=await this.api.machineStatus(e),r=this.getState().machineStatusSnapshots[e];(r===t||r===void 0||r.epochId===n.epochId)&&this.apply(e,n)})}apply(e,t){let n=this.getState().machineStatusSnapshots;yl(n[e],t)&&this.setState({machineStatusSnapshots:{...n,[e]:t}})}};function yl(e,t){return e===void 0||e.epochId!==t.epochId||t.revision>e.revision}function bl(e){switch(e.kind){case`projects`:return JSON.stringify([e.kind,e.machineId]);case`workspaces`:return JSON.stringify([e.kind,e.machineId,e.projectId]);case`sessionPins`:return JSON.stringify([e.kind,e.machineId,e.projectId,e.workspaceId])}}var xl=class{constructor(e,t={}){this.port=e,this.options=t,this.states=new Map}ids(e){return[...this.state(e).snapshot?.ids??[]]}pending(e){return this.state(e).pending>0}ensure(e){let t=this.state(e);if(t.ensuring)return t.ensuring;if(t.snapshot)return Promise.resolve();let n=this.load(e);return t.ensuring=n,n.finally(()=>{t.ensuring=void 0}).catch(()=>void 0),n}load(e){return e={...e},this.enqueue(e,async t=>{t.snapshot=await this.port.load(e)})}mutate(e,t){return e={...e},this.enqueue(e,async n=>{n.snapshot??=await this.port.load(e);let r=n.snapshot,i=[...t([...r.ids])];if(!(i.length===r.ids.length&&i.every((e,t)=>e===r.ids[t])))try{n.snapshot=await this.port.save(e,i,r.revision)}catch(t){n.snapshot=void 0;try{n.snapshot=await this.port.load(e)}catch(t){this.options.onError?.(e,t)}throw t}})}state(e){let t=bl(e),n=this.states.get(t);return n||(n={snapshot:void 0,tail:Promise.resolve(),ensuring:void 0,pending:0},this.states.set(t,n)),n}enqueue(e,t){e={...e};let n=this.state(e);n.pending++,this.options.onChange?.(e);let r=n.tail.then(async()=>{try{await t(n)}catch(t){throw this.options.onError?.(e,t),t}finally{n.pending--,this.options.onChange?.(e)}});return n.tail=r.catch(()=>void 0),r}};function Sl(e){let t=`api/machines/${encodeURIComponent(e.machineId)}/navigation/projects`;switch(e.kind){case`projects`:return t;case`workspaces`:return`${t}/${encodeURIComponent(e.projectId)}/workspaces`;case`sessionPins`:return`${t}/${encodeURIComponent(e.projectId)}/workspaces/${encodeURIComponent(e.workspaceId)}/session-pins`}}function Cl(e){if(!wl(e))throw Error(`Invalid navigation order response`);let t=e.ids,n=e.revision;if(!Array.isArray(t)||!t.every(e=>typeof e==`string`&&e.trim()!==``)||new Set(t).size!==t.length||typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Invalid navigation order response: ids and revision are required`);return{ids:[...t],revision:n}}function wl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Tl={load:e=>D(Sl(e),Cl,{cache:`no-store`}),save:(e,t,n)=>{let r={ids:[...t],revision:n};return D(Sl(e),Cl,{method:`PUT`,body:JSON.stringify(r)})}};function El(e,t){let n=new Map;for(let e of t)n.has(e)||n.set(e,n.size);return[...e].sort((e,t)=>(n.get(e.id)??1/0)-(n.get(t.id)??1/0))}function Dl(e,t,n,r,i){let a=[...new Set([...e,...t])];if(n===r||!t.includes(n)||!t.includes(r))return a;let o=a.filter(e=>e!==n),s=o.indexOf(r);return o.splice(s+ +(i===`after`),0,n),o}var Ol=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.loadErrors=new Map,this.api=r.api??Ks,this.onProjectsApplied=r.onProjectsApplied,this.navigateToProject=r.navigateToProject,this.captureNavigation=r.captureNavigation,this.browserErrors=new Hc(e,t)}managementEntryProject(e){let t=this.getState();if(!(e.machineId!==`local`||R(t)!==`local`||e.projectId!==void 0||e.workspaceId!==void 0||e.sessionId!==void 0||t.isLoadingProjects||this.loadErrors.has(`local`)||t.projects.length!==1))return t.projects[0]}async loadProjects(){let e=R(this.getState());this.loadErrors.delete(e),this.setState({isLoadingProjects:!0});try{let t=await this.api.projects(e);if(R(this.getState())!==e)return;let n=new Set(t.map(e=>e.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>n.has(e)));this.setState({projects:t,workspacesByProjectId:r}),this.onProjectsApplied?.(e)}catch(t){this.loadErrors.set(e,String(t)),this.browserErrors.report(Mc(e),String(t))}finally{R(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t,n){if(e.trim()===``)return;let r=R(this.getState()),i=kl(this.getState(),this.captureNavigation),a;try{a=await this.api.addProject(e.trim(),void 0,t,r)}catch(e){this.browserErrors.report(Mc(r),String(e));return}try{if(R(this.getState())===r){let e=this.getState().projects;this.setState({projects:[...e.filter(e=>e.id!==a.id),a],projectDialogOpen:!1}),this.onProjectsApplied?.(r)}if(n?.changed===!0&&await this.applyTrustChoice(a,n.trusted,r),R(this.getState())!==r)return;this.navigateToProject===void 0?await this.workspaces.selectProject(a):await this.navigateToProject(a,{expected:i})}catch(e){this.browserErrors.report(Nc(r,a.id),String(e))}}async applyTrustChoice(e,t,r){let i=(await(this.api.workspaces??Ks.workspaces)(e.id,r)).find(t=>t.projectId===e.id&&t.isMain);if(i===void 0)throw Error(n(`ui.main.7800af593e97`,`Could not save trust choice for project {arg0}: the primary workspace is unavailable`,{arg0:e.id}));await(this.api.setWorkspaceTrust??Ks.setWorkspaceTrust)(e.id,i.id,t,r)}async closeProject(e){let t=R(this.getState());try{if(await this.api.closeProject(e,t),R(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();if(this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id!==e)return;let r=kl(this.getState(),this.captureNavigation);this.navigateToProject===void 0?this.workspaces.clearSelection():await this.navigateToProject(void 0,{expected:r})}catch(n){this.browserErrors.report(Nc(t,e),String(n))}}};function kl(e,t){return t?.()??{machineId:R(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}var Al=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??Ps,this.onError=n.onError}handleActivityApplied(e){return R(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return R(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(R(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!jl(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=await this.api.workspaces(t.id,e.machineId);this.applyProjectWorkspaces(e,t,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!jl(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(R(this.getState()))}applyProjectWorkspaces(e,t,n){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let r=this.getState();r.projects.find(e=>e.id===t.id)?.path===t.path&&r.workspacesByProjectId[t.id]===t.startingWorkspaces&&this.setState({workspacesByProjectId:{...r.workspacesByProjectId,[t.id]:n}})}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&R(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(Xc).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function jl(e,t,n){return e.some(e=>el(e,t[e.id]??[],n))}var Ml=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??ys,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=R(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebStatus(e);this.isCurrent(e,t)&&this.setState({piWebStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=R(this.getState()),t=this.pendingUpdateCheck;if(t?.machineId===e)return t.promise;let n=++this.requestSequence,r=this.api.checkForUpdates(e).then(t=>{this.isCurrent(e,n)&&(this.setState({piWebStatus:t}),Nl(t))}).catch(t=>{if(this.isCurrent(e,n))throw t}).finally(()=>{this.pendingUpdateCheck?.requestSequence===n&&(this.pendingUpdateCheck=void 0)});return this.pendingUpdateCheck={machineId:e,requestSequence:n,promise:r},r}isCurrent(e,t){return R(this.getState())===e&&t===this.requestSequence}};function Nl(e){if(e.release.error!==void 0)throw Error(n(`client.piWebStatusController.pi.web.update.check.failed.495ae6`,`PI WEB update check failed: {value1}`,{value1:e.release.error}));if(e.release.skipped===!0)throw Error(n(`client.piWebStatusController.pi.web.update.check.skipped.because.remote.checks.are.disabled.by.offl.e9da2f`,`PI WEB update check skipped because remote checks are disabled by offline or version-check settings`))}function Pl(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}var Fl=`pi-web:cached-new-sessions:v1`,Il=`browserCachedNew`,Ll=`local`;function Rl(e,t=Ll,n=Pl()){if(e.messageCount!==0||e.archived===!0)return;let r=Wl(n).filter(n=>n.id!==e.id||n.machineId!==t);Gl([zl(e,t),...r],n)}function zl(e,t=Ll){return{...e,browserCachedNew:!0,machineId:t}}function Bl(e,t=Ll,n=Pl()){Gl(Wl(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Vl(e,t,n=Ll,r=Pl()){let i=new Set(t.map(e=>e.id)),a=Wl(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&Gl(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Hl(e){return e!==void 0&&ql(e)&&e.browserCachedNew===!0}function Ul(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},...e.agentSubsession===!0?{agentSubsession:!0}:{},...`machineId`in e&&typeof e.machineId==`string`?{machineId:e.machineId}:{machineId:Ll},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Wl(e=Pl()){try{let t=e?.getItem(Fl);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Kl(e)):[]}catch{return[]}}function Gl(e,t=Pl()){try{e.length===0?t?.removeItem(Fl):t?.setItem(Fl,JSON.stringify(e))}catch{}}function Kl(e){if(!Jl(e))return[];let t=Yl(e,`id`),n=Yl(e,`path`),r=Yl(e,`cwd`),i=Yl(e,`created`),a=Yl(e,`modified`),o=Yl(e,`firstMessage`),s=Zl(e,`messageCount`);if(t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s!==0)return[];let c=Xl(e,`name`),l=Xl(e,`parentSessionPath`),u=Xl(e,`machineId`)??Ll;return[{id:t,path:n,cwd:r,...c===void 0?{}:{name:c},created:i,modified:a,messageCount:s,firstMessage:o,...l===void 0?{}:{parentSessionPath:l},...e.agentSubsession===!0?{agentSubsession:!0}:{},machineId:u,browserCachedNew:!0}]}function ql(e){return Il in e}function Jl(e){return typeof e==`object`&&!!e}function Yl(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Xl(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function Zl(e,t){let n=e[t];return typeof n==`number`?n:void 0}function Ql(e,t){let n=[];return e.forEach((e,r)=>{let i=ru(e);i.every(e=>e.parts.length===0)&&z(e,`role`)!==void 0&&n.at(-1)?.parts.at(-1)?.type===`askUserQuestion`&&(i=[{...i[0]??eu({role:pu(z(e,`role`)),parts:[]},e),parts:[{type:`empty`}]}]),n.push(...i.map(e=>t===void 0?e:{...e,transcriptIndex:t+r}))}),Su(n).filter(e=>e.parts.length>0)}function $l(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function eu(e,t){let n=lu(t),r=z(t,`entryId`),i=z(t,`streamId`);return n===void 0&&r===void 0&&i===void 0?e:{...e,...i===void 0?{}:{streamId:i},...n===void 0?{}:{meta:n},...r===void 0||r===``?{}:{entryId:r}}}function tu(e,t,n){if(n===``)return e;let r=e.at(-1),i=r?.parts.at(-1);return r?.role===t&&i?.type===`text`?[...e.slice(0,-1),{...r,parts:[...r.parts.slice(0,-1),{type:`text`,text:i.text+n}]}]:r?.role===t?[...e.slice(0,-1),{...r,parts:[...r.parts,{type:`text`,text:n}]}]:[...e,$l(t,n)]}function nu(e,t){if(t===``)return e;let n=e.at(-1),r=n?.parts.at(-1);return n?.role===`assistant`&&r?.type===`thinking`?[...e.slice(0,-1),{...n,parts:[...n.parts.slice(0,-1),{type:`thinking`,text:r.text+t}]}]:n?.role===`assistant`?[...e.slice(0,-1),{...n,parts:[...n.parts,{type:`thinking`,text:t}]}]:[...e,{role:`assistant`,parts:[{type:`thinking`,text:t}]}]}function ru(e){if(au(e))return e.parts.some(e=>z(e,`type`)===`image`)?[{...e,parts:e.parts.flatMap(e=>z(e,`type`)===`image`?hu(e):[e])}]:[e];if(z(e,`role`)===`bashExecution`)return[eu(fu(e),e)];let t=z(e,`role`),n=pu(t),r=mu(Au(e,`content`),e),i=t===`toolResult`?vu(z(e,`toolName`)??``,Au(e,`details`)):void 0,a=t===`toolResult`?_u(z(e,`toolName`)??``,Au(e,`details`),ju(e,`isError`)===!0):void 0,o=[...t===`toolResult`&&!r.some(e=>e.type===`toolResult`)?[bu(r.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
8
8
  `),e),...r.filter(e=>e.type===`image`)]:r,...i===void 0?[]:[i],...a===void 0?[]:[a]],s=n===`user`?ou(o):void 0;if(s!==void 0)return s.map(t=>eu(t,e));let c=cu(e);if(n===`tool`)return[eu({role:n,parts:o,...c===void 0?{}:{source:c}},e)];let l=o.filter(e=>e.type!==`empty`),u=n===`assistant`&&l.length>0&&l.every(e=>e.type===`skillRead`)?`skill`:n,d=l.length>0?[eu({role:u,parts:l,...c===void 0?{}:{source:c}},e)]:[],f=iu(e);return f===void 0?d:[...d,eu(f,e)]}function iu(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim(),r=t===void 0||t===``?n(`client.chatMessages.the.model.returned.an.error.8306e3`,`The model returned an error.`):t;return $l(`system`,n(`client.chatMessages.model.response.failed.f24385`,`Model response failed: {value1}`,{value1:r}))}function au(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Au(e,`parts`))}function ou(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=su(e[0].text);if(t!==void 0)return[{role:`user`,parts:[{type:`skillInvocation`,name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:`user`,parts:[{type:`text`,text:t.userMessage}]}]]}function su(e){let t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;let n=t[4]?.trim();return{name:t[1]??`skill`,location:t[2]??``,content:t[3]??``,...n===void 0||n===``?{}:{userMessage:n}}}function cu(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function lu(e){let t=uu(Au(e,`timestamp`)),n=du(e),r=z(e,`thinkingLevel`);if(t!==void 0||n!==void 0||r!==void 0&&r!==``)return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n},...r===void 0||r===``?{}:{thinkingLevel:r}}}function uu(e){if(typeof e==`number`&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!=`string`||e===``)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function du(e){if(z(e,`role`)!==`assistant`)return;let t=z(e,`provider`),n=z(e,`model`),r=z(e,`responseModel`);if(t!==void 0&&t!==``||n!==void 0&&n!==``||r!==void 0&&r!==``)return{...t===void 0||t===``?{}:{provider:t},...n===void 0||n===``?{}:{id:n},...r===void 0||r===``?{}:{responseId:r}}}function fu(e){let t=z(e,`command`)??``,r=ju(e,`excludeFromContext`)===!0?[n(`client.chatMessages.excluded.from.context.858b78`,`Excluded from context`),``,`$ ${t}`]:[`$ ${t}`],i=Au(e,`output`);i!=null&&r.push(``,Nu(i));let a=Au(e,`exitCode`);a!=null&&r.push(``,n(`client.shellMessages.exit.code.2beadf`,`Exit code {value1}`,{value1:Nu(a)})),ju(e,`cancelled`)===!0&&r.push(``,n(`client.shellMessages.cancelled.a37778`,`Cancelled`)),ju(e,`truncated`)===!0&&r.push(``,n(`client.shellMessages.output.truncated.07e9bf`,`Output truncated`));let o=z(e,`fullOutputPath`);return o!==void 0&&o!==``&&r.push(``,n(`client.shellMessages.full.output.89763a`,`Full output: {value1}`,{value1:o})),{role:`bash`,parts:[{type:`text`,text:r.join(`
9
9
  `)}]}}function pu(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function mu(e,t){let n=gu(t);if(n!==void 0)return[n];if(typeof e==`string`){let n=z(t,`displayText`);return e===``?[]:[{type:`text`,text:e,...n===void 0?{}:{displayText:n}}]}return Array.isArray(e)?e.flatMap(e=>{let t=z(e,`type`),n=z(e,`text`),r=z(e,`displayText`),i=r===void 0?{}:{displayText:r};if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n,...i}]:[];if(t===`thinking`){let t=z(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t,...i}]:[]}if(t===`toolCall`){let t=z(e,`name`)??`tool`,n=Au(e,`arguments`),r=z(e,`id`),i=t===`read`?xu(z(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:Du(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}return t===`image`?hu(e):Eu(e)}).map(e=>e.type===`text`&&z(t,`role`)===`toolResult`?bu(e.text,t):e):Eu(e)}function hu(e){let t=z(e,`mimeType`),n=Au(e,`mediaId`),r=Qo(Au(e,`width`),Au(e,`height`));if(n!==void 0){let i=Mu(e,`byteSize`);if(es(n)&&t!==void 0&&/^image\/[a-z0-9][a-z0-9.+-]*$/iu.test(t)&&i!==void 0&&Number.isSafeInteger(i)&&i>=0)return[{type:`image`,mediaId:n,mimeType:t,byteSize:i,...r}]}else{let n=z(e,`data`);if(n!==void 0&&n!==``&&t!==void 0&&t!==``)return[{type:`image`,mimeType:t,data:n,...r}]}return[{type:`text`,text:`[image]`}]}function gu(e){if(z(e,`role`)===`custom`&&z(e,`customType`)===`pi-web.ask.answers`)return yu(Au(e,`details`))}function _u(e,t,n){if(!(e!==`ask_user`||n))try{return{type:`askUserQuestion`,ask:jr(Au(t,`ask`))}}catch{return}}function vu(e,t){if(e===`ask_user`)return yu(Au(t,`superseded`))}function yu(e){try{return{type:`askUserRecord`,outcome:Pr(e)}}catch{return}}function bu(e,t){let n=z(t,`toolCallId`),r=Au(t,`content`),i=Au(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:z(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:ju(t,`isError`)===!0}}function xu(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(n!==void 0&&n!==``)return{name:n,path:e}}function Su(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.streamId===void 0?{}:{streamId:r.streamId},...r.entryId===void 0?{}:{entryId:r.entryId},...r.transcriptIndex===void 0?{}:{transcriptIndex:r.transcriptIndex},...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts)if(o.type===`toolCall`){a();let e=Cu(o),r=t.length;t.push({role:`tool`,parts:[e],...i}),e.toolCallId!==void 0&&n.set(e.toolCallId,{lineIndex:r,partIndex:0})}else{if(o.type===`toolResult`){let i=o.toolCallId===void 0?void 0:n.get(o.toolCallId);if(i!==void 0&&wu(t,i,o,r.meta)){n.delete(o.toolCallId??``),t.at(-1)?.parts.at(-1)?.type===`askUserQuestion`&&!r.parts.some(e=>e.type===`askUserQuestion`||e.type===`askUserRecord`)&&e.push({type:`toolResultBoundary`,...o.toolCallId===void 0?{}:{toolCallId:o.toolCallId}});continue}}o.type===`askUserQuestion`||o.type===`askUserRecord`?(a(),t.push({role:r.role,parts:[o],...i})):e.push(o)}a()}return t}function Cu(e){return{type:`toolExecution`,...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:`pending`}}function wu(e,t,n,r){let i=e[t.lineIndex],a=i?.parts[t.partIndex];if(i===void 0||a?.type!==`toolExecution`)return!1;let o=Tu(n.details)??a.preview,s={...a,status:n.isError?`error`:`success`,resultText:n.text,...n.content===void 0?{}:{content:n.content},...n.details===void 0?{}:{details:n.details},...o===void 0?{}:{preview:o}};return e[t.lineIndex]={...i,parts:[...i.parts.slice(0,t.partIndex),s,...i.parts.slice(t.partIndex+1)],...r===void 0?{}:{meta:r}},!0}function Tu(e){let t=Au(e,`preview`);if(!ku(t))return;let n=z(t,`diff`),r=z(t,`error`),i=Mu(t,`firstChangedLine`);if(n!==void 0||r!==void 0||i!==void 0)return{...n===void 0?{}:{diff:n},...r===void 0?{}:{error:r},...i===void 0?{}:{firstChangedLine:i}}}function Eu(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:Du(e)}]:[{type:`text`,text:Nu(e)}]}function Du(e){if(!ku(e))return Nu(e);let t=z(e,`command`);if(t!==void 0)return t;let n=z(e,`path`);if(n!==void 0)return n;if(typeof e.oldText==`string`&&typeof e.newText==`string`)return`edit text replacement`;let r=e.edits;return Array.isArray(r)?`${String(r.length)} edit${r.length===1?``:`s`}`:Object.entries(e).filter(([,e])=>e!=null).slice(0,3).map(([e,t])=>`${e}: ${Ou(t)}`).join(` · `)}function Ou(e){return typeof e==`string`?e.length>80?`${e.slice(0,77)}…`:e:typeof e==`number`||typeof e==`boolean`?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?``:`s`}`:typeof e==`object`&&e?`object`:``}function ku(e){return typeof e==`object`&&!!e}function Au(e,t){return ku(e)?e[t]:void 0}function z(e,t){let n=Au(e,t);return typeof n==`string`?n:void 0}function ju(e,t){let n=Au(e,t);return typeof n==`boolean`?n:void 0}function Mu(e,t){let n=Au(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Nu(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var Pu=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,Fu=/^[a-z][a-z0-9.-]*$/u,Iu=/^[a-z][a-z0-9.-]*\.[a-z][a-z0-9.-]*--[a-z][a-z0-9.-]*$/u,Lu=64,Ru=16,zu=256,Bu=4096,Vu=65536;function Hu(e){return e.replaceAll(`:`,`.`)}function Uu(e,t=[]){return Gu(new URLSearchParams(window.location.search),e,t)}function Wu(e,t,n=[]){let r=new URLSearchParams;for(let[t,n]of Object.entries(qu(e)))if(typeof n==`string`)r.append(t,n);else for(let e of n)r.append(t,e);return Gu(r,t,n)}function Gu(e,t,n){let r=ud(),i={parameterCount:0,recordLength:0};for(let a of ed(t,n)){let t=Hu(a),n=$u(e,t);for(let[e,a]of Object.entries(n))Qu(e)&&!Object.hasOwn(r,e)&&od(r,e,a,`${t}--${e}`.length,i)}return td(r)}function Ku(){return ad(new URLSearchParams(window.location.search),e=>Zu(e)?{key:e,parameterLength:e.length}:void 0)}function qu(e){if(!dd(e))return ud();let t=ud(),n=0,r=0;for(let[i,a]of Object.entries(e)){if(n>=Lu)break;if(!Zu(i)||i.length>zu)continue;let e=typeof a==`string`?[a]:Array.isArray(a)&&a.every(e=>typeof e==`string`)?a.slice(0,Ru):void 0;if(e===void 0||e.length===0||e.some(e=>e.length>Bu))continue;let o=i.length+e.reduce((e,t)=>e+t.length,0);if(r+o>Vu)break;t[i]=e.length===1?e[0]??``:e,n+=1,r+=o}return t}function Ju(e,t,n,r){nd(t);for(let e of n)nd(e);let i=qu(e),a=new Set,o=new URLSearchParams;for(let[e,i]of Object.entries(r)){if(!Qu(e))throw Error(`Invalid contribution navigation key: ${e}`);for(let r of ed(t,n))a.add(`${Hu(r)}--${e}`);if(i==null)continue;let r=`${Hu(t)}--${e}`;for(let t of rd(e,i))o.append(r,t)}ld(o);let s=new URLSearchParams(o);for(let[e,t]of Object.entries(i))if(!a.has(e)){if(typeof t==`string`)s.append(e,t);else for(let n of t)s.append(e,n)}return ad(s,e=>Zu(e)?{key:e,parameterLength:e.length}:void 0)}function Yu(e,t){let n=qu(e),r=new URL(window.location.href);return cd(r.searchParams,n),id(r,t)}function Xu(e,t,n,r,i){nd(e);for(let e of t)nd(e);if(!Qu(n))throw Error(`Invalid contribution navigation key: ${n}`);let a=r==null?[]:rd(n,r),o=ed(e,t).map(e=>`${Hu(e)}--${n}`),s=o[0];if(s===void 0)throw Error(`Contribution navigation requires a canonical contribution id`);if(s.length>zu)throw Error(`Contribution navigation parameter is too long for key: ${n}`);let c=new URLSearchParams;for(let e of a)c.append(s,e);ld(c);let l=new Set(o),u=new URLSearchParams(c),d=new URL(window.location.href);for(let[e,t]of d.searchParams)Zu(e)&&!l.has(e)&&u.append(e,t);let f=ad(u,e=>Zu(e)?{key:e,parameterLength:e.length}:void 0);return cd(d.searchParams,f),id(d,i)}function Zu(e){return Iu.test(e)}function Qu(e){return Fu.test(e)}function $u(e,t){let n=`${t}--`;return ad(e,e=>{if(!e.startsWith(n))return;let t=e.slice(n.length);return Qu(t)?{key:t,parameterLength:e.length}:void 0})}function ed(e,t){return[...new Set([e,...t])]}function td(e){let t=ud();for(let[n,r]of Object.entries(e))t[n]=Array.isArray(r)?Object.freeze([...r]):r;return Object.freeze(t)}function nd(e){if(!Pu.test(e))throw Error(`Invalid qualified contribution id: ${e}`)}function rd(e,t){let n=Array.isArray(t)?t:[t];if(n.length>Ru)throw Error(`Contribution navigation value has too many items for key: ${e}`);let r=n.map(t=>{if(typeof t!=`string`&&typeof t!=`number`&&typeof t!=`boolean`)throw Error(`Invalid contribution navigation value for key: ${e}`);return String(t)});if(r.some(e=>e.length>Bu)||r.reduce((e,t)=>e+t.length,0)>Vu)throw Error(`Contribution navigation value is too long for key: ${e}`);return r}function id(e,t){return`${e.pathname}${e.search}${e.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,e):window.history.pushState({},``,e),!0)}function ad(e,t){let n=ud(),r={parameterCount:0,recordLength:0};for(let[i,a]of e){let e=t(i);e===void 0||e.parameterLength>zu||a.length>Bu||sd(n,e.key,a,e.parameterLength,r)}return n}function od(e,t,n,r,i){if(Object.hasOwn(e,t))return!1;let a=typeof n==`string`?[n]:[...n];if(a.length===0||a.length>Ru||a.some(e=>e.length>Bu)||i.parameterCount>=Lu)return!1;let o=r+a.reduce((e,t)=>e+t.length,0);return i.recordLength+o>Vu?!1:(e[t]=a.length===1?a[0]??``:a,i.parameterCount+=1,i.recordLength+=o,!0)}function sd(e,t,n,r,i){if(!Object.hasOwn(e,t)){od(e,t,n,r,i);return}let a=e[t],o=Array.isArray(a)?a:[a??``];o.length>=Ru||i.recordLength+n.length>Vu||(e[t]=[...o,n],i.recordLength+=n.length)}function cd(e,t){for(let t of[...e.keys()])Zu(t)&&e.delete(t);for(let[n,r]of Object.entries(t))if(typeof r==`string`)e.set(n,r);else for(let t of r)e.append(n,t)}function ld(e){let t=new Map,n=0,r=0;for(let[i,a]of e){if(!Zu(i))continue;if(i.length>zu)throw Error(`Contribution navigation parameter is too long: ${i}`);if(a.length>Bu)throw Error(`Contribution navigation value is too long for parameter: ${i}`);let e=t.get(i)??0;if(e===0&&(n+=1,r+=i.length,n>Lu))throw Error(`Contribution navigation has too many parameters`);let o=e+1;if(o>Ru)throw Error(`Contribution navigation parameter has too many values: ${i}`);if(t.set(i,o),r+=a.length,r>Vu)throw Error(`Contribution navigation record is too long`)}}function ud(){return Object.create(null)}function dd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fd(e){return e===`navigation`||e===`chat`||e===`workspace`?e:void 0}function pd(e){return e?.startsWith(`creating:`)===!0}function md(e,t){return(e.machineId??`local`)===t.machineId&&e.projectId===t.projectId&&e.workspaceId===t.workspaceId&&e.sessionId===t.sessionId}function hd(){let e=new URLSearchParams(window.location.search);return{machineId:bd(e.get(`machine`)),projectId:bd(e.get(`project`)),workspaceId:bd(e.get(`workspace`)),sessionId:bd(e.get(`session`)),tool:bd(e.get(`tool`)),view:bd(e.get(`view`))}}function gd(e,t){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool===void 0?void 0:_d(e.tool,t),view:fd(e.view)}}function _d(e,t){if(e!==void 0)return t(e)??(xd(e)?e:void 0)}function vd(e,t){return(e.machineId??`local`)===t.machineId&&e.projectId===t.projectId&&e.workspaceId===t.workspaceId}function yd(e,t){let n=new URL(window.location.href);n.searchParams.delete(`machine`),n.searchParams.delete(`project`),n.searchParams.delete(`workspace`),n.searchParams.delete(`session`),n.searchParams.delete(`tool`),n.searchParams.delete(`view`),e.machineId!==void 0&&e.machineId!==``&&e.machineId!==`local`&&n.searchParams.set(`machine`,e.machineId),e.projectId!==void 0&&e.projectId!==``&&n.searchParams.set(`project`,e.projectId),e.workspaceId!==void 0&&e.workspaceId!==``&&n.searchParams.set(`workspace`,e.workspaceId),e.sessionId!==void 0&&e.sessionId!==``&&n.searchParams.set(`session`,e.sessionId),e.tool!==void 0&&e.tool!==``&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&e.view!==``&&n.searchParams.set(`view`,e.view),t?.contributionQuery!==void 0&&cd(n.searchParams,qu(t.contributionQuery)),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function bd(e){return e===null||e===``?void 0:e}function xd(e){return/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}var Sd=class{constructor(e=()=>void 0){this.onChanged=e,this.chips=new Map}set(e,t,n){for(let[e,t]of[[`id`,n.id],[`label`,n.label],[`text`,n.text]])if(typeof t!=`string`||t.trim()===``)throw TypeError(`Prompt chip ${e} must be a non-empty string`);if(n.onRemove!==void 0&&typeof n.onRemove!=`function`)throw TypeError(`Prompt chip onRemove must be a function`);let r=Td(e,t,n.id);this.chips.set(r,Object.freeze({id:n.id,label:n.label,text:n.text,...n.onRemove===void 0?{}:{onRemove:n.onRemove},pluginId:e,target:Object.freeze({...t}),key:r})),this.onChanged()}remove(e,t,n){this.chips.delete(Td(e,t,n))&&this.onChanged()}list(e){return[...this.chips.values()].filter(t=>Cd(t.target,e))}removeByUser(e){this.chips.get(e.key)===e&&(this.chips.delete(e.key),this.onChanged(),Ed(e,`user`))}consume(e){for(let t of e)this.chips.get(t.key)===t&&this.chips.delete(t.key);this.onChanged();for(let t of e)Ed(t,`submitted`)}clear(){this.chips.clear(),this.onChanged()}};function Cd(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function wd(e,t){return[...e===``?[]:[e],...t.map(e=>e.text)].join(`
10
10
 
@@ -4711,7 +4711,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
4711
4711
  </div>
4712
4712
  <button type="button" class="ui-button ui-button--action" @click=${this.handleDismissActivityNotice}>${n(`ui.sessionActivity.dismiss`,`Dismiss and continue`)}</button>
4713
4713
  </section>
4714
- `}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);if(!this.isSessionSeen(t,e))return;let n=this.renderedTranscript;n?.sessionId===e.id&&n.messages===this.state.messages&&n.start===this.state.messagePageStart&&n.end===this.state.messagePageEnd&&this.sessionUnread.acknowledgeLoaded(t,e,{start:n.start,end:n.end,total:this.state.messagePageTotal,leafId:this.state.messagePageLeafId})}markSessionsRead(e){let t=R(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=Eq(e,t);await this.updateComplete,this.unreadConnected&&Dq(this.state)===n&&(this.readyChatIdentity=n,this.refreshSelectedUnreadHistory(),this.syncSelectedSessionReadState())}refreshSelectedUnreadHistory(){let e=this.state.selectedSession,t=R(this.state);e!==void 0&&this.readyChatIdentity===Eq(t,e)&&this.sessionUnread.needsHistoryRefresh(t,e,this.state.messagePageEnd,this.state.messagePageLeafId)&&this.sessions.refreshSelectedSession(e.id)}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);Nq(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=Ng({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:R(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});zg(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=Eq(e,t);if(Dq(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isRenderedModalOpen())return!1;let r=this.effectiveMainView();return r===`chat`?!0:r===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isRenderedModalOpen(){return ft(this.ownerDocument)}connectedCallback(){super.connectedCallback(),this.normalAuthInitSeq+=1,this.stylesheetRuntime.connect(this.ownerDocument),window.addEventListener(`popstate`,this.onPopState),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,lq),window.addEventListener(`focusin`,this.resetKeyboardSequence),window.addEventListener(`blur`,this.resetKeyboardSequence),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.initializeNormalAuth(this.normalAuthInitSeq)}startAuthenticatedApp(){this.isConnected&&!this.authenticatedAppRunning&&(this.authenticatedAppRunning=!0,this.syncNavigationOrder(),this.unreadConnected=!0,this.connectRealtime(),this.renegotiateUnreadMachines(),this.apiScope===`normal`&&(this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},tq)),this.scheduleSelectedSessionRefresh(),this.refreshWorkspaceActivity(),this.refreshMachineStatusSnapshots(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()}))}async initializeNormalAuth(e){if(this.apiScope===`management`){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus={configured:!0,authenticated:!0},this.normalAuthLoading=!1,this.startAuthenticatedApp()}else{this.normalAuthLoading=!0,this.normalAuthError=``;try{let t=await ws.status();if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus=t,t.authenticated&&this.startAuthenticatedApp()}catch(t){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthError=n(`ui.piWebApp.failedToCheckNormalModePassword`,`Failed to check normal-mode password: {errorMessageerror}`,{errorMessageerror:Uq(t)})}finally{this.isConnected&&e===this.normalAuthInitSeq&&(this.normalAuthLoading=!1)}}}disconnectedCallback(){this.workspaceNavigationGeneration+=1,this.normalAuthInitSeq+=1,this.authenticatedAppRunning=!1,this.stylesheetRuntime.disconnect(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,lq),window.removeEventListener(`focusin`,this.resetKeyboardSequence),window.removeEventListener(`blur`,this.resetKeyboardSequence),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.builtInPluginsReady.catch(()=>void 0),this.plugins.beginShutdown(),this.plugins.dispose(),this.auth.dispose(),this.sessions.dispose(),this.sessionWorkTransitions.clear(),this.cancelSelectedChatLoad(),this.notifications.dispose(),this.serverNotices.retainMachines(new Set),this.realtime.close(),this.closeMachineActivitySockets(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.cancelWorkspaceDeletionRefresh(),this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!Mq(this.state,e))return;let t=this.state;this.state={...this.state,...e},Rq(t)!==Rq(this.state)&&(this.cancelWorkspaceDeletionRefresh(),this.state={...this.state,workspaceDeletionRuns:{}}),(R(t)!==R(this.state)||t.selectedProject?.id!==this.state.selectedProject?.id||t.selectedWorkspace?.id!==this.state.selectedWorkspace?.id||t.workspaceTool!==this.state.workspaceTool||t.mainView!==this.state.mainView)&&(this.workspaceNavigationGeneration+=1);let n=Sq(t.status)!==Sq(this.state.status);this.state.modelDialog!==void 0&&(n||!this.modelDialogOriginIsCurrent(this.state.modelDialog.origin))&&(this.state={...this.state,modelDialog:void 0}),this.state.thinkingDialog!==void 0&&(n||!this.modelDialogOriginIsCurrent(this.state.thinkingDialog.origin))&&(this.state={...this.state,thinkingDialog:void 0}),Dq(t)!==Dq(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.displayedChatIdentity=void 0),Oq(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),kq(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),(R(t)!==R(this.state)||t.selectedProject?.id!==this.state.selectedProject?.id||t.selectedWorkspace?.id!==this.state.selectedWorkspace?.id)&&this.syncNavigationOrder()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=hd();if(!await this.machines.loadMachines(e.machineId)){this.setContentError(e,this.state.error);return}if(!this.routeLocationMatchesUrl(e)){await this.projects.loadProjects(),await this.withChatScrollTransition(async()=>{await this.restoreRoute(!1)}),await this.refreshWorkspaceDeletionRuns();return}let t=this.state.machineStatuses[e.machineId??`local`];R(this.state)===(e.machineId??`local`)&&await this.projects.loadProjects(),this.routeLocationMatchesUrl(e)?(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),this.shouldDeferRemoteRouteRestore(e,t)?this.deferRemoteRouteRestore(e):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()):(await this.withChatScrollTransition(async()=>{await this.restoreRoute(!1)}),await this.refreshWorkspaceDeletionRuns())}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await Om([this.renegotiateUnreadMachines(),this.sessions.refreshSelectedSession(void 0,{recoverNetwork:!0}),this.sessions.refreshCurrentWorkspaceSessions(R(this.state),{recoverNetwork:!0}),this.refreshMachineActivities(),this.refreshMachineStatusSnapshots(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology(),...this.navigationOrderScopes().map(e=>this.navigationOrder.load(e))])}schedulePiWebStatusRefresh(e=rq){this.apiScope!==`management`&&(this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh()},e))}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>jq(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}scheduleSelectedSessionRefresh(e=this.normalAuthInitSeq){this.isConnected&&this.authenticatedAppRunning&&e===this.normalAuthInitSeq&&(this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=window.setTimeout(()=>{this.selectedSessionRefreshTimer=void 0,this.refreshSelectedTranscript().finally(()=>{this.scheduleSelectedSessionRefresh(e)})},nq))}async refreshSelectedTranscript(){let e=this.state.selectedSession,t=this.state.status;e!==void 0&&e.archived!==!0&&this.isChatVisible()&&document.visibilityState===`visible`&&(t?.isStreaming===!0||t?.isCompacting===!0||t?.isBashRunning===!0||(t?.pendingMessageCount??0)>0||await this.sessions.refreshSelectedSession(e.id,{silent:!0}))}async refreshMachineStatusSnapshots(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>jq(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(async e=>{try{await this.machineStatus.refresh(e)}catch(t){console.warn(`Failed to refresh machine status for ${e}`,t)}}))}async loadClientConfig(){if(this.apiScope!==`management`)try{this.applyClientConfig((await Cs.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.configuredThemePreference=e.defaultTheme,this.applyPreferredTheme(!1),this.shortcutConfig=e.shortcuts??{},this.defaultStreamingBehavior=e.defaultStreamingBehavior??`steer`,this.workspaceUploadDefaultFolder=Qs(e),this.workspaceAttachmentsDefaultFolder=fc(e)}async submitNormalAuth(e){let t=this.normalAuthDialogMode??this.normalAuthGateMode();if(!(t===void 0||this.normalAuthLoading)){this.normalAuthLoading=!0,this.normalAuthError=``;try{t===`setup`?await ws.setup(e.password):t===`change`?await ws.changePassword(e.currentPassword??``,e.password):await ws.login(e.password);let n=await ws.status();this.normalAuthStatus=n,this.normalAuthDialogMode=void 0,n.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=Uq(e)}finally{this.normalAuthLoading=!1}}}normalAuthGateMode(){if(this.apiScope!==`management`&&this.normalAuthStatus?.authenticated!==!0)return this.normalAuthStatus?.configured===!0?`login`:`setup`}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Om([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology(),...this.navigationOrderScopes().map(e=>this.navigationOrder.load(e))]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.effectiveWorkspaceTool();e!==void 0&&t!==void 0&&await this.invalidateWorkspacePanels(t)}hardReloadApp(){window.location.reload()}async restoreRoute(e,t,n=`current-url`){let r=this.restoreRouteFor(hd(),e,void 0,t,n),i=this.routeRestoreSeq;return await r,i===this.routeRestoreSeq&&(this.rememberCurrentMachineNavigation(),!0)}async navigate(e,t,n){let{route:r,contributionQuery:i}=p_(e,t,hd(),Ku(),R(this.state),(e,t)=>{let n=this.plugins.resolveWorkspacePanelRouteId(e,t);if(n!==void 0)return{contributionId:n,sourceContributionId:this.plugins.getWorkspacePanels().find(e=>e.id===n)?.sourceContributionId}},n);await this.commitAndRestoreNavigation({...r,machineId:r.machineId??`local`,tool:r.tool,view:r.view,surface:{contributionQuery:i}},{replace:t?.history===`replace`})}async restoreRouteFor(e,t,r=this.readWorkspaceRouteSurface(e),i,a=`current-url`){this.setContentError(e,``);let o=R(this.state),s=e.projectId===void 0||e.projectId===``?Fq():r,c=this.beginNavigationOperation(pq),l=this.beginNavigationOperation(oq);this.routeMatchesCurrentSelection(e)||(this.routeSelectionRestoreSeq+=1);let u=this.routeSelectionRestoreSeq,d={...l,isCurrent:()=>u===this.routeSelectionRestoreSeq&&l.isCurrent()},f=++this.routeRestoreSeq;this.routeRestoreDepth+=1;try{if(!await this.restoreRouteMachine(e,!1)){if(!d.isCurrent())return;let t=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),t!==``&&this.setState({error:t});let r=e.machineId??`local`;this.setContentError(e,n(`ui.main.9c637b97e1a5`,`Machine not found: {arg0}`,{arg0:r}));let i=Mc(r);this.state.browserErrors[Ic(i)]===void 0&&this.browserErrors.report(i,t||n(`ui.main.9c637b97e1a5`,`Machine not found: {arg0}`,{arg0:r}));return}if(!d.isCurrent())return;let r=this.loadPluginsForSelectedMachine();r.catch(()=>void 0);let o=gd({...e,tool:void 0},()=>void 0),l=e.view!==void 0&&o.view===void 0,u=bq(o),p={updateUrl:t,urlPublication:a,unavailableToolRoute:!1,unavailablePanelViewRoute:l,requestedTool:void 0,requestedRoute:e,restoreSeq:f,navigation:c,...u===void 0?{}:{restoredWorkspaceIdentity:u}},m=e.tool!==void 0||l,h=async()=>{if(!m)return p;if(await r,!this.isCurrentRouteRestore(f,c)||R(this.state)!==(e.machineId??`local`))return;let t=this.resolveBrowserAppRoute(e);return this.setState({workspaceTool:t.tool,...i===void 0&&t.view!==void 0?{mainView:t.view}:{}}),{...p,unavailableToolRoute:e.tool!==void 0&&t.tool===void 0,unavailablePanelViewRoute:e.view!==void 0&&t.view===void 0,requestedTool:t.tool}};if(this.isCurrentRouteRestore(f,c)&&this.setState({...m?{}:{workspaceTool:void 0},mainView:i??o.view??this.defaultRouteView()}),o.projectId===void 0||o.projectId===``){let e=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),e!==``&&this.setState({error:e});let t=await h();t!==void 0&&await this.finishWorkspaceRouteRestore(s,t);return}if(this.routeMatchesCurrentSelection(o)){let e=await h();e!==void 0&&await this.finishWorkspaceRouteRestore(s,e);return}let g=this.state.projects.find(e=>e.id===o.projectId);if(!g){let t=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),t!==``&&this.setState({error:t}),this.setContentError(e,this.projects.loadErrors.get(R(this.state))??n(`ui.main.bd4a8479284a`,`Project not found: {arg0}`,{arg0:o.projectId}));let r=Mc(R(this.state));this.state.browserErrors[Ic(r)]===void 0&&this.browserErrors.report(r,n(`ui.main.bd4a8479284a`,`Project not found: {arg0}`,{arg0:o.projectId})),await h();return}let _=a===`deferred`&&this.state.selectedProject?.id===g.id&&o.workspaceId!==void 0?this.state.workspaces.find(e=>e.projectId===g.id&&e.id===o.workspaceId):void 0,v=_!==void 0&&this.state.selectedWorkspace?.projectId===_.projectId&&this.state.selectedWorkspace.id===_.id?this.sessions.preferredSession(_.path,this.state.sessions,o.sessionId):void 0,ee;if(v===void 0?ee=_===void 0?await this.workspaces.selectProject(g,{workspaceId:o.workspaceId,sessionId:o.sessionId,updateUrl:!1,navigation:d}):await this.workspaces.selectWorkspace(_,{sessionId:o.sessionId,updateUrl:!1,navigation:d}):await this.sessions.selectSession(v,{deferChatLoading:o.sessionId===void 0,updateUrl:!1,navigation:d}),d.isCurrent()&&this.setContentError(e,ee??``),!this.isCurrentRouteRestore(f,c))return;let y=await h();y!==void 0&&await this.finishWorkspaceRouteRestore(s,y)}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),R(this.state)!==o&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e,t){return e===this.routeRestoreSeq&&(t===void 0||t.isCurrent())}beginNavigationOperation(e){this.syncNavigationFreshness();let t={generation:this.navigationGeneration,scope:Object.freeze([...e]),isCurrent:()=>this.isNavigationFresh(t)};return t}isNavigationFresh(e){return this.syncNavigationFreshness(),e.scope.every(t=>this.navigationFieldGenerations[t]<=e.generation)}syncNavigationFreshness(){let e=hd(),t=this.observedNavigationRoute;if(t!==void 0){let n=aq.filter(n=>Iq(t,n)!==Iq(e,n));if(n.length>0){let e=++this.navigationGeneration;for(let t of n)this.navigationFieldGenerations[t]=e}}this.observedNavigationRoute=e}retireNavigationScope(e){if(this.workspaceNavigationGeneration+=1,this.syncNavigationFreshness(),e.length===0)return;let t=++this.navigationGeneration;for(let n of e)this.navigationFieldGenerations[n]=t;this.sessions.retireReadRecoveries(e),this.invalidateWorkspaceSurface()}retireRouteRestoreForSynchronousNavigation(){this.retireNavigationScope(sq),this.routeRestoreSeq+=1}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?Fq():{contributionQuery:Ku()}}isPendingSessionStartRouteCurrent(e){return md(hd(),e)}commitPendingSessionStartNavigation(e,t){this.isPendingSessionStartRouteCurrent(e)&&(this.syncNavigationFreshness(),yd({...hd(),sessionId:t.id},{replace:!0}),this.syncNavigationFreshness(),this.rememberCurrentMachineNavigation())}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.kind!==`remote`||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===``?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=zq(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e))this.clearPendingRemoteRouteRestore();else{this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=Mc(t),r=this.state.browserErrors[Ic(n)],i=()=>this.state.browserErrors[Ic(n)]!==r,a=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(a?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.contentError()===``&&this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}}scheduleNextRemoteRouteRestoreAttempt(e){this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=iq.length?(this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore()):(this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore())}setRemoteRouteRestoreMessage(e,t={}){let r=e.machineId??`local`,i=this.state.machines.find(e=>e.id===r)?.name??this.state.selectedMachine?.name??n(`bundled.info.remote.machine.674281`,`Remote machine`),a=this.state.machineStatuses[r],o=Mc(r),s=this.state.browserErrors[Ic(o)]?.message,c=a?.error??(s!==void 0&&!s.startsWith(n(`ui.main.8829a2aadeba`,`{arg0} is unavailable`,{arg0:i}))&&!s.startsWith(n(`ui.main.ae729e314f15`,`{arg0} is still unavailable`,{arg0:i}))?s:void 0),l=t.exhausted===!0?n(`ui.piWebApp.isStillUnavailable`,`{machineName} is still unavailable.`,{machineName:i}):n(`ui.piWebApp.isUnavailableReconnecting`,`{machineName} is unavailable. Reconnecting…`,{machineName:i});this.browserErrors.report(o,`${l}${c===void 0?``:` ${c}`}`)}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.routeLocationMatchesUrl(e)&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(R(this.state)===n)return!0;let r=this.state.machines.find(e=>e.id===n);return r!==void 0&&(await this.machines.selectMachine(r,{updateUrl:t}),this.state.selectedMachine?.id===n)}routeMatchesCurrentSelection(e){let t=this.state.selectedWorkspace;return(e.machineId??`local`)!==R(this.state)||e.workspaceId===void 0||e.workspaceId===``||this.state.selectedProject?.id!==e.projectId||t?.id!==e.workspaceId||!this.sessions.canReuseSelectedSession()?!1:e.sessionId===void 0?this.state.selectedSession?.id===this.sessions.preferredSession(t.path,this.state.sessions,void 0)?.id:this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e!==void 0&&await this.invalidateWorkspacePanels(e,t)}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await Gq(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return!this.isRenderedModalOpen()&&this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e,t=this.currentContributionQueryForState()){this.commitMachineNavigationSnapshot(xh(this.state,t),e)}rememberCurrentMachineNavigation(){this.machineNavigation.remember(xh(this.state,this.currentContributionQueryForState()))}writeWorkspaceRouteSurfaceToUrl(e){Yu(e.contributionQuery??{},{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return!0;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??bh(e.id);return!await this.commitAndRestoreNavigation(r,t)||n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id?!1:this.shouldPreserveUnrestoredMachineNavigation(r)?(this.replaceMachineNavigationSnapshot(r),!0):(this.replaceNavigationUrl(this.currentContributionQueryForState()),!0)}captureNavigation(){let e=hd();return{...e,machineId:e.machineId??`local`}}navigationSelectionMatchesUrl(e,t=!1){let n=hd();return(n.machineId??`local`)===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.sessionId===e.sessionId&&(t||n.tool===e.tool&&n.view===e.view)}routeLocationMatchesUrl(e){let t=hd();return this.routeSelectionMatchesUrl(e)&&t.tool===e.tool&&t.view===e.view}async commitAndRestoreNavigation(e,t={}){return t.expected!==void 0&&!this.navigationSelectionMatchesUrl(t.expected,t.creationHandoff===!0)?!1:t.creationHandoff===!0?pd(t.expected?.sessionId)?(yd({...hd(),sessionId:e.sessionId},{replace:!0}),this.restoreRoute(!1,void 0,`deferred`)):!1:(this.commitMachineNavigationSnapshot(e,{replace:t.replace}),this.restoreCommittedNavigation(e))}async navigateToProjectFromController(e,t={}){let n=xh(this.state,this.currentContributionQueryForState()),r=e===void 0?{...n,projectId:void 0,workspaceId:void 0,sessionId:void 0,surface:{}}:{...n,projectId:e.id,workspaceId:void 0,sessionId:void 0,surface:{}};return await this.commitAndRestoreNavigation(r,t)?(this.replaceNavigationUrl(),!0):!1}async navigateToWorkspaceFromController(e,t={}){let n=xh(this.state,this.currentContributionQueryForState()),r=e===void 0?{...n,projectId:void 0,workspaceId:void 0,sessionId:void 0,surface:{}}:{...n,projectId:e.projectId,workspaceId:e.id,sessionId:void 0,surface:{}};return await this.commitAndRestoreNavigation(r,t)?(this.replaceNavigationUrl(),!0):!1}async navigateToSessionFromController(e,t={}){let n=xh(this.state,this.currentContributionQueryForState()),r=this.state.selectedWorkspace,i={...n,...e!==void 0&&r!==void 0?{projectId:r.projectId,workspaceId:r.id}:{},sessionId:e?.id};return await this.commitAndRestoreNavigation(i,t)?(this.replaceNavigationUrl(),!0):!1}shouldPreserveUnrestoredMachineNavigation(e){let t=this.state.browserErrors[Ic(Mc(R(this.state)))];return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&(this.state.error!==``||t!==void 0)}openWorkspaceTool(e,t={}){let n=R(this.state),r=this.state.selectedWorkspace;r!==void 0&&this.terminalAvailableForMachine(n)&&e===this.requiredTerminalPanelId(n)?this.workspaceTerminal(`core`,r,n).open():this.publishWorkspaceTool(e,this.currentContributionQueryForState(),t)}publishWorkspaceTool(e,t=this.currentContributionQueryForState(),n={}){let r=this.availableWorkspacePanelId(e);if(r===void 0)return;let i=this.state.workspaceTool!==r||this.state.mainView!==`workspace`;i&&n.invalidateNavigationSelection!==!1&&this.invalidateNavigationSelection();let a=xh(this.state,t);this.commitMachineNavigationSnapshot({...a,tool:r,view:`workspace`,surface:{contributionQuery:t}}),i?this.retireRouteRestoreForSynchronousNavigation():this.routeRestoreSeq+=1,i?this.setState({workspaceTool:r,mainView:`workspace`}):this.requestUpdate(),this.refreshSelectedWorkspaceTool(r)}openTerminal(e){let t=R(this.state),n=this.state.selectedWorkspace;n!==void 0&&this.workspaceTerminal(`core`,n,t).open(e)}workspaceTerminal(e,t,r,i){if(this.apiScope===`management`)return Object.freeze({open:()=>void 0,runCommand:n=>this.terminalCommandRunsForOrigin(e,r).runCommand({...n,workspace:t})});let a=this.requiredTerminalByMachine.get(r),o=a===void 0?void 0:Cj(a.binding,t,r);if(a===void 0||o===void 0){let e=eI(r);return Object.freeze({open:()=>{i?.isCurrent()!==!1&&this.setState({error:e.message})},runCommand:()=>Promise.reject(e)})}let s=e=>R(this.state)===r&&(i===void 0||this.state.selectedProject?.id===t.projectId&&this.state.selectedWorkspace?.id===t.id&&vd(hd(),{machineId:r,projectId:t.projectId,workspaceId:t.id})&&(!e||i.isCurrent())),c=n=>a.facade.createWorkspaceTerminal({origin:e,registrationPluginId:a.binding.registrationPluginId,workspace:t,peer:o,host:{navigateWorkspaceContribution:(e,t)=>this.navigateRuntimeWorkspaceContribution(r,e,t,n)}});return Object.freeze({open:e=>{s(!0)&&c({...hq(i),generation:this.workspaceNavigationGeneration}).open(e)},runCommand:e=>{if(!s(e.open===!0))return Promise.reject(Error(n(`ui.main.4971c700c4fd`,`Workspace panel context is no longer current`)));let t={...hq(e.open===!0?i:void 0),generation:this.workspaceNavigationGeneration};return c(t).runCommand(e)}})}async navigateRuntimeWorkspaceContribution(e,t,n,r){if(!this.navigationUrlContextMatchesUrl(r))return;let i=n.navigationAliases??[],a=this.selectedWorkspaceRouteIdentity(),o={machineId:e,projectId:t.projectId,workspaceId:t.id},s=Ju(a!==void 0&&xq(a,o)?this.currentContributionQueryForState():{},n.contributionId,i,n.query),c={machineId:e,projectId:t.projectId,workspaceId:t.id,sessionId:void 0,tool:n.contributionId,view:`workspace`,surface:{contributionQuery:s}};if(R(this.state)!==e||this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId){if(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),!await this.commitAndRestoreNavigation(c))return;this.replaceNavigationUrl()}else this.publishWorkspaceTool(n.contributionId,s)}terminalCommandRunsForOrigin(e,t=R(this.state)){let n=Lq(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;if(this.apiScope===`normal`){let r={runCommand:({workspace:n,...r})=>this.workspaceTerminal(e,n,t).runCommand(r),listCommandRuns:e=>this.listTerminalCommandRuns(t,e),getCommandRun:async e=>(await this.listTerminalCommandRuns(t)).find(t=>t.id===e),open:e=>{R(this.state)===t&&this.openTerminal(e)}};return this.terminalCommandRunRuntimes.set(n,r),r}let i=yL(e,{api:{runTerminalCommand:(e,n)=>Is.runTerminalCommand(e,n,t),listCommandRuns:e=>Is.listCommandRuns(e,t),getCommandRun:e=>Is.getCommandRun(e,t)},openTerminal:()=>void 0});return this.terminalCommandRunRuntimes.set(n,i),i}async listTerminalCommandRuns(e,t){let n=this.requiredTerminalByMachine.get(e);if(n===void 0)throw eI(e);if(R(this.state)!==e)return[];let r=t?.projectId??this.state.selectedProject?.id,i=((r===this.state.selectedProject?.id?this.state.workspaces:this.state.workspacesByProjectId[r??``])??[]).filter(e=>t?.workspaceId===void 0||e.id===t.workspaceId);return(await Promise.all(i.map(r=>{let i=Cj(n.binding,r,e);if(i===void 0)throw eI(e);return n.facade.listCommandRuns({peer:i,filter:{...t?.terminalId===void 0?{}:{terminalId:t.terminalId},...t?.statuses===void 0?{}:{statuses:t.statuses},...t?.metadata===void 0?{}:{metadata:t.metadata}}})}))).flat()}selectMainView(e,t={}){t.invalidateNavigationSelection!==!1&&this.invalidateNavigationSelection();let n=xh(this.state,this.currentContributionQueryForState());this.commitMachineNavigationSnapshot({...n,view:e}),this.retireRouteRestoreForSynchronousNavigation(),this.setState({mainView:e})}openSettings(e=`general`){pL(e),this.settingsSection=e}closeSettings(){this.settingsSection=void 0,pL(void 0)}navigateSettings(e){this.settingsSection=e,pL(e)}restoreSettingsRoute(){this.settingsSection=fL()}handleWorkspaceChange(e,t){(R(e)!==R(t)||e.selectedProject?.id!==t.selectedProject?.id||e.selectedWorkspace?.id!==t.selectedWorkspace?.id)&&(this.routeRestoreInProgress||(this.reconcileWorkspacePanelSelection(),this.rememberCurrentMachineNavigation()),this.sessions.updatePolling(),t.selectedWorkspace!==void 0&&(this.sessions.refreshPinnedSessions(t.selectedWorkspace.path,R(this.state)),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(this.state.workspaceTool)))}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),this.sessionUnread.retainMachines(e);for(let t of e)this.sessionUnread.projection(t)===void 0&&this.sessionUnread.refresh(t)}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){return this.unreadConnected?this.sessionUnread.refresh(e):Promise.resolve()}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.sessions.refreshCurrentWorkspaceSessions(e,{recoverNetwork:!0}),R(this.state)===e&&this.workspaces.refreshSelectedProjectTopology(),this.renegotiateUnreadMachine(e),this.apiScope===`normal`&&this.serverNotices.refresh(e),this.refreshWorkspaceActivity(e),this.machineStatus.refresh(e).catch(t=>{console.warn(`Failed to refresh machine status for ${e}`,t)})},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new bp(this.apiScope);e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t),this.machineStatus.refresh(t).catch(e=>{console.warn(`Failed to refresh machine status for ${t}`,e)})},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>Aq(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity,e):t.type===`machine.status`&&this.machineStatus.apply(e,t.status)}handleRealtimeEvent(e,t){if(t.type===`sessions.unread`)this.sessionUnread.applyEvent(e,t);else if(t.type===`notices.updated`)this.serverNotices.applyEvent(e,t);else if(t.type===`workspace.activity`)this.activity.applyWorkspaceActivity(t.activity);else if(t.type===`machine.status`)this.machineStatus.apply(e,t.status);else if(t.type===`workspaces.changed`)R(this.state)===e&&this.state.selectedProject?.id===t.projectId&&this.workspaces.refreshSelectedProjectTopology();else if(Pq(t))t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns();else{if(t.type===`status.update`||t.type===`activity.update`){let n=this.sessionWorkTransitions.observe(e,t);n!==void 0&&this.invalidateFilesForSessionActivity(e,n)}this.sessions.applyGlobalEvent(t)}}invalidateFilesForSessionActivity(e,t){let n=this.state,r=n.selectedWorkspace;if(e!==R(n)||r===void 0||!n.sessions.some(e=>e.id===t&&e.cwd===r.path))return;let i=()=>{console.warn(`Workspace file refresh after session activity failed`)};try{this.invalidateWorkspaceResources(r,wq(n),{reason:`agent-activity`,resources:[`workspace.files`]}).catch(i)}catch{i()}}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.sessionCleanupDialog=void 0,this.setState({piWebStatus:void 0}),this.sessions.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e!==void 0&&this.invalidateWorkspacePanels(e)}invalidateWorkspaceSurface(){this.workspaceSurfaceRevision+=1}workspaceSurfaceInputs(){let e=this.state;return[e.selectedMachine,e.selectedWorkspace,e.selectedSession,e.workspaceTool,e.mainView,e.piWebStatus,this.appShell.isMobileNavigationLayout,e.selectedProject,e.projects,e.workspaces,e.isLoadingProjects,e.isLoadingWorkspaces,this.workspaceContentError(),this.workspaceUploadDefaultFolder,this.workspaceSurfaceRevision,this.navigationPreferences,this.isDesktopSideBySideLayout(),gq()]}renderWorkspacePanel(){let e=this.state.selectedWorkspace,t=e===void 0?this.workspacePanelEmptyState():void 0,n=this.visibleWorkspacePanels();return b`
4714
+ `}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);if(!this.isSessionSeen(t,e))return;let n=this.renderedTranscript;n?.sessionId===e.id&&n.messages===this.state.messages&&n.start===this.state.messagePageStart&&n.end===this.state.messagePageEnd&&this.sessionUnread.acknowledgeLoaded(t,e,{start:n.start,end:n.end,total:this.state.messagePageTotal,leafId:this.state.messagePageLeafId})}markSessionsRead(e){let t=R(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=Eq(e,t);await this.updateComplete,this.unreadConnected&&Dq(this.state)===n&&(this.readyChatIdentity=n,this.refreshSelectedUnreadHistory(),this.syncSelectedSessionReadState())}refreshSelectedUnreadHistory(){let e=this.state.selectedSession,t=R(this.state);e!==void 0&&this.readyChatIdentity===Eq(t,e)&&this.sessionUnread.needsHistoryRefresh(t,e,this.state.messagePageEnd,this.state.messagePageLeafId)&&this.sessions.refreshSelectedSession(e.id)}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);Nq(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=Ng({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:R(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});zg(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=Eq(e,t);if(Dq(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isRenderedModalOpen())return!1;let r=this.effectiveMainView();return r===`chat`?!0:r===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isRenderedModalOpen(){return ft(this.ownerDocument)}connectedCallback(){super.connectedCallback(),this.normalAuthInitSeq+=1,this.stylesheetRuntime.connect(this.ownerDocument),window.addEventListener(`popstate`,this.onPopState),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,lq),window.addEventListener(`focusin`,this.resetKeyboardSequence),window.addEventListener(`blur`,this.resetKeyboardSequence),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.initializeNormalAuth(this.normalAuthInitSeq)}startAuthenticatedApp(){this.isConnected&&!this.authenticatedAppRunning&&(this.authenticatedAppRunning=!0,this.syncNavigationOrder(),this.unreadConnected=!0,this.connectRealtime(),this.renegotiateUnreadMachines(),this.apiScope===`normal`&&(this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},tq)),this.scheduleSelectedSessionRefresh(),this.refreshWorkspaceActivity(),this.refreshMachineStatusSnapshots(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()}))}async initializeNormalAuth(e){if(this.apiScope===`management`){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus={configured:!0,authenticated:!0},this.normalAuthLoading=!1,this.startAuthenticatedApp()}else{this.normalAuthLoading=!0,this.normalAuthError=``;try{let t=await ws.status();if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus=t,t.authenticated&&this.startAuthenticatedApp()}catch(t){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthError=n(`ui.piWebApp.failedToCheckNormalModePassword`,`Failed to check normal-mode password: {errorMessageerror}`,{errorMessageerror:Uq(t)})}finally{this.isConnected&&e===this.normalAuthInitSeq&&(this.normalAuthLoading=!1)}}}disconnectedCallback(){this.workspaceNavigationGeneration+=1,this.normalAuthInitSeq+=1,this.authenticatedAppRunning=!1,this.stylesheetRuntime.disconnect(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,lq),window.removeEventListener(`focusin`,this.resetKeyboardSequence),window.removeEventListener(`blur`,this.resetKeyboardSequence),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.builtInPluginsReady.catch(()=>void 0),this.plugins.beginShutdown(),this.plugins.dispose(),this.auth.dispose(),this.sessions.dispose(),this.sessionWorkTransitions.clear(),this.cancelSelectedChatLoad(),this.notifications.dispose(),this.serverNotices.retainMachines(new Set),this.realtime.close(),this.closeMachineActivitySockets(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.cancelWorkspaceDeletionRefresh(),this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!Mq(this.state,e))return;let t=this.state;this.state={...this.state,...e},Rq(t)!==Rq(this.state)&&(this.cancelWorkspaceDeletionRefresh(),this.state={...this.state,workspaceDeletionRuns:{}}),(R(t)!==R(this.state)||t.selectedProject?.id!==this.state.selectedProject?.id||t.selectedWorkspace?.id!==this.state.selectedWorkspace?.id||t.workspaceTool!==this.state.workspaceTool||t.mainView!==this.state.mainView)&&(this.workspaceNavigationGeneration+=1);let n=Sq(t.status)!==Sq(this.state.status);this.state.modelDialog!==void 0&&(n||!this.modelDialogOriginIsCurrent(this.state.modelDialog.origin))&&(this.state={...this.state,modelDialog:void 0}),this.state.thinkingDialog!==void 0&&(n||!this.modelDialogOriginIsCurrent(this.state.thinkingDialog.origin))&&(this.state={...this.state,thinkingDialog:void 0}),Dq(t)!==Dq(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.displayedChatIdentity=void 0),Oq(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),kq(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),(R(t)!==R(this.state)||t.selectedProject?.id!==this.state.selectedProject?.id||t.selectedWorkspace?.id!==this.state.selectedWorkspace?.id)&&this.syncNavigationOrder()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=hd();if(!await this.machines.loadMachines(e.machineId)){this.setContentError(e,this.state.error);return}if(!this.routeLocationMatchesUrl(e)){await this.projects.loadProjects(),await this.withChatScrollTransition(async()=>{await this.restoreRoute(!1)}),await this.refreshWorkspaceDeletionRuns();return}let t=this.state.machineStatuses[e.machineId??`local`];if(R(this.state)===(e.machineId??`local`)&&await this.projects.loadProjects(),!this.routeLocationMatchesUrl(e)){await this.withChatScrollTransition(async()=>{await this.restoreRoute(!1)}),await this.refreshWorkspaceDeletionRuns();return}let n=this.apiScope===`management`?this.projects.managementEntryProject({...e,machineId:e.machineId??`local`}):void 0;n===void 0?await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)):await this.navigateToProjectFromController(n,{expected:{...e,machineId:e.machineId??`local`}}),this.shouldDeferRemoteRouteRestore(e,t)?this.deferRemoteRouteRestore(e):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await Om([this.renegotiateUnreadMachines(),this.sessions.refreshSelectedSession(void 0,{recoverNetwork:!0}),this.sessions.refreshCurrentWorkspaceSessions(R(this.state),{recoverNetwork:!0}),this.refreshMachineActivities(),this.refreshMachineStatusSnapshots(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology(),...this.navigationOrderScopes().map(e=>this.navigationOrder.load(e))])}schedulePiWebStatusRefresh(e=rq){this.apiScope!==`management`&&(this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh()},e))}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>jq(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}scheduleSelectedSessionRefresh(e=this.normalAuthInitSeq){this.isConnected&&this.authenticatedAppRunning&&e===this.normalAuthInitSeq&&(this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=window.setTimeout(()=>{this.selectedSessionRefreshTimer=void 0,this.refreshSelectedTranscript().finally(()=>{this.scheduleSelectedSessionRefresh(e)})},nq))}async refreshSelectedTranscript(){let e=this.state.selectedSession,t=this.state.status;e!==void 0&&e.archived!==!0&&this.isChatVisible()&&document.visibilityState===`visible`&&(t?.isStreaming===!0||t?.isCompacting===!0||t?.isBashRunning===!0||(t?.pendingMessageCount??0)>0||await this.sessions.refreshSelectedSession(e.id,{silent:!0}))}async refreshMachineStatusSnapshots(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>jq(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(async e=>{try{await this.machineStatus.refresh(e)}catch(t){console.warn(`Failed to refresh machine status for ${e}`,t)}}))}async loadClientConfig(){if(this.apiScope!==`management`)try{this.applyClientConfig((await Cs.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.configuredThemePreference=e.defaultTheme,this.applyPreferredTheme(!1),this.shortcutConfig=e.shortcuts??{},this.defaultStreamingBehavior=e.defaultStreamingBehavior??`steer`,this.workspaceUploadDefaultFolder=Qs(e),this.workspaceAttachmentsDefaultFolder=fc(e)}async submitNormalAuth(e){let t=this.normalAuthDialogMode??this.normalAuthGateMode();if(!(t===void 0||this.normalAuthLoading)){this.normalAuthLoading=!0,this.normalAuthError=``;try{t===`setup`?await ws.setup(e.password):t===`change`?await ws.changePassword(e.currentPassword??``,e.password):await ws.login(e.password);let n=await ws.status();this.normalAuthStatus=n,this.normalAuthDialogMode=void 0,n.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=Uq(e)}finally{this.normalAuthLoading=!1}}}normalAuthGateMode(){if(this.apiScope!==`management`&&this.normalAuthStatus?.authenticated!==!0)return this.normalAuthStatus?.configured===!0?`login`:`setup`}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Om([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology(),...this.navigationOrderScopes().map(e=>this.navigationOrder.load(e))]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.effectiveWorkspaceTool();e!==void 0&&t!==void 0&&await this.invalidateWorkspacePanels(t)}hardReloadApp(){window.location.reload()}async restoreRoute(e,t,n=`current-url`){let r=this.restoreRouteFor(hd(),e,void 0,t,n),i=this.routeRestoreSeq;return await r,i===this.routeRestoreSeq&&(this.rememberCurrentMachineNavigation(),!0)}async navigate(e,t,n){let{route:r,contributionQuery:i}=p_(e,t,hd(),Ku(),R(this.state),(e,t)=>{let n=this.plugins.resolveWorkspacePanelRouteId(e,t);if(n!==void 0)return{contributionId:n,sourceContributionId:this.plugins.getWorkspacePanels().find(e=>e.id===n)?.sourceContributionId}},n);await this.commitAndRestoreNavigation({...r,machineId:r.machineId??`local`,tool:r.tool,view:r.view,surface:{contributionQuery:i}},{replace:t?.history===`replace`})}async restoreRouteFor(e,t,r=this.readWorkspaceRouteSurface(e),i,a=`current-url`){this.setContentError(e,``);let o=R(this.state),s=e.projectId===void 0||e.projectId===``?Fq():r,c=this.beginNavigationOperation(pq),l=this.beginNavigationOperation(oq);this.routeMatchesCurrentSelection(e)||(this.routeSelectionRestoreSeq+=1);let u=this.routeSelectionRestoreSeq,d={...l,isCurrent:()=>u===this.routeSelectionRestoreSeq&&l.isCurrent()},f=++this.routeRestoreSeq;this.routeRestoreDepth+=1;try{if(!await this.restoreRouteMachine(e,!1)){if(!d.isCurrent())return;let t=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),t!==``&&this.setState({error:t});let r=e.machineId??`local`;this.setContentError(e,n(`ui.main.9c637b97e1a5`,`Machine not found: {arg0}`,{arg0:r}));let i=Mc(r);this.state.browserErrors[Ic(i)]===void 0&&this.browserErrors.report(i,t||n(`ui.main.9c637b97e1a5`,`Machine not found: {arg0}`,{arg0:r}));return}if(!d.isCurrent())return;let r=this.loadPluginsForSelectedMachine();r.catch(()=>void 0);let o=gd({...e,tool:void 0},()=>void 0),l=e.view!==void 0&&o.view===void 0,u=bq(o),p={updateUrl:t,urlPublication:a,unavailableToolRoute:!1,unavailablePanelViewRoute:l,requestedTool:void 0,requestedRoute:e,restoreSeq:f,navigation:c,...u===void 0?{}:{restoredWorkspaceIdentity:u}},m=e.tool!==void 0||l,h=async()=>{if(!m)return p;if(await r,!this.isCurrentRouteRestore(f,c)||R(this.state)!==(e.machineId??`local`))return;let t=this.resolveBrowserAppRoute(e);return this.setState({workspaceTool:t.tool,...i===void 0&&t.view!==void 0?{mainView:t.view}:{}}),{...p,unavailableToolRoute:e.tool!==void 0&&t.tool===void 0,unavailablePanelViewRoute:e.view!==void 0&&t.view===void 0,requestedTool:t.tool}};if(this.isCurrentRouteRestore(f,c)&&this.setState({...m?{}:{workspaceTool:void 0},mainView:i??o.view??this.defaultRouteView()}),o.projectId===void 0||o.projectId===``){let e=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),e!==``&&this.setState({error:e});let t=await h();t!==void 0&&await this.finishWorkspaceRouteRestore(s,t);return}if(this.routeMatchesCurrentSelection(o)){let e=await h();e!==void 0&&await this.finishWorkspaceRouteRestore(s,e);return}let g=this.state.projects.find(e=>e.id===o.projectId);if(!g){let t=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),t!==``&&this.setState({error:t}),this.setContentError(e,this.projects.loadErrors.get(R(this.state))??n(`ui.main.bd4a8479284a`,`Project not found: {arg0}`,{arg0:o.projectId}));let r=Mc(R(this.state));this.state.browserErrors[Ic(r)]===void 0&&this.browserErrors.report(r,n(`ui.main.bd4a8479284a`,`Project not found: {arg0}`,{arg0:o.projectId})),await h();return}let _=a===`deferred`&&this.state.selectedProject?.id===g.id&&o.workspaceId!==void 0?this.state.workspaces.find(e=>e.projectId===g.id&&e.id===o.workspaceId):void 0,v=_!==void 0&&this.state.selectedWorkspace?.projectId===_.projectId&&this.state.selectedWorkspace.id===_.id?this.sessions.preferredSession(_.path,this.state.sessions,o.sessionId):void 0,ee;if(v===void 0?ee=_===void 0?await this.workspaces.selectProject(g,{workspaceId:o.workspaceId,sessionId:o.sessionId,updateUrl:!1,navigation:d}):await this.workspaces.selectWorkspace(_,{sessionId:o.sessionId,updateUrl:!1,navigation:d}):await this.sessions.selectSession(v,{deferChatLoading:o.sessionId===void 0,updateUrl:!1,navigation:d}),d.isCurrent()&&this.setContentError(e,ee??``),!this.isCurrentRouteRestore(f,c))return;let y=await h();y!==void 0&&await this.finishWorkspaceRouteRestore(s,y)}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),R(this.state)!==o&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e,t){return e===this.routeRestoreSeq&&(t===void 0||t.isCurrent())}beginNavigationOperation(e){this.syncNavigationFreshness();let t={generation:this.navigationGeneration,scope:Object.freeze([...e]),isCurrent:()=>this.isNavigationFresh(t)};return t}isNavigationFresh(e){return this.syncNavigationFreshness(),e.scope.every(t=>this.navigationFieldGenerations[t]<=e.generation)}syncNavigationFreshness(){let e=hd(),t=this.observedNavigationRoute;if(t!==void 0){let n=aq.filter(n=>Iq(t,n)!==Iq(e,n));if(n.length>0){let e=++this.navigationGeneration;for(let t of n)this.navigationFieldGenerations[t]=e}}this.observedNavigationRoute=e}retireNavigationScope(e){if(this.workspaceNavigationGeneration+=1,this.syncNavigationFreshness(),e.length===0)return;let t=++this.navigationGeneration;for(let n of e)this.navigationFieldGenerations[n]=t;this.sessions.retireReadRecoveries(e),this.invalidateWorkspaceSurface()}retireRouteRestoreForSynchronousNavigation(){this.retireNavigationScope(sq),this.routeRestoreSeq+=1}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?Fq():{contributionQuery:Ku()}}isPendingSessionStartRouteCurrent(e){return md(hd(),e)}commitPendingSessionStartNavigation(e,t){this.isPendingSessionStartRouteCurrent(e)&&(this.syncNavigationFreshness(),yd({...hd(),sessionId:t.id},{replace:!0}),this.syncNavigationFreshness(),this.rememberCurrentMachineNavigation())}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.kind!==`remote`||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===``?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=zq(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e))this.clearPendingRemoteRouteRestore();else{this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=Mc(t),r=this.state.browserErrors[Ic(n)],i=()=>this.state.browserErrors[Ic(n)]!==r,a=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(a?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.contentError()===``&&this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}}scheduleNextRemoteRouteRestoreAttempt(e){this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=iq.length?(this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore()):(this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore())}setRemoteRouteRestoreMessage(e,t={}){let r=e.machineId??`local`,i=this.state.machines.find(e=>e.id===r)?.name??this.state.selectedMachine?.name??n(`bundled.info.remote.machine.674281`,`Remote machine`),a=this.state.machineStatuses[r],o=Mc(r),s=this.state.browserErrors[Ic(o)]?.message,c=a?.error??(s!==void 0&&!s.startsWith(n(`ui.main.8829a2aadeba`,`{arg0} is unavailable`,{arg0:i}))&&!s.startsWith(n(`ui.main.ae729e314f15`,`{arg0} is still unavailable`,{arg0:i}))?s:void 0),l=t.exhausted===!0?n(`ui.piWebApp.isStillUnavailable`,`{machineName} is still unavailable.`,{machineName:i}):n(`ui.piWebApp.isUnavailableReconnecting`,`{machineName} is unavailable. Reconnecting…`,{machineName:i});this.browserErrors.report(o,`${l}${c===void 0?``:` ${c}`}`)}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.routeLocationMatchesUrl(e)&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(R(this.state)===n)return!0;let r=this.state.machines.find(e=>e.id===n);return r!==void 0&&(await this.machines.selectMachine(r,{updateUrl:t}),this.state.selectedMachine?.id===n)}routeMatchesCurrentSelection(e){let t=this.state.selectedWorkspace;return(e.machineId??`local`)!==R(this.state)||e.workspaceId===void 0||e.workspaceId===``||this.state.selectedProject?.id!==e.projectId||t?.id!==e.workspaceId||!this.sessions.canReuseSelectedSession()?!1:e.sessionId===void 0?this.state.selectedSession?.id===this.sessions.preferredSession(t.path,this.state.sessions,void 0)?.id:this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e!==void 0&&await this.invalidateWorkspacePanels(e,t)}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await Gq(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return!this.isRenderedModalOpen()&&this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e,t=this.currentContributionQueryForState()){this.commitMachineNavigationSnapshot(xh(this.state,t),e)}rememberCurrentMachineNavigation(){this.machineNavigation.remember(xh(this.state,this.currentContributionQueryForState()))}writeWorkspaceRouteSurfaceToUrl(e){Yu(e.contributionQuery??{},{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return!0;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??bh(e.id);return!await this.commitAndRestoreNavigation(r,t)||n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id?!1:this.shouldPreserveUnrestoredMachineNavigation(r)?(this.replaceMachineNavigationSnapshot(r),!0):(this.replaceNavigationUrl(this.currentContributionQueryForState()),!0)}captureNavigation(){let e=hd();return{...e,machineId:e.machineId??`local`}}navigationSelectionMatchesUrl(e,t=!1){let n=hd();return(n.machineId??`local`)===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.sessionId===e.sessionId&&(t||n.tool===e.tool&&n.view===e.view)}routeLocationMatchesUrl(e){let t=hd();return this.routeSelectionMatchesUrl(e)&&t.tool===e.tool&&t.view===e.view}async commitAndRestoreNavigation(e,t={}){return t.expected!==void 0&&!this.navigationSelectionMatchesUrl(t.expected,t.creationHandoff===!0)?!1:t.creationHandoff===!0?pd(t.expected?.sessionId)?(yd({...hd(),sessionId:e.sessionId},{replace:!0}),this.restoreRoute(!1,void 0,`deferred`)):!1:(this.commitMachineNavigationSnapshot(e,{replace:t.replace}),this.restoreCommittedNavigation(e))}async navigateToProjectFromController(e,t={}){let n=xh(this.state,this.currentContributionQueryForState()),r=e===void 0?{...n,projectId:void 0,workspaceId:void 0,sessionId:void 0,surface:{}}:{...n,projectId:e.id,workspaceId:void 0,sessionId:void 0,surface:{}};return await this.commitAndRestoreNavigation(r,t)?(this.replaceNavigationUrl(),!0):!1}async navigateToWorkspaceFromController(e,t={}){let n=xh(this.state,this.currentContributionQueryForState()),r=e===void 0?{...n,projectId:void 0,workspaceId:void 0,sessionId:void 0,surface:{}}:{...n,projectId:e.projectId,workspaceId:e.id,sessionId:void 0,surface:{}};return await this.commitAndRestoreNavigation(r,t)?(this.replaceNavigationUrl(),!0):!1}async navigateToSessionFromController(e,t={}){let n=xh(this.state,this.currentContributionQueryForState()),r=this.state.selectedWorkspace,i={...n,...e!==void 0&&r!==void 0?{projectId:r.projectId,workspaceId:r.id}:{},sessionId:e?.id};return await this.commitAndRestoreNavigation(i,t)?(this.replaceNavigationUrl(),!0):!1}shouldPreserveUnrestoredMachineNavigation(e){let t=this.state.browserErrors[Ic(Mc(R(this.state)))];return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&(this.state.error!==``||t!==void 0)}openWorkspaceTool(e,t={}){let n=R(this.state),r=this.state.selectedWorkspace;r!==void 0&&this.terminalAvailableForMachine(n)&&e===this.requiredTerminalPanelId(n)?this.workspaceTerminal(`core`,r,n).open():this.publishWorkspaceTool(e,this.currentContributionQueryForState(),t)}publishWorkspaceTool(e,t=this.currentContributionQueryForState(),n={}){let r=this.availableWorkspacePanelId(e);if(r===void 0)return;let i=this.state.workspaceTool!==r||this.state.mainView!==`workspace`;i&&n.invalidateNavigationSelection!==!1&&this.invalidateNavigationSelection();let a=xh(this.state,t);this.commitMachineNavigationSnapshot({...a,tool:r,view:`workspace`,surface:{contributionQuery:t}}),i?this.retireRouteRestoreForSynchronousNavigation():this.routeRestoreSeq+=1,i?this.setState({workspaceTool:r,mainView:`workspace`}):this.requestUpdate(),this.refreshSelectedWorkspaceTool(r)}openTerminal(e){let t=R(this.state),n=this.state.selectedWorkspace;n!==void 0&&this.workspaceTerminal(`core`,n,t).open(e)}workspaceTerminal(e,t,r,i){if(this.apiScope===`management`)return Object.freeze({open:()=>void 0,runCommand:n=>this.terminalCommandRunsForOrigin(e,r).runCommand({...n,workspace:t})});let a=this.requiredTerminalByMachine.get(r),o=a===void 0?void 0:Cj(a.binding,t,r);if(a===void 0||o===void 0){let e=eI(r);return Object.freeze({open:()=>{i?.isCurrent()!==!1&&this.setState({error:e.message})},runCommand:()=>Promise.reject(e)})}let s=e=>R(this.state)===r&&(i===void 0||this.state.selectedProject?.id===t.projectId&&this.state.selectedWorkspace?.id===t.id&&vd(hd(),{machineId:r,projectId:t.projectId,workspaceId:t.id})&&(!e||i.isCurrent())),c=n=>a.facade.createWorkspaceTerminal({origin:e,registrationPluginId:a.binding.registrationPluginId,workspace:t,peer:o,host:{navigateWorkspaceContribution:(e,t)=>this.navigateRuntimeWorkspaceContribution(r,e,t,n)}});return Object.freeze({open:e=>{s(!0)&&c({...hq(i),generation:this.workspaceNavigationGeneration}).open(e)},runCommand:e=>{if(!s(e.open===!0))return Promise.reject(Error(n(`ui.main.4971c700c4fd`,`Workspace panel context is no longer current`)));let t={...hq(e.open===!0?i:void 0),generation:this.workspaceNavigationGeneration};return c(t).runCommand(e)}})}async navigateRuntimeWorkspaceContribution(e,t,n,r){if(!this.navigationUrlContextMatchesUrl(r))return;let i=n.navigationAliases??[],a=this.selectedWorkspaceRouteIdentity(),o={machineId:e,projectId:t.projectId,workspaceId:t.id},s=Ju(a!==void 0&&xq(a,o)?this.currentContributionQueryForState():{},n.contributionId,i,n.query),c={machineId:e,projectId:t.projectId,workspaceId:t.id,sessionId:void 0,tool:n.contributionId,view:`workspace`,surface:{contributionQuery:s}};if(R(this.state)!==e||this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId){if(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),!await this.commitAndRestoreNavigation(c))return;this.replaceNavigationUrl()}else this.publishWorkspaceTool(n.contributionId,s)}terminalCommandRunsForOrigin(e,t=R(this.state)){let n=Lq(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;if(this.apiScope===`normal`){let r={runCommand:({workspace:n,...r})=>this.workspaceTerminal(e,n,t).runCommand(r),listCommandRuns:e=>this.listTerminalCommandRuns(t,e),getCommandRun:async e=>(await this.listTerminalCommandRuns(t)).find(t=>t.id===e),open:e=>{R(this.state)===t&&this.openTerminal(e)}};return this.terminalCommandRunRuntimes.set(n,r),r}let i=yL(e,{api:{runTerminalCommand:(e,n)=>Is.runTerminalCommand(e,n,t),listCommandRuns:e=>Is.listCommandRuns(e,t),getCommandRun:e=>Is.getCommandRun(e,t)},openTerminal:()=>void 0});return this.terminalCommandRunRuntimes.set(n,i),i}async listTerminalCommandRuns(e,t){let n=this.requiredTerminalByMachine.get(e);if(n===void 0)throw eI(e);if(R(this.state)!==e)return[];let r=t?.projectId??this.state.selectedProject?.id,i=((r===this.state.selectedProject?.id?this.state.workspaces:this.state.workspacesByProjectId[r??``])??[]).filter(e=>t?.workspaceId===void 0||e.id===t.workspaceId);return(await Promise.all(i.map(r=>{let i=Cj(n.binding,r,e);if(i===void 0)throw eI(e);return n.facade.listCommandRuns({peer:i,filter:{...t?.terminalId===void 0?{}:{terminalId:t.terminalId},...t?.statuses===void 0?{}:{statuses:t.statuses},...t?.metadata===void 0?{}:{metadata:t.metadata}}})}))).flat()}selectMainView(e,t={}){t.invalidateNavigationSelection!==!1&&this.invalidateNavigationSelection();let n=xh(this.state,this.currentContributionQueryForState());this.commitMachineNavigationSnapshot({...n,view:e}),this.retireRouteRestoreForSynchronousNavigation(),this.setState({mainView:e})}openSettings(e=`general`){pL(e),this.settingsSection=e}closeSettings(){this.settingsSection=void 0,pL(void 0)}navigateSettings(e){this.settingsSection=e,pL(e)}restoreSettingsRoute(){this.settingsSection=fL()}handleWorkspaceChange(e,t){(R(e)!==R(t)||e.selectedProject?.id!==t.selectedProject?.id||e.selectedWorkspace?.id!==t.selectedWorkspace?.id)&&(this.routeRestoreInProgress||(this.reconcileWorkspacePanelSelection(),this.rememberCurrentMachineNavigation()),this.sessions.updatePolling(),t.selectedWorkspace!==void 0&&(this.sessions.refreshPinnedSessions(t.selectedWorkspace.path,R(this.state)),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(this.state.workspaceTool)))}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),this.sessionUnread.retainMachines(e);for(let t of e)this.sessionUnread.projection(t)===void 0&&this.sessionUnread.refresh(t)}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){return this.unreadConnected?this.sessionUnread.refresh(e):Promise.resolve()}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.sessions.refreshCurrentWorkspaceSessions(e,{recoverNetwork:!0}),R(this.state)===e&&this.workspaces.refreshSelectedProjectTopology(),this.renegotiateUnreadMachine(e),this.apiScope===`normal`&&this.serverNotices.refresh(e),this.refreshWorkspaceActivity(e),this.machineStatus.refresh(e).catch(t=>{console.warn(`Failed to refresh machine status for ${e}`,t)})},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new bp(this.apiScope);e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t),this.machineStatus.refresh(t).catch(e=>{console.warn(`Failed to refresh machine status for ${t}`,e)})},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>Aq(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity,e):t.type===`machine.status`&&this.machineStatus.apply(e,t.status)}handleRealtimeEvent(e,t){if(t.type===`sessions.unread`)this.sessionUnread.applyEvent(e,t);else if(t.type===`notices.updated`)this.serverNotices.applyEvent(e,t);else if(t.type===`workspace.activity`)this.activity.applyWorkspaceActivity(t.activity);else if(t.type===`machine.status`)this.machineStatus.apply(e,t.status);else if(t.type===`workspaces.changed`)R(this.state)===e&&this.state.selectedProject?.id===t.projectId&&this.workspaces.refreshSelectedProjectTopology();else if(Pq(t))t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns();else{if(t.type===`status.update`||t.type===`activity.update`){let n=this.sessionWorkTransitions.observe(e,t);n!==void 0&&this.invalidateFilesForSessionActivity(e,n)}this.sessions.applyGlobalEvent(t)}}invalidateFilesForSessionActivity(e,t){let n=this.state,r=n.selectedWorkspace;if(e!==R(n)||r===void 0||!n.sessions.some(e=>e.id===t&&e.cwd===r.path))return;let i=()=>{console.warn(`Workspace file refresh after session activity failed`)};try{this.invalidateWorkspaceResources(r,wq(n),{reason:`agent-activity`,resources:[`workspace.files`]}).catch(i)}catch{i()}}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.sessionCleanupDialog=void 0,this.setState({piWebStatus:void 0}),this.sessions.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e!==void 0&&this.invalidateWorkspacePanels(e)}invalidateWorkspaceSurface(){this.workspaceSurfaceRevision+=1}workspaceSurfaceInputs(){let e=this.state;return[e.selectedMachine,e.selectedWorkspace,e.selectedSession,e.workspaceTool,e.mainView,e.piWebStatus,this.appShell.isMobileNavigationLayout,e.selectedProject,e.projects,e.workspaces,e.isLoadingProjects,e.isLoadingWorkspaces,this.workspaceContentError(),this.workspaceUploadDefaultFolder,this.workspaceSurfaceRevision,this.navigationPreferences,this.isDesktopSideBySideLayout(),gq()]}renderWorkspacePanel(){let e=this.state.selectedWorkspace,t=e===void 0?this.workspacePanelEmptyState():void 0,n=this.visibleWorkspacePanels();return b`
4715
4715
  <workspace-panel
4716
4716
  id="workspace-panel"
4717
4717
  .workspace=${e}
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./PiWebApp-vueV4eKR.js","./external-B9K8duyP.js","./vendor-editor-core-BfnHL1Dg.js","./vendor-editor-languages-bNquDJP0.js"])))=>i.map(i=>d[i]);
2
- import{B as e,Q as t,R as n,U as r,X as i,t as a,z as o}from"./external-B9K8duyP.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();async function s(n=async()=>(await a(`pi-web-plugins/localization.json`,{shouldLoadPlugin:e=>e.id===`zh-cn`})).registrations){o(`en`,{});try{let r=(await n()).find(e=>e.id===`zh-cn`&&e.machineId===void 0);if(r!==void 0){let n=new AbortController,a=(await r.plugin.activate({apiVersion:4,pluginId:r.id,runtimePluginId:r.id,html:i,svg:t,translate:e,signal:n.signal,lifetimeSignal:n.signal})).contributions.localizations?.find(e=>e.locale===`zh-CN`);a!==void 0&&o(a.locale,a.messages)}}catch(e){console.warn(`Could not initialize UI localization; using English`,e)}}function c(t){t.documentElement.lang=n();let i=t.querySelector(`meta[name="description"]`);i!==null&&(i.content=e(`app.description`,`Remote web UI and browser control plane for persistent Pi Coding Agent sessions.`));let a=t.querySelector(`link[rel="manifest"]`);a!==null&&(a.href=r(n()===`zh-CN`?`pi-web-plugins/zh-cn/manifest.webmanifest`:`manifest.webmanifest`))}var l=`modulepreload`,u=function(e,t){return new URL(e,t).href},d={},f=function(e){return e.pathname.endsWith(`.css`)},p=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i};await s(),c(document),await function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=u(t,n);let r=s(t),i=f(r);return p(d,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:l,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})}(()=>import(`./PiWebApp-vueV4eKR.js`),__vite__mapDeps([0,1,2,3]),import.meta.url);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./PiWebApp-BVnLs9Kj.js","./external-B9K8duyP.js","./vendor-editor-core-BfnHL1Dg.js","./vendor-editor-languages-bNquDJP0.js"])))=>i.map(i=>d[i]);
2
+ import{B as e,Q as t,R as n,U as r,X as i,t as a,z as o}from"./external-B9K8duyP.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();async function s(n=async()=>(await a(`pi-web-plugins/localization.json`,{shouldLoadPlugin:e=>e.id===`zh-cn`})).registrations){o(`en`,{});try{let r=(await n()).find(e=>e.id===`zh-cn`&&e.machineId===void 0);if(r!==void 0){let n=new AbortController,a=(await r.plugin.activate({apiVersion:4,pluginId:r.id,runtimePluginId:r.id,html:i,svg:t,translate:e,signal:n.signal,lifetimeSignal:n.signal})).contributions.localizations?.find(e=>e.locale===`zh-CN`);a!==void 0&&o(a.locale,a.messages)}}catch(e){console.warn(`Could not initialize UI localization; using English`,e)}}function c(t){t.documentElement.lang=n();let i=t.querySelector(`meta[name="description"]`);i!==null&&(i.content=e(`app.description`,`Remote web UI and browser control plane for persistent Pi Coding Agent sessions.`));let a=t.querySelector(`link[rel="manifest"]`);a!==null&&(a.href=r(n()===`zh-CN`?`pi-web-plugins/zh-cn/manifest.webmanifest`:`manifest.webmanifest`))}var l=`modulepreload`,u=function(e,t){return new URL(e,t).href},d={},f=function(e){return e.pathname.endsWith(`.css`)},p=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i};await s(),c(document),await function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=u(t,n);let r=s(t),i=f(r);return p(d,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:l,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})}(()=>import(`./PiWebApp-BVnLs9Kj.js`),__vite__mapDeps([0,1,2,3]),import.meta.url);
@@ -10,7 +10,7 @@
10
10
  <link rel="apple-touch-icon" href="./apple-touch-icon.png" />
11
11
  <link rel="manifest" crossorigin="use-credentials" href="./manifest.webmanifest" />
12
12
  <style>:root{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--pi-control-font-size:16px;--pi-control-font-family:var(--pi-font,system-ui, sans-serif);--pi-control-monospace-font-family:var(--pi-mono,ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);--pi-bg:#0d1117;--pi-surface:#161b22;--pi-surface-hover:#21262d;--pi-terminal-bg:#05070a;--pi-terminal-text:#e6edf3;--pi-border:#30363d;--pi-border-muted:#21262d;--pi-text:#e6edf3;--pi-text-secondary:#c9d1d9;--pi-text-bright:#f0f6fc;--pi-muted:#8b949e;--pi-dim:#6e7681;--pi-accent:#58a6ff;--pi-accent-border:#2f81f7;--pi-selection-bg:#0d2847;--pi-success:#3fb950;--pi-success-border:#238636;--pi-success-bg:#0f1b12;--pi-success-surface:#0f2a16;--pi-success-ring:#3fb95055;--pi-warning:#d29922;--pi-warning-border:#6e5200;--pi-warning-surface:#1f1a10;--pi-danger:#ff7b72;--pi-purple:#d2a8ff;--pi-purple-border:#a371f7;--pi-purple-surface:#21132f;--pi-overlay:#0008;--pi-shadow-soft:#0006;--pi-shadow:#0008;--pi-shadow-strong:#000b;--pi-bg-overlay-soft:#0d1117dd;--pi-bg-overlay:#0d1117e6;--pi-success-bg-overlay:#0f1b12ee;--pi-terminal-selection:#264f78}html,body{background:var(--pi-bg);height:100%;color:var(--pi-text);margin:0;overflow:hidden}body{min-height:100dvh}</style>
13
- <script type="module" crossorigin src="./assets/index-C8f0d0CR.js"></script>
13
+ <script type="module" crossorigin src="./assets/index-pOnX1cs_.js"></script>
14
14
  <link rel="modulepreload" crossorigin href="./assets/external-B9K8duyP.js">
15
15
  </head>
16
16
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chainingintention/pi-web-cn",
3
- "version": "2.202610.1",
3
+ "version": "2.202610.2",
4
4
  "description": "Web UI for persistent Pi Coding Agent sessions in real workspaces.",
5
5
  "license": "MIT",
6
6
  "author": "Federico Jaramillo Martinez",