@sema-agent/server 7.47.0 → 7.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/USAGE.md +10 -0
- package/dist/approval-card.d.ts +1 -1
- package/dist/auth-bridge.d.ts +2 -2
- package/dist/auth-bridge.js +1 -1
- package/dist/boot/config-center.js +2 -2
- package/dist/boot/runner-deps.d.ts +4 -2
- package/dist/boot/stores.js +13 -0
- package/dist/config-center/apply-effective.js +1 -1
- package/dist/config-center/http-client.d.ts +1 -1
- package/dist/config-center/http-client.js +1 -1
- package/dist/config-center/restart-signal.js +1 -1
- package/dist/config-center/skills-mcp.js +1 -1
- package/dist/config-provider.d.ts +2 -2
- package/dist/config-provider.js +2 -2
- package/dist/config-types.d.ts +1 -1
- package/dist/config.d.ts +4 -1
- package/dist/config.js +16 -2
- package/dist/fleet/fleet-bus.d.ts +93 -6
- package/dist/fleet/fleet-bus.js +40 -1
- package/dist/fleet-client.d.ts +1 -1
- package/dist/fleet-client.js +1 -1
- package/dist/fleet-lease.d.ts +1 -1
- package/dist/fleet-lease.js +1 -1
- package/dist/hooks/hook-runner.d.ts +11 -11
- package/dist/hooks/hook-runner.js +143 -24
- package/dist/http/route-ctx.d.ts +24 -0
- package/dist/http/route-ctx.js +8 -0
- package/dist/http/routes/approvals-assistant.js +67 -9
- package/dist/http/routes/capabilities.js +1 -1
- package/dist/http/routes/fleet.js +2 -2
- package/dist/http/routes/notify-wake.js +3 -4
- package/dist/http/routes/runs.d.ts +1 -1
- package/dist/http/routes/runs.js +27 -3
- package/dist/http/routes/tasks.js +8 -3
- package/dist/http/server.js +11 -7
- package/dist/observability/fail-open.d.ts +8 -0
- package/dist/observability/fail-open.js +8 -0
- package/dist/orchestration/workflow-completion-inbox.d.ts +12 -1
- package/dist/orchestration/workflow-completion-inbox.js +6 -1
- package/dist/org-memory-admission.js +1 -1
- package/dist/plugins/approval-ask-store-memory.js +2 -0
- package/dist/plugins/approval-ask-store-sql.d.ts +50 -1
- package/dist/plugins/approval-ask-store-sql.js +40 -5
- package/dist/plugins/checkpoint-store-sql.d.ts +108 -1
- package/dist/plugins/checkpoint-store-sql.js +65 -0
- package/dist/plugins/local-checkpoint-store.d.ts +14 -1
- package/dist/plugins/local-checkpoint-store.js +22 -1
- package/dist/plugins/permission-rule-store-sql.d.ts +33 -0
- package/dist/plugins/permission-rule-store-sql.js +1 -8
- package/dist/plugins/scheduler-support.d.ts +1 -1
- package/dist/plugins/scheduler-support.js +1 -1
- package/dist/plugins/sql-errors.d.ts +18 -0
- package/dist/plugins/sql-errors.js +10 -0
- package/dist/resource-window.d.ts +111 -0
- package/dist/resource-window.js +80 -0
- package/dist/rules-consent.d.ts +29 -1
- package/dist/rules-consent.js +22 -1
- package/dist/run-local.js +1 -1
- package/dist/runs.js +3 -3
- package/dist/runtime-caps-resolver.d.ts +1 -1
- package/dist/runtime-governance.d.ts +1 -1
- package/dist/task-settings.d.ts +1 -1
- package/dist/tool-approval.d.ts +47 -1
- package/dist/tool-approval.js +131 -11
- package/dist/trace/engine-notice-wire.d.ts +13 -3
- package/dist/trace/engine-notice-wire.js +3 -0
- package/dist/trace/injection-tier.d.ts +33 -0
- package/dist/trace/injection-tier.js +7 -0
- package/dist/trace/project.d.ts +5 -1
- package/dist/trace/project.js +5 -0
- package/package.json +3 -3
package/dist/http/routes/runs.js
CHANGED
|
@@ -21,8 +21,9 @@ import { normalizeRunEventType } from "../../trace/project.js";
|
|
|
21
21
|
import { sendJson, sendError, httpErrorCode, sseHeaders } from "../send.js";
|
|
22
22
|
import { buildActiveRunConflict } from "../active-run-conflict.js";
|
|
23
23
|
import { clearTurnActivity, readTurnActivityMs } from "../../turn-activity.js";
|
|
24
|
+
import { buildCrossSliceUsage, readResourceWindow, recordResourceWindow } from "../../resource-window.js";
|
|
24
25
|
import { headerStr, gatedPrincipal, explicitOperatorOk } from "../principal-gate.js";
|
|
25
|
-
import { ActorAssertionWire } from "@sema-agent/
|
|
26
|
+
import { ActorAssertionWire } from "@sema-agent/settings-schema";
|
|
26
27
|
import { RUN_NOT_FOUND_MESSAGE, runNotFoundMessage } from "../route-ctx.js";
|
|
27
28
|
export const RUN_ID_RE = /^\/v1\/runs\/([^/]+)(\/events)?$/;
|
|
28
29
|
export const RUN_CANCEL_RE = /^\/v1\/runs\/([^/]+)\/cancel$/;
|
|
@@ -192,7 +193,20 @@ async function handleRunsBody(req, res, url, ctx, miss) {
|
|
|
192
193
|
const infraRates = deps.config.infraCostRates;
|
|
193
194
|
const needCost = Boolean(run.result?.stats && !stale && infraRates && hasInfraPricing(infraRates));
|
|
194
195
|
const needSuggestions = !stale && run.status === "completed";
|
|
195
|
-
const
|
|
196
|
+
const resourceWindow = run.status === "running" && !stale ? readResourceWindow(run.taskId) : undefined;
|
|
197
|
+
let events;
|
|
198
|
+
let eventsUnavailable = false;
|
|
199
|
+
if (needCost || needSuggestions || resourceWindow !== undefined) {
|
|
200
|
+
if (deps.runStore.getEvents) {
|
|
201
|
+
events = await deps.runStore.getEvents(taskId, 0).catch(() => {
|
|
202
|
+
eventsUnavailable = true;
|
|
203
|
+
return [];
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
eventsUnavailable = true;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
196
210
|
let supervisorCost;
|
|
197
211
|
if (needCost && events && run.result?.stats) {
|
|
198
212
|
const durMs = new Date(run.updatedAt).getTime() - new Date(run.createdAt).getTime();
|
|
@@ -208,11 +222,19 @@ async function handleRunsBody(req, res, url, ctx, miss) {
|
|
|
208
222
|
suggestions = arr.map((s) => String(s));
|
|
209
223
|
}
|
|
210
224
|
const lastActivityAt = run.status === "running" && !stale ? readTurnActivityMs(run.taskId) : undefined;
|
|
225
|
+
let crossSliceUsage;
|
|
226
|
+
if (resourceWindow !== undefined) {
|
|
227
|
+
if (eventsUnavailable || events === undefined)
|
|
228
|
+
recordFailOpen("server.runs.cross-slice-usage-unavailable");
|
|
229
|
+
else
|
|
230
|
+
crossSliceUsage = buildCrossSliceUsage(resourceWindow, events);
|
|
231
|
+
}
|
|
211
232
|
sendJson(res, 200, {
|
|
212
233
|
taskId: run.taskId,
|
|
213
234
|
sessionId: run.sessionId,
|
|
214
235
|
status: stale ? "failed" : run.status,
|
|
215
236
|
...(lastActivityAt !== undefined ? { msSinceLastActivity: Math.max(0, Date.now() - lastActivityAt) } : {}),
|
|
237
|
+
...(crossSliceUsage !== undefined ? { crossSliceUsage } : {}),
|
|
216
238
|
result: run.result ?? undefined,
|
|
217
239
|
supervisorCost,
|
|
218
240
|
suggestions,
|
|
@@ -1070,7 +1092,7 @@ async function handleRunVerbsBody(req, res, url, ctx, miss) {
|
|
|
1070
1092
|
}
|
|
1071
1093
|
const { status, body: respBody } = await deps.toolApproval.respond(id, principal, body, req);
|
|
1072
1094
|
const retryAfterSec = respBody.retryAfterSec;
|
|
1073
|
-
if (
|
|
1095
|
+
if (typeof retryAfterSec === "number" && Number.isFinite(retryAfterSec) && retryAfterSec >= 0) {
|
|
1074
1096
|
res.setHeader("retry-after", String(Math.ceil(retryAfterSec)));
|
|
1075
1097
|
}
|
|
1076
1098
|
sendJson(res, status, respBody);
|
|
@@ -1330,6 +1352,8 @@ export async function createDurableRun(req, res, ctx, prepared, idemKey) {
|
|
|
1330
1352
|
const created = await runStore.createRun(taskId, sessionId, prepared.auth?.principal ?? null, deps.instanceId ?? "default", runMeta(prepared, source));
|
|
1331
1353
|
if (created.ok)
|
|
1332
1354
|
clearTurnActivity(taskId);
|
|
1355
|
+
if (created.ok)
|
|
1356
|
+
recordResourceWindow(taskId, prepared.spec.resourceSuspend);
|
|
1333
1357
|
if (created.ok)
|
|
1334
1358
|
deps.sessionTitler?.maybeTitle(sessionId, prepared.spec.objective, typeof prepared.spec.model === "string" ? prepared.spec.model : prepared.spec.model?.id);
|
|
1335
1359
|
if (!created.ok) {
|
|
@@ -7,6 +7,7 @@ import { emitPendingWorkflowCompletions, taskNotificationInboxEntry, taskNotific
|
|
|
7
7
|
import { createLedgerSink } from "../../trace/ledger-sink.js";
|
|
8
8
|
import { registerEngineNoticeLeg } from "../../trace/engine-notice-wire.js";
|
|
9
9
|
import { clearTurnActivity, readTurnActivityMs, recordTurnActivity } from "../../turn-activity.js";
|
|
10
|
+
import { recordResourceWindow } from "../../resource-window.js";
|
|
10
11
|
import { redactSecrets } from "../../trace/redact.js";
|
|
11
12
|
import { contextUsageEventData, toolStartEventData, toolEndEventData, taskProgressEventData, taskNotificationEventData, compactedEventData, diagnosticsEventData, brainStatusEventData, steeringInjectedEventData, compactionOutcomeEventData, workspaceChangedEventData, wiringManifestEventData, wiringManifestOperatorEventData, humanInputEventData, appendModelUsageDelta, attachModelUsage } from "../../trace/project.js";
|
|
12
13
|
import { cascadeConfig, runMeta } from "../run-meta.js";
|
|
@@ -192,6 +193,8 @@ async function handleTasksBody(req, res, url, ctx, miss) {
|
|
|
192
193
|
const created = await deps.runStore.createRun(tid, prepared.spec.sessionId, principal ?? null, deps.instanceId ?? "default", runMeta(prepared, source));
|
|
193
194
|
if (created.ok)
|
|
194
195
|
clearTurnActivity(tid);
|
|
196
|
+
if (created.ok)
|
|
197
|
+
recordResourceWindow(tid, prepared.spec.resourceSuspend);
|
|
195
198
|
if (created.ok)
|
|
196
199
|
deps.sessionTitler?.maybeTitle(prepared.spec.sessionId, prepared.spec.objective, typeof prepared.spec.model === "string" ? prepared.spec.model : prepared.spec.model?.id);
|
|
197
200
|
if (!created.ok) {
|
|
@@ -333,7 +336,7 @@ async function handleTasksBody(req, res, url, ctx, miss) {
|
|
|
333
336
|
sseData(res, { type: "reasoning_delta", delta: redactSecrets(rd.delta), ...(rd.eventId ? { eventId: rd.eventId } : {}), ...(rd.parentToolCallId ? { parentToolCallId: rd.parentToolCallId } : {}) });
|
|
334
337
|
}
|
|
335
338
|
},
|
|
336
|
-
onTaskNotification: (n) => {
|
|
339
|
+
onTaskNotification: (n, opts) => {
|
|
337
340
|
if (n.task_type === "workflow")
|
|
338
341
|
return;
|
|
339
342
|
defaultSubagentTailBus.forgetHandleContentMode(n.task_id);
|
|
@@ -345,13 +348,13 @@ async function handleTasksBody(req, res, url, ctx, miss) {
|
|
|
345
348
|
const parked = !deliverable && Boolean(deps.workflowCompletionInbox && prepared.spec.sessionId);
|
|
346
349
|
deps.logger?.info?.("task_notification_observed", { route: "sync-stream", taskId: n.task_id, taskType: n.task_type, status: n.status, hadFleetRow: hadRow, legLive: syncLegLive, parkedDurable: parked });
|
|
347
350
|
if (parked) {
|
|
348
|
-
void deps.workflowCompletionInbox.enqueue(taskNotificationInboxEntry(prepared.spec.sessionId, askOwner, n, Date.now(), durableTaskId)).catch((err) => deps.logger?.warn?.("park_enqueue_failed", { route: "sync-stream", taskId: n.task_id, err: err instanceof Error ? err.message : String(err) }));
|
|
351
|
+
void deps.workflowCompletionInbox.enqueue(taskNotificationInboxEntry(prepared.spec.sessionId, askOwner, n, Date.now(), durableTaskId, opts?.priority)).catch((err) => deps.logger?.warn?.("park_enqueue_failed", { route: "sync-stream", taskId: n.task_id, err: err instanceof Error ? err.message : String(err) }));
|
|
349
352
|
}
|
|
350
353
|
else if (deliverable) {
|
|
351
354
|
const key = taskNotificationStreamKey(n);
|
|
352
355
|
if (syncNotifiedKeys.get(key) === undefined) {
|
|
353
356
|
syncNotifiedKeys.set(key, Promise.resolve(true));
|
|
354
|
-
sseData(res, { type: "task_notification", ...taskNotificationEventData({ notification: n }) });
|
|
357
|
+
sseData(res, { type: "task_notification", ...taskNotificationEventData({ notification: n, ...(opts?.priority !== undefined ? { priority: opts.priority } : {}) }) });
|
|
355
358
|
}
|
|
356
359
|
}
|
|
357
360
|
},
|
|
@@ -715,6 +718,8 @@ async function handleTasksBody(req, res, url, ctx, miss) {
|
|
|
715
718
|
const created = await deps.runStore.createRun(tid, prepared.spec.sessionId, principal ?? null, deps.instanceId ?? "default", runMeta(prepared, source));
|
|
716
719
|
if (created.ok)
|
|
717
720
|
clearTurnActivity(tid);
|
|
721
|
+
if (created.ok)
|
|
722
|
+
recordResourceWindow(tid, prepared.spec.resourceSuspend);
|
|
718
723
|
if (!created.ok)
|
|
719
724
|
return { status: 409, body: await buildActiveRunConflict({ runStore: deps.runStore, checkpointStore: deps.checkpointStore, governance: deps.config, runStaleSec: deps.config.runStaleSec, turnActivity: readTurnActivityMs }, prepared.spec.sessionId, created.activeTaskId) };
|
|
720
725
|
deps.sessionTitler?.maybeTitle(prepared.spec.sessionId, prepared.spec.objective, typeof prepared.spec.model === "string" ? prepared.spec.model : prepared.spec.model?.id);
|
package/dist/http/server.js
CHANGED
|
@@ -14,8 +14,9 @@ import { normalizeApproachNotice, validateTaskAgents } from "../spec-fields.js";
|
|
|
14
14
|
import { isValidCwd, MAX_ADDITIONAL_DIRS } from "../task-cwd.js";
|
|
15
15
|
import { runInBackground, evictIfConflict, stripCheckpointToken, parkToolCallId, TurnAnchorCapture, HEARTBEAT_MS, markChildrenStoppedByUserOnAbort } from "../runs.js";
|
|
16
16
|
import { readTurnActivityMs, recordTurnActivity } from "../turn-activity.js";
|
|
17
|
+
import { recordResumeResourceWindow } from "../resource-window.js";
|
|
17
18
|
import { publicStoreProbeError } from "../store-live-probe.js";
|
|
18
|
-
import { looksLikeJwt } from "@sema-agent/
|
|
19
|
+
import { looksLikeJwt } from "@sema-agent/settings-schema/api/auth-bridge";
|
|
19
20
|
import {} from "../orchestration/workflow-agent-steer.js";
|
|
20
21
|
import { emitPendingWorkflowCompletions, taskNotificationInboxEntry, taskNotificationStreamKey, NotifiedKeys } from "../orchestration/workflow-completion-inbox.js";
|
|
21
22
|
import { HANDS_BAND_TOOL_NAMES } from "../capabilities/hands-lane.js";
|
|
@@ -1140,6 +1141,8 @@ export function createHttpServer(rawDeps) {
|
|
|
1140
1141
|
? fleetRunPublisher(deps.fleetBus, { runId: taskId, scope: fleetScope, rootTaskId: taskId, ...fleetRunLabels(resumeObjective) })
|
|
1141
1142
|
: undefined;
|
|
1142
1143
|
const resumeTaskConfig = taskId ? { ...taskConfig, taskId } : taskConfig;
|
|
1144
|
+
if (taskId && resumeTaskConfig.resourceSuspend)
|
|
1145
|
+
recordResumeResourceWindow(taskId, resumeTaskConfig.resourceSuspend);
|
|
1143
1146
|
let fleetSettled = false;
|
|
1144
1147
|
const settleFleet = (status, residuals) => {
|
|
1145
1148
|
if (fleetSettled)
|
|
@@ -1246,7 +1249,7 @@ export function createHttpServer(rawDeps) {
|
|
|
1246
1249
|
void verifySink.appendStatus(e).catch((err) => deps.logger?.warn?.("status_event_append_failed", { route: "resume-verify", taskId, err: err instanceof Error ? err.message : String(err) }));
|
|
1247
1250
|
}
|
|
1248
1251
|
},
|
|
1249
|
-
onTaskNotification: (n) => {
|
|
1252
|
+
onTaskNotification: (n, opts) => {
|
|
1250
1253
|
if (n.task_type === "workflow")
|
|
1251
1254
|
return;
|
|
1252
1255
|
defaultSubagentTailBus.forgetHandleContentMode(n.task_id);
|
|
@@ -1257,12 +1260,12 @@ export function createHttpServer(rawDeps) {
|
|
|
1257
1260
|
const parked = !resumeLegLive && Boolean(deps.workflowCompletionInbox && sessionId);
|
|
1258
1261
|
deps.logger?.info?.("task_notification_observed", { route: "resume-verify", taskId: n.task_id, taskType: n.task_type, status: n.status, hadFleetRow: hadRow, legLive: resumeLegLive, parkedDurable: parked });
|
|
1259
1262
|
if (parked) {
|
|
1260
|
-
void deps.workflowCompletionInbox.enqueue(taskNotificationInboxEntry(sessionId, principal ?? null, n, Date.now(), taskId)).catch((err) => deps.logger?.warn?.("park_enqueue_failed", { route: "resume-verify", taskId: n.task_id, err: err instanceof Error ? err.message : String(err) }));
|
|
1263
|
+
void deps.workflowCompletionInbox.enqueue(taskNotificationInboxEntry(sessionId, principal ?? null, n, Date.now(), taskId, opts?.priority)).catch((err) => deps.logger?.warn?.("park_enqueue_failed", { route: "resume-verify", taskId: n.task_id, err: err instanceof Error ? err.message : String(err) }));
|
|
1261
1264
|
}
|
|
1262
1265
|
else if (resumeLegLive) {
|
|
1263
1266
|
const key = taskNotificationStreamKey(n);
|
|
1264
1267
|
if (resumeNotifiedKeys.get(key) === undefined) {
|
|
1265
|
-
resumeNotifiedKeys.set(key, vAppend("task_notification", taskNotificationEventData({ notification: n })).then(() => true, () => false));
|
|
1268
|
+
resumeNotifiedKeys.set(key, vAppend("task_notification", taskNotificationEventData({ notification: n, ...(opts?.priority !== undefined ? { priority: opts.priority } : {}) })).then(() => true, () => false));
|
|
1266
1269
|
}
|
|
1267
1270
|
}
|
|
1268
1271
|
},
|
|
@@ -1373,7 +1376,7 @@ export function createHttpServer(rawDeps) {
|
|
|
1373
1376
|
void append("tool_end", toolEndEventData(e)).catch(warnAppend(t));
|
|
1374
1377
|
}
|
|
1375
1378
|
},
|
|
1376
|
-
onTaskNotification: (n) => {
|
|
1379
|
+
onTaskNotification: (n, opts) => {
|
|
1377
1380
|
if (n.task_type === "workflow")
|
|
1378
1381
|
return;
|
|
1379
1382
|
defaultSubagentTailBus.forgetHandleContentMode(n.task_id);
|
|
@@ -1384,12 +1387,12 @@ export function createHttpServer(rawDeps) {
|
|
|
1384
1387
|
const parked = !resumeLegLive && Boolean(deps.workflowCompletionInbox && sessionId);
|
|
1385
1388
|
deps.logger?.info?.("task_notification_observed", { route: "resume", taskId: n.task_id, taskType: n.task_type, status: n.status, hadFleetRow: hadRow, legLive: resumeLegLive, parkedDurable: parked });
|
|
1386
1389
|
if (parked) {
|
|
1387
|
-
void deps.workflowCompletionInbox.enqueue(taskNotificationInboxEntry(sessionId, principal ?? null, n, Date.now(), taskId)).catch((err) => deps.logger?.warn?.("park_enqueue_failed", { route: "resume", taskId: n.task_id, err: err instanceof Error ? err.message : String(err) }));
|
|
1390
|
+
void deps.workflowCompletionInbox.enqueue(taskNotificationInboxEntry(sessionId, principal ?? null, n, Date.now(), taskId, opts?.priority)).catch((err) => deps.logger?.warn?.("park_enqueue_failed", { route: "resume", taskId: n.task_id, err: err instanceof Error ? err.message : String(err) }));
|
|
1388
1391
|
}
|
|
1389
1392
|
else if (resumeLegLive) {
|
|
1390
1393
|
const key = taskNotificationStreamKey(n);
|
|
1391
1394
|
if (resumeNotifiedKeys.get(key) === undefined) {
|
|
1392
|
-
resumeNotifiedKeys.set(key, append("task_notification", taskNotificationEventData({ notification: n })).then(() => true, () => false));
|
|
1395
|
+
resumeNotifiedKeys.set(key, append("task_notification", taskNotificationEventData({ notification: n, ...(opts?.priority !== undefined ? { priority: opts.priority } : {}) })).then(() => true, () => false));
|
|
1393
1396
|
}
|
|
1394
1397
|
}
|
|
1395
1398
|
},
|
|
@@ -1608,6 +1611,7 @@ export function createHttpServer(rawDeps) {
|
|
|
1608
1611
|
return {
|
|
1609
1612
|
status,
|
|
1610
1613
|
body: {
|
|
1614
|
+
...(taskId !== undefined ? { taskId } : {}),
|
|
1611
1615
|
error: e.message,
|
|
1612
1616
|
errorCode: e.code === "checkpoint.invalid_outcome"
|
|
1613
1617
|
? (outcome.gate === "policy_ask" ? "approval_binding_mismatch" : "resume_outcome_invalid")
|
|
@@ -105,6 +105,10 @@ export declare const FAIL_OPEN_TAGS: {
|
|
|
105
105
|
readonly cls: "F";
|
|
106
106
|
readonly note: "#193 车5(staleness-sweep P1-3):OTLP 周期导出失败(HTTP 非 2xx 或 fetch 拒绝)⇒ 丢弃本轮快照继续服务。导出本就 best-effort(collector 打嗝绝不影响 serving,方向不改),但此前唯一留痕是装配层 onError 的一条 warn——**metrics 轴零信号**,而 USAGE 力荐的 Prometheus-only 部署恰好只看 metrics ⇒ collector 持续宕机对运维完全不可见(遥测腿自盲)。放行的最坏后果 = 一段时间的指标断供;计数让「断供正在发生」本身成为一条指标。";
|
|
107
107
|
};
|
|
108
|
+
readonly "server.runs.cross-slice-usage-unavailable": {
|
|
109
|
+
readonly cls: "F";
|
|
110
|
+
readonly note: "[3833] S-4:`GET /v1/runs/:id` 的 running 态跨片用量投影(`crossSliceUsage`)在**已登记跨片窗**的 run 上,因账本读不可用而整键缺席 —— 两形:`runStore.getEvents` 抛(store 抖动/连接断),或降级/部分实现的 store 根本没有 `getEvents`。放行的最坏后果 = **预警面缺料**:运维读不到「已耗 / 上限」这一对,退回既有的事后姿势(等行翻 `suspended` + `resource_limit` gate 才知道逼近过)——不参与任何门/CAS/resume 判定(跨片额度的执法读的是 core 挂在 checkpoint 行上的 `ResourceLedger`,不经本投影),故 F 类。**方向刻意选缺席而不是铸零**:`spentTokens:0` / `spentMicroUsd:0` 在观测不到用量的那一刻恰好长得像「还没花钱」,是比缺席更坏的假象(RB-368「不知道≠免费」同一条纪律)。留痕理由:缺席与「这条 run 本来就没配跨片窗」在 wire 上完全同形,不计数则「投影为什么一直不出现」只能靠间接症状发现。红先=`test/resource-suspend.test.ts` 的 S-4 账本不可用两格(读抛 / 店无 getEvents ⇒ 计数 +1 且**无**零值投影)";
|
|
111
|
+
};
|
|
108
112
|
readonly "server.approvals.active-run-conflict-material-unavailable": {
|
|
109
113
|
readonly cls: "F";
|
|
110
114
|
readonly note: "A-057.47:`buildActiveRunConflict` 的材料装配段(getRun / turnActivity / peekPendingScope / findPendingTokenBySession / checkpoint `get`)任一失败 ⇒ 整段退化成裸 409(只剩 error + errorCode + activeTaskId),`activeTaskStatus` / `msSinceLastActivity` / `pendingGate`(kind·decidePath·governanceForced·checkpointId)全部蒸发。放行的最坏后果 = **展示/分诊**面缺料:壳画不出「这条 run 卡在哪道门、去哪儿决」,人退回 `POST /v1/runs/{activeTaskId}/cancel` 这条保底真路 —— 不参与任何门/CAS/resume 判定(执法面读的是 checkpoint blob 的 `get()`,不经本材料;与 census 第 21 行同一条判据),故 F 类。方向刻意不改:本材料是 best-effort 增强,让它抛会把一次 store 抖动变成整个 409 路径的 500(顶注第 11 行逐字成文「store 面任何失败都不得挡 409 本体」)。必须留痕的理由:本文件零 logger 席、pool 层无 per-query 错误日志、调用侧(tasks.ts / runs.ts / server.ts 五处)因本函数恒不 reject 结构上拿不到信号 ⇒ 「approval 出路材料系统性丢失」此前在遥测里与「一切正常」同形;滚动升级期 `checkpoint-store-sql.ts` 的 version-too-new throw 与 strict parseJson 也一并被吞在这里。";
|
|
@@ -117,6 +121,10 @@ export declare const FAIL_OPEN_TAGS: {
|
|
|
117
121
|
readonly cls: "F";
|
|
118
122
|
readonly note: "#310:`engine_notice` 分流器把一条白名单通告投给某条 run 腿的登记口时,那只口抛了(live 口写向已断/已撕裂的 SSE socket,或 durable 口的账本写同步抛)。放行的最坏后果 = **这一条通告的这一个终点**缺席:①日志终点在分流之前已经逐字打过(事实一条不丢);②两个终点注册成两只独立 sink ⇒ live 抛不牵连 durable(断连后仍看得见的那半保住);③同会话其余口照投。故 F 类。不放行的代价是把异常回抛给 core 的 `deliverEngineNotice` —— 它会吞掉,于是同一次失败**既没有留痕也没有第二只口**,正是本 tag 要根除的形。留痕是承重的:静默吞掉之后「wire 腿为什么总有几条通告不到」在遥测里与「core 本来就没发」同形。";
|
|
119
123
|
};
|
|
124
|
+
readonly "server.hooks.notice-sink-threw": {
|
|
125
|
+
readonly cls: "F";
|
|
126
|
+
readonly note: "#281:hook 观测回调(`onHookNotice`,部署把它接到 fleet 流)自己抛了。放行的最坏后果 = **这一条观测帧**缺席;补偿是结构性的:①日志终点在投递之前就已逐字落定(`hook_command_failed` / `hook_command_timeout` / `hook_command_spawn_failed` 一族),运维面零回退;②观测帧不参与任何门/裁决(纯 observe,#281 全族判据里「裁决面一个字节不动」是承重条款),故 F 类。不放行的代价严重不对称:异常会掀回 core 的 hook 回调栈,把一次**观察动作**变成一次**工具调用失败** —— 「观察一件事的动作反过来改变了那件事」正是本 tag 要根除的形,而它伤的恰恰是 hook 已经坏掉、用户最需要任务照跑的那一刻。留痕承重:静默吞掉之后「这台机器为什么一条 hook 通知都没有」在遥测里与「hook 从来没坏过」同形。";
|
|
127
|
+
};
|
|
120
128
|
readonly "server.park.toolcallid-read-failed": {
|
|
121
129
|
readonly cls: "F";
|
|
122
130
|
readonly note: "[4913]:durable park 投影腿在 strip 之前拿结果里的 checkpointToken 换 `pendingAction.toolCallId`(cs.get 一次读),那次读**抛了**(store 抖动 / 滚动升级期 checkpoint 格式 version guard / 行已被并发消费)⇒ 本次 park 的 wire 投影**缺 `toolCallId` 键**,其余键(gate/checkpointId)照旧。放行的最坏后果 = 消费方(cli 判别子 v3 写者②)退回该键到货前的行为——同族多兄弟 durable park 分不出主角、诚实全不标(cli 侧 S3 局限,成文的旧现状),纯展示/关联面,不参与任何门/CAS/resume 判定,故 F 类。绝不挡终局路径是承重的:park 投影点全在 done/suspended 事件写链上,让它抛会把一次 store 抖动升级成整条 run 终局写失败。必须留痕:键缺席与「tool-less park 本就无键」([1995]② OMITTED 契约)在 wire 上同形,不计数则「投影为什么总缺」在遥测里永不显形。";
|
|
@@ -96,6 +96,10 @@ export const FAIL_OPEN_TAGS = {
|
|
|
96
96
|
cls: "F",
|
|
97
97
|
note: "#193 车5(staleness-sweep P1-3):OTLP 周期导出失败(HTTP 非 2xx 或 fetch 拒绝)⇒ 丢弃本轮快照继续服务。导出本就 best-effort(collector 打嗝绝不影响 serving,方向不改),但此前唯一留痕是装配层 onError 的一条 warn——**metrics 轴零信号**,而 USAGE 力荐的 Prometheus-only 部署恰好只看 metrics ⇒ collector 持续宕机对运维完全不可见(遥测腿自盲)。放行的最坏后果 = 一段时间的指标断供;计数让「断供正在发生」本身成为一条指标。",
|
|
98
98
|
},
|
|
99
|
+
"server.runs.cross-slice-usage-unavailable": {
|
|
100
|
+
cls: "F",
|
|
101
|
+
note: "[3833] S-4:`GET /v1/runs/:id` 的 running 态跨片用量投影(`crossSliceUsage`)在**已登记跨片窗**的 run 上,因账本读不可用而整键缺席 —— 两形:`runStore.getEvents` 抛(store 抖动/连接断),或降级/部分实现的 store 根本没有 `getEvents`。放行的最坏后果 = **预警面缺料**:运维读不到「已耗 / 上限」这一对,退回既有的事后姿势(等行翻 `suspended` + `resource_limit` gate 才知道逼近过)——不参与任何门/CAS/resume 判定(跨片额度的执法读的是 core 挂在 checkpoint 行上的 `ResourceLedger`,不经本投影),故 F 类。**方向刻意选缺席而不是铸零**:`spentTokens:0` / `spentMicroUsd:0` 在观测不到用量的那一刻恰好长得像「还没花钱」,是比缺席更坏的假象(RB-368「不知道≠免费」同一条纪律)。留痕理由:缺席与「这条 run 本来就没配跨片窗」在 wire 上完全同形,不计数则「投影为什么一直不出现」只能靠间接症状发现。红先=`test/resource-suspend.test.ts` 的 S-4 账本不可用两格(读抛 / 店无 getEvents ⇒ 计数 +1 且**无**零值投影)",
|
|
102
|
+
},
|
|
99
103
|
"server.approvals.active-run-conflict-material-unavailable": {
|
|
100
104
|
cls: "F",
|
|
101
105
|
note: "A-057.47:`buildActiveRunConflict` 的材料装配段(getRun / turnActivity / peekPendingScope / findPendingTokenBySession / checkpoint `get`)任一失败 ⇒ 整段退化成裸 409(只剩 error + errorCode + activeTaskId),`activeTaskStatus` / `msSinceLastActivity` / `pendingGate`(kind·decidePath·governanceForced·checkpointId)全部蒸发。放行的最坏后果 = **展示/分诊**面缺料:壳画不出「这条 run 卡在哪道门、去哪儿决」,人退回 `POST /v1/runs/{activeTaskId}/cancel` 这条保底真路 —— 不参与任何门/CAS/resume 判定(执法面读的是 checkpoint blob 的 `get()`,不经本材料;与 census 第 21 行同一条判据),故 F 类。方向刻意不改:本材料是 best-effort 增强,让它抛会把一次 store 抖动变成整个 409 路径的 500(顶注第 11 行逐字成文「store 面任何失败都不得挡 409 本体」)。必须留痕的理由:本文件零 logger 席、pool 层无 per-query 错误日志、调用侧(tasks.ts / runs.ts / server.ts 五处)因本函数恒不 reject 结构上拿不到信号 ⇒ 「approval 出路材料系统性丢失」此前在遥测里与「一切正常」同形;滚动升级期 `checkpoint-store-sql.ts` 的 version-too-new throw 与 strict parseJson 也一并被吞在这里。",
|
|
@@ -108,6 +112,10 @@ export const FAIL_OPEN_TAGS = {
|
|
|
108
112
|
cls: "F",
|
|
109
113
|
note: "#310:`engine_notice` 分流器把一条白名单通告投给某条 run 腿的登记口时,那只口抛了(live 口写向已断/已撕裂的 SSE socket,或 durable 口的账本写同步抛)。放行的最坏后果 = **这一条通告的这一个终点**缺席:①日志终点在分流之前已经逐字打过(事实一条不丢);②两个终点注册成两只独立 sink ⇒ live 抛不牵连 durable(断连后仍看得见的那半保住);③同会话其余口照投。故 F 类。不放行的代价是把异常回抛给 core 的 `deliverEngineNotice` —— 它会吞掉,于是同一次失败**既没有留痕也没有第二只口**,正是本 tag 要根除的形。留痕是承重的:静默吞掉之后「wire 腿为什么总有几条通告不到」在遥测里与「core 本来就没发」同形。",
|
|
110
114
|
},
|
|
115
|
+
"server.hooks.notice-sink-threw": {
|
|
116
|
+
cls: "F",
|
|
117
|
+
note: "#281:hook 观测回调(`onHookNotice`,部署把它接到 fleet 流)自己抛了。放行的最坏后果 = **这一条观测帧**缺席;补偿是结构性的:①日志终点在投递之前就已逐字落定(`hook_command_failed` / `hook_command_timeout` / `hook_command_spawn_failed` 一族),运维面零回退;②观测帧不参与任何门/裁决(纯 observe,#281 全族判据里「裁决面一个字节不动」是承重条款),故 F 类。不放行的代价严重不对称:异常会掀回 core 的 hook 回调栈,把一次**观察动作**变成一次**工具调用失败** —— 「观察一件事的动作反过来改变了那件事」正是本 tag 要根除的形,而它伤的恰恰是 hook 已经坏掉、用户最需要任务照跑的那一刻。留痕承重:静默吞掉之后「这台机器为什么一条 hook 通知都没有」在遥测里与「hook 从来没坏过」同形。",
|
|
118
|
+
},
|
|
111
119
|
"server.park.toolcallid-read-failed": {
|
|
112
120
|
cls: "F",
|
|
113
121
|
note: "[4913]:durable park 投影腿在 strip 之前拿结果里的 checkpointToken 换 `pendingAction.toolCallId`(cs.get 一次读),那次读**抛了**(store 抖动 / 滚动升级期 checkpoint 格式 version guard / 行已被并发消费)⇒ 本次 park 的 wire 投影**缺 `toolCallId` 键**,其余键(gate/checkpointId)照旧。放行的最坏后果 = 消费方(cli 判别子 v3 写者②)退回该键到货前的行为——同族多兄弟 durable park 分不出主角、诚实全不标(cli 侧 S3 局限,成文的旧现状),纯展示/关联面,不参与任何门/CAS/resume 判定,故 F 类。绝不挡终局路径是承重的:park 投影点全在 done/suspended 事件写链上,让它抛会把一次 store 抖动升级成整条 run 终局写失败。必须留痕:键缺席与「tool-less park 本就无键」([1995]② OMITTED 契约)在 wire 上同形,不计数则「投影为什么总缺」在遥测里永不显形。",
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SystemInjectionPriority } from "@sema-agent/core";
|
|
1
2
|
import type { LedgerEventType } from "../trace/ledger-events.js";
|
|
2
3
|
/** One pending completion, scoped to the session that must be told about it. `summary` is ALREADY
|
|
3
4
|
* redacted + length-bounded by core's notifier seam (see {@link WorkflowCompletionPayload}). */
|
|
@@ -262,7 +263,17 @@ export declare function taskNotificationInboxEntry(sessionId: string, owner: str
|
|
|
262
263
|
/** lead-b (dual-ID audit): the PARENT run's durable taskId (the uuid the shell's footer rows
|
|
263
264
|
* key on) — rides the drained frame so a consumer can bind the a*-keyed child notification to its uuid-keyed
|
|
264
265
|
* parent row without a side lookup. */
|
|
265
|
-
parentTaskId?: string
|
|
266
|
+
parentTaskId?: string,
|
|
267
|
+
/**
|
|
268
|
+
* design/373 §3.6(core 5.61.0,#366 / codex R1[high]):core 在 `onTaskNotification` 的**第二参**上报的
|
|
269
|
+
* 投递档位。park 是**跨 run** 的那条投递路径 —— 不带过去,档位就在最常走的一条路上恒缺席。
|
|
270
|
+
*
|
|
271
|
+
* 🔴 只在 core **真的给了**档位时传:缺席原样缺席(与 live 投影同一条「缺席≠later」纪律)。
|
|
272
|
+
* 闭集之外的值当作缺席(下面的 `INJECTION_TIERS` 守卫)——durable 载荷更不该出现引擎从没发过的词。
|
|
273
|
+
* ⚠️ 本仓自己铸的 park(`POST /v1/sessions/:id/notify` 的 idle 半场)**不传**这一位:那条 park 是
|
|
274
|
+
* 纯展示帧,没有任何引擎侧的档位承诺,填一个词就是凭空铸一条投递声明。
|
|
275
|
+
*/
|
|
276
|
+
priority?: SystemInjectionPriority): WorkflowCompletionInboxEntry;
|
|
266
277
|
/**
|
|
267
278
|
* Resolve WHERE a workflow completion routes (core 1.208): the SESSION comes straight off
|
|
268
279
|
* `originatingSessionId` (the Runner closes over it at RunWorkflow mount — lookup-free). The OWNER comes from,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { mkdirSync, readFileSync, existsSync, openSync, writeSync, fsyncSync, closeSync, renameSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { redactSecrets } from "../trace/redact.js";
|
|
4
|
+
import { injectionTierOrAbsent } from "../trace/injection-tier.js";
|
|
4
5
|
export const MAX_PENDING_PER_SESSION = 100;
|
|
5
6
|
export const COMPACT_EVERY = 512;
|
|
6
7
|
export const PURGE_FENCE_MS = 10 * 60 * 1000;
|
|
@@ -288,10 +289,14 @@ export async function emitPendingWorkflowCompletions(inbox, sessionId, callerPri
|
|
|
288
289
|
}
|
|
289
290
|
}
|
|
290
291
|
}
|
|
291
|
-
export function taskNotificationInboxEntry(sessionId, owner, n, enqueuedAt, parentTaskId) {
|
|
292
|
+
export function taskNotificationInboxEntry(sessionId, owner, n, enqueuedAt, parentTaskId, priority) {
|
|
292
293
|
const cap = (s, max) => (s.length > max ? `${s.slice(0, max)}…[+${s.length - max} chars]` : s);
|
|
293
294
|
const extras = {
|
|
294
295
|
task_type: n.task_type,
|
|
296
|
+
...(() => {
|
|
297
|
+
const tier = injectionTierOrAbsent(priority);
|
|
298
|
+
return tier !== undefined ? { priority: tier } : {};
|
|
299
|
+
})(),
|
|
295
300
|
...(parentTaskId ? { parentTaskId } : {}),
|
|
296
301
|
...(n.sessionId ? { sessionId: n.sessionId } : {}),
|
|
297
302
|
...(n.toolUseId ? { toolUseId: n.toolUseId } : {}),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PrincipalOrgMemoryWire } from "@sema-agent/
|
|
1
|
+
import { PrincipalOrgMemoryWire } from "@sema-agent/settings-schema";
|
|
2
2
|
import { assertPrincipalShape } from "./security.js";
|
|
3
3
|
const isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
4
4
|
const ORG_SCOPE_RE = /^org:\S+$/;
|
|
@@ -62,6 +62,8 @@ export class InMemoryApprovalAskStore {
|
|
|
62
62
|
gateBoundInputHash: null,
|
|
63
63
|
idempotencyKey: null,
|
|
64
64
|
cardJson: row.cardJson,
|
|
65
|
+
ruleCommand: row.ruleCommand ?? null,
|
|
66
|
+
ruleScopeRoot: row.ruleScopeRoot ?? null,
|
|
65
67
|
schemaVersion: row.schemaVersion,
|
|
66
68
|
expiresAtMs: row.expiresAtMs,
|
|
67
69
|
createdAtMs: row.createdAtMs,
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
import type { Pool as MySqlPool } from "mysql2/promise";
|
|
40
40
|
import type { Pool as PgPool } from "pg";
|
|
41
41
|
import type { PgQueryFn } from "./pg-query.js";
|
|
42
|
-
import { type SqlDriver } from "./sql-driver.js";
|
|
42
|
+
import { type SqlDriver, type SqlDialect } from "./sql-driver.js";
|
|
43
43
|
import { type AskState, type BatchState } from "../approval-ask-machine.js";
|
|
44
44
|
export type AskDecision = "approve" | "deny";
|
|
45
45
|
export interface AskRow {
|
|
@@ -94,6 +94,26 @@ export interface AskRow {
|
|
|
94
94
|
idempotencyKey: string | null;
|
|
95
95
|
/** 重放腿的帧载荷(args 已帽已洗后的投影)。 */
|
|
96
96
|
cardJson: unknown;
|
|
97
|
+
/**
|
|
98
|
+
* #363 —— **规则车道素材**两列之一:这只 ask 被裁决的**命令**(已过基础脱敏,见 `tool-approval.ts`
|
|
99
|
+
* 的落盘点)。`null` = 这只 ask 从没进过规则车道(治理档 / 无属主 / 引擎没铸候选 / args 读不出命令),
|
|
100
|
+
* 或它由**加这两列之前**的构建落的行。
|
|
101
|
+
*
|
|
102
|
+
* 🔴 **为什么必须是行上的一列,而不是从 `card_json` 里挖**:卡上有的是 `ruleOffers[].command`
|
|
103
|
+
* ——那是**每条候选**的去规范化命令(batch 臂上是**分段**),不是被裁决的那一条整命令;而
|
|
104
|
+
* `persistCardRule` 的覆盖门与候选重铸吃的正是后者。拿分段当整命令喂进去 = 让一条**我们自己切过**
|
|
105
|
+
* 的命令去决定一条常驻放行规则的形状。
|
|
106
|
+
*
|
|
107
|
+
* 🔴 **LONGTEXT/TEXT,不是 VARCHAR**(与 `permission_rule_approval.command` 同款同理由):命令行没有
|
|
108
|
+
* 入口上限,VARCHAR 会造一个静默截断面,而截断过的命令与原命令是两条不同的命令。
|
|
109
|
+
*/
|
|
110
|
+
ruleCommand: string | null;
|
|
111
|
+
/**
|
|
112
|
+
* #363 —— 规则车道素材两列之二:**授权发生地**的 project root(`ruleScopeRootFor` 在**铸卡时**咨询
|
|
113
|
+
* 的那一份,#295 F-1 的快照语义)。`null` = 解析不出 root ⇒ 兑付时**不铸 scope**,core 落 global
|
|
114
|
+
* (= live 腿逐字同形;绝不在坐标系不明时编一个 root)。
|
|
115
|
+
*/
|
|
116
|
+
ruleScopeRoot: string | null;
|
|
97
117
|
schemaVersion: number;
|
|
98
118
|
/** 一次铸定永不重算。 */
|
|
99
119
|
expiresAtMs: number;
|
|
@@ -114,6 +134,11 @@ export interface NewAskRow {
|
|
|
114
134
|
/** 车5 §9 C2 的对账 join 键(语义见 `AskRow.boundInputHash`)。缺席 ⇒ 该行结构上永不满足判据 1。 */
|
|
115
135
|
boundInputHash?: string | null;
|
|
116
136
|
cardJson: unknown;
|
|
137
|
+
/** #363 规则车道素材(语义与「为什么是行上的列」见 {@link AskRow.ruleCommand})。缺席 ⇒ 列 NULL ⇒
|
|
138
|
+
* 这条行上的迟到决议对 `persistRule` 响亮拒(`rule_material_absent`),绝不猜命令。 */
|
|
139
|
+
ruleCommand?: string | null;
|
|
140
|
+
/** #363 授权发生地(语义见 {@link AskRow.ruleScopeRoot})。 */
|
|
141
|
+
ruleScopeRoot?: string | null;
|
|
117
142
|
schemaVersion: number;
|
|
118
143
|
expiresAtMs: number;
|
|
119
144
|
createdAtMs: number;
|
|
@@ -337,6 +362,30 @@ export declare const TIDB_APPROVAL_ASK_STATEMENTS: readonly string[];
|
|
|
337
362
|
* (那里展开了同一份数组),本函数留给只需要这两张表的集成测试。 */
|
|
338
363
|
export declare function ensureTiDBApprovalAskSchema(pool: MySqlPool): Promise<void>;
|
|
339
364
|
export declare function ensurePgApprovalAskSchema(q: PgQueryFn): Promise<void>;
|
|
365
|
+
/**
|
|
366
|
+
* #363 升级前置断言 —— **拒启**,不是 warn(形照 #340 的 `assertPermissionRuleApprovalSchema` /
|
|
367
|
+
* #119 的 `assertToolResultProvenanceSchema` 两条先例)。
|
|
368
|
+
*
|
|
369
|
+
* 病:本仓不发 `ALTER TABLE`(SCHEMA POLICY:改列就改 CREATE + 删库重建)。于是一台**没删表**就升上来
|
|
370
|
+
* 的部署,`CREATE TABLE IF NOT EXISTS` 对存量 `approval_ask` 是空操作 —— 本车新加的
|
|
371
|
+
* `rule_command` / `rule_scope_root` 两列不在,而 `ensureAsk` 的 INSERT 与 `ASK_COLS` 的每一条读
|
|
372
|
+
* **无条件**引用它们。后果不是「少一个新功能」,是**整条流内审批协议**在那台机器上是坏的:
|
|
373
|
+
* · 每一只 ask 的 `ensureAsk` 撞 unknown column ⇒ 被 `noteStoreError` 吞掉 ⇒ 整只 ask 退回 park 路由
|
|
374
|
+
* (卡不落库、`GET /v1/approvals` 的重放面恒空、迟到决议腿恒 404);
|
|
375
|
+
* · 而 `/v1/capabilities` 的 `streamApproval` 仍然报 active ⇒「says yes ⟺ route works」整句为假。
|
|
376
|
+
* 没有这道断言,运维得不到**任何**「这次升级必须重建表」的信号 —— 正是 #157「禁静默降级」要挡的形。
|
|
377
|
+
*
|
|
378
|
+
* 判据 = **能力探测**(恒空的 `WHERE 1=0` 读)+ **方言的缺列错误码**(判据属主 `sql-errors.ts` 的
|
|
379
|
+
* {@link isMissingColumnError});其余错误**原样 rethrow**,一个字都不加工 —— 一句破坏性的
|
|
380
|
+
* 「去 DROP TABLE」指路比它要挡的缺陷更贵(#340 那两轮收窄的结论逐字继承)。
|
|
381
|
+
*
|
|
382
|
+
* 🔴 位置与两条先例同款:**不在** `ensureSchema` 里(那条通道的契约是「只发 CREATE」,有运行时门看着),
|
|
383
|
+
* 放在 DDL 之后、任何路由装配之前;且**只在流内审批协议真会上场时**跑(判据 = 与协调器同一个符号
|
|
384
|
+
* `resolveStreamApprovalGate`,见调用点)——协议不上场的部署根本不碰这张表,为它拒启是纯误伤。
|
|
385
|
+
*/
|
|
386
|
+
export declare function assertApprovalAskRuleMaterialSchema(query: (sql: string) => Promise<{
|
|
387
|
+
rows: Record<string, unknown>[];
|
|
388
|
+
}>, dialect: SqlDialect): Promise<void>;
|
|
340
389
|
/** 双方言 `ApprovalAskStore`。见文件头注的 CAS 铁则 + 方言差异清单。 */
|
|
341
390
|
export declare class SqlApprovalAskStore implements ApprovalAskStore {
|
|
342
391
|
private readonly db;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { mysqlDriver, pgDriver, dialectJsonEncoder } from "./sql-driver.js";
|
|
2
2
|
import { canAskTransition } from "../approval-ask-machine.js";
|
|
3
|
-
import { isDupKeyError } from "./sql-errors.js";
|
|
3
|
+
import { isDupKeyError, isMissingColumnError } from "./sql-errors.js";
|
|
4
4
|
export function assertIdempotencyKeyShape(key) {
|
|
5
5
|
if (key.length === 0 || key.length > 255 || key.trim() !== key) {
|
|
6
6
|
throw new Error(`invalid idempotency key: must be 1-255 chars with no leading/trailing whitespace (got ${JSON.stringify(key.slice(0, 32))}${key.length > 32 ? "…" : ""}, length ${key.length})`);
|
|
@@ -79,6 +79,13 @@ export const TIDB_APPROVAL_ASK_STATEMENTS = [
|
|
|
79
79
|
idempotency_key VARCHAR(255) NULL,
|
|
80
80
|
-- LONGTEXT 照 image-bake/background-agent 的 pending_steer 先例:重放帧载荷可能超 64K TEXT 墙。
|
|
81
81
|
card_json LONGTEXT NOT NULL,
|
|
82
|
+
-- #363 规则车道素材两列(语义/类型理由逐字见 AskRow.ruleCommand / ruleScopeRoot 的顶注)。
|
|
83
|
+
-- rule_command 与 permission_rule_approval.command 同款 LONGTEXT:命令行没有入口上限,VARCHAR
|
|
84
|
+
-- 会造一个静默截断面,而截断过的命令与原命令是两条不同的命令(覆盖门会据一条我们自己改过的命令判)。
|
|
85
|
+
rule_command LONGTEXT NULL,
|
|
86
|
+
-- rule_scope_root:root 的真上界 = task-cwd.ts 的 MAX_CWD_CHARS(4096,入口 isValidCwd 硬拒更长者),
|
|
87
|
+
-- 宽度与那把尺同源 —— 与 MAX_RULE_SCOPE_CHARS 的取值法(由铸侧的尺派生)逐字同精神。
|
|
88
|
+
rule_scope_root VARCHAR(4096) NULL,
|
|
82
89
|
schema_version INT NOT NULL,
|
|
83
90
|
expires_at_ms BIGINT NOT NULL,
|
|
84
91
|
created_at_ms BIGINT NOT NULL,
|
|
@@ -140,6 +147,9 @@ export async function ensurePgApprovalAskSchema(q) {
|
|
|
140
147
|
gate_bound_input_hash VARCHAR(255) COLLATE "C",
|
|
141
148
|
idempotency_key VARCHAR(255) COLLATE "C",
|
|
142
149
|
card_json TEXT COLLATE "C" NOT NULL,
|
|
150
|
+
-- #363 规则车道素材两列 —— MySQL 孪生逐字同形(类型/宽度的取值理由写在那侧的行内注)。
|
|
151
|
+
rule_command TEXT COLLATE "C",
|
|
152
|
+
rule_scope_root VARCHAR(4096) COLLATE "C",
|
|
143
153
|
schema_version INT NOT NULL,
|
|
144
154
|
expires_at_ms BIGINT NOT NULL,
|
|
145
155
|
created_at_ms BIGINT NOT NULL,
|
|
@@ -153,9 +163,30 @@ export async function ensurePgApprovalAskSchema(q) {
|
|
|
153
163
|
await q(`CREATE INDEX IF NOT EXISTS idx_ask_batch ON ${APPROVAL_ASK_TABLE} (batch_id)`);
|
|
154
164
|
await q(`CREATE INDEX IF NOT EXISTS idx_ask_state ON ${APPROVAL_ASK_TABLE} (state)`);
|
|
155
165
|
}
|
|
166
|
+
export async function assertApprovalAskRuleMaterialSchema(query, dialect) {
|
|
167
|
+
try {
|
|
168
|
+
await query(`SELECT rule_command, rule_scope_root FROM ${APPROVAL_ASK_TABLE} WHERE 1=0`);
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
if (!isMissingColumnError(err, dialect))
|
|
172
|
+
throw err;
|
|
173
|
+
throw new Error(`${APPROVAL_ASK_TABLE} is missing the #363 rule-material columns (rule_command / rule_scope_root) — refusing to start. ` +
|
|
174
|
+
`A parked approval's late decision can now carry \`persistRule\` ("don't ask again"), and the row is where the ` +
|
|
175
|
+
`adjudicated command and the project root of the authorization site live; every ask-row write and read names ` +
|
|
176
|
+
`both columns unconditionally, so on this table the whole in-stream approval protocol degrades silently (no card ` +
|
|
177
|
+
`is persisted, the replay list stays empty, late decisions 404) while /v1/capabilities still reports it active. ` +
|
|
178
|
+
`This repository ships no ALTER TABLE migrations, so the table must be recreated: run ` +
|
|
179
|
+
`\`DROP TABLE ${APPROVAL_ASK_TABLE}; DROP TABLE ${APPROVAL_BATCH_TABLE};\` on the ` +
|
|
180
|
+
`${dialect === "pg" ? "PostgreSQL" : "MySQL-protocol"} backend and restart — the schema is recreated at boot. ` +
|
|
181
|
+
`The cost is bounded: these two tables hold IN-FLIGHT approval asks (cards awaiting an answer) plus settled ` +
|
|
182
|
+
`bookkeeping; the durable park face (checkpoint rows) and the persisted rules themselves are untouched, so an ` +
|
|
183
|
+
`in-flight card falls back to the durable gate (\`POST /v1/approvals/:sessionId/decide\`). ` +
|
|
184
|
+
`Underlying probe error: ${err instanceof Error ? err.message : String(err)}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
156
187
|
const ASK_COLS = "ask_id, task_id, source_task_id, session_id, owner, batch_id, tool_call_id, leg_key, parent_tool_call_id, bound_input_hash, state, " +
|
|
157
188
|
"provisional, rev, decision, decision_actor, decision_note, decided_at_ms, denied_reason, gate_token, " +
|
|
158
|
-
"gate_bound_call_id, gate_bound_input_hash, idempotency_key, card_json, schema_version, expires_at_ms, " +
|
|
189
|
+
"gate_bound_call_id, gate_bound_input_hash, idempotency_key, card_json, rule_command, rule_scope_root, schema_version, expires_at_ms, " +
|
|
159
190
|
"created_at_ms, updated_at_ms";
|
|
160
191
|
const BATCH_COLS = "batch_id, task_id, state, bound_ask_id, rev, created_at_ms, updated_at_ms";
|
|
161
192
|
function parseJsonColumn(v) {
|
|
@@ -195,6 +226,8 @@ function mapAskRow(r) {
|
|
|
195
226
|
gateBoundInputHash: strOrNull(r.gate_bound_input_hash),
|
|
196
227
|
idempotencyKey: strOrNull(r.idempotency_key),
|
|
197
228
|
cardJson: parseJsonColumn(r.card_json),
|
|
229
|
+
ruleCommand: strOrNull(r.rule_command),
|
|
230
|
+
ruleScopeRoot: strOrNull(r.rule_scope_root),
|
|
198
231
|
schemaVersion: Number(r.schema_version),
|
|
199
232
|
expiresAtMs: Number(r.expires_at_ms),
|
|
200
233
|
createdAtMs: Number(r.created_at_ms),
|
|
@@ -266,9 +299,9 @@ export class SqlApprovalAskStore {
|
|
|
266
299
|
try {
|
|
267
300
|
await conn.begin();
|
|
268
301
|
await conn.query(this.q(`INSERT IGNORE INTO ${APPROVAL_BATCH_TABLE} (batch_id, task_id, state, rev, created_at_ms, updated_at_ms) VALUES (?, ?, 'OPEN', 0, ?, ?)`, `INSERT INTO ${APPROVAL_BATCH_TABLE} (batch_id, task_id, state, rev, created_at_ms, updated_at_ms) VALUES ($1, $2, 'OPEN', 0, $3, $4) ON CONFLICT (batch_id) DO NOTHING`), [row.batchId, row.taskId, now, now]);
|
|
269
|
-
const askInsert = await conn.query(this.q(`INSERT IGNORE INTO ${APPROVAL_ASK_TABLE} (ask_id, task_id, source_task_id, session_id, owner, batch_id, tool_call_id, leg_key, parent_tool_call_id, bound_input_hash, state, provisional, rev, decision, decision_actor, decision_note, decided_at_ms, denied_reason, gate_token, gate_bound_call_id, gate_bound_input_hash, idempotency_key, card_json, schema_version, expires_at_ms, created_at_ms, updated_at_ms) ` +
|
|
270
|
-
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'STREAM_PENDING', 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, ?, ?, ?)", `INSERT INTO ${APPROVAL_ASK_TABLE} (ask_id, task_id, source_task_id, session_id, owner, batch_id, tool_call_id, leg_key, parent_tool_call_id, bound_input_hash, state, provisional, rev, decision, decision_actor, decision_note, decided_at_ms, denied_reason, gate_token, gate_bound_call_id, gate_bound_input_hash, idempotency_key, card_json, schema_version, expires_at_ms, created_at_ms, updated_at_ms) ` +
|
|
271
|
-
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'STREAM_PENDING', 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $11, $12, $13, $14, $15) ON CONFLICT (ask_id) DO NOTHING"), [
|
|
302
|
+
const askInsert = await conn.query(this.q(`INSERT IGNORE INTO ${APPROVAL_ASK_TABLE} (ask_id, task_id, source_task_id, session_id, owner, batch_id, tool_call_id, leg_key, parent_tool_call_id, bound_input_hash, state, provisional, rev, decision, decision_actor, decision_note, decided_at_ms, denied_reason, gate_token, gate_bound_call_id, gate_bound_input_hash, idempotency_key, card_json, rule_command, rule_scope_root, schema_version, expires_at_ms, created_at_ms, updated_at_ms) ` +
|
|
303
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'STREAM_PENDING', 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, ?, ?, ?, ?, ?)", `INSERT INTO ${APPROVAL_ASK_TABLE} (ask_id, task_id, source_task_id, session_id, owner, batch_id, tool_call_id, leg_key, parent_tool_call_id, bound_input_hash, state, provisional, rev, decision, decision_actor, decision_note, decided_at_ms, denied_reason, gate_token, gate_bound_call_id, gate_bound_input_hash, idempotency_key, card_json, rule_command, rule_scope_root, schema_version, expires_at_ms, created_at_ms, updated_at_ms) ` +
|
|
304
|
+
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'STREAM_PENDING', 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $11, $12, $13, $14, $15, $16, $17) ON CONFLICT (ask_id) DO NOTHING"), [
|
|
272
305
|
row.askId,
|
|
273
306
|
row.taskId,
|
|
274
307
|
row.sourceTaskId,
|
|
@@ -280,6 +313,8 @@ export class SqlApprovalAskStore {
|
|
|
280
313
|
row.parentToolCallId ?? null,
|
|
281
314
|
row.boundInputHash ?? null,
|
|
282
315
|
this.json(row.cardJson),
|
|
316
|
+
row.ruleCommand ?? null,
|
|
317
|
+
row.ruleScopeRoot ?? null,
|
|
283
318
|
row.schemaVersion,
|
|
284
319
|
row.expiresAtMs,
|
|
285
320
|
now,
|