From fa4efccb0672f1da431a67ec9202544901eda97a Mon Sep 17 00:00:00 2001 From: rUv Date: Tue, 1 Dec 2026 00:19:09 -0500 Subject: [PATCH] fix(phone-host): Teams & swarm view, live terminal kept on a late cancel, chat fixes (1.2.0) + README phone connector (#5212) * fix(phone-host): Teams & swarm view, live terminal kept on a late cancel, chat fixes in the phone screens (1.2.0) - ruflo.teamSnapshot.read: the phone's Teams & swarm screen now works on a ruflo host. Read-only; swarms, hive-mind, agents, tasks and claims from each shared workspace's .claude-flow, plus Claude Code agent teams whose lead works in one. Allowlisted fields: names, statuses, counts, message summaries (280 chars) and task subjects; never tokens, agent prompts or claim notes. - terminal.unsubscribe with a requestId ends only that request's stream, so a late cancel of an older stream no longer stops the phone's live one. - A Claude tab reports its session to the phone only once Claude trusts the folder (its .claude.json) or has written its transcript, so a chat view never covers Claude's first-run trust prompt. - Phone screens rebuilt from ruflo-ui fix/mobile-chat-ux-5211 (98448b90c): agent tabs open in chat once the agent has a session, and the @ file menu narrows as you type. Refs #5211 Co-Authored-By: RuFlo * docs(readme): phone connector section with header picture Co-Authored-By: RuFlo --------- Co-authored-by: r --- README.md | 20 ++ docs/assets/readme/phone.svg | 32 +++ phone-host/README.md | 3 +- ...c119900de484383435ea299085d7474108b765.js} | 4 +- ...ba3fa3814b945530e46703eebfef26582ef924.js} | 2 +- phone-host/bundle/index.html | 2 +- phone-host/bundle/manifest.json | 30 +-- phone-host/package-lock.json | 4 +- phone-host/package.json | 2 +- phone-host/src/chat-sessions.mjs | 25 +++ phone-host/src/full-methods.mjs | 54 ++++- phone-host/src/rpc.mjs | 3 + phone-host/src/team-snapshot.mjs | 205 ++++++++++++++++++ phone-host/test/chat-host.test.mjs | 43 +++- phone-host/test/full.test.mjs | 13 ++ phone-host/test/host.test.mjs | 44 ++++ 16 files changed, 450 insertions(+), 36 deletions(-) create mode 100644 docs/assets/readme/phone.svg rename phone-host/bundle/assets/{ff5bafc87134b6a566c67255bb9546eabc92bd5b335b13af7d063abaa4a9fd20.js => 0812724a10c2f7e160171ae846c119900de484383435ea299085d7474108b765.js} (92%) rename phone-host/bundle/assets/{48fae3d9447c3e75964d9031d9ede8a0d784d091f9c0b0625c12d3a73b621247.js => 393753fcec4b8acaddf3b0214cba3fa3814b945530e46703eebfef26582ef924.js} (99%) create mode 100644 phone-host/src/team-snapshot.mjs diff --git a/README.md b/README.md index 91b3f6a247..859c93caa8 100644 --- a/README.md +++ b/README.md @@ -195,6 +195,26 @@ The default is **read + ask**. Available levels are `read`, `write`, `manage`, a [Watch the recorded Claude Haiku session](docs/assets/ruflo-console-claude-control.gif) to see mission creation, page navigation, a refused swarm stop, and control being taken back. The recording uses `write + auto`. Step 1 uses `ask` so you can approve creation yourself. [Recorded test findings](v3/docs/adr/ADR-444-claude-controls-the-console.md) · [Reproduction script](plugins/ruflo-console/scripts/e2e-control.sh) + + +## Phone connector + +

Pair a phone with the ruflo CLI: terminals, Claude and Codex tabs on the phone, end-to-end encrypted

+ +Pair the RuFlo or Orca phone app with this computer over your LAN or Tailscale. The link is end-to-end encrypted and needs no desktop app, relay or account. The connector is an opt-in add-on (`@claude-flow/phone-host`) that is installed only when you run setup: + +```bash +ruflo phone setup # installs the add-on into ~/.ruflo/phone-host +ruflo phone daemon start --full # leave out --full for a read-only phone +ruflo phone pair --full # shows a QR code for one phone +``` + +- **Read-only by default.** A phone sees the shared workspaces and their status, and changes nothing. +- **With `--full`**, it opens terminals and Claude, Codex and other agent tabs that run as you, with a chat view for Claude and Codex. +- **A pairing code is a password.** Check `ruflo phone devices` and remove a phone with `ruflo phone revoke `. + +[Setup, access levels and security](phone-host/README.md) + ## Choose your next capability diff --git a/docs/assets/readme/phone.svg b/docs/assets/readme/phone.svg new file mode 100644 index 0000000000..33375ee8d9 --- /dev/null +++ b/docs/assets/readme/phone.svg @@ -0,0 +1,32 @@ + +Your agents, in your pocket.Pair a phone with the ruflo CLI. End-to-end encrypted, no desktop app, relay or account. + + + + +RUFLO · PHONE CONNECTOR +Your agents, +in your pocket. +Pair a phone with the CLI. No desktop app, relay or account. + + + +$ ruflo phone + pair --full +QR + + + +E2EE + + + + +Claude +Codex +Terminal +Fix the tests +Done: 70 pass + + + diff --git a/phone-host/README.md b/phone-host/README.md index bd169fd1a7..39f6167630 100644 --- a/phone-host/README.md +++ b/phone-host/README.md @@ -75,6 +75,7 @@ An agent can start the host and pair a phone, including a full-access phone when - `status.get`; - `repo.list`, `worktree.ps` and `worktree.show`, which list only what you chose to share; - `github.repoSlug`, which reads the `origin` remote; +- `ruflo.teamSnapshot.read`, for the Teams & swarm screen. It reads the ruflo swarms, hive-mind, agents, tasks and claims in each shared workspace's `.claude-flow`, plus the Claude Code agent teams whose lead works in one. It sends names, statuses and counts, plus short text: the first 280 characters of each recent team message, and each task's subject or description (ruflo task descriptions are cut at 200). It never sends tokens, agent prompts or claim notes; - `worktree.activate`, `ui.get`, `mobileRelay.projectSections`, `runtime.clientCapabilities.update` and `runtime.clientEvents.*`. These are the reads the workspace screen makes when it opens. - the `mobileWeb.bundle.*` reads that load the app's screens. @@ -97,7 +98,7 @@ A full-access phone can open terminal tabs and agent tabs in a shared workspace. ## Host screens -The app draws its host screens from a web bundle that the host serves. This package ships the RuFlo build in `bundle/`: about 15 MB unpacked, built from cognitum-one/ruflo-ui `phone/mobile-lanes-merged-20261130` (`ef1e43563`, Orca `98e7dbec`). It is used by default. +The app draws its host screens from a web bundle that the host serves. This package ships the RuFlo build in `bundle/`: about 15 MB unpacked, built from cognitum-one/ruflo-ui `fix/mobile-chat-ux-5211` (`98448b90c`, Orca `98e7dbec`). That is `phone/mobile-lanes-merged-20261130` (`ef1e43563`) plus two chat fixes. A tab set to chat waits in the terminal until its agent has a session, so a first-run prompt stays visible; with no stored choice, chat is the default. And the `@` file menu narrows as you type. It is used by default. Every asset is checked against the manifest's SHA-256 before it is sent. diff --git a/phone-host/bundle/assets/ff5bafc87134b6a566c67255bb9546eabc92bd5b335b13af7d063abaa4a9fd20.js b/phone-host/bundle/assets/0812724a10c2f7e160171ae846c119900de484383435ea299085d7474108b765.js similarity index 92% rename from phone-host/bundle/assets/ff5bafc87134b6a566c67255bb9546eabc92bd5b335b13af7d063abaa4a9fd20.js rename to phone-host/bundle/assets/0812724a10c2f7e160171ae846c119900de484383435ea299085d7474108b765.js index 473542bd0b..6373ac2d35 100644 --- a/phone-host/bundle/assets/ff5bafc87134b6a566c67255bb9546eabc92bd5b335b13af7d063abaa4a9fd20.js +++ b/phone-host/bundle/assets/0812724a10c2f7e160171ae846c119900de484383435ea299085d7474108b765.js @@ -669,7 +669,7 @@ ${t} #selection-overlay, ${t} #scroll-indicator { position: absolute; }`,documen `)||s?e:n.slice(0,n.endsWith(`\r `)?-2:-1)}var vM=/^\[Image:\s*source:\s*(.+?)\]\s*$/,vR=/\[Image #\d+\]/,vI=/\[Image #\d+\]/g,vA=(RegExp(`(${ek.source})|\\[Image #(\\d+)\\]`,"g"),/^[^\S\r\n]*\[Image #\d+\]/),vP=/\[Image #\d+\][^\S\r\n]*$/,vE=/^[^\S\r\n]+/,vD=/[^\S\r\n]+$/;function vB(e){if("user"!==e.role||0===e.blocks.length)return[];let t=[];for(let r of e.blocks){var i;if(!g6(r))return[];let e=(i=r.text,i.match(vM)?.[1]?.trim()??null);if(null===e)return[];t.push(e)}return t}function vQ(e){return vB(e).length>0}function vj(e){var t=e.replace(vI,"");if(t===e)return e;let i=vA.test(e)?t.replace(vE,""):t;return vP.test(e)&&(i=i.replace(vD,"")),i}function vF(e){return vj(vT(vL(e)).replace(vb,"")).trim().replace(/\s+/g," ")}function vO(e){let t=!1,i=null;for(let r=0;rg6(e)&&vR.test(e.text))}function vH(e){let t=null;for(let i=0;i0){t??=e.slice(0,i);let s=[...n],o=i+1;for(;o({type:"image-ref",path:e})),...vO(a.blocks)]}),i=o;continue}t.push({...r,blocks:n.map(e=>({type:"image-ref",path:e}))});continue}let s=vO(r.blocks);s===r.blocks?t?.push(r):(t??=e.slice(0,i)).push({...r,blocks:s})}return t??e}var vN=oa(os());function vz(e){let t=e?.replaceAll(/[^a-z0-9]/gi,"").toLowerCase();return"askuserquestion"===t||"requestuserinput"===t}var v$=new Map;function vq(e){return e?`question:${JSON.stringify(e.questions)}`:null}function vK(e){if(!e||"object"!=typeof e||!("questions"in e))return null;let t=e.questions;if(!Array.isArray(t)||0===t.length)return null;let i=[];for(let e of t){var r;if(!e||"object"!=typeof e)continue;let t="question"in e&&"string"==typeof e.question?e.question:"",n=Array.isArray(r="options"in e?e.options:void 0)?r.map(e=>"string"==typeof e?{label:e}:e&&"object"==typeof e&&"label"in e&&"string"==typeof e.label?{label:e.label,description:"description"in e&&"string"==typeof e.description?e.description:void 0}:null).filter(e=>null!==e):[];(t||n.length>0)&&i.push({question:t,header:"header"in e&&"string"==typeof e.header?e.header:void 0,multiSelect:"multiSelect"in e?!0===e.multiSelect:"multiple"in e&&!0===e.multiple,options:n})}return i.length>0?{questions:i}:null}for(let e of["AskUserQuestion","ask_user_question","askUserQuestion"])v$.set(e,vK);function vV(e,t){let i=e?v$.get(e):void 0;return(i?i(t):null)??vK(t)}function vU(e,t){if(!e)return null;try{return vV(t,JSON.parse(e))}catch{return null}}function vZ(e,t){return"string"==typeof t?vU(t,e):vV(e,t)}function vG(e,t){let i=(t?.indices??[]).map(t=>e.options[t]?.label??"").filter(e=>e.length>0),r=(t?.other??"").trim();return r?[...i,r]:i}function vY(e){return g4(e)&&"failed"!==e.state&&vz(e.name)}function vX(e){if(!e.some(vY))return{asks:[],unansweredAsks:[],work:e};let t=new Set,i=[],r=[];for(let{call:n,result:s}of bd(e))!n||!vY(n)||s?.isError||(i.push(n),s||r.push(n),t.add(n),s&&t.add(s));return{asks:i,unansweredAsks:r,work:t.size?e.filter(e=>!t.has(e)):e}}function vJ(e){if(!g4(e))return[];let t=vZ(e.name,e.input);return t?t.questions.map(e=>e.question.trim()).filter(e=>e.length>0):[]}var v0=new Set(["working","monitoring","waiting"]),v1=["agent","workflow","command","monitor","unknown"],v5={agent:"background agent",workflow:"background workflow",command:"background command",monitor:"background monitor",unknown:"background task"},v2={done:"finished",blocked:"failed",idle:"was stopped"};function v3(e){return e.map(e=>g6(e)?e.text:"").filter(e=>e.length>0).join(` -`)}var v6=new WeakMap;function v4(e){let t,i,r,n,s,o=v6.get(e);if(o)return o;let a=(i=b3((t=bg(e.filter(e=>!ba(e)))).prose),r=t.prose.filter(bt),n=function(e){let t=new Set,i=new Map,r=new Map,n=[];for(let[i,s]of(e.forEach((e,t)=>{if(bt(e)){let i=function(e){var t,i;let r=e.summary?.trim()||e.error?.trim();if(r)return r;let n=v5[t=e.kind,v1.find(e=>e===t)??"unknown"],s=e.label.trim()?`${n} "${e.label}"`:n;if(i=e.state,v0.has(i))return`Started ${s}`;let o=v2[e.state]??"stopped reporting";return`${s.charAt(0).toUpperCase()}${s.slice(1)} ${o}`}(e);n.push({index:t,sentence:i}),r.set(i,(r.get(i)??0)+1)}}),e.entries())){let e="text"===s.type?r.get(s.text)??0:0;"text"===s.type&&e>0&&(r.set(s.text,e-1),t.add(i))}for(let e of n){let t=r.get(e.sentence)??0;t>0&&(r.set(e.sentence,t-1),i.set(e.index,e.sentence))}return{twinTextIndexes:t,unpairedRows:i}}(t.prose),{prose:s=0===i.length&&0===r.length?t.prose:t.prose.filter((e,t)=>!g9(e)&&!bt(e)&&!n.twinTextIndexes.has(t)&&!b6(e,i.length>0)),tools:t.tools,subagentGroups:i,backgroundTasks:r,markdown:v3(s),hasImages:s.some(e=>"image-ref"===e.type)});return v6.set(e,a),a}function v7(e){let{markdown:t,hasImages:i,tools:r,subagentGroups:n,backgroundTasks:s}=v4(e);return t.length>0||i||r.length>0||n.length>0||s.length>0}var v8=/^[\s\S]{0,40}~orca-oversized~(?:[1-9]\d*)~[0-9a-f]{16}$/,v9=Symbol("parsedJournalItemKey");function ye(e,t){let i=t>>>0;for(let t=0;t>>0;return i>>>0}function yt(e){let t=String(e),i=function(e){if(e.length<=1024&&!function(e){for(let t=0;t=55296&&i<=56319){let i=t+157343)return!0;t+=1}else if(i>=56320&&i<=57343)return!0}return!1}(e))return e;let t=ye(e,0x811c9dc5).toString(16).padStart(8,"0"),i=ye(e,0x1000193).toString(16).padStart(8,"0");return`${function(e){let t="",i=0;for(;i=55296&&r<=56319){let r=i+1=56320&&r<=57343){if(i+1>=40)break;t+=e.charAt(i)+e.charAt(i+1),i+=2;continue}t+="�",i+=1;continue}t+=r>=56320&&r<=57343?"�":e.charAt(i),i+=1}return t}(e)}~orca-oversized~${e.length}~${t}${i}`}(t),r=encodeURIComponent(i);return t===i&&yi(t)?`%FF${r}`:r}function yi(e){return v8.test(e)}function yr(e){let t=e[v9];return void 0!==t?t:"codex"===e.provider?["codex",yt(e.threadId),yt(e.turnId),yt(e.ordinal)].join(":"):"claude"===e.provider?["claude",yt(e.sessionId),yt(e.uuid)].join(":"):"orca"===e.provider?["orca",yt(e.clientMessageId)].join(":"):["legacy",yt(e.agent),yt(e.sessionId),yt(e.recordId)].join(":")}function yn(e){return yr({provider:"orca",clientMessageId:e})}function ys(e){let t=[],i=!1;for(let r of e.split(":")){let e=function(e){let t=e.startsWith("%FF");try{let i=decodeURIComponent(t?e.slice(3):e);return!t||yi(i)?{value:i,tagged:t}:null}catch{return null}}(r);if(!e)return null;t.push(e.value),i||=e.tagged||yi(e.value)}let[r,...n]=t;if("codex"===r&&3===n.length){let t=Number(n[2]);return Number.isSafeInteger(t)&&t>=0?yo({provider:r,threadId:n[0],turnId:n[1],ordinal:t},e,i):null}return"claude"===r&&2===n.length?yo({provider:r,sessionId:n[0],uuid:n[1]},e,i):"orca"===r&&1===n.length?yo({provider:r,clientMessageId:n[0]},e,i):"legacy"===r&&3===n.length?yo({provider:r,agent:n[0],sessionId:n[1],recordId:n[2]},e,i):null}function yo(e,t,i){return i&&Object.defineProperty(e,v9,{value:t}),e}function ya(e){return{id:e.itemId,timestamp:e.observedAt,source:"transcript",journalPosition:yl(e)}}function yl(e){return{sequence:e.sequence,index:e.sequenceIndex??0}}function yc(e,t){return e.sequence-t.sequence||e.index-t.index}function yd(e,t){return e.sequence-t.sequence||(e.sequenceIndex??0)-(t.sequenceIndex??0)}function yu(e,t){let i=e.map(e=>{let{submittedSequence:i,submittedAt:r}=t(e);return{entry:e,submittedSequence:i,submittedAt:r}});return(i.every(e=>void 0!==e.submittedSequence)?[...i].sort((e,t)=>e.submittedSequence-t.submittedSequence):[...i].sort((e,t)=>e.submittedAt-t.submittedAt)).map(({entry:e})=>e)}function yh(e){return!0===e.handoverRecorded&&"pending"===e.dispatchState&&void 0===e.handedOverAt}var yf=["goal"],yp=["running","completed"],ym={kind:"thread"},yg=sF().finite().nonnegative(),yb=sF().finite().positive(),yv=sF().finite(),yy=sj().min(1).max(256),y_=sz({inputTokens:yg,cacheCreationInputTokens:yg,cacheReadInputTokens:yg,outputTokens:yg}),yw=sV("kind",[sz({kind:sY("report"),model:yy,usedTokens:yg,windowTokens:yb,percentage:sF().finite(),autoCompactAtTokens:yg.optional(),categories:sH(sz({name:sj().min(1).max(80),tokens:yg,deferred:sY(!0).optional()})).max(64),capturedAt:yv}),sz({kind:sY("estimate"),usage:y_,capturedAt:yv}),sz({kind:sY("unknown"),capturedAt:yv})]),yS=sz({window:sz({tokens:yb,capturedAt:yv}).optional(),used:yw.optional()});function yx(e){if(!e)return null;if("turn"===e.kind){let{kind:t,...i}=e;return i}return"status"===e.kind?e.turnLifecycle??null:null}function yT(e){let t=e?.outcome;return P.find(e=>e===t)??null}var yk=e=>"user"===e.role;function yC(e,t,i=yk){let r;return e.map(e=>{let n=t?.get(e.id);return void 0!==n?(r=n,n):(i(e)&&(r=e.id),r)})}function yL(e,t,i){let r=r=>e[r]?.role==="user"&&t[r]===e[r].id&&i.has(e[r].id),n=new Map;t.forEach((e,t)=>{void 0===e||n.has(e)||n.set(e,t)});let s=new Map,o=new Set;for(let[i,a]of e.entries()){if(!r(i))continue;let l=-1;for(let s=i+1;si)break;l=s}}-1!==l&&(o.add(i),s.set(l,[...s.get(l)??[],i]))}return 0===o.size?null:e.flatMap((e,t)=>[...o.has(t)?[]:[t],...s.get(t)??[]])}function yM(e,t){return null===t?e:t.map(t=>e[t])}function yR(e){if("object"!=typeof e||null===e||Array.isArray(e)||!("agent"in e)||!("problem"in e)||!("option"in e))return;let t=e.agent,i=e.problem,r=e.option;if(!("Codex"!==t&&"Claude"!==t||"unsupportedOption"!==i&&"missingValue"!==i&&"multipleValues"!==i&&"positionalPrompt"!==i||"string"!=typeof r||("positionalPrompt"===i?"prompt"!==r:!/^(?:--[a-zA-Z][a-zA-Z0-9-]{0,63}|-[a-zA-Z]|--\?)$/.test(r))))return{agent:t,option:r,problem:i}}var yI=["session","weekly","weeklyModel","credits"],yA=/^[A-Za-z][\w./-]{0,63}$/,yP={sameValueLeaves:!0,absentKeyEqualsUndefined:!0};function yE(e){if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function yD(e){let t;return null!==((t=e.trim().replace(/^v/i,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-.]+))?(?:\+([0-9A-Za-z-.]+))?$/))?{core:[Number(t[1]),Number(t[2]),Number(t[3])],prerelease:t[4]?.split(".")??[]}:null)}function yB(e){let t=e.def.discriminator;return new Set(e.options.flatMap(e=>{let i=e instanceof sN?e.shape[t]:void 0;return i instanceof sG?[...i.values].map(String):[]}))}function yQ(e){let t=e.def.discriminator,i=yB(e);return sK([e,sz({[t]:sj().regex(/\S/)}).refine(e=>!i.has(e[t]??""),{abort:!0})])}var yj=sz({objective:sj(),status:sj().min(1),tokenBudget:sF().finite().nullable(),tokensUsed:sF().finite(),timeUsedSeconds:sF().finite(),createdAt:sF().finite(),updatedAt:sF().finite()}),yF=yQ(sV("state",[sz({state:sY("set"),goal:yj}),sz({state:sY("cleared")})])),yO=sz({kind:sj().min(1),detail:sz({text:sj(),audience:sj().min(1)}).optional(),refusal:sz({code:sj().min(1),details:sq({}).optional()}).optional(),argumentProblem:sz({agent:sj(),option:sj(),problem:sj()}).optional(),requestTimeout:sq({}).optional()}),yW=sz({head:sj(),byteLength:sF(),digest:sj(),truncated:sO()}),yH=sz({provider:sj(),kind:sj(),payload:yW}),yN={mcpIdentity:sz({server:sj(),tool:sj()}).optional(),exitCode:sF().int().optional(),durationMs:sF().nonnegative().optional(),webSearchResults:sH(sz({title:sj(),url:sj()})).optional()},yz=sj().refine(e=>e.trim().length>0,"callId must contain a non-whitespace character"),y$=sz({id:sj(),label:sj(),state:sj().min(1),tokens:sF().optional(),startedAt:sF().optional(),settledAt:sF().optional()}),yq=yQ(sV("type",[sz({type:sY("text"),text:sj(),presentation:sj().optional(),tone:sj().optional(),providerFrame:yH.optional()}),sz({type:sY("tool-call"),name:sj(),input:sW().optional(),callId:yz.optional(),...yN}),sz({type:sY("tool-result"),output:sj(),isError:sO().optional()}),sz({type:sY("image-ref"),path:sj().optional(),url:sj().optional(),alt:sj().optional()}),sz({type:sY("subagent-group"),groupId:sj(),agents:sH(y$)}),y$.extend({type:sY("subagent"),groupId:sj(),parentId:sj().optional(),run:sj().optional(),outcomeBasis:sj().optional(),background:sO().optional()}),sz({type:sY("background-task"),taskId:sj().min(1),kind:sj().min(1),label:sj(),state:sj().min(1),parentToolUseId:sj().optional(),summary:sj().optional(),error:sj().optional(),outputFile:sj().optional(),tokens:sF().optional(),startedAt:sF().optional(),settledAt:sF().optional()})])),yK=sz({id:sj(),label:sj(),description:sj().optional()}),yV=sz({allowEmpty:sO().optional(),multiline:sO().optional(),initialValue:sj().optional(),placeholder:sj().optional()}),yU=sz({id:sj(),question:sj(),header:sj().optional(),multiSelect:sO(),options:sH(yK),freeTextQuestionId:sj().optional(),freeTextInput:yV.optional()}),yZ=sz({state:sj().min(1),selectedOptionId:sj().nullable(),answers:sH(sz({questionId:sj(),optionIds:sH(sj()),other:sj().optional()})).optional(),resolvedBy:sj().nullable(),resolvedAt:sF().nullable()}),yG=sz({source:sj(),toolName:sj(),ruleContent:sj().optional()}),yY=sV("kind",[sz({kind:sY("plan"),text:sj().min(1),filePath:sj().optional()})]),yX=(yB(yY),yQ(yY)),yJ=sz({kind:sY("message"),role:sj().min(1),blocks:sH(yq),sentAs:sj().min(1).optional(),command:sz({name:sj().min(1)}).optional(),state:sj().min(1).optional(),completedAt:sF().finite().optional()}),y0={turnId:sj(),state:sj().min(1),outcome:sj().min(1).optional(),userItemId:sj().min(1).optional(),startedAt:sF().finite().positive().optional(),requestedAt:sF().finite().positive().optional(),completedAt:sF().finite().positive().optional(),durationMs:sF().finite().nonnegative().optional()},y1=sV("kind",[yJ,sz({kind:sY("tool-call"),...yN,name:sj(),input:sW().optional(),callId:yz.optional(),state:sj().min(1),endedAs:sj().min(1).optional(),output:yW.optional()}),sz({kind:sY("diff"),path:sj(),patch:yW}),sz({kind:sY("approval"),title:sj(),displayName:sj().optional(),description:sj().optional(),decisionReason:sj().optional(),blockedPath:sj().optional(),matchedAskRule:yG.optional(),subject:yX.optional(),detail:sj().nullable(),options:sH(yK),resolution:yZ}),sz({kind:sY("question"),question:sj(),options:sH(yK),questions:sH(yU).optional(),freeTextQuestionId:sj().optional(),freeTextInput:yV.optional(),resolution:yZ}),sz({kind:sY("status"),text:sj(),presentation:sj().optional(),contextClear:sz({operationId:sj().min(1).max(512),afterFence:sF().int().nonnegative(),clearedAt:sF().int().nonnegative()}).optional(),tone:sj().optional(),turnLifecycle:sz(y0).optional(),providerFrame:yH.optional(),threadGoal:yF.optional(),failure:yO.optional(),orcaStop:sz({cause:sj().min(1)}).optional()}),sz({kind:sY("turn"),...y0,contextUsage:yS.optional(),providerTurnId:sj().min(1).optional()})]),y5=(yB(y1),yQ(y1)),y2={agentId:sj().min(1).optional(),parentAgentId:sj().min(1).optional(),providerParentRef:sj().min(1).optional(),producerKind:sj().min(1).optional(),attempt:sF().int().optional()},y3=sz({kind:sj().min(1),turnItemId:sj().min(1).optional()}),y6=sz({itemId:sj().min(1),revision:sF().int(),body:y5,sequence:sF().int(),sequenceIndex:sF().int().nonnegative().optional(),observedAt:sF(),recovered:sY(!0).optional(),recoveredAt:sF().optional(),turnScope:y3.optional(),...y2});function y4(e){return y6.safeParse(e).success}var y7=["unsupported","history-not-paginated","busy","stale-epoch","invalid-target","history-limit","provider-refused","proof-mismatch","outcome-unknown"],y8=sj().min(1).max(4096);sz({operationId:y8,callerKey:y8,itemId:y8,providerItemId:y8.optional(),expectedEpoch:y8,contextClearOperationId:y8.optional(),contextClearSequence:sF().int().positive().optional(),phase:sZ(["prepared","provider-succeeded","completed","refused"]),epoch:y8.optional(),sequence:sF().int().nonnegative().optional(),hydrationVerified:sO().optional(),reason:sj().min(1).max(512).optional(),retained:sH(sz({itemId:y8.refine(e=>null!==ys(e)),body:y5,observedAt:sF().finite(),turnScope:y3.optional(),ownerFence:sF().int().nonnegative().optional(),executionOwner:sF().int().nonnegative().optional(),...y2})).max(1e4).optional()});var y9={agent_session_operation_invalid:["requestMalformed","operationIdInvalid","messageIdReused","operationRefusedEarlier","journalWriteFailed","stopFailed","cancelNotSaved","attachmentExpired","conversationCleared","clearUnconfirmed","conversationCommandUnconfirmed","conversationCommandInFlight","handoffInFlight","turnActive","continuationSuperseded","promptPending","backgroundTasksRunning","messagesUnsettled","queueTooLarge","rewindRefused","rewindUnconfirmed","promptGone","promptOwnerEnded","optionRejected","providerStarting","goalsUnsupported","providerRejected","providerStartFailed","notSignedIn","cliMissing","historyTooLarge","managedAccountEnvOverride","accountSwitchInProgress","managedAccountUnsupported","launchFolderMissing","historyInOtherAccount","claudeAccountFolderMissing","claudeAccountSetupFailed","agentCommandNotRunnable","runtimeNotInstalled","attachFailed"],agent_session_ownership_unknown:["sessionNotAttached","noLiveOwner","ownerUnproven","claimConflicted","recordMissing","replaySuperseded","leaseMoved","spawnIdentityMismatch","notResumable","noProviderChild","conversationHeldElsewhere","previousExitUnverifiable"],agent_session_conflict:["chatStarting","ownerUnproven","claimConflicted","ownerAlive","identityMismatch","sessionExists","conversationHeldElsewhere","tabIdTaken"],execution_owner_reconciling:["hostReconciling","recordUnreadable"],agent_session_checkpoint_stale:["fenceStale","leaseMoved","recordMissing"],agent_session_identity_required:["recordMissing","transcriptNotFound","transcriptUnreadable"],agent_session_operation_conflict:["fingerprintMismatch","operationIdReused","handoffInFlight"],agent_session_operation_expired:["operationExpired"],agent_session_operation_capacity:["operationCapacity"],agent_session_operation_unknown:["outcomeUnknown","resultLost","rewindUnconfirmed","tabUnconfirmed"],agent_session_item_revision_stale:["promptMoved"],agent_session_already_resolved:["promptAlreadyResolved"],agent_session_journal_unreadable:["journalCorrupt","journalUnavailable","journalWrittenByNewerOrca"],structured_agent_session_unsupported:["clientCapabilityMissing","hostDisabled","hostUnsupported"],agent_session_owner_restart_failed:[]},_e={agent_session_operation_invalid:["rewindReason"],agent_session_operation_unknown:["rewindReason"],agent_session_checkpoint_stale:["currentFence"],agent_session_item_revision_stale:["currentRevision","resolution"],agent_session_already_resolved:["currentRevision","resolution"]},_t=["live","unverifiable","exited"];function _i(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _r(e,t){var i,r;let n;if(!_i(t))return;let s=[..._e[e]??[],"ownerVerdict"].reduce((e,i)=>({...e,...function(e,t){switch(e){case"currentFence":return Number.isSafeInteger(t)&&"number"==typeof t?{currentFence:t}:{};case"currentRevision":return Number.isSafeInteger(t)&&"number"==typeof t?{currentRevision:t}:{};case"resolution":return yZ.safeParse(t).success?{resolution:t}:{};case"ownerVerdict":{let e=_t.find(e=>e===t);return e?{ownerVerdict:e}:{}}case"rewindReason":{let e=y7.find(e=>e===t);return e?{rewindReason:e}:{}}}}(i,t[i])}),{}),o="agent_session_operation_invalid"===e?yR(t.argumentProblem):void 0,a="agent_session_operation_invalid"===e?function(e){if(!("object"!=typeof e||null===e||!("installedVersion"in e)||!("minimumVersion"in e)||null!==e.installedVersion&&("string"!=typeof e.installedVersion||!yD(e.installedVersion))||"string"!=typeof e.minimumVersion||!yD(e.minimumVersion)))return{installedVersion:e.installedVersion,minimumVersion:e.minimumVersion}}(t.codexInstallation):void 0,l=("agent_session_conflict"===e||"agent_session_ownership_unknown"===e)&&"conversationHeldElsewhere"===t.reason&&_i(t.owner)&&"string"==typeof t.owner.sessionId&&t.owner.sessionId.trim().length>0&&"string"==typeof t.owner.workspaceId&&t.owner.workspaceId.trim().length>0?{sessionId:t.owner.sessionId,workspaceId:t.owner.workspaceId}:void 0,c={...(i=t.reason,n=y9[e],"string"==typeof i&&n.includes(i))?{reason:t.reason}:{},...s,...l?{owner:l}:{},..."agent_session_operation_invalid"===e&&"notSignedIn"===t.reason&&("managed"===t.account||"system"===t.account)?{account:t.account}:{},...o?{argumentProblem:o}:{},..."agent_session_operation_invalid"===e&&"stopFailed"===t.reason&&"string"==typeof(r=t.agent)&&Object.hasOwn(re,r)?{agent:t.agent}:{},...a?{codexInstallation:a}:{}};return Object.keys(c).length>0?c:void 0}var _n=["structured_agent_session_unsupported","agent_session_checkpoint_stale","agent_session_conflict","agent_session_ownership_unknown","agent_session_operation_conflict","agent_session_operation_expired","agent_session_operation_capacity","agent_session_operation_invalid","agent_session_operation_unknown","agent_session_item_revision_stale","agent_session_already_resolved","agent_session_identity_required","agent_session_journal_unreadable","execution_owner_reconciling","agent_session_owner_restart_failed"];function _s(e){return"string"==typeof e&&_n.includes(e)}function _o(e){if(!("object"!=typeof e||null===e||!("code"in e)||!_s(e.code))){var t;return{code:e.code,...(t="details"in e?_r(e.code,e.details):void 0)?{details:t}:{}}}}var _a=["providerStartFailed","startFailed","notSignedIn","cliMissing","historyTooLarge","managedAccountEnvOverride","accountSwitchInProgress","managedAccountUnsupported","launchFolderMissing","historyInOtherAccount","claudeAccountFolderMissing","claudeAccountSetupFailed","agentCommandNotRunnable","runtimeNotInstalled","providerExited","restartFailed","providerRejected","attachmentInvalid","attachmentUnreadable","emptyMessage","commandUnavailable","queueFull","writeFailed","cancelled","chatClosed","hostRestarted","notDelivered","commandRefused","compactionFailed","compactionUnconfirmed","cancelUnconfirmed","stopRefused","stopFailed","backgroundTaskNotStopped","answerUnconfirmed","hostFault","hostStopped","providerRetrying","usageLimitReached","previousExitUnverifiable","sessionNotRestored"];function _l(e){return"string"==typeof e&&_a.some(t=>t===e)}var _c=["compactionFailed","compactionUnconfirmed","cancelUnconfirmed","stopRefused","stopFailed","backgroundTaskNotStopped","answerUnconfirmed","providerRetrying","usageLimitReached","previousExitUnverifiable","sessionNotRestored"];function _d(e){return _l(e)&&!_c.some(t=>t===e)}var _u=["empty","tooLarge","tooMany","totalTooLarge","unsupportedType","notAFile","noSource"];function _h(e,t){let i=e.trim().slice(0,512).trim();return i?{text:i,audience:t}:void 0}function _f(e,t={}){let i=t.detail?_h(t.detail.text,t.detail.audience):void 0;return{kind:e,...t.account?{account:t.account}:{},...i?{detail:i}:{},...t.refusal?{refusal:t.refusal}:{},...t.attachment?{attachment:t.attachment}:{},...t.retry?{retry:t.retry}:{},...t.usageLimit?{usageLimit:t.usageLimit}:{},...t.argumentProblem?{argumentProblem:t.argumentProblem}:{},...t.neverReachedAgent?{neverReachedAgent:!0}:{},...t.backgroundStop?{backgroundStop:t.backgroundStop}:{},...t.requestTimeout?{requestTimeout:t.requestTimeout}:{}}}function _p(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _m(e){return"number"==typeof e&&Number.isInteger(e)&&e>0?e:void 0}function _g(e){var t;if(!_p(e)||!_l(e.kind))return;let i=_o(e.refusal),r=function(e){if(!_p(e))return;let t=_u.find(t=>t===e.reason);if(!t)return;let i=e.limit;return"number"==typeof i&&Number.isFinite(i)&&i>0?{reason:t,limit:i}:{reason:t}}(e.attachment),n=function(e){if(!_p(e))return;let t="string"==typeof e.error&&e.error.trim()?e.error.trim():void 0,i=_m(e.status),r="string"==typeof e.cause?_h(e.cause,"person")?.text:void 0,n=_m(e.attempt),s=_m(e.maxRetries),o=n&&s&&s>=n?s:void 0;return t||i||r||n?{...t?{error:t}:{},...i?{status:i}:{},...r?{cause:r}:{},...n?{attempt:n}:{},...o?{maxRetries:o}:{}}:void 0}(e.retry),s=function(e){if("object"!=typeof e||null===e||Array.isArray(e))return;let t={...e},i=yI.find(e=>e===t.window),r="number"==typeof t.resetsAt&&Number.isFinite(t.resetsAt)&&t.resetsAt>0?t.resetsAt:void 0;return i||r?{...i?{window:i}:{},...r?{resetsAt:r}:{}}:void 0}(e.usageLimit),o=yR(e.argumentProblem),a=function(e){if("object"!=typeof e||null===e||Array.isArray(e))return;let{method:t,timeoutMs:i}={...e};return"string"==typeof t&&yA.test(t)&&"number"==typeof i&&Number.isInteger(i)&&i>0?{method:t,timeoutMs:i}:void 0}(e.requestTimeout);return _f(e.kind,{..."managed"===e.account||"system"===e.account?{account:e.account}:{},..._p(t=e.detail)&&"string"==typeof t.text&&("person"===t.audience||"log"===t.audience)?{detail:e.detail}:{},...i?{refusal:i}:{},...r?{attachment:r}:{},...n?{retry:n}:{},...s?{usageLimit:s}:{},...o?{argumentProblem:o}:{},...!0===e.neverReachedAgent?{neverReachedAgent:!0}:{},..."task"===e.backgroundStop||"all"===e.backgroundStop?{backgroundStop:e.backgroundStop}:{},...a?{requestTimeout:a}:{}})}function _b(e){let t=_g(e);return t&&function e(t,i,r){if(r.sameValueLeaves?Object.is(t,i):t===i)return!0;if(Array.isArray(t)||Array.isArray(i))return Array.isArray(t)&&Array.isArray(i)&&t.length===i.length&&t.every((t,n)=>e(t,i[n],r));if(!yE(t)||!yE(i))return!1;if(r.absentKeyEqualsUndefined){for(let n of new Set([...Object.keys(t),...Object.keys(i)]))if(!e(t[n],i[n],r))return!1;return!0}let n=Object.keys(t);return n.length===Object.keys(i).length&&n.every(n=>Object.hasOwn(i,n)&&e(t[n],i[n],r))}(t,e,yP)?t:void 0}var _v="provider_write_failed",_y="claude structured dispatch queue is full",__="codex structured dispatch queue is full",_w="provider_cancelled_before_start",_S={cancelled:"withdrawn",hostRestarted:"undelivered",chatClosed:"undelivered",notDelivered:"undelivered",providerExited:"undelivered",hostStopped:"undelivered",providerStartFailed:"startFailed",startFailed:"startFailed",notSignedIn:"startFailed",cliMissing:"startFailed",historyTooLarge:"startFailed",managedAccountEnvOverride:"startFailed",accountSwitchInProgress:"startFailed",managedAccountUnsupported:"startFailed",launchFolderMissing:"startFailed",historyInOtherAccount:"startFailed",claudeAccountFolderMissing:"startFailed",claudeAccountSetupFailed:"startFailed",agentCommandNotRunnable:"startFailed",runtimeNotInstalled:"startFailed",restartFailed:"startFailed",providerRejected:"content",attachmentInvalid:"content",attachmentUnreadable:"content",emptyMessage:"content",commandUnavailable:"content",commandRefused:"content",queueFull:"transport",writeFailed:"transport",hostFault:"transport"},_x={cancelled:null,hostRestarted:null,chatClosed:null,notDelivered:null,providerExited:"failure",providerStartFailed:"failure",startFailed:"failure",notSignedIn:"failure",cliMissing:"failure",historyTooLarge:"failure",managedAccountEnvOverride:"failure",accountSwitchInProgress:"failure",managedAccountUnsupported:"failure",launchFolderMissing:"failure",historyInOtherAccount:"failure",claudeAccountFolderMissing:"failure",claudeAccountSetupFailed:"failure",agentCommandNotRunnable:"failure",runtimeNotInstalled:"failure",restartFailed:"failure",providerRejected:"failure",attachmentInvalid:"failure",attachmentUnreadable:"failure",emptyMessage:"failure",commandUnavailable:"failure",commandRefused:"failure",queueFull:"failure",writeFailed:"failure",hostFault:"failure",hostStopped:"failure"},_T=new Map([[_w,"cancelled"],["host_restarted_before_delivery","hostRestarted"],["provider_closed_before_delivery","chatClosed"],[_y,"queueFull"],[__,"queueFull"],["not_delivered","notDelivered"]]);function _k(e){var t,i;let{rejection:r}=e,n=_g(r)?.kind;if("object"==typeof r&&null!==r&&!_d(n))return{category:"undelivered",verdict:null};let s=_d(n)?n:(i=t=e.reason)===_v||i?.startsWith(`${_v}: `)===!0?"writeFailed":null===t?void 0:_T.get(t);return s?{category:_S[s],verdict:_x[s],kind:s}:{category:"content",verdict:"failure"}}function _C(e){return e?.dispatchState==="rejected"&&"withdrawn"===_k(e).category}function _L(e){return"object"==typeof e&&null!==e&&"operationId"in e&&"string"==typeof e.operationId&&e.operationId.length>0&&e.operationId.length<=512&&"afterFence"in e&&"number"==typeof e.afterFence&&Number.isSafeInteger(e.afterFence)&&e.afterFence>=0&&"clearedAt"in e&&"number"==typeof e.clearedAt&&Number.isSafeInteger(e.clearedAt)&&e.clearedAt>=0}function _M(e){return e?.kind==="status"&&_L(e.contextClear)}function _R(e){let t=0;for(let i of e)i.sequence>t&&_M(i.body)&&(t=i.sequence);return t}function _I(e,t){return t&&!e.some(e=>_M(e.body))}function _A(e){return void 0===e.latestTurn?function(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(_M(i?.body))break;let r=yx(i?.body);if(r)return"running"===r.state?r.turnId:null}return null}(e.items):e.latestTurn?.turn.state==="running"?e.latestTurn.turn.turnId:null}function _P(e){let t;return void 0===e.latestTurn?(t=function(e){let t=null;for(let i of e)(null===t||i.sequence>=t.sequence)&&(yx(i.body)||_M(i.body))&&(t=i);let i=t?yx(t.body):null;return t&&i?.state==="running"?{item:t,turnId:i.turnId}:null}(e.items))?{kind:"turn",turnItemId:t.item.itemId}:ym:e.latestTurn?.turn.state==="running"?{kind:"turn",turnItemId:e.latestTurn.itemId}:ym}function _E(e,t){return void 0===t||t.includes(e)}function _D(e,t){let i=new Set(t.flatMap(e=>"pending"===e.dispatchState&&void 0!==e.handedOverAt?[yn(e.clientMessageId)]:[]));if(0===i.size)return null;let r={handover:null,handoverAt:-1,settledAt:-1};return(t=>{for(let i of e)t(i)})(e=>{i.has(e.itemId)&&e.turnScope?.kind==="thread"&&e.sequence>r.handoverAt&&(r.handover=e.itemId,r.handoverAt=e.sequence),yx(e.body)&&bU(e)&&(r.settledAt=Math.max(r.settledAt,e.sequence))}),r.handoverAt>r.settledAt?r.handover:null}function _B(e,t,i){let r=_D(i.items,i.submissions),n=null===r?-1:e.findIndex(e=>e.id===r);return -1===n?void 0:t[n]}function _Q(e,t,i){let r,n=e.filter(e=>"tool"===e.role&&void 0!==e.journalPosition&&!i.has(e.id));if(0===n.length)return i;let s=new Set,o=new Map;for(let e of t){s.add(e.itemId);let{sequence:t,index:i}=yl(e),r=`${t}:${i}`;o.set(r,o.has(r)?null:e.itemId)}for(let e of n){let t=e.journalPosition;if(!t||s.has(e.id))continue;let n=o.get(`${t.sequence}:${t.index}`),a=n?i.get(n):void 0;void 0!==a&&(r??=new Map(i)).set(e.id,a)}return r??i}function _j(e){return e.some(e=>void 0!==e.turnScope)}function _F(e,t=[],i){let r=new Set(e.flatMap(e=>"message"===e.body.kind&&"user"===e.body.role?[e.itemId]:[])),n=new Map(e.flatMap(e=>e.turnScope?.kind==="turn"&&r.has(e.itemId)?[[e.itemId,e.turnScope.turnItemId]]:[])),s=new Map;for(let e of t)e.providerItemId&&!s.has(e.providerItemId)&&s.set(e.providerItemId,yn(e.clientMessageId));let o=new Set(t.filter(e=>"pending"===e.dispatchState&&!e.providerItemId&&!yh(e)).map(e=>yn(e.clientMessageId))),a=t.filter(e=>!e.providerItemId&&void 0===e.queuedMessageId&&null!==e.resolvedAt&&_C(e)),l=a.length>0?new Map(e.map(e=>[e.itemId,e])):void 0,c=_O(a),d=yu(a.filter(e=>void 0===e.answeredInTurn).flatMap(e=>{let t=l?.get(yn(e.clientMessageId));return t?[{sent:t,submission:e}]:[]}),({submission:e})=>e),u=new Set,h=new Map,f=null,p=null;for(let t of e){if(r.has(t.itemId)){f=t.itemId,null===p&&o.has(t.itemId)&&(p=t.itemId);continue}let e=yx(t.body);if(!e||!bU(t))continue;let i=_W(t.itemId,e,r,s,n,f,p),a=e.userItemId;if(void 0!==a&&!r.has(a)&&!r.has(s.get(a)??"")&&a!==t.itemId){let r=c.get(t.itemId);if(void 0!==r&&l?.has(r))i=r;else if(i===t.itemId){let r=d.find(({sent:i,submission:r})=>!u.has(i.itemId)&&(void 0!==r.submittedSequence?r.submittedSequencee[i]?.unsent===!0?void 0:t)}function _N(e,t){let i=e.findLastIndex(e=>"user"===e.role&&!0!==e.unsent);return -1===i?void 0:t[i]}var _z="stopped-before-start";function _$(e){return"text"===e.type&&e.presentation===_z}function _q(e,t){let i=yl(e),r=yl(t);return yc(i,r)>0?{sequence:r.sequence,index:r.index-.5}:i}function _K(e){let t=[],i=new Map,r=[];for(let n of e){if("reasoning"===n.role){r.push(n);continue}let{tools:e}=v4(n.blocks);0!==e.length&&(r.length>0&&(i.set(e[0],r),r=[]),t.push(...e))}return{blocks:t,thoughtsBefore:i,thoughtsAfter:r}}function _V(e){let t=new Map;for(let i of e)for(let e of i.blocks)t.has(e)||t.set(e,i.id);return t}function _U(e,t){let i=new Set,r=new Set;for(let n of e.blocks){let e=t.get(n);g9(n)?i.add(`subagent-group:${n.groupId}`):void 0!==e&&g7(n)?r.add(`result:${e}`):void 0!==e&&i.add(`body:${e}`)}let n=[...i,...r],s=i.size>0?[...i]:r.size>0?[...r]:[`body:${e.id}`];return{identity:s,content:n.length>0?n:s}}function _Z(e,t,i){let r=_V(t);return e.map(e=>{let t=_U(e,r);if(!i)return t;let n=t=>`${t}\0${i(e)??""}`;return{identity:t.identity.map(n),content:t.content.map(n)}})}function _G(e,t,i,r,n,s){let o=new Map,a=new Set,l=(e,t)=>{o.set(e.id,t),a.add(t)},c=new Set(t.map(e=>e.id)),d=[],u,h=()=>u??=s?.()??_Z(t,i,n);if(r&&h(),!r&&e?.rows.every(e=>c.has(e.id)))for(let i of t){let t=e.keyById.get(i.id);void 0!==t&&l(i,t)}else if(e){d=e.sources??e.prepareSources?.()??_Z(e.rows,e.messages),h();let i=new Map;d.forEach(({identity:e},t)=>e.forEach(e=>i.set(e,t)));let r=h().map(({identity:e})=>new Set(e.flatMap(e=>i.get(e)??[]))),n=new Map;r.forEach(e=>e.forEach(e=>n.set(e,(n.get(e)??0)+1))),r.forEach((i,r)=>{let[s]=i,o=void 0!==s&&1===i.size&&1===n.get(s)?e.keyById.get(e.rows[s].id):void 0;void 0!==o&&l(t[r],o)})}for(let e of t.filter(e=>!o.has(e.id))){let t=r?.()??e.id;for(let i=1;a.has(t);i+=1)t=`${e.id}~${i}`;l(e,t)}let f=new Map;u?.forEach(({identity:e,content:t},i)=>{e[0].startsWith("result:")||t.forEach(e=>{f.has(e)||f.set(e,i)})});let p=new Map;return d.forEach(({content:i},r)=>{let n=e?.keyById.get(e.rows[r].id);if(void 0!==n&&!a.has(n)){let e=t[Math.min(...i.map(e=>f.get(e)??1/0))];p.set(n,e&&o.get(e.id))}}),{keyById:o,moved:p,...u?{sources:u}:{}}}var _Y=oa(os());function _X(e){return Number.isNaN(e)?1:Math.min(1.8,Math.max(.8,e))}var _J=oa(os()),_0=oa(oe());function _1(){return"web"!==_0.Platform.OS}var _5={minIndexForVisible:1},_2={minIndexForVisible:0};function _3(e){return 80>=function(e){let{contentOffset:t,contentSize:i,layoutMeasurement:r}=e;return i.height-(t.y+r.height)}(e)}var _6=oa(os());function _4(e){return`reasoning:${e}`}var _7={reasoning:"Reasoning",thought:"Thought",thoughtFor:e=>`Thought for ${e}`};function _8(e){return"thoughtFor"===e.kind?_7.thoughtFor(e.duration):_7[e.kind]}var _9=oa(os()),we="compaction-skipped",wt=["update","quit","crash"],wi="orca-stop";function wr(e){let t=v4(e.blocks);return t.markdown.length>0||t.hasImages}var wn={foldedRows:new Set,foldableTurnKeys:new Set},ws=new Map,wo={heads:new Map,joined:new Set},wa=oa(os()),wl=Object.freeze({}),wc=new Set,wd=[];function wu(e){let[t,i]=(0,_6.useState)(()=>({scopeKey:e,keys:new Set})),r=(0,_6.useCallback)(t=>{i(i=>{let r=new Set(i.scopeKey===e?i.keys:[]);if(!r.delete(t)){if(r.size>=128){let e=r.values().next().value;e&&r.delete(e)}r.add(t)}return{scopeKey:e,keys:r}})},[e]);return[t.scopeKey===e?t.keys:wc,r]}var wh=oa(os()),wf=oa(os()),wp=oa(oe()),wm=oa(oe()),wg=oa(oo());function wb({size:e,color:t}){let i=tY(),r=j(!1===i);return i?(0,wg.jsx)(nX,{size:e,color:t,strokeWidth:2}):(0,wg.jsx)(wm.Animated.View,{style:{transform:[{rotate:r}]},children:(0,wg.jsx)(r1,{size:e,color:t,strokeWidth:2})})}var wv=oa(os()),wy=oa(oe()),w_="chat-row:",ww="chat-member:";function wS(e){return`${w_}${e}`}function wx(e){return`${ww}${e}`}function wT(e,t){return Array.from(e.querySelectorAll(`[data-testid^="${t}"]`),e=>({id:e.getAttribute("data-testid")?.slice(t.length)??"",node:e}))}var wk=class extends wv.Component{getSnapshotBeforeUpdate(e){let t=e.layoutKey!==this.props.layoutKey,i=new Set(Array.from(e.runPlacements??[]).flatMap(([e,t])=>this.props.runPlacements?.get(e)!==t?[e]:[]));if("web"===wy.Platform.OS&&e.rowKeys.scope===this.props.rowKeys.scope&&this.props.roots?.capture(i,t),"web"!==wy.Platform.OS||e.rowKeys.scope!==this.props.rowKeys.scope||e.rowKeys.sourceHead===this.props.rowKeys.sourceHead&&!t&&0===i.size||this.props.isFollowing())return null;let r=this.props.listRef.current,n=r?.getScrollableNode(),s=n&&!function({scrollTop:e,scrollHeight:t,clientHeight:i}){return e<0||e>t-i+1}(n)?function(e,{placement:t}){let i=e.getBoundingClientRect(),r=wT(e,w_),n=0,s=r.length;for(;n({key:e,top:i.getBoundingClientRect().top,placed:t(e)});return r.slice(n,o).flatMap(e=>(function(e,t,i){let r=[];for(let{id:n,node:s}of"u">typeof Element&&e instanceof Element?bR(e).map(e=>({node:e,id:void 0!==bL(e)?`root:${bL(e)}`:e.getAttribute("data-testid")?.slice(ww.length)??""})):wT(e,ww)){let e=s.getBoundingClientRect();if(e.top>=t.bottom)break;("run"===n?e.top>=t.top:e.bottom>t.top&&e.top"run"!==e.member);return n.length>0?n:[r[0]??i]})(e.node,i,a(e))).concat([r[o],r[n-1]].flatMap(e=>e?[a(e)]:[]))}(n,e.rowKeys):null;return s&&(b_()||t||function(e,t,i,r){if(!e)return!1;if(void 0===e.member)return t.placement(e.key)!==e.placed;if(e.member.startsWith("root:")){let t=r?.owner(e.member.slice(5)),n=void 0===t?void 0:i?.get(t);return void 0!==n&&n!==e.placed}return e.member.startsWith("result:")||"run"!==e.member&&t.current(e.key)!==e.key}(s[0],this.props.rowKeys,this.props.runPlacements,this.props.roots))?(r?.holdPlace?.(!0),s):null}componentDidMount(){this.props.roots?.restoreAll()}componentDidUpdate(e,t,i){try{let t=e.layoutKey!==this.props.layoutKey;this.props.roots?.restoreAll(t,!1),i&&this.restore(i,t)}finally{this.props.roots?.releaseHold(),i&&this.props.listRef.current?.holdPlace?.(!1)}}restore(e,t){let i=this.props.listRef.current,r=e.length?i?.getScrollableNode():null;if(!r)return;let n=new Map(wT(r,w_).map(({id:e,node:t})=>[e,t]));for(let s of e){let e=function(e,t,i,r){let{key:n,member:s}=e;if(s?.startsWith("root:"))return r?.frame(s.slice(5));if(void 0===s)return i.placement(n)===e.placed?t.get(n):void 0;let o=t.get("run"===s?n:i.current(n)??""),a=s.startsWith("result:")?`call:${s.slice(7)}`:s;return o&&wT(o,ww).find(e=>e.id===s||e.id===a)?.node}(s,n,this.props.rowKeys,this.props.roots);if(e){let n=e.getBoundingClientRect().top-s.top;Math.abs(n)>=.5&&i?.keepInPlace?i.keepInPlace(n,t):Math.abs(n)>=.5&&(r.scrollTop+=n);return}}}render(){return this.props.children??null}},wC=oa(os()),wL=oa(oe()),wM=oa(os()),wR=oa(oe()),wI=oa(oo()),wA=(0,wM.createContext)(null);function wP({positionKey:e,rootIdentity:t=e,owner:i,initialFollow:r=!1,followKey:n,ref:s,children:o,...a}){let l=(0,wM.useContext)(bE),c=(0,wM.useContext)(wA),d=c?`${c.id}/${t}`:t,u=c?`${c.address}/${e}`:e,h=i??c?.owner??d,f=(0,wM.useMemo)(()=>({id:d,address:u,owner:h}),[d,u,h]),p=l?.roots,m=(0,wM.useRef)(null),g=(0,wM.useRef)(void 0),b=(0,wM.useCallback)(e=>{if(m.current=e,"function"==typeof s)return s(e);s&&(s.current=e)},[s]);return(0,wM.useLayoutEffect)(()=>()=>{g.current?.(),g.current=void 0},[p,d]),(0,wM.useLayoutEffect)(()=>{if("web"!==wR.Platform.OS||!p)return;let e=m.current?.getScrollableNode();"u">typeof HTMLElement&&e instanceof HTMLElement&&null!==e.firstElementChild&&(g.current=p.register(d,e,e.firstElementChild,h,u,r),p.layout(d,u,n))}),(0,wI.jsx)(wR.ScrollView,{...a,ref:b,children:(0,wI.jsx)(wA.Provider,{value:f,children:o})})}var wE=oa(oe()),wD=oa(oo());function wB({testID:e,onLongPress:t,style:i,children:r}){return t?(0,wD.jsx)(wE.Pressable,{testID:e,onLongPress:t,accessible:!1,style:i,children:r}):(0,wD.jsx)(wE.View,{testID:e,style:i,children:r})}var wQ=oa(oe());function wj(e,t,i=6){return{fontSize:e*t,lineHeight:(e+i)*t}}var wF=wQ.StyleSheet.create({row:{paddingHorizontal:s6.lg,paddingVertical:s6.sm},rowUser:{alignItems:"flex-end"},content:{maxWidth:"100%",gap:s6.sm},userBubble:{maxWidth:"88%",backgroundColor:s2.textPrimary,borderRadius:s4.card,paddingHorizontal:s6.md,paddingVertical:s6.sm},hostNotice:{color:s2.textMuted},reasoning:{opacity:.7,paddingLeft:15+s6.sm},reasoningToggle:{flexDirection:"row",alignItems:"center",gap:s6.sm,minHeight:32},reasoningPressed:{opacity:.6},reasoningHeadline:{color:s2.textMuted,fontSize:s7.bodySize,flexShrink:1},reasoningCaretOpen:{transform:[{rotate:"90deg"}]},reasoningBody:{maxHeight:240},agentMessage:{paddingLeft:s6.md,borderLeftWidth:2,borderLeftColor:s2.borderSubtle},agentAttribution:{color:s2.textMuted,fontSize:s7.metaSize},meta:{flexDirection:"row",alignItems:"center",gap:s6.xs},unsentNotice:{maxWidth:"88%",marginTop:s6.xs,color:s2.statusRed,fontSize:s7.metaSize},imageRef:{color:s2.textSecondary,fontSize:17},imageThumb:{width:200,height:150,borderRadius:s4.card,backgroundColor:s2.bgRaised,borderWidth:wQ.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle}}),wO=oa(oo());function wW({message:e,markdown:t,fontScale:i,live:r=!1,expanded:n=!1,onToggle:s,onOpenFile:o,onLongPress:a}){let[l,c]=(0,wC.useState)(!1),d=s?n:l,u=_8(function(e,{live:t}){return void 0===e.state||t&&"completed"!==e.state?{kind:"reasoning"}:"completed"!==e.state||void 0===e.completedAt||null===e.timestamp?{kind:"thought"}:{kind:"thoughtFor",duration:G(Math.max(1,(e.completedAt-e.timestamp)/1e3))}}(e,{live:r})),h=_8({kind:"reasoning"});return(0,wO.jsxs)(wL.View,{testID:wx(`thought:${e.id}`),children:[(0,wO.jsxs)(wL.Pressable,{style:({pressed:e})=>[wF.reasoningToggle,e&&wF.reasoningPressed],onPress:()=>s?s(_4(e.id)):c(!d),hitSlop:6,accessibilityRole:"button",accessibilityState:{expanded:d},accessibilityLabel:u===h?h:`${h}: ${u}`,children:[(0,wO.jsx)(n5,{size:15,color:s2.textMuted,strokeWidth:2}),(0,wO.jsx)(wL.Text,{style:wF.reasoningHeadline,numberOfLines:1,children:u}),(0,wO.jsx)(wL.View,{style:d?wF.reasoningCaretOpen:void 0,children:(0,wO.jsx)(rj,{size:14,color:s2.textMuted,strokeWidth:2})})]}),d?(0,wO.jsx)(wH,{positionKey:_4(e.id),markdown:t,fontScale:i,onOpenFile:o,onLongPress:a}):null]})}function wH({positionKey:e,markdown:t,fontScale:i,onOpenFile:r,onLongPress:n}){return(0,wO.jsx)(wP,{positionKey:e,style:wF.reasoningBody,nestedScrollEnabled:!0,children:(0,wO.jsx)(wB,{onLongPress:n,style:wF.reasoning,children:(0,wO.jsx)(tZ,{content:t,rangeSelectable:!0,textScale:1.25*i,onOpenFile:r,onLongPress:n})})})}var wN=(0,oa(os()).createContext)({openImage:()=>{},openActions:()=>{}}),wz=oa(oo());function w$({line:e,onToggleReasoning:t,fontScale:i,onOpenFile:r}){let{reasoning:n,reasoningExpanded:s}=e,o=null!==n&&s,a=X(e),{openActions:l}=(0,wf.useContext)(wN);return(0,wz.jsxs)(wp.View,{children:[(0,wz.jsxs)(wp.Pressable,{style:({pressed:e})=>[wq.row,n&&e&&wq.pressed],onPress:n?()=>t(_4(n.message.id)):void 0,hitSlop:6,accessibilityRole:n?"button":void 0,accessibilityState:n?{expanded:o}:void 0,accessibilityLabel:a,accessibilityLiveRegion:"polite",children:[(0,wz.jsx)(wp.View,{style:wq.glyph,children:(0,wz.jsx)(wb,{size:15,color:s2.textMuted})}),(0,wz.jsx)(wp.Text,{style:wq.label,numberOfLines:1,children:a}),n?(0,wz.jsx)(wp.View,{style:o?wq.caretOpen:void 0,children:(0,wz.jsx)(rj,{size:14,color:s2.textMuted,strokeWidth:2})}):null]}),n&&o?(0,wz.jsx)(wp.View,{style:wq.body,children:(0,wz.jsx)(wH,{positionKey:_4(n.message.id),markdown:n.markdown,fontScale:i,onOpenFile:r,onLongPress:tK?void 0:()=>l(n.message)})}):null]})}var wq=wp.StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:s6.sm,minHeight:32,paddingHorizontal:s6.lg},glyph:{width:15,alignItems:"center",overflow:"visible"},pressed:{opacity:.6},label:{color:s2.textMuted,fontSize:s7.bodySize,flexShrink:1},caretOpen:{transform:[{rotate:"90deg"}]},body:{paddingHorizontal:s6.lg}}),wK=oa(oe()),wV=oa(oo());function wU({toolCallCount:e,toolsExpanded:t,onToggleTools:i,showJumpToTail:r,onJumpToTail:n}){return(0,wV.jsxs)(wK.View,{pointerEvents:"box-none",style:bW.floatingControls,children:[e>0?(0,wV.jsxs)(wK.Pressable,{accessibilityRole:"button",accessibilityLabel:t?"Collapse tool runs":"Expand tool runs",accessibilityState:{expanded:t},style:({pressed:e})=>[bW.toolsPill,e&&bW.pressed],onPress:i,children:[t?(0,wV.jsx)(rq,{size:14,color:s2.textSecondary,strokeWidth:2}):(0,wV.jsx)(rZ,{size:14,color:s2.textSecondary,strokeWidth:2}),(0,wV.jsx)(wK.Text,{style:bW.toolsPillLabel,children:t?"Collapse":`Tools \xb7 ${e}`})]}):null,r?(0,wV.jsx)(wK.Pressable,{accessibilityLabel:"Scroll to latest",style:bW.fab,onPress:n,children:(0,wV.jsx)(nF,{size:18,color:s2.textPrimary,strokeWidth:2.2})}):null]})}var wZ=oa(os()),wG=oa(oe()),wY=oa(oe()),wX=oa(oo());function wJ(e){return"capability"===e.kind?("open"===e.mode?"/ruflo/":"@ruflo/")+e.capability.id:"file"===e.kind?`@${e.path}`:e.token}var w0={command:"Commands",skill:"Skills",file:"Files",capability:"RuFlo capabilities"};function w1({rows:e,onPick:t}){return(0,wX.jsx)(wY.View,{testID:"rupro-chat-suggestion-card",style:w2.card,children:(0,wX.jsx)(wY.ScrollView,{testID:"rupro-chat-suggestions",keyboardShouldPersistTaps:"always",style:w2.scroll,children:e.map((i,r)=>(0,wX.jsxs)(wY.View,{children:[e[r-1]?.kind!==i.kind?(0,wX.jsx)(wY.Text,{style:w2.heading,children:w0[i.kind]}):null,(0,wX.jsx)(w5,{row:i,onPick:t})]},i.id))})})}function w5({row:e,onPick:t}){let i="capability"===e.kind?st:"skill"===e.kind?nc:"command"===e.kind?rF:nk,r="file"===e.kind?null:"capability"===e.kind?e.capability.description:e.description;return(0,wX.jsxs)(wY.Pressable,{accessibilityRole:"button",accessibilityLabel:wJ(e),style:({pressed:e})=>[w2.row,e&&w2.rowPressed],onPress:()=>t(e),children:[(0,wX.jsx)(i,{size:16,color:s2.textSecondary,strokeWidth:2,style:w2.icon}),(0,wX.jsxs)(wY.View,{style:w2.body,children:[(0,wX.jsxs)(wY.View,{style:w2.nameLine,children:[(0,wX.jsx)(wY.Text,{style:w2.name,numberOfLines:1,children:"file"===e.kind?e.path:"capability"===e.kind?e.capability.title:e.token}),"command"===e.kind&&e.argumentHint?(0,wX.jsx)(wY.Text,{style:w2.hint,numberOfLines:1,children:e.argumentHint}):null]}),"capability"===e.kind&&(0,wX.jsxs)(wY.Text,{style:w2.hint,numberOfLines:1,children:[wJ(e)," · ","mention"===e.mode?"Insert reference":e.capability.section?"Open in console":"View reference"]}),r?(0,wX.jsx)(wY.Text,{style:w2.description,numberOfLines:2,children:r}):null]})]})}var w2=wY.StyleSheet.create({card:{marginHorizontal:10,marginBottom:s6.sm,paddingVertical:6,borderRadius:20,borderWidth:wY.StyleSheet.hairlineWidth,borderColor:s2.composerBorder,backgroundColor:s2.bgPanel,overflow:"hidden"},scroll:{maxHeight:300},heading:{color:s2.textMuted,fontSize:11,fontWeight:"600",letterSpacing:.5,textTransform:"uppercase",paddingHorizontal:s6.lg,paddingTop:s6.sm,paddingBottom:s6.xs},row:{flexDirection:"row",gap:10,paddingHorizontal:s6.lg,paddingVertical:s6.sm,minHeight:44},rowPressed:{backgroundColor:s2.bgRaised},icon:{marginTop:2},body:{flex:1,minWidth:0,gap:2},nameLine:{flexDirection:"row",alignItems:"baseline",gap:6},name:{flexShrink:1,color:s2.textPrimary,fontFamily:s7.monoFamily,fontSize:13.5},hint:{flexShrink:1,color:s2.textMuted,fontFamily:s7.monoFamily,fontSize:s7.metaSize},description:{color:s2.textMuted,fontSize:12.5,lineHeight:17}}),w3=oa(os()),w6=oa(oe()),w4=oa(oe()),w7={minHeight:40,color:s2.textPrimary,backgroundColor:s2.bgRaised,borderRadius:s4.input,paddingHorizontal:s6.md,paddingTop:s6.sm,paddingBottom:s6.sm},w8={input:{width:"100%",minHeight:30,maxHeight:154,lineHeight:22,color:s2.textPrimary,paddingHorizontal:6,paddingTop:2,paddingBottom:2},freeInput:{...w7,flex:1,maxHeight:120}},w9=w4.StyleSheet.create({input:{...w8.input,fontSize:iC},freeInput:{...w8.freeInput,fontSize:iC}}),Se=oa(oe()).StyleSheet.create({token:{color:s2.skillToken,backgroundColor:s2.skillTokenSurface}}),St=oa(oo()),Si={field:{color:"transparent",caretColor:s2.textPrimary}};function Sr({value:e,skillToken:t,onSendKey:i,onKeyPress:r,ref:n,...s}){let[o,a]=(0,w3.useState)(0);return(0,St.jsxs)(w6.View,{style:Sn.frame,children:[t?(0,St.jsx)(w6.View,{pointerEvents:"none",style:Sn.copyLayer,children:(0,St.jsxs)(w6.Text,{"aria-hidden":!0,style:[w9.input,Sn.copy,{transform:[{translateY:-o}]}],children:[(0,St.jsx)(w6.Text,{style:Se.token,children:t}),e.slice(t.length)]})}):null,(0,St.jsx)(w6.TextInput,{ref:n,value:e,style:t?[w9.input,Si.field]:w9.input,onScroll:t?e=>{let t;return a("object"==typeof(t="object"==typeof e&&null!==e&&"currentTarget"in e?e.currentTarget:null)&&null!==t&&"scrollTop"in t&&"number"==typeof t.scrollTop?t.scrollTop:0)}:void 0,...s,onKeyPress:e=>{r?.(e);let t=e.nativeEvent;!i||e.defaultPrevented||"Enter"!==t.key||t.shiftKey||t.altKey||t.ctrlKey||t.metaKey||t.isComposing||229===t.keyCode||(e.preventDefault(),t.repeat||i())}})]})}var Sn=w6.StyleSheet.create({frame:{width:"100%",overflow:"hidden"},copyLayer:{...w6.StyleSheet.absoluteFillObject},copy:{maxHeight:void 0}}),Ss=oa(oe()),So=oa(oo());function Sa({images:e,files:t,onRemoveImage:i,onRemoveFile:r}){return 0===e.length&&0===t.length?null:(0,So.jsxs)(Ss.ScrollView,{horizontal:!0,keyboardShouldPersistTaps:"always",showsHorizontalScrollIndicator:!1,style:Sc.strip,contentContainerStyle:Sc.stripContent,children:[e.map(e=>(0,So.jsxs)(Ss.View,{style:Sc.thumb,children:[(0,So.jsx)(Ss.Image,{source:{uri:e.previewUri},style:Sc.thumbImage,resizeMode:"cover"}),i?(0,So.jsx)(Sl,{label:"Remove image",onPress:()=>i(e.id)}):null]},e.id)),t.map(e=>{let t,i;return(0,So.jsxs)(Ss.View,{style:Sc.fileCard,children:[(0,So.jsx)(Ss.View,{style:Sc.fileIcon,children:(0,So.jsx)(nk,{size:17,color:s2.textSecondary,strokeWidth:2})}),(0,So.jsxs)(Ss.View,{style:Sc.fileText,children:[(0,So.jsx)(Ss.Text,{style:Sc.fileName,numberOfLines:1,children:e.name}),(0,So.jsx)(Ss.Text,{style:Sc.fileMeta,numberOfLines:1,children:(t=/\.([a-z0-9]{1,8})$/i.exec(e.name)?.[1],i=/^[^/]+\/([a-z0-9]{1,8})$/i.exec(e.mime)?.[1],`${(t??i??"File").toUpperCase()} \xb7 ${l(e.byteLength)}`)})]}),null===e.path?(0,So.jsx)(Ss.View,{style:Sc.uploading,accessibilityLabel:`Uploading ${e.name}`,children:(0,So.jsx)(Ss.ActivityIndicator,{size:"small",color:s2.textPrimary})}):null,r?(0,So.jsx)(Sl,{label:`Remove ${e.name}`,onPress:()=>r(e.id)}):null]},e.id)})]})}function Sl({label:e,onPress:t}){return(0,So.jsx)(Ss.Pressable,{accessibilityLabel:e,style:Sc.remove,onPress:t,hitSlop:8,children:(0,So.jsx)(r7,{size:11,color:s2.textPrimary,strokeWidth:3})})}var Sc=Ss.StyleSheet.create({strip:{flexGrow:0,marginBottom:10},stripContent:{gap:s6.sm,paddingTop:5,paddingLeft:2,paddingRight:5},thumb:{width:58,height:58,borderRadius:s4.composerItem,backgroundColor:s2.composerControl},thumbImage:{width:"100%",height:"100%",borderRadius:s4.composerItem},fileCard:{height:58,minWidth:140,maxWidth:220,flexDirection:"row",alignItems:"center",gap:9,paddingLeft:10,paddingRight:s6.md,borderRadius:s4.composerItem,backgroundColor:s2.composerControl},fileIcon:{width:32,height:36,borderRadius:7,alignItems:"center",justifyContent:"center",backgroundColor:s2.bgRaised},fileText:{flexShrink:1,minWidth:0},fileName:{color:s2.textPrimary,fontSize:13,fontWeight:"500"},fileMeta:{color:s2.textMuted,fontSize:11.5,marginTop:1},uploading:{...Ss.StyleSheet.absoluteFillObject,borderRadius:s4.composerItem,alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0, 0, 0, 0.45)"},remove:{position:"absolute",top:-5,right:-5,width:20,height:20,borderRadius:10,alignItems:"center",justifyContent:"center",backgroundColor:s2.bgRaised,borderWidth:2,borderColor:s2.composerSurface}}),Sd=oa(oe());function Su(e){return"dispatched"===e.valueSource&&"catalog"===e.transport}function Sh(e){if("unknown"===e.valueSource||"select"!==e.kind.type||!e.kind.currentValue)return null;let t=e.kind.currentValue;return(e.kind.choices.find(e=>e.value===t)??{value:t,label:t}).label}var Sf=oa(oe()),Sp=oa(oo());function Sm({children:e}){return(0,Sp.jsx)(Sf.Text,{style:SS.caption,children:e})}function Sg({primary:e,secondary:t,warning:i,accessibleName:r,disabled:n,onPress:s}){return(0,Sp.jsxs)(Sf.Pressable,{accessibilityLabel:r,accessibilityRole:"button",accessibilityState:{disabled:n},style:({pressed:e})=>[SS.pill,e&&!n&&SS.pressed],onPress:s,disabled:n,hitSlop:6,children:[i?(0,Sp.jsx)(n$,{size:15,color:s2.statusAmber,strokeWidth:2.2}):null,(0,Sp.jsxs)(Sf.Text,{style:SS.pillText,numberOfLines:1,ellipsizeMode:"tail",children:[(0,Sp.jsx)(Sf.Text,{style:[SS.pillPrimary,n&&SS.pillTextDisabled],children:e}),t?(0,Sp.jsx)(Sf.Text,{style:SS.pillSecondary,children:` ${t}`}):null]})]})}function Sb({label:e,description:t,selected:i,disabled:r,grouped:n,divided:s,onPress:o,labelColor:a}){return(0,Sp.jsxs)(Sf.Pressable,{accessibilityRole:"radio",accessibilityState:{checked:i,disabled:r},style:[SS.row,i&&SS.rowSelected,n&&SS.rowGrouped,s&&SS.rowDivided,r&&SS.rowDisabled],onPress:o,disabled:r,children:[(0,Sp.jsxs)(Sf.View,{style:SS.rowBody,children:[(0,Sp.jsx)(Sf.Text,{style:[SS.rowLabel,a?{color:a}:null],children:e}),t?(0,Sp.jsx)(Sf.Text,{style:SS.rowDescription,numberOfLines:2,children:t}):null]}),i?(0,Sp.jsx)(si,{size:18,color:s2.textPrimary,strokeWidth:2.4}):null]})}function Sv({label:e,checked:t,marker:i,disabled:r,grouped:n,onToggle:s}){return(0,Sp.jsxs)(Sf.View,{style:[SS.row,n&&SS.rowGrouped,r&&SS.rowDisabled],children:[(0,Sp.jsx)(Sf.View,{style:SS.rowBody,children:(0,Sp.jsx)(Sf.Text,{style:SS.rowLabel,children:e})}),i?(0,Sp.jsx)(Sf.Text,{style:SS.rowMarker,children:"default"===i?"Default":"Not reported"}):null,(0,Sp.jsx)(Sf.Switch,{accessibilityLabel:e,value:t,onValueChange:s,disabled:r,trackColor:{false:s2.bgRaised,true:s2.textSecondary},thumbColor:s2.textPrimary})]})}function Sy({label:e,disabled:t,grouped:i,onPress:r}){return(0,Sp.jsx)(Sf.Pressable,{accessibilityRole:"button",accessibilityState:{disabled:t},style:[SS.row,i&&SS.rowGrouped,t&&SS.rowDisabled],onPress:r,disabled:t,children:(0,Sp.jsx)(Sf.View,{style:SS.rowBody,children:(0,Sp.jsx)(Sf.Text,{style:SS.rowLabel,children:e})})})}function S_({label:e,value:t,valueColor:i,disabled:r,divided:n,onPress:s}){return s?(0,Sp.jsxs)(Sf.Pressable,{accessibilityLabel:`${e}, ${t}`,accessibilityRole:"button",accessibilityState:{disabled:r},style:({pressed:e})=>[SS.summaryRow,n&&SS.rowDivided,e&&!r&&SS.pressed,r&&SS.rowDisabled],onPress:s,disabled:r,children:[(0,Sp.jsx)(Sf.Text,{style:SS.summaryLabel,children:e}),(0,Sp.jsx)(Sf.Text,{style:[SS.summaryValue,i?{color:i}:null],numberOfLines:1,children:t}),(0,Sp.jsx)(rj,{size:16,color:s2.textMuted,strokeWidth:2.2})]}):(0,Sp.jsxs)(Sf.View,{accessible:!0,accessibilityLabel:`${e}, ${t}`,style:[SS.summaryRow,n&&SS.rowDivided],children:[(0,Sp.jsx)(Sf.Text,{style:SS.summaryLabel,children:e}),(0,Sp.jsx)(Sf.Text,{style:SS.summaryValue,numberOfLines:1,children:t})]})}function Sw({descriptor:e,disabled:t,grouped:i=!1,onSetOption:r,onInvokeAction:n,choiceLabelColor:s}){let o=t||!e.settable;if(e.action?.type==="toggle-command")return(0,Sp.jsx)(Sy,{label:`Toggle ${e.label.toLowerCase()}`,disabled:o,grouped:i,onPress:n});if(e.action?.type==="agent-picker")return(0,Sp.jsx)(Sy,{label:"Choose in agent picker…",disabled:o,grouped:i,onPress:n});if("boolean"===e.kind.type)return(0,Sp.jsx)(Sv,{label:e.label,checked:e.kind.currentValue,marker:"default"===e.valueSource?"default":"unknown"===e.valueSource?"unreported":null,disabled:o,grouped:i,onToggle:e=>r(e)});let{currentValue:a,choices:l}=e.kind;return(0,Sp.jsx)(Sp.Fragment,{children:l.map((e,t)=>(0,Sp.jsx)(Sb,{label:e.label,description:e.description,selected:e.value===a,disabled:o,grouped:i,divided:i&&tr(e.value),labelColor:s?.(e.value)},e.value))})}var SS=Sf.StyleSheet.create({pill:{flexDirection:"row",alignItems:"center",gap:6,height:38,paddingHorizontal:14,borderRadius:19,backgroundColor:s2.composerControl},pillText:{flexShrink:1,fontSize:s7.bodySize},pillPrimary:{color:s2.textPrimary,fontWeight:"500"},pillSecondary:{color:s2.textMuted},pillTextDisabled:{color:s2.textMuted},pressed:{opacity:.7},caption:{color:s2.textMuted,fontSize:s7.metaSize,paddingHorizontal:s6.md,paddingBottom:s6.xs},rowMarker:{color:s2.textMuted,fontSize:s7.metaSize},row:{flexDirection:"row",gap:s6.sm,paddingHorizontal:14,paddingVertical:s6.sm,minHeight:50,alignItems:"center",borderRadius:s4.card,backgroundColor:s2.bgRaised,borderWidth:1,borderColor:s2.borderSubtle,marginBottom:s6.xs},rowSelected:{borderColor:s2.textSecondary},rowGrouped:{marginBottom:0,borderWidth:0,borderRadius:0,backgroundColor:"transparent"},rowDivided:{borderBottomWidth:Sf.StyleSheet.hairlineWidth,borderBottomColor:s2.composerBorder},rowDisabled:{opacity:.5},rowBody:{flex:1,gap:2},rowLabel:{color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"},rowDescription:{color:s2.textSecondary,fontSize:s7.metaSize},summaryRow:{minHeight:50,flexDirection:"row",alignItems:"center",gap:s6.sm,paddingHorizontal:14,paddingVertical:s6.sm},summaryLabel:{flex:1,color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"},summaryValue:{maxWidth:160,color:s2.textSecondary,fontSize:s7.bodySize}}),Sx=oa(oe()),ST=oa(oo());function Sk(e){return"thought_level"===e.category&&"select"===e.kind.type&&!e.action&&e.kind.choices.length>1&&e.kind.choices.length<=5}function SC({descriptor:e,disabled:t,onSetOption:i}){if("select"!==e.kind.type)return null;let{choices:r,currentValue:n}=e.kind;return(0,ST.jsxs)(Sx.View,{style:SL.block,children:[(0,ST.jsx)(Sx.Text,{style:SL.label,children:e.label}),(0,ST.jsx)(Q,{segments:r,selected:"unknown"===e.valueSource?void 0:n,onSelect:i,fill:!0,disabled:t||!e.settable}),Su(e)?(0,ST.jsx)(Sm,{children:"Sent to the agent — not confirmed"}):null]})}var SL=Sx.StyleSheet.create({block:{marginTop:s6.md},label:{color:s2.textMuted,fontSize:s7.metaSize,paddingHorizontal:s6.xs,paddingBottom:6}}),SM="permissionMode",SR={modes:["ask","full-access"]},SI=new Map([["claude",{modes:["ask","accept-edits","auto","full-access"],autoNeedsModelSupport:!0}],["codex",{modes:["ask","auto","full-access"]}],["grok",SR],["opencode",SR],["opencode2",SR],["omp",SR],["antigravity",{modes:["ask","accept-edits","full-access"]}]]);function SA(e){return SI.get(e)??null}function SP(e){return{agent:e,valuesByModel:{}}}function SE(e){return e?.kind==="toggle-command"}function SD(e,t,i){return t?e.valuesByModel[t]?.[i]:void 0}function SB(e,t,i){if(!t)return;let r=e.valuesByModel[t];if(!r||!(i in r))return;let n={...r};delete n[i],0===Object.keys(n).length?delete e.valuesByModel[t]:e.valuesByModel[t]=n}function SQ(e){let t="string"==typeof e.model?.value?e.model.value:null;e.model=void 0,t&&delete e.valuesByModel[t]}function Sj(e,t,i,r,n=null){if("model"===t)return e.model={value:i,source:r},"string"==typeof i?i:null;let s=("string"==typeof e.model?.value?e.model.value:null)??n;return s?(e.valuesByModel[s]={...e.valuesByModel[s],[t]:{value:i,source:r}},s):null}function SF(e,t,i){let r=e=>void 0===i||i.includes(e)?"reported":"dispatched",n="string"==typeof t.model?t.model:null;if(!n)return!1;let s=e.model?.value!==n,o=s||e.model?.source!==r("model");e.model={value:n,source:r("model")};let a=s?{}:{...e.valuesByModel[n]};for(let[e,i]of Object.entries(t)){if("model"===e)continue;let t=a[e];(t?.value!==i||t.source!==r(e))&&(o=!0),a[e]={value:i,source:r(e)}}return e.valuesByModel[n]=a,o}function SO(e,t){let i=t.trim().toLowerCase();if(!i)return null;if(0===e.models.length)return t.trim();let r=e.models.find(e=>e.id.toLowerCase()===i);if(r)return r.id;let n=e.models.find(e=>e.label.toLowerCase()===i);if(n)return n.id;let s=null;for(let t of e.models)(null===s||t.id.length>s.length)&&i.includes(t.id.toLowerCase())&&(s=t.id);return s}function SW(e){if("draft"===e.mode)return e.apply.launchArgs||e.apply.composedIntoModel?{settable:!0}:{settable:!1,disabledReason:"available-after-session-start"};if("agent-session"===e.liveTransport||e.apply.composedIntoModel&&e.composedModelApply?.midSession?.kind==="command")return{settable:!0};let t=e.apply.midSession;return t&&"unsupported"!==t.kind?{settable:!0}:{settable:!1,disabledReason:"set-when-session-starts"}}function SH(e,t,i,r){if("live"===i&&"agent-session"!==r)return e.midSession?.kind==="agent-picker"?{type:"agent-picker"}:SE(e.midSession)&&!t?{type:"toggle-command"}:void 0}var SN={thought_level:0,model_config:1,mode:2};function Sz(e,t,i){let r="string"==typeof i.model?.value?i.model.value:null;return!r||t.some(e=>e.id===r)?[...t]:[...t,e.models.find(e=>e.id===r)??{id:r,label:r,options:[]}]}function S$(e,t,i){return i||!e.defaultModelIsCliDefault?null:t.find(e=>e.isDefault)?.id??null}function Sq(e,t,i){let r="string"==typeof i.model?.value?i.model.value:null;return r??S$(e,t,r)}function SK(e){let{catalog:t,models:i,record:r,mode:n,modelLabel:s,liveTransport:o}=e;if(0===i.length)return[];let a=r.model,l=i.map(({id:e,label:t,description:i})=>({value:e,label:t,...i?{description:i}:{}})),c="string"==typeof a?.value?a.value:null,d=S$(t,i,c),u=c??d,h=SH(t.modelApply,a,n,o),f=[{id:"model",label:s,category:"model",kind:{type:"select",...u?{currentValue:u}:{},choices:l},valueSource:a?.source??(d?"default":"unknown"),transport:o,...SW({mode:n,liveTransport:o,apply:t.modelApply}),...h?{action:h}:{}}];if(!u)return f;let p=i.find(e=>e.id===u),m=r.valuesByModel[u]??{};for(let e of p?.options??[]){let i=function(e){let{option:t,tracked:i,mode:r,liveTransport:n,modelIsCliDefault:s,composedModelApply:o}=e,a=SH(t.apply,i,r,n),l=SW({mode:r,liveTransport:n,apply:t.apply,composedModelApply:o}),c=s&&"select"===t.kind.type&&!0===t.kind.defaultIsCliDefault,d=!i&&(c||"draft"===r&&!s),u=i?.source??(d?"default":"unknown");if("select"===t.kind.type){let e,r,s=(e=[...t.kind.choices],(r="string"==typeof i?.value?i.value:null)&&!e.some(e=>e.value===r)&&e.push({value:r,label:r}),e);if(s.length<=1)return null;let o="string"==typeof i?.value?i.value:d?t.kind.defaultValue:void 0;return{id:t.id,label:t.label,...t.description?{description:t.description}:{},...t.category?{category:t.category}:{},kind:{type:"select",...void 0===o?{}:{currentValue:o},choices:s},valueSource:u,transport:n,...l,...a?{action:a}:{}}}let h="boolean"==typeof i?.value?i.value:t.kind.defaultValue;return{id:t.id,label:t.label,...t.description?{description:t.description}:{},...t.category?{category:t.category}:{},kind:{type:"boolean",currentValue:h},valueSource:u,transport:n,...l,...a?{action:a}:{}}}({option:e,tracked:m[e.id],mode:n,liveTransport:o,modelIsCliDefault:u===d,composedModelApply:t.modelApply});i&&f.push(i)}return f}var SV=oa(oo());function SU(e){return"full-access"===e?s2.statusAmber:void 0}function SZ({controller:e,isWorking:t,sendInFlight:i=!1,presentation:r,onNavigate:n,onDrawerOpen:s,onDrawerAfterClose:o}){let{snapshot:a,pendingId:l}=e,c=a.find(e=>"model"===e.category),d=a.find(e=>e.id===SM),u=a.filter(e=>"model"!==e.category&&e.id!==SM).sort((e,t)=>(SN[e.category??""]??3)-(SN[t.category??""]??3));if(!c&&!d)return null;let h=c??d,f=a.find(e=>e.id===r?.page),p=void 0!==f&&f===d,m=void 0!==f&&f===h,g=null!==l||i,b=t||g,v=function(e){switch(e){case"set-when-session-starts":return"Set when the session starts.";case"available-after-session-start":return"Available after the session starts.";case void 0:return null}}(f?.disabledReason),y=d?.kind.type==="select"?d.kind.choices.find(e=>e.value===d.kind.currentValue):void 0,_=SU(y?.value),w=void 0!==_,S=u.filter(Sk),x=u.filter(e=>!S.includes(e)),T=c?Sh(c)??"Model":y?.label??"Permissions",k=c&&u.length>0?function(e){let t=[];for(let i of e)if("unknown"!==i.valueSource&&("serviceTier"!==i.id||"select"!==i.kind.type||"default"!==i.kind.currentValue))if("select"===i.kind.type){let e=Sh(i);e&&t.push(e)}else!0===i.kind.currentValue&&t.push("fastMode"===i.id?"Fast":i.label);if(t.length>0)return t.join(" · ");let i=e.find(e=>"effort"===e.id);return i?i.label:"Options"}(u):null,C=()=>n(null),L=(t,i)=>{"unknown"!==t.valueSource&&"select"===t.kind.type&&t.kind.currentValue===i||(t===d&&n(t===h?null:h.id),e.setOption(t.id,i).then(e=>{e&&t!==h&&t!==d&&n(h.id)}))};return(0,SV.jsxs)(Sd.View,{style:SY.pillSlot,children:[(0,SV.jsx)(Sg,{primary:T,secondary:k,warning:w,accessibleName:c?`Model, ${k?`${T} ${k}`:T}${w?", full access":""}`:`Permissions, ${T}`,disabled:g,onPress:()=>{s(h.id),Sd.Keyboard.dismiss()}}),(0,SV.jsx)(iD,{visible:void 0!==f,onClose:C,onAfterClose:o,children:f?(0,SV.jsxs)(Sd.View,{style:SY.sheet,children:[(0,SV.jsxs)(Sd.View,{style:SY.sheetHeader,children:[(0,SV.jsx)(Sd.Pressable,{accessibilityLabel:m?"Close picker":"Back to models",accessibilityRole:"button",style:({pressed:e})=>[SY.sheetNav,e&&SY.pressed],onPress:m?C:()=>n(h.id),hitSlop:8,children:m?(0,SV.jsx)(r7,{size:18,color:s2.textSecondary,strokeWidth:2.2}):(0,SV.jsx)(rO,{size:18,color:s2.textSecondary,strokeWidth:2.2})}),(0,SV.jsx)(Sd.Text,{style:SY.sheetTitle,children:f.label}),(0,SV.jsx)(Sd.View,{style:SY.sheetHeaderSide,children:null!==l?(0,SV.jsx)(Sd.ActivityIndicator,{size:"small",color:s2.textSecondary}):null})]}),Su(f)?(0,SV.jsx)(Sm,{children:"Sent to the agent — not confirmed"}):null,v?(0,SV.jsx)(Sm,{children:v}):null,(0,SV.jsx)(Sd.View,{style:SY.group,children:(0,SV.jsx)(Sw,{descriptor:f,disabled:p?g:b,grouped:!0,onSetOption:e=>L(f,e),onInvokeAction:()=>{e.invokeAction(f.id).then(e=>{e&&C()})},...p?{choiceLabelColor:SU}:{}})}),m&&c?(0,SV.jsxs)(SV.Fragment,{children:[S.map(e=>(0,SV.jsx)(SC,{descriptor:e,disabled:b,onSetOption:t=>L(e,t)},e.id)),(0,SV.jsx)(SG,{descriptors:[...x,...d?[d]:[]],permission:d,permissionColor:_,locked:b,busy:g,onNavigate:n,onSetOption:L})]}):null]}):null})]})}function SG({descriptors:e,permission:t,permissionColor:i,locked:r,busy:n,onNavigate:s,onSetOption:o}){return 0===e.length?null:(0,SV.jsx)(Sd.View,{style:[SY.group,SY.groupSpaced],children:e.map((a,l)=>{let c=a===t,d=c?n:r;if("boolean"===a.kind.type&&!a.action)return(0,SV.jsx)(Sd.View,{style:lo(a,e),onInvokeAction:()=>s(a.id)})},a.id);let u="boolean"===a.kind.type?a.kind.currentValue?"On":"Off":"unknown"===a.valueSource?"Not set":Sh(a)??"Not set";return(0,SV.jsx)(S_,{label:c?"Permissions":a.label,value:u,valueColor:c?i:void 0,disabled:d,divided:ls(a.id):void 0},a.id)})})}var SY=Sd.StyleSheet.create({pillSlot:{flexShrink:1,minWidth:0},sheet:{paddingBottom:s6.xs},sheetHeader:{flexDirection:"row",alignItems:"center",paddingBottom:s6.lg},sheetTitle:{flex:1,color:s2.textPrimary,fontSize:s7.titleSize,fontWeight:"700",textAlign:"center"},sheetNav:{width:36,height:36,borderRadius:18,alignItems:"center",justifyContent:"center",backgroundColor:s2.bgRaised,borderWidth:Sd.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle},sheetHeaderSide:{width:36,height:36,alignItems:"center",justifyContent:"center"},group:{overflow:"hidden",borderRadius:s4.card,backgroundColor:s2.bgRaised},groupSpaced:{marginTop:s6.md},divided:{borderBottomWidth:Sd.StyleSheet.hairlineWidth,borderBottomColor:s2.composerBorder},pressed:{opacity:.7}}),SX=oa(os()),SJ=oa(oe()),S0=/[^\s]/;function S1(e,t,i=8){let r=t.toLowerCase();if(0===r.length)return e.slice(0,i);let n=[],s=[];for(let t of e){let e=t.toLowerCase(),o=e.slice(e.lastIndexOf("/")+1);if(e.startsWith(r)||o.startsWith(r)?n.push(t):s.length=i)break}return[...n,...s].slice(0,i)}function S5(e){let t=e.codePointAt(0)??0;return!(t<=31||t>=127&&t<=159||8203===t||8206===t||8207===t||1564===t||8288===t||65279===t||8232===t||8233===t||t>=8234&&t<=8238||t>=8294&&t<=8297)}function S2(e,t){return(ol??=new Intl.Collator(void 0,{sensitivity:"base"})).compare(e,t)}var S3={repo:0,home:1,bundled:2,plugin:3};function S6(e,t,i){let r=[...t].sort(S9);return{kind:"skill",id:`skill:${e}`,name:e,token:`${i}${e}`,description:r[0]?.description?S8(r[0].description,240):null,sources:r.map(e=>({sourceKind:e.sourceKind,skillFilePath:e.skillFilePath}))}}function S4(e,t,i=!0){return t?e.map(e=>{var r;let n,s;return{...e,rank:(r=e.item,n=t.toLocaleLowerCase(),(s=r.name.toLocaleLowerCase())===n?0:s.startsWith(n)?1:s.includes(n)?2:!function(e,t){let i=0;for(let r of t)if(r===e[i]&&(i+=1),i===e.length)return!0;return!1}(n,s)?i&&r.description?.toLocaleLowerCase().includes(n)?4:null:3)}}).filter(e=>null!==e.rank).sort((e,t)=>e.rank-t.rank||e.stableOrder-t.stableOrder).map(e=>e.item):e.map(e=>e.item)}function S7(e){return e.length>0&&e.length<=200&&!/\s/u.test(e)&&[...e].every(S5)}function S8(e,t){return[...e].filter(S5).join("").slice(0,t)}function S9(e,t){return S3[e.sourceKind]-S3[t.sourceKind]||S2(e.name,t.name)||e.skillFilePath.localeCompare(t.skillFilePath)}var xe=Object.keys(S3).length;function xt(e){let t=e.sources[0]?.sourceKind;return void 0===t?xe:S3[t]}function xi(e,t){return xt(e)-xt(t)||S2(e.name,t.name)}var xr=[{name:"clear",description:"Clear conversation context"},{name:"compact",description:"Compact conversation context"}],xn=[{name:"model",description:"Choose the model"},{name:"effort",description:"Choose reasoning effort"}];function xs(e){if(!e.startsWith("/"))return null;let t=/^\/([^\s]+)(?:\s+(.*))?$/.exec(e.trimEnd());return t?{name:t[1].toLowerCase(),argument:t[2]?.trim()??""}:null}function xo(e,t="codex"){let i=xs(e);return!!(i&&[...xn,...xr,...function(e){let t=vl(e);if(t?.expandsSlashCommandsFromText)return[];let i=new Set(t?.textDrivenCommands??[]);return vc(e).filter(e=>!i.has(e.name))}(t)].some(e=>e.name===i.name))}async function xa(e,t){let i=xs(e);if(i?.name==="goal"&&t.setThreadGoalObjective)return i.argument?{handled:!0,accepted:await t.setThreadGoalObjective(i.argument),error:null}:{handled:!0,accepted:!1,error:"Describe the goal after /goal."};if(!i||!xo(e,t.agent))return{handled:!1,accepted:!1,error:null};if("clear"===i.name||"compact"===i.name)return i.argument?{handled:!0,accepted:!1,error:`Use /${i.name} without arguments.`}:t.conversationCommands?.includes(i.name)&&t.runConversationCommand?{handled:!0,...await t.runConversationCommand(i.name)}:{handled:!0,accepted:!1,error:`/${i.name} is not supported by this chat host.`};if("model"!==i.name&&"effort"!==i.name){var r;return r=i.name,{handled:!0,accepted:!0,error:`/${r} is not available in chat sessions. Use the slash menu to see available commands.`}}let n=t.snapshot.find(e=>e.id===i.name);if(!n||"select"!==n.kind.type)return{handled:!0,accepted:!0,error:`${"model"===i.name?"Models":"Reasoning effort"} are unavailable for this chat session.`};if(!i.argument){let e=await t.invokeAction(i.name);return{handled:!0,accepted:e,error:e?null:`Could not open the ${i.name} picker.`}}let s=i.argument.toLowerCase(),o=n.kind.choices.find(e=>e.value.toLowerCase()===s||e.label.toLowerCase()===s);if(!o)return{handled:!0,accepted:!1,error:`${i.argument} is not an available ${i.name} for this chat session.`};let a=await t.setOption(i.name,o.value);return{handled:!0,accepted:a,error:a?null:`Could not apply ${i.name} ${o.label}.`}}function xl(e){return vc(e).filter(e=>void 0===e.reply)}function xc({agent:e,structured:t,query:i},r){if(!e)return[];let n=t?.reported;return function(e,t,i,r,n,s=50,o="/"){let a="/"===r,l=function(e,t,i,r){let n=new Map;for(let t of e)t.installed&&!n.has(t.skillFilePath)&&n.set(t.skillFilePath,t);let s=new Map;for(let e of n.values()){let t=function(e){if(S7(e.name))return e.name;let t=e.directoryPath.split(/[\\/]/).findLast(Boolean)??"";return S7(t)?t:null}(e);t&&s.set(t,[...s.get(t)??[],{...e,name:t}])}let o=new Map([...s.entries()].map(([e,t])=>[e,S6(e,t,r)]));return[...new Set(void 0!==t?[...t.map(e=>e.name).filter(S7),...[...o.keys()].filter(e=>i.has(e))]:[...o.keys()])].map(e=>{let i=o.get(e)??S6(e,[],r),n=t?.find(t=>t.name===e)?.description;return null===i.description&&n?{...i,description:S8(n,240)}:i}).sort(xi)}(t,n,new Set(e.filter(e=>e.kindUnspecified).map(e=>e.name)),r),c=new Set(l.map(e=>e.name)),d=new Set(e.filter(e=>e.orcaOwned).map(e=>e.name)),u=e.filter(e=>e.orcaOwned||!(d.has(e.name)||a&&e.kindUnspecified&&c.has(e.name))),h=new Set(u.filter(e=>!e.orcaOwned).map(e=>e.name)),f=S4(u.map((e,t)=>({item:{kind:"command",id:`command:${e.name}`,name:e.name,token:`/${e.name}`,description:e.description?S8(e.description,240):void 0,argumentHint:e.argumentHint?S8(e.argumentHint,80):void 0,skillCollision:a&&!e.orcaOwned&&c.has(e.name),...e.orcaOwned?{orcaOwned:!0}:{}},stableOrder:t})),i),p=S4(l.filter(e=>!(a&&h.has(e.name))).map((e,t)=>({item:e,stableOrder:t})),i,"/"===o);return[...f.slice(0,s),...p.slice(0,s)]}(t?function(e,t,i){let r,n=function(e=[],t){let i=[...xn,...xr.filter(t=>e.includes(t.name))];return[...i,...(function(e){if(!e)return[];let t=new Set(vl(e)?.textDrivenCommands??[]);return 0===t.size?[]:vc(e).filter(e=>t.has(e.name))})(t).filter(e=>!i.some(t=>t.name===e.name))]}(t,e);if(void 0===i)return n;let s=new Set(n.map(({name:e})=>e));return[...n,...(r=new Map((vs[e]??vi).map(e=>[e.name,e.description])),i.filter(e=>"command"===e.kind).map(e=>{let t=e.description??r.get(e.name);return{name:e.name,...t?{description:t}:{},...e.argumentHint?{argumentHint:e.argumentHint}:{},...e.kindUnspecified?{kindUnspecified:!0}:{}}})).filter(({name:e})=>!s.has(e))]}(e,t.conversationCommands,n):xl(e),[],i,vl(e)?.skillPrefix??"/",n?n.flatMap(e=>"skill"===e.kind?[{name:e.name,...e.description?{description:e.description}:{}}]:[]):[],r)}function xd(){}var xu=oa(oe()),xh=oa(oe()),xf={width:38,height:38,borderRadius:19,alignItems:"center",justifyContent:"center"},xp=xh.StyleSheet.create({composerInset:{paddingHorizontal:10,paddingTop:6,paddingBottom:s6.sm},bar:{paddingTop:s6.md,paddingHorizontal:10,paddingBottom:10,borderWidth:xh.StyleSheet.hairlineWidth,borderColor:s2.composerBorder,borderRadius:s4.composer,backgroundColor:s2.composerSurface,shadowColor:"#000",shadowOpacity:.45,shadowRadius:15,shadowOffset:{width:0,height:10},elevation:8},actionRow:{marginTop:10,flexDirection:"row",alignItems:"center",gap:s6.sm},actionSpacer:{flex:1},controlButton:{...xf,backgroundColor:s2.composerControl},ghostButton:{...xf},sendButton:{...xf,backgroundColor:s2.surfaceBright},sendButtonDisabled:{backgroundColor:s2.composerControl},pressed:{opacity:.7}}),xm=oa(oo());function xg({onStop:e,held:t}){return(0,xm.jsx)(xu.Pressable,{style:({pressed:e})=>[xp.controlButton,e&&xp.pressed],onPress:e,disabled:t,accessibilityRole:"button",accessibilityLabel:t?U.stopping:"Stop the agent",children:t?(0,xm.jsx)(xu.ActivityIndicator,{size:"small",color:s2.textPrimary}):(0,xm.jsx)(se,{size:13,color:s2.textPrimary,strokeWidth:2.4,fill:s2.textPrimary})})}var xb=oa(oo()),xv=[],xy=[],x_=[];function xw({inputRef:e,value:t,onChangeText:i,onSend:r,sendSurfaceId:n,getSendCompletionGeneration:s,getComposerEditGeneration:o,agent:a=null,structured:l=null,sessionOptions:c,onAttachImage:d,attachments:u=xy,onRemoveAttachment:h,isAttaching:f=!1,onMicPress:p,micActive:m=!1,dictationMode:g="toggle",onMicPressIn:b,onMicPressOut:v,disabled:y=!1,sendDisabled:_=!1,placeholder:w="Message, @files, /commands",filePaths:S=xv,onNeedFiles:x,stop:T=null}){var k,C;let L,M,R=(0,wZ.useRef)(null),I=e??R,[A,P]=(0,wZ.useState)(!1),[E,D]=(0,wZ.useState)(!1),[B,Q]=(0,wZ.useState)(null),j=c?.controller.optionPickerRequest,[F,O]=(0,wZ.useState)(j);j&&F!==j&&(O(j),Q({page:j.id,refocus:!1}));let W=l?.files??x_,H=function(e){let{value:t,onChangeText:i,agent:r,structuredCatalog:n,filePaths:s}=e,o=(0,SX.useContext)(of),[a,l]=(0,SX.useState)(null),[c,d]=(0,SX.useState)(0),[u,h]=(0,SX.useState)(null),[f,p]=(0,SX.useState)(null),m=(0,SX.useMemo)(()=>new Set(xc({agent:r,structured:n,query:""},1/0).flatMap(e=>"skill"===e.kind?[e.token]:[])),[r,n]),g=function(e,t){let i=e.indexOf(" ");if(i<=0)return null;let r=e.slice(0,i);return t.has(r)?r:null}(t,m),b=e=>{e.startsWith("/")||p(null),i(e)},v=(0,SX.useMemo)(()=>(function(e,t){let i=Math.max(0,Math.min(t,e.length)),r=i-1;for(;r>=0&&S0.test(e[r]);)r--;let n=r+1;if(i<=n)return null;let s=e[n];if("@"!==s&&"/"!==s)return null;let o=0===n?"":e[n-1];if("/"===s&&0!==n||"@"===s&&0!==n&&!/\s/.test(o))return null;let a=e.slice(n+1,i);return/\s/.test(a)?null:{kind:"@"===s?"file":"slash",query:a,start:n,end:i}})(t,c),[t,c]),y=v?.kind??null,_=v?.query??"",w="file"===y&&v?.start===0,S=null!==y;(0,SX.useEffect)(()=>{if(!S||!o)return;let e=!0;return o.load().then(t=>{e&&l({owner:o,rows:t})},()=>{}),()=>{e=!1}},[S,o]);let x=a?.owner===o?a?.rows:void 0,T=(0,SX.useMemo)(()=>{var e;let t,i,o,a,l,c=x&&"skill"!==f?(t=_.toLowerCase().replace(/^ruflo(?:[:/-]|$)/u,"").split(/[-/\s]+/u).filter(Boolean),i=x.filter(({id:e,title:i,description:r})=>{let n=`${e} ${i} ${r}`.toLowerCase();return t.every(e=>n.includes(e))}),o=t.join("-"),a=({id:e,title:i,section:r})=>o&&e===o?0:o&&i.toLowerCase().startsWith(t.join(" "))?1:r?2:3,i.sort((e,t)=>a(e)-a(t)).slice(0,12)).map(e=>({id:"ruflo-capability:"+e.id,kind:"capability",capability:e,mode:"slash"===y?"open":"mention"})):[];if("file"===y){let e=S1(s,_).map(e=>({kind:"file",id:`file:${e}`,path:e})),t=w?xc({agent:r,structured:n,query:_},10):[];return _?[...c,...e,...t]:[...e,...c,...t]}if("slash"!==y)return[];let d=(e=xc({agent:r,structured:n,query:_},10),(l=f?e.filter(e=>e.kind===f):[]).length>0?l:e);return _?[...c,...d]:[...d,...c]},[r,x,w,s,f,y,_,n]),{onNeedFiles:k,onSlashMenuOpen:C}=e;(0,SX.useEffect)(()=>{v?.kind==="file"&&k?.(v.query)},[k,v?.kind,v?.query]);let L=v?.kind==="slash"||w;(0,SX.useEffect)(()=>{L&&C?.()},[C,L]);let M=e=>{d(e),h({start:e,end:e})};return{onFieldChange:e=>{let i=g?function(e,t,i){let r=`${i} `;if(t.startsWith(r))return t;let n=e.slice(r.length);return t.length{var n;let s;if(!v)return;if(p(null),"capability"===r.kind&&"open"===r.mode){o?.open(r.capability)&&(i(t.slice(v.end).trimStart()),M(0),SJ.Keyboard.dismiss());return}if(e.focusField(),"skill"===r.kind){let e=t.slice(v.end).trimStart();i(`${r.token} ${e}`),M(r.token.length+1);return}let a=(n=wJ(r),s=`${n} `,{text:t.slice(0,v.start)+s+t.slice(v.end),cursor:v.start+s.length});b(a.text),M(a.cursor)},openSlashMenu:r=>{let n=(g?t.slice(g.length+1):t).trimStart();i(n?`/ ${n}`:"/"),p(r),M(1),e.focusField()},openFileMenu:()=>{let i=t.slice(0,c),r=0===i.length||/\s$/.test(i)?"@":" @";b(i+r+t.slice(c)),M(i.length+r.length),e.focusField()},pendingSelection:u,onSelectionChange:e=>{d(e.end),h(null)},resetCursor:()=>d(0)}}({value:t,onChangeText:i,agent:a,structuredCatalog:l?.catalog,filePaths:S,onNeedFiles:x,onSlashMenuOpen:l?.onSlashMenuOpen,focusField:()=>I.current?.focus()}),N=(0,wZ.useRef)(!1),z=(0,wZ.useRef)(!0),$=(0,wZ.useRef)(n),q=(0,wZ.useRef)(0);(0,wZ.useLayoutEffect)(()=>{$.current!==n&&($.current=n,q.current+=1)},[n]);let[K,V]=(0,wZ.useState)(!1),U=c?.controller.pendingId!=null,Z=W.some(e=>null===e.path),G=u.length+W.length,Y=(t.trim().length>0||G>0)&&!y&&!_&&!K&&!f&&!Z&&!U,X=(L=0===(k={canStop:null!==T,sendBlocked:_,canSend:Y,editing:f||Z||m,draft:t,attachmentCount:G}).draft.trim().length&&0===k.attachmentCount,k.canStop&&(k.sendBlocked||L||!k.editing&&!k.canSend));(0,wZ.useEffect)(()=>(z.current=!0,()=>{z.current=!1,q.current+=1}),[]);let J=async()=>{if(!Y||N.current)return;N.current=!0,V(!0);let e=q.current,i=s(),n=o();try{await r(t)&&z.current&&e===q.current&&i===s()&&n===o()&&(H.resetCursor(),wG.Keyboard.dismiss())}finally{N.current=!1,V(!1)}},ee=l?()=>D(!0):d,et=l?"Add to message":"Attach image";return(0,xb.jsxs)(wG.View,{testID:"rupro-chat-composer-shell",children:[H.rows.length>0?(0,xb.jsx)(w1,{rows:H.rows,onPick:H.pick}):null,(0,xb.jsx)(wG.View,{style:xp.composerInset,testID:"native-chat-composer-inset",children:(0,xb.jsxs)(wG.View,{style:xp.bar,testID:"native-chat-composer",children:[(0,xb.jsx)(Sa,{images:u,files:W,onRemoveImage:h,onRemoveFile:l?.onRemoveFile}),(0,xb.jsx)(Sr,{ref:I,value:t,skillToken:H.skillToken,onSendKey:J,onChangeText:H.onFieldChange,onFocus:()=>P(!0),onBlur:()=>P(!1),selection:H.pendingSelection??void 0,onSelectionChange:e=>H.onSelectionChange(e.nativeEvent.selection),placeholder:w,placeholderTextColor:s2.textMuted,selectionColor:s2.accentBlue,multiline:!0,textAlignVertical:"top"}),(0,xb.jsxs)(wG.View,{style:xp.actionRow,testID:"native-chat-composer-actions",children:[ee?(0,xb.jsx)(wG.Pressable,{accessibilityLabel:et,style:({pressed:e})=>[xp.controlButton,e&&xp.pressed],onPress:ee,disabled:f||y,children:f?(0,xb.jsx)(wG.ActivityIndicator,{size:"small",color:s2.textSecondary}):(0,xb.jsx)(nC,{size:19,color:s2.textPrimary,strokeWidth:2})}):null,c?(0,xb.jsx)(SZ,{...c,sendInFlight:K||f,presentation:B,onNavigate:e=>Q(t=>t&&{...t,page:e}),onDrawerOpen:e=>Q({page:e,refocus:A}),onDrawerAfterClose:()=>{B?.refocus&&I.current?.focus(),Q(null)}}):null,(0,xb.jsx)(wG.View,{style:xp.actionSpacer}),H.hasCapabilities&&(0,xb.jsxs)(wG.View,{style:{flexDirection:"row"},children:[(0,xb.jsx)(wG.Pressable,{accessibilityRole:"button",accessibilityLabel:"Browse RuFlo commands",onPress:()=>H.openSlashMenu(null),style:xp.ghostButton,children:(0,xb.jsx)(nZ,{size:17,color:s2.brandAccent})}),(0,xb.jsx)(wG.Pressable,{accessibilityRole:"button",accessibilityLabel:"Browse RuFlo references and files",onPress:H.openFileMenu,style:xp.ghostButton,children:(0,xb.jsx)(nN,{size:17,color:s2.brandAccent})})]}),p?(0,xb.jsx)(wG.Pressable,{accessibilityLabel:m?"Stop dictation":"Dictate",style:({pressed:e})=>[xp.ghostButton,e&&xp.pressed],onPress:"hold"===g?void 0:p,onPressIn:"hold"===g?b:void 0,onPressOut:"hold"===g?v:void 0,onLongPress:"hold"===g?xd:void 0,disabled:y&&!m,children:m?(0,xb.jsx)(se,{pointerEvents:"none",size:16,color:s2.statusRed,strokeWidth:2.4,fill:s2.statusRed}):(0,xb.jsx)(ni,{pointerEvents:"none",size:19,color:s2.textSecondary,strokeWidth:2})}):null,X&&T?(0,xb.jsx)(xg,{onStop:T.onStop,held:T.held}):(0,xb.jsx)(wG.Pressable,{accessibilityRole:"button",accessibilityLabel:"Send message",style:({pressed:e})=>[xp.sendButton,!Y&&xp.sendButtonDisabled,e&&Y&&xp.pressed],onPress:J,disabled:!Y,children:(0,xb.jsx)(nW,{size:19,color:Y?s2.bgBase:s2.textMuted,strokeWidth:2.4})})]})]})}),l?(0,xb.jsx)(ik,{visible:E,onClose:()=>D(!1),actions:(C={onPhotos:d,onFiles:l.onAttachFiles,onWorkspaceFile:H.openFileMenu,onSkills:()=>H.openSlashMenu("skill"),onCommands:()=>H.openSlashMenu("command"),skillCount:H.skillCount},M=[],C.onPhotos&&M.push({label:"Photos",icon:n2,closeBeforePress:!0,onPress:C.onPhotos}),C.onFiles&&M.push({label:"Files",hint:"PDF, text, code…",icon:nm,closeBeforePress:!0,onPress:C.onFiles}),M.push({label:"Workspace file",icon:nN,closeBeforePress:!0,onPress:C.onWorkspaceFile},{label:"Skills",...C.skillCount>0?{hint:`${C.skillCount} available`}:{},icon:nc,closeBeforePress:!0,onPress:C.onSkills},{label:"Commands",icon:rF,closeBeforePress:!0,onPress:C.onCommands}),M)}):null]})}var xS=oa(oe()),xx=oa(os()),xT=oa(oe()),xk=oa(oe()),xC=oa(oo());function xL({prompt:e,onCancel:t,onCollapse:i,disabled:r}){if(!t&&!i)return null;let n=t?r7:ss;return(0,xC.jsx)(xk.Pressable,{accessibilityLabel:t?"Cancel":"Collapse",accessibilityState:t?void 0:{expanded:!0},hitSlop:8,style:xM.action,onPress:()=>{t?t(e):(xk.Keyboard.dismiss(),i?.())},disabled:r,children:(0,xC.jsx)(n,{size:16,color:s2.textMuted})})}var xM=xk.StyleSheet.create({action:{width:28,height:28,alignItems:"center",justifyContent:"center"}}),xR=oa(os()),xI=oa(oo());function xA({prompt:e,onAnswer:t,onCancel:i,onCollapse:r}){let n,s,[o,a]=(0,xx.useState)(0),[l,c]=(0,xx.useState)(()=>e.questions.map(()=>[])),[d,u]=(0,xx.useState)(()=>e.questions.map(()=>"")),[h,f]=(0,xx.useState)(!1),p=(0,xx.useRef)(!1),m=(n=(0,xR.useRef)(void 0),s=()=>clearTimeout(n.current),(0,xR.useEffect)(()=>()=>clearTimeout(n.current),[]),{schedule:e=>{s(),n.current=setTimeout(e,200)},cancel:s}),g=(e,t,i)=>{if(p.current)return;let r=l[e]??[],n=!r.includes(t),s=n?i?[...r,t]:[t]:r.filter(e=>e!==t),o=l.map((t,i)=>i===e?s:t);c(o),m.cancel(),n&&!i&&-1!==t&&m.schedule(()=>{k(o)})},b=(e,t=l)=>{let i=(t[e]??[]).filter(e=>-1!==e),r=(t[e]??[]).includes(-1)?(d[e]??"").trim():"";return r?{indices:i,other:r}:{indices:i}},v=(e,t=l)=>{let i=b(e,t);return i.indices.length>0||(i.other??"").length>0},y=e.questions.length,_=o===y-1,w=(0,xx.useMemo)(()=>v(o),[l,d,o]),S=(0,xx.useMemo)(()=>e.questions.every((e,t)=>v(t)),[d,e.questions,l]),x=!h&&(_?S:w),T=async i=>{if(!(!e.questions.every((e,t)=>v(t,i))||p.current)){p.current=!0,f(!0);try{await t(e.questions.map((e,t)=>b(t,i)))}finally{p.current=!1,f(!1)}}},k=async(e=l)=>{m.cancel(),_?await T(e):a(e=>Math.min(e+1,y-1))},C=e.questions[o],L=(l[o]??[]).includes(-1);return(0,xI.jsxs)(xT.View,{style:xE.card,children:[y>1?(0,xI.jsx)(xT.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!1,style:xE.tabs,contentContainerStyle:xE.tabsContent,keyboardShouldPersistTaps:"always",children:e.questions.map((e,t)=>(0,xI.jsxs)(xT.Pressable,{style:[xE.tab,t===o&&xE.tabActive],disabled:h,onPress:()=>{m.cancel(),a(t)},children:[(0,xI.jsx)(xT.Text,{style:[xE.tabText,t===o&&xE.tabTextActive],numberOfLines:1,children:e.header||`Step ${t+1}`}),v(t)?(0,xI.jsx)(si,{size:11,color:s2.statusGreen,strokeWidth:3}):null]},t))}):null,(0,xI.jsxs)(xT.ScrollView,{style:xE.scroll,keyboardShouldPersistTaps:"always",children:[(0,xI.jsxs)(xT.View,{style:xE.questionRow,children:[(0,xI.jsx)(xT.Text,{style:xE.questionText,children:C.question}),(0,xI.jsx)(xL,{onCollapse:r&&(()=>{m.cancel(),r()}),disabled:h})]}),C.options.map((e,t)=>(0,xI.jsx)(xP,{label:e.label,description:e.description,selected:(l[o]??[]).includes(t),multi:C.multiSelect,disabled:h,onPress:()=>g(o,t,C.multiSelect)},`${t}:${e.label}`)),(0,xI.jsx)(xP,{label:"Other…",selected:L,multi:C.multiSelect,disabled:h,onPress:()=>g(o,-1,C.multiSelect)}),L?(0,xI.jsx)(xT.TextInput,{style:xE.input,value:d[o],onChangeText:e=>{u(t=>{let i=[...t];return i[o]=e,i})},placeholder:"Type your answer",placeholderTextColor:s2.textMuted,multiline:!0,autoFocus:!0}):null]}),(0,xI.jsxs)(xT.View,{style:xE.footer,children:[(0,xI.jsx)(xT.Pressable,{style:xE.cancel,onPress:async()=>{if(m.cancel(),!p.current&&i){p.current=!0,f(!0);try{await i()}finally{p.current=!1,f(!1)}}},disabled:h,hitSlop:8,children:(0,xI.jsx)(xT.Text,{style:xE.cancelText,children:"Cancel"})}),y>1?(0,xI.jsxs)(xT.Text,{style:xE.progress,children:[o+1,"/",y]}):null,(0,xI.jsx)(xT.Pressable,{style:[xE.next,!x&&xE.nextDisabled],onPress:()=>{k()},disabled:!x,children:(0,xI.jsx)(xT.Text,{style:[xE.nextText,!x&&xE.nextTextDisabled],children:_?"Submit":"Next"})})]})]})}function xP({label:e,description:t,selected:i,multi:r,disabled:n,onPress:s}){return(0,xI.jsxs)(xT.Pressable,{style:[xE.option,i&&xE.optionSelected],disabled:n,onPress:s,children:[(0,xI.jsx)(xT.View,{style:[xE.check,r?xE.checkSquare:xE.checkCircle,i&&xE.checkOn],children:i?(0,xI.jsx)(si,{size:12,color:s2.bgBase,strokeWidth:3}):null}),(0,xI.jsxs)(xT.View,{style:xE.optionBody,children:[(0,xI.jsx)(xT.Text,{style:xE.optionLabel,children:e}),t?(0,xI.jsx)(xT.Text,{style:xE.optionDescription,numberOfLines:3,children:t}):null]})]})}var xE=xT.StyleSheet.create({card:{maxHeight:380,backgroundColor:s2.bgPanel,borderTopWidth:xT.StyleSheet.hairlineWidth,borderTopColor:s2.borderSubtle},tabs:{flexGrow:0,paddingTop:s6.sm,borderBottomWidth:xT.StyleSheet.hairlineWidth,borderBottomColor:s2.borderSubtle},tabsContent:{paddingHorizontal:s6.sm,gap:s6.xs,alignItems:"center"},tab:{flexDirection:"row",alignItems:"center",gap:4,minHeight:36,paddingHorizontal:s6.sm,paddingVertical:s6.xs,borderBottomWidth:2,borderBottomColor:"transparent"},tabActive:{borderBottomColor:s2.statusGreen},tabText:{color:s2.textSecondary,fontSize:s7.metaSize,fontWeight:"600"},tabTextActive:{color:s2.textPrimary},scroll:{paddingHorizontal:s6.md},questionRow:{flexDirection:"row",alignItems:"flex-start",gap:s6.sm},questionText:{flex:1,color:s2.textPrimary,fontSize:s7.bodySize+1,fontWeight:"600",marginVertical:s6.sm},option:{flexDirection:"row",alignItems:"center",gap:s6.sm,padding:s6.sm,borderRadius:s4.card,backgroundColor:s2.bgRaised,borderWidth:1,borderColor:s2.borderSubtle,marginBottom:s6.xs},optionSelected:{borderColor:s2.statusGreen},check:{width:18,height:18,borderWidth:1.5,borderColor:s2.textMuted,alignItems:"center",justifyContent:"center"},checkCircle:{borderRadius:9},checkSquare:{borderRadius:4},checkOn:{backgroundColor:s2.statusGreen,borderColor:s2.statusGreen},optionBody:{flex:1,gap:2},optionLabel:{color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"},optionDescription:{color:s2.textSecondary,fontSize:s7.metaSize},input:{backgroundColor:s2.bgRaised,borderWidth:1,borderColor:s2.borderSubtle,borderRadius:s4.card,color:s2.textPrimary,fontSize:iC,padding:s6.sm,minHeight:44,marginBottom:s6.xs},footer:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",padding:s6.md,gap:s6.sm,borderTopWidth:xT.StyleSheet.hairlineWidth,borderTopColor:s2.borderSubtle},cancel:{paddingVertical:s6.sm,paddingHorizontal:s6.sm},cancelText:{color:s2.textSecondary,fontSize:s7.bodySize,fontWeight:"600"},progress:{color:s2.textMuted,fontSize:s7.metaSize},next:{paddingVertical:s6.sm,paddingHorizontal:s6.lg,borderRadius:s4.button,backgroundColor:s2.textPrimary},nextDisabled:{backgroundColor:s2.bgRaised},nextText:{color:s2.bgBase,fontSize:s7.bodySize,fontWeight:"700"},nextTextDisabled:{color:s2.textMuted}}),xD=oa(os()),xB=oa(oe()),xQ=new Set(["plan"]);function xj(e){return e?.kind==="plan"}function xF(e){return void 0!==e&&!xQ.has(e.kind)}function xO(e){let t=!1;for(let{body:i}of e)if(("approval"===i.kind||"question"===i.kind)&&"pending"===i.resolution.state){if("question"===i.kind||!xF(i.subject))return!1;t=!0}return t}var xW=/[\s'"`/\\]/,xH=oa(oo()),xN=(0,xD.memo)(function({permission:e,onRespond:t,onCancel:i,onCollapse:r}){let[n,s]=(0,xD.useState)(!1),o=(0,xD.useRef)(!1),a=xF(e.subject),l=async e=>{!o.current&&(o.current=!0,s(!0),await t(e)||(o.current=!1,s(!1)))};return(0,xH.jsxs)(xB.View,{testID:"native-chat-approval-card",style:x$.card,children:[(0,xH.jsxs)(xB.View,{style:x$.header,children:[(0,xH.jsx)(nK,{size:16,color:s2.accentBlue,strokeWidth:2}),(0,xH.jsx)(xB.Text,{testID:"native-chat-approval-title",style:x$.title,numberOfLines:2,ellipsizeMode:"tail",children:e.title}),(0,xH.jsx)(xL,{prompt:e.prompt,onCancel:i,onCollapse:r,disabled:n})]}),(0,xH.jsx)(xz,{permission:e,newerSubject:a}),(0,xH.jsx)(xB.View,{testID:"native-chat-approval-actions",style:x$.options,children:e.options.map((e,t)=>{let i=0===t;return(0,xH.jsx)(xB.Pressable,{style:({pressed:e})=>[x$.option,i?x$.optionPrimary:x$.optionSecondary,e&&!n&&x$.optionPressed,a&&x$.disabled],hitSlop:6,onPress:()=>l(e.send),disabled:n||a,children:(0,xH.jsx)(xB.Text,{style:[x$.optionText,i&&x$.optionTextPrimary],children:e.label})},`${e.send}:${e.label}`)})})]})});function xz({permission:e,newerSubject:t}){let i=function(e){let t=e.blockedPath;if(!t)return null;let i=[t,JSON.stringify(t).slice(1,-1)],r=xj(e.subject)?[e.subject.text,e.subject.filePath]:[e.detail];return[e.description,e.decisionReason,...r].some(e=>void 0!==e&&i.some(t=>(function(e,t){for(let i=e.indexOf(t);-1!==i;i=e.indexOf(t,i+1)){let r=e[i+t.length];if(void 0===r||xW.test(r))return!0}return!1})(e,t)))?null:t}(e);return e.description||e.decisionReason||i||e.subject||e.detail?(0,xH.jsxs)(xB.ScrollView,{testID:"native-chat-approval-content",style:x$.contentScroll,contentContainerStyle:x$.content,nestedScrollEnabled:!0,children:[e.description?(0,xH.jsx)(xB.Text,{style:x$.detail,children:e.description}):null,e.decisionReason?(0,xH.jsxs)(xB.Text,{style:x$.detail,children:[(0,xH.jsx)(xB.Text,{style:x$.contextLabel,children:"Reason: "}),e.decisionReason]}):null,i?(0,xH.jsxs)(xB.Text,{style:x$.detail,children:[(0,xH.jsx)(xB.Text,{style:x$.contextLabel,children:"Needs access to: "}),i]}):null,xj(e.subject)?(0,xH.jsxs)(xB.View,{children:[(0,xH.jsx)(tZ,{content:e.subject.text}),e.subject.filePath?(0,xH.jsxs)(xB.Text,{style:x$.planFile,children:["Plan file: ",e.subject.filePath]}):null]}):e.detail?(0,xH.jsx)(xB.Text,{style:x$.detail,children:e.detail}):null,t?(0,xH.jsx)(xB.Text,{testID:"native-chat-approval-needs-newer-orca",style:x$.detail,children:"This request needs a newer version of RuFlo."}):null]}):null}var x$=xB.StyleSheet.create({card:{marginHorizontal:s6.lg,marginVertical:s6.sm,padding:s6.md,gap:s6.sm,borderRadius:s4.card,borderWidth:xB.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle,backgroundColor:s2.bgPanel,flexShrink:1,minHeight:0},header:{flexDirection:"row",alignItems:"center",gap:s6.sm,flexShrink:0},title:{flex:1,color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"},detail:{color:s2.textSecondary,fontSize:s7.metaSize,lineHeight:s7.metaSize+5},planFile:{marginTop:s6.sm,color:s2.textSecondary,fontFamily:s7.monoFamily,fontSize:s7.metaSize,lineHeight:s7.metaSize+5},contextLabel:{color:s2.textPrimary,fontWeight:"600"},contentScroll:{maxHeight:240,minHeight:0,flexShrink:1},content:{gap:s6.sm},options:{flexDirection:"row",flexWrap:"wrap",gap:s6.sm,flexShrink:0},option:{minHeight:44,justifyContent:"center",paddingHorizontal:s6.md,paddingVertical:s6.sm,borderRadius:s4.button},optionPrimary:{backgroundColor:s2.accentBlue},optionSecondary:{backgroundColor:s2.bgRaised,borderWidth:xB.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle},optionPressed:{opacity:.7},disabled:{opacity:.5},optionText:{color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"},optionTextPrimary:{color:s2.onAccent}}),xq=oa(os()),xK=oa(oe()),xV=/^(\s*)(?:❯|›|»)\s+/,xU=[{re:/^\s*(\d{1,2})[.)]\s+(\S.*?)\s*$/,token:1,label:2},{re:/^\s*\[([0-9a-zA-Z])\]\s+(\S.*?)\s*$/,token:1,label:2},{re:/^\s*([a-zA-Z])[.)]\s+(\S.*?)\s*$/,token:1,label:2},{re:/^\s*(?:[-*•>])\s+(\S.*?)\s*$/,token:0,label:1}];function xZ(e){let t=e.replace(xV,"$1");for(let{re:e,token:i,label:r}of xU){let n=t.match(e);if(!n)continue;let s=n[r].trim();if(0!==s.length)return{label:s,token:i>0?n[i]:null}}return null}var xG=/\b(select all|choose all|choose multiple|select multiple|pick multiple|all that apply|one or more|comma[- ]separated|multiple options)\b/i,xY=/[?:]\s*$/;function xX(e,t){if(!Number.isInteger(t)||t<0||t>=e.options.length)return null;let i=e.options[t];if(null==i||0===i.trim().length)return null;let r=e.optionTokens[t];return null!=r&&r.length>0?r:i}function xJ(e,t){return t.map(t=>xX(e,t)).filter(e=>null!=e&&e.trim().length>0)}function x0(e,t){return xJ(e,t).join(e.multiSelect?", ":" ")}function x1(e,t,i){let r=xJ(e,t),n=x5(e,i);return n.length>0&&r.push(n),r.join(e.multiSelect?", ":" ")}function x5(e,t){let i,r=e.freeTextInput?.allowEmpty?t:t.trim();return 0!==r.length||e.freeTextInput?.allowEmpty?e.freeTextToken?`${e.freeTextToken}:${encodeURIComponent(r)}`:e.freeTextInput?.allowEmpty?r:0===(i=[r].map(e=>e.trim()).filter(e=>e.length>0)).length?"":i.map(t=>{let i=e.options.indexOf(t);return -1===i?t:xX(e,i)??t}).join(e.multiSelect?", ":" "):""}var x2=oa(oo());function x3({question:e,onAnswer:t,onCancel:i,onCollapse:r}){let[n,s]=(0,xq.useState)([]),[o,a]=(0,xq.useState)(()=>e.freeTextInput?.initialValue??""),[l,c]=(0,xq.useState)(!1),d=(0,xq.useRef)(!1),u=!1!==e.allowOther,h=e.options.length>0,f=e.freeTextInput?.allowEmpty?o:o.trim(),p=async e=>{if(d.current)return!1;d.current=!0,c(!0);try{return await t(e)}finally{d.current=!1,c(!1)}},m=async t=>{let i=e.optionTokens[t];await p(i&&i.length>0?i:x0(e,[t]))},g=async()=>{if(0===n.length)return;let t=e.freeTextToken&&f.length>0?x1(e,n,f):x0(e,n);await p(t)&&a("")},b=async()=>{if(!u||0===f.length&&!e.freeTextInput?.allowEmpty)return;let t=e.multiSelect&&e.freeTextToken&&n.length>0?x1(e,n,f):x5(e,f);await p(t)&&a("")},v=n.length>0&&!l,y=u&&(f.length>0||e.freeTextInput?.allowEmpty===!0)&&!l,_=(0,xq.useMemo)(()=>e.options.map((t,i)=>({label:t,description:e.optionDescriptions?.[i],key:`${i}:${t}`})),[e.optionDescriptions,e.options]);return(0,x2.jsxs)(xK.View,{style:x6.card,children:[(0,x2.jsxs)(xK.View,{style:x6.header,children:[(0,x2.jsx)(r6,{size:15,color:s2.accentBlue,strokeWidth:2.2}),(0,x2.jsx)(xK.Text,{style:x6.question,children:e.question}),(0,x2.jsx)(xL,{prompt:e.prompt,onCancel:i,onCollapse:r,disabled:l})]}),h?(0,x2.jsx)(xK.View,{style:x6.options,children:_.map(({label:t,description:i,key:r},o)=>{let a=n.includes(o);return(0,x2.jsxs)(xK.Pressable,{accessibilityRole:e.multiSelect?"checkbox":"button",accessibilityState:e.multiSelect?{checked:a}:void 0,style:({pressed:e})=>[x6.option,a&&x6.optionSelected,e&&x6.pressed],onPress:()=>e.multiSelect?void s(e=>e.includes(o)?e.filter(e=>e!==o):[...e,o]):m(o),children:[e.multiSelect?(0,x2.jsx)(xK.View,{style:[x6.checkbox,a&&x6.checkboxOn],children:a?(0,x2.jsx)(si,{size:13,color:s2.bgBase,strokeWidth:3}):null}):null,(0,x2.jsxs)(xK.View,{style:x6.optionBody,children:[(0,x2.jsx)(xK.Text,{style:x6.optionText,children:t}),i?(0,x2.jsx)(xK.Text,{style:x6.optionDescription,numberOfLines:2,children:i}):null]})]},r)})}):null,e.multiSelect&&h?(0,x2.jsx)(xK.Pressable,{accessibilityLabel:"Submit selected options",style:({pressed:e})=>[x6.submit,!v&&x6.submitDisabled,e&&v&&x6.pressed],onPress:g,disabled:!v,children:(0,x2.jsxs)(xK.Text,{style:[x6.submitText,!v&&x6.submitTextDisabled],children:["Submit",n.length>0?` (${n.length})`:""]})}):null,u?(0,x2.jsxs)(xK.View,{style:x6.freeTextRow,children:[(0,x2.jsx)(xK.TextInput,{style:w9.freeInput,value:o,onChangeText:a,placeholder:e.freeTextInput?.placeholder??(h?"Or type a reply…":"Type your reply…"),placeholderTextColor:s2.textMuted,selectionColor:s2.accentBlue,onSubmitEditing:b,returnKeyType:"send",multiline:!e.freeTextInput||!0===e.freeTextInput.multiline}),(0,x2.jsx)(xK.Pressable,{accessibilityLabel:"Send reply",style:({pressed:e})=>[x6.freeSend,!y&&x6.freeSendDisabled,e&&y&&x6.pressed],onPress:b,disabled:!y,children:(0,x2.jsx)(nW,{size:18,color:y?s2.bgBase:s2.textMuted,strokeWidth:2.6})})]}):null]})}var x6=xK.StyleSheet.create({card:{marginHorizontal:s6.lg,marginVertical:s6.sm,padding:s6.md,gap:s6.sm,backgroundColor:s2.bgPanel,borderRadius:s4.card,borderWidth:xK.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle},header:{flexDirection:"row",alignItems:"center",gap:s6.sm},question:{flex:1,color:s2.textPrimary,fontSize:s7.bodySize+1,fontWeight:"600",lineHeight:s7.bodySize+7},options:{gap:s6.xs},option:{flexDirection:"row",alignItems:"center",gap:s6.sm,minHeight:44,paddingHorizontal:s6.md,paddingVertical:s6.sm,backgroundColor:s2.bgRaised,borderRadius:s4.button,borderWidth:xK.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle},optionSelected:{borderColor:s2.accentBlue},optionBody:{flex:1,gap:2},optionText:{color:s2.textPrimary,fontSize:s7.bodySize+1},optionDescription:{color:s2.textMuted,fontSize:s7.metaSize,lineHeight:s7.metaSize+5},checkbox:{width:20,height:20,borderRadius:s4.button,borderWidth:1.5,borderColor:s2.textMuted,alignItems:"center",justifyContent:"center"},checkboxOn:{backgroundColor:s2.accentBlue,borderColor:s2.accentBlue},submit:{minHeight:44,alignItems:"center",justifyContent:"center",borderRadius:s4.button,backgroundColor:s2.accentBlue},submitDisabled:{backgroundColor:s2.bgRaised},submitText:{color:s2.onMergeGreen,fontSize:s7.bodySize+1,fontWeight:"600"},submitTextDisabled:{color:s2.textMuted},freeTextRow:{flexDirection:"row",alignItems:"flex-end",gap:s6.sm},freeSend:{width:40,height:40,borderRadius:20,alignItems:"center",justifyContent:"center",backgroundColor:s2.textPrimary},freeSendDisabled:{backgroundColor:s2.bgRaised},pressed:{opacity:.7}}),x4=oa(oe()),x7=oa(oo());function x8({title:e,onExpand:t}){return(0,x7.jsxs)(x4.View,{testID:"native-chat-prompt-strip",style:x9.strip,children:[(0,x7.jsx)(x4.Text,{style:x9.title,numberOfLines:1,children:e}),(0,x7.jsx)(x4.Pressable,{accessibilityLabel:"Expand",accessibilityState:{expanded:!1},hitSlop:8,style:x9.action,onPress:t,children:(0,x7.jsx)(rN,{size:16,color:s2.textMuted})})]})}var x9=x4.StyleSheet.create({action:{width:28,height:28,alignItems:"center",justifyContent:"center"},strip:{flexDirection:"row",alignItems:"center",gap:s6.sm,paddingLeft:s6.md,paddingRight:s6.sm,paddingVertical:s6.xs,backgroundColor:s2.bgPanel,borderTopWidth:x4.StyleSheet.hairlineWidth,borderTopColor:s2.borderSubtle},title:{flex:1,color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"}}),Te=oa(oo());function Tt({ask:e,askKey:t,onDismissAsk:i,onAnswerAsk:r,onCancelAsk:n,onCancelPrompt:s,onCollapseAsk:o,onCollapsePrompt:a,collapsedPrompt:l,permission:c,onRespondPermission:d,question:u,onAnswerQuestion:h}){let f=e?(0,Te.jsx)(xA,{prompt:e,onAnswer:async t=>{let n=await r?.(e,t)??!1;return n&&i?.(),n},onCancel:async()=>{let e=await n?.()??!1;return e&&i?.(),e},onCollapse:o},t??"ask"):c?(0,Te.jsx)(xN,{permission:c,onRespond:async e=>await d?.(e)??!1,onCancel:s,onCollapse:a},JSON.stringify(c)):u?(0,Te.jsx)(x3,{question:u,onAnswer:async e=>await h?.(e)??!1,onCancel:s,onCollapse:a},JSON.stringify(u)):null;return(0,Te.jsxs)(Te.Fragment,{children:[(0,Te.jsx)(xS.View,{style:l?Ti.collapsed:void 0,children:f}),l?(0,Te.jsx)(x8,{title:l.title,onExpand:l.expand}):null]})}var Ti=xS.StyleSheet.create({collapsed:{display:"none"}}),Tr=oa(os()),Tn=oa(os()),Ts=oa(oe());function To(e,t,i){let r={value0:t};switch(e){case"agent":return 1===t?i("countAgentsOne"):i("countAgentsMany",r);case"command":return 1===t?i("countShellOne"):i("countShellMany",r);case"monitor":return 1===t?i("countMonitorsOne"):i("countMonitorsMany",r);case"workflow":return 1===t?i("countWorkflowsOne"):i("countWorkflowsMany",r);case"unknown":return 1===t?i("countTasksOne"):i("countTasksMany",r)}}var Ta=["working","monitoring","waiting","blocked","unverifiable","idle","done"],Tl=new Set(["waiting","unverifiable","blocked"]),Tc=oa(os()),Td=[],Tu=new Set;function Th(e,t,i){let r=e=>!t.has(i(e)??"");return e.every(r)?e:e.filter(r)}function Tf(e,t){if(!e.show)return null;if(!e.children)return e.tasks.some(e=>e.id===t)?t:null;let i=e.children.find(e=>e.providerId===t);return i?`${i.invocation.invocationId}#${i.invocation.generation}`:null}var Tp=new Set,Tm=new Map,Tg={taskIds:Tp,all:!1},Tb=oa(oo());function Tv({kind:e,size:t}){let i={size:t,color:"monitor"===e?F:s2.textMuted,strokeWidth:2};switch(e){case"agent":return(0,Tb.jsx)(nG,{...i});case"command":return(0,Tb.jsx)(n8,{...i});case"monitor":return(0,Tb.jsx)(nQ,{...i});case"workflow":return(0,Tb.jsx)(r5,{...i});case"unknown":return(0,Tb.jsx)(r6,{...i})}}function Ty({row:e,now:t,hostNow:i,supportsTaskStop:r,stopping:n,onStop:s}){let{lead:o,trail:a}=w(e,t),l=v(e,i),c=y(e,r),d=null!==c&&n.taskIds.has(c);return(0,Tb.jsxs)(Tb.Fragment,{children:[(0,Tb.jsxs)(Ts.View,{testID:"background-task-row",style:Tw.row,children:[(0,Tb.jsx)(Tv,{kind:e.kind,size:14}),(0,Tb.jsx)(O,{state:e.displayState}),(0,Tb.jsxs)(Ts.Text,{style:Tw.rowText,numberOfLines:1,ellipsizeMode:"tail",children:[(0,Tb.jsx)(Ts.Text,{style:Tw.lead,children:o}),a?(0,Tb.jsx)(Ts.Text,{style:Tw.trail,children:` \xb7 ${a}`}):null]}),l?(0,Tb.jsx)(Ts.Text,{style:Tw.meta,importantForAccessibility:"no",accessibilityElementsHidden:!0,children:l}):null,null!==c?(0,Tb.jsx)(Ts.Pressable,{accessibilityRole:"button",accessibilityLabel:H("stopTask",{value0:_(e)}),accessibilityState:{disabled:d},disabled:d,hitSlop:6,style:({pressed:e})=>[Tw.textAction,e&&Tw.pressed,d&&Tw.disabled],onPress:()=>s(c),children:(0,Tb.jsx)(Ts.Text,{style:Tw.actionLabel,children:H("stop")})}):null]}),e.owned.length>0?(0,Tb.jsx)(Ts.View,{style:Tw.owned,children:e.owned.map(e=>(0,Tb.jsx)(Ty,{row:e,now:t,hostNow:i,supportsTaskStop:r,stopping:n,onStop:s},e.id))}):null]})}var T_=(0,Tn.memo)(function({tasks:e}){let{view:t,rowContext:i}=e,[r,n]=(0,Tn.useState)(!1),[s,o]=(0,Tn.useState)(()=>Ts.Dimensions.get("window").width-2*s6.lg<384),{stopping:a,onStop:l}=function(e){let t,{view:i,stop:r}=e,[n,s]=(0,Tc.useState)(Tg),o=(0,Tc.useRef)(Tg),[a,l]=(0,Tc.useState)(Tm),c=(t=[...a].filter(([e,t])=>Tf(i,e)===t)).length===a.size?a:new Map(t);c!==a&&l(c);let d=e=>{o.current=e,s(e)};return{stopping:c.size?{...n,taskIds:new Set([...n.taskIds,...c.keys()])}:n,onStop:e=>{let t=o.current;if(e?t.taskIds.has(e):t.all)return;let n=e?Tf(i,e):null;d({taskIds:e?new Set([...t.taskIds,e]):t.taskIds,all:!e||t.all}),r(e).then(t=>{e&&null!==n&&"accepted"===t.status&&t.value.cancelled&&l(t=>new Map([...t,[e,n]]))}).finally(()=>{let t=o.current,i=new Set(t.taskIds);e&&i.delete(e),d({taskIds:i,all:!!e&&t.all})})}}}(e),c=(0,Tn.useMemo)(()=>void 0!==t.children?es(t.children,i):en(t.tasks,t.settledTasks,H),[t.children,t.tasks,t.settledTasks,i]),d=rn(1e3,t.show&&b(c,r));if(!t.show)return null;let u=d-i.hostClockOffsetMs,v=function(e,t,i){let r=e.flatMap(e=>e.tasks);if(0===r.length)return{segments:[],detail:i("monitoring")};if(e.length>3||t.narrow&&e.length>1)return{segments:[{text:i("headerTotal",{value0:r.length}),kind:null}],detail:null};if(e.length>1)return{segments:e.map(e=>({text:To(e.kind,e.tasks.length,i),kind:e.kind})),detail:null};let n=e[0],s=n.tasks.length,o=n.tasks.every(e=>e.state===n.tasks[0].state)?n.tasks[0].state:null;if(o&&Tl.has(o))return{segments:[{text:p(To(n.kind,s,i),o,i),kind:n.kind}],detail:f(o,i)};if(1===s){let e=n.tasks[0],r="command"===n.kind?i("countShellCommandOne"):To(n.kind,1,i),s="command"!==n.kind||e.row.settled?null:g(e.row.firstObservedAt,t.now);return{segments:[{text:r,kind:n.kind}],detail:s??h(e.state,i)}}let a=Ta.map(e=>({state:e,count:n.tasks.filter(t=>t.state===e).length})).filter(e=>e.count>0);return{segments:[{text:To(n.kind,s,i),kind:n.kind}],detail:a.length>0?a.map(e=>p(e.count,e.state,i)).join(", "):null}}(c,{narrow:s,now:u},H);return(0,Tb.jsx)(Ts.View,{style:Tw.list,onLayout:e=>{o(e.nativeEvent.layout.width<384)},testID:"background-tasks-strip",children:(0,Tb.jsxs)(Ts.View,{style:Tw.box,children:[(0,Tb.jsxs)(Ts.Pressable,{accessibilityRole:"button",accessibilityState:{expanded:r},accessibilityLabel:`${v.segments.map(e=>e.text).join(" · ")}${v.detail?`${v.segments.length>0?" — ":""}${v.detail}`:""}`,hitSlop:s6.xs,style:({pressed:e})=>[Tw.header,e&&Tw.pressed],onPress:()=>n(!r),children:[(0,Tb.jsxs)(Ts.View,{style:Tw.headerText,children:[v.segments.map((e,i)=>(0,Tb.jsxs)(Ts.View,{style:Tw.segment,children:[i>0?(0,Tb.jsx)(Ts.Text,{style:Tw.separator,children:"·"}):null,e.kind?(0,Tb.jsx)(Ts.View,{style:t.isMonitoring?void 0:Tw.dimmed,children:(0,Tb.jsx)(Tv,{kind:e.kind,size:12})}):null,(0,Tb.jsx)(Ts.Text,{style:Tw.segmentText,numberOfLines:1,ellipsizeMode:"tail",children:e.text})]},e.kind??"total")),v.detail?(0,Tb.jsx)(Ts.Text,{style:Tw.detail,numberOfLines:1,ellipsizeMode:"tail",children:v.segments.length>0?`— ${v.detail}`:v.detail}):null]}),(0,Tb.jsx)(Ts.View,{style:r?Tw.caretOpen:void 0,children:(0,Tb.jsx)(ss,{size:14,color:s2.textMuted,strokeWidth:2})})]}),r?(0,Tb.jsxs)(Ts.ScrollView,{style:Tw.body,nestedScrollEnabled:!0,children:[c.length>0?c.map(e=>(0,Tb.jsxs)(Ts.View,{style:Tw.group,children:[(0,Tb.jsx)(Ts.Text,{style:Tw.groupLabel,children:m(e.kind,H)}),e.tasks.map(e=>(0,Tb.jsx)(Ty,{row:e.row,now:d,hostNow:u,supportsTaskStop:t.supportsStop,stopping:a,onStop:l},e.row.id))]},e.kind)):(0,Tb.jsx)(Ts.Text,{style:Tw.unavailable,children:H("detailsUnavailable")}),t.incomplete&&c.length>0?(0,Tb.jsx)(Ts.Text,{style:Tw.unavailable,children:H("detailsUnavailable")}):null,t.offersStopAll?(0,Tb.jsx)(Ts.Pressable,{accessibilityRole:"button",accessibilityLabel:H("stopAll"),accessibilityState:{disabled:a.all},disabled:a.all,hitSlop:6,style:({pressed:e})=>[Tw.textAction,Tw.stopAll,e&&Tw.pressed,a.all&&Tw.disabled],onPress:()=>l(),children:(0,Tb.jsx)(Ts.Text,{style:Tw.actionLabel,children:H("stop")})}):null]}):null]})})}),Tw=Ts.StyleSheet.create({list:{marginHorizontal:s6.lg,marginVertical:s6.xs},box:{backgroundColor:s2.bgPanel,borderRadius:s4.row,borderWidth:Ts.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle,overflow:"hidden"},header:{minHeight:36,flexDirection:"row",alignItems:"center",gap:s6.sm,paddingHorizontal:s6.md},headerText:{flex:1,minWidth:0,flexDirection:"row",alignItems:"center",gap:s6.xs,overflow:"hidden"},segment:{flexDirection:"row",alignItems:"center",gap:s6.xs,flexShrink:1,minWidth:0},separator:{color:s2.textMuted,fontSize:s7.metaSize},segmentText:{flexShrink:1,color:s2.textPrimary,fontSize:s7.metaSize,fontWeight:"500"},detail:{flexShrink:1,color:s2.textMuted,fontSize:s7.metaSize},dimmed:{opacity:.4},caretOpen:{transform:[{rotate:"180deg"}]},body:{maxHeight:220,borderTopWidth:Ts.StyleSheet.hairlineWidth,borderTopColor:s2.borderSubtle},group:{paddingHorizontal:s6.md,paddingTop:s6.xs,paddingBottom:s6.xs},groupLabel:{color:s2.textMuted,fontSize:10,fontFamily:s7.monoFamily,letterSpacing:.8,textTransform:"uppercase",paddingBottom:s6.xs/2},row:{minHeight:32,flexDirection:"row",alignItems:"center",gap:s6.sm},owned:{marginLeft:s6.lg},rowText:{flex:1,minWidth:0,fontSize:s7.metaSize},lead:{color:s2.textPrimary,fontWeight:"500"},trail:{color:s2.textMuted},meta:{color:s2.textMuted,fontSize:10,fontFamily:s7.monoFamily},unavailable:{color:s2.textMuted,fontSize:s7.metaSize,padding:s6.md},textAction:{minHeight:32,minWidth:44,alignItems:"center",justifyContent:"center",paddingHorizontal:s6.sm,borderRadius:s4.button},stopAll:{alignSelf:"flex-start",marginHorizontal:s6.sm},actionLabel:{color:s2.textPrimary,fontSize:s7.metaSize,fontWeight:"500"},pressed:{backgroundColor:s2.bgRaised},disabled:{opacity:.5}}),TS=oa(os()),Tx=oa(oe()),TT=oa(oe()),Tk=oa(os()),TC=oa(oe()),TL=oa(os()),TM=oa(oe()),TR=oa(os()),TI=["fontFamily","fontSize","fontWeight","fontStyle","lineHeight","letterSpacing","wordSpacing","textTransform","textIndent","whiteSpace","overflowWrap","wordBreak","tabSize","paddingTop","paddingRight","paddingBottom","paddingLeft"],TA=oa(oo()),TP=s6.xs;function TE({editor:e,attribution:t}){let i=(0,TL.useRef)(null),r=function(e,t){let[i,r]=(0,TR.useState)(),n=(0,TR.useRef)(null),s=(0,TR.useRef)(t),o=(0,TR.useCallback)(()=>{let t=e.current,i=n.current;if(!i||!(t instanceof HTMLTextAreaElement)||t.clientWidth<=0)return;let o=getComputedStyle(t);for(let e of TI)i.style[e]=o[e];i.style.width=`${t.clientWidth}px`,i.value=s.current.endsWith(` +`)}var v6=new WeakMap;function v4(e){let t,i,r,n,s,o=v6.get(e);if(o)return o;let a=(i=b3((t=bg(e.filter(e=>!ba(e)))).prose),r=t.prose.filter(bt),n=function(e){let t=new Set,i=new Map,r=new Map,n=[];for(let[i,s]of(e.forEach((e,t)=>{if(bt(e)){let i=function(e){var t,i;let r=e.summary?.trim()||e.error?.trim();if(r)return r;let n=v5[t=e.kind,v1.find(e=>e===t)??"unknown"],s=e.label.trim()?`${n} "${e.label}"`:n;if(i=e.state,v0.has(i))return`Started ${s}`;let o=v2[e.state]??"stopped reporting";return`${s.charAt(0).toUpperCase()}${s.slice(1)} ${o}`}(e);n.push({index:t,sentence:i}),r.set(i,(r.get(i)??0)+1)}}),e.entries())){let e="text"===s.type?r.get(s.text)??0:0;"text"===s.type&&e>0&&(r.set(s.text,e-1),t.add(i))}for(let e of n){let t=r.get(e.sentence)??0;t>0&&(r.set(e.sentence,t-1),i.set(e.index,e.sentence))}return{twinTextIndexes:t,unpairedRows:i}}(t.prose),{prose:s=0===i.length&&0===r.length?t.prose:t.prose.filter((e,t)=>!g9(e)&&!bt(e)&&!n.twinTextIndexes.has(t)&&!b6(e,i.length>0)),tools:t.tools,subagentGroups:i,backgroundTasks:r,markdown:v3(s),hasImages:s.some(e=>"image-ref"===e.type)});return v6.set(e,a),a}function v7(e){let{markdown:t,hasImages:i,tools:r,subagentGroups:n,backgroundTasks:s}=v4(e);return t.length>0||i||r.length>0||n.length>0||s.length>0}var v8=/^[\s\S]{0,40}~orca-oversized~(?:[1-9]\d*)~[0-9a-f]{16}$/,v9=Symbol("parsedJournalItemKey");function ye(e,t){let i=t>>>0;for(let t=0;t>>0;return i>>>0}function yt(e){let t=String(e),i=function(e){if(e.length<=1024&&!function(e){for(let t=0;t=55296&&i<=56319){let i=t+157343)return!0;t+=1}else if(i>=56320&&i<=57343)return!0}return!1}(e))return e;let t=ye(e,0x811c9dc5).toString(16).padStart(8,"0"),i=ye(e,0x1000193).toString(16).padStart(8,"0");return`${function(e){let t="",i=0;for(;i=55296&&r<=56319){let r=i+1=56320&&r<=57343){if(i+1>=40)break;t+=e.charAt(i)+e.charAt(i+1),i+=2;continue}t+="�",i+=1;continue}t+=r>=56320&&r<=57343?"�":e.charAt(i),i+=1}return t}(e)}~orca-oversized~${e.length}~${t}${i}`}(t),r=encodeURIComponent(i);return t===i&&yi(t)?`%FF${r}`:r}function yi(e){return v8.test(e)}function yr(e){let t=e[v9];return void 0!==t?t:"codex"===e.provider?["codex",yt(e.threadId),yt(e.turnId),yt(e.ordinal)].join(":"):"claude"===e.provider?["claude",yt(e.sessionId),yt(e.uuid)].join(":"):"orca"===e.provider?["orca",yt(e.clientMessageId)].join(":"):["legacy",yt(e.agent),yt(e.sessionId),yt(e.recordId)].join(":")}function yn(e){return yr({provider:"orca",clientMessageId:e})}function ys(e){let t=[],i=!1;for(let r of e.split(":")){let e=function(e){let t=e.startsWith("%FF");try{let i=decodeURIComponent(t?e.slice(3):e);return!t||yi(i)?{value:i,tagged:t}:null}catch{return null}}(r);if(!e)return null;t.push(e.value),i||=e.tagged||yi(e.value)}let[r,...n]=t;if("codex"===r&&3===n.length){let t=Number(n[2]);return Number.isSafeInteger(t)&&t>=0?yo({provider:r,threadId:n[0],turnId:n[1],ordinal:t},e,i):null}return"claude"===r&&2===n.length?yo({provider:r,sessionId:n[0],uuid:n[1]},e,i):"orca"===r&&1===n.length?yo({provider:r,clientMessageId:n[0]},e,i):"legacy"===r&&3===n.length?yo({provider:r,agent:n[0],sessionId:n[1],recordId:n[2]},e,i):null}function yo(e,t,i){return i&&Object.defineProperty(e,v9,{value:t}),e}function ya(e){return{id:e.itemId,timestamp:e.observedAt,source:"transcript",journalPosition:yl(e)}}function yl(e){return{sequence:e.sequence,index:e.sequenceIndex??0}}function yc(e,t){return e.sequence-t.sequence||e.index-t.index}function yd(e,t){return e.sequence-t.sequence||(e.sequenceIndex??0)-(t.sequenceIndex??0)}function yu(e,t){let i=e.map(e=>{let{submittedSequence:i,submittedAt:r}=t(e);return{entry:e,submittedSequence:i,submittedAt:r}});return(i.every(e=>void 0!==e.submittedSequence)?[...i].sort((e,t)=>e.submittedSequence-t.submittedSequence):[...i].sort((e,t)=>e.submittedAt-t.submittedAt)).map(({entry:e})=>e)}function yh(e){return!0===e.handoverRecorded&&"pending"===e.dispatchState&&void 0===e.handedOverAt}var yf=["goal"],yp=["running","completed"],ym={kind:"thread"},yg=sF().finite().nonnegative(),yb=sF().finite().positive(),yv=sF().finite(),yy=sj().min(1).max(256),y_=sz({inputTokens:yg,cacheCreationInputTokens:yg,cacheReadInputTokens:yg,outputTokens:yg}),yw=sV("kind",[sz({kind:sY("report"),model:yy,usedTokens:yg,windowTokens:yb,percentage:sF().finite(),autoCompactAtTokens:yg.optional(),categories:sH(sz({name:sj().min(1).max(80),tokens:yg,deferred:sY(!0).optional()})).max(64),capturedAt:yv}),sz({kind:sY("estimate"),usage:y_,capturedAt:yv}),sz({kind:sY("unknown"),capturedAt:yv})]),yS=sz({window:sz({tokens:yb,capturedAt:yv}).optional(),used:yw.optional()});function yx(e){if(!e)return null;if("turn"===e.kind){let{kind:t,...i}=e;return i}return"status"===e.kind?e.turnLifecycle??null:null}function yT(e){let t=e?.outcome;return P.find(e=>e===t)??null}var yk=e=>"user"===e.role;function yC(e,t,i=yk){let r;return e.map(e=>{let n=t?.get(e.id);return void 0!==n?(r=n,n):(i(e)&&(r=e.id),r)})}function yL(e,t,i){let r=r=>e[r]?.role==="user"&&t[r]===e[r].id&&i.has(e[r].id),n=new Map;t.forEach((e,t)=>{void 0===e||n.has(e)||n.set(e,t)});let s=new Map,o=new Set;for(let[i,a]of e.entries()){if(!r(i))continue;let l=-1;for(let s=i+1;si)break;l=s}}-1!==l&&(o.add(i),s.set(l,[...s.get(l)??[],i]))}return 0===o.size?null:e.flatMap((e,t)=>[...o.has(t)?[]:[t],...s.get(t)??[]])}function yM(e,t){return null===t?e:t.map(t=>e[t])}function yR(e){if("object"!=typeof e||null===e||Array.isArray(e)||!("agent"in e)||!("problem"in e)||!("option"in e))return;let t=e.agent,i=e.problem,r=e.option;if(!("Codex"!==t&&"Claude"!==t||"unsupportedOption"!==i&&"missingValue"!==i&&"multipleValues"!==i&&"positionalPrompt"!==i||"string"!=typeof r||("positionalPrompt"===i?"prompt"!==r:!/^(?:--[a-zA-Z][a-zA-Z0-9-]{0,63}|-[a-zA-Z]|--\?)$/.test(r))))return{agent:t,option:r,problem:i}}var yI=["session","weekly","weeklyModel","credits"],yA=/^[A-Za-z][\w./-]{0,63}$/,yP={sameValueLeaves:!0,absentKeyEqualsUndefined:!0};function yE(e){if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function yD(e){let t;return null!==((t=e.trim().replace(/^v/i,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-.]+))?(?:\+([0-9A-Za-z-.]+))?$/))?{core:[Number(t[1]),Number(t[2]),Number(t[3])],prerelease:t[4]?.split(".")??[]}:null)}function yB(e){let t=e.def.discriminator;return new Set(e.options.flatMap(e=>{let i=e instanceof sN?e.shape[t]:void 0;return i instanceof sG?[...i.values].map(String):[]}))}function yQ(e){let t=e.def.discriminator,i=yB(e);return sK([e,sz({[t]:sj().regex(/\S/)}).refine(e=>!i.has(e[t]??""),{abort:!0})])}var yj=sz({objective:sj(),status:sj().min(1),tokenBudget:sF().finite().nullable(),tokensUsed:sF().finite(),timeUsedSeconds:sF().finite(),createdAt:sF().finite(),updatedAt:sF().finite()}),yF=yQ(sV("state",[sz({state:sY("set"),goal:yj}),sz({state:sY("cleared")})])),yO=sz({kind:sj().min(1),detail:sz({text:sj(),audience:sj().min(1)}).optional(),refusal:sz({code:sj().min(1),details:sq({}).optional()}).optional(),argumentProblem:sz({agent:sj(),option:sj(),problem:sj()}).optional(),requestTimeout:sq({}).optional()}),yW=sz({head:sj(),byteLength:sF(),digest:sj(),truncated:sO()}),yH=sz({provider:sj(),kind:sj(),payload:yW}),yN={mcpIdentity:sz({server:sj(),tool:sj()}).optional(),exitCode:sF().int().optional(),durationMs:sF().nonnegative().optional(),webSearchResults:sH(sz({title:sj(),url:sj()})).optional()},yz=sj().refine(e=>e.trim().length>0,"callId must contain a non-whitespace character"),y$=sz({id:sj(),label:sj(),state:sj().min(1),tokens:sF().optional(),startedAt:sF().optional(),settledAt:sF().optional()}),yq=yQ(sV("type",[sz({type:sY("text"),text:sj(),presentation:sj().optional(),tone:sj().optional(),providerFrame:yH.optional()}),sz({type:sY("tool-call"),name:sj(),input:sW().optional(),callId:yz.optional(),...yN}),sz({type:sY("tool-result"),output:sj(),isError:sO().optional()}),sz({type:sY("image-ref"),path:sj().optional(),url:sj().optional(),alt:sj().optional()}),sz({type:sY("subagent-group"),groupId:sj(),agents:sH(y$)}),y$.extend({type:sY("subagent"),groupId:sj(),parentId:sj().optional(),run:sj().optional(),outcomeBasis:sj().optional(),background:sO().optional()}),sz({type:sY("background-task"),taskId:sj().min(1),kind:sj().min(1),label:sj(),state:sj().min(1),parentToolUseId:sj().optional(),summary:sj().optional(),error:sj().optional(),outputFile:sj().optional(),tokens:sF().optional(),startedAt:sF().optional(),settledAt:sF().optional()})])),yK=sz({id:sj(),label:sj(),description:sj().optional()}),yV=sz({allowEmpty:sO().optional(),multiline:sO().optional(),initialValue:sj().optional(),placeholder:sj().optional()}),yU=sz({id:sj(),question:sj(),header:sj().optional(),multiSelect:sO(),options:sH(yK),freeTextQuestionId:sj().optional(),freeTextInput:yV.optional()}),yZ=sz({state:sj().min(1),selectedOptionId:sj().nullable(),answers:sH(sz({questionId:sj(),optionIds:sH(sj()),other:sj().optional()})).optional(),resolvedBy:sj().nullable(),resolvedAt:sF().nullable()}),yG=sz({source:sj(),toolName:sj(),ruleContent:sj().optional()}),yY=sV("kind",[sz({kind:sY("plan"),text:sj().min(1),filePath:sj().optional()})]),yX=(yB(yY),yQ(yY)),yJ=sz({kind:sY("message"),role:sj().min(1),blocks:sH(yq),sentAs:sj().min(1).optional(),command:sz({name:sj().min(1)}).optional(),state:sj().min(1).optional(),completedAt:sF().finite().optional()}),y0={turnId:sj(),state:sj().min(1),outcome:sj().min(1).optional(),userItemId:sj().min(1).optional(),startedAt:sF().finite().positive().optional(),requestedAt:sF().finite().positive().optional(),completedAt:sF().finite().positive().optional(),durationMs:sF().finite().nonnegative().optional()},y1=sV("kind",[yJ,sz({kind:sY("tool-call"),...yN,name:sj(),input:sW().optional(),callId:yz.optional(),state:sj().min(1),endedAs:sj().min(1).optional(),output:yW.optional()}),sz({kind:sY("diff"),path:sj(),patch:yW}),sz({kind:sY("approval"),title:sj(),displayName:sj().optional(),description:sj().optional(),decisionReason:sj().optional(),blockedPath:sj().optional(),matchedAskRule:yG.optional(),subject:yX.optional(),detail:sj().nullable(),options:sH(yK),resolution:yZ}),sz({kind:sY("question"),question:sj(),options:sH(yK),questions:sH(yU).optional(),freeTextQuestionId:sj().optional(),freeTextInput:yV.optional(),resolution:yZ}),sz({kind:sY("status"),text:sj(),presentation:sj().optional(),contextClear:sz({operationId:sj().min(1).max(512),afterFence:sF().int().nonnegative(),clearedAt:sF().int().nonnegative()}).optional(),tone:sj().optional(),turnLifecycle:sz(y0).optional(),providerFrame:yH.optional(),threadGoal:yF.optional(),failure:yO.optional(),orcaStop:sz({cause:sj().min(1)}).optional()}),sz({kind:sY("turn"),...y0,contextUsage:yS.optional(),providerTurnId:sj().min(1).optional()})]),y5=(yB(y1),yQ(y1)),y2={agentId:sj().min(1).optional(),parentAgentId:sj().min(1).optional(),providerParentRef:sj().min(1).optional(),producerKind:sj().min(1).optional(),attempt:sF().int().optional()},y3=sz({kind:sj().min(1),turnItemId:sj().min(1).optional()}),y6=sz({itemId:sj().min(1),revision:sF().int(),body:y5,sequence:sF().int(),sequenceIndex:sF().int().nonnegative().optional(),observedAt:sF(),recovered:sY(!0).optional(),recoveredAt:sF().optional(),turnScope:y3.optional(),...y2});function y4(e){return y6.safeParse(e).success}var y7=["unsupported","history-not-paginated","busy","stale-epoch","invalid-target","history-limit","provider-refused","proof-mismatch","outcome-unknown"],y8=sj().min(1).max(4096);sz({operationId:y8,callerKey:y8,itemId:y8,providerItemId:y8.optional(),expectedEpoch:y8,contextClearOperationId:y8.optional(),contextClearSequence:sF().int().positive().optional(),phase:sZ(["prepared","provider-succeeded","completed","refused"]),epoch:y8.optional(),sequence:sF().int().nonnegative().optional(),hydrationVerified:sO().optional(),reason:sj().min(1).max(512).optional(),retained:sH(sz({itemId:y8.refine(e=>null!==ys(e)),body:y5,observedAt:sF().finite(),turnScope:y3.optional(),ownerFence:sF().int().nonnegative().optional(),executionOwner:sF().int().nonnegative().optional(),...y2})).max(1e4).optional()});var y9={agent_session_operation_invalid:["requestMalformed","operationIdInvalid","messageIdReused","operationRefusedEarlier","journalWriteFailed","stopFailed","cancelNotSaved","attachmentExpired","conversationCleared","clearUnconfirmed","conversationCommandUnconfirmed","conversationCommandInFlight","handoffInFlight","turnActive","continuationSuperseded","promptPending","backgroundTasksRunning","messagesUnsettled","queueTooLarge","rewindRefused","rewindUnconfirmed","promptGone","promptOwnerEnded","optionRejected","providerStarting","goalsUnsupported","providerRejected","providerStartFailed","notSignedIn","cliMissing","historyTooLarge","managedAccountEnvOverride","accountSwitchInProgress","managedAccountUnsupported","launchFolderMissing","historyInOtherAccount","claudeAccountFolderMissing","claudeAccountSetupFailed","agentCommandNotRunnable","runtimeNotInstalled","attachFailed"],agent_session_ownership_unknown:["sessionNotAttached","noLiveOwner","ownerUnproven","claimConflicted","recordMissing","replaySuperseded","leaseMoved","spawnIdentityMismatch","notResumable","noProviderChild","conversationHeldElsewhere","previousExitUnverifiable"],agent_session_conflict:["chatStarting","ownerUnproven","claimConflicted","ownerAlive","identityMismatch","sessionExists","conversationHeldElsewhere","tabIdTaken"],execution_owner_reconciling:["hostReconciling","recordUnreadable"],agent_session_checkpoint_stale:["fenceStale","leaseMoved","recordMissing"],agent_session_identity_required:["recordMissing","transcriptNotFound","transcriptUnreadable"],agent_session_operation_conflict:["fingerprintMismatch","operationIdReused","handoffInFlight"],agent_session_operation_expired:["operationExpired"],agent_session_operation_capacity:["operationCapacity"],agent_session_operation_unknown:["outcomeUnknown","resultLost","rewindUnconfirmed","tabUnconfirmed"],agent_session_item_revision_stale:["promptMoved"],agent_session_already_resolved:["promptAlreadyResolved"],agent_session_journal_unreadable:["journalCorrupt","journalUnavailable","journalWrittenByNewerOrca"],structured_agent_session_unsupported:["clientCapabilityMissing","hostDisabled","hostUnsupported"],agent_session_owner_restart_failed:[]},_e={agent_session_operation_invalid:["rewindReason"],agent_session_operation_unknown:["rewindReason"],agent_session_checkpoint_stale:["currentFence"],agent_session_item_revision_stale:["currentRevision","resolution"],agent_session_already_resolved:["currentRevision","resolution"]},_t=["live","unverifiable","exited"];function _i(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _r(e,t){var i,r;let n;if(!_i(t))return;let s=[..._e[e]??[],"ownerVerdict"].reduce((e,i)=>({...e,...function(e,t){switch(e){case"currentFence":return Number.isSafeInteger(t)&&"number"==typeof t?{currentFence:t}:{};case"currentRevision":return Number.isSafeInteger(t)&&"number"==typeof t?{currentRevision:t}:{};case"resolution":return yZ.safeParse(t).success?{resolution:t}:{};case"ownerVerdict":{let e=_t.find(e=>e===t);return e?{ownerVerdict:e}:{}}case"rewindReason":{let e=y7.find(e=>e===t);return e?{rewindReason:e}:{}}}}(i,t[i])}),{}),o="agent_session_operation_invalid"===e?yR(t.argumentProblem):void 0,a="agent_session_operation_invalid"===e?function(e){if(!("object"!=typeof e||null===e||!("installedVersion"in e)||!("minimumVersion"in e)||null!==e.installedVersion&&("string"!=typeof e.installedVersion||!yD(e.installedVersion))||"string"!=typeof e.minimumVersion||!yD(e.minimumVersion)))return{installedVersion:e.installedVersion,minimumVersion:e.minimumVersion}}(t.codexInstallation):void 0,l=("agent_session_conflict"===e||"agent_session_ownership_unknown"===e)&&"conversationHeldElsewhere"===t.reason&&_i(t.owner)&&"string"==typeof t.owner.sessionId&&t.owner.sessionId.trim().length>0&&"string"==typeof t.owner.workspaceId&&t.owner.workspaceId.trim().length>0?{sessionId:t.owner.sessionId,workspaceId:t.owner.workspaceId}:void 0,c={...(i=t.reason,n=y9[e],"string"==typeof i&&n.includes(i))?{reason:t.reason}:{},...s,...l?{owner:l}:{},..."agent_session_operation_invalid"===e&&"notSignedIn"===t.reason&&("managed"===t.account||"system"===t.account)?{account:t.account}:{},...o?{argumentProblem:o}:{},..."agent_session_operation_invalid"===e&&"stopFailed"===t.reason&&"string"==typeof(r=t.agent)&&Object.hasOwn(re,r)?{agent:t.agent}:{},...a?{codexInstallation:a}:{}};return Object.keys(c).length>0?c:void 0}var _n=["structured_agent_session_unsupported","agent_session_checkpoint_stale","agent_session_conflict","agent_session_ownership_unknown","agent_session_operation_conflict","agent_session_operation_expired","agent_session_operation_capacity","agent_session_operation_invalid","agent_session_operation_unknown","agent_session_item_revision_stale","agent_session_already_resolved","agent_session_identity_required","agent_session_journal_unreadable","execution_owner_reconciling","agent_session_owner_restart_failed"];function _s(e){return"string"==typeof e&&_n.includes(e)}function _o(e){if(!("object"!=typeof e||null===e||!("code"in e)||!_s(e.code))){var t;return{code:e.code,...(t="details"in e?_r(e.code,e.details):void 0)?{details:t}:{}}}}var _a=["providerStartFailed","startFailed","notSignedIn","cliMissing","historyTooLarge","managedAccountEnvOverride","accountSwitchInProgress","managedAccountUnsupported","launchFolderMissing","historyInOtherAccount","claudeAccountFolderMissing","claudeAccountSetupFailed","agentCommandNotRunnable","runtimeNotInstalled","providerExited","restartFailed","providerRejected","attachmentInvalid","attachmentUnreadable","emptyMessage","commandUnavailable","queueFull","writeFailed","cancelled","chatClosed","hostRestarted","notDelivered","commandRefused","compactionFailed","compactionUnconfirmed","cancelUnconfirmed","stopRefused","stopFailed","backgroundTaskNotStopped","answerUnconfirmed","hostFault","hostStopped","providerRetrying","usageLimitReached","previousExitUnverifiable","sessionNotRestored"];function _l(e){return"string"==typeof e&&_a.some(t=>t===e)}var _c=["compactionFailed","compactionUnconfirmed","cancelUnconfirmed","stopRefused","stopFailed","backgroundTaskNotStopped","answerUnconfirmed","providerRetrying","usageLimitReached","previousExitUnverifiable","sessionNotRestored"];function _d(e){return _l(e)&&!_c.some(t=>t===e)}var _u=["empty","tooLarge","tooMany","totalTooLarge","unsupportedType","notAFile","noSource"];function _h(e,t){let i=e.trim().slice(0,512).trim();return i?{text:i,audience:t}:void 0}function _f(e,t={}){let i=t.detail?_h(t.detail.text,t.detail.audience):void 0;return{kind:e,...t.account?{account:t.account}:{},...i?{detail:i}:{},...t.refusal?{refusal:t.refusal}:{},...t.attachment?{attachment:t.attachment}:{},...t.retry?{retry:t.retry}:{},...t.usageLimit?{usageLimit:t.usageLimit}:{},...t.argumentProblem?{argumentProblem:t.argumentProblem}:{},...t.neverReachedAgent?{neverReachedAgent:!0}:{},...t.backgroundStop?{backgroundStop:t.backgroundStop}:{},...t.requestTimeout?{requestTimeout:t.requestTimeout}:{}}}function _p(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function _m(e){return"number"==typeof e&&Number.isInteger(e)&&e>0?e:void 0}function _g(e){var t;if(!_p(e)||!_l(e.kind))return;let i=_o(e.refusal),r=function(e){if(!_p(e))return;let t=_u.find(t=>t===e.reason);if(!t)return;let i=e.limit;return"number"==typeof i&&Number.isFinite(i)&&i>0?{reason:t,limit:i}:{reason:t}}(e.attachment),n=function(e){if(!_p(e))return;let t="string"==typeof e.error&&e.error.trim()?e.error.trim():void 0,i=_m(e.status),r="string"==typeof e.cause?_h(e.cause,"person")?.text:void 0,n=_m(e.attempt),s=_m(e.maxRetries),o=n&&s&&s>=n?s:void 0;return t||i||r||n?{...t?{error:t}:{},...i?{status:i}:{},...r?{cause:r}:{},...n?{attempt:n}:{},...o?{maxRetries:o}:{}}:void 0}(e.retry),s=function(e){if("object"!=typeof e||null===e||Array.isArray(e))return;let t={...e},i=yI.find(e=>e===t.window),r="number"==typeof t.resetsAt&&Number.isFinite(t.resetsAt)&&t.resetsAt>0?t.resetsAt:void 0;return i||r?{...i?{window:i}:{},...r?{resetsAt:r}:{}}:void 0}(e.usageLimit),o=yR(e.argumentProblem),a=function(e){if("object"!=typeof e||null===e||Array.isArray(e))return;let{method:t,timeoutMs:i}={...e};return"string"==typeof t&&yA.test(t)&&"number"==typeof i&&Number.isInteger(i)&&i>0?{method:t,timeoutMs:i}:void 0}(e.requestTimeout);return _f(e.kind,{..."managed"===e.account||"system"===e.account?{account:e.account}:{},..._p(t=e.detail)&&"string"==typeof t.text&&("person"===t.audience||"log"===t.audience)?{detail:e.detail}:{},...i?{refusal:i}:{},...r?{attachment:r}:{},...n?{retry:n}:{},...s?{usageLimit:s}:{},...o?{argumentProblem:o}:{},...!0===e.neverReachedAgent?{neverReachedAgent:!0}:{},..."task"===e.backgroundStop||"all"===e.backgroundStop?{backgroundStop:e.backgroundStop}:{},...a?{requestTimeout:a}:{}})}function _b(e){let t=_g(e);return t&&function e(t,i,r){if(r.sameValueLeaves?Object.is(t,i):t===i)return!0;if(Array.isArray(t)||Array.isArray(i))return Array.isArray(t)&&Array.isArray(i)&&t.length===i.length&&t.every((t,n)=>e(t,i[n],r));if(!yE(t)||!yE(i))return!1;if(r.absentKeyEqualsUndefined){for(let n of new Set([...Object.keys(t),...Object.keys(i)]))if(!e(t[n],i[n],r))return!1;return!0}let n=Object.keys(t);return n.length===Object.keys(i).length&&n.every(n=>Object.hasOwn(i,n)&&e(t[n],i[n],r))}(t,e,yP)?t:void 0}var _v="provider_write_failed",_y="claude structured dispatch queue is full",__="codex structured dispatch queue is full",_w="provider_cancelled_before_start",_S={cancelled:"withdrawn",hostRestarted:"undelivered",chatClosed:"undelivered",notDelivered:"undelivered",providerExited:"undelivered",hostStopped:"undelivered",providerStartFailed:"startFailed",startFailed:"startFailed",notSignedIn:"startFailed",cliMissing:"startFailed",historyTooLarge:"startFailed",managedAccountEnvOverride:"startFailed",accountSwitchInProgress:"startFailed",managedAccountUnsupported:"startFailed",launchFolderMissing:"startFailed",historyInOtherAccount:"startFailed",claudeAccountFolderMissing:"startFailed",claudeAccountSetupFailed:"startFailed",agentCommandNotRunnable:"startFailed",runtimeNotInstalled:"startFailed",restartFailed:"startFailed",providerRejected:"content",attachmentInvalid:"content",attachmentUnreadable:"content",emptyMessage:"content",commandUnavailable:"content",commandRefused:"content",queueFull:"transport",writeFailed:"transport",hostFault:"transport"},_x={cancelled:null,hostRestarted:null,chatClosed:null,notDelivered:null,providerExited:"failure",providerStartFailed:"failure",startFailed:"failure",notSignedIn:"failure",cliMissing:"failure",historyTooLarge:"failure",managedAccountEnvOverride:"failure",accountSwitchInProgress:"failure",managedAccountUnsupported:"failure",launchFolderMissing:"failure",historyInOtherAccount:"failure",claudeAccountFolderMissing:"failure",claudeAccountSetupFailed:"failure",agentCommandNotRunnable:"failure",runtimeNotInstalled:"failure",restartFailed:"failure",providerRejected:"failure",attachmentInvalid:"failure",attachmentUnreadable:"failure",emptyMessage:"failure",commandUnavailable:"failure",commandRefused:"failure",queueFull:"failure",writeFailed:"failure",hostFault:"failure",hostStopped:"failure"},_T=new Map([[_w,"cancelled"],["host_restarted_before_delivery","hostRestarted"],["provider_closed_before_delivery","chatClosed"],[_y,"queueFull"],[__,"queueFull"],["not_delivered","notDelivered"]]);function _k(e){var t,i;let{rejection:r}=e,n=_g(r)?.kind;if("object"==typeof r&&null!==r&&!_d(n))return{category:"undelivered",verdict:null};let s=_d(n)?n:(i=t=e.reason)===_v||i?.startsWith(`${_v}: `)===!0?"writeFailed":null===t?void 0:_T.get(t);return s?{category:_S[s],verdict:_x[s],kind:s}:{category:"content",verdict:"failure"}}function _C(e){return e?.dispatchState==="rejected"&&"withdrawn"===_k(e).category}function _L(e){return"object"==typeof e&&null!==e&&"operationId"in e&&"string"==typeof e.operationId&&e.operationId.length>0&&e.operationId.length<=512&&"afterFence"in e&&"number"==typeof e.afterFence&&Number.isSafeInteger(e.afterFence)&&e.afterFence>=0&&"clearedAt"in e&&"number"==typeof e.clearedAt&&Number.isSafeInteger(e.clearedAt)&&e.clearedAt>=0}function _M(e){return e?.kind==="status"&&_L(e.contextClear)}function _R(e){let t=0;for(let i of e)i.sequence>t&&_M(i.body)&&(t=i.sequence);return t}function _I(e,t){return t&&!e.some(e=>_M(e.body))}function _A(e){return void 0===e.latestTurn?function(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(_M(i?.body))break;let r=yx(i?.body);if(r)return"running"===r.state?r.turnId:null}return null}(e.items):e.latestTurn?.turn.state==="running"?e.latestTurn.turn.turnId:null}function _P(e){let t;return void 0===e.latestTurn?(t=function(e){let t=null;for(let i of e)(null===t||i.sequence>=t.sequence)&&(yx(i.body)||_M(i.body))&&(t=i);let i=t?yx(t.body):null;return t&&i?.state==="running"?{item:t,turnId:i.turnId}:null}(e.items))?{kind:"turn",turnItemId:t.item.itemId}:ym:e.latestTurn?.turn.state==="running"?{kind:"turn",turnItemId:e.latestTurn.itemId}:ym}function _E(e,t){return void 0===t||t.includes(e)}function _D(e,t){let i=new Set(t.flatMap(e=>"pending"===e.dispatchState&&void 0!==e.handedOverAt?[yn(e.clientMessageId)]:[]));if(0===i.size)return null;let r={handover:null,handoverAt:-1,settledAt:-1};return(t=>{for(let i of e)t(i)})(e=>{i.has(e.itemId)&&e.turnScope?.kind==="thread"&&e.sequence>r.handoverAt&&(r.handover=e.itemId,r.handoverAt=e.sequence),yx(e.body)&&bU(e)&&(r.settledAt=Math.max(r.settledAt,e.sequence))}),r.handoverAt>r.settledAt?r.handover:null}function _B(e,t,i){let r=_D(i.items,i.submissions),n=null===r?-1:e.findIndex(e=>e.id===r);return -1===n?void 0:t[n]}function _Q(e,t,i){let r,n=e.filter(e=>"tool"===e.role&&void 0!==e.journalPosition&&!i.has(e.id));if(0===n.length)return i;let s=new Set,o=new Map;for(let e of t){s.add(e.itemId);let{sequence:t,index:i}=yl(e),r=`${t}:${i}`;o.set(r,o.has(r)?null:e.itemId)}for(let e of n){let t=e.journalPosition;if(!t||s.has(e.id))continue;let n=o.get(`${t.sequence}:${t.index}`),a=n?i.get(n):void 0;void 0!==a&&(r??=new Map(i)).set(e.id,a)}return r??i}function _j(e){return e.some(e=>void 0!==e.turnScope)}function _F(e,t=[],i){let r=new Set(e.flatMap(e=>"message"===e.body.kind&&"user"===e.body.role?[e.itemId]:[])),n=new Map(e.flatMap(e=>e.turnScope?.kind==="turn"&&r.has(e.itemId)?[[e.itemId,e.turnScope.turnItemId]]:[])),s=new Map;for(let e of t)e.providerItemId&&!s.has(e.providerItemId)&&s.set(e.providerItemId,yn(e.clientMessageId));let o=new Set(t.filter(e=>"pending"===e.dispatchState&&!e.providerItemId&&!yh(e)).map(e=>yn(e.clientMessageId))),a=t.filter(e=>!e.providerItemId&&void 0===e.queuedMessageId&&null!==e.resolvedAt&&_C(e)),l=a.length>0?new Map(e.map(e=>[e.itemId,e])):void 0,c=_O(a),d=yu(a.filter(e=>void 0===e.answeredInTurn).flatMap(e=>{let t=l?.get(yn(e.clientMessageId));return t?[{sent:t,submission:e}]:[]}),({submission:e})=>e),u=new Set,h=new Map,f=null,p=null;for(let t of e){if(r.has(t.itemId)){f=t.itemId,null===p&&o.has(t.itemId)&&(p=t.itemId);continue}let e=yx(t.body);if(!e||!bU(t))continue;let i=_W(t.itemId,e,r,s,n,f,p),a=e.userItemId;if(void 0!==a&&!r.has(a)&&!r.has(s.get(a)??"")&&a!==t.itemId){let r=c.get(t.itemId);if(void 0!==r&&l?.has(r))i=r;else if(i===t.itemId){let r=d.find(({sent:i,submission:r})=>!u.has(i.itemId)&&(void 0!==r.submittedSequence?r.submittedSequencee[i]?.unsent===!0?void 0:t)}function _N(e,t){let i=e.findLastIndex(e=>"user"===e.role&&!0!==e.unsent);return -1===i?void 0:t[i]}var _z="stopped-before-start";function _$(e){return"text"===e.type&&e.presentation===_z}function _q(e,t){let i=yl(e),r=yl(t);return yc(i,r)>0?{sequence:r.sequence,index:r.index-.5}:i}function _K(e){let t=[],i=new Map,r=[];for(let n of e){if("reasoning"===n.role){r.push(n);continue}let{tools:e}=v4(n.blocks);0!==e.length&&(r.length>0&&(i.set(e[0],r),r=[]),t.push(...e))}return{blocks:t,thoughtsBefore:i,thoughtsAfter:r}}function _V(e){let t=new Map;for(let i of e)for(let e of i.blocks)t.has(e)||t.set(e,i.id);return t}function _U(e,t){let i=new Set,r=new Set;for(let n of e.blocks){let e=t.get(n);g9(n)?i.add(`subagent-group:${n.groupId}`):void 0!==e&&g7(n)?r.add(`result:${e}`):void 0!==e&&i.add(`body:${e}`)}let n=[...i,...r],s=i.size>0?[...i]:r.size>0?[...r]:[`body:${e.id}`];return{identity:s,content:n.length>0?n:s}}function _Z(e,t,i){let r=_V(t);return e.map(e=>{let t=_U(e,r);if(!i)return t;let n=t=>`${t}\0${i(e)??""}`;return{identity:t.identity.map(n),content:t.content.map(n)}})}function _G(e,t,i,r,n,s){let o=new Map,a=new Set,l=(e,t)=>{o.set(e.id,t),a.add(t)},c=new Set(t.map(e=>e.id)),d=[],u,h=()=>u??=s?.()??_Z(t,i,n);if(r&&h(),!r&&e?.rows.every(e=>c.has(e.id)))for(let i of t){let t=e.keyById.get(i.id);void 0!==t&&l(i,t)}else if(e){d=e.sources??e.prepareSources?.()??_Z(e.rows,e.messages),h();let i=new Map;d.forEach(({identity:e},t)=>e.forEach(e=>i.set(e,t)));let r=h().map(({identity:e})=>new Set(e.flatMap(e=>i.get(e)??[]))),n=new Map;r.forEach(e=>e.forEach(e=>n.set(e,(n.get(e)??0)+1))),r.forEach((i,r)=>{let[s]=i,o=void 0!==s&&1===i.size&&1===n.get(s)?e.keyById.get(e.rows[s].id):void 0;void 0!==o&&l(t[r],o)})}for(let e of t.filter(e=>!o.has(e.id))){let t=r?.()??e.id;for(let i=1;a.has(t);i+=1)t=`${e.id}~${i}`;l(e,t)}let f=new Map;u?.forEach(({identity:e,content:t},i)=>{e[0].startsWith("result:")||t.forEach(e=>{f.has(e)||f.set(e,i)})});let p=new Map;return d.forEach(({content:i},r)=>{let n=e?.keyById.get(e.rows[r].id);if(void 0!==n&&!a.has(n)){let e=t[Math.min(...i.map(e=>f.get(e)??1/0))];p.set(n,e&&o.get(e.id))}}),{keyById:o,moved:p,...u?{sources:u}:{}}}var _Y=oa(os());function _X(e){return Number.isNaN(e)?1:Math.min(1.8,Math.max(.8,e))}var _J=oa(os()),_0=oa(oe());function _1(){return"web"!==_0.Platform.OS}var _5={minIndexForVisible:1},_2={minIndexForVisible:0};function _3(e){return 80>=function(e){let{contentOffset:t,contentSize:i,layoutMeasurement:r}=e;return i.height-(t.y+r.height)}(e)}var _6=oa(os());function _4(e){return`reasoning:${e}`}var _7={reasoning:"Reasoning",thought:"Thought",thoughtFor:e=>`Thought for ${e}`};function _8(e){return"thoughtFor"===e.kind?_7.thoughtFor(e.duration):_7[e.kind]}var _9=oa(os()),we="compaction-skipped",wt=["update","quit","crash"],wi="orca-stop";function wr(e){let t=v4(e.blocks);return t.markdown.length>0||t.hasImages}var wn={foldedRows:new Set,foldableTurnKeys:new Set},ws=new Map,wo={heads:new Map,joined:new Set},wa=oa(os()),wl=Object.freeze({}),wc=new Set,wd=[];function wu(e){let[t,i]=(0,_6.useState)(()=>({scopeKey:e,keys:new Set})),r=(0,_6.useCallback)(t=>{i(i=>{let r=new Set(i.scopeKey===e?i.keys:[]);if(!r.delete(t)){if(r.size>=128){let e=r.values().next().value;e&&r.delete(e)}r.add(t)}return{scopeKey:e,keys:r}})},[e]);return[t.scopeKey===e?t.keys:wc,r]}var wh=oa(os()),wf=oa(os()),wp=oa(oe()),wm=oa(oe()),wg=oa(oo());function wb({size:e,color:t}){let i=tY(),r=j(!1===i);return i?(0,wg.jsx)(nX,{size:e,color:t,strokeWidth:2}):(0,wg.jsx)(wm.Animated.View,{style:{transform:[{rotate:r}]},children:(0,wg.jsx)(r1,{size:e,color:t,strokeWidth:2})})}var wv=oa(os()),wy=oa(oe()),w_="chat-row:",ww="chat-member:";function wS(e){return`${w_}${e}`}function wx(e){return`${ww}${e}`}function wT(e,t){return Array.from(e.querySelectorAll(`[data-testid^="${t}"]`),e=>({id:e.getAttribute("data-testid")?.slice(t.length)??"",node:e}))}var wk=class extends wv.Component{getSnapshotBeforeUpdate(e){let t=e.layoutKey!==this.props.layoutKey,i=new Set(Array.from(e.runPlacements??[]).flatMap(([e,t])=>this.props.runPlacements?.get(e)!==t?[e]:[]));if("web"===wy.Platform.OS&&e.rowKeys.scope===this.props.rowKeys.scope&&this.props.roots?.capture(i,t),"web"!==wy.Platform.OS||e.rowKeys.scope!==this.props.rowKeys.scope||e.rowKeys.sourceHead===this.props.rowKeys.sourceHead&&!t&&0===i.size||this.props.isFollowing())return null;let r=this.props.listRef.current,n=r?.getScrollableNode(),s=n&&!function({scrollTop:e,scrollHeight:t,clientHeight:i}){return e<0||e>t-i+1}(n)?function(e,{placement:t}){let i=e.getBoundingClientRect(),r=wT(e,w_),n=0,s=r.length;for(;n({key:e,top:i.getBoundingClientRect().top,placed:t(e)});return r.slice(n,o).flatMap(e=>(function(e,t,i){let r=[];for(let{id:n,node:s}of"u">typeof Element&&e instanceof Element?bR(e).map(e=>({node:e,id:void 0!==bL(e)?`root:${bL(e)}`:e.getAttribute("data-testid")?.slice(ww.length)??""})):wT(e,ww)){let e=s.getBoundingClientRect();if(e.top>=t.bottom)break;("run"===n?e.top>=t.top:e.bottom>t.top&&e.top"run"!==e.member);return n.length>0?n:[r[0]??i]})(e.node,i,a(e))).concat([r[o],r[n-1]].flatMap(e=>e?[a(e)]:[]))}(n,e.rowKeys):null;return s&&(b_()||t||function(e,t,i,r){if(!e)return!1;if(void 0===e.member)return t.placement(e.key)!==e.placed;if(e.member.startsWith("root:")){let t=r?.owner(e.member.slice(5)),n=void 0===t?void 0:i?.get(t);return void 0!==n&&n!==e.placed}return e.member.startsWith("result:")||"run"!==e.member&&t.current(e.key)!==e.key}(s[0],this.props.rowKeys,this.props.runPlacements,this.props.roots))?(r?.holdPlace?.(!0),s):null}componentDidMount(){this.props.roots?.restoreAll()}componentDidUpdate(e,t,i){try{let t=e.layoutKey!==this.props.layoutKey;this.props.roots?.restoreAll(t,!1),i&&this.restore(i,t)}finally{this.props.roots?.releaseHold(),i&&this.props.listRef.current?.holdPlace?.(!1)}}restore(e,t){let i=this.props.listRef.current,r=e.length?i?.getScrollableNode():null;if(!r)return;let n=new Map(wT(r,w_).map(({id:e,node:t})=>[e,t]));for(let s of e){let e=function(e,t,i,r){let{key:n,member:s}=e;if(s?.startsWith("root:"))return r?.frame(s.slice(5));if(void 0===s)return i.placement(n)===e.placed?t.get(n):void 0;let o=t.get("run"===s?n:i.current(n)??""),a=s.startsWith("result:")?`call:${s.slice(7)}`:s;return o&&wT(o,ww).find(e=>e.id===s||e.id===a)?.node}(s,n,this.props.rowKeys,this.props.roots);if(e){let n=e.getBoundingClientRect().top-s.top;Math.abs(n)>=.5&&i?.keepInPlace?i.keepInPlace(n,t):Math.abs(n)>=.5&&(r.scrollTop+=n);return}}}render(){return this.props.children??null}},wC=oa(os()),wL=oa(oe()),wM=oa(os()),wR=oa(oe()),wI=oa(oo()),wA=(0,wM.createContext)(null);function wP({positionKey:e,rootIdentity:t=e,owner:i,initialFollow:r=!1,followKey:n,ref:s,children:o,...a}){let l=(0,wM.useContext)(bE),c=(0,wM.useContext)(wA),d=c?`${c.id}/${t}`:t,u=c?`${c.address}/${e}`:e,h=i??c?.owner??d,f=(0,wM.useMemo)(()=>({id:d,address:u,owner:h}),[d,u,h]),p=l?.roots,m=(0,wM.useRef)(null),g=(0,wM.useRef)(void 0),b=(0,wM.useCallback)(e=>{if(m.current=e,"function"==typeof s)return s(e);s&&(s.current=e)},[s]);return(0,wM.useLayoutEffect)(()=>()=>{g.current?.(),g.current=void 0},[p,d]),(0,wM.useLayoutEffect)(()=>{if("web"!==wR.Platform.OS||!p)return;let e=m.current?.getScrollableNode();"u">typeof HTMLElement&&e instanceof HTMLElement&&null!==e.firstElementChild&&(g.current=p.register(d,e,e.firstElementChild,h,u,r),p.layout(d,u,n))}),(0,wI.jsx)(wR.ScrollView,{...a,ref:b,children:(0,wI.jsx)(wA.Provider,{value:f,children:o})})}var wE=oa(oe()),wD=oa(oo());function wB({testID:e,onLongPress:t,style:i,children:r}){return t?(0,wD.jsx)(wE.Pressable,{testID:e,onLongPress:t,accessible:!1,style:i,children:r}):(0,wD.jsx)(wE.View,{testID:e,style:i,children:r})}var wQ=oa(oe());function wj(e,t,i=6){return{fontSize:e*t,lineHeight:(e+i)*t}}var wF=wQ.StyleSheet.create({row:{paddingHorizontal:s6.lg,paddingVertical:s6.sm},rowUser:{alignItems:"flex-end"},content:{maxWidth:"100%",gap:s6.sm},userBubble:{maxWidth:"88%",backgroundColor:s2.textPrimary,borderRadius:s4.card,paddingHorizontal:s6.md,paddingVertical:s6.sm},hostNotice:{color:s2.textMuted},reasoning:{opacity:.7,paddingLeft:15+s6.sm},reasoningToggle:{flexDirection:"row",alignItems:"center",gap:s6.sm,minHeight:32},reasoningPressed:{opacity:.6},reasoningHeadline:{color:s2.textMuted,fontSize:s7.bodySize,flexShrink:1},reasoningCaretOpen:{transform:[{rotate:"90deg"}]},reasoningBody:{maxHeight:240},agentMessage:{paddingLeft:s6.md,borderLeftWidth:2,borderLeftColor:s2.borderSubtle},agentAttribution:{color:s2.textMuted,fontSize:s7.metaSize},meta:{flexDirection:"row",alignItems:"center",gap:s6.xs},unsentNotice:{maxWidth:"88%",marginTop:s6.xs,color:s2.statusRed,fontSize:s7.metaSize},imageRef:{color:s2.textSecondary,fontSize:17},imageThumb:{width:200,height:150,borderRadius:s4.card,backgroundColor:s2.bgRaised,borderWidth:wQ.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle}}),wO=oa(oo());function wW({message:e,markdown:t,fontScale:i,live:r=!1,expanded:n=!1,onToggle:s,onOpenFile:o,onLongPress:a}){let[l,c]=(0,wC.useState)(!1),d=s?n:l,u=_8(function(e,{live:t}){return void 0===e.state||t&&"completed"!==e.state?{kind:"reasoning"}:"completed"!==e.state||void 0===e.completedAt||null===e.timestamp?{kind:"thought"}:{kind:"thoughtFor",duration:G(Math.max(1,(e.completedAt-e.timestamp)/1e3))}}(e,{live:r})),h=_8({kind:"reasoning"});return(0,wO.jsxs)(wL.View,{testID:wx(`thought:${e.id}`),children:[(0,wO.jsxs)(wL.Pressable,{style:({pressed:e})=>[wF.reasoningToggle,e&&wF.reasoningPressed],onPress:()=>s?s(_4(e.id)):c(!d),hitSlop:6,accessibilityRole:"button",accessibilityState:{expanded:d},accessibilityLabel:u===h?h:`${h}: ${u}`,children:[(0,wO.jsx)(n5,{size:15,color:s2.textMuted,strokeWidth:2}),(0,wO.jsx)(wL.Text,{style:wF.reasoningHeadline,numberOfLines:1,children:u}),(0,wO.jsx)(wL.View,{style:d?wF.reasoningCaretOpen:void 0,children:(0,wO.jsx)(rj,{size:14,color:s2.textMuted,strokeWidth:2})})]}),d?(0,wO.jsx)(wH,{positionKey:_4(e.id),markdown:t,fontScale:i,onOpenFile:o,onLongPress:a}):null]})}function wH({positionKey:e,markdown:t,fontScale:i,onOpenFile:r,onLongPress:n}){return(0,wO.jsx)(wP,{positionKey:e,style:wF.reasoningBody,nestedScrollEnabled:!0,children:(0,wO.jsx)(wB,{onLongPress:n,style:wF.reasoning,children:(0,wO.jsx)(tZ,{content:t,rangeSelectable:!0,textScale:1.25*i,onOpenFile:r,onLongPress:n})})})}var wN=(0,oa(os()).createContext)({openImage:()=>{},openActions:()=>{}}),wz=oa(oo());function w$({line:e,onToggleReasoning:t,fontScale:i,onOpenFile:r}){let{reasoning:n,reasoningExpanded:s}=e,o=null!==n&&s,a=X(e),{openActions:l}=(0,wf.useContext)(wN);return(0,wz.jsxs)(wp.View,{children:[(0,wz.jsxs)(wp.Pressable,{style:({pressed:e})=>[wq.row,n&&e&&wq.pressed],onPress:n?()=>t(_4(n.message.id)):void 0,hitSlop:6,accessibilityRole:n?"button":void 0,accessibilityState:n?{expanded:o}:void 0,accessibilityLabel:a,accessibilityLiveRegion:"polite",children:[(0,wz.jsx)(wp.View,{style:wq.glyph,children:(0,wz.jsx)(wb,{size:15,color:s2.textMuted})}),(0,wz.jsx)(wp.Text,{style:wq.label,numberOfLines:1,children:a}),n?(0,wz.jsx)(wp.View,{style:o?wq.caretOpen:void 0,children:(0,wz.jsx)(rj,{size:14,color:s2.textMuted,strokeWidth:2})}):null]}),n&&o?(0,wz.jsx)(wp.View,{style:wq.body,children:(0,wz.jsx)(wH,{positionKey:_4(n.message.id),markdown:n.markdown,fontScale:i,onOpenFile:r,onLongPress:tK?void 0:()=>l(n.message)})}):null]})}var wq=wp.StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:s6.sm,minHeight:32,paddingHorizontal:s6.lg},glyph:{width:15,alignItems:"center",overflow:"visible"},pressed:{opacity:.6},label:{color:s2.textMuted,fontSize:s7.bodySize,flexShrink:1},caretOpen:{transform:[{rotate:"90deg"}]},body:{paddingHorizontal:s6.lg}}),wK=oa(oe()),wV=oa(oo());function wU({toolCallCount:e,toolsExpanded:t,onToggleTools:i,showJumpToTail:r,onJumpToTail:n}){return(0,wV.jsxs)(wK.View,{pointerEvents:"box-none",style:bW.floatingControls,children:[e>0?(0,wV.jsxs)(wK.Pressable,{accessibilityRole:"button",accessibilityLabel:t?"Collapse tool runs":"Expand tool runs",accessibilityState:{expanded:t},style:({pressed:e})=>[bW.toolsPill,e&&bW.pressed],onPress:i,children:[t?(0,wV.jsx)(rq,{size:14,color:s2.textSecondary,strokeWidth:2}):(0,wV.jsx)(rZ,{size:14,color:s2.textSecondary,strokeWidth:2}),(0,wV.jsx)(wK.Text,{style:bW.toolsPillLabel,children:t?"Collapse":`Tools \xb7 ${e}`})]}):null,r?(0,wV.jsx)(wK.Pressable,{accessibilityLabel:"Scroll to latest",style:bW.fab,onPress:n,children:(0,wV.jsx)(nF,{size:18,color:s2.textPrimary,strokeWidth:2.2})}):null]})}var wZ=oa(os()),wG=oa(oe()),wY=oa(oe()),wX=oa(oo());function wJ(e){return"capability"===e.kind?("open"===e.mode?"/ruflo/":"@ruflo/")+e.capability.id:"file"===e.kind?`@${e.path}`:e.token}var w0={command:"Commands",skill:"Skills",file:"Files",capability:"RuFlo capabilities"};function w1({rows:e,onPick:t}){return(0,wX.jsx)(wY.View,{testID:"rupro-chat-suggestion-card",style:w2.card,children:(0,wX.jsx)(wY.ScrollView,{testID:"rupro-chat-suggestions",keyboardShouldPersistTaps:"always",style:w2.scroll,children:e.map((i,r)=>(0,wX.jsxs)(wY.View,{children:[e[r-1]?.kind!==i.kind?(0,wX.jsx)(wY.Text,{style:w2.heading,children:w0[i.kind]}):null,(0,wX.jsx)(w5,{row:i,onPick:t})]},i.id))})})}function w5({row:e,onPick:t}){let i="capability"===e.kind?st:"skill"===e.kind?nc:"command"===e.kind?rF:nk,r="file"===e.kind?null:"capability"===e.kind?e.capability.description:e.description;return(0,wX.jsxs)(wY.Pressable,{accessibilityRole:"button",accessibilityLabel:wJ(e),style:({pressed:e})=>[w2.row,e&&w2.rowPressed],onPress:()=>t(e),children:[(0,wX.jsx)(i,{size:16,color:s2.textSecondary,strokeWidth:2,style:w2.icon}),(0,wX.jsxs)(wY.View,{style:w2.body,children:[(0,wX.jsxs)(wY.View,{style:w2.nameLine,children:[(0,wX.jsx)(wY.Text,{style:w2.name,numberOfLines:1,children:"file"===e.kind?e.path:"capability"===e.kind?e.capability.title:e.token}),"command"===e.kind&&e.argumentHint?(0,wX.jsx)(wY.Text,{style:w2.hint,numberOfLines:1,children:e.argumentHint}):null]}),"capability"===e.kind&&(0,wX.jsxs)(wY.Text,{style:w2.hint,numberOfLines:1,children:[wJ(e)," · ","mention"===e.mode?"Insert reference":e.capability.section?"Open in console":"View reference"]}),r?(0,wX.jsx)(wY.Text,{style:w2.description,numberOfLines:2,children:r}):null]})]})}var w2=wY.StyleSheet.create({card:{marginHorizontal:10,marginBottom:s6.sm,paddingVertical:6,borderRadius:20,borderWidth:wY.StyleSheet.hairlineWidth,borderColor:s2.composerBorder,backgroundColor:s2.bgPanel,overflow:"hidden"},scroll:{maxHeight:300},heading:{color:s2.textMuted,fontSize:11,fontWeight:"600",letterSpacing:.5,textTransform:"uppercase",paddingHorizontal:s6.lg,paddingTop:s6.sm,paddingBottom:s6.xs},row:{flexDirection:"row",gap:10,paddingHorizontal:s6.lg,paddingVertical:s6.sm,minHeight:44},rowPressed:{backgroundColor:s2.bgRaised},icon:{marginTop:2},body:{flex:1,minWidth:0,gap:2},nameLine:{flexDirection:"row",alignItems:"baseline",gap:6},name:{flexShrink:1,color:s2.textPrimary,fontFamily:s7.monoFamily,fontSize:13.5},hint:{flexShrink:1,color:s2.textMuted,fontFamily:s7.monoFamily,fontSize:s7.metaSize},description:{color:s2.textMuted,fontSize:12.5,lineHeight:17}}),w3=oa(os()),w6=oa(oe()),w4=oa(oe()),w7={minHeight:40,color:s2.textPrimary,backgroundColor:s2.bgRaised,borderRadius:s4.input,paddingHorizontal:s6.md,paddingTop:s6.sm,paddingBottom:s6.sm},w8={input:{width:"100%",minHeight:30,maxHeight:154,lineHeight:22,color:s2.textPrimary,paddingHorizontal:6,paddingTop:2,paddingBottom:2},freeInput:{...w7,flex:1,maxHeight:120}},w9=w4.StyleSheet.create({input:{...w8.input,fontSize:iC},freeInput:{...w8.freeInput,fontSize:iC}}),Se=oa(oe()).StyleSheet.create({token:{color:s2.skillToken,backgroundColor:s2.skillTokenSurface}}),St=oa(oo()),Si={field:{color:"transparent",caretColor:s2.textPrimary}};function Sr({value:e,skillToken:t,onSendKey:i,onKeyPress:r,ref:n,...s}){let[o,a]=(0,w3.useState)(0);return(0,St.jsxs)(w6.View,{style:Sn.frame,children:[t?(0,St.jsx)(w6.View,{pointerEvents:"none",style:Sn.copyLayer,children:(0,St.jsxs)(w6.Text,{"aria-hidden":!0,style:[w9.input,Sn.copy,{transform:[{translateY:-o}]}],children:[(0,St.jsx)(w6.Text,{style:Se.token,children:t}),e.slice(t.length)]})}):null,(0,St.jsx)(w6.TextInput,{ref:n,value:e,style:t?[w9.input,Si.field]:w9.input,onScroll:t?e=>{let t;return a("object"==typeof(t="object"==typeof e&&null!==e&&"currentTarget"in e?e.currentTarget:null)&&null!==t&&"scrollTop"in t&&"number"==typeof t.scrollTop?t.scrollTop:0)}:void 0,...s,onKeyPress:e=>{r?.(e);let t=e.nativeEvent;!i||e.defaultPrevented||"Enter"!==t.key||t.shiftKey||t.altKey||t.ctrlKey||t.metaKey||t.isComposing||229===t.keyCode||(e.preventDefault(),t.repeat||i())}})]})}var Sn=w6.StyleSheet.create({frame:{width:"100%",overflow:"hidden"},copyLayer:{...w6.StyleSheet.absoluteFillObject},copy:{maxHeight:void 0}}),Ss=oa(oe()),So=oa(oo());function Sa({images:e,files:t,onRemoveImage:i,onRemoveFile:r}){return 0===e.length&&0===t.length?null:(0,So.jsxs)(Ss.ScrollView,{horizontal:!0,keyboardShouldPersistTaps:"always",showsHorizontalScrollIndicator:!1,style:Sc.strip,contentContainerStyle:Sc.stripContent,children:[e.map(e=>(0,So.jsxs)(Ss.View,{style:Sc.thumb,children:[(0,So.jsx)(Ss.Image,{source:{uri:e.previewUri},style:Sc.thumbImage,resizeMode:"cover"}),i?(0,So.jsx)(Sl,{label:"Remove image",onPress:()=>i(e.id)}):null]},e.id)),t.map(e=>{let t,i;return(0,So.jsxs)(Ss.View,{style:Sc.fileCard,children:[(0,So.jsx)(Ss.View,{style:Sc.fileIcon,children:(0,So.jsx)(nk,{size:17,color:s2.textSecondary,strokeWidth:2})}),(0,So.jsxs)(Ss.View,{style:Sc.fileText,children:[(0,So.jsx)(Ss.Text,{style:Sc.fileName,numberOfLines:1,children:e.name}),(0,So.jsx)(Ss.Text,{style:Sc.fileMeta,numberOfLines:1,children:(t=/\.([a-z0-9]{1,8})$/i.exec(e.name)?.[1],i=/^[^/]+\/([a-z0-9]{1,8})$/i.exec(e.mime)?.[1],`${(t??i??"File").toUpperCase()} \xb7 ${l(e.byteLength)}`)})]}),null===e.path?(0,So.jsx)(Ss.View,{style:Sc.uploading,accessibilityLabel:`Uploading ${e.name}`,children:(0,So.jsx)(Ss.ActivityIndicator,{size:"small",color:s2.textPrimary})}):null,r?(0,So.jsx)(Sl,{label:`Remove ${e.name}`,onPress:()=>r(e.id)}):null]},e.id)})]})}function Sl({label:e,onPress:t}){return(0,So.jsx)(Ss.Pressable,{accessibilityLabel:e,style:Sc.remove,onPress:t,hitSlop:8,children:(0,So.jsx)(r7,{size:11,color:s2.textPrimary,strokeWidth:3})})}var Sc=Ss.StyleSheet.create({strip:{flexGrow:0,marginBottom:10},stripContent:{gap:s6.sm,paddingTop:5,paddingLeft:2,paddingRight:5},thumb:{width:58,height:58,borderRadius:s4.composerItem,backgroundColor:s2.composerControl},thumbImage:{width:"100%",height:"100%",borderRadius:s4.composerItem},fileCard:{height:58,minWidth:140,maxWidth:220,flexDirection:"row",alignItems:"center",gap:9,paddingLeft:10,paddingRight:s6.md,borderRadius:s4.composerItem,backgroundColor:s2.composerControl},fileIcon:{width:32,height:36,borderRadius:7,alignItems:"center",justifyContent:"center",backgroundColor:s2.bgRaised},fileText:{flexShrink:1,minWidth:0},fileName:{color:s2.textPrimary,fontSize:13,fontWeight:"500"},fileMeta:{color:s2.textMuted,fontSize:11.5,marginTop:1},uploading:{...Ss.StyleSheet.absoluteFillObject,borderRadius:s4.composerItem,alignItems:"center",justifyContent:"center",backgroundColor:"rgba(0, 0, 0, 0.45)"},remove:{position:"absolute",top:-5,right:-5,width:20,height:20,borderRadius:10,alignItems:"center",justifyContent:"center",backgroundColor:s2.bgRaised,borderWidth:2,borderColor:s2.composerSurface}}),Sd=oa(oe());function Su(e){return"dispatched"===e.valueSource&&"catalog"===e.transport}function Sh(e){if("unknown"===e.valueSource||"select"!==e.kind.type||!e.kind.currentValue)return null;let t=e.kind.currentValue;return(e.kind.choices.find(e=>e.value===t)??{value:t,label:t}).label}var Sf=oa(oe()),Sp=oa(oo());function Sm({children:e}){return(0,Sp.jsx)(Sf.Text,{style:SS.caption,children:e})}function Sg({primary:e,secondary:t,warning:i,accessibleName:r,disabled:n,onPress:s}){return(0,Sp.jsxs)(Sf.Pressable,{accessibilityLabel:r,accessibilityRole:"button",accessibilityState:{disabled:n},style:({pressed:e})=>[SS.pill,e&&!n&&SS.pressed],onPress:s,disabled:n,hitSlop:6,children:[i?(0,Sp.jsx)(n$,{size:15,color:s2.statusAmber,strokeWidth:2.2}):null,(0,Sp.jsxs)(Sf.Text,{style:SS.pillText,numberOfLines:1,ellipsizeMode:"tail",children:[(0,Sp.jsx)(Sf.Text,{style:[SS.pillPrimary,n&&SS.pillTextDisabled],children:e}),t?(0,Sp.jsx)(Sf.Text,{style:SS.pillSecondary,children:` ${t}`}):null]})]})}function Sb({label:e,description:t,selected:i,disabled:r,grouped:n,divided:s,onPress:o,labelColor:a}){return(0,Sp.jsxs)(Sf.Pressable,{accessibilityRole:"radio",accessibilityState:{checked:i,disabled:r},style:[SS.row,i&&SS.rowSelected,n&&SS.rowGrouped,s&&SS.rowDivided,r&&SS.rowDisabled],onPress:o,disabled:r,children:[(0,Sp.jsxs)(Sf.View,{style:SS.rowBody,children:[(0,Sp.jsx)(Sf.Text,{style:[SS.rowLabel,a?{color:a}:null],children:e}),t?(0,Sp.jsx)(Sf.Text,{style:SS.rowDescription,numberOfLines:2,children:t}):null]}),i?(0,Sp.jsx)(si,{size:18,color:s2.textPrimary,strokeWidth:2.4}):null]})}function Sv({label:e,checked:t,marker:i,disabled:r,grouped:n,onToggle:s}){return(0,Sp.jsxs)(Sf.View,{style:[SS.row,n&&SS.rowGrouped,r&&SS.rowDisabled],children:[(0,Sp.jsx)(Sf.View,{style:SS.rowBody,children:(0,Sp.jsx)(Sf.Text,{style:SS.rowLabel,children:e})}),i?(0,Sp.jsx)(Sf.Text,{style:SS.rowMarker,children:"default"===i?"Default":"Not reported"}):null,(0,Sp.jsx)(Sf.Switch,{accessibilityLabel:e,value:t,onValueChange:s,disabled:r,trackColor:{false:s2.bgRaised,true:s2.textSecondary},thumbColor:s2.textPrimary})]})}function Sy({label:e,disabled:t,grouped:i,onPress:r}){return(0,Sp.jsx)(Sf.Pressable,{accessibilityRole:"button",accessibilityState:{disabled:t},style:[SS.row,i&&SS.rowGrouped,t&&SS.rowDisabled],onPress:r,disabled:t,children:(0,Sp.jsx)(Sf.View,{style:SS.rowBody,children:(0,Sp.jsx)(Sf.Text,{style:SS.rowLabel,children:e})})})}function S_({label:e,value:t,valueColor:i,disabled:r,divided:n,onPress:s}){return s?(0,Sp.jsxs)(Sf.Pressable,{accessibilityLabel:`${e}, ${t}`,accessibilityRole:"button",accessibilityState:{disabled:r},style:({pressed:e})=>[SS.summaryRow,n&&SS.rowDivided,e&&!r&&SS.pressed,r&&SS.rowDisabled],onPress:s,disabled:r,children:[(0,Sp.jsx)(Sf.Text,{style:SS.summaryLabel,children:e}),(0,Sp.jsx)(Sf.Text,{style:[SS.summaryValue,i?{color:i}:null],numberOfLines:1,children:t}),(0,Sp.jsx)(rj,{size:16,color:s2.textMuted,strokeWidth:2.2})]}):(0,Sp.jsxs)(Sf.View,{accessible:!0,accessibilityLabel:`${e}, ${t}`,style:[SS.summaryRow,n&&SS.rowDivided],children:[(0,Sp.jsx)(Sf.Text,{style:SS.summaryLabel,children:e}),(0,Sp.jsx)(Sf.Text,{style:SS.summaryValue,numberOfLines:1,children:t})]})}function Sw({descriptor:e,disabled:t,grouped:i=!1,onSetOption:r,onInvokeAction:n,choiceLabelColor:s}){let o=t||!e.settable;if(e.action?.type==="toggle-command")return(0,Sp.jsx)(Sy,{label:`Toggle ${e.label.toLowerCase()}`,disabled:o,grouped:i,onPress:n});if(e.action?.type==="agent-picker")return(0,Sp.jsx)(Sy,{label:"Choose in agent picker…",disabled:o,grouped:i,onPress:n});if("boolean"===e.kind.type)return(0,Sp.jsx)(Sv,{label:e.label,checked:e.kind.currentValue,marker:"default"===e.valueSource?"default":"unknown"===e.valueSource?"unreported":null,disabled:o,grouped:i,onToggle:e=>r(e)});let{currentValue:a,choices:l}=e.kind;return(0,Sp.jsx)(Sp.Fragment,{children:l.map((e,t)=>(0,Sp.jsx)(Sb,{label:e.label,description:e.description,selected:e.value===a,disabled:o,grouped:i,divided:i&&tr(e.value),labelColor:s?.(e.value)},e.value))})}var SS=Sf.StyleSheet.create({pill:{flexDirection:"row",alignItems:"center",gap:6,height:38,paddingHorizontal:14,borderRadius:19,backgroundColor:s2.composerControl},pillText:{flexShrink:1,fontSize:s7.bodySize},pillPrimary:{color:s2.textPrimary,fontWeight:"500"},pillSecondary:{color:s2.textMuted},pillTextDisabled:{color:s2.textMuted},pressed:{opacity:.7},caption:{color:s2.textMuted,fontSize:s7.metaSize,paddingHorizontal:s6.md,paddingBottom:s6.xs},rowMarker:{color:s2.textMuted,fontSize:s7.metaSize},row:{flexDirection:"row",gap:s6.sm,paddingHorizontal:14,paddingVertical:s6.sm,minHeight:50,alignItems:"center",borderRadius:s4.card,backgroundColor:s2.bgRaised,borderWidth:1,borderColor:s2.borderSubtle,marginBottom:s6.xs},rowSelected:{borderColor:s2.textSecondary},rowGrouped:{marginBottom:0,borderWidth:0,borderRadius:0,backgroundColor:"transparent"},rowDivided:{borderBottomWidth:Sf.StyleSheet.hairlineWidth,borderBottomColor:s2.composerBorder},rowDisabled:{opacity:.5},rowBody:{flex:1,gap:2},rowLabel:{color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"},rowDescription:{color:s2.textSecondary,fontSize:s7.metaSize},summaryRow:{minHeight:50,flexDirection:"row",alignItems:"center",gap:s6.sm,paddingHorizontal:14,paddingVertical:s6.sm},summaryLabel:{flex:1,color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"},summaryValue:{maxWidth:160,color:s2.textSecondary,fontSize:s7.bodySize}}),Sx=oa(oe()),ST=oa(oo());function Sk(e){return"thought_level"===e.category&&"select"===e.kind.type&&!e.action&&e.kind.choices.length>1&&e.kind.choices.length<=5}function SC({descriptor:e,disabled:t,onSetOption:i}){if("select"!==e.kind.type)return null;let{choices:r,currentValue:n}=e.kind;return(0,ST.jsxs)(Sx.View,{style:SL.block,children:[(0,ST.jsx)(Sx.Text,{style:SL.label,children:e.label}),(0,ST.jsx)(Q,{segments:r,selected:"unknown"===e.valueSource?void 0:n,onSelect:i,fill:!0,disabled:t||!e.settable}),Su(e)?(0,ST.jsx)(Sm,{children:"Sent to the agent — not confirmed"}):null]})}var SL=Sx.StyleSheet.create({block:{marginTop:s6.md},label:{color:s2.textMuted,fontSize:s7.metaSize,paddingHorizontal:s6.xs,paddingBottom:6}}),SM="permissionMode",SR={modes:["ask","full-access"]},SI=new Map([["claude",{modes:["ask","accept-edits","auto","full-access"],autoNeedsModelSupport:!0}],["codex",{modes:["ask","auto","full-access"]}],["grok",SR],["opencode",SR],["opencode2",SR],["omp",SR],["antigravity",{modes:["ask","accept-edits","full-access"]}]]);function SA(e){return SI.get(e)??null}function SP(e){return{agent:e,valuesByModel:{}}}function SE(e){return e?.kind==="toggle-command"}function SD(e,t,i){return t?e.valuesByModel[t]?.[i]:void 0}function SB(e,t,i){if(!t)return;let r=e.valuesByModel[t];if(!r||!(i in r))return;let n={...r};delete n[i],0===Object.keys(n).length?delete e.valuesByModel[t]:e.valuesByModel[t]=n}function SQ(e){let t="string"==typeof e.model?.value?e.model.value:null;e.model=void 0,t&&delete e.valuesByModel[t]}function Sj(e,t,i,r,n=null){if("model"===t)return e.model={value:i,source:r},"string"==typeof i?i:null;let s=("string"==typeof e.model?.value?e.model.value:null)??n;return s?(e.valuesByModel[s]={...e.valuesByModel[s],[t]:{value:i,source:r}},s):null}function SF(e,t,i){let r=e=>void 0===i||i.includes(e)?"reported":"dispatched",n="string"==typeof t.model?t.model:null;if(!n)return!1;let s=e.model?.value!==n,o=s||e.model?.source!==r("model");e.model={value:n,source:r("model")};let a=s?{}:{...e.valuesByModel[n]};for(let[e,i]of Object.entries(t)){if("model"===e)continue;let t=a[e];(t?.value!==i||t.source!==r(e))&&(o=!0),a[e]={value:i,source:r(e)}}return e.valuesByModel[n]=a,o}function SO(e,t){let i=t.trim().toLowerCase();if(!i)return null;if(0===e.models.length)return t.trim();let r=e.models.find(e=>e.id.toLowerCase()===i);if(r)return r.id;let n=e.models.find(e=>e.label.toLowerCase()===i);if(n)return n.id;let s=null;for(let t of e.models)(null===s||t.id.length>s.length)&&i.includes(t.id.toLowerCase())&&(s=t.id);return s}function SW(e){if("draft"===e.mode)return e.apply.launchArgs||e.apply.composedIntoModel?{settable:!0}:{settable:!1,disabledReason:"available-after-session-start"};if("agent-session"===e.liveTransport||e.apply.composedIntoModel&&e.composedModelApply?.midSession?.kind==="command")return{settable:!0};let t=e.apply.midSession;return t&&"unsupported"!==t.kind?{settable:!0}:{settable:!1,disabledReason:"set-when-session-starts"}}function SH(e,t,i,r){if("live"===i&&"agent-session"!==r)return e.midSession?.kind==="agent-picker"?{type:"agent-picker"}:SE(e.midSession)&&!t?{type:"toggle-command"}:void 0}var SN={thought_level:0,model_config:1,mode:2};function Sz(e,t,i){let r="string"==typeof i.model?.value?i.model.value:null;return!r||t.some(e=>e.id===r)?[...t]:[...t,e.models.find(e=>e.id===r)??{id:r,label:r,options:[]}]}function S$(e,t,i){return i||!e.defaultModelIsCliDefault?null:t.find(e=>e.isDefault)?.id??null}function Sq(e,t,i){let r="string"==typeof i.model?.value?i.model.value:null;return r??S$(e,t,r)}function SK(e){let{catalog:t,models:i,record:r,mode:n,modelLabel:s,liveTransport:o}=e;if(0===i.length)return[];let a=r.model,l=i.map(({id:e,label:t,description:i})=>({value:e,label:t,...i?{description:i}:{}})),c="string"==typeof a?.value?a.value:null,d=S$(t,i,c),u=c??d,h=SH(t.modelApply,a,n,o),f=[{id:"model",label:s,category:"model",kind:{type:"select",...u?{currentValue:u}:{},choices:l},valueSource:a?.source??(d?"default":"unknown"),transport:o,...SW({mode:n,liveTransport:o,apply:t.modelApply}),...h?{action:h}:{}}];if(!u)return f;let p=i.find(e=>e.id===u),m=r.valuesByModel[u]??{};for(let e of p?.options??[]){let i=function(e){let{option:t,tracked:i,mode:r,liveTransport:n,modelIsCliDefault:s,composedModelApply:o}=e,a=SH(t.apply,i,r,n),l=SW({mode:r,liveTransport:n,apply:t.apply,composedModelApply:o}),c=s&&"select"===t.kind.type&&!0===t.kind.defaultIsCliDefault,d=!i&&(c||"draft"===r&&!s),u=i?.source??(d?"default":"unknown");if("select"===t.kind.type){let e,r,s=(e=[...t.kind.choices],(r="string"==typeof i?.value?i.value:null)&&!e.some(e=>e.value===r)&&e.push({value:r,label:r}),e);if(s.length<=1)return null;let o="string"==typeof i?.value?i.value:d?t.kind.defaultValue:void 0;return{id:t.id,label:t.label,...t.description?{description:t.description}:{},...t.category?{category:t.category}:{},kind:{type:"select",...void 0===o?{}:{currentValue:o},choices:s},valueSource:u,transport:n,...l,...a?{action:a}:{}}}let h="boolean"==typeof i?.value?i.value:t.kind.defaultValue;return{id:t.id,label:t.label,...t.description?{description:t.description}:{},...t.category?{category:t.category}:{},kind:{type:"boolean",currentValue:h},valueSource:u,transport:n,...l,...a?{action:a}:{}}}({option:e,tracked:m[e.id],mode:n,liveTransport:o,modelIsCliDefault:u===d,composedModelApply:t.modelApply});i&&f.push(i)}return f}var SV=oa(oo());function SU(e){return"full-access"===e?s2.statusAmber:void 0}function SZ({controller:e,isWorking:t,sendInFlight:i=!1,presentation:r,onNavigate:n,onDrawerOpen:s,onDrawerAfterClose:o}){let{snapshot:a,pendingId:l}=e,c=a.find(e=>"model"===e.category),d=a.find(e=>e.id===SM),u=a.filter(e=>"model"!==e.category&&e.id!==SM).sort((e,t)=>(SN[e.category??""]??3)-(SN[t.category??""]??3));if(!c&&!d)return null;let h=c??d,f=a.find(e=>e.id===r?.page),p=void 0!==f&&f===d,m=void 0!==f&&f===h,g=null!==l||i,b=t||g,v=function(e){switch(e){case"set-when-session-starts":return"Set when the session starts.";case"available-after-session-start":return"Available after the session starts.";case void 0:return null}}(f?.disabledReason),y=d?.kind.type==="select"?d.kind.choices.find(e=>e.value===d.kind.currentValue):void 0,_=SU(y?.value),w=void 0!==_,S=u.filter(Sk),x=u.filter(e=>!S.includes(e)),T=c?Sh(c)??"Model":y?.label??"Permissions",k=c&&u.length>0?function(e){let t=[];for(let i of e)if("unknown"!==i.valueSource&&("serviceTier"!==i.id||"select"!==i.kind.type||"default"!==i.kind.currentValue))if("select"===i.kind.type){let e=Sh(i);e&&t.push(e)}else!0===i.kind.currentValue&&t.push("fastMode"===i.id?"Fast":i.label);if(t.length>0)return t.join(" · ");let i=e.find(e=>"effort"===e.id);return i?i.label:"Options"}(u):null,C=()=>n(null),L=(t,i)=>{"unknown"!==t.valueSource&&"select"===t.kind.type&&t.kind.currentValue===i||(t===d&&n(t===h?null:h.id),e.setOption(t.id,i).then(e=>{e&&t!==h&&t!==d&&n(h.id)}))};return(0,SV.jsxs)(Sd.View,{style:SY.pillSlot,children:[(0,SV.jsx)(Sg,{primary:T,secondary:k,warning:w,accessibleName:c?`Model, ${k?`${T} ${k}`:T}${w?", full access":""}`:`Permissions, ${T}`,disabled:g,onPress:()=>{s(h.id),Sd.Keyboard.dismiss()}}),(0,SV.jsx)(iD,{visible:void 0!==f,onClose:C,onAfterClose:o,children:f?(0,SV.jsxs)(Sd.View,{style:SY.sheet,children:[(0,SV.jsxs)(Sd.View,{style:SY.sheetHeader,children:[(0,SV.jsx)(Sd.Pressable,{accessibilityLabel:m?"Close picker":"Back to models",accessibilityRole:"button",style:({pressed:e})=>[SY.sheetNav,e&&SY.pressed],onPress:m?C:()=>n(h.id),hitSlop:8,children:m?(0,SV.jsx)(r7,{size:18,color:s2.textSecondary,strokeWidth:2.2}):(0,SV.jsx)(rO,{size:18,color:s2.textSecondary,strokeWidth:2.2})}),(0,SV.jsx)(Sd.Text,{style:SY.sheetTitle,children:f.label}),(0,SV.jsx)(Sd.View,{style:SY.sheetHeaderSide,children:null!==l?(0,SV.jsx)(Sd.ActivityIndicator,{size:"small",color:s2.textSecondary}):null})]}),Su(f)?(0,SV.jsx)(Sm,{children:"Sent to the agent — not confirmed"}):null,v?(0,SV.jsx)(Sm,{children:v}):null,(0,SV.jsx)(Sd.View,{style:SY.group,children:(0,SV.jsx)(Sw,{descriptor:f,disabled:p?g:b,grouped:!0,onSetOption:e=>L(f,e),onInvokeAction:()=>{e.invokeAction(f.id).then(e=>{e&&C()})},...p?{choiceLabelColor:SU}:{}})}),m&&c?(0,SV.jsxs)(SV.Fragment,{children:[S.map(e=>(0,SV.jsx)(SC,{descriptor:e,disabled:b,onSetOption:t=>L(e,t)},e.id)),(0,SV.jsx)(SG,{descriptors:[...x,...d?[d]:[]],permission:d,permissionColor:_,locked:b,busy:g,onNavigate:n,onSetOption:L})]}):null]}):null})]})}function SG({descriptors:e,permission:t,permissionColor:i,locked:r,busy:n,onNavigate:s,onSetOption:o}){return 0===e.length?null:(0,SV.jsx)(Sd.View,{style:[SY.group,SY.groupSpaced],children:e.map((a,l)=>{let c=a===t,d=c?n:r;if("boolean"===a.kind.type&&!a.action)return(0,SV.jsx)(Sd.View,{style:lo(a,e),onInvokeAction:()=>s(a.id)})},a.id);let u="boolean"===a.kind.type?a.kind.currentValue?"On":"Off":"unknown"===a.valueSource?"Not set":Sh(a)??"Not set";return(0,SV.jsx)(S_,{label:c?"Permissions":a.label,value:u,valueColor:c?i:void 0,disabled:d,divided:ls(a.id):void 0},a.id)})})}var SY=Sd.StyleSheet.create({pillSlot:{flexShrink:1,minWidth:0},sheet:{paddingBottom:s6.xs},sheetHeader:{flexDirection:"row",alignItems:"center",paddingBottom:s6.lg},sheetTitle:{flex:1,color:s2.textPrimary,fontSize:s7.titleSize,fontWeight:"700",textAlign:"center"},sheetNav:{width:36,height:36,borderRadius:18,alignItems:"center",justifyContent:"center",backgroundColor:s2.bgRaised,borderWidth:Sd.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle},sheetHeaderSide:{width:36,height:36,alignItems:"center",justifyContent:"center"},group:{overflow:"hidden",borderRadius:s4.card,backgroundColor:s2.bgRaised},groupSpaced:{marginTop:s6.md},divided:{borderBottomWidth:Sd.StyleSheet.hairlineWidth,borderBottomColor:s2.composerBorder},pressed:{opacity:.7}}),SX=oa(os()),SJ=oa(oe()),S0=/[^\s]/;function S1(e,t,i=8){let r=t.toLowerCase();if(0===r.length)return e.slice(0,i);let n=[],s=[];for(let t of e){let e=t.toLowerCase(),o=e.slice(e.lastIndexOf("/")+1);if(e.startsWith(r)||o.startsWith(r)?n.push(t):s.length=i)break}return[...n,...s].slice(0,i)}function S5(e){let t=e.codePointAt(0)??0;return!(t<=31||t>=127&&t<=159||8203===t||8206===t||8207===t||1564===t||8288===t||65279===t||8232===t||8233===t||t>=8234&&t<=8238||t>=8294&&t<=8297)}function S2(e,t){return(ol??=new Intl.Collator(void 0,{sensitivity:"base"})).compare(e,t)}var S3={repo:0,home:1,bundled:2,plugin:3};function S6(e,t,i){let r=[...t].sort(S9);return{kind:"skill",id:`skill:${e}`,name:e,token:`${i}${e}`,description:r[0]?.description?S8(r[0].description,240):null,sources:r.map(e=>({sourceKind:e.sourceKind,skillFilePath:e.skillFilePath}))}}function S4(e,t,i=!0){return t?e.map(e=>{var r;let n,s;return{...e,rank:(r=e.item,n=t.toLocaleLowerCase(),(s=r.name.toLocaleLowerCase())===n?0:s.startsWith(n)?1:s.includes(n)?2:!function(e,t){let i=0;for(let r of t)if(r===e[i]&&(i+=1),i===e.length)return!0;return!1}(n,s)?i&&r.description?.toLocaleLowerCase().includes(n)?4:null:3)}}).filter(e=>null!==e.rank).sort((e,t)=>e.rank-t.rank||e.stableOrder-t.stableOrder).map(e=>e.item):e.map(e=>e.item)}function S7(e){return e.length>0&&e.length<=200&&!/\s/u.test(e)&&[...e].every(S5)}function S8(e,t){return[...e].filter(S5).join("").slice(0,t)}function S9(e,t){return S3[e.sourceKind]-S3[t.sourceKind]||S2(e.name,t.name)||e.skillFilePath.localeCompare(t.skillFilePath)}var xe=Object.keys(S3).length;function xt(e){let t=e.sources[0]?.sourceKind;return void 0===t?xe:S3[t]}function xi(e,t){return xt(e)-xt(t)||S2(e.name,t.name)}var xr=[{name:"clear",description:"Clear conversation context"},{name:"compact",description:"Compact conversation context"}],xn=[{name:"model",description:"Choose the model"},{name:"effort",description:"Choose reasoning effort"}];function xs(e){if(!e.startsWith("/"))return null;let t=/^\/([^\s]+)(?:\s+(.*))?$/.exec(e.trimEnd());return t?{name:t[1].toLowerCase(),argument:t[2]?.trim()??""}:null}function xo(e,t="codex"){let i=xs(e);return!!(i&&[...xn,...xr,...function(e){let t=vl(e);if(t?.expandsSlashCommandsFromText)return[];let i=new Set(t?.textDrivenCommands??[]);return vc(e).filter(e=>!i.has(e.name))}(t)].some(e=>e.name===i.name))}async function xa(e,t){let i=xs(e);if(i?.name==="goal"&&t.setThreadGoalObjective)return i.argument?{handled:!0,accepted:await t.setThreadGoalObjective(i.argument),error:null}:{handled:!0,accepted:!1,error:"Describe the goal after /goal."};if(!i||!xo(e,t.agent))return{handled:!1,accepted:!1,error:null};if("clear"===i.name||"compact"===i.name)return i.argument?{handled:!0,accepted:!1,error:`Use /${i.name} without arguments.`}:t.conversationCommands?.includes(i.name)&&t.runConversationCommand?{handled:!0,...await t.runConversationCommand(i.name)}:{handled:!0,accepted:!1,error:`/${i.name} is not supported by this chat host.`};if("model"!==i.name&&"effort"!==i.name){var r;return r=i.name,{handled:!0,accepted:!0,error:`/${r} is not available in chat sessions. Use the slash menu to see available commands.`}}let n=t.snapshot.find(e=>e.id===i.name);if(!n||"select"!==n.kind.type)return{handled:!0,accepted:!0,error:`${"model"===i.name?"Models":"Reasoning effort"} are unavailable for this chat session.`};if(!i.argument){let e=await t.invokeAction(i.name);return{handled:!0,accepted:e,error:e?null:`Could not open the ${i.name} picker.`}}let s=i.argument.toLowerCase(),o=n.kind.choices.find(e=>e.value.toLowerCase()===s||e.label.toLowerCase()===s);if(!o)return{handled:!0,accepted:!1,error:`${i.argument} is not an available ${i.name} for this chat session.`};let a=await t.setOption(i.name,o.value);return{handled:!0,accepted:a,error:a?null:`Could not apply ${i.name} ${o.label}.`}}function xl(e){return vc(e).filter(e=>void 0===e.reply)}function xc({agent:e,structured:t,query:i},r){if(!e)return[];let n=t?.reported;return function(e,t,i,r,n,s=50,o="/"){let a="/"===r,l=function(e,t,i,r){let n=new Map;for(let t of e)t.installed&&!n.has(t.skillFilePath)&&n.set(t.skillFilePath,t);let s=new Map;for(let e of n.values()){let t=function(e){if(S7(e.name))return e.name;let t=e.directoryPath.split(/[\\/]/).findLast(Boolean)??"";return S7(t)?t:null}(e);t&&s.set(t,[...s.get(t)??[],{...e,name:t}])}let o=new Map([...s.entries()].map(([e,t])=>[e,S6(e,t,r)]));return[...new Set(void 0!==t?[...t.map(e=>e.name).filter(S7),...[...o.keys()].filter(e=>i.has(e))]:[...o.keys()])].map(e=>{let i=o.get(e)??S6(e,[],r),n=t?.find(t=>t.name===e)?.description;return null===i.description&&n?{...i,description:S8(n,240)}:i}).sort(xi)}(t,n,new Set(e.filter(e=>e.kindUnspecified).map(e=>e.name)),r),c=new Set(l.map(e=>e.name)),d=new Set(e.filter(e=>e.orcaOwned).map(e=>e.name)),u=e.filter(e=>e.orcaOwned||!(d.has(e.name)||a&&e.kindUnspecified&&c.has(e.name))),h=new Set(u.filter(e=>!e.orcaOwned).map(e=>e.name)),f=S4(u.map((e,t)=>({item:{kind:"command",id:`command:${e.name}`,name:e.name,token:`/${e.name}`,description:e.description?S8(e.description,240):void 0,argumentHint:e.argumentHint?S8(e.argumentHint,80):void 0,skillCollision:a&&!e.orcaOwned&&c.has(e.name),...e.orcaOwned?{orcaOwned:!0}:{}},stableOrder:t})),i),p=S4(l.filter(e=>!(a&&h.has(e.name))).map((e,t)=>({item:e,stableOrder:t})),i,"/"===o);return[...f.slice(0,s),...p.slice(0,s)]}(t?function(e,t,i){let r,n=function(e=[],t){let i=[...xn,...xr.filter(t=>e.includes(t.name))];return[...i,...(function(e){if(!e)return[];let t=new Set(vl(e)?.textDrivenCommands??[]);return 0===t.size?[]:vc(e).filter(e=>t.has(e.name))})(t).filter(e=>!i.some(t=>t.name===e.name))]}(t,e);if(void 0===i)return n;let s=new Set(n.map(({name:e})=>e));return[...n,...(r=new Map((vs[e]??vi).map(e=>[e.name,e.description])),i.filter(e=>"command"===e.kind).map(e=>{let t=e.description??r.get(e.name);return{name:e.name,...t?{description:t}:{},...e.argumentHint?{argumentHint:e.argumentHint}:{},...e.kindUnspecified?{kindUnspecified:!0}:{}}})).filter(({name:e})=>!s.has(e))]}(e,t.conversationCommands,n):xl(e),[],i,vl(e)?.skillPrefix??"/",n?n.flatMap(e=>"skill"===e.kind?[{name:e.name,...e.description?{description:e.description}:{}}]:[]):[],r)}function xd(){}var xu=oa(oe()),xh=oa(oe()),xf={width:38,height:38,borderRadius:19,alignItems:"center",justifyContent:"center"},xp=xh.StyleSheet.create({composerInset:{paddingHorizontal:10,paddingTop:6,paddingBottom:s6.sm},bar:{paddingTop:s6.md,paddingHorizontal:10,paddingBottom:10,borderWidth:xh.StyleSheet.hairlineWidth,borderColor:s2.composerBorder,borderRadius:s4.composer,backgroundColor:s2.composerSurface,shadowColor:"#000",shadowOpacity:.45,shadowRadius:15,shadowOffset:{width:0,height:10},elevation:8},actionRow:{marginTop:10,flexDirection:"row",alignItems:"center",gap:s6.sm},actionSpacer:{flex:1},controlButton:{...xf,backgroundColor:s2.composerControl},ghostButton:{...xf},sendButton:{...xf,backgroundColor:s2.surfaceBright},sendButtonDisabled:{backgroundColor:s2.composerControl},pressed:{opacity:.7}}),xm=oa(oo());function xg({onStop:e,held:t}){return(0,xm.jsx)(xu.Pressable,{style:({pressed:e})=>[xp.controlButton,e&&xp.pressed],onPress:e,disabled:t,accessibilityRole:"button",accessibilityLabel:t?U.stopping:"Stop the agent",children:t?(0,xm.jsx)(xu.ActivityIndicator,{size:"small",color:s2.textPrimary}):(0,xm.jsx)(se,{size:13,color:s2.textPrimary,strokeWidth:2.4,fill:s2.textPrimary})})}var xb=oa(oo()),xv=[],xy=[],x_=[];function xw({inputRef:e,value:t,onChangeText:i,onSend:r,sendSurfaceId:n,getSendCompletionGeneration:s,getComposerEditGeneration:o,agent:a=null,structured:l=null,sessionOptions:c,onAttachImage:d,attachments:u=xy,onRemoveAttachment:h,isAttaching:f=!1,onMicPress:p,micActive:m=!1,dictationMode:g="toggle",onMicPressIn:b,onMicPressOut:v,disabled:y=!1,sendDisabled:_=!1,placeholder:w="Message, @files, /commands",filePaths:S=xv,onNeedFiles:x,stop:T=null}){var k,C;let L,M,R=(0,wZ.useRef)(null),I=e??R,[A,P]=(0,wZ.useState)(!1),[E,D]=(0,wZ.useState)(!1),[B,Q]=(0,wZ.useState)(null),j=c?.controller.optionPickerRequest,[F,O]=(0,wZ.useState)(j);j&&F!==j&&(O(j),Q({page:j.id,refocus:!1}));let W=l?.files??x_,H=function(e){let{value:t,onChangeText:i,agent:r,structuredCatalog:n,filePaths:s}=e,o=(0,SX.useContext)(of),[a,l]=(0,SX.useState)(null),[c,d]=(0,SX.useState)(0),[u,h]=(0,SX.useState)(null),[f,p]=(0,SX.useState)(null),m=(0,SX.useMemo)(()=>new Set(xc({agent:r,structured:n,query:""},1/0).flatMap(e=>"skill"===e.kind?[e.token]:[])),[r,n]),g=function(e,t){let i=e.indexOf(" ");if(i<=0)return null;let r=e.slice(0,i);return t.has(r)?r:null}(t,m),b=e=>{e.startsWith("/")||p(null),i(e)},v=(0,SX.useMemo)(()=>(function(e,t){let i=Math.max(0,Math.min(t,e.length)),r=i-1;for(;r>=0&&S0.test(e[r]);)r--;let n=r+1;if(i<=n)return null;let s=e[n];if("@"!==s&&"/"!==s)return null;let o=0===n?"":e[n-1];if("/"===s&&0!==n||"@"===s&&0!==n&&!/\s/.test(o))return null;let a=e.slice(n+1,i);return/\s/.test(a)?null:{kind:"@"===s?"file":"slash",query:a,start:n,end:i}})(t,c),[t,c]),y=v?.kind??null,_=v?.query??"",w="file"===y&&v?.start===0,S=null!==y;(0,SX.useEffect)(()=>{if(!S||!o)return;let e=!0;return o.load().then(t=>{e&&l({owner:o,rows:t})},()=>{}),()=>{e=!1}},[S,o]);let x=a?.owner===o?a?.rows:void 0,T=(0,SX.useMemo)(()=>{var e;let t,i,o,a,l,c=x&&"skill"!==f?(t=_.toLowerCase().replace(/^ruflo(?:[:/-]|$)/u,"").split(/[-/\s]+/u).filter(Boolean),i=x.filter(({id:e,title:i,description:r})=>{let n=`${e} ${i} ${r}`.toLowerCase();return t.every(e=>n.includes(e))}),o=t.join("-"),a=({id:e,title:i,section:r})=>o&&e===o?0:o&&i.toLowerCase().startsWith(t.join(" "))?1:r?2:3,i.sort((e,t)=>a(e)-a(t)).slice(0,12)).map(e=>({id:"ruflo-capability:"+e.id,kind:"capability",capability:e,mode:"slash"===y?"open":"mention"})):[];if("file"===y){let e=S1(s,_).map(e=>({kind:"file",id:`file:${e}`,path:e})),t=w?xc({agent:r,structured:n,query:_},10):[];return _?[...c,...e,...t]:[...e,...c,...t]}if("slash"!==y)return[];let d=(e=xc({agent:r,structured:n,query:_},10),(l=f?e.filter(e=>e.kind===f):[]).length>0?l:e);return _?[...c,...d]:[...d,...c]},[r,x,w,s,f,y,_,n]),{onNeedFiles:k,onSlashMenuOpen:C}=e;(0,SX.useEffect)(()=>{v?.kind==="file"&&k?.(v.query)},[k,v?.kind,v?.query]);let L=v?.kind==="slash"||w;(0,SX.useEffect)(()=>{L&&C?.()},[C,L]);let M=e=>{d(e),h({start:e,end:e})};return{onFieldChange:e=>{let i=g?function(e,t,i){let r=`${i} `;if(t.startsWith(r))return t;let n=e.slice(r.length);return t.length{var n;let s;if(!v)return;if(p(null),"capability"===r.kind&&"open"===r.mode){o?.open(r.capability)&&(i(t.slice(v.end).trimStart()),M(0),SJ.Keyboard.dismiss());return}if(e.focusField(),"skill"===r.kind){let e=t.slice(v.end).trimStart();i(`${r.token} ${e}`),M(r.token.length+1);return}let a=(n=wJ(r),s=`${n} `,{text:t.slice(0,v.start)+s+t.slice(v.end),cursor:v.start+s.length});b(a.text),M(a.cursor)},openSlashMenu:r=>{let n=(g?t.slice(g.length+1):t).trimStart();i(n?`/ ${n}`:"/"),p(r),M(1),e.focusField()},openFileMenu:()=>{let i=t.slice(0,c),r=0===i.length||/\s$/.test(i)?"@":" @";b(i+r+t.slice(c)),M(i.length+r.length),e.focusField()},pendingSelection:u,onSelectionChange:e=>{d(e.end),h(null)},resetCursor:()=>d(0)}}({value:t,onChangeText:i,agent:a,structuredCatalog:l?.catalog,filePaths:S,onNeedFiles:x,onSlashMenuOpen:l?.onSlashMenuOpen,focusField:()=>I.current?.focus()}),N=(0,wZ.useRef)(!1),z=(0,wZ.useRef)(!0),$=(0,wZ.useRef)(n),q=(0,wZ.useRef)(0);(0,wZ.useLayoutEffect)(()=>{$.current!==n&&($.current=n,q.current+=1)},[n]);let[K,V]=(0,wZ.useState)(!1),U=c?.controller.pendingId!=null,Z=W.some(e=>null===e.path),G=u.length+W.length,Y=(t.trim().length>0||G>0)&&!y&&!_&&!K&&!f&&!Z&&!U,X=(L=0===(k={canStop:null!==T,sendBlocked:_,canSend:Y,editing:f||Z||m,draft:t,attachmentCount:G}).draft.trim().length&&0===k.attachmentCount,k.canStop&&(k.sendBlocked||L||!k.editing&&!k.canSend));(0,wZ.useEffect)(()=>(z.current=!0,()=>{z.current=!1,q.current+=1}),[]);let J=async()=>{if(!Y||N.current)return;N.current=!0,V(!0);let e=q.current,i=s(),n=o();try{await r(t)&&z.current&&e===q.current&&i===s()&&n===o()&&(H.resetCursor(),wG.Keyboard.dismiss())}finally{N.current=!1,V(!1)}},ee=l?()=>D(!0):d,et=l?"Add to message":"Attach image";return(0,xb.jsxs)(wG.View,{testID:"rupro-chat-composer-shell",children:[H.rows.length>0?(0,xb.jsx)(w1,{rows:H.rows,onPick:H.pick}):null,(0,xb.jsx)(wG.View,{style:xp.composerInset,testID:"native-chat-composer-inset",children:(0,xb.jsxs)(wG.View,{style:xp.bar,testID:"native-chat-composer",children:[(0,xb.jsx)(Sa,{images:u,files:W,onRemoveImage:h,onRemoveFile:l?.onRemoveFile}),(0,xb.jsx)(Sr,{ref:I,value:t,skillToken:H.skillToken,onSendKey:J,onChangeText:H.onFieldChange,onFocus:()=>P(!0),onBlur:()=>P(!1),selection:H.pendingSelection??void 0,onSelectionChange:e=>H.onSelectionChange(e.nativeEvent.selection),placeholder:w,placeholderTextColor:s2.textMuted,selectionColor:s2.accentBlue,multiline:!0,textAlignVertical:"top"}),(0,xb.jsxs)(wG.View,{style:xp.actionRow,testID:"native-chat-composer-actions",children:[ee?(0,xb.jsx)(wG.Pressable,{accessibilityLabel:et,style:({pressed:e})=>[xp.controlButton,e&&xp.pressed],onPress:ee,disabled:f||y,children:f?(0,xb.jsx)(wG.ActivityIndicator,{size:"small",color:s2.textSecondary}):(0,xb.jsx)(nC,{size:19,color:s2.textPrimary,strokeWidth:2})}):null,c?(0,xb.jsx)(SZ,{...c,sendInFlight:K||f,presentation:B,onNavigate:e=>Q(t=>t&&{...t,page:e}),onDrawerOpen:e=>Q({page:e,refocus:A}),onDrawerAfterClose:()=>{B?.refocus&&I.current?.focus(),Q(null)}}):null,(0,xb.jsx)(wG.View,{style:xp.actionSpacer}),H.hasCapabilities&&(0,xb.jsxs)(wG.View,{style:{flexDirection:"row"},children:[(0,xb.jsx)(wG.Pressable,{accessibilityRole:"button",accessibilityLabel:"Browse RuFlo commands",onPress:()=>H.openSlashMenu(null),style:xp.ghostButton,children:(0,xb.jsx)(nZ,{size:17,color:s2.brandAccent})}),(0,xb.jsx)(wG.Pressable,{accessibilityRole:"button",accessibilityLabel:"Browse RuFlo references and files",onPress:H.openFileMenu,style:xp.ghostButton,children:(0,xb.jsx)(nN,{size:17,color:s2.brandAccent})})]}),p?(0,xb.jsx)(wG.Pressable,{accessibilityLabel:m?"Stop dictation":"Dictate",style:({pressed:e})=>[xp.ghostButton,e&&xp.pressed],onPress:"hold"===g?void 0:p,onPressIn:"hold"===g?b:void 0,onPressOut:"hold"===g?v:void 0,onLongPress:"hold"===g?xd:void 0,disabled:y&&!m,children:m?(0,xb.jsx)(se,{pointerEvents:"none",size:16,color:s2.statusRed,strokeWidth:2.4,fill:s2.statusRed}):(0,xb.jsx)(ni,{pointerEvents:"none",size:19,color:s2.textSecondary,strokeWidth:2})}):null,X&&T?(0,xb.jsx)(xg,{onStop:T.onStop,held:T.held}):(0,xb.jsx)(wG.Pressable,{accessibilityRole:"button",accessibilityLabel:"Send message",style:({pressed:e})=>[xp.sendButton,!Y&&xp.sendButtonDisabled,e&&Y&&xp.pressed],onPress:J,disabled:!Y,children:(0,xb.jsx)(nW,{size:19,color:Y?s2.bgBase:s2.textMuted,strokeWidth:2.4})})]})]})}),l?(0,xb.jsx)(ik,{visible:E,onClose:()=>D(!1),actions:(C={onPhotos:d,onFiles:l.onAttachFiles,onWorkspaceFile:H.openFileMenu,onSkills:()=>H.openSlashMenu("skill"),onCommands:()=>H.openSlashMenu("command"),skillCount:H.skillCount},M=[],C.onPhotos&&M.push({label:"Photos",icon:n2,closeBeforePress:!0,onPress:C.onPhotos}),C.onFiles&&M.push({label:"Files",hint:"PDF, text, code…",icon:nm,closeBeforePress:!0,onPress:C.onFiles}),M.push({label:"Workspace file",icon:nN,closeBeforePress:!0,onPress:C.onWorkspaceFile},{label:"Skills",...C.skillCount>0?{hint:`${C.skillCount} available`}:{},icon:nc,closeBeforePress:!0,onPress:C.onSkills},{label:"Commands",icon:rF,closeBeforePress:!0,onPress:C.onCommands}),M)}):null]})}var xS=oa(oe()),xx=oa(os()),xT=oa(oe()),xk=oa(oe()),xC=oa(oo());function xL({prompt:e,onCancel:t,onCollapse:i,disabled:r}){if(!t&&!i)return null;let n=t?r7:ss;return(0,xC.jsx)(xk.Pressable,{accessibilityLabel:t?"Cancel":"Collapse",accessibilityState:t?void 0:{expanded:!0},hitSlop:8,style:xM.action,onPress:()=>{t?t(e):(xk.Keyboard.dismiss(),i?.())},disabled:r,children:(0,xC.jsx)(n,{size:16,color:s2.textMuted})})}var xM=xk.StyleSheet.create({action:{width:28,height:28,alignItems:"center",justifyContent:"center"}}),xR=oa(os()),xI=oa(oo());function xA({prompt:e,onAnswer:t,onCancel:i,onCollapse:r}){let n,s,[o,a]=(0,xx.useState)(0),[l,c]=(0,xx.useState)(()=>e.questions.map(()=>[])),[d,u]=(0,xx.useState)(()=>e.questions.map(()=>"")),[h,f]=(0,xx.useState)(!1),p=(0,xx.useRef)(!1),m=(n=(0,xR.useRef)(void 0),s=()=>clearTimeout(n.current),(0,xR.useEffect)(()=>()=>clearTimeout(n.current),[]),{schedule:e=>{s(),n.current=setTimeout(e,200)},cancel:s}),g=(e,t,i)=>{if(p.current)return;let r=l[e]??[],n=!r.includes(t),s=n?i?[...r,t]:[t]:r.filter(e=>e!==t),o=l.map((t,i)=>i===e?s:t);c(o),m.cancel(),n&&!i&&-1!==t&&m.schedule(()=>{k(o)})},b=(e,t=l)=>{let i=(t[e]??[]).filter(e=>-1!==e),r=(t[e]??[]).includes(-1)?(d[e]??"").trim():"";return r?{indices:i,other:r}:{indices:i}},v=(e,t=l)=>{let i=b(e,t);return i.indices.length>0||(i.other??"").length>0},y=e.questions.length,_=o===y-1,w=(0,xx.useMemo)(()=>v(o),[l,d,o]),S=(0,xx.useMemo)(()=>e.questions.every((e,t)=>v(t)),[d,e.questions,l]),x=!h&&(_?S:w),T=async i=>{if(!(!e.questions.every((e,t)=>v(t,i))||p.current)){p.current=!0,f(!0);try{await t(e.questions.map((e,t)=>b(t,i)))}finally{p.current=!1,f(!1)}}},k=async(e=l)=>{m.cancel(),_?await T(e):a(e=>Math.min(e+1,y-1))},C=e.questions[o],L=(l[o]??[]).includes(-1);return(0,xI.jsxs)(xT.View,{style:xE.card,children:[y>1?(0,xI.jsx)(xT.ScrollView,{horizontal:!0,showsHorizontalScrollIndicator:!1,style:xE.tabs,contentContainerStyle:xE.tabsContent,keyboardShouldPersistTaps:"always",children:e.questions.map((e,t)=>(0,xI.jsxs)(xT.Pressable,{style:[xE.tab,t===o&&xE.tabActive],disabled:h,onPress:()=>{m.cancel(),a(t)},children:[(0,xI.jsx)(xT.Text,{style:[xE.tabText,t===o&&xE.tabTextActive],numberOfLines:1,children:e.header||`Step ${t+1}`}),v(t)?(0,xI.jsx)(si,{size:11,color:s2.statusGreen,strokeWidth:3}):null]},t))}):null,(0,xI.jsxs)(xT.ScrollView,{style:xE.scroll,keyboardShouldPersistTaps:"always",children:[(0,xI.jsxs)(xT.View,{style:xE.questionRow,children:[(0,xI.jsx)(xT.Text,{style:xE.questionText,children:C.question}),(0,xI.jsx)(xL,{onCollapse:r&&(()=>{m.cancel(),r()}),disabled:h})]}),C.options.map((e,t)=>(0,xI.jsx)(xP,{label:e.label,description:e.description,selected:(l[o]??[]).includes(t),multi:C.multiSelect,disabled:h,onPress:()=>g(o,t,C.multiSelect)},`${t}:${e.label}`)),(0,xI.jsx)(xP,{label:"Other…",selected:L,multi:C.multiSelect,disabled:h,onPress:()=>g(o,-1,C.multiSelect)}),L?(0,xI.jsx)(xT.TextInput,{style:xE.input,value:d[o],onChangeText:e=>{u(t=>{let i=[...t];return i[o]=e,i})},placeholder:"Type your answer",placeholderTextColor:s2.textMuted,multiline:!0,autoFocus:!0}):null]}),(0,xI.jsxs)(xT.View,{style:xE.footer,children:[(0,xI.jsx)(xT.Pressable,{style:xE.cancel,onPress:async()=>{if(m.cancel(),!p.current&&i){p.current=!0,f(!0);try{await i()}finally{p.current=!1,f(!1)}}},disabled:h,hitSlop:8,children:(0,xI.jsx)(xT.Text,{style:xE.cancelText,children:"Cancel"})}),y>1?(0,xI.jsxs)(xT.Text,{style:xE.progress,children:[o+1,"/",y]}):null,(0,xI.jsx)(xT.Pressable,{style:[xE.next,!x&&xE.nextDisabled],onPress:()=>{k()},disabled:!x,children:(0,xI.jsx)(xT.Text,{style:[xE.nextText,!x&&xE.nextTextDisabled],children:_?"Submit":"Next"})})]})]})}function xP({label:e,description:t,selected:i,multi:r,disabled:n,onPress:s}){return(0,xI.jsxs)(xT.Pressable,{style:[xE.option,i&&xE.optionSelected],disabled:n,onPress:s,children:[(0,xI.jsx)(xT.View,{style:[xE.check,r?xE.checkSquare:xE.checkCircle,i&&xE.checkOn],children:i?(0,xI.jsx)(si,{size:12,color:s2.bgBase,strokeWidth:3}):null}),(0,xI.jsxs)(xT.View,{style:xE.optionBody,children:[(0,xI.jsx)(xT.Text,{style:xE.optionLabel,children:e}),t?(0,xI.jsx)(xT.Text,{style:xE.optionDescription,numberOfLines:3,children:t}):null]})]})}var xE=xT.StyleSheet.create({card:{maxHeight:380,backgroundColor:s2.bgPanel,borderTopWidth:xT.StyleSheet.hairlineWidth,borderTopColor:s2.borderSubtle},tabs:{flexGrow:0,paddingTop:s6.sm,borderBottomWidth:xT.StyleSheet.hairlineWidth,borderBottomColor:s2.borderSubtle},tabsContent:{paddingHorizontal:s6.sm,gap:s6.xs,alignItems:"center"},tab:{flexDirection:"row",alignItems:"center",gap:4,minHeight:36,paddingHorizontal:s6.sm,paddingVertical:s6.xs,borderBottomWidth:2,borderBottomColor:"transparent"},tabActive:{borderBottomColor:s2.statusGreen},tabText:{color:s2.textSecondary,fontSize:s7.metaSize,fontWeight:"600"},tabTextActive:{color:s2.textPrimary},scroll:{paddingHorizontal:s6.md},questionRow:{flexDirection:"row",alignItems:"flex-start",gap:s6.sm},questionText:{flex:1,color:s2.textPrimary,fontSize:s7.bodySize+1,fontWeight:"600",marginVertical:s6.sm},option:{flexDirection:"row",alignItems:"center",gap:s6.sm,padding:s6.sm,borderRadius:s4.card,backgroundColor:s2.bgRaised,borderWidth:1,borderColor:s2.borderSubtle,marginBottom:s6.xs},optionSelected:{borderColor:s2.statusGreen},check:{width:18,height:18,borderWidth:1.5,borderColor:s2.textMuted,alignItems:"center",justifyContent:"center"},checkCircle:{borderRadius:9},checkSquare:{borderRadius:4},checkOn:{backgroundColor:s2.statusGreen,borderColor:s2.statusGreen},optionBody:{flex:1,gap:2},optionLabel:{color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"},optionDescription:{color:s2.textSecondary,fontSize:s7.metaSize},input:{backgroundColor:s2.bgRaised,borderWidth:1,borderColor:s2.borderSubtle,borderRadius:s4.card,color:s2.textPrimary,fontSize:iC,padding:s6.sm,minHeight:44,marginBottom:s6.xs},footer:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",padding:s6.md,gap:s6.sm,borderTopWidth:xT.StyleSheet.hairlineWidth,borderTopColor:s2.borderSubtle},cancel:{paddingVertical:s6.sm,paddingHorizontal:s6.sm},cancelText:{color:s2.textSecondary,fontSize:s7.bodySize,fontWeight:"600"},progress:{color:s2.textMuted,fontSize:s7.metaSize},next:{paddingVertical:s6.sm,paddingHorizontal:s6.lg,borderRadius:s4.button,backgroundColor:s2.textPrimary},nextDisabled:{backgroundColor:s2.bgRaised},nextText:{color:s2.bgBase,fontSize:s7.bodySize,fontWeight:"700"},nextTextDisabled:{color:s2.textMuted}}),xD=oa(os()),xB=oa(oe()),xQ=new Set(["plan"]);function xj(e){return e?.kind==="plan"}function xF(e){return void 0!==e&&!xQ.has(e.kind)}function xO(e){let t=!1;for(let{body:i}of e)if(("approval"===i.kind||"question"===i.kind)&&"pending"===i.resolution.state){if("question"===i.kind||!xF(i.subject))return!1;t=!0}return t}var xW=/[\s'"`/\\]/,xH=oa(oo()),xN=(0,xD.memo)(function({permission:e,onRespond:t,onCancel:i,onCollapse:r}){let[n,s]=(0,xD.useState)(!1),o=(0,xD.useRef)(!1),a=xF(e.subject),l=async e=>{!o.current&&(o.current=!0,s(!0),await t(e)||(o.current=!1,s(!1)))};return(0,xH.jsxs)(xB.View,{testID:"native-chat-approval-card",style:x$.card,children:[(0,xH.jsxs)(xB.View,{style:x$.header,children:[(0,xH.jsx)(nK,{size:16,color:s2.accentBlue,strokeWidth:2}),(0,xH.jsx)(xB.Text,{testID:"native-chat-approval-title",style:x$.title,numberOfLines:2,ellipsizeMode:"tail",children:e.title}),(0,xH.jsx)(xL,{prompt:e.prompt,onCancel:i,onCollapse:r,disabled:n})]}),(0,xH.jsx)(xz,{permission:e,newerSubject:a}),(0,xH.jsx)(xB.View,{testID:"native-chat-approval-actions",style:x$.options,children:e.options.map((e,t)=>{let i=0===t;return(0,xH.jsx)(xB.Pressable,{style:({pressed:e})=>[x$.option,i?x$.optionPrimary:x$.optionSecondary,e&&!n&&x$.optionPressed,a&&x$.disabled],hitSlop:6,onPress:()=>l(e.send),disabled:n||a,children:(0,xH.jsx)(xB.Text,{style:[x$.optionText,i&&x$.optionTextPrimary],children:e.label})},`${e.send}:${e.label}`)})})]})});function xz({permission:e,newerSubject:t}){let i=function(e){let t=e.blockedPath;if(!t)return null;let i=[t,JSON.stringify(t).slice(1,-1)],r=xj(e.subject)?[e.subject.text,e.subject.filePath]:[e.detail];return[e.description,e.decisionReason,...r].some(e=>void 0!==e&&i.some(t=>(function(e,t){for(let i=e.indexOf(t);-1!==i;i=e.indexOf(t,i+1)){let r=e[i+t.length];if(void 0===r||xW.test(r))return!0}return!1})(e,t)))?null:t}(e);return e.description||e.decisionReason||i||e.subject||e.detail?(0,xH.jsxs)(xB.ScrollView,{testID:"native-chat-approval-content",style:x$.contentScroll,contentContainerStyle:x$.content,nestedScrollEnabled:!0,children:[e.description?(0,xH.jsx)(xB.Text,{style:x$.detail,children:e.description}):null,e.decisionReason?(0,xH.jsxs)(xB.Text,{style:x$.detail,children:[(0,xH.jsx)(xB.Text,{style:x$.contextLabel,children:"Reason: "}),e.decisionReason]}):null,i?(0,xH.jsxs)(xB.Text,{style:x$.detail,children:[(0,xH.jsx)(xB.Text,{style:x$.contextLabel,children:"Needs access to: "}),i]}):null,xj(e.subject)?(0,xH.jsxs)(xB.View,{children:[(0,xH.jsx)(tZ,{content:e.subject.text}),e.subject.filePath?(0,xH.jsxs)(xB.Text,{style:x$.planFile,children:["Plan file: ",e.subject.filePath]}):null]}):e.detail?(0,xH.jsx)(xB.Text,{style:x$.detail,children:e.detail}):null,t?(0,xH.jsx)(xB.Text,{testID:"native-chat-approval-needs-newer-orca",style:x$.detail,children:"This request needs a newer version of RuFlo."}):null]}):null}var x$=xB.StyleSheet.create({card:{marginHorizontal:s6.lg,marginVertical:s6.sm,padding:s6.md,gap:s6.sm,borderRadius:s4.card,borderWidth:xB.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle,backgroundColor:s2.bgPanel,flexShrink:1,minHeight:0},header:{flexDirection:"row",alignItems:"center",gap:s6.sm,flexShrink:0},title:{flex:1,color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"},detail:{color:s2.textSecondary,fontSize:s7.metaSize,lineHeight:s7.metaSize+5},planFile:{marginTop:s6.sm,color:s2.textSecondary,fontFamily:s7.monoFamily,fontSize:s7.metaSize,lineHeight:s7.metaSize+5},contextLabel:{color:s2.textPrimary,fontWeight:"600"},contentScroll:{maxHeight:240,minHeight:0,flexShrink:1},content:{gap:s6.sm},options:{flexDirection:"row",flexWrap:"wrap",gap:s6.sm,flexShrink:0},option:{minHeight:44,justifyContent:"center",paddingHorizontal:s6.md,paddingVertical:s6.sm,borderRadius:s4.button},optionPrimary:{backgroundColor:s2.accentBlue},optionSecondary:{backgroundColor:s2.bgRaised,borderWidth:xB.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle},optionPressed:{opacity:.7},disabled:{opacity:.5},optionText:{color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"},optionTextPrimary:{color:s2.onAccent}}),xq=oa(os()),xK=oa(oe()),xV=/^(\s*)(?:❯|›|»)\s+/,xU=[{re:/^\s*(\d{1,2})[.)]\s+(\S.*?)\s*$/,token:1,label:2},{re:/^\s*\[([0-9a-zA-Z])\]\s+(\S.*?)\s*$/,token:1,label:2},{re:/^\s*([a-zA-Z])[.)]\s+(\S.*?)\s*$/,token:1,label:2},{re:/^\s*(?:[-*•>])\s+(\S.*?)\s*$/,token:0,label:1}];function xZ(e){let t=e.replace(xV,"$1");for(let{re:e,token:i,label:r}of xU){let n=t.match(e);if(!n)continue;let s=n[r].trim();if(0!==s.length)return{label:s,token:i>0?n[i]:null}}return null}var xG=/\b(select all|choose all|choose multiple|select multiple|pick multiple|all that apply|one or more|comma[- ]separated|multiple options)\b/i,xY=/[?:]\s*$/;function xX(e,t){if(!Number.isInteger(t)||t<0||t>=e.options.length)return null;let i=e.options[t];if(null==i||0===i.trim().length)return null;let r=e.optionTokens[t];return null!=r&&r.length>0?r:i}function xJ(e,t){return t.map(t=>xX(e,t)).filter(e=>null!=e&&e.trim().length>0)}function x0(e,t){return xJ(e,t).join(e.multiSelect?", ":" ")}function x1(e,t,i){let r=xJ(e,t),n=x5(e,i);return n.length>0&&r.push(n),r.join(e.multiSelect?", ":" ")}function x5(e,t){let i,r=e.freeTextInput?.allowEmpty?t:t.trim();return 0!==r.length||e.freeTextInput?.allowEmpty?e.freeTextToken?`${e.freeTextToken}:${encodeURIComponent(r)}`:e.freeTextInput?.allowEmpty?r:0===(i=[r].map(e=>e.trim()).filter(e=>e.length>0)).length?"":i.map(t=>{let i=e.options.indexOf(t);return -1===i?t:xX(e,i)??t}).join(e.multiSelect?", ":" "):""}var x2=oa(oo());function x3({question:e,onAnswer:t,onCancel:i,onCollapse:r}){let[n,s]=(0,xq.useState)([]),[o,a]=(0,xq.useState)(()=>e.freeTextInput?.initialValue??""),[l,c]=(0,xq.useState)(!1),d=(0,xq.useRef)(!1),u=!1!==e.allowOther,h=e.options.length>0,f=e.freeTextInput?.allowEmpty?o:o.trim(),p=async e=>{if(d.current)return!1;d.current=!0,c(!0);try{return await t(e)}finally{d.current=!1,c(!1)}},m=async t=>{let i=e.optionTokens[t];await p(i&&i.length>0?i:x0(e,[t]))},g=async()=>{if(0===n.length)return;let t=e.freeTextToken&&f.length>0?x1(e,n,f):x0(e,n);await p(t)&&a("")},b=async()=>{if(!u||0===f.length&&!e.freeTextInput?.allowEmpty)return;let t=e.multiSelect&&e.freeTextToken&&n.length>0?x1(e,n,f):x5(e,f);await p(t)&&a("")},v=n.length>0&&!l,y=u&&(f.length>0||e.freeTextInput?.allowEmpty===!0)&&!l,_=(0,xq.useMemo)(()=>e.options.map((t,i)=>({label:t,description:e.optionDescriptions?.[i],key:`${i}:${t}`})),[e.optionDescriptions,e.options]);return(0,x2.jsxs)(xK.View,{style:x6.card,children:[(0,x2.jsxs)(xK.View,{style:x6.header,children:[(0,x2.jsx)(r6,{size:15,color:s2.accentBlue,strokeWidth:2.2}),(0,x2.jsx)(xK.Text,{style:x6.question,children:e.question}),(0,x2.jsx)(xL,{prompt:e.prompt,onCancel:i,onCollapse:r,disabled:l})]}),h?(0,x2.jsx)(xK.View,{style:x6.options,children:_.map(({label:t,description:i,key:r},o)=>{let a=n.includes(o);return(0,x2.jsxs)(xK.Pressable,{accessibilityRole:e.multiSelect?"checkbox":"button",accessibilityState:e.multiSelect?{checked:a}:void 0,style:({pressed:e})=>[x6.option,a&&x6.optionSelected,e&&x6.pressed],onPress:()=>e.multiSelect?void s(e=>e.includes(o)?e.filter(e=>e!==o):[...e,o]):m(o),children:[e.multiSelect?(0,x2.jsx)(xK.View,{style:[x6.checkbox,a&&x6.checkboxOn],children:a?(0,x2.jsx)(si,{size:13,color:s2.bgBase,strokeWidth:3}):null}):null,(0,x2.jsxs)(xK.View,{style:x6.optionBody,children:[(0,x2.jsx)(xK.Text,{style:x6.optionText,children:t}),i?(0,x2.jsx)(xK.Text,{style:x6.optionDescription,numberOfLines:2,children:i}):null]})]},r)})}):null,e.multiSelect&&h?(0,x2.jsx)(xK.Pressable,{accessibilityLabel:"Submit selected options",style:({pressed:e})=>[x6.submit,!v&&x6.submitDisabled,e&&v&&x6.pressed],onPress:g,disabled:!v,children:(0,x2.jsxs)(xK.Text,{style:[x6.submitText,!v&&x6.submitTextDisabled],children:["Submit",n.length>0?` (${n.length})`:""]})}):null,u?(0,x2.jsxs)(xK.View,{style:x6.freeTextRow,children:[(0,x2.jsx)(xK.TextInput,{style:w9.freeInput,value:o,onChangeText:a,placeholder:e.freeTextInput?.placeholder??(h?"Or type a reply…":"Type your reply…"),placeholderTextColor:s2.textMuted,selectionColor:s2.accentBlue,onSubmitEditing:b,returnKeyType:"send",multiline:!e.freeTextInput||!0===e.freeTextInput.multiline}),(0,x2.jsx)(xK.Pressable,{accessibilityLabel:"Send reply",style:({pressed:e})=>[x6.freeSend,!y&&x6.freeSendDisabled,e&&y&&x6.pressed],onPress:b,disabled:!y,children:(0,x2.jsx)(nW,{size:18,color:y?s2.bgBase:s2.textMuted,strokeWidth:2.6})})]}):null]})}var x6=xK.StyleSheet.create({card:{marginHorizontal:s6.lg,marginVertical:s6.sm,padding:s6.md,gap:s6.sm,backgroundColor:s2.bgPanel,borderRadius:s4.card,borderWidth:xK.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle},header:{flexDirection:"row",alignItems:"center",gap:s6.sm},question:{flex:1,color:s2.textPrimary,fontSize:s7.bodySize+1,fontWeight:"600",lineHeight:s7.bodySize+7},options:{gap:s6.xs},option:{flexDirection:"row",alignItems:"center",gap:s6.sm,minHeight:44,paddingHorizontal:s6.md,paddingVertical:s6.sm,backgroundColor:s2.bgRaised,borderRadius:s4.button,borderWidth:xK.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle},optionSelected:{borderColor:s2.accentBlue},optionBody:{flex:1,gap:2},optionText:{color:s2.textPrimary,fontSize:s7.bodySize+1},optionDescription:{color:s2.textMuted,fontSize:s7.metaSize,lineHeight:s7.metaSize+5},checkbox:{width:20,height:20,borderRadius:s4.button,borderWidth:1.5,borderColor:s2.textMuted,alignItems:"center",justifyContent:"center"},checkboxOn:{backgroundColor:s2.accentBlue,borderColor:s2.accentBlue},submit:{minHeight:44,alignItems:"center",justifyContent:"center",borderRadius:s4.button,backgroundColor:s2.accentBlue},submitDisabled:{backgroundColor:s2.bgRaised},submitText:{color:s2.onMergeGreen,fontSize:s7.bodySize+1,fontWeight:"600"},submitTextDisabled:{color:s2.textMuted},freeTextRow:{flexDirection:"row",alignItems:"flex-end",gap:s6.sm},freeSend:{width:40,height:40,borderRadius:20,alignItems:"center",justifyContent:"center",backgroundColor:s2.textPrimary},freeSendDisabled:{backgroundColor:s2.bgRaised},pressed:{opacity:.7}}),x4=oa(oe()),x7=oa(oo());function x8({title:e,onExpand:t}){return(0,x7.jsxs)(x4.View,{testID:"native-chat-prompt-strip",style:x9.strip,children:[(0,x7.jsx)(x4.Text,{style:x9.title,numberOfLines:1,children:e}),(0,x7.jsx)(x4.Pressable,{accessibilityLabel:"Expand",accessibilityState:{expanded:!1},hitSlop:8,style:x9.action,onPress:t,children:(0,x7.jsx)(rN,{size:16,color:s2.textMuted})})]})}var x9=x4.StyleSheet.create({action:{width:28,height:28,alignItems:"center",justifyContent:"center"},strip:{flexDirection:"row",alignItems:"center",gap:s6.sm,paddingLeft:s6.md,paddingRight:s6.sm,paddingVertical:s6.xs,backgroundColor:s2.bgPanel,borderTopWidth:x4.StyleSheet.hairlineWidth,borderTopColor:s2.borderSubtle},title:{flex:1,color:s2.textPrimary,fontSize:s7.bodySize,fontWeight:"600"}}),Te=oa(oo());function Tt({ask:e,askKey:t,onDismissAsk:i,onAnswerAsk:r,onCancelAsk:n,onCancelPrompt:s,onCollapseAsk:o,onCollapsePrompt:a,collapsedPrompt:l,permission:c,onRespondPermission:d,question:u,onAnswerQuestion:h}){let f=e?(0,Te.jsx)(xA,{prompt:e,onAnswer:async t=>{let n=await r?.(e,t)??!1;return n&&i?.(),n},onCancel:async()=>{let e=await n?.()??!1;return e&&i?.(),e},onCollapse:o},t??"ask"):c?(0,Te.jsx)(xN,{permission:c,onRespond:async e=>await d?.(e)??!1,onCancel:s,onCollapse:a},JSON.stringify(c)):u?(0,Te.jsx)(x3,{question:u,onAnswer:async e=>await h?.(e)??!1,onCancel:s,onCollapse:a},JSON.stringify(u)):null;return(0,Te.jsxs)(Te.Fragment,{children:[(0,Te.jsx)(xS.View,{style:l?Ti.collapsed:void 0,children:f}),l?(0,Te.jsx)(x8,{title:l.title,onExpand:l.expand}):null]})}var Ti=xS.StyleSheet.create({collapsed:{display:"none"}}),Tr=oa(os()),Tn=oa(os()),Ts=oa(oe());function To(e,t,i){let r={value0:t};switch(e){case"agent":return 1===t?i("countAgentsOne"):i("countAgentsMany",r);case"command":return 1===t?i("countShellOne"):i("countShellMany",r);case"monitor":return 1===t?i("countMonitorsOne"):i("countMonitorsMany",r);case"workflow":return 1===t?i("countWorkflowsOne"):i("countWorkflowsMany",r);case"unknown":return 1===t?i("countTasksOne"):i("countTasksMany",r)}}var Ta=["working","monitoring","waiting","blocked","unverifiable","idle","done"],Tl=new Set(["waiting","unverifiable","blocked"]),Tc=oa(os()),Td=[],Tu=new Set;function Th(e,t,i){let r=e=>!t.has(i(e)??"");return e.every(r)?e:e.filter(r)}function Tf(e,t){if(!e.show)return null;if(!e.children)return e.tasks.some(e=>e.id===t)?t:null;let i=e.children.find(e=>e.providerId===t);return i?`${i.invocation.invocationId}#${i.invocation.generation}`:null}var Tp=new Set,Tm=new Map,Tg={taskIds:Tp,all:!1},Tb=oa(oo());function Tv({kind:e,size:t}){let i={size:t,color:"monitor"===e?F:s2.textMuted,strokeWidth:2};switch(e){case"agent":return(0,Tb.jsx)(nG,{...i});case"command":return(0,Tb.jsx)(n8,{...i});case"monitor":return(0,Tb.jsx)(nQ,{...i});case"workflow":return(0,Tb.jsx)(r5,{...i});case"unknown":return(0,Tb.jsx)(r6,{...i})}}function Ty({row:e,now:t,hostNow:i,supportsTaskStop:r,stopping:n,onStop:s}){let{lead:o,trail:a}=w(e,t),l=v(e,i),c=y(e,r),d=null!==c&&n.taskIds.has(c);return(0,Tb.jsxs)(Tb.Fragment,{children:[(0,Tb.jsxs)(Ts.View,{testID:"background-task-row",style:Tw.row,children:[(0,Tb.jsx)(Tv,{kind:e.kind,size:14}),(0,Tb.jsx)(O,{state:e.displayState}),(0,Tb.jsxs)(Ts.Text,{style:Tw.rowText,numberOfLines:1,ellipsizeMode:"tail",children:[(0,Tb.jsx)(Ts.Text,{style:Tw.lead,children:o}),a?(0,Tb.jsx)(Ts.Text,{style:Tw.trail,children:` \xb7 ${a}`}):null]}),l?(0,Tb.jsx)(Ts.Text,{style:Tw.meta,importantForAccessibility:"no",accessibilityElementsHidden:!0,children:l}):null,null!==c?(0,Tb.jsx)(Ts.Pressable,{accessibilityRole:"button",accessibilityLabel:H("stopTask",{value0:_(e)}),accessibilityState:{disabled:d},disabled:d,hitSlop:6,style:({pressed:e})=>[Tw.textAction,e&&Tw.pressed,d&&Tw.disabled],onPress:()=>s(c),children:(0,Tb.jsx)(Ts.Text,{style:Tw.actionLabel,children:H("stop")})}):null]}),e.owned.length>0?(0,Tb.jsx)(Ts.View,{style:Tw.owned,children:e.owned.map(e=>(0,Tb.jsx)(Ty,{row:e,now:t,hostNow:i,supportsTaskStop:r,stopping:n,onStop:s},e.id))}):null]})}var T_=(0,Tn.memo)(function({tasks:e}){let{view:t,rowContext:i}=e,[r,n]=(0,Tn.useState)(!1),[s,o]=(0,Tn.useState)(()=>Ts.Dimensions.get("window").width-2*s6.lg<384),{stopping:a,onStop:l}=function(e){let t,{view:i,stop:r}=e,[n,s]=(0,Tc.useState)(Tg),o=(0,Tc.useRef)(Tg),[a,l]=(0,Tc.useState)(Tm),c=(t=[...a].filter(([e,t])=>Tf(i,e)===t)).length===a.size?a:new Map(t);c!==a&&l(c);let d=e=>{o.current=e,s(e)};return{stopping:c.size?{...n,taskIds:new Set([...n.taskIds,...c.keys()])}:n,onStop:e=>{let t=o.current;if(e?t.taskIds.has(e):t.all)return;let n=e?Tf(i,e):null;d({taskIds:e?new Set([...t.taskIds,e]):t.taskIds,all:!e||t.all}),r(e).then(t=>{e&&null!==n&&"accepted"===t.status&&t.value.cancelled&&l(t=>new Map([...t,[e,n]]))}).finally(()=>{let t=o.current,i=new Set(t.taskIds);e&&i.delete(e),d({taskIds:i,all:!!e&&t.all})})}}}(e),c=(0,Tn.useMemo)(()=>void 0!==t.children?es(t.children,i):en(t.tasks,t.settledTasks,H),[t.children,t.tasks,t.settledTasks,i]),d=rn(1e3,t.show&&b(c,r));if(!t.show)return null;let u=d-i.hostClockOffsetMs,v=function(e,t,i){let r=e.flatMap(e=>e.tasks);if(0===r.length)return{segments:[],detail:i("monitoring")};if(e.length>3||t.narrow&&e.length>1)return{segments:[{text:i("headerTotal",{value0:r.length}),kind:null}],detail:null};if(e.length>1)return{segments:e.map(e=>({text:To(e.kind,e.tasks.length,i),kind:e.kind})),detail:null};let n=e[0],s=n.tasks.length,o=n.tasks.every(e=>e.state===n.tasks[0].state)?n.tasks[0].state:null;if(o&&Tl.has(o))return{segments:[{text:p(To(n.kind,s,i),o,i),kind:n.kind}],detail:f(o,i)};if(1===s){let e=n.tasks[0],r="command"===n.kind?i("countShellCommandOne"):To(n.kind,1,i),s="command"!==n.kind||e.row.settled?null:g(e.row.firstObservedAt,t.now);return{segments:[{text:r,kind:n.kind}],detail:s??h(e.state,i)}}let a=Ta.map(e=>({state:e,count:n.tasks.filter(t=>t.state===e).length})).filter(e=>e.count>0);return{segments:[{text:To(n.kind,s,i),kind:n.kind}],detail:a.length>0?a.map(e=>p(e.count,e.state,i)).join(", "):null}}(c,{narrow:s,now:u},H);return(0,Tb.jsx)(Ts.View,{style:Tw.list,onLayout:e=>{o(e.nativeEvent.layout.width<384)},testID:"background-tasks-strip",children:(0,Tb.jsxs)(Ts.View,{style:Tw.box,children:[(0,Tb.jsxs)(Ts.Pressable,{accessibilityRole:"button",accessibilityState:{expanded:r},accessibilityLabel:`${v.segments.map(e=>e.text).join(" · ")}${v.detail?`${v.segments.length>0?" — ":""}${v.detail}`:""}`,hitSlop:s6.xs,style:({pressed:e})=>[Tw.header,e&&Tw.pressed],onPress:()=>n(!r),children:[(0,Tb.jsxs)(Ts.View,{style:Tw.headerText,children:[v.segments.map((e,i)=>(0,Tb.jsxs)(Ts.View,{style:Tw.segment,children:[i>0?(0,Tb.jsx)(Ts.Text,{style:Tw.separator,children:"·"}):null,e.kind?(0,Tb.jsx)(Ts.View,{style:t.isMonitoring?void 0:Tw.dimmed,children:(0,Tb.jsx)(Tv,{kind:e.kind,size:12})}):null,(0,Tb.jsx)(Ts.Text,{style:Tw.segmentText,numberOfLines:1,ellipsizeMode:"tail",children:e.text})]},e.kind??"total")),v.detail?(0,Tb.jsx)(Ts.Text,{style:Tw.detail,numberOfLines:1,ellipsizeMode:"tail",children:v.segments.length>0?`— ${v.detail}`:v.detail}):null]}),(0,Tb.jsx)(Ts.View,{style:r?Tw.caretOpen:void 0,children:(0,Tb.jsx)(ss,{size:14,color:s2.textMuted,strokeWidth:2})})]}),r?(0,Tb.jsxs)(Ts.ScrollView,{style:Tw.body,nestedScrollEnabled:!0,children:[c.length>0?c.map(e=>(0,Tb.jsxs)(Ts.View,{style:Tw.group,children:[(0,Tb.jsx)(Ts.Text,{style:Tw.groupLabel,children:m(e.kind,H)}),e.tasks.map(e=>(0,Tb.jsx)(Ty,{row:e.row,now:d,hostNow:u,supportsTaskStop:t.supportsStop,stopping:a,onStop:l},e.row.id))]},e.kind)):(0,Tb.jsx)(Ts.Text,{style:Tw.unavailable,children:H("detailsUnavailable")}),t.incomplete&&c.length>0?(0,Tb.jsx)(Ts.Text,{style:Tw.unavailable,children:H("detailsUnavailable")}):null,t.offersStopAll?(0,Tb.jsx)(Ts.Pressable,{accessibilityRole:"button",accessibilityLabel:H("stopAll"),accessibilityState:{disabled:a.all},disabled:a.all,hitSlop:6,style:({pressed:e})=>[Tw.textAction,Tw.stopAll,e&&Tw.pressed,a.all&&Tw.disabled],onPress:()=>l(),children:(0,Tb.jsx)(Ts.Text,{style:Tw.actionLabel,children:H("stop")})}):null]}):null]})})}),Tw=Ts.StyleSheet.create({list:{marginHorizontal:s6.lg,marginVertical:s6.xs},box:{backgroundColor:s2.bgPanel,borderRadius:s4.row,borderWidth:Ts.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle,overflow:"hidden"},header:{minHeight:36,flexDirection:"row",alignItems:"center",gap:s6.sm,paddingHorizontal:s6.md},headerText:{flex:1,minWidth:0,flexDirection:"row",alignItems:"center",gap:s6.xs,overflow:"hidden"},segment:{flexDirection:"row",alignItems:"center",gap:s6.xs,flexShrink:1,minWidth:0},separator:{color:s2.textMuted,fontSize:s7.metaSize},segmentText:{flexShrink:1,color:s2.textPrimary,fontSize:s7.metaSize,fontWeight:"500"},detail:{flexShrink:1,color:s2.textMuted,fontSize:s7.metaSize},dimmed:{opacity:.4},caretOpen:{transform:[{rotate:"180deg"}]},body:{maxHeight:220,borderTopWidth:Ts.StyleSheet.hairlineWidth,borderTopColor:s2.borderSubtle},group:{paddingHorizontal:s6.md,paddingTop:s6.xs,paddingBottom:s6.xs},groupLabel:{color:s2.textMuted,fontSize:10,fontFamily:s7.monoFamily,letterSpacing:.8,textTransform:"uppercase",paddingBottom:s6.xs/2},row:{minHeight:32,flexDirection:"row",alignItems:"center",gap:s6.sm},owned:{marginLeft:s6.lg},rowText:{flex:1,minWidth:0,fontSize:s7.metaSize},lead:{color:s2.textPrimary,fontWeight:"500"},trail:{color:s2.textMuted},meta:{color:s2.textMuted,fontSize:10,fontFamily:s7.monoFamily},unavailable:{color:s2.textMuted,fontSize:s7.metaSize,padding:s6.md},textAction:{minHeight:32,minWidth:44,alignItems:"center",justifyContent:"center",paddingHorizontal:s6.sm,borderRadius:s4.button},stopAll:{alignSelf:"flex-start",marginHorizontal:s6.sm},actionLabel:{color:s2.textPrimary,fontSize:s7.metaSize,fontWeight:"500"},pressed:{backgroundColor:s2.bgRaised},disabled:{opacity:.5}}),TS=oa(os()),Tx=oa(oe()),TT=oa(oe()),Tk=oa(os()),TC=oa(oe()),TL=oa(os()),TM=oa(oe()),TR=oa(os()),TI=["fontFamily","fontSize","fontWeight","fontStyle","lineHeight","letterSpacing","wordSpacing","textTransform","textIndent","whiteSpace","overflowWrap","wordBreak","tabSize","paddingTop","paddingRight","paddingBottom","paddingLeft"],TA=oa(oo()),TP=s6.xs;function TE({editor:e,attribution:t}){let i=(0,TL.useRef)(null),r=function(e,t){let[i,r]=(0,TR.useState)(),n=(0,TR.useRef)(null),s=(0,TR.useRef)(t),o=(0,TR.useCallback)(()=>{let t=e.current,i=n.current;if(!i||!(t instanceof HTMLTextAreaElement)||t.clientWidth<=0)return;let o=getComputedStyle(t);for(let e of TI)i.style[e]=o[e];i.style.width=`${t.clientWidth}px`,i.value=s.current.endsWith(` `)?`${s.current} `:s.current;let a=Number.parseFloat(o.borderTopWidth)+Number.parseFloat(o.borderBottomWidth);r(i.scrollHeight+a)},[e]);return(0,TR.useLayoutEffect)(()=>{let e=document.createElement("textarea");return e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e.readOnly=!0,e.rows=1,Object.assign(e.style,{position:"absolute",top:"0",left:"0",visibility:"hidden",pointerEvents:"none",overflow:"hidden",border:"0",margin:"0",boxSizing:"border-box"}),document.body.appendChild(e),n.current=e,()=>{e.remove(),n.current=null}},[]),(0,TR.useLayoutEffect)(()=>{s.current=t,o()},[t,o]),(0,TR.useEffect)(()=>{let t=e.current;if(!(t instanceof HTMLTextAreaElement))return;let i=t.clientWidth,r=new ResizeObserver(()=>{t.clientWidth!==i&&(i=t.clientWidth,o())});return r.observe(t),()=>r.disconnect()},[e,o]),i}(i,e.text),[n,s]=(0,TL.useState)(!1);(0,TL.useEffect)(()=>{i.current?.focus()},[]);let o=e.saving||!e.canSave,a=!e.canSave&&!e.saving;return(0,TA.jsxs)(TM.View,{style:TB.editor,testID:"queued-card-editor",children:[t?(0,TA.jsx)(TM.Text,{style:TB.attribution,numberOfLines:1,children:t}):null,(0,TA.jsxs)(TM.View,{style:TB.line,children:[(0,TA.jsx)(TM.TextInput,{ref:i,accessibilityLabel:"Edit queued message",value:e.text,editable:!e.saving,multiline:!0,selectionColor:s2.accentBlue,textAlignVertical:"top",style:[w9.freeInput,TB.field,void 0!==r&&{height:Math.min(96,Math.max(36,r))},n&&!e.saving&&TB.fieldFocused,e.saving&&TB.disabled],onChangeText:e.change,onFocus:()=>s(!0),onBlur:()=>s(!1)}),(0,TA.jsx)(TD,{label:"Cancel editing",disabled:e.saving,targetStyle:TB.cancelTarget,squareStyle:[TB.buttonRaised,e.saving&&TB.disabled],pressedStyle:TB.cancelPressed,onPress:e.cancel,children:(0,TA.jsx)(r7,{size:16,color:s2.textSecondary,strokeWidth:2})}),(0,TA.jsx)(TD,{label:"Save edited message",disabled:o,busy:e.saving,targetStyle:TB.saveTarget,squareStyle:a?TB.buttonRaised:TB.save,pressedStyle:TB.savePressed,onPress:()=>{e.save()},children:e.saving?(0,TA.jsx)(TM.ActivityIndicator,{size:"small",color:s2.bgBase}):(0,TA.jsx)(si,{size:16,color:a?s2.textMuted:s2.bgBase,strokeWidth:2.6})})]})]})}function TD({label:e,disabled:t,busy:i,targetStyle:r,squareStyle:n,pressedStyle:s,onPress:o,children:a}){let[l,c]=(0,TL.useState)(!1);return(0,TA.jsx)(TM.Pressable,{accessibilityRole:"button",accessibilityLabel:e,accessibilityState:{disabled:t},"aria-busy":i,disabled:t,style:[TB.target,r],onPress:o,onPressIn:()=>c(!0),onPressOut:()=>c(!1),children:(0,TA.jsx)(TM.View,{style:[TB.button,n,l&&!t&&s],children:a})})}var TB=TM.StyleSheet.create({editor:{paddingVertical:s6.sm,paddingLeft:s6.md,paddingRight:s6.sm,gap:s6.xs},attribution:{color:s2.textMuted,fontSize:s7.metaSize,lineHeight:s7.metaSize+s6.xs},line:{flexDirection:"row",alignItems:"flex-end",marginVertical:-4,marginRight:-s6.sm},field:{minHeight:36,maxHeight:96,lineHeight:20,paddingTop:7,paddingBottom:7,paddingHorizontal:10,borderWidth:1,borderColor:s2.borderSubtle,marginVertical:4},fieldFocused:{borderColor:s2.accentBlue},target:{height:44,justifyContent:"center"},cancelTarget:{paddingLeft:6,paddingRight:TP/2},saveTarget:{paddingLeft:TP/2,paddingRight:s6.sm},button:{width:28,height:28,borderRadius:s4.input,alignItems:"center",justifyContent:"center"},buttonRaised:{backgroundColor:s2.bgRaised,borderWidth:TM.StyleSheet.hairlineWidth,borderColor:s2.borderSubtle},cancelPressed:{backgroundColor:s2.bgPanel},save:{backgroundColor:s2.textPrimary},savePressed:{backgroundColor:s2.textSecondary},disabled:{opacity:.5}}),TQ=oa(os()),Tj=oa(oe()),TF=oa(oe()),TO=s6.xl+s6.sm,TW=s7.metaSize+s6.xs,TH=TF.StyleSheet.create({list:{marginHorizontal:s6.lg,marginTop:s6.xs,marginBottom:-18},box:{paddingBottom:12,backgroundColor:s2.bgPanel,borderTopLeftRadius:18,borderTopRightRadius:18,borderWidth:TF.StyleSheet.hairlineWidth,borderBottomWidth:0,borderColor:s2.composerBorder,overflow:"hidden"},header:{minHeight:TO,flexDirection:"row",alignItems:"center",gap:s6.xs,paddingLeft:s6.md},headerActionsLine:{flexDirection:"row",flexWrap:"wrap",justifyContent:"flex-end",gap:s6.xs,paddingHorizontal:s6.xs},headerToggle:{position:"absolute",top:0,right:0,bottom:0,left:0},headerLabels:{flex:1,minWidth:0,flexDirection:"row",alignItems:"center",gap:s6.xs},headerPaused:{backgroundColor:s2.bgRaised},headerLabel:{color:s2.textMuted,fontSize:s7.metaSize,lineHeight:TW,paddingVertical:s6.sm},headerLabelPaused:{color:s2.textPrimary,fontWeight:"500"},headerCount:{color:s2.textMuted,fontSize:s7.metaSize,lineHeight:TW,paddingVertical:s6.sm,fontVariant:["tabular-nums"]},headerCaption:{flex:1,minWidth:0,color:s2.statusRed,fontSize:s7.metaSize,lineHeight:TW,paddingVertical:s6.sm},headerAction:{minHeight:TO,minWidth:44,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:s6.xs,paddingHorizontal:s6.sm,borderRadius:s4.button},chevron:{width:36,minHeight:TO,alignItems:"center",justifyContent:"center"},card:{minHeight:44},row:{minHeight:44,flexDirection:"row",alignItems:"center",gap:s6.sm,paddingLeft:s6.md},divided:{borderTopWidth:TF.StyleSheet.hairlineWidth,borderTopColor:s2.composerBorder},textColumn:{flex:1,minWidth:0,paddingVertical:s6.sm,gap:2},bodyText:{color:s2.textPrimary,fontSize:s7.bodySize,lineHeight:s7.bodySize+6},expandedBody:{paddingLeft:s6.md+14+s6.sm,paddingRight:s6.md,paddingBottom:s6.sm},caption:{color:s2.textMuted,fontSize:s7.metaSize},captionReturned:{color:s2.statusRed},actions:{flexDirection:"row"},textAction:{minHeight:44,minWidth:44,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:s6.xs,paddingHorizontal:s6.sm,borderRadius:s4.button},iconAction:{minHeight:44,width:40,alignItems:"center",justifyContent:"center",borderRadius:s4.button},lastIconAction:{width:44},actionLabel:{color:s2.textPrimary,fontSize:s7.metaSize,fontWeight:"500"},pressed:{backgroundColor:s2.bgRaised},disabled:{opacity:.5}}),TN=oa(oo());function Tz({text:e,expanded:t,onToggle:i}){let[r,n]=(0,TQ.useState)(!1),s=(0,TN.jsx)(Tj.Text,{style:[TH.bodyText,T$.measure],pointerEvents:"none",accessibilityElementsHidden:!0,importantForAccessibility:"no-hide-descendants",onTextLayout:e=>n(e.nativeEvent.lines.length>2),children:e});if(!r&&!t)return(0,TN.jsxs)(Tj.View,{children:[s,(0,TN.jsx)(Tj.Text,{style:TH.bodyText,numberOfLines:2,children:e})]});let o=(0,TN.jsxs)(Tj.Pressable,{testID:"queued-card-text",accessibilityRole:"button",accessibilityState:{expanded:t},accessibilityHint:t?"Shows less of the message":"Shows the whole message",onPress:i,children:[t?null:(0,TN.jsx)(Tj.Text,{style:TH.bodyText,numberOfLines:2,children:e}),(0,TN.jsx)(Tj.Text,{style:T$.caption,children:t?"Show less":"Show more"})]});return(0,TN.jsxs)(Tj.View,{children:[t?null:s,o]})}var T$=Tj.StyleSheet.create({measure:{position:"absolute",left:0,right:0,opacity:0},caption:{color:s2.textMuted,fontSize:s7.metaSize}}),Tq=oa(oo());function TK({card:e,editor:t,onEditorLayout:i,...r}){return t?(0,Tq.jsx)(TC.View,{testID:"queued-card-row",style:TH.divided,onLayout:e=>i(e.nativeEvent.layout),children:(0,Tq.jsx)(TE,{editor:t,attribution:e.attribution})}):(0,Tq.jsx)(TV,{card:e,...r})}function TV({card:e,busy:t,editBlocked:i,steerHeld:r,onSend:n,onDelete:s,onMore:o}){let[a,l]=(0,Tk.useState)(!1),c="returned"===e.state,d=!c&&!e.paused&&!e.command;return(0,Tq.jsxs)(TC.View,{testID:"queued-card-row",style:[TH.card,TH.divided],children:[(0,Tq.jsxs)(TC.View,{style:TH.row,children:[e.needsAttention?(0,Tq.jsx)(rY,{size:14,color:s2.statusRed,strokeWidth:2}):(0,Tq.jsx)(rK,{size:14,color:s2.textMuted,strokeWidth:2}),(0,Tq.jsxs)(TC.View,{style:TH.textColumn,children:[e.attribution?(0,Tq.jsx)(TC.Text,{style:TH.caption,numberOfLines:1,children:e.attribution}):null,(0,Tq.jsx)(Tz,{text:e.text,expanded:a,onToggle:()=>l(!a)}),e.caption&&!c?(0,Tq.jsx)(TC.Text,{style:TH.caption,numberOfLines:1,children:e.caption}):null]}),(0,Tq.jsxs)(TC.View,{style:TH.actions,children:[e.waitsForAgent?null:(0,Tq.jsxs)(TC.Pressable,{accessibilityRole:"button",accessibilityState:{disabled:t||r},accessibilityLabel:c?"Send this message again":d?"Submit without interrupting the model":"Send this message",style:({pressed:e})=>[TH.textAction,e&&TH.pressed,(t||r)&&TH.disabled],disabled:t||r,onPress:n,children:[d?(0,Tq.jsx)(nl,{size:12,color:s2.textPrimary,strokeWidth:2}):(0,Tq.jsx)(nO,{size:12,color:s2.textPrimary,strokeWidth:2}),(0,Tq.jsx)(TC.Text,{style:TH.actionLabel,children:d?"Steer":"Send"})]}),(0,Tq.jsx)(TC.Pressable,{accessibilityRole:"button",accessibilityState:{disabled:t},accessibilityLabel:"Delete this queued message",style:({pressed:i})=>[TH.iconAction,e.command&&TH.lastIconAction,i&&TH.pressed,t&&TH.disabled],disabled:t,onPress:s,children:(0,Tq.jsx)(rH,{size:14,color:s2.textPrimary,strokeWidth:2})}),e.command?null:(0,Tq.jsx)(TC.Pressable,{accessibilityRole:"button",accessibilityState:{disabled:i},accessibilityLabel:"More actions",style:({pressed:e})=>[TH.iconAction,TH.lastIconAction,e&&TH.pressed,i&&TH.disabled],disabled:i,onPress:o,children:(0,Tq.jsx)(nf,{size:14,color:s2.textPrimary,strokeWidth:2})})]})]}),a||c&&e.caption?(0,Tq.jsxs)(TC.View,{style:TH.expandedBody,children:[a?(0,Tq.jsx)(TC.Pressable,{accessibilityRole:"button",accessibilityState:{expanded:!0},accessibilityHint:"Shows less of the message",onPress:()=>l(!1),children:(0,Tq.jsx)(TC.Text,{style:TH.bodyText,children:e.text})}):null,c&&e.caption?(0,Tq.jsx)(TC.Text,{style:[TH.caption,TH.captionReturned],children:e.caption}):null]}):null]})}var TU=oa(os()),TZ=oa(oe()),TG=oa(oo());function TY({messageIds:e,newestIsPersons:t,children:i}){let r=(0,TU.useRef)(null),n=(0,TU.useRef)({offset:0,viewport:0,content:0}),s=(0,TU.useRef)(new Set(e)),o=(0,TU.useRef)(!1),[a,l]=(0,TU.useState)({above:!1,below:!1});(0,TU.useLayoutEffect)(()=>{let i=e.at(-1),n=s.current.size>0&&void 0!==i&&!s.current.has(i);s.current=new Set(e),n&&t&&r.current?.scrollToEnd({animated:!1})},[e,t]);let c=e=>{let t=Object.assign(n.current,e),i=t.offset>1,s=t.offset+t.viewporte.above===i&&e.below===s?e:{above:i,below:s}),!o.current&&t.viewport>0&&t.content>t.viewport+1&&(o.current=!0,"ios"===TZ.Platform.OS&&r.current?.flashScrollIndicators())};return(0,TG.jsxs)(TZ.View,{children:[(0,TG.jsx)(TZ.ScrollView,{ref:r,style:TJ.scroll,nestedScrollEnabled:!0,showsVerticalScrollIndicator:!0,persistentScrollbar:!0,keyboardShouldPersistTaps:"handled",scrollEventThrottle:32,onScroll:e=>c({offset:e.nativeEvent.contentOffset.y}),onLayout:e=>c({viewport:e.nativeEvent.layout.height}),onContentSizeChange:(e,t)=>c({content:t}),children:i(e=>{let{offset:t,viewport:i,content:s}=n.current;if(0===i)return;let o=e.y+e.height,a=Math.max(0,e.y-s6.lg),l=Math.min(Math.max(s,o),o+s6.lg);at+i&&r.current?.scrollTo({y:l-i,animated:!1})})}),a.above?(0,TG.jsx)(TX,{edge:"top"}):null,a.below?(0,TG.jsx)(TX,{edge:"bottom"}):null]})}function TX({edge:e}){let t=`queued-list-fade-${e}`,i="top"===e;return(0,TG.jsx)(TZ.View,{pointerEvents:"none",style:[TJ.fade,i?TJ.fadeTop:TJ.fadeBottom],children:(0,TG.jsxs)(nB,{width:"100%",height:"100%",children:[(0,TG.jsx)(nS,{children:(0,TG.jsxs)(nL,{id:t,x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,TG.jsx)(nE,{offset:"0",stopColor:s2.bgPanel,stopOpacity:+!!i}),(0,TG.jsx)(nE,{offset:"1",stopColor:s2.bgPanel,stopOpacity:+!i})]})}),(0,TG.jsx)(nP,{width:"100%",height:"100%",fill:`url(#${t})`})]})})}var TJ=TZ.StyleSheet.create({scroll:{maxHeight:160},fade:{position:"absolute",left:0,right:0,height:s6.lg},fadeTop:{top:0},fadeBottom:{bottom:0}}),T0=oa(oo()),T1="\0resume",T5="\0clear";function T2({cards:e,onSend:t,onDelete:i,onClearAll:r,onEdit:n,editor:s,pause:o,onResume:a,steerHeld:l=!1}){let[c,d]=(0,TS.useState)(()=>new Set),u=(0,TS.useRef)(new Set),[h,f]=(0,TS.useState)(null),[p,m]=(0,TS.useState)(!0),g=(0,TT.useWindowDimensions)().fontScale>1.3;if(!e||0===e.length)return p||m(!0),null;let b=async(e,t)=>{if(!(u.current.has(e)||!t)){u.current.add(e),d(new Set(u.current));try{await t(e)}finally{u.current.delete(e),d(new Set(u.current))}}},v=c.has(T1),y=c.has(T5),_=e.find(e=>e.messageId===h);null===h||_||f(null);let w=o?(0,T0.jsxs)(T0.Fragment,{children:[r?(0,T0.jsxs)(Tx.Pressable,{accessibilityRole:"button",accessibilityState:{disabled:y},accessibilityLabel:"Delete every queued message",style:({pressed:e})=>[TH.headerAction,e&&TH.pressed,y&&TH.disabled],disabled:y,onPress:()=>{b(T5,()=>r(e.map(e=>e.messageId)))},children:[(0,T0.jsx)(rH,{size:12,color:s2.textPrimary,strokeWidth:2}),(0,T0.jsx)(Tx.Text,{style:TH.actionLabel,children:"Clear all"})]}):null,(0,T0.jsxs)(Tx.Pressable,{accessibilityRole:"button",accessibilityState:{disabled:v},accessibilityLabel:"Resume sending the queued messages",style:({pressed:e})=>[TH.headerAction,e&&TH.pressed,v&&TH.disabled],disabled:v,onPress:()=>{b(T1,a&&(()=>a()))},children:[(0,T0.jsx)(nw,{size:12,color:s2.textPrimary,strokeWidth:2}),(0,T0.jsx)(Tx.Text,{style:TH.actionLabel,children:"Resume"})]})]}):null,S=p?null:e.find(e=>e.needsAttention)?.caption,x=[TH.headerCount,S&&TH.captionReturned];return(0,T0.jsxs)(Tx.View,{style:TH.list,children:[(0,T0.jsxs)(Tx.View,{style:TH.box,testID:"queued-box",children:[(0,T0.jsxs)(Tx.View,{testID:"queued-header",style:[TH.header,o&&TH.headerPaused],accessibilityLiveRegion:"polite",children:[(0,T0.jsx)(Tx.Pressable,{accessibilityRole:"button",accessibilityState:{expanded:p},accessibilityLabel:"Queued messages",style:({pressed:e})=>[TH.headerToggle,e&&TH.pressed],onPress:()=>m(!p)}),(0,T0.jsxs)(Tx.View,{style:TH.headerLabels,pointerEvents:"none",children:[(0,T0.jsx)(Tx.Text,{style:[TH.headerLabel,o&&TH.headerLabelPaused],children:o?"Paused":"Queued"}),(0,T0.jsx)(Tx.Text,{style:TH.headerLabel,importantForAccessibility:"no",accessibilityElementsHidden:!0,children:"·"}),(0,T0.jsx)(Tx.Text,{style:x,children:e.length}),S?(0,T0.jsx)(Tx.Text,{style:TH.headerCaption,numberOfLines:1,children:`\xb7 ${S}`}):null]}),g?null:w,(0,T0.jsx)(Tx.View,{style:TH.chevron,pointerEvents:"none",children:p?(0,T0.jsx)(ss,{size:12,color:s2.textMuted,strokeWidth:2}):(0,T0.jsx)(rj,{size:12,color:s2.textMuted,strokeWidth:2})})]}),g&&w?(0,T0.jsx)(Tx.View,{style:[TH.headerActionsLine,TH.headerPaused],children:w}):null,p?(0,T0.jsx)(TY,{messageIds:e.map(e=>e.messageId),newestIsPersons:!e.at(-1)?.attribution,children:r=>e.map(e=>{let o=c.has(e.messageId);return(0,T0.jsx)(TK,{card:e,editor:s?.messageId===e.messageId?s:void 0,busy:o,editBlocked:o||void 0!==s||!n,steerHeld:l,onSend:()=>{b(e.messageId,t)},onDelete:()=>{b(e.messageId,i)},onMore:()=>f(e.messageId),onEditorLayout:r},e.messageId)})}):null]}),(0,T0.jsx)(ik,{visible:void 0!==_,title:_?.text,actions:[{label:"Edit message",icon:nb,closeBeforePress:!0,onPress:()=>{_&&b(_.messageId,n)}}],onClose:()=>f(null)})]})}var T3=oa(os()),T6={},T4=oa(oe()),T7=oa(os()),T8=oa(oe()),T9=oa(oe()),ke=oa(oo());function kt({ref:e,children:t,contentContainerStyle:i,...r}){return(0,ke.jsx)(T9.ScrollView,{ref:e,testID:"rupro-chat-transcript",...r,contentContainerStyle:ki.fill,children:(0,ke.jsx)(T9.View,{testID:"rupro-chat-transcript-content",style:i,children:t})})}var ki=T9.StyleSheet.create({fill:{flexGrow:1},anchorless:{overflowAnchor:"none"}}),kr=ki.anchorless,kn=oa(os()),ks=class{entries=new Map;sum=0;samples=0;px(e){return void 0===e?void 0:this.entries.get(e)?.px}estimate(){return this.samples>0?this.sum/this.samples:80}valid(e,t,i,r){let n,s,o=this.entries.get(e);return void 0!==o&&o.row===t&&o.layout===r&&(n=Object.entries(o.state),s=new Map(Object.entries(i)),n.length===s.size&&n.every(([e,t])=>s.get(e)===t))}remember(e,t,i,r,n){this.entries.has(e)||(this.samples+=1),this.sum+=t-(this.entries.get(e)?.px??0),this.entries.set(e,{px:t,row:i,state:r,layout:n})}sourceKeys(e,t,i){let r=i?.length!==e.length,n=e.map((e,n)=>{let s=t(e);return r||=i?.[n]!==s,s}),s;return{keys:n,changed:r,indexOf:e=>void 0===e?void 0:(s??=new Map(n.map((e,t)=>[e,t]))).get(e)}}retain(e){let t=new Set(e);for(let e of this.entries.keys())t.has(e)||this.entries.delete(e)}spacers(e,[t,i],[r,n],s){let[o,a,l,c]=[t,s,0,0];for(let t=this.px(e[o-1]);o>0&&void 0!==t;)a+=t,o-=1,t=this.px(e[o-1]);for(let t=i;tthis.valid(n[i],e.rows[i],e.rowState(i,e.rows[i]),t),[a,l]=[s-1,0];for(;a>=0&&l<=i&&o(a);a-=1)l+=this.px(n[a])??0;if(a<0||l>i)return null;let c=a;for(;c>0&&a-c+10?[Math.max(0,e.first-r),e.first-1]:n?this.nearestStale(e,t,1/0,r):null}clear(){this.entries.clear(),this.sum=0,this.samples=0}},ko=class{nodes=new Map;keys=new WeakMap;refs=new Map;observer=null;anchor=null;keyOf(e){return this.keys.get(e)}node(e){return void 0===e?void 0:this.nodes.get(e)}observeWith=e=>{this.observer=e,this.nodes.forEach(t=>e?.observe(t))};ref=e=>{let t=this.refs.get(e);return t||(t=t=>{let i=this.nodes.get(e);i&&(this.observer?.unobserve(i),this.nodes.delete(e)),"u">typeof Element&&t instanceof Element?(this.nodes.set(e,t),this.keys.set(t,e),this.observer?.observe(t)):this.refs.delete(e)},this.refs.set(e,t)),t};takeAnchor(e,t,[i,r],n){let s=e.getBoundingClientRect().top,[o,a]=[i,r];for(;o=t)return r;i=r,r=r.firstElementChild}}return i}(c,s):c),u=d&&d.getBoundingClientRect().top-s;this.anchor=l&&d&&void 0!==u?{key:l,part:d,top:u,scrollTop:e.scrollTop}:null}placeShift(e){let t=this.anchor?.part;return this.anchor&&t?.isConnected&&this.node(this.anchor.key)?t.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop-this.anchor.top-this.anchor.scrollTop:null}placeMoved(e){return Math.abs(this.placeShift(e)??0)>=.5}forgetAnchor(){this.anchor=null}},ka=oa(os()),kl=oa(oo());function kc({ref:e,roots:t,endAnchored:i,isFollowing:r,pin:n,rows:s,rowKeys:o,renderItem:a,rowState:l,layoutKey:c,contentContainerStyle:d,header:u,footer:h,emptyStateView:f,onScroll:p}){let m=(0,T7.useRef)(null),{view:g,rowRef:b,list:v}=function(e){let t,i,{rows:r,rowKeys:n,rowState:s,following:o,isFollowing:a,layoutKey:l,scroller:c,roots:d}=e,u=(t=(0,ka.useRef)({version:0,notify:()=>{}}),i=(0,ka.useCallback)(e=>(t.current.notify=e,()=>{t.current.notify=()=>{}}),[]),(0,ka.useSyncExternalStore)(i,()=>t.current.version),(0,ka.useCallback)(()=>{t.current.version+=1,t.current.notify()},[])),[h]=(0,kn.useState)(()=>new ks),f=(0,kn.useRef)(null),p=(0,kn.useRef)(null),m=(0,kn.useRef)(!1),[g]=(0,kn.useState)(()=>new ko),b=(0,kn.useRef)(!1),v=(0,kn.useRef)(0),y=(0,kn.useRef)(globalThis.innerHeight||800),_=(0,kn.useRef)(0),w=(0,kn.useRef)(0),S=(0,kn.useRef)(()=>{}),[x]=(0,kn.useState)(()=>new bx(()=>S.current())),[T]=(0,kn.useState)(()=>new bT(c,a)),{keys:k,changed:C,indexOf:L}=(0,kn.useMemo)(()=>h.sourceKeys(r,n.keyOf,p.current?.keys),[r,n.keyOf,h]),M=k.length,R=(e,t)=>k[t]===e?t:L(n.current(e))??Math.max(0,Math.min(t,M-1)),I=()=>{let e=M;for(let t=0;e>0&&t=M?{...P,last:null}:I(),E=M);let D=Math.min(R(P.first,P.firstAt),Math.max(0,E-1));E=Math.min(M,Math.max(E,D+1));let B=p.current,Q=null!==B&&B.sourceHead!==n.sourceHead,j=o||!A||m.current?0:P.slack;if(B&&Q&&!o&&A&&B.keys!==k)for(let e=B.first;e0&&Math.min(F,D)>0&&void 0===h.px(k[0]),K=(0,kn.useCallback)((e,t)=>{let i=Math.max(0,Math.min(t,e.scrollHeight-e.clientHeight));e.scrollTop>=0&&Math.abs(i-e.scrollTop)>=.5&&(x.wrote(i),e.scrollTop=i)},[x]),V=(0,kn.useCallback)(e=>{if(!bw(e.scrollTop))return void g.forgetAnchor();let t=p.current;g.takeAnchor(e,t?.keys??[],[t?.start??0,t?.end??0],!t?.following)},[g]),U=(0,kn.useCallback)(e=>{let[t,i]=[p.current,f.current],r=t&&g.node(t.keys[t.start]),n=t&&t.keys.slice(t.start,t.end).some(e=>void 0===h.px(e));if(!t||!i||!r||n)return;let s=function(e,t,i){let{n:r,following:n,scrollTop:s,viewport:o}=e,a=e=>t(e)??i,[l,c]=[s-o,s+2*o],[d,u,h]=[e.start,e.end,e.windowTop],f=h;for(let e=d;es+o||fs)for(;d>0&&void 0!==t(d-1)&&h>s;)d-=1,h-=t(d);else for(h=f,d=u;d0&&h>l&&void 0!==t(d-1);)d-=1,h-=t(d);for(;dd&&f-a(u-1)>s+3*o;)u-=1,f-=a(u)}return u=n?r:Math.max(u,d+1),d===e.start&&u===e.end?null:{start:d,end:u}}({n:t.keys.length,start:t.start,end:t.end,following:t.following&&e.scrollTop>=e.scrollHeight-2*e.clientHeight,windowTop:r.getBoundingClientRect().top-e.getBoundingClientRect().top+e.scrollTop,scrollTop:e.scrollTop,viewport:e.clientHeight},e=>h.px(t.keys[e]),h.estimate());if(s){let e=s.end>=t.keys.length?null:t.keys[s.end-1],r=s.start===t.start?i.measure:null,n={first:t.keys[s.start],firstAt:s.start,last:e};f.current={...i,...n,lastAt:s.end-1,measure:r},u()}},[h,u,g]),Z=(0,kn.useCallback)(()=>{let[e,t]=[p.current,f.current];if(!e||!t||0===e.keys.length)return;let i=`${e.layoutKey}:${v.current}`;if(t.measure&&void 0===h.px(t.measure.to))return;let r=300-(Date.now()-w.current);if(e.following&&r>0)return void x.pokeIn(r);let n=Date.now()-_.current,s=e.following&&0===e.first&&n>=1e3,o=h.next(e,i,3*y.current,8,s);s?_.current=Date.now():!o&&e.following&&0===e.first&&x.pokeIn(1e3-n);let a=o&&{from:e.keys[o[0]],fromAt:o[0],to:e.keys[o[1]],toAt:o[1]};(a?.from!==t.measure?.from||a?.to!==t.measure?.to||t.slack>0)&&(f.current={...t,measure:a},m.current=!0,x.quiet(32),u())},[h,x,u]);(0,kn.useLayoutEffect)(()=>{S.current=Z,f.current&&f.current.scope!==n.scope&&(h.clear(),x.release(),g.forgetAnchor()),C&&p.current?.keys!==k&&h.retain(k);let e=E>=M?null:k[E-1],t=F0&&x.poke()}),(0,kn.useLayoutEffect)(()=>{let e=c();if(!e)return;let t=()=>{let t=e.scrollHeight-e.clientHeight,{by:i}=x.scrolled(e.scrollTop,t,()=>g.placeMoved(e));"reader"===i&&V(e),"reader"!==i&&("layout"!==i||b_())||U(e)},i=x.attach(e);return e.addEventListener("scroll",t,{passive:!0}),()=>{i(),e.removeEventListener("scroll",t),x.release()}},[c,x,V,U,g,T,d]);let G=(0,kn.useCallback)((e,t)=>{let[i,r]=[c(),p.current];if(!i||!r)return t();y.current=i.clientHeight,v.current=i.clientWidth;let n=`${r.layoutKey}:${v.current}`;for(let t of e){let e=g.keyOf(t.target),i=r.indexOf(e);if(void 0!==e&&void 0!==i){let s=r.rows[i];h.remember(e,t.contentRect.height,s,r.rowState(i,s),n)}}d?.restoreAll();let s=!r.following&&x.mayCorrect()&&bw(i.scrollTop)?g.placeShift(i):null,o=i.scrollHeight-i.clientHeight,{by:a,moved:l}=x.reconciled(i.scrollTop,o);null!==s&&K(i,i.scrollTop-("layout"===a?l:0)+s),t(),V(i),U(i),x.poke()},[c,h,x,K,U,g,V,d]),Y=(0,kn.useCallback)((e,t)=>{let i=c();i&&!p.current?.following&&(t||x.mayCorrect())&&(K(i,i.scrollTop+e),b.current=!0)},[c,x,K]),X=(0,kn.useMemo)(()=>({afterResize:G,keepInPlace:Y,observeWith:e=>{g.observeWith(e),d?.observeWith(e)},settled:()=>d?.settled(x)??x.whenSettled(),syncAnchoring:()=>T.sync(),holdPlace:e=>T.hold(e),watchMotion:e=>{x.onMotion=e},wrote:e=>x.wrote(e)}),[G,Y,g,x,T,d]);return{view:{m0:F,m1:O,start:D,end:E,above:N,mid:z,bottom:$,measuring:q},rowRef:g.ref,list:X}}({roots:t,rows:s,rowKeys:o,rowState:l,following:i,isFollowing:r,layoutKey:c,scroller:(0,T7.useCallback)(()=>m.current?.getScrollableNode(),[])});(0,T7.useImperativeHandle)(e,()=>({getScrollableNode:()=>m.current?.getScrollableNode(),scrollToOffset:({offset:e,animated:t})=>{v.wrote(e),m.current?.scrollTo({y:e,animated:t})},scrollToEnd:e=>m.current?.scrollToEnd(e),...v}),[v]);let y=(0,T7.useRef)(""),_=`${o.scope}:${s.length>0}`;(0,T7.useLayoutEffect)(()=>{y.current!==_&&(y.current=_,n())},[_,n]);let w=(e,t)=>{let i=o.keyOf(e);return(0,kl.jsx)(T8.View,{ref:b(i),children:a({item:e,index:t})},i)};return(0,kl.jsxs)(kt,{ref:m,contentContainerStyle:d,keyboardShouldPersistTaps:"handled",onScroll:p,scrollEventThrottle:32,children:[(0,kl.jsx)(T8.View,{style:kr,children:u(g.measuring)}),0===s.length?f:(0,kl.jsxs)(T7.Fragment,{children:[(0,kl.jsx)(T8.View,{style:[kr,{height:g.above}]}),s.slice(g.m0,g.m1).map((e,t)=>w(e,g.m0+t)),(0,kl.jsx)(T8.View,{style:[kr,{height:g.mid}]}),s.slice(g.start,g.end).map((e,t)=>w(e,g.start+t)),(0,kl.jsx)(T8.View,{style:[kr,{height:g.bottom}]})]},o.scope),h]})}var kd=oa(oo());function ku(e){let{tail:t,rowKeys:i,rows:r,renderItem:n,contentContainerStyle:s,onScroll:o,footer:a}=e;if("web"===T4.Platform.OS){let{roots:l,rowState:c,header:d,emptyStateView:u,layoutKey:h}=e;return(0,kd.jsx)(kc,{...t.pageListProps,rows:r,rowKeys:i,roots:l,renderItem:n,rowState:c,contentContainerStyle:s,footer:a,emptyStateView:u,onScroll:o,header:d,layoutKey:h})}return(0,kd.jsx)(T4.FlatList,{...t.listProps,data:r,keyExtractor:i.keyOf,renderItem:n,contentContainerStyle:s,keyboardShouldPersistTaps:"handled",onScroll:o,onScrollBeginDrag:t.beginUserScroll,onScrollEndDrag:t.endUserDrag,onMomentumScrollBegin:t.beginMomentum,onMomentumScrollEnd:t.endMomentum,scrollEventThrottle:32,onContentSizeChange:t.pinToTailAfterContentResize,onLayout:t.pinToTail,maintainVisibleContentPosition:e.hasHeader?_5:_2,ListHeaderComponent:e.nativeHeader,ListFooterComponent:a,ListEmptyComponent:e.emptyStateView})}var kh=oa(os()),kf=oa(os()),kp=oa(oe());function km(e){if(e.length<=160)return e.replace(/\s+/g," ").trim();let t="",i=!1,r=/\s+/y;for(let n=0;n0;continue}if(i&&(t+=" ",i=!1),(t+=e[n++]).length>80)break}return t}var kg=/^\s*(?:.*[\\/])?(?:ba|z|k|da|fi)?sh(?:\.exe)?\s+-[a-zA-Z]*c\s+(['"])([\s\S]*)\1\s*$/;function kb(e){return kg.exec(e)?.[2]??e}var kv=["query","pattern","directory","command","cmd","url","description"],ky=["command","cmd"];function k_(e){let t=km(kb(function(e){if(null==e)return"";if("string"==typeof e)return e;if("object"!=typeof e)return String(e);try{return JSON.stringify(function e(t,i,r){if("string"==typeof t)return t.length>160?`${t.slice(0,160)}…`:t;if(!t||"object"!=typeof t)return t;if(r.has(t))return"[circular]";if(i>=2)return"[…]";if(r.add(t),Array.isArray(t)){let n=t.slice(0,8).map(t=>e(t,i+1,r));return t.length>8&&n.push("…"),n}let n={},s=0;for(let o in t)if(Object.hasOwn(t,o)){if(s>=8){n["…"]="…";break}n[o]=e(t[o],i+1,r),s+=1}return n}(e,0,new WeakSet))??""}catch{return""}}(e)));return t.length<=80?t:`${t.slice(0,79)}…`}function kw(e){let t=kx(e),i=function(e){if(!e||"object"!=typeof e)return null;let t=null!==kk(e.query)||null!==kk(e.pattern)?void 0:e.path,i=e.file_path??e.filePath??t??e.notebook_path??function(e){if(Array.isArray(e.changes)){for(let t of e.changes)if("object"==typeof t&&null!==t&&"string"==typeof t.path)return t.path}}(e);return"string"==typeof i&&i.length>0?i:null}(t),r=function(e,t){if(t){let e=t.replace(/\s+/g," ").trim();if(e.length<=80)return e;let i=e.slice(e.length-79),r=i.search(/[\\/]/);return`…${r>0?i.slice(r):i}`}if(e&&"object"==typeof e){let t=kT(e,kv);if(t)return t}return k_(e)}(t,i);return{label:r,filePath:i,hasDetail:!!(null!==t&&"object"==typeof t&&(Array.isArray(t)?t.length>0:Object.keys(t).length>0))||"string"==typeof t&&km(t)!==r,formatDetail:()=>kS(function(e){if(null==e)return"";if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return String(e);try{return JSON.stringify(e,null,2)??""}catch{return""}}(t))}}function kS(e){return e.length>4e3?`${e.slice(0,4e3)}…`:e}function kx(e){if("string"!=typeof e)return e;let t=e.trimStart()[0];if("{"!==t&&"["!==t)return e;try{let t=JSON.parse(e);return null!==t&&"object"==typeof t?t:e}catch{return e}}function kT(e,t){for(let i of t){let t=kk(e[i]);if(t)return t}return null}function kk(e){return"string"==typeof e&&e.trim()?k_(e):Array.isArray(e)&&e.length>0&&e.every(e=>"string"==typeof e)?k_(e.join(" ")):null}var kC={runningPreview:"Running {{preview}}",runningCommand:"Running command",runningNamedPreview:"Running {{toolName}} {{preview}}",runningNamed:"Running {{toolName}}",countOne:"1 tool call",countN:"{{value0}} tool calls",moreCalls:"+{{value0}} more",failedCount:"{{value0}} failed",failedCallsLabel:"Failed tool calls: {{value0}}",interruptedCount:"{{value0}} interrupted",interruptedCallsLabel:"Interrupted tool calls: {{value0}}"},kL=new Set(["bash","shell","powershell","terminal","execute","run_command","run_shell_command","shell_command","exec_command","run_terminal_cmd","run_terminal_command"]);function kM(e){return kL.has(e.trim().toLowerCase())}function kR(e){let t=kw(e.input).label,i=kM(e.name);return{key:i?t?"runningPreview":"runningCommand":t?"runningNamedPreview":"runningNamed",toolName:e.name,preview:t,isCommand:i}}function kI(e,{activeTurnIsWorking:t}){if(!1===t)return null;let i=e.filter(g4);for(let e=i.length-1;e>=0;e--){let r=i[e];if(r&&("running"===r.state||null==r.state&&!0===t))return r}return null}var kA={"history-repaired":"Part of this chat's history couldn't be loaded.","history-item-too-large":"This part of the chat was too large to show."};function kP(e){return void 0!==e&&Object.hasOwn(kA,e)}function kE(e){return e.blocks.filter(g6).map(t=>kP(t.presentation)?kA[t.presentation]:"user"===e.role?t.text:t9(t.text)).filter(e=>e.trim().length>0).join(` `)}var kD=oa(os()),kB=oa(oe()),kQ=oa(oo());function kj({startedAt:e,workedSeconds:t,verdict:i,expanded:r=!1,onToggleExpanded:n}){let s=null!=t,o=J({workedSeconds:t,elapsedSeconds:function(e,t){let[i]=(0,kD.useState)(()=>Date.now()),[r,n]=(0,kD.useState)(()=>Date.now());return(0,kD.useEffect)(()=>{if(!t)return;n(Date.now());let e=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(e)},[t]),t?er(e,i,r):0}(e,!s),verdict:i});return s&&n?(0,kQ.jsxs)(kB.Pressable,{style:({pressed:e})=>[kF.row,kF.bar,e&&kF.pressed],onPress:n,hitSlop:6,accessibilityRole:"button",accessibilityState:{expanded:r},accessibilityLabel:U.toggleDetails,children:[(0,kQ.jsx)(kB.Text,{style:kF.label,children:o}),(0,kQ.jsx)(kB.View,{style:r?kF.caretOpen:void 0,children:(0,kQ.jsx)(rj,{size:14,color:s2.textMuted,strokeWidth:2})})]}):(0,kQ.jsx)(kB.View,{style:[kF.row,kF.bar],children:(0,kQ.jsx)(kB.Text,{style:kF.label,numberOfLines:1,children:o})})}var kF=kB.StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:s6.xs,minHeight:28,paddingHorizontal:s6.md},bar:{borderBottomWidth:kB.StyleSheet.hairlineWidth,borderBottomColor:s2.borderSubtle},pressed:{opacity:.6},label:{color:s2.textMuted,fontSize:s7.bodySize,flexShrink:1},caretOpen:{transform:[{rotate:"90deg"}]}}),kO=oa(oe()),kW={compaction:"Context compacted",contextCleared:"Context cleared",plan:"Plan"},kH="This chat is still open in a terminal agent.",kN="Quit that agent to continue the chat here.",kz="Start a new chat to continue.",k$="Background tasks are still running.",kq="Wait for the background tasks to finish.",kK="The agent is still starting.",kV="Wait for the agent to finish starting.",kU="The agent is still working.",kZ={theAgent:"The agent",providerStartFailed:"{{agent}} stopped before it finished starting.",runCommandAgain:"Run /{{command}} again.",sendToTryAgain:"Send your message to try again.",sendAgainToTryOnceMore:"Send your message again to try once more.",couldNotStart:"{{agent}} couldn't start.",couldNotRestart:"{{agent}} couldn't restart.",startTimedOut:"{{agent}} took too long to start (no response to {{method}} after {{seconds}}s).",startTimedOutKeepsHappening:"If this keeps happening, the computer running this chat may be overloaded.",codexCliTooOld:"Codex {{installedVersion}} is too old for chats. Update to {{minimumVersion}} or newer.",argumentsUnsupportedOption:"Saved Arguments contain an unsupported option ({{option}}).",argumentsMissingValue:"Saved Arguments need a value for {{option}}.",argumentsMultipleValues:"Saved Arguments give {{option}} more than one value.",argumentsPositionalPrompt:"Saved Arguments include a prompt.",editSavedArguments:"Edit them in Settings > Agents > Arguments.",terminalAgentHoldsChat:kH,quitTerminalAgent:kN,startNewChat:kz,notSignedIn:"{{agent}} is not signed in.",claudeSystemNotSignedIn:"Claude isn't signed in. Run `{{loginCommand}}`, or choose an account in Claude Accounts settings.",claudeManagedNotSignedIn:"This Claude account isn't signed in. Sign in again in Claude Accounts settings.",codexSystemNotSignedIn:"Codex isn't signed in. Run `{{loginCommand}}`.",codexManagedNotSignedIn:"This Codex account isn't signed in. Sign in again in Codex Accounts settings.",antigravityNotSignedIn:"Antigravity isn't signed in. Sign in under Settings → Accounts → Antigravity. Then send your message again.",agentCommandNotSignedIn:"Sign in to {{agent}} with `{{loginCommand}}` on the computer running this chat.",interactiveAgentNotSignedIn:"Sign in to {{agent}} by running `{{loginCommand}}` and using `{{slashCommand}}` on the computer running this chat.",agentNotSignedIn:"Sign in to {{agent}}.",cliMissing:"{{agent}} wasn't found on the computer running this chat. Install it, or check its Command in Settings → Agents.",signInFirst:"Sign in first.",signInThenRunCommand:"Sign in, then run /{{command}} again.",signInThenSend:"Sign in, then send your message again.",thenSendAgain:"Then send your message again.",historyTooLarge:"This conversation's history is too large to restore here.",managedAccountEnvOverride:"This Claude launch sets its own Anthropic sign-in variables. Remove them to use a managed Claude account.",accountSwitchInProgress:"{{agent}}'s setup is changing on this host. Try again after it finishes.",managedAccountUnsupported:"While a Claude account is added in WSL, Claude chats need a Windows Claude account.",launchFolderMissing:"The folder this chat ran in no longer exists. Restore it to continue this chat.",historyInOtherAccount:"This chat's history is in another Claude account. Switch back to that account to continue it.",claudeAccountFolderMissing:"The selected Claude account's folder is missing. Sign in to it again or choose another account.",claudeAccountSetupFailed:"The selected Claude account could not be set up. Try again or choose another account.",agentCommandNotRunnable:"{{agent}}'s Command in Settings → Agents must be a program path or name RuFlo can find, with no arguments or variables. Change it or reset it.",runtimeNotInstalled:"{{agent}} isn't installed on the computer running this chat. Install it from the chat in a current version of RuFlo.",chooseClaudeAccount:"Choose or add one in Claude Accounts settings.",chooseClaudeAccountThenRunCommand:"Choose or add one in Claude Accounts settings, then run /{{command}} again.",chooseClaudeAccountThenSend:"Choose or add one in Claude Accounts settings, then send your message again.",providerExitedRow:"{{agent}} stopped while this response was in progress. You can continue in this conversation.",providerExitedRejection:"{{agent}} stopped before this message was sent.",providerExitedAnswer:"{{agent}} has stopped, so your answer was not sent. Send a message to continue.",providerRejected:"{{agent}} didn't accept this message.",providerRejectedQuoted:"{{agent}} didn't accept this message: {{detail}}.",attachmentEmpty:"An image on this message is empty, so the message was not sent.",attachmentTooLarge:"An image on this message is too large, so the message was not sent.",attachmentLargerThan:"An image on this message is larger than {{size}} MB, so the message was not sent.",attachmentTooMany:"This message has too many images, so it was not sent.",attachmentAtMost:"{{agent}} accepts at most {{limit}} images in one message, so this message was not sent.",attachmentTotalTooLarge:"The images on this message are too large together, so the message was not sent.",attachmentTotalMoreThan:"The images on this message add up to more than {{size}} MB, so the message was not sent.",attachmentUnsupportedType:"{{agent}} accepts only PNG, JPEG, GIF, and WebP images, so this message was not sent.",attachmentNotAFile:"An image on this message isn't a file, so the message was not sent.",attachmentNoSource:"An image on this message has no file to send, so the message was not sent.",attachmentInvalid:"An attachment on this message can't be sent to the agent.",attachmentUnreadable:"An attachment on this message couldn't be read, so the message was not sent.",emptyMessage:"This message is empty, so it was not sent.",commandUnavailable:"This command isn't available in {{agent}} chats, so it was not sent.",queueFull:"Too many messages were waiting for the agent, so this one was not sent.",writeFailed:"RuFlo couldn't hand this message to the agent, so it was not sent.",cancelled:"This message was withdrawn before the agent started it.",chatClosed:"The chat closed before this message was sent.",hostRestarted:"RuFlo restarted before this message was sent.",notDelivered:"This message was not delivered.",notDeliveredSendAgain:"This message was not delivered. Send it again to continue.",commandRefused:"This command didn't run.",commandRefusedTryAgain:"This command didn't run. Try it again.",backgroundTasksRunning:k$,waitForBackgroundTasks:kq,agentStarting:kK,waitForStart:kV,agentStillWorking:kU,runCommandWhenDone:"Run /{{command}} when it's done.",commandAfterAnswer:"Answer the agent's question or approval, then run /{{command}}.",compactionFailed:"Compaction failed.",compactionFailedQuoted:"Compaction failed: {{detail}}.",compactionUnconfirmed:"Compaction completion is unconfirmed.",cancelUnconfirmed:"Cancellation was not confirmed.",stopRefused:"{{agent}} didn't stop.",stopRefusedQuoted:"{{agent}} didn't stop: {{detail}}.",couldNotStop:"Couldn't stop {{agent}}.",couldNotStopTheAgent:"Couldn't stop the agent.",noTurnToStop:"{{agent}} had no turn running to stop.",backgroundTaskNotStopped:"The background task wasn't stopped.",backgroundTasksNotStopped:"The background tasks weren't stopped.",answerUnconfirmed:"Your answer was recorded but the agent did not confirm it.",hostFault:"RuFlo ran into a problem, so this didn't go through.",hostFaultTryAgain:"RuFlo ran into a problem, so this didn't go through. Try again.",hostStopped:"{{agent}} never finished starting, so RuFlo stopped it.",providerRateLimited:"{{agent}} is rate-limited and retrying.",providerRetrying:"{{agent}} hit a temporary problem and is retrying.",providerRetryingQuoted:"{{agent}} is retrying: {{detail}}.",providerRetryNumber:"Retry {{attempt}}.",providerRetryNumberOf:"Retry {{attempt}} of {{maxRetries}}.",providerRetryLastError:"Last error: {{detail}}.",usageLimitReached:"{{agent}} hit its usage limit.",usageLimitReachedNamed:"{{agent}} hit its {{window}} limit.",usageLimitWindowSession:"session",usageLimitWindowWeekly:"weekly",usageLimitWindowWeeklyModel:"weekly model",usageLimitWindowCredits:"extra usage",usageLimitResetsAt:"It resets at {{when}}.",usageLimitSendAfterReset:"Send a message once it resets to continue.",previousExitUnverifiable:"Couldn't stop {{agent}} from before.",sessionNotRestored:"{{agent}} couldn't reopen its earlier session, so this chat continues in a new one. {{agent}} doesn't remember the earlier messages."},kG=(e,t={})=>{let i=new Map(Object.entries(t));return kZ[e].replace(/\{\{(\w+)\}\}/g,(e,t)=>i.get(t)??e)},kY=/[。!?]$/;function kX(e){return e.map((t,i)=>0===i||kY.test(e[i-1])?t:` ${t}`).join("")}var kJ={session:"usageLimitWindowSession",weekly:"usageLimitWindowWeekly",weeklyModel:"usageLimitWindowWeeklyModel",credits:"usageLimitWindowCredits"},k0=oa(oo()),k1={warning:s2.statusAmber,error:s2.statusRed,notice:s2.textMuted};function k5({blocks:e,fontScale:t,onOpenFile:i,onLongPress:r}){let n=e.find(e=>"text"===e.type&&(void 0!==e.presentation||void 0!==e.tone)),s=[k2.faint,wj(s7.bodySize,t)];if(!n){let t=e.filter(g6).map(e=>e.text).join(` @@ -1008,7 +1008,7 @@ ${e.content}`).join(` `);eS.writeText(e).then(()=>{D(null),ee()}).catch(()=>{sy(),U("Couldn't copy drafts",1500)})}},{label:"Discard & Leave",destructive:!0,onPress:()=>{D(null),ee()}}],onClose:()=>D(null)}),(0,Bi.jsx)(iB,{visible:null!=A,title:"Discard Changes",message:"Replace the phone draft with the latest desktop file?",confirmLabel:"Discard",destructive:!0,onConfirm:ei,onCancel:()=>P(null)}),(0,Bi.jsx)(AK,{visible:null!=Q,title:"Rename Terminal",defaultValue:Q?.title||"Terminal",placeholder:"Terminal name",onSubmit:e=>{eu(e)},onCancel:()=>B(null)}),(0,Bi.jsx)(AK,{visible:v,title:"New Browser",message:!0===q?"Enter a URL, or leave blank for a desktop browser tab.":"Desktop streaming is unavailable. Enter a web URL to open on this phone.",defaultValue:"",placeholder:"https://example.com",submitLabel:!0===q?"Open":"Open on phone",allowEmpty:!0===q,selectTextOnFocus:!0,keyboardType:"ios"===EI.Platform.OS?"url":"default",onSubmit:e=>{if(!0!==q){let t=ai(e);return t&&/^https?:/i.test(t)?(sf(t),void b(!1)):void U("Enter an HTTP or HTTPS address.",1800)}ec(e).then(e=>{e&&b(!1)})},onCancel:()=>b(!1)}),(0,Bi.jsx)(Dj,{visible:F,onClose:()=>O(!1),onKeysChanged:j,onManageShortcuts:en}),(0,Bi.jsx)(D8,{visible:z,client:l,onClose:()=>$(!1),onReady:()=>$(!1)}),(0,Bi.jsx)(ik,{visible:null!=W,title:W?.label??"Shortcut",message:"Remove this custom shortcut?",actions:[{label:"Remove",destructive:!0,onPress:()=>{W&&er(W),H(null)}}],onClose:()=>H(null)})]})}var Bn=oa(oo());function Bs({controller:e}){let{setMobileSessionRootRef:t}=e,i=function(e){let{hostId:t,worktreeId:i,activeSessionTabId:r,activeHandle:n,showNativeChat:s,activeBrowserTab:o,activeFileTab:a,activeMarkdownTab:l,activePendingTerminalTab:c,showEmptyState:d,showLoadingState:u}=e,h=d||u||o||a||l||c?null:s?"chat":n?"terminal":null,f=h?JSON.stringify([t,i,r,h]):null,[p,m]=(0,oT.useState)(null),g=null!==f&&f===p;return(0,oT.useEffect)(()=>{m(e=>e===f?e:null)},[f]),rD(g?()=>(m(null),!0):null),{kind:h,expanded:g,toggle:()=>m(g?null:f)}}(e);return(0,Bn.jsx)(ox,{expanded:i.expanded,kind:i.kind,children:(0,Bn.jsxs)(oy.View,{ref:t,testID:"rupro-session-root",style:oE.container,children:[(0,Bn.jsxs)(oy.View,{style:oE.kavInner,children:[(0,Bn.jsx)(EM,{controller:e,focus:i}),(0,Bn.jsx)(PU,{controller:e,expanded:i.expanded,focusedTerminal:i.expanded&&"terminal"===i.kind})]}),(0,Bn.jsx)(Br,{controller:e})]})})}var Bo=oa(os()),Ba=oa(os()),Bl=oa(ot()),Bc=oa(oi()),Bd=oa(os());async function Bu(e,t){let i=await eJ(e,t);return{isGithubRepo:i.ok&&null!==i.result}}async function Bh(e,t){let[i,r]=await Promise.all([Bf(e,t),Bp(e,t).catch(()=>null)]);return{branch:i?.branch??null,headSha:i?.head??r?.summary.headOid??null,status:i}}async function Bf(e,t){let i=await eS.request(e,{worktree:`id:${t}`}),r=eS.interpret(i);return r.accepted?r.value:null}async function Bp(e,t){let i=await ts(e,t);if(!i)return null;let r=await ex.request(e,{worktree:`id:${t}`,baseRef:i}),n=ex.interpret(r);return n.accepted?n.value:null}var Bm=oa(os()),Bg=oa(oi()),Bb="selector_not_found",Bv=/(?:: |\n)[ \t]*$/,By=oa(os()),B_=oa(os()),Bw=oa(oe());function BS(){return D_.map(e=>e.id)}function Bx(e=BS()){return{version:2,orderedBuiltInIds:[...e],visibleBuiltInIds:[...e]}}function BT(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)?e:null}function Bk(e,t){let i=new Set,r=[];for(let n of e)!t.has(n)||i.has(n)||(i.add(n),r.push(n));return r}function BC(){return BS()}async function BL(){try{let e=await sh.getItem("orca:terminal-accessory-layout");return e?function(e,t=BS()){let i=Bx(t);if(!e||"object"!=typeof e)return i;let r=new Set(t);if(2===e.version){let n=BT(e.orderedBuiltInIds),s=BT(e.visibleBuiltInIds);if(!n||!s)return i;let{ordered:o,inserted:a}=function(e,t){let i=new Set(e),r=[...e],n=[];for(let e=0;e=0;i--){let e=r.indexOf(t[i]);if(-1!==e){o=e+1;break}}r.splice(o,0,s),i.add(s),n.push(s)}return{ordered:r,inserted:n}}(Bk(n,r),t),l=new Set(Bk(s,r));for(let e of a)l.add(e);return{version:2,orderedBuiltInIds:o,visibleBuiltInIds:o.filter(e=>l.has(e))}}if(1===e.version){let n=BT(e.visibleBuiltInIds),s=BT(e.knownBuiltInIds);if(!n||!s)return i;let o=new Set(s.filter(e=>r.has(e))),a=new Set(Bk(n,r));for(let e of t)o.has(e)||a.add(e);return{version:2,orderedBuiltInIds:[...t],visibleBuiltInIds:t.filter(e=>a.has(e))}}return i}(JSON.parse(e)):Bx()}catch{return Bx()}}var BM=oa(os()),BR=new TextEncoder,BI=new Map([["Escape","escape"],["Esc","escape"],["Tab","tab"],["Backspace","backspace"],["Delete","delete"],["Insert","insert"],["ArrowUp","arrowUp"],["ArrowDown","arrowDown"],["ArrowLeft","arrowLeft"],["ArrowRight","arrowRight"],["Home","home"],["End","end"],["PageUp","pageUp"],["PageDown","pageDown"],["F1","f1"],["F2","f2"],["F3","f3"],["F4","f4"],["F5","f5"],["F6","f6"],["F7","f7"],["F8","f8"],["F9","f9"],["F10","f10"],["F11","f11"],["F12","f12"]]);function BA(e){null!==e.current&&(clearTimeout(e.current),e.current=null)}function BP(e,t,i=50){BA(e),e.current=setTimeout(()=>{e.current=null,t()},i)}var BE=oa(os());function BD(){return{autoCreatedForWorktree:null,sawSessionTabs:!1}}var BB=oa(os()),BQ=oa(os()),Bj=oa(oi()),BF=oa(os()),BO=oa(os());async function BW(e,t){return!!await e()&&t()}var BH=/[\u2013\u2014]/g;function BN(e){return e.replace(BH,"--")}var Bz=oa(os());function B$(e,t){let i=e.current;(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&(i.value=t)}function Bq(e){e.generation+=1;let t=[...e.activeRequests,...e.pendingBatches.flatMap(e=>e.requests)];e.activeRequests=[],e.pendingBatches=[],e.current=null,t.forEach(({resolve:e})=>e(!1))}async function BK(e,t){let i=!0;for(;e.generation===t;){let r=e.pendingBatches.shift();if(!r)return e.current=null,i;e.activeRequests=r.requests;let n=await r.sender(r.handle,r.payload).catch(()=>!1);if(e.generation!==t)break;e.activeRequests=[],r.requests.forEach(({resolve:e})=>e(n)),i&&=n}return!1}var BV=oa(os());async function BU(e){return await e()?{kind:"allow-raw"}:{kind:"suppress-raw"}}var BZ=[0,750,3e3];function BG(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:null}function BY(e){return{hostCols:BG(e.cols),hostRows:BG(e.rows)}}var BX=class{attemptsByHandle=new Map;absentSinceExhaustion=new Set;announcedExhaustion=new Set;retryGenerationByHandle=new Map;attempts(e){return this.attemptsByHandle.get(e)??0}chargeAttempt(e){this.attemptsByHandle.set(e,this.attempts(e)+1)}retryGeneration(e){let t=this.retryGenerationByHandle.get(e);if(t)return t;let i={};return this.retryGenerationByHandle.set(e,i),i}isRetryGenerationCurrent(e,t){return this.retryGenerationByHandle.get(e)===t}observeResize(e,t,i){let{hostCols:r,hostRows:n}=BY(t),s=r??80,o=n??24;return i?.cols===s&&i.rows===o&&this.markConverged(e),[s,o]}markConverged(e){this.forget(e)}shouldAnnounceExhaustion(e){return!this.announcedExhaustion.has(e)&&(this.announcedExhaustion.add(e),!0)}notifyListedHandles(e){for(let t of Array.from(this.attemptsByHandle.keys()))if(!(3>this.attempts(t))){if(!e.has(t)){this.absentSinceExhaustion.add(t);continue}this.absentSinceExhaustion.delete(t)&&this.forget(t)}}forget(e){this.attemptsByHandle.delete(e),this.absentSinceExhaustion.delete(e),this.announcedExhaustion.delete(e),this.retryGenerationByHandle.delete(e)}clear(){this.attemptsByHandle.clear(),this.absentSinceExhaustion.clear(),this.announcedExhaustion.clear(),this.retryGenerationByHandle.clear()}},BJ=oa(os());function B0(e,t,i){if(!t)return e;let r=e[t]??"",n="function"==typeof i?i(r):i;return n===r?e:{...e,[t]:n}}function B1(e,t,i){let r=e.get(t)===i?t:i.handle;return e.get(r)===i&&(e.delete(r),!0)}function B5(e,t){let i=e;for(let r of Object.keys(e))t.has(r)||(i===e&&(i={...e}),delete i[r]);return i}function B2(e,t){for(let i of e.keys())t.has(i)||e.delete(i)}function B3(e){return e.leafId?`leaf:${e.leafId}`:`tab:${e.id}`}var B6=oa(os()),B4=oa(oe()),B7=oa(os()),B8=oa(oe()),B9=oa(os()),Qe=oa(oi()),Qt=oa(os()),Qi=oa(os());function Qr(e,t){return e.add(t),{remove:()=>{e.delete(t)}}}var Qn=oa(a());function Qs(e){var t,i,r,n,s;return t=e.getCurrentGeneration(),i=e.generation,r=e.getEnabled(),n=e.getActiveId(),s=e.dictationId,t===i&&r&&n===s}function Qo(e){return e.getCurrentGeneration()===e.generation&&e.getEnabled()}function Qa(e){e.getCurrentGeneration()===e.generation&&e.setIdle()}async function Ql(e){let{client:t,dictationId:i}=e;e.clearActiveId(i),Qa(e),await D0.request(t,{dictationId:i}).catch(()=>{})}async function Qc(e){let{client:t,dictationId:i}=e;try{let e=await DY.request(t,{dictationId:i});DY.interpret(e)}catch(s){let r=Qs(e);if(r)try{e.rollbackRecordingStart()}catch{}e.clearActiveId(i),await D0.request(t,{dictationId:i}).catch(()=>{});let n=r&&Qo(e);if(Qa(e),!n)return!1;throw s}if(!Qs(e))return await Ql(e),!1;try{if(!e.commitRecordingStart())throw Error("Failed to start microphone recording")}catch(s){let r=Qs(e);try{e.rollbackRecordingStart()}catch{}e.clearActiveId(i),await D0.request(t,{dictationId:i}).catch(()=>{});let n=r&&Qo(e);if(Qa(e),!n)return!1;throw s}return!0}function Qd(e,t){return e.trim()?`${e.trimEnd()} ${t}`:t}var Qu=oa(os()),Qh=oa(os()),Qf=oa(os()),Qp=(i=new Map,r=new Set,n=()=>{for(let e of r)e()},{subscribe:e=>(r.add(e),()=>{r.delete(e)}),read:e=>i.get(e),write:(e,t)=>{(function(e,t,i){for(e.delete(t),e.set(t,i);e.size>128;){let t=e.keys().next().value;if(void 0===t)break;e.delete(t)}})(i,e,t),n()},forget:e=>{i.delete(e)&&n()},forgetWhere:e=>{let t=[...i.keys()].filter(e);for(let e of t)i.delete(e);t.length>0&&n()},clearForTests:()=>i.clear()});function Qm({kind:e,promptKey:t,detectedPromptKey:i,scopeKey:r,sessionKey:n,observing:s}){let o=JSON.stringify([e,r]),a=(0,Qf.useRef)(new Map),l=(0,Qf.useMemo)(()=>{let e=a.current.get(r);return e?.sessionKey===n&&e.promptKey===i?e:{sessionKey:n,promptKey:i}},[n,i,r]),c=(0,Qf.useSyncExternalStore)(Qp.subscribe,()=>Qp.read(o));(0,Qf.useLayoutEffect)(()=>{s&&a.current.set(r,l)},[s,i,r,n,l]),(0,Qf.useEffect)(()=>{s&&void 0!==c&&(c.sessionKey!==n||c.promptKey!==i)&&Qp.forget(o)},[s,c,i,o,n]);let d=null!==t&&c?.sessionKey===n&&c.promptKey===t,u=e=>{let i=a.current.get(r);null!==t&&i===l&&i.sessionKey===n&&i.promptKey===t&&Qp.write(o,{sessionKey:n,promptKey:t,state:e})};return{showPrompt:null!==t&&!d,collapsed:d&&c?.state==="collapsed",dismissPrompt:()=>u("answered"),collapsePrompt:()=>u("collapsed"),expandPrompt:()=>Qp.forget(o)}}var Qg=oa(os());function Qb(e){return"user"!==e.role?null:vF(e.blocks.filter(g6).map(e=>vL(e.text)).join(" "))||null}function Qv(e,t,i){let r=Object.entries(e[t]??{});for(let e of i){let t=r.findIndex(([t])=>t===e.messageId);-1!==t&&r.splice(t,1),r.push([e.messageId,e.images])}let n={...e};for(let e of(delete n[t],n[t]=Object.fromEntries(r.slice(-32)),Object.keys(n).slice(0,-8)))delete n[e];return n}function Qy(e,t){let i=new Map,r=new Map;for(let[t,n]of e.entries()){if(i.set(n.id,t),"user"!==n.role)continue;let e=vQ(n)?"":Qb(n)??"",s=r.get(e)??[];s.push({id:n.id,index:t}),r.set(e,s)}let n=new Set,s=[];for(let e of t){let t=e.baselineTailMessageId?i.get(e.baselineTailMessageId):-1;if(void 0===t)continue;let o=r.get(e.normalizedText)?.find(e=>e.index>t&&!n.has(e.id));o&&(n.add(o.id),s.push(e))}return s}var Q_=oa(os()),Qw="Delivery unconfirmed — check chat before retrying",QS=new Set;function Qx(e,t,i,r,n,s){let o=e[t]??[],a=o.filter(e=>vF(e.text)===r.normalizedText&&e.expectedOccurrence>r.baselineOccurrences).length,l=o.filter(e=>""===vF(e.text)&&e.images?.length).length+1;return{...e,[t]:[...o,{id:i,text:n,expectedOccurrence:""===r.normalizedText?l:r.baselineOccurrences+a+1,baselineTailMessageId:r.baselineTailMessageId,baselineResolved:r.baselineResolved,sentAt:r.sentAt,...s?.length?{images:s}:{}}]}}function QT(e,t,i){return i?`${e}\0${t}\0${i}`:null}var Qk=oa(os()),QC=oa(os()),QL=new Map,QM=new Set,QR=new Map;function QI(e){return QM.add(e),()=>{QM.delete(e)}}function QA(e,t,i){let r=QL.get(e),n=r?.text??"",s="function"==typeof t?t(n):t;if(!(s===n&&!i)&&(QL.set(e,{text:s,editGeneration:(r?.editGeneration??0)+1}),s!==n))for(let e of QM)e()}function QP(e,t){QA(e,t,!1)}var QE=[],QD={},QB=oa(os()),QQ={},Qj=oa(os()),QF=new Set;function QO(e){return!QF.has(e)&&(QF.add(e),!0)}function QW(e){QF.delete(e)}var QH=oa(os()),QN=sz({success:sY(!0),catalogOrigin:sY("probe"),models:sH(sz({id:sj().min(1),label:sj(),description:sj().optional()}))}),Qz=rM({name:"omp.configured-models",method:"git.discoverCommitMessageModels",acceptance:"require-result-or-throw",barrier:"on-settle",read:e=>{let t=QN.safeParse(e);return{compatible:!0,variant:"configured-models",value:t.success?t.data.models.map(e=>({...e,options:[]})):null,salvage:{droppedPaths:[],droppedCount:0}}}}),Q$=oa(os()),Qq=new Map,QK=new Map;function QV(e,t){let i=Qq.get(e),r=i&&i.agent===t?i:SP(t);for(r!==i&&QK.delete(e),Qq.delete(e),Qq.set(e,r);Qq.size>32;){let e=Qq.keys().next().value;if(void 0===e)break;Qq.delete(e),QK.delete(e)}return r}var QU=oa(os());function QZ(e,t){return e?.kind==="agent-picker"&&t===e.command||e?.kind==="command"&&t===e.pickerCommand}function QG(e){let{record:t,optionId:i,midSession:r,command:n,canonicalize:s,effectiveModelId:o,persist:a}=e;if(!r||"unsupported"===r.kind)return!1;if(SE(r)&&n===r.command)return SB(t,o,i),!0;if(QZ(r,n))return SQ(t),!0;if("command"!==r.kind)return!1;let l=function(e,t){let i="__orca_session_option_value__",r=e(i),n=r.indexOf(i);if(-1===n)return null;let s=r.slice(0,n),o=r.slice(n+i.length);return t.startsWith(s)&&t.endsWith(o)&&t.slice(s.length,t.length-o.length).trim()||null}(r.build,n);if(!l)return!1;let c=s(l);return!!c&&("model"===i?(o!==c&&delete t.valuesByModel[c],t.model={value:c,source:"dispatched"},a?.(c,i,c)):o&&(t.valuesByModel[o]={...t.valuesByModel[o],[i]:{value:c,source:"dispatched"}},a?.(o,i,c)),!0)}var QY=[],QX=oa(os()),QJ=oa(os()),Q0=[];function Q1(e){return JSON.stringify(e)}function Q5(e,t){e.list=[...t],e.indexById.clear(),e.list.forEach((t,i)=>e.indexById.set(t.id,i))}function Q2(e,t,i,r){for(let n of i){let i=t.get(n.id);if(void 0===i){t.set(n.id,e.length),e.push(n);continue}let s=e[i];r[n.source]>=r[s.source]&&(e[i]=n)}}var Q3=oa(os());function Q6(){let[e,t]=(0,Q3.useState)("idle"),i=(0,Q3.useRef)(null),r=(0,Q3.useRef)(!1);return{phase:e,load:(0,Q3.useCallback)(e=>{if(i.current||r.current)return;let n={};i.current=n,t("loading");let s=()=>i.current===n,o=Date.now()+15e3;(async()=>{let t="drew-nothing";for(let i=0;i<8&&"drew-nothing"===t;i+=1){let i=o-Date.now();if(!s()||i<1e3)return"end";t=await e({timeoutMs:i,isCurrent:s})}return t})().catch(()=>"failed").then(e=>{s()&&(i.current=null,r.current="unavailable"===e,t("failed"===e||"unavailable"===e?e:"idle"))})},[]),supersede:(0,Q3.useCallback)(()=>{i.current=null,r.current=!1,t("idle")},[])}}var Q4=oa(os());function Q7(e){let t=1===e.blocks.length?e.blocks[0]:void 0;return"system"===e.role&&t?.type==="text"&&t.failure?.kind==="providerRetrying"}function Q8(e){if(!e.some(Q7))return e;let t=new Map,i=[];for(let r of e){if("system"===r.role&&r.blocks.some(e=>"text"===e.type&&_L(e.contextClear))&&t.clear(),!Q7(r)){t.size>0&&t.delete(bZ(r)),i.push(r);continue}let e=bZ(r),n=t.get(e);void 0!==n&&(i[n]=null),t.set(e,i.length),i.push(r)}return i.filter(e=>null!==e)}function Q9(e,t){return e.journalPosition&&t.journalPosition?yc(e.journalPosition,t.journalPosition):e.journalPosition||t.journalPosition?e.journalPosition?-1:1:void 0!==e.transcriptOrder&&void 0!==t.transcriptOrder&&e.transcriptOrder!==t.transcriptOrder?e.transcriptOrder-t.transcriptOrder:void 0===e.transcriptOrder!=(void 0===t.transcriptOrder)?void 0===e.transcriptOrder?1:-1:function(e,t){let i=e.timestamp??-1/0,r=t.timestamp??-1/0;if(i!==r)return i-r;let n=g3(e),s=g3(t),o=n!==e.id,a=s!==t.id;return ns?1:Number(a)-Number(o)}(e,t)}var je=new WeakMap,jt=new WeakMap;function ji(e){let t=e.map(({question:e})=>e.trim());return t.length>0&&t.every(Boolean)?JSON.stringify(t.sort()):null}var jr=new WeakMap;function jn(e){let t=jr.get(e);return t||(t=function(e){let t=new Map,i=[],r="";for(let n of e){"message"===n.body.kind&&"user"===n.body.role&&(r=n.itemId);let e=yx(n.body);e&&(r=e.turnId);let s=function(e){let t=je.get(e);if(t)return t;let{body:i}=e,r=LC(e),n=null;if("question"===i.kind)n=ji(i.questions?.length?i.questions:[{question:i.question}]),"pending"===i.resolution.state&&(r={...ya(e),...bG(e),role:"system",blocks:[{type:"text",text:i.question}]});else if("tool-call"===i.kind&&vz(i.name)&&"failed"!==i.state){let e=vZ(i.name,i.input);n=e?ji(e.questions):null}let s={message:r,questionKey:n};return je.set(e,s),s}(n);if(i.push({item:n,projection:s,turn:r}),r&&"question"===n.body.kind&&s.questionKey){let e=t.get(r);e||t.set(r,e=new Map),e.set(s.questionKey,(e.get(s.questionKey)??0)+1)}}let n=[],s=new Map,o=null,a=()=>{o&&(s.set(o.id,function(e){let t=e[0];if(1===e.length)return t;let i=jt.get(t);if(i?.bodies.length===e.length&&e.every((e,t)=>e===i.bodies[t]))return i.body;let r={...t,questions:e.flatMap((e,t)=>e.questions?.length?e.questions:[{id:String(t),question:e.question,options:e.options,multiSelect:!1}])};return jt.set(t,{bodies:e,body:r}),r}(o.bodies)),o=null)};for(let{item:e,projection:r,turn:l}of i){if("tool-call"===e.body.kind&&r.questionKey&&(t.get(l)?.get(r.questionKey)??0)>0){let e=t.get(l),i=e.get(r.questionKey)-1;0===i?e.delete(r.questionKey):e.set(r.questionKey,i);continue}if("question"===e.body.kind&&"pending"===e.body.resolution.state){if(o){o.bodies.push(e.body);continue}o={id:e.itemId,bodies:[e.body]}}else a(),("question"===e.body.kind||"approval"===e.body.kind)&&"pending"!==e.body.resolution.state&&s.set(e.itemId,e.body);r.message&&n.push(r.message)}return a(),{messages:n,receipts:s}}(e),jr.set(e,t)),t}function js(e){return jn(e).messages}function jo(e){let t=yx(e.body);return t&&bU(e)?D({state:t.state,outcome:yT(t)}):"none"}var ja=new WeakMap;function jl(e){return e?.code==="agent_session_journal_unreadable"&&(e.details?.reason==="journalCorrupt"||e.details?.reason==="journalWrittenByNewerOrca")}function jc(e){let t=e.length;for(;t>0;){let i=e.lastIndexOf(` `,t-1)+1,r=e.slice(i,t).trim();if(r)return T(r)||null;if(0===i)break;t=i-1}return null}function jd(e){return{currentRequests:e.currentRequests,requestMarker:e.requestMarker,requestAuthority:e.requestAuthority}}function ju(e,t){if(t.contract!==tM)return e;let i=e.requestMarker??e.requestAuthority;if(i?.publisher===t.publisher&&t.revision<=i.revision)return jd(e);let r=i?.publisher===t.publisher&&i.owner===t.owner&&i.epoch===t.epoch&&i.sessionId===t.sessionId;return{currentRequests:r?e.currentRequests:[],requestAuthority:r?e.requestAuthority:void 0,requestMarker:t}}function jh(e,t,i){if(t.currentRequests)return ju(e,t.currentRequests);if(i)return jd({});let r="batch"===t.type?t.batch.cursor.epoch:t.page.epoch;return e.requestMarker&&(r!==e.epoch||void 0!==t.fence&&t.fence!==e.fence)?{currentRequests:[],requestMarker:void 0,requestAuthority:void 0}:jd(e)}function jf(e){return(e.currentRequests??function(e,t=[],i=0){let r=Math.max(i,_R(e));return r>0?{items:e.filter(e=>e.sequence>r),submissions:t.filter(e=>(e.acceptedSequence??0)>r)}:{items:e,submissions:t}}(e.items).items).filter(e=>("approval"===e.body.kind||"question"===e.body.kind)&&"pending"===e.body.resolution.state)}var jp="structured-grouped-question:";function jm(e){return`${jp}${encodeURIComponent(JSON.stringify(e))}`}function jg(e){if(!e.startsWith(jp))return null;try{let t=JSON.parse(decodeURIComponent(e.slice(jp.length)));if("string"!=typeof t.promptKey||"string"!=typeof t.questionId)return null;if("option"===t.kind&&"string"==typeof t.optionId)return{kind:"option",promptKey:t.promptKey,questionId:t.questionId,optionId:t.optionId};if("free-text"===t.kind)return{kind:"free-text",promptKey:t.promptKey,questionId:t.questionId}}catch{}return null}function jb(e,t){return e&&e.promptKey===t?e.answers:[]}var jv="structured-agent-prompt:";function jy(e){return`${jv}${encodeURIComponent(JSON.stringify(e))}`}function j_(e){if(!e.startsWith(jv))return null;try{let t=JSON.parse(decodeURIComponent(e.slice(jv.length)));if("string"!=typeof t.itemId||"number"!=typeof t.revision||!Number.isFinite(t.revision))return null;if("approval"===t.kind&&"string"==typeof t.optionId)return{kind:t.kind,itemId:t.itemId,revision:t.revision,optionId:t.optionId};if("question-option"===t.kind&&"string"==typeof t.questionId&&"string"==typeof t.optionId)return{kind:t.kind,itemId:t.itemId,revision:t.revision,questionId:t.questionId,optionId:t.optionId};if("question-free-text"===t.kind&&"string"==typeof t.questionId)return{kind:t.kind,itemId:t.itemId,revision:t.revision,questionId:t.questionId}}catch{}return null}function jw(e){return jf(e).find(t=>"approval"===t.body.kind&&"pending"===t.body.resolution.state&&_E(t.itemId,e.actionablePromptIds))??null}function jS(e){return jf(e).find(t=>"question"===t.body.kind&&"pending"===t.body.resolution.state&&_E(t.itemId,e.actionablePromptIds))??null}var jx=oa(os()),jT="send_failed";function jk(e,t){return e===t||!!e&&!!t&&e.length===t.length&&e.every((e,i)=>{var r;return r=t[i],e.id===r.id&&e.kind===r.kind&&e.description===r.description&&e.name===r.name&&e.state===r.state&&e.startedAt===r.startedAt&&e.totalTokens===r.totalTokens&&e.stoppable===r.stoppable})}var jC=0;function jL(e){return e.reduce((e,t)=>bU(t)?e+1:e,0)}function jM(e,t,i){let r=new Map(e.map(e=>[e.clientMessageId,e]));for(let e of t)r.set(e.clientMessageId,e);let n=[...r.values()].sort((e,t)=>e.submittedAt-t.submittedAt),s=new Set(i.filter(e=>"message"===e.body.kind&&"user"===e.body.role).map(e=>e.itemId));return n.filter((e,t)=>t>=n.length-256||s.has(yn(e.clientMessageId)))}var jR=new Map;function jI(e,t,i=[],r=[]){let n={next:null},s=()=>n.next??=new Map(e);if(i.length>0){let t=new Set(i);for(let[i,r]of e)t.has(r.rosterItemId)&&s().delete(i)}for(let i of t){let t=function(e){if(!bU(e)||"message"!==e.body.kind)return null;let t=e.body.blocks.flatMap(b8);return 0===t.length?null:new Set(t.map(e=>e.id))}(i);if(null!==t)for(let[r,o]of n.next??e)o.rosterItemId===i.itemId&&i.revision>o.rosterRevision&&!t.has(r)&&s().delete(r)}let o=t=>{let i=(n.next??e).get(t.entry.id);((i?yc(t.rosterPosition,i.rosterPosition):-1)<0||i?.rosterItemId===t.rosterItemId&&t.rosterRevision>i.rosterRevision)&&s().set(t.entry.id,t)};for(let e of r)o({entry:e.entry,rosterItemId:e.itemId,rosterPosition:yl(e),rosterRevision:e.revision});for(let e of t)if(!(!bU(e)||"message"!==e.body.kind))for(let t of e.body.blocks.flatMap(b8))o({entry:t,rosterItemId:e.itemId,rosterPosition:yl(e),rosterRevision:e.revision});let a=n.next;return null===a?e:a.size>512?new Map([...a].sort(([,e],[,t])=>yc(t.rosterPosition,e.rosterPosition)).slice(0,512)):a}function jA(e,t){return jI(e??jR,t.items,t.removedItemIds,t.subagentRoster)}function jP(e,t){return e===t||!!e&&!!t&&e.state===t.state&&e.supportsTaskStop===t.supportsTaskStop&&e.supportsStopAll===t.supportsStopAll&&e.incomplete===t.incomplete&&jk(e.tasks,t.tasks)&&jk(e.settledTasks,t.settledTasks)&&x(e.children,t.children)}function jE(e,t){if(!e)return e;let{children:i,...r}=e,n=S(i),s={...r,...n?{children:n}:{}};return t&&jP(s,t)?t:s}function jD(e,t,i){let r=void 0!==e?{hostNow:e,receivedAt:t}:i;return r?{hostClock:r}:{}}function jB(e,t,i,r){return{epoch:e.epoch,cursor:e.liveCursor??e.window.nextCursor,fence:t,items:[...e.items].sort(yd),submissions:e.submissions,retainedOwnItemLimit:Math.max(1024,jL(e.items)),retainedItemCap:Math.max(4096,e.items.length),hasOlder:_I(e.items,e.hasOlder),status:"ready",subagentRoster:jA(void 0,e),activity:r??null,...void 0!==e.latestTurn?{latestTurn:e.latestTurn}:{},...void 0!==e.actionablePromptIds?{actionablePromptIds:e.actionablePromptIds}:{},...void 0!==e.working?{working:e.working}:{},...void 0!==i?{backgroundTasks:i}:void 0!==e.backgroundTasks?{backgroundTasks:jE(e.backgroundTasks)}:{}}}function jQ(e,t,i){let r=new Set(i),n=new Map(e.filter(e=>!r.has(e.itemId)).map(e=>[e.itemId,e]));for(let e of t){let t=n.get(e.itemId);(!t||e.revision>=t.revision)&&n.set(e.itemId,e)}return[...n.values()].sort(yd)}function jj(...e){for(let t of e)if(void 0!==t.queuedMessages)return{queuedMessages:t.queuedMessages,queuePause:t.queuePause??null,nextQueuedMessageId:t.nextQueuedMessageId??null};return{}}var jF={epoch:null,cursor:null,fence:null,items:[],submissions:[],retainedOwnItemLimit:1024,retainedItemCap:4096,hasOlder:!1,status:"idle"};function jO(e){let t=e.items[0];return e.epoch&&t?{epoch:e.epoch,sequence:t.sequence}:null}var jW=class extends Error{constructor(e,t,i){super(t),this.code=e,this.data=i}code;data};function jH(e){return Ro("object"==typeof e&&null!==e&&"error"in e?e.error:e)}async function jN(e,t,i,r=15e3,n){let s=await e.sendRequest(t,i,{timeoutMs:r,budgetSpansConnect:!0,...n?.failWhenDisconnected?{failWhenDisconnected:!0}:{}});if(!s.ok)throw new jW(s.error.code,s.error.message,s.error.data);return s.result}function jz(e){if(void 0===e)return 15e3;let t=e-Date.now();return t>=eB?t:null}function j$(e,t){let i="agentSession.send"===e?"send":"agentSession.cancel"===e?"background-tasks"!==t.scope?"stop":"string"==typeof t.taskId?"stop-task":"stop-tasks":e.startsWith("agentSession.respondTo")?"answer":"agentSession.setOption"===e?"option":"agentSession.threadGoal"===e?"goal":"agentSession.conversationCommand"===e&&("clear"===t.command||"compact"===t.command)?t.command:"command";return"send"===i?"composer-send":i}async function jq(e){let{client:t,method:i,fingerprintMethod:r,sessionId:n,expectedRuntimeFence:s,fields:o,clientOperationId:a,timeoutMs:l,agentName:c}=e,d=c?{agentName:c}:{};try{let e=await jN(t,i,{envelope:{sessionId:n,clientOperationId:a??tm(),expectedRuntimeFence:s,payloadFingerprint:tp({method:r,sessionId:n,fields:o})},...o},l);return e.ok||"agentSession.cancel"!==i&&"agentSession.conversationCommand"!==i||"agent_session_operation_unknown"!==e.refusal.code?e.ok?{status:"accepted",value:e.value,cursor:e.cursor}:{status:"refused",code:e.refusal.code,message:function(e,t,i={}){return Rv(Rb(Rn(e),t,i))}(e.refusal,j$(r,o),d)}:{status:"unknown"}}catch(i){var u;let e,t=i instanceof jW?(u=i.code,(e=Ro(i))?Rn(e):"method_not_found"===u||"method_not_supported"===u?{kind:"refused",code:"structured_agent_session_unsupported"}:"invalid_argument"===u||"unauthorized"===u?{kind:"refused",code:"agent_session_operation_invalid"}:{kind:"unconfirmed"}):null;return t&&"unconfirmed"!==t.kind?{status:"failed",message:Rv(Rb(t,j$(r,o),d))}:sw(i)||rk(i)||i instanceof jW?{status:"unknown"}:{status:"failed",message:Rv(Rb({kind:"failed"},j$(r,o)))}}}var jK={messages:null,pause:null},jV=oa(os()),jU=oa(os()),jZ=new WeakMap;function jG(e){let t,i,r,n,s,o,a,l,c,d=jZ.get(e);return d||(t=new Map,i="closed",r=()=>{},n=()=>{let e=r;r=()=>{},e()},s=new Set,o=e=>{if(e!==t)for(let i of(t=e,s))i()},a=()=>o(function(e){let t=null;for(let[i,r]of e){if(!r.hostExecutionOwned&&!r.stopping&&!r.restartResume)continue;t??=new Map(e);let{hostExecutionOwned:n,hostExecutionPhase:s,stopping:o,restartResume:a,...l}=r;t.set(i,l)}return t??e}(t)),l=e=>{if(function(e){if("object"!=typeof e||null===e||!("type"in e))return!1;switch(e.type){case"snapshot":return"sessions"in e&&Array.isArray(e.sessions);case"status":return"session"in e&&"object"==typeof e.session&&null!==e.session;case"end":return!0;default:return!1}}(e)){if("end"===e.type){n(),i="closed",a();return}o(function(e,t){if("snapshot"===t.type){let i=new Map(e);for(let e of t.sessions)i.set(e.sessionId,e);return i}if("status"===t.type){let i=new Map(e);return i.set(t.session.sessionId,t.session),i}return e}(t,e));return}let r=function(e){if("object"!=typeof e||null===e||!("type"in e)||"error"!==e.type)return null;let t="error"in e&&"object"==typeof e.error?e.error:null,i=t&&"code"in t&&"string"==typeof t.code?t.code:void 0,r="message"in e&&"string"==typeof e.message?e.message:void 0;return{...void 0!==i?{code:i}:{},...void 0!==r?{message:r}:{}}}(e);r&&(n(),i=rh(r.code,r.message)?"unavailable":"closed",a())},c=()=>{if("closed"===i&&s.size>0){i="open";let t=e.subscribe("agentSession.subscribeStatus",{},l);"open"===i?r=t:t()}},e.onStateChange(e=>{"connected"===e?c():("unavailable"===i&&(i="closed"),a())}),d={subscribe:e=>(s.add(e),c(),()=>{s.delete(e)}),getSnapshot:()=>t},jZ.set(e,d)),d}var jY=oa(os()),jX=oa(os()),jJ={models:[],modelApply:{}};function j0(e,t){let i=e.efforts.length<=1?null:{id:"effort",label:"Reasoning effort",category:"thought_level",kind:{type:"select",choices:e.efforts,defaultValue:e.defaultEffort??e.efforts[0].value,...e.defaultEffort?{defaultIsCliDefault:!0}:{}},apply:{midSession:{kind:"command",build:e=>`/effort ${String(e)}`}}},r=e.serviceTiers?.length?{id:"serviceTier",label:"Speed",category:"mode",kind:{type:"select",choices:[{value:"default",label:"Standard"},...e.serviceTiers],defaultValue:"default"},apply:{}}:null;return{id:e.id,label:e.label,...e.description?{description:e.description}:{},...e.isDefault?{isDefault:!0}:{},...void 0!==e.supportsAutoMode?{supportsAutoMode:e.supportsAutoMode}:{},options:[...i?[i]:[],...r?[r]:t&&!0===e.supportsFastMode?[{id:"fastMode",label:"Fast mode",category:"mode",kind:{type:"boolean",defaultValue:!1},apply:{}}]:[]]}}var j1=new Set(["fastMode"]);function j5(e,t){return j1.has(e)?"boolean"==typeof t?String(t):null:"string"==typeof t?t:null}function j2(e,t){return j1.has(e)?"true"===t||"false"!==t&&null:t}var j3=["model","effort","fastMode","serviceTier"],j6=[...j3,SM],j4={ask:{label:"Ask for approval",description:"Asks before edits and commands your settings don't allow"},"accept-edits":{label:"Accept edits",description:"Approves file edits and file commands; asks for the rest"},auto:{label:"Approve for me",description:"Reviews approval requests for you"},"full-access":{label:"Full access",description:"Never asks before edits or commands"}},j7={ask:"Asks before edits or commands it isn't already allowed to make"},j8=new Map([["codex",{ask:"Edits files and runs commands in this workspace; asks before anything else","full-access":"Never asks; can edit any file and use the network"}],["claude",{}],["antigravity",{...j7,"accept-edits":"Approves file edits; asks for the rest"}]]),j9="host";function Fe(e="codex",t){return{catalog:t??null,catalogSource:t?"seed":null,record:SP(e),permissionMode:null,pendingId:null}}function Ft(e){return"seed"===e.catalogSource?{...e,catalogSource:"builtin"}:e}function Fi(e,t,i){let r;return void 0===i.current.fastMode&&SB(e.record,i.current.model??null,"fastMode"),void 0===i.current.serviceTier&&SB(e.record,i.current.model??null,"serviceTier"),SF(e.record,{...i.current.model?{model:i.current.model}:{},...i.current.effort?{effort:i.current.effort}:{},...void 0!==i.current.fastMode?{fastMode:i.current.fastMode}:{},...i.current.serviceTier?{serviceTier:i.current.serviceTier}:{}},i.current.confirmed??[]),{...e,catalog:(r=i.models.map(e=>j0(e,i.fastModeSupport?.supported===!0)),i.current.model&&!r.some(e=>e.id===i.current.model)&&r.push({id:i.current.model,label:i.current.model,options:t.unknownModelOptions??[]}),{...t,models:r,defaultModelIsCliDefault:!0}),catalogSource:"live",verifiedModelIds:i.listedModelIds?.length?i.listedModelIds:void 0,permissionMode:i.current.permissionMode??null}}var Fr={id:"model",label:"Model",category:"model",kind:{type:"select",choices:[]},valueSource:"unknown",transport:"agent-session",settable:!1,disabledReason:"available-after-session-start"};function Fn(e){let t=function(e){var t,i,r,n,s;let o,a=SA(e.record.agent),l=a?.modes.find(t=>t===e.permissionMode);if(!a||!l)return null;let c=(s="auto"===l||(t=e.catalog,i=e.record,o=i.model?.value,null!==t&&(r=t.models,n="string"==typeof o?o:void 0,r.find(e=>null==n||"default"===n?!0===e.isDefault:e.id===n)?.supportsAutoMode===!0)),a.autoNeedsModelSupport&&!s?a.modes.filter(e=>"auto"!==e):a.modes);return{id:SM,label:"Permissions",category:"mode",kind:{type:"select",currentValue:l,choices:c.map(t=>{var i;return{value:t,label:j4[t].label,description:(i=e.record.agent,j8.get(i)??j7)[t]??j4[t].description}})},valueSource:"applied",transport:"agent-session",settable:!0}}(e),i=function(e){if(!e.catalog)return[];if("seed"===e.catalogSource)return[Fr];let t=SK({catalog:e.catalog,models:Sz(e.catalog,e.catalog.models,e.record),record:e.record,mode:"live",modelLabel:"Model",liveTransport:"agent-session"});return t.length>0||"live"===e.catalogSource?function(e,t,i,r){let n=Sq(e,e.models,t),s=SD(t,n,"effort");if(!n||!i||i.includes(n)||"string"!=typeof s?.value||r.some(e=>"effort"===e.id))return r;let o=e.models.flatMap(e=>e.options).filter(e=>"effort"===e.id),a=o.flatMap(e=>"select"===e.kind.type?e.kind.choices:[]).find(e=>e.value===s.value);return[...r,{id:"effort",label:o[0]?.label??"Reasoning effort",category:"thought_level",kind:{type:"select",currentValue:s.value,choices:[a??{value:s.value,label:s.value}]},valueSource:s.source,transport:"agent-session",settable:!1}]}(e.catalog,e.record,e.verifiedModelIds,t):[Fr]}(e);return t?[...i,t]:i}function Fs(e,t,i){if(t===SM)return{...e,permissionMode:i,pendingId:null};if(!e.catalog)return e;let r=Sq(e.catalog,e.catalog.models,e.record),n=j2(t,i);if(null===n)return{...e,pendingId:null};let s="model"===t?SD(e.record,r,"effort"):void 0;return Sj(e.record,t,n,"dispatched",r),s&&Sj(e.record,"effort",s.value,"dispatched"),{...e,pendingId:null}}function Fo(e,t){let i=e;for(let e of j6){let r=t[e];void 0!==r&&(i=Fs(i,e,r))}return i}function Fa(e,t){let i=t.model;return void 0===i||!!e.catalog?.models.some(e=>e.id===i)}function Fl(e,t,i){let{[SM]:r,...n}=i,s=function(e,t,i){var r;let n=void 0!==t&&void 0===e.record.model,s=Object.keys(i).length>0;if(n&&"host"===e.catalogSource&&!s&&!Fa(e,t))return{...e,catalogSource:"seed"};let o=n&&("host"===e.catalogSource||"live"===e.catalogSource)&&Fa(e,t);if(!e.catalog||!o&&!s)return e;let a={...e,record:{agent:(r=e.record).agent,...r.model?{model:{...r.model}}:{},valuesByModel:Object.fromEntries(Object.entries(r.valuesByModel).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([e,t])=>[e,{...t}]))]))}};return o&&(a=Fo(a,t)),{...Fo(a,i),pendingId:e.pendingId}}(e,t,n),o=r??e.permissionMode??t?.[SM]??null;return s.permissionMode===o?s:{...s,permissionMode:o}}function Fc(e){return Fn(Fl(e,void 0,{}))}var Fd=oa(os()),Fu=oa(os()),Fh=[],Ff=oa(os()),Fp=oa(os());function Fm(e,t){let i=yx(e.body);if(!i)return null;let{state:r,startedAt:n,requestedAt:s,completedAt:o,durationMs:a}=i;if(void 0===n||!Number.isFinite(n)||n<=0)return null;let l=void 0!==s&&Number.isFinite(s)&&s>0?s:void 0,c=void 0!==o&&Number.isFinite(o)&&o>=n?o:void 0,d=void 0!==a&&Number.isFinite(a)&&a>=0?a:void 0,u=D({state:r,outcome:yT(i)}),h=void 0===t?void 0:Math.min(t,n);return{state:r,startedAt:n,...void 0!==l?{requestedAt:l}:{},...void 0!==c?{completedAt:c}:{},...void 0!==d?{durationMs:d}:{},...void 0!==l&&void 0!==h&&h>l?{queuedUntil:h}:{},observedAt:e.observedAt,...u?{verdict:u}:{}}}function Fg(e){return e.queuedUntil??e.requestedAt??e.startedAt}async function Fb(e){let{client:t,enabled:i,inFlight:r,onSendError:n,sessionId:s,stateRef:o}=e,a=o.current,l=_A(a),c=e.prompt&&!0===e.promptCancelSupported?e.prompt:void 0,d=!0===e.hostStopsConversation&&!e.prompt;if(!t||!s||!i||null===a.fence||!l&&!d)return n("Stop not sent"),!1;let u=d?{}:{turnId:l,...c?{prompt:c}:{}},h=a.fence,f=()=>Fv({client:t,sessionId:s,fence:h,fields:u,onSendError:n});if(!0===e.hostAnswersRepeatedStops)return f();let p=`${s}:agentSession.cancel:${JSON.stringify(u)}`,m=r.get(p);if(m)return m;let g=f();return r.set(p,g),g.finally(()=>{r.get(p)===g&&r.delete(p)}),g}async function Fv(e){let t=await jq({client:e.client,method:"agentSession.cancel",fingerprintMethod:"agentSession.cancel",sessionId:e.sessionId,expectedRuntimeFence:e.fence,fields:e.fields});return"accepted"===t.status||("unknown"===t.status?e.onSendError("Stop unconfirmed — check chat before retrying"):("refused"===t.status||"failed"===t.status)&&e.onSendError(t.message),!1)}var Fy=oa(os()),F_=oa(os());function Fw(e,t){return tp({method:"agentSession.send",sessionId:e,fields:{body:"message"===t.kind?function(e){let{from:t,...i}=e;return i}(t):t}})}function FS(e,t){return{kind:"message",role:"user",blocks:[...e.trim().length>0?[{type:"text",text:e.trimEnd()}]:[],...t.map(e=>({type:"image-ref",path:e.path}))]}}var Fx={turnActive:"working",messagesUnsettled:"working",promptPending:"prompt",backgroundTasksRunning:"background"};async function FT(e){if(e.pending.current)return"rejected";if(!xo(e.text,e.controller.agent))return null;if(e.hasAttachments)return e.onError("Remove attachments before using a chat-session command."),"rejected";let t=!1,i=await xa(e.text,{...e.controller,runConversationCommand:async i=>{var r,n;let s=e.busy(),o=e.waitsInLine(i),a=o?null:s;if(a){let e;return{accepted:!1,error:(e="clear"===i,Rv("prompt"===a?[e?"clearAfterAnswer":"compactAfterAnswer"]:["agentStillWorking",e?"runClearWhenDone":"runCompactWhenDone"])),refusedWhile:a}}e.pending.current=!0;try{let a,l=await jq({client:e.client,sessionId:e.sessionId,expectedRuntimeFence:e.fence,method:"agentSession.conversationCommand",fingerprintMethod:"agentSession.conversationCommand",fields:o?{command:i,delivery:"queue-if-active"}:{command:i},timeoutMs:Math.max(e.timeoutMs,195e3)});if("unknown"===l.status||"accepted"===l.status&&"unknown"===l.value.state)return t=!0,{accepted:!1,error:"Conversation operation was not confirmed."};if("accepted"!==l.status)return{accepted:!1,error:l.message};let c=(r=l.value,(a="clear"===(n=r.command)||"compact"===n?_b(r.failure)?.refusal?.details:void 0)&&"reason"in a&&"string"==typeof a.reason?Fx[a.reason]:void 0);return{accepted:!l.value.error,error:l.value.error??null,...l.value.error&&void 0!==c&&c===s?{refusedWhile:c}:{}}}finally{e.pending.current=!1}}});return i.error&&e.onError(i.error,i.refusedWhile?{refusedWhile:i.refusedWhile}:void 0),t?"unknown":i.accepted?"accepted":"rejected"}async function Fk(e){let t=jz(e.deadline);if(null===t)return e.onError("Message not sent"),"rejected";let i=await jq({client:e.client,method:"agentSession.send",fingerprintMethod:"agentSession.send",sessionId:e.sessionId,expectedRuntimeFence:e.expectedRuntimeFence,fields:{body:FS(e.text,e.attachments),...e.delivery?{delivery:e.delivery}:{},...e.options?{options:e.options}:{}},clientOperationId:e.clientMessageId,timeoutMs:t}),r=function(e){if("unknown"===e.status)return{outcome:"unknown",error:null};if("refused"===e.status)return"unknown"===function(e){switch(e){case"agent_session_owner_restart_failed":case"agent_session_operation_conflict":case"agent_session_operation_expired":case"agent_session_operation_invalid":case"agent_session_item_revision_stale":case"agent_session_already_resolved":return"settled-rejected";case"agent_session_operation_unknown":return"unknown";case"structured_agent_session_unsupported":case"agent_session_checkpoint_stale":case"agent_session_conflict":case"agent_session_ownership_unknown":case"agent_session_operation_capacity":case"agent_session_identity_required":case"agent_session_journal_unreadable":case"execution_owner_reconciling":return"pending-admission"}}(e.code)?{outcome:"unknown",error:null}:{outcome:"rejected",error:e.message};if("accepted"!==e.status)return{outcome:"rejected",error:e.message};if("queued"in e.value&&e.value.queued)return"withdrawn"===e.value.queued.state?{outcome:"rejected",error:"Message not sent"}:{outcome:"queued",error:null};let t="submission"in e.value?e.value.submission:void 0;return t&&"unknown"!==t.dispatchState?t.queuedMessageId===e.value.clientMessageId?{outcome:"unknown",error:null}:"rejected"===t.dispatchState&&void 0!==t.keptAsQueuedMessageId?{outcome:"queued",error:null}:{outcome:"accepted",error:null}:{outcome:"unknown",error:null}}(i);return null!==r.error&&e.onError(r.error),"accepted"===r.outcome&&"accepted"===i.status&&e.onAccepted?.(i.cursor),r.outcome}var FC=class extends Error{constructor(e){super(`${e??"That file"} is over ${Math.floor(sE/1048576)} MB`),this.name="MobileFileTooLargeError"}},FL=class extends Error{constructor(){super("Photo library permission denied"),this.name="ImageLibraryPermissionError"}};function FM(e,t){return e instanceof FC?e.message:t?`Couldn't upload ${t}`:"Couldn't attach that file"}async function FR(e){try{for await(let t of e.picked){let i=e.nextId();e.onPicked({id:i,name:t.name,mime:t.mime,byteLength:t.byteLength,path:null});try{e.onStored(i,await e.upload(t))}catch(r){e.onFailed(i),e.onError(FM(r,t.name))}}}catch(t){e.onError(FM(t))}}var FI=oa(os()),FA=oa(os()),FP=sV("type",[sz({type:sY("text"),text:sj()}).strict(),sz({type:sY("image-ref"),path:sj().min(1).max(4096).optional(),url:sj().min(1).max(4096).optional(),alt:sj().max(512).optional()}).strict().refine(e=>!!e.path!=!!e.url,"Provide exactly one of path/url")]),FE=sz({kind:sY("message"),role:sY("user"),blocks:sH(FP).min(1).max(64)}).strict().refine(e=>262144>=Buffer.byteLength(JSON.stringify(e.blocks),"utf8"),"Message is too large"),FD=512,FB=sj().max(FD).refine(Lm,"Invalid agent session id"),FQ=(e,t=FD)=>sj().min(1,e).max(t,e).refine(e=>e===e.trim(),e),Fj=sz({epoch:FQ("Invalid journal epoch"),sequence:sF().int().nonnegative()}).strict(),FF=sz({sessionId:FB,clientOperationId:FQ("Invalid client operation id"),expectedRuntimeFence:sF().int().positive().nullable(),payloadFingerprint:sj().regex(/^[0-9a-f]{64}$/,"Payload fingerprint must be a sha256 hex digest")}).strict(),FO=sV("kind",[sz({kind:sY("codex"),threadId:FQ("Invalid thread id")}).strict(),sz({kind:sY("claude"),sessionId:FQ("Invalid provider session id"),leafUuid:FQ("Invalid leaf uuid").nullable()}).strict()]),FW=sj().refine(e6,"Invalid agent"),FH=sz({executionHostId:sj().max(FD).transform(e=>rv(e)).refine(e=>null!==e,{message:"Invalid execution host id"}),wslDistro:FQ("Invalid WSL distro").nullable(),workspaceId:FQ("Invalid workspace id"),workspaceKind:sZ(["git-worktree","folder"])}).strict(),FN=sz({variable:sZ(["CLAUDE_CONFIG_DIR","CODEX_HOME"]),path:sj().min(1).max(4096)}).strict(),Fz=sz({envelope:FF,location:FH,provider:sZ(["codex","claude"]),agent:FQ("Invalid agent"),accountHome:FN,runtimeKind:sY("native"),providerHandle:FO}).strict(),F$=sz({providerSessionId:FQ("Invalid provider session id"),cliSource:sz({workspaceId:FQ("Invalid workspace id"),paneKey:FQ("Invalid pane key")}).strict().optional()}).strict(),Fq=(sz({worktree:FQ("Invalid worktree selector"),agent:FW}).strict(),sU(sj(),sj()).refine(function(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;let t=Object.entries(e);return t.length<=32&&t.every(([e,t])=>Lp(e,512)&&Lp(t,512))})),FK=sz({envelope:FF,retryUnknown:sY(!0).optional(),delivery:sY("queue-if-active").optional(),options:Fq.optional(),usageLimitContinuationOfTurnItemId:FQ("Invalid source turn item id").optional(),body:FE}).strict(),FV=(sK([Fz,sz({envelope:FF,worktree:FQ("Invalid worktree selector"),agent:FW,resumeFrom:F$.optional(),tabId:sj().refine(function(e){var t;return"string"==typeof e&&e.length<=512&&(t=e).length>0&&!t.includes(":")&&!t.startsWith("web-terminal-")},"Invalid chat tab ID").optional(),firstMessage:sz({clientMessageId:FQ("Invalid client message id"),body:FK.shape.body}).strict().optional(),options:Fq.optional()}).strict()]),sz({envelope:FF,turnId:FQ("Invalid turn id").optional(),scope:sY("background-tasks").optional(),taskId:FQ("Invalid task id").optional(),prompt:sz({itemId:FQ("Invalid item id"),expectedRevision:sF().int().positive()}).strict().optional()}).strict().superRefine((e,t)=>{void 0!==e.taskId&&"background-tasks"!==e.scope&&t.addIssue({code:"custom",message:"A task id requires background-task scope"}),void 0!==e.prompt&&"background-tasks"===e.scope&&t.addIssue({code:"custom",message:"A prompt cannot use background-task scope"}),void 0===e.turnId&&(void 0!==e.prompt||void 0!==e.scope)&&t.addIssue({code:"custom",message:"A prompt or background-task cancel names its turn"})}),sz({envelope:FF,messageId:FQ("Invalid queued message id")}).strict(),sz({envelope:FF}).strict(),sz({envelope:FF,itemId:FQ("Invalid item id"),expectedRevision:sF().int().positive(),optionId:FQ("Invalid option id",1024)}).strict(),sz({questionId:sj().min(1,"Invalid question id").max(1024,"Invalid question id"),optionIds:sH(FQ("Invalid option id",1024)).max(64),other:sj().max(65536).refine(e=>65536>=Buffer.byteLength(e,"utf8"),"Answer is too large").optional()}).strict()),FU=(sz({envelope:FF,itemId:FQ("Invalid item id"),expectedRevision:sF().int().positive(),optionId:FQ("Invalid option id",1024).optional(),answers:sH(FV).min(1).max(4).optional()}).strict().superRefine((e,t)=>{void 0===e.optionId==(void 0===e.answers)&&t.addIssue({code:"custom",message:"Send exactly one of an option id or answers"}),void 0!==e.answers&&Buffer.byteLength(JSON.stringify(e.answers),"utf8")>262144&&t.addIssue({code:"custom",message:"Answer is too large"})}),sz({envelope:FF,key:FQ("Invalid option key"),value:sj().max(512)}).strict(),sz({sessionId:FB}).strict());function FZ(e){return e.command||e.blocks.some(e=>"text"!==e.type&&"image-ref"!==e.type)?null:e.blocks.flatMap(e=>"text"===e.type?[e.text]:[]).join(` -`)}function FG(e,t){if(null===FZ(e)||new TextEncoder().encode(t).length>262144||!t.trim()&&!e.blocks.some(e=>"image-ref"===e.type))return null;if(t===FZ(e))return e;let i=[],r=!1;for(let n of e.blocks)"text"!==n.type?i.push(n):r||(i.push({type:"text",text:t}),r=!0);return r||i.unshift({type:"text",text:t}),{...e,blocks:i}}function FY(e,t){return e.current===t}sz({workspaceId:sj().min(1)}).strict(),FU.extend({observedCursor:Fj}),sz({}).strict(),s$({}),s$({agent:FW,sessionId:FB.optional(),worktree:FQ("Invalid worktree selector").optional(),waitForListing:sO().optional(),savedOnly:sO().optional()}),sz({envelope:FF,command:sZ(["clear","compact"]),delivery:sY("queue-if-active").optional()}).strict(),sz({envelope:FF,change:sV("kind",[sz({kind:sY("set"),objective:sj().max(4e3).refine(e=>e.trim().length>0,"Objective is empty")}).strict(),sz({kind:sY("status"),status:sZ(["active","paused"])}).strict(),sz({kind:sY("clear")}).strict()])}).strict(),sz({sessionId:FB,holderId:FQ("Invalid holder id")}).strict(),sz({sessionIds:sH(FB).max(512).optional()}).strict(),sz({sessionIds:sH(FB).max(512).optional()}).strict(),sz({sessionId:FB,direction:sZ(["tail","before","after"]),cursor:Fj.optional(),limit:sF().int().positive().max(200).optional()}).strict(),sz({sessionId:FB,cursor:Fj.optional()}).strict(),sz({includePrompts:sO().optional()}),sz({sessionId:FB,subscriptionId:FQ("Invalid subscription id").optional()}).strict(),sz({sessionId:FB}).strict(),sz({envelope:FF,itemId:FQ("Invalid item id",4096),expectedEpoch:FQ("Invalid journal epoch")}).strict();var FX=oa(os()),FJ=oa(os()),F0=[],F1={},F5=oa(os()),F2=oa(os());function F3(e,t){let i;if(!e)return null;try{i=JSON.parse(e)}catch{return null}if(!i||"object"!=typeof i)return null;let r=i.approval;if(!r||"object"!=typeof r)return null;let n=r.tool;if("string"!=typeof n||0===n.length)return null;let s=r.summary;return{title:`Allow ${n}?`,detail:"string"==typeof s&&s.length>0?s:void 0,options:[{label:"Allow",send:"opencode"===Am(t)?"\r":"1"},{label:"Deny",send:"\x1b"}]}}var F6=new Set(["blocked","waiting"]),F4=[/\bpermission\b/i,/\bapprove\b/i,/\bapproval\b/i,/\ballow\b/i,/\bdeny\b/i,/\bgrant\b/i,/\bauthorize\b/i,/\bdo you want to\b/i,/\bwould you like to\b/i,/\bproceed\?/i,/\bconfirm\b/i,/\(y\/n\)/i,/\by\/n\b/i,/\byes\/no\b/i,/\bplease confirm\b/i],F7=/(?:^|\n)\s*(\d+)[.)]\s*([^\n]+)/g;function F8(e,t=40){let i=e.replace(/\s+/g," ").trim();return i.length>t?`${i.slice(0,t-1)}…`:i}var F9=oa(os());function Oe(e,t){return(0,F9.useCallback)(async(...i)=>{let r=await e(...i);return r&&t(),r},[e,t])}var Ot=oa(os()),Oi=oa(os()),Or=oa(os()),On=oa(os()),Os=oa(os()),Oo=oa(os()),Oa=oa(os()),Ol=oa(oi()),Oc=new Map;function Od(e,t){return`orca:nativeChatTabs:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}async function Ou(){await null;try{let e=await sh.getItem("orca:defaultSessionView");return{value:"chat"===e||"terminal"===e?e:null,loaded:!0,hasStoredValue:null!==e}}catch{return{value:null,loaded:!1,hasStoredValue:!1}}}async function Oh(){return(await Ou()).value??"terminal"}async function Of(e){let t,i;try{t=await sh.getItem(e)}catch{return{overrides:new Map,loaded:!1}}if(!t)return{overrides:new Map,loaded:!0};try{i=JSON.parse(t)}catch{return{overrides:new Map,loaded:!0}}return Array.isArray(i)?{overrides:new Map(i.filter(e=>"string"==typeof e).map(e=>[e,"chat"])),loaded:!0}:i&&"object"==typeof i?{overrides:new Map(Object.entries(i).filter(e=>"terminal"===e[1]||"chat"===e[1])),loaded:!0}:{overrides:new Map,loaded:!0}}async function Op(e,t){let i=Od(e,t);return await Oc.get(i),Of(i)}async function Om(e,t,i,r){let n=Od(e,t),s=(Oc.get(n)??Promise.resolve()).then(async()=>{let e=await Of(n);if(!e.loaded)throw Error("Session view overrides could not be read");e.overrides.set(i,r);let t=JSON.stringify(Object.fromEntries(e.overrides));await tJ(n,t)}),o=s.catch(()=>{});Oc.set(n,o);try{await s}finally{Oc.get(n)===o&&Oc.delete(n)}}function Og(e,t,i){return e.hostId===t&&e.worktreeId===i}function Ob(e,t){let i=new Map(e);for(let[e,r]of t)i.set(e,r);return i}var Ov=oa(os()),Oy=oa(os()),O_=oa(os()),Ow=oa(os()),OS=oa(oi()),Ox=oa(os()),OT=oa(os());function Ok(e){return Array.isArray(e)&&e.every(e=>null!=e&&"object"==typeof e&&Number.isInteger(e.row)&&Number.isInteger(e.startCol)&&Number.isInteger(e.endCol)&&"string"==typeof e.uri)}var OC=sB-function(e="a".repeat(function(){let e=/\{(\d+)\}\$$/.exec(su.source);if(null===e)throw Error("the bridge id pattern is no longer a fixed length");return Number(e[1])}())){return JSON.stringify({v:sd,type:"event",id:e,seq:Number.MAX_SAFE_INTEGER,payload:0}).length}(),OL=oa(os()),OM=oa(os()),OR=oa(os());function OI(e,t){if(e===t)return!0;if(!e||!t||e.mode!==t.mode)return!1;let i=e.theme,r=t.theme;for(let e in i)if(Object.hasOwn(i,e)&&(!Object.hasOwn(r,e)||i[e]!==r[e]))return!1;for(let e in r)if(Object.hasOwn(r,e)&&!Object.hasOwn(i,e))return!1;return!0}function OA(e){return e.flatMap(e=>"terminal"!==e.type||"string"!=typeof e.terminal?[]:[{handle:e.terminal,title:e.title||"Terminal",terminalTheme:e.terminalTheme,isActive:!0===e.isActive,connected:!0}])}function OP(e,t){return e.length===t.length&&e.every((e,i)=>e.handle===t[i]?.handle&&e.title===t[i]?.title&&OI(e.terminalTheme,t[i]?.terminalTheme)&&e.isActive===t[i]?.isActive)}function OE(e){return!e.liveHandles.has(e.handle)&&!(e.showNativeChat&&e.handle===e.activeHandle)}var OD=class{activation=null;inFlight=null;activate(){let e=Symbol("terminal-inventory-activation");return this.activation=e,()=>{this.activation===e&&(this.activation=null)}}run(e,t,i){if(this.inFlight)return this.inFlight.allowEmptyLoaded||=e,i?.(this.inFlight.startedAt),this.inFlight.promise;let r=this.activation,n={allowEmptyLoaded:e,promise:Promise.resolve(!1),startedAt:Date.now()};i?.(n.startedAt);let s=Promise.resolve().then(()=>t(()=>n.allowEmptyLoaded,()=>null!==r&&this.activation===r));return n.promise=s.finally(()=>{this.inFlight===n&&(this.inFlight=null)}),this.inFlight=n,n.promise}};function OB(e,t,i=5){return{kind:"launched",lock:e,surface:{pane:null,sessionId:null,handle:null,...t},snapshotsLeft:i}}function OQ(e,t,i){return e?.kind!=="launched"||e.lock!==t?e:{...e,surface:{...e.surface,...i},snapshotsLeft:5}}function Oj(e,t){return e?.kind==="launched"&&e.lock===t&&null===e.snapshotsLeft?null:e}function OF(e){return e?.kind==="tab"||e?.kind==="terminal"?e.tabId:null}function OO(e){return e?.kind==="terminal"?e.handle:null}function OW(e){return e?.kind!=="terminal"?e:e.tabId?{kind:"tab",tabId:e.tabId}:null}function OH(e,t){return"agent-session"===e.type?null!==t.sessionId&&e.sessionId===t.sessionId:"terminal"===e.type&&(null!==t.pane&&e.parentTabId===t.pane.tabId&&e.leafId===t.pane.leafId||null!==t.handle&&e.terminal===t.handle)}var ON=oa(os());function Oz(e){return!e?.startsWith("mobile-local:")}function O$(e,t){e.creatingTerminalRef.current===t&&(e.creatingTerminalRef.current=null,e.setCreating(!1))}var Oq=oa(os()),OK=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]),OV=[137,80,78,71,13,10,26,10];function OU(e,t,i){return t>=0&&i>=0&&t+i<=e.byteLength}function OZ(e,t,i){if(!OU(e,t,i.length))return!1;for(let r=0;r>>0}function O0(e,t){return(e[t]<<24>>>0|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function O1(e,t){return Number.isSafeInteger(e)&&Number.isSafeInteger(t)&&e>0&&t>0?{width:e,height:t}:null}function O5(e){return OU(e,0,OV.length)&&OV.every((t,i)=>e[0+i]===t)&&OU(e,8,16)&&13===O0(e,8)&&OZ(e,12,"IHDR")?O1(O0(e,16),O0(e,20)):null}function O2(e,t){if(!OU(e,t,12))return null;let i=OJ(e,t);return 12===i?O1(OG(e,t+4),OG(e,t+6)):i<40||!OU(e,t,12)?null:O1(Math.abs(0|OJ(e,t+4)),Math.abs(0|OJ(e,t+8)))}var O3=new Set(["image/apng","image/bmp","image/gif","image/ico","image/jpeg","image/jpg","image/pjpeg","image/png","image/vnd.microsoft.icon","image/webp","image/x-bmp","image/x-icon","image/x-ms-bmp"]);function O6(e,t,i,r){let n=i[0],s=i[1],o=r>2?i[2]:-2,a=r>3?i[3]:-2;return r<2||void 0===n||void 0===s||n<0||s<0?null:-2===o?-2!==a?null:(t>4),{bytesWritten:Math.min(1,e.length-t),padded:!0}):void 0===o||o<0?null:(t>4),t+1>2),-2===a?{bytesWritten:Math.min(2,e.length-t),padded:!0}:void 0===a||a<0?null:(t+2=65&&i<=90?i-65:i>=97&&i<=122?i-71:i>=48&&i<=57?i+4:43===i?62:47===i?63:61===i?-2:-1;if(-1===l)return null;if(n[s]=l,4!==(s+=1))continue;let c=O6(r,o,n,4);if(!c)return null;o+=c.bytesWritten,a=c.padded,s=0}if(!a&&o0){for(let e=0;e=8388608,n=O5(t)??(OU(t,0,10)&&(OZ(t,0,"GIF87a")||OZ(t,0,"GIF89a"))?O1(OG(t,6),OG(t,8)):null)??function(e){if(!OU(e,0,4)||255!==e[0]||216!==e[1])return null;let t=2,i=e.byteLength;for(;t=208&&r<=216)continue;if(!OU(e,t,2))break;let n=OY(e,t);if(n<2||t+n>i)break;if(OK.has(r))return n>=7?O1(OY(e,t+5),OY(e,t+3)):null;t+=n}return null}(t)??function(e){if(!OU(e,0,20)||!OZ(e,0,"RIFF")||!OZ(e,8,"WEBP"))return null;let t=12;for(;OU(e,t,8);){let i=OJ(e,t+4),r=t+8,n=r+i;if(OZ(e,t,"VP8X")&&i>=10&&OU(e,r,10))return O1(OX(e,r+4)+1,OX(e,r+7)+1);if(OZ(e,t,"VP8L")&&i>=5&&OU(e,r,5)&&47===e[r]){let t=e[r+1],i=e[r+2],n=e[r+3];return O1(1+((63&i)<<8|t),1+((15&e[r+4])<<10|n<<2|(192&i)>>6))}if(OZ(e,t,"VP8 ")&&i>=10&&OU(e,r,10)&&157===e[r+3]&&1===e[r+4]&&42===e[r+5])return O1(16383&OG(e,r+6),16383&OG(e,r+8));if(n>e.byteLength)break;t=n+i%2}return null}(t)??(OZ(t,0,"BM")?O2(t,14):null)??function(e){if(!OU(e,0,6)||0!==OG(e,0)||1!==OG(e,2))return null;let t=OG(e,4);if(t<=0||t>1024||!OU(e,6,16*t))return null;let i=0,r=0;for(let n=0;n0&&n.height>0&&n.width<=32768&&n.height<=32768&&n.width<=Math.floor(0x2000000/n.height);if(e||i)return!e;r=8388608;continue}if(i)return!1;r=Math.min(16*r,8388608)}}(i,e)?null:`data:${e};base64,${i}`}var O7=sq({content:sj(),truncated:sO(),byteLength:sF()}),O8=sq({content:sj(),isImage:sW().optional(),mimeType:sj().optional()}),O9=sq({kind:sY("text"),originalContent:sj(),modifiedContent:sj()}),We=sq({kind:sj().refine(e=>"text"!==e,"not the text arm").transform(()=>"binary"),originalContent:sC("originalContent",sj()),modifiedContent:sC("modifiedContent",sj()),isImage:sC("isImage",sO()),modifiedDeleted:sC("modifiedDeleted",sO()),mimeType:sj().optional()}),Wt=rI(rM({name:"git.file-tab-diff",method:"git.diff",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rP([rA("file-tab-text-diff",O9),rA("file-tab-binary-diff",We)])})),Wi=rI(rM({name:"files.file-tab-text",method:"files.read",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rA("file-tab-text",O7)})),Wr=rI(rM({name:"files.file-tab-image",method:"files.readPreview",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rA("file-tab-image",O8)}));async function Wn(e,t){let i=`id:${t.worktreeId}`,{relativePath:r}=t;if("staged"===t.diffSource||"unstaged"===t.diffSource){let n=await Wt.request(e,{worktree:i,filePath:r,staged:"staged"===t.diffSource}),s=Wt.interpret(n);if("text"!==s.kind){let e=function(e){if(!0!==e.isImage)return null;let t=e.modifiedContent||"";return t?O4(e.mimeType,t):!0===e.modifiedDeleted?O4(e.mimeType,e.originalContent||""):null}(s);if(!e)throw Error("binary_file");return{status:"ready",kind:"image",dataUri:e}}let o=ti(s.originalContent,s.modifiedContent);return{status:"ready",kind:"diff",lines:o.lines,truncated:o.truncated}}let n=rc(t.worktreeId,r);if(n)return{status:"ready",kind:"media",media:n};let s=rl(r);if("image"===s){let t=await Wr.request(e,{worktree:i,relativePath:r}),n=Wr.interpret(t),s=n.isImage?O4(n.mimeType,n.content):null;if(!s)throw Error("binary_file");return{status:"ready",kind:"image",dataUri:s}}let o=await Wi.request(e,{worktree:i,relativePath:r}),a=Wi.interpret(o);return"html"===s?{status:"ready",kind:"html",content:a.content}:{status:"ready",kind:"file",content:a.content,truncated:a.truncated,byteLength:a.byteLength}}function Ws(e,t){let i=(e.get(t)??0)+1;return e.set(t,i),i}function Wo(e){return e?.status==="ready"&&!e.isDirty}function Wa(e){return e?.status==="ready"}function Wl(e,t,i,r){if(r(e.get(t)))return e;let n=new Map(e);return n.set(t,i),n}function Wc(e,t,i,r,n){let s=e.get(t);if(!s)return e;let o=n(s,i,r);if(!o||o===s)return e;let a=new Map(e);return a.set(t,o),a}function Wd(e,t,i){return"ready"===e.status?"ready"!==i.status||function(e,t){var i,r,n,s;if("ready"!==t.status||e.kind!==t.kind)return!1;switch(e.kind){case"file":return"file"===t.kind&&e.content===t.content&&e.truncated===t.truncated&&e.byteLength===t.byteLength;case"html":return"html"===t.kind&&e.content===t.content;case"image":return"image"===t.kind&&e.dataUri===t.dataUri;case"media":return"media"===t.kind&&(i=e.media,r=t.media,i.worktreeId===r.worktreeId&&i.relativePath===r.relativePath&&i.mimeType===r.mimeType);case"diff":return"diff"===t.kind&&e.truncated===t.truncated&&(n=e.lines,s=t.lines,n.length===s.length&&n.every((e,t)=>{let i=s[t];return e.kind===i?.kind&&e.text===i?.text&&e.oldLineNumber===i?.oldLineNumber&&e.newLineNumber===i?.newLineNumber}))}}(e,i)?void 0:i:e===t?i:void 0}function Wu(e,t){let i=e instanceof Error?e.message:"";return"binary_file"===i?"Binary preview unavailable":"file_too_large"===i?"File too large for mobile preview":t}var Wh=oa(os()),Wf=oa(os()),Wp=oa(oe()),Wm=oa(os()),Wg=oa(os()),Wb=oa(os()),Wv=oa(oe()),Wy=oa(oi()),W_=class{constructor(e){this.options=e,this.generation=this.readGeneration(),this.applicationRevision=this.readApplicationRevision()}options;inFlight=new Map;generation;barrier=0;subscriptionEpoch=0;requirementRevision=0;satisfiedRevision=0;applicationRevision=0;health="probing";snapshotSeen=!1;reconciliationActive=!1;disposed=!1;requestReconciliation(){return this.syncGeneration(),this.requirementRevision+=1,this.startCurrentRequest()}ensureReconciliation(){return this.syncGeneration(),this.requirementRevision<=this.satisfiedRevision&&(this.requirementRevision+=1),this.startCurrentRequest()}requestPendingRecovery(){return this.options.hasRecoveryNeed()?this.requestReconciliation():Promise.resolve()}retryReconciliation(){this.syncGeneration();let e=this.inFlight.get(`${this.generation}:${this.barrier}`);return e?.retry?e.promise:(this.requirementRevision+=1,this.barrier+=+!!e,this.startCurrentRequest(!0))}poll(){if(this.syncGeneration(),!this.reconciliationActive)return null;let e=this.options.hasRecoveryNeed();if("live"===this.health){if(!e&&this.requirementRevision<=this.satisfiedRevision)return null;let t=this.inFlight.get(`${this.generation}:${this.barrier}`);if(t)return t.promise;if(e&&this.options.allowRecoveryPoll?.()===!1)return null}return this.ensureReconciliation()}setReconciliationActive(e){this.reconciliationActive=e}beginSubscription(){this.syncGeneration();let e=++this.subscriptionEpoch;return this.invalidateStream("probing"),{listener:t=>{this.disposed||e!==this.subscriptionEpoch||this.handleStreamPayload(t)},cancel:()=>{e===this.subscriptionEpoch&&(this.subscriptionEpoch+=1,this.invalidateStream("degraded"))}}}isCertified(){return this.syncGeneration(),"live"===this.health}dispose(){this.disposed=!0,this.subscriptionEpoch+=1}handleStreamPayload(e){if(this.syncGeneration(),e&&"object"==typeof e){if("snapshot"===e.type){this.invalidateStream("probing"),this.snapshotSeen=!0,this.applyCurrent(e,"stream"),this.startCurrentRequest();return}if("updated"===e.type){let t=this.requirementRevision,i=this.generation;if(!this.applyCurrent(e,"stream").accepted||!this.isCurrentGeneration(i))return;this.health="live",this.satisfiedRevision=Math.max(this.satisfiedRevision,t),this.startTrailingRequest();return}("error"===e.type||"end"===e.type)&&(this.invalidateStream("degraded"),this.startCurrentRequest())}}applyCurrent(e,t){let i=this.generation,r=this.options.apply(e);return r.accepted&&this.isCurrentGeneration(i)?(this.applicationRevision=void 0===r.applicationRevision?this.applicationRevision+1:Math.max(this.applicationRevision,r.applicationRevision),this.options.consumeAccepted(e,r.effectiveTabs,t),r):{accepted:!1}}invalidateStream(e){this.barrier+=1,this.health=e,this.snapshotSeen=!1,this.requirementRevision+=1}startCurrentRequest(e=!1){if(this.disposed||!this.reconciliationActive)return Promise.resolve();let t=`${this.generation}:${this.barrier}`,i=this.inFlight.get(t);if(i)return i.promise;let r,n=new Promise(e=>{r=e}),s={promise:n,resolve:r,retry:e};return this.inFlight.set(t,s),this.runCohortRequest(t,s),n}runCohortRequest(e,t){let i={generation:this.generation,barrier:this.barrier,requirement:this.requirementRevision,applicationRevision:this.readApplicationRevision()},r=i=>{i&&this.inFlight.get(e)===t&&e===`${this.generation}:${this.barrier}`&&this.reconciliationActive&&this.requirementRevision>this.satisfiedRevision?this.runCohortRequest(e,t):(this.inFlight.get(e)===t&&this.inFlight.delete(e),t.resolve())};this.runRequest(i).then(r,()=>r(!1))}async runRequest(e){try{this.options.onFetchStarted?.();let t=await ib.request(this.options.client,{worktree:this.options.scope});if(!this.isCurrentGeneration(e.generation))return!1;if(!t.ok)return e.barrier===this.barrier&&this.options.onFetchFailed?.(t),!1;let i=ib.interpret(t);return e.barrier===this.barrier&&e.applicationRevision===this.readApplicationRevision()&&(this.options.onFetchSucceeded?.(i),!!this.applyCurrent(i,"list").accepted&&!!this.isCurrentGeneration(e.generation))&&(this.satisfiedRevision=Math.max(this.satisfiedRevision,e.requirement),this.snapshotSeen&&(this.health="live"),!0)}catch(t){return this.isCurrentGeneration(e.generation)&&e.barrier===this.barrier&&this.options.onFetchErrored?.(t),!1}}startTrailingRequest(){!this.disposed&&this.reconciliationActive&&this.requirementRevision>this.satisfiedRevision&&!this.inFlight.has(`${this.generation}:${this.barrier}`)&&this.startCurrentRequest()}syncGeneration(){if(this.disposed)return;let e=this.readGeneration();e!==this.generation&&(this.generation=e,this.invalidateStream("probing"))}isCurrentGeneration(e){return!this.disposed&&e===this.generation&&e===this.readGeneration()}readGeneration(){return this.options.client.getGeneration?.()??0}readApplicationRevision(){return Math.max(this.applicationRevision,this.options.getApplicationRevision?.()??0)}},Ww=class{contextKey=null;remaining=5;observeContext(e){e!==this.contextKey&&(this.contextKey=e,this.remaining=5)}take(e){return this.observeContext(e),null===e?{allowed:!1,parked:!1}:0===this.remaining?{allowed:!1,parked:!0}:(this.remaining-=1,{allowed:!0,parked:!1})}reset(){this.contextKey=null,this.remaining=5}},WS=class{activeTabId=null;contextKey=null;initialized=!1;tabs=null;read(e,t){return this.initialized&&e===this.tabs&&t===this.activeTabId||(this.initialized=!0,this.tabs=e,this.activeTabId=t,this.contextKey=function(e,t){if(null===t)return null;let i=e.find(e=>e.id===t);return i?.type!=="terminal"||"string"==typeof i.terminal?null:JSON.stringify([i.id,i.parentTabId,i.leafId??null])}(e,t)),this.contextKey}},Wx=Promise.resolve(),WT=oa(os()),Wk=oa(oe()),WC=oa(oi());function WL(e,t,i){return"ios"===i&&"active"===t&&("background"===e||"inactive"===e)}function WM({activeHandleRef:e,terminalRefs:t,initializedHandlesRef:i,connStateRef:r,unsubscribeTerminal:n,subscribeToTerminal:s,schedule:o,delayMs:a=120}){if("connected"!==r.current)return"deferred";let l=Array.from(i.current).filter(e=>t.current.has(e));if(0===l.length)return"skipped";let c=e.current,d=!!c&&t.current.has(c)&&i.current.has(c);for(let e of l)i.current.delete(e);return d&&c&&(n(c),o(()=>{"connected"===r.current&&e.current===c&&t.current.has(c)&&s(c)},a)),"recovered"}var WR=oa(os()),WI=oa(os()),WA=oa(oe());function WP(e,t){return"refit-committed"===t.type?e.keyboardVisible?{state:{...e,pending:!0},shouldRefit:!1}:{state:{...e,pending:!1},shouldRefit:!0}:"keyboard-visibility"===t.type?t.visible===e.keyboardVisible?{state:e,shouldRefit:!1}:t.visible?{state:{...e,keyboardVisible:!0},shouldRefit:!1}:{state:{...e,keyboardVisible:!1,pending:!1},shouldRefit:e.pending}:t.height===e.frameHeight?{state:e,shouldRefit:!1}:e.keyboardVisible?{state:{...e,frameHeight:t.height,pending:!0},shouldRefit:!1}:{state:{...e,frameHeight:t.height,pending:!1},shouldRefit:!0}}var WE=oa(os()),WD=oa(os()),WB=oa(oi()),WQ=oa(os()),Wj=oa(os()),WF=oa(os()),WO=oa(oe()),WW={failWhenDisconnected:!0};function WH(e){return{terminal:e.terminal,text:e.text,enter:e.enter,...e.deviceToken?{client:{id:e.deviceToken,type:"mobile"}}:{}}}async function WN(e){let t=function({targetHandle:e,activeHandle:t,activeSessionTabType:i}){return e!==t||"terminal"!==i?null:e}({targetHandle:e.targetHandle,activeHandle:e.activeHandle,activeSessionTabType:e.activeSessionTabType});return!!e.client&&!!t&&"connected"===e.connState&&eI.request(e.client,WH({terminal:t,text:e.bytes,enter:!1,deviceToken:e.deviceToken}),WW).then(i=>{let r=!0===eI.interpret(i);return r&&eE(e.client,t),r},()=>!1)}var Wz=oa(os());function W$(e,t){let i=(0,Wz.useRef)(t);(0,Wz.useEffect)(()=>{i.current=t});let r=(0,Wz.useRef)(null);return(0,Wz.useCallback)(t=>{e.current=t,r.current?.(),r.current=t?function(e,t){if(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLTextAreaElement))return()=>{};let i=e=>{e instanceof InputEvent&&("insertLineBreak"!==e.inputType&&"insertParagraph"!==e.inputType||(e.preventDefault(),t()))};return e.addEventListener("beforeinput",i),()=>e.removeEventListener("beforeinput",i)}(t,()=>i.current()):null},[e])}var Wq=oa(os()),WK=oa(os()),WV=oa(os());async function WU(e){let t=()=>{let t=e.getActivationState();return t.activated||t.activationSeq!==t.latestActivationSeq};if(t()||(await e.fetchSessionTabs(),t()))return!1;let i=function(e,t,i={}){let r=e.filter(e=>"browser"!==e.type&&"terminal"!==e.type&&e.relativePath===t);return 0===r.length?null:"diff"===i.preferMode?r.find(e=>"diff"===e.mode)??r[0]??null:r.find(e=>"diff"!==e.mode)??r[0]??null}(e.getTabs(),e.relativePath,{preferMode:"diff"});if(!i)return!1;let r=e.getActiveTabId();return r===i.id||r===e.activeTabIdAtTap&&(e.switchSessionTab(i),!0)}function WZ(e){let t="agent-session"===e.activeTabType?null!==e.sourceSessionTabId&&void 0!==e.sourceSessionTabId&&e.activeSessionTabId===e.sourceSessionTabId:"terminal"===e.activeTabType&&null!==e.sourceTerminalHandle&&e.activeTerminalHandle===e.sourceTerminalHandle;return!e.activated&&e.activationSeq===e.latestActivationSeq&&t}function WG(e){WX(e).catch(()=>{WY(e)})}function WY(e){e.onOpenFailed&&WZ(e.getActivationState(!1))&&e.onOpenFailed()}async function WX(e){let t,i,r=`id:${e.worktreeId}`,n=await iZ.request(e.client,{worktree:r,pathText:e.pathText,crossWorkspace:!0,...e.terminalHandle&&e.terminalHandle.trim().length>0?{terminal:e.terminalHandle}:{},...e.cwd&&e.cwd.trim().length>0?{cwd:e.cwd}:{},...e.nativeChatContext?{nativeChatContext:e.nativeChatContext}:{}},{timeoutMs:1e4}),s=iZ.interpret(n);if(!s.accepted)return void WY(e);let o=s.value;if(!o.exists||o.isDirectory)return void WY(e);if(!WZ(e.getActivationState(!1)))return;let a=o.worktree?.trim()||e.worktreeId,l=`id:${a}`,c=a===e.worktreeId?e.worktreeName:void 0;if(o.openTarget?.kind==="absolute-file"){e.triggerOpenFeedback(),e.pushPreviewRoute(rd({hostId:e.hostId,worktreeId:a,source:"terminalArtifact",absolutePath:o.openTarget.absolutePath,grantId:o.openTarget.grantId,pathText:e.pathText,...e.cwd&&e.cwd.trim().length>0?{cwd:e.cwd}:{},...e.terminalHandle&&e.terminalHandle.trim().length>0?{terminal:e.terminalHandle}:{},...e.nativeChatContext?{nativeChatTab:e.nativeChatContext.tabId,nativeChatSession:e.nativeChatContext.sessionId}:{},name:WJ(o.openTarget.absolutePath),...null!==e.line?{line:String(e.line)}:{},...null!==e.column?{column:String(e.column)}:{},...c?{worktreeName:c}:{}}));return}let d=o.openTarget?.kind==="worktree-file"?o.openTarget.relativePath:o.relativePath;if(!d)return void WY(e);e.triggerOpenFeedback();let u=()=>e.pushPreviewRoute(rd({hostId:e.hostId,worktreeId:a,source:"worktree",relativePath:d,name:WJ(d),...null!==e.line?{line:String(e.line)}:{},...null!==e.column?{column:String(e.column)}:{},...c?{worktreeName:c}:{}}));if(a!==e.worktreeId||null!==e.line||null!==e.column)return void u();if("html"===rl(d)&&o.openTarget?.kind==="worktree-file"&&"local"===o.openTarget.provider)return void e.openBrowser(ie(o.openTarget.absolutePath));let h=await iH.request(e.client,{worktree:l,relativePath:d},{timeoutMs:15e3});if(ej(h)){if(!WZ(e.getActivationState(!1)))return;u();return}let f=iH.interpret(h);f.accepted&&f.value.opened?(t=!1,i=async()=>{if(!WZ(e.getActivationState(t))||(await e.fetchSessionTabs(),!WZ(e.getActivationState(t))))return;let i=e.getSessionTabs().find(e=>e.relativePath===d);i&&(e.getActiveSessionTabId()!==i.id&&e.switchSessionTab(i),t=!0)},e.scheduleDelayedAction(()=>{i()},300),e.scheduleDelayedAction(()=>{i()},900),e.scheduleDelayedAction(()=>{i()},1800)):WY(e)}function WJ(e){return e.split(/[\\/]/).findLast(Boolean)}var W0=oa(os()),W1=oa(os()),W5=oa(oe()),W2=/^ */;function W3(e){let t=e.endsWith("\r"),i=t?e.slice(0,-1):e;return{indent:W2.exec(i)?.[0].length??0,text:i,terminator:t?"\r":""}}var W6=oa(os()),W4=oa(os()),W7=oa(oe()),W8=oa(os()),W9=oa(os()),He={"application/pdf":"pdf","application/json":"json","application/zip":"zip","application/xml":"xml","text/plain":"txt","text/markdown":"md","text/csv":"csv","text/html":"html","image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic"};async function*Ht(e,t){let i=[...t];try{for(;i.length>0;){let t=i[0],r=await it(e,t);i.shift(),await ii(e,t.handle),yield{base64:r}}}finally{await ir(e,i)}}async function Hi(e){try{return await e.pickMedia("files",!0)}catch(e){throw e instanceof is&&"native_media_too_large"===e.reason?new FC(null):e}}async function*Hr(e,t){let i=[...t];try{let t=0;for(;i.length>0;){let r=i[0];t+=1;let n=(e.canNameMedia?await e.nameMedia(r.handle):null)??function(e,t){let i=e.split(";")[0].trim().toLowerCase(),r=He[i],n=i.split("/")[1]??"",s=r??(/^[a-z0-9]{1,8}$/.test(n)?n:"");return s?`attachment-${t}.${s}`:`attachment-${t}`}(r.mime,t),s=await it(e,r);i.shift(),await ii(e,r.handle),yield{name:n,mime:r.mime,byteLength:r.byteLength,base64:s}}}finally{await ir(e,i)}}function Hn(){let e=io();return(0,W9.useMemo)(()=>({pickImage:async t=>{for await(let i of Ht(e,await e.pickMedia(t,!1)))return i;return null},pickImages:t=>({[Symbol.asyncIterator]:async function*(){yield*Ht(e,await e.pickMedia(t,!0))}}),pickFiles:()=>({[Symbol.asyncIterator]:async function*(){yield*Hr(e,await Hi(e))}})}),[e])}async function Hs(e,{client:t,agent:i,terminal:r,deviceToken:n,getConnectionId:s,pickImage:o,onUploadStart:a,beforeTerminalSend:l}){let c=await o(e);if(!c)return!1;a?.();let d=await s(),u=eT(eR(await eM(t,c.base64,{connectionId:d}),i),!0);if(l&&!await l(r))return!1;let h=await tl.request(t,{terminal:r,text:u,enter:!1,...n?{client:{id:n,type:"mobile"}}:{}});return!0===tl.interpret(h)}var Ho=oa(os());async function Ha(e,{client:t,getConnectionId:i,pickImages:r,onUploadStart:n,onImageUploaded:s}){let o=await r(e),a=[],l=null;for await(let e of o){0===a.length&&(n?.(),l=await i());let r={path:await eM(t,e.base64,{connectionId:l}),previewUri:e.uri??`data:image/png;base64,${e.base64}`};a.push(r),s?.(r)}return a}var Hl=[];function Hc(e,t,i){if(i.length>0)return{...e,[t]:i};let r={...e};return delete r[t],r}var Hd=oa(os()),Hu=[],Hh=oa(os()),Hf=sq({uploadId:sj()}),Hp=sq({path:sj(),name:sj(),byteLength:sF()}),Hm=rI(rM({name:"agent-session-attachment.upload-start",method:"agentSessionAttachment.uploadStart",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rA("agent-session-attachment-upload-slot",Hf)})),Hg=rI(rM({name:"agent-session-attachment.upload-append",method:"agentSessionAttachment.uploadAppend",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rA("agent-session-attachment-chunk-appended",sW())})),Hb=rI(rM({name:"agent-session-attachment.upload-commit",method:"agentSessionAttachment.uploadCommit",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rA("agent-session-attachment-stored",Hp)})),Hv=rI(rM({name:"agent-session-attachment.upload-abort-or-skip",method:"agentSessionAttachment.uploadAbort",acceptance:"success-result-or-skip",barrier:"after-caller-barrier",read:rA("agent-session-attachment-upload-aborted",sW())}));async function Hy(e,t){var i;let r,{uploadId:n}=Hm.interpret(await Hm.request(e,{sessionId:t.sessionId,name:t.name,byteLength:(r=(i=t.base64).endsWith("==")?2:+!!i.endsWith("="),i.length/4*3-r)}));try{for(let i of function*(e){let t=0;do yield{offset:t/4*3,contentBase64:e.slice(t,t+524288)},t+=524288;while(t{}),t}}var H_=[],Hw=oa(os()),HS=oa(os()),Hx=rI(rM({name:"agent-session.commands-or-skip",method:"agentSession.commands",acceptance:"success-result-or-skip",barrier:"after-caller-barrier",read:rA("agent-session-commands",sq({commands:sH(sq({name:sj(),kind:sZ(["command","skill"]),kindUnspecified:sY(!0).optional(),description:sj().optional(),argumentHint:sj().optional()})).optional()}))})),HT=[],Hk=oa(os()),HC=oa(os()),HL=/^data:image\/[a-z0-9.+-]+;base64,/i,HM="image/png",HR=async(e,t)=>{let i=e.replace(HL,""),r=new Image;r.src=`data:${HM};base64,${i}`,await r.decode();let n=document.createElement("canvas");n.width=t.width,n.height=t.height;let s=n.getContext("2d");if(null===s)throw Error("Failed to encode resized clipboard image");s.drawImage(r,0,0,n.width,n.height);let o=n.toDataURL(HM).replace(HL,"");if(0===o.length)throw Error("Failed to encode resized clipboard image");return{data:o,width:n.width,height:n.height}},HI=oa(os()),HA=new Set(["structured_agent_session_unsupported"]),HP=new Set(["method_not_found"]),HE=/(?:: |\n)[ \t]*$/;function HD(e,t){let i=e.trimEnd();if(!i.endsWith(t))return!1;let r=i.slice(0,-t.length);return""===r.trim()||HE.test(r)}function HB(e,t){let i=new Set,r=e;for(;!i.has(r);){if("string"==typeof r)return HD(r,t);if(!r||"object"!=typeof r)break;i.add(r);let e=r;if(e.code===t||e.error?.code===t||e.response?.error?.code===t||[e.message,e.error?.message,e.response?.error?.message].some(e=>"string"==typeof e&&HD(e,t)))return!0;r=e.cause}return!1}var HQ="selector_not_found",Hj=[50,150,300];function HF(e){return new Promise(t=>setTimeout(t,e))}function HO(e,t){return{kind:"unknown",message:(t instanceof Error?t.message.trim():"")||HW(e)}}function HW(e){return`The ${re[e]} chat result could not be confirmed.`}function HH(e,t,i){return"string"==typeof t&&(HA.has(t)||HP.has(t))?{kind:"failed",message:i||`Could not open ${re[e]} chat.`}:HO(e,Error(i))}async function HN(e,t,i){let r,n=`id:${t}`,s;for(let t=0;;t+=1){try{s=await i$.request(e,{worktree:n,agent:i})}catch(i){let e=Hj[t];if(void 0===e||!HB(i,HQ))return{kind:"unsupported"};await HF(e);continue}let r=Hj[t];if(void 0!==r&&HB(s,HQ)){await HF(r);continue}break}if(!s||"object"!=typeof s||"boolean"!=typeof s.ok||!s.ok)return{kind:"unsupported"};let o=s.result;if(!o||"object"!=typeof o||!0!==o.supported)return{kind:"unsupported",reason:o?.reason};let a=e8({sessionId:e7(i,iR),worktree:n,agent:i,randomUuid:iR});e9(a.envelope.sessionId,n);try{r=await iq.request(e,a,{timeoutMs:15e3,budgetSpansConnect:!0})}catch{try{r=await iq.request(e,a,{timeoutMs:15e3,budgetSpansConnect:!0})}catch(e){return HO(i,e)}}if(!r||"object"!=typeof r||"boolean"!=typeof r.ok)return HO(i,Error(HW(i)));if(!r.ok){let e=r.error;return e&&"object"==typeof e&&"string"==typeof e.code&&"string"==typeof e.message?HH(i,e.code,e.message):HO(i,Error(HW(i)))}let l=r.result;return l&&"object"==typeof l&&"boolean"==typeof l.ok?l.ok?l.value&&"string"==typeof l.value.sessionId&&l.value.sessionId.trim()?{kind:"created",sessionId:l.value.sessionId}:HO(i,Error(HW(i))):l.refusal&&"object"==typeof l.refusal&&"string"==typeof l.refusal.code&&"string"==typeof l.refusal.message?HH(i,l.refusal.code,l.refusal.message):HO(i,Error(HW(i))):HO(i,Error(HW(i)))}async function Hz(e){let{options:t,pendingSelectionRef:i,showToast:r}=e,n=t?.agentPrompt??t?.initialPrompt,s=tr(e.agent),o=e.hostCapabilities?.includes(tq)?function(e,t){let i=t?e.find(e=>e.id===t):void 0;if(i)return"terminal"===i.type?i.parentTabId:i.id}(e.getSessionTabs(),e.activeSessionTabId):void 0;i.current=OB(e.lock,s,null);let a=await tn({client:e.client,hostCapabilities:e.hostCapabilities,worktreeId:e.worktreeId,agent:e.agent,reservation:s,...o?{placement:{afterTabId:o}}:{},...n?.trim()?{prompt:{text:n,delivery:"submit"}}:{},...t?.agentPrompt?{launchSource:"quick_command"}:t?.initialPrompt?{launchSource:"diff_notes_send"}:{}});if("unsupported"===a.kind)return i.current=Oj(i.current,e.lock),!1;if("failed"===a.kind)return e.reportCreateFailure(a.message),!0;if("tab-closed"===a.kind)return i.current=Oj(i.current,e.lock),!0;if("unknown"===a.kind){var l;let i;return(l=e.getSessionTabs(),i={pane:null,sessionId:null,handle:null,...s},l.some(e=>OH(e,i)&&("terminal"!==e.type||null!==e.terminal)))?n?.trim()&&(sy(),r(t?.initialPrompt?"The agent started, but couldn't confirm the notes were sent.":"The agent started, but couldn't confirm the prompt was sent.",2400)):(e.setCreateError(a.message),sy(),r(a.message,1800)),!0}let{outcome:c,warning:d}=a.result;return i.current=OQ(i.current,e.lock,"structured"===c.kind?{sessionId:c.sessionId}:{handle:c.handle}),e.fetchSessionTabs(),!1===a.promptDelivered?(sy(),r(t?.initialPrompt?"The agent started, but the notes weren't sent.":eY,2400)):a.promptDelivered&&t?.initialPrompt?(sv(),r(t.successToast??"Notes sent"),t.onPromptSent?.()):d?.trim()&&r(d.trim(),2400),!0}var H$=oa(os()),Hq={"browser.back":ad,"browser.forward":au,"browser.reload":ah},HK=oa(os()),HV=[{mode:"others",label:"Close Other Tabs"},{mode:"left",label:"Close Tabs to the Left"}];function HU(e,t,i){return Math.max(0,(Math.max(e.cursorY,e.contentBottomRow)+1)*t+t-i)}var HZ=oa(os()),HG=oa(oo()),HY=oa(oo());function HX(){let e,t,i,r,n,s,a,l,c,d,h,f,p,m,g,b,v,y,_,w,S,x,T,C,L,R,P,D,Q=(function(e){let{hostId:t,worktreeId:i,created:r,isFloatingWorkspaceRoute:n,connState:s,client:o,setTerminals:a,terminalsRef:l,setSessionTabs:c,appliedSnapshotMarkerRef:d,closedTabTombstonesRef:h,setTerminalsLoaded:f,setActiveHandle:p,setActiveSessionTabId:m,setMarkdownDocs:g,setFileDocs:b,terminalGestureInputQueuesRef:v,terminalGestureInputInFlightRef:y,sessionTabActionSheetKeyboardHideSubRef:_,sessionTabActionSheetRequestSeqRef:w,initializedHandlesRef:S,terminalDiagnosticsRef:x,activeHandleRef:T,activeSessionTabTypeRef:k,pendingSelectionRef:C,selectedSessionTabIdRef:L,pendingBrowserFocusPageIdRef:M,pendingTerminalActivationAttemptRef:R,initialSessionAutoCreateRef:I,bufferedTerminalDraftState:A,clearPendingLiveInputCommit:P,clearDelayedActionTimers:E,showToast:D,clearTerminalCache:B,fetchTerminals:Q,ensureSessionTabs:j}=e;(0,WE.useEffect)(()=>{for(let e of(w.current+=1,_.current?.remove(),_.current=null,B(),T.current=null,k.current=null,C.current=null,L.current=null,M.current=null,R.current=null,I.current=BD(),x.current.resetRoute(),d.current={epoch:null,version:-1},h.current.clear(),A.resetDrafts(),v.current.values()))e.timer&&clearTimeout(e.timer);return v.current.clear(),y.current.clear(),p(null),a([]),l.current=[],c([]),m(null),P(),g(new Map),b(new Map),E(),()=>{w.current+=1,_.current?.remove(),A.clearPendingRestorations(),P(),E()}},[E,P,A.clearPendingRestorations,B,t,A.resetDrafts,i]),(0,WE.useEffect)(()=>{if("connected"!==s)return;0===S.current.size&&f(!1),S.current.clear();let e=!1,t=[];function a(i,r){e||t.push(setTimeout(i,r))}return(async()=>{let t=t=>{var i;let r=null===t?null:u.interpret(t);!e&&r?.accepted===!0&&(i=r.value)&&"object"==typeof i&&"sleepingAgentWake"in i&&"unsupported-headless"===i.sleepingAgentWake&&D("Open RuFlo on the host to wake sleeping agents.",3e3)};o&&"1"!==r&&!n&&u.request(o,{worktree:`id:${i}`,notifyClients:!1,navigation:"caller"}).then(t).catch(()=>null),e||(await j().catch(()=>null),!e&&(await Q({allowEmptyLoaded:!1}),e||(a(()=>{Q({allowEmptyLoaded:!1})},750),a(()=>{Q({allowEmptyLoaded:!0})},1500),o&&"1"===r&&!n&&a(()=>{T.current||(async()=>{t(await u.request(o,{worktree:`id:${i}`,notifyClients:!1,navigation:"caller"}).catch(()=>null)),e||(await Q({allowEmptyLoaded:!0}),a(()=>{Q({allowEmptyLoaded:!0})},750))})()},1800))))})(),()=>{for(let i of(e=!0,t))clearTimeout(i)}},[o,s,r,Q,j,n,D,i])}(b=Object.assign(g=Object.assign(m=Object.assign(p=Object.assign(f=Object.assign(h=Object.assign(d=Object.assign(c=Object.assign(l=Object.assign(a=Object.assign(s=Object.assign(n=Object.assign(r=Object.assign(i=Object.assign(t=Object.assign(e=function(){var e;let{hostId:t,worktreeId:i,name:r,created:n,warning:s}=(0,Bc.useLocalSearchParams)(),o=i.startsWith("folder:"),a=tf(i),l=rB(),c=(0,Bl.useSafeAreaInsets)(),{client:d,clientId:u,state:h}=rf(t),{hostCapabilities:f}=rg(),p=t4(t),m=t7(t),g=nd(),{name:b,resolution:v}=function({client:e,connState:t,routeName:i,worktreeId:r}){let n=tf(r),s=i?.trim()??"",[o,a]=(0,Bm.useState)(()=>({worktreeId:r,name:s})),[l,c]=(0,Bm.useState)(()=>({worktreeId:r,resolution:"unknown"})),d=(0,Bm.useRef)({worktreeId:r,count:0});return(0,Bm.useEffect)(()=>{a(e=>e.worktreeId===r&&e.name===s?e:{worktreeId:r,name:s})},[s,r]),(0,Bm.useEffect)(()=>{c(e=>e.worktreeId===r?e:{worktreeId:r,resolution:"unknown"})},[r]),(0,Bg.useFocusEffect)((0,Bm.useCallback)(()=>{if(n||!e||"connected"!==t)return;let i=!1,s=!1,o=!1,l=null,u=0,h=iF(r),f=()=>{null!==l&&(clearInterval(l),l=null)},p=async()=>{let t=++u;try{let n,l=await iS.request(e,{worktree:`id:${r}`});if(i||t!==u)return;let h=l.ok?"present":l.error.code===Bb?"missing":"runtime_error"!==l.error.code||!function(e){let t=e.trimEnd();if(!t.endsWith(Bb))return!1;let i=t.slice(0,-Bb.length);return""===i.trim()||Bv.test(i)}(l.error.message)?"unknown":"missing",p=d.current;d.current={worktreeId:r,count:"missing"===h?(p.worktreeId===r?p.count:0)+1:0};let m="missing"===h&&d.current.count<2?"unknown":h;c(e=>e.worktreeId===r&&e.resolution===m?e:{worktreeId:r,resolution:m});let g=iS.interpret(l);if(!g.accepted)return;let b=g.value,v=b&&(n=[b].find(e=>(e.worktreeId??e.id)===r))&&(n.displayName?.trim()||n.repo?.trim())||null;v&&a(e=>e.worktreeId===r&&e.name===v?e:{worktreeId:r,name:v}),o=!0,s&&f()}catch{}},m=()=>{i||null!==l||(l=setInterval(()=>{p()},3e3))},g=()=>{o=!1,m(),p()};m();let b=e.subscribe("runtime.clientEvents.subscribe",null,e=>{if(!i&&e&&"object"==typeof e){if("ready"===e.type){let e=s;s=!0,o&&f(),e&&g();return}if("end"===e.type||"error"===e.type){s=!1,m();return}("reposChanged"===e.type||"worktreesChanged"===e.type&&e.repoId===h)&&g()}});return p(),()=>{i=!0,f(),b()}},[e,t,r,n])),n?{name:th,resolution:"unknown"}:{name:o.worktreeId===r?o.name:s,resolution:l.worktreeId===r?l.resolution:"unknown"}}({client:d,connState:h,routeName:r,worktreeId:i});!function(e){let{hostId:t,worktreeId:i,resolution:r}=e,n=(0,By.useRef)(null),s=(0,By.useRef)(e.bounce);(0,By.useEffect)(()=>{s.current=e.bounce}),(0,By.useEffect)(()=>{!t||n.current===i||"missing"!==r||i.startsWith("folder:")||tf(i)||(n.current=i,s.current(t))},[t,i,r])}({hostId:t,worktreeId:i,resolution:v,bounce:e=>l.replace(k(e,"worktree-missing"))});let{isWideLayout:y}=iE(),[_,w]=(0,Ba.useState)(null),[S,x]=(0,Ba.useState)(0),T=!a&&(e={isWideLayout:y,availableWidth:S,dockWidth:N}).isWideLayout&&e.availableWidth>=e.dockWidth+(e.minMainWidth??360);(0,Ba.useEffect)(()=>{T||null===_||w(null)},[T,_]);let{isGithubRepo:C,repoLoaded:L}=function(e){let{client:t,connState:i,worktreeId:r,includeBranchIdentity:n=!0}=e,[s,o]=(0,Bd.useState)({branch:null,headSha:null,status:null,isGithubRepo:!1,repoLoaded:!1,loaded:!1}),a=null!==t&&"connected"===i;return(0,Bd.useEffect)(()=>{let e=!1;return a&&t?(o({branch:null,headSha:null,status:null,isGithubRepo:!1,repoLoaded:!1,loaded:!n}),Bu(t,r).then(t=>{e||o(e=>({...e,isGithubRepo:t.isGithubRepo,repoLoaded:!0}))}).catch(()=>{e||o(e=>({...e,isGithubRepo:!1,repoLoaded:!0}))}),n?(Bh(t,r).then(t=>{e||o(e=>({...e,...t,loaded:!0}))}).catch(()=>{e||o(e=>({...e,branch:null,headSha:null,status:null,loaded:!0}))}),()=>{e=!0}):()=>{e=!0}):void o({branch:null,headSha:null,status:null,isGithubRepo:!1,repoLoaded:!1,loaded:!n})},[a,t,r,n]),s}({client:a?null:d,connState:h,worktreeId:i,includeBranchIdentity:!1});(0,Ba.useEffect)(()=>{L&&!C&&"pr"===_&&w(null)},[_,L,C]);let M="string"==typeof s?s.trim():"";return{hostId:t,worktreeId:i,routeWorktreeName:r,created:n,createdWarning:s,isFolderWorkspaceRoute:o,isFloatingWorkspaceRoute:a,router:l,insets:c,client:d,clientId:u,connState:h,hostCapabilities:f,reconnectAttempts:p,lastConnectedAt:m,forceReconnectHost:g,worktreeName:b,worktreeResolution:v,isWideLayout:y,activePanel:_,setActivePanel:w,sessionContentRowWidth:S,setSessionContentRowWidth:x,canDockPanel:T,prIsGithubRepo:C,prRepoContextLoaded:L,initialCreateWarning:M}}(),function(e){let{worktreeId:t,hostId:i,initialCreateWarning:r}=e,[n,s]=(0,B_.useState)([]),o=(0,B_.useRef)([]),[a,l]=(0,B_.useState)([]),c=(0,B_.useRef)([]),d=(0,B_.useRef)({epoch:null,version:-1}),u=(0,B_.useRef)(0),h=(0,B_.useRef)(new Map),[f,p]=function(e){let[t,i]=(0,BE.useReducer)((t,i)=>i?e:null,null);return[t===e,i]}(t),[m,g]=(0,B_.useState)(""),[b,v]=(0,B_.useState)(1),[y,_]=(0,B_.useState)(!1),[w,S]=(0,B_.useState)("orca-browser"),[x,T]=(0,B_.useState)(""),{clearTerminalLiveInputDefault:k,defaultTerminalHandlesToLiveInput:C,liveInputTerminalHandles:L,liveInputTerminalHandlesRef:M,pruneTerminalHandlesFromLiveInput:R,toggleTerminalLiveInput:I}=function({hostId:e,worktreeId:t}){let[i,r]=(0,BM.useState)(()=>new Set),n=(0,BM.useRef)(new Set),s=(0,BM.useRef)(new Set),o=(0,BM.useRef)(new Set),a=(0,BM.useRef)(!1),l=(0,BM.useRef)(new Map),c=(0,BM.useRef)(new Set),d=(0,BM.useCallback)(e=>{var t;if(!a.current){for(let t of e)c.current.add(t);return}let i=(t=o.current,e.filter(e=>!t.has(e))),l=function(e,t,i){let r=null,n=null;for(let s of i)t.has(s)||(r??=new Set(e),n??=new Set(t),r.add(s),n.add(s));return r&&n?{enabledHandles:r,defaultedHandles:n,changed:!0}:{enabledHandles:e,defaultedHandles:t,changed:!1}}(n.current,s.current,i);if(!l.changed)return;let d=new Set(l.enabledHandles),u=new Set(l.defaultedHandles);n.current=d,s.current=u,r(d)},[]),u=(0,BM.useCallback)(()=>{B(e,t,o.current).catch(()=>{})},[e,t]),h=(0,BM.useCallback)(e=>{let t=function(e,t,i){let r=null,n=null;for(let t of e)i.has(t)||(r??=new Set(e)).delete(t);for(let e of t)i.has(e)||(n??=new Set(t)).delete(e);return r||n?{enabledHandles:r??e,defaultedHandles:n??t,changed:!0}:{enabledHandles:e,defaultedHandles:t,changed:!1}}(n.current,s.current,e),i=!1;for(let t of o.current)e.has(t)||(o.current.delete(t),a.current||l.current.set(t,!1),i=!0);if(i&&a.current&&u(),!t.changed)return;let c=new Set(t.enabledHandles),d=new Set(t.defaultedHandles);n.current=c,s.current=d,r(c)},[u]),f=(0,BM.useCallback)(e=>{let t=new Set([...n.current,...s.current]);t.delete(e),a.current||l.current.set(e,!1),o.current.delete(e)&&a.current&&u(),h(t)},[u,h]),p=(0,BM.useCallback)(e=>{let t=!n.current.has(e);return t?o.current.delete(e):o.current.add(e),a.current||l.current.set(e,!t),a.current&&u(),r(i=>{let r=new Set(i);return t?r.add(e):r.delete(e),n.current=r,r}),t},[u]);return(0,BM.useEffect)(()=>{n.current=new Set,s.current=new Set,o.current=new Set,a.current=!1,l.current=new Map,c.current=new Set,r(new Set);let i=!1;return E(e,t).then(e=>{if(i)return;let t=l.current,h=new Set(e.handles);for(let[e,i]of t)i?h.add(e):h.delete(e);o.current=h,a.current=!0,l.current=new Map,e.loaded&&t.size>0&&u();let f=function(e,t,i){let r=null,n=null;for(let t of e)i.has(t)&&(r??=new Set(e)).delete(t);for(let e of i)t.has(e)||(n??=new Set(t)).add(e);return r||n?{enabledHandles:r??e,defaultedHandles:n??t,changed:!0}:{enabledHandles:e,defaultedHandles:t,changed:!1}}(n.current,s.current,h),p=new Set(f.enabledHandles),m=new Set(f.defaultedHandles);n.current=p,s.current=m,r(p);let g=[...c.current];c.current.clear(),d(g)}),()=>{i=!0}},[d,e,u,t]),{clearTerminalLiveInputDefault:f,defaultTerminalHandlesToLiveInput:d,liveInputTerminalHandles:i,liveInputTerminalHandlesRef:n,pruneTerminalHandlesFromLiveInput:h,toggleTerminalLiveInput:p}}({hostId:i,worktreeId:t}),[A,P]=(0,B_.useState)(null),[D,Q]=(0,B_.useState)(0),[j,F]=(0,B_.useState)(null),O=(0,B_.useRef)(null),W=(0,B_.useRef)(null),H=(0,B_.useRef)(null),N=(0,B_.useRef)(0),z=(0,B_.useRef)(0),$=(0,B_.useRef)(0),q=(0,B_.useRef)(new Map),[K,V]=(0,B_.useState)(new Map),U=(0,B_.useRef)(new Map),[Z,G]=(0,B_.useState)(new Map),[Y,X]=(0,B_.useState)([]),J=(0,B_.useRef)([]),[ee,et]=(0,B_.useState)(!1),[ei,er]=(0,B_.useState)(null),[en,es]=(0,B_.useState)(!1),eo=(0,B_.useRef)(null),[ea,el]=(0,B_.useState)(!1),[ec,ed]=(0,B_.useState)(!1),[eu,eh]=(0,B_.useState)(""),[ef,ep]=(0,B_.useState)(()=>o$(r)),[em,eg]=(0,B_.useState)(!1),[eb,ev]=(0,B_.useState)(!1),[ey,e_]=(0,B_.useState)("idle"),[ew,eS]=(0,B_.useState)([]),[ex,eT]=(0,B_.useState)(!1),[ek,eC]=(0,B_.useState)(!1),eL=function(){let[e,t]=(0,BB.useState)(null),[i,r]=(0,BB.useState)(null),[n,s]=(0,BB.useState)(null),[o,a]=(0,BB.useState)(null),[l,c]=(0,BB.useState)(null);return{actionTarget:e,agentSessionActionTarget:l,browserActionTarget:o,fileActionTarget:n,markdownActionTarget:i,setActionTarget:t,setAgentSessionActionTarget:c,setBrowserActionTarget:a,setFileActionTarget:s,setMarkdownActionTarget:r}}(),[eM,eR]=(0,B_.useState)(null),[eI,eA]=(0,B_.useState)(null),[eP,eE]=(0,B_.useState)(null),[eD,eB]=(0,B_.useState)([]),[eQ,ej]=(0,B_.useState)(BC),[eF,eO]=(0,B_.useState)(!1),[eW,eH]=(0,B_.useState)(null),eN=(0,B_.useMemo)(()=>{let e;return Bk(eQ,new Set((e=new Map(D_.map(e=>[e.id,e]))).keys())).flatMap(t=>{let i=e.get(t);return i?[i]:[]})},[eQ]),[ez,e$]=(0,B_.useState)(0),[eq,eK]=(0,B_.useState)(new Map),[eV,eU]=(0,B_.useState)(new Map),[eZ,eG]=(0,B_.useState)(!1),[eY,eX]=(0,B_.useState)(!1),[eJ,e0]=(0,B_.useState)(!1),[e1,e5]=(0,B_.useState)("toggle"),[e2,e3]=(0,B_.useState)(null),e6=(0,B_.useRef)(new Bw.Animated.Value(0)),e4=(0,B_.useRef)(null),e7=(0,B_.useRef)(0);return{terminals:n,setTerminals:s,terminalsRef:o,sessionTabs:a,setSessionTabs:l,sessionTabsRef:c,appliedSnapshotMarkerRef:d,appliedSessionTabsRevisionRef:u,closedTabTombstonesRef:h,terminalsLoaded:f,setTerminalsLoaded:p,input:m,setInput:g,terminalTextScale:b,setTerminalTextScale:v,autocompleteEnabled:y,setAutocompleteEnabled:_,terminalLinkOpenMode:w,setTerminalLinkOpenMode:S,liveInputCapture:x,setLiveInputCapture:T,clearTerminalLiveInputDefault:k,defaultTerminalHandlesToLiveInput:C,liveInputTerminalHandles:L,liveInputTerminalHandlesRef:M,pruneTerminalHandlesFromLiveInput:R,toggleTerminalLiveInput:I,activeHandle:A,setActiveHandle:P,coveredStreamRevision:D,setCoveredStreamRevision:Q,activeSessionTabId:j,setActiveSessionTabId:F,activeSessionTabIdRef:O,selectedSessionTabIdRef:W,tabStripRef:H,tabStripOffsetRef:N,tabStripViewportWidthRef:z,tabStripContentWidthRef:$,tabLayoutsRef:q,markdownDocs:K,setMarkdownDocs:V,markdownDocsRef:U,fileDocs:Z,setFileDocs:G,diffComments:Y,setDiffComments:X,diffCommentsRef:J,diffCommentBusy:ee,setDiffCommentBusy:et,pendingDiffNotesDelivery:ei,setPendingDiffNotesDelivery:er,creating:en,setCreating:es,creatingTerminalRef:eo,creatingBrowser:ea,setCreatingBrowser:el,creatingMarkdown:ec,setCreatingMarkdown:ed,createError:eu,setCreateError:eh,createWarningState:ef,setCreateWarningState:ep,showCreateTabDrawer:em,setShowCreateTabDrawer:eg,showQuickCommands:eb,setShowQuickCommands:ev,createTabAgentLoadState:ey,setCreateTabAgentLoadState:e_,createTabAgentOptions:ew,setCreateTabAgentOptions:eS,showCreateBrowserModal:ex,setShowCreateBrowserModal:eT,showHeaderMoreActions:ek,setShowHeaderMoreActions:eC,...eL,discardMarkdownTarget:eM,setDiscardMarkdownTarget:eR,leaveDrafts:eI,setLeaveDrafts:eA,renameTarget:eP,setRenameTarget:eE,customKeys:eD,setCustomKeys:eB,visibleBuiltInIds:eQ,setVisibleBuiltInIds:ej,showCustomKeyModal:eF,setShowCustomKeyModal:eO,deleteKeyTarget:eW,setDeleteKeyTarget:eH,visibleBuiltInAccessoryKeys:eN,keyboardHeight:ez,setKeyboardHeight:e$,terminalModes:eq,setTerminalModes:eK,terminalKeyboardMetrics:eV,setTerminalKeyboardMetrics:eU,selectModeActive:eZ,setSelectModeActive:eG,canPaste:eY,setCanPaste:eX,showDictationSetup:eJ,setShowDictationSetup:e0,dictationMode:e1,setDictationMode:e5,toastMessage:e2,setToastMessage:e3,toastOpacityRef:e6,toastHideTimerRef:e4,toastSeqRef:e7}}(e)),function(e){let t,i,r,n,{hostId:s,worktreeId:o,connState:a,client:l,clientId:c,sessionTabs:d,setLiveInputCapture:u,liveInputTerminalHandles:h,liveInputTerminalHandlesRef:f,activeHandle:p,activeSessionTabId:m,keyboardHeight:g}=e,b=(0,BQ.useRef)(new Map),v=(0,BQ.useRef)(new Map),y=(0,BQ.useRef)(new Map),_=(0,BQ.useRef)(new Set),w=(0,BQ.useRef)(new Map),S=(0,BQ.useRef)(new Set),x=(0,BQ.useRef)(c);x.current=c;let[T,k]=(0,BQ.useState)(null),C=(0,BQ.useRef)(null),L=(0,BQ.useRef)(a),M=(0,BQ.useRef)(null),R=(0,BQ.useRef)(!1),I=(0,BQ.useRef)(new Map),A=(0,BQ.useRef)(null),P=(0,BQ.useRef)(null),E=(0,BQ.useRef)(null),D=(0,BQ.useRef)(async()=>!1),B=(0,BQ.useRef)(null),Q=(0,BQ.useRef)(0),j=(0,BQ.useRef)(null),F=(0,BQ.useRef)(new Map),O=(0,BQ.useRef)(new Set),W=(0,BQ.useRef)(new Set),H=(0,BQ.useRef)(new Set),N=(0,BQ.useRef)(new eF),z=(0,BQ.useRef)(new BX),$=(0,BQ.useRef)(new Set),q=(0,BQ.useRef)(null),K=function({activeHandle:e,activeHandleRef:t}){let[i,r]=(0,BJ.useState)({}),n=(0,BJ.useRef)(new Map),s=(0,BJ.useRef)(new Map),o=e?i[e]??"":"",a=(0,BJ.useCallback)(e=>{let i=t.current;i&&(n.current.delete(i),r(t=>B0(t,i,e)))},[t]),l=(0,BJ.useCallback)((e,t)=>{var i;let s,o=(i=n.current,s={handle:e},i.set(e,s),s);return r(t=>B0(t,e,"")),{draft:t,handle:e,token:o}},[]),c=(0,BJ.useCallback)(e=>{B1(n.current,e.handle,e.token)&&r(t=>{var i,r;return i=e.token.handle,r=e.draft,(t[i]??"").length>0?t:B0(t,i,r)})},[]),d=(0,BJ.useCallback)(e=>B1(n.current,e.handle,e.token),[]),u=(0,BJ.useCallback)(e=>{let t=new Set(e);for(let e of s.current.values())t.add(e);r(e=>B5(e,t)),B2(n.current,t)},[]),h=(0,BJ.useCallback)((e,t,{retainMissingSurfaces:i=!1}={})=>{let o=s.current;for(let t of e)if(!(t.type&&"terminal"!==t.type)&&"string"==typeof t.terminal){let e=B3(t);o.has(e)||o.set(e,t.terminal)}let a=new Set(i?o.values():[]),l=new Set(i?o.keys():[]),c=[];for(let e of t){if(e.type&&"terminal"!==e.type)continue;let t=B3(e);l.add(t);let i=o.get(t);"string"==typeof e.terminal?(a.add(e.terminal),i&&i!==e.terminal&&c.push({previousHandle:i,nextHandle:e.terminal}),o.set(t,e.terminal)):i&&a.add(i)}for(let e of o.keys())l.has(e)||o.delete(e);for(let{previousHandle:e,nextHandle:t}of c)!function(e,t,i){let r=e.get(t);!r||e.has(i)?e.delete(t):(e.delete(t),r.handle=i,e.set(i,r))}(n.current,e,t);B2(n.current,a),r(e=>{let t=e;for(let{previousHandle:e,nextHandle:i}of c)t=function(e,t,i){if(t===i||!Object.hasOwn(e,t))return e;let r={...e};return Object.hasOwn(e,i)||(r[i]=e[t]??""),delete r[t],r}(t,e,i);return B5(t,a)})},[]),f=(0,BJ.useCallback)(()=>{n.current.clear(),s.current.clear(),r(e=>0===Object.keys(e).length?e:{})},[]);return{beginBufferedTerminalDraftSend:l,clearPendingRestorations:(0,BJ.useCallback)(()=>{n.current.clear()},[]),input:o,pruneDrafts:u,reconcileTerminalTabs:h,resetDrafts:f,restoreRejectedDraft:c,setInput:a,settleBufferedTerminalDraftSend:d}}({activeHandle:p,activeHandleRef:q}),V=(0,BQ.useRef)(K.reconcileTerminalTabs),U=(0,BQ.useRef)(null),Z=(0,BQ.useRef)(null),G=(0,BQ.useRef)(null),Y=(0,BQ.useRef)(null),X=(0,BQ.useRef)(null),J=(0,BQ.useRef)(null),ee=JSON.stringify([s,o]),{registerTerminalInventoryRecoveryAction:et,signalTerminalInventoryRecovery:ei}=(t=(0,B6.useRef)(null),i=(0,B6.useRef)(null),r=(0,B6.useRef)(null),(0,B6.useEffect)(()=>(t.current=ee,()=>{t.current===ee&&(t.current=null)}),[ee]),n=(0,B6.useCallback)(()=>{let e=t.current;if(null!==e&&e!==ee)return;let n=i.current;n?.scope===ee?n.request():r.current=ee},[ee]),{registerTerminalInventoryRecoveryAction:(0,B6.useCallback)(e=>{let t={request:e,scope:ee};i.current=t;let n=r.current;return r.current=null,n===ee&&e(),()=>{i.current===t&&(i.current=null)}},[ee]),signalTerminalInventoryRecovery:n}),er=(0,BQ.useRef)(BD()),en=(0,BQ.useRef)(new Map),es=(0,BQ.useRef)(new Set),eo=(0,BQ.useRef)(new Map),ea=(0,BQ.useRef)(new Set),el=(0,BQ.useRef)(new Map),ec=(0,BQ.useRef)(!1),ed=(0,BQ.useRef)(null),eu=d.find(e=>e.id===m)??null,{clearPendingLiveInputCommit:eh,flushPendingLiveInputBeforeExternalSend:ef,getLiveInputInteractionGeneration:ep,handleLiveInputAccessoryBytes:em,handleLiveInputChange:eg,handleLiveInputKeyPress:eb,handleLiveInputSubmit:ev}=function({activeHandle:e,activeHandleRef:t,activeSessionTabType:i,activeSessionTabTypeRef:r,connected:n,liveInputRef:s,liveInputTerminalHandles:o,liveInputTerminalHandlesRef:a,sendLiveTerminalInputRef:l,setLiveInputCapture:c}){let d=(0,BO.useRef)(0),u=(0,BO.useCallback)(()=>{d.current+=1},[]),{applyLiveInputMirror:h,clearPendingLiveInputCommit:f,flushPendingLiveInputText:p,heldLiveInputTextRef:m,liveInputComposingRef:g,pendingLiveInputHandleRef:b,sentLiveInputTextRef:v,waitForPendingLiveInputFlush:y}=function({activeHandleRef:e,activeSessionTabTypeRef:t,liveInputRef:i,liveInputTerminalHandlesRef:r,sendLiveTerminalInputRef:n,setLiveInputCapture:s}){let o=(0,Bz.useRef)(null),a=(0,Bz.useRef)({current:null,activeRequests:[],generation:0,pendingBatches:[]}),l=(0,Bz.useRef)(""),c=(0,Bz.useRef)(void 0),d=(0,Bz.useRef)(""),u=(0,Bz.useRef)(null),h=(0,Bz.useRef)(async()=>!1),f=(0,Bz.useCallback)(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),p=(0,Bz.useCallback)(()=>{f(),Bq(a.current),l.current="",c.current=void 0,d.current="",u.current=null},[f]),m=(0,Bz.useCallback)(()=>{p(),s(""),B$(i,"")},[i,p,s]),g=(0,Bz.useCallback)(async()=>a.current.current??Promise.resolve(!0),[]),b=(0,Bz.useCallback)((e,t)=>n.current(e,t),[n]),v=(0,Bz.useCallback)(async(i,n,s,m)=>{var v,y;let _,w,S,x,T,k;if(i!==e.current||null!=t.current&&"terminal"!==t.current||!r.current.has(i))return p(),!1;let C=(v=d.current,y={commitHeld:s,composing:m},_=Array.from(n),S=function(e,t){let i=0;for(;i127;)r+=1;return Math.min(r,e.length-t)}(_,S,y.composing),k=Math.min(S,(T=_.slice(0,_.length-x)).length),{eraseCount:w.length-k,appendText:T.slice(k).join(""),nextSentText:T.join(""),heldText:_.slice(_.length-x).join("")});d.current=C.nextSentText,l.current=C.heldText,c.current=m,u.current=C.heldText.length>0||C.nextSentText.length>0?i:null,f(),C.heldText.length>0&&void 0===m&&(o.current=setTimeout(()=>{o.current=null;let e=d.current+l.current;h.current(i,e,!0)},300));let L="".repeat(C.eraseCount)+C.appendText;return 0===L.length?g():function(e,t,i,r){let n=()=>{},s=new Promise(e=>{n=e}),o=e.pendingBatches.at(-1);if(o?.handle===t&&o.sender===r?(o.payload+=i,o.requests.push({resolve:n})):e.pendingBatches.push({handle:t,payload:i,requests:[{resolve:n}],sender:r}),!e.current){let t=e.generation,i=BK(e,t).catch(()=>!1);e.current=i,i.then(()=>{e.current===i&&(e.current=null)})}return s}(a.current,i,L,b)},[e,t,f,r,p,b,g]);(0,Bz.useEffect)(()=>{h.current=v},[v]);let y=(0,Bz.useCallback)((e,t,i)=>v(e,t,!1,i),[v]),_=(0,Bz.useCallback)(async e=>{let t=u.current;if(!t)return g();if(null!==e&&t!==e)return m(),g();let i=l.current,r=i.length>0?await v(t,d.current+i,!0):await g();return m(),r},[m,v,g]);return(0,Bz.useEffect)(()=>()=>{o.current&&(clearTimeout(o.current),o.current=null),l.current="",c.current=void 0,d.current="",u.current=null,Bq(a.current)},[]),{applyLiveInputMirror:y,clearPendingLiveInputCommit:m,flushPendingLiveInputText:_,heldLiveInputTextRef:l,liveInputComposingRef:c,pendingLiveInputHandleRef:u,sentLiveInputTextRef:d,waitForPendingLiveInputFlush:g}}({activeHandleRef:t,activeSessionTabTypeRef:r,liveInputRef:s,liveInputTerminalHandlesRef:a,sendLiveTerminalInputRef:l,setLiveInputCapture:c});(0,BO.useEffect)(()=>{n||f()},[n,f]),(0,BO.useEffect)(()=>{let t=b.current;!t||e&&t===e&&(null==i||"terminal"===i)&&o.has(e)||f()},[e,i,f,o]);let _=(0,BO.useCallback)(async e=>{u();let t=b.current;return t&&t!==e?(f(),y()):t===e?p(e):y()},[u,f,p,y]),w=(0,BO.useCallback)(({nativeEvent:t})=>{e&&o.has(e)?(u(),c(t.text),h(e,BN(t.text),function(e){if(!globalThis.navigator?.userAgent?.includes("Android"))return e}(t.isComposing))):f()},[e,u,h,f,o,c]),S=(0,BO.useCallback)(()=>d.current,[]),x=(0,BO.useCallback)(t=>{if(!e||!o.has(e))return;u();let i=b.current===e;b.current&&!i&&f();let r=function({key:e,heldText:t,sentText:i}){let r,n=(r=BI.get(e))?Dw({key:r,modifiers:[]})?.bytes??null:null;return null===n?{kind:"ignore"}:("Backspace"===e||"Delete"===e)&&(t.length>0||i.length>0)?{kind:"local-edit"}:t.length>0?{kind:"commit-held-then-send",bytes:n}:{kind:"send-now",bytes:n}}({key:t.nativeEvent.key,heldText:i?m.current:"",sentText:i?v.current:""});switch(r.kind){case"ignore":case"local-edit":return;case"send-now":BW(y,()=>l.current(e,r.bytes));return;case"commit-held-then-send":BW(()=>p(e),()=>l.current(e,r.bytes));return}},[e,u,f,p,o,l,y]),T=function({activeHandle:e,applyLiveInputMirror:t,clearPendingLiveInputCommit:i,flushPendingLiveInputText:r,heldLiveInputTextRef:n,liveInputComposingRef:s,liveInputRef:o,liveInputTerminalHandles:a,onInteraction:l,pendingLiveInputHandleRef:c,sentLiveInputTextRef:d,sendLiveTerminalInputRef:u,setLiveInputCapture:h,waitForPendingLiveInputFlush:f}){return(0,BV.useCallback)(async p=>{if(!e)return{kind:"allow-raw"};if(!a.has(e))return BU(f);l();let m=c.current===e;c.current&&!m&&i();let g=m?n.current:"",b=m?d.current:"",v=function({bytes:e,localEdit:t,heldText:i,sentText:r}){return t&&(i.length>0||r.length>0)?{kind:"local-edit",localEdit:t}:i.length>0?{kind:"commit-held-then-send",bytes:e}:{kind:"send-now",bytes:e}}({...p,heldText:g,sentText:b});switch(v.kind){case"send-now":return(p.bytes.endsWith("\r")?await r(e):await f())?{kind:"allow-raw"}:{kind:"suppress-raw"};case"local-edit":{let i=function({localEdit:e,fieldText:t}){if("delete"===e)return t;let i=t.length,r=i>1&&i2(t,i-2)>65535?2:1;return t.slice(0,-r)}({localEdit:v.localEdit,fieldText:b+g});return h(i),B$(o,i),await t(e,i,s.current)?{kind:"handled"}:{kind:"suppress-raw"}}case"commit-held-then-send":return await BW(()=>r(e),()=>u.current(e,v.bytes))?{kind:"handled"}:{kind:"suppress-raw"};default:return{kind:"handled"}}},[e,t,i,r,n,s,o,a,l,c,d,u,h,f])}({activeHandle:e,applyLiveInputMirror:h,clearPendingLiveInputCommit:f,flushPendingLiveInputText:p,heldLiveInputTextRef:m,liveInputComposingRef:g,liveInputRef:s,liveInputTerminalHandles:o,onInteraction:u,pendingLiveInputHandleRef:b,sentLiveInputTextRef:v,sendLiveTerminalInputRef:l,setLiveInputCapture:c,waitForPendingLiveInputFlush:y});return{clearPendingLiveInputCommit:f,flushPendingLiveInputBeforeExternalSend:_,getLiveInputInteractionGeneration:S,handleLiveInputAccessoryBytes:T,handleLiveInputChange:w,handleLiveInputKeyPress:x,handleLiveInputSubmit:(0,BO.useCallback)(()=>e&&o.has(e)?(u(),BW(()=>p(e),()=>l.current(e,"\r"))):Promise.resolve(!1),[e,u,p,o,l])}}({activeHandle:p,activeHandleRef:q,activeSessionTabType:eu?.type,activeSessionTabTypeRef:U,connected:"connected"===a,liveInputRef:A,liveInputTerminalHandles:h,liveInputTerminalHandlesRef:f,sendLiveTerminalInputRef:D,setLiveInputCapture:u}),ey=function({connState:e,activeHandle:t,activeSessionTabType:i}){let r=null!=t&&"markdown"!==i&&"file"!==i&&"browser"!==i;return{canCompose:r,canSend:r&&"connected"===e}}({connState:a,activeHandle:p,activeSessionTabType:eu?.type}),e_=ey.canCompose,ew=ey.canSend&&null!==c,eS=!!p&&h.has(p),{focusLiveInput:ex,handleTerminalTap:eT,resetLiveInputFocus:ek}=function({activeHandleRef:e,canSend:t,inputRef:i,keyboardHeight:r,lifecycleIdentity:n,lifecycleKey:s,reopenFocusedInputWhenKeyboardHidden:o,liveInputEnabled:a,timerRef:l}){let c=(0,BF.useRef)({canSend:t,keyboardHeight:r,liveInputEnabled:a,reopenFocusedInputWhenKeyboardHidden:o});(0,BF.useLayoutEffect)(()=>{c.current={canSend:t,keyboardHeight:r,liveInputEnabled:a,reopenFocusedInputWhenKeyboardHidden:o}},[t,r,a,o]);let d=(0,BF.useCallback)(()=>{BA(l),i.current?.blur()},[i,l]);(0,BF.useLayoutEffect)(()=>d,[n,s,d]);let u=(0,BF.useCallback)(()=>{let e=c.current;e.canSend&&e.liveInputEnabled&&function(e,{keyboardHeight:t,refocus:i,reopenFocusedInputWhenKeyboardHidden:r}){if(e){if(r&&t<=0&&e.isFocused?.()){e.blur(),i();return}e.focus()}}(i.current,{keyboardHeight:e.keyboardHeight,reopenFocusedInputWhenKeyboardHidden:e.reopenFocusedInputWhenKeyboardHidden,refocus:()=>BP(l,u)})},[i,l]),h=(0,BF.useCallback)(t=>{let i=c.current;t===e.current&&i.canSend&&i.liveInputEnabled&&BP(l,()=>{e.current===t&&u()})},[e,u,l]);return{focusLiveInput:u,handleTerminalTap:h,resetLiveInputFocus:d}}({activeHandleRef:q,canSend:ew,inputRef:A,keyboardHeight:g,lifecycleIdentity:l,lifecycleKey:JSON.stringify([s,o,a]),liveInputEnabled:eS,reopenFocusedInputWhenKeyboardHidden:"android"===rs(),timerRef:E});return(0,Bj.useFocusEffect)((0,BQ.useCallback)(()=>ek,[ek])),{ptyModesRef:b,terminalGestureInputBucketsRef:v,terminalGestureInputQueuesRef:y,terminalGestureInputInFlightRef:_,terminalCwdRef:w,initialModesSeenRef:S,deviceTokenRef:x,hostEndpoint:T,setHostEndpoint:k,clientRef:C,connStateRef:L,viewportRef:M,viewportMeasuredRef:R,terminalRefs:I,liveInputRef:A,commandInputRef:P,liveInputFocusTimerRef:E,sendLiveTerminalInputRef:D,sessionTabActionSheetKeyboardHideSubRef:B,sessionTabActionSheetRequestSeqRef:Q,dictationRouteContextRef:j,terminalUnsubsRef:F,subscribingHandlesRef:O,leaseOnlyHandlesRef:W,initializedHandlesRef:H,terminalDiagnosticsRef:N,viewportResubscribeBudgetRef:z,webReadyHandlesRef:$,activeHandleRef:q,activeSessionTabTypeRef:U,pendingSelectionRef:Z,pendingBrowserFocusPageIdRef:G,switchSessionTabRef:Y,pendingTerminalActivationAttemptRef:X,handleCreateBrowserRef:J,initialSessionAutoCreateRef:er,markdownSaveSeqRef:en,markdownSaveInFlightRef:es,subscribeSeqRef:eo,delayedActionTimersRef:ea,layoutSeqRef:el,sendingRef:ec,terminalFrameRef:ed,activeSessionTab:eu,clearPendingLiveInputCommit:eh,flushPendingLiveInputBeforeExternalSend:ef,handleLiveInputAccessoryBytes:em,handleLiveInputChange:eg,handleLiveInputKeyPress:eb,handleLiveInputSubmit:ev,canCompose:e_,canSend:ew,liveInputEnabled:eS,focusLiveInput:ex,handleTerminalTap:eT,resetLiveInputFocus:ek,terminalInventoryRecoveryScope:ee,registerTerminalInventoryRecoveryAction:et,signalTerminalInventoryRecovery:ei,bufferedTerminalDraftState:K,reconcileBufferedDraftsRef:V,input:K.input,setInput:K.setInput,getLiveInteractionGeneration:ep}}(t)),function(e){let{client:t,connState:i,initialCreateWarning:r,sessionTabs:n,sessionTabsRef:s,activeSessionTabId:o,activeSessionTabIdRef:a,markdownDocs:l,markdownDocsRef:c,createWarningState:d,setCreateWarningState:u,setToastMessage:h,toastOpacityRef:f,toastHideTimerRef:p,toastSeqRef:m,clientRef:g,connStateRef:b,activeSessionTabTypeRef:v,delayedActionTimersRef:y,activeSessionTab:_}=e,[w,S]=(0,B7.useState)(null),[x,T]=(0,B7.useState)(null),[k,C]=(0,B7.useState)(null),[L,M]=(0,B7.useState)(null),[R,I]=(0,B7.useState)(null),A=(0,B7.useRef)(w);A.current=w,g.current=t,b.current=i,v.current=_?.type??null,s.current=n,a.current=o,c.current=l;let P=d.source===r?d:o$(r);P!==d&&u(P);let E=P.visible,D=(0,B7.useRef)(!0);(0,B7.useEffect)(()=>(D.current=!0,()=>{D.current=!1}),[]);let B=(0,B7.useCallback)(()=>{for(let e of y.current)clearTimeout(e);y.current.clear()},[]),Q=(0,B7.useCallback)((e,t)=>{let i=setTimeout(()=>{y.current.delete(i),e()},t);y.current.add(i)},[]),j=(0,B7.useCallback)(()=>{p.current&&(clearTimeout(p.current),p.current=null)},[]),F=(0,B7.useCallback)((e,t=1200)=>{if(!D.current)return;let i=m.current+1;m.current=i,j(),h(e),B8.Animated.timing(f.current,{toValue:1,duration:150,useNativeDriver:!0}).start(({finished:e})=>{e&&m.current===i&&(p.current=setTimeout(()=>{p.current=null,B8.Animated.timing(f.current,{toValue:0,duration:200,useNativeDriver:!0}).start(e=>{e.finished&&m.current===i&&h(null)})},t))})},[j]);return{browserScreencastSupported:w,setBrowserScreencastSupported:S,agentSessionHistorySupported:x,setAgentSessionHistorySupported:T,quickCommandsSupported:k,setQuickCommandsSupported:C,quickCommandAgentPromptMaxLength:L,setQuickCommandAgentPromptMaxLength:M,agentSessionHostSupport:R,setAgentSessionHostSupport:I,browserScreencastSupportedRef:A,reconciledCreateWarningState:P,createWarning:E,clearDelayedActionTimers:B,scheduleDelayedAction:Q,clearToastHideTimer:j,showToast:F}}(i)),function(e,t){let{hostId:i,worktreeId:r,client:n,connState:s,agentSessionHostSupport:o,setInput:a,liveInputTerminalHandles:l,activeHandle:c,activeSessionTabId:d,diffComments:u,diffCommentsRef:h,setShowDictationSetup:f,setDictationMode:p,deviceTokenRef:m,dictationRouteContextRef:g,activeHandleRef:b,activeSessionTab:v,flushPendingLiveInputBeforeExternalSend:y,canSend:_,liveInputEnabled:w,showToast:S,resetLiveInputFocus:x}=e,T=QT(i,r,d),k=function(e){let[t,i]=(0,O_.useState)(null);t&&t.scopeKey!==e.scopeKey&&i(null);let r=t?.scopeKey===e.scopeKey?t:null,n=(0,O_.useRef)(null),s=(0,O_.useRef)(!1),o=(0,O_.useRef)(e.showToast);o.current=e.showToast;let a=(0,O_.useRef)(e.scopeKey);a.current=e.scopeKey;let l=e.scopeKey,c=(0,O_.useCallback)(()=>{n.current&&(clearTimeout(n.current),n.current=null)},[]),d=(0,O_.useCallback)(()=>{a.current===l&&(c(),i(null))},[c,l]),u=(0,O_.useCallback)((e,t)=>{a.current===l&&s.current?(c(),i({scopeKey:l,message:e,...t}),n.current=setTimeout(()=>{n.current=null,i(null)},4e3)):o.current(e,1600)},[c,l]);return(0,O_.useEffect)(()=>{c()},[c,l]),(0,O_.useEffect)(()=>()=>{s.current=!1,c()},[c]),{message:r?.message??null,show:u,clear:d,keepWhile:e=>{let t=r?.refusedWhile;void 0!==t&&e?.[t]===!1&&i(null)},bannerMountedRef:s}}({scopeKey:T,showToast:S}),C=function(e,t){let i=tf(t),[r,n]=(0,Oy.useState)({client:null,worktreeId:"",readable:!1});return(0,Oy.useEffect)(()=>{if(i)return;let r=!0;return e?t.startsWith("folder:")?(iW.request(e).then(i=>{if(!r)return;let s=iW.interpret(i);n({client:e,worktreeId:t,readable:s.accepted&&function(e,t){if(!e||"object"!=typeof e||!("folderWorkspaces"in e)||!Array.isArray(e.folderWorkspaces))return!1;let i=t.slice(7),r=e.folderWorkspaces.find(e=>null!==e&&"object"==typeof e&&"id"in e&&e.id===i);if(!r||"object"!=typeof r)return!1;let n="connectionId"in r?r.connectionId:null;return null===n||"string"==typeof n&&Ag(n)}(s.value,t)})}).catch(()=>{r&&n({client:e,worktreeId:t,readable:!1})}),()=>{r=!1}):(ig.request(e).then(i=>{if(!r)return;let s=ig.interpret(i),o=s.accepted?s.value??[]:[],a=tx(t),l=o.find(e=>e.id===a);n({client:e,worktreeId:t,readable:!!l&&Ag(l.connectionId??null)})}).catch(()=>{r&&n({client:e,worktreeId:t,readable:!1})}),()=>{r=!1}):void n({client:e,worktreeId:t,readable:!1})},[e,i,t]),!!i||r.client===e&&r.worktreeId===t&&r.readable}(n,r),{ready:L,readyRef:M,lockReason:R,markReady:I,clear:A}=function(e){let[t,i]=(0,wh.useState)(new Set),r=(0,wh.useRef)(t),n=null!=e.activeHandle&&t.has(e.activeHandle),s=e.connected?n?null:"waiting":"disconnected",o=(0,wh.useRef)(n);o.current=n;let a=(0,wh.useCallback)(e=>{r.current=e,i(e)},[]);return(0,wh.useEffect)(()=>{!e.connected&&r.current.size>0&&a(new Set)},[e.connected,a]),{ready:n,readyRef:o,lockReason:s,markReady:(0,wh.useCallback)(e=>{r.current.has(e)||a(new Set(r.current).add(e))},[a]),clear:(0,wh.useCallback)(e=>{let t=r.current;if(void 0===e)return 0!==t.size&&(a(new Set),!0);if(!t.has(e))return!1;let i=new Set(t);return i.delete(e),a(i),!0},[a])}}({activeHandle:c,connected:"connected"===s}),P=function(e){var t;let i,r,n,{client:s,hostId:o,worktreeId:a,activeSessionTab:l,activeSessionTabId:c,activeHandleRef:d,deviceTokenRef:u,nativeChatInputLeaseReady:h,connState:f,agentSessionHostSupport:p=null,onSendError:m,onSendResolved:g}=e,{activeChatAgent:b,activeChatAgentRef:v,activeChatResolution:y,activeChatSessionId:_,activeChatStructured:w,activeTabAgentWorking:S,isTabChatView:x,setTabView:T,nativeChatStatus:k,showNativeChat:C,showNativeChatRef:L,sourceIdentity:M,streamIdentity:R,streamScopeKey:I,toggleTabChatView:A}=function(e){let{activeHandleRef:t,activeSessionTab:i,activeSessionTabId:r,hostId:n,nativeChatTranscriptIsLocalReadable:s,worktreeId:o}=e,{isTabChatView:a,setTabView:l,toggleTabChatView:c}=function(e){let{hostId:t,worktreeId:i}=e,[r,n]=(0,Oa.useState)(()=>({hostId:t,worktreeId:i,overrides:new Map,loaded:!1})),s=(0,Oa.useRef)(r);s.current=r;let o=(0,Oa.useRef)(null),a=(0,Oa.useRef)(!0);(0,Oa.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let l=(0,Oa.useCallback)((e,t)=>{let i=o.current;if(i?.hostId===e&&i.worktreeId===t)return i;let r={hostId:e,worktreeId:t,loadPromise:Op(e,t),currentOverrides:new Map,mutationRevisions:new Map};return o.current=r,r},[]),[c,d]=(0,Oa.useState)("terminal"),u=(0,Oa.useRef)(c);u.current=c,(0,Oa.useEffect)(()=>{let e=!0,r=l(t,i);return r.loadPromise.then(o=>{if(!e)return;let a=Ob(o.overrides,r.currentOverrides);r.currentOverrides=a;let l={hostId:t,worktreeId:i,overrides:a,loaded:o.loaded};s.current=l,n(l)}),()=>{e=!1}},[l,t,i]),(0,Ol.useFocusEffect)((0,Oa.useCallback)(()=>{let e=!0;return Oh().then(t=>{e&&d(t)}),()=>{e=!1}},[]));let h=(0,Oa.useCallback)(e=>!!Og(r,t,i)&&(r.overrides.get(e)??(r.loaded?c:"terminal"))==="chat",[c,t,r,i]),f=(0,Oa.useCallback)((e,r)=>{let c=s.current,d=Og(c,t,i)?c:{hostId:t,worktreeId:i,overrides:new Map,loaded:!1},u=new Map(d.overrides);u.set(e,r);let h={...d,overrides:u};s.current=h,n(h);let f=l(t,i);f.currentOverrides=u;let p=(f.mutationRevisions.get(e)??0)+1;f.mutationRevisions.set(e,p),Om(t,i,e,r).catch(async()=>{if(!a.current||o.current!==f)return;let r=await Op(t,i);if(!a.current||o.current!==f||f.mutationRevisions.get(e)!==p)return;let l=r.loaded?Ob(r.overrides,f.currentOverrides):new Map(f.currentOverrides),c=r.loaded?r.overrides.get(e):"terminal";c?l.set(e,c):l.delete(e),f.currentOverrides=l;let d=s.current;if(!Og(d,t,i))return;let u={...d,overrides:l,loaded:r.loaded};s.current=u,n(u)})},[l,t,i]),p=(0,Oa.useCallback)(e=>{let r=s.current,n=r.loaded?u.current:"terminal",o=Og(r,t,i)&&(r.overrides.get(e)??n)==="chat";f(e,o?"terminal":"chat")},[t,f,i]);return{isTabChatView:h,setTabView:f,toggleTabChatView:p}}({hostId:n,worktreeId:o}),d=i?.type==="agent-session"||!!r&&a(r),u=i&&r&&d?Ab(i,s):null,h=null!=u,f=(0,Oo.useRef)(h),p=u?.agent??null,m=(0,Oo.useRef)(p);(0,Oo.useLayoutEffect)(()=>{f.current=h,m.current=p},[p,h]);let g=u?.sessionId??null,b=null!=u&&i?.type==="agent-session",v=i?.agentStatus,y=v?.state==="working"&&"monitoring"!==v.workingMode&&!0!==v.restoredUnconfirmed,_=u&&!b?v:null,w=`${n}\0${o}\0${r??""}`,S=`${w}\0${g??""}\0${t.current??""}`,x=i?.agentStatus?.providerSession?.id??"",T=`${w}\0${g??x}\0${t.current??""}`;return{isTabChatView:a,setTabView:l,toggleTabChatView:c,showNativeChat:h,showNativeChatRef:f,activeChatAgent:p,activeChatAgentRef:m,activeChatSessionId:g,activeChatStructured:b,activeChatResolution:u,activeTabAgentWorking:y,nativeChatStatus:_,sourceIdentity:Q1([n,o]),streamIdentity:S,streamScopeKey:T}}(e),P=(0,Qu.useRef)(()=>!1),{structuredSession:E,session:D}=function({client:e,structured:t,agent:i,resolvedAgent:r,transcriptPath:n,sessionId:s,sourceIdentity:o,hostSupport:a,appendComposerTextRef:l,enabled:c,connState:d,onSendError:u,onActionResolved:h}){let f=(0,QX.useCallback)(e=>l.current(e),[l]),p=function(e){let t,{client:i,sourceIdentity:r,agent:n,sessionId:s,transcriptPath:o}=e,[a,l]=(0,QJ.useState)([]),c=Q1([r,n,s,o]),d=i&&n?s?"loading":"waiting-session":"idle",[u,h]=(0,QJ.useState)(null),f=u;null!==f&&(f.identity!==c||f.client!==i)&&(f=null,h(null));let p="loading"===d?f:null,m=p?p.status:d,[g,b]=(0,QJ.useState)(void 0),[v,y]=(0,QJ.useState)(!1),{phase:_,load:w,supersede:S}=Q6(),x=(0,QJ.useRef)(null),T=(0,QJ.useRef)(function(e=g2){return{list:[],indexById:new Map,priority:e}}()),k=(0,QJ.useRef)(40),C=(0,QJ.useRef)(s);C.current=s;let L=(0,QJ.useRef)(!1),M=(0,QJ.useRef)((t=null,{capture(e,i){t={identity:e,messages:i}},visible:({identity:e,messages:i,settled:r})=>r?i:t?.identity===e?t.messages:Q0})),R=p?.status==="ready";(0,QJ.useEffect)(()=>{R&&M.current.capture(c,a)},[c,a,R]);let I=(0,QJ.useCallback)(e=>{Q5(T.current,e),l(T.current.list)},[]);(0,QJ.useEffect)(()=>{var e;let t=!1;if(S(),k.current=40,L.current=!1,I([]),b(void 0),y(!1),x.current=null,!i||!n||!s)return;let r=i.subscribe("nativeChat.subscribe",{agent:n,sessionId:s,limit:k.current,subscriptionId:(e=iR())?`${n}:${s}:${e}`:`${n}:${s}`,capabilities:{transcriptPending:1},...o?{transcriptPath:o}:{}},e=>{if(t)return;let r=function(e){let{merger:t,frame:i,limit:r,replaceSnapshot:n}=e;if("error"===i.type)return{kind:"error",error:i.message??i.error??"Transcript stream failed"};if("end"===i.type)return{kind:"error",error:"Transcript stream ended"};if("snapshot"!==i.type&&"replacement"!==i.type&&"appended"!==i.type)return{kind:"ignored"};if(i.error)return{kind:"error",error:i.error};if(!Array.isArray(i.messages))return{kind:"ignored"};let s="snapshot"===i.type&&!0===i.pending,o="snapshot"===i.type&&!n&&t.list.length>0?function(e,t,i){let r=t[0]?e.indexById.get(t[0].id):void 0;if(void 0===r||!1===i&&r>0)return null;let n=r,s=!1;for(let i of t){let t=e.indexById.get(i.id);if(void 0===t)s=!0;else{if(s||t!==n)return null;n+=1}}return n===e.list.length?r:null}(t,i.messages,i.hasMore):null;if("replacement"===i.type||"snapshot"===i.type&&null===o)return Q5(t,i.messages),{kind:"messages",messages:t.list,hasMore:i.hasMore,windowReplaced:!0,...s?{pending:!0}:{},...null==i.beforeOffset?{}:{beforeOffset:i.beforeOffset}};let a=t.list[0]?.id,l=function(e,t,i){if(0===t.length)return e.list;let r=[...e.list];Q2(r,e.indexById,t,e.priority);let n=void 0===i?r:function(e,t){var i,r;if(t<=0||e.length<=t)return e;let n=e.length-t;for(;n>0&&(i=e[n-1],r=e[n],"number"==typeof i.transcriptOffset&&"number"==typeof r.transcriptOffset?i.transcriptOffset===r.transcriptOffset:"reasoning"===i.role&&"assistant"===r.role&&g3(i)===r.id);)n-=1;return e.slice(n)}(r,i);return n!==r?(Q5(e,n),e.list):(e.list=r,r)}(t,i.messages,r),c=!!(a&&l[0]?.id!==a),d="snapshot"===i.type&&0===o;return{kind:"messages",messages:l,...s?{pending:!0}:{},...c?{cursorInvalidated:!0}:{},..."snapshot"===i.type&&c?{hasMore:!0}:d?{...null==i.hasMore?{}:{hasMore:i.hasMore},...null==i.beforeOffset?{}:{beforeOffset:i.beforeOffset}}:{}}}({merger:T.current,frame:e,limit:2e3,replaceSnapshot:!L.current});if("ignored"!==r.kind){if("error"===r.kind){h({client:i,identity:c,status:"error"}),b(r.error);return}"snapshot"!==e.type||r.pending||(L.current=!0),(r.windowReplaced||"snapshot"===e.type&&null===x.current)&&S(),r.windowReplaced&&(k.current=40,x.current=r.beforeOffset??null,y(r.hasMore??r.messages.length>=40)),l(r.messages),r.windowReplaced||null==r.hasMore||y(r.hasMore),r.windowReplaced||null==r.beforeOffset||(x.current=r.beforeOffset),r.cursorInvalidated&&(S(),x.current=null),h({client:i,identity:c,status:r.pending?"awaiting-transcript":"ready"})}});return()=>{t=!0,S(),r()}},[i,n,s,o,c,I,S]);let A=(0,QJ.useCallback)(e=>{i&&n&&s&&v&&w(async({timeoutMs:t,isCurrent:r})=>{let a,l,c,d=(l=Math.min((a=Math.max(k.current,T.current.list.length))+60,2e3))>a?{nextLimit:l,pageLimit:l-a}:null;if(!d)return y(!1),"end";let{nextLimit:u,pageLimit:h}=d,f=x.current,p=await i_.request(i,{agent:n,sessionId:s,limit:null===f?u:h,...null===f?{}:{beforeOffset:f},...o?{transcriptPath:o}:{}},{timeoutMs:t,budgetSpansConnect:!0}),m=i_.interpret(p);if(!m.accepted)return"failed";let g=m.value;if(null===g||"object"!=typeof g||"error"in g)return"failed";let b=new Map(T.current.list.map(e=>[e.id,e]));if(e&&await e(),!r()||C.current!==s||x.current!==f)return"end";if(k.current=u,null!==f&&null!=g.beforeOffset)x.current=g.beforeOffset,I([...g.messages,...T.current.list]),c=u<2e3&&(g.hasMore??g.messages.length>=h);else{let e=T.current.list,t=e.findIndex(e=>e.id===g.messages.at(-1)?.id);I(function(e,t){if(0===t.length)return e;let i=[...e],r=new Map;return i.forEach((e,t)=>r.set(e.id,t)),Q2(i,r,t,g2),i}(-1===t?g.messages:[...g.messages,...e.slice(t+1)],e.filter(e=>b.get(e.id)!==e))),c=g.messages.length>=u}return y(c),c?"drew":"end"})},[i,n,s,o,v,I,w]);return{messages:M.current.visible({identity:c,messages:a,settled:R}),status:m,transcriptLoading:"loading"===m||"awaiting-transcript"===m,error:g,hasMore:v,loadingEarlier:"loading"===_,olderPages:_,loadEarlier:A}}({client:e,sourceIdentity:o,agent:t?null:r,sessionId:t?null:s,transcriptPath:t?null:n}),m=function(e){var t,i,r;let{agent:n,appendComposerText:s,client:o,connected:a,sessionId:l,sourceIdentity:c="",enabled:d,onActionResolved:u,onSendError:h,hostSupport:f}=e,p=f?.queuedMessages===!0,m=p&&f?.queuedCommands===!0,g=f?.promptCancel??null,b=f?.quietRepeatedStop??null,v=f?.conversationStop??null,y=Q1([c,n,l]),_=(0,Q4.useRef)(!1),w=(0,Q4.useRef)(new Map),{state:S,stateRef:x,queuedMessages:T,queuePause:k,olderPages:C,loadEarlier:L}=function(e){let{client:t,connected:i,enabled:r,sessionId:n,sessionKey:s}=e,[o,a]=(0,jx.useState)(()=>new Map),[l,c]=(0,jx.useState)(()=>new Map),d=r&&s?o.get(s)??jF:jF,u=(r&&s?l.get(s):void 0)??jK,h=u.messages,{phase:f,load:p,supersede:m}=Q6(),g=(0,jx.useRef)(d);(0,jx.useLayoutEffect)(()=>{g.current=d},[d]);let b=(0,jx.useCallback)(e=>{s&&a(t=>{let i=t.get(s)??jF,r=function(e,t,i=Date.now()){var r;let n;if("requests-marker"===t.type)return{...e,...ju(e,t.marker)};if("requests-complete"===t.type)return t.marker.version===e.requestMarker?.version?{...e,currentRequests:t.items,requestAuthority:t.marker}:e;if("loading"===t.type)return{...e,status:"loading",error:void 0,readRefusal:void 0};if("error"===t.type)return{...e,status:"error",error:t.message,readRefusal:t.refusal};if("history-page"===t.type)return{...jB(t.page,t.page.fence??null,e.backgroundTasks,e.activity),...jd(e),commands:e.commands,...jj(e,t.page),...jD(t.page.hostNow,i,e.hostClock)};if("older-page"===t.type){let r=t.requestedCursor;if(e.epoch!==r.epoch||t.page.epoch!==r.epoch)return e;let n=e.items[0];if(n&&n.sequence>r.sequence)return e;let s=jQ(e.items,t.page.items,t.page.removedItemIds);return{...e,items:s,retainedOwnItemLimit:Math.max(e.retainedOwnItemLimit,jL(s)),retainedItemCap:Math.max(e.retainedItemCap,s.length),subagentRoster:jA(e.subagentRoster,t.page),submissions:jM(e.submissions,t.page.submissions,s),hasOlder:_I(s,t.page.hasOlder),...jD(t.page.hostNow,i,e.hostClock)}}let s=t.event;if("end"===s.type)return e;if("snapshot"===s.type||"reset"===s.type){let t=jh(e,s,!0);return{...jB(s.page,s.fence,jE(s.backgroundTasks),s.activity),...t,status:"ready",commands:s.commands,...jj(s,s.page,e),...jD(s.hostNow,i,e.hostClock)}}if(e.epoch!==s.batch.cursor.epoch||e.cursor&&s.batch.cursor.sequencee.sequence>=n.sequence):r),d=jI(e.subagentRoster??jR,s.batch.items,s.batch.removedItemIds),u=0===c.length&&0===s.batch.removedItemIds.length&&0===s.batch.submissions.length;if(s.batch.cursor.sequence===e.cursor?.sequence&&u&&d===(e.subagentRoster??jR)&&(void 0===s.fence||s.fence===e.fence)&&(void 0===s.commands||s.commands===e.commands)&&(void 0===s.queuedMessages||s.queuedMessages===e.queuedMessages)&&(void 0===s.queuePause||s.queuePause===e.queuePause)&&(void 0===s.nextQueuedMessageId||s.nextQueuedMessageId===e.nextQueuedMessageId)&&jP(a,e.backgroundTasks)&&(void 0===s.latestTurn||JSON.stringify(s.latestTurn)===JSON.stringify(e.latestTurn))&&(void 0===s.actionablePromptIds||s.actionablePromptIds.join(` +`)}function FG(e,t){if(null===FZ(e)||new TextEncoder().encode(t).length>262144||!t.trim()&&!e.blocks.some(e=>"image-ref"===e.type))return null;if(t===FZ(e))return e;let i=[],r=!1;for(let n of e.blocks)"text"!==n.type?i.push(n):r||(i.push({type:"text",text:t}),r=!0);return r||i.unshift({type:"text",text:t}),{...e,blocks:i}}function FY(e,t){return e.current===t}sz({workspaceId:sj().min(1)}).strict(),FU.extend({observedCursor:Fj}),sz({}).strict(),s$({}),s$({agent:FW,sessionId:FB.optional(),worktree:FQ("Invalid worktree selector").optional(),waitForListing:sO().optional(),savedOnly:sO().optional()}),sz({envelope:FF,command:sZ(["clear","compact"]),delivery:sY("queue-if-active").optional()}).strict(),sz({envelope:FF,change:sV("kind",[sz({kind:sY("set"),objective:sj().max(4e3).refine(e=>e.trim().length>0,"Objective is empty")}).strict(),sz({kind:sY("status"),status:sZ(["active","paused"])}).strict(),sz({kind:sY("clear")}).strict()])}).strict(),sz({sessionId:FB,holderId:FQ("Invalid holder id")}).strict(),sz({sessionIds:sH(FB).max(512).optional()}).strict(),sz({sessionIds:sH(FB).max(512).optional()}).strict(),sz({sessionId:FB,direction:sZ(["tail","before","after"]),cursor:Fj.optional(),limit:sF().int().positive().max(200).optional()}).strict(),sz({sessionId:FB,cursor:Fj.optional()}).strict(),sz({includePrompts:sO().optional()}),sz({sessionId:FB,subscriptionId:FQ("Invalid subscription id").optional()}).strict(),sz({sessionId:FB}).strict(),sz({envelope:FF,itemId:FQ("Invalid item id",4096),expectedEpoch:FQ("Invalid journal epoch")}).strict();var FX=oa(os()),FJ=oa(os()),F0=[],F1={},F5=oa(os()),F2=oa(os());function F3(e,t){let i;if(!e)return null;try{i=JSON.parse(e)}catch{return null}if(!i||"object"!=typeof i)return null;let r=i.approval;if(!r||"object"!=typeof r)return null;let n=r.tool;if("string"!=typeof n||0===n.length)return null;let s=r.summary;return{title:`Allow ${n}?`,detail:"string"==typeof s&&s.length>0?s:void 0,options:[{label:"Allow",send:"opencode"===Am(t)?"\r":"1"},{label:"Deny",send:"\x1b"}]}}var F6=new Set(["blocked","waiting"]),F4=[/\bpermission\b/i,/\bapprove\b/i,/\bapproval\b/i,/\ballow\b/i,/\bdeny\b/i,/\bgrant\b/i,/\bauthorize\b/i,/\bdo you want to\b/i,/\bwould you like to\b/i,/\bproceed\?/i,/\bconfirm\b/i,/\(y\/n\)/i,/\by\/n\b/i,/\byes\/no\b/i,/\bplease confirm\b/i],F7=/(?:^|\n)\s*(\d+)[.)]\s*([^\n]+)/g;function F8(e,t=40){let i=e.replace(/\s+/g," ").trim();return i.length>t?`${i.slice(0,t-1)}…`:i}var F9=oa(os());function Oe(e,t){return(0,F9.useCallback)(async(...i)=>{let r=await e(...i);return r&&t(),r},[e,t])}var Ot=oa(os()),Oi=oa(os()),Or=oa(os()),On=oa(os()),Os=oa(os()),Oo=oa(os()),Oa=oa(os()),Ol=oa(oi()),Oc=new Map;function Od(e,t){return`orca:nativeChatTabs:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}async function Ou(){await null;try{let e=await sh.getItem("orca:defaultSessionView");return{value:"chat"===e||"terminal"===e?e:null,loaded:!0,hasStoredValue:null!==e}}catch{return{value:null,loaded:!1,hasStoredValue:!1}}}async function Oh(){let e=await Ou();return e.value??(e.loaded?"chat":"terminal")}async function Of(e){let t,i;try{t=await sh.getItem(e)}catch{return{overrides:new Map,loaded:!1}}if(!t)return{overrides:new Map,loaded:!0};try{i=JSON.parse(t)}catch{return{overrides:new Map,loaded:!0}}return Array.isArray(i)?{overrides:new Map(i.filter(e=>"string"==typeof e).map(e=>[e,"chat"])),loaded:!0}:i&&"object"==typeof i?{overrides:new Map(Object.entries(i).filter(e=>"terminal"===e[1]||"chat"===e[1])),loaded:!0}:{overrides:new Map,loaded:!0}}async function Op(e,t){let i=Od(e,t);return await Oc.get(i),Of(i)}async function Om(e,t,i,r){let n=Od(e,t),s=(Oc.get(n)??Promise.resolve()).then(async()=>{let e=await Of(n);if(!e.loaded)throw Error("Session view overrides could not be read");e.overrides.set(i,r);let t=JSON.stringify(Object.fromEntries(e.overrides));await tJ(n,t)}),o=s.catch(()=>{});Oc.set(n,o);try{await s}finally{Oc.get(n)===o&&Oc.delete(n)}}function Og(e,t,i){return e.hostId===t&&e.worktreeId===i}function Ob(e,t){let i=new Map(e);for(let[e,r]of t)i.set(e,r);return i}var Ov=oa(os()),Oy=oa(os()),O_=oa(os()),Ow=oa(os()),OS=oa(oi()),Ox=oa(os()),OT=oa(os());function Ok(e){return Array.isArray(e)&&e.every(e=>null!=e&&"object"==typeof e&&Number.isInteger(e.row)&&Number.isInteger(e.startCol)&&Number.isInteger(e.endCol)&&"string"==typeof e.uri)}var OC=sB-function(e="a".repeat(function(){let e=/\{(\d+)\}\$$/.exec(su.source);if(null===e)throw Error("the bridge id pattern is no longer a fixed length");return Number(e[1])}())){return JSON.stringify({v:sd,type:"event",id:e,seq:Number.MAX_SAFE_INTEGER,payload:0}).length}(),OL=oa(os()),OM=oa(os()),OR=oa(os());function OI(e,t){if(e===t)return!0;if(!e||!t||e.mode!==t.mode)return!1;let i=e.theme,r=t.theme;for(let e in i)if(Object.hasOwn(i,e)&&(!Object.hasOwn(r,e)||i[e]!==r[e]))return!1;for(let e in r)if(Object.hasOwn(r,e)&&!Object.hasOwn(i,e))return!1;return!0}function OA(e){return e.flatMap(e=>"terminal"!==e.type||"string"!=typeof e.terminal?[]:[{handle:e.terminal,title:e.title||"Terminal",terminalTheme:e.terminalTheme,isActive:!0===e.isActive,connected:!0}])}function OP(e,t){return e.length===t.length&&e.every((e,i)=>e.handle===t[i]?.handle&&e.title===t[i]?.title&&OI(e.terminalTheme,t[i]?.terminalTheme)&&e.isActive===t[i]?.isActive)}function OE(e){return!e.liveHandles.has(e.handle)&&!(e.showNativeChat&&e.handle===e.activeHandle)}var OD=class{activation=null;inFlight=null;activate(){let e=Symbol("terminal-inventory-activation");return this.activation=e,()=>{this.activation===e&&(this.activation=null)}}run(e,t,i){if(this.inFlight)return this.inFlight.allowEmptyLoaded||=e,i?.(this.inFlight.startedAt),this.inFlight.promise;let r=this.activation,n={allowEmptyLoaded:e,promise:Promise.resolve(!1),startedAt:Date.now()};i?.(n.startedAt);let s=Promise.resolve().then(()=>t(()=>n.allowEmptyLoaded,()=>null!==r&&this.activation===r));return n.promise=s.finally(()=>{this.inFlight===n&&(this.inFlight=null)}),this.inFlight=n,n.promise}};function OB(e,t,i=5){return{kind:"launched",lock:e,surface:{pane:null,sessionId:null,handle:null,...t},snapshotsLeft:i}}function OQ(e,t,i){return e?.kind!=="launched"||e.lock!==t?e:{...e,surface:{...e.surface,...i},snapshotsLeft:5}}function Oj(e,t){return e?.kind==="launched"&&e.lock===t&&null===e.snapshotsLeft?null:e}function OF(e){return e?.kind==="tab"||e?.kind==="terminal"?e.tabId:null}function OO(e){return e?.kind==="terminal"?e.handle:null}function OW(e){return e?.kind!=="terminal"?e:e.tabId?{kind:"tab",tabId:e.tabId}:null}function OH(e,t){return"agent-session"===e.type?null!==t.sessionId&&e.sessionId===t.sessionId:"terminal"===e.type&&(null!==t.pane&&e.parentTabId===t.pane.tabId&&e.leafId===t.pane.leafId||null!==t.handle&&e.terminal===t.handle)}var ON=oa(os());function Oz(e){return!e?.startsWith("mobile-local:")}function O$(e,t){e.creatingTerminalRef.current===t&&(e.creatingTerminalRef.current=null,e.setCreating(!1))}var Oq=oa(os()),OK=new Set([192,193,194,195,197,198,199,201,202,203,205,206,207]),OV=[137,80,78,71,13,10,26,10];function OU(e,t,i){return t>=0&&i>=0&&t+i<=e.byteLength}function OZ(e,t,i){if(!OU(e,t,i.length))return!1;for(let r=0;r>>0}function O0(e,t){return(e[t]<<24>>>0|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function O1(e,t){return Number.isSafeInteger(e)&&Number.isSafeInteger(t)&&e>0&&t>0?{width:e,height:t}:null}function O5(e){return OU(e,0,OV.length)&&OV.every((t,i)=>e[0+i]===t)&&OU(e,8,16)&&13===O0(e,8)&&OZ(e,12,"IHDR")?O1(O0(e,16),O0(e,20)):null}function O2(e,t){if(!OU(e,t,12))return null;let i=OJ(e,t);return 12===i?O1(OG(e,t+4),OG(e,t+6)):i<40||!OU(e,t,12)?null:O1(Math.abs(0|OJ(e,t+4)),Math.abs(0|OJ(e,t+8)))}var O3=new Set(["image/apng","image/bmp","image/gif","image/ico","image/jpeg","image/jpg","image/pjpeg","image/png","image/vnd.microsoft.icon","image/webp","image/x-bmp","image/x-icon","image/x-ms-bmp"]);function O6(e,t,i,r){let n=i[0],s=i[1],o=r>2?i[2]:-2,a=r>3?i[3]:-2;return r<2||void 0===n||void 0===s||n<0||s<0?null:-2===o?-2!==a?null:(t>4),{bytesWritten:Math.min(1,e.length-t),padded:!0}):void 0===o||o<0?null:(t>4),t+1>2),-2===a?{bytesWritten:Math.min(2,e.length-t),padded:!0}:void 0===a||a<0?null:(t+2=65&&i<=90?i-65:i>=97&&i<=122?i-71:i>=48&&i<=57?i+4:43===i?62:47===i?63:61===i?-2:-1;if(-1===l)return null;if(n[s]=l,4!==(s+=1))continue;let c=O6(r,o,n,4);if(!c)return null;o+=c.bytesWritten,a=c.padded,s=0}if(!a&&o0){for(let e=0;e=8388608,n=O5(t)??(OU(t,0,10)&&(OZ(t,0,"GIF87a")||OZ(t,0,"GIF89a"))?O1(OG(t,6),OG(t,8)):null)??function(e){if(!OU(e,0,4)||255!==e[0]||216!==e[1])return null;let t=2,i=e.byteLength;for(;t=208&&r<=216)continue;if(!OU(e,t,2))break;let n=OY(e,t);if(n<2||t+n>i)break;if(OK.has(r))return n>=7?O1(OY(e,t+5),OY(e,t+3)):null;t+=n}return null}(t)??function(e){if(!OU(e,0,20)||!OZ(e,0,"RIFF")||!OZ(e,8,"WEBP"))return null;let t=12;for(;OU(e,t,8);){let i=OJ(e,t+4),r=t+8,n=r+i;if(OZ(e,t,"VP8X")&&i>=10&&OU(e,r,10))return O1(OX(e,r+4)+1,OX(e,r+7)+1);if(OZ(e,t,"VP8L")&&i>=5&&OU(e,r,5)&&47===e[r]){let t=e[r+1],i=e[r+2],n=e[r+3];return O1(1+((63&i)<<8|t),1+((15&e[r+4])<<10|n<<2|(192&i)>>6))}if(OZ(e,t,"VP8 ")&&i>=10&&OU(e,r,10)&&157===e[r+3]&&1===e[r+4]&&42===e[r+5])return O1(16383&OG(e,r+6),16383&OG(e,r+8));if(n>e.byteLength)break;t=n+i%2}return null}(t)??(OZ(t,0,"BM")?O2(t,14):null)??function(e){if(!OU(e,0,6)||0!==OG(e,0)||1!==OG(e,2))return null;let t=OG(e,4);if(t<=0||t>1024||!OU(e,6,16*t))return null;let i=0,r=0;for(let n=0;n0&&n.height>0&&n.width<=32768&&n.height<=32768&&n.width<=Math.floor(0x2000000/n.height);if(e||i)return!e;r=8388608;continue}if(i)return!1;r=Math.min(16*r,8388608)}}(i,e)?null:`data:${e};base64,${i}`}var O7=sq({content:sj(),truncated:sO(),byteLength:sF()}),O8=sq({content:sj(),isImage:sW().optional(),mimeType:sj().optional()}),O9=sq({kind:sY("text"),originalContent:sj(),modifiedContent:sj()}),We=sq({kind:sj().refine(e=>"text"!==e,"not the text arm").transform(()=>"binary"),originalContent:sC("originalContent",sj()),modifiedContent:sC("modifiedContent",sj()),isImage:sC("isImage",sO()),modifiedDeleted:sC("modifiedDeleted",sO()),mimeType:sj().optional()}),Wt=rI(rM({name:"git.file-tab-diff",method:"git.diff",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rP([rA("file-tab-text-diff",O9),rA("file-tab-binary-diff",We)])})),Wi=rI(rM({name:"files.file-tab-text",method:"files.read",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rA("file-tab-text",O7)})),Wr=rI(rM({name:"files.file-tab-image",method:"files.readPreview",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rA("file-tab-image",O8)}));async function Wn(e,t){let i=`id:${t.worktreeId}`,{relativePath:r}=t;if("staged"===t.diffSource||"unstaged"===t.diffSource){let n=await Wt.request(e,{worktree:i,filePath:r,staged:"staged"===t.diffSource}),s=Wt.interpret(n);if("text"!==s.kind){let e=function(e){if(!0!==e.isImage)return null;let t=e.modifiedContent||"";return t?O4(e.mimeType,t):!0===e.modifiedDeleted?O4(e.mimeType,e.originalContent||""):null}(s);if(!e)throw Error("binary_file");return{status:"ready",kind:"image",dataUri:e}}let o=ti(s.originalContent,s.modifiedContent);return{status:"ready",kind:"diff",lines:o.lines,truncated:o.truncated}}let n=rc(t.worktreeId,r);if(n)return{status:"ready",kind:"media",media:n};let s=rl(r);if("image"===s){let t=await Wr.request(e,{worktree:i,relativePath:r}),n=Wr.interpret(t),s=n.isImage?O4(n.mimeType,n.content):null;if(!s)throw Error("binary_file");return{status:"ready",kind:"image",dataUri:s}}let o=await Wi.request(e,{worktree:i,relativePath:r}),a=Wi.interpret(o);return"html"===s?{status:"ready",kind:"html",content:a.content}:{status:"ready",kind:"file",content:a.content,truncated:a.truncated,byteLength:a.byteLength}}function Ws(e,t){let i=(e.get(t)??0)+1;return e.set(t,i),i}function Wo(e){return e?.status==="ready"&&!e.isDirty}function Wa(e){return e?.status==="ready"}function Wl(e,t,i,r){if(r(e.get(t)))return e;let n=new Map(e);return n.set(t,i),n}function Wc(e,t,i,r,n){let s=e.get(t);if(!s)return e;let o=n(s,i,r);if(!o||o===s)return e;let a=new Map(e);return a.set(t,o),a}function Wd(e,t,i){return"ready"===e.status?"ready"!==i.status||function(e,t){var i,r,n,s;if("ready"!==t.status||e.kind!==t.kind)return!1;switch(e.kind){case"file":return"file"===t.kind&&e.content===t.content&&e.truncated===t.truncated&&e.byteLength===t.byteLength;case"html":return"html"===t.kind&&e.content===t.content;case"image":return"image"===t.kind&&e.dataUri===t.dataUri;case"media":return"media"===t.kind&&(i=e.media,r=t.media,i.worktreeId===r.worktreeId&&i.relativePath===r.relativePath&&i.mimeType===r.mimeType);case"diff":return"diff"===t.kind&&e.truncated===t.truncated&&(n=e.lines,s=t.lines,n.length===s.length&&n.every((e,t)=>{let i=s[t];return e.kind===i?.kind&&e.text===i?.text&&e.oldLineNumber===i?.oldLineNumber&&e.newLineNumber===i?.newLineNumber}))}}(e,i)?void 0:i:e===t?i:void 0}function Wu(e,t){let i=e instanceof Error?e.message:"";return"binary_file"===i?"Binary preview unavailable":"file_too_large"===i?"File too large for mobile preview":t}var Wh=oa(os()),Wf=oa(os()),Wp=oa(oe()),Wm=oa(os()),Wg=oa(os()),Wb=oa(os()),Wv=oa(oe()),Wy=oa(oi()),W_=class{constructor(e){this.options=e,this.generation=this.readGeneration(),this.applicationRevision=this.readApplicationRevision()}options;inFlight=new Map;generation;barrier=0;subscriptionEpoch=0;requirementRevision=0;satisfiedRevision=0;applicationRevision=0;health="probing";snapshotSeen=!1;reconciliationActive=!1;disposed=!1;requestReconciliation(){return this.syncGeneration(),this.requirementRevision+=1,this.startCurrentRequest()}ensureReconciliation(){return this.syncGeneration(),this.requirementRevision<=this.satisfiedRevision&&(this.requirementRevision+=1),this.startCurrentRequest()}requestPendingRecovery(){return this.options.hasRecoveryNeed()?this.requestReconciliation():Promise.resolve()}retryReconciliation(){this.syncGeneration();let e=this.inFlight.get(`${this.generation}:${this.barrier}`);return e?.retry?e.promise:(this.requirementRevision+=1,this.barrier+=+!!e,this.startCurrentRequest(!0))}poll(){if(this.syncGeneration(),!this.reconciliationActive)return null;let e=this.options.hasRecoveryNeed();if("live"===this.health){if(!e&&this.requirementRevision<=this.satisfiedRevision)return null;let t=this.inFlight.get(`${this.generation}:${this.barrier}`);if(t)return t.promise;if(e&&this.options.allowRecoveryPoll?.()===!1)return null}return this.ensureReconciliation()}setReconciliationActive(e){this.reconciliationActive=e}beginSubscription(){this.syncGeneration();let e=++this.subscriptionEpoch;return this.invalidateStream("probing"),{listener:t=>{this.disposed||e!==this.subscriptionEpoch||this.handleStreamPayload(t)},cancel:()=>{e===this.subscriptionEpoch&&(this.subscriptionEpoch+=1,this.invalidateStream("degraded"))}}}isCertified(){return this.syncGeneration(),"live"===this.health}dispose(){this.disposed=!0,this.subscriptionEpoch+=1}handleStreamPayload(e){if(this.syncGeneration(),e&&"object"==typeof e){if("snapshot"===e.type){this.invalidateStream("probing"),this.snapshotSeen=!0,this.applyCurrent(e,"stream"),this.startCurrentRequest();return}if("updated"===e.type){let t=this.requirementRevision,i=this.generation;if(!this.applyCurrent(e,"stream").accepted||!this.isCurrentGeneration(i))return;this.health="live",this.satisfiedRevision=Math.max(this.satisfiedRevision,t),this.startTrailingRequest();return}("error"===e.type||"end"===e.type)&&(this.invalidateStream("degraded"),this.startCurrentRequest())}}applyCurrent(e,t){let i=this.generation,r=this.options.apply(e);return r.accepted&&this.isCurrentGeneration(i)?(this.applicationRevision=void 0===r.applicationRevision?this.applicationRevision+1:Math.max(this.applicationRevision,r.applicationRevision),this.options.consumeAccepted(e,r.effectiveTabs,t),r):{accepted:!1}}invalidateStream(e){this.barrier+=1,this.health=e,this.snapshotSeen=!1,this.requirementRevision+=1}startCurrentRequest(e=!1){if(this.disposed||!this.reconciliationActive)return Promise.resolve();let t=`${this.generation}:${this.barrier}`,i=this.inFlight.get(t);if(i)return i.promise;let r,n=new Promise(e=>{r=e}),s={promise:n,resolve:r,retry:e};return this.inFlight.set(t,s),this.runCohortRequest(t,s),n}runCohortRequest(e,t){let i={generation:this.generation,barrier:this.barrier,requirement:this.requirementRevision,applicationRevision:this.readApplicationRevision()},r=i=>{i&&this.inFlight.get(e)===t&&e===`${this.generation}:${this.barrier}`&&this.reconciliationActive&&this.requirementRevision>this.satisfiedRevision?this.runCohortRequest(e,t):(this.inFlight.get(e)===t&&this.inFlight.delete(e),t.resolve())};this.runRequest(i).then(r,()=>r(!1))}async runRequest(e){try{this.options.onFetchStarted?.();let t=await ib.request(this.options.client,{worktree:this.options.scope});if(!this.isCurrentGeneration(e.generation))return!1;if(!t.ok)return e.barrier===this.barrier&&this.options.onFetchFailed?.(t),!1;let i=ib.interpret(t);return e.barrier===this.barrier&&e.applicationRevision===this.readApplicationRevision()&&(this.options.onFetchSucceeded?.(i),!!this.applyCurrent(i,"list").accepted&&!!this.isCurrentGeneration(e.generation))&&(this.satisfiedRevision=Math.max(this.satisfiedRevision,e.requirement),this.snapshotSeen&&(this.health="live"),!0)}catch(t){return this.isCurrentGeneration(e.generation)&&e.barrier===this.barrier&&this.options.onFetchErrored?.(t),!1}}startTrailingRequest(){!this.disposed&&this.reconciliationActive&&this.requirementRevision>this.satisfiedRevision&&!this.inFlight.has(`${this.generation}:${this.barrier}`)&&this.startCurrentRequest()}syncGeneration(){if(this.disposed)return;let e=this.readGeneration();e!==this.generation&&(this.generation=e,this.invalidateStream("probing"))}isCurrentGeneration(e){return!this.disposed&&e===this.generation&&e===this.readGeneration()}readGeneration(){return this.options.client.getGeneration?.()??0}readApplicationRevision(){return Math.max(this.applicationRevision,this.options.getApplicationRevision?.()??0)}},Ww=class{contextKey=null;remaining=5;observeContext(e){e!==this.contextKey&&(this.contextKey=e,this.remaining=5)}take(e){return this.observeContext(e),null===e?{allowed:!1,parked:!1}:0===this.remaining?{allowed:!1,parked:!0}:(this.remaining-=1,{allowed:!0,parked:!1})}reset(){this.contextKey=null,this.remaining=5}},WS=class{activeTabId=null;contextKey=null;initialized=!1;tabs=null;read(e,t){return this.initialized&&e===this.tabs&&t===this.activeTabId||(this.initialized=!0,this.tabs=e,this.activeTabId=t,this.contextKey=function(e,t){if(null===t)return null;let i=e.find(e=>e.id===t);return i?.type!=="terminal"||"string"==typeof i.terminal?null:JSON.stringify([i.id,i.parentTabId,i.leafId??null])}(e,t)),this.contextKey}},Wx=Promise.resolve(),WT=oa(os()),Wk=oa(oe()),WC=oa(oi());function WL(e,t,i){return"ios"===i&&"active"===t&&("background"===e||"inactive"===e)}function WM({activeHandleRef:e,terminalRefs:t,initializedHandlesRef:i,connStateRef:r,unsubscribeTerminal:n,subscribeToTerminal:s,schedule:o,delayMs:a=120}){if("connected"!==r.current)return"deferred";let l=Array.from(i.current).filter(e=>t.current.has(e));if(0===l.length)return"skipped";let c=e.current,d=!!c&&t.current.has(c)&&i.current.has(c);for(let e of l)i.current.delete(e);return d&&c&&(n(c),o(()=>{"connected"===r.current&&e.current===c&&t.current.has(c)&&s(c)},a)),"recovered"}var WR=oa(os()),WI=oa(os()),WA=oa(oe());function WP(e,t){return"refit-committed"===t.type?e.keyboardVisible?{state:{...e,pending:!0},shouldRefit:!1}:{state:{...e,pending:!1},shouldRefit:!0}:"keyboard-visibility"===t.type?t.visible===e.keyboardVisible?{state:e,shouldRefit:!1}:t.visible?{state:{...e,keyboardVisible:!0},shouldRefit:!1}:{state:{...e,keyboardVisible:!1,pending:!1},shouldRefit:e.pending}:t.height===e.frameHeight?{state:e,shouldRefit:!1}:e.keyboardVisible?{state:{...e,frameHeight:t.height,pending:!0},shouldRefit:!1}:{state:{...e,frameHeight:t.height,pending:!1},shouldRefit:!0}}var WE=oa(os()),WD=oa(os()),WB=oa(oi()),WQ=oa(os()),Wj=oa(os()),WF=oa(os()),WO=oa(oe()),WW={failWhenDisconnected:!0};function WH(e){return{terminal:e.terminal,text:e.text,enter:e.enter,...e.deviceToken?{client:{id:e.deviceToken,type:"mobile"}}:{}}}async function WN(e){let t=function({targetHandle:e,activeHandle:t,activeSessionTabType:i}){return e!==t||"terminal"!==i?null:e}({targetHandle:e.targetHandle,activeHandle:e.activeHandle,activeSessionTabType:e.activeSessionTabType});return!!e.client&&!!t&&"connected"===e.connState&&eI.request(e.client,WH({terminal:t,text:e.bytes,enter:!1,deviceToken:e.deviceToken}),WW).then(i=>{let r=!0===eI.interpret(i);return r&&eE(e.client,t),r},()=>!1)}var Wz=oa(os());function W$(e,t){let i=(0,Wz.useRef)(t);(0,Wz.useEffect)(()=>{i.current=t});let r=(0,Wz.useRef)(null);return(0,Wz.useCallback)(t=>{e.current=t,r.current?.(),r.current=t?function(e,t){if(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLTextAreaElement))return()=>{};let i=e=>{e instanceof InputEvent&&("insertLineBreak"!==e.inputType&&"insertParagraph"!==e.inputType||(e.preventDefault(),t()))};return e.addEventListener("beforeinput",i),()=>e.removeEventListener("beforeinput",i)}(t,()=>i.current()):null},[e])}var Wq=oa(os()),WK=oa(os()),WV=oa(os());async function WU(e){let t=()=>{let t=e.getActivationState();return t.activated||t.activationSeq!==t.latestActivationSeq};if(t()||(await e.fetchSessionTabs(),t()))return!1;let i=function(e,t,i={}){let r=e.filter(e=>"browser"!==e.type&&"terminal"!==e.type&&e.relativePath===t);return 0===r.length?null:"diff"===i.preferMode?r.find(e=>"diff"===e.mode)??r[0]??null:r.find(e=>"diff"!==e.mode)??r[0]??null}(e.getTabs(),e.relativePath,{preferMode:"diff"});if(!i)return!1;let r=e.getActiveTabId();return r===i.id||r===e.activeTabIdAtTap&&(e.switchSessionTab(i),!0)}function WZ(e){let t="agent-session"===e.activeTabType?null!==e.sourceSessionTabId&&void 0!==e.sourceSessionTabId&&e.activeSessionTabId===e.sourceSessionTabId:"terminal"===e.activeTabType&&null!==e.sourceTerminalHandle&&e.activeTerminalHandle===e.sourceTerminalHandle;return!e.activated&&e.activationSeq===e.latestActivationSeq&&t}function WG(e){WX(e).catch(()=>{WY(e)})}function WY(e){e.onOpenFailed&&WZ(e.getActivationState(!1))&&e.onOpenFailed()}async function WX(e){let t,i,r=`id:${e.worktreeId}`,n=await iZ.request(e.client,{worktree:r,pathText:e.pathText,crossWorkspace:!0,...e.terminalHandle&&e.terminalHandle.trim().length>0?{terminal:e.terminalHandle}:{},...e.cwd&&e.cwd.trim().length>0?{cwd:e.cwd}:{},...e.nativeChatContext?{nativeChatContext:e.nativeChatContext}:{}},{timeoutMs:1e4}),s=iZ.interpret(n);if(!s.accepted)return void WY(e);let o=s.value;if(!o.exists||o.isDirectory)return void WY(e);if(!WZ(e.getActivationState(!1)))return;let a=o.worktree?.trim()||e.worktreeId,l=`id:${a}`,c=a===e.worktreeId?e.worktreeName:void 0;if(o.openTarget?.kind==="absolute-file"){e.triggerOpenFeedback(),e.pushPreviewRoute(rd({hostId:e.hostId,worktreeId:a,source:"terminalArtifact",absolutePath:o.openTarget.absolutePath,grantId:o.openTarget.grantId,pathText:e.pathText,...e.cwd&&e.cwd.trim().length>0?{cwd:e.cwd}:{},...e.terminalHandle&&e.terminalHandle.trim().length>0?{terminal:e.terminalHandle}:{},...e.nativeChatContext?{nativeChatTab:e.nativeChatContext.tabId,nativeChatSession:e.nativeChatContext.sessionId}:{},name:WJ(o.openTarget.absolutePath),...null!==e.line?{line:String(e.line)}:{},...null!==e.column?{column:String(e.column)}:{},...c?{worktreeName:c}:{}}));return}let d=o.openTarget?.kind==="worktree-file"?o.openTarget.relativePath:o.relativePath;if(!d)return void WY(e);e.triggerOpenFeedback();let u=()=>e.pushPreviewRoute(rd({hostId:e.hostId,worktreeId:a,source:"worktree",relativePath:d,name:WJ(d),...null!==e.line?{line:String(e.line)}:{},...null!==e.column?{column:String(e.column)}:{},...c?{worktreeName:c}:{}}));if(a!==e.worktreeId||null!==e.line||null!==e.column)return void u();if("html"===rl(d)&&o.openTarget?.kind==="worktree-file"&&"local"===o.openTarget.provider)return void e.openBrowser(ie(o.openTarget.absolutePath));let h=await iH.request(e.client,{worktree:l,relativePath:d},{timeoutMs:15e3});if(ej(h)){if(!WZ(e.getActivationState(!1)))return;u();return}let f=iH.interpret(h);f.accepted&&f.value.opened?(t=!1,i=async()=>{if(!WZ(e.getActivationState(t))||(await e.fetchSessionTabs(),!WZ(e.getActivationState(t))))return;let i=e.getSessionTabs().find(e=>e.relativePath===d);i&&(e.getActiveSessionTabId()!==i.id&&e.switchSessionTab(i),t=!0)},e.scheduleDelayedAction(()=>{i()},300),e.scheduleDelayedAction(()=>{i()},900),e.scheduleDelayedAction(()=>{i()},1800)):WY(e)}function WJ(e){return e.split(/[\\/]/).findLast(Boolean)}var W0=oa(os()),W1=oa(os()),W5=oa(oe()),W2=/^ */;function W3(e){let t=e.endsWith("\r"),i=t?e.slice(0,-1):e;return{indent:W2.exec(i)?.[0].length??0,text:i,terminator:t?"\r":""}}var W6=oa(os()),W4=oa(os()),W7=oa(oe()),W8=oa(os()),W9=oa(os()),He={"application/pdf":"pdf","application/json":"json","application/zip":"zip","application/xml":"xml","text/plain":"txt","text/markdown":"md","text/csv":"csv","text/html":"html","image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/heic":"heic"};async function*Ht(e,t){let i=[...t];try{for(;i.length>0;){let t=i[0],r=await it(e,t);i.shift(),await ii(e,t.handle),yield{base64:r}}}finally{await ir(e,i)}}async function Hi(e){try{return await e.pickMedia("files",!0)}catch(e){throw e instanceof is&&"native_media_too_large"===e.reason?new FC(null):e}}async function*Hr(e,t){let i=[...t];try{let t=0;for(;i.length>0;){let r=i[0];t+=1;let n=(e.canNameMedia?await e.nameMedia(r.handle):null)??function(e,t){let i=e.split(";")[0].trim().toLowerCase(),r=He[i],n=i.split("/")[1]??"",s=r??(/^[a-z0-9]{1,8}$/.test(n)?n:"");return s?`attachment-${t}.${s}`:`attachment-${t}`}(r.mime,t),s=await it(e,r);i.shift(),await ii(e,r.handle),yield{name:n,mime:r.mime,byteLength:r.byteLength,base64:s}}}finally{await ir(e,i)}}function Hn(){let e=io();return(0,W9.useMemo)(()=>({pickImage:async t=>{for await(let i of Ht(e,await e.pickMedia(t,!1)))return i;return null},pickImages:t=>({[Symbol.asyncIterator]:async function*(){yield*Ht(e,await e.pickMedia(t,!0))}}),pickFiles:()=>({[Symbol.asyncIterator]:async function*(){yield*Hr(e,await Hi(e))}})}),[e])}async function Hs(e,{client:t,agent:i,terminal:r,deviceToken:n,getConnectionId:s,pickImage:o,onUploadStart:a,beforeTerminalSend:l}){let c=await o(e);if(!c)return!1;a?.();let d=await s(),u=eT(eR(await eM(t,c.base64,{connectionId:d}),i),!0);if(l&&!await l(r))return!1;let h=await tl.request(t,{terminal:r,text:u,enter:!1,...n?{client:{id:n,type:"mobile"}}:{}});return!0===tl.interpret(h)}var Ho=oa(os());async function Ha(e,{client:t,getConnectionId:i,pickImages:r,onUploadStart:n,onImageUploaded:s}){let o=await r(e),a=[],l=null;for await(let e of o){0===a.length&&(n?.(),l=await i());let r={path:await eM(t,e.base64,{connectionId:l}),previewUri:e.uri??`data:image/png;base64,${e.base64}`};a.push(r),s?.(r)}return a}var Hl=[];function Hc(e,t,i){if(i.length>0)return{...e,[t]:i};let r={...e};return delete r[t],r}var Hd=oa(os()),Hu=[],Hh=oa(os()),Hf=sq({uploadId:sj()}),Hp=sq({path:sj(),name:sj(),byteLength:sF()}),Hm=rI(rM({name:"agent-session-attachment.upload-start",method:"agentSessionAttachment.uploadStart",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rA("agent-session-attachment-upload-slot",Hf)})),Hg=rI(rM({name:"agent-session-attachment.upload-append",method:"agentSessionAttachment.uploadAppend",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rA("agent-session-attachment-chunk-appended",sW())})),Hb=rI(rM({name:"agent-session-attachment.upload-commit",method:"agentSessionAttachment.uploadCommit",acceptance:"require-result-or-throw-message",barrier:"after-caller-barrier",read:rA("agent-session-attachment-stored",Hp)})),Hv=rI(rM({name:"agent-session-attachment.upload-abort-or-skip",method:"agentSessionAttachment.uploadAbort",acceptance:"success-result-or-skip",barrier:"after-caller-barrier",read:rA("agent-session-attachment-upload-aborted",sW())}));async function Hy(e,t){var i;let r,{uploadId:n}=Hm.interpret(await Hm.request(e,{sessionId:t.sessionId,name:t.name,byteLength:(r=(i=t.base64).endsWith("==")?2:+!!i.endsWith("="),i.length/4*3-r)}));try{for(let i of function*(e){let t=0;do yield{offset:t/4*3,contentBase64:e.slice(t,t+524288)},t+=524288;while(t{}),t}}var H_=[],Hw=oa(os()),HS=oa(os()),Hx=rI(rM({name:"agent-session.commands-or-skip",method:"agentSession.commands",acceptance:"success-result-or-skip",barrier:"after-caller-barrier",read:rA("agent-session-commands",sq({commands:sH(sq({name:sj(),kind:sZ(["command","skill"]),kindUnspecified:sY(!0).optional(),description:sj().optional(),argumentHint:sj().optional()})).optional()}))})),HT=[],Hk=oa(os()),HC=oa(os()),HL=/^data:image\/[a-z0-9.+-]+;base64,/i,HM="image/png",HR=async(e,t)=>{let i=e.replace(HL,""),r=new Image;r.src=`data:${HM};base64,${i}`,await r.decode();let n=document.createElement("canvas");n.width=t.width,n.height=t.height;let s=n.getContext("2d");if(null===s)throw Error("Failed to encode resized clipboard image");s.drawImage(r,0,0,n.width,n.height);let o=n.toDataURL(HM).replace(HL,"");if(0===o.length)throw Error("Failed to encode resized clipboard image");return{data:o,width:n.width,height:n.height}},HI=oa(os()),HA=new Set(["structured_agent_session_unsupported"]),HP=new Set(["method_not_found"]),HE=/(?:: |\n)[ \t]*$/;function HD(e,t){let i=e.trimEnd();if(!i.endsWith(t))return!1;let r=i.slice(0,-t.length);return""===r.trim()||HE.test(r)}function HB(e,t){let i=new Set,r=e;for(;!i.has(r);){if("string"==typeof r)return HD(r,t);if(!r||"object"!=typeof r)break;i.add(r);let e=r;if(e.code===t||e.error?.code===t||e.response?.error?.code===t||[e.message,e.error?.message,e.response?.error?.message].some(e=>"string"==typeof e&&HD(e,t)))return!0;r=e.cause}return!1}var HQ="selector_not_found",Hj=[50,150,300];function HF(e){return new Promise(t=>setTimeout(t,e))}function HO(e,t){return{kind:"unknown",message:(t instanceof Error?t.message.trim():"")||HW(e)}}function HW(e){return`The ${re[e]} chat result could not be confirmed.`}function HH(e,t,i){return"string"==typeof t&&(HA.has(t)||HP.has(t))?{kind:"failed",message:i||`Could not open ${re[e]} chat.`}:HO(e,Error(i))}async function HN(e,t,i){let r,n=`id:${t}`,s;for(let t=0;;t+=1){try{s=await i$.request(e,{worktree:n,agent:i})}catch(i){let e=Hj[t];if(void 0===e||!HB(i,HQ))return{kind:"unsupported"};await HF(e);continue}let r=Hj[t];if(void 0!==r&&HB(s,HQ)){await HF(r);continue}break}if(!s||"object"!=typeof s||"boolean"!=typeof s.ok||!s.ok)return{kind:"unsupported"};let o=s.result;if(!o||"object"!=typeof o||!0!==o.supported)return{kind:"unsupported",reason:o?.reason};let a=e8({sessionId:e7(i,iR),worktree:n,agent:i,randomUuid:iR});e9(a.envelope.sessionId,n);try{r=await iq.request(e,a,{timeoutMs:15e3,budgetSpansConnect:!0})}catch{try{r=await iq.request(e,a,{timeoutMs:15e3,budgetSpansConnect:!0})}catch(e){return HO(i,e)}}if(!r||"object"!=typeof r||"boolean"!=typeof r.ok)return HO(i,Error(HW(i)));if(!r.ok){let e=r.error;return e&&"object"==typeof e&&"string"==typeof e.code&&"string"==typeof e.message?HH(i,e.code,e.message):HO(i,Error(HW(i)))}let l=r.result;return l&&"object"==typeof l&&"boolean"==typeof l.ok?l.ok?l.value&&"string"==typeof l.value.sessionId&&l.value.sessionId.trim()?{kind:"created",sessionId:l.value.sessionId}:HO(i,Error(HW(i))):l.refusal&&"object"==typeof l.refusal&&"string"==typeof l.refusal.code&&"string"==typeof l.refusal.message?HH(i,l.refusal.code,l.refusal.message):HO(i,Error(HW(i))):HO(i,Error(HW(i)))}async function Hz(e){let{options:t,pendingSelectionRef:i,showToast:r}=e,n=t?.agentPrompt??t?.initialPrompt,s=tr(e.agent),o=e.hostCapabilities?.includes(tq)?function(e,t){let i=t?e.find(e=>e.id===t):void 0;if(i)return"terminal"===i.type?i.parentTabId:i.id}(e.getSessionTabs(),e.activeSessionTabId):void 0;i.current=OB(e.lock,s,null);let a=await tn({client:e.client,hostCapabilities:e.hostCapabilities,worktreeId:e.worktreeId,agent:e.agent,reservation:s,...o?{placement:{afterTabId:o}}:{},...n?.trim()?{prompt:{text:n,delivery:"submit"}}:{},...t?.agentPrompt?{launchSource:"quick_command"}:t?.initialPrompt?{launchSource:"diff_notes_send"}:{}});if("unsupported"===a.kind)return i.current=Oj(i.current,e.lock),!1;if("failed"===a.kind)return e.reportCreateFailure(a.message),!0;if("tab-closed"===a.kind)return i.current=Oj(i.current,e.lock),!0;if("unknown"===a.kind){var l;let i;return(l=e.getSessionTabs(),i={pane:null,sessionId:null,handle:null,...s},l.some(e=>OH(e,i)&&("terminal"!==e.type||null!==e.terminal)))?n?.trim()&&(sy(),r(t?.initialPrompt?"The agent started, but couldn't confirm the notes were sent.":"The agent started, but couldn't confirm the prompt was sent.",2400)):(e.setCreateError(a.message),sy(),r(a.message,1800)),!0}let{outcome:c,warning:d}=a.result;return i.current=OQ(i.current,e.lock,"structured"===c.kind?{sessionId:c.sessionId}:{handle:c.handle}),e.fetchSessionTabs(),!1===a.promptDelivered?(sy(),r(t?.initialPrompt?"The agent started, but the notes weren't sent.":eY,2400)):a.promptDelivered&&t?.initialPrompt?(sv(),r(t.successToast??"Notes sent"),t.onPromptSent?.()):d?.trim()&&r(d.trim(),2400),!0}var H$=oa(os()),Hq={"browser.back":ad,"browser.forward":au,"browser.reload":ah},HK=oa(os()),HV=[{mode:"others",label:"Close Other Tabs"},{mode:"left",label:"Close Tabs to the Left"}];function HU(e,t,i){return Math.max(0,(Math.max(e.cursorY,e.contentBottomRow)+1)*t+t-i)}var HZ=oa(os()),HG=oa(oo()),HY=oa(oo());function HX(){let e,t,i,r,n,s,a,l,c,d,h,f,p,m,g,b,v,y,_,w,S,x,T,C,L,R,P,D,Q=(function(e){let{hostId:t,worktreeId:i,created:r,isFloatingWorkspaceRoute:n,connState:s,client:o,setTerminals:a,terminalsRef:l,setSessionTabs:c,appliedSnapshotMarkerRef:d,closedTabTombstonesRef:h,setTerminalsLoaded:f,setActiveHandle:p,setActiveSessionTabId:m,setMarkdownDocs:g,setFileDocs:b,terminalGestureInputQueuesRef:v,terminalGestureInputInFlightRef:y,sessionTabActionSheetKeyboardHideSubRef:_,sessionTabActionSheetRequestSeqRef:w,initializedHandlesRef:S,terminalDiagnosticsRef:x,activeHandleRef:T,activeSessionTabTypeRef:k,pendingSelectionRef:C,selectedSessionTabIdRef:L,pendingBrowserFocusPageIdRef:M,pendingTerminalActivationAttemptRef:R,initialSessionAutoCreateRef:I,bufferedTerminalDraftState:A,clearPendingLiveInputCommit:P,clearDelayedActionTimers:E,showToast:D,clearTerminalCache:B,fetchTerminals:Q,ensureSessionTabs:j}=e;(0,WE.useEffect)(()=>{for(let e of(w.current+=1,_.current?.remove(),_.current=null,B(),T.current=null,k.current=null,C.current=null,L.current=null,M.current=null,R.current=null,I.current=BD(),x.current.resetRoute(),d.current={epoch:null,version:-1},h.current.clear(),A.resetDrafts(),v.current.values()))e.timer&&clearTimeout(e.timer);return v.current.clear(),y.current.clear(),p(null),a([]),l.current=[],c([]),m(null),P(),g(new Map),b(new Map),E(),()=>{w.current+=1,_.current?.remove(),A.clearPendingRestorations(),P(),E()}},[E,P,A.clearPendingRestorations,B,t,A.resetDrafts,i]),(0,WE.useEffect)(()=>{if("connected"!==s)return;0===S.current.size&&f(!1),S.current.clear();let e=!1,t=[];function a(i,r){e||t.push(setTimeout(i,r))}return(async()=>{let t=t=>{var i;let r=null===t?null:u.interpret(t);!e&&r?.accepted===!0&&(i=r.value)&&"object"==typeof i&&"sleepingAgentWake"in i&&"unsupported-headless"===i.sleepingAgentWake&&D("Open RuFlo on the host to wake sleeping agents.",3e3)};o&&"1"!==r&&!n&&u.request(o,{worktree:`id:${i}`,notifyClients:!1,navigation:"caller"}).then(t).catch(()=>null),e||(await j().catch(()=>null),!e&&(await Q({allowEmptyLoaded:!1}),e||(a(()=>{Q({allowEmptyLoaded:!1})},750),a(()=>{Q({allowEmptyLoaded:!0})},1500),o&&"1"===r&&!n&&a(()=>{T.current||(async()=>{t(await u.request(o,{worktree:`id:${i}`,notifyClients:!1,navigation:"caller"}).catch(()=>null)),e||(await Q({allowEmptyLoaded:!0}),a(()=>{Q({allowEmptyLoaded:!0})},750))})()},1800))))})(),()=>{for(let i of(e=!0,t))clearTimeout(i)}},[o,s,r,Q,j,n,D,i])}(b=Object.assign(g=Object.assign(m=Object.assign(p=Object.assign(f=Object.assign(h=Object.assign(d=Object.assign(c=Object.assign(l=Object.assign(a=Object.assign(s=Object.assign(n=Object.assign(r=Object.assign(i=Object.assign(t=Object.assign(e=function(){var e;let{hostId:t,worktreeId:i,name:r,created:n,warning:s}=(0,Bc.useLocalSearchParams)(),o=i.startsWith("folder:"),a=tf(i),l=rB(),c=(0,Bl.useSafeAreaInsets)(),{client:d,clientId:u,state:h}=rf(t),{hostCapabilities:f}=rg(),p=t4(t),m=t7(t),g=nd(),{name:b,resolution:v}=function({client:e,connState:t,routeName:i,worktreeId:r}){let n=tf(r),s=i?.trim()??"",[o,a]=(0,Bm.useState)(()=>({worktreeId:r,name:s})),[l,c]=(0,Bm.useState)(()=>({worktreeId:r,resolution:"unknown"})),d=(0,Bm.useRef)({worktreeId:r,count:0});return(0,Bm.useEffect)(()=>{a(e=>e.worktreeId===r&&e.name===s?e:{worktreeId:r,name:s})},[s,r]),(0,Bm.useEffect)(()=>{c(e=>e.worktreeId===r?e:{worktreeId:r,resolution:"unknown"})},[r]),(0,Bg.useFocusEffect)((0,Bm.useCallback)(()=>{if(n||!e||"connected"!==t)return;let i=!1,s=!1,o=!1,l=null,u=0,h=iF(r),f=()=>{null!==l&&(clearInterval(l),l=null)},p=async()=>{let t=++u;try{let n,l=await iS.request(e,{worktree:`id:${r}`});if(i||t!==u)return;let h=l.ok?"present":l.error.code===Bb?"missing":"runtime_error"!==l.error.code||!function(e){let t=e.trimEnd();if(!t.endsWith(Bb))return!1;let i=t.slice(0,-Bb.length);return""===i.trim()||Bv.test(i)}(l.error.message)?"unknown":"missing",p=d.current;d.current={worktreeId:r,count:"missing"===h?(p.worktreeId===r?p.count:0)+1:0};let m="missing"===h&&d.current.count<2?"unknown":h;c(e=>e.worktreeId===r&&e.resolution===m?e:{worktreeId:r,resolution:m});let g=iS.interpret(l);if(!g.accepted)return;let b=g.value,v=b&&(n=[b].find(e=>(e.worktreeId??e.id)===r))&&(n.displayName?.trim()||n.repo?.trim())||null;v&&a(e=>e.worktreeId===r&&e.name===v?e:{worktreeId:r,name:v}),o=!0,s&&f()}catch{}},m=()=>{i||null!==l||(l=setInterval(()=>{p()},3e3))},g=()=>{o=!1,m(),p()};m();let b=e.subscribe("runtime.clientEvents.subscribe",null,e=>{if(!i&&e&&"object"==typeof e){if("ready"===e.type){let e=s;s=!0,o&&f(),e&&g();return}if("end"===e.type||"error"===e.type){s=!1,m();return}("reposChanged"===e.type||"worktreesChanged"===e.type&&e.repoId===h)&&g()}});return p(),()=>{i=!0,f(),b()}},[e,t,r,n])),n?{name:th,resolution:"unknown"}:{name:o.worktreeId===r?o.name:s,resolution:l.worktreeId===r?l.resolution:"unknown"}}({client:d,connState:h,routeName:r,worktreeId:i});!function(e){let{hostId:t,worktreeId:i,resolution:r}=e,n=(0,By.useRef)(null),s=(0,By.useRef)(e.bounce);(0,By.useEffect)(()=>{s.current=e.bounce}),(0,By.useEffect)(()=>{!t||n.current===i||"missing"!==r||i.startsWith("folder:")||tf(i)||(n.current=i,s.current(t))},[t,i,r])}({hostId:t,worktreeId:i,resolution:v,bounce:e=>l.replace(k(e,"worktree-missing"))});let{isWideLayout:y}=iE(),[_,w]=(0,Ba.useState)(null),[S,x]=(0,Ba.useState)(0),T=!a&&(e={isWideLayout:y,availableWidth:S,dockWidth:N}).isWideLayout&&e.availableWidth>=e.dockWidth+(e.minMainWidth??360);(0,Ba.useEffect)(()=>{T||null===_||w(null)},[T,_]);let{isGithubRepo:C,repoLoaded:L}=function(e){let{client:t,connState:i,worktreeId:r,includeBranchIdentity:n=!0}=e,[s,o]=(0,Bd.useState)({branch:null,headSha:null,status:null,isGithubRepo:!1,repoLoaded:!1,loaded:!1}),a=null!==t&&"connected"===i;return(0,Bd.useEffect)(()=>{let e=!1;return a&&t?(o({branch:null,headSha:null,status:null,isGithubRepo:!1,repoLoaded:!1,loaded:!n}),Bu(t,r).then(t=>{e||o(e=>({...e,isGithubRepo:t.isGithubRepo,repoLoaded:!0}))}).catch(()=>{e||o(e=>({...e,isGithubRepo:!1,repoLoaded:!0}))}),n?(Bh(t,r).then(t=>{e||o(e=>({...e,...t,loaded:!0}))}).catch(()=>{e||o(e=>({...e,branch:null,headSha:null,status:null,loaded:!0}))}),()=>{e=!0}):()=>{e=!0}):void o({branch:null,headSha:null,status:null,isGithubRepo:!1,repoLoaded:!1,loaded:!n})},[a,t,r,n]),s}({client:a?null:d,connState:h,worktreeId:i,includeBranchIdentity:!1});(0,Ba.useEffect)(()=>{L&&!C&&"pr"===_&&w(null)},[_,L,C]);let M="string"==typeof s?s.trim():"";return{hostId:t,worktreeId:i,routeWorktreeName:r,created:n,createdWarning:s,isFolderWorkspaceRoute:o,isFloatingWorkspaceRoute:a,router:l,insets:c,client:d,clientId:u,connState:h,hostCapabilities:f,reconnectAttempts:p,lastConnectedAt:m,forceReconnectHost:g,worktreeName:b,worktreeResolution:v,isWideLayout:y,activePanel:_,setActivePanel:w,sessionContentRowWidth:S,setSessionContentRowWidth:x,canDockPanel:T,prIsGithubRepo:C,prRepoContextLoaded:L,initialCreateWarning:M}}(),function(e){let{worktreeId:t,hostId:i,initialCreateWarning:r}=e,[n,s]=(0,B_.useState)([]),o=(0,B_.useRef)([]),[a,l]=(0,B_.useState)([]),c=(0,B_.useRef)([]),d=(0,B_.useRef)({epoch:null,version:-1}),u=(0,B_.useRef)(0),h=(0,B_.useRef)(new Map),[f,p]=function(e){let[t,i]=(0,BE.useReducer)((t,i)=>i?e:null,null);return[t===e,i]}(t),[m,g]=(0,B_.useState)(""),[b,v]=(0,B_.useState)(1),[y,_]=(0,B_.useState)(!1),[w,S]=(0,B_.useState)("orca-browser"),[x,T]=(0,B_.useState)(""),{clearTerminalLiveInputDefault:k,defaultTerminalHandlesToLiveInput:C,liveInputTerminalHandles:L,liveInputTerminalHandlesRef:M,pruneTerminalHandlesFromLiveInput:R,toggleTerminalLiveInput:I}=function({hostId:e,worktreeId:t}){let[i,r]=(0,BM.useState)(()=>new Set),n=(0,BM.useRef)(new Set),s=(0,BM.useRef)(new Set),o=(0,BM.useRef)(new Set),a=(0,BM.useRef)(!1),l=(0,BM.useRef)(new Map),c=(0,BM.useRef)(new Set),d=(0,BM.useCallback)(e=>{var t;if(!a.current){for(let t of e)c.current.add(t);return}let i=(t=o.current,e.filter(e=>!t.has(e))),l=function(e,t,i){let r=null,n=null;for(let s of i)t.has(s)||(r??=new Set(e),n??=new Set(t),r.add(s),n.add(s));return r&&n?{enabledHandles:r,defaultedHandles:n,changed:!0}:{enabledHandles:e,defaultedHandles:t,changed:!1}}(n.current,s.current,i);if(!l.changed)return;let d=new Set(l.enabledHandles),u=new Set(l.defaultedHandles);n.current=d,s.current=u,r(d)},[]),u=(0,BM.useCallback)(()=>{B(e,t,o.current).catch(()=>{})},[e,t]),h=(0,BM.useCallback)(e=>{let t=function(e,t,i){let r=null,n=null;for(let t of e)i.has(t)||(r??=new Set(e)).delete(t);for(let e of t)i.has(e)||(n??=new Set(t)).delete(e);return r||n?{enabledHandles:r??e,defaultedHandles:n??t,changed:!0}:{enabledHandles:e,defaultedHandles:t,changed:!1}}(n.current,s.current,e),i=!1;for(let t of o.current)e.has(t)||(o.current.delete(t),a.current||l.current.set(t,!1),i=!0);if(i&&a.current&&u(),!t.changed)return;let c=new Set(t.enabledHandles),d=new Set(t.defaultedHandles);n.current=c,s.current=d,r(c)},[u]),f=(0,BM.useCallback)(e=>{let t=new Set([...n.current,...s.current]);t.delete(e),a.current||l.current.set(e,!1),o.current.delete(e)&&a.current&&u(),h(t)},[u,h]),p=(0,BM.useCallback)(e=>{let t=!n.current.has(e);return t?o.current.delete(e):o.current.add(e),a.current||l.current.set(e,!t),a.current&&u(),r(i=>{let r=new Set(i);return t?r.add(e):r.delete(e),n.current=r,r}),t},[u]);return(0,BM.useEffect)(()=>{n.current=new Set,s.current=new Set,o.current=new Set,a.current=!1,l.current=new Map,c.current=new Set,r(new Set);let i=!1;return E(e,t).then(e=>{if(i)return;let t=l.current,h=new Set(e.handles);for(let[e,i]of t)i?h.add(e):h.delete(e);o.current=h,a.current=!0,l.current=new Map,e.loaded&&t.size>0&&u();let f=function(e,t,i){let r=null,n=null;for(let t of e)i.has(t)&&(r??=new Set(e)).delete(t);for(let e of i)t.has(e)||(n??=new Set(t)).add(e);return r||n?{enabledHandles:r??e,defaultedHandles:n??t,changed:!0}:{enabledHandles:e,defaultedHandles:t,changed:!1}}(n.current,s.current,h),p=new Set(f.enabledHandles),m=new Set(f.defaultedHandles);n.current=p,s.current=m,r(p);let g=[...c.current];c.current.clear(),d(g)}),()=>{i=!0}},[d,e,u,t]),{clearTerminalLiveInputDefault:f,defaultTerminalHandlesToLiveInput:d,liveInputTerminalHandles:i,liveInputTerminalHandlesRef:n,pruneTerminalHandlesFromLiveInput:h,toggleTerminalLiveInput:p}}({hostId:i,worktreeId:t}),[A,P]=(0,B_.useState)(null),[D,Q]=(0,B_.useState)(0),[j,F]=(0,B_.useState)(null),O=(0,B_.useRef)(null),W=(0,B_.useRef)(null),H=(0,B_.useRef)(null),N=(0,B_.useRef)(0),z=(0,B_.useRef)(0),$=(0,B_.useRef)(0),q=(0,B_.useRef)(new Map),[K,V]=(0,B_.useState)(new Map),U=(0,B_.useRef)(new Map),[Z,G]=(0,B_.useState)(new Map),[Y,X]=(0,B_.useState)([]),J=(0,B_.useRef)([]),[ee,et]=(0,B_.useState)(!1),[ei,er]=(0,B_.useState)(null),[en,es]=(0,B_.useState)(!1),eo=(0,B_.useRef)(null),[ea,el]=(0,B_.useState)(!1),[ec,ed]=(0,B_.useState)(!1),[eu,eh]=(0,B_.useState)(""),[ef,ep]=(0,B_.useState)(()=>o$(r)),[em,eg]=(0,B_.useState)(!1),[eb,ev]=(0,B_.useState)(!1),[ey,e_]=(0,B_.useState)("idle"),[ew,eS]=(0,B_.useState)([]),[ex,eT]=(0,B_.useState)(!1),[ek,eC]=(0,B_.useState)(!1),eL=function(){let[e,t]=(0,BB.useState)(null),[i,r]=(0,BB.useState)(null),[n,s]=(0,BB.useState)(null),[o,a]=(0,BB.useState)(null),[l,c]=(0,BB.useState)(null);return{actionTarget:e,agentSessionActionTarget:l,browserActionTarget:o,fileActionTarget:n,markdownActionTarget:i,setActionTarget:t,setAgentSessionActionTarget:c,setBrowserActionTarget:a,setFileActionTarget:s,setMarkdownActionTarget:r}}(),[eM,eR]=(0,B_.useState)(null),[eI,eA]=(0,B_.useState)(null),[eP,eE]=(0,B_.useState)(null),[eD,eB]=(0,B_.useState)([]),[eQ,ej]=(0,B_.useState)(BC),[eF,eO]=(0,B_.useState)(!1),[eW,eH]=(0,B_.useState)(null),eN=(0,B_.useMemo)(()=>{let e;return Bk(eQ,new Set((e=new Map(D_.map(e=>[e.id,e]))).keys())).flatMap(t=>{let i=e.get(t);return i?[i]:[]})},[eQ]),[ez,e$]=(0,B_.useState)(0),[eq,eK]=(0,B_.useState)(new Map),[eV,eU]=(0,B_.useState)(new Map),[eZ,eG]=(0,B_.useState)(!1),[eY,eX]=(0,B_.useState)(!1),[eJ,e0]=(0,B_.useState)(!1),[e1,e5]=(0,B_.useState)("toggle"),[e2,e3]=(0,B_.useState)(null),e6=(0,B_.useRef)(new Bw.Animated.Value(0)),e4=(0,B_.useRef)(null),e7=(0,B_.useRef)(0);return{terminals:n,setTerminals:s,terminalsRef:o,sessionTabs:a,setSessionTabs:l,sessionTabsRef:c,appliedSnapshotMarkerRef:d,appliedSessionTabsRevisionRef:u,closedTabTombstonesRef:h,terminalsLoaded:f,setTerminalsLoaded:p,input:m,setInput:g,terminalTextScale:b,setTerminalTextScale:v,autocompleteEnabled:y,setAutocompleteEnabled:_,terminalLinkOpenMode:w,setTerminalLinkOpenMode:S,liveInputCapture:x,setLiveInputCapture:T,clearTerminalLiveInputDefault:k,defaultTerminalHandlesToLiveInput:C,liveInputTerminalHandles:L,liveInputTerminalHandlesRef:M,pruneTerminalHandlesFromLiveInput:R,toggleTerminalLiveInput:I,activeHandle:A,setActiveHandle:P,coveredStreamRevision:D,setCoveredStreamRevision:Q,activeSessionTabId:j,setActiveSessionTabId:F,activeSessionTabIdRef:O,selectedSessionTabIdRef:W,tabStripRef:H,tabStripOffsetRef:N,tabStripViewportWidthRef:z,tabStripContentWidthRef:$,tabLayoutsRef:q,markdownDocs:K,setMarkdownDocs:V,markdownDocsRef:U,fileDocs:Z,setFileDocs:G,diffComments:Y,setDiffComments:X,diffCommentsRef:J,diffCommentBusy:ee,setDiffCommentBusy:et,pendingDiffNotesDelivery:ei,setPendingDiffNotesDelivery:er,creating:en,setCreating:es,creatingTerminalRef:eo,creatingBrowser:ea,setCreatingBrowser:el,creatingMarkdown:ec,setCreatingMarkdown:ed,createError:eu,setCreateError:eh,createWarningState:ef,setCreateWarningState:ep,showCreateTabDrawer:em,setShowCreateTabDrawer:eg,showQuickCommands:eb,setShowQuickCommands:ev,createTabAgentLoadState:ey,setCreateTabAgentLoadState:e_,createTabAgentOptions:ew,setCreateTabAgentOptions:eS,showCreateBrowserModal:ex,setShowCreateBrowserModal:eT,showHeaderMoreActions:ek,setShowHeaderMoreActions:eC,...eL,discardMarkdownTarget:eM,setDiscardMarkdownTarget:eR,leaveDrafts:eI,setLeaveDrafts:eA,renameTarget:eP,setRenameTarget:eE,customKeys:eD,setCustomKeys:eB,visibleBuiltInIds:eQ,setVisibleBuiltInIds:ej,showCustomKeyModal:eF,setShowCustomKeyModal:eO,deleteKeyTarget:eW,setDeleteKeyTarget:eH,visibleBuiltInAccessoryKeys:eN,keyboardHeight:ez,setKeyboardHeight:e$,terminalModes:eq,setTerminalModes:eK,terminalKeyboardMetrics:eV,setTerminalKeyboardMetrics:eU,selectModeActive:eZ,setSelectModeActive:eG,canPaste:eY,setCanPaste:eX,showDictationSetup:eJ,setShowDictationSetup:e0,dictationMode:e1,setDictationMode:e5,toastMessage:e2,setToastMessage:e3,toastOpacityRef:e6,toastHideTimerRef:e4,toastSeqRef:e7}}(e)),function(e){let t,i,r,n,{hostId:s,worktreeId:o,connState:a,client:l,clientId:c,sessionTabs:d,setLiveInputCapture:u,liveInputTerminalHandles:h,liveInputTerminalHandlesRef:f,activeHandle:p,activeSessionTabId:m,keyboardHeight:g}=e,b=(0,BQ.useRef)(new Map),v=(0,BQ.useRef)(new Map),y=(0,BQ.useRef)(new Map),_=(0,BQ.useRef)(new Set),w=(0,BQ.useRef)(new Map),S=(0,BQ.useRef)(new Set),x=(0,BQ.useRef)(c);x.current=c;let[T,k]=(0,BQ.useState)(null),C=(0,BQ.useRef)(null),L=(0,BQ.useRef)(a),M=(0,BQ.useRef)(null),R=(0,BQ.useRef)(!1),I=(0,BQ.useRef)(new Map),A=(0,BQ.useRef)(null),P=(0,BQ.useRef)(null),E=(0,BQ.useRef)(null),D=(0,BQ.useRef)(async()=>!1),B=(0,BQ.useRef)(null),Q=(0,BQ.useRef)(0),j=(0,BQ.useRef)(null),F=(0,BQ.useRef)(new Map),O=(0,BQ.useRef)(new Set),W=(0,BQ.useRef)(new Set),H=(0,BQ.useRef)(new Set),N=(0,BQ.useRef)(new eF),z=(0,BQ.useRef)(new BX),$=(0,BQ.useRef)(new Set),q=(0,BQ.useRef)(null),K=function({activeHandle:e,activeHandleRef:t}){let[i,r]=(0,BJ.useState)({}),n=(0,BJ.useRef)(new Map),s=(0,BJ.useRef)(new Map),o=e?i[e]??"":"",a=(0,BJ.useCallback)(e=>{let i=t.current;i&&(n.current.delete(i),r(t=>B0(t,i,e)))},[t]),l=(0,BJ.useCallback)((e,t)=>{var i;let s,o=(i=n.current,s={handle:e},i.set(e,s),s);return r(t=>B0(t,e,"")),{draft:t,handle:e,token:o}},[]),c=(0,BJ.useCallback)(e=>{B1(n.current,e.handle,e.token)&&r(t=>{var i,r;return i=e.token.handle,r=e.draft,(t[i]??"").length>0?t:B0(t,i,r)})},[]),d=(0,BJ.useCallback)(e=>B1(n.current,e.handle,e.token),[]),u=(0,BJ.useCallback)(e=>{let t=new Set(e);for(let e of s.current.values())t.add(e);r(e=>B5(e,t)),B2(n.current,t)},[]),h=(0,BJ.useCallback)((e,t,{retainMissingSurfaces:i=!1}={})=>{let o=s.current;for(let t of e)if(!(t.type&&"terminal"!==t.type)&&"string"==typeof t.terminal){let e=B3(t);o.has(e)||o.set(e,t.terminal)}let a=new Set(i?o.values():[]),l=new Set(i?o.keys():[]),c=[];for(let e of t){if(e.type&&"terminal"!==e.type)continue;let t=B3(e);l.add(t);let i=o.get(t);"string"==typeof e.terminal?(a.add(e.terminal),i&&i!==e.terminal&&c.push({previousHandle:i,nextHandle:e.terminal}),o.set(t,e.terminal)):i&&a.add(i)}for(let e of o.keys())l.has(e)||o.delete(e);for(let{previousHandle:e,nextHandle:t}of c)!function(e,t,i){let r=e.get(t);!r||e.has(i)?e.delete(t):(e.delete(t),r.handle=i,e.set(i,r))}(n.current,e,t);B2(n.current,a),r(e=>{let t=e;for(let{previousHandle:e,nextHandle:i}of c)t=function(e,t,i){if(t===i||!Object.hasOwn(e,t))return e;let r={...e};return Object.hasOwn(e,i)||(r[i]=e[t]??""),delete r[t],r}(t,e,i);return B5(t,a)})},[]),f=(0,BJ.useCallback)(()=>{n.current.clear(),s.current.clear(),r(e=>0===Object.keys(e).length?e:{})},[]);return{beginBufferedTerminalDraftSend:l,clearPendingRestorations:(0,BJ.useCallback)(()=>{n.current.clear()},[]),input:o,pruneDrafts:u,reconcileTerminalTabs:h,resetDrafts:f,restoreRejectedDraft:c,setInput:a,settleBufferedTerminalDraftSend:d}}({activeHandle:p,activeHandleRef:q}),V=(0,BQ.useRef)(K.reconcileTerminalTabs),U=(0,BQ.useRef)(null),Z=(0,BQ.useRef)(null),G=(0,BQ.useRef)(null),Y=(0,BQ.useRef)(null),X=(0,BQ.useRef)(null),J=(0,BQ.useRef)(null),ee=JSON.stringify([s,o]),{registerTerminalInventoryRecoveryAction:et,signalTerminalInventoryRecovery:ei}=(t=(0,B6.useRef)(null),i=(0,B6.useRef)(null),r=(0,B6.useRef)(null),(0,B6.useEffect)(()=>(t.current=ee,()=>{t.current===ee&&(t.current=null)}),[ee]),n=(0,B6.useCallback)(()=>{let e=t.current;if(null!==e&&e!==ee)return;let n=i.current;n?.scope===ee?n.request():r.current=ee},[ee]),{registerTerminalInventoryRecoveryAction:(0,B6.useCallback)(e=>{let t={request:e,scope:ee};i.current=t;let n=r.current;return r.current=null,n===ee&&e(),()=>{i.current===t&&(i.current=null)}},[ee]),signalTerminalInventoryRecovery:n}),er=(0,BQ.useRef)(BD()),en=(0,BQ.useRef)(new Map),es=(0,BQ.useRef)(new Set),eo=(0,BQ.useRef)(new Map),ea=(0,BQ.useRef)(new Set),el=(0,BQ.useRef)(new Map),ec=(0,BQ.useRef)(!1),ed=(0,BQ.useRef)(null),eu=d.find(e=>e.id===m)??null,{clearPendingLiveInputCommit:eh,flushPendingLiveInputBeforeExternalSend:ef,getLiveInputInteractionGeneration:ep,handleLiveInputAccessoryBytes:em,handleLiveInputChange:eg,handleLiveInputKeyPress:eb,handleLiveInputSubmit:ev}=function({activeHandle:e,activeHandleRef:t,activeSessionTabType:i,activeSessionTabTypeRef:r,connected:n,liveInputRef:s,liveInputTerminalHandles:o,liveInputTerminalHandlesRef:a,sendLiveTerminalInputRef:l,setLiveInputCapture:c}){let d=(0,BO.useRef)(0),u=(0,BO.useCallback)(()=>{d.current+=1},[]),{applyLiveInputMirror:h,clearPendingLiveInputCommit:f,flushPendingLiveInputText:p,heldLiveInputTextRef:m,liveInputComposingRef:g,pendingLiveInputHandleRef:b,sentLiveInputTextRef:v,waitForPendingLiveInputFlush:y}=function({activeHandleRef:e,activeSessionTabTypeRef:t,liveInputRef:i,liveInputTerminalHandlesRef:r,sendLiveTerminalInputRef:n,setLiveInputCapture:s}){let o=(0,Bz.useRef)(null),a=(0,Bz.useRef)({current:null,activeRequests:[],generation:0,pendingBatches:[]}),l=(0,Bz.useRef)(""),c=(0,Bz.useRef)(void 0),d=(0,Bz.useRef)(""),u=(0,Bz.useRef)(null),h=(0,Bz.useRef)(async()=>!1),f=(0,Bz.useCallback)(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),p=(0,Bz.useCallback)(()=>{f(),Bq(a.current),l.current="",c.current=void 0,d.current="",u.current=null},[f]),m=(0,Bz.useCallback)(()=>{p(),s(""),B$(i,"")},[i,p,s]),g=(0,Bz.useCallback)(async()=>a.current.current??Promise.resolve(!0),[]),b=(0,Bz.useCallback)((e,t)=>n.current(e,t),[n]),v=(0,Bz.useCallback)(async(i,n,s,m)=>{var v,y;let _,w,S,x,T,k;if(i!==e.current||null!=t.current&&"terminal"!==t.current||!r.current.has(i))return p(),!1;let C=(v=d.current,y={commitHeld:s,composing:m},_=Array.from(n),S=function(e,t){let i=0;for(;i127;)r+=1;return Math.min(r,e.length-t)}(_,S,y.composing),k=Math.min(S,(T=_.slice(0,_.length-x)).length),{eraseCount:w.length-k,appendText:T.slice(k).join(""),nextSentText:T.join(""),heldText:_.slice(_.length-x).join("")});d.current=C.nextSentText,l.current=C.heldText,c.current=m,u.current=C.heldText.length>0||C.nextSentText.length>0?i:null,f(),C.heldText.length>0&&void 0===m&&(o.current=setTimeout(()=>{o.current=null;let e=d.current+l.current;h.current(i,e,!0)},300));let L="".repeat(C.eraseCount)+C.appendText;return 0===L.length?g():function(e,t,i,r){let n=()=>{},s=new Promise(e=>{n=e}),o=e.pendingBatches.at(-1);if(o?.handle===t&&o.sender===r?(o.payload+=i,o.requests.push({resolve:n})):e.pendingBatches.push({handle:t,payload:i,requests:[{resolve:n}],sender:r}),!e.current){let t=e.generation,i=BK(e,t).catch(()=>!1);e.current=i,i.then(()=>{e.current===i&&(e.current=null)})}return s}(a.current,i,L,b)},[e,t,f,r,p,b,g]);(0,Bz.useEffect)(()=>{h.current=v},[v]);let y=(0,Bz.useCallback)((e,t,i)=>v(e,t,!1,i),[v]),_=(0,Bz.useCallback)(async e=>{let t=u.current;if(!t)return g();if(null!==e&&t!==e)return m(),g();let i=l.current,r=i.length>0?await v(t,d.current+i,!0):await g();return m(),r},[m,v,g]);return(0,Bz.useEffect)(()=>()=>{o.current&&(clearTimeout(o.current),o.current=null),l.current="",c.current=void 0,d.current="",u.current=null,Bq(a.current)},[]),{applyLiveInputMirror:y,clearPendingLiveInputCommit:m,flushPendingLiveInputText:_,heldLiveInputTextRef:l,liveInputComposingRef:c,pendingLiveInputHandleRef:u,sentLiveInputTextRef:d,waitForPendingLiveInputFlush:g}}({activeHandleRef:t,activeSessionTabTypeRef:r,liveInputRef:s,liveInputTerminalHandlesRef:a,sendLiveTerminalInputRef:l,setLiveInputCapture:c});(0,BO.useEffect)(()=>{n||f()},[n,f]),(0,BO.useEffect)(()=>{let t=b.current;!t||e&&t===e&&(null==i||"terminal"===i)&&o.has(e)||f()},[e,i,f,o]);let _=(0,BO.useCallback)(async e=>{u();let t=b.current;return t&&t!==e?(f(),y()):t===e?p(e):y()},[u,f,p,y]),w=(0,BO.useCallback)(({nativeEvent:t})=>{e&&o.has(e)?(u(),c(t.text),h(e,BN(t.text),function(e){if(!globalThis.navigator?.userAgent?.includes("Android"))return e}(t.isComposing))):f()},[e,u,h,f,o,c]),S=(0,BO.useCallback)(()=>d.current,[]),x=(0,BO.useCallback)(t=>{if(!e||!o.has(e))return;u();let i=b.current===e;b.current&&!i&&f();let r=function({key:e,heldText:t,sentText:i}){let r,n=(r=BI.get(e))?Dw({key:r,modifiers:[]})?.bytes??null:null;return null===n?{kind:"ignore"}:("Backspace"===e||"Delete"===e)&&(t.length>0||i.length>0)?{kind:"local-edit"}:t.length>0?{kind:"commit-held-then-send",bytes:n}:{kind:"send-now",bytes:n}}({key:t.nativeEvent.key,heldText:i?m.current:"",sentText:i?v.current:""});switch(r.kind){case"ignore":case"local-edit":return;case"send-now":BW(y,()=>l.current(e,r.bytes));return;case"commit-held-then-send":BW(()=>p(e),()=>l.current(e,r.bytes));return}},[e,u,f,p,o,l,y]),T=function({activeHandle:e,applyLiveInputMirror:t,clearPendingLiveInputCommit:i,flushPendingLiveInputText:r,heldLiveInputTextRef:n,liveInputComposingRef:s,liveInputRef:o,liveInputTerminalHandles:a,onInteraction:l,pendingLiveInputHandleRef:c,sentLiveInputTextRef:d,sendLiveTerminalInputRef:u,setLiveInputCapture:h,waitForPendingLiveInputFlush:f}){return(0,BV.useCallback)(async p=>{if(!e)return{kind:"allow-raw"};if(!a.has(e))return BU(f);l();let m=c.current===e;c.current&&!m&&i();let g=m?n.current:"",b=m?d.current:"",v=function({bytes:e,localEdit:t,heldText:i,sentText:r}){return t&&(i.length>0||r.length>0)?{kind:"local-edit",localEdit:t}:i.length>0?{kind:"commit-held-then-send",bytes:e}:{kind:"send-now",bytes:e}}({...p,heldText:g,sentText:b});switch(v.kind){case"send-now":return(p.bytes.endsWith("\r")?await r(e):await f())?{kind:"allow-raw"}:{kind:"suppress-raw"};case"local-edit":{let i=function({localEdit:e,fieldText:t}){if("delete"===e)return t;let i=t.length,r=i>1&&i2(t,i-2)>65535?2:1;return t.slice(0,-r)}({localEdit:v.localEdit,fieldText:b+g});return h(i),B$(o,i),await t(e,i,s.current)?{kind:"handled"}:{kind:"suppress-raw"}}case"commit-held-then-send":return await BW(()=>r(e),()=>u.current(e,v.bytes))?{kind:"handled"}:{kind:"suppress-raw"};default:return{kind:"handled"}}},[e,t,i,r,n,s,o,a,l,c,d,u,h,f])}({activeHandle:e,applyLiveInputMirror:h,clearPendingLiveInputCommit:f,flushPendingLiveInputText:p,heldLiveInputTextRef:m,liveInputComposingRef:g,liveInputRef:s,liveInputTerminalHandles:o,onInteraction:u,pendingLiveInputHandleRef:b,sentLiveInputTextRef:v,sendLiveTerminalInputRef:l,setLiveInputCapture:c,waitForPendingLiveInputFlush:y});return{clearPendingLiveInputCommit:f,flushPendingLiveInputBeforeExternalSend:_,getLiveInputInteractionGeneration:S,handleLiveInputAccessoryBytes:T,handleLiveInputChange:w,handleLiveInputKeyPress:x,handleLiveInputSubmit:(0,BO.useCallback)(()=>e&&o.has(e)?(u(),BW(()=>p(e),()=>l.current(e,"\r"))):Promise.resolve(!1),[e,u,p,o,l])}}({activeHandle:p,activeHandleRef:q,activeSessionTabType:eu?.type,activeSessionTabTypeRef:U,connected:"connected"===a,liveInputRef:A,liveInputTerminalHandles:h,liveInputTerminalHandlesRef:f,sendLiveTerminalInputRef:D,setLiveInputCapture:u}),ey=function({connState:e,activeHandle:t,activeSessionTabType:i}){let r=null!=t&&"markdown"!==i&&"file"!==i&&"browser"!==i;return{canCompose:r,canSend:r&&"connected"===e}}({connState:a,activeHandle:p,activeSessionTabType:eu?.type}),e_=ey.canCompose,ew=ey.canSend&&null!==c,eS=!!p&&h.has(p),{focusLiveInput:ex,handleTerminalTap:eT,resetLiveInputFocus:ek}=function({activeHandleRef:e,canSend:t,inputRef:i,keyboardHeight:r,lifecycleIdentity:n,lifecycleKey:s,reopenFocusedInputWhenKeyboardHidden:o,liveInputEnabled:a,timerRef:l}){let c=(0,BF.useRef)({canSend:t,keyboardHeight:r,liveInputEnabled:a,reopenFocusedInputWhenKeyboardHidden:o});(0,BF.useLayoutEffect)(()=>{c.current={canSend:t,keyboardHeight:r,liveInputEnabled:a,reopenFocusedInputWhenKeyboardHidden:o}},[t,r,a,o]);let d=(0,BF.useCallback)(()=>{BA(l),i.current?.blur()},[i,l]);(0,BF.useLayoutEffect)(()=>d,[n,s,d]);let u=(0,BF.useCallback)(()=>{let e=c.current;e.canSend&&e.liveInputEnabled&&function(e,{keyboardHeight:t,refocus:i,reopenFocusedInputWhenKeyboardHidden:r}){if(e){if(r&&t<=0&&e.isFocused?.()){e.blur(),i();return}e.focus()}}(i.current,{keyboardHeight:e.keyboardHeight,reopenFocusedInputWhenKeyboardHidden:e.reopenFocusedInputWhenKeyboardHidden,refocus:()=>BP(l,u)})},[i,l]),h=(0,BF.useCallback)(t=>{let i=c.current;t===e.current&&i.canSend&&i.liveInputEnabled&&BP(l,()=>{e.current===t&&u()})},[e,u,l]);return{focusLiveInput:u,handleTerminalTap:h,resetLiveInputFocus:d}}({activeHandleRef:q,canSend:ew,inputRef:A,keyboardHeight:g,lifecycleIdentity:l,lifecycleKey:JSON.stringify([s,o,a]),liveInputEnabled:eS,reopenFocusedInputWhenKeyboardHidden:"android"===rs(),timerRef:E});return(0,Bj.useFocusEffect)((0,BQ.useCallback)(()=>ek,[ek])),{ptyModesRef:b,terminalGestureInputBucketsRef:v,terminalGestureInputQueuesRef:y,terminalGestureInputInFlightRef:_,terminalCwdRef:w,initialModesSeenRef:S,deviceTokenRef:x,hostEndpoint:T,setHostEndpoint:k,clientRef:C,connStateRef:L,viewportRef:M,viewportMeasuredRef:R,terminalRefs:I,liveInputRef:A,commandInputRef:P,liveInputFocusTimerRef:E,sendLiveTerminalInputRef:D,sessionTabActionSheetKeyboardHideSubRef:B,sessionTabActionSheetRequestSeqRef:Q,dictationRouteContextRef:j,terminalUnsubsRef:F,subscribingHandlesRef:O,leaseOnlyHandlesRef:W,initializedHandlesRef:H,terminalDiagnosticsRef:N,viewportResubscribeBudgetRef:z,webReadyHandlesRef:$,activeHandleRef:q,activeSessionTabTypeRef:U,pendingSelectionRef:Z,pendingBrowserFocusPageIdRef:G,switchSessionTabRef:Y,pendingTerminalActivationAttemptRef:X,handleCreateBrowserRef:J,initialSessionAutoCreateRef:er,markdownSaveSeqRef:en,markdownSaveInFlightRef:es,subscribeSeqRef:eo,delayedActionTimersRef:ea,layoutSeqRef:el,sendingRef:ec,terminalFrameRef:ed,activeSessionTab:eu,clearPendingLiveInputCommit:eh,flushPendingLiveInputBeforeExternalSend:ef,handleLiveInputAccessoryBytes:em,handleLiveInputChange:eg,handleLiveInputKeyPress:eb,handleLiveInputSubmit:ev,canCompose:e_,canSend:ew,liveInputEnabled:eS,focusLiveInput:ex,handleTerminalTap:eT,resetLiveInputFocus:ek,terminalInventoryRecoveryScope:ee,registerTerminalInventoryRecoveryAction:et,signalTerminalInventoryRecovery:ei,bufferedTerminalDraftState:K,reconcileBufferedDraftsRef:V,input:K.input,setInput:K.setInput,getLiveInteractionGeneration:ep}}(t)),function(e){let{client:t,connState:i,initialCreateWarning:r,sessionTabs:n,sessionTabsRef:s,activeSessionTabId:o,activeSessionTabIdRef:a,markdownDocs:l,markdownDocsRef:c,createWarningState:d,setCreateWarningState:u,setToastMessage:h,toastOpacityRef:f,toastHideTimerRef:p,toastSeqRef:m,clientRef:g,connStateRef:b,activeSessionTabTypeRef:v,delayedActionTimersRef:y,activeSessionTab:_}=e,[w,S]=(0,B7.useState)(null),[x,T]=(0,B7.useState)(null),[k,C]=(0,B7.useState)(null),[L,M]=(0,B7.useState)(null),[R,I]=(0,B7.useState)(null),A=(0,B7.useRef)(w);A.current=w,g.current=t,b.current=i,v.current=_?.type??null,s.current=n,a.current=o,c.current=l;let P=d.source===r?d:o$(r);P!==d&&u(P);let E=P.visible,D=(0,B7.useRef)(!0);(0,B7.useEffect)(()=>(D.current=!0,()=>{D.current=!1}),[]);let B=(0,B7.useCallback)(()=>{for(let e of y.current)clearTimeout(e);y.current.clear()},[]),Q=(0,B7.useCallback)((e,t)=>{let i=setTimeout(()=>{y.current.delete(i),e()},t);y.current.add(i)},[]),j=(0,B7.useCallback)(()=>{p.current&&(clearTimeout(p.current),p.current=null)},[]),F=(0,B7.useCallback)((e,t=1200)=>{if(!D.current)return;let i=m.current+1;m.current=i,j(),h(e),B8.Animated.timing(f.current,{toValue:1,duration:150,useNativeDriver:!0}).start(({finished:e})=>{e&&m.current===i&&(p.current=setTimeout(()=>{p.current=null,B8.Animated.timing(f.current,{toValue:0,duration:200,useNativeDriver:!0}).start(e=>{e.finished&&m.current===i&&h(null)})},t))})},[j]);return{browserScreencastSupported:w,setBrowserScreencastSupported:S,agentSessionHistorySupported:x,setAgentSessionHistorySupported:T,quickCommandsSupported:k,setQuickCommandsSupported:C,quickCommandAgentPromptMaxLength:L,setQuickCommandAgentPromptMaxLength:M,agentSessionHostSupport:R,setAgentSessionHostSupport:I,browserScreencastSupportedRef:A,reconciledCreateWarningState:P,createWarning:E,clearDelayedActionTimers:B,scheduleDelayedAction:Q,clearToastHideTimer:j,showToast:F}}(i)),function(e,t){let{hostId:i,worktreeId:r,client:n,connState:s,agentSessionHostSupport:o,setInput:a,liveInputTerminalHandles:l,activeHandle:c,activeSessionTabId:d,diffComments:u,diffCommentsRef:h,setShowDictationSetup:f,setDictationMode:p,deviceTokenRef:m,dictationRouteContextRef:g,activeHandleRef:b,activeSessionTab:v,flushPendingLiveInputBeforeExternalSend:y,canSend:_,liveInputEnabled:w,showToast:S,resetLiveInputFocus:x}=e,T=QT(i,r,d),k=function(e){let[t,i]=(0,O_.useState)(null);t&&t.scopeKey!==e.scopeKey&&i(null);let r=t?.scopeKey===e.scopeKey?t:null,n=(0,O_.useRef)(null),s=(0,O_.useRef)(!1),o=(0,O_.useRef)(e.showToast);o.current=e.showToast;let a=(0,O_.useRef)(e.scopeKey);a.current=e.scopeKey;let l=e.scopeKey,c=(0,O_.useCallback)(()=>{n.current&&(clearTimeout(n.current),n.current=null)},[]),d=(0,O_.useCallback)(()=>{a.current===l&&(c(),i(null))},[c,l]),u=(0,O_.useCallback)((e,t)=>{a.current===l&&s.current?(c(),i({scopeKey:l,message:e,...t}),n.current=setTimeout(()=>{n.current=null,i(null)},4e3)):o.current(e,1600)},[c,l]);return(0,O_.useEffect)(()=>{c()},[c,l]),(0,O_.useEffect)(()=>()=>{s.current=!1,c()},[c]),{message:r?.message??null,show:u,clear:d,keepWhile:e=>{let t=r?.refusedWhile;void 0!==t&&e?.[t]===!1&&i(null)},bannerMountedRef:s}}({scopeKey:T,showToast:S}),C=function(e,t){let i=tf(t),[r,n]=(0,Oy.useState)({client:null,worktreeId:"",readable:!1});return(0,Oy.useEffect)(()=>{if(i)return;let r=!0;return e?t.startsWith("folder:")?(iW.request(e).then(i=>{if(!r)return;let s=iW.interpret(i);n({client:e,worktreeId:t,readable:s.accepted&&function(e,t){if(!e||"object"!=typeof e||!("folderWorkspaces"in e)||!Array.isArray(e.folderWorkspaces))return!1;let i=t.slice(7),r=e.folderWorkspaces.find(e=>null!==e&&"object"==typeof e&&"id"in e&&e.id===i);if(!r||"object"!=typeof r)return!1;let n="connectionId"in r?r.connectionId:null;return null===n||"string"==typeof n&&Ag(n)}(s.value,t)})}).catch(()=>{r&&n({client:e,worktreeId:t,readable:!1})}),()=>{r=!1}):(ig.request(e).then(i=>{if(!r)return;let s=ig.interpret(i),o=s.accepted?s.value??[]:[],a=tx(t),l=o.find(e=>e.id===a);n({client:e,worktreeId:t,readable:!!l&&Ag(l.connectionId??null)})}).catch(()=>{r&&n({client:e,worktreeId:t,readable:!1})}),()=>{r=!1}):void n({client:e,worktreeId:t,readable:!1})},[e,i,t]),!!i||r.client===e&&r.worktreeId===t&&r.readable}(n,r),{ready:L,readyRef:M,lockReason:R,markReady:I,clear:A}=function(e){let[t,i]=(0,wh.useState)(new Set),r=(0,wh.useRef)(t),n=null!=e.activeHandle&&t.has(e.activeHandle),s=e.connected?n?null:"waiting":"disconnected",o=(0,wh.useRef)(n);o.current=n;let a=(0,wh.useCallback)(e=>{r.current=e,i(e)},[]);return(0,wh.useEffect)(()=>{!e.connected&&r.current.size>0&&a(new Set)},[e.connected,a]),{ready:n,readyRef:o,lockReason:s,markReady:(0,wh.useCallback)(e=>{r.current.has(e)||a(new Set(r.current).add(e))},[a]),clear:(0,wh.useCallback)(e=>{let t=r.current;if(void 0===e)return 0!==t.size&&(a(new Set),!0);if(!t.has(e))return!1;let i=new Set(t);return i.delete(e),a(i),!0},[a])}}({activeHandle:c,connected:"connected"===s}),P=function(e){var t;let i,r,n,{client:s,hostId:o,worktreeId:a,activeSessionTab:l,activeSessionTabId:c,activeHandleRef:d,deviceTokenRef:u,nativeChatInputLeaseReady:h,connState:f,agentSessionHostSupport:p=null,onSendError:m,onSendResolved:g}=e,{activeChatAgent:b,activeChatAgentRef:v,activeChatResolution:y,activeChatSessionId:_,activeChatStructured:w,activeTabAgentWorking:S,isTabChatView:x,setTabView:T,nativeChatStatus:k,showNativeChat:C,showNativeChatRef:L,sourceIdentity:M,streamIdentity:R,streamScopeKey:I,toggleTabChatView:A}=function(e){let{activeHandleRef:t,activeSessionTab:i,activeSessionTabId:r,hostId:n,nativeChatTranscriptIsLocalReadable:s,worktreeId:o}=e,a=function(e){let{hostId:t,worktreeId:i}=e,[r,n]=(0,Oa.useState)(()=>({hostId:t,worktreeId:i,overrides:new Map,loaded:!1})),s=(0,Oa.useRef)(r);s.current=r;let o=(0,Oa.useRef)(null),a=(0,Oa.useRef)(!0);(0,Oa.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let l=(0,Oa.useCallback)((e,t)=>{let i=o.current;if(i?.hostId===e&&i.worktreeId===t)return i;let r={hostId:e,worktreeId:t,loadPromise:Op(e,t),currentOverrides:new Map,mutationRevisions:new Map};return o.current=r,r},[]),[c,d]=(0,Oa.useState)("terminal"),u=(0,Oa.useRef)(c);u.current=c,(0,Oa.useEffect)(()=>{let e=!0,r=l(t,i);return r.loadPromise.then(o=>{if(!e)return;let a=Ob(o.overrides,r.currentOverrides);r.currentOverrides=a;let l={hostId:t,worktreeId:i,overrides:a,loaded:o.loaded};s.current=l,n(l)}),()=>{e=!1}},[l,t,i]),(0,Ol.useFocusEffect)((0,Oa.useCallback)(()=>{let e=!0;return Oh().then(t=>{e&&d(t)}),()=>{e=!1}},[]));let h=(0,Oa.useCallback)(e=>!!Og(r,t,i)&&(r.overrides.get(e)??(r.loaded?c:"terminal"))==="chat",[c,t,r,i]),f=(0,Oa.useCallback)((e,r)=>{let c=s.current,d=Og(c,t,i)?c:{hostId:t,worktreeId:i,overrides:new Map,loaded:!1},u=new Map(d.overrides);u.set(e,r);let h={...d,overrides:u};s.current=h,n(h);let f=l(t,i);f.currentOverrides=u;let p=(f.mutationRevisions.get(e)??0)+1;f.mutationRevisions.set(e,p),Om(t,i,e,r).catch(async()=>{if(!a.current||o.current!==f)return;let r=await Op(t,i);if(!a.current||o.current!==f||f.mutationRevisions.get(e)!==p)return;let l=r.loaded?Ob(r.overrides,f.currentOverrides):new Map(f.currentOverrides),c=r.loaded?r.overrides.get(e):"terminal";c?l.set(e,c):l.delete(e),f.currentOverrides=l;let d=s.current;if(!Og(d,t,i))return;let u={...d,overrides:l,loaded:r.loaded};s.current=u,n(u)})},[l,t,i]),p=(0,Oa.useCallback)(e=>{let r=s.current,n=r.loaded?u.current:"terminal",o=Og(r,t,i)&&(r.overrides.get(e)??n)==="chat";f(e,o?"terminal":"chat")},[t,f,i]);return{isTabChatView:h,setTabView:f,toggleTabChatView:p,hasTabOverride:(0,Oa.useCallback)(e=>Og(r,t,i)&&r.overrides.has(e),[t,r,i])}}({hostId:n,worktreeId:o}),{setTabView:l}=a,c=i?.type??null,d=i?.agentStatus?.providerSession?.id??null,u=(0,Oo.useCallback)(e=>e===r&&"terminal"===c&&!d&&!a.hasTabOverride(e),[d,r,c,a.hasTabOverride]),h=(0,Oo.useCallback)(e=>!u(e)&&a.isTabChatView(e),[u,a.isTabChatView]),f=(0,Oo.useCallback)(e=>{u(e)?l(e,"chat"):a.toggleTabChatView(e)},[u,l,a.toggleTabChatView]),p=i?.type==="agent-session"||!!r&&h(r),m=i&&r&&p?Ab(i,s):null,g=null!=m,b=(0,Oo.useRef)(g),v=m?.agent??null,y=(0,Oo.useRef)(v);(0,Oo.useLayoutEffect)(()=>{b.current=g,y.current=v},[v,g]);let _=m?.sessionId??null,w=null!=m&&i?.type==="agent-session",S=i?.agentStatus,x=S?.state==="working"&&"monitoring"!==S.workingMode&&!0!==S.restoredUnconfirmed,T=m&&!w?S:null,k=`${n}\0${o}\0${r??""}`,C=`${k}\0${_??""}\0${t.current??""}`,L=i?.agentStatus?.providerSession?.id??"",M=`${k}\0${_??L}\0${t.current??""}`;return{isTabChatView:h,setTabView:l,toggleTabChatView:f,showNativeChat:g,showNativeChatRef:b,activeChatAgent:v,activeChatAgentRef:y,activeChatSessionId:_,activeChatStructured:w,activeChatResolution:m,activeTabAgentWorking:x,nativeChatStatus:T,sourceIdentity:Q1([n,o]),streamIdentity:C,streamScopeKey:M}}(e),P=(0,Qu.useRef)(()=>!1),{structuredSession:E,session:D}=function({client:e,structured:t,agent:i,resolvedAgent:r,transcriptPath:n,sessionId:s,sourceIdentity:o,hostSupport:a,appendComposerTextRef:l,enabled:c,connState:d,onSendError:u,onActionResolved:h}){let f=(0,QX.useCallback)(e=>l.current(e),[l]),p=function(e){let t,{client:i,sourceIdentity:r,agent:n,sessionId:s,transcriptPath:o}=e,[a,l]=(0,QJ.useState)([]),c=Q1([r,n,s,o]),d=i&&n?s?"loading":"waiting-session":"idle",[u,h]=(0,QJ.useState)(null),f=u;null!==f&&(f.identity!==c||f.client!==i)&&(f=null,h(null));let p="loading"===d?f:null,m=p?p.status:d,[g,b]=(0,QJ.useState)(void 0),[v,y]=(0,QJ.useState)(!1),{phase:_,load:w,supersede:S}=Q6(),x=(0,QJ.useRef)(null),T=(0,QJ.useRef)(function(e=g2){return{list:[],indexById:new Map,priority:e}}()),k=(0,QJ.useRef)(40),C=(0,QJ.useRef)(s);C.current=s;let L=(0,QJ.useRef)(!1),M=(0,QJ.useRef)((t=null,{capture(e,i){t={identity:e,messages:i}},visible:({identity:e,messages:i,settled:r})=>r?i:t?.identity===e?t.messages:Q0})),R=p?.status==="ready";(0,QJ.useEffect)(()=>{R&&M.current.capture(c,a)},[c,a,R]);let I=(0,QJ.useCallback)(e=>{Q5(T.current,e),l(T.current.list)},[]);(0,QJ.useEffect)(()=>{var e;let t=!1;if(S(),k.current=40,L.current=!1,I([]),b(void 0),y(!1),x.current=null,!i||!n||!s)return;let r=i.subscribe("nativeChat.subscribe",{agent:n,sessionId:s,limit:k.current,subscriptionId:(e=iR())?`${n}:${s}:${e}`:`${n}:${s}`,capabilities:{transcriptPending:1},...o?{transcriptPath:o}:{}},e=>{if(t)return;let r=function(e){let{merger:t,frame:i,limit:r,replaceSnapshot:n}=e;if("error"===i.type)return{kind:"error",error:i.message??i.error??"Transcript stream failed"};if("end"===i.type)return{kind:"error",error:"Transcript stream ended"};if("snapshot"!==i.type&&"replacement"!==i.type&&"appended"!==i.type)return{kind:"ignored"};if(i.error)return{kind:"error",error:i.error};if(!Array.isArray(i.messages))return{kind:"ignored"};let s="snapshot"===i.type&&!0===i.pending,o="snapshot"===i.type&&!n&&t.list.length>0?function(e,t,i){let r=t[0]?e.indexById.get(t[0].id):void 0;if(void 0===r||!1===i&&r>0)return null;let n=r,s=!1;for(let i of t){let t=e.indexById.get(i.id);if(void 0===t)s=!0;else{if(s||t!==n)return null;n+=1}}return n===e.list.length?r:null}(t,i.messages,i.hasMore):null;if("replacement"===i.type||"snapshot"===i.type&&null===o)return Q5(t,i.messages),{kind:"messages",messages:t.list,hasMore:i.hasMore,windowReplaced:!0,...s?{pending:!0}:{},...null==i.beforeOffset?{}:{beforeOffset:i.beforeOffset}};let a=t.list[0]?.id,l=function(e,t,i){if(0===t.length)return e.list;let r=[...e.list];Q2(r,e.indexById,t,e.priority);let n=void 0===i?r:function(e,t){var i,r;if(t<=0||e.length<=t)return e;let n=e.length-t;for(;n>0&&(i=e[n-1],r=e[n],"number"==typeof i.transcriptOffset&&"number"==typeof r.transcriptOffset?i.transcriptOffset===r.transcriptOffset:"reasoning"===i.role&&"assistant"===r.role&&g3(i)===r.id);)n-=1;return e.slice(n)}(r,i);return n!==r?(Q5(e,n),e.list):(e.list=r,r)}(t,i.messages,r),c=!!(a&&l[0]?.id!==a),d="snapshot"===i.type&&0===o;return{kind:"messages",messages:l,...s?{pending:!0}:{},...c?{cursorInvalidated:!0}:{},..."snapshot"===i.type&&c?{hasMore:!0}:d?{...null==i.hasMore?{}:{hasMore:i.hasMore},...null==i.beforeOffset?{}:{beforeOffset:i.beforeOffset}}:{}}}({merger:T.current,frame:e,limit:2e3,replaceSnapshot:!L.current});if("ignored"!==r.kind){if("error"===r.kind){h({client:i,identity:c,status:"error"}),b(r.error);return}"snapshot"!==e.type||r.pending||(L.current=!0),(r.windowReplaced||"snapshot"===e.type&&null===x.current)&&S(),r.windowReplaced&&(k.current=40,x.current=r.beforeOffset??null,y(r.hasMore??r.messages.length>=40)),l(r.messages),r.windowReplaced||null==r.hasMore||y(r.hasMore),r.windowReplaced||null==r.beforeOffset||(x.current=r.beforeOffset),r.cursorInvalidated&&(S(),x.current=null),h({client:i,identity:c,status:r.pending?"awaiting-transcript":"ready"})}});return()=>{t=!0,S(),r()}},[i,n,s,o,c,I,S]);let A=(0,QJ.useCallback)(e=>{i&&n&&s&&v&&w(async({timeoutMs:t,isCurrent:r})=>{let a,l,c,d=(l=Math.min((a=Math.max(k.current,T.current.list.length))+60,2e3))>a?{nextLimit:l,pageLimit:l-a}:null;if(!d)return y(!1),"end";let{nextLimit:u,pageLimit:h}=d,f=x.current,p=await i_.request(i,{agent:n,sessionId:s,limit:null===f?u:h,...null===f?{}:{beforeOffset:f},...o?{transcriptPath:o}:{}},{timeoutMs:t,budgetSpansConnect:!0}),m=i_.interpret(p);if(!m.accepted)return"failed";let g=m.value;if(null===g||"object"!=typeof g||"error"in g)return"failed";let b=new Map(T.current.list.map(e=>[e.id,e]));if(e&&await e(),!r()||C.current!==s||x.current!==f)return"end";if(k.current=u,null!==f&&null!=g.beforeOffset)x.current=g.beforeOffset,I([...g.messages,...T.current.list]),c=u<2e3&&(g.hasMore??g.messages.length>=h);else{let e=T.current.list,t=e.findIndex(e=>e.id===g.messages.at(-1)?.id);I(function(e,t){if(0===t.length)return e;let i=[...e],r=new Map;return i.forEach((e,t)=>r.set(e.id,t)),Q2(i,r,t,g2),i}(-1===t?g.messages:[...g.messages,...e.slice(t+1)],e.filter(e=>b.get(e.id)!==e))),c=g.messages.length>=u}return y(c),c?"drew":"end"})},[i,n,s,o,v,I,w]);return{messages:M.current.visible({identity:c,messages:a,settled:R}),status:m,transcriptLoading:"loading"===m||"awaiting-transcript"===m,error:g,hasMore:v,loadingEarlier:"loading"===_,olderPages:_,loadEarlier:A}}({client:e,sourceIdentity:o,agent:t?null:r,sessionId:t?null:s,transcriptPath:t?null:n}),m=function(e){var t,i,r;let{agent:n,appendComposerText:s,client:o,connected:a,sessionId:l,sourceIdentity:c="",enabled:d,onActionResolved:u,onSendError:h,hostSupport:f}=e,p=f?.queuedMessages===!0,m=p&&f?.queuedCommands===!0,g=f?.promptCancel??null,b=f?.quietRepeatedStop??null,v=f?.conversationStop??null,y=Q1([c,n,l]),_=(0,Q4.useRef)(!1),w=(0,Q4.useRef)(new Map),{state:S,stateRef:x,queuedMessages:T,queuePause:k,olderPages:C,loadEarlier:L}=function(e){let{client:t,connected:i,enabled:r,sessionId:n,sessionKey:s}=e,[o,a]=(0,jx.useState)(()=>new Map),[l,c]=(0,jx.useState)(()=>new Map),d=r&&s?o.get(s)??jF:jF,u=(r&&s?l.get(s):void 0)??jK,h=u.messages,{phase:f,load:p,supersede:m}=Q6(),g=(0,jx.useRef)(d);(0,jx.useLayoutEffect)(()=>{g.current=d},[d]);let b=(0,jx.useCallback)(e=>{s&&a(t=>{let i=t.get(s)??jF,r=function(e,t,i=Date.now()){var r;let n;if("requests-marker"===t.type)return{...e,...ju(e,t.marker)};if("requests-complete"===t.type)return t.marker.version===e.requestMarker?.version?{...e,currentRequests:t.items,requestAuthority:t.marker}:e;if("loading"===t.type)return{...e,status:"loading",error:void 0,readRefusal:void 0};if("error"===t.type)return{...e,status:"error",error:t.message,readRefusal:t.refusal};if("history-page"===t.type)return{...jB(t.page,t.page.fence??null,e.backgroundTasks,e.activity),...jd(e),commands:e.commands,...jj(e,t.page),...jD(t.page.hostNow,i,e.hostClock)};if("older-page"===t.type){let r=t.requestedCursor;if(e.epoch!==r.epoch||t.page.epoch!==r.epoch)return e;let n=e.items[0];if(n&&n.sequence>r.sequence)return e;let s=jQ(e.items,t.page.items,t.page.removedItemIds);return{...e,items:s,retainedOwnItemLimit:Math.max(e.retainedOwnItemLimit,jL(s)),retainedItemCap:Math.max(e.retainedItemCap,s.length),subagentRoster:jA(e.subagentRoster,t.page),submissions:jM(e.submissions,t.page.submissions,s),hasOlder:_I(s,t.page.hasOlder),...jD(t.page.hostNow,i,e.hostClock)}}let s=t.event;if("end"===s.type)return e;if("snapshot"===s.type||"reset"===s.type){let t=jh(e,s,!0);return{...jB(s.page,s.fence,jE(s.backgroundTasks),s.activity),...t,status:"ready",commands:s.commands,...jj(s,s.page,e),...jD(s.hostNow,i,e.hostClock)}}if(e.epoch!==s.batch.cursor.epoch||e.cursor&&s.batch.cursor.sequencee.sequence>=n.sequence):r),d=jI(e.subagentRoster??jR,s.batch.items,s.batch.removedItemIds),u=0===c.length&&0===s.batch.removedItemIds.length&&0===s.batch.submissions.length;if(s.batch.cursor.sequence===e.cursor?.sequence&&u&&d===(e.subagentRoster??jR)&&(void 0===s.fence||s.fence===e.fence)&&(void 0===s.commands||s.commands===e.commands)&&(void 0===s.queuedMessages||s.queuedMessages===e.queuedMessages)&&(void 0===s.queuePause||s.queuePause===e.queuePause)&&(void 0===s.nextQueuedMessageId||s.nextQueuedMessageId===e.nextQueuedMessageId)&&jP(a,e.backgroundTasks)&&(void 0===s.latestTurn||JSON.stringify(s.latestTurn)===JSON.stringify(e.latestTurn))&&(void 0===s.actionablePromptIds||s.actionablePromptIds.join(` `)===e.actionablePromptIds?.join(` `))&&(void 0===s.working||s.working===e.working)&&l?.turnId===e.activity?.turnId&&l?.text===e.activity?.text&&"ready"===e.status&&void 0===e.error&&o.currentRequests===e.currentRequests&&o.requestMarker===e.requestMarker&&o.requestAuthority===e.requestAuthority)return e;let h=u?e.items:jQ(e.items,c,s.batch.removedItemIds),f=function(e,t,i){let r=Math.max(0,e.length-i),n=0;for(let i=e.length-1;i>=r;i-=1)if(bU(e[i])&&(n+=1)>t){r=i+1;break}return 0===r?e:e.slice(r)}(h,e.retainedOwnItemLimit,e.retainedItemCap),p=[...c.length!c.includes(e)):[],...h.slice(0,h.length-f.length)].some(e=>null!==yx(e.body));return{...e,...o,cursor:s.batch.cursor,fence:s.fence??e.fence,items:f,subagentRoster:d,hasOlder:_I(f,f.length0||r.length>0||n.length>0||void 0!==t.latestTurn?t.latestTurn:e}(e.latestTurn,s),actionablePromptIds:function(e,t){let{items:i,removedItemIds:r,submissions:n}=t.batch;return i.length>0||r.length>0||n.length>0||void 0!==t.actionablePromptIds?t.actionablePromptIds:e}(e.actionablePromptIds,s),working:function(e,t){let{items:i,removedItemIds:r,submissions:n}=t.batch;return i.length>0||r.length>0||n.length>0||void 0!==t.working?t.working:e}(e.working,s),...jj(s,e),backgroundTasks:a,...void 0!==l?{activity:l}:{},...p?{unloadedTurnRevisions:(e.unloadedTurnRevisions??0)+1}:{},...jD(s.hostNow,i,e.hostClock)}}(i,e,Date.now());if(r===i)return t;let n=new Map(t);for(n.delete(s),n.set(s,r);n.size>32;){let e=n.keys().next().value;if(void 0===e)break;n.delete(e)}return n})},[s]),v=(0,jx.useCallback)(e=>{let t,i=jH(e);b({type:"error",message:(t=jH(e))?Rv(Rb(Rn(t),"read-history")):e instanceof Error?e.message:"object"==typeof e&&null!==e?"message"in e?String(e.message??""):"":String(e),...i?{refusal:i}:{}})},[b]),y=(0,jx.useCallback)(e=>{s&&c(t=>{let i=t.get(s)??jK,r=function(e,t){if("end"===t.type||void 0===t.queuedMessages)return e;let i=t.queuedMessages??[];return 0===i.length&&null!==e&&0===e.length?e:[...i].sort((e,t)=>e.position-t.position)}(i.messages,e),n=function(e,t){if("end"===t.type||void 0===t.queuedMessages)return e;let i=t.queuePause??null;return null===i!=(null===e)?i:i?.reason===e?.reason?e:i}(i.pause,e);if(r===i.messages&&n===i.pause)return t;let o=new Map(t);for(o.delete(s),o.set(s,{messages:r,pause:n});o.size>32;){let e=o.keys().next().value;if(void 0===e)break;o.delete(e)}return o})},[s]);(0,jx.useEffect)(()=>{if(m(),!t||!n||!r||!i)return;b({type:"loading"});let e=!0,s=(jC+=1,`mobile-chat:${jC}`),o=jN(t,"agentSession.hold",{sessionId:n,holderId:s}),a=function(e){let t=!1,i=0,r=!1,n=()=>{},s=()=>!t&&e.isCurrent(),o=()=>{i+=1,a.invalidate();let e=n;n=()=>{},e()},a=function(e){let t=0,i,r=!1,n;async function s(){if(r||!i||n===i.version)return;r=!0;let o=t,a=i;n=a.version;let l=0,c=[],d=()=>t===o&&i?.version===a.version;try{for(;d();){let t=await e.read({sessionId:a.sessionId,version:a.version,cursor:l});if(!d())return;if(t.restart){if(t.marker.sessionId!==a.sessionId||t.marker.version===a.version||t.marker.contract!==tM)throw Error("Invalid request owner");i=a=t.marker,n=a.version,e.replaceMarker(a),c.length=0,l=0;continue}if(t.marker.version!==a.version||t.marker.owner!==a.owner||t.marker.epoch!==a.epoch||t.marker.sessionId!==a.sessionId)throw Error("Current-request version changed");if(c.push(t.json),null===t.nextCursor){let t=JSON.parse(c.join(""));if(!Array.isArray(t)||!t.every(y4)||!t.every(e=>("approval"===e.body.kind||"question"===e.body.kind)&&"pending"===e.body.resolution.state))throw Error("Invalid current requests");e.complete(a,t);return}if(!Number.isSafeInteger(t.nextCursor)||t.nextCursor<=l)throw Error("Invalid current-request cursor");l=t.nextCursor}}catch(t){d()&&e.error(t,a)}finally{r=!1,s()}}return{observe(e){e&&e.contract!==tM||i?.version!==e?.version&&(e&&i?.publisher===e.publisher&&e.revision<=i.revision||(i=e,s()))},invalidate(){t+=1,i=void 0,n=void 0}}}({read:e.read,complete:(t,i)=>{s()&&e.apply({type:"requests-complete",marker:t,items:i})},replaceMarker:t=>{s()&&e.apply({type:"requests-marker",marker:t})},error:i=>{s()&&(o(),e.error(i),r?t=!0:(r=!0,l()))}});function l(){let r=++i,l=!0;n=e.open(n=>{if(!(!s()||i!==r)){if("object"==typeof n&&null!==n&&"type"in n&&"error"===n.type){o(),t=!0,e.error(n);return}(function(e){if("object"!=typeof e||null===e)return!1;let t="type"in e?e.type:void 0;return"snapshot"===t||"batch"===t||"reset"===t||"end"===t})(n)&&(("snapshot"===n.type||"reset"===n.type)&&a.invalidate(),e.apply({type:"event",event:n,opensSubscription:l}),e.applyQueued(n),"end"===n.type?a.invalidate():(l=!1,n.currentRequests?.sessionId===e.sessionId&&a.observe(n.currentRequests)))}})}return l(),()=>{t=!0,o()}}({sessionId:n,open:e=>{let i,r;return i=!1,r=()=>{},o.catch(()=>{}).then(()=>{i||(r=t.subscribe("agentSession.subscribe",{sessionId:n},e))}),()=>{i=!0,r()}},read:e=>jN(t,"agentSession.currentRequests",e),apply:e=>{"event"===e.type&&("snapshot"===e.event.type||"reset"===e.event.type)&&m(),b(e)},applyQueued:y,error:v,isCurrent:()=>e});return()=>{e=!1,m(),a(),o.then(()=>jN(t,"agentSession.release",{sessionId:n,holderId:s},void 0,{failWhenDisconnected:!0}).catch(()=>{})).catch(()=>{})}},[b,y,v,t,i,r,n,s,m]);let _=(0,jx.useCallback)(e=>{let i=jO(g.current);if(!t||!n||!s||!g.current.hasOlder||!i)return;let r=i,o=new Set([i.sequence]),a=()=>{let e=jO(g.current);return e?.epoch===r.epoch&&o.has(e.sequence)};p(async({timeoutMs:i,isCurrent:s})=>{let l;if(!a()){let e=jO(g.current);if(!e)return"end";r=e,o=new Set([e.sequence])}try{l=await jN(t,"agentSession.history",{sessionId:n,direction:"before",cursor:r,limit:200},i)}catch(e){return jl(jH(e))?"unavailable":"failed"}if(e&&await e(),!s()||!l.ok)return"end";if(!a())return"drew-nothing";let{page:c}=l;b({type:"older-page",requestedCursor:r,page:c});let d=c.items[0];return c.hasOlder&&d?(o.add(d.sequence),r=c.window.nextCursor,c.items.some(bU)?"drew":"drew-nothing"):"end"})},[b,t,p,n,s]),w="ready"===d.status&&d.hasOlder&&!d.items.some(bU)?`${s}:${d.epoch}:${d.items[0]?.sequence}`:null,S=(0,jx.useRef)(null),x="loading"===f;return(0,jx.useEffect)(()=>{null===w||x||S.current===w||(S.current=w,_())},[w,_,x]),{state:d,stateRef:g,queuedMessages:h,queuePause:u.pause,olderPages:f,loadEarlier:_}}({client:o,sessionId:l,sessionKey:y,enabled:d,connected:a}),M=function(e){let{agentName:t,client:i,enabled:r,onSendError:n,sessionId:s,stateRef:o}=e;return(0,Fy.useCallback)(async(e,a,l,c)=>{let d=o.current;if(!i||!s||!r||null===d.fence)return{status:"rejected"};let u=d.fence,h=await jq({client:i,method:e,fingerprintMethod:a,sessionId:s,expectedRuntimeFence:u,fields:l,...t?{agentName:t}:{}});return"accepted"===h.status?{status:"accepted",value:h.value,sameFence:o.current.fence===u}:"unknown"===h.status?h:(c?.()!==!1&&n(h.message),{status:"rejected"})},[t,i,r,n,s,o])}({client:o,sessionId:l,enabled:d,stateRef:x,onSendError:h,...n?{agentName:ri(n)??n}:{}}),R=function(e){let{client:t,sessionId:i,enabled:r}=e,n=r&&t&&i?jG(t):null,s=(0,Ff.useCallback)(e=>n?n.subscribe(e):()=>{},[n]),o=()=>{let e=n&&i?n.getSnapshot().get(i):void 0;return`${e?.model??""}|${e?.permissionMode??""}`};return(0,Ff.useSyncExternalStore)(s,o,o)}({client:o,sessionId:l,enabled:d&&a&&f?.statusFeed===!0}),I=function(e){let{agent:t,client:i,enabled:r,fence:n,mutate:s,optionStamp:o,sessionId:a,hostSupport:l}=e,c=(0,jX.useMemo)(()=>t?e4(t)?ij(t)??jJ:jJ:null,[t]),[d,u]=(0,jX.useState)(()=>Fe(t??"codex",c)),h=(0,jX.useRef)(d),f=(0,jX.useRef)(d.record),p=(0,jX.useRef)(null),m=(0,jX.useRef)(0),g=(0,jX.useCallback)(e=>{let t=e(h.current);h.current=t,u(t)},[]),[b,v]=(0,jX.useState)(null),[y,_]=(0,jX.useState)(null),w=(0,jX.useRef)(`${t}:${a}`);(0,jX.useEffect)(()=>{let e=`${t}:${a}`,i=w.current===e;w.current=e;let r=h.current,n=Fe(t??"codex",c),s=i&&("host"===r.catalogSource||"builtin"===r.catalogSource)?{...n,catalog:r.catalog,catalogSource:r.catalogSource}:n,o=i?{...s,permissionMode:r.permissionMode}:s;m.current+=1,p.current=null,h.current=o,f.current=o.record,u(o)},[t,r,n,c,a]);let S=(0,jX.useMemo)(()=>a?te(a):void 0,[a]),[x,T]=(0,jX.useState)(0),k=(0,jX.useCallback)(()=>T(e=>e+1),[]);(function(e){let{activeOptionRecordRef:t,agent:i,client:r,enabled:n,fence:s,newLaunch:o,onListingLanded:a,optionCatalog:l,sessionId:c,updateOptionState:d,worktree:u}=e;(0,Fd.useEffect)(()=>{if(!r||!c||!n||!i||!l)return;let e=!1,s={agent:i,sessionId:c,...o&&u?{worktree:u}:{}},h=e=>e?jN(r,"agentSession.modelCatalog",{...s,waitForListing:e},45e3):jN(r,"agentSession.modelCatalog",s),f=i=>{e||d(e=>e.record===t.current?function(e,t,i,r){if("live"===e.catalogSource)return e;let n="unknown"===i.origin?[]:i.models.map(e=>j0(e,i.fastModeSupport?.supported===!0));if("unknown"===i.origin||0===n.length)return Ft(e);let s=r.newLaunch&&(i.listingNamesConfiguredModel??!0===t.hostListingNamesConfiguredModel);return{...e,catalog:{...t,models:n,...s?{defaultModelIsCliDefault:!0}:{}},catalogSource:"host"}}(e,l,i,{newLaunch:o}):e)};return h(!1).then(t=>{if("unknown"===t.origin&&!0===t.listingInProgress&&!e)return f(t),h(!0).then(t=>{f(t),e||"unknown"===t.origin||a?.()});f(t)}).catch(()=>{e||d(e=>e.record===t.current?Ft(e):e)}),()=>{e=!0}},[t,i,r,n,s,o,a,l,c,d,u])})({agent:t,client:i,sessionId:a,enabled:r,fence:n,newLaunch:void 0!==S,...S?{worktree:S.worktree}:{},optionCatalog:c,activeOptionRecordRef:f,updateOptionState:g,onListingLanded:k}),(0,jX.useEffect)(()=>{if(!i||!a||!r||!c)return;let e=!1,t=m.current;return jN(i,"agentSession.options",{sessionId:a}).then(i=>{tt(a),e||_({sessionId:a,acceptsImages:i.acceptsImages,statesPermissionMode:i.current?.permissionMode!==void 0}),e||m.current!==t||(v({sessionId:a,commands:i.conversationCommands??[]}),g(e=>e.record===f.current?Fi(e,c,i):e))}).catch(()=>{}),()=>{e=!0}},[i,r,c,o,x,a,n,g]);let C=null!==t&&null!==SA(t)&&l?.permissionModes===!1&&y?.sessionId===a&&!y.statesPermissionMode&&null===d.permissionMode,L=(0,jX.useMemo)(()=>{let e=Fc(d);return C?[...e,{id:SM,label:"Permissions",category:"mode",kind:{type:"select",currentValue:j9,choices:[{value:j9,label:"Host's Agent Permissions",description:"This host runs an older Orca that applies its Agent Permissions to every chat and can't ask per chat. Update Orca on the host to choose a mode here."}]},valueSource:"applied",transport:"agent-session",settable:!1}]:e},[C,d]),M=(0,jX.useCallback)(async(e,r)=>{var n;let o,l=h.current,d=j5(e,r);if(null!==p.current||!i||!a||!c||null===d||(o=Fn(n=Fl(l,void 0,{})).find(t=>t.id===e),!(n.catalog&&n.pendingId!==e&&("string"==typeof r&&o?.kind.type==="select"&&o.kind.choices.some(e=>e.value===r)||"boolean"==typeof r&&o?.kind.type==="boolean"))))return!1;let u=l.record,b=++m.current,v=()=>f.current===u&&m.current===b,y=e===SM;y?g(t=>t.record===u?Fs(t,e,d):t):(p.current=e,g(t=>({...t,pendingId:e})));let _=y;try{let r=await s("agentSession.setOption","agentSession.setOption",{key:e,value:d});if(!v())return"rejected"!==r.status;if("accepted"===r.status){let n=r.value.options??{[e]:d};return g(e=>e.record===u&&r.sameFence?Fo(e,n):e),t&&function(e){let{agent:t,client:i,picks:r}=e;if(!i||0===r.length)return Promise.resolve();let n={type:"apply-picks",agent:t,picks:[...r]};iK.request(i,n).then(()=>{}).catch(()=>{})}({client:i,agent:t,picks:function(e,t){if(!e.catalog)return[];let i=t.model,r="string"==typeof i&&i.trim()?i:Sq(e.catalog,e.catalog.models,e.record);return r?j3.flatMap(e=>{let i=t[e];if(void 0===i)return[];let n=j2(e,i);return null!==n&&("string"!=typeof n||n.trim())&&null!==j5(e,n)?[{modelId:r,optionId:e,value:n}]:[]}):[]}(l,n)}),_=r.sameFence,!0}return"unknown"===r.status&&(_=!1,g(t=>t.record===u?Fs(t,e,d):t),!0)}finally{_&&v()&&jN(i,"agentSession.options",{sessionId:a}).then(e=>{v()&&g(t=>t.record===u?Fi(t,c,e):t)}).catch(()=>{}),v()&&(p.current=null,g(t=>t.record===u&&t.pendingId===e?{...t,pendingId:null}:t))}},[t,i,s,c,a,g]),{optionPickerRequest:R,invokeStructuredOption:I,optionSurface:A}=function(e){let{optionSnapshot:t,optionStateRef:i,setStructuredOption:r}=e,[n,s]=(0,Fu.useState)(null),o=(0,Fu.useCallback)(async e=>!!t.some(t=>t.id===e)&&(s(t=>({id:e,sequence:(t?.sequence??0)+1})),!0),[t]),a=(0,Fu.useCallback)(async(e,t)=>(await r(e,t),{snapshot:Fc(i.current)}),[i,r]);return{optionPickerRequest:n,invokeStructuredOption:o,optionSurface:(0,Fu.useMemo)(()=>({getSnapshot:()=>t,setOption:a,invokeAction:async()=>({snapshot:t}),subscribe:()=>()=>{}}),[t,a])}}({optionSnapshot:L,setStructuredOption:M,optionStateRef:h});return{optionPickerRequest:R,conversationCommands:b?.sessionId===a?b.commands:Fh,acceptsImages:(y?.sessionId===a?y.acceptsImages:void 0)??(null!==t&&e4(t)),optionSnapshot:L,optionSurface:A,pendingOptionId:d.pendingId,setStructuredOption:M,invokeStructuredOption:I}}({agent:n,client:o,sessionId:l,enabled:d,fence:S.fence,mutate:M,optionStamp:R,hostSupport:f}),{conversationCommands:A,invokeStructuredOption:P,optionSnapshot:E,setStructuredOption:D}=I,B=(0,Q4.useMemo)(()=>({snapshot:E,setOption:D,invokeAction:P,conversationCommands:A}),[A,P,E,D]),{groupedDraft:Q,respondPermission:j,respondQuestion:F}=function(e){let{mutate:t,onSendError:i,questionAnswersSupported:r,sessionKey:n,stateRef:s}=e,[o,a]=(0,jY.useState)(null),l=o?.sessionKey===n?o.draft:null,c=(0,jY.useCallback)(async e=>{let r=function(e,t){let i=j_(e);if(i?.kind==="approval")return{itemId:i.itemId,expectedRevision:i.revision,optionId:i.optionId};if(i)return null;let r=t?.body.options.find(t=>t.id===e||t.label===e);return t&&r?{itemId:t.itemId,expectedRevision:t.revision,optionId:r.id}:null}(e,jw(s.current));if(!r)return!1;let n=await t("agentSession.respondToApproval","agentSession.respondTo:approval",r);return"unknown"===n.status?(i("Response unconfirmed — check chat before retrying"),!1):"accepted"===n.status},[t,i,s]),d=(0,jY.useCallback)((e,n,s)=>{let o=i=>t("agentSession.respondToQuestion","agentSession.respondTo:question",{...e,...i});if(!0===r)return o({answers:s});let a=function(e,t){var i;if(e.questions)return`${Cf}${JSON.stringify(t).replaceAll("%","%25")}`;let[r]=t;if(!r||1!==t.length)return null;let n=e.freeTextInput?.allowEmpty?r.other:r.other?.trim();return r.optionIds[0]??(void 0!==n&&(n.length>0||e.freeTextInput?.allowEmpty)?(i=r.questionId,`${encodeURIComponent(i)}:${encodeURIComponent(n)}`):null)}(n,s);return null===a?Promise.resolve(null):a.length>1024?null===r?o({answers:s}):(i("Update RuFlo on your computer to send answers this long"),Promise.resolve(null)):o({optionId:a})},[t,i,r]),u=(0,jY.useCallback)(async e=>{let t=jS(s.current);if(t?.body.questions){var r,o;let s=(r=t.itemId,o=t.revision,`${r}:${o}`),c=function(e){let t=jb(e.draft,e.promptKey),i=e.questions[t.length];if(!i)return null;let r=function(e,t,i){let r=[],n;for(let s of e.split(", ")){let e=s.trim(),o=function(e){if(!e.startsWith(jp))return null;let t=e.indexOf(":",jp.length);if(-1===t)return null;let i=jg(e.slice(0,t));if(i?.kind!=="free-text")return null;try{return{promptKey:i.promptKey,questionId:i.questionId,answer:decodeURIComponent(e.slice(t+1))}}catch{return null}}(e);if(o){let e=t.freeTextInput?.allowEmpty===!0,r=e?o.answer:o.answer.trim();if(o.promptKey!==i||o.questionId!==t.id||0===r.length&&!e||void 0!==n)return null;n=r;continue}let a=jg(e);if(a?.kind!=="option"||a.promptKey!==i||a.questionId!==t.id)return null;r.push(a.optionId)}let s=new Set(t.options.map(e=>e.id));if(r.some(e=>!s.has(e))||void 0!==n&&!t.freeTextQuestionId)return null;let o=r.length+ +(void 0!==n);return 0!==o&&(t.multiSelect||1===o)?{questionId:t.id,optionIds:r,...void 0!==n?{other:n}:{}}:null}(e.response,i,e.promptKey);if(!r)return null;let n=[...t,r];return n.length[e.questionId,e]));return i.size===t.length&&e.every(e=>{let t=i.get(e.id);if(!t)return!1;let r=new Set(e.options.map(e=>e.id));if(t.optionIds.some(e=>!r.has(e)))return!1;let n=void 0!==t.other&&(e.freeTextInput?.allowEmpty===!0||t.other.trim().length>0);if(n&&!e.freeTextQuestionId)return!1;let s=t.optionIds.length+ +!!n;return s>0&&(e.multiSelect||1===s)})}(e.questions,n)?null:{kind:"submit",answers:n}}({response:e,questions:t.body.questions,draft:l,promptKey:s});if(!c)return!1;if("advance"===c.kind)return a({sessionKey:n,draft:c.draft}),!0;let u=await d({itemId:t.itemId,expectedRevision:t.revision},t.body,c.answers);return!!u&&("rejected"!==u.status&&a(e=>e?.sessionKey===n&&e.draft.promptKey===s?null:e),"unknown"===u.status?(i("Answer unconfirmed — check chat before retrying"),!1):"accepted"===u.status)}let c=function(e,t){let i=j_(e);if(i?.kind==="question-option")return{itemId:i.itemId,expectedRevision:i.revision,answer:{questionId:i.questionId,optionIds:[i.optionId]}};if(i)return null;let r=function(e){if(!e.startsWith(jv))return null;let t=e.indexOf(":",jv.length);if(-1===t)return null;let i=j_(e.slice(0,t));return i?.kind!=="question-free-text"?null:{payload:i,answer:decodeURIComponent(e.slice(t+1))}}(e);if(r){let e=t?.itemId===r.payload.itemId&&t.revision===r.payload.revision&&t.body.freeTextQuestionId===r.payload.questionId&&t.body.freeTextInput?.allowEmpty===!0,i=e?r.answer:r.answer.trim();return i.length>0||e?{itemId:r.payload.itemId,expectedRevision:r.payload.revision,answer:{questionId:r.payload.questionId,optionIds:[],other:i}}:null}if(!t)return null;let[n]=Cp(t.body),s=e.trim(),o=t.body.freeTextInput?.allowEmpty===!0,a=t.body.options.find(t=>t.id===e||t.label===s);return n&&a?{itemId:t.itemId,expectedRevision:t.revision,answer:{questionId:n.id,optionIds:[a.id]}}:n&&t.body.freeTextQuestionId&&(s||o)?{itemId:t.itemId,expectedRevision:t.revision,answer:{questionId:n.id,optionIds:[],other:o?e:s}}:null}(e,t);if(!c)return!1;let u=await d({itemId:c.itemId,expectedRevision:c.expectedRevision},{},[c.answer]);return!!u&&("unknown"===u.status?(i("Answer unconfirmed — check chat before retrying"),!1):"accepted"===u.status)},[l,i,d,n,s]);return{groupedDraft:l,respondPermission:c,respondQuestion:u}}({stateRef:x,sessionKey:y,mutate:M,questionAnswersSupported:f?.questionAnswers??null,onSendError:h}),O=(0,Q4.useMemo)(()=>(function(e,t={}){let i=function(e){let t=new Set,i=null,r=null;for(let n of e){let e=jo(n);if("none"!==e){i=r="interruption"===e?n.itemId:null;continue}if("message"===n.body.kind&&"user"===n.body.role&&bU(n)){i=null;continue}let s=function(e){if("status"!==e.body.kind||yx(e.body)||Ry(e.itemId))return null;let t=ys(e.itemId),i=t?.provider==="orca"?t.clientMessageId:"";if(i.startsWith("stale-session:"))return"owner-death";if(_g(e.body.failure)?.kind==="providerExited"||i.startsWith("provider-exit:"))return"exit";let{tone:r}=e.body;return i.startsWith("restart-continuation:")&&("error"===r||"warning"===r)?"not-continued":null}(n);if(null===s)continue;let o=n.turnScope,a="exit"===s?i:r;o?.kind==="turn"?t.add(o.turnItemId):null!==a&&t.add(a)}return t}(e),r=_j(e),n=new Map;return e.forEach((s,o)=>{if("interruption"===jo(s)&&!i.has(s.itemId)){let i=function(e,t,i){let r=e[t].itemId,n=t;for(let s=t+1;s[e,...n.get(t)??[]])})(function(e,t=_R(e)){return t>0?e.filter(e=>e.sequence>=t):e}(S.items),{agentName:n?ri(n)??n:void 0}),[n,S.items]),W=function(e){let{cursor:t,onSendError:i,queuedMessages:r,sessionKey:n,submissions:s}=e,[o,a]=(0,FJ.useState)({}),[l,c]=(0,FJ.useState)({}),d=(0,FJ.useRef)(new Map),u=(0,FJ.useRef)(!1),h=(0,FJ.useCallback)(e=>a(t=>({...t,[n]:[...t[n]??[],e]})),[n]),f=(0,FJ.useCallback)(e=>a(t=>{let i=(t[n]??[]).filter(t=>!e.has(t.clientMessageId)),r={...t,[n]:i};return 0===i.length&&delete r[n],r}),[n]),p=(0,FJ.useCallback)((e,t)=>{if(h(e),t?.length){let i=yn(e.clientMessageId);c(e=>Qv(e,n,[{messageId:i,images:t}]))}},[h,n]),m=(0,FJ.useCallback)(e=>{if(!u.current)return;let t=e.clientMessageId;d.current.set(t,setTimeout(()=>{d.current.delete(t),f(new Set([t])),i(Qw)},2e4)),h({...e,unconfirmed:!0})},[f,h,i]),g=o[n]??F0;return(0,FJ.useEffect)(()=>{if(0===g.length)return;let{cards:e,recorded:i}={cards:new Set([...(r??[]).map(e=>e.messageId),...function(e){let t=new Set;for(let i of e)void 0!==i.queuedMessageId&&t.add(i.queuedMessageId);return t}(s)]),recorded:new Map(s.map(e=>[e.clientMessageId,e]))},n=new Set(g.filter(r=>{var n;return e.has(r.clientMessageId)||i.has(r.clientMessageId)||(n=r.recordedCursor,!!(t&&n&&t.epoch===n.epoch&&t.sequence>=n.sequence))}).map(e=>e.clientMessageId));if(0!==n.size){for(let e of n)clearTimeout(d.current.get(e)),d.current.delete(e);f(n)}},[t,f,r,g,s]),(0,FJ.useEffect)(()=>{u.current=!0;let e=d.current;return()=>{for(let t of(u.current=!1,e.values()))clearTimeout(t);e.clear()}},[]),{optimistic:(0,FJ.useMemo)(()=>g.filter(e=>!e.unconfirmed),[g]),imagePreviewsByMessageId:l[n]??F1,accept:p,hold:m}}({sessionKey:y,cursor:S.cursor,submissions:S.submissions,queuedMessages:T,onSendError:h}),H=(0,Q4.useMemo)(()=>(function(e,t,i,r=function(e){let t=[];return e.forEach(e=>{let i=LC(e);i&&t.push(i)}),t}){let n,s,o,a,l,c,d=new Map(i.filter(e=>_C(e)&&void 0===e.queuedMessageId).map(e=>[yn(e.clientMessageId),e])),u=new Set(i.filter(e=>"rejected"===e.dispatchState).map(e=>yn(e.clientMessageId)).filter(e=>!d.has(e))),h=d.size>0?(s=new Map([...n=_F(e,i)].map(([e,t])=>[t,e])),o=new Map(e.map(e=>[e.itemId,e])),a=function(e,t,i){let r=new Map,n=(e,t)=>{let i=r.get(e);(!i||yc(t,i)>0)&&r.set(e,t)};for(let i of e){let e=yl(i);t.has(i.itemId)&&n(i.itemId,e),i.turnScope?.kind==="turn"&&n(i.turnScope.turnItemId,e)}let s=[...t].flatMap(([e,t])=>{let n=i.get(t),s=i.get(e),o=r.get(e);return n&&s&&o?[{opener:_q(n,s),last:o}]:[]});s.sort((e,t)=>yc(e.opener,t.opener));let o=[];for(let e of s){let t=o.at(-1);o.push(t&&yc(t,e.last)>0?t:e.last)}return e=>{let t=0,i=s.length;for(;t>1;0>yc(s[r].opener,e)?t=r+1:i=r}let r=t>0?o[t-1]:void 0;return r&&yc(r,e)>0?{sequence:r.sequence,index:r.index+.5}:e}}(e,n,o),l=function(e,t,i){let r=new Map([..._O([...i.values()])].filter(([e])=>!t.has(e))),n=new Map;for(let t of e){let e=t.turnScope?.kind==="turn"?t.turnScope.turnItemId:void 0;if(void 0===e||!r.has(e)||n.has(e))continue;let i="message"===t.body.kind&&"user"===t.body.role,s=yl(t);n.set(e,i?null:{...s,index:s.index-.5})}return new Map([...r].flatMap(([e,t])=>{let i=n.get(e);return i?[[t,i]]:[]}))}(e,o,d),c=[...d.values()].some(e=>void 0===e.submittedSequence)?function(e,t){let i=e.map((e,t)=>({submission:e,order:t})).sort((e,t)=>e.submission.submittedAt-t.submission.submittedAt||e.order-t.order),r=new Map,n;for(let{submission:e}of i){let i=yn(e.clientMessageId);n&&r.set(i,n);let s=t.get(i);s&&(!n||yd(s,n)>0)&&(n=s)}return r}(i,o):void 0,e=>{let t=o.get(e);if(!t)return{opensTurn:!1};let i=yl(t),r=o.get(s.get(e)??""),n=r?_q(t,r):l.get(e);if(n)return 0!==yc(i,n)?{opensTurn:!0,position:n}:{opensTurn:!0};let d=c?.get(e),u=d?yl(d):void 0,h=a(u&&yc(u,i)>0?{sequence:u.sequence,index:u.index+.5}:i);return 0!==yc(h,i)?{opensTurn:!1,position:h}:{opensTurn:!1}}):null,f=function(e,t,i=[]){let r=new Map,n=e=>JSON.stringify([function(e,t){let i=0,r=t.length;for(;i0?t[i-1]:0}(e.acceptedSequence??0,i),e.payloadFingerprint]);for(let[t,i]of e.entries())if(!_C(i)){let e={index:t,submittedAt:i.submittedAt},s=r.get(n(i));s?s.push(e):r.set(n(i),[e])}let s=new Set;for(let[i,o]of e.entries()){let{resolvedAt:e}=o;"rejected"!==o.dispatchState||_C(o)||void 0!==o.queuedMessageId||void 0!==o.keptAsQueuedMessageId||t.has(yn(o.clientMessageId))||null!==e&&(r.get(n(o))??[]).some(t=>t.index>i&&t.submittedAt>=e)||s.add(yn(o.clientMessageId))}return s}(i,new Set(e.filter(e=>"message"===e.body.kind&&e.body.command).map(e=>e.itemId)),e.filter(e=>_M(e.body)).map(e=>e.sequence)),p=[],m=[];for(let t of e)f.has(t.itemId)?m.push(t):u.has(t.itemId)||p.push(t);let g=new Set(p.map(e=>e.itemId)),b=new Set(i.filter(yh).map(e=>yn(e.clientMessageId))),v=[],y=[],_=new Set,w=!1;for(let e of r(p))if(b.has(e.id))y.push({...e,queued:!0});else if(h&&d.has(e.id)){let{opensTurn:t,position:i}=h(e.id);w||=void 0!==i,t||_.add(e.id),v.push({...e,stoppedBeforeStart:!0,...i?{journalPosition:i}:{}})}else v.push(e);_.size>0&&(w=function(e,t,i){let r=new Map;e.forEach((e,t)=>{i.has(e.id)&&r.set(e.id,t)});let n=yu([...t].flatMap(([e,t])=>{let i=r.get(e);return void 0===i?[]:[{index:i,submission:t}]}),({submission:e})=>e),s,o=!1;for(let{index:t}of n){let i=e[t],r=i.journalPosition;r&&(s&&0>=yc(r,s)?(s={sequence:s.sequence,index:s.index+1/1024},e[t]={...i,journalPosition:s},o=!0):s=r)}return o}(v,d,_)||w);let S=w?Array.from(Q8(v)).sort(Q9):Q8(v),x=_.size>0?S.flatMap((e,t)=>_.has(e.id)&&!_.has(S[t+1]?.id??"")?[e,{id:`stopped-before-start:${e.id}`,role:"system",source:"transcript",timestamp:e.timestamp,blocks:[{type:"text",text:"Stopped manually",presentation:_z}],...e.journalPosition?{journalPosition:e.journalPosition}:{}}]:[e]):S;return[...m.length>0?function(e,t){t.sort(Q9);let i=[],r=0;for(let n of e){for(;rQ9(t[r],n);)i.push(t[r++]);i.push(n)}return i.concat(t.slice(r))}(x,r(m).map(e=>({...e,unsent:!0}))):x,...y,...t.filter(e=>!g.has(yn(e.clientMessageId))&&!i.some(t=>t.clientMessageId===e.clientMessageId)).map(e=>({id:yn(e.clientMessageId),role:"user",source:"transcript",timestamp:e.queuedAt,blocks:e.body.blocks,...e.sentWhileStopping?{sentWhileStopping:!0}:{}}))]})(O,W.optimistic,S.submissions,js),[O,W.optimistic,S.submissions]),N=_A(S),$=function({items:e,submissions:t,latestTurn:i,working:r,hostClock:n},s){let{settledTurns:o,runningTiming:a}=(0,Fp.useMemo)(()=>{let r,n;return r=function(e,t=[]){let i=_F(e,t),r=new Map,n=new Map,s;for(let t of e){let e=i.get(t.itemId),o=void 0===e?null:yx(t.body);if(void 0===e||!o)continue;let a=Fm(t,s);s=a?.completedAt??t.observedAt,n.set(o.turnId,a),(a||"unverifiable"===o.state)&&r.set(e,a)}return{byAnchor:r,byTurnId:n}}(e,t),n=null===s||r.byTurnId.has(s)||i?.turn.turnId!==s?null:i,{settledTurns:function(e,t){let i=new Map;for(let[t,r]of e.byAnchor){let e=r&&("completed"===r.state||"interrupted"===r.state)?void 0!==r.requestedAt&&void 0!==r.completedAt?Math.max(0,Math.floor((r.completedAt-Fg(r))/1e3)):void 0!==r.durationMs?Math.floor(r.durationMs/1e3):void 0!==r.completedAt?Math.max(0,Math.floor((r.completedAt-Fg(r))/1e3)):null:null;i.set(t,null===e||null===r?null:{startedAt:r.startedAt,workedSeconds:e,...r.verdict?{verdict:r.verdict}:{}})}for(let e of t){let t=yn(e.clientMessageId);"rejected"!==e.dispatchState||i.has(t)||i.set(t,null)}return i}(r,t),runningTiming:n?Fm({body:{kind:"turn",...n.turn},observedAt:n.observedAt},void 0):null===s?null:r.byTurnId.get(s)??null}},[e,t,s,i]),l=(0,Fp.useMemo)(()=>({items:e,submissions:t,latestTurn:i,...void 0!==r?{working:r}:{}}),[e,t,i,r]),[c,d]=(0,Fp.useState)(null),u=function(e){var t,i,r,n;let s,{timing:o,turnId:a,latch:l}=e;if(null===a)return{latch:null,workingStartedAt:null};let c=l?.turnId===a?l:{turnId:a,firstSeenAt:t=e.now(),...(i=e.hostClock)?{hostNow:i.hostNow+(t-i.receivedAt)}:{}};return{latch:c,workingStartedAt:o?(r=c.firstSeenAt,n=c.hostNow,s=Fg(o),r-Math.max(0,void 0!==n&&Number.isFinite(n)?n-s:o.observedAt-s)):null}}({timing:a,turnId:s,now:Date.now,hostClock:n,latch:c});return u.latch!==c&&d(u.latch),{settledTurns:o,turnJournal:l,workingStartedAt:u.workingStartedAt}}({...S,items:O},N),q=function(e,t,i){if(!t||i?.turnId!==t)return null;let r=jc(i.text);if(!r)return null;let n=e.findLastIndex(e=>{let i=yx(e.body);return i?.turnId===t&&"running"===i.state});return!function(e,t){let i=e.toLowerCase();for(let e of t)if(i===e||i.startsWith(`${e} `)||i.endsWith(` ${e}`)||i.includes(` ${e} `))return!0;return!1}(r,function(e){let t=new Set,i=!1,r=!1;for(let n=e.length-1;n>=0&&(!i||!r);n-=1){let s=e[n]?.body;if(s?.kind!=="tool-call")continue;let o="running"===s.state;if(o&&i||!o&&r)continue;let a=kR({type:"tool-call",name:s.name,input:s.input,state:s.state});for(let e of[kC[a.key].replaceAll("{{preview}}",a.preview).replaceAll("{{toolName}}",a.toolName),a.preview,a.preview?`${a.toolName} ${a.preview}`:a.toolName]){let i=jc(e)?.toLowerCase();i&&t.add(i)}i||=o,r||=!o}return t}(e.slice(Math.max(0,n)).filter(bU)))?{kind:"description",text:r}:null}(S.items,N,S.activity)?.text??null,K=function({items:e,latestTurn:t}){let i=void 0===t?null:t?.turn.state==="running",r=null;for(let t=e.length-1;t>=0;t-=1){let n=e[t],s=n?.body;if(_M(s))return!1;let o=yx(s);if(o)return(i??"running"===o.state)&&!0===r;null===r&&bU(n)&&(s?.kind==="message"?r="reasoning"===s.role&&(void 0===s.state||"running"===s.state):(s?.kind==="tool-call"||s?.kind==="diff"||s?.kind==="approval"||s?.kind==="question")&&(r=!1))}return!0===i&&!0===r}(S),V=(t=S.working,i=()=>{var e,t;return e=S.submissions,t=S.fence,null!==N||e.some(e=>!!yh(e)||(null==t||e.fence>=t)&&("pending"===e.dispatchState||"unknown"===e.dispatchState&&!0!==e.recovered&&"host_restarted_before_acknowledgement"!==e.reason))},t??i()),U=function(e){let{connected:t,mutate:i,sessionKey:r,state:n,turnId:s}=e,o=(0,FX.useMemo)(()=>(function(e,t,i=Tu){let r=e?.state==="monitoring",n=r&&e.children?Th(e.children,i,e=>e.providerId):void 0,s=Th(e?.tasks??Td,i,e=>e.id),o=!n&&!s.length&&!!e?.settledTasks?.length,a=i.size>0&&!n?.length&&!s.length&&!!(e?.children?.length||e?.tasks?.length),l=r&&!0===e.incomplete,c=r&&(l||!o&&!a),d=n?null!==z(n):c,u=e?.supportsTaskStop===!0;return{show:c,isMonitoring:null===t&&d,tasks:s,settledTasks:Td,...n?{children:n}:{},supportsStop:u,offersStopAll:!u&&e?.supportsStopAll!==!1||l&&null===t,incomplete:l}})(n.backgroundTasks,s),[n.backgroundTasks,s]),a=t&&"ready"===n.status,l=n.hostClock,c=l?1e3*Math.round((l.receivedAt-l.hostNow)/1e3):0,d=(0,FX.useMemo)(()=>({parentEvidenceFresh:!0,transportObservation:a?"live":"unverifiable",parentObservedAt:0,hostClockOffsetMs:c}),[a,c]),u=(0,FX.useCallback)(e=>i("agentSession.cancel","agentSession.cancel",{turnId:"background-tasks",scope:"background-tasks",...e?{taskId:e}:{}}),[i]);return(0,FX.useMemo)(()=>({sessionKey:r,view:o,rowContext:d,stop:u}),[r,o,d,u])}({sessionKey:y,state:S,turnId:N,connected:a,mutate:M}),Z=function(e){let{client:t,sessionId:i,enabled:r}=e,n=r&&t&&i?jG(t):null,s=(0,jU.useCallback)(e=>n?n.subscribe(e):()=>{},[n]),o=()=>{let e=n&&i?n.getSnapshot().get(i):void 0;return e?.status==="working"&&!0===e.stopping};return(0,jU.useSyncExternalStore)(s,o,o)}({client:o,sessionId:l,enabled:d&&a&&f?.statusFeed===!0}),G=function(e){let[t,i]=(0,jV.useState)(null),r=(0,jV.useRef)(null),n=(0,jV.useCallback)(async t=>{let n=Symbol("stop-press");r.current=n,i({sessionKey:e,token:n});try{return await t()}finally{r.current===n&&(r.current=null,i(null))}},[e]);return{pressed:t?.sessionKey===e,track:n}}(y),Y="stopping"==((r={working:V,hostStopping:Z,stopPressed:G.pressed}).working?!0===r.hostStopping||!0===r.stopPressed?"stopping":"working":"not-working"),X=V&&G.pressed,J=function(e){let{accept:t,agent:i,client:r,commandPending:n,commandsWait:s,controller:o,enabled:a,hold:l,onSendError:c,queueCapable:d,carriesOptions:u,sessionId:h,stateRef:f,stopping:p}=e;return(0,F_.useCallback)(async(e,m,g,b)=>{var v;let y=f.current.fence;if(!r||!h||!a||null===y)return c("Message not sent (disconnected)"),"rejected";let _=jz(g);if(null===_||void 0===b&&void 0!==m&&m.length>0)return c("Message not sent"),"rejected";let w=b??[],S=await FT({text:e,hasAttachments:!!(w.length||m?.length),client:r,sessionId:h,fence:y,pending:n,controller:{agent:i??void 0,...o},busy:()=>jw(f.current)||jS(f.current)?"prompt":_A(f.current)?"working":null,waitsInLine:e=>"compact"===e&&s&&!xO(jf(f.current)),onError:c,timeoutMs:_});if(null!==S)return S;let x=[],T=[];for(let e of w)"file"===e.kind?T.push(e):x.push(e);let k=function(e,t){if(0===t.length)return e;let i=t.map(e=>eC(e.path)).join(" ");return 0===e.trim().length?i:`${e.trimEnd()} ${i}`}(e,T),C=FS(k,x);if(0===C.blocks.length)return"rejected";let L={clientMessageId:tm(),body:C,queuedAt:Date.now(),...p?{sentWhileStopping:!0}:{}},M=u&&i?function(e,t){if("claude"!==e)return;let i=e=>{let i=t.find(t=>t.id===e)?.kind;return i?.type==="select"?i.currentValue:void 0},r=i("model"),n=i("effort");return r?{model:r,...n?{effort:n}:{}}:void 0}(i,o.snapshot):void 0,R=await Fk({client:r,sessionId:h,expectedRuntimeFence:y,text:k,attachments:x,...(v=f.current,d&&!xO(jf(v)))?{delivery:"queue-if-active"}:{},...M?{options:M}:{},deadline:g,clientMessageId:L.clientMessageId,onAccepted:e=>t({...L,...e?{recordedCursor:e}:{}},m),onError:c});return"unknown"===R&&l(L),R},[t,i,r,n,s,o,a,l,c,d,u,h,f,p])}({agent:n,client:o,sessionId:l,enabled:d,queueCapable:p,commandsWait:m,stateRef:x,stopping:Y,accept:W.accept,hold:W.hold,commandPending:_,controller:B,onSendError:h,carriesOptions:f?.sendOptions===!0}),ee=(0,Q4.useMemo)(()=>({thinking:K,activityText:q,stopping:Y,stopRequestInFlight:X,...Y?{afterStop:p&&!xO(jf(S))?"queue":"send"}:{}}),[K,q,Y,X,p,S]),{items:et,currentRequests:ei,actionablePromptIds:er,status:en}=S,[es,eo]=(0,Q4.useMemo)(()=>{let e={items:et,currentRequests:ei,actionablePromptIds:er};return[jw(e),jS(e)]},[et,ei,er]),ea=(0,Q4.useMemo)(()=>({working:null!==N,prompt:null!==es||null!==eo}),[es,eo,N]),el=function(e){let{appendComposerText:t,mutate:i,onActionResolved:r,onSendError:n,queuedMessages:s,queuePause:o,sessionKey:a,submissions:l}=e,c=!0===e.agentWorking,d=(0,FI.useMemo)(()=>(function(e,t,i={}){if(!e||0===e.length)return[];let r=new Set(t.flatMap(e=>void 0!==e.queuedMessageId&&"rejected"!==e.dispatchState?[e.queuedMessageId]:[])),n=!1,s=[];for(let t of e){var o,a;if("returned"!==t.state&&r.has(t.messageId))continue;let e=!0===t.paused,l="returned"===t.state?function(e,t,i=[]){let r=e.returnedReason??null,n=e.returnedRejection;return Rw(n,i)?Rv(Rm("send")):_C({dispatchState:"rejected",reason:r,rejection:n})?"Stopped before it was sent":Rv(function(e,t={},i){return RS(e.reason,"send",i,t)}({kind:"rejected",reason:r},{agentName:t,retryControl:!0},_b(n)))}(t,i.agentName,i.statedFailures):e?(o=t.pausedReason,a=void 0!==t.body.command&&!0===i.agentWorking,o===jT?a?"Couldn't send — tap Send to retry once the agent finishes":"Couldn't send — tap Send to retry":"Paused"):n?"Waiting — a message ahead needs attention":null;s.push({messageId:t.messageId,text:t.body.blocks.flatMap(e=>"text"===e.type?[e.text]:[]).join(` diff --git a/phone-host/bundle/assets/48fae3d9447c3e75964d9031d9ede8a0d784d091f9c0b0625c12d3a73b621247.js b/phone-host/bundle/assets/393753fcec4b8acaddf3b0214cba3fa3814b945530e46703eebfef26582ef924.js similarity index 99% rename from phone-host/bundle/assets/48fae3d9447c3e75964d9031d9ede8a0d784d091f9c0b0625c12d3a73b621247.js rename to phone-host/bundle/assets/393753fcec4b8acaddf3b0214cba3fa3814b945530e46703eebfef26582ef924.js index df7218c6b7..a68b0dd5fe 100644 --- a/phone-host/bundle/assets/48fae3d9447c3e75964d9031d9ede8a0d784d091f9c0b0625c12d3a73b621247.js +++ b/phone-host/bundle/assets/393753fcec4b8acaddf3b0214cba3fa3814b945530e46703eebfef26582ef924.js @@ -621,4 +621,4 @@ Return JSON only. A person will review and explicitly apply the result to the de padding-bottom:2px; } } -`;function rz({name:e}){return(0,ry.jsx)("span",{"data-tool-icon":!0,"aria-hidden":"true",children:(0,ry.jsx)("svg",{viewBox:"0 0 24 24",width:"22",height:"22",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:(0,ry.jsx)("path",{d:{help:"M16 10a6 6 0 1 0-12 0 6 6 0 0 0 12 0zM15 15l5 5",desktops:"M3 4h18v13H3zM8 21h8M12 17v4",account:"M20 21v-2a7 7 0 0 0-14 0v2M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0",ruflo:"M4 6h16M4 12h16M4 18h16M8 3v6M16 9v6M10 15v6",teams:"M12 7a3 3 0 1 0 0-6 3 3 0 0 0 0 6M5 21a7 7 0 0 1 14 0M4 13a2.5 2.5 0 1 0 0-5M20 13a2.5 2.5 0 1 0 0-5",walkthrough:"M5 3h14v18H5zM10 8l5 4-5 4z",demo:"M3 3h8v10H3zM15 3h6v6h-6zM3 17h8v4H3zM15 13h6v8h-6z"}[e]})})})}var rO=es(eo()),rA=es(X()),rM=es(ee()),rT=class{held=null;listeners=new Set;read(){return this.held}prime(e){let t=this.held?.state!==e.state;this.held=e,t&&this.fanOut(e.state)}apply(e){let t=this.held;return null===t?"unprimed":null!==t.generation&&null!==e.generation&&e.generation{this.listeners.delete(e)}}close(){let e=this.held;null!==e&&"disconnected"!==e.state&&(this.held={...e,state:"disconnected"},this.fanOut("disconnected")),this.listeners.clear()}fanOut(e){for(let t of this.listeners)t(e)}},rP=class extends Error{constructor(){super("the page bridge has no session yet; wait for init before calling the client"),this.name="BridgeClientNotReadyError"}},r_=class extends Error{constructor(){super("the page bridge was closed"),this.name="BridgeClientClosedError"}},rL=class extends Error{constructor(){super("the shell behind this page was replaced"),this.name="BridgeShellReplacedError"}},rq=class extends Error{constructor(e){super(e),this.name="BridgeClientCapExceededError"}},rD=class extends Error{constructor(e){super(`the reply could not be read (${e})`),this.name="BridgeReplyRefusedError",M(this)}},rF=class extends Error{constructor(){super("the request could not be posted to the shell"),this.name="BridgeSendFailedError"}},rW=class extends Error{code="bridge_request_oversized";constructor(){super("This action sends too much at once to reach RuFlo. Try it on fewer files."),this.name="BridgeRequestOversizedError"}},rH=class extends Error{code="native_verb_not_a_verb";constructor(e){super(`${e} is not a native verb`),this.name="BridgeClientNotNativeVerbError"}},rU=class extends Error{code="bridge_rpc_envelope_ungranted";constructor(){super("this app version cannot send extra request fields; update the RuFlo app"),this.name="BridgeRpcEnvelopeUngrantedError"}},rB=class extends Error{code="bridge_rpc_envelope_invalid";constructor(){super("extra request fields must be a plain JSON object"),this.name="BridgeRpcEnvelopeInvalidError"}},r$=4*F,rV=class{pending=new Map;refused=new Map;accept(e){let t=this.refused.get(e.id);if(void 0!==t)return{status:"failed",refusal:t};if(!("part"in e))return this.pending.delete(e.id),{status:"complete",payload:e.payload};let{id:a,part:r,chunk:o}=e,n=this.pending.get(a);if(r.i>=r.of||void 0!==n&&n.of!==r.of)return this.fail(a,"inconsistent-part");if(void 0===n&&this.pending.size>=q)return this.fail(a,"too-many-pending");let s=n??{of:r.of,chunks:new Map,units:0};if(s.chunks.has(r.i))return this.fail(a,"duplicate-part");if(this.assemblingUnits()+o.length>r$)return this.fail(a,"too-many-pending");let i=s.units+o.length;return i>F?this.fail(a,"reply-too-large"):(s.chunks.set(r.i,o),s.units=i,this.pending.set(a,s),s.chunks.sizee-t).map(([,e])=>e).join("");if(W(a)>F)return{status:"failed",refusal:"reply-too-large"};try{t=JSON.parse(a)}catch{return{status:"failed",refusal:"malformed-json"}}let r=j.safeParse(t);return r.success?{status:"complete",payload:r.data}:{status:"failed",refusal:"unrecognised-message"}}(s)))}discard(e){this.pending.delete(e),this.refused.delete(e)}clear(){this.pending.clear(),this.refused.clear()}assemblingUnits(){let e=0;for(let t of this.pending.values())e+=t.units;return e}fail(e,t){if(this.pending.delete(e),this.refused.size>=q){let e=this.refused.keys().next();e.done||this.refused.delete(e.value)}return this.refused.set(e,t),{status:"failed",refusal:t}}},rG=class{pending=new Map;assembler=new rV;get size(){return this.pending.size}has(e){return this.pending.has(e)}open(e,t){this.pending.set(e,t)}abandon(e){this.pending.delete(e)}acceptReply(e){let t=this.assembler.accept(e);if("pending"===t.status){this.pending.has(e.id)||this.assembler.discard(e.id);return}"failed"===t.status?this.fail(e.id,new rD(t.refusal)):this.settle(e.id,e=>{e.resolve(t.payload)})}fail(e,t){this.settle(e,e=>{e.reject(t)})}closeAll(e=new r_){let t=M(e);for(let e of this.pending.values())e.reject(t);this.pending.clear(),this.assembler.clear()}settle(e,t){this.assembler.discard(e);let a=this.pending.get(e);void 0!==a&&(this.pending.delete(e),t(a))}};function rK(e,t){if(void 0===e)return;let a=h.safeParse(e);if(!a.success)throw new rB;if(0!==Object.keys(a.data).length){if(!t(k))throw new rU;return a.data}}function rY(e,t){return void 0===t?{type:"error",message:e}:{type:"error",message:e,error:t}}var rJ=class{constructor(e){this.options=e}options;streams=new Map;get size(){return this.streams.size}has(e){return this.streams.has(e)}open(e,t,a,r,o,n){return this.streams.set(e,{onData:r,onBinaryFrame:o,lastSeq:0,unackedFrames:0,unackedBytes:0}),!!this.options.send({v:f,type:"subscribe",id:e,method:t,params:a,...void 0===o?{}:{wantsBinary:!0},...void 0===n?{}:{envelope:n}})||(this.streams.delete(e),r(rY("the subscribe could not be posted to the shell")),!1)}deliver(e,t){let a=this.streams.get(e.id);if(void 0!==a){if(a.lastSeq=e.seq,a.unackedFrames+=1,a.unackedBytes+=t,this.ackIfDue(e.id,a),"binary"in e)return void this.deliverBinary(a,e.binary);a.onData(e.payload)}}end(e,t,a){let r=this.streams.get(e);void 0!==r&&(this.streams.delete(e),r.onData(rY(t,a)))}abandon(e,t,a){let r=this.streams.get(e);void 0!==r&&(this.cancel(e),r.onData(rY(t,a)))}cancel(e){this.streams.delete(e)&&this.options.send({v:f,type:"cancel",id:e,target:"subscription"})}closeAll(){this.streams.clear()}failAll(e){let t=this.streams;for(let a of(this.streams=new Map,t.values()))a.onData(rY(e))}deliverBinary(e,t){let a,r=e.onBinaryFrame;if(void 0===r)return void this.options.onDroppedBinaryFrame();let o=null===(a=function(e){let t;try{t=atob(e)}catch{return null}let a=new Uint8Array(t.length);for(let e=0;e()=>{});function r1({report:e,children:t}){return(0,rX.jsx)(r0.Provider,{value:e,children:t})}function r2(e){let t=e.default;return{default:function(e){let a=(0,rZ.useContext)(r0);return(0,rZ.useEffect)(()=>a(),[a]),(0,rX.jsx)(t,{...e})}}}var r4=es(eo()),r6=class extends r4.Component{state={faulted:!1};static getDerivedStateFromError(){return{faulted:!0}}componentDidCatch(e){this.props.onFault(e)}render(){return this.state.faulted?null:this.props.children}},r8=es(eo()),r3={"./_layout.tsx":{default:(0,r8.lazy)(()=>import("/assets/1d37541fcf09b7d464600e9b2171e267e031198335cf20983c94696b6e2f6fb7.js"))},"./h/[hostId]/[...page].tsx":{default:(0,r8.lazy)(()=>import("/assets/c3f3bffb9ef60f82fcea02de055109409f5a561423c1c2edc7a651058e80321a.js").then(r2))},"./h/[hostId]/accounts.tsx":{default:(0,r8.lazy)(()=>import("/assets/4405dbd1a8c01298144be65b1ee2f2298f33b8fe39e194465d4db7b16dd6050f.js").then(r2))},"./h/[hostId]/agent-history/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/f1a251abcb4bb2c1316806cdef71e01a77dff27c5e390f54b73ede6bfa71154c.js").then(r2))},"./h/[hostId]/edit.tsx":{default:(0,r8.lazy)(()=>import("/assets/a942603319844e9aaec9d932e14335c9b44eefb850257ea29aba6f52914f3cb1.js").then(r2))},"./h/[hostId]/files/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/2473e3361965b8db2d910f8772ad561b5c862c6712327b57b4c71b41b09711ff.js").then(r2))},"./h/[hostId]/files/preview/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/5184c92fd49169d698ce36be1f0831cd3321cdbe359f5f63cd21ac642616dc37.js").then(r2))},"./h/[hostId]/history/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/301f677d57709861ad8206cd37d413c7ccbc114ca3e79d8744ac558b209dd430.js").then(r2))},"./h/[hostId]/index.tsx":{default:(0,r8.lazy)(()=>import("/assets/453999a244b592464c56a7cfde13f1d02cc068236cb56e819e63a842525eedc1.js").then(r2))},"./h/[hostId]/pr/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/f0886d78eca829b5a6bebc1105197b6acc05c75ba4e1baa00003a08a532d31a7.js").then(r2))},"./h/[hostId]/review/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/c5fc0821f14cbcb3cd66c98153640ddce383f236465173b4ed66e6e0e66994d7.js").then(r2))},"./h/[hostId]/session/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/ff5bafc87134b6a566c67255bb9546eabc92bd5b335b13af7d063abaa4a9fd20.js").then(r2))},"./h/[hostId]/source-control/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/b75c3c6bd8b17c1c93e13060c58bb5df119b3729daafe457a3c65afdb4018968.js").then(r2))},"./h/[hostId]/tasks.tsx":{default:(0,r8.lazy)(()=>import("/assets/5152a5cb84bc3d3016abe04383658f817ff5fa4fe3553c63311080e1c9bf48d5.js").then(r2))},"./h/_layout.tsx":{default:(0,r8.lazy)(()=>import("/assets/77efe1035a95d226958585d9cddcf171ccc0326f95ae939818c28ff806f7ed16.js"))}},r5=Object.keys(r3);function r9(e){if(!Object.prototype.hasOwnProperty.call(r3,e))throw Error("[orca-mobile-web-app] no route module for "+e);return r3[e]}r9.keys=()=>r5.slice(),r9.resolve=e=>{if(!Object.prototype.hasOwnProperty.call(r3,e))throw Error("[orca-mobile-web-app] cannot resolve route "+e);return e},r9.id="orca-mobile-web-app-routes";var r7=es(en()),oe=document.createElement("style");oe.textContent=Y,document.head.append(oe);var ot=document.getElementById("root");if(!ot)throw Error("[orca-mobile-web-app] #root missing");var oa=document.documentElement;oa.style.setProperty("--muted-foreground",J.textMuted),oa.style.setProperty("--foreground",J.textPrimary),rQ(oa,"started"),function(e){let{target:t,client:a,replaceUrl:r,mount:o,refuseUnroutedShell:n}=e;if(null===a)return rQ(t,"unbridged");let s=()=>{var e;let s,i=a.getShellSession();return null!==i&&(t.dataset.orcaWebSessionId=i.sessionId,t.dataset.orcaWebBuildId=i.buildId,null===i.route?(rQ(t,"shell-too-old"),n()):(r(""===(s=new URLSearchParams((e=i.route).params??{}).toString())?e.pathname:`${e.pathname}?${s}`),rQ(t,"shell-ready"),o(a,i)),!0)};s()||a.onReady(()=>{s()})}({target:oa,client:null===(t=void 0===(e=globalThis.orcaBridge)||"function"!=typeof e.postMessage?null:e)?null:function(e){var t;let a,r,o,n,s,i,l=new rG,d=new rT,c=!1,h=0;function j(t){e.onDiagnostic?.(t)}function N(t){try{let a=JSON.stringify(t);return H(a)?(e.send(a),"sent"):(j({kind:"send-oversized",bytes:W(a)}),"oversized")}catch(e){return j({kind:"send-failed",error:e}),"port-failed"}}let R=e=>B.current()?.grants.native.includes(e)===!0,E=e=>"sent"===N(e);function O(){return(h+=1).toString(36).padStart(22,"0")}let A=new rJ({send:e=>E(e),onDroppedBinaryFrame:()=>{j({kind:"binary-frame-dropped"})}}),M=function(e){let t=null,a=50;function r(){e(),t=setTimeout(()=>{a=Math.min(2*a,2e3),r()},a)}function o(){null!==t&&(clearTimeout(t),t=null)}return{start:r,stop:o,restart:()=>{o(),a=50,r()}}}(()=>{N({v:f,type:"ready"})});function P(){if(null===B.current()&&!c)throw new rP}function F(){let e=d.read();if(null===e)throw new rP;return e}let B=(t={onReplaced:()=>{let e=new rL;l.closeAll(e),A.failAll(e.message)},prime:e=>{d.prime(e)}},a=null,r=new Set,o=new Set,n=new Set,s=new Set,i=new Set,{current:()=>a,accept:e=>{let l=a,d=null!==l&&l.sessionId===e.sessionId?l:null;null!==l&&null===d&&t.onReplaced();let c=e.safeAreaInsets??I,p=null!==l&&!z(l.safeAreaInsets,c),h=null===l||p?c:l.safeAreaInsets,m=e.keyboardInset??0,g=null!==l&&l.keyboardInset!==m;for(let r of(a=null===d?{...{sessionId:e.sessionId,buildId:e.buildId,grants:e.grants,route:e.route??null,pageRoutes:e.pageRoutes??[],pageRouteGrants:e.pageRouteGrants??null,safeAreaInsets:e.safeAreaInsets??I,keyboardInset:e.keyboardInset??0,host:e.host??null,storage:e.storage??{},storageOversize:e.storageOversize??[],ownsHostArea:!0===e.ownsHostArea},safeAreaInsets:h}:{...d,route:e.route??null,safeAreaInsets:h,keyboardInset:m},t.prime(e.connection),o))r();for(let e of r)e();if(r.clear(),p)for(let e of s)e(h);if(g)for(let e of i)e(m);if(!(null===d||!u(d.route,a.route)))for(let e of n)e(a.route)},onReady:e=>null!==a?(e(),()=>{}):(r.add(e),()=>{r.delete(e)}),onRouteUpdate:e=>(n.add(e),()=>{n.delete(e)}),onShellSessionChange:e=>(o.add(e),()=>{o.delete(e)}),onSafeAreaInsetsUpdate:e=>(s.add(e),()=>{s.delete(e)}),onKeyboardInsetUpdate:e=>(i.add(e),()=>{i.delete(e)}),close:()=>{a=null,r.clear(),o.clear()}}),$=function(e){let t=[];function a(a){0===a!=(0===t.length)&&e.publishClaim(t.length>0)}return{claim:e=>{let r={consumer:e},o=t.length;return t.push(r),a(o),()=>{let e=t.indexOf(r);if(-1===e)return;let o=t.length;t.splice(e,1),a(o)}},press:()=>{t.toReversed().some(e=>e.consumer())||e.onUnclaimed()},reassert:()=>{t.length>0&&e.publishClaim(!0)},clear:()=>{let e=t.length;t.length=0,a(e)}}}({publishClaim:e=>K.notifyBackClaim(e),onUnclaimed:()=>{j({kind:"back-unclaimed"}),K.notifyNavigateBack()}}),V=function(e){let{requests:t,subscriptions:a,report:r}=e;function o(e,o,n){if(a.has(e)){r({kind:"stream-failed",error:o});let t=o instanceof Error?o.message:"the shell could not keep this stream open";n?a.end(e,t,o):a.abandon(e,t,o);return}t.has(e)||r({kind:"unknown-id"}),t.fail(e,o)}return n=>{let s=C(n);if(s.ok)return void function(n,s){switch(n.type){case"init":e.acceptInit(n);return;case"state":e.acceptState(n.connection);return;case"back":e.acceptBack();return;case"reply":t.has(n.id)||r({kind:"unknown-id"}),t.acceptReply(n);return;case"error":o(n.id,g(n.error),!0);return;case"event":a.deliver(n,W(s));return;case"end":r({kind:"stream-ended",reason:n.reason}),a.end(n.id,`the shell ended this stream (${n.reason})`);return}}(s.message,n);r({kind:"refused",refusal:s.refusal});let i=S(n);null!==i&&(t.has(i)||a.has(i))&&o(i,new rD(s.refusal),!1)}}({requests:l,subscriptions:A,report:j,acceptInit:e=>{M.stop(),B.accept(e),$.reassert()},acceptState:function(e){"stale"===d.apply(e)&&(j({kind:"state-out-of-order"}),M.restart())},acceptBack:$.press});function G(...e){if(P(),c)return Promise.reject(new r_);if(l.size>=q)return Promise.reject(new rq(`over ${q} requests in flight`));let[t,a,r]=e;return new Promise((o,n)=>{let s=function(e,t){if(void 0===e)return{};let{envelope:a,...r}=e,o=rK(a,t);return{...void 0!==a&&0===Object.keys(r).length?{}:{options:r},...void 0===o?{}:{envelope:o}}}(r,R),i=O();l.open(i,{resolve:o,reject:n});let d=N({v:f,type:"request",id:i,method:t,...e.length>1?{params:a}:{},...s});"sent"!==d&&(l.abandon(i),n("oversized"===d?new rW:new rF))})}let K=function(e){function t(t){return e.requireSession(),!e.isClosed()&&e.send(t)}return{updateTerminalSubscriptionViewport:(e,a)=>{t({v:f,type:"notify",name:"terminalViewport",terminal:e,cols:a.cols,rows:a.rows})},notifyForeground:e=>{t({v:f,type:"notify",name:"foreground",...void 0===e?{}:{reason:e}})},notifyNavigate:a=>e.hasGrant("navigate")&&t({v:f,type:"notify",name:"navigate",href:a}),notifyNavigateBack:()=>e.hasGrant("navigate")&&t({v:f,type:"notify",name:w}),notifyExternalLink:a=>{if(!e.hasGrant(y))return!1;let r=L(a);return null!==r&&t({v:f,type:"notify",name:y,url:r})},notifyStorageWrite:(a,r)=>e.hasGrant("storage")&&t({v:f,type:"notify",name:"storage",key:a,value:r}),notifyHaptics:a=>e.hasGrant(U)&&t({v:f,type:"notify",name:T,kind:a}),notifyPageFault:t=>!e.isClosed()&&!!e.hasGrant(v)&&e.send({v:f,type:"notify",name:v,error:m(t)}),notifyPagePainted:()=>{t({v:f,type:"notify",name:b})},notifyBackClaim:e=>{t({v:f,type:"notify",name:x,claimed:e})}}}({send:E,requireSession:P,isClosed:()=>c,hasGrant:R}),Y=e.onMessage(function(e){if(!c)try{V(e)}catch(e){j({kind:"inbound-listener-threw",error:e})}});return M.start(),{sendRequest:G,subscribe:function(e,t,a,r){if(P(),c)return()=>{};if(A.size>=D)throw new rq(`over ${D} subscriptions`);let{onBinaryFrame:o,envelope:n}=r??{},s=rK(n,R),i=O();if(!A.open(i,e,t,a,o,s))return()=>{};let l=!1;return()=>{l||(l=!0,A.cancel(i))}},updateTerminalSubscriptionViewport:K.updateTerminalSubscriptionViewport,getState:()=>F().state,getReconnectAttempt:()=>F().reconnectAttempt,getLastConnectedAt:()=>F().lastConnectedAt,getLastInboundAt:()=>F().lastInboundAt,getGeneration:()=>F().generation??0,carriesRpcEnvelope:()=>R(k),onStateChange:e=>d.onStateChange(e),notifyForeground:K.notifyForeground,notifyNavigate:K.notifyNavigate,notifyNavigateBack:K.notifyNavigateBack,notifyExternalLink:K.notifyExternalLink,callNativeVerb:(e,t)=>_(e)?G(e,t).then(e=>{if(!e.ok)throw Error(e.error.message);return e}):Promise.reject(new rH(e)),notifyStorageWrite:K.notifyStorageWrite,notifyHaptics:K.notifyHaptics,notifyPageFault:K.notifyPageFault,notifyPagePainted:K.notifyPagePainted,claimBack:$.claim,close:function(){c||(c=!0,M.stop(),$.clear(),A.closeAll(),N({v:f,type:"close"}),l.closeAll(),d.close(),B.close(),Y())},onReady:B.onReady,onRouteUpdate:B.onRouteUpdate,onSafeAreaInsetsUpdate:B.onSafeAreaInsetsUpdate,onShellSessionChange:B.onShellSessionChange,onKeyboardInsetUpdate:B.onKeyboardInsetUpdate,getShellSession:B.current,clearRouteParam:(e,t)=>E({v:f,type:"notify",name:p,param:e,value:t})}}({...{send:e=>{t.postMessage(e)},onMessage:e=>(t.onmessage=t=>{e(t.data)},()=>{t.onmessage=null})},onDiagnostic:(a=new Set,e=>{a.has(e.kind)||(a.add(e.kind),console.warn("[page-bridge]",e.kind,e))})}),replaceUrl:e=>{history.replaceState(null,"",e)},mount:(e,t)=>{var a,r;let o,n,s;B(t.host),E(t=>e.notifyExternalLink(t)),A(t=>e.notifyHaptics(t)),O({read:()=>e.getShellSession()?.keyboardInset??0,subscribe:e.onKeyboardInsetUpdate}),N(t.storage,(t,a)=>e.notifyStorageWrite(t,a),t.host?.id??"",t.route?.pathname??"",t.storageOversize,t.ownsHostArea?async t=>P.parse((await e.callNativeVerb("native.storage.read",{key:t})).result).value:null),K(()=>R.getItem($)),G(()=>R.getItem(V)),(0,rA.createRoot)(ot).render((0,r7.jsx)(r6,{onFault:t=>{e.notifyPageFault(t)},children:(0,r7.jsx)(rM.ExpoRoot,{context:r9,location:new URL(window.location.href),wrapper:(a={requestFrame:e=>requestAnimationFrame(e),cancelFrame:e=>{cancelAnimationFrame(e)}},r=()=>{e.notifyPagePainted()},o=!1,n=null,s=()=>{var e;let t,s;if(o)return()=>{};n?.();let i=(e=()=>{n=null,o=!0,r()},t=!1,s=a.requestFrame(()=>{s=a.requestFrame(()=>{t=!0,e()})}),()=>!t&&(t=!0,a.cancelFrame(s),!0));return n=i,()=>{i()}},function({children:t}){return(0,rO.useEffect)(()=>{rQ(oa,"mounted")},[]),(0,r7.jsxs)(Q,{client:e,children:[(0,r7.jsx)(rC,{client:e}),(0,r7.jsx)(r1,{report:s,children:(0,r7.jsx)("div",{"data-mobile-tools-content":!0,style:{position:"relative",display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,marginBottom:"var(--mobile-tools-clearance, 102px)"},children:t})})]})})})}))},refuseUnroutedShell:()=>{let e,t,a;(e=document.createElement("div")).setAttribute("role","alert"),e.style.cssText="font:16px/1.5 system-ui,-apple-system,sans-serif;color:var(--rupro-textPrimary);background:var(--rupro-bgBase);min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:24px;text-align:center",(t=document.createElement("div")).style.cssText="font-weight:600",t.textContent="Update Orca to open this workspace",(a=document.createElement("div")).style.cssText="color:var(--rupro-textMuted);font-size:14px",a.textContent="This version of the app cannot open the workspace it downloaded.",e.append(t,a),ot.replaceChildren(e)}}); \ No newline at end of file +`;function rz({name:e}){return(0,ry.jsx)("span",{"data-tool-icon":!0,"aria-hidden":"true",children:(0,ry.jsx)("svg",{viewBox:"0 0 24 24",width:"22",height:"22",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:(0,ry.jsx)("path",{d:{help:"M16 10a6 6 0 1 0-12 0 6 6 0 0 0 12 0zM15 15l5 5",desktops:"M3 4h18v13H3zM8 21h8M12 17v4",account:"M20 21v-2a7 7 0 0 0-14 0v2M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0",ruflo:"M4 6h16M4 12h16M4 18h16M8 3v6M16 9v6M10 15v6",teams:"M12 7a3 3 0 1 0 0-6 3 3 0 0 0 0 6M5 21a7 7 0 0 1 14 0M4 13a2.5 2.5 0 1 0 0-5M20 13a2.5 2.5 0 1 0 0-5",walkthrough:"M5 3h14v18H5zM10 8l5 4-5 4z",demo:"M3 3h8v10H3zM15 3h6v6h-6zM3 17h8v4H3zM15 13h6v8h-6z"}[e]})})})}var rO=es(eo()),rA=es(X()),rM=es(ee()),rT=class{held=null;listeners=new Set;read(){return this.held}prime(e){let t=this.held?.state!==e.state;this.held=e,t&&this.fanOut(e.state)}apply(e){let t=this.held;return null===t?"unprimed":null!==t.generation&&null!==e.generation&&e.generation{this.listeners.delete(e)}}close(){let e=this.held;null!==e&&"disconnected"!==e.state&&(this.held={...e,state:"disconnected"},this.fanOut("disconnected")),this.listeners.clear()}fanOut(e){for(let t of this.listeners)t(e)}},rP=class extends Error{constructor(){super("the page bridge has no session yet; wait for init before calling the client"),this.name="BridgeClientNotReadyError"}},r_=class extends Error{constructor(){super("the page bridge was closed"),this.name="BridgeClientClosedError"}},rL=class extends Error{constructor(){super("the shell behind this page was replaced"),this.name="BridgeShellReplacedError"}},rq=class extends Error{constructor(e){super(e),this.name="BridgeClientCapExceededError"}},rD=class extends Error{constructor(e){super(`the reply could not be read (${e})`),this.name="BridgeReplyRefusedError",M(this)}},rF=class extends Error{constructor(){super("the request could not be posted to the shell"),this.name="BridgeSendFailedError"}},rW=class extends Error{code="bridge_request_oversized";constructor(){super("This action sends too much at once to reach RuFlo. Try it on fewer files."),this.name="BridgeRequestOversizedError"}},rH=class extends Error{code="native_verb_not_a_verb";constructor(e){super(`${e} is not a native verb`),this.name="BridgeClientNotNativeVerbError"}},rU=class extends Error{code="bridge_rpc_envelope_ungranted";constructor(){super("this app version cannot send extra request fields; update the RuFlo app"),this.name="BridgeRpcEnvelopeUngrantedError"}},rB=class extends Error{code="bridge_rpc_envelope_invalid";constructor(){super("extra request fields must be a plain JSON object"),this.name="BridgeRpcEnvelopeInvalidError"}},r$=4*F,rV=class{pending=new Map;refused=new Map;accept(e){let t=this.refused.get(e.id);if(void 0!==t)return{status:"failed",refusal:t};if(!("part"in e))return this.pending.delete(e.id),{status:"complete",payload:e.payload};let{id:a,part:r,chunk:o}=e,n=this.pending.get(a);if(r.i>=r.of||void 0!==n&&n.of!==r.of)return this.fail(a,"inconsistent-part");if(void 0===n&&this.pending.size>=q)return this.fail(a,"too-many-pending");let s=n??{of:r.of,chunks:new Map,units:0};if(s.chunks.has(r.i))return this.fail(a,"duplicate-part");if(this.assemblingUnits()+o.length>r$)return this.fail(a,"too-many-pending");let i=s.units+o.length;return i>F?this.fail(a,"reply-too-large"):(s.chunks.set(r.i,o),s.units=i,this.pending.set(a,s),s.chunks.sizee-t).map(([,e])=>e).join("");if(W(a)>F)return{status:"failed",refusal:"reply-too-large"};try{t=JSON.parse(a)}catch{return{status:"failed",refusal:"malformed-json"}}let r=j.safeParse(t);return r.success?{status:"complete",payload:r.data}:{status:"failed",refusal:"unrecognised-message"}}(s)))}discard(e){this.pending.delete(e),this.refused.delete(e)}clear(){this.pending.clear(),this.refused.clear()}assemblingUnits(){let e=0;for(let t of this.pending.values())e+=t.units;return e}fail(e,t){if(this.pending.delete(e),this.refused.size>=q){let e=this.refused.keys().next();e.done||this.refused.delete(e.value)}return this.refused.set(e,t),{status:"failed",refusal:t}}},rG=class{pending=new Map;assembler=new rV;get size(){return this.pending.size}has(e){return this.pending.has(e)}open(e,t){this.pending.set(e,t)}abandon(e){this.pending.delete(e)}acceptReply(e){let t=this.assembler.accept(e);if("pending"===t.status){this.pending.has(e.id)||this.assembler.discard(e.id);return}"failed"===t.status?this.fail(e.id,new rD(t.refusal)):this.settle(e.id,e=>{e.resolve(t.payload)})}fail(e,t){this.settle(e,e=>{e.reject(t)})}closeAll(e=new r_){let t=M(e);for(let e of this.pending.values())e.reject(t);this.pending.clear(),this.assembler.clear()}settle(e,t){this.assembler.discard(e);let a=this.pending.get(e);void 0!==a&&(this.pending.delete(e),t(a))}};function rK(e,t){if(void 0===e)return;let a=h.safeParse(e);if(!a.success)throw new rB;if(0!==Object.keys(a.data).length){if(!t(k))throw new rU;return a.data}}function rY(e,t){return void 0===t?{type:"error",message:e}:{type:"error",message:e,error:t}}var rJ=class{constructor(e){this.options=e}options;streams=new Map;get size(){return this.streams.size}has(e){return this.streams.has(e)}open(e,t,a,r,o,n){return this.streams.set(e,{onData:r,onBinaryFrame:o,lastSeq:0,unackedFrames:0,unackedBytes:0}),!!this.options.send({v:f,type:"subscribe",id:e,method:t,params:a,...void 0===o?{}:{wantsBinary:!0},...void 0===n?{}:{envelope:n}})||(this.streams.delete(e),r(rY("the subscribe could not be posted to the shell")),!1)}deliver(e,t){let a=this.streams.get(e.id);if(void 0!==a){if(a.lastSeq=e.seq,a.unackedFrames+=1,a.unackedBytes+=t,this.ackIfDue(e.id,a),"binary"in e)return void this.deliverBinary(a,e.binary);a.onData(e.payload)}}end(e,t,a){let r=this.streams.get(e);void 0!==r&&(this.streams.delete(e),r.onData(rY(t,a)))}abandon(e,t,a){let r=this.streams.get(e);void 0!==r&&(this.cancel(e),r.onData(rY(t,a)))}cancel(e){this.streams.delete(e)&&this.options.send({v:f,type:"cancel",id:e,target:"subscription"})}closeAll(){this.streams.clear()}failAll(e){let t=this.streams;for(let a of(this.streams=new Map,t.values()))a.onData(rY(e))}deliverBinary(e,t){let a,r=e.onBinaryFrame;if(void 0===r)return void this.options.onDroppedBinaryFrame();let o=null===(a=function(e){let t;try{t=atob(e)}catch{return null}let a=new Uint8Array(t.length);for(let e=0;e()=>{});function r1({report:e,children:t}){return(0,rX.jsx)(r0.Provider,{value:e,children:t})}function r2(e){let t=e.default;return{default:function(e){let a=(0,rZ.useContext)(r0);return(0,rZ.useEffect)(()=>a(),[a]),(0,rX.jsx)(t,{...e})}}}var r4=es(eo()),r6=class extends r4.Component{state={faulted:!1};static getDerivedStateFromError(){return{faulted:!0}}componentDidCatch(e){this.props.onFault(e)}render(){return this.state.faulted?null:this.props.children}},r8=es(eo()),r3={"./_layout.tsx":{default:(0,r8.lazy)(()=>import("/assets/1d37541fcf09b7d464600e9b2171e267e031198335cf20983c94696b6e2f6fb7.js"))},"./h/[hostId]/[...page].tsx":{default:(0,r8.lazy)(()=>import("/assets/c3f3bffb9ef60f82fcea02de055109409f5a561423c1c2edc7a651058e80321a.js").then(r2))},"./h/[hostId]/accounts.tsx":{default:(0,r8.lazy)(()=>import("/assets/4405dbd1a8c01298144be65b1ee2f2298f33b8fe39e194465d4db7b16dd6050f.js").then(r2))},"./h/[hostId]/agent-history/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/f1a251abcb4bb2c1316806cdef71e01a77dff27c5e390f54b73ede6bfa71154c.js").then(r2))},"./h/[hostId]/edit.tsx":{default:(0,r8.lazy)(()=>import("/assets/a942603319844e9aaec9d932e14335c9b44eefb850257ea29aba6f52914f3cb1.js").then(r2))},"./h/[hostId]/files/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/2473e3361965b8db2d910f8772ad561b5c862c6712327b57b4c71b41b09711ff.js").then(r2))},"./h/[hostId]/files/preview/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/5184c92fd49169d698ce36be1f0831cd3321cdbe359f5f63cd21ac642616dc37.js").then(r2))},"./h/[hostId]/history/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/301f677d57709861ad8206cd37d413c7ccbc114ca3e79d8744ac558b209dd430.js").then(r2))},"./h/[hostId]/index.tsx":{default:(0,r8.lazy)(()=>import("/assets/453999a244b592464c56a7cfde13f1d02cc068236cb56e819e63a842525eedc1.js").then(r2))},"./h/[hostId]/pr/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/f0886d78eca829b5a6bebc1105197b6acc05c75ba4e1baa00003a08a532d31a7.js").then(r2))},"./h/[hostId]/review/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/c5fc0821f14cbcb3cd66c98153640ddce383f236465173b4ed66e6e0e66994d7.js").then(r2))},"./h/[hostId]/session/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/0812724a10c2f7e160171ae846c119900de484383435ea299085d7474108b765.js").then(r2))},"./h/[hostId]/source-control/[worktreeId].tsx":{default:(0,r8.lazy)(()=>import("/assets/b75c3c6bd8b17c1c93e13060c58bb5df119b3729daafe457a3c65afdb4018968.js").then(r2))},"./h/[hostId]/tasks.tsx":{default:(0,r8.lazy)(()=>import("/assets/5152a5cb84bc3d3016abe04383658f817ff5fa4fe3553c63311080e1c9bf48d5.js").then(r2))},"./h/_layout.tsx":{default:(0,r8.lazy)(()=>import("/assets/77efe1035a95d226958585d9cddcf171ccc0326f95ae939818c28ff806f7ed16.js"))}},r5=Object.keys(r3);function r9(e){if(!Object.prototype.hasOwnProperty.call(r3,e))throw Error("[orca-mobile-web-app] no route module for "+e);return r3[e]}r9.keys=()=>r5.slice(),r9.resolve=e=>{if(!Object.prototype.hasOwnProperty.call(r3,e))throw Error("[orca-mobile-web-app] cannot resolve route "+e);return e},r9.id="orca-mobile-web-app-routes";var r7=es(en()),oe=document.createElement("style");oe.textContent=Y,document.head.append(oe);var ot=document.getElementById("root");if(!ot)throw Error("[orca-mobile-web-app] #root missing");var oa=document.documentElement;oa.style.setProperty("--muted-foreground",J.textMuted),oa.style.setProperty("--foreground",J.textPrimary),rQ(oa,"started"),function(e){let{target:t,client:a,replaceUrl:r,mount:o,refuseUnroutedShell:n}=e;if(null===a)return rQ(t,"unbridged");let s=()=>{var e;let s,i=a.getShellSession();return null!==i&&(t.dataset.orcaWebSessionId=i.sessionId,t.dataset.orcaWebBuildId=i.buildId,null===i.route?(rQ(t,"shell-too-old"),n()):(r(""===(s=new URLSearchParams((e=i.route).params??{}).toString())?e.pathname:`${e.pathname}?${s}`),rQ(t,"shell-ready"),o(a,i)),!0)};s()||a.onReady(()=>{s()})}({target:oa,client:null===(t=void 0===(e=globalThis.orcaBridge)||"function"!=typeof e.postMessage?null:e)?null:function(e){var t;let a,r,o,n,s,i,l=new rG,d=new rT,c=!1,h=0;function j(t){e.onDiagnostic?.(t)}function N(t){try{let a=JSON.stringify(t);return H(a)?(e.send(a),"sent"):(j({kind:"send-oversized",bytes:W(a)}),"oversized")}catch(e){return j({kind:"send-failed",error:e}),"port-failed"}}let R=e=>B.current()?.grants.native.includes(e)===!0,E=e=>"sent"===N(e);function O(){return(h+=1).toString(36).padStart(22,"0")}let A=new rJ({send:e=>E(e),onDroppedBinaryFrame:()=>{j({kind:"binary-frame-dropped"})}}),M=function(e){let t=null,a=50;function r(){e(),t=setTimeout(()=>{a=Math.min(2*a,2e3),r()},a)}function o(){null!==t&&(clearTimeout(t),t=null)}return{start:r,stop:o,restart:()=>{o(),a=50,r()}}}(()=>{N({v:f,type:"ready"})});function P(){if(null===B.current()&&!c)throw new rP}function F(){let e=d.read();if(null===e)throw new rP;return e}let B=(t={onReplaced:()=>{let e=new rL;l.closeAll(e),A.failAll(e.message)},prime:e=>{d.prime(e)}},a=null,r=new Set,o=new Set,n=new Set,s=new Set,i=new Set,{current:()=>a,accept:e=>{let l=a,d=null!==l&&l.sessionId===e.sessionId?l:null;null!==l&&null===d&&t.onReplaced();let c=e.safeAreaInsets??I,p=null!==l&&!z(l.safeAreaInsets,c),h=null===l||p?c:l.safeAreaInsets,m=e.keyboardInset??0,g=null!==l&&l.keyboardInset!==m;for(let r of(a=null===d?{...{sessionId:e.sessionId,buildId:e.buildId,grants:e.grants,route:e.route??null,pageRoutes:e.pageRoutes??[],pageRouteGrants:e.pageRouteGrants??null,safeAreaInsets:e.safeAreaInsets??I,keyboardInset:e.keyboardInset??0,host:e.host??null,storage:e.storage??{},storageOversize:e.storageOversize??[],ownsHostArea:!0===e.ownsHostArea},safeAreaInsets:h}:{...d,route:e.route??null,safeAreaInsets:h,keyboardInset:m},t.prime(e.connection),o))r();for(let e of r)e();if(r.clear(),p)for(let e of s)e(h);if(g)for(let e of i)e(m);if(!(null===d||!u(d.route,a.route)))for(let e of n)e(a.route)},onReady:e=>null!==a?(e(),()=>{}):(r.add(e),()=>{r.delete(e)}),onRouteUpdate:e=>(n.add(e),()=>{n.delete(e)}),onShellSessionChange:e=>(o.add(e),()=>{o.delete(e)}),onSafeAreaInsetsUpdate:e=>(s.add(e),()=>{s.delete(e)}),onKeyboardInsetUpdate:e=>(i.add(e),()=>{i.delete(e)}),close:()=>{a=null,r.clear(),o.clear()}}),$=function(e){let t=[];function a(a){0===a!=(0===t.length)&&e.publishClaim(t.length>0)}return{claim:e=>{let r={consumer:e},o=t.length;return t.push(r),a(o),()=>{let e=t.indexOf(r);if(-1===e)return;let o=t.length;t.splice(e,1),a(o)}},press:()=>{t.toReversed().some(e=>e.consumer())||e.onUnclaimed()},reassert:()=>{t.length>0&&e.publishClaim(!0)},clear:()=>{let e=t.length;t.length=0,a(e)}}}({publishClaim:e=>K.notifyBackClaim(e),onUnclaimed:()=>{j({kind:"back-unclaimed"}),K.notifyNavigateBack()}}),V=function(e){let{requests:t,subscriptions:a,report:r}=e;function o(e,o,n){if(a.has(e)){r({kind:"stream-failed",error:o});let t=o instanceof Error?o.message:"the shell could not keep this stream open";n?a.end(e,t,o):a.abandon(e,t,o);return}t.has(e)||r({kind:"unknown-id"}),t.fail(e,o)}return n=>{let s=C(n);if(s.ok)return void function(n,s){switch(n.type){case"init":e.acceptInit(n);return;case"state":e.acceptState(n.connection);return;case"back":e.acceptBack();return;case"reply":t.has(n.id)||r({kind:"unknown-id"}),t.acceptReply(n);return;case"error":o(n.id,g(n.error),!0);return;case"event":a.deliver(n,W(s));return;case"end":r({kind:"stream-ended",reason:n.reason}),a.end(n.id,`the shell ended this stream (${n.reason})`);return}}(s.message,n);r({kind:"refused",refusal:s.refusal});let i=S(n);null!==i&&(t.has(i)||a.has(i))&&o(i,new rD(s.refusal),!1)}}({requests:l,subscriptions:A,report:j,acceptInit:e=>{M.stop(),B.accept(e),$.reassert()},acceptState:function(e){"stale"===d.apply(e)&&(j({kind:"state-out-of-order"}),M.restart())},acceptBack:$.press});function G(...e){if(P(),c)return Promise.reject(new r_);if(l.size>=q)return Promise.reject(new rq(`over ${q} requests in flight`));let[t,a,r]=e;return new Promise((o,n)=>{let s=function(e,t){if(void 0===e)return{};let{envelope:a,...r}=e,o=rK(a,t);return{...void 0!==a&&0===Object.keys(r).length?{}:{options:r},...void 0===o?{}:{envelope:o}}}(r,R),i=O();l.open(i,{resolve:o,reject:n});let d=N({v:f,type:"request",id:i,method:t,...e.length>1?{params:a}:{},...s});"sent"!==d&&(l.abandon(i),n("oversized"===d?new rW:new rF))})}let K=function(e){function t(t){return e.requireSession(),!e.isClosed()&&e.send(t)}return{updateTerminalSubscriptionViewport:(e,a)=>{t({v:f,type:"notify",name:"terminalViewport",terminal:e,cols:a.cols,rows:a.rows})},notifyForeground:e=>{t({v:f,type:"notify",name:"foreground",...void 0===e?{}:{reason:e}})},notifyNavigate:a=>e.hasGrant("navigate")&&t({v:f,type:"notify",name:"navigate",href:a}),notifyNavigateBack:()=>e.hasGrant("navigate")&&t({v:f,type:"notify",name:w}),notifyExternalLink:a=>{if(!e.hasGrant(y))return!1;let r=L(a);return null!==r&&t({v:f,type:"notify",name:y,url:r})},notifyStorageWrite:(a,r)=>e.hasGrant("storage")&&t({v:f,type:"notify",name:"storage",key:a,value:r}),notifyHaptics:a=>e.hasGrant(U)&&t({v:f,type:"notify",name:T,kind:a}),notifyPageFault:t=>!e.isClosed()&&!!e.hasGrant(v)&&e.send({v:f,type:"notify",name:v,error:m(t)}),notifyPagePainted:()=>{t({v:f,type:"notify",name:b})},notifyBackClaim:e=>{t({v:f,type:"notify",name:x,claimed:e})}}}({send:E,requireSession:P,isClosed:()=>c,hasGrant:R}),Y=e.onMessage(function(e){if(!c)try{V(e)}catch(e){j({kind:"inbound-listener-threw",error:e})}});return M.start(),{sendRequest:G,subscribe:function(e,t,a,r){if(P(),c)return()=>{};if(A.size>=D)throw new rq(`over ${D} subscriptions`);let{onBinaryFrame:o,envelope:n}=r??{},s=rK(n,R),i=O();if(!A.open(i,e,t,a,o,s))return()=>{};let l=!1;return()=>{l||(l=!0,A.cancel(i))}},updateTerminalSubscriptionViewport:K.updateTerminalSubscriptionViewport,getState:()=>F().state,getReconnectAttempt:()=>F().reconnectAttempt,getLastConnectedAt:()=>F().lastConnectedAt,getLastInboundAt:()=>F().lastInboundAt,getGeneration:()=>F().generation??0,carriesRpcEnvelope:()=>R(k),onStateChange:e=>d.onStateChange(e),notifyForeground:K.notifyForeground,notifyNavigate:K.notifyNavigate,notifyNavigateBack:K.notifyNavigateBack,notifyExternalLink:K.notifyExternalLink,callNativeVerb:(e,t)=>_(e)?G(e,t).then(e=>{if(!e.ok)throw Error(e.error.message);return e}):Promise.reject(new rH(e)),notifyStorageWrite:K.notifyStorageWrite,notifyHaptics:K.notifyHaptics,notifyPageFault:K.notifyPageFault,notifyPagePainted:K.notifyPagePainted,claimBack:$.claim,close:function(){c||(c=!0,M.stop(),$.clear(),A.closeAll(),N({v:f,type:"close"}),l.closeAll(),d.close(),B.close(),Y())},onReady:B.onReady,onRouteUpdate:B.onRouteUpdate,onSafeAreaInsetsUpdate:B.onSafeAreaInsetsUpdate,onShellSessionChange:B.onShellSessionChange,onKeyboardInsetUpdate:B.onKeyboardInsetUpdate,getShellSession:B.current,clearRouteParam:(e,t)=>E({v:f,type:"notify",name:p,param:e,value:t})}}({...{send:e=>{t.postMessage(e)},onMessage:e=>(t.onmessage=t=>{e(t.data)},()=>{t.onmessage=null})},onDiagnostic:(a=new Set,e=>{a.has(e.kind)||(a.add(e.kind),console.warn("[page-bridge]",e.kind,e))})}),replaceUrl:e=>{history.replaceState(null,"",e)},mount:(e,t)=>{var a,r;let o,n,s;B(t.host),E(t=>e.notifyExternalLink(t)),A(t=>e.notifyHaptics(t)),O({read:()=>e.getShellSession()?.keyboardInset??0,subscribe:e.onKeyboardInsetUpdate}),N(t.storage,(t,a)=>e.notifyStorageWrite(t,a),t.host?.id??"",t.route?.pathname??"",t.storageOversize,t.ownsHostArea?async t=>P.parse((await e.callNativeVerb("native.storage.read",{key:t})).result).value:null),K(()=>R.getItem($)),G(()=>R.getItem(V)),(0,rA.createRoot)(ot).render((0,r7.jsx)(r6,{onFault:t=>{e.notifyPageFault(t)},children:(0,r7.jsx)(rM.ExpoRoot,{context:r9,location:new URL(window.location.href),wrapper:(a={requestFrame:e=>requestAnimationFrame(e),cancelFrame:e=>{cancelAnimationFrame(e)}},r=()=>{e.notifyPagePainted()},o=!1,n=null,s=()=>{var e;let t,s;if(o)return()=>{};n?.();let i=(e=()=>{n=null,o=!0,r()},t=!1,s=a.requestFrame(()=>{s=a.requestFrame(()=>{t=!0,e()})}),()=>!t&&(t=!0,a.cancelFrame(s),!0));return n=i,()=>{i()}},function({children:t}){return(0,rO.useEffect)(()=>{rQ(oa,"mounted")},[]),(0,r7.jsxs)(Q,{client:e,children:[(0,r7.jsx)(rC,{client:e}),(0,r7.jsx)(r1,{report:s,children:(0,r7.jsx)("div",{"data-mobile-tools-content":!0,style:{position:"relative",display:"flex",flexDirection:"column",flex:1,minWidth:0,minHeight:0,marginBottom:"var(--mobile-tools-clearance, 102px)"},children:t})})]})})})}))},refuseUnroutedShell:()=>{let e,t,a;(e=document.createElement("div")).setAttribute("role","alert"),e.style.cssText="font:16px/1.5 system-ui,-apple-system,sans-serif;color:var(--rupro-textPrimary);background:var(--rupro-bgBase);min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:24px;text-align:center",(t=document.createElement("div")).style.cssText="font-weight:600",t.textContent="Update Orca to open this workspace",(a=document.createElement("div")).style.cssText="color:var(--rupro-textMuted);font-size:14px",a.textContent="This version of the app cannot open the workspace it downloaded.",e.append(t,a),ot.replaceChildren(e)}}); \ No newline at end of file diff --git a/phone-host/bundle/index.html b/phone-host/bundle/index.html index 11bc380b2b..94a887b556 100644 --- a/phone-host/bundle/index.html +++ b/phone-host/bundle/index.html @@ -70,6 +70,6 @@
- + diff --git a/phone-host/bundle/manifest.json b/phone-host/bundle/manifest.json index e7b43466e8..5dec5a1d97 100644 --- a/phone-host/bundle/manifest.json +++ b/phone-host/bundle/manifest.json @@ -1,12 +1,12 @@ { "schemaVersion": 1, - "buildId": "1dd1e40238ecaa5a0bf1fb723992f8461d814a1dd9e42690a05ca38be090c1f0", + "buildId": "a8732ed7cbe5be7ff01a9704c50270f7f58591c4902e92e99396775dcbe4e512", "desktopVersion": "1.4.214", "minCompatibleRuntimeProtocolVersion": 2, "runtimeProtocolVersion": 3, "pageVersion": 1, "entrypoint": "index.html", - "totalBytes": 14972943, + "totalBytes": 14973499, "assets": [ { "path": "assets/023370fd50d18b0eca615bb6715d60291daf9e38df72e478878ac041efac4a8a.mp4", @@ -44,6 +44,12 @@ "byteLength": 12012, "contentType": "text/javascript; charset=utf-8" }, + { + "path": "assets/0812724a10c2f7e160171ae846c119900de484383435ea299085d7474108b765.js", + "sha256": "0812724a10c2f7e160171ae846c119900de484383435ea299085d7474108b765", + "byteLength": 1533941, + "contentType": "text/javascript; charset=utf-8" + }, { "path": "assets/0944f11730bc7fe1d434b91a21a79c0d8badf70b9860bcbe0d8ef171ad16c70f.js", "sha256": "0944f11730bc7fe1d434b91a21a79c0d8badf70b9860bcbe0d8ef171ad16c70f", @@ -224,6 +230,12 @@ "byteLength": 7103, "contentType": "text/javascript; charset=utf-8" }, + { + "path": "assets/393753fcec4b8acaddf3b0214cba3fa3814b945530e46703eebfef26582ef924.js", + "sha256": "393753fcec4b8acaddf3b0214cba3fa3814b945530e46703eebfef26582ef924", + "byteLength": 421872, + "contentType": "text/javascript; charset=utf-8" + }, { "path": "assets/3cfddb6c48e4a53b864c10cb51b79d487f4fe7f2f5a468ef9f74e425f284a6e2.js", "sha256": "3cfddb6c48e4a53b864c10cb51b79d487f4fe7f2f5a468ef9f74e425f284a6e2", @@ -272,12 +284,6 @@ "byteLength": 2005, "contentType": "text/javascript; charset=utf-8" }, - { - "path": "assets/48fae3d9447c3e75964d9031d9ede8a0d784d091f9c0b0625c12d3a73b621247.js", - "sha256": "48fae3d9447c3e75964d9031d9ede8a0d784d091f9c0b0625c12d3a73b621247", - "byteLength": 421872, - "contentType": "text/javascript; charset=utf-8" - }, { "path": "assets/490dff5263bf369721e167cfeb10d4de9d64c24d33fdcd8a6f98be29f240f778.js", "sha256": "490dff5263bf369721e167cfeb10d4de9d64c24d33fdcd8a6f98be29f240f778", @@ -1034,12 +1040,6 @@ "byteLength": 10615, "contentType": "text/javascript; charset=utf-8" }, - { - "path": "assets/ff5bafc87134b6a566c67255bb9546eabc92bd5b335b13af7d063abaa4a9fd20.js", - "sha256": "ff5bafc87134b6a566c67255bb9546eabc92bd5b335b13af7d063abaa4a9fd20", - "byteLength": 1533385, - "contentType": "text/javascript; charset=utf-8" - }, { "path": "assets/ff7d075108ea20b3bd3c8ddf6d2dbd27e2369c32bfbf4d6c6afe3c33c794ec08.js", "sha256": "ff7d075108ea20b3bd3c8ddf6d2dbd27e2369c32bfbf4d6c6afe3c33c794ec08", @@ -1048,7 +1048,7 @@ }, { "path": "index.html", - "sha256": "80612ab8dd761f948c90b2c30e3a2751893de67895145387078632cd1f36dffb", + "sha256": "78fdf65d33bf712407c399a4a7c7525f17ea1d531641db0a35455232589e0454", "byteLength": 2720, "contentType": "text/html; charset=utf-8" } diff --git a/phone-host/package-lock.json b/phone-host/package-lock.json index 0f861f8e06..3399edda30 100644 --- a/phone-host/package-lock.json +++ b/phone-host/package-lock.json @@ -1,12 +1,12 @@ { "name": "@claude-flow/phone-host", - "version": "1.1.1", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@claude-flow/phone-host", - "version": "1.1.1", + "version": "1.2.0", "license": "MIT", "dependencies": { "@lydell/node-pty": "1.2.0-beta.18", diff --git a/phone-host/package.json b/phone-host/package.json index 2603c627d9..17cc292091 100644 --- a/phone-host/package.json +++ b/phone-host/package.json @@ -1,6 +1,6 @@ { "name": "@claude-flow/phone-host", - "version": "1.1.1", + "version": "1.2.0", "description": "Opt-in add-on: pair the RuFlo or Orca phone app with this computer over LAN or Tailscale (end-to-end encrypted), with an optional full-access mode for terminals and agent tabs", "type": "module", "license": "MIT", diff --git a/phone-host/src/chat-sessions.mjs b/phone-host/src/chat-sessions.mjs index 8426591602..e8b37c5061 100644 --- a/phone-host/src/chat-sessions.mjs +++ b/phone-host/src/chat-sessions.mjs @@ -28,6 +28,31 @@ export function defaultChatRoots(env = process.env) { }; } +const MAX_CLAUDE_CONFIG_BYTES = 32 * 1024 * 1024; + +/** + * Whether Claude Code already trusts this exact folder (`projects[cwd].hasTrustDialogAccepted` in + * its `.claude.json`), so it will not stop at its first-run trust prompt. Anything unreadable, and + * a trust only a parent folder holds, counts as not trusted: the cost is that the phone shows the + * terminal a little longer, never that the prompt is hidden behind the chat view. + */ +export async function claudeFolderTrusted(cwd, env = process.env) { + const files = [...new Set([join(absOr(env.CLAUDE_CONFIG_DIR, homedir()), '.claude.json'), join(homedir(), '.claude.json')])]; + let real; + try { real = await realpath(cwd); } catch { real = cwd; } + for (const file of files) { + try { + if ((await stat(file)).size > MAX_CLAUDE_CONFIG_BYTES) continue; + const fh = await open(file, 'r'); + let text; + try { text = await fh.readFile('utf8'); } finally { await fh.close(); } + const projects = JSON.parse(text)?.projects; + if (projects && typeof projects === 'object' && [cwd, real].some((p) => Object.hasOwn(projects, p) && projects[p]?.hasTrustDialogAccepted === true)) return true; + } catch { /* missing or unreadable: not trusted */ } + } + return false; +} + /** Claude Code's project directory name for a cwd (every non-alphanumeric becomes '-'). */ export const claudeProjectSlug = (cwd) => cwd.replace(/[^A-Za-z0-9]/g, '-'); diff --git a/phone-host/src/full-methods.mjs b/phone-host/src/full-methods.mjs index d5f84ccd71..bcdbe222ee 100644 --- a/phone-host/src/full-methods.mjs +++ b/phone-host/src/full-methods.mjs @@ -6,9 +6,10 @@ // catalog. That decides where a terminal starts. It is not a sandbox: a shell can go anywhere the // user can. import { randomUUID } from 'node:crypto'; +import { stat } from 'node:fs/promises'; import { AGENT_TITLES, agentCommand, detectAgents, shellQuote } from './agents.mjs'; import { createChatMethods } from './chat-methods.mjs'; -import { createChatSessions } from './chat-sessions.mjs'; +import { claudeFolderTrusted, createChatSessions } from './chat-sessions.mjs'; import { initialTabStatus, nextTabStatus, statusFields, watchChatStatus } from './chat-status.mjs'; import { createFilesMethods } from './files-methods.mjs'; import { createQuickCommands } from './quick-commands.mjs'; @@ -25,6 +26,8 @@ export function submitDelayMs(text, platform = process.platform) { const MUTATION_MEMORY = 256; const MAX_TITLE = 200; const FOREGROUND_CHECK_MS = 2000; +/** How long a Claude tab in an untrusted folder is watched for trust before the phone is left on the terminal. */ +const TRUST_WATCH_MS = 30 * 60_000; // A quick command's starting prompt for Claude or Codex, one argument after the fixed command // (Orca's 'argv' prompt injection, src/shared/tui-agent-startup.ts). The prompt is never typed: it // rides in the terminal's environment and the typed line ends in "$RUFLO_PHONE_AGENT_PROMPT", so the @@ -52,7 +55,8 @@ export const CLOSE_REVOKED = Symbol('closeRevoked'); * chatSessions: where Claude/Codex transcripts are looked for (tests pass their own roots). * stateDir: where quick commands are saved; without one they live in memory. */ -export function createFullMethods({ terminals, projects, log = () => {}, detect = detectAgents, chatSessions = createChatSessions(), chatPollMs, stateDir = null }) { +export function createFullMethods({ terminals, projects, log = () => {}, detect = detectAgents, chatSessions = createChatSessions(), chatPollMs, stateDir = null, + claudeTrust = (cwd) => claudeFolderTrusted(cwd), trustPollMs = 1500 }) { const publicationEpoch = `ruflo-phone:${randomUUID()}`; let snapshotVersion = 0; /** worktreeId -> { tabs: Tab[], activeTabId: string|null } (tab = { tabId, leafId, handle, title, launchAgent }) */ @@ -80,7 +84,8 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect return { ...statusFields(t.chat.status), agentType: t.chat.agent, paneKey: `${t.tabId}:${t.leafId}`, terminalHandle: t.handle, tabId: t.tabId, worktreeId, - ...(t.chat.sessionId ? { providerSession: { key: 'session_id', id: t.chat.sessionId, transcriptPath: t.chat.transcriptPath } } : {}), + // Held back until the agent is past its first-run prompt (see revealWhenTrusted). + ...(t.chat.sessionId && t.chat.shown !== false ? { providerSession: { key: 'session_id', id: t.chat.sessionId, transcriptPath: t.chat.transcriptPath } } : {}), }; } @@ -158,6 +163,32 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect }); } + /** + * The phone opens an agent tab in its chat view once the tab reports a session, and Claude is + * given its session id at launch. In a folder Claude does not trust yet, its first-run trust + * prompt is in the terminal, and the chat view would hide it. So the session is reported only + * once Claude trusts the folder, or has written its transcript (it is past the prompt then). + */ + function revealWhenTrusted(tab, row, t) { + const started = Date.now(); + let timer = null; + const check = async () => { + timer = null; + if (terminals.get(t.handle) !== t || tab.chat.shown !== false) return; + let ready = await claudeTrust(row.path); + // The path the host chose at launch, not one from the phone. + if (!ready) ready = await stat(tab.chat.transcriptPath).then((s) => s.isFile(), () => false); + if (ready) { + tab.chat.shown = true; + if (sessionOf(row.worktreeId).tabs.includes(tab)) publish(row.worktreeId); + } else if (Date.now() - started < TRUST_WATCH_MS) { + timer = setTimeout(check, trustPollMs); + timer.unref?.(); + } + }; + void check(); + } + // A turn the transcript left open (the agent crashed or was quit mid-turn) must not keep Stop up. const foregroundTimer = setInterval(() => { for (const [worktreeId, s] of sessions) for (const tab of s.tabs) if (tab.chat?.status.state === 'working') applyStatus(tab, worktreeId); @@ -193,8 +224,9 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect }; const launchedAt = Date.now(); if (claude) { - tab.chat = { agent: 'claude', sessionId: claude.sessionId, transcriptPath: claude.transcriptPath, status: initialTabStatus(launchedAt) }; + tab.chat = { agent: 'claude', sessionId: claude.sessionId, transcriptPath: claude.transcriptPath, status: initialTabStatus(launchedAt), shown: false }; followStatus(tab, row.worktreeId, claude); + revealWhenTrusted(tab, row, t); } if (agent === 'codex') { // Codex names its own session when it writes the first prompt; the tab gains it then. @@ -344,8 +376,18 @@ export function createFullMethods({ terminals, projects, log = () => {}, detect 'terminal.unsubscribe': (p, conn) => { const streams = streamsOf(conn); - const keys = [p?.requestId, p?.subscriptionId, p?.client?.id ? `${p?.subscriptionId}:${p.client.id}` : null].filter((k) => typeof k === 'string'); - for (const k of keys) { const stop = streams.get(k); if (stop) { stop(); streams.delete(k); } } + // With a requestId, end only that request's stream: a cancel for an older stream that lands + // after the phone re-subscribed must not stop the new one, which the slot key (terminal:client) + // now names. Without a requestId, use the slot, as Orca's hosts that predate it do. + const keys = typeof p?.requestId === 'string' + ? [p.requestId] + : [p?.subscriptionId, p?.client?.id ? `${p?.subscriptionId}:${p.client.id}` : null].filter((k) => typeof k === 'string'); + for (const k of keys) { + const stop = streams.get(k); + if (!stop) continue; + stop(); + for (const [key, value] of streams) if (value === stop) streams.delete(key); + } return { unsubscribed: true }; }, diff --git a/phone-host/src/rpc.mjs b/phone-host/src/rpc.mjs index 3bdc9cbc6b..8baf447806 100644 --- a/phone-host/src/rpc.mjs +++ b/phone-host/src/rpc.mjs @@ -2,6 +2,7 @@ // launches, no git writes (projects.mjs only reads `git worktree list`). Anything not listed here answers `method_not_found`. import { hostname } from 'node:os'; import { BUNDLE_CAPABILITY, BundleError } from './bundle.mjs'; +import { createTeamSnapshotRead } from './team-snapshot.mjs'; import { createWorkspaceReads } from './workspace-reads.mjs'; /** Orca runtime protocol this host speaks (src/shared/protocol-version.ts). */ @@ -49,6 +50,8 @@ export function createDispatcher({ runtimeId, bundle, projects = null, machineNa 'worktree.ps': (p) => (projects ? projects.worktreePs(p) : { worktrees: [], totalCount: 0, truncated: false }), 'repo.list': () => (projects ? projects.repoList() : { repos: [] }), ...(projects ? createWorkspaceReads({ projects }) : {}), + // Teams & swarm: read-only, so a monitor phone gets it too, as on the RuPro desktop. + ...(projects ? createTeamSnapshotRead({ projects }) : {}), }; if (bundle) { methods['mobileWeb.bundle.manifest'] = () => bundle.manifestReply(); diff --git a/phone-host/src/team-snapshot.mjs b/phone-host/src/team-snapshot.mjs new file mode 100644 index 0000000000..9217422299 --- /dev/null +++ b/phone-host/src/team-snapshot.mjs @@ -0,0 +1,205 @@ +// `ruflo.teamSnapshot.read`, the phone's Teams & swarm screen. The reader below is the RuPro +// desktop's (cognitum-one/ruflo-ui overlays/ruflo/runtime/ruflo-team-snapshot-reader.mjs at +// 8bbe93d73), unchanged, so both hosts send the phone the same shape. +// +// Read-only snapshot of who is working in a workspace: Claude Code agent teams +// (~/.claude/teams, ~/.claude/tasks) and ruflo swarm / hive-mind / tasks / claims +// (/.claude-flow). Every value is copied field by field from an +// allowlist, never spread, so tokens (hive-mind `hiveToken`), member prompts and +// claim context never leave the host. Files are size-capped, symlinks refused. +import {createHash} from 'node:crypto'; +import {closeSync,fstatSync,lstatSync,openSync,readSync,readdirSync} from 'node:fs'; +import {homedir} from 'node:os'; +import {basename,join} from 'node:path'; +import {RpcError} from './rpc.mjs'; + +export const LIMITS=Object.freeze({teams:6,members:24,messages:40,inboxes:64,teamTasks:60,swarms:5,agents:30,tasks:30,claims:30,file:512*1024,text:280}); +const NAME=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; +const DONE_SWARM=new Set(['terminated','stopped','completed','failed','shutdown']); +const OPEN_TASK=new Set(['pending','in_progress','in-progress','running','assigned','blocked','queued']); +const OPEN_CLAIM=new Set(['active','paused','blocked','review','handoff-pending']); +const DAY=86_400_000,FORTNIGHT=14*DAY; + +function clip(value,max=LIMITS.text){ + if(typeof value!=='string')return null; + const text=value.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g,'').replace(/\s+/g,' ').trim(); + return text?(text.length>max?text.slice(0,max-1)+'…':text):null; +} +function id(value){return typeof value==='string'&&value.length<=200?clip(value,200):null} +function num(value){return typeof value==='number'&&Number.isFinite(value)?value:null} +function time(value){ + if(typeof value==='number'&&Number.isFinite(value))return value; + if(typeof value==='string'){const t=Date.parse(value);return Number.isFinite(t)?t:null} + return null; +} +/** Regular file, not a symlink, under the size cap; otherwise null. */ +function readJson(path){ + try{ + const stat=lstatSync(path); + if(!stat.isFile()||stat.size>LIMITS.file)return null; + const fd=openSync(path,'r'); + try{ + const size=fstatSync(fd).size;if(size>LIMITS.file)return null; + const buffer=Buffer.alloc(size);let read=0; + while(read!e.isSymbolicLink()).slice(0,limit*4); + }catch{return []} +} +function inside(path,root){return path===root||path.startsWith(root.endsWith('/')?root:root+'/')} + +/** Message text is often JSON inside JSON ({type:'idle_notification',summary,...}). */ +function message(raw,inbox){ + if(!raw||typeof raw!=='object')return null; + let kind='message',summary=null; + if(typeof raw.text==='string'){ + const text=raw.text.trim(); + if(text.startsWith('{')){ + try{const inner=JSON.parse(text);if(inner&&typeof inner==='object'){kind=id(inner.type)??'message';summary=clip(inner.summary)??clip(inner.result)??clip(inner.content)??clip(inner.reason)}}catch{summary=clip(text)} + }else summary=clip(text); + } + if(kind==='message'&&typeof raw.type==='string')kind=id(raw.type)??kind; + return {from:id(raw.from)??'unknown',to:inbox,at:time(raw.timestamp),kind,summary,read:raw.read===true}; +} +function memberStatus(name,lead,messages){ + if(name===lead)return 'lead'; + const last=messages.filter(m=>m.from===name).sort((a,b)=>(b.at??0)-(a.at??0))[0]; + if(!last)return 'unknown'; + if(/shutdown|terminated|stopped/.test(last.kind))return 'stopped'; + if(last.kind==='idle_notification')return 'idle'; + return 'working'; +} + +function readTeam(home,name,config,mtime){ + const members=Array.isArray(config.members)?config.members.slice(0,LIMITS.members):[]; + const lead=id(members.find(m=>m?.agentId===config.leadAgentId)?.name)??'team-lead'; + const messages=[]; + for(const entry of listDir(join(home,'.claude','teams',name,'inboxes'),LIMITS.inboxes).slice(0,LIMITS.inboxes)){ + if(!entry.isFile()||!entry.name.endsWith('.json'))continue; + const inbox=entry.name.slice(0,-5);if(!NAME.test(inbox))continue; + const file=readJson(join(home,'.claude','teams',name,'inboxes',entry.name)); + if(!Array.isArray(file?.value))continue; + for(const raw of file.value.slice(-LIMITS.messages)){const m=message(raw,inbox);if(m)messages.push(m)} + } + messages.sort((a,b)=>(b.at??0)-(a.at??0)); + const tasks=[]; + for(const entry of listDir(join(home,'.claude','tasks',name),LIMITS.teamTasks)){ + if(tasks.length>=LIMITS.teamTasks)break; + if(!entry.isFile()||!entry.name.endsWith('.json'))continue; + const task=readJson(join(home,'.claude','tasks',name,entry.name))?.value; + if(!task||typeof task!=='object')continue; + tasks.push({id:id(task.id)??entry.name.slice(0,-5),subject:clip(task.subject)??clip(task.description)??'Untitled task',status:id(task.status)??'unknown',owner:id(task.owner),blocked:Array.isArray(task.blockedBy)&&task.blockedBy.length>0}); + } + return { + source:'claude-team',name,createdAt:time(config.createdAt),updatedAt:Math.max(mtime,messages[0]?.at??0)||null, + lead,leadCwd:typeof members[0]?.cwd==='string'?members[0].cwd:null, + members:members.filter(m=>m&&typeof m==='object').map(m=>{ + const memberName=id(m.name)??'member'; + const recent=messages.find(x=>x.from===memberName); + return {name:memberName,agentType:id(m.agentType),model:id(m.model),color:id(m.color), + backend:memberName===lead?'lead':m.backendType==='tmux'||(typeof m.tmuxPaneId==='string'&&/^%\d+$/.test(m.tmuxPaneId))?'pane':'in-process', + joinedAt:time(m.joinedAt),status:memberStatus(memberName,lead,messages),lastSummary:recent?.summary??null,lastActivityAt:recent?.at??null}; + }), + messages:messages.slice(0,LIMITS.messages),tasks, + memberCount:Array.isArray(config.members)?config.members.length:0, + }; +} + +/** Claude Code agent teams whose lead works in one of `roots` (newest first). */ +export function readClaudeTeams(home,roots){ + const base=join(home,'.claude','teams'),found=[]; + for(const entry of listDir(base,256)){ + if(!entry.isDirectory()||!NAME.test(entry.name))continue; + const file=readJson(join(base,entry.name,'config.json')); + const config=file?.value;if(!config||typeof config!=='object'||!Array.isArray(config.members))continue; + const cwd=config.members.find(m=>m?.agentId===config.leadAgentId)?.cwd??config.members[0]?.cwd; + if(typeof cwd!=='string')continue; + const root=[...roots].sort((x,y)=>y.length-x.length).find(r=>inside(cwd,r));if(!root)continue; + found.push({name:entry.name,config,mtime:file.mtime,root}); + } + found.sort((a,b)=>b.mtime-a.mtime); + return found.slice(0,LIMITS.teams).map(t=>({...readTeam(home,t.name,t.config,t.mtime),root:t.root})); +} + +/** Live ruflo coordination state for one workspace; stale or finished entries are dropped. */ +export function readRufloState(worktreePath,now=Date.now()){ + const dir=join(worktreePath,'.claude-flow'); + const swarmFile=readJson(join(dir,'swarm','swarm-state.json'))?.value; + const swarms=[]; + if(swarmFile&&typeof swarmFile.swarms==='object'&&swarmFile.swarms) + for(const s of Object.values(swarmFile.swarms)){ + if(!s||typeof s!=='object'||DONE_SWARM.has(s.status))continue; + const updatedAt=time(s.updatedAt); + swarms.push({source:'ruflo-swarm',id:id(s.swarmId)??'swarm',topology:id(s.topology),strategy:id(s.config?.strategy),status:id(s.status)??'unknown', + maxAgents:num(s.maxAgents),agentCount:Array.isArray(s.agents)?s.agents.length:0,taskCount:Array.isArray(s.tasks)?s.tasks.length:0, + consensus:id(s.config?.consensusMechanism),updatedAt,stale:updatedAt!==null&&now-updatedAt>DAY}); + } + swarms.sort((a,b)=>(b.updatedAt??0)-(a.updatedAt??0)); + const h=readJson(join(dir,'hive-mind','state.json'))?.value; + let hive=null; + if(h&&typeof h==='object'&&h.initialized===true){ + const updatedAt=time(h.updatedAt); + hive={source:'ruflo-hive',topology:id(h.topology),consensus:id(h.consensusStrategy), + queen:h.queen&&typeof h.queen==='object'?{agentId:id(h.queen.agentId),term:num(h.queen.term)}:null, + workerCount:Array.isArray(h.workers)?h.workers.length:0,pendingVotes:Array.isArray(h.consensus?.pending)?h.consensus.pending.length:0, + decidedVotes:Array.isArray(h.consensus?.history)?h.consensus.history.length:0,updatedAt,stale:updatedAt!==null&&now-updatedAt>DAY}; + } + const a=readJson(join(dir,'agents.json'))?.value; + const agents=a&&typeof a.agents==='object'&&a.agents?Object.values(a.agents).filter(x=>x&&typeof x==='object'&&!DONE_SWARM.has(x.status)).slice(0,LIMITS.agents).map(x=>({ + id:id(x.agentId)??'agent',type:id(x.agentType),status:id(x.status)??'unknown',role:id(x.config?.hiveRole)??id(x.config?.role),domain:id(x.domain),health:num(x.health),taskCount:num(x.taskCount)})):[]; + const t=readJson(join(dir,'tasks','store.json'))?.value; + const tasks=t&&typeof t.tasks==='object'&&t.tasks?Object.values(t.tasks).filter(x=>x&&typeof x==='object'&&OPEN_TASK.has(x.status)&&now-(time(x.startedAt)??time(x.createdAt)??0)(time(y.createdAt)??0)-(time(x.createdAt)??0)).slice(0,LIMITS.tasks).map(x=>({ + source:'ruflo-task',id:id(x.taskId)??'task',type:id(x.type),status:id(x.status),priority:id(x.priority),description:clip(x.description,200),assignees:Array.isArray(x.assignedTo)?x.assignedTo.length:0,progress:num(x.progress)})):[]; + const c=readJson(join(dir,'claims','claims.json'))?.value; + const claims=c&&typeof c.claims==='object'&&c.claims?Object.values(c.claims).filter(x=>x&&typeof x==='object'&&OPEN_CLAIM.has(x.status)&&now-(time(x.statusChangedAt)??time(x.claimedAt)??0)({ + source:'ruflo-claim',issueId:id(x.issueId)??'claim',claimant:id(x.claimant?.agentId)??id(x.claimant?.userId)??'unknown',claimantType:id(x.claimant?.agentType)??id(x.claimant?.type), + status:id(x.status),progress:num(x.progress),claimedAt:time(x.claimedAt)})):[]; + return {swarms:swarms.slice(0,LIMITS.swarms),hive,agents,tasks,claims}; +} + +function hasRuflo(state){return state.swarms.length>0||state.hive!==null||state.agents.length>0||state.tasks.length>0||state.claims.length>0} + +/** One normalized model for the phone: per workspace, its Claude teams and ruflo state. */ +export function readTeamSnapshot({home,worktrees,now=Date.now()}){ + const roots=worktrees.map(w=>w.path); + const teams=readClaudeTeams(home,roots); + const workspaces=[]; + for(const w of worktrees){ + const ruflo=readRufloState(w.path,now); + const own=teams.filter(t=>t.root===w.path).map(({root,leadCwd,...team})=>team); + if(!own.length&&!hasRuflo(ruflo))continue; + workspaces.push({id:w.id,name:w.name,claudeTeams:own,ruflo}); + } + workspaces.sort((x,y)=>Math.max(0,...y.claudeTeams.map(t=>t.updatedAt??0))-Math.max(0,...x.claudeTeams.map(t=>t.updatedAt??0))); + return {generatedAt:now,workspaces:workspaces.slice(0,8)}; +} + +/** + * The method, over the workspaces this host shares and nothing else: the phone sends no path, + * and a team shows only when its lead works inside one of them. Worktree ids embed the absolute + * path, so the phone gets a hash of it as the key, as the desktop does. + * @param {{ projects: { worktreePs: Function }, home?: string }} deps + */ +export function createTeamSnapshotRead({ projects, home = homedir() }) { + return { + 'ruflo.teamSnapshot.read': async () => { + try { + const rows = (await projects.worktreePs({})).worktrees; + const worktrees = rows.filter((r) => typeof r.path === 'string' && r.path.startsWith('/')).map((r) => ({ + id: createHash('sha256').update(String(r.worktreeId)).digest('hex').slice(0, 16), + name: basename(r.path) || 'Workspace', + path: r.path, + })); + return readTeamSnapshot({ home, worktrees }); + } catch { + throw new RpcError('invalid_argument', 'ruflo_team_snapshot_unavailable'); + } + }, + }; +} diff --git a/phone-host/test/chat-host.test.mjs b/phone-host/test/chat-host.test.mjs index 95c9c0e1c6..4db3bfdb08 100644 --- a/phone-host/test/chat-host.test.mjs +++ b/phone-host/test/chat-host.test.mjs @@ -3,12 +3,12 @@ // are fake agents on PATH that write fixture transcripts where the real ones would. import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; -import { chmodSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs'; +import { chmodSync, mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { after, before, describe, it } from 'node:test'; import { fileURLToPath } from 'node:url'; -import { createChatSessions } from '../src/chat-sessions.mjs'; +import { claudeFolderTrusted, createChatSessions } from '../src/chat-sessions.mjs'; import { createFullMethods } from '../src/full-methods.mjs'; import { decodePairingOffer } from '../src/offer.mjs'; import { mintPairing } from '../src/pairing.mjs'; @@ -26,6 +26,7 @@ const FAKE_CLAUDE = `#!/usr/bin/env node const fs = require('fs'); const path = require('path'); const id = process.argv[process.argv.indexOf('--session-id') + 1]; const dir = path.join(process.env.FAKE_CLAUDE_ROOT, process.cwd().replace(/[^A-Za-z0-9]/g, '-')); +if (process.env.FAKE_CLAUDE_QUIET) { console.log('FAKE-CLAUDE waiting at its trust prompt'); setTimeout(() => {}, 60000); return; } fs.mkdirSync(dir, { recursive: true }); const file = path.join(dir, id + '.jsonl'); const lines = fs.readFileSync(path.join(process.env.FAKE_FIXTURES, 'claude-transcript.jsonl'), 'utf8').replaceAll('SESSION', id).split('\\n'); @@ -52,7 +53,7 @@ setTimeout(() => {}, 60000); `; describe('chat view over the phone connection', () => { - let store; let host; let terminals; let worktreeId; let phone; let readOnly; let claudeRoot; let codexRoot; let tabs; + let store; let host; let terminals; let worktreeId; let repoDir; let phone; let readOnly; let claudeRoot; let codexRoot; let tabs; const saved = { PATH: process.env.PATH, SHELL: process.env.SHELL, HOME: process.env.HOME }; const wt = () => ({ worktree: `id:${worktreeId}` }); @@ -65,7 +66,7 @@ describe('chat view over the phone connection', () => { // `claude` ahead of the fake one on PATH. Object.assign(process.env, { PATH: `${bin}:${saved.PATH}`, SHELL: '/bin/sh', HOME: tmp(), FAKE_CLAUDE_ROOT: claudeRoot, FAKE_CODEX_ROOT: codexRoot, FAKE_FIXTURES: fixtureDir }); - const repoDir = tmp(); + repoDir = tmp(); const g = (...a) => execFileSync('git', ['-C', repoDir, ...a], { stdio: 'pipe' }); g('init', '-q', '-b', 'main'); g('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '--allow-empty', '-m', 'init'); const projects = createProjectCatalog(await resolveProjects({ projects: [repoDir] })); @@ -74,7 +75,7 @@ describe('chat view over the phone connection', () => { store = openStore({ dir: tmp() }); terminals = createTerminalManager({ pty: await loadPty() }); const chatSessions = createChatSessions({ roots: { claude: [claudeRoot], codex: [codexRoot] }, pollMs: 100, maxPollMs: 200 }); - const fullMethods = createFullMethods({ terminals, projects, chatSessions, chatPollMs: 100 }); + const fullMethods = createFullMethods({ terminals, projects, chatSessions, chatPollMs: 100, trustPollMs: 100 }); host = await startPhoneHost({ store, bind: '127.0.0.1', port: 0, projects, fullMethods }); phone = await connectPhone(decodePairingOffer(mintPairing({ store, endpoint: host.endpoint, name: 'Full', access: 'full' }).url)); readOnly = await connectPhone(decodePairingOffer(mintPairing({ store, endpoint: host.endpoint, name: 'RO' }).url)); @@ -91,9 +92,10 @@ describe('chat view over the phone connection', () => { const tabRow = async (id, pred) => (await tabs.until((f) => f.result?.type === 'updated' && f.result.tabs.some((t) => t.id === id && pred(t)), 15000)).result.tabs.find((t) => t.id === id); - it('a Claude tab carries its session from the start, and its transcript streams to the chat view', async () => { + it('a Claude tab reports its session once Claude is past its trust prompt, and its transcript streams to the chat view', async () => { const created = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'claude' }); - const row = await tabRow(created.result.tab.id, (t) => t.agentStatus); + // This folder is not trusted (a fresh HOME), so the session shows once Claude writes its transcript. + const row = await tabRow(created.result.tab.id, (t) => t.agentStatus?.providerSession); const { agentStatus } = row; assert.equal(row.launchAgent, 'claude'); assert.equal(agentStatus.agentType, 'claude'); @@ -130,6 +132,33 @@ describe('chat view over the phone connection', () => { assert.equal(end.streaming, undefined); }); + it('holds a Claude tab\'s session back while Claude waits at its trust prompt, and shows it once the folder is trusted', async () => { + process.env.FAKE_CLAUDE_QUIET = '1'; + let created; + try { created = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'claude' }); } finally { delete process.env.FAKE_CLAUDE_QUIET; } + const id = created.result.tab.id; + const waiting = await tabRow(id, (t) => t.agentStatus); + await new Promise((r) => setTimeout(r, 2000)); + const still = (await phone.call('session.tabs.list', wt())).result?.tabs?.find((t) => t.id === id) ?? waiting; + assert.equal(still.agentStatus.agentType, 'claude'); + assert.equal(still.agentStatus.providerSession, undefined, 'no session while the trust prompt is up'); + writeFileSync(join(process.env.HOME, '.claude.json'), JSON.stringify({ projects: { [repoDir]: { hasTrustDialogAccepted: true } } })); + const shown = await tabRow(id, (t) => t.agentStatus?.providerSession); + assert.match(shown.agentStatus.providerSession.id, /^[0-9a-f-]{36}$/); + await phone.call('session.tabs.close', { ...wt(), tabId: id, reason: 'user' }); + }); + + it('counts only a trust Claude recorded for that exact folder', async () => { + const home = tmp(); const env = { CLAUDE_CONFIG_DIR: home }; + const parent = tmp(); const child = join(parent, 'child'); mkdirSync(child); + assert.equal(await claudeFolderTrusted(child, env), false, 'no file'); + writeFileSync(join(home, '.claude.json'), '{not json'); + assert.equal(await claudeFolderTrusted(child, env), false, 'unreadable'); + writeFileSync(join(home, '.claude.json'), JSON.stringify({ projects: { [parent]: { hasTrustDialogAccepted: true }, [child]: { hasTrustDialogAccepted: false } } })); + assert.equal(await claudeFolderTrusted(child, env), false, 'a parent folder does not count'); + assert.equal(await claudeFolderTrusted(parent, env), true); + }); + it('a Codex tab gains its session once Codex writes its rollout, and the chat view reads it', async () => { const created = await phone.call('session.tabs.createTerminal', { ...wt(), agent: 'codex' }); const id = created.result.tab.id; diff --git a/phone-host/test/full.test.mjs b/phone-host/test/full.test.mjs index 82b360782c..79ed79d28f 100644 --- a/phone-host/test/full.test.mjs +++ b/phone-host/test/full.test.mjs @@ -101,6 +101,19 @@ describe('full access: tabs, terminals and agents', () => { await phone.call('terminal.send', { terminal, text: 'stty size', enter: true }); await term.until(() => text(term).includes('20 60')); + // A late cancel of an older stream must not stop the newer one on the same terminal and client. + const client = { id: 'phone-1', type: 'mobile' }; + const fresh = phone.stream('terminal.subscribe', { terminal, client, viewport: { cols: 60, rows: 20 } }); + await fresh.until((f) => f.result?.type === 'subscribed'); + await phone.call('terminal.unsubscribe', { subscriptionId: terminal, client: { id: 'phone-1' }, requestId: term.id }); + await phone.call('terminal.send', { terminal, text: 'echo still-$((6*7))', enter: true }); + await fresh.until(() => text(fresh).includes('still-42')); + // Without a requestId the slot is used, so this one ends the live stream. + await phone.call('terminal.unsubscribe', { subscriptionId: terminal, client: { id: 'phone-1' } }); + await phone.call('terminal.send', { terminal, text: 'echo gone-$((6*8))', enter: true }); + await new Promise((r) => setTimeout(r, 400)); + assert.ok(!text(fresh).includes('gone-48'), 'the slot cancel ended the stream'); + const list = await phone.call('terminal.list', { worktree: `id:${worktreeId}` }); assert.ok(list.result.terminals.some((t) => t.handle === terminal)); diff --git a/phone-host/test/host.test.mjs b/phone-host/test/host.test.mjs index 87bca65cda..1198956cec 100644 --- a/phone-host/test/host.test.mjs +++ b/phone-host/test/host.test.mjs @@ -266,6 +266,50 @@ describe('access levels', () => { }); }); +describe('teams and swarms', () => { + it('shows a read-only phone the swarms, claims and Claude teams in shared workspaces only, without secrets', async () => { + const { execFileSync } = await import('node:child_process'); + const { realpathSync } = await import('node:fs'); + const { resolveProjects, createProjectCatalog } = await import('../src/projects.mjs'); + const repoDir = realpathSync(tmp()); const elsewhere = realpathSync(tmp()); const home = realpathSync(tmp()); + execFileSync('git', ['-C', repoDir, 'init', '-q', '-b', 'main']); + const write = (path, value) => { mkdirSync(join(path, '..'), { recursive: true }); writeFileSync(path, JSON.stringify(value)); }; + const now = Date.now(); const iso = new Date(now).toISOString(); + write(join(repoDir, '.claude-flow', 'swarm', 'swarm-state.json'), { swarms: { + s1: { swarmId: 'swarm-1', topology: 'hierarchical', status: 'running', maxAgents: 8, agents: [{}, {}], tasks: [{}], updatedAt: iso, config: { strategy: 'specialized' } }, + s2: { swarmId: 'swarm-old', status: 'terminated' } } }); + write(join(repoDir, '.claude-flow', 'hive-mind', 'state.json'), { initialized: true, topology: 'mesh', hiveToken: 'SECRET-HIVE-TOKEN', workers: [{}], updatedAt: iso }); + write(join(repoDir, '.claude-flow', 'claims', 'claims.json'), { claims: { c1: { issueId: 'pr-7', status: 'active', claimant: { agentId: 'coder-1' }, claimedAt: now, context: 'SECRET-CONTEXT' } } }); + const team = (name, cwd) => write(join(home, '.claude', 'teams', name, 'config.json'), + { leadAgentId: 'lead', createdAt: now, members: [{ agentId: 'lead', name: 'team-lead', cwd, prompt: 'SECRET-PROMPT' }, { agentId: 'w', name: 'worker', cwd }] }); + team('shared-team', join(repoDir, 'src')); team('private-team', elsewhere); + write(join(home, '.claude', 'teams', 'shared-team', 'inboxes', 'team-lead.json'), + [{ from: 'worker', timestamp: iso, text: JSON.stringify({ type: 'idle_notification', summary: 'done with tests' }) }]); + + const { repos } = await resolveProjects([repoDir]); + const savedHome = process.env.HOME; process.env.HOME = home; + const s = openStore({ dir: tmp() }); + let h; + try { h = await startPhoneHost({ store: s, bind: BIND, port: 0, projects: createProjectCatalog({ repos }) }); } finally { process.env.HOME = savedHome; } + try { + const phone = await connectPhone(decodePairingOffer(mintPairing({ store: s, endpoint: h.endpoint, name: 'Monitor' }).url)); + const r = await phone.call('ruflo.teamSnapshot.read', {}); + assert.equal(r.ok, true, JSON.stringify(r.error)); + assert.equal(r.result.workspaces.length, 1); + const [ws] = r.result.workspaces; + assert.match(ws.id, /^[0-9a-f]{16}$/, 'the key is a hash, not the path'); + assert.deepEqual(ws.claudeTeams.map((t) => t.name), ['shared-team']); + assert.equal(ws.claudeTeams[0].members.find((m) => m.name === 'worker').status, 'idle'); + assert.deepEqual(ws.ruflo.swarms.map((x) => [x.id, x.agentCount, x.strategy]), [['swarm-1', 2, 'specialized']]); + assert.equal(ws.ruflo.hive.workerCount, 1); + assert.deepEqual(ws.ruflo.claims.map((c) => [c.issueId, c.claimant]), [['pr-7', 'coder-1']]); + const sent = JSON.stringify(r.result); + for (const secret of ['SECRET-HIVE-TOKEN', 'SECRET-CONTEXT', 'SECRET-PROMPT', elsewhere, home]) assert.ok(!sent.includes(secret), secret); + await phone.close(); + } finally { await h.close(); } + }); +}); + describe('default listen address', () => { const lan = (address, name = 'en0') => ({ name, address, kind: 'lan' }); it('prefers a tailnet address', () => {