@gencode/agents 0.16.0 → 0.16.1

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.
@@ -0,0 +1,4 @@
1
+ import{i as e,t}from"./provider-registry-DPbmbWqS.js";import{n}from"./loader-CkdBGDtW.js";import{validateUiToolResult as r}from"@gencode/shared";import i from"node:path";import a from"node:os";import{AsyncLocalStorage as o}from"node:async_hooks";import s from"node:fs";import c from"log4js";import{Type as l}from"@earendil-works/pi-ai";import u from"ajv";import{createJiti as d}from"jiti";function f(e){return e??`openai-completions`}function p(e,t,n){let r={"Client-Code":`AIMax`,"X-Session-Id":e};return t&&(r[`X-Message-Id`]=t),n&&(r[`X-Channel`]=n),r}function m(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}const h={apiFormat:`anthropic-messages`,createModel:g,buildRequest:v,normalizeResponse:y};function g(e,t,n,r){return{id:e.model,name:e.model,api:`anthropic-messages`,provider:`anthropic`,baseUrl:_(e.baseUrl),reasoning:!1,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:p(t,n,r)}}function _(e){return e.replace(/\/+$/,``).replace(/\/v1$/,``)}function v(e,t,n,r){let i=e.baseUrl.replace(/\/+$/,``),a=[],o=[];for(let e of n){if(e.role===`system`){e.content.trim()&&o.push(e.content);continue}a.push({role:e.role,content:e.content})}let s={model:t,messages:a.length>0?a:[{role:`user`,content:``}],max_tokens:r.maxTokens??2048,stream:!1};return o.length>0&&(s.system=o.join(`
2
+
3
+ `)),typeof r.temperature==`number`&&(s.temperature=r.temperature),{url:i.endsWith(`/v1`)?`${i}/messages`:`${i}/v1/messages`,headers:{"content-type":`application/json`,"x-api-key":e.apiKey,"anthropic-version":`2023-06-01`,"Client-Code":`AIMax`},body:s}}function y(e){let t=e,n=t.content?.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``)??``,r=(t.usage?.input_tokens??0)+(t.usage?.cache_read_input_tokens??0)+(t.usage?.cache_creation_input_tokens??0),i=t.usage?.output_tokens??0;return{text:n,usage:{input:r,output:i,total:r+i},raw:e}}const b={apiFormat:`openai-completions`,createModel:ee,buildRequest:te,normalizeResponse:ne};function ee(e,t,n,r){let i=e.baseUrl.includes(`deepseek.com`),a=e.thinking;return{id:e.model,name:e.model,api:`openai-completions`,provider:i?`deepseek`:`openai`,baseUrl:e.baseUrl,reasoning:i||!!a,...i&&{thinkingLevelMap:{high:`high`,xhigh:`max`}},...a&&!i&&{thinkingLevelMap:{high:`high`,xhigh:`high`}},input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:p(t,n,r),compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!!(a&&!i),supportsUsageInStreaming:!0,...a&&!i&&{thinkingFormat:`deepseek`}}}}function te(e,t,n,r){let i={model:t,messages:n,stream:!1};return typeof r.temperature==`number`&&(i.temperature=r.temperature),typeof r.maxTokens==`number`&&(i.max_tokens=r.maxTokens),{url:`${e.baseUrl.replace(/\/+$/,``)}/chat/completions`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:i}}function ne(e){let t=e;return{text:t.choices?.[0]?.message?.content??t.choices?.[0]?.text??``,usage:m(t.usage),raw:e}}const re={"openai-completions":b,"anthropic-messages":h};function ie(e){return re[e]}const ae=new o;async function oe(e,t){return await ae.run(e,t)}function se(e){return{async emit(t){let n=ae.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const ce={before_prompt_build:`before_agent_start`,after_tool_call:`tool_result (for mutable results) or before_tool_call (for blocking)`},le=new Set([`before_model_resolve`,`before_prompt_build`,`before_agent_start`,`before_tool_call`,`tool_result`,`before_compaction`,`context`,`before_provider_request`,`dream_gate`,`input`,`resources_discover`]);var ue=class extends Error{constructor(e,t,n){super(`Plugin hook "${e}" timed out after ${n}ms (plugin: ${t})`),this.hookName=e,this.pluginId=t,this.timeoutMs=n,this.name=`PluginHookTimeoutError`}},de=class{hooks=new Map;deprecatedWarned=new Set;blockingTimeoutMs;bestEffortTimeoutMs;constructor(e={}){this.blockingTimeoutMs=fe(e.blockingTimeoutMs,1e4),this.bestEffortTimeoutMs=fe(e.bestEffortTimeoutMs,3e3)}register(e){let t=ce[e.hookName];t&&!this.deprecatedWarned.has(e.hookName)&&(this.deprecatedWarned.add(e.hookName),console.warn(`[PluginHookRegistry] Hook "${e.hookName}" is deprecated. Use "${t}" instead. (plugin: ${e.pluginId})`));let n=this.hooks.get(e.hookName)??[];n.push(e),n.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,n)}async dispatch(e,t,n,r){return(await this.dispatchWithMetadata(e,t,n,r)).map(e=>e.result)}async dispatchWithMetadata(e,t,n,r){let i=this.hooks.get(e)??[],a=[],o=this.getDispatchPolicy(e);for(let s of i){let i=pe(n),c=async()=>await s.handler(t,i.ctx);try{let t=await me(r?oe({pluginId:s.pluginId,hookContext:i.ctx,eventDispatcher:r.eventDispatcher},c):c(),{hookName:e,pluginId:s.pluginId,timeoutMs:o.timeoutMs,abort:i.abort});i.clear(),a.push({pluginId:s.pluginId,source:s.source,result:t})}catch(t){if(i.clear(),o.mode===`blocking`)throw t;await he({runtime:r,ctx:n,hookName:e,entry:s,policy:o,error:t})}}return a}getDispatchPolicy(e){return le.has(e)?{mode:`blocking`,timeoutMs:this.blockingTimeoutMs}:{mode:`bestEffort`,timeoutMs:this.bestEffortTimeoutMs}}};function fe(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:t}function pe(e){let t=new AbortController,n;return e.signal&&(e.signal.aborted?t.abort():(n=()=>t.abort(),e.signal.addEventListener(`abort`,n,{once:!0}))),{ctx:{...e,signal:t.signal},abort:()=>t.abort(),clear:()=>{n&&e.signal&&e.signal.removeEventListener(`abort`,n)}}}async function me(e,t){let n;try{return await Promise.race([e,new Promise((e,r)=>{n=setTimeout(()=>{t.abort(),r(new ue(t.hookName,t.pluginId,t.timeoutMs))},t.timeoutMs),n.unref?.()})])}finally{n&&clearTimeout(n)}}async function he(e){if(!e.runtime||!e.ctx.sessionId)return;let t=e.error instanceof ue;await e.runtime.eventDispatcher.dispatchProgress(e.ctx.sessionId,{type:`diagnostic`,level:`warn`,scope:`plugin`,phase:t?`hook_timeout`:`hook_failed`,message:t?`plugin hook timed out: ${e.hookName}`:`plugin hook failed: ${e.hookName}`,details:{hookName:e.hookName,pluginId:e.entry.pluginId,source:e.entry.source,mode:e.policy.mode,timeoutMs:e.policy.timeoutMs,error:e.error instanceof Error?e.error.message:String(e.error)}}).catch(()=>{})}function ge(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function _e(e=new Date){let t=ge(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let x=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});const S=new o;function ve(e,t){return S.run(e,t)}let C=null,w=!1,T=[];function ye(){return _e()}function be(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function xe(e){return i.join(e,`.aimax`)}function Se(e){let t=e?.trim();return t&&t.replace(/[^A-Za-z0-9_.-]/g,`_`)||`no-message-${process.pid}`}function Ce(e,t){let n=t?.sessionStoreName?.trim()||`sessions`,r=Se(t?.messageId);return t?.sessionDir?{runLogId:r,logDir:i.join(t.sessionDir,`logs`,r)}:t?.sessionId?{runLogId:r,logDir:i.join(xe(e),n,t.sessionId,`logs`,r)}:{runLogId:r,logDir:i.join(xe(e),`logs`,r)}}function we(e){return{appLogPath:i.join(e,`app.log`),errorLogPath:i.join(e,`errors.log`)}}function E(e){let{appLogPath:t,errorLogPath:n}=we(e);c.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function D(e,t,n){return`[${ye()}] [${e}] ${t}${be(n)}`}function Te(e,t,n){let r=S.getStore();if(r){r({level:e,message:t,context:n,formatted:D(e,t,n)});return}try{process.stderr.write(`${D(e,t,n)}\n`)}catch{}}function O(e,t,n){if(!C){T.push({level:e,message:t,context:n}),T.length>200&&(T=T.slice(-200)),Te(e,t,n);return}w||=(E(C.logDir),!0);let r=D(e,t,n),i=c.getLogger();e===x.ERROR?i.error(r):e===x.WARN?i.warn(r):i.info(r);let a=S.getStore();a&&a({level:e,message:t,context:n,formatted:r})}function Ee(e,t){let{logDir:n,runLogId:r}=Ce(e,t);if(w&&C?.dataDir===e&&C.runLogId===r&&C.logDir===n)return;s.mkdirSync(n,{recursive:!0}),E(n),w=!0,C={dataDir:e,logDir:n,runLogId:r};let i=T;T=[];for(let e of i)O(e.level,e.message,e.context)}async function De(){await c.shutdown(),w=!1}const k={info:(e,t)=>O(x.INFO,e,t),warn:(e,t)=>O(x.WARN,e,t),error:(e,t)=>O(x.ERROR,e,t)};function Oe(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}var A=class extends Error{code;statusCode;statusText;providerMessage;providerCode;providerType;retryable;constructor(e){super(e.message,{cause:e.cause}),this.name=`LlmRequestError`,this.code=e.code,this.statusCode=e.statusCode,this.statusText=e.statusText,this.providerMessage=e.providerMessage,this.providerCode=e.providerCode,this.providerType=e.providerType,this.retryable=e.retryable}};function ke(e){return{async chat(t){let n=je(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await Ne(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:Me(n),historyMessages:n},e.hookCtx);let i=ie(f(e.apiFormat)),a=i.buildRequest(e,r,n,t),{signal:o,clear:s,didTimeout:c}=Pe(t.signal,t.timeoutMs);try{let t;try{t=await fetch(a.url,{method:`POST`,headers:a.headers,body:JSON.stringify(a.body),signal:o})}catch(e){throw Ie(e,c())}if(!t.ok){let e=await Fe(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new A({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:Le(t.status)})}let n=Date.now(),s;try{s=await t.json()}catch(e){throw Ae(e,c())}let{text:l,usage:u}=i.normalizeResponse(s),d=Math.max(0,Date.now()-n);return await Ne(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:l?[l]:[],durationMs:d,usage:u},e.hookCtx),{text:l,usage:u,raw:s}}finally{s()}}}}function Ae(e,t){return j(e)&&t?new A({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):j(e)?new A({message:`LLM request was aborted`,code:`aborted`,retryable:!0,cause:e}):new A({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}function je(e){if(Array.isArray(e.messages)&&e.messages.length>0)return e.messages;let t=[];if(e.system?.trim()&&t.push({role:`system`,content:e.system}),e.user?.trim()&&t.push({role:`user`,content:e.user}),t.length===0)throw Error(`LLM messages are required`);return t}function Me(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
4
+ `)}async function Ne(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function Pe(e,t){if(!e&&(!t||t<=0))return{signal:void 0,clear:()=>{},didTimeout:()=>!1};let n=new AbortController,r,i=!1;return e&&(e.aborted?n.abort():e.addEventListener(`abort`,()=>n.abort(),{once:!0})),t&&t>0&&(r=setTimeout(()=>{i=!0,n.abort()},t)),{signal:n.signal,clear:()=>{r&&clearTimeout(r)},didTimeout:()=>i}}async function Fe(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function Ie(e,t){return e instanceof A?e:j(e)?t?new A({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new A({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function j(e){return e instanceof Error&&e.name===`AbortError`}function Le(e){return e===408||e===409||e===425||e===429||e>=500}var M=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,outputSchema:i,extra:a,createdAt:new Date().toISOString()}}};function Re(e){return!!(e instanceof M||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const N=new o;function ze(){return{}}async function Be(e,t){return await N.run(e,t)}function Ve(e){let t=N.getStore();!t||t.signal||(t.signal=e)}const P=l.Object({reason:l.String({description:`A brief explanation of why user input is needed through this UI form.`})});function F(e){let{name:t,label:n,description:i,sessionId:a,inputSchema:o,outputSchema:s,extra:c,validate:l,resume:u}=e;return{name:t,label:n,description:i,parameters:o??P,async execute(e,n){if(u&&u.toolCallId===e&&u.toolName===t&&u.sessionId===a){let e=r(s,u.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(l){let e=await l(u.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:u.values})}],details:{}}}let i=new M(e,a,t,e,s,c,n);throw Ve(i),i}}}const I=Symbol(`pluginToolOwner`);var L=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,I,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}registerUiTool(e,t,n){this.uiTools.push({pluginId:e,descriptor:t,optional:n?.optional??!1})}list(){return[...this.tools]}listUiTools(){return[...this.uiTools]}namesForPlugin(e){let t=this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names),n=this.uiTools.filter(t=>t.pluginId===e).map(e=>e.descriptor.name);return[...t,...n]}resolveEnabled(e){let t=new Set((e??[]).map(e=>e.trim()).filter(Boolean));return this.tools.filter(e=>{if(!e.optional)return!0;if(t.size===0)return!1;if(t.has(e.pluginId))return!0;for(let n of e.names)if(t.has(n))return!0;return!1}).map(e=>e.tool)}resolveUiTools(e,t,n){let r=new Set((n??[]).map(e=>e.trim()).filter(Boolean));return this.uiTools.filter(e=>e.optional?r.size===0?!1:!!(r.has(e.pluginId)||r.has(e.descriptor.name)):!0).map(n=>{let r=F({name:n.descriptor.name,label:n.descriptor.label,description:n.descriptor.description,sessionId:e,inputSchema:n.descriptor.inputSchema,outputSchema:n.descriptor.outputSchema,extra:n.descriptor.extra,validate:n.descriptor.validate,resume:t});return Object.defineProperty(r,I,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function He(e){return e[I]}function R(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function z(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function B(){let e=a.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Ue(e){let t=e.trim(),n=B();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?i.join(n,t.slice(2)):void 0:i.resolve(t)}const We=new u({allErrors:!0,strict:!1}),Ge=new Map;function Ke(e,t){let n=Ge.get(t);if(n)return n;let r=We.compile(e);return Ge.set(t,r),r}function qe(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Ke(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function Je(e){let t=z(e?.allow),n=z(e?.deny),r=z(e?.load?.paths),i=z(e?.piExtensions?.paths),a=e?.entries??{},o=e?.slots??{};return{enabled:e?.enabled??!0,allow:Array.from(new Set(t)),deny:Array.from(new Set(n)),loadPaths:Array.from(new Set(r)),piExtensionPaths:Array.from(new Set(i)),entries:a,slots:o}}function Ye(e){let t=[],{config:n,registry:r}=e,i=new Set(r.manifests.keys()),a=(e,n)=>i.has(e)?!0:(t.push({level:`error`,message:`unknown plugin id in ${n}: ${e}`,pluginId:e}),!1);for(let e of n.allow)a(e,`plugins.allow`);for(let e of n.deny)a(e,`plugins.deny`);for(let e of Object.keys(n.entries))a(e,`plugins.entries`);let o=n.slots??{};for(let[e,n]of Object.entries(o)){if(!n||n===`none`||!a(n,`plugins.slots.${e}`))continue;let i=r.manifests.get(n);i?.manifest.kind?i.manifest.kind!==e&&t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n}):t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n})}for(let[e,i]of Object.entries(n.entries)){let n=r.manifests.get(e);if(!n)continue;let a=n.manifest.configSchema,o=qe({schema:a,cacheKey:`${e}:${n.manifestPath}`,value:i?.config??{}});if(!o.ok)for(let n of o.errors)t.push({level:`error`,message:`plugin config invalid (${e}) at ${n.path}: ${n.message}`,pluginId:e});i?.enabled===!1&&i?.config&&t.push({level:`warn`,message:`plugin config set while disabled: ${e}`,pluginId:e})}return{ok:t.every(e=>e.level!==`error`),diagnostics:t}}function V(e){try{return s.realpathSync(e)}catch{return null}}function Xe(e){try{return s.statSync(e)}catch{return null}}function H(e,t){let n=i.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!i.isAbsolute(n)}function Ze(e){return`0o${e.toString(8).padStart(3,`0`)}`}const U=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Qe=[`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`];function $e(e){let t=i.join(e,`package.json`);if(s.existsSync(t))try{let e=JSON.parse(s.readFileSync(t,`utf-8`));return R(e)?e:void 0}catch{return}}function et(e){let t=e?.aimax?.extensions;if(!Array.isArray(t))return{status:`missing`,entries:[]};let n=t.map(e=>typeof e==`string`?e.trim():``).filter(Boolean);return n.length===0?{status:`empty`,entries:[]}:{status:`ok`,entries:n}}function tt(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function nt(e){let t=V(e.source),n=V(e.rootDir);return!t||!n||H(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function rt(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=i.resolve(r);if(n.has(t))continue;n.add(t);let a=Xe(r);if(!a)return{reason:`path_stat_failed`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r};let o=a.mode&511;if(o&2)return{reason:`path_world_writable`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,modeBits:o};if(e.origin!==`bundled`&&e.uid!==null&&typeof a.uid==`number`&&a.uid!==e.uid&&a.uid!==0)return{reason:`path_suspicious_ownership`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,foundUid:a.uid,expectedUid:e.uid}}return null}function it(e){return nt({source:e.source,rootDir:e.rootDir})||rt({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:tt(e.ownershipUid)})}function at(e){return e.reason===`source_escapes_root`?`blocked plugin candidate: source escapes plugin root (${e.sourcePath} -> ${e.sourceRealPath}; root=${e.rootRealPath})`:e.reason===`path_stat_failed`?`blocked plugin candidate: cannot stat path (${e.targetPath})`:e.reason===`path_world_writable`?`blocked plugin candidate: world-writable path (${e.targetPath}, mode=${Ze(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function W(e){let t=it({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:at(t),source:e.source}),!0):!1}function G(e){return i.basename(e,i.extname(e))}function K(e){return{idHint:e.idHint,source:e.source,rootDir:e.rootDir,origin:e.origin,workspaceDir:e.workspaceDir,packageName:e.packageName,packageVersion:e.packageVersion,packageDescription:e.packageDescription,packageDir:e.packageDir,packageManifest:e.packageManifest}}function ot(e){for(let t of Qe){let n=i.join(e,t);if(s.existsSync(n))return n}return null}function q(e){let t;try{t=s.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=i.join(e.rootDir,n.name);if(n.isFile()){if(!U.has(i.extname(n.name)))continue;let r=i.dirname(t);if(W({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(K({idHint:G(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=$e(t),a=et(r);if(a.status===`ok`){for(let n of a.entries){let a=i.resolve(t,n);if(!H(t,a)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:a});continue}if(!s.existsSync(a)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${a}`,source:a});continue}if(!U.has(i.extname(a))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${a}`,source:a});continue}if(W({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let o=r?.name?.trim(),c=o?`${o}/${G(a)}`:G(a);e.candidates.push(K({idHint:c,source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir,packageName:r?.name,packageVersion:r?.version,packageDescription:r?.description,packageDir:t,packageManifest:r?.aimax}))}continue}let o=ot(t);o&&(W({source:o,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(K({idHint:i.basename(t),source:o,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function st(e){return e?e.map(Ue).filter(e=>typeof e==`string`&&e.length>0):[]}function ct(){let e=B();if(e)return i.join(e,`.aimax`,`extensions`)}function lt(e){return i.join(e,`.aimax`,`extensions`)}function ut(e){return i.join(e,`.aimax`,`extensions`)}function dt(e={}){let t=[],n=[],r=st(e.extraPaths);for(let a of r){if(!s.existsSync(a)){n.push({level:`warn`,message:`plugin path not found: ${a}`,source:a});continue}let r=Xe(a);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${a}`,source:a});continue}if(r.isFile()){if(!U.has(i.extname(a))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${a}`,source:a});continue}let r=i.dirname(a);if(W({source:a,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(K({idHint:G(a),source:a,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&q({rootDir:a,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?q({rootDir:lt(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&q({rootDir:ut(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let a=ct();return a?q({rootDir:a,origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):n.push({level:`warn`,message:`skipping global plugin discovery: home directory is unavailable`}),e.bundledDir&&q({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function ft(e){let t=e.rejectHardlinks??!0,n=V(e.rootPath),r=V(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!H(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=s.lstatSync(r)}catch{return{ok:!1,reason:`stat`}}if(t&&typeof i.nlink==`number`&&i.nlink>1)return{ok:!1,reason:`hardlink`};try{return{ok:!0,fd:s.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const J=`aimax.plugin.json`,pt=[J];function mt(e){for(let t of pt){let n=i.join(e,t);if(s.existsSync(n))return n}return i.join(e,J)}function ht(e,t=!0){let n=mt(e),r=ft({absolutePath:n,rootPath:e,rejectHardlinks:t});if(!r.ok){let e=r.reason;return e===`path`?{ok:!1,error:`plugin manifest not found: ${n}`,manifestPath:n}:{ok:!1,error:`unsafe plugin manifest path: ${n} (${e})`,manifestPath:n}}let i;try{i=JSON.parse(s.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{s.closeSync(r.fd)}if(!R(i))return{ok:!1,error:`plugin manifest must be an object`,manifestPath:n};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,error:`plugin manifest requires id`,manifestPath:n};let o=R(i.configSchema)?i.configSchema:null;if(!o)return{ok:!1,error:`plugin manifest requires configSchema`,manifestPath:n};let c=typeof i.kind==`string`?i.kind:void 0,l=typeof i.name==`string`?i.name.trim():void 0,u=typeof i.description==`string`?i.description.trim():void 0,d=typeof i.version==`string`?i.version.trim():void 0,f=z(i.skills),p;return R(i.uiHints)&&(p=i.uiHints),{ok:!0,manifest:{id:a,configSchema:o,kind:c,name:l,description:u,version:d,skills:f,uiHints:p},manifestPath:n}}function gt(e){let t=new Map,n=[];for(let r of e){let e=ht(r.rootDir);if(!e.ok){n.push({level:`error`,message:e.error,source:r.source,pluginId:r.idHint});continue}let i=e.manifest.id;if(t.has(i)){n.push({level:`warn`,message:`duplicate plugin id ignored: ${i}`,source:r.source,pluginId:i});continue}t.set(i,{id:i,rootDir:r.rootDir,source:r.source,origin:r.origin,manifestPath:e.manifestPath,manifest:e.manifest})}return{manifests:t,diagnostics:n}}let Y=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function X(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===Y.ERROR){k.error(i);return}if(e===Y.WARN){k.warn(i);return}k.info(i)}function _t(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>X(Y.INFO,e.pluginId,t,n),warn:n=>X(Y.WARN,e.pluginId,t,n),error:n=>X(Y.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}let vt;function yt(){return vt||=d(import.meta.url,{interopDefault:!0,requireCache:!0}),vt}function bt(e){if(!e.config.enabled)return!1;let t=e.config.entries[e.pluginId];if(t?.enabled===!1||e.config.deny.includes(e.pluginId)||e.config.allow.length>0&&!e.config.allow.includes(e.pluginId)||e.origin===`bundled`&&t?.enabled!==!0)return!1;if(e.kind&&e.config.slots?.[e.kind]){let t=e.config.slots[e.kind];if(t&&t!==`none`&&t!==e.pluginId)return!1}return!0}function xt(e){return{id:e.id,source:e.source,origin:e.origin,enabled:e.enabled,status:e.enabled?`loaded`:`disabled`,toolCount:0,hookCount:0,skills:e.skills,configSchema:e.configSchema}}function St(n){let r=[...n.registry.diagnostics],a=new L,o=new de,s=[],c=[],l=n.runtime?.llm?ke({apiFormat:n.runtime.llm.apiFormat,baseUrl:n.runtime.llm.baseUrl,apiKey:n.runtime.llm.apiKey,defaultModel:n.runtime.llm.model,hooks:o,hookCtx:n.runtime.hookCtx}):void 0,u=Ct(n.runtime?.llmAllowlist),d=yt();for(let f of n.registry.manifests.values()){let p=bt({config:n.plugins,pluginId:f.id,origin:f.origin,kind:f.manifest.kind}),m=xt({id:f.id,source:f.source,origin:f.origin,enabled:p,configSchema:!0,skills:f.manifest.skills??[]});if(!p){c.push(m);continue}let h=Date.now(),g;try{g=d(f.source)}catch(e){m.status=`error`,m.error=String(e),m.durationMs=Math.max(0,Date.now()-h),r.push({level:`error`,message:`failed to load plugin ${f.id}: ${String(e)}`,pluginId:f.id,source:f.source}),c.push(m);continue}let _=g&&typeof g==`object`&&`default`in g?g.default:g,v=typeof _==`function`?_:_&&typeof _==`object`&&typeof _.register==`function`?_.register:void 0;if(!v){m.status=`error`,m.error=`plugin module does not export a register function`,m.durationMs=Math.max(0,Date.now()-h),r.push({level:`error`,message:`plugin ${f.id} has no register function`,pluginId:f.id,source:f.source}),c.push(m);continue}let y=_t({pluginId:f.id,env:n.runtime?.env}),b=n.plugins.entries[f.id]?.config,ee={id:f.id,source:f.source,rootDir:f.rootDir,config:b,runtime:y,llm:{chat:async e=>{if(!l)throw Error(`LLM client is not configured`);if(!wt(f.id,a,u))throw Error(`Plugin ${f.id} is not allowed to use LLM`);return l.chat(e)}},registerTool:(e,t)=>{a.register(f.id,e,t),m.toolCount+=1},registerUiTool:(e,t)=>{a.registerUiTool(f.id,e,t),m.toolCount+=1},registerEmbeddingProvider:t=>{if(f.manifest.kind!==`memory`)throw Error(`Plugin ${f.id} is not allowed to register embedding providers`);e({pluginId:f.id,id:t.id,create:t.create,config:b,rootDir:f.rootDir,source:f.source})},registerMemoryProvider:e=>{if(f.manifest.kind!==`memory`)throw Error(`Plugin ${f.id} is not allowed to register memory providers`);t({pluginId:f.id,id:e.id,create:e.create,config:b,rootDir:f.rootDir,source:f.source})},registerHook:(e,t,n)=>{o.register({pluginId:f.id,hookName:e,handler:t,priority:n?.priority,source:f.source}),m.hookCount+=1},registerSkillDir:e=>{let t=i.isAbsolute(e)?e:i.resolve(f.rootDir,e);s.push(t)},createProgressEmitter:()=>se(f.id)};try{v(ee)}catch(e){m.status=`error`,m.error=String(e),r.push({level:`error`,message:`plugin ${f.id} registration failed: ${String(e)}`,pluginId:f.id,source:f.source})}if(f.manifest.skills&&f.manifest.skills.length>0)for(let e of f.manifest.skills){let t=i.isAbsolute(e)?e:i.resolve(f.rootDir,e);s.push(t)}m.durationMs=Math.max(0,Date.now()-h),c.push(m)}return{plugins:c,diagnostics:r,tools:a,hooks:o,skills:s}}function Ct(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function wt(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}let Z=null,Q=null;function Tt(e){let{dataDir:t,bundledDir:n,workspaceDir:r}=e,i=e.config?JSON.stringify({allow:e.config.allow,deny:e.config.deny,enabled:e.config.enabled,piExtensions:e.config.piExtensions}):``;return`${t??``}|${n??``}|${r??``}|${i}`}function Et(e){let t=Tt(e);return Z&&Q===t?Z:(Z=$(e),Q=t,Z)}function Dt(e){return Z&&Q===Tt(e)?Z:$(e)}function $(e={}){let t=Je(e.config),n=dt({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=gt(n.candidates),i=Ye({config:t,registry:r}),a=St({registry:r,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime});return{registry:a,diagnostics:[...n.diagnostics,...r.diagnostics,...i.diagnostics,...a.diagnostics],normalizedConfig:t,piExtensions:[]}}function Ot(e,t){return Array.from(new Set([...t?.piExtensionPaths??[],...e.piExtensionPaths]))}async function kt(e,t){let r=Ot(e,t);return r.length===0?[]:n(r)}function At(e={}){return{runtimeInitialized:!0,pluginSystem:Et({bundledDir:e.bundledDir,config:e.config,ownershipUid:e.ownershipUid,piExtensionPaths:e.piExtensionPaths}),loadedAt:new Date().toISOString(),version:1}}export{Oe as A,M as C,k as D,ke as E,ie as F,f as I,de as M,se as N,Ee as O,oe as P,Be as S,A as T,L as _,Et as a,P as b,_t as c,pt as d,ht as f,Ye as g,Je as h,$ as i,ve as j,De as k,gt as l,dt as m,kt as n,Ot as o,mt as p,Dt as r,St as s,At as t,J as u,He as v,Re as w,ze as x,F as y};
@@ -1 +1 @@
1
- import{t as e}from"./system-runtime-7UR4nDc0.js";import"./provider-registry-DPbmbWqS.js";import"./loader-CkdBGDtW.js";export{e as prepareSystemRuntime};
1
+ import{t as e}from"./system-runtime-g4RJ5wzA.js";import"./provider-registry-DPbmbWqS.js";import"./loader-CkdBGDtW.js";export{e as prepareSystemRuntime};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/agents",
3
- "version": "0.16.0",
3
+ "version": "0.16.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -1,4 +0,0 @@
1
- import{i as e,t}from"./provider-registry-DPbmbWqS.js";import{n}from"./loader-CkdBGDtW.js";import{validateUiToolResult as r}from"@gencode/shared";import i from"node:path";import a from"node:os";import{AsyncLocalStorage as o}from"node:async_hooks";import s from"node:fs";import c from"log4js";import{Type as l}from"@earendil-works/pi-ai";import u from"ajv";import{createJiti as d}from"jiti";function f(e){return e??`openai-completions`}function p(e,t,n){let r={"Client-Code":`AIMax`,"X-Session-Id":e};return t&&(r[`X-Message-Id`]=t),n&&(r[`X-Channel`]=n),r}function m(e){let t=e?.input??e?.prompt_tokens??0,n=e?.output??e?.completion_tokens??0;return{input:t,output:n,total:e?.total??e?.total_tokens??t+n}}const h={apiFormat:`anthropic-messages`,createModel:g,buildRequest:v,normalizeResponse:y};function g(e,t,n,r){return{id:e.model,name:e.model,api:`anthropic-messages`,provider:`anthropic`,baseUrl:_(e.baseUrl),reasoning:!1,input:[`text`,`image`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:p(t,n,r)}}function _(e){return e.replace(/\/+$/,``).replace(/\/v1$/,``)}function v(e,t,n,r){let i=e.baseUrl.replace(/\/+$/,``),a=[],o=[];for(let e of n){if(e.role===`system`){e.content.trim()&&o.push(e.content);continue}a.push({role:e.role,content:e.content})}let s={model:t,messages:a.length>0?a:[{role:`user`,content:``}],max_tokens:r.maxTokens??2048,stream:!1};return o.length>0&&(s.system=o.join(`
2
-
3
- `)),typeof r.temperature==`number`&&(s.temperature=r.temperature),{url:i.endsWith(`/v1`)?`${i}/messages`:`${i}/v1/messages`,headers:{"content-type":`application/json`,"x-api-key":e.apiKey,"anthropic-version":`2023-06-01`,"Client-Code":`AIMax`},body:s}}function y(e){let t=e,n=t.content?.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``)??``,r=(t.usage?.input_tokens??0)+(t.usage?.cache_read_input_tokens??0)+(t.usage?.cache_creation_input_tokens??0),i=t.usage?.output_tokens??0;return{text:n,usage:{input:r,output:i,total:r+i},raw:e}}const b={apiFormat:`openai-completions`,createModel:ee,buildRequest:te,normalizeResponse:ne};function ee(e,t,n,r){let i=e.baseUrl.includes(`deepseek.com`),a=e.thinking;return{id:e.model,name:e.model,api:`openai-completions`,provider:i?`deepseek`:`openai`,baseUrl:e.baseUrl,reasoning:i||!!a,...i&&{thinkingLevelMap:{high:`high`,xhigh:`max`}},...a&&!i&&{thinkingLevelMap:{high:`high`,xhigh:`high`}},input:[`text`],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:e.contextWindow??2e5,maxTokens:e.maxTokens??32768,headers:p(t,n,r),compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!!(a&&!i),supportsUsageInStreaming:!0,...a&&!i&&{thinkingFormat:`deepseek`}}}}function te(e,t,n,r){let i={model:t,messages:n,stream:!1};return typeof r.temperature==`number`&&(i.temperature=r.temperature),typeof r.maxTokens==`number`&&(i.max_tokens=r.maxTokens),{url:`${e.baseUrl.replace(/\/+$/,``)}/chat/completions`,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`,"Client-Code":`AIMax`},body:i}}function ne(e){let t=e;return{text:t.choices?.[0]?.message?.content??t.choices?.[0]?.text??``,usage:m(t.usage),raw:e}}const re={"openai-completions":b,"anthropic-messages":h};function ie(e){return re[e]}const ae=new o;async function oe(e,t){return await ae.run(e,t)}function se(e){return{async emit(t){let n=ae.getStore();if(!n||n.pluginId!==e)throw Error(`Plugin ${e} cannot emit progress outside its runtime context`);if(!n.hookContext.sessionId)throw Error(`Plugin ${e} cannot emit progress without an active session`);await n.eventDispatcher.dispatchProgress(n.hookContext.sessionId,{type:`custom`,pluginId:e,name:t.name,label:t.label,data:t.data})}}}const ce={before_prompt_build:`before_agent_start`,after_tool_call:`tool_result (for mutable results) or before_tool_call (for blocking)`},le=new Set([`before_model_resolve`,`before_prompt_build`,`before_agent_start`,`before_tool_call`,`tool_result`,`before_compaction`,`context`,`before_provider_request`,`dream_gate`,`input`,`resources_discover`]);var ue=class extends Error{constructor(e,t,n){super(`Plugin hook "${e}" timed out after ${n}ms (plugin: ${t})`),this.hookName=e,this.pluginId=t,this.timeoutMs=n,this.name=`PluginHookTimeoutError`}},de=class{hooks=new Map;deprecatedWarned=new Set;blockingTimeoutMs;bestEffortTimeoutMs;constructor(e={}){this.blockingTimeoutMs=fe(e.blockingTimeoutMs,1e4),this.bestEffortTimeoutMs=fe(e.bestEffortTimeoutMs,3e3)}register(e){let t=ce[e.hookName];t&&!this.deprecatedWarned.has(e.hookName)&&(this.deprecatedWarned.add(e.hookName),console.warn(`[PluginHookRegistry] Hook "${e.hookName}" is deprecated. Use "${t}" instead. (plugin: ${e.pluginId})`));let n=this.hooks.get(e.hookName)??[];n.push(e),n.sort((e,t)=>(e.priority??0)-(t.priority??0)),this.hooks.set(e.hookName,n)}async dispatch(e,t,n,r){return(await this.dispatchWithMetadata(e,t,n,r)).map(e=>e.result)}async dispatchWithMetadata(e,t,n,r){let i=this.hooks.get(e)??[],a=[],o=this.getDispatchPolicy(e);for(let s of i){let i=pe(n),c=async()=>await s.handler(t,i.ctx);try{let t=await me(r?oe({pluginId:s.pluginId,hookContext:i.ctx,eventDispatcher:r.eventDispatcher},c):c(),{hookName:e,pluginId:s.pluginId,timeoutMs:o.timeoutMs,abort:i.abort});i.clear(),a.push({pluginId:s.pluginId,source:s.source,result:t})}catch(t){if(i.clear(),o.mode===`blocking`)throw t;await he({runtime:r,ctx:n,hookName:e,entry:s,policy:o,error:t})}}return a}getDispatchPolicy(e){return le.has(e)?{mode:`blocking`,timeoutMs:this.blockingTimeoutMs}:{mode:`bestEffort`,timeoutMs:this.bestEffortTimeoutMs}}};function fe(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:t}function pe(e){let t=new AbortController,n;return e.signal&&(e.signal.aborted?t.abort():(n=()=>t.abort(),e.signal.addEventListener(`abort`,n,{once:!0}))),{ctx:{...e,signal:t.signal},abort:()=>t.abort(),clear:()=>{n&&e.signal&&e.signal.removeEventListener(`abort`,n)}}}async function me(e,t){let n;try{return await Promise.race([e,new Promise((e,r)=>{n=setTimeout(()=>{t.abort(),r(new ue(t.hookName,t.pluginId,t.timeoutMs))},t.timeoutMs),n.unref?.()})])}finally{n&&clearTimeout(n)}}async function he(e){if(!e.runtime||!e.ctx.sessionId)return;let t=e.error instanceof ue;await e.runtime.eventDispatcher.dispatchProgress(e.ctx.sessionId,{type:`diagnostic`,level:`warn`,scope:`plugin`,phase:t?`hook_timeout`:`hook_failed`,message:t?`plugin hook timed out: ${e.hookName}`:`plugin hook failed: ${e.hookName}`,details:{hookName:e.hookName,pluginId:e.entry.pluginId,source:e.entry.source,mode:e.policy.mode,timeoutMs:e.policy.timeoutMs,error:e.error instanceof Error?e.error.message:String(e.error)}}).catch(()=>{})}function ge(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function _e(e=new Date){let t=ge(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let x=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});const S=new o;function ve(e,t){return S.run(e,t)}let C=null,w=[];function ye(){return _e()}function be(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function xe(e){return i.join(e,`.aimax`)}function Se(e){let t=e?.trim();return t&&t.replace(/[^A-Za-z0-9_.-]/g,`_`)||`no-message-${process.pid}`}function Ce(e,t){let n=t?.sessionStoreName?.trim()||`sessions`,r=Se(t?.messageId);return t?.sessionDir?{runLogId:r,logDir:i.join(t.sessionDir,`logs`,r)}:t?.sessionId?{runLogId:r,logDir:i.join(xe(e),n,t.sessionId,`logs`,r)}:{runLogId:r,logDir:i.join(xe(e),`logs`,r)}}function we(e){return{appLogPath:i.join(e,`app.log`),errorLogPath:i.join(e,`errors.log`)}}function Te(e){let{appLogPath:t,errorLogPath:n}=we(e);c.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function T(e,t,n){return`[${ye()}] [${e}] ${t}${be(n)}`}function Ee(e,t,n){let r=S.getStore();if(r){r({level:e,message:t,context:n,formatted:T(e,t,n)});return}try{process.stderr.write(`${T(e,t,n)}\n`)}catch{}}function E(e,t,n){if(!C){w.push({level:e,message:t,context:n}),w.length>200&&(w=w.slice(-200)),Ee(e,t,n);return}let r=T(e,t,n),i=c.getLogger();e===x.ERROR?i.error(r):e===x.WARN?i.warn(r):i.info(r);let a=S.getStore();a&&a({level:e,message:t,context:n,formatted:r})}function De(e,t){let{logDir:n,runLogId:r}=Ce(e,t);if(C?.dataDir===e&&C.runLogId===r&&C.logDir===n)return;s.mkdirSync(n,{recursive:!0}),Te(n),C={dataDir:e,logDir:n,runLogId:r};let i=w;w=[];for(let e of i)E(e.level,e.message,e.context)}const D={info:(e,t)=>E(x.INFO,e,t),warn:(e,t)=>E(x.WARN,e,t),error:(e,t)=>E(x.ERROR,e,t)};function Oe(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}var O=class extends Error{code;statusCode;statusText;providerMessage;providerCode;providerType;retryable;constructor(e){super(e.message,{cause:e.cause}),this.name=`LlmRequestError`,this.code=e.code,this.statusCode=e.statusCode,this.statusText=e.statusText,this.providerMessage=e.providerMessage,this.providerCode=e.providerCode,this.providerType=e.providerType,this.retryable=e.retryable}};function k(e){return{async chat(t){let n=Ae(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await A(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:je(n),historyMessages:n},e.hookCtx);let i=ie(f(e.apiFormat)),a=i.buildRequest(e,r,n,t),{signal:o,clear:s,didTimeout:c}=Me(t.signal,t.timeoutMs);try{let t;try{t=await fetch(a.url,{method:`POST`,headers:a.headers,body:JSON.stringify(a.body),signal:o})}catch(e){throw Pe(e,c())}if(!t.ok){let e=await Ne(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new O({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:Fe(t.status)})}let n=Date.now(),s;try{s=await t.json()}catch(e){throw ke(e,c())}let{text:l,usage:u}=i.normalizeResponse(s),d=Math.max(0,Date.now()-n);return await A(e.hooks,`llm_output`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,assistantTexts:l?[l]:[],durationMs:d,usage:u},e.hookCtx),{text:l,usage:u,raw:s}}finally{s()}}}}function ke(e,t){return j(e)&&t?new O({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):j(e)?new O({message:`LLM request was aborted`,code:`aborted`,retryable:!0,cause:e}):new O({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}function Ae(e){if(Array.isArray(e.messages)&&e.messages.length>0)return e.messages;let t=[];if(e.system?.trim()&&t.push({role:`system`,content:e.system}),e.user?.trim()&&t.push({role:`user`,content:e.user}),t.length===0)throw Error(`LLM messages are required`);return t}function je(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
4
- `)}async function A(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function Me(e,t){if(!e&&(!t||t<=0))return{signal:void 0,clear:()=>{},didTimeout:()=>!1};let n=new AbortController,r,i=!1;return e&&(e.aborted?n.abort():e.addEventListener(`abort`,()=>n.abort(),{once:!0})),t&&t>0&&(r=setTimeout(()=>{i=!0,n.abort()},t)),{signal:n.signal,clear:()=>{r&&clearTimeout(r)},didTimeout:()=>i}}async function Ne(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function Pe(e,t){return e instanceof O?e:j(e)?t?new O({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new O({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function j(e){return e instanceof Error&&e.name===`AbortError`}function Fe(e){return e===408||e===409||e===425||e===429||e>=500}var M=class extends Error{isUiToolPause=!0;request;constructor(e,t,n,r,i,a,o){super(`UI_TOOL_PAUSED`),this.toolArgs=o,this.name=`UiToolPauseSignal`,this.request={requestId:e,sessionId:t,toolName:n,toolCallId:r,outputSchema:i,extra:a,createdAt:new Date().toISOString()}}};function Ie(e){return!!(e instanceof M||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const N=new o;function Le(){return{}}async function Re(e,t){return await N.run(e,t)}function ze(e){let t=N.getStore();!t||t.signal||(t.signal=e)}const P=l.Object({reason:l.String({description:`A brief explanation of why user input is needed through this UI form.`})});function F(e){let{name:t,label:n,description:i,sessionId:a,inputSchema:o,outputSchema:s,extra:c,validate:l,resume:u}=e;return{name:t,label:n,description:i,parameters:o??P,async execute(e,n){if(u&&u.toolCallId===e&&u.toolName===t&&u.sessionId===a){let e=r(s,u.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}if(l){let e=await l(u.values);if(!e.valid){let t=e.errors;return{content:[{type:`text`,text:JSON.stringify({error:`validation_failed`,errors:t})}],details:{}}}}return{content:[{type:`text`,text:JSON.stringify({submitted:!0,values:u.values})}],details:{}}}let i=new M(e,a,t,e,s,c,n);throw ze(i),i}}}const I=Symbol(`pluginToolOwner`);var L=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,I,{value:e,enumerable:!1,configurable:!1,writable:!1}),this.tools.push({pluginId:e,tool:t,optional:n?.optional??!1,names:i})}registerUiTool(e,t,n){this.uiTools.push({pluginId:e,descriptor:t,optional:n?.optional??!1})}list(){return[...this.tools]}listUiTools(){return[...this.uiTools]}namesForPlugin(e){let t=this.tools.filter(t=>t.pluginId===e).flatMap(e=>e.names),n=this.uiTools.filter(t=>t.pluginId===e).map(e=>e.descriptor.name);return[...t,...n]}resolveEnabled(e){let t=new Set((e??[]).map(e=>e.trim()).filter(Boolean));return this.tools.filter(e=>{if(!e.optional)return!0;if(t.size===0)return!1;if(t.has(e.pluginId))return!0;for(let n of e.names)if(t.has(n))return!0;return!1}).map(e=>e.tool)}resolveUiTools(e,t,n){let r=new Set((n??[]).map(e=>e.trim()).filter(Boolean));return this.uiTools.filter(e=>e.optional?r.size===0?!1:!!(r.has(e.pluginId)||r.has(e.descriptor.name)):!0).map(n=>{let r=F({name:n.descriptor.name,label:n.descriptor.label,description:n.descriptor.description,sessionId:e,inputSchema:n.descriptor.inputSchema,outputSchema:n.descriptor.outputSchema,extra:n.descriptor.extra,validate:n.descriptor.validate,resume:t});return Object.defineProperty(r,I,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Be(e){return e[I]}function R(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function z(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Ve(){let e=a.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function He(e){let t=e.trim(),n=Ve();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?i.join(n,t.slice(2)):void 0:i.resolve(t)}const Ue=new u({allErrors:!0,strict:!1}),We=new Map;function Ge(e,t){let n=We.get(t);if(n)return n;let r=Ue.compile(e);return We.set(t,r),r}function Ke(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Ge(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function qe(e){let t=z(e?.allow),n=z(e?.deny),r=z(e?.load?.paths),i=z(e?.piExtensions?.paths),a=e?.entries??{},o=e?.slots??{};return{enabled:e?.enabled??!0,allow:Array.from(new Set(t)),deny:Array.from(new Set(n)),loadPaths:Array.from(new Set(r)),piExtensionPaths:Array.from(new Set(i)),entries:a,slots:o}}function Je(e){let t=[],{config:n,registry:r}=e,i=new Set(r.manifests.keys()),a=(e,n)=>i.has(e)?!0:(t.push({level:`error`,message:`unknown plugin id in ${n}: ${e}`,pluginId:e}),!1);for(let e of n.allow)a(e,`plugins.allow`);for(let e of n.deny)a(e,`plugins.deny`);for(let e of Object.keys(n.entries))a(e,`plugins.entries`);let o=n.slots??{};for(let[e,n]of Object.entries(o)){if(!n||n===`none`||!a(n,`plugins.slots.${e}`))continue;let i=r.manifests.get(n);i?.manifest.kind?i.manifest.kind!==e&&t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n}):t.push({level:`error`,message:`plugin ${n} does not declare kind ${e}`,pluginId:n})}for(let[e,i]of Object.entries(n.entries)){let n=r.manifests.get(e);if(!n)continue;let a=n.manifest.configSchema,o=Ke({schema:a,cacheKey:`${e}:${n.manifestPath}`,value:i?.config??{}});if(!o.ok)for(let n of o.errors)t.push({level:`error`,message:`plugin config invalid (${e}) at ${n.path}: ${n.message}`,pluginId:e});i?.enabled===!1&&i?.config&&t.push({level:`warn`,message:`plugin config set while disabled: ${e}`,pluginId:e})}return{ok:t.every(e=>e.level!==`error`),diagnostics:t}}function B(e){try{return s.realpathSync(e)}catch{return null}}function Ye(e){try{return s.statSync(e)}catch{return null}}function V(e,t){let n=i.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!i.isAbsolute(n)}function Xe(e){return`0o${e.toString(8).padStart(3,`0`)}`}const H=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Ze=[`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`];function Qe(e){let t=i.join(e,`package.json`);if(s.existsSync(t))try{let e=JSON.parse(s.readFileSync(t,`utf-8`));return R(e)?e:void 0}catch{return}}function $e(e){let t=e?.aimax?.extensions;if(!Array.isArray(t))return{status:`missing`,entries:[]};let n=t.map(e=>typeof e==`string`?e.trim():``).filter(Boolean);return n.length===0?{status:`empty`,entries:[]}:{status:`ok`,entries:n}}function et(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function tt(e){let t=B(e.source),n=B(e.rootDir);return!t||!n||V(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function nt(e){if(process.platform===`win32`)return null;let t=[e.rootDir,e.source],n=new Set;for(let r of t){let t=i.resolve(r);if(n.has(t))continue;n.add(t);let a=Ye(r);if(!a)return{reason:`path_stat_failed`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r};let o=a.mode&511;if(o&2)return{reason:`path_world_writable`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,modeBits:o};if(e.origin!==`bundled`&&e.uid!==null&&typeof a.uid==`number`&&a.uid!==e.uid&&a.uid!==0)return{reason:`path_suspicious_ownership`,sourcePath:e.source,rootPath:e.rootDir,targetPath:r,foundUid:a.uid,expectedUid:e.uid}}return null}function rt(e){return tt({source:e.source,rootDir:e.rootDir})||nt({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:et(e.ownershipUid)})}function it(e){return e.reason===`source_escapes_root`?`blocked plugin candidate: source escapes plugin root (${e.sourcePath} -> ${e.sourceRealPath}; root=${e.rootRealPath})`:e.reason===`path_stat_failed`?`blocked plugin candidate: cannot stat path (${e.targetPath})`:e.reason===`path_world_writable`?`blocked plugin candidate: world-writable path (${e.targetPath}, mode=${Xe(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function U(e){let t=rt({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:it(t),source:e.source}),!0):!1}function W(e){return i.basename(e,i.extname(e))}function G(e){return{idHint:e.idHint,source:e.source,rootDir:e.rootDir,origin:e.origin,workspaceDir:e.workspaceDir,packageName:e.packageName,packageVersion:e.packageVersion,packageDescription:e.packageDescription,packageDir:e.packageDir,packageManifest:e.packageManifest}}function at(e){for(let t of Ze){let n=i.join(e,t);if(s.existsSync(n))return n}return null}function K(e){let t;try{t=s.readdirSync(e.rootDir,{withFileTypes:!0})}catch{return}for(let n of t){let t=i.join(e.rootDir,n.name);if(n.isFile()){if(!H.has(i.extname(n.name)))continue;let r=i.dirname(t);if(U({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(G({idHint:W(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=Qe(t),a=$e(r);if(a.status===`ok`){for(let n of a.entries){let a=i.resolve(t,n);if(!V(t,a)){e.diagnostics.push({level:`warn`,message:`blocked plugin candidate: package entry escapes package root (${n})`,source:a});continue}if(!s.existsSync(a)){e.diagnostics.push({level:`warn`,message:`plugin entry missing: ${a}`,source:a});continue}if(!H.has(i.extname(a))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${a}`,source:a});continue}if(U({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let o=r?.name?.trim(),c=o?`${o}/${W(a)}`:W(a);e.candidates.push(G({idHint:c,source:a,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir,packageName:r?.name,packageVersion:r?.version,packageDescription:r?.description,packageDir:t,packageManifest:r?.aimax}))}continue}let o=at(t);o&&(U({source:o,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(G({idHint:i.basename(t),source:o,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function ot(e){return e?e.map(He).filter(e=>typeof e==`string`&&e.length>0):[]}function st(){let e=Ve();if(e)return i.join(e,`.aimax`,`extensions`)}function ct(e){return i.join(e,`.aimax`,`extensions`)}function lt(e){return i.join(e,`.aimax`,`extensions`)}function ut(e={}){let t=[],n=[],r=ot(e.extraPaths);for(let a of r){if(!s.existsSync(a)){n.push({level:`warn`,message:`plugin path not found: ${a}`,source:a});continue}let r=Ye(a);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${a}`,source:a});continue}if(r.isFile()){if(!H.has(i.extname(a))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${a}`,source:a});continue}let r=i.dirname(a);if(U({source:a,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(G({idHint:W(a),source:a,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&K({rootDir:a,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?K({rootDir:ct(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&K({rootDir:lt(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let a=st();return a?K({rootDir:a,origin:`global`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):n.push({level:`warn`,message:`skipping global plugin discovery: home directory is unavailable`}),e.bundledDir&&K({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function dt(e){let t=e.rejectHardlinks??!0,n=B(e.rootPath),r=B(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!V(n,r))return{ok:!1,reason:`unsafe`};let i;try{i=s.lstatSync(r)}catch{return{ok:!1,reason:`stat`}}if(t&&typeof i.nlink==`number`&&i.nlink>1)return{ok:!1,reason:`hardlink`};try{return{ok:!0,fd:s.openSync(r,`r`)}}catch{return{ok:!1,reason:`path`}}}const q=`aimax.plugin.json`,ft=[q];function pt(e){for(let t of ft){let n=i.join(e,t);if(s.existsSync(n))return n}return i.join(e,q)}function mt(e,t=!0){let n=pt(e),r=dt({absolutePath:n,rootPath:e,rejectHardlinks:t});if(!r.ok){let e=r.reason;return e===`path`?{ok:!1,error:`plugin manifest not found: ${n}`,manifestPath:n}:{ok:!1,error:`unsafe plugin manifest path: ${n} (${e})`,manifestPath:n}}let i;try{i=JSON.parse(s.readFileSync(r.fd,`utf-8`))}catch(e){return{ok:!1,error:`failed to parse plugin manifest: ${String(e)}`,manifestPath:n}}finally{s.closeSync(r.fd)}if(!R(i))return{ok:!1,error:`plugin manifest must be an object`,manifestPath:n};let a=typeof i.id==`string`?i.id.trim():``;if(!a)return{ok:!1,error:`plugin manifest requires id`,manifestPath:n};let o=R(i.configSchema)?i.configSchema:null;if(!o)return{ok:!1,error:`plugin manifest requires configSchema`,manifestPath:n};let c=typeof i.kind==`string`?i.kind:void 0,l=typeof i.name==`string`?i.name.trim():void 0,u=typeof i.description==`string`?i.description.trim():void 0,d=typeof i.version==`string`?i.version.trim():void 0,f=z(i.skills),p;return R(i.uiHints)&&(p=i.uiHints),{ok:!0,manifest:{id:a,configSchema:o,kind:c,name:l,description:u,version:d,skills:f,uiHints:p},manifestPath:n}}function ht(e){let t=new Map,n=[];for(let r of e){let e=mt(r.rootDir);if(!e.ok){n.push({level:`error`,message:e.error,source:r.source,pluginId:r.idHint});continue}let i=e.manifest.id;if(t.has(i)){n.push({level:`warn`,message:`duplicate plugin id ignored: ${i}`,source:r.source,pluginId:i});continue}t.set(i,{id:i,rootDir:r.rootDir,source:r.source,origin:r.origin,manifestPath:e.manifestPath,manifest:e.manifest})}return{manifests:t,diagnostics:n}}let J=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function Y(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===J.ERROR){D.error(i);return}if(e===J.WARN){D.warn(i);return}D.info(i)}function gt(e){return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>Y(J.INFO,e.pluginId,t,n),warn:n=>Y(J.WARN,e.pluginId,t,n),error:n=>Y(J.ERROR,e.pluginId,t,n)})},session:{env:Object.freeze({...e.env??{}})}}}let _t;function vt(){return _t||=d(import.meta.url,{interopDefault:!0,requireCache:!0}),_t}function yt(e){if(!e.config.enabled)return!1;let t=e.config.entries[e.pluginId];if(t?.enabled===!1||e.config.deny.includes(e.pluginId)||e.config.allow.length>0&&!e.config.allow.includes(e.pluginId)||e.origin===`bundled`&&t?.enabled!==!0)return!1;if(e.kind&&e.config.slots?.[e.kind]){let t=e.config.slots[e.kind];if(t&&t!==`none`&&t!==e.pluginId)return!1}return!0}function bt(e){return{id:e.id,source:e.source,origin:e.origin,enabled:e.enabled,status:e.enabled?`loaded`:`disabled`,toolCount:0,hookCount:0,skills:e.skills,configSchema:e.configSchema}}function xt(n){let r=[...n.registry.diagnostics],a=new L,o=new de,s=[],c=[],l=n.runtime?.llm?k({apiFormat:n.runtime.llm.apiFormat,baseUrl:n.runtime.llm.baseUrl,apiKey:n.runtime.llm.apiKey,defaultModel:n.runtime.llm.model,hooks:o,hookCtx:n.runtime.hookCtx}):void 0,u=St(n.runtime?.llmAllowlist),d=vt();for(let f of n.registry.manifests.values()){let p=yt({config:n.plugins,pluginId:f.id,origin:f.origin,kind:f.manifest.kind}),m=bt({id:f.id,source:f.source,origin:f.origin,enabled:p,configSchema:!0,skills:f.manifest.skills??[]});if(!p){c.push(m);continue}let h=Date.now(),g;try{g=d(f.source)}catch(e){m.status=`error`,m.error=String(e),m.durationMs=Math.max(0,Date.now()-h),r.push({level:`error`,message:`failed to load plugin ${f.id}: ${String(e)}`,pluginId:f.id,source:f.source}),c.push(m);continue}let _=g&&typeof g==`object`&&`default`in g?g.default:g,v=typeof _==`function`?_:_&&typeof _==`object`&&typeof _.register==`function`?_.register:void 0;if(!v){m.status=`error`,m.error=`plugin module does not export a register function`,m.durationMs=Math.max(0,Date.now()-h),r.push({level:`error`,message:`plugin ${f.id} has no register function`,pluginId:f.id,source:f.source}),c.push(m);continue}let y=gt({pluginId:f.id,env:n.runtime?.env}),b=n.plugins.entries[f.id]?.config,ee={id:f.id,source:f.source,rootDir:f.rootDir,config:b,runtime:y,llm:{chat:async e=>{if(!l)throw Error(`LLM client is not configured`);if(!Ct(f.id,a,u))throw Error(`Plugin ${f.id} is not allowed to use LLM`);return l.chat(e)}},registerTool:(e,t)=>{a.register(f.id,e,t),m.toolCount+=1},registerUiTool:(e,t)=>{a.registerUiTool(f.id,e,t),m.toolCount+=1},registerEmbeddingProvider:t=>{if(f.manifest.kind!==`memory`)throw Error(`Plugin ${f.id} is not allowed to register embedding providers`);e({pluginId:f.id,id:t.id,create:t.create,config:b,rootDir:f.rootDir,source:f.source})},registerMemoryProvider:e=>{if(f.manifest.kind!==`memory`)throw Error(`Plugin ${f.id} is not allowed to register memory providers`);t({pluginId:f.id,id:e.id,create:e.create,config:b,rootDir:f.rootDir,source:f.source})},registerHook:(e,t,n)=>{o.register({pluginId:f.id,hookName:e,handler:t,priority:n?.priority,source:f.source}),m.hookCount+=1},registerSkillDir:e=>{let t=i.isAbsolute(e)?e:i.resolve(f.rootDir,e);s.push(t)},createProgressEmitter:()=>se(f.id)};try{v(ee)}catch(e){m.status=`error`,m.error=String(e),r.push({level:`error`,message:`plugin ${f.id} registration failed: ${String(e)}`,pluginId:f.id,source:f.source})}if(f.manifest.skills&&f.manifest.skills.length>0)for(let e of f.manifest.skills){let t=i.isAbsolute(e)?e:i.resolve(f.rootDir,e);s.push(t)}m.durationMs=Math.max(0,Date.now()-h),c.push(m)}return{plugins:c,diagnostics:r,tools:a,hooks:o,skills:s}}function St(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Ct(e,t,n){return n.length===0?!1:n.includes(e)?!0:t.namesForPlugin(e).some(e=>n.includes(e))}let X=null,Z=null;function wt(e){let{dataDir:t,bundledDir:n,workspaceDir:r}=e,i=e.config?JSON.stringify({allow:e.config.allow,deny:e.config.deny,enabled:e.config.enabled,piExtensions:e.config.piExtensions}):``;return`${t??``}|${n??``}|${r??``}|${i}`}function Tt(e){let t=wt(e);return X&&Z===t?X:(X=Q(e),Z=t,X)}function Et(e){return X&&Z===wt(e)?X:Q(e)}function Q(e={}){let t=qe(e.config),n=ut({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=ht(n.candidates),i=Je({config:t,registry:r}),a=xt({registry:r,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime});return{registry:a,diagnostics:[...n.diagnostics,...r.diagnostics,...i.diagnostics,...a.diagnostics],normalizedConfig:t,piExtensions:[]}}function $(e,t){return Array.from(new Set([...t?.piExtensionPaths??[],...e.piExtensionPaths]))}async function Dt(e,t){let r=$(e,t);return r.length===0?[]:n(r)}function Ot(e={}){return{runtimeInitialized:!0,pluginSystem:Tt({bundledDir:e.bundledDir,config:e.config,ownershipUid:e.ownershipUid,piExtensionPaths:e.piExtensionPaths}),loadedAt:new Date().toISOString(),version:1}}export{ve as A,M as C,D,k as E,f as F,se as M,oe as N,De as O,ie as P,Re as S,O as T,L as _,Tt as a,P as b,gt as c,ft as d,mt as f,Je as g,qe as h,Q as i,de as j,Oe as k,ht as l,ut as m,Dt as n,$ as o,pt as p,Et as r,xt as s,Ot as t,q as u,Be as v,Ie as w,Le as x,F as y};