@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
@@ -1,218 +1,2 @@
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
- export const PG_IMAGE_INDEX_SCHEMA = [
5
- `CREATE TABLE IF NOT EXISTS sandbox_image_index (
6
- id VARCHAR(64) NOT NULL,
7
- profile VARCHAR(64) NOT NULL,
8
- bands JSONB,
9
- repo VARCHAR(255) NOT NULL,
10
- tag VARCHAR(128) NOT NULL,
11
- digest VARCHAR(80) NOT NULL,
12
- toolchain_versions JSONB,
13
- capabilities JSONB,
14
- pod_contract JSONB,
15
- size_bytes BIGINT,
16
- status VARCHAR(16) NOT NULL DEFAULT 'building',
17
- visibility VARCHAR(16) NOT NULL DEFAULT 'public',
18
- tenant_id VARCHAR(64),
19
- manifest_sha VARCHAR(64),
20
- recipe_git_sha VARCHAR(64),
21
- generator_version VARCHAR(32),
22
- build_date TIMESTAMPTZ(3),
23
- supersedes VARCHAR(64),
24
- signed SMALLINT NOT NULL DEFAULT 0,
25
- created_at TIMESTAMPTZ(3) NOT NULL,
26
- updated_at TIMESTAMPTZ(3) NOT NULL,
27
- PRIMARY KEY (id)
28
- )`,
29
- `CREATE UNIQUE INDEX IF NOT EXISTS uq_repo_digest ON sandbox_image_index (repo, digest)`,
30
- `CREATE INDEX IF NOT EXISTS idx_profile_status ON sandbox_image_index (profile, status, visibility)`,
31
- `CREATE INDEX IF NOT EXISTS idx_digest ON sandbox_image_index (digest)`,
32
- `CREATE INDEX IF NOT EXISTS idx_tenant ON sandbox_image_index (tenant_id, status)`,
33
- ];
34
- export async function ensureSchema(pool) {
35
- for (const stmt of PG_IMAGE_INDEX_SCHEMA)
36
- await pool.query(stmt);
37
- }
38
- const MAX_LIMIT = 200;
39
- const DEFAULT_LIMIT = 50;
40
- function visibilityClause(viewer, startIdx) {
41
- if (viewer.operator)
42
- return { sql: "1=1", params: [], nextIdx: startIdx };
43
- if (viewer.tenantId)
44
- return {
45
- sql: `(visibility = 'public' OR tenant_id = $${startIdx})`,
46
- params: [viewer.tenantId],
47
- nextIdx: startIdx + 1,
48
- };
49
- return { sql: "visibility = 'public'", params: [], nextIdx: startIdx };
50
- }
51
- function encodeCursor(e) {
52
- return Buffer.from(`${e.createdAt}|${e.id}`, "utf8").toString("base64url");
53
- }
54
- function decodeCursor(c) {
55
- try {
56
- const [createdAt, id] = Buffer.from(c, "base64url").toString("utf8").split("|");
57
- if (!createdAt || !id)
58
- return null;
59
- return { createdAt, id };
60
- }
61
- catch {
62
- return null;
63
- }
64
- }
65
- const UPSERT_COLS = "(id, profile, bands, repo, tag, digest, toolchain_versions, capabilities, pod_contract, size_bytes, " +
66
- "status, visibility, tenant_id, manifest_sha, recipe_git_sha, generator_version, build_date, supersedes, " +
67
- "signed, created_at, updated_at)";
68
- const 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)";
69
- function upsertParams(e, id, now) {
70
- return [
71
- id,
72
- pgSanitizeText(e.profile),
73
- pgSafeJsonStringify(e.bands ?? []),
74
- e.repo,
75
- pgSanitizeText(e.tag),
76
- e.digest,
77
- pgSafeJsonStringify(e.toolchainVersions ?? {}),
78
- pgSafeJsonStringify(e.capabilities ?? {}),
79
- pgSafeJsonStringify(e.podContract ?? {}),
80
- e.sizeBytes,
81
- e.status,
82
- e.visibility,
83
- e.tenantId ?? null,
84
- e.manifestSha ?? null,
85
- e.recipeGitSha == null ? null : pgSanitizeText(e.recipeGitSha),
86
- e.generatorVersion == null ? null : pgSanitizeText(e.generatorVersion),
87
- e.buildDate ? new Date(e.buildDate) : null,
88
- e.supersedes == null ? null : pgSanitizeText(e.supersedes),
89
- e.signed ? 1 : 0,
90
- now,
91
- now,
92
- ];
93
- }
94
- export class PgImageIndex {
95
- pool;
96
- constructor(pool) {
97
- this.pool = pool;
98
- }
99
- static idFor(repo, digest) {
100
- return createHash("sha256").update(`${repo}@${digest}`).digest("hex").slice(0, 64);
101
- }
102
- async upsert(e) {
103
- if (pgHasUnstorable(e.repo))
104
- throw new PgUnstorableError("image repo (identity)");
105
- if (e.tenantId != null && pgHasUnstorable(e.tenantId))
106
- throw new PgUnstorableError("image tenantId (identity)");
107
- const id = PgImageIndex.idFor(e.repo, e.digest);
108
- const now = new Date();
109
- await this.pool.query(`INSERT INTO sandbox_image_index ${UPSERT_COLS}
110
- VALUES ${UPSERT_VALUES}
111
- ON CONFLICT (id) DO UPDATE SET
112
- profile = EXCLUDED.profile, bands = EXCLUDED.bands, tag = EXCLUDED.tag,
113
- toolchain_versions = EXCLUDED.toolchain_versions, capabilities = EXCLUDED.capabilities,
114
- pod_contract = EXCLUDED.pod_contract, size_bytes = EXCLUDED.size_bytes,
115
- status = EXCLUDED.status, visibility = EXCLUDED.visibility, tenant_id = EXCLUDED.tenant_id,
116
- manifest_sha = EXCLUDED.manifest_sha, recipe_git_sha = EXCLUDED.recipe_git_sha,
117
- generator_version = EXCLUDED.generator_version, build_date = EXCLUDED.build_date,
118
- supersedes = EXCLUDED.supersedes, signed = EXCLUDED.signed, updated_at = EXCLUDED.updated_at`, upsertParams(e, id, now));
119
- return id;
120
- }
121
- async registerBuilding(e) {
122
- if (pgHasUnstorable(e.repo))
123
- throw new PgUnstorableError("image repo (identity)");
124
- if (e.tenantId != null && pgHasUnstorable(e.tenantId))
125
- throw new PgUnstorableError("image tenantId (identity)");
126
- const id = PgImageIndex.idFor(e.repo, e.digest);
127
- const now = new Date();
128
- await this.pool.query(`INSERT INTO sandbox_image_index ${UPSERT_COLS}
129
- VALUES ${UPSERT_VALUES}
130
- ON CONFLICT (id) DO UPDATE SET
131
- profile = EXCLUDED.profile, bands = EXCLUDED.bands, tag = EXCLUDED.tag,
132
- toolchain_versions = EXCLUDED.toolchain_versions, capabilities = EXCLUDED.capabilities,
133
- pod_contract = EXCLUDED.pod_contract, size_bytes = EXCLUDED.size_bytes,
134
- status = CASE WHEN sandbox_image_index.status = 'published'
135
- THEN sandbox_image_index.status ELSE EXCLUDED.status END,
136
- visibility = CASE WHEN sandbox_image_index.status = 'published'
137
- THEN sandbox_image_index.visibility ELSE EXCLUDED.visibility END,
138
- tenant_id = CASE WHEN sandbox_image_index.status = 'published'
139
- THEN sandbox_image_index.tenant_id ELSE EXCLUDED.tenant_id END,
140
- manifest_sha = EXCLUDED.manifest_sha, recipe_git_sha = EXCLUDED.recipe_git_sha,
141
- generator_version = EXCLUDED.generator_version, build_date = EXCLUDED.build_date,
142
- supersedes = EXCLUDED.supersedes,
143
- signed = CASE WHEN sandbox_image_index.status = 'published'
144
- THEN sandbox_image_index.signed ELSE EXCLUDED.signed END,
145
- updated_at = EXCLUDED.updated_at`, upsertParams(e, id, now));
146
- return id;
147
- }
148
- async getById(id) {
149
- const res = await this.pool.query("SELECT * FROM sandbox_image_index WHERE id = $1 LIMIT 1", [id]);
150
- return res.rows[0] ? mapRow(res.rows[0]) : null;
151
- }
152
- async getByDigest(digest) {
153
- const res = await this.pool.query("SELECT * FROM sandbox_image_index WHERE digest = $1 ORDER BY updated_at DESC LIMIT 1", [digest]);
154
- return res.rows[0] ? mapRow(res.rows[0]) : null;
155
- }
156
- async latestPublished(profile, viewer) {
157
- const vis = visibilityClause(viewer, 2);
158
- const res = await this.pool.query(`SELECT * FROM sandbox_image_index
159
- WHERE profile = $1 AND status = 'published' AND ${vis.sql}
160
- ORDER BY build_date DESC NULLS LAST, created_at DESC LIMIT 1`, [profile, ...vis.params]);
161
- return res.rows[0] ? mapRow(res.rows[0]) : null;
162
- }
163
- async list(filter) {
164
- const limit = Math.min(Math.max(1, filter.limit ?? DEFAULT_LIMIT), MAX_LIMIT);
165
- const vis = visibilityClause(filter, 1);
166
- const where = [vis.sql];
167
- const params = [...vis.params];
168
- let idx = vis.nextIdx;
169
- if (filter.profile) {
170
- where.push(`profile = $${idx++}`);
171
- params.push(filter.profile);
172
- }
173
- if (filter.status) {
174
- where.push(`status = $${idx++}`);
175
- params.push(filter.status);
176
- }
177
- if (filter.capability) {
178
- where.push(`capabilities -> $${idx++} = 'true'::jsonb`);
179
- params.push(filter.capability);
180
- }
181
- if (filter.cursor) {
182
- const c = decodeCursor(filter.cursor);
183
- if (c) {
184
- where.push(`(created_at < $${idx} OR (created_at = $${idx + 1} AND id < $${idx + 2}))`);
185
- params.push(new Date(c.createdAt), new Date(c.createdAt), c.id);
186
- idx += 3;
187
- }
188
- }
189
- const sql = `SELECT * FROM sandbox_image_index WHERE ${where.join(" AND ")} ` +
190
- `ORDER BY created_at DESC, id DESC LIMIT $${idx}`;
191
- params.push(limit + 1);
192
- const res = await this.pool.query(sql, params);
193
- let entries = res.rows.map(mapRow);
194
- let nextCursor = null;
195
- if (entries.length > limit) {
196
- entries = entries.slice(0, limit);
197
- const last = entries[entries.length - 1];
198
- nextCursor = encodeCursor({ createdAt: last.createdAt, id: last.id });
199
- }
200
- if (filter.latestOnly) {
201
- const seen = new Set();
202
- entries = entries.filter((e) => (seen.has(e.profile) ? false : (seen.add(e.profile), true)));
203
- }
204
- return { entries, nextCursor };
205
- }
206
- async setStatus(id, status, opts) {
207
- const sets = ["status = $1", "updated_at = $2"];
208
- const params = [status, new Date()];
209
- let idx = 3;
210
- if (opts && "supersedes" in opts) {
211
- sets.push(`supersedes = $${idx++}`);
212
- params.push(opts.supersedes ?? null);
213
- }
214
- params.push(id);
215
- await this.pool.query(`UPDATE sandbox_image_index SET ${sets.join(", ")} WHERE id = $${idx}`, params);
216
- }
217
- }
1
+ export { PgImageIndex, PG_IMAGE_INDEX_SCHEMA, ensureSchema } from "./image-index-sql.js";
218
2
  //# sourceMappingURL=pg-image-index.js.map
@@ -1,23 +1,3 @@
1
- import type { Pool, PoolClient } from "pg";
2
- import { type TaskOutcome, type RunStatus } from "./tidb-outcome-ledger.js";
3
- import type { TaskOutcome as CoreTaskOutcome } from "@sema-agent/core";
4
- export declare const PG_OUTCOME_LEDGER_SCHEMA: string[];
5
- export declare function ensureSchema(pool: Pool | PoolClient): Promise<void>;
6
- export declare class PgOutcomeLedger {
7
- private readonly pool;
8
- constructor(pool: Pool);
9
- record(o: TaskOutcome): Promise<string>;
10
- recordCore(o: CoreTaskOutcome): Promise<void>;
11
- summary(opts?: {
12
- taskSignature?: string;
13
- includeAborted?: boolean;
14
- }): Promise<Array<{
15
- taskSignature: string;
16
- model: string;
17
- n: number;
18
- passRate: number;
19
- meanCostMicroUsd: number;
20
- }>>;
21
- }
22
- export type { TaskOutcome, RunStatus };
1
+ export { PgOutcomeLedger, PG_OUTCOME_LEDGER_SCHEMA, ensurePgOutcomeLedgerSchema as ensureSchema, } from "./outcome-ledger-sql.js";
2
+ export type { TaskOutcome, RunStatus } from "./outcome-ledger-sql.js";
23
3
  //# sourceMappingURL=pg-outcome-ledger.d.ts.map
@@ -1,105 +1,2 @@
1
- import { randomUUID } from "node:crypto";
2
- import { taskSignature, deriveOutcome, } from "./tidb-outcome-ledger.js";
3
- import { coreOutcomeToLedgerRow } from "./tidb-outcome-ledger.js";
4
- import { pgSafeJsonStringify } from "./pg-safe-json.js";
5
- export const PG_OUTCOME_LEDGER_SCHEMA = [
6
- `CREATE TABLE IF NOT EXISTS outcome_ledger (
7
- id VARCHAR(64) NOT NULL,
8
- task_signature VARCHAR(190) NOT NULL,
9
- model VARCHAR(190) NOT NULL,
10
- task_id VARCHAR(64),
11
- run_status VARCHAR(20) NOT NULL DEFAULT 'completed-graded',
12
- route VARCHAR(16),
13
- worker_count INTEGER,
14
- oracle_passed INTEGER,
15
- oracle_total INTEGER,
16
- assemble_exit INTEGER,
17
- lint_exit INTEGER,
18
- merge_ok SMALLINT,
19
- replan_triggers JSONB,
20
- cost_micro_usd BIGINT,
21
- turns INTEGER,
22
- outcome VARCHAR(8),
23
- llm_assisted JSONB,
24
- signature_inputs JSONB,
25
- -- design/73 §1 bridge: the VERBATIM core TaskOutcome fact (oracleHadRedRun / status / oracle blob) as it
26
- -- came off core, kept alongside the derived mechanical columns. NULL when the caller recorded through the
27
- -- non-core \`record()\` path (no core fact to bridge).
28
- core_outcome JSONB,
29
- created_at TIMESTAMPTZ(3) NOT NULL,
30
- PRIMARY KEY (id)
31
- )`,
32
- `CREATE INDEX IF NOT EXISTS idx_outcome_ledger_sig_model ON outcome_ledger (task_signature, model, run_status)`,
33
- `CREATE INDEX IF NOT EXISTS idx_outcome_ledger_outcome ON outcome_ledger (outcome)`,
34
- `CREATE INDEX IF NOT EXISTS idx_outcome_ledger_created ON outcome_ledger (created_at)`,
35
- ];
36
- export async function ensureSchema(pool) {
37
- for (const stmt of PG_OUTCOME_LEDGER_SCHEMA)
38
- await pool.query(stmt);
39
- }
40
- export class PgOutcomeLedger {
41
- pool;
42
- constructor(pool) {
43
- this.pool = pool;
44
- }
45
- async record(o) {
46
- const id = randomUUID().replace(/-/g, "").slice(0, 32);
47
- const sig = taskSignature(o.signatureInputs);
48
- const m = o.mechanical;
49
- const runStatus = o.runStatus ?? "completed-graded";
50
- await this.pool.query(`INSERT INTO outcome_ledger
51
- (id, task_signature, model, task_id, run_status, route, worker_count, oracle_passed, oracle_total,
52
- assemble_exit, lint_exit, merge_ok, replan_triggers, cost_micro_usd, turns, outcome,
53
- llm_assisted, signature_inputs, core_outcome, created_at)
54
- 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)`, [
55
- id,
56
- sig,
57
- o.model,
58
- o.taskId ?? null,
59
- runStatus,
60
- m.route ?? null,
61
- m.workerCount ?? null,
62
- m.oraclePassed ?? null,
63
- m.oracleTotal ?? null,
64
- m.assembleExit ?? null,
65
- m.lintExit ?? null,
66
- m.mergeOk == null ? null : m.mergeOk ? 1 : 0,
67
- m.replanTriggers ? pgSafeJsonStringify(m.replanTriggers) : null,
68
- m.costMicroUsd ?? null,
69
- m.turns ?? null,
70
- deriveOutcome(m, runStatus),
71
- o.llmAssisted ? pgSafeJsonStringify(o.llmAssisted) : null,
72
- pgSafeJsonStringify(o.signatureInputs),
73
- o.core != null ? pgSafeJsonStringify(o.core) : null,
74
- new Date(),
75
- ]);
76
- return id;
77
- }
78
- async recordCore(o) {
79
- await this.record(coreOutcomeToLedgerRow(o));
80
- }
81
- async summary(opts = {}) {
82
- const clauses = [];
83
- const params = [];
84
- if (!opts.includeAborted)
85
- clauses.push("run_status = 'completed-graded'");
86
- if (opts.taskSignature) {
87
- params.push(opts.taskSignature);
88
- clauses.push(`task_signature = $${params.length}`);
89
- }
90
- const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
91
- const res = await this.pool.query(`SELECT task_signature, model, COUNT(*) n,
92
- AVG((outcome = 'pass')::int) pass_rate, AVG(cost_micro_usd) mean_cost
93
- FROM outcome_ledger ${where}
94
- GROUP BY task_signature, model
95
- ORDER BY task_signature, model`, params);
96
- return res.rows.map((r) => ({
97
- taskSignature: String(r.task_signature),
98
- model: String(r.model),
99
- n: Number(r.n),
100
- passRate: Number(r.pass_rate),
101
- meanCostMicroUsd: Number(r.mean_cost ?? 0),
102
- }));
103
- }
104
- }
1
+ export { PgOutcomeLedger, PG_OUTCOME_LEDGER_SCHEMA, ensurePgOutcomeLedgerSchema as ensureSchema, } from "./outcome-ledger-sql.js";
105
2
  //# sourceMappingURL=pg-outcome-ledger.js.map
@@ -1,14 +1,2 @@
1
- import type { Pool } from "pg";
2
- export declare class PgResumeAnchorStore {
3
- private readonly pool;
4
- constructor(pool: Pool);
5
- put(sessionId: string, eventId: string, entryId: string, owner: string | null): Promise<void>;
6
- resolve(sessionId: string, eventId: string, owner: string | null): Promise<string | undefined>;
7
- listBySession(sessionId: string): Promise<Array<{
8
- eventId: string;
9
- entryId: string;
10
- owner: string | null;
11
- }>>;
12
- deleteBySession(sessionId: string): Promise<number>;
13
- }
1
+ export { PgResumeAnchorStore } from "./resume-anchor-store-sql.js";
14
2
  //# sourceMappingURL=pg-resume-anchor-store.d.ts.map
@@ -1,23 +1,2 @@
1
- export class PgResumeAnchorStore {
2
- pool;
3
- constructor(pool) {
4
- this.pool = pool;
5
- }
6
- async put(sessionId, eventId, entryId, owner) {
7
- await this.pool.query("INSERT INTO resume_anchor (session_id, event_id, entry_id, owner, created_at) VALUES ($1,$2,$3,$4,$5) " +
8
- "ON CONFLICT (session_id, event_id) DO UPDATE SET entry_id = EXCLUDED.entry_id, owner = EXCLUDED.owner", [sessionId, eventId, entryId, owner, new Date()]);
9
- }
10
- async resolve(sessionId, eventId, owner) {
11
- const r = await this.pool.query("SELECT entry_id FROM resume_anchor WHERE session_id = $1 AND event_id = $2 AND owner IS NOT DISTINCT FROM $3", [sessionId, eventId, owner]);
12
- return r.rows[0] ? String(r.rows[0].entry_id) : undefined;
13
- }
14
- async listBySession(sessionId) {
15
- const r = await this.pool.query("SELECT event_id, entry_id, owner FROM resume_anchor WHERE session_id = $1", [sessionId]);
16
- return r.rows.map((row) => ({ eventId: String(row.event_id), entryId: String(row.entry_id), owner: row.owner == null ? null : String(row.owner) }));
17
- }
18
- async deleteBySession(sessionId) {
19
- const r = await this.pool.query("DELETE FROM resume_anchor WHERE session_id = $1", [sessionId]);
20
- return r.rowCount ?? 0;
21
- }
22
- }
1
+ export { PgResumeAnchorStore } from "./resume-anchor-store-sql.js";
23
2
  //# sourceMappingURL=pg-resume-anchor-store.js.map
@@ -1,76 +1,2 @@
1
- import type { TaskResult, TaskStatus } from "@sema-agent/core";
2
- import { type UsageRow } from "../usage-analytics.js";
3
- import type { Pool } from "pg";
4
- import type { RunRecord, RunEvent, SessionSummary } from "./store-contracts.js";
5
- export declare class PgRunStore {
6
- private readonly pool;
7
- constructor(pool: Pool);
8
- private tx;
9
- createRun(taskId: string, sessionId: string, owner: string | null, instanceId: string, meta?: {
10
- jobId?: string | null;
11
- source?: string | null;
12
- objectivePreview?: string | null;
13
- }): Promise<{
14
- ok: true;
15
- } | {
16
- ok: false;
17
- activeTaskId: string;
18
- }>;
19
- requestCancel(taskId: string, owner: string | null): Promise<boolean>;
20
- isCancelRequested(taskId: string, owner: string | null): Promise<boolean>;
21
- requestPreempt(taskId: string, owner: string | null): Promise<boolean>;
22
- isPreemptRequested(taskId: string, owner: string | null): Promise<boolean>;
23
- heartbeat(taskId: string, owner: string | null): Promise<void>;
24
- appendEvent(taskId: string, seq: number, type: string, data: unknown): Promise<void>;
25
- maxSeq(taskId: string): Promise<number>;
26
- setTerminal(taskId: string, status: TaskStatus, result: TaskResult | null, error: string | null): Promise<void>;
27
- setSuspended(taskId: string): Promise<void>;
28
- setNeedsReview(taskId: string): Promise<void>;
29
- markResuming(taskId: string): Promise<boolean>;
30
- getActiveTaskId(sessionId: string): Promise<string | undefined>;
31
- private rowToRun;
32
- getRun(taskId: string): Promise<RunRecord | undefined>;
33
- listRuns(opts: {
34
- status?: string;
35
- jobId?: string;
36
- source?: string;
37
- owner?: string;
38
- cursor?: {
39
- createdAt: string;
40
- taskId: string;
41
- };
42
- limit: number;
43
- }): Promise<RunRecord[]>;
44
- listSessions(opts: {
45
- owner?: string;
46
- cursor?: {
47
- lastActivityAt: string;
48
- sessionId: string;
49
- };
50
- limit: number;
51
- q?: string;
52
- }): Promise<SessionSummary[]>;
53
- deleteBySession(sessionId: string, owner: string | null): Promise<{
54
- removed: number;
55
- } | {
56
- active: string;
57
- }>;
58
- sourceSummary(sinceMs: number): Promise<Array<{
59
- source: string | null;
60
- status: string;
61
- count: number;
62
- }>>;
63
- usageScan(fromMs: number, toMs: number, opts?: {
64
- owner?: string;
65
- limit?: number;
66
- }): Promise<{
67
- rows: UsageRow[];
68
- truncated: boolean;
69
- }>;
70
- retainedFrom(taskId: string): Promise<number>;
71
- getEvents(taskId: string, afterSeq: number): Promise<RunEvent[]>;
72
- reapStale(olderThanMs: number): Promise<number>;
73
- reapSuspended(olderThanMs: number): Promise<number>;
74
- failSuspendedWithExpiredCheckpoint(): Promise<number>;
75
- }
1
+ export { PgRunStore } from "./run-store-sql.js";
76
2
  //# sourceMappingURL=pg-run-store.d.ts.map