@sema-agent/server 1.314.0 → 1.316.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/approval-hmac.d.ts +17 -0
- package/dist/approval-hmac.js +27 -0
- package/dist/config-center/apply-effective.d.ts +22 -0
- package/dist/config-center/apply-effective.js +283 -0
- package/dist/config-center/http-client.d.ts +23 -0
- package/dist/config-center/http-client.js +109 -0
- package/dist/config-center/restart-signal.d.ts +12 -0
- package/dist/config-center/restart-signal.js +70 -0
- package/dist/config-center/skills-mcp.d.ts +13 -0
- package/dist/config-center/skills-mcp.js +113 -0
- package/dist/config-center/types.d.ts +143 -0
- package/dist/config-center/types.js +2 -0
- package/dist/fleet/fleet-bus.js +92 -83
- package/dist/hooks/hook-runner.js +18 -9
- package/dist/http/idempotency.d.ts +1 -0
- package/dist/http/idempotency.js +3 -0
- package/dist/http/principal-gate.d.ts +12 -0
- package/dist/http/principal-gate.js +52 -0
- package/dist/http/route-ctx.d.ts +67 -0
- package/dist/http/route-ctx.js +2 -0
- package/dist/http/routes/attachments.d.ts +4 -0
- package/dist/http/routes/attachments.js +106 -0
- package/dist/http/routes/capabilities.d.ts +4 -0
- package/dist/http/routes/capabilities.js +111 -0
- package/dist/http/routes/images.d.ts +20 -0
- package/dist/http/routes/images.js +572 -0
- package/dist/http/routes/memory-policy.d.ts +4 -0
- package/dist/http/routes/memory-policy.js +105 -0
- package/dist/http/routes/observability.d.ts +4 -0
- package/dist/http/routes/observability.js +63 -0
- package/dist/http/routes/session-sync.d.ts +36 -0
- package/dist/http/routes/session-sync.js +513 -0
- package/dist/http/routes/sessions-list.d.ts +4 -0
- package/dist/http/routes/sessions-list.js +117 -0
- package/dist/http/routes/sessions.d.ts +17 -0
- package/dist/http/routes/sessions.js +746 -0
- package/dist/http/send.d.ts +6 -0
- package/dist/http/send.js +19 -0
- package/dist/http/server.d.ts +101 -76
- package/dist/http/server.js +129 -2410
- package/dist/http/sse-log.d.ts +25 -0
- package/dist/http/sse-log.js +59 -0
- package/dist/http/workspace-content.d.ts +3 -0
- package/dist/http/workspace-content.js +20 -0
- package/dist/index.d.ts +1 -1
- package/dist/leader/leader.js +5 -2
- package/dist/leader/wire.js +169 -165
- package/dist/main.js +462 -451
- package/dist/plugins/approval-store-sql.d.ts +52 -0
- package/dist/plugins/approval-store-sql.js +119 -0
- package/dist/plugins/breaker-state-sql.d.ts +29 -0
- package/dist/plugins/breaker-state-sql.js +104 -0
- package/dist/plugins/checkpoint-store-sql.d.ts +67 -0
- package/dist/plugins/checkpoint-store-sql.js +224 -0
- package/dist/plugins/file-snapshot-store-sql.d.ts +38 -0
- package/dist/plugins/file-snapshot-store-sql.js +210 -0
- package/dist/plugins/image-bake-store-sql.d.ts +53 -0
- package/dist/plugins/image-bake-store-sql.js +463 -0
- package/dist/plugins/image-index-sql.d.ts +33 -0
- package/dist/plugins/image-index-sql.js +328 -0
- package/dist/plugins/k8s-bg-scripts.d.ts +19 -0
- package/dist/plugins/k8s-bg-scripts.js +129 -0
- package/dist/plugins/k8s-exec-protocol.d.ts +20 -0
- package/dist/plugins/k8s-exec-protocol.js +87 -0
- package/dist/plugins/outcome-ledger-sql.d.ts +70 -0
- package/dist/plugins/outcome-ledger-sql.js +158 -0
- package/dist/plugins/pg-approval-store.d.ts +1 -27
- package/dist/plugins/pg-approval-store.js +1 -83
- package/dist/plugins/pg-breaker-state.d.ts +1 -19
- package/dist/plugins/pg-breaker-state.js +1 -88
- package/dist/plugins/pg-checkpoint-store.d.ts +1 -33
- package/dist/plugins/pg-checkpoint-store.js +1 -189
- package/dist/plugins/pg-cost-quota.js +3 -143
- package/dist/plugins/pg-file-snapshot-store.d.ts +1 -27
- package/dist/plugins/pg-file-snapshot-store.js +1 -190
- package/dist/plugins/pg-image-bake.d.ts +1 -40
- package/dist/plugins/pg-image-bake.js +1 -420
- package/dist/plugins/pg-image-index.d.ts +1 -21
- package/dist/plugins/pg-image-index.js +1 -217
- package/dist/plugins/pg-outcome-ledger.d.ts +2 -22
- package/dist/plugins/pg-outcome-ledger.js +1 -104
- package/dist/plugins/pg-rate-limiter.d.ts +2 -32
- package/dist/plugins/pg-rate-limiter.js +4 -147
- package/dist/plugins/pg-resume-anchor-store.d.ts +1 -13
- package/dist/plugins/pg-resume-anchor-store.js +1 -22
- package/dist/plugins/pg-run-store.d.ts +1 -75
- package/dist/plugins/pg-run-store.js +1 -287
- package/dist/plugins/pg-session-policy-store.d.ts +1 -11
- package/dist/plugins/pg-session-policy-store.js +1 -90
- package/dist/plugins/pg-tool-result-store.d.ts +1 -15
- package/dist/plugins/pg-tool-result-store.js +1 -52
- package/dist/plugins/pg-workflow-journal-store.d.ts +1 -20
- package/dist/plugins/pg-workflow-journal-store.js +1 -34
- package/dist/plugins/pg-workflow-run-store.d.ts +1 -55
- package/dist/plugins/pg-workflow-run-store.js +1 -220
- package/dist/plugins/remote-env-k8s.d.ts +5 -38
- package/dist/plugins/remote-env-k8s.js +7 -213
- package/dist/plugins/resume-anchor-store-sql.d.ts +23 -0
- package/dist/plugins/resume-anchor-store-sql.js +38 -0
- package/dist/plugins/run-store-sql.d.ts +89 -0
- package/dist/plugins/run-store-sql.js +397 -0
- package/dist/plugins/session-policy-store-sql.d.ts +22 -0
- package/dist/plugins/session-policy-store-sql.js +109 -0
- package/dist/plugins/sql-driver.d.ts +25 -0
- package/dist/plugins/sql-driver.js +59 -0
- package/dist/plugins/tidb-approval-store.d.ts +1 -39
- package/dist/plugins/tidb-approval-store.js +1 -71
- package/dist/plugins/tidb-breaker-state.d.ts +1 -17
- package/dist/plugins/tidb-breaker-state.js +1 -74
- package/dist/plugins/tidb-checkpoint-store.d.ts +1 -49
- package/dist/plugins/tidb-checkpoint-store.js +1 -191
- package/dist/plugins/tidb-file-snapshot-store.d.ts +1 -27
- package/dist/plugins/tidb-file-snapshot-store.js +1 -192
- package/dist/plugins/tidb-image-bake.d.ts +1 -38
- package/dist/plugins/tidb-image-bake.js +1 -348
- package/dist/plugins/tidb-image-index.d.ts +1 -19
- package/dist/plugins/tidb-image-index.js +1 -149
- package/dist/plugins/tidb-outcome-ledger.d.ts +1 -57
- package/dist/plugins/tidb-outcome-ledger.js +1 -97
- package/dist/plugins/tidb-resume-anchor-store.d.ts +1 -13
- package/dist/plugins/tidb-resume-anchor-store.js +1 -22
- package/dist/plugins/tidb-run-store.d.ts +1 -75
- package/dist/plugins/tidb-run-store.js +1 -306
- package/dist/plugins/tidb-session-policy-store.d.ts +1 -11
- package/dist/plugins/tidb-session-policy-store.js +1 -86
- package/dist/plugins/tidb-tool-result-store.d.ts +1 -13
- package/dist/plugins/tidb-tool-result-store.js +1 -38
- package/dist/plugins/tidb-workflow-journal-store.d.ts +1 -20
- package/dist/plugins/tidb-workflow-journal-store.js +1 -34
- package/dist/plugins/tidb-workflow-run-store.d.ts +1 -61
- package/dist/plugins/tidb-workflow-run-store.js +1 -231
- package/dist/plugins/tool-result-store-sql.d.ts +25 -0
- package/dist/plugins/tool-result-store-sql.js +69 -0
- package/dist/plugins/workflow-journal-store-sql.d.ts +30 -0
- package/dist/plugins/workflow-journal-store-sql.js +53 -0
- package/dist/plugins/workflow-run-store-sql.d.ts +85 -0
- package/dist/plugins/workflow-run-store-sql.js +299 -0
- package/dist/plugins/write-behind-counter.d.ts +14 -3
- package/dist/plugins/write-behind-counter.js +39 -12
- package/dist/principal-jwt.d.ts +44 -0
- package/dist/principal-jwt.js +95 -0
- package/dist/security.d.ts +2 -58
- package/dist/security.js +3 -118
- package/dist/sema-registry.d.ts +5 -200
- package/dist/sema-registry.js +4 -567
- package/package.json +1 -1
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { randomUUID, createHash } from "node:crypto";
|
|
2
|
+
import { pgSafeJsonStringify } from "./pg-safe-json.js";
|
|
3
|
+
import { mysqlDriver, pgDriver } from "./sql-driver.js";
|
|
4
|
+
export function taskSignature(s) {
|
|
5
|
+
if (s.tag)
|
|
6
|
+
return `tag:${s.tag}`;
|
|
7
|
+
const canon = JSON.stringify({
|
|
8
|
+
taskType: s.taskType ?? "",
|
|
9
|
+
toolset: [...(s.toolset ?? [])].sort(),
|
|
10
|
+
targetLang: s.targetLang ?? "",
|
|
11
|
+
moduleCount: s.moduleCount ?? 0,
|
|
12
|
+
});
|
|
13
|
+
return `h:${createHash("sha256").update(canon).digest("hex").slice(0, 16)}`;
|
|
14
|
+
}
|
|
15
|
+
export function deriveOutcome(m, runStatus = "completed-graded") {
|
|
16
|
+
if (runStatus === "infra-aborted")
|
|
17
|
+
return "aborted";
|
|
18
|
+
const oracleGreen = m.oracleTotal != null && m.oracleTotal > 0 && m.oraclePassed === m.oracleTotal;
|
|
19
|
+
const buildGreen = (m.assembleExit == null || m.assembleExit === 0) && (m.lintExit == null || m.lintExit === 0);
|
|
20
|
+
const mergeGreen = m.mergeOk !== false;
|
|
21
|
+
if (oracleGreen && buildGreen && mergeGreen)
|
|
22
|
+
return "pass";
|
|
23
|
+
const anyGreen = oracleGreen || (m.oraclePassed != null && m.oraclePassed > 0) || m.mergeOk === true;
|
|
24
|
+
return anyGreen ? "partial" : "fail";
|
|
25
|
+
}
|
|
26
|
+
export function coreOutcomeToLedgerRow(o) {
|
|
27
|
+
const passed = typeof o.oracle?.oraclePassed === "number" ? o.oracle.oraclePassed : o.oracle?.green ? 1 : 0;
|
|
28
|
+
const total = typeof o.oracle?.oracleTotal === "number" ? o.oracle.oracleTotal : 1;
|
|
29
|
+
return {
|
|
30
|
+
taskId: o.runId.slice(0, 64),
|
|
31
|
+
model: (o.model ?? "unknown").slice(0, 190),
|
|
32
|
+
signatureInputs: {
|
|
33
|
+
tag: o.taskSignature.slice(0, 186),
|
|
34
|
+
...(o.signatureInputs?.toolset ? { toolset: o.signatureInputs.toolset } : {}),
|
|
35
|
+
...(o.signatureInputs?.targetLang ? { targetLang: o.signatureInputs.targetLang } : {}),
|
|
36
|
+
...(o.signatureInputs?.moduleCount !== undefined ? { moduleCount: o.signatureInputs.moduleCount } : {}),
|
|
37
|
+
},
|
|
38
|
+
mechanical: {
|
|
39
|
+
oraclePassed: passed,
|
|
40
|
+
oracleTotal: total,
|
|
41
|
+
...(o.costMicroUsd !== undefined ? { costMicroUsd: o.costMicroUsd } : {}),
|
|
42
|
+
...(o.turns !== undefined ? { turns: o.turns } : {}),
|
|
43
|
+
},
|
|
44
|
+
core: o,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export const PG_OUTCOME_LEDGER_SCHEMA = [
|
|
48
|
+
`CREATE TABLE IF NOT EXISTS outcome_ledger (
|
|
49
|
+
id VARCHAR(64) NOT NULL,
|
|
50
|
+
task_signature VARCHAR(190) NOT NULL,
|
|
51
|
+
model VARCHAR(190) NOT NULL,
|
|
52
|
+
task_id VARCHAR(64),
|
|
53
|
+
run_status VARCHAR(20) NOT NULL DEFAULT 'completed-graded',
|
|
54
|
+
route VARCHAR(16),
|
|
55
|
+
worker_count INTEGER,
|
|
56
|
+
oracle_passed INTEGER,
|
|
57
|
+
oracle_total INTEGER,
|
|
58
|
+
assemble_exit INTEGER,
|
|
59
|
+
lint_exit INTEGER,
|
|
60
|
+
merge_ok SMALLINT,
|
|
61
|
+
replan_triggers JSONB,
|
|
62
|
+
cost_micro_usd BIGINT,
|
|
63
|
+
turns INTEGER,
|
|
64
|
+
outcome VARCHAR(8),
|
|
65
|
+
llm_assisted JSONB,
|
|
66
|
+
signature_inputs JSONB,
|
|
67
|
+
-- design/73 §1 bridge: the VERBATIM core TaskOutcome fact (oracleHadRedRun / status / oracle blob) as it
|
|
68
|
+
-- came off core, kept alongside the derived mechanical columns. NULL when the caller recorded through the
|
|
69
|
+
-- non-core \`record()\` path (no core fact to bridge).
|
|
70
|
+
core_outcome JSONB,
|
|
71
|
+
created_at TIMESTAMPTZ(3) NOT NULL,
|
|
72
|
+
PRIMARY KEY (id)
|
|
73
|
+
)`,
|
|
74
|
+
`CREATE INDEX IF NOT EXISTS idx_outcome_ledger_sig_model ON outcome_ledger (task_signature, model, run_status)`,
|
|
75
|
+
`CREATE INDEX IF NOT EXISTS idx_outcome_ledger_outcome ON outcome_ledger (outcome)`,
|
|
76
|
+
`CREATE INDEX IF NOT EXISTS idx_outcome_ledger_created ON outcome_ledger (created_at)`,
|
|
77
|
+
];
|
|
78
|
+
export async function ensurePgOutcomeLedgerSchema(pool) {
|
|
79
|
+
for (const stmt of PG_OUTCOME_LEDGER_SCHEMA)
|
|
80
|
+
await pool.query(stmt);
|
|
81
|
+
}
|
|
82
|
+
export class SqlOutcomeLedger {
|
|
83
|
+
db;
|
|
84
|
+
constructor(db) {
|
|
85
|
+
this.db = db;
|
|
86
|
+
}
|
|
87
|
+
q(tidb, pg) {
|
|
88
|
+
return this.db.dialect === "tidb" ? tidb : pg;
|
|
89
|
+
}
|
|
90
|
+
json(value) {
|
|
91
|
+
return this.db.dialect === "tidb" ? JSON.stringify(value) : pgSafeJsonStringify(value);
|
|
92
|
+
}
|
|
93
|
+
async record(o) {
|
|
94
|
+
const id = randomUUID().replace(/-/g, "").slice(0, 32);
|
|
95
|
+
const sig = taskSignature(o.signatureInputs);
|
|
96
|
+
const m = o.mechanical;
|
|
97
|
+
const runStatus = o.runStatus ?? "completed-graded";
|
|
98
|
+
await this.db.query(this.q(`INSERT INTO outcome_ledger
|
|
99
|
+
(id, task_signature, model, task_id, run_status, route, worker_count, oracle_passed, oracle_total,
|
|
100
|
+
assemble_exit, lint_exit, merge_ok, replan_triggers, cost_micro_usd, turns, outcome,
|
|
101
|
+
llm_assisted, signature_inputs, core_outcome, created_at)
|
|
102
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, `INSERT INTO outcome_ledger
|
|
103
|
+
(id, task_signature, model, task_id, run_status, route, worker_count, oracle_passed, oracle_total,
|
|
104
|
+
assemble_exit, lint_exit, merge_ok, replan_triggers, cost_micro_usd, turns, outcome,
|
|
105
|
+
llm_assisted, signature_inputs, core_outcome, created_at)
|
|
106
|
+
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13::jsonb,$14,$15,$16,$17::jsonb,$18::jsonb,$19::jsonb,$20)`), [
|
|
107
|
+
id, sig, o.model, o.taskId ?? null, runStatus, m.route ?? null, m.workerCount ?? null,
|
|
108
|
+
m.oraclePassed ?? null, m.oracleTotal ?? null, m.assembleExit ?? null, m.lintExit ?? null,
|
|
109
|
+
m.mergeOk == null ? null : m.mergeOk ? 1 : 0,
|
|
110
|
+
m.replanTriggers ? this.json(m.replanTriggers) : null,
|
|
111
|
+
m.costMicroUsd ?? null, m.turns ?? null, deriveOutcome(m, runStatus),
|
|
112
|
+
o.llmAssisted ? this.json(o.llmAssisted) : null,
|
|
113
|
+
this.json(o.signatureInputs), o.core != null ? this.json(o.core) : null, new Date(),
|
|
114
|
+
]);
|
|
115
|
+
return id;
|
|
116
|
+
}
|
|
117
|
+
async recordCore(o) {
|
|
118
|
+
await this.record(coreOutcomeToLedgerRow(o));
|
|
119
|
+
}
|
|
120
|
+
async summary(opts = {}) {
|
|
121
|
+
const clauses = [];
|
|
122
|
+
const params = [];
|
|
123
|
+
if (!opts.includeAborted)
|
|
124
|
+
clauses.push("run_status = 'completed-graded'");
|
|
125
|
+
if (opts.taskSignature) {
|
|
126
|
+
params.push(opts.taskSignature);
|
|
127
|
+
clauses.push(this.q("task_signature = ?", `task_signature = $${params.length}`));
|
|
128
|
+
}
|
|
129
|
+
const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
|
|
130
|
+
const { rows } = await this.db.query(this.q(`SELECT task_signature, model, COUNT(*) n,
|
|
131
|
+
AVG(outcome = 'pass') pass_rate, AVG(cost_micro_usd) mean_cost
|
|
132
|
+
FROM outcome_ledger ${where}
|
|
133
|
+
GROUP BY task_signature, model
|
|
134
|
+
ORDER BY task_signature, model`, `SELECT task_signature, model, COUNT(*) n,
|
|
135
|
+
AVG((outcome = 'pass')::int) pass_rate, AVG(cost_micro_usd) mean_cost
|
|
136
|
+
FROM outcome_ledger ${where}
|
|
137
|
+
GROUP BY task_signature, model
|
|
138
|
+
ORDER BY task_signature, model`), params);
|
|
139
|
+
return rows.map((r) => ({
|
|
140
|
+
taskSignature: String(r.task_signature),
|
|
141
|
+
model: String(r.model),
|
|
142
|
+
n: Number(r.n),
|
|
143
|
+
passRate: Number(r.pass_rate),
|
|
144
|
+
meanCostMicroUsd: Number(r.mean_cost ?? 0),
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
export class TiDBOutcomeLedger extends SqlOutcomeLedger {
|
|
149
|
+
constructor(pool) {
|
|
150
|
+
super(mysqlDriver(pool));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
export class PgOutcomeLedger extends SqlOutcomeLedger {
|
|
154
|
+
constructor(pool) {
|
|
155
|
+
super(pgDriver(pool));
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
//# sourceMappingURL=outcome-ledger-sql.js.map
|
|
@@ -1,28 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import { type ApprovalRow, type ApprovalStatus } from "./tidb-approval-store.js";
|
|
3
|
-
export type { ApprovalRow, ApprovalStatus } from "./tidb-approval-store.js";
|
|
4
|
-
export declare const PG_APPROVAL_SCHEMA: string[];
|
|
5
|
-
export declare function ensureSchema(pool: Pool | PoolClient): Promise<void>;
|
|
6
|
-
export declare class PgApprovalStore {
|
|
7
|
-
private readonly pool;
|
|
8
|
-
constructor(pool: Pool);
|
|
9
|
-
createPending(id: string, scope: string | null, ctx: {
|
|
10
|
-
taskId?: string | null;
|
|
11
|
-
sessionId?: string | null;
|
|
12
|
-
owner?: string | null;
|
|
13
|
-
toolName: string;
|
|
14
|
-
args: unknown;
|
|
15
|
-
}): Promise<void>;
|
|
16
|
-
getStatus(id: string, scope: string | null): Promise<{
|
|
17
|
-
status: ApprovalStatus;
|
|
18
|
-
reason: string | null;
|
|
19
|
-
decidedBy: string | null;
|
|
20
|
-
} | undefined>;
|
|
21
|
-
decide(id: string, scope: string | null, decision: "approved" | "denied" | "expired", reason: string | null, decidedBy: string | null): Promise<boolean>;
|
|
22
|
-
listPending(scope: string | null, owner?: string): Promise<ApprovalRow[]>;
|
|
23
|
-
get(id: string, scope: string | null): Promise<ApprovalRow | undefined>;
|
|
24
|
-
getById(id: string): Promise<ApprovalRow | undefined>;
|
|
25
|
-
listPendingAll(): Promise<ApprovalRow[]>;
|
|
26
|
-
expireStale(olderThanMs: number): Promise<number>;
|
|
27
|
-
}
|
|
1
|
+
export { PgApprovalStore, PG_APPROVAL_SCHEMA, ensureSchema, type ApprovalRow, type ApprovalStatus, } from "./approval-store-sql.js";
|
|
28
2
|
//# sourceMappingURL=pg-approval-store.d.ts.map
|
|
@@ -1,84 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import { pgProtocolJsonStringify } from "./pg-safe-json.js";
|
|
3
|
-
export const PG_APPROVAL_SCHEMA = [
|
|
4
|
-
`CREATE TABLE IF NOT EXISTS approval (
|
|
5
|
-
id VARCHAR(64) NOT NULL,
|
|
6
|
-
task_id VARCHAR(64),
|
|
7
|
-
session_id VARCHAR(64),
|
|
8
|
-
owner VARCHAR(190),
|
|
9
|
-
-- Single-DB fleet scope guard (tenant isolation). NULLABLE on purpose: a NULL-scope row is an untenanted
|
|
10
|
-
-- run, and every read/decide path matches it with \`scope IS NOT DISTINCT FROM $n\` (the PG twin of TiDB
|
|
11
|
-
-- \`<=>\`) so NULL matches only NULL and one tenant's scope NEVER matches another's.
|
|
12
|
-
scope VARCHAR(190),
|
|
13
|
-
tool_name VARCHAR(190) NOT NULL,
|
|
14
|
-
args JSONB,
|
|
15
|
-
status VARCHAR(16) NOT NULL,
|
|
16
|
-
reason TEXT,
|
|
17
|
-
decided_by VARCHAR(190),
|
|
18
|
-
created_at TIMESTAMPTZ(3) NOT NULL,
|
|
19
|
-
decided_at TIMESTAMPTZ(3),
|
|
20
|
-
PRIMARY KEY (id)
|
|
21
|
-
)`,
|
|
22
|
-
`CREATE INDEX IF NOT EXISTS idx_approval_owner_status ON approval (owner, status)`,
|
|
23
|
-
`CREATE INDEX IF NOT EXISTS idx_approval_status ON approval (status)`,
|
|
24
|
-
`CREATE INDEX IF NOT EXISTS idx_approval_scope_status ON approval (scope, status)`,
|
|
25
|
-
];
|
|
26
|
-
export async function ensureSchema(pool) {
|
|
27
|
-
for (const stmt of PG_APPROVAL_SCHEMA)
|
|
28
|
-
await pool.query(stmt);
|
|
29
|
-
}
|
|
30
|
-
export class PgApprovalStore {
|
|
31
|
-
pool;
|
|
32
|
-
constructor(pool) {
|
|
33
|
-
this.pool = pool;
|
|
34
|
-
}
|
|
35
|
-
async createPending(id, scope, ctx) {
|
|
36
|
-
await this.pool.query("INSERT INTO approval (id, task_id, session_id, owner, scope, tool_name, args, status, created_at) " +
|
|
37
|
-
"VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,'pending',$8)", [
|
|
38
|
-
id,
|
|
39
|
-
ctx.taskId ?? null,
|
|
40
|
-
ctx.sessionId ?? null,
|
|
41
|
-
ctx.owner ?? null,
|
|
42
|
-
scope,
|
|
43
|
-
ctx.toolName,
|
|
44
|
-
ctx.args == null ? null : pgProtocolJsonStringify(ctx.args, "approval args"),
|
|
45
|
-
new Date(),
|
|
46
|
-
]);
|
|
47
|
-
}
|
|
48
|
-
async getStatus(id, scope) {
|
|
49
|
-
const res = await this.pool.query("SELECT status, reason, decided_by FROM approval WHERE id = $1 AND scope IS NOT DISTINCT FROM $2", [id, scope]);
|
|
50
|
-
const r = res.rows[0];
|
|
51
|
-
if (!r)
|
|
52
|
-
return undefined;
|
|
53
|
-
return { status: r.status, reason: r.reason ?? null, decidedBy: r.decided_by ?? null };
|
|
54
|
-
}
|
|
55
|
-
async decide(id, scope, decision, reason, decidedBy) {
|
|
56
|
-
const res = await this.pool.query("UPDATE approval SET status = $1, reason = $2, decided_by = $3, decided_at = $4 WHERE id = $5 AND scope IS NOT DISTINCT FROM $6 AND status = 'pending'", [decision, reason, decidedBy, new Date(), id, scope]);
|
|
57
|
-
return (res.rowCount ?? 0) === 1;
|
|
58
|
-
}
|
|
59
|
-
async listPending(scope, owner) {
|
|
60
|
-
const res = owner
|
|
61
|
-
? await this.pool.query("SELECT * FROM approval WHERE status = 'pending' AND scope IS NOT DISTINCT FROM $1 AND owner = $2 ORDER BY created_at ASC", [scope, owner])
|
|
62
|
-
: await this.pool.query("SELECT * FROM approval WHERE status = 'pending' AND scope IS NOT DISTINCT FROM $1 ORDER BY created_at ASC", [scope]);
|
|
63
|
-
return res.rows.map(mapRow);
|
|
64
|
-
}
|
|
65
|
-
async get(id, scope) {
|
|
66
|
-
const res = await this.pool.query("SELECT * FROM approval WHERE id = $1 AND scope IS NOT DISTINCT FROM $2", [id, scope]);
|
|
67
|
-
return res.rows[0] ? mapRow(res.rows[0]) : undefined;
|
|
68
|
-
}
|
|
69
|
-
async getById(id) {
|
|
70
|
-
const res = await this.pool.query("SELECT * FROM approval WHERE id = $1", [id]);
|
|
71
|
-
return res.rows[0] ? mapRow(res.rows[0]) : undefined;
|
|
72
|
-
}
|
|
73
|
-
async listPendingAll() {
|
|
74
|
-
const res = await this.pool.query("SELECT * FROM approval WHERE status = 'pending' ORDER BY created_at ASC");
|
|
75
|
-
return res.rows.map(mapRow);
|
|
76
|
-
}
|
|
77
|
-
async expireStale(olderThanMs) {
|
|
78
|
-
const cutoff = new Date(Date.now() - olderThanMs);
|
|
79
|
-
const res = await this.pool.query("UPDATE approval SET status = 'expired', reason = 'timed out before decision', decided_at = $1 " +
|
|
80
|
-
"WHERE status = 'pending' AND created_at < $2", [new Date(), cutoff]);
|
|
81
|
-
return res.rowCount ?? 0;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
1
|
+
export { PgApprovalStore, PG_APPROVAL_SCHEMA, ensureSchema, } from "./approval-store-sql.js";
|
|
84
2
|
//# sourceMappingURL=pg-approval-store.js.map
|
|
@@ -1,20 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import type { BreakerSnapshot, BreakerState } from "@sema-agent/core";
|
|
3
|
-
export declare const PG_BREAKER_STATE_SCHEMA: string[];
|
|
4
|
-
export declare function ensureSchema(pool: Pool | PoolClient): Promise<void>;
|
|
5
|
-
export declare class PgBreakerState implements BreakerState {
|
|
6
|
-
private readonly pool;
|
|
7
|
-
private readonly onWriteFail?;
|
|
8
|
-
private cache;
|
|
9
|
-
private timer?;
|
|
10
|
-
private readonly pending;
|
|
11
|
-
constructor(pool: Pool, onWriteFail?: ((streak: number) => void) | undefined);
|
|
12
|
-
private writeFailStreak;
|
|
13
|
-
get(key: string): BreakerSnapshot | undefined;
|
|
14
|
-
set(key: string, snap: BreakerSnapshot): void;
|
|
15
|
-
private writeThrough;
|
|
16
|
-
refresh(): Promise<void>;
|
|
17
|
-
startRefresh(intervalMs?: number): this;
|
|
18
|
-
stop(): void;
|
|
19
|
-
}
|
|
1
|
+
export { PgBreakerState, PG_BREAKER_STATE_SCHEMA, ensureSchema } from "./breaker-state-sql.js";
|
|
20
2
|
//# sourceMappingURL=pg-breaker-state.d.ts.map
|
|
@@ -1,89 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
`CREATE TABLE IF NOT EXISTS circuit_breaker (
|
|
3
|
-
breaker_key VARCHAR(190) NOT NULL,
|
|
4
|
-
phase VARCHAR(16) NOT NULL,
|
|
5
|
-
failures INTEGER NOT NULL DEFAULT 0,
|
|
6
|
-
opened_at TIMESTAMPTZ(3),
|
|
7
|
-
updated_at TIMESTAMPTZ(3) NOT NULL,
|
|
8
|
-
PRIMARY KEY (breaker_key)
|
|
9
|
-
)`,
|
|
10
|
-
];
|
|
11
|
-
export async function ensureSchema(pool) {
|
|
12
|
-
for (const stmt of PG_BREAKER_STATE_SCHEMA)
|
|
13
|
-
await pool.query(stmt);
|
|
14
|
-
}
|
|
15
|
-
export class PgBreakerState {
|
|
16
|
-
pool;
|
|
17
|
-
onWriteFail;
|
|
18
|
-
cache = new Map();
|
|
19
|
-
timer;
|
|
20
|
-
pending = new Set();
|
|
21
|
-
constructor(pool, onWriteFail) {
|
|
22
|
-
this.pool = pool;
|
|
23
|
-
this.onWriteFail = onWriteFail;
|
|
24
|
-
}
|
|
25
|
-
writeFailStreak = 0;
|
|
26
|
-
get(key) {
|
|
27
|
-
return this.cache.get(key);
|
|
28
|
-
}
|
|
29
|
-
set(key, snap) {
|
|
30
|
-
this.cache.set(key, snap);
|
|
31
|
-
this.pending.add(key);
|
|
32
|
-
void this.writeThrough(key, snap);
|
|
33
|
-
}
|
|
34
|
-
async writeThrough(key, snap) {
|
|
35
|
-
try {
|
|
36
|
-
await this.pool.query("INSERT INTO circuit_breaker (breaker_key, phase, failures, opened_at, updated_at) VALUES ($1,$2,$3,$4,$5) " +
|
|
37
|
-
"ON CONFLICT (breaker_key) DO UPDATE SET phase=EXCLUDED.phase, failures=EXCLUDED.failures, opened_at=EXCLUDED.opened_at, updated_at=EXCLUDED.updated_at", [key, snap.phase, snap.failures, snap.openedAt != null ? new Date(snap.openedAt) : null, new Date()]);
|
|
38
|
-
this.pending.delete(key);
|
|
39
|
-
if (this.writeFailStreak > 0) {
|
|
40
|
-
this.writeFailStreak = 0;
|
|
41
|
-
try {
|
|
42
|
-
this.onWriteFail?.(0);
|
|
43
|
-
}
|
|
44
|
-
catch { }
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
catch {
|
|
48
|
-
try {
|
|
49
|
-
this.onWriteFail?.(++this.writeFailStreak);
|
|
50
|
-
}
|
|
51
|
-
catch { }
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
async refresh() {
|
|
55
|
-
try {
|
|
56
|
-
const pendingAtStart = new Set(this.pending);
|
|
57
|
-
const guarded = (key) => this.pending.has(key) || pendingAtStart.has(key);
|
|
58
|
-
const res = await this.pool.query("SELECT breaker_key, phase, failures, opened_at FROM circuit_breaker");
|
|
59
|
-
const seen = new Set();
|
|
60
|
-
for (const r of res.rows) {
|
|
61
|
-
const key = String(r.breaker_key);
|
|
62
|
-
seen.add(key);
|
|
63
|
-
if (guarded(key))
|
|
64
|
-
continue;
|
|
65
|
-
this.cache.set(key, {
|
|
66
|
-
phase: r.phase,
|
|
67
|
-
failures: Number(r.failures),
|
|
68
|
-
openedAt: r.opened_at != null ? new Date(r.opened_at).getTime() : undefined,
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
for (const key of this.cache.keys())
|
|
72
|
-
if (!seen.has(key) && !guarded(key))
|
|
73
|
-
this.cache.delete(key);
|
|
74
|
-
}
|
|
75
|
-
catch {
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
startRefresh(intervalMs = 5_000) {
|
|
79
|
-
this.timer ??= setInterval(() => void this.refresh(), intervalMs);
|
|
80
|
-
this.timer.unref?.();
|
|
81
|
-
return this;
|
|
82
|
-
}
|
|
83
|
-
stop() {
|
|
84
|
-
if (this.timer)
|
|
85
|
-
clearInterval(this.timer);
|
|
86
|
-
this.timer = undefined;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
1
|
+
export { PgBreakerState, PG_BREAKER_STATE_SCHEMA, ensureSchema } from "./breaker-state-sql.js";
|
|
89
2
|
//# sourceMappingURL=pg-breaker-state.js.map
|
|
@@ -1,34 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import { type Checkpoint, type CheckpointStore, type CheckpointSummary, type CheckpointToken, type ResumeOutcome, type ResolveExpectation, type ReopenReason } from "@sema-agent/core";
|
|
3
|
-
import { type PendingCheckpoint } from "./tidb-checkpoint-store.js";
|
|
4
|
-
export declare class PgCheckpointStore implements CheckpointStore {
|
|
5
|
-
private readonly pool;
|
|
6
|
-
private readonly logger?;
|
|
7
|
-
constructor(pool: Pool, logger?: {
|
|
8
|
-
info?(msg: string, meta?: unknown): void;
|
|
9
|
-
} | undefined);
|
|
10
|
-
put(token: CheckpointToken, cp: Checkpoint): Promise<void>;
|
|
11
|
-
get(token: CheckpointToken): Promise<Checkpoint | null>;
|
|
12
|
-
resolve(token: CheckpointToken, scope: string, outcome: ResumeOutcome, expect?: ResolveExpectation): Promise<boolean>;
|
|
13
|
-
reopen(token: CheckpointToken, scope: string, reason: ReopenReason): Promise<boolean>;
|
|
14
|
-
setPendingSteer(token: CheckpointToken, scope: string, steer: {
|
|
15
|
-
text: string;
|
|
16
|
-
trusted: boolean;
|
|
17
|
-
}): Promise<boolean>;
|
|
18
|
-
expire(token: CheckpointToken, scope: string): Promise<boolean>;
|
|
19
|
-
reap(scope: string, cutoff: number): Promise<number>;
|
|
20
|
-
reapExpired(cutoff: number): Promise<number>;
|
|
21
|
-
listExpiredApprovalGates(cutoff: number, limit?: number): Promise<Array<{
|
|
22
|
-
sessionId: string;
|
|
23
|
-
scope: string;
|
|
24
|
-
}>>;
|
|
25
|
-
listPending(scope?: string): Promise<PendingCheckpoint[]>;
|
|
26
|
-
listByScope(scope: string): Promise<CheckpointSummary[]>;
|
|
27
|
-
findPendingTokenBySession(sessionId: string, scope?: string): Promise<CheckpointToken | null>;
|
|
28
|
-
peekPendingScope(sessionId: string): Promise<string | null | undefined>;
|
|
29
|
-
putCtx(sessionId: string, ctx: unknown): Promise<void>;
|
|
30
|
-
getCtx<T = unknown>(sessionId: string): Promise<T | null>;
|
|
31
|
-
reapCtx(cutoff: number): Promise<number>;
|
|
32
|
-
deleteBySession(sessionId: string, owner: string | null): Promise<number>;
|
|
33
|
-
}
|
|
1
|
+
export { PgCheckpointStore } from "./checkpoint-store-sql.js";
|
|
34
2
|
//# sourceMappingURL=pg-checkpoint-store.d.ts.map
|
|
@@ -1,190 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
import { redactDeep } from "../trace/redact.js";
|
|
3
|
-
import { tokenFingerprint } from "./tidb-checkpoint-store.js";
|
|
4
|
-
import { pgProtocolJsonStringify } from "./pg-safe-json.js";
|
|
5
|
-
import { parseJsonStrict as parseJson } from "./sql-row-helpers.js";
|
|
6
|
-
const MAX_TOOL_INPUT_CHARS = 8192;
|
|
7
|
-
const TERMINAL_BACKSTOP_MS = Math.max(60_000, Number(process.env.APPROVAL_TERMINAL_BACKSTOP_MS) || 30 * 86_400_000);
|
|
8
|
-
const TERMINAL_GRACE_MS = 3_600_000;
|
|
9
|
-
const PG_UNIQUE_VIOLATION = "23505";
|
|
10
|
-
function boundedToolInput(args) {
|
|
11
|
-
if (args === undefined)
|
|
12
|
-
return null;
|
|
13
|
-
const redacted = redactDeep(args);
|
|
14
|
-
const json = JSON.stringify(redacted);
|
|
15
|
-
if (json === undefined)
|
|
16
|
-
return null;
|
|
17
|
-
if (json.length > MAX_TOOL_INPUT_CHARS)
|
|
18
|
-
return { truncated: true, bytes: json.length };
|
|
19
|
-
return redacted;
|
|
20
|
-
}
|
|
21
|
-
export class PgCheckpointStore {
|
|
22
|
-
pool;
|
|
23
|
-
logger;
|
|
24
|
-
constructor(pool, logger) {
|
|
25
|
-
this.pool = pool;
|
|
26
|
-
this.logger = logger;
|
|
27
|
-
}
|
|
28
|
-
async put(token, cp) {
|
|
29
|
-
const pa = cp.pendingAction;
|
|
30
|
-
const version = checkpointVersionOf(cp);
|
|
31
|
-
const toolInput = boundedToolInput(pa?.args);
|
|
32
|
-
try {
|
|
33
|
-
await this.pool.query("INSERT INTO checkpoint (token, scope, session_id, version, status, tool_name, tool_call_id, tool_input, checkpoint, deadline, created_at, terminal_at, gate_kind, bound_input_hash, risk_descriptor) " +
|
|
34
|
-
"VALUES ($1,$2,$3,$4,'pending',$5,$6,$7::jsonb,$8::jsonb,$9,$10,$11,$12,$13,$14)", [
|
|
35
|
-
token,
|
|
36
|
-
cp.scope,
|
|
37
|
-
cp.sessionId,
|
|
38
|
-
version,
|
|
39
|
-
pa?.toolName ?? null,
|
|
40
|
-
pa?.toolCallId ?? null,
|
|
41
|
-
toolInput === null ? null : pgProtocolJsonStringify(toolInput, "approval tool_input"),
|
|
42
|
-
pgProtocolJsonStringify(cp, "checkpoint"),
|
|
43
|
-
cp.deadline ?? null,
|
|
44
|
-
cp.createdAt,
|
|
45
|
-
Math.max(cp.createdAt + TERMINAL_BACKSTOP_MS, (cp.deadline ?? 0) + TERMINAL_GRACE_MS),
|
|
46
|
-
cp.gate?.kind ?? null,
|
|
47
|
-
pa?.boundInputHash ?? null,
|
|
48
|
-
((g) => (g?.riskDescriptor ? pgProtocolJsonStringify(g.riskDescriptor, "risk descriptor") : null))(cp.gate),
|
|
49
|
-
]);
|
|
50
|
-
}
|
|
51
|
-
catch (e) {
|
|
52
|
-
if (e?.code === PG_UNIQUE_VIOLATION) {
|
|
53
|
-
throw new CheckpointError("checkpoint.already_exists", `checkpoint token already exists`);
|
|
54
|
-
}
|
|
55
|
-
throw e;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
async get(token) {
|
|
59
|
-
const res = await this.pool.query("SELECT version, status, checkpoint, outcome, reopen_reason, rev, pending_steer FROM checkpoint WHERE token = $1", [token]);
|
|
60
|
-
const r = res.rows[0];
|
|
61
|
-
if (!r)
|
|
62
|
-
return null;
|
|
63
|
-
const version = Number(r.version);
|
|
64
|
-
if (version > MAX_SUPPORTED_CHECKPOINT_VERSION) {
|
|
65
|
-
throw new Error(`checkpoint format version ${version} is newer than this build supports (max ${MAX_SUPPORTED_CHECKPOINT_VERSION}) — upgrade the service to resume it`);
|
|
66
|
-
}
|
|
67
|
-
const cp = parseJson(r.checkpoint);
|
|
68
|
-
cp.status = r.status;
|
|
69
|
-
const outcomeRaw = parseJson(r.outcome);
|
|
70
|
-
if (outcomeRaw)
|
|
71
|
-
cp.resolvedOutcome = winnerFromOutcome(outcomeRaw);
|
|
72
|
-
cp.reopenReason = r.reopen_reason ?? undefined;
|
|
73
|
-
cp.rev = r.rev == null ? 0 : Number(r.rev);
|
|
74
|
-
const steerRaw = parseJson(r.pending_steer);
|
|
75
|
-
if (steerRaw && cp.state)
|
|
76
|
-
cp.state.pendingSteer = steerRaw;
|
|
77
|
-
this.logger?.info?.("checkpoint_get", {
|
|
78
|
-
tokenFp: tokenFingerprint(token),
|
|
79
|
-
status: cp.status,
|
|
80
|
-
version,
|
|
81
|
-
hasWorkspaceHandle: !!cp.state?.workspaceHandle,
|
|
82
|
-
snapshotId: cp.state?.workspaceHandle?.snapshotId,
|
|
83
|
-
});
|
|
84
|
-
return cp;
|
|
85
|
-
}
|
|
86
|
-
async resolve(token, scope, outcome, expect) {
|
|
87
|
-
const params = [pgProtocolJsonStringify(outcome, "checkpoint outcome"), Date.now(), token, scope];
|
|
88
|
-
if (expect)
|
|
89
|
-
params.push(expect.rev);
|
|
90
|
-
const res = await this.pool.query("UPDATE checkpoint SET status = 'resolved', outcome = $1::jsonb, decided_at = $2, rev = rev + 1, reopen_reason = NULL WHERE token = $3 AND scope = $4 AND status = 'pending'" +
|
|
91
|
-
(expect ? " AND rev = $5" : ""), params);
|
|
92
|
-
return (res.rowCount ?? 0) === 1;
|
|
93
|
-
}
|
|
94
|
-
async reopen(token, scope, reason) {
|
|
95
|
-
const res = await this.pool.query("UPDATE checkpoint SET status = 'pending', reopen_reason = $1, rev = rev + 1 WHERE token = $2 AND scope = $3 AND status = 'resolved'", [reason, token, scope]);
|
|
96
|
-
return (res.rowCount ?? 0) === 1;
|
|
97
|
-
}
|
|
98
|
-
async setPendingSteer(token, scope, steer) {
|
|
99
|
-
const clean = validatePendingSteer(steer);
|
|
100
|
-
const res = await this.pool.query("UPDATE checkpoint SET pending_steer = $1 WHERE token = $2 AND scope = $3 AND status = 'pending'", [pgProtocolJsonStringify(clean, "pending steer"), token, scope]);
|
|
101
|
-
return (res.rowCount ?? 0) > 0;
|
|
102
|
-
}
|
|
103
|
-
async expire(token, scope) {
|
|
104
|
-
const res = await this.pool.query("UPDATE checkpoint SET status = 'expired', decided_at = $1 WHERE token = $2 AND scope = $3 AND status = 'pending'", [Date.now(), token, scope]);
|
|
105
|
-
return (res.rowCount ?? 0) === 1;
|
|
106
|
-
}
|
|
107
|
-
async reap(scope, cutoff) {
|
|
108
|
-
const res = await this.pool.query("UPDATE checkpoint SET status = 'expired', decided_at = $1 WHERE scope = $2 AND status = 'pending' AND deadline IS NOT NULL AND deadline <= $3", [Date.now(), scope, cutoff]);
|
|
109
|
-
return res.rowCount ?? 0;
|
|
110
|
-
}
|
|
111
|
-
async reapExpired(cutoff) {
|
|
112
|
-
const res = await this.pool.query("UPDATE checkpoint SET status = 'expired', decided_at = $1 " +
|
|
113
|
-
"WHERE status = 'pending' AND ((deadline IS NOT NULL AND deadline <= $2 AND (gate_kind IS NULL OR gate_kind NOT IN ('human','irreversible_ask') OR COALESCE(tool_name,'') = 'AskUserQuestion')) OR (terminal_at IS NOT NULL AND terminal_at <= $3))", [Date.now(), cutoff, cutoff]);
|
|
114
|
-
return res.rowCount ?? 0;
|
|
115
|
-
}
|
|
116
|
-
async listExpiredApprovalGates(cutoff, limit = 100) {
|
|
117
|
-
const res = await this.pool.query("SELECT session_id, scope FROM checkpoint WHERE status = 'pending' AND gate_kind IN ('human','irreversible_ask') " +
|
|
118
|
-
"AND COALESCE(tool_name,'') <> 'AskUserQuestion' AND deadline IS NOT NULL AND deadline <= $1 ORDER BY deadline ASC LIMIT $2", [cutoff, limit]);
|
|
119
|
-
return res.rows.map((r) => ({ sessionId: String(r.session_id), scope: String(r.scope) }));
|
|
120
|
-
}
|
|
121
|
-
async listPending(scope) {
|
|
122
|
-
const base = "SELECT c.session_id, c.scope, c.tool_name, c.tool_call_id, c.tool_input, c.bound_input_hash, c.risk_descriptor, c.created_at, c.deadline, ta.task_id " +
|
|
123
|
-
"FROM checkpoint c LEFT JOIN task_active ta ON ta.session_id = c.session_id WHERE c.status='pending'";
|
|
124
|
-
const res = scope
|
|
125
|
-
? await this.pool.query(`${base} AND c.scope=$1 ORDER BY c.created_at ASC`, [scope])
|
|
126
|
-
: await this.pool.query(`${base} ORDER BY c.created_at ASC`);
|
|
127
|
-
const out = res.rows.map((r) => {
|
|
128
|
-
const toolCallId = r.tool_call_id ?? null;
|
|
129
|
-
return {
|
|
130
|
-
sessionId: String(r.session_id),
|
|
131
|
-
scope: String(r.scope),
|
|
132
|
-
toolName: r.tool_name ?? null,
|
|
133
|
-
toolCallId,
|
|
134
|
-
boundCallId: toolCallId,
|
|
135
|
-
boundInputHash: r.bound_input_hash ?? null,
|
|
136
|
-
taskId: r.task_id ?? null,
|
|
137
|
-
input: r.tool_input ?? null,
|
|
138
|
-
createdAt: Number(r.created_at),
|
|
139
|
-
deadline: r.deadline == null ? null : Number(r.deadline),
|
|
140
|
-
riskDescriptor: parseJson(r.risk_descriptor),
|
|
141
|
-
};
|
|
142
|
-
});
|
|
143
|
-
return out.sort((a, b) => (b.riskDescriptor?.severity ?? 0) - (a.riskDescriptor?.severity ?? 0) || a.createdAt - b.createdAt);
|
|
144
|
-
}
|
|
145
|
-
async listByScope(scope) {
|
|
146
|
-
const res = await this.pool.query("SELECT checkpoint, status FROM checkpoint WHERE status = 'pending' AND scope = $1 ORDER BY created_at ASC LIMIT 500", [scope]);
|
|
147
|
-
const out = [];
|
|
148
|
-
for (const r of res.rows) {
|
|
149
|
-
const cp = parseJson(r.checkpoint);
|
|
150
|
-
if (!cp)
|
|
151
|
-
continue;
|
|
152
|
-
cp.status = r.status;
|
|
153
|
-
out.push(summarizeCheckpoint(cp));
|
|
154
|
-
}
|
|
155
|
-
return out;
|
|
156
|
-
}
|
|
157
|
-
async findPendingTokenBySession(sessionId, scope) {
|
|
158
|
-
const res = scope
|
|
159
|
-
? await this.pool.query("SELECT token FROM checkpoint WHERE session_id=$1 AND scope=$2 AND status='pending' LIMIT 1", [sessionId, scope])
|
|
160
|
-
: await this.pool.query("SELECT token FROM checkpoint WHERE session_id=$1 AND status='pending' LIMIT 1", [sessionId]);
|
|
161
|
-
return res.rows[0] ? String(res.rows[0].token) : null;
|
|
162
|
-
}
|
|
163
|
-
async peekPendingScope(sessionId) {
|
|
164
|
-
const res = await this.pool.query("SELECT scope FROM checkpoint WHERE session_id=$1 AND status='pending' LIMIT 1", [sessionId]);
|
|
165
|
-
if (!res.rows[0])
|
|
166
|
-
return undefined;
|
|
167
|
-
return res.rows[0].scope ?? null;
|
|
168
|
-
}
|
|
169
|
-
async putCtx(sessionId, ctx) {
|
|
170
|
-
await this.pool.query("INSERT INTO checkpoint_ctx (session_id, ctx, updated_at) VALUES ($1,$2::jsonb,$3) " +
|
|
171
|
-
"ON CONFLICT (session_id) DO UPDATE SET ctx = EXCLUDED.ctx, updated_at = EXCLUDED.updated_at", [sessionId, pgProtocolJsonStringify(ctx, "checkpoint ctx"), Date.now()]);
|
|
172
|
-
}
|
|
173
|
-
async getCtx(sessionId) {
|
|
174
|
-
const res = await this.pool.query("SELECT ctx FROM checkpoint_ctx WHERE session_id=$1", [sessionId]);
|
|
175
|
-
return res.rows[0] ? parseJson(res.rows[0].ctx) : null;
|
|
176
|
-
}
|
|
177
|
-
async reapCtx(cutoff) {
|
|
178
|
-
const res = await this.pool.query("DELETE FROM checkpoint_ctx WHERE updated_at < $1 " +
|
|
179
|
-
"AND session_id NOT IN (SELECT session_id FROM checkpoint WHERE status='pending') " +
|
|
180
|
-
"AND session_id NOT IN (SELECT session_id FROM task_active)", [cutoff]);
|
|
181
|
-
return res.rowCount ?? 0;
|
|
182
|
-
}
|
|
183
|
-
async deleteBySession(sessionId, owner) {
|
|
184
|
-
const ownerGuard = "EXISTS (SELECT 1 FROM session_meta sm WHERE sm.session_id = $1 AND sm.owner IS NOT DISTINCT FROM $2)";
|
|
185
|
-
const res = await this.pool.query(`DELETE FROM checkpoint WHERE session_id = $1 AND ${ownerGuard}`, [sessionId, owner]);
|
|
186
|
-
await this.pool.query(`DELETE FROM checkpoint_ctx WHERE session_id = $1 AND ${ownerGuard}`, [sessionId, owner]);
|
|
187
|
-
return res.rowCount ?? 0;
|
|
188
|
-
}
|
|
189
|
-
}
|
|
1
|
+
export { PgCheckpointStore } from "./checkpoint-store-sql.js";
|
|
190
2
|
//# sourceMappingURL=pg-checkpoint-store.js.map
|