@x-otto/coding 0.0.1-alpha.11 → 0.0.1-alpha.12
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/dist/index.d.ts +198 -54
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +16 -16
package/dist/index.js
CHANGED
|
@@ -9,7 +9,7 @@ GIT binary patch`)){r++;continue}for(let r of e.split(`
|
|
|
9
9
|
`))r.startsWith(`+`)&&!r.startsWith(`+++`)?t++:r.startsWith(`-`)&&!r.startsWith(`---`)&&n++}let a=r>0?`, ${r} binary file${r===1?``:`s`}`:``;return`+${t}/-${n}${a}`}const So=/^[a-zA-Z0-9_-]+$/;function Co(e){return{save(t,n){if(!So.test(t))throw Error(`Invalid jobId for applied diff store: ${t}`);O(e,{recursive:!0}),A(x(e,`${t}.patch`),n,`utf-8`)},load(t){let n=x(e,`${t}.patch`);if(D(n))return k(n,`utf-8`)},delete(t){let n=x(e,`${t}.patch`);D(n)&&$r(n)},loadAll(){return D(e)?Kr(e).filter(e=>Ve(e)===`.patch`).map(t=>({jobId:t.slice(0,-6),diff:k(x(e,t),`utf-8`)})):[]}}}const wo=[`delegate_job`];function To(e){return e.filter(e=>!wo.includes(e.name))}function Eo(){return`job_${mi().replace(/-/g,``).slice(0,8)}`}function Do(e){let t=e.outputDir??x(Be(),`otto-jobs`);return e.registry.setWorktreeCleanupErrorHandler((t,n,r)=>e.logger.warn({jobId:t,op:n,err:r instanceof Error?r.message:String(r)},`Failed to clean up agent job worktree`)),new yo({repoRoot:e.repoRoot,registry:e.registry,notify:e.notify,onWorktreeCleanupError:(t,n)=>{e.logger.warn({op:t,err:n instanceof Error?n.message:String(n)},`Failed to clean up agent job worktree`)},appliedDiffStore:e.appliedDiffDir?Co(e.appliedDiffDir):void 0,spawnRun:({runId:t,prompt:n,outputPath:r,workspaceDir:i,onAwaitingInput:a})=>vo({runId:t,prompt:n,outputPath:r,model:e.getModel(),systemPrompt:e.systemPrompt,tools:[...To(e.buildTools(i)),...e.mcpTools?.()??[]],maxToolTurns:e.maxToolTurns,stream:e.stream,logger:e.logger,hookRegistry:e.hookRegistry,onAwaitingInput:a}),buildOutputPath:e=>(O(t,{recursive:!0}),x(t,`agent-job-${e}.log`)),newJobId:e.newJobId??Eo})}function Oo(e){return Do({repoRoot:e.workspaceDir,registry:Lt,notify:(t,n)=>e.agentJobNotify?.(t,n),buildTools:t=>e.buildToolsForWorkspace(t),mcpTools:()=>e.connectorTools(),getModel:()=>{let t=e.settings.get(`model`),n=(t?e.modelRegistry.find(t):void 0)??e.modelRegistry.getAll().find(e=>e.id!==`__otto_setup__`);if(!n)throw Error(`No model available — configure a model or run /model first.`);return n},stream:e.stream,logger:e.logger,hookRegistry:e.hookRegistry,appliedDiffDir:s()?void 0:x(n,`jobs`,`applied`)})}function ko(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.role!==`assistant`)continue;let r=(n.content??[]).filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
10
10
|
`).trim();if(r.length>0)return r}return``}function Ao(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.role!==`assistant`)continue;let r=n.stopReason;return r===`refusal`||r===`max_tokens`?r:null}return null}function jo(e){let t=Error(e);return t.name=`AbortError`,t}function Mo(e){let t=new Map;return{runSession:async n=>{let r=Date.now(),i=new AbortController;n.taskId&&t.set(n.taskId,i);let a=n.signal,o=()=>i.abort();a&&(a.aborted?i.abort():a.addEventListener(`abort`,o,{once:!0}));let s;s=n.sessionMode===`sticky`&&n.sessionId?e.getSession(n.sessionId)||await e.createSession({id:n.sessionId,agentName:n.agentName,slot:n.slot,modelId:n.model,category:n.category,delegated:!0,promptContext:n.promptContext??(n.agentName?{taskDescription:n.prompt}:void 0),depth:n.depth,readOnly:n.readOnly}):await e.createSession({agentName:n.agentName,slot:n.slot,modelId:n.model,category:n.category,delegated:!0,promptContext:n.promptContext??(n.agentName?{taskDescription:n.prompt}:void 0),depth:n.depth,transient:!0,readOnly:n.readOnly});let c=s.id,l=St(s.coreAgent,{id:c,agentName:n.agentName??`agent`,title:n.agentName??n.prompt.replace(/\s+/g,` `).slice(0,48),prompt:n.prompt,model:n.model??s.model.id,modelDecidedBy:s.modelResolution?.decidedBy,origin:`main`,depth:n.depth??0,abort:()=>s.abort(),messages:()=>s.session.messages()});try{if(i.signal.aborted)throw jo(`Task cancelled before the session started`);let e=n.agentName?`<agent-guardrails>\n${hn}\n</agent-guardrails>\n\n<task>\n${n.prompt}\n</task>`:n.prompt,t=s.prompt(e);t.catch(()=>{}),await Promise.race([t,new Promise((e,t)=>{i.signal.addEventListener(`abort`,()=>{s.abort(),t(jo(`Task cancelled`))})})]);let a=s.session.messages(),o=ko(a),c=Ao(a);return c&&(o=`${o}\n\n[⚠ subagent did not complete cleanly (stop reason: ${c}) — the output above may be partial or unreliable; verify before relying on it]`),{text:o,sessionId:s.id,durationMs:Date.now()-r}}finally{zt.setMessages(c,s.session.messages()),l(),zt.markEnded(c),a?.removeEventListener(`abort`,o),n.taskId&&t.delete(n.taskId),n.sessionMode===`ephemeral`&&await e.removeSession(s.id).catch(t=>{e.logger.warn(`Failed to remove ephemeral session %s: %s`,s.id,t)})}},abortTask:e=>{t.get(e)?.abort()}}}function No(e){let t=new yi({focusTracking:process.env.OTTO_TUI_FOCUS===`1`}),n=new vi({getConfig:e.getConfig,getCwd:e.getCwd,onInteraction:()=>t.recordInteraction(),isFollowUpPending:e.isFollowUpPending,gate:new xi({getCondition:()=>e.getConfig()?.condition,getIdleThresholdMs:()=>e.getConfig()?.idle_threshold_ms,state:t})});return n.registerChannel(new bi({getConfig:e.getConfig})),n.registerChannel(new gi(`hook`,()=>!0,t=>e.emitHookNotification({sessionId:t.sessionId,message:t.message,title:t.title,notification_type:t.type}))),n.registerChannel(new _i({getConfig:e.getConfig,isTrusted:()=>Tr(e.getCwd())})),{dispatcher:n,presenceTracker:t}}function Po(e,t){if(!t||t.length===0)return e;let n=t.map(e=>RegExp(`^`+e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`)+`$`,`i`));return e.filter(e=>!n.some(t=>t.test(e)))}var Fo=class{catalog;derivedModelIds=new Map;constructor(e,t,n){this.modelRegistry=e,this.authStore=t,this.catalog=n??new d}async hydrate(){let e=new Set,t=await this.catalog.load();if(!t)return e;for(let n of Object.values(t.providers)){let t=oe(this.modelRegistry,n.mergeProvider,n.modelIds,{templateApi:n.modelApi});for(let n of t.availableIds)e.add(n);let r=this.derivedModelIds.get(n.mergeProvider)??new Set;for(let e of t.derivedIds)r.add(e);this.derivedModelIds.set(n.mergeProvider,r)}return e}refreshInFlight=null;async refresh(){return this.refreshInFlight||=this.doRefresh().finally(()=>{this.refreshInFlight=null}),this.refreshInFlight}async doRefresh(){let e=this.modelRegistry,t=this.authStore,n=t.listProviders(),r=await Promise.all(n.map(e=>t.getAuthSource(e).catch(()=>null))),i=[];for(let a=0;a<n.length;a++){let o=n[a];if(!r[a]){i.push({provider:o,status:`skipped`,reason:`not authenticated`});continue}let s=await t.resolveAuth(o).catch(()=>null);if(!s?.token){let e=r[a]===`oauth`&&!t.oauth.has(o)?`provider capability not granted — trust the plugin in /extension`:`credential expired or refresh failed — re-login`;i.push({provider:o,status:`skipped`,reason:e});continue}let c=ue(o,s.token,{mode:s.mode,beta:s.beta});if(!c){let t=e.getByProvider(o);if(t.length>0){let e=t.map(e=>e.id);await this.catalog.put(o,{fetchedAt:Date.now(),mergeProvider:o,modelIds:e}).catch(()=>{}),i.push({provider:o,status:`ok`,added:0,kept:e.length,total:e.length,availableIds:e})}else i.push({provider:o,status:`skipped`,reason:`no live models endpoint`});continue}try{let t=Po(await v(c),c.modelIdExclude),n=oe(e,c.mergeProvider,t,{templateApi:c.modelApi}),r=new Set(n.availableIds),a=this.derivedModelIds.get(c.mergeProvider)??new Set;for(let t of a)r.has(t)||e.unregister(t);this.derivedModelIds.set(c.mergeProvider,new Set([...[...a].filter(e=>r.has(e)),...n.derivedIds])),await this.catalog.put(o,{fetchedAt:Date.now(),mergeProvider:c.mergeProvider,modelApi:c.modelApi,modelIds:t}).catch(()=>{}),i.push({provider:o,status:`ok`,added:n.added,kept:n.kept,total:n.total,availableIds:n.availableIds})}catch(e){i.push({provider:o,status:`failed`,reason:e instanceof Error?e.message:String(e)})}}return i}};function Io(e){return e.modelRegistry.getAll()}function Lo(e,t){return e.modelRegistry.resolve(t)}function Ro(e){return e.providerRegistry.list()}function zo(e,t){e.hookRegistry.register(t)}function Bo(e,t){return e.hookRegistry.unregister(t)}async function Vo(e){return e.modelCatalogManager.hydrate()}function Ho(e,t){return e.codingSessionPool.getSessionAvailableModels(t)}function Uo(e,t,n){e.codingSessionPool.setSessionAvailableModels(t,n)}async function Wo(e){return e.modelCatalogManager.refresh()}async function Go(e,t){let n=new Set(t?e.codingSessionPool.getSessionAvailableModels(t):[]),r=ne(e.authStore,`delegation`);return Promise.all(e.modelRegistry.getAll().filter(e=>e.id!==`__otto_setup__`).map(async e=>{let t=await r(e);return{id:e.id,provider:e.provider,strengths:e.strengths??[],available:n.has(e.id),usable:t.usable,...t.reason?{unusableReason:t.reason}:{}}}))}function Ko(e,t){e.notificationDispatcher.registerChannel(t)}function qo(e,t){e.notificationDispatcher.registerChannel(new gi(`inapp`,()=>!0,e=>t(e.title??`otto`,e.message,e.type)))}function Jo(e){e.presenceTracker.recordInteraction()}function Yo(e,t){e.presenceTracker.setFocus(t)}async function Xo(e,t,n){if(!t)return;if(n){e.permissionRegistry.addSessionAlwaysAllow(n,t),e.codingSessionPool.setSessionPermissionAllow(n,e.permissionRegistry.getSessionAlwaysAllow(n)),e.logger.info({tool:t,sessionId:n},`Tool added to session always-allow list`);return}let r=e.settings.get(`permission_always_allow`)??[];r.includes(t)||(e.permissionRegistry.addAlwaysAllow(t),await e.settings.persist({permission_always_allow:[...r,t]}),e.logger.info({tool:t},`Tool added to project always-allow list`))}function Zo(e){return e.settings.get(`permission_mode`)??`auto`}async function Qo(e,t){let n=Zo(e);await e.settings.update({permission_mode:t}),e.settings.persist({permission_mode:t}).catch(n=>e.logger.warn({err:n instanceof Error?n.message:String(n),mode:t},`Failed to persist permission mode`)),e.logger.info({from:n,to:t},`Permission mode set`)}function $o(e,t){return e.permissionRegistry.getSessionAlwaysAllow(t)}async function es(e,t){if(!t)return!1;let n=e.settings.get(`permission_always_allow`)??[];if(!n.includes(t))return!1;let r=n.filter(e=>e!==t);return e.permissionRegistry.setAlwaysAllow(r),await e.settings.persist({permission_always_allow:r}),e.logger.info({tool:t},`Tool removed from project always-allow list`),!0}function ts(e,t){t&&(e.permissionRegistry.clearSessionAlwaysAllow(t),e.codingSessionPool.setSessionPermissionAllow(t,[]),e.logger.info({sessionId:t},`Session always-allow list cleared`))}async function ns(e,t={}){e.ensureNotDisposed(),await e.ensureSettingsLoaded();let n=await e.sessionConfigResolver.resolve(t),r=await e.agentRuntime.createSession(n);return e.notificationDispatcher.attach(r),e.toolsSyncCoordinator?.record(r.id,{agentName:t.agentName,promptPreset:t.promptPreset??(t.agentName?`subagent`:`main`),readOnly:t.readOnly,hasExplicitTools:t.tools!==void 0}),e.logger.info({sessionId:r.id},`Session created`),r}function rs(e,t){return e.codingSessionPool.getSession(t)}async function is(e,t,n){if(!e.storage.storageHost)throw Error(`shareSession requires a configured storage.host`);await e.storage.storageHost.host.updateMetadata(`sessions`,e.workspaceRef?.key,t,{visibility:n.visibility},void 0),e.logger.info({sessionId:t,visibility:n.visibility},`Session visibility changed`)}function as(e){return e.codingSessionPool.active}function os(e,t){return e.codingSessionPool.listSessions(t)}async function ss(e,t){let n=os(e,t).filter(t=>{let n=e.codingSessionPool.getSession(t.id);return n?!(n.transient===!0||n.depth>0||n.listable===!1):!0}),r;try{r=t?.workspaceId===void 0?e.workspaceRef?.key:Ei(t.workspaceId)}catch{r=void 0}if(!r)return n;let i=await e.codingSessionPool.listAllPersistedSessions({workspaceKey:r}).catch(()=>[]),a=t?.workspaceId??e.workspaceRef?.id,o=new Set(n.map(e=>e.id)),s=i.filter(e=>!o.has(e.id)).map(e=>({...e,workspaceId:a})),c=[...n,...s];return c.sort((e,t)=>{let n=e.updatedAt?.getTime()??e.createdAt.getTime();return(t.updatedAt?.getTime()??t.createdAt.getTime())-n}),c}async function cs(e,t){e.notificationDispatcher.detach(t);let n=await e.codingSessionPool.removeSession(t);return n&&(e.toolsSyncCoordinator?.forget(t),e.logger.info({sessionId:t},`Session removed`)),n}async function ls(e,t){let n=await e.codingSessionPool.archiveSession(t);return n&&e.logger.info({sessionId:t},`Session archived`),n}async function us(e,t,n){let r=await e.codingSessionPool.forkSession(t,n);return r&&e.notificationDispatcher.attach(r),r}var ds=class{contexts=new Map;constructor(e){this.deps=e}record(e,t){t.hasExplicitTools||this.contexts.set(e,{agentName:t.agentName,promptPreset:t.promptPreset,readOnly:t.readOnly})}forget(e){this.contexts.delete(e)}resyncOne(e){let t=this.contexts.get(e);return t?this.resyncSession(e,t):!1}resync(){let e=new Set(this.deps.listSessionIds());for(let t of this.contexts.keys())e.has(t)||this.contexts.delete(t);let t=0;for(let[e,n]of this.contexts)this.resyncSession(e,n)&&t++;return t}resyncSession(e,t){let n=this.deps.getSession(e);if(!n)return!1;try{let e=this.deps.sessionConfigResolver.resolveToolsForResync(t.agentName,t.promptPreset,t.readOnly);return n.model.supportsTools===!1&&(e=[]),n.tools=e,!0}catch(t){return this.deps.logger.warn({sessionId:e,err:t instanceof Error?t.message:String(t)},`[session-tools-sync] resync failed for session, skipping (fail-soft)`),!1}}};const fs=C(`@x-otto/coding:plugin-panel-manager`);function ps(e){let t=e.plugins??Vn({cwd:e.workspaceDir,homedir:e.homedir,disabled:e.disabledPlugins}),n=[];for(let e of t){let t=e.manifest.contributes?.panels;if(!t||t.length===0)continue;let r=E(e);if(!r.gated){if(!e.manifest.capabilities?.includes(`tui.renderer`)){fs.warn({pluginId:e.id},`plugin declares contributes.panels but not capabilities:["tui.renderer"], skipped (fail-closed)`);continue}if(r.pendingCapabilities.includes(`tui.renderer`)){fs.warn({pluginId:e.id},`plugin capability "tui.renderer" declared but not yet granted, skipping panels (fail-closed)`);continue}for(let r of t){let t=x(e.dir,r.entry);if(!D(t)){fs.warn({pluginId:e.id,panelId:r.id,modulePath:t},`panel entry not found — postinstall build may not have run`);continue}n.push({id:`${e.id}:${r.id}`,pluginId:e.id,title:r.title,modulePath:t,exportName:r.export??`default`})}}}return n}function ms(e){let t=[];for(let n of e){if(E(n).gated)continue;let e=n.manifest.contributes?.statusItems;if(!e?.length)continue;let r=Un(n.manifest.contributes?.contextKeys);for(let i of e){if((i.point??Mn.statuslineItem)!==Mn.statuslineItem||!Gn(i.when,r))continue;let e=r[i.dataSource.contextKey];e!=null&&t.push({item:{id:`${n.id}:${i.id}`,text:e},order:i.order??0})}}return t.sort((e,t)=>e.order-t.order).map(e=>e.item)}function hs(e){let t=[];for(let n of e){if(E(n).gated)continue;let e=n.manifest.contributes;if(!e?.menus?.length)continue;let r=Un(e.contextKeys);t.push(...rr(Mn.menuItem,e.menus,e.actions,r))}return t}const gs={capability:`tui.renderer`,axis:`renderers`,noun:`renderer`,pendingNote:`RFC-140 D3`,logger:C(`@x-otto/coding:plugin-renderer-loader`),entries:e=>e.manifest.contributes?.renderers,entryPath:e=>e.entry,exportName:e=>e.export,idLogFields:e=>({rendererId:e.id}),logTypeofOnNotFunction:!0,build:(e,t,n)=>({id:`${e.id}:${t.id}`,pluginId:e.id,matcher:t.matcher,render:n}),successLogFields:e=>({rendererId:e.id,matcher:e.matcher})};function _s(e){return Ja(e,gs)}const vs=C(`@x-otto/coding:plugin-a2ui-component-loader`),ys=new Set([`Text`,`Card`,`List`,`Progress`,`Chip`,`Button`]),bs={capability:`a2ui.component`,axis:`a2uiComponents`,noun:`a2ui component`,pendingNote:`RFC-140 D3 pattern`,logger:vs,entries:e=>e.manifest.contributes?.a2uiComponents,entryPath:e=>e.entry,exportName:e=>e.export,idLogFields:e=>({type:e.type}),logTypeofOnNotFunction:!1,preCheck:(e,t)=>ys.has(t.type)?(vs.warn({pluginId:e.id,type:t.type},`plugin a2ui component type collides with builtin reserved type, rejected (R4)`),!1):!0,build:(e,t,n)=>({type:t.type,pluginId:e.id,render:n})};function xs(e){return Ja(e,bs,{key:e=>e.type,onConflict:(e,t)=>{vs.warn({pluginId:e.pluginId,type:e.type,existingOwner:t},`a2ui component type already registered by another plugin, rejected (first-registered wins)`)}})}const Ss={capability:`tui.renderer`,axis:`statusWidgets`,noun:`status widget`,pendingNote:`RFC-140 D3 pattern`,logger:C(`@x-otto/coding:plugin-status-widget-loader`),entries:e=>e.manifest.contributes?.statusWidgets,entryPath:e=>e.entry,exportName:e=>e.export,idLogFields:e=>({widgetId:e.id}),logTypeofOnNotFunction:!0,build:(e,t,n)=>({id:`${e.id}:${t.id}`,pluginId:e.id,render:n,tickMs:t.tickMs,order:t.order}),successLogFields:e=>({widgetId:e.id})};function Cs(e){return Ja(e,Ss)}const ws={capability:`tui.renderer`,axis:`fileViewers`,noun:`file viewer`,pendingNote:`RFC-140 D3 pattern`,logger:C(`@x-otto/coding:plugin-file-viewer-loader`),entries:e=>e.manifest.contributes?.fileViewers,entryPath:e=>e.entry,exportName:e=>e.export,idLogFields:e=>({viewerId:e.id}),logTypeofOnNotFunction:!0,build:(e,t,n)=>({id:`${e.id}:${t.id}`,pluginId:e.id,label:t.label,matcher:t.matcher,render:n,order:t.order}),successLogFields:e=>({viewerId:e.id,matcher:e.matcher})};function Ts(e){return Ja(e,ws)}var Es=class{constructor(e){this.deps=e}listFileCommands(){return[...vr(this.deps.getWorkspaceDir(),this.deps.getActivePlugins()),...this.deps.pluginModuleManager.commands]}computedPluginCommands(){return this.deps.pluginModuleManager.commands}async callMcpTool(e,t,n){let r=this.deps.mcpController.getMcpClient(e);if(!r)throw Error(`MCP server "${e}" not connected or not found`);let i=await r.callTool({name:t,arguments:n});return{content:i.content,isError:i.isError}}getPluginPanelRegistrations(){return ps({workspaceDir:this.deps.getWorkspaceDir(),homedir:ze(),disabledPlugins:this.deps.settings.get(`disabled_plugins`),plugins:this.deps.getActivePlugins()})}getPluginStatusItems(){return ms(this.deps.getActivePlugins())}getGlobalMenuItems(){return hs(this.deps.getActivePlugins())}getPluginRenderers(){return _s(this.deps.getActivePlugins())}getPluginA2uiComponents(){return xs(this.deps.getActivePlugins())}getPluginStatusWidgets(){return Cs(this.deps.getActivePlugins())}getPluginFileViewers(){return Ts(this.deps.getActivePlugins())}getPluginRegistrations(){let e=new Map,t=t=>{let n=e.get(t);return n||(n={pluginId:t},e.set(t,n)),n};for(let e of this.getPluginRenderers()){let n=t(e.pluginId);(n.renderers??=[]).push(e)}for(let e of this.getPluginStatusItems()){let n=t(e.id.split(`:`)[0]??e.id);(n.statusItems??=[]).push(e)}for(let e of this.getPluginPanelRegistrations()){let n=t(e.pluginId);(n.panels??=[]).push(e)}for(let e of this.getPluginA2uiComponents()){let n=t(e.pluginId);(n.a2uiComponents??=[]).push(e)}for(let e of this.getPluginStatusWidgets()){let n=t(e.pluginId);(n.statusWidgets??=[]).push(e)}for(let e of this.getPluginFileViewers()){let n=t(e.pluginId);(n.fileViewers??=[]).push(e)}return[...e.values()]}};const j=C(`@x-otto/coding:plugin-hooks`),Ds=4096;function Os(e,t){let n=Je();return n.OTTO_PLUGIN_DIR=e.pluginDir,n.OTTO_PLUGIN_ID=e.pluginId,e.workspaceDir&&(n.OTTO_WORKSPACE_DIR=e.workspaceDir),t&&Object.assign(n,t),n}function ks(e){let t=Ye(e);return t.safe?null:{success:!1,hook:`pre-check`,command:e,error:`Dangerous command blocked: ${t.reason}`}}function As(e,t){let n=!1,r,i;if(e?.length){let t=typeof e==`string`?e:e.toString(`utf-8`);r=t.slice(0,Ds),n=t.length>Ds}if(t?.length){let e=typeof t==`string`?t:t.toString(`utf-8`);i=e.slice(0,Ds),n||=e.length>Ds}return{stdout:r,stderr:i,truncated:n}}async function js(e,t){return ks(t)||(j.info({pluginId:e.pluginId,command:t},`Executing postinstall hook`),new Promise(n=>{let r=Oi(t,{cwd:e.pluginDir,env:Os(e),shell:!0,stdio:`pipe`}),i=[],a=[];r.stdout?.on(`data`,e=>{i.push(e)}),r.stderr?.on(`data`,e=>{a.push(e)});let o=!1,s=setTimeout(()=>{o=!0,r.kill()},3e4);r.on(`close`,(r,c)=>{clearTimeout(s);let{stdout:l,stderr:u,truncated:d}=As(Buffer.concat(i),Buffer.concat(a)),f={success:!o&&r===0&&c===null,hook:`postinstall`,command:t,exitCode:r,signal:c??void 0,stdout:l,stderr:u,truncated:d||void 0};o&&(f.timeout=!0,f.error=`postinstall hook timed out (30s)`),f.success||j.warn({pluginId:e.pluginId,result:f},`Postinstall hook failed`),n(f)}),r.on(`error`,e=>{clearTimeout(s),n({success:!1,hook:`postinstall`,command:t,error:e.message})})}))}function Ms(e,t,n,r,i){let a=ks(t);if(a){j.warn({pluginId:e.pluginId,command:t},`Setup hook blocked by safety check`),n?.(a);return}if(j.info({pluginId:e.pluginId,command:t},`Executing setup hook (async)`),r){let a=r.spawn({command:t,args:[],options:{shell:!0},owner:{type:`plugin-hook`,id:e.pluginId},category:`plugin`,label:`${e.pluginId}:setup`,lifecycle:`evictable`,killGraceMs:5e3,cwd:e.pluginDir,env:Os(e),signal:i}),o=setTimeout(()=>{j.warn({pluginId:e.pluginId},`Setup hook exceeded 60s — killing`),a.kill({reason:`setup timeout (60s)`})},6e4);o.unref?.();let s=``,c=``;a.onStdoutLine(e=>{s+=e+`
|
|
11
11
|
`}),a.onStderrLine(e=>{c+=e+`
|
|
12
|
-
`}),a.onExit(r=>{clearTimeout(o);let{stdout:i,stderr:a,truncated:l}=As(s,c),u={success:r.code===0&&r.signal===null,hook:`setup`,command:t,exitCode:r.code,signal:r.signal??void 0,stdout:i,stderr:a,truncated:l||void 0};u.success?j.info({pluginId:e.pluginId},`Setup hook succeeded`):j.error({pluginId:e.pluginId,exitCode:r.code,signal:r.signal,stderr:a?.slice(0,512)},`Setup hook failed`),n?.(u)}),a.onError(r=>{j.error({pluginId:e.pluginId,err:r},`Setup hook spawn error`),n?.({success:!1,hook:`setup`,command:t,error:r.message})});return}let o=Oi(t,{cwd:e.pluginDir,env:Os(e),shell:!0,timeout:6e4,stdio:`pipe`}),s=``,c=``;o.stdout?.on(`data`,e=>{s+=e.toString(`utf-8`)}),o.stderr?.on(`data`,e=>{c+=e.toString(`utf-8`)}),o.on(`close`,(r,i)=>{let{stdout:a,stderr:o,truncated:l}=As(s,c),u={success:r===0&&i===null,hook:`setup`,command:t,exitCode:r,signal:i,stdout:a,stderr:o,truncated:l||void 0};u.success?j.info({pluginId:e.pluginId},`Setup hook succeeded`):j.error({pluginId:e.pluginId,exitCode:r,signal:i,stderr:o?.slice(0,512)},`Setup hook failed`),n?.(u)}),o.on(`error`,r=>{j.error({pluginId:e.pluginId,err:r},`Setup hook spawn error`),n?.({success:!1,hook:`setup`,command:t,error:r.message})})}const Ns=C(`@x-otto/coding:plugin-lifecycle`),Ps=`plugin_lifecycle`,Fs=new Set;async function Is(e,t,n){let r=t.get(Ps)?.setupDone??[],i=new Map(r.map(e=>[e.id,e.version])),a=new Set(e.map(e=>e.id));for(let e of i.keys())a.has(e)||i.delete(e);let o=!1;for(let r of e){let e=i.get(r.id),a=r.manifest.version,s=r.manifest.scripts?.setup;if(!s){(e===void 0||e!==a)&&(i.set(r.id,a),o=!0);continue}if(!(e!==void 0&&e===a)){if(E(r).gated){Ns.info({pluginId:r.id},`Setup hook deferred: plugin not yet trusted`);continue}Fs.has(r.id)||(Fs.add(r.id),Ms({pluginDir:r.dir,pluginId:r.id,workspaceDir:n},s,e=>{Fs.delete(r.id),i.set(r.id,a),Ls(t,i)},Vt))}}o&&await Ls(t,i)}async function Ls(e,t){let n=[...t].map(([e,t])=>({id:e,version:t}));await e.persist({[Ps]:{setupDone:n}})}function Rs(e,t){let n;try{n=Jr(t)}catch{return!1}let r;try{r=Jr(e)}catch{r=e}return r===n||r.startsWith(n+We)}const M=C(`@x-otto/coding:plugin-i18n-loader`),zs=/^([a-zA-Z0-9_-]+)\.json$/;function Bs(e){return Buffer.byteLength(e,`utf8`)<=En?e:`${Buffer.from(e,`utf8`).subarray(0,En).toString(`utf8`)}…`}function Vs(e,t,n){let r=new Map,i=S(t,n);if(!Rs(i,t))return M.warn({pluginId:e,i18nDir:n},`i18nDir resolves outside plugin dir, skipped`),r;let a;try{a=Kr(i)}catch{return r}let o=a.filter(e=>zs.test(e)).sort();o.length>Tn&&(M.warn({pluginId:e,i18nDir:n,declared:o.length,limit:Tn},`plugin i18nDir declares more locale files than the per-plugin limit, truncated`),o=o.slice(0,Tn));for(let n of o){let a=zs.exec(n)?.[1];if(!a)continue;let o=S(i,n);if(!Rs(o,t)){M.warn({pluginId:e,filename:n},`i18nDir locale file resolves outside plugin dir, skipped`);continue}let s;try{s=k(o,`utf8`)}catch(t){M.warn({pluginId:e,filename:n,err:String(t)},`i18nDir locale file read failed, skipped`);continue}if(Buffer.byteLength(s,`utf8`)>wn){M.warn({pluginId:e,filename:n,limit:wn},`i18nDir locale file exceeds byte limit, skipped`);continue}let c;try{c=JSON.parse(s)}catch(t){M.warn({pluginId:e,filename:n,err:String(t)},`i18nDir locale file is not valid JSON, skipped`);continue}if(typeof c!=`object`||!c||Array.isArray(c)){M.warn({pluginId:e,filename:n},`i18nDir locale file is not a flat object, skipped`);continue}for(let[e,t]of Object.entries(c)){if(typeof t!=`string`)continue;let n=r.get(e)??{};n[a]=t,r.set(e,n)}}return r}function Hs(e){let t=[];for(let n of e){if(E(n).gated)continue;let e=n.manifest.contributes?.i18nDir,r=n.manifest.contributes?.i18n;if(!e&&!r?.length)continue;let i=e?Vs(n.id,n.dir,e):new Map;if(r?.length)for(let e of r){let t=i.get(e.id)??{};for(let[r,i]of Object.entries(e.translations))r in t&&M.debug({pluginId:n.id,id:e.id,locale:r},`i18n inline entry overrides locale dir value`),t[r]=i;i.set(e.id,t)}let a=[...i.keys()];a.length>Cn&&(M.warn({pluginId:n.id,declared:a.length,limit:Cn},`plugin declares more i18n entries than the per-plugin limit, truncated`),a=a.slice(0,Cn));for(let e of a){let r=i.get(e);if(!r)continue;let a={};for(let[e,t]of Object.entries(r))a[e]=Bs(t);t.push({pluginId:n.id,id:e,translations:a})}}return t}const Us=C(`@x-otto/coding:declarative-agents`);function Ws(e){return{...e,defaultTools:e.defaultTools?.length?Or(e.defaultTools):e.defaultTools,disallowedTools:e.disallowedTools?.length?Or(e.disallowedTools):e.disallowedTools}}function Gs(e,t){let n=et(e);if(!n)return Us.warn({sourcePath:t},`Agent definition missing frontmatter, skipped`),null;let{fields:r,body:i}=n,a=r.get(`name`),o=r.get(`description`);if(!a||!o||!i)return Us.warn({sourcePath:t},`Agent definition requires name/description/body, skipped`),null;let s=Qe(r.get(`tools`)),c=Number.parseInt(r.get(`maxtoolturns`)??``,10),l=Number.parseInt(r.get(`maxtoolturnextensions`)??``,10),u=r.get(`prompt-mode`),d=Qe(r.get(`disallowed-tools`)),f=r.get(`allow-subagents`)===`true`?!0:r.get(`allow-subagents`)===`false`?!1:void 0;return{name:a,description:o,taskTypes:Qe(r.get(`tasktypes`))??[o],capabilities:Qe(r.get(`capabilities`))??[],systemPromptTemplate:i,promptMode:u===`append`||u===`replace`?u:void 0,defaultTools:s,disallowedTools:d?.length?d:void 0,preferredModelTier:r.get(`slot`)??r.get(`tier`),defaultMaxToolTurns:Number.isInteger(c)?c:void 0,defaultMaxToolTurnExtensions:Number.isInteger(l)?l:void 0,allowSubagents:f}}async function Ks(e,t){let{homedir:n}=await import(`node:os`),{join:r}=await import(`node:path`),i=t?.globalDir??r(n(),`.otto`,`agents`),a=r(e,`.otto`,`agents`),s=(t?.plugins??Vn({cwd:e,homedir:n()})).filter(e=>e.manifest.contributes?.agents!==!1).filter(e=>!E(e).gated).map(e=>({dir:r(e.dir,`agents`),claude:!1})),c=o(),l=c&&!br(e).gated,u=[...s,...c?[{dir:r(n(),`.claude`,`agents`),claude:!0}]:[],{dir:i,claude:!1},...l?[{dir:r(e,`.claude`,`agents`),claude:!0}]:[],{dir:a,claude:!1}],d=new Map;for(let{dir:e,claude:t}of u)for(let n of await qs(e))d.set(n.name,t?Ws(n):n);let f=[...d.values()];return f.length>0&&Us.info(`Loaded %d declarative agent(s): %s`,f.length,f.map(e=>e.name).join(`, `)),f}async function qs(e){let{readFile:t,readdir:n}=await import(`node:fs/promises`),{join:r}=await import(`node:path`),i;try{i=await n(e)}catch{return[]}let a=[];for(let n of i.filter(e=>e.endsWith(`.md`)).sort()){let i=r(e,n);try{let e=Gs(await t(i,`utf-8`),i);e&&a.push(e)}catch(e){Us.warn({sourcePath:i,err:e},`Failed to read agent definition, skipped`)}}return a}const Js=C(`@x-otto/coding:declarative-teams`),Ys=new Set([`handoff`,`sequential`,`parallel`,`hierarchical`,`router`]);function Xs(e){if(!e)return;let t=[];for(let n of e.split(`|`)){let[e,r]=n.split(/→|->/);if(e===void 0||r===void 0)continue;let i=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(e=>e!==``),a=r.trim();i.length>0&&a!==``&&t.push({keywords:i,agentId:a})}return t.length>0?t:void 0}function Zs(e,t){let n=et(e);if(!n)return Js.warn({sourcePath:t},`Team definition missing frontmatter, skipped`),null;let{fields:r}=n,i=r.get(`name`),a=r.get(`pattern`),o=Qe(r.get(`agents`));if(!i||!a||!Ys.has(a)||!o||o.length===0)return Js.warn({sourcePath:t},`Team definition requires name, valid pattern and non-empty agents, skipped`),null;let s=Number.parseInt(r.get(`maxhandoffdepth`)??``,10);return{name:i,pattern:a,agentNames:o,pipeline:Qe(r.get(`pipeline`)),supervisorId:r.get(`supervisor`),entryAgentId:r.get(`entry`),routerStrategy:r.get(`router`),rules:Xs(r.get(`rules`)),maxHandoffDepth:Number.isInteger(s)?s:void 0}}async function Qs(e,t){let{homedir:n}=await import(`node:os`),{join:r}=await import(`node:path`),i=t?.globalDir??r(n(),`.otto`,`teams`),a=r(e,`.otto`,`teams`),o=new Map;for(let e of[i,a])for(let t of await $s(e))o.set(t.name,t);let s=[...o.values()];return s.length>0&&Js.info(`Loaded %d declarative team(s): %s`,s.length,s.map(e=>e.name).join(`, `)),s}async function $s(e){let{readFile:t,readdir:n}=await import(`node:fs/promises`),{join:r}=await import(`node:path`),i;try{i=await n(e)}catch{return[]}let a=[];for(let n of i.filter(e=>e.endsWith(`.md`)).sort()){let i=r(e,n);try{let e=Zs(await t(i,`utf-8`),i);e&&a.push(e)}catch(e){Js.warn({sourcePath:i,err:e},`Failed to read team definition, skipped`)}}return a}var ec=class{reloadQueue=Promise.resolve();constructor(e,t,n,r,i,a,o,s,c,l){this.settings=e,this.mcp=t,this.skills=n,this.pluginModules=r,this.pluginProviders=i,this.tools=a,this.modelCatalog=o,this.workspaceDir=s,this.activePlugins=c,this.i18n=l}async reload(){let e=this.reloadQueue.then(()=>this.reloadSerial());return this.reloadQueue=e.catch(()=>void 0),e}async reloadSerial(){await this.settings.load(),Is(this.activePlugins(),this.settings,this.workspaceDir),await this.mcp.reload(),this.skills&&(this.skills.updatePluginDirs(this.activePlugins().filter(e=>e.manifest.contributes?.skills!==!1).filter(e=>!E(e).gated).map(e=>({id:e.id,dir:x(e.dir,`skills`)}))),await this.skills.discover());let e=Hs(this.activePlugins());this.i18n.register(e);let t=(await this.modelCatalog.refresh().catch(()=>[])).reduce((e,t)=>e+(t.added??0),0),n=await Ks(this.workspaceDir,{plugins:this.activePlugins()}),r=await Qs(this.workspaceDir),i=await this.pluginModules.reload(new Set(n.map(e=>e.name)));n.push(...i);let a=await this.pluginProviders.reload();return{mcpTools:this.tools.getAvailable(`full`).filter(e=>e.name.startsWith(`mcp__`)).length,models:t,agents:n.length,teamCount:r.length,agentProfiles:n,teamDeclarations:r,pendingProviderCapabilities:a.pendingCapabilityPluginIds,i18nEntries:e.length}}};const tc=C(`@x-otto/coding:panel-backend-controller`);var nc=class{stateListeners=new Map;statusListeners=new Map;inProcessHandlers=new Map;subscribedManager=null;constructor(e){this.deps=e}registerInProcessBackend(e,t){this.inProcessHandlers.set(e,t);let n=this.statusListeners.get(e);if(n)for(let e of n)e(`ready`)}unregisterInProcessBackend(e){this.inProcessHandlers.delete(e)}resolveServerForPlugin(e){if(this.inProcessHandlers.has(e))return{ok:!0};let t=this.deps.getActivePlugins().find(t=>t.id===e);if(!t)return{ok:!1,reason:`plugin "${e}" not found or not active`};if(!t.manifest.capabilities?.includes(`panel.backend`))return{ok:!1,reason:`plugin "${e}" does not declare capabilities:["panel.backend"]`};let n=E(t);if(n.pendingCapabilities.includes(`panel.backend`))return{ok:!1,reason:`plugin "${e}" capability "panel.backend" declared but not yet granted`};if(n.gated)return{ok:!1,reason:`plugin "${e}" is untrusted`};let r=this.deps.mcpController.listEffectiveServers(),i=Object.entries(r).filter(([,t])=>t.pluginId===e);return i.length===0?{ok:!1,reason:`plugin "${e}" has no associated MCP server`}:(i.length>1&&tc.warn({pluginId:e,serverNames:i.map(([e])=>e)},`plugin contributes multiple MCP servers; panel backend uses the first match (multi-server routing not yet supported)`),{ok:!0,serverName:i[0][0]})}async call(e,t,n,r){let i=this.inProcessHandlers.get(e);if(i)return i(t,n);let a=this.resolveServerForPlugin(e);if(!a.ok||!a.serverName)throw Error(a.reason??`cannot resolve backend server for plugin "${e}"`);let o=this.deps.mcpController.getMcpClient(a.serverName);if(!o)throw Error(`MCP server "${a.serverName}" for plugin "${e}" is not connected`);let s=r?.operationId?{...n,__operationId:r.operationId}:n;return o.callRaw(t,s,r?.signal)}async cancel(e,t){if(this.inProcessHandlers.has(e))return;let n=this.resolveServerForPlugin(e);if(!n.ok||!n.serverName)return;let r=this.deps.mcpController.getMcpClient(n.serverName);r&&await r.callRaw(`backend/cancel`,{id:t}).catch(()=>void 0)}subscribeState(e,t){return this.ensureNotificationSubscription(),this.stateListeners.has(e)||this.stateListeners.set(e,new Set),this.stateListeners.get(e).add(t),()=>{this.stateListeners.get(e)?.delete(t)}}onStatusChange(e,t){return this.ensureNotificationSubscription(),this.statusListeners.has(e)||this.statusListeners.set(e,new Set),this.statusListeners.get(e).add(t),()=>{this.statusListeners.get(e)?.delete(t)}}getStatus(e){if(this.inProcessHandlers.has(e))return`ready`;let t=this.resolveServerForPlugin(e);if(!t.ok||!t.serverName||this.deps.mcpController.listEffectiveServers()[t.serverName]?.disabled)return`disabled`;let n=this.deps.mcpController.getMcpClient(t.serverName);if(!n)return`crashed`;let r=n.getStatus();return r===`ready`?`ready`:r===`connecting`||r===`reconnecting`?`connecting`:`crashed`}notifyReload(){this.ensureNotificationSubscription();for(let[e,t]of this.statusListeners){if(t.size===0)continue;let n=this.getStatus(e);for(let e of t)e(n)}}ensureNotificationSubscription(){let e=this.deps.mcpController.manager;if(this.subscribedManager===e||(this.subscribedManager=e,!e))return;e.on(`server.notification`,({name:e,method:t,params:n})=>{if(t!==`backend/state`)return;let r=this.pluginIdForServer(e);if(!r)return;let i=this.stateListeners.get(r);if(!(!i||i.size===0))for(let e of i)e(n??{})});let t=e=>{let t=this.pluginIdForServer(e);if(!t)return;let n=this.statusListeners.get(t);if(!n||n.size===0)return;let r=this.getStatus(t);for(let e of n)e(r)};e.on(`server.connected`,({name:e})=>t(e)),e.on(`server.disconnected`,({name:e})=>t(e))}pluginIdForServer(e){return this.deps.mcpController.listEffectiveServers()[e]?.pluginId}};const rc=C(`@x-otto/coding:plugin-log-writer`);function ic(){return S(n,`plugin-logs`)}function ac(e){return Sn.test(e)?x(ic(),`${e}.jsonl`):(rc.warn({pluginId:e},`plugin id failed kebab-case validation, skipping log path resolution`),null)}function oc(e){let t;try{t=Zr(e).size}catch{return}if(!(t<=5242880))try{let t=k(e,`utf8`),n=Math.floor(t.length/2),r=t.indexOf(`
|
|
12
|
+
`}),a.onExit(r=>{clearTimeout(o);let{stdout:i,stderr:a,truncated:l}=As(s,c),u={success:r.code===0&&r.signal===null,hook:`setup`,command:t,exitCode:r.code,signal:r.signal??void 0,stdout:i,stderr:a,truncated:l||void 0};u.success?j.info({pluginId:e.pluginId},`Setup hook succeeded`):j.error({pluginId:e.pluginId,exitCode:r.code,signal:r.signal,stderr:a?.slice(0,512)},`Setup hook failed`),n?.(u)}),a.onError(r=>{j.error({pluginId:e.pluginId,err:r},`Setup hook spawn error`),n?.({success:!1,hook:`setup`,command:t,error:r.message})});return}let o=Oi(t,{cwd:e.pluginDir,env:Os(e),shell:!0,timeout:6e4,stdio:`pipe`}),s=``,c=``;o.stdout?.on(`data`,e=>{s+=e.toString(`utf-8`)}),o.stderr?.on(`data`,e=>{c+=e.toString(`utf-8`)}),o.on(`close`,(r,i)=>{let{stdout:a,stderr:o,truncated:l}=As(s,c),u={success:r===0&&i===null,hook:`setup`,command:t,exitCode:r,signal:i,stdout:a,stderr:o,truncated:l||void 0};u.success?j.info({pluginId:e.pluginId},`Setup hook succeeded`):j.error({pluginId:e.pluginId,exitCode:r,signal:i,stderr:o?.slice(0,512)},`Setup hook failed`),n?.(u)}),o.on(`error`,r=>{j.error({pluginId:e.pluginId,err:r},`Setup hook spawn error`),n?.({success:!1,hook:`setup`,command:t,error:r.message})})}const Ns=C(`@x-otto/coding:plugin-lifecycle`),Ps=`plugin_lifecycle`,Fs=new Set;async function Is(e,t,n){let r=t.get(Ps)?.setupDone??[],i=new Map(r.map(e=>[e.id,e.version])),a=new Set(e.map(e=>e.id));for(let e of i.keys())a.has(e)||i.delete(e);let o=!1;for(let r of e){let e=i.get(r.id),a=r.manifest.version,s=r.manifest.scripts?.setup;if(!s){(e===void 0||e!==a)&&(i.set(r.id,a),o=!0);continue}if(!(e!==void 0&&e===a)){if(E(r).gated){Ns.info({pluginId:r.id},`Setup hook deferred: plugin not yet trusted`);continue}Fs.has(r.id)||(Fs.add(r.id),Ms({pluginDir:r.dir,pluginId:r.id,workspaceDir:n},s,e=>{Fs.delete(r.id),i.set(r.id,a),Ls(t,i)},Vt))}}o&&await Ls(t,i)}async function Ls(e,t){let n=[...t].map(([e,t])=>({id:e,version:t}));await e.persist({[Ps]:{setupDone:n}})}function Rs(e,t){let n;try{n=Jr(t)}catch{return!1}let r;try{r=Jr(e)}catch{r=e}return r===n||r.startsWith(n+We)}const M=C(`@x-otto/coding:plugin-i18n-loader`),zs=/^([a-zA-Z0-9_-]+)\.json$/;function Bs(e){return Buffer.byteLength(e,`utf8`)<=En?e:`${Buffer.from(e,`utf8`).subarray(0,En).toString(`utf8`)}…`}function Vs(e,t,n){let r=new Map,i=S(t,n);if(!Rs(i,t))return M.warn({pluginId:e,i18nDir:n},`i18nDir resolves outside plugin dir, skipped`),r;let a;try{a=Kr(i)}catch{return r}let o=a.filter(e=>zs.test(e)).sort();o.length>Tn&&(M.warn({pluginId:e,i18nDir:n,declared:o.length,limit:Tn},`plugin i18nDir declares more locale files than the per-plugin limit, truncated`),o=o.slice(0,Tn));for(let n of o){let a=zs.exec(n)?.[1];if(!a)continue;let o=S(i,n);if(!Rs(o,t)){M.warn({pluginId:e,filename:n},`i18nDir locale file resolves outside plugin dir, skipped`);continue}let s;try{s=k(o,`utf8`)}catch(t){M.warn({pluginId:e,filename:n,err:String(t)},`i18nDir locale file read failed, skipped`);continue}if(Buffer.byteLength(s,`utf8`)>wn){M.warn({pluginId:e,filename:n,limit:wn},`i18nDir locale file exceeds byte limit, skipped`);continue}let c;try{c=JSON.parse(s)}catch(t){M.warn({pluginId:e,filename:n,err:String(t)},`i18nDir locale file is not valid JSON, skipped`);continue}if(typeof c!=`object`||!c||Array.isArray(c)){M.warn({pluginId:e,filename:n},`i18nDir locale file is not a flat object, skipped`);continue}for(let[e,t]of Object.entries(c)){if(typeof t!=`string`)continue;let n=r.get(e)??{};n[a]=t,r.set(e,n)}}return r}function Hs(e){let t=[];for(let n of e){if(E(n).gated)continue;let e=n.manifest.contributes?.i18nDir,r=n.manifest.contributes?.i18n;if(!e&&!r?.length)continue;let i=e?Vs(n.id,n.dir,e):new Map;if(r?.length)for(let e of r){let t=i.get(e.id)??{};for(let[r,i]of Object.entries(e.translations))r in t&&M.debug({pluginId:n.id,id:e.id,locale:r},`i18n inline entry overrides locale dir value`),t[r]=i;i.set(e.id,t)}let a=[...i.keys()];a.length>Cn&&(M.warn({pluginId:n.id,declared:a.length,limit:Cn},`plugin declares more i18n entries than the per-plugin limit, truncated`),a=a.slice(0,Cn));for(let e of a){let r=i.get(e);if(!r)continue;let a={};for(let[e,t]of Object.entries(r))a[e]=Bs(t);t.push({pluginId:n.id,id:e,translations:a})}}return t}const Us=C(`@x-otto/coding:declarative-agents`);function Ws(e){return{...e,defaultTools:e.defaultTools?.length?Or(e.defaultTools):e.defaultTools,disallowedTools:e.disallowedTools?.length?Or(e.disallowedTools):e.disallowedTools}}function Gs(e,t){let n=et(e);if(!n)return Us.warn({sourcePath:t},`Agent definition missing frontmatter, skipped`),null;let{fields:r,body:i}=n,a=r.get(`name`),o=r.get(`description`);if(!a||!o||!i)return Us.warn({sourcePath:t},`Agent definition requires name/description/body, skipped`),null;let s=Qe(r.get(`tools`)),c=Number.parseInt(r.get(`maxtoolturns`)??``,10),l=Number.parseInt(r.get(`maxtoolturnextensions`)??``,10),u=r.get(`prompt-mode`),d=Qe(r.get(`disallowed-tools`)),f=r.get(`allow-subagents`)===`true`?!0:r.get(`allow-subagents`)===`false`?!1:void 0;return{name:a,description:o,taskTypes:Qe(r.get(`tasktypes`))??[o],capabilities:Qe(r.get(`capabilities`))??[],systemPromptTemplate:i,promptMode:u===`append`||u===`replace`?u:void 0,defaultTools:s,disallowedTools:d?.length?d:void 0,preferredModelTier:r.get(`slot`)??r.get(`tier`),defaultMaxToolTurns:Number.isInteger(c)?c:void 0,defaultMaxToolTurnExtensions:Number.isInteger(l)?l:void 0,allowSubagents:f}}async function Ks(e,t){let{homedir:n}=await import(`node:os`),{join:r}=await import(`node:path`),i=t?.globalDir??r(n(),`.otto`,`agents`),a=r(e,`.otto`,`agents`),s=(t?.plugins??Vn({cwd:e,homedir:n()})).filter(e=>e.manifest.contributes?.agents!==!1).filter(e=>!E(e).gated).map(e=>({dir:r(e.dir,`agents`),claude:!1})),c=o(),l=c&&!br(e).gated,u=[...s,...c?[{dir:r(n(),`.claude`,`agents`),claude:!0}]:[],{dir:i,claude:!1},...l?[{dir:r(e,`.claude`,`agents`),claude:!0}]:[],{dir:a,claude:!1}],d=new Map;for(let{dir:e,claude:t}of u)for(let n of await qs(e))d.set(n.name,t?Ws(n):n);let f=[...d.values()];return f.length>0&&Us.info(`Loaded %d declarative agent(s): %s`,f.length,f.map(e=>e.name).join(`, `)),f}async function qs(e){let{readFile:t,readdir:n}=await import(`node:fs/promises`),{join:r}=await import(`node:path`),i;try{i=await n(e)}catch{return[]}let a=[];for(let n of i.filter(e=>e.endsWith(`.md`)).sort()){let i=r(e,n);try{let e=Gs(await t(i,`utf-8`),i);e&&a.push(e)}catch(e){Us.warn({sourcePath:i,err:e},`Failed to read agent definition, skipped`)}}return a}const Js=C(`@x-otto/coding:declarative-teams`),Ys=new Set([`handoff`,`sequential`,`parallel`,`hierarchical`,`router`]);function Xs(e){if(!e)return;let t=[];for(let n of e.split(`|`)){let[e,r]=n.split(/→|->/);if(e===void 0||r===void 0)continue;let i=e.split(`,`).map(e=>e.trim().toLowerCase()).filter(e=>e!==``),a=r.trim();i.length>0&&a!==``&&t.push({keywords:i,agentId:a})}return t.length>0?t:void 0}function Zs(e,t){let n=et(e);if(!n)return Js.warn({sourcePath:t},`Team definition missing frontmatter, skipped`),null;let{fields:r}=n,i=r.get(`name`),a=r.get(`pattern`),o=Qe(r.get(`agents`));if(!i||!a||!Ys.has(a)||!o||o.length===0)return Js.warn({sourcePath:t},`Team definition requires name, valid pattern and non-empty agents, skipped`),null;let s=Number.parseInt(r.get(`maxhandoffdepth`)??``,10);return{name:i,pattern:a,agentNames:o,pipeline:Qe(r.get(`pipeline`)),supervisorId:r.get(`supervisor`),entryAgentId:r.get(`entry`),routerStrategy:r.get(`router`),rules:Xs(r.get(`rules`)),maxHandoffDepth:Number.isInteger(s)?s:void 0}}async function Qs(e,t){let{homedir:n}=await import(`node:os`),{join:r}=await import(`node:path`),i=t?.globalDir??r(n(),`.otto`,`teams`),a=r(e,`.otto`,`teams`),o=new Map;for(let e of[i,a])for(let t of await $s(e))o.set(t.name,t);let s=[...o.values()];return s.length>0&&Js.info(`Loaded %d declarative team(s): %s`,s.length,s.map(e=>e.name).join(`, `)),s}async function $s(e){let{readFile:t,readdir:n}=await import(`node:fs/promises`),{join:r}=await import(`node:path`),i;try{i=await n(e)}catch{return[]}let a=[];for(let n of i.filter(e=>e.endsWith(`.md`)).sort()){let i=r(e,n);try{let e=Zs(await t(i,`utf-8`),i);e&&a.push(e)}catch(e){Js.warn({sourcePath:i,err:e},`Failed to read team definition, skipped`)}}return a}var ec=class{reloadQueue=Promise.resolve();constructor(e,t,n,r,i,a,o,s,c,l){this.settings=e,this.mcp=t,this.skills=n,this.pluginModules=r,this.pluginProviders=i,this.tools=a,this.modelCatalog=o,this.workspaceDir=s,this.activePlugins=c,this.i18n=l}async reload(){let e=this.reloadQueue.then(()=>this.reloadSerial());return this.reloadQueue=e.catch(()=>void 0),e}async reloadSerial(){await this.settings.load(),Is(this.activePlugins(),this.settings,this.workspaceDir),await this.mcp.reload(),this.skills&&(this.skills.updatePluginDirs(this.activePlugins().filter(e=>e.manifest.contributes?.skills!==!1).filter(e=>!E(e).gated).map(e=>({id:e.id,dir:x(e.dir,`skills`)}))),await this.skills.discover());let e=Hs(this.activePlugins());this.i18n.register(e);let t=(await this.modelCatalog.refresh().catch(()=>[])).reduce((e,t)=>e+(t.added??0),0),n=await Ks(this.workspaceDir,{plugins:this.activePlugins()}),r=await Qs(this.workspaceDir),i=[],a=[];try{a=await this.pluginModules.reload(new Set(n.map(e=>e.name)))}catch(e){i.push({path:`pluginModules`,error:e instanceof Error?e.message:String(e)})}n.push(...a);let o={pendingCapabilityPluginIds:[]};try{o=await this.pluginProviders.reload()}catch(e){i.push({path:`pluginProviders`,error:e instanceof Error?e.message:String(e)})}return{mcpTools:this.tools.getAvailable(`full`).filter(e=>e.name.startsWith(`mcp__`)).length,models:t,agents:n.length,teamCount:r.length,agentProfiles:n,teamDeclarations:r,pendingProviderCapabilities:o.pendingCapabilityPluginIds,i18nEntries:e.length,...i.length>0?{reloadFailures:i}:{}}}};const tc=C(`@x-otto/coding:panel-backend-controller`);var nc=class{stateListeners=new Map;statusListeners=new Map;inProcessHandlers=new Map;subscribedManager=null;constructor(e){this.deps=e}registerInProcessBackend(e,t){this.inProcessHandlers.set(e,t);let n=this.statusListeners.get(e);if(n)for(let e of n)e(`ready`)}unregisterInProcessBackend(e){this.inProcessHandlers.delete(e)}resolveServerForPlugin(e){if(this.inProcessHandlers.has(e))return{ok:!0};let t=this.deps.getActivePlugins().find(t=>t.id===e);if(!t)return{ok:!1,reason:`plugin "${e}" not found or not active`};if(!t.manifest.capabilities?.includes(`panel.backend`))return{ok:!1,reason:`plugin "${e}" does not declare capabilities:["panel.backend"]`};let n=E(t);if(n.pendingCapabilities.includes(`panel.backend`))return{ok:!1,reason:`plugin "${e}" capability "panel.backend" declared but not yet granted`};if(n.gated)return{ok:!1,reason:`plugin "${e}" is untrusted`};let r=this.deps.mcpController.listEffectiveServers(),i=Object.entries(r).filter(([,t])=>t.pluginId===e);return i.length===0?{ok:!1,reason:`plugin "${e}" has no associated MCP server`}:(i.length>1&&tc.warn({pluginId:e,serverNames:i.map(([e])=>e)},`plugin contributes multiple MCP servers; panel backend uses the first match (multi-server routing not yet supported)`),{ok:!0,serverName:i[0][0]})}async call(e,t,n,r){let i=this.inProcessHandlers.get(e);if(i)return i(t,n);let a=this.resolveServerForPlugin(e);if(!a.ok||!a.serverName)throw Error(a.reason??`cannot resolve backend server for plugin "${e}"`);let o=this.deps.mcpController.getMcpClient(a.serverName);if(!o)throw Error(`MCP server "${a.serverName}" for plugin "${e}" is not connected`);let s=r?.operationId?{...n,__operationId:r.operationId}:n;return o.callRaw(t,s,r?.signal)}async cancel(e,t){if(this.inProcessHandlers.has(e))return;let n=this.resolveServerForPlugin(e);if(!n.ok||!n.serverName)return;let r=this.deps.mcpController.getMcpClient(n.serverName);r&&await r.callRaw(`backend/cancel`,{id:t}).catch(()=>void 0)}subscribeState(e,t){return this.ensureNotificationSubscription(),this.stateListeners.has(e)||this.stateListeners.set(e,new Set),this.stateListeners.get(e).add(t),()=>{this.stateListeners.get(e)?.delete(t)}}onStatusChange(e,t){return this.ensureNotificationSubscription(),this.statusListeners.has(e)||this.statusListeners.set(e,new Set),this.statusListeners.get(e).add(t),()=>{this.statusListeners.get(e)?.delete(t)}}getStatus(e){if(this.inProcessHandlers.has(e))return`ready`;let t=this.resolveServerForPlugin(e);if(!t.ok||!t.serverName||this.deps.mcpController.listEffectiveServers()[t.serverName]?.disabled)return`disabled`;let n=this.deps.mcpController.getMcpClient(t.serverName);if(!n)return`crashed`;let r=n.getStatus();return r===`ready`?`ready`:r===`connecting`||r===`reconnecting`?`connecting`:`crashed`}notifyReload(){this.ensureNotificationSubscription();for(let[e,t]of this.statusListeners){if(t.size===0)continue;let n=this.getStatus(e);for(let e of t)e(n)}}ensureNotificationSubscription(){let e=this.deps.mcpController.manager;if(this.subscribedManager===e||(this.subscribedManager=e,!e))return;e.on(`server.notification`,({name:e,method:t,params:n})=>{if(t!==`backend/state`)return;let r=this.pluginIdForServer(e);if(!r)return;let i=this.stateListeners.get(r);if(!(!i||i.size===0))for(let e of i)e(n??{})});let t=e=>{let t=this.pluginIdForServer(e);if(!t)return;let n=this.statusListeners.get(t);if(!n||n.size===0)return;let r=this.getStatus(t);for(let e of n)e(r)};e.on(`server.connected`,({name:e})=>t(e)),e.on(`server.disconnected`,({name:e})=>t(e))}pluginIdForServer(e){return this.deps.mcpController.listEffectiveServers()[e]?.pluginId}};const rc=C(`@x-otto/coding:plugin-log-writer`);function ic(){return S(n,`plugin-logs`)}function ac(e){return Sn.test(e)?x(ic(),`${e}.jsonl`):(rc.warn({pluginId:e},`plugin id failed kebab-case validation, skipping log path resolution`),null)}function oc(e){let t;try{t=Zr(e).size}catch{return}if(!(t<=5242880))try{let t=k(e,`utf8`),n=Math.floor(t.length/2),r=t.indexOf(`
|
|
13
13
|
`,n);A(e,r>=0?t.slice(r+1):t.slice(n))}catch(t){rc.warn({path:e,err:String(t)},`plugin log truncation failed (fail-soft)`)}}function sc(e,t,n){if(!s())try{let r=ac(e);if(!r)return;let i=ic();D(i)||O(i,{recursive:!0}),oc(r),Br(r,`${JSON.stringify({ts:Date.now(),level:t,pluginId:e,msg:n})}\n`)}catch(t){rc.warn({pluginId:e,err:String(t)},`plugin log append failed (fail-soft)`)}}const cc=C(`@x-otto/coding:plugin-tool-wiring`);function N(e,t){return`plugin:${e}:${t}`}function lc(e){let t=e.split(`:`);return t.length<3||t[0]!==`plugin`?null:t[1]||null}function uc(e){let t=e?.content;return typeof t==`string`?t:Array.isArray(t)?t.map(e=>e&&typeof e==`object`&&`text`in e?String(e.text):``).join(``):``}const P={preToolUse:`tool.execute.before`,postToolUse:`tool.execute.after`,userPromptSubmit:`chat.message.before`,sessionStart:`session.created`,stop:`stream.end`,sessionRestored:`session.restored`,sessionDeleted:`session.deleted`,sessionIdle:`session.idle`,sessionError:`session.error`,streamStart:`stream.start`,compactionPending:`compaction.before`,compactionOccurred:`compaction.after`,taskCreated:`task.created`,taskStarted:`task.started`,taskCompleted:`task.completed`,taskFailed:`task.failed`};function dc(e,t){let n=[];if(t.preToolUse){let r=t.preToolUse;n.push(y({name:N(e,`preToolUse`),timing:P.preToolUse,handle:async(t,n)=>{let i=await r({toolName:t.toolName,input:t.args});i&&(i.decision===`deny`?(n.decision=`deny`,n.cancelled=!0,n.cancelReason=i.reason??`denied by plugin ${e}`):i.decision===`ask`&&(n.decision=`ask`,n.decisionReason=i.reason??`requires approval (plugin ${e})`))}}))}if(t.postToolUse){let r=t.postToolUse;n.push(y({name:N(e,`postToolUse`),timing:P.postToolUse,handle:async e=>{await r({toolName:e.toolName,input:e.args,result:e.result})}}))}if(t.userPromptSubmit){let r=t.userPromptSubmit;n.push(y({name:N(e,`userPromptSubmit`),timing:P.userPromptSubmit,handle:async e=>{await r({prompt:uc(e.message)})}}))}if(t.sessionStart){let r=t.sessionStart;n.push(y({name:N(e,`sessionStart`),timing:P.sessionStart,handle:async()=>{await r()}}))}if(t.stop){let r=t.stop;n.push(y({name:N(e,`stop`),timing:P.stop,handle:async()=>{await r()}}))}if(t.sessionRestored){let r=t.sessionRestored;n.push(y({name:N(e,`sessionRestored`),timing:P.sessionRestored,handle:async e=>{await r({sessionId:e.sessionId})}}))}if(t.sessionDeleted){let r=t.sessionDeleted;n.push(y({name:N(e,`sessionDeleted`),timing:P.sessionDeleted,handle:async e=>{await r({sessionId:e.sessionId})}}))}if(t.sessionIdle){let r=t.sessionIdle;n.push(y({name:N(e,`sessionIdle`),timing:P.sessionIdle,handle:async e=>{await r({sessionId:e.sessionId})}}))}if(t.sessionError){let r=t.sessionError;n.push(y({name:N(e,`sessionError`),timing:P.sessionError,handle:async e=>{await r({sessionId:e.sessionId,error:e.error})}}))}if(t.streamStart){let r=t.streamStart;n.push(y({name:N(e,`streamStart`),timing:P.streamStart,handle:async e=>{await r({sessionId:e.sessionId,model:e.model})}}))}if(t.compactionPending){let r=t.compactionPending;n.push(y({name:N(e,`compactionPending`),timing:P.compactionPending,handle:async e=>{await r({sessionId:e.sessionId,messageCount:e.messageCount})}}))}if(t.compactionOccurred){let r=t.compactionOccurred;n.push(y({name:N(e,`compactionOccurred`),timing:P.compactionOccurred,handle:async e=>{await r({sessionId:e.sessionId,retainedCount:e.retainedCount})}}))}if(t.taskCreated){let r=t.taskCreated;n.push(y({name:N(e,`taskCreated`),timing:P.taskCreated,handle:async e=>{await r({taskId:e.task.id})}}))}if(t.taskStarted){let r=t.taskStarted;n.push(y({name:N(e,`taskStarted`),timing:P.taskStarted,handle:async e=>{await r({taskId:e.task.id,agent:e.agent})}}))}if(t.taskCompleted){let r=t.taskCompleted;n.push(y({name:N(e,`taskCompleted`),timing:P.taskCompleted,handle:async e=>{await r({taskId:e.task.id,status:e.task.status,durationMs:e.result.durationMs,tokenUsage:e.result.tokenUsage})}}))}if(t.taskFailed){let r=t.taskFailed;n.push(y({name:N(e,`taskFailed`),timing:P.taskFailed,handle:async e=>{await r({taskId:e.task.id,error:e.error.message})}}))}return n}function fc(e,t,n,r){return r.map(r=>({name:r.name,description:r.description,argumentHint:r.argumentHint,allowedTools:r.allowedTools,model:r.model,body:r.body,source:`plugin`,scope:t===`bundled`?`project`:t,pluginId:e,filePath:`${n}#computed:${r.name}`}))}function pc(e){return e.map(e=>({name:e.name,description:e.description,taskTypes:e.taskTypes??[],capabilities:e.capabilities??[],systemPromptTemplate:e.systemPromptTemplate,...e.promptMode?{promptMode:e.promptMode}:{},...e.defaultTools?{defaultTools:e.defaultTools}:{},...e.disallowedTools?{disallowedTools:e.disallowedTools}:{},...e.preferredModelTier?{preferredModelTier:e.preferredModelTier}:{},...e.allowSubagents===void 0?{}:{allowSubagents:e.allowSubagents}}))}function mc(e,t,n){return n.map(n=>({definition:{metadata:{name:n.name,description:n.description??``},body:n.body,directory:t,filePath:`${t}#computed:${n.name}`,supportingFiles:[]},source:{type:`plugin`,root:t,id:e}}))}function hc(e,t){return t instanceof Ge?t.pluginSource===void 0?new t.constructor(t.message,{code:t.code,cause:t.cause,status:t.status,headers:t.headers,errorType:t.errorType,pluginSource:e}):t:new Ke(t instanceof Error?t.message:String(t),{code:`PROVIDER_PLUGIN_ERROR`,cause:t instanceof Error?t:void 0,pluginSource:e})}function gc(e,t){return()=>{let n=t();return{...n,async*converse(t,r,i,a){try{for await(let o of n.converse(t,r,i,a))o.type===`error`?yield{type:`error`,error:hc(e,o.error)}:yield o}catch(t){throw hc(e,t)}}}}}function _c(e,t){try{return t()}catch(t){let n=String(t);return cc.warn({pluginId:e,err:n},`plugin oauthProviderFactory threw, skipped`),sc(e,`warn`,`oauthProviderFactory threw, skipped: ${n}`),null}}function vc(e){return e&&typeof e==`object`&&Array.isArray(e.content)?e:{content:[{type:`text`,text:typeof e==`string`?e:JSON.stringify(e??null)}]}}function yc(e,t,n){let r=t;if(!r||typeof r!=`object`)return cc.warn({pluginId:e},`plugin tool entry is not an object, skipped`),null;if(typeof r.name!=`string`||!r.name)return cc.warn({pluginId:e},`plugin tool missing valid name, skipped`),null;if(typeof r.execute!=`function`)return cc.warn({pluginId:e,tool:r.name},`plugin tool missing execute function, skipped`),null;if(!r.parameters||typeof r.parameters.safeParse!=`function`)return cc.warn({pluginId:e,tool:r.name},`plugin tool missing valid parameters.safeParse, skipped`),null;let i=r.name,a=r.description??``,o=r.parameters,s=r.execute;return{name:i,description:a,parameters:o,async execute(t){try{let r={pluginId:e,workspaceDir:n?.workspaceDir??``,logger:n?.logger??{info:()=>{},warn:()=>{},error:()=>{}},host:n?.host,signal:t.signal,storage:n?.storage},i=vc(await s(t.params,r));return i.isError?{...i,pluginSource:e}:i}catch(t){throw t instanceof Error&&Object.assign(t,{pluginSource:e}),t}}}}function bc(e,t){let n=[],r=async(t,n)=>{try{await t.onEvent(n)}catch(n){cc.warn({pluginId:e,monitorId:t.id,err:String(n)},`plugin monitor onEvent threw, isolated`)}};for(let i of t)n.push(y({name:N(e,`monitor:${i.id}:stream.end`),timing:`stream.end`,handle:async e=>{e.tokenUsage&&await r(i,{type:`turn.completed`,sessionId:e.sessionId,tokens:{input:e.tokenUsage.input,output:e.tokenUsage.output}})}})),n.push(y({name:N(e,`monitor:${i.id}:compaction.after`),timing:`compaction.after`,handle:async e=>{await r(i,{type:`compaction.occurred`,sessionId:e.sessionId})}})),n.push(y({name:N(e,`monitor:${i.id}:session.error`),timing:`session.error`,handle:async e=>{await r(i,{type:`error`,sessionId:e.sessionId,message:e.error})}}));return n}function xc(e){return{...e}}var Sc=class{stats=new Map;clock;constructor(e=()=>Date.now()){this.clock=e}ensure(e){let t=this.stats.get(e);return t||(t={pluginId:e,hookTimeouts:0,toolTimeouts:0},this.stats.set(e,t)),t}recordHookTimeout(e,t){let n=this.ensure(e);n.hookTimeouts++,n.lastTimeoutHook=t}recordToolTimeout(e){let t=this.ensure(e);t.toolTimeouts++}recordError(e,t){let n=this.ensure(e);n.lastError={message:t,timestamp:this.clock()}}query(e){let t=this.stats.get(e);return t?xc(t):{pluginId:e,hookTimeouts:0,toolTimeouts:0}}all(){return[...this.stats.values()].map(xc)}clear(){this.stats.clear()}};function Cc(e){return new Sc(e)}const wc=3600*1e3;function Tc(){return{authorizedSessionIds:new Set,readCountThisEpoch:0,llmCountThisEpoch:0,llmCallTimes:[],notifyTimes:[]}}var Ec=class{states=new Map;constructor(e=()=>Date.now()){this.now=e}stateOf(e){let t=this.states.get(e);return t||(t=Tc(),this.states.set(e,t)),t}onNotifyDelivered(e,t){let n=this.stateOf(e);n.authorizedSessionIds.add(t),n.readCountThisEpoch=0,n.llmCountThisEpoch=0}isSessionAuthorized(e,t){return this.stateOf(e).authorizedSessionIds.has(t)}tryConsumeRead(e){let t=this.stateOf(e);return t.readCountThisEpoch>=1?!1:(t.readCountThisEpoch+=1,!0)}tryConsumeLlm(e){let t=this.stateOf(e);if(t.llmCountThisEpoch>=2)return{ok:!1,reason:`epoch`};let n=this.now()-wc;return t.llmCallTimes=t.llmCallTimes.filter(e=>e>n),t.llmCallTimes.length>=30?{ok:!1,reason:`hourly`}:(t.llmCountThisEpoch+=1,t.llmCallTimes.push(this.now()),{ok:!0})}tryConsumeNotify(e){let t=this.stateOf(e),n=this.now()-wc;return t.notifyTimes=t.notifyTimes.filter(e=>e>n),t.notifyTimes.length>=20?!1:(t.notifyTimes.push(this.now()),!0)}reset(e){this.states.delete(e)}};function Dc(e){return e.kind===`session`?0:1}var Oc=class{queue=[];inFlightId=null;maxPending;maxPerPlugin;ttlMs;now;constructor(e={}){this.maxPending=e.maxPending??8,this.maxPerPlugin=e.maxPerPlugin??1,this.ttlMs=e.ttlMs??3e5,this.now=e.now??Date.now}enqueue(e){if(this.sweepExpired(),this.queue.length>=this.maxPending)return{accepted:!1,reason:`queue-full`};if(e.origin.kind===`plugin`){let t=e.origin.pluginId;if(this.queue.filter(e=>e.request.origin.kind===`plugin`&&e.request.origin.pluginId===t).length>=this.maxPerPlugin)return{accepted:!1,reason:`plugin-concurrency`}}let t,n=new Promise(e=>{t=e}),r={...e,enqueuedAt:this.now()};return this.queue.push({request:r,resolve:t,dispatched:!1}),this.queue.sort((e,t)=>Dc(e.request.origin)-Dc(t.request.origin)||e.request.enqueuedAt-t.request.enqueuedAt),{accepted:!0,answer:n}}async waitForTurn(e,t=25){for(;;){if(this.takeNext()?.id===e)return!0;if(!this.queue.some(t=>t.request.id===e))return!1;await new Promise(e=>setTimeout(e,t))}}takeNext(){if(this.sweepExpired(),this.inFlightId!==null)return;let e=this.queue.find(e=>!e.dispatched);if(e)return e.dispatched=!0,this.inFlightId=e.request.id,e.request}settle(e,t){let n=this.queue.findIndex(t=>t.request.id===e);if(n===-1)return!1;let[r]=this.queue.splice(n,1);return this.inFlightId===e&&(this.inFlightId=null),r.resolve(t),!0}release(e){let t=this.queue.findIndex(t=>t.request.id===e);return t===-1?!1:(this.queue.splice(t,1),this.inFlightId===e&&(this.inFlightId=null),!0)}get hasInFlight(){return this.inFlightId!==null}get size(){return this.queue.length}sweepExpired(){let e=this.now()-this.ttlMs;for(let t=this.queue.length-1;t>=0;t--){let n=this.queue[t];n.dispatched||n.request.enqueuedAt>e||(this.queue.splice(t,1),n.resolve(kc(n.request.question)))}}shutdown(){let e=this.queue.splice(0,this.queue.length);this.inFlightId=null;for(let t of e)t.resolve(kc(t.request.question))}};function kc(e){return{answer:``,acceptedRecommendation:!1,resolvedBy:`human`}}const F={start:`service.start`,started:`service.started`,stop:`service.stop`,stopped:`service.stopped`,hostCall:`service.hostCall`,hostResult:`service.hostResult`,crashed:`service.crashed`,notify:`service.notify`};function Ac(){return`const { parentPort, workerData } = require('worker_threads')
|
|
14
14
|
const __send = (m) => parentPort.postMessage(m)
|
|
15
15
|
|
|
@@ -364,7 +364,7 @@ __onMessage(async (msg) => {
|
|
|
364
364
|
return
|
|
365
365
|
}
|
|
366
366
|
if (msg.type === '${z.stop}') { toolExecutors.clear(); pluginInstance = null; process.exit(0) }
|
|
367
|
-
})`}`}var wl=class{pending=new Map;idCounter=0;boundPluginId=``;hostCallDispatcher=null;setHostCallDispatcher(e){this.hostCallDispatcher=e}constructor(e){this.adapter=e,this.adapter.onMessage(e=>{if(e.type===z.loaded){let t=this.settlePending(`__load__`);t&&t.resolve(e.module);return}if(e.type===z.error){let t=this.settlePending(`__load__`);t&&t.reject(Error(e.error??this.adapter.loadFailedMessage?.()??`plugin isolated transport load failed`));return}if(e.type===z.toolResult){let t=this.settlePending(e.id);t&&t.resolve({result:e.result,error:e.error});return}if(e.type===z.sigilResult){let t=this.settlePending(e.id);t&&t.resolve({result:e.result,error:e.error});return}if(e.type===z.activated||e.type===z.deactivated){let t=this.settlePending(e.id);t&&t.resolve({error:e.error});return}if(e.type===z.hostCall){let t=this.boundPluginId,n=this.hostCallDispatcher,r=t=>{try{this.adapter.send({type:z.hostResult,id:e.id,...t})}catch{}};if(!n){r({error:`host call dispatcher not installed (plugin host capabilities unavailable)`});return}n(t,e.method??``,e.args??[]).then(e=>r({result:e})).catch(e=>r({error:e instanceof Error?e.message:String(e)}));return}}),this.adapter.onError(e=>{this.adapter.onErrorLog?.(e),this.rejectAllPending(e)}),this.adapter.onExit(e=>{if(this.pending.size===0)return;this.adapter.onExitLog?.(e);let t=this.adapter.exitErrorMessage?.(e)??`plugin isolated transport exited unexpectedly (code ${e})`;this.rejectAllPending(Error(t))})}rejectAllPending(e){for(let[,t]of this.pending)t.type===`load`?t.reject(e):t.resolve({error:e.message});this.pending.clear(),this.adapter.unref()}syncRefState(){this.pending.size>0?this.adapter.ref():this.adapter.unref()}trackPending(e,t){this.pending.set(e,t),this.syncRefState()}settlePending(e){let t=this.pending.get(e);return t&&(this.pending.delete(e),this.syncRefState()),t}async load(e,t,n){if(this.pending.has(`__load__`))throw Error(this.adapter.alreadyLoadingMessage?.(e)??`plugin isolated transport already loading ${e}`);return this.boundPluginId=e,new Promise((r,i)=>{this.trackPending(`__load__`,{type:`load`,resolve:r,reject:i}),this.adapter.send({type:z.load,pluginId:e,compiledPath:t,ctx:n,...n.hostMethods?{hostMethods:n.hostMethods}:{},...n.hostExternals?{hostExternals:n.hostExternals}:{}})})}async executeTool(e,t,n){let r=`tool-${++this.idCounter}`,i=n?.timeoutMs??6e4,a=n?.signal;return a?.aborted?{error:`plugin tool execution aborted`}:new Promise(n=>{let o,s,c=()=>{o!==void 0&&clearTimeout(o),s&&a&&a.removeEventListener(`abort`,s)};this.trackPending(r,{type:`tool`,resolve:e=>{c(),n(e)}});let l=e=>{let t=this.settlePending(r);if(t){try{this.adapter.send({type:z.toolCancel,id:r})}catch{}t.resolve({error:e})}};i>0&&(o=setTimeout(()=>{this.adapter.onToolTimeout?.(e,i),l(`plugin tool "${e}" timed out after ${i}ms`)},i),o.unref?.()),a&&(s=()=>l(`plugin tool execution aborted`),a.addEventListener(`abort`,s,{once:!0})),this.adapter.send({type:z.toolExecute,id:r,name:e,params:t})})}async resolveSigil(e,t,n,r){let i=`sigil-${++this.idCounter}`,a=r?.timeoutMs??6e4;return new Promise(r=>{let o;this.trackPending(i,{type:`sigil`,resolve:e=>{o!==void 0&&clearTimeout(o),r(e)}}),a>0&&(o=setTimeout(()=>{let t=this.settlePending(i);t&&t.resolve({error:`sigil resolver "${e}" timed out after ${a}ms`})},a),o.unref?.()),this.adapter.send({type:z.sigilResolve,id:i,name:e,param:t,ctx:n})})}async activate(){let e=`lifecycle-${++this.idCounter}`;return new Promise(t=>{this.trackPending(e,{type:`lifecycle`,resolve:t}),this.adapter.send({type:z.onActivate,id:e})})}async deactivate(){let e=`lifecycle-${++this.idCounter}`;return new Promise(t=>{this.trackPending(e,{type:`lifecycle`,resolve:t}),this.adapter.send({type:z.onDeactivate,id:e})})}clearPending(){this.pending.clear()}};const Tl=C(`@x-otto/coding:plugin-worker-pool`);let El=null,Dl=null;function Ol(){return Dl||(El||=Wr(x(Be(),`otto-plugin-worker-`)),Dl=x(El,`worker-entry.cjs`),A(Dl,Cl(`worker`)),Dl)}var kl=class extends wl{worker;constructor(){let e=new Pi(Ol());e.unref(),super({send:t=>e.postMessage(t),onMessage:t=>e.on(`message`,e=>t(e)),onError:t=>e.on(`error`,e=>t(e)),onExit:t=>e.on(`exit`,t),ref:()=>e.ref(),unref:()=>e.unref(),onToolTimeout:(e,t)=>{Tl.warn({tool:e,timeoutMs:t},`plugin tool execution timed out`)},onErrorLog:e=>{Tl.warn({err:String(e)},`plugin worker error`)},onExitLog:e=>{Tl.warn({code:e},`plugin worker exited unexpectedly with pending requests`)},exitErrorMessage:e=>`plugin worker exited unexpectedly (code ${e})`,loadFailedMessage:()=>`plugin worker load failed`,alreadyLoadingMessage:e=>`plugin worker already loading ${e}`}),this.worker=e}async stop(){try{this.worker.postMessage({type:z.stop}),await this.worker.terminate()}catch{}this.clearPending(),this.worker.unref()}},Al=class{workers=new Map;maxConcurrent;hostCallDispatcher=null;constructor(e=8){this.maxConcurrent=e}setHostCallDispatcher(e){this.hostCallDispatcher=e}async load(e,t,n){if(this.workers.size>=this.maxConcurrent)return null;await this.unload(e);let r=new kl;this.hostCallDispatcher&&r.setHostCallDispatcher(this.hostCallDispatcher),this.workers.set(e,r);try{return await r.load(e,t,n)}catch(t){throw this.workers.delete(e),r.stop().catch(()=>{}),t}}async executeTool(e,t,n,r){let i=this.workers.get(e);if(!i)throw Error(`no worker for plugin ${e}`);return i.executeTool(t,n,r)}async resolveSigil(e,t,n,r,i){let a=this.workers.get(e);if(!a)throw Error(`no worker for plugin ${e}`);return a.resolveSigil(t,n,r,i)}async activate(e){let t=this.workers.get(e);if(!t)throw Error(`no worker for plugin ${e}`);return t.activate()}async deactivate(e){let t=this.workers.get(e);if(!t)throw Error(`no worker for plugin ${e}`);return t.deactivate()}async unload(e){let t=this.workers.get(e);t&&(this.workers.delete(e),await t.stop())}async dispose(){let e=[...this.workers.values()];if(this.workers.clear(),El){try{Xr(El,{recursive:!0,force:!0})}catch{}El=null,Dl=null}await Promise.all(e.map(e=>e.stop().catch(()=>{})))}get size(){return this.workers.size}};const jl=C(`@x-otto/coding:plugin-process-pool`);let Ml=null,Nl=null;function Pl(){return Nl||(Ml||=Wr(x(Be(),`otto-plugin-process-`)),Nl=x(Ml,`process-entry.cjs`),A(Nl,Cl(`process`)),Nl)}var Fl=class extends wl{child;sandboxToDispose;constructor(e){let t=Pl(),n=process.execPath,r=[t],i=n,a=r,o;if(Re()){let t=Fe({network:`deny`}),s=t.wrap({command:n,args:r,options:{timeout:0,cwd:e},projectRoot:e});i=s.command,a=s.args,o=t}else jl.warn(`No platform sandbox available for project/repository scope plugin isolation — falling back to plain child_process (still process-isolated, but without OS-level file/network constraints)`);let s=Oi(i,a,{cwd:e,stdio:[`ignore`,`ignore`,`pipe`,`ipc`]});s.unref(),super({send:e=>s.send(e),onMessage:e=>s.on(`message`,t=>e(t)),onError:e=>s.on(`error`,t=>e(t)),onExit:e=>s.on(`exit`,e),ref:()=>{s.channel?.ref(),s.stderr?.ref?.()},unref:()=>{s.channel?.unref(),s.stderr?.unref?.()},onToolTimeout:(e,t)=>{jl.warn({tool:e,timeoutMs:t},`plugin tool execution timed out (isolated process)`)},onErrorLog:e=>{jl.warn({err:String(e)},`plugin process error`)},onExitLog:e=>{jl.warn({code:e},`plugin process exited unexpectedly with pending requests`)},exitErrorMessage:e=>`plugin process exited unexpectedly (code ${e})`,loadFailedMessage:()=>`plugin process load failed`,alreadyLoadingMessage:e=>`plugin process already loading ${e}`}),this.child=s,this.sandboxToDispose=o,this.child.stderr?.on(`data`,e=>{jl.warn({stderr:e.toString().slice(0,500)},`plugin process stderr output`)}),this.child.on(`exit`,()=>{this.sandboxToDispose?.dispose().catch(()=>void 0),this.sandboxToDispose=void 0})}async stop(){try{this.child.send({type:z.stop})}catch{}try{this.child.kill()}catch{}this.clearPending()}},Il=class{processes=new Map;maxConcurrent;hostCallDispatcher=null;constructor(e=4){this.maxConcurrent=e}setHostCallDispatcher(e){this.hostCallDispatcher=e}async load(e,t,n){if(this.processes.size>=this.maxConcurrent)return null;await this.unload(e);let r=new Fl(n.workspaceDir);this.hostCallDispatcher&&r.setHostCallDispatcher(this.hostCallDispatcher),this.processes.set(e,r);try{return await r.load(e,t,n)}catch(t){throw this.processes.delete(e),r.stop().catch(()=>{}),t}}async executeTool(e,t,n,r){let i=this.processes.get(e);if(!i)throw Error(`no process for plugin ${e}`);return i.executeTool(t,n,r)}async resolveSigil(e,t,n,r,i){let a=this.processes.get(e);if(!a)throw Error(`no process for plugin ${e}`);return a.resolveSigil(t,n,r,i)}async activate(e){let t=this.processes.get(e);if(!t)throw Error(`no process for plugin ${e}`);return t.activate()}async deactivate(e){let t=this.processes.get(e);if(!t)throw Error(`no process for plugin ${e}`);return t.deactivate()}async unload(e){let t=this.processes.get(e);t&&(this.processes.delete(e),await t.stop())}async dispose(){let e=[...this.processes.values()];if(this.processes.clear(),Ml){try{Xr(Ml,{recursive:!0,force:!0})}catch{}Ml=null,Nl=null}await Promise.all(e.map(e=>e.stop().catch(()=>{})))}get size(){return this.processes.size}};const Ll=C(`@x-otto/coding:plugin-module-loader-isolated`);let Rl=null;function zl(){return Rl||=new Al,Rl}let Bl=null;function Vl(){return Bl||=new Il,Bl}async function Hl(){await Promise.all([Rl?.dispose()??Promise.resolve(),Bl?.dispose()??Promise.resolve()])}function Ul(e){return e===`project`||e===`repository`?Vl():zl()}function Wl(e){return!!e.manifest.capabilities?.includes(`tools`)}function Gl(e,t,n){let r={};if(t.contributions&&(r.contributions=t.contributions),t.tools.length>0&&(r.tools=t.tools.map(t=>({name:t.name,description:t.description||t.name,parameters:{safeParse(e){return t.hasParameters?{success:!0,data:e}:{success:!0,data:{}}},...t.parametersSchema===void 0?{}:{toJSONSchema:()=>t.parametersSchema}},async execute(r,i){let{result:a,error:o}=await n.executeTool(e,t.name,r,{signal:i?.signal});if(o)throw Error(o);return a&&typeof a==`object`&&Array.isArray(a.content)?a:{content:[{type:`text`,text:typeof a==`string`?a:JSON.stringify(a??null)}]}}}))),t.hasSigilProviders&&Ll.warn({pluginId:e},`plugin declares sigilProviders but is loaded via the isolated path (tools capability) — dynamic @ search providers are not proxied over RPC and will be inactive; declare input.resolver without tools to use the in-process path, or use static sigilEntries`),t.sigilResolvers?.length>0){r.sigilResolvers={};for(let i of t.sigilResolvers)r.sigilResolvers[i.name]={resolve:(t,r)=>n.resolveSigil(e,i.name,t,r,{timeoutMs:i.timeoutMs}).then(e=>{if(e.error)throw Error(e.error);return e.result??``}),timeoutMs:i.timeoutMs,uiHostOnly:i.uiHostOnly}}return t.hasOnActivate&&(r.onActivate=async()=>{let{error:t}=await n.activate(e);if(t)throw Error(t)}),t.hasOnDeactivate&&(r.onDeactivate=async()=>{let{error:t}=await n.deactivate(e);if(t)throw Error(t)}),r}async function Kl(e,t,n,r){if((e.scope===`project`||e.scope===`repository`)&&!Zn(e.dir))return Ll.warn({pluginId:e.id},`project/repository plugin not trusted, skipping isolated code module (fail-closed)`),null;let i=E(e);if(i.pendingCapabilities.length>0)return Ll.warn({pluginId:e.id,pendingCapabilities:i.pendingCapabilities},`plugin declares high-risk capabilities not yet granted, skipping isolated code module before worker execution (fail-closed, RFC-140 D3)`),null;let a=n??Ul(e.scope),o=ol(e.dir);try{o?Ll.info({pluginId:e.id,compiledPath:o},`using prebuilt plugin module (isolated path, RFC-150 D5)`):o=await Qc(e.dir)}catch(t){let n=String(t);return Ll.warn({pluginId:e.id,err:n},`plugin.ts compile failed (isolated path)`),r?.(e.id,`compile failed: ${n}`),null}if(!o)return null;let s=[...Object.keys(t.host??{}),`listActivePlugins`];if(t.host&&Object.keys(t.host).length>0||t.listActivePlugins){let e=t.host;a.setHostCallDispatcher?.(async(n,r,i)=>{if(r===`listActivePlugins`)return t.listActivePlugins?t.listActivePlugins():[];if(!e||typeof e[r]!=`function`)throw Error(`host method '${r}' not available (not declared or not granted)`);if(!(r in e))throw Error(`host method '${r}' not in whitelist`);let a=e[r];return a(...i)})}try{let n=await a.load(e.id,o,{pluginId:t.pluginId,pluginDir:t.pluginDir,workspaceDir:t.workspaceDir,hostMethods:s,listActivePlugins:!0,hostExternals:Yc()});if(n===null){if(e.scope===`project`||e.scope===`repository`){let t=`plugin process pool exhausted (project/repository scope requires isolated execution, refusing to downgrade to in-process)`;return Ll.warn({pluginId:e.id},t),r?.(e.id,t),null}return Ll.info({pluginId:e.id},`plugin worker pool exhausted, falling back to in-process load`),sl(e,t,r)}return{pluginId:e.id,module:Gl(e.id,n,a),compiledPath:o}}catch(t){let n=String(t);return Ll.warn({pluginId:e.id,err:n},`plugin.ts worker load failed`),r?.(e.id,`worker load failed: ${n}`),null}}function ql(e,t){return e.includes(`onStartup`)?!0:e.some(e=>t.has(e))}var Jl=class{axisName=`hooks`;hookNamesByPlugin=new Map;constructor(e){this.hookRegistry=e}register(e){let t=e.loaded.module.hooks;if(t){let n=dc(e.plugin.id,t);this.hookRegistry.registerAll(n);let r=this.hookNamesByPlugin.get(e.plugin.id)??[];r.push(...n.map(e=>e.name)),this.hookNamesByPlugin.set(e.plugin.id,r)}}unregister(e){let t=this.hookNamesByPlugin.get(e);if(t){for(let e of t)this.hookRegistry.unregister(e);this.hookNamesByPlugin.delete(e)}}unregisterAll(){for(let e of[...this.hookNamesByPlugin.keys()])this.unregister(e)}},Yl=class{axisName=`monitors`;hookNamesByPlugin=new Map;monitorsByPlugin=new Map;constructor(e,t){this.hookRegistry=e,this.logger=t}register(e){let t=e.loaded.module.monitors;if(!t?.length)return;if(!e.plugin.manifest.capabilities?.includes(`monitor`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares monitors but not capabilities:["monitor"], skipped (fail-closed)`);return}let n=bc(e.plugin.id,t);this.hookRegistry.registerAll(n);let r=this.hookNamesByPlugin.get(e.plugin.id)??[];r.push(...n.map(e=>e.name)),this.hookNamesByPlugin.set(e.plugin.id,r),this.monitorsByPlugin.set(e.plugin.id,t)}unregister(e){let t=this.hookNamesByPlugin.get(e);if(t){for(let e of t)this.hookRegistry.unregister(e);this.hookNamesByPlugin.delete(e)}this.monitorsByPlugin.delete(e)}unregisterAll(){for(let e of[...this.hookNamesByPlugin.keys()])this.unregister(e)}async dispatch(e){for(let[t,n]of this.monitorsByPlugin)for(let r of n)try{await r.onEvent(e)}catch(n){this.logger.warn({pluginId:t,monitorId:r.id,eventType:e.type,err:String(n)},`plugin monitor onEvent threw (host event), isolated`)}}get monitorPluginIds(){return[...this.monitorsByPlugin.keys()]}},Xl=class{axisName=`feedback`;feedbackRegisteredSources=new Set;constructor(e,t){this.feedbackRegistry=e,this.logger=t}register(e){let t=e.loaded.module.feedbackProviders;if(!(!t||!this.feedbackRegistry)){if(!e.plugin.manifest.capabilities?.includes(`feedback`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares feedbackProviders but not capabilities:["feedback"], skipped (fail-closed)`);return}this.feedbackRegistry.register(t,e.plugin.id)?this.feedbackRegisteredSources.add(e.plugin.id):this.logger.warn({pluginId:e.plugin.id},`plugin feedbackProviders rejected (already registered by a different plugin)`)}}unregister(e){!this.feedbackRegistry||!this.feedbackRegisteredSources.has(e)||(this.feedbackRegistry.unregister(e),this.feedbackRegisteredSources.delete(e))}unregisterAll(){for(let e of[...this.feedbackRegisteredSources])this.unregister(e)}};const Zl=C(`@x-otto/coding:plugin-sigil-loader`);function Ql(e){return e.startsWith(`!`)||e.startsWith(`#`)}function $l(e){let t=[];for(let n of e){let e=n.manifest.contributes?.sigilEntries;if(e?.length){if(E(n).gated){Zl.warn({pluginId:n.id},`plugin gated (untrusted), sigilEntries skipped`);continue}for(let r of e){if(Ql(r.value)){Zl.warn({pluginId:n.id,label:r.label},`sigilEntries value starts with '!' or '#' (mode-prefix collision), skipped`);continue}t.push({label:r.label,value:r.value,kind:r.kind,description:r.description,source:n.id,resolverId:r.resolverId?`${n.id}:${r.resolverId}`:void 0})}}}return t}function eu(e){for(let t of e)t.manifest.contributes?.inputEntries&&Zl.warn({pluginId:t.id},`contributes.inputEntries is deprecated (RFC-210); migrate to contributes.sigilEntries (inline array) — the file-path form is no longer loaded`)}function tu(e,t){let n=[];for(let[r,i]of Object.entries(t)){let t=`${e}:${r}`;typeof i==`function`?n.push({id:t,resolve:i}):i&&typeof i.resolve==`function`?n.push({id:t,resolve:i.resolve,timeoutMs:i.timeoutMs,uiHostOnly:i.uiHostOnly}):Zl.warn({pluginId:e,name:r},`sigilResolvers entry is neither function nor {resolve}, skipped`)}return n}function nu(e,t){return t.map(t=>async(n,r)=>(await t(n,r)).filter(e=>!Ql(e.value)).map(t=>({...t,source:e})))}function ru(e,t){for(let n of e)n.resolverId&&!t(n.resolverId)&&Zl.warn({label:n.label,resolverId:n.resolverId,source:n.source},`sigilEntries.resolverId has no matching resolver (declared sigilResolvers missing or capability not granted) — entry will pass through unexpanded at submit`)}var iu=class{axisName=`sigil`;sigilResolverSourcePluginIds=new Set;sigilProviderUnsubsByPlugin=new Map;constructor(e,t,n){this.sigilResolverRegistry=e,this.pluginInput=t,this.logger=n}register(e){let t=e.loaded.module.sigilResolvers,n=e.loaded.module.sigilProviders;if(t&&Object.keys(t).length>0||n?.length){if(!e.plugin.manifest.capabilities?.includes(`input.resolver`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares sigilResolvers/sigilProviders but not capabilities:["input.resolver"], skipped (fail-closed)`);return}if(e.verdict.pendingCapabilities.includes(`input.resolver`)){this.logger.warn({pluginId:e.plugin.id},`plugin capability "input.resolver" declared but not yet granted, skipping sigil axes (fail-closed)`);return}if(t&&this.sigilResolverRegistry){let n=tu(e.plugin.id,t);n.length>0&&(this.sigilResolverRegistry.register(n,e.plugin.id),this.sigilResolverSourcePluginIds.add(e.plugin.id))}if(n?.length&&this.pluginInput){let t=this.sigilProviderUnsubsByPlugin.get(e.plugin.id)??[];for(let r of nu(e.plugin.id,n))t.push(this.pluginInput.registerProvider(`@`,r));this.sigilProviderUnsubsByPlugin.set(e.plugin.id,t)}if(this.sigilResolverRegistry){let t=this.sigilResolverRegistry;ru($l([e.plugin]),e=>t.get(e)!==void 0)}}}unregister(e){this.sigilResolverRegistry&&this.sigilResolverSourcePluginIds.has(e)&&(this.sigilResolverRegistry.unregisterBySource(e),this.sigilResolverSourcePluginIds.delete(e));let t=this.sigilProviderUnsubsByPlugin.get(e);if(t){for(let e of t)try{e()}catch{}this.sigilProviderUnsubsByPlugin.delete(e)}}unregisterAll(){let e=new Set([...this.sigilResolverSourcePluginIds,...this.sigilProviderUnsubsByPlugin.keys()]);for(let t of e)this.unregister(t)}},au=class{axisName=`computedCommands`;commandsByPlugin=new Map;register(e){let t=e.loaded.module.contributions?.commands;if(t?.length&&e.plugin.scope!==`builtin`){let n=this.commandsByPlugin.get(e.plugin.id)??[];n.push(...fc(e.plugin.id,e.plugin.scope,e.plugin.dir,t)),this.commandsByPlugin.set(e.plugin.id,n)}}unregister(e){this.commandsByPlugin.delete(e)}unregisterAll(){}resetForReload(){this.commandsByPlugin.clear()}getComputedCommands(){return[...this.commandsByPlugin.values()].flat()}},ou=class{axisName=`computedAgents`;profilesByPlugin=new Map;existingAgentNames=new Set;register(e){let t=e.loaded.module.contributions?.agents;if(!t?.length)return;let n=this.profilesByPlugin.get(e.plugin.id)??[];n.push(...pc(t)),this.profilesByPlugin.set(e.plugin.id,n)}unregister(e){this.profilesByPlugin.delete(e)}unregisterAll(){}setExistingAgentNames(e){this.existingAgentNames=e}resetForReload(e){this.profilesByPlugin.clear(),this.existingAgentNames=e}getAppendedAgents(){let e=new Set(this.existingAgentNames),t=[];for(let n of this.profilesByPlugin.values())for(let r of n)e.has(r.name)||(e.add(r.name),t.push(r));return t}},su=class{axisName=`computedSkills`;skillNamesByPlugin=new Map;constructor(e){this.skillRegistry=e}register(e){let t=e.loaded.module.contributions?.skills;if(!t?.length||!this.skillRegistry)return;let n=this.skillNamesByPlugin.get(e.plugin.id)??[];for(let{definition:r,source:i}of mc(e.plugin.id,e.plugin.dir,t))this.skillRegistry.get(r.metadata.name)||(this.skillRegistry.register(r,i),n.push(r.metadata.name));n.length>0&&this.skillNamesByPlugin.set(e.plugin.id,n)}unregister(e){let t=this.skillNamesByPlugin.get(e);if(t){for(let e of t)this.skillRegistry?.unregister(e);this.skillNamesByPlugin.delete(e)}}unregisterAll(){for(let e of[...this.skillNamesByPlugin.keys()])this.unregister(e)}};const B=C(`@x-otto/coding:plugin-provider-loader`);function cu(e){let t=C(`wire-protocol:${e}`),n=e=>(t,...n)=>e(t,...n);return{debug:n(t.debug.bind(t)),info:n(t.info.bind(t)),warn:n(t.warn.bind(t)),error:n(t.error.bind(t))}}function V(e,t){return`${e}:${t}`}function lu(e){return new Set([...(e.contributes?.providers??[]).filter(e=>e.preserveProviderId===!0&&e.oauthRef).map(e=>e.oauthRef),...e.codeProviderIds??[]])}function uu(e,t){let n=lu(t);return new Set((t.contributes?.oauth??[]).map(t=>n.has(t.id)?t.id:V(e,t.id)))}function du(e,t){return new Set((t.contributes?.providers??[]).filter(e=>e.catalogOnly!==!0&&e.baseUrl&&e.wireApi).map(t=>t.preserveProviderId===!0?t.id:V(e,t.id)))}function fu(e,t,n){return new Set([...n.codeProviderIds??[],...(n.contributes?.providers??[]).filter(e=>e.preserveProviderId===!0).map(e=>e.id)]).has(t)?t:V(e,t)}function pu(e){return`code:${e}`}function mu(e,t,n,r,i,a,o){let s=e.id.indexOf(`/`),c=s>=0?e.id.slice(s+1):e.id;return{id:e.id,name:c,api:n,provider:t,baseUrl:r,reasoning:e.reasoning??!1,input:e.input??[`text`],cost:e.cost,contextWindow:e.contextWindow,maxOutputTokens:e.maxOutput,imageConstraints:i,supportsTools:a,strengths:e.strengths,thinkingLevels:e.thinkingLevels,thinkingMode:e.thinkingMode,responseBodyPolicy:o}}function hu(e,t,n,r,i){return(a,o)=>{let s=e.url.replace(`{baseUrl}`,r??``).replace(`{clientVersion}`,process.env.OTTO_CODEX_CLIENT_VERSION||`1.0.0`),c=e.authScheme??`bearer`,l=c===`x-api-key`||c===`auto`&&o.mode!==`oauth`?{"x-api-key":a}:{authorization:`Bearer ${a}`};return c===`auto`&&o.mode===`oauth`&&o.beta&&e.betaHeaderName&&(l[e.betaHeaderName]=o.beta),{url:s,headers:{...i,...e.headers,...l},mergeProvider:t,modelApi:n,modelIdExclude:e.modelIdExclude}}}function gu(e,t,n,r,i,a){return()=>{let o=r.get(a);if(!o)throw new Ke(`wire protocol '${a}' is not registered — is its provider plugin installed and trusted? (RFC-148)`,{code:`WIRE_PROTOCOL_NOT_REGISTERED`});return o.create({resolveAuth:()=>t.resolveAuth(n).then(e=>e??void 0),resolveBaseUrl:async()=>i,headers:e.headers,tokenDerivedHeaders:e.tokenDerivedHeaders,allowAuthHeaderOverride:e.allowAuthHeaderOverride,logger:cu(a)})}}function _u(e,t,n,r,i,a,o){let s=t.contributes?.oauth;if(s?.length&&n)if(t.capabilities?.includes(`provider`))for(let t of s){let s=r.has(t.id)?t.id:V(e,t.id);if(f.includes(t.id)||n.isReservedId(t.id)){a.rejected.push({id:t.id,reason:`oauth id collides with builtin reserved OAuth provider`}),B.warn({pluginId:e,oauthId:t.id},`plugin oauth id collides with builtin reserved, rejected (R3)`);continue}let c=t.name??i.get(t.id)??t.id,l=t.kind===`pkce`?Ri({...t,id:s,name:c,tokenExchangeEncoding:t.tokenExchangeEncoding??`form`,assumesLoopbackAlways:t.assumesLoopbackAlways??!1,subscriptionScoped:t.subscriptionScoped??!1}):Li({...t,id:s,name:c,allowCustomDomain:t.allowCustomDomain??!1});if(o?.has(s))n.replace(l,e);else if(!n.register(l,e)){a.rejected.push({id:t.id,reason:`oauth registration rejected (id already claimed by another plugin or reserved)`});continue}}else{B.warn({pluginId:e},`plugin declares contributes.oauth but not capabilities:["provider"], skipped (fail-closed)`);for(let e of s)a.rejected.push({id:e.id,reason:`capability "provider" not declared`})}}function vu(e,t,n,r,i,a){let o=t.contributes?.providers;if(!o?.length)return;if(!t.capabilities?.includes(`provider`)){B.warn({pluginId:e},`plugin declares contributes.providers but not capabilities:["provider"], skipped (fail-closed)`);for(let e of o)i.rejected.push({id:e.id,reason:`capability "provider" not declared`});return}let s=new Set;for(let t of o){if(i.registered.includes(t.id)){i.rejected.push({id:t.id,reason:`duplicate provider id in manifest`}),B.warn({pluginId:e,providerId:t.id},`duplicate provider id in manifest, second entry rejected (review F5)`);continue}if(ae(t.id)){i.rejected.push({id:t.id,reason:`reserved builtin provider id`}),B.warn({pluginId:e,providerId:t.id},`plugin provider id collides with builtin, rejected (R3)`);continue}let o=t.preserveProviderId===!0,c=o?t.id:V(e,t.id),l=o?t.id:V(e,t.id);if(t.catalogOnly===!0){let a=l;if(t.oauthRef){let n=o?t.oauthRef:V(e,t.oauthRef);if(!r?.get(n)){i.rejected.push({id:t.id,reason:`oauthRef '${t.oauthRef}' not found in current plugin's oauth table (R7)`}),B.warn({pluginId:e,providerId:t.id,oauthRef:t.oauthRef},`catalog provider oauthRef not found, rejected (R7)`);continue}a=n}if(t.envKey&&!n.authStore.registerEnvKey(l,t.envKey,e)){i.rejected.push({id:t.id,reason:`envKey registration rejected (reserved or claimed)`});continue}if(!le({id:l,name:t.name,env:t.oauthRef?void 0:t.envKey,requiresIntranet:t.requiresIntranet===!0},e)){i.rejected.push({id:t.id,reason:`provider descriptor id already claimed`}),t.envKey&&n.authStore.unregisterEnvKey(l);continue}if(t.models?.length){let r=t.models.map(e=>mu(e,a,c,t.baseUrl??``,void 0,t.supportsTools,t.responseBodyPolicy)),i=n.modelRegistry.registerWithSource(r,e);for(let t of i)B.warn({pluginId:e,modelId:t},`plugin model id collides, rejected`)}i.registered.push(t.id);continue}let u=l;if(t.oauthRef){let n=o?t.oauthRef:V(e,t.oauthRef);if(!r?.get(n)){i.rejected.push({id:t.id,reason:`oauthRef '${t.oauthRef}' not found in current plugin's oauth table (R7: cross-plugin/invalid ref rejected)`}),B.warn({pluginId:e,providerId:t.id,oauthRef:t.oauthRef},`provider oauthRef not found in current plugin oauth table, rejected (R7)`);continue}u=n,t.envKey&&B.warn({pluginId:e,providerId:t.id},`provider declares both oauthRef and envKey; ignoring envKey (R2, oauth takes priority)`)}if(t.envKey&&!t.oauthRef&&!n.authStore.registerEnvKey(l,t.envKey,e)){i.rejected.push({id:t.id,reason:`envKey registration rejected (reserved or claimed by another plugin)`});continue}let d=t.baseUrl,f=t.wireApi;if(!d||!f){i.rejected.push({id:t.id,reason:`baseUrl and wireApi required for non-catalog providers`});continue}let p=t.modelsEndpoint?hu(t.modelsEndpoint,l,c,t.baseUrl,t.headers):void 0,m=()=>{t.oauthRef&&r&&!s.has(u)&&r.unregister(u)};if(!le({id:l,name:t.name,env:t.oauthRef?void 0:t.envKey,buildModelsRequest:p,requiresIntranet:t.requiresIntranet===!0},e)){i.rejected.push({id:t.id,reason:`provider descriptor id already claimed by another plugin`}),t.envKey&&!t.oauthRef&&n.authStore.unregisterEnvKey(l),m();continue}t.allowAuthHeaderOverride&&B.warn({pluginId:e,providerId:t.id},`provider declares allowAuthHeaderOverride: custom headers may replace auth headers (RFC-270 D3)`);let h=gu(t,n.authStore,u,n.wireProtocolRegistry,d,f);if(!(a?.has(c)?n.providerRegistry.replacePluginProvider(c,h,e):n.providerRegistry.registerPluginProvider(c,h,e))){i.rejected.push({id:t.id,reason:`api already registered by another plugin or reserved`}),pe(l),t.envKey&&!t.oauthRef&&n.authStore.unregisterEnvKey(l),m();continue}if(t.models?.length){let r=t.models.map(e=>mu(e,u,c,d,t.imageConstraints,t.supportsTools,t.responseBodyPolicy)),i=n.modelRegistry.registerWithSource(r,e);for(let t of i)B.warn({pluginId:e,modelId:t},`plugin model id collides with an existing model, rejected (no silent override)`)}i.registered.push(t.id),t.oauthRef&&s.add(u)}}function yu(e,t,n,r,i){let a={registered:[],rejected:[]},o=n.authStore.oauth;return _u(e,t,o,lu(t),new Map((t.contributes?.providers??[]).filter(e=>e.oauthRef&&e.name).map(e=>[e.oauthRef,e.name])),a,r),vu(e,t,n,o,a,i),a}async function bu(e,t,n,r,i){let a=n.authStore.oauth,o=lu(t),s=t.contributes?.oauth;if(s?.length&&a)for(let t of s){let n=o.has(t.id)?t.id:V(e,t.id);r?.has(n)||a.unregister(n)}let c=t.contributes?.providers;if(c?.length){for(let t of c){let r=t.preserveProviderId===!0?t.id:V(e,t.id);pe(r),t.envKey&&!t.oauthRef&&n.authStore.unregisterEnvKey(r)}await n.providerRegistry.unregisterBySource(e,i),n.modelRegistry.unregisterBySource(e)}}var xu=class{axisName=`oauthProviderFactories`;oauthIdsByPlugin=new Map;constructor(e,t){this.authStore=e,this.logger=t}register(e){let t=e.loaded.module.oauthProviderFactories;if(!t||!this.authStore)return;if(!e.plugin.manifest.capabilities?.includes(`provider`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares oauthProviderFactories but not capabilities:["provider"], skipped (fail-closed)`);return}if(e.verdict.pendingCapabilities.includes(`provider`)){this.logger.warn({pluginId:e.plugin.id},`plugin capability "provider" not yet granted, skipping oauthProviderFactories (fail-closed)`);return}let n=new Set((e.plugin.manifest.contributes?.providers??[]).filter(e=>e.preserveProviderId===!0&&e.oauthRef).map(e=>e.oauthRef));for(let[r,i]of Object.entries(t)){let t=_c(e.plugin.id,i);if(!t)continue;let a=n.has(r)?r:V(e.plugin.id,r);if(t.id!==a){this.logger.warn({pluginId:e.plugin.id,name:r,expectedId:a,actualId:t.id},`plugin oauth provider id mismatch with manifest oauthRef/preserveProviderId, skipped`);continue}if(this.authStore.oauth.register(t,e.plugin.id)){let n=this.oauthIdsByPlugin.get(e.plugin.id)??new Set;n.add(t.id),this.oauthIdsByPlugin.set(e.plugin.id,n)}else this.logger.warn({pluginId:e.plugin.id,oauthId:t.id},`plugin oauthProviderFactory rejected (reserved or claimed)`)}}unregister(e){if(!this.authStore)return;let t=this.oauthIdsByPlugin.get(e);if(t){for(let e of t)this.authStore.oauth.unregister(e);this.oauthIdsByPlugin.delete(e)}}unregisterAll(){for(let e of[...this.oauthIdsByPlugin.keys()])this.unregister(e)}},Su=class{axisName=`providerFactories`;providerSourcePluginIds=new Set;modelSourcePluginIds=new Set;descriptorIdsByPlugin=new Map;constructor(e,t,n){this.providerRegistry=e,this.modelRegistry=t,this.logger=n}register(e){let t=e.loaded.module.providerFactories;if(!t||!this.providerRegistry)return;if(!e.plugin.manifest.capabilities?.includes(`provider`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares providerFactories but not capabilities:["provider"], skipped (fail-closed)`);return}if(e.verdict.pendingCapabilities.includes(`provider`)){this.logger.warn({pluginId:e.plugin.id},`plugin capability "provider" declared but not yet granted, skipping providerFactories (fail-closed, RFC-124 C2)`);return}let n=e.plugin.manifest.codeProviderModelsEndpoints??{},r=e.plugin.manifest.codeProviderModels??{};for(let[i,a]of Object.entries(t)){let t=fu(e.plugin.id,i,e.plugin.manifest);if(!this.providerRegistry.registerPluginProvider(t,gc(e.plugin.id,a),pu(e.plugin.id))){this.logger.warn({pluginId:e.plugin.id,api:t},`plugin providerFactory rejected (reserved builtin or claimed by another plugin)`);continue}this.providerSourcePluginIds.add(e.plugin.id);let o=n[i];if(o)if(le({id:t,buildModelsRequest:hu(o,t,t)},pu(e.plugin.id))){let n=this.descriptorIdsByPlugin.get(e.plugin.id)??new Set;n.add(t),this.descriptorIdsByPlugin.set(e.plugin.id,n)}else this.logger.warn({pluginId:e.plugin.id,api:t},`plugin codeProviderModelsEndpoints descriptor rejected (reserved builtin or claimed by another plugin)`);let s=r[i];if(s?.models?.length&&this.modelRegistry){let n=s.models.map(e=>mu(e,t,t,s.baseUrl,s.imageConstraints,s.supportsTools,s.responseBodyPolicy)),r=this.modelRegistry.registerWithSource(n,e.plugin.id);this.modelSourcePluginIds.add(e.plugin.id),r.length>0&&this.logger.warn({pluginId:e.plugin.id,rejectedModelIds:r},`plugin codeProviderModels contains model ids already claimed by another source, rejected`)}}}async unregister(e){this.providerRegistry&&this.providerSourcePluginIds.has(e)&&(await this.providerRegistry.unregisterBySource(pu(e)),this.providerSourcePluginIds.delete(e)),this.modelRegistry&&this.modelSourcePluginIds.has(e)&&(this.modelRegistry.unregisterBySource(e),this.modelSourcePluginIds.delete(e));let t=this.descriptorIdsByPlugin.get(e);if(t){for(let e of t)pe(e);this.descriptorIdsByPlugin.delete(e)}}async unregisterAll(){let e=new Set([...this.providerSourcePluginIds,...this.modelSourcePluginIds,...this.descriptorIdsByPlugin.keys()]);for(let t of e)await this.unregister(t)}},Cu=class{axisName=`wireProtocols`;wireProtocolSourcePluginIds=new Set;cacheReportingApisByPlugin=new Map;constructor(e,t){this.wireProtocolRegistry=e,this.logger=t}register(e){let t=e.loaded.module.wireProtocols;if(!(!t||!this.wireProtocolRegistry)){if(!e.plugin.manifest.capabilities?.includes(`wire-protocol`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares wireProtocols but not capabilities:["wire-protocol"], skipped (fail-closed)`);return}if(e.verdict.pendingCapabilities.includes(`wire-protocol`)){this.logger.warn({pluginId:e.plugin.id},`plugin capability "wire-protocol" declared but not yet granted, skipping wireProtocols (fail-closed, RFC-124 C2 pattern)`);return}for(let[n,r]of Object.entries(t))if(this.wireProtocolRegistry.register(n,r,e.plugin.id)){if(this.wireProtocolSourcePluginIds.add(e.plugin.id),r.meta?.reportsCacheTokens){ce(n);let t=this.cacheReportingApisByPlugin.get(e.plugin.id)??new Set;t.add(n),this.cacheReportingApisByPlugin.set(e.plugin.id,t)}}else this.logger.warn({pluginId:e.plugin.id,wireApi:n},`plugin wireProtocol rejected (already registered by another plugin, first-win)`)}}unregister(e){this.wireProtocolRegistry&&this.wireProtocolSourcePluginIds.has(e)&&(this.wireProtocolRegistry.unregisterBySource(e),this.wireProtocolSourcePluginIds.delete(e));let t=this.cacheReportingApisByPlugin.get(e);if(t){for(let e of t)fe(e);this.cacheReportingApisByPlugin.delete(e)}}unregisterAll(){let e=new Set([...this.wireProtocolSourcePluginIds,...this.cacheReportingApisByPlugin.keys()]);for(let t of e)this.unregister(t)}},wu=class{axisName=`tools`;toolSourcePluginIds=new Set;constructor(e,t){this.toolRegistry=e,this.logger=t}register(e){let t=e.loaded.module.tools;if(!t?.length||!this.toolRegistry)return;if(!e.plugin.manifest.capabilities?.includes(`tools`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares tools but not capabilities:["tools"], skipped (fail-closed)`);return}if(e.verdict.pendingCapabilities.includes(`tools`)){this.logger.warn({pluginId:e.plugin.id},`plugin capability "tools" declared but not yet granted, skipping tools (fail-closed, RFC-124 C2)`);return}let n=this.toolRegistry,r={workspaceDir:e.workspaceDir,logger:{info:t=>this.logger.info({pluginId:e.plugin.id},t),warn:t=>this.logger.warn({pluginId:e.plugin.id},t),error:t=>this.logger.error({pluginId:e.plugin.id},t)},host:e.host,storage:e.storage},i=t.map(t=>yc(e.plugin.id,t,r)).filter(e=>e!==null).filter(t=>n.has(t.name)?(this.logger.warn({pluginId:e.plugin.id,tool:t.name},`plugin tool name collides with an existing tool, rejected (R3, no silent override)`),!1):!0);i.length>0&&(n.register(i,{preset:`full`,source:e.plugin.id}),this.toolSourcePluginIds.add(e.plugin.id))}unregister(e){!this.toolRegistry||!this.toolSourcePluginIds.has(e)||(this.toolRegistry.unregisterBySource(e),this.toolSourcePluginIds.delete(e))}unregisterAll(){for(let e of[...this.toolSourcePluginIds])this.unregister(e)}};const Tu=`[plugin]`;function Eu(e,t,n){let r=n.name?.trim()||n.key;return`${Tu} ${e}:${t}:${n.key} — ${r}`}function Du(e,t,n){let r=e.subscriber;return!r||r.kind!==`plugin-service`||r.pluginId!==t||r.serviceId!==n?!1:e.name.startsWith(Tu)}function Ou(e,t,n){let r=`${Tu} ${t}:${n}:`;if(!e.name.startsWith(r))return;let i=e.name.slice(r.length),a=i.indexOf(` — `);if(!(a<=0))return i.slice(0,a)}function ku(e){let{port:t,logger:n,pluginId:r,serviceId:i}=e,a={added:0,updated:0,removed:0},o=new Map;for(let t of e.declared){let e=t?.key?.trim(),a=t?.cron?.trim();if(!e||!a){n.warn({pluginId:r,serviceId:i,key:t?.key},`plugin schedule subscription missing key or cron, skipped (RFC-327 D2)`);continue}if(o.has(e)){n.warn({pluginId:r,serviceId:i,key:e},`duplicate plugin schedule subscription key, later declaration ignored`);continue}o.set(e,{...t,key:e,cron:a})}let s=new Map;for(let e of t.list()){if(!Du(e,r,i))continue;let t=Ou(e,r,i);t!==void 0&&s.set(t,e)}for(let[e,c]of o){let o=Eu(r,i,c),l=s.get(e);if(!l){try{t.add({name:o,prompt:`plugin service subscription (${r}:${i}:${e})`,cronExpression:c.cron,recurring:!0,origin:`user`,subscriber:{kind:`plugin-service`,pluginId:r,serviceId:i}}),a.added+=1}catch(t){n.warn({pluginId:r,serviceId:i,key:e,err:t instanceof Error?t.message:String(t)},`failed to register plugin schedule subscription`)}continue}(l.cronExpression!==c.cron||l.name!==o)&&t.update(l.id,{cronExpression:c.cron,name:o})&&(a.updated+=1)}for(let[e,n]of s)o.has(e)||t.remove(n.id)&&(a.removed+=1);return a}function Au(e){let{port:t,pluginId:n}=e,r=0;for(let e of t.list()){let i=e.subscriber;!i||i.kind!==`plugin-service`||i.pluginId!==n||e.name.startsWith(Tu)&&t.remove(e.id)&&(r+=1)}return r}var ju=class{axisName=`services`;startedByPlugin=new Map;scheduleDeclarations=new Map;constructor(e){this.deps=e}async register(e){let t=e.loaded.module.services;if(!t?.length)return;if(!e.plugin.manifest.capabilities?.includes(`service`)){this.deps.logger.warn({pluginId:e.plugin.id},`plugin declares services but not capabilities:["service"], skipped (fail-closed, RFC-287 D-M3-1)`);return}if(e.verdict.pendingCapabilities.includes(`service`)){this.deps.logger.warn({pluginId:e.plugin.id},`plugin capability "service" declared but not yet granted, skipping services (fail-closed)`);return}let n=e.loaded.compiledPath;if(!n){this.deps.logger.warn({pluginId:e.plugin.id},`plugin declares services but has no compiled entry path; services need a compiled module to run in the service worker (skipped)`);return}let r=this.startedByPlugin.get(e.plugin.id)??[];for(let i of t){if(!i?.id)continue;let t=this.deps.getWorkspaceKey(),a=this.deps.hasStorageCapability(e.plugin.id),{error:o}=await this.deps.pool.start({pluginId:e.plugin.id,serviceId:i.id,compiledPath:n,workspaceDir:this.deps.workspaceDir,workspaceKey:t,factoryCtx:{pluginId:e.plugin.id,pluginDir:e.plugin.dir,workspaceDir:this.deps.workspaceDir},hostCapabilities:this.deps.hostCapabilitiesFor(e.plugin.id),storageDir:a?this.deps.storageDirFor(e.plugin.id,t):``,hasStorageCapability:a,bridge:this.deps.bridgeFor(e.plugin.id)});o&&this.deps.logger.warn({pluginId:e.plugin.id,serviceId:i.id,err:o},`plugin service failed to start`),r.push(i.id),this.scheduleDeclarations.set(`${e.plugin.id}:${i.id}`,i.schedules??[]);let s=this.deps.getSchedulePort?.();if(i.schedules?.length){if(!s)this.deps.logger.debug({pluginId:e.plugin.id,serviceId:i.id,count:i.schedules.length},`plugin declares schedule subscriptions but no scheduler in this process, skipped (RFC-327 D2 boundary)`);else if(!o){let t=ku({port:s,logger:this.deps.logger,pluginId:e.plugin.id,serviceId:i.id,declared:i.schedules});(t.added||t.updated||t.removed)&&this.deps.logger.info({pluginId:e.plugin.id,serviceId:i.id,...t},`plugin schedule subscriptions reconciled`)}}else s&&ku({port:s,logger:this.deps.logger,pluginId:e.plugin.id,serviceId:i.id,declared:[]})}r.length>0&&this.startedByPlugin.set(e.plugin.id,r)}async unregister(e){if(!this.startedByPlugin.has(e))return;this.startedByPlugin.delete(e);for(let t of[...this.scheduleDeclarations.keys()])t.startsWith(`${e}:`)&&this.scheduleDeclarations.delete(t);let t=this.deps.getSchedulePort?.();if(t){let n=Au({port:t,pluginId:e});n>0&&this.deps.logger.info({pluginId:e,removed:n},`plugin schedule subscriptions revoked`)}await this.deps.pool.stopPlugin(e)}async unregisterAll(){for(let e of[...this.startedByPlugin.keys()])await this.unregister(e)}reconcileAllSchedules(){let e=this.deps.getSchedulePort?.();if(e)for(let[t,n]of this.startedByPlugin)for(let r of n){let n=this.scheduleDeclarations.get(`${t}:${r}`);if(n===void 0)continue;let i=ku({port:e,logger:this.deps.logger,pluginId:t,serviceId:r,declared:n});(i.added||i.updated||i.removed)&&this.deps.logger.info({pluginId:t,serviceId:r,...i,source:`scheduler-ready reconcile`},`plugin schedule subscriptions reconciled (M3 scheduler-ready)`)}}};const Mu=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Nu=x(n,`plugin-state`);function Pu(e){let t=Fu(e);try{return Xr(t,{recursive:!0,force:!0}),{removed:!D(t),dir:t}}catch{return{removed:!1,dir:t}}}function Fu(e){if(!Mu.test(e))throw Error(`invalid pluginId for scoped storage: ${e} (must be kebab-case)`);return x(Nu,e)}var Iu=class{persistence;baseDir;pluginId;workspaceKey;constructor(e,t){if(this.pluginId=e,this.workspaceKey=t,!Mu.test(e))throw Error(`invalid pluginId for scoped storage: ${e} (must be kebab-case)`);if(typeof t!=`string`||t.length===0||t.includes(`/`)||t.includes(`\\`)||t.includes(`..`))throw Error(`invalid workspaceKey for scoped storage: ${t}`);if(s()){this.baseDir=`:memory:/plugin-state/${e}/${t}`,this.persistence=sn({type:`memory`});return}let n=S(x(Fu(e),t));O(n,{recursive:!0});let r=Jr(n),i=Jr(Nu);if(r!==i&&!r.startsWith(i+`/`))throw Error(`scoped storage path escapes plugin-state root: ${r}`);this.baseDir=n,this.persistence=sn({type:`file`,baseDir:n})}async save(e,t){await this.persistence.save({id:e,data:t,version:1,metadata:{}})}async load(e){let t=await this.persistence.load(e);return t?t.data:null}delete(e){return this.persistence.delete(e)}list(){return this.persistence.list()}};function Lu(e){let t=new Set([...e.manifest.codeProviderIds??[],...(e.manifest.contributes?.providers??[]).filter(e=>e.preserveProviderId===!0).map(e=>e.id)]),n=`${e.id}:`;return e=>t.has(e)||e.startsWith(n)}function Ru(e,t,n){let r=e.manifest.capabilities??[],i={},a=!1,o=n.startPluginJob;r.includes(`agent.dispatch`)&&!t.pendingCapabilities.includes(`agent.dispatch`)&&o?(i.startJob=async t=>{let r=n.getSessionId?.();if(!r)throw Error(`agent.dispatch unavailable: no active session to attach the job to`);return{jobId:o({pluginId:e.id,title:t.title,prompt:t.prompt,sessionId:r}).id}},a=!0):r.includes(`agent.dispatch`)&&n.logger.warn({pluginId:e.id,pending:t.pendingCapabilities.includes(`agent.dispatch`)},`plugin declares agent.dispatch but it is not available (not yet granted, or host provides no job dispatcher) — skipping (fail-closed, RFC-287 D2)`);let s=n.getSessionMessages,c=Bu(n);r.includes(`session.read`)&&!t.pendingCapabilities.includes(`session.read`)&&s?(i.readTranscript=async t=>{if(!c.isSessionAuthorized(e.id,t.sessionId))throw Error(`session not authorized for this plugin`);let n=s(t.sessionId);if(!n)throw Error(`session not found`);if(!c.tryConsumeRead(e.id))throw Error(`readTranscript quota exceeded for this notification`);return Sl(n,t.sinceIndex??0,500)},a=!0):r.includes(`session.read`)&&n.logger.warn({pluginId:e.id,pending:t.pendingCapabilities.includes(`session.read`)},`plugin declares session.read but it is not available (not yet granted, or host provides no transcript source) — skipping (fail-closed, RFC-318 D2)`);let l=n.completeText;r.includes(`llm.complete`)&&!t.pendingCapabilities.includes(`llm.complete`)&&l?(i.complete=async t=>{if(t.prompt.length>32e3)throw Error(`prompt exceeds 32000 chars limit`);let n=c.tryConsumeLlm(e.id);if(!n.ok)throw Error(`llm.complete quota exceeded (${n.reason})`);let r=Math.min(t.maxTokens??2048,2048);return l(t.prompt,{maxTokens:r})},a=!0):r.includes(`llm.complete`)&&n.logger.warn({pluginId:e.id,pending:t.pendingCapabilities.includes(`llm.complete`)},`plugin declares llm.complete but it is not available (not yet granted, or host provides no model caller) — skipping (fail-closed, RFC-318 D2)`);let u=n.askUser;r.includes(`user.ask`)&&!t.pendingCapabilities.includes(`user.ask`)&&u?(i.ask=async t=>u(e.id,{header:String(t.header??``),question:String(t.question??``),background:String(t.background??``),recommendation:String(t.recommendation??``),...Array.isArray(t.options)?{options:t.options}:{},...t.allowFreeform===void 0?{}:{allowFreeform:!!t.allowFreeform},...t.multiSelect===void 0?{}:{multiSelect:!!t.multiSelect},...Array.isArray(t.evidence)?{evidence:t.evidence.map(String)}:{}}),a=!0):r.includes(`user.ask`)&&n.logger.warn({pluginId:e.id,pending:t.pendingCapabilities.includes(`user.ask`)},`plugin declares user.ask but it is not available (not yet granted, or host provides no UI sink) — skipping (fail-closed, RFC-344 M3)`);let d=n.notifyUser;return r.includes(`user.notify`)&&!t.pendingCapabilities.includes(`user.notify`)&&d?(i.notify=async t=>{if(!c.tryConsumeNotify(e.id)){n.logger.debug({pluginId:e.id,code:t.code},`plugin user.notify dropped: rate limit exceeded (silent by design, RFC-327 D3)`);return}let r=t.message.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,` `).slice(0,500);d({pluginId:e.id,level:t.level,code:t.code.slice(0,120),message:r})},a=!0):r.includes(`user.notify`)&&n.logger.warn({pluginId:e.id,pending:t.pendingCapabilities.includes(`user.notify`)},`plugin declares user.notify but it is not available (not yet granted, or host provides no UI sink) — skipping (fail-closed, RFC-327 D3)`),a?i:void 0}const zu=new WeakMap;function Bu(e){if(e.capabilityQuota)return e.capabilityQuota;let t=zu.get(e);return t||(t=new Ec,zu.set(e,t)),t}const Vu=new Map([[`oauthProviderFactories`,`provider`],[`providerFactories`,`provider`],[`wireProtocols`,`wire-protocol`]]);function Hu(e){let t=e.manifest.contributes;return!t||typeof t!=`object`?[]:Object.keys(t)}var Uu=class e{contributesSnapshot=new Map;static DEACTIVATE_TIMEOUT_MS=5e3;hooksAxis;monitorsAxis;feedbackAxis;sigilAxis;computedCommandsAxis;computedAgentsAxis;computedSkillsAxis;oauthProviderAxis;codeProviderAxis;wireProtocolAxis;toolsAxis;servicesAxis;axisHandlers;firedEvents=new Set;deferredIds=new Set;loadedModules=new Map;constructor(e){this.deps=e,this.hooksAxis=new Jl(e.hookRegistry),this.monitorsAxis=new Yl(e.hookRegistry,e.logger),this.feedbackAxis=new Xl(e.feedbackRegistry,e.logger),this.sigilAxis=new iu(e.sigilResolverRegistry,e.pluginInput,e.logger),this.computedCommandsAxis=new au,this.computedAgentsAxis=new ou,this.computedSkillsAxis=new su(e.skillRegistry),this.oauthProviderAxis=new xu(e.authStore,e.logger),this.codeProviderAxis=new Su(e.providerRegistry,e.modelRegistry,e.logger),this.wireProtocolAxis=new Cu(e.wireProtocolRegistry,e.logger),this.toolsAxis=new wu(e.toolRegistry,e.logger),this.servicesAxis=new ju({pool:e.servicePool??gl(),logger:e.logger,workspaceDir:e.workspaceDir,getWorkspaceKey:()=>e.getWorkspaceKey?.()??`default`,bridgeFor:t=>{let n=e.activePlugins().find(e=>e.id===t);if(!n)return{};let r=Ru(n,E(n),e);if(!r)return{};let i={};return r.startJob&&(i.startJob=r.startJob),r.readTranscript&&(i.readTranscript=r.readTranscript),r.complete&&(i.complete=r.complete),r.notify&&(i.notify=r.notify),i},hostCapabilitiesFor:t=>{let n=e.activePlugins().find(e=>e.id===t);if(!n)return[];let r=Ru(n,E(n),e);if(!r)return[];let i=[];return r.startJob&&i.push(`startJob`),r.readTranscript&&i.push(`readTranscript`),r.complete&&i.push(`complete`),r.notify&&i.push(`notify`),i},storageDirFor:(e,t)=>new Iu(e,t).baseDir,hasStorageCapability:t=>!!e.activePlugins().find(e=>e.id===t)?.manifest.capabilities?.includes(`storage`),...e.getSchedulePort?{getSchedulePort:e.getSchedulePort}:{}}),this.axisHandlers=[this.hooksAxis,this.monitorsAxis,this.feedbackAxis,this.sigilAxis,this.computedCommandsAxis,this.computedAgentsAxis,this.computedSkillsAxis,this.oauthProviderAxis,this.codeProviderAxis,this.wireProtocolAxis,this.toolsAxis,this.servicesAxis]}get deferredPluginIds(){return this.deferredIds}emitMonitorEvent(e){return this.monitorsAxis.dispatch(e)}reconcileServiceSchedules(){this.servicesAxis.reconcileAllSchedules()}get monitorPluginIds(){return this.monitorsAxis.monitorPluginIds}async activateOn(e,t){return this.firedEvents.add(e),this.reload(t)}get commands(){return this.computedCommandsAxis.getComputedCommands()}async callOnDeactivate(t,n){let r;try{await Promise.race([n(),new Promise((n,i)=>{r=setTimeout(()=>{i(Error(`plugin "${t}" onDeactivate timed out after ${e.DEACTIVATE_TIMEOUT_MS}ms`))},e.DEACTIVATE_TIMEOUT_MS),r.unref?.()})])}catch(e){this.deps.logger.warn({pluginId:t,err:String(e)},`plugin onDeactivate failed or timed out`)}finally{r!==void 0&&clearTimeout(r)}}async unregisterAllAxes(){for(let e of this.axisHandlers)await e.unregisterAll()}async unregisterPluginAxes(e,t){let n=t?E(t):void 0;for(let r of this.axisHandlers){let i=Vu.get(r.axisName);i!==void 0&&t!==void 0&&n!==void 0&&t.manifest.capabilities?.some(e=>e===i)&&!n.gated&&!n.pendingCapabilities.includes(i)||await r.unregister(e)}Bu(this.deps).reset(e)}pluginSignature(e){let t=E(e),n=`${t.gated?`gated`:`ok`}:${[...t.pendingCapabilities].sort().join(`,`)}`,r=`nofile`;for(let t of[`plugin.ts`,`plugin.tsx`])try{let n=Zr(x(e.dir,t));r=`${t}:${n.mtimeMs}:${n.size}`;break}catch{}return`${JSON.stringify(e.manifest)}|${n}|${r}`}async reload(e){let t=this.deps.activePlugins(),n=new Map(t.map(e=>[e.id,e])),r=new Map(t.map(e=>[e.id,this.pluginSignature(e)])),i=[],a=new Set,o=new Set;for(let[e,t]of this.loadedModules)n.get(e)?r.get(e)!==t.signature&&(t.module.module.onDeactivate&&i.push({pluginId:e,onDeactivate:t.module.module.onDeactivate}),o.add(e)):(t.module.module.onDeactivate&&i.push({pluginId:e,onDeactivate:t.module.module.onDeactivate}),a.add(e));for(let{pluginId:e,onDeactivate:t}of i)await this.callOnDeactivate(e,t);for(let e of a)await this.unregisterPluginAxes(e,void 0),this.loadedModules.delete(e);for(let e of o)await this.unregisterPluginAxes(e,n.get(e));this.computedAgentsAxis.setExistingAgentNames(e);let s=new Set;for(let e of this.deps.activePlugins()){if(!ql(ir(e.manifest),this.firedEvents)){s.add(e.id);continue}if(this.loadedModules.get(e.id)&&!o.has(e.id))continue;let t={pluginId:e.id,pluginDir:e.dir,workspaceDir:this.deps.workspaceDir,callMcpTool:(e,t,n)=>this.deps.callMcpTool(e,t,n),logger:{debug:t=>{this.deps.logger.debug({pluginId:e.id},t)},info:t=>{this.deps.logger.info({pluginId:e.id},t),sc(e.id,`info`,t)},warn:t=>{this.deps.logger.warn({pluginId:e.id},t),sc(e.id,`warn`,t)},error:t=>{this.deps.logger.error({pluginId:e.id},t),sc(e.id,`error`,t)}},getWireProtocol:e=>this.deps.wireProtocolRegistry?.get(e),resolveProviderCredential:(()=>{let t=Lu(e);return e=>t(e)?this.deps.providerRegistry?.resolveAccessKey(e)??Promise.resolve(null):Promise.resolve(null)})(),resolveProviderAuth:(()=>{let t=Lu(e);return e=>t(e)?this.deps.providerRegistry?.resolveAuth(e)??Promise.resolve(null):Promise.resolve(null)})(),host:Ru(e,E(e),this.deps),listActivePlugins:()=>this.deps.activePlugins().map(e=>({id:e.id,version:e.manifest.version,capabilities:e.manifest.capabilities??[],contributes:this.contributesSnapshot.get(e.id)??Hu(e)}))},n=this.deps.useIsolatedLoading!==!1&&Wl(e)?await Kl(e,t,void 0,this.deps.onPluginLoadError):await sl(e,t,this.deps.onPluginLoadError);if(!n)continue;let i=E(e);if(i.gated){this.deps.logger.warn({pluginId:e.id},`project plugin not trusted, skipping code axes (fail-closed, RFC-124 C1)`);continue}let a;if(e.manifest.capabilities?.includes(`storage`))try{let t=this.deps.getWorkspaceKey?.()??Si;a=new Iu(e.id,t)}catch(t){this.deps.logger.warn({pluginId:e.id,err:String(t)},`failed to construct scoped storage for plugin, storage capability unavailable`)}let c={plugin:e,verdict:i,loaded:n,host:Ru(e,i,this.deps),workspaceDir:this.deps.workspaceDir,storage:a};for(let e of this.axisHandlers)await e.register(c);if(n.module.onActivate)try{await n.module.onActivate()}catch(t){this.deps.logger.warn({pluginId:e.id,err:String(t)},`plugin onActivate threw`)}this.contributesSnapshot.set(e.id,Hu(e)),this.loadedModules.set(e.id,{module:n,manifest:e.manifest,signature:r.get(e.id)??this.pluginSignature(e)})}return this.deferredIds=s,this.computedAgentsAxis.getAppendedAgents()}async cleanup(){for(let[e,t]of this.loadedModules)t.module.module.onDeactivate&&await this.callOnDeactivate(e,t.module.module.onDeactivate);this.loadedModules.clear(),await this.unregisterAllAxes();let e=Bu(this.deps);for(let t of this.deps.activePlugins())e.reset(t.id);this.firedEvents.clear()}};const Wu=C(`@x-otto/coding:panel-compiler`);function Gu(e){let t=x(e,`panels`);if(!D(t))return{compiled:[],errors:[],skipped:!0};let n;try{n=Kr(t).filter(e=>e.endsWith(`.tsx`))}catch{return{compiled:[],errors:[],skipped:!0}}if(n.length===0)return{compiled:[],errors:[],skipped:!0};let r=x(e,`panels-dist`);O(r,{recursive:!0});let i=Wr(x(Be(),`otto-panel-shims-`)),a=x(i,`react-shim.js`),o=x(i,`ink-shim.js`),s=x(i,`tui-shim.js`);A(a,`const R = globalThis.React
|
|
367
|
+
})`}`}var wl=class{pending=new Map;idCounter=0;boundPluginId=``;hostCallDispatcher=null;setHostCallDispatcher(e){this.hostCallDispatcher=e}constructor(e){this.adapter=e,this.adapter.onMessage(e=>{if(e.type===z.loaded){let t=this.settlePending(`__load__`);t&&t.resolve(e.module);return}if(e.type===z.error){let t=this.settlePending(`__load__`);t&&t.reject(Error(e.error??this.adapter.loadFailedMessage?.()??`plugin isolated transport load failed`));return}if(e.type===z.toolResult){let t=this.settlePending(e.id);t&&t.resolve({result:e.result,error:e.error});return}if(e.type===z.sigilResult){let t=this.settlePending(e.id);t&&t.resolve({result:e.result,error:e.error});return}if(e.type===z.activated||e.type===z.deactivated){let t=this.settlePending(e.id);t&&t.resolve({error:e.error});return}if(e.type===z.hostCall){let t=this.boundPluginId,n=this.hostCallDispatcher,r=t=>{try{this.adapter.send({type:z.hostResult,id:e.id,...t})}catch{}};if(!n){r({error:`host call dispatcher not installed (plugin host capabilities unavailable)`});return}n(t,e.method??``,e.args??[]).then(e=>r({result:e})).catch(e=>r({error:e instanceof Error?e.message:String(e)}));return}}),this.adapter.onError(e=>{this.adapter.onErrorLog?.(e),this.rejectAllPending(e)}),this.adapter.onExit(e=>{if(this.pending.size===0)return;this.adapter.onExitLog?.(e);let t=this.adapter.exitErrorMessage?.(e)??`plugin isolated transport exited unexpectedly (code ${e})`;this.rejectAllPending(Error(t))})}rejectAllPending(e){for(let[,t]of this.pending)t.type===`load`?t.reject(e):t.resolve({error:e.message});this.pending.clear(),this.adapter.unref()}syncRefState(){this.pending.size>0?this.adapter.ref():this.adapter.unref()}trackPending(e,t){this.pending.set(e,t),this.syncRefState()}settlePending(e){let t=this.pending.get(e);return t&&(this.pending.delete(e),this.syncRefState()),t}async load(e,t,n){if(this.pending.has(`__load__`))throw Error(this.adapter.alreadyLoadingMessage?.(e)??`plugin isolated transport already loading ${e}`);return this.boundPluginId=e,new Promise((r,i)=>{this.trackPending(`__load__`,{type:`load`,resolve:r,reject:i}),this.adapter.send({type:z.load,pluginId:e,compiledPath:t,ctx:n,...n.hostMethods?{hostMethods:n.hostMethods}:{},...n.hostExternals?{hostExternals:n.hostExternals}:{}})})}async executeTool(e,t,n){let r=`tool-${++this.idCounter}`,i=n?.timeoutMs??6e4,a=n?.signal;return a?.aborted?{error:`plugin tool execution aborted`}:new Promise(n=>{let o,s,c=()=>{o!==void 0&&clearTimeout(o),s&&a&&a.removeEventListener(`abort`,s)};this.trackPending(r,{type:`tool`,resolve:e=>{c(),n(e)}});let l=e=>{let t=this.settlePending(r);if(t){try{this.adapter.send({type:z.toolCancel,id:r})}catch{}t.resolve({error:e})}};i>0&&(o=setTimeout(()=>{this.adapter.onToolTimeout?.(e,i),l(`plugin tool "${e}" timed out after ${i}ms`)},i),o.unref?.()),a&&(s=()=>l(`plugin tool execution aborted`),a.addEventListener(`abort`,s,{once:!0})),this.adapter.send({type:z.toolExecute,id:r,name:e,params:t})})}async resolveSigil(e,t,n,r){let i=`sigil-${++this.idCounter}`,a=r?.timeoutMs??6e4;return new Promise(r=>{let o;this.trackPending(i,{type:`sigil`,resolve:e=>{o!==void 0&&clearTimeout(o),r(e)}}),a>0&&(o=setTimeout(()=>{let t=this.settlePending(i);t&&t.resolve({error:`sigil resolver "${e}" timed out after ${a}ms`})},a),o.unref?.()),this.adapter.send({type:z.sigilResolve,id:i,name:e,param:t,ctx:n})})}async activate(){let e=`lifecycle-${++this.idCounter}`;return new Promise(t=>{this.trackPending(e,{type:`lifecycle`,resolve:t}),this.adapter.send({type:z.onActivate,id:e})})}async deactivate(){let e=`lifecycle-${++this.idCounter}`;return new Promise(t=>{this.trackPending(e,{type:`lifecycle`,resolve:t}),this.adapter.send({type:z.onDeactivate,id:e})})}clearPending(){this.pending.clear()}};const Tl=C(`@x-otto/coding:plugin-worker-pool`);let El=null,Dl=null;function Ol(){return Dl||(El||=Wr(x(Be(),`otto-plugin-worker-`)),Dl=x(El,`worker-entry.cjs`),A(Dl,Cl(`worker`)),Dl)}var kl=class extends wl{worker;constructor(){let e=new Pi(Ol());e.unref(),super({send:t=>e.postMessage(t),onMessage:t=>e.on(`message`,e=>t(e)),onError:t=>e.on(`error`,e=>t(e)),onExit:t=>e.on(`exit`,t),ref:()=>e.ref(),unref:()=>e.unref(),onToolTimeout:(e,t)=>{Tl.warn({tool:e,timeoutMs:t},`plugin tool execution timed out`)},onErrorLog:e=>{Tl.warn({err:String(e)},`plugin worker error`)},onExitLog:e=>{Tl.warn({code:e},`plugin worker exited unexpectedly with pending requests`)},exitErrorMessage:e=>`plugin worker exited unexpectedly (code ${e})`,loadFailedMessage:()=>`plugin worker load failed`,alreadyLoadingMessage:e=>`plugin worker already loading ${e}`}),this.worker=e}async stop(){try{this.worker.postMessage({type:z.stop}),await this.worker.terminate()}catch{}this.clearPending(),this.worker.unref()}},Al=class{workers=new Map;maxConcurrent;hostCallDispatcher=null;constructor(e=8){this.maxConcurrent=e}setHostCallDispatcher(e){this.hostCallDispatcher=e}async load(e,t,n){if(this.workers.size>=this.maxConcurrent)return null;await this.unload(e);let r=new kl;this.hostCallDispatcher&&r.setHostCallDispatcher(this.hostCallDispatcher),this.workers.set(e,r);try{return await r.load(e,t,n)}catch(t){throw this.workers.delete(e),r.stop().catch(()=>{}),t}}async executeTool(e,t,n,r){let i=this.workers.get(e);if(!i)throw Error(`no worker for plugin ${e}`);return i.executeTool(t,n,r)}async resolveSigil(e,t,n,r,i){let a=this.workers.get(e);if(!a)throw Error(`no worker for plugin ${e}`);return a.resolveSigil(t,n,r,i)}async activate(e){let t=this.workers.get(e);if(!t)throw Error(`no worker for plugin ${e}`);return t.activate()}async deactivate(e){let t=this.workers.get(e);if(!t)throw Error(`no worker for plugin ${e}`);return t.deactivate()}async unload(e){let t=this.workers.get(e);t&&(this.workers.delete(e),await t.stop())}async dispose(){let e=[...this.workers.values()];if(this.workers.clear(),El){try{Xr(El,{recursive:!0,force:!0})}catch{}El=null,Dl=null}await Promise.all(e.map(e=>e.stop().catch(()=>{})))}get size(){return this.workers.size}};const jl=C(`@x-otto/coding:plugin-process-pool`);let Ml=null,Nl=null;function Pl(){return Nl||(Ml||=Wr(x(Be(),`otto-plugin-process-`)),Nl=x(Ml,`process-entry.cjs`),A(Nl,Cl(`process`)),Nl)}var Fl=class extends wl{child;sandboxToDispose;constructor(e){let t=Pl(),n=process.execPath,r=[t],i=n,a=r,o;if(Re()){let t=Fe({network:`deny`}),s=t.wrap({command:n,args:r,options:{timeout:0,cwd:e},projectRoot:e});i=s.command,a=s.args,o=t}else jl.warn(`No platform sandbox available for project/repository scope plugin isolation — falling back to plain child_process (still process-isolated, but without OS-level file/network constraints)`);let s=Oi(i,a,{cwd:e,stdio:[`ignore`,`ignore`,`pipe`,`ipc`]});s.unref(),super({send:e=>s.send(e),onMessage:e=>s.on(`message`,t=>e(t)),onError:e=>s.on(`error`,t=>e(t)),onExit:e=>s.on(`exit`,e),ref:()=>{s.channel?.ref(),s.stderr?.ref?.()},unref:()=>{s.channel?.unref(),s.stderr?.unref?.()},onToolTimeout:(e,t)=>{jl.warn({tool:e,timeoutMs:t},`plugin tool execution timed out (isolated process)`)},onErrorLog:e=>{jl.warn({err:String(e)},`plugin process error`)},onExitLog:e=>{jl.warn({code:e},`plugin process exited unexpectedly with pending requests`)},exitErrorMessage:e=>`plugin process exited unexpectedly (code ${e})`,loadFailedMessage:()=>`plugin process load failed`,alreadyLoadingMessage:e=>`plugin process already loading ${e}`}),this.child=s,this.sandboxToDispose=o,this.child.stderr?.on(`data`,e=>{jl.warn({stderr:e.toString().slice(0,500)},`plugin process stderr output`)}),this.child.on(`exit`,()=>{this.sandboxToDispose?.dispose().catch(()=>void 0),this.sandboxToDispose=void 0})}async stop(){try{this.child.send({type:z.stop})}catch{}try{this.child.kill()}catch{}this.clearPending()}},Il=class{processes=new Map;maxConcurrent;hostCallDispatcher=null;constructor(e=4){this.maxConcurrent=e}setHostCallDispatcher(e){this.hostCallDispatcher=e}async load(e,t,n){if(this.processes.size>=this.maxConcurrent)return null;await this.unload(e);let r=new Fl(n.workspaceDir);this.hostCallDispatcher&&r.setHostCallDispatcher(this.hostCallDispatcher),this.processes.set(e,r);try{return await r.load(e,t,n)}catch(t){throw this.processes.delete(e),r.stop().catch(()=>{}),t}}async executeTool(e,t,n,r){let i=this.processes.get(e);if(!i)throw Error(`no process for plugin ${e}`);return i.executeTool(t,n,r)}async resolveSigil(e,t,n,r,i){let a=this.processes.get(e);if(!a)throw Error(`no process for plugin ${e}`);return a.resolveSigil(t,n,r,i)}async activate(e){let t=this.processes.get(e);if(!t)throw Error(`no process for plugin ${e}`);return t.activate()}async deactivate(e){let t=this.processes.get(e);if(!t)throw Error(`no process for plugin ${e}`);return t.deactivate()}async unload(e){let t=this.processes.get(e);t&&(this.processes.delete(e),await t.stop())}async dispose(){let e=[...this.processes.values()];if(this.processes.clear(),Ml){try{Xr(Ml,{recursive:!0,force:!0})}catch{}Ml=null,Nl=null}await Promise.all(e.map(e=>e.stop().catch(()=>{})))}get size(){return this.processes.size}};const Ll=C(`@x-otto/coding:plugin-module-loader-isolated`);let Rl=null;function zl(){return Rl||=new Al,Rl}let Bl=null;function Vl(){return Bl||=new Il,Bl}async function Hl(){await Promise.all([Rl?.dispose()??Promise.resolve(),Bl?.dispose()??Promise.resolve()])}function Ul(e){return e===`project`||e===`repository`?Vl():zl()}function Wl(e){return!!e.manifest.capabilities?.includes(`tools`)}function Gl(e,t,n){let r={};if(t.contributions&&(r.contributions=t.contributions),t.tools.length>0&&(r.tools=t.tools.map(t=>({name:t.name,description:t.description||t.name,parameters:{safeParse(e){return t.hasParameters?{success:!0,data:e}:{success:!0,data:{}}},...t.parametersSchema===void 0?{}:{toJSONSchema:()=>t.parametersSchema}},async execute(r,i){let{result:a,error:o}=await n.executeTool(e,t.name,r,{signal:i?.signal});if(o)throw Error(o);return a&&typeof a==`object`&&Array.isArray(a.content)?a:{content:[{type:`text`,text:typeof a==`string`?a:JSON.stringify(a??null)}]}}}))),t.hasSigilProviders&&Ll.warn({pluginId:e},`plugin declares sigilProviders but is loaded via the isolated path (tools capability) — dynamic @ search providers are not proxied over RPC and will be inactive; declare input.resolver without tools to use the in-process path, or use static sigilEntries`),t.sigilResolvers?.length>0){r.sigilResolvers={};for(let i of t.sigilResolvers)r.sigilResolvers[i.name]={resolve:(t,r)=>n.resolveSigil(e,i.name,t,r,{timeoutMs:i.timeoutMs}).then(e=>{if(e.error)throw Error(e.error);return e.result??``}),timeoutMs:i.timeoutMs,uiHostOnly:i.uiHostOnly}}return t.hasOnActivate&&(r.onActivate=async()=>{let{error:t}=await n.activate(e);if(t)throw Error(t)}),t.hasOnDeactivate&&(r.onDeactivate=async()=>{let{error:t}=await n.deactivate(e);if(t)throw Error(t)}),r}async function Kl(e,t,n,r){if((e.scope===`project`||e.scope===`repository`)&&!Zn(e.dir))return Ll.warn({pluginId:e.id},`project/repository plugin not trusted, skipping isolated code module (fail-closed)`),null;let i=E(e);if(i.pendingCapabilities.length>0)return Ll.warn({pluginId:e.id,pendingCapabilities:i.pendingCapabilities},`plugin declares high-risk capabilities not yet granted, skipping isolated code module before worker execution (fail-closed, RFC-140 D3)`),null;let a=n??Ul(e.scope),o=ol(e.dir);try{o?Ll.info({pluginId:e.id,compiledPath:o},`using prebuilt plugin module (isolated path, RFC-150 D5)`):o=await Qc(e.dir)}catch(t){let n=String(t);return Ll.warn({pluginId:e.id,err:n},`plugin.ts compile failed (isolated path)`),r?.(e.id,`compile failed: ${n}`),null}if(!o)return null;let s=[...Object.keys(t.host??{}),`listActivePlugins`];if(t.host&&Object.keys(t.host).length>0||t.listActivePlugins){let e=t.host;a.setHostCallDispatcher?.(async(n,r,i)=>{if(r===`listActivePlugins`)return t.listActivePlugins?t.listActivePlugins():[];if(!e||typeof e[r]!=`function`)throw Error(`host method '${r}' not available (not declared or not granted)`);if(!(r in e))throw Error(`host method '${r}' not in whitelist`);let a=e[r];return a(...i)})}try{let n=await a.load(e.id,o,{pluginId:t.pluginId,pluginDir:t.pluginDir,workspaceDir:t.workspaceDir,hostMethods:s,listActivePlugins:!0,hostExternals:Yc()});if(n===null){if(e.scope===`project`||e.scope===`repository`){let t=`plugin process pool exhausted (project/repository scope requires isolated execution, refusing to downgrade to in-process)`;return Ll.warn({pluginId:e.id},t),r?.(e.id,t),null}return Ll.info({pluginId:e.id},`plugin worker pool exhausted, falling back to in-process load`),sl(e,t,r)}return{pluginId:e.id,module:Gl(e.id,n,a),compiledPath:o}}catch(t){let n=String(t);return Ll.warn({pluginId:e.id,err:n},`plugin.ts worker load failed`),r?.(e.id,`worker load failed: ${n}`),null}}function ql(e,t){return e.includes(`onStartup`)?!0:e.some(e=>t.has(e))}var Jl=class{axisName=`hooks`;hookNamesByPlugin=new Map;constructor(e){this.hookRegistry=e}register(e){let t=e.loaded.module.hooks;if(t){let n=dc(e.plugin.id,t);this.hookRegistry.registerAll(n);let r=this.hookNamesByPlugin.get(e.plugin.id)??[];r.push(...n.map(e=>e.name)),this.hookNamesByPlugin.set(e.plugin.id,r)}}unregister(e){let t=this.hookNamesByPlugin.get(e);if(t){for(let e of t)this.hookRegistry.unregister(e);this.hookNamesByPlugin.delete(e)}}unregisterAll(){for(let e of[...this.hookNamesByPlugin.keys()])this.unregister(e)}},Yl=class{axisName=`monitors`;hookNamesByPlugin=new Map;monitorsByPlugin=new Map;constructor(e,t){this.hookRegistry=e,this.logger=t}register(e){let t=e.loaded.module.monitors;if(!t?.length)return;if(!e.plugin.manifest.capabilities?.includes(`monitor`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares monitors but not capabilities:["monitor"], skipped (fail-closed)`);return}let n=bc(e.plugin.id,t);this.hookRegistry.registerAll(n);let r=this.hookNamesByPlugin.get(e.plugin.id)??[];r.push(...n.map(e=>e.name)),this.hookNamesByPlugin.set(e.plugin.id,r),this.monitorsByPlugin.set(e.plugin.id,t)}unregister(e){let t=this.hookNamesByPlugin.get(e);if(t){for(let e of t)this.hookRegistry.unregister(e);this.hookNamesByPlugin.delete(e)}this.monitorsByPlugin.delete(e)}unregisterAll(){for(let e of[...this.hookNamesByPlugin.keys()])this.unregister(e)}async dispatch(e){for(let[t,n]of this.monitorsByPlugin)for(let r of n)try{await r.onEvent(e)}catch(n){this.logger.warn({pluginId:t,monitorId:r.id,eventType:e.type,err:String(n)},`plugin monitor onEvent threw (host event), isolated`)}}get monitorPluginIds(){return[...this.monitorsByPlugin.keys()]}},Xl=class{axisName=`feedback`;feedbackRegisteredSources=new Set;constructor(e,t){this.feedbackRegistry=e,this.logger=t}register(e){let t=e.loaded.module.feedbackProviders;if(!(!t||!this.feedbackRegistry)){if(!e.plugin.manifest.capabilities?.includes(`feedback`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares feedbackProviders but not capabilities:["feedback"], skipped (fail-closed)`);return}this.feedbackRegistry.register(t,e.plugin.id)?this.feedbackRegisteredSources.add(e.plugin.id):this.logger.warn({pluginId:e.plugin.id},`plugin feedbackProviders rejected (already registered by a different plugin)`)}}unregister(e){!this.feedbackRegistry||!this.feedbackRegisteredSources.has(e)||(this.feedbackRegistry.unregister(e),this.feedbackRegisteredSources.delete(e))}unregisterAll(){for(let e of[...this.feedbackRegisteredSources])this.unregister(e)}};const Zl=C(`@x-otto/coding:plugin-sigil-loader`);function Ql(e){return e.startsWith(`!`)||e.startsWith(`#`)}function $l(e){let t=[];for(let n of e){let e=n.manifest.contributes?.sigilEntries;if(e?.length){if(E(n).gated){Zl.warn({pluginId:n.id},`plugin gated (untrusted), sigilEntries skipped`);continue}for(let r of e){if(Ql(r.value)){Zl.warn({pluginId:n.id,label:r.label},`sigilEntries value starts with '!' or '#' (mode-prefix collision), skipped`);continue}t.push({label:r.label,value:r.value,kind:r.kind,description:r.description,source:n.id,resolverId:r.resolverId?`${n.id}:${r.resolverId}`:void 0})}}}return t}function eu(e){for(let t of e)t.manifest.contributes?.inputEntries&&Zl.warn({pluginId:t.id},`contributes.inputEntries is deprecated (RFC-210); migrate to contributes.sigilEntries (inline array) — the file-path form is no longer loaded`)}function tu(e,t){let n=[];for(let[r,i]of Object.entries(t)){let t=`${e}:${r}`;typeof i==`function`?n.push({id:t,resolve:i}):i&&typeof i.resolve==`function`?n.push({id:t,resolve:i.resolve,timeoutMs:i.timeoutMs,uiHostOnly:i.uiHostOnly}):Zl.warn({pluginId:e,name:r},`sigilResolvers entry is neither function nor {resolve}, skipped`)}return n}function nu(e,t){return t.map(t=>async(n,r)=>(await t(n,r)).filter(e=>!Ql(e.value)).map(t=>({...t,source:e})))}function ru(e,t){for(let n of e)n.resolverId&&!t(n.resolverId)&&Zl.warn({label:n.label,resolverId:n.resolverId,source:n.source},`sigilEntries.resolverId has no matching resolver (declared sigilResolvers missing or capability not granted) — entry will pass through unexpanded at submit`)}var iu=class{axisName=`sigil`;sigilResolverSourcePluginIds=new Set;sigilProviderUnsubsByPlugin=new Map;constructor(e,t,n){this.sigilResolverRegistry=e,this.pluginInput=t,this.logger=n}register(e){let t=e.loaded.module.sigilResolvers,n=e.loaded.module.sigilProviders;if(t&&Object.keys(t).length>0||n?.length){if(!e.plugin.manifest.capabilities?.includes(`input.resolver`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares sigilResolvers/sigilProviders but not capabilities:["input.resolver"], skipped (fail-closed)`);return}if(e.verdict.pendingCapabilities.includes(`input.resolver`)){this.logger.warn({pluginId:e.plugin.id},`plugin capability "input.resolver" declared but not yet granted, skipping sigil axes (fail-closed)`);return}if(t&&this.sigilResolverRegistry){let n=tu(e.plugin.id,t);n.length>0&&(this.sigilResolverRegistry.register(n,e.plugin.id),this.sigilResolverSourcePluginIds.add(e.plugin.id))}if(n?.length&&this.pluginInput){let t=this.sigilProviderUnsubsByPlugin.get(e.plugin.id)??[];for(let r of nu(e.plugin.id,n))t.push(this.pluginInput.registerProvider(`@`,r));this.sigilProviderUnsubsByPlugin.set(e.plugin.id,t)}if(this.sigilResolverRegistry){let t=this.sigilResolverRegistry;ru($l([e.plugin]),e=>t.get(e)!==void 0)}}}unregister(e){this.sigilResolverRegistry&&this.sigilResolverSourcePluginIds.has(e)&&(this.sigilResolverRegistry.unregisterBySource(e),this.sigilResolverSourcePluginIds.delete(e));let t=this.sigilProviderUnsubsByPlugin.get(e);if(t){for(let e of t)try{e()}catch{}this.sigilProviderUnsubsByPlugin.delete(e)}}unregisterAll(){let e=new Set([...this.sigilResolverSourcePluginIds,...this.sigilProviderUnsubsByPlugin.keys()]);for(let t of e)this.unregister(t)}},au=class{axisName=`computedCommands`;commandsByPlugin=new Map;register(e){let t=e.loaded.module.contributions?.commands;if(t?.length&&e.plugin.scope!==`builtin`){let n=this.commandsByPlugin.get(e.plugin.id)??[];n.push(...fc(e.plugin.id,e.plugin.scope,e.plugin.dir,t)),this.commandsByPlugin.set(e.plugin.id,n)}}unregister(e){this.commandsByPlugin.delete(e)}unregisterAll(){}resetForReload(){this.commandsByPlugin.clear()}getComputedCommands(){return[...this.commandsByPlugin.values()].flat()}},ou=class{axisName=`computedAgents`;profilesByPlugin=new Map;existingAgentNames=new Set;register(e){let t=e.loaded.module.contributions?.agents;if(!t?.length)return;let n=this.profilesByPlugin.get(e.plugin.id)??[];n.push(...pc(t)),this.profilesByPlugin.set(e.plugin.id,n)}unregister(e){this.profilesByPlugin.delete(e)}unregisterAll(){}setExistingAgentNames(e){this.existingAgentNames=e}resetForReload(e){this.profilesByPlugin.clear(),this.existingAgentNames=e}getAppendedAgents(){let e=new Set(this.existingAgentNames),t=[];for(let n of this.profilesByPlugin.values())for(let r of n)e.has(r.name)||(e.add(r.name),t.push(r));return t}},su=class{axisName=`computedSkills`;skillNamesByPlugin=new Map;constructor(e){this.skillRegistry=e}register(e){let t=e.loaded.module.contributions?.skills;if(!t?.length||!this.skillRegistry)return;let n=this.skillNamesByPlugin.get(e.plugin.id)??[];for(let{definition:r,source:i}of mc(e.plugin.id,e.plugin.dir,t))this.skillRegistry.get(r.metadata.name)||(this.skillRegistry.register(r,i),n.push(r.metadata.name));n.length>0&&this.skillNamesByPlugin.set(e.plugin.id,n)}unregister(e){let t=this.skillNamesByPlugin.get(e);if(t){for(let e of t)this.skillRegistry?.unregister(e);this.skillNamesByPlugin.delete(e)}}unregisterAll(){for(let e of[...this.skillNamesByPlugin.keys()])this.unregister(e)}};const B=C(`@x-otto/coding:plugin-provider-loader`);function cu(e){let t=C(`wire-protocol:${e}`),n=e=>(t,...n)=>e(t,...n);return{debug:n(t.debug.bind(t)),info:n(t.info.bind(t)),warn:n(t.warn.bind(t)),error:n(t.error.bind(t))}}function V(e,t){return`${e}:${t}`}function lu(e){return new Set([...(e.contributes?.providers??[]).filter(e=>e.preserveProviderId===!0&&e.oauthRef).map(e=>e.oauthRef),...e.codeProviderIds??[]])}function uu(e,t){let n=lu(t);return new Set((t.contributes?.oauth??[]).map(t=>n.has(t.id)?t.id:V(e,t.id)))}function du(e,t){return new Set((t.contributes?.providers??[]).filter(e=>e.catalogOnly!==!0&&e.baseUrl&&e.wireApi).map(t=>t.preserveProviderId===!0?t.id:V(e,t.id)))}function fu(e,t,n){return new Set([...n.codeProviderIds??[],...(n.contributes?.providers??[]).filter(e=>e.preserveProviderId===!0).map(e=>e.id)]).has(t)?t:V(e,t)}function pu(e){return`code:${e}`}function mu(e,t,n,r,i,a,o){let s=e.id.indexOf(`/`),c=s>=0?e.id.slice(s+1):e.id;return{id:e.id,name:c,api:n,provider:t,baseUrl:r,reasoning:e.reasoning??!1,input:e.input??[`text`],cost:e.cost,contextWindow:e.contextWindow,maxOutputTokens:e.maxOutput,imageConstraints:i,supportsTools:a,strengths:e.strengths,thinkingLevels:e.thinkingLevels,thinkingMode:e.thinkingMode,responseBodyPolicy:o}}function hu(e,t,n,r,i){return(a,o)=>{let s=e.url.replace(`{baseUrl}`,r??``).replace(`{clientVersion}`,process.env.OTTO_CODEX_CLIENT_VERSION||`1.0.0`),c=e.authScheme??`bearer`,l=c===`x-api-key`||c===`auto`&&o.mode!==`oauth`?{"x-api-key":a}:{authorization:`Bearer ${a}`};return c===`auto`&&o.mode===`oauth`&&o.beta&&e.betaHeaderName&&(l[e.betaHeaderName]=o.beta),{url:s,headers:{...i,...e.headers,...l},mergeProvider:t,modelApi:n,modelIdExclude:e.modelIdExclude}}}function gu(e,t,n,r,i,a){return()=>{let o=r.get(a);if(!o)throw new Ke(`wire protocol '${a}' is not registered — is its provider plugin installed and trusted? (RFC-148)`,{code:`WIRE_PROTOCOL_NOT_REGISTERED`});return o.create({resolveAuth:()=>t.resolveAuth(n).then(e=>e??void 0),resolveBaseUrl:async()=>i,headers:e.headers,tokenDerivedHeaders:e.tokenDerivedHeaders,allowAuthHeaderOverride:e.allowAuthHeaderOverride,logger:cu(a)})}}function _u(e,t,n,r,i,a,o){let s=t.contributes?.oauth;if(s?.length&&n)if(t.capabilities?.includes(`provider`))for(let t of s){let s=r.has(t.id)?t.id:V(e,t.id);if(f.includes(t.id)||n.isReservedId(t.id)){a.rejected.push({id:t.id,reason:`oauth id collides with builtin reserved OAuth provider`}),B.warn({pluginId:e,oauthId:t.id},`plugin oauth id collides with builtin reserved, rejected (R3)`);continue}let c=t.name??i.get(t.id)??t.id,l=t.kind===`pkce`?Ri({...t,id:s,name:c,tokenExchangeEncoding:t.tokenExchangeEncoding??`form`,assumesLoopbackAlways:t.assumesLoopbackAlways??!1,subscriptionScoped:t.subscriptionScoped??!1}):Li({...t,id:s,name:c,allowCustomDomain:t.allowCustomDomain??!1});if(o?.has(s))n.replace(l,e);else if(!n.register(l,e)){a.rejected.push({id:t.id,reason:`oauth registration rejected (id already claimed by another plugin or reserved)`});continue}}else{B.warn({pluginId:e},`plugin declares contributes.oauth but not capabilities:["provider"], skipped (fail-closed)`);for(let e of s)a.rejected.push({id:e.id,reason:`capability "provider" not declared`})}}function vu(e,t,n,r,i,a){let o=t.contributes?.providers;if(!o?.length)return;if(!t.capabilities?.includes(`provider`)){B.warn({pluginId:e},`plugin declares contributes.providers but not capabilities:["provider"], skipped (fail-closed)`);for(let e of o)i.rejected.push({id:e.id,reason:`capability "provider" not declared`});return}let s=new Set;for(let t of o){if(i.registered.includes(t.id)){i.rejected.push({id:t.id,reason:`duplicate provider id in manifest`}),B.warn({pluginId:e,providerId:t.id},`duplicate provider id in manifest, second entry rejected (review F5)`);continue}if(ae(t.id)){i.rejected.push({id:t.id,reason:`reserved builtin provider id`}),B.warn({pluginId:e,providerId:t.id},`plugin provider id collides with builtin, rejected (R3)`);continue}let o=t.preserveProviderId===!0,c=o?t.id:V(e,t.id),l=o?t.id:V(e,t.id);if(t.catalogOnly===!0){let a=l;if(t.oauthRef){let n=o?t.oauthRef:V(e,t.oauthRef);if(!r?.get(n)){i.rejected.push({id:t.id,reason:`oauthRef '${t.oauthRef}' not found in current plugin's oauth table (R7)`}),B.warn({pluginId:e,providerId:t.id,oauthRef:t.oauthRef},`catalog provider oauthRef not found, rejected (R7)`);continue}a=n}if(t.envKey&&!n.authStore.registerEnvKey(l,t.envKey,e)){i.rejected.push({id:t.id,reason:`envKey registration rejected (reserved or claimed)`});continue}if(!le({id:l,name:t.name,env:t.oauthRef?void 0:t.envKey,requiresIntranet:t.requiresIntranet===!0},e)){i.rejected.push({id:t.id,reason:`provider descriptor id already claimed`}),t.envKey&&n.authStore.unregisterEnvKey(l);continue}if(t.models?.length){let r=t.models.map(e=>mu(e,a,c,t.baseUrl??``,void 0,t.supportsTools,t.responseBodyPolicy)),i=n.modelRegistry.registerWithSource(r,e);for(let t of i)B.warn({pluginId:e,modelId:t},`plugin model id collides, rejected`)}i.registered.push(t.id);continue}let u=l;if(t.oauthRef){let n=o?t.oauthRef:V(e,t.oauthRef);if(!r?.get(n)){i.rejected.push({id:t.id,reason:`oauthRef '${t.oauthRef}' not found in current plugin's oauth table (R7: cross-plugin/invalid ref rejected)`}),B.warn({pluginId:e,providerId:t.id,oauthRef:t.oauthRef},`provider oauthRef not found in current plugin oauth table, rejected (R7)`);continue}u=n,t.envKey&&B.warn({pluginId:e,providerId:t.id},`provider declares both oauthRef and envKey; ignoring envKey (R2, oauth takes priority)`)}if(t.envKey&&!t.oauthRef&&!n.authStore.registerEnvKey(l,t.envKey,e)){i.rejected.push({id:t.id,reason:`envKey registration rejected (reserved or claimed by another plugin)`});continue}let d=t.baseUrl,f=t.wireApi;if(!d||!f){i.rejected.push({id:t.id,reason:`baseUrl and wireApi required for non-catalog providers`});continue}let p=t.modelsEndpoint?hu(t.modelsEndpoint,l,c,t.baseUrl,t.headers):void 0,m=()=>{t.oauthRef&&r&&!s.has(u)&&r.unregister(u)};if(!le({id:l,name:t.name,env:t.oauthRef?void 0:t.envKey,buildModelsRequest:p,requiresIntranet:t.requiresIntranet===!0},e)){i.rejected.push({id:t.id,reason:`provider descriptor id already claimed by another plugin`}),t.envKey&&!t.oauthRef&&n.authStore.unregisterEnvKey(l),m();continue}t.allowAuthHeaderOverride&&B.warn({pluginId:e,providerId:t.id},`provider declares allowAuthHeaderOverride: custom headers may replace auth headers (RFC-270 D3)`);let h=gu(t,n.authStore,u,n.wireProtocolRegistry,d,f);if(!(a?.has(c)?n.providerRegistry.replacePluginProvider(c,h,e):n.providerRegistry.registerPluginProvider(c,h,e))){i.rejected.push({id:t.id,reason:`api already registered by another plugin or reserved`}),pe(l),t.envKey&&!t.oauthRef&&n.authStore.unregisterEnvKey(l),m();continue}if(t.models?.length){let r=t.models.map(e=>mu(e,u,c,d,t.imageConstraints,t.supportsTools,t.responseBodyPolicy)),i=n.modelRegistry.registerWithSource(r,e);for(let t of i)B.warn({pluginId:e,modelId:t},`plugin model id collides with an existing model, rejected (no silent override)`)}i.registered.push(t.id),t.oauthRef&&s.add(u)}}function yu(e,t,n,r,i){let a={registered:[],rejected:[]},o=n.authStore.oauth;return _u(e,t,o,lu(t),new Map((t.contributes?.providers??[]).filter(e=>e.oauthRef&&e.name).map(e=>[e.oauthRef,e.name])),a,r),vu(e,t,n,o,a,i),a}async function bu(e,t,n,r,i){let a=n.authStore.oauth,o=lu(t),s=t.contributes?.oauth;if(s?.length&&a)for(let t of s){let n=o.has(t.id)?t.id:V(e,t.id);r?.has(n)||a.unregister(n)}let c=t.contributes?.providers;if(c?.length){for(let t of c){let r=t.preserveProviderId===!0?t.id:V(e,t.id);pe(r),t.envKey&&!t.oauthRef&&n.authStore.unregisterEnvKey(r)}await n.providerRegistry.unregisterBySource(e,i),n.modelRegistry.unregisterBySource(e)}}var xu=class{axisName=`oauthProviderFactories`;oauthIdsByPlugin=new Map;constructor(e,t){this.authStore=e,this.logger=t}register(e){let t=e.loaded.module.oauthProviderFactories;if(!t||!this.authStore)return;if(!e.plugin.manifest.capabilities?.includes(`provider`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares oauthProviderFactories but not capabilities:["provider"], skipped (fail-closed)`);return}if(e.verdict.pendingCapabilities.includes(`provider`)){this.logger.warn({pluginId:e.plugin.id},`plugin capability "provider" not yet granted, skipping oauthProviderFactories (fail-closed)`);return}let n=new Set((e.plugin.manifest.contributes?.providers??[]).filter(e=>e.preserveProviderId===!0&&e.oauthRef).map(e=>e.oauthRef));for(let[r,i]of Object.entries(t)){let t=_c(e.plugin.id,i);if(!t)continue;let a=n.has(r)?r:V(e.plugin.id,r);if(t.id!==a){this.logger.warn({pluginId:e.plugin.id,name:r,expectedId:a,actualId:t.id},`plugin oauth provider id mismatch with manifest oauthRef/preserveProviderId, skipped`);continue}if(this.authStore.oauth.register(t,e.plugin.id)){let n=this.oauthIdsByPlugin.get(e.plugin.id)??new Set;n.add(t.id),this.oauthIdsByPlugin.set(e.plugin.id,n)}else this.logger.warn({pluginId:e.plugin.id,oauthId:t.id},`plugin oauthProviderFactory rejected (reserved or claimed)`)}}unregister(e){if(!this.authStore)return;let t=this.oauthIdsByPlugin.get(e);if(t){for(let e of t)this.authStore.oauth.unregister(e);this.oauthIdsByPlugin.delete(e)}}unregisterAll(){for(let e of[...this.oauthIdsByPlugin.keys()])this.unregister(e)}},Su=class{axisName=`providerFactories`;providerSourcePluginIds=new Set;modelSourcePluginIds=new Set;descriptorIdsByPlugin=new Map;constructor(e,t,n){this.providerRegistry=e,this.modelRegistry=t,this.logger=n}register(e){let t=e.loaded.module.providerFactories;if(!t||!this.providerRegistry)return;if(!e.plugin.manifest.capabilities?.includes(`provider`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares providerFactories but not capabilities:["provider"], skipped (fail-closed)`);return}if(e.verdict.pendingCapabilities.includes(`provider`)){this.logger.warn({pluginId:e.plugin.id},`plugin capability "provider" declared but not yet granted, skipping providerFactories (fail-closed, RFC-124 C2)`);return}let n=e.plugin.manifest.codeProviderModelsEndpoints??{},r=e.plugin.manifest.codeProviderModels??{};for(let[i,a]of Object.entries(t)){let t=fu(e.plugin.id,i,e.plugin.manifest);if(!this.providerRegistry.registerPluginProvider(t,gc(e.plugin.id,a),pu(e.plugin.id))){this.logger.warn({pluginId:e.plugin.id,api:t},`plugin providerFactory rejected (reserved builtin or claimed by another plugin)`);continue}this.providerSourcePluginIds.add(e.plugin.id);let o=n[i];if(o)if(le({id:t,buildModelsRequest:hu(o,t,t)},pu(e.plugin.id))){let n=this.descriptorIdsByPlugin.get(e.plugin.id)??new Set;n.add(t),this.descriptorIdsByPlugin.set(e.plugin.id,n)}else this.logger.warn({pluginId:e.plugin.id,api:t},`plugin codeProviderModelsEndpoints descriptor rejected (reserved builtin or claimed by another plugin)`);let s=r[i];if(s?.models?.length&&this.modelRegistry){let n=s.models.map(e=>mu(e,t,t,s.baseUrl,s.imageConstraints,s.supportsTools,s.responseBodyPolicy)),r=this.modelRegistry.registerWithSource(n,e.plugin.id);this.modelSourcePluginIds.add(e.plugin.id),r.length>0&&this.logger.warn({pluginId:e.plugin.id,rejectedModelIds:r},`plugin codeProviderModels contains model ids already claimed by another source, rejected`)}}}async unregister(e){this.providerRegistry&&this.providerSourcePluginIds.has(e)&&(await this.providerRegistry.unregisterBySource(pu(e)),this.providerSourcePluginIds.delete(e)),this.modelRegistry&&this.modelSourcePluginIds.has(e)&&(this.modelRegistry.unregisterBySource(e),this.modelSourcePluginIds.delete(e));let t=this.descriptorIdsByPlugin.get(e);if(t){for(let e of t)pe(e);this.descriptorIdsByPlugin.delete(e)}}async unregisterAll(){let e=new Set([...this.providerSourcePluginIds,...this.modelSourcePluginIds,...this.descriptorIdsByPlugin.keys()]);for(let t of e)await this.unregister(t)}},Cu=class{axisName=`wireProtocols`;wireProtocolSourcePluginIds=new Set;cacheReportingApisByPlugin=new Map;constructor(e,t){this.wireProtocolRegistry=e,this.logger=t}register(e){let t=e.loaded.module.wireProtocols;if(!(!t||!this.wireProtocolRegistry)){if(!e.plugin.manifest.capabilities?.includes(`wire-protocol`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares wireProtocols but not capabilities:["wire-protocol"], skipped (fail-closed)`);return}if(e.verdict.pendingCapabilities.includes(`wire-protocol`)){this.logger.warn({pluginId:e.plugin.id},`plugin capability "wire-protocol" declared but not yet granted, skipping wireProtocols (fail-closed, RFC-124 C2 pattern)`);return}for(let[n,r]of Object.entries(t))if(this.wireProtocolRegistry.register(n,r,e.plugin.id)){if(this.wireProtocolSourcePluginIds.add(e.plugin.id),r.meta?.reportsCacheTokens){ce(n);let t=this.cacheReportingApisByPlugin.get(e.plugin.id)??new Set;t.add(n),this.cacheReportingApisByPlugin.set(e.plugin.id,t)}}else this.logger.warn({pluginId:e.plugin.id,wireApi:n},`plugin wireProtocol rejected (already registered by another plugin, first-win)`)}}unregister(e){this.wireProtocolRegistry&&this.wireProtocolSourcePluginIds.has(e)&&(this.wireProtocolRegistry.unregisterBySource(e),this.wireProtocolSourcePluginIds.delete(e));let t=this.cacheReportingApisByPlugin.get(e);if(t){for(let e of t)fe(e);this.cacheReportingApisByPlugin.delete(e)}}unregisterAll(){let e=new Set([...this.wireProtocolSourcePluginIds,...this.cacheReportingApisByPlugin.keys()]);for(let t of e)this.unregister(t)}},wu=class{axisName=`tools`;toolSourcePluginIds=new Set;constructor(e,t){this.toolRegistry=e,this.logger=t}register(e){let t=e.loaded.module.tools;if(!t?.length||!this.toolRegistry)return;if(!e.plugin.manifest.capabilities?.includes(`tools`)){this.logger.warn({pluginId:e.plugin.id},`plugin declares tools but not capabilities:["tools"], skipped (fail-closed)`);return}if(e.verdict.pendingCapabilities.includes(`tools`)){this.logger.warn({pluginId:e.plugin.id},`plugin capability "tools" declared but not yet granted, skipping tools (fail-closed, RFC-124 C2)`);return}let n=this.toolRegistry,r={workspaceDir:e.workspaceDir,logger:{info:t=>this.logger.info({pluginId:e.plugin.id},t),warn:t=>this.logger.warn({pluginId:e.plugin.id},t),error:t=>this.logger.error({pluginId:e.plugin.id},t)},host:e.host,storage:e.storage},i=t.map(t=>yc(e.plugin.id,t,r)).filter(e=>e!==null).filter(t=>n.has(t.name)?(this.logger.warn({pluginId:e.plugin.id,tool:t.name},`plugin tool name collides with an existing tool, rejected (R3, no silent override)`),!1):!0);i.length>0&&(n.register(i,{preset:`full`,source:e.plugin.id}),this.toolSourcePluginIds.add(e.plugin.id))}unregister(e){!this.toolRegistry||!this.toolSourcePluginIds.has(e)||(this.toolRegistry.unregisterBySource(e),this.toolSourcePluginIds.delete(e))}unregisterAll(){for(let e of[...this.toolSourcePluginIds])this.unregister(e)}};const Tu=`[plugin]`;function Eu(e,t,n){let r=n.name?.trim()||n.key;return`${Tu} ${e}:${t}:${n.key} — ${r}`}function Du(e,t,n){let r=e.subscriber;return!r||r.kind!==`plugin-service`||r.pluginId!==t||r.serviceId!==n?!1:e.name.startsWith(Tu)}function Ou(e,t,n){let r=`${Tu} ${t}:${n}:`;if(!e.name.startsWith(r))return;let i=e.name.slice(r.length),a=i.indexOf(` — `);if(!(a<=0))return i.slice(0,a)}function ku(e){let{port:t,logger:n,pluginId:r,serviceId:i}=e,a={added:0,updated:0,removed:0},o=new Map;for(let t of e.declared){let e=t?.key?.trim(),a=t?.cron?.trim();if(!e||!a){n.warn({pluginId:r,serviceId:i,key:t?.key},`plugin schedule subscription missing key or cron, skipped (RFC-327 D2)`);continue}if(o.has(e)){n.warn({pluginId:r,serviceId:i,key:e},`duplicate plugin schedule subscription key, later declaration ignored`);continue}o.set(e,{...t,key:e,cron:a})}let s=new Map;for(let e of t.list()){if(!Du(e,r,i))continue;let t=Ou(e,r,i);t!==void 0&&s.set(t,e)}for(let[e,c]of o){let o=Eu(r,i,c),l=s.get(e);if(!l){try{t.add({name:o,prompt:`plugin service subscription (${r}:${i}:${e})`,cronExpression:c.cron,recurring:!0,origin:`user`,subscriber:{kind:`plugin-service`,pluginId:r,serviceId:i}}),a.added+=1}catch(t){n.warn({pluginId:r,serviceId:i,key:e,err:t instanceof Error?t.message:String(t)},`failed to register plugin schedule subscription`)}continue}(l.cronExpression!==c.cron||l.name!==o)&&t.update(l.id,{cronExpression:c.cron,name:o})&&(a.updated+=1)}for(let[e,n]of s)o.has(e)||t.remove(n.id)&&(a.removed+=1);return a}function Au(e){let{port:t,pluginId:n}=e,r=0;for(let e of t.list()){let i=e.subscriber;!i||i.kind!==`plugin-service`||i.pluginId!==n||e.name.startsWith(Tu)&&t.remove(e.id)&&(r+=1)}return r}var ju=class{axisName=`services`;startedByPlugin=new Map;scheduleDeclarations=new Map;constructor(e){this.deps=e}async register(e){let t=e.loaded.module.services;if(!t?.length)return;if(!e.plugin.manifest.capabilities?.includes(`service`)){this.deps.logger.warn({pluginId:e.plugin.id},`plugin declares services but not capabilities:["service"], skipped (fail-closed, RFC-287 D-M3-1)`);return}if(e.verdict.pendingCapabilities.includes(`service`)){this.deps.logger.warn({pluginId:e.plugin.id},`plugin capability "service" declared but not yet granted, skipping services (fail-closed)`);return}let n=e.loaded.compiledPath;if(!n){this.deps.logger.warn({pluginId:e.plugin.id},`plugin declares services but has no compiled entry path; services need a compiled module to run in the service worker (skipped)`);return}let r=this.startedByPlugin.get(e.plugin.id)??[];for(let i of t){if(!i?.id)continue;let t=this.deps.getWorkspaceKey(),a=this.deps.hasStorageCapability(e.plugin.id),{error:o}=await this.deps.pool.start({pluginId:e.plugin.id,serviceId:i.id,compiledPath:n,workspaceDir:this.deps.workspaceDir,workspaceKey:t,factoryCtx:{pluginId:e.plugin.id,pluginDir:e.plugin.dir,workspaceDir:this.deps.workspaceDir},hostCapabilities:this.deps.hostCapabilitiesFor(e.plugin.id),storageDir:a?this.deps.storageDirFor(e.plugin.id,t):``,hasStorageCapability:a,bridge:this.deps.bridgeFor(e.plugin.id)});o&&this.deps.logger.warn({pluginId:e.plugin.id,serviceId:i.id,err:o},`plugin service failed to start`),r.push(i.id),this.scheduleDeclarations.set(`${e.plugin.id}:${i.id}`,i.schedules??[]);let s=this.deps.getSchedulePort?.();if(i.schedules?.length){if(!s)this.deps.logger.debug({pluginId:e.plugin.id,serviceId:i.id,count:i.schedules.length},`plugin declares schedule subscriptions but no scheduler in this process, skipped (RFC-327 D2 boundary)`);else if(!o){let t=ku({port:s,logger:this.deps.logger,pluginId:e.plugin.id,serviceId:i.id,declared:i.schedules});(t.added||t.updated||t.removed)&&this.deps.logger.info({pluginId:e.plugin.id,serviceId:i.id,...t},`plugin schedule subscriptions reconciled`)}}else s&&ku({port:s,logger:this.deps.logger,pluginId:e.plugin.id,serviceId:i.id,declared:[]})}r.length>0&&this.startedByPlugin.set(e.plugin.id,r)}async unregister(e){if(!this.startedByPlugin.has(e))return;this.startedByPlugin.delete(e);for(let t of[...this.scheduleDeclarations.keys()])t.startsWith(`${e}:`)&&this.scheduleDeclarations.delete(t);let t=this.deps.getSchedulePort?.();if(t){let n=Au({port:t,pluginId:e});n>0&&this.deps.logger.info({pluginId:e,removed:n},`plugin schedule subscriptions revoked`)}await this.deps.pool.stopPlugin(e)}async unregisterAll(){for(let e of[...this.startedByPlugin.keys()])await this.unregister(e)}reconcileAllSchedules(){let e=this.deps.getSchedulePort?.();if(e)for(let[t,n]of this.startedByPlugin)for(let r of n){let n=this.scheduleDeclarations.get(`${t}:${r}`);if(n===void 0)continue;let i=ku({port:e,logger:this.deps.logger,pluginId:t,serviceId:r,declared:n});(i.added||i.updated||i.removed)&&this.deps.logger.info({pluginId:t,serviceId:r,...i,source:`scheduler-ready reconcile`},`plugin schedule subscriptions reconciled (M3 scheduler-ready)`)}}};const Mu=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Nu=x(n,`plugin-state`);function Pu(e){let t=Fu(e);try{return Xr(t,{recursive:!0,force:!0}),{removed:!D(t),dir:t}}catch{return{removed:!1,dir:t}}}function Fu(e){if(!Mu.test(e))throw Error(`invalid pluginId for scoped storage: ${e} (must be kebab-case)`);return x(Nu,e)}var Iu=class{persistence;baseDir;pluginId;workspaceKey;constructor(e,t){if(this.pluginId=e,this.workspaceKey=t,!Mu.test(e))throw Error(`invalid pluginId for scoped storage: ${e} (must be kebab-case)`);if(typeof t!=`string`||t.length===0||t.includes(`/`)||t.includes(`\\`)||t.includes(`..`))throw Error(`invalid workspaceKey for scoped storage: ${t}`);if(s()){this.baseDir=`:memory:/plugin-state/${e}/${t}`,this.persistence=sn({type:`memory`});return}let n=S(x(Fu(e),t));O(n,{recursive:!0});let r=Jr(n),i=Jr(Nu);if(r!==i&&!r.startsWith(i+`/`))throw Error(`scoped storage path escapes plugin-state root: ${r}`);this.baseDir=n,this.persistence=sn({type:`file`,baseDir:n})}async save(e,t){await this.persistence.save({id:e,data:t,version:1,metadata:{}})}async load(e){let t=await this.persistence.load(e);return t?t.data:null}delete(e){return this.persistence.delete(e)}list(){return this.persistence.list()}};function Lu(e){let t=new Set([...e.manifest.codeProviderIds??[],...(e.manifest.contributes?.providers??[]).filter(e=>e.preserveProviderId===!0).map(e=>e.id)]),n=`${e.id}:`;return e=>t.has(e)||e.startsWith(n)}function Ru(e,t,n){let r=e.manifest.capabilities??[],i={},a=!1,o=n.startPluginJob;r.includes(`agent.dispatch`)&&!t.pendingCapabilities.includes(`agent.dispatch`)&&o?(i.startJob=async t=>{let r=n.getSessionId?.();if(!r)throw Error(`agent.dispatch unavailable: no active session to attach the job to`);return{jobId:o({pluginId:e.id,title:t.title,prompt:t.prompt,sessionId:r}).id}},a=!0):r.includes(`agent.dispatch`)&&n.logger.warn({pluginId:e.id,pending:t.pendingCapabilities.includes(`agent.dispatch`)},`plugin declares agent.dispatch but it is not available (not yet granted, or host provides no job dispatcher) — skipping (fail-closed, RFC-287 D2)`);let s=n.getSessionMessages,c=Bu(n);r.includes(`session.read`)&&!t.pendingCapabilities.includes(`session.read`)&&s?(i.readTranscript=async t=>{if(!c.isSessionAuthorized(e.id,t.sessionId))throw Error(`session not authorized for this plugin`);let n=s(t.sessionId);if(!n)throw Error(`session not found`);if(!c.tryConsumeRead(e.id))throw Error(`readTranscript quota exceeded for this notification`);return Sl(n,t.sinceIndex??0,500)},a=!0):r.includes(`session.read`)&&n.logger.warn({pluginId:e.id,pending:t.pendingCapabilities.includes(`session.read`)},`plugin declares session.read but it is not available (not yet granted, or host provides no transcript source) — skipping (fail-closed, RFC-318 D2)`);let l=n.completeText;r.includes(`llm.complete`)&&!t.pendingCapabilities.includes(`llm.complete`)&&l?(i.complete=async t=>{if(t.prompt.length>32e3)throw Error(`prompt exceeds 32000 chars limit`);let n=c.tryConsumeLlm(e.id);if(!n.ok)throw Error(`llm.complete quota exceeded (${n.reason})`);let r=Math.min(t.maxTokens??2048,2048);return l(t.prompt,{maxTokens:r})},a=!0):r.includes(`llm.complete`)&&n.logger.warn({pluginId:e.id,pending:t.pendingCapabilities.includes(`llm.complete`)},`plugin declares llm.complete but it is not available (not yet granted, or host provides no model caller) — skipping (fail-closed, RFC-318 D2)`);let u=n.askUser;r.includes(`user.ask`)&&!t.pendingCapabilities.includes(`user.ask`)&&u?(i.ask=async t=>u(e.id,{header:String(t.header??``),question:String(t.question??``),background:String(t.background??``),recommendation:String(t.recommendation??``),...Array.isArray(t.options)?{options:t.options}:{},...t.allowFreeform===void 0?{}:{allowFreeform:!!t.allowFreeform},...t.multiSelect===void 0?{}:{multiSelect:!!t.multiSelect},...Array.isArray(t.evidence)?{evidence:t.evidence.map(String)}:{}}),a=!0):r.includes(`user.ask`)&&n.logger.warn({pluginId:e.id,pending:t.pendingCapabilities.includes(`user.ask`)},`plugin declares user.ask but it is not available (not yet granted, or host provides no UI sink) — skipping (fail-closed, RFC-344 M3)`);let d=n.notifyUser;return r.includes(`user.notify`)&&!t.pendingCapabilities.includes(`user.notify`)&&d?(i.notify=async t=>{if(!c.tryConsumeNotify(e.id)){n.logger.debug({pluginId:e.id,code:t.code},`plugin user.notify dropped: rate limit exceeded (silent by design, RFC-327 D3)`);return}let r=t.message.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,` `).slice(0,500);d({pluginId:e.id,level:t.level,code:t.code.slice(0,120),message:r})},a=!0):r.includes(`user.notify`)&&n.logger.warn({pluginId:e.id,pending:t.pendingCapabilities.includes(`user.notify`)},`plugin declares user.notify but it is not available (not yet granted, or host provides no UI sink) — skipping (fail-closed, RFC-327 D3)`),a?i:void 0}const zu=new WeakMap;function Bu(e){if(e.capabilityQuota)return e.capabilityQuota;let t=zu.get(e);return t||(t=new Ec,zu.set(e,t)),t}const Vu=new Map([[`oauthProviderFactories`,`provider`],[`providerFactories`,`provider`],[`wireProtocols`,`wire-protocol`]]);function Hu(e){let t=e.manifest.contributes;return!t||typeof t!=`object`?[]:Object.keys(t)}var Uu=class e{contributesSnapshot=new Map;static DEACTIVATE_TIMEOUT_MS=5e3;hooksAxis;monitorsAxis;feedbackAxis;sigilAxis;computedCommandsAxis;computedAgentsAxis;computedSkillsAxis;oauthProviderAxis;codeProviderAxis;wireProtocolAxis;toolsAxis;servicesAxis;axisHandlers;firedEvents=new Set;deferredIds=new Set;dirtyPluginIds=new Set;loadedModules=new Map;constructor(e){this.deps=e,this.hooksAxis=new Jl(e.hookRegistry),this.monitorsAxis=new Yl(e.hookRegistry,e.logger),this.feedbackAxis=new Xl(e.feedbackRegistry,e.logger),this.sigilAxis=new iu(e.sigilResolverRegistry,e.pluginInput,e.logger),this.computedCommandsAxis=new au,this.computedAgentsAxis=new ou,this.computedSkillsAxis=new su(e.skillRegistry),this.oauthProviderAxis=new xu(e.authStore,e.logger),this.codeProviderAxis=new Su(e.providerRegistry,e.modelRegistry,e.logger),this.wireProtocolAxis=new Cu(e.wireProtocolRegistry,e.logger),this.toolsAxis=new wu(e.toolRegistry,e.logger),this.servicesAxis=new ju({pool:e.servicePool??gl(),logger:e.logger,workspaceDir:e.workspaceDir,getWorkspaceKey:()=>e.getWorkspaceKey?.()??`default`,bridgeFor:t=>{let n=e.activePlugins().find(e=>e.id===t);if(!n)return{};let r=Ru(n,E(n),e);if(!r)return{};let i={};return r.startJob&&(i.startJob=r.startJob),r.readTranscript&&(i.readTranscript=r.readTranscript),r.complete&&(i.complete=r.complete),r.notify&&(i.notify=r.notify),i},hostCapabilitiesFor:t=>{let n=e.activePlugins().find(e=>e.id===t);if(!n)return[];let r=Ru(n,E(n),e);if(!r)return[];let i=[];return r.startJob&&i.push(`startJob`),r.readTranscript&&i.push(`readTranscript`),r.complete&&i.push(`complete`),r.notify&&i.push(`notify`),i},storageDirFor:(e,t)=>new Iu(e,t).baseDir,hasStorageCapability:t=>!!e.activePlugins().find(e=>e.id===t)?.manifest.capabilities?.includes(`storage`),...e.getSchedulePort?{getSchedulePort:e.getSchedulePort}:{}}),this.axisHandlers=[this.hooksAxis,this.monitorsAxis,this.feedbackAxis,this.sigilAxis,this.computedCommandsAxis,this.computedAgentsAxis,this.computedSkillsAxis,this.oauthProviderAxis,this.codeProviderAxis,this.wireProtocolAxis,this.toolsAxis,this.servicesAxis]}get deferredPluginIds(){return this.deferredIds}emitMonitorEvent(e){return this.monitorsAxis.dispatch(e)}reconcileServiceSchedules(){this.servicesAxis.reconcileAllSchedules()}get monitorPluginIds(){return this.monitorsAxis.monitorPluginIds}async activateOn(e,t){return this.firedEvents.add(e),this.reload(t)}get commands(){return this.computedCommandsAxis.getComputedCommands()}async callOnDeactivate(t,n){let r;try{await Promise.race([n(),new Promise((n,i)=>{r=setTimeout(()=>{i(Error(`plugin "${t}" onDeactivate timed out after ${e.DEACTIVATE_TIMEOUT_MS}ms`))},e.DEACTIVATE_TIMEOUT_MS),r.unref?.()})])}catch(e){this.deps.logger.warn({pluginId:t,err:String(e)},`plugin onDeactivate failed or timed out`)}finally{r!==void 0&&clearTimeout(r)}}async unregisterAllAxes(){for(let e of this.axisHandlers)await e.unregisterAll()}async unregisterPluginAxes(e,t,n){let r=[],i=t?E(t):void 0;for(let n of this.axisHandlers){let a=Vu.get(n.axisName);if(!(a!==void 0&&t!==void 0&&i!==void 0&&t.manifest.capabilities?.some(e=>e===a)&&!i.gated&&!i.pendingCapabilities.includes(a)))try{await n.unregister(e)}catch(t){r.push(n.axisName),this.deps.logger.warn({pluginId:e,axis:n.axisName,err:t instanceof Error?t.message:String(t)},`plugin axis unregister failed (continuing with remaining axes; plugin marked dirty for full reload next round)`)}}Bu(this.deps).reset(e),r.length>0&&(this.dirtyPluginIds.add(e),n?.add(e),this.deps.logger.warn({pluginId:e,failedAxes:r},`plugin marked dirty due to axis unregister failures; next reload will force a full reinstall of this plugin`))}pluginSignature(e){let t=E(e),n=`${t.gated?`gated`:`ok`}:${[...t.pendingCapabilities].sort().join(`,`)}`,r=`nofile`;for(let t of[`plugin.ts`,`plugin.tsx`])try{let n=Zr(x(e.dir,t));r=`${t}:${n.mtimeMs}:${n.size}`;break}catch{}return`${JSON.stringify(e.manifest)}|${n}|${r}`}async reload(e){let t=this.deps.activePlugins(),n=new Map(t.map(e=>[e.id,e])),r=new Map(t.map(e=>[e.id,this.pluginSignature(e)])),i=[],a=new Set,o=new Set;for(let[e,t]of this.loadedModules)n.get(e)?(r.get(e)!==t.signature||this.dirtyPluginIds.has(e))&&(t.module.module.onDeactivate&&i.push({pluginId:e,onDeactivate:t.module.module.onDeactivate}),o.add(e)):(t.module.module.onDeactivate&&i.push({pluginId:e,onDeactivate:t.module.module.onDeactivate}),a.add(e));for(let{pluginId:e,onDeactivate:t}of i)await this.callOnDeactivate(e,t);let s=new Set;for(let e of a)await this.unregisterPluginAxes(e,void 0,s),this.loadedModules.delete(e);for(let e of o)await this.unregisterPluginAxes(e,n.get(e),s);this.computedAgentsAxis.setExistingAgentNames(e);let c=new Set;for(let e of this.deps.activePlugins()){if(!ql(ir(e.manifest),this.firedEvents)){c.add(e.id);continue}if(this.loadedModules.get(e.id)&&!o.has(e.id))continue;let t={pluginId:e.id,pluginDir:e.dir,workspaceDir:this.deps.workspaceDir,callMcpTool:(e,t,n)=>this.deps.callMcpTool(e,t,n),logger:{debug:t=>{this.deps.logger.debug({pluginId:e.id},t)},info:t=>{this.deps.logger.info({pluginId:e.id},t),sc(e.id,`info`,t)},warn:t=>{this.deps.logger.warn({pluginId:e.id},t),sc(e.id,`warn`,t)},error:t=>{this.deps.logger.error({pluginId:e.id},t),sc(e.id,`error`,t)}},getWireProtocol:e=>this.deps.wireProtocolRegistry?.get(e),resolveProviderCredential:(()=>{let t=Lu(e);return e=>t(e)?this.deps.providerRegistry?.resolveAccessKey(e)??Promise.resolve(null):Promise.resolve(null)})(),resolveProviderAuth:(()=>{let t=Lu(e);return e=>t(e)?this.deps.providerRegistry?.resolveAuth(e)??Promise.resolve(null):Promise.resolve(null)})(),host:Ru(e,E(e),this.deps),listActivePlugins:()=>this.deps.activePlugins().map(e=>({id:e.id,version:e.manifest.version,capabilities:e.manifest.capabilities??[],contributes:this.contributesSnapshot.get(e.id)??Hu(e)}))},n=this.deps.useIsolatedLoading!==!1&&Wl(e)?await Kl(e,t,void 0,this.deps.onPluginLoadError):await sl(e,t,this.deps.onPluginLoadError);if(!n)continue;let i=E(e);if(i.gated){this.deps.logger.warn({pluginId:e.id},`project plugin not trusted, skipping code axes (fail-closed, RFC-124 C1)`);continue}let a;if(e.manifest.capabilities?.includes(`storage`))try{let t=this.deps.getWorkspaceKey?.()??Si;a=new Iu(e.id,t)}catch(t){this.deps.logger.warn({pluginId:e.id,err:String(t)},`failed to construct scoped storage for plugin, storage capability unavailable`)}let l={plugin:e,verdict:i,loaded:n,host:Ru(e,i,this.deps),workspaceDir:this.deps.workspaceDir,storage:a};for(let e of this.axisHandlers)await e.register(l);if(n.module.onActivate)try{await n.module.onActivate()}catch(t){this.deps.logger.warn({pluginId:e.id,err:String(t)},`plugin onActivate threw`)}this.contributesSnapshot.set(e.id,Hu(e)),this.loadedModules.set(e.id,{module:n,manifest:e.manifest,signature:r.get(e.id)??this.pluginSignature(e)}),s.has(e.id)||this.dirtyPluginIds.delete(e.id)}return this.deferredIds=c,this.computedAgentsAxis.getAppendedAgents()}async cleanup(){for(let[e,t]of this.loadedModules)t.module.module.onDeactivate&&await this.callOnDeactivate(e,t.module.module.onDeactivate);this.loadedModules.clear(),await this.unregisterAllAxes();let e=Bu(this.deps);for(let t of this.deps.activePlugins())e.reset(t.id);this.firedEvents.clear()}};const Wu=C(`@x-otto/coding:panel-compiler`);function Gu(e){let t=x(e,`panels`);if(!D(t))return{compiled:[],errors:[],skipped:!0};let n;try{n=Kr(t).filter(e=>e.endsWith(`.tsx`))}catch{return{compiled:[],errors:[],skipped:!0}}if(n.length===0)return{compiled:[],errors:[],skipped:!0};let r=x(e,`panels-dist`);O(r,{recursive:!0});let i=Wr(x(Be(),`otto-panel-shims-`)),a=x(i,`react-shim.js`),o=x(i,`ink-shim.js`),s=x(i,`tui-shim.js`);A(a,`const R = globalThis.React
|
|
368
368
|
if (!R) throw new Error('otto panel: globalThis.React 未注入(TUI 须在加载面板前 import panel-globals)')
|
|
369
369
|
export default R
|
|
370
370
|
export const useState = R.useState, useEffect = R.useEffect, useCallback = R.useCallback,
|
|
@@ -500,7 +500,7 @@ If the recorded paths turn out to be too varied, too thin, or not actually the s
|
|
|
500
500
|
library permanently; skipping costs nothing — otto will offer again if the pattern recurs.
|
|
501
501
|
|
|
502
502
|
The draft you produce is a proposal: it will be reviewed as a diff and only takes effect if the
|
|
503
|
-
user explicitly applies it.`}function hy(e){return`Draft skill: ${e.taskSignature.length>60?`${e.taskSignature.slice(0,60)}…`:e.taskSignature}`}function gy(e){try{let t=fy({pluginId:e.pluginId,workspaceKey:e.workspaceKey,sessionIds:e.brief.sessionIds});return{jobId:e.startJob({title:hy(e.brief),prompt:my(e.brief,t),sessionId:e.sessionId}).id}}catch(t){e.logger?.warn(`skill-loop: failed to start skill draft job: ${t instanceof Error?t.message:String(t)}`);return}}function _y(e){e.hookRegistry.register(df(e.toolRegistry,e.getDefaultToolPreset)),e.hookRegistry.register(we(e.failureSignals)),e.hookRegistry.register(Ee(e.failureSignals)),e.hookRegistry.registerAll(e.contextSourcesBuildHooks(e.workspaceDir,e.memory)),e.memory&&e.hookRegistry.registerAll(Dt(e.memory)),e.hookRegistry.registerAll(At({getTodoList:t=>e.getSession(t)?.session.getTodoList()}));let t=/-milestone\.md$/,n=/^Status:\s*Done\b/m;e.hookRegistry.registerAll(Et({isDocSyncTrigger:e=>{let r=typeof e.args.path==`string`?e.args.path:``;if(!t.test(r))return!1;let i=typeof e.args.newContent==`string`?e.args.newContent:typeof e.args.content==`string`?e.args.content:``;return n.test(i)}})),e.hookRegistry.registerAll(bf(e.learningStore,e.promptManager,e.localLearningStore)),e.skillRegistry&&e.hookRegistry.registerAll(xf(e.skillRegistry)),e.hookRegistry.registerAll(pr({workspaceDir:e.workspaceDir})),e.hookRegistry.registerAll(wf()),e.hookRegistry.on(`session.deleted`,`rfc047-notification-detach`,t=>e.notificationDispatcher.detach(t.sessionId));let r=iy();e.hookRegistry.registerAll(r.hooks),e.hookRegistry.register(Tf(e=>{w.killAllForSession(e)})),e.hookRegistry.registerAll(Ef({registry:e.permissionRegistry,getPersistedAllow:t=>e.codingSessionPool.getSessionPermissionAllow(t)})),e.hookRegistry.register(ny({getContext:()=>{let t=je(e.workspaceDir,ze());if(!e.sandbox.enabled)return{mode:`bypass`,projectRoot:e.workspaceDir,writableRoots:[],deniedRoots:t,networkAllowed:!0};let n=e.settings.get(`permission_mode`)??`auto`;return{mode:n,projectRoot:e.workspaceDir,writableRoots:be(n,e.workspaceDir,Be(),e.sandbox.writablePaths),deniedRoots:t,networkAllowed:e.sandbox.isNetworkAllowed,autoAllowBashIfSandboxed:e.sandbox.autoAllowBashIfSandboxed}}})),e.hookRegistry.registerAll(Of(t=>e.getSession(t),e.memoryAutoExtractor,{isEnabled:()=>e.settings.get(`memory_auto_extract`)?.enabled===!0||process.env.OTTO_MEMORY_AUTO_EXTRACT===`1`}));let i=()=>e.settings.get(`skill_loop`)?.enabled===!0||process.env.OTTO_SKILL_LOOP===`1`;return e.hookRegistry.registerAll(kf({isEnabled:i})),e.hookRegistry.registerAll(ey({isEnabled:i,getMinMessages:()=>e.settings.get(`skill_loop`)?.min_messages,getCooldownDays:()=>e.settings.get(`skill_loop`)?.dismiss_cooldown_days,notifyServices:e.notifyPluginServices,getWorkspaceKey:e.getWorkspaceKey,getRequestGrill:t=>{let n=e.getSession(t);return n?e=>n.requestGrill({...e,askedBy:`skill-loop`}):void 0},onAccepted:({sessionId:t,brief:n})=>{gy({startJob:t=>e.startSkillDraftJob({...t,origin:`user`}),brief:n,sessionId:t,pluginId:Zv,workspaceKey:e.getWorkspaceKey()??Qv,logger:{warn:t=>e.logger.warn(t)}})},logger:e.logger})),e.hookRegistry.register(Se({getOnFileEdited:e.getEditFileCallback,dedupCache:e.editFilesDedup})),{agentJobNotify:r.notify}}function vy(e,t,n,r){return lf({processOwnerId:e.processOwnerId,orchestrator:e.orchestrator,writeTodos:e.writeTodos,sandbox:t=>e.sandbox.isBypassed(t?.command)?void 0:e.sandbox.current??void 0,autoMemory:e.storage.autoMemory,reloadMemory:e.storage.memory?()=>e.storage.memory.loadMemory():void 0,archiveRecall:e.storage.memory,runTeam:e.runTeam,runSession:e.runSession,fileStateManager:e.fileStateManager,learningStore:e.learningStore,localLearningStore:e.localLearningStore,sessions:{list:()=>e.listSessions(),create:()=>e.createSession(),remove:t=>e.removeSession(t),get:t=>e.getSession(t)},listModels:t=>e.buildModelCatalog(t),startJob:t=>({jobId:e.agentJobs.start({...t,origin:`main`}).id}),getScheduleService:()=>e.scheduleServiceInstance,searchEcosystem:e.searchEcosystem},t,n,r)}function yy(e,t){return Ie(t,uf(vy(e,t,e.skillRegistry?un(e.skillRegistry,t):void 0,!1))).getAvailable(e.defaultToolPreset)}function by(e){return e.toolRegistry.getAvailable(e.defaultToolPreset).filter(e=>e.name.startsWith(`mcp__`))}function xy(e,t){let n=t.skillProvider??(e.skillRegistry?un(e.skillRegistry,e.workspaceDir):void 0);t.sandbox&&e.sandbox.pin(t.sandbox);let r={registerChild(e,t){return{pid:Vt.registerChild(e,t).pid??0}}};return Ie(e.workspaceDir,{...uf(vy(e,e.workspaceDir,n,t.lsp===!0)),processTracker:r})}function Sy(e){e.agentJobNotify=_y({hookRegistry:e.hookRegistry,toolRegistry:e.toolRegistry,getDefaultToolPreset:()=>e.defaultToolPreset,failureSignals:e.failureSignals,contextSourcesBuildHooks:(t,n)=>e.agentRuntime.contextSources.sealAndBuildHooks(t,n),workspaceDir:e.workspaceDir,memory:e.storage.memory,learningStore:e.learningStore,localLearningStore:e.localLearningStore,promptManager:e.promptManager,skillRegistry:e.skillRegistry,notificationDispatcher:e.notificationDispatcher,permissionRegistry:e.permissionRegistry,codingSessionPool:e.codingSessionPool,sandbox:e.sandbox,settings:e.settings,getEditFileCallback:()=>e.editFileCallback,editFilesDedup:e._editFilesDedup,memoryAutoExtractor:e.memoryAutoExtractor,getSession:t=>e.getSession(t),notifyPluginServices:t=>e.notifyPluginServices(t),getWorkspaceKey:()=>e.workspaceRef?.key,startSkillDraftJob:t=>e.agentJobs.start(t),logger:e.logger}).agentJobNotify}function Cy(e){return{async readFile(e){try{return await Mi(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}},async writeFile(e,t){await Ai(b(e),{recursive:!0}),await tn(e,t)},async writeFileExclusive(e,t){await Ai(b(e),{recursive:!0});try{let n=await ji(e,`wx`);try{await n.writeFile(t,`utf8`)}finally{await n.close()}return!0}catch(e){if(e.code===`EEXIST`)return!1;throw e}},genId:e?.genId??wi,now:e?.now??(()=>new Date().toISOString()),...e?.confirmTrust?{confirmTrust:e.confirmTrust}:{}}}async function wy(e){if(e.ensureNotDisposed(),await e.ensureSettingsLoaded(),!e.workspaceRef&&!e.pendingWorkspaceInit&&!e.parentWorkspaceExisted)try{let t=Ci(Cy()),n=e._workspaceId?{id:e._workspaceId}:void 0,r=await t.resolveLocal(e.workspaceDir,{...n,autoCreate:!(e._interactive&&!n)});`kind`in r&&r.kind===`uninitialized`?e.pendingWorkspaceInit={root:r.root}:`kind`in r&&r.kind===`parentWorkspaceExisted`?e.parentWorkspaceExisted={parentRoot:r.parentRoot,currentRoot:r.currentRoot,marker:r.marker}:e.workspaceRef=r}catch(t){e.logger.warn({err:t,workspaceDir:e.workspaceDir},`Workspace resolution failed; continuing without workspace identity. Sessions previously saved under a workspace key will not be restored.`)}e.storage.autoMemory&&await e.storage.autoMemory.load(),await tt(`skills/agents/teams discovery + plugin module load`,async()=>{if(e.skillRegistry){await e.skillRegistry.discover();for(let t of e.settings.get(`disabled_skills`)??[])e.skillRegistry.disable(t);let t=new Set(e.settings.get(`disabled_plugins`)??[]);if(t.size>0)for(let[n,r]of e.skillRegistry.getAll())r.source?.type===`plugin`&&r.source.id&&t.has(r.source.id)&&e.skillRegistry.disable(n)}e.declarativeAgentProfiles=await Ks(e.workspaceDir,{plugins:e.activePlugins()}),e.declarativeTeams=await Qs(e.workspaceDir);let t=await e.pluginModuleManager.reload(new Set(e.declarativeAgentProfiles.map(e=>e.name)));e.declarativeAgentProfiles.push(...t),e._pendingProviderCapabilities=(await e.pluginProviderManager.reload()).pendingCapabilityPluginIds,await e.diagnoseTopoSortIssues()});let t=()=>tt(`mcpController.start()`,()=>e.mcpController.start()).then(t=>(e.syncSessionTools(),e.onMcpStartupSettled?e.onMcpStartupSettled(t):e.pendingMcpStartupResult=t,t)).catch(t=>(e.logger.warn({err:t instanceof Error?t.message:String(t)},`mcpController.start() failed unexpectedly (non-blocking path)`),{connected:0,failed:0}));e._interactive?t():await t(),e.pendingWorkspaceInit?e.logger.info({workspaceDir:e.workspaceDir},`Workspace identity pending trust confirmation; session restore deferred`):e.parentWorkspaceExisted?e.logger.info({workspaceDir:e.workspaceDir,parentRoot:e.parentWorkspaceExisted.parentRoot},`Parent workspace detected; waiting for user choice (adopt parent or create new)`):e._interactive?await tt(`completeWorkspaceDependentStartup (session restoreAll)`,()=>Ty(e)):tt(`sweepOrphanTraceFiles (headless)`,()=>My(e)),e.devtools&&await e.devtools.start(),e._memoryGovernor.setCallbacks({onWarning:()=>{let t=e.getActiveSession();t&&t.compactNow().catch(t=>{e.logger.warn({err:t instanceof Error?t.message:String(t)},`[memory-governor] headless compactNow (soft degrade) failed`)})},onCritical:t=>{let n=process.env.OTTO_HEADLESS_OOM_POLICY??`log-only`;e.logger.error({policy:n,level:t.level,usedPct:t.usedPct,heapUsed:t.heapUsed},`[memory-governor] critical memory threshold reached (headless/service)`),n===`graceful-exit`&&Ny(e).finally(()=>process.exit(1))},onSample:t=>{e._residencyGovernor.setLevel(t.level);let n=performance.getEntriesByType(`measure`).length;n>5e4&&(performance.clearMeasures(),performance.clearMarks(),e.logger.warn({measureCount:n},`[memory-governor] user-timing buffer exceeded guard threshold — cleared (likely a dev-mode library leaking performance.measure; see a7eaa826)`));let r=e.getActiveSession()?.id;r&&e.storage.traceStore.append(r,{ts:t.ts,sessionId:r,kind:`lifecycle`,node:`process.memory.sample`,payload:{pid:process.pid,level:t.level,heapUsed:t.heapUsed,heapSizeLimit:t.heapSizeLimit,usedPct:Number(t.usedPct.toFixed(2)),rss:t.rss,external:t.external}}).catch(t=>{e.logger.warn({err:t instanceof Error?t.message:String(t)},`[memory-governor] trace sample append failed`)})}}),e._memoryGovernor.start(),e._fleetMonitor.setCallbacks({onSample:t=>{let n=e.getActiveSession()?.id;n&&e.storage.traceStore.append(n,{ts:t.ts,sessionId:n,kind:`lifecycle`,node:`process.fleet.sample`,payload:{pid:process.pid,processCount:t.processCount,totalRssMb:t.totalRssMb,suspectedOrphanCount:t.suspectedOrphanCount,maxGeneration:t.maxGeneration}}).catch(t=>{e.logger.warn({err:t instanceof Error?t.message:String(t)},`[fleet-monitor] trace sample append failed`)})}}),e._fleetMonitor.start(),Ze(`app.start() internal phases complete`),e.logger.info(`App started`)}async function Ty(e){if(e.codingSessionPool.autoPersist){let t=await e.codingSessionPool.restoreAll();if(t>0){e.logger.info({count:t},`Sessions restored from storage`);for(let t of e.listSessions()){let n=e.getSession(t.id);n&&e.notificationDispatcher.attach(n)}}}My(e)}function Ey(e){return!!e.pendingWorkspaceInit}function Dy(e){return!!e.parentWorkspaceExisted}async function Oy(e){let t=e.parentWorkspaceExisted;if(!t)return e.workspaceRef;e.parentWorkspaceExisted=void 0;try{return e.workspaceRef=await Ci(Cy()).resolveLocal(t.parentRoot),await Ty(e),e.workspaceRef}catch(n){e.parentWorkspaceExisted=t,e.logger.warn({err:n,parentRoot:t.parentRoot},`Failed to adopt parent workspace; continuing without workspace identity. Will retry on next startup.`);return}}async function ky(e){let t=e.parentWorkspaceExisted;if(!t)return e.workspaceRef;e.parentWorkspaceExisted=void 0;try{return e.workspaceRef=await Ci(Cy()).createLocal(t.currentRoot),await Ty(e),e.workspaceRef}catch(n){e.parentWorkspaceExisted=t,e.logger.warn({err:n,currentRoot:t.currentRoot},`Failed to create new workspace; continuing without workspace identity. Will retry on next startup.`);return}}async function Ay(e){let t=e.pendingWorkspaceInit;if(!t)return e.workspaceRef;e.pendingWorkspaceInit=void 0;try{return e.workspaceRef=await Ci(Cy()).createLocal(t.root),await Ty(e),e.workspaceRef}catch(n){e.pendingWorkspaceInit=t,e.logger.warn({err:n,root:t.root},`Workspace identity creation failed; continuing without workspace identity. Will retry on next startup.`);return}}async function jy(e,t){let n=e.workspaceRef?.root;if(!n)return!1;let r=Cy(),i=await Ti(n,r);if(!i)return!1;if(!t&&i.memorySyncEnabled){try{await e.storage.autoMemory?.load()}catch{}try{await e.learningStore.refresh()}catch{}}let a=t?{...i,memorySyncEnabled:!0}:{id:i.id,name:i.name,createdAt:i.createdAt,...i.remote?{remote:i.remote}:{}};return await Di(n,a,r),e.workspaceRef={key:Ei(a.id),id:a.id,backend:e.workspaceRef.backend,root:n,...a.remote?{remote:a.remote}:{},...a.memorySyncEnabled?{memorySyncEnabled:!0}:{}},!0}async function My(e){let t=e.sessionStorageDir,n=e.sessionRepoRef?.current;if(!t||!n)return;let r=process.env.OTTO_TRACE_SWEEP;if(r!==`off`)try{let{sweepOrphanTraces:i}=await import(`./trace-orphan-sweeper-BdEIlLfB.js`),a=new Set(await n.listAllSessionIds());for(let t of e.codingSessionPool.listSessions())a.add(t.id);await i({dirs:[x(t,`trace`),x(t,`checkpoint`)],liveSessionIds:a,logger:e.logger,mode:r===`dry-run`?`dry-run`:`delete`})}catch(t){e.logger.warn({err:t instanceof Error?t.message:String(t)},`Orphan trace sweep failed`)}}async function Ny(e){if(e.disposed)return;e.disposed=!0;let t=[],n=async(e,n)=>{try{await n()}catch(n){t.push(Error(`stop:${e}: ${n.message}`))}};e.codingSessionPool.autoPersist&&await n(`saveSessions`,()=>e.codingSessionPool.saveAll()),await n(`processRegistryUnsubs`,()=>{for(let t of e.processRegistryUnsubs)t();e.processRegistryUnsubs.length=0}),await n(`bgProcesses`,()=>w.killAllForOwner(e.processOwnerId)),await n(`mcpController`,()=>e.mcpController.stop()),await n(`processRuntime`,()=>Vt.killAll()),await n(`scheduleService`,()=>e.scheduleServiceInstance?.stop()),await n(`memoryGovernor`,()=>e._memoryGovernor.dispose()),await n(`fleetMonitor`,()=>e._fleetMonitor.dispose()),await n(`agentJobs`,()=>e.agentJobServiceInstance?.dispose()),await n(`settings`,()=>e.settings.dispose()),await n(`toolRegistry`,()=>e.toolRegistry.dispose()),await n(`orchestrator`,()=>e.orchestrator.dispose()),await n(`notification`,()=>e.notificationDispatcher.dispose()),await n(`agentRuntime`,()=>e.agentRuntime.dispose()),await n(`hooks`,()=>{for(let t of e.ownedHookNames)e.hookRegistry.unregister(t);e.ownedHookNames.length=0}),await n(`pluginModules`,()=>e.pluginModuleManager.cleanup()),await n(`pluginProviders`,()=>e.pluginProviderManager.cleanup()),await n(`pluginWorkers`,()=>Hl()),await n(`pluginServices`,()=>_l()),await n(`sandbox`,()=>e.sandbox.dispose()),e.devtools&&await n(`devtools`,()=>e.devtools.stop()),await n(`logSub`,()=>{e.globalLogSubscription&&=(e.globalLogSubscription(),null)}),await n(`traceStore`,()=>e.storage.traceStore.close?.()),await n(`checkpointStore`,()=>e.storage.checkpointStore.close?.()),await n(`authStore`,()=>e._authStore.dispose()),t.length>0&&e.logger.warn({count:t.length,errors:t.map(e=>e.message)},`stop: %d subsystems reported errors`),e.logger.info(`App stopped`)}async function Py(e,t,n){let r=n.current;if(!r)throw Error(`导出归档仅支持关系化 SQLite 后端(sessions.db)。当前后端不支持。`);let i=await si(e,r);if(!i)throw Error(`会话 ${e.slice(0,8)} 不存在或无法加载`);let a=JSON.stringify(i,null,2),o=pi(`sha256`).update(a,`utf-8`).digest(`hex`);await Ai(b(t),{recursive:!0}),await Ni(t,a,`utf-8`);let s=await Mi(t,`utf-8`),c=pi(`sha256`).update(s,`utf-8`).digest(`hex`);if(o!==c)throw Error(`Checksum 校验失败:写入前 sha256=${o.slice(0,16)},读回 sha256=${c.slice(0,16)}。导出文件 ${t} 可能已损坏,操作整体失败。`);return{entryCount:i.entries.length,checksum:o,path:t}}async function Fy(e){let t=await e.capabilityReloader.reload();return e.applyResults({agentProfiles:t.agentProfiles,teamDeclarations:t.teamDeclarations,pendingProviderCapabilities:t.pendingProviderCapabilities}),await e.diagnoseTopoSortIssues(),e.syncSessionTools(),e.panelBackendController.notifyReload(),{mcpTools:t.mcpTools,models:t.models,agents:t.agents,teams:t.teamCount,pendingProviderCapabilities:t.pendingProviderCapabilities,i18nEntries:t.i18nEntries,agentProfiles:t.agentProfiles,teamDeclarations:t.teamDeclarations}}let Iy=0;function Ly(e){let t=`__ottoResidencyDiagnostics`,n=globalThis;n[t]||Object.defineProperty(n,t,{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze({getResidency:()=>e.getResidencyDiagnostics()})})}var Ry=class{processOwnerId=`app-${++Iy}`;get processOwner(){return this.processOwnerId}settings;toolRegistry;hookRegistry;providerRegistry;wireProtocolRegistry;agentRuntime;codingSessionPool;permissionRegistry;auditLog;logger;sessionRepoRef;sessionStorageDir;get workspaceDir(){return this.workspaceRef?.root??this._workspaceDir}_workspaceDir;_workspaceId;_interactive;_shadow;_pluginHomedir;_pluginBundledDirs;workspaceRef;pendingWorkspaceInit;parentWorkspaceExisted;maxSessions;maxToolTurns;maxToolTurnExtensions;promptOutputTokenBudget;promptWallClockBudgetMs;sessionCostBudgetUSD;stallDetection;devtools=null;editFileCallback=void 0;_editFilesDedup=new Set;storage;userMemory=new nt({store:(()=>{let e=new at(ze());return s()?dt(e):e})()});completeText;clock;fileStateManager;learningStore;localLearningStore;memoryAutoExtractor;promptManager;orchestrator;runSession;writeTodos;sessionConfigResolver;runTeam;skillRegistry;i18nRegistry;_pendingProviderCapabilities=[];get pendingProviderCapabilities(){return this._pendingProviderCapabilities}declarativeAgentProfiles=[];extensions;pluginInput=Rn();sigilResolvers=new Ia;expandSigilChips(e,t){return Ga(e,this.sigilResolvers,{workspaceDir:this.workspaceDir},{...t,lookupResolverId:e=>{for(let t of this.pluginInput.getAll())if(t.value===e&&t.resolverId)return t.resolverId}})}feedbackRegistry=new Fa;getShortcuts(){return this.settings.get(`shortcuts`)??[]}async saveShortcut(e,t,n){let r=e.trim();if(!r||!/^[A-Za-z0-9_-]+$/.test(r))throw Error(`invalid shortcut name: ${JSON.stringify(e)}`);if(!t.trim())throw Error(`shortcut text cannot be empty`);let i=this.getShortcuts();if(i.some(e=>e.name===r&&e.name!==n))throw Error(`shortcut name already exists: ${r}`);let a=[...n?i.filter(e=>e.name!==n):i,{name:r,text:t}];await this.settings.persist({shortcuts:a},`project`)}async deleteShortcut(e){let t=this.getShortcuts(),n=t.filter(t=>t.name!==e);n.length!==t.length&&await this.settings.persist({shortcuts:n},`project`)}declarativeTeams=[];mcpController;panelBackendController;get mcpManager(){return this.mcpController.manager}disposed=!1;ownedHookNames=[];failureSignals=new he;diagnoser=new me(this.failureSignals);pluginHealthTracker=Cc();pluginCapabilityQuota=new Ec;inquiryCenter=new Oc;userAskRenderer;userAskSeq=0;processRegistryUnsubs=[];settingsLoaded=!1;lastSettingsConfig=null;_resilienceOverride;_resilienceConfig;defaultToolPreset=`full`;permissionSync;sandbox;_memoryGovernor;_residencyGovernor;_fleetMonitor;get tools(){return this.toolRegistry.getAvailable(this.defaultToolPreset)}agentJobNotify;agentJobServiceInstance;scheduleServiceInstance;searchEcosystem;notificationDispatcher;presenceTracker;followUpPendingProbe;toolsSyncCoordinator;onMcpStartupSettled;pendingMcpStartupResult;setMcpStartupCallback(e){this.onMcpStartupSettled=e,this.pendingMcpStartupResult&&=(e(this.pendingMcpStartupResult),void 0)}pluginContributionsFacade;buildToolsForWorkspace(e){return yy(this,e)}connectorTools(){return by(this)}get agentJobs(){return this.agentJobServiceInstance||=Oo({workspaceDir:this.workspaceDir,agentJobNotify:this.agentJobNotify,buildToolsForWorkspace:e=>this.buildToolsForWorkspace(e),connectorTools:()=>this.connectorTools(),settings:this.settings,modelRegistry:this.modelRegistry,stream:this.codingSessionPool.stream,logger:this.logger,hookRegistry:this.hookRegistry}),this.agentJobServiceInstance}setScheduleService(e){this.scheduleServiceInstance=e,this.pluginModuleManager?.reconcileServiceSchedules()}setEcosystemSearch(e){this.searchEcosystem!==e&&(this.searchEcosystem=e,this.reloadCapabilities().catch(e=>{this.logger.warn({err:e instanceof Error?e.message:String(e)},`Failed to refresh capability_gap after ecosystem search injection`)}))}get memoryGovernor(){return this._memoryGovernor}get fleetMonitor(){return this._fleetMonitor}get modelRegistry(){return this._modelRegistry}get authStore(){return this._authStore}modelCatalogManager;_modelRegistry;_authStore;getAllModels(){return Io(this)}resolveModel(e){return Lo(this,e)}listProviders(){return Ro(this)}registerHook(e){zo(this,e)}unregisterHook(e){return Bo(this,e)}async hydrateModelCache(){return Vo(this)}getSessionAvailableModels(e){return Ho(this,e)}async refreshModels(){return Wo(this)}async reloadCapabilities(){let e=await Fy({capabilityReloader:this.capabilityReloader,applyResults:e=>{this.declarativeAgentProfiles=e.agentProfiles,this.declarativeTeams=e.teamDeclarations,this._pendingProviderCapabilities=e.pendingProviderCapabilities},diagnoseTopoSortIssues:()=>this.diagnoseTopoSortIssues(),syncSessionTools:()=>this.syncSessionTools(),panelBackendController:this.panelBackendController});return{mcpTools:e.mcpTools,models:e.models,agents:e.agents,teams:e.teams,pendingProviderCapabilities:e.pendingProviderCapabilities,i18nEntries:e.i18nEntries}}syncSessionTools(){return this.toolsSyncCoordinator.resync()}syncSessionToolsFor(e){return this.toolsSyncCoordinator.resyncOne(e)}pluginTopology=new od;pluginModuleManager;pluginProviderManager;capabilityReloader;computedPluginCommands(){return this.pluginContributionsFacade.computedPluginCommands()}get sessionManager(){return this.codingSessionPool}getResidencyDiagnostics(){return this.codingSessionPool.getResidencyDiagnostics()}globalLogSubscription=null;constructor(e){let{inspect:t,logger:n,projectConfigPath:r,maxSessions:i,maxToolTurns:a,maxToolTurnExtensions:o,promptOutputTokenBudget:c,promptWallClockBudgetMs:l,sessionCostBudgetUSD:u,stallDetection:d,workspaceDir:f,workspaceId:p,pluginHomedir:m,pluginBundledDirs:h}=e;this.maxSessions=i??ri,this.maxToolTurns=a??gt.maxToolTurns,this.maxToolTurnExtensions=o,this.promptOutputTokenBudget=c,this.promptWallClockBudgetMs=l,this.sessionCostBudgetUSD=u,this.stallDetection=d,this._workspaceDir=f??process.cwd(),this._workspaceId=p,this._interactive=e.interactive??!1,this._shadow=e.shadow??s(),this._pluginHomedir=m??ze(),this._pluginBundledDirs=h??[],this._resilienceOverride=e.resilience,this.logger=C(n.name,{level:n.level,destination:n.destination});let g={};this.sessionRepoRef=g,this.sessionStorageDir=e.storage?.session&&`dir`in e.storage.session?e.storage.session.dir:void 0;let _=Yd({logger:this.logger,hookRegistry:e.hookRegistry,getToolRegistry:()=>this.toolRegistry,getPermissionRegistry:()=>this.permissionRegistry,onHookTimeout:({hookName:e,timeoutMs:t})=>{let n=lc(e);n&&this.pluginHealthTracker.recordHookTimeout(n,e)}});this.sandbox=_.sandbox,this._memoryGovernor=_.memoryGovernor,this._residencyGovernor=_.residencyGovernor,this._fleetMonitor=_.fleetMonitor,this.permissionSync=_.permissionSync,this.hookRegistry=_.hookRegistry;let ee=sd(e,()=>this.settings);this._authStore=ee.authStore,this._modelRegistry=ee.modelRegistry,this.providerRegistry=ee.providerRegistry,this.wireProtocolRegistry=ee.wireProtocolRegistry,this.modelCatalogManager=ee.modelCatalogManager;let te=ee.defaultModel,re=ee.resolveEffectiveModel,ie=e.modelId,v=_a({options:e,workspaceDir:this.workspaceDir,providerRegistry:this.providerRegistry,defaultModel:te,resolveEffectiveModel:re,repoRef:g,getWorkspaceRef:()=>this.workspaceRef,onMemoryConflict:e.onMemoryConflict,getActiveSessionBytes:()=>{let e=this.codingSessionPool?.active?.session;return e instanceof ti?e.estimatedContentBytes:void 0},getEffectiveMaxBytes:()=>{let e=this.codingSessionPool;if(e)return e.getResidencyDiagnostics().maxBytesPerSession},getCoverageThresholds:()=>{let e=this.settings.get(`residency`),t=(e,t)=>t!=null&&process.env[e]===void 0?t:void 0;return{warn:t(`OTTO_MEMORY_COVERAGE_WARN_THRESHOLD`,e?.coverage_warn_threshold),error:t(`OTTO_MEMORY_COVERAGE_ERROR_THRESHOLD`,e?.coverage_error_threshold),floor:t(`OTTO_MEMORY_COVERAGE_FLOOR_THRESHOLD`,e?.coverage_floor_threshold)}}});this.storage={storageHost:v.storageHost,autoMemory:v.autoMemory,memory:v.memory,traceStore:v.traceStore,traceLive:v.traceLive,checkpointStore:v.checkpointStore,remoteMemoryConfigured:!!(e.storage?.remote?.getAuth&&e.storage?.session&&`url`in e.storage.session),remoteSessionConfigured:!!(e.storage?.session&&`url`in e.storage.session)},this.clock=v.clock;let ae=Xd({inspect:t,loggerName:n.name,workspaceDir:this.workspaceDir,projectConfigPath:r,interactive:this._interactive,permissionSync:this.permissionSync,sandbox:this.sandbox,onSettingsApplied:e=>{this.settingsLoaded=!0,e.tool_preset&&(this.defaultToolPreset=e.tool_preset)},getI18nRegistry:()=>this.i18nRegistry});this.devtools=ae.devtools,this.globalLogSubscription=ae.logSubscription,this.settings=ae.settings;let oe=No({getConfig:()=>this.settings.get(`notification`),getCwd:()=>this.workspaceDir,isFollowUpPending:()=>this.followUpPendingProbe?.()??!1,emitHookNotification:e=>void this.hookRegistry.emit(`notification`,e)});this.notificationDispatcher=oe.dispatcher,this.presenceTracker=oe.presenceTracker;let se=this.settings,ce=xa({skillProvider:e.skillProvider,workspaceDir:this.workspaceDir,activePlugins:()=>this.activePlugins(),resolveEffectiveModel:re,providerRegistry:this.providerRegistry,prompt:e.prompt,memoryStore:v.memoryStore,memoryAutoExtractConfig:{enabled:!0,get everyNTurns(){return se.get(`memory_auto_extract`)?.every_n_turns},get maxLessons(){return se.get(`memory_auto_extract`)?.max_lessons},get similarityThreshold(){return se.get(`memory_auto_extract`)?.similarity_threshold}}});this.skillRegistry=ce.skillRegistry,this.fileStateManager=ce.fileStateManager,this.learningStore=ce.learningStore,this.localLearningStore=ce.localLearningStore,this.memoryAutoExtractor=ce.memoryAutoExtractor,this.completeText=ce.completeText,this.promptManager=ce.promptManager;let le=ne(this._authStore,`delegation`),ue=Zd({getModelRegistry:()=>this.modelRegistry,providerRegistry:this.providerRegistry,authStore:this._authStore,getSettings:()=>this.settings,promptManager:this.promptManager,getTools:()=>this.tools,getDeclarativeAgentProfiles:()=>this.getEnabledAgentProfiles(),defaultModel:te,explicitModelId:ie,isModelUsable:le,maxToolTurns:this.maxToolTurns,maxToolTurnExtensions:this.maxToolTurnExtensions,promptOutputTokenBudget:this.promptOutputTokenBudget,promptWallClockBudgetMs:this.promptWallClockBudgetMs,sessionCostBudgetUSD:this.sessionCostBudgetUSD,stallDetection:this.stallDetection,workspaceDir:this.workspaceDir,getWorkspaceRef:()=>this.workspaceRef,workspaceId:this._workspaceId,logger:this.logger,getResilienceConfig:()=>this.getResilienceConfig()}),de=ue.visionDelegateService;this.sessionConfigResolver=ue.sessionConfigResolver;let fe=Qd({options:e,hookRegistry:this.hookRegistry,providerRegistry:this.providerRegistry,getModelRegistry:()=>this._modelRegistry,logger:this.logger,workspaceDir:this.workspaceDir,getTools:()=>this.tools,getDeclarativeAgentProfiles:()=>this.getEnabledAgentProfiles(),getWorkspaceRef:()=>this.workspaceRef,repoRef:g,maxToolTurns:this.maxToolTurns,promptManager:this.promptManager,memory:this.storage.memory,traceStore:this.storage.traceStore,checkpointStore:this.storage.checkpointStore,clock:this.clock,devtools:this.devtools??void 0,residencyGovernor:this._residencyGovernor,getResidencyConfig:()=>this.getResidencyConfig(),visionDelegateService:de,resolveEffectiveModel:re,defaultModel:te});this.agentRuntime=fe.agentRuntime,this.codingSessionPool=fe.codingSessionPool,Ly(this);let pe=fe.swarmAgentRunner,me=$d({hookRegistry:this.hookRegistry,stream:this.codingSessionPool.stream,logger:this.logger,defaultModel:fe.defaultModel,providerRegistry:this.providerRegistry,getDeclarativeTeams:()=>this.declarativeTeams,getDeclarativeAgentProfiles:()=>this.getEnabledAgentProfiles(),getSession:e=>this.getSession(e),createSession:e=>this.createSession(e),removeSession:e=>this.removeSession(e),sessionConfigResolver:this.sessionConfigResolver,swarmAgentRunner:pe,workflowConfig:{retry:this.settings.get(`workflow`)?.retry,circuitBreaker:this.settings.get(`workflow`)?.circuitBreaker}});this.orchestrator=me.orchestrator,this.runSession=me.runSession,this.runTeam=me.runTeam,this.writeTodos=me.writeTodos,this.toolRegistry=this.initToolRegistry(e);let he=rf({toolRegistry:this.toolRegistry,hookRegistry:this.hookRegistry,settings:this.settings,workspaceDir:this.workspaceDir,logger:this.logger,getResilienceConfig:()=>this.getResilienceConfig()});this.permissionRegistry=he.permissionRegistry,this.auditLog=he.auditLog,this.mcpController=he.mcpController;let ge=he.preExistingHooks;this.extensions=af({settings:this.settings,mcpController:this.mcpController,skillRegistry:this.skillRegistry,declarativeAgentProfiles:this.declarativeAgentProfiles,workspaceDir:this.workspaceDir,pluginHomedir:this._pluginHomedir,pluginBundledDirs:this._pluginBundledDirs,onPluginToggle:(e,t)=>{this.pluginModuleManager?.emitMonitorEvent({type:t?`plugin.enabled`:`plugin.disabled`,pluginId:e})}}),this.panelBackendController=ef({mcpController:this.mcpController,callMcpTool:(e,t,n)=>this.callMcpTool(e,t,n),getActivePlugins:()=>this.activePlugins()}).panelBackendController;let _e=of({pluginInput:this.pluginInput,sigilResolvers:this.sigilResolvers,settings:this.settings,workspaceDir:this.workspaceDir,activePlugins:()=>this.activePlugins(),agentRuntime:this.agentRuntime,hookRegistry:this.hookRegistry,preExistingHooks:ge,codingSessionPoolGet:e=>this.codingSessionPool.getSession(e),logger:this.logger,registerHooks:()=>this.registerHooks()});this.ownedHookNames=_e.ownedHookNames,this.processRegistryUnsubs=_e.processRegistryUnsubs,this.i18nRegistry=new jn;let ve=tf({hookRegistry:this.hookRegistry,skillRegistry:this.skillRegistry,providerRegistry:this.providerRegistry,wireProtocolRegistry:this.wireProtocolRegistry,modelRegistry:this._modelRegistry,authStore:this._authStore,toolRegistry:this.toolRegistry,feedbackRegistry:this.feedbackRegistry,sigilResolverRegistry:this.sigilResolvers,pluginInput:this.pluginInput,workspaceDir:this.workspaceDir,activePlugins:()=>this.activePlugins(),callMcpTool:(e,t,n)=>this.callMcpTool(e,t,n),startPluginJob:({pluginId:e,title:t,prompt:n,sessionId:r})=>this.agentJobs.start({title:`[${e}] ${t}`,prompt:n,sessionId:r,origin:`plugin`}),getPluginJobSessionId:()=>this.getActiveSession()?.id,getSessionMessages:e=>this.getSession(e)?.session.messages().filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`),completeText:(e,t)=>this.completeText(e,t),capabilityQuota:this.pluginCapabilityQuota,askUser:(e,t)=>this.askPluginUser(e,t),getWorkspaceKey:()=>this.workspaceRef?.key,logger:this.logger,onPluginLoadError:(e,t)=>this.pluginHealthTracker.recordError(e,t),getSchedulePort:()=>this.scheduleServiceInstance,settings:this.settings,mcpController:this.mcpController,skillRegistryForReloader:this.skillRegistry,modelCatalogManager:this.modelCatalogManager,getActivePluginsForReloader:()=>this.activePlugins(),i18nRegistry:this.i18nRegistry});this.pluginModuleManager=ve.pluginModuleManager,this.pluginProviderManager=ve.pluginProviderManager,this.capabilityReloader=ve.capabilityReloader,this.toolRegistry.onMutation=e=>{this.permissionSync.sync(this.settings.config);for(let t of e.added??[])this.pluginModuleManager.emitMonitorEvent({type:`tool.registered`,toolName:t,source:e.source});for(let t of e.removed??[])this.pluginModuleManager.emitMonitorEvent({type:`tool.unregistered`,toolName:t,source:e.source})},this.settings.on(`change`,e=>{let t=e,n=this.lastSettingsConfig;if(this.lastSettingsConfig=t,!n)return;let r=new Set([...Object.keys(n),...Object.keys(t)]),i=[];for(let e of r)n[e]!==t[e]&&i.push(e);i.length>0&&this.pluginModuleManager.emitMonitorEvent({type:`settings.changed`,keys:i})});let ye=nf({sessionConfigResolver:this.sessionConfigResolver,getSession:e=>this.codingSessionPool.getSession(e),listSessionIds:()=>this.codingSessionPool.listSessions().map(e=>e.id),logger:this.logger,workspaceDir:this.workspaceDir,settings:this.settings,pluginModuleManager:this.pluginModuleManager,mcpController:this.mcpController,getActivePlugins:()=>this.activePlugins()});this.toolsSyncCoordinator=ye.toolsSyncCoordinator,this.pluginContributionsFacade=ye.pluginContributionsFacade}deferredConfigSteps(){return[{label:`resilience-config`,apply:()=>{this.freezeResilienceConfig()}},{label:`residency-config`,apply:()=>{this.freezeResidencyConfig()}},{label:`memory-governor-thresholds`,apply:()=>{let e=this.settings.get(`residency`);e&&this._memoryGovernor.updateThresholds({warnThresholdPct:e.warn_threshold_pct,hardThresholdPct:e.hard_threshold_pct})}},{label:`auth-store-lock-timeout`,apply:()=>{this._authStore.setRefreshLockTimeoutMs(this.getResilienceConfig().oauth.refreshLockTimeoutMs)}}]}async ensureSettingsLoaded(){await sf(this.settings,()=>this.settingsLoaded,e=>{this.settingsLoaded=e}),cf(this.deferredConfigSteps())}freezeResilienceConfig(){this._resilienceConfig===void 0&&(this._resilienceConfig=l(this._resilienceOverride,this.settings.get(`resilience`)))}_residencyConfig;freezeResidencyConfig(){if(this._residencyConfig!==void 0)return;let e=this.settings.get(`residency`),t=(e,t)=>t!=null&&process.env[e]===void 0?t:void 0;this._residencyConfig={totalBytes:t(`OTTO_SESSION_TOTAL_RESIDENCY_BUDGET`,e?.total_bytes),minPerSessionBytes:t(`OTTO_SESSION_MIN_PER_SESSION_BYTES`,e?.min_per_session_bytes),maxPerSessionBytes:t(`OTTO_SESSION_MAX_PER_SESSION_BYTES`,e?.max_per_session_bytes),maxContentBytes:t(`OTTO_SESSION_MAX_CONTENT_BYTES`,e?.max_content_bytes),maxHistoryMessages:t(`OTTO_SESSION_MAX_HISTORY_MESSAGES`,e?.max_history_messages),resumeWindowMessages:t(`OTTO_SESSION_RESUME_WINDOW_MESSAGES`,e?.resume_window_messages),compactionTimeoutMs:t(`OTTO_SESSION_COMPACTION_TIMEOUT_MS`,e?.compaction_timeout_ms)}}getResidencyConfig(){return this._residencyConfig}getResilienceConfig(){if(this._resilienceConfig===void 0)throw Error(`getResilienceConfig() called before settings are loaded — call after ensureSettingsLoaded()/start()`);return this._resilienceConfig}async allowToolAlways(e,t){return Xo(this,e,t)}getPermissionMode(){return Zo(this)}async setPermissionMode(e){return Qo(this,e)}getSessionAlwaysAllow(e){return $o(this,e)}bashAlwaysAllowPrefix(e){return ve(e)}isWellFormedAllowEntry(e){return Ne(e)}async disallowToolAlways(e){return es(this,e)}clearSessionAlwaysAllow(e){ts(this,e)}activePlugins(){return this.pluginTopology.resolve({workspaceDir:this.workspaceDir,disabledPlugins:this.settings.get(`disabled_plugins`)??[],homedir:this._pluginHomedir,bundledDirs:this._pluginBundledDirs})}async diagnoseTopoSortIssues(){await this.pluginTopology.diagnose(this.logger,this.settings)}listFileCommands(){return this.pluginContributionsFacade.listFileCommands()}async callMcpTool(e,t,n){return this.pluginContributionsFacade.callMcpTool(e,t,n)}getPluginPanelRegistrations(){return this.pluginContributionsFacade.getPluginPanelRegistrations()}getPluginStatusItems(){return this.pluginContributionsFacade.getPluginStatusItems()}getGlobalMenuItems(){return this.pluginContributionsFacade.getGlobalMenuItems()}getPluginRenderers(){return this.pluginContributionsFacade.getPluginRenderers()}getPluginStatusWidgets(){return this.pluginContributionsFacade.getPluginStatusWidgets()}getPluginFileViewers(){return this.pluginContributionsFacade.getPluginFileViewers()}isFeedbackAvailable(){return this.feedbackRegistry.get()!==void 0}getPulseSurveyConfig(){return this.settings.get(`pulse_survey`)??{}}recordPulseSurvey(e){this.feedbackRegistry.get()?.recordPulseSurvey?.(e)}buildFeedbackIssueUrl(e){return this.feedbackRegistry.get()?.buildIssueUrl?.(e)}updateSettings(e){return this.settings.update(e)}resolveA2uiRendererPayload(e){return eo(Za(this.activePlugins()),e)}getPluginRegistrations(){return this.pluginContributionsFacade.getPluginRegistrations()}async firePluginActivationEvent(e){await this.pluginModuleManager.activateOn(e,new Set(this.declarativeAgentProfiles.map(e=>e.name)))}async start(){return wy(this)}async completeWorkspaceDependentStartup(){return Ty(this)}needsWorkspaceInit(){return Ey(this)}async confirmWorkspaceInit(){return Ay(this)}hasParentWorkspace(){return Dy(this)}async adoptParentWorkspace(){return Oy(this)}async createLocalWorkspace(){return ky(this)}async setWorkspaceMemorySyncEnabled(e){return jy(this,e)}async sweepOrphanTraceFiles(){return My(this)}async stop(){return Ny(this)}async createSession(e={}){return ns(this,e)}registerNotificationChannel(e){Ko(this,e)}registerInAppNotificationChannel(e){qo(this,e)}setUserAskRenderer(e){this.userAskRenderer=e}async askPluginUser(e,t){let n={...By(t),id:`plugin_ask_${++this.userAskSeq}`,askedBy:`plugin:${e}`},r=this.userAskRenderer;if(!this._interactive||!r)return zy();let i=this.inquiryCenter.enqueue({id:n.id,origin:{kind:`plugin`,pluginId:e},question:n});if(!i.accepted)return zy();if(!await this.inquiryCenter.waitForTurn(n.id))return await i.answer;try{let e=await r(n);return this.inquiryCenter.settle(n.id,e),e}catch(e){throw this.inquiryCenter.settle(n.id,zy()),e}}notifyUserInteraction(){Jo(this)}setTerminalFocus(e){Yo(this,e)}setFollowUpPendingProbe(e){this.followUpPendingProbe=e}notifyPluginServices(e){let t=gl(),n=0;for(let r of this.activePlugins())for(let i of t.runningServiceIds(r.id))t.notify(r.id,i,e)&&(this.pluginCapabilityQuota.onNotifyDelivered(r.id,e.sessionId),n+=1);return n}notifyPluginServiceSchedule(e,t){return this.activePlugins().some(t=>t.id===e.pluginId)?gl().notify(e.pluginId,e.serviceId,{type:`schedule.tick`,scheduleId:t.scheduleId,occurrenceId:t.occurrenceId,occurredAt:t.occurredAt}):!1}getSession(e){return rs(this,e)}async shareSession(e,t){return is(this,e,t)}getActiveSession(){return as(this)}listSessions(e){return os(this,e)}async listAllSessions(e){return ss(this,e)}async removeSession(e){return cs(this,e)}async exportSessionArchive(e,t){return Py(e,t,this.sessionRepoRef??{})}archiveSession(e){return ls(this,e)}async forkSession(e,t){return us(this,e,t)}getEnabledAgentProfiles(){let e=new Set(this.settings.get(`disabled_agents`)??[]);return e.size===0?this.declarativeAgentProfiles:this.declarativeAgentProfiles.filter(t=>!e.has(t.name))}initToolRegistry(e){return xy(this,e)}async buildModelCatalog(e){return Go(this,e)}setSessionAvailableModels(e,t){Uo(this,e,t)}registerHooks(){Sy(this)}get activeSandbox(){return this.sandbox.activeName}approveSandboxBypass(e){this.sandbox.approveBypass(e)}ensureNotDisposed(){if(this.disposed)throw Error(`App has been stopped and cannot be reused.`)}};function zy(){return{answer:``,acceptedRecommendation:!1,resolvedBy:`human`}}function By(e){return{header:Vy(e.header,160),question:Vy(e.question,2e3),background:Vy(e.background,4e3),recommendation:Vy(e.recommendation,1e3),...e.options?{options:e.options.slice(0,8).map(e=>({label:Vy(e.label,120),rationale:Vy(e.rationale,1e3),...e.recommended?{recommended:!0}:{}}))}:{},...e.allowFreeform===void 0?{}:{allowFreeform:e.allowFreeform},...e.multiSelect===void 0?{}:{multiSelect:e.multiSelect},...e.evidence?{evidence:e.evidence.slice(0,8).map(e=>Vy(e,1e3))}:{}}}function Vy(e,t){return String(e??``).replace(/[----]/g,` `).slice(0,t)}function Hy(e){return new Ry(e)}function Uy(e){return{get id(){return e.id},get title(){return e.title},get agentName(){return e.agentName},get model(){return{id:e.model.id,name:e.model.name,provider:e.model.provider}},get isBusy(){return e.isBusy},messageCount:()=>e.session.messages().length,lastAssistantText:()=>ko(e.session.messages()),prompt:(t,n)=>e.prompt(t,n),subscribe:((t,n)=>e.subscribe(t,n)),resolveApproval:(t,n)=>e.resolveApproval(t,n),resolveAskUser:(t,n)=>e.resolveAskUser(t,n),clearContext:()=>e.clearContext(),compactNow:()=>e.compactNow(),renameSession:t=>e.renameSession(t),abort:()=>e.abort(),dispose:()=>e.dispose()}}function Wy(e){return{createSession:async t=>Uy(await e.createSession(t)),jobs:Lt,models:{getAll:()=>e.modelRegistry.getAll().map(e=>({id:e.id,name:e.name,provider:e.provider})),switchModel:async(t,n)=>{let r=e.getSession(t);if(!r)return`会话未找到`;if(r.isBusy)return`当前有正在执行的对话,请等待完成后重试。`;let i=e.modelRegistry.find(n);return i?(r.model=i,null):`未知模型 \`${n}\`。`},refresh:async()=>(await e.refreshModels()).map(e=>({provider:e.provider,status:e.status,added:e.added,kept:e.kept,total:e.total,reason:e.reason}))},permission:{getMode:()=>e.getPermissionMode(),setMode:t=>e.setPermissionMode(t)},auth:{getAuthSource:t=>e.authStore.getAuthSource(t)},i18n:{t:(t,n)=>e.i18nRegistry.t(t,n)},reloadCapabilities:()=>e.reloadCapabilities(),workspaceDir:e.workspaceDir}}const Gy=new Set(`assert.async_hooks.buffer.child_process.cluster.console.constants.crypto.dgram.diagnostics_channel.dns.domain.events.fs.http.http2.https.inspector.module.net.os.path.perf_hooks.process.punycode.querystring.readline.repl.sqlite.stream.string_decoder.timers.tls.trace_events.tty.url.util.v8.vm.wasi.worker_threads.zlib`.split(`.`));function Ky(e){return e.absolutePaths.length>0||e.bareSpecifiers.length>0}function qy(e){let t=[],n=[];for(let r of e.matchAll(/require\("([^"]+)"\)/g)){let e=r[1];if(e.startsWith(`/`)){t.includes(e)||t.push(e);continue}e.startsWith(`.`)||e.startsWith(`node:`)||Gy.has(e)||n.includes(e)||n.push(e)}return{absolutePaths:t,bareSpecifiers:n}}function Jy(e,t){let n=qy(t);if(!Ky(n))return;let r=[`${e}: 产物不可分发(RFC-365 R1/R2)`];throw n.absolutePaths.length>0&&r.push(` 编译机绝对路径 require(R1)——发布机路径在用户机器不存在:`,...n.absolutePaths.map(e=>` ${e}`)),n.bareSpecifiers.length>0&&r.push(` 裸模块名 require(R2)——假设运行机有 node_modules,在 ~/.otto/plugins/<id>/ 必然 MODULE_NOT_FOUND:`,...n.bareSpecifiers.map(e=>` ${e}`)),Error(r.join(`
|
|
503
|
+
user explicitly applies it.`}function hy(e){return`Draft skill: ${e.taskSignature.length>60?`${e.taskSignature.slice(0,60)}…`:e.taskSignature}`}function gy(e){try{let t=fy({pluginId:e.pluginId,workspaceKey:e.workspaceKey,sessionIds:e.brief.sessionIds});return{jobId:e.startJob({title:hy(e.brief),prompt:my(e.brief,t),sessionId:e.sessionId}).id}}catch(t){e.logger?.warn(`skill-loop: failed to start skill draft job: ${t instanceof Error?t.message:String(t)}`);return}}function _y(e){e.hookRegistry.register(df(e.toolRegistry,e.getDefaultToolPreset)),e.hookRegistry.register(we(e.failureSignals)),e.hookRegistry.register(Ee(e.failureSignals)),e.hookRegistry.registerAll(e.contextSourcesBuildHooks(e.workspaceDir,e.memory)),e.memory&&e.hookRegistry.registerAll(Dt(e.memory)),e.hookRegistry.registerAll(At({getTodoList:t=>e.getSession(t)?.session.getTodoList()}));let t=/-milestone\.md$/,n=/^Status:\s*Done\b/m;e.hookRegistry.registerAll(Et({isDocSyncTrigger:e=>{let r=typeof e.args.path==`string`?e.args.path:``;if(!t.test(r))return!1;let i=typeof e.args.newContent==`string`?e.args.newContent:typeof e.args.content==`string`?e.args.content:``;return n.test(i)}})),e.hookRegistry.registerAll(bf(e.learningStore,e.promptManager,e.localLearningStore)),e.skillRegistry&&e.hookRegistry.registerAll(xf(e.skillRegistry)),e.hookRegistry.registerAll(pr({workspaceDir:e.workspaceDir})),e.hookRegistry.registerAll(wf()),e.hookRegistry.on(`session.deleted`,`rfc047-notification-detach`,t=>e.notificationDispatcher.detach(t.sessionId));let r=iy();e.hookRegistry.registerAll(r.hooks),e.hookRegistry.register(Tf(e=>{w.killAllForSession(e)})),e.hookRegistry.registerAll(Ef({registry:e.permissionRegistry,getPersistedAllow:t=>e.codingSessionPool.getSessionPermissionAllow(t)})),e.hookRegistry.register(ny({getContext:()=>{let t=je(e.workspaceDir,ze());if(!e.sandbox.enabled)return{mode:`bypass`,projectRoot:e.workspaceDir,writableRoots:[],deniedRoots:t,networkAllowed:!0};let n=e.settings.get(`permission_mode`)??`auto`;return{mode:n,projectRoot:e.workspaceDir,writableRoots:be(n,e.workspaceDir,Be(),e.sandbox.writablePaths),deniedRoots:t,networkAllowed:e.sandbox.isNetworkAllowed,autoAllowBashIfSandboxed:e.sandbox.autoAllowBashIfSandboxed}}})),e.hookRegistry.registerAll(Of(t=>e.getSession(t),e.memoryAutoExtractor,{isEnabled:()=>e.settings.get(`memory_auto_extract`)?.enabled===!0||process.env.OTTO_MEMORY_AUTO_EXTRACT===`1`}));let i=()=>e.settings.get(`skill_loop`)?.enabled===!0||process.env.OTTO_SKILL_LOOP===`1`;return e.hookRegistry.registerAll(kf({isEnabled:i})),e.hookRegistry.registerAll(ey({isEnabled:i,getMinMessages:()=>e.settings.get(`skill_loop`)?.min_messages,getCooldownDays:()=>e.settings.get(`skill_loop`)?.dismiss_cooldown_days,notifyServices:e.notifyPluginServices,getWorkspaceKey:e.getWorkspaceKey,getRequestGrill:t=>{let n=e.getSession(t);return n?e=>n.requestGrill({...e,askedBy:`skill-loop`}):void 0},onAccepted:({sessionId:t,brief:n})=>{gy({startJob:t=>e.startSkillDraftJob({...t,origin:`user`}),brief:n,sessionId:t,pluginId:Zv,workspaceKey:e.getWorkspaceKey()??Qv,logger:{warn:t=>e.logger.warn(t)}})},logger:e.logger})),e.hookRegistry.register(Se({getOnFileEdited:e.getEditFileCallback,dedupCache:e.editFilesDedup})),{agentJobNotify:r.notify}}function vy(e,t,n,r){return lf({processOwnerId:e.processOwnerId,orchestrator:e.orchestrator,writeTodos:e.writeTodos,sandbox:t=>e.sandbox.isBypassed(t?.command)?void 0:e.sandbox.current??void 0,autoMemory:e.storage.autoMemory,reloadMemory:e.storage.memory?()=>e.storage.memory.loadMemory():void 0,archiveRecall:e.storage.memory,runTeam:e.runTeam,runSession:e.runSession,fileStateManager:e.fileStateManager,learningStore:e.learningStore,localLearningStore:e.localLearningStore,sessions:{list:()=>e.listSessions(),create:()=>e.createSession(),remove:t=>e.removeSession(t),get:t=>e.getSession(t)},listModels:t=>e.buildModelCatalog(t),startJob:t=>({jobId:e.agentJobs.start({...t,origin:`main`}).id}),getScheduleService:()=>e.scheduleServiceInstance,searchEcosystem:e.searchEcosystem},t,n,r)}function yy(e,t){return Ie(t,uf(vy(e,t,e.skillRegistry?un(e.skillRegistry,t):void 0,!1))).getAvailable(e.defaultToolPreset)}function by(e){return e.toolRegistry.getAvailable(e.defaultToolPreset).filter(e=>e.name.startsWith(`mcp__`))}function xy(e,t){let n=t.skillProvider??(e.skillRegistry?un(e.skillRegistry,e.workspaceDir):void 0);t.sandbox&&e.sandbox.pin(t.sandbox);let r={registerChild(e,t){return{pid:Vt.registerChild(e,t).pid??0}}};return Ie(e.workspaceDir,{...uf(vy(e,e.workspaceDir,n,t.lsp===!0)),processTracker:r})}function Sy(e){e.agentJobNotify=_y({hookRegistry:e.hookRegistry,toolRegistry:e.toolRegistry,getDefaultToolPreset:()=>e.defaultToolPreset,failureSignals:e.failureSignals,contextSourcesBuildHooks:(t,n)=>e.agentRuntime.contextSources.sealAndBuildHooks(t,n),workspaceDir:e.workspaceDir,memory:e.storage.memory,learningStore:e.learningStore,localLearningStore:e.localLearningStore,promptManager:e.promptManager,skillRegistry:e.skillRegistry,notificationDispatcher:e.notificationDispatcher,permissionRegistry:e.permissionRegistry,codingSessionPool:e.codingSessionPool,sandbox:e.sandbox,settings:e.settings,getEditFileCallback:()=>e.editFileCallback,editFilesDedup:e._editFilesDedup,memoryAutoExtractor:e.memoryAutoExtractor,getSession:t=>e.getSession(t),notifyPluginServices:t=>e.notifyPluginServices(t),getWorkspaceKey:()=>e.workspaceRef?.key,startSkillDraftJob:t=>e.agentJobs.start(t),logger:e.logger}).agentJobNotify}function Cy(e){return{async readFile(e){try{return await Mi(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}},async writeFile(e,t){await Ai(b(e),{recursive:!0}),await tn(e,t)},async writeFileExclusive(e,t){await Ai(b(e),{recursive:!0});try{let n=await ji(e,`wx`);try{await n.writeFile(t,`utf8`)}finally{await n.close()}return!0}catch(e){if(e.code===`EEXIST`)return!1;throw e}},genId:e?.genId??wi,now:e?.now??(()=>new Date().toISOString()),...e?.confirmTrust?{confirmTrust:e.confirmTrust}:{}}}async function wy(e){if(e.ensureNotDisposed(),await e.ensureSettingsLoaded(),!e.workspaceRef&&!e.pendingWorkspaceInit&&!e.parentWorkspaceExisted)try{let t=Ci(Cy()),n=e._workspaceId?{id:e._workspaceId}:void 0,r=await t.resolveLocal(e.workspaceDir,{...n,autoCreate:!(e._interactive&&!n)});`kind`in r&&r.kind===`uninitialized`?e.pendingWorkspaceInit={root:r.root}:`kind`in r&&r.kind===`parentWorkspaceExisted`?e.parentWorkspaceExisted={parentRoot:r.parentRoot,currentRoot:r.currentRoot,marker:r.marker}:e.workspaceRef=r}catch(t){e.logger.warn({err:t,workspaceDir:e.workspaceDir},`Workspace resolution failed; continuing without workspace identity. Sessions previously saved under a workspace key will not be restored.`)}e.storage.autoMemory&&await e.storage.autoMemory.load(),await tt(`skills/agents/teams discovery + plugin module load`,async()=>{if(e.skillRegistry){await e.skillRegistry.discover();for(let t of e.settings.get(`disabled_skills`)??[])e.skillRegistry.disable(t);let t=new Set(e.settings.get(`disabled_plugins`)??[]);if(t.size>0)for(let[n,r]of e.skillRegistry.getAll())r.source?.type===`plugin`&&r.source.id&&t.has(r.source.id)&&e.skillRegistry.disable(n)}e.declarativeAgentProfiles=await Ks(e.workspaceDir,{plugins:e.activePlugins()}),e.declarativeTeams=await Qs(e.workspaceDir);let t=await e.pluginModuleManager.reload(new Set(e.declarativeAgentProfiles.map(e=>e.name)));e.declarativeAgentProfiles.push(...t),e._pendingProviderCapabilities=(await e.pluginProviderManager.reload()).pendingCapabilityPluginIds,await e.diagnoseTopoSortIssues()});let t=()=>tt(`mcpController.start()`,()=>e.mcpController.start()).then(t=>(e.syncSessionTools(),e.onMcpStartupSettled?e.onMcpStartupSettled(t):e.pendingMcpStartupResult=t,t)).catch(t=>(e.logger.warn({err:t instanceof Error?t.message:String(t)},`mcpController.start() failed unexpectedly (non-blocking path)`),{connected:0,failed:0}));e._interactive?t():await t(),e.pendingWorkspaceInit?e.logger.info({workspaceDir:e.workspaceDir},`Workspace identity pending trust confirmation; session restore deferred`):e.parentWorkspaceExisted?e.logger.info({workspaceDir:e.workspaceDir,parentRoot:e.parentWorkspaceExisted.parentRoot},`Parent workspace detected; waiting for user choice (adopt parent or create new)`):e._interactive?await tt(`completeWorkspaceDependentStartup (session restoreAll)`,()=>Ty(e)):tt(`sweepOrphanTraceFiles (headless)`,()=>My(e)),e.devtools&&await e.devtools.start(),e._memoryGovernor.setCallbacks({onWarning:()=>{let t=e.getActiveSession();t&&t.compactNow().catch(t=>{e.logger.warn({err:t instanceof Error?t.message:String(t)},`[memory-governor] headless compactNow (soft degrade) failed`)})},onCritical:t=>{let n=process.env.OTTO_HEADLESS_OOM_POLICY??`log-only`;e.logger.error({policy:n,level:t.level,usedPct:t.usedPct,heapUsed:t.heapUsed},`[memory-governor] critical memory threshold reached (headless/service)`),n===`graceful-exit`&&Ny(e).finally(()=>process.exit(1))},onSample:t=>{e._residencyGovernor.setLevel(t.level);let n=performance.getEntriesByType(`measure`).length;n>5e4&&(performance.clearMeasures(),performance.clearMarks(),e.logger.warn({measureCount:n},`[memory-governor] user-timing buffer exceeded guard threshold — cleared (likely a dev-mode library leaking performance.measure; see a7eaa826)`));let r=e.getActiveSession()?.id;r&&e.storage.traceStore.append(r,{ts:t.ts,sessionId:r,kind:`lifecycle`,node:`process.memory.sample`,payload:{pid:process.pid,level:t.level,heapUsed:t.heapUsed,heapSizeLimit:t.heapSizeLimit,usedPct:Number(t.usedPct.toFixed(2)),rss:t.rss,external:t.external}}).catch(t=>{e.logger.warn({err:t instanceof Error?t.message:String(t)},`[memory-governor] trace sample append failed`)})}}),e._memoryGovernor.start(),e._fleetMonitor.setCallbacks({onSample:t=>{let n=e.getActiveSession()?.id;n&&e.storage.traceStore.append(n,{ts:t.ts,sessionId:n,kind:`lifecycle`,node:`process.fleet.sample`,payload:{pid:process.pid,processCount:t.processCount,totalRssMb:t.totalRssMb,suspectedOrphanCount:t.suspectedOrphanCount,maxGeneration:t.maxGeneration}}).catch(t=>{e.logger.warn({err:t instanceof Error?t.message:String(t)},`[fleet-monitor] trace sample append failed`)})}}),e._fleetMonitor.start(),Ze(`app.start() internal phases complete`),e.logger.info(`App started`)}async function Ty(e){if(e.codingSessionPool.autoPersist){let t=await e.codingSessionPool.restoreAll();if(t>0){e.logger.info({count:t},`Sessions restored from storage`);for(let t of e.listSessions()){let n=e.getSession(t.id);n&&e.notificationDispatcher.attach(n)}}}My(e)}function Ey(e){return!!e.pendingWorkspaceInit}function Dy(e){return!!e.parentWorkspaceExisted}async function Oy(e){let t=e.parentWorkspaceExisted;if(!t)return e.workspaceRef;e.parentWorkspaceExisted=void 0;try{return e.workspaceRef=await Ci(Cy()).resolveLocal(t.parentRoot),await Ty(e),e.workspaceRef}catch(n){e.parentWorkspaceExisted=t,e.logger.warn({err:n,parentRoot:t.parentRoot},`Failed to adopt parent workspace; continuing without workspace identity. Will retry on next startup.`);return}}async function ky(e){let t=e.parentWorkspaceExisted;if(!t)return e.workspaceRef;e.parentWorkspaceExisted=void 0;try{return e.workspaceRef=await Ci(Cy()).createLocal(t.currentRoot),await Ty(e),e.workspaceRef}catch(n){e.parentWorkspaceExisted=t,e.logger.warn({err:n,currentRoot:t.currentRoot},`Failed to create new workspace; continuing without workspace identity. Will retry on next startup.`);return}}async function Ay(e){let t=e.pendingWorkspaceInit;if(!t)return e.workspaceRef;e.pendingWorkspaceInit=void 0;try{return e.workspaceRef=await Ci(Cy()).createLocal(t.root),await Ty(e),e.workspaceRef}catch(n){e.pendingWorkspaceInit=t,e.logger.warn({err:n,root:t.root},`Workspace identity creation failed; continuing without workspace identity. Will retry on next startup.`);return}}async function jy(e,t){let n=e.workspaceRef?.root;if(!n)return!1;let r=Cy(),i=await Ti(n,r);if(!i)return!1;if(!t&&i.memorySyncEnabled){try{await e.storage.autoMemory?.load()}catch{}try{await e.learningStore.refresh()}catch{}}let a=t?{...i,memorySyncEnabled:!0}:{id:i.id,name:i.name,createdAt:i.createdAt,...i.remote?{remote:i.remote}:{}};return await Di(n,a,r),e.workspaceRef={key:Ei(a.id),id:a.id,backend:e.workspaceRef.backend,root:n,...a.remote?{remote:a.remote}:{},...a.memorySyncEnabled?{memorySyncEnabled:!0}:{}},!0}async function My(e){let t=e.sessionStorageDir,n=e.sessionRepoRef?.current;if(!t||!n)return;let r=process.env.OTTO_TRACE_SWEEP;if(r!==`off`)try{let{sweepOrphanTraces:i}=await import(`./trace-orphan-sweeper-BdEIlLfB.js`),a=new Set(await n.listAllSessionIds());for(let t of e.codingSessionPool.listSessions())a.add(t.id);await i({dirs:[x(t,`trace`),x(t,`checkpoint`)],liveSessionIds:a,logger:e.logger,mode:r===`dry-run`?`dry-run`:`delete`})}catch(t){e.logger.warn({err:t instanceof Error?t.message:String(t)},`Orphan trace sweep failed`)}}async function Ny(e){if(e.disposed)return;e.disposed=!0;let t=[],n=async(e,n)=>{try{await n()}catch(n){t.push(Error(`stop:${e}: ${n.message}`))}};e.codingSessionPool.autoPersist&&await n(`saveSessions`,()=>e.codingSessionPool.saveAll()),await n(`processRegistryUnsubs`,()=>{for(let t of e.processRegistryUnsubs)t();e.processRegistryUnsubs.length=0}),await n(`bgProcesses`,()=>w.killAllForOwner(e.processOwnerId)),await n(`mcpController`,()=>e.mcpController.stop()),await n(`processRuntime`,()=>Vt.killAll()),await n(`scheduleService`,()=>e.scheduleServiceInstance?.stop()),await n(`memoryGovernor`,()=>e._memoryGovernor.dispose()),await n(`fleetMonitor`,()=>e._fleetMonitor.dispose()),await n(`agentJobs`,()=>e.agentJobServiceInstance?.dispose()),await n(`settings`,()=>e.settings.dispose()),await n(`toolRegistry`,()=>e.toolRegistry.dispose()),await n(`orchestrator`,()=>e.orchestrator.dispose()),await n(`notification`,()=>e.notificationDispatcher.dispose()),await n(`agentRuntime`,()=>e.agentRuntime.dispose()),await n(`hooks`,()=>{for(let t of e.ownedHookNames)e.hookRegistry.unregister(t);e.ownedHookNames.length=0}),await n(`pluginModules`,()=>e.pluginModuleManager.cleanup()),await n(`pluginProviders`,()=>e.pluginProviderManager.cleanup()),await n(`pluginWorkers`,()=>Hl()),await n(`pluginServices`,()=>_l()),await n(`sandbox`,()=>e.sandbox.dispose()),e.devtools&&await n(`devtools`,()=>e.devtools.stop()),await n(`logSub`,()=>{e.globalLogSubscription&&=(e.globalLogSubscription(),null)}),await n(`traceStore`,()=>e.storage.traceStore.close?.()),await n(`checkpointStore`,()=>e.storage.checkpointStore.close?.()),await n(`authStore`,()=>e._authStore.dispose()),t.length>0&&e.logger.warn({count:t.length,errors:t.map(e=>e.message)},`stop: %d subsystems reported errors`),e.logger.info(`App stopped`)}async function Py(e,t,n){let r=n.current;if(!r)throw Error(`导出归档仅支持关系化 SQLite 后端(sessions.db)。当前后端不支持。`);let i=await si(e,r);if(!i)throw Error(`会话 ${e.slice(0,8)} 不存在或无法加载`);let a=JSON.stringify(i,null,2),o=pi(`sha256`).update(a,`utf-8`).digest(`hex`);await Ai(b(t),{recursive:!0}),await Ni(t,a,`utf-8`);let s=await Mi(t,`utf-8`),c=pi(`sha256`).update(s,`utf-8`).digest(`hex`);if(o!==c)throw Error(`Checksum 校验失败:写入前 sha256=${o.slice(0,16)},读回 sha256=${c.slice(0,16)}。导出文件 ${t} 可能已损坏,操作整体失败。`);return{entryCount:i.entries.length,checksum:o,path:t}}async function Fy(e){let t=await e.capabilityReloader.reload();return e.applyResults({agentProfiles:t.agentProfiles,teamDeclarations:t.teamDeclarations,pendingProviderCapabilities:t.pendingProviderCapabilities}),await e.diagnoseTopoSortIssues(),e.syncSessionTools(),e.panelBackendController.notifyReload(),{mcpTools:t.mcpTools,models:t.models,agents:t.agents,teams:t.teamCount,pendingProviderCapabilities:t.pendingProviderCapabilities,i18nEntries:t.i18nEntries,agentProfiles:t.agentProfiles,teamDeclarations:t.teamDeclarations,...t.reloadFailures?{reloadFailures:t.reloadFailures}:{}}}let Iy=0;function Ly(e){let t=`__ottoResidencyDiagnostics`,n=globalThis;n[t]||Object.defineProperty(n,t,{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze({getResidency:()=>e.getResidencyDiagnostics()})})}var Ry=class{processOwnerId=`app-${++Iy}`;get processOwner(){return this.processOwnerId}settings;toolRegistry;hookRegistry;providerRegistry;wireProtocolRegistry;agentRuntime;codingSessionPool;permissionRegistry;auditLog;logger;sessionRepoRef;sessionStorageDir;get workspaceDir(){return this.workspaceRef?.root??this._workspaceDir}_workspaceDir;_workspaceId;_interactive;_shadow;_pluginHomedir;_pluginBundledDirs;workspaceRef;pendingWorkspaceInit;parentWorkspaceExisted;maxSessions;maxToolTurns;maxToolTurnExtensions;promptOutputTokenBudget;promptWallClockBudgetMs;sessionCostBudgetUSD;stallDetection;devtools=null;editFileCallback=void 0;_editFilesDedup=new Set;storage;userMemory=new nt({store:(()=>{let e=new at(ze());return s()?dt(e):e})()});completeText;clock;fileStateManager;learningStore;localLearningStore;memoryAutoExtractor;promptManager;orchestrator;runSession;writeTodos;sessionConfigResolver;runTeam;skillRegistry;i18nRegistry;_pendingProviderCapabilities=[];get pendingProviderCapabilities(){return this._pendingProviderCapabilities}declarativeAgentProfiles=[];extensions;pluginInput=Rn();sigilResolvers=new Ia;expandSigilChips(e,t){return Ga(e,this.sigilResolvers,{workspaceDir:this.workspaceDir},{...t,lookupResolverId:e=>{for(let t of this.pluginInput.getAll())if(t.value===e&&t.resolverId)return t.resolverId}})}feedbackRegistry=new Fa;getShortcuts(){return this.settings.get(`shortcuts`)??[]}async saveShortcut(e,t,n){let r=e.trim();if(!r||!/^[A-Za-z0-9_-]+$/.test(r))throw Error(`invalid shortcut name: ${JSON.stringify(e)}`);if(!t.trim())throw Error(`shortcut text cannot be empty`);let i=this.getShortcuts();if(i.some(e=>e.name===r&&e.name!==n))throw Error(`shortcut name already exists: ${r}`);let a=[...n?i.filter(e=>e.name!==n):i,{name:r,text:t}];await this.settings.persist({shortcuts:a},`project`)}async deleteShortcut(e){let t=this.getShortcuts(),n=t.filter(t=>t.name!==e);n.length!==t.length&&await this.settings.persist({shortcuts:n},`project`)}declarativeTeams=[];mcpController;panelBackendController;get mcpManager(){return this.mcpController.manager}disposed=!1;ownedHookNames=[];failureSignals=new he;diagnoser=new me(this.failureSignals);pluginHealthTracker=Cc();pluginCapabilityQuota=new Ec;inquiryCenter=new Oc;userAskRenderer;userAskSeq=0;processRegistryUnsubs=[];settingsLoaded=!1;lastSettingsConfig=null;_resilienceOverride;_resilienceConfig;defaultToolPreset=`full`;permissionSync;sandbox;_memoryGovernor;_residencyGovernor;_fleetMonitor;get tools(){return this.toolRegistry.getAvailable(this.defaultToolPreset)}agentJobNotify;agentJobServiceInstance;scheduleServiceInstance;searchEcosystem;notificationDispatcher;presenceTracker;followUpPendingProbe;toolsSyncCoordinator;onMcpStartupSettled;pendingMcpStartupResult;setMcpStartupCallback(e){this.onMcpStartupSettled=e,this.pendingMcpStartupResult&&=(e(this.pendingMcpStartupResult),void 0)}pluginContributionsFacade;buildToolsForWorkspace(e){return yy(this,e)}connectorTools(){return by(this)}get agentJobs(){return this.agentJobServiceInstance||=Oo({workspaceDir:this.workspaceDir,agentJobNotify:this.agentJobNotify,buildToolsForWorkspace:e=>this.buildToolsForWorkspace(e),connectorTools:()=>this.connectorTools(),settings:this.settings,modelRegistry:this.modelRegistry,stream:this.codingSessionPool.stream,logger:this.logger,hookRegistry:this.hookRegistry}),this.agentJobServiceInstance}setScheduleService(e){this.scheduleServiceInstance=e,this.pluginModuleManager?.reconcileServiceSchedules()}setEcosystemSearch(e){this.searchEcosystem!==e&&(this.searchEcosystem=e,this.reloadCapabilities().catch(e=>{this.logger.warn({err:e instanceof Error?e.message:String(e)},`Failed to refresh capability_gap after ecosystem search injection`)}))}get memoryGovernor(){return this._memoryGovernor}get fleetMonitor(){return this._fleetMonitor}get modelRegistry(){return this._modelRegistry}get authStore(){return this._authStore}modelCatalogManager;_modelRegistry;_authStore;getAllModels(){return Io(this)}resolveModel(e){return Lo(this,e)}listProviders(){return Ro(this)}registerHook(e){zo(this,e)}unregisterHook(e){return Bo(this,e)}async hydrateModelCache(){return Vo(this)}getSessionAvailableModels(e){return Ho(this,e)}async refreshModels(){return Wo(this)}async reloadCapabilities(){let{agentProfiles:e,teamDeclarations:t,...n}=await Fy({capabilityReloader:this.capabilityReloader,applyResults:e=>{this.declarativeAgentProfiles=e.agentProfiles,this.declarativeTeams=e.teamDeclarations,this._pendingProviderCapabilities=e.pendingProviderCapabilities},diagnoseTopoSortIssues:()=>this.diagnoseTopoSortIssues(),syncSessionTools:()=>this.syncSessionTools(),panelBackendController:this.panelBackendController});return n}syncSessionTools(){return this.toolsSyncCoordinator.resync()}syncSessionToolsFor(e){return this.toolsSyncCoordinator.resyncOne(e)}pluginTopology=new od;pluginModuleManager;pluginProviderManager;capabilityReloader;computedPluginCommands(){return this.pluginContributionsFacade.computedPluginCommands()}get sessionManager(){return this.codingSessionPool}getResidencyDiagnostics(){return this.codingSessionPool.getResidencyDiagnostics()}globalLogSubscription=null;constructor(e){let{inspect:t,logger:n,projectConfigPath:r,maxSessions:i,maxToolTurns:a,maxToolTurnExtensions:o,promptOutputTokenBudget:c,promptWallClockBudgetMs:l,sessionCostBudgetUSD:u,stallDetection:d,workspaceDir:f,workspaceId:p,pluginHomedir:m,pluginBundledDirs:h}=e;this.maxSessions=i??ri,this.maxToolTurns=a??gt.maxToolTurns,this.maxToolTurnExtensions=o,this.promptOutputTokenBudget=c,this.promptWallClockBudgetMs=l,this.sessionCostBudgetUSD=u,this.stallDetection=d,this._workspaceDir=f??process.cwd(),this._workspaceId=p,this._interactive=e.interactive??!1,this._shadow=e.shadow??s(),this._pluginHomedir=m??ze(),this._pluginBundledDirs=h??[],this._resilienceOverride=e.resilience,this.logger=C(n.name,{level:n.level,destination:n.destination});let g={};this.sessionRepoRef=g,this.sessionStorageDir=e.storage?.session&&`dir`in e.storage.session?e.storage.session.dir:void 0;let _=Yd({logger:this.logger,hookRegistry:e.hookRegistry,getToolRegistry:()=>this.toolRegistry,getPermissionRegistry:()=>this.permissionRegistry,onHookTimeout:({hookName:e,timeoutMs:t})=>{let n=lc(e);n&&this.pluginHealthTracker.recordHookTimeout(n,e)}});this.sandbox=_.sandbox,this._memoryGovernor=_.memoryGovernor,this._residencyGovernor=_.residencyGovernor,this._fleetMonitor=_.fleetMonitor,this.permissionSync=_.permissionSync,this.hookRegistry=_.hookRegistry;let ee=sd(e,()=>this.settings);this._authStore=ee.authStore,this._modelRegistry=ee.modelRegistry,this.providerRegistry=ee.providerRegistry,this.wireProtocolRegistry=ee.wireProtocolRegistry,this.modelCatalogManager=ee.modelCatalogManager;let te=ee.defaultModel,re=ee.resolveEffectiveModel,ie=e.modelId,v=_a({options:e,workspaceDir:this.workspaceDir,providerRegistry:this.providerRegistry,defaultModel:te,resolveEffectiveModel:re,repoRef:g,getWorkspaceRef:()=>this.workspaceRef,onMemoryConflict:e.onMemoryConflict,getActiveSessionBytes:()=>{let e=this.codingSessionPool?.active?.session;return e instanceof ti?e.estimatedContentBytes:void 0},getEffectiveMaxBytes:()=>{let e=this.codingSessionPool;if(e)return e.getResidencyDiagnostics().maxBytesPerSession},getCoverageThresholds:()=>{let e=this.settings.get(`residency`),t=(e,t)=>t!=null&&process.env[e]===void 0?t:void 0;return{warn:t(`OTTO_MEMORY_COVERAGE_WARN_THRESHOLD`,e?.coverage_warn_threshold),error:t(`OTTO_MEMORY_COVERAGE_ERROR_THRESHOLD`,e?.coverage_error_threshold),floor:t(`OTTO_MEMORY_COVERAGE_FLOOR_THRESHOLD`,e?.coverage_floor_threshold)}}});this.storage={storageHost:v.storageHost,autoMemory:v.autoMemory,memory:v.memory,traceStore:v.traceStore,traceLive:v.traceLive,checkpointStore:v.checkpointStore,remoteMemoryConfigured:!!(e.storage?.remote?.getAuth&&e.storage?.session&&`url`in e.storage.session),remoteSessionConfigured:!!(e.storage?.session&&`url`in e.storage.session)},this.clock=v.clock;let ae=Xd({inspect:t,loggerName:n.name,workspaceDir:this.workspaceDir,projectConfigPath:r,interactive:this._interactive,permissionSync:this.permissionSync,sandbox:this.sandbox,onSettingsApplied:e=>{this.settingsLoaded=!0,e.tool_preset&&(this.defaultToolPreset=e.tool_preset)},getI18nRegistry:()=>this.i18nRegistry});this.devtools=ae.devtools,this.globalLogSubscription=ae.logSubscription,this.settings=ae.settings;let oe=No({getConfig:()=>this.settings.get(`notification`),getCwd:()=>this.workspaceDir,isFollowUpPending:()=>this.followUpPendingProbe?.()??!1,emitHookNotification:e=>void this.hookRegistry.emit(`notification`,e)});this.notificationDispatcher=oe.dispatcher,this.presenceTracker=oe.presenceTracker;let se=this.settings,ce=xa({skillProvider:e.skillProvider,workspaceDir:this.workspaceDir,activePlugins:()=>this.activePlugins(),resolveEffectiveModel:re,providerRegistry:this.providerRegistry,prompt:e.prompt,memoryStore:v.memoryStore,memoryAutoExtractConfig:{enabled:!0,get everyNTurns(){return se.get(`memory_auto_extract`)?.every_n_turns},get maxLessons(){return se.get(`memory_auto_extract`)?.max_lessons},get similarityThreshold(){return se.get(`memory_auto_extract`)?.similarity_threshold}}});this.skillRegistry=ce.skillRegistry,this.fileStateManager=ce.fileStateManager,this.learningStore=ce.learningStore,this.localLearningStore=ce.localLearningStore,this.memoryAutoExtractor=ce.memoryAutoExtractor,this.completeText=ce.completeText,this.promptManager=ce.promptManager;let le=ne(this._authStore,`delegation`),ue=Zd({getModelRegistry:()=>this.modelRegistry,providerRegistry:this.providerRegistry,authStore:this._authStore,getSettings:()=>this.settings,promptManager:this.promptManager,getTools:()=>this.tools,getDeclarativeAgentProfiles:()=>this.getEnabledAgentProfiles(),defaultModel:te,explicitModelId:ie,isModelUsable:le,maxToolTurns:this.maxToolTurns,maxToolTurnExtensions:this.maxToolTurnExtensions,promptOutputTokenBudget:this.promptOutputTokenBudget,promptWallClockBudgetMs:this.promptWallClockBudgetMs,sessionCostBudgetUSD:this.sessionCostBudgetUSD,stallDetection:this.stallDetection,workspaceDir:this.workspaceDir,getWorkspaceRef:()=>this.workspaceRef,workspaceId:this._workspaceId,logger:this.logger,getResilienceConfig:()=>this.getResilienceConfig()}),de=ue.visionDelegateService;this.sessionConfigResolver=ue.sessionConfigResolver;let fe=Qd({options:e,hookRegistry:this.hookRegistry,providerRegistry:this.providerRegistry,getModelRegistry:()=>this._modelRegistry,logger:this.logger,workspaceDir:this.workspaceDir,getTools:()=>this.tools,getDeclarativeAgentProfiles:()=>this.getEnabledAgentProfiles(),getWorkspaceRef:()=>this.workspaceRef,repoRef:g,maxToolTurns:this.maxToolTurns,promptManager:this.promptManager,memory:this.storage.memory,traceStore:this.storage.traceStore,checkpointStore:this.storage.checkpointStore,clock:this.clock,devtools:this.devtools??void 0,residencyGovernor:this._residencyGovernor,getResidencyConfig:()=>this.getResidencyConfig(),visionDelegateService:de,resolveEffectiveModel:re,defaultModel:te});this.agentRuntime=fe.agentRuntime,this.codingSessionPool=fe.codingSessionPool,Ly(this);let pe=fe.swarmAgentRunner,me=$d({hookRegistry:this.hookRegistry,stream:this.codingSessionPool.stream,logger:this.logger,defaultModel:fe.defaultModel,providerRegistry:this.providerRegistry,getDeclarativeTeams:()=>this.declarativeTeams,getDeclarativeAgentProfiles:()=>this.getEnabledAgentProfiles(),getSession:e=>this.getSession(e),createSession:e=>this.createSession(e),removeSession:e=>this.removeSession(e),sessionConfigResolver:this.sessionConfigResolver,swarmAgentRunner:pe,workflowConfig:{retry:this.settings.get(`workflow`)?.retry,circuitBreaker:this.settings.get(`workflow`)?.circuitBreaker}});this.orchestrator=me.orchestrator,this.runSession=me.runSession,this.runTeam=me.runTeam,this.writeTodos=me.writeTodos,this.toolRegistry=this.initToolRegistry(e);let he=rf({toolRegistry:this.toolRegistry,hookRegistry:this.hookRegistry,settings:this.settings,workspaceDir:this.workspaceDir,logger:this.logger,getResilienceConfig:()=>this.getResilienceConfig()});this.permissionRegistry=he.permissionRegistry,this.auditLog=he.auditLog,this.mcpController=he.mcpController;let ge=he.preExistingHooks;this.extensions=af({settings:this.settings,mcpController:this.mcpController,skillRegistry:this.skillRegistry,declarativeAgentProfiles:this.declarativeAgentProfiles,workspaceDir:this.workspaceDir,pluginHomedir:this._pluginHomedir,pluginBundledDirs:this._pluginBundledDirs,onPluginToggle:(e,t)=>{this.pluginModuleManager?.emitMonitorEvent({type:t?`plugin.enabled`:`plugin.disabled`,pluginId:e})}}),this.panelBackendController=ef({mcpController:this.mcpController,callMcpTool:(e,t,n)=>this.callMcpTool(e,t,n),getActivePlugins:()=>this.activePlugins()}).panelBackendController;let _e=of({pluginInput:this.pluginInput,sigilResolvers:this.sigilResolvers,settings:this.settings,workspaceDir:this.workspaceDir,activePlugins:()=>this.activePlugins(),agentRuntime:this.agentRuntime,hookRegistry:this.hookRegistry,preExistingHooks:ge,codingSessionPoolGet:e=>this.codingSessionPool.getSession(e),logger:this.logger,registerHooks:()=>this.registerHooks()});this.ownedHookNames=_e.ownedHookNames,this.processRegistryUnsubs=_e.processRegistryUnsubs,this.i18nRegistry=new jn;let ve=tf({hookRegistry:this.hookRegistry,skillRegistry:this.skillRegistry,providerRegistry:this.providerRegistry,wireProtocolRegistry:this.wireProtocolRegistry,modelRegistry:this._modelRegistry,authStore:this._authStore,toolRegistry:this.toolRegistry,feedbackRegistry:this.feedbackRegistry,sigilResolverRegistry:this.sigilResolvers,pluginInput:this.pluginInput,workspaceDir:this.workspaceDir,activePlugins:()=>this.activePlugins(),callMcpTool:(e,t,n)=>this.callMcpTool(e,t,n),startPluginJob:({pluginId:e,title:t,prompt:n,sessionId:r})=>this.agentJobs.start({title:`[${e}] ${t}`,prompt:n,sessionId:r,origin:`plugin`}),getPluginJobSessionId:()=>this.getActiveSession()?.id,getSessionMessages:e=>this.getSession(e)?.session.messages().filter(e=>e.role===`user`||e.role===`assistant`||e.role===`tool_result`),completeText:(e,t)=>this.completeText(e,t),capabilityQuota:this.pluginCapabilityQuota,askUser:(e,t)=>this.askPluginUser(e,t),getWorkspaceKey:()=>this.workspaceRef?.key,logger:this.logger,onPluginLoadError:(e,t)=>this.pluginHealthTracker.recordError(e,t),getSchedulePort:()=>this.scheduleServiceInstance,settings:this.settings,mcpController:this.mcpController,skillRegistryForReloader:this.skillRegistry,modelCatalogManager:this.modelCatalogManager,getActivePluginsForReloader:()=>this.activePlugins(),i18nRegistry:this.i18nRegistry});this.pluginModuleManager=ve.pluginModuleManager,this.pluginProviderManager=ve.pluginProviderManager,this.capabilityReloader=ve.capabilityReloader,this.toolRegistry.onMutation=e=>{this.permissionSync.sync(this.settings.config);for(let t of e.added??[])this.pluginModuleManager.emitMonitorEvent({type:`tool.registered`,toolName:t,source:e.source});for(let t of e.removed??[])this.pluginModuleManager.emitMonitorEvent({type:`tool.unregistered`,toolName:t,source:e.source})},this.settings.on(`change`,e=>{let t=e,n=this.lastSettingsConfig;if(this.lastSettingsConfig=t,!n)return;let r=new Set([...Object.keys(n),...Object.keys(t)]),i=[];for(let e of r)n[e]!==t[e]&&i.push(e);i.length>0&&this.pluginModuleManager.emitMonitorEvent({type:`settings.changed`,keys:i})});let ye=nf({sessionConfigResolver:this.sessionConfigResolver,getSession:e=>this.codingSessionPool.getSession(e),listSessionIds:()=>this.codingSessionPool.listSessions().map(e=>e.id),logger:this.logger,workspaceDir:this.workspaceDir,settings:this.settings,pluginModuleManager:this.pluginModuleManager,mcpController:this.mcpController,getActivePlugins:()=>this.activePlugins()});this.toolsSyncCoordinator=ye.toolsSyncCoordinator,this.pluginContributionsFacade=ye.pluginContributionsFacade}deferredConfigSteps(){return[{label:`resilience-config`,apply:()=>{this.freezeResilienceConfig()}},{label:`residency-config`,apply:()=>{this.freezeResidencyConfig()}},{label:`memory-governor-thresholds`,apply:()=>{let e=this.settings.get(`residency`);e&&this._memoryGovernor.updateThresholds({warnThresholdPct:e.warn_threshold_pct,hardThresholdPct:e.hard_threshold_pct})}},{label:`auth-store-lock-timeout`,apply:()=>{this._authStore.setRefreshLockTimeoutMs(this.getResilienceConfig().oauth.refreshLockTimeoutMs)}}]}async ensureSettingsLoaded(){await sf(this.settings,()=>this.settingsLoaded,e=>{this.settingsLoaded=e}),cf(this.deferredConfigSteps())}freezeResilienceConfig(){this._resilienceConfig===void 0&&(this._resilienceConfig=l(this._resilienceOverride,this.settings.get(`resilience`)))}_residencyConfig;freezeResidencyConfig(){if(this._residencyConfig!==void 0)return;let e=this.settings.get(`residency`),t=(e,t)=>t!=null&&process.env[e]===void 0?t:void 0;this._residencyConfig={totalBytes:t(`OTTO_SESSION_TOTAL_RESIDENCY_BUDGET`,e?.total_bytes),minPerSessionBytes:t(`OTTO_SESSION_MIN_PER_SESSION_BYTES`,e?.min_per_session_bytes),maxPerSessionBytes:t(`OTTO_SESSION_MAX_PER_SESSION_BYTES`,e?.max_per_session_bytes),maxContentBytes:t(`OTTO_SESSION_MAX_CONTENT_BYTES`,e?.max_content_bytes),maxHistoryMessages:t(`OTTO_SESSION_MAX_HISTORY_MESSAGES`,e?.max_history_messages),resumeWindowMessages:t(`OTTO_SESSION_RESUME_WINDOW_MESSAGES`,e?.resume_window_messages),compactionTimeoutMs:t(`OTTO_SESSION_COMPACTION_TIMEOUT_MS`,e?.compaction_timeout_ms)}}getResidencyConfig(){return this._residencyConfig}getResilienceConfig(){if(this._resilienceConfig===void 0)throw Error(`getResilienceConfig() called before settings are loaded — call after ensureSettingsLoaded()/start()`);return this._resilienceConfig}async allowToolAlways(e,t){return Xo(this,e,t)}getPermissionMode(){return Zo(this)}async setPermissionMode(e){return Qo(this,e)}getSessionAlwaysAllow(e){return $o(this,e)}bashAlwaysAllowPrefix(e){return ve(e)}isWellFormedAllowEntry(e){return Ne(e)}async disallowToolAlways(e){return es(this,e)}clearSessionAlwaysAllow(e){ts(this,e)}activePlugins(){return this.pluginTopology.resolve({workspaceDir:this.workspaceDir,disabledPlugins:this.settings.get(`disabled_plugins`)??[],homedir:this._pluginHomedir,bundledDirs:this._pluginBundledDirs})}async diagnoseTopoSortIssues(){await this.pluginTopology.diagnose(this.logger,this.settings)}listFileCommands(){return this.pluginContributionsFacade.listFileCommands()}async callMcpTool(e,t,n){return this.pluginContributionsFacade.callMcpTool(e,t,n)}getPluginPanelRegistrations(){return this.pluginContributionsFacade.getPluginPanelRegistrations()}getPluginStatusItems(){return this.pluginContributionsFacade.getPluginStatusItems()}getGlobalMenuItems(){return this.pluginContributionsFacade.getGlobalMenuItems()}getPluginRenderers(){return this.pluginContributionsFacade.getPluginRenderers()}getPluginStatusWidgets(){return this.pluginContributionsFacade.getPluginStatusWidgets()}getPluginFileViewers(){return this.pluginContributionsFacade.getPluginFileViewers()}isFeedbackAvailable(){return this.feedbackRegistry.get()!==void 0}getPulseSurveyConfig(){return this.settings.get(`pulse_survey`)??{}}recordPulseSurvey(e){this.feedbackRegistry.get()?.recordPulseSurvey?.(e)}buildFeedbackIssueUrl(e){return this.feedbackRegistry.get()?.buildIssueUrl?.(e)}updateSettings(e){return this.settings.update(e)}resolveA2uiRendererPayload(e){return eo(Za(this.activePlugins()),e)}getPluginRegistrations(){return this.pluginContributionsFacade.getPluginRegistrations()}async firePluginActivationEvent(e){await this.pluginModuleManager.activateOn(e,new Set(this.declarativeAgentProfiles.map(e=>e.name)))}async start(){return wy(this)}async completeWorkspaceDependentStartup(){return Ty(this)}needsWorkspaceInit(){return Ey(this)}async confirmWorkspaceInit(){return Ay(this)}hasParentWorkspace(){return Dy(this)}async adoptParentWorkspace(){return Oy(this)}async createLocalWorkspace(){return ky(this)}async setWorkspaceMemorySyncEnabled(e){return jy(this,e)}async sweepOrphanTraceFiles(){return My(this)}async stop(){return Ny(this)}async createSession(e={}){return ns(this,e)}registerNotificationChannel(e){Ko(this,e)}registerInAppNotificationChannel(e){qo(this,e)}setUserAskRenderer(e){this.userAskRenderer=e}async askPluginUser(e,t){let n={...By(t),id:`plugin_ask_${++this.userAskSeq}`,askedBy:`plugin:${e}`},r=this.userAskRenderer;if(!this._interactive||!r)return zy();let i=this.inquiryCenter.enqueue({id:n.id,origin:{kind:`plugin`,pluginId:e},question:n});if(!i.accepted)return zy();if(!await this.inquiryCenter.waitForTurn(n.id))return await i.answer;try{let e=await r(n);return this.inquiryCenter.settle(n.id,e),e}catch(e){throw this.inquiryCenter.settle(n.id,zy()),e}}notifyUserInteraction(){Jo(this)}setTerminalFocus(e){Yo(this,e)}setFollowUpPendingProbe(e){this.followUpPendingProbe=e}notifyPluginServices(e){let t=gl(),n=0;for(let r of this.activePlugins())for(let i of t.runningServiceIds(r.id))t.notify(r.id,i,e)&&(this.pluginCapabilityQuota.onNotifyDelivered(r.id,e.sessionId),n+=1);return n}notifyPluginServiceSchedule(e,t){return this.activePlugins().some(t=>t.id===e.pluginId)?gl().notify(e.pluginId,e.serviceId,{type:`schedule.tick`,scheduleId:t.scheduleId,occurrenceId:t.occurrenceId,occurredAt:t.occurredAt}):!1}getSession(e){return rs(this,e)}async shareSession(e,t){return is(this,e,t)}getActiveSession(){return as(this)}listSessions(e){return os(this,e)}async listAllSessions(e){return ss(this,e)}async removeSession(e){return cs(this,e)}async exportSessionArchive(e,t){return Py(e,t,this.sessionRepoRef??{})}archiveSession(e){return ls(this,e)}async forkSession(e,t){return us(this,e,t)}getEnabledAgentProfiles(){let e=new Set(this.settings.get(`disabled_agents`)??[]);return e.size===0?this.declarativeAgentProfiles:this.declarativeAgentProfiles.filter(t=>!e.has(t.name))}initToolRegistry(e){return xy(this,e)}async buildModelCatalog(e){return Go(this,e)}setSessionAvailableModels(e,t){Uo(this,e,t)}registerHooks(){Sy(this)}get activeSandbox(){return this.sandbox.activeName}approveSandboxBypass(e){this.sandbox.approveBypass(e)}ensureNotDisposed(){if(this.disposed)throw Error(`App has been stopped and cannot be reused.`)}};function zy(){return{answer:``,acceptedRecommendation:!1,resolvedBy:`human`}}function By(e){return{header:Vy(e.header,160),question:Vy(e.question,2e3),background:Vy(e.background,4e3),recommendation:Vy(e.recommendation,1e3),...e.options?{options:e.options.slice(0,8).map(e=>({label:Vy(e.label,120),rationale:Vy(e.rationale,1e3),...e.recommended?{recommended:!0}:{}}))}:{},...e.allowFreeform===void 0?{}:{allowFreeform:e.allowFreeform},...e.multiSelect===void 0?{}:{multiSelect:e.multiSelect},...e.evidence?{evidence:e.evidence.slice(0,8).map(e=>Vy(e,1e3))}:{}}}function Vy(e,t){return String(e??``).replace(/[----]/g,` `).slice(0,t)}function Hy(e){return new Ry(e)}function Uy(e){return{get id(){return e.id},get title(){return e.title},get agentName(){return e.agentName},get model(){return{id:e.model.id,name:e.model.name,provider:e.model.provider}},get isBusy(){return e.isBusy},messageCount:()=>e.session.messages().length,lastAssistantText:()=>ko(e.session.messages()),prompt:(t,n)=>e.prompt(t,n),subscribe:((t,n)=>e.subscribe(t,n)),resolveApproval:(t,n)=>e.resolveApproval(t,n),resolveAskUser:(t,n)=>e.resolveAskUser(t,n),clearContext:()=>e.clearContext(),compactNow:()=>e.compactNow(),renameSession:t=>e.renameSession(t),abort:()=>e.abort(),dispose:()=>e.dispose()}}function Wy(e){return{createSession:async t=>Uy(await e.createSession(t)),jobs:Lt,models:{getAll:()=>e.modelRegistry.getAll().map(e=>({id:e.id,name:e.name,provider:e.provider})),switchModel:async(t,n)=>{let r=e.getSession(t);if(!r)return`会话未找到`;if(r.isBusy)return`当前有正在执行的对话,请等待完成后重试。`;let i=e.modelRegistry.find(n);return i?(r.model=i,null):`未知模型 \`${n}\`。`},refresh:async()=>(await e.refreshModels()).map(e=>({provider:e.provider,status:e.status,added:e.added,kept:e.kept,total:e.total,reason:e.reason}))},permission:{getMode:()=>e.getPermissionMode(),setMode:t=>e.setPermissionMode(t)},auth:{getAuthSource:t=>e.authStore.getAuthSource(t)},i18n:{t:(t,n)=>e.i18nRegistry.t(t,n)},reloadCapabilities:()=>e.reloadCapabilities(),workspaceDir:e.workspaceDir}}const Gy=new Set(`assert.async_hooks.buffer.child_process.cluster.console.constants.crypto.dgram.diagnostics_channel.dns.domain.events.fs.http.http2.https.inspector.module.net.os.path.perf_hooks.process.punycode.querystring.readline.repl.sqlite.stream.string_decoder.timers.tls.trace_events.tty.url.util.v8.vm.wasi.worker_threads.zlib`.split(`.`));function Ky(e){return e.absolutePaths.length>0||e.bareSpecifiers.length>0}function qy(e){let t=[],n=[];for(let r of e.matchAll(/require\("([^"]+)"\)/g)){let e=r[1];if(e.startsWith(`/`)){t.includes(e)||t.push(e);continue}e.startsWith(`.`)||e.startsWith(`node:`)||Gy.has(e)||n.includes(e)||n.push(e)}return{absolutePaths:t,bareSpecifiers:n}}function Jy(e,t){let n=qy(t);if(!Ky(n))return;let r=[`${e}: 产物不可分发(RFC-365 R1/R2)`];throw n.absolutePaths.length>0&&r.push(` 编译机绝对路径 require(R1)——发布机路径在用户机器不存在:`,...n.absolutePaths.map(e=>` ${e}`)),n.bareSpecifiers.length>0&&r.push(` 裸模块名 require(R2)——假设运行机有 node_modules,在 ~/.otto/plugins/<id>/ 必然 MODULE_NOT_FOUND:`,...n.bareSpecifiers.map(e=>` ${e}`)),Error(r.join(`
|
|
504
504
|
`))}function Yy(e,t){return new Promise((n,r)=>{let i=setTimeout(()=>r(Error(`timeout`)),t);i.unref?.(),e.then(e=>{clearTimeout(i),n(e)},e=>{clearTimeout(i),r(e)})})}function Xy(e,t=E){let n=t(e);return n.gated||!(e.manifest.capabilities?.includes(`tools`)??!1)?!1:!n.pendingCapabilities.includes(`tools`)}async function Zy(e,t,n){let r=[];for(let i of e){if(!Xy(i,t))continue;let e=i.manifest.contributes?.perfMetrics;if(!e?.length)continue;let a=Ul(i.scope);for(let t of e){let e=(async()=>{try{let{result:e,error:n}=await Yy(a.executeTool(i.id,t.toolRef,{}),5e3);return n?{id:t.id,label:t.label,error:n}:{id:t.id,label:t.label,value:e}}catch(e){let r=e instanceof Error?e.message:String(e);return r===`timeout`&&n?.(i.id),{id:t.id,label:t.label,error:r}}})();r.push(e)}}return(await Promise.allSettled(r)).map((e,t)=>e.status===`fulfilled`?e.value:{id:`unknown-${t}`,label:`unknown`,error:String(e.reason)})}const Qy=20;function $y(e,t=20){let n=ac(e);if(!n||!D(n))return[];let r;try{r=k(n,`utf8`)}catch{return[]}let i=r.split(`
|
|
505
505
|
`).filter(e=>e.trim().length>0).slice(-t),a=[];for(let e of i)try{a.push(JSON.parse(e))}catch{}return a}function eb(e,t,n){let r=e?.manifest.contributes?.contextKeys;return{...t,...Un(r,n)}}function tb(e,t){let n=e.manifest.scripts?.[t];if(!n)return Promise.reject(Error(`plugin ${e.id} 无脚本「${t}」`));let r=Ye(n);return r.safe?new Promise((r,i)=>{let a=Oi(n,{shell:!0,cwd:e.dir,stdio:`ignore`,env:Je()});a.on(`error`,i),a.on(`exit`,e=>e===0?r():i(Error(`脚本「${t}」退出码 ${e}`)))}):Promise.reject(Error(`脚本「${t}」被安全检查拦截:${r.reason}`))}function nb(e){let t=e.startsWith(`chrome://`);process.platform===`darwin`?Oi(`open`,t?[`-a`,`Google Chrome`,e]:[e],{detached:!0,stdio:`ignore`}).unref():process.platform===`win32`?Oi(`cmd`,[`/c`,`start`,``,e],{detached:!0,stdio:`ignore`}).unref():Oi(t?`google-chrome`:`xdg-open`,[e],{detached:!0,stdio:`ignore`}).unref()}const rb=C(`@x-otto/coding:plugin-cli-passthrough`);function ib(e){let t=e.manifest.contributes?.cli?.bin,n=t?x(e.dir,t):ab(e.dir);if(n)return ob(n,e.dir)}function ab(e){let t=x(e,`package.json`);if(D(t))try{let n=JSON.parse(k(t,`utf8`));if(typeof n.bin==`string`)return x(e,n.bin);if(n.bin&&typeof n.bin==`object`){let t=Object.values(n.bin)[0];return typeof t==`string`?x(e,t):void 0}return}catch{return}}function ob(e,t){if(!D(e))return;let n,r;try{n=Jr(e),r=Jr(t)}catch{return}let i=r.endsWith(`/`)?r:`${r}/`;if(!n.startsWith(i)&&n!==r){rb.warn({candidate:e,pluginDir:t},`Plugin CLI bin resolves outside plugin directory (symlink escape rejected)`);return}try{if(!Zr(n).isFile())return}catch{return}return n}function sb(e,t){let n=new Map;for(let r of e){let e=r.manifest.contributes?.cli?.name;if(!e)continue;if(t.has(e)){rb.warn({pluginId:r.id,name:e},`Plugin CLI contribution name collides with a built-in command; ignored`);continue}let i=n.get(e);i?i.push(r):n.set(e,[r])}return n}function cb(e,t){let n=sb(e,t),r=new Map;for(let[e,t]of n){if(t.length===1){r.set(e,t[0]);continue}rb.warn({name:e,conflictingPluginIds:t.map(e=>e.id)},`Plugin CLI contribution name claimed by multiple plugins; command disabled (fail-closed, RFC-124 §10.2.2 — rename one of the conflicting plugins to resolve)`)}return r}function lb(e,t,n){let r=sb(e,t).get(n);return r&&r.length>=2?r.map(e=>e.id):void 0}function ub(e,t,n,r=6e4){return new Promise((i,a)=>{let o=Oi(e,t,{stdio:`inherit`,cwd:n,env:Je()}),s=setTimeout(()=>{o.kill(`SIGTERM`),a(Error(`插件 CLI 执行超时(${r}ms),已终止子进程`))},r);s.unref(),o.on(`error`,e=>{clearTimeout(s),a(e)}),o.on(`exit`,(e,t)=>{clearTimeout(s),i(e??(t?1:0))})})}function db(e,t={}){return Vn({cwd:t.workspaceDir??process.cwd(),homedir:t.homedir??ze(),bundledDirs:t.bundledDirs}).find(t=>t.id===e)}function fb(e,t,n={}){let r=db(e,n);if(!r)return{ok:!1,reason:`plugin-not-found`,granted:[],pending:[],message:`Plugin "${e}" not found. Install it first, or check workspaceDir/homedir options.`};let i=(r.manifest?.capabilities??[]).filter(e=>xn.includes(e)),a=t??[],o=a.filter(e=>!xn.includes(e));if(o.length>0)return{ok:!1,reason:`unknown-capability`,granted:[],pending:i,message:`Unknown capability: ${o.join(`, `)}. Valid high-risk capabilities: ${xn.join(`, `)}.`};let s=a.filter(e=>!i.includes(e));if(s.length>0)return{ok:!1,reason:`capability-not-declared`,granted:[],pending:i,message:`Plugin "${e}" does not declare capability: ${s.join(`, `)}. Declared: ${i.length?i.join(`, `):`(none)`}.`};cr(r.dir),a.length>0&&Jn(r.dir,a);let c=E(r);return{ok:!0,granted:[...a],pending:c.pendingCapabilities}}function pb(e,t={}){let n=db(e,t);if(!n)return{found:!1,trusted:!1,gated:!1,declared:[],granted:[],pending:[]};let r=E(n),i=(n.manifest?.capabilities??[]).filter(e=>xn.includes(e));return{found:!0,trusted:r.trusted,gated:r.gated,declared:[...i],granted:[...r.grantedCapabilities],pending:[...r.pendingCapabilities]}}function mb(e,t={}){let n=db(e,t);return n?(ur(n.dir),!0):!1}const hb=C(`@x-otto/coding:plugin-theme-preset-loader`),gb=new Set([`dark`,`light`,`system`,`builtin`]);function _b(e){let t=[];for(let n of e){let e=n.manifest.contributes?.themePresets;if(!e?.length)continue;if(E(n).gated){hb.warn({pluginId:n.id},`plugin gated (untrusted), themePresets skipped`);continue}let r=e;r.length>Dn&&(hb.warn({pluginId:n.id,declared:r.length,limit:Dn},`plugin declares more theme presets than the per-plugin limit, truncated`),r=r.slice(0,Dn));for(let e of r){if(gb.has(e.localId)){hb.warn({pluginId:n.id,localId:e.localId},`themePresets localId collides with a reserved name, skipped`);continue}t.push({pluginId:n.id,localId:e.localId,label:e.label,appearance:e.appearance,colors:e.colors,markdown:e.markdown,meta:e.meta})}}return t}export{yo as AgentJobService,pt as AgentSession,Ry as App,bt as CodingSessionPool,Qv as DEFAULT_WORKSPACE_KEY,Pa as ExtensionManager,bn as HIGH_RISK_CAPABILITIES,Zv as INDUCTOR_PLUGIN_ID,Ji as InstallManager,Qy as PLUGIN_LOG_TAIL_LINES,kn as PLUGIN_MANIFEST_FILENAME,An as POINT,Yi as RegistryClient,ty as SANDBOX_ESCALATION_MARKER,Bi as SCHEDULE_LEASE_MIGRATIONS,yt as SandboxUnavailableError,Vi as ScheduleRegistry,Hi as SchedulerService,Ia as SigilResolverRegistry,m as apiCredentialId,Jy as assertPortableArtifact,fb as authorizePlugin,eb as buildExtensionContext,pa as buildMemoryStore,cb as buildPluginCliRegistry,Xi as builtinOfficialSource,wt as captureFiles,Zi as checkArchiveBomb,Qi as checkGitUpgrades,ad as checkPluginConsistency,$i as checkUpgrades,dr as claudeTrustStorePath,ea as cleanTempDir,Zy as collectPluginPerfMetrics,_b as collectPluginThemePresets,Qc as compilePluginModule,Gu as compilePluginPanels,tl as computeSourceHash,Hy as createApp,ta as createArchive,Nn as createBuiltinHashtags,Jd as createBuiltinResolvers,fr as createClaudeHookBridgeHooks,Fn as createFileProvider,Wy as createFrontendPort,bf as createLessonInjectionHooks,Ui as createLocalFireOwnership,Ln as createPluginInputRegistry,Wi as createRemoteFireOwnership,Gi as createRemoteScheduleStore,qi as createScheduleStore,Ot as createSessionStableInjectionHooks,xf as createSkillCatalogInjectionHooks,na as createTempDir,df as createToolGuidanceHook,mr as defaultHookRunner,Nt as defaultMaxToolTurnExtensions,js as defaultPostInstallExecutor,Ft as deriveSessionTitle,hr as detectClaudeExecutableSurface,zn as detectPluginExecutableSurface,gr as detectProjectConfigGating,ra as detectUninstallTarget,_r as discoverFileCommands,Bn as discoverPlugins,Hn as dispatch,yr as evaluateClaudeTrust,Wn as evaluatePluginTrust,xr as evaluateWorkspaceTrustPrompt,Sr as expandCommandBody,Ga as expandSigilChips,ia as extractArchive,lb as findPluginCliNameConflict,qy as findPortabilityViolations,i as findWorkspaceRoot,Pc as getEsbuildModule,Ao as getIncompleteSubagentReason,ko as getLastAssistantText,It as globalAgentJobRegistry,Rt as globalAgentObservability,Bt as globalProcessRegistry,qn as grantPluginCapabilities,Yn as grantedPluginCapabilities,Ky as hasPortabilityViolations,pb as inspectPluginAuthorization,Lc as installEsbuildExitHook,zc as installEsbuildSignalBridges,ed as installPluginFromDir,$u as installPluginFromPackage,Xc as installPluginHostExternals,Cr as interpretPreToolUse,cd as isInternalDelegatedSession,Xn as isPluginTrusted,wr as isProjectTrusted,Er as isStrictProjectConfigEnabled,aa as listInstalledItems,Dr as loadClaudeHooksConfig,sl as loadPluginModule,Fc as markEsbuildStarted,kr as matchesHookMatcher,Gt as messagesFromSnapshot,nb as openTarget,Ar as parseClaudeHooks,jr as parseDotMcpJson,Qn as parsePluginManifest,oa as parseRegistry,er as pluginTrustStorePath,Pu as purgePluginState,tr as readHighRiskCapabilities,$y as readPluginLogTail,cy as readSkillLoopStatus,go as readTaskOutputTail,Kt as reconstructMessages,rd as recordPluginInstalled,id as recordPluginUninstalled,nd as removeInstalledPluginEntry,nr as resolveActions,Nr as resolveClaudeMcpServers,Yc as resolveHostExternalPaths,Qu as resolvePackageDir,ib as resolvePluginCliBin,Ea as resolvePluginMcpServers,Fr as resolveProjectConfigTrusted,Jt as resolveSessionTitle,Xt as restoreFiles,mb as revokePluginAuthorization,rl as rewriteArtifactSourceHash,tb as runPluginScript,sa as scanInstalledVersions,ar as sigilOf,ub as spawnPluginCli,Ic as stopEsbuildService,sr as trustPlugin,Lr as trustProject,ca as uninstall,lr as untrustPlugin,Rr as untrustProject,td as upsertInstalledPluginEntry,la as validateExtractedPaths,Bc as withBuildTimeout};
|
|
506
506
|
//# sourceMappingURL=index.js.map
|