@roll-agent/runtime 0.9.0 → 0.10.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.
@@ -12,8 +12,8 @@ import type { ThreadStore } from "../store/thread-store.ts";
12
12
  import { AgentSession, type AgentSessionOptions, type SessionAgentRefresh } from "./agent-session.ts";
13
13
  import { type CapabilityHostMode, type CapabilityVcsSnapshot } from "./capability-manifest.ts";
14
14
  import { resolveShellProfile, type ShellProfile } from "../bash/profile.ts";
15
- export type EnsureAgentReady = (agent: RegisteredAgent, env: Readonly<Record<string, string>> | undefined) => Promise<void>;
16
- export type AcquireAgentUsage = (agent: RegisteredAgent, env: Readonly<Record<string, string>> | undefined) => Promise<AgentUsageLease | undefined>;
15
+ export type EnsureAgentReady = (agent: RegisteredAgent, env: Readonly<Record<string, string>> | undefined, signal?: AbortSignal) => Promise<void>;
16
+ export type AcquireAgentUsage = (agent: RegisteredAgent, env: Readonly<Record<string, string>> | undefined, signal?: AbortSignal) => Promise<AgentUsageLease | undefined>;
17
17
  export interface ConversationEngineOptions {
18
18
  readonly config: RollConfig;
19
19
  readonly agents?: readonly RegisteredAgent[];
@@ -87,6 +87,7 @@ export declare class ConversationEngine {
87
87
  private shellUnsupportedWarned;
88
88
  private readonly liveSessions;
89
89
  private readonly agentUsageLeases;
90
+ private readonly shutdownController;
90
91
  private disposePromise;
91
92
  private closing;
92
93
  constructor(options: ConversationEngineOptions);
@@ -1 +1 @@
1
- import{randomUUID as e}from"node:crypto";import{waitForPromiseSettlement as t}from"../bounded-wait.js";import{McpClientManager as s}from"@roll-agent/core/mcp/client-manager";import{createProviderModel as i}from"@roll-agent/core/llm/providers";import{AgentStore as o}from"@roll-agent/core/registry/store";import{resolveTransportWithDevSpawnSpec as r}from"@roll-agent/core/registry/dev-spawn";import{getAgentPid as n,startAgent as a,waitForAgentReady as l}from"@roll-agent/core/registry/process-manager";import{acquireAgentUsageLease as c}from"@roll-agent/core/registry/agent-usage-lease";import{normalizeListedTools as h}from"@roll-agent/core/cli/utils/agent-tools";import{getAgentEnv as u}from"@roll-agent/core/config/helpers";import{catalogPackageSpec as d,getAgentCatalog as p}from"@roll-agent/core/registry/catalog";import{resolveAgentCatalog as g}from"@roll-agent/core/registry/catalog-discovery";import{installAgent as m}from"@roll-agent/core/registry/install";import{createSkillLibrary as f}from"@roll-agent/core/skills/library";import{ROLL_RESOURCE_HINTS_META_KEY as v}from"../tool-bridge/build-tools.js";import{TOOL_RESOURCE_ACCESS_MODES as y,TOOL_RESOURCE_HINT_KINDS as S}from"../tool-bridge/tool-execution-coordinator.js";import{AgentSession as b}from"./agent-session.js";import{resolveContextWindow as w}from"./context-window.js";import{CAPABILITY_HOST_MODES as x}from"./capability-manifest.js";import{}from"../tool-bridge/bash-tool.js";import{unknownCommandClassifier as C}from"../types/command-classification.js";import{resolveShellProfile as A}from"../bash/profile.js";import{inspectGitVcsContext as k}from"./vcs-context.js";const M=80,O=6e3;function P(e){if("object"!=typeof e||null===e||!("annotations"in e))return;const t=e.annotations;if("object"!=typeof t||null===t)return;const s={};return"readOnlyHint"in t&&"boolean"==typeof t.readOnlyHint&&(s.readOnlyHint=t.readOnlyHint),"destructiveHint"in t&&"boolean"==typeof t.destructiveHint&&(s.destructiveHint=t.destructiveHint),void 0===s.readOnlyHint&&void 0===s.destructiveHint?void 0:s}function E(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function L(e){return Object.values(S).some(t=>t===e)}function R(e){return Object.values(y).some(t=>t===e)}function T(e){return{hints:void 0,issue:e}}function I(e){if(!E(e)||!E(e._meta))return{hints:void 0,issue:void 0};if(!Object.hasOwn(e._meta,v))return{hints:void 0,issue:void 0};const t=e._meta[v];if(!Array.isArray(t))return T("必须是数组");const s=[];for(const[e,i]of t.entries()){if(!E(i)||"string"!=typeof i.field||0===i.field.trim().length||"string"!=typeof i.kind||!L(i.kind)||void 0!==i.mode&&("string"!=typeof i.mode||!R(i.mode))||void 0!==i.namespace&&"string"!=typeof i.namespace||i.kind===S.custom&&("string"!=typeof i.namespace||0===i.namespace.trim().length))return T(`第 ${String(e+1)} 项字段无效`);const t=i.kind===S.custom&&"string"==typeof i.namespace?i.namespace.trim():void 0;s.push({field:i.field.trim(),kind:i.kind,...void 0!==i.mode?{mode:i.mode}:{},...void 0!==t?{namespace:t}:{}})}return{hints:s.length>0?s:void 0,issue:void 0}}function N(e){return"retry"===e.type?`安装遇到网络问题,${Math.round(e.delayMs/1e3)}s 后重试(第 ${e.attempt+1} 次)...`:"warn"===e.type?`警告:${e.message}`:e.message}async function U(e,t,s){"core-managed"===e.runtime.ownership&&(void 0===n(t,e.skill.name)&&a(e,t,s),await l(e))}export class ConversationEngine{config;clientManager;store;policy;maxSteps;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;acquireAgentUsage;debugEvents;explicitAgents;explicitModel;explicitSources;explicitSkillLibrary;onSkillLibraryIssue;onAgentBootstrapIssue;hostMode;resolveDynamicCapabilityContext;sessionExecEnabled;explicitShellProfile;resolveShellProfileFn;installAgentFn;resolveCatalogFn;inspectVcsContext;shellEnv;ready;refreshChain=Promise.resolve();resolvedCatalog;shellProfileResolution;shellUnsupportedWarned=!1;liveSessions=new Map;agentUsageLeases=new Map;disposePromise;closing=!1;constructor(e){this.config=e.config,this.clientManager=e.clientManager??new s,this.store=e.store,this.policy=e.policy,this.maxSteps=e.maxSteps??M,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.acquireAgentUsage=e.acquireAgentUsage??(e.ensureAgentReady?async(t,s)=>{await(e.ensureAgentReady?.(t,s))}:(e,t)=>this.acquireDefaultAgentUsage(e,t)),this.debugEvents=e.debugEvents??!1,this.hostMode=e.hostMode??x.embedded,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.sessionExecEnabled=e.sessionExecEnabled??!0,this.explicitShellProfile=e.shellProfile,this.resolveShellProfileFn=e.resolveShellProfileFn??A,this.explicitAgents=e.agents,this.explicitModel=e.model,this.explicitSources=e.sources,this.explicitSkillLibrary=e.skillLibrary,this.onSkillLibraryIssue=e.onSkillLibraryIssue,this.onAgentBootstrapIssue=e.onAgentBootstrapIssue,this.installAgentFn=e.installAgentFn??m,this.resolveCatalogFn=e.resolveCatalogFn??g,this.inspectVcsContext=e.inspectVcsContext??k,this.shellEnv={...e.shellEnv??process.env}}async acquireDefaultAgentUsage(e,t){const s=await c(e,this.config.agents.dataDir,t,{holderKind:"chat",startIfStopped:!0});if(void 0!==s)return s;await U(e,this.config.agents.dataDir,t)}async createSession(t={}){this.assertAcceptingSessions();const s=await this.ensureReady();this.assertAcceptingSessions();const i=this.store?this.store.createThread({...t.title?{title:t.title}:{},model:this.resolveModelName()}):e();return this.buildSession(s,i,[])}async resumeSession(e){if(this.assertAcceptingSessions(),!this.store)throw new Error("resumeSession requires a ThreadStore");const t=this.liveSessions.get(e);if(void 0!==t)return t;if(!this.store.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const s=await this.ensureReady();this.assertAcceptingSessions();const i=this.liveSessions.get(e);if(void 0!==i)return i;const o=this.store.loadSessionState(e);return this.buildSession(s,e,o.messages,o.checkpoint)}assertAcceptingSessions(){if(this.closing)throw new Error("ConversationEngine is closing")}resolveRuntimeShellProfile(){if(!this.config.runtime.shell.enabled)return;if(void 0!==this.explicitShellProfile)return this.explicitShellProfile??void 0;void 0===this.shellProfileResolution&&(this.shellProfileResolution=this.resolveShellProfileFn({platform:process.platform,env:this.shellEnv}));const e=this.shellProfileResolution;if(e.supported)return e.profile;if(!this.shellUnsupportedWarned){this.shellUnsupportedWarned=!0;const t="pwsh-version-unsupported"===e.reason?"检测到的 pwsh 版本低于 7":"未检测到 PowerShell 7 (pwsh)";process.stderr.write(`roll chat: ${t},Windows 原生 shell 工具已跳过注册;可运行 winget install Microsoft.PowerShell\n`)}}resolveShellSettings(e){const t=this.config.runtime.shell;return{workdir:process.cwd(),defaultTimeoutMs:t.defaultTimeoutMs,maxTimeoutMs:t.maxTimeoutMs,turnTimeoutMs:this.config.runtime.turnTimeoutMs,maxCaptureBytes:t.maxCaptureBytes,maxModelOutputChars:t.maxModelOutputChars,profile:e,env:this.shellEnv}}resolveSessionExecSettings(e){if(!this.sessionExecEnabled)return;const t=this.config.runtime.shell;return t.enabled&&t.session.enabled&&e.supportsSessionExec?{workdir:process.cwd(),profile:e,maxSessions:t.session.maxSessions,defaultYieldMs:t.session.defaultYieldMs,maxOutputTokens:t.session.maxOutputTokens,bufferCapacity:t.maxCaptureBytes,env:this.shellEnv}:void 0}buildSession(e,t,s,i){const o=this.store,r=w(this.resolveModelName(),this.config.runtime.contextWindow),n=(e.skillLibrary?.list()??[]).length>0?e.skillLibrary:void 0,a=this.resolveRuntimeShellProfile(),l=a?this.resolveShellSettings(a):void 0,c=a?this.resolveSessionExecSettings(a):void 0,h=a?a.supportsSafeCommandClassification&&this.config.runtime.shell.autoApproveSafe?a:C:void 0,u=this.resolveAgentInstallBinding(),d=this.composeCapabilityContext(e.sources.length,a),p=new b({id:t,model:e.model,sources:e.sources,capabilityContext:d,resolveDynamicCapabilityContext:async e=>{const[t,s]=await Promise.all([this.inspectVcsContext(d.cwd),this.resolveDynamicCapabilityContext?.(e)??{}]),i=s.vcs??t;return{...s.ruleIds?{ruleIds:s.ruleIds}:{},...i?{vcs:i}:{}}},...n?{skillLibrary:n}:{},...l?{bash:l}:{},...h?{bashClassifier:h}:{},...c?{bashSession:c}:{},...u?{agentInstall:u}:{},maxSteps:this.maxSteps,compaction:this.config.runtime.compaction,turnTimeoutMs:this.config.runtime.turnTimeoutMs,debugEvents:this.debugEvents,...this.providerOptions?{providerOptions:this.providerOptions}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},onProviderOptionsChange:e=>this.syncProviderOptions(e),...void 0!==r?{contextWindow:r}:{},...this.policy?{policy:this.policy}:{},initialMessages:s,...i?{initialCheckpoint:i}:{},...o?{onPersist:e=>o.appendMessages(t,e),onReplace:e=>o.replaceMessages(t,e),onToolExecution:e=>o.appendToolExecution(t,e),listToolExecutions:e=>o.listToolExecutions(t,e),getToolExecution:e=>o.getToolExecution(t,e),listTranscriptMessages:e=>o.listTranscriptMessages(t,e),commitCompaction:e=>o.commitCompaction(t,e),readCheckpointTranscript:e=>o.readCheckpointTranscript(t,e)}:{},onClose:()=>{this.liveSessions.get(t)===p&&this.liveSessions.delete(t)}});return this.liveSessions.set(t,p),p}syncProviderOptions(e){this.providerOptions=e,this.clientManager.setSamplingProviderOptions(e)}ensureReady(){return this.assertAcceptingSessions(),this.ready||(this.ready=this.bootstrap()),this.ready}async bootstrap(){const e=this.explicitModel??this.resolveModel();if(this.explicitSources)return{model:e,sources:this.explicitSources,...this.explicitSkillLibrary?{skillLibrary:this.explicitSkillLibrary}:{}};const t=this.explicitAgents??new o(this.config.agents.dataDir).list();this.agentInstallEnabled()&&(this.resolvedCatalog=await this.resolveCatalogFn(this.config,{allowNetwork:!1,...this.config.install.registry?{registry:this.config.install.registry}:{}}));const s=[];for(const i of t)try{s.push(await this.connectAgentSource(i,e))}catch(e){this.onAgentBootstrapIssue?.({agentName:i.skill.name,message:e instanceof Error?e.message:String(e)})}const i=this.resolveSkillLibrary(t);return{model:e,sources:s,...i?{skillLibrary:i}:{}}}async connectAgentSource(e,t){this.assertAcceptingSessions();const s=r(e),i=u(this.config,e.skill.name),o=void 0===this.agentUsageLeases.get(e.skill.name)?await this.acquireAgentUsage(e,i):void 0;try{this.assertAcceptingSessions();const r=await this.clientManager.connect(e.skill.name,s,e.installPath,{samplingModel:t,...this.providerOptions?{samplingProviderOptions:this.providerOptions}:{},...i?{env:i}:{}});this.assertAcceptingSessions();const n=(await r.listTools()).tools;this.assertAcceptingSessions();const a=h(n).map((t,s)=>{const i=I(n[s]);return void 0!==i.issue&&this.onAgentBootstrapIssue?.({agentName:e.skill.name,message:`Tool "${t.name}" 的 ${v} 无效(${i.issue}),已回退 Agent 级资源锁`}),{tool:t,annotations:P(n[s]),...i.hints?{resourceHints:i.hints}:{}}});return void 0!==o&&this.agentUsageLeases.set(e.skill.name,o),{agentName:e.skill.name,client:r,tools:a,...e.source?{agentSource:e.source.type}:{},transport:s.type,runtimeOwnership:e.runtime.ownership,..."stdio"===s.type?{resourceBaseDir:e.installPath}:{}}}catch(t){throw void 0!==o&&(await this.clientManager.disconnect(e.skill.name).catch(()=>{}),await o.release().catch(()=>{})),t}}async prepareAgentRefresh(e){this.assertAcceptingSessions();const t=this.refreshChain.then(()=>this.runAgentRefresh(e));return this.refreshChain=t.then(()=>{},()=>{}),t}async runAgentRefresh(e){const t=await this.ensureReady(),s=await this.connectAgentSource(e,t.model),i=[...t.sources.filter(e=>e.agentName!==s.agentName),s],r=this.explicitAgents??new o(this.config.agents.dataDir).list(),n=this.resolveSkillLibrary(r);this.ready=Promise.resolve({model:t.model,sources:i,...n?{skillLibrary:n}:{}});const a=n?.list()??[],l=n&&a.length>0?n:void 0,c=this.resolveRuntimeShellProfile();return{source:s,...l?{skillLibrary:l}:{},capabilityContext:this.composeCapabilityContext(i.length,c)}}composeCapabilityContext(e,t){const s=this.resolveAgentOnboardingInfo();return{profile:t?.toolName??"no-shell",hostMode:this.hostMode,cwd:process.cwd(),platform:process.platform,...t?{shellHints:t.systemPromptHints()}:{},agentCount:e,...s?{agentOnboardingCatalog:s}:{}}}agentInstallEnabled(){return void 0===this.explicitSources&&void 0===this.explicitAgents}currentCatalog(){return this.resolvedCatalog??p(this.config)}resolveAgentOnboardingInfo(){if(!this.agentInstallEnabled())return;const e=this.currentCatalog();return 0!==e.length?e.map(e=>({shortName:e.shortName,description:e.description})):void 0}resolveAgentInstallBinding(){if(!this.agentInstallEnabled())return;const e=this.currentCatalog();return 0!==e.length?{catalog:e.map(e=>({shortName:e.shortName,description:e.description})),install:(e,t)=>this.installCatalogAgent(e,t)}:void 0}async installCatalogAgent(e,t){const s=this.currentCatalog().find(t=>t.shortName===e);if(!s)return{outcome:{ok:!1,message:`未知的官方 Agent 短名: ${e}`}};const i=await this.installAgentFn({packageSpec:d(s),skipBrowserSetup:!0,autoStart:!1,expectedSkillName:s.skillName},{agentsConfig:this.config.agents,installConfig:this.config.install,getStartEnv:e=>u(this.config,e),report:e=>t(N(e))});if(!i.ok)return{outcome:{ok:!1,message:i.message,...i.retryCommand?{retryCommand:i.retryCommand}:{}}};const o=i.agent,r="installed-package"===o.source?.type?o.source.installedVersion:void 0,n="core-managed"===o.runtime.ownership&&void 0!==o.runtime.setup?.playwright,a={ok:!0,agentName:o.skill.name,...r?{version:r}:{},missingEnv:(i.envReport?.missingRequired??[]).map(e=>e.name),...n?{retryCommand:`roll agent install ${s.shortName}`}:{},refreshApplied:!1};if((await this.ensureReady()).sources.some(e=>e.agentName===o.skill.name))return t(`Agent "${o.skill.name}" 本会话已接入旧版本连接,更新需重启 roll chat 生效。`),{outcome:a};try{return{outcome:a,refresh:await this.prepareAgentRefresh(o)}}catch(e){return t(`接入新 Agent 失败:${e instanceof Error?e.message:String(e)}`),{outcome:a}}}resolveSkillLibrary(e){if(null!==this.explicitSkillLibrary)return void 0!==this.explicitSkillLibrary?this.explicitSkillLibrary:f({agents:e,extraDirs:this.config.skills.dirs,...this.onSkillLibraryIssue?{onIssue:this.onSkillLibraryIssue}:{}})}resolveModel(){const e=this.resolveProviderName(),t=this.resolveModelName(),s=this.config.llm.providers[e];if(!s)throw new Error(`LLM provider "${e}" 未配置`);return i(e,t,s.apiKey,s.baseUrl)}resolveProviderName(){return this.config.runtime.provider??this.config.llm.defaultProvider}resolveModelName(){return this.config.runtime.model??this.config.llm.defaultModel}async getContextSummary(){const e=await this.ensureReady();return this.assertAcceptingSessions(),{agentCount:e.sources.length,toolCount:e.sources.reduce((e,t)=>e+t.tools.length,0),skillCount:e.skillLibrary?.list().length??0}}async releaseAgentUsageLeases(){const e=[...this.agentUsageLeases.entries()],t=await Promise.allSettled(e.map(async([e,t])=>{try{await t.release()}finally{this.agentUsageLeases.get(e)===t&&this.agentUsageLeases.delete(e)}}));for(const e of t)"rejected"===e.status&&process.stderr.write(`roll chat: Agent 使用租约释放失败: ${e.reason instanceof Error?e.reason.message:String(e.reason)}\n`)}async dispose(){if(void 0!==this.disposePromise)return this.disposePromise;this.closing=!0;const e=Promise.allSettled([...this.ready?[this.ready]:[],this.refreshChain]).then(()=>{});return this.disposePromise=(async()=>{let s={failed:!1};try{await Promise.all([...this.liveSessions.values()].map(e=>e.close()))}catch(e){s={failed:!0,error:e}}this.liveSessions.clear();const i=await t(e,O);i||process.stderr.write(`roll chat: Engine 在 ${String(O)}ms 内未完成在飞初始化,将在其结束后再清理迟到连接\n`);let o={failed:!1};try{await this.clientManager.disconnectAll()}catch(e){o={failed:!0,error:e}}if(await this.releaseAgentUsageLeases(),i||e.then(async()=>{try{await this.clientManager.disconnectAll()}finally{await this.releaseAgentUsageLeases()}}).catch(e=>{process.stderr.write(`roll chat: 迟到 MCP/租约清理失败: ${e instanceof Error?e.message:String(e)}\n`)}),s.failed&&o.failed)throw new AggregateError([s.error,o.error],"ConversationEngine 关闭 session 与 MCP 连接均失败。");if(s.failed)throw s.error;if(o.failed)throw o.error})(),this.disposePromise}}
1
+ import{randomUUID as e}from"node:crypto";import{McpClientManager as t}from"@roll-agent/core/mcp/client-manager";import{createProviderModel as s}from"@roll-agent/core/llm/providers";import{AgentStore as i}from"@roll-agent/core/registry/store";import{resolveTransportWithDevSpawnSpec as o}from"@roll-agent/core/registry/dev-spawn";import{getAgentPid as n,startAgent as r,waitForAgentReady as a}from"@roll-agent/core/registry/process-manager";import{acquireAgentUsageLease as l}from"@roll-agent/core/registry/agent-usage-lease";import{normalizeListedTools as c}from"@roll-agent/core/cli/utils/agent-tools";import{getAgentEnv as h}from"@roll-agent/core/config/helpers";import{catalogPackageSpec as u,getAgentCatalog as d}from"@roll-agent/core/registry/catalog";import{resolveAgentCatalog as g}from"@roll-agent/core/registry/catalog-discovery";import{installAgent as p}from"@roll-agent/core/registry/install";import{createSkillLibrary as m}from"@roll-agent/core/skills/library";import{ROLL_RESOURCE_HINTS_META_KEY as f}from"../tool-bridge/build-tools.js";import{TOOL_RESOURCE_ACCESS_MODES as v,TOOL_RESOURCE_HINT_KINDS as y}from"../tool-bridge/tool-execution-coordinator.js";import{AgentSession as w}from"./agent-session.js";import{resolveContextWindow as b}from"./context-window.js";import{CAPABILITY_HOST_MODES as S}from"./capability-manifest.js";import{}from"../tool-bridge/bash-tool.js";import{unknownCommandClassifier as C}from"../types/command-classification.js";import{resolveShellProfile as A}from"../bash/profile.js";import{inspectGitVcsContext as x}from"./vcs-context.js";import{AGENT_BOOTSTRAP_MAX_CONCURRENCY as k,mapWithBoundedConcurrency as E}from"./agent-bootstrap.js";const M=80,O="ConversationEngine is closing",P=3e4,L=6e4,T={connected:"connected",failed:"failed"};class AgentBootstrapTimeoutError extends Error{constructor(e){super(`Agent bootstrap timed out after ${String(e)}ms`),this.name="AgentBootstrapTimeoutError"}}class AgentBootstrapCleanupError extends AggregateError{cleanupErrors;constructor(e,t,s){const i=s.map(e=>e instanceof Error?e.message:String(e)).join("; ");super([t,...s],`Agent "${e}" bootstrap failed and resource cleanup also failed: ${i}`),this.name="AgentBootstrapCleanupError",this.cleanupErrors=s}}function R(){return new Error(O)}function N(e){return e.reason??new Error("Operation aborted")}function I(e){if(!0===e?.aborted)throw N(e)}function B(e,t){return void 0===t?e:Math.max(1,Math.min(e,t-Date.now()))}function U(e){if(void 0!==e&&Date.now()>=e)throw new Error("Agent bootstrap deadline expired")}function j(e){if("object"!=typeof e||null===e||!("annotations"in e))return;const t=e.annotations;if("object"!=typeof t||null===t)return;const s={};return"readOnlyHint"in t&&"boolean"==typeof t.readOnlyHint&&(s.readOnlyHint=t.readOnlyHint),"destructiveHint"in t&&"boolean"==typeof t.destructiveHint&&(s.destructiveHint=t.destructiveHint),void 0===s.readOnlyHint&&void 0===s.destructiveHint?void 0:s}function D(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function $(e){return Object.values(y).some(t=>t===e)}function H(e){return Object.values(v).some(t=>t===e)}function F(e){return{hints:void 0,issue:e}}function q(e){if(!D(e)||!D(e._meta))return{hints:void 0,issue:void 0};if(!Object.hasOwn(e._meta,f))return{hints:void 0,issue:void 0};const t=e._meta[f];if(!Array.isArray(t))return F("必须是数组");const s=[];for(const[e,i]of t.entries()){if(!D(i)||"string"!=typeof i.field||0===i.field.trim().length||"string"!=typeof i.kind||!$(i.kind)||void 0!==i.mode&&("string"!=typeof i.mode||!H(i.mode))||void 0!==i.namespace&&"string"!=typeof i.namespace||i.kind===y.custom&&("string"!=typeof i.namespace||0===i.namespace.trim().length))return F(`第 ${String(e+1)} 项字段无效`);const t=i.kind===y.custom&&"string"==typeof i.namespace?i.namespace.trim():void 0;s.push({field:i.field.trim(),kind:i.kind,...void 0!==i.mode?{mode:i.mode}:{},...void 0!==t?{namespace:t}:{}})}return{hints:s.length>0?s:void 0,issue:void 0}}function W(e){return"retry"===e.type?`安装遇到网络问题,${Math.round(e.delayMs/1e3)}s 后重试(第 ${e.attempt+1} 次)...`:"warn"===e.type?`警告:${e.message}`:e.message}async function V(e,t,s,i){I(i),"core-managed"===e.runtime.ownership&&(void 0===n(t,e.skill.name)&&r(e,t,s),await a(e,{...i?{signal:i}:{}}))}export class ConversationEngine{config;clientManager;store;policy;maxSteps;providerOptions;structuredOutputProviderOptions;structuredOutputReasoning;acquireAgentUsage;debugEvents;explicitAgents;explicitModel;explicitSources;explicitSkillLibrary;onSkillLibraryIssue;onAgentBootstrapIssue;hostMode;resolveDynamicCapabilityContext;sessionExecEnabled;explicitShellProfile;resolveShellProfileFn;installAgentFn;resolveCatalogFn;inspectVcsContext;shellEnv;ready;refreshChain=Promise.resolve();resolvedCatalog;shellProfileResolution;shellUnsupportedWarned=!1;liveSessions=new Map;agentUsageLeases=new Map;shutdownController=new AbortController;disposePromise;closing=!1;constructor(e){this.config=e.config,this.clientManager=e.clientManager??new t,this.store=e.store,this.policy=e.policy,this.maxSteps=e.maxSteps??M,this.providerOptions=e.providerOptions,this.structuredOutputProviderOptions=e.structuredOutputProviderOptions,this.structuredOutputReasoning=e.structuredOutputReasoning,this.acquireAgentUsage=e.acquireAgentUsage??(e.ensureAgentReady?async(t,s,i)=>{await(e.ensureAgentReady?.(t,s,i))}:(e,t,s)=>this.acquireDefaultAgentUsage(e,t,s)),this.debugEvents=e.debugEvents??!1,this.hostMode=e.hostMode??S.embedded,this.resolveDynamicCapabilityContext=e.resolveDynamicCapabilityContext,this.sessionExecEnabled=e.sessionExecEnabled??!0,this.explicitShellProfile=e.shellProfile,this.resolveShellProfileFn=e.resolveShellProfileFn??A,this.explicitAgents=e.agents,this.explicitModel=e.model,this.explicitSources=e.sources,this.explicitSkillLibrary=e.skillLibrary,this.onSkillLibraryIssue=e.onSkillLibraryIssue,this.onAgentBootstrapIssue=e.onAgentBootstrapIssue,this.installAgentFn=e.installAgentFn??p,this.resolveCatalogFn=e.resolveCatalogFn??g,this.inspectVcsContext=e.inspectVcsContext??x,this.shellEnv={...e.shellEnv??process.env}}async acquireDefaultAgentUsage(e,t,s){const i=await l(e,this.config.agents.dataDir,t,{holderKind:"chat",startIfStopped:!0,...s?{signal:s}:{}});if(void 0!==i)return i;await V(e,this.config.agents.dataDir,t,s)}async createSession(t={}){this.assertAcceptingSessions();const s=await this.ensureReady();this.assertAcceptingSessions();const i=this.store?this.store.createThread({...t.title?{title:t.title}:{},model:this.resolveModelName()}):e();return this.buildSession(s,i,[])}async resumeSession(e){if(this.assertAcceptingSessions(),!this.store)throw new Error("resumeSession requires a ThreadStore");const t=this.liveSessions.get(e);if(void 0!==t)return t;if(!this.store.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const s=await this.ensureReady();this.assertAcceptingSessions();const i=this.liveSessions.get(e);if(void 0!==i)return i;const o=this.store.loadSessionState(e);return this.buildSession(s,e,o.messages,o.checkpoint)}assertAcceptingSessions(){if(this.closing)throw R()}resolveRuntimeShellProfile(){if(!this.config.runtime.shell.enabled)return;if(void 0!==this.explicitShellProfile)return this.explicitShellProfile??void 0;void 0===this.shellProfileResolution&&(this.shellProfileResolution=this.resolveShellProfileFn({platform:process.platform,env:this.shellEnv}));const e=this.shellProfileResolution;if(e.supported)return e.profile;if(!this.shellUnsupportedWarned){this.shellUnsupportedWarned=!0;const t="pwsh-version-unsupported"===e.reason?"检测到的 pwsh 版本低于 7":"未检测到 PowerShell 7 (pwsh)";process.stderr.write(`roll chat: ${t},Windows 原生 shell 工具已跳过注册;可运行 winget install Microsoft.PowerShell\n`)}}resolveShellSettings(e){const t=this.config.runtime.shell;return{workdir:process.cwd(),defaultTimeoutMs:t.defaultTimeoutMs,maxTimeoutMs:t.maxTimeoutMs,turnTimeoutMs:this.config.runtime.turnTimeoutMs,maxCaptureBytes:t.maxCaptureBytes,maxModelOutputChars:t.maxModelOutputChars,profile:e,env:this.shellEnv}}resolveSessionExecSettings(e){if(!this.sessionExecEnabled)return;const t=this.config.runtime.shell;return t.enabled&&t.session.enabled&&e.supportsSessionExec?{workdir:process.cwd(),profile:e,maxSessions:t.session.maxSessions,defaultYieldMs:t.session.defaultYieldMs,maxOutputTokens:t.session.maxOutputTokens,bufferCapacity:t.maxCaptureBytes,env:this.shellEnv}:void 0}buildSession(e,t,s,i){const o=this.store,n=b(this.resolveModelName(),this.config.runtime.contextWindow),r=(e.skillLibrary?.list()??[]).length>0?e.skillLibrary:void 0,a=this.resolveRuntimeShellProfile(),l=a?this.resolveShellSettings(a):void 0,c=a?this.resolveSessionExecSettings(a):void 0,h=a?a.supportsSafeCommandClassification&&this.config.runtime.shell.autoApproveSafe?a:C:void 0,u=this.resolveAgentInstallBinding(),d=this.composeCapabilityContext(e.sources.length,a),g=new w({id:t,model:e.model,sources:e.sources,capabilityContext:d,resolveDynamicCapabilityContext:async e=>{const[t,s]=await Promise.all([this.inspectVcsContext(d.cwd),this.resolveDynamicCapabilityContext?.(e)??{}]),i=s.vcs??t;return{...s.ruleIds?{ruleIds:s.ruleIds}:{},...i?{vcs:i}:{}}},...r?{skillLibrary:r}:{},...l?{bash:l}:{},...h?{bashClassifier:h}:{},...c?{bashSession:c}:{},...u?{agentInstall:u}:{},maxSteps:this.maxSteps,compaction:this.config.runtime.compaction,turnTimeoutMs:this.config.runtime.turnTimeoutMs,debugEvents:this.debugEvents,...this.providerOptions?{providerOptions:this.providerOptions}:{},...this.structuredOutputProviderOptions?{structuredOutputProviderOptions:this.structuredOutputProviderOptions}:{},...this.structuredOutputReasoning?{structuredOutputReasoning:this.structuredOutputReasoning}:{},onProviderOptionsChange:e=>this.syncProviderOptions(e),...void 0!==n?{contextWindow:n}:{},...this.policy?{policy:this.policy}:{},initialMessages:s,...i?{initialCheckpoint:i}:{},...o?{onPersist:e=>o.appendMessages(t,e),onReplace:e=>o.replaceMessages(t,e),onToolExecution:e=>o.appendToolExecution(t,e),listToolExecutions:e=>o.listToolExecutions(t,e),getToolExecution:e=>o.getToolExecution(t,e),listTranscriptMessages:e=>o.listTranscriptMessages(t,e),commitCompaction:e=>o.commitCompaction(t,e),readCheckpointTranscript:e=>o.readCheckpointTranscript(t,e)}:{},onClose:()=>{this.liveSessions.get(t)===g&&this.liveSessions.delete(t)}});return this.liveSessions.set(t,g),g}syncProviderOptions(e){this.providerOptions=e,this.clientManager.setSamplingProviderOptions(e)}ensureReady(){return this.assertAcceptingSessions(),this.ready||(this.ready=this.bootstrap()),this.ready}async bootstrap(){const e=Date.now(),t=this.explicitModel??this.resolveModel();if(this.explicitSources)return{model:t,sources:this.explicitSources,...this.explicitSkillLibrary?{skillLibrary:this.explicitSkillLibrary}:{}};const s=this.explicitAgents??new i(this.config.agents.dataDir).list(),o=this.config.runtime.agentBootstrap.timeoutMs,n=e+o,r=new AbortController,a=new AgentBootstrapTimeoutError(o);let l=!1;const c=()=>{r.signal.aborted||r.abort(N(this.shutdownController.signal))},h=()=>{!this.closing&&!r.signal.aborted&&Date.now()>=n&&(l=!0,r.abort(a))};this.shutdownController.signal.aborted?c():this.shutdownController.signal.addEventListener("abort",c,{once:!0});const u=setTimeout(()=>{this.closing||r.signal.aborted||(l=!0,r.abort(a))},Math.max(0,n-Date.now())),d=(e,t)=>({kind:T.failed,issues:[{agentName:e.skill.name,message:a.message},...void 0===t?[]:[{agentName:e.skill.name,message:t.message}]]});try{if(this.agentInstallEnabled())try{this.resolvedCatalog=await this.resolveCatalogFn(this.config,{allowNetwork:!1,signal:r.signal,...this.config.install.registry?{registry:this.config.install.registry}:{}})}catch(e){if(this.closing||this.shutdownController.signal.aborted)throw R();if(h(),!l)throw e}if(this.closing||this.shutdownController.signal.aborted)throw R();if(h(),0===s.length){const e=this.resolveSkillLibrary(s);return{model:t,sources:[],...e?{skillLibrary:e}:{}}}const e=await E(s,k,async e=>{const s=[],i=e=>{s.push(e)};try{h(),I(r.signal);const o=await this.connectAgentSource(e,t,i,{signal:r.signal,deadlineAt:n});return{kind:T.connected,source:o,issues:s}}catch(t){if(this.closing||this.shutdownController.signal.aborted)throw R();return h(),l?d(e,t instanceof AgentBootstrapCleanupError?t:void 0):(s.push({agentName:e.skill.name,message:t instanceof Error?t.message:String(t)}),{kind:T.failed,issues:s})}},{signal:r.signal,onSkipped:e=>d(e)});if(this.closing||this.shutdownController.signal.aborted)throw R();const i=[];for(const t of e){for(const e of t.issues)this.onAgentBootstrapIssue?.(e);t.kind===T.connected&&i.push(t.source)}const o=this.resolveSkillLibrary(s);return{model:t,sources:i,...o?{skillLibrary:o}:{}}}finally{clearTimeout(u),this.shutdownController.signal.removeEventListener("abort",c)}}async connectAgentSource(e,t,s=e=>this.onAgentBootstrapIssue?.(e),i={}){this.assertAcceptingSessions(),I(i.signal),U(i.deadlineAt);const n=o(e),r=h(this.config,e.skill.name),a=this.agentUsageLeases.get(e.skill.name);let l,u;try{l=void 0===a?await this.acquireAgentUsage(e,r,i.signal):void 0,this.assertAcceptingSessions(),I(i.signal),U(i.deadlineAt);const o={timeoutMs:B(P,i.deadlineAt),samplingModel:t,...this.providerOptions?{samplingProviderOptions:this.providerOptions}:{},...r?{env:r}:{},...i.signal?{signal:i.signal}:{}},h=this.clientManager.connectWithOwnership;u="function"==typeof h?await h.call(this.clientManager,e.skill.name,n,e.installPath,o):{client:await this.clientManager.connect(e.skill.name,n,e.installPath,o),commit:()=>{},rollback:async()=>{}},this.assertAcceptingSessions(),I(i.signal),U(i.deadlineAt);const d=(await u.client.listTools(void 0,{timeout:B(L,i.deadlineAt),...i.signal?{signal:i.signal}:{}})).tools;this.assertAcceptingSessions(),I(i.signal),U(i.deadlineAt);const g=c(d).map((t,i)=>{const o=q(d[i]);return void 0!==o.issue&&s({agentName:e.skill.name,message:`Tool "${t.name}" 的 ${f} 无效(${o.issue}),已回退 Agent 级资源锁`}),{tool:t,annotations:j(d[i]),...o.hints?{resourceHints:o.hints}:{}}});return u.commit(),void 0!==l&&this.agentUsageLeases.set(e.skill.name,l),{agentName:e.skill.name,client:u.client,tools:g,...e.source?{agentSource:e.source.type}:{},transport:n.type,runtimeOwnership:e.runtime.ownership,..."stdio"===n.type?{resourceBaseDir:e.installPath}:{}}}catch(t){const s=[];if(void 0!==u&&await u.rollback().catch(e=>{s.push(e)}),void 0!==l){const t=l;await t.release().catch(i=>{this.agentUsageLeases.set(e.skill.name,t),s.push(i)})}if(s.length>0)throw new AgentBootstrapCleanupError(e.skill.name,t,s);throw t}}async prepareAgentRefresh(e){this.assertAcceptingSessions();const t=this.refreshChain.then(()=>this.runAgentRefresh(e));return this.refreshChain=t.then(()=>{},()=>{}),t}async runAgentRefresh(e){const t=await this.ensureReady(),s=await this.connectAgentSource(e,t.model,void 0,{signal:this.shutdownController.signal}),o=[...t.sources.filter(e=>e.agentName!==s.agentName),s],n=this.explicitAgents??new i(this.config.agents.dataDir).list(),r=this.resolveSkillLibrary(n);this.ready=Promise.resolve({model:t.model,sources:o,...r?{skillLibrary:r}:{}});const a=r?.list()??[],l=r&&a.length>0?r:void 0,c=this.resolveRuntimeShellProfile();return{source:s,...l?{skillLibrary:l}:{},capabilityContext:this.composeCapabilityContext(o.length,c)}}composeCapabilityContext(e,t){const s=this.resolveAgentOnboardingInfo();return{profile:t?.toolName??"no-shell",hostMode:this.hostMode,cwd:process.cwd(),platform:process.platform,...t?{shellHints:t.systemPromptHints()}:{},agentCount:e,...s?{agentOnboardingCatalog:s}:{}}}agentInstallEnabled(){return void 0===this.explicitSources&&void 0===this.explicitAgents}currentCatalog(){return this.resolvedCatalog??d(this.config)}resolveAgentOnboardingInfo(){if(!this.agentInstallEnabled())return;const e=this.currentCatalog();return 0!==e.length?e.map(e=>({shortName:e.shortName,description:e.description})):void 0}resolveAgentInstallBinding(){if(!this.agentInstallEnabled())return;const e=this.currentCatalog();return 0!==e.length?{catalog:e.map(e=>({shortName:e.shortName,description:e.description})),install:(e,t)=>this.installCatalogAgent(e,t)}:void 0}async installCatalogAgent(e,t){const s=this.currentCatalog().find(t=>t.shortName===e);if(!s)return{outcome:{ok:!1,message:`未知的官方 Agent 短名: ${e}`}};const i=await this.installAgentFn({packageSpec:u(s),skipBrowserSetup:!0,autoStart:!1,expectedSkillName:s.skillName},{agentsConfig:this.config.agents,installConfig:this.config.install,getStartEnv:e=>h(this.config,e),report:e=>t(W(e))});if(!i.ok)return{outcome:{ok:!1,message:i.message,...i.retryCommand?{retryCommand:i.retryCommand}:{}}};const o=i.agent,n="installed-package"===o.source?.type?o.source.installedVersion:void 0,r="core-managed"===o.runtime.ownership&&void 0!==o.runtime.setup?.playwright,a={ok:!0,agentName:o.skill.name,...n?{version:n}:{},missingEnv:(i.envReport?.missingRequired??[]).map(e=>e.name),...r?{retryCommand:`roll agent install ${s.shortName}`}:{},refreshApplied:!1};if((await this.ensureReady()).sources.some(e=>e.agentName===o.skill.name))return t(`Agent "${o.skill.name}" 本会话已接入旧版本连接,更新需重启 roll chat 生效。`),{outcome:a};try{return{outcome:a,refresh:await this.prepareAgentRefresh(o)}}catch(e){return t(`接入新 Agent 失败:${e instanceof Error?e.message:String(e)}`),{outcome:a}}}resolveSkillLibrary(e){if(null!==this.explicitSkillLibrary)return void 0!==this.explicitSkillLibrary?this.explicitSkillLibrary:m({agents:e,extraDirs:this.config.skills.dirs,...this.onSkillLibraryIssue?{onIssue:this.onSkillLibraryIssue}:{}})}resolveModel(){const e=this.resolveProviderName(),t=this.resolveModelName(),i=this.config.llm.providers[e];if(!i)throw new Error(`LLM provider "${e}" 未配置`);return s(e,t,i.apiKey,i.baseUrl)}resolveProviderName(){return this.config.runtime.provider??this.config.llm.defaultProvider}resolveModelName(){return this.config.runtime.model??this.config.llm.defaultModel}async getContextSummary(){const e=await this.ensureReady();return this.assertAcceptingSessions(),{agentCount:e.sources.length,toolCount:e.sources.reduce((e,t)=>e+t.tools.length,0),skillCount:e.skillLibrary?.list().length??0}}async releaseAgentUsageLeases(){const e=[...this.agentUsageLeases.entries()],t=await Promise.allSettled(e.map(async([e,t])=>{try{await t.release()}finally{this.agentUsageLeases.get(e)===t&&this.agentUsageLeases.delete(e)}}));for(const e of t)"rejected"===e.status&&process.stderr.write(`roll chat: Agent 使用租约释放失败: ${e.reason instanceof Error?e.reason.message:String(e.reason)}\n`)}async dispose(){if(void 0!==this.disposePromise)return this.disposePromise;this.closing=!0,this.shutdownController.abort(R());const e=Promise.allSettled([...this.ready?[this.ready]:[],this.refreshChain]).then(()=>{});return this.disposePromise=(async()=>{let t={failed:!1};try{await Promise.all([...this.liveSessions.values()].map(e=>e.close()))}catch(e){t={failed:!0,error:e}}this.liveSessions.clear(),await e;let s={failed:!1};try{await this.clientManager.disconnectAll()}catch(e){s={failed:!0,error:e}}if(await this.releaseAgentUsageLeases(),t.failed&&s.failed)throw new AggregateError([t.error,s.error],"ConversationEngine 关闭 session 与 MCP 连接均失败。");if(t.failed)throw t.error;if(s.failed)throw s.error})(),this.disposePromise}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@roll-agent/runtime",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -33,7 +33,7 @@
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/node": "^22.0.0",
36
- "@roll-agent/core": "0.22.0"
36
+ "@roll-agent/core": "0.23.0"
37
37
  },
38
38
  "scripts": {
39
39
  "build": "rm -rf dist && tsc -p tsconfig.build.json && node ../../scripts/obfuscate.mjs",