const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/webviewWindow-DadQRP9I.js","assets/core-DcH9fClu.js"])))=>i.map(i=>d[i]);
import{r as e}from"./core-DcH9fClu.js";import{a as t,r as n,t as r}from"./taskTags-BlltlGgh.js";var i={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`}]}]};i.version;var a=i.project.id;i.project.slug;function o(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 s(e=new Date().toISOString()){return[{id:i.project.id,slug:i.project.slug,name:i.project.name,description:i.project.description??null,taskPrefix:i.project.taskPrefix,defaultRepositoryId:null,createdAt:e,updatedAt:e,repositories:[]}]}function c(e=new Date().toISOString()){return i.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 l(e=new Date().toISOString()){return i.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(o)}))}var u=new Set([`tauri`,`hosted_web`,`mock`]);function d(e){return typeof e==`string`&&u.has(e)?e:null}function f(){return!!window.__TAURI_INTERNALS__}function p(){return f()?`tauri`:d(window.__ORCHESTRA_HOST_MODE__)||(d(void 0)??`mock`)}function m(){return p()===`hosted_web`}var h=`orchestra.preferences.active-project-id`,g=`orchestra.mock.active-project-id`,_=`orchestra.preferences.active-project-slug`,ee=`orchestra:projects-changed`;function v(e){return window.localStorage.getItem(e)}function y(){return v(h)??v(g)??null}function te(){return v(_)??null}function ne(e,t){let n=y(),r=te();e?(window.localStorage.setItem(h,e),window.localStorage.setItem(g,e)):(window.localStorage.removeItem(h),window.localStorage.removeItem(g));let i=t?.trim()||null;i?window.localStorage.setItem(_,i):window.localStorage.removeItem(_),(n!==e||r!==i)&&window.dispatchEvent(new CustomEvent(ee))}var re=/^[A-Z][A-Z0-9]{1,7}$/,ie=/^([A-Za-z][A-Za-z0-9]*)-([0-9]+)(.*)$/,b=8,ae=2;function oe(e){return e.toUpperCase().replace(/[^A-Z0-9]+/g,``)}function se(e){let t=oe(e);return t||=`PR`,/^[A-Z]/.test(t)||(t=`P${t}`),t.length<ae&&(t=`${t}X`),t.slice(0,b)}function ce(e){let t=e.trim().split(/[^A-Za-z0-9]+/).map(e=>oe(e)).filter(Boolean),n=t.length>1?t.map(e=>e[0]??``).join(``):oe(e).slice(0,3);return n.length<ae&&(n=oe(e)),se(n)}function le(e,t){let n=se(e),r=n,i=2;for(;t.has(r);){let e=String(i);r=se(`${n.slice(0,Math.max(1,b-e.length))}${e}`),i+=1}return r}function ue(e){return(e??``).trim().toUpperCase()}function de(e){let t=ue(e);return t?re.test(t)?null:`Task prefix must start with a letter and contain only A-Z or 0-9.`:`Task prefix is required.`}function fe(e,t=[]){let n=new Set(Array.from(t,e=>ue(e)).filter(Boolean));return le(ce(e),n)}function pe(e,t){return`${ue(e)}-${t}`}function me(e){if(!e)return{hasTask:!1,prefix:``,sequence:1/0,suffix:``};let t=e.match(ie);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 he=null;function ge(e){he=e}function _e(){return he}function x(){return he?.bootstrap.hostKind===`remote_api`?he:null}var ve=`orchestra.mock.projects`,ye=`orchestra.mock.sessions`,be=`orchestra.mock.session-models`,xe=`orchestra.mock.dismissed-sessions`,Se=`orchestra.mock.tasks`,Ce=`orchestra.mock.task-dependencies`,we=`orchestra.mock.task-comment-user-receipts`,Te=`orchestra.mock.mailbox`,Ee=`orchestra.mock.agent-runtimes`,De=`orchestra.mock.agent-queue`,Oe=`orchestra.mock.task-schedules`,ke=`orchestra.mock.domain-events`,Ae=`no-project`;function S(){return!!window.__TAURI_INTERNALS__}function C(){return x()?.client??null}function je(e){return`${e}-${Math.random().toString(36).slice(2,8)}-${Date.now().toString(36)}`}function w(){return new Date().toISOString()}function Me(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`project`}function Ne(){let e=window.localStorage.getItem(ve);return e?JSON.parse(e):null}function T(e){window.localStorage.setItem(ve,JSON.stringify(e)),window.dispatchEvent(new CustomEvent(`orchestra:projects-changed`))}function E(e){let t=window.localStorage.getItem(e);return t?JSON.parse(t):[]}function Pe(e,t){window.localStorage.setItem(e,JSON.stringify(t))}function Fe(e){let t=new Set(E(Se).filter(t=>t.projectId===e).map(e=>e.id)),n=new Set(E(Oe).filter(t=>t.projectId===e).map(e=>e.id));Pe(Se,E(Se).filter(t=>t.projectId!==e)),Pe(Ce,E(Ce).filter(e=>!t.has(e.blockerTaskId)&&!t.has(e.blockedTaskId))),Pe(we,E(we).filter(e=>!t.has(e.taskId))),Pe(Te,E(Te).filter(n=>n.projectId!==e&&!(n.taskId&&t.has(n.taskId)))),Pe(Ee,E(Ee).filter(t=>t.projectId!==e)),Pe(De,E(De).filter(n=>n.projectId!==e&&!(n.sourceTaskId&&t.has(n.sourceTaskId)))),Pe(Oe,E(Oe).filter(t=>t.projectId!==e)),Pe(ke,E(ke).filter(t=>t.projectId!==e).filter(e=>!e.entityId||!t.has(e.entityId)&&!n.has(e.entityId))),window.localStorage.removeItem(`${ye}.${e}`),window.localStorage.removeItem(`${be}.${e}`),window.localStorage.removeItem(`${xe}.${e}`)}function Ie(){return s(w())}function Le(e,t,n){let r=e.name.trim();if(!r)throw Error(`Project name is required.`);let i=de(e.taskPrefix);if(i)throw Error(i);let a=ue(e.taskPrefix);if(t.some(e=>e.id!==n&&ue(e.taskPrefix)===a))throw Error(`Task prefix ${a} is already used by another project.`);return{name:r,taskPrefix:a}}function Re(e){let t=new Set,n=!1,r=e.map(e=>{let r=ue(e.taskPrefix),i=!de(r)&&!t.has(r)?r:fe(e.id===a?`Orchestra`:e.name,t);return t.add(i),e.taskPrefix===i?e:(n=!0,{...e,taskPrefix:i})});return n&&T(r),r}function D(){let e=Ne();if(e)return Re(e);let t=Ie();return T(t),!y()&&t[0]&&ne(t[0].id,t[0].slug),t}function ze(e,t){return t&&e.some(e=>e.id===t)?t:e[0]?.id??null}function Be(){let e=y();return S()||m()?e:ze(D(),e)}function O(){let e=y();return S()||m()?e:ze(D(),e)}function Ve(){if(m()||S())return te();let e=D(),t=ze(e,y());return e.find(e=>e.id===t)?.slug??e[0]?.slug??null}function He(e){if(S()||m())return`/mock/projects/${e??O()??a}`;let t=D(),n=ze(t,e??O()),r=n?t.find(e=>e.id===n)??null:null;return(r?.defaultRepositoryId?r.repositories.find(e=>e.id===r.defaultRepositoryId)??null:r?.repositories[0]??null)?.repositoryPath??`/mock/projects/${r?.slug??n??Ae}`}function Ue(e,t){ne(e,t)}async function We(){let t=C();return t?t.catalog.listProjects():S()?e(`list_projects`):D().map(({repositories:e,...t})=>t)}async function Ge(t){let n=C();if(n)return n.catalog.getProject(t);if(!S()){let e=D().find(e=>e.id===t);if(!e)throw Error(`Project ${t} was not found`);return e}return e(`get_project`,{projectId:t})}function Ke(){window.dispatchEvent(new CustomEvent(`orchestra:projects-changed`))}async function k(e){let t=await e();return Ke(),t}async function qe(t){let n=C();return n?n.projects.listRepositories(t??null):S()?e(`list_repositories`,{projectId:t??null}):t?Ge(t).then(e=>e.repositories):D().flatMap(e=>e.repositories)}async function Je(t){let n=C();if(n)return n.projects.getRepository(t);if(!S()){let e=D().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 Ye(t){let n=C();if(n)return k(()=>n.projects.createProject(t));if(!S()){let e=D(),{name:n,taskPrefix:r}=Le(t,e),i=w(),a={id:je(`project`),slug:Me(n),name:n,description:t.description?.trim()||null,taskPrefix:r,defaultRepositoryId:null,repositories:[],createdAt:i,updatedAt:i};return T([a,...e]),Ue(a.id,a.slug),a}return k(()=>e(`create_project`,{input:t}))}async function Xe(t,n){let r=C();if(r)return k(()=>r.projects.updateProject(t,n));if(!S()){let e=D(),r=e.find(e=>e.id===t);if(!r)throw Error(`Project ${t} was not found`);let{name:i,taskPrefix:a}=Le(n,e,t),o={...r,slug:Me(i),name:i,description:n.description?.trim()||null,taskPrefix:a,updatedAt:w()};return T(e.map(e=>e.id===t?o:e)),o}return k(()=>e(`update_project`,{projectId:t,input:n}))}async function Ze(t){let n=C();if(n)return k(()=>n.projects.deleteProject(t));if(!S()){let e=D(),n=e.find(e=>e.id===t);if(!n)throw Error(`Project ${t} was not found`);let r=y(),i=e.filter(e=>e.id!==t);if(r===t){let e=i[0]??null;Ue(e?.id??null,e?.slug??null)}return Fe(t),T(i),Ke(),n}return k(()=>e(`delete_project`,{projectId:t}))}async function Qe(t,n){let r=C();if(r)return k(()=>r.projects.createRepository(t,n));if(!S()){let e=D(),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:je(`repo`),projectId:t,slug:Me(n.name),name:n.name.trim(),repositoryPath:i===`local_new`?`/mock/projects/${r.slug}/repositories/${Me(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:w(),updatedAt:w()},o={...r,repositories:[a,...r.repositories],defaultRepositoryId:r.defaultRepositoryId??a.id,updatedAt:w()};return T(e.map(e=>e.id===t?o:e)),O()===t&&window.dispatchEvent(new CustomEvent(`orchestra:projects-changed`)),a}return k(()=>e(`create_repository`,{projectId:t,input:n}))}async function $e(t,n){let r=C();if(r)return k(()=>r.projects.updateRepository(t,n));if(!S()){let e=D(),r=null;if(T(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:Me(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:w()},r})}))),!r)throw Error(`Repository ${t} was not found`);return r}return k(()=>e(`update_repository`,{repositoryId:t,input:n}))}async function et(t){let n=C();if(n)return k(()=>n.projects.deleteRepository(t));if(!S()){let e=D(),n=null;if(T(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:w()}})),!n)throw Error(`Repository ${t} was not found`);return n}return k(()=>e(`delete_repository`,{repositoryId:t}))}async function tt(t,n){let r=C();if(r)return k(()=>r.projects.attachRepositoryRemote(t,n));if(!S()){let e=D(),r=null;if(T(e.map(e=>({...e,repositories:e.repositories.map(e=>e.id===t?(r={...e,sourcePath:n.remoteUrl.trim(),sourceKind:`remote`,updatedAt:w()},r):e)}))),!r)throw Error(`Repository ${t} was not found`);return r}return k(()=>e(`attach_repository_remote`,{repositoryId:t,input:n}))}async function nt(t,n){let r=C();if(r)return k(()=>r.projects.setProjectDefaultRepository(t,n));if(!S()){let e=D(),r=null;if(T(e.map(e=>e.id===t?(r={...e,defaultRepositoryId:n,updatedAt:w()},r):e)),!r)throw Error(`Project ${t} was not found`);return r}return k(()=>e(`set_project_default_repository`,{projectId:t,repositoryId:n}))}var A={sessionStream:`orchestra:session-stream`,sessionChange:`orchestra:session-change`,taskChange:`orchestra:task-change`,inboxChange:`orchestra:inbox-change`,notificationIntent:`orchestra:notification-intent`};function rt(e,t){window.dispatchEvent(new CustomEvent(e,{detail:t}))}function j(e){rt(A.sessionStream,e)}function M(e){rt(A.sessionChange,e)}function N(e){rt(A.taskChange,e)}function it(e){rt(A.inboxChange,e)}function at(e){rt(A.notificationIntent,e)}function ot(e){return[e.taskNumber,e.workerName].filter(Boolean).join(` · `)||(e.workerName??`Standalone session`)}function st(e){return e.taskTitle??e.title}function ct(e){return e.activeTaskId??e.taskId??e.taskNumber??null}function lt(e){switch(e){case`active`:return 0;case`closed`:return 1;case`hidden`:return 2;default:return 3}}function ut(e,t){let n=me(e.taskNumber),r=me(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=ct(e),s=ct(t);if(o&&o===s){let n=!!e.activeTaskId;if(n!==!!t.activeTaskId)return n?-1:1;let r=lt(e.listVisibility)-lt(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=st(e).localeCompare(st(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 dt(e){return[...e].sort(ut)}var ft=`orchestra.mock.sessions`,pt=`orchestra.mock.projects`,mt=`no-project`;function ht(e){return`${e}-${Math.random().toString(36).slice(2,8)}-${Date.now().toString(36)}`}function gt(){return new Date().toISOString()}function _t(e,t,n){return{id:ht(`event`),kind:e,message:t,timestamp:gt(),...n}}function vt(){let e=window.localStorage.getItem(pt);return e?JSON.parse(e):s().map(e=>({id:e.id,slug:e.slug}))}function yt(e){let t=vt();return e&&t.some(t=>t.id===e)?e:t[0]?.id??null}function bt(e){return`${ft}.${yt(e??O())??mt}`}function xt(e){let t=window.localStorage.getItem(bt(e));return t?JSON.parse(t):[]}function St(e,t){window.localStorage.setItem(bt(t),JSON.stringify(e))}function Ct(e,t){St(dt([e,...xt(t).filter(t=>t.id!==e.id)]),t)}function wt(e,t){let n=gt();return{id:ht(`session`),title:e,status:`active`,createdAt:n,updatedAt:n,subscribed:!1,listVisibility:`active`,messageability:`messageable`,events:[_t(`system`,`${e} created from Orchestra runtime.`),_t(`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 Tt=`orchestra.mock.project-settings`;function Et(){let e=window.localStorage.getItem(Tt);return e?JSON.parse(e):{}}function Dt(e){window.localStorage.setItem(Tt,JSON.stringify(e))}function Ot(e){let t=Et();return{...t.general??{},...t.projects?.[e]?.runtime??{}}}function kt(e,t){let n=Et(),r=t(Ot(e));return n.projects={...n.projects??{},[e]:{...n.projects?.[e]??{},runtime:r}},Dt(n),r}function At(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function jt(e,t){return e.find(e=>e.id===t)?.name??`Orchestra`}function Mt(e,t){let n=e.taskNumber?e.taskTitle?`${e.taskNumber} · ${e.taskTitle}`:e.taskNumber:null,r=At(e.body),i=[t,e.senderLabel,n].filter(Boolean).join(` · `);return r?`${i}\n${r}`:i}function Nt(e,t,n){return[`${t} · ${e.number} · ${e.title}`,(e.activeLaneAssignment?.completionNotes?At(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 Pt(e,t,n){let r=[t,e].filter(Boolean).join(` · `),i=At(n);return i?`${r}\n${i}`:r}function Ft(e,t){return{id:`notification-mailbox-${e.deliveryId}`,eventType:`mailbox.message_received`,title:`Orchestra — New message`,body:Mt(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 It(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:Nt(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 Lt({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:Pt(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 Rt(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 zt(e){let t=atob(e);return Uint8Array.from(t,e=>e.charCodeAt(0))}function Bt(e,t){return new Blob([zt(e)],{type:t||`application/octet-stream`})}var Vt=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`]),Ht=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`]),Ut=`.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(`,`),Wt=new Set([`dockerfile`,`makefile`,`justfile`,`procfile`,`gemfile`,`rakefile`,`brewfile`,`podfile`,`readme`,`license`]),Gt=new Set([`text/markdown`,`text/x-markdown`,`application/markdown`,`application/x-markdown`]),Kt=[`.md`,`.markdown`,`.mdown`,`.mkd`,`.mdx`],qt=[`.wav`,`.mp3`,`.m4a`,`.aac`,`.ogg`,`.flac`],Jt=[`.mp4`,`.mov`,`.m4v`,`.webm`,`.ogv`,`.avi`,`.mkv`],Yt=[`.zip`,`.tar`,`.tgz`,`.gz`,`.bz2`,`.xz`,`.7z`,`.rar`];function Xt(e){return typeof e.base64Data==`string`}function Zt(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t)}async function Qt(e){if(Xt(e))return e;let t=await e.file.arrayBuffer();return{fileName:e.fileName,mediaType:e.mediaType,base64Data:Zt(new Uint8Array(t)),caption:e.caption??null}}function $t(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 en(e){return e.split(`;`)[0]?.trim().toLowerCase()??``}function tn(e){return e?.split(`/`).pop()?.trim().toLowerCase()??``}function nn(e){let t=en(e);return t.startsWith(`text/`)||Ht.has(t)||t.endsWith(`+json`)||t.endsWith(`+xml`)||t.endsWith(`+yaml`)}function rn(e){let t=tn(e);return Wt.has(t)||Ut.some(e=>t.endsWith(e))}function an(e,t){let n=en(e),r=tn(t);return Gt.has(n)||Kt.some(e=>r.endsWith(e))?`markdown`:n.startsWith(`image/`)?`image`:n.startsWith(`video/`)||Jt.some(e=>r.endsWith(e))?`video`:n.startsWith(`audio/`)||qt.some(e=>r.endsWith(e))?`audio`:Vt.has(n)||Yt.some(e=>r.endsWith(e))?`archive`:nn(n)||rn(r)?`text`:`binary`}function on(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 sn(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 cn={field:`updatedAt`,direction:`desc`},ln={P0:0,P1:1,P2:2,P3:3,P4:4},un={draft:0,ready:1,in_progress:2,blocked:3,in_review:4,completed:5,canceled:6};function dn(e){return e.trim().toLowerCase()}function fn(e){return pn(e).join(`\0`)}function pn(e){return n(Array.isArray(e.tags)?e.tags:[])}function mn(e,t){return e.localeCompare(t,void 0,{sensitivity:`base`})}function hn(e,t){return e-t}function gn(e,t){return hn(Date.parse(e),Date.parse(t))}function _n(e,t,n){let r=fn(e),i=fn(t),a=r.length===0;if(a!==(i.length===0))return a?1:-1;let o=n===`asc`?1:-1;return mn(r,i)*o}function vn(e,t,n){switch(n.field){case`createdAt`:return gn(e.createdAt,t.createdAt);case`priority`:return hn(ln[e.priority]??2**53-1,ln[t.priority]??2**53-1);case`title`:return mn(e.title,t.title);case`status`:return hn(un[e.status]??2**53-1,un[t.status]??2**53-1);default:return gn(e.updatedAt,t.updatedAt)}}function yn(e,t,n){let r=n.direction===`asc`?1:-1,i=n.field===`tags`?_n(e,t,n.direction):vn(e,t,n)*r;if(i!==0)return i;let a=gn(e.updatedAt,t.updatedAt)*-1;if(a!==0)return a;let o=gn(e.createdAt,t.createdAt)*-1;if(o!==0)return o;let s=mn(e.number,t.number);return s===0?mn(e.id,t.id):s}function bn(e,t){let r=n((t?.tags??[]).map(dn));if(r.length===0)return e;let i=t?.tagMatch===`all`?`all`:`any`;return e.filter(e=>{let t=pn(e);return i===`all`?r.every(e=>t.includes(e)):r.some(e=>t.includes(e))})}function xn(e,t){let n=t??cn;return e.slice().sort((e,t)=>yn(e,t,n))}function Sn(e,t){return xn(bn(e,t),t?.sort??cn)}function Cn(e){return e.status===`in_review`&&e.assigneeType===`user`&&!!e.currentLaneId}function wn(e){let t=e.activeLaneAssignment;if(!t)return null;if(Cn(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 Tn(e){return wn(e)??e.activeLaneAssignment?.status??null}function En(e){return{kind:`session.change`,...e}}function Dn(e){return{kind:`session.stream`,...e}}function On(e){return{kind:`task.change`,...e}}function kn(e){return{kind:`inbox.change`,...e}}function An(e){return{kind:`notification.intent`,...e}}async function jn(e,t){let n=e=>{e instanceof CustomEvent&&t(e.detail)};return window.addEventListener(e,n),()=>{window.removeEventListener(e,n)}}function Mn(e){return jn(A.sessionStream,e)}function Nn(e){return jn(A.sessionChange,e)}function Pn(e){return jn(A.taskChange,e)}function Fn(e){return jn(A.inboxChange,e)}function In(e){return jn(A.notificationIntent,e)}async function Ln(e){let[t,n,r,i,a]=await Promise.all([Mn(t=>e(Dn(t))),Nn(t=>e(En(t))),Pn(t=>e(On(t))),Fn(t=>e(kn(t))),In(t=>e(An(t)))]);return()=>{t(),n(),r(),i(),a()}}var Rn=`modulepreload`,zn=function(e){return`/`+e},Bn={},Vn=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=zn(t,n),t in Bn)return;Bn[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`:Rn,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)})},Hn=`orchestra.mock.logs`,Un=`orchestra.mock.session-diagnostic-logs`,Wn=`orchestra.mock.sessions`,Gn=`orchestra.mock.session-models`,Kn=`orchestra.mock.workflows`,qn=`orchestra.mock.tasks`,Jn=`orchestra.mock.task-attachment-bytes`,Yn=`orchestra.mock.file-contents`,Xn=`orchestra.mock.task-dependencies`,Zn=`orchestra.mock.task-comment-receipts`,Qn=`orchestra.mock.task-comment-user-receipts`,$n=`orchestra.mock.mailbox`,er=`orchestra.mock.agents`,tr=`orchestra.mock.agent-runtimes`,nr=`orchestra.mock.agent-queue`,rr=`orchestra.mock.roles`,ir=`orchestra.mock.role-queue`,ar=`orchestra.mock.role-instances`,or=`orchestra.mock.bridge-diagnostics`,sr=`orchestra.mock.active-session-runs`,cr=`orchestra.mock.dismissed-sessions`,lr=`orchestra.mock.harness-settings`,ur=`orchestra.mock.pi-setup`,dr=`orchestra.mock.pi-oauth-flow`,fr=`orchestra.mock.pi-models-json`,pr=`orchestra.mock.task-schedules`,mr=`orchestra.mock.domain-events`,hr=`no-project`,gr=`Great work finishing the next slice, keep going in the next todo until you have finished it!`,_r=`Great work finishing this next slice, create todos for the remaining work then keep working until you finish the next todos`;function vr(){let e=window.__ORCHESTRA_WINDOW_KIND__;return typeof e==`string`?e:null}function yr(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 br(e,t){let n=yr(e,t);if(n)throw Error(n.message)}function xr(){return R(lr)??{}}function Sr(){return R(`orchestra.mock.projects`)??s()}function Cr(){return Sr().map(e=>({id:e.id,slug:e.slug}))}function wr(e){let t=Cr();return e&&t.some(t=>t.id===e)?e:t[0]?.id??null}function Tr(e){return Cr().some(t=>t.id===e)}function Er(e,t=`task`){let n=wr(e);if(n)return n;throw Error(`Create a project before creating a ${t}.`)}function Dr(){return vr()===`logs`||new URLSearchParams(window.location.search).get(`view`)===`logs`}function Or(){return vr()===`agent-terminal`||new URLSearchParams(window.location.search).get(`view`)===`agent-terminal`}function kr(){let e=window.__ORCHESTRA_AGENT_TERMINAL_SESSION_ID__;return typeof e==`string`&&e.length>0?e:new URLSearchParams(window.location.search).get(`sessionId`)}function Ar(e){return`${Wn}.${wr(e??O())??hr}`}function jr(e){return`${Gn}.${wr(e??O())??hr}`}function Mr(e){return`${cr}.${wr(e??O())??hr}`}var Nr=[{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 P(e){return`${e}-${Math.random().toString(36).slice(2,8)}-${Date.now().toString(36)}`}function F(){return new Date().toISOString()}function Pr(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`workflow`}function Fr(e,t){switch(e){case`debug`:case`info`:case`warn`:case`error`:return e;default:return t===`sessions.rpc.event`?`debug`:`info`}}function Ir(e){let t=Fr(e.level,e.target);return t===e.level?e:{...e,level:t}}function Lr(e,t,n){return{id:P(`log`),level:Fr(e,t),target:t,message:n,timestamp:F()}}function I(e,t,n){return{id:P(`event`),kind:e,message:t,timestamp:F(),...n}}function Rr(){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 L(){return R(ur)??{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:Nr,issues:[],warnings:[],importState:{canImportLegacy:!1,importedAt:null,dismissedAt:null},packageDiagnostics:Rr()}}function zr(e){z(ur,e)}function Br(){return R(dr)}function Vr(e){if(!e){window.localStorage.removeItem(dr);return}z(dr,e)}function Hr(e){window.dispatchEvent(new CustomEvent(`orchestra:pi-setup-change`,{detail:e}))}function Ur(e){window.dispatchEvent(new CustomEvent(`orchestra:pi-oauth-flow-change`,{detail:e}))}function Wr(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 Gr(e,t){let n=L(),r={...n,status:`ready`,issues:[],warnings:[],availableProviders:n.availableProviders.map(n=>n.id===e?{...n,connected:!0,usingOAuth:t}:n)};return zr(r),r}function Kr(e){Ur({...e,status:`succeeded`,prompt:null,error:null,latestProgressMessage:`Connected.`,finishedAt:F()}),Gr(e.providerId,!0),Vr(null),Hr({reason:`pi.oauth.succeeded`,providerId:e.providerId})}function qr(){return window.localStorage.getItem(fr)??`{
  "providers": {}
}
`}function Jr(e){window.localStorage.setItem(fr,e)}function R(e){let t=window.localStorage.getItem(e);return t?JSON.parse(t):null}function Yr(){return R(Qn)??[]}function Xr(e){z(Qn,e)}function Zr(){return R(Zn)??[]}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 z(e,t){window.localStorage.setItem(e,JSON.stringify(t))}function ti(){return R(Jn)??{}}function ni(e){z(Jn,e)}function ri(){return R($n)??[]}function ii(e){z($n,e)}function B(e,t,n){return{sessionId:e,runId:t,event:n,receivedAt:F()}}function ai(){return[Lr(`info`,`app.bootstrap`,`Frontend scaffold initialized`),Lr(`info`,`session.mock`,`Using browser-backed session fallback until Tauri backend is running`)]}function oi(){let e=F();return[{id:P(`session`),title:`Session-first spike`,status:`idle`,createdAt:e,updatedAt:e,subscribed:!1,events:[I(`system`,`Mock session created in browser fallback mode.`),I(`assistant`,`Ready when you are. Create a session, resume it, or send me a message.`)]}]}function si(){return l(F())}function ci(){let e=R(Hn);if(e){let t=e.map(Ir);return t.some((t,n)=>t.level!==e[n]?.level)&&z(Hn,t),t}let t=ai();return z(Hn,t),t}function li(){return[{id:P(`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:F(),detailsText:JSON.stringify({cwd:null,reason:`missing_project_root`},null,2)},{id:P(`session-diagnostic`),sessionId:`session-2`,runId:`run-2`,level:`warn`,code:`session.context.degraded`,message:`Mock session continued with a reduced context snapshot.`,timestamp:F(),detailsText:JSON.stringify({mode:`fallback`,filesSkipped:3},null,2)}]}function ui(){let e=R(Un);if(e)return e;let t=li();return z(Un,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 V(e){let t=R(Ar(e));if(t)return t;let n=wr(e??O());if(e&&e!==n)return[];let r=oi();return z(Ar(n),r),r}function mi(){let e=R(or);if(e)return e;let t=F(),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 z(or,n),n}function hi(){return R(er)??[]}function H(){return R(tr)??[]}function U(e){z(tr,e)}function gi(){return R(nr)??[]}function _i(e){z(nr,e)}function vi(){return R(rr)??[]}function yi(){return R(ir)??[]}function bi(e){z(ir,e)}function xi(){return R(ar)??[]}function Si(e){z(ar,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 W(){let e=R(Kn);if(e){let t=Ci(e);return JSON.stringify(t)!==JSON.stringify(e)&&z(Kn,t),t}let t=si();return z(Kn,t),t}function wi(e){z(Kn,e)}function Ti(){return R(jr())??{}}function Ei(e){z(jr(),e)}function Di(){let e=R(sr)??{},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)&&z(sr,t),t}function Oi(e){z(sr,e)}function ki(e,t){return Di()[e]?.includes(t)??!1}function Ai(e){let t=Ti();return t[e]||(t[e]=Nr[0],Ei(t)),t[e]}function G(e,t,n){let r=ci();z(Hn,[Lr(e,t,n),...r].slice(0,200))}function ji(e){return new Set(R(Mr(e))??[])}function Mi(e,t){z(Mr(t),Array.from(new Set(e)).sort())}function Ni(e,t){z(Ar(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=Sr(),i=e.projectId??O()??null;return Lt({sessionId:e.id,runId:t,sessionTitle:e.title,projectId:i,projectLabel:jt(r,i),reply:n,occurredAt:F()})}function Ri(e,t){let n=e?.sessionId??null,r=t?.sessionId??null;!n||n===r||(K(n,e=>Fi(e)),M({sessionIds:[n],reason:`task.assignment.cleared`}))}function zi(e,t){let n=H().find(e=>e.agentId===t&&e.projectId===a)??null,r=typeof n?.mainSessionId==`string`?n.mainSessionId:null,i=(r?V().find(e=>e.id===r)??null:null)??wt(`${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),Ct(i),U(H().map(e=>e.agentId===t&&e.projectId===a?{...e,mainSessionId:i.id,runtimeCwd:typeof e.runtimeCwd==`string`&&e.runtimeCwd?e.runtimeCwd:He(a),status:e.currentQueueEntryId?`running`:`idle`,updatedAt:F()}:e)),i}function K(e,t){let n=V().map(n=>n.id===e?t(n):n);return Ni(n),n.find(t=>t.id===e)??null}function Bi(e){return dt(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:Nr}}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=X().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=F(),t=W()[0],n=t?.lanes[0],r=t?.lanes[1],i=P(`task`),o=P(`task`),s=P(`task`),c=P(`session`),l=[{id:i,projectId:a,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:o,projectId:a,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:P(`task-comment`),taskId:o,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:P(`lane-run`),taskId:o,laneId:r.id,sessionId:c,result:`needs_user`,notes:`Waiting on task persistence APIs.`,startedAt:e,completedAt:null}]:[],laneSummaries:[]},{id:s,projectId:a,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:P(`task-dependency`),blockerTaskId:o,blockedTaskId:s,blocker:Q(l[1]),blocked:Q(l[2]),createdAt:e}];return Ki(u),Oa(l,u)}function q(){return R(Xn)??[]}function Ki(e){z(Xn,e)}function qi(){return R(mr)??[]}function Ji(e){z(mr,e)}function J(e,t,n,r,i){let a=qi(),o={sequence:((a.length>0?a[a.length-1]?.sequence:0)??0)+1,id:P(`domain-event`),projectId:i??null,topic:e,entityType:t,entityId:n,payload:r,createdAt:F()};return Ji([...a,o]),o}function Yi(){return R(pr)??[]}function Xi(e){z(pr,e)}function Zi(e){return n(e??[])}function Qi(e){let n=Zi(e),i=[];return n.length>20&&i.push({path:`tags`,message:r}),n.forEach((e,n)=>{let r=t(e);r&&i.push({path:`tags[${n}]`,message:r})}),{normalized:n,errors:i}}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=F();return{id:P(`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=>Q(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=F(),i=$i(e.task),a=e.trigger.type===`time`?t?.nextFireAt??oa(e.trigger,r):null,o=t?.projectId??Er(n??O(),`task schedule`);return{id:t?.id??P(`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=wr(e??O()),n=Yi(),r=qi(),i=X(),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=F(),e.lastError=t.error;else{let n=s(e);t.status=`materialized`,t.taskId=n.id,t.updatedAt=F(),e.lastMaterializedTaskId=n.id,e.lastError=null,J(`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),G(`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=F(),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,J(`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),G(`info`,`task.schedule.materialized`,`Materialized task ${t.id} from schedule ${e.id}`)}r.updatedAt=F(),e.lastFiredAt=t.createdAt,e.occurrences=[...e.occurrences,r],e.updatedAt=F(),e.oneShot&&(e.enabled=!1),a=!0,n.add(t.id)}}return o&&Z(i),a&&Xi(n),{tasks:o?X():i,schedules:a?Yi():n,changed:o||a}}function ha(e){return[...new Set(e)]}function ga(e){let t=e.workflowId?W().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 Y(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?W().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=F()){let i=e.map(e=>Y(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=F()){let r=e.map(e=>Y(e)),i=gi(),a=H(),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),U(a),bi(o),Si(s)),{tasks:r,pausedTaskIds:c,pausedSessionIds:[...l]}}function Ea(e,t,n=F()){let r=e.map(e=>Y(e)),i=gi(),a=H(),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),U(a),bi(o),Si(s);for(let e of l)K(e,e=>Fi(e)),M({sessionIds:[e],reason:`task.blocked.runtime_cleared`})}return{tasks:r,cleanedTaskIds:c}}function X(){let e=R(qn),t=q();if(e)return Oa(e,t);if(!Tr(a))return z(qn,[]),[];let n=Gi().map(e=>Y(e));return z(qn,n),n}function Z(e){z(qn,Oa(e.map(e=>Y(e)),q()))}function Da(e){return e.some(e=>!e.archived&&![`completed`,`canceled`].includes(e.status))}function Q(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:pn(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(Q(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=>Q(e)),s=t.filter(t=>t.blockedTaskId===e.id).map(t=>({...t,blocker:Q(r.get(t.blockerTaskId)??e),blocked:Q(r.get(t.blockedTaskId)??e)})),c=t.filter(t=>t.blockerTaskId===e.id).map(t=>({...t,blocker:Q(r.get(t.blockerTaskId)??e),blocked:Q(r.get(t.blockedTaskId)??e)})),l=s.some(e=>xa(e,e.blocker))||Da(o);return{...e,parent:e.parentTaskId&&r.get(e.parentTaskId)?Q(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=me(e);return Number.isFinite(t.sequence)?t.sequence:0}function ja(e,t,n){let r=F(),i=X(),a=e.workflowId?W().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??Er(n??O()),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??P(`task`),projectId:c,number:t?.number??pe(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?X().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=X();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=Pr(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=F(),r=e.lanes.map((e,t)=>({id:e.id?.trim()||P(`lane`),key:Pr(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??P(`workflow`),slug:t?.slug??Pr(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(t,n,r){let i=x()?.client;if(i)return i.app.reportError(t,n,r);let a=Fa(n,r);if(console.error(`[${t}] ${a}`,n),!f())return G(`error`,t,a),a;try{await e(`report_client_error`,{target:t,message:a})}catch(e){console.error(`[report_client_error.failed] ${t}`,e)}return a}async function La(){if(!f()){let e=L();return{appName:`Orchestra`,environment:`browser`,backendStatus:`mock`,versionDisplay:`0.1.0-mock0000`,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 f()?e(`get_logs`):ci()}async function za(){return f()?e(`list_log_viewer_sources`):pi()}async function Ba(t){if(!f()){let e=pi().find(e=>e.id===t.sourceId);if(!e)throw Error(`Unknown log viewer source ${t.sourceId}`);let n=t.minimumLevel??`info`,r={debug:10,info:20,warn:30,error:40},i=(t.textFilter??``).trim().toLowerCase(),a=ci().map(di),o=ui(),s=(t.sourceId===`runtime`?a:t.sourceId===`session-diagnostics`?o.map(e=>fi(`session-diagnostics`,e)):o.filter(e=>`session-diagnostic:${e.sessionId}`===t.sourceId).map(e=>fi(t.sourceId,e))).filter(e=>r[e.level]<r[n]?!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,t.offset??0),l=Math.min(Math.max(1,t.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:t.sourceId,minimumLevel:t.minimumLevel??null,textFilter:t.textFilter??null,offset:t.offset??null,limit:t.limit??null})}async function Va(t,n=!1){if(!f()){let e=pi().find(e=>e.id===t);if(!e?.path)throw Error(`No path is available for ${t}`);return n&&t.startsWith(`session-diagnostic:`)?`/mock/.orchestra/runtime/session-diagnostics`:e.path}return e(`open_log_viewer_source_path`,{sourceId:t,openDirectory:n})}async function Ha(){return f()?e(`get_bridge_diagnostics`):mi()}async function Ua(){if(!f()){let e=mi();return z(or,{...e,recentCleanupEvents:[{id:`bridge-cleanup-${Date.now()}`,instanceId:e.instance.instanceId,pid:e.instance.ownerPid,action:`cleanup_requested`,reason:`mock_cleanup`,success:!0,timestamp:F()},...e.recentCleanupEvents].slice(0,20)}),mi().recentCleanupEvents}return e(`cleanup_stale_bridge_instances`)}async function Wa(){if(!f()){z(Hn,[]);return}await e(`clear_logs`)}async function Ga(t=!1){if(!f())throw Error(`Log bundle export is only available in the desktop app.`);return e(`export_logs_bundle`,{includeRelatedSessionSnapshot:t})}async function Ka(){let t=new URL(window.location.href);if(t.searchParams.set(`view`,`logs`),!f()){window.open(t.toString(),`orchestra-logs`,`popup=yes,width=980,height=760,resizable=yes,scrollbars=yes`);return}await e(`open_logs_window`)}async function qa(){if(!f())return Dr();let{getCurrentWebviewWindow:e}=await Vn(async()=>{let{getCurrentWebviewWindow:e}=await import(`./webviewWindow-DadQRP9I.js`);return{getCurrentWebviewWindow:e}},__vite__mapDeps([0,1]));return e().label===`logs`}async function Ja(){if(!f())return Or();let{getCurrentWebviewWindow:e}=await Vn(async()=>{let{getCurrentWebviewWindow:e}=await import(`./webviewWindow-DadQRP9I.js`);return{getCurrentWebviewWindow:e}},__vite__mapDeps([0,1]));return e().label.startsWith(`agent-terminal-`)}async function Ya(){if(!f())return kr();let{getCurrentWebviewWindow:e}=await Vn(async()=>{let{getCurrentWebviewWindow:e}=await import(`./webviewWindow-DadQRP9I.js`);return{getCurrentWebviewWindow:e}},__vite__mapDeps([0,1])),t=e().label;return t.startsWith(`agent-terminal-`)?t.slice(15):null}async function Xa(t){if(!f()){let e=ji(t),n=Bi(V(t).filter(t=>!e.has(t.id)));return G(`info`,`sessions.list`,`Listed ${n.length} sessions`),n}return e(`list_sessions`,{projectId:t??null})}async function Za(t){if(!f()){br(`get`,t);let e=V().find(e=>e.id===t)??null;if(!e)throw Error(`Unable to find session ${t}`);let n=ji();return G(`info`,`sessions.record`,`Loaded session record ${t}`),{...e,listVisibility:n.has(t)?`hidden`:e.listVisibility??(e.status===`closed`?`closed`:`active`),messageability:e.messageability??(e.status===`closed`?`closed`:`messageable`)}}return e(`get_session_record`,{sessionId:t})}async function Qa(t){if(!f()){let e=V().find(e=>e.id===t)??null;if(!e)throw Error(`Unable to find session ${t}`);let n=xr(),r=[...new Set((n.extraExtensions??[]).map(e=>e.trim()).filter(Boolean))],i=`extensions/orchestra-tools.ts`,o={enabled:n.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`},s={enabled:n.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:t,source:e.subscribed?`live_runtime`:`expected_config`,runtimeActive:e.subscribed,subscribed:e.subscribed,extensionLoadMode:`explicit_only`,automaticExtensionsDisabled:!0,orchestraExtensionPath:i,bundledSubagents:o,bundledProcesses:s,extraExtensions:r,blockedExtraExtensions:[],loadedExtensions:[i,...o.enabled?[o.extensionPath]:[],...s.enabled?[s.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/${t}.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:t,projectId:a,roleId:null,agentId:null,workflowId:null,workflowLaneId:null,contextSource:`project_session`},contextHash:`mock-skill-context-${t}`,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:t})}async function $a(t){if(!f()){br(`getStats`,t);let e=V().find(e=>e.id===t)??null;if(!e)throw Error(`Unable to find session ${t}`);let n=e.events.map(e=>e.message).join(`
`),r=Math.max(0,Math.round(n.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:t,sessionFile:`/mock/orchestra/sessions/${t}.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:t})}function eo(e,t){let n=Ti();if(n[e]){n[t]=n[e],Ei(n);return}Ai(t)}function to(e){return{...wt(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),K(e,e=>({...e,status:`closed`,subscribed:!1,listVisibility:`hidden`,messageability:`closed`,updatedAt:t,events:[...e.events,I(`system`,`Session replaced by a newer worker session.`)]}))}function ro(e,t){let n=V(),r=n.find(t=>t.id===e);if(!r)throw Error(`Unable to find session ${e}`);let i=F(),o=wr(t??O())??null,s=X(),c=s.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),Ct(n);let a={...t,id:P(`task-assignment`),sessionId:n.id,startedAt:i,completedAt:null,createdAt:i,updatedAt:i};return Z(s.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:P(`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&&U(H().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),G(`info`,`sessions.create_contextual`,`Rotated worker session ${e} to ${n.id}`),M({sessionIds:[e,n.id],reason:`sessions.create_contextual`}),N({taskIds:[c.id],reason:`task.assignment.session_rotated`}),n}let l=H().find(t=>t.mainSessionId===e)??null;if(l){let t=to(r.title);return eo(e,t.id),Ct(t),U(H().map(n=>n.mainSessionId===e?{...n,mainSessionId:t.id,updatedAt:i}:n)),no(e,i,typeof l.projectId==`string`?l.projectId:o),G(`info`,`sessions.create_contextual`,`Rotated agent main session ${e} to ${t.id}`),M({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),Ct(t),Si(xi().map(e=>e.id===u.id?{...e,sessionId:t.id,updatedAt:i}:e)),no(e,i,o),G(`info`,`sessions.create_contextual`,`Rotated role session ${e} to ${t.id}`),M({sessionIds:[e,t.id],reason:`sessions.create_contextual`}),t}let d={id:P(`session`),title:`New session ${new Date().toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}`,status:`active`,createdAt:i,updatedAt:i,subscribed:!0,events:[I(`system`,`Session created from the Orchestra Sessions page.`),I(`assistant`,`Session is active. Send a message to begin the interaction loop.`)]};return Ai(d.id),Ni(Bi([d,...n])),G(`info`,`sessions.create_contextual`,`Created generic successor session ${d.id} in ${t??a}`),M({sessionIds:[d.id],reason:`sessions.create_contextual`}),d}async function io(t,n,r){if(!f()){let e=F(),n={id:P(`session`),title:t?.trim()||`New session ${new Date().toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}`,status:`active`,createdAt:e,updatedAt:e,subscribed:!0,events:[I(`system`,`Session created from the Orchestra Sessions page.`),I(`assistant`,`Session is active. Send a message to begin the interaction loop.`)]};if(Ai(n.id),Ni(Bi([n,...V()])),r){let t=a,i=H();U(i.some(e=>e.agentId===r&&e.projectId===t)?i.map(i=>i.agentId===r&&i.projectId===t?{...i,mainSessionId:n.id,updatedAt:e}:i):[...i,{projectId:t,agentId:r,status:`idle`,mainSessionId:n.id,runtimeCwd:He(t),currentQueueEntryId:null,lastDispatchAt:null,lastError:null,terminalAttached:!1,createdAt:e,updatedAt:e}])}return G(`info`,`sessions.create`,`Created session ${n.id}`),M({sessionIds:[n.id],reason:`sessions.create`}),n}return e(`create_session`,{title:t,projectSlug:n,agentId:r})}async function ao(t,n,r){return f()?e(`create_contextual_session`,{sessionId:t,projectSlug:n,agentId:r}):ro(t,n)}async function oo(t){if(!f()){let e=ji();e.add(t),Mi(e),G(`info`,`sessions.dismiss`,`Dismissed session ${t}`);return}await e(`delete_session`,{sessionId:t})}async function so(t){if(!f()){br(`resume`,t);let e=ji();e.delete(t),Mi(e);let n=K(t,e=>({...e,status:`active`,subscribed:!0,listVisibility:`active`,messageability:`messageable`,updatedAt:F(),events:[...e.events,I(`system`,`Session resumed from the Sessions page.`)]}));if(!n)throw Error(`Unable to find session ${t}`);return G(`info`,`sessions.resume`,`Resumed session ${n.id}`),n}return e(`resume_session`,{sessionId:t})}async function co(t){if(!f()){br(`subscribe`,t);let e=K(t,e=>({...e,subscribed:!0}));if(!e)throw Error(`Unable to find session ${t}`);return G(`info`,`sessions.subscribe`,`Subscribed to session ${e.id}`),e}return e(`subscribe_session`,{sessionId:t})}async function lo(t){if(!f()){let e=K(t,e=>({...e,subscribed:!1}));if(!e)throw Error(`Unable to find session ${t}`);return G(`info`,`sessions.unsubscribe`,`Unsubscribed from session ${e.id}`),e}return e(`unsubscribe_session`,{sessionId:t})}async function uo(t,n){let r=x()?.client;if(r)return r.sessions.stopRuntime(t,n);if(!f()){let e=Di();delete e[t],Oi(e);let r=K(t,e=>({...e,status:`paused`,updatedAt:F(),events:[...e.events,I(`system`,n?.trim()?`Session run stopped by operator. ${n.trim()}`:`Session run stopped by operator.`)]}));if(!r)throw Error(`Unable to find session ${t}`);return G(`info`,`sessions.stop`,`Stopped session runtime ${t}`),M({sessionIds:[t],reason:`sessions.stop`}),r}return e(`stop_session_runtime`,{sessionId:t,notes:n})}async function fo(){let t=x()?.client;if(t)try{return await t.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 f()?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 f()?e(`get_pi_runtime_diagnostics`):(await La()).piRuntimeDiagnostics}async function mo(t,n){return f()?e(`import_legacy_pi_configuration`,{importAuth:t,importModels:n}):{imported:[t?`auth.json`:null,n?`models.json`:null].filter(e=>!!e),skipped:[],diagnostics:await po()}}async function ho(){return f()?e(`get_pi_setup_state`):L()}async function go(){return f()?e(`get_pi_models_json`):qr()}async function _o(t){return f()?e(`save_pi_models_json`,{content:t}):(Jr(t),L())}async function vo(t,n){if(!f()){let e=L(),n={...e,status:`ready`,issues:[],warnings:[],availableProviders:e.availableProviders.map(e=>e.id===t?{...e,connected:!0,usingOAuth:!1}:e)};return zr(n),n}return e(`set_pi_provider_api_key`,{providerId:t,apiKey:n})}async function yo(t){if(!f()){let e=L(),n={...e,availableProviders:e.availableProviders.map(e=>e.id===t?{...e,connected:!1,usingOAuth:!1}:e)};zr(n);let r=Br();return r?.providerId===t&&r.finishedAt&&(Vr(null),Ur(null)),n}return e(`remove_pi_provider_credential`,{providerId:t})}async function bo(t=!1){if(!f()){let e=L(),t={...e,status:`ready`,importState:{...e.importState,canImportLegacy:!1,importedAt:F()}};return zr(t),t}return e(`import_pi_legacy_config`,{replaceExisting:t})}async function xo(){if(!f()){let e=L(),t={...e,importState:{...e.importState,dismissedAt:F()}};return zr(t),t}return e(`dismiss_pi_legacy_import`)}async function So(){return f()?e(`get_pi_oauth_flow_state`):Br()??null}async function Co(t,n){if(!f()){let e=L().availableProviders.find(e=>e.id===t);if(!e)throw Error(`Unknown Pi provider ${t}`);let r=n?(e.oauthMethods??[]).find(e=>e.id===n)??null:Wr(t,e.oauthMethods);if(!r)throw Error(`Provider ${t} does not support OAuth method ${n}`);let i=r.kind===`device_code`?{providerId:t,providerName:e.name,methodId:r.id,methodKind:r.kind,usesCallbackServer:e.usesCallbackServer,status:t===`github-copilot`?`awaiting_input`:`running`,authStep:t===`github-copilot`?null:{kind:`device_code`,url:`https://example.com/device/${t}`,linkLabel:`Open verification page`,instructions:`Enter the device code on the verification page.`,userCode:`ABCD-EFGH`},browserOpened:t!==`github-copilot`,browserOpenError:null,prompt:t===`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:F(),finishedAt:null}:{providerId:t,providerName:e.name,methodId:r.id,methodKind:r.kind,usesCallbackServer:e.usesCallbackServer,status:`running`,authStep:{kind:`browser`,url:`https://example.com/oauth/${t}`,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:F(),finishedAt:null};return Vr(i),Ur(i),i.methodKind===`browser`&&window.setTimeout(()=>{let e=Br();e&&e.providerId===i.providerId&&e.startedAt===i.startedAt&&Kr(e)},200),i}return e(`start_pi_oauth_flow`,{providerId:t,methodId:n??null})}async function wo(t){if(!f()){let e=Br();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 Vr(t),Ur(t),t}return e(`submit_pi_oauth_flow_input`,{value:t})}async function To(){if(!f()){let e=Br();if(!e)return null;let t={...e,status:`cancelled`,prompt:null,error:`Login cancelled`,finishedAt:F()};return Vr(t),Ur(t),t}return e(`cancel_pi_oauth_flow`)}async function Eo(){if(!f()){let e=Br();if(!e)return null;if(!e.finishedAt)throw Error(`Active Pi OAuth flows must be cancelled before they can be dismissed.`);return Vr(null),Ur(null),null}return e(`dismiss_pi_oauth_flow`)}async function Do(){let t=x()?.client;return t?t.settings.listPiModels():f()?e(`list_pi_models`):Nr}async function Oo(t){return f()?e(`get_session_model_state`,{sessionId:t}):(br(`getModelState`,t),Hi(t))}async function ko(t,n,r){if(!f()){let e=Nr.find(e=>e.provider===n&&e.id===r);if(!e)throw Error(`Unknown model ${n}/${r}`);let i=Ti();return i[t]=e,Ei(i),G(`info`,`sessions.model`,`Changed session ${t} to ${n}/${r}`),Hi(t)}return e(`set_session_model`,{sessionId:t,provider:n,modelId:r})}async function Ao(t,n){let r=F();if(!f()){let e=K(t,e=>({...e,updatedAt:r,controlOperation:{kind:`compact`,trigger:`manual`,status:`succeeded`,startedAt:r,finishedAt:r,message:n?.trim()?`Session compacted. ${n.trim()}`:`Session compacted.`},events:[...e.events,I(`system`,n?.trim()?`Session compacted. ${n.trim()}`:`Session compacted.`,{id:`compact-${t}-${r}`})]}));if(!e)throw Error(`Unable to find session ${t}`);return G(`info`,`sessions.compact`,`Compacted session ${t}`),M({sessionIds:[t],reason:`sessions.compact`}),e}return e(`compact_session`,{sessionId:t,customInstructions:n??null})}async function jo(t){let n=F();if(!f()){let e=K(t,e=>({...e,updatedAt:n,controlOperation:{kind:`reload`,trigger:`manual`,status:`succeeded`,startedAt:n,finishedAt:n,message:`Session reloaded.`},events:[...e.events,I(`system`,`Session reloaded.`,{id:`reload-${t}-${n}`})]}));if(!e)throw Error(`Unable to find session ${t}`);return G(`info`,`sessions.reload`,`Reloaded session ${t}`),M({sessionIds:[t],reason:`sessions.reload`}),e}return e(`reload_session`,{sessionId:t})}async function Mo(t){if(!f()){let e=`/mock/orchestra/sessions/${t}.jsonl`;return G(`info`,`sessions.open_file`,`Opened session file ${e}`),e}return e(`open_session_file`,{sessionId:t})}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(t,n,r,i=`default`){let a=n.trim();if(!a)throw Error(`Message cannot be empty`);if(!f()){let e=No(t,i),n={sessionId:t,runId:r,message:a,timestamp:F(),deliveryMode:e},o=mi();z(or,{...o,instance:{...o.instance,activeClientCount:1,inFlightRequestCount:1,heartbeatAt:n.timestamp},clients:[{clientId:`browser-client-${t}`,sessionId:t,actorType:`session`,actorId:t,requestCount:(o.clients[0]?.requestCount??0)+1,inFlightRequestCount:1,lastSeenAt:n.timestamp,lastCommand:`send_session_message`,lastError:null,active:!0,bridgeInstanceId:o.instance.instanceId}],recentRequests:[{requestId:`browser-request-${r}`,clientId:`browser-client-${t}`,sessionId:t,command:`send_session_message`,startedAt:n.timestamp,finishedAt:null,durationMs:null,success:!0,error:null},...o.recentRequests].slice(0,20)});let s=Di();s[t]=Array.from(new Set([...s[t]??[],r])),Oi(s),K(t,e=>({...e,status:`streaming`,updatedAt:n.timestamp,events:[...e.events.filter(e=>e.runId!==r),{id:`pending-user-${r}`,kind:`user`,message:a,timestamp:n.timestamp,pending:!0,runId:r}]}));let c=V().find(e=>e.id===t)??null;M({sessionIds:[t],reason:`sessions.message.queued`});let l=Po(e);G(`info`,l.target,`${l.message} for session ${t}`);let u=Vi(a),d=u.split(/(\s+)/).filter(Boolean),f=`Considering: ${a}`,p=f.split(/(\s+)/).filter(Boolean),m={role:`user`,content:[{type:`text`,text:a}],timestamp:Date.now()},h={role:`assistant`,content:[],timestamp:Date.now()};return window.setTimeout(()=>{j(B(t,r,{type:`agent_start`})),j(B(t,r,{type:`turn_start`})),j(B(t,r,{type:`message_start`,message:m})),j(B(t,r,{type:`message_end`,message:m})),j(B(t,r,{type:`message_start`,message:h})),j(B(t,r,{type:`message_update`,message:{...h,content:[{type:`thinking`,thinking:``}]},assistantMessageEvent:{type:`thinking_start`,contentIndex:0,partial:{}}})),p.forEach((e,n)=>{window.setTimeout(()=>{j(B(t,r,{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*(n+1))}),window.setTimeout(()=>{j(B(t,r,{type:`message_update`,message:{...h,content:[{type:`thinking`,thinking:f}]},assistantMessageEvent:{type:`thinking_end`,contentIndex:0,partial:{}}})),j(B(t,r,{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,n)=>{window.setTimeout(()=>{j(B(t,r,{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*(n+1))}),window.setTimeout(()=>{if(!ki(t,r)){let e=V().find(e=>e.id===t)??null;if(!e||e.status===`paused`||e.status===`closed`)return}let e={...h,content:[{type:`thinking`,thinking:f},{type:`text`,text:u}]};j(B(t,r,{type:`message_update`,message:e,assistantMessageEvent:{type:`text_end`,contentIndex:0,content:u,partial:{}}})),j(B(t,r,{type:`message_end`,message:e})),j(B(t,r,{type:`turn_end`,message:e,toolResults:[]}));let n=K(t,e=>{let n=F(),i=(Di()[t]??[]).filter(e=>e!==r);return{...e,status:i.length>0?`streaming`:`idle`,updatedAt:n,events:[...e.events.filter(e=>e.runId!==r),I(`user`,a,{runId:r,timestamp:n}),I(`assistant`,u,{thinkingText:f,timestamp:n,runId:r})]}});if(!n&&!c){j(B(t,r,{type:`error`,message:`Unable to find session ${t}`,source:`mock`}));return}let i=Li(c??n,r,u);i&&at(i);let o=Di(),s=(o[t]??[]).filter(e=>e!==r);s.length>0?o[t]=s:delete o[t],Oi(o),j(B(t,r,{type:`agent_end`}))},80*(d.length+2))},120),n}return e(`send_session_message`,{sessionId:t,message:a,runId:r,sendMode:i})}async function Io(t){let n=t??O();if(!f())return n;let r=await e(`list_projects`);return n&&r.some(e=>e.id===n)?n:r[0]?.id??n??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?me(t.number).sequence-me(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=(me(e.number).sequence-me(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(t=!1,n){let r=Lo(t,n),i=r.projectId??O(),a=Zi(r.tags);if(!f()){let e=ma(i).tasks.filter(e=>e.projectId===i).filter(e=>r.includeArchived||!e.archived).map(Q).filter(e=>zo(e,a,r.tagMatch)).sort((e,t)=>Bo(e,t,r));return G(`info`,`tasks.list`,`Listed ${e.length} tasks for ${i??`default`}`),e}return e(`list_tasks`,{projectId:await Io(r.projectId),includeArchived:r.includeArchived,tags:a,tagMatch:r.tagMatch,sortBy:r.sortBy,sortDirection:r.sortDirection})}async function $(t){if(!f()){let e=ma().tasks.find(e=>e.id===t);if(!e)throw Error(`Task ${t} was not found`);return e}return e(`get_task`,{taskId:t})}async function Ho(t){return f()?e(`list_task_todos`,{taskId:t}):is(t)}async function Uo(t,n){return f()?e(`list_unfinished_task_todos`,{taskId:t,laneId:n??null}):is(t,n??void 0,!1)}async function Wo(t,n){if(!f()){let e=X(),r=e.find(e=>e.id===t);if(!r)throw Error(`Task ${t} was not found`);let i=n.description.trim(),a=n.laneId?.trim()||null;if(!i)throw Error(`description: Task todo description is required.`);if(!r.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(!W().find(e=>e.id===r.workflowId)?.lanes.some(e=>e.id===a))throw Error(`laneId: Todo lane must belong to the task workflow.`);let o=F(),s={id:P(`task-todo`),taskId:t,laneId:a,description:i,completed:!1,createdAt:o,updatedAt:o};return Z(e.map(e=>e.id===t?{...e,todos:[...e.todos??[],s],updatedAt:o}:e)),G(`info`,`task.todo.added`,`Added todo ${s.id} to task ${t}`),N({taskIds:[t],reason:`task.todo.added`}),s}return e(`add_task_todo`,{taskId:t,input:n})}async function Go(t){if(!f()){let{task:e,todo:n}=as(t),r=F();return Z(X().map(n=>n.id===e.id?{...n,todos:(n.todos??[]).map(e=>e.id===t?{...e,completed:!0,updatedAt:r}:e),updatedAt:r}:n)),G(`info`,`task.todo.finished`,`Marked todo ${t} finished`),N({taskIds:[e.id],reason:`task.todo.finished`}),as(t).todo}return e(`mark_task_todo_finished`,{todoId:t})}async function Ko(t){if(!f()){let{task:e,todo:n}=as(t),r=F();return Z(X().map(n=>n.id===e.id?{...n,todos:(n.todos??[]).map(e=>e.id===t?{...e,completed:!1,updatedAt:r}:e),updatedAt:r}:n)),G(`info`,`task.todo.unfinished`,`Marked todo ${t} unfinished`),N({taskIds:[e.id],reason:`task.todo.unfinished`}),as(t).todo}return e(`mark_task_todo_unfinished`,{todoId:t})}async function qo(t){if(!f()){let{task:e,todo:n}=as(t),r=F();return Z(X().map(n=>n.id===e.id?{...n,todos:(n.todos??[]).filter(e=>e.id!==t),updatedAt:r}:n)),G(`info`,`task.todo.deleted`,`Deleted todo ${t}`),N({taskIds:[e.id],reason:`task.todo.deleted`}),n}return e(`delete_task_todo`,{todoId:t})}async function Jo(t,n){let r=n??O();if(!f()){let e=Ma(t);if(e.length>0)throw Error(e.map(e=>`${e.path}: ${e.message}`).join(`; `));let n=X().map(e=>Y(e)),i=ja(t,void 0,r??void 0),a=q(),o=[i,...n].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)),s=ya(o,a,i.id,i.parentTaskId,i.parentTaskId);Z(Ea(wa(o,a,s,i.updatedAt).tasks,s,i.updatedAt).tasks),G(`info`,`task.created`,`Created task ${i.id}`);let c=await $(i.id);return J(`task.created`,`task`,i.id,{taskId:i.id,taskNumber:i.number,status:c.status},i.projectId),N({taskIds:s,reason:`task.created`}),c}let i=await Io(n);return console.debug(`createTask resolvedProjectId`,{projectId:n,resolvedProjectId:i,input:t}),e(`create_task`,{projectId:i,input:t})}async function Yo(t,n){if(!f()){let e=Ma(n,t);if(e.length>0)throw Error(e.map(e=>`${e.path}: ${e.message}`).join(`; `));let r=X().map(e=>Y(e)),i=r.find(e=>e.id===t);if(!i)throw Error(`Task ${t} was not found`);let a=ja(n,i);a.status!==i.status&&(a.autoBlockedByDependencies=!1);let o=q(),s=ya(r,o,t,i.parentTaskId,a.parentTaskId),c=Ta(wa(r.map(e=>e.id===t?a:e).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)),o,s,a.updatedAt).tasks,a.status===`blocked`?[t]:[],a.updatedAt);Z(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.`);G(`info`,`task.updated`,`Updated task ${t}`);let l=await $(t);return J(`task.updated`,`task`,t,{taskId:t,taskNumber:l.number,status:l.status},l.projectId),N({taskIds:s,reason:`task.updated`}),l}return e(`update_task`,{taskId:t,input:n})}async function Xo(t){if(!f()){let e=ma().tasks,n=e.find(e=>e.id===t);if(!n)throw Error(`Task ${t} was not found`);return Ki(q().filter(e=>e.blockerTaskId!==t&&e.blockedTaskId!==t)),Z(e.filter(e=>e.id!==t).map(e=>e.parentTaskId===t?{...e,parentTaskId:null}:e)),G(`info`,`task.deleted`,`Deleted task ${t}`),J(`task.deleted`,`task`,t,{taskId:t,taskNumber:n.number,status:n.status},n.projectId),N({taskIds:[t],reason:`task.deleted`}),n}return e(`delete_task`,{taskId:t})}async function Zo(t){let n=x()?.client;if(n)return n.tasks.dispatch(t);if(!f()){let e=X(),n=e.find(e=>e.id===t);if(!n)throw Error(`Task ${t} was not found`);if(!n.workflowId||!n.currentLaneId)throw Error(`Task must have a workflow and current lane before dispatch.`);if(n.activeLaneAssignment)return $(t);if(n.status===`blocked`)throw Error(`Task ${t} is blocked and cannot be dispatched until it becomes runnable.`);if(n.dependencyBlocked)throw Error(`Task ${t} is blocked by unresolved dependencies or unfinished subtasks.`);let r=W().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.`);if(i.assignedEntityType===`user`)throw Error(`Current lane is user-owned and cannot be dispatched.`);let o=i.assignedEntityType===`agent`?hi().find(e=>e.slug===i.assignedEntityId)?.id??i.assignedEntityId??null:i.assignedEntityId??null,s=F(),c={id:P(`task-assignment`),taskId:n.id,workflowId:r.id,laneId:i.id,workerType:i.assignedEntityType,workerId:o,status:`active`,sessionId:null,runtimeCwd:`/mock/runtime/${i.assignedEntityType}/${i.assignedEntityId??`user`}`,roleQueueEntryId:i.assignedEntityType===`role`?P(`queue`):null,roleInstanceId:i.assignedEntityType===`role`?P(`instance`):null,prompt:`Work task ${n.number}: ${n.title}`,startedAt:s,completedAt:null,createdAt:s,updatedAt:s};if(i.assignedEntityType===`agent`&&c.workerId){let e=zi(i.assignedEntityId??`Agent`,c.workerId);c.sessionId=e.id,c.runtimeCwd=He(a),K(e.id,e=>Pi(e,n,`agent`,i.assignedEntityId??`Agent`));let t=P(`agent-queue`);_i([...gi(),{id:t,projectId:a,agentId:c.workerId,status:`dispatched`,sourceType:`workflow_lane`,sourceTaskId:n.id,sourceWorkflowId:r.id,sourceLaneId:i.id,deliveryMode:`prompt`,title:`${n.number} · ${n.title}`,message:c.prompt,sessionId:c.sessionId,runId:P(`run`),dispatchedAt:c.startedAt,completedAt:null,createdAt:c.createdAt,updatedAt:c.updatedAt}]),U(H().map(e=>e.agentId===c.workerId&&e.projectId===a?{...e,status:`running`,mainSessionId:c.sessionId,runtimeCwd:c.runtimeCwd,currentQueueEntryId:t,lastDispatchAt:c.updatedAt,lastError:null,updatedAt:c.updatedAt}:e))}else if(i.assignedEntityType===`role`){let e=Pi(wt(`${i.name} · ${n.title}`,`Role runtime session for ${n.number} is active and ready to continue the assigned lane.`),n,`role`,i.assignedEntityId??i.name);c.sessionId=e.id,Ct(e),M({sessionIds:[e.id],reason:`task.dispatch.role_session`})}return Z(e.map(e=>e.id===t?{...e,status:`in_progress`,assigneeType:i.assignedEntityType,assigneeId:i.assignedEntityId??null,activeLaneAssignment:c,laneRuns:[...e.laneRuns,{id:P(`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)),G(`info`,`task.dispatch`,`Dispatched task ${t} into ${i.assignedEntityType}:${i.assignedEntityId??`user`}`),J(`task.dispatched`,`task`,t,{taskId:t,assignmentId:c.id,laneId:i.id,sessionId:c.sessionId??null},n.projectId),c.sessionId&&M({sessionIds:[c.sessionId],reason:`task.dispatch`}),N({taskIds:[t],reason:`task.dispatch`}),$(t)}return e(`dispatch_task_lane`,{taskId:t})}function Qo(e,t,n,r){if(n.assignedEntityType===`user`)return null;let i={id:P(`task-assignment`),taskId:e.id,workflowId:t.id,laneId:n.id,workerType:n.assignedEntityType,workerId:n.assignedEntityId??null,status:`active`,sessionId:P(`session`),runtimeCwd:n.assignedEntityType===`agent`?He(e.projectId):`/mock/runtime/${n.assignedEntityType}/${n.assignedEntityId??`user`}`,roleQueueEntryId:n.assignedEntityType===`role`?P(`queue`):null,roleInstanceId:n.assignedEntityType===`role`?P(`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,K(t.id,t=>Pi(t,e,`agent`,n.assignedEntityId??`Agent`)),M({sessionIds:[t.id],reason:`task.transition.next_assignment`})}if(n.assignedEntityType===`role`){let t=Pi(wt(`${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,Ct(t),M({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`&&H().some(e=>e.mainSessionId===r)||(K(r,e=>({...Fi(e),status:`closed`,updatedAt:n})),M({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)),U(H().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:P(`run`),dispatchedAt:n.startedAt,completedAt:null,createdAt:n.createdAt,updatedAt:n.updatedAt}])}function ns(e){let t=Cr().find(t=>t.id===e)?.slug??a;return!!((Ot(t).autoDispatchOnBlockerCompletion??!0)&&t)}async function rs(e){let t=q().filter(t=>t.blockerTaskId===e);if(t.length===0)return[];let n=X(),r=new Map(W().map(e=>[e.id,e])),i=F(),a=[],o=[...n];for(let e of t){let t=o.findIndex(t=>t.id===e.blockedTaskId);if(t<0)continue;let n=await $(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:P(`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&&Z(o.sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))),a}function is(e,t,n){let r=X().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 X()){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):[]}async function cs(e,t,n,r,i=!0){let a=X(),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=W().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=F(),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?gr:_r;return Z(a.map(t=>t.id===e?{...t,status:`in_progress`,assigneeType:c.assignedEntityType,assigneeId:c.assignedEntityId??null,updatedAt:l}:t)),K(r,e=>({...e,status:`active`,updatedAt:l,events:[...e.events,I(`system`,i)]})),M({sessionIds:[r],reason:`task.transition.continue_working`}),N({taskIds:[e],reason:`task.transition.continue_working`}),G(`info`,`task.transition.continue_working`,`Kept task ${e} in progress after ${t} requested continue-working guidance`),$(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 Z(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),G(`info`,`task.transition`,`Stopped blocked task ${e} at transition time`),N({taskIds:[e],reason:`task.transition.blocked`}),$(e)}if(t===`success`&&o.activeLaneAssignment&&[`agent`,`role`].includes(o.activeLaneAssignment.workerType)&&(c.requireUserApprovalOnSuccess??!1)){Z(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)),G(`info`,`task.transition`,`Task ${e} is awaiting user approval on ${c.name}`),N({taskIds:[e],reason:`task.transition.awaiting_user_approval`});let n=await $(e);return at(It(n,`task.awaiting_user_approval`,jt(Sr(),n.projectId))),n}if(t===`needs_user`&&o.activeLaneAssignment&&[`agent`,`role`].includes(o.activeLaneAssignment.workerType)){Z(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)),G(`info`,`task.transition`,`Task ${e} is awaiting user intervention on ${c.name}`),N({taskIds:[e],reason:`task.transition.awaiting_user_intervention`});let n=await $(e);return at(It(n,`task.awaiting_user_intervention`,jt(Sr(),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,y=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,te=a.map(t=>t.id===e?{...Y(t),currentLaneId:m,status:h,assigneeType:g,assigneeId:_,activeLaneAssignment:v,autoBlockedByDependencies:[`completed`,`canceled`].includes(h)?!1:Y(t).autoBlockedByDependencies,laneRuns:v&&ee?[...y,{id:P(`lane-run`),taskId:t.id,laneId:ee.id,sessionId:v.sessionId,result:`needs_user`,notes:null,startedAt:v.startedAt,completedAt:null}]:y,updatedAt:l}:Y(t)),ne=q(),re=ya(te,ne,e,o.parentTaskId,o.parentTaskId);Z(wa(te,ne,re,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 ie=await rs(e);G(`info`,`task.transition`,`Completed task ${e} lane with ${t}`);let b=await $(e);return J(t===`success`&&b.status===`completed`?`task.completed`:t===`success`?`task.transition_success`:t===`failure`?`task.failed`:`task.user_intervention_requested`,`task`,e,{taskId:e,status:b.status,outcome:t,summary:u,notes:d,workflowId:b.workflowId??null,laneId:b.currentLaneId??null},b.projectId),N({taskIds:ha([...re,...ie]),reason:`task.transition.${t}`}),t!==`needs_user`&&b.assigneeType===`user`&&at(It(b,`task.assigned_to_user`,jt(Sr(),b.projectId))),b}async function ls(e){let t=X(),n=t.find(t=>t.id===e);if(!n||!n.workflowId||!n.currentLaneId||Tn(n)!==`awaiting_user_approval`)throw Error(`Task ${e} is not awaiting lane approval.`);let r=W().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=F(),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?{...Y(t),currentLaneId:o,status:s,assigneeType:c,assigneeId:l,activeLaneAssignment:d,autoBlockedByDependencies:[`completed`,`canceled`].includes(s)?!1:Y(t).autoBlockedByDependencies,laneRuns:d&&u?[...f,{id:P(`lane-run`),taskId:t.id,laneId:u.id,sessionId:d.sessionId,result:`needs_user`,notes:null,startedAt:d.startedAt,completedAt:null}]:f,updatedAt:a}:Y(t)),m=q(),h=ya(p,m,e,n.parentTaskId,n.parentTaskId);Z(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 G(`info`,`task.transition`,`Approved pending lane completion for task ${e}`),N({taskIds:ha([...h,...g]),reason:`task.transition.approved_success`}),$(e)}async function us(e){let t=X(),n=t.find(t=>t.id===e),r=n?Tn(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=W().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=F(),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 Z(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:P(`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),G(`info`,`task.transition`,`Sent task ${e} to configured Needs Work lane ${a.id}`),N({taskIds:[e],reason:`task.transition.needs_work`}),$(e)}}let i=F(),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 Z(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:P(`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)),K(n.activeLaneAssignment.sessionId,e=>({...e,status:`active`,updatedAt:i,events:[...e.events,I(`system`,a)]})),M({sessionIds:[n.activeLaneAssignment.sessionId],reason:`task.transition.rework`}),G(`info`,`task.transition`,`Sent task ${e} back to the current lane session for more work`),N({taskIds:[e],reason:`task.transition.needs_work`}),$(e)}async function ds(e,t){let n=await $(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=F();return n.activeLaneAssignment.sessionId&&await uo(n.activeLaneAssignment.sessionId,t),Z(X().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)),G(`info`,`task.control.paused`,`Paused task lane for task ${e}`),N({taskIds:[e],reason:`task.control.paused`}),$(e)}async function fs(e,t){let n=await $(e);n.activeLaneAssignment?.sessionId&&await uo(n.activeLaneAssignment.sessionId,t);let r=await Ts(e);return G(`info`,`task.control.stopped`,`Stopped task activity for task ${e}`),N({taskIds:[e],reason:`task.control.stopped`}),r}async function ps(e,t,n){let r=X(),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=W().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=F(),c=n?.trim()||null,l=c?{id:P(`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 Z(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:P(`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),G(`info`,`task.transition`,`Re-laned task ${e} to lane ${t}`),J(`task.relaned`,`task`,e,{taskId:e,laneId:o.id,status:p?`in_progress`:u,notes:c},i.projectId),N({taskIds:[e],reason:`task.transition.relane`}),$(e)}async function ms(t,n,r){return f()?e(`complete_lane_as_success`,{taskId:t,summary:n,notes:r}):cs(t,`success`,n,r)}async function hs(t,n,r,i){return f()?e(`complete_lane_as_failure`,{taskId:t,summary:n,actuallyFailed:r,notes:i}):cs(t,`failure`,n,i,r)}async function gs(t,n,r,i){return f()?e(`request_user_intervention`,{taskId:t,summary:n,actuallyBlocked:r,notes:i}):cs(t,`needs_user`,n,i,r)}async function _s(t){return f()?e(`approve_task_review`,{taskId:t}):ls(t)}async function vs(t){return f()?e(`approve_lane_completion`,{taskId:t}):ls(t)}async function ys(t,n){if(!f()){if(Tn(await $(t))!==`awaiting_user_approval`)throw Error(`Task ${t} is not awaiting user approval.`);return us(t)}return e(`mark_task_needs_work`,{taskId:t,notes:n})}async function bs(t,n){if(!f()){let e=await $(t),n=Tn(e);if(!e.activeLaneAssignment||![`awaiting_user_intervention`,`paused_by_user`].includes(n??``))throw Error(`Task ${t} is not paused for user intervention or a user pause.`);return n===`paused_by_user`?await(async()=>{let n=F();return Z(X().map(e=>e.id===t?{...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:n}:null,updatedAt:n}:e)),e.activeLaneAssignment?.sessionId&&(K(e.activeLaneAssignment.sessionId,e=>({...e,status:`active`,updatedAt:n,events:[...e.events,I(`system`,`The user resumed this paused lane. Reload the latest task context before continuing.`)]})),M({sessionIds:[e.activeLaneAssignment.sessionId],reason:`task.control.resumed`})),N({taskIds:[t],reason:`task.control.resumed`}),$(t)})():us(t)}return e(`resume_task_lane`,{taskId:t,notes:n})}async function xs(t,n){return f()?e(`pause_task_lane`,{taskId:t,notes:n}):ds(t,n)}async function Ss(t,n){return f()?e(`stop_task_activity`,{taskId:t,notes:n}):fs(t,n)}async function Cs(t,n,r){return f()?e(`reassign_task_to_lane`,{taskId:t,laneId:n,notes:r}):ps(t,n,r)}async function ws(t){if(!f()){let e=await $(t);if(!e.activeLaneAssignment)throw Error(`Task ${t} does not have an active lane assignment to whip.`);let n={...e,activeLaneAssignment:{...e.activeLaneAssignment,whipCount:(e.activeLaneAssignment.whipCount??0)+1,lastWhipAt:F()},updatedAt:F()};return Z(X().map(e=>e.id===t?n:e)),G(`info`,`task.whip.sent`,`Sent manual whip for task ${t}`),N({taskIds:[t],reason:`task.whip.sent`}),$(t)}return e(`manual_task_whip`,{taskId:t})}async function Ts(t){let n=x()?.client;if(n)return n.tasks.resetRuntime(t);if(!f()){let e=await $(t),n=F(),r=e.activeLaneAssignment,i={...e,status:e.currentLaneId?`ready`:e.status,activeLaneAssignment:null,updatedAt:n};return r?.workerType===`agent`&&(_i(gi().filter(e=>e.sourceTaskId!==t)),U(H().map(e=>e.agentId===r.workerId&&e.projectId===a?{...e,status:`idle`,currentQueueEntryId:null,lastError:null,updatedAt:n}:e))),r?.workerType===`role`&&(bi(yi().map(e=>e.sourceTaskId===t&&[`queued`,`assigned`].includes(String(e.status??``))?{...e,status:`canceled`,assignedInstanceId:null,completedAt:n,updatedAt:n}:e)),Si(xi().map(e=>e.id===r.roleInstanceId?{...e,status:`idle`,currentQueueEntryId:null,updatedAt:n}:e))),Z(X().map(e=>e.id===t?i:e)),r?.sessionId&&(K(r.sessionId,e=>Fi(e)),M({sessionIds:[r.sessionId],reason:`task.runtime.reset`})),N({taskIds:[t],reason:`task.runtime.reset`}),$(t)}return e(`reset_task_runtime`,{taskId:t})}async function Es(t,n){if(!f()){if(t===n)throw Error(`A task cannot depend on itself.`);let e=X();if(!e.some(e=>e.id===t)||!e.some(e=>e.id===n))throw Error(`Both tasks must exist before adding a dependency.`);let r=q();if(r.some(e=>e.blockerTaskId===t&&e.blockedTaskId===n))throw Error(`That dependency already exists.`);let i=[n],a=new Set;for(;i.length>0;){let e=i.pop();if(a.add(e)){if(e===t)throw Error(`That dependency would create a cycle.`);i.push(...r.filter(t=>t.blockerTaskId===e).map(e=>e.blockedTaskId))}}let o=e.find(e=>e.id===t),s=e.find(e=>e.id===n),c={id:P(`task-dependency`),blockerTaskId:t,blockedTaskId:n,blocker:Q(o),blocked:Q(s),...ba(e,t),createdAt:F()},l=[...r,c];Ki(l);let u=ya(e.map(e=>Y(e)),l,n,s.parentTaskId,s.parentTaskId);return Z(Ea(wa(e.map(e=>Y(e)),l,u,c.createdAt).tasks,u,c.createdAt).tasks),G(`info`,`task.dependency.added`,`Added dependency ${t} -> ${n}`),N({taskIds:ha([t,...u]),reason:`task.dependency.added`}),c}return e(`add_task_dependency`,{blockerTaskId:t,blockedTaskId:n})}async function Ds(t){if(!f()){let e=q(),n=e.find(e=>e.id===t);if(!n)throw Error(`Task dependency ${t} was not found`);let r=e.filter(e=>e.id!==t);Ki(r);let i=X().map(e=>Y(e)),a=i.find(e=>e.id===n.blockedTaskId)??null,o=ya(i,r,n.blockedTaskId,a?.parentTaskId,a?.parentTaskId);return Z(Ea(wa(i,r,o).tasks,o).tasks),G(`info`,`task.dependency.removed`,`Removed dependency ${t}`),N({taskIds:ha([n.blockerTaskId,...o]),reason:`task.dependency.removed`}),n}return e(`remove_task_dependency`,{dependencyId:t})}async function Os(t,n,r=10){if(!f()){let e=X().find(e=>e.id===t)??null;if(!e)return[];let i=n.trim().replace(/^[@$]/,``).toLowerCase(),a=new Set(e.fileReferences.map(e=>e.repositoryId)).size;return e.fileReferences.map(e=>{let t=`${e.repositorySlug}:${e.relativePath}`.toLowerCase(),n=e.relativePath.toLowerCase().indexOf(i),r=t.indexOf(i),o=n>=0?n:r;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,r).map(({bestIndex:e,...t})=>t)}return e(`search_task_comment_file_mentions`,{taskId:t,query:n,limit:r})}async function ks(t,n){if(!f()){let e=X(),r=e.find(e=>e.id===t);if(!r)throw Error(`Task ${t} was not found`);let i=n.author.trim(),a=n.message.trim(),o=n.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=r.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:P(`task-comment`),taskId:t,parentCommentId:o,author:i,originType:n.originType?.trim()||`user`,originId:n.originId?.trim()||null,message:a,interruptAgent:n.interruptAgent,repositoryId:n.repositoryId?.trim()||null,relativePath:n.relativePath?.trim()||null,lineStart:n.lineStart??null,lineEnd:n.lineEnd??n.lineStart??null,columnStart:n.columnStart??null,columnEnd:n.columnEnd??null,selectedText:n.selectedText?.trim()||null,anchorCommitHash:null,anchorHasUncommittedChanges:null,diffAnchor:n.diffAnchor??null,createdAt:F(),updatedAt:F()};return Z(e.map(e=>e.id===t?{...e,comments:[...e.comments,s],updatedAt:s.updatedAt}:e)),G(`info`,n.interruptAgent?`task.comment.interrupt_requested`:`task.commented`,`Added comment ${s.id} to task ${t}`),J(`task.comment_added`,`task`,t,{taskId:t,commentId:s.id,interrupt:n.interruptAgent},r.projectId),N({taskIds:[t],reason:n.interruptAgent?`task.comment.interrupt_requested`:`task.commented`}),s}return e(`comment_on_task`,{taskId:t,input:n})}async function As(t){if(!f()){let e=await $(t),n=Yr(),r=F(),i=[...n];for(let n of e.comments.map(Qr)){if(n.originType===`user`)continue;let e=i.find(e=>e.commentId===n.id&&e.taskId===t&&e.userId===`desktop-user`);e?e.readAt=r:i.push({commentId:n.id,taskId:t,userId:`desktop-user`,readAt:r})}return Xr(i),G(`info`,`task.comment.user_read`,`Marked non-user task comments read for task ${t}`),N({taskIds:[t],reason:`task.comment.user_read`}),$(t)}return e(`mark_task_comments_read_for_user`,{taskId:t})}async function js(t,n=!1){return f()?e(`list_inbox_messages`,{projectId:t??null,includeArchived:n}):ri().filter(e=>e.recipientType===`user`&&(!t||e.projectId===t)).filter(e=>n||!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(t){return f()?e(`list_task_messages`,{taskId:t}):ri().filter(e=>e.taskId===t).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}async function Ns(t){if(!f()){let e=X(),n=t.taskId?e.find(e=>e.id===t.taskId)??null:null,r=n?.projectId??t.projectId??O()??a,i=Sr(),o=R(er)??[],s=t.recipientType,c=t.recipientId??null,l=`User`,u=null;if(s===`agent`){let e=o.find(e=>e.id===t.recipientId);if(!e)throw Error(`Agent ${t.recipientId} was not found`);l=e.name}else if(s===`active_assignment`){if(!n?.activeLaneAssignment)throw Error(`Task ${t.taskId} has no active assignment mailbox`);s=`assignment`,c=n.activeLaneAssignment.workerId??null,u=n.activeLaneAssignment.id,l=`${o.find(e=>e.id===n.activeLaneAssignment?.workerId)?.name??n.activeLaneAssignment.workerType} · ${n.number}`}let d={deliveryId:P(`mail-delivery`),messageId:P(`mail-message`),projectId:r,taskId:n?.id??t.taskId??null,taskNumber:n?.number??null,taskTitle:n?.title??null,senderType:`user`,senderId:`desktop-user`,senderLabel:t.senderLabel?.trim()||`User`,recipientType:s,recipientId:c,recipientLabel:l,assignmentId:u,body:t.body.trim(),priority:t.priority===`interrupt`?`interrupt`:`normal`,readAt:null,readSessionId:null,archivedAt:null,lastNotifiedAt:s===`user`?null:F(),createdAt:F(),updatedAt:F()};return ii([d,...ri()]),it({deliveryIds:[d.deliveryId],reason:`mailbox.sent`}),d.taskId&&N({taskIds:[d.taskId],reason:`mailbox.sent`}),d.recipientType===`user`&&at(Ft(d,jt(i,d.projectId))),G(`info`,`mailbox.sent`,`Sent mailbox delivery ${d.deliveryId} to ${d.recipientLabel}`),d}return e(`send_mailbox_message`,{input:t})}async function Ps(t){if(!f()){let e=F(),n=new Set(t.deliveryIds??ri().filter(e=>e.recipientType===`user`&&!e.readAt).map(e=>e.deliveryId)),r=[];return ii(ri().map(t=>{if(t.recipientType!==`user`||!n.has(t.deliveryId))return t;let i={...t,readAt:e,readSessionId:`desktop-user`,updatedAt:e};return r.push(i),i})),r.length&&it({deliveryIds:r.map(e=>e.deliveryId),reason:`mailbox.read`}),r}return e(`mark_mailbox_messages_read`,{input:t})}async function Fs(t){if(!f()){let e=F(),n=new Set(t.deliveryIds??ri().filter(e=>e.recipientType===`user`&&!e.archivedAt).map(e=>e.deliveryId)),r=[];return ii(ri().map(t=>{if(t.recipientType!==`user`||!n.has(t.deliveryId))return t;let i={...t,archivedAt:e,updatedAt:e};return r.push(i),i})),r.length&&it({deliveryIds:r.map(e=>e.deliveryId),reason:`mailbox.archived`}),r}return e(`archive_mailbox_messages`,{input:t})}async function Is(t){if(!f()){let e=X().find(e=>e.id===t);if(!e)throw Error(`Task ${t} was not found`);return e.comments}return e(`list_task_comments`,{taskId:t})}async function Ls(t,n){if(!f()){let e=X(),r=null;if(Z(e.map(e=>({...e,comments:e.comments.map(e=>e.id===t?(r={...e,message:n.message.trim(),updatedAt:F()},r):e)}))),!r)throw Error(`Task comment ${t} was not found`);let i=r;return J(`task.comment_updated`,`task`,i.taskId,{taskId:i.taskId,commentId:i.id},X().find(e=>e.id===i.taskId)?.projectId??null),i}return e(`update_task_comment`,{commentId:t,input:n})}async function Rs(t){if(!f()){let e=X(),n=null;if(Z(e.map(e=>{let r=e.comments.find(e=>e.id===t);if(!r)return e;n=r;let i=new Set([t,...e.comments.filter(e=>e.parentCommentId===t).map(e=>e.id)]);return{...e,comments:e.comments.filter(e=>!i.has(e.id))}})),!n)throw Error(`Task comment ${t} was not found`);let r=n;return J(`task.comment_deleted`,`task`,r.taskId,{taskId:r.taskId,commentId:r.id},X().find(e=>e.id===r.taskId)?.projectId??null),r}return e(`delete_task_comment`,{commentId:t})}async function zs(t){if(!f()){let e=X().find(e=>e.id===t||e.comments.some(e=>e.id===t));if(!e)throw Error(`Task not found for comment ${t}`);let n=e.comments.find(e=>e.id===t);if(!n)throw Error(`Task comment ${t} 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(t),o=new Set([t]);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(t);let c=1+a;return{commentId:n.id,taskId:n.taskId,replyCount:a,attachmentCount:0,fileReferenceCount:0,cascadeDeletedCount:c}}return e(`get_task_comment_delete_impact`,{commentId:t})}async function Bs(t,n){if(!f()){let e=X(),r=e.find(e=>e.id===t);if(!r)throw Error(`Task ${t} was not found`);let i=(Sr().find(e=>e.id===r.projectId)??null)?.repositories.find(e=>e.id===n.repositoryId)??null;if(!i)throw Error(`Repository ${n.repositoryId} was not found`);let a=n.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:P(`task-file-reference`),taskId:t,repositoryId:i.id,repositoryName:i.name,repositorySlug:i.slug,relativePath:a,absolutePath:i.repositoryPath?`${i.repositoryPath.replace(/\/$/,``)}/${a}`:null,exists:!1,isDefault:!1,createdAt:F()};return Z(e.map(e=>e.id===t?{...e,fileReferences:[...e.fileReferences,o],updatedAt:o.createdAt}:e)),G(`info`,`task.file_reference.added`,`Added file reference ${o.id} to task ${t}`),J(`task.file_reference_added`,`task`,t,{taskId:t,referenceId:o.id,relativePath:o.relativePath},r.projectId),N({taskIds:[t],reason:`task.file_reference.added`}),o}return e(`add_task_file_reference`,{taskId:t,input:n})}async function Vs(t){if(!f()){let e=X().find(e=>e.id===t);if(!e)throw Error(`Task ${t} was not found`);return e.fileReferences}return e(`list_task_file_references`,{taskId:t})}async function Hs(t){if(!f()){let e=X().map(e=>({...e,fileReferences:e.fileReferences.map(e=>({...e,isDefault:e.id===t}))}));Z(e);let n=e.flatMap(e=>e.fileReferences).find(e=>e.id===t);if(!n)throw Error(`Task file reference ${t} was not found`);return G(`info`,`task.file_reference.default_set`,`Set ${t} as default`),N({taskIds:[n.taskId],reason:`task.file_reference.default_set`}),n}return e(`set_default_task_file_reference`,{referenceId:t})}async function Us(t){return f()?e(`get_task_file_content`,{path:t}):(R(Yn)??{})[t]??[`Mocked file content for: ${t}`,`Second line for anchored comments.`,`Third line with text selection support.`].join(`
`)}async function Ws(t){if(!f()){let e=await $(t);return{taskId:t,generatedAt:F(),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:t})}async function Gs(t){if(!f()){let e=X(),n=null,r=e.map(e=>{let r=e.fileReferences.find(e=>e.id===t)??null;return r?(n=r,{...e,fileReferences:e.fileReferences.filter(e=>e.id!==t)}):e});if(!n)throw Error(`Task file reference ${t} was not found`);let i=n;return Z(r),G(`info`,`task.file_reference.removed`,`Removed file reference ${t}`),J(`task.file_reference_removed`,`task`,i.taskId,{taskId:i.taskId,referenceId:i.id,relativePath:i.relativePath},X().find(e=>e.id===i.taskId)?.projectId??null),N({taskIds:[i.taskId],reason:`task.file_reference.removed`}),i}return e(`remove_task_file_reference`,{referenceId:t})}async function Ks(t,n){if(!f()){let e=X(),r=e.find(e=>e.id===t);if(!r)throw Error(`Task ${t} was not found`);let i=await Qt(n),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:P(`task-attachment`),taskId:t,fileName:i.fileName,mediaType:i.mediaType||`application/octet-stream`,byteSize:a.length,storedPath:`/mock/attachments/${t}/${i.fileName}`,caption:i.caption?.trim()||null,previewText:s,imageDataUrl:o,createdAt:F()};return Z(e.map(e=>e.id===t?{...e,attachments:[...e.attachments,c]}:e)),ni({...ti(),[c.id]:{base64Data:i.base64Data,mediaType:c.mediaType,fileName:c.fileName}}),G(`info`,`task.attachment.added`,`Added attachment ${c.id} to task ${t}`),J(`task.attachment_added`,`task`,t,{taskId:t,attachmentId:c.id,fileName:c.fileName},r.projectId),N({taskIds:[t],reason:`task.attachment.added`}),c}return e(`add_task_attachment`,{taskId:t,input:await Qt(n)})}async function qs(t){if(!f()){let e=ti()[t];if(!e)throw Error(`Task attachment ${t} was not found`);return{fileName:e.fileName,mediaType:e.mediaType,blob:Bt(e.base64Data,e.mediaType)}}let n=await e(`get_task_attachment_content`,{attachmentId:t});return{fileName:n.fileName,mediaType:n.mediaType,blob:Bt(n.base64Data,n.mediaType)}}async function Js(t){if(!f()){let e=ti()[t];if(!e)throw Error(`Task attachment ${t} was not found`);Rt(Bt(e.base64Data,e.mediaType),e.fileName);return}await e(`download_task_attachment`,{attachmentId:t})}async function Ys(t){if(!f()){let e=X(),n=null,r=e.map(e=>{let r=e.attachments.find(e=>e.id===t)??null;return r?(n=r,{...e,attachments:e.attachments.filter(e=>e.id!==t)}):e});if(!n)throw Error(`Task attachment ${t} was not found`);let i=n,a={...ti()};return delete a[t],ni(a),Z(r),G(`info`,`task.attachment.removed`,`Removed attachment ${t}`),J(`task.attachment_removed`,`task`,i.taskId,{taskId:i.taskId,attachmentId:i.id,fileName:i.fileName},X().find(e=>e.id===i.taskId)?.projectId??null),N({taskIds:[i.taskId],reason:`task.attachment.removed`}),i}return e(`remove_task_attachment`,{attachmentId:t})}async function Xs(t){let n=t??O();return f()?e(`list_task_schedules`,{projectId:await Io(t)}):ma(n).schedules.filter(e=>e.projectId===n).map(e=>la(e,X()))}async function Zs(t){if(!f()){let e=ma(),n=e.schedules.find(e=>e.id===t);if(!n)throw Error(`Task schedule ${t} was not found`);return ua(n,e.tasks)}return e(`get_task_schedule`,{scheduleId:t})}async function Qs(t,n){let r=n??O();if(!f()){let e=fa(t);if(e.length>0)throw Error(e.map(e=>`${e.path}: ${e.message}`).join(`; `));let n=pa(t,void 0,r??void 0);Xi([n,...Yi()].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)));let i=ma(r);G(`info`,`task.schedule.created`,`Created task schedule ${n.id}`),J(`task.schedule.created`,`task_schedule`,n.id,{scheduleId:n.id,title:n.taskBlueprint.title,enabled:n.enabled,triggerType:n.trigger.type},n.projectId),N({taskIds:[],reason:`task.schedule.created`});let a=i.schedules.find(e=>e.id===n.id);if(!a)throw Error(`Task schedule ${n.id} was not found after creation`);return ua(a,i.tasks)}return e(`create_task_schedule`,{projectId:await Io(n),input:t})}async function $s(t,n){if(!f()){let e=fa(n);if(e.length>0)throw Error(e.map(e=>`${e.path}: ${e.message}`).join(`; `));let r=Yi(),i=r.find(e=>e.id===t);if(!i)throw Error(`Task schedule ${t} was not found`);let a=pa(n,{...i,trigger:n.trigger,nextFireAt:n.trigger.type===`time`?oa(n.trigger,F()):null});a.occurrences=i.occurrences,a.lastFiredAt=i.lastFiredAt??null,a.lastMaterializedTaskId=i.lastMaterializedTaskId??null,a.lastError=i.lastError??null,Xi(r.map(e=>e.id===t?a:e).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)));let o=ma(i.projectId);G(`info`,`task.schedule.updated`,`Updated task schedule ${t}`),J(`task.schedule.updated`,`task_schedule`,t,{scheduleId:t,title:a.taskBlueprint.title,enabled:a.enabled,triggerType:a.trigger.type},a.projectId),N({taskIds:[],reason:`task.schedule.updated`});let s=o.schedules.find(e=>e.id===t);if(!s)throw Error(`Task schedule ${t} was not found after update`);return ua(s,o.tasks)}return e(`update_task_schedule`,{scheduleId:t,input:n})}async function ec(t){if(!f()){let e=ma(),n=e.schedules,r=n.find(e=>e.id===t);if(!r)throw Error(`Task schedule ${t} was not found`);return Xi(n.filter(e=>e.id!==t)),G(`info`,`task.schedule.deleted`,`Deleted task schedule ${t}`),J(`task.schedule.deleted`,`task_schedule`,t,{scheduleId:t,title:r.taskBlueprint.title},r.projectId),N({taskIds:[],reason:`task.schedule.deleted`}),ua(r,e.tasks)}return e(`delete_task_schedule`,{scheduleId:t})}async function tc(t=!1){let n=x()?.client;return n?n.catalog.listWorkflows(t):f()?e(`list_workflows`,{includeArchived:t}):W().filter(e=>t||!e.archived).map(Ui)}async function nc(t){let n=x()?.client;if(n)return n.catalog.getWorkflow(t);if(!f()){let e=W().find(e=>e.id===t);if(!e)throw Error(`Workflow ${t} was not found`);return e}return e(`get_workflow`,{workflowId:t})}async function rc(t){let n=x()?.client;return n?n.workflows.validateWorkflow(t):f()?e(`validate_workflow`,{input:t}):Na(t)}async function ic(t){let n=x()?.client;if(n)return n.workflows.createWorkflow(t);if(!f()){let e=Na(t);if(!e.valid)throw Error(e.errors.map(e=>`${e.path}: ${e.message}`).join(`; `));let n=Pa(t);return wi([n,...W()]),G(`info`,`workflow.created`,`Created workflow ${n.id}`),n}return e(`create_workflow`,{input:t})}async function ac(t,n){let r=x()?.client;if(r)return r.workflows.updateWorkflow(t,n);if(!f()){let e=Na(n);if(!e.valid)throw Error(e.errors.map(e=>`${e.path}: ${e.message}`).join(`; `));let r=W(),i=r.find(e=>e.id===t);if(!i)throw Error(`Workflow ${t} was not found`);let a=Pa(n,i);return wi(r.map(e=>e.id===t?a:e)),G(`info`,`workflow.updated`,`Updated workflow ${t}`),a}return e(`update_workflow`,{workflowId:t,input:n})}async function oc(t,n){let r=x()?.client;if(r)return r.workflows.duplicateWorkflow(t,n);if(!f()){let e=await nc(t);return ic({name:n?.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:t,newName:n})}async function sc(t){let n=x()?.client;if(n)return n.workflows.archiveWorkflow(t);if(!f()){let e=W(),n=e.find(e=>e.id===t);if(!n)throw Error(`Workflow ${t} was not found`);let r={...n,archived:!0,updatedAt:F()};return wi(e.map(e=>e.id===t?r:e)),G(`info`,`workflow.archived`,`Archived workflow ${t}`),r}return e(`archive_workflow`,{workflowId:t})}async function cc(t){let n=x()?.client;if(n)return n.workflows.getWorkflowDeleteImpact(t);if(!f()){let e=W().find(e=>e.id===t);if(!e)throw Error(`Workflow ${t} was not found`);return Wi(e)}return e(`get_workflow_delete_impact`,{workflowId:t})}async function lc(t){let n=x()?.client;if(n)return n.workflows.deleteWorkflow(t);if(!f()){let e=W(),n=e.find(e=>e.id===t);if(!n)throw Error(`Workflow ${t} was not found`);let r=Wi(n);if(!r.canDelete)throw Error(`Workflow ${t} 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!==t)),G(`info`,`workflow.deleted`,`Deleted workflow ${t}`),J(`workflow.deleted`,`workflow`,t,{workflowId:t,name:n.name},null),r}return e(`delete_workflow`,{workflowId:t})}export{Zs as $,ue as $n,Yo as $t,Js as A,st as An,jo as At,fo as B,Be as Bn,_o as Bt,Rs as C,Ot as Cn,Ko as Ct,xo as D,wt as Dn,xs as Dt,lc as E,kt as En,Mo as Et,Ya as F,Qe as Fn,Ia as Ft,Za as G,qe as Gn,vo as Gt,So as H,He as Hn,Ns as Ht,kr as I,Ze as In,gs as It,$ as J,Xe as Jn,uo as Jt,Qa as K,Ue as Kn,ko as Kt,Or as L,et as Ln,Ts as Lt,Ga as M,M as Mn,Ys as Mt,La as N,tt as Nn,Ds as Nt,Eo as O,Ct as On,Ba as Ot,Ha as P,Ye as Pn,Gs as Pt,Ws as Q,ge as Qn,lo as Qt,Dr as R,O as Rn,so as Rt,Xo as S,Rt as Sn,Go as St,qo as T,Dt as Tn,Ka as Tt,ho as U,Je as Un,Fo as Ut,go as V,Ge as Vn,Os as Vt,Oo as W,We as Wn,Hs as Wt,zs as X,_e as Xn,wo as Xt,qs as Y,$e as Yn,Ss as Yt,Us as Z,x as Zn,co as Zt,io as _,an as _n,tc as _t,vs as a,Ln as an,qa as at,ic as b,Qt as bn,As as bt,sc as c,En as cn,Do as ct,Wa as d,Tn as dn,Vs as dt,Ls as en,fe as er,nc as et,ks as f,cn as fn,Ms as ft,ao as g,sn as gn,Uo as gt,ms as h,$t as hn,Vo as ht,Wo as i,Vn as in,Ja as it,oc as j,dt as jn,yo as jt,Zo as k,ot as kn,Cs as kt,To as l,Dn as ln,Xa as lt,hs as m,pn as mn,Ho as mt,Es as n,ac as nn,f as nr,mo as nt,_s as o,kn as on,js as ot,Ao as p,Sn as pn,Xs as pt,$a as q,nt as qn,Co as qt,Bs as r,rc as rn,c as rr,bo as rt,Fs as s,An as sn,za as st,Ks as t,$s as tn,de as tr,cc as tt,Ua as u,On as un,Is as ut,Jo as v,on as vn,ws as vt,ec as w,Et as wn,Va as wt,oo as x,Bt as xn,ys as xt,Qs as y,Xt as yn,Ps as yt,Ra as z,Ve as zn,bs as zt};