@sema-agent/server 4.3.0 → 5.0.1
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/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/USAGE.md +16 -16
- package/dist/approval-hmac.js +1 -1
- package/dist/approval.d.ts +17 -37
- package/dist/approval.js +26 -112
- package/dist/auth-bridge.d.ts +0 -1
- package/dist/auth-bridge.js +0 -1
- package/dist/auth-keys.d.ts +1 -1
- package/dist/auth-keys.js +1 -1
- package/dist/bench/s1/run-firm.js +1 -1
- package/dist/boot/config-center.d.ts +1 -1
- package/dist/boot/config-center.js +4 -3
- package/dist/boot/reapers.d.ts +1 -2
- package/dist/boot/reapers.js +4 -5
- package/dist/boot/resolve-spec.d.ts +1 -3
- package/dist/boot/resolve-spec.js +21 -35
- package/dist/boot/stores.js +1 -1
- package/dist/brain.js +3 -1
- package/dist/capabilities/center-prompts.d.ts +2 -3
- package/dist/capabilities/center-prompts.js +2 -3
- package/dist/capabilities/sandbox-file-send.d.ts +0 -2
- package/dist/capabilities/sandbox-file-send.js +2 -5
- package/dist/capabilities/scenarios.d.ts +2 -13
- package/dist/capabilities/scenarios.js +3 -22
- package/dist/capabilities/send-user-file-tool.js +3 -3
- package/dist/config-center/apply-effective.js +51 -13
- package/dist/config-center/types.d.ts +10 -3
- package/dist/config-provider.d.ts +1 -1
- package/dist/config-provider.js +6 -11
- package/dist/config-types.d.ts +15 -29
- package/dist/config.d.ts +28 -0
- package/dist/config.js +122 -68
- package/dist/fleet/fleet-bus.d.ts +1 -1
- package/dist/fleet/fleet-bus.js +25 -33
- package/dist/fleet-client.js +1 -1
- package/dist/http/active-run-conflict.d.ts +2 -0
- package/dist/http/active-run-conflict.js +1 -0
- package/dist/http/routes/approvals-assistant.d.ts +2 -1
- package/dist/http/routes/approvals-assistant.js +10 -96
- package/dist/http/routes/capabilities.js +6 -5
- package/dist/http/routes/fleet.js +7 -2
- package/dist/http/routes/images.js +10 -4
- package/dist/http/routes/runs.js +42 -65
- package/dist/http/routes/session-sync.d.ts +1 -1
- package/dist/http/routes/session-sync.js +2 -1
- package/dist/http/routes/tasks.js +7 -7
- package/dist/http/routes/trace-usage.js +1 -1
- package/dist/http/routes/workflows.js +3 -1
- package/dist/http/server.d.ts +1 -6
- package/dist/http/server.js +15 -10
- package/dist/http/verify-rounds.d.ts +2 -2
- package/dist/http/wire-types.d.ts +1 -1
- package/dist/images/bake-validate.d.ts +0 -22
- package/dist/images/bake-validate.js +0 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -5
- package/dist/main.js +9 -10
- package/dist/memory-scope.d.ts +1 -2
- package/dist/memory-scope.js +8 -4
- package/dist/orchestration/workflow-completion-inbox.d.ts +6 -4
- package/dist/orchestration/workflow-completion-inbox.js +6 -4
- package/dist/plugins/breaker-state-sql.d.ts +2 -3
- package/dist/plugins/file-run-store.d.ts +1 -1
- package/dist/plugins/file-run-store.js +1 -1
- package/dist/plugins/image-index-sql.d.ts +0 -1
- package/dist/plugins/image-index-sql.js +0 -1
- package/dist/plugins/local-checkpoint-store.d.ts +1 -1
- package/dist/plugins/local-checkpoint-store.js +1 -1
- package/dist/plugins/memory-engine-pg.js +2 -1
- package/dist/plugins/memory-engine-tidb.js +1 -1
- package/dist/plugins/memory-engine-vector-util.d.ts +2 -3
- package/dist/plugins/memory-engine-vector-util.js +2 -3
- package/dist/plugins/memory-run-store.d.ts +2 -2
- package/dist/plugins/memory-run-store.js +1 -1
- package/dist/plugins/memory-session-policy-store.d.ts +1 -1
- package/dist/plugins/memory-session-policy-store.js +1 -1
- package/dist/plugins/memory-sync-store-pg.js +1 -1
- package/dist/plugins/pg-pool.js +8 -10
- package/dist/plugins/pg-rate-limiter.d.ts +1 -4
- package/dist/plugins/pg-rate-limiter.js +0 -1
- package/dist/plugins/roster-store-sql.d.ts +1 -3
- package/dist/plugins/roster-store-sql.js +3 -5
- package/dist/plugins/store-backend.d.ts +7 -17
- package/dist/plugins/store-backend.js +14 -30
- package/dist/plugins/tidb-pool.js +6 -30
- package/dist/plugins/workflow-journal-store-sql.d.ts +1 -1
- package/dist/plugins/workflow-journal-store-sql.js +1 -1
- package/dist/principal-jwt.js +2 -2
- package/dist/prompts-domain-validate.d.ts +4 -3
- package/dist/prompts-domain-validate.js +7 -8
- package/dist/router/route-orchestration.js +3 -3
- package/dist/run-local.js +13 -10
- package/dist/runs.js +8 -6
- package/dist/runtime-caps-resolver.d.ts +3 -2
- package/dist/runtime-caps-resolver.js +4 -4
- package/dist/runtime-governance.d.ts +4 -7
- package/dist/runtime-governance.js +12 -17
- package/dist/sealed-key.d.ts +1 -1
- package/dist/sealed-key.js +1 -1
- package/dist/security.d.ts +0 -5
- package/dist/security.js +8 -12
- package/dist/session-sync.d.ts +0 -2
- package/dist/session-sync.js +10 -17
- package/dist/spec-fields.js +6 -6
- package/dist/task-settings.d.ts +0 -27
- package/dist/task-settings.js +42 -11
- package/dist/tool-approval.d.ts +3 -3
- package/dist/tool-approval.js +10 -10
- package/dist/trace/artifacts.d.ts +11 -0
- package/dist/trace/artifacts.js +8 -19
- package/dist/trace/ledger-sink.js +7 -1
- package/dist/trace/project.d.ts +17 -0
- package/dist/trace/project.js +58 -5
- package/package.json +3 -3
- package/dist/capabilities/oa-tools.d.ts +0 -15
- package/dist/capabilities/oa-tools.js +0 -54
- package/dist/plugins/approval-store-sql.d.ts +0 -116
- package/dist/plugins/approval-store-sql.js +0 -150
- package/dist/plugins/file-workflow-journal-store.d.ts +0 -12
- package/dist/plugins/file-workflow-journal-store.js +0 -12
- package/dist/plugins/pg-approval-store.d.ts +0 -9
- package/dist/plugins/pg-approval-store.js +0 -9
- package/dist/plugins/pg-breaker-state.d.ts +0 -8
- package/dist/plugins/pg-breaker-state.js +0 -8
- package/dist/plugins/pg-checkpoint-store.d.ts +0 -10
- package/dist/plugins/pg-checkpoint-store.js +0 -10
- package/dist/plugins/pg-file-snapshot-store.d.ts +0 -8
- package/dist/plugins/pg-file-snapshot-store.js +0 -8
- package/dist/plugins/pg-image-bake.d.ts +0 -12
- package/dist/plugins/pg-image-bake.js +0 -11
- package/dist/plugins/pg-image-index.d.ts +0 -12
- package/dist/plugins/pg-image-index.js +0 -11
- package/dist/plugins/pg-outcome-ledger.d.ts +0 -12
- package/dist/plugins/pg-outcome-ledger.js +0 -11
- package/dist/plugins/pg-resume-anchor-store.d.ts +0 -7
- package/dist/plugins/pg-resume-anchor-store.js +0 -7
- package/dist/plugins/pg-run-store.d.ts +0 -9
- package/dist/plugins/pg-run-store.js +0 -9
- package/dist/plugins/pg-session-policy-store.d.ts +0 -7
- package/dist/plugins/pg-session-policy-store.js +0 -7
- package/dist/plugins/pg-session-store.d.ts +0 -12
- package/dist/plugins/pg-session-store.js +0 -12
- package/dist/plugins/pg-tool-result-store.d.ts +0 -9
- package/dist/plugins/pg-tool-result-store.js +0 -9
- package/dist/plugins/pg-workflow-journal-store.d.ts +0 -9
- package/dist/plugins/pg-workflow-journal-store.js +0 -9
- package/dist/plugins/pg-workflow-run-store.d.ts +0 -9
- package/dist/plugins/pg-workflow-run-store.js +0 -9
- package/dist/plugins/tidb-approval-store.d.ts +0 -8
- package/dist/plugins/tidb-approval-store.js +0 -8
- package/dist/plugins/tidb-breaker-state.d.ts +0 -7
- package/dist/plugins/tidb-breaker-state.js +0 -7
- package/dist/plugins/tidb-checkpoint-store.d.ts +0 -9
- package/dist/plugins/tidb-checkpoint-store.js +0 -9
- package/dist/plugins/tidb-file-snapshot-store.d.ts +0 -8
- package/dist/plugins/tidb-file-snapshot-store.js +0 -8
- package/dist/plugins/tidb-image-bake.d.ts +0 -12
- package/dist/plugins/tidb-image-bake.js +0 -11
- package/dist/plugins/tidb-image-index.d.ts +0 -12
- package/dist/plugins/tidb-image-index.js +0 -11
- package/dist/plugins/tidb-outcome-ledger.d.ts +0 -12
- package/dist/plugins/tidb-outcome-ledger.js +0 -12
- package/dist/plugins/tidb-resume-anchor-store.d.ts +0 -7
- package/dist/plugins/tidb-resume-anchor-store.js +0 -7
- package/dist/plugins/tidb-run-store.d.ts +0 -10
- package/dist/plugins/tidb-run-store.js +0 -9
- package/dist/plugins/tidb-session-policy-store.d.ts +0 -7
- package/dist/plugins/tidb-session-policy-store.js +0 -7
- package/dist/plugins/tidb-tool-result-store.d.ts +0 -8
- package/dist/plugins/tidb-tool-result-store.js +0 -10
- package/dist/plugins/tidb-workflow-journal-store.d.ts +0 -9
- package/dist/plugins/tidb-workflow-journal-store.js +0 -9
- package/dist/plugins/tidb-workflow-run-store.d.ts +0 -10
- package/dist/plugins/tidb-workflow-run-store.js +0 -10
- package/dist/plugins/workflow-journal-limits.d.ts +0 -12
- package/dist/plugins/workflow-journal-limits.js +0 -12
package/dist/trace/project.js
CHANGED
|
@@ -12,6 +12,8 @@ export async function appendModelUsageDelta(append, modelUsage, taskId) {
|
|
|
12
12
|
const delta = modelUsage?.drain(taskId);
|
|
13
13
|
if (delta) {
|
|
14
14
|
const tagged = {};
|
|
15
|
+
// [2373]A-4 记账(2026-08-02):usageBasis(与 TraceTurn.tokens.uncachedIn 同族)五端+黑盒仓零运行时读者——
|
|
16
|
+
// 3.0.0 cache 语义翻转的诚实位,契约正确但暂无消费;web/desktop 接账单面时它是现成的。
|
|
15
17
|
for (const [model, d] of Object.entries(delta))
|
|
16
18
|
tagged[model] = { ...d, usageBasis: "uncached-components-v1" };
|
|
17
19
|
await append("model_usage", { usage: tagged });
|
|
@@ -296,6 +298,22 @@ export function steeringInjectedEventData(ev) {
|
|
|
296
298
|
...identityFields(ev),
|
|
297
299
|
};
|
|
298
300
|
}
|
|
301
|
+
/** `compaction_outcome`(core 2.5.0 [2105]②:压缩非 compacted 结局——manual /compact 的 mooted/failed
|
|
302
|
+
* 两条真路)。[2373]A-2/C-2:此前它是**唯一**不走共享 builder、只在 live 腿 res.write 内联挑键的
|
|
303
|
+
* 内容帧 ⇒ 两条 durable 腿零 case、回放即消失、三方普查各自失明。收进共享白名单 builder,三腿同源。
|
|
304
|
+
* outcome/trigger=闭枚举 verbatim;reason=引擎说明文本(可能引用配置值)→ redactSecrets;identity 同款。 */
|
|
305
|
+
export function compactionOutcomeEventData(ev) {
|
|
306
|
+
// 形参照 contextUsageEventData 先例:全可选 unknown + 内部窄化,call site 免宽铸型(棘轮零新增)。
|
|
307
|
+
// 🔴 缺键守卫(同款「不合形即缺席」):无条件 String() 会把缺席/非串的键铸成字面 "undefined"/"null"
|
|
308
|
+
// 落进 durable 行——回放端读到的是一个看起来合法的枚举值,比缺席更难发现。
|
|
309
|
+
const s = (v) => (typeof v === "string" ? v : undefined);
|
|
310
|
+
return {
|
|
311
|
+
...(s(ev.outcome) !== undefined ? { outcome: s(ev.outcome) } : {}),
|
|
312
|
+
...(s(ev.trigger) !== undefined ? { trigger: s(ev.trigger) } : {}),
|
|
313
|
+
...(ev.reason !== undefined ? { reason: redactSecrets(String(ev.reason)) } : {}),
|
|
314
|
+
...identityFields(ev),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
299
317
|
/** The `workspace_changed` payload([1559]二 core 裁定:design/99 §E13 旧臂,L1 门本车首次撞见——非新增,
|
|
300
318
|
* 是本门扩 TaskEvent 臂集时第一次显式处置。语义 = bash `cd`/EnterWorktree 移动任务逻辑 cwd 后,在移动
|
|
301
319
|
* 它的工具结算后发一帧,给 shell/宿主 UI 一个路径提示行。cwd 与已展示的工具 args 同信任级[UNTRUSTED,
|
|
@@ -395,6 +413,9 @@ export function compactedEventData(ev) {
|
|
|
395
413
|
* 挂那儿会是"另一次更早的测量顶着同一个名字")。去 turn_end 找是找不到的。
|
|
396
414
|
* 三个字段都是引擎派生的有限数标量 ⇒ 走 finite 门(与 compacted 的 1.289 标量同姿势),非有限即缺席。
|
|
397
415
|
*/
|
|
416
|
+
// [2373]A-3 记账(2026-08-02):SDK 有臂、五端零读点(webC Composer 读的是本端自己的 state.context,
|
|
417
|
+
// 非 wire 三键)——半死:契约面已就位、消费端一个都没接。头注下方的三条口径纪律警告的消费者还不存在;
|
|
418
|
+
// 谁要做压缩面板,这是真正需要的量,先上黑板认领。
|
|
398
419
|
export function contextUsageEventData(ev) {
|
|
399
420
|
const n = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
|
|
400
421
|
return {
|
|
@@ -442,6 +463,29 @@ export function toContractTokens(usage) {
|
|
|
442
463
|
...(u.cacheWriteTokens != null ? { cacheWrite: u.cacheWriteTokens } : {}),
|
|
443
464
|
};
|
|
444
465
|
}
|
|
466
|
+
/** [2373]C-13:tool_start/tool_end 的**共享挑键**——`projectEvents`(turns 面)与 `mapTraceEvent`
|
|
467
|
+
* (trace SSE 面)对同一账本行的字段选择逐字同构,此前两处独立手写,structured/totalChars/label
|
|
468
|
+
* 三次扩字段各改两遍(见两处对偶注)。收一份:两面各自包装键名皮(id/name/input vs 同名),
|
|
469
|
+
* 字段集合从此单点演进。 */
|
|
470
|
+
export function toolCallFieldsOf(d) {
|
|
471
|
+
return {
|
|
472
|
+
id: String(d.toolCallId ?? ""),
|
|
473
|
+
name: String(d.toolName ?? ""),
|
|
474
|
+
...(typeof d.label === "string" ? { label: d.label } : {}),
|
|
475
|
+
input: d.args,
|
|
476
|
+
...identityFields(d),
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
export function toolResultFieldsOf(d) {
|
|
480
|
+
return {
|
|
481
|
+
callId: String(d.toolCallId ?? ""),
|
|
482
|
+
...(typeof d.label === "string" ? { label: d.label } : {}),
|
|
483
|
+
...(d.truncated ? { truncated: true } : {}),
|
|
484
|
+
...(Number.isFinite(d.totalChars) ? { totalChars: d.totalChars } : {}),
|
|
485
|
+
...(d.structured !== undefined ? { structured: d.structured } : {}),
|
|
486
|
+
...identityFields(d),
|
|
487
|
+
};
|
|
488
|
+
}
|
|
445
489
|
/** Project a per-task event slice (seq-ascending) into ordered `TraceTurn[]`. Pure + total (never throws). */
|
|
446
490
|
export function projectEvents(events, opts = {}) {
|
|
447
491
|
const turns = [];
|
|
@@ -470,14 +514,14 @@ export function projectEvents(events, opts = {}) {
|
|
|
470
514
|
break;
|
|
471
515
|
case "tool_start":
|
|
472
516
|
firstTs ??= ev.ts;
|
|
473
|
-
blocks.push({ type: "tool-call",
|
|
517
|
+
blocks.push({ type: "tool-call", ...toolCallFieldsOf(d) });
|
|
474
518
|
break;
|
|
475
519
|
case "tool_end": {
|
|
476
520
|
const callId = String(d.toolCallId ?? "");
|
|
477
521
|
// E1: output is read straight off the (already-redacted-at-append) event — no session join. Absent ⇒ undefined.
|
|
478
522
|
// `structured` (core 1.203 CC card) was redacted at APPEND (toolEndEventData) — passthrough on the read
|
|
479
523
|
// path so a cold-replay/turns consumer renders the same rich card the live wire carried (additive field).
|
|
480
|
-
blocks.push({ type: "tool-result",
|
|
524
|
+
blocks.push({ type: "tool-result", ...toolResultFieldsOf(d), output: d.output, ...(d.isError ? { isError: true } : {}) });
|
|
481
525
|
break;
|
|
482
526
|
}
|
|
483
527
|
case "prompt_assembled":
|
|
@@ -525,6 +569,8 @@ export function lastStep(latestEventType, status) {
|
|
|
525
569
|
/** A run record → the cheap list summary (contract 2.1). Token/cost/turns come from the terminal result.stats;
|
|
526
570
|
* scenario isn't denormalized on the run row (omitted — a later push-index/column refinement). */
|
|
527
571
|
export function taskSummary(run, latestEventType) {
|
|
572
|
+
// [2373]D-1(活 bug 修):core 2.0.0 起浮点 costUsd 族整删,stats 只有整数 costMicroUsd —— 旧读点
|
|
573
|
+
// (costUsd × 1e6)对现役 core 恒缺席,verbatim 透传才是唯一正确形。
|
|
528
574
|
const stats = (run.result?.stats ?? {});
|
|
529
575
|
const terminal = run.status !== "running";
|
|
530
576
|
return {
|
|
@@ -538,7 +584,7 @@ export function taskSummary(run, latestEventType) {
|
|
|
538
584
|
...(terminal ? { endedAt: run.updatedAt } : {}),
|
|
539
585
|
...(stats.turns !== undefined ? { turns: stats.turns } : {}),
|
|
540
586
|
...(stats.tokens !== undefined ? { tokens: stats.tokens } : {}),
|
|
541
|
-
...(stats.
|
|
587
|
+
...(stats.costMicroUsd !== undefined ? { costMicroUsd: stats.costMicroUsd } : {}),
|
|
542
588
|
lastStep: lastStep(latestEventType, run.status),
|
|
543
589
|
};
|
|
544
590
|
}
|
|
@@ -560,16 +606,23 @@ export function normalizeRunEventType(type) {
|
|
|
560
606
|
/** Map one durable event → a sema-registry SSE trace event (contract 2.3). null = not a client event. The
|
|
561
607
|
* durable log is block-grained, so each block ships as one "delta" the client appends (stream mode = "delta"). */
|
|
562
608
|
export function mapTraceEvent(type, seq, data) {
|
|
609
|
+
const mapped = mapTraceEventInner(type, seq, data);
|
|
610
|
+
if (mapped === null)
|
|
611
|
+
return null;
|
|
612
|
+
// [2373]C-12:data 里补 `type`(=event 名)双发(fleet 流同批;error 帧 arm 自带 type 保持原值)。
|
|
613
|
+
return { event: mapped.event, data: { type: mapped.event, ...mapped.data } };
|
|
614
|
+
}
|
|
615
|
+
function mapTraceEventInner(type, seq, data) {
|
|
563
616
|
switch (type) {
|
|
564
617
|
case "reasoning":
|
|
565
618
|
return { event: "block-thinking-delta", data: { seq, text: String(data.text ?? "") } };
|
|
566
619
|
case "text":
|
|
567
620
|
return { event: "block-content-delta", data: { seq, text: String(data.text ?? "") } };
|
|
568
621
|
case "tool_start":
|
|
569
|
-
return { event: "tool-call", data: { seq,
|
|
622
|
+
return { event: "tool-call", data: { seq, ...toolCallFieldsOf(data) } };
|
|
570
623
|
case "tool_end":
|
|
571
624
|
// E1: output/truncated are already redacted+bounded at append; pass through. E2: identity additive.
|
|
572
|
-
return { event: "tool-result", data: { seq,
|
|
625
|
+
return { event: "tool-result", data: { seq, ...toolResultFieldsOf(data), isError: Boolean(data.isError), ...(data.output !== undefined ? { output: data.output } : {}) } };
|
|
573
626
|
case "turn_end": {
|
|
574
627
|
const tokens = toContractTokens(data.usage);
|
|
575
628
|
return { event: "turn", data: { seq, ...(tokens ? { tokens } : {}) } };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sema-agent/server",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "5.0.1",
|
|
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",
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"build:binary:run-local:darwin-arm64": "bun build --compile --target=bun-darwin-arm64 src/run-local.ts --outfile dist/run-local-darwin-arm64"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"@sema-agent/core": "^
|
|
57
|
+
"@sema-agent/core": "^5.1.0",
|
|
58
58
|
"@sema-agent/registry-core": "^0.13.0",
|
|
59
59
|
"e2b": "^2.28.0",
|
|
60
60
|
"libsodium-wrappers": "^0.8.4",
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"sharp": "^0.35.3"
|
|
69
69
|
},
|
|
70
70
|
"devDependencies": {
|
|
71
|
-
"@sema-agent/sdk": "^
|
|
71
|
+
"@sema-agent/sdk": "^4.0.0",
|
|
72
72
|
"@types/libsodium-wrappers": "^0.7.14",
|
|
73
73
|
"@types/node": "22.10.2",
|
|
74
74
|
"@types/pg": "^8.20.0",
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import type { ToolSpec } from "@sema-agent/core";
|
|
2
|
-
/**
|
|
3
|
-
* OA scenario — tools are thin HTTP clients to the OA backend's existing APIs (read = /api/v1/*,
|
|
4
|
-
* write = /api/assets/*). The shared service token + the request's principal are forwarded so OA
|
|
5
|
-
* enforces THAT end-user's RBAC + audit (the service never holds per-user creds). Decoupled: the
|
|
6
|
-
* service knows no OA schema/DB — OA stays the source of truth (its /api/v1/meta is self-describing).
|
|
7
|
-
*/
|
|
8
|
-
export interface OaCtx {
|
|
9
|
-
baseUrl: string;
|
|
10
|
-
token: string;
|
|
11
|
-
principal?: string;
|
|
12
|
-
}
|
|
13
|
-
export declare function oaTools(ctx: OaCtx): ToolSpec[];
|
|
14
|
-
export declare const oaPrompt: import("@sema-agent/core").PromptProvider;
|
|
15
|
-
//# sourceMappingURL=oa-tools.d.ts.map
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import { Type } from "typebox";
|
|
2
|
-
import { stablePrompt } from "./prompt.js";
|
|
3
|
-
async function oaFetch(ctx, path, init) {
|
|
4
|
-
if (!ctx.baseUrl || !ctx.token)
|
|
5
|
-
return "OA 后端未配置(OA_API_BASEURL / OA_SERVICE_TOKEN)";
|
|
6
|
-
try {
|
|
7
|
-
const res = await fetch(ctx.baseUrl + path, {
|
|
8
|
-
method: init?.method ?? "GET",
|
|
9
|
-
headers: {
|
|
10
|
-
"content-type": "application/json",
|
|
11
|
-
authorization: `Bearer ${ctx.token}`,
|
|
12
|
-
...(ctx.principal ? { "x-agent-principal": ctx.principal } : {}),
|
|
13
|
-
},
|
|
14
|
-
body: init?.body !== undefined ? JSON.stringify(init.body) : undefined,
|
|
15
|
-
});
|
|
16
|
-
const text = await res.text();
|
|
17
|
-
if (!res.ok)
|
|
18
|
-
return `OA ${res.status}: ${text.slice(0, 600)}`;
|
|
19
|
-
return text.slice(0, 60_000);
|
|
20
|
-
}
|
|
21
|
-
catch (e) {
|
|
22
|
-
return `调用 OA 失败:${e.message}`;
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
const needWrite = (ctx) => (!ctx.principal ? "缺少身份(principal),无法代表用户写库;请让调用方带上 x-agent-principal。" : null);
|
|
26
|
-
export function oaTools(ctx) {
|
|
27
|
-
const obj = Type.Object({}, { additionalProperties: true });
|
|
28
|
-
return [
|
|
29
|
-
{ name: "oa_schema", effect: "read", description: "取 OA 数据结构(每类资产的字段/必填/条件必填 requiredWhen/联动 showWhen/枚举、生命周期、表名)。建/改前先调它,别凭记忆。", parameters: Type.Object({}), execute: () => oaFetch(ctx, "/api/v1/meta") },
|
|
30
|
-
{ name: "oa_alerts", effect: "read", description: "派生告警:GP 闲置(已注册未变现) / APP 未上架(已接广告未 LIVE)。", parameters: Type.Object({}), execute: () => oaFetch(ctx, "/api/v1/alerts") },
|
|
31
|
-
{ name: "oa_list", effect: "read", description: "列出某类资产。type∈gp/package/ad-platform/ad-unit/email/environment/proxy。可选 q 关键字。", parameters: Type.Object({ type: Type.String(), q: Type.Optional(Type.String()) }), execute: (a) => { const x = a; return oaFetch(ctx, `/api/v1/entities/${encodeURIComponent(x.type)}${x.q ? `?q=${encodeURIComponent(x.q)}` : ""}`); } },
|
|
32
|
-
{ name: "oa_get", effect: "read", description: "取某资产详情(敏感字段为掩码)。", parameters: Type.Object({ type: Type.String(), id: Type.String() }), execute: (a) => { const x = a; return oaFetch(ctx, `/api/v1/entities/${encodeURIComponent(x.type)}/${encodeURIComponent(x.id)}`); } },
|
|
33
|
-
{ name: "oa_lookup", effect: "read", description: "约定字段值反查(同手机/证件=同一实物)。field: phone|idCardNo|bizLicenseNo。", parameters: Type.Object({ field: Type.String(), value: Type.String() }), execute: (a) => { const x = a; return oaFetch(ctx, `/api/v1/lookup?field=${encodeURIComponent(x.field)}&value=${encodeURIComponent(x.value)}`); } },
|
|
34
|
-
{ name: "oa_create", effect: "write", description: "创建实体(走 OA 校验+当前用户 RBAC+审计)。type + data(字段对象,参照 oa_schema)。失败会返回缺失/非法字段。", parameters: Type.Object({ type: Type.String(), data: obj }), execute: (a) => { const e = needWrite(ctx); if (e)
|
|
35
|
-
return e; const x = a; return oaFetch(ctx, `/api/assets/${encodeURIComponent(x.type)}`, { method: "POST", body: x.data ?? {} }); } },
|
|
36
|
-
{ name: "oa_update", effect: "write", description: "改字段(敏感留空=保持原值;状态字段改不动,用 oa_transition)。", parameters: Type.Object({ type: Type.String(), id: Type.String(), data: obj }), execute: (a) => { const e = needWrite(ctx); if (e)
|
|
37
|
-
return e; const x = a; return oaFetch(ctx, `/api/assets/${encodeURIComponent(x.type)}/${encodeURIComponent(x.id)}`, { method: "PATCH", body: x.data ?? {} }); } },
|
|
38
|
-
{ name: "oa_transition", effect: "write", description: "受控状态流转(先 oa_schema 看可用迁移;风险/弃用等需 note)。", parameters: Type.Object({ type: Type.String(), id: Type.String(), to: Type.String(), note: Type.Optional(Type.String()) }), execute: (a) => { const e = needWrite(ctx); if (e)
|
|
39
|
-
return e; const x = a; return oaFetch(ctx, `/api/assets/${encodeURIComponent(x.type)}/${encodeURIComponent(x.id)}/transition`, { method: "POST", body: { to: x.to, note: x.note ?? null } }); } },
|
|
40
|
-
];
|
|
41
|
-
}
|
|
42
|
-
// OA business prompt MOVED OUT — migration complete (design/29, 2026-06-05). Persona / 工作准则 / UI
|
|
43
|
-
// markers (::FORM:: / ::GOTO:: / ::SUGGEST:: / ::ISSUE_FORM::) / 分级确认 / 报bug流程 are OA's business,
|
|
44
|
-
// and OA now injects the WHOLE thing per request via `request.systemPrompt` (it holds the service token,
|
|
45
|
-
// content is stable per OA version → cacheable prefix; page context still rides `objective`). Keeping
|
|
46
|
-
// any of it here would just DUPLICATE OA's prompt, so the base is EMPTY — single source of truth = OA.
|
|
47
|
-
// The service stays business-agnostic: it provides the oa_* tools (referenced by NAME from OA's prompt;
|
|
48
|
-
// they carry their own descriptions) and nothing else. `stablePrompt` keeps STABLE→VARIABLE order —
|
|
49
|
-
// OA's systemPrompt is appended after this (empty) base, before core's <user_memory>.
|
|
50
|
-
// (::ISSUE_FORM:: is parsed/rendered + submitted entirely by OA's frontend via OA /api/ai/issue — the
|
|
51
|
-
// service never touches it; `open_gitea_issue` remains only as the unattended/automated fallback.)
|
|
52
|
-
const OA_SYSTEM = "";
|
|
53
|
-
export const oaPrompt = stablePrompt(OA_SYSTEM);
|
|
54
|
-
//# sourceMappingURL=oa-tools.js.map
|
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Durable approval store for the human-in-the-loop write gate (F4) — SINGLE-FILE DUAL-DIALECT
|
|
3
|
-
* (design/158 A12 定型半场). ONE implementation, TWO dialects; the historical `TiDBApprovalStore` /
|
|
4
|
-
* `PgApprovalStore` class names survive as thin ctor subclasses so every consumer (store-backend.ts,
|
|
5
|
-
* src/index.ts, the approval/audit/security-coverage suites) is untouched.
|
|
6
|
-
*
|
|
7
|
-
* When a gated tool call is about to run, a `pending` row is recorded here; the instance running the
|
|
8
|
-
* task polls it for a decision. Because the row is durable and shared, an operator's approve/deny can
|
|
9
|
-
* land on ANY instance — critical under async runs + a load balancer, where the deciding request and
|
|
10
|
-
* the waiting run are usually on different instances.
|
|
11
|
-
*
|
|
12
|
-
* Unlike the run/checkpoint PG store (whose schema is owned centrally by pg-pool.ts), this file also
|
|
13
|
-
* exports a self-contained PG schema (`PG_APPROVAL_SCHEMA` + `ensureSchema`) — the `approval` table is
|
|
14
|
-
* DISJOINT from the other PG stores' tables, so a CREATE IF NOT EXISTS here shadows nothing. Central
|
|
15
|
-
* aggregation into pg-pool.ts composes it alongside the others. Kept in lock-step with the TiDB store
|
|
16
|
-
* by the shared real-DB integration suite (test/pg-approval-store-integration.test.ts).
|
|
17
|
-
*
|
|
18
|
-
* ── Dialect deltas, kept EXPLICIT ────────────────────────────────────────────────────────────────────
|
|
19
|
-
* - `?` placeholders vs `$n`
|
|
20
|
-
* - null-safe scope compare: `<=>` vs `IS NOT DISTINCT FROM` (a NULL scope row — legacy/untenanted
|
|
21
|
-
* run — is matched by a NULL scope arg; one tenant's scope NEVER matches another's — the
|
|
22
|
-
* single-DB fleet read guard, defense-in-depth)
|
|
23
|
-
* - JSON binding: TiDB `JSON.stringify` verbatim vs PG `pgProtocolJsonStringify` (codex R4-H2: the
|
|
24
|
-
* persisted approval `args` is the operator's REVIEW surface and must agree byte-for-byte with the
|
|
25
|
-
* policy-executed args — a lossy/rewriting envelope would let an operator approve one payload while
|
|
26
|
-
* a different one runs)
|
|
27
|
-
* - affectedRows vs rowCount (via SqlDriver)
|
|
28
|
-
* - schema ownership: TiDB DDL lives in tidb-pool.ts SCHEMA_STATEMENTS; PG DDL is this file's own
|
|
29
|
-
* self-contained `PG_APPROVAL_SCHEMA` (see the PG twin's original header — unlike the other PG
|
|
30
|
-
* stores, `approval` is NOT centrally owned by pg-pool.ts's DDL array, only aggregated into its
|
|
31
|
-
* `ensureSchema` composition).
|
|
32
|
-
* - `getStatus` result shape: `RowDataPacket[]` (mysql2 typed query) vs a plain-record `pg` query —
|
|
33
|
-
* normalized to `SqlRow` by the shared driver, so both arms read the same field names.
|
|
34
|
-
*/
|
|
35
|
-
import type { Pool as MySqlPool } from "mysql2/promise";
|
|
36
|
-
import type { Pool as PgPool, PoolClient } from "pg";
|
|
37
|
-
import { type SqlDriver } from "./sql-driver.js";
|
|
38
|
-
export type ApprovalStatus = "pending" | "approved" | "denied" | "expired";
|
|
39
|
-
export interface ApprovalRow {
|
|
40
|
-
id: string;
|
|
41
|
-
taskId: string | null;
|
|
42
|
-
sessionId: string | null;
|
|
43
|
-
owner: string | null;
|
|
44
|
-
/** Single-DB fleet scope guard (defense-in-depth): the run's tenant identity, owner-sourced. Reads filter on it. */
|
|
45
|
-
scope: string | null;
|
|
46
|
-
toolName: string;
|
|
47
|
-
args: unknown;
|
|
48
|
-
status: ApprovalStatus;
|
|
49
|
-
reason: string | null;
|
|
50
|
-
decidedBy: string | null;
|
|
51
|
-
createdAt: string;
|
|
52
|
-
decidedAt: string | null;
|
|
53
|
-
}
|
|
54
|
-
/** PG translation of the `approval` DDL in tidb-pool.ts SCHEMA_STATEMENTS (JSON→JSONB, DATETIME(3)→TIMESTAMPTZ(3),
|
|
55
|
-
* inline KEY→separate CREATE INDEX).
|
|
56
|
-
*
|
|
57
|
-
* SCHEMA POLICY: see the header of pg-pool.ts — the code is the single source of truth, schema changes are
|
|
58
|
-
* drop-and-recreate, and NO new `ALTER TABLE` seams are added here; fold into the CREATE instead. */
|
|
59
|
-
export declare const PG_APPROVAL_SCHEMA: string[];
|
|
60
|
-
/** Idempotent self-contained schema apply (for the integration test; central aggregation is done separately). */
|
|
61
|
-
export declare function ensureSchema(pool: PgPool | PoolClient): Promise<void>;
|
|
62
|
-
/** Dual-dialect durable approval store. See the file header for the dialect-delta ledger. */
|
|
63
|
-
export declare class SqlApprovalStore {
|
|
64
|
-
protected readonly db: SqlDriver;
|
|
65
|
-
constructor(db: SqlDriver);
|
|
66
|
-
/** Pick the dialect's SQL text. Both statements stay written out at the call site ON PURPOSE. */
|
|
67
|
-
private q;
|
|
68
|
-
/** JSON column binding: TiDB stores the string verbatim; PG goes through the LOSSLESS protocol envelope
|
|
69
|
-
* (codex R4-H2 — the approval `args` is the operator's review surface and must agree with the
|
|
70
|
-
* policy-executed args at the NUL position). */
|
|
71
|
-
private json;
|
|
72
|
-
createPending(id: string, scope: string | null, ctx: {
|
|
73
|
-
taskId?: string | null;
|
|
74
|
-
sessionId?: string | null;
|
|
75
|
-
owner?: string | null;
|
|
76
|
-
toolName: string;
|
|
77
|
-
args: unknown;
|
|
78
|
-
}): Promise<void>;
|
|
79
|
-
getStatus(id: string, scope: string | null): Promise<{
|
|
80
|
-
status: ApprovalStatus;
|
|
81
|
-
reason: string | null;
|
|
82
|
-
decidedBy: string | null;
|
|
83
|
-
} | undefined>;
|
|
84
|
-
/** Apply a terminal decision, but only to a still-pending row (CAS). Returns whether it applied. The scope
|
|
85
|
-
* guard (null-safe) is carried on the operator path too for consistency with the read paths. */
|
|
86
|
-
decide(id: string, scope: string | null, decision: "approved" | "denied" | "expired", reason: string | null, decidedBy: string | null): Promise<boolean>;
|
|
87
|
-
/** Pending approvals (operator queue), scoped to one tenant (single-DB fleet read guard, null-safe), optionally
|
|
88
|
-
* further filtered to one owner. */
|
|
89
|
-
listPending(scope: string | null, owner?: string): Promise<ApprovalRow[]>;
|
|
90
|
-
get(id: string, scope: string | null): Promise<ApprovalRow | undefined>;
|
|
91
|
-
/** Operator-only CROSS-tenant by-id read (no scope filter). The F4 operator queue serves/decides across
|
|
92
|
-
* tenants by design; the HTTP layer gates this to an operator and then re-binds decide() to the row's OWN
|
|
93
|
-
* scope. Tenants NEVER reach this — they use the scope-bound {@link get}. */
|
|
94
|
-
getById(id: string): Promise<ApprovalRow | undefined>;
|
|
95
|
-
/** Operator-only CROSS-tenant pending list (no scope filter) — the unfiltered operator queue across all
|
|
96
|
-
* tenants. Tenants use the scope-bound {@link listPending}; this is HTTP-gated to an operator.
|
|
97
|
-
* 🔴 identical SQL text on both dialects (no placeholders, nothing dialect-specific) — kept as ONE literal
|
|
98
|
-
* rather than a `q()` pair so a reader isn't misled into looking for a divergence that isn't there. */
|
|
99
|
-
listPendingAll(): Promise<ApprovalRow[]>;
|
|
100
|
-
/** Expire pending approvals older than `olderThanMs` (a never-answered operator request). Deliberately GLOBAL
|
|
101
|
-
* (NOT scope-filtered): staleness expiry is fleet-level maintenance that protects the worker regardless of
|
|
102
|
-
* tenant — a stale row in any scope must be reaped. Scope isolation applies to the per-tenant READ paths, not
|
|
103
|
-
* to this maintenance sweep. */
|
|
104
|
-
expireStale(olderThanMs: number): Promise<number>;
|
|
105
|
-
}
|
|
106
|
-
/** approval row → {@link ApprovalRow} — shared by BOTH dialects. design/158 S8 归位 / A12 收编. */
|
|
107
|
-
export declare function mapRow(r: Record<string, unknown>): ApprovalRow;
|
|
108
|
-
/** MySQL-protocol (TiDB) binding — historical class name + ctor shape preserved. */
|
|
109
|
-
export declare class TiDBApprovalStore extends SqlApprovalStore {
|
|
110
|
-
constructor(pool: MySqlPool);
|
|
111
|
-
}
|
|
112
|
-
/** PostgreSQL binding — historical class name + ctor shape preserved. */
|
|
113
|
-
export declare class PgApprovalStore extends SqlApprovalStore {
|
|
114
|
-
constructor(pool: PgPool);
|
|
115
|
-
}
|
|
116
|
-
//# sourceMappingURL=approval-store-sql.d.ts.map
|
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
import { parseJsonStrict as parseJson, toIsoOrNull as iso } from "./sql-row-helpers.js";
|
|
2
|
-
import { mysqlDriver, pgDriver, dialectProtocolJsonEncoder } from "./sql-driver.js";
|
|
3
|
-
/** PG translation of the `approval` DDL in tidb-pool.ts SCHEMA_STATEMENTS (JSON→JSONB, DATETIME(3)→TIMESTAMPTZ(3),
|
|
4
|
-
* inline KEY→separate CREATE INDEX).
|
|
5
|
-
*
|
|
6
|
-
* SCHEMA POLICY: see the header of pg-pool.ts — the code is the single source of truth, schema changes are
|
|
7
|
-
* drop-and-recreate, and NO new `ALTER TABLE` seams are added here; fold into the CREATE instead. */
|
|
8
|
-
export const PG_APPROVAL_SCHEMA = [
|
|
9
|
-
`CREATE TABLE IF NOT EXISTS approval (
|
|
10
|
-
id VARCHAR(64) NOT NULL,
|
|
11
|
-
task_id VARCHAR(64),
|
|
12
|
-
session_id VARCHAR(64),
|
|
13
|
-
owner VARCHAR(190),
|
|
14
|
-
-- Single-DB fleet scope guard (tenant isolation). NULLABLE on purpose: a NULL-scope row is an untenanted
|
|
15
|
-
-- run, and every read/decide path matches it with \`scope IS NOT DISTINCT FROM $n\` (the PG twin of TiDB
|
|
16
|
-
-- \`<=>\`) so NULL matches only NULL and one tenant's scope NEVER matches another's.
|
|
17
|
-
scope VARCHAR(190),
|
|
18
|
-
tool_name VARCHAR(190) NOT NULL,
|
|
19
|
-
args JSONB,
|
|
20
|
-
status VARCHAR(16) NOT NULL,
|
|
21
|
-
reason TEXT,
|
|
22
|
-
decided_by VARCHAR(190),
|
|
23
|
-
created_at TIMESTAMPTZ(3) NOT NULL,
|
|
24
|
-
decided_at TIMESTAMPTZ(3),
|
|
25
|
-
PRIMARY KEY (id)
|
|
26
|
-
)`,
|
|
27
|
-
`CREATE INDEX IF NOT EXISTS idx_approval_owner_status ON approval (owner, status)`,
|
|
28
|
-
`CREATE INDEX IF NOT EXISTS idx_approval_status ON approval (status)`,
|
|
29
|
-
`CREATE INDEX IF NOT EXISTS idx_approval_scope_status ON approval (scope, status)`,
|
|
30
|
-
];
|
|
31
|
-
/** Idempotent self-contained schema apply (for the integration test; central aggregation is done separately). */
|
|
32
|
-
export async function ensureSchema(pool) {
|
|
33
|
-
for (const stmt of PG_APPROVAL_SCHEMA)
|
|
34
|
-
await pool.query(stmt);
|
|
35
|
-
}
|
|
36
|
-
/** Dual-dialect durable approval store. See the file header for the dialect-delta ledger. */
|
|
37
|
-
export class SqlApprovalStore {
|
|
38
|
-
db;
|
|
39
|
-
constructor(db) {
|
|
40
|
-
this.db = db;
|
|
41
|
-
}
|
|
42
|
-
/** Pick the dialect's SQL text. Both statements stay written out at the call site ON PURPOSE. */
|
|
43
|
-
q(tidb, pg) {
|
|
44
|
-
return this.db.dialect === "tidb" ? tidb : pg;
|
|
45
|
-
}
|
|
46
|
-
/** JSON column binding: TiDB stores the string verbatim; PG goes through the LOSSLESS protocol envelope
|
|
47
|
-
* (codex R4-H2 — the approval `args` is the operator's review surface and must agree with the
|
|
48
|
-
* policy-executed args at the NUL position). */
|
|
49
|
-
json(value, label) {
|
|
50
|
-
return dialectProtocolJsonEncoder(this.db.dialect)(value, label);
|
|
51
|
-
}
|
|
52
|
-
async createPending(id, scope, ctx) {
|
|
53
|
-
await this.db.query(this.q("INSERT INTO approval (id, task_id, session_id, owner, scope, tool_name, args, status, created_at) " +
|
|
54
|
-
"VALUES (?,?,?,?,?,?,?,'pending',?)", "INSERT INTO approval (id, task_id, session_id, owner, scope, tool_name, args, status, created_at) " +
|
|
55
|
-
"VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,'pending',$8)"), [
|
|
56
|
-
id,
|
|
57
|
-
ctx.taskId ?? null,
|
|
58
|
-
ctx.sessionId ?? null,
|
|
59
|
-
ctx.owner ?? null,
|
|
60
|
-
scope,
|
|
61
|
-
ctx.toolName,
|
|
62
|
-
ctx.args == null ? null : this.json(ctx.args, "approval args"),
|
|
63
|
-
new Date(),
|
|
64
|
-
]);
|
|
65
|
-
}
|
|
66
|
-
async getStatus(id, scope) {
|
|
67
|
-
// null-safe scope match (`<=>` / `IS NOT DISTINCT FROM`): a NULL scope row (legacy / untenanted run) is
|
|
68
|
-
// matched by a NULL scope arg, and a tenant's scope NEVER matches another tenant's — the single-DB fleet
|
|
69
|
-
// read guard (defense-in-depth).
|
|
70
|
-
const { rows } = await this.db.query(this.q("SELECT status, reason, decided_by FROM approval WHERE id = ? AND scope <=> ?", "SELECT status, reason, decided_by FROM approval WHERE id = $1 AND scope IS NOT DISTINCT FROM $2"), [id, scope]);
|
|
71
|
-
const r = rows[0];
|
|
72
|
-
if (!r)
|
|
73
|
-
return undefined;
|
|
74
|
-
return { status: r.status, reason: r.reason ?? null, decidedBy: r.decided_by ?? null };
|
|
75
|
-
}
|
|
76
|
-
/** Apply a terminal decision, but only to a still-pending row (CAS). Returns whether it applied. The scope
|
|
77
|
-
* guard (null-safe) is carried on the operator path too for consistency with the read paths. */
|
|
78
|
-
async decide(id, scope, decision, reason, decidedBy) {
|
|
79
|
-
const res = await this.db.query(this.q("UPDATE approval SET status = ?, reason = ?, decided_by = ?, decided_at = ? WHERE id = ? AND scope <=> ? AND status = 'pending'", "UPDATE approval SET status = $1, reason = $2, decided_by = $3, decided_at = $4 WHERE id = $5 AND scope IS NOT DISTINCT FROM $6 AND status = 'pending'"), [decision, reason, decidedBy, new Date(), id, scope]);
|
|
80
|
-
return res.affected === 1;
|
|
81
|
-
}
|
|
82
|
-
/** Pending approvals (operator queue), scoped to one tenant (single-DB fleet read guard, null-safe), optionally
|
|
83
|
-
* further filtered to one owner. */
|
|
84
|
-
async listPending(scope, owner) {
|
|
85
|
-
const { rows } = owner
|
|
86
|
-
? await this.db.query(this.q("SELECT * FROM approval WHERE status = 'pending' AND scope <=> ? AND owner = ? ORDER BY created_at ASC", "SELECT * FROM approval WHERE status = 'pending' AND scope IS NOT DISTINCT FROM $1 AND owner = $2 ORDER BY created_at ASC"), [scope, owner])
|
|
87
|
-
: await this.db.query(this.q("SELECT * FROM approval WHERE status = 'pending' AND scope <=> ? ORDER BY created_at ASC", "SELECT * FROM approval WHERE status = 'pending' AND scope IS NOT DISTINCT FROM $1 ORDER BY created_at ASC"), [scope]);
|
|
88
|
-
return rows.map(mapRow);
|
|
89
|
-
}
|
|
90
|
-
async get(id, scope) {
|
|
91
|
-
const { rows } = await this.db.query(this.q("SELECT * FROM approval WHERE id = ? AND scope <=> ?", "SELECT * FROM approval WHERE id = $1 AND scope IS NOT DISTINCT FROM $2"), [id, scope]);
|
|
92
|
-
return rows[0] ? mapRow(rows[0]) : undefined;
|
|
93
|
-
}
|
|
94
|
-
/** Operator-only CROSS-tenant by-id read (no scope filter). The F4 operator queue serves/decides across
|
|
95
|
-
* tenants by design; the HTTP layer gates this to an operator and then re-binds decide() to the row's OWN
|
|
96
|
-
* scope. Tenants NEVER reach this — they use the scope-bound {@link get}. */
|
|
97
|
-
async getById(id) {
|
|
98
|
-
const { rows } = await this.db.query(this.q("SELECT * FROM approval WHERE id = ?", "SELECT * FROM approval WHERE id = $1"), [id]);
|
|
99
|
-
return rows[0] ? mapRow(rows[0]) : undefined;
|
|
100
|
-
}
|
|
101
|
-
/** Operator-only CROSS-tenant pending list (no scope filter) — the unfiltered operator queue across all
|
|
102
|
-
* tenants. Tenants use the scope-bound {@link listPending}; this is HTTP-gated to an operator.
|
|
103
|
-
* 🔴 identical SQL text on both dialects (no placeholders, nothing dialect-specific) — kept as ONE literal
|
|
104
|
-
* rather than a `q()` pair so a reader isn't misled into looking for a divergence that isn't there. */
|
|
105
|
-
async listPendingAll() {
|
|
106
|
-
const { rows } = await this.db.query("SELECT * FROM approval WHERE status = 'pending' ORDER BY created_at ASC");
|
|
107
|
-
return rows.map(mapRow);
|
|
108
|
-
}
|
|
109
|
-
/** Expire pending approvals older than `olderThanMs` (a never-answered operator request). Deliberately GLOBAL
|
|
110
|
-
* (NOT scope-filtered): staleness expiry is fleet-level maintenance that protects the worker regardless of
|
|
111
|
-
* tenant — a stale row in any scope must be reaped. Scope isolation applies to the per-tenant READ paths, not
|
|
112
|
-
* to this maintenance sweep. */
|
|
113
|
-
async expireStale(olderThanMs) {
|
|
114
|
-
const cutoff = new Date(Date.now() - olderThanMs);
|
|
115
|
-
const res = await this.db.query(this.q("UPDATE approval SET status = 'expired', reason = 'timed out before decision', decided_at = ? " +
|
|
116
|
-
"WHERE status = 'pending' AND created_at < ?", "UPDATE approval SET status = 'expired', reason = 'timed out before decision', decided_at = $1 " +
|
|
117
|
-
"WHERE status = 'pending' AND created_at < $2"), [new Date(), cutoff]);
|
|
118
|
-
return res.affected;
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
/** approval row → {@link ApprovalRow} — shared by BOTH dialects. design/158 S8 归位 / A12 收编. */
|
|
122
|
-
export function mapRow(r) {
|
|
123
|
-
return {
|
|
124
|
-
id: String(r.id),
|
|
125
|
-
taskId: r.task_id ?? null,
|
|
126
|
-
sessionId: r.session_id ?? null,
|
|
127
|
-
owner: r.owner ?? null,
|
|
128
|
-
scope: r.scope ?? null,
|
|
129
|
-
toolName: String(r.tool_name),
|
|
130
|
-
args: parseJson(r.args),
|
|
131
|
-
status: r.status,
|
|
132
|
-
reason: r.reason ?? null,
|
|
133
|
-
decidedBy: r.decided_by ?? null,
|
|
134
|
-
createdAt: iso(r.created_at),
|
|
135
|
-
decidedAt: iso(r.decided_at),
|
|
136
|
-
};
|
|
137
|
-
}
|
|
138
|
-
/** MySQL-protocol (TiDB) binding — historical class name + ctor shape preserved. */
|
|
139
|
-
export class TiDBApprovalStore extends SqlApprovalStore {
|
|
140
|
-
constructor(pool) {
|
|
141
|
-
super(mysqlDriver(pool));
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
/** PostgreSQL binding — historical class name + ctor shape preserved. */
|
|
145
|
-
export class PgApprovalStore extends SqlApprovalStore {
|
|
146
|
-
constructor(pool) {
|
|
147
|
-
super(pgDriver(pool));
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
//# sourceMappingURL=approval-store-sql.js.map
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SVC-2 — FILE-backed durable WorkflowJournalStore for the LOCAL (TOC) backend.
|
|
3
|
-
*
|
|
4
|
-
* Now a RE-EXPORT of core's copy (the write-here-then-core-adopts 剧本): the implementation was written here for server
|
|
5
|
-
* 1.89.0, then adopted verbatim by core (`@sema-agent/core` 1.223.0, file
|
|
6
|
-
* `src/stores/file/workflow-journal-store.ts` — crash-safe per-run JSONL, scope-guarded [CORE-9],
|
|
7
|
-
* idempotent-per-ordinal, oversize skip-journal, traversal-runId load degrade, 0o600/0o700). One source of
|
|
8
|
-
* truth in core; the SQL twins (tidb/pg) stay service-side (dialect = deployment glue). The service test
|
|
9
|
-
* suite (test/file-workflow-journal-store.test.ts) keeps pinning the contract through this re-export.
|
|
10
|
-
*/
|
|
11
|
-
export { FileWorkflowJournalStore } from "@sema-agent/core";
|
|
12
|
-
//# sourceMappingURL=file-workflow-journal-store.d.ts.map
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SVC-2 — FILE-backed durable WorkflowJournalStore for the LOCAL (TOC) backend.
|
|
3
|
-
*
|
|
4
|
-
* Now a RE-EXPORT of core's copy (the write-here-then-core-adopts 剧本): the implementation was written here for server
|
|
5
|
-
* 1.89.0, then adopted verbatim by core (`@sema-agent/core` 1.223.0, file
|
|
6
|
-
* `src/stores/file/workflow-journal-store.ts` — crash-safe per-run JSONL, scope-guarded [CORE-9],
|
|
7
|
-
* idempotent-per-ordinal, oversize skip-journal, traversal-runId load degrade, 0o600/0o700). One source of
|
|
8
|
-
* truth in core; the SQL twins (tidb/pg) stay service-side (dialect = deployment glue). The service test
|
|
9
|
-
* suite (test/file-workflow-journal-store.test.ts) keeps pinning the contract through this re-export.
|
|
10
|
-
*/
|
|
11
|
-
export { FileWorkflowJournalStore } from "@sema-agent/core";
|
|
12
|
-
//# sourceMappingURL=file-workflow-journal-store.js.map
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Thin re-export shim (design/158 A12 收编 — see src/plugins/approval-store-sql.ts for the
|
|
3
|
-
* implementation, now SINGLE-FILE DUAL-DIALECT alongside the TiDB twin). Class name, ctor arity,
|
|
4
|
-
* and every exported type/const/helper stay EXACTLY as they were so no consumer (pg-pool.ts's
|
|
5
|
-
* central schema composition, store-backend.ts, test/pg-approval-store-integration.test.ts) has
|
|
6
|
-
* to move.
|
|
7
|
-
*/
|
|
8
|
-
export { PgApprovalStore, PG_APPROVAL_SCHEMA, ensureSchema, type ApprovalRow, type ApprovalStatus, } from "./approval-store-sql.js";
|
|
9
|
-
//# sourceMappingURL=pg-approval-store.d.ts.map
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Thin re-export shim (design/158 A12 收编 — see src/plugins/approval-store-sql.ts for the
|
|
3
|
-
* implementation, now SINGLE-FILE DUAL-DIALECT alongside the TiDB twin). Class name, ctor arity,
|
|
4
|
-
* and every exported type/const/helper stay EXACTLY as they were so no consumer (pg-pool.ts's
|
|
5
|
-
* central schema composition, store-backend.ts, test/pg-approval-store-integration.test.ts) has
|
|
6
|
-
* to move.
|
|
7
|
-
*/
|
|
8
|
-
export { PgApprovalStore, PG_APPROVAL_SCHEMA, ensureSchema, } from "./approval-store-sql.js";
|
|
9
|
-
//# sourceMappingURL=pg-approval-store.js.map
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Re-export shim (design/158 A12 收编) — the real implementation moved to breaker-state-sql.ts
|
|
3
|
-
* (single-file dual-dialect: `SqlBreakerState` + the `TiDBBreakerState`/`PgBreakerState` ctor subclasses).
|
|
4
|
-
* Kept so every consumer's `from "./pg-breaker-state.js"` import (incl. pg-pool.ts's central ensureSchema
|
|
5
|
-
* composition and the real dual-DB integration suite) keeps working unchanged.
|
|
6
|
-
*/
|
|
7
|
-
export { PgBreakerState, PG_BREAKER_STATE_SCHEMA, ensureSchema } from "./breaker-state-sql.js";
|
|
8
|
-
//# sourceMappingURL=pg-breaker-state.d.ts.map
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Re-export shim (design/158 A12 收编) — the real implementation moved to breaker-state-sql.ts
|
|
3
|
-
* (single-file dual-dialect: `SqlBreakerState` + the `TiDBBreakerState`/`PgBreakerState` ctor subclasses).
|
|
4
|
-
* Kept so every consumer's `from "./pg-breaker-state.js"` import (incl. pg-pool.ts's central ensureSchema
|
|
5
|
-
* composition and the real dual-DB integration suite) keeps working unchanged.
|
|
6
|
-
*/
|
|
7
|
-
export { PgBreakerState, PG_BREAKER_STATE_SCHEMA, ensureSchema } from "./breaker-state-sql.js";
|
|
8
|
-
//# sourceMappingURL=pg-breaker-state.js.map
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* PostgreSQL `CheckpointStore` — the implementation now lives in the single-file dual-dialect
|
|
3
|
-
* `checkpoint-store-sql.ts` (design/158 A12 定型半场), alongside its TiDB twin so the dialect deltas
|
|
4
|
-
* (placeholders, ON CONFLICT, `IS NOT DISTINCT FROM` + its placeholder-arity consequence, the lossless
|
|
5
|
-
* JSON envelope) read side by side instead of drifting across two files.
|
|
6
|
-
*
|
|
7
|
-
* This file is the historical import path: class name and ctor shape unchanged.
|
|
8
|
-
*/
|
|
9
|
-
export { PgCheckpointStore } from "./checkpoint-store-sql.js";
|
|
10
|
-
//# sourceMappingURL=pg-checkpoint-store.d.ts.map
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* PostgreSQL `CheckpointStore` — the implementation now lives in the single-file dual-dialect
|
|
3
|
-
* `checkpoint-store-sql.ts` (design/158 A12 定型半场), alongside its TiDB twin so the dialect deltas
|
|
4
|
-
* (placeholders, ON CONFLICT, `IS NOT DISTINCT FROM` + its placeholder-arity consequence, the lossless
|
|
5
|
-
* JSON envelope) read side by side instead of drifting across two files.
|
|
6
|
-
*
|
|
7
|
-
* This file is the historical import path: class name and ctor shape unchanged.
|
|
8
|
-
*/
|
|
9
|
-
export { PgCheckpointStore } from "./checkpoint-store-sql.js";
|
|
10
|
-
//# sourceMappingURL=pg-checkpoint-store.js.map
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Thin re-export shim (design/158 A12 定型半场) — the real implementation collapsed into
|
|
3
|
-
* `file-snapshot-store-sql.ts` (single file, dual dialect). Kept so every existing import path
|
|
4
|
-
* (store-backend.ts, the migration script, the contract/integration/minio-equivalence suites) is
|
|
5
|
-
* untouched: same class name, same ctor arity, same exported surface.
|
|
6
|
-
*/
|
|
7
|
-
export { PgFileSnapshotStore } from "./file-snapshot-store-sql.js";
|
|
8
|
-
//# sourceMappingURL=pg-file-snapshot-store.d.ts.map
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Thin re-export shim (design/158 A12 定型半场) — the real implementation collapsed into
|
|
3
|
-
* `file-snapshot-store-sql.ts` (single file, dual dialect). Kept so every existing import path
|
|
4
|
-
* (store-backend.ts, the migration script, the contract/integration/minio-equivalence suites) is
|
|
5
|
-
* untouched: same class name, same ctor arity, same exported surface.
|
|
6
|
-
*/
|
|
7
|
-
export { PgFileSnapshotStore } from "./file-snapshot-store-sql.js";
|
|
8
|
-
//# sourceMappingURL=pg-file-snapshot-store.js.map
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* PostgreSQL BAKE store — the implementation now lives in the single-file dual-dialect
|
|
3
|
-
* `image-bake-store-sql.ts` (design/158 A12 定型半场), alongside its TiDB twin so the dialect deltas
|
|
4
|
-
* (placeholders, ON CONFLICT, jsonb casts, the admission-statement divergence, the PG-only
|
|
5
|
-
* protocol-byte defenses) read side by side instead of drifting across two files.
|
|
6
|
-
*
|
|
7
|
-
* This file is the historical import path: class name, ctor shape, `PG_IMAGE_BAKE_SCHEMA` and
|
|
8
|
-
* `ensureSchema` are unchanged, so pg-pool.ts / store-backend.ts / the integration suite are untouched.
|
|
9
|
-
*/
|
|
10
|
-
export { PgImageBake, PG_IMAGE_BAKE_SCHEMA, ensurePgImageBakeSchema as ensureSchema } from "./image-bake-store-sql.js";
|
|
11
|
-
export type { BakeStatus, BakeState, BakeErrorCode, BakeRecord, BakeEvent, CreateBakeInput, BakeTerminal, } from "./store-contracts.js";
|
|
12
|
-
//# sourceMappingURL=pg-image-bake.d.ts.map
|