mindexec-ai 0.2.385
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +354 -0
- package/codex-runtime.js +1339 -0
- package/launch-bridge.cjs +236 -0
- package/package.json +77 -0
- package/port-guard.cjs +232 -0
- package/remote-fast/osx-arm64/mindexec-remote-fast +0 -0
- package/remote-fast/osx-arm64/mindexec-remote-fast.deps.json +24 -0
- package/remote-fast/osx-arm64/mindexec-remote-fast.dll +0 -0
- package/remote-fast/osx-arm64/mindexec-remote-fast.runtimeconfig.json +13 -0
- package/remote-fast/osx-x64/mindexec-remote-fast +0 -0
- package/remote-fast/osx-x64/mindexec-remote-fast.deps.json +24 -0
- package/remote-fast/osx-x64/mindexec-remote-fast.dll +0 -0
- package/remote-fast/osx-x64/mindexec-remote-fast.runtimeconfig.json +13 -0
- package/remote-fast/win-x64/mindexec-remote-fast.deps.json +24 -0
- package/remote-fast/win-x64/mindexec-remote-fast.dll +0 -0
- package/remote-fast/win-x64/mindexec-remote-fast.exe +0 -0
- package/remote-fast/win-x64/mindexec-remote-fast.runtimeconfig.json +20 -0
- package/remote-hub.js +3106 -0
- package/scripts/auth-session-smoke.mjs +262 -0
- package/scripts/remote-agent-managed-smoke.mjs +291 -0
- package/scripts/remote-agent-package-smoke.mjs +64 -0
- package/scripts/remote-agent-ws-smoke.mjs +202 -0
- package/scripts/remote-fast-live-rate-smoke.mjs +355 -0
- package/scripts/remote-fast-mdm-browser-smoke.mjs +476 -0
- package/scripts/remote-fleet-render-smoke.mjs +1491 -0
- package/scripts/remote-frame-ws-smoke.mjs +234 -0
- package/scripts/remote-http-smoke.mjs +592 -0
- package/scripts/remote-hub-identity-smoke.mjs +146 -0
- package/scripts/remote-hub-scale-smoke.mjs +124 -0
- package/scripts/remote-hub-smoke.mjs +631 -0
- package/scripts/remote-input-ws-smoke.mjs +263 -0
- package/scripts/remote-registry-follower-smoke.mjs +752 -0
- package/scripts/setup-tree-sitter-grammars.mjs +80 -0
- package/server.js +15709 -0
- package/start-bridge.bat +32 -0
- package/start-bridge.sh +81 -0
- package/tree-sitter-grammars/README.md +18 -0
- package/tree-sitter-grammars/tree-sitter-c_sharp.wasm +0 -0
- package/tree-sitter-grammars/tree-sitter-go.wasm +0 -0
- package/tree-sitter-grammars/tree-sitter-java.wasm +0 -0
- package/tree-sitter-grammars/tree-sitter-javascript.wasm +0 -0
- package/tree-sitter-grammars/tree-sitter-python.wasm +0 -0
- package/tree-sitter-grammars/tree-sitter-rust.wasm +0 -0
- package/tree-sitter-grammars/tree-sitter-tsx.wasm +0 -0
- package/tree-sitter-grammars/tree-sitter-typescript.wasm +0 -0
- package/wwwroot/_headers +73 -0
- package/wwwroot/_redirects +1 -0
- package/wwwroot/appsettings.json +83 -0
- package/wwwroot/assets/AdminDashboardPage-B2vz2Px9.css +1 -0
- package/wwwroot/assets/AdminDashboardPage-DnuCHywn.js +1 -0
- package/wwwroot/assets/AppSidebar-DU2OgSiv.js +2 -0
- package/wwwroot/assets/AuthPages-BrH6kRcv.css +1 -0
- package/wwwroot/assets/AuthPages-Dgezl7Vj.js +1 -0
- package/wwwroot/assets/CodePage-7kgZlB3O.js +87 -0
- package/wwwroot/assets/CodePage-Bncc352E.css +1 -0
- package/wwwroot/assets/CompanyCorePage-ChBnq1ve.css +1 -0
- package/wwwroot/assets/CompanyCorePage-CzIZIIU_.js +13 -0
- package/wwwroot/assets/ExecutionModePage-B-etp_mc.js +18 -0
- package/wwwroot/assets/ExecutionModePage-TLuld9l3.css +1 -0
- package/wwwroot/assets/LaunchLeadCapture-Bx9LM0IX.js +1 -0
- package/wwwroot/assets/LaunchLeadCapture-CiRI1shz.css +1 -0
- package/wwwroot/assets/MarketingHome-BsyerRpe.js +1 -0
- package/wwwroot/assets/MarketingHome-DPzaYzA_.css +1 -0
- package/wwwroot/assets/MindCanvas-DtqOZnoW.css +1 -0
- package/wwwroot/assets/MindCanvas-zEDXzaxW.js +49 -0
- package/wwwroot/assets/PlanMasterPage-CJ36rep-.css +1 -0
- package/wwwroot/assets/PlanMasterPage-NZ_mPvaE.js +4 -0
- package/wwwroot/assets/PricingPage-Cg_0i_ZR.css +1 -0
- package/wwwroot/assets/PricingPage-Ylrn8l2g.js +1 -0
- package/wwwroot/assets/ToolPages-3M2KqA9k.js +28 -0
- package/wwwroot/assets/ToolPages-DIB187pZ.css +1 -0
- package/wwwroot/assets/YouTubeSearchPage-COv1oAA7.js +4 -0
- package/wwwroot/assets/YouTubeSearchPage-IPPa_BIH.css +1 -0
- package/wwwroot/assets/app-runtime-xD2Z3NdN.js +1 -0
- package/wwwroot/assets/canvas-runtime-BbicBcOj.js +44 -0
- package/wwwroot/assets/code-agent-runtime-B5PPZd1t.js +74 -0
- package/wwwroot/assets/executionModeSettings-NJqurj-o.js +1 -0
- package/wwwroot/assets/index-CQMKCp-t.js +2 -0
- package/wwwroot/assets/index-yNpEK-gp.css +1 -0
- package/wwwroot/assets/marketingTools-DN_rnHeB.js +4 -0
- package/wwwroot/assets/mindCanvasSearchWorker-BzPMsHOB.js +1 -0
- package/wwwroot/assets/mindexecution-mindcanvas.png +0 -0
- package/wwwroot/assets/mindexecution-prod-home-current.png +0 -0
- package/wwwroot/assets/mindexecution-prod-pricing-current.png +0 -0
- package/wwwroot/assets/pricingCheckoutShell-O-DnwmbU.js +1 -0
- package/wwwroot/assets/productionAdapterConfig-C5jfk6oG.js +1 -0
- package/wwwroot/assets/runtimeSettingsPersistenceProjection-BoNWmYjU.js +1 -0
- package/wwwroot/assets/storage-TM3YrWaj.js +1 -0
- package/wwwroot/assets/supabaseAuthAdapter-DA43DeSY.js +44 -0
- package/wwwroot/assets/toolHandoff-D5e5f7t5.js +4 -0
- package/wwwroot/assets/vendor-icons-DE3gIReG.js +681 -0
- package/wwwroot/assets/vendor-msgpack-BE8aAsr3.js +1 -0
- package/wwwroot/assets/vendor-react-BXzpOyCS.js +40 -0
- package/wwwroot/favicon.svg +7 -0
- package/wwwroot/index.html +22 -0
- package/wwwroot/manifest.webmanifest +19 -0
- package/wwwroot/robots.txt +4 -0
- package/wwwroot/service-worker.js +7 -0
- package/wwwroot/sitemap.xml +39 -0
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
function xn(e=""){return{runtimePrompt:Sn(e),allowedToolNames:[],allowedToolPrefixes:[],enabledPluginIds:[]}}function Pe(e){return $o(e)?{runtimePrompt:Sn(e.runtimePrompt??e.RuntimePrompt),allowedToolNames:he(at(e.allowedToolNames??e.AllowedToolNames)),allowedToolPrefixes:he(at(e.allowedToolPrefixes??e.AllowedToolPrefixes)),enabledPluginIds:he(at(e.enabledPluginIds??e.EnabledPluginIds))}:xn()}function He(e){return e.allowedToolNames.length>0||e.allowedToolPrefixes.length>0}function Ye(e){return e.enabledPluginIds.length>0}function zt(e,t){const n=Pe(e),o=t?Pe(t):null;if(!o)return n;const r=Co([n.runtimePrompt.trim(),o.runtimePrompt.trim()].filter(Boolean)),s=He(n)||He(o),i=Ye(n)||Ye(o);return{runtimePrompt:r.join(`
|
|
2
|
+
|
|
3
|
+
`),allowedToolNames:s?he([...n.allowedToolNames,...o.allowedToolNames]):[],allowedToolPrefixes:s?he([...n.allowedToolPrefixes,...o.allowedToolPrefixes]):[],enabledPluginIds:i?he([...n.enabledPluginIds,...o.enabledPluginIds]):[]}}function va(e){const t=Pe(e);return["Agent Runtime Profile:",`Runtime prompt: ${t.runtimePrompt||"-"}`,`Allowed tool names: ${t.allowedToolNames.join(", ")||"allow-all"}`,`Allowed tool prefixes: ${t.allowedToolPrefixes.join(", ")||"allow-all"}`,`Enabled plugins: ${t.enabledPluginIds.join(", ")||"allow-all"}`,`Tool restricted: ${He(t)?"yes":"no"}`,`Plugin restricted: ${Ye(t)?"yes":"no"}`].join(`
|
|
4
|
+
`)}function ba(e){const t=Pe(e),n=t.allowedToolNames.length+t.allowedToolPrefixes.length,o=t.enabledPluginIds.length;return n===0&&o===0&&!t.runtimePrompt?"allow-all":[t.runtimePrompt?"prompt":"",n>0?`${n} tool rule${n===1?"":"s"}`:"",o>0?`${o} plugin${o===1?"":"s"}`:""].filter(Boolean).join(" / ")}function Sn(e){return String(e??"").trim()}function at(e){return Array.isArray(e)?e.map(t=>String(t).trim()).filter(Boolean).slice(0,48):typeof e=="string"?e.split(/\r?\n|,/).map(t=>t.trim()).filter(Boolean).slice(0,48):[]}function Co(e){return e.filter((t,n)=>e.indexOf(t)===n)}function he(e){const t=new Set,n=[];for(const o of e){const r=o.trim();if(!r)continue;const s=r.toLowerCase();t.has(s)||(t.add(s),n.push(r))}return n}function $o(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}const Tn="Tool: Browser.Actionbook",jt="Args:";function ya(e){if(!e||!e.trim())return null;const t=e.toLowerCase(),n=t.indexOf(Tn.toLowerCase());if(n<0)return null;const o=t.indexOf(jt.toLowerCase(),n);if(o<0)return lt("market");const r=Ro(e,o+jt.length);if(!r)return lt("market");try{const s=JSON.parse(r),i=Ln(we(s.template)||"actionbook"),a=we(s.query),l=we(s.url),c=we(s.targetDomain),u=xo(s.includeSnapshot)??!1,d=So(s.maxChars),p=we(s.followText);return Pn(i,a,l,c,u,d,p)}catch{return lt("actionbook")}}function Io(e){const t={template:Ln(e.template||"market"),query:We(e.query),url:We(e.url),targetDomain:We(e.targetDomain),includeSnapshot:e.includeSnapshot===!0,maxChars:Number.isFinite(e.maxChars)?Math.max(0,Math.trunc(e.maxChars)):void 0,followText:We(e.followText)};return[Tn,`Args: ${JSON.stringify(t)}`].join(`
|
|
5
|
+
`)}function ka(e){return e?["Browser.Actionbook Hint:",`- Template: ${e.template}`,e.query?`- Query: ${e.query}`:"",e.url?`- Url: ${e.url}`:"",e.targetDomain?`- Target domain: ${e.targetDomain}`:"",`- Include snapshot: ${e.includeSnapshot?"yes":"no"}`,e.maxChars!=null?`- Max chars: ${e.maxChars}`:"",e.followText?`- Follow text: ${e.followText}`:""].filter(Boolean).join(`
|
|
6
|
+
`):""}function lt(e){return Pn(e,"","","",!1,null,"")}function Pn(e,t,n,o,r,s,i){const a=ct(n?To(n)||n:o||t,80),l=a?`Actionbook - ${e} - ${a}`:`Actionbook - ${e}`,c=[`Template: ${e}`,n?`Url: ${n}`:"",t?`Query: ${t}`:"",o?`Target domain: ${o}`:"",s!=null?`Max chars: ${s}`:"",`Include snapshot: ${r?"yes":"no"}`,i?`Follow text: ${i}`:""].filter(Boolean).join(`
|
|
7
|
+
`);return{template:e,query:t,url:n,targetDomain:o,includeSnapshot:r,maxChars:s,followText:i,railText:`B - ${e}`,summaryText:l,tooltip:c}}function Ro(e,t){const n=e.indexOf("{",t);if(n<0)return"";let o=0,r=!1,s=!1,i="";for(let a=n;a<e.length;a+=1){const l=e[a];if(i+=l,r){if(s){s=!1;continue}if(l==="\\"){s=!0;continue}l==='"'&&(r=!1);continue}if(l==='"'){r=!0;continue}if(l==="{"&&(o+=1),l==="}"&&(o-=1,o===0))return i}return""}function we(e){return typeof e=="string"?e.trim():e==null?"":String(e).trim()}function xo(e){if(typeof e=="boolean")return e;if(typeof e=="string"){if(e.toLowerCase()==="true")return!0;if(e.toLowerCase()==="false")return!1}return null}function So(e){const t=typeof e=="number"?e:typeof e=="string"?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)?Math.trunc(t):null}function Ln(e){return(e||"actionbook").trim().toLowerCase()||"actionbook"}function We(e){return(e||"").trim()||void 0}function ct(e,t){const n=e.replace(/\r?\n|\r/g," ").trim();return n.length<=t?n:`${n.slice(0,t).trimEnd()}...`}function To(e){try{return new URL(e).host}catch{return""}}const ut="CodeWorkflow",Kt="Code Workflow",Vt=160,Qt="Documents/MindExecution/Workspace",Mn=["rm -rf","del /s","format","shutdown","reboot","mkfs","dd if=",":(){","wget ","curl ","| sh","|sh","| bash","|bash","chmod 777","chown root"],Ht=["NodeMemory.Recall","SearchInFiles / ReadFileRange / Code.Actionbook","ApplyPatch or focused WriteFile","RunBuild / RunTests / GetDiagnostics / Test.Runbook","NodeMemory.Upsert and RecordArtifact","FinalAnswer with edits, validation, and residual risks"];function Z(e){return typeof e=="string"?e.trim():e==null?"":String(e).trim()}function Po(e,t=160){const n=Z(e).replace(/\s+/g," ");return n.length<=t?n:`${n.slice(0,Math.max(0,t-3)).trimEnd()}...`}function Yt(e){const t=new Set,n=[];for(const o of e){const r=Z(o),s=r.toLowerCase();!r||t.has(s)||(t.add(s),n.push(r))}return n}function _e(e,t,n,o){const r=typeof e=="number"?e:Number(e),s=Number.isFinite(r)?Math.trunc(r):t;return Math.min(o,Math.max(n,s))}function Lo(e){const t=Z(e).toLowerCase();return t==="bug-fix"?"bugfix":t==="code-review"?"review":t==="implementation"?"implementation":t==="ops-automation"?"ops":t||"implementation"}function Mo(e){const t=`${e.objective||""}
|
|
8
|
+
${e.plannerSummary||""}
|
|
9
|
+
${(e.plannedTools||[]).join(`
|
|
10
|
+
`)}`.toLowerCase();return t.includes("bug")||t.includes("fix")||t.includes("error")?"bugfix":t.includes("review")||t.includes("검토")?"review":t.includes("ops")||t.includes("deploy")||t.includes("automation")?"ops":Lo(Z(e.requestedRole).toLowerCase().includes("review")?"review":"implementation")}function No(e){const t=e.toLowerCase();return Mn.find(n=>t.includes(n))||""}function Eo(e){const t=Z(e.validationCommand);if(t)return t;const n=(e.plannedTools||[]).join(" ").toLowerCase();return n.includes("getdiagnostics")?"npx tsc --noEmit -p tsconfig.json --pretty false":n.includes("runtests")||n.includes("test.runbook")?"npm test":"npm run build"}function Jt(e,t){const n=(e.plannedTools||[]).map(r=>Z(r).toLowerCase());if(n.length===0)return!0;const o=t.toLowerCase();return n.some(r=>r===o||r.includes(o))}function qo(e){return Z(e).toLowerCase()!=="purellm"}function wa(e={}){const t=qo(e.executionMode),n=Yt(e.linkedFiles||[]).slice(0,12),o=Mo(e),r=_e(n.length||6,6,1,12),s=_e(700,700,250,2e3),i=Eo(e),a=No(i),l=_e(45e3,45e3,1e3,18e4),c=_e(2200,2200,500,6e3),u=Yt(e.plannedTools||[]),d=t&&Jt(e,"Code.Actionbook"),p=t&&Jt(e,"Test.Runbook")&&!a,f={name:"Code.Actionbook",requiresApproval:!1,enabled:d,summary:d?`Inspect ${n.length||r} focused file slot(s) with ${o} guidance.`:"Code.Actionbook is inactive for this execution mode or tool selection.",args:{template:o,objective:Po(e.objective||e.plannerSummary,180),files:n.slice(0,r),directory:Z(e.workingDir)||Qt,includeDirectoryPreview:!0,maxFiles:r,perFileChars:s}},g={name:"Test.Runbook",requiresApproval:!0,enabled:p,summary:a?`Dangerous command pattern detected: ${a}`:p?`Plan approval-gated validation command: ${i}`:"Test.Runbook is inactive for this execution mode or tool selection.",args:{command:i,workingDir:Z(e.workingDir)||Qt,timeoutMs:l,maxChars:c,dangerousPattern:a||null}};return{pluginId:ut,displayName:Kt,promptPriority:Vt,activeForMode:t,codeActionbook:f,testRunbook:g,promptLoop:[...Ht],dangerousPatterns:[...Mn],selectedToolNames:u,projectionLines:[`Plugin: ${ut} / ${Kt} / priority ${Vt}`,`Active for mode: ${t?"yes":"no"}`,`Code.Actionbook: ${f.enabled?o:"inactive"} / files ${n.slice(0,r).length}/${r} / chars ${s}`,`Test.Runbook: ${g.enabled?"approval-gated":"inactive"} / timeout ${l} / maxChars ${c}`,`Dangerous command: ${a||"none"}`,`Loop: ${Ht.join(" -> ")}`],governanceLines:["CodeWorkflowAgentPlugin exposes PluginId CodeWorkflow, DisplayName Code Workflow, PromptPriority 160, and stays inactive only for PureLLM mode.","Code.Actionbook is non-approval, normalizes templates, caps maxFiles to 1..12, caps perFileChars to 250..2000, and returns compact file/directory inspection JSON in the original service.","Test.Runbook requires approval, rejects dangerous command patterns, caps timeoutMs to 1000..180000, caps maxChars to 500..6000, and summarizes stdout/stderr instead of dumping full output.","The original prompt loop prefers NodeMemory.Recall, focused file inspection, ApplyPatch, safe validation, NodeMemory.Upsert, RecordArtifact, and FinalAnswer.","React Code Workflow Tooling is a browser-local plan only and must not run shell commands, read files, list directories, call BridgeService, LocalBridge, live AI, Cloudflare, billing, npm publish, or evidence-save adapters."],summaryLine:`${ut} projects ${f.enabled?"active":"inactive"} inspection and ${g.enabled?"approval-gated validation":"no validation run"} for the selected command.`}}function Aa(e){return["Code Workflow Tooling:",...e.projectionLines,"Tool plans:",`- ${e.codeActionbook.name}: ${e.codeActionbook.summary}`,`- ${e.testRunbook.name}: ${e.testRunbook.summary}`,"Governance:",...e.governanceLines.map(t=>`- ${t}`)].join(`
|
|
11
|
+
`)}const dt="CodeNoteCanvas",Xt="Code Note Canvas",Zt=150,mt="AgentCommandCanvas",en="Agent Canvas",tn=145,nn=["Canvas.ListCodeNotes","Canvas.CreateCodeNote or Canvas.UpdateCodeNote","Code.Actionbook and implementation tools","Canvas.SetCodeNoteState or Canvas.LinkCodeNote"],on=["Canvas.ListAgentCommands","Canvas.CreateAgentCommand or Canvas.UpdateAgentCommand","Canvas.PlanAgentCommand","Canvas.SetAgentCommandState"];function P(e){return typeof e=="string"?e.trim():e==null?"":String(e).trim()}function ge(e,t=160){const n=P(e).replace(/\s+/g," ");return n.length<=t?n:`${n.slice(0,Math.max(0,t-3)).trimEnd()}...`}function te(e,t=20){const n=new Set,o=[];for(const r of e){const s=P(r),i=s.toLowerCase();if(!(!s||n.has(i))&&(n.add(i),o.push(s),o.length>=t))break}return o}function Je(e,t,n,o){const r=typeof e=="number"?e:Number(e),s=Number.isFinite(r)?Math.trunc(r):t;return Math.min(o,Math.max(n,s))}function Fo(e){return P(e).toLowerCase()!=="purellm"}function Bo(e){const t=e.command,n=[t==null?void 0:t.objective,t==null?void 0:t.plannerSummary,...(t==null?void 0:t.plannedTools)||[],...(t==null?void 0:t.plannedConcepts)||[]].join(`
|
|
12
|
+
`).toLowerCase();return n.includes("bug")||n.includes("fix")||n.includes("error")?"Bugfix":n.includes("refactor")||n.includes("cleanup")?"Refactor":n.includes("test")||n.includes("verify")||n.includes("validation")?"Test":n.includes("resource")||n.includes("docs")||n.includes("document")?"Resource":"Feature"}function je(e){var t,n,o;return!!(P((t=e.command)==null?void 0:t.id)||P((n=e.command)==null?void 0:n.objective)||P((o=e.command)==null?void 0:o.title))}function Oo(e,t){const n=e.command,o=e.linkedNotes||[],r=te(o.flatMap(f=>f.relatedFiles||[]),12),s=te(o.flatMap(f=>f.relatedSymbols||[]),12),i=te(o.map(f=>f.id),12),a=Je(e.allNoteCount||50,50,1,200),l=Bo(e),c=o[0]||null,u=o.length>0,d=o.some(f=>(f.artifacts||[]).length>0),p=ge((n==null?void 0:n.objective)||(n==null?void 0:n.title)||(c==null?void 0:c.title)||"Code Note",180);return[{name:"Canvas.ListCodeNotes",requiresApproval:!1,enabled:t,summary:t?`List up to ${a} Code Note memo nodes from the current canvas.`:"PureLLM mode disables Code Note canvas tools.",args:{max:a,currentLinkedNotes:o.length}},{name:"Canvas.CreateCodeNote",requiresApproval:!1,enabled:t,summary:t?`Create a structured ${l} Code Note draft before implementation.`:"PureLLM mode disables Code Note creation.",args:{title:p,body:p,why:ge((n==null?void 0:n.constraints)||(n==null?void 0:n.plannerSummary)||"Keep implementation rationale visible on the canvas.",180),kind:l,relatedFiles:r,relatedSymbols:s}},{name:"Canvas.UpdateCodeNote",requiresApproval:!1,enabled:t&&u,summary:u?`Update ${o.length} linked Code Note memo node(s).`:"No linked Code Note is selected for update.",args:{nodeId:P(c==null?void 0:c.id)||null,status:P(c==null?void 0:c.status)||null,relatedFiles:r,relatedSymbols:s}},{name:"Canvas.LinkCodeNote",requiresApproval:!1,enabled:t&&u&&(d||(n==null?void 0:n.status)==="done"),summary:u?"Link changed files, mission/work-item output, and artifacts back to Code Notes.":"A linked Code Note is required before output can be linked.",args:{nodeId:P(c==null?void 0:c.id)||null,changedFiles:r,outputArtifacts:te(o.flatMap(f=>f.artifacts||[]),12),mergeRelatedFiles:!0}},{name:"Canvas.SetCodeNoteState",requiresApproval:!1,enabled:t&&u,summary:u?"Set Code Note status and syncState after planning, implementation, or review.":"No linked Code Note state is ready to update.",args:{nodeId:P(c==null?void 0:c.id)||null,status:(n==null?void 0:n.status)==="done"?"Implemented":"Proposed",syncState:r.length>0?"Planned":"Unlinked",linkedCodeNoteNodeIds:i}}]}function Do(e,t){const n=e.command,o=te((n==null?void 0:n.linkedNoteIds)||[],12),r=te((n==null?void 0:n.plannedSkills)||[],12),s=te((n==null?void 0:n.plannedTools)||[],12),i=te((n==null?void 0:n.plannedConcepts)||[],12),a=Je(e.allCommandCount||50,50,1,200),l=je(e),c=ge((n==null?void 0:n.objective)||(n==null?void 0:n.title)||"Agent command",180),u=t&&l&&!!P(n==null?void 0:n.objective);return[{name:"Canvas.ListAgentCommands",requiresApproval:!1,enabled:t,summary:t?`List up to ${a} Agent Command memo nodes from the current canvas.`:"PureLLM mode disables Agent Command canvas tools.",args:{max:a,selectedCommandId:P(n==null?void 0:n.id)||null}},{name:"Canvas.CreateAgentCommand",requiresApproval:!1,enabled:t,summary:t?"Create a short operational Agent Command memo with objective, constraints, role, and mode.":"PureLLM mode disables Agent Command creation.",args:{objective:c,title:ge((n==null?void 0:n.title)||"Agent",80),constraints:ge((n==null?void 0:n.constraints)||"",180),mode:s.some(d=>d.toLowerCase().includes("code"))||o.length>0?"Coding":"Task",requestedRole:P(n==null?void 0:n.requestedRole)||"Ceo"}},{name:"Canvas.UpdateAgentCommand",requiresApproval:!1,enabled:t&&l,summary:l?"Update the selected Agent Command memo with planner state and linked Code Notes.":"No selected Agent Command is ready to update.",args:{nodeId:P(n==null?void 0:n.id)||null,status:P(n==null?void 0:n.status)||null,plannerSummary:ge((n==null?void 0:n.plannerSummary)||"",220),plannedSkills:r,plannedTools:s,plannedConcepts:i,linkedCodeNoteNodeIds:o}},{name:"Canvas.PlanAgentCommand",requiresApproval:!1,enabled:u,summary:u?"Expand the selected Agent Command into requested role, tools, skills, concepts, and linked Code Notes.":"A selected command with a non-empty objective is required before planning.",args:{nodeId:P(n==null?void 0:n.id)||null}},{name:"Canvas.SetAgentCommandState",requiresApproval:!1,enabled:t&&l,summary:l?"Reflect whether the command is planned, running, completed, failed, or cancelled.":"No selected Agent Command state is ready to update.",args:{nodeId:P(n==null?void 0:n.id)||null,status:P(n==null?void 0:n.status)||"Planned"}}]}function Ca(e={}){var g;const t=Fo(e.executionMode),o=(e.linkedNotes||[]).length,r=Je(e.allCommandCount||(je(e)?1:0),je(e)?1:0,0,200),s=Je(e.allNoteCount||o,o,0,200),i=je(e),a=t&&i&&!!P((g=e.command)==null?void 0:g.objective),l=Oo(e,t),c=Do(e,t),u=l.filter(m=>m.enabled).length,d=c.filter(m=>m.enabled).length,p={pluginId:dt,displayName:Xt,promptPriority:Zt,activeForMode:t,tools:l,promptLoop:[...nn],summaryLine:`${dt} has ${u}/${l.length} canvas note tools ready.`},f={pluginId:mt,displayName:en,promptPriority:tn,activeForMode:t,tools:c,promptLoop:[...on],summaryLine:`${mt} has ${d}/${c.length} canvas command tools ready.`};return{activeForMode:t,codeNotePlugin:p,agentCommandPlugin:f,linkedNoteCount:o,totalCommandCount:r,totalNoteCount:s,planReady:a,projectionLines:[`Plugin: ${dt} / ${Xt} / priority ${Zt}`,`Plugin: ${mt} / ${en} / priority ${tn}`,`Active for mode: ${t?"yes":"no"}`,`Canvas counts: ${r} command(s), ${s} note(s), ${o} linked note(s)`,`Code Note loop: ${nn.join(" -> ")}`,`Agent Command loop: ${on.join(" -> ")}`,`Plan ready: ${a?"yes":"no"}`],governanceLines:["CodeNoteCanvasAgentPlugin exposes PluginId CodeNoteCanvas, DisplayName Code Note Canvas, PromptPriority 150, and five Canvas.* Code Note tools.","AgentCommandCanvasAgentPlugin exposes PluginId AgentCommandCanvas, DisplayName Agent Canvas, PromptPriority 145, and five Canvas.* Agent Command tools.","Both original plugins are inactive only for PureLLM mode and all listed tools are non-approval canvas state tools.","React Canvas Agent Tooling is a browser-local projection only and must not mutate canvas nodes, call scoped services, BridgeService, LocalBridge, live AI, filesystem, Cloudflare, billing, npm publish, or evidence-save adapters."],summaryLine:`Canvas Agent Tooling projects ${u+d}/${l.length+c.length} ready canvas tools for the selected command.`}}function $a(e){return["Canvas Agent Tooling:",...e.projectionLines,"Code Note tools:",...e.codeNotePlugin.tools.map(t=>`- ${t.name}: ${t.summary}`),"Agent Command tools:",...e.agentCommandPlugin.tools.map(t=>`- ${t.name}: ${t.summary}`),"Governance:",...e.governanceLines.map(t=>`- ${t}`)].join(`
|
|
13
|
+
`)}const Wo=[{name:"FinalAnswer",pluginId:null,requiresApproval:!1},{name:"WriteFile",pluginId:null,requiresApproval:!0},{name:"ReadFile",pluginId:null,requiresApproval:!1},{name:"ExecuteShell",pluginId:null,requiresApproval:!0},{name:"ListDirectory",pluginId:null,requiresApproval:!1},{name:"CreateDirectory",pluginId:null,requiresApproval:!0},{name:"ReadFileRange",pluginId:null,requiresApproval:!1},{name:"SearchInFiles",pluginId:null,requiresApproval:!1},{name:"ApplyPatch",pluginId:null,requiresApproval:!1},{name:"RunBuild",pluginId:null,requiresApproval:!1},{name:"RunTests",pluginId:null,requiresApproval:!1},{name:"GetDiagnostics",pluginId:null,requiresApproval:!1},{name:"RecordArtifact",pluginId:null,requiresApproval:!1},{name:"NodeMemory.Upsert",pluginId:null,requiresApproval:!1},{name:"NodeMemory.Recall",pluginId:null,requiresApproval:!1}],_o=[{name:"Code.Actionbook",pluginId:"CodeWorkflow",requiresApproval:!1},{name:"Test.Runbook",pluginId:"CodeWorkflow",requiresApproval:!0},{name:"Canvas.ListCodeNotes",pluginId:"CodeNoteCanvas",requiresApproval:!1},{name:"Canvas.CreateCodeNote",pluginId:"CodeNoteCanvas",requiresApproval:!1},{name:"Canvas.UpdateCodeNote",pluginId:"CodeNoteCanvas",requiresApproval:!1},{name:"Canvas.LinkCodeNote",pluginId:"CodeNoteCanvas",requiresApproval:!1},{name:"Canvas.SetCodeNoteState",pluginId:"CodeNoteCanvas",requiresApproval:!1},{name:"Canvas.ListAgentCommands",pluginId:"AgentCommandCanvas",requiresApproval:!1},{name:"Canvas.CreateAgentCommand",pluginId:"AgentCommandCanvas",requiresApproval:!1},{name:"Canvas.UpdateAgentCommand",pluginId:"AgentCommandCanvas",requiresApproval:!1},{name:"Canvas.PlanAgentCommand",pluginId:"AgentCommandCanvas",requiresApproval:!1},{name:"Canvas.SetAgentCommandState",pluginId:"AgentCommandCanvas",requiresApproval:!1},{name:"Web.Search",pluginId:"WebResearch",requiresApproval:!1},{name:"Web.FetchPage",pluginId:"WebResearch",requiresApproval:!1},{name:"Download.File",pluginId:"WebResearch",requiresApproval:!1},{name:"Extract.Structured",pluginId:"WebResearch",requiresApproval:!1},{name:"Evidence.Save",pluginId:"WebResearch",requiresApproval:!1},{name:"Browser.Open",pluginId:"WebResearch",requiresApproval:!1},{name:"Browser.Actionbook",pluginId:"WebResearch",requiresApproval:!1},{name:"Browser.Snapshot",pluginId:"WebResearch",requiresApproval:!1},{name:"Browser.Extract",pluginId:"WebResearch",requiresApproval:!1},{name:"Browser.Act",pluginId:"WebResearch",requiresApproval:!1}],Xe=[...Wo,..._o];Xe.map(e=>e.name);const Uo=["rm -rf","del /s","format","shutdown","reboot","mkfs","dd if=",":(){","wget ","curl ","| sh","|sh","| bash","|bash","chmod 777","chown root"];function ot(e){return typeof e=="string"?e.trim():e==null?"":String(e).trim()}function Go(e){const t=new Set,n=[];for(const o of e){const r=ot(o),s=r.toLowerCase();!r||t.has(s)||(t.add(s),n.push(r))}return n}function Ke(e,t){const n=t.toLowerCase();return e.some(o=>o.toLowerCase()===n)}function zo(e){var n;const t=ot(e);return t&&((n=Xe.find(o=>o.name.toLowerCase()===t.toLowerCase()))==null?void 0:n.name)||""}function jo(e,t){const n=t.toLowerCase();return e.find(o=>n.startsWith(o.toLowerCase()))||""}function Ko(e,t){return Ke(e,t)?!0:t.toLowerCase()!=="webresearch"?!1:Ke(e,"web-research")||Ke(e,"browser-automation")}function Vo(e){return ot(e).toLowerCase()==="purellm"}function Qo(e,t){const n=e.toLowerCase();return t.some(o=>{const r=o.toLowerCase();return r===n||n.startsWith(r)||r.startsWith(n)})}function Ho(e){const t=e.toLowerCase();return Uo.find(n=>t.includes(n))||""}function Yo(e,t,n,o,r,s,i){const a=Qo(e.name,n);return e.pluginId&&(i||s&&!Ko(o,e.pluginId))?{...e,enabled:!1,requested:a,reason:"plugin-disabled"}:r?Ke(t.allowedToolNames,e.name)?{...e,enabled:!0,requested:a,reason:"allowed-name"}:jo(t.allowedToolPrefixes,e.name)?{...e,enabled:!0,requested:a,reason:"allowed-prefix"}:{...e,enabled:!1,requested:a,reason:"tool-policy-blocked"}:{...e,enabled:!0,requested:a,reason:"allow-all"}}function Ia(e={}){const t=Pe(e.runtimeProfile),n=Go(e.plannedTools||[]),o=He(t),r=Ye(t),s=Vo(e.executionMode),i=t.enabledPluginIds,a=Xe.map(g=>Yo(g,t,n,i,o,r,s)),l=a.filter(g=>g.enabled).map(g=>g.name),c=a.filter(g=>g.enabled&&g.requiresApproval).map(g=>g.name),u=a.filter(g=>g.requested&&!g.enabled).map(g=>g.name),d=n.filter(g=>!Xe.some(m=>m.name.toLowerCase()===g.toLowerCase())),p=Ho(ot(e.validationCommand)),f=u.length+d.length;return{totalToolCount:a.length,enabledToolCount:l.length,blockedToolCount:a.length-l.length,approvalToolCount:c.length,requestedToolCount:n.length,requestedBlockedCount:f,toolRestricted:o,pluginRestricted:r,dangerousPattern:p,tools:a,requestedTools:n,enabledTools:l,approvalTools:c,blockedRequestedTools:[...u,...d],projectionLines:[`Tool policy: ${o?"restricted":"allow-all"} / plugin policy: ${r||s?"restricted":"allow-all"}`,`Enabled tools: ${l.length}/${a.length}`,`Approval tools: ${c.join(", ")||"none"}`,`Requested tools: ${n.join(", ")||"none"}`,`Blocked requested: ${f>0?[...u,...d].join(", "):"none"}`,`Dangerous validation command: ${p||"none"}`],governanceLines:["ToolSystem registers built-in tools and plugin tools under plugin ids, then exposes only enabled tools through GetAllTools.","Disabled plugin tools win before allowed exact-name and allowed-prefix checks, matching the original IsToolEnabled order.","Allowed tool policy is allow-all when no exact names or prefixes are present; otherwise exact names and prefixes are the only enabled path.","RequiresApproval is meaningful only for enabled registered tools, matching the original RequiresApproval guard.","React Agent Tool System is a browser-local projection only and must not execute tools, write files, run shell commands, call BridgeService, LocalBridge, live AI, Cloudflare, billing, npm publish, or evidence-save adapters."],summaryLine:`ToolSystem projects ${l.length}/${a.length} enabled tool(s), ${c.length} approval gate(s), and ${f} blocked requested tool(s).`}}function Ra(e){return["Agent Tool System:",...e.projectionLines,"Enabled sample:",`- ${e.enabledTools.slice(0,12).join(", ")||"none"}`,"Governance:",...e.governanceLines.map(t=>`- ${t}`)].join(`
|
|
14
|
+
`)}function Jo(e){return typeof e=="string"?e.trim():e==null?"":String(e).trim()}function Ue(e){const t=new Set,n=[];for(const o of e){const r=Jo(o),s=r.toLowerCase();!r||t.has(s)||(t.add(s),n.push(r))}return n}function Xo(e){return/^[A-Z][A-Za-z0-9]*(\.[A-Z][A-Za-z0-9]*)+$/.test(e)||/^(ReadFile|WriteFile|FinalAnswer|ExecuteShell|RunBuild|RunTests|GetDiagnostics|ApplyPatch|SearchInFiles|ReadFileRange|RecordArtifact|CreateDirectory|ListDirectory)$/i.test(e)}function Zo(e={}){const t=Ue(e.plannedTools||[]),n=Ue(e.plannedConcepts||[]),o=[],r=[],s=[];for(const u of t){const d=zo(u);d?o.push(d):(r.push(u),Xo(u)&&s.push(u))}const i=Ue([...n,...r]),a=Ue(o),l=i,c=r.length+s.length;return{actualTools:a,conceptHints:i,misplacedConcepts:r,unknownToolLikeItems:s,repairedPlannedTools:a,repairedPlannedConcepts:l,toolCount:a.length,conceptCount:l.length,driftCount:c,needsRepair:c>0||a.length!==t.length||l.length!==n.length,projectionLines:[`Actual tools: ${a.join(", ")||"none"}`,`Concept hints: ${l.join(", ")||"none"}`,`Misplaced concepts: ${r.join(", ")||"none"}`,`Unknown tool-like items: ${s.join(", ")||"none"}`],governanceLines:["AgentCommandPlannerService writes real tool names into PlannedTools and planning vocabulary into PlannedConcepts.","React repairs stored or manually edited PlannedTools by keeping only registered ToolSystem names in the tool lane.","Non-registered planning phrases move to PlannedConcepts so ToolSystem policy does not confuse concepts with executable tools.","Unknown tool-like names stay visible as drift until the registry or the plan is corrected.","Agent Planned Work is a browser-local projection only and must not execute tools, write files, run shell commands, call BridgeService, LocalBridge, live AI, Cloudflare, billing, npm publish, or evidence-save adapters."],summaryLine:`Planned work keeps ${a.length} actual tool(s), ${l.length} concept hint(s), and ${c} drift item(s).`}}function xa(e={}){const t=Zo(e);return{plannedTools:t.repairedPlannedTools,plannedConcepts:t.repairedPlannedConcepts}}function Sa(e){return["Agent Planned Work:",...e.projectionLines,"Governance:",...e.governanceLines.map(t=>`- ${t}`)].join(`
|
|
15
|
+
`)}function Nn(e){return typeof e=="string"?e.trim():e==null?"":String(e).trim()}function ft(e,t=12){const n=new Set,o=[];for(const r of e){const s=Nn(r),i=s.toLowerCase();if(!(!s||n.has(i))&&(n.add(i),o.push(s),o.length>=t))break}return o}function er(e){const t=e.toLowerCase(),n=o=>o.some(r=>t.includes(r));return n(["bug","fix","error","exception","crash"])?"Bugfix":n(["refactor","cleanup","clean up","restructure"])?"Refactor":n(["test","verify","verification","qa"])?"Test":n(["resource","docs","document","readme","asset"])?"Resource":"Feature"}function tr(e){const t=e.trim();return t.length<=28?t:`${t.slice(0,28).trimEnd()}...`}function Ta(e){const t=Nn(e.goal);if(!t)return{goal:"",inferredKind:"Feature",relatedFiles:[],relatedNamespaces:[],relatedSymbols:[],syncState:"unlinked",drafts:[],summaryLine:"No Code Note plan because the goal is empty.",projectionLines:["CodeNotePlannerService parity: empty goals create no notes."]};const n=Array.isArray(e.contextRefs)?e.contextRefs:[],o=ft(n.map(u=>u.filePath)),r=ft(n.map(u=>u.namespace)),s=ft(n.map(u=>u.label)),i=er(t),a=tr(t),l=o.length>0?"planned":"unlinked",c=[{title:`${a} - implementation block`,body:`Define the implementation block for "${t}" before changing code.`,kind:i,status:"proposed",syncState:l,why:"Keep the requested change separate from execution so the implementation boundary is visible before edits.",relatedFiles:o,relatedNamespaces:r,relatedSymbols:s,acceptanceCriteria:["The responsibility of the change is described as a bounded implementation block.","The affected files or symbols are traceable before coding starts."],phase:"implementation"},{title:`${a} - links and contracts`,body:`Capture the dependency, file, route, and contract links that "${t}" must preserve.`,kind:i==="Test"?"Feature":i,status:"proposed",syncState:l,why:"Stabilize related files and contracts first so the work does not spread through hidden coupling.",relatedFiles:o,relatedNamespaces:r,relatedSymbols:s,acceptanceCriteria:["At least one related file or symbol is connected when graph context exists.","The expected contract impact is stated before the note can be approved."],phase:"contracts"},{title:`${a} - verification`,body:`Define the verification criteria for completing "${t}".`,kind:"Test",status:"proposed",syncState:l,why:"Separate implementation from verification so the note cannot be reviewed without evidence.",relatedFiles:o,relatedNamespaces:r,relatedSymbols:s,acceptanceCriteria:["The done criteria are clear enough to verify manually or through local commands.","Required tests or smoke checks are named before marking the note reviewed."],phase:"verification"}];return{goal:t,inferredKind:i,relatedFiles:o,relatedNamespaces:r,relatedSymbols:s,syncState:l,drafts:c,summaryLine:`CodeNotePlannerService parity created ${c.length} proposed note(s), ${o.length} related file(s), and ${s.length} related symbol(s).`,projectionLines:[`Goal: ${t}`,`Inferred kind: ${i}`,`Sync state: ${l}`,`Related files: ${o.join(", ")||"none"}`,`Related symbols: ${s.join(", ")||"none"}`,`Draft phases: ${c.map(u=>u.phase).join(", ")}`]}}const nr=new Set([".cs",".razor",".cshtml",".js",".jsx",".ts",".tsx",".json",".xml",".xaml",".yml",".yaml",".css",".scss",".sass",".less",".html",".sql",".py",".go",".java",".kt",".swift",".cpp",".cc",".c",".h",".hpp",".props",".targets",".csproj",".sln"]),or=new Set(["title","body","why","kind","relatedFiles","relatedSymbols","acceptanceCriteria"]);function En(e){return typeof e=="string"?e.replace(/\\/g,"/").trim():""}function It(e){const t=new Set,n=[];for(const o of e??[]){const r=En(o),s=r.toLowerCase();!r||t.has(s)||(t.add(s),n.push(r))}return n}function rn(e,t){return It([...e??[],...t??[]])}function rr(e){const t=En(e);if(!t)return!1;const n=t.lastIndexOf(".");return n<0?!1:nr.has(t.slice(n).toLowerCase())}function sr(e,t){const n=[e].map(r=>{const s=r?Date.parse(r):Number.NaN;return Number.isFinite(s)?s:Number.NaN}).filter(r=>Number.isFinite(r)),o=n.length>0?Math.max(...n):Date.now();return new Date(o).toISOString()}function Pa(e,t){const n=It(t.outputArtifacts),o=It(t.changedFiles),r=n.filter(rr),s=rn(e.relatedFiles,[...o,...r]),i=rn(e.artifacts,n);return{status:"implemented",syncState:s.length>0||i.length>0?"in-sync":"needs-review",relatedFiles:s,artifacts:i,linkedMissionId:t.missionId,linkedWorkItemId:t.workItemId,lastAppliedAt:sr(t.completedAt)}}function La(e){return e.filter(t=>t.syncState==="out-of-sync"||t.syncState==="needs-review"||t.syncState==="orphaned")}function ir(e,t){return e==="draft"?"unlinked":e==="proposed"||e==="approved"||e==="implementing"?"planned":e==="queued"||e==="blocked"?"needs-review":e==="implemented"||e==="reviewed"?"in-sync":e==="out-of-sync"?"out-of-sync":t}function Ma(e,t){return t.syncState||!e.lastAppliedAt||!Object.keys(t).some(o=>or.has(o))?t:{...t,syncState:"out-of-sync"}}function be(e){return typeof e=="string"?e.trim():e==null?"":String(e).trim()}function ar(e){return be(e)||"CEO"}function gt(e,t=24){const n=new Set,o=[];for(const r of e){const s=be(r),i=s.toLowerCase();if(!(!s||n.has(i))&&(n.add(i),o.push(s),o.length>=t))break}return o}function lr(e,t){const n=t.replace(/[^0-9]/g,"").slice(0,14)||"local";return`local-agent-mission://${e}/${n}`}function cr(e){return`local-agent-work://${e}/root`}function sn(e,t){return`local-agent-work://${e}/note/${t}`}function ur(...e){const t=new Set,n=[];for(const o of e)for(const r of o??[]){if(!r)continue;const s=be(r.filePath),i=be(r.label),a=Number.isFinite(Number(r.startLine))?Number(r.startLine):null,l=Number.isFinite(Number(r.endLine))?Number(r.endLine):null,c=`${s}:${a??""}:${l??""}:${i}`.toLowerCase();!s&&!i||t.has(c)||(t.add(c),n.push({filePath:s,startLine:a,endLine:l,label:i}))}return n}function Na(e){return be(e.objective).length>0&&e.plannedTools.length===0&&e.linkedNoteIds.length===0}function Ea(e){if(!be(e.command.objective))return null;const n=e.executedAt||new Date().toISOString(),o=e.command.linkedMissionId||lr(e.command.id,n),r=gt([...e.command.linkedNoteIds,...e.linkedNotes.map(u=>u.id)]),s=r.map(u=>sn(e.command.id,u)),i=gt([...e.command.linkedWorkItemIds||[],cr(e.command.id),...s]),a=ur(e.noteContextRefs,e.focusedContextRefs),l=gt(e.command.plannedSkills),c=ar(e.command.requestedRole);return{missionId:o,workItemIds:i,linkedNoteIds:r,requestedRole:c,plannedSkills:l,contextRefs:a,commandPatch:{status:"running",linkedMissionId:o,linkedWorkItemIds:i,lastExecutedAt:n},notePatches:r.map(u=>({id:u,status:"implementing",syncState:ir("implementing","planned"),linkedMissionId:o,linkedWorkItemId:sn(e.command.id,u)})),summaryLine:`AgentCommandExecutionService parity staged ${i.length} local work item(s), ${r.length} linked note(s), and ${a.length} context ref(s).`}}const ee=["ReadFile","WriteFile","ExecuteShell","ListDirectory","CreateDirectory","Code.Actionbook","Test.Runbook","FinalAnswer"],ue=["ReadFile","ExecuteShell","ListDirectory","Code.Actionbook","Test.Runbook","FinalAnswer"],B=["ReadFile","WriteFile","ListDirectory","CreateDirectory","Web.Search","Web.FetchPage","Download.File","Extract.Structured","Evidence.Save","Browser.Actionbook","Browser.Open","Browser.Snapshot","Browser.Extract","Browser.Act","FinalAnswer"],Ae=["ReadFile","ListDirectory","Canvas.ListCodeNotes","Canvas.CreateCodeNote","Canvas.UpdateCodeNote","Canvas.SetCodeNoteState","Canvas.LinkCodeNote","FinalAnswer"],Rt=[{id:"CEO",displayName:"CEO",iconLabel:"CEO",summary:"Delegates, prioritizes, synthesizes, and keeps mission-level decisions clear.",cssClass:"ceo",canDelegate:!0,runtimeProfile:{runtimePrompt:"Role: CEO. Focus on delegation, prioritization, synthesis, and mission-level decision making. Prefer read-only inspection and concise summaries.",allowedToolNames:["FinalAnswer","ReadFile","ListDirectory"],allowedToolPrefixes:["Canvas."],enabledPluginIds:[]}},{id:"Planner",displayName:"Planner",iconLabel:"PLAN",summary:"Breaks goals into concrete work items, dependencies, and execution order.",cssClass:"planner",canDelegate:!0,runtimeProfile:{runtimePrompt:"Role: Planner. Break goals into concrete work items, identify dependencies, and keep plans actionable. Prefer inspection tools and structured planning over direct mutation.",allowedToolNames:["FinalAnswer","ReadFile","ListDirectory"],allowedToolPrefixes:["Canvas."],enabledPluginIds:[]}},{id:"Researcher",displayName:"Researcher",iconLabel:"RES",summary:"Collects evidence from workspace and public sources, then writes concise briefs.",cssClass:"researcher",canDelegate:!1,runtimeProfile:{runtimePrompt:"Role: Researcher. Gather facts from available workspace context and external public sources. Prefer Web.Search -> Web.FetchPage or Browser.Actionbook -> Extract.Structured -> Evidence.Save, then stop once enough evidence is gathered.",allowedToolNames:B,allowedToolPrefixes:["Canvas."],enabledPluginIds:["WebResearch"]}},{id:"Programmer",displayName:"Programmer",iconLabel:"</>",summary:"Reads the codebase carefully, patches narrowly, and validates often.",cssClass:"programmer",canDelegate:!1,runtimeProfile:{runtimePrompt:"Role: Programmer. Read the codebase carefully before editing, keep changes minimal, and validate often. Prefer Code.Actionbook, ApplyPatch, RunBuild, and RunTests over broad shell work.",allowedToolNames:[...ee,"ApplyPatch","RunBuild","RunTests","GetDiagnostics","RecordArtifact","NodeMemory.Upsert","NodeMemory.Recall"],allowedToolPrefixes:["Concept.","Canvas."],enabledPluginIds:["Concept","CodeWorkflow","CodeNoteCanvas","AgentCommandCanvas"]}},{id:"Reviewer",displayName:"Reviewer",iconLabel:"QA",summary:"Inspects implementation details, regression risk, and verification evidence.",cssClass:"reviewer",canDelegate:!1,runtimeProfile:{runtimePrompt:"Role: Reviewer. Inspect implementation details, verify correctness, and surface concrete risks or regressions. Prefer targeted file inspection and tests as evidence.",allowedToolNames:[...ue,"RunTests","GetDiagnostics","RecordArtifact","NodeMemory.Upsert","NodeMemory.Recall"],allowedToolPrefixes:["Canvas."],enabledPluginIds:[]}},{id:"Marketer",displayName:"Marketer",iconLabel:"MKT",summary:"Turns product context into messaging, positioning, and growth experiments.",cssClass:"marketer",canDelegate:!1,runtimeProfile:{runtimePrompt:"Role: Marketer. Produce messaging, positioning, and experiment ideas from the available context. Stay focused on briefs and summaries rather than filesystem mutation.",allowedToolNames:["FinalAnswer","ReadFile","ListDirectory"],allowedToolPrefixes:["Canvas."],enabledPluginIds:[]}},{id:"Ops",displayName:"Ops",iconLabel:"OPS",summary:"Handles deployment, automation, run-state, and operational validation.",cssClass:"ops",canDelegate:!1,runtimeProfile:{runtimePrompt:"Role: Ops. Investigate environment issues, automation, and run-state concerns. Prefer safe build, test, diagnostics, and reproducible runbook evidence.",allowedToolNames:[...ee,"ApplyPatch","RunBuild","RunTests","GetDiagnostics","RecordArtifact","NodeMemory.Upsert","NodeMemory.Recall"],allowedToolPrefixes:["Concept.","Canvas."],enabledPluginIds:["Concept","CodeWorkflow","CodeNoteCanvas","AgentCommandCanvas"]}},{id:"Agent",displayName:"Agent",iconLabel:"AGT",summary:"General execution agent with broad tools and pragmatic task ownership.",cssClass:"specialist",canDelegate:!0,runtimeProfile:{runtimePrompt:"Role: Agent. Solve the assigned task pragmatically, use precise inspection, edit, and validation tools before broad shell commands, and record durable artifacts whenever progress or decisions matter.",allowedToolNames:[...ee,...B,"ApplyPatch","RunBuild","RunTests","GetDiagnostics","RecordArtifact","NodeMemory.Upsert","NodeMemory.Recall"],allowedToolPrefixes:["Concept.","Canvas."],enabledPluginIds:["Concept","WebResearch","CodeWorkflow","CodeNoteCanvas","AgentCommandCanvas"]}}],dr=new Map(Rt.map(e=>[e.id.toLowerCase(),e])),qn=[{id:"repo-bugfix",displayName:"Repo Bugfix",description:"Code bug fixing, root cause isolation, and regression checks.",entryRole:"Programmer",requiredRoles:["Programmer","Reviewer"],triggerKeywords:["bug","fix","debug","error","exception","hotfix","regression"],forceDelegation:!1,runtimeOverlays:{Programmer:{runtimePromptFragment:"Active skill: Repo Bugfix. Reproduce the issue from available evidence, isolate root cause, implement the smallest safe fix, and verify with focused checks before concluding.",allowedToolNames:[...ee,...B],allowedToolPrefixes:["Concept."],enabledPluginIds:["Concept","WebResearch","CodeWorkflow"],actionbookGuide:{template:"docs",querySuffix:"official documentation release notes known issue",maxChars:1800,guidance:"Use a compact docs actionbook before raw page dumps when external docs materially help the fix."}},Reviewer:{runtimePromptFragment:"Active skill: Repo Bugfix. Validate the fix against regression risk, missing tests, rollback concerns, and edge cases. Lead with concrete findings.",allowedToolNames:ue,allowedToolPrefixes:[],enabledPluginIds:[]}}},{id:"code-review",displayName:"Code Review",description:"Change review, risk checks, and regression validation.",entryRole:"Reviewer",requiredRoles:["Reviewer","Programmer"],triggerKeywords:["review","qa","validate","verification","risk","regression"],forceDelegation:!1,runtimeOverlays:{Reviewer:{runtimePromptFragment:"Active skill: Code Review. Review from a bug and regression perspective. Lead with findings, then residual risks, and keep summaries brief.",allowedToolNames:ue,allowedToolPrefixes:[],enabledPluginIds:[]},Programmer:{runtimePromptFragment:"Active skill: Code Review. When proposing fixes, keep patches small, directly justified by review findings, and easy to verify.",allowedToolNames:ee,allowedToolPrefixes:["Concept."],enabledPluginIds:["Concept","CodeWorkflow"]}}},{id:"general-research",displayName:"General Research",description:"General investigation, source gathering, and concise synthesis.",entryRole:"Researcher",requiredRoles:["Planner","Researcher","Agent"],triggerKeywords:["research","investigate","study","explore","explain","summarize","source","evidence"],forceDelegation:!0,runtimeOverlays:{Researcher:{runtimePromptFragment:"Active skill: General Research. Collect evidence from authoritative sources, synthesize findings into a concise brief, and save reusable evidence when material.",allowedToolNames:B,allowedToolPrefixes:[],enabledPluginIds:["WebResearch"],actionbookGuide:{template:"docs",maxChars:1800,guidance:"Use the docs actionbook to extract structured content from authoritative sources."}},Planner:{runtimePromptFragment:"Active skill: General Research. Turn collected evidence into a structured brief with key findings, sources, and actionable next steps.",allowedToolNames:B,allowedToolPrefixes:[],enabledPluginIds:["WebResearch"],actionbookGuide:{template:"docs",maxChars:1800,guidance:"Start with a docs actionbook pass to gather evidence from authoritative sources, then synthesize into a structured brief."}},Agent:{runtimePromptFragment:"Active skill: General Research. Investigate the topic using authoritative sources and produce a concise deliverable. Stop gathering after 2-3 strong sources and write the deliverable.",allowedToolNames:B,allowedToolPrefixes:[],enabledPluginIds:["WebResearch"],actionbookGuide:{template:"docs",maxChars:1800,guidance:"Use the docs actionbook to extract structured content from authoritative sources. Stop gathering after 2-3 sources and write the deliverable."}}}},{id:"market-research",displayName:"Market Research",description:"Market, competitor, pricing, and positioning research.",entryRole:"Researcher",requiredRoles:["Planner","Researcher","Marketer"],triggerKeywords:["market","competitor","benchmark","pricing","positioning","gtm","customer","channel"],forceDelegation:!0,runtimeOverlays:{Researcher:{runtimePromptFragment:"Active skill: Market Research. Produce evidence-based comparisons, competitor summaries, positioning notes, and decision-ready takeaways.",allowedToolNames:B,allowedToolPrefixes:[],enabledPluginIds:["WebResearch"],actionbookGuide:{template:"market",querySuffix:"competitor comparison pricing positioning",maxChars:1800,guidance:"Start with a compact market actionbook run, then persist a concise evidence brief."}},Planner:{runtimePromptFragment:"Active skill: Market Research. Turn findings into a structured brief with themes, gaps, recommendations, and next experiments.",allowedToolNames:B,allowedToolPrefixes:[],enabledPluginIds:["WebResearch"],actionbookGuide:{template:"market",querySuffix:"competitor comparison pricing positioning",maxChars:1800,guidance:"Use a market actionbook pass to gather evidence, then convert it into a structured brief with recommendations."}},Marketer:{runtimePromptFragment:"Active skill: Market Research. Convert market signals into positioning, messaging angles, and campaign-ready notes.",allowedToolNames:B,allowedToolPrefixes:[],enabledPluginIds:["WebResearch"],actionbookGuide:{template:"market",querySuffix:"competitor comparison pricing positioning",maxChars:1800}}}},{id:"landing-page-growth",displayName:"Landing Page Growth",description:"Landing page conversion, copy, implementation, and review work.",entryRole:"Planner",requiredRoles:["Planner","Researcher","Programmer","Reviewer","Marketer"],triggerKeywords:["landing","conversion","copy","funnel","seo","cta","hero"],forceDelegation:!0,runtimeOverlays:{Planner:{runtimePromptFragment:"Active skill: Landing Page Growth. Keep work oriented around conversion improvements, hypotheses, experiment structure, and decision-ready briefs.",allowedToolNames:B,allowedToolPrefixes:[],enabledPluginIds:["WebResearch"],actionbookGuide:{template:"landing",querySuffix:"landing page conversion hero pricing faq cta",preferDetectedUrl:!0,maxChars:1800,guidance:"Use hero, CTA, pricing, and FAQ extracts before drafting copy or implementation changes."}},Researcher:{runtimePromptFragment:"Active skill: Landing Page Growth. Gather evidence on audience pain points, competitor patterns, and conversion opportunities. Keep summaries actionable for copy and implementation.",allowedToolNames:B,allowedToolPrefixes:[],enabledPluginIds:["WebResearch"],actionbookGuide:{template:"landing",querySuffix:"landing page conversion hero pricing faq cta",preferDetectedUrl:!0,maxChars:1800,guidance:"Run the landing actionbook first and keep the output focused on conversion evidence, audience pain points, and CTA structure."}},Marketer:{runtimePromptFragment:"Active skill: Landing Page Growth. Write concrete copy variants, messaging experiments, and CTA options from compact landing evidence.",allowedToolNames:B,allowedToolPrefixes:[],enabledPluginIds:["WebResearch"],actionbookGuide:{template:"landing",querySuffix:"landing page conversion hero pricing faq cta",preferDetectedUrl:!0,maxChars:1800,guidance:"Use the landing actionbook to collect hero, CTA, pricing, and FAQ context before drafting copy variants or experiments."}},Programmer:{runtimePromptFragment:"Active skill: Landing Page Growth. Translate copy and UX changes into focused implementation steps that are easy to validate and revert.",allowedToolNames:ee,allowedToolPrefixes:["Concept."],enabledPluginIds:["Concept","CodeWorkflow"]},Reviewer:{runtimePromptFragment:"Active skill: Landing Page Growth. Review for conversion intent, implementation regressions, and missing validation before sign-off.",allowedToolNames:ue,allowedToolPrefixes:[],enabledPluginIds:[]}}},{id:"ops-automation",displayName:"Ops Automation",description:"Deployment, release, cron, script, and automation work.",entryRole:"Ops",requiredRoles:["Planner","Ops","Reviewer"],triggerKeywords:["deploy","release","cron","automation","script","ops","wrangler","cloudflare"],forceDelegation:!0,runtimeOverlays:{Ops:{runtimePromptFragment:"Active skill: Ops Automation. Prefer reproducible scripts, explicit run steps, idempotent changes, rollback paths, and environment-safe automation.",allowedToolNames:[...ee,...B],allowedToolPrefixes:["Concept."],enabledPluginIds:["Concept","WebResearch","CodeWorkflow"],actionbookGuide:{template:"docs",querySuffix:"official documentation setup configuration best practices",maxChars:1800}},Planner:{runtimePromptFragment:"Active skill: Ops Automation. Produce concrete rollout plans, checklists, and operational runbooks that others can execute safely.",allowedToolNames:B,allowedToolPrefixes:[],enabledPluginIds:["WebResearch"],actionbookGuide:{template:"docs",querySuffix:"official documentation setup configuration best practices",maxChars:1800,guidance:"Start from a docs actionbook pass, then turn the findings into a concrete rollout checklist or runbook."}},Reviewer:{runtimePromptFragment:"Active skill: Ops Automation. Check rollback paths, risk boundaries, observability, and operational validation before release.",allowedToolNames:ue,allowedToolPrefixes:[],enabledPluginIds:[]}}},{id:"code-note-plan",displayName:"Code Note Plan",description:"Structure natural language implementation goals into Code Notes first.",entryRole:"Planner",requiredRoles:["Planner","Programmer"],triggerKeywords:["code note","design note","implementation block","plan from goal"],forceDelegation:!1,runtimeOverlays:{Planner:{runtimePromptFragment:"Active skill: Code Note Plan. Before implementation, create or update Code Notes so structure, rationale, related files, and done criteria are visible.",allowedToolNames:Ae,allowedToolPrefixes:[],enabledPluginIds:["CodeNoteCanvas"]},Programmer:{runtimePromptFragment:"Active skill: Code Note Plan. Convert approved intent into compact implementation-oriented notes before patching.",allowedToolNames:Ae,allowedToolPrefixes:[],enabledPluginIds:["CodeNoteCanvas"]}}},{id:"code-note-implement",displayName:"Code Note Implement",description:"Implement from approved Code Notes and link the result back.",entryRole:"Programmer",requiredRoles:["Programmer","Reviewer"],triggerKeywords:["implement approved notes","code note implement","approved note","note based implementation"],forceDelegation:!1,runtimeOverlays:{Programmer:{runtimePromptFragment:"Active skill: Code Note Implement. Treat approved Code Notes as the implementation contract, inspect notes first, patch minimally, verify, and sync artifacts back.",allowedToolNames:[...ee,...Ae],allowedToolPrefixes:["Concept."],enabledPluginIds:["Concept","CodeWorkflow","CodeNoteCanvas"]},Reviewer:{runtimePromptFragment:"Active skill: Code Note Implement. Confirm implemented behavior, note sync, artifact evidence, and regression coverage before review sign-off.",allowedToolNames:[...ue,...Ae],allowedToolPrefixes:[],enabledPluginIds:["CodeNoteCanvas"]}}},{id:"code-note-sync",displayName:"Code Note Sync",description:"Refresh Code Note and implementation consistency state.",entryRole:"Reviewer",requiredRoles:["Programmer","Reviewer"],triggerKeywords:["code note sync","out of sync","drift","consistency"],forceDelegation:!1,runtimeOverlays:{Reviewer:{runtimePromptFragment:"Active skill: Code Note Sync. Compare implementation results against the Code Note contract, then mark notes in sync, needs review, or out of sync.",allowedToolNames:Ae,allowedToolPrefixes:[],enabledPluginIds:["CodeNoteCanvas"]}}}],Fn=new Map(qn.map(e=>[e.id.toLowerCase(),e]));function Bn(e){const t=String(e??"").trim().toLowerCase();return t==="ceo"||t==="chief executive"?"CEO":t==="planner"?"Planner":t==="researcher"?"Researcher":t==="programmer"||t==="developer"?"Programmer":t==="reviewer"||t==="qa"?"Reviewer":t==="marketer"?"Marketer":t==="ops"||t==="operator"?"Ops":"Agent"}function On(e){const t=Bn(e);return dr.get(t.toLowerCase())??Rt[Rt.length-1]}function qa(e){const t=Math.max(1,e.maxSkills??2),n=[],o=new Set;for(const s of e.skillIds??[]){const i=Fn.get(String(s).trim().toLowerCase());i&&!o.has(i.id)&&(o.add(i.id),n.push(i))}if(n.length>0)return n.slice(0,t);const r=String(e.userInstruction??"").trim().toLowerCase();if(!r)return[];for(const s of qn)if(s.triggerKeywords.some(i=>r.includes(i.toLowerCase()))&&(o.add(s.id),n.push(s),n.length>=t))break;return n}function Fa(e,t,n=xn()){const o=On(e),r=Lt(t);let s=zt(n,o.runtimeProfile);for(const i of r){const a=Dn(i,o.id);a&&(s=zt(s,{runtimePrompt:mr(i,o.id,a.runtimePromptFragment),allowedToolNames:a.allowedToolNames,allowedToolPrefixes:a.allowedToolPrefixes,enabledPluginIds:a.enabledPluginIds}))}return s}function Ba(e){const t=Bn(e.role),n=Lt(e.skills);for(const o of n){const r=Dn(o,t);if(r!=null&&r.actionbookGuide)return fr(o,r.actionbookGuide,e.missionObjective,e.workItemTitle,e.workItemGoal)}for(const o of n){const r=gr(o,e.missionObjective,e.workItemTitle,e.workItemGoal);if(r)return r}return""}function Oa(e){const t=On(e);return["Agent Role Catalog:",`- Role: ${t.displayName}`,`- Can delegate: ${t.canDelegate?"yes":"no"}`,`- Summary: ${t.summary}`].join(`
|
|
16
|
+
`)}function Da(e){const t=Lt(e);return t.length===0?"Mission Skill Catalog: none resolved.":["Mission Skill Catalog:",...t.map(n=>[`- ${n.id}: ${n.displayName}`,` Entry role: ${n.entryRole}`,` Required roles: ${n.requiredRoles.join(", ")}`,` Intent: ${n.description}`].join(`
|
|
17
|
+
`))].join(`
|
|
18
|
+
`)}function Lt(e){if(!e)return[];const t=[],n=new Set;for(const o of e){const r=typeof o=="string"?Fn.get(o.trim().toLowerCase()):o;!r||n.has(r.id)||(n.add(r.id),t.push(r))}return t}function Dn(e,t){return e.runtimeOverlays[t]??e.runtimeOverlays[e.entryRole]??e.runtimeOverlays.Agent??Object.values(e.runtimeOverlays)[0]??null}function mr(e,t,n=""){const o=`Active skill: ${e.displayName}. Apply it as reusable guidance for ${t}.`,r=n.trim()||e.description;return`${o} Skill intent: ${e.description}
|
|
19
|
+
${r}`}function fr(e,t,n,o,r){const s=Wn(n,o,r),i=an(s)||an(n),a=i?vr(i):"",l=t.preferDetectedUrl&&i?"":hr(s,t.querySuffix);return["Mission Skill Execution Hint:",`Skill: ${e.displayName}`,Io({template:t.template,query:l,url:t.preferDetectedUrl?i:"",targetDomain:a,includeSnapshot:t.includeSnapshot===!0,maxChars:yr(t.maxChars??1800,800,6e3),followText:t.followText||t.guidance||`Use this actionbook pass before executing ${e.displayName}.`}),t.guidance?`Guidance: ${t.guidance}`:""].filter(Boolean).join(`
|
|
20
|
+
`)}function gr(e,t,n,o){const r=pr(e.id);if(!r)return"";const s=br(o,4),i={template:r,objective:Wn(t,n,o),maxFiles:4,perFileChars:700,files:s.length>0?s:void 0};return["Mission Skill Execution Hint:",`Skill: ${e.displayName}`,"Recommended first code pass:","Tool: Code.Actionbook",`Args: ${JSON.stringify(i)}`,"After the compact code pass, make the smallest justified change or run the narrowest validation needed."].join(`
|
|
21
|
+
`)}function pr(e){switch(e.toLowerCase()){case"repo-bugfix":return"bugfix";case"code-review":return"review";case"landing-page-growth":return"implementation";case"ops-automation":return"ops";default:return""}}function Wn(e,t,n){const o=String(n??"").trim();return o&&o.length<=220&&!o.includes(`
|
|
22
|
+
`)&&!o.toLowerCase().startsWith("mission objective:")?o:e.trim()||t.trim()}function hr(e,t=""){let o=e.replace(/https?:\/\/\S+/gi," ").replace(/\s+/g," ").trim()||"relevant reference";const r=t.trim();return r&&!o.toLowerCase().includes(r.toLowerCase())&&(o=`${o} ${r}`.trim()),o.length<=180?o:o.slice(0,180).trimEnd()}function an(e){const t=String(e??"").match(/https?:\/\/[^\s\])]+/i);return t?t[0].trim():""}function vr(e){try{return new URL(e).host.trim()}catch{return""}}function br(e,t){const n=[];for(const o of String(e??"").split(/\r?\n/)){if(!o.trim().startsWith("- "))continue;const r=o.trim().slice(2).split(" (")[0].split("#")[0].trim();if(r&&(n.push(r),n.length>=Math.max(1,t)))break}return n}function yr(e,t,n){return Math.min(n,Math.max(t,Math.trunc(e)))}const kr=new Map([["ceo","CEO"],["chiefexecutive","CEO"],["planner","Planner"],["researcher","Researcher"],["programmer","Programmer"],["developer","Programmer"],["reviewer","Reviewer"],["qa","Reviewer"],["marketer","Marketer"],["ops","Ops"],["operator","Ops"],["specialist","Agent"],["agent","Agent"]]);function C(e){return typeof e=="string"?e.trim():""}function pe(e,t="Agent"){const n=C(e).replace(/[\s_-]+/g,"").toLowerCase();return kr.get(n)||t}function ln(e){const t=new Set,n=[];for(const o of e){const r=C(o),s=r.toLowerCase();!r||t.has(s)||(t.add(s),n.push(r))}return n}function wr(e){const t=e.trim();if(t.startsWith("```")){const n=t.indexOf("{"),o=t.lastIndexOf("}");if(n>=0&&o>n)return t.slice(n,o+1)}return t}function _n(e){const t=C(e);if(!t)return null;try{const n=JSON.parse(wr(t));return n&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}function J(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t];const n=Object.keys(e).find(o=>o.toLowerCase()===t.toLowerCase());return n?e[n]:void 0}function Ar(e,t){const n=J(e,t);return Array.isArray(n)?n:[]}function Cr(e,t,n){const o=typeof e=="number"?e:Number(e);return Number.isFinite(o)?Math.min(n,Math.max(t,o)):t}function Un(e,t){const n=ln(t.map(o=>o.id));return n.length>0?n:ln(e.skillIds||[])}function $r(e){const t=e.runtimeOverlays||{};return Object.entries(t).map(([n,o])=>{var s;const r=C((s=o==null?void 0:o.actionbookGuide)==null?void 0:s.template);return r?`${n}:${r}`:""}).filter(Boolean)}function Ir(){return["You are a planning worker for MindExec, a headless multi-agent mission OS.","Return only a single JSON object. Do not use markdown fences. Do not add commentary.","","JSON schema:","{",' "entryRole": "Ceo|Planner|Researcher|Programmer|Reviewer|Marketer|Ops|Specialist",',' "workItems": ['," {",' "title": "short title",',' "goal": "specific executable goal in Korean",',' "roleHint": "Ceo|Planner|Researcher|Programmer|Reviewer|Marketer|Ops|Specialist",',' "isRoot": true'," }"," ]","}","","Rules:","- Use Korean for title and goal.","- Keep workItems between 1 and 6.","- Exactly one item should have isRoot=true.","- Make goals concrete and execution-ready.","- Prefer parallelizable work items for different roles when the mission is broad.","- Do not invent roles outside the allowed enum."].join(`
|
|
23
|
+
`)}function Rr(e={},t=[]){const n=e||{},o=["Mission objective:",C(n.userInstruction),""],r=C(n.targetRole);r&&o.push(`Requested target role: ${r}`);const s=C(n.targetAgentId);if(s&&o.push(`Requested target agent: ${s}`),t.length>0){o.push("Resolved skills:");for(const a of t){const l=$r(a),c=(a.requiredRoles||[]).join(", "),u=l.length>0?` | browser=[${l.join(", ")}]`:"";o.push(`- ${a.id}: ${C(a.description)} | entry=${C(a.entryRole)} | roles=[${c}]${u}`)}o.push("")}const i=(n.contextRefs||[]).filter(a=>C(a.filePath));if(i.length>0){o.push("Code context refs:");for(const a of i.slice(0,8)){const l=typeof a.startLine=="number"?a.startLine:null,c=typeof a.endLine=="number"?a.endLine:l,u=l?`:${l}-${c||l}`:"";o.push(`- ${C(a.filePath)}${u} (${C(a.label)})`)}o.push("")}return o.push("Return the best execution plan JSON now."),o.join(`
|
|
24
|
+
`)}function xr(e,t={},n=[]){var u;const o=t||{},r=C(o.userInstruction);if(!r)return null;const s=_n(e);if(!s)return null;const i=Ar(s,"workItems");if(i.length===0)return null;const a=Un(o,n),l=pe(J(s,"entryRole"),pe(o.targetRole,(u=n[0])!=null&&u.entryRole?pe(n[0].entryRole):"Agent")),c=i.slice(0,6).map((d,p)=>{if(!d||typeof d!="object"||Array.isArray(d))return null;const f=d,g=C(J(f,"goal"));return g?{title:C(J(f,"title"))||`Task ${p+1}`,goal:g,roleHint:pe(J(f,"roleHint"),l),isRoot:J(f,"isRoot")===!0}:null}).filter(d=>!!d);if(c.length===0)return null;if(c.filter(d=>d.isRoot).length!==1)for(let d=0;d<c.length;d+=1)c[d]={...c[d],isRoot:d===0};return{objective:r,entryRole:l,skillIds:a,workItems:c}}function Sr(e,t){const n=_n(e);if(!n)return null;const o=C(J(n,"verdict")).toLowerCase()||"partial",r=Cr(J(n,"score"),0,1),s=C(J(n,"notes"))||`${C(t)||"work-item"} structured evaluation`;return{evaluator:"fleet-structured-llm",verdict:o,score:r,notes:s}}function Tr(e){const t=e.workItem||{},n=C(t.id),o=["Evaluate this completed work item.",`Title: ${C(t.title)}`,`Goal: ${C(t.goal)}`,`State: ${C(t.stateText)}`,`RoleHint: ${C(t.roleHint)}`,`Outcome: ${C(t.lastOutcome)}`];e.mission&&(o.push(`Mission objective: ${C(e.mission.objective)}`),o.push(`Mission state: ${C(e.mission.stateText)}`));const r=e.timeline||[];if(r.length>0){o.push("Recent execution trace:");for(const i of r.slice(-8))o.push(`- [${C(i.category)}] ${C(i.message)}`)}const s=(e.artifacts||[]).filter(i=>C(i.workItemId)===n);if(s.length>0){o.push(""),o.push("Delivered artifacts:");for(const i of s.slice(0,10)){o.push(`- [${C(i.kind)}] ${C(i.title)}: ${C(i.summary)}`);const a=C(i.path);a&&o.push(` Path: ${a}`);const l=C(i.content);l&&o.push(` Content preview: ${l.length>200?`${l.slice(0,200)}...`:l}`)}}return o.join(`
|
|
25
|
+
`)}function Pr(e={},t=[]){const n=e||{},o=t||[];return["Evaluate this mission.",`Objective: ${C(n.objective)}`,`State: ${C(n.stateText)}`,`Outcome: ${C(n.lastOutcome)}`,`Target role: ${C(n.targetRole)}`,`Work item count: ${o.length}`,"Work items:",...o.slice(0,10).map(r=>`- ${C(r.title)} | ${C(r.roleHint)} | ${C(r.stateText)} | ${C(r.lastOutcome)}`)].join(`
|
|
26
|
+
`)}function Wa(e={}){var f,g;const t=e.request||{},n=e.skills||[],o=Ir(),r=Rr(t,n),s=xr(e.rawPlanJson,t,n),i=Sr(e.rawEvaluationJson,(f=e.workItem)!=null&&f.id?"work-item":"mission"),a=Tr({workItem:e.workItem,mission:e.mission,timeline:e.timeline,artifacts:e.artifacts}),l=Pr(e.mission||{},e.missionWorkItems||[]),c=(s==null?void 0:s.skillIds)||Un(t,n),u=(s==null?void 0:s.entryRole)||pe(t.targetRole,(g=n[0])!=null&&g.entryRole?pe(n[0].entryRole):"Agent"),d=(s==null?void 0:s.workItems.length)||0,p=(s==null?void 0:s.workItems.filter(m=>m.isRoot).length)||0;return{hasObjective:!!C(t.userInstruction),plannerSystemPrompt:o,plannerUserPrompt:r,workItemEvaluationPrompt:a,missionEvaluationPrompt:l,parsedPlan:s,parsedEvaluation:i,workItemCount:d,rootWorkItemCount:p,entryRole:u,skillIds:c,evaluationVerdict:(i==null?void 0:i.verdict)||"none",evaluationScore:(i==null?void 0:i.score)??0,projectionLines:[`Objective ready: ${C(t.userInstruction)?"yes":"no"}`,`Skill ids: ${c.join(", ")||"none"}`,`Entry role: ${u}`,`Parsed work items: ${d}`,`Root work items: ${p}`,`Evaluation: ${i?`${i.verdict} / ${i.score.toFixed(2)}`:"none"}`],governanceLines:["TryBuildExecutionPlanAsync returns null without an objective, AI settings, raw JSON, or valid work items.","Planner prompts require one JSON object, 1-6 work items, exactly one root item, concrete executable goals, and allowed roles only.","TryParsePlan extracts fenced JSON, resolves skill ids from resolved skills before request skill ids, falls back to target role, first skill entry role, or Specialist, drops empty goals, caps work items at six, and rewrites root flags when the root count is not one.","TryParseEvaluation extracts JSON, defaults verdict to partial, clamps score between 0.0 and 1.0, defaults notes, and uses evaluator fleet-structured-llm.","Work-item evaluation prompts include title, goal, state, role, outcome, mission context, last eight timeline entries, and up to ten delivered artifacts with 200-character content previews.","Mission structured task projection is browser-local and must not call live AI, LocalBridge, filesystem, Cloudflare, billing, evidence-save, AgentFleet, or MissionControl adapters."],summaryLine:s?`${s.workItems.length} structured work item${s.workItems.length===1?"":"s"} parsed for ${s.entryRole}.`:"Structured task prompts are ready, but no live AI plan is parsed in the React shell."}}function _a(e){var t;return["Mission Structured Task:",...e.projectionLines,"Planner prompt:",e.plannerUserPrompt,e.parsedPlan?"Parsed work items:":"",...((t=e.parsedPlan)==null?void 0:t.workItems.map(n=>`- ${n.isRoot?"[root] ":""}${n.title}: ${n.roleHint}`))||[],e.parsedEvaluation?`Structured evaluation: ${e.parsedEvaluation.verdict} / ${e.parsedEvaluation.score.toFixed(2)}`:"","Governance:",...e.governanceLines.map(n=>`- ${n}`)].filter(Boolean).join(`
|
|
27
|
+
`)}const Lr=["ApplyPatch","RunBuild","RunTests","GetDiagnostics","RecordArtifact","Web.Search","Web.FetchPage","Extract.Structured","Evidence.Save","FinalAnswer"],Mr=["fail","error","unable","blocked","warning","missing"];function Ua(e={}){const t=se(e.blockers,3),n=se(e.nextActions,3),o=D(e.currentFocus,e.activeGoal,e.goal,"Current objective"),r=N(e.rationale,160),s=N(e.toolName,48),i=Math.max(1,Math.trunc(Number(e.requiredEvidence)||1)),a=Math.max(0,Math.trunc(Number(e.evidenceCount)||0)),l=Kr(e.missionProgress??0);return e.isResearchContext===!0?Or({rationale:r,blockers:t,nextActions:n,evidenceCount:a,requiredEvidence:i,toolName:s,completed:e.completed===!0}):Dr({focus:o,rationale:r,blockers:t,nextActions:n,missionProgress:l,toolName:s,completed:e.completed===!0})}function Ga(e={}){const t=e.mindState??{},n=e.phase??null,o=e.step??{},r=!!(n!=null&&n.key&&String(e.previousPhaseKey||"").trim().toLowerCase()!==String(n.key).trim().toLowerCase()),s=Er(o.observation);s.length===0&&(n!=null&&n.summary)&&s.push(N(n.summary,180));const i=Qr(t.blockers,qr(o.observation),n!=null&&n.gap?[n.gap]:[]).slice(0,3);let a=se(t.nextActions,3);a.length===0&&(a=se(n==null?void 0:n.candidates,3)),a.length===0&&a.push("Use this result as the next tranche input.");const l=Fr(o.toolName,s),c=r||l>0||s.length>0||Br(o.toolName),u=D(n==null?void 0:n.why,t.currentDecisionRationale,n==null?void 0:n.summary,"This step reduces the largest uncertainty before choosing the next action."),d=D(n==null?void 0:n.title,Vr(o.toolName,o.stepNumber),"Progress");return Nr({title:`Progress Report - ${d}`,scope:"step",phaseKey:n==null?void 0:n.key,phaseTitle:n==null?void 0:n.title,evidenceGain:l,toolName:o.toolName,stepNumber:o.stepNumber,shouldPublish:c,facts:s,risks:i,nextExploration:a,why:u})}function za(e){if(!e)return"";const t=Object.entries(e.metadata??{}).map(([n,o])=>`- ${n}: ${o}`).join(`
|
|
28
|
+
`);return["Agent Progress Digest:",`Title: ${e.title}`,`Should publish: ${e.shouldPublish?"yes":"no"}`,t?`Metadata:
|
|
29
|
+
${t}`:"","Content:",e.content].filter(Boolean).join(`
|
|
30
|
+
`)}function ja(e){if(!e||typeof e!="object")return;const t=e,n=t.metadata&&typeof t.metadata=="object"?Object.fromEntries(Object.entries(t.metadata).filter(([s,i])=>s.trim()&&i!=null).map(([s,i])=>[s.trim(),String(i).trim()])):{},o=N(t.title||"Progress Report",120),r=String(t.content||"").trim();if(r)return{title:o,content:r,shouldPublish:t.shouldPublish===!0,metadata:n}}function Nr(e){const t=e.facts.length>0?e.facts:["This step mainly clarified the current state rather than adding a new fact."],n=e.risks.length>0?e.risks:["No immediate blocker is known yet; verify before treating the conclusion as final."],o=e.nextExploration.length>0?e.nextExploration:["Use the current result as the next action input."],r={scope:e.scope,cardStyle:"compact",evidenceGain:String(e.evidenceGain)};return e.phaseKey&&(r.phaseKey=N(e.phaseKey,80)),e.phaseTitle&&(r.phaseTitle=N(e.phaseTitle,120)),e.toolName&&(r.toolName=N(e.toolName,80)),Number.isFinite(e.stepNumber)&&(r.stepNumber=String(Math.trunc(e.stepNumber))),{title:N(e.title,120),content:["Confirmed",Ge(t),"","Remaining risks",Ge(n),"","Next exploration",Ge(o),"","Why this choice",Ge([N(e.why,220)])].join(`
|
|
31
|
+
`),shouldPublish:e.shouldPublish,metadata:r}}function Er(e){return zn(e).filter(t=>!Gn(t)).slice(0,3).map(t=>N(t,180))}function qr(e){return zn(e).filter(Gn).slice(0,3).map(t=>N(t,180))}function Gn(e){const t=e.toLowerCase();return Mr.some(n=>t.includes(n))}function zn(e){return String(e||"").replace(/\r\n/g,`
|
|
32
|
+
`).split(`
|
|
33
|
+
`).map(t=>t.trim().replace(/^[-*0-9.)\s]+/,"").trim()).filter(t=>t.length>=8)}function Fr(e,t){const n=String(e||"").trim().toLowerCase();return n==="web.search"||n==="web.fetchpage"||n==="extract.structured"||n==="evidence.save"||n.startsWith("browser.")?Math.max(1,t.length):t.length}function Br(e){const t=String(e||"").trim();return t?Lr.some(n=>n.toLowerCase()===t.toLowerCase())||t.toLowerCase().startsWith("browser."):!1}function Or(e){const t=Math.max(0,e.requiredEvidence-e.evidenceCount),n=e.toolName.toLowerCase(),o=D(e.rationale,t>0?"Research should keep reducing the open evidence gap before a final answer is trusted.":"The evidence floor is met, so the next useful move is synthesis or a challenge check.");if(e.evidenceCount>=e.requiredEvidence||e.completed){const r=Kn(n);return{key:r?"research-challenge":"research-synthesis",title:r?"Challenge the conclusion":"Shape the synthesis",summary:r?"Enough evidence exists for a final pass that tries to disprove the current conclusion.":"Enough evidence exists to organize the surviving claims into a usable answer.",why:o,gap:D(e.nextActions[0],"Package the strongest evidence and resolve the last open question."),candidates:O(e.nextActions,r?["Check one counter-source","Save the strongest evidence trail","Write the final answer"]:["Save the strongest evidence trail","Check one counter-signal","Write the final answer"])}}return Wr(n)?{key:e.evidenceCount===0?"research-search-first":"research-search-more",title:e.evidenceCount===0?"Search for first evidence":"Search for more evidence",summary:e.evidenceCount===0?"Find public source candidates before narrowing to conclusions.":"Broaden the source set to fill the remaining evidence gap.",why:o,gap:`Public evidence still needs ${t} more source signal(s).`,candidates:O(e.nextActions,["Web.Search for source candidates","Web.FetchPage on the top source","Extract.Structured then Evidence.Save"])}:_r(n)?{key:"research-verify-source",title:"Verify source details",summary:"Read a candidate source directly and extract claims, dates, and sourceable signals.",why:o,gap:`Public evidence still needs ${t} more source signal(s).`,candidates:O(e.nextActions,["Confirm the source claim and date","Cross-check against another source","Extract.Structured for durable evidence"])}:Ur(n)?{key:"research-shape-evidence",title:"Shape evidence",summary:"Turn verified source text into reusable evidence that can support a later answer.",why:o,gap:t>0?`Public evidence still needs ${t} more source signal(s).`:"Evidence is ready to be connected into a conclusion.",candidates:O(e.nextActions,["Structure the strongest claim and source","Keep Evidence.Save gated until a save adapter exists","Fetch one more source if the evidence is thin"])}:jn(n)?{key:t>0?"research-premature-summary":"research-synthesis",title:t>0?"Summary is premature":"Shape the synthesis",summary:t>0?"A final answer should wait until the public evidence floor is met.":"The evidence floor is met, so organize the conclusion.",why:o,gap:t>0?`Public evidence still needs ${t} more source signal(s).`:"The remaining work is packaging and risk cleanup.",candidates:O(e.nextActions,t>0?["Web.Search for the missing source","Web.FetchPage an official source","Extract.Structured before FinalAnswer"]:["Save strongest evidence","Write final synthesis"])}:{key:e.evidenceCount===0?"research-scope":"research-gap",title:e.evidenceCount===0?"Scope the research":"Find the evidence gap",summary:e.evidenceCount===0?"Identify which public evidence should come before conclusions.":"Separate what is already known from the missing evidence.",why:o,gap:D(e.blockers[0],`Public evidence still needs ${t} more source signal(s).`),candidates:O(e.nextActions,["Web.Search for source candidates","Web.FetchPage an official source","Use Browser only when search/fetch is not enough"])}}function Dr(e){const t=e.toolName.toLowerCase(),n=D(e.rationale,e.blockers.length>0?"The safest progress is to remove the current blocker before expanding scope.":"The next step should move the objective forward through the smallest verifiable action.");return e.blockers.length>0?{key:"execution-stabilize",title:"Stabilize blocker",summary:"Reduce the failure cause and choose the safest recovery path.",why:n,gap:e.blockers[0],candidates:O(e.nextActions,["Read the failure point again","Choose the smallest safe recovery","Verify that the blocker moved"])}:Gr(t)?{key:"execution-verify",title:"Verify result",summary:"Look for a counterexample or failing edge before trusting the result.",why:n,gap:D(e.nextActions[0],"After verification, package the result."),candidates:O(e.nextActions,["Run the narrowest test or diagnostic","Check one suspected weak point","Summarize the verified result"])}:zr(t)?{key:"execution-hypothesis",title:"Shape hypothesis",summary:"Read the relevant code or notes and reduce the work to one actionable hypothesis.",why:n,gap:D(e.nextActions[0],`Current focus: ${N(e.focus,140)}`),candidates:O(e.nextActions,["Read the most relevant code path","Compare likely hypotheses","Choose the next small action"])}:jr(t)?{key:"execution-implement",title:"Implement the move",summary:"Turn the current hypothesis into a concrete change or execution step.",why:n,gap:D(e.nextActions[0],`Current focus: ${N(e.focus,140)}`),candidates:O(e.nextActions,["Make the smallest safe change","Split work so it can be verified immediately","Hand off to verification after the change"])}:jn(t)||e.missionProgress>=.82||e.completed?{key:"execution-synthesize",title:"Package the result",summary:"Turn the verified work into a usable conclusion and next action.",why:n,gap:D(e.nextActions[0],"Summarize the result, risk, and one next action."),candidates:O(e.nextActions,["Summarize the result","Name the remaining risk","Decide whether to close or continue"])}:e.missionProgress<.18?{key:"execution-interpret",title:"Interpret objective",summary:"Clarify the request, constraints, and first useful action.",why:n,gap:D(e.nextActions[0],`Current focus: ${N(e.focus,140)}`),candidates:O(e.nextActions,["Restate goal and constraints","Pick one first action","Identify the first check"])}:{key:e.missionProgress<.42?"execution-hypothesis":"execution-implement",title:e.missionProgress<.42?"Shape hypothesis":"Implement the move",summary:e.missionProgress<.42?"Reduce the possible paths to a concrete next action.":"Move the chosen path forward and connect it to verification.",why:n,gap:D(e.nextActions[0],`Current focus: ${N(e.focus,140)}`),candidates:O(e.nextActions,["Choose the next smallest action","Run the immediate check afterward","Update the plan if a gap appears"])}}function O(e,t){const n=se(e,3);return n.length>0?n:se(t,3)}function Wr(e){return e==="web.search"}function _r(e){return e==="web.fetchpage"||e.startsWith("browser.")}function Ur(e){return e==="extract.structured"||e==="evidence.save"||e==="nodememory.upsert"}function jn(e){return e==="finalanswer"||e==="recordartifact"}function Kn(e){return e==="runbuild"||e==="runtests"||e==="getdiagnostics"}function Gr(e){return Kn(e)}function zr(e){return["searchinfiles","readfile","readfilerange","nodememory.recall"].includes(e)}function jr(e){return e==="applypatch"||e==="writefile"||e==="executeshell"||e.includes("patch")||e.includes("write")||e.includes("exec")}function Kr(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}function Vr(e,t){return e&&e.trim()?N(e,48):`step ${Math.max(1,Math.trunc(Number(t)||1))}`}function Ge(e){return e.filter(Boolean).slice(0,3).map(t=>`- ${N(t,220)}`).join(`
|
|
34
|
+
`)}function se(e,t){return Array.from(new Set((e??[]).map(n=>N(n,220)).filter(Boolean).map(n=>n.trim()))).slice(0,t)}function Qr(...e){return se(e.flatMap(t=>t??[]),12)}function D(...e){var t;return((t=e.find(n=>String(n||"").trim()))==null?void 0:t.trim())??""}function N(e,t){const n=String(e||"").replace(/\r?\n|\r/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-3)).trimEnd()}...`}const Hr={nodememory:"Recall",nodememoryrecall:"Recall",runbuild:"Build",runtests:"Tests",getdiagnostics:"Diag",recordartifact:"Artifact",applypatch:"Patch",readfile:"Read",readfilerange:"Read",searchinfiles:"Search",finalanswer:"Answer",websearch:"Web.Search",webfetchpage:"Web.Fetch",browseractionbook:"Browser.Actionbook",extractstructured:"Extract.Structured",evidencesave:"Evidence.Save",localbridgecodex:"LocalBridge.Codex"};function Ka(e={}){var v,h,A;const t=e.progressDigest??null,n=Ve((v=t==null?void 0:t.metadata)==null?void 0:v.phaseTitle,e.title,e.objective,"Selected command"),o=Ve(pt(t,"Why this choice"),Vn(e.plannerSummary),e.plannerSummary,e.objective,"Choose the next action that reduces the largest verified gap."),r=Jr(e.plannedTools,(h=t==null?void 0:t.metadata)==null?void 0:h.toolName),s=Xr(r),i=Zr(e.status,t),a=`${Mt(e.status)} ${Math.round(i*100)}%`,l=Math.max(1,Math.trunc(Number((A=t==null?void 0:t.metadata)==null?void 0:A.stepNumber)||1)),c=Math.max(0,Math.trunc(Number(e.linkedNoteCount)||0)),u=pt(t,"Remaining risks").split(`
|
|
35
|
+
`).map(b=>b.replace(/^[-*]\s*/,"").trim()).filter(Boolean),d=pt(t,"Next exploration").split(`
|
|
36
|
+
`).map(b=>b.replace(/^[-*]\s*/,"").trim()).filter(Boolean),p=Ve(d[0],es(e.status,e.plannerSummary,e.plannedTools)),f=Ze([`Loop ${l}/8`,c>0?`Pending ${c}`:"",u.length>0?`Blockers ${u.length}`:"",s?`Tool ${s}`:"",e.requestedRole?`Role ${H(e.requestedRole,24)}`:""],4),g=Ze([`Focus - ${H(n,96)}`,p?`Next - ${H(p,96)}`:"",`Decision - ${H(o,120)}`,s?`Tool loop - ${H(s,96)}`:""],4),m=Yr({status:e.status,objective:e.objective,currentFocus:n,currentDecisionRationale:o,preferredToolLoop:r,summarizedToolLoop:s,nextAction:p,blocker:u[0],progressLabel:a,progressTooltip:cn(i,l,c,e.status)});return{progressLabel:a,progressValue:i,progressTooltip:cn(i,l,c,e.status),currentFocus:n,currentDecisionRationale:o,preferredToolLoop:r,summarizedToolLoop:s,consoleMetrics:f,consoleLines:g,scopeFeedItems:m}}function Va(e){if(!e)return"";const t=e.scopeFeedItems.map(n=>`- ${n.kind}: ${n.text}`).join(`
|
|
37
|
+
`);return["Agent Mind Projection:",`Progress: ${e.progressLabel}`,`Focus: ${e.currentFocus}`,`Decision: ${e.currentDecisionRationale}`,`Tool loop: ${e.preferredToolLoop}`,e.consoleMetrics.length?`Console metrics: ${e.consoleMetrics.join(" | ")}`:"",e.consoleLines.length?`Console lines:
|
|
38
|
+
${e.consoleLines.map(n=>`- ${n}`).join(`
|
|
39
|
+
`)}`:"",t?`Scope feed:
|
|
40
|
+
${t}`:""].filter(Boolean).join(`
|
|
41
|
+
`)}function Yr(e){const t=[];return oe(t,"status",`Command - ${Mt(e.status)}`,Ve(e.objective,e.currentFocus)),oe(t,"progress",e.progressLabel,e.progressTooltip),oe(t,"focus",`Focus - ${e.currentFocus}`,e.currentFocus),oe(t,"decision",e.currentDecisionRationale,`Decision rationale
|
|
42
|
+
${e.currentDecisionRationale}`),oe(t,"toolloop",e.summarizedToolLoop,`Preferred tool loop
|
|
43
|
+
${e.preferredToolLoop}`),oe(t,"next",e.nextAction,`Next action
|
|
44
|
+
${e.nextAction}`),oe(t,"blocker",e.blocker,`Blocker
|
|
45
|
+
${e.blocker}`),t.slice(0,7)}function oe(e,t,n,o){const r=H(n,140);r&&(e.some(s=>s.kind===t&&s.text.toLowerCase()===r.toLowerCase())||e.push({kind:t,text:r,tooltip:H(o||r,260)}))}function Jr(e,t){const n=Ze([...e??[],t||""],8),o=n.map(Qn),r=o.some(i=>i.includes("runbuild")||i.includes("runtests")||i.includes("getdiagnostics")),s=o.some(i=>i.includes("websearch")||i.includes("browser")||i.includes("extractstructured"));if(r)return"NodeMemory.Recall -> RunBuild/RunTests/GetDiagnostics -> RecordArtifact";if(s){const i=[o.some(a=>a.includes("websearch"))?"Web.Search":"",o.some(a=>a.includes("browser"))?"Browser.Actionbook":"",o.some(a=>a.includes("extractstructured"))?"Extract.Structured":"",o.some(a=>a.includes("evidencesave"))?"Evidence.Save":""].filter(Boolean);if(i.length>0)return i.join(" -> ")}return n.length>0?n.slice(0,4).join(" -> "):"ReviewContext -> SelectNextAction -> FinalAnswer"}function Xr(e){const t=e.split("->").map(n=>H(n,48)).filter(Boolean);return t.length===0?"":t.map(n=>{const o=Qn(n);return o==="runbuildruntestsgetdiagnostics"?"Build+Tests+Diag":Hr[o]??n.replace(/^NodeMemory\./i,"")}).join(" -> ")}function Zr(e,t){var i,a;const n=String(e||"").trim().toLowerCase(),o=n==="done"?1:n==="blocked"?.34:n==="running"?.56:n==="paused"?.44:.18,r=Math.max(0,Number((i=t==null?void 0:t.metadata)==null?void 0:i.evidenceGain)||0),s=Math.max(0,Number((a=t==null?void 0:t.metadata)==null?void 0:a.stepNumber)||0);return Hn(o+Math.min(.22,r*.05)+Math.min(.12,s*.015))}function Mt(e){const t=String(e||"").trim().toLowerCase();return t==="done"?"Complete":t==="blocked"?"Blocked":t==="running"?"Progress":t==="paused"?"Paused":"Draft"}function es(e,t,n){const o=String(e||"").trim().toLowerCase();if(o==="done")return"Package the result and link the final evidence.";if(o==="blocked")return"Inspect the blocker and choose the lowest-risk unblock step.";const r=Ze(n??[],1)[0];return r?`Run ${r} against the current command evidence.`:Vn(t)||"Select the next verified action."}function pt(e,t){if(!(e!=null&&e.content))return"";const n=e.content.split(/\r?\n/),o=n.findIndex(s=>s.trim().toLowerCase()===t.trim().toLowerCase());if(o<0)return"";const r=[];for(let s=o+1;s<n.length;s+=1){const i=n[s].trim();if(!i){if(r.length>0)break;continue}if(/^[A-Z][A-Za-z\s]+$/.test(i)&&!i.startsWith("-"))break;r.push(i)}return r.join(`
|
|
46
|
+
`).trim()}function Vn(e){const t=String(e||"").split(/\r?\n/).map(n=>n.replace(/^[-*]\s*/,"").trim()).filter(Boolean);return t.find(n=>/because|so |risk|verify|evidence|decision|next/i.test(n))||t[0]||""}function cn(e,t,n,o){return[`Progress ${Math.round(Hn(e)*100)}%`,`Loop ${Math.max(1,t)}/8`,`Linked notes ${Math.max(0,n)}`,`Status ${Mt(o)}`].join(`
|
|
47
|
+
`)}function Ze(e,t){const n=[],o=new Set;for(const r of e){const s=H(r,180),i=s.toLowerCase();if(!(!s||o.has(i))&&(n.push(s),o.add(i),n.length>=t))break}return n}function Ve(...e){return e.map(t=>H(t,220)).find(Boolean)||""}function H(e,t){const n=String(e||"").replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-3)).trimEnd()}...`}function Qn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Hn(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}const ts=["delete","drop","truncate","wipe","destroy","remove all","reset","overwrite","rm -rf"],Yn=["verify","review","test","check","validate","confirm","diagnostic","regression"],ns=["inspect","analyze","read","observe","measure","trace","list","collect","compare","evidence","source"],os=["implement","build","create","write","patch","fix","update","refactor","rewrite"],rs=["package","handoff","summarize","document","deliver","finalize","ship"],ss=["blocker","resolve","debug","retry","failure","error","missing","unable","stuck"],un=["research","investigate","competitor","benchmark","market","pricing","docs","release notes","news","website","source","citation","public source","official","trend","customer signal","money","revenue","profit","business","startup","channel","acquisition","willingness to pay","time-to-cash","sales","customer","web.search","web.fetchpage","browser.actionbook","browser.snapshot","extract.structured","evidence.save"],Nt=.6;function Qa(e={}){var u,d;const t=as(e),n=ne([e.title,e.objective,e.constraints,e.requestedRole,e.status,e.plannerSummary,(u=e.progressDigest)==null?void 0:u.content,(d=e.mindProjection)==null?void 0:d.currentDecisionRationale,...e.plannedTools||[],...e.plannedSkills||[]].filter(Boolean).join(" ")).toLowerCase(),o=e.requiresExternalResearch??$s(t,n),r=Jn(t),s=Math.max(0,(e.costBudgetLimitUsd??1)-(e.estimatedCostUsd??.02)),i=ms(e,r,o).map(p=>is(p,t,r,o,s)).sort((p,f)=>p.survives!==f.survives?p.survives?-1:1:f.score-p.score),a=i.filter(p=>p.survives),l=i.filter(p=>!p.survives),c=a[0]??i[0];return{phaseHint:r,survivalScore:t.survivalScore,survivalFloor:Nt,missionProgress:t.missionProgress,profitScore:t.profitScore,requiresExternalResearch:o,topCandidate:c,candidates:i,acceptedCandidates:a,rejectedCandidates:l,summaryLine:`${r} selects ${c.label} at ${de(c.score)} with ${c.preferredToolLoop}`}}function is(e,t,n=Jn(t),o=!1,r=1){const s=Xn(e.instruction,320),i=s.toLowerCase(),a=e.kindOverride??fs(i,t),l=As(a,n,o),c=ws(i,a,n,o),u=t.nextActions.some(U=>U.toLowerCase()===i)?.35:0,d=t.failurePatterns.some(U=>U&&i.includes(U.toLowerCase()))?.18:0,p=t.blockers.some(U=>U&&i.includes(U.toLowerCase()))?.16:0,f=gs(i),g=a==="verification"?.16:0,m=a==="evidence"?.14:0,v=a==="implementation"?.15:0,h=a==="summary"?.1:0,A=a==="blocker"?.24:0,b=z(hs(n,a,t,o)+A+p+u+g+m+v+h+c-d),w=z(vs(n,a,t,o)+g+h+t.profitScore*.2+c*.65),k=bs(a,u+c,n,o),S=ys(a,n,c),R=ks(a,n,r,d,c,o),I=a==="verification"?.02:a==="evidence"?.03:a==="summary"?.015:.05,$=a==="verification"||a==="evidence"||a==="blocker",T=f>=.7,F=f>=.85,G=ps({riskScore:f,estimatedCost:I,costBudgetRemaining:r,mayCorruptState:T,mayDeleteUserData:F,safetyBiased:$},t),x=Rs(b*.6+w*.2+k*.1+S*.1-R*.2);return{id:e.id,label:e.label,instruction:s,kind:a,phaseHint:n,preferredToolLoop:l,rationale:Cs(a,n,t,l,o),score:x,riskScore:f,expectedMissionDelta:b,expectedProfitDelta:w,evidenceGain:k,reusabilityGain:S,costPenalty:R,estimatedCost:I,costBudgetRemaining:r,safetyBiased:$,mayCorruptState:T,mayDeleteUserData:F,survives:G,rejectionReason:G?void 0:Is(f,t,$,T,F)}}function Ha(e){if(!e)return"";const t=e.acceptedCandidates.slice(0,3).map(o=>`${o.label}(${o.kind}:${de(o.score)})`).join(", ")||"-",n=e.rejectedCandidates.slice(0,3).map(o=>`${o.label}(${o.rejectionReason||"gate rejected"})`).join(", ")||"-";return["Agent Objective Kernel:",`Phase: ${e.phaseHint}`,`Mission progress: ${de(e.missionProgress)}`,`Survival gate: ${de(e.survivalScore)} / floor ${de(e.survivalFloor)}`,`External research required: ${e.requiresExternalResearch?"yes":"no"}`,`Top candidate: ${e.topCandidate.label} (${e.topCandidate.kind}, score ${de(e.topCandidate.score)})`,`Tool loop: ${e.topCandidate.preferredToolLoop}`,`Rationale: ${e.topCandidate.rationale}`,`Accepted candidates: ${t}`,`Rejected candidates: ${n}`].join(`
|
|
48
|
+
`)}function as(e){var r,s,i,a,l,c,u,d,p;const t=z(e.missionProgress??((r=e.mindProjection)==null?void 0:r.progressValue)??ls(e)),n=Ce([...e.blockers||[],...ds(e)]),o=Ce([...e.nextActions||[],(i=(s=e.progressDigest)==null?void 0:s.metadata)==null?void 0:i.nextAction,(l=(a=e.mindProjection)==null?void 0:a.consoleLines)==null?void 0:l.find(f=>f.toLowerCase().includes("next"))]);return{mission:ne(e.objective||e.title||"Selected CodeMaster command"),currentFocus:ne(e.plannerSummary||e.title||""),currentIntent:ne(e.title||e.objective||""),lastReflectionSummary:ne(((c=e.progressDigest)==null?void 0:c.content)||((u=e.mindProjection)==null?void 0:u.currentDecisionRationale)||""),missionProgress:t,survivalScore:z(e.survivalScore??cs(e,t,n)),profitScore:z(e.profitScore??us(e,t)),stretchPassCount:Math.max(0,Math.floor(e.stretchPassCount??0)),maxStretchPasses:Math.max(0,Math.floor(e.maxStretchPasses??1)),blockers:n,nextActions:o,failurePatterns:Ce([...e.failurePatterns||[],...n]),openLoops:Ce([e.constraints,(p=(d=e.progressDigest)==null?void 0:d.metadata)!=null&&p.riskCount?`risk count ${e.progressDigest.metadata.riskCount}`:""]),constraints:Ce([e.constraints])}}function ls(e){var n,o,r;const t=String(e.status||"").toLowerCase();return t==="done"||t==="completed"?.96:t==="running"?.72:t==="blocked"||t==="error"?.4:(n=e.progressDigest)!=null&&n.shouldPublish?.82:Number(((r=(o=e.progressDigest)==null?void 0:o.metadata)==null?void 0:r.stepNumber)||0)>=3?.7:(e.linkedNoteCount||0)>0?.48:.28}function cs(e,t,n){var s,i;const o=String(e.status||"").toLowerCase();let r=.86;return(o==="blocked"||o==="error")&&(r-=.3),n.length>0&&(r-=Math.min(.22,n.length*.08)),Number(((i=(s=e.progressDigest)==null?void 0:s.metadata)==null?void 0:i.riskCount)||0)>0&&(r-=.07),t>=.8&&(r+=.04),(e.plannedTools||[]).some(a=>/runtests|getdiagnostics|runbuild/i.test(a))&&(r+=.04),r}function us(e,t){const n=ne([e.title,e.objective,e.plannerSummary,...e.plannedTools||[]].filter(Boolean).join(" ")).toLowerCase();let o=.42+t*.14;return E(n,["revenue","pricing","customer","sales","market","business","profit"])&&(o+=.12),String(e.status||"").toLowerCase()==="done"&&(o+=.06),z(o)}function ds(e){var r,s;const t=String(e.status||"").toLowerCase(),n=[],o=Number(((s=(r=e.progressDigest)==null?void 0:r.metadata)==null?void 0:s.riskCount)||0);return t==="blocked"&&n.push("blocked status"),t==="error"&&n.push("error status"),o>0&&n.push("remaining risk"),n}function ms(e,t,n){const o=Xn(e.objective||e.title||"selected command",120),r=[];return t==="stabilize"&&r.push({id:"blocker",label:"Blocker stabilization",instruction:`Verify blocker details for ${o} and confirm the lowest-risk recovery path.`,kindOverride:"blocker"}),t==="elevate"&&r.push({id:"review",label:"Stretch review",instruction:`Review the completed result for ${o} and tighten one weak spot before handoff.`,kindOverride:"verification"}),n&&r.push({id:"external-evidence",label:"External evidence pass",instruction:`Use NodeMemory.Recall, Web.Search, Web.FetchPage, Extract.Structured, and Evidence.Save to collect public-source evidence for ${o}.`,kindOverride:"evidence"}),r.push({id:"verification",label:"Verification pass",instruction:`Use NodeMemory.Recall, RunBuild, RunTests, and GetDiagnostics to verify ${o} and capture the remaining gap.`,kindOverride:"verification"}),r.push({id:"implementation",label:"Scoped implementation",instruction:`Implement the next scoped change for ${o}, then record the result.`,kindOverride:"implementation"}),r.push({id:"summary",label:"Handoff package",instruction:`Package the verified result for ${o}, summarize risks, and deliver the next action.`,kindOverride:"summary"}),r}function Jn(e){return e.blockers.length>0?"stabilize":e.missionProgress>=.92&&e.survivalScore>=.88&&e.stretchPassCount<e.maxStretchPasses?"elevate":e.missionProgress>=.78?"verify":e.missionProgress<=.32?"explore":"progress"}function fs(e,t){return E(e,ss)||t.blockers.some(n=>e.includes(n.toLowerCase()))?"blocker":E(e,Yn)?"verification":E(e,ns)?"evidence":E(e,rs)?"summary":(E(e,os),"implementation")}function gs(e){return E(e,ts)?.92:E(e,["migrate","schema","production"])?.55:E(e,Yn)?.18:.12}function ps(e,t){const n=e.costBudgetRemaining===0?1:e.costBudgetRemaining;return e.riskScore<.4&&e.estimatedCost<=Math.max(0,n)&&!e.mayCorruptState&&!e.mayDeleteUserData&&t.survivalScore>=.35&&(t.survivalScore>=Nt||e.safetyBiased)}function hs(e,t,n,o){const r=t==="blocker"?.36:t==="verification"?.31:t==="evidence"?.28:t==="summary"?.18:.34;let s=0;e==="stabilize"&&t==="blocker"?s=.28:e==="stabilize"&&t==="verification"?s=.1:e==="elevate"&&(t==="verification"||t==="summary")?s=.26:e==="elevate"&&t==="evidence"?s=.1:e==="elevate"&&t==="implementation"?s=-.04:e==="verify"&&(t==="verification"||t==="summary")?s=.24:e==="verify"&&t==="implementation"?s=-.08:e==="explore"&&(t==="evidence"||t==="implementation")?s=.18:e==="explore"&&t==="summary"&&(s=-.1);const i=n.nextActions.some(l=>l.toLowerCase().includes(t))?.05:0;let a=0;return o&&(t==="evidence"?a=.18:t==="verification"?a=.1:t==="summary"?a=e==="elevate"?.05:-.03:t==="implementation"?a=e==="explore"||e==="progress"?-.1:-.04:a=.04),r+s+i+a}function vs(e,t,n,o){const r=t==="verification"?.22:t==="summary"?.2:t==="implementation"?.17:t==="evidence"?.14:.16;let s=0;e==="elevate"&&(t==="verification"||t==="summary")?s=.14:e==="elevate"&&t==="evidence"?s=.06:e==="verify"&&(t==="verification"||t==="summary")?s=.12:e==="explore"&&t==="evidence"?s=.08:e==="stabilize"&&t==="blocker"&&(s=.1);let i=0;return o&&(t==="evidence"?i=.12:t==="verification"?i=.08:t==="summary"?i=.05:t==="implementation"?i=-.05:i=.03),r+s+i+n.profitScore*.08}function bs(e,t,n,o){let r=e==="verification"?.34:e==="evidence"?.38:e==="blocker"?.22:.14;return n==="verify"&&e==="verification"&&(r+=.08),n==="elevate"&&(e==="verification"||e==="summary")&&(r+=.1),o&&(e==="evidence"?r+=.12:e==="verification"?r+=.08:e==="summary"?r+=.05:r+=.03),z(r+t)}function ys(e,t,n){let o=e==="summary"?.28:e==="verification"?.22:e==="implementation"?.18:e==="evidence"?.16:.12;return t==="verify"&&e==="summary"&&(o+=.06),t==="elevate"&&e==="summary"&&(o+=.08),z(o+n*.35)}function ks(e,t,n,o,r,s){let i=e==="summary"?.06:e==="verification"?.1:e==="evidence"?.12:e==="blocker"?.16:.2;return t==="verify"&&e==="implementation"&&(i+=.12),t==="elevate"&&e==="implementation"&&(i+=.16),t==="stabilize"&&e!=="blocker"&&e!=="verification"&&(i+=.08),s&&e==="implementation"&&(i+=.08),n<=.05&&(i+=.08),z(i+o-Math.min(.12,r*.5))}function ws(e,t,n,o){let r=0;return E(e,["nodememory.recall","nodememory.upsert"])&&(r+=.05),t==="verification"&&E(e,["runbuild","runtests","getdiagnostics"])&&(r+=.14),t==="evidence"&&E(e,["web.search","web.fetchpage","browser.actionbook","extract.structured","evidence.save"])&&(r+=.18),t==="implementation"&&E(e,["searchinfiles","readfilerange","applypatch"])&&(r+=.1),o&&E(e,["web.search","evidence.save","extract.structured"])&&(r+=.12),n==="elevate"&&E(e,["recordartifact","finalanswer"])&&(r+=.04),z(r)}function As(e,t,n){return n?e==="blocker"?"NodeMemory.Recall -> Web.Search -> Web.FetchPage/Browser.Actionbook -> Extract.Structured -> Evidence.Save -> NodeMemory.Upsert":e==="verification"?t==="elevate"?"NodeMemory.Recall -> Web.Search/Web.FetchPage -> Extract.Structured -> Evidence.Save -> RecordArtifact -> NodeMemory.Upsert":"NodeMemory.Recall -> Web.Search/Web.FetchPage -> Extract.Structured -> Evidence.Save -> NodeMemory.Upsert":e==="evidence"?"NodeMemory.Recall -> Web.Search -> Web.FetchPage/Browser.Actionbook -> Extract.Structured -> Evidence.Save -> NodeMemory.Upsert":e==="summary"?"NodeMemory.Recall -> Evidence.Save -> RecordArtifact -> NodeMemory.Upsert -> FinalAnswer":"NodeMemory.Recall -> Web.Search -> Web.FetchPage/Browser.Actionbook -> Extract.Structured -> NodeMemory.Upsert -> SearchInFiles/ReadFileRange -> ApplyPatch -> RunBuild/RunTests -> RecordArtifact":e==="blocker"?"NodeMemory.Recall -> SearchInFiles -> ReadFileRange -> GetDiagnostics/RunTests -> ApplyPatch if safe -> NodeMemory.Upsert":e==="verification"?t==="elevate"?"NodeMemory.Recall -> RunBuild/RunTests/GetDiagnostics -> RecordArtifact -> NodeMemory.Upsert":"NodeMemory.Recall -> RunBuild/RunTests/GetDiagnostics -> NodeMemory.Upsert":e==="evidence"?"NodeMemory.Recall -> SearchInFiles -> ReadFileRange -> NodeMemory.Upsert":e==="summary"?"NodeMemory.Recall -> RecordArtifact -> NodeMemory.Upsert -> FinalAnswer":"NodeMemory.Recall -> SearchInFiles -> ReadFileRange -> ApplyPatch -> RunBuild/RunTests -> NodeMemory.Upsert -> RecordArtifact"}function Cs(e,t,n,o,r){return r&&t==="explore"&&e==="evidence"?`Mission depends on outside facts, so gather and persist authoritative evidence before narrowing the plan. Prefer tool loop: ${o}`:r&&t==="verify"&&e==="verification"?`Mission needs source-backed confirmation, so verify against current public evidence before concluding. Prefer tool loop: ${o}`:r&&e==="summary"?`Package a source-backed result and preserve reusable citations for later review. Prefer tool loop: ${o}`:t==="stabilize"&&e==="blocker"?`Resolve an active blocker before further implementation. Prefer tool loop: ${o}`:t==="verify"&&e==="verification"?`Mission is late-stage, so validation is the highest-value next step. Prefer tool loop: ${o}`:t==="elevate"&&(e==="verification"||e==="summary")?`The target is essentially met, so run one more safe review pass and raise the final quality bar. Prefer tool loop: ${o}`:t==="explore"&&e==="evidence"?`Mission is early-stage, so gathering better evidence reduces the search space. Prefer tool loop: ${o}`:e==="summary"?`Package durable output and make the result reusable. Prefer tool loop: ${o}`:n.blockers.length>0&&e!=="blocker"?`Still useful, but secondary until blockers are reduced. Prefer tool loop: ${o}`:`${e==="verification"?"Validate the latest result against the mission.":e==="evidence"?"Collect more context before the next irreversible move.":e==="implementation"?"Direct mission progress through implementation work.":e==="blocker"?"Reduce a blocker that is constraining forward progress.":"Advance the mission safely."} Prefer tool loop: ${o}`}function $s(e,t){if(E(t,un))return!0;const n=[e.mission,e.currentIntent,e.currentFocus,e.lastReflectionSummary,...e.openLoops.slice(0,3),...e.nextActions.slice(0,3),...e.constraints.slice(0,2)].join(" ").toLowerCase();return E(n,un)}function Is(e,t,n,o,r){return r?"delete-data risk":o?"corrupt-state risk":e>=.4?"risk score above survival gate":t.survivalScore<.35?"survival below hard floor":t.survivalScore<Nt&&!n?"low survival requires safety-biased action":"survival gate rejected"}function Xn(e,t){const n=ne(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}...`:n}function ne(e){return String(e??"").replace(/\s+/g," ").trim()}function Ce(e){const t=new Set,n=[];return e.forEach(o=>{const r=ne(o);if(!r)return;const s=r.toLowerCase();t.has(s)||(t.add(s),n.push(r))}),n}function E(e,t){return t.some(n=>e.includes(n))}function z(e){return Math.min(1,Math.max(0,Number.isFinite(e)?e:0))}function Rs(e){return Math.round((Number.isFinite(e)?e:0)*1e3)/1e3}function de(e){return z(e).toFixed(2)}function Ya(e={}){var v,h,A,b,w,k,S,R,I,$,T,F,G,x,U,Fe,Be,ke,K,Oe,Dt,Wt,_t,Ut,Gt;const t=me(e.goal,(v=e.mindProjection)==null?void 0:v.currentFocus,"Selected CodeMaster command"),n=me(e.activeGoal,(h=e.mindProjection)==null?void 0:h.currentDecisionRationale,e.goal,t),o=me(e.focus,(A=e.objectiveKernel)==null?void 0:A.topCandidate.label,e.activeGoal,n,t),r=Se(((b=e.objectiveKernel)==null?void 0:b.missionProgress)??((w=e.mindProjection)==null?void 0:w.progressValue)??0),s=Se(((k=e.objectiveKernel)==null?void 0:k.survivalScore)??Ss(e.status)),i=Se(((S=e.objectiveKernel)==null?void 0:S.profitScore)??Ts(e.progressDigest)),a=me((R=e.objectiveKernel)==null?void 0:R.topCandidate.rationale,(I=e.mindProjection)==null?void 0:I.currentDecisionRationale),l=me(($=e.objectiveKernel)==null?void 0:$.topCandidate.preferredToolLoop,(T=e.mindProjection)==null?void 0:T.preferredToolLoop),c=fe([...e.workingMemory||[],(F=e.progressDigest)!=null&&F.title?`Latest progress: ${e.progressDigest.title}`:"",(G=e.progressDigest)!=null&&G.content?Le(e.progressDigest.content,180):""]),u=fe([...e.openLoops||[],e.constraints,(U=(x=e.progressDigest)==null?void 0:x.metadata)!=null&&U.phaseTitle?`Phase: ${e.progressDigest.metadata.phaseTitle}`:""]),d=fe([...e.blockers||[],String(e.status||"").toLowerCase()==="blocked"?"Command status is blocked.":"",Number(((Be=(Fe=e.progressDigest)==null?void 0:Fe.metadata)==null?void 0:Be.riskCount)||0)>0?`Remaining risk count: ${(K=(ke=e.progressDigest)==null?void 0:ke.metadata)==null?void 0:K.riskCount}`:"",...(((Oe=e.objectiveKernel)==null?void 0:Oe.rejectedCandidates)||[]).slice(0,2).map(De=>`${De.label}: ${De.rejectionReason||"survival gate rejected"}`)]),p=fe([...e.learnedFacts||[],(Wt=(Dt=e.progressDigest)==null?void 0:Dt.metadata)!=null&&Wt.toolName?`Tool evidence: ${e.progressDigest.metadata.toolName}`:"",(_t=e.objectiveKernel)!=null&&_t.requiresExternalResearch?"Outside facts must be source-backed before conclusion.":""]),f=fe([...e.nextActions||[],(Ut=e.objectiveKernel)==null?void 0:Ut.topCandidate.instruction,...(((Gt=e.objectiveKernel)==null?void 0:Gt.acceptedCandidates)||[]).slice(1,3).map(De=>De.instruction)]),g=xs(e.canvasNotes||[]),m=["Cognitive State:",`- Mission: ${t}`,`- Current intent: ${n}`,`- Current focus: ${o}`,`- Mission progress: ${ht(r)}`,`- Survival score: ${ht(s)}`,`- Profit score: ${ht(i)}`,"- Treat survival as a hard constraint, user mission as direct work, and profit/efficiency as a tie-breaker.","- Think internally, but only write meaningful artifacts, evidence, blockers, decisions, and next actions to PlanMaster notes."];return a&&m.push(`- Current decision: ${a}`),l&&m.push(`- Preferred tool loop: ${l}`),ae(m,"Working memory",c,6),ae(m,"Open loops",u,5),ae(m,"Blockers",d,4),ae(m,"Learned facts",p,5),ae(m,"Candidate next actions",f,3),ae(m,"External canvas memory",g,4),{text:m.join(`
|
|
49
|
+
`),lines:m,mission:t,currentIntent:n,currentFocus:o,missionProgress:r,survivalScore:s,profitScore:i,currentDecision:a,preferredToolLoop:l,canvasNoteItems:g}}function Ja(e){return(e==null?void 0:e.text)||""}function xs(e){return e.map(t=>{const n=Le(t.kind||t.status||"note",32),o=me(t.title,Le(t.content,90));return o?`[${n}] ${o}`:""}).filter(Boolean).slice(0,4)}function ae(e,t,n,o){const r=fe(n).slice(0,o);r.length!==0&&(e.push(`${t}:`),r.forEach(s=>{e.push(`- ${s}`)}))}function me(...e){for(const t of e){const n=Le(t,220);if(n)return n}return""}function fe(e){const t=new Set,n=[];return e.forEach(o=>{const r=Le(o,220);if(!r)return;const s=r.toLowerCase();t.has(s)||(t.add(s),n.push(r))}),n}function Le(e,t){const n=String(e??"").replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-3)).trimEnd()}...`}function Ss(e){const t=String(e||"").toLowerCase();return t==="blocked"||t==="error"?.52:t==="done"||t==="completed"?.9:t==="running"?.78:.7}function Ts(e){var n;if(!e)return .42;const t=Number(((n=e.metadata)==null?void 0:n.evidenceGain)||0);return Se(.44+Math.min(.18,t*.03))}function Se(e){return Math.min(1,Math.max(0,Number.isFinite(e)?e:0))}function ht(e){return Se(e).toFixed(2)}const Ps=["blocked","blocker","unable","failed","failure","error","cannot","can't","missing","need ","needs "],Ls=["research","investigate","compare","competitor","benchmark","market","pricing","price","docs","documentation","release note","release notes","news","website","web","browser","source","citation","public source","external","official","trend","money","revenue","profit","business","startup","channel","distribution","acquisition","willingness to pay","time-to-cash","monetize","sales","customer","authority","authoritative"],Ms=["business","startup","revenue","profit","market","pricing","sales","customer","acquisition","channel","distribution","willingness to pay","time-to-cash","monetize","solo founder","micro-saas"];function Xa(e={}){var w,k,S,R,I;const t=vt(e.mission,(w=e.mindPacket)==null?void 0:w.mission,"Selected CodeMaster command"),n=vt(e.activeGoal,(k=e.mindPacket)==null?void 0:k.currentIntent,t),o=vt(e.lastResult,(S=e.progressDigest)==null?void 0:S.content,(R=e.objectiveKernel)==null?void 0:R.topCandidate.rationale,(I=e.mindPacket)==null?void 0:I.currentDecision),r=e.succeeded??!Te(`${e.failureMessage||""} ${o}`.toLowerCase(),["failed","failure","error","unable","missing"]),s=e.canvasNotes||[],i=Ns(o).concat(s.filter($=>Ie($,"evidence")||Ie($,"artifact")).map($=>Q($.content||$.title,180))).filter(Boolean).filter($e).slice(0,6),a=[...!r&&e.failureMessage?[Q(e.failureMessage,180)]:[],...s.filter($=>Ie($,"blocker")).map($=>Q($.content||$.title,180)),...Es(o)].filter(Boolean).filter($e).slice(0,6),l=qs(e,t,n,o,i,a,s),c=l||Te(`${t} ${n}`.toLowerCase(),["research","investigate","compare"]),u=Te(`${t} ${n} ${o}`.toLowerCase(),Ms),d=Fs(e,r,i,a,c,u,l),p=Bs(e,r,a),f=Os(e,r,i),g=a.concat(s.filter($=>Ie($,"next_action")).map($=>Q($.content||$.title,180))).filter(Boolean).filter($e).slice(0,8),m=Ds({succeeded:r,pendingGoalCount:Math.max(0,Number(e.pendingGoalCount||0)),blockers:a,facts:i,missionProgress:d,requiresExternalEvidence:l,businessOpportunityMission:u}).filter(Boolean).filter($e).slice(0,3),v=[`Mission: ${Q(t,200)}`,`Focus: ${Q(n,200)}`,...i.map($=>`Fact: ${$}`),...a.map($=>`Blocker: ${$}`)].filter(Boolean).filter($e).slice(0,8),h=a.length===0&&d>=(c?u?.86:.9:.92)&&(!l||i.length>=(u?3:2)),A=h&&p>=.88&&m.length>0,b=(!h||A)&&m.length>0&&p>=.55;return{summary:_s({missionProgress:d,survivalScore:p,profitScore:f,succeeded:r,facts:i,blockers:a,nextActions:m,isComplete:h,shouldStretchReview:A,shouldAutoReplan:b,persistentResearchMission:c}),facts:i,blockers:a,openLoops:g,workingMemory:v,nextActions:m,missionProgress:d,survivalScore:p,profitScore:f,shouldAutoReplan:b,isComplete:h,shouldStretchReview:A,requiresExternalEvidence:l,persistentResearchMission:c,businessOpportunityMission:u}}function Za(e){return e?["Agent Reflection Replan:",e.summary,`Auto replan: ${e.shouldAutoReplan?"yes":"no"}`,`Stretch review: ${e.shouldStretchReview?"yes":"no"}`,`External evidence required: ${e.requiresExternalEvidence?"yes":"no"}`,"Next actions:",...e.nextActions.map(t=>`- ${t}`)].join(`
|
|
50
|
+
`):""}function Ns(e){return Zn(e).filter(t=>!eo(t)).slice(0,4).map(t=>Q(t,180))}function Es(e){return Zn(e).filter(eo).slice(0,3).map(t=>Q(t,180))}function Zn(e){return String(e||"").split(/\r?\n/).map(t=>t.trim().replace(/^[-*0-9.)\s]+/,"").trim()).filter(t=>t.length>=8)}function eo(e){return Te(e.toLowerCase(),Ps)}function qs(e,t,n,o,r,s,i){var l;if((l=e.objectiveKernel)!=null&&l.requiresExternalResearch||i.some(c=>Ie(c,"evidence")))return!0;const a=[t,n,o,e.failureMessage,...r,...s,...i.slice(0,4).map(c=>`${c.kind||""} ${c.title||""} ${c.content||""}`)].join(" ").toLowerCase();return Te(a,Ls)}function Fs(e,t,n,o,r,s,i){var l,c;let a=Math.max(.05,((l=e.objectiveKernel)==null?void 0:l.missionProgress)??((c=e.mindPacket)==null?void 0:c.missionProgress)??.18);return a+=t?r?.12:.22:r?-.06:-.1,a+=Math.min(r?.14:.18,n.length*(r?.03:.04)),a-=Math.min(.22,o.length*(r?.07:.08)),Number(e.pendingGoalCount||0)===0&&t&&o.length===0&&(a+=r?s?.03:.05:.12),r&&i&&n.length<4&&(a=Math.min(a,s?.86:.9)),rt(a)}function Bs(e,t,n){let o=e.budgetLimitExceeded?.2:e.budgetWarning?.72:.96;return t||(o-=.18),o-=Math.min(.3,n.length*.05),rt(o)}function Os(e,t,n){var r;let o=Math.max(.18,e.historicalEvaluationScore??((r=e.objectiveKernel)==null?void 0:r.profitScore)??.5);return o+=t?.12:-.08,o+=Math.min(.1,n.length*.02),o+=Math.min(.08,Number(e.artifactCount||0)*.01),e.budgetWarning&&(o-=.08),rt(o)}function Ds(e){const t=[];return t.push(...Ws(e)),e.requiresExternalEvidence&&e.blockers.length>0?(t.push(`Use NodeMemory.Recall, Web.Search, and Web.FetchPage or Browser.Actionbook to re-check public evidence around blocker: ${e.blockers[0]}, then Extract.Structured and Evidence.Save the strongest source before retrying.`),t.push("If the latest conclusion depends on outside facts, gather 2-3 authoritative sources with Web.Search, condense them with Extract.Structured, and persist the strongest citation with Evidence.Save before changing direction.")):e.blockers.length>0?(t.push(`Use NodeMemory.Recall plus SearchInFiles/ReadFileRange to inspect blocker: ${e.blockers[0]}, then GetDiagnostics or RunTests to confirm the narrowest safe retry.`),t.push("Inspect the latest failure with SearchInFiles/ReadFileRange, reduce the scope, and only ApplyPatch the smallest safe change before re-running RunBuild or RunTests.")):e.requiresExternalEvidence&&!e.succeeded?t.push("Use NodeMemory.Recall, Web.Search, and Web.FetchPage or Browser.Actionbook to gather missing outside facts, then Extract.Structured and Evidence.Save the strongest evidence before another recommendation."):e.succeeded||t.push("Use NodeMemory.Recall, inspect the latest failure with SearchInFiles/ReadFileRange, and generate a safe retry plan before another ApplyPatch."),e.requiresExternalEvidence&&e.missionProgress<.92?t.push("Use Web.Search to find 2-3 authoritative sources, inspect them with Web.FetchPage or Browser.Actionbook, then Extract.Structured the strongest facts and Evidence.Save the citation-backed gap with NodeMemory.Upsert."):e.missionProgress<.92&&t.push("Use RunBuild, RunTests, or GetDiagnostics to verify the latest result against the mission and capture the biggest remaining gap with NodeMemory.Upsert."),e.requiresExternalEvidence&&e.facts.length>0?t.push("Use NodeMemory.Recall to pick the strongest learned fact, re-open its source with Web.FetchPage or Browser.Actionbook, then Extract.Structured and Evidence.Save a durable citation before the next summary."):e.facts.length>0&&t.push("Use NodeMemory.Recall to pick the strongest learned fact, inspect the target slice with ReadFileRange, then ApplyPatch only the smallest needed change."),e.requiresExternalEvidence&&e.pendingGoalCount===0&&e.succeeded&&e.blockers.length===0?t.push("Evidence.Save the final supporting sources, RecordArtifact a concise source-backed brief, and NodeMemory.Upsert the citations plus follow-up monitoring needs."):e.pendingGoalCount===0&&e.succeeded&&e.blockers.length===0&&t.push("RecordArtifact the completed result, summarize what changed, and NodeMemory.Upsert the final decisions plus any follow-up still needed."),t.map(n=>Q(n,220))}function Ws(e){return e.businessOpportunityMission?e.missionProgress<.25?["Use Web.Search to collect 5-8 solo-founder-friendly markets, then Web.FetchPage current sources and Extract.Structured a ledger of pain severity, buyer urgency, and substitute behavior.","For every surviving market, Evidence.Save one public demand signal and one monetization signal so the next tranche can rank them by time-to-cash."]:e.missionProgress<.5?["Reduce the field to the top 3 candidates by comparing willingness to pay, competitor density, and time-to-cash from current public evidence, then Extract.Structured the ranking rationale.","Use Evidence.Save to preserve the strongest pricing, customer pain, and demand citations for each surviving wedge before narrowing the frontier again."]:e.missionProgress<.75?["Compare the leading wedges on acquisition channel, distribution confidence, MVP scope, and defensibility, then rank the fastest path to first revenue for a solo developer.","RecordArtifact a short frontier brief that explains why the losing wedges dropped out and what evidence would be needed to revive them."]:e.requiresExternalEvidence?["Turn the leading wedge into experiments: landing message, pricing hypothesis, first-sale scenario, and a 7-day execution playbook, then Web.Search/Web.FetchPage one more benchmark for the riskiest claim.","Extract.Structured and Evidence.Save one additional authority on distribution or pricing, then RecordArtifact the tighter go-to-market playbook for immediate execution."]:["Turn the leading wedge into experiments: landing message, pricing hypothesis, first-sale scenario, and a 7-day execution playbook with the smallest MVP that can get to cash quickly.","RecordArtifact the tighter go-to-market playbook and preserve which assumptions still need live validation before shipping."]:[]}function _s(e){const t=[`Mission progress: ${bt(e.missionProgress)}`,`Survival score: ${bt(e.survivalScore)}`,`Profit score: ${bt(e.profitScore)}`,`Outcome: ${e.succeeded?"latest run succeeded":"latest run failed"}`];return e.facts.length>0&&t.push(`Facts: ${e.facts.slice(0,2).join(" | ")}`),e.blockers.length>0&&t.push(`Blockers: ${e.blockers.slice(0,2).join(" | ")}`),e.nextActions.length>0&&t.push(`Next: ${e.nextActions[0]}`),t.push(`Complete: ${e.isComplete?"yes":"no"}`),t.push(`Auto replan: ${e.shouldAutoReplan?"yes":"no"}`),e.shouldStretchReview&&t.push("Stretch review: yes"),e.persistentResearchMission&&t.push("Research loop: persistent evidence mission"),t.join(`
|
|
51
|
+
`)}function Ie(e,t){return String(e.kind||e.status||"").toLowerCase()===t}function vt(...e){for(const t of e){const n=Q(t,220);if(n)return n}return""}function Q(e,t){const n=String(e??"").replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-3)).trimEnd()}...`}function Te(e,t){return t.some(n=>e.includes(n))}function $e(e,t,n){const o=e.toLowerCase();return n.findIndex(r=>r.toLowerCase()===o)===t}function rt(e){return Math.min(1,Math.max(0,Number.isFinite(e)?e:0))}function bt(e){return rt(e).toFixed(2)}const dn=512,mn=512;function y(e){return typeof e=="string"?e.trim():""}function et(e,t=120){const n=y(e).replace(/\s+/g," ");return to(n,t)}function Ee(e,t=4e3){const n=y(e).replace(/\r\n/g,`
|
|
52
|
+
`).replace(/\r/g,`
|
|
53
|
+
`);return n.length>t?`${n.slice(0,Math.max(0,t-3))}...`:n}function to(e,t){const n=y(e);return n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}function Us(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(1,Math.trunc(t)):128}function Gs(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function qe(e,...t){return`${e}:${Gs(`${e}|${t.map(n=>y(n)).join("|")}`)}`}function no(e){const t=y(e).replace(/[\s_-]+/g,"").toLowerCase();return t==="pending"?"Pending":t==="queued"?"Queued":t==="assigned"?"Assigned":t==="running"?"Running":t==="paused"?"Paused":t==="completed"||t==="done"?"Completed":t==="stopped"||t==="cancelled"?"Stopped":t==="archived"?"Archived":"Failed"}function oo(e){const t=y(e).replace(/[\s_-]+/g,"").toLowerCase();return t==="pending"?"Pending":t==="routed"?"Routed":t==="running"?"Running":t==="completed"||t==="done"?"Completed":t==="archived"?"Archived":"Failed"}function zs(e){return e==="Completed"?"result":e==="Failed"?"error":e==="Stopped"?"stop":e==="Archived"?"archive":"event"}function js(e){return e==="Completed"?"mission-result":e==="Failed"?"mission-failed":e==="Archived"?"mission-archived":"mission"}function Ks(e){return e==="Completed"?{score:1,verdict:"success"}:e==="Failed"?{score:0,verdict:"failed"}:e==="Stopped"?{score:.25,verdict:"stopped"}:e==="Archived"?{score:.1,verdict:"archived"}:{score:.5,verdict:"unknown"}}function Vs(e){return e==="Completed"?{score:1,verdict:"success"}:e==="Failed"?{score:0,verdict:"failed"}:e==="Archived"?{score:.1,verdict:"archived"}:{score:.5,verdict:"unknown"}}function Qs(e){var n;const t=(((n=e.match(/\.[^.\\/]+$/))==null?void 0:n[0])||"").toLowerCase();return[".md",".markdown",".txt",".html",".pdf"].includes(t)?"document":[".json",".csv",".xml",".yml",".yaml"].includes(t)?"data":[".cs",".js",".ts",".tsx",".razor"].includes(t)?"code":[".png",".jpg",".jpeg",".gif",".webp"].includes(t)?"image":"result"}function Hs(e){return{id:y(e.id),missionId:y(e.missionId),workItemId:y(e.workItemId),agentId:y(e.agentId),kind:y(e.kind)||"result",title:y(e.title),summary:y(e.summary),content:y(e.content),path:y(e.path),createdAtIso:y(e.createdAtIso)||new Date(0).toISOString()}}function Ys(e){return{id:y(e.id),missionId:y(e.missionId),workItemId:y(e.workItemId),agentId:y(e.agentId),evaluator:y(e.evaluator)||"fleet-heuristic",subjectKind:y(e.subjectKind)||"work-item",verdict:y(e.verdict),score:typeof e.score=="number"&&Number.isFinite(e.score)?Math.max(0,Math.min(1,e.score)):0,notes:y(e.notes),createdAtIso:y(e.createdAtIso)||new Date(0).toISOString()}}function Js(e,t){const n=no(e.state),o=n,r=y(e.title)||"Work Item",s=y(e.goal),i=y(e.lastOutcome);return{id:qe("artifact:work-item",e.id,n),missionId:y(e.missionId),workItemId:y(e.id),agentId:y(e.assignedAgentId),kind:zs(n),title:`${r} - ${o}`,summary:et(i||o,200),content:Ee([`Title: ${r}`,`Goal: ${s}`,`State: ${o}`,`AgentId: ${y(e.assignedAgentId)}`,"Outcome:",i].join(`
|
|
54
|
+
`),8e3),path:"",createdAtIso:y(e.completedAtIso)||t}}function Xs(e,t){const n=no(e.state),o=y(e.title)||"Work Item",{score:r,verdict:s}=Ks(n);return{id:qe("evaluation:work-item",e.id,n),missionId:y(e.missionId),workItemId:y(e.id),agentId:y(e.assignedAgentId),evaluator:"fleet-heuristic",subjectKind:"work-item",verdict:s,score:r,notes:Ee(`${o} - ${n}
|
|
55
|
+
${y(e.lastOutcome)}`,2e3),createdAtIso:y(e.completedAtIso)||t}}function Zs(e,t){const n=oo(e.state),o=y(e.objective)||"Mission",r=y(e.lastOutcome),s=e.workItemIds||[];return{id:qe("artifact:mission",e.id,n),missionId:y(e.id),workItemId:y(e.rootWorkItemId),agentId:"",kind:js(n),title:`${to(o,96)} - ${n}`,summary:et(r||n,200),content:Ee([`Objective: ${o}`,`State: ${n}`,`WorkItems: ${s.length}`,"Outcome:",r].join(`
|
|
56
|
+
`),8e3),path:"",createdAtIso:y(e.completedAtIso)||t}}function ei(e,t){const n=oo(e.state),o=y(e.objective)||"Mission",{score:r,verdict:s}=Vs(n);return{id:qe("evaluation:mission",e.id,n),missionId:y(e.id),workItemId:y(e.rootWorkItemId),agentId:"",evaluator:"fleet-heuristic",subjectKind:"mission",verdict:s,score:r,notes:Ee(`${o}
|
|
57
|
+
${n}
|
|
58
|
+
${y(e.lastOutcome)}`,2e3),createdAtIso:y(e.completedAtIso)||t}}function ti(e,t){const n=y(e.path),o=y(e.title)||n.split(/[\\/]/).pop()||"Workspace file",r=et(e.summary,160),s=[n?`Path: ${n}`:"",(n&&y(e.content),""),y(e.content)].filter((i,a,l)=>i||a>0&&l[a-1]);return{id:qe("artifact:workspace-file",e.workItemId,n,o),missionId:y(e.missionId),workItemId:y(e.workItemId),agentId:y(e.agentId),kind:y(e.kind)||Qs(n),title:et(o,120),summary:r,content:Ee(s.join(`
|
|
59
|
+
`),4e3),path:n,createdAtIso:t}}function fn(e,t){const n=new Map,o=[];for(const r of e)if(r.id)for(n.has(r.id)||o.push(r.id),n.set(r.id,{...r});o.length>t;){const s=o.shift();s&&n.delete(s)}return o.map(r=>n.get(r)).filter(Boolean)}function gn(e,t){const n=y(t==null?void 0:t.missionId),o=y(t==null?void 0:t.workItemId),r=y(t==null?void 0:t.agentId),s=Us(t==null?void 0:t.limit);return[...e].reverse().filter(a=>!(n&&a.missionId!==n||o&&a.workItemId!==o||r&&a.agentId!==r)).slice(0,s).reverse()}function el(e={}){var d,p,f,g;const t=y(e.nowIso)||new Date().toISOString(),n=[],o=[];(d=e.workItem)!=null&&d.id&&(n.push(Js(e.workItem,t)),o.push(Xs(e.workItem,t))),(p=e.mission)!=null&&p.id&&(n.push(Zs(e.mission,t)),o.push(ei(e.mission,t)));for(const m of e.workspaceFiles||[])m.workItemId&&n.push(ti(m,t));const r=fn([...(e.existingArtifacts||[]).map(Hs),...n],dn),s=fn([...(e.existingEvaluations||[]).map(Ys),...o],mn),i=gn(r,e.filter),a=gn(s,e.filter),l=o.find(m=>m.subjectKind==="work-item"),c=n.find(m=>{var v;return m.workItemId===y((v=e.workItem)==null?void 0:v.id)}),u=n.find(m=>{var v;return m.missionId===y((v=e.mission)==null?void 0:v.id)&&!m.agentId});return{artifactCount:r.length,evaluationCount:s.length,recentArtifactCount:i.length,recentEvaluationCount:a.length,workItemArtifactKind:(c==null?void 0:c.kind)||"none",workItemEvaluationVerdict:(l==null?void 0:l.verdict)||"none",workItemEvaluationScore:(l==null?void 0:l.score)??0,missionArtifactKind:(u==null?void 0:u.kind)||"none",structuredUpgradePlanned:!!(e.structuredEvaluationAvailable&&((f=e.workItem)!=null&&f.id||(g=e.mission)!=null&&g.id)),observableArtifactCap:dn,observableEvaluationCap:mn,artifacts:r,evaluations:s,recentArtifacts:i,recentEvaluations:a,projectionLines:[`Artifacts: ${r.length}`,`Evaluations: ${s.length}`,`Recent artifacts: ${i.length}`,`Recent evaluations: ${a.length}`,`Work item kind: ${(c==null?void 0:c.kind)||"none"}`,`Work item verdict: ${(l==null?void 0:l.verdict)||"none"}`,`Structured upgrade: ${e.structuredEvaluationAvailable?"planned":"not configured"}`],governanceLines:["MirrorWorkItemOutcomeRecords builds one work-item artifact and one fleet-heuristic work-item evaluation before optional structured evaluation upgrade.","MirrorMissionOutcomeRecords builds one mission artifact and one fleet-heuristic mission evaluation before optional structured evaluation upgrade.","StoreArtifact and StoreEvaluation ignore empty ids, clone stored records, preserve first insertion order for existing ids, and evict oldest records above 512.","GetRecentArtifacts and GetRecentEvaluations scan newest-first, apply optional mission/work-item/agent filters, cap the normalized limit at one or more, then reverse results back to chronological order.","Workspace file artifacts classify document, data, code, image, or result from the path extension unless an explicit kind is provided.","Artifact projection is browser-local and must not mutate live AgentFleet, MissionControl, artifacts, evaluations, model state, live AI, browser, LocalBridge, filesystem, Cloudflare, billing, or evidence-save adapters."],summaryLine:n.length>0?`${n.length} artifact${n.length===1?"":"s"} and ${o.length} evaluation${o.length===1?"":"s"} would be mirrored locally.`:"No work-item or mission outcome is ready for artifact projection."}}function tl(e){return["Agent Artifact Projection:",`Artifacts: ${e.artifactCount}`,`Evaluations: ${e.evaluationCount}`,`Recent: ${e.recentArtifactCount} artifacts / ${e.recentEvaluationCount} evaluations`,`Work item: ${e.workItemArtifactKind} / ${e.workItemEvaluationVerdict} / ${e.workItemEvaluationScore.toFixed(2)}`,`Mission kind: ${e.missionArtifactKind}`,`Structured upgrade: ${e.structuredUpgradePlanned?"planned":"not configured"}`,"Projection:",...e.projectionLines.map(t=>`- ${t}`),e.recentArtifacts.length>0?"Recent artifacts:":"",...e.recentArtifacts.map(t=>`- ${t.title}: ${t.kind} / ${t.summary}`),e.recentEvaluations.length>0?"Recent evaluations:":"",...e.recentEvaluations.map(t=>`- ${t.subjectKind}: ${t.verdict} / ${t.score.toFixed(2)}`),"Governance:",...e.governanceLines.map(t=>`- ${t}`)].filter(Boolean).join(`
|
|
60
|
+
`)}const ni=16,oi=8,ri=8,si=12,ii=6,ai=6,li=12,ci=6,ui=6,di="Tool: Browser.Actionbook",pn="Args:";function L(e){return typeof e=="string"?e.trim():e==null?"":String(e).trim()}function Y(e,t){const n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?Math.max(1,Math.trunc(n)):t}function mi(e,t){return L(t).localeCompare(L(e))}function Et(e,t,n){return[...e].sort((o,r)=>mi(n(o),n(r))).slice(0,t).reverse()}function st(e){const t=L(e);return!t||t==="00000000-0000-0000-0000-000000000000"}function X(e,t){return st(t)||L(e)===t}function qt(e,t,n){return Et(e.filter(o=>X(o.agentId,n.agentId||"")&&X(o.missionId,n.missionId||"")&&X(o.workItemId,n.workItemId||"")),t,o=>o.timestampIso)}function Ft(e,t,n){return Et(e.filter(o=>X(o.agentId,n.agentId||"")&&X(o.missionId,n.missionId||"")&&X(o.workItemId,n.workItemId||"")),t,o=>o.createdAtIso)}function Bt(e,t,n){return Et(e.filter(o=>X(o.agentId,n.agentId||"")&&X(o.missionId,n.missionId||"")&&X(o.workItemId,n.workItemId||"")),t,o=>o.createdAtIso)}function fi(e,t){const n=e.indexOf("{",t);if(n<0)return"";let o=0,r=!1,s=!1,i="";for(let a=n;a<e.length;a+=1){const l=e[a];if(i+=l,r){if(s){s=!1;continue}if(l==="\\"){s=!0;continue}l==='"'&&(r=!1);continue}if(l==='"'){r=!0;continue}if(l==="{"&&(o+=1),l==="}"&&(o-=1,o===0))return i}return""}function ro(e){const t=L(e);if(!t)return null;const n=t.toLowerCase(),o=n.indexOf(di.toLowerCase());if(o<0)return null;const r=n.indexOf(pn.toLowerCase(),o);if(r<0)return{template:"market",summaryText:"Actionbook - market",tooltip:"Template: market"};const s=fi(t,r+pn.length);if(!s)return{template:"actionbook",summaryText:"Actionbook - actionbook",tooltip:"Template: actionbook"};try{const i=JSON.parse(s),a=L(i.template).toLowerCase()||"actionbook",l=L(i.query),c=L(i.url),u=L(i.targetDomain),d=c||u||l;return{template:a,summaryText:d?`Actionbook - ${a} - ${d}`:`Actionbook - ${a}`,tooltip:[`Template: ${a}`,c?`Url: ${c}`:"",l?`Query: ${l}`:"",u?`Target domain: ${u}`:""].filter(Boolean).join(`
|
|
61
|
+
`)}}catch{return{template:"actionbook",summaryText:"Actionbook - actionbook",tooltip:"Template: actionbook"}}}function gi(e,t,n){const o=L(e.agentId);return st(o)?{agentId:"",activity:[],artifacts:[],evaluations:[],refreshedAtIso:t}:{agentId:o,activity:qt(e.activity||[],n.agentActivity,{agentId:o}),artifacts:Ft(e.artifacts||[],n.agentArtifacts,{agentId:o}),evaluations:Bt(e.evaluations||[],n.agentEvaluations,{agentId:o}),refreshedAtIso:t}}function pi(e,t,n){const o=L(e.missionId);if(st(o))return{missionId:"",mission:null,actionbookHint:null,activity:[],artifacts:[],evaluations:[],refreshedAtIso:t};const r=(e.missions||[]).find(a=>L(a.id)===o)||null,s=L(r==null?void 0:r.rootWorkItemId),i=s&&(e.workItems||[]).find(a=>L(a.id)===s)||null;return{missionId:o,mission:r,actionbookHint:ro(i==null?void 0:i.goal),activity:qt(e.activity||[],n.missionActivity,{missionId:o}),artifacts:Ft(e.artifacts||[],n.missionArtifacts,{missionId:o}),evaluations:Bt(e.evaluations||[],n.missionEvaluations,{missionId:o}),refreshedAtIso:t}}function hi(e,t,n){const o=L(e.workItemId);if(st(o))return{workItemId:"",workItem:null,mission:null,actionbookHint:null,activity:[],artifacts:[],evaluations:[],refreshedAtIso:t};const r=(e.workItems||[]).find(a=>L(a.id)===o)||null,s=L(r==null?void 0:r.missionId),i=s&&(e.missions||[]).find(a=>L(a.id)===s)||null;return{workItemId:o,workItem:r,mission:i,actionbookHint:ro(r==null?void 0:r.goal),activity:qt(e.activity||[],n.workItemActivity,{workItemId:o}),artifacts:Ft(e.artifacts||[],n.workItemArtifacts,{workItemId:o}),evaluations:Bt(e.evaluations||[],n.workItemEvaluations,{workItemId:o}),refreshedAtIso:t}}function nl(e={}){var p,f;const t=L(e.nowIso)||new Date().toISOString(),n=e.limits||{},o={agentActivity:Y(n.agentActivity,ni),agentArtifacts:Y(n.agentArtifacts,oi),agentEvaluations:Y(n.agentEvaluations,ri),missionActivity:Y(n.missionActivity,si),missionArtifacts:Y(n.missionArtifacts,ii),missionEvaluations:Y(n.missionEvaluations,ai),workItemActivity:Y(n.workItemActivity,li),workItemArtifacts:Y(n.workItemArtifacts,ci),workItemEvaluations:Y(n.workItemEvaluations,ui)},r=gi(e,t,o),s=pi(e,t,o),i=hi(e,t,o),a=r.activity.length+s.activity.length+i.activity.length,l=r.artifacts.length+s.artifacts.length+i.artifacts.length,c=r.evaluations.length+s.evaluations.length+i.evaluations.length,u=((p=s.actionbookHint)==null?void 0:p.template)||"none",d=((f=i.actionbookHint)==null?void 0:f.template)||"none";return{agentReport:r,missionReport:s,workItemReport:i,totalActivityCount:a,totalArtifactCount:l,totalEvaluationCount:c,agentActivityLimit:o.agentActivity,agentArtifactLimit:o.agentArtifacts,agentEvaluationLimit:o.agentEvaluations,missionActivityLimit:o.missionActivity,missionArtifactLimit:o.missionArtifacts,missionEvaluationLimit:o.missionEvaluations,workItemActivityLimit:o.workItemActivity,workItemArtifactLimit:o.workItemArtifacts,workItemEvaluationLimit:o.workItemEvaluations,missionActionbookTemplate:u,workItemActionbookTemplate:d,projectionLines:[`Agent report: ${r.activity.length} activity / ${r.artifacts.length} artifacts / ${r.evaluations.length} evaluations`,`Mission report: ${s.activity.length} activity / ${s.artifacts.length} artifacts / ${s.evaluations.length} evaluations`,`Work item report: ${i.activity.length} activity / ${i.artifacts.length} artifacts / ${i.evaluations.length} evaluations`,`Mission actionbook: ${u}`,`Work item actionbook: ${d}`,`Refreshed: ${t}`],governanceLines:["BuildAgentReportAsync returns an empty report for Guid.Empty and otherwise reads recent activity, artifacts, and evaluations filtered by agent id.","BuildMissionReportAsync returns an empty report for Guid.Empty, resolves the mission from the snapshot, resolves the root work-item actionbook hint, and uses default limits 12/6/6.","BuildWorkItemReportAsync returns an empty report for Guid.Empty, resolves the work item and mission from the snapshot, parses the work-item goal actionbook hint, and uses default limits 12/6/6.","Recent activity, artifacts, and evaluations are read newest-first, capped with Math.Max(1, limit), then reversed to chronological order like the original AgentFleetService observable APIs.","Execution observatory projection is browser-local and must not call live AgentFleet, MissionControl, LocalBridge, browser automation, filesystem, Cloudflare, billing, or evidence-save adapters."],summaryLine:`Observatory reports ${a} activity, ${l} artifacts, and ${c} evaluations across agent, mission, and work item views.`}}function ol(e){return["Execution Observatory:",...e.projectionLines,"Governance:",...e.governanceLines.map(t=>`- ${t}`)].join(`
|
|
62
|
+
`)}function q(e){return typeof e=="string"?e.trim():""}function vi(e,t="Pending"){const n=q(e).replace(/[\s_-]+/g,"").toLowerCase();return n==="pending"?"Pending":n==="routed"?"Routed":n==="running"?"Running":n==="completed"||n==="done"?"Completed":n==="archived"?"Archived":n==="failed"||n==="blocked"?"Failed":t}function bi(e){const t=q(e).replace(/[\s_-]+/g,"").toLowerCase();return t==="pending"?"Pending":t==="queued"||t==="planned"?"Queued":t==="assigned"?"Assigned":t==="running"?"Running":t==="paused"?"Paused":t==="completed"||t==="done"?"Completed":t==="stopped"||t==="cancelled"?"Stopped":t==="archived"?"Archived":t==="failed"||t==="blocked"?"Failed":"Pending"}function hn(e){return e==="Completed"||e==="Failed"||e==="Stopped"||e==="Archived"}function yt(e){return e==="Completed"||e==="Failed"||e==="Archived"}function vn(e){return e==="Running"||e==="Assigned"||e==="Queued"||e==="Paused"}function bn(e){for(let t=e.length-1;t>=0;t-=1){const n=q(e[t].lastOutcome);if(n)return n}return""}function rl(e={}){var v;const t=q(e.nowIso)||new Date().toISOString(),n=e.mission||{id:"react-local-mission"},o=vi(n.previousState,q(n.targetAgentId)?"Routed":"Pending"),r=(e.workItems||[]).filter(h=>q(h.id)).map(h=>({...h,id:q(h.id),normalizedState:bi(h.state)}));let s,i=q(n.completedAtIso),a=q(n.lastOutcome);r.length===0?(s="Pending",i=""):r.every(h=>h.normalizedState==="Completed")?(s="Completed",i||(i=t),a=bn(r)||a):r.every(h=>h.normalizedState==="Archived")?(s="Archived",i||(i=t)):r.some(h=>vn(h.normalizedState))?(s="Running",i=""):r.every(h=>hn(h.normalizedState))?(s="Failed",i||(i=t),a=bn(r)||a):(s="Routed",i="");const l=yt(s)&&(!yt(o)||o!==s),c=r.filter(h=>h.normalizedState==="Completed").length,u=r.filter(h=>h.normalizedState==="Archived").length,d=r.filter(h=>vn(h.normalizedState)).length,p=r.filter(h=>hn(h.normalizedState)).length,f=r.filter(h=>h.normalizedState==="Failed"||h.normalizedState==="Stopped").length,g=q(n.rootWorkItemId)||q((v=r[0])==null?void 0:v.id),m=r.map(h=>{const A=q(h.title)||h.id,b=q(h.assignedAgentId)||"unassigned";return`${A}: ${h.normalizedState} / ${b}`});return{missionId:q(n.id)||"react-local-mission",objective:q(n.objective)||q(n.normalizedInstruction)||"Mission",previousState:o,projectedState:s,stateText:s,workItemCount:r.length,completedCount:c,archivedCount:u,runningLikeCount:d,terminalCount:p,failedTerminalCount:f,rootWorkItemId:g,completedAtIso:i,lastOutcome:a,shouldMirrorMissionOutcome:l,shouldClearCompletedAt:!yt(s),shouldMirrorToMissionControl:r.length>0,workItemLines:m,governanceLines:["CreateMission starts Routed when TargetAgentId exists and Pending otherwise.","CreateWorkItem starts Queued when AssignedAgentId exists and Pending otherwise, adds the work item to the mission, and sets RootWorkItemId when missing.","RefreshMissionState sets Pending for missions with no work items, Completed when all work items are Completed, Archived when all are Archived, Running when any work item is Running, Assigned, Queued, or Paused, Failed when all work items are terminal, and Routed otherwise.","Completed, Archived, and Failed missions keep or set CompletedAtUtc; Running, Routed, and Pending clear CompletedAtUtc.","A terminal mission transition calls MirrorMissionOutcomeRecordsLocked only when the previous state was non-terminal or changed terminal state.","Mission registry projection is browser-local and must not mutate live AgentFleet, MissionControl, missions, work items, mailbox, pending approvals, artifacts, evaluations, live AI, browser, LocalBridge, filesystem, Cloudflare, billing, or evidence-save adapters."],summaryLine:r.length>0?`${r.length} work item${r.length===1?"":"s"} project mission state ${s}.`:"No work items are attached, so the mission projects Pending."}}function sl(e){return["Agent Mission Registry:",`Mission: ${e.projectedState}`,`Previous: ${e.previousState}`,`Work items: ${e.workItemCount}`,`Completed: ${e.completedCount}`,`Running-like: ${e.runningLikeCount}`,`Terminal: ${e.terminalCount}`,`Mirror mission outcome: ${e.shouldMirrorMissionOutcome?"yes":"no"}`,`CompletedAt: ${e.completedAtIso||"none"}`,e.lastOutcome?`Last outcome: ${e.lastOutcome}`:"","Work items:",...e.workItemLines.map(t=>`- ${t}`),"Governance:",...e.governanceLines.map(t=>`- ${t}`)].filter(Boolean).join(`
|
|
63
|
+
`)}const so=45e3;function W(e){return typeof e=="string"?e.trim():""}function kt(e){const t=W(e);if(!t)return null;const n=Date.parse(t);return Number.isFinite(n)?n:null}function yi(e){return Number.isFinite(e)?Math.max(0,Math.floor(Number(e))):0}function io(e){const t=W(e).replace(/[\s_-]+/g,"").toLowerCase();return t==="instruction"?"instruction":t==="approvalrequest"||t==="approval"?"approval_request":t==="decision"?"decision":t==="handoff"?"handoff":t==="artifact"?"artifact":"unknown"}function ao(e){const t=W(e).toLowerCase();return!["approved","rejected","completed","done","processed","closed"].includes(t)}function ki(e){if((e.mailbox||[]).some(s=>io(s.kind)==="approval_request")||(e.approvalRequests||[]).some(s=>ao(s.status)))return[];const n=`${e.title||""}
|
|
64
|
+
${e.objective||""}
|
|
65
|
+
${e.plannerSummary||""}`.toLowerCase();return W(e.status).toLowerCase()==="blocked"||n.includes("approval")||n.includes("requires approval")||n.includes("waitingtool")||n.includes("waiting tool")?[{id:e.commandId?`${e.commandId}:approval`:"react-local-approval",kind:"approval_request",summary:"Approval required before tool execution."}]:[]}function wi(e){if(e.lease)return e.lease;if(W(e.status).toLowerCase()!=="running")return null;const n=W(e.nowIso)||new Date().toISOString();return{ownerAgentId:"react-local-agent",acquiredAtIso:n,heartbeatAtIso:n,timeoutMs:so}}function Ai(e,t,n,o){return o>0?"Approval mailbox is restored as a tool gate, not as a pending goal.":e==="handoff-ready"?"Lease heartbeat is stale, so the work item is ready for handoff.":t?"Lease is fresh because heartbeat age is within the timeout.":n>0?"Instruction mailbox can queue local agent work.":e==="completed"?"Command is complete; no mailbox-driven execution is pending.":"No active lease or executable mailbox is projected."}function il(e){const t=kt(e.nowIso)??Date.now(),n=wi(e),o=Math.max(1,Number((n==null?void 0:n.timeoutMs)||so)),r=kt(n==null?void 0:n.heartbeatAtIso),s=kt(n==null?void 0:n.acquiredAtIso),i=r??s,a=r!==null?"heartbeat":s!==null?"acquired":"none",l=i===null?null:Math.max(0,t-i),c=l!==null&&l<o,d=[...e.mailbox||[],...ki(e)].map(x=>({...x,kind:io(x.kind)})),p=d.filter(x=>x.kind==="instruction"&&!W(x.completedAtIso)).length,f=d.filter(x=>x.kind==="approval_request"&&!W(x.completedAtIso)).length,g=(e.approvalRequests||[]).filter(x=>ao(x.status)).length,m=f+g,v=d.filter(x=>!W(x.completedAtIso)).length,h=d.filter(x=>W(x.leasedAtIso)||W(x.leaseOwner)).length,A=W(e.status).toLowerCase(),b=!!(n&&!c&&a!=="none"),w=m>0;let k="idle";w?k="waiting-tool":b?k="handoff-ready":c?k="running":p>0?k="queued":(A==="done"||A==="completed")&&(k="completed");const S=p>0,R=!1,I=yi(e.linkedNoteCount),$=W(n==null?void 0:n.ownerAgentId)||"none",T=k==="waiting-tool"?"Hold execution until the approval mailbox is resolved.":k==="handoff-ready"?"Find an available agent and requeue the active goal for handoff.":k==="running"?"Keep touching heartbeat before the 45s lease timeout.":k==="queued"?"Lease the instruction mailbox and enqueue exactly one pending goal.":k==="completed"?"Mirror completion outcome and leave the dispatch queue idle.":"Stay idle until an instruction mailbox or fresh lease appears.",F=[`Instruction mailbox: ${p}`,`Approval mailbox: ${m}`,`Pending mailbox: ${v}`,`Leased mailbox: ${h}`],G=[`Lease freshness uses ${a==="heartbeat"?"LeaseHeartbeatAtUtc":a==="acquired"?"LeaseAcquiredAtUtc fallback":"no timestamp"}; acquired age alone cannot steal a live heartbeat.`,`Instruction mailbox queues goals: ${S?"yes":"no"}.`,"Approval mailbox queues goals: no; it restores a waiting-tool gate.",`Linked code notes in local context: ${I}.`];return{runtimeState:k,summaryLine:Ai(k,c,p,m),leaseOwnerAgentId:$,leaseFresh:c,leaseAgeMs:l,leaseTimeoutMs:o,leaseHeartbeatSource:a,handoffReady:b,mailboxCount:d.length,instructionMailboxCount:p,approvalRequestCount:m,pendingMailboxCount:v,leasedMailboxCount:h,queuesInstruction:S,approvalQueuesGoal:R,approvalGateActive:w,nextRuntimeAction:T,governanceLines:G,mailboxLines:F}}function al(e){return["Agent Fleet Runtime Projection:",`Runtime state: ${e.runtimeState}`,`Lease: ${e.leaseFresh?"fresh":"not-fresh"}; owner ${e.leaseOwnerAgentId}; source ${e.leaseHeartbeatSource}; timeout ${e.leaseTimeoutMs}ms.`,`Mailbox: instructions ${e.instructionMailboxCount}, approvals ${e.approvalRequestCount}, pending ${e.pendingMailboxCount}, leased ${e.leasedMailboxCount}.`,`Handoff ready: ${e.handoffReady?"yes":"no"}`,`Approval gate active: ${e.approvalGateActive?"yes":"no"}`,`Next runtime action: ${e.nextRuntimeAction}`,"Governance:",...e.governanceLines.map(t=>`- ${t}`)].join(`
|
|
66
|
+
`)}const Ci="00000000-0000-0000-0000-000000000000";function Me(e){return typeof e=="string"?e.trim():""}function ie(e){return Me(e)}function xt(e){const t=ie(e).toLowerCase();return!t||t===Ci}function ve(e,t){const n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function $i(e){const t=Me(e).replace(/[\s_-]+/g,"").toLowerCase();return t==="instruction"?"Instruction":t==="result"?"Result":t==="blocker"?"Blocker":t==="reviewrequest"||t==="review"?"ReviewRequest":t==="approvalrequest"||t==="approval"?"ApprovalRequest":"System"}function tt(e){return new Set((e||[]).map(t=>ie(t)).filter(Boolean))}function Ii(e){return new Map((e||[]).filter(t=>!xt(t.id)).map((t,n)=>[ie(t.id),{...t,id:ie(t.id),sequence:ve(t.sequence,n),pendingMailboxIds:[...tt(t.pendingMailboxIds)]}]))}function Ri(e){return[...e||[]].sort((t,n)=>ve(t.sequence,Number.MAX_SAFE_INTEGER)-ve(n.sequence,Number.MAX_SAFE_INTEGER))}function xi(e,t){return Me(e==null?void 0:e.name)||t||"unknown-agent"}function Si(e,t){return ie(e.currentMailboxId)===t?!0:tt(e.pendingMailboxIds).has(t)}function ll(e={}){const t=Ii(e.agents),n=tt(e.existingMailboxIds),o=tt(e.pendingApprovalIds),r=new Set,s=[],i=[];let a=ve(e.mailboxSequence,0);for(const g of Ri(e.availableMailbox)){const m=ie(g.id),v=ie(g.agentId),h=F=>{i.push({mailboxId:m,agentId:v,reason:F})};if(xt(m)){h("empty-mailbox-id");continue}if(xt(v)){h("empty-agent-id");continue}if(n.has(m)){h("already-hydrated");continue}if(r.has(m)){h("duplicate-batch-mailbox");continue}r.add(m);const A=ve(g.sequence,0)>0?ve(g.sequence,0):a+1;a=Math.max(a,A);const b=$i(g.kind),w=t.get(v),k=xi(w,v),S=Me(g.payload)||Me(g.summary);let R="stored-only",I=!1,$=!1,T=!1;!w||w.isArchived?R="agent-missing-or-archived":b==="ApprovalRequest"?($=!o.has(m),R="restored-approval"):b!=="Instruction"?R="ignored-non-executable":Si(w,m)?R="already-current-or-pending":(I=!0,T=!w.pauseRequested&&!w.stopRequested,R=T?"queued-goal":"queued-goal-no-dispatch"),s.push({mailboxId:m,agentId:v,agentName:k,sequence:A,kind:b,instruction:S,action:R,enqueuesAgent:T,queuesGoal:I,restoresApproval:$})}const l=s.filter(g=>g.queuesGoal).length,c=s.filter(g=>g.restoresApproval).length,u=s.filter(g=>g.enqueuesAgent).length,d=s.filter(g=>!g.queuesGoal&&!g.restoresApproval).length,p=[`Available mailbox: ${(e.availableMailbox||[]).length}`,`Accepted: ${s.length}`,`Skipped: ${i.length}`,`Queued goals: ${l}`,`Restored approvals: ${c}`,`Enqueued agents: ${u}`,`Sequence max: ${a}`,`Force hydrate: ${e.force?"yes":"no"}`],f=s.length>0?`${s.length} mailbox item${s.length===1?"":"s"} would be hydrated locally.`:"No available mailbox item would be accepted by hydration.";return{changed:s.length>0,force:!!e.force,inputMailboxCount:(e.availableMailbox||[]).length,acceptedMailboxCount:s.length,skippedMailboxCount:i.length,queuedGoalCount:l,restoredApprovalCount:c,enqueuedAgentCount:u,storedOnlyCount:d,sequenceMax:a,acceptedMailbox:s,skippedMailbox:i,hydrationLines:p,governanceLines:["HydrateAvailableMailboxAsync is skipped when MissionControl is absent or the 4000ms MailboxHydrationInterval has not elapsed unless forced.","ApplyHydratedMailboxLocked processes available mailbox by Sequence and ignores empty ids, empty AgentId values, already hydrated ids, and duplicate ids in the same batch.","Accepted mailbox records advance the local mailbox sequence and mark the hydration pass as changed before agent-specific execution rules run.","ApprovalRequest mailbox records call UpsertRestoredApprovalLocked and must not enqueue pending goals.","Only Instruction mailbox records may drive execution through CanMailboxDriveExecution.","Instruction mailbox records enqueue one pending goal unless the mailbox is already current or pending, and EnqueueAgentLocked is projected only when pause/stop are not requested.","Mailbox hydration projection is browser-local and must not mutate live AgentFleet, MissionControl, mailbox records, pending approvals, dispatch queues, live AI, browser, LocalBridge, filesystem, Cloudflare, billing, or evidence-save adapters."],summaryLine:f}}function cl(e){return["Agent Mailbox Hydration:",`Changed: ${e.changed?"yes":"no"}`,`Accepted: ${e.acceptedMailboxCount}`,`Queued goals: ${e.queuedGoalCount}`,`Restored approvals: ${e.restoredApprovalCount}`,`Enqueued agents: ${e.enqueuedAgentCount}`,"Hydration:",...e.hydrationLines.map(t=>`- ${t}`),e.acceptedMailbox.length>0?"Accepted mailbox:":"",...e.acceptedMailbox.map(t=>`- ${t.agentName}: ${t.kind} / ${t.action} / sequence ${t.sequence}`),e.skippedMailbox.length>0?"Skipped mailbox:":"",...e.skippedMailbox.map(t=>`- ${t.mailboxId||"empty"}: ${t.reason}`),"Governance:",...e.governanceLines.map(t=>`- ${t}`)].filter(Boolean).join(`
|
|
67
|
+
`)}const Ti=2e3,lo=3,co=1e3;function yn(e){const t=String(e??"");return t.trim()?Math.trunc(t.length/lo):0}function Pi(e=0,t=0){return co}const Li=.8;function le(e){return typeof e=="string"?e.trim():""}function it(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function re(e){return Math.max(0,it(e)??0)}function kn(e){const t=it(e);return t===null||t<=0?null:Math.trunc(t)}function Mi(e){const t=it(e);return t===null||t<=0?null:Ne(t)}function Ne(e){return Math.round(Math.max(0,e)*1e4)/1e4}function V(e,t){if(!e)return null;const n=Object.entries(e);for(const o of t){const r=n.find(([i])=>i.trim().toLowerCase()===o.toLowerCase());if(!r)continue;const s=it(r[1].replace(/[$,\s]/g,""));if(s!==null)return s}return null}function Ni(e,t){if(!e)return null;const n=Object.entries(e);for(const o of t){const r=n.find(([i])=>i.trim().toLowerCase()===o.toLowerCase());if(!r)continue;const s=r[1].trim().toLowerCase();if(["true","yes","1","on"].includes(s))return!0;if(["false","no","0","off"].includes(s))return!1}return null}function St(e){return Math.trunc(e).toLocaleString("en-US")}function uo(e){return`$${Ne(e).toFixed(4).replace(/\.?0+$/,"")}`}function Ei(e,t=!1){const n=e*Li;return t?Ne(n):Math.max(1,Math.ceil(n))}function wt(e,t,n,o,r,s=!1){if(o===null)return{id:e,label:t,current:n,limit:o,warningThreshold:null,ratio:null,state:"tracking",display:`${t} ${r(n)} tracking`};const i=Ei(o,s),a=o<=0?0:n/o,l=n>=o?"exceeded":n>=i?"warning":"within";return{id:e,label:t,current:n,limit:o,warningThreshold:i,ratio:a,state:l,display:`${t} ${r(n)}/${r(o)}`}}function qi(e){const t=e.filter(r=>r.state==="exceeded");if(t.length>0)return{warningRaised:!0,limitExceeded:!0,statusText:`Budget exceeded: ${t.map(r=>r.display).join("; ")}`};const n=e.filter(r=>r.state==="warning");return n.length>0?{warningRaised:!0,limitExceeded:!1,statusText:`Budget warning: ${n.map(r=>r.display).join("; ")}`}:{warningRaised:!1,limitExceeded:!1,statusText:e.some(r=>r.limit!==null)?"Within budget":"Tracking only"}}function Fi(e,t){const n=e.filter(o=>o.limit!==null).map(o=>`${o.id} ${o.id==="cost"?uo(o.limit):St(o.limit)}`);return n.length===0?`Budget policy updated - tracking only - auto-pause ${t?"on":"off"}`:`Budget policy updated - ${n.join(" / ")} - auto-pause ${t?"on":"off"}`}function ul(e={}){var ke;const t=(ke=e.progressDigest)==null?void 0:ke.metadata,n=e.lastRun||{},o=re(n.tokensUsed??V(t,["lastRunTokensUsed","tokensUsed"])),r=re(n.estimatedPoints??V(t,["lastRunEstimatedPoints","estimatedPoints"])),s=Ne(re(n.estimatedCostUsd??V(t,["lastRunEstimatedCostUsd","estimatedCostUsd"]))),i=o>0||r>0||s>0,a=re(e.totalTokensUsed??V(t,["totalTokensUsed","tokensTotal","tokens"]))+o,l=re(e.estimatedPointsUsed??V(t,["estimatedPointsUsed","pointsUsed","points"]))+r,c=Ne(re(e.estimatedCostUsd??V(t,["estimatedCostUsdTotal","costUsdTotal","costUsd"]))+s),u=kn(e.tokenBudgetLimit??V(t,["tokenBudgetLimit","tokenLimit"])),d=kn(e.pointBudgetLimit??V(t,["pointBudgetLimit","pointLimit"])),p=Mi(e.costBudgetLimitUsd??V(t,["costBudgetLimitUsd","costLimitUsd"])),f=e.autoPauseWhenLimitExceeded??Ni(t,["autoPauseWhenLimitExceeded","autoPause"])??!0,g=[wt("tokens","tokens",a,u,St),wt("points","points",l,d,St),wt("cost","cost",c,p,uo,!0)],m=qi(g),v=m.limitExceeded&&f,h=le(e.status).toLowerCase()==="paused",A=v||h?"paused":m.limitExceeded?"exceeded":m.warningRaised?"warning":g.some(K=>K.limit!==null)?"within":"tracking",b=!e.previousLimitExceeded&&m.limitExceeded||!e.previousWarningRaised&&m.warningRaised||i,w=le(n.provider??(t==null?void 0:t.provider))||"local-react",k=le(n.modelId??(t==null?void 0:t.modelId))||"adapter-gated",S=le(n.reasoningEffort??(t==null?void 0:t.reasoningEffort))||"default",R=le(e.estimatedInputText??(t==null?void 0:t.clientEstimatedInputText)),I=le(e.estimatedOutputText??(t==null?void 0:t.clientEstimatedOutputText)),$=re(e.imageCount??V(t,["imageCount","generatedImageCount"])),T=yn(R),F=yn(I),G=Math.trunc($)*Pi(0,0),x=`TokenService fallback length/${lo}, ${Ti}ms timeout, image=${co}`,U=Fi(g,f),Fe=g.map(K=>{const Oe=K.ratio===null?"tracking":`${Math.round(K.ratio*100)}%`;return`${K.label}: ${K.display} (${K.state}, ${Oe})`}),Be=A==="paused"?"Budget limit is exceeded and auto-pause would stop the agent before more work.":A==="exceeded"?"Budget limit is exceeded, but auto-pause is off for this projection.":A==="warning"?"Budget usage crossed the 80% warning threshold.":A==="within"?"Budget limits are configured and current usage is within bounds.":"Budget is tracking usage without configured limits.";return{budgetState:A,warningRaised:m.warningRaised,limitExceeded:m.limitExceeded,shouldPause:v,autoPauseWhenLimitExceeded:f,statusText:m.statusText,summaryLine:Be,policyTimelineMessage:U,shouldEmitBudgetTimeline:b,lastRunApplied:i,provider:w,modelId:k,reasoningEffort:S,clientEstimatedInputTokens:T,clientEstimatedOutputTokens:F,estimatedImageTokens:G,tokenEstimateSource:x,metrics:g,metricLines:Fe,governanceLines:["Warning threshold is 80% of each configured token, point, or cost limit.","Limit comparison is inclusive: current usage greater than or equal to the limit is exceeded.","When auto-pause is on and a limit is exceeded, the original fleet pauses the agent.","Run accounting updates provider, model, reasoning effort, last-run usage, totals, status text, and budget timeline state.","Client token estimates preserve the original TokenService performance guard: async worker budget is 2s, failure falls back to text length / 3, and images reserve 1000 tokens."]}}function dl(e){return["Agent Budget Guard:",`State: ${e.budgetState}`,`Status: ${e.statusText}`,`Auto-pause: ${e.autoPauseWhenLimitExceeded?"on":"off"}`,`Should pause: ${e.shouldPause?"yes":"no"}`,`Provider/model: ${e.provider} / ${e.modelId} / ${e.reasoningEffort}`,`Timeline: ${e.shouldEmitBudgetTimeline?"budget event pending":"no new budget event"}`,`Client estimate: input ${e.clientEstimatedInputTokens.toLocaleString("en-US")} / output ${e.clientEstimatedOutputTokens.toLocaleString("en-US")} / image ${e.estimatedImageTokens.toLocaleString("en-US")}`,`Token estimate source: ${e.tokenEstimateSource}`,"Metrics:",...e.metricLines.map(t=>`- ${t}`),"Governance:",...e.governanceLines.map(t=>`- ${t}`)].join(`
|
|
68
|
+
`)}const wn=8;function ye(e){return typeof e=="string"?e.trim():""}function Re(e){return ye(e)}function Ot(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(0,Math.trunc(t)):0}function mo(e){const t=ye(e);if(!t)return null;const n=Date.parse(t);return Number.isFinite(n)?n:null}function Bi(e){const t=new Set,n=[];for(const o of e.map(Re).filter(Boolean))t.has(o)||(t.add(o),n.push(o));return n}function Oi(e){return e.filter(t=>!t.isArchived).filter(t=>!t.stopRequested).filter(t=>ye(t.activeGoal)||Ot(t.pendingGoalCount)>0).map(t=>t.id)}function An(e,t){return ye(e==null?void 0:e.name)||ye(e==null?void 0:e.id)||t||"unknown-agent"}function Di(e,t){if(!e)return"missing";if(e.isArchived)return"archived";if(e.pauseRequested)return"paused";if(e.stopRequested)return"stopped";if(e.actorBusy)return"actor-busy";const n=mo(e.leaseRetryAvailableAtIso);return n!==null&&n>t?"lease-retry-wait":e.isRunning?"already-running":!ye(e.activeGoal)&&Ot(e.pendingGoalCount)===0?"no-goal":null}function ml(e={}){const t=(e.agents||[]).filter(k=>Re(k.id)).map(k=>({...k,id:Re(k.id)})),n=new Map(t.map(k=>[k.id,k])),r=(e.dispatchQueueIds&&e.dispatchQueueIds.length>0?e.dispatchQueueIds:Oi(t)).map(Re).filter(Boolean),s=Bi(r),i=mo(e.nowIso)??Date.now(),a=Math.max(1,Ot(e.concurrencyLimit)||wn),l=t.filter(k=>k.isRunning).length,c=Math.max(0,a-l),u=[],d=[];for(const k of s){const S=n.get(k),R=Di(S,i);if(R){u.push({agentId:k,name:An(S,k),reason:R});continue}d.length<c&&d.push(k)}const p=d.map(k=>An(n.get(k),k)),f=Re(e.selectedAgentId),g=f?s.includes(f):!1,m=d[0]||"",v=p[0]||"none",h=Math.max(0,r.length-s.length),A=s.length-u.length,b=[`Input queue: ${r.length}`,`Dispatch set: ${s.length}`,`Duplicates suppressed: ${h}`,`Skipped candidates: ${u.length}`,`Runnable candidates: ${A}`,`Startable now: ${d.length}`],w=m?`${v} is the first runnable agent after dispatch skip rules.`:s.length>0?"Dispatch queue has candidates, but all are skipped or concurrency is full.":"Dispatch queue is empty until a runnable active goal or pending goal appears.";return{queueInputCount:r.length,uniqueQueueCount:s.length,duplicateCount:h,dispatchSetCount:s.length,runningCount:l,concurrencyLimit:a,availableSlots:c,canDequeue:d.length>0,firstRunnableAgentId:m,firstRunnableAgentName:v,selectedAgentQueued:g,toStartAgentIds:d,toStartAgentNames:p,skippedAgents:u,runnableCount:A,queueLines:b,governanceLines:["Enqueue uses a dispatch set so the same agent id appears only once in the queue.","Dequeue removes the candidate from the dispatch set before evaluating skip rules.","Archived, paused, stopped, actor-busy, lease-retry, already-running, and no-goal agents are skipped.",`Scheduler may start queued agents only while running count is below the ${wn} default concurrency limit.`],summaryLine:w}}function fl(e){return["Agent Dispatch Queue:",`Can dequeue: ${e.canDequeue?"yes":"no"}`,`First runnable: ${e.firstRunnableAgentName}`,`Running slots: ${e.runningCount}/${e.concurrencyLimit}`,`Selected queued: ${e.selectedAgentQueued?"yes":"no"}`,"Queue:",...e.queueLines.map(t=>`- ${t}`),e.skippedAgents.length>0?"Skipped:":"",...e.skippedAgents.map(t=>`- ${t.name}: ${t.reason}`),"Governance:",...e.governanceLines.map(t=>`- ${t}`)].filter(Boolean).join(`
|
|
69
|
+
`)}function nt(e){return typeof e=="string"?e.trim():""}function Tt(e){return nt(e)}function fo(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(0,Math.trunc(t)):0}function Wi(e){return e==="Next"||e==="ReplacePending"?e:"Append"}function go(e){return nt(e).replace(/\s+/g," ")}function _i(e){const t=new Set,n=[];for(const o of e.map(Tt).filter(Boolean))t.has(o)||(t.add(o),n.push(o));return n}function Cn(e,t){return nt(e==null?void 0:e.name)||nt(e==null?void 0:e.id)||t||"unknown-agent"}function Ui(e){return Array.isArray(e.pendingGoals)?e.pendingGoals.map(go).filter(Boolean):Array.from({length:fo(e.pendingGoalCount)},(t,n)=>`pending-${n+1}`)}function gl(e={}){const t=Wi(e.queueMode),n=go(e.instruction),o=n.length>0,r=fo(e.contextRefCount),s=e.createAgentIfNone!==!1,i=e.missionControlAvailable!==!1,a=(e.agents||[]).filter(I=>Tt(I.id)).map(I=>({...I,id:Tt(I.id)})),l=new Map(a.map(I=>[I.id,I])),c=_i(e.selectedAgentIds&&e.selectedAgentIds.length>0?e.selectedAgentIds:a.map(I=>I.id)),u=c.filter(I=>{const $=l.get(I);return $&&!$.isArchived}),d=c.length-u.length,p=o&&u.length===0&&s,f=u.length===1?l.get(u[0]):void 0,g=!!(o&&i&&(f!=null&&f.canDelegate)),m=[];let v=0;if(o&&u.length>0&&!g)for(const I of u){const $=l.get(I);if(!$)continue;const T=Ui($),F=t==="ReplacePending"?T.length:0,G=t==="Append"?T.length:0,x=t==="ReplacePending"?[n]:t==="Next"?[n,...T]:[...T,n];v+=F,m.push({agentId:I,name:Cn($,I),pendingBefore:T.length,pendingAfter:x.length,insertedAt:G,replacedPendingCount:F,pauseCleared:!!$.pauseRequested,stopCleared:!!$.stopRequested})}const h=m.length,A=h>0,b=h>0,w=b,k=b?"Instruction":"None",S=f!=null&&f.canDelegate?Cn(f,f.id):"none",R=o?p?"No valid selected agent exists, so the original service would fall back to SubmitMissionAsync.":g?`${S} can delegate; MissionControl may route this as a structured mission instead of direct queueing.`:h>0?`${h} agent${h===1?"":"s"} would receive an Instruction mailbox and queued goal.`:"No direct instruction queue mutation would be staged.":"Direct instruction is empty, so no queue mutation would be staged.";return{queueMode:t,normalizedInstruction:n,instructionReady:o,selectedAgentCount:c.length,validAgentCount:u.length,invalidAgentCount:d,queuedAgentCount:h,fallbackToMission:p,delegationCandidateName:S,shouldDelegateToMission:g,contextRefCount:r,createsMailbox:b,mailboxKind:k,schedulerWake:w,replacedPendingCount:v,selectedAgentQueued:A,queuedAgents:m,queueLines:[`Mode: ${t}`,`Selected agents: ${c.length}`,`Valid agents: ${u.length}`,`Invalid/archived agents: ${d}`,`Context refs: ${r}`,`Queued agents: ${h}`,`Replaced pending goals: ${v}`,`Mailbox kind: ${k}`,`Scheduler wake: ${w?"yes":"no"}`],governanceLines:["SubmitDirectInstructionAsync trims empty instructions and exits before queue mutation.","No valid target agents fall back to SubmitMissionAsync with CreateAgentIfNone when allowed.","QueueGoalLocked creates an Instruction mailbox, updates the agent goal and mind focus, resets lease retry, and enqueues the agent.","Append places the new instruction after existing pending goals.","Next places the new instruction before existing pending goals.","ReplacePending stops and clears existing pending goals before queueing the new instruction.","Direct instruction projection is browser-local and does not execute a live Agent."],summaryLine:R}}function pl(e){return["Agent Direct Instruction Queue:",`Ready: ${e.instructionReady?"yes":"no"}`,`Mode: ${e.queueMode}`,`Queued agents: ${e.queuedAgentCount}`,`Fallback mission: ${e.fallbackToMission?"yes":"no"}`,`Delegation candidate: ${e.delegationCandidateName}`,`Scheduler wake: ${e.schedulerWake?"yes":"no"}`,"Queue:",...e.queueLines.map(t=>`- ${t}`),e.queuedAgents.length>0?"Queued targets:":"",...e.queuedAgents.map(t=>`- ${t.name}: pending ${t.pendingBefore} -> ${t.pendingAfter}, inserted at ${t.insertedAt}, replaced ${t.replacedPendingCount}`),"Governance:",...e.governanceLines.map(t=>`- ${t}`)].filter(Boolean).join(`
|
|
70
|
+
`)}const po=800,Pt=6e3,ho=8;function Qe(e){return typeof e=="string"?e.trim():""}function ze(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(0,Math.trunc(t)):0}function $n(e){const t=Qe(e);if(!t)return null;const n=Date.parse(t);return Number.isFinite(n)?n:null}function Gi(e){return e===null?"none":new Date(e).toISOString()}function zi(e){return Math.min(e+1,ho)}function ji(e){const t=Math.max(0,e-1),n=po*2**t;return Math.min(n,Pt)}function Ki(e,t){return e.isArchived?"archived":e.pauseRequested?"paused":e.stopRequested?"stopped":t?"stale-ticket":"none"}function hl(e={}){const t=$n(e.nowIso)??Date.now(),n=Math.min(ze(e.leaseRetryAttempt),ho),o=zi(n),r=ji(o),s=r>=Pt,i=$n(e.leaseRetryAvailableAtIso),a=i===null?0:Math.max(0,i-t),l=i!==null&&a===0,c=ze(e.leaseRetryTicket),u=e.scheduledTicket===null||e.scheduledTicket===void 0?c:ze(e.scheduledTicket),d=u!==c,p=Ki(e,d),f=!!Qe(e.activeGoal)||ze(e.pendingGoalCount)>0,g=l&&p==="none",m=Qe(e.agentId)||"react-local-agent",v=Qe(e.name)||m,h=c+1,A=Gi(i),b=p!=="none"?`Lease retry callback would be ignored because the retry is ${p}.`:g?"Lease retry delay has elapsed; the original service would enqueue the agent and trigger the scheduler.":i!==null?`Lease retry is waiting ${a}ms before enqueue is allowed.`:`Next lease retry would use attempt ${o} with a ${r}ms delay.`;return{agentId:m,name:v,currentAttempt:n,nextAttempt:o,nextDelayMs:r,minDelayMs:po,maxDelayMs:Pt,cappedAtMaxDelay:s,leaseRetryTicket:c,scheduledTicket:u,staleTicketIgnored:d,leaseRetryAvailableAtIso:A,dueInMs:a,retryDue:l,hasRunnableGoal:f,invalidationReason:p,shouldEnqueueAfterDelay:g,resetAttempt:0,resetTicket:h,resetClearsAvailableAt:!0,queueLines:[`Current attempt: ${n}`,`Next attempt: ${o}`,`Next delay: ${r}ms`,`Available at: ${A}`,`Due in: ${a}ms`,`Retry ticket: ${c}`,`Scheduled ticket: ${u}`,`Runnable goal present: ${f?"yes":"no"}`,`Should enqueue after delay: ${g?"yes":"no"}`],governanceLines:["ScheduleLeaseRetry increments LeaseRetryAttempt, caps it at 8, and computes exponential backoff from 800ms.","Lease retry delay is capped at 6000ms.","ScheduleLeaseRetry stores LeaseRetryAvailableAtUtc and captures the incremented LeaseRetryTicket.","Retry callbacks are ignored when the agent is archived, paused, stopped, or the ticket is stale.","When the delay is due, the original callback enqueues the agent and triggers the scheduler.","ResetLeaseRetryBackoff clears the available-at timestamp, resets attempt to 0, and increments the ticket."],summaryLine:b}}function vl(e){return["Agent Lease Retry Backoff:",`Agent: ${e.name}`,`Attempt: ${e.currentAttempt} -> ${e.nextAttempt}`,`Next delay: ${e.nextDelayMs}ms`,`Available at: ${e.leaseRetryAvailableAtIso}`,`Retry due: ${e.retryDue?"yes":"no"}`,`Invalidation: ${e.invalidationReason}`,`Should enqueue: ${e.shouldEnqueueAfterDelay?"yes":"no"}`,"Queue:",...e.queueLines.map(t=>`- ${t}`),"Governance:",...e.governanceLines.map(t=>`- ${t}`)].join(`
|
|
71
|
+
`)}function M(e){return typeof e=="string"?e.trim():""}function At(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(0,Math.trunc(t)):0}function Vi(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.min(1,Math.max(0,t)):0}function vo(e,t){const n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function bo(e){const t=M(e);if(!t)return null;const n=Date.parse(t);return Number.isFinite(n)?n:null}function yo(e,t="none"){return M(e==null?void 0:e.name)||M(e==null?void 0:e.id)||t}function Qi(e,t){const n=M(e.currentMissionId),o=M(t.currentMissionId);return!!(n&&o&&n===o)}function Hi(e,t){return t?M(e.currentWorkItemId)===t?!0:(e.pendingWorkItemIds||[]).map(M).includes(t):!1}function Yi(e,t,n,o){const r=At(e.completedRunCount),s=At(e.failedRunCount),i=r+s,a=i>0?r/i:.5,l=Vi(e.averageEvaluationScore),c=Qi(e,t)?2:0,u=At(e.pendingGoalCount),d=bo(e.leaseRetryAvailableAtIso),p=d!==null&&d>n?4:0,f=c+a*4+l*6-u*1.25-p;return{agentId:M(e.id),name:yo(e),score:f,sequence:o,pendingGoalCount:u,successRatio:a,averageEvaluationScore:l,sameMissionBonus:c,retryPenalty:p}}function Ji(e){return(e||[]).filter(t=>M(t.id)).map((t,n)=>({...t,id:M(t.id),sequence:vo(t.sequence,n)}))}function bl(e={}){const t=e.sourceAgent&&M(e.sourceAgent.id)?{...e.sourceAgent,id:M(e.sourceAgent.id)}:null,n=M(e.workItemId||(t==null?void 0:t.currentWorkItemId)),o=M(e.workItemTitle)||n||"work-item",r=bo(e.nowIso)??Date.now(),s=Ji(e.candidates),i=M(e.leaseOwnerAgentId),a=t&&n&&i&&i!==t.id?s.find(b=>b.id===i&&!b.isArchived):void 0,l=t&&n?s.filter(b=>b.id!==t.id).filter(b=>!b.isArchived).filter(b=>!b.isRunning).filter(b=>!M(b.activeGoal)).map((b,w)=>Yi(b,t,r,vo(b.sequence,w))).sort((b,w)=>w.score-b.score||b.pendingGoalCount-w.pendingGoalCount||b.sequence-w.sequence):[],c=l[0]?s.find(b=>b.id===l[0].agentId):void 0,u=a||c,d=a?"existing-lease-owner":u?"best-score":"none",p=u?Hi(u,n):!1,f=!!(u&&n&&!p&&M(t==null?void 0:t.activeGoal)),g=!!(t&&n&&u),m=M(u==null?void 0:u.id)||"none",v=u?yo(u):"none",h=l.map(b=>`${b.name}: score ${b.score.toFixed(2)}, pending ${b.pendingGoalCount}, success ${b.successRatio.toFixed(2)}, eval ${b.averageEvaluationScore.toFixed(2)}`),A=!t||!n?"No source work item is checked out, so handoff is not available.":u?d==="existing-lease-owner"?`${v} already owns the lease, so handoff resolves to the existing owner.`:`${v} is the best available handoff candidate by score.`:"No available handoff candidate passed the source, archive, running, and active-goal filters.";return{handoffReady:g,selectionReason:d,selectedTargetId:m,selectedTargetName:v,workItemId:n,workItemTitle:o,queueMode:"Next",candidateCount:s.length,eligibleCandidateCount:l.length,targetAlreadyOwnsWorkItem:p,willQueueGoal:f,scoredCandidates:l,candidateLines:h,governanceLines:["TryHandoffLeasedWorkItem returns false when the source agent has no current work item.","An existing non-archived LeaseOwnerAgentId is selected before scoring other candidates.","Scored candidates exclude the source agent, archived agents, running agents, and agents with ActiveGoal.","Score = same mission bonus 2 + success ratio * 4 + average evaluation * 6 - pending goals * 1.25 - future retry penalty 4.","Candidates sort by descending score, then lower pending goal count, then lower sequence.","If the target does not already own the work item, QueueGoalLocked uses AgentDirectInstructionQueueMode.Next.","Lease handoff projection is browser-local and does not call MissionControl, actor queue, or live Agent services."],summaryLine:A}}function yl(e){return["Agent Lease Handoff:",`Ready: ${e.handoffReady?"yes":"no"}`,`Selected target: ${e.selectedTargetName}`,`Reason: ${e.selectionReason}`,`Work item: ${e.workItemTitle}`,`Queue mode: ${e.queueMode}`,`Will queue source goal: ${e.willQueueGoal?"yes":"no"}`,`Target already owns item: ${e.targetAlreadyOwnsWorkItem?"yes":"no"}`,"Candidates:",...e.candidateLines.map(t=>`- ${t}`),"Governance:",...e.governanceLines.map(t=>`- ${t}`)].join(`
|
|
72
|
+
`)}const Xi=1e4,ko=new Set(["Planning","Running","WaitingTool"]);function j(e){return typeof e=="string"?e.trim():""}function wo(e){const t=j(e);if(!t)return null;const n=Date.parse(t);return Number.isFinite(n)?n:null}function Ct(e){return new Date(e).toISOString()}function Zi(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>0?Math.trunc(t):Xi}function ea(e){const t=j(e).replace(/[\s_-]+/g,"").toLowerCase();return t==="queued"?"Queued":t==="planning"||t==="planned"?"Planning":t==="running"?"Running":t==="waitingtool"||t==="blocked"?"WaitingTool":t==="paused"?"Paused":t==="completed"||t==="done"?"Completed":t==="failed"?"Failed":t==="stopped"?"Stopped":"Idle"}function In(e,t){return j(e==null?void 0:e.name)||j(e==null?void 0:e.id)||t||"unknown-agent"}function ta(e){return(e||[]).filter(t=>j(t.id)).map(t=>({...t,id:j(t.id)}))}function na(e){return(e||[]).filter(t=>j(t.id)).map(t=>({...t,id:j(t.id)}))}function oa(e,t,n,o){if(e.isArchived)return"archived";if(!ko.has(t))return"non-runtime-state";const r=wo(e.lastHeartbeatAtIso);return r!==null&&n-r<o?"heartbeat-fresh":null}function kl(e={}){const t=wo(e.nowIso)??Date.now(),n=Ct(t),o=Zi(e.heartbeatIntervalMs),r=j(e.selectedAgentId),s=ta(e.agents),i=na(e.workItems),a=new Map(i.map(m=>[m.id,m])),l=[],c=[];let u=0;for(const m of s){const v=ea(m.state);!m.isArchived&&ko.has(v)&&(u+=1);const h=oa(m,v,t,o);if(h){c.push({agentId:m.id,name:In(m,m.id),reason:h});continue}const A=j(m.currentWorkItemId),b=A?a.get(A):void 0,w=!!(b&&j(b.leaseOwnerAgentId)===m.id);l.push({agentId:m.id,name:In(m,m.id),state:v,lastHeartbeatAtIso:n,nextHeartbeatAtIso:Ct(t+o),touchesWorkItem:w,workItemId:w?A:"none"})}const d=r?l.find(m=>m.agentId===r):void 0,p=l.filter(m=>m.touchesWorkItem).length,f=[`Agents: ${s.length}`,`Runtime eligible: ${u}`,`Touched agents: ${l.length}`,`Touched work items: ${p}`,`Skipped agents: ${c.length}`,`Interval: ${o}ms`],g=l.length>0?`${l.length} runtime agent${l.length===1?"":"s"} would receive LastHeartbeatAtUtc=${n}.`:"Heartbeat pump would not touch any agent until a runtime state is due.";return{heartbeatIntervalMs:o,agentCount:s.length,eligibleRuntimeAgentCount:u,touchedAgentCount:l.length,touchedWorkItemCount:p,selectedAgentTouched:!!d,selectedWorkItemTouched:!!(d!=null&&d.touchesWorkItem),nextPumpAtIso:Ct(t+o),touchedAgents:l,skippedAgents:c,heartbeatLines:f,governanceLines:["TouchHeartbeatPump only considers Planning, Running, and WaitingTool agents.","Archived agents and non-runtime states are skipped before heartbeat mutation.","Agents with LastHeartbeatAtUtc newer than the 10000ms interval are skipped.","TouchAgentHeartbeat always updates LastHeartbeatAtUtc for due runtime agents.","Work item LeaseHeartbeatAtUtc updates only when CurrentWorkItemId exists and LeaseOwnerAgentId matches the agent.","The original service mirrors touched agents and lease-owned work items to MissionControl.","Heartbeat projection is browser-local and does not start timers, schedulers, MissionControl, or live Agent services."],summaryLine:g}}function wl(e){return["Agent Heartbeat Pump:",`Touched agents: ${e.touchedAgentCount}`,`Touched work items: ${e.touchedWorkItemCount}`,`Selected agent touched: ${e.selectedAgentTouched?"yes":"no"}`,`Selected work item touched: ${e.selectedWorkItemTouched?"yes":"no"}`,`Next pump at: ${e.nextPumpAtIso}`,"Heartbeat:",...e.heartbeatLines.map(t=>`- ${t}`),e.touchedAgents.length>0?"Touched:":"",...e.touchedAgents.map(t=>`- ${t.name}: state ${t.state}, work item ${t.workItemId}, next ${t.nextHeartbeatAtIso}`),e.skippedAgents.length>0?"Skipped:":"",...e.skippedAgents.map(t=>`- ${t.name}: ${t.reason}`),"Governance:",...e.governanceLines.map(t=>`- ${t}`)].filter(Boolean).join(`
|
|
73
|
+
`)}const ra=3e4,sa=new Set(["Planning","Running","WaitingTool"]);function _(e){return typeof e=="string"?e.trim():""}function ia(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(0,Math.trunc(t)):0}function $t(e,t){const n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?Math.max(0,Math.trunc(n)):t}function aa(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>0?Math.trunc(t):ra}function xe(e){const t=_(e);if(!t)return null;const n=Date.parse(t);return Number.isFinite(n)?n:null}function la(e){const t=_(e).replace(/[\s_-]+/g,"").toLowerCase();return t==="queued"?"Queued":t==="planning"||t==="planned"?"Planning":t==="running"?"Running":t==="waitingtool"||t==="blocked"?"WaitingTool":t==="paused"?"Paused":t==="completed"||t==="done"?"Completed":t==="failed"?"Failed":t==="stopped"?"Stopped":"Idle"}function ca(e,t){return _(e==null?void 0:e.name)||_(e==null?void 0:e.id)||t||"unknown-agent"}function ua(e){return!!_(e.activeGoal)||ia(e.pendingGoalCount)>0}function da(e,t,n,o){const r=xe(e.lastHeartbeatAtIso);return r===null||t-r>=n||o}function ma(e){return(e||[]).filter(t=>_(t.id)).map((t,n)=>({...t,id:_(t.id),sequence:$t(t.sequence,n)})).sort((t,n)=>$t(t.sequence,0)-$t(n.sequence,0))}function Al(e={}){const t=xe(e.nowIso)??Date.now(),n=aa(e.staleThresholdMs),o=xe(e.browserHiddenAtIso),r=xe(e.browserVisibleAtIso),s=o!==null&&(r===null||r>=o),i=_(e.selectedAgentId),a=_(e.reason)||"scheduler recovery",l=ma(e.agents),c=[],u=[];for(const v of l){const h=la(v.state),A=_(v.id),b=ca(v,A),w=k=>{u.push({agentId:A,name:b,reason:k})};if(v.isArchived){w("archived");continue}if(v.pauseRequested){w("paused");continue}if(v.stopRequested){w("stopped");continue}if(!ua(v)){w("no-goal");continue}if(v.runtimeTaskActive){w("runtime-task-active");continue}if(v.actorBusy){w("actor-busy");continue}if(sa.has(h)){if(!da(v,t,n,s)){w("heartbeat-fresh");continue}c.push({agentId:A,name:b,stateBefore:h,recoveryReason:"stale-runtime",resetLeaseRetry:!0,queuesWorkItem:!!_(v.currentWorkItemId),refreshesMission:!_(v.currentWorkItemId)&&!!_(v.currentMissionId),enqueuesAgent:!0});continue}if(h==="Queued"){if(v.dispatchQueued){w("queued-already-dispatched");continue}const k=xe(v.leaseRetryAvailableAtIso);if(k!==null&&k>t){w("lease-retry-wait");continue}c.push({agentId:A,name:b,stateBefore:h,recoveryReason:"queued-not-dispatched",resetLeaseRetry:!1,queuesWorkItem:!1,refreshesMission:!1,enqueuesAgent:!0});continue}w("non-recoverable-state")}const d=i?c.find(v=>v.agentId===i):void 0,p=c.filter(v=>v.recoveryReason==="stale-runtime").length,f=c.filter(v=>v.recoveryReason==="queued-not-dispatched").length,g=[`Agents: ${l.length}`,`Recovered: ${c.length}`,`Stale runtime: ${p}`,`Queued re-enqueue: ${f}`,`Skipped: ${u.length}`,`Threshold: ${n}ms`,`Browser visibility recovery: ${s?"yes":"no"}`,`Reason: ${a}`],m=c.length>0?`${c.length} agent${c.length===1?"":"s"} would be recovered into the dispatch queue.`:"No stale or dropped queued agent is recoverable right now.";return{staleThresholdMs:n,agentCount:l.length,recoveredCount:c.length,staleRuntimeRecoveredCount:p,queuedReenqueueCount:f,selectedAgentRecovered:!!d,selectedRecoveryReason:(d==null?void 0:d.recoveryReason)||"none",browserVisibilityRecovery:s,recoveredAgents:c,skippedAgents:u,recoveryLines:g,governanceLines:["RecoverStaleExecutionsLocked iterates agents by Sequence.","Archived, paused, stopped, no-goal, active-runtime, and busy-actor agents are skipped.","Planning, Running, and WaitingTool agents recover only when LastHeartbeatAtUtc is missing, older than 30000ms, or browser visibility recovery is active.","Stale runtime recovery calls ResetLeaseRetryBackoffLocked, queues the current work item or refreshes the mission, sets the agent state to Queued, adds a recover timeline entry, and enqueues the agent.","Queued agents that are not in the dispatch set and whose lease retry delay is due are enqueued again.","Runtime recovery projection is browser-local and does not mutate live AgentFleet, MissionControl, work items, dispatch queues, schedulers, or timers."],summaryLine:m}}function Cl(e){return["Agent Runtime Recovery:",`Recovered: ${e.recoveredCount}`,`Stale runtime: ${e.staleRuntimeRecoveredCount}`,`Queued re-enqueue: ${e.queuedReenqueueCount}`,`Selected recovered: ${e.selectedAgentRecovered?"yes":"no"}`,`Selected reason: ${e.selectedRecoveryReason}`,"Recovery:",...e.recoveryLines.map(t=>`- ${t}`),e.recoveredAgents.length>0?"Recovered agents:":"",...e.recoveredAgents.map(t=>`- ${t.name}: ${t.recoveryReason}, work item queued ${t.queuesWorkItem?"yes":"no"}, mission refresh ${t.refreshesMission?"yes":"no"}`),e.skippedAgents.length>0?"Skipped:":"",...e.skippedAgents.map(t=>`- ${t.name}: ${t.reason}`),"Governance:",...e.governanceLines.map(t=>`- ${t}`)].filter(Boolean).join(`
|
|
74
|
+
`)}const Rn=new Set(["completed","failed","stopped","archived","cancelled"]);function fa(e){return Array.from(new Set((e??[]).map(t=>t.trim()).filter(Boolean)))}function Ao(e,t){var o;const n=(o=e.workItemId)==null?void 0:o.trim();return!n||t.has(n)}function ga(e,t){return(e??[]).filter(n=>{var o,r,s;return Ao(n,t)&&(((o=n.path)==null?void 0:o.trim())||((r=n.summary)==null?void 0:r.trim())||((s=n.content)==null?void 0:s.trim()))}).length}function pa(e,t){return(e??[]).filter(n=>{var o,r,s,i,a;return Ao(n,t)&&(((o=n.verdict)==null?void 0:o.trim())||((r=n.notes)==null?void 0:r.trim())||(n.score??0)>0||((s=n.summary)==null?void 0:s.trim())||((i=n.content)==null?void 0:i.trim())||((a=n.path)==null?void 0:a.trim()))}).length}function ce(e,t){return{shouldDefer:!0,reason:e,...t}}function ha(e,t){return{shouldDefer:!1,reason:e,...t}}function $l(e){var p;const t={targetFileCount:0,artifactEvidenceCount:0,evaluationEvidenceCount:0,outcomeEvidenceCount:0,openWorkItemCount:0,terminalWorkItemCount:0};if(!((p=e==null?void 0:e.reviewTitle)!=null&&p.trim()))return ce("Review title is required before reviewer evidence can be evaluated.",t);const n=fa(e.targetFiles).length,o=e.upstreamWorkItems??[],r=o.filter(f=>Rn.has(f.status)),s=o.filter(f=>!Rn.has(f.status)),i=new Set(r.map(f=>f.id.trim()).filter(Boolean)),a=ga(e.artifacts,i),l=pa(e.evaluations,i),c=r.filter(f=>{var g;return(g=f.lastOutcome)==null?void 0:g.trim()}).length,u=a>0||l>0||c>0,d={targetFileCount:n,artifactEvidenceCount:a,evaluationEvidenceCount:l,outcomeEvidenceCount:c,openWorkItemCount:s.length,terminalWorkItemCount:r.length};return n===0&&!u?ce("Target files and concrete upstream evidence are required before review.",d):n===0?ce("Target files are required before review.",d):u?ha("Reviewer evidence is available.",d):s.length>0?ce("Upstream work is still open; wait for artifact or evaluation evidence.",d):r.length===0?ce("No upstream work item has reached a terminal outcome.",d):ce("Concrete upstream artifact or evaluation evidence is missing.",d)}export{sl as $,Na as A,Ta as B,xa as C,Bn as D,Ma as E,ir as F,Pa as G,Rt as H,ba as I,Pe as J,Ye as K,He as L,rl as M,el as N,nl as O,Wa as P,Ia as Q,wa as R,Ca as S,Io as T,_a as U,ka as V,za as W,Va as X,Ha as Y,Ja as Z,Za as _,Ka as a,tl as a0,ol as a1,al as a2,cl as a3,wl as a4,Cl as a5,dl as a6,fl as a7,pl as a8,Sa as a9,Ra as aa,Aa as ab,$a as ac,vl as ad,yl as ae,Oa as af,Da as ag,va as ah,ja as ai,Ba as b,Qa as c,Ya as d,Xa as e,Zo as f,On as g,il as h,ll as i,kl as j,Al as k,ul as l,ml as m,gl as n,hl as o,ya as p,bl as q,qa as r,$l as s,La as t,Fa as u,xn as v,Ga as w,zt as x,Ua as y,Ea as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{R as i}from"./app-runtime-xD2Z3NdN.js";import{e as l,f as S,g as p,h as m,n as x,i as f}from"./runtimeSettingsPersistenceProjection-BoNWmYjU.js";const u="mindexec.execution-mode.settings.v1";function c(){return typeof window<"u"&&typeof window.localStorage<"u"}function d(t){return f(t)}function a(t){return x(t)}function g(t,e){return{executionMode:d(t.executionMode),directInstructionQueueMode:a(t.directInstructionQueueMode),source:e,updatedAtUtc:new Date().toISOString()}}function I(t){if(!t)return null;try{const e=JSON.parse(t);return{executionMode:d(e.executionMode),directInstructionQueueMode:a(e.directInstructionQueueMode),source:"stored",updatedAtUtc:typeof e.updatedAtUtc=="string"?e.updatedAtUtc:new Date().toISOString()}}catch(e){return i.emit("executionMode.settings.load.failed",{message:e instanceof Error?e.message:String(e)}),null}}function Q(t={}){const e=g(t,"default");if(!c())return i.emit("executionMode.settings.load",{source:e.source,storage:"unavailable"}),e;const o=I(window.localStorage.getItem(u)),n=p({ExecutionMode:e.executionMode}),r=m({DirectInstructionQueueMode:e.directInstructionQueueMode}),M=n.source==="stored"||r.source==="stored"?{executionMode:n.settings.ExecutionMode,directInstructionQueueMode:r.settings.DirectInstructionQueueMode,source:"stored",updatedAtUtc:new Date().toISOString()}:null,s=o??M??e;return i.emit("executionMode.settings.load",{source:s.source,executionMode:s.executionMode,directInstructionQueueMode:s.directInstructionQueueMode}),s}function y(t,e="settings.patch"){const o=g(t,"board");if(!c())return i.emit("executionMode.settings.persist",{storage:"unavailable",patchSource:e,...o}),o;try{window.localStorage.setItem(u,JSON.stringify(o)),l({ExecutionMode:o.executionMode}),S({DirectInstructionQueueMode:o.directInstructionQueueMode}),i.emit("executionMode.settings.persist",{patchSource:e,...o})}catch(n){i.emit("executionMode.settings.persist.failed",{source:e,message:n instanceof Error?n.message:String(n)})}return o}function w(t){const e=Q(t.settings);return{...t,settings:{...t.settings,executionMode:e.executionMode,directInstructionQueueMode:e.directInstructionQueueMode}}}export{w as a,Q as l,y as s};
|