@sema-agent/server 4.3.0 → 5.0.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 +5 -3
- package/dist/approval-hmac.js +1 -1
- package/dist/approval.d.ts +5 -37
- package/dist/approval.js +12 -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 +3 -2
- 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 +0 -9
- package/dist/capabilities/scenarios.js +1 -20
- package/dist/capabilities/send-user-file-tool.js +3 -3
- package/dist/config-center/apply-effective.js +8 -8
- package/dist/config-center/types.d.ts +10 -3
- package/dist/config-provider.js +6 -11
- package/dist/config-types.d.ts +12 -26
- package/dist/config.js +95 -68
- 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 +4 -1
- package/dist/http/routes/images.js +10 -4
- package/dist/http/routes/runs.js +34 -49
- 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/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 +5 -9
- package/dist/memory-scope.js +2 -2
- 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/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 +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 +4 -28
- 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 +5 -4
- 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.js +7 -7
- 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 +55 -5
- package/package.json +2 -2
- 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/session-sync.js
CHANGED
|
@@ -12,15 +12,6 @@ export function fileSnapshotImportFace(fs) {
|
|
|
12
12
|
return undefined;
|
|
13
13
|
return { importManifest: candidate.bind(fs) };
|
|
14
14
|
}
|
|
15
|
-
// ── PURE KERNEL moved to ./session-sync-kernel.ts (design/158 A2) ─────────────────────────────────────────────
|
|
16
|
-
// The §7 relation classifier (classifySyncRelationship[ByIds]), the staging-id scheme (stagingIdFor /
|
|
17
|
-
// STAGING_ID_MARKER / realIdOfStaging), the StagingHandle / ImportStagingStore contracts and SyncConflictError
|
|
18
|
-
// lived here (lines ~26–187) but depend on NOTHING in this repo — while THIS module value-imports StoreBackend and
|
|
19
|
-
// type-imports security's OwnerAwareSessionStore. The three DB session adapters (local/pg/tidb) and security.ts
|
|
20
|
-
// need only those pure symbols, and security.ts importing them from HERE formed the repo's only true type cycle
|
|
21
|
-
// (security ↔ session-sync; lens2 §B/§E). They now live in the leaf module session-sync-kernel.ts (same shape as
|
|
22
|
-
// session-sync-content.ts) and are RE-EXPORTED verbatim below, so existing importers of this module keep working.
|
|
23
|
-
export { stagingIdFor, STAGING_ID_MARKER, realIdOfStaging, classifySyncRelationship, classifySyncRelationshipByIds, SyncConflictError } from "./session-sync-kernel.js";
|
|
24
15
|
/** Narrow `backend.session()` to the optional ownership/export seam (the concrete TiDB/PG/Local stores carry it;
|
|
25
16
|
* the bare in-memory dev store doesn't → the methods are optional, exactly like the fork route narrows). */
|
|
26
17
|
function ownerAware(backend) {
|
|
@@ -77,7 +68,8 @@ export async function exportSession(sessionId, srcBackend) {
|
|
|
77
68
|
// snapshots — listKeys → per-key manifest. exportManifest may be absent (no snapshot export seam) → no snapshots.
|
|
78
69
|
const fs = srcBackend.fileSnapshot();
|
|
79
70
|
const snapshots = [];
|
|
80
|
-
|
|
71
|
+
// [2373]B-5b:core 接口 listKeys 必填(恒真半支删);exportManifest? 可选——探测只留真可选的那半。
|
|
72
|
+
if (typeof fs.exportManifest === "function") {
|
|
81
73
|
const keys = await fs.listKeys(sessionId);
|
|
82
74
|
for (const key of keys) {
|
|
83
75
|
const manifest = await fs.exportManifest(sessionId, key);
|
|
@@ -93,9 +85,9 @@ export async function exportSession(sessionId, srcBackend) {
|
|
|
93
85
|
: [];
|
|
94
86
|
// anchors — every E18 resume anchor (eventId→entryId + source owner). resumeAnchor is REQUIRED on all backends.
|
|
95
87
|
const anchorStore = srcBackend.resumeAnchor();
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
88
|
+
// [2373]B-5a:ResumeAnchorStore 是三实现的闭合联合、listBySession 全必填——feature-detect 恒真,
|
|
89
|
+
// `: []` 臂不可达([2195] deleteBySession 同判据,那轮漏了这对双胞胎)。直调。
|
|
90
|
+
const anchors = await anchorStore.listBySession(sessionId);
|
|
99
91
|
// getBlob — bound to the SOURCE snapshot store so the importer pulls bytes content-addressed (deduped), lazily.
|
|
100
92
|
// A source without getBlob (no blobs to move) supplies a getter that always returns undefined → snapshots with a
|
|
101
93
|
// missing blob fail the §10 validation below before any write (never a partial restore).
|
|
@@ -131,7 +123,8 @@ export async function exportSessionManifest(sessionId, srcBackend) {
|
|
|
131
123
|
// snapshots / policy / anchors — IDENTICAL to exportSession (no entry payloads loaded anywhere here).
|
|
132
124
|
const fs = srcBackend.fileSnapshot();
|
|
133
125
|
const snapshots = [];
|
|
134
|
-
|
|
126
|
+
// [2373]B-5b:core 接口 listKeys 必填(恒真半支删);exportManifest? 可选——探测只留真可选的那半。
|
|
127
|
+
if (typeof fs.exportManifest === "function") {
|
|
135
128
|
const keys = await fs.listKeys(sessionId);
|
|
136
129
|
for (const key of keys) {
|
|
137
130
|
const manifest = await fs.exportManifest(sessionId, key);
|
|
@@ -145,9 +138,9 @@ export async function exportSessionManifest(sessionId, srcBackend) {
|
|
|
145
138
|
? await policyStore.listBySession(sessionId)
|
|
146
139
|
: [];
|
|
147
140
|
const anchorStore = srcBackend.resumeAnchor();
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
141
|
+
// [2373]B-5a:ResumeAnchorStore 是三实现的闭合联合、listBySession 全必填——feature-detect 恒真,
|
|
142
|
+
// `: []` 臂不可达([2195] deleteBySession 同判据,那轮漏了这对双胞胎)。直调。
|
|
143
|
+
const anchors = await anchorStore.listBySession(sessionId);
|
|
151
144
|
// getBlob — bound to the SOURCE snapshot store (content-addressed, lazy), exactly like exportSession.
|
|
152
145
|
const getBlobFn = fs.getBlob?.bind(fs);
|
|
153
146
|
const getBlob = getBlobFn ? (hash) => getBlobFn(hash) : async () => undefined;
|
package/dist/spec-fields.js
CHANGED
|
@@ -159,17 +159,17 @@ const skillOk = (s) => {
|
|
|
159
159
|
}
|
|
160
160
|
return true;
|
|
161
161
|
};
|
|
162
|
-
/** MemorySpecInput 闭合白名单(core dist/core/memory.d.ts
|
|
163
|
-
* 迭代 `scopes` —— 非数组形状(如 {scopes:{length:1}})在服务门不拦就是 core 运行期异常(cross-review 抓获)。
|
|
162
|
+
/** MemorySpecInput 闭合白名单(core dist/core/memory.d.ts 亲读)。core 的 normalizeMemorySpec 会直接
|
|
163
|
+
* 迭代 `scopes` —— 非数组形状(如 {scopes:{length:1}})在服务门不拦就是 core 运行期异常(cross-review 抓获)。
|
|
164
|
+
* core 5.1.0([2390]②,原 [2387] 预告):单数 `scope` 键已删,`scopes: string[]` 唯一拼法——白名单
|
|
165
|
+
* 同步剔键,收了就是穿门死键(用户以为设了 scope,core 静默无视)。 */
|
|
164
166
|
const memoryOk = (v) => {
|
|
165
167
|
if (!plainObject(v))
|
|
166
168
|
return false;
|
|
167
169
|
for (const k of Object.keys(v)) {
|
|
168
|
-
if (k !== "
|
|
170
|
+
if (k !== "scopes" && k !== "writeScope" && k !== "enabled" && k !== "scopeContract")
|
|
169
171
|
return false;
|
|
170
172
|
}
|
|
171
|
-
if (v.scope !== undefined && typeof v.scope !== "string")
|
|
172
|
-
return false;
|
|
173
173
|
if (v.scopes !== undefined && !(Array.isArray(v.scopes) && v.scopes.every((x) => typeof x === "string")))
|
|
174
174
|
return false;
|
|
175
175
|
if (v.writeScope !== undefined && v.writeScope !== null && typeof v.writeScope !== "string")
|
|
@@ -212,7 +212,7 @@ const TASK_AGENT_FIELD_SHAPES = {
|
|
|
212
212
|
desc: `a positive integer of at most ${MAX_AGENT_MAX_TURNS}`,
|
|
213
213
|
ok: (v) => typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= MAX_AGENT_MAX_TURNS,
|
|
214
214
|
},
|
|
215
|
-
memory: { desc: "a memory spec object ({
|
|
215
|
+
memory: { desc: "a memory spec object ({ scopes?, writeScope?, enabled?, scopeContract? })", ok: memoryOk },
|
|
216
216
|
observer: { desc: `a string of at most ${MAX_AGENT_TEXT_CHARS} characters`, ok: boundedString(MAX_AGENT_TEXT_CHARS) },
|
|
217
217
|
observerMessage: { desc: `a string of at most ${MAX_AGENT_TEXT_CHARS} characters`, ok: boundedString(MAX_AGENT_TEXT_CHARS) },
|
|
218
218
|
};
|
package/dist/task-settings.js
CHANGED
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
* - (`hooks` NO LONGER deferred either — 轴B #2 注释保鲜:applied 形已接线(本文件 hooks 分片 +
|
|
36
36
|
* main.ts 单用户闸),仅 malformed 才报 deferred;旧「需要 remote hook-runner」是接线前拍照。)
|
|
37
37
|
*/
|
|
38
|
-
import { combinePolicies, createAllowDenyPolicy, createFsWriteGatePolicy, createSensitivePathPolicy,
|
|
38
|
+
import { combinePolicies, createAllowDenyPolicy, createFsWriteGatePolicy, createSensitivePathPolicy, tightenTaskSpec, resolveReasoningProfile, rankOf, isThinkingLevel, CYBER_RISK, URL_SAFETY, HARNESS_SECTION_ANCHOR, } from "@sema-agent/core";
|
|
39
39
|
import { parseHooksConfig } from "./hooks/hook-runner.js";
|
|
40
40
|
/**
|
|
41
41
|
* R4: coerce a raw top-level `body.permissionMode` (the LIGHT per-turn wire — the shell sends the
|
|
@@ -250,10 +250,10 @@ function createAskListPolicy(askNames) {
|
|
|
250
250
|
// Canonical-space matching, mirroring core's `createAllowDenyPolicy` (1.202): a rule written against a legacy
|
|
251
251
|
// alias ("MultiEdit"/"Task") keeps asking after a CC-parity rename, and a durable-resume replay carrying a
|
|
252
252
|
// pre-rename `req.toolName` can't slip a rule written in the new names (ask only ever tightens — widening-safe).
|
|
253
|
-
const askSet = new Set(askNames.
|
|
253
|
+
const askSet = new Set(askNames); // RAW(5.0.0):折叠面退役
|
|
254
254
|
return {
|
|
255
255
|
check(req) {
|
|
256
|
-
return askSet.has(
|
|
256
|
+
return askSet.has(req.toolName)
|
|
257
257
|
? { action: "ask", message: `tool "${req.toolName}" requires approval by your settings`, decisionReason: "rule" }
|
|
258
258
|
: { action: "allow" };
|
|
259
259
|
},
|
|
@@ -266,7 +266,7 @@ function createAskListPolicy(askNames) {
|
|
|
266
266
|
/** [1245]/[1247]③ — the mode-derived dynamic-workflow ask gate (CC "Run a dynamic workflow?" dialog, engine half).
|
|
267
267
|
* core mounts `run_workflow` with effect="write" and NO exemption in the gate stack, but the mode-derived leg here
|
|
268
268
|
* only ever gated fs writes — so manual/default mode ran workflows un-asked ([1245] clay dogfood). This leg keys
|
|
269
|
-
* the canonical name
|
|
269
|
+
* the canonical name(`Workflow`;5.0.0:旧拼法 aliases 已随 core RB-476 退役,raw 直比)
|
|
270
270
|
* and attaches on default/auto/acceptEdits, independent of the fs-gate wiring (workflow gating is not
|
|
271
271
|
* fs-dependent — sandbox lanes get it too). acceptEdits asks ON PURPOSE: CC's acceptEdits auto-allows file edits
|
|
272
272
|
* only, a workflow confirmation is not an edit ([1248]② — cli to verify against the 212 live shell; flip there
|
|
@@ -277,7 +277,7 @@ const WORKFLOW_ASK_NAMES = ["Workflow"];
|
|
|
277
277
|
function createWorkflowAskPolicy(isExempt) {
|
|
278
278
|
return {
|
|
279
279
|
async check(req) {
|
|
280
|
-
if (
|
|
280
|
+
if (req.toolName !== "Workflow")
|
|
281
281
|
return { action: "allow" };
|
|
282
282
|
// codex F2 (durable lane): the "don't ask again this session" grant (decide remember="session" →
|
|
283
283
|
// approvalExemptionStore) is probed at the POLICY layer here — the durable lane parks every policy `ask`
|
|
@@ -286,7 +286,7 @@ function createWorkflowAskPolicy(isExempt) {
|
|
|
286
286
|
// (canonical toolName key space, one grant serves all layers); a THROWN probe ⇒ not exempt (fail-closed).
|
|
287
287
|
if (isExempt) {
|
|
288
288
|
try {
|
|
289
|
-
if (await isExempt(
|
|
289
|
+
if (await isExempt(req.toolName))
|
|
290
290
|
return { action: "allow", decisionReason: "rule" };
|
|
291
291
|
}
|
|
292
292
|
catch {
|
|
@@ -307,7 +307,7 @@ function createWorkflowAskPolicy(isExempt) {
|
|
|
307
307
|
function createWorkflowPlanDenyPolicy() {
|
|
308
308
|
return {
|
|
309
309
|
check(req) {
|
|
310
|
-
return
|
|
310
|
+
return req.toolName === "Workflow"
|
|
311
311
|
? { action: "deny", message: `Plan mode is active — "${req.toolName}" is a write/mutating tool and is read-only-blocked.`, decisionReason: "rule" }
|
|
312
312
|
: { action: "allow" };
|
|
313
313
|
},
|
package/dist/tool-approval.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AskRequest } from "@sema-agent/core";
|
|
1
|
+
import { type AskRequest, type AskOutcome } from "@sema-agent/core";
|
|
2
2
|
/** A live approval frame delivered to whoever tails this run's stream. `type` IS the SSE event name (named-event
|
|
3
3
|
* convention, same as question). The shell renders `tool_approval` as the CC three-choice card and dismisses on
|
|
4
4
|
* `tool_approval_complete`. */
|
|
@@ -103,7 +103,7 @@ export declare class ToolApprovalCoordinator {
|
|
|
103
103
|
* approverUnavailable 回路把这只 ask 交回 suspendAsk 走 durable park(park 设施缺席的部署 core 自己
|
|
104
104
|
* fail-closed deny)。1.199 的「durable 部署不 wire onAsk」止血就此撤除:恒 wire,park 与 live 卡两全。
|
|
105
105
|
* Arrow property so it can be passed as `onAsk: coordinator.ask` with `this` bound. */
|
|
106
|
-
ask: (req: AskRequest, signal?: AbortSignal) => Promise<
|
|
106
|
+
ask: (req: AskRequest, signal?: AbortSignal) => Promise<AskOutcome>;
|
|
107
107
|
/** [1535] server 半场(审批链战役,[1539] 定谳断点①的修;[1546] HIGH-1 broker 形):宿主 sync
|
|
108
108
|
* streaming 腿在装配点以本闭包挂 `spec.onAsk`;core 继承链(parentConstraints 冻结
|
|
109
109
|
* `spec.onAsk ?? deps.onAsk`,1.294 起)把它逐 ancestor 冻给每个委派子代——子代(bg/嵌套孙代)的
|
|
@@ -115,7 +115,7 @@ export declare class ToolApprovalCoordinator {
|
|
|
115
115
|
owner: string | null;
|
|
116
116
|
taskId: string;
|
|
117
117
|
sessionId?: string;
|
|
118
|
-
}) => ((req: AskRequest, signal?: AbortSignal) => Promise<
|
|
118
|
+
}) => ((req: AskRequest, signal?: AbortSignal) => Promise<AskOutcome>);
|
|
119
119
|
/** 广播版裁决路径——`ask()`(ALS,恒单元素数组)与 `boundAsk`([1559]四多活集合,可能多元素)共用。
|
|
120
120
|
* 全体 `ctxs` 保证同一 (owner, sessionId)(streamKey 分组不变式;单元素数组平凡成立)。
|
|
121
121
|
*
|
package/dist/tool-approval.js
CHANGED
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
* and asks are turn-blocking by construction — the TTL bounds the human-side exposure instead.
|
|
42
42
|
*/
|
|
43
43
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
44
|
-
import { uuidv7
|
|
44
|
+
import { uuidv7 } from "@sema-agent/core";
|
|
45
45
|
import { redactDeep, redactSecrets } from "./trace/redact.js";
|
|
46
46
|
/** Size bound on the redacted args payload in a `tool_approval` frame (parity with question's MAX_QUESTIONS_BYTES).
|
|
47
47
|
* Over the cap ⇒ the frame still goes out WITHOUT args (`argsOmitted: true`) — unlike a question (undisplayable ⇒
|
|
@@ -53,17 +53,17 @@ const DEFAULT_APPROVAL_TTL_MS = 5 * 60_000;
|
|
|
53
53
|
/** Bound on the remembered allow-all grants (insertion-order evict — a long-lived worker must not grow unbounded). */
|
|
54
54
|
const MAX_ALLOW_SESSIONS = 4096;
|
|
55
55
|
/** The fs-write tool family the session allow-all collapses into ONE capability bucket (canonical space — a
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
const FS_WRITE_TOOLS = new Set(["Write", "Edit", "NotebookEdit"]
|
|
56
|
+
* 5.0.0 RB-476:折叠面退役,三名即 CC canonical(旧拼法在 core roster 层响亮 miss)。Mirrors core's
|
|
57
|
+
* PATH_WRITE_TOOLS + NotebookEdit (the same set `createFsWriteGatePolicy` gates); NOT exported by core's
|
|
58
|
+
* index, so the names are pinned here deliberately. */
|
|
59
|
+
const FS_WRITE_TOOLS = new Set(["Write", "Edit", "NotebookEdit"]);
|
|
60
60
|
/** The session allow-all CAPABILITY CATEGORY for a tool (修2): the fs-write family shares one bucket ("fs-write" —
|
|
61
61
|
* a yes-to-edits covers Write/Edit/NotebookEdit alike, CC 207 semantics); every other tool is its OWN bucket
|
|
62
62
|
* ("tool:<canonical>") so an allow_session on it never grants anything beyond that same tool — a low-risk ask must
|
|
63
63
|
* not become a session-wide write unlock. Canonical space in, category out. */
|
|
64
64
|
function sessionAllowCategory(toolName) {
|
|
65
|
-
|
|
66
|
-
return FS_WRITE_TOOLS.has(
|
|
65
|
+
// RAW(5.0.0):live 名恒 canonical;存量 grant 键当年也是 canonical 空间铸的,键空间不变。
|
|
66
|
+
return FS_WRITE_TOOLS.has(toolName) ? "fs-write" : `tool:${toolName}`;
|
|
67
67
|
}
|
|
68
68
|
/** The allow-all grant key (修2): owner + sessionId + capability category, JSON-tuple-encoded so no segment can
|
|
69
69
|
* ambiguate the boundary with the next (an owner or sessionId containing a separator can't forge another key).
|
|
@@ -396,9 +396,9 @@ export class ToolApprovalCoordinator {
|
|
|
396
396
|
// 方法顶注。
|
|
397
397
|
if (!emitSettled && lastOutcome === "expired")
|
|
398
398
|
return "unavailable";
|
|
399
|
-
// [1458]
|
|
400
|
-
//
|
|
401
|
-
//
|
|
399
|
+
// [1458] 编辑放行对象臂:core AskOutcome 公开类型已含 `{allow, updatedInput?}`([1462])——
|
|
400
|
+
// 宽铸退役,真类型直返(core BAGGAGE #17 严格化前提=对象臂 allow 恒严格 true,我方满足)。
|
|
401
|
+
// deny 恒返 false(falsy 纪律)。
|
|
402
402
|
if (settled.allowed && settled.updatedInput !== undefined) {
|
|
403
403
|
return { allow: true, updatedInput: settled.updatedInput };
|
|
404
404
|
}
|
|
@@ -1,3 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* trace.artifacts (M2) — project "what the agent produced" from the durable event log.
|
|
3
|
+
*
|
|
4
|
+
* Deterministic projection, no new write path: artifacts are DERIVED from the already-persisted
|
|
5
|
+
* tool_start/tool_end pairs (S2 log), so they exist for every historical run and cannot drift from execution.
|
|
6
|
+
* v1 produces two kinds:
|
|
7
|
+
* - `file` — a successful `Write` / `Edit` call (deduped per path; the summary counts edits).
|
|
8
|
+
* - `git-push` — a successful `bash` call whose command contains `git push` (ref = the parsed refspec tail).
|
|
9
|
+
* `diff` is declared in the wire schema but NOT produced in v1 (we don't capture patch bodies in the log) —
|
|
10
|
+
* consumers must treat kinds as an open set. Args in the log are already secret-redacted at persist time.
|
|
11
|
+
*/
|
|
1
12
|
import type { RunEvent } from "../plugins/store-contracts.js";
|
|
2
13
|
export interface TraceArtifact {
|
|
3
14
|
/** Stable within the task: `<taskId>:<n>` in first-seen order — safe as a UI key + dedupe handle. */
|
package/dist/trace/artifacts.js
CHANGED
|
@@ -1,24 +1,12 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* trace.artifacts (M2) — project "what the agent produced" from the durable event log.
|
|
3
|
-
*
|
|
4
|
-
* Deterministic projection, no new write path: artifacts are DERIVED from the already-persisted
|
|
5
|
-
* tool_start/tool_end pairs (S2 log), so they exist for every historical run and cannot drift from execution.
|
|
6
|
-
* v1 produces two kinds:
|
|
7
|
-
* - `file` — a successful `Write` / `Edit` call (deduped per path; the summary counts edits).
|
|
8
|
-
* - `git-push` — a successful `bash` call whose command contains `git push` (ref = the parsed refspec tail).
|
|
9
|
-
* `diff` is declared in the wire schema but NOT produced in v1 (we don't capture patch bodies in the log) —
|
|
10
|
-
* consumers must treat kinds as an open set. Args in the log are already secret-redacted at persist time.
|
|
11
|
-
*/
|
|
12
|
-
import { canonicalToolName } from "@sema-agent/core";
|
|
13
1
|
/** Line count of a tool-arg string ("" = 0; no trailing-newline inflation). */
|
|
14
2
|
function lines(v) {
|
|
15
3
|
if (typeof v !== "string" || v.length === 0)
|
|
16
4
|
return 0;
|
|
17
5
|
return v.split("\n").length;
|
|
18
6
|
}
|
|
19
|
-
// Q6 (core 1.161) CC names
|
|
20
|
-
//
|
|
21
|
-
//
|
|
7
|
+
// Q6 (core 1.161) CC names。5.0.0 RB-476:折叠面退役——本投影跑在历史事件日志上,pre-rename 旧行
|
|
8
|
+
// (如 1.171 时代的 "MultiEdit")不再折到 canonical:旧名行按原名滑过 FILE_TOOLS 判定=不进 artifacts
|
|
9
|
+
// 归类(诚实历史,读面不再兜旧名;耐久面按 [2364] 令牺牲)。
|
|
22
10
|
const FILE_TOOLS = new Set(["Write", "Edit", "NotebookEdit"]);
|
|
23
11
|
const GIT_PUSH_RE = /\bgit\b[^;|&]*\bpush\b\s*(.*)/;
|
|
24
12
|
/** Project the durable event log into artifacts. Events must be in seq order (getEvents guarantees it). */
|
|
@@ -39,11 +27,12 @@ export function projectArtifacts(events, run) {
|
|
|
39
27
|
if (!start)
|
|
40
28
|
continue;
|
|
41
29
|
starts.delete(d.toolCallId); // each call contributes at most once
|
|
42
|
-
const toolName =
|
|
30
|
+
const toolName = start.toolName; // RAW(5.0.0):折叠面退役,历史旧名行按原名处理(见文件头注)
|
|
43
31
|
if (FILE_TOOLS.has(toolName)) {
|
|
44
|
-
// Write/Edit key the write target on `file_path
|
|
45
|
-
//
|
|
46
|
-
//
|
|
32
|
+
// Write/Edit key the write target on `file_path`. core 5.1.0([2390])收窄 schema 为 `file_path` 单形,
|
|
33
|
+
// 但**门读侧 over-read 保留**是同批 KEEP 裁定(fail-closed 方向)——这里是耐久历史行的读侧([2373] D 类),
|
|
34
|
+
// pre-1.169 emit/旧 durable checkpoint 仍带 `path`,回落臂是对自己旧数据的容忍,不是对上游新帧的兼容。
|
|
35
|
+
// 再回落 NotebookEdit 的 `notebook_path`(core 1.163)。三键全缺 → 非带路径调用。
|
|
47
36
|
const path = typeof start.args["file_path"] === "string" ? start.args["file_path"] : typeof start.args["path"] === "string" ? start.args["path"] : typeof start.args["notebook_path"] === "string" ? start.args["notebook_path"] : undefined;
|
|
48
37
|
if (!path)
|
|
49
38
|
continue;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { redactSecrets } from "./redact.js";
|
|
2
|
-
import { toolStartEventData, toolEndEventData, taskProgressEventData, taskNotificationEventData, compactedEventData, diagnosticsEventData, brainStatusEventData, steeringInjectedEventData, workspaceChangedEventData, turnEndEventData, contextUsageEventData } from "./project.js";
|
|
2
|
+
import { toolStartEventData, toolEndEventData, taskProgressEventData, taskNotificationEventData, compactedEventData, diagnosticsEventData, brainStatusEventData, steeringInjectedEventData, compactionOutcomeEventData, workspaceChangedEventData, turnEndEventData, contextUsageEventData } from "./project.js";
|
|
3
3
|
import { NotifiedKeys, taskNotificationStreamKey } from "../orchestration/workflow-completion-inbox.js";
|
|
4
4
|
export function createLedgerSink(opts) {
|
|
5
5
|
const keys = opts.notifiedKeys ?? new NotifiedKeys();
|
|
@@ -101,6 +101,12 @@ export function createLedgerSink(opts) {
|
|
|
101
101
|
await flush();
|
|
102
102
|
await append("steering_injected", steeringInjectedEventData(ev));
|
|
103
103
|
break;
|
|
104
|
+
case "compaction_outcome":
|
|
105
|
+
// [2373]A-2/C-2:此前 durable 双腿零 case ⇒ 回放即消失(与 [1622] label / [1611] workflowRunId
|
|
106
|
+
// 同族)。共享 builder(§E1 脱敏)三腿同源;差集门 durable-append-arm-parity 看守。
|
|
107
|
+
await flush();
|
|
108
|
+
await append("compaction_outcome", compactionOutcomeEventData(ev));
|
|
109
|
+
break;
|
|
104
110
|
case "workspace_changed":
|
|
105
111
|
// [1559]二 core 裁定:design/99 §E13 旧臂,L1 门扩臂时首次撞见。durable 记账与其余内容型臂
|
|
106
112
|
// 同处置(轨迹回放时「何时 cd 到了哪」是合法历史事实,「不当持久态渲染」是 LIVE 消费端纪律,
|
package/dist/trace/project.d.ts
CHANGED
|
@@ -235,6 +235,17 @@ export declare function steeringInjectedEventData(ev: {
|
|
|
235
235
|
eventId?: string;
|
|
236
236
|
parentToolCallId?: string;
|
|
237
237
|
}): Record<string, unknown>;
|
|
238
|
+
/** `compaction_outcome`(core 2.5.0 [2105]②:压缩非 compacted 结局——manual /compact 的 mooted/failed
|
|
239
|
+
* 两条真路)。[2373]A-2/C-2:此前它是**唯一**不走共享 builder、只在 live 腿 res.write 内联挑键的
|
|
240
|
+
* 内容帧 ⇒ 两条 durable 腿零 case、回放即消失、三方普查各自失明。收进共享白名单 builder,三腿同源。
|
|
241
|
+
* outcome/trigger=闭枚举 verbatim;reason=引擎说明文本(可能引用配置值)→ redactSecrets;identity 同款。 */
|
|
242
|
+
export declare function compactionOutcomeEventData(ev: {
|
|
243
|
+
outcome?: unknown;
|
|
244
|
+
trigger?: unknown;
|
|
245
|
+
reason?: unknown;
|
|
246
|
+
eventId?: unknown;
|
|
247
|
+
parentToolCallId?: unknown;
|
|
248
|
+
}): Record<string, unknown>;
|
|
238
249
|
/** The `workspace_changed` payload([1559]二 core 裁定:design/99 §E13 旧臂,L1 门本车首次撞见——非新增,
|
|
239
250
|
* 是本门扩 TaskEvent 臂集时第一次显式处置。语义 = bash `cd`/EnterWorktree 移动任务逻辑 cwd 后,在移动
|
|
240
251
|
* 它的工具结算后发一帧,给 shell/宿主 UI 一个路径提示行。cwd 与已展示的工具 args 同信任级[UNTRUSTED,
|
|
@@ -347,6 +358,12 @@ export declare function turnEndEventData(ev: {
|
|
|
347
358
|
* `in` 落回旧值,读端零伤)。`uncachedIn` 只在**能确认自己踩在新契约帧上**(`totalInputTokens` 在场)时
|
|
348
359
|
* 才发——旧帧的 `inputTokens` 是族依赖的旧语义,标成「uncachedIn(cache-MISS)」会是谎言。 */
|
|
349
360
|
export declare function toContractTokens(usage: unknown): TraceTurn["tokens"] | undefined;
|
|
361
|
+
/** [2373]C-13:tool_start/tool_end 的**共享挑键**——`projectEvents`(turns 面)与 `mapTraceEvent`
|
|
362
|
+
* (trace SSE 面)对同一账本行的字段选择逐字同构,此前两处独立手写,structured/totalChars/label
|
|
363
|
+
* 三次扩字段各改两遍(见两处对偶注)。收一份:两面各自包装键名皮(id/name/input vs 同名),
|
|
364
|
+
* 字段集合从此单点演进。 */
|
|
365
|
+
export declare function toolCallFieldsOf(d: Record<string, unknown>): Record<string, unknown>;
|
|
366
|
+
export declare function toolResultFieldsOf(d: Record<string, unknown>): Record<string, unknown>;
|
|
350
367
|
export interface ProjectOpts {
|
|
351
368
|
/** Prepend the user turn (the objective is not in the event log; the endpoint supplies it). */
|
|
352
369
|
objective?: string;
|
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,19 @@ 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
|
+
return {
|
|
308
|
+
outcome: String(ev.outcome),
|
|
309
|
+
trigger: String(ev.trigger),
|
|
310
|
+
...(ev.reason !== undefined ? { reason: redactSecrets(String(ev.reason)) } : {}),
|
|
311
|
+
...identityFields(ev),
|
|
312
|
+
};
|
|
313
|
+
}
|
|
299
314
|
/** The `workspace_changed` payload([1559]二 core 裁定:design/99 §E13 旧臂,L1 门本车首次撞见——非新增,
|
|
300
315
|
* 是本门扩 TaskEvent 臂集时第一次显式处置。语义 = bash `cd`/EnterWorktree 移动任务逻辑 cwd 后,在移动
|
|
301
316
|
* 它的工具结算后发一帧,给 shell/宿主 UI 一个路径提示行。cwd 与已展示的工具 args 同信任级[UNTRUSTED,
|
|
@@ -395,6 +410,9 @@ export function compactedEventData(ev) {
|
|
|
395
410
|
* 挂那儿会是"另一次更早的测量顶着同一个名字")。去 turn_end 找是找不到的。
|
|
396
411
|
* 三个字段都是引擎派生的有限数标量 ⇒ 走 finite 门(与 compacted 的 1.289 标量同姿势),非有限即缺席。
|
|
397
412
|
*/
|
|
413
|
+
// [2373]A-3 记账(2026-08-02):SDK 有臂、五端零读点(webC Composer 读的是本端自己的 state.context,
|
|
414
|
+
// 非 wire 三键)——半死:契约面已就位、消费端一个都没接。头注下方的三条口径纪律警告的消费者还不存在;
|
|
415
|
+
// 谁要做压缩面板,这是真正需要的量,先上黑板认领。
|
|
398
416
|
export function contextUsageEventData(ev) {
|
|
399
417
|
const n = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
|
|
400
418
|
return {
|
|
@@ -442,6 +460,29 @@ export function toContractTokens(usage) {
|
|
|
442
460
|
...(u.cacheWriteTokens != null ? { cacheWrite: u.cacheWriteTokens } : {}),
|
|
443
461
|
};
|
|
444
462
|
}
|
|
463
|
+
/** [2373]C-13:tool_start/tool_end 的**共享挑键**——`projectEvents`(turns 面)与 `mapTraceEvent`
|
|
464
|
+
* (trace SSE 面)对同一账本行的字段选择逐字同构,此前两处独立手写,structured/totalChars/label
|
|
465
|
+
* 三次扩字段各改两遍(见两处对偶注)。收一份:两面各自包装键名皮(id/name/input vs 同名),
|
|
466
|
+
* 字段集合从此单点演进。 */
|
|
467
|
+
export function toolCallFieldsOf(d) {
|
|
468
|
+
return {
|
|
469
|
+
id: String(d.toolCallId ?? ""),
|
|
470
|
+
name: String(d.toolName ?? ""),
|
|
471
|
+
...(typeof d.label === "string" ? { label: d.label } : {}),
|
|
472
|
+
input: d.args,
|
|
473
|
+
...identityFields(d),
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
export function toolResultFieldsOf(d) {
|
|
477
|
+
return {
|
|
478
|
+
callId: String(d.toolCallId ?? ""),
|
|
479
|
+
...(typeof d.label === "string" ? { label: d.label } : {}),
|
|
480
|
+
...(d.truncated ? { truncated: true } : {}),
|
|
481
|
+
...(Number.isFinite(d.totalChars) ? { totalChars: d.totalChars } : {}),
|
|
482
|
+
...(d.structured !== undefined ? { structured: d.structured } : {}),
|
|
483
|
+
...identityFields(d),
|
|
484
|
+
};
|
|
485
|
+
}
|
|
445
486
|
/** Project a per-task event slice (seq-ascending) into ordered `TraceTurn[]`. Pure + total (never throws). */
|
|
446
487
|
export function projectEvents(events, opts = {}) {
|
|
447
488
|
const turns = [];
|
|
@@ -470,14 +511,14 @@ export function projectEvents(events, opts = {}) {
|
|
|
470
511
|
break;
|
|
471
512
|
case "tool_start":
|
|
472
513
|
firstTs ??= ev.ts;
|
|
473
|
-
blocks.push({ type: "tool-call",
|
|
514
|
+
blocks.push({ type: "tool-call", ...toolCallFieldsOf(d) });
|
|
474
515
|
break;
|
|
475
516
|
case "tool_end": {
|
|
476
517
|
const callId = String(d.toolCallId ?? "");
|
|
477
518
|
// E1: output is read straight off the (already-redacted-at-append) event — no session join. Absent ⇒ undefined.
|
|
478
519
|
// `structured` (core 1.203 CC card) was redacted at APPEND (toolEndEventData) — passthrough on the read
|
|
479
520
|
// path so a cold-replay/turns consumer renders the same rich card the live wire carried (additive field).
|
|
480
|
-
blocks.push({ type: "tool-result",
|
|
521
|
+
blocks.push({ type: "tool-result", ...toolResultFieldsOf(d), output: d.output, ...(d.isError ? { isError: true } : {}) });
|
|
481
522
|
break;
|
|
482
523
|
}
|
|
483
524
|
case "prompt_assembled":
|
|
@@ -525,6 +566,8 @@ export function lastStep(latestEventType, status) {
|
|
|
525
566
|
/** A run record → the cheap list summary (contract 2.1). Token/cost/turns come from the terminal result.stats;
|
|
526
567
|
* scenario isn't denormalized on the run row (omitted — a later push-index/column refinement). */
|
|
527
568
|
export function taskSummary(run, latestEventType) {
|
|
569
|
+
// [2373]D-1(活 bug 修):core 2.0.0 起浮点 costUsd 族整删,stats 只有整数 costMicroUsd —— 旧读点
|
|
570
|
+
// (costUsd × 1e6)对现役 core 恒缺席,verbatim 透传才是唯一正确形。
|
|
528
571
|
const stats = (run.result?.stats ?? {});
|
|
529
572
|
const terminal = run.status !== "running";
|
|
530
573
|
return {
|
|
@@ -538,7 +581,7 @@ export function taskSummary(run, latestEventType) {
|
|
|
538
581
|
...(terminal ? { endedAt: run.updatedAt } : {}),
|
|
539
582
|
...(stats.turns !== undefined ? { turns: stats.turns } : {}),
|
|
540
583
|
...(stats.tokens !== undefined ? { tokens: stats.tokens } : {}),
|
|
541
|
-
...(stats.
|
|
584
|
+
...(stats.costMicroUsd !== undefined ? { costMicroUsd: stats.costMicroUsd } : {}),
|
|
542
585
|
lastStep: lastStep(latestEventType, run.status),
|
|
543
586
|
};
|
|
544
587
|
}
|
|
@@ -560,16 +603,23 @@ export function normalizeRunEventType(type) {
|
|
|
560
603
|
/** Map one durable event → a sema-registry SSE trace event (contract 2.3). null = not a client event. The
|
|
561
604
|
* durable log is block-grained, so each block ships as one "delta" the client appends (stream mode = "delta"). */
|
|
562
605
|
export function mapTraceEvent(type, seq, data) {
|
|
606
|
+
const mapped = mapTraceEventInner(type, seq, data);
|
|
607
|
+
if (mapped === null)
|
|
608
|
+
return null;
|
|
609
|
+
// [2373]C-12:data 里补 `type`(=event 名)双发(fleet 流同批;error 帧 arm 自带 type 保持原值)。
|
|
610
|
+
return { event: mapped.event, data: { type: mapped.event, ...mapped.data } };
|
|
611
|
+
}
|
|
612
|
+
function mapTraceEventInner(type, seq, data) {
|
|
563
613
|
switch (type) {
|
|
564
614
|
case "reasoning":
|
|
565
615
|
return { event: "block-thinking-delta", data: { seq, text: String(data.text ?? "") } };
|
|
566
616
|
case "text":
|
|
567
617
|
return { event: "block-content-delta", data: { seq, text: String(data.text ?? "") } };
|
|
568
618
|
case "tool_start":
|
|
569
|
-
return { event: "tool-call", data: { seq,
|
|
619
|
+
return { event: "tool-call", data: { seq, ...toolCallFieldsOf(data) } };
|
|
570
620
|
case "tool_end":
|
|
571
621
|
// E1: output/truncated are already redacted+bounded at append; pass through. E2: identity additive.
|
|
572
|
-
return { event: "tool-result", data: { seq,
|
|
622
|
+
return { event: "tool-result", data: { seq, ...toolResultFieldsOf(data), isError: Boolean(data.isError), ...(data.output !== undefined ? { output: data.output } : {}) } };
|
|
573
623
|
case "turn_end": {
|
|
574
624
|
const tokens = toContractTokens(data.usage);
|
|
575
625
|
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.0",
|
|
4
4
|
"description": "Sema Server — the server/API implementation layer for Sema, wiring core, registry, model providers, and cloud agent execution. Built on @sema-agent/core.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "BUSL-1.1",
|
|
@@ -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",
|
|
@@ -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
|