@sema-agent/server 7.3.0 → 7.5.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 +63 -0
- package/dist/approval-card.d.ts +15 -3
- package/dist/approval-card.js +41 -7
- package/dist/approval-reconciler.d.ts +120 -16
- package/dist/approval-reconciler.js +146 -19
- package/dist/boot/coordinators.js +13 -3
- package/dist/boot/deferred-sandbox-path-env.d.ts +99 -0
- package/dist/boot/deferred-sandbox-path-env.js +279 -0
- package/dist/boot/execution-env.js +11 -1
- package/dist/boot/org-memory.d.ts +6 -0
- package/dist/boot/org-memory.js +1 -1
- package/dist/boot/reapers.d.ts +2 -0
- package/dist/boot/reapers.js +11 -4
- package/dist/boot/resolve-spec.d.ts +3 -2
- package/dist/boot/resolve-spec.js +175 -63
- package/dist/boot/runner-deps.d.ts +23 -1
- package/dist/boot/runner-deps.js +8 -11
- package/dist/boot/workflow-orchestration.d.ts +8 -3
- package/dist/boot/workflow-orchestration.js +23 -1
- package/dist/capabilities/center-prompts.js +4 -1
- package/dist/config-center/apply-effective.js +33 -10
- package/dist/config-types.d.ts +32 -9
- package/dist/config.d.ts +6 -1
- package/dist/config.js +65 -12
- package/dist/elicitation.js +5 -1
- package/dist/env-facts.d.ts +3 -1
- package/dist/env-facts.js +3 -1
- package/dist/fleet/fleet-bus.d.ts +6 -1
- package/dist/fleet/fleet-bus.js +25 -3
- package/dist/governance-ask-marks.d.ts +31 -0
- package/dist/governance-ask-marks.js +122 -0
- package/dist/hooks/hook-runner.d.ts +28 -0
- package/dist/hooks/hook-runner.js +180 -24
- package/dist/http/routes/diagnostics.d.ts +84 -0
- package/dist/http/routes/diagnostics.js +145 -0
- package/dist/http/routes/memory-policy.d.ts +2 -1
- package/dist/http/routes/memory-policy.js +77 -13
- package/dist/http/routes/runs.js +1 -1
- package/dist/http/routes/tasks.js +87 -29
- package/dist/http/server.d.ts +10 -0
- package/dist/http/server.js +29 -12
- package/dist/http/wire-types.d.ts +7 -2
- package/dist/main.js +51 -8
- package/dist/observability/fail-open.d.ts +109 -0
- package/dist/observability/fail-open.js +227 -0
- package/dist/observability/prompt-manifest.d.ts +17 -0
- package/dist/observability/prompt-manifest.js +8 -0
- package/dist/orchestration/workflow-notify-journal.d.ts +57 -1
- package/dist/orchestration/workflow-notify-journal.js +137 -32
- package/dist/parked-decide.js +9 -4
- package/dist/plugins/approval-ask-store-memory.d.ts +2 -2
- package/dist/plugins/approval-ask-store-memory.js +3 -2
- package/dist/plugins/approval-ask-store-sql.d.ts +27 -5
- package/dist/plugins/approval-ask-store-sql.js +9 -2
- package/dist/plugins/background-shell-support.d.ts +1 -1
- package/dist/plugins/background-shell-support.js +2 -2
- package/dist/plugins/checkpoint-store-sql.d.ts +62 -6
- package/dist/plugins/checkpoint-store-sql.js +71 -11
- package/dist/plugins/local-checkpoint-store.d.ts +20 -1
- package/dist/plugins/local-checkpoint-store.js +19 -0
- package/dist/plugins/mailbox-store-sql.d.ts +4 -10
- package/dist/plugins/mailbox-store-sql.js +57 -4
- package/dist/question.d.ts +18 -14
- package/dist/question.js +83 -34
- package/dist/runs.d.ts +8 -0
- package/dist/runs.js +15 -2
- package/dist/runtime-governance.d.ts +18 -0
- package/dist/runtime-governance.js +90 -3
- package/dist/task-settings.d.ts +16 -21
- package/dist/task-settings.js +22 -19
- package/dist/tool-approval.d.ts +33 -6
- package/dist/tool-approval.js +95 -30
- package/dist/trace/core-keyset-guard.d.ts +17 -3
- package/dist/trace/project.d.ts +36 -1
- package/dist/trace/project.js +55 -2
- package/package.json +3 -3
- package/dist/boot/lexical-path-env.d.ts +0 -14
- package/dist/boot/lexical-path-env.js +0 -116
|
@@ -99,8 +99,15 @@ function pendingActionToolCallId(blob) {
|
|
|
99
99
|
}
|
|
100
100
|
if (typeof parsed !== "object" || parsed === null)
|
|
101
101
|
return { readable: false };
|
|
102
|
+
// 🔴 `sourceTaskId` 是 checkpoint 的**顶层**字段(不在 pendingAction 里),没有对应的列 ⇒ 只能从
|
|
103
|
+
// blob 读。它是和解三元组的第一维(#168 件1);形不合(有这个键但不是字符串)= 结构漂移,按本函数
|
|
104
|
+
// 一贯的收窄纪律判 `readable: false`,不静默折成缺席。
|
|
105
|
+
const rawSource = "sourceTaskId" in parsed ? parsed.sourceTaskId : null;
|
|
106
|
+
if (rawSource !== null && rawSource !== undefined && typeof rawSource !== "string")
|
|
107
|
+
return { readable: false };
|
|
108
|
+
const sourceTaskId = typeof rawSource === "string" ? rawSource : null;
|
|
102
109
|
if (!("pendingAction" in parsed))
|
|
103
|
-
return { readable: true, toolCallId: null, boundInputHash: null, kind: null }; // 无 pendingAction 的 park:确定不匹配
|
|
110
|
+
return { readable: true, toolCallId: null, boundInputHash: null, kind: null, sourceTaskId }; // 无 pendingAction 的 park:确定不匹配
|
|
104
111
|
const pa = parsed.pendingAction;
|
|
105
112
|
if (typeof pa !== "object" || pa === null)
|
|
106
113
|
return { readable: false };
|
|
@@ -108,7 +115,7 @@ function pendingActionToolCallId(blob) {
|
|
|
108
115
|
if (kind !== null && typeof kind !== "string")
|
|
109
116
|
return { readable: false };
|
|
110
117
|
if (!("toolCallId" in pa))
|
|
111
|
-
return { readable: true, toolCallId: null, boundInputHash: null, kind }; // plan_review / task_done / resource_limit 腿
|
|
118
|
+
return { readable: true, toolCallId: null, boundInputHash: null, kind, sourceTaskId }; // plan_review / task_done / resource_limit 腿
|
|
112
119
|
const id = pa.toolCallId;
|
|
113
120
|
if (typeof id !== "string")
|
|
114
121
|
return { readable: false };
|
|
@@ -122,7 +129,7 @@ function pendingActionToolCallId(blob) {
|
|
|
122
129
|
const bih = "boundInputHash" in pa ? pa.boundInputHash : null;
|
|
123
130
|
if (bih !== null && typeof bih !== "string")
|
|
124
131
|
return { readable: false };
|
|
125
|
-
return { readable: true, toolCallId: id, boundInputHash: bih, kind };
|
|
132
|
+
return { readable: true, toolCallId: id, boundInputHash: bih, kind, sourceTaskId };
|
|
126
133
|
}
|
|
127
134
|
const DUP_ENTRY = 1062; // MySQL/TiDB ER_DUP_ENTRY
|
|
128
135
|
const PG_UNIQUE_VIOLATION = "23505";
|
|
@@ -228,6 +235,39 @@ const STEER_CAS_ATTEMPTS = 8;
|
|
|
228
235
|
export class SqlCheckpointStore {
|
|
229
236
|
db;
|
|
230
237
|
logger;
|
|
238
|
+
/**
|
|
239
|
+
* `CheckpointStore.durability` 声明(#167 欠账,#168 件5)—— 行落在 MySQL-protocol / PostgreSQL 的
|
|
240
|
+
* `checkpoint` 表里,进程重启、副本轮换、整机重建都不丢 ⇒ `"durable"`,如实。
|
|
241
|
+
*
|
|
242
|
+
* 🔴 为什么这一格空着是有代价的:core 的 `resolveDeclaredDurability` 把**缺席**折成 `"process-local"`
|
|
243
|
+
* (它不能替一个没表态的店猜),于是静态装配面对每一个真持久部署都读出 `process_local`,
|
|
244
|
+
* `GET /v1/diagnostics/wiring` 的 park 车道读数与启动自检的那条警告都因此不可信 —— 而 park 正是流内
|
|
245
|
+
* 审批协议的降级目的地,「重启后还赎不赎得回」是运维必须能一眼看见的事。声明是店自己的责任,不是
|
|
246
|
+
* 消费侧靠 backend.kind 猜出来的。
|
|
247
|
+
*/
|
|
248
|
+
durability = "durable";
|
|
249
|
+
/**
|
|
250
|
+
* `CheckpointStore.fidelity` 声明(core 5.17.0 [3052] 提货批 #172)——**如实按介质判**:本店把整个
|
|
251
|
+
* checkpoint 经 {@link SqlCheckpointStore.json} 编码进一个 JSON 列(TiDB 逐字文本 / PG lossless
|
|
252
|
+
* `::jsonb` 协议信封),读侧 `parseJson` 还原 ⇒ 能扛过 round-trip 的只有 JSON 值域,`"json"`。
|
|
253
|
+
*
|
|
254
|
+
* 🔴 为什么必须显式写、哪怕缺席也折向 json:core 的 `resolveDeclaredFidelity` 对缺席是 fail-closed
|
|
255
|
+
* (读 json),所以沉默不会立刻错——但沉默**表达不出**「我核对过我的介质就是这个宽度」。park 铸行
|
|
256
|
+
* 的 args / preview / 风险描述 / `boundInputHash` 全部从这一格算出的投影铸;哪天这四行编码里任何
|
|
257
|
+
* 一处改了介质(换存储格式、换列类型),声明在场才有东西可以红,沉默那格只会安静地按错宽度铸出
|
|
258
|
+
* 一份「审批人看到的 ≠ 盘上躺着的 ≠ resume 执行的」。同 `durability` 的 #168 件5 教训:表态是店
|
|
259
|
+
* 自己的责任,不是消费侧靠 backend.kind 猜。
|
|
260
|
+
*
|
|
261
|
+
* ⚠️ **已知残余(不是遮掩,是这两个词表达不了的那一格)**:PG 臂比 `"json"` 字面**略窄** ——
|
|
262
|
+
* {@link pgProtocolJsonStringify} 对含 NUL / lone surrogate 的串 fail-loud 拒绝(R4-H1 有意裁定:
|
|
263
|
+
* 复核面必须与真执行的 args 在 NUL 那一位上一致,「悄悄清洗再存」是不可接受的那一支),而 core 的
|
|
264
|
+
* json 宽度收下这些码位。`StoreFidelity` 的闭集只有 `"structured-clone" | "json"`,没有第三个词能说
|
|
265
|
+
* 「json 减去本介质存不下的码位」——声明 `"structured-clone"` 是大得多的谎,所以 `"json"` 仍是两者
|
|
266
|
+
* 里唯一诚实的选择。后果有界且 fail-closed:core 5.17.0 起 park 铸行失败会把 cause 带到 gate、追加
|
|
267
|
+
* 到 fallback 的 deny 上,这条 args 退回**同步门**由人判(不静默漏批、不挂死)。边界钉在
|
|
268
|
+
* `wiring-governance-operator.test.ts` 的 #172 组;已上报上游求一个能表达该宽度的词。
|
|
269
|
+
*/
|
|
270
|
+
fidelity = "json";
|
|
231
271
|
constructor(db, logger) {
|
|
232
272
|
this.db = db;
|
|
233
273
|
this.logger = logger;
|
|
@@ -236,8 +276,16 @@ export class SqlCheckpointStore {
|
|
|
236
276
|
q(tidb, pg) {
|
|
237
277
|
return this.db.dialect === "tidb" ? tidb : pg;
|
|
238
278
|
}
|
|
239
|
-
/** JSON column binding
|
|
240
|
-
*
|
|
279
|
+
/** JSON column binding. TiDB: plain `JSON.stringify`, stored verbatim. PG: `pgProtocolJsonStringify` —
|
|
280
|
+
* ordinary `JSON.stringify` that **refuses** (throws `PgUnstorableError`) when the value carries a code
|
|
281
|
+
* point PG cannot hold (NUL / lone surrogate); the `::jsonb` at the call site is just the bind cast, not
|
|
282
|
+
* an escaping layer.
|
|
283
|
+
*
|
|
284
|
+
* "LOSSLESS" in R4-H1 means exactly **"never silently lossy"**, not "encodes everything": the contrast is
|
|
285
|
+
* with `pgSanitizeText`, the lossy U+FFFD-scarring path used for CONTENT faces. An approval row is not a
|
|
286
|
+
* content face — the operator's review surface has to agree with the executed args AT the NUL position, so
|
|
287
|
+
* scrubbing the byte and storing the scrubbed row is the unacceptable arm; refusing loudly is the chosen one.
|
|
288
|
+
* That refusal is why {@link SqlCheckpointStore.fidelity} carries a documented residual (see it). */
|
|
241
289
|
json(value, label) {
|
|
242
290
|
return dialectProtocolJsonEncoder(this.db.dialect)(value, label);
|
|
243
291
|
}
|
|
@@ -300,8 +348,12 @@ export class SqlCheckpointStore {
|
|
|
300
348
|
// design/80 D-1: surface the reopen-by-reason + OCC fields off the AUTHORITATIVE columns (the blob is the
|
|
301
349
|
// suspend-time snapshot; resolve/reopen mutate only the columns). Core's resume reads these to validate an
|
|
302
350
|
// env_failed re-resume against the persisted winner, and to require the `rev` it observed is still live (OCC).
|
|
303
|
-
// resolvedOutcome is DERIVED from the stored full outcome
|
|
304
|
-
//
|
|
351
|
+
// resolvedOutcome is DERIVED from the stored full outcome by core's `winnerFromOutcome`, so it is preserved
|
|
352
|
+
// across a reopen for free (reopen leaves `outcome` untouched). Do NOT read a key list into this line: the
|
|
353
|
+
// derived shape is core's and it GROWS (`answer` since 5.7.0, `reason` since 5.16.0 — the operator's deny
|
|
354
|
+
// note IS persisted; an older copy of this comment enumerated only {boundCallId,decision,updatedInput?} and
|
|
355
|
+
// read as if it weren't). We store the whole outcome blob and round-trip it, so additive keys ride for free
|
|
356
|
+
// — `ResolvedOutcome` in core's `checkpoint-store.d.ts` is the single owner of that list.
|
|
305
357
|
const outcomeRaw = parseJson(r.outcome);
|
|
306
358
|
if (outcomeRaw)
|
|
307
359
|
cp.resolvedOutcome = winnerFromOutcome(outcomeRaw);
|
|
@@ -595,9 +647,14 @@ export class SqlCheckpointStore {
|
|
|
595
647
|
* 扫描(§8 C-6)。什么算读不出:blob 的 `version` 超出本 build 支持(`get()` 那条前向兼容门在这里
|
|
596
648
|
* 不能 throw,否则一条超前行会让整个 session 的对账永久卡死)、或 blob JSON 坏。
|
|
597
649
|
*
|
|
598
|
-
* 匹配是两段的:`tool_call_id` **列**是 `put()` 从 `pendingAction.toolCallId`
|
|
599
|
-
*
|
|
600
|
-
*
|
|
650
|
+
* 匹配是两段的:`tool_call_id` **列**是 `put()` 从 `pendingAction.toolCallId` 盖下来的权威投影,SQL 谓词
|
|
651
|
+
* 先按它(或 NULL)收窄;列为 NULL 的行(无工具动作的 park,或列存在之前的旧行)靠解 blob 补判——解得出
|
|
652
|
+
* 且相等才算候选,解不出就标 `unparseable`。
|
|
653
|
+
* 🔴 **没有「列命中即零解析」的快路径**(原注写过,已作废,别照它优化):函数体对**每一行**无条件解
|
|
654
|
+
* blob,原因有二 ——(a) 前向兼容门与 blob 可读性门必须门在**所有**命中路径之前(codex F3 + 确认轮:
|
|
655
|
+
* 列长得对不代表 blob 读得出,放行一条读不出的行去 `bindBatch` 会把 ask 钉成 PARKED + 一张本进程读不出
|
|
656
|
+
* 的 resume 坐标,而 PARKED 不可回滚);(b) `#168` 之后 blob 顶层的 `sourceTaskId` 是和解三元组的第一
|
|
657
|
+
* 维,列命中行结构上也必须解 blob 才拿得到它。
|
|
601
658
|
*/
|
|
602
659
|
async findCheckpointCandidatesForAsk(scope, sessionId, toolCallId, sinceMs) {
|
|
603
660
|
const { rows } = await this.db.query(this.q("SELECT token, status, created_at, tool_call_id, bound_input_hash, version, checkpoint FROM checkpoint " +
|
|
@@ -605,11 +662,14 @@ export class SqlCheckpointStore {
|
|
|
605
662
|
"WHERE scope=$1 AND session_id=$2 AND created_at>=$3 AND (tool_call_id=$4 OR tool_call_id IS NULL) ORDER BY created_at ASC"), [scope, sessionId, sinceMs, toolCallId]);
|
|
606
663
|
const out = [];
|
|
607
664
|
for (const r of rows) {
|
|
665
|
+
// `sourceTaskId: null` 是**所有 unparseable 臂的共同底**(读不出的行不许带出一个可用于身份比对的
|
|
666
|
+
// 值);健康臂在下面用 blob 解出来的值覆盖它。
|
|
608
667
|
const base = {
|
|
609
668
|
token: String(r.token),
|
|
610
669
|
status: String(r.status),
|
|
611
670
|
createdAtMs: Number(r.created_at),
|
|
612
671
|
boundInputHash: r.bound_input_hash == null ? null : String(r.bound_input_hash),
|
|
672
|
+
sourceTaskId: null,
|
|
613
673
|
};
|
|
614
674
|
// 🔴 前向兼容门必须在**任何**命中路径之前(codex 复审 F3,2026-08-06 真缺陷):版本超前的行是
|
|
615
675
|
// `get()` 明确拒读的行,而 `tool_call_id` 列命中与否跟能不能读懂 blob 毫无关系。若让列的快路径
|
|
@@ -652,7 +712,7 @@ export class SqlCheckpointStore {
|
|
|
652
712
|
// 列在场时以列为准(权威投影);列为 NULL 的旧行回落用 blob 解出来的值。
|
|
653
713
|
const effective = col ?? derived.toolCallId;
|
|
654
714
|
if (effective === toolCallId)
|
|
655
|
-
out.push({ ...base, boundInputHash: effectiveHash, boundCallId: effective });
|
|
715
|
+
out.push({ ...base, boundInputHash: effectiveHash, sourceTaskId: derived.sourceTaskId, boundCallId: effective });
|
|
656
716
|
// 解得出、但不是这只 ask 的 callId(或这条 park 本来就没有工具动作)⇒ **确定**不是候选:
|
|
657
717
|
// 既不返回也不标坏行(标坏行会让收敛器把一条明确的「不匹配」当成「不确定」)。
|
|
658
718
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type Checkpoint, type CheckpointSummary, type CheckpointToken, type PendingSteerInput, type ReopenReason, type ResolveExpectation, type ResumeOutcome } from "@sema-agent/core";
|
|
1
|
+
import { type Checkpoint, type CheckpointSummary, type CheckpointToken, type PendingSteerInput, type ReopenReason, type ResolveExpectation, type ResumeOutcome, type StoreDurability, type StoreFidelity } from "@sema-agent/core";
|
|
2
2
|
import { type PendingCheckpoint } from "./checkpoint-store-sql.js";
|
|
3
3
|
export interface LocalCheckpointStoreOptions {
|
|
4
4
|
/** taskId join for the pending card (the local FileRunStore's `getActiveTaskId`). Absent ⇒ `taskId: null`. */
|
|
@@ -8,6 +8,25 @@ export interface LocalCheckpointStoreOptions {
|
|
|
8
8
|
ownerOf?: (sessionId: string) => Promise<string | null | undefined>;
|
|
9
9
|
}
|
|
10
10
|
export declare class LocalCheckpointStore {
|
|
11
|
+
/**
|
|
12
|
+
* `CheckpointStore.durability` 声明(#167 欠账,#168 件5)——**如实按内核判**:本类的内核是 core 的
|
|
13
|
+
* `FileCheckpointStore`(crash-safe ledger + snapshot,自身声明 `"durable"`),本地 scope 注册表也落
|
|
14
|
+
* 在同一个盘上目录里 ⇒ 进程重启后 park 全部还在、还赎得回,`"durable"` 是诚实读数而不是抬举。
|
|
15
|
+
*
|
|
16
|
+
* 它与「session store 的 local 形声明 durable 就拒启」不矛盾:那条判据管的是**声明 vs 介质**,而这里
|
|
17
|
+
* 的介质就是盘。真正的 process-local 形(`InMemoryCheckpointStore`)由 core 自己声明 `"process-local"`。
|
|
18
|
+
*/
|
|
19
|
+
readonly durability: StoreDurability;
|
|
20
|
+
/**
|
|
21
|
+
* `CheckpointStore.fidelity` 声明(core 5.17.0 [3052] 提货批 #172)——**如实按内核判**,与 durability
|
|
22
|
+
* 同一条判据:本类的读写内核是 core 的 `FileCheckpointStore`,它自己声明 `"json"`(盘上是 JSON 行),
|
|
23
|
+
* 包装层只加 scope/session 索引与 ctx 附属文件,不改这条 round-trip 的宽度 ⇒ 抄内核的读数是诚实的。
|
|
24
|
+
*
|
|
25
|
+
* ⚠️ 包装类**不继承**被包装者的声明(本类是委派不是子类),所以这一格必须自己写。它与内核那一格
|
|
26
|
+
* 是否仍然一致由测试盯着(`wiring-governance-operator.test.ts` 的 #172 组直接读内核那一格对表)——
|
|
27
|
+
* 内核哪天改宽度,包装层的声明会被那条钉当场揪出来,而不是靠人记得同步。
|
|
28
|
+
*/
|
|
29
|
+
readonly fidelity: StoreFidelity;
|
|
11
30
|
private readonly inner;
|
|
12
31
|
private readonly scopesPath;
|
|
13
32
|
private readonly sessionTokensPath;
|
|
@@ -34,6 +34,25 @@ function ctxFileOf(sessionId) {
|
|
|
34
34
|
return `${sanitizePathComponent(sessionId).slice(0, 48)}-${createHash("sha256").update(sessionId).digest("hex").slice(0, 12)}.json`;
|
|
35
35
|
}
|
|
36
36
|
export class LocalCheckpointStore {
|
|
37
|
+
/**
|
|
38
|
+
* `CheckpointStore.durability` 声明(#167 欠账,#168 件5)——**如实按内核判**:本类的内核是 core 的
|
|
39
|
+
* `FileCheckpointStore`(crash-safe ledger + snapshot,自身声明 `"durable"`),本地 scope 注册表也落
|
|
40
|
+
* 在同一个盘上目录里 ⇒ 进程重启后 park 全部还在、还赎得回,`"durable"` 是诚实读数而不是抬举。
|
|
41
|
+
*
|
|
42
|
+
* 它与「session store 的 local 形声明 durable 就拒启」不矛盾:那条判据管的是**声明 vs 介质**,而这里
|
|
43
|
+
* 的介质就是盘。真正的 process-local 形(`InMemoryCheckpointStore`)由 core 自己声明 `"process-local"`。
|
|
44
|
+
*/
|
|
45
|
+
durability = "durable";
|
|
46
|
+
/**
|
|
47
|
+
* `CheckpointStore.fidelity` 声明(core 5.17.0 [3052] 提货批 #172)——**如实按内核判**,与 durability
|
|
48
|
+
* 同一条判据:本类的读写内核是 core 的 `FileCheckpointStore`,它自己声明 `"json"`(盘上是 JSON 行),
|
|
49
|
+
* 包装层只加 scope/session 索引与 ctx 附属文件,不改这条 round-trip 的宽度 ⇒ 抄内核的读数是诚实的。
|
|
50
|
+
*
|
|
51
|
+
* ⚠️ 包装类**不继承**被包装者的声明(本类是委派不是子类),所以这一格必须自己写。它与内核那一格
|
|
52
|
+
* 是否仍然一致由测试盯着(`wiring-governance-operator.test.ts` 的 #172 组直接读内核那一格对表)——
|
|
53
|
+
* 内核哪天改宽度,包装层的声明会被那条钉当场揪出来,而不是靠人记得同步。
|
|
54
|
+
*/
|
|
55
|
+
fidelity = "json";
|
|
37
56
|
inner;
|
|
38
57
|
scopesPath;
|
|
39
58
|
sessionTokensPath;
|
|
@@ -38,6 +38,7 @@
|
|
|
38
38
|
import type { Pool as MySqlPool } from "mysql2/promise";
|
|
39
39
|
import type { Pool as PgPool } from "pg";
|
|
40
40
|
import type { MailboxLease, MailboxStore } from "@sema-agent/core";
|
|
41
|
+
type MailboxAppendMessage = Parameters<MailboxStore["append"]>[2];
|
|
41
42
|
export declare const MAILBOX_TABLE = "mailboxes";
|
|
42
43
|
export declare const MAILBOX_MSG_TABLE = "mailbox_messages";
|
|
43
44
|
export declare function ensureTiDBMailboxSchema(pool: MySqlPool): Promise<void>;
|
|
@@ -46,11 +47,7 @@ export declare class TiDBMailboxStore implements MailboxStore {
|
|
|
46
47
|
private readonly pool;
|
|
47
48
|
constructor(pool: MySqlPool);
|
|
48
49
|
private tx;
|
|
49
|
-
append(scope: string, handle: string, msg:
|
|
50
|
-
from?: string;
|
|
51
|
-
content: string;
|
|
52
|
-
sentAt: number;
|
|
53
|
-
}): Promise<number>;
|
|
50
|
+
append(scope: string, handle: string, msg: MailboxAppendMessage): Promise<number>;
|
|
54
51
|
claimLease(scope: string, handle: string, owner: string, ttlMs: number, now?: number): Promise<MailboxLease | null>;
|
|
55
52
|
ack(scope: string, handle: string, owner: string, upToSeq: number): Promise<void>;
|
|
56
53
|
releaseLease(scope: string, handle: string, owner: string): Promise<void>;
|
|
@@ -66,11 +63,7 @@ export declare class PgMailboxStore implements MailboxStore {
|
|
|
66
63
|
private tx;
|
|
67
64
|
/** 身份键拒绝式([1439] 协议纪律):scope/handle/owner/from 清洗形变 = 路由/attribution 错位。 */
|
|
68
65
|
private assertIdentity;
|
|
69
|
-
append(scope: string, handle: string, msg:
|
|
70
|
-
from?: string;
|
|
71
|
-
content: string;
|
|
72
|
-
sentAt: number;
|
|
73
|
-
}): Promise<number>;
|
|
66
|
+
append(scope: string, handle: string, msg: MailboxAppendMessage): Promise<number>;
|
|
74
67
|
claimLease(scope: string, handle: string, owner: string, ttlMs: number, now?: number): Promise<MailboxLease | null>;
|
|
75
68
|
ack(scope: string, handle: string, owner: string, upToSeq: number): Promise<void>;
|
|
76
69
|
releaseLease(scope: string, handle: string, owner: string): Promise<void>;
|
|
@@ -80,4 +73,5 @@ export declare class PgMailboxStore implements MailboxStore {
|
|
|
80
73
|
maxAgeMs?: number;
|
|
81
74
|
}): Promise<number>;
|
|
82
75
|
}
|
|
76
|
+
export {};
|
|
83
77
|
//# sourceMappingURL=mailbox-store-sql.d.ts.map
|
|
@@ -25,12 +25,58 @@ function assertKeyBytes(what, v) {
|
|
|
25
25
|
function bufToStr(v) {
|
|
26
26
|
return Buffer.isBuffer(v) ? v.toString("utf8") : String(v);
|
|
27
27
|
}
|
|
28
|
+
/** `hopChain` 的 JSON 文本列上界(TiDB `TEXT` = 65535 字节)。core 侧链本就有界
|
|
29
|
+
* (`PEER_ADMISSION_DEFAULTS.maxChainLength` = 28,`PEER_HOP_CHAIN_WINDOW` = 32,元素是 peerAxisToken
|
|
30
|
+
* 短串)⇒ 正常形离这个数几个数量级远;守卫存在的理由是**关掉 MySQL 的静默截断类**(非严格模式下
|
|
31
|
+
* 超长 TEXT 写入只发 warning),截断后的 JSON 文本读侧 parse 失败 = 整条链静默变缺席,而缺席在
|
|
32
|
+
* mailbox 上是有语义的(见下 encodeHopChain 注)。同 assertKeyBytes 精神:写入面 fail-loud。 */
|
|
33
|
+
const HOP_CHAIN_MAX_BYTES = 60_000;
|
|
34
|
+
/**
|
|
35
|
+
* `hopChain` 存取(core 5.17.0 design/176)。**JSON 文本列**,不是清洗面也不是身份键面:
|
|
36
|
+
*
|
|
37
|
+
* - 为什么不清洗:链元素参与 core 的 `hop_loop` **等值比对**。内容面的 lossy 清洗(pgSanitizeText 的
|
|
38
|
+
* U+FFFD 标记)会让两个不同 token 塌成同一个(误报环路)或让一个 token 变形(漏判环路)——两个
|
|
39
|
+
* 方向都是把准入判决改错,与 `content` 那种「读者读到近似文本仍可用」的容忍面性质不同。
|
|
40
|
+
* - 为什么也不需要拒绝:`JSON.stringify` 是 **well-formed**(ES2019)——NUL 转义成 `\u0000`、lone
|
|
41
|
+
* surrogate 转义成 `\udXXX`,产物恒是 ASCII 可存字节。于是 PG 的 unstorable 面根本不会被触及,
|
|
42
|
+
* 两方言都拿到逐字 round-trip,不必像 `from`/`scope`/`handle` 那样走拒绝式。
|
|
43
|
+
* - **缺席 ≠ 空数组**:core 明示 mailbox 的 `hopChain` 在场性本身携带语义(「经 sema 准入门录入」vs
|
|
44
|
+
* 「外部/存量写入」,是整份契约里唯一允许从在场性推断的例外)。所以 NULL 读回 = 不铸键,`[]` 读回
|
|
45
|
+
* = 铸一个空数组键,两者绝不互相折叠。
|
|
46
|
+
*/
|
|
47
|
+
function encodeHopChain(hopChain) {
|
|
48
|
+
if (hopChain === undefined)
|
|
49
|
+
return null;
|
|
50
|
+
const text = JSON.stringify(hopChain);
|
|
51
|
+
if (Buffer.byteLength(text, "utf8") > HOP_CHAIN_MAX_BYTES) {
|
|
52
|
+
throw new Error(`MailboxStore: hopChain exceeds the ${HOP_CHAIN_MAX_BYTES}-byte column (refusing — a truncated chain would silently read back as ABSENT, which mailbox treats as "not gate-admitted")`);
|
|
53
|
+
}
|
|
54
|
+
return text;
|
|
55
|
+
}
|
|
56
|
+
/** 读侧:NULL/缺席 ⇒ undefined(不铸键);坏行(非 JSON / 非字符串数组)⇒ 同样 undefined —— 一条读不
|
|
57
|
+
* 懂的链只能诚实降级成「没有链」,绝不半解析出一条会被拿去做环路比对的残链。 */
|
|
58
|
+
function decodeHopChain(raw) {
|
|
59
|
+
if (raw === null || raw === undefined)
|
|
60
|
+
return undefined;
|
|
61
|
+
let parsed;
|
|
62
|
+
try {
|
|
63
|
+
parsed = JSON.parse(bufToStr(raw));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
if (!Array.isArray(parsed) || parsed.some((x) => typeof x !== "string"))
|
|
69
|
+
return undefined;
|
|
70
|
+
return parsed;
|
|
71
|
+
}
|
|
28
72
|
function rowToMessage(r) {
|
|
73
|
+
const hopChain = decodeHopChain(r.hop_chain);
|
|
29
74
|
return {
|
|
30
75
|
seq: Number(r.seq),
|
|
31
76
|
...(r.from_id !== null && r.from_id !== undefined ? { from: bufToStr(r.from_id) } : {}),
|
|
32
77
|
content: String(r.content),
|
|
33
78
|
sentAt: Number(r.sent_at_ms),
|
|
79
|
+
...(hopChain !== undefined ? { hopChain } : {}),
|
|
34
80
|
};
|
|
35
81
|
}
|
|
36
82
|
export async function ensureTiDBMailboxSchema(pool) {
|
|
@@ -53,6 +99,10 @@ export async function ensureTiDBMailboxSchema(pool) {
|
|
|
53
99
|
from_id VARBINARY(255) NULL,
|
|
54
100
|
content LONGTEXT NOT NULL,
|
|
55
101
|
sent_at_ms BIGINT NOT NULL,
|
|
102
|
+
-- hop_chain(core 5.17.0 design/176):peer 准入的 hop 链,JSON 文本;NULL = 缺席(**有语义**,
|
|
103
|
+
-- 见 encodeHopChain 头注:缺席 vs 空数组绝不互折)。TEXT 而非 LONGTEXT——链上界在 core(28 跳,
|
|
104
|
+
-- 短 token),写入面另有 HOP_CHAIN_MAX_BYTES fail-loud 守卫关掉静默截断类。
|
|
105
|
+
hop_chain TEXT NULL,
|
|
56
106
|
PRIMARY KEY (scope_key, handle, seq),
|
|
57
107
|
KEY idx_mbm_sent (scope_key, handle, sent_at_ms)
|
|
58
108
|
) COLLATE utf8mb4_bin`);
|
|
@@ -75,6 +125,7 @@ export async function ensurePgMailboxSchema(q) {
|
|
|
75
125
|
from_id VARCHAR(255) COLLATE "C",
|
|
76
126
|
content TEXT NOT NULL,
|
|
77
127
|
sent_at_ms BIGINT NOT NULL,
|
|
128
|
+
hop_chain TEXT, -- core 5.17.0 design/176(TiDB twin 同注:NULL = 缺席且有语义)
|
|
78
129
|
PRIMARY KEY (scope_key, handle, seq)
|
|
79
130
|
)`);
|
|
80
131
|
await q(`CREATE INDEX IF NOT EXISTS idx_mbm_sent ON ${MAILBOX_MSG_TABLE} (scope_key, handle, sent_at_ms)`);
|
|
@@ -106,6 +157,7 @@ export class TiDBMailboxStore {
|
|
|
106
157
|
assertIdentityChars("handle", handle);
|
|
107
158
|
assertKeyBytes("scope", scope);
|
|
108
159
|
assertKeyBytes("handle", handle);
|
|
160
|
+
const hopChain = encodeHopChain(msg.hopChain); // 事务外先编码:超界 fail-loud 必须在建盒/分配 seq 之前
|
|
109
161
|
// ensure-first 形:先幂等 INSERT IGNORE 建盒(next_seq=1,首条/drop 后重建同臂)再 FOR UPDATE——
|
|
110
162
|
// 「无行 FOR UPDATE + INSERT」的并发死锁/dup 撞车形整个消掉;seq 分配与 append 同事务(定谳 2)。
|
|
111
163
|
return this.tx(async (c) => {
|
|
@@ -119,7 +171,7 @@ export class TiDBMailboxStore {
|
|
|
119
171
|
}
|
|
120
172
|
const seq = Number(rows[0].next_seq);
|
|
121
173
|
await c.query(`UPDATE ${MAILBOX_TABLE} SET next_seq = ? WHERE scope_key = ? AND handle = ?`, [seq + 1, scope, handle]);
|
|
122
|
-
await c.query(`INSERT INTO ${MAILBOX_MSG_TABLE} (scope_key, handle, seq, from_id, content, sent_at_ms) VALUES (?, ?, ?, ?, ?, ?)`, [scope, handle, seq, msg.from ?? null, msg.content, msg.sentAt]);
|
|
174
|
+
await c.query(`INSERT INTO ${MAILBOX_MSG_TABLE} (scope_key, handle, seq, from_id, content, sent_at_ms, hop_chain) VALUES (?, ?, ?, ?, ?, ?, ?)`, [scope, handle, seq, msg.from ?? null, msg.content, msg.sentAt, hopChain]);
|
|
123
175
|
return seq;
|
|
124
176
|
});
|
|
125
177
|
}
|
|
@@ -139,7 +191,7 @@ export class TiDBMailboxStore {
|
|
|
139
191
|
}
|
|
140
192
|
// FOR UPDATE = 当前读:TiDB 悲观事务的普通 SELECT 按 start_ts 快照(task-list twin 同案)——
|
|
141
193
|
// 锁到 box 行后消息集必须读「现在」,否则 drop+重建窗内老消息混进新盒 lease(maxSeq 错位)。
|
|
142
|
-
const [msgs] = (await c.query(`SELECT seq, from_id, content, sent_at_ms FROM ${MAILBOX_MSG_TABLE} WHERE scope_key = ? AND handle = ? ORDER BY seq FOR UPDATE`, [scope, handle]));
|
|
194
|
+
const [msgs] = (await c.query(`SELECT seq, from_id, content, sent_at_ms, hop_chain FROM ${MAILBOX_MSG_TABLE} WHERE scope_key = ? AND handle = ? ORDER BY seq FOR UPDATE`, [scope, handle]));
|
|
143
195
|
if (msgs.length === 0)
|
|
144
196
|
return null; // 定谳 5:空盒 claim = null(box 行在也 null)
|
|
145
197
|
const maxSeq = Number(msgs[msgs.length - 1].seq);
|
|
@@ -241,6 +293,7 @@ export class PgMailboxStore {
|
|
|
241
293
|
const content = pgSanitizeText(msg.content); // 内容面 lossy(U+FFFD 标记,与 PG 转录 payload 同族)
|
|
242
294
|
assertKeyBytes("scope", scope);
|
|
243
295
|
assertKeyBytes("handle", handle);
|
|
296
|
+
const hopChain = encodeHopChain(msg.hopChain); // TiDB 同注:事务外先编码,超界 fail-loud 不留半个盒
|
|
244
297
|
// ensure-first 形(TiDB 同注):幂等建盒再 FOR UPDATE,死锁/dup 撞车形消。
|
|
245
298
|
return this.tx(async (c) => {
|
|
246
299
|
await c.query(`INSERT INTO ${MAILBOX_TABLE} (scope_key, handle, scope, next_seq) VALUES ($1, $2, $3, 1) ON CONFLICT (scope_key, handle) DO NOTHING`, [
|
|
@@ -260,7 +313,7 @@ export class PgMailboxStore {
|
|
|
260
313
|
}
|
|
261
314
|
const seq = Number(rows[0].next_seq);
|
|
262
315
|
await c.query(`UPDATE ${MAILBOX_TABLE} SET next_seq = $1 WHERE scope_key = $2 AND handle = $3`, [seq + 1, scope, handle]);
|
|
263
|
-
await c.query(`INSERT INTO ${MAILBOX_MSG_TABLE} (scope_key, handle, seq, from_id, content, sent_at_ms) VALUES ($1, $2, $3, $4, $5, $6)`, [scope, handle, seq, msg.from ?? null, content, msg.sentAt]);
|
|
316
|
+
await c.query(`INSERT INTO ${MAILBOX_MSG_TABLE} (scope_key, handle, seq, from_id, content, sent_at_ms, hop_chain) VALUES ($1, $2, $3, $4, $5, $6, $7)`, [scope, handle, seq, msg.from ?? null, content, msg.sentAt, hopChain]);
|
|
264
317
|
return seq;
|
|
265
318
|
});
|
|
266
319
|
}
|
|
@@ -273,7 +326,7 @@ export class PgMailboxStore {
|
|
|
273
326
|
const box = boxes[0];
|
|
274
327
|
if (box.lease_owner !== null && Number(box.lease_expires_at_ms) > now && String(box.lease_owner) !== owner)
|
|
275
328
|
return null;
|
|
276
|
-
const { rows: msgs } = await c.query(`SELECT seq, from_id, content, sent_at_ms FROM ${MAILBOX_MSG_TABLE} WHERE scope_key = $1 AND handle = $2 ORDER BY seq FOR UPDATE`, [scope, handle]);
|
|
329
|
+
const { rows: msgs } = await c.query(`SELECT seq, from_id, content, sent_at_ms, hop_chain FROM ${MAILBOX_MSG_TABLE} WHERE scope_key = $1 AND handle = $2 ORDER BY seq FOR UPDATE`, [scope, handle]);
|
|
277
330
|
if (msgs.length === 0)
|
|
278
331
|
return null;
|
|
279
332
|
const maxSeq = Number(msgs[msgs.length - 1].seq);
|
package/dist/question.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AskQuestionRequest, type QuestionAnswer, type AskQuestion } from "@sema-agent/core";
|
|
1
|
+
import { type AskQuestionRequest, type OnQuestionOutcome, type QuestionAnswer, type AskQuestion } from "@sema-agent/core";
|
|
2
2
|
/** A live question frame delivered to whoever tails this run's stream. `type` IS the SSE event name (mirrors the
|
|
3
3
|
* named-event convention; the payload also carries `type` so a proxy that strips event names still works). The shell
|
|
4
4
|
* renders `question` as a dialog and dismisses on `question_complete`. */
|
|
@@ -6,10 +6,10 @@ export interface QuestionFrame {
|
|
|
6
6
|
type: "question" | "question_complete";
|
|
7
7
|
questionId: string;
|
|
8
8
|
/** "question" only: the model's structured questions, secret-redacted. UNTRUSTED-for-display (shell renders; never
|
|
9
|
-
* re-feeds a model). Absent on an over-cap payload (the ask then
|
|
9
|
+
* re-feeds a model). Absent on an over-cap payload (the ask then reports unavailable — no frame is emitted at all). */
|
|
10
10
|
questions?: AskQuestion[];
|
|
11
11
|
/** "question_complete" only: whether the human answered (`answered`) or the ask was released unanswered
|
|
12
|
-
* (`unanswered` — ttl/abort →
|
|
12
|
+
* (`unanswered` — ttl/abort → core was told nobody was reachable). Cosmetic dialog-dismiss. */
|
|
13
13
|
outcome?: "answered" | "unanswered";
|
|
14
14
|
/** Server-signed emit timestamp (additive, [2805]§五→[2806]). Server-minted side-frame ⇒ no core-stream
|
|
15
15
|
* `eventId` to carry (absence is honest); this is the frame's own time coordinate. */
|
|
@@ -31,12 +31,14 @@ export interface QuestionRunContext {
|
|
|
31
31
|
* background leg (emit appends to the durable events tail, readable whenever a client attaches). */
|
|
32
32
|
deliverable?: () => boolean;
|
|
33
33
|
}
|
|
34
|
+
/** The per-run question window the deployment owns (core caps nothing). Env: `QUESTION_MAX_CONCURRENT_PER_RUN` /
|
|
35
|
+
* `QUESTION_MAX_TOTAL_PER_RUN` / `QUESTION_TTL_MS` (see `ServiceConfig.questionThrottle`). */
|
|
34
36
|
export interface QuestionThrottle {
|
|
35
|
-
/** Max concurrent in-flight questions per run leg (parallel tool calls can each ask). Breach ⇒
|
|
37
|
+
/** Max concurrent in-flight questions per run leg (parallel tool calls can each ask). Breach ⇒ unavailable. */
|
|
36
38
|
maxConcurrentPerRun: number;
|
|
37
|
-
/** Max total questions one run leg surfaces to the human. Breach ⇒
|
|
39
|
+
/** Max total questions one run leg surfaces to the human. Breach ⇒ unavailable (flood defense). */
|
|
38
40
|
maxTotalPerRun: number;
|
|
39
|
-
/** An unanswered question auto-releases
|
|
41
|
+
/** An unanswered question auto-releases as unavailable after this (ms) — the human walked away; don't hold core. */
|
|
40
42
|
ttlMs: number;
|
|
41
43
|
}
|
|
42
44
|
export declare const DEFAULT_QUESTION_THROTTLE: QuestionThrottle;
|
|
@@ -54,7 +56,7 @@ export declare function parseQuestionResponse(body: unknown): {
|
|
|
54
56
|
* Coordinates AskUserQuestion HITL for the singleton runner. Process-local + same-replica (the pending map is in memory,
|
|
55
57
|
* like ElicitationCoordinator / steerableRuns): a respond that lands on another replica finds nothing → 404. Present
|
|
56
58
|
* (passed into `RunnerDeps.onQuestion` + the respond route) ONLY when `ASK_QUESTION_ENABLED` — absent ⇒ core mounts the
|
|
57
|
-
* AskUserQuestion tool with
|
|
59
|
+
* AskUserQuestion tool with no seam at all (`seam_absent` continuation; the model just can't get a live answer).
|
|
58
60
|
*/
|
|
59
61
|
export declare class QuestionCoordinator {
|
|
60
62
|
private readonly als;
|
|
@@ -63,12 +65,13 @@ export declare class QuestionCoordinator {
|
|
|
63
65
|
private readonly throttle;
|
|
64
66
|
constructor(throttle?: QuestionThrottle);
|
|
65
67
|
/** Run `fn` with the per-run question context ambient. On exit, release any still-pending question for this run (a
|
|
66
|
-
* live-only question cannot outlive its leg →
|
|
68
|
+
* live-only question cannot outlive its leg → unavailable) and drop the run's counters (no leak). */
|
|
67
69
|
runWithContext<T>(ctx: QuestionRunContext, fn: () => Promise<T>): Promise<T>;
|
|
68
|
-
/** `RunnerDeps.onQuestion`. core calls this when the agent's AskUserQuestion tool fires; the resolved
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
|
|
70
|
+
/** `RunnerDeps.onQuestion`. core calls this when the agent's AskUserQuestion tool fires; the resolved outcome is what
|
|
71
|
+
* core acts on — a {@link QuestionAnswer} ONLY when a human really answered, otherwise `{kind:"unavailable"}` (core
|
|
72
|
+
* then parks on a durable leg / continues with the `declined_unavailable` card on a non-durable one; either way the
|
|
73
|
+
* run never hangs). Arrow property so it can be passed as `onQuestion: coordinator.question` with `this` bound. */
|
|
74
|
+
question: (req: AskQuestionRequest, signal?: AbortSignal) => Promise<OnQuestionOutcome>;
|
|
72
75
|
/** `POST /v1/questions/:id/respond` — resolve a parked question with the shell's answer. Owner-gated with a 404 (no
|
|
73
76
|
* existence oracle): a non-owner AND an unknown id (answered / expired / wrong replica) both get 404. Returns the
|
|
74
77
|
* HTTP {status, body}; the HTTP layer owns auth (gatedPrincipal + REQUIRE_PRINCIPAL) before calling. */
|
|
@@ -83,9 +86,10 @@ export declare class QuestionCoordinator {
|
|
|
83
86
|
* resolve-spec 的 durable question policy 用它在**判决时**分腿:有活流 ⇒ allow(问活人),无 ⇒
|
|
84
87
|
* ask(durable park)。ALS 让这个判断天然 per-leg,policy 组装期不必预知腿别。
|
|
85
88
|
* 🔴 判据是「投递面此刻可达」而不只是「ALS 在场」(复审 A1):detach 腿断连后 run 仍在本作用域里跑,
|
|
86
|
-
* 只判 ALS 会把一条谁也收不到的问题判成 allow
|
|
89
|
+
* 只判 ALS 会把一条谁也收不到的问题判成 allow——挂满 ttl 后以 unavailable 结算,非 durable 形 core
|
|
90
|
+
* 就此合成续跑,活人再没机会答;而 park 才是它该走的腿。
|
|
87
91
|
* 谓词缺席 ⇒ 恒可达(后台腿的 durable events tail 语义)。谓词本身抛错按不可达处理:判决面
|
|
88
|
-
* fail-closed 到 park(park
|
|
92
|
+
* fail-closed 到 park(park 可由运维补答,续跑掉的问题不可回收)。 */
|
|
89
93
|
hasLiveContext(): boolean;
|
|
90
94
|
private countersFor;
|
|
91
95
|
}
|