const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/webviewWindow-CHLyLPiW.js","assets/core-DcH9fClu.js"])))=>i.map(i=>d[i]);
import{r as e}from"./core-DcH9fClu.js";import{n as t,t as n}from"./host-IZNQjG4L.js";import{a as r,r as i,t as a}from"./taskTags-BEqMEKnV.js";var o={version:1,project:{id:`orchestra`,slug:`orchestra`,name:`Orchestra`,description:`Seeded starter workspace for strategy, planning, and development work. You can rename, replace, archive, or delete it at any time.`,taskPrefix:`ORC`},roles:[{id:`role-architect`,slug:`architect`,name:`Architect`,description:`Clarifies requirements, frames technical direction, and produces implementation-ready plans.`,systemPrompt:`You are the Architect role in Orchestra. Your job is to turn fuzzy requests into clear, workable technical direction. Optimize for clarity, sound structure, practical tradeoffs, and a plan other workers can execute without guessing.

When you work, first make sure you understand the problem, constraints, dependencies, and desired outcome. Call out assumptions, open questions, risks, and sequencing issues early. Prefer the smallest design that satisfies the requirement well. When multiple approaches are possible, compare them briefly and recommend one with a concrete reason.

Good output from you is specific and execution-ready: crisp scope, proposed architecture or change shape, key data/model impacts, integration points, validation expectations, and follow-up risks worth tracking. In Orchestra, keep the task state accurate: leave useful comments when important decisions are made, capture why the plan changed, and make handoffs easy for implementation and QA.

Avoid vague strategy, overengineering, and plans that only restate the problem. Do not hide uncertainty. If something needs a decision, say so directly and explain the options.`,provider:null,model:null,thinkingLevel:`high`,capacity:1,directPermissions:[`tasks.read`,`tasks.create`,`tasks.update`,`tasks.comment`,`tasks.transition`,`tasks.attachments.write`,`tasks.dependencies.write`]},{id:`role-senior-developer`,slug:`senior-developer`,name:`Senior Developer`,description:`Implements approved work carefully, validates changes, and delivers reviewable results.`,systemPrompt:`You are the Senior Developer role in Orchestra. Your job is to implement approved work carefully, keep changes scoped, and leave the codebase better understood than you found it. Optimize for correctness, maintainability, and reliable delivery.

Before changing code, understand the current behavior and the intended outcome. Follow the approved plan when one exists, and only expand scope when the new work is clearly necessary to make the feature correct. Validate the important paths you touched, explain the tradeoffs you made, and surface any follow-up items that should stay visible.

Good output from you includes clean implementation, focused diffs, relevant tests or verification steps, and concise notes about what changed and why. In Orchestra, keep the task state accurate: leave progress comments during substantial work, note meaningful decisions, and make it easy for QA and reviewers to understand what to check.

Avoid speculative rewrites, unnecessary churn, hidden shortcuts, and claiming confidence without evidence. If validation is limited, say exactly what you did and what still needs verification.`,provider:null,model:null,thinkingLevel:`medium`,capacity:2,directPermissions:[`tasks.read`,`tasks.create`,`tasks.update`,`tasks.comment`,`tasks.transition`,`tasks.attachments.write`,`tasks.dependencies.write`]},{id:`role-qa`,slug:`qa`,name:`QA`,description:`Verifies acceptance criteria, reproduces defects precisely, and reports findings with evidence.`,systemPrompt:`You are the QA role in Orchestra. Your job is to verify whether work actually satisfies the requirement and to communicate findings clearly enough that the next person knows exactly what to do. Optimize for evidence, reproducibility, regression awareness, and release confidence.

Start from the acceptance criteria and the stated intent of the change. Check the primary path, relevant edge cases, and the most likely regressions. When you find a problem, report the observed behavior, expected behavior, concrete repro steps, and the impact. Distinguish blockers from nits and unknowns.

Good output from you is decisive and well-supported: pass/fail framing, evidence, concise repro notes, and clear follow-up guidance. In Orchestra, keep task state accurate by leaving durable comments with findings, referencing exactly what was validated, and avoiding ambiguous "looks good" approvals.

Avoid vague feedback, unprioritized laundry lists, and conclusions without evidence. If you could not validate something, say what prevented it and what still needs coverage.`,provider:null,model:null,thinkingLevel:`medium`,capacity:1,directPermissions:[`tasks.read`,`tasks.create`,`tasks.update`,`tasks.comment`,`tasks.transition`,`tasks.attachments.write`,`tasks.dependencies.write`]},{id:`role-product-owner`,slug:`product-owner`,name:`Product Owner`,description:`Keeps work aligned to user value, scope, and acceptance criteria.`,systemPrompt:`You are the Product Owner role in Orchestra. Your job is to keep work anchored to real user value, clear scope, and explicit acceptance criteria. Optimize for outcome clarity, sensible prioritization, and decisions that reduce ambiguity for the rest of the workflow.

When you work, make the user problem, expected behavior, constraints, and success conditions explicit. Tighten scope when a request is broad, highlight tradeoffs, and identify missing information early. Prefer simple statements of intent that can be tested and implemented directly.

Good output from you includes clear problem framing, concrete acceptance criteria, explicit priorities, and crisp guidance about what is in or out of scope. In Orchestra, leave comments that capture product decisions and rationale so downstream workers do not have to reverse-engineer intent.

Avoid placeholder requirements, hand-wavy priorities, and acceptance criteria that depend on interpretation. If something is unclear, surface it instead of letting the workflow drift.`,provider:null,model:null,thinkingLevel:`medium`,capacity:1,directPermissions:[`tasks.read`,`tasks.create`,`tasks.update`,`tasks.comment`,`tasks.transition`,`tasks.attachments.write`,`tasks.dependencies.write`]},{id:`role-project-manager`,slug:`project-manager`,name:`Project Manager`,description:`Keeps execution sequenced, coordinated, and accurately tracked.`,systemPrompt:`You are the Project Manager role in Orchestra. Your job is to keep execution moving in the right order with clear ownership, visible blockers, and reliable status. Optimize for coordination, sequencing, and handoffs that reduce idle time and confusion.

When you work, identify what is blocking progress, what can happen in parallel, what depends on what, and what decision or artifact is needed next. Turn vague progress into concrete status. Keep plans realistic and keep the next action obvious.

Good output from you includes clear sequencing, blocker tracking, ownership clarity, and concise status notes that help everyone else move faster. In Orchestra, use comments and task structure to make progress legible, preserve context at lane boundaries, and call out follow-up items that should not be lost.

Avoid status theater, redundant commentary, and handoffs that say work moved without explaining why. If something is blocked, say what is blocked, by whom, and what unblocks it.`,provider:null,model:null,thinkingLevel:`low`,capacity:1,directPermissions:[`tasks.read`,`tasks.create`,`tasks.update`,`tasks.comment`,`tasks.transition`,`tasks.attachments.write`,`tasks.dependencies.write`]}],workflows:[{id:`workflow-development`,slug:`development`,name:`Development`,description:`Plan, implement, verify, and review delivery work.`,lanes:[{id:`lane-development-plan`,key:`plan`,name:`Plan`,description:`Turn the request into an implementation-ready technical approach.`,order:0,assignedEntityType:`role`,assignedEntityId:`architect`,entryPromptTemplate:`Review the task, clarify the approach, and leave an implementation-ready plan with notable risks or dependencies.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`lane`,successTargetLaneId:`lane-development-implement`,failureTransitionType:`user_intervention`,failureTargetLaneId:null},{id:`lane-development-implement`,key:`implement`,name:`Implement`,description:`Execute the approved plan and validate the changed behavior.`,order:1,assignedEntityType:`role`,assignedEntityId:`senior-developer`,entryPromptTemplate:`Implement the planned change, keep the diff focused, run relevant validation, and document important tradeoffs or follow-up work.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`lane`,successTargetLaneId:`lane-development-verify`,failureTransitionType:`lane`,failureTargetLaneId:`lane-development-plan`},{id:`lane-development-verify`,key:`verify`,name:`Verify`,description:`Validate acceptance criteria and report concrete findings.`,order:2,assignedEntityType:`role`,assignedEntityId:`qa`,entryPromptTemplate:`Verify the delivered work against the acceptance criteria, check likely regressions, and leave evidence-backed findings.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`lane`,successTargetLaneId:`lane-development-review`,failureTransitionType:`lane`,failureTargetLaneId:`lane-development-implement`},{id:`lane-development-review`,key:`review`,name:`Review`,description:`User review and final disposition.`,order:3,assignedEntityType:`user`,assignedEntityId:null,entryPromptTemplate:`Review the completed work, approve it if it meets expectations, or send it back with specific feedback.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`end`,successTargetLaneId:null,failureTransitionType:`lane`,failureTargetLaneId:`lane-development-implement`}]},{id:`workflow-product-strategy`,slug:`product-strategy`,name:`Product Strategy`,description:`Frame an opportunity, pressure-test it technically, and prepare it for review.`,lanes:[{id:`lane-product-strategy-opportunity`,key:`frame-opportunity`,name:`Frame opportunity`,description:`Clarify the user problem, target outcome, and success criteria.`,order:0,assignedEntityType:`role`,assignedEntityId:`product-owner`,entryPromptTemplate:`Frame the opportunity from the user and product perspective, define success, and call out scope or ambiguity that needs resolution.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`lane`,successTargetLaneId:`lane-product-strategy-technical`,failureTransitionType:`user_intervention`,failureTargetLaneId:null},{id:`lane-product-strategy-technical`,key:`technical-framing`,name:`Technical framing`,description:`Assess feasibility, constraints, and implementation implications.`,order:1,assignedEntityType:`role`,assignedEntityId:`architect`,entryPromptTemplate:`Assess feasibility, technical constraints, and major implementation considerations for the proposed strategy.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`lane`,successTargetLaneId:`lane-product-strategy-delivery`,failureTransitionType:`lane`,failureTargetLaneId:`lane-product-strategy-opportunity`},{id:`lane-product-strategy-delivery`,key:`delivery-framing`,name:`Delivery framing`,description:`Outline sequencing, dependencies, and execution concerns.`,order:2,assignedEntityType:`role`,assignedEntityId:`project-manager`,entryPromptTemplate:`Translate the strategy into execution terms: sequencing, dependencies, risks, and the shape of the work required.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`lane`,successTargetLaneId:`lane-product-strategy-review`,failureTransitionType:`lane`,failureTargetLaneId:`lane-product-strategy-technical`},{id:`lane-product-strategy-review`,key:`review`,name:`Review`,description:`User review of the proposed strategy.`,order:3,assignedEntityType:`user`,assignedEntityId:null,entryPromptTemplate:`Review the proposed strategy, approve it if it is directionally right, or return it with specific feedback.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`end`,successTargetLaneId:null,failureTransitionType:`lane`,failureTargetLaneId:`lane-product-strategy-opportunity`}]},{id:`workflow-planning`,slug:`planning`,name:`Planning`,description:`Turn scoped product intent into an execution-ready plan.`,lanes:[{id:`lane-planning-scope`,key:`clarify-scope`,name:`Clarify scope`,description:`Confirm what is in scope, what success looks like, and what must not be missed.`,order:0,assignedEntityType:`role`,assignedEntityId:`product-owner`,entryPromptTemplate:`Clarify the scope, acceptance criteria, assumptions, and open questions so downstream planning is grounded in a clear outcome.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`lane`,successTargetLaneId:`lane-planning-technical`,failureTransitionType:`user_intervention`,failureTargetLaneId:null},{id:`lane-planning-technical`,key:`technical-plan`,name:`Technical plan`,description:`Define the implementation approach, risks, and technical sequencing.`,order:1,assignedEntityType:`role`,assignedEntityId:`architect`,entryPromptTemplate:`Produce an implementation-ready technical plan, including risks, dependencies, and the most important validation expectations.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`lane`,successTargetLaneId:`lane-planning-execution`,failureTransitionType:`lane`,failureTargetLaneId:`lane-planning-scope`},{id:`lane-planning-execution`,key:`execution-plan`,name:`Execution plan`,description:`Turn the technical plan into concrete sequencing and ownership.`,order:2,assignedEntityType:`role`,assignedEntityId:`project-manager`,entryPromptTemplate:`Break the plan into a realistic execution sequence, call out blockers and dependencies, and make the next steps obvious.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`lane`,successTargetLaneId:`lane-planning-review`,failureTransitionType:`lane`,failureTargetLaneId:`lane-planning-technical`},{id:`lane-planning-review`,key:`review`,name:`Review`,description:`User review of the full plan.`,order:3,assignedEntityType:`user`,assignedEntityId:null,entryPromptTemplate:`Review the proposed plan, approve it if it is execution-ready, or send it back with specific gaps or changes.`,useSeparateWorktree:!1,requireUserApprovalOnSuccess:!1,successTransitionType:`end`,successTargetLaneId:null,failureTransitionType:`lane`,failureTargetLaneId:`lane-planning-scope`}]}]};o.version;var s=o.project.id;o.project.slug;function c(e){return{id:e.id,key:e.key,name:e.name,description:e.description??null,order:e.order,assignedEntityType:e.assignedEntityType,assignedEntityId:e.assignedEntityId??null,entryPromptTemplate:e.entryPromptTemplate??null,useSeparateWorktree:!!e.useSeparateWorktree,requireUserApprovalOnSuccess:!!e.requireUserApprovalOnSuccess,needsWorkTargetLaneId:null,successTransitionType:e.successTransitionType,successTargetLaneId:e.successTargetLaneId??null,failureTransitionType:e.failureTransitionType,failureTargetLaneId:e.failureTargetLaneId??null}}function l(e=new Date().toISOString()){return[{id:o.project.id,slug:o.project.slug,name:o.project.name,description:o.project.description??null,taskPrefix:o.project.taskPrefix,defaultRepositoryId:null,createdAt:e,updatedAt:e,repositories:[]}]}function u(e=new Date().toISOString()){return o.roles.map(t=>({id:t.id,slug:t.slug,name:t.name,description:t.description??null,systemPrompt:t.systemPrompt??null,provider:t.provider??null,model:t.model??null,thinkingLevel:t.thinkingLevel,capacity:t.capacity,policyIds:[],directPermissions:[...t.directPermissions??[]],archived:!1,createdAt:e,updatedAt:e}))}function d(e=new Date().toISOString()){return o.workflows.map(t=>({id:t.id,slug:t.slug,name:t.name,description:t.description??null,archived:!1,createdAt:e,updatedAt:e,lanes:t.lanes.map(c)}))}var f=`orchestra.preferences.active-project-id`,p=`orchestra.mock.active-project-id`,m=`orchestra.preferences.active-project-slug`,h=`orchestra:projects-changed`;function g(e){return window.localStorage.getItem(e)}function _(){return g(f)??g(p)??null}function ee(){return g(m)??null}function v(e,t){let n=_(),r=ee();e?(window.localStorage.setItem(f,e),window.localStorage.setItem(p,e)):(window.localStorage.removeItem(f),window.localStorage.removeItem(p));let i=t?.trim()||null;i?window.localStorage.setItem(m,i):window.localStorage.removeItem(m),(n!==e||r!==i)&&window.dispatchEvent(new CustomEvent(h))}var te=/^[A-Z][A-Z0-9]{1,7}$/,ne=/^([A-Za-z][A-Za-z0-9]*)-([0-9]+)(.*)$/,re=8,ie=2;function ae(e){return e.toUpperCase().replace(/[^A-Z0-9]+/g,``)}function y(e){let t=ae(e);return t||=`PR`,/^[A-Z]/.test(t)||(t=`P${t}`),t.length<ie&&(t=`${t}X`),t.slice(0,re)}function oe(e){let t=e.trim().split(/[^A-Za-z0-9]+/).map(e=>ae(e)).filter(Boolean),n=t.length>1?t.map(e=>e[0]??``).join(``):ae(e).slice(0,3);return n.length<ie&&(n=ae(e)),y(n)}function se(e,t){let n=y(e),r=n,i=2;for(;t.has(r);){let e=String(i);r=y(`${n.slice(0,Math.max(1,re-e.length))}${e}`),i+=1}return r}function ce(e){return(e??``).trim().toUpperCase()}function le(e){let t=ce(e);return t?te.test(t)?null:`Task prefix must start with a letter and contain only A-Z or 0-9.`:`Task prefix is required.`}function ue(e,t=[]){let n=new Set(Array.from(t,e=>ce(e)).filter(Boolean));return se(oe(e),n)}function de(e,t){return`${ce(e)}-${t}`}function fe(e){if(!e)return{hasTask:!1,prefix:``,sequence:1/0,suffix:``};let t=e.match(ne);return t?{hasTask:!0,prefix:(t[1]??``).toLowerCase(),sequence:Number.parseInt(t[2]??``,10),suffix:(t[3]??``).toLowerCase()}:{hasTask:!0,prefix:e.toLowerCase(),sequence:1/0,suffix:``}}var pe=null;function me(e){pe=e}function he(){return pe}function b(){return pe?.bootstrap.hostKind===`remote_api`?pe:null}var ge=`orchestra.mock.projects`,_e=`orchestra.mock.sessions`,ve=`orchestra.mock.session-models`,ye=`orchestra.mock.dismissed-sessions`,be=`orchestra.mock.tasks`,xe=`orchestra.mock.task-dependencies`,Se=`orchestra.mock.task-comment-user-receipts`,Ce=`orchestra.mock.mailbox`,we=`orchestra.mock.agent-runtimes`,Te=`orchestra.mock.agent-queue`,Ee=`orchestra.mock.task-schedules`,De=`orchestra.mock.domain-events`,Oe=`no-project`;function x(){return!!window.__TAURI_INTERNALS__}function S(){return b()?.client??null}function ke(e){return`${e}-${Math.random().toString(36).slice(2,8)}-${Date.now().toString(36)}`}function C(){return new Date().toISOString()}function Ae(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`project`}function je(){let e=window.localStorage.getItem(ge);return e?JSON.parse(e):null}function w(e){window.localStorage.setItem(ge,JSON.stringify(e)),window.dispatchEvent(new CustomEvent(`orchestra:projects-changed`))}function T(e){let t=window.localStorage.getItem(e);return t?JSON.parse(t):[]}function Me(e,t){window.localStorage.setItem(e,JSON.stringify(t))}function Ne(e){let t=new Set(T(be).filter(t=>t.projectId===e).map(e=>e.id)),n=new Set(T(Ee).filter(t=>t.projectId===e).map(e=>e.id));Me(be,T(be).filter(t=>t.projectId!==e)),Me(xe,T(xe).filter(e=>!t.has(e.blockerTaskId)&&!t.has(e.blockedTaskId))),Me(Se,T(Se).filter(e=>!t.has(e.taskId))),Me(Ce,T(Ce).filter(n=>n.projectId!==e&&!(n.taskId&&t.has(n.taskId)))),Me(we,T(we).filter(t=>t.projectId!==e)),Me(Te,T(Te).filter(n=>n.projectId!==e&&!(n.sourceTaskId&&t.has(n.sourceTaskId)))),Me(Ee,T(Ee).filter(t=>t.projectId!==e)),Me(De,T(De).filter(t=>t.projectId!==e).filter(e=>!e.entityId||!t.has(e.entityId)&&!n.has(e.entityId))),window.localStorage.removeItem(`${_e}.${e}`),window.localStorage.removeItem(`${ve}.${e}`),window.localStorage.removeItem(`${ye}.${e}`)}function Pe(){return l(C())}function Fe(e,t,n){let r=e.name.trim();if(!r)throw Error(`Project name is required.`);let i=le(e.taskPrefix);if(i)throw Error(i);let a=ce(e.taskPrefix);if(t.some(e=>e.id!==n&&ce(e.taskPrefix)===a))throw Error(`Task prefix ${a} is already used by another project.`);return{name:r,taskPrefix:a}}function Ie(e){let t=new Set,n=!1,r=e.map(e=>{let r=ce(e.taskPrefix),i=!le(r)&&!t.has(r)?r:ue(e.id===s?`Orchestra`:e.name,t);return t.add(i),e.taskPrefix===i?e:(n=!0,{...e,taskPrefix:i})});return n&&w(r),r}function E(){let e=je();if(e)return Ie(e);let t=Pe();return w(t),!_()&&t[0]&&v(t[0].id,t[0].slug),t}function Le(e,t){return t&&e.some(e=>e.id===t)?t:e[0]?.id??null}function Re(){let e=_();return x()||n()?e:Le(E(),e)}function D(){let e=_();return x()||n()?e:Le(E(),e)}function ze(){if(n()||x())return ee();let e=E(),t=Le(e,_());return e.find(e=>e.id===t)?.slug??e[0]?.slug??null}function Be(e){if(x()||n())return`/mock/projects/${e??D()??s}`;let t=E(),r=Le(t,e??D()),i=r?t.find(e=>e.id===r)??null:null;return(i?.defaultRepositoryId?i.repositories.find(e=>e.id===i.defaultRepositoryId)??null:i?.repositories[0]??null)?.repositoryPath??`/mock/projects/${i?.slug??r??Oe}`}function Ve(e,t){v(e,t)}async function He(){let t=S();return t?t.catalog.listProjects():x()?e(`list_projects`):E().map(({repositories:e,...t})=>t)}async function Ue(t){let n=S();if(n)return n.catalog.getProject(t);if(!x()){let e=E().find(e=>e.id===t);if(!e)throw Error(`Project ${t} was not found`);return e}return e(`get_project`,{projectId:t})}function We(){window.dispatchEvent(new CustomEvent(`orchestra:projects-changed`))}async function O(e){let t=await e();return We(),t}async function Ge(t){let n=S();return n?n.projects.listRepositories(t??null):x()?e(`list_repositories`,{projectId:t??null}):t?Ue(t).then(e=>e.repositories):E().flatMap(e=>e.repositories)}async function Ke(t){let n=S();if(n)return n.projects.getRepository(t);if(!x()){let e=E().flatMap(e=>e.repositories).find(e=>e.id===t)??null;if(!e)throw Error(`Repository ${t} was not found`);return e}return e(`get_repository`,{repositoryId:t})}async function qe(t){let n=S();if(n)return O(()=>n.projects.createProject(t));if(!x()){let e=E(),{name:n,taskPrefix:r}=Fe(t,e),i=C(),a={id:ke(`project`),slug:Ae(n),name:n,description:t.description?.trim()||null,taskPrefix:r,defaultRepositoryId:null,repositories:[],createdAt:i,updatedAt:i};return w([a,...e]),Ve(a.id,a.slug),a}return O(()=>e(`create_project`,{input:t}))}async function Je(t,n){let r=S();if(r)return O(()=>r.projects.updateProject(t,n));if(!x()){let e=E(),r=e.find(e=>e.id===t);if(!r)throw Error(`Project ${t} was not found`);let{name:i,taskPrefix:a}=Fe(n,e,t),o={...r,slug:Ae(i),name:i,description:n.description?.trim()||null,taskPrefix:a,updatedAt:C()};return w(e.map(e=>e.id===t?o:e)),o}return O(()=>e(`update_project`,{projectId:t,input:n}))}async function Ye(t){let n=S();if(n)return O(()=>n.projects.deleteProject(t));if(!x()){let e=E(),n=e.find(e=>e.id===t);if(!n)throw Error(`Project ${t} was not found`);let r=_(),i=e.filter(e=>e.id!==t);if(r===t){let e=i[0]??null;Ve(e?.id??null,e?.slug??null)}return Ne(t),w(i),We(),n}return O(()=>e(`delete_project`,{projectId:t}))}async function Xe(t,n){let r=S();if(r)return O(()=>r.projects.createRepository(t,n));if(!x()){let e=E(),r=e.find(e=>e.id===t);if(!r)throw Error(`Project ${t} was not found`);let i=n.mode===`local_new`?`local_new`:`existing`,a={id:ke(`repo`),projectId:t,slug:Ae(n.name),name:n.name.trim(),repositoryPath:i===`local_new`?`/mock/projects/${r.slug}/repositories/${Ae(n.name)}/repository`:n.repositoryPath?.trim()||null,sourcePath:i===`existing`&&n.repositoryPath?.trim()||null,sourceKind:i===`existing`&&n.repositoryPath?.trim()?n.repositoryPath.includes(`://`)||n.repositoryPath.includes(`@`)?`remote`:`local`:null,mode:i,defaultBranch:n.defaultBranch?.trim()||null,createdAt:C(),updatedAt:C()},o={...r,repositories:[a,...r.repositories],defaultRepositoryId:r.defaultRepositoryId??a.id,updatedAt:C()};return w(e.map(e=>e.id===t?o:e)),D()===t&&window.dispatchEvent(new CustomEvent(`orchestra:projects-changed`)),a}return O(()=>e(`create_repository`,{projectId:t,input:n}))}async function Ze(t,n){let r=S();if(r)return O(()=>r.projects.updateRepository(t,n));if(!x()){let e=E(),r=null;if(w(e.map(e=>({...e,repositories:e.repositories.map(e=>{if(e.id!==t)return e;let i=e.mode??(n.mode===`local_new`?`local_new`:`existing`),a=i===`local_new`?e.sourcePath??null:n.repositoryPath?.trim()||null;return r={...e,slug:Ae(n.name),name:n.name.trim(),repositoryPath:i===`local_new`?e.repositoryPath??null:n.repositoryPath?.trim()||null,sourcePath:a,sourceKind:i===`local_new`?e.sourceKind??null:a?a.includes(`://`)||a.includes(`@`)?`remote`:`local`:null,mode:i,defaultBranch:n.defaultBranch?.trim()||null,updatedAt:C()},r})}))),!r)throw Error(`Repository ${t} was not found`);return r}return O(()=>e(`update_repository`,{repositoryId:t,input:n}))}async function Qe(t){let n=S();if(n)return O(()=>n.projects.deleteRepository(t));if(!x()){let e=E(),n=null;if(w(e.map(e=>{let r=e.repositories.find(e=>e.id===t)??null;if(!r)return e;n=r;let i=e.repositories.filter(e=>e.id!==t);return{...e,repositories:i,defaultRepositoryId:e.defaultRepositoryId===t?i[0]?.id??null:e.defaultRepositoryId,updatedAt:C()}})),!n)throw Error(`Repository ${t} was not found`);return n}return O(()=>e(`delete_repository`,{repositoryId:t}))}async function $e(t,n){let r=S();if(r)return O(()=>r.projects.attachRepositoryRemote(t,n));if(!x()){let e=E(),r=null;if(w(e.map(e=>({...e,repositories:e.repositories.map(e=>e.id===t?(r={...e,sourcePath:n.remoteUrl.trim(),sourceKind:`remote`,updatedAt:C()},r):e)}))),!r)throw Error(`Repository ${t} was not found`);return r}return O(()=>e(`attach_repository_remote`,{repositoryId:t,input:n}))}async function et(t,n){let r=S();if(r)return O(()=>r.projects.setProjectDefaultRepository(t,n));if(!x()){let e=E(),r=null;if(w(e.map(e=>e.id===t?(r={...e,defaultRepositoryId:n,updatedAt:C()},r):e)),!r)throw Error(`Project ${t} was not found`);return r}return O(()=>e(`set_project_default_repository`,{projectId:t,repositoryId:n}))}var k={sessionStream:`orchestra:session-stream`,sessionChange:`orchestra:session-change`,taskChange:`orchestra:task-change`,inboxChange:`orchestra:inbox-change`,notificationIntent:`orchestra:notification-intent`};function tt(e,t){window.dispatchEvent(new CustomEvent(e,{detail:t}))}function A(e){tt(k.sessionStream,e)}function j(e){tt(k.sessionChange,e)}function M(e){tt(k.taskChange,e)}function nt(e){tt(k.inboxChange,e)}function rt(e){tt(k.notificationIntent,e)}function it(e){return[e.taskNumber,e.workerName].filter(Boolean).join(` · `)||(e.workerName??`Standalone session`)}function at(e){return e.taskTitle??e.title}function ot(e){return e.activeTaskId??e.taskId??e.taskNumber??null}function st(e){switch(e){case`active`:return 0;case`closed`:return 1;case`hidden`:return 2;default:return 3}}function ct(e,t){let n=fe(e.taskNumber),r=fe(t.taskNumber);if(n.hasTask!==r.hasTask)return n.hasTask?-1:1;let i=n.prefix.localeCompare(r.prefix,void 0,{numeric:!0,sensitivity:`base`});if(i!==0)return i;if(n.sequence!==r.sequence)return n.sequence-r.sequence;let a=n.suffix.localeCompare(r.suffix,void 0,{numeric:!0,sensitivity:`base`});if(a!==0)return a;let o=ot(e),s=ot(t);if(o&&o===s){let n=!!e.activeTaskId;if(n!==!!t.activeTaskId)return n?-1:1;let r=st(e.listVisibility)-st(t.listVisibility);if(r!==0)return r;let i=t.updatedAt.localeCompare(e.updatedAt);if(i!==0)return i;let a=t.createdAt.localeCompare(e.createdAt);if(a!==0)return a}let c=(e.workerName??``).localeCompare(t.workerName??``,void 0,{numeric:!0,sensitivity:`base`});if(c!==0)return c;let l=at(e).localeCompare(at(t),void 0,{numeric:!0,sensitivity:`base`});if(l!==0)return l;let u=e.title.localeCompare(t.title,void 0,{numeric:!0,sensitivity:`base`});if(u!==0)return u;let d=e.createdAt.localeCompare(t.createdAt);return d===0?e.id.localeCompare(t.id,void 0,{numeric:!0,sensitivity:`base`}):d}function lt(e){return[...e].sort(ct)}var ut=`orchestra.mock.sessions`,dt=`orchestra.mock.projects`,ft=`no-project`;function pt(e){return`${e}-${Math.random().toString(36).slice(2,8)}-${Date.now().toString(36)}`}function mt(){return new Date().toISOString()}function ht(e,t,n){return{id:pt(`event`),kind:e,message:t,timestamp:mt(),...n}}function gt(){let e=window.localStorage.getItem(dt);return e?JSON.parse(e):l().map(e=>({id:e.id,slug:e.slug}))}function _t(e){let t=gt();return e&&t.some(t=>t.id===e)?e:t[0]?.id??null}function vt(e){return`${ut}.${_t(e??D())??ft}`}function yt(e){let t=window.localStorage.getItem(vt(e));return t?JSON.parse(t):[]}function bt(e,t){window.localStorage.setItem(vt(t),JSON.stringify(e))}function xt(e,t){bt(lt([e,...yt(t).filter(t=>t.id!==e.id)]),t)}function St(e,t){let n=mt();return{id:pt(`session`),title:e,status:`active`,createdAt:n,updatedAt:n,subscribed:!1,listVisibility:`active`,messageability:`messageable`,events:[ht(`system`,`${e} created from Orchestra runtime.`),ht(`assistant`,t)],controlCapabilities:{reload:{status:`supported`,reason:null},compact:{status:`supported`,reason:null},autoCompact:{status:`supported`,reason:null},effectiveCompactionWindow:`10%`,effectiveCompactionWindowSource:`global`},controlOperation:null}}var Ct=`orchestra.mock.project-settings`;function wt(){let e=window.localStorage.getItem(Ct);return e?JSON.parse(e):{}}function Tt(e){window.localStorage.setItem(Ct,JSON.stringify(e))}function Et(e){let t=wt();return{...t.general??{},...t.projects?.[e]?.runtime??{}}}function Dt(e,t){let n=wt(),r=t(Et(e));return n.projects={...n.projects??{},[e]:{...n.projects?.[e]??{},runtime:r}},Tt(n),r}function Ot(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function kt(e,t){return e.find(e=>e.id===t)?.name??`Orchestra`}function At(e,t){let n=e.taskNumber?e.taskTitle?`${e.taskNumber} · ${e.taskTitle}`:e.taskNumber:null,r=Ot(e.body),i=[t,e.senderLabel,n].filter(Boolean).join(` · `);return r?`${i}\n${r}`:i}function jt(e,t,n){return[`${t} · ${e.number} · ${e.title}`,(e.activeLaneAssignment?.completionNotes?Ot(e.activeLaneAssignment.completionNotes):``)||(n===`task.awaiting_user_approval`?`Open Orchestra to approve the lane or send it back for more work.`:n===`task.awaiting_user_intervention`?`Open Orchestra to review the blocker and decide how to proceed.`:`Open Orchestra to review the task and continue the workflow.`)].filter(Boolean).join(`
`)}function Mt(e,t,n){let r=[t,e].filter(Boolean).join(` · `),i=Ot(n);return i?`${r}\n${i}`:r}function Nt(e,t){return{id:`notification-mailbox-${e.deliveryId}`,eventType:`mailbox.message_received`,title:`Orchestra — New message`,body:At(e,t),tag:`mailbox:${e.deliveryId}`,projectId:e.projectId,taskId:e.taskId??null,deliveryId:e.deliveryId,action:{type:`open_inbox`,taskId:e.taskId??null,sessionId:null,target:null},occurredAt:e.createdAt}}function Pt(e,t,n){return{id:`notification-task-${t}-${e.id}-${e.updatedAt}`,eventType:t,title:t===`task.awaiting_user_approval`?`Orchestra — Approval needed`:t===`task.awaiting_user_intervention`?`Orchestra — User intervention needed`:`Orchestra — Task assigned to you`,body:jt(e,n??`Orchestra`,t),tag:`task-attention:${t}:${e.id}`,projectId:e.projectId,taskId:e.id,deliveryId:null,action:{type:`open_task`,taskId:e.id,sessionId:null,target:t===`task.awaiting_user_approval`?`review`:`details`},occurredAt:e.updatedAt}}function Ft({sessionId:e,runId:t,sessionTitle:n,projectId:r,projectLabel:i,reply:a,occurredAt:o}){return{id:`notification-session-reply-completed-${e}-${t}`,eventType:`session.reply_completed`,title:`Orchestra — New reply`,body:Mt(n,i,a),tag:`session-reply:${e}`,projectId:r??null,taskId:null,deliveryId:null,action:{type:`open_session`,taskId:null,sessionId:e,target:null},occurredAt:o}}function It(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.style.display=`none`,document.body.appendChild(r),r.click(),r.remove(),queueMicrotask(()=>{URL.revokeObjectURL(n)})}function Lt(e){let t=atob(e);return Uint8Array.from(t,e=>e.charCodeAt(0))}function Rt(e,t){return new Blob([Lt(e)],{type:t||`application/octet-stream`})}var zt=new Set([`application/zip`,`application/x-zip-compressed`,`application/x-tar`,`application/gzip`,`application/x-gzip`,`application/x-7z-compressed`,`application/vnd.rar`,`application/x-rar-compressed`,`application/x-bzip2`,`application/x-xz`,`application/zstd`]),Bt=new Set([`application/json`,`application/ld+json`,`application/javascript`,`application/x-javascript`,`application/typescript`,`application/xml`,`application/rss+xml`,`application/atom+xml`,`application/x-sh`,`application/x-shellscript`,`application/sql`,`application/graphql`,`application/yaml`,`application/x-yaml`,`application/toml`,`application/x-toml`]),Vt=`.txt,.md,.markdown,.log,.csv,.tsv,.json,.jsonc,.yaml,.yml,.toml,.ini,.conf,.cfg,.env,.gitignore,.editorconfig,.npmrc,.js,.jsx,.mjs,.cjs,.ts,.tsx,.mts,.cts,.py,.rb,.go,.rs,.java,.kt,.swift,.c,.h,.cpp,.cxx,.cc,.hpp,.cs,.php,.sh,.bash,.zsh,.fish,.ps1,.xml,.html,.css,.scss,.less,.sql,.graphql,.gql`.split(`,`),Ht=new Set([`dockerfile`,`makefile`,`justfile`,`procfile`,`gemfile`,`rakefile`,`brewfile`,`podfile`,`readme`,`license`]),Ut=new Set([`text/markdown`,`text/x-markdown`,`application/markdown`,`application/x-markdown`]),Wt=[`.md`,`.markdown`,`.mdown`,`.mkd`,`.mdx`],Gt=[`.wav`,`.mp3`,`.m4a`,`.aac`,`.ogg`,`.flac`],Kt=[`.mp4`,`.mov`,`.m4v`,`.webm`,`.ogv`,`.avi`,`.mkv`],qt=[`.zip`,`.tar`,`.tgz`,`.gz`,`.bz2`,`.xz`,`.7z`,`.rar`];function Jt(e){return typeof e.base64Data==`string`}function Yt(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}async function Xt(e){if(Jt(e))return e;let t=await e.file.arrayBuffer();return{fileName:e.fileName,mediaType:e.mediaType,base64Data:Yt(new Uint8Array(t)),caption:e.caption??null}}function Zt(e){if(!Number.isFinite(e)||e<=0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n>=10||r===0?Math.round(n):Math.round(n*10)/10} ${t[r]}`}function Qt(e){return e.split(`;`)[0]?.trim().toLowerCase()??``}function $t(e){return e?.split(`/`).pop()?.trim().toLowerCase()??``}function en(e){let t=Qt(e);return t.startsWith(`text/`)||Bt.has(t)||t.endsWith(`+json`)||t.endsWith(`+xml`)||t.endsWith(`+yaml`)}function tn(e){let t=$t(e);return Ht.has(t)||Vt.some(e=>t.endsWith(e))}function nn(e,t){let n=Qt(e),r=$t(t);return Ut.has(n)||Wt.some(e=>r.endsWith(e))?`markdown`:n.startsWith(`image/`)?`image`:n.startsWith(`video/`)||Kt.some(e=>r.endsWith(e))?`video`:n.startsWith(`audio/`)||Gt.some(e=>r.endsWith(e))?`audio`:zt.has(n)||qt.some(e=>r.endsWith(e))?`archive`:en(n)||tn(r)?`text`:`binary`}function rn(e){switch(e){case`markdown`:return`markdown`;case`text`:return`text`;case`image`:return`image`;case`video`:return`video`;case`audio`:return`audio`;case`archive`:return`archive`;default:return`binary`}}function an(e){switch(e){case`audio`:return{label:`Audio attachment`,description:`Preview is intentionally skipped for audio files here. Download the file to listen locally.`};case`archive`:return{label:`Archive attachment`,description:`Archives are stored and downloadable as-is. Download the file to inspect its contents locally.`};case`binary`:return{label:`Binary attachment`,description:`This file type is stored without inline preview. Download it to inspect the original bytes locally.`};default:return{label:`Attachment`,description:`Download this attachment to inspect it locally.`}}}var on={field:`updatedAt`,direction:`desc`},sn={P0:0,P1:1,P2:2,P3:3,P4:4},cn={draft:0,ready:1,in_progress:2,blocked:3,in_review:4,completed:5,canceled:6};function ln(e){return e.trim().toLowerCase()}function un(e){return dn(e).join(`\0`)}function dn(e){return i(Array.isArray(e.tags)?e.tags:[])}function fn(e,t){return e.localeCompare(t,void 0,{sensitivity:`base`})}function pn(e,t){return e-t}function mn(e,t){return pn(Date.parse(e),Date.parse(t))}function hn(e,t,n){let r=un(e),i=un(t),a=r.length===0;if(a!==(i.length===0))return a?1:-1;let o=n===`asc`?1:-1;return fn(r,i)*o}function gn(e,t,n){switch(n.field){case`createdAt`:return mn(e.createdAt,t.createdAt);case`priority`:return pn(sn[e.priority]??2**53-1,sn[t.priority]??2**53-1);case`title`:return fn(e.title,t.title);case`status`:return pn(cn[e.status]??2**53-1,cn[t.status]??2**53-1);default:return mn(e.updatedAt,t.updatedAt)}}function _n(e,t,n){let r=n.direction===`asc`?1:-1,i=n.field===`tags`?hn(e,t,n.direction):gn(e,t,n)*r;if(i!==0)return i;let a=mn(e.updatedAt,t.updatedAt)*-1;if(a!==0)return a;let o=mn(e.createdAt,t.createdAt)*-1;if(o!==0)return o;let s=fn(e.number,t.number);return s===0?fn(e.id,t.id):s}function vn(e,t){let n=i((t?.tags??[]).map(ln));if(n.length===0)return e;let r=t?.tagMatch===`all`?`all`:`any`;return e.filter(e=>{let t=dn(e);return r===`all`?n.every(e=>t.includes(e)):n.some(e=>t.includes(e))})}function yn(e,t){let n=t??on;return e.slice().sort((e,t)=>_n(e,t,n))}function bn(e,t){return yn(vn(e,t),t?.sort??on)}function xn(e){return e.status===`in_review`&&e.assigneeType===`user`&&!!e.currentLaneId}function Sn(e){let t=e.activeLaneAssignment;if(!t)return null;if(xn(e)){if(t.pendingOutcome===`success`)return`awaiting_user_approval`;if(t.pendingOutcome===`needs_user`)return`awaiting_user_intervention`;if(t.pendingOutcome===`paused`)return`paused_by_user`}return[`awaiting_user_approval`,`awaiting_user_intervention`,`paused_by_user`].includes(t.status)?t.status:null}function Cn(e){return Sn(e)??e.activeLaneAssignment?.status??null}function wn(e){return{kind:`session.change`,...e}}function Tn(e){return{kind:`session.stream`,...e}}function En(e){return{kind:`task.change`,...e}}function Dn(e){return{kind:`inbox.change`,...e}}function On(e){return{kind:`notification.intent`,...e}}async function kn(e,t){let n=e=>{e instanceof CustomEvent&&t(e.detail)};return window.addEventListener(e,n),()=>{window.removeEventListener(e,n)}}function An(e){return kn(k.sessionStream,e)}function jn(e){return kn(k.sessionChange,e)}function Mn(e){return kn(k.taskChange,e)}function Nn(e){return kn(k.inboxChange,e)}function Pn(e){return kn(k.notificationIntent,e)}async function Fn(e){let[t,n,r,i,a]=await Promise.all([An(t=>e(Tn(t))),jn(t=>e(wn(t))),Mn(t=>e(En(t))),Nn(t=>e(Dn(t))),Pn(t=>e(On(t)))]);return()=>{t(),n(),r(),i(),a()}}var In=`modulepreload`,Ln=function(e){return`/`+e},Rn={},zn=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=Ln(t,n),t in Rn)return;Rn[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:In,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Bn=`orchestra.mock.logs`,Vn=`orchestra.mock.session-diagnostic-logs`,Hn=`orchestra.mock.sessions`,Un=`orchestra.mock.session-models`,Wn=`orchestra.mock.workflows`,Gn=`orchestra.mock.tasks`,Kn=`orchestra.mock.task-attachment-bytes`,qn=`orchestra.mock.file-contents`,Jn=`orchestra.mock.task-dependencies`,Yn=`orchestra.mock.task-comment-receipts`,Xn=`orchestra.mock.task-comment-user-receipts`,Zn=`orchestra.mock.mailbox`,Qn=`orchestra.mock.agents`,$n=`orchestra.mock.agent-runtimes`,er=`orchestra.mock.agent-queue`,tr=`orchestra.mock.roles`,nr=`orchestra.mock.role-queue`,rr=`orchestra.mock.role-instances`,ir=`orchestra.mock.bridge-diagnostics`,ar=`orchestra.mock.active-session-runs`,or=`orchestra.mock.dismissed-sessions`,sr=`orchestra.mock.harness-settings`,cr=`orchestra.mock.pi-setup`,lr=`orchestra.mock.pi-oauth-flow`,ur=`orchestra.mock.pi-models-json`,dr=`orchestra.mock.task-schedules`,fr=`orchestra.mock.domain-events`,pr=`orchestra.mock.app-update-status`,mr=`no-project`,hr=`Great work finishing the next slice, keep going in the next todo until you have finished it!`,gr=`Great work finishing this next slice, create todos for the remaining work then keep working until you finish the next todos`;function _r(){let e=window.__ORCHESTRA_WINDOW_KIND__;return typeof e==`string`?e:null}function vr(e,t){let n=window,r=n.__orchestraTestMockSessionFailures;if(!Array.isArray(r)||r.length===0)return null;let i=r.findIndex(n=>n.operation===e&&n.sessionId===t);if(i===-1)return null;let[a]=r.splice(i,1);return a&&a.once===!1&&r.push(a),n.__orchestraTestMockSessionFailures=r,a??null}function yr(e,t){let n=vr(e,t);if(n)throw Error(n.message)}function br(){return L(sr)??{}}function xr(){return L(`orchestra.mock.projects`)??l()}function Sr(){return xr().map(e=>({id:e.id,slug:e.slug}))}function Cr(e){let t=Sr();return e&&t.some(t=>t.id===e)?e:t[0]?.id??null}function wr(e){return Sr().some(t=>t.id===e)}function Tr(e,t=`task`){let n=Cr(e);if(n)return n;throw Error(`Create a project before creating a ${t}.`)}function Er(){return _r()===`logs`||new URLSearchParams(window.location.search).get(`view`)===`logs`}function Dr(){return _r()===`agent-terminal`||new URLSearchParams(window.location.search).get(`view`)===`agent-terminal`}function Or(){let e=window.__ORCHESTRA_AGENT_TERMINAL_SESSION_ID__;return typeof e==`string`&&e.length>0?e:new URLSearchParams(window.location.search).get(`sessionId`)}function kr(e){return`${Hn}.${Cr(e??D())??mr}`}function Ar(e){return`${Un}.${Cr(e??D())??mr}`}function jr(e){return`${or}.${Cr(e??D())??mr}`}var Mr=[{id:`claude-sonnet-4-20250514`,name:`Claude Sonnet 4`,provider:`anthropic`,api:`anthropic-messages`,reasoning:!0},{id:`gpt-5.4`,name:`GPT-5.4`,provider:`openai-codex`,api:`openai-codex-responses`,reasoning:!0},{id:`gemini-2.5-pro`,name:`Gemini 2.5 Pro`,provider:`google`,api:`google-generative-ai`,reasoning:!0}];function N(e){return`${e}-${Math.random().toString(36).slice(2,8)}-${Date.now().toString(36)}`}function P(){return new Date().toISOString()}function Nr(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`workflow`}function Pr(e,t){switch(e){case`debug`:case`info`:case`warn`:case`error`:return e;default:return t===`sessions.rpc.event`?`debug`:`info`}}function Fr(e){let t=Pr(e.level,e.target);return t===e.level?e:{...e,level:t}}function Ir(e,t,n){return{id:N(`log`),level:Pr(e,t),target:t,message:n,timestamp:P()}}function F(e,t,n){return{id:N(`event`),kind:e,message:t,timestamp:P(),...n}}function Lr(){return{bun:{available:!1,path:null,message:`Browser-mode mock does not resolve Bun.`},sources:[],blocking:!1,packageFreeProbeSucceeded:!1,packageFreeModelCount:0,message:`No package-based Pi sources are configured in browser-mode mock.`}}function I(){return L(cr)??{status:`ready`,agentDir:`/mock/.orchestra/runtime/pi/agent`,authPath:`/mock/.orchestra/runtime/pi/agent/auth.json`,modelsPath:`/mock/.orchestra/runtime/pi/agent/models.json`,settingsPath:`/mock/.orchestra/runtime/pi/agent/settings.json`,legacyAgentDir:`/mock/.pi/agent`,availableProviders:[{id:`anthropic`,name:`Anthropic`,authModes:[`api_key`,`oauth`],connected:!0,usingOAuth:!1,modelCount:1,usesCallbackServer:!0,oauthMethods:[{id:`browser_oauth`,label:`Browser sign-in`,kind:`browser`,isDefault:!0}]},{id:`openai`,name:`OpenAI`,authModes:[`api_key`],connected:!0,usingOAuth:!1,modelCount:1,usesCallbackServer:!1,oauthMethods:null},{id:`openai-codex`,name:`OpenAI Codex`,authModes:[`oauth`],connected:!1,usingOAuth:!1,modelCount:1,usesCallbackServer:!0,oauthMethods:[{id:`browser_oauth`,label:`Browser sign-in`,kind:`browser`,isDefault:!0}]},{id:`github-copilot`,name:`GitHub Copilot`,authModes:[`oauth`],connected:!1,usingOAuth:!1,modelCount:1,usesCallbackServer:!1,oauthMethods:[{id:`device_code`,label:`Device code auth`,kind:`device_code`,isDefault:!0}]}],availableModels:Mr,issues:[],warnings:[],importState:{canImportLegacy:!1,importedAt:null,dismissedAt:null},packageDiagnostics:Lr()}}function Rr(e){R(cr,e)}function zr(){return L(lr)}function Br(e){if(!e){window.localStorage.removeItem(lr);return}R(lr,e)}function Vr(e){window.dispatchEvent(new CustomEvent(`orchestra:pi-setup-change`,{detail:e}))}function Hr(e){window.dispatchEvent(new CustomEvent(`orchestra:pi-oauth-flow-change`,{detail:e}))}function Ur(e,t){let n=t??[],r=n.find(e=>e.isDefault)??n[0]??null;if(!r)throw Error(`Provider ${e} does not expose any OAuth methods.`);return r}function Wr(e,t){let n=I(),r={...n,status:`ready`,issues:[],warnings:[],availableProviders:n.availableProviders.map(n=>n.id===e?{...n,connected:!0,usingOAuth:t}:n)};return Rr(r),r}function Gr(e){Hr({...e,status:`succeeded`,prompt:null,error:null,latestProgressMessage:`Connected.`,finishedAt:P()}),Wr(e.providerId,!0),Br(null),Vr({reason:`pi.oauth.succeeded`,providerId:e.providerId})}function Kr(){return window.localStorage.getItem(ur)??`{
  "providers": {}
}
`}function qr(e){window.localStorage.setItem(ur,e)}function L(e){let t=window.localStorage.getItem(e);return t?JSON.parse(t):null}function Jr(){return L(pr)??{currentVersion:`0.1.0`,currentChannel:`dev`,catalogueUrl:`https://orchestra.hnsn.io/releases/dev/versions.json`,state:`checking`,latestVersion:null,latestPublishedAt:null,latestChangelogUrl:null,lastCheckedAt:null,lastSuccessfulCheckAt:null,nextCheckAt:null,error:null}}function Yr(){return L(Xn)??[]}function Xr(e){R(Xn,e)}function Zr(){return L(Yn)??[]}function Qr(e){return{...e,originType:e.originType??`user`,originId:e.originId??null}}function $r(e){let t=e.activeLaneAssignment?.sessionId?.trim(),n=t?Zr():[];return e.comments.map(r=>{let i=Qr(r),{activeAssignmentReadAt:a,...o}=i;if(!t||i.originType!==`user`)return o;let s=n.find(n=>n.commentId===i.id&&n.taskId===e.id&&n.sessionId===t)?.readAt??null;return s?{...o,activeAssignmentReadAt:s}:o})}function ei(e){let t=Yr();return e.comments.map(Qr).filter(e=>e.originType!==`user`).filter(n=>!t.some(t=>t.commentId===n.id&&t.taskId===e.id&&t.userId===`desktop-user`)).length}function R(e,t){window.localStorage.setItem(e,JSON.stringify(t))}function ti(){return L(Kn)??{}}function ni(e){R(Kn,e)}function ri(){return L(Zn)??[]}function ii(e){R(Zn,e)}function z(e,t,n){return{sessionId:e,runId:t,event:n,receivedAt:P()}}function ai(){return[Ir(`info`,`app.bootstrap`,`Frontend scaffold initialized`),Ir(`info`,`session.mock`,`Using browser-backed session fallback until Tauri backend is running`)]}function oi(){let e=P();return[{id:N(`session`),title:`Session-first spike`,status:`idle`,createdAt:e,updatedAt:e,subscribed:!1,events:[F(`system`,`Mock session created in browser fallback mode.`),F(`assistant`,`Ready when you are. Create a session, resume it, or send me a message.`)]}]}function si(){return d(P())}function ci(){let e=L(Bn);if(e){let t=e.map(Fr);return t.some((t,n)=>t.level!==e[n]?.level)&&R(Bn,t),t}let t=ai();return R(Bn,t),t}function li(){return[{id:N(`session-diagnostic`),sessionId:`session-1`,runId:`run-1`,level:`error`,code:`session.rpc.error`,message:`Mock session failed to resolve a project working directory.`,timestamp:P(),detailsText:JSON.stringify({cwd:null,reason:`missing_project_root`},null,2)},{id:N(`session-diagnostic`),sessionId:`session-2`,runId:`run-2`,level:`warn`,code:`session.context.degraded`,message:`Mock session continued with a reduced context snapshot.`,timestamp:P(),detailsText:JSON.stringify({mode:`fallback`,filesSkipped:3},null,2)}]}function ui(){let e=L(Vn);if(e)return e;let t=li();return R(Vn,t),t}function di(e){return{id:e.id,sourceId:`runtime`,sourceKind:`runtime`,timestamp:e.timestamp,level:e.level,category:e.target,message:e.message,sessionId:null,runId:null,detailsPreview:null,detailsText:null}}function fi(e,t){let n=t.detailsText??null;return{id:t.id,sourceId:e,sourceKind:`session_diagnostic`,timestamp:t.timestamp,level:t.level,category:t.code,message:t.message,sessionId:t.sessionId,runId:t.runId??null,detailsPreview:n?n.replace(/\s+/g,` `).trim().slice(0,240):null,detailsText:n}}function pi(){let e=ci(),t=ui(),n=t.map(e=>e.timestamp).sort().slice(-1)[0]??null,r=Array.from(new Set(t.map(e=>e.sessionId)));return[{id:`runtime`,kind:`runtime`,label:`Runtime log`,description:`Recent Orchestra app/runtime log entries persisted under the local runtime root.`,path:`/mock/.orchestra/runtime/logs/runtime-log.jsonl`,updatedAt:e[0]?.timestamp??null,supportsClear:!0,supportsOpenFile:!0,supportsOpenDirectory:!0,availability:`available`,unavailableReason:null},{id:`session-diagnostics`,kind:`session_diagnostic`,label:`Session diagnostics`,description:`Read-only diagnostic JSONL events aggregated across recently updated sessions.`,path:`/mock/.orchestra/runtime/session-diagnostics`,updatedAt:n,supportsClear:!1,supportsOpenFile:!1,supportsOpenDirectory:!0,availability:`available`,unavailableReason:null},...r.map(e=>({id:`session-diagnostic:${e}`,kind:`session_diagnostic`,label:`Session diagnostics · ${e}`,description:`Read-only diagnostic events recorded for a single session.`,path:`/mock/.orchestra/runtime/session-diagnostics/${e}.jsonl`,updatedAt:t.find(t=>t.sessionId===e)?.timestamp??null,supportsClear:!1,supportsOpenFile:!0,supportsOpenDirectory:!0,availability:`available`,unavailableReason:null}))]}function B(e){let t=L(kr(e));if(t)return t;let n=Cr(e??D());if(e&&e!==n)return[];let r=oi();return R(kr(n),r),r}function mi(){let e=L(ir);if(e)return e;let t=P(),n={instance:{instanceId:`bridge-instance-browser`,url:`http://127.0.0.1:0`,ownerPid:0,startedAt:t,heartbeatAt:t,metadataPath:`/mock/.orchestra/bridge/bridge-instance-browser.json`,activeClientCount:0,inFlightRequestCount:0},clients:[],recentRequests:[],recentCleanupEvents:[]};return R(ir,n),n}function hi(){return L(Qn)??[]}function V(){return L($n)??[]}function H(e){R($n,e)}function gi(){return L(er)??[]}function _i(e){R(er,e)}function vi(){return L(tr)??[]}function yi(){return L(nr)??[]}function bi(e){R(nr,e)}function xi(){return L(rr)??[]}function Si(e){R(rr,e)}function Ci(e){let t=new Map(hi().map(e=>[e.id,e.slug])),n=new Map(vi().map(e=>[e.id,e.slug]));return e.map(e=>({...e,lanes:e.lanes.map(e=>e.assignedEntityType===`agent`&&e.assignedEntityId&&t.has(e.assignedEntityId)?{...e,assignedEntityId:t.get(e.assignedEntityId)??e.assignedEntityId}:e.assignedEntityType===`role`&&e.assignedEntityId&&n.has(e.assignedEntityId)?{...e,assignedEntityId:n.get(e.assignedEntityId)??e.assignedEntityId}:e)}))}function U(){let e=L(Wn);if(e){let t=Ci(e);return JSON.stringify(t)!==JSON.stringify(e)&&R(Wn,t),t}let t=si();return R(Wn,t),t}function wi(e){R(Wn,e)}function Ti(){return L(Ar())??{}}function Ei(e){R(Ar(),e)}function Di(){let e=L(ar)??{},t=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Array.isArray(t)?t:typeof t==`string`&&t?[t]:[]]).filter(([,e])=>e.length>0));return JSON.stringify(e)!==JSON.stringify(t)&&R(ar,t),t}function Oi(e){R(ar,e)}function ki(e,t){return Di()[e]?.includes(t)??!1}function Ai(e){let t=Ti();return t[e]||(t[e]=Mr[0],Ei(t)),t[e]}function W(e,t,n){let r=ci();R(Bn,[Ir(e,t,n),...r].slice(0,200))}function ji(e){return new Set(L(jr(e))??[])}function Mi(e,t){R(jr(t),Array.from(new Set(e)).sort())}function Ni(e,t){R(kr(t),e)}function Pi(e,t,n,r){return{...e,taskId:t.id,taskProjectId:t.projectId,taskNumber:t.number,taskTitle:t.title,activeTaskId:t.id,activeTaskProjectId:t.projectId,activeTaskNumber:t.number,activeTaskTitle:t.title,workerType:n,workerName:r??null}}function Fi(e){return{...e,activeTaskId:null,activeTaskProjectId:null,activeTaskNumber:null,activeTaskTitle:null}}function Ii(e,t){if(!t.trim())return!1;let n=typeof e.sessionKind==`string`?e.sessionKind:null,r=typeof e.ownerWorkerType==`string`?e.ownerWorkerType:e.workerType??null,i=!!(e.activeTaskId??e.taskId??e.primaryTaskId);return n===`agent_main`&&r===`agent`&&!!e.agentId&&!i}function Li(e,t,n){if(!Ii(e,n))return null;let r=xr(),i=e.projectId??D()??null;return Ft({sessionId:e.id,runId:t,sessionTitle:e.title,projectId:i,projectLabel:kt(r,i),reply:n,occurredAt:P()})}function Ri(e,t){let n=e?.sessionId??null,r=t?.sessionId??null;!n||n===r||(G(n,e=>Fi(e)),j({sessionIds:[n],reason:`task.assignment.cleared`}))}function zi(e,t){let n=V().find(e=>e.agentId===t&&e.projectId===s)??null,r=typeof n?.mainSessionId==`string`?n.mainSessionId:null,i=(r?B().find(e=>e.id===r)??null:null)??St(`${e} main session`.replace(/(^|\s)\S/g,e=>e.toUpperCase()),`${e} is ready. This persistent session keeps the agent context for dispatched work.`);return Ai(i.id),xt(i),H(V().map(e=>e.agentId===t&&e.projectId===s?{...e,mainSessionId:i.id,runtimeCwd:typeof e.runtimeCwd==`string`&&e.runtimeCwd?e.runtimeCwd:Be(s),status:e.currentQueueEntryId?`running`:`idle`,updatedAt:P()}:e)),i}function G(e,t){let n=B().map(n=>n.id===e?t(n):n);return Ni(n),n.find(t=>t.id===e)??null}function Bi(e){return lt(e)}function Vi(e){return`Acknowledged: ${e}\n\nThis is the mock session layer. The UI flow for create, resume, subscribe, interaction, and model switching is wired and ready for the real pi backend.`}function Hi(e){return{sessionId:e,currentModel:Ai(e),currentThinkingLevel:`medium`,availableModels:Mr}}function Ui(e){return{id:e.id,slug:e.slug,name:e.name,description:e.description,archived:e.archived,laneCount:e.lanes.length,createdAt:e.createdAt,updatedAt:e.updatedAt}}function Wi(e){let t=Y().filter(t=>t.workflowId===e.id).length,n=Yi().filter(t=>t.taskBlueprint.workflowId===e.id).length,r=[];return t>0&&r.push(`${t} ${t===1?`task`:`tasks`}`),n>0&&r.push(`${n} ${n===1?`task schedule`:`task schedules`}`),{workflowId:e.id,workflowName:e.name,canDelete:r.length===0,referenceCounts:{tasks:t,taskSchedules:n,taskLaneAssignments:0,roleQueueEntries:0,agentQueueEntries:0},blockerMessages:r}}function Gi(){let e=P(),t=U()[0],n=t?.lanes[0],r=t?.lanes[1],i=N(`task`),a=N(`task`),o=N(`task`),c=N(`session`),l=[{id:i,projectId:s,number:`ORC-1`,title:`Define Orchestra task system`,description:`Document the task model including hierarchy, dependencies, attachments, and task tools.`,type:`epic`,status:`ready`,priority:`P1`,workflowId:t?.id??null,currentLaneId:n?.id??null,assigneeType:`user`,assigneeId:null,repositoryId:null,repositoryIds:[],tags:[],parentTaskId:null,archived:!1,commentCount:0,unreadCommentCount:0,laneRunCount:0,childCount:0,completedChildCount:0,inProgressChildCount:0,blockedChildCount:0,blockedByCount:0,blockingCount:0,attachmentCount:0,dependencyBlocked:!1,readyForDispatch:!0,parent:null,lineage:[],children:[],blockedBy:[],blocking:[],attachments:[],taskRepositories:[],fileReferences:[],activeLaneAssignment:null,createdAt:e,updatedAt:e,comments:[],todos:[],laneRuns:[],laneSummaries:[]},{id:a,projectId:s,number:`ORC-2`,title:`Implement task foundation shell`,description:`Add the first real Tasks page with list/detail editing so task orchestration can move out of placeholders.`,type:`feature`,status:`in_progress`,priority:`P1`,workflowId:t?.id??null,currentLaneId:r?.id??null,assigneeType:`role`,assigneeId:`developer`,repositoryId:null,repositoryIds:[],tags:[],parentTaskId:i,archived:!1,commentCount:1,unreadCommentCount:0,laneRunCount:1,childCount:0,completedChildCount:0,inProgressChildCount:0,blockedChildCount:0,blockedByCount:0,blockingCount:0,attachmentCount:0,dependencyBlocked:!1,readyForDispatch:!0,parent:null,lineage:[],children:[],blockedBy:[],blocking:[],attachments:[],taskRepositories:[],fileReferences:[],activeLaneAssignment:null,createdAt:e,updatedAt:e,comments:[{id:N(`task-comment`),taskId:a,author:`User`,originType:`user`,originId:null,message:`Start with persistence and a task list/detail shell before layering on graph features.`,interruptAgent:!1,createdAt:e,updatedAt:e}],todos:[],laneRuns:r?[{id:N(`lane-run`),taskId:a,laneId:r.id,sessionId:c,result:`needs_user`,notes:`Waiting on task persistence APIs.`,startedAt:e,completedAt:null}]:[],laneSummaries:[]},{id:o,projectId:s,number:`ORC-3`,title:`Plan hierarchy rollups`,description:`Use the epic container to summarize child task progress and expose lineage in the task detail pane.`,type:`task`,status:`ready`,priority:`P2`,workflowId:t?.id??null,currentLaneId:n?.id??null,assigneeType:`user`,assigneeId:null,repositoryId:null,repositoryIds:[],tags:[],parentTaskId:i,archived:!1,commentCount:0,unreadCommentCount:0,laneRunCount:0,childCount:0,completedChildCount:0,inProgressChildCount:0,blockedChildCount:0,blockedByCount:0,blockingCount:0,attachmentCount:0,dependencyBlocked:!1,readyForDispatch:!0,parent:null,lineage:[],children:[],blockedBy:[],blocking:[],attachments:[],taskRepositories:[],fileReferences:[],activeLaneAssignment:null,createdAt:e,updatedAt:e,comments:[],todos:[],laneRuns:[],laneSummaries:[]}],u=[{id:N(`task-dependency`),blockerTaskId:a,blockedTaskId:o,blocker:Z(l[1]),blocked:Z(l[2]),createdAt:e}];return Ki(u),Oa(l,u)}function K(){return L(Jn)??[]}function Ki(e){R(Jn,e)}function qi(){return L(fr)??[]}function Ji(e){R(fr,e)}function q(e,t,n,r,i){let a=qi(),o={sequence:((a.length>0?a[a.length-1]?.sequence:0)??0)+1,id:N(`domain-event`),projectId:i??null,topic:e,entityType:t,entityId:n,payload:r,createdAt:P()};return Ji([...a,o]),o}function Yi(){return L(dr)??[]}function Xi(e){R(dr,e)}function Zi(e){return i(e??[])}function Qi(e){let t=Zi(e),n=[];return t.length>20&&n.push({path:`tags`,message:a}),t.forEach((e,t)=>{let i=r(e);i&&n.push({path:`tags[${t}]`,message:i})}),{normalized:t,errors:n}}function $i(e){return{...e,tags:Zi(e.tags),status:`ready`,archived:!1,currentLaneId:null}}function ea(e){let t=e.trim().match(/^(\d{2}):(\d{2})$/);if(!t)return null;let n=Number(t[1]),r=Number(t[2]);return!Number.isInteger(n)||!Number.isInteger(r)||n<0||n>23||r<0||r>59?null:{hours:n,minutes:r}}function ta(e,t){let n=new Intl.DateTimeFormat(`en-CA`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,hour12:!1}),r=Object.fromEntries(n.formatToParts(e).map(e=>[e.type,e.value]));return{year:Number(r.year),month:Number(r.month),day:Number(r.day),hour:Number(r.hour),minute:Number(r.minute)}}function na(e,t,n,r){let i=new Date(Date.UTC(e,t-1,n+r));return{year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate()}}function ra(e,t){return new Date(Date.UTC(e,t,0)).getUTCDate()}function ia(e,t,n,r){let i=new Date(Date.UTC(e,t-1+r,1)),a=i.getUTCFullYear(),o=i.getUTCMonth()+1;return{year:a,month:o,day:Math.min(n,ra(a,o))}}function aa(e,t,n,r,i,a){let o=Date.UTC(e,t-1,n,r,i,0,0),s=Date.UTC(e,t-1,n,r,i,0,0);for(let e=0;e<4;e+=1){let e=ta(new Date(o),a),t=s-Date.UTC(e.year,e.month-1,e.day,e.hour,e.minute,0,0);if(t===0)break;o+=t}return new Date(o)}function oa(e,t){if(e.type!==`time`)return null;let n=new Date(t);if(Number.isNaN(n.getTime()))throw Error(`trigger: Unable to parse schedule time trigger reference.`);switch(e.kind){case`once`:return e.at;case`everyMinutes`:return new Date(n.getTime()+Math.max(1,e.everyMinutes)*6e4).toISOString();case`daily`:{let t=ea(e.timeOfDay);if(!t)throw Error(`trigger.timeOfDay: Expected HH:MM in 24 hour time.`);let r=ta(n,e.timezone);for(let i=0;i<=7;i+=1){let a=na(r.year,r.month,r.day,i),o=aa(a.year,a.month,a.day,t.hours,t.minutes,e.timezone);if(o.getTime()>n.getTime())return o.toISOString()}throw Error(`trigger.timeOfDay: Unable to compute next daily fire time.`)}case`weekly`:{let t=ea(e.timeOfDay);if(!t)throw Error(`trigger.timeOfDay: Expected HH:MM in 24 hour time.`);if(!e.daysOfWeek.length)throw Error(`trigger.daysOfWeek: Select at least one weekday.`);let r=ta(n,e.timezone),i=[...e.daysOfWeek].sort((e,t)=>e-t);for(let a=0;a<=14;a+=1){let o=na(r.year,r.month,r.day,a),s=new Date(Date.UTC(o.year,o.month-1,o.day)).getUTCDay();if(!i.includes(s))continue;let c=aa(o.year,o.month,o.day,t.hours,t.minutes,e.timezone);if(c.getTime()>n.getTime())return c.toISOString()}throw Error(`trigger.daysOfWeek: Unable to compute next weekly fire time.`)}case`monthly`:{let t=ea(e.timeOfDay);if(!t)throw Error(`trigger.timeOfDay: Expected HH:MM in 24 hour time.`);let r=ta(n,e.timezone),i=Math.min(Math.max(1,e.dayOfMonth),31);for(let a=0;a<24;a+=1){let o=ia(r.year,r.month,i,a),s=aa(o.year,o.month,o.day,t.hours,t.minutes,e.timezone);if(s.getTime()>n.getTime())return s.toISOString()}throw Error(`trigger.dayOfMonth: Unable to compute next monthly fire time.`)}default:return null}}function sa(e,t,n,r){let i=P();return{id:N(`task-schedule-occurrence`),scheduleId:e,occurrenceKey:t,scheduledAt:n??null,eventId:r??null,status:`pending`,taskId:null,error:null,createdAt:i,updatedAt:i}}function ca(e,t){let n=new Set(e.occurrences.filter(e=>e.status===`materialized`&&e.taskId).map(e=>e.taskId));return t.filter(e=>n.has(e.id)&&![`completed`,`canceled`].includes(e.status)).length}function la(e,t){let n=e.occurrences.filter(e=>e.status===`materialized`&&e.taskId).map(e=>e.taskId);return{id:e.id,projectId:e.projectId,title:e.taskBlueprint.title,description:e.taskBlueprint.description??null,type:e.taskBlueprint.type,priority:e.taskBlueprint.priority,workflowId:e.taskBlueprint.workflowId??null,repositoryIds:e.taskBlueprint.repositoryIds??[],enabled:e.enabled,oneShot:e.oneShot,overlapPolicy:e.overlapPolicy,trigger:e.trigger,nextFireAt:e.nextFireAt??null,lastFiredAt:e.lastFiredAt??null,lastMaterializedTaskId:e.lastMaterializedTaskId??n[0]??null,lastError:e.lastError??null,materializedTaskCount:n.length,openMaterializedTaskCount:ca(e,t),createdAt:e.createdAt,updatedAt:e.updatedAt}}function ua(e,t){let n=la(e,t),r=e.occurrences.filter(e=>e.status===`materialized`&&e.taskId).slice().reverse().map(e=>t.find(t=>t.id===e.taskId)??null).filter(e=>!!e).map(e=>Z(e)).slice(0,10);return{...n,taskBlueprint:{...e.taskBlueprint},recentMaterializedTasks:r,recentOccurrences:e.occurrences.slice(-20).reverse()}}function da(e){try{return new Intl.DateTimeFormat(`en-US`,{timeZone:e}).format(new Date),!0}catch{return!1}}function fa(e,t){let n=[],r=Ma($i(e.task));return n.push(...r),[`skip`,`create_another`].includes(e.overlapPolicy)||n.push({path:`overlapPolicy`,message:`Expected skip or create_another.`}),e.trigger.type===`event`?e.trigger.eventKey.trim()||n.push({path:`trigger.eventKey`,message:`Event trigger key is required.`}):e.trigger.kind===`once`?(e.trigger.timezone.trim()?da(e.trigger.timezone.trim())||n.push({path:`trigger.timezone`,message:`Expected a valid IANA timezone such as UTC or America/New_York.`}):n.push({path:`trigger.timezone`,message:`Timezone is required.`}),Number.isNaN(Date.parse(e.trigger.at))&&n.push({path:`trigger.at`,message:`Expected an RFC3339 datetime.`})):e.trigger.kind===`everyMinutes`?e.trigger.everyMinutes<1&&n.push({path:`trigger.everyMinutes`,message:`Must be at least 1 minute.`}):e.trigger.kind===`daily`?(ea(e.trigger.timeOfDay)||n.push({path:`trigger.timeOfDay`,message:`Expected HH:MM in 24 hour time.`}),e.trigger.timezone.trim()?da(e.trigger.timezone.trim())||n.push({path:`trigger.timezone`,message:`Expected a valid IANA timezone such as UTC or America/New_York.`}):n.push({path:`trigger.timezone`,message:`Timezone is required.`})):e.trigger.kind===`weekly`?(ea(e.trigger.timeOfDay)||n.push({path:`trigger.timeOfDay`,message:`Expected HH:MM in 24 hour time.`}),e.trigger.timezone.trim()?da(e.trigger.timezone.trim())||n.push({path:`trigger.timezone`,message:`Expected a valid IANA timezone such as UTC or America/New_York.`}):n.push({path:`trigger.timezone`,message:`Timezone is required.`}),(!e.trigger.daysOfWeek.length||e.trigger.daysOfWeek.some(e=>e<0||e>6))&&n.push({path:`trigger.daysOfWeek`,message:`Select one or more weekdays between Sunday and Saturday.`})):e.trigger.kind===`monthly`&&(ea(e.trigger.timeOfDay)||n.push({path:`trigger.timeOfDay`,message:`Expected HH:MM in 24 hour time.`}),e.trigger.timezone.trim()?da(e.trigger.timezone.trim())||n.push({path:`trigger.timezone`,message:`Expected a valid IANA timezone such as UTC or America/New_York.`}):n.push({path:`trigger.timezone`,message:`Timezone is required.`}),(e.trigger.dayOfMonth<1||e.trigger.dayOfMonth>31)&&n.push({path:`trigger.dayOfMonth`,message:`Expected a day between 1 and 31.`})),n}function pa(e,t,n){let r=P(),i=$i(e.task),a=e.trigger.type===`time`?t?.nextFireAt??oa(e.trigger,r):null,o=t?.projectId??Tr(n??D(),`task schedule`);return{id:t?.id??N(`task-schedule`),projectId:o,taskBlueprint:i,enabled:e.enabled??t?.enabled??!0,oneShot:e.oneShot,overlapPolicy:e.overlapPolicy,trigger:e.trigger,nextFireAt:a,lastFiredAt:t?.lastFiredAt??null,lastMaterializedTaskId:t?.lastMaterializedTaskId??null,lastError:t?.lastError??null,occurrences:t?.occurrences??[],createdAt:t?.createdAt??r,updatedAt:r}}function ma(e){let t=Cr(e??D()),n=Yi(),r=qi(),i=Y(),a=!1,o=!1,s=e=>{let t=ja({...e.taskBlueprint,status:`ready`,archived:!1},void 0,e.projectId);return i=[t,...i].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)),o=!0,t};for(let e of n){if(e.projectId!==t||!e.enabled)continue;if(e.trigger.type===`time`){if(e.enabled&&e.nextFireAt&&Date.parse(e.nextFireAt)<=Date.now()){let t=sa(e.id,e.nextFireAt,e.nextFireAt,null),n=ca(e,i);if(e.overlapPolicy===`skip`&&n>0)t.status=`skipped`,t.error=`Skipped because an open materialized task already exists.`,t.updatedAt=P(),e.lastError=t.error;else{let n=s(e);t.status=`materialized`,t.taskId=n.id,t.updatedAt=P(),e.lastMaterializedTaskId=n.id,e.lastError=null,q(`task.created`,`task`,n.id,{taskId:n.id,taskNumber:n.number,status:n.status,workflowId:n.workflowId??null,laneId:n.currentLaneId??null,sourceScheduleId:e.id,sourceScheduleOccurrenceId:t.id},e.projectId),W(`info`,`task.schedule.materialized`,`Materialized task ${n.id} from schedule ${e.id}`)}e.lastFiredAt=t.scheduledAt??t.updatedAt,e.occurrences=[...e.occurrences,t],e.updatedAt=P(),e.nextFireAt=e.oneShot||e.trigger.kind===`once`?null:oa(e.trigger,t.scheduledAt??t.updatedAt),(e.oneShot||e.trigger.kind===`once`)&&(e.enabled=!1),a=!0}continue}let n=new Set(e.occurrences.map(e=>e.eventId).filter(e=>!!e));for(let t of r){if(!e.enabled)break;if(n.has(t.id)||t.topic!==e.trigger.eventKey||t.projectId&&t.projectId!==e.projectId||Date.parse(t.createdAt)<=Date.parse(e.updatedAt)||typeof t.payload.sourceScheduleId==`string`)continue;let r=sa(e.id,t.id,null,t.id),o=ca(e,i);if(e.overlapPolicy===`skip`&&o>0)r.status=`skipped`,r.error=`Skipped ${t.topic} because an open materialized task already exists.`,e.lastError=r.error;else{let t=s(e);r.status=`materialized`,r.taskId=t.id,e.lastMaterializedTaskId=t.id,e.lastError=null,q(`task.created`,`task`,t.id,{taskId:t.id,taskNumber:t.number,status:t.status,workflowId:t.workflowId??null,laneId:t.currentLaneId??null,sourceScheduleId:e.id,sourceScheduleOccurrenceId:r.id},e.projectId),W(`info`,`task.schedule.materialized`,`Materialized task ${t.id} from schedule ${e.id}`)}r.updatedAt=P(),e.lastFiredAt=t.createdAt,e.occurrences=[...e.occurrences,r],e.updatedAt=P(),e.oneShot&&(e.enabled=!1),a=!0,n.add(t.id)}}return o&&X(i),a&&Xi(n),{tasks:o?Y():i,schedules:a?Yi():n,changed:o||a}}function ha(e){return[...new Set(e)]}function ga(e){let t=e.workflowId?U().find(t=>t.id===e.workflowId)??null:null,n=new Map((t?.lanes??[]).map(e=>[e.id,e])),r=new Map,i=e.activeLaneAssignment;i?.completionSummary&&[`awaiting_user_approval`,`awaiting_user_intervention`].includes(i.status)&&r.set(i.laneId,{laneId:i.laneId,laneName:n.get(i.laneId)?.name??null,summary:i.completionSummary,outcome:i.pendingOutcome??null,pending:!0,sessionId:i.sessionId??null,updatedAt:i.updatedAt});for(let t of[...e.laneRuns].reverse())!t.summary||r.has(t.laneId)||r.set(t.laneId,{laneId:t.laneId,laneName:n.get(t.laneId)?.name??null,summary:t.summary,outcome:t.result,pending:!1,sessionId:t.sessionId,updatedAt:t.completedAt??t.startedAt});return[...r.values()].sort((e,t)=>{let r=n.get(e.laneId)?.order??2**53-1,i=n.get(t.laneId)?.order??2**53-1;return r===i?e.laneId.localeCompare(t.laneId):r-i})}function J(e){let t={...e,tags:Zi(e.tags),autoBlockedByDependencies:e.autoBlockedByDependencies??!1};return{...t,laneSummaries:ga(t)}}function _a(e,t){let n=[],r=t??null;for(;r;)n.push(r),r=e.find(e=>e.id===r)?.parentTaskId??null;return n}function va(e,t){return e.filter(e=>e.blockerTaskId===t).map(e=>e.blockedTaskId)}function ya(e,t,n,r,i){return ha([n,...va(t,n),..._a(e,r),..._a(e,i)])}function ba(e,t){let n=e.find(e=>e.id===t),r=n?.workflowId?U().find(e=>e.id===n.workflowId):null,i=n?.currentLaneId?r?.lanes.find(e=>e.id===n.currentLaneId):null;return{blockerWorkflowId:n?.workflowId??null,blockerLaneId:n?.currentLaneId??null,blockerLaneOrder:i?.order??null}}function xa(e,t){return t!=null&&![`completed`,`canceled`].includes(t.status)}function Sa(e,t,n){return n.some(n=>n.blockedTaskId===e?xa(n,t.find(e=>e.id===n.blockerTaskId)):!1)}function Ca(e,t){return t.some(t=>t.parentTaskId===e&&!t.archived&&![`completed`,`canceled`].includes(t.status))}function wa(e,t,n,r=P()){let i=e.map(e=>J(e)),a=new Set;for(let e of ha(n)){let n=i.findIndex(t=>t.id===e);if(n<0)continue;let o=i[n],s=Sa(e,i,t)||Ca(e,i);if([`completed`,`canceled`].includes(o.status)){o.autoBlockedByDependencies&&(i[n]={...o,autoBlockedByDependencies:!1,updatedAt:r},a.add(e));continue}if(s){[`ready`,`in_progress`,`in_review`].includes(o.status)?(i[n]={...o,status:`blocked`,autoBlockedByDependencies:!0,updatedAt:r},a.add(e)):![`blocked`].includes(o.status)&&o.autoBlockedByDependencies&&(i[n]={...o,autoBlockedByDependencies:!1,updatedAt:r},a.add(e));continue}if(o.status===`blocked`&&o.autoBlockedByDependencies){i[n]={...o,status:`ready`,autoBlockedByDependencies:!1,updatedAt:r},a.add(e);continue}o.autoBlockedByDependencies&&(i[n]={...o,autoBlockedByDependencies:!1,updatedAt:r},a.add(e))}return{tasks:i,changedTaskIds:[...a]}}function Ta(e,t,n=P()){let r=e.map(e=>J(e)),i=gi(),a=V(),o=yi(),s=xi(),c=[],l=new Set;for(let e of ha(t)){let t=r.findIndex(t=>t.id===e);if(t<0)continue;let u=r[t];if(u.status!==`blocked`||u.dependencyBlocked||!u.activeLaneAssignment)continue;let d=!1,f=u.activeLaneAssignment;f.status!==`paused_by_user`&&(f.sessionId&&l.add(f.sessionId),d=!0),r[t]={...u,currentLaneId:f.laneId??u.currentLaneId,assigneeType:f.workerType,assigneeId:f.workerId,status:`blocked`,activeLaneAssignment:{...f,status:`paused_by_user`,pendingOutcome:`paused`,completionSummary:null,completionNotes:f.completionNotes??`Task is blocked and the current lane is preserved in a paused state.`,updatedAt:n},updatedAt:n},i=i.map(t=>t.sourceTaskId===e&&[`queued`,`dispatched`,`paused_by_user`].includes(String(t.status??``))?{...t,status:`paused_by_user`,completedAt:null,updatedAt:n}:t),o=o.map(t=>t.sourceTaskId===e&&[`queued`,`assigned`,`paused_by_user`].includes(String(t.status??``))?{...t,status:`paused_by_user`,completedAt:null,updatedAt:n}:t),f.workerType===`agent`&&f.workerId&&(a=a.map(e=>e.agentId===f.workerId&&e.projectId===u.projectId?{...e,status:`waiting`,updatedAt:n}:e)),f.workerType===`role`&&f.roleInstanceId&&(s=s.map(e=>e.id===f.roleInstanceId?{...e,status:`waiting`,updatedAt:n}:e)),d&&c.push(e)}return c.length>0&&(_i(i),H(a),bi(o),Si(s)),{tasks:r,pausedTaskIds:c,pausedSessionIds:[...l]}}function Ea(e,t,n=P()){let r=e.map(e=>J(e)),i=gi(),a=V(),o=yi(),s=xi(),c=[],l=new Set;for(let e of ha(t)){let t=r.findIndex(t=>t.id===e);if(t<0)continue;let u=r[t];if(u.status!==`blocked`||!u.dependencyBlocked)continue;let d=!1,f=new Set,p=new Set;i=i.map(t=>t.sourceTaskId!==e||![`queued`,`dispatched`,`paused_by_user`].includes(String(t.status??``))?t:(typeof t.agentId==`string`&&t.agentId&&f.add(t.agentId),d=!0,{...t,status:`canceled`,completedAt:n,updatedAt:n})),o=o.map(t=>t.sourceTaskId!==e||![`queued`,`assigned`,`paused_by_user`].includes(String(t.status??``))?t:(typeof t.assignedInstanceId==`string`&&t.assignedInstanceId&&p.add(t.assignedInstanceId),d=!0,{...t,status:`canceled`,assignedInstanceId:null,completedAt:n,updatedAt:n})),u.activeLaneAssignment&&(d=!0,u.activeLaneAssignment.sessionId&&l.add(u.activeLaneAssignment.sessionId),u.activeLaneAssignment.workerType===`agent`&&u.activeLaneAssignment.workerId&&f.add(u.activeLaneAssignment.workerId),u.activeLaneAssignment.workerType===`role`&&u.activeLaneAssignment.roleInstanceId&&p.add(u.activeLaneAssignment.roleInstanceId),r[t]={...u,activeLaneAssignment:null,updatedAt:n}),f.size>0&&(a=a.map(e=>typeof e.agentId==`string`&&f.has(e.agentId)&&e.projectId===u.projectId?{...e,status:`idle`,currentQueueEntryId:null,lastError:null,updatedAt:n}:e),d=!0),p.size>0&&(s=s.map(e=>typeof e.id==`string`&&p.has(e.id)?{...e,status:`canceled`,currentQueueEntryId:null,sessionId:null,updatedAt:n}:e),d=!0),d&&c.push(e)}if(c.length>0){_i(i),H(a),bi(o),Si(s);for(let e of l)G(e,e=>Fi(e)),j({sessionIds:[e],reason:`task.blocked.runtime_cleared`})}return{tasks:r,cleanedTaskIds:c}}function Y(){let e=L(Gn),t=K();if(e)return Oa(e,t);if(!wr(s))return R(Gn,[]),[];let n=Gi().map(e=>J(e));return R(Gn,n),n}function X(e){R(Gn,Oa(e.map(e=>J(e)),K()))}function Da(e){return e.some(e=>!e.archived&&![`completed`,`canceled`].includes(e.status))}function Z(e){let t=e.blockedBy.some(e=>xa(e,e.blocker))||Da(e.children);return{id:e.id,projectId:e.projectId,number:e.number,title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,workflowId:e.workflowId,currentLaneId:e.currentLaneId,assigneeType:e.assigneeType,assigneeId:e.assigneeId,parentTaskId:e.parentTaskId,archived:e.archived,commentCount:e.comments.length,unreadCommentCount:ei(e),laneRunCount:e.laneRuns.length,childCount:e.children.length,completedChildCount:e.children.filter(e=>e.status===`completed`).length,inProgressChildCount:e.children.filter(e=>e.status===`in_progress`).length,blockedChildCount:e.children.filter(e=>!e.archived&&![`completed`,`canceled`].includes(e.status)).length,blockedByCount:e.blockedBy.length,blockingCount:e.blocking.length,attachmentCount:e.attachments.length,dependencyBlocked:t,activeLaneAssignmentStatus:e.activeLaneAssignment?.status??e.activeLaneAssignmentStatus??null,readyForDispatch:!e.archived&&!!(e.workflowId&&e.currentLaneId)&&[`ready`,`in_progress`].includes(e.status)&&!t&&!e.activeLaneAssignment,tags:dn(e),createdAt:e.createdAt,updatedAt:e.updatedAt}}function Oa(e,t){let n=e.map(e=>({...e,comments:$r(e),parent:null,lineage:[],children:[],blockedBy:[],blocking:[],childCount:0,completedChildCount:0,inProgressChildCount:0,blockedChildCount:0,blockedByCount:0,blockingCount:0,attachmentCount:0,dependencyBlocked:!1,activeLaneAssignmentStatus:e.activeLaneAssignment?.status??e.activeLaneAssignmentStatus??null,readyForDispatch:!1,attachments:e.attachments??[],todos:e.todos??[],activeLaneAssignment:e.activeLaneAssignment??null})),r=new Map(n.map(e=>[e.id,e]));return n.map(e=>{let i=[],a=e.parentTaskId??null;for(;a;){let e=r.get(a);if(!e)break;i.push(Z(e)),a=e.parentTaskId??null}i.reverse();let o=n.filter(t=>t.parentTaskId===e.id).sort((e,t)=>e.number.localeCompare(t.number)).map(e=>Z(e)),s=t.filter(t=>t.blockedTaskId===e.id).map(t=>({...t,blocker:Z(r.get(t.blockerTaskId)??e),blocked:Z(r.get(t.blockedTaskId)??e)})),c=t.filter(t=>t.blockerTaskId===e.id).map(t=>({...t,blocker:Z(r.get(t.blockerTaskId)??e),blocked:Z(r.get(t.blockedTaskId)??e)})),l=s.some(e=>xa(e,e.blocker))||Da(o);return{...e,parent:e.parentTaskId&&r.get(e.parentTaskId)?Z(r.get(e.parentTaskId)):null,lineage:i,children:o,blockedBy:s,blocking:c,commentCount:e.comments.length,unreadCommentCount:ei(e),laneRunCount:e.laneRuns.length,childCount:o.length,completedChildCount:o.filter(e=>e.status===`completed`).length,inProgressChildCount:o.filter(e=>e.status===`in_progress`).length,blockedChildCount:o.filter(e=>!e.archived&&![`completed`,`canceled`].includes(e.status)).length,blockedByCount:s.length,blockingCount:c.length,attachmentCount:e.attachments.length,dependencyBlocked:l,activeLaneAssignmentStatus:e.activeLaneAssignment?.status??e.activeLaneAssignmentStatus??null,readyForDispatch:!e.archived&&!!(e.workflowId&&e.currentLaneId)&&[`ready`,`in_progress`].includes(e.status)&&!l&&!e.activeLaneAssignment}}).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))}function ka(e){let t=window.localStorage.getItem(`orchestra.mock.projects`);return t&&JSON.parse(t).find(t=>t.id===e)?.taskPrefix?.trim().toUpperCase()||`ORC`}function Aa(e){let t=fe(e);return Number.isFinite(t.sequence)?t.sequence:0}function ja(e,t,n){let r=P(),i=Y(),a=e.workflowId?U().find(t=>t.id===e.workflowId):null,o=e.currentLaneId?.trim()||a?.lanes.slice().sort((e,t)=>e.order-t.order)[0]?.id||null,s=a?.lanes.find(e=>e.id===o)??null,c=t?.projectId??Tr(n??D()),l=i.filter(e=>e.projectId===c),u=t?Aa(t.number)||l.length+1:l.reduce((e,t)=>Math.max(e,Aa(t.number)),0)+1;return{id:t?.id??N(`task`),projectId:c,number:t?.number??de(ka(c),u),title:e.title.trim(),description:e.description?.trim()||null,type:e.type,tags:Zi(e.tags),status:e.status,priority:e.priority,workflowId:e.workflowId?.trim()||null,currentLaneId:o,assigneeType:s?.assignedEntityType??e.assigneeType,assigneeId:s?.assignedEntityId??(e.assigneeId?.trim()||null),repositoryId:e.repositoryIds?.[0]?.trim()||e.repositoryId?.trim()||null,repositoryIds:(e.repositoryIds??[]).map(e=>e.trim()).filter(Boolean),parentTaskId:e.parentTaskId?.trim()||null,whipMaxAttempts:Math.max(1,e.whipMaxAttempts??t?.whipMaxAttempts??10),archived:e.archived??t?.archived??!1,commentCount:t?.comments.length??0,unreadCommentCount:t?.unreadCommentCount??0,laneRunCount:t?.laneRuns.length??0,childCount:0,completedChildCount:0,inProgressChildCount:0,blockedChildCount:0,blockedByCount:0,blockingCount:0,attachmentCount:t?.attachments.length??0,dependencyBlocked:!1,readyForDispatch:!1,parent:null,lineage:[],children:[],blockedBy:[],blocking:[],attachments:t?.attachments??[],taskRepositories:t?.taskRepositories??[],fileReferences:t?.fileReferences??[],activeLaneAssignment:t?.activeLaneAssignment??null,autoBlockedByDependencies:t?.autoBlockedByDependencies??!1,createdAt:t?.createdAt??r,updatedAt:r,comments:t?.comments??[],todos:t?.todos??[],laneRuns:t?.laneRuns??[],laneSummaries:t?.laneSummaries??[]}}function Ma(e,t){let n=[],r=t?Y().find(e=>e.id===t)??null:null;if(e.title.trim()||n.push({path:`title`,message:`Task title is required.`}),n.push(...Qi(e.tags).errors),[`task`,`bug`,`feature`,`chore`,`epic`].includes(e.type)||n.push({path:`type`,message:`Task type must be one of: task, bug, feature, chore, epic.`}),[`draft`,`ready`,`in_progress`,`blocked`,`in_review`,`completed`,`canceled`].includes(e.status)||n.push({path:`status`,message:`Task status must be one of: draft, ready, in_progress, blocked, in_review, completed, canceled.`}),[`P0`,`P1`,`P2`,`P3`,`P4`].includes(e.priority)||n.push({path:`priority`,message:`Task priority must be one of: P0, P1, P2, P3, P4.`}),[`user`,`agent`,`role`,`unassigned`].includes(e.assigneeType)||n.push({path:`assigneeType`,message:`Assignee type must be one of: user, agent, role, unassigned.`}),(e.whipMaxAttempts??10)<1&&n.push({path:`whipMaxAttempts`,message:`Task whip max attempts must be at least 1.`}),[`user`,`unassigned`].includes(e.assigneeType)&&e.assigneeId?.trim()&&n.push({path:`assigneeId`,message:`User and unassigned tasks must not specify an assignee id.`}),[`agent`,`role`].includes(e.assigneeType)&&!e.assigneeId?.trim()&&n.push({path:`assigneeId`,message:`Agent and role tasks require an assignee id.`}),e.workflowId?.trim()||(t?r?.workflowId&&n.push({path:`workflowId`,message:`Workflow cannot be cleared from an existing task.`}):n.push({path:`workflowId`,message:`Workflow selection is required when creating a task.`})),e.currentLaneId?.trim()&&!e.workflowId?.trim()&&n.push({path:`currentLaneId`,message:`A current lane requires a workflow selection.`}),e.parentTaskId?.trim()){let r=e.parentTaskId.trim(),i=Y();if(t&&r===t)n.push({path:`parentTaskId`,message:`A task cannot be its own parent.`});else if(!i.some(e=>e.id===r))n.push({path:`parentTaskId`,message:`Parent task was not found.`});else if(t){let e=r;for(;e;){if(e===t){n.push({path:`parentTaskId`,message:`Parent would create a hierarchy cycle.`});break}e=i.find(t=>t.id===e)?.parentTaskId??null}}}return n}function Na(e){let t=[];e.name.trim()||t.push({code:`required`,path:`name`,message:`Workflow name is required.`}),e.lanes.length||t.push({code:`required`,path:`lanes`,message:`A workflow must contain at least one lane.`});let n=new Set,r=new Set,i=new Set,a=e.lanes.map((e,t)=>e.id?.trim()||`lane-${t}`);e.lanes.forEach((e,o)=>{let s=a[o],c=Nr(e.key),l=e.order??o,u=`lanes[${o}]`;if(e.name.trim()||t.push({code:`required`,path:`${u}.name`,message:`Lane name is required.`}),e.key.trim()||t.push({code:`required`,path:`${u}.key`,message:`Lane key is required.`}),n.has(s)&&t.push({code:`duplicate`,path:`${u}.id`,message:`Lane ids must be unique within a workflow.`}),n.add(s),r.has(c)&&t.push({code:`duplicate`,path:`${u}.key`,message:`Lane keys must be unique within a workflow.`}),r.add(c),i.has(l)&&t.push({code:`duplicate`,path:`${u}.order`,message:`Lane order values must be unique within a workflow.`}),i.add(l),[`user`,`agent`,`role`].includes(e.assignedEntityType)||t.push({code:`invalid`,path:`${u}.assignedEntityType`,message:`Lane owner type must be one of: user, agent, role.`}),e.assignedEntityType===`user`&&e.assignedEntityId?.trim()&&t.push({code:`invalid`,path:`${u}.assignedEntityId`,message:`User-owned lanes must not specify an assigned entity id.`}),e.assignedEntityType===`user`&&e.requireUserApprovalOnSuccess&&t.push({code:`invalid`,path:`${u}.requireUserApprovalOnSuccess`,message:`User-owned lanes cannot require user approval on success.`}),!e.requireUserApprovalOnSuccess&&e.needsWorkTargetLaneId?.trim()&&t.push({code:`invalid`,path:`${u}.needsWorkTargetLaneId`,message:`Needs Work target lane is only available when success review is required.`}),e.assignedEntityType===`agent`){let n=e.assignedEntityId?.trim(),r=hi();n?r.length>0&&!r.some(e=>!e.archived&&e.slug===n)&&t.push({code:`invalid_reference`,path:`${u}.assignedEntityId`,message:`Assigned entity id does not reference an existing active worker.`}):t.push({code:`required`,path:`${u}.assignedEntityId`,message:`This lane owner type requires an assigned entity id.`})}if(e.assignedEntityType===`role`){let n=e.assignedEntityId?.trim(),r=vi();n?r.length>0&&!r.some(e=>!e.archived&&e.slug===n)&&t.push({code:`invalid_reference`,path:`${u}.assignedEntityId`,message:`Assigned entity id does not reference an existing active worker.`}):t.push({code:`required`,path:`${u}.assignedEntityId`,message:`This lane owner type requires an assigned entity id.`})}});let o=new Set(a);return e.lanes.forEach((e,n)=>{let r=[[e.successTransitionType,e.successTargetLaneId,`successTransitionType`,`successTargetLaneId`],[e.failureTransitionType,e.failureTargetLaneId,`failureTransitionType`,`failureTargetLaneId`]],i=e.needsWorkTargetLaneId?.trim()||null;i&&(e.requireUserApprovalOnSuccess?i===a[n]?t.push({code:`invalid`,path:`lanes[${n}].needsWorkTargetLaneId`,message:`Needs Work target lane must be different from the current lane. Leave it empty to resume the current lane/session.`}):o.has(i)||t.push({code:`invalid_reference`,path:`lanes[${n}].needsWorkTargetLaneId`,message:`Needs Work target lane must reference an existing lane id.`}):t.push({code:`invalid`,path:`lanes[${n}].needsWorkTargetLaneId`,message:`Needs Work target lane is only available when success review is required.`})),r.forEach(([e,r,i,a])=>{if(![`lane`,`user_intervention`,`end`].includes(e)){t.push({code:`invalid`,path:`lanes[${n}].${i}`,message:`Transition type must be one of: lane, user_intervention, end.`});return}e===`lane`?r?.trim()?o.has(r.trim())||t.push({code:`invalid_reference`,path:`lanes[${n}].${a}`,message:`Transition target must reference an existing lane id.`}):t.push({code:`required`,path:`lanes[${n}].${a}`,message:`Lane transitions must reference a target lane.`}):r?.trim()&&t.push({code:`invalid`,path:`lanes[${n}].${a}`,message:`Only lane transitions may specify a target lane.`})})}),{valid:t.length===0,errors:t}}function Pa(e,t){let n=P(),r=e.lanes.map((e,t)=>({id:e.id?.trim()||N(`lane`),key:Nr(e.key),name:e.name.trim(),description:e.description?.trim()||null,order:e.order??t,assignedEntityType:e.assignedEntityType,assignedEntityId:e.assignedEntityId?.trim()||null,entryPromptTemplate:e.entryPromptTemplate?.trim()||null,useSeparateWorktree:(e.useSeparateWorktree??!1)&&e.assignedEntityType!==`user`,requireUserApprovalOnSuccess:e.requireUserApprovalOnSuccess??!1,needsWorkTargetLaneId:e.requireUserApprovalOnSuccess&&e.needsWorkTargetLaneId?.trim()||null,successTransitionType:e.successTransitionType,successTargetLaneId:e.successTransitionType===`lane`&&e.successTargetLaneId?.trim()||null,failureTransitionType:e.failureTransitionType,failureTargetLaneId:e.failureTransitionType===`lane`&&e.failureTargetLaneId?.trim()||null}));return{id:t?.id??N(`workflow`),slug:t?.slug??Nr(e.name),name:e.name.trim(),description:e.description?.trim()||null,archived:t?.archived??!1,lanes:r,createdAt:t?.createdAt??n,updatedAt:n}}function Fa(e,t){return e instanceof Error&&e.message.trim()?e.message:typeof e==`string`&&e.trim()?e:t}async function Ia(n,r,i){let a=b()?.client;if(a)return a.app.reportError(n,r,i);let o=Fa(r,i);if(console.error(`[${n}] ${o}`,r),!t())return W(`error`,n,o),o;try{await e(`report_client_error`,{target:n,message:o})}catch(e){console.error(`[report_client_error.failed] ${n}`,e)}return o}async function La(){if(!t()){let e=I(),t=Jr();return{appName:`Orchestra`,environment:`browser`,backendStatus:`mock`,versionDisplay:`0.1.0-mock0000`,currentVersion:t.currentVersion,releaseChannel:t.currentChannel,updateStatus:t,dispatchBlocked:e.status!==`ready`,dispatchBlockedReason:e.status===`ready`?null:`No Pi models are configured yet. Open Settings → Harness to connect a provider or import an existing Pi setup.`,piRuntimeDiagnostics:{runtime:{available:!0,source:`external`,packagedMode:!1,resolvedPath:`pi (mock)`,error:null,message:`PI runtime resolved in browser-mode mock.`},auth:{configured:e.status===`ready`,agentDir:`~/.orchestra/runtime/pi/agent`,authPath:`~/.orchestra/runtime/pi/agent/auth.json`,modelsPath:`~/.orchestra/runtime/pi/agent/models.json`,settingsPath:`~/.orchestra/runtime/pi/agent/settings.json`,authExists:e.availableProviders.some(e=>e.connected),modelsExists:e.status===`ready`,legacyAgentDir:e.legacyAgentDir??`~/.pi/agent`,legacyAuthAvailable:e.status===`legacy_import_available`||e.importState.canImportLegacy,legacyModelsAvailable:e.status===`legacy_import_available`||e.importState.canImportLegacy,authImportedAt:e.importState.importedAt,modelsImportedAt:e.importState.importedAt,message:e.status===`ready`?`Browser-mode mock simulates configured Orchestra-managed PI auth.`:`Browser-mode mock requires Pi setup before Pi-backed flows are available.`},addOns:{packagedMode:!1,allowed:!0,extraExtensions:[],blockedExtensions:[],message:`Browser-mode mock allows free-form PI extension entries.`}}}}return e(`get_app_info`)}async function Ra(){return t()?e(`get_logs`):ci()}async function za(){return t()?e(`list_log_viewer_sources`):pi()}async function Ba(n){if(!t()){let e=pi().find(e=>e.id===n.sourceId);if(!e)throw Error(`Unknown log viewer source ${n.sourceId}`);let t=n.minimumLevel??`info`,r={debug:10,info:20,warn:30,error:40},i=(n.textFilter??``).trim().toLowerCase(),a=ci().map(di),o=ui(),s=(n.sourceId===`runtime`?a:n.sourceId===`session-diagnostics`?o.map(e=>fi(`session-diagnostics`,e)):o.filter(e=>`session-diagnostic:${e.sessionId}`===n.sourceId).map(e=>fi(n.sourceId,e))).filter(e=>r[e.level]<r[t]?!1:i?[e.category,e.message,e.sessionId??``,e.runId??``,e.detailsPreview??``].join(` `).toLowerCase().includes(i):!0);s.sort((e,t)=>t.timestamp.localeCompare(e.timestamp));let c=Math.max(0,n.offset??0),l=Math.min(Math.max(1,n.limit??100),200);return{source:e,entries:s.slice(c,c+l),nextOffset:c+l<s.length?c+l:null,totalCount:s.length}}return e(`query_log_viewer_entries`,{sourceId:n.sourceId,minimumLevel:n.minimumLevel??null,textFilter:n.textFilter??null,offset:n.offset??null,limit:n.limit??null})}async function Va(n,r=!1){if(!t()){let e=pi().find(e=>e.id===n);if(!e?.path)throw Error(`No path is available for ${n}`);return r&&n.startsWith(`session-diagnostic:`)?`/mock/.orchestra/runtime/session-diagnostics`:e.path}return e(`open_log_viewer_source_path`,{sourceId:n,openDirectory:r})}async function Ha(){return t()?e(`get_bridge_diagnostics`):mi()}async function Ua(){if(!t()){let e=mi();return R(ir,{...e,recentCleanupEvents:[{id:`bridge-cleanup-${Date.now()}`,instanceId:e.instance.instanceId,pid:e.instance.ownerPid,action:`cleanup_requested`,reason:`mock_cleanup`,success:!0,timestamp:P()},...e.recentCleanupEvents].slice(0,20)}),mi().recentCleanupEvents}return e(`cleanup_stale_bridge_instances`)}async function Wa(){if(!t()){R(Bn,[]);return}await e(`clear_logs`)}async function Ga(n=!1){if(!t())throw Error(`Log bundle export is only available in the desktop app.`);return e(`export_logs_bundle`,{includeRelatedSessionSnapshot:n})}async function Ka(){let n=new URL(window.location.href);if(n.searchParams.set(`view`,`logs`),!t()){window.open(n.toString(),`orchestra-logs`,`popup=yes,width=980,height=760,resizable=yes,scrollbars=yes`);return}await e(`open_logs_window`)}async function qa(){if(!t())return Er();let{getCurrentWebviewWindow:e}=await zn(async()=>{let{getCurrentWebviewWindow:e}=await import(`./webviewWindow-CHLyLPiW.js`);return{getCurrentWebviewWindow:e}},__vite__mapDeps([0,1]));return e().label===`logs`}async function Ja(){if(!t())return Dr();let{getCurrentWebviewWindow:e}=await zn(async()=>{let{getCurrentWebviewWindow:e}=await import(`./webviewWindow-CHLyLPiW.js`);return{getCurrentWebviewWindow:e}},__vite__mapDeps([0,1]));return e().label.startsWith(`agent-terminal-`)}async function Ya(){if(!t())return Or();let{getCurrentWebviewWindow:e}=await zn(async()=>{let{getCurrentWebviewWindow:e}=await import(`./webviewWindow-CHLyLPiW.js`);return{getCurrentWebviewWindow:e}},__vite__mapDeps([0,1])),n=e().label;return n.startsWith(`agent-terminal-`)?n.slice(15):null}async function Xa(n){if(!t()){let e=ji(n),t=Bi(B(n).filter(t=>!e.has(t.id)));return W(`info`,`sessions.list`,`Listed ${t.length} sessions`),t}return e(`list_sessions`,{projectId:n??null})}async function Za(n){if(!t()){yr(`get`,n);let e=B().find(e=>e.id===n)??null;if(!e)throw Error(`Unable to find session ${n}`);let t=ji();return W(`info`,`sessions.record`,`Loaded session record ${n}`),{...e,listVisibility:t.has(n)?`hidden`:e.listVisibility??(e.status===`closed`?`closed`:`active`),messageability:e.messageability??(e.status===`closed`?`closed`:`messageable`)}}return e(`get_session_record`,{sessionId:n})}async function Qa(n){if(!t()){let e=B().find(e=>e.id===n)??null;if(!e)throw Error(`Unable to find session ${n}`);let t=br(),r=[...new Set((t.extraExtensions??[]).map(e=>e.trim()).filter(Boolean))],i=`extensions/orchestra-tools.ts`,a={enabled:t.enableBundledSubagents??!0,version:`0.24.0`,packageRoot:`/mock/orchestra/extensions/bundled/pi-subagents`,extensionPath:`/mock/orchestra/extensions/bundled/pi-subagents/src/extension/index.ts`,skillsPath:`/mock/orchestra/extensions/bundled/pi-subagents/skills`,promptsPath:`/mock/orchestra/extensions/bundled/pi-subagents/prompts`,agentRoot:`/mock/.orchestra/runtime/pi/agent`},o={enabled:t.enableBundledProcesses??!0,version:`0.9.0`,packageRoot:`/mock/orchestra/extensions/bundled/pi-processes`,extensionPath:`/mock/orchestra/extensions/bundled/pi-processes/dist/orchestra-extension.mjs`,skillsPath:`/mock/orchestra/extensions/bundled/pi-processes/skills`,agentRoot:`/mock/.orchestra/runtime/pi/agent`};return{sessionId:n,source:e.subscribed?`live_runtime`:`expected_config`,runtimeActive:e.subscribed,subscribed:e.subscribed,extensionLoadMode:`explicit_only`,automaticExtensionsDisabled:!0,orchestraExtensionPath:i,bundledSubagents:a,bundledProcesses:o,extraExtensions:r,blockedExtraExtensions:[],loadedExtensions:[i,...a.enabled?[a.extensionPath]:[],...o.enabled?[o.extensionPath]:[],...r],piRuntimeSource:`bundled`,piRuntimeMode:`packaged`,piRuntimeStatus:`healthy`,piExecutablePath:`/mock/orchestra/pi-runtime/runtime/pi`,piPackageDir:`/mock/orchestra/pi-runtime/runtime`,piAgentDir:`/mock/.orchestra/runtime/pi/agent`,piRuntimeVersion:`0.68.1`,piRuntimeBuiltAt:`2026-04-22T00:00:00Z`,piRuntimeManifestPath:`/mock/orchestra/pi-runtime/manifest.json`,piRuntimeErrorKind:null,piRuntimeErrorMessage:null,shellPath:`/mock/bin`,projectRoot:e.debugInfo?.projectRoot??`/mock/orchestra/project`,sessionDir:`/mock/orchestra/sessions`,sessionPath:`/mock/orchestra/sessions/${n}.jsonl`,notes:e.subscribed?[`Browser-mode mock simulates an active runtime for subscribed sessions.`]:[`No live runtime is active in browser mode; these are the extensions Orchestra would load the next time this session spawns a runtime.`],managedSkills:{state:`resolved`,context:{sessionId:n,projectId:s,roleId:null,agentId:null,workflowId:null,workflowLaneId:null,contextSource:`project_session`},contextHash:`mock-skill-context-${n}`,ambientSkills:[],resolvedSkills:[],suppressedSkills:[],scopedSnapshot:null,globalPublicationManifestPath:`/mock/.orchestra/runtime/pi/agent/skills/manifest.json`,notes:[`Browser-mode mock exposes an empty managed-skills diagnostics payload for compatibility with the desktop runtime details UI.`],warnings:[],errorMessage:null},controlCapabilities:e.controlCapabilities??null,controlOperation:e.controlOperation??null}}return e(`get_session_runtime_details`,{sessionId:n})}async function $a(n){if(!t()){yr(`getStats`,n);let e=B().find(e=>e.id===n)??null;if(!e)throw Error(`Unable to find session ${n}`);let t=e.events.map(e=>e.message).join(`
`),r=Math.max(0,Math.round(t.length/4)),i=e.events.filter(e=>e.kind===`user`).length,a=e.events.filter(e=>e.kind===`assistant`).length,o=i+a,s=2e5,c=o===0?null:Math.max(r,1200);return{sessionId:n,sessionFile:`/mock/orchestra/sessions/${n}.jsonl`,userMessages:i,assistantMessages:a,toolCalls:e.events.filter(e=>e.presentation===`tool_call`).length,toolResults:0,totalMessages:o,tokens:{input:Math.round(r*.6),output:Math.round(r*.25),cacheRead:Math.round(r*.1),cacheWrite:Math.round(r*.05),total:r},cost:0,contextUsage:{tokens:c,contextWindow:s,percent:c==null?null:c/s*100},contextResolution:c==null?{status:`unavailable`,reason:`not_started`}:{status:`reported`,reason:null}}}return e(`get_session_stats`,{sessionId:n})}function eo(e,t){let n=Ti();if(n[e]){n[t]=n[e],Ei(n);return}Ai(t)}function to(e){return{...St(e,`Fresh session is active. Continue here while the prior session remains in history.`),subscribed:!0}}function no(e,t,n){let r=ji(n);r.add(e),Mi(r,n),G(e,e=>({...e,status:`closed`,subscribed:!1,listVisibility:`hidden`,messageability:`closed`,updatedAt:t,events:[...e.events,F(`system`,`Session replaced by a newer worker session.`)]}))}function ro(e,t){let n=B(),r=n.find(t=>t.id===e);if(!r)throw Error(`Unable to find session ${e}`);let i=P(),a=Cr(t??D())??null,o=Y(),c=o.find(t=>{let n=t.activeLaneAssignment;return n?.sessionId===e&&[`queued`,`active`,`awaiting_user_approval`,`awaiting_user_intervention`,`paused_by_user`].includes(n.status)})??null;if(c?.activeLaneAssignment){let t=c.activeLaneAssignment,n=to(r.title);eo(e,n.id),xt(n);let a={...t,id:N(`task-assignment`),sessionId:n.id,startedAt:i,completedAt:null,createdAt:i,updatedAt:i};return X(o.map(t=>t.id===c.id?{...t,activeLaneAssignment:a,laneRuns:[...t.laneRuns.map(t=>t.sessionId===e&&t.completedAt==null?{...t,result:`canceled`,notes:`Session rotated by operator.`,completedAt:i}:t),{id:N(`lane-run`),taskId:t.id,laneId:a.laneId,sessionId:n.id,result:`needs_user`,notes:null,startedAt:i,completedAt:null}],updatedAt:i}:t)),t.workerType===`agent`&&t.workerId&&H(V().map(e=>e.agentId===t.workerId&&e.projectId===c.projectId?{...e,mainSessionId:n.id,runtimeCwd:t.runtimeCwd,updatedAt:i}:e)),t.workerType===`role`&&t.roleInstanceId&&Si(xi().map(e=>e.id===t.roleInstanceId?{...e,sessionId:n.id,updatedAt:i}:e)),no(e,i,c.projectId),W(`info`,`sessions.create_contextual`,`Rotated worker session ${e} to ${n.id}`),j({sessionIds:[e,n.id],reason:`sessions.create_contextual`}),M({taskIds:[c.id],reason:`task.assignment.session_rotated`}),n}let l=V().find(t=>t.mainSessionId===e)??null;if(l){let t=to(r.title);return eo(e,t.id),xt(t),H(V().map(n=>n.mainSessionId===e?{...n,mainSessionId:t.id,updatedAt:i}:n)),no(e,i,typeof l.projectId==`string`?l.projectId:a),W(`info`,`sessions.create_contextual`,`Rotated agent main session ${e} to ${t.id}`),j({sessionIds:[e,t.id],reason:`sessions.create_contextual`}),t}let u=xi().find(t=>t.sessionId===e&&typeof t.status==`string`&&[`running`,`waiting`,`idle`].includes(t.status))??null;if(u){let t=to(r.title);return eo(e,t.id),xt(t),Si(xi().map(e=>e.id===u.id?{...e,sessionId:t.id,updatedAt:i}:e)),no(e,i,a),W(`info`,`sessions.create_contextual`,`Rotated role session ${e} to ${t.id}`),j({sessionIds:[e,t.id],reason:`sessions.create_contextual`}),t}let d={id:N(`session`),title:`New session ${new Date().toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}`,status:`active`,createdAt:i,updatedAt:i,subscribed:!0,events:[F(`system`,`Session created from the Orchestra Sessions page.`),F(`assistant`,`Session is active. Send a message to begin the interaction loop.`)]};return Ai(d.id),Ni(Bi([d,...n])),W(`info`,`sessions.create_contextual`,`Created generic successor session ${d.id} in ${t??s}`),j({sessionIds:[d.id],reason:`sessions.create_contextual`}),d}async function io(n,r,i){if(!t()){let e=P(),t={id:N(`session`),title:n?.trim()||`New session ${new Date().toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}`,status:`active`,createdAt:e,updatedAt:e,subscribed:!0,events:[F(`system`,`Session created from the Orchestra Sessions page.`),F(`assistant`,`Session is active. Send a message to begin the interaction loop.`)]};if(Ai(t.id),Ni(Bi([t,...B()])),i){let n=s,r=V();H(r.some(e=>e.agentId===i&&e.projectId===n)?r.map(r=>r.agentId===i&&r.projectId===n?{...r,mainSessionId:t.id,updatedAt:e}:r):[...r,{projectId:n,agentId:i,status:`idle`,mainSessionId:t.id,runtimeCwd:Be(n),currentQueueEntryId:null,lastDispatchAt:null,lastError:null,terminalAttached:!1,createdAt:e,updatedAt:e}])}return W(`info`,`sessions.create`,`Created session ${t.id}`),j({sessionIds:[t.id],reason:`sessions.create`}),t}return e(`create_session`,{title:n,projectSlug:r,agentId:i})}async function ao(n,r,i){return t()?e(`create_contextual_session`,{sessionId:n,projectSlug:r,agentId:i}):ro(n,r)}async function oo(n){if(!t()){let e=ji();e.add(n),Mi(e),W(`info`,`sessions.dismiss`,`Dismissed session ${n}`);return}await e(`delete_session`,{sessionId:n})}async function so(n){if(!t()){yr(`resume`,n);let e=ji();e.delete(n),Mi(e);let t=G(n,e=>({...e,status:`active`,subscribed:!0,listVisibility:`active`,messageability:`messageable`,updatedAt:P(),events:[...e.events,F(`system`,`Session resumed from the Sessions page.`)]}));if(!t)throw Error(`Unable to find session ${n}`);return W(`info`,`sessions.resume`,`Resumed session ${t.id}`),t}return e(`resume_session`,{sessionId:n})}async function co(n){if(!t()){yr(`subscribe`,n);let e=G(n,e=>({...e,subscribed:!0}));if(!e)throw Error(`Unable to find session ${n}`);return W(`info`,`sessions.subscribe`,`Subscribed to session ${e.id}`),e}return e(`subscribe_session`,{sessionId:n})}async function lo(n){if(!t()){let e=G(n,e=>({...e,subscribed:!1}));if(!e)throw Error(`Unable to find session ${n}`);return W(`info`,`sessions.unsubscribe`,`Unsubscribed from session ${e.id}`),e}return e(`unsubscribe_session`,{sessionId:n})}async function uo(n,r){let i=b()?.client;if(i)return i.sessions.stopRuntime(n,r);if(!t()){let e=Di();delete e[n],Oi(e);let t=G(n,e=>({...e,status:`paused`,updatedAt:P(),events:[...e.events,F(`system`,r?.trim()?`Session run stopped by operator. ${r.trim()}`:`Session run stopped by operator.`)]}));if(!t)throw Error(`Unable to find session ${n}`);return W(`info`,`sessions.stop`,`Stopped session runtime ${n}`),j({sessionIds:[n],reason:`sessions.stop`}),t}return e(`stop_session_runtime`,{sessionId:n,notes:r})}async function fo(){let n=b()?.client;if(n)try{return await n.settings.getPiExecutableDiagnostic()}catch{return{source:`remote_api`,mode:`browser`,status:`unsupported`,resolvedPath:null,packageDir:null,agentDir:null,version:null,builtAt:null,manifestPath:null,errorKind:`desktop_only`,errorMessage:`Local Pi executable diagnostics are only available in the desktop app.`}}return t()?e(`get_pi_executable_diagnostic`):{source:`bundled`,mode:`packaged`,status:`healthy`,resolvedPath:`/mock/orchestra/pi-runtime/runtime/pi`,packageDir:`/mock/orchestra/pi-runtime/runtime`,agentDir:`/mock/.orchestra/runtime/pi/agent`,version:`0.68.1`,builtAt:`2026-04-22T00:00:00Z`,manifestPath:`/mock/orchestra/pi-runtime/manifest.json`,errorKind:null,errorMessage:null}}async function po(){return t()?e(`get_pi_runtime_diagnostics`):(await La()).piRuntimeDiagnostics}async function mo(n,r){return t()?e(`import_legacy_pi_configuration`,{importAuth:n,importModels:r}):{imported:[n?`auth.json`:null,r?`models.json`:null].filter(e=>!!e),skipped:[],diagnostics:await po()}}async function ho(){return t()?e(`get_pi_setup_state`):I()}async function go(){return t()?e(`get_pi_models_json`):Kr()}async function _o(n){return t()?e(`save_pi_models_json`,{content:n}):(qr(n),I())}async function vo(n,r){if(!t()){let e=I(),t={...e,status:`ready`,issues:[],warnings:[],availableProviders:e.availableProviders.map(e=>e.id===n?{...e,connected:!0,usingOAuth:!1}:e)};return Rr(t),t}return e(`set_pi_provider_api_key`,{providerId:n,apiKey:r})}async function yo(n){if(!t()){let e=I(),t={...e,availableProviders:e.availableProviders.map(e=>e.id===n?{...e,connected:!1,usingOAuth:!1}:e)};Rr(t);let r=zr();return r?.providerId===n&&r.finishedAt&&(Br(null),Hr(null)),t}return e(`remove_pi_provider_credential`,{providerId:n})}async function bo(n=!1){if(!t()){let e=I(),t={...e,status:`ready`,importState:{...e.importState,canImportLegacy:!1,importedAt:P()}};return Rr(t),t}return e(`import_pi_legacy_config`,{replaceExisting:n})}async function xo(){if(!t()){let e=I(),t={...e,importState:{...e.importState,dismissedAt:P()}};return Rr(t),t}return e(`dismiss_pi_legacy_import`)}async function So(){return t()?e(`get_pi_oauth_flow_state`):zr()??null}async function Co(n,r){if(!t()){let e=I().availableProviders.find(e=>e.id===n);if(!e)throw Error(`Unknown Pi provider ${n}`);let t=r?(e.oauthMethods??[]).find(e=>e.id===r)??null:Ur(n,e.oauthMethods);if(!t)throw Error(`Provider ${n} does not support OAuth method ${r}`);let i=t.kind===`device_code`?{providerId:n,providerName:e.name,methodId:t.id,methodKind:t.kind,usesCallbackServer:e.usesCallbackServer,status:n===`github-copilot`?`awaiting_input`:`running`,authStep:n===`github-copilot`?null:{kind:`device_code`,url:`https://example.com/device/${n}`,linkLabel:`Open verification page`,instructions:`Enter the device code on the verification page.`,userCode:`ABCD-EFGH`},browserOpened:n!==`github-copilot`,browserOpenError:null,prompt:n===`github-copilot`?{kind:`prompt`,message:`GitHub Enterprise URL/domain (blank for github.com)`,placeholder:`company.ghe.com`,allowEmpty:!0}:null,latestProgressMessage:`Starting ${e.name} sign-in…`,error:null,startedAt:P(),finishedAt:null}:{providerId:n,providerName:e.name,methodId:t.id,methodKind:t.kind,usesCallbackServer:e.usesCallbackServer,status:`running`,authStep:{kind:`browser`,url:`https://example.com/oauth/${n}`,linkLabel:`Open browser sign-in`,instructions:`If nothing opened automatically, use the link above.`,userCode:null},browserOpened:!0,browserOpenError:null,prompt:null,latestProgressMessage:`Starting ${e.name} sign-in…`,error:null,startedAt:P(),finishedAt:null};return Br(i),Hr(i),i.methodKind===`browser`&&window.setTimeout(()=>{let e=zr();e&&e.providerId===i.providerId&&e.startedAt===i.startedAt&&Gr(e)},200),i}return e(`start_pi_oauth_flow`,{providerId:n,methodId:r??null})}async function wo(n){if(!t()){let e=zr();if(!e)throw Error(`No active Pi OAuth flow.`);let t=e.methodKind===`device_code`?{...e,status:`running`,prompt:null,authStep:e.authStep??{kind:`device_code`,url:`https://example.com/device/${e.providerId}`,linkLabel:`Open verification page`,instructions:`Enter the device code on the verification page.`,userCode:`ABCD-EFGH`},browserOpened:!0,latestProgressMessage:`Waiting for device-code verification…`}:{...e,status:`running`,prompt:null,latestProgressMessage:`Waiting for browser sign-in to finish…`};return Br(t),Hr(t),t}return e(`submit_pi_oauth_flow_input`,{value:n})}async function To(){if(!t()){let e=zr();if(!e)return null;let t={...e,status:`cancelled`,prompt:null,error:`Login cancelled`,finishedAt:P()};return Br(t),Hr(t),t}return e(`cancel_pi_oauth_flow`)}async function Eo(){if(!t()){let e=zr();if(!e)return null;if(!e.finishedAt)throw Error(`Active Pi OAuth flows must be cancelled before they can be dismissed.`);return Br(null),Hr(null),null}return e(`dismiss_pi_oauth_flow`)}async function Do(){let n=b()?.client;return n?n.settings.listPiModels():t()?e(`list_pi_models`):Mr}async function Oo(n){return t()?e(`get_session_model_state`,{sessionId:n}):(yr(`getModelState`,n),Hi(n))}async function ko(n,r,i){if(!t()){let e=Mr.find(e=>e.provider===r&&e.id===i);if(!e)throw Error(`Unknown model ${r}/${i}`);let t=Ti();return t[n]=e,Ei(t),W(`info`,`sessions.model`,`Changed session ${n} to ${r}/${i}`),Hi(n)}return e(`set_session_model`,{sessionId:n,provider:r,modelId:i})}async function Ao(n,r){let i=P();if(!t()){let e=G(n,e=>({...e,updatedAt:i,controlOperation:{kind:`compact`,trigger:`manual`,status:`succeeded`,startedAt:i,finishedAt:i,message:r?.trim()?`Session compacted. ${r.trim()}`:`Session compacted.`},events:[...e.events,F(`system`,r?.trim()?`Session compacted. ${r.trim()}`:`Session compacted.`,{id:`compact-${n}-${i}`})]}));if(!e)throw Error(`Unable to find session ${n}`);return W(`info`,`sessions.compact`,`Compacted session ${n}`),j({sessionIds:[n],reason:`sessions.compact`}),e}return e(`compact_session`,{sessionId:n,customInstructions:r??null})}async function jo(n){let r=P();if(!t()){let e=G(n,e=>({...e,updatedAt:r,controlOperation:{kind:`reload`,trigger:`manual`,status:`succeeded`,startedAt:r,finishedAt:r,message:`Session reloaded.`},events:[...e.events,F(`system`,`Session reloaded.`,{id:`reload-${n}-${r}`})]}));if(!e)throw Error(`Unable to find session ${n}`);return W(`info`,`sessions.reload`,`Reloaded session ${n}`),j({sessionIds:[n],reason:`sessions.reload`}),e}return e(`reload_session`,{sessionId:n})}async function Mo(n){if(!t()){let e=`/mock/orchestra/sessions/${n}.jsonl`;return W(`info`,`sessions.open_file`,`Opened session file ${e}`),e}return e(`open_session_file`,{sessionId:n})}function No(e,t){return(Di()[e]??[]).length>0?t===`interrupt`?`steer`:`follow_up`:`prompt`}function Po(e){switch(e){case`follow_up`:return{target:`sessions.message.follow_up`,message:`Queued follow-up message`};case`steer`:return{target:`sessions.message.steer`,message:`Queued interrupt steer message`};default:return{target:`sessions.message.start`,message:`Sent prompt`}}}async function Fo(n,r,i,a=`default`){let o=r.trim();if(!o)throw Error(`Message cannot be empty`);if(!t()){let e=No(n,a),t={sessionId:n,runId:i,message:o,timestamp:P(),deliveryMode:e},r=mi();R(ir,{...r,instance:{...r.instance,activeClientCount:1,inFlightRequestCount:1,heartbeatAt:t.timestamp},clients:[{clientId:`browser-client-${n}`,sessionId:n,actorType:`session`,actorId:n,requestCount:(r.clients[0]?.requestCount??0)+1,inFlightRequestCount:1,lastSeenAt:t.timestamp,lastCommand:`send_session_message`,lastError:null,active:!0,bridgeInstanceId:r.instance.instanceId}],recentRequests:[{requestId:`browser-request-${i}`,clientId:`browser-client-${n}`,sessionId:n,command:`send_session_message`,startedAt:t.timestamp,finishedAt:null,durationMs:null,success:!0,error:null},...r.recentRequests].slice(0,20)});let s=Di();s[n]=Array.from(new Set([...s[n]??[],i])),Oi(s),G(n,e=>({...e,status:`streaming`,updatedAt:t.timestamp,events:[...e.events.filter(e=>e.runId!==i),{id:`pending-user-${i}`,kind:`user`,message:o,timestamp:t.timestamp,pending:!0,runId:i}]}));let c=B().find(e=>e.id===n)??null;j({sessionIds:[n],reason:`sessions.message.queued`});let l=Po(e);W(`info`,l.target,`${l.message} for session ${n}`);let u=Vi(o),d=u.split(/(\s+)/).filter(Boolean),f=`Considering: ${o}`,p=f.split(/(\s+)/).filter(Boolean),m={role:`user`,content:[{type:`text`,text:o}],timestamp:Date.now()},h={role:`assistant`,content:[],timestamp:Date.now()};return window.setTimeout(()=>{A(z(n,i,{type:`agent_start`})),A(z(n,i,{type:`turn_start`})),A(z(n,i,{type:`message_start`,message:m})),A(z(n,i,{type:`message_end`,message:m})),A(z(n,i,{type:`message_start`,message:h})),A(z(n,i,{type:`message_update`,message:{...h,content:[{type:`thinking`,thinking:``}]},assistantMessageEvent:{type:`thinking_start`,contentIndex:0,partial:{}}})),p.forEach((e,t)=>{window.setTimeout(()=>{A(z(n,i,{type:`message_update`,message:{...h,content:[{type:`thinking`,thinking:f.slice(0,f.indexOf(e)>=0?f.indexOf(e)+e.length:f.length)}]},assistantMessageEvent:{type:`thinking_delta`,contentIndex:0,delta:e,partial:{}}}))},40*(t+1))}),window.setTimeout(()=>{A(z(n,i,{type:`message_update`,message:{...h,content:[{type:`thinking`,thinking:f}]},assistantMessageEvent:{type:`thinking_end`,contentIndex:0,partial:{}}})),A(z(n,i,{type:`message_update`,message:{...h,content:[{type:`text`,text:``},{type:`thinking`,thinking:f}]},assistantMessageEvent:{type:`text_start`,contentIndex:0,partial:{}}}))},40*(p.length+1)),d.forEach((e,t)=>{window.setTimeout(()=>{A(z(n,i,{type:`message_update`,message:{...h,content:[{type:`text`,text:u.slice(0,u.indexOf(e)>=0?u.indexOf(e)+e.length:u.length)}]},assistantMessageEvent:{type:`text_delta`,contentIndex:0,delta:e,partial:{}}}))},40*(p.length+1)+80*(t+1))}),window.setTimeout(()=>{if(!ki(n,i)){let e=B().find(e=>e.id===n)??null;if(!e||e.status===`paused`||e.status===`closed`)return}let e={...h,content:[{type:`thinking`,thinking:f},{type:`text`,text:u}]};A(z(n,i,{type:`message_update`,message:e,assistantMessageEvent:{type:`text_end`,contentIndex:0,content:u,partial:{}}})),A(z(n,i,{type:`message_end`,message:e})),A(z(n,i,{type:`turn_end`,message:e,toolResults:[]}));let t=G(n,e=>{let t=P(),r=(Di()[n]??[]).filter(e=>e!==i);return{...e,status:r.length>0?`streaming`:`idle`,updatedAt:t,events:[...e.events.filter(e=>e.runId!==i),F(`user`,o,{runId:i,timestamp:t}),F(`assistant`,u,{thinkingText:f,timestamp:t,runId:i})]}});if(!t&&!c){A(z(n,i,{type:`error`,message:`Unable to find session ${n}`,source:`mock`}));return}let r=Li(c??t,i,u);r&&rt(r);let a=Di(),s=(a[n]??[]).filter(e=>e!==i);s.length>0?a[n]=s:delete a[n],Oi(a),A(z(n,i,{type:`agent_end`}))},80*(d.length+2))},120),t}return e(`send_session_message`,{sessionId:n,message:o,runId:i,sendMode:a})}async function Io(n){let r=n??D();if(!t())return r;let i=await e(`list_projects`);return r&&i.some(e=>e.id===r)?r:i[0]?.id??r??null}function Lo(e,t){return typeof e==`object`&&e?{projectId:e.projectId,includeArchived:e.includeArchived??!1,tags:e.tags,tagMatch:e.tagMatch??`all`,sortBy:e.sortBy??`updatedAt`,sortDirection:e.sortDirection??`desc`}:{projectId:t,includeArchived:e??!1,tags:void 0,tagMatch:`all`,sortBy:`updatedAt`,sortDirection:`desc`}}function Ro(e){return Zi(e).join(`,`)}function zo(e,t,n){if(t.length===0)return!0;let r=new Set(e.tags??[]);return n===`any`?t.some(e=>r.has(e)):t.every(e=>r.has(e))}function Bo(e,t,n){if(e.archived!==t.archived)return Number(e.archived)-Number(t.archived);let r=n.sortDirection===`asc`?1:-1,i=e=>({P0:0,P1:1,P2:2,P3:3,P4:4})[e]??5,a=()=>{let n=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return n===0?fe(t.number).sequence-fe(e.number).sequence:n},o=0;switch(n.sortBy){case`createdAt`:o=(Date.parse(e.createdAt)-Date.parse(t.createdAt))*r;break;case`priority`:o=(i(e.priority)-i(t.priority))*r;break;case`number`:o=(fe(e.number).sequence-fe(t.number).sequence)*r;break;case`title`:o=e.title.localeCompare(t.title,void 0,{sensitivity:`base`})*r;break;case`tags`:{let n=Ro(e.tags),i=Ro(t.tags),a=n.length===0;if(a!==(i.length===0))return a?1:-1;o=n.localeCompare(i)*r;break}default:o=(Date.parse(e.updatedAt)-Date.parse(t.updatedAt))*r;break}return o===0?a():o}async function Vo(n=!1,r){let i=Lo(n,r),a=i.projectId??D(),o=Zi(i.tags);if(!t()){let e=ma(a).tasks.filter(e=>e.projectId===a).filter(e=>i.includeArchived||!e.archived).map(Z).filter(e=>zo(e,o,i.tagMatch)).sort((e,t)=>Bo(e,t,i));return W(`info`,`tasks.list`,`Listed ${e.length} tasks for ${a??`default`}`),e}return e(`list_tasks`,{projectId:await Io(i.projectId),includeArchived:i.includeArchived,tags:o,tagMatch:i.tagMatch,sortBy:i.sortBy,sortDirection:i.sortDirection})}async function Q(n){if(!t()){let e=ma().tasks.find(e=>e.id===n);if(!e)throw Error(`Task ${n} was not found`);return e}return e(`get_task`,{taskId:n})}async function Ho(n){return t()?e(`list_task_todos`,{taskId:n}):is(n)}async function Uo(n,r){return t()?e(`list_unfinished_task_todos`,{taskId:n,laneId:r??null}):is(n,r??void 0,!1)}async function Wo(n,r){if(!t()){let e=Y(),t=e.find(e=>e.id===n);if(!t)throw Error(`Task ${n} was not found`);let i=r.description.trim(),a=r.laneId?.trim()||null;if(!i)throw Error(`description: Task todo description is required.`);if(!t.workflowId)throw Error(`laneId: Task todos require the task to have a workflow.`);if(!a)throw Error(`laneId: A workflow lane is required for task todos.`);if(!U().find(e=>e.id===t.workflowId)?.lanes.some(e=>e.id===a))throw Error(`laneId: Todo lane must belong to the task workflow.`);let o=P(),s={id:N(`task-todo`),taskId:n,laneId:a,description:i,completed:!1,createdAt:o,updatedAt:o};return X(e.map(e=>e.id===n?{...e,todos:[...e.todos??[],s],updatedAt:o}:e)),W(`info`,`task.todo.added`,`Added todo ${s.id} to task ${n}`),M({taskIds:[n],reason:`task.todo.added`}),s}return e(`add_task_todo`,{taskId:n,input:r})}async function Go(n){if(!t()){let{task:e,todo:t}=as(n),r=P();return X(Y().map(t=>t.id===e.id?{...t,todos:(t.todos??[]).map(e=>e.id===n?{...e,completed:!0,updatedAt:r}:e),updatedAt:r}:t)),W(`info`,`task.todo.finished`,`Marked todo ${n} finished`),M({taskIds:[e.id],reason:`task.todo.finished`}),as(n).todo}return e(`mark_task_todo_finished`,{todoId:n})}async function Ko(n){if(!t()){let{task:e,todo:t}=as(n),r=P();return X(Y().map(t=>t.id===e.id?{...t,todos:(t.todos??[]).map(e=>e.id===n?{...e,completed:!1,updatedAt:r}:e),updatedAt:r}:t)),W(`info`,`task.todo.unfinished`,`Marked todo ${n} unfinished`),M({taskIds:[e.id],reason:`task.todo.unfinished`}),as(n).todo}return e(`mark_task_todo_unfinished`,{todoId:n})}async function qo(n){if(!t()){let{task:e,todo:t}=as(n),r=P();return X(Y().map(t=>t.id===e.id?{...t,todos:(t.todos??[]).filter(e=>e.id!==n),updatedAt:r}:t)),W(`info`,`task.todo.deleted`,`Deleted todo ${n}`),M({taskIds:[e.id],reason:`task.todo.deleted`}),t}return e(`delete_task_todo`,{todoId:n})}async function Jo(n,r){let i=r??D();if(!t()){let e=Ma(n);if(e.length>0)throw Error(e.map(e=>`${e.path}: ${e.message}`).join(`; `));let t=Y().map(e=>J(e)),r=ja(n,void 0,i??void 0),a=K(),o=[r,...t].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)),s=ya(o,a,r.id,r.parentTaskId,r.parentTaskId);X(Ea(wa(o,a,s,r.updatedAt).tasks,s,r.updatedAt).tasks),W(`info`,`task.created`,`Created task ${r.id}`);let c=await Q(r.id);return q(`task.created`,`task`,r.id,{taskId:r.id,taskNumber:r.number,status:c.status},r.projectId),M({taskIds:s,reason:`task.created`}),c}let a=await Io(r);return console.debug(`createTask resolvedProjectId`,{projectId:r,resolvedProjectId:a,input:n}),e(`create_task`,{projectId:a,input:n})}async function Yo(n,r){if(!t()){let e=Ma(r,n);if(e.length>0)throw Error(e.map(e=>`${e.path}: ${e.message}`).join(`; `));let t=Y().map(e=>J(e)),i=t.find(e=>e.id===n);if(!i)throw Error(`Task ${n} was not found`);let a=ja(r,i);a.status!==i.status&&(a.autoBlockedByDependencies=!1);let o=K(),s=ya(t,o,n,i.parentTaskId,a.parentTaskId),c=Ta(wa(t.map(e=>e.id===n?a:e).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)),o,s,a.updatedAt).tasks,a.status===`blocked`?[n]:[],a.updatedAt);X(Ea(c.tasks,s,a.updatedAt).tasks);for(let e of c.pausedSessionIds)await uo(e,`Task is blocked and the current lane was paused.`);W(`info`,`task.updated`,`Updated task ${n}`);let l=await Q(n);return q(`task.updated`,`task`,n,{taskId:n,taskNumber:l.number,status:l.status},l.projectId),M({taskIds:s,reason:`task.updated`}),l}return e(`update_task`,{taskId:n,input:r})}async function Xo(n){if(!t()){let e=ma().tasks,t=e.find(e=>e.id===n);if(!t)throw Error(`Task ${n} was not found`);return Ki(K().filter(e=>e.blockerTaskId!==n&&e.blockedTaskId!==n)),X(e.filter(e=>e.id!==n).map(e=>e.parentTaskId===n?{...e,parentTaskId:null}:e)),W(`info`,`task.deleted`,`Deleted task ${n}`),q(`task.deleted`,`task`,n,{taskId:n,taskNumber:t.number,status:t.status},t.projectId),M({taskIds:[n],reason:`task.deleted`}),t}return e(`delete_task`,{taskId:n})}async function Zo(n){let r=b()?.client;if(r)return r.tasks.dispatch(n);if(!t()){let e=Y(),t=e.find(e=>e.id===n);if(!t)throw Error(`Task ${n} was not found`);if(!t.workflowId||!t.currentLaneId)throw Error(`Task must have a workflow and current lane before dispatch.`);if(t.activeLaneAssignment)return Q(n);if(t.status===`blocked`)throw Error(`Task ${n} is blocked and cannot be dispatched until it becomes runnable.`);if(t.dependencyBlocked)throw Error(`Task ${n} is blocked by unresolved dependencies or unfinished subtasks.`);let r=U().find(e=>e.id===t.workflowId),i=r?.lanes.find(e=>e.id===t.currentLaneId);if(!r||!i)throw Error(`Current workflow lane could not be resolved.`);if(i.assignedEntityType===`user`)throw Error(`Current lane is user-owned and cannot be dispatched.`);let a=i.assignedEntityType===`agent`?hi().find(e=>e.slug===i.assignedEntityId)?.id??i.assignedEntityId??null:i.assignedEntityId??null,o=P(),c={id:N(`task-assignment`),taskId:t.id,workflowId:r.id,laneId:i.id,workerType:i.assignedEntityType,workerId:a,status:`active`,sessionId:null,runtimeCwd:`/mock/runtime/${i.assignedEntityType}/${i.assignedEntityId??`user`}`,roleQueueEntryId:i.assignedEntityType===`role`?N(`queue`):null,roleInstanceId:i.assignedEntityType===`role`?N(`instance`):null,prompt:`Work task ${t.number}: ${t.title}`,startedAt:o,completedAt:null,createdAt:o,updatedAt:o};if(i.assignedEntityType===`agent`&&c.workerId){let e=zi(i.assignedEntityId??`Agent`,c.workerId);c.sessionId=e.id,c.runtimeCwd=Be(s),G(e.id,e=>Pi(e,t,`agent`,i.assignedEntityId??`Agent`));let n=N(`agent-queue`);_i([...gi(),{id:n,projectId:s,agentId:c.workerId,status:`dispatched`,sourceType:`workflow_lane`,sourceTaskId:t.id,sourceWorkflowId:r.id,sourceLaneId:i.id,deliveryMode:`prompt`,title:`${t.number} · ${t.title}`,message:c.prompt,sessionId:c.sessionId,runId:N(`run`),dispatchedAt:c.startedAt,completedAt:null,createdAt:c.createdAt,updatedAt:c.updatedAt}]),H(V().map(e=>e.agentId===c.workerId&&e.projectId===s?{...e,status:`running`,mainSessionId:c.sessionId,runtimeCwd:c.runtimeCwd,currentQueueEntryId:n,lastDispatchAt:c.updatedAt,lastError:null,updatedAt:c.updatedAt}:e))}else if(i.assignedEntityType===`role`){let e=Pi(St(`${i.name} · ${t.title}`,`Role runtime session for ${t.number} is active and ready to continue the assigned lane.`),t,`role`,i.assignedEntityId??i.name);c.sessionId=e.id,xt(e),j({sessionIds:[e.id],reason:`task.dispatch.role_session`})}return X(e.map(e=>e.id===n?{...e,status:`in_progress`,assigneeType:i.assignedEntityType,assigneeId:i.assignedEntityId??null,activeLaneAssignment:c,laneRuns:[...e.laneRuns,{id:N(`lane-run`),taskId:e.id,laneId:i.id,sessionId:c.sessionId,result:`needs_user`,notes:null,startedAt:c.startedAt,completedAt:null}],updatedAt:c.updatedAt}:e)),W(`info`,`task.dispatch`,`Dispatched task ${n} into ${i.assignedEntityType}:${i.assignedEntityId??`user`}`),q(`task.dispatched`,`task`,n,{taskId:n,assignmentId:c.id,laneId:i.id,sessionId:c.sessionId??null},t.projectId),c.sessionId&&j({sessionIds:[c.sessionId],reason:`task.dispatch`}),M({taskIds:[n],reason:`task.dispatch`}),Q(n)}return e(`dispatch_task_lane`,{taskId:n})}function Qo(e,t,n,r){if(n.assignedEntityType===`user`)return null;let i={id:N(`task-assignment`),taskId:e.id,workflowId:t.id,laneId:n.id,workerType:n.assignedEntityType,workerId:n.assignedEntityId??null,status:`active`,sessionId:N(`session`),runtimeCwd:n.assignedEntityType===`agent`?Be(e.projectId):`/mock/runtime/${n.assignedEntityType}/${n.assignedEntityId??`user`}`,roleQueueEntryId:n.assignedEntityType===`role`?N(`queue`):null,roleInstanceId:n.assignedEntityType===`role`?N(`instance`):null,prompt:`Work task ${e.number}: ${e.title}`,pendingOutcome:null,completionNotes:null,startedAt:r,completedAt:null,createdAt:r,updatedAt:r};if(n.assignedEntityType===`agent`&&i.workerId){let t=zi(n.assignedEntityId??`Agent`,i.workerId);i.sessionId=t.id,G(t.id,t=>Pi(t,e,`agent`,n.assignedEntityId??`Agent`)),j({sessionIds:[t.id],reason:`task.transition.next_assignment`})}if(n.assignedEntityType===`role`){let t=Pi(St(`${n.name} · ${e.title}`,`Role runtime session for ${e.number} is active and ready to continue the assigned lane.`),e,`role`,n.assignedEntityId??n.name);i.sessionId=t.id,xt(t),j({sessionIds:[t.id],reason:`task.dispatch.role_session`})}return i}function $o(e,t,n){if(![`completed`,`canceled`,`blocked`].includes(t)||!e.activeLaneAssignment?.sessionId)return;let r=e.activeLaneAssignment.sessionId;e.activeLaneAssignment.workerType===`agent`&&V().some(e=>e.mainSessionId===r)||(G(r,e=>({...Fi(e),status:`closed`,updatedAt:n})),j({sessionIds:[r],reason:`task.session.closed`}))}function es(e,t,n,r){e.activeLaneAssignment?.workerType!==`agent`||!e.activeLaneAssignment.workerId||(_i(gi().map(r=>r.id===e.activeLaneAssignment?.id||r.sessionId===e.activeLaneAssignment?.sessionId?{...r,status:t===`failure`?`failed`:`completed`,completedAt:n,updatedAt:n}:r)),H(V().map(i=>i.agentId===e.activeLaneAssignment?.workerId?{...i,status:t===`failure`?`needs_attention`:r?`running`:`idle`,mainSessionId:r?.sessionId??e.activeLaneAssignment?.sessionId,runtimeCwd:r?.runtimeCwd??e.activeLaneAssignment?.runtimeCwd,currentQueueEntryId:r?.id??null,lastDispatchAt:n,lastError:t===`failure`?e.activeLaneAssignment?.completionNotes??`Marked failed`:null,updatedAt:n}:i)))}function ts(e,t,n){n?.workerType!==`agent`||!n.workerId||_i([...gi(),{id:n.id,projectId:e.projectId,agentId:n.workerId,status:`dispatched`,sourceType:`workflow_lane`,sourceTaskId:e.id,sourceWorkflowId:t.id,sourceLaneId:n.laneId,deliveryMode:`prompt`,title:`${e.number} · ${e.title}`,message:n.prompt,sessionId:n.sessionId,runId:N(`run`),dispatchedAt:n.startedAt,completedAt:null,createdAt:n.createdAt,updatedAt:n.updatedAt}])}function ns(e){let t=Sr().find(t=>t.id===e)?.slug??s;return!!((Et(t).autoDispatchOnBlockerCompletion??!0)&&t)}async function rs(e){let t=K().filter(t=>t.blockerTaskId===e);if(t.length===0)return[];let n=Y(),r=new Map(U().map(e=>[e.id,e])),i=P(),a=[],o=[...n];for(let e of t){let t=o.findIndex(t=>t.id===e.blockedTaskId);if(t<0)continue;let n=await Q(e.blockedTaskId);if(!ns(n.projectId)||!n.readyForDispatch||n.activeLaneAssignment)continue;let s=n.workflowId?r.get(n.workflowId)??null:null,c=s?.lanes.find(e=>e.id===n.currentLaneId)??null;if(!s||!c||c.assignedEntityType===`user`)continue;let l=Qo(n,s,c,i);l?.sessionId&&(o[t]={...o[t],status:`in_progress`,assigneeType:c.assignedEntityType,assigneeId:c.assignedEntityId??null,activeLaneAssignment:l,laneRuns:[...n.laneRuns,{id:N(`lane-run`),taskId:n.id,laneId:c.id,sessionId:l.sessionId,result:`needs_user`,notes:null,startedAt:i,completedAt:null}],updatedAt:i},ts(n,s,l),a.push(n.id))}return a.length>0&&X(o.sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))),a}function is(e,t,n){let r=Y().find(t=>t.id===e);if(!r)throw Error(`Task ${e} was not found`);return(r.todos??[]).filter(e=>(t?e.laneId===t:!0)&&(n===void 0?!0:e.completed===n))}function as(e){for(let t of Y()){let n=(t.todos??[]).find(t=>t.id===e);if(n)return{task:t,todo:n}}throw Error(`Task todo ${e} was not found`)}function os(e){return e.length===0?``:e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(`, `)}, and ${e[e.length-1]}`}function ss(e){let t=e.activeLaneAssignment;return t?ri().filter(e=>e.readAt||e.archivedAt?!1:e.assignmentId===t.id?!0:t.workerType===`agent`&&e.recipientType===`agent`&&e.recipientId===t.workerId):[]}function $(e,t,n,r,i){return{action:t,disposition:n,taskId:e.id,taskNumber:e.number,title:e.title,status:e.status,currentLaneId:e.currentLaneId??null,assigneeType:e.assigneeType,assigneeId:e.assigneeId??null,activeLaneAssignmentStatus:Cn(e)??e.activeLaneAssignment?.status??null,pendingOutcome:e.activeLaneAssignment?.pendingOutcome??null,sessionId:e.activeLaneAssignment?.sessionId??null,summary:r??null,notes:i??null}}async function cs(e,t,n,r,i=!0){let a=Y(),o=a.find(t=>t.id===e);if(!o||!o.workflowId||!o.currentLaneId)throw Error(`Task ${e} does not have an active workflow lane.`);let s=U().find(e=>e.id===o.workflowId),c=s?.lanes.find(e=>e.id===o.currentLaneId);if(!s||!c)throw Error(`Current workflow lane could not be resolved.`);let l=P(),u=n.trim();if(!u)throw Error(`summary: A lane summary is required when closing a lane transition.`);if(Array.from(u).length>500)throw Error(`summary: Lane summaries must be 500 characters or fewer.`);let d=r?.trim()||null,f=t===`success`?ss(o):[],p=t===`success`?is(e,c.id,!1):[];if(f.length>0||p.length>0){let t=[],n=[];throw f.length>0&&(t.push(`${f.length} unread mail message(s)`),n.push(`Call get_unread_mail(${e}), review them, then call mark_mail_read(${e}).`)),p.length>0&&(t.push(`${p.length} unfinished todo item(s) for lane ${c.id}`),n.push(`Call list_unfinished_task_todos(${e}, laneId=${c.id}), review them, then finish or reopen them.`)),Error(`Task ${e} cannot complete as success yet because it has ${os(t)}. ${n.join(` `)} Clear those items and then try the completion tool again.`)}if(!i&&t!==`success`&&o.activeLaneAssignment&&[`agent`,`role`].includes(o.activeLaneAssignment.workerType)){let n=o.activeLaneAssignment;if(!n.sessionId)throw Error(`Task ${e} is missing an active session for continued work.`);let r=n.sessionId,i=is(e,void 0,!1).length>0?hr:gr;return X(a.map(t=>t.id===e?{...t,status:`in_progress`,assigneeType:c.assignedEntityType,assigneeId:c.assignedEntityId??null,updatedAt:l}:t)),G(r,e=>({...e,status:`active`,updatedAt:l,events:[...e.events,F(`system`,i)]})),j({sessionIds:[r],reason:`task.transition.continue_working`}),M({taskIds:[e],reason:`task.transition.continue_working`}),W(`info`,`task.transition.continue_working`,`Kept task ${e} in progress after ${t} requested continue-working guidance`),Q(e)}if(!i&&t!==`success`)throw Error(`Task ${e} can only continue working after a slice-complete failure/intervention request when the active lane is owned by an agent or role.`);if(o.status===`blocked`||o.dependencyBlocked){if(!o.activeLaneAssignment)throw Error(`Task ${e} is blocked by unresolved dependencies or unfinished subtasks and cannot progress until those blockers are resolved.`);return X(a.map(t=>t.id===e?{...t,status:`blocked`,activeLaneAssignment:null,laneRuns:t.laneRuns.map((e,t,n)=>t===n.length-1&&e.completedAt==null?{...e,result:`blocked`,summary:u,notes:d??e.notes??null,completedAt:l}:e),updatedAt:l}:t)),Ri(o.activeLaneAssignment,null),es({...o,activeLaneAssignment:o.activeLaneAssignment?{...o.activeLaneAssignment,completionSummary:u,completionNotes:d}:null},`success`,l,null),$o(o,`blocked`,l),W(`info`,`task.transition`,`Stopped blocked task ${e} at transition time`),M({taskIds:[e],reason:`task.transition.blocked`}),Q(e)}if(t===`success`&&o.activeLaneAssignment&&[`agent`,`role`].includes(o.activeLaneAssignment.workerType)&&(c.requireUserApprovalOnSuccess??!1)){X(a.map(n=>n.id===e?{...n,status:`in_review`,assigneeType:`user`,assigneeId:null,activeLaneAssignment:n.activeLaneAssignment?{...n.activeLaneAssignment,status:`awaiting_user_approval`,pendingOutcome:`success`,completionSummary:u,completionNotes:d,updatedAt:l}:null,laneRuns:n.laneRuns.map((e,n,r)=>n===r.length-1&&e.completedAt==null?{...e,result:t,summary:u,notes:d??e.notes??null,completedAt:l}:e),updatedAt:l}:n)),W(`info`,`task.transition`,`Task ${e} is awaiting user approval on ${c.name}`),M({taskIds:[e],reason:`task.transition.awaiting_user_approval`});let n=await Q(e);return rt(Pt(n,`task.awaiting_user_approval`,kt(xr(),n.projectId))),n}if(t===`needs_user`&&o.activeLaneAssignment&&[`agent`,`role`].includes(o.activeLaneAssignment.workerType)){X(a.map(n=>n.id===e?{...n,status:`in_review`,assigneeType:`user`,assigneeId:null,activeLaneAssignment:n.activeLaneAssignment?{...n.activeLaneAssignment,status:`awaiting_user_intervention`,pendingOutcome:`needs_user`,completionSummary:u,completionNotes:d,updatedAt:l}:null,laneRuns:n.laneRuns.map((e,n,r)=>n===r.length-1&&e.completedAt==null?{...e,result:t,summary:u,notes:d??e.notes??null,completedAt:l}:e),updatedAt:l}:n)),W(`info`,`task.transition`,`Task ${e} is awaiting user intervention on ${c.name}`),M({taskIds:[e],reason:`task.transition.awaiting_user_intervention`});let n=await Q(e);return rt(Pt(n,`task.awaiting_user_intervention`,kt(xr(),n.projectId))),n}let m=o.currentLaneId,h=o.status,g=o.assigneeType,_=o.assigneeId??null;if(t===`success`)if(c.successTransitionType===`lane`&&c.successTargetLaneId){let e=s.lanes.find(e=>e.id===c.successTargetLaneId);m=e?.id??null,h=e?.assignedEntityType===`user`?`in_review`:`ready`,g=e?.assignedEntityType??`unassigned`,_=e?.assignedEntityId??null}else m=null,h=`completed`,g=`unassigned`,_=null;else if(t===`failure`)if(c.failureTransitionType===`lane`&&c.failureTargetLaneId){let e=s.lanes.find(e=>e.id===c.failureTargetLaneId);m=e?.id??null,h=e?.assignedEntityType===`user`?`in_review`:`ready`,g=e?.assignedEntityType??`unassigned`,_=e?.assignedEntityId??null}else h=`blocked`,g=`user`,_=null;else h=`in_review`,g=`user`,_=null;let ee=m?s.lanes.find(e=>e.id===m)??null:null,v=ee&&ee.assignedEntityType!==`user`&&[`ready`,`in_progress`].includes(h)?Qo(o,s,ee,l):null,te=o.activeLaneAssignment?o.laneRuns.map((e,n,r)=>n===r.length-1&&e.completedAt==null?{...e,result:t,summary:u,notes:d??e.notes??null,completedAt:l}:e):o.laneRuns,ne=a.map(t=>t.id===e?{...J(t),currentLaneId:m,status:h,assigneeType:g,assigneeId:_,activeLaneAssignment:v,autoBlockedByDependencies:[`completed`,`canceled`].includes(h)?!1:J(t).autoBlockedByDependencies,laneRuns:v&&ee?[...te,{id:N(`lane-run`),taskId:t.id,laneId:ee.id,sessionId:v.sessionId,result:`needs_user`,notes:null,startedAt:v.startedAt,completedAt:null}]:te,updatedAt:l}:J(t)),re=K(),ie=ya(ne,re,e,o.parentTaskId,o.parentTaskId);X(wa(ne,re,ie,l).tasks),Ri(o.activeLaneAssignment,v),es({...o,activeLaneAssignment:o.activeLaneAssignment?{...o.activeLaneAssignment,completionSummary:u,completionNotes:d}:null},t,l,v),ts(o,s,v),$o(o,h,l);let ae=await rs(e);W(`info`,`task.transition`,`Completed task ${e} lane with ${t}`);let y=await Q(e);return q(t===`success`&&y.status===`completed`?`task.completed`:t===`success`?`task.transition_success`:t===`failure`?`task.failed`:`task.user_intervention_requested`,`task`,e,{taskId:e,status:y.status,outcome:t,summary:u,notes:d,workflowId:y.workflowId??null,laneId:y.currentLaneId??null},y.projectId),M({taskIds:ha([...ie,...ae]),reason:`task.transition.${t}`}),t!==`needs_user`&&y.assigneeType===`user`&&rt(Pt(y,`task.assigned_to_user`,kt(xr(),y.projectId))),y}async function ls(e){let t=Y(),n=t.find(t=>t.id===e);if(!n||!n.workflowId||!n.currentLaneId||Cn(n)!==`awaiting_user_approval`)throw Error(`Task ${e} is not awaiting lane approval.`);let r=U().find(e=>e.id===n.workflowId),i=r?.lanes.find(e=>e.id===n.currentLaneId);if(!r||!i)throw Error(`Current workflow lane could not be resolved.`);let a=P(),o=n.currentLaneId,s=n.status,c=n.assigneeType,l=n.assigneeId??null;if(i.successTransitionType===`lane`&&i.successTargetLaneId){let e=r.lanes.find(e=>e.id===i.successTargetLaneId);o=e?.id??null,s=e?.assignedEntityType===`user`?`in_review`:`ready`,c=e?.assignedEntityType??`unassigned`,l=e?.assignedEntityId??null}else o=null,s=`completed`,c=`unassigned`,l=null;let u=o?r.lanes.find(e=>e.id===o)??null:null,d=u&&u.assignedEntityType!==`user`&&[`ready`,`in_progress`].includes(s)?Qo(n,r,u,a):null,f=n.laneRuns.map((e,t,r)=>t===r.length-1&&e.completedAt==null?{...e,result:`success`,notes:n.activeLaneAssignment?.completionNotes??e.notes??null,completedAt:a}:e),p=t.map(t=>t.id===e?{...J(t),currentLaneId:o,status:s,assigneeType:c,assigneeId:l,activeLaneAssignment:d,autoBlockedByDependencies:[`completed`,`canceled`].includes(s)?!1:J(t).autoBlockedByDependencies,laneRuns:d&&u?[...f,{id:N(`lane-run`),taskId:t.id,laneId:u.id,sessionId:d.sessionId,result:`needs_user`,notes:null,startedAt:d.startedAt,completedAt:null}]:f,updatedAt:a}:J(t)),m=K(),h=ya(p,m,e,n.parentTaskId,n.parentTaskId);X(wa(p,m,h,a).tasks),Ri(n.activeLaneAssignment,d),es(n,`success`,a,d),ts(n,r,d),$o(n,s,a);let g=await rs(e);return W(`info`,`task.transition`,`Approved pending lane completion for task ${e}`),M({taskIds:ha([...h,...g]),reason:`task.transition.approved_success`}),Q(e)}async function us(e){let t=Y(),n=t.find(t=>t.id===e),r=n?Cn(n):null;if(!n||!n.activeLaneAssignment?.sessionId||![`awaiting_user_approval`,`awaiting_user_intervention`].includes(r??``))throw Error(`Task ${e} is not paused for user review.`);if(r===`awaiting_user_approval`&&n.workflowId&&n.currentLaneId){let r=U().find(e=>e.id===n.workflowId),i=r?.lanes.find(e=>e.id===n.currentLaneId),a=i?.needsWorkTargetLaneId?r?.lanes.find(e=>e.id===i.needsWorkTargetLaneId)??null:null;if(i?.needsWorkTargetLaneId&&!a)throw Error(`Needs Work target lane ${i.needsWorkTargetLaneId} could not be resolved for task ${e}.`);if(i&&a){let i=P(),o=a.assignedEntityType===`user`?`in_review`:`ready`,s=a.assignedEntityType,c=a.assignedEntityId??null,l=a.assignedEntityType===`user`?null:Qo(n,r,a,i),u=n.activeLaneAssignment?n.laneRuns.map((e,t,n)=>t===n.length-1&&e.completedAt==null?{...e,result:`failure`,notes:e.notes??null,completedAt:i}:e):n.laneRuns;return X(t.map(t=>t.id===e?{...t,currentLaneId:a.id,status:l?`in_progress`:o,assigneeType:s,assigneeId:c,activeLaneAssignment:l,laneRuns:l?[...u,{id:N(`lane-run`),taskId:t.id,laneId:a.id,sessionId:l.sessionId,result:`needs_user`,notes:null,startedAt:l.startedAt,completedAt:null}]:u,updatedAt:i}:t)),Ri(n.activeLaneAssignment,l),es(n,`failure`,i,l),ts(n,r,l),W(`info`,`task.transition`,`Sent task ${e} to configured Needs Work lane ${a.id}`),M({taskIds:[e],reason:`task.transition.needs_work`}),Q(e)}}let i=P(),a=r===`awaiting_user_intervention`?`The user has responded to your intervention request and resumed this lane. Reload the latest task context, comments, and mail before continuing.`:`The user has requested more work be done on this lane. Reload the latest task context and comments before continuing.`;return X(t.map(t=>t.id===e?{...t,status:`in_progress`,assigneeType:t.activeLaneAssignment?.workerType??t.assigneeType,assigneeId:t.activeLaneAssignment?.workerId??t.assigneeId,activeLaneAssignment:t.activeLaneAssignment?{...t.activeLaneAssignment,status:`active`,pendingOutcome:null,completionSummary:null,completionNotes:null,updatedAt:i}:null,laneRuns:t.activeLaneAssignment?.sessionId?[...t.laneRuns,{id:N(`lane-run`),taskId:t.id,laneId:t.activeLaneAssignment.laneId,sessionId:t.activeLaneAssignment.sessionId,result:`needs_user`,summary:null,notes:null,startedAt:i,completedAt:null}]:t.laneRuns,updatedAt:i}:t)),G(n.activeLaneAssignment.sessionId,e=>({...e,status:`active`,updatedAt:i,events:[...e.events,F(`system`,a)]})),j({sessionIds:[n.activeLaneAssignment.sessionId],reason:`task.transition.rework`}),W(`info`,`task.transition`,`Sent task ${e} back to the current lane session for more work`),M({taskIds:[e],reason:`task.transition.needs_work`}),Q(e)}async function ds(e,t){let n=await Q(e);if(!n.activeLaneAssignment||![`active`,`queued`].includes(n.activeLaneAssignment.status))throw Error(`Task ${e} is not active or queued and cannot be paused.`);let r=P();return n.activeLaneAssignment.sessionId&&await uo(n.activeLaneAssignment.sessionId,t),X(Y().map(n=>n.id===e?{...n,status:`in_review`,assigneeType:`user`,assigneeId:null,activeLaneAssignment:n.activeLaneAssignment?{...n.activeLaneAssignment,status:`paused_by_user`,pendingOutcome:`paused`,completionNotes:t?.trim()||null,updatedAt:r}:null,updatedAt:r}:n)),W(`info`,`task.control.paused`,`Paused task lane for task ${e}`),M({taskIds:[e],reason:`task.control.paused`}),Q(e)}async function fs(e,t){let n=await Q(e);n.activeLaneAssignment?.sessionId&&await uo(n.activeLaneAssignment.sessionId,t);let r=await Ts(e);return W(`info`,`task.control.stopped`,`Stopped task activity for task ${e}`),M({taskIds:[e],reason:`task.control.stopped`}),r}async function ps(e,t,n){let r=Y(),i=r.find(t=>t.id===e);if(!i||!i.workflowId||!i.currentLaneId)throw Error(`Task ${e} does not have an active workflow lane.`);if(i.currentLaneId===t)throw Error(`Task ${e} is already in lane ${t}.`);let a=U().find(e=>e.id===i.workflowId),o=a?.lanes.find(e=>e.id===t)??null;if(!a||!o)throw Error(`Workflow lane ${t} could not be resolved for task ${e}.`);let s=P(),c=n?.trim()||null,l=c?{id:N(`task-comment`),taskId:e,parentCommentId:null,author:`Orchestra`,originType:`system`,originId:null,message:`Re-lane note for move to ${o.name} (${o.id}):\n\n${c}`,interruptAgent:!1,repositoryId:null,relativePath:null,lineStart:null,lineEnd:null,columnStart:null,columnEnd:null,selectedText:null,anchorCommitHash:null,anchorHasUncommittedChanges:null,createdAt:s,updatedAt:s}:null,u=o.assignedEntityType===`user`?`in_review`:`ready`,d=o.assignedEntityType,f=o.assignedEntityId??null,p=o.assignedEntityType===`user`?null:Qo(i,a,o,s),m=i.activeLaneAssignment?i.laneRuns.map((e,t,n)=>t===n.length-1&&e.completedAt==null?{...e,result:`failure`,notes:c??e.notes??null,completedAt:s}:e):i.laneRuns;return X(r.map(t=>t.id===e?{...t,currentLaneId:o.id,status:p?`in_progress`:u,assigneeType:d,assigneeId:f,activeLaneAssignment:p,comments:l?[...t.comments,l]:t.comments,laneRuns:p?[...m,{id:N(`lane-run`),taskId:t.id,laneId:o.id,sessionId:p.sessionId,result:`needs_user`,notes:null,startedAt:p.startedAt,completedAt:null}]:m,updatedAt:s}:t)),Ri(i.activeLaneAssignment,p),es({...i,activeLaneAssignment:i.activeLaneAssignment?{...i.activeLaneAssignment,completionNotes:c}:null},`failure`,s,p),ts(i,a,p),W(`info`,`task.transition`,`Re-laned task ${e} to lane ${t}`),q(`task.relaned`,`task`,e,{taskId:e,laneId:o.id,status:p?`in_progress`:u,notes:c},i.projectId),M({taskIds:[e],reason:`task.transition.relane`}),Q(e)}async function ms(n,r,i){return t()?e(`complete_lane_as_success`,{taskId:n,summary:r,notes:i}):$(await cs(n,`success`,r,i),`complete_lane_as_success`,`transitioned`,r,i)}async function hs(n,r,i,a){return t()?e(`complete_lane_as_failure`,{taskId:n,summary:r,actuallyFailed:i,notes:a}):$(await cs(n,`failure`,r,a,i),`complete_lane_as_failure`,i?`transitioned`:`continue_working`,r,a)}async function gs(n,r,i,a){return t()?e(`request_user_intervention`,{taskId:n,summary:r,actuallyBlocked:i,notes:a}):$(await cs(n,`needs_user`,r,a,i),`request_user_intervention`,i?`transitioned`:`continue_working`,r,a)}async function _s(n){if(!t()){let e=await Q(n);return $(await ls(n),`approve_task_review`,`updated`,e.activeLaneAssignment?.completionSummary??null,e.activeLaneAssignment?.completionNotes??null)}return e(`approve_task_review`,{taskId:n})}async function vs(n){if(!t()){let e=await Q(n);return $(await ls(n),`approve_lane_completion`,`updated`,e.activeLaneAssignment?.completionSummary??null,e.activeLaneAssignment?.completionNotes??null)}return e(`approve_lane_completion`,{taskId:n})}async function ys(n,r){if(!t()){let e=await Q(n);if(Cn(e)!==`awaiting_user_approval`)throw Error(`Task ${n} is not awaiting user approval.`);return $(await us(n),`mark_task_needs_work`,`updated`,e.activeLaneAssignment?.completionSummary??null,r??e.activeLaneAssignment?.completionNotes??null)}return e(`mark_task_needs_work`,{taskId:n,notes:r})}async function bs(n,r){if(!t()){let e=await Q(n),t=Cn(e);if(!e.activeLaneAssignment||![`awaiting_user_intervention`,`paused_by_user`].includes(t??``))throw Error(`Task ${n} is not paused for user intervention or a user pause.`);return $(t===`paused_by_user`?await(async()=>{let t=P();return X(Y().map(e=>e.id===n?{...e,status:`in_progress`,assigneeType:e.activeLaneAssignment?.workerType??e.assigneeType,assigneeId:e.activeLaneAssignment?.workerId??e.assigneeId,activeLaneAssignment:e.activeLaneAssignment?{...e.activeLaneAssignment,status:`active`,pendingOutcome:null,completionNotes:null,updatedAt:t}:null,updatedAt:t}:e)),e.activeLaneAssignment?.sessionId&&(G(e.activeLaneAssignment.sessionId,e=>({...e,status:`active`,updatedAt:t,events:[...e.events,F(`system`,`The user resumed this paused lane. Reload the latest task context before continuing.`)]})),j({sessionIds:[e.activeLaneAssignment.sessionId],reason:`task.control.resumed`})),M({taskIds:[n],reason:`task.control.resumed`}),Q(n)})():await us(n),`resume_task_lane`,`updated`,null,r)}return e(`resume_task_lane`,{taskId:n,notes:r})}async function xs(n,r){return t()?e(`pause_task_lane`,{taskId:n,notes:r}):$(await ds(n,r),`pause_task_lane`,`updated`,null,r)}async function Ss(n,r){return t()?e(`stop_task_activity`,{taskId:n,notes:r}):$(await fs(n,r),`stop_task_activity`,`updated`,null,r)}async function Cs(n,r,i){return t()?e(`reassign_task_to_lane`,{taskId:n,laneId:r,notes:i}):$(await ps(n,r,i),`reassign_task_to_lane`,`transitioned`,null,i)}async function ws(n){if(!t()){let e=await Q(n);if(!e.activeLaneAssignment)throw Error(`Task ${n} does not have an active lane assignment to whip.`);let t={...e,activeLaneAssignment:{...e.activeLaneAssignment,whipCount:(e.activeLaneAssignment.whipCount??0)+1,lastWhipAt:P()},updatedAt:P()};return X(Y().map(e=>e.id===n?t:e)),W(`info`,`task.whip.sent`,`Sent manual whip for task ${n}`),M({taskIds:[n],reason:`task.whip.sent`}),Q(n)}return e(`manual_task_whip`,{taskId:n})}async function Ts(n){let r=b()?.client;if(r)return r.tasks.resetRuntime(n);if(!t()){let e=await Q(n),t=P(),r=e.activeLaneAssignment,i={...e,status:e.currentLaneId?`ready`:e.status,activeLaneAssignment:null,updatedAt:t};return r?.workerType===`agent`&&(_i(gi().filter(e=>e.sourceTaskId!==n)),H(V().map(e=>e.agentId===r.workerId&&e.projectId===s?{...e,status:`idle`,currentQueueEntryId:null,lastError:null,updatedAt:t}:e))),r?.workerType===`role`&&(bi(yi().map(e=>e.sourceTaskId===n&&[`queued`,`assigned`].includes(String(e.status??``))?{...e,status:`canceled`,assignedInstanceId:null,completedAt:t,updatedAt:t}:e)),Si(xi().map(e=>e.id===r.roleInstanceId?{...e,status:`idle`,currentQueueEntryId:null,updatedAt:t}:e))),X(Y().map(e=>e.id===n?i:e)),r?.sessionId&&(G(r.sessionId,e=>Fi(e)),j({sessionIds:[r.sessionId],reason:`task.runtime.reset`})),M({taskIds:[n],reason:`task.runtime.reset`}),Q(n)}return e(`reset_task_runtime`,{taskId:n})}async function Es(n,r){if(!t()){if(n===r)throw Error(`A task cannot depend on itself.`);let e=Y();if(!e.some(e=>e.id===n)||!e.some(e=>e.id===r))throw Error(`Both tasks must exist before adding a dependency.`);let t=K();if(t.some(e=>e.blockerTaskId===n&&e.blockedTaskId===r))throw Error(`That dependency already exists.`);let i=[r],a=new Set;for(;i.length>0;){let e=i.pop();if(a.add(e)){if(e===n)throw Error(`That dependency would create a cycle.`);i.push(...t.filter(t=>t.blockerTaskId===e).map(e=>e.blockedTaskId))}}let o=e.find(e=>e.id===n),s=e.find(e=>e.id===r),c={id:N(`task-dependency`),blockerTaskId:n,blockedTaskId:r,blocker:Z(o),blocked:Z(s),...ba(e,n),createdAt:P()},l=[...t,c];Ki(l);let u=ya(e.map(e=>J(e)),l,r,s.parentTaskId,s.parentTaskId);return X(Ea(wa(e.map(e=>J(e)),l,u,c.createdAt).tasks,u,c.createdAt).tasks),W(`info`,`task.dependency.added`,`Added dependency ${n} -> ${r}`),M({taskIds:ha([n,...u]),reason:`task.dependency.added`}),c}return e(`add_task_dependency`,{blockerTaskId:n,blockedTaskId:r})}async function Ds(n){if(!t()){let e=K(),t=e.find(e=>e.id===n);if(!t)throw Error(`Task dependency ${n} was not found`);let r=e.filter(e=>e.id!==n);Ki(r);let i=Y().map(e=>J(e)),a=i.find(e=>e.id===t.blockedTaskId)??null,o=ya(i,r,t.blockedTaskId,a?.parentTaskId,a?.parentTaskId);return X(Ea(wa(i,r,o).tasks,o).tasks),W(`info`,`task.dependency.removed`,`Removed dependency ${n}`),M({taskIds:ha([t.blockerTaskId,...o]),reason:`task.dependency.removed`}),t}return e(`remove_task_dependency`,{dependencyId:n})}async function Os(n,r,i=10){if(!t()){let e=Y().find(e=>e.id===n)??null;if(!e)return[];let t=r.trim().replace(/^[@$]/,``).toLowerCase(),a=new Set(e.fileReferences.map(e=>e.repositoryId)).size;return e.fileReferences.map(e=>{let n=`${e.repositorySlug}:${e.relativePath}`.toLowerCase(),r=e.relativePath.toLowerCase().indexOf(t),i=n.indexOf(t),o=r>=0?r:i;return{repositoryId:e.repositoryId,repositoryName:e.repositoryName,repositorySlug:e.repositorySlug,relativePath:e.relativePath,displayText:a>1?`${e.relativePath} — ${e.repositoryName}`:e.relativePath,insertText:a>1?`$${e.repositorySlug}:${e.relativePath}`:`$${e.relativePath}`,bestIndex:o}}).filter(e=>e.bestIndex>=0).sort((e,t)=>e.bestIndex===t.bestIndex?e.relativePath.localeCompare(t.relativePath):e.bestIndex-t.bestIndex).slice(0,i).map(({bestIndex:e,...t})=>t)}return e(`search_task_comment_file_mentions`,{taskId:n,query:r,limit:i})}async function ks(n,r){if(!t()){let e=Y(),t=e.find(e=>e.id===n);if(!t)throw Error(`Task ${n} was not found`);let i=r.author.trim(),a=r.message.trim(),o=r.parentCommentId?.trim()||null;if(!i)throw Error(`author: Comment author is required.`);if(!a)throw Error(`message: Comment message is required.`);if(o){let e=t.comments.find(e=>e.id===o)??null;if(!e)throw Error(`parentCommentId: Comment ${o} was not found.`);if(e.parentCommentId)throw Error(`parentCommentId: Replies can only target top-level comments.`)}let s={id:N(`task-comment`),taskId:n,parentCommentId:o,author:i,originType:r.originType?.trim()||`user`,originId:r.originId?.trim()||null,message:a,interruptAgent:r.interruptAgent,repositoryId:r.repositoryId?.trim()||null,relativePath:r.relativePath?.trim()||null,lineStart:r.lineStart??null,lineEnd:r.lineEnd??r.lineStart??null,columnStart:r.columnStart??null,columnEnd:r.columnEnd??null,selectedText:r.selectedText?.trim()||null,anchorCommitHash:null,anchorHasUncommittedChanges:null,diffAnchor:r.diffAnchor??null,createdAt:P(),updatedAt:P()};return X(e.map(e=>e.id===n?{...e,comments:[...e.comments,s],updatedAt:s.updatedAt}:e)),W(`info`,r.interruptAgent?`task.comment.interrupt_requested`:`task.commented`,`Added comment ${s.id} to task ${n}`),q(`task.comment_added`,`task`,n,{taskId:n,commentId:s.id,interrupt:r.interruptAgent},t.projectId),M({taskIds:[n],reason:r.interruptAgent?`task.comment.interrupt_requested`:`task.commented`}),s}return e(`comment_on_task`,{taskId:n,input:r})}async function As(n){if(!t()){let e=await Q(n),t=Yr(),r=P(),i=[...t];for(let t of e.comments.map(Qr)){if(t.originType===`user`)continue;let e=i.find(e=>e.commentId===t.id&&e.taskId===n&&e.userId===`desktop-user`);e?e.readAt=r:i.push({commentId:t.id,taskId:n,userId:`desktop-user`,readAt:r})}return Xr(i),W(`info`,`task.comment.user_read`,`Marked non-user task comments read for task ${n}`),M({taskIds:[n],reason:`task.comment.user_read`}),Q(n)}return e(`mark_task_comments_read_for_user`,{taskId:n})}async function js(n,r=!1){return t()?e(`list_inbox_messages`,{projectId:n??null,includeArchived:r}):ri().filter(e=>e.recipientType===`user`&&(!n||e.projectId===n)).filter(e=>r||!e.archivedAt).sort((e,t)=>!e.archivedAt&&t.archivedAt?-1:e.archivedAt&&!t.archivedAt?1:!e.readAt&&t.readAt?-1:e.readAt&&!t.readAt?1:t.createdAt.localeCompare(e.createdAt))}async function Ms(n){return t()?e(`list_task_messages`,{taskId:n}):ri().filter(e=>e.taskId===n).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}async function Ns(n){if(!t()){let e=Y(),t=n.taskId?e.find(e=>e.id===n.taskId)??null:null,r=t?.projectId??n.projectId??D()??s,i=xr(),a=L(Qn)??[],o=n.recipientType,c=n.recipientId??null,l=`User`,u=null;if(o===`agent`){let e=a.find(e=>e.id===n.recipientId);if(!e)throw Error(`Agent ${n.recipientId} was not found`);l=e.name}else if(o===`active_assignment`){if(!t?.activeLaneAssignment)throw Error(`Task ${n.taskId} has no active assignment mailbox`);o=`assignment`,c=t.activeLaneAssignment.workerId??null,u=t.activeLaneAssignment.id,l=`${a.find(e=>e.id===t.activeLaneAssignment?.workerId)?.name??t.activeLaneAssignment.workerType} · ${t.number}`}let d={deliveryId:N(`mail-delivery`),messageId:N(`mail-message`),projectId:r,taskId:t?.id??n.taskId??null,taskNumber:t?.number??null,taskTitle:t?.title??null,senderType:`user`,senderId:`desktop-user`,senderLabel:n.senderLabel?.trim()||`User`,recipientType:o,recipientId:c,recipientLabel:l,assignmentId:u,body:n.body.trim(),priority:n.priority===`interrupt`?`interrupt`:`normal`,readAt:null,readSessionId:null,archivedAt:null,lastNotifiedAt:o===`user`?null:P(),createdAt:P(),updatedAt:P()};return ii([d,...ri()]),nt({deliveryIds:[d.deliveryId],reason:`mailbox.sent`}),d.taskId&&M({taskIds:[d.taskId],reason:`mailbox.sent`}),d.recipientType===`user`&&rt(Nt(d,kt(i,d.projectId))),W(`info`,`mailbox.sent`,`Sent mailbox delivery ${d.deliveryId} to ${d.recipientLabel}`),d}return e(`send_mailbox_message`,{input:n})}async function Ps(n){if(!t()){let e=P(),t=new Set(n.deliveryIds??ri().filter(e=>e.recipientType===`user`&&!e.readAt).map(e=>e.deliveryId)),r=[];return ii(ri().map(n=>{if(n.recipientType!==`user`||!t.has(n.deliveryId))return n;let i={...n,readAt:e,readSessionId:`desktop-user`,updatedAt:e};return r.push(i),i})),r.length&&nt({deliveryIds:r.map(e=>e.deliveryId),reason:`mailbox.read`}),r}return e(`mark_mailbox_messages_read`,{input:n})}async function Fs(n){if(!t()){let e=P(),t=new Set(n.deliveryIds??ri().filter(e=>e.recipientType===`user`&&!e.archivedAt).map(e=>e.deliveryId)),r=[];return ii(ri().map(n=>{if(n.recipientType!==`user`||!t.has(n.deliveryId))return n;let i={...n,archivedAt:e,updatedAt:e};return r.push(i),i})),r.length&&nt({deliveryIds:r.map(e=>e.deliveryId),reason:`mailbox.archived`}),r}return e(`archive_mailbox_messages`,{input:n})}async function Is(n){if(!t()){let e=Y().find(e=>e.id===n);if(!e)throw Error(`Task ${n} was not found`);return e.comments}return e(`list_task_comments`,{taskId:n})}async function Ls(n,r){if(!t()){let e=Y(),t=null;if(X(e.map(e=>({...e,comments:e.comments.map(e=>e.id===n?(t={...e,message:r.message.trim(),updatedAt:P()},t):e)}))),!t)throw Error(`Task comment ${n} was not found`);let i=t;return q(`task.comment_updated`,`task`,i.taskId,{taskId:i.taskId,commentId:i.id},Y().find(e=>e.id===i.taskId)?.projectId??null),i}return e(`update_task_comment`,{commentId:n,input:r})}async function Rs(n){if(!t()){let e=Y(),t=null;if(X(e.map(e=>{let r=e.comments.find(e=>e.id===n);if(!r)return e;t=r;let i=new Set([n,...e.comments.filter(e=>e.parentCommentId===n).map(e=>e.id)]);return{...e,comments:e.comments.filter(e=>!i.has(e.id))}})),!t)throw Error(`Task comment ${n} was not found`);let r=t;return q(`task.comment_deleted`,`task`,r.taskId,{taskId:r.taskId,commentId:r.id},Y().find(e=>e.id===r.taskId)?.projectId??null),r}return e(`delete_task_comment`,{commentId:n})}async function zs(n){if(!t()){let e=Y().find(e=>e.id===n||e.comments.some(e=>e.id===n));if(!e)throw Error(`Task not found for comment ${n}`);let t=e.comments.find(e=>e.id===n);if(!t)throw Error(`Task comment ${n} was not found`);let r=e;function i(e){let t=r.comments.filter(t=>t.parentCommentId===e),n=t.length;for(let e of t)n+=i(e.id);return n}let a=i(n),o=new Set([n]);function s(e){let t=r.comments.filter(t=>t.parentCommentId===e);for(let e of t)o.add(e.id),s(e.id)}s(n);let c=1+a;return{commentId:t.id,taskId:t.taskId,replyCount:a,attachmentCount:0,fileReferenceCount:0,cascadeDeletedCount:c}}return e(`get_task_comment_delete_impact`,{commentId:n})}async function Bs(n,r){if(!t()){let e=Y(),t=e.find(e=>e.id===n);if(!t)throw Error(`Task ${n} was not found`);let i=(xr().find(e=>e.id===t.projectId)??null)?.repositories.find(e=>e.id===r.repositoryId)??null;if(!i)throw Error(`Repository ${r.repositoryId} was not found`);let a=r.relativePath.trim().replace(/\\/g,`/`).replace(/^\.\//,``);if(!a||a.startsWith(`/`)||a.split(`/`).includes(`..`))throw Error(`relativePath: File path must stay inside the repository root.`);let o={id:N(`task-file-reference`),taskId:n,repositoryId:i.id,repositoryName:i.name,repositorySlug:i.slug,relativePath:a,absolutePath:i.repositoryPath?`${i.repositoryPath.replace(/\/$/,``)}/${a}`:null,exists:!1,isDefault:!1,createdAt:P()};return X(e.map(e=>e.id===n?{...e,fileReferences:[...e.fileReferences,o],updatedAt:o.createdAt}:e)),W(`info`,`task.file_reference.added`,`Added file reference ${o.id} to task ${n}`),q(`task.file_reference_added`,`task`,n,{taskId:n,referenceId:o.id,relativePath:o.relativePath},t.projectId),M({taskIds:[n],reason:`task.file_reference.added`}),o}return e(`add_task_file_reference`,{taskId:n,input:r})}async function Vs(n){if(!t()){let e=Y().find(e=>e.id===n);if(!e)throw Error(`Task ${n} was not found`);return e.fileReferences}return e(`list_task_file_references`,{taskId:n})}async function Hs(n){if(!t()){let e=Y().map(e=>({...e,fileReferences:e.fileReferences.map(e=>({...e,isDefault:e.id===n}))}));X(e);let t=e.flatMap(e=>e.fileReferences).find(e=>e.id===n);if(!t)throw Error(`Task file reference ${n} was not found`);return W(`info`,`task.file_reference.default_set`,`Set ${n} as default`),M({taskIds:[t.taskId],reason:`task.file_reference.default_set`}),t}return e(`set_default_task_file_reference`,{referenceId:n})}async function Us(n){return t()?e(`get_task_file_content`,{path:n}):(L(qn)??{})[n]??[`Mocked file content for: ${n}`,`Second line for anchored comments.`,`Third line with text selection support.`].join(`
`)}async function Ws(n){if(!t()){let e=await Q(n);return{taskId:n,generatedAt:P(),repositories:e.taskRepositories.map(e=>({repositoryId:e.repositoryId,repositoryName:e.repositoryName,repositorySlug:e.repositorySlug,status:`clean`,reviewRootPath:e.taskWorktreePath??e.managedRepositoryPath??null,reviewRootKind:e.taskWorktreePath?`task_worktree`:e.managedRepositoryPath?`managed_repository`:null,unavailableReason:null,defaultBranch:null,baseCommitHash:null,headCommitHash:null,worktreeOnly:!1,hasUncommittedChanges:!1,committedFileCount:0,uncommittedFileCount:0,mixedFileCount:0,files:[]}))}}return e(`get_task_pull_request`,{taskId:n})}async function Gs(n){if(!t()){let e=Y(),t=null,r=e.map(e=>{let r=e.fileReferences.find(e=>e.id===n)??null;return r?(t=r,{...e,fileReferences:e.fileReferences.filter(e=>e.id!==n)}):e});if(!t)throw Error(`Task file reference ${n} was not found`);let i=t;return X(r),W(`info`,`task.file_reference.removed`,`Removed file reference ${n}`),q(`task.file_reference_removed`,`task`,i.taskId,{taskId:i.taskId,referenceId:i.id,relativePath:i.relativePath},Y().find(e=>e.id===i.taskId)?.projectId??null),M({taskIds:[i.taskId],reason:`task.file_reference.removed`}),i}return e(`remove_task_file_reference`,{referenceId:n})}async function Ks(n,r){if(!t()){let e=Y(),t=e.find(e=>e.id===n);if(!t)throw Error(`Task ${n} was not found`);let i=await Xt(r),a=atob(i.base64Data),o=i.mediaType.startsWith(`image/`)?`data:${i.mediaType};base64,${i.base64Data}`:null,s=i.mediaType.startsWith(`text/`)||i.mediaType===`application/json`?a:null,c={id:N(`task-attachment`),taskId:n,fileName:i.fileName,mediaType:i.mediaType||`application/octet-stream`,byteSize:a.length,storedPath:`/mock/attachments/${n}/${i.fileName}`,caption:i.caption?.trim()||null,previewText:s,imageDataUrl:o,createdAt:P()};return X(e.map(e=>e.id===n?{...e,attachments:[...e.attachments,c]}:e)),ni({...ti(),[c.id]:{base64Data:i.base64Data,mediaType:c.mediaType,fileName:c.fileName}}),W(`info`,`task.attachment.added`,`Added attachment ${c.id} to task ${n}`),q(`task.attachment_added`,`task`,n,{taskId:n,attachmentId:c.id,fileName:c.fileName},t.projectId),M({taskIds:[n],reason:`task.attachment.added`}),c}return e(`add_task_attachment`,{taskId:n,input:await Xt(r)})}async function qs(n){if(!t()){let e=ti()[n];if(!e)throw Error(`Task attachment ${n} was not found`);return{fileName:e.fileName,mediaType:e.mediaType,blob:Rt(e.base64Data,e.mediaType)}}let r=await e(`get_task_attachment_content`,{attachmentId:n});return{fileName:r.fileName,mediaType:r.mediaType,blob:Rt(r.base64Data,r.mediaType)}}async function Js(n){if(!t()){let e=ti()[n];if(!e)throw Error(`Task attachment ${n} was not found`);It(Rt(e.base64Data,e.mediaType),e.fileName);return}await e(`download_task_attachment`,{attachmentId:n})}async function Ys(n){if(!t()){let e=Y(),t=null,r=e.map(e=>{let r=e.attachments.find(e=>e.id===n)??null;return r?(t=r,{...e,attachments:e.attachments.filter(e=>e.id!==n)}):e});if(!t)throw Error(`Task attachment ${n} was not found`);let i=t,a={...ti()};return delete a[n],ni(a),X(r),W(`info`,`task.attachment.removed`,`Removed attachment ${n}`),q(`task.attachment_removed`,`task`,i.taskId,{taskId:i.taskId,attachmentId:i.id,fileName:i.fileName},Y().find(e=>e.id===i.taskId)?.projectId??null),M({taskIds:[i.taskId],reason:`task.attachment.removed`}),i}return e(`remove_task_attachment`,{attachmentId:n})}async function Xs(n){let r=n??D();return t()?e(`list_task_schedules`,{projectId:await Io(n)}):ma(r).schedules.filter(e=>e.projectId===r).map(e=>la(e,Y()))}async function Zs(n){if(!t()){let e=ma(),t=e.schedules.find(e=>e.id===n);if(!t)throw Error(`Task schedule ${n} was not found`);return ua(t,e.tasks)}return e(`get_task_schedule`,{scheduleId:n})}async function Qs(n,r){let i=r??D();if(!t()){let e=fa(n);if(e.length>0)throw Error(e.map(e=>`${e.path}: ${e.message}`).join(`; `));let t=pa(n,void 0,i??void 0);Xi([t,...Yi()].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)));let r=ma(i);W(`info`,`task.schedule.created`,`Created task schedule ${t.id}`),q(`task.schedule.created`,`task_schedule`,t.id,{scheduleId:t.id,title:t.taskBlueprint.title,enabled:t.enabled,triggerType:t.trigger.type},t.projectId),M({taskIds:[],reason:`task.schedule.created`});let a=r.schedules.find(e=>e.id===t.id);if(!a)throw Error(`Task schedule ${t.id} was not found after creation`);return ua(a,r.tasks)}return e(`create_task_schedule`,{projectId:await Io(r),input:n})}async function $s(n,r){if(!t()){let e=fa(r);if(e.length>0)throw Error(e.map(e=>`${e.path}: ${e.message}`).join(`; `));let t=Yi(),i=t.find(e=>e.id===n);if(!i)throw Error(`Task schedule ${n} was not found`);let a=pa(r,{...i,trigger:r.trigger,nextFireAt:r.trigger.type===`time`?oa(r.trigger,P()):null});a.occurrences=i.occurrences,a.lastFiredAt=i.lastFiredAt??null,a.lastMaterializedTaskId=i.lastMaterializedTaskId??null,a.lastError=i.lastError??null,Xi(t.map(e=>e.id===n?a:e).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)));let o=ma(i.projectId);W(`info`,`task.schedule.updated`,`Updated task schedule ${n}`),q(`task.schedule.updated`,`task_schedule`,n,{scheduleId:n,title:a.taskBlueprint.title,enabled:a.enabled,triggerType:a.trigger.type},a.projectId),M({taskIds:[],reason:`task.schedule.updated`});let s=o.schedules.find(e=>e.id===n);if(!s)throw Error(`Task schedule ${n} was not found after update`);return ua(s,o.tasks)}return e(`update_task_schedule`,{scheduleId:n,input:r})}async function ec(n){if(!t()){let e=ma(),t=e.schedules,r=t.find(e=>e.id===n);if(!r)throw Error(`Task schedule ${n} was not found`);return Xi(t.filter(e=>e.id!==n)),W(`info`,`task.schedule.deleted`,`Deleted task schedule ${n}`),q(`task.schedule.deleted`,`task_schedule`,n,{scheduleId:n,title:r.taskBlueprint.title},r.projectId),M({taskIds:[],reason:`task.schedule.deleted`}),ua(r,e.tasks)}return e(`delete_task_schedule`,{scheduleId:n})}async function tc(n=!1){let r=b()?.client;return r?r.catalog.listWorkflows(n):t()?e(`list_workflows`,{includeArchived:n}):U().filter(e=>n||!e.archived).map(Ui)}async function nc(n){let r=b()?.client;if(r)return r.catalog.getWorkflow(n);if(!t()){let e=U().find(e=>e.id===n);if(!e)throw Error(`Workflow ${n} was not found`);return e}return e(`get_workflow`,{workflowId:n})}async function rc(n){let r=b()?.client;return r?r.workflows.validateWorkflow(n):t()?e(`validate_workflow`,{input:n}):Na(n)}async function ic(n){let r=b()?.client;if(r)return r.workflows.createWorkflow(n);if(!t()){let e=Na(n);if(!e.valid)throw Error(e.errors.map(e=>`${e.path}: ${e.message}`).join(`; `));let t=Pa(n);return wi([t,...U()]),W(`info`,`workflow.created`,`Created workflow ${t.id}`),t}return e(`create_workflow`,{input:n})}async function ac(n,r){let i=b()?.client;if(i)return i.workflows.updateWorkflow(n,r);if(!t()){let e=Na(r);if(!e.valid)throw Error(e.errors.map(e=>`${e.path}: ${e.message}`).join(`; `));let t=U(),i=t.find(e=>e.id===n);if(!i)throw Error(`Workflow ${n} was not found`);let a=Pa(r,i);return wi(t.map(e=>e.id===n?a:e)),W(`info`,`workflow.updated`,`Updated workflow ${n}`),a}return e(`update_workflow`,{workflowId:n,input:r})}async function oc(n,r){let i=b()?.client;if(i)return i.workflows.duplicateWorkflow(n,r);if(!t()){let e=await nc(n);return ic({name:r?.trim()||`${e.name} Copy`,description:e.description,lanes:e.lanes.map((e,t)=>({key:e.key,name:e.name,description:e.description,order:t,assignedEntityType:e.assignedEntityType,assignedEntityId:e.assignedEntityId,entryPromptTemplate:e.entryPromptTemplate,useSeparateWorktree:e.useSeparateWorktree??!1,requireUserApprovalOnSuccess:e.requireUserApprovalOnSuccess??!1,needsWorkTargetLaneId:e.needsWorkTargetLaneId,successTransitionType:e.successTransitionType,successTargetLaneId:e.successTargetLaneId,failureTransitionType:e.failureTransitionType,failureTargetLaneId:e.failureTargetLaneId}))})}return e(`duplicate_workflow`,{workflowId:n,newName:r})}async function sc(n){let r=b()?.client;if(r)return r.workflows.archiveWorkflow(n);if(!t()){let e=U(),t=e.find(e=>e.id===n);if(!t)throw Error(`Workflow ${n} was not found`);let r={...t,archived:!0,updatedAt:P()};return wi(e.map(e=>e.id===n?r:e)),W(`info`,`workflow.archived`,`Archived workflow ${n}`),r}return e(`archive_workflow`,{workflowId:n})}async function cc(n){let r=b()?.client;if(r)return r.workflows.getWorkflowDeleteImpact(n);if(!t()){let e=U().find(e=>e.id===n);if(!e)throw Error(`Workflow ${n} was not found`);return Wi(e)}return e(`get_workflow_delete_impact`,{workflowId:n})}async function lc(n){let r=b()?.client;if(r)return r.workflows.deleteWorkflow(n);if(!t()){let e=U(),t=e.find(e=>e.id===n);if(!t)throw Error(`Workflow ${n} was not found`);let r=Wi(t);if(!r.canDelete)throw Error(`Workflow ${n} cannot be deleted because it is still referenced by ${r.blockerMessages.join(`, `)}. Archive it instead if you want to hide it without removing historical state.`);return wi(e.filter(e=>e.id!==n)),W(`info`,`workflow.deleted`,`Deleted workflow ${n}`),q(`workflow.deleted`,`workflow`,n,{workflowId:n,name:t.name},null),r}return e(`delete_workflow`,{workflowId:n})}export{Zs as $,ce as $n,Yo as $t,Js as A,at as An,jo as At,fo as B,Re as Bn,_o as Bt,Rs as C,Et as Cn,Ko as Ct,xo as D,St as Dn,xs as Dt,lc as E,Dt as En,Mo as Et,Ya as F,Xe as Fn,Ia as Ft,Za as G,Ge as Gn,vo as Gt,So as H,Be as Hn,Ns as Ht,Or as I,Ye as In,gs as It,Q as J,Je as Jn,uo as Jt,Qa as K,Ve as Kn,ko as Kt,Dr as L,Qe as Ln,Ts as Lt,Ga as M,j as Mn,Ys as Mt,La as N,$e as Nn,Ds as Nt,Eo as O,xt as On,Ba as Ot,Ha as P,qe as Pn,Gs as Pt,Ws as Q,me as Qn,lo as Qt,Er as R,D as Rn,so as Rt,Xo as S,It as Sn,Go as St,qo as T,Tt as Tn,Ka as Tt,ho as U,Ke as Un,Fo as Ut,go as V,Ue as Vn,Os as Vt,Oo as W,He as Wn,Hs as Wt,zs as X,he as Xn,wo as Xt,qs as Y,Ze as Yn,Ss as Yt,Us as Z,b as Zn,co as Zt,io as _,nn as _n,tc as _t,vs as a,Fn as an,qa as at,ic as b,Xt as bn,As as bt,sc as c,wn as cn,Do as ct,Wa as d,Cn as dn,Vs as dt,Ls as en,ue as er,nc as et,ks as f,on as fn,Ms as ft,ao as g,an as gn,Uo as gt,ms as h,Zt as hn,Vo as ht,Wo as i,zn as in,Ja as it,oc as j,lt as jn,yo as jt,Zo as k,it as kn,Cs as kt,To as l,Tn as ln,Xa as lt,hs as m,dn as mn,Ho as mt,Es as n,ac as nn,u as nr,mo as nt,_s as o,Dn as on,js as ot,Ao as p,bn as pn,Xs as pt,$a as q,et as qn,Co as qt,Bs as r,rc as rn,bo as rt,Fs as s,On as sn,za as st,Ks as t,$s as tn,le as tr,cc as tt,Ua as u,En as un,Is as ut,Jo as v,rn as vn,ws as vt,ec as w,wt as wn,Va as wt,oo as x,Rt as xn,ys as xt,Qs as y,Jt as yn,Ps as yt,Ra as z,ze as zn,bs as zt};