coremind-runtime 0.3.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/README.md +49 -1
  2. package/dist/active-run-binding.d.ts +24 -0
  3. package/dist/active-run-binding.d.ts.map +1 -0
  4. package/dist/active-run-binding.js +22 -0
  5. package/dist/active-run-binding.js.map +1 -0
  6. package/dist/agent-driver.d.ts +139 -0
  7. package/dist/agent-driver.d.ts.map +1 -0
  8. package/dist/agent-driver.js +135 -0
  9. package/dist/agent-driver.js.map +1 -0
  10. package/dist/agent-factory.d.ts +10 -10
  11. package/dist/agent-factory.d.ts.map +1 -1
  12. package/dist/agent-factory.js +179 -14
  13. package/dist/agent-factory.js.map +1 -1
  14. package/dist/budget.d.ts +11 -1
  15. package/dist/budget.d.ts.map +1 -1
  16. package/dist/budget.js +59 -16
  17. package/dist/budget.js.map +1 -1
  18. package/dist/canonical-json.d.ts +3 -0
  19. package/dist/canonical-json.d.ts.map +1 -0
  20. package/dist/canonical-json.js +28 -0
  21. package/dist/canonical-json.js.map +1 -0
  22. package/dist/chat-session.d.ts +3 -0
  23. package/dist/chat-session.d.ts.map +1 -1
  24. package/dist/chat-session.js +5 -0
  25. package/dist/chat-session.js.map +1 -1
  26. package/dist/checkpoint.d.ts +25 -8
  27. package/dist/checkpoint.d.ts.map +1 -1
  28. package/dist/checkpoint.js +135 -52
  29. package/dist/checkpoint.js.map +1 -1
  30. package/dist/child-run.d.ts +344 -0
  31. package/dist/child-run.d.ts.map +1 -0
  32. package/dist/child-run.js +1373 -0
  33. package/dist/child-run.js.map +1 -0
  34. package/dist/child-runtime-adapter.d.ts +18 -0
  35. package/dist/child-runtime-adapter.d.ts.map +1 -0
  36. package/dist/child-runtime-adapter.js +309 -0
  37. package/dist/child-runtime-adapter.js.map +1 -0
  38. package/dist/compaction-projection.d.ts +5 -0
  39. package/dist/compaction-projection.d.ts.map +1 -1
  40. package/dist/compaction-projection.js +19 -1
  41. package/dist/compaction-projection.js.map +1 -1
  42. package/dist/context-lifecycle.d.ts +182 -0
  43. package/dist/context-lifecycle.d.ts.map +1 -0
  44. package/dist/context-lifecycle.js +455 -0
  45. package/dist/context-lifecycle.js.map +1 -0
  46. package/dist/context-task-state.d.ts +23 -0
  47. package/dist/context-task-state.d.ts.map +1 -0
  48. package/dist/context-task-state.js +183 -0
  49. package/dist/context-task-state.js.map +1 -0
  50. package/dist/control-inbox.d.ts +106 -0
  51. package/dist/control-inbox.d.ts.map +1 -0
  52. package/dist/control-inbox.js +291 -0
  53. package/dist/control-inbox.js.map +1 -0
  54. package/dist/delegated-context.d.ts +29 -0
  55. package/dist/delegated-context.d.ts.map +1 -0
  56. package/dist/delegated-context.js +76 -0
  57. package/dist/delegated-context.js.map +1 -0
  58. package/dist/delegation-tool.d.ts +30 -0
  59. package/dist/delegation-tool.d.ts.map +1 -0
  60. package/dist/delegation-tool.js +232 -0
  61. package/dist/delegation-tool.js.map +1 -0
  62. package/dist/effect-receipt-binding.d.ts +34 -0
  63. package/dist/effect-receipt-binding.d.ts.map +1 -0
  64. package/dist/effect-receipt-binding.js +125 -0
  65. package/dist/effect-receipt-binding.js.map +1 -0
  66. package/dist/errors.d.ts +11 -315
  67. package/dist/errors.d.ts.map +1 -1
  68. package/dist/errors.js +7 -129
  69. package/dist/errors.js.map +1 -1
  70. package/dist/evaluation.d.ts.map +1 -1
  71. package/dist/evaluation.js +12 -5
  72. package/dist/evaluation.js.map +1 -1
  73. package/dist/events.d.ts +91 -3
  74. package/dist/events.d.ts.map +1 -1
  75. package/dist/events.js +44 -0
  76. package/dist/events.js.map +1 -1
  77. package/dist/execution-error.d.ts +14 -0
  78. package/dist/execution-error.d.ts.map +1 -0
  79. package/dist/execution-error.js +129 -0
  80. package/dist/execution-error.js.map +1 -0
  81. package/dist/execution-security.d.ts +11 -0
  82. package/dist/execution-security.d.ts.map +1 -0
  83. package/dist/execution-security.js +40 -0
  84. package/dist/execution-security.js.map +1 -0
  85. package/dist/fact-ledger.d.ts +60 -0
  86. package/dist/fact-ledger.d.ts.map +1 -0
  87. package/dist/fact-ledger.js +167 -0
  88. package/dist/fact-ledger.js.map +1 -0
  89. package/dist/ids.d.ts +4 -0
  90. package/dist/ids.d.ts.map +1 -1
  91. package/dist/ids.js.map +1 -1
  92. package/dist/index.d.ts +15 -5
  93. package/dist/index.d.ts.map +1 -1
  94. package/dist/index.js +11 -2
  95. package/dist/index.js.map +1 -1
  96. package/dist/internal.d.ts +11 -0
  97. package/dist/internal.d.ts.map +1 -0
  98. package/dist/internal.js +11 -0
  99. package/dist/internal.js.map +1 -0
  100. package/dist/invariant-checker.d.ts.map +1 -1
  101. package/dist/invariant-checker.js +51 -10
  102. package/dist/invariant-checker.js.map +1 -1
  103. package/dist/loop-runner.d.ts.map +1 -1
  104. package/dist/loop-runner.js +14 -8
  105. package/dist/loop-runner.js.map +1 -1
  106. package/dist/observability.d.ts +211 -0
  107. package/dist/observability.d.ts.map +1 -0
  108. package/dist/observability.js +814 -0
  109. package/dist/observability.js.map +1 -0
  110. package/dist/orchestrator.d.ts +2 -2
  111. package/dist/orchestrator.d.ts.map +1 -1
  112. package/dist/orchestrator.js +12 -6
  113. package/dist/orchestrator.js.map +1 -1
  114. package/dist/project-check.d.ts +3 -0
  115. package/dist/project-check.d.ts.map +1 -1
  116. package/dist/project-check.js +21 -5
  117. package/dist/project-check.js.map +1 -1
  118. package/dist/projection.d.ts +131 -0
  119. package/dist/projection.d.ts.map +1 -0
  120. package/dist/projection.js +972 -0
  121. package/dist/projection.js.map +1 -0
  122. package/dist/provider.d.ts +23 -1
  123. package/dist/provider.d.ts.map +1 -1
  124. package/dist/provider.js +134 -23
  125. package/dist/provider.js.map +1 -1
  126. package/dist/public-tool.d.ts +3 -0
  127. package/dist/public-tool.d.ts.map +1 -1
  128. package/dist/public-tool.js +28 -3
  129. package/dist/public-tool.js.map +1 -1
  130. package/dist/replay-kit.d.ts +41 -0
  131. package/dist/replay-kit.d.ts.map +1 -0
  132. package/dist/replay-kit.js +96 -0
  133. package/dist/replay-kit.js.map +1 -0
  134. package/dist/result.d.ts +17 -1
  135. package/dist/result.d.ts.map +1 -1
  136. package/dist/result.js +16 -0
  137. package/dist/result.js.map +1 -1
  138. package/dist/retry-policy.d.ts.map +1 -1
  139. package/dist/retry-policy.js +22 -72
  140. package/dist/retry-policy.js.map +1 -1
  141. package/dist/run-context.d.ts +77 -0
  142. package/dist/run-context.d.ts.map +1 -0
  143. package/dist/run-context.js +159 -0
  144. package/dist/run-context.js.map +1 -0
  145. package/dist/run-effect-coordinator.d.ts.map +1 -1
  146. package/dist/run-effect-coordinator.js +3 -0
  147. package/dist/run-effect-coordinator.js.map +1 -1
  148. package/dist/run-kernel.d.ts +14 -0
  149. package/dist/run-kernel.d.ts.map +1 -0
  150. package/dist/run-kernel.js +34 -0
  151. package/dist/run-kernel.js.map +1 -0
  152. package/dist/run-state.d.ts +65 -4
  153. package/dist/run-state.d.ts.map +1 -1
  154. package/dist/run-state.js +502 -76
  155. package/dist/run-state.js.map +1 -1
  156. package/dist/run-terminalizer.d.ts.map +1 -1
  157. package/dist/run-terminalizer.js +4 -3
  158. package/dist/run-terminalizer.js.map +1 -1
  159. package/dist/runtime-instance-authority.d.ts +3 -0
  160. package/dist/runtime-instance-authority.d.ts.map +1 -0
  161. package/dist/runtime-instance-authority.js +8 -0
  162. package/dist/runtime-instance-authority.js.map +1 -0
  163. package/dist/runtime.d.ts +83 -2
  164. package/dist/runtime.d.ts.map +1 -1
  165. package/dist/runtime.js +2048 -348
  166. package/dist/runtime.js.map +1 -1
  167. package/dist/session.d.ts +4 -3
  168. package/dist/session.d.ts.map +1 -1
  169. package/dist/session.js.map +1 -1
  170. package/dist/tool-call-lifecycle.d.ts +89 -0
  171. package/dist/tool-call-lifecycle.d.ts.map +1 -0
  172. package/dist/tool-call-lifecycle.js +379 -0
  173. package/dist/tool-call-lifecycle.js.map +1 -0
  174. package/dist/tool-capability-identity.d.ts +3 -0
  175. package/dist/tool-capability-identity.d.ts.map +1 -0
  176. package/dist/tool-capability-identity.js +5 -0
  177. package/dist/tool-capability-identity.js.map +1 -0
  178. package/dist/tool-capability-projection.d.ts +17 -0
  179. package/dist/tool-capability-projection.d.ts.map +1 -0
  180. package/dist/tool-capability-projection.js +99 -0
  181. package/dist/tool-capability-projection.js.map +1 -0
  182. package/dist/tool-effect-selectors.d.ts +3 -0
  183. package/dist/tool-effect-selectors.d.ts.map +1 -0
  184. package/dist/tool-effect-selectors.js +18 -0
  185. package/dist/tool-effect-selectors.js.map +1 -0
  186. package/dist/tool-policy.d.ts +13 -2
  187. package/dist/tool-policy.d.ts.map +1 -1
  188. package/dist/tool-policy.js +149 -44
  189. package/dist/tool-policy.js.map +1 -1
  190. package/dist/trace.d.ts +1 -0
  191. package/dist/trace.d.ts.map +1 -1
  192. package/dist/trace.js +10 -3
  193. package/dist/trace.js.map +1 -1
  194. package/dist/turn-tracker.d.ts.map +1 -1
  195. package/dist/turn-tracker.js +1 -0
  196. package/dist/turn-tracker.js.map +1 -1
  197. package/dist/workspace-lease.d.ts +81 -0
  198. package/dist/workspace-lease.d.ts.map +1 -0
  199. package/dist/workspace-lease.js +300 -0
  200. package/dist/workspace-lease.js.map +1 -0
  201. package/package.json +11 -5
@@ -0,0 +1,814 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isIP } from "node:net";
3
+ import { canonicalJson } from "./canonical-json.js";
4
+ import { CoreMindError } from "./errors.js";
5
+ import { projectToolCallLifecycles } from "./tool-call-lifecycle.js";
6
+ import { redactSensitiveValue } from "./trace.js";
7
+ /** 创建与授权范围精确绑定的持久 consent Fact。 */
8
+ export function createTelemetryConsentFact(input) {
9
+ const fact = {
10
+ schemaVersion: 1,
11
+ scopeFingerprint: telemetryConsentScopeFingerprint(input),
12
+ runId: input.runId,
13
+ consentId: input.consentId,
14
+ kind: input.kind,
15
+ targetOrigin: input.targetOrigin,
16
+ contentLevel: input.contentLevel,
17
+ allowedFields: [...new Set(input.allowedFields)].sort(),
18
+ ...(input.throughSequence === undefined ? {} : { throughSequence: input.throughSequence }),
19
+ ...(input.factPrefixFingerprint === undefined
20
+ ? {}
21
+ : { factPrefixFingerprint: input.factPrefixFingerprint }),
22
+ ...(input.retentionPurpose === undefined ? {} : { retentionPurpose: input.retentionPurpose }),
23
+ ...(input.revocationMethod === undefined ? {} : { revocationMethod: input.revocationMethod }),
24
+ grantedAt: input.grantedAt,
25
+ };
26
+ return validateTelemetryConsentFact(fact);
27
+ }
28
+ /** consent 只绑定发送范围,不把 UI 状态或授权时间混入范围身份。 */
29
+ export function telemetryConsentScopeFingerprint(input) {
30
+ return createHash("sha256")
31
+ .update(canonicalJson({
32
+ runId: input.runId,
33
+ kind: input.kind,
34
+ targetOrigin: input.targetOrigin,
35
+ contentLevel: input.contentLevel,
36
+ allowedFields: [...new Set(input.allowedFields)].sort(),
37
+ ...(input.throughSequence === undefined ? {} : { throughSequence: input.throughSequence }),
38
+ ...(input.factPrefixFingerprint === undefined
39
+ ? {}
40
+ : { factPrefixFingerprint: input.factPrefixFingerprint }),
41
+ ...(input.retentionPurpose === undefined
42
+ ? {}
43
+ : { retentionPurpose: input.retentionPurpose }),
44
+ ...(input.revocationMethod === undefined
45
+ ? {}
46
+ : { revocationMethod: input.revocationMethod }),
47
+ }), "utf8")
48
+ .digest("hex");
49
+ }
50
+ export class TelemetryExporterError extends Error {
51
+ code;
52
+ constructor(code, message) {
53
+ super(message);
54
+ this.code = code;
55
+ this.name = "TelemetryExporterError";
56
+ }
57
+ }
58
+ /**
59
+ * 可丢弃的 Telemetry 投影器。它只消费已经持久化的 Facts,且永远不写回运行事实。
60
+ */
61
+ export class TelemetryEgressController {
62
+ options;
63
+ constructor(options) {
64
+ this.options = options;
65
+ }
66
+ async export(records) {
67
+ const policy = normalizePolicy(this.options.policy);
68
+ const projection = emptyDelivery(policy);
69
+ if (policy.mode === "DISABLED")
70
+ return projection;
71
+ let endpointOrigin;
72
+ try {
73
+ endpointOrigin = endpointOriginOf(policy.endpoint);
74
+ }
75
+ catch (error) {
76
+ projection.failed = 1;
77
+ projection.lastFailure = failureCodeOf(error);
78
+ return projection;
79
+ }
80
+ projection.endpointOrigin = endpointOrigin;
81
+ let persistedPolicy;
82
+ try {
83
+ persistedPolicy = telemetryStateFromFacts(canonicalAuthorizationRecords(records));
84
+ }
85
+ catch {
86
+ projection.failed = 1;
87
+ projection.lastFailure = "configuration_mismatch";
88
+ return projection;
89
+ }
90
+ if (!telemetryConfigurationMatches(persistedPolicy, policy, endpointOrigin)) {
91
+ projection.failed = 1;
92
+ projection.lastFailure = "configuration_mismatch";
93
+ return projection;
94
+ }
95
+ const consentFailure = consentFailureFor(records, policy, endpointOrigin);
96
+ if (consentFailure) {
97
+ projection.failed = 1;
98
+ projection.lastFailure = consentFailure;
99
+ return projection;
100
+ }
101
+ if (!this.options.createExporter) {
102
+ projection.failed = 1;
103
+ projection.lastFailure = "exporter_unavailable";
104
+ return projection;
105
+ }
106
+ if (!this.options.authorizeEgress) {
107
+ projection.failed = 1;
108
+ projection.lastFailure = "egress_policy_missing";
109
+ return projection;
110
+ }
111
+ const exportDeadline = Date.now() + Math.max(0, this.options.exportTimeoutMs ?? 5_000);
112
+ const authorizationResult = await invokeBeforeDeadline((signal) => this.options.authorizeEgress({ endpointOrigin, signal }), exportDeadline);
113
+ if (authorizationResult.status !== "fulfilled") {
114
+ projection.failed = 1;
115
+ projection.lastFailure =
116
+ authorizationResult.status === "timed_out"
117
+ ? "timeout"
118
+ : failureCodeOf(authorizationResult.reason);
119
+ return projection;
120
+ }
121
+ let authorization;
122
+ try {
123
+ authorization = validateTelemetryEgressAuthorization(authorizationResult.value, endpointOrigin);
124
+ }
125
+ catch {
126
+ projection.failed = 1;
127
+ projection.lastFailure = "egress_policy_denied";
128
+ return projection;
129
+ }
130
+ let exporter;
131
+ try {
132
+ const credentialsResult = this.options.readCredentials
133
+ ? await invokeBeforeDeadline((signal) => this.options.readCredentials(signal), exportDeadline)
134
+ : { status: "fulfilled", value: undefined };
135
+ if (credentialsResult.status !== "fulfilled") {
136
+ projection.failed = 1;
137
+ projection.lastFailure =
138
+ credentialsResult.status === "timed_out"
139
+ ? "timeout"
140
+ : failureCodeOf(credentialsResult.reason);
141
+ return projection;
142
+ }
143
+ const exporterResult = await invokeBeforeDeadline((signal) => this.options.createExporter({
144
+ endpointOrigin,
145
+ authorization,
146
+ signal,
147
+ ...(credentialsResult.value ? { credentials: credentialsResult.value } : {}),
148
+ }), exportDeadline);
149
+ if (exporterResult.status !== "fulfilled") {
150
+ projection.failed = 1;
151
+ projection.lastFailure =
152
+ exporterResult.status === "timed_out" ? "timeout" : failureCodeOf(exporterResult.reason);
153
+ return projection;
154
+ }
155
+ exporter = exporterResult.value;
156
+ projection.exporterLoaded = true;
157
+ }
158
+ catch (error) {
159
+ projection.failed = 1;
160
+ projection.lastFailure = failureCodeOf(error);
161
+ return projection;
162
+ }
163
+ const eligible = eligibleRecords(records, policy, endpointOrigin);
164
+ const unique = [];
165
+ const identities = new Set();
166
+ for (const record of eligible) {
167
+ const identity = identityOf(record);
168
+ if (identities.has(identity)) {
169
+ projection.duplicates += 1;
170
+ continue;
171
+ }
172
+ identities.add(identity);
173
+ unique.push(record);
174
+ }
175
+ const queueLimit = Math.max(0, this.options.queueLimit ?? Number.POSITIVE_INFINITY);
176
+ const queue = unique.slice(0, queueLimit);
177
+ projection.dropped += unique.length - queue.length;
178
+ projection.queued = queue.length;
179
+ for (const [index, record] of queue.entries()) {
180
+ try {
181
+ const projected = projectExportRecord(record, policy, this.options.redact);
182
+ const exported = await invokeBeforeDeadline((signal) => exporter.export(projected, { authorization, signal }), exportDeadline);
183
+ if (exported.status === "timed_out") {
184
+ projection.failed += 1;
185
+ projection.lastFailure = "timeout";
186
+ projection.dropped += queue.length - index - 1;
187
+ projection.queued = 0;
188
+ break;
189
+ }
190
+ if (exported.status === "rejected")
191
+ throw exported.reason;
192
+ projection.handedOff += 1;
193
+ }
194
+ catch (error) {
195
+ projection.failed += 1;
196
+ projection.lastFailure = failureCodeOf(error);
197
+ }
198
+ finally {
199
+ if (projection.queued > 0)
200
+ projection.queued -= 1;
201
+ }
202
+ }
203
+ if (exporter.shutdown) {
204
+ const shutdown = await invokeWithin((signal) => exporter.shutdown({ signal }), this.options.shutdownTimeoutMs ?? 5_000);
205
+ if (shutdown.status === "timed_out") {
206
+ projection.shutdownTimedOut = true;
207
+ projection.failed += 1;
208
+ projection.lastFailure = "timeout";
209
+ }
210
+ else if (shutdown.status === "rejected") {
211
+ projection.failed += 1;
212
+ projection.lastFailure = failureCodeOf(shutdown.reason);
213
+ }
214
+ }
215
+ return projection;
216
+ }
217
+ }
218
+ function telemetryConfigurationMatches(persisted, policy, endpointOrigin) {
219
+ return (persisted.mode === policy.mode &&
220
+ persisted.endpointOrigin === endpointOrigin &&
221
+ persisted.contentLevel === policy.contentLevel &&
222
+ persisted.allowedFields.length === policy.allowedFields.length &&
223
+ persisted.allowedFields.every((field, index) => field === policy.allowedFields[index]));
224
+ }
225
+ /** 写入 Run start 的安全配置快照:只保留 endpoint origin,不落 query 或凭据。 */
226
+ export function createTelemetryConfigurationFact(policy, configuredAt) {
227
+ const normalized = normalizePolicy(policy);
228
+ return validateTelemetryConfigurationFact({
229
+ schemaVersion: 1,
230
+ mode: normalized.mode,
231
+ contentLevel: normalized.contentLevel,
232
+ allowedFields: normalized.allowedFields,
233
+ configuredAt,
234
+ ...(normalized.endpoint ? { endpointOrigin: endpointOriginOf(normalized.endpoint) } : {}),
235
+ });
236
+ }
237
+ /** 从 canonical Run Facts 重建默认开启的本地观测视图。 */
238
+ export function projectLocalObservability(records, options = {}) {
239
+ const ordered = orderedFacts(records);
240
+ const events = ordered.flatMap((record) => {
241
+ if (record.kind !== "event" || !isRecord(record.payload))
242
+ return [];
243
+ const event = record.payload.event;
244
+ return isRecord(event) && typeof event.type === "string"
245
+ ? [{ sequence: record.sequence, event }]
246
+ : [];
247
+ });
248
+ const startedTurns = events.filter(({ event }) => event.type === "agent_start").length;
249
+ const completedTurns = events.filter(({ event }) => event.type === "turn_end").length;
250
+ const startedCalls = events.filter(({ event }) => event.type === "tool_call").length;
251
+ const callResults = events.filter(({ event }) => event.type === "tool_result");
252
+ const telemetry = telemetryStateFromFacts(ordered);
253
+ const delivery = options.telemetryDelivery ?? emptyDelivery(telemetry);
254
+ const runDurationMs = terminalDurationMs(ordered);
255
+ const callDurationMs = events.reduce((total, { event }) => {
256
+ if (event.type !== "tool_execution_evidence" || !isRecord(event.execution))
257
+ return total;
258
+ const durationMs = event.execution.durationMs;
259
+ return typeof durationMs === "number" && durationMs >= 0 ? total + durationMs : total;
260
+ }, 0);
261
+ const tools = projectToolCallLifecycles(events.flatMap(({ event }) => (event.type === "tool_lifecycle" ? [event] : [])));
262
+ const authorizedScopes = ordered.flatMap((record) => {
263
+ if (record.kind !== "telemetry_consent")
264
+ return [];
265
+ const consent = validateTelemetryConsentForRecords(record.payload, record, ordered);
266
+ return [
267
+ {
268
+ runId: consent.runId,
269
+ consentId: consent.consentId,
270
+ scopeFingerprint: consent.scopeFingerprint,
271
+ kind: consent.kind,
272
+ targetOrigin: consent.targetOrigin,
273
+ contentLevel: consent.contentLevel,
274
+ allowedFields: [...new Set(consent.allowedFields)].sort(),
275
+ ...(consent.throughSequence === undefined
276
+ ? {}
277
+ : { throughSequence: consent.throughSequence }),
278
+ ...(consent.factPrefixFingerprint === undefined
279
+ ? {}
280
+ : { factPrefixFingerprint: consent.factPrefixFingerprint }),
281
+ ...(consent.retentionPurpose === undefined
282
+ ? {}
283
+ : { retentionPurpose: consent.retentionPurpose }),
284
+ ...(consent.revocationMethod === undefined
285
+ ? {}
286
+ : { revocationMethod: consent.revocationMethod }),
287
+ grantedAt: consent.grantedAt,
288
+ },
289
+ ];
290
+ });
291
+ return {
292
+ schemaVersion: 1,
293
+ localEnabled: true,
294
+ derivedFromSequence: ordered.at(-1)?.sequence ?? 0,
295
+ run: {
296
+ status: options.runStatus ?? statusFromFacts(ordered),
297
+ resumable: options.resumable ?? false,
298
+ ...(options.operationState ? { operationState: options.operationState } : {}),
299
+ ...(runDurationMs === undefined ? {} : { durationMs: runDurationMs }),
300
+ },
301
+ turns: {
302
+ started: startedTurns,
303
+ completed: completedTurns,
304
+ active: Math.max(0, startedTurns - completedTurns),
305
+ },
306
+ calls: {
307
+ started: startedCalls,
308
+ completed: callResults.length,
309
+ failed: callResults.filter(({ event }) => event.isError === true).length,
310
+ active: Math.max(0, startedCalls - callResults.length),
311
+ durationMs: callDurationMs,
312
+ },
313
+ tools,
314
+ errors: events.flatMap(({ sequence, event }) => event.type === "error" &&
315
+ typeof event.message === "string" &&
316
+ typeof event.fatal === "boolean"
317
+ ? [{ sequence, message: event.message, fatal: event.fatal }]
318
+ : []),
319
+ context: options.context ?? {
320
+ budgets: events.filter(({ event }) => event.type === "context_budget_resolved").length,
321
+ compactions: events.filter(({ event }) => event.type === "context_compacted").length,
322
+ failures: events.filter(({ event }) => event.type === "context_compaction_failed" || event.type === "context_lifecycle_failed").length,
323
+ },
324
+ artifacts: options.artifacts ?? {
325
+ stored: events.filter(({ event }) => event.type === "artifact_created" && event.status === "stored").length,
326
+ blocked: events.filter(({ event }) => event.type === "artifact_created" && event.status === "blocked").length,
327
+ },
328
+ sharedState: { pendingControls: options.pendingControls ?? 0 },
329
+ recovery: {
330
+ resumable: options.resumable ?? false,
331
+ ...(options.operationState ? { operationState: options.operationState } : {}),
332
+ },
333
+ telemetry: {
334
+ ...delivery,
335
+ mode: telemetry.mode,
336
+ contentLevel: telemetry.contentLevel,
337
+ allowedFields: telemetry.allowedFields,
338
+ ...(telemetry.endpointOrigin ? { endpointOrigin: telemetry.endpointOrigin } : {}),
339
+ source: telemetry.source,
340
+ deliverySemantics: "best_effort_handoff_not_delivery",
341
+ authorizedScopes,
342
+ },
343
+ };
344
+ }
345
+ function terminalDurationMs(records) {
346
+ const terminal = [...records]
347
+ .reverse()
348
+ .find((record) => record.kind === "finish" || record.kind === "pause");
349
+ if (!terminal || !isRecord(terminal.payload) || !isRecord(terminal.payload.metrics)) {
350
+ return undefined;
351
+ }
352
+ const durationMs = terminal.payload.metrics.durationMs;
353
+ return typeof durationMs === "number" && durationMs >= 0 ? durationMs : undefined;
354
+ }
355
+ function normalizePolicy(policy) {
356
+ if (!["DISABLED", "FEEDBACK_ONLY", "FULL"].includes(policy.mode)) {
357
+ throw new CoreMindError("run_state_corrupt", `未知 Telemetry mode:${String(policy.mode)}`);
358
+ }
359
+ const contentLevel = policy.contentLevel ?? "metrics_only";
360
+ if (contentLevel !== "metrics_only" && contentLevel !== "content") {
361
+ throw new CoreMindError("run_state_corrupt", `未知 Telemetry content level:${contentLevel}`);
362
+ }
363
+ return {
364
+ mode: policy.mode,
365
+ contentLevel,
366
+ allowedFields: [...new Set(policy.allowedFields ?? [])].sort(),
367
+ ...(policy.endpoint ? { endpoint: policy.endpoint } : {}),
368
+ };
369
+ }
370
+ function emptyDelivery(policy) {
371
+ return {
372
+ mode: policy.mode,
373
+ exporterLoaded: false,
374
+ ...(policy.endpointOrigin ? { endpointOrigin: policy.endpointOrigin } : {}),
375
+ contentLevel: policy.contentLevel ?? "metrics_only",
376
+ allowedFields: [...(policy.allowedFields ?? [])],
377
+ queued: 0,
378
+ handedOff: 0,
379
+ failed: 0,
380
+ dropped: 0,
381
+ duplicates: 0,
382
+ shutdownTimedOut: false,
383
+ };
384
+ }
385
+ function telemetryStateFromFacts(records) {
386
+ const changed = [...records]
387
+ .reverse()
388
+ .find((record) => record.kind === "telemetry_configuration");
389
+ if (changed) {
390
+ const policy = validateTelemetryConfigurationFact(changed.payload);
391
+ return {
392
+ ...policy,
393
+ source: "configured",
394
+ effectiveFromSequence: changed.sequence,
395
+ };
396
+ }
397
+ const start = records.find((record) => record.kind === "start");
398
+ if (!start || !isRecord(start.payload) || !("telemetry" in start.payload)) {
399
+ return {
400
+ mode: "DISABLED",
401
+ contentLevel: "metrics_only",
402
+ allowedFields: [],
403
+ source: "legacy_default",
404
+ effectiveFromSequence: 1,
405
+ };
406
+ }
407
+ const policy = validateTelemetryConfigurationFact(start.payload.telemetry);
408
+ return {
409
+ ...policy,
410
+ source: policy.mode === "DISABLED" ? "default" : "configured",
411
+ effectiveFromSequence: start.sequence,
412
+ };
413
+ }
414
+ function consentFailureFor(records, policy, endpointOrigin) {
415
+ const canonical = canonicalAuthorizationRecords(records);
416
+ const consents = canonical.flatMap((record) => {
417
+ if (record.kind !== "telemetry_consent")
418
+ return [];
419
+ try {
420
+ return [validateTelemetryConsentForRecords(record.payload, record, canonical)];
421
+ }
422
+ catch {
423
+ return [];
424
+ }
425
+ });
426
+ if (policy.mode === "FEEDBACK_ONLY" &&
427
+ !consents.some((consent) => consent.kind === "feedback" &&
428
+ consent.targetOrigin === endpointOrigin &&
429
+ consent.contentLevel === policy.contentLevel &&
430
+ Number.isInteger(consent.throughSequence))) {
431
+ return "feedback_consent_missing";
432
+ }
433
+ if (policy.contentLevel === "content" &&
434
+ !consents.some((consent) => consent.kind === "content" &&
435
+ consent.targetOrigin === endpointOrigin &&
436
+ consent.contentLevel === "content" &&
437
+ policy.allowedFields.every((field) => consent.allowedFields.includes(field)))) {
438
+ return "content_consent_missing";
439
+ }
440
+ return undefined;
441
+ }
442
+ function eligibleRecords(records, policy, endpointOrigin) {
443
+ const source = records.filter((record) => record.kind !== "telemetry_consent" && record.kind !== "telemetry_configuration");
444
+ if (policy.mode === "FULL") {
445
+ const effectiveFromSequence = telemetryStateFromFacts(canonicalAuthorizationRecords(records)).effectiveFromSequence;
446
+ return source.filter((record) => record.sequence >= effectiveFromSequence);
447
+ }
448
+ const canonical = canonicalAuthorizationRecords(records);
449
+ const throughSequence = records
450
+ .flatMap((record) => {
451
+ if (record.kind !== "telemetry_consent")
452
+ return [];
453
+ try {
454
+ return [validateTelemetryConsentForRecords(record.payload, record, canonical)];
455
+ }
456
+ catch {
457
+ return [];
458
+ }
459
+ })
460
+ .filter((consent) => consent.kind === "feedback" &&
461
+ consent.targetOrigin === endpointOrigin &&
462
+ consent.contentLevel === policy.contentLevel)
463
+ .reduce((highest, consent) => Math.max(highest, consent.throughSequence ?? 0), 0);
464
+ return source.filter((record) => record.sequence <= throughSequence);
465
+ }
466
+ function projectExportRecord(record, policy, redact) {
467
+ const event = traceEventOf(record);
468
+ const fields = metricsFields(record, event);
469
+ if (policy.contentLevel === "content") {
470
+ for (const field of policy.allowedFields) {
471
+ const value = contentField(record, event, field);
472
+ if (value !== undefined)
473
+ fields[field] = value;
474
+ }
475
+ }
476
+ try {
477
+ const redacted = (redact ?? ((value) => redactSensitiveValue(value, { redactBodies: false })))(fields);
478
+ if (!isRecord(redacted))
479
+ throw new Error("脱敏器没有返回对象");
480
+ return {
481
+ identity: identityOf(record),
482
+ runId: record.runId,
483
+ sequence: record.sequence,
484
+ timestamp: record.timestamp,
485
+ kind: record.kind,
486
+ ...(event ? { eventType: String(event.type) } : {}),
487
+ fields: redacted,
488
+ };
489
+ }
490
+ catch (error) {
491
+ throw new TelemetryExporterError("redaction_failed", `Telemetry 脱敏失败:${error instanceof Error ? error.message : String(error)}`);
492
+ }
493
+ }
494
+ function metricsFields(record, event) {
495
+ const fields = {};
496
+ if (event) {
497
+ for (const key of [
498
+ "status",
499
+ "fatal",
500
+ "isError",
501
+ "durationMs",
502
+ "tokens",
503
+ "inputTokens",
504
+ "outputTokens",
505
+ "cacheReadTokens",
506
+ "cacheWriteTokens",
507
+ "beforeTokens",
508
+ "afterTokens",
509
+ "removedMessages",
510
+ "sizeBytes",
511
+ "attempt",
512
+ ]) {
513
+ const value = event[key];
514
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "string") {
515
+ fields[key] = value;
516
+ }
517
+ }
518
+ }
519
+ if ((record.kind === "pause" || record.kind === "finish") && isRecord(record.payload)) {
520
+ const outcome = record.payload.outcome;
521
+ if (isRecord(outcome) && typeof outcome.status === "string")
522
+ fields.outcomeStatus = outcome.status;
523
+ const metrics = record.payload.metrics;
524
+ if (isRecord(metrics) && typeof metrics.durationMs === "number") {
525
+ fields.durationMs = metrics.durationMs;
526
+ }
527
+ }
528
+ return fields;
529
+ }
530
+ function contentField(record, event, field) {
531
+ if (field.startsWith("start.") && record.kind === "start" && isRecord(record.payload)) {
532
+ return valueAtPath(record.payload, field.slice("start.".length));
533
+ }
534
+ if (!event || !field.startsWith("event."))
535
+ return undefined;
536
+ const [, eventType, ...path] = field.split(".");
537
+ return event.type === eventType ? valueAtPath(event, path.join(".")) : undefined;
538
+ }
539
+ function valueAtPath(value, path) {
540
+ let current = value;
541
+ for (const segment of path.split(".")) {
542
+ if (!isRecord(current))
543
+ return undefined;
544
+ current = current[segment];
545
+ }
546
+ return current;
547
+ }
548
+ function orderedFacts(records) {
549
+ const ordered = [...records].sort((left, right) => left.sequence - right.sequence);
550
+ const runId = ordered[0]?.runId;
551
+ for (const [index, record] of ordered.entries()) {
552
+ if (record.runId !== runId || record.sequence !== index + 1) {
553
+ throw new CoreMindError("run_state_corrupt", "Run Facts 身份或 sequence 不连续");
554
+ }
555
+ }
556
+ return ordered;
557
+ }
558
+ function statusFromFacts(records) {
559
+ const terminal = [...records]
560
+ .reverse()
561
+ .find((record) => record.kind === "finish" || record.kind === "pause");
562
+ return terminal?.kind === "finish"
563
+ ? "finished"
564
+ : terminal?.kind === "pause"
565
+ ? "paused"
566
+ : "interrupted";
567
+ }
568
+ function endpointOriginOf(endpoint) {
569
+ if (!endpoint)
570
+ throw new TelemetryExporterError("exporter_unavailable", "Telemetry endpoint 未配置");
571
+ try {
572
+ const parsed = new URL(endpoint);
573
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:")
574
+ throw new Error("协议不受支持");
575
+ return parsed.origin;
576
+ }
577
+ catch (error) {
578
+ throw new TelemetryExporterError("exporter_unavailable", `Telemetry endpoint 无效:${error instanceof Error ? error.message : String(error)}`);
579
+ }
580
+ }
581
+ function identityOf(record) {
582
+ return `${record.runId}:${record.sequence}:${record.eventId ?? record.kind}`;
583
+ }
584
+ function traceEventOf(record) {
585
+ if (record.kind !== "event" || !isRecord(record.payload) || !isRecord(record.payload.event)) {
586
+ return undefined;
587
+ }
588
+ return record.payload.event;
589
+ }
590
+ export function isTelemetryConsentFact(value) {
591
+ return (isRecord(value) &&
592
+ value.schemaVersion === 1 &&
593
+ typeof value.scopeFingerprint === "string" &&
594
+ isNonBlankString(value.runId) &&
595
+ isNonBlankString(value.consentId) &&
596
+ (value.kind === "feedback" || value.kind === "content") &&
597
+ typeof value.targetOrigin === "string" &&
598
+ isEndpointOrigin(value.targetOrigin) &&
599
+ (value.contentLevel === "metrics_only" || value.contentLevel === "content") &&
600
+ Array.isArray(value.allowedFields) &&
601
+ isCanonicalStringList(value.allowedFields) &&
602
+ (value.throughSequence === undefined ||
603
+ (Number.isInteger(value.throughSequence) && Number(value.throughSequence) >= 0)) &&
604
+ (value.factPrefixFingerprint === undefined || isSha256(value.factPrefixFingerprint)) &&
605
+ (value.retentionPurpose === undefined || isNonBlankString(value.retentionPurpose)) &&
606
+ (value.revocationMethod === undefined || isNonBlankString(value.revocationMethod)) &&
607
+ isNonBlankString(value.grantedAt) &&
608
+ !Number.isNaN(Date.parse(value.grantedAt)) &&
609
+ (value.kind !== "feedback" ||
610
+ (Number.isInteger(value.throughSequence) && isSha256(value.factPrefixFingerprint))) &&
611
+ (value.kind !== "content" ||
612
+ (value.contentLevel === "content" &&
613
+ isNonBlankString(value.retentionPurpose) &&
614
+ isNonBlankString(value.revocationMethod))) &&
615
+ value.scopeFingerprint ===
616
+ telemetryConsentScopeFingerprint({
617
+ runId: value.runId,
618
+ kind: value.kind,
619
+ targetOrigin: value.targetOrigin,
620
+ contentLevel: value.contentLevel,
621
+ allowedFields: value.allowedFields,
622
+ ...(value.throughSequence === undefined
623
+ ? {}
624
+ : { throughSequence: value.throughSequence }),
625
+ ...(value.factPrefixFingerprint === undefined
626
+ ? {}
627
+ : { factPrefixFingerprint: value.factPrefixFingerprint }),
628
+ ...(value.retentionPurpose === undefined
629
+ ? {}
630
+ : { retentionPurpose: value.retentionPurpose }),
631
+ ...(value.revocationMethod === undefined
632
+ ? {}
633
+ : { revocationMethod: value.revocationMethod }),
634
+ }));
635
+ }
636
+ function isEndpointOrigin(value) {
637
+ try {
638
+ const parsed = new URL(value);
639
+ return (parsed.protocol === "https:" || parsed.protocol === "http:") && parsed.origin === value;
640
+ }
641
+ catch {
642
+ return false;
643
+ }
644
+ }
645
+ export function validateTelemetryConsentFact(value) {
646
+ if (!isTelemetryConsentFact(value)) {
647
+ throw new CoreMindError("run_state_corrupt", "Telemetry consent Fact 已损坏");
648
+ }
649
+ return structuredClone(value);
650
+ }
651
+ /** 在写入前验证 consent 只覆盖同一 Run 已经 durable 的 Fact 高水位。 */
652
+ export function validateTelemetryConsentBinding(value, persistedRecords) {
653
+ const ordered = orderedFacts(persistedRecords);
654
+ const runId = ordered[0]?.runId;
655
+ if (!runId)
656
+ throw new CoreMindError("run_state_corrupt", "Telemetry consent 缺少目标 Run");
657
+ return validateTelemetryConsentForRecords(value, {
658
+ version: 1,
659
+ runId,
660
+ sequence: ordered.length + 1,
661
+ timestamp: new Date(0).toISOString(),
662
+ kind: "telemetry_consent",
663
+ payload: value,
664
+ }, ordered);
665
+ }
666
+ /** 把 feedback 授权绑定到同一 Run 当时已持久化的精确 Fact 前缀。 */
667
+ export function telemetryFactPrefixFingerprint(records, throughSequence) {
668
+ const ordered = orderedFacts(records);
669
+ if (!Number.isInteger(throughSequence) ||
670
+ throughSequence < 1 ||
671
+ throughSequence > ordered.length) {
672
+ throw new CoreMindError("run_state_corrupt", "Telemetry feedback 前缀超出已持久化 Fact 高水位");
673
+ }
674
+ return createHash("sha256")
675
+ .update(canonicalJson(ordered.slice(0, throughSequence)), "utf8")
676
+ .digest("hex");
677
+ }
678
+ function validateTelemetryConsentForRecords(value, consentRecord, records) {
679
+ const consent = validateTelemetryConsentFact(value);
680
+ if (consent.runId !== consentRecord.runId) {
681
+ throw new CoreMindError("run_state_corrupt", "Telemetry consent 绑定了不同 Run");
682
+ }
683
+ if (consent.kind === "feedback") {
684
+ const throughSequence = consent.throughSequence;
685
+ if (throughSequence >= consentRecord.sequence) {
686
+ throw new CoreMindError("run_state_corrupt", "Telemetry feedback consent 不能预授权未来 Fact");
687
+ }
688
+ if (consent.factPrefixFingerprint !== telemetryFactPrefixFingerprint(records, throughSequence)) {
689
+ throw new CoreMindError("run_state_corrupt", "Telemetry feedback Fact 前缀指纹不匹配");
690
+ }
691
+ }
692
+ return consent;
693
+ }
694
+ export function validateTelemetryConfigurationFact(value) {
695
+ if (!isRecord(value)) {
696
+ throw new CoreMindError("run_state_corrupt", "Telemetry 配置 Fact 已损坏");
697
+ }
698
+ const mode = value.mode;
699
+ const contentLevel = value.contentLevel;
700
+ const allowedFields = value.allowedFields;
701
+ const endpointOrigin = value.endpointOrigin;
702
+ if (value.schemaVersion !== 1 ||
703
+ !(mode === "DISABLED" || mode === "FEEDBACK_ONLY" || mode === "FULL") ||
704
+ !(contentLevel === "metrics_only" || contentLevel === "content") ||
705
+ !isCanonicalStringList(allowedFields) ||
706
+ !isNonBlankString(value.configuredAt) ||
707
+ Number.isNaN(Date.parse(value.configuredAt)) ||
708
+ (endpointOrigin !== undefined &&
709
+ (typeof endpointOrigin !== "string" || !isEndpointOrigin(endpointOrigin))) ||
710
+ (mode !== "DISABLED" && typeof endpointOrigin !== "string")) {
711
+ throw new CoreMindError("run_state_corrupt", "Telemetry 配置 Fact 已损坏");
712
+ }
713
+ return structuredClone(value);
714
+ }
715
+ /**
716
+ * 构造供 Core 校验的出站策略收据;真实 DNS/TLS 与网络策略必须由受信任 Adapter 执行。
717
+ */
718
+ export function createTelemetryEgressAuthorization(input) {
719
+ if (!isEndpointOrigin(input.targetOrigin) ||
720
+ input.resolvedAddresses.length === 0 ||
721
+ input.resolvedAddresses.some((address) => isIP(address) === 0)) {
722
+ throw new Error("Telemetry egress authorization 缺少合法 origin 或解析地址");
723
+ }
724
+ const value = {
725
+ schemaVersion: 1,
726
+ targetOrigin: input.targetOrigin,
727
+ resolvedAddresses: [...new Set(input.resolvedAddresses)].sort(),
728
+ redirectPolicy: "deny",
729
+ proxyPolicy: "deny",
730
+ tlsPolicy: "strict",
731
+ };
732
+ return {
733
+ ...value,
734
+ policyFingerprint: createHash("sha256").update(canonicalJson(value), "utf8").digest("hex"),
735
+ };
736
+ }
737
+ function validateTelemetryEgressAuthorization(value, endpointOrigin) {
738
+ if (!isRecord(value))
739
+ throw new Error("缺少 Telemetry egress authorization");
740
+ const expected = createTelemetryEgressAuthorization({
741
+ targetOrigin: endpointOrigin,
742
+ resolvedAddresses: Array.isArray(value.resolvedAddresses)
743
+ ? value.resolvedAddresses.filter((item) => isNonBlankString(item))
744
+ : [],
745
+ });
746
+ if (value.schemaVersion !== 1 ||
747
+ value.targetOrigin !== endpointOrigin ||
748
+ !Array.isArray(value.resolvedAddresses) ||
749
+ value.resolvedAddresses.length === 0 ||
750
+ !isCanonicalStringList(value.resolvedAddresses) ||
751
+ !value.resolvedAddresses.every((address) => isIP(address) !== 0) ||
752
+ value.redirectPolicy !== "deny" ||
753
+ value.proxyPolicy !== "deny" ||
754
+ value.tlsPolicy !== "strict" ||
755
+ value.policyFingerprint !== expected.policyFingerprint) {
756
+ throw new Error("Telemetry egress authorization 与配置目标不一致");
757
+ }
758
+ return structuredClone(value);
759
+ }
760
+ function failureCodeOf(error) {
761
+ return error instanceof TelemetryExporterError ? error.code : "exporter_failed";
762
+ }
763
+ function invokeBeforeDeadline(invoke, deadline) {
764
+ return invokeWithin(invoke, Math.max(0, deadline - Date.now()));
765
+ }
766
+ async function invokeWithin(invoke, timeoutMs) {
767
+ const controller = new AbortController();
768
+ let timer;
769
+ try {
770
+ return await Promise.race([
771
+ Promise.resolve()
772
+ .then(() => invoke(controller.signal))
773
+ .then((value) => ({ status: "fulfilled", value }), (reason) => ({ status: "rejected", reason })),
774
+ new Promise((resolve) => {
775
+ timer = setTimeout(() => {
776
+ controller.abort();
777
+ resolve({ status: "timed_out" });
778
+ }, Math.max(0, timeoutMs));
779
+ }),
780
+ ]);
781
+ }
782
+ finally {
783
+ if (timer)
784
+ clearTimeout(timer);
785
+ }
786
+ }
787
+ function canonicalAuthorizationRecords(records) {
788
+ const byIdentity = new Map();
789
+ for (const record of records) {
790
+ const identity = identityOf(record);
791
+ const previous = byIdentity.get(identity);
792
+ if (previous && canonicalJson(previous) !== canonicalJson(record)) {
793
+ throw new CoreMindError("run_state_corrupt", "Telemetry 输入包含身份相同但内容冲突的 Fact");
794
+ }
795
+ byIdentity.set(identity, record);
796
+ }
797
+ return orderedFacts([...byIdentity.values()]);
798
+ }
799
+ function isCanonicalStringList(value) {
800
+ if (!Array.isArray(value) || !value.every((item) => isNonBlankString(item)))
801
+ return false;
802
+ const canonical = [...new Set(value)].sort();
803
+ return (canonical.length === value.length && canonical.every((item, index) => item === value[index]));
804
+ }
805
+ function isSha256(value) {
806
+ return typeof value === "string" && /^[a-f0-9]{64}$/u.test(value);
807
+ }
808
+ function isNonBlankString(value) {
809
+ return typeof value === "string" && value.trim().length > 0;
810
+ }
811
+ function isRecord(value) {
812
+ return value !== null && typeof value === "object" && !Array.isArray(value);
813
+ }
814
+ //# sourceMappingURL=observability.js.map