@botbotgo/agent-harness 0.0.475 → 0.0.476
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/README.md +3 -1234
- package/README.zh.md +3 -1191
- package/dist/acp.js +1 -1
- package/dist/api.js +1 -404
- package/dist/benchmark/checkpoint-resume-cost-benchmark.js +1 -55
- package/dist/benchmark/deepagent-local-model-benchmark.js +2 -35
- package/dist/benchmark/upstream-runtime-ab-benchmark.js +1 -179
- package/dist/cli/chat-interactive.js +25 -244
- package/dist/cli/chat-rendering.js +6 -100
- package/dist/cli/chat-stream.js +23 -512
- package/dist/cli/chat-ui.js +21 -199
- package/dist/cli/chat-workspace.js +2 -210
- package/dist/cli/main.js +21 -428
- package/dist/cli/managed-service-commands.js +9 -63
- package/dist/cli/managed-service.js +2 -137
- package/dist/cli/options-init-chat.js +1 -108
- package/dist/cli/options-runtime.js +1 -158
- package/dist/cli/options-serve.js +1 -282
- package/dist/cli/options.js +2 -19
- package/dist/cli/process-guards.js +1 -139
- package/dist/cli/request-tree.js +7 -296
- package/dist/cli/runtime-commands.js +12 -258
- package/dist/cli/runtime-output.js +16 -155
- package/dist/cli/server-commands.js +16 -270
- package/dist/cli/workspace.js +1 -67
- package/dist/cli.js +1 -7
- package/dist/client/acp.js +1 -1
- package/dist/client/in-process.js +1 -67
- package/dist/client/index.js +1 -2
- package/dist/client/types.js +0 -1
- package/dist/client.js +1 -1
- package/dist/contracts/core.js +1 -1
- package/dist/contracts/runtime-evaluation.js +0 -1
- package/dist/contracts/runtime-memory.js +0 -1
- package/dist/contracts/runtime-observability.js +0 -1
- package/dist/contracts/runtime-requests.js +0 -1
- package/dist/contracts/runtime-scheduling.js +0 -1
- package/dist/contracts/runtime.js +1 -27
- package/dist/contracts/types.js +1 -3
- package/dist/contracts/workspace.js +0 -1
- package/dist/flow/build-flow-graph.js +1 -50
- package/dist/flow/export-mermaid.js +2 -464
- package/dist/flow/export-sequence-mermaid.js +2 -325
- package/dist/flow/flow-graph-normalization.js +1 -214
- package/dist/flow/flow-graph-runtime.js +1 -107
- package/dist/flow/flow-graph-upstream.js +1 -494
- package/dist/flow/index.js +1 -3
- package/dist/flow/types.js +0 -1
- package/dist/index.js +1 -5
- package/dist/init-project.js +1 -1
- package/dist/knowledge/config.js +1 -32
- package/dist/knowledge/contracts.js +0 -1
- package/dist/knowledge/index.js +1 -2
- package/dist/knowledge/module.js +12 -909
- package/dist/knowledge/procedural/config.js +1 -125
- package/dist/knowledge/procedural/index.js +1 -2
- package/dist/knowledge/procedural/manager.js +9 -345
- package/dist/mcp.js +1 -2
- package/dist/package-version.d.ts +1 -1
- package/dist/package-version.js +1 -2
- package/dist/persistence/file-store.js +3 -758
- package/dist/persistence/sqlite-request-context-store.js +5 -54
- package/dist/persistence/sqlite-request-queue-store.js +10 -108
- package/dist/persistence/sqlite-runtime.js +1 -86
- package/dist/persistence/sqlite-store.js +62 -810
- package/dist/persistence/types.js +0 -1
- package/dist/projections/presentation.js +37 -206
- package/dist/projections/request-events.js +2 -502
- package/dist/projections/upstream-events.js +1 -201
- package/dist/protocol/a2a/http-discovery.js +1 -178
- package/dist/protocol/a2a/http-rpc.js +6 -622
- package/dist/protocol/a2a/http.js +1 -138
- package/dist/protocol/a2a/task-state.js +3 -317
- package/dist/protocol/acp/client.js +8 -294
- package/dist/protocol/acp/harness-client.js +1 -218
- package/dist/protocol/acp/http.js +5 -130
- package/dist/protocol/acp/server.js +1 -310
- package/dist/protocol/acp/stdio.js +2 -69
- package/dist/protocol/ag-ui/http.js +3 -378
- package/dist/protocol/mcp/server.js +1 -428
- package/dist/resource/backend/workspace-scoped-backend.js +1 -319
- package/dist/resource/isolation.js +1 -237
- package/dist/resource/mcp/tool-support.js +3 -296
- package/dist/resource/mcp-tool-support.js +1 -2
- package/dist/resource/providers/resource-provider.js +1 -215
- package/dist/resource/resource-impl.js +1 -3
- package/dist/resource/resource-types.js +0 -1
- package/dist/resource/resource.js +1 -1
- package/dist/resource/sources.js +1 -247
- package/dist/resource/tools/function-tool-resolver.js +2 -272
- package/dist/runtime/adapter/compat/deepagent-compat.js +1 -29
- package/dist/runtime/adapter/compat/openai-compatible.js +1 -55
- package/dist/runtime/adapter/direct-builtin-utility.js +2 -90
- package/dist/runtime/adapter/flow/execution-context.js +1 -71
- package/dist/runtime/adapter/flow/invocation-flow.js +8 -425
- package/dist/runtime/adapter/flow/invoke-runtime.js +1 -20
- package/dist/runtime/adapter/flow/stream-runtime.js +11 -1395
- package/dist/runtime/adapter/invocation-result.js +2 -473
- package/dist/runtime/adapter/local-tool-invocation.js +6 -638
- package/dist/runtime/adapter/middleware/context-hygiene.js +1 -83
- package/dist/runtime/adapter/middleware-assembly.js +5 -477
- package/dist/runtime/adapter/model/invocation-request.js +3 -183
- package/dist/runtime/adapter/model/message-assembly.js +1 -28
- package/dist/runtime/adapter/model/model-providers.js +23 -1115
- package/dist/runtime/adapter/model/prompted-json-tool-call-capture.js +1 -40
- package/dist/runtime/adapter/model/prompted-json-tool-policy.js +1 -22
- package/dist/runtime/adapter/resilience.js +1 -104
- package/dist/runtime/adapter/runtime-adapter-support.js +3 -141
- package/dist/runtime/adapter/runtime-shell.js +5 -166
- package/dist/runtime/adapter/stream-event-projection.js +2 -622
- package/dist/runtime/adapter/stream-text-consumption.js +1 -18
- package/dist/runtime/adapter/terminal-status.js +2 -67
- package/dist/runtime/adapter/tool/builtin-middleware-tools.js +6 -627
- package/dist/runtime/adapter/tool/declared-middleware.js +1 -154
- package/dist/runtime/adapter/tool/interrupt-policy.js +1 -34
- package/dist/runtime/adapter/tool/provider-tool.js +1 -25
- package/dist/runtime/adapter/tool/resolved-tool.js +1 -225
- package/dist/runtime/adapter/tool/tool-arguments.js +3 -486
- package/dist/runtime/adapter/tool/tool-hitl.js +1 -346
- package/dist/runtime/adapter/tool/tool-name-mapping.js +1 -128
- package/dist/runtime/adapter/tool/tool-output-artifacts.js +2 -88
- package/dist/runtime/adapter/tool/tool-replay.js +1 -37
- package/dist/runtime/adapter/tool-resolution.js +1 -86
- package/dist/runtime/adapter/upstream-configurable-keys.js +1 -2
- package/dist/runtime/agent-runtime-adapter.js +60 -2338
- package/dist/runtime/agent-runtime-assembly.js +7 -249
- package/dist/runtime/env/runtime-env.js +1 -62
- package/dist/runtime/harness/background-runtime.js +1 -8
- package/dist/runtime/harness/bindings.js +1 -58
- package/dist/runtime/harness/events/event-bus.js +1 -16
- package/dist/runtime/harness/events/event-sink.js +1 -61
- package/dist/runtime/harness/events/events.js +1 -80
- package/dist/runtime/harness/events/listener-runtime.js +1 -13
- package/dist/runtime/harness/events/runtime-event-operations.js +1 -9
- package/dist/runtime/harness/events/streaming.js +1 -100
- package/dist/runtime/harness/events/timeline.js +1 -52
- package/dist/runtime/harness/public-shapes.js +1 -186
- package/dist/runtime/harness/run/artifact-paths.js +1 -15
- package/dist/runtime/harness/run/governance.js +1 -295
- package/dist/runtime/harness/run/helpers.js +1 -71
- package/dist/runtime/harness/run/inspection.js +1 -409
- package/dist/runtime/harness/run/operator-overview.js +1 -80
- package/dist/runtime/harness/run/queue-diagnostics.js +1 -15
- package/dist/runtime/harness/run/recovery.js +1 -162
- package/dist/runtime/harness/run/resources.js +1 -60
- package/dist/runtime/harness/run/resume.js +1 -56
- package/dist/runtime/harness/run/routing.js +1 -48
- package/dist/runtime/harness/run/run-lifecycle.js +1 -66
- package/dist/runtime/harness/run/run-operations.js +1 -217
- package/dist/runtime/harness/run/run-queue.js +1 -43
- package/dist/runtime/harness/run/run-slot-acquisition.js +1 -157
- package/dist/runtime/harness/run/session-records.js +1 -97
- package/dist/runtime/harness/run/start-run.js +1 -120
- package/dist/runtime/harness/run/startup-runtime.js +1 -69
- package/dist/runtime/harness/run/stream-run.js +8 -1418
- package/dist/runtime/harness/run/surface-semantics.js +1 -79
- package/dist/runtime/harness/runtime-defaults.js +1 -39
- package/dist/runtime/harness/system/boundary-analysis.js +1 -234
- package/dist/runtime/harness/system/health-monitor.js +1 -258
- package/dist/runtime/harness/system/inventory.js +1 -129
- package/dist/runtime/harness/system/mem0-ingestion-sync.js +5 -345
- package/dist/runtime/harness/system/policy-engine.js +1 -175
- package/dist/runtime/harness/system/runtime-memory-candidates.js +4 -110
- package/dist/runtime/harness/system/runtime-memory-consolidation.js +1 -51
- package/dist/runtime/harness/system/runtime-memory-manager.js +10 -693
- package/dist/runtime/harness/system/runtime-memory-policy.js +1 -155
- package/dist/runtime/harness/system/runtime-memory-records.js +11 -577
- package/dist/runtime/harness/system/runtime-memory-sync.js +5 -206
- package/dist/runtime/harness/system/session-memory-sync.js +3 -113
- package/dist/runtime/harness/system/skill-requirements.js +1 -112
- package/dist/runtime/harness/system/store.js +9 -365
- package/dist/runtime/harness/tool-gateway/index.js +1 -2
- package/dist/runtime/harness/tool-gateway/policy.js +1 -45
- package/dist/runtime/harness/tool-gateway/validation.js +1 -176
- package/dist/runtime/harness/tool-schema.js +1 -3
- package/dist/runtime/harness.js +3 -1490
- package/dist/runtime/index.js +1 -3
- package/dist/runtime/layout/runtime-layout.js +1 -31
- package/dist/runtime/maintenance/checkpoint-maintenance.js +2 -178
- package/dist/runtime/maintenance/file-checkpoint-saver.js +1 -106
- package/dist/runtime/maintenance/runtime-record-maintenance.js +2 -169
- package/dist/runtime/maintenance/sqlite-checkpoint-saver.js +4 -289
- package/dist/runtime/parsing/output-content.js +10 -550
- package/dist/runtime/parsing/output-parsing.js +1 -4
- package/dist/runtime/parsing/output-recovery.js +3 -213
- package/dist/runtime/parsing/output-tool-args.js +7 -663
- package/dist/runtime/parsing/stream-event-parsing.js +3 -362
- package/dist/runtime/prompts/runtime-prompts.js +4 -73
- package/dist/runtime/scheduling/system-schedule-manager.js +11 -532
- package/dist/runtime/skills/skill-metadata.js +1 -197
- package/dist/runtime/startup-tracing.js +2 -37
- package/dist/runtime/support/compiled-binding.js +1 -290
- package/dist/runtime/support/embedding-models.js +1 -118
- package/dist/runtime/support/harness-support.js +5 -137
- package/dist/runtime/support/llamaindex.js +1 -108
- package/dist/runtime/support/runtime-adapter-options.js +1 -29
- package/dist/runtime/support/runtime-factories.js +1 -51
- package/dist/runtime/support/vector-stores.js +9 -270
- package/dist/scaffold/init-project.js +54 -233
- package/dist/tooling/extensions.js +1 -311
- package/dist/tooling/module-loader.js +1 -55
- package/dist/tools.js +1 -176
- package/dist/utils/agent-display.js +1 -18
- package/dist/utils/bundled-text.js +4 -39
- package/dist/utils/compiled-binding.js +1 -33
- package/dist/utils/fs.js +2 -45
- package/dist/utils/id.js +1 -9
- package/dist/utils/message-content.js +1 -30
- package/dist/utils/object.js +1 -6
- package/dist/workspace/agent-binding-compiler.js +3 -613
- package/dist/workspace/compile.js +1 -472
- package/dist/workspace/framework-contract-validation.js +2 -322
- package/dist/workspace/index.js +1 -1
- package/dist/workspace/object-loader-paths.js +1 -71
- package/dist/workspace/object-loader-readers.js +1 -187
- package/dist/workspace/object-loader.js +1 -754
- package/dist/workspace/resource-compilers.js +1 -374
- package/dist/workspace/support/agent-capabilities.js +1 -37
- package/dist/workspace/support/agent-execution-config.js +1 -44
- package/dist/workspace/support/discovery.js +1 -147
- package/dist/workspace/support/source-collectors.js +1 -30
- package/dist/workspace/support/source-protocols.js +2 -192
- package/dist/workspace/support/workspace-ref-utils.js +1 -362
- package/dist/workspace/tool-hydration.js +1 -280
- package/dist/workspace/validate.js +1 -99
- package/dist/workspace/yaml-object-reader.js +1 -285
- package/package.json +7 -3
|
@@ -1,112 +1,13 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { mkdir, rm } from "node:fs/promises";
|
|
3
|
-
import { createClient } from "@libsql/client";
|
|
4
|
-
import { fileExists, readJson, writeJson } from "../utils/fs.js";
|
|
5
|
-
import { resolveRuntimeRoot, resolveRuntimeSqlitePath } from "../runtime/layout/runtime-layout.js";
|
|
6
|
-
import { asBoolean, asNullableString, asRow, asString, buildWhereClause, executeWithBusyRetry, nowIso, parseJson, throwWrappedRuntimeSqliteError, toSqliteUrl, } from "./sqlite-runtime.js";
|
|
7
|
-
import { SqliteRequestContextStore } from "./sqlite-request-context-store.js";
|
|
8
|
-
import { SqliteRequestQueueStore } from "./sqlite-request-queue-store.js";
|
|
9
|
-
const RUNTIME_SQLITE_SCHEMA_VERSION = 7;
|
|
10
|
-
const RUNTIME_SQLITE_SCHEMA_FAMILY = "agent-harness-runtime";
|
|
11
|
-
const ACTIVE_REQUEST_STATES = new Set([
|
|
12
|
-
"queued",
|
|
13
|
-
"claimed",
|
|
14
|
-
"running",
|
|
15
|
-
"waiting_for_approval",
|
|
16
|
-
"resuming",
|
|
17
|
-
"cancelling",
|
|
18
|
-
]);
|
|
19
|
-
async function selectProtectedSessionIds(dbPath) {
|
|
20
|
-
if (!(await fileExists(dbPath))) {
|
|
21
|
-
return [];
|
|
22
|
-
}
|
|
23
|
-
const client = createClient({ url: toSqliteUrl(dbPath) });
|
|
24
|
-
const sql = `SELECT DISTINCT session_id
|
|
1
|
+
import E from"node:path";import{mkdir as c,rm as g}from"node:fs/promises";import{createClient as h}from"@libsql/client";import{fileExists as I,readJson as C,writeJson as y}from"../utils/fs.js";import{resolveRuntimeRoot as p,resolveRuntimeSqlitePath as X}from"../runtime/layout/runtime-layout.js";import{asBoolean as A,asNullableString as r,asRow as q,asString as i,buildWhereClause as N,executeWithBusyRetry as m,nowIso as S,parseJson as _,throwWrappedRuntimeSqliteError as l,toSqliteUrl as w}from"./sqlite-runtime.js";import{SqliteRequestContextStore as x}from"./sqlite-request-context-store.js";import{SqliteRequestQueueStore as U}from"./sqlite-request-queue-store.js";const o=7,L="agent-harness-runtime",v=new Set(["queued","claimed","running","waiting_for_approval","resuming","cancelling"]);async function f(T){if(!await I(T))return[];const e=h({url:w(T)}),t=`SELECT DISTINCT session_id
|
|
25
2
|
FROM requests
|
|
26
3
|
WHERE checkpoint_ref IS NOT NULL
|
|
27
4
|
AND checkpoint_ref != ''
|
|
28
|
-
AND (resumable = 1 OR state NOT IN ('completed', 'failed'))`;
|
|
29
|
-
try {
|
|
30
|
-
const result = await client.execute(sql);
|
|
31
|
-
return result.rows.map((row) => asString(asRow(row).session_id)).filter((value) => value.length > 0);
|
|
32
|
-
}
|
|
33
|
-
catch (error) {
|
|
34
|
-
throwWrappedRuntimeSqliteError(dbPath, sql, error);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
export async function listProtectedCheckpointSessionIds(dbPath) {
|
|
38
|
-
return new Set(await selectProtectedSessionIds(dbPath));
|
|
39
|
-
}
|
|
40
|
-
export class SqlitePersistence {
|
|
41
|
-
runtimeRoot;
|
|
42
|
-
dbPath;
|
|
43
|
-
requestContextStore;
|
|
44
|
-
requestQueueStore;
|
|
45
|
-
client = null;
|
|
46
|
-
initialized = false;
|
|
47
|
-
initialization = null;
|
|
48
|
-
constructor(runtimeRoot, dbFile = "runtime.sqlite") {
|
|
49
|
-
this.runtimeRoot = runtimeRoot;
|
|
50
|
-
this.dbPath = dbFile === "runtime.sqlite"
|
|
51
|
-
? resolveRuntimeSqlitePath(runtimeRoot)
|
|
52
|
-
: path.join(resolveRuntimeRoot(runtimeRoot), dbFile);
|
|
53
|
-
this.requestContextStore = new SqliteRequestContextStore({
|
|
54
|
-
execute: (sql, args) => this.execute(sql, args),
|
|
55
|
-
selectOne: (sql, args) => this.selectOne(sql, args),
|
|
56
|
-
selectAll: (sql, args) => this.selectAll(sql, args),
|
|
57
|
-
});
|
|
58
|
-
this.requestQueueStore = new SqliteRequestQueueStore({
|
|
59
|
-
execute: (sql, args) => this.execute(sql, args),
|
|
60
|
-
selectOne: (sql, args) => this.selectOne(sql, args),
|
|
61
|
-
selectAll: (sql, args) => this.selectAll(sql, args),
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
async getClient() {
|
|
65
|
-
if (!this.client) {
|
|
66
|
-
await mkdir(path.dirname(this.dbPath), { recursive: true });
|
|
67
|
-
this.client = createClient({ url: toSqliteUrl(this.dbPath) });
|
|
68
|
-
}
|
|
69
|
-
return this.client;
|
|
70
|
-
}
|
|
71
|
-
async rawExecute(sql, args) {
|
|
72
|
-
const client = await this.getClient();
|
|
73
|
-
await executeWithBusyRetry(client, this.dbPath, sql, args, async () => {
|
|
74
|
-
if (args) {
|
|
75
|
-
await client.execute(sql, args);
|
|
76
|
-
return;
|
|
77
|
-
}
|
|
78
|
-
await client.execute(sql);
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
async rawSelectAll(sql, args) {
|
|
82
|
-
const client = await this.getClient();
|
|
83
|
-
return executeWithBusyRetry(client, this.dbPath, sql, args, async () => {
|
|
84
|
-
const result = args ? await client.execute(sql, args) : await client.execute(sql);
|
|
85
|
-
return result.rows.map((row) => asRow(row));
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
async ensureInitialized() {
|
|
89
|
-
if (this.initialized) {
|
|
90
|
-
return;
|
|
91
|
-
}
|
|
92
|
-
if (this.initialization) {
|
|
93
|
-
await this.initialization;
|
|
94
|
-
return;
|
|
95
|
-
}
|
|
96
|
-
this.initialization = (async () => {
|
|
97
|
-
await mkdir(resolveRuntimeRoot(this.runtimeRoot), { recursive: true });
|
|
98
|
-
await this.getClient();
|
|
99
|
-
await this.rawExecute("PRAGMA journal_mode=WAL");
|
|
100
|
-
await this.rawExecute("PRAGMA foreign_keys=ON");
|
|
101
|
-
await this.rawExecute("PRAGMA busy_timeout=5000");
|
|
102
|
-
await this.rawExecute(`
|
|
5
|
+
AND (resumable = 1 OR state NOT IN ('completed', 'failed'))`;try{return(await e.execute(t)).rows.map(a=>i(q(a).session_id)).filter(a=>a.length>0)}catch(s){l(T,t,s)}}async function W(T){return new Set(await f(T))}class H{runtimeRoot;dbPath;requestContextStore;requestQueueStore;client=null;initialized=!1;initialization=null;constructor(e,t="runtime.sqlite"){this.runtimeRoot=e,this.dbPath=t==="runtime.sqlite"?X(e):E.join(p(e),t),this.requestContextStore=new x({execute:(s,a)=>this.execute(s,a),selectOne:(s,a)=>this.selectOne(s,a),selectAll:(s,a)=>this.selectAll(s,a)}),this.requestQueueStore=new U({execute:(s,a)=>this.execute(s,a),selectOne:(s,a)=>this.selectOne(s,a),selectAll:(s,a)=>this.selectAll(s,a)})}async getClient(){return this.client||(await c(E.dirname(this.dbPath),{recursive:!0}),this.client=h({url:w(this.dbPath)})),this.client}async rawExecute(e,t){const s=await this.getClient();await m(s,this.dbPath,e,t,async()=>{if(t){await s.execute(e,t);return}await s.execute(e)})}async rawSelectAll(e,t){const s=await this.getClient();return m(s,this.dbPath,e,t,async()=>(t?await s.execute(e,t):await s.execute(e)).rows.map(n=>q(n)))}async ensureInitialized(){if(!this.initialized){if(this.initialization){await this.initialization;return}this.initialization=(async()=>{await c(p(this.runtimeRoot),{recursive:!0}),await this.getClient(),await this.rawExecute("PRAGMA journal_mode=WAL"),await this.rawExecute("PRAGMA foreign_keys=ON"),await this.rawExecute("PRAGMA busy_timeout=5000"),await this.rawExecute(`
|
|
103
6
|
CREATE TABLE IF NOT EXISTS runtime_metadata (
|
|
104
7
|
key TEXT PRIMARY KEY,
|
|
105
8
|
value TEXT NOT NULL
|
|
106
9
|
)
|
|
107
|
-
`)
|
|
108
|
-
await this.ensureSchemaMetadata();
|
|
109
|
-
await this.rawExecute(`
|
|
10
|
+
`),await this.ensureSchemaMetadata(),await this.rawExecute(`
|
|
110
11
|
CREATE TABLE IF NOT EXISTS sessions (
|
|
111
12
|
session_id TEXT PRIMARY KEY,
|
|
112
13
|
workspace_id TEXT NOT NULL,
|
|
@@ -116,9 +17,7 @@ export class SqlitePersistence {
|
|
|
116
17
|
created_at TEXT NOT NULL,
|
|
117
18
|
updated_at TEXT NOT NULL
|
|
118
19
|
)
|
|
119
|
-
`)
|
|
120
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS sessions_updated_idx ON sessions(updated_at DESC)");
|
|
121
|
-
await this.rawExecute(`
|
|
20
|
+
`),await this.rawExecute("CREATE INDEX IF NOT EXISTS sessions_updated_idx ON sessions(updated_at DESC)"),await this.rawExecute(`
|
|
122
21
|
CREATE TABLE IF NOT EXISTS requests (
|
|
123
22
|
request_id TEXT PRIMARY KEY,
|
|
124
23
|
session_id TEXT NOT NULL,
|
|
@@ -136,8 +35,7 @@ export class SqlitePersistence {
|
|
|
136
35
|
checkpoint_ref TEXT,
|
|
137
36
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id)
|
|
138
37
|
)
|
|
139
|
-
`)
|
|
140
|
-
await this.rawExecute(`
|
|
38
|
+
`),await this.rawExecute(`
|
|
141
39
|
CREATE TABLE IF NOT EXISTS request_inspection (
|
|
142
40
|
request_id TEXT PRIMARY KEY,
|
|
143
41
|
session_id TEXT NOT NULL,
|
|
@@ -151,8 +49,7 @@ export class SqlitePersistence {
|
|
|
151
49
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
152
50
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
153
51
|
)
|
|
154
|
-
`)
|
|
155
|
-
await this.rawExecute(`
|
|
52
|
+
`),await this.rawExecute(`
|
|
156
53
|
CREATE TABLE IF NOT EXISTS request_trace_items (
|
|
157
54
|
trace_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
158
55
|
request_id TEXT NOT NULL,
|
|
@@ -162,15 +59,7 @@ export class SqlitePersistence {
|
|
|
162
59
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
163
60
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
164
61
|
)
|
|
165
|
-
`)
|
|
166
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_thread_updated_idx ON requests(session_id, updated_at DESC)");
|
|
167
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_thread_created_idx ON requests(session_id, created_at DESC)");
|
|
168
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_updated_idx ON requests(updated_at DESC)");
|
|
169
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_state_updated_idx ON requests(state, updated_at DESC)");
|
|
170
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_agent_updated_idx ON requests(agent_id, updated_at DESC)");
|
|
171
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS request_inspection_thread_activity_idx ON request_inspection(session_id, last_activity_at DESC)");
|
|
172
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS request_trace_items_thread_run_trace_idx ON request_trace_items(session_id, request_id, trace_id)");
|
|
173
|
-
await this.rawExecute(`
|
|
62
|
+
`),await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_thread_updated_idx ON requests(session_id, updated_at DESC)"),await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_thread_created_idx ON requests(session_id, created_at DESC)"),await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_updated_idx ON requests(updated_at DESC)"),await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_state_updated_idx ON requests(state, updated_at DESC)"),await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_agent_updated_idx ON requests(agent_id, updated_at DESC)"),await this.rawExecute("CREATE INDEX IF NOT EXISTS request_inspection_thread_activity_idx ON request_inspection(session_id, last_activity_at DESC)"),await this.rawExecute("CREATE INDEX IF NOT EXISTS request_trace_items_thread_run_trace_idx ON request_trace_items(session_id, request_id, trace_id)"),await this.rawExecute(`
|
|
174
63
|
CREATE TABLE IF NOT EXISTS session_messages (
|
|
175
64
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
176
65
|
session_id TEXT NOT NULL,
|
|
@@ -180,9 +69,7 @@ export class SqlitePersistence {
|
|
|
180
69
|
created_at TEXT NOT NULL,
|
|
181
70
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id)
|
|
182
71
|
)
|
|
183
|
-
`)
|
|
184
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS session_messages_thread_created_idx ON session_messages(session_id, created_at, id)");
|
|
185
|
-
await this.rawExecute(`
|
|
72
|
+
`),await this.rawExecute("CREATE INDEX IF NOT EXISTS session_messages_thread_created_idx ON session_messages(session_id, created_at, id)"),await this.rawExecute(`
|
|
186
73
|
CREATE TABLE IF NOT EXISTS events (
|
|
187
74
|
session_id TEXT NOT NULL,
|
|
188
75
|
request_id TEXT NOT NULL,
|
|
@@ -193,8 +80,7 @@ export class SqlitePersistence {
|
|
|
193
80
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
194
81
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
195
82
|
)
|
|
196
|
-
`)
|
|
197
|
-
await this.rawExecute(`
|
|
83
|
+
`),await this.rawExecute(`
|
|
198
84
|
CREATE TABLE IF NOT EXISTS approvals (
|
|
199
85
|
approval_id TEXT PRIMARY KEY,
|
|
200
86
|
pending_action_id TEXT NOT NULL,
|
|
@@ -212,10 +98,7 @@ export class SqlitePersistence {
|
|
|
212
98
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
213
99
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
214
100
|
)
|
|
215
|
-
`)
|
|
216
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS approvals_thread_request_idx ON approvals(session_id, request_id)");
|
|
217
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS approvals_status_idx ON approvals(status, requested_at DESC)");
|
|
218
|
-
await this.rawExecute(`
|
|
101
|
+
`),await this.rawExecute("CREATE INDEX IF NOT EXISTS approvals_thread_request_idx ON approvals(session_id, request_id)"),await this.rawExecute("CREATE INDEX IF NOT EXISTS approvals_status_idx ON approvals(status, requested_at DESC)"),await this.rawExecute(`
|
|
219
102
|
CREATE TABLE IF NOT EXISTS request_inputs (
|
|
220
103
|
request_id TEXT PRIMARY KEY,
|
|
221
104
|
session_id TEXT NOT NULL,
|
|
@@ -224,8 +107,7 @@ export class SqlitePersistence {
|
|
|
224
107
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
225
108
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
226
109
|
)
|
|
227
|
-
`)
|
|
228
|
-
await this.rawExecute(`
|
|
110
|
+
`),await this.rawExecute(`
|
|
229
111
|
CREATE TABLE IF NOT EXISTS recovery_intents (
|
|
230
112
|
request_id TEXT PRIMARY KEY,
|
|
231
113
|
session_id TEXT NOT NULL,
|
|
@@ -234,8 +116,7 @@ export class SqlitePersistence {
|
|
|
234
116
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
235
117
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
236
118
|
)
|
|
237
|
-
`)
|
|
238
|
-
await this.rawExecute(`
|
|
119
|
+
`),await this.rawExecute(`
|
|
239
120
|
CREATE TABLE IF NOT EXISTS request_queue (
|
|
240
121
|
request_id TEXT PRIMARY KEY,
|
|
241
122
|
session_id TEXT NOT NULL,
|
|
@@ -251,10 +132,7 @@ export class SqlitePersistence {
|
|
|
251
132
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
252
133
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
253
134
|
)
|
|
254
|
-
`)
|
|
255
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS request_queue_available_idx ON request_queue(available_at, priority DESC, enqueued_at ASC)");
|
|
256
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS request_queue_claim_idx ON request_queue(claimed_by, lease_expires_at)");
|
|
257
|
-
await this.rawExecute(`
|
|
135
|
+
`),await this.rawExecute("CREATE INDEX IF NOT EXISTS request_queue_available_idx ON request_queue(available_at, priority DESC, enqueued_at ASC)"),await this.rawExecute("CREATE INDEX IF NOT EXISTS request_queue_claim_idx ON request_queue(claimed_by, lease_expires_at)"),await this.rawExecute(`
|
|
258
136
|
CREATE TABLE IF NOT EXISTS request_plan_state (
|
|
259
137
|
request_id TEXT PRIMARY KEY,
|
|
260
138
|
session_id TEXT NOT NULL,
|
|
@@ -264,9 +142,7 @@ export class SqlitePersistence {
|
|
|
264
142
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
265
143
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
266
144
|
)
|
|
267
|
-
`)
|
|
268
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS request_plan_state_thread_updated_idx ON request_plan_state(session_id, updated_at DESC)");
|
|
269
|
-
await this.rawExecute(`
|
|
145
|
+
`),await this.rawExecute("CREATE INDEX IF NOT EXISTS request_plan_state_thread_updated_idx ON request_plan_state(session_id, updated_at DESC)"),await this.rawExecute(`
|
|
270
146
|
CREATE TABLE IF NOT EXISTS request_control (
|
|
271
147
|
request_id TEXT PRIMARY KEY,
|
|
272
148
|
cancel_requested INTEGER NOT NULL DEFAULT 0,
|
|
@@ -277,8 +153,7 @@ export class SqlitePersistence {
|
|
|
277
153
|
worker_started_at TEXT,
|
|
278
154
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
279
155
|
)
|
|
280
|
-
`)
|
|
281
|
-
await this.rawExecute(`
|
|
156
|
+
`),await this.rawExecute(`
|
|
282
157
|
CREATE TABLE IF NOT EXISTS artifacts (
|
|
283
158
|
artifact_id TEXT PRIMARY KEY,
|
|
284
159
|
session_id TEXT NOT NULL,
|
|
@@ -289,164 +164,10 @@ export class SqlitePersistence {
|
|
|
289
164
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
290
165
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
291
166
|
)
|
|
292
|
-
`);
|
|
293
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS artifacts_thread_request_idx ON artifacts(session_id, request_id, created_at)");
|
|
294
|
-
this.initialized = true;
|
|
295
|
-
})().finally(() => {
|
|
296
|
-
this.initialization = null;
|
|
297
|
-
});
|
|
298
|
-
await this.initialization;
|
|
299
|
-
}
|
|
300
|
-
sessionDir(sessionId) {
|
|
301
|
-
return path.join(this.runtimeRoot, "sessions", sessionId);
|
|
302
|
-
}
|
|
303
|
-
requestDir(sessionId, requestId) {
|
|
304
|
-
return path.join(this.sessionDir(sessionId), "requests", requestId);
|
|
305
|
-
}
|
|
306
|
-
async execute(sql, args) {
|
|
307
|
-
await this.ensureInitialized();
|
|
308
|
-
const client = await this.getClient();
|
|
309
|
-
try {
|
|
310
|
-
if (args) {
|
|
311
|
-
await client.execute(sql, args);
|
|
312
|
-
return;
|
|
313
|
-
}
|
|
314
|
-
await client.execute(sql);
|
|
315
|
-
}
|
|
316
|
-
catch (error) {
|
|
317
|
-
throwWrappedRuntimeSqliteError(this.dbPath, sql, error);
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
async executeTransaction(steps) {
|
|
321
|
-
await this.ensureInitialized();
|
|
322
|
-
const client = await this.getClient();
|
|
323
|
-
let lastSql = "BEGIN IMMEDIATE";
|
|
324
|
-
try {
|
|
325
|
-
await client.execute("BEGIN IMMEDIATE");
|
|
326
|
-
for (const step of steps) {
|
|
327
|
-
lastSql = step.sql;
|
|
328
|
-
if (step.args) {
|
|
329
|
-
await client.execute(step.sql, step.args);
|
|
330
|
-
}
|
|
331
|
-
else {
|
|
332
|
-
await client.execute(step.sql);
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
lastSql = "COMMIT";
|
|
336
|
-
await client.execute("COMMIT");
|
|
337
|
-
}
|
|
338
|
-
catch (error) {
|
|
339
|
-
try {
|
|
340
|
-
await client.execute("ROLLBACK");
|
|
341
|
-
}
|
|
342
|
-
catch {
|
|
343
|
-
// Ignore rollback failures and preserve the original error.
|
|
344
|
-
}
|
|
345
|
-
throwWrappedRuntimeSqliteError(this.dbPath, lastSql, error);
|
|
346
|
-
}
|
|
347
|
-
}
|
|
348
|
-
async selectOne(sql, args) {
|
|
349
|
-
await this.ensureInitialized();
|
|
350
|
-
const client = await this.getClient();
|
|
351
|
-
try {
|
|
352
|
-
const result = args ? await client.execute(sql, args) : await client.execute(sql);
|
|
353
|
-
const first = result.rows[0];
|
|
354
|
-
return first ? asRow(first) : null;
|
|
355
|
-
}
|
|
356
|
-
catch (error) {
|
|
357
|
-
throwWrappedRuntimeSqliteError(this.dbPath, sql, error);
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
async selectAll(sql, args) {
|
|
361
|
-
await this.ensureInitialized();
|
|
362
|
-
const client = await this.getClient();
|
|
363
|
-
try {
|
|
364
|
-
const result = args ? await client.execute(sql, args) : await client.execute(sql);
|
|
365
|
-
return result.rows.map((row) => asRow(row));
|
|
366
|
-
}
|
|
367
|
-
catch (error) {
|
|
368
|
-
throwWrappedRuntimeSqliteError(this.dbPath, sql, error);
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
mapSessionSummary(row) {
|
|
372
|
-
return {
|
|
373
|
-
agentId: asString(row.entry_agent_id),
|
|
374
|
-
sessionId: asString(row.session_id),
|
|
375
|
-
latestRequestId: asString(row.latest_request_id),
|
|
376
|
-
createdAt: asString(row.created_at),
|
|
377
|
-
updatedAt: asString(row.updated_at),
|
|
378
|
-
status: asString(row.status),
|
|
379
|
-
currentAgentId: asNullableString(row.current_agent_id) ?? undefined,
|
|
380
|
-
};
|
|
381
|
-
}
|
|
382
|
-
mapRequestSummary(row) {
|
|
383
|
-
const runtimeSnapshot = row.runtime_snapshot_json ? parseJson(row.runtime_snapshot_json) : null;
|
|
384
|
-
return {
|
|
385
|
-
requestId: asString(row.request_id),
|
|
386
|
-
sessionId: asString(row.session_id),
|
|
387
|
-
agentId: asString(row.agent_id),
|
|
388
|
-
...(asNullableString(row.parent_request_id) ? { parentRequestId: asNullableString(row.parent_request_id) } : {}),
|
|
389
|
-
executionMode: asString(row.execution_mode),
|
|
390
|
-
adapterKind: asNullableString(row.adapter_kind) ?? undefined,
|
|
391
|
-
createdAt: asString(row.created_at),
|
|
392
|
-
updatedAt: asString(row.updated_at),
|
|
393
|
-
state: asString(row.state),
|
|
394
|
-
checkpointRef: asNullableString(row.checkpoint_ref),
|
|
395
|
-
resumable: asBoolean(row.resumable),
|
|
396
|
-
startedAt: asNullableString(row.started_at) ?? asString(row.created_at),
|
|
397
|
-
endedAt: asNullableString(row.ended_at) ?? undefined,
|
|
398
|
-
lastActivityAt: asNullableString(row.last_activity_at) ?? asString(row.updated_at),
|
|
399
|
-
currentAgentId: asNullableString(row.current_agent_id) ?? undefined,
|
|
400
|
-
delegationChain: row.delegation_chain_json ? parseJson(row.delegation_chain_json) : [asString(row.agent_id)],
|
|
401
|
-
...(runtimeSnapshot ? { runtimeSnapshot } : {}),
|
|
402
|
-
};
|
|
403
|
-
}
|
|
404
|
-
async listRequestSnapshots(requestIds) {
|
|
405
|
-
if (requestIds.length === 0) {
|
|
406
|
-
return new Map();
|
|
407
|
-
}
|
|
408
|
-
const placeholders = requestIds.map(() => "?").join(", ");
|
|
409
|
-
const rows = await this.selectAll(`SELECT request_id, runtime_snapshot_json
|
|
167
|
+
`),await this.rawExecute("CREATE INDEX IF NOT EXISTS artifacts_thread_request_idx ON artifacts(session_id, request_id, created_at)"),this.initialized=!0})().finally(()=>{this.initialization=null}),await this.initialization}}sessionDir(e){return E.join(this.runtimeRoot,"sessions",e)}requestDir(e,t){return E.join(this.sessionDir(e),"requests",t)}async execute(e,t){await this.ensureInitialized();const s=await this.getClient();try{if(t){await s.execute(e,t);return}await s.execute(e)}catch(a){l(this.dbPath,e,a)}}async executeTransaction(e){await this.ensureInitialized();const t=await this.getClient();let s="BEGIN IMMEDIATE";try{await t.execute("BEGIN IMMEDIATE");for(const a of e)s=a.sql,a.args?await t.execute(a.sql,a.args):await t.execute(a.sql);s="COMMIT",await t.execute("COMMIT")}catch(a){try{await t.execute("ROLLBACK")}catch{}l(this.dbPath,s,a)}}async selectOne(e,t){await this.ensureInitialized();const s=await this.getClient();try{const n=(t?await s.execute(e,t):await s.execute(e)).rows[0];return n?q(n):null}catch(a){l(this.dbPath,e,a)}}async selectAll(e,t){await this.ensureInitialized();const s=await this.getClient();try{return(t?await s.execute(e,t):await s.execute(e)).rows.map(n=>q(n))}catch(a){l(this.dbPath,e,a)}}mapSessionSummary(e){return{agentId:i(e.entry_agent_id),sessionId:i(e.session_id),latestRequestId:i(e.latest_request_id),createdAt:i(e.created_at),updatedAt:i(e.updated_at),status:i(e.status),currentAgentId:r(e.current_agent_id)??void 0}}mapRequestSummary(e){const t=e.runtime_snapshot_json?_(e.runtime_snapshot_json):null;return{requestId:i(e.request_id),sessionId:i(e.session_id),agentId:i(e.agent_id),...r(e.parent_request_id)?{parentRequestId:r(e.parent_request_id)}:{},executionMode:i(e.execution_mode),adapterKind:r(e.adapter_kind)??void 0,createdAt:i(e.created_at),updatedAt:i(e.updated_at),state:i(e.state),checkpointRef:r(e.checkpoint_ref),resumable:A(e.resumable),startedAt:r(e.started_at)??i(e.created_at),endedAt:r(e.ended_at)??void 0,lastActivityAt:r(e.last_activity_at)??i(e.updated_at),currentAgentId:r(e.current_agent_id)??void 0,delegationChain:e.delegation_chain_json?_(e.delegation_chain_json):[i(e.agent_id)],...t?{runtimeSnapshot:t}:{}}}async listRequestSnapshots(e){if(e.length===0)return new Map;const t=e.map(()=>"?").join(", "),s=await this.selectAll(`SELECT request_id, runtime_snapshot_json
|
|
410
168
|
FROM request_inspection
|
|
411
|
-
WHERE request_id IN (${
|
|
412
|
-
AND runtime_snapshot_json IS NOT NULL`,
|
|
413
|
-
return new Map(rows.map((row) => [asString(row.request_id), parseJson(row.runtime_snapshot_json)]));
|
|
414
|
-
}
|
|
415
|
-
mapApproval(row) {
|
|
416
|
-
return {
|
|
417
|
-
approvalId: asString(row.approval_id),
|
|
418
|
-
pendingActionId: asString(row.pending_action_id),
|
|
419
|
-
sessionId: asString(row.session_id),
|
|
420
|
-
requestId: asString(row.request_id),
|
|
421
|
-
toolCallId: asString(row.tool_call_id),
|
|
422
|
-
toolName: asString(row.tool_name),
|
|
423
|
-
status: asString(row.status),
|
|
424
|
-
requestedAt: asString(row.requested_at),
|
|
425
|
-
resolvedAt: asNullableString(row.resolved_at),
|
|
426
|
-
allowedDecisions: parseJson(row.allowed_decisions_json),
|
|
427
|
-
inputPreview: parseJson(row.input_preview_json),
|
|
428
|
-
checkpointRef: asString(row.checkpoint_ref),
|
|
429
|
-
eventRefs: parseJson(row.event_refs_json),
|
|
430
|
-
};
|
|
431
|
-
}
|
|
432
|
-
async initialize() {
|
|
433
|
-
await this.ensureInitialized();
|
|
434
|
-
}
|
|
435
|
-
async ensureSchemaMetadata() {
|
|
436
|
-
const rows = await this.rawSelectAll("SELECT key, value FROM runtime_metadata WHERE key IN ('schema_family', 'schema_version')");
|
|
437
|
-
const metadata = new Map(rows.map((row) => [asString(row.key), asString(row.value)]));
|
|
438
|
-
const family = metadata.get("schema_family");
|
|
439
|
-
const version = metadata.get("schema_version");
|
|
440
|
-
if (!family && !version) {
|
|
441
|
-
await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)", ["schema_family", RUNTIME_SQLITE_SCHEMA_FAMILY]);
|
|
442
|
-
await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)", ["schema_version", String(RUNTIME_SQLITE_SCHEMA_VERSION)]);
|
|
443
|
-
return;
|
|
444
|
-
}
|
|
445
|
-
if (family !== RUNTIME_SQLITE_SCHEMA_FAMILY) {
|
|
446
|
-
throw new Error(`Unsupported runtime sqlite schema family ${JSON.stringify(family)} in ${this.dbPath}. Expected ${JSON.stringify(RUNTIME_SQLITE_SCHEMA_FAMILY)}.`);
|
|
447
|
-
}
|
|
448
|
-
if (version === "1" || version === "2") {
|
|
449
|
-
await this.rawExecute(`
|
|
169
|
+
WHERE request_id IN (${t})
|
|
170
|
+
AND runtime_snapshot_json IS NOT NULL`,e);return new Map(s.map(a=>[i(a.request_id),_(a.runtime_snapshot_json)]))}mapApproval(e){return{approvalId:i(e.approval_id),pendingActionId:i(e.pending_action_id),sessionId:i(e.session_id),requestId:i(e.request_id),toolCallId:i(e.tool_call_id),toolName:i(e.tool_name),status:i(e.status),requestedAt:i(e.requested_at),resolvedAt:r(e.resolved_at),allowedDecisions:_(e.allowed_decisions_json),inputPreview:_(e.input_preview_json),checkpointRef:i(e.checkpoint_ref),eventRefs:_(e.event_refs_json)}}async initialize(){await this.ensureInitialized()}async ensureSchemaMetadata(){const e=await this.rawSelectAll("SELECT key, value FROM runtime_metadata WHERE key IN ('schema_family', 'schema_version')"),t=new Map(e.map(n=>[i(n.key),i(n.value)])),s=t.get("schema_family"),a=t.get("schema_version");if(!s&&!a){await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)",["schema_family",L]),await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)",["schema_version",String(o)]);return}if(s!==L)throw new Error(`Unsupported runtime sqlite schema family ${JSON.stringify(s)} in ${this.dbPath}. Expected ${JSON.stringify(L)}.`);if(a==="1"||a==="2"){await this.rawExecute(`
|
|
450
171
|
CREATE TABLE IF NOT EXISTS request_inspection (
|
|
451
172
|
request_id TEXT PRIMARY KEY,
|
|
452
173
|
session_id TEXT NOT NULL,
|
|
@@ -460,31 +181,12 @@ export class SqlitePersistence {
|
|
|
460
181
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
461
182
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
462
183
|
)
|
|
463
|
-
`)
|
|
464
|
-
await this.rawExecute(`
|
|
184
|
+
`),await this.rawExecute(`
|
|
465
185
|
INSERT OR IGNORE INTO request_inspection
|
|
466
186
|
(request_id, session_id, started_at, ended_at, last_activity_at, current_agent_id, delegation_chain_json, runtime_snapshot_json, upstream_events_json)
|
|
467
187
|
SELECT request_id, session_id, created_at, NULL, updated_at, agent_id, json_array(agent_id), NULL, '[]'
|
|
468
188
|
FROM requests
|
|
469
|
-
`);
|
|
470
|
-
await this.rawExecute("ALTER TABLE requests ADD COLUMN parent_request_id TEXT");
|
|
471
|
-
await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)", ["schema_version", String(RUNTIME_SQLITE_SCHEMA_VERSION)]);
|
|
472
|
-
return;
|
|
473
|
-
}
|
|
474
|
-
if (version === "3") {
|
|
475
|
-
await this.rawExecute("ALTER TABLE request_inspection ADD COLUMN upstream_events_json TEXT NOT NULL DEFAULT '[]'");
|
|
476
|
-
await this.rawExecute("UPDATE request_inspection SET upstream_events_json = '[]' WHERE upstream_events_json IS NULL");
|
|
477
|
-
await this.rawExecute("ALTER TABLE requests ADD COLUMN parent_request_id TEXT");
|
|
478
|
-
await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)", ["schema_version", String(RUNTIME_SQLITE_SCHEMA_VERSION)]);
|
|
479
|
-
return;
|
|
480
|
-
}
|
|
481
|
-
if (version === "4") {
|
|
482
|
-
await this.rawExecute("ALTER TABLE requests ADD COLUMN parent_request_id TEXT");
|
|
483
|
-
await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)", ["schema_version", String(RUNTIME_SQLITE_SCHEMA_VERSION)]);
|
|
484
|
-
return;
|
|
485
|
-
}
|
|
486
|
-
if (version === "5") {
|
|
487
|
-
await this.rawExecute(`
|
|
189
|
+
`),await this.rawExecute("ALTER TABLE requests ADD COLUMN parent_request_id TEXT"),await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)",["schema_version",String(o)]);return}if(a==="3"){await this.rawExecute("ALTER TABLE request_inspection ADD COLUMN upstream_events_json TEXT NOT NULL DEFAULT '[]'"),await this.rawExecute("UPDATE request_inspection SET upstream_events_json = '[]' WHERE upstream_events_json IS NULL"),await this.rawExecute("ALTER TABLE requests ADD COLUMN parent_request_id TEXT"),await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)",["schema_version",String(o)]);return}if(a==="4"){await this.rawExecute("ALTER TABLE requests ADD COLUMN parent_request_id TEXT"),await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)",["schema_version",String(o)]);return}if(a==="5"){await this.rawExecute(`
|
|
488
190
|
CREATE TABLE IF NOT EXISTS request_trace_items (
|
|
489
191
|
trace_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
490
192
|
request_id TEXT NOT NULL,
|
|
@@ -494,14 +196,7 @@ export class SqlitePersistence {
|
|
|
494
196
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
495
197
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
496
198
|
)
|
|
497
|
-
`);
|
|
498
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_thread_created_idx ON requests(session_id, created_at DESC)");
|
|
499
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS request_trace_items_thread_run_trace_idx ON request_trace_items(session_id, request_id, trace_id)");
|
|
500
|
-
await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)", ["schema_version", String(RUNTIME_SQLITE_SCHEMA_VERSION)]);
|
|
501
|
-
return;
|
|
502
|
-
}
|
|
503
|
-
if (version === "6") {
|
|
504
|
-
await this.rawExecute(`
|
|
199
|
+
`),await this.rawExecute("CREATE INDEX IF NOT EXISTS requests_thread_created_idx ON requests(session_id, created_at DESC)"),await this.rawExecute("CREATE INDEX IF NOT EXISTS request_trace_items_thread_run_trace_idx ON request_trace_items(session_id, request_id, trace_id)"),await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)",["schema_version",String(o)]);return}if(a==="6"){await this.rawExecute(`
|
|
505
200
|
CREATE TABLE IF NOT EXISTS request_plan_state (
|
|
506
201
|
request_id TEXT PRIMARY KEY,
|
|
507
202
|
session_id TEXT NOT NULL,
|
|
@@ -511,185 +206,48 @@ export class SqlitePersistence {
|
|
|
511
206
|
FOREIGN KEY (session_id) REFERENCES sessions(session_id),
|
|
512
207
|
FOREIGN KEY (request_id) REFERENCES requests(request_id)
|
|
513
208
|
)
|
|
514
|
-
`);
|
|
515
|
-
await this.rawExecute("CREATE INDEX IF NOT EXISTS request_plan_state_thread_updated_idx ON request_plan_state(session_id, updated_at DESC)");
|
|
516
|
-
await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)", ["schema_version", String(RUNTIME_SQLITE_SCHEMA_VERSION)]);
|
|
517
|
-
return;
|
|
518
|
-
}
|
|
519
|
-
if (version !== String(RUNTIME_SQLITE_SCHEMA_VERSION)) {
|
|
520
|
-
throw new Error(`Unsupported runtime sqlite schema version ${JSON.stringify(version)} in ${this.dbPath}. Expected ${RUNTIME_SQLITE_SCHEMA_VERSION}.`);
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
async createSession(input) {
|
|
524
|
-
await mkdir(this.sessionDir(input.sessionId), { recursive: true });
|
|
525
|
-
await this.execute(`INSERT OR REPLACE INTO sessions
|
|
209
|
+
`),await this.rawExecute("CREATE INDEX IF NOT EXISTS request_plan_state_thread_updated_idx ON request_plan_state(session_id, updated_at DESC)"),await this.rawExecute("INSERT OR REPLACE INTO runtime_metadata (key, value) VALUES (?, ?)",["schema_version",String(o)]);return}if(a!==String(o))throw new Error(`Unsupported runtime sqlite schema version ${JSON.stringify(a)} in ${this.dbPath}. Expected ${o}.`)}async createSession(e){await c(this.sessionDir(e.sessionId),{recursive:!0}),await this.execute(`INSERT OR REPLACE INTO sessions
|
|
526
210
|
(session_id, workspace_id, entry_agent_id, status, latest_request_id, created_at, updated_at)
|
|
527
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
528
|
-
}
|
|
529
|
-
async bootstrapRequest(input) {
|
|
530
|
-
const parentRequestId = input.createSession ? null : (await this.getSessionMeta(input.sessionId))?.latestRequestId ?? null;
|
|
531
|
-
await mkdir(this.sessionDir(input.sessionId), { recursive: true });
|
|
532
|
-
await mkdir(path.join(this.requestDir(input.sessionId, input.requestId), "events"), { recursive: true });
|
|
533
|
-
const steps = [];
|
|
534
|
-
if (input.createSession) {
|
|
535
|
-
steps.push({
|
|
536
|
-
sql: `INSERT OR REPLACE INTO sessions
|
|
211
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,[e.sessionId,"default",e.agentId,e.status,e.requestId,e.createdAt,e.createdAt])}async bootstrapRequest(e){const t=e.createSession?null:(await this.getSessionMeta(e.sessionId))?.latestRequestId??null;await c(this.sessionDir(e.sessionId),{recursive:!0}),await c(E.join(this.requestDir(e.sessionId,e.requestId),"events"),{recursive:!0});const s=[];e.createSession?s.push({sql:`INSERT OR REPLACE INTO sessions
|
|
537
212
|
(session_id, workspace_id, entry_agent_id, status, latest_request_id, created_at, updated_at)
|
|
538
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
539
|
-
args: [input.sessionId, "default", input.agentId, input.status, input.requestId, input.createdAt, input.createdAt],
|
|
540
|
-
});
|
|
541
|
-
}
|
|
542
|
-
else {
|
|
543
|
-
steps.push({
|
|
544
|
-
sql: `UPDATE sessions
|
|
213
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,args:[e.sessionId,"default",e.agentId,e.status,e.requestId,e.createdAt,e.createdAt]}):s.push({sql:`UPDATE sessions
|
|
545
214
|
SET status = ?, latest_request_id = ?, updated_at = ?
|
|
546
|
-
WHERE session_id = ?`,
|
|
547
|
-
args: [input.status, input.requestId, input.createdAt, input.sessionId],
|
|
548
|
-
});
|
|
549
|
-
}
|
|
550
|
-
steps.push({
|
|
551
|
-
sql: `INSERT OR REPLACE INTO requests
|
|
215
|
+
WHERE session_id = ?`,args:[e.status,e.requestId,e.createdAt,e.sessionId]}),s.push({sql:`INSERT OR REPLACE INTO requests
|
|
552
216
|
(request_id, session_id, agent_id, parent_request_id, execution_mode, adapter_kind, created_at, updated_at, state, previous_state, state_entered_at, last_transition_at, resumable, checkpoint_ref)
|
|
553
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
554
|
-
args: [
|
|
555
|
-
input.requestId,
|
|
556
|
-
input.sessionId,
|
|
557
|
-
input.agentId,
|
|
558
|
-
parentRequestId,
|
|
559
|
-
input.executionMode,
|
|
560
|
-
input.adapterKind ?? input.executionMode ?? null,
|
|
561
|
-
input.createdAt,
|
|
562
|
-
input.createdAt,
|
|
563
|
-
"running",
|
|
564
|
-
null,
|
|
565
|
-
input.createdAt,
|
|
566
|
-
input.createdAt,
|
|
567
|
-
0,
|
|
568
|
-
null,
|
|
569
|
-
],
|
|
570
|
-
}, {
|
|
571
|
-
sql: `INSERT OR REPLACE INTO request_control
|
|
217
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,args:[e.requestId,e.sessionId,e.agentId,t,e.executionMode,e.adapterKind??e.executionMode??null,e.createdAt,e.createdAt,"running",null,e.createdAt,e.createdAt,0,null]},{sql:`INSERT OR REPLACE INTO request_control
|
|
572
218
|
(request_id, cancel_requested, cancel_reason, cancel_requested_at, heartbeat_at, worker_id, worker_started_at)
|
|
573
|
-
VALUES (?, 0, NULL, NULL, NULL, NULL, NULL)`,
|
|
574
|
-
args: [input.requestId],
|
|
575
|
-
}, {
|
|
576
|
-
sql: `INSERT OR REPLACE INTO request_inspection
|
|
219
|
+
VALUES (?, 0, NULL, NULL, NULL, NULL, NULL)`,args:[e.requestId]},{sql:`INSERT OR REPLACE INTO request_inspection
|
|
577
220
|
(request_id, session_id, started_at, ended_at, last_activity_at, current_agent_id, delegation_chain_json, runtime_snapshot_json, upstream_events_json)
|
|
578
|
-
VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?)`,
|
|
579
|
-
args: [
|
|
580
|
-
input.requestId,
|
|
581
|
-
input.sessionId,
|
|
582
|
-
input.startedAt ?? input.createdAt,
|
|
583
|
-
input.createdAt,
|
|
584
|
-
input.currentAgentId ?? input.agentId,
|
|
585
|
-
JSON.stringify(input.delegationChain ?? [input.currentAgentId ?? input.agentId]),
|
|
586
|
-
input.runtimeSnapshot ? JSON.stringify(input.runtimeSnapshot) : null,
|
|
587
|
-
"[]",
|
|
588
|
-
],
|
|
589
|
-
}, {
|
|
590
|
-
sql: `INSERT INTO session_messages
|
|
221
|
+
VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?)`,args:[e.requestId,e.sessionId,e.startedAt??e.createdAt,e.createdAt,e.currentAgentId??e.agentId,JSON.stringify(e.delegationChain??[e.currentAgentId??e.agentId]),e.runtimeSnapshot?JSON.stringify(e.runtimeSnapshot):null,"[]"]},{sql:`INSERT INTO session_messages
|
|
591
222
|
(session_id, role, content_json, request_id, created_at)
|
|
592
|
-
VALUES (?, ?, ?, ?, ?)`,
|
|
593
|
-
args: [
|
|
594
|
-
input.sessionId,
|
|
595
|
-
input.userMessage.role,
|
|
596
|
-
JSON.stringify(input.userMessage.content),
|
|
597
|
-
input.userMessage.requestId,
|
|
598
|
-
input.userMessage.createdAt,
|
|
599
|
-
],
|
|
600
|
-
}, {
|
|
601
|
-
sql: `INSERT OR REPLACE INTO request_inputs
|
|
223
|
+
VALUES (?, ?, ?, ?, ?)`,args:[e.sessionId,e.userMessage.role,JSON.stringify(e.userMessage.content),e.userMessage.requestId,e.userMessage.createdAt]},{sql:`INSERT OR REPLACE INTO request_inputs
|
|
602
224
|
(request_id, session_id, request_json, saved_at)
|
|
603
|
-
VALUES (?, ?, ?, ?)`,
|
|
604
|
-
args: [input.requestId, input.sessionId, JSON.stringify(input.requestInput), input.requestInput.savedAt],
|
|
605
|
-
});
|
|
606
|
-
await this.executeTransaction(steps);
|
|
607
|
-
}
|
|
608
|
-
async createRequest(input) {
|
|
609
|
-
const sessionMeta = await this.getSessionMeta(input.sessionId);
|
|
610
|
-
const parentRequestId = sessionMeta?.latestRequestId === input.requestId
|
|
611
|
-
? null
|
|
612
|
-
: sessionMeta?.latestRequestId ?? null;
|
|
613
|
-
await mkdir(path.join(this.requestDir(input.sessionId, input.requestId), "events"), { recursive: true });
|
|
614
|
-
await this.execute(`INSERT OR REPLACE INTO requests
|
|
225
|
+
VALUES (?, ?, ?, ?)`,args:[e.requestId,e.sessionId,JSON.stringify(e.requestInput),e.requestInput.savedAt]}),await this.executeTransaction(s)}async createRequest(e){const t=await this.getSessionMeta(e.sessionId),s=t?.latestRequestId===e.requestId?null:t?.latestRequestId??null;await c(E.join(this.requestDir(e.sessionId,e.requestId),"events"),{recursive:!0}),await this.execute(`INSERT OR REPLACE INTO requests
|
|
615
226
|
(request_id, session_id, agent_id, parent_request_id, execution_mode, adapter_kind, created_at, updated_at, state, previous_state, state_entered_at, last_transition_at, resumable, checkpoint_ref)
|
|
616
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
617
|
-
input.requestId,
|
|
618
|
-
input.sessionId,
|
|
619
|
-
input.agentId,
|
|
620
|
-
parentRequestId,
|
|
621
|
-
input.executionMode,
|
|
622
|
-
input.adapterKind ?? input.executionMode ?? null,
|
|
623
|
-
input.createdAt,
|
|
624
|
-
input.createdAt,
|
|
625
|
-
"running",
|
|
626
|
-
null,
|
|
627
|
-
input.createdAt,
|
|
628
|
-
input.createdAt,
|
|
629
|
-
0,
|
|
630
|
-
null,
|
|
631
|
-
]);
|
|
632
|
-
await this.execute(`INSERT OR REPLACE INTO request_control
|
|
227
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.requestId,e.sessionId,e.agentId,s,e.executionMode,e.adapterKind??e.executionMode??null,e.createdAt,e.createdAt,"running",null,e.createdAt,e.createdAt,0,null]),await this.execute(`INSERT OR REPLACE INTO request_control
|
|
633
228
|
(request_id, cancel_requested, cancel_reason, cancel_requested_at, heartbeat_at, worker_id, worker_started_at)
|
|
634
|
-
VALUES (?, 0, NULL, NULL, NULL, NULL, NULL)`,
|
|
635
|
-
await this.execute(`INSERT OR REPLACE INTO request_inspection
|
|
229
|
+
VALUES (?, 0, NULL, NULL, NULL, NULL, NULL)`,[e.requestId]),await this.execute(`INSERT OR REPLACE INTO request_inspection
|
|
636
230
|
(request_id, session_id, started_at, ended_at, last_activity_at, current_agent_id, delegation_chain_json, runtime_snapshot_json, upstream_events_json)
|
|
637
|
-
VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?)`,
|
|
638
|
-
input.requestId,
|
|
639
|
-
input.sessionId,
|
|
640
|
-
input.startedAt ?? input.createdAt,
|
|
641
|
-
input.createdAt,
|
|
642
|
-
input.currentAgentId ?? input.agentId,
|
|
643
|
-
JSON.stringify(input.delegationChain ?? [input.currentAgentId ?? input.agentId]),
|
|
644
|
-
input.runtimeSnapshot ? JSON.stringify(input.runtimeSnapshot) : null,
|
|
645
|
-
"[]",
|
|
646
|
-
]);
|
|
647
|
-
await this.execute(`UPDATE sessions
|
|
231
|
+
VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?)`,[e.requestId,e.sessionId,e.startedAt??e.createdAt,e.createdAt,e.currentAgentId??e.agentId,JSON.stringify(e.delegationChain??[e.currentAgentId??e.agentId]),e.runtimeSnapshot?JSON.stringify(e.runtimeSnapshot):null,"[]"]),await this.execute(`UPDATE sessions
|
|
648
232
|
SET status = ?, latest_request_id = ?, updated_at = ?
|
|
649
|
-
WHERE session_id = ?`,
|
|
650
|
-
}
|
|
651
|
-
async setRequestState(sessionId, requestId, state, checkpointRef) {
|
|
652
|
-
const current = await this.getRequestLifecycle(sessionId, requestId);
|
|
653
|
-
const now = nowIso();
|
|
654
|
-
const nextCheckpointRef = checkpointRef === undefined ? current.checkpointRef : checkpointRef;
|
|
655
|
-
const resumable = state === "waiting_for_approval" ? 1 : 0;
|
|
656
|
-
await this.execute(`UPDATE requests
|
|
233
|
+
WHERE session_id = ?`,["running",e.requestId,e.createdAt,e.sessionId])}async setRequestState(e,t,s,a){const n=await this.getRequestLifecycle(e,t),u=S(),d=a===void 0?n.checkpointRef:a,R=s==="waiting_for_approval"?1:0;await this.execute(`UPDATE requests
|
|
657
234
|
SET state = ?, previous_state = ?, state_entered_at = ?, last_transition_at = ?, updated_at = ?, resumable = ?, checkpoint_ref = ?
|
|
658
|
-
WHERE request_id = ? AND session_id = ?`,
|
|
659
|
-
await this.execute(`UPDATE sessions
|
|
235
|
+
WHERE request_id = ? AND session_id = ?`,[s,n.state,u,u,u,R,d,t,e]),await this.execute(`UPDATE sessions
|
|
660
236
|
SET status = ?, latest_request_id = ?, updated_at = ?
|
|
661
|
-
WHERE session_id = ?`,
|
|
662
|
-
await this.execute(`UPDATE request_inspection
|
|
237
|
+
WHERE session_id = ?`,[s,t,u,e]),await this.execute(`UPDATE request_inspection
|
|
663
238
|
SET last_activity_at = ?, ended_at = CASE
|
|
664
239
|
WHEN ? IN ('completed', 'failed', 'cancelled') THEN ?
|
|
665
240
|
ELSE ended_at
|
|
666
241
|
END
|
|
667
|
-
WHERE request_id = ? AND session_id = ?`,
|
|
668
|
-
}
|
|
669
|
-
async appendEvent(event) {
|
|
670
|
-
await this.execute(`INSERT OR REPLACE INTO events
|
|
242
|
+
WHERE request_id = ? AND session_id = ?`,[u,s,u,t,e])}async appendEvent(e){await this.execute(`INSERT OR REPLACE INTO events
|
|
671
243
|
(session_id, request_id, sequence, event_json, created_at)
|
|
672
|
-
VALUES (?, ?, ?, ?, ?)`,
|
|
673
|
-
await this.execute(`UPDATE request_inspection
|
|
244
|
+
VALUES (?, ?, ?, ?, ?)`,[e.sessionId,e.requestId,e.sequence,JSON.stringify(e),e.timestamp]),await this.execute(`UPDATE request_inspection
|
|
674
245
|
SET last_activity_at = ?
|
|
675
|
-
WHERE request_id = ? AND session_id = ?`,
|
|
676
|
-
}
|
|
677
|
-
async listSessions(filter = {}) {
|
|
678
|
-
const { clause, args } = buildWhereClause([
|
|
679
|
-
["sessions.entry_agent_id = ?", filter.agentId],
|
|
680
|
-
]);
|
|
681
|
-
const rows = await this.selectAll(`SELECT sessions.session_id, sessions.entry_agent_id, sessions.latest_request_id, sessions.created_at, sessions.updated_at, sessions.status, request_inspection.current_agent_id
|
|
246
|
+
WHERE request_id = ? AND session_id = ?`,[e.timestamp,e.requestId,e.sessionId])}async listSessions(e={}){const{clause:t,args:s}=N([["sessions.entry_agent_id = ?",e.agentId]]);return(await this.selectAll(`SELECT sessions.session_id, sessions.entry_agent_id, sessions.latest_request_id, sessions.created_at, sessions.updated_at, sessions.status, request_inspection.current_agent_id
|
|
682
247
|
FROM sessions
|
|
683
248
|
LEFT JOIN request_inspection ON request_inspection.request_id = sessions.latest_request_id
|
|
684
|
-
${
|
|
685
|
-
ORDER BY updated_at DESC`, args);
|
|
686
|
-
return rows.map((row) => this.mapSessionSummary(row));
|
|
687
|
-
}
|
|
688
|
-
async listSessionSummaries(filter = {}) {
|
|
689
|
-
const { clause, args } = buildWhereClause([
|
|
690
|
-
["sessions.entry_agent_id = ?", filter.agentId],
|
|
691
|
-
]);
|
|
692
|
-
const rows = await this.selectAll(`WITH ranked_messages AS (
|
|
249
|
+
${t}
|
|
250
|
+
ORDER BY updated_at DESC`,s)).map(n=>this.mapSessionSummary(n))}async listSessionSummaries(e={}){const{clause:t,args:s}=N([["sessions.entry_agent_id = ?",e.agentId]]);return(await this.selectAll(`WITH ranked_messages AS (
|
|
693
251
|
SELECT session_id,
|
|
694
252
|
role,
|
|
695
253
|
content_json,
|
|
@@ -728,358 +286,52 @@ export class SqlitePersistence {
|
|
|
728
286
|
LEFT JOIN ranked_messages AS last_message
|
|
729
287
|
ON last_message.session_id = sessions.session_id
|
|
730
288
|
AND last_message.last_rank = 1
|
|
731
|
-
${
|
|
732
|
-
ORDER BY sessions.updated_at DESC`, args)
|
|
733
|
-
return rows.map((row) => ({
|
|
734
|
-
...this.mapSessionSummary(row),
|
|
735
|
-
entryAgentId: asString(row.entry_agent_id),
|
|
736
|
-
messageCount: Number(row.message_count ?? 0),
|
|
737
|
-
firstMessage: row.first_message_role
|
|
738
|
-
? {
|
|
739
|
-
role: asString(row.first_message_role),
|
|
740
|
-
content: parseJson(row.first_message_content_json),
|
|
741
|
-
requestId: asString(row.first_message_request_id),
|
|
742
|
-
createdAt: asString(row.first_message_created_at),
|
|
743
|
-
}
|
|
744
|
-
: undefined,
|
|
745
|
-
lastMessage: row.last_message_role
|
|
746
|
-
? {
|
|
747
|
-
role: asString(row.last_message_role),
|
|
748
|
-
content: parseJson(row.last_message_content_json),
|
|
749
|
-
requestId: asString(row.last_message_request_id),
|
|
750
|
-
createdAt: asString(row.last_message_created_at),
|
|
751
|
-
}
|
|
752
|
-
: undefined,
|
|
753
|
-
}));
|
|
754
|
-
}
|
|
755
|
-
async listRequests(filter = {}) {
|
|
756
|
-
const { clause, args } = buildWhereClause([
|
|
757
|
-
["requests.agent_id = ?", filter.agentId],
|
|
758
|
-
["requests.session_id = ?", filter.sessionId],
|
|
759
|
-
["requests.state = ?", filter.state],
|
|
760
|
-
]);
|
|
761
|
-
const rows = await this.selectAll(`SELECT requests.request_id, requests.session_id, requests.agent_id, requests.parent_request_id, requests.execution_mode, requests.adapter_kind, requests.created_at, requests.updated_at, requests.state, requests.checkpoint_ref, requests.resumable,
|
|
289
|
+
${t}
|
|
290
|
+
ORDER BY sessions.updated_at DESC`,s)).map(n=>({...this.mapSessionSummary(n),entryAgentId:i(n.entry_agent_id),messageCount:Number(n.message_count??0),firstMessage:n.first_message_role?{role:i(n.first_message_role),content:_(n.first_message_content_json),requestId:i(n.first_message_request_id),createdAt:i(n.first_message_created_at)}:void 0,lastMessage:n.last_message_role?{role:i(n.last_message_role),content:_(n.last_message_content_json),requestId:i(n.last_message_request_id),createdAt:i(n.last_message_created_at)}:void 0}))}async listRequests(e={}){const{clause:t,args:s}=N([["requests.agent_id = ?",e.agentId],["requests.session_id = ?",e.sessionId],["requests.state = ?",e.state]]),a=await this.selectAll(`SELECT requests.request_id, requests.session_id, requests.agent_id, requests.parent_request_id, requests.execution_mode, requests.adapter_kind, requests.created_at, requests.updated_at, requests.state, requests.checkpoint_ref, requests.resumable,
|
|
762
291
|
request_inspection.started_at, request_inspection.ended_at, request_inspection.last_activity_at, request_inspection.current_agent_id, request_inspection.delegation_chain_json
|
|
763
292
|
FROM requests
|
|
764
293
|
LEFT JOIN request_inspection ON request_inspection.request_id = requests.request_id
|
|
765
|
-
${
|
|
766
|
-
ORDER BY requests.updated_at DESC`,
|
|
767
|
-
const activeRequestIds = rows
|
|
768
|
-
.filter((row) => ACTIVE_REQUEST_STATES.has(asString(row.state)))
|
|
769
|
-
.map((row) => asString(row.request_id));
|
|
770
|
-
const snapshotsByRequestId = await this.listRequestSnapshots(activeRequestIds);
|
|
771
|
-
return rows.map((row) => {
|
|
772
|
-
const requestId = asString(row.request_id);
|
|
773
|
-
const runtimeSnapshot = snapshotsByRequestId.get(requestId);
|
|
774
|
-
return {
|
|
775
|
-
...this.mapRequestSummary(row),
|
|
776
|
-
...(runtimeSnapshot ? { runtimeSnapshot } : {}),
|
|
777
|
-
};
|
|
778
|
-
});
|
|
779
|
-
}
|
|
780
|
-
async getRequest(requestId) {
|
|
781
|
-
const row = await this.selectOne(`SELECT requests.request_id, requests.session_id, requests.agent_id, requests.parent_request_id, requests.execution_mode, requests.adapter_kind, requests.created_at, requests.updated_at, requests.state, requests.checkpoint_ref, requests.resumable,
|
|
294
|
+
${t}
|
|
295
|
+
ORDER BY requests.updated_at DESC`,s),n=a.filter(d=>v.has(i(d.state))).map(d=>i(d.request_id)),u=await this.listRequestSnapshots(n);return a.map(d=>{const R=i(d.request_id),O=u.get(R);return{...this.mapRequestSummary(d),...O?{runtimeSnapshot:O}:{}}})}async getRequest(e){const t=await this.selectOne(`SELECT requests.request_id, requests.session_id, requests.agent_id, requests.parent_request_id, requests.execution_mode, requests.adapter_kind, requests.created_at, requests.updated_at, requests.state, requests.checkpoint_ref, requests.resumable,
|
|
782
296
|
request_inspection.started_at, request_inspection.ended_at, request_inspection.last_activity_at, request_inspection.current_agent_id, request_inspection.delegation_chain_json, request_inspection.runtime_snapshot_json
|
|
783
297
|
FROM requests
|
|
784
298
|
LEFT JOIN request_inspection ON request_inspection.request_id = requests.request_id
|
|
785
|
-
WHERE requests.request_id = ?`,
|
|
786
|
-
return row ? this.mapRequestSummary(row) : null;
|
|
787
|
-
}
|
|
788
|
-
async getSession(sessionId) {
|
|
789
|
-
const row = await this.selectOne(`SELECT sessions.session_id, sessions.entry_agent_id, sessions.latest_request_id, sessions.created_at, sessions.updated_at, sessions.status, request_inspection.current_agent_id
|
|
299
|
+
WHERE requests.request_id = ?`,[e]);return t?this.mapRequestSummary(t):null}async getSession(e){const t=await this.selectOne(`SELECT sessions.session_id, sessions.entry_agent_id, sessions.latest_request_id, sessions.created_at, sessions.updated_at, sessions.status, request_inspection.current_agent_id
|
|
790
300
|
FROM sessions
|
|
791
301
|
LEFT JOIN request_inspection ON request_inspection.request_id = sessions.latest_request_id
|
|
792
|
-
WHERE sessions.session_id = ?`, [
|
|
793
|
-
return row ? this.mapSessionSummary(row) : null;
|
|
794
|
-
}
|
|
795
|
-
async getSessionMeta(sessionId) {
|
|
796
|
-
const row = await this.selectOne("SELECT * FROM sessions WHERE session_id = ?", [sessionId]);
|
|
797
|
-
if (!row) {
|
|
798
|
-
return null;
|
|
799
|
-
}
|
|
800
|
-
return {
|
|
801
|
-
sessionId: asString(row.session_id),
|
|
802
|
-
workspaceId: asString(row.workspace_id),
|
|
803
|
-
entryAgentId: asString(row.entry_agent_id),
|
|
804
|
-
createdAt: asString(row.created_at),
|
|
805
|
-
updatedAt: asString(row.updated_at),
|
|
806
|
-
status: asString(row.status),
|
|
807
|
-
latestRequestId: asString(row.latest_request_id),
|
|
808
|
-
};
|
|
809
|
-
}
|
|
810
|
-
async listSessionRequests(sessionId) {
|
|
811
|
-
const rows = await this.selectAll(`SELECT requests.request_id, requests.session_id, requests.agent_id, requests.parent_request_id, requests.execution_mode, requests.adapter_kind, requests.created_at, requests.updated_at, requests.state, requests.checkpoint_ref, requests.resumable,
|
|
302
|
+
WHERE sessions.session_id = ?`,[e]);return t?this.mapSessionSummary(t):null}async getSessionMeta(e){const t=await this.selectOne("SELECT * FROM sessions WHERE session_id = ?",[e]);return t?{sessionId:i(t.session_id),workspaceId:i(t.workspace_id),entryAgentId:i(t.entry_agent_id),createdAt:i(t.created_at),updatedAt:i(t.updated_at),status:i(t.status),latestRequestId:i(t.latest_request_id)}:null}async listSessionRequests(e){return(await this.selectAll(`SELECT requests.request_id, requests.session_id, requests.agent_id, requests.parent_request_id, requests.execution_mode, requests.adapter_kind, requests.created_at, requests.updated_at, requests.state, requests.checkpoint_ref, requests.resumable,
|
|
812
303
|
request_inspection.started_at, request_inspection.ended_at, request_inspection.last_activity_at, request_inspection.current_agent_id, request_inspection.delegation_chain_json, request_inspection.runtime_snapshot_json
|
|
813
304
|
FROM requests
|
|
814
305
|
LEFT JOIN request_inspection ON request_inspection.request_id = requests.request_id
|
|
815
306
|
WHERE requests.session_id = ?
|
|
816
|
-
ORDER BY created_at DESC`,
|
|
817
|
-
return rows.map((row) => this.mapRequestSummary(row));
|
|
818
|
-
}
|
|
819
|
-
async listRequestEvents(sessionId, requestId) {
|
|
820
|
-
const rows = await this.selectAll(`SELECT event_json
|
|
307
|
+
ORDER BY created_at DESC`,[e])).map(s=>this.mapRequestSummary(s))}async listRequestEvents(e,t){return(await this.selectAll(`SELECT event_json
|
|
821
308
|
FROM events
|
|
822
309
|
WHERE session_id = ? AND request_id = ?
|
|
823
|
-
ORDER BY sequence ASC`, [sessionId, requestId]);
|
|
824
|
-
return rows.map((row) => parseJson(row.event_json));
|
|
825
|
-
}
|
|
826
|
-
async listApprovals(filter = {}) {
|
|
827
|
-
const { clause, args } = buildWhereClause([
|
|
828
|
-
["status = ?", filter.status],
|
|
829
|
-
["session_id = ?", filter.sessionId],
|
|
830
|
-
["request_id = ?", filter.requestId],
|
|
831
|
-
]);
|
|
832
|
-
const rows = await this.selectAll(`SELECT * FROM approvals${clause} ORDER BY requested_at ASC, approval_id ASC`, args);
|
|
833
|
-
return rows.map((row) => this.mapApproval(row));
|
|
834
|
-
}
|
|
835
|
-
async getApproval(approvalId) {
|
|
836
|
-
const row = await this.selectOne("SELECT * FROM approvals WHERE approval_id = ?", [approvalId]);
|
|
837
|
-
return row ? this.mapApproval(row) : null;
|
|
838
|
-
}
|
|
839
|
-
async getRequestApprovals(sessionId, requestId) {
|
|
840
|
-
const rows = await this.selectAll("SELECT * FROM approvals WHERE session_id = ? AND request_id = ? ORDER BY requested_at ASC, approval_id ASC", [sessionId, requestId]);
|
|
841
|
-
return rows.map((row) => this.mapApproval(row));
|
|
842
|
-
}
|
|
843
|
-
async getRequestMeta(sessionId, requestId) {
|
|
844
|
-
const row = await this.selectOne(`SELECT request_id, session_id, agent_id, parent_request_id, execution_mode, adapter_kind, created_at, updated_at
|
|
310
|
+
ORDER BY sequence ASC`,[e,t])).map(a=>_(a.event_json))}async listApprovals(e={}){const{clause:t,args:s}=N([["status = ?",e.status],["session_id = ?",e.sessionId],["request_id = ?",e.requestId]]);return(await this.selectAll(`SELECT * FROM approvals${t} ORDER BY requested_at ASC, approval_id ASC`,s)).map(n=>this.mapApproval(n))}async getApproval(e){const t=await this.selectOne("SELECT * FROM approvals WHERE approval_id = ?",[e]);return t?this.mapApproval(t):null}async getRequestApprovals(e,t){return(await this.selectAll("SELECT * FROM approvals WHERE session_id = ? AND request_id = ? ORDER BY requested_at ASC, approval_id ASC",[e,t])).map(a=>this.mapApproval(a))}async getRequestMeta(e,t){const s=await this.selectOne(`SELECT request_id, session_id, agent_id, parent_request_id, execution_mode, adapter_kind, created_at, updated_at
|
|
845
311
|
FROM requests
|
|
846
|
-
WHERE session_id = ? AND request_id = ?`,
|
|
847
|
-
if (!row) {
|
|
848
|
-
throw new Error(`Missing request ${requestId} for session ${sessionId}`);
|
|
849
|
-
}
|
|
850
|
-
return {
|
|
851
|
-
requestId: asString(row.request_id),
|
|
852
|
-
sessionId: asString(row.session_id),
|
|
853
|
-
agentId: asString(row.agent_id),
|
|
854
|
-
parentRequestId: asNullableString(row.parent_request_id),
|
|
855
|
-
executionMode: asString(row.execution_mode),
|
|
856
|
-
adapterKind: asNullableString(row.adapter_kind) ?? undefined,
|
|
857
|
-
createdAt: asString(row.created_at),
|
|
858
|
-
updatedAt: asString(row.updated_at),
|
|
859
|
-
};
|
|
860
|
-
}
|
|
861
|
-
async getRequestLifecycle(sessionId, requestId) {
|
|
862
|
-
const row = await this.selectOne(`SELECT state, previous_state, state_entered_at, last_transition_at, resumable, checkpoint_ref
|
|
312
|
+
WHERE session_id = ? AND request_id = ?`,[e,t]);if(!s)throw new Error(`Missing request ${t} for session ${e}`);return{requestId:i(s.request_id),sessionId:i(s.session_id),agentId:i(s.agent_id),parentRequestId:r(s.parent_request_id),executionMode:i(s.execution_mode),adapterKind:r(s.adapter_kind)??void 0,createdAt:i(s.created_at),updatedAt:i(s.updated_at)}}async getRequestLifecycle(e,t){const s=await this.selectOne(`SELECT state, previous_state, state_entered_at, last_transition_at, resumable, checkpoint_ref
|
|
863
313
|
FROM requests
|
|
864
|
-
WHERE session_id = ? AND request_id = ?`,
|
|
865
|
-
if (!row) {
|
|
866
|
-
throw new Error(`Missing request lifecycle ${requestId} for session ${sessionId}`);
|
|
867
|
-
}
|
|
868
|
-
return {
|
|
869
|
-
state: asString(row.state),
|
|
870
|
-
previousState: asNullableString(row.previous_state),
|
|
871
|
-
stateEnteredAt: asString(row.state_entered_at),
|
|
872
|
-
lastTransitionAt: asString(row.last_transition_at),
|
|
873
|
-
resumable: asBoolean(row.resumable),
|
|
874
|
-
checkpointRef: asNullableString(row.checkpoint_ref),
|
|
875
|
-
};
|
|
876
|
-
}
|
|
877
|
-
async getRequestInspection(sessionId, requestId) {
|
|
878
|
-
const row = await this.selectOne(`SELECT started_at, ended_at, last_activity_at, current_agent_id, delegation_chain_json, runtime_snapshot_json, upstream_events_json
|
|
314
|
+
WHERE session_id = ? AND request_id = ?`,[e,t]);if(!s)throw new Error(`Missing request lifecycle ${t} for session ${e}`);return{state:i(s.state),previousState:r(s.previous_state),stateEnteredAt:i(s.state_entered_at),lastTransitionAt:i(s.last_transition_at),resumable:A(s.resumable),checkpointRef:r(s.checkpoint_ref)}}async getRequestInspection(e,t){const s=await this.selectOne(`SELECT started_at, ended_at, last_activity_at, current_agent_id, delegation_chain_json, runtime_snapshot_json, upstream_events_json
|
|
879
315
|
FROM request_inspection
|
|
880
|
-
WHERE session_id = ? AND request_id = ?`,
|
|
881
|
-
if (!row) {
|
|
882
|
-
throw new Error(`Missing request inspection ${requestId} for session ${sessionId}`);
|
|
883
|
-
}
|
|
884
|
-
return {
|
|
885
|
-
startedAt: asString(row.started_at),
|
|
886
|
-
endedAt: asNullableString(row.ended_at),
|
|
887
|
-
lastActivityAt: asString(row.last_activity_at),
|
|
888
|
-
currentAgentId: asNullableString(row.current_agent_id),
|
|
889
|
-
delegationChain: parseJson(row.delegation_chain_json),
|
|
890
|
-
runtimeSnapshot: row.runtime_snapshot_json ? parseJson(row.runtime_snapshot_json) : null,
|
|
891
|
-
traceItems: await this.listRequestTraceItems(sessionId, requestId),
|
|
892
|
-
};
|
|
893
|
-
}
|
|
894
|
-
async updateRequestInspection(sessionId, requestId, patch) {
|
|
895
|
-
const row = await this.selectOne(`SELECT ended_at, last_activity_at, current_agent_id, delegation_chain_json, runtime_snapshot_json
|
|
316
|
+
WHERE session_id = ? AND request_id = ?`,[e,t]);if(!s)throw new Error(`Missing request inspection ${t} for session ${e}`);return{startedAt:i(s.started_at),endedAt:r(s.ended_at),lastActivityAt:i(s.last_activity_at),currentAgentId:r(s.current_agent_id),delegationChain:_(s.delegation_chain_json),runtimeSnapshot:s.runtime_snapshot_json?_(s.runtime_snapshot_json):null,traceItems:await this.listRequestTraceItems(e,t)}}async updateRequestInspection(e,t,s){const a=await this.selectOne(`SELECT ended_at, last_activity_at, current_agent_id, delegation_chain_json, runtime_snapshot_json
|
|
896
317
|
FROM request_inspection
|
|
897
|
-
WHERE request_id = ? AND session_id = ?`,
|
|
898
|
-
if (!row) {
|
|
899
|
-
throw new Error(`Missing request inspection ${requestId} for session ${sessionId}`);
|
|
900
|
-
}
|
|
901
|
-
await this.execute(`UPDATE request_inspection
|
|
318
|
+
WHERE request_id = ? AND session_id = ?`,[t,e]);if(!a)throw new Error(`Missing request inspection ${t} for session ${e}`);await this.execute(`UPDATE request_inspection
|
|
902
319
|
SET ended_at = ?, last_activity_at = ?, current_agent_id = ?, delegation_chain_json = ?, runtime_snapshot_json = ?, upstream_events_json = ?
|
|
903
|
-
WHERE request_id = ? AND session_id = ?`, [
|
|
904
|
-
|
|
905
|
-
patch.lastActivityAt ?? asString(row.last_activity_at),
|
|
906
|
-
patch.currentAgentId === undefined ? asNullableString(row.current_agent_id) : patch.currentAgentId,
|
|
907
|
-
JSON.stringify(patch.delegationChain ?? parseJson(row.delegation_chain_json)),
|
|
908
|
-
JSON.stringify(patch.runtimeSnapshot === undefined
|
|
909
|
-
? (row.runtime_snapshot_json ? parseJson(row.runtime_snapshot_json) : null)
|
|
910
|
-
: patch.runtimeSnapshot),
|
|
911
|
-
"[]",
|
|
912
|
-
requestId,
|
|
913
|
-
sessionId,
|
|
914
|
-
]);
|
|
915
|
-
}
|
|
916
|
-
async appendRequestTraceItem(sessionId, requestId, item) {
|
|
917
|
-
await this.execute(`INSERT INTO request_trace_items (request_id, session_id, item_json, created_at)
|
|
918
|
-
VALUES (?, ?, ?, ?)`, [requestId, sessionId, JSON.stringify(item), nowIso()]);
|
|
919
|
-
}
|
|
920
|
-
async listRequestTraceItems(sessionId, requestId) {
|
|
921
|
-
const rows = await this.selectAll(`SELECT item_json
|
|
320
|
+
WHERE request_id = ? AND session_id = ?`,[s.endedAt===void 0?r(a.ended_at):s.endedAt,s.lastActivityAt??i(a.last_activity_at),s.currentAgentId===void 0?r(a.current_agent_id):s.currentAgentId,JSON.stringify(s.delegationChain??_(a.delegation_chain_json)),JSON.stringify(s.runtimeSnapshot===void 0?a.runtime_snapshot_json?_(a.runtime_snapshot_json):null:s.runtimeSnapshot),"[]",t,e])}async appendRequestTraceItem(e,t,s){await this.execute(`INSERT INTO request_trace_items (request_id, session_id, item_json, created_at)
|
|
321
|
+
VALUES (?, ?, ?, ?)`,[t,e,JSON.stringify(s),S()])}async listRequestTraceItems(e,t){const s=await this.selectAll(`SELECT item_json
|
|
922
322
|
FROM request_trace_items
|
|
923
323
|
WHERE session_id = ? AND request_id = ?
|
|
924
|
-
ORDER BY trace_id ASC`,
|
|
925
|
-
if (rows.length > 0) {
|
|
926
|
-
return rows.map((row) => parseJson(row.item_json));
|
|
927
|
-
}
|
|
928
|
-
const row = await this.selectOne(`SELECT upstream_events_json
|
|
324
|
+
ORDER BY trace_id ASC`,[e,t]);if(s.length>0)return s.map(n=>_(n.item_json));const a=await this.selectOne(`SELECT upstream_events_json
|
|
929
325
|
FROM request_inspection
|
|
930
|
-
WHERE session_id = ? AND request_id = ?`, [
|
|
931
|
-
return row?.upstream_events_json ? parseJson(row.upstream_events_json) : [];
|
|
932
|
-
}
|
|
933
|
-
async deleteSession(sessionId) {
|
|
934
|
-
const exists = await this.getSession(sessionId);
|
|
935
|
-
if (!exists) {
|
|
936
|
-
return false;
|
|
937
|
-
}
|
|
938
|
-
await this.execute("DELETE FROM request_plan_state WHERE session_id = ?", [sessionId]);
|
|
939
|
-
await this.execute("DELETE FROM artifacts WHERE session_id = ?", [sessionId]);
|
|
940
|
-
await this.execute("DELETE FROM approvals WHERE session_id = ?", [sessionId]);
|
|
941
|
-
await this.execute("DELETE FROM events WHERE session_id = ?", [sessionId]);
|
|
942
|
-
await this.execute("DELETE FROM request_trace_items WHERE session_id = ?", [sessionId]);
|
|
943
|
-
await this.execute("DELETE FROM request_inspection WHERE session_id = ?", [sessionId]);
|
|
944
|
-
await this.execute("DELETE FROM request_queue WHERE session_id = ?", [sessionId]);
|
|
945
|
-
await this.execute("DELETE FROM request_inputs WHERE session_id = ?", [sessionId]);
|
|
946
|
-
await this.execute("DELETE FROM recovery_intents WHERE session_id = ?", [sessionId]);
|
|
947
|
-
await this.execute("DELETE FROM session_messages WHERE session_id = ?", [sessionId]);
|
|
948
|
-
await this.execute("DELETE FROM request_control WHERE request_id IN (SELECT request_id FROM requests WHERE session_id = ?)", [sessionId]);
|
|
949
|
-
await this.execute("DELETE FROM requests WHERE session_id = ?", [sessionId]);
|
|
950
|
-
await this.execute("DELETE FROM sessions WHERE session_id = ?", [sessionId]);
|
|
951
|
-
await rm(this.sessionDir(sessionId), { recursive: true, force: true });
|
|
952
|
-
return true;
|
|
953
|
-
}
|
|
954
|
-
async saveRequestInput(sessionId, requestId, request) {
|
|
955
|
-
await this.requestContextStore.saveRequestInput(sessionId, requestId, request);
|
|
956
|
-
}
|
|
957
|
-
async getRequestInput(sessionId, requestId) {
|
|
958
|
-
return this.requestContextStore.getRequestInput(sessionId, requestId);
|
|
959
|
-
}
|
|
960
|
-
async clearRequestInput(sessionId, requestId) {
|
|
961
|
-
await this.requestContextStore.clearRequestInput(sessionId, requestId);
|
|
962
|
-
}
|
|
963
|
-
async createApproval(record) {
|
|
964
|
-
const sessionId = record.sessionId;
|
|
965
|
-
const requestId = record.requestId;
|
|
966
|
-
await this.execute(`INSERT OR REPLACE INTO approvals
|
|
326
|
+
WHERE session_id = ? AND request_id = ?`,[e,t]);return a?.upstream_events_json?_(a.upstream_events_json):[]}async deleteSession(e){return await this.getSession(e)?(await this.execute("DELETE FROM request_plan_state WHERE session_id = ?",[e]),await this.execute("DELETE FROM artifacts WHERE session_id = ?",[e]),await this.execute("DELETE FROM approvals WHERE session_id = ?",[e]),await this.execute("DELETE FROM events WHERE session_id = ?",[e]),await this.execute("DELETE FROM request_trace_items WHERE session_id = ?",[e]),await this.execute("DELETE FROM request_inspection WHERE session_id = ?",[e]),await this.execute("DELETE FROM request_queue WHERE session_id = ?",[e]),await this.execute("DELETE FROM request_inputs WHERE session_id = ?",[e]),await this.execute("DELETE FROM recovery_intents WHERE session_id = ?",[e]),await this.execute("DELETE FROM session_messages WHERE session_id = ?",[e]),await this.execute("DELETE FROM request_control WHERE request_id IN (SELECT request_id FROM requests WHERE session_id = ?)",[e]),await this.execute("DELETE FROM requests WHERE session_id = ?",[e]),await this.execute("DELETE FROM sessions WHERE session_id = ?",[e]),await g(this.sessionDir(e),{recursive:!0,force:!0}),!0):!1}async saveRequestInput(e,t,s){await this.requestContextStore.saveRequestInput(e,t,s)}async getRequestInput(e,t){return this.requestContextStore.getRequestInput(e,t)}async clearRequestInput(e,t){await this.requestContextStore.clearRequestInput(e,t)}async createApproval(e){const t=e.sessionId,s=e.requestId;await this.execute(`INSERT OR REPLACE INTO approvals
|
|
967
327
|
(approval_id, pending_action_id, session_id, request_id, tool_call_id, tool_name, status, requested_at, resolved_at, allowed_decisions_json, input_preview_json, checkpoint_ref, event_refs_json)
|
|
968
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
969
|
-
record.approvalId,
|
|
970
|
-
record.pendingActionId,
|
|
971
|
-
sessionId,
|
|
972
|
-
requestId,
|
|
973
|
-
record.toolCallId,
|
|
974
|
-
record.toolName,
|
|
975
|
-
record.status,
|
|
976
|
-
record.requestedAt,
|
|
977
|
-
record.resolvedAt,
|
|
978
|
-
JSON.stringify(record.allowedDecisions),
|
|
979
|
-
JSON.stringify(record.inputPreview),
|
|
980
|
-
record.checkpointRef,
|
|
981
|
-
JSON.stringify(record.eventRefs),
|
|
982
|
-
]);
|
|
983
|
-
}
|
|
984
|
-
async resolveApproval(sessionId, requestId, approvalId, status) {
|
|
985
|
-
const current = await this.getApproval(approvalId);
|
|
986
|
-
if (!current || current.sessionId !== sessionId || current.requestId !== requestId) {
|
|
987
|
-
throw new Error(`Missing approval ${approvalId} for request ${requestId}`);
|
|
988
|
-
}
|
|
989
|
-
const updated = {
|
|
990
|
-
...current,
|
|
991
|
-
status,
|
|
992
|
-
resolvedAt: nowIso(),
|
|
993
|
-
};
|
|
994
|
-
await this.createApproval(updated);
|
|
995
|
-
return updated;
|
|
996
|
-
}
|
|
997
|
-
async saveRequestPlanState(sessionId, requestId, planState) {
|
|
998
|
-
await this.execute(`INSERT OR REPLACE INTO request_plan_state
|
|
328
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.approvalId,e.pendingActionId,t,s,e.toolCallId,e.toolName,e.status,e.requestedAt,e.resolvedAt,JSON.stringify(e.allowedDecisions),JSON.stringify(e.inputPreview),e.checkpointRef,JSON.stringify(e.eventRefs)])}async resolveApproval(e,t,s,a){const n=await this.getApproval(s);if(!n||n.sessionId!==e||n.requestId!==t)throw new Error(`Missing approval ${s} for request ${t}`);const u={...n,status:a,resolvedAt:S()};return await this.createApproval(u),u}async saveRequestPlanState(e,t,s){await this.execute(`INSERT OR REPLACE INTO request_plan_state
|
|
999
329
|
(request_id, session_id, version, updated_at, plan_json)
|
|
1000
|
-
VALUES (?, ?, ?, ?, ?)`,
|
|
1001
|
-
}
|
|
1002
|
-
async getRequestPlanState(sessionId, requestId) {
|
|
1003
|
-
const row = await this.selectOne(`SELECT plan_json
|
|
330
|
+
VALUES (?, ?, ?, ?, ?)`,[t,e,s.version,s.updatedAt,JSON.stringify(s)])}async getRequestPlanState(e,t){const s=await this.selectOne(`SELECT plan_json
|
|
1004
331
|
FROM request_plan_state
|
|
1005
|
-
WHERE session_id = ? AND request_id = ?`, [
|
|
1006
|
-
return row?.plan_json ? parseJson(row.plan_json) : null;
|
|
1007
|
-
}
|
|
1008
|
-
async clearRequestPlanState(sessionId, requestId) {
|
|
1009
|
-
await this.execute("DELETE FROM request_plan_state WHERE session_id = ? AND request_id = ?", [sessionId, requestId]);
|
|
1010
|
-
}
|
|
1011
|
-
async createRequestArtifact(sessionId, requestId, artifact, content) {
|
|
1012
|
-
const filePath = path.join(this.requestDir(sessionId, requestId), artifact.path);
|
|
1013
|
-
await mkdir(path.dirname(filePath), { recursive: true });
|
|
1014
|
-
await writeJson(filePath, content);
|
|
1015
|
-
await this.execute(`INSERT OR REPLACE INTO artifacts
|
|
332
|
+
WHERE session_id = ? AND request_id = ?`,[e,t]);return s?.plan_json?_(s.plan_json):null}async clearRequestPlanState(e,t){await this.execute("DELETE FROM request_plan_state WHERE session_id = ? AND request_id = ?",[e,t])}async createRequestArtifact(e,t,s,a){const n=E.join(this.requestDir(e,t),s.path);return await c(E.dirname(n),{recursive:!0}),await y(n,a),await this.execute(`INSERT OR REPLACE INTO artifacts
|
|
1016
333
|
(artifact_id, session_id, request_id, kind, path, created_at)
|
|
1017
|
-
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
1018
|
-
return artifact;
|
|
1019
|
-
}
|
|
1020
|
-
async listRequestArtifacts(sessionId, requestId) {
|
|
1021
|
-
const rows = await this.selectAll(`SELECT artifact_id, kind, path, created_at
|
|
334
|
+
VALUES (?, ?, ?, ?, ?, ?)`,[s.artifactId,e,t,s.kind,s.path,s.createdAt]),s}async listRequestArtifacts(e,t){const s=await this.selectAll(`SELECT artifact_id, kind, path, created_at
|
|
1022
335
|
FROM artifacts
|
|
1023
336
|
WHERE session_id = ? AND request_id = ?
|
|
1024
|
-
ORDER BY created_at ASC, artifact_id ASC`,
|
|
1025
|
-
return {
|
|
1026
|
-
sessionId,
|
|
1027
|
-
requestId,
|
|
1028
|
-
items: rows.map((row) => ({
|
|
1029
|
-
artifactId: asString(row.artifact_id),
|
|
1030
|
-
kind: asString(row.kind),
|
|
1031
|
-
path: asString(row.path),
|
|
1032
|
-
createdAt: asString(row.created_at),
|
|
1033
|
-
})),
|
|
1034
|
-
};
|
|
1035
|
-
}
|
|
1036
|
-
async appendSessionMessage(sessionId, message) {
|
|
1037
|
-
await this.requestContextStore.appendSessionMessage(sessionId, message);
|
|
1038
|
-
}
|
|
1039
|
-
async listSessionMessages(sessionId, limit = 12) {
|
|
1040
|
-
return this.requestContextStore.listSessionMessages(sessionId, limit);
|
|
1041
|
-
}
|
|
1042
|
-
async saveRequestRecoveryIntent(sessionId, requestId, intent) {
|
|
1043
|
-
await this.requestContextStore.saveRequestRecoveryIntent(sessionId, requestId, intent);
|
|
1044
|
-
}
|
|
1045
|
-
async getRequestRecoveryIntent(sessionId, requestId) {
|
|
1046
|
-
return this.requestContextStore.getRequestRecoveryIntent(sessionId, requestId);
|
|
1047
|
-
}
|
|
1048
|
-
async clearRequestRecoveryIntent(sessionId, requestId) {
|
|
1049
|
-
await this.requestContextStore.clearRequestRecoveryIntent(sessionId, requestId);
|
|
1050
|
-
}
|
|
1051
|
-
async enqueueRequest(input) {
|
|
1052
|
-
await this.requestQueueStore.enqueueRequest(input);
|
|
1053
|
-
}
|
|
1054
|
-
async getQueuedRequest(requestId) {
|
|
1055
|
-
return this.requestQueueStore.getQueuedRequest(requestId);
|
|
1056
|
-
}
|
|
1057
|
-
async claimQueuedRequest(input) {
|
|
1058
|
-
return this.requestQueueStore.claimQueuedRequest(input);
|
|
1059
|
-
}
|
|
1060
|
-
async renewRequestLease(input) {
|
|
1061
|
-
await this.requestQueueStore.renewRequestLease(input);
|
|
1062
|
-
}
|
|
1063
|
-
async releaseRequestClaim(requestId) {
|
|
1064
|
-
await this.requestQueueStore.releaseRequestClaim(requestId);
|
|
1065
|
-
}
|
|
1066
|
-
async listExpiredClaimedRequests(cutoffIso) {
|
|
1067
|
-
return this.requestQueueStore.listExpiredClaimedRequests(cutoffIso);
|
|
1068
|
-
}
|
|
1069
|
-
async getRequestControl(requestId) {
|
|
1070
|
-
return this.requestQueueStore.getRequestControl(requestId);
|
|
1071
|
-
}
|
|
1072
|
-
async requestRequestCancel(requestId, reason) {
|
|
1073
|
-
return this.requestQueueStore.requestRequestCancel(requestId, reason);
|
|
1074
|
-
}
|
|
1075
|
-
async clearRequestCancel(requestId) {
|
|
1076
|
-
await this.requestQueueStore.clearRequestCancel(requestId);
|
|
1077
|
-
}
|
|
1078
|
-
async readRequestArtifact(sessionId, requestId, artifactPath) {
|
|
1079
|
-
const filePath = path.join(this.requestDir(sessionId, requestId), artifactPath);
|
|
1080
|
-
if (!(await fileExists(filePath))) {
|
|
1081
|
-
return null;
|
|
1082
|
-
}
|
|
1083
|
-
return readJson(filePath);
|
|
1084
|
-
}
|
|
1085
|
-
}
|
|
337
|
+
ORDER BY created_at ASC, artifact_id ASC`,[e,t]);return{sessionId:e,requestId:t,items:s.map(a=>({artifactId:i(a.artifact_id),kind:i(a.kind),path:i(a.path),createdAt:i(a.created_at)}))}}async appendSessionMessage(e,t){await this.requestContextStore.appendSessionMessage(e,t)}async listSessionMessages(e,t=12){return this.requestContextStore.listSessionMessages(e,t)}async saveRequestRecoveryIntent(e,t,s){await this.requestContextStore.saveRequestRecoveryIntent(e,t,s)}async getRequestRecoveryIntent(e,t){return this.requestContextStore.getRequestRecoveryIntent(e,t)}async clearRequestRecoveryIntent(e,t){await this.requestContextStore.clearRequestRecoveryIntent(e,t)}async enqueueRequest(e){await this.requestQueueStore.enqueueRequest(e)}async getQueuedRequest(e){return this.requestQueueStore.getQueuedRequest(e)}async claimQueuedRequest(e){return this.requestQueueStore.claimQueuedRequest(e)}async renewRequestLease(e){await this.requestQueueStore.renewRequestLease(e)}async releaseRequestClaim(e){await this.requestQueueStore.releaseRequestClaim(e)}async listExpiredClaimedRequests(e){return this.requestQueueStore.listExpiredClaimedRequests(e)}async getRequestControl(e){return this.requestQueueStore.getRequestControl(e)}async requestRequestCancel(e,t){return this.requestQueueStore.requestRequestCancel(e,t)}async clearRequestCancel(e){await this.requestQueueStore.clearRequestCancel(e)}async readRequestArtifact(e,t,s){const a=E.join(this.requestDir(e,t),s);return await I(a)?C(a):null}}export{H as SqlitePersistence,W as listProtectedCheckpointSessionIds};
|