@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,299 @@
1
+ import { summarizeWorkflowRun, isTerminalWorkflowStatus, WorkflowRunStoreError } from "@sema-agent/core";
2
+ import { foldKeyFamily, MAX_PENDING_PER_SESSION, PURGE_FENCE_MS, SERVED_FENCE_MS, } from "../orchestration/workflow-completion-inbox.js";
3
+ import { mysqlDriver, pgDriver } from "./sql-driver.js";
4
+ export const MAX_RUN_BLOB_BYTES = 4 * 1024 * 1024;
5
+ const onWarnType = (msg, meta) => void [msg, meta];
6
+ export function slimOversizeRun(run, maxBytes) {
7
+ const MARK = "…[truncated: run blob exceeded the store cap]";
8
+ const cut = (s) => s.slice(0, 4000) + MARK;
9
+ const step1 = {
10
+ ...run,
11
+ ...(typeof run.result === "string" && run.result.length > 4000 ? { result: cut(run.result) } : {}),
12
+ ...(typeof run.error === "string" && run.error.length > 4000 ? { error: cut(run.error) } : {}),
13
+ };
14
+ let blob = JSON.stringify(step1);
15
+ if (Buffer.byteLength(blob) <= maxBytes)
16
+ return blob;
17
+ const step2 = { ...step1, phases: [], agents: [], groups: [], error: step1.error ? String(step1.error).slice(0, 1000) + MARK : MARK };
18
+ blob = JSON.stringify(step2);
19
+ return Buffer.byteLength(blob) <= maxBytes ? blob : null;
20
+ }
21
+ export class SqlWorkflowRunStore {
22
+ db;
23
+ constructor(db) {
24
+ this.db = db;
25
+ }
26
+ q(tidb, pg) {
27
+ return this.db.dialect === "tidb" ? tidb : pg;
28
+ }
29
+ async put(id, run) {
30
+ const stored = { ...run, id, rev: run.rev ?? 0 };
31
+ try {
32
+ await this.db.query(this.q("INSERT INTO workflow_run (id, scope, status, run, rev, created_at, ended_at) VALUES (?,?,?,?,?,?,?)", "INSERT INTO workflow_run (id, scope, status, run, rev, created_at, ended_at) VALUES ($1,$2,$3,$4,$5,$6,$7)"), [id, run.scope, run.status, JSON.stringify(stored), stored.rev, run.createdAt, run.endedAt ?? null]);
33
+ }
34
+ catch (e) {
35
+ const isDupKey = this.db.dialect === "tidb" ? e.code === "ER_DUP_ENTRY" : e.code === "23505";
36
+ if (isDupKey) {
37
+ throw new WorkflowRunStoreError("workflow_run.already_exists", "workflow run id already exists");
38
+ }
39
+ throw e;
40
+ }
41
+ }
42
+ async get(id) {
43
+ const { rows } = await this.db.query(this.q("SELECT run, rev FROM workflow_run WHERE id = ?", "SELECT run, rev FROM workflow_run WHERE id = $1"), [id]);
44
+ const r = rows[0];
45
+ if (!r)
46
+ return null;
47
+ const run = JSON.parse(String(r.run));
48
+ run.rev = Number(r.rev);
49
+ return run;
50
+ }
51
+ async update(id, scope, run, expect) {
52
+ let blob = JSON.stringify({ ...run, id, scope });
53
+ if (Buffer.byteLength(blob) > MAX_RUN_BLOB_BYTES) {
54
+ const slim = slimOversizeRun({ ...run, id, scope }, MAX_RUN_BLOB_BYTES);
55
+ if (slim === null)
56
+ return false;
57
+ blob = slim;
58
+ }
59
+ const res = await this.db.query(this.q(`UPDATE workflow_run SET run = ?, rev = rev + 1, status = ?, ended_at = ? WHERE id = ? AND scope = ?${expect !== undefined ? " AND rev = ?" : ""}`, `UPDATE workflow_run SET run = $1, rev = rev + 1, status = $2, ended_at = $3 WHERE id = $4 AND scope = $5${expect !== undefined ? " AND rev = $6" : ""}`), expect !== undefined
60
+ ? [blob, run.status, run.endedAt ?? null, id, scope, expect.rev]
61
+ : [blob, run.status, run.endedAt ?? null, id, scope]);
62
+ return res.affected === 1;
63
+ }
64
+ async listByScope(scope, opts) {
65
+ const params = [scope];
66
+ let where;
67
+ let limit = "";
68
+ if (this.db.dialect === "tidb") {
69
+ where = "scope = ?";
70
+ if (opts?.status !== undefined) {
71
+ where += " AND status = ?";
72
+ params.push(opts.status);
73
+ }
74
+ if (opts?.session !== undefined) {
75
+ where += " AND JSON_UNQUOTE(JSON_EXTRACT(run, '$.originatingSessionId')) = ?";
76
+ params.push(opts.session);
77
+ }
78
+ if (opts?.limit !== undefined) {
79
+ limit = " LIMIT ?";
80
+ params.push(Math.max(0, opts.limit));
81
+ }
82
+ }
83
+ else {
84
+ where = "scope = $1";
85
+ if (opts?.status !== undefined) {
86
+ params.push(opts.status);
87
+ where += ` AND status = $${params.length}`;
88
+ }
89
+ if (opts?.session !== undefined) {
90
+ params.push(opts.session);
91
+ where += ` AND run::json->>'originatingSessionId' = $${params.length}`;
92
+ }
93
+ if (opts?.limit !== undefined) {
94
+ params.push(Math.max(0, opts.limit));
95
+ limit = ` LIMIT $${params.length}`;
96
+ }
97
+ }
98
+ const { rows } = await this.db.query(`SELECT run, rev FROM workflow_run WHERE ${where} ORDER BY created_at DESC, id DESC${limit}`, params);
99
+ return rows.map((r) => {
100
+ const run = JSON.parse(String(r.run));
101
+ run.rev = Number(r.rev);
102
+ return summarizeWorkflowRun(run);
103
+ });
104
+ }
105
+ async reapAllScopes(now, opts) {
106
+ const { rows } = await this.db.query("SELECT DISTINCT scope FROM workflow_run");
107
+ let total = 0;
108
+ for (const r of rows)
109
+ total += await this.reap(String(r.scope), now, opts);
110
+ return total;
111
+ }
112
+ async reap(scope, now, opts) {
113
+ if (opts?.maxAgeMs === undefined && opts?.keep === undefined)
114
+ return 0;
115
+ const { rows } = await this.db.query(this.q("SELECT id, status, created_at, ended_at FROM workflow_run WHERE scope = ? ORDER BY created_at DESC, id DESC", "SELECT id, status, created_at, ended_at FROM workflow_run WHERE scope = $1 ORDER BY created_at DESC, id DESC"), [scope]);
116
+ const terminal = rows.filter((r) => isTerminalWorkflowStatus(String(r.status)));
117
+ const doomed = [];
118
+ for (let i = 0; i < terminal.length; i++) {
119
+ const r = terminal[i];
120
+ const anchor = r.ended_at != null ? Number(r.ended_at) : Number(r.created_at);
121
+ const tooOld = opts.maxAgeMs !== undefined && anchor < now - opts.maxAgeMs;
122
+ const overKeep = opts.keep !== undefined && i >= opts.keep;
123
+ if (tooOld || overKeep)
124
+ doomed.push(String(r.id));
125
+ }
126
+ if (doomed.length === 0)
127
+ return 0;
128
+ const res = await this.db.query(this.q(`DELETE FROM workflow_run WHERE scope = ? AND id IN (${doomed.map(() => "?").join(",")})`, "DELETE FROM workflow_run WHERE scope = $1 AND id = ANY($2::text[])"), this.db.dialect === "tidb" ? [scope, ...doomed] : [scope, doomed]);
129
+ return res.affected;
130
+ }
131
+ }
132
+ const KIND_SERVED = "served";
133
+ const KIND_PURGE = "purge";
134
+ export class SqlWorkflowCompletionInbox {
135
+ db;
136
+ onWarn;
137
+ constructor(db, onWarn) {
138
+ this.db = db;
139
+ this.onWarn = onWarn;
140
+ }
141
+ q(tidb, pg) {
142
+ return this.db.dialect === "tidb" ? tidb : pg;
143
+ }
144
+ async sweepFences(now) {
145
+ await this.db.query(this.q("DELETE FROM workflow_inbox_fence WHERE until_ms < ?", "DELETE FROM workflow_inbox_fence WHERE until_ms < $1"), [now]);
146
+ }
147
+ async enqueue(entry) {
148
+ const now = Date.now();
149
+ await this.sweepFences(now);
150
+ const served = await this.db.query(this.q("SELECT 1 FROM workflow_inbox_fence WHERE session_id = ? AND kind = ? AND run_id IN (?, ?) AND until_ms >= ?", "SELECT 1 FROM workflow_inbox_fence WHERE session_id = $1 AND kind = $2 AND run_id IN ($3, $4) AND until_ms >= $5"), [entry.sessionId, KIND_SERVED, entry.runId, foldKeyFamily(entry.runId), now]);
151
+ if (served.rows.length > 0) {
152
+ this.onWarn?.("workflow_completion_enqueue_after_poll_served", { sessionId: entry.sessionId, runId: entry.runId });
153
+ return;
154
+ }
155
+ const purge = await this.db.query(this.q("SELECT owner, owner_known FROM workflow_inbox_fence WHERE session_id = ? AND kind = ? AND run_id = '' AND until_ms >= ?", "SELECT owner, owner_known FROM workflow_inbox_fence WHERE session_id = $1 AND kind = $2 AND run_id = '' AND until_ms >= $3"), [entry.sessionId, KIND_PURGE, now]);
156
+ const pf = purge.rows[0];
157
+ if (pf && (Number(pf.owner_known) === 0 || (pf.owner === null ? entry.owner === null : String(pf.owner) === entry.owner))) {
158
+ this.onWarn?.("workflow_completion_enqueue_after_purge", { sessionId: entry.sessionId, runId: entry.runId });
159
+ return;
160
+ }
161
+ await this.db.query(this.q("REPLACE INTO workflow_completion_inbox (session_id, run_id, owner, status, summary, enqueued_at, kind, payload) VALUES (?,?,?,?,?,?,?,?)", "INSERT INTO workflow_completion_inbox (session_id, run_id, owner, status, summary, enqueued_at, kind, payload) VALUES ($1,$2,$3,$4,$5,$6,$7,$8) " +
162
+ "ON CONFLICT (session_id, run_id) DO UPDATE SET seq = nextval(pg_get_serial_sequence('workflow_completion_inbox','seq')), " +
163
+ "owner = EXCLUDED.owner, status = EXCLUDED.status, summary = EXCLUDED.summary, enqueued_at = EXCLUDED.enqueued_at, kind = EXCLUDED.kind, payload = EXCLUDED.payload"), [entry.sessionId, entry.runId, entry.owner, entry.status, entry.summary, entry.enqueuedAt, entry.kind ?? null, entry.payload ?? null]);
164
+ const confirm = await this.db.query(this.q("SELECT kind, owner, owner_known FROM workflow_inbox_fence WHERE session_id = ? AND until_ms >= ? AND (run_id IN (?, ?) OR (kind = ? AND run_id = ''))", "SELECT kind, owner, owner_known FROM workflow_inbox_fence WHERE session_id = $1 AND until_ms >= $2 AND (run_id IN ($3, $4) OR (kind = $5 AND run_id = ''))"), [entry.sessionId, now, entry.runId, foldKeyFamily(entry.runId), KIND_PURGE]);
165
+ for (const f of confirm.rows) {
166
+ const isServed = String(f.kind) === KIND_SERVED;
167
+ const purgeFencesUs = !isServed && (Number(f.owner_known) === 0 || (f.owner === null ? entry.owner === null : String(f.owner) === entry.owner));
168
+ if (isServed || purgeFencesUs) {
169
+ await this.ack(entry.sessionId, entry.runId);
170
+ this.onWarn?.(isServed ? "workflow_completion_enqueue_after_poll_served" : "workflow_completion_enqueue_after_purge", {
171
+ sessionId: entry.sessionId,
172
+ runId: entry.runId,
173
+ });
174
+ return;
175
+ }
176
+ }
177
+ const over = await this.db.query(this.q("SELECT seq, run_id FROM workflow_completion_inbox WHERE session_id = ? ORDER BY seq DESC LIMIT 100000 OFFSET ?", "SELECT seq, run_id FROM workflow_completion_inbox WHERE session_id = $1 ORDER BY seq DESC OFFSET $2"), [entry.sessionId, MAX_PENDING_PER_SESSION]);
178
+ if (over.rows.length > 0) {
179
+ await this.db.query(this.q(`DELETE FROM workflow_completion_inbox WHERE session_id = ? AND seq IN (${over.rows.map(() => "?").join(",")})`, "DELETE FROM workflow_completion_inbox WHERE session_id = $1 AND seq = ANY($2::bigint[])"), this.db.dialect === "tidb" ? [entry.sessionId, ...over.rows.map((r) => r.seq)] : [entry.sessionId, over.rows.map((r) => r.seq)]);
180
+ for (const r of over.rows)
181
+ this.onWarn?.("workflow_completion_inbox_overflow", { sessionId: entry.sessionId, droppedRunId: String(r.run_id) });
182
+ }
183
+ }
184
+ async pending(sessionId) {
185
+ const { rows } = await this.db.query(this.q("SELECT i.run_id, i.owner, i.status, i.summary, i.enqueued_at, i.kind, i.payload FROM workflow_completion_inbox i " +
186
+ "WHERE i.session_id = ? AND NOT EXISTS (SELECT 1 FROM workflow_inbox_fence f WHERE f.session_id = i.session_id AND f.kind = ? AND f.run_id IN (i.run_id, REGEXP_REPLACE(i.run_id, '#[0-9]+$', '')) AND f.until_ms >= ?) " +
187
+ "ORDER BY i.seq ASC", "SELECT i.run_id, i.owner, i.status, i.summary, i.enqueued_at, i.kind, i.payload FROM workflow_completion_inbox i " +
188
+ "WHERE i.session_id = $1 AND NOT EXISTS (SELECT 1 FROM workflow_inbox_fence f WHERE f.session_id = i.session_id AND f.kind = $2 AND f.run_id IN (i.run_id, regexp_replace(i.run_id, '#[0-9]+$', '')) AND f.until_ms >= $3) " +
189
+ "ORDER BY i.seq ASC"), [sessionId, KIND_SERVED, Date.now()]);
190
+ return rows.map((r) => ({
191
+ sessionId,
192
+ runId: String(r.run_id),
193
+ owner: r.owner === null ? null : String(r.owner),
194
+ status: String(r.status),
195
+ summary: String(r.summary),
196
+ enqueuedAt: Number(r.enqueued_at),
197
+ ...(r.kind != null ? { kind: String(r.kind) } : {}),
198
+ ...(r.payload != null ? { payload: String(r.payload) } : {}),
199
+ }));
200
+ }
201
+ async ack(sessionId, runId) {
202
+ await this.db.query(this.q("DELETE FROM workflow_completion_inbox WHERE session_id = ? AND run_id = ?", "DELETE FROM workflow_completion_inbox WHERE session_id = $1 AND run_id = $2"), [sessionId, runId]);
203
+ }
204
+ async purge(sessionId, purgedOwner) {
205
+ const now = Date.now();
206
+ await this.sweepFences(now);
207
+ await this.db.query(this.q("INSERT INTO workflow_inbox_fence (session_id, kind, run_id, owner, owner_known, until_ms) VALUES (?,?,?,?,?,?) " +
208
+ "ON DUPLICATE KEY UPDATE owner = VALUES(owner), owner_known = VALUES(owner_known), until_ms = VALUES(until_ms)", "INSERT INTO workflow_inbox_fence (session_id, kind, run_id, owner, owner_known, until_ms) VALUES ($1,$2,'',$3,$4,$5) " +
209
+ "ON CONFLICT (session_id, kind, run_id) DO UPDATE SET owner = EXCLUDED.owner, owner_known = EXCLUDED.owner_known, until_ms = EXCLUDED.until_ms"), this.db.dialect === "tidb"
210
+ ? [sessionId, KIND_PURGE, "", purgedOwner ?? null, purgedOwner !== undefined ? 1 : 0, now + PURGE_FENCE_MS]
211
+ : [sessionId, KIND_PURGE, purgedOwner ?? null, purgedOwner !== undefined ? 1 : 0, now + PURGE_FENCE_MS]);
212
+ await this.db.query(this.q("DELETE FROM workflow_completion_inbox WHERE session_id = ?", "DELETE FROM workflow_completion_inbox WHERE session_id = $1"), [sessionId]);
213
+ }
214
+ async markTerminalServed(sessionId, runId) {
215
+ const now = Date.now();
216
+ await this.sweepFences(now);
217
+ await this.db.query(this.q("INSERT INTO workflow_inbox_fence (session_id, kind, run_id, owner, owner_known, until_ms) VALUES (?,?,?,NULL,0,?) " +
218
+ "ON DUPLICATE KEY UPDATE until_ms = VALUES(until_ms)", "INSERT INTO workflow_inbox_fence (session_id, kind, run_id, owner, owner_known, until_ms) VALUES ($1,$2,$3,NULL,0,$4) " +
219
+ "ON CONFLICT (session_id, kind, run_id) DO UPDATE SET until_ms = EXCLUDED.until_ms"), [sessionId, KIND_SERVED, runId, now + SERVED_FENCE_MS]);
220
+ await this.ack(sessionId, runId);
221
+ await this.db.query(this.q("DELETE FROM workflow_completion_inbox WHERE session_id = ? AND run_id <> ? AND REGEXP_REPLACE(run_id, '#[0-9]+$', '') = ?", "DELETE FROM workflow_completion_inbox WHERE session_id = $1 AND run_id <> $2 AND regexp_replace(run_id, '#[0-9]+$', '') = $3"), [sessionId, runId, runId]);
222
+ }
223
+ }
224
+ export class SqlWorkflowNotifyJournalStore {
225
+ db;
226
+ constructor(db) {
227
+ this.db = db;
228
+ }
229
+ q(tidb, pg) {
230
+ return this.db.dialect === "tidb" ? tidb : pg;
231
+ }
232
+ async record(input) {
233
+ await this.db.query(this.q("INSERT IGNORE INTO workflow_notify_journal (run_id, scope, acked, source_task_id, principal, created_at) VALUES (?,?,0,?,?,?)", "INSERT INTO workflow_notify_journal (run_id, scope, acked, source_task_id, principal, created_at) VALUES ($1,$2,0,$3,$4,$5) ON CONFLICT (run_id) DO NOTHING"), [input.runId, input.scope, input.sourceTaskId ?? null, input.principal ?? null, input.createdAt]);
234
+ }
235
+ async ack(runId, ackedAt) {
236
+ await this.db.query(this.q("UPDATE workflow_notify_journal SET acked = 1, acked_at = ? WHERE run_id = ? AND acked = 0", "UPDATE workflow_notify_journal SET acked = 1, acked_at = $1 WHERE run_id = $2 AND acked = 0"), [ackedAt, runId]);
237
+ }
238
+ async listPending() {
239
+ const { rows } = await this.db.query("SELECT run_id, scope, source_task_id, principal, created_at FROM workflow_notify_journal WHERE acked = 0");
240
+ return rows.map((r) => ({
241
+ runId: String(r.run_id),
242
+ scope: String(r.scope),
243
+ acked: false,
244
+ ...(r.source_task_id != null ? { sourceTaskId: String(r.source_task_id) } : {}),
245
+ ...(r.principal != null ? { principal: String(r.principal) } : {}),
246
+ createdAt: Number(r.created_at),
247
+ }));
248
+ }
249
+ async reapAcked(before) {
250
+ const res = await this.db.query(this.q("DELETE FROM workflow_notify_journal WHERE acked = 1 AND acked_at < ?", "DELETE FROM workflow_notify_journal WHERE acked = 1 AND acked_at < $1"), [before]);
251
+ return res.affected;
252
+ }
253
+ async get(runId) {
254
+ const { rows } = await this.db.query(this.q("SELECT run_id, scope, acked, source_task_id, principal, created_at, acked_at FROM workflow_notify_journal WHERE run_id = ?", "SELECT run_id, scope, acked, source_task_id, principal, created_at, acked_at FROM workflow_notify_journal WHERE run_id = $1"), [runId]);
255
+ const r = rows[0];
256
+ if (!r)
257
+ return null;
258
+ return {
259
+ runId: String(r.run_id),
260
+ scope: String(r.scope),
261
+ acked: Number(r.acked) === 1,
262
+ ...(r.source_task_id != null ? { sourceTaskId: String(r.source_task_id) } : {}),
263
+ ...(r.principal != null ? { principal: String(r.principal) } : {}),
264
+ createdAt: Number(r.created_at),
265
+ ...(r.acked_at != null ? { ackedAt: Number(r.acked_at) } : {}),
266
+ };
267
+ }
268
+ }
269
+ export class TiDBWorkflowRunStore extends SqlWorkflowRunStore {
270
+ constructor(pool) {
271
+ super(mysqlDriver(pool));
272
+ }
273
+ }
274
+ export class TiDBWorkflowCompletionInbox extends SqlWorkflowCompletionInbox {
275
+ constructor(pool, onWarn) {
276
+ super(mysqlDriver(pool), onWarn);
277
+ }
278
+ }
279
+ export class TiDBWorkflowNotifyJournalStore extends SqlWorkflowNotifyJournalStore {
280
+ constructor(pool) {
281
+ super(mysqlDriver(pool));
282
+ }
283
+ }
284
+ export class PgWorkflowRunStore extends SqlWorkflowRunStore {
285
+ constructor(pool) {
286
+ super(pgDriver(pool));
287
+ }
288
+ }
289
+ export class PgWorkflowCompletionInbox extends SqlWorkflowCompletionInbox {
290
+ constructor(pool, onWarn) {
291
+ super(pgDriver(pool), onWarn);
292
+ }
293
+ }
294
+ export class PgWorkflowNotifyJournalStore extends SqlWorkflowNotifyJournalStore {
295
+ constructor(pool) {
296
+ super(pgDriver(pool));
297
+ }
298
+ }
299
+ //# sourceMappingURL=workflow-run-store-sql.js.map
package/dist/question.js CHANGED
@@ -118,10 +118,10 @@ export class QuestionCoordinator {
118
118
  respond(id, principal, body) {
119
119
  const parsed = parseQuestionResponse(body);
120
120
  if (!parsed.ok)
121
- return { status: 400, body: { error: parsed.error } };
121
+ return { status: 400, body: { error: parsed.error, errorCode: "request.body_shape" } };
122
122
  const entry = this.pending.get(id);
123
123
  if (!entry || (entry.owner !== null && entry.owner !== principal)) {
124
- return { status: 404, body: { error: "no pending question for this id (answered, expired, or not on this replica)" } };
124
+ return { status: 404, body: { error: "no pending question for this id (answered, expired, or not on this replica)", errorCode: "question.not_pending" } };
125
125
  }
126
126
  entry.settle(parsed.value, "answered");
127
127
  return { status: 200, body: { questionId: id, delivery: "applied" } };
package/dist/run-local.js CHANGED
@@ -254,7 +254,7 @@ export async function runLocal(argv, deps = {}) {
254
254
  toolResultStore: fileBackend.toolResultStore,
255
255
  ...(executionEnvFactory ? { executionEnvFactory } : {}),
256
256
  ...(lspManager ? { lspManager } : {}),
257
- ...(!config.projectMemoryDisabled
257
+ ...(config.projectMemoryEnabled
258
258
  ? { loadProjectMemory: makeLoadProjectMemory({ logger }), probeInstructionSources: makeProbeInstructionSources() }
259
259
  : {}),
260
260
  });
@@ -211,10 +211,10 @@ export class ToolApprovalCoordinator {
211
211
  respond(id, principal, body) {
212
212
  const parsed = parseToolApprovalResponse(body);
213
213
  if (!parsed.ok)
214
- return { status: 400, body: { error: parsed.error } };
214
+ return { status: 400, body: { error: parsed.error, errorCode: "request.body_shape" } };
215
215
  const entry = this.pending.get(id);
216
216
  if (!entry || (entry.owner !== null && entry.owner !== principal)) {
217
- return { status: 404, body: { error: "no pending tool approval for this id (settled, expired, or not on this replica)" } };
217
+ return { status: 404, body: { error: "no pending tool approval for this id (settled, expired, or not on this replica)", errorCode: "tool_approval.not_pending" } };
218
218
  }
219
219
  let rememberApplied;
220
220
  if (parsed.value === "allow_session")
@@ -45,7 +45,7 @@ export function createLedgerSink(opts) {
45
45
  break;
46
46
  case "status":
47
47
  await flush();
48
- await append("brain_status", brainStatusEventData(ev));
48
+ await append("status", brainStatusEventData(ev));
49
49
  break;
50
50
  case "context_usage":
51
51
  await flush();
@@ -221,6 +221,7 @@ export interface TaskSummary {
221
221
  };
222
222
  }
223
223
  export declare function runSummary(run: RunRecord, latestEventType?: string): TaskSummary;
224
+ export declare function normalizeRunEventType(type: string): string;
224
225
  export declare function mapTraceEvent(type: string, seq: number, data: Record<string, unknown>): {
225
226
  event: string;
226
227
  data: Record<string, unknown>;
@@ -299,6 +299,9 @@ export function runSummary(run, latestEventType) {
299
299
  lastStep: lastStep(latestEventType, run.status),
300
300
  };
301
301
  }
302
+ export function normalizeRunEventType(type) {
303
+ return type === "brain_status" ? "status" : type;
304
+ }
302
305
  export function mapTraceEvent(type, seq, data) {
303
306
  switch (type) {
304
307
  case "reasoning":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sema-agent/server",
3
- "version": "1.315.0",
3
+ "version": "1.317.0",
4
4
  "description": "Sema Server — the server/API implementation layer for Sema, wiring core, registry, model providers, and cloud agent execution. Built on @sema-agent/core.",
5
5
  "type": "module",
6
6
  "license": "BUSL-1.1",