@gencode/agents 0.15.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.
- package/CHANGELOG.md +20 -0
- package/dist/index.d.ts +11 -5
- package/dist/index.js +147 -113
- package/dist/{loader-CVsd42rJ.d.ts → loader-D9_1WNPg.d.ts} +8 -0
- package/dist/pi-extensions/index.d.ts +1 -1
- package/dist/{system-runtime-De6fo44S.d.ts → system-runtime-Bi5ESko9.d.ts} +1 -1
- package/dist/system-runtime-g4RJ5wzA.js +4 -0
- package/dist/system-runtime.d.ts +1 -1
- package/dist/system-runtime.js +1 -1
- package/package.json +2 -2
- package/dist/system-runtime-DfAhRq2L.js +0 -4
|
@@ -593,12 +593,20 @@ type PluginHookDispatchResult<K extends PluginHookName> = {
|
|
|
593
593
|
source: string;
|
|
594
594
|
result: Awaited<ReturnType<PluginHookHandlerMap[K]>>;
|
|
595
595
|
};
|
|
596
|
+
type PluginHookRegistryOptions = {
|
|
597
|
+
blockingTimeoutMs?: number;
|
|
598
|
+
bestEffortTimeoutMs?: number;
|
|
599
|
+
};
|
|
596
600
|
declare class PluginHookRegistry {
|
|
597
601
|
private readonly hooks;
|
|
598
602
|
private readonly deprecatedWarned;
|
|
603
|
+
private readonly blockingTimeoutMs;
|
|
604
|
+
private readonly bestEffortTimeoutMs;
|
|
605
|
+
constructor(options?: PluginHookRegistryOptions);
|
|
599
606
|
register<K extends PluginHookName>(registration: PluginHookRegistration<K>): void;
|
|
600
607
|
dispatch<K extends PluginHookName>(hookName: K, event: Parameters<PluginHookHandlerMap[K]>[0], ctx: Parameters<PluginHookHandlerMap[K]>[1], runtime?: PluginExecutionRuntime): Promise<Array<Awaited<ReturnType<PluginHookHandlerMap[K]>>>>;
|
|
601
608
|
dispatchWithMetadata<K extends PluginHookName>(hookName: K, event: Parameters<PluginHookHandlerMap[K]>[0], ctx: Parameters<PluginHookHandlerMap[K]>[1], runtime?: PluginExecutionRuntime): Promise<Array<PluginHookDispatchResult<K>>>;
|
|
609
|
+
private getDispatchPolicy;
|
|
602
610
|
}
|
|
603
611
|
//#endregion
|
|
604
612
|
//#region src/runner/event-dispatcher.d.ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as TranscriptEntry, Hn as PluginHookRegistry, i as preloadExtensions, ln as RunEventDispatcher, mn as PluginHookAgentContext, n as discoverPiExtensions, o as PluginToolRegistry, r as getExtensions, t as DiscoveredPiExtension } from "../loader-
|
|
1
|
+
import { C as TranscriptEntry, Hn as PluginHookRegistry, i as preloadExtensions, ln as RunEventDispatcher, mn as PluginHookAgentContext, n as discoverPiExtensions, o as PluginToolRegistry, r as getExtensions, t as DiscoveredPiExtension } from "../loader-D9_1WNPg.js";
|
|
2
2
|
import { Agent, AgentTool } from "@earendil-works/pi-agent-core";
|
|
3
3
|
|
|
4
4
|
//#region src/pi-extensions/tool-adapter.d.ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $t as PluginManifestRegistry, Bn as PluginHookName, Hn as PluginHookRegistry, Pn as PluginHookHandlerMap, Yt as PluginsConfig, c as PluginUiToolOptions, cn as PluginOrigin, ir as MemoryProviderFactory, it as LlmApiFormat, mn as PluginHookAgentContext, o as PluginToolRegistry, qt as NormalizedPluginsConfig, rn as PluginDiagnostic, s as PluginUiToolDescriptor, t as DiscoveredPiExtension } from "./loader-
|
|
1
|
+
import { $t as PluginManifestRegistry, Bn as PluginHookName, Hn as PluginHookRegistry, Pn as PluginHookHandlerMap, Yt as PluginsConfig, c as PluginUiToolOptions, cn as PluginOrigin, ir as MemoryProviderFactory, it as LlmApiFormat, mn as PluginHookAgentContext, o as PluginToolRegistry, qt as NormalizedPluginsConfig, rn as PluginDiagnostic, s as PluginUiToolDescriptor, t as DiscoveredPiExtension } from "./loader-D9_1WNPg.js";
|
|
2
2
|
import { AgentProgressEvent } from "@gencode/shared";
|
|
3
3
|
|
|
4
4
|
//#region src/plugins/runtime.d.ts
|
|
@@ -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};
|
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-Bi5ESko9.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-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.
|
|
3
|
+
"version": "0.16.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"openai": "6.10.0",
|
|
42
42
|
"sqlite-vec": "^0.1.6",
|
|
43
43
|
"zod": "^4.3.6",
|
|
44
|
-
"@gencode/shared": "0.
|
|
44
|
+
"@gencode/shared": "0.4.0"
|
|
45
45
|
},
|
|
46
46
|
"engines": {
|
|
47
47
|
"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 ae(e){return ie[e]}const b=new o;async function x(e,t){return await b.run(e,t)}function S(e){return{async emit(t){let n=b.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 oe={before_prompt_build:`before_agent_start`,after_tool_call:`tool_result (for mutable results) or before_tool_call (for blocking)`};var C=class{hooks=new Map;deprecatedWarned=new Set;register(e){let t=oe[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=[];for(let e of i){let i=async()=>await e.handler(t,n),o=r?await x({pluginId:e.pluginId,hookContext:n,eventDispatcher:r.eventDispatcher},i):await i();a.push({pluginId:e.pluginId,source:e.source,result:o})}return a}};function se(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 ce(e=new Date){let t=se(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 le(e,t){return T.run(e,t)}let E=null,D=[];function ue(){return ce()}function de(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 fe(e){return i.join(e,`.aimax`)}function pe(e){let t=e?.trim();return t&&t.replace(/[^A-Za-z0-9_.-]/g,`_`)||`no-message-${process.pid}`}function me(e,t){let n=t?.sessionStoreName?.trim()||`sessions`,r=pe(t?.messageId);return t?.sessionDir?{runLogId:r,logDir:i.join(t.sessionDir,`logs`,r)}:t?.sessionId?{runLogId:r,logDir:i.join(fe(e),n,t.sessionId,`logs`,r)}:{runLogId:r,logDir:i.join(fe(e),`logs`,r)}}function he(e){return{appLogPath:i.join(e,`app.log`),errorLogPath:i.join(e,`errors.log`)}}function ge(e){let{appLogPath:t,errorLogPath:n}=he(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 O(e,t,n){return`[${ue()}] [${e}] ${t}${de(n)}`}function _e(e,t,n){let r=T.getStore();if(r){r({level:e,message:t,context:n,formatted:O(e,t,n)});return}try{process.stderr.write(`${O(e,t,n)}\n`)}catch{}}function k(e,t,n){if(!E){D.push({level:e,message:t,context:n}),D.length>200&&(D=D.slice(-200)),_e(e,t,n);return}let r=O(e,t,n),i=c.getLogger();e===w.ERROR?i.error(r):e===w.WARN?i.warn(r):i.info(r);let a=T.getStore();a&&a({level:e,message:t,context:n,formatted:r})}function ve(e,t){let{logDir:n,runLogId:r}=me(e,t);if(E?.dataDir===e&&E.runLogId===r&&E.logDir===n)return;s.mkdirSync(n,{recursive:!0}),ge(n),E={dataDir:e,logDir:n,runLogId:r};let i=D;D=[];for(let e of i)k(e.level,e.message,e.context)}const A={info:(e,t)=>k(w.INFO,e,t),warn:(e,t)=>k(w.WARN,e,t),error:(e,t)=>k(w.ERROR,e,t)};function ye(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 j=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 M(e){return{async chat(t){let n=xe(t),r=t.model??e.defaultModel;if(!r)throw Error(`LLM model is required`);await N(e.hooks,`llm_input`,{sessionId:e.hookCtx?.sessionId??`unknown`,model:r,prompt:Se(n),historyMessages:n},e.hookCtx);let i=ae(f(e.apiFormat)),a=i.buildRequest(e,r,n,t),{signal:o,clear:s,didTimeout:c}=Ce(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 Te(e,c())}if(!t.ok){let e=await we(t)||void 0,n=t.statusText?.trim()||void 0,r=[t.status,n].filter(Boolean).join(` `);throw new j({message:e?`LLM upstream returned HTTP ${r}: ${e}`:`LLM upstream returned HTTP ${r}`,code:`http_error`,statusCode:t.status,statusText:n,providerMessage:e,retryable:Ee(t.status)})}let n=Date.now(),s;try{s=await t.json()}catch(e){throw be(e,c())}let{text:l,usage:u}=i.normalizeResponse(s),d=Math.max(0,Date.now()-n);return await N(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 be(e,t){return P(e)&&t?new j({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):P(e)?new j({message:`LLM request was aborted`,code:`aborted`,retryable:!0,cause:e}):new j({message:`LLM upstream returned an invalid JSON response`,code:`invalid_response`,retryable:!1,cause:e})}function xe(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 Se(e){return e.map(e=>`${e.role}: ${e.content}`).join(`
|
|
4
|
-
`)}async function N(e,t,n,r){!e||!r||await e.dispatch(t,n,r)}function Ce(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 we(e){try{let t=await e.text();return t?t.trim().slice(0,200):``}catch{return``}}function Te(e,t){return e instanceof j?e:P(e)?t?new j({message:`LLM request timed out`,code:`timeout`,retryable:!0,cause:e}):e:new j({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 Ee(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 De(e){return!!(e instanceof F||typeof e==`object`&&e&&`isUiToolPause`in e&&e.isUiToolPause===!0)}const I=new o;function Oe(){return{}}async function ke(e,t){return await I.run(e,t)}function Ae(e){let t=I.getStore();!t||t.signal||(t.signal=e)}const je=l.Object({reason:l.String({description:`A brief explanation of why user input is needed through this UI form.`})});function Me(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??je,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 Ae(i),i}}}const L=Symbol(`pluginToolOwner`);var Ne=class{tools=[];uiTools=[];register(e,t,n){let r=t.name,i=n?.names??(n?.name?[n.name]:r?[r]:[]);Object.defineProperty(t,L,{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=Me({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,L,{value:n.pluginId,enumerable:!1,configurable:!1,writable:!1}),r})}};function Pe(e){return e[L]}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 Fe(){let e=a.homedir();if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Ie(e){let t=e.trim(),n=Fe();return t===`~`?n:t.startsWith(`~/`)||t.startsWith(`~\\`)?n?i.join(n,t.slice(2)):void 0:i.resolve(t)}const Le=new u({allErrors:!0,strict:!1}),Re=new Map;function ze(e,t){let n=Re.get(t);if(n)return n;let r=Le.compile(e);return Re.set(t,r),r}function Be(e){let t=e.cacheKey??JSON.stringify(e.schema),n=ze(e.schema,t);return n(e.value)?{ok:!0}:{ok:!1,errors:(n.errors??[]).map(e=>({path:e.instancePath||`/`,message:e.message??`invalid`}))}}function Ve(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 He(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=Be({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 Ue(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 We(e){return`0o${e.toString(8).padStart(3,`0`)}`}const H=new Set([`.ts`,`.js`,`.mts`,`.cts`,`.mjs`,`.cjs`]),Ge=[`index.js`,`index.mjs`,`index.cjs`,`index.ts`,`index.mts`,`index.cts`];function Ke(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 qe(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 Je(e){return e===void 0?process.platform===`win32`||typeof process.getuid!=`function`?null:process.getuid():e}function Ye(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 Xe(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=Ue(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 Ze(e){return Ye({source:e.source,rootDir:e.rootDir})||Xe({source:e.source,rootDir:e.rootDir,origin:e.origin,uid:Je(e.ownershipUid)})}function Qe(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=${We(e.modeBits??0)})`:`blocked plugin candidate: suspicious ownership (${e.targetPath}, uid=${e.foundUid}, expected uid=${e.expectedUid} or root)`}function U(e){let t=Ze({source:e.source,rootDir:e.rootDir,origin:e.origin,ownershipUid:e.ownershipUid});return t?(e.diagnostics.push({level:`warn`,message:Qe(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 $e(e){for(let t of Ge){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=Ke(t),a=qe(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=$e(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 et(e){return e?e.map(Ie).filter(e=>typeof e==`string`&&e.length>0):[]}function tt(){let e=Fe();if(e)return i.join(e,`.aimax`,`extensions`)}function nt(e){return i.join(e,`.aimax`,`extensions`)}function rt(e){return i.join(e,`.aimax`,`extensions`)}function it(e={}){let t=[],n=[],r=et(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=Ue(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:nt(e.dataDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid}):e.workspaceDir&&K({rootDir:rt(e.workspaceDir),origin:`workspace`,workspaceDir:e.workspaceDir,diagnostics:n,candidates:t,ownershipUid:e.ownershipUid});let a=tt();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 at(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`,ot=[q];function st(e){for(let t of ot){let n=i.join(e,t);if(s.existsSync(n))return n}return i.join(e,q)}function ct(e,t=!0){let n=st(e),r=at({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 lt(e){let t=new Map,n=[];for(let r of e){let e=ct(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){A.error(i);return}if(e===J.WARN){A.warn(i);return}A.info(i)}function ut(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 dt;function ft(){return dt||=d(import.meta.url,{interopDefault:!0,requireCache:!0}),dt}function pt(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 mt(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 ht(n){let r=[...n.registry.diagnostics],a=new Ne,o=new C,s=[],c=[],l=n.runtime?.llm?M({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=gt(n.runtime?.llmAllowlist),d=ft();for(let f of n.registry.manifests.values()){let p=pt({config:n.plugins,pluginId:f.id,origin:f.origin,kind:f.manifest.kind}),m=mt({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=ut({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(!_t(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:()=>S(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 gt(e){return(e??[]).map(e=>e.trim()).filter(Boolean)}function _t(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 vt(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 yt(e){let t=vt(e);return X&&Z===t?X:(X=Q(e),Z=t,X)}function bt(e){return X&&Z===vt(e)?X:Q(e)}function Q(e={}){let t=Ve(e.config),n=it({dataDir:e.dataDir,workspaceDir:e.workspaceDir,extraPaths:t.loadPaths,bundledDir:e.bundledDir,ownershipUid:e.ownershipUid}),r=lt(n.candidates),i=He({config:t,registry:r}),a=ht({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 xt(e,t){let r=$(e,t);return r.length===0?[]:n(r)}function St(e={}){return{runtimeInitialized:!0,pluginSystem:yt({bundledDir:e.bundledDir,config:e.config,ownershipUid:e.ownershipUid,piExtensionPaths:e.piExtensionPaths}),loadedAt:new Date().toISOString(),version:1}}export{le as A,F as C,A as D,M as E,f as F,S as M,x as N,ve as O,ae as P,ke as S,j as T,Ne as _,yt as a,je as b,ut as c,ot as d,ct as f,He as g,Ve as h,Q as i,C as j,ye as k,lt as l,it as m,xt as n,$ as o,st as p,bt as r,ht as s,St as t,q as u,Pe as v,De as w,Oe as x,Me as y};
|