bailinghub 0.9.2 → 0.9.3

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 (78) hide show
  1. package/README.en.md +6 -6
  2. package/README.md +6 -6
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/CHANGELOG.en.md +12 -1
  5. package/docs/CHANGELOG.md +12 -1
  6. package/docs/CORE_RELIABILITY.en.md +22 -2
  7. package/docs/CORE_RELIABILITY.md +22 -2
  8. package/docs/IMPLEMENTATION_STATUS.en.md +19 -15
  9. package/docs/IMPLEMENTATION_STATUS.md +19 -15
  10. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  11. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  12. package/docs/OPERATIONS.en.md +13 -0
  13. package/docs/OPERATIONS.md +12 -0
  14. package/docs/README.en.md +3 -1
  15. package/docs/README.md +3 -1
  16. package/docs/RELEASE_NOTES_v0.9.3.en.md +51 -0
  17. package/docs/RELEASE_NOTES_v0.9.3.md +51 -0
  18. package/docs/TOOLS_DESIGN.md +1 -0
  19. package/docs/UPGRADE_v0.9.3.en.md +63 -0
  20. package/docs/UPGRADE_v0.9.3.md +63 -0
  21. package/package.json +1 -1
  22. package/scripts/check-doc-links.mjs +2 -0
  23. package/scripts/check-image-tags.sh +1 -1
  24. package/scripts/check-release-consistency.test.mjs +2 -2
  25. package/scripts/install.sh +1 -1
  26. package/scripts/publish-images.sh +1 -1
  27. package/scripts/release-audit.mjs +4 -0
  28. package/scripts/verify-github-repo.mjs +4 -0
  29. package/security/dependency-audit-exceptions.json +1 -1
  30. package/sql/067_delivery_dlq_replay.sql +10 -0
  31. package/sql/README.en.md +6 -0
  32. package/sql/README.md +6 -0
  33. package/src/adapters/llm/file.test.ts +59 -0
  34. package/src/adapters/llm/file.ts +11 -4
  35. package/src/app/agent-tool-invocations.test.ts +3 -1
  36. package/src/app/approval-continuations.test.ts +27 -1
  37. package/src/app/approval-continuations.ts +44 -3
  38. package/src/app/channels-attachments.test.ts +63 -0
  39. package/src/app/channels.ts +7 -4
  40. package/src/app/delivery-dlq-replay.mysql.test.ts +139 -0
  41. package/src/app/delivery-dlq-replay.test.ts +75 -0
  42. package/src/app/delivery-dlq-replay.ts +41 -0
  43. package/src/app/delivery.ts +3 -2
  44. package/src/app/kernel-notification-lifecycle.test.ts +49 -0
  45. package/src/app/kernel.ts +9 -0
  46. package/src/app/notification-outbound.test.ts +53 -0
  47. package/src/app/operational-metrics.test.ts +37 -1
  48. package/src/app/operational-metrics.ts +25 -2
  49. package/src/app/outbound.ts +13 -2
  50. package/src/app/runtime-lifecycle.test.ts +89 -0
  51. package/src/app/runtime-lifecycle.ts +20 -18
  52. package/src/app/tool-approvals.ts +2 -1
  53. package/src/core/contracts/delivery-replay.ts +41 -0
  54. package/src/core/contracts/tools-idempotency.test.ts +121 -5
  55. package/src/core/contracts/tools.ts +21 -11
  56. package/src/core/contracts/types.ts +2 -0
  57. package/src/core/observability/openmetrics.test.ts +28 -0
  58. package/src/core/observability/openmetrics.ts +91 -0
  59. package/src/core/platform/http-body.test.ts +185 -0
  60. package/src/core/platform/http-body.ts +58 -0
  61. package/src/core/runtime/finish-runtime.test.ts +2 -0
  62. package/src/core/runtime/finish-runtime.ts +10 -7
  63. package/src/core/runtime/notification-background-work.test.ts +50 -0
  64. package/src/core/runtime/notification-background-work.ts +101 -0
  65. package/src/core/state/delivery-replay.ts +19 -0
  66. package/src/core/state/state-codec.ts +1 -0
  67. package/src/core/state/state-contracts.ts +3 -0
  68. package/src/infrastructure/config/config-delivery-dlq-ledger.ts +36 -10
  69. package/src/infrastructure/config/configstore.ts +2 -1
  70. package/src/infrastructure/state/state-jsonl.ts +16 -1
  71. package/src/infrastructure/state/state-mysql.ts +27 -0
  72. package/src/modules/usage/background-work.test.ts +28 -0
  73. package/src/modules/usage/background-work.ts +43 -7
  74. package/src/modules/usage/billing-reconciliation.test.ts +16 -2
  75. package/src/modules/usage/billing-repository.ts +9 -0
  76. package/src/modules/usage/maintenance.test.ts +18 -2
  77. package/src/modules/usage/maintenance.ts +8 -0
  78. package/src/routes/admin-runtime.ts +14 -0
@@ -4,6 +4,7 @@ import { effectiveToolRateLimit, type RateLimitRequest, type RateLimitDecision }
4
4
  // 中枢只做 reach(白名单/风险闸/限流/签名/审计);authority(这个人能不能做)永远由业务侧验签后裁决。
5
5
  import { createHash, createHmac } from 'node:crypto';
6
6
  import { AgentTaskControlError } from '../runtime/agent-task-control';
7
+ import { readResponseBody, truncateUtf8 } from '../platform/http-body';
7
8
  import type { ToolProvider } from './types';
8
9
  import { schemaAtPath, schemaTypes, valueMatchesSchemaType, type ToolConfirmCondition, type ToolDefinition } from './tool-definition';
9
10
  import { toolSummary } from './tool-definition';
@@ -219,18 +220,17 @@ function escapeRegExp(s: string): string {
219
220
  */
220
221
  function modelFacingToolResponse(fullText: string, status: number, truncateBytes: number, contentType: string): string {
221
222
  const limit = Math.max(0, truncateBytes);
222
- if (status >= 200 && status < 300) return fullText.slice(0, limit);
223
- if (status === 0) return fullText.slice(0, limit);
223
+ if (status >= 200 && status < 300) return truncateUtf8(fullText, limit);
224
+ if (status === 0) return truncateUtf8(fullText, limit);
224
225
 
225
226
  const looksLikeHtml = /text\/html/i.test(contentType)
226
227
  || /^\s*(?:<!doctype\s+html|<html\b)/i.test(fullText);
227
228
  if (looksLikeHtml) {
228
- return `HTTP ${status}:业务工具返回 HTML 错误页(${fullText.length} 字符)。完整响应已保留在审计记录中。`
229
- .slice(0, limit);
229
+ return truncateUtf8(`HTTP ${status}:业务工具返回 HTML 错误页(${fullText.length} 字符)。响应按独立预算保留在审计记录中。`, limit);
230
230
  }
231
231
 
232
- const errorText = fullText.trim().slice(0, Math.min(limit, 2048));
233
- return (errorText ? `HTTP ${status}:${errorText}` : `HTTP ${status} 空响应`).slice(0, limit);
232
+ const errorText = truncateUtf8(fullText.trim(), Math.min(limit, 2048));
233
+ return truncateUtf8(errorText ? `HTTP ${status}:${errorText}` : `HTTP ${status} 空响应`, limit);
234
234
  }
235
235
 
236
236
  // ---- 限流(进程内滑窗,三层:每任务 max_calls 由调用方计数 / 每工具 ACC execution.rate_limit / 工具源总闸)----
@@ -278,6 +278,8 @@ export const TOOL_INLINE_MAX = 12;
278
278
  * 真实字节数始终另记 resp_bytes/args_bytes,超封顶记 *_truncated=true,绝不静默丢。64KB 覆盖绝大多数业务响应。
279
279
  */
280
280
  export const AUDIT_MAX_BYTES = 65536;
281
+ /** Independent HTTP body budget; the application uses this fixed default, not an ACC field. */
282
+ export const TOOL_RESPONSE_MAX_BYTES = 5 * 1024 * 1024;
281
283
 
282
284
  /** 大脑可用的工具运行时:清单(喂 LLM)+ 受治理的调用句柄。由 server 在派发时装配并注入 AdapterContext。 */
283
285
  export interface ToolRuntime {
@@ -427,6 +429,8 @@ export interface ToolRuntimeDeps {
427
429
  jobId: string;
428
430
  clientAppId: string;
429
431
  truncateBytes: number; // 工具结果回流截断(默认 8192)
432
+ /** Trusted runtime assembly only; independent from model/audit view budgets. */
433
+ maxResponseBodyBytes?: number;
430
434
  approvedNote?: string; // 重跑时已批准调用清单提示
431
435
  approvals?: ApprovalDeps; // 不注入 = high/confirm 一律拦
432
436
  /** A trusted assembly supplies these hooks; model parameters cannot create a task or permit. */
@@ -458,6 +462,8 @@ export interface ToolRuntimeDeps {
458
462
  }
459
463
 
460
464
  export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
465
+ const responseMaxBytes = d.maxResponseBodyBytes ?? TOOL_RESPONSE_MAX_BYTES;
466
+ if (!Number.isSafeInteger(responseMaxBytes) || responseMaxBytes <= 0) throw new RangeError('Invalid tool response byte limit');
461
467
  const byName = new Map(d.allowedTools.map((t) => [t.name, t]));
462
468
  const llmTools = d.allowedTools.map((t) => ({
463
469
  type: 'function' as const,
@@ -682,8 +688,9 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
682
688
  // logFull 时入参全量入审计(封顶 AUDIT_MAX_BYTES,超出记 args_truncated;真实字节数 args_bytes 始终记)。
683
689
  const logFull = d.provider.log_payload && !t.sensitive;
684
690
  const argsStr = JSON.stringify(callArgs);
691
+ const argsBytes = Buffer.byteLength(argsStr, 'utf8');
685
692
  const argsLog = logFull
686
- ? { args: argsStr.slice(0, AUDIT_MAX_BYTES), args_bytes: argsStr.length, ...(argsStr.length > AUDIT_MAX_BYTES ? { args_truncated: true } : {}) }
693
+ ? { args: truncateUtf8(argsStr, AUDIT_MAX_BYTES), args_bytes: argsBytes, ...(argsBytes > AUDIT_MAX_BYTES ? { args_truncated: true } : {}) }
687
694
  : { args: JSON.stringify(Object.keys(callArgs)) };
688
695
  await d.audit('tool_call', {
689
696
  provider: d.provider.name, tool: name, scope: t.scope, method: t.method, path: t.path,
@@ -740,6 +747,7 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
740
747
  const started = Date.now();
741
748
  const timeoutMs = t.timeoutMs || d.provider.timeout_ms || 10000; // ACC execution.timeout_ms 单工具覆盖(慢接口放宽),缺省工具源超时
742
749
  let status = 0; let fullText = '';
750
+ let responseBytes = 0;
743
751
  let responseContentType = '';
744
752
  try {
745
753
  const r = await fetch(d.provider.base_url.replace(/\/+$/, '') + pathWithQuery, {
@@ -764,7 +772,9 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
764
772
  });
765
773
  status = r.status;
766
774
  responseContentType = r.headers?.get?.('content-type') ?? '';
767
- fullText = await r.text();
775
+ const responseBody = await readResponseBody(r, responseMaxBytes);
776
+ responseBytes = responseBody.byteLength;
777
+ fullText = new TextDecoder().decode(responseBody);
768
778
  } catch (e) {
769
779
  const error = e instanceof Error && e.name === 'TimeoutError' ? `超时(${timeoutMs}ms)` : String(e);
770
780
  fullText = `调用结果不确定:${error}`;
@@ -809,7 +819,7 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
809
819
  // 回流给模型的:受上下文预算 truncateBytes 截断(与审计留存解耦)
810
820
  const text = modelFacingToolResponse(fullText, status, d.truncateBytes, responseContentType);
811
821
  const ok = status >= 200 && status < 300;
812
- const retText = text || `(HTTP ${status} 空响应)`;
822
+ const retText = text || truncateUtf8(`(HTTP ${status} 空响应)`, d.truncateBytes);
813
823
  if (idemHash && !d.taskControl) {
814
824
  try {
815
825
  await d.idempotency!.recordResponse(name, idemHash, { ok, status, text: retText });
@@ -834,8 +844,8 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
834
844
  }
835
845
  // 审计留存:logFull 记全量响应(封顶 AUDIT_MAX_BYTES,超出记 resp_truncated);resp_bytes 始终记真实字节数。
836
846
  const respLog = logFull
837
- ? { resp: fullText.slice(0, AUDIT_MAX_BYTES), resp_bytes: fullText.length, ...(fullText.length > AUDIT_MAX_BYTES ? { resp_truncated: true } : {}) }
838
- : { resp: `<${fullText.length} bytes>`, resp_bytes: fullText.length };
847
+ ? { resp: truncateUtf8(fullText, AUDIT_MAX_BYTES), resp_bytes: responseBytes, ...(Buffer.byteLength(fullText, 'utf8') > AUDIT_MAX_BYTES ? { resp_truncated: true } : {}) }
848
+ : { resp: `<${responseBytes} bytes>`, resp_bytes: responseBytes };
839
849
  try {
840
850
  await d.audit('tool_result', {
841
851
  tool: name,
@@ -34,6 +34,8 @@ export interface Job {
34
34
  metadata: Record<string, unknown>;
35
35
  /** Core-owned durable queue admissions; ordinary updates must preserve these keys. */
36
36
  approval_continuation_keys?: Record<string, string>;
37
+ /** Permanent DLQ replay admission keys; ordinary updates cannot clear them. */
38
+ delivery_replay_keys?: Record<string, string>;
37
39
  callback_url?: string;
38
40
  // 远端执行器派活相关(含 route 快照:route 之后可能改/删,故落到 job 上);kb_refs=知识检索命中快照(引用来源回流)
39
41
  // user_images/user_audio/user_files=用户原始输入里的媒体 URL 快照(只取用户发的,不含知识库注入资产);多模态适配器据此送模型,rerun 也能复现
@@ -1,6 +1,7 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import test from 'node:test';
3
3
  import { renderOperationalMetrics } from './openmetrics';
4
+ import type { RuntimeMaintenanceMetricsSnapshot } from './openmetrics';
4
5
 
5
6
  test('OpenMetrics renderer: emits fixed low-cardinality families and escapes build labels', () => {
6
7
  const text = renderOperationalMetrics({
@@ -55,3 +56,30 @@ test('OpenMetrics renderer: unavailable optional collectors are explicit and do
55
56
  assert.doesNotMatch(text, /bailinghub_job_records/);
56
57
  assert.doesNotMatch(text, /bailinghub_approvals_pending/);
57
58
  });
59
+
60
+ test('maintenance renderer allows only fixed sources, kinds, phases and page outcomes', () => {
61
+ const known = { kind: 'model-completion', inFlight: 2, completed: 4, failed: 1, oldestPendingAgeMs: 3000,
62
+ lastStartedAt: new Date(1000).toISOString(), lastCompletedAt: null, lastFailedAt: new Date(2000).toISOString() };
63
+ const snapshot: RuntimeMaintenanceMetricsSnapshot = {
64
+ capturedAtMs: 5000,
65
+ usage: { draining: true, drainTimeouts: 2, kinds: [known,
66
+ { ...known, kind: 'PRIVATE_ACCOUNT_PROMPT_TOKEN_ROUTE' }] },
67
+ usageReconciliation: { scanned: 50, settled: 1, deferred: 48, failed: 1, hasMore: true },
68
+ approvalReconciliation: { scanned: 3, completed: 1, pending: 1, failed: 1 },
69
+ usageRetry: { running: false, consecutiveFailures: 1, retryAfterMs: 2500 },
70
+ };
71
+ const text = renderOperationalMetrics({ version: 'test', commit: 'abc', paused: false, queue: { running: 0, waiting: 0 },
72
+ state: { available: false, success: false }, controlPlane: { available: false, success: false },
73
+ maintenance: { available: true, success: true, value: snapshot }, auditWriteFailuresTotal: 0, scrapeDurationSeconds: 0 });
74
+ assert.match(text, /bailinghub_background_work_in_flight\{source="usage",kind="model-completion"\} 2/);
75
+ assert.match(text, /bailinghub_background_work_oldest_pending_age_seconds\{source="usage",kind="model-completion"\} 3/);
76
+ assert.match(text, /bailinghub_background_work_finished_total\{source="usage",kind="model-completion",outcome="failed"\} 1/);
77
+ assert.match(text, /bailinghub_background_work_last_run_age_seconds\{source="usage",kind="model-completion",phase="started"\} 4/);
78
+ assert.match(text, /bailinghub_background_work_last_run_timestamp_seconds\{source="usage",kind="model-completion",phase="completed"\} 0/);
79
+ assert.doesNotMatch(text, /bailinghub_background_work_last_run_age_seconds[^\n]*phase="completed"/);
80
+ assert.match(text, /bailinghub_background_drain_timeouts_total\{source="usage"\} 2/);
81
+ assert.match(text, /bailinghub_maintenance_last_page_records\{kind="usage-reconciliation",outcome="failed"\} 1/);
82
+ assert.match(text, /bailinghub_maintenance_last_page_records\{kind="approval-continuation",outcome="pending"\} 1/);
83
+ assert.match(text, /bailinghub_usage_maintenance_retry_after_seconds 2\.5/);
84
+ assert.doesNotMatch(text, /PRIVATE_ACCOUNT|PROMPT|TOKEN|ROUTE/);
85
+ });
@@ -13,6 +13,23 @@ export interface CollectorResult<T> {
13
13
  value?: T;
14
14
  }
15
15
 
16
+ export interface BackgroundWorkMetricsSnapshot {
17
+ draining?: boolean;
18
+ drainTimeouts?: number;
19
+ kinds: Array<{ kind: string; inFlight: number; completed: number; failed: number; oldestPendingAgeMs: number;
20
+ lastStartedAt: string | null; lastCompletedAt: string | null; lastFailedAt: string | null }>;
21
+ }
22
+
23
+ export interface RuntimeMaintenanceMetricsSnapshot {
24
+ capturedAtMs: number;
25
+ usage?: BackgroundWorkMetricsSnapshot;
26
+ notification?: BackgroundWorkMetricsSnapshot;
27
+ approval?: BackgroundWorkMetricsSnapshot;
28
+ usageReconciliation?: { scanned: number; settled: number; deferred: number; failed: number; hasMore: boolean };
29
+ approvalReconciliation?: { scanned: number; completed: number; pending: number; failed: number };
30
+ usageRetry?: { running: boolean; consecutiveFailures: number; retryAfterMs: number };
31
+ }
32
+
16
33
  export interface OperationalMetricsDocument {
17
34
  version: string;
18
35
  commit: string;
@@ -20,6 +37,7 @@ export interface OperationalMetricsDocument {
20
37
  queue: { running: number; waiting: number };
21
38
  state: CollectorResult<JobOperationalMetricsSnapshot>;
22
39
  controlPlane: CollectorResult<ControlPlaneOperationalMetricsSnapshot>;
40
+ maintenance?: CollectorResult<RuntimeMaintenanceMetricsSnapshot>;
23
41
  auditWriteFailuresTotal: number;
24
42
  scrapeDurationSeconds: number;
25
43
  }
@@ -38,6 +56,75 @@ function family(lines: string[], name: string, help: string, type: 'counter' | '
38
56
  lines.push(...samples);
39
57
  }
40
58
 
59
+ // Never render a caller-supplied kind, phase, status or source as a label.
60
+ const BACKGROUND_KINDS = {
61
+ usage: ['model-completion', 'settlement', 'response-cleanup', 'usage-reconciliation', 'reference-price-refresh'],
62
+ notification: ['callback', 'delivery', 'approval-notification', 'alert', 'delivery-dlq'],
63
+ approval: ['approval-continuation'],
64
+ } as const;
65
+
66
+ function renderMaintenance(lines: string[], snapshot: RuntimeMaintenanceMetricsSnapshot): void {
67
+ const flight: string[] = [], oldest: string[] = [], finished: string[] = [], timestamps: string[] = [], ages: string[] = [];
68
+ const draining: string[] = [], timeouts: string[] = [];
69
+ for (const source of ['usage', 'notification', 'approval'] as const) {
70
+ const value = snapshot[source];
71
+ if (!value) continue;
72
+ if (value.draining !== undefined) draining.push(`bailinghub_background_draining{source="${source}"} ${value.draining ? 1 : 0}`);
73
+ if (value.drainTimeouts !== undefined) timeouts.push(`bailinghub_background_drain_timeouts_total{source="${source}"} ${finite(value.drainTimeouts)}`);
74
+ for (const kind of BACKGROUND_KINDS[source]) {
75
+ const work = value.kinds.find(row => row.kind === kind);
76
+ if (!work) continue;
77
+ const labels = `source="${source}",kind="${kind}"`;
78
+ flight.push(`bailinghub_background_work_in_flight{${labels}} ${finite(work.inFlight)}`);
79
+ oldest.push(`bailinghub_background_work_oldest_pending_age_seconds{${labels}} ${finite(work.oldestPendingAgeMs) / 1000}`);
80
+ for (const outcome of ['completed', 'failed'] as const) {
81
+ finished.push(`bailinghub_background_work_finished_total{${labels},outcome="${outcome}"} ${finite(work[outcome])}`);
82
+ }
83
+ for (const phase of ['started', 'completed', 'failed'] as const) {
84
+ const at = work[phase === 'started' ? 'lastStartedAt' : phase === 'completed' ? 'lastCompletedAt' : 'lastFailedAt'];
85
+ const epoch = at === null ? NaN : Date.parse(at);
86
+ timestamps.push(`bailinghub_background_work_last_run_timestamp_seconds{${labels},phase="${phase}"} ${Number.isFinite(epoch) ? epoch / 1000 : 0}`);
87
+ // Missing history is explicit as timestamp=0; do not invent an age of zero.
88
+ if (Number.isFinite(epoch)) ages.push(`bailinghub_background_work_last_run_age_seconds{${labels},phase="${phase}"} ${Math.max(0, finite(snapshot.capturedAtMs - epoch)) / 1000}`);
89
+ }
90
+ }
91
+ }
92
+ const groups: Array<[string, string, 'counter' | 'gauge', string[]]> = [
93
+ ['bailinghub_background_work_in_flight', 'Accepted process-local continuations currently in flight.', 'gauge', flight],
94
+ ['bailinghub_background_work_oldest_pending_age_seconds', 'Age of the oldest accepted process-local continuation.', 'gauge', oldest],
95
+ ['bailinghub_background_work_finished_total', 'Process-local continuation outcomes, not recipient delivery acknowledgements.', 'counter', finished],
96
+ ['bailinghub_background_work_last_run_timestamp_seconds', 'Last observed start or completion time; zero means never observed.', 'gauge', timestamps],
97
+ ['bailinghub_background_work_last_run_age_seconds', 'Age since the last observed start or completion, omitted when never observed.', 'gauge', ages],
98
+ ['bailinghub_background_draining', 'Whether an owning background tracker has stopped new maintenance admission.', 'gauge', draining],
99
+ ['bailinghub_background_drain_timeouts_total', 'Process-local background drain calls that exhausted their budget.', 'counter', timeouts],
100
+ ];
101
+ for (const [name, help, type, samples] of groups) if (samples.length) family(lines, name, help, type, samples);
102
+
103
+ const progress: string[] = [];
104
+ if (snapshot.usageReconciliation) {
105
+ for (const outcome of ['scanned', 'settled', 'deferred', 'failed'] as const) {
106
+ progress.push(`bailinghub_maintenance_last_page_records{kind="usage-reconciliation",outcome="${outcome}"} ${finite(snapshot.usageReconciliation[outcome])}`);
107
+ }
108
+ family(lines, 'bailinghub_maintenance_last_page_has_more', 'Whether the last usage reconciliation page reached its bounded scan size.', 'gauge', [
109
+ `bailinghub_maintenance_last_page_has_more{kind="usage-reconciliation"} ${snapshot.usageReconciliation.hasMore ? 1 : 0}`,
110
+ ]);
111
+ }
112
+ if (snapshot.approvalReconciliation) {
113
+ for (const outcome of ['scanned', 'completed', 'pending', 'failed'] as const) {
114
+ progress.push(`bailinghub_maintenance_last_page_records{kind="approval-continuation",outcome="${outcome}"} ${finite(snapshot.approvalReconciliation[outcome])}`);
115
+ }
116
+ }
117
+ if (progress.length) family(lines, 'bailinghub_maintenance_last_page_records', 'Aggregate records processed in the latest/current bounded maintenance page, not total persisted backlog.', 'gauge', progress);
118
+ if (snapshot.usageRetry) {
119
+ family(lines, 'bailinghub_usage_maintenance_consecutive_failures', 'Current bounded usage maintenance failure backoff count.', 'gauge', [
120
+ `bailinghub_usage_maintenance_consecutive_failures ${finite(snapshot.usageRetry.consecutiveFailures)}`,
121
+ ]);
122
+ family(lines, 'bailinghub_usage_maintenance_retry_after_seconds', 'Seconds until the current usage maintenance retry backoff expires.', 'gauge', [
123
+ `bailinghub_usage_maintenance_retry_after_seconds ${finite(snapshot.usageRetry.retryAfterMs) / 1000}`,
124
+ ]);
125
+ }
126
+ }
127
+
41
128
  /** Render only fixed, low-cardinality labels. Job, tenant, principal and argument data never enter this document. */
42
129
  export function renderOperationalMetrics(document: OperationalMetricsDocument): string {
43
130
  const lines: string[] = [];
@@ -55,10 +142,12 @@ export function renderOperationalMetrics(document: OperationalMetricsDocument):
55
142
  family(lines, 'bailinghub_metrics_collector_available', 'Whether an optional metrics collector is implemented.', 'gauge', [
56
143
  `bailinghub_metrics_collector_available{collector="state"} ${document.state.available ? 1 : 0}`,
57
144
  `bailinghub_metrics_collector_available{collector="control_plane"} ${document.controlPlane.available ? 1 : 0}`,
145
+ `bailinghub_metrics_collector_available{collector="maintenance"} ${document.maintenance?.available ? 1 : 0}`,
58
146
  ]);
59
147
  family(lines, 'bailinghub_metrics_collector_success', 'Whether an optional collector succeeded during this scrape.', 'gauge', [
60
148
  `bailinghub_metrics_collector_success{collector="state"} ${document.state.success ? 1 : 0}`,
61
149
  `bailinghub_metrics_collector_success{collector="control_plane"} ${document.controlPlane.success ? 1 : 0}`,
150
+ `bailinghub_metrics_collector_success{collector="maintenance"} ${document.maintenance?.success ? 1 : 0}`,
62
151
  ]);
63
152
 
64
153
  if (document.state.value) {
@@ -92,6 +181,8 @@ export function renderOperationalMetrics(document: OperationalMetricsDocument):
92
181
  ]);
93
182
  }
94
183
 
184
+ if (document.maintenance?.value) renderMaintenance(lines, document.maintenance.value);
185
+
95
186
  family(lines, 'bailinghub_audit_write_failures_total', 'Audit ledger write failures observed by this process.', 'counter', [
96
187
  `bailinghub_audit_write_failures_total ${finite(document.auditWriteFailuresTotal)}`,
97
188
  ]);
@@ -0,0 +1,185 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { createServer, type ServerResponse } from 'node:http';
4
+ import { gzipSync } from 'node:zlib';
5
+ import { readResponseBody, ResponseBodyLimitError, truncateUtf8 } from './http-body';
6
+
7
+ function response(chunks: Uint8Array[], headers: Record<string, string> = {}) {
8
+ let pulls = 0;
9
+ let cancels = 0;
10
+ const body = new ReadableStream<Uint8Array>({
11
+ pull(controller) {
12
+ const chunk = chunks[pulls++];
13
+ if (chunk) controller.enqueue(chunk);
14
+ else controller.close();
15
+ },
16
+ cancel() { cancels++; },
17
+ }, { highWaterMark: 0 });
18
+ return { response: new Response(body, { headers }), body, counts: () => ({ pulls, cancels }) };
19
+ }
20
+
21
+ async function withLoopbackServer(handler: (response: ServerResponse) => void, check: (url: string) => Promise<void>) {
22
+ const server = createServer((_req, res) => handler(res));
23
+ await new Promise<void>((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
24
+ try {
25
+ const address = server.address();
26
+ assert.ok(address && typeof address !== 'string');
27
+ await check(`http://127.0.0.1:${address.port}/synthetic`);
28
+ } finally {
29
+ server.closeAllConnections();
30
+ await new Promise<void>((resolve) => server.close(() => resolve()));
31
+ }
32
+ }
33
+
34
+ test('bounded response: exact limit preserves bytes and releases the reader', async () => {
35
+ const fx = response([new Uint8Array([1, 2]), new Uint8Array([3, 4])]);
36
+ assert.deepEqual(new Uint8Array(await readResponseBody(fx.response, 4)), new Uint8Array([1, 2, 3, 4]));
37
+ assert.equal(fx.body.locked, false);
38
+ assert.equal(fx.counts().cancels, 0);
39
+ });
40
+
41
+ test('bounded response: stream over limit cancels before consuming later chunks', async () => {
42
+ const fx = response([new Uint8Array(4), new Uint8Array(1), new Uint8Array(100)]);
43
+ await assert.rejects(readResponseBody(fx.response, 4), (error: unknown) => {
44
+ assert.ok(error instanceof ResponseBodyLimitError);
45
+ assert.equal(error.source, 'stream');
46
+ assert.equal(error.observedBytes, 5);
47
+ return true;
48
+ });
49
+ assert.deepEqual(fx.counts(), { pulls: 2, cancels: 1 });
50
+ assert.equal(fx.body.locked, false);
51
+ });
52
+
53
+ test('bounded response: excessive declared length cancels without reading', async () => {
54
+ const fx = response([new Uint8Array(4)], { 'content-length': '5' });
55
+ await assert.rejects(readResponseBody(fx.response, 4), (error: unknown) => {
56
+ assert.ok(error instanceof ResponseBodyLimitError);
57
+ assert.equal(error.source, 'content-length');
58
+ return true;
59
+ });
60
+ assert.deepEqual(fx.counts(), { pulls: 0, cancels: 1 });
61
+ });
62
+
63
+ test('bounded response: low encoded length cannot bypass decoded stream budget', async () => {
64
+ const fx = response([new Uint8Array(5)], { 'content-length': '1', 'content-encoding': 'gzip' });
65
+ await assert.rejects(readResponseBody(fx.response, 4), ResponseBodyLimitError);
66
+ assert.equal(fx.counts().cancels, 1);
67
+ });
68
+
69
+ test('bounded response: native fetch gzip decoding cannot bypass the byte budget', async () => {
70
+ const encoded = gzipSync('a'.repeat(2048));
71
+ assert.ok(encoded.byteLength < 1024);
72
+ await withLoopbackServer((r) => {
73
+ r.writeHead(200, { 'content-encoding': 'gzip', 'content-length': encoded.byteLength });
74
+ r.end(encoded);
75
+ }, async (url) => {
76
+ const r = await fetch(url);
77
+ await assert.rejects(readResponseBody(r, 1024), (error: unknown) => {
78
+ assert.ok(error instanceof ResponseBodyLimitError);
79
+ assert.equal(error.source, 'stream');
80
+ assert.ok(error.observedBytes > 1024);
81
+ return true;
82
+ });
83
+ assert.equal(r.body!.locked, false);
84
+ });
85
+ });
86
+
87
+ test('bounded response: native fetch abort after headers rejects partial body', async () => {
88
+ await withLoopbackServer((r) => { r.writeHead(200); r.write('a'); }, async (url) => {
89
+ const abort = new AbortController();
90
+ const r = await fetch(url, { signal: abort.signal });
91
+ const pending = readResponseBody(r, 1024);
92
+ abort.abort();
93
+ await assert.rejects(pending, (error: unknown) => error instanceof Error && error.name === 'AbortError');
94
+ assert.equal(r.body!.locked, false);
95
+ });
96
+ });
97
+
98
+ test('bounded response: invalid length is ignored while the stream remains limited', async () => {
99
+ for (const length of ['garbage', '-1', '2.5']) {
100
+ const fx = response([new Uint8Array(5)], { 'content-length': length });
101
+ await assert.rejects(readResponseBody(fx.response, 4), ResponseBodyLimitError);
102
+ assert.equal(fx.counts().cancels, 1);
103
+ }
104
+ });
105
+
106
+ test('bounded response: enormous declared lengths also fail closed', async () => {
107
+ const fx = response([], { 'content-length': '9'.repeat(400) });
108
+ await assert.rejects(readResponseBody(fx.response, 4), ResponseBodyLimitError);
109
+ assert.equal(fx.counts().pulls, 0);
110
+ });
111
+
112
+ test('bounded response: empty body and zero budget are supported', async () => {
113
+ assert.equal((await readResponseBody(new Response(null), 0)).byteLength, 0);
114
+ });
115
+
116
+ test('bounded response: invalid budget rejects before response consumption', async () => {
117
+ const fx = response([new Uint8Array(5)]);
118
+ await assert.rejects(readResponseBody(fx.response, Infinity), RangeError);
119
+ assert.equal(fx.counts().pulls, 0);
120
+ });
121
+
122
+ test('bounded response: original error survives rejected/pending cancellation and releases reader', { timeout: 1000 }, async () => {
123
+ for (const pending of [false, true]) {
124
+ const original = new DOMException('synthetic body timeout', 'TimeoutError');
125
+ let cancels = 0;
126
+ let releases = 0;
127
+ const fake = { headers: new Headers(), body: { getReader: () => ({
128
+ read: async () => { throw original; },
129
+ cancel: async () => {
130
+ cancels++;
131
+ if (pending) await new Promise<void>(() => undefined);
132
+ else throw new Error('synthetic cancellation failure');
133
+ },
134
+ releaseLock: () => { releases++; },
135
+ }) } } as unknown as Response;
136
+ await assert.rejects(readResponseBody(fake, 4), (error: unknown) => error === original);
137
+ assert.equal(cancels, 1);
138
+ assert.equal(releases, 1);
139
+ }
140
+ });
141
+
142
+ test('bounded response: pending cancel cannot hold a limit error or reader lock open', { timeout: 1000 }, async () => {
143
+ for (const declared of [false, true]) {
144
+ let cancels = 0;
145
+ const body = new ReadableStream<Uint8Array>({
146
+ pull(controller) { controller.enqueue(new Uint8Array(5)); },
147
+ cancel() { cancels++; return new Promise<void>(() => undefined); },
148
+ }, { highWaterMark: 0 });
149
+ const r = new Response(body, { headers: declared ? { 'content-length': '5' } : {} });
150
+ await assert.rejects(readResponseBody(r, 4), ResponseBodyLimitError);
151
+ assert.equal(cancels, 1);
152
+ assert.equal(body.locked, false);
153
+ }
154
+ });
155
+
156
+ test('bounded response: fetch body abort is propagated without partial success', async () => {
157
+ const controller = new AbortController();
158
+ const failure = new DOMException('synthetic timeout', 'TimeoutError');
159
+ const body = new ReadableStream<Uint8Array>({
160
+ start(stream) {
161
+ stream.enqueue(new Uint8Array([1]));
162
+ controller.signal.addEventListener('abort', () => stream.error(controller.signal.reason), { once: true });
163
+ },
164
+ });
165
+ const pending = readResponseBody(new Response(body), 4);
166
+ controller.abort(failure);
167
+ await assert.rejects(pending, (error: unknown) => error === failure);
168
+ assert.equal(body.locked, false);
169
+ });
170
+
171
+ test('bounded response: Unicode split between chunks remains intact', async () => {
172
+ const bytes = new TextEncoder().encode('汉🙂');
173
+ const fx = response([bytes.subarray(0, 1), bytes.subarray(1, 4), bytes.subarray(4)]);
174
+ assert.equal(new TextDecoder().decode(await readResponseBody(fx.response, 7)), '汉🙂');
175
+ });
176
+
177
+ test('UTF-8 view budget: no split characters, replacement suffix, or excess bytes', () => {
178
+ for (let limit = 0; limit <= 9; limit++) {
179
+ const got = truncateUtf8('a汉🙂z', limit);
180
+ assert.ok(Buffer.byteLength(got) <= limit);
181
+ assert.equal(got.includes('\ufffd'), false);
182
+ }
183
+ assert.equal(truncateUtf8('汉🙂', 6), '汉');
184
+ assert.equal(truncateUtf8('汉🙂', 7), '汉🙂');
185
+ });
@@ -0,0 +1,58 @@
1
+ /** A response that exceeded its byte budget is incomplete evidence, never a partial success. */
2
+ export class ResponseBodyLimitError extends Error {
3
+ constructor(
4
+ readonly maxBytes: number,
5
+ readonly observedBytes: number,
6
+ readonly source: 'content-length' | 'stream',
7
+ ) {
8
+ super(`HTTP response exceeds ${maxBytes} byte limit`);
9
+ this.name = 'ResponseBodyLimitError';
10
+ }
11
+ }
12
+
13
+ export function cancelResponseBody(response: Response): void {
14
+ try { void response.body?.cancel().catch(() => undefined); } catch { /* Best effort; never wait on an unbounded cancel hook. */ }
15
+ }
16
+
17
+ /** Counts fetch's decoded body bytes before buffering; Content-Length is only an early rejection hint. */
18
+ export async function readResponseBody(response: Response, maxBytes: number): Promise<ArrayBuffer> {
19
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new RangeError('Invalid HTTP response byte limit');
20
+ const declared = response.headers.get('content-length')?.trim();
21
+ if (declared && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
22
+ cancelResponseBody(response);
23
+ throw new ResponseBodyLimitError(maxBytes, Number(declared), 'content-length');
24
+ }
25
+ if (!response.body) return new ArrayBuffer(0);
26
+
27
+ const reader = response.body.getReader();
28
+ const chunks: Uint8Array[] = [];
29
+ let total = 0;
30
+ try {
31
+ while (true) {
32
+ const { done, value } = await reader.read();
33
+ if (done) break;
34
+ total += value.byteLength;
35
+ if (total > maxBytes) throw new ResponseBodyLimitError(maxBytes, total, 'stream');
36
+ chunks.push(value);
37
+ }
38
+ const body = new Uint8Array(total);
39
+ let offset = 0;
40
+ for (const chunk of chunks) { body.set(chunk, offset); offset += chunk.byteLength; }
41
+ return body.buffer;
42
+ } catch (error) {
43
+ try { void reader.cancel().catch(() => undefined); } catch { /* Preserve a limit/timeout/transport error without waiting. */ }
44
+ throw error;
45
+ } finally {
46
+ reader.releaseLock();
47
+ }
48
+ }
49
+
50
+ /** UTF-8 byte budget without splitting a multibyte character or surrogate pair. */
51
+ export function truncateUtf8(text: string, maxBytes: number): string {
52
+ const limit = Number.isFinite(maxBytes) ? Math.max(0, Math.floor(maxBytes)) : 0;
53
+ const bytes = Buffer.from(text, 'utf8');
54
+ if (bytes.byteLength <= limit) return text;
55
+ let end = limit;
56
+ while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end--;
57
+ return bytes.subarray(0, end).toString('utf8');
58
+ }
@@ -144,6 +144,8 @@ test('finishJob: delivery 子任务最终失败时告警并写 DLQ', async () =>
144
144
  recipient: 'zhangsan',
145
145
  content: '投递正文',
146
146
  error: '发送失败',
147
+ deliveryKind: 'executor_target',
148
+ notificationJobId: 'job-1',
147
149
  }]);
148
150
  });
149
151
 
@@ -2,6 +2,7 @@
2
2
  // 不依赖 runtime 单例;engine 只注入收尾所需的状态仓库、会话账本、送达死信账本与出站能力。
3
3
  import type { AuditEntry } from '../contracts/types';
4
4
  import type { Job } from '../contracts/types';
5
+ import { notificationBackgroundWorkFor } from './notification-background-work';
5
6
 
6
7
  export interface FinishStateStoreLike {
7
8
  updateJob(jobId: string, patch: Partial<Job>): Promise<Job | null>;
@@ -13,7 +14,7 @@ export interface FinishConversationLedgerLike {
13
14
  }
14
15
 
15
16
  export interface FinishDeliveryDlqLike {
16
- record(d: { parentJobId: string; channel: string; recipient: string; content: string; error: string }): Promise<void>;
17
+ record(d: { parentJobId: string; channel: string; recipient: string; content: string; error: string; deliveryKind?: 'native_channel' | 'executor_target'; notificationJobId?: string }): Promise<void>;
17
18
  }
18
19
 
19
20
  export interface FinishRuntimeDeps {
@@ -39,6 +40,7 @@ export function deliveryFailureRecipient(job: Job): string {
39
40
  }
40
41
 
41
42
  export async function finishJob(job: Job, patch: Partial<Job>, deps: FinishRuntimeDeps): Promise<Job | null> {
43
+ const notifications = notificationBackgroundWorkFor(deps.store);
42
44
  const terminal = patch.status === 'done' || patch.status === 'error' || patch.status === 'rejected';
43
45
  const finalPatch: Partial<Job> = terminal
44
46
  ? { ...patch, executor_id: undefined, claimed_at: undefined, lease_until: undefined, dispatched_at: undefined, claim_token: undefined }
@@ -60,23 +62,24 @@ export async function finishJob(job: Job, patch: Partial<Job>, deps: FinishRunti
60
62
  }
61
63
  }
62
64
 
63
- if (updated && job.callback_url) void deps.fireCallback(job.callback_url, updated);
65
+ if (updated && job.callback_url) void notifications.track('callback', () => deps.fireCallback(job.callback_url!, updated));
64
66
 
65
67
  // 送达层:done 或 error 都进(spawnDeliveryJob 内裁决:失败只回调 webhook 不推人渠道)。
66
68
  if (updated && (updated.status === 'done' || updated.status === 'error')) {
67
- void deps.spawnDeliveryJob(updated).catch(async (e) => {
69
+ void notifications.track('delivery', async () => { try { await deps.spawnDeliveryJob(updated); } catch (e) {
68
70
  await deps.store.appendAudit({ ts: deps.now(), job_id: job.job_id, request_id: job.request_id, event: 'delivery_error', detail: { error: String(e) } });
69
- });
71
+ throw e;
72
+ } });
70
73
  }
71
74
 
72
75
  // 送达子任务(executor-notify 渠道)重试耗尽 → 终态 error:必须告警 + 落 DLQ。
73
76
  if (updated && updated.status === 'error' && (job.source === 'delivery' || (job.target ?? '').endsWith('-notify'))) {
74
77
  const to = deliveryFailureRecipient(job);
75
78
  const err = String(patch.error ?? updated.error ?? '未知错误').slice(0, 200);
76
- void deps.sendAlert(`delivery_failed_${job.target}`,
79
+ void notifications.track('alert', () => deps.sendAlert(`delivery_failed_${job.target}`,
77
80
  `送达任务最终失败(渠道 ${job.target},收件人 ${to}):${err}。收件人可能未收到结果,请到控制台「任务」查 ${job.job_id} 并手动补发。`)
78
- .catch(() => { /* 告警失败不影响主流程 */ });
79
- void deps.deliveryDlq?.record({ parentJobId: job.job_id, channel: String(job.target ?? ''), recipient: to, content: job.input ?? '', error: err }).catch(() => undefined);
81
+ );
82
+ if (deps.deliveryDlq) void notifications.track('delivery-dlq', () => deps.deliveryDlq!.record({ parentJobId: job.job_id, channel: String(job.target ?? ''), recipient: to, content: job.input ?? '', error: err, deliveryKind: 'executor_target', notificationJobId: job.job_id }));
80
83
  }
81
84
 
82
85
  return updated;
@@ -0,0 +1,50 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { NotificationBackgroundWork, notificationBackgroundWorkFor, bindNotificationBackgroundWork } from './notification-background-work';
4
+
5
+ test('notification drain includes children accepted during drain and retries a timeout', async () => {
6
+ const work = new NotificationBackgroundWork();
7
+ let releaseParent!: () => void, releaseChild!: () => void;
8
+ const parentGate = new Promise<void>(resolve => { releaseParent = resolve; });
9
+ const childGate = new Promise<void>(resolve => { releaseChild = resolve; });
10
+ void work.track('delivery', async () => {
11
+ await parentGate;
12
+ void work.track('delivery-dlq', () => childGate);
13
+ });
14
+ work.beginDrain();
15
+ assert.equal(await work.drain(1), false);
16
+ releaseParent();
17
+ await new Promise(resolve => setImmediate(resolve));
18
+ assert.equal(work.snapshot().kinds.find(x => x.kind === 'delivery-dlq')?.inFlight, 1);
19
+ assert.equal(await work.drain(1), false);
20
+ releaseChild();
21
+ assert.equal(await work.drain(100), true);
22
+ assert.equal(work.snapshot().drainTimeouts, 2);
23
+ assert.equal(work.snapshot().kinds.find(x => x.kind === 'delivery-dlq')?.completed, 1);
24
+ });
25
+
26
+ test('notification failure diagnostics expose only fixed kinds and guard outcome predicates', async () => {
27
+ const work = new NotificationBackgroundWork();
28
+ const kinds: string[] = [];
29
+ work.setFailureReporter(kind => { kinds.push(kind); throw new Error('diagnostic sink unavailable'); });
30
+ await assert.rejects(work.track('callback', async () => { throw new Error('private payload'); }));
31
+ assert.equal(await work.track('alert', async () => false, sent => !sent), false);
32
+ assert.equal(await work.track('delivery', async () => true, () => { throw new Error('bad predicate'); }), true);
33
+ assert.equal(await work.drain(100), true);
34
+ assert.deepEqual(kinds, ['callback', 'alert', 'delivery']);
35
+ assert.equal(work.snapshot().kinds.reduce((sum, x) => sum + x.failed, 0), 3);
36
+ assert.equal(JSON.stringify(work.snapshot()).includes('private'), false);
37
+ });
38
+
39
+ test('notification tracking belongs to one store/Kernel and snapshot handles large pending sets', async () => {
40
+ const one = {}, two = {};
41
+ const work = new NotificationBackgroundWork();
42
+ bindNotificationBackgroundWork(one, work);
43
+ assert.equal(notificationBackgroundWorkFor(one), work);
44
+ assert.notEqual(notificationBackgroundWorkFor(two), work);
45
+ let release!: () => void;
46
+ const gate = new Promise<void>(resolve => { release = resolve; });
47
+ for (let i = 0; i < 10000; i++) void work.track('callback', () => gate);
48
+ assert.equal(work.snapshot().kinds.find(x => x.kind === 'callback')?.inFlight, 10000);
49
+ release(); await work.drain(1000);
50
+ });