@gencode/agents 0.16.3 → 0.17.0
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/CHANGELOG.md +26 -0
- package/dist/index.d.ts +7 -1
- package/dist/index.js +119 -116
- package/dist/system-runtime-BwN5oJYF.js +4 -0
- package/dist/{system-runtime-CbHrwg94.d.ts → system-runtime-CEaCYWXK.d.ts} +6 -0
- package/dist/system-runtime.d.ts +1 -1
- package/dist/system-runtime.js +1 -1
- package/package.json +3 -2
- package/dist/system-runtime-CpWEW04p.js +0 -4
|
@@ -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 ee={apiFormat:`openai-completions`,createModel:te,buildRequest:ne,normalizeResponse:re};function te(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 ne(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 re(e){let t=e;return{text:t.choices?.[0]?.message?.content??t.choices?.[0]?.text??``,usage:m(t.usage),raw:e}}const ie={"openai-completions":ee,"anthropic-messages":h};function ae(e){return ie[e]}const oe=new o;async function se(e,t){return await oe.run(e,t)}function ce(e){return{async emit(t){let n=oe.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 le={before_prompt_build:`before_agent_start`,after_tool_call:`tool_result (for mutable results) or before_tool_call (for blocking)`},ue=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 de=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`}},fe=class{hooks=new Map;deprecatedWarned=new Set;blockingTimeoutMs;bestEffortTimeoutMs;constructor(e={}){this.blockingTimeoutMs=pe(e.blockingTimeoutMs,1e4),this.bestEffortTimeoutMs=pe(e.bestEffortTimeoutMs,3e3)}register(e){let t=le[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=me(n),c=async()=>await s.handler(t,i.ctx);try{let t=await he(r?se({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 ge({runtime:r,ctx:n,hookName:e,entry:s,policy:o,error:t})}}return a}getDispatchPolicy(e){return ue.has(e)?{mode:`blocking`,timeoutMs:this.blockingTimeoutMs}:{mode:`bestEffort`,timeoutMs:this.bestEffortTimeoutMs}}};function pe(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:t}function me(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 he(e,t){let n;try{return await Promise.race([e,new Promise((e,r)=>{n=setTimeout(()=>{t.abort(),r(new de(t.hookName,t.pluginId,t.timeoutMs))},t.timeoutMs),n.unref?.()})])}finally{n&&clearTimeout(n)}}async function ge(e){if(!e.runtime||!e.ctx.sessionId)return;let t=e.error instanceof de;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 _e(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 ve(e=new Date){let t=_e(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let b=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});const x=new o;function ye(e,t){return x.run({onLog:e},t)}let S=null,C=!1,w=[];function be(){return ve()}function xe(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 Se(e){return i.join(e,`.aimax`)}function Ce(e){let t=e?.trim();return t&&t.replace(/[^A-Za-z0-9_.-]/g,`_`)||`no-message-${process.pid}`}function we(e,t){let n=t?.sessionStoreName?.trim()||`sessions`,r=Ce(t?.messageId);return t?.sessionDir?{runLogId:r,logDir:i.join(t.sessionDir,`logs`,r)}:t?.sessionId?{runLogId:r,logDir:i.join(Se(e),n,t.sessionId,`logs`,r)}:{runLogId:r,logDir:i.join(Se(e),`logs`,r)}}function Te(e){return{appLogPath:i.join(e,`app.log`),errorLogPath:i.join(e,`errors.log`)}}function Ee(e){let{appLogPath:t,errorLogPath:n}=Te(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`[${be()}] [${e}] ${t}${xe(n)}`}function De(e,t,n){try{process.stderr.write(`${T(e,t,n)}\n`)}catch{}}function E(e,t,n){let r=x.getStore();if(r){r.onLog({level:e,message:t,context:n,formatted:T(e,t,n),logDir:r.logDir});return}if(!S){w.push({level:e,message:t,context:n}),w.length>200&&(w=w.slice(-200)),De(e,t,n);return}C||=(Ee(S.logDir),!0);let i=T(e,t,n),a=c.getLogger();e===b.ERROR?a.error(i):e===b.WARN?a.warn(i):a.info(i)}function Oe(e,t){let{logDir:n,runLogId:r}=we(e,t),i=x.getStore();if(i){i.logDir=n;return}if(C&&S?.dataDir===e&&S.runLogId===r&&S.logDir===n)return;s.mkdirSync(n,{recursive:!0}),Ee(n),C=!0,S={dataDir:e,logDir:n,runLogId:r};let a=w;w=[];for(let e of a)E(e.level,e.message,e.context)}async function ke(){try{await Ae()}finally{C=!1}}function Ae(){return new Promise((e,t)=>{c.shutdown(n=>{if(n){t(n);return}e()})})}const D={info:(e,t)=>E(b.INFO,e,t),warn:(e,t)=>E(b.WARN,e,t),error:(e,t)=>E(b.ERROR,e,t)};function je(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 Me(e){return{async chat(t){let n=Pe(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await k(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:Fe(n),historyMessages:n},e.hookCtx);let i=ae(f(e.apiFormat)),a=i.buildRequest(e,r,n,t),{signal:o,clear:s,didTimeout:c}=Ie(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 Re(e,c())}if(!t.ok){let e=await Le(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:ze(t.status)})}let n=Date.now(),s;try{s=await t.json()}catch(e){throw Ne(e,c())}let{text:l,usage:u}=i.normalizeResponse(s),d=Math.max(0,Date.now()-n);return await k(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 Ne(e,t){return A(e)&&t?new O({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):A(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 Pe(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 Fe(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
|
|
4
|
+
`)}async function k(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function Ie(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 Le(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function Re(e,t){return e instanceof O?e:A(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 A(e){return e instanceof Error&&e.name===`AbortError`}function ze(e){return e===408||e===409||e===425||e===429||e>=500}var j=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 Be(e){return!!(e instanceof j||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const Ve=new o;function He(){return{}}async function Ue(e,t){return await Ve.run(e,t)}function We(e){let t=Ve.getStore();!t||t.signal||(t.signal=e)}const Ge=l.Object({reason:l.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Ke(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??Ge,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 j(e,a,t,e,s,c,n);throw We(i),i}}}const M=Symbol(`pluginToolOwner`);var qe=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,M,{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=Ke({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,M,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Je(e){return e[M]}function N(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function P(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Ye(){let e=a.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Xe(e){let t=e.trim(),n=Ye();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?i.join(n,t.slice(2)):void 0:i.resolve(t)}const Ze=new u({allErrors:!0,strict:!1}),F=new Map;function Qe(e,t){let n=F.get(t);if(n)return n;let r=Ze.compile(e);return F.set(t,r),r}function $e(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Qe(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function I(e){let t=P(e?.allow),n=P(e?.deny),r=P(e?.load?.paths),i=P(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 L(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=$e({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 R(e){try{return s.realpathSync(e)}catch{return null}}function z(e){try{return s.statSync(e)}catch{return null}}function B(e,t){let n=i.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!i.isAbsolute(n)}function et(e){return`0o${e.toString(8).padStart(3,`0`)}`}const V=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),tt=[`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`];function nt(e){let t=i.join(e,`package.json`);if(s.existsSync(t))try{let e=JSON.parse(s.readFileSync(t,`utf-8`));return N(e)?e:void 0}catch{return}}function rt(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 it(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function at(e){let t=R(e.source),n=R(e.rootDir);return!t||!n||B(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function ot(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=z(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 st(e){return at({source:e.source,rootDir:e.rootDir})||ot({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:it(e.ownershipUid)})}function ct(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=${et(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function H(e){let t=st({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:ct(t),source:e.source}),!0):!1}function U(e){return i.basename(e,i.extname(e))}function W(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 lt(e){for(let t of tt){let n=i.join(e,t);if(s.existsSync(n))return n}return null}function G(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(!V.has(i.extname(n.name)))continue;let r=i.dirname(t);if(H({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(W({idHint:U(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=nt(t),a=rt(r);if(a.status===`ok`){for(let n of a.entries){let a=i.resolve(t,n);if(!B(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(!V.has(i.extname(a))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${a}`,source:a});continue}if(H({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let o=r?.name?.trim(),c=o?`${o}/${U(a)}`:U(a);e.candidates.push(W({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=lt(t);o&&(H({source:o,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(W({idHint:i.basename(t),source:o,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function ut(e){return e?e.map(Xe).filter(e=>typeof e==`string`&&e.length>0):[]}function dt(){let e=Ye();if(e)return i.join(e,`.aimax`,`extensions`)}function ft(e){return i.join(e,`.aimax`,`extensions`)}function pt(e){return i.join(e,`.aimax`,`extensions`)}function mt(e={}){let t=[],n=[],r=ut(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=z(a);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${a}`,source:a});continue}if(r.isFile()){if(!V.has(i.extname(a))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${a}`,source:a});continue}let r=i.dirname(a);if(H({source:a,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(W({idHint:U(a),source:a,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&G({rootDir:a,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?G({rootDir:ft(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&G({rootDir:pt(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let a=dt();return a?G({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&&G({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function ht(e){let t=e.rejectHardlinks??!0,n=R(e.rootPath),r=R(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!B(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 K=`aimax.plugin.json`,gt=[K];function _t(e){for(let t of gt){let n=i.join(e,t);if(s.existsSync(n))return n}return i.join(e,K)}function vt(e,t=!0){let n=_t(e),r=ht({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(!N(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=N(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=P(i.skills),p;return N(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 yt(e){let t=new Map,n=[];for(let r of e){let e=vt(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 q=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});function J(e,t,n,r){let i=`[plugin:${t}][logger:${n}] ${r}`;if(e===q.ERROR){D.error(i);return}if(e===q.WARN){D.warn(i);return}D.info(i)}function bt(e){let t=()=>e.getEnv?.()??e.env??{};return{version:`0.1.0`,logging:{getLogger:t=>({info:n=>J(q.INFO,e.pluginId,t,n),warn:n=>J(q.WARN,e.pluginId,t,n),error:n=>J(q.ERROR,e.pluginId,t,n)})},session:{get env(){return Object.freeze({...t()})}}}}let Y;function xt(){return Y||=d(import.meta.url,{interopDefault:!0,requireCache:!0}),Y}function St(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 Ct(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 wt(n){let r=[...n.registry.diagnostics],a=new qe,o=new fe,s=[],c=[],l=n.runtimeRef??{current:n.runtime};n.runtime!==void 0&&(l.current=n.runtime);let u=xt();for(let d of n.registry.manifests.values()){let f=St({config:n.plugins,pluginId:d.id,origin:d.origin,kind:d.manifest.kind}),p=Ct({id:d.id,source:d.source,origin:d.origin,enabled:f,configSchema:!0,skills:d.manifest.skills??[]});if(!f){c.push(p);continue}let m=Date.now(),h;try{h=u(d.source)}catch(e){p.status=`error`,p.error=String(e),p.durationMs=Math.max(0,Date.now()-m),r.push({level:`error`,message:`failed to load plugin ${d.id}: ${String(e)}`,pluginId:d.id,source:d.source}),c.push(p);continue}let g=h&&typeof h==`object`&&`default`in h?h.default:h,_=typeof g==`function`?g:g&&typeof g==`object`&&typeof g.register==`function`?g.register:void 0;if(!_){p.status=`error`,p.error=`plugin module does not export a register function`,p.durationMs=Math.max(0,Date.now()-m),r.push({level:`error`,message:`plugin ${d.id} has no register function`,pluginId:d.id,source:d.source}),c.push(p);continue}let v=bt({pluginId:d.id,getEnv:()=>l.current?.env}),y=n.plugins.entries[d.id]?.config,ee={id:d.id,source:d.source,rootDir:d.rootDir,config:y,runtime:v,llm:{chat:async e=>{let t=l.current,n=t?.llm?Me({apiFormat:t.llm.apiFormat,baseUrl:t.llm.baseUrl,apiKey:t.llm.apiKey,defaultModel:t.llm.model,hooks:o,hookCtx:t.hookCtx}):void 0;if(!n)throw Error(`LLM client is not configured`);let r=Tt(t?.llmAllowlist);if(!Et(d.id,a,r))throw Error(`Plugin ${d.id} is not allowed to use LLM`);return n.chat(e)}},registerTool:(e,t)=>{a.register(d.id,e,t),p.toolCount+=1},registerUiTool:(e,t)=>{a.registerUiTool(d.id,e,t),p.toolCount+=1},registerEmbeddingProvider:t=>{if(d.manifest.kind!==`memory`)throw Error(`Plugin ${d.id} is not allowed to register embedding providers`);e({pluginId:d.id,id:t.id,create:t.create,config:y,rootDir:d.rootDir,source:d.source})},registerMemoryProvider:e=>{if(d.manifest.kind!==`memory`)throw Error(`Plugin ${d.id} is not allowed to register memory providers`);t({pluginId:d.id,id:e.id,create:e.create,config:y,rootDir:d.rootDir,source:d.source})},registerHook:(e,t,n)=>{o.register({pluginId:d.id,hookName:e,handler:t,priority:n?.priority,source:d.source}),p.hookCount+=1},registerSkillDir:e=>{let t=i.isAbsolute(e)?e:i.resolve(d.rootDir,e);s.push(t)},createProgressEmitter:()=>ce(d.id)};try{_(ee)}catch(e){p.status=`error`,p.error=String(e),r.push({level:`error`,message:`plugin ${d.id} registration failed: ${String(e)}`,pluginId:d.id,source:d.source})}if(d.manifest.skills&&d.manifest.skills.length>0)for(let e of d.manifest.skills){let t=i.isAbsolute(e)?e:i.resolve(d.rootDir,e);s.push(t)}p.durationMs=Math.max(0,Date.now()-m),c.push(p)}return{plugins:c,diagnostics:r,tools:a,hooks:o,skills:s}}function Tt(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Et(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,Dt=null;function Ot(e){return e===void 0?``:JSON.stringify(e)}function kt(e){return[e.dataDir??``,e.bundledDir??``,e.workspaceDir??``,e.ownershipUid??``,Q(e)].join(`|`)}function Q(e){let t=I(e.config);return Ot({bundledDir:e.bundledDir,ownershipUid:e.ownershipUid,piExtensionPaths:e.piExtensionPaths,config:t})}function At(e,t){return e.runtimeRef&&(e.runtimeRef.current=t),e}function jt(e){let t=kt(e);return X&&Z===t?At(X,e.runtime):(X=$(e),Z=t,Dt=Q(e),X)}function Mt(e){return X&&Z===kt(e)||X&&Dt===Q(e)?At(X,e.runtime):$(e)}function $(e={}){let t=I(e.config),n={current:e.runtime},r=mt({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),i=yt(r.candidates),a=L({config:t,registry:i}),o=wt({registry:i,plugins:t,workspaceDir:e.workspaceDir,runtime:e.runtime,runtimeRef:n});return{registry:o,diagnostics:[...r.diagnostics,...i.diagnostics,...a.diagnostics,...o.diagnostics],normalizedConfig:t,piExtensions:[],runtimeRef:n}}function Nt(e,t){return Array.from(new Set([...t?.piExtensionPaths??[],...e.piExtensionPaths]))}async function Pt(e,t){let r=Nt(e,t);return r.length===0?[]:n(r)}function Ft(e={}){return{runtimeInitialized:!0,pluginSystem:jt({bundledDir:e.bundledDir,config:e.config,ownershipUid:e.ownershipUid,piExtensionPaths:e.piExtensionPaths}),loadedAt:new Date().toISOString(),version:1}}export{je as A,j as C,D,Me as E,ae as F,f as I,fe as M,ce as N,Oe as O,se as P,Ue as S,O as T,qe as _,jt as a,Ge as b,bt as c,gt as d,vt as f,L as g,I as h,$ as i,ye as j,ke as k,yt as l,mt as m,Pt as n,Nt as o,_t as p,Mt as r,wt as s,Ft as t,K as u,Je as v,Be as w,He as x,Ke as y};
|
|
@@ -27,6 +27,7 @@ type CreatePluginRuntimeOptions = {
|
|
|
27
27
|
* prevent plugins from mutating shared state.
|
|
28
28
|
*/
|
|
29
29
|
env?: Record<string, string>;
|
|
30
|
+
getEnv?: () => Record<string, string> | undefined;
|
|
30
31
|
};
|
|
31
32
|
declare function createPluginRuntime(options: CreatePluginRuntimeOptions): PluginRuntime;
|
|
32
33
|
//#endregion
|
|
@@ -88,6 +89,9 @@ type PluginRuntimeContext = {
|
|
|
88
89
|
*/
|
|
89
90
|
env?: Record<string, string>;
|
|
90
91
|
};
|
|
92
|
+
type PluginRuntimeContextRef = {
|
|
93
|
+
current?: PluginRuntimeContext;
|
|
94
|
+
};
|
|
91
95
|
//#endregion
|
|
92
96
|
//#region src/memory/embeddings.d.ts
|
|
93
97
|
type EmbeddingProvider = {
|
|
@@ -160,6 +164,7 @@ type PluginLoadOptions = {
|
|
|
160
164
|
plugins: NormalizedPluginsConfig;
|
|
161
165
|
workspaceDir?: string;
|
|
162
166
|
runtime?: PluginRuntimeContext;
|
|
167
|
+
runtimeRef?: PluginRuntimeContextRef;
|
|
163
168
|
};
|
|
164
169
|
type PluginApi = {
|
|
165
170
|
id: string;
|
|
@@ -223,6 +228,7 @@ type PluginSystem = {
|
|
|
223
228
|
diagnostics: PluginDiagnostic[];
|
|
224
229
|
normalizedConfig: NormalizedPluginsConfig;
|
|
225
230
|
piExtensions: DiscoveredPiExtension[];
|
|
231
|
+
runtimeRef?: PluginRuntimeContextRef;
|
|
226
232
|
};
|
|
227
233
|
declare function initializePluginSystem(options?: PluginSystemOptions): PluginSystem;
|
|
228
234
|
//#endregion
|
package/dist/system-runtime.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as SystemWarmState, r as prepareSystemRuntime, t as PrepareSystemRuntimeOptions } from "./system-runtime-
|
|
1
|
+
import { n as SystemWarmState, r as prepareSystemRuntime, t as PrepareSystemRuntimeOptions } from "./system-runtime-CEaCYWXK.js";
|
|
2
2
|
export { PrepareSystemRuntimeOptions, SystemWarmState, prepareSystemRuntime };
|
package/dist/system-runtime.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./system-runtime-
|
|
1
|
+
import{t as e}from"./system-runtime-BwN5oJYF.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.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -40,8 +40,9 @@
|
|
|
40
40
|
"log4js": "^6.9.1",
|
|
41
41
|
"openai": "6.10.0",
|
|
42
42
|
"sqlite-vec": "^0.1.6",
|
|
43
|
+
"yaml": "^2.9.0",
|
|
43
44
|
"zod": "^4.3.6",
|
|
44
|
-
"@gencode/shared": "0.
|
|
45
|
+
"@gencode/shared": "0.5.0"
|
|
45
46
|
},
|
|
46
47
|
"engines": {
|
|
47
48
|
"node": ">=22.19.0"
|
|
@@ -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:ee};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 ee(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 y={apiFormat:`openai-completions`,createModel:te,buildRequest:ne,normalizeResponse:re};function te(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 ne(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 re(e){let t=e;return{text:t.choices?.[0]?.message?.content??t.choices?.[0]?.text??``,usage:m(t.usage),raw:e}}const ie={"openai-completions":y,"anthropic-messages":h};function b(e){return ie[e]}const x=new o;async function S(e,t){return await x.run(e,t)}function C(e){return{async emit(t){let n=x.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 ae={before_prompt_build:`before_agent_start`,after_tool_call:`tool_result (for mutable results) or before_tool_call (for blocking)`},oe=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 se=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`}},ce=class{hooks=new Map;deprecatedWarned=new Set;blockingTimeoutMs;bestEffortTimeoutMs;constructor(e={}){this.blockingTimeoutMs=le(e.blockingTimeoutMs,1e4),this.bestEffortTimeoutMs=le(e.bestEffortTimeoutMs,3e3)}register(e){let t=ae[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=ue(n),c=async()=>await s.handler(t,i.ctx);try{let t=await de(r?S({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 fe({runtime:r,ctx:n,hookName:e,entry:s,policy:o,error:t})}}return a}getDispatchPolicy(e){return oe.has(e)?{mode:`blocking`,timeoutMs:this.blockingTimeoutMs}:{mode:`bestEffort`,timeoutMs:this.bestEffortTimeoutMs}}};function le(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:t}function ue(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 de(e,t){let n;try{return await Promise.race([e,new Promise((e,r)=>{n=setTimeout(()=>{t.abort(),r(new se(t.hookName,t.pluginId,t.timeoutMs))},t.timeoutMs),n.unref?.()})])}finally{n&&clearTimeout(n)}}async function fe(e){if(!e.runtime||!e.ctx.sessionId)return;let t=e.error instanceof se;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 pe(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 me(e=new Date){let t=pe(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let w=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({});const T=new o;function he(e,t){return T.run({onLog:e},t)}let E=null,D=!1,O=[];function ge(){return me()}function _e(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 ve(e){return i.join(e,`.aimax`)}function ye(e){let t=e?.trim();return t&&t.replace(/[^A-Za-z0-9_.-]/g,`_`)||`no-message-${process.pid}`}function be(e,t){let n=t?.sessionStoreName?.trim()||`sessions`,r=ye(t?.messageId);return t?.sessionDir?{runLogId:r,logDir:i.join(t.sessionDir,`logs`,r)}:t?.sessionId?{runLogId:r,logDir:i.join(ve(e),n,t.sessionId,`logs`,r)}:{runLogId:r,logDir:i.join(ve(e),`logs`,r)}}function xe(e){return{appLogPath:i.join(e,`app.log`),errorLogPath:i.join(e,`errors.log`)}}function k(e){let{appLogPath:t,errorLogPath:n}=xe(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 A(e,t,n){return`[${ge()}] [${e}] ${t}${_e(n)}`}function Se(e,t,n){try{process.stderr.write(`${A(e,t,n)}\n`)}catch{}}function j(e,t,n){let r=T.getStore();if(r){r.onLog({level:e,message:t,context:n,formatted:A(e,t,n),logDir:r.logDir});return}if(!E){O.push({level:e,message:t,context:n}),O.length>200&&(O=O.slice(-200)),Se(e,t,n);return}D||=(k(E.logDir),!0);let i=A(e,t,n),a=c.getLogger();e===w.ERROR?a.error(i):e===w.WARN?a.warn(i):a.info(i)}function Ce(e,t){let{logDir:n,runLogId:r}=be(e,t),i=T.getStore();if(i){i.logDir=n;return}if(D&&E?.dataDir===e&&E.runLogId===r&&E.logDir===n)return;s.mkdirSync(n,{recursive:!0}),k(n),D=!0,E={dataDir:e,logDir:n,runLogId:r};let a=O;O=[];for(let e of a)j(e.level,e.message,e.context)}async function we(){try{await Te()}finally{D=!1}}function Te(){return new Promise((e,t)=>{c.shutdown(n=>{if(n){t(n);return}e()})})}const M={info:(e,t)=>j(w.INFO,e,t),warn:(e,t)=>j(w.WARN,e,t),error:(e,t)=>j(w.ERROR,e,t)};function Ee(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 N=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 De(e){return{async chat(t){let n=ke(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await je(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:Ae(n),historyMessages:n},e.hookCtx);let i=b(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 N({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 Oe(e,c())}let{text:l,usage:u}=i.normalizeResponse(s),d=Math.max(0,Date.now()-n);return await je(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 Oe(e,t){return P(e)&&t?new N({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):P(e)?new N({message:`LLM request was aborted`,code:`aborted`,retryable:!0,cause:e}):new N({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}function ke(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 Ae(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
|
|
4
|
-
`)}async function je(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 N?e:P(e)?t?new N({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new N({message:`LLM network request failed: ${e instanceof Error?e.message:String(e)}`,code:`network_error`,retryable:!0,cause:e})}function P(e){return e instanceof Error&&e.name===`AbortError`}function Fe(e){return e===408||e===409||e===425||e===429||e>=500}var F=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 F||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const Le=new o;function Re(){return{}}async function ze(e,t){return await Le.run(e,t)}function Be(e){let t=Le.getStore();!t||t.signal||(t.signal=e)}const Ve=l.Object({reason:l.String({description:`A brief explanation of why user input is needed through this UI form.`})});function He(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??Ve,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 F(e,a,t,e,s,c,n);throw Be(i),i}}}const I=Symbol(`pluginToolOwner`);var Ue=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=He({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 We(e){return e[I]}function L(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function R(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):[]}function Ge(){let e=a.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Ke(e){let t=e.trim(),n=Ge();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?i.join(n,t.slice(2)):void 0:i.resolve(t)}const qe=new u({allErrors:!0,strict:!1}),Je=new Map;function Ye(e,t){let n=Je.get(t);if(n)return n;let r=qe.compile(e);return Je.set(t,r),r}function Xe(e){let t=e.cacheKey??JSON.stringify(e.schema),n=Ye(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function Ze(e){let t=R(e?.allow),n=R(e?.deny),r=R(e?.load?.paths),i=R(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 Qe(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=Xe({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 z(e){try{return s.realpathSync(e)}catch{return null}}function $e(e){try{return s.statSync(e)}catch{return null}}function B(e,t){let n=i.relative(e,t);return n===``?!0:n.startsWith(`..`)?!1:!i.isAbsolute(n)}function et(e){return`0o${e.toString(8).padStart(3,`0`)}`}const V=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),tt=[`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`];function nt(e){let t=i.join(e,`package.json`);if(s.existsSync(t))try{let e=JSON.parse(s.readFileSync(t,`utf-8`));return L(e)?e:void 0}catch{return}}function rt(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 it(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function at(e){let t=z(e.source),n=z(e.rootDir);return!t||!n||B(n,t)?null:{reason:`source_escapes_root`,sourcePath:e.source,rootPath:e.rootDir,targetPath:e.source,sourceRealPath:t,rootRealPath:n}}function ot(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=$e(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 st(e){return at({source:e.source,rootDir:e.rootDir})||ot({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:it(e.ownershipUid)})}function ct(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=${et(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function H(e){let t=st({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:ct(t),source:e.source}),!0):!1}function U(e){return i.basename(e,i.extname(e))}function W(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 lt(e){for(let t of tt){let n=i.join(e,t);if(s.existsSync(n))return n}return null}function G(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(!V.has(i.extname(n.name)))continue;let r=i.dirname(t);if(H({source:t,rootDir:r,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;e.candidates.push(W({idHint:U(t),source:t,rootDir:r,origin:e.origin,workspaceDir:e.workspaceDir}));continue}if(!n.isDirectory())continue;let r=nt(t),a=rt(r);if(a.status===`ok`){for(let n of a.entries){let a=i.resolve(t,n);if(!B(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(!V.has(i.extname(a))){e.diagnostics.push({level:`warn`,message:`plugin entry not a supported extension: ${a}`,source:a});continue}if(H({source:a,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid}))continue;let o=r?.name?.trim(),c=o?`${o}/${U(a)}`:U(a);e.candidates.push(W({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=lt(t);o&&(H({source:o,rootDir:t,origin:e.origin,diagnostics:e.diagnostics,ownershipUid:e.ownershipUid})||e.candidates.push(W({idHint:i.basename(t),source:o,rootDir:t,origin:e.origin,workspaceDir:e.workspaceDir})))}}function ut(e){return e?e.map(Ke).filter(e=>typeof e==`string`&&e.length>0):[]}function dt(){let e=Ge();if(e)return i.join(e,`.aimax`,`extensions`)}function ft(e){return i.join(e,`.aimax`,`extensions`)}function pt(e){return i.join(e,`.aimax`,`extensions`)}function mt(e={}){let t=[],n=[],r=ut(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=$e(a);if(!r){n.push({level:`warn`,message:`plugin path not readable: ${a}`,source:a});continue}if(r.isFile()){if(!V.has(i.extname(a))){n.push({level:`warn`,message:`plugin file has unsupported extension: ${a}`,source:a});continue}let r=i.dirname(a);if(H({source:a,rootDir:r,origin:`config`,diagnostics:n,ownershipUid:e.ownershipUid}))continue;t.push(W({idHint:U(a),source:a,rootDir:r,origin:`config`,workspaceDir:e.workspaceDir}));continue}r.isDirectory()&&G({rootDir:a,origin:`config`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid})}e.dataDir?G({rootDir:ft(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&G({rootDir:pt(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let a=dt();return a?G({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&&G({rootDir:e.bundledDir,origin:`bundled`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}),{candidates:t,diagnostics:n}}function ht(e){let t=e.rejectHardlinks??!0,n=z(e.rootPath),r=z(e.absolutePath);if(!n||!r)return{ok:!1,reason:`path`};if(!B(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 K=`aimax.plugin.json`,gt=[K];function _t(e){for(let t of gt){let n=i.join(e,t);if(s.existsSync(n))return n}return i.join(e,K)}function q(e,t=!0){let n=_t(e),r=ht({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(!L(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=L(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=R(i.skills),p;return L(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 vt(e){let t=new Map,n=[];for(let r of e){let e=q(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){M.error(i);return}if(e===J.WARN){M.warn(i);return}M.info(i)}function yt(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 bt;function xt(){return bt||=d(import.meta.url,{interopDefault:!0,requireCache:!0}),bt}function St(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 Ct(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 wt(n){let r=[...n.registry.diagnostics],a=new Ue,o=new ce,s=[],c=[],l=n.runtime?.llm?De({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=Tt(n.runtime?.llmAllowlist),d=xt();for(let f of n.registry.manifests.values()){let p=St({config:n.plugins,pluginId:f.id,origin:f.origin,kind:f.manifest.kind}),m=Ct({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 ee=yt({pluginId:f.id,env:n.runtime?.env}),y=n.plugins.entries[f.id]?.config,te={id:f.id,source:f.source,rootDir:f.rootDir,config:y,runtime:ee,llm:{chat:async e=>{if(!l)throw Error(`LLM client is not configured`);if(!Et(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:y,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:y,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:()=>C(f.id)};try{v(te)}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 Tt(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function Et(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 Dt(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 Ot(e){let t=Dt(e);return X&&Z===t?X:(X=Q(e),Z=t,X)}function kt(e){return X&&Z===Dt(e)?X:Q(e)}function Q(e={}){let t=Ze(e.config),n=mt({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=vt(n.candidates),i=Qe({config:t,registry:r}),a=wt({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 At(e,t){let r=$(e,t);return r.length===0?[]:n(r)}function jt(e={}){return{runtimeInitialized:!0,pluginSystem:Ot({bundledDir:e.bundledDir,config:e.config,ownershipUid:e.ownershipUid,piExtensionPaths:e.piExtensionPaths}),loadedAt:new Date().toISOString(),version:1}}export{Ee as A,F as C,M as D,De as E,b as F,f as I,ce as M,C as N,Ce as O,S as P,ze as S,N as T,Ue as _,Ot as a,Ve as b,yt as c,gt as d,q as f,Qe as g,Ze as h,Q as i,he as j,we as k,vt as l,mt as m,At as n,$ as o,_t as p,kt as r,wt as s,jt as t,K as u,We as v,Ie as w,Re as x,He as y};
|