@sema-agent/server 1.315.0 → 1.317.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.
Files changed (133) hide show
  1. package/README.md +9 -0
  2. package/README.zh-CN.md +7 -0
  3. package/dist/config-types.d.ts +1 -1
  4. package/dist/config.d.ts +14 -0
  5. package/dist/config.js +148 -45
  6. package/dist/elicitation.js +2 -2
  7. package/dist/http/idempotency.d.ts +1 -0
  8. package/dist/http/idempotency.js +3 -0
  9. package/dist/http/principal-gate.d.ts +12 -0
  10. package/dist/http/principal-gate.js +52 -0
  11. package/dist/http/route-ctx.d.ts +116 -0
  12. package/dist/http/route-ctx.js +2 -0
  13. package/dist/http/routes/approvals-assistant.d.ts +11 -0
  14. package/dist/http/routes/approvals-assistant.js +530 -0
  15. package/dist/http/routes/attachments.d.ts +4 -0
  16. package/dist/http/routes/attachments.js +106 -0
  17. package/dist/http/routes/capabilities.d.ts +4 -0
  18. package/dist/http/routes/capabilities.js +111 -0
  19. package/dist/http/routes/fleet.d.ts +4 -0
  20. package/dist/http/routes/fleet.js +147 -0
  21. package/dist/http/routes/images.d.ts +20 -0
  22. package/dist/http/routes/images.js +572 -0
  23. package/dist/http/routes/leader.d.ts +4 -0
  24. package/dist/http/routes/leader.js +48 -0
  25. package/dist/http/routes/memory-policy.d.ts +4 -0
  26. package/dist/http/routes/memory-policy.js +105 -0
  27. package/dist/http/routes/notify-wake.d.ts +4 -0
  28. package/dist/http/routes/notify-wake.js +133 -0
  29. package/dist/http/routes/observability.d.ts +4 -0
  30. package/dist/http/routes/observability.js +63 -0
  31. package/dist/http/routes/runs.d.ts +19 -0
  32. package/dist/http/routes/runs.js +967 -0
  33. package/dist/http/routes/session-sync.d.ts +36 -0
  34. package/dist/http/routes/session-sync.js +513 -0
  35. package/dist/http/routes/sessions-list.d.ts +4 -0
  36. package/dist/http/routes/sessions-list.js +117 -0
  37. package/dist/http/routes/sessions.d.ts +17 -0
  38. package/dist/http/routes/sessions.js +746 -0
  39. package/dist/http/routes/side-query.d.ts +4 -0
  40. package/dist/http/routes/side-query.js +88 -0
  41. package/dist/http/routes/tasks.d.ts +4 -0
  42. package/dist/http/routes/tasks.js +632 -0
  43. package/dist/http/routes/trace-usage.d.ts +4 -0
  44. package/dist/http/routes/trace-usage.js +239 -0
  45. package/dist/http/routes/workflows.d.ts +5 -0
  46. package/dist/http/routes/workflows.js +337 -0
  47. package/dist/http/run-meta.d.ts +11 -0
  48. package/dist/http/run-meta.js +16 -0
  49. package/dist/http/send.d.ts +7 -0
  50. package/dist/http/send.js +34 -0
  51. package/dist/http/server.d.ts +12 -12
  52. package/dist/http/server.js +289 -5502
  53. package/dist/http/sse-log.d.ts +25 -0
  54. package/dist/http/sse-log.js +59 -0
  55. package/dist/http/wire-types.d.ts +6 -0
  56. package/dist/http/workspace-content.d.ts +3 -0
  57. package/dist/http/workspace-content.js +20 -0
  58. package/dist/leader/endpoint.js +4 -4
  59. package/dist/main.js +5 -5
  60. package/dist/plugins/approval-store-sql.d.ts +52 -0
  61. package/dist/plugins/approval-store-sql.js +119 -0
  62. package/dist/plugins/breaker-state-sql.d.ts +29 -0
  63. package/dist/plugins/breaker-state-sql.js +104 -0
  64. package/dist/plugins/file-snapshot-store-sql.d.ts +38 -0
  65. package/dist/plugins/file-snapshot-store-sql.js +210 -0
  66. package/dist/plugins/image-index-sql.d.ts +33 -0
  67. package/dist/plugins/image-index-sql.js +328 -0
  68. package/dist/plugins/outcome-ledger-sql.d.ts +70 -0
  69. package/dist/plugins/outcome-ledger-sql.js +158 -0
  70. package/dist/plugins/pg-approval-store.d.ts +1 -27
  71. package/dist/plugins/pg-approval-store.js +1 -83
  72. package/dist/plugins/pg-breaker-state.d.ts +1 -19
  73. package/dist/plugins/pg-breaker-state.js +1 -88
  74. package/dist/plugins/pg-file-snapshot-store.d.ts +1 -27
  75. package/dist/plugins/pg-file-snapshot-store.js +1 -190
  76. package/dist/plugins/pg-image-index.d.ts +1 -21
  77. package/dist/plugins/pg-image-index.js +1 -217
  78. package/dist/plugins/pg-outcome-ledger.d.ts +2 -22
  79. package/dist/plugins/pg-outcome-ledger.js +1 -104
  80. package/dist/plugins/pg-resume-anchor-store.d.ts +1 -13
  81. package/dist/plugins/pg-resume-anchor-store.js +1 -22
  82. package/dist/plugins/pg-run-store.d.ts +1 -75
  83. package/dist/plugins/pg-run-store.js +1 -287
  84. package/dist/plugins/pg-session-policy-store.d.ts +1 -11
  85. package/dist/plugins/pg-session-policy-store.js +1 -90
  86. package/dist/plugins/pg-tool-result-store.d.ts +1 -15
  87. package/dist/plugins/pg-tool-result-store.js +1 -52
  88. package/dist/plugins/pg-workflow-journal-store.d.ts +1 -20
  89. package/dist/plugins/pg-workflow-journal-store.js +1 -34
  90. package/dist/plugins/pg-workflow-run-store.d.ts +1 -55
  91. package/dist/plugins/pg-workflow-run-store.js +1 -220
  92. package/dist/plugins/remote-env-host.js +4 -3
  93. package/dist/plugins/resume-anchor-store-sql.d.ts +23 -0
  94. package/dist/plugins/resume-anchor-store-sql.js +38 -0
  95. package/dist/plugins/run-store-sql.d.ts +89 -0
  96. package/dist/plugins/run-store-sql.js +397 -0
  97. package/dist/plugins/session-policy-store-sql.d.ts +22 -0
  98. package/dist/plugins/session-policy-store-sql.js +109 -0
  99. package/dist/plugins/tidb-approval-store.d.ts +1 -39
  100. package/dist/plugins/tidb-approval-store.js +1 -71
  101. package/dist/plugins/tidb-breaker-state.d.ts +1 -17
  102. package/dist/plugins/tidb-breaker-state.js +1 -74
  103. package/dist/plugins/tidb-file-snapshot-store.d.ts +1 -27
  104. package/dist/plugins/tidb-file-snapshot-store.js +1 -192
  105. package/dist/plugins/tidb-image-index.d.ts +1 -19
  106. package/dist/plugins/tidb-image-index.js +1 -149
  107. package/dist/plugins/tidb-outcome-ledger.d.ts +1 -57
  108. package/dist/plugins/tidb-outcome-ledger.js +1 -97
  109. package/dist/plugins/tidb-resume-anchor-store.d.ts +1 -13
  110. package/dist/plugins/tidb-resume-anchor-store.js +1 -22
  111. package/dist/plugins/tidb-run-store.d.ts +1 -75
  112. package/dist/plugins/tidb-run-store.js +1 -306
  113. package/dist/plugins/tidb-session-policy-store.d.ts +1 -11
  114. package/dist/plugins/tidb-session-policy-store.js +1 -86
  115. package/dist/plugins/tidb-tool-result-store.d.ts +1 -13
  116. package/dist/plugins/tidb-tool-result-store.js +1 -38
  117. package/dist/plugins/tidb-workflow-journal-store.d.ts +1 -20
  118. package/dist/plugins/tidb-workflow-journal-store.js +1 -34
  119. package/dist/plugins/tidb-workflow-run-store.d.ts +1 -61
  120. package/dist/plugins/tidb-workflow-run-store.js +1 -231
  121. package/dist/plugins/tool-result-store-sql.d.ts +25 -0
  122. package/dist/plugins/tool-result-store-sql.js +69 -0
  123. package/dist/plugins/workflow-journal-store-sql.d.ts +30 -0
  124. package/dist/plugins/workflow-journal-store-sql.js +53 -0
  125. package/dist/plugins/workflow-run-store-sql.d.ts +85 -0
  126. package/dist/plugins/workflow-run-store-sql.js +299 -0
  127. package/dist/question.js +2 -2
  128. package/dist/run-local.js +1 -1
  129. package/dist/tool-approval.js +2 -2
  130. package/dist/trace/ledger-sink.js +1 -1
  131. package/dist/trace/project.d.ts +1 -0
  132. package/dist/trace/project.js +3 -0
  133. package/package.json +1 -1
@@ -0,0 +1,210 @@
1
+ import { captureManifest, applyManifest, DEFAULT_SNAPSHOT_BOUNDS } from "@sema-agent/core";
2
+ import { createHash } from "node:crypto";
3
+ import { SqlBlobBackend, sqlBlobSizes } from "./blob-backend.js";
4
+ import { mysqlDriver, pgDriver } from "./sql-driver.js";
5
+ export class SqlFileSnapshotStore {
6
+ db;
7
+ pool;
8
+ bounds;
9
+ inFlight = new Set();
10
+ blobs;
11
+ onSkippedVanished = undefined;
12
+ constructor(db, pool, blobBackend, bounds = DEFAULT_SNAPSHOT_BOUNDS) {
13
+ this.db = db;
14
+ this.pool = pool;
15
+ this.bounds = bounds;
16
+ this.blobs = blobBackend ?? new SqlBlobBackend(this.db.dialect, this.pool);
17
+ }
18
+ q(tidb, pg) {
19
+ return this.db.dialect === "tidb" ? tidb : pg;
20
+ }
21
+ async putBlobRow(hash, bytes) {
22
+ await this.blobs.putBlob(hash, bytes);
23
+ }
24
+ async putBlob(hash, bytes) {
25
+ if (createHash("sha256").update(bytes).digest("hex") !== hash) {
26
+ return { ok: false, error: { code: "read_failed", message: `putBlob ${hash} fails content-address integrity — nothing stored` } };
27
+ }
28
+ try {
29
+ await this.putBlobRow(hash, bytes);
30
+ return { ok: true };
31
+ }
32
+ catch (err) {
33
+ return { ok: false, error: { code: "restore_failed", message: `putBlob ${hash} write/upload failed: ${err.message}` } };
34
+ }
35
+ }
36
+ async snapshot(scope, key, env, root, signal) {
37
+ const flightKey = `${scope}\x00${key}`;
38
+ if (this.inFlight.has(flightKey))
39
+ return { ok: true };
40
+ this.inFlight.add(flightKey);
41
+ try {
42
+ if (await this.has(scope, key))
43
+ return { ok: true };
44
+ let cap;
45
+ try {
46
+ cap = await captureManifest(env, root, this.bounds, signal, async (hash, bytes) => {
47
+ await this.putBlobRow(hash, bytes);
48
+ });
49
+ }
50
+ catch (err) {
51
+ return { ok: false, error: { code: "restore_failed", message: `snapshot blob write failed: ${err.message}` } };
52
+ }
53
+ if (!cap.ok)
54
+ return { ok: false, error: cap.error };
55
+ if (cap.skippedVanished > 0 && this.onSkippedVanished) {
56
+ try {
57
+ void Promise.resolve(this.onSkippedVanished(cap.skippedVanished)).catch(() => { });
58
+ }
59
+ catch { }
60
+ }
61
+ await this.tx(async (conn) => {
62
+ const exists = await conn.query(this.q("SELECT 1 FROM snapshot_manifest WHERE scope = ? AND snap_key = ? LIMIT 1", "SELECT 1 FROM snapshot_manifest WHERE scope = $1 AND snap_key = $2 LIMIT 1"), [scope, key]);
63
+ if (exists.rows[0])
64
+ return;
65
+ for (const [relPath, hash] of cap.value) {
66
+ await conn.query(this.q("INSERT INTO snapshot_manifest (scope, snap_key, rel_path, blob_hash) VALUES (?,?,?,?)", "INSERT INTO snapshot_manifest (scope, snap_key, rel_path, blob_hash) VALUES ($1,$2,$3,$4)"), [scope, key, relPath, hash]);
67
+ }
68
+ });
69
+ return { ok: true };
70
+ }
71
+ catch (err) {
72
+ return { ok: false, error: { code: "restore_failed", message: `snapshot persist failed: ${err.message}` } };
73
+ }
74
+ finally {
75
+ this.inFlight.delete(flightKey);
76
+ }
77
+ }
78
+ async importManifest(scope, key, manifest, srcGetBlob) {
79
+ const flightKey = `${scope}\x00${key}`;
80
+ if (this.inFlight.has(flightKey))
81
+ return { ok: true };
82
+ this.inFlight.add(flightKey);
83
+ try {
84
+ if (await this.has(scope, key))
85
+ return { ok: true };
86
+ for (const hash of new Set(manifest.values())) {
87
+ let bytes;
88
+ try {
89
+ bytes = await srcGetBlob(hash);
90
+ }
91
+ catch (err) {
92
+ return { ok: false, error: { code: "read_failed", message: `source blob ${hash} fetch failed: ${err.message}` } };
93
+ }
94
+ if (!bytes)
95
+ return { ok: false, error: { code: "read_failed", message: `missing source blob ${hash}` } };
96
+ if (createHash("sha256").update(bytes).digest("hex") !== hash) {
97
+ return { ok: false, error: { code: "read_failed", message: `source blob ${hash} fails content-address integrity` } };
98
+ }
99
+ await this.putBlobRow(hash, bytes);
100
+ }
101
+ await this.tx(async (conn) => {
102
+ const exists = await conn.query(this.q("SELECT 1 FROM snapshot_manifest WHERE scope = ? AND snap_key = ? LIMIT 1", "SELECT 1 FROM snapshot_manifest WHERE scope = $1 AND snap_key = $2 LIMIT 1"), [scope, key]);
103
+ if (exists.rows[0])
104
+ return;
105
+ for (const [relPath, hash] of manifest) {
106
+ await conn.query(this.q("INSERT INTO snapshot_manifest (scope, snap_key, rel_path, blob_hash) VALUES (?,?,?,?)", "INSERT INTO snapshot_manifest (scope, snap_key, rel_path, blob_hash) VALUES ($1,$2,$3,$4)"), [scope, key, relPath, hash]);
107
+ }
108
+ });
109
+ return { ok: true };
110
+ }
111
+ catch (err) {
112
+ return { ok: false, error: { code: "restore_failed", message: `import persist failed: ${err.message}` } };
113
+ }
114
+ finally {
115
+ this.inFlight.delete(flightKey);
116
+ }
117
+ }
118
+ async restore(scope, key, env, root, signal) {
119
+ try {
120
+ const { rows } = await this.db.query(this.q("SELECT rel_path, blob_hash FROM snapshot_manifest WHERE scope = ? AND snap_key = ?", "SELECT rel_path, blob_hash FROM snapshot_manifest WHERE scope = $1 AND snap_key = $2"), [scope, key]);
121
+ if (rows.length === 0)
122
+ return { ok: false, error: { code: "not_found", message: `no file snapshot for ${scope}/${key}` } };
123
+ const manifest = new Map(rows.map((r) => [String(r.rel_path), String(r.blob_hash)]));
124
+ return await applyManifest(env, root, this.bounds, signal, manifest, (hash) => this.blobs.getBlob(hash));
125
+ }
126
+ catch (err) {
127
+ return { ok: false, error: { code: "restore_failed", message: `restore blob read failed: ${err.message}` } };
128
+ }
129
+ }
130
+ async has(scope, key) {
131
+ const { rows } = await this.db.query(this.q("SELECT 1 FROM snapshot_manifest WHERE scope = ? AND snap_key = ? LIMIT 1", "SELECT 1 FROM snapshot_manifest WHERE scope = $1 AND snap_key = $2 LIMIT 1"), [scope, key]);
132
+ return Boolean(rows[0]);
133
+ }
134
+ async listKeys(scope) {
135
+ const { rows } = await this.db.query(this.q("SELECT DISTINCT snap_key FROM snapshot_manifest WHERE scope = ?", "SELECT DISTINCT snap_key FROM snapshot_manifest WHERE scope = $1"), [scope]);
136
+ return rows.map((r) => String(r.snap_key));
137
+ }
138
+ async exportManifest(scope, key) {
139
+ const { rows } = await this.db.query(this.q("SELECT rel_path, blob_hash FROM snapshot_manifest WHERE scope = ? AND snap_key = ?", "SELECT rel_path, blob_hash FROM snapshot_manifest WHERE scope = $1 AND snap_key = $2"), [scope, key]);
140
+ if (rows.length === 0)
141
+ return null;
142
+ return new Map(rows.map((r) => [String(r.rel_path), String(r.blob_hash)]));
143
+ }
144
+ async getBlob(hash) {
145
+ return this.blobs.getBlob(hash);
146
+ }
147
+ async hasBlobs(hashes) {
148
+ return this.blobs.hasBlobs(hashes);
149
+ }
150
+ async blobSizes(hashes) {
151
+ return sqlBlobSizes(this.db.dialect, this.pool, hashes);
152
+ }
153
+ async reap(scope, keepKeys) {
154
+ return this.tx(async (conn) => {
155
+ const { rows: keys } = await conn.query(this.q("SELECT DISTINCT snap_key FROM snapshot_manifest WHERE scope = ?", "SELECT DISTINCT snap_key FROM snapshot_manifest WHERE scope = $1"), [scope]);
156
+ const drop = keys.map((k) => String(k.snap_key)).filter((k) => !keepKeys.includes(k));
157
+ for (const k of drop) {
158
+ await conn.query(this.q("DELETE FROM snapshot_manifest WHERE scope = ? AND snap_key = ?", "DELETE FROM snapshot_manifest WHERE scope = $1 AND snap_key = $2"), [scope, k]);
159
+ }
160
+ return drop.length;
161
+ });
162
+ }
163
+ async deleteBySession(scope) {
164
+ const { affected } = await this.db.query(this.q("DELETE FROM snapshot_manifest WHERE scope = ?", "DELETE FROM snapshot_manifest WHERE scope = $1"), [scope]);
165
+ return affected;
166
+ }
167
+ async gcOrphanBlobs() {
168
+ const { rows } = await this.db
169
+ .query("SELECT blob_hash FROM snapshot_blob WHERE blob_hash NOT IN (SELECT blob_hash FROM snapshot_manifest)")
170
+ .catch(() => ({ rows: [], affected: 0 }));
171
+ const orphans = rows.map((r) => String(r.blob_hash));
172
+ if (orphans.length === 0)
173
+ return 0;
174
+ return this.blobs.deleteBlobs(orphans);
175
+ }
176
+ async sweepOrphanBlobs() {
177
+ return this.gcOrphanBlobs();
178
+ }
179
+ async tx(fn) {
180
+ const conn = await this.db.connect();
181
+ try {
182
+ await conn.begin();
183
+ const out = await fn(conn);
184
+ await conn.commit();
185
+ return out;
186
+ }
187
+ catch (err) {
188
+ try {
189
+ await conn.rollback();
190
+ }
191
+ catch {
192
+ }
193
+ throw err;
194
+ }
195
+ finally {
196
+ conn.release();
197
+ }
198
+ }
199
+ }
200
+ export class TiDBFileSnapshotStore extends SqlFileSnapshotStore {
201
+ constructor(pool, blobBackend, bounds = DEFAULT_SNAPSHOT_BOUNDS) {
202
+ super(mysqlDriver(pool), pool, blobBackend, bounds);
203
+ }
204
+ }
205
+ export class PgFileSnapshotStore extends SqlFileSnapshotStore {
206
+ constructor(pool, blobBackend, bounds = DEFAULT_SNAPSHOT_BOUNDS) {
207
+ super(pgDriver(pool), pool, blobBackend, bounds);
208
+ }
209
+ }
210
+ //# sourceMappingURL=file-snapshot-store-sql.js.map
@@ -0,0 +1,33 @@
1
+ import type { Pool as MySqlPool } from "mysql2/promise";
2
+ import type { Pool as PgPool, PoolClient } from "pg";
3
+ import { type ImageStatus, type ImageIndexEntry, type ImageIndexUpsert, type ImageViewer, type ImageListFilter } from "./store-contracts.js";
4
+ import { type SqlDriver } from "./sql-driver.js";
5
+ export type { ImageNestedBuildMode, ImageCapabilities, ImagePodContract, ImageStatus, ImageVisibility, ImageIndexEntry, ImageIndexUpsert, ImageViewer, ImageListFilter, ImageRow, } from "./store-contracts.js";
6
+ export { mapImageRow as mapRow } from "./store-contracts.js";
7
+ export declare const PG_IMAGE_INDEX_SCHEMA: string[];
8
+ export declare function ensureSchema(pool: PgPool | PoolClient): Promise<void>;
9
+ export declare class SqlImageIndex {
10
+ protected readonly db: SqlDriver;
11
+ constructor(db: SqlDriver);
12
+ private q;
13
+ static idFor(repo: string, digest: string): string;
14
+ upsert(e: ImageIndexUpsert): Promise<string>;
15
+ registerBuilding(e: ImageIndexUpsert): Promise<string>;
16
+ getById(id: string): Promise<ImageIndexEntry | null>;
17
+ getByDigest(digest: string): Promise<ImageIndexEntry | null>;
18
+ latestPublished(profile: string, viewer: ImageViewer): Promise<ImageIndexEntry | null>;
19
+ list(filter: ImageListFilter): Promise<{
20
+ entries: ImageIndexEntry[];
21
+ nextCursor: string | null;
22
+ }>;
23
+ setStatus(id: string, status: ImageStatus, opts?: {
24
+ supersedes?: string | null;
25
+ }): Promise<void>;
26
+ }
27
+ export declare class TiDBImageIndex extends SqlImageIndex {
28
+ constructor(pool: MySqlPool);
29
+ }
30
+ export declare class PgImageIndex extends SqlImageIndex {
31
+ constructor(pool: PgPool);
32
+ }
33
+ //# sourceMappingURL=image-index-sql.d.ts.map
@@ -0,0 +1,328 @@
1
+ import { createHash } from "node:crypto";
2
+ import { pgSafeJsonStringify, pgSanitizeText, pgHasUnstorable, PgUnstorableError } from "./pg-safe-json.js";
3
+ import { mapImageRow as mapRow, } from "./store-contracts.js";
4
+ import { mysqlDriver, pgDriver } from "./sql-driver.js";
5
+ export { mapImageRow as mapRow } from "./store-contracts.js";
6
+ export const PG_IMAGE_INDEX_SCHEMA = [
7
+ `CREATE TABLE IF NOT EXISTS sandbox_image_index (
8
+ id VARCHAR(64) NOT NULL,
9
+ profile VARCHAR(64) NOT NULL,
10
+ bands JSONB,
11
+ repo VARCHAR(255) NOT NULL,
12
+ tag VARCHAR(128) NOT NULL,
13
+ digest VARCHAR(80) NOT NULL,
14
+ toolchain_versions JSONB,
15
+ capabilities JSONB,
16
+ pod_contract JSONB,
17
+ size_bytes BIGINT,
18
+ status VARCHAR(16) NOT NULL DEFAULT 'building',
19
+ visibility VARCHAR(16) NOT NULL DEFAULT 'public',
20
+ tenant_id VARCHAR(64),
21
+ manifest_sha VARCHAR(64),
22
+ recipe_git_sha VARCHAR(64),
23
+ generator_version VARCHAR(32),
24
+ build_date TIMESTAMPTZ(3),
25
+ supersedes VARCHAR(64),
26
+ signed SMALLINT NOT NULL DEFAULT 0,
27
+ created_at TIMESTAMPTZ(3) NOT NULL,
28
+ updated_at TIMESTAMPTZ(3) NOT NULL,
29
+ PRIMARY KEY (id)
30
+ )`,
31
+ `CREATE UNIQUE INDEX IF NOT EXISTS uq_repo_digest ON sandbox_image_index (repo, digest)`,
32
+ `CREATE INDEX IF NOT EXISTS idx_profile_status ON sandbox_image_index (profile, status, visibility)`,
33
+ `CREATE INDEX IF NOT EXISTS idx_digest ON sandbox_image_index (digest)`,
34
+ `CREATE INDEX IF NOT EXISTS idx_tenant ON sandbox_image_index (tenant_id, status)`,
35
+ ];
36
+ export async function ensureSchema(pool) {
37
+ for (const stmt of PG_IMAGE_INDEX_SCHEMA)
38
+ await pool.query(stmt);
39
+ }
40
+ const MAX_LIMIT = 200;
41
+ const DEFAULT_LIMIT = 50;
42
+ function visibilityClauseTidb(viewer) {
43
+ if (viewer.operator)
44
+ return { sql: "1=1", params: [] };
45
+ if (viewer.tenantId)
46
+ return { sql: "(visibility='public' OR tenant_id=?)", params: [viewer.tenantId] };
47
+ return { sql: "visibility='public'", params: [] };
48
+ }
49
+ function visibilityClausePg(viewer, startIdx) {
50
+ if (viewer.operator)
51
+ return { sql: "1=1", params: [], nextIdx: startIdx };
52
+ if (viewer.tenantId)
53
+ return {
54
+ sql: `(visibility = 'public' OR tenant_id = $${startIdx})`,
55
+ params: [viewer.tenantId],
56
+ nextIdx: startIdx + 1,
57
+ };
58
+ return { sql: "visibility = 'public'", params: [], nextIdx: startIdx };
59
+ }
60
+ function encodeCursor(e) {
61
+ return Buffer.from(`${e.createdAt}|${e.id}`, "utf8").toString("base64url");
62
+ }
63
+ function decodeCursor(c) {
64
+ try {
65
+ const [createdAt, id] = Buffer.from(c, "base64url").toString("utf8").split("|");
66
+ if (!createdAt || !id)
67
+ return null;
68
+ return { createdAt, id };
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
74
+ function tidbUpsertParams(e, id, now) {
75
+ return [
76
+ id, e.profile, JSON.stringify(e.bands ?? []), e.repo, e.tag, e.digest,
77
+ JSON.stringify(e.toolchainVersions ?? {}), JSON.stringify(e.capabilities ?? {}),
78
+ JSON.stringify(e.podContract ?? {}), e.sizeBytes,
79
+ e.status, e.visibility, e.tenantId ?? null, e.manifestSha ?? null, e.recipeGitSha ?? null,
80
+ e.generatorVersion ?? null, e.buildDate ? new Date(e.buildDate) : null, e.supersedes ?? null,
81
+ e.signed ? 1 : 0, now, now,
82
+ ];
83
+ }
84
+ const PG_UPSERT_COLS = "(id, profile, bands, repo, tag, digest, toolchain_versions, capabilities, pod_contract, size_bytes, " +
85
+ "status, visibility, tenant_id, manifest_sha, recipe_git_sha, generator_version, build_date, supersedes, " +
86
+ "signed, created_at, updated_at)";
87
+ const PG_UPSERT_VALUES = "($1,$2,$3::jsonb,$4,$5,$6,$7::jsonb,$8::jsonb,$9::jsonb,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21)";
88
+ function pgUpsertParams(e, id, now) {
89
+ return [
90
+ id,
91
+ pgSanitizeText(e.profile),
92
+ pgSafeJsonStringify(e.bands ?? []),
93
+ e.repo,
94
+ pgSanitizeText(e.tag),
95
+ e.digest,
96
+ pgSafeJsonStringify(e.toolchainVersions ?? {}),
97
+ pgSafeJsonStringify(e.capabilities ?? {}),
98
+ pgSafeJsonStringify(e.podContract ?? {}),
99
+ e.sizeBytes,
100
+ e.status,
101
+ e.visibility,
102
+ e.tenantId ?? null,
103
+ e.manifestSha ?? null,
104
+ e.recipeGitSha == null ? null : pgSanitizeText(e.recipeGitSha),
105
+ e.generatorVersion == null ? null : pgSanitizeText(e.generatorVersion),
106
+ e.buildDate ? new Date(e.buildDate) : null,
107
+ e.supersedes == null ? null : pgSanitizeText(e.supersedes),
108
+ e.signed ? 1 : 0,
109
+ now,
110
+ now,
111
+ ];
112
+ }
113
+ export class SqlImageIndex {
114
+ db;
115
+ constructor(db) {
116
+ this.db = db;
117
+ }
118
+ q(tidb, pg) {
119
+ return this.db.dialect === "tidb" ? tidb : pg;
120
+ }
121
+ static idFor(repo, digest) {
122
+ return createHash("sha256").update(`${repo}@${digest}`).digest("hex").slice(0, 64);
123
+ }
124
+ async upsert(e) {
125
+ if (this.db.dialect === "pg") {
126
+ if (pgHasUnstorable(e.repo))
127
+ throw new PgUnstorableError("image repo (identity)");
128
+ if (e.tenantId != null && pgHasUnstorable(e.tenantId))
129
+ throw new PgUnstorableError("image tenantId (identity)");
130
+ }
131
+ const id = SqlImageIndex.idFor(e.repo, e.digest);
132
+ const now = new Date();
133
+ await this.db.query(this.q(`INSERT INTO sandbox_image_index
134
+ (id, profile, bands, repo, tag, digest, toolchain_versions, capabilities, pod_contract, size_bytes,
135
+ status, visibility, tenant_id, manifest_sha, recipe_git_sha, generator_version, build_date, supersedes,
136
+ signed, created_at, updated_at)
137
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
138
+ ON DUPLICATE KEY UPDATE
139
+ profile=VALUES(profile), bands=VALUES(bands), tag=VALUES(tag), toolchain_versions=VALUES(toolchain_versions),
140
+ capabilities=VALUES(capabilities), pod_contract=VALUES(pod_contract), size_bytes=VALUES(size_bytes),
141
+ status=VALUES(status), visibility=VALUES(visibility), tenant_id=VALUES(tenant_id),
142
+ manifest_sha=VALUES(manifest_sha), recipe_git_sha=VALUES(recipe_git_sha),
143
+ generator_version=VALUES(generator_version), build_date=VALUES(build_date), supersedes=VALUES(supersedes),
144
+ signed=VALUES(signed), updated_at=VALUES(updated_at)`, `INSERT INTO sandbox_image_index ${PG_UPSERT_COLS}
145
+ VALUES ${PG_UPSERT_VALUES}
146
+ ON CONFLICT (id) DO UPDATE SET
147
+ profile = EXCLUDED.profile, bands = EXCLUDED.bands, tag = EXCLUDED.tag,
148
+ toolchain_versions = EXCLUDED.toolchain_versions, capabilities = EXCLUDED.capabilities,
149
+ pod_contract = EXCLUDED.pod_contract, size_bytes = EXCLUDED.size_bytes,
150
+ status = EXCLUDED.status, visibility = EXCLUDED.visibility, tenant_id = EXCLUDED.tenant_id,
151
+ manifest_sha = EXCLUDED.manifest_sha, recipe_git_sha = EXCLUDED.recipe_git_sha,
152
+ generator_version = EXCLUDED.generator_version, build_date = EXCLUDED.build_date,
153
+ supersedes = EXCLUDED.supersedes, signed = EXCLUDED.signed, updated_at = EXCLUDED.updated_at`), this.db.dialect === "tidb" ? tidbUpsertParams(e, id, now) : pgUpsertParams(e, id, now));
154
+ return id;
155
+ }
156
+ async registerBuilding(e) {
157
+ if (this.db.dialect === "pg") {
158
+ if (pgHasUnstorable(e.repo))
159
+ throw new PgUnstorableError("image repo (identity)");
160
+ if (e.tenantId != null && pgHasUnstorable(e.tenantId))
161
+ throw new PgUnstorableError("image tenantId (identity)");
162
+ }
163
+ const id = SqlImageIndex.idFor(e.repo, e.digest);
164
+ const now = new Date();
165
+ await this.db.query(this.q(`INSERT INTO sandbox_image_index
166
+ (id, profile, bands, repo, tag, digest, toolchain_versions, capabilities, pod_contract, size_bytes,
167
+ status, visibility, tenant_id, manifest_sha, recipe_git_sha, generator_version, build_date, supersedes,
168
+ signed, created_at, updated_at)
169
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
170
+ ON DUPLICATE KEY UPDATE
171
+ profile=VALUES(profile), bands=VALUES(bands), tag=VALUES(tag), toolchain_versions=VALUES(toolchain_versions),
172
+ capabilities=VALUES(capabilities), pod_contract=VALUES(pod_contract), size_bytes=VALUES(size_bytes),
173
+ status=IF(sandbox_image_index.status='published', sandbox_image_index.status, VALUES(status)),
174
+ visibility=IF(sandbox_image_index.status='published', sandbox_image_index.visibility, VALUES(visibility)),
175
+ tenant_id=IF(sandbox_image_index.status='published', sandbox_image_index.tenant_id, VALUES(tenant_id)),
176
+ manifest_sha=VALUES(manifest_sha), recipe_git_sha=VALUES(recipe_git_sha),
177
+ generator_version=VALUES(generator_version), build_date=VALUES(build_date), supersedes=VALUES(supersedes),
178
+ signed=IF(sandbox_image_index.status='published', sandbox_image_index.signed, VALUES(signed)), updated_at=VALUES(updated_at)`, `INSERT INTO sandbox_image_index ${PG_UPSERT_COLS}
179
+ VALUES ${PG_UPSERT_VALUES}
180
+ ON CONFLICT (id) DO UPDATE SET
181
+ profile = EXCLUDED.profile, bands = EXCLUDED.bands, tag = EXCLUDED.tag,
182
+ toolchain_versions = EXCLUDED.toolchain_versions, capabilities = EXCLUDED.capabilities,
183
+ pod_contract = EXCLUDED.pod_contract, size_bytes = EXCLUDED.size_bytes,
184
+ status = CASE WHEN sandbox_image_index.status = 'published'
185
+ THEN sandbox_image_index.status ELSE EXCLUDED.status END,
186
+ visibility = CASE WHEN sandbox_image_index.status = 'published'
187
+ THEN sandbox_image_index.visibility ELSE EXCLUDED.visibility END,
188
+ tenant_id = CASE WHEN sandbox_image_index.status = 'published'
189
+ THEN sandbox_image_index.tenant_id ELSE EXCLUDED.tenant_id END,
190
+ manifest_sha = EXCLUDED.manifest_sha, recipe_git_sha = EXCLUDED.recipe_git_sha,
191
+ generator_version = EXCLUDED.generator_version, build_date = EXCLUDED.build_date,
192
+ supersedes = EXCLUDED.supersedes,
193
+ signed = CASE WHEN sandbox_image_index.status = 'published'
194
+ THEN sandbox_image_index.signed ELSE EXCLUDED.signed END,
195
+ updated_at = EXCLUDED.updated_at`), this.db.dialect === "tidb" ? tidbUpsertParams(e, id, now) : pgUpsertParams(e, id, now));
196
+ return id;
197
+ }
198
+ async getById(id) {
199
+ const { rows } = await this.db.query(this.q("SELECT * FROM sandbox_image_index WHERE id=? LIMIT 1", "SELECT * FROM sandbox_image_index WHERE id = $1 LIMIT 1"), [id]);
200
+ return rows[0] ? mapRow(rows[0]) : null;
201
+ }
202
+ async getByDigest(digest) {
203
+ const { rows } = await this.db.query(this.q("SELECT * FROM sandbox_image_index WHERE digest=? ORDER BY updated_at DESC LIMIT 1", "SELECT * FROM sandbox_image_index WHERE digest = $1 ORDER BY updated_at DESC LIMIT 1"), [digest]);
204
+ return rows[0] ? mapRow(rows[0]) : null;
205
+ }
206
+ async latestPublished(profile, viewer) {
207
+ if (this.db.dialect === "tidb") {
208
+ const vis = visibilityClauseTidb(viewer);
209
+ const { rows } = await this.db.query(`SELECT * FROM sandbox_image_index
210
+ WHERE profile=? AND status='published' AND ${vis.sql}
211
+ ORDER BY (build_date IS NULL), build_date DESC, created_at DESC LIMIT 1`, [profile, ...vis.params]);
212
+ return rows[0] ? mapRow(rows[0]) : null;
213
+ }
214
+ const vis = visibilityClausePg(viewer, 2);
215
+ const { rows } = await this.db.query(`SELECT * FROM sandbox_image_index
216
+ WHERE profile = $1 AND status = 'published' AND ${vis.sql}
217
+ ORDER BY build_date DESC NULLS LAST, created_at DESC LIMIT 1`, [profile, ...vis.params]);
218
+ return rows[0] ? mapRow(rows[0]) : null;
219
+ }
220
+ async list(filter) {
221
+ const limit = Math.min(Math.max(1, filter.limit ?? DEFAULT_LIMIT), MAX_LIMIT);
222
+ let rawRows;
223
+ if (this.db.dialect === "tidb") {
224
+ const vis = visibilityClauseTidb(filter);
225
+ const where = [vis.sql];
226
+ const params = [...vis.params];
227
+ if (filter.profile) {
228
+ where.push("profile=?");
229
+ params.push(filter.profile);
230
+ }
231
+ if (filter.status) {
232
+ where.push("status=?");
233
+ params.push(filter.status);
234
+ }
235
+ if (filter.capability) {
236
+ where.push("JSON_EXTRACT(capabilities, ?) = true");
237
+ params.push(`$.${filter.capability}`);
238
+ }
239
+ if (filter.cursor) {
240
+ const c = decodeCursor(filter.cursor);
241
+ if (c) {
242
+ where.push("(created_at < ? OR (created_at = ? AND id < ?))");
243
+ params.push(new Date(c.createdAt), new Date(c.createdAt), c.id);
244
+ }
245
+ }
246
+ const sql = `SELECT * FROM sandbox_image_index WHERE ${where.join(" AND ")} ` +
247
+ `ORDER BY created_at DESC, id DESC LIMIT ?`;
248
+ const { rows } = await this.db.query(sql, [...params, limit + 1]);
249
+ rawRows = rows;
250
+ }
251
+ else {
252
+ const vis = visibilityClausePg(filter, 1);
253
+ const where = [vis.sql];
254
+ const params = [...vis.params];
255
+ let idx = vis.nextIdx;
256
+ if (filter.profile) {
257
+ where.push(`profile = $${idx++}`);
258
+ params.push(filter.profile);
259
+ }
260
+ if (filter.status) {
261
+ where.push(`status = $${idx++}`);
262
+ params.push(filter.status);
263
+ }
264
+ if (filter.capability) {
265
+ where.push(`capabilities -> $${idx++} = 'true'::jsonb`);
266
+ params.push(filter.capability);
267
+ }
268
+ if (filter.cursor) {
269
+ const c = decodeCursor(filter.cursor);
270
+ if (c) {
271
+ where.push(`(created_at < $${idx} OR (created_at = $${idx + 1} AND id < $${idx + 2}))`);
272
+ params.push(new Date(c.createdAt), new Date(c.createdAt), c.id);
273
+ idx += 3;
274
+ }
275
+ }
276
+ const sql = `SELECT * FROM sandbox_image_index WHERE ${where.join(" AND ")} ` +
277
+ `ORDER BY created_at DESC, id DESC LIMIT $${idx}`;
278
+ params.push(limit + 1);
279
+ const { rows } = await this.db.query(sql, params);
280
+ rawRows = rows;
281
+ }
282
+ let entries = rawRows.map(mapRow);
283
+ let nextCursor = null;
284
+ if (entries.length > limit) {
285
+ entries = entries.slice(0, limit);
286
+ const last = entries[entries.length - 1];
287
+ nextCursor = encodeCursor({ createdAt: last.createdAt, id: last.id });
288
+ }
289
+ if (filter.latestOnly) {
290
+ const seen = new Set();
291
+ entries = entries.filter((e) => (seen.has(e.profile) ? false : (seen.add(e.profile), true)));
292
+ }
293
+ return { entries, nextCursor };
294
+ }
295
+ async setStatus(id, status, opts) {
296
+ if (this.db.dialect === "tidb") {
297
+ const sets = ["status=?", "updated_at=?"];
298
+ const params = [status, new Date()];
299
+ if (opts && "supersedes" in opts) {
300
+ sets.push("supersedes=?");
301
+ params.push(opts.supersedes ?? null);
302
+ }
303
+ params.push(id);
304
+ await this.db.query(`UPDATE sandbox_image_index SET ${sets.join(", ")} WHERE id=?`, params);
305
+ return;
306
+ }
307
+ const sets = ["status = $1", "updated_at = $2"];
308
+ const params = [status, new Date()];
309
+ let idx = 3;
310
+ if (opts && "supersedes" in opts) {
311
+ sets.push(`supersedes = $${idx++}`);
312
+ params.push(opts.supersedes ?? null);
313
+ }
314
+ params.push(id);
315
+ await this.db.query(`UPDATE sandbox_image_index SET ${sets.join(", ")} WHERE id = $${idx}`, params);
316
+ }
317
+ }
318
+ export class TiDBImageIndex extends SqlImageIndex {
319
+ constructor(pool) {
320
+ super(mysqlDriver(pool));
321
+ }
322
+ }
323
+ export class PgImageIndex extends SqlImageIndex {
324
+ constructor(pool) {
325
+ super(pgDriver(pool));
326
+ }
327
+ }
328
+ //# sourceMappingURL=image-index-sql.js.map
@@ -0,0 +1,70 @@
1
+ import type { Pool as MySqlPool } from "mysql2/promise";
2
+ import type { Pool as PgPool, PoolClient } from "pg";
3
+ import type { TaskOutcome as CoreTaskOutcome } from "@sema-agent/core";
4
+ import { type SqlDriver } from "./sql-driver.js";
5
+ export interface MechanicalOutcome {
6
+ route?: "single" | "fanout";
7
+ workerCount?: number;
8
+ oraclePassed?: number;
9
+ oracleTotal?: number;
10
+ assembleExit?: number;
11
+ lintExit?: number;
12
+ mergeOk?: boolean;
13
+ replanTriggers?: string[];
14
+ costMicroUsd?: number;
15
+ turns?: number;
16
+ }
17
+ export interface LlmAssistedOutcome {
18
+ stuckEvents?: number;
19
+ verifier?: {
20
+ verdict: string;
21
+ confidence: number;
22
+ };
23
+ }
24
+ export interface SignatureInputs {
25
+ taskType?: string;
26
+ toolset?: string[];
27
+ targetLang?: string;
28
+ moduleCount?: number;
29
+ tag?: string;
30
+ }
31
+ export type RunStatus = "completed-graded" | "infra-aborted";
32
+ export interface TaskOutcome {
33
+ taskId?: string;
34
+ model: string;
35
+ runStatus?: RunStatus;
36
+ signatureInputs: SignatureInputs;
37
+ mechanical: MechanicalOutcome;
38
+ llmAssisted?: LlmAssistedOutcome;
39
+ core?: unknown;
40
+ }
41
+ export declare function taskSignature(s: SignatureInputs): string;
42
+ export declare function deriveOutcome(m: MechanicalOutcome, runStatus?: RunStatus): "pass" | "partial" | "fail" | "aborted";
43
+ export declare function coreOutcomeToLedgerRow(o: CoreTaskOutcome): TaskOutcome;
44
+ export declare const PG_OUTCOME_LEDGER_SCHEMA: string[];
45
+ export declare function ensurePgOutcomeLedgerSchema(pool: PgPool | PoolClient): Promise<void>;
46
+ export declare class SqlOutcomeLedger {
47
+ private readonly db;
48
+ constructor(db: SqlDriver);
49
+ private q;
50
+ private json;
51
+ record(o: TaskOutcome): Promise<string>;
52
+ recordCore(o: CoreTaskOutcome): Promise<void>;
53
+ summary(opts?: {
54
+ taskSignature?: string;
55
+ includeAborted?: boolean;
56
+ }): Promise<Array<{
57
+ taskSignature: string;
58
+ model: string;
59
+ n: number;
60
+ passRate: number;
61
+ meanCostMicroUsd: number;
62
+ }>>;
63
+ }
64
+ export declare class TiDBOutcomeLedger extends SqlOutcomeLedger {
65
+ constructor(pool: MySqlPool);
66
+ }
67
+ export declare class PgOutcomeLedger extends SqlOutcomeLedger {
68
+ constructor(pool: PgPool);
69
+ }
70
+ //# sourceMappingURL=outcome-ledger-sql.d.ts.map