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
@@ -3,7 +3,8 @@ import test from 'node:test';
3
3
  import type { AppConfig } from '../core/config/config';
4
4
  import type { RuntimeStateStore } from '../core/state/state-contracts';
5
5
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
6
- import { createOperationalMetricsEndpointFor } from './operational-metrics';
6
+ import { createOperationalMetricsEndpointFor, type OperationalMetricsDeps } from './operational-metrics';
7
+ import { UsageRepository } from '../modules/usage/repository';
7
8
 
8
9
  const metrics = {
9
10
  enabled: true,
@@ -15,6 +16,7 @@ function endpoint(input: {
15
16
  store: RuntimeStateStore;
16
17
  configStore?: ConfigStoreContract | null;
17
18
  logger?: Pick<Console, 'error'>;
19
+ notificationWork?: OperationalMetricsDeps['notificationWork'];
18
20
  }) {
19
21
  return createOperationalMetricsEndpointFor({
20
22
  cfg: { root: process.cwd(), metrics } as Pick<AppConfig, 'root' | 'metrics'>,
@@ -24,6 +26,7 @@ function endpoint(input: {
24
26
  isPaused: () => false,
25
27
  auditFailures: { snapshot: () => ({ total: 3, lastFailureAt: null }) },
26
28
  logger: input.logger,
29
+ notificationWork: input.notificationWork,
27
30
  build: { version: 'test', commit: 'abc123' },
28
31
  });
29
32
  }
@@ -71,3 +74,36 @@ test('operational metrics: a stalled collector is bounded by the configured time
71
74
  assert.match(text, /bailinghub_metrics_collector_success\{collector="state"\} 0/);
72
75
  assert.match(logs[0]!, /"failure":"timeout"/);
73
76
  });
77
+
78
+ test('maintenance scrape reads in-memory usage and notification snapshots without database or provider work', async () => {
79
+ let reads = 0, snapshots = 0;
80
+ const usage = new UsageRepository(() => { reads++; throw new Error('No SQL or provider calls during maintenance scrape'); });
81
+ const configStore = { usage, observability: {} } as unknown as ConfigStoreContract;
82
+ const target = endpoint({ store: {} as RuntimeStateStore, configStore, notificationWork: { snapshot() {
83
+ snapshots++;
84
+ return { draining: false, drainTimeouts: 0, kinds: [{ kind: 'callback', inFlight: 1, completed: 2, failed: 3,
85
+ oldestPendingAgeMs: 1000, lastStartedAt: null, lastCompletedAt: null, lastFailedAt: null }] };
86
+ } } });
87
+ const text = await target.scrape();
88
+ assert.equal(reads, 0);
89
+ assert.equal(snapshots, 1);
90
+ assert.match(text, /bailinghub_metrics_collector_success\{collector="maintenance"\} 1/);
91
+ assert.match(text, /bailinghub_background_work_in_flight\{source="notification",kind="callback"\} 1/);
92
+ assert.match(text, /bailinghub_background_work_in_flight\{source="usage",kind="settlement"\} 0/);
93
+ assert.doesNotMatch(text, /bailinghub_maintenance_last_page_records/); // No billing page was initialized by the scrape.
94
+ });
95
+
96
+ test('maintenance snapshot failures leave existing metrics available and redact raw errors', async () => {
97
+ const logs: string[] = [];
98
+ const text = await endpoint({ store: {} as RuntimeStateStore,
99
+ notificationWork: { snapshot() { throw new Error('PRIVATE_TENANT_ACCOUNT_JOB_ROUTE_PROMPT_TOKEN_BODY'); } },
100
+ logger: { error(message) { logs.push(message); } },
101
+ }).scrape();
102
+ assert.match(text, /bailinghub_up 1/);
103
+ assert.match(text, /bailinghub_runtime_queue\{state="running"\} 1/);
104
+ assert.match(text, /bailinghub_metrics_collector_success\{collector="maintenance"\} 0/);
105
+ assert.doesNotMatch(text, /bailinghub_background_work_in_flight/);
106
+ assert.equal(logs.length, 1);
107
+ assert.match(logs[0]!, /"collector":"maintenance"/);
108
+ assert.doesNotMatch(logs[0]!, /PRIVATE|TENANT|ACCOUNT|JOB|ROUTE|PROMPT|TOKEN|BODY/);
109
+ });
@@ -4,11 +4,16 @@ import {
4
4
  renderOperationalMetrics,
5
5
  type CollectorResult,
6
6
  type ControlPlaneOperationalMetricsSnapshot,
7
+ type BackgroundWorkMetricsSnapshot,
8
+ type RuntimeMaintenanceMetricsSnapshot,
7
9
  } from '../core/observability/openmetrics';
8
10
  import { buildVersionInfo } from '../core/platform/version';
9
11
  import type { AuditFailureTracker } from '../core/state/audit-observability';
10
12
  import type { JobOperationalMetricsSnapshot, RuntimeStateStore } from '../core/state/state-contracts';
11
13
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
14
+ import { usageReconciliationSnapshotFor } from '../modules/usage/billing-repository';
15
+ import { usageMaintenanceSnapshotFor } from '../modules/usage/maintenance';
16
+ import { approvalContinuationMaintenanceSnapshotFor } from './approval-continuations';
12
17
 
13
18
  export interface OperationalMetricsEndpoint {
14
19
  readonly enabled: boolean;
@@ -23,6 +28,7 @@ export interface OperationalMetricsDeps {
23
28
  queue: { stats(): { running: number; waiting: number } };
24
29
  isPaused(): boolean;
25
30
  auditFailures: Pick<AuditFailureTracker, 'snapshot'>;
31
+ notificationWork?: { snapshot(nowMs?: number): BackgroundWorkMetricsSnapshot };
26
32
  logger?: Pick<Console, 'error'>;
27
33
  now?: () => number;
28
34
  build?: { version: string; commit: string };
@@ -51,7 +57,7 @@ function buildIdentity(root: string): { version: string; commit: string } {
51
57
  }
52
58
 
53
59
  async function collect<T>(
54
- collector: 'state' | 'control_plane',
60
+ collector: 'state' | 'control_plane' | 'maintenance',
55
61
  action: (() => Promise<T>) | undefined,
56
62
  timeoutMs: number,
57
63
  logger: Pick<Console, 'error'>,
@@ -96,7 +102,7 @@ export function createOperationalMetricsEndpointFor(deps: OperationalMetricsDeps
96
102
  async scrape(): Promise<string> {
97
103
  const startedAt = now();
98
104
  const snapshotAt = now();
99
- const [state, controlPlane] = await Promise.all([
105
+ const [state, controlPlane, maintenance] = await Promise.all([
100
106
  collect<JobOperationalMetricsSnapshot>(
101
107
  'state',
102
108
  stateCollector ? () => stateCollector(snapshotAt) : undefined,
@@ -109,6 +115,22 @@ export function createOperationalMetricsEndpointFor(deps: OperationalMetricsDeps
109
115
  deps.cfg.metrics.scrapeTimeoutMs,
110
116
  logger,
111
117
  ),
118
+ collect<RuntimeMaintenanceMetricsSnapshot>(
119
+ 'maintenance',
120
+ async () => {
121
+ const usage = deps.configStore?.usage;
122
+ const approval = approvalContinuationMaintenanceSnapshotFor({ configStore: deps.configStore, stateStore: deps.store }, snapshotAt);
123
+ return {
124
+ capturedAtMs: snapshotAt,
125
+ ...(usage ? { usage: usage.backgroundWork.snapshot(snapshotAt), usageReconciliation: usageReconciliationSnapshotFor(usage),
126
+ usageRetry: usageMaintenanceSnapshotFor(usage) } : {}),
127
+ ...(deps.notificationWork ? { notification: deps.notificationWork.snapshot(snapshotAt) } : {}),
128
+ ...(approval ? { approval: approval.work, approvalReconciliation: approval.progress } : {}),
129
+ };
130
+ },
131
+ deps.cfg.metrics.scrapeTimeoutMs,
132
+ logger,
133
+ ),
112
134
  ]);
113
135
  return renderOperationalMetrics({
114
136
  ...build,
@@ -116,6 +138,7 @@ export function createOperationalMetricsEndpointFor(deps: OperationalMetricsDeps
116
138
  queue: deps.queue.stats(),
117
139
  state,
118
140
  controlPlane,
141
+ maintenance,
119
142
  auditWriteFailuresTotal: deps.auditFailures.snapshot().total,
120
143
  scrapeDurationSeconds: Math.max((now() - startedAt) / 1000, 0),
121
144
  });
@@ -9,6 +9,7 @@ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
9
9
  import type { RuntimeStateStore } from '../core/state/state-contracts';
10
10
  import type { AppConfig } from '../core/config/config';
11
11
  import { requireServerToken } from '../core/platform/server-token';
12
+ import { notificationBackgroundWorkFor, type NotificationBackgroundKind } from '../core/runtime/notification-background-work';
12
13
 
13
14
  export { signBody };
14
15
 
@@ -63,7 +64,13 @@ export async function secretForJobWithDeps(deps: Pick<OutboundRuntimeDeps, 'cfg'
63
64
  }
64
65
 
65
66
  const OUTBOUND_BACKOFF_MS = [0, 2000, 10_000]; // 共 3 次尝试
66
- export async function postSignedWithDeps(deps: Pick<OutboundRuntimeDeps, 'stateStore' | 'now' | 'sleep' | 'fetch'>, url: string, payload: unknown, secret: string, audit: { job_id: string; request_id: string; event: string }): Promise<boolean> {
67
+ export function postSignedWithDeps(deps: Pick<OutboundRuntimeDeps, 'stateStore' | 'now' | 'sleep' | 'fetch'>, url: string, payload: unknown, secret: string, audit: { job_id: string; request_id: string; event: string }): Promise<boolean> {
68
+ const kind: NotificationBackgroundKind = audit.event.startsWith('approval_') ? 'approval-notification'
69
+ : audit.event.startsWith('alert') ? 'alert' : audit.event === 'callback' ? 'callback' : 'delivery';
70
+ return notificationBackgroundWorkFor(deps.stateStore).track(kind, () => postSignedInner(deps, url, payload, secret, audit), sent => !sent);
71
+ }
72
+
73
+ async function postSignedInner(deps: Pick<OutboundRuntimeDeps, 'stateStore' | 'now' | 'sleep' | 'fetch'>, url: string, payload: unknown, secret: string, audit: { job_id: string; request_id: string; event: string }): Promise<boolean> {
67
74
  const body = JSON.stringify(payload);
68
75
  for (let i = 0; i < OUTBOUND_BACKOFF_MS.length; i++) {
69
76
  if (OUTBOUND_BACKOFF_MS[i]! > 0) await deps.sleep(OUTBOUND_BACKOFF_MS[i]!);
@@ -101,7 +108,11 @@ export async function fireCallbackWithDeps(deps: OutboundRuntimeDeps, url: strin
101
108
  // 渠道规则使用 channelSend 直推(复用渠道凭证),通用 webhook 使用签名 HTTP 直发;
102
109
  // 两种出口都不创建需要执行器认领的任务,避免告警链路因执行器离线而积压。
103
110
  const alertSentAtByStore = new WeakMap<RuntimeStateStore, Map<string, number>>();
104
- export async function sendAlertWithDeps(deps: OutboundRuntimeDeps, key: string, text: string): Promise<void> {
111
+ export function sendAlertWithDeps(deps: OutboundRuntimeDeps, key: string, text: string): Promise<void> {
112
+ return notificationBackgroundWorkFor(deps.stateStore).track('alert', () => sendAlertInner(deps, key, text));
113
+ }
114
+
115
+ async function sendAlertInner(deps: OutboundRuntimeDeps, key: string, text: string): Promise<void> {
105
116
  const rules = deps.configStore ? await deps.configStore.alertRules.matching(key).catch(() => []) : [];
106
117
  const a = deps.cfg.alerts;
107
118
  const webhookUrl = (a && a.type === 'webhook' && a.url) ? a.url : '';
@@ -5,6 +5,7 @@ import type { ToolProvider } from '../core/contracts/types';
5
5
  import type { RuntimeStateStore } from '../core/state/state-contracts';
6
6
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
7
7
  import type { ToolIndexService } from '../services/tools-index';
8
+ import { notificationBackgroundWorkFor } from '../core/runtime/notification-background-work';
8
9
  import {
9
10
  createManagedRuntimeMaintenanceFor,
10
11
  createManagedRuntimeMaintenanceStateV1,
@@ -32,6 +33,94 @@ function toolProvider(name: string, input: Partial<ToolProvider> = {}): ToolProv
32
33
  };
33
34
  }
34
35
 
36
+ interface CapturedTimer { fire(): void; ms: number; interval: boolean; unref(): void }
37
+ async function withCapturedTimers<T>(action: (timers: CapturedTimer[]) => Promise<T>): Promise<T> {
38
+ const timers: CapturedTimer[] = [];
39
+ const originalTimeout = globalThis.setTimeout, originalInterval = globalThis.setInterval, originalClear = globalThis.clearTimeout;
40
+ const register = (interval: boolean) => ((fn: () => void, ms: number) => {
41
+ const timer: CapturedTimer = { fire: fn, ms, interval, unref() {} };
42
+ timers.push(timer); return timer;
43
+ });
44
+ globalThis.setTimeout = register(false) as unknown as typeof setTimeout;
45
+ globalThis.setInterval = register(true) as unknown as typeof setInterval;
46
+ globalThis.clearTimeout = (() => {}) as typeof clearTimeout;
47
+ try { return await action(timers); } finally {
48
+ globalThis.setTimeout = originalTimeout; globalThis.setInterval = originalInterval; globalThis.clearTimeout = originalClear;
49
+ }
50
+ }
51
+
52
+ test('standalone stop waits for a monitor producer before notification drain can release resources', async () => {
53
+ let releaseMonitor!: () => void, enteredMonitor!: () => void, enteredFetch!: () => void, releaseFetch!: () => void;
54
+ const monitorGate = new Promise<void>(resolve => { releaseMonitor = resolve; });
55
+ const monitorEntered = new Promise<void>(resolve => { enteredMonitor = resolve; });
56
+ const sendEntered = new Promise<void>(resolve => { enteredFetch = resolve; });
57
+ const sendGate = new Promise<void>(resolve => { releaseFetch = resolve; });
58
+ const stateStore = { async listJobsByStatus() { return []; }, async appendAudit() {} } as unknown as RuntimeStateStore;
59
+ const notifications = notificationBackgroundWorkFor(stateStore);
60
+ const originalFetch = globalThis.fetch;
61
+ globalThis.fetch = async () => { enteredFetch(); await sendGate; return new Response('', { status: 200 }); };
62
+ let resourcesClosed = false;
63
+ const schedulers = await withCapturedTimers(async timers => {
64
+ const target = startRuntimeSchedulersFor({
65
+ cfg: { auditRetentionDays: 0, server: { token: 'synthetic-only' }, brand: { name: 'Synthetic' },
66
+ alerts: { type: 'webhook', url: 'https://synthetic.invalid/alert', cooldown_min: 0 } } as AppConfig,
67
+ configStore: { executors: { async list() { return []; } }, alertRules: { async matching() { return []; } },
68
+ observability: { async monitorSnapshot() { enteredMonitor(); await monitorGate; return { errors_15m: 5, oldest_queued_min: 0 }; } },
69
+ } as unknown as ConfigStoreContract,
70
+ stateStore, kbService: null, kbSync: null, toolIndex: null, isPaused: () => false,
71
+ async refreshTargets() {}, kickInhubScheduler() {}, async drainInhubScheduler() { return 0; },
72
+ async recoverInhubJobs() { return 0; }, now: () => new Date().toISOString(), async sleep() {},
73
+ });
74
+ timers.find(timer => !timer.interval && timer.ms === 60000)!.fire();
75
+ await monitorEntered;
76
+ return target;
77
+ });
78
+ const closeResources = async (budget: number) => {
79
+ if (!await schedulers.drain!(budget)) return false;
80
+ notifications.beginDrain();
81
+ if (!await notifications.drain(budget)) return false;
82
+ resourcesClosed = true;
83
+ return true;
84
+ };
85
+ try {
86
+ schedulers.stop();
87
+ assert.equal(await closeResources(1), false);
88
+ assert.equal(resourcesClosed, false);
89
+ assert.equal(notifications.snapshot().draining, false, 'the producer must drain before the child tracker starts draining');
90
+ releaseMonitor(); await sendEntered;
91
+ assert.equal(await schedulers.drain!(100), true);
92
+ assert.equal(await closeResources(1), false);
93
+ assert.equal(resourcesClosed, false);
94
+ assert.ok(notifications.snapshot().kinds.find(value => value.kind === 'alert')!.inFlight > 0);
95
+ releaseFetch();
96
+ assert.equal(await closeResources(100), true);
97
+ assert.equal(resourcesClosed, true);
98
+ } finally {
99
+ releaseMonitor(); releaseFetch(); schedulers.stop();
100
+ await schedulers.drain!(100); await notifications.drain(100); globalThis.fetch = originalFetch;
101
+ }
102
+ });
103
+
104
+ test('standalone stopped callbacks cannot admit maintenance or create the recurring monitor timer', async () => {
105
+ let targetRefreshes = 0, drains = 0;
106
+ await withCapturedTimers(async timers => {
107
+ const schedulers = startRuntimeSchedulersFor({
108
+ cfg: { auditRetentionDays: 0 } as AppConfig, configStore: null,
109
+ stateStore: {} as RuntimeStateStore, kbService: null, kbSync: null, toolIndex: null,
110
+ isPaused: () => false, async refreshTargets() { targetRefreshes++; }, kickInhubScheduler() {},
111
+ async drainInhubScheduler() { drains++; return 0; }, async recoverInhubJobs() { return 0; },
112
+ now: () => new Date().toISOString(), async sleep() {},
113
+ });
114
+ const registered = timers.length;
115
+ schedulers.stop();
116
+ for (const timer of [...timers]) timer.fire();
117
+ await new Promise<void>(resolve => setImmediate(resolve));
118
+ assert.equal(timers.length, registered);
119
+ assert.equal(targetRefreshes, 0); assert.equal(drains, 0);
120
+ assert.equal(await schedulers.drain!(0), true);
121
+ });
122
+ });
123
+
35
124
  test('initializeRuntimeLifecycleFor: Store 初始化后、目标刷新前执行启动契约', async () => {
36
125
  const events: string[] = [];
37
126
  const stateStore = {
@@ -39,7 +39,7 @@ const TOOL_CALL_RETENTION_MS = 3 * 24 * 60 * 60 * 1000;
39
39
 
40
40
  export interface RuntimeSchedulers {
41
41
  stop(): void;
42
- /** New persisted-evidence maintenance must finish before its stores close. */
42
+ /** Accepted scheduler producers must finish registering children before resources close. */
43
43
  drain?(drainMs?: number): Promise<boolean>;
44
44
  }
45
45
 
@@ -393,60 +393,62 @@ export function createManagedRuntimeMaintenanceFor(
393
393
  export function startRuntimeSchedulersFor(deps: RuntimeLifecycleDeps): RuntimeSchedulers {
394
394
  const actions = runtimeMaintenanceActionsFor(deps);
395
395
  const timers: Array<ReturnType<typeof setInterval> | ReturnType<typeof setTimeout>> = [];
396
- const evidenceWork = new Set<Promise<void>>();
396
+ const acceptedWork = new Set<Promise<unknown>>();
397
397
  let stopped = false;
398
- function reconcile(action: () => Promise<void>): void {
398
+ function reconcile(action: () => Promise<unknown>): void {
399
399
  if (stopped) return;
400
400
  const work = Promise.resolve().then(action);
401
- evidenceWork.add(work);
402
- void work.finally(() => evidenceWork.delete(work)).catch(() => undefined);
401
+ acceptedWork.add(work);
402
+ void work.finally(() => acceptedWork.delete(work)).catch(() => undefined);
403
403
  }
404
404
  const every = (fn: () => void, ms: number): void => {
405
+ if (stopped) return;
405
406
  const timer = setInterval(fn, ms);
406
407
  timer.unref();
407
408
  timers.push(timer);
408
409
  };
409
410
  const later = (fn: () => void, ms: number): void => {
411
+ if (stopped) return;
410
412
  const timer = setTimeout(fn, ms);
411
413
  timer.unref();
412
414
  timers.push(timer);
413
415
  };
414
416
 
415
417
  // 服务先启动,索引随后在后台预热;任何数据库/索引异常都不阻塞 HTTP 就绪。
416
- later(() => void actions.prewarmToolIndexes(), TOOL_INDEX_PREWARM_DELAY_MS);
418
+ later(() => reconcile(actions.prewarmToolIndexes), TOOL_INDEX_PREWARM_DELAY_MS);
417
419
  later(() => reconcile(actions.reconcileUsage), 0);
418
420
  later(() => reconcile(actions.reconcileApprovals), 0);
419
421
  every(() => reconcile(actions.reconcileUsage), USAGE_MAINTENANCE_MS);
420
422
  every(() => reconcile(actions.reconcileApprovals), APPROVAL_CONTINUATION_MS);
421
423
 
422
- every(() => void actions.refreshTargets().catch(() => undefined), TARGET_REFRESH_MS);
424
+ every(() => reconcile(actions.refreshTargets), TARGET_REFRESH_MS);
423
425
 
424
426
  // inhub DB 调度器:llm 等中枢内目标也从 bz_jobs 队列认领,避免依赖建单进程的内存 promise。
425
427
  // kick 提供低延迟,tick 提供兜底与多实例拾取;认领本身在 DB 里原子化。
426
- every(() => void actions.drainInhub(1).catch(() => undefined), INHUB_DRAIN_MS);
428
+ every(() => reconcile(() => actions.drainInhub(1)), INHUB_DRAIN_MS);
427
429
 
428
430
  // 自监控:启动 1 分钟后首跑,避开冷启动误报。
429
431
  later(() => {
430
- void actions.monitor();
431
- every(() => void actions.monitor(), MONITOR_INTERVAL_MS);
432
+ reconcile(actions.monitor);
433
+ every(() => reconcile(actions.monitor), MONITOR_INTERVAL_MS);
432
434
  }, MONITOR_DELAY_MS);
433
435
 
434
436
  // 工具源 spec 自动刷新:每分钟扫一遍,按各源 auto_refresh_min 节流。
435
- every(() => void actions.refreshSpecs().catch(() => undefined), SPEC_REFRESH_MS);
437
+ every(() => reconcile(actions.refreshSpecs), SPEC_REFRESH_MS);
436
438
 
437
439
  // 知识库数据源连接器:每分钟扫一遍到点的(变更/出错记审计,平稳无事不刷流水)。
438
440
  if (deps.kbSync) {
439
- every(() => void actions.syncKnowledgeBases().catch(() => undefined), KB_SYNC_MS);
441
+ every(() => reconcile(actions.syncKnowledgeBases), KB_SYNC_MS);
440
442
  }
441
443
 
442
- every(() => void actions.reapStaleWork(), REAPER_INTERVAL_MS);
444
+ every(() => reconcile(actions.reapStaleWork), REAPER_INTERVAL_MS);
443
445
 
444
446
  // 执行日志清理:只删除超龄且已确认 completed 的行;未决状态必须保留给人工对账。
445
- every(() => void actions.cleanupToolCalls(), TOOL_CALL_CLEANUP_MS);
447
+ every(() => reconcile(actions.cleanupToolCalls), TOOL_CALL_CLEANUP_MS);
446
448
 
447
449
  if (deps.cfg.auditRetentionDays > 0) {
448
- later(() => void actions.cleanupAudit(), 60_000);
449
- every(() => void actions.cleanupAudit(), AUDIT_RETENTION_CLEANUP_MS);
450
+ later(() => reconcile(actions.cleanupAudit), 60_000);
451
+ every(() => reconcile(actions.cleanupAudit), AUDIT_RETENTION_CLEANUP_MS);
450
452
  }
451
453
 
452
454
  return {
@@ -455,12 +457,12 @@ export function startRuntimeSchedulersFor(deps: RuntimeLifecycleDeps): RuntimeSc
455
457
  for (const timer of timers.splice(0)) clearTimeout(timer);
456
458
  },
457
459
  async drain(drainMs = 30_000) {
458
- if (evidenceWork.size === 0) return true;
460
+ if (acceptedWork.size === 0) return true;
459
461
  const bounded = Number.isFinite(drainMs) ? Math.max(0, Math.floor(drainMs)) : 0;
460
462
  let timer: ReturnType<typeof setTimeout> | undefined;
461
463
  try {
462
464
  return await Promise.race([
463
- Promise.allSettled([...evidenceWork]).then(() => true),
465
+ Promise.allSettled([...acceptedWork]).then(() => true),
464
466
  new Promise<boolean>(resolve => { timer = setTimeout(() => resolve(false), bounded); }),
465
467
  ]);
466
468
  } finally { if (timer) clearTimeout(timer); }
@@ -9,6 +9,7 @@ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
9
9
  import type { RuntimeStateStore } from '../core/state/state-contracts';
10
10
  import type { AppConfig } from '../core/config/config';
11
11
  import { isAgentToolInvocationJob } from './agent-tool-job';
12
+ import { notificationBackgroundWorkFor } from '../core/runtime/notification-background-work';
12
13
 
13
14
  /** 重跑时的"已批准调用清单"提示:审批车道 B 的另一半。 */
14
15
  export async function approvedNoteForJobFor(config: ConfigStoreContract | null, jobId: string): Promise<string | undefined> {
@@ -67,7 +68,7 @@ export function approvalDepsForStores(
67
68
  });
68
69
  },
69
70
  async notify(id, snap) {
70
- await notifyApprovalFor(config, state, job, provider, toolsCfg, sourceCfg, id, snap, appConfig, nowFn, sleepFn, targetRegistry);
71
+ await notificationBackgroundWorkFor(state).track('approval-notification', () => notifyApprovalFor(config, state, job, provider, toolsCfg, sourceCfg, id, snap, appConfig, nowFn, sleepFn, targetRegistry));
71
72
  },
72
73
  };
73
74
  }
@@ -0,0 +1,41 @@
1
+ import type { Job } from './types';
2
+ import { truncateUtf8 } from '../platform/http-body';
3
+
4
+ export type DeliveryKind = 'native_channel' | 'executor_target';
5
+ export interface DeliveryDlqRecord {
6
+ id: number;
7
+ parent_job_id?: string;
8
+ channel: string;
9
+ recipient: string;
10
+ content: string;
11
+ resolved: boolean;
12
+ delivery_kind?: DeliveryKind | null;
13
+ notification_job_id?: string | null;
14
+ executor_replay_key?: string | null;
15
+ }
16
+
17
+ export interface DeliveryRequeueInput {
18
+ dlq_id: number;
19
+ replay_key: string;
20
+ job_id: string;
21
+ request_id: string;
22
+ target: string;
23
+ /** Non-SQL adapters recheck the original DLQ under their single-writer lock. */
24
+ isOriginalDelivery?: () => Promise<boolean>;
25
+ }
26
+ export type DeliveryRequeueOutcome = 'queued' | 'already_queued' | 'in_flight' | 'missing' | 'conflict';
27
+
28
+ export function deliveryReplayKey(dlqId: number): string {
29
+ if (!Number.isSafeInteger(dlqId) || dlqId <= 0) throw new Error('delivery_dlq_invalid_id');
30
+ return `delivery-dlq:${dlqId}`;
31
+ }
32
+
33
+ /** A DLQ may only replay the original notification child, never its business parent. */
34
+ export function isOriginalExecutorDelivery(d: DeliveryDlqRecord, job: Job | null): boolean {
35
+ if (!job || job.source !== 'delivery' || !job.target?.endsWith('-notify') || d.channel !== job.target
36
+ || d.parent_job_id !== job.job_id || (d.notification_job_id && d.notification_job_id !== job.job_id)
37
+ || (d.delivery_kind && d.delivery_kind !== 'executor_target')) return false;
38
+ const recipient = String(job.metadata?.recipient ?? job.metadata?.to ?? '?').slice(0, 512);
39
+ const content = String(job.input ?? '');
40
+ return d.recipient === recipient && (d.content === truncateUtf8(content, 60000) || d.content === content.slice(0, 60000));
41
+ }
@@ -3,7 +3,7 @@
3
3
  import { test } from 'node:test';
4
4
  import assert from 'node:assert/strict';
5
5
  import { TOOL_DEFINITION_SCHEMA_VERSION, type ToolDefinition } from './tool-definition';
6
- import { argsHash, buildToolRuntime, toolCallIdempotencyKey, type ToolExecutionJournalEntry, type ToolRuntimeDeps } from './tools';
6
+ import { argsHash, AUDIT_MAX_BYTES, buildToolRuntime, toolCallIdempotencyKey, type ToolExecutionJournalEntry, type ToolRuntimeDeps } from './tools';
7
7
 
8
8
  function mkTool(over: Partial<ToolDefinition>): ToolDefinition {
9
9
  return {
@@ -21,6 +21,7 @@ function mkRuntime(
21
21
  tool: ToolDefinition,
22
22
  audit: ToolRuntimeDeps['audit'] = async () => { /* noop */ },
23
23
  ledger = new Map<string, ToolExecutionJournalEntry>(),
24
+ overrides: Partial<ToolRuntimeDeps> = {},
24
25
  ) {
25
26
  const deps: ToolRuntimeDeps = {
26
27
  provider: { name: 'p', base_url: 'http://x.invalid', secret: 's', timeout_ms: 5000, rate_limit_per_min: 0, log_payload: false } as any,
@@ -60,7 +61,7 @@ function mkRuntime(
60
61
  },
61
62
  },
62
63
  };
63
- return buildToolRuntime(deps);
64
+ return buildToolRuntime({ ...deps, ...overrides });
64
65
  }
65
66
 
66
67
  function mkRuntimeWithApprovals(tool: ToolDefinition) {
@@ -115,7 +116,7 @@ function mkRuntimeWithApprovals(tool: ToolDefinition) {
115
116
  async function withFetchCounter(fn: (count: () => number) => Promise<void>): Promise<void> {
116
117
  let n = 0;
117
118
  const orig = globalThis.fetch;
118
- globalThis.fetch = (async () => { n++; return { status: 200, text: async () => '{"ok":true}' } as unknown as Response; }) as typeof fetch;
119
+ globalThis.fetch = (async () => { n++; return new Response('{"ok":true}', { status: 200 }); }) as typeof fetch;
119
120
  try { await fn(() => n); } finally { globalThis.fetch = orig; }
120
121
  }
121
122
 
@@ -222,6 +223,121 @@ test('副作用工具:下游超时后冻结执行,恢复或重跑不得再
222
223
  }
223
224
  });
224
225
 
226
+ test('工具响应传输:200/302/500 正文超限都取消并冻结,恢复不得重投写入', async (t) => {
227
+ for (const status of [200, 302, 500]) {
228
+ for (const declared of [false, true]) {
229
+ await t.test(`status=${status}, declared=${declared}`, async (t) => {
230
+ let calls = 0;
231
+ let pulls = 0;
232
+ let cancels = 0;
233
+ const audits: Array<{ event: string; detail: Record<string, unknown> }> = [];
234
+ t.mock.method(globalThis, 'fetch', async () => {
235
+ calls++;
236
+ return new Response(new ReadableStream<Uint8Array>({
237
+ pull(controller) {
238
+ pulls++;
239
+ controller.enqueue(new Uint8Array(pulls === 1 ? 32 : 1));
240
+ },
241
+ cancel() { cancels++; },
242
+ }, { highWaterMark: 0 }), { status, headers: declared ? { 'content-length': '33' } : {} });
243
+ });
244
+ const ledger = new Map<string, ToolExecutionJournalEntry>();
245
+ const runtime = mkRuntime(mkTool({}), async (event, detail) => { audits.push({ event, detail }); }, ledger, { maxResponseBodyBytes: 32 });
246
+ const first = await runtime.invoke('create_thing', { x: 1 });
247
+ assert.equal(first.ok, false);
248
+ assert.equal(first.status, 0, 'headers alone cannot confirm a write after body loss');
249
+ assert.equal(first.governance_state, 'reconciliation_required');
250
+ assert.equal(first.auto_retry_allowed, false);
251
+ assert.equal(runtime.executionUncertainty()?.state, 'uncertain');
252
+ assert.equal(cancels, 1);
253
+ assert.equal(pulls, declared ? 0 : 2);
254
+ assert.equal(audits.some((audit) => audit.event === 'tool_result'), false);
255
+ const recovered = mkRuntime(mkTool({}), undefined, ledger, { maxResponseBodyBytes: 32 });
256
+ assert.equal((await recovered.invoke('create_thing', { x: 1 })).ok, false);
257
+ assert.equal(calls, 1);
258
+ });
259
+ }
260
+ }
261
+ });
262
+
263
+ test('工具默认传输预算:超过固定5 MiB的声明也不能确认小正文写入', async (t) => {
264
+ t.mock.method(globalThis, 'fetch', async () => new Response('synthetic', {
265
+ status: 200, headers: { 'content-length': String(5 * 1024 * 1024 + 1) },
266
+ }));
267
+ const runtime = mkRuntime(mkTool({}));
268
+ const result = await runtime.invoke('create_thing', {});
269
+ assert.equal(result.ok, false);
270
+ assert.equal(result.governance_state, 'reconciliation_required');
271
+ assert.equal(result.auto_retry_allowed, false);
272
+ assert.equal(runtime.executionUncertainty()?.state, 'uncertain');
273
+ });
274
+
275
+ test('工具响应传输:body timeout 保留原信号和 unknown 结果,不记录半截成功', async (t) => {
276
+ let calls = 0;
277
+ const audits: Array<{ event: string; detail: Record<string, unknown> }> = [];
278
+ t.mock.method(globalThis, 'fetch', async (_url: unknown, init: RequestInit) => {
279
+ calls++;
280
+ return new Response(new ReadableStream<Uint8Array>({
281
+ start(controller) {
282
+ controller.enqueue(new TextEncoder().encode('{"ok":'));
283
+ init.signal!.addEventListener('abort', () => controller.error(init.signal!.reason), { once: true });
284
+ },
285
+ }), { status: 200 });
286
+ });
287
+ const runtime = mkRuntime(mkTool({ timeoutMs: 20 }), async (event, detail) => { audits.push({ event, detail }); });
288
+ const watchdog = setTimeout(() => undefined, 1000);
289
+ try {
290
+ const result = await runtime.invoke('create_thing', { x: 1 });
291
+ assert.equal(result.ok, false);
292
+ assert.equal(result.governance_state, 'reconciliation_required');
293
+ assert.match(runtime.executionUncertainty()?.reason ?? '', /超时/);
294
+ assert.equal(audits.some((audit) => audit.event === 'tool_result'), false);
295
+ await runtime.invoke('create_thing', { x: 1 });
296
+ assert.equal(calls, 1);
297
+ } finally { clearTimeout(watchdog); }
298
+ });
299
+
300
+ test('工具响应视图:中文的模型和审计 UTF-8 字节预算真实有界', async (t) => {
301
+ const audits: Array<{ event: string; detail: Record<string, unknown> }> = [];
302
+ const value = '汉'.repeat(AUDIT_MAX_BYTES);
303
+ t.mock.method(globalThis, 'fetch', async () => new Response(value));
304
+ const def = mkTool({ inputSchema: { type: 'object', properties: { x: { type: 'string' } } } });
305
+ const runtime = mkRuntime(def, async (event, detail) => { audits.push({ event, detail }); }, undefined,
306
+ { provider: { name: 'p', base_url: 'https://synthetic.invalid', secret: 'synthetic', timeout_ms: 5000, rate_limit_per_min: 0, log_payload: true } as any });
307
+ const result = await runtime.invoke('create_thing', { x: value });
308
+ assert.equal(result.ok, true);
309
+ assert.equal(Buffer.byteLength(result.text), 8190);
310
+ assert.equal(result.text.includes('\ufffd'), false);
311
+ const call = audits.find((entry) => entry.event === 'tool_call')!.detail;
312
+ assert.equal(call.args_bytes, Buffer.byteLength(JSON.stringify({ x: value })));
313
+ assert.ok(Buffer.byteLength(String(call.args)) <= AUDIT_MAX_BYTES);
314
+ assert.equal(call.args_truncated, true);
315
+ const response = audits.find((entry) => entry.event === 'tool_result')!.detail;
316
+ assert.equal(response.resp_bytes, Buffer.byteLength(value));
317
+ assert.ok(Buffer.byteLength(String(response.resp)) <= AUDIT_MAX_BYTES);
318
+ assert.equal(response.resp_truncated, true);
319
+ });
320
+
321
+ test('工具响应视图:敏感工具仍脱敏,响应字节数保持实际输入计数', async (t) => {
322
+ const audits: Array<{ event: string; detail: Record<string, unknown> }> = [];
323
+ t.mock.method(globalThis, 'fetch', async () => new Response(new Uint8Array([255])));
324
+ const runtime = mkRuntime(mkTool({ sensitive: true }), async (event, detail) => { audits.push({ event, detail }); }, undefined,
325
+ { provider: { name: 'p', base_url: 'https://synthetic.invalid', secret: 'synthetic', timeout_ms: 5000, rate_limit_per_min: 0, log_payload: true } as any });
326
+ await runtime.invoke('create_thing', { x: 42 });
327
+ const response = audits.find((entry) => entry.event === 'tool_result')!.detail;
328
+ assert.equal(response.resp_bytes, 1, 'replacement decoding must not alter consumed byte count');
329
+ assert.equal(response.resp, '<1 bytes>');
330
+ assert.equal(audits.find((entry) => entry.event === 'tool_call')!.detail.args, '["x"]');
331
+ });
332
+
333
+ test('工具响应视图:空响应 fallback 也遵守极小字节预算', async (t) => {
334
+ t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 204 }));
335
+ const runtime = mkRuntime(mkTool({}), undefined, undefined, { truncateBytes: 1 });
336
+ const result = await runtime.invoke('create_thing', {});
337
+ assert.equal(result.ok, true);
338
+ assert.ok(Buffer.byteLength(result.text) <= 1);
339
+ });
340
+
225
341
  test('副作用工具:崩溃遗留 dispatching 占位时,新运行时 fail-closed 且不外发', async () => {
226
342
  const callArgs = { x: 10 };
227
343
  const hash = argsHash(callArgs);
@@ -268,7 +384,7 @@ test('副作用工具:发送稳定的下游幂等键,且该键与任务、
268
384
  let seen = '';
269
385
  globalThis.fetch = (async (_url, init) => {
270
386
  seen = String((init?.headers as Record<string, string>)['x-bailing-idempotency-key'] ?? '');
271
- return { status: 200, text: async () => '{"ok":true}' } as unknown as Response;
387
+ return new Response('{"ok":true}', { status: 200 });
272
388
  }) as typeof fetch;
273
389
  try {
274
390
  await rt.invoke('create_thing', { x: 9 });
@@ -347,7 +463,7 @@ test('工具调用:path/header/query/body 参数按 ToolDefinition.paramIn 组
347
463
  seenUrl = String(url);
348
464
  seenHeaders = init?.headers;
349
465
  seenBody = init?.body;
350
- return { status: 200, text: async () => '{"ok":true}' } as unknown as Response;
466
+ return new Response('{"ok":true}', { status: 200 });
351
467
  }) as typeof fetch;
352
468
  try {
353
469
  await rt.invoke('update_staff', { store_id: 's 1', staff_id: 'u/2', tenant: 't1', dry_run: true, name: 'Alice' });