@roll-agent/runtime 0.9.0 → 0.11.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/dist/index.d.ts CHANGED
@@ -28,6 +28,8 @@ export type { ToolPolicy, ToolPolicyContext, PolicyDecision, PolicyAction, ToolA
28
28
  export { ApprovalGate } from "./approval/approval-gate.ts";
29
29
  export type { ApprovalDecision } from "./approval/approval-gate.ts";
30
30
  export { RuntimeServer } from "./server/runtime-server.ts";
31
+ export { RuntimeService, RuntimeServiceError } from "./service/runtime-service.ts";
32
+ export type { RuntimeServiceEngine, RuntimeServiceOptions, RuntimeServiceSession, } from "./service/runtime-service.ts";
31
33
  export { createStdioConnection } from "./server/transport/stdio.ts";
32
34
  export { RpcMethod, EVENT_NOTIFICATION, isRequest } from "./server/protocol.ts";
33
35
  export type { JsonRpcConnection, JsonRpcMessage, JsonRpcRequest, JsonRpcNotification, JsonRpcId, } from "./server/protocol.ts";
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export{ConversationEngine}from"./engine/conversation-engine.js";export{AgentSession}from"./engine/agent-session.js";export{resolveContextWindow,lookupContextWindow}from"./engine/context-window.js";export{compactMessages,findTurnBoundaries,SUMMARY_PREFIX,SUMMARY_ACK}from"./engine/compactor.js";export{ROLL_RESOURCE_HINTS_META_KEY,buildAgentToolset}from"./tool-bridge/build-tools.js";export{COMMAND_CLASSIFICATIONS,unknownCommandClassifier}from"./types/command-classification.js";export{ruleBasedClassifier}from"./bash/classifier/index.js";export{buildPowerShellEncodedCommand,resolveShellProfile,SHELL_PROFILE_IDS,SHELL_TOOL_NAMES}from"./bash/profile.js";export{buildSessionExecToolset,EXEC_COMMAND_ID,EXEC_LIST_ID,EXEC_POLL_ID}from"./tool-bridge/session-exec-tool.js";export{ToolRegistry}from"./tool-bridge/naming.js";export{TOOL_RESOURCE_ACCESS_MODES,TOOL_RESOURCE_HINT_KINDS}from"./tool-bridge/tool-execution-coordinator.js";export{TOOL_OUTCOME_KINDS,normalizeToolResult,readToolOutcome}from"./tool-bridge/normalize-result.js";export{ThreadStore,defaultThreadsDir,expandTilde}from"./store/thread-store.js";export{DefaultToolPolicy}from"./policy/default-policy.js";export{ConfigurableToolPolicy}from"./policy/configurable-policy.js";export{ApprovalGate}from"./approval/approval-gate.js";export{RuntimeServer}from"./server/runtime-server.js";export{createStdioConnection}from"./server/transport/stdio.js";export{RpcMethod,EVENT_NOTIFICATION,isRequest}from"./server/protocol.js";export{createTurnCancellationMessage,readTurnCancellationReason,SESSION_CANCELLATION_REASONS,USER_CANCELLATION_ABORT_REASON}from"./types/cancellation.js";
1
+ export{ConversationEngine}from"./engine/conversation-engine.js";export{AgentSession}from"./engine/agent-session.js";export{resolveContextWindow,lookupContextWindow}from"./engine/context-window.js";export{compactMessages,findTurnBoundaries,SUMMARY_PREFIX,SUMMARY_ACK}from"./engine/compactor.js";export{ROLL_RESOURCE_HINTS_META_KEY,buildAgentToolset}from"./tool-bridge/build-tools.js";export{COMMAND_CLASSIFICATIONS,unknownCommandClassifier}from"./types/command-classification.js";export{ruleBasedClassifier}from"./bash/classifier/index.js";export{buildPowerShellEncodedCommand,resolveShellProfile,SHELL_PROFILE_IDS,SHELL_TOOL_NAMES}from"./bash/profile.js";export{buildSessionExecToolset,EXEC_COMMAND_ID,EXEC_LIST_ID,EXEC_POLL_ID}from"./tool-bridge/session-exec-tool.js";export{ToolRegistry}from"./tool-bridge/naming.js";export{TOOL_RESOURCE_ACCESS_MODES,TOOL_RESOURCE_HINT_KINDS}from"./tool-bridge/tool-execution-coordinator.js";export{TOOL_OUTCOME_KINDS,normalizeToolResult,readToolOutcome}from"./tool-bridge/normalize-result.js";export{ThreadStore,defaultThreadsDir,expandTilde}from"./store/thread-store.js";export{DefaultToolPolicy}from"./policy/default-policy.js";export{ConfigurableToolPolicy}from"./policy/configurable-policy.js";export{ApprovalGate}from"./approval/approval-gate.js";export{RuntimeServer}from"./server/runtime-server.js";export{RuntimeService,RuntimeServiceError}from"./service/runtime-service.js";export{createStdioConnection}from"./server/transport/stdio.js";export{RpcMethod,EVENT_NOTIFICATION,isRequest}from"./server/protocol.js";export{createTurnCancellationMessage,readTurnCancellationReason,SESSION_CANCELLATION_REASONS,USER_CANCELLATION_ABORT_REASON}from"./types/cancellation.js";
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import type { RuntimeProtocolErrorData } from "@roll-agent/protocol";
2
3
  export type JsonRpcId = number | string;
3
4
  export interface JsonRpcRequest {
4
5
  readonly jsonrpc: "2.0";
@@ -22,6 +23,7 @@ export interface JsonRpcErrorResponse {
22
23
  readonly error: {
23
24
  readonly code: number;
24
25
  readonly message: string;
26
+ readonly data?: RuntimeProtocolErrorData;
25
27
  };
26
28
  }
27
29
  export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcSuccessResponse | JsonRpcErrorResponse;
@@ -0,0 +1,13 @@
1
+ import { type JsonRpcRequest, type RuntimeMethod } from "@roll-agent/protocol";
2
+ import { RuntimeService } from "../service/runtime-service.ts";
3
+ import type { JsonRpcConnection } from "./protocol.ts";
4
+ export declare class RuntimeProtocolAdapter {
5
+ private readonly service;
6
+ private readonly connection;
7
+ private readonly unsubscribe;
8
+ private initialized;
9
+ constructor(service: RuntimeService, connection: JsonRpcConnection);
10
+ handles(method: string): method is RuntimeMethod;
11
+ dispatch(request: JsonRpcRequest): Promise<unknown>;
12
+ close(): Promise<void>;
13
+ }
@@ -0,0 +1 @@
1
+ import{RUNTIME_ERROR_CODES as e,RUNTIME_EVENT_NOTIFICATION as a,RUNTIME_METHODS as r,isRuntimeMethod as s,runtimeMethodSchemas as t}from"@roll-agent/protocol";import{RuntimeService as i,RuntimeServiceError as n}from"../service/runtime-service.js";export class RuntimeProtocolAdapter{service;connection;unsubscribe;initialized=!1;constructor(e,r){this.service=e,this.connection=r,this.unsubscribe=e.onEvent(e=>{this.initialized&&this.connection.send({jsonrpc:"2.0",method:a,params:e})})}handles(e){return s(e)}async dispatch(a){if(!this.handles(a.method))throw new n(e.capabilityUnavailable,`未知 Runtime Protocol 方法:${a.method}`);if(a.method===r.initialize){const e=t[r.initialize].params.parse(a.params),s=this.service.initialize(e);return this.initialized=!0,s}if(!this.initialized)throw new n(e.initializeRequired,"调用 Runtime Protocol 方法前必须先完成 initialize");switch(a.method){case r.threadList:return this.service.listThreads(t[r.threadList].params.parse(a.params));case r.threadCreate:return this.service.createThread(t[r.threadCreate].params.parse(a.params));case r.threadOpen:return this.service.openThread(t[r.threadOpen].params.parse(a.params));case r.threadSnapshot:return this.service.snapshotThread(t[r.threadSnapshot].params.parse(a.params));case r.threadRename:return this.service.renameThread(t[r.threadRename].params.parse(a.params));case r.threadDelete:return this.service.deleteThread(t[r.threadDelete].params.parse(a.params));case r.threadDetach:return this.service.detachThread(t[r.threadDetach].params.parse(a.params));case r.threadCapabilities:return this.service.threadCapabilities(t[r.threadCapabilities].params.parse(a.params));case r.turnStart:return this.service.startTurn(t[r.turnStart].params.parse(a.params));case r.turnCancel:return this.service.cancelTurn(t[r.turnCancel].params.parse(a.params));case r.approvalRespond:return this.service.respondApproval(t[r.approvalRespond].params.parse(a.params));case r.operationGet:return this.service.getOperation(t[r.operationGet].params.parse(a.params))}}async close(){this.unsubscribe(),await this.service.close()}}
@@ -1,4 +1,5 @@
1
1
  import type { ConversationEngine } from "../engine/conversation-engine.ts";
2
+ import { type RuntimeService } from "../service/runtime-service.ts";
2
3
  import { type JsonRpcConnection } from "./protocol.ts";
3
4
  export interface RawToolEvidenceAccessRequest {
4
5
  readonly sessionId: string;
@@ -10,6 +11,8 @@ export interface RuntimeServerOptions {
10
11
  * Omission is deny-by-default; `includeRaw: true` is only a request, never authorization.
11
12
  */
12
13
  readonly authorizeRawToolEvidence?: (request: RawToolEvidenceAccessRequest) => boolean | Promise<boolean>;
14
+ /** Versioned public Runtime Protocol adapter. Legacy `session.*` remains available. */
15
+ readonly runtimeService?: RuntimeService;
13
16
  }
14
17
  /**
15
18
  * JSON-RPC host for trusted local transports.
@@ -24,6 +27,7 @@ export declare class RuntimeServer {
24
27
  private readonly connection;
25
28
  private readonly authorizeRawToolEvidence;
26
29
  private readonly sessions;
30
+ private readonly protocolAdapter;
27
31
  constructor(engine: ConversationEngine, connection: JsonRpcConnection, options?: RuntimeServerOptions);
28
32
  abortAll(): Promise<void>;
29
33
  private handleMessage;
@@ -1 +1 @@
1
- import{createSafeCapabilitySnapshot as e}from"../engine/capability-manifest.js";import{isPersistedToolExecutionRecord as s}from"../tool-bridge/tool-execution-record.js";import{EVENT_NOTIFICATION as o,RpcMethod as i,abortParamsSchema as n,approveParamsSchema as t,capabilitiesParamsSchema as r,closeParamsSchema as a,compactParamsSchema as c,createParamsSchema as d,isRequest as l,messagesParamsSchema as u,rejectParamsSchema as p,resumeParamsSchema as h,sendParamsSchema as m,toolExecutionsParamsSchema as w}from"./protocol.js";function I(e){return e instanceof Error?e.message:String(e)}export class RuntimeServer{engine;connection;authorizeRawToolEvidence;sessions=new Map;constructor(e,s,o={}){this.engine=e,this.connection=s,this.authorizeRawToolEvidence=o.authorizeRawToolEvidence,this.connection.onMessage(e=>this.handleMessage(e))}async abortAll(){const e=[...this.sessions.values()];this.sessions.clear(),await Promise.all(e.map(e=>e.close()))}handleMessage(e){l(e)&&this.dispatch(e).then(s=>{this.connection.send({jsonrpc:"2.0",id:e.id,result:s})}).catch(s=>{this.connection.send({jsonrpc:"2.0",id:e.id,error:{code:-32e3,message:I(s)}})})}requireSession(e){const s=this.sessions.get(e);if(!s)throw new Error(`Session "${e}" 不存在`);return s}async dispatch(l){switch(l.method){case i.Create:{const e=d.parse(l.params),s=await this.engine.createSession(e.title?{title:e.title}:{});return this.sessions.set(s.id,s),{sessionId:s.id}}case i.Resume:{const e=h.parse(l.params),s=await this.engine.resumeSession(e.threadId);return this.sessions.set(s.id,s),{sessionId:s.id}}case i.Send:{const e=m.parse(l.params),s=this.requireSession(e.sessionId);for await(const i of s.send(e.input))this.connection.send({jsonrpc:"2.0",method:o,params:{sessionId:e.sessionId,event:i}});return{status:"completed"}}case i.Approve:{const e=t.parse(l.params);return{resolved:this.requireSession(e.sessionId).approve(e.approvalId)}}case i.Reject:{const e=p.parse(l.params);return{resolved:this.requireSession(e.sessionId).reject(e.approvalId,e.reason)}}case i.Abort:{const e=n.parse(l.params);return{ok:!0,cancelled:this.requireSession(e.sessionId).cancel()}}case i.Close:{const e=a.parse(l.params),s=this.requireSession(e.sessionId);return await s.close(),this.sessions.delete(e.sessionId),{closed:!0}}case i.Messages:{const e=u.parse(l.params);return{messages:this.requireSession(e.sessionId).getMessages()}}case i.ToolExecutions:{const e=w.parse(l.params),o=this.requireSession(e.sessionId);if(e.includeRaw&&!await(this.authorizeRawToolEvidence?.({sessionId:e.sessionId,...void 0!==e.executionId?{executionId:e.executionId}:{}})))throw new Error("Raw Tool evidence access denied by RuntimeServer policy");if(void 0!==e.executionId){const i=o.getToolExecution(e.executionId,e.includeRaw);if(e.includeRaw&&void 0!==i&&!s(i))throw new Error("Raw Tool evidence is unavailable without a durable ledger projection");return{record:i}}const i=o.getToolExecutions({...void 0!==e.afterSequence?{afterSequence:e.afterSequence}:{},...void 0!==e.limit?{limit:e.limit}:{},...void 0!==e.toolCallId?{toolCallId:e.toolCallId}:{}},e.includeRaw);if(e.includeRaw&&i.some(e=>!s(e)))throw new Error("Raw Tool evidence is unavailable without a durable ledger projection");return{records:i}}case i.Capabilities:{const s=r.parse(l.params),o=this.requireSession(s.sessionId);return e(o.getCapabilityManifest(),o.getCapabilityTurnContext())}case i.Compact:{const e=c.parse(l.params),s=this.requireSession(e.sessionId);for await(const i of s.compact("manual"))this.connection.send({jsonrpc:"2.0",method:o,params:{sessionId:e.sessionId,event:i}});return{status:"completed"}}default:throw new Error(`Unknown method: ${l.method}`)}}}
1
+ import{jsonValueSchema as e}from"@roll-agent/protocol";import{createSafeCapabilitySnapshot as s}from"../engine/capability-manifest.js";import{isPersistedToolExecutionRecord as o}from"../tool-bridge/tool-execution-record.js";import{RuntimeServiceError as t}from"../service/runtime-service.js";import{RuntimeProtocolAdapter as r}from"./runtime-protocol-adapter.js";import{EVENT_NOTIFICATION as i,RpcMethod as n,abortParamsSchema as a,approveParamsSchema as c,capabilitiesParamsSchema as d,closeParamsSchema as l,compactParamsSchema as u,createParamsSchema as p,isRequest as h,messagesParamsSchema as m,rejectParamsSchema as v,resumeParamsSchema as w,sendParamsSchema as I,toolExecutionsParamsSchema as f}from"./protocol.js";function g(e){return e instanceof Error?e.message:String(e)}class MethodNotFoundError extends Error{}function S(e){return e instanceof Error&&"ZodError"===e.name&&"issues"in e&&Array.isArray(e.issues)}function R(s,o){if(s instanceof t){const o=e.safeParse(s.details);return{code:-32e3,message:s.message,data:{rollCode:s.rollCode,retryable:s.retryable,...o.success?{details:o.data}:{}}}}return S(s)?{code:-32602,message:"Invalid params",data:{rollCode:"INVALID_PARAMS",retryable:!1}}:s instanceof MethodNotFoundError?{code:-32601,message:s.message}:{code:-32603,message:o?"Internal error":g(s),data:{rollCode:"INTERNAL_ERROR",retryable:!1}}}export class RuntimeServer{engine;connection;authorizeRawToolEvidence;sessions=new Map;protocolAdapter;constructor(e,s,o={}){this.engine=e,this.connection=s,this.authorizeRawToolEvidence=o.authorizeRawToolEvidence,this.protocolAdapter=void 0===o.runtimeService?void 0:new r(o.runtimeService,s),this.connection.onMessage(e=>this.handleMessage(e))}async abortAll(){const e=[...this.sessions.values()];this.sessions.clear(),await Promise.all([...e.map(e=>e.close()),...void 0===this.protocolAdapter?[]:[this.protocolAdapter.close()]])}handleMessage(e){if(!h(e))return;const s=!0===this.protocolAdapter?.handles(e.method);this.dispatch(e).then(s=>{this.connection.send({jsonrpc:"2.0",id:e.id,result:s})}).catch(o=>{this.connection.send({jsonrpc:"2.0",id:e.id,error:R(o,s)})})}requireSession(e){const s=this.sessions.get(e);if(!s)throw new Error(`Session "${e}" 不存在`);return s}async dispatch(e){if(!0===this.protocolAdapter?.handles(e.method))return this.protocolAdapter.dispatch(e);switch(e.method){case n.Create:{const s=p.parse(e.params),o=await this.engine.createSession(s.title?{title:s.title}:{});return this.sessions.set(o.id,o),{sessionId:o.id}}case n.Resume:{const s=w.parse(e.params),o=await this.engine.resumeSession(s.threadId);return this.sessions.set(o.id,o),{sessionId:o.id}}case n.Send:{const s=I.parse(e.params),o=this.requireSession(s.sessionId);for await(const e of o.send(s.input))this.connection.send({jsonrpc:"2.0",method:i,params:{sessionId:s.sessionId,event:e}});return{status:"completed"}}case n.Approve:{const s=c.parse(e.params);return{resolved:this.requireSession(s.sessionId).approve(s.approvalId)}}case n.Reject:{const s=v.parse(e.params);return{resolved:this.requireSession(s.sessionId).reject(s.approvalId,s.reason)}}case n.Abort:{const s=a.parse(e.params);return{ok:!0,cancelled:this.requireSession(s.sessionId).cancel()}}case n.Close:{const s=l.parse(e.params),o=this.requireSession(s.sessionId);return await o.close(),this.sessions.delete(s.sessionId),{closed:!0}}case n.Messages:{const s=m.parse(e.params);return{messages:this.requireSession(s.sessionId).getMessages()}}case n.ToolExecutions:{const s=f.parse(e.params),t=this.requireSession(s.sessionId);if(s.includeRaw&&!await(this.authorizeRawToolEvidence?.({sessionId:s.sessionId,...void 0!==s.executionId?{executionId:s.executionId}:{}})))throw new Error("Raw Tool evidence access denied by RuntimeServer policy");if(void 0!==s.executionId){const e=t.getToolExecution(s.executionId,s.includeRaw);if(s.includeRaw&&void 0!==e&&!o(e))throw new Error("Raw Tool evidence is unavailable without a durable ledger projection");return{record:e}}const r=t.getToolExecutions({...void 0!==s.afterSequence?{afterSequence:s.afterSequence}:{},...void 0!==s.limit?{limit:s.limit}:{},...void 0!==s.toolCallId?{toolCallId:s.toolCallId}:{}},s.includeRaw);if(s.includeRaw&&r.some(e=>!o(e)))throw new Error("Raw Tool evidence is unavailable without a durable ledger projection");return{records:r}}case n.Capabilities:{const o=d.parse(e.params),t=this.requireSession(o.sessionId);return s(t.getCapabilityManifest(),t.getCapabilityTurnContext())}case n.Compact:{const s=u.parse(e.params),o=this.requireSession(s.sessionId);for await(const e of o.compact("manual"))this.connection.send({jsonrpc:"2.0",method:i,params:{sessionId:s.sessionId,event:e}});return{status:"completed"}}default:throw new MethodNotFoundError(`Method not found: ${e.method}`)}}}
@@ -1,3 +1,7 @@
1
1
  import type { Readable, Writable } from "node:stream";
2
2
  import type { JsonRpcConnection } from "../protocol.ts";
3
- export declare function createStdioConnection(input: Readable, output: Writable): JsonRpcConnection;
3
+ export declare const STDIO_MAX_FRAME_BYTES: number;
4
+ export interface StdioConnectionOptions {
5
+ readonly maxFrameBytes?: number;
6
+ }
7
+ export declare function createStdioConnection(input: Readable, output: Writable, options?: StdioConnectionOptions): JsonRpcConnection;
@@ -1 +1 @@
1
- import{createInterface as n}from"node:readline";function o(n){return"object"==typeof n&&null!==n&&"jsonrpc"in n&&"2.0"===n.jsonrpc}export function createStdioConnection(e,t){const r=[],s=[],c=n({input:e});return c.on("line",n=>{const e=n.trim();if(0===e.length)return;let t;try{t=JSON.parse(e)}catch{return}if(o(t))for(const n of r)n(t)}),c.on("close",()=>{for(const n of s)n()}),{send(n){t.write(`${JSON.stringify(n)}\n`)},onMessage(n){r.push(n)},onClose(n){s.push(n)},close(){c.close()}}}
1
+ import{createInterface as e}from"node:readline";import{once as r}from"node:events";export const STDIO_MAX_FRAME_BYTES=4194304;function n(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function o(e){return"string"==typeof e||"number"==typeof e&&Number.isFinite(e)}function t(e){return n(e)&&o(e.id)?e.id:null}function i(e){return!(!n(e)||"2.0"!==e.jsonrpc)&&("method"in e?"string"==typeof e.method&&0!==e.method.length&&(!("id"in e)||o(e.id)):"result"in e?o(e.id)&&!("error"in e):(null===e.id||o(e.id))&&n(e.error)&&"number"==typeof e.error.code&&Number.isInteger(e.error.code)&&"string"==typeof e.error.message)}export function createStdioConnection(n,o,s={}){const c=[],u=[],d=e({input:n}),l=s.maxFrameBytes??4194304;let f=Promise.resolve();const a=e=>{const n=`${JSON.stringify(e)}\n`;f=f.then(async()=>{o.write(n)||await r(o,"drain")}).catch(()=>{d.close()})};return d.on("line",e=>{const r=e.trim();if(0===r.length)return;if(Buffer.byteLength(e,"utf8")>l)return void a({jsonrpc:"2.0",id:null,error:{code:-32600,message:`Invalid Request: frame exceeds ${String(l)} byte limit`}});let n;try{n=JSON.parse(r)}catch{return void a({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}if(i(n))for(const e of c)e(n);else a({jsonrpc:"2.0",id:t(n),error:{code:-32600,message:"Invalid Request"}})}),d.on("close",()=>{for(const e of u)e()}),{send(e){a(e)},onMessage(e){c.push(e)},onClose(e){u.push(e)},close(){d.close()}}}
@@ -0,0 +1,89 @@
1
+ import { RUNTIME_METHODS, type InitializeParams, type InitializeResult, type RuntimeEventEnvelope, type RuntimeInstanceId, type RuntimeMethodParams, type RuntimeMethodResult, type RuntimeProtocolErrorData } from "@roll-agent/protocol";
2
+ import type { AgentSession } from "../engine/agent-session.ts";
3
+ import { ThreadStore } from "../store/thread-store.ts";
4
+ type RollErrorCode = RuntimeProtocolErrorData["rollCode"];
5
+ export type RuntimeServiceSession = Pick<AgentSession, "id" | "send" | "approve" | "reject" | "cancel" | "close" | "getCapabilityManifest" | "getCapabilityTurnContext">;
6
+ export interface RuntimeServiceEngine {
7
+ createSession(input?: {
8
+ readonly title?: string;
9
+ }): Promise<RuntimeServiceSession>;
10
+ resumeSession(threadId: string): Promise<RuntimeServiceSession>;
11
+ }
12
+ export interface RuntimeServiceOptions {
13
+ readonly serverName?: string;
14
+ readonly serverVersion?: string;
15
+ readonly runtimeVersion?: string;
16
+ readonly maxFrameBytes?: number;
17
+ readonly idempotencyCacheEntries?: number;
18
+ /**
19
+ * Optional host-controlled projection. Raw model reasoning is never sent to public clients.
20
+ * Supplying this enables the `reasoning-summary` capability.
21
+ */
22
+ readonly reasoningSummaryProjector?: (delta: string) => string | undefined;
23
+ }
24
+ export declare class RuntimeServiceError extends Error {
25
+ readonly rollCode: RollErrorCode;
26
+ readonly retryable: boolean;
27
+ readonly details: unknown;
28
+ constructor(rollCode: RollErrorCode, message: string, options?: {
29
+ readonly retryable?: boolean;
30
+ readonly details?: unknown;
31
+ });
32
+ }
33
+ type MutationRuntimeMethod = typeof RUNTIME_METHODS.threadCreate | typeof RUNTIME_METHODS.threadRename | typeof RUNTIME_METHODS.threadDelete | typeof RUNTIME_METHODS.threadDetach | typeof RUNTIME_METHODS.turnStart | typeof RUNTIME_METHODS.turnCancel | typeof RUNTIME_METHODS.approvalRespond;
34
+ export declare class MutationRequestCache {
35
+ private readonly maxEntries;
36
+ private readonly inFlight;
37
+ private readonly settled;
38
+ constructor(maxEntries: number);
39
+ run<TMethod extends MutationRuntimeMethod>(requestId: string, method: TMethod, params: RuntimeMethodParams<TMethod>, action: () => RuntimeMethodResult<TMethod> | Promise<RuntimeMethodResult<TMethod>>): Promise<RuntimeMethodResult<TMethod>>;
40
+ clear(): void;
41
+ private assertMatchingRequest;
42
+ private settle;
43
+ }
44
+ export declare class RuntimeService {
45
+ readonly runtimeInstanceId: RuntimeInstanceId;
46
+ private readonly engine;
47
+ private readonly store;
48
+ private readonly serverName;
49
+ private readonly serverVersion;
50
+ private readonly runtimeVersion;
51
+ private readonly maxFrameBytes;
52
+ private readonly idempotencyCacheEntries;
53
+ private readonly reasoningSummaryProjector;
54
+ private readonly sessions;
55
+ private readonly activeTurns;
56
+ private readonly activeTurnOwners;
57
+ private readonly settledTurnOwners;
58
+ private readonly pendingApprovals;
59
+ private readonly listeners;
60
+ private readonly mutationRequests;
61
+ private sequence;
62
+ private closing;
63
+ constructor(engine: RuntimeServiceEngine, store: ThreadStore, options?: RuntimeServiceOptions);
64
+ initialize(params: InitializeParams): InitializeResult;
65
+ onEvent(listener: (event: RuntimeEventEnvelope) => void): () => void;
66
+ listThreads(params: RuntimeMethodParams<"thread.list">): RuntimeMethodResult<"thread.list">;
67
+ createThread(params: RuntimeMethodParams<"thread.create">): Promise<RuntimeMethodResult<"thread.create">>;
68
+ openThread(params: RuntimeMethodParams<"thread.open">): Promise<RuntimeMethodResult<"thread.open">>;
69
+ snapshotThread(params: RuntimeMethodParams<"thread.snapshot">): RuntimeMethodResult<"thread.snapshot">;
70
+ renameThread(params: RuntimeMethodParams<"thread.rename">): Promise<RuntimeMethodResult<"thread.rename">>;
71
+ deleteThread(params: RuntimeMethodParams<"thread.delete">): Promise<RuntimeMethodResult<"thread.delete">>;
72
+ detachThread(params: RuntimeMethodParams<"thread.detach">): Promise<RuntimeMethodResult<"thread.detach">>;
73
+ threadCapabilities(params: RuntimeMethodParams<"thread.capabilities">): Promise<RuntimeMethodResult<"thread.capabilities">>;
74
+ startTurn(params: RuntimeMethodParams<"turn.start">): Promise<RuntimeMethodResult<"turn.start">>;
75
+ cancelTurn(params: RuntimeMethodParams<"turn.cancel">): Promise<RuntimeMethodResult<"turn.cancel">>;
76
+ respondApproval(params: RuntimeMethodParams<"approval.respond">): Promise<RuntimeMethodResult<"approval.respond">>;
77
+ getOperation(params: RuntimeMethodParams<"operation.get">): RuntimeMethodResult<"operation.get">;
78
+ close(): Promise<void>;
79
+ private assertOpen;
80
+ private requireThread;
81
+ private requireSession;
82
+ private emit;
83
+ private driveTurn;
84
+ private findTurnOwner;
85
+ private settleTurnOwner;
86
+ private projectSessionEvent;
87
+ private projectToolOutcome;
88
+ }
89
+ export {};
@@ -0,0 +1 @@
1
+ import{createHash as e,randomUUID as t}from"node:crypto";import{RUNTIME_ERROR_CODES as r,RUNTIME_FEATURES as s,RUNTIME_METHODS as n,RUNTIME_PROTOCOL_VERSION as i,approvalIdSchema as a,operationIdSchema as o,parseRuntimeMethodResult as d,runtimeInstanceIdSchema as u,streamIdSchema as h,threadIdSchema as l}from"@roll-agent/protocol";import{createSafeCapabilitySnapshot as c}from"../engine/capability-manifest.js";import{isSensitiveFieldName as m,redactSecretText as p,toRedactedToolExecutionRecordSummary as I}from"../tool-bridge/tool-execution-record.js";import{ThreadStore as v}from"../store/thread-store.js";const g=4194304,f=500,y=1e4,T=16e3,w=64,S=128,q=16,O=new Set(["_meta","authorization","cookie","password","providerOptions","raw","secret","token"]);export class RuntimeServiceError extends Error{rollCode;retryable;details;constructor(e,t,r={}){super(t),this.name="RuntimeServiceError",this.rollCode=e,this.retryable=r.retryable??!1,this.details=r.details}}function x(t){const s=JSON.stringify(t);if(void 0===s)throw new RuntimeServiceError(r.invalidParams,"无法为 mutation 请求生成稳定指纹");return e("sha256").update(s).digest("hex")}export class MutationRequestCache{maxEntries;inFlight=new Map;settled=new Map;constructor(e){if(!Number.isInteger(e)||e<1)throw new Error("idempotencyCacheEntries must be a positive integer");this.maxEntries=e}run(e,t,r,s){const n=x(r),i=this.inFlight.get(e);if(void 0!==i)return this.assertMatchingRequest(e,t,n,i),i.response.then(e=>d(t,e));const a=this.settled.get(e);if(void 0!==a)return this.assertMatchingRequest(e,t,n,a),this.settled.delete(e),this.settled.set(e,a),a.response.then(e=>d(t,e));const o=Promise.resolve().then(s),u={method:t,fingerprint:n,response:o};return this.inFlight.set(e,u),o.then(()=>{this.settle(e,u)},()=>{this.settle(e,u)}),o}clear(){this.inFlight.clear(),this.settled.clear()}assertMatchingRequest(e,t,s,n){if(n.method!==t||n.fingerprint!==s)throw new RuntimeServiceError(r.invalidParams,`requestId "${e}" 已用于不同请求`)}settle(e,t){if(this.inFlight.get(e)===t)for(this.inFlight.delete(e),this.settled.set(e,t);this.settled.size>this.maxEntries;){const e=this.settled.keys().next().value;if(void 0===e)return;this.settled.delete(e)}}}function E(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function R(e,t,r=0){if(void 0!==t&&(O.has(t.toLowerCase())||m(t)))return"[redacted]";if(r>=q)return"[nested value omitted]";if(null===e||"boolean"==typeof e)return e;if("string"==typeof e){const t=p(e);return t.length<=T?t:`${t.slice(0,T)}\n[value clipped]`}if("number"==typeof e)return Number.isFinite(e)?e:String(e);if(Array.isArray(e)){const t=e.slice(0,w).map(e=>R(e,void 0,r+1));return e.length>w&&t.push(`[${String(e.length-w)} items omitted]`),t}if(E(e)){const t={};for(const[s,n]of Object.entries(e).slice(0,S))void 0!==n&&(t[s]=R(n,s,r+1));return Object.keys(e).length>S&&(t._omitted=`${String(Object.keys(e).length-S)} keys omitted`),t}return void 0===e?null:String(e)}function A(e){return e instanceof Error?e.message:String(e)}function N(e){const t=e.content;return"string"==typeof t?t:Array.isArray(t)?t.flatMap(e=>E(e)&&"text"===e.type&&"string"==typeof e.text?[e.text]:[]).join(""):""}function C(e){return l.parse(e)}function b(e,t){return{id:C(t.id),...void 0!==t.title?{title:t.title}:{},...void 0!==t.model?{model:t.model}:{},createdAt:t.createdAt,updatedAt:t.updatedAt,messageCount:e.countTranscriptMessages(t.id)}}function j(e){if("user"!==e.message.role&&"assistant"!==e.message.role)return;const t=p(N(e.message));return{sequence:e.sequence,role:e.message.role,createdAt:e.createdAt,parts:t.length>0?[{type:"text",text:t}]:[]}}function M(e){const t=I(e);return{id:o.parse(t.id),sequence:e.sequence,toolCallId:t.toolCallId,agentName:t.agentName,toolName:t.toolName,createdAt:t.createdAt,outcome:t.outcome,display:R(t.display,void 0)}}function F(e,t){return{id:a.parse(t.approvalId),turnId:e,agentName:t.agentName,toolName:t.toolName,preview:R(t.input,void 0),...void 0!==t.reason?{reason:p(t.reason)}:{}}}export class RuntimeService{runtimeInstanceId;engine;store;serverName;serverVersion;runtimeVersion;maxFrameBytes;idempotencyCacheEntries;reasoningSummaryProjector;sessions=new Map;activeTurns=new Map;activeTurnOwners=new Map;settledTurnOwners=new Map;pendingApprovals=new Map;listeners=new Set;mutationRequests;sequence=0;closing=!1;constructor(e,r,s={}){this.engine=e,this.store=r,this.serverName=s.serverName??"roll-runtime",this.serverVersion=s.serverVersion??"1.0",this.runtimeVersion=s.runtimeVersion??"development",this.maxFrameBytes=s.maxFrameBytes??g,this.idempotencyCacheEntries=s.idempotencyCacheEntries??y,this.mutationRequests=new MutationRequestCache(this.idempotencyCacheEntries),this.reasoningSummaryProjector=s.reasoningSummaryProjector,this.runtimeInstanceId=u.parse(t())}initialize(e){if(!e.protocolVersions.includes(i))throw new RuntimeServiceError(r.protocolVersionUnsupported,`不支持客户端协议版本:${e.protocolVersions.join(", ")}`,{details:{supportedVersions:[i]}});return{protocolVersion:i,runtimeInstanceId:this.runtimeInstanceId,server:{name:this.serverName,version:this.serverVersion,runtimeVersion:this.runtimeVersion},features:s.filter(e=>"reasoning-summary"!==e||void 0!==this.reasoningSummaryProjector),limits:{maxFrameBytes:this.maxFrameBytes,maxPageSize:f,eventReplay:!1,idempotencyCacheEntries:this.idempotencyCacheEntries}}}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}listThreads(e){this.assertOpen();const t=void 0===e.cursor?0:Number(e.cursor);if(!Number.isSafeInteger(t)||t<0)throw new RuntimeServiceError(r.invalidParams,"thread.list cursor 超出安全整数范围");const s=this.store.listThreads(),n=s.slice(t,t+e.limit).map(e=>b(this.store,e)),i=t+n.length;return{items:n,nextCursor:i<s.length?String(i):null}}async createThread(e){return this.mutationRequests.run(e.requestId,n.threadCreate,e,async()=>{this.assertOpen();const t=await this.engine.createSession(void 0!==e.title?{title:e.title}:{});return this.sessions.set(t.id,t),{thread:b(this.store,this.requireThread(t.id))}})}async openThread(e){return await this.requireSession(e.threadId),this.snapshotThread({threadId:e.threadId,limit:100})}snapshotThread(e){this.assertOpen();const t=this.requireThread(e.threadId),r=this.store.listRecentTranscriptMessages(e.threadId,{...void 0!==e.messageBeforeSequence?{beforeSequence:e.messageBeforeSequence}:{},limit:e.limit}),s=this.store.listRecentToolExecutions(e.threadId,{...void 0!==e.operationBeforeSequence?{beforeSequence:e.operationBeforeSequence}:{},limit:e.limit}),n=this.activeTurns.get(e.threadId),i=void 0===n?void 0:{id:n.turnId,status:n.status,startedAt:n.startedAt};return{thread:b(this.store,t),messages:{items:r.entries.flatMap(e=>{const t=j(e);return void 0===t?[]:[t]}),nextBeforeSequence:r.nextBeforeSequence??null},operations:{items:s.entries.map(M),nextBeforeSequence:s.nextBeforeSequence??null},...void 0!==i?{activeTurn:i}:{},pendingApprovals:[...this.pendingApprovals.values()].filter(t=>t.threadId===e.threadId).map(e=>e.approval),transcriptCompleteness:this.store.getTranscriptCompleteness(e.threadId)}}async renameThread(e){return this.mutationRequests.run(e.requestId,n.threadRename,e,()=>(this.assertOpen(),this.requireThread(e.threadId),this.store.updateTitle(e.threadId,e.title),{thread:b(this.store,this.requireThread(e.threadId))}))}async deleteThread(e){return this.mutationRequests.run(e.requestId,n.threadDelete,e,async()=>{if(this.assertOpen(),this.requireThread(e.threadId),this.activeTurns.has(e.threadId))throw new RuntimeServiceError(r.threadBusy,`Thread "${e.threadId}" 仍有活动 Turn`,{retryable:!0});const t=this.sessions.get(e.threadId);return void 0!==t&&(await t.close(),this.sessions.delete(e.threadId)),this.store.deleteThread(e.threadId),{deleted:!0}})}async detachThread(e){return this.mutationRequests.run(e.requestId,n.threadDetach,e,async()=>{if(this.assertOpen(),this.requireThread(e.threadId),this.activeTurns.has(e.threadId))return{detached:!1};const t=this.sessions.get(e.threadId);return void 0===t?{detached:!1}:(await t.close(),this.sessions.delete(e.threadId),{detached:!0})})}async threadCapabilities(e){const t=await this.requireSession(e.threadId);return{manifest:R(c(t.getCapabilityManifest(),t.getCapabilityTurnContext()),void 0)}}async startTurn(e){return this.mutationRequests.run(e.requestId,n.turnStart,e,async()=>{this.assertOpen();const t=this.findTurnOwner(e.turnId,e.threadId);if(void 0!==t){if(t===e.threadId)return{accepted:!0,turnId:e.turnId};throw new RuntimeServiceError(r.turnAlreadyActive,`Turn "${e.turnId}" 已属于另一个 Thread`)}if(this.activeTurns.has(e.threadId))throw new RuntimeServiceError(r.turnAlreadyActive,`Thread "${e.threadId}" 已有活动 Turn`,{retryable:!0});const s=await this.requireSession(e.threadId),n=this.findTurnOwner(e.turnId,e.threadId);if(void 0!==n){if(n===e.threadId)return{accepted:!0,turnId:e.turnId};throw new RuntimeServiceError(r.turnAlreadyActive,`Turn "${e.turnId}" 已属于另一个 Thread`)}if(this.activeTurns.has(e.threadId))throw new RuntimeServiceError(r.turnAlreadyActive,`Thread "${e.threadId}" 已有活动 Turn`,{retryable:!0});const i={threadId:e.threadId,turnId:e.turnId,session:s,startedAt:(new Date).toISOString(),status:"running"};return this.activeTurns.set(e.threadId,i),this.activeTurnOwners.set(e.turnId,e.threadId),this.emit(e.threadId,e.turnId,{type:"turn.started"}),this.driveTurn(i,e.input.text).catch(()=>{}),{accepted:!0,turnId:e.turnId}})}async cancelTurn(e){return this.mutationRequests.run(e.requestId,n.turnCancel,e,()=>{this.assertOpen();const t=this.activeTurns.get(e.threadId);if(void 0===t||t.turnId!==e.turnId)throw new RuntimeServiceError(r.turnNotFound,`Turn "${e.turnId}" 不存在或已结束`);return t.status="cancelling",{cancelling:t.session.cancel()}})}async respondApproval(e){return this.mutationRequests.run(e.requestId,n.approvalRespond,e,()=>{this.assertOpen();const t=this.pendingApprovals.get(e.approvalId);if(void 0===t||t.threadId!==e.threadId||t.approval.turnId!==e.turnId)throw new RuntimeServiceError(r.approvalNotFound,`Approval "${e.approvalId}" 不存在或已失效`);if(!("approve"===e.decision?t.session.approve(e.approvalId):t.session.reject(e.approvalId,e.reason)))throw new RuntimeServiceError(r.approvalNotFound,`Approval "${e.approvalId}" 已失效`);return this.pendingApprovals.delete(e.approvalId),{resolved:!0}})}getOperation(e){this.assertOpen(),this.requireThread(e.threadId);const t=this.store.getToolExecution(e.threadId,e.operationId);return{operation:void 0===t?null:M(t)}}async close(){if(this.closing)return;this.closing=!0;for(const e of this.activeTurns.values())e.session.cancel();const e=[...this.sessions.values()];this.sessions.clear(),this.activeTurns.clear(),this.activeTurnOwners.clear(),this.settledTurnOwners.clear(),this.pendingApprovals.clear(),await Promise.allSettled(e.map(e=>e.close())),this.mutationRequests.clear()}assertOpen(){if(this.closing)throw new RuntimeServiceError(r.runtimeClosing,"Runtime 正在关闭",{retryable:!0})}requireThread(e){const t=this.store.getThread(e);if(void 0===t)throw new RuntimeServiceError(r.threadNotFound,`Thread "${e}" 不存在`);return t}async requireSession(e){this.assertOpen(),this.requireThread(e);const t=this.sessions.get(e);if(void 0!==t)return t;const r=await this.engine.resumeSession(e);return this.sessions.set(e,r),r}emit(e,t,r){const s={protocolVersion:i,runtimeInstanceId:this.runtimeInstanceId,sequence:this.sequence,timestamp:(new Date).toISOString(),threadId:e,...void 0!==t?{turnId:t}:{},event:r};this.sequence+=1;for(const e of this.listeners)e(s)}async driveTurn(e,t){const r={streamId:void 0,text:"",terminalEmitted:!1};try{for await(const s of e.session.send(t))this.projectSessionEvent(e,r,s);r.terminalEmitted||this.emit(e.threadId,e.turnId,{type:"turn.completed"})}catch(t){r.terminalEmitted||this.emit(e.threadId,e.turnId,{type:"turn.failed",stage:"execute",message:p(A(t))})}finally{this.activeTurns.get(e.threadId)===e&&this.activeTurns.delete(e.threadId),this.settleTurnOwner(e);for(const[t,r]of this.pendingApprovals)r.approval.turnId===e.turnId&&this.pendingApprovals.delete(t)}}findTurnOwner(e,t){const r=this.activeTurnOwners.get(e);if(void 0!==r)return r;const s=this.settledTurnOwners.get(e);return s===t&&(this.settledTurnOwners.delete(e),this.settledTurnOwners.set(e,s)),s}settleTurnOwner(e){if(this.activeTurnOwners.get(e.turnId)===e.threadId&&(this.activeTurnOwners.delete(e.turnId),!this.closing))for(this.settledTurnOwners.set(e.turnId,e.threadId);this.settledTurnOwners.size>this.idempotencyCacheEntries;){const e=this.settledTurnOwners.keys().next().value;if(void 0===e)return;this.settledTurnOwners.delete(e)}}projectSessionEvent(e,r,s){switch(s.type){case"message-start":{const s=h.parse(t());return r.streamId=s,r.text="",void this.emit(e.threadId,e.turnId,{type:"message.started",streamId:s})}case"text-delta":{const n=r.streamId??h.parse(t());return void 0===r.streamId&&(r.streamId=n,this.emit(e.threadId,e.turnId,{type:"message.started",streamId:n})),r.text+=s.delta,void this.emit(e.threadId,e.turnId,{type:"message.delta",streamId:n,delta:s.delta})}case"message-finish":{const n=r.streamId??h.parse(t());return this.emit(e.threadId,e.turnId,{type:"message.completed",streamId:n,text:p(s.text||r.text)}),this.emit(e.threadId,e.turnId,{type:"turn.completed"}),void(r.terminalEmitted=!0)}case"reasoning-delta":{const t=this.reasoningSummaryProjector?.(s.delta);return void(void 0!==t&&t.length>0&&this.emit(e.threadId,e.turnId,{type:"reasoning.summary.delta",reasoningId:s.reasoningId,delta:p(t)}))}case"tool-call":return void this.emit(e.threadId,e.turnId,{type:"tool.started",toolCallId:s.toolCallId,agentName:s.agentName,toolName:s.toolName,input:R(s.input,void 0)});case"tool-output-delta":return void this.emit(e.threadId,e.turnId,{type:"tool.output",toolCallId:s.toolCallId,agentName:s.agentName,toolName:s.toolName,stream:s.stream,delta:p(s.delta)});case"tool-result":return void this.emit(e.threadId,e.turnId,{type:"tool.completed",toolCallId:s.toolCallId,agentName:s.agentName,toolName:s.toolName,...void 0!==s.executionId?{operationId:o.parse(s.executionId)}:{},...void 0!==s.outcome?{outcome:this.projectToolOutcome(s.outcome)}:{},display:R(s.display,void 0)});case"confirmation-required":{const t=F(e.turnId,s);return this.pendingApprovals.set(t.id,{threadId:e.threadId,session:e.session,approval:t}),void this.emit(e.threadId,e.turnId,{type:"approval.required",approval:t})}case"turn-cancelled":this.emit(e.threadId,e.turnId,{type:"turn.cancelled",reason:s.reason,message:p(s.message)}),r.terminalEmitted=!0;break;case"error":this.emit(e.threadId,e.turnId,{type:"turn.failed",stage:s.stage,message:p(s.message)}),r.terminalEmitted=!0}}projectToolOutcome(e){return{kind:e.kind,..."reason"in e&&void 0!==e.reason?{reason:p(e.reason)}:{}}}}
@@ -38,6 +38,18 @@ export interface ListTranscriptMessagesOptions {
38
38
  readonly throughSequence?: number;
39
39
  readonly limit?: number;
40
40
  }
41
+ export interface ListRecentEntriesOptions {
42
+ readonly beforeSequence?: number;
43
+ readonly limit?: number;
44
+ }
45
+ export interface RecentTranscriptMessagePage {
46
+ readonly entries: readonly ArchivedTranscriptMessage[];
47
+ readonly nextBeforeSequence: number | undefined;
48
+ }
49
+ export interface RecentToolExecutionPage {
50
+ readonly entries: readonly SequencedToolExecutionRecord[];
51
+ readonly nextBeforeSequence: number | undefined;
52
+ }
41
53
  export interface CompactionEvidenceWatermarks {
42
54
  /** Highest append-only transcript sequence that was visible while building the draft. */
43
55
  readonly transcriptMessagesThroughSequence: number;
@@ -101,6 +113,7 @@ export declare class ThreadStore {
101
113
  getThread(id: string): ThreadRecord | undefined;
102
114
  listThreads(): ThreadRecord[];
103
115
  countMessages(threadId: string): number;
116
+ countTranscriptMessages(threadId: string): number;
104
117
  updateTitle(threadId: string, title: string): void;
105
118
  deleteThread(threadId: string): void;
106
119
  appendMessages(threadId: string, messages: readonly ModelMessage[]): void;
@@ -110,9 +123,11 @@ export declare class ThreadStore {
110
123
  appendToolExecution(threadId: string, record: ToolExecutionRecord): number;
111
124
  private enforceToolExecutionRetentionInTransaction;
112
125
  listToolExecutions(threadId: string, options?: ListToolExecutionsOptions): SequencedToolExecutionRecord[];
126
+ listRecentToolExecutions(threadId: string, options?: ListRecentEntriesOptions): RecentToolExecutionPage;
113
127
  getToolExecution(threadId: string, executionId: string): SequencedToolExecutionRecord | undefined;
114
128
  getTranscriptCompleteness(threadId: string): TranscriptCompleteness;
115
129
  listTranscriptMessages(threadId: string, options?: ListTranscriptMessagesOptions): ArchivedTranscriptMessage[];
130
+ listRecentTranscriptMessages(threadId: string, options?: ListRecentEntriesOptions): RecentTranscriptMessagePage;
116
131
  getLatestCheckpoint(threadId: string): CompactionCheckpoint | undefined;
117
132
  getLatestSummaryCheckpoint(threadId: string): CompactionCheckpoint | undefined;
118
133
  getCheckpoint(threadId: string, checkpointId: string): CompactionCheckpoint | undefined;
@@ -123,5 +138,6 @@ export declare class ThreadStore {
123
138
  private maxToolExecutionSequence;
124
139
  private withCurrentTranscriptCompleteness;
125
140
  private validateTranscriptRange;
141
+ private validateRecentPage;
126
142
  close(): void;
127
143
  }
@@ -1 +1 @@
1
- import{chmodSync as e,existsSync as t,mkdirSync as n}from"node:fs";import{homedir as r}from"node:os";import{resolve as s}from"node:path";import{randomUUID as o}from"node:crypto";import{DatabaseSync as a}from"node:sqlite";import{modelMessageSchema as i}from"ai";import{parsePersistedToolExecutionRecord as c,prepareToolExecutionRecordForPersistence as d,redactSecretText as E}from"../tool-bridge/tool-execution-record.js";import{COMPACTION_CHECKPOINT_VERSION as h,COMPACTION_TRANSCRIPT_COMPLETENESS as T,TRANSCRIPT_MESSAGE_PROVENANCES as p,UnsupportedCompactionCheckpointVersionError as u,archivedTranscriptMessageSchema as _,createCompactionCheckpoint as l,createCompactionCheckpointDraft as m,parseCompactionCheckpoint as g}from"../engine/compaction-checkpoint.js";import{legacyCompactionTranscriptFragmentsSchema as S}from"../engine/compaction-semantic-state.js";import{createLegacyCompactionTranscriptMessage as N}from"../engine/compactor.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as R,repairActiveToolProtocol as O}from"../engine/tool-protocol-repair.js";import{sanitizePersistedExplicitSkillCheckpoint as I}from"../engine/explicit-skill-context.js";const L=4,C=100,x=500,A=50,f=500,b=100,q=15e3;export const TOOL_EXECUTION_RETENTION_POLICY={maxBytesPerThread:16777216,maxRecordsPerThread:2e3,maxAgeMs:2592e6};export const TRANSCRIPT_ENTRY_KINDS=["message","tool_execution"];export function expandTilde(e){return e.startsWith("~/")?s(r(),e.slice(2)):e}export function defaultThreadsDir(){return s(r(),".roll-agent","threads")}function M(e){return e.prepare("PRAGMA foreign_key_list(messages)").all().some(e=>"threads"===e.table&&"thread_id"===e.from&&"id"===e.to&&"CASCADE"===e.on_delete.toUpperCase())}function w(e,t){return"valid"===e.status?e:"fallback"===e.status?{status:"fallback",reason:e.reason,...void 0!==t?{lastValidCheckpointId:t.id}:{}}:{status:"skipped",...void 0!==t?{lastValidCheckpointId:t.id}:{}}}function v(e){if(Number.isInteger(e.schema_version)&&e.schema_version>h)throw new u(e.schema_version);if(!Number.isInteger(e.schema_version))throw new Error("Invalid persisted compaction checkpoint schema version");const t=g(JSON.parse(e.checkpoint_json));if(t.version!==e.schema_version)throw new Error(`Compaction checkpoint schema version mismatch: row v${String(e.schema_version)}, payload v${String(t.version)}`);return t}function k(e){return{id:e.id,title:e.title??void 0,model:e.model??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}export class ThreadStore{db;constructor(r=defaultThreadsDir()){const o=expandTilde(r);t(o)||n(o,{recursive:!0,mode:448}),"win32"!==process.platform&&e(o,448);const i=s(o,"threads.db");if(this.db=new a(i),"win32"!==process.platform)try{e(i,384)}catch(e){throw this.db.close(),e}this.init()}init(){this.db.exec(`PRAGMA busy_timeout = ${String(q)};\n PRAGMA foreign_keys = ON;\n PRAGMA secure_delete = ON;`);const e=this.db.prepare("PRAGMA user_version").get();if(e.user_version>4)throw new Error(`ThreadStore schema v${String(e.user_version)} 高于当前支持的 v${String(4)}`);this.db.exec("BEGIN IMMEDIATE");try{this.db.exec("CREATE TABLE IF NOT EXISTS threads (\n id TEXT PRIMARY KEY,\n title TEXT,\n model TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS messages (\n thread_id TEXT NOT NULL,\n idx INTEGER NOT NULL,\n role TEXT NOT NULL,\n content_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (thread_id, idx),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );"),M(this.db)||this.db.exec("CREATE TABLE messages_with_thread_fk (\n thread_id TEXT NOT NULL,\n idx INTEGER NOT NULL,\n role TEXT NOT NULL,\n content_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (thread_id, idx),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n INSERT INTO messages_with_thread_fk\n (thread_id, idx, role, content_json, created_at)\n SELECT messages.thread_id, messages.idx, messages.role,\n messages.content_json, messages.created_at\n FROM messages\n INNER JOIN threads ON threads.id = messages.thread_id;\n DROP TABLE messages;\n ALTER TABLE messages_with_thread_fk RENAME TO messages;"),this.db.exec("CREATE TABLE IF NOT EXISTS tool_executions (\n thread_id TEXT NOT NULL,\n sequence INTEGER NOT NULL,\n id TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n agent_name TEXT NOT NULL,\n tool_name TEXT NOT NULL,\n record_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (thread_id, id),\n UNIQUE (thread_id, sequence),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n CREATE INDEX IF NOT EXISTS idx_tool_executions_thread_call\n ON tool_executions(thread_id, tool_call_id, sequence);\n CREATE TABLE IF NOT EXISTS thread_tool_execution_state (\n thread_id TEXT PRIMARY KEY,\n next_sequence INTEGER NOT NULL CHECK (next_sequence >= 0),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n CREATE TABLE IF NOT EXISTS transcript_messages (\n thread_id TEXT NOT NULL,\n sequence INTEGER NOT NULL,\n role TEXT NOT NULL,\n message_json TEXT NOT NULL,\n provenance TEXT NOT NULL CHECK (provenance IN ('native', 'legacy_snapshot')),\n created_at TEXT NOT NULL,\n PRIMARY KEY (thread_id, sequence),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n CREATE TABLE IF NOT EXISTS thread_transcript_state (\n thread_id TEXT PRIMARY KEY,\n completeness TEXT NOT NULL CHECK (completeness IN ('complete', 'legacy_snapshot')),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n CREATE TABLE IF NOT EXISTS compaction_checkpoints (\n id TEXT PRIMARY KEY,\n thread_id TEXT NOT NULL,\n generation INTEGER NOT NULL,\n schema_version INTEGER NOT NULL,\n message_from_sequence INTEGER NOT NULL,\n message_through_sequence INTEGER NOT NULL,\n tool_from_sequence INTEGER NOT NULL,\n tool_through_sequence INTEGER NOT NULL,\n checkpoint_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n UNIQUE (thread_id, generation),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n CREATE INDEX IF NOT EXISTS idx_compaction_checkpoints_thread_generation\n ON compaction_checkpoints(thread_id, generation DESC);"),this.db.exec("INSERT OR IGNORE INTO thread_tool_execution_state (thread_id, next_sequence)\n SELECT id, 0 FROM threads;\n UPDATE thread_tool_execution_state\n SET next_sequence = MAX(\n next_sequence,\n COALESCE((\n SELECT MAX(tool_executions.sequence) + 1\n FROM tool_executions\n WHERE tool_executions.thread_id = thread_tool_execution_state.thread_id\n ), 0)\n );"),e.user_version<3&&this.db.exec("INSERT OR IGNORE INTO thread_transcript_state (thread_id, completeness)\n SELECT id, 'legacy_snapshot' FROM threads;\n INSERT OR IGNORE INTO transcript_messages\n (thread_id, sequence, role, message_json, provenance, created_at)\n SELECT thread_id, idx, role, content_json, 'legacy_snapshot', created_at\n FROM messages;"),e.user_version<4&&(this.migrateToolExecutionPersistenceInTransaction(),this.migrateExplicitSkillCheckpointPersistenceInTransaction()),this.enforceAllToolExecutionRetentionInTransaction((new Date).toISOString()),this.db.exec(`PRAGMA user_version = ${String(4)};`),this.db.exec("COMMIT")}catch(e){throw this.db.exec("ROLLBACK"),e}}migrateToolExecutionPersistenceInTransaction(){const e=this.db.prepare("SELECT rowid AS storage_rowid, record_json\n FROM tool_executions\n WHERE rowid > ?\n ORDER BY rowid ASC\n LIMIT 100"),t=this.db.prepare("UPDATE tool_executions\n SET tool_call_id = ?, agent_name = ?, tool_name = ?, record_json = ?, created_at = ?\n WHERE rowid = ?");let n=0;for(;;){const r=e.all(n);if(0===r.length)break;for(const e of r){const r=c(JSON.parse(e.record_json));t.run(r.toolCallId,r.agentName,r.toolName,JSON.stringify(r),r.createdAt,e.storage_rowid),n=e.storage_rowid}}}enforceAllToolExecutionRetentionInTransaction(e){const t=this.db.prepare("SELECT DISTINCT thread_id AS id FROM tool_executions").all();for(const{id:n}of t)this.enforceToolExecutionRetentionInTransaction(n,e)}migrateExplicitSkillCheckpointPersistenceInTransaction(){const e=[{table:"messages",column:"content_json"},{table:"transcript_messages",column:"message_json"}];for(const t of e){const e=this.db.prepare(`SELECT rowid AS storage_rowid, ${t.column} AS message_json\n FROM ${t.table}\n WHERE ${t.column} LIKE '%"modelUserContent"%'`).all(),n=this.db.prepare(`UPDATE ${t.table} SET ${t.column} = ? WHERE rowid = ?`);for(const t of e){const e=i.parse(JSON.parse(t.message_json)),r=I(e);n.run(JSON.stringify(r),t.storage_rowid)}}}createThread(e={}){const t=e.id??o(),n=(new Date).toISOString();this.db.exec("BEGIN IMMEDIATE");try{return this.db.prepare("INSERT INTO threads (id, title, model, created_at, updated_at) VALUES (?, ?, ?, ?, ?)").run(t,e.title??null,e.model??null,n,n),this.db.prepare("INSERT INTO thread_transcript_state (thread_id, completeness) VALUES (?, ?)").run(t,T[0]),this.db.prepare("INSERT INTO thread_tool_execution_state (thread_id, next_sequence) VALUES (?, 0)").run(t),this.db.exec("COMMIT"),t}catch(e){throw this.db.exec("ROLLBACK"),e}}hasThread(e){return void 0!==this.db.prepare("SELECT 1 FROM threads WHERE id = ?").get(e)}getThread(e){const t=this.db.prepare("SELECT * FROM threads WHERE id = ?").get(e);return t?k(t):void 0}listThreads(){return this.db.prepare("SELECT * FROM threads ORDER BY updated_at DESC, rowid DESC").all().map(k)}countMessages(e){return this.db.prepare("SELECT COUNT(*) AS n FROM messages WHERE thread_id = ?").get(e).n}updateTitle(e,t){this.db.prepare("UPDATE threads SET title = ? WHERE id = ?").run(t,e)}deleteThread(e){this.db.prepare("DELETE FROM threads WHERE id = ?").run(e)}appendMessages(e,t){if(0===t.length)return;if(!this.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const n=t.map(e=>I(i.parse(e))),r=(new Date).toISOString(),s=this.db.prepare("INSERT INTO messages (thread_id, idx, role, content_json, created_at) VALUES (?, ?, ?, ?, ?)"),o=this.db.prepare("INSERT INTO transcript_messages\n (thread_id, sequence, role, message_json, provenance, created_at)\n VALUES (?, ?, ?, ?, ?, ?)");this.db.exec("BEGIN IMMEDIATE");try{const t=this.db.prepare("SELECT COALESCE(MAX(idx), -1) AS maxIdx FROM messages WHERE thread_id = ?").get(e),a=this.db.prepare("SELECT COALESCE(MAX(sequence), -1) AS maxSequence FROM transcript_messages WHERE thread_id = ?").get(e);let i=t.maxIdx+1,c=a.maxSequence+1;for(const t of n){const n=JSON.stringify(t);s.run(e,i,t.role,n,r),o.run(e,c,t.role,n,p[0],r),i+=1,c+=1}this.db.prepare("UPDATE threads SET updated_at = ? WHERE id = ?").run(r,e),this.db.exec("COMMIT")}catch(e){throw this.db.exec("ROLLBACK"),e}}replaceMessages(e,t){if(!this.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const n=t.map(e=>i.parse(e)),r=(new Date).toISOString();this.db.exec("BEGIN IMMEDIATE");try{this.replaceMessagesInTransaction(e,n,r),this.db.exec("COMMIT")}catch(e){throw this.db.exec("ROLLBACK"),e}}getMessages(e){return this.db.prepare("SELECT content_json FROM messages WHERE thread_id = ? ORDER BY idx ASC").all(e).map(e=>i.parse(JSON.parse(e.content_json)))}replaceMessagesInTransaction(e,t,n){const r=this.db.prepare("INSERT INTO messages (thread_id, idx, role, content_json, created_at) VALUES (?, ?, ?, ?, ?)");this.db.prepare("DELETE FROM messages WHERE thread_id = ?").run(e),t.forEach((t,s)=>{const o=I(t);r.run(e,s,o.role,JSON.stringify(o),n)}),this.db.prepare("UPDATE threads SET updated_at = ? WHERE id = ?").run(n,e)}appendToolExecution(e,t){if(!this.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const n=d(t),r=JSON.stringify(n),s=(new Date).toISOString();this.db.exec("BEGIN IMMEDIATE");try{const t=this.db.prepare("SELECT next_sequence FROM thread_tool_execution_state WHERE thread_id = ?").get(e);if(void 0===t)throw new Error(`Thread "${e}" 缺少 Tool execution sequence state`);const o=t.next_sequence;return this.db.prepare("INSERT INTO tool_executions\n (thread_id, sequence, id, tool_call_id, agent_name, tool_name, record_json, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(e,o,n.id,n.toolCallId,n.agentName,n.toolName,r,n.createdAt),this.db.prepare("UPDATE thread_tool_execution_state SET next_sequence = ? WHERE thread_id = ?").run(o+1,e),this.enforceToolExecutionRetentionInTransaction(e,s),this.db.prepare("UPDATE threads SET updated_at = ? WHERE id = ?").run(s,e),this.db.exec("COMMIT"),o}catch(e){throw this.db.exec("ROLLBACK"),e}}enforceToolExecutionRetentionInTransaction(e,t){const n=new Date(Date.parse(t)-TOOL_EXECUTION_RETENTION_POLICY.maxAgeMs).toISOString();let r=!1;const s=this.db.prepare("DELETE FROM tool_executions\n WHERE thread_id = ?\n AND created_at < ?").run(e,n);r=Number(s.changes)>0;const o=this.db.prepare("SELECT sequence\n FROM (\n SELECT sequence,\n ROW_NUMBER() OVER (ORDER BY sequence DESC) AS retained_rank,\n SUM(length(CAST(record_json AS BLOB))) OVER (\n ORDER BY sequence DESC\n ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\n ) AS retained_bytes\n FROM tool_executions\n WHERE thread_id = ?\n )\n WHERE retained_rank > ? OR retained_bytes > ?").all(e,TOOL_EXECUTION_RETENTION_POLICY.maxRecordsPerThread,TOOL_EXECUTION_RETENTION_POLICY.maxBytesPerThread);if(o.length>0){const t=this.db.prepare("DELETE FROM tool_executions WHERE thread_id = ? AND sequence = ?");for(const n of o)t.run(e,n.sequence);r=!0}r&&this.db.prepare("INSERT INTO thread_transcript_state (thread_id, completeness)\n VALUES (?, 'legacy_snapshot')\n ON CONFLICT(thread_id) DO UPDATE SET completeness = 'legacy_snapshot'").run(e)}listToolExecutions(e,t={}){const n=t.afterSequence??-1,r=t.throughSequence??Number.MAX_SAFE_INTEGER,s=t.limit??C;if(!Number.isInteger(n)||n<-1)throw new Error("afterSequence 必须是大于等于 -1 的整数");if(!Number.isInteger(s)||s<1||s>x)throw new Error(`limit 必须是 1-${String(x)} 之间的整数`);if(!Number.isInteger(r)||r<-1)throw new Error("throughSequence 必须是大于等于 -1 的整数");if(r<=n)return[];return this.db.prepare("SELECT sequence, record_json\n FROM tool_executions\n WHERE thread_id = ?\n AND sequence > ?\n AND sequence <= ?\n AND (? IS NULL OR tool_call_id = ?)\n ORDER BY sequence ASC\n LIMIT ?").all(e,n,r,t.toolCallId??null,t.toolCallId??null,s).map(e=>({...c(JSON.parse(e.record_json)),sequence:e.sequence}))}getToolExecution(e,t){const n=this.db.prepare("SELECT sequence, record_json FROM tool_executions WHERE thread_id = ? AND id = ?").get(e,t);if(n)return{...c(JSON.parse(n.record_json)),sequence:n.sequence}}getTranscriptCompleteness(e){const t=this.db.prepare("SELECT completeness FROM thread_transcript_state WHERE thread_id = ?").get(e);return t?.completeness===T[0]?T[0]:T[1]}listTranscriptMessages(e,t={}){const n=t.afterSequence??-1,r=t.throughSequence??Number.MAX_SAFE_INTEGER,s=t.limit??A;if(this.validateTranscriptRange(n,r,s,f),r<=n)return[];return this.db.prepare("SELECT sequence, provenance, created_at, message_json\n FROM transcript_messages\n WHERE thread_id = ?\n AND sequence > ?\n AND sequence <= ?\n ORDER BY sequence ASC\n LIMIT ?").all(e,n,r,s).map(e=>_.parse({sequence:e.sequence,provenance:e.provenance,createdAt:e.created_at,message:JSON.parse(e.message_json)}))}getLatestCheckpoint(e){const t=this.db.prepare("SELECT schema_version, checkpoint_json\n FROM compaction_checkpoints\n WHERE thread_id = ?\n ORDER BY generation DESC").all(e);for(const n of t)try{return this.withCurrentTranscriptCompleteness(e,v(n))}catch(e){if(e instanceof u)throw e}}getLatestSummaryCheckpoint(e){const t=this.db.prepare("SELECT schema_version, checkpoint_json\n FROM compaction_checkpoints\n WHERE thread_id = ?\n ORDER BY generation DESC").all(e);for(const n of t)try{const t=v(n);if("valid"===t.summary.status)return this.withCurrentTranscriptCompleteness(e,t)}catch(e){if(e instanceof u)throw e}}getCheckpoint(e,t){const n=this.db.prepare("SELECT schema_version, checkpoint_json\n FROM compaction_checkpoints\n WHERE thread_id = ? AND id = ?").get(e,t);if(void 0!==n)try{return this.withCurrentTranscriptCompleteness(e,v(n))}catch(e){if(e instanceof u)throw e;return}}loadSessionState(e){if(!this.hasThread(e))throw new Error(`Thread "${e}" 不存在`);return{messages:O(this.getMessages(e)).messages,checkpoint:this.getLatestCheckpoint(e),transcriptCompleteness:this.getTranscriptCompleteness(e)}}commitCompaction(e,t){if(!this.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const n=t.messages.map(e=>i.parse(e)),r=t.expectedActiveMessages.map(e=>i.parse(e)),s=O(n);if(s.status!==R.valid){const e=[...s.removedToolCallIds,...s.removedToolResultIds].filter((e,t,n)=>n.indexOf(e)===t).sort((e,t)=>e.localeCompare(t));throw new Error(`Compaction active projection contains malformed Tool protocol: ${e.join(", ")}`)}const o=m(t.draft),a=S.parse(t.legacySnapshotTranscriptFragments??[]),c=S.parse(a.map(e=>E(e))).map(e=>i.parse(N(e))),d=(new Date).toISOString();this.db.exec("BEGIN IMMEDIATE");try{const s=O(this.getMessages(e)).messages;if(JSON.stringify(s)!==JSON.stringify(r))throw new Error("Compaction active projection changed after the draft snapshot was captured");const a=this.getLatestCheckpoint(e);if(a?.id!==t.expectedLatestCheckpointId)throw new Error("Compaction checkpoint ancestry changed after the draft snapshot was captured");const i=this.getLatestSummaryCheckpoint(e),E=w(o.summary,i),h=this.getTranscriptCompleteness(e),u=m({...o,summary:E,...h===T[1]&&"valid"===o.toolState.integrityStatus?{toolState:{...o.toolState,integrityStatus:"sanitized"}}:{}}),_=this.db.prepare("SELECT COALESCE(MAX(generation), 0) AS maxGeneration\n FROM compaction_checkpoints\n WHERE thread_id = ?").get(e),g=this.maxTranscriptMessageSequence(e),S=this.maxToolExecutionSequence(e),N=t.evidenceWatermarks.transcriptMessagesThroughSequence,R=t.evidenceWatermarks.toolExecutionsThroughSequence,I=a?.transcript.messages.throughSequence??-1,L=a?.transcript.toolExecutions.throughSequence??-1,C=2===a?.version?a.semanticEvidence.messagesThroughSequence:-1,x=2===a?.version?a.semanticEvidence.toolExecutionsThroughSequence:-1;if(c.length>0&&1!==a?.version)throw new Error("Legacy snapshot transcript archive requires a V1 parent checkpoint");if(!Number.isInteger(N)||N<I||N>g)throw new Error(`Compaction transcript message watermark ${String(N)} is outside the available range ${String(I)}-${String(g)}`);if(!Number.isInteger(t.semanticEvidenceWatermarks.messagesThroughSequence)||t.semanticEvidenceWatermarks.messagesThroughSequence<C||t.semanticEvidenceWatermarks.messagesThroughSequence>N)throw new Error(`Compaction semantic message watermark ${String(t.semanticEvidenceWatermarks.messagesThroughSequence)} is outside the available range ${String(C)}-${String(N)}`);if(!Number.isInteger(t.semanticEvidenceWatermarks.toolExecutionsThroughSequence)||t.semanticEvidenceWatermarks.toolExecutionsThroughSequence<x||t.semanticEvidenceWatermarks.toolExecutionsThroughSequence>R)throw new Error(`Compaction semantic Tool watermark ${String(t.semanticEvidenceWatermarks.toolExecutionsThroughSequence)} is outside the available range ${String(x)}-${String(R)}`);if(!Number.isInteger(R)||R<L||R>S)throw new Error(`Compaction tool execution watermark ${String(R)} is outside the available range ${String(L)}-${String(S)}`);let A=N;if(c.length>0){if(N!==g)throw new Error("Legacy snapshot transcript archive requires the latest message watermark");const t=this.db.prepare("INSERT INTO transcript_messages\n (thread_id, sequence, role, message_json, provenance, created_at)\n VALUES (?, ?, ?, ?, ?, ?)");let n=g+1;for(const r of c)t.run(e,n,r.role,JSON.stringify(r),p[1],d),n+=1;A=n-1}const f={messages:{fromSequenceExclusive:I,throughSequence:A},toolExecutions:{fromSequenceExclusive:L,throughSequence:R},completeness:h},b=l({draft:u,semanticState:t.semanticState,semanticEvidence:t.semanticEvidenceWatermarks,generation:_.maxGeneration+1,transcript:f,...void 0!==a?{previousCheckpointId:a.id}:{},createdAt:d});return this.db.prepare("INSERT INTO compaction_checkpoints\n (id, thread_id, generation, schema_version,\n message_from_sequence, message_through_sequence,\n tool_from_sequence, tool_through_sequence,\n checkpoint_json, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(b.id,e,b.generation,b.version,b.transcript.messages.fromSequenceExclusive,b.transcript.messages.throughSequence,b.transcript.toolExecutions.fromSequenceExclusive,b.transcript.toolExecutions.throughSequence,JSON.stringify(b),b.createdAt),this.replaceMessagesInTransaction(e,n,d),this.db.exec("COMMIT"),b}catch(e){throw this.db.exec("ROLLBACK"),e}}readCheckpointTranscript(e,t){if("message"!==t.kind&&"tool_execution"!==t.kind)throw new Error("kind 必须是 message 或 tool_execution");const n=this.getCheckpoint(e,t.checkpointId);if(void 0===n)throw new Error("checkpoint 不存在、已损坏或不属于当前 thread");const r=t.limit??A,s="message"===t.kind?n.transcript.messages:n.transcript.toolExecutions,o=Math.max(t.afterSequence??s.fromSequenceExclusive,s.fromSequenceExclusive);this.validateTranscriptRange(o,s.throughSequence,r,b);const a="message"===t.kind?this.listTranscriptMessages(e,{afterSequence:o,throughSequence:s.throughSequence,limit:r+1}).map(e=>({kind:"message",...e})):this.listToolExecutions(e,{afterSequence:o,throughSequence:s.throughSequence,limit:Math.min(r+1,x)}).map(e=>({kind:"tool_execution",...e})),i=a.length>r,c=i?a.slice(0,r):a,d=c.at(-1)?.sequence;return{checkpointId:n.id,kind:t.kind,entries:c,...i&&void 0!==d?{nextAfterSequence:d}:{},...void 0!==n.previousCheckpointId?{previousCheckpointId:n.previousCheckpointId}:{},completeness:n.transcript.completeness}}maxTranscriptMessageSequence(e){return this.db.prepare("SELECT COALESCE(MAX(sequence), -1) AS maxSequence FROM transcript_messages WHERE thread_id = ?").get(e).maxSequence}maxToolExecutionSequence(e){const t=this.db.prepare("SELECT next_sequence FROM thread_tool_execution_state WHERE thread_id = ?").get(e);return(t?.next_sequence??0)-1}withCurrentTranscriptCompleteness(e,t){const n=T[1],r=t.transcript.completeness===n||this.getTranscriptCompleteness(e)===n?n:T[0],s=r===n&&"valid"===t.toolState.integrityStatus?{...t.toolState,integrityStatus:"sanitized"}:t.toolState;return t.transcript.completeness===r&&t.toolState===s?t:{...t,toolState:s,transcript:{...t.transcript,completeness:r}}}validateTranscriptRange(e,t,n,r){if(!Number.isInteger(e)||e<-1)throw new Error("afterSequence 必须是大于等于 -1 的整数");if(!Number.isInteger(t)||t<-1)throw new Error("throughSequence 必须是大于等于 -1 的整数");if(!Number.isInteger(n)||n<1||n>r)throw new Error(`limit 必须是 1-${String(r)} 之间的整数`)}close(){this.db.close()}}
1
+ import{chmodSync as e,existsSync as t,mkdirSync as n}from"node:fs";import{homedir as r}from"node:os";import{resolve as s}from"node:path";import{randomUUID as a}from"node:crypto";import{DatabaseSync as o}from"node:sqlite";import{modelMessageSchema as i}from"ai";import{parsePersistedToolExecutionRecord as c,prepareToolExecutionRecordForPersistence as E,redactSecretText as d}from"../tool-bridge/tool-execution-record.js";import{COMPACTION_CHECKPOINT_VERSION as h,COMPACTION_TRANSCRIPT_COMPLETENESS as T,TRANSCRIPT_MESSAGE_PROVENANCES as u,UnsupportedCompactionCheckpointVersionError as p,archivedTranscriptMessageSchema as _,createCompactionCheckpoint as l,createCompactionCheckpointDraft as m,parseCompactionCheckpoint as g}from"../engine/compaction-checkpoint.js";import{legacyCompactionTranscriptFragmentsSchema as S}from"../engine/compaction-semantic-state.js";import{createLegacyCompactionTranscriptMessage as N}from"../engine/compactor.js";import{ACTIVE_TOOL_PROTOCOL_REPAIR_STATUS as R,repairActiveToolProtocol as O}from"../engine/tool-protocol-repair.js";import{sanitizePersistedExplicitSkillCheckpoint as I}from"../engine/explicit-skill-context.js";const L=4,C=100,A=500,x=50,f=500,q=100,b=15e3;export const TOOL_EXECUTION_RETENTION_POLICY={maxBytesPerThread:16777216,maxRecordsPerThread:2e3,maxAgeMs:2592e6};export const TRANSCRIPT_ENTRY_KINDS=["message","tool_execution"];export function expandTilde(e){return e.startsWith("~/")?s(r(),e.slice(2)):e}export function defaultThreadsDir(){return s(r(),".roll-agent","threads")}function M(e){return e.prepare("PRAGMA foreign_key_list(messages)").all().some(e=>"threads"===e.table&&"thread_id"===e.from&&"id"===e.to&&"CASCADE"===e.on_delete.toUpperCase())}function v(e,t){return"valid"===e.status?e:"fallback"===e.status?{status:"fallback",reason:e.reason,...void 0!==t?{lastValidCheckpointId:t.id}:{}}:{status:"skipped",...void 0!==t?{lastValidCheckpointId:t.id}:{}}}function w(e){if(Number.isInteger(e.schema_version)&&e.schema_version>h)throw new p(e.schema_version);if(!Number.isInteger(e.schema_version))throw new Error("Invalid persisted compaction checkpoint schema version");const t=g(JSON.parse(e.checkpoint_json));if(t.version!==e.schema_version)throw new Error(`Compaction checkpoint schema version mismatch: row v${String(e.schema_version)}, payload v${String(t.version)}`);return t}function D(e){return{id:e.id,title:e.title??void 0,model:e.model??void 0,createdAt:e.created_at,updatedAt:e.updated_at}}export class ThreadStore{db;constructor(r=defaultThreadsDir()){const a=expandTilde(r);t(a)||n(a,{recursive:!0,mode:448}),"win32"!==process.platform&&e(a,448);const i=s(a,"threads.db");if(this.db=new o(i),"win32"!==process.platform)try{e(i,384)}catch(e){throw this.db.close(),e}this.init()}init(){this.db.exec(`PRAGMA busy_timeout = ${String(b)};\n PRAGMA foreign_keys = ON;\n PRAGMA secure_delete = ON;`);const e=this.db.prepare("PRAGMA user_version").get();if(e.user_version>4)throw new Error(`ThreadStore schema v${String(e.user_version)} 高于当前支持的 v${String(4)}`);this.db.exec("BEGIN IMMEDIATE");try{this.db.exec("CREATE TABLE IF NOT EXISTS threads (\n id TEXT PRIMARY KEY,\n title TEXT,\n model TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS messages (\n thread_id TEXT NOT NULL,\n idx INTEGER NOT NULL,\n role TEXT NOT NULL,\n content_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (thread_id, idx),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );"),M(this.db)||this.db.exec("CREATE TABLE messages_with_thread_fk (\n thread_id TEXT NOT NULL,\n idx INTEGER NOT NULL,\n role TEXT NOT NULL,\n content_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (thread_id, idx),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n INSERT INTO messages_with_thread_fk\n (thread_id, idx, role, content_json, created_at)\n SELECT messages.thread_id, messages.idx, messages.role,\n messages.content_json, messages.created_at\n FROM messages\n INNER JOIN threads ON threads.id = messages.thread_id;\n DROP TABLE messages;\n ALTER TABLE messages_with_thread_fk RENAME TO messages;"),this.db.exec("CREATE TABLE IF NOT EXISTS tool_executions (\n thread_id TEXT NOT NULL,\n sequence INTEGER NOT NULL,\n id TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n agent_name TEXT NOT NULL,\n tool_name TEXT NOT NULL,\n record_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY (thread_id, id),\n UNIQUE (thread_id, sequence),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n CREATE INDEX IF NOT EXISTS idx_tool_executions_thread_call\n ON tool_executions(thread_id, tool_call_id, sequence);\n CREATE TABLE IF NOT EXISTS thread_tool_execution_state (\n thread_id TEXT PRIMARY KEY,\n next_sequence INTEGER NOT NULL CHECK (next_sequence >= 0),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n CREATE TABLE IF NOT EXISTS transcript_messages (\n thread_id TEXT NOT NULL,\n sequence INTEGER NOT NULL,\n role TEXT NOT NULL,\n message_json TEXT NOT NULL,\n provenance TEXT NOT NULL CHECK (provenance IN ('native', 'legacy_snapshot')),\n created_at TEXT NOT NULL,\n PRIMARY KEY (thread_id, sequence),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n CREATE TABLE IF NOT EXISTS thread_transcript_state (\n thread_id TEXT PRIMARY KEY,\n completeness TEXT NOT NULL CHECK (completeness IN ('complete', 'legacy_snapshot')),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n CREATE TABLE IF NOT EXISTS compaction_checkpoints (\n id TEXT PRIMARY KEY,\n thread_id TEXT NOT NULL,\n generation INTEGER NOT NULL,\n schema_version INTEGER NOT NULL,\n message_from_sequence INTEGER NOT NULL,\n message_through_sequence INTEGER NOT NULL,\n tool_from_sequence INTEGER NOT NULL,\n tool_through_sequence INTEGER NOT NULL,\n checkpoint_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n UNIQUE (thread_id, generation),\n FOREIGN KEY (thread_id) REFERENCES threads(id) ON DELETE CASCADE\n );\n CREATE INDEX IF NOT EXISTS idx_compaction_checkpoints_thread_generation\n ON compaction_checkpoints(thread_id, generation DESC);"),this.db.exec("INSERT OR IGNORE INTO thread_tool_execution_state (thread_id, next_sequence)\n SELECT id, 0 FROM threads;\n UPDATE thread_tool_execution_state\n SET next_sequence = MAX(\n next_sequence,\n COALESCE((\n SELECT MAX(tool_executions.sequence) + 1\n FROM tool_executions\n WHERE tool_executions.thread_id = thread_tool_execution_state.thread_id\n ), 0)\n );"),e.user_version<3&&this.db.exec("INSERT OR IGNORE INTO thread_transcript_state (thread_id, completeness)\n SELECT id, 'legacy_snapshot' FROM threads;\n INSERT OR IGNORE INTO transcript_messages\n (thread_id, sequence, role, message_json, provenance, created_at)\n SELECT thread_id, idx, role, content_json, 'legacy_snapshot', created_at\n FROM messages;"),e.user_version<4&&(this.migrateToolExecutionPersistenceInTransaction(),this.migrateExplicitSkillCheckpointPersistenceInTransaction()),this.enforceAllToolExecutionRetentionInTransaction((new Date).toISOString()),this.db.exec(`PRAGMA user_version = ${String(4)};`),this.db.exec("COMMIT")}catch(e){throw this.db.exec("ROLLBACK"),e}}migrateToolExecutionPersistenceInTransaction(){const e=this.db.prepare("SELECT rowid AS storage_rowid, record_json\n FROM tool_executions\n WHERE rowid > ?\n ORDER BY rowid ASC\n LIMIT 100"),t=this.db.prepare("UPDATE tool_executions\n SET tool_call_id = ?, agent_name = ?, tool_name = ?, record_json = ?, created_at = ?\n WHERE rowid = ?");let n=0;for(;;){const r=e.all(n);if(0===r.length)break;for(const e of r){const r=c(JSON.parse(e.record_json));t.run(r.toolCallId,r.agentName,r.toolName,JSON.stringify(r),r.createdAt,e.storage_rowid),n=e.storage_rowid}}}enforceAllToolExecutionRetentionInTransaction(e){const t=this.db.prepare("SELECT DISTINCT thread_id AS id FROM tool_executions").all();for(const{id:n}of t)this.enforceToolExecutionRetentionInTransaction(n,e)}migrateExplicitSkillCheckpointPersistenceInTransaction(){const e=[{table:"messages",column:"content_json"},{table:"transcript_messages",column:"message_json"}];for(const t of e){const e=this.db.prepare(`SELECT rowid AS storage_rowid, ${t.column} AS message_json\n FROM ${t.table}\n WHERE ${t.column} LIKE '%"modelUserContent"%'`).all(),n=this.db.prepare(`UPDATE ${t.table} SET ${t.column} = ? WHERE rowid = ?`);for(const t of e){const e=i.parse(JSON.parse(t.message_json)),r=I(e);n.run(JSON.stringify(r),t.storage_rowid)}}}createThread(e={}){const t=e.id??a(),n=(new Date).toISOString();this.db.exec("BEGIN IMMEDIATE");try{return this.db.prepare("INSERT INTO threads (id, title, model, created_at, updated_at) VALUES (?, ?, ?, ?, ?)").run(t,e.title??null,e.model??null,n,n),this.db.prepare("INSERT INTO thread_transcript_state (thread_id, completeness) VALUES (?, ?)").run(t,T[0]),this.db.prepare("INSERT INTO thread_tool_execution_state (thread_id, next_sequence) VALUES (?, 0)").run(t),this.db.exec("COMMIT"),t}catch(e){throw this.db.exec("ROLLBACK"),e}}hasThread(e){return void 0!==this.db.prepare("SELECT 1 FROM threads WHERE id = ?").get(e)}getThread(e){const t=this.db.prepare("SELECT * FROM threads WHERE id = ?").get(e);return t?D(t):void 0}listThreads(){return this.db.prepare("SELECT * FROM threads ORDER BY updated_at DESC, rowid DESC").all().map(D)}countMessages(e){return this.db.prepare("SELECT COUNT(*) AS n FROM messages WHERE thread_id = ?").get(e).n}countTranscriptMessages(e){return this.db.prepare("SELECT COUNT(*) AS n FROM transcript_messages WHERE thread_id = ?").get(e).n}updateTitle(e,t){this.db.prepare("UPDATE threads SET title = ? WHERE id = ?").run(t,e)}deleteThread(e){this.db.prepare("DELETE FROM threads WHERE id = ?").run(e)}appendMessages(e,t){if(0===t.length)return;if(!this.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const n=t.map(e=>I(i.parse(e))),r=(new Date).toISOString(),s=this.db.prepare("INSERT INTO messages (thread_id, idx, role, content_json, created_at) VALUES (?, ?, ?, ?, ?)"),a=this.db.prepare("INSERT INTO transcript_messages\n (thread_id, sequence, role, message_json, provenance, created_at)\n VALUES (?, ?, ?, ?, ?, ?)");this.db.exec("BEGIN IMMEDIATE");try{const t=this.db.prepare("SELECT COALESCE(MAX(idx), -1) AS maxIdx FROM messages WHERE thread_id = ?").get(e),o=this.db.prepare("SELECT COALESCE(MAX(sequence), -1) AS maxSequence FROM transcript_messages WHERE thread_id = ?").get(e);let i=t.maxIdx+1,c=o.maxSequence+1;for(const t of n){const n=JSON.stringify(t);s.run(e,i,t.role,n,r),a.run(e,c,t.role,n,u[0],r),i+=1,c+=1}this.db.prepare("UPDATE threads SET updated_at = ? WHERE id = ?").run(r,e),this.db.exec("COMMIT")}catch(e){throw this.db.exec("ROLLBACK"),e}}replaceMessages(e,t){if(!this.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const n=t.map(e=>i.parse(e)),r=(new Date).toISOString();this.db.exec("BEGIN IMMEDIATE");try{this.replaceMessagesInTransaction(e,n,r),this.db.exec("COMMIT")}catch(e){throw this.db.exec("ROLLBACK"),e}}getMessages(e){return this.db.prepare("SELECT content_json FROM messages WHERE thread_id = ? ORDER BY idx ASC").all(e).map(e=>i.parse(JSON.parse(e.content_json)))}replaceMessagesInTransaction(e,t,n){const r=this.db.prepare("INSERT INTO messages (thread_id, idx, role, content_json, created_at) VALUES (?, ?, ?, ?, ?)");this.db.prepare("DELETE FROM messages WHERE thread_id = ?").run(e),t.forEach((t,s)=>{const a=I(t);r.run(e,s,a.role,JSON.stringify(a),n)}),this.db.prepare("UPDATE threads SET updated_at = ? WHERE id = ?").run(n,e)}appendToolExecution(e,t){if(!this.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const n=E(t),r=JSON.stringify(n),s=(new Date).toISOString();this.db.exec("BEGIN IMMEDIATE");try{const t=this.db.prepare("SELECT next_sequence FROM thread_tool_execution_state WHERE thread_id = ?").get(e);if(void 0===t)throw new Error(`Thread "${e}" 缺少 Tool execution sequence state`);const a=t.next_sequence;return this.db.prepare("INSERT INTO tool_executions\n (thread_id, sequence, id, tool_call_id, agent_name, tool_name, record_json, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(e,a,n.id,n.toolCallId,n.agentName,n.toolName,r,n.createdAt),this.db.prepare("UPDATE thread_tool_execution_state SET next_sequence = ? WHERE thread_id = ?").run(a+1,e),this.enforceToolExecutionRetentionInTransaction(e,s),this.db.prepare("UPDATE threads SET updated_at = ? WHERE id = ?").run(s,e),this.db.exec("COMMIT"),a}catch(e){throw this.db.exec("ROLLBACK"),e}}enforceToolExecutionRetentionInTransaction(e,t){const n=new Date(Date.parse(t)-TOOL_EXECUTION_RETENTION_POLICY.maxAgeMs).toISOString();let r=!1;const s=this.db.prepare("DELETE FROM tool_executions\n WHERE thread_id = ?\n AND created_at < ?").run(e,n);r=Number(s.changes)>0;const a=this.db.prepare("SELECT sequence\n FROM (\n SELECT sequence,\n ROW_NUMBER() OVER (ORDER BY sequence DESC) AS retained_rank,\n SUM(length(CAST(record_json AS BLOB))) OVER (\n ORDER BY sequence DESC\n ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW\n ) AS retained_bytes\n FROM tool_executions\n WHERE thread_id = ?\n )\n WHERE retained_rank > ? OR retained_bytes > ?").all(e,TOOL_EXECUTION_RETENTION_POLICY.maxRecordsPerThread,TOOL_EXECUTION_RETENTION_POLICY.maxBytesPerThread);if(a.length>0){const t=this.db.prepare("DELETE FROM tool_executions WHERE thread_id = ? AND sequence = ?");for(const n of a)t.run(e,n.sequence);r=!0}r&&this.db.prepare("INSERT INTO thread_transcript_state (thread_id, completeness)\n VALUES (?, 'legacy_snapshot')\n ON CONFLICT(thread_id) DO UPDATE SET completeness = 'legacy_snapshot'").run(e)}listToolExecutions(e,t={}){const n=t.afterSequence??-1,r=t.throughSequence??Number.MAX_SAFE_INTEGER,s=t.limit??C;if(!Number.isInteger(n)||n<-1)throw new Error("afterSequence 必须是大于等于 -1 的整数");if(!Number.isInteger(s)||s<1||s>A)throw new Error(`limit 必须是 1-${String(A)} 之间的整数`);if(!Number.isInteger(r)||r<-1)throw new Error("throughSequence 必须是大于等于 -1 的整数");if(r<=n)return[];return this.db.prepare("SELECT sequence, record_json\n FROM tool_executions\n WHERE thread_id = ?\n AND sequence > ?\n AND sequence <= ?\n AND (? IS NULL OR tool_call_id = ?)\n ORDER BY sequence ASC\n LIMIT ?").all(e,n,r,t.toolCallId??null,t.toolCallId??null,s).map(e=>({...c(JSON.parse(e.record_json)),sequence:e.sequence}))}listRecentToolExecutions(e,t={}){const n=t.beforeSequence??Number.MAX_SAFE_INTEGER,r=t.limit??C;this.validateRecentPage(n,r,A);const s=this.db.prepare("SELECT sequence, record_json\n FROM tool_executions\n WHERE thread_id = ?\n AND sequence < ?\n ORDER BY sequence DESC\n LIMIT ?").all(e,n,r+1),a=s.length>r,o=s.slice(0,r).map(e=>({...c(JSON.parse(e.record_json)),sequence:e.sequence})).reverse();return{entries:o,nextBeforeSequence:a?o[0]?.sequence:void 0}}getToolExecution(e,t){const n=this.db.prepare("SELECT sequence, record_json FROM tool_executions WHERE thread_id = ? AND id = ?").get(e,t);if(n)return{...c(JSON.parse(n.record_json)),sequence:n.sequence}}getTranscriptCompleteness(e){const t=this.db.prepare("SELECT completeness FROM thread_transcript_state WHERE thread_id = ?").get(e);return t?.completeness===T[0]?T[0]:T[1]}listTranscriptMessages(e,t={}){const n=t.afterSequence??-1,r=t.throughSequence??Number.MAX_SAFE_INTEGER,s=t.limit??x;if(this.validateTranscriptRange(n,r,s,f),r<=n)return[];return this.db.prepare("SELECT sequence, provenance, created_at, message_json\n FROM transcript_messages\n WHERE thread_id = ?\n AND sequence > ?\n AND sequence <= ?\n ORDER BY sequence ASC\n LIMIT ?").all(e,n,r,s).map(e=>_.parse({sequence:e.sequence,provenance:e.provenance,createdAt:e.created_at,message:JSON.parse(e.message_json)}))}listRecentTranscriptMessages(e,t={}){const n=t.beforeSequence??Number.MAX_SAFE_INTEGER,r=t.limit??x;this.validateRecentPage(n,r,f);const s=this.db.prepare("SELECT sequence, provenance, created_at, message_json\n FROM transcript_messages\n WHERE thread_id = ?\n AND sequence < ?\n ORDER BY sequence DESC\n LIMIT ?").all(e,n,r+1),a=s.length>r,o=s.slice(0,r).map(e=>_.parse({sequence:e.sequence,provenance:e.provenance,createdAt:e.created_at,message:JSON.parse(e.message_json)})).reverse();return{entries:o,nextBeforeSequence:a?o[0]?.sequence:void 0}}getLatestCheckpoint(e){const t=this.db.prepare("SELECT schema_version, checkpoint_json\n FROM compaction_checkpoints\n WHERE thread_id = ?\n ORDER BY generation DESC").all(e);for(const n of t)try{return this.withCurrentTranscriptCompleteness(e,w(n))}catch(e){if(e instanceof p)throw e}}getLatestSummaryCheckpoint(e){const t=this.db.prepare("SELECT schema_version, checkpoint_json\n FROM compaction_checkpoints\n WHERE thread_id = ?\n ORDER BY generation DESC").all(e);for(const n of t)try{const t=w(n);if("valid"===t.summary.status)return this.withCurrentTranscriptCompleteness(e,t)}catch(e){if(e instanceof p)throw e}}getCheckpoint(e,t){const n=this.db.prepare("SELECT schema_version, checkpoint_json\n FROM compaction_checkpoints\n WHERE thread_id = ? AND id = ?").get(e,t);if(void 0!==n)try{return this.withCurrentTranscriptCompleteness(e,w(n))}catch(e){if(e instanceof p)throw e;return}}loadSessionState(e){if(!this.hasThread(e))throw new Error(`Thread "${e}" 不存在`);return{messages:O(this.getMessages(e)).messages,checkpoint:this.getLatestCheckpoint(e),transcriptCompleteness:this.getTranscriptCompleteness(e)}}commitCompaction(e,t){if(!this.hasThread(e))throw new Error(`Thread "${e}" 不存在`);const n=t.messages.map(e=>i.parse(e)),r=t.expectedActiveMessages.map(e=>i.parse(e)),s=O(n);if(s.status!==R.valid){const e=[...s.removedToolCallIds,...s.removedToolResultIds].filter((e,t,n)=>n.indexOf(e)===t).sort((e,t)=>e.localeCompare(t));throw new Error(`Compaction active projection contains malformed Tool protocol: ${e.join(", ")}`)}const a=m(t.draft),o=S.parse(t.legacySnapshotTranscriptFragments??[]),c=S.parse(o.map(e=>d(e))).map(e=>i.parse(N(e))),E=(new Date).toISOString();this.db.exec("BEGIN IMMEDIATE");try{const s=O(this.getMessages(e)).messages;if(JSON.stringify(s)!==JSON.stringify(r))throw new Error("Compaction active projection changed after the draft snapshot was captured");const o=this.getLatestCheckpoint(e);if(o?.id!==t.expectedLatestCheckpointId)throw new Error("Compaction checkpoint ancestry changed after the draft snapshot was captured");const i=this.getLatestSummaryCheckpoint(e),d=v(a.summary,i),h=this.getTranscriptCompleteness(e),p=m({...a,summary:d,...h===T[1]&&"valid"===a.toolState.integrityStatus?{toolState:{...a.toolState,integrityStatus:"sanitized"}}:{}}),_=this.db.prepare("SELECT COALESCE(MAX(generation), 0) AS maxGeneration\n FROM compaction_checkpoints\n WHERE thread_id = ?").get(e),g=this.maxTranscriptMessageSequence(e),S=this.maxToolExecutionSequence(e),N=t.evidenceWatermarks.transcriptMessagesThroughSequence,R=t.evidenceWatermarks.toolExecutionsThroughSequence,I=o?.transcript.messages.throughSequence??-1,L=o?.transcript.toolExecutions.throughSequence??-1,C=2===o?.version?o.semanticEvidence.messagesThroughSequence:-1,A=2===o?.version?o.semanticEvidence.toolExecutionsThroughSequence:-1;if(c.length>0&&1!==o?.version)throw new Error("Legacy snapshot transcript archive requires a V1 parent checkpoint");if(!Number.isInteger(N)||N<I||N>g)throw new Error(`Compaction transcript message watermark ${String(N)} is outside the available range ${String(I)}-${String(g)}`);if(!Number.isInteger(t.semanticEvidenceWatermarks.messagesThroughSequence)||t.semanticEvidenceWatermarks.messagesThroughSequence<C||t.semanticEvidenceWatermarks.messagesThroughSequence>N)throw new Error(`Compaction semantic message watermark ${String(t.semanticEvidenceWatermarks.messagesThroughSequence)} is outside the available range ${String(C)}-${String(N)}`);if(!Number.isInteger(t.semanticEvidenceWatermarks.toolExecutionsThroughSequence)||t.semanticEvidenceWatermarks.toolExecutionsThroughSequence<A||t.semanticEvidenceWatermarks.toolExecutionsThroughSequence>R)throw new Error(`Compaction semantic Tool watermark ${String(t.semanticEvidenceWatermarks.toolExecutionsThroughSequence)} is outside the available range ${String(A)}-${String(R)}`);if(!Number.isInteger(R)||R<L||R>S)throw new Error(`Compaction tool execution watermark ${String(R)} is outside the available range ${String(L)}-${String(S)}`);let x=N;if(c.length>0){if(N!==g)throw new Error("Legacy snapshot transcript archive requires the latest message watermark");const t=this.db.prepare("INSERT INTO transcript_messages\n (thread_id, sequence, role, message_json, provenance, created_at)\n VALUES (?, ?, ?, ?, ?, ?)");let n=g+1;for(const r of c)t.run(e,n,r.role,JSON.stringify(r),u[1],E),n+=1;x=n-1}const f={messages:{fromSequenceExclusive:I,throughSequence:x},toolExecutions:{fromSequenceExclusive:L,throughSequence:R},completeness:h},q=l({draft:p,semanticState:t.semanticState,semanticEvidence:t.semanticEvidenceWatermarks,generation:_.maxGeneration+1,transcript:f,...void 0!==o?{previousCheckpointId:o.id}:{},createdAt:E});return this.db.prepare("INSERT INTO compaction_checkpoints\n (id, thread_id, generation, schema_version,\n message_from_sequence, message_through_sequence,\n tool_from_sequence, tool_through_sequence,\n checkpoint_json, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(q.id,e,q.generation,q.version,q.transcript.messages.fromSequenceExclusive,q.transcript.messages.throughSequence,q.transcript.toolExecutions.fromSequenceExclusive,q.transcript.toolExecutions.throughSequence,JSON.stringify(q),q.createdAt),this.replaceMessagesInTransaction(e,n,E),this.db.exec("COMMIT"),q}catch(e){throw this.db.exec("ROLLBACK"),e}}readCheckpointTranscript(e,t){if("message"!==t.kind&&"tool_execution"!==t.kind)throw new Error("kind 必须是 message 或 tool_execution");const n=this.getCheckpoint(e,t.checkpointId);if(void 0===n)throw new Error("checkpoint 不存在、已损坏或不属于当前 thread");const r=t.limit??x,s="message"===t.kind?n.transcript.messages:n.transcript.toolExecutions,a=Math.max(t.afterSequence??s.fromSequenceExclusive,s.fromSequenceExclusive);this.validateTranscriptRange(a,s.throughSequence,r,q);const o="message"===t.kind?this.listTranscriptMessages(e,{afterSequence:a,throughSequence:s.throughSequence,limit:r+1}).map(e=>({kind:"message",...e})):this.listToolExecutions(e,{afterSequence:a,throughSequence:s.throughSequence,limit:Math.min(r+1,A)}).map(e=>({kind:"tool_execution",...e})),i=o.length>r,c=i?o.slice(0,r):o,E=c.at(-1)?.sequence;return{checkpointId:n.id,kind:t.kind,entries:c,...i&&void 0!==E?{nextAfterSequence:E}:{},...void 0!==n.previousCheckpointId?{previousCheckpointId:n.previousCheckpointId}:{},completeness:n.transcript.completeness}}maxTranscriptMessageSequence(e){return this.db.prepare("SELECT COALESCE(MAX(sequence), -1) AS maxSequence FROM transcript_messages WHERE thread_id = ?").get(e).maxSequence}maxToolExecutionSequence(e){const t=this.db.prepare("SELECT next_sequence FROM thread_tool_execution_state WHERE thread_id = ?").get(e);return(t?.next_sequence??0)-1}withCurrentTranscriptCompleteness(e,t){const n=T[1],r=t.transcript.completeness===n||this.getTranscriptCompleteness(e)===n?n:T[0],s=r===n&&"valid"===t.toolState.integrityStatus?{...t.toolState,integrityStatus:"sanitized"}:t.toolState;return t.transcript.completeness===r&&t.toolState===s?t:{...t,toolState:s,transcript:{...t.transcript,completeness:r}}}validateTranscriptRange(e,t,n,r){if(!Number.isInteger(e)||e<-1)throw new Error("afterSequence 必须是大于等于 -1 的整数");if(!Number.isInteger(t)||t<-1)throw new Error("throughSequence 必须是大于等于 -1 的整数");if(!Number.isInteger(n)||n<1||n>r)throw new Error(`limit 必须是 1-${String(r)} 之间的整数`)}validateRecentPage(e,t,n){if(!Number.isSafeInteger(e)||e<0||e>Number.MAX_SAFE_INTEGER)throw new Error("beforeSequence 必须是非负安全整数");if(!Number.isInteger(t)||t<1||t>n)throw new Error(`limit 必须是 1-${String(n)} 之间的整数`)}close(){this.db.close()}}
@@ -12,12 +12,12 @@ export declare const turnCancellationMetadataV1Schema: z.ZodReadonly<z.ZodObject
12
12
  reason: z.ZodEnum<["user", "timeout", "runtime"]>;
13
13
  }, "strip", z.ZodTypeAny, {
14
14
  version: 1;
15
- kind: "turn-cancellation";
16
15
  reason: "user" | "timeout" | "runtime";
16
+ kind: "turn-cancellation";
17
17
  }, {
18
18
  version: 1;
19
- kind: "turn-cancellation";
20
19
  reason: "user" | "timeout" | "runtime";
20
+ kind: "turn-cancellation";
21
21
  }>>;
22
22
  export declare function createTurnCancellationMessage(content: string, reason: SessionCancellationReason): AssistantModelMessage;
23
23
  export declare function readTurnCancellationReason(message: ModelMessage): SessionCancellationReason | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@roll-agent/runtime",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,11 +29,12 @@
29
29
  "@ai-sdk/provider": "^4.0.1",
30
30
  "@modelcontextprotocol/sdk": "^1.12.0",
31
31
  "ai": "^7.0.9",
32
- "zod": "^3.25.76"
32
+ "zod": "^3.25.76",
33
+ "@roll-agent/protocol": "0.1.0"
33
34
  },
34
35
  "devDependencies": {
35
36
  "@types/node": "^22.0.0",
36
- "@roll-agent/core": "0.22.0"
37
+ "@roll-agent/core": "0.24.0"
37
38
  },
38
39
  "scripts": {
39
40
  "build": "rm -rf dist && tsc -p tsconfig.build.json && node ../../scripts/obfuscate.mjs",