@roll-agent/runtime 0.10.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.
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/server/protocol.d.ts +2 -0
- package/dist/server/runtime-protocol-adapter.d.ts +13 -0
- package/dist/server/runtime-protocol-adapter.js +1 -0
- package/dist/server/runtime-server.d.ts +4 -0
- package/dist/server/runtime-server.js +1 -1
- package/dist/server/transport/stdio.d.ts +5 -1
- package/dist/server/transport/stdio.js +1 -1
- package/dist/service/runtime-service.d.ts +89 -0
- package/dist/service/runtime-service.js +1 -0
- package/dist/store/thread-store.d.ts +16 -0
- package/dist/store/thread-store.js +1 -1
- package/dist/types/cancellation.d.ts +2 -2
- package/package.json +4 -3
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{
|
|
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
|
|
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
|
|
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.
|
|
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.
|
|
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",
|