bailinghub 0.9.1 → 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 (115) 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 +23 -1
  5. package/docs/CHANGELOG.md +23 -1
  6. package/docs/CORE_RELIABILITY.en.md +79 -0
  7. package/docs/CORE_RELIABILITY.md +79 -0
  8. package/docs/DEPLOYMENT_DIAGNOSTICS.en.md +78 -0
  9. package/docs/DEPLOYMENT_DIAGNOSTICS.md +78 -0
  10. package/docs/IMPLEMENTATION_STATUS.en.md +27 -15
  11. package/docs/IMPLEMENTATION_STATUS.md +27 -15
  12. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  13. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  14. package/docs/KERNEL_HOST_API.en.md +2 -0
  15. package/docs/KERNEL_HOST_API.md +2 -0
  16. package/docs/MODEL_BILLING.en.md +4 -0
  17. package/docs/MODEL_BILLING.md +4 -0
  18. package/docs/MODEL_PROCESS_RECOVERY.en.md +32 -0
  19. package/docs/MODEL_PROCESS_RECOVERY.md +37 -0
  20. package/docs/OPERATIONS.en.md +13 -0
  21. package/docs/OPERATIONS.md +12 -0
  22. package/docs/README.en.md +7 -0
  23. package/docs/README.md +7 -0
  24. package/docs/RELEASE_NOTES_v0.9.2.en.md +45 -0
  25. package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
  26. package/docs/RELEASE_NOTES_v0.9.3.en.md +51 -0
  27. package/docs/RELEASE_NOTES_v0.9.3.md +51 -0
  28. package/docs/TOOLS_DESIGN.md +1 -0
  29. package/docs/UPGRADE_v0.9.2.en.md +62 -0
  30. package/docs/UPGRADE_v0.9.2.md +62 -0
  31. package/docs/UPGRADE_v0.9.3.en.md +63 -0
  32. package/docs/UPGRADE_v0.9.3.md +63 -0
  33. package/package.json +7 -3
  34. package/scripts/check-doc-links.mjs +4 -0
  35. package/scripts/check-image-tags.sh +1 -1
  36. package/scripts/check-release-consistency.test.mjs +2 -2
  37. package/scripts/doctor-deployment.test.ts +419 -0
  38. package/scripts/doctor-deployment.ts +357 -0
  39. package/scripts/doctor.ts +8 -1
  40. package/scripts/install-secrets.test.mjs +185 -0
  41. package/scripts/install.sh +10 -6
  42. package/scripts/publish-images.sh +1 -1
  43. package/scripts/release-audit.mjs +8 -0
  44. package/scripts/verify-github-repo.mjs +8 -0
  45. package/security/dependency-audit-exceptions.json +1 -1
  46. package/sql/065_usage_reconciliation_scan.sql +4 -0
  47. package/sql/066_approval_continuations.sql +15 -0
  48. package/sql/067_delivery_dlq_replay.sql +10 -0
  49. package/sql/README.en.md +6 -0
  50. package/sql/README.md +15 -0
  51. package/src/adapters/llm/file.test.ts +59 -0
  52. package/src/adapters/llm/file.ts +11 -4
  53. package/src/app/agent-tool-invocations.test.ts +3 -1
  54. package/src/app/approval-continuations.mysql.test.ts +138 -0
  55. package/src/app/approval-continuations.test.ts +351 -0
  56. package/src/app/approval-continuations.ts +148 -0
  57. package/src/app/channels-attachments.test.ts +63 -0
  58. package/src/app/channels.ts +7 -4
  59. package/src/app/delivery-dlq-replay.mysql.test.ts +139 -0
  60. package/src/app/delivery-dlq-replay.test.ts +75 -0
  61. package/src/app/delivery-dlq-replay.ts +41 -0
  62. package/src/app/delivery.ts +3 -2
  63. package/src/app/http-server.ts +3 -0
  64. package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
  65. package/src/app/kernel-notification-lifecycle.test.ts +49 -0
  66. package/src/app/kernel.ts +22 -0
  67. package/src/app/notification-outbound.test.ts +53 -0
  68. package/src/app/operational-metrics.test.ts +37 -1
  69. package/src/app/operational-metrics.ts +25 -2
  70. package/src/app/outbound.ts +13 -2
  71. package/src/app/runtime-evidence-maintenance.test.ts +55 -0
  72. package/src/app/runtime-lifecycle-default.ts +7 -0
  73. package/src/app/runtime-lifecycle.test.ts +89 -0
  74. package/src/app/runtime-lifecycle.ts +52 -11
  75. package/src/app/tool-approvals.ts +2 -1
  76. package/src/core/contracts/approval-continuation.ts +43 -0
  77. package/src/core/contracts/delivery-replay.ts +41 -0
  78. package/src/core/contracts/tools-idempotency.test.ts +121 -5
  79. package/src/core/contracts/tools.ts +21 -11
  80. package/src/core/contracts/types.ts +4 -0
  81. package/src/core/observability/openmetrics.test.ts +28 -0
  82. package/src/core/observability/openmetrics.ts +91 -0
  83. package/src/core/platform/http-body.test.ts +185 -0
  84. package/src/core/platform/http-body.ts +58 -0
  85. package/src/core/runtime/finish-runtime.test.ts +2 -0
  86. package/src/core/runtime/finish-runtime.ts +10 -7
  87. package/src/core/runtime/notification-background-work.test.ts +50 -0
  88. package/src/core/runtime/notification-background-work.ts +101 -0
  89. package/src/core/state/approval-continuation.ts +22 -0
  90. package/src/core/state/delivery-replay.ts +19 -0
  91. package/src/core/state/state-codec.ts +2 -0
  92. package/src/core/state/state-contracts.ts +6 -0
  93. package/src/infrastructure/config/config-approval-ledger.ts +75 -0
  94. package/src/infrastructure/config/config-delivery-dlq-ledger.ts +36 -10
  95. package/src/infrastructure/config/configstore.ts +4 -3
  96. package/src/infrastructure/state/state-jsonl.ts +56 -11
  97. package/src/infrastructure/state/state-mysql.ts +54 -0
  98. package/src/modules/usage/background-work.test.ts +28 -0
  99. package/src/modules/usage/background-work.ts +43 -7
  100. package/src/modules/usage/billing-reconciliation.mysql.test.ts +163 -0
  101. package/src/modules/usage/billing-reconciliation.test.ts +85 -0
  102. package/src/modules/usage/billing-repository.ts +63 -11
  103. package/src/modules/usage/maintenance.test.ts +78 -0
  104. package/src/modules/usage/maintenance.ts +39 -0
  105. package/src/modules/usage/model-gateway.ts +2 -1
  106. package/src/routes/admin-default.ts +2 -2
  107. package/src/routes/admin-runtime-default.ts +2 -2
  108. package/src/routes/admin-runtime.test.ts +1 -1
  109. package/src/routes/admin-runtime.ts +39 -18
  110. package/src/routes/admin.ts +1 -1
  111. package/src/routes/approvals-default.ts +2 -2
  112. package/src/routes/approvals.ts +30 -33
  113. package/src/routes/critical-routes.test.ts +16 -3
  114. package/src/test-support/approval-continuation-crash-child.ts +24 -0
  115. package/src/test-support/model-process-crash-child.ts +78 -0
@@ -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
+ });
@@ -0,0 +1,101 @@
1
+ export const NOTIFICATION_BACKGROUND_KINDS = ['callback', 'delivery', 'approval-notification', 'alert', 'delivery-dlq'] as const;
2
+ export type NotificationBackgroundKind = typeof NOTIFICATION_BACKGROUND_KINDS[number];
3
+
4
+ export interface NotificationBackgroundKindSnapshot {
5
+ kind: NotificationBackgroundKind;
6
+ inFlight: number;
7
+ completed: number;
8
+ failed: number;
9
+ oldestPendingAgeMs: number;
10
+ lastStartedAt: string | null;
11
+ lastCompletedAt: string | null;
12
+ lastFailedAt: string | null;
13
+ }
14
+
15
+ export interface NotificationBackgroundSnapshot {
16
+ draining: boolean;
17
+ drainTimeouts: number;
18
+ kinds: NotificationBackgroundKindSnapshot[];
19
+ }
20
+
21
+ /** One Kernel owns its accepted notifications, including children registered during drain. */
22
+ export class NotificationBackgroundWork {
23
+ private readonly pending = new Map<Promise<unknown>, { kind: NotificationBackgroundKind; startedAt: number }>();
24
+ private readonly counters = new Map(NOTIFICATION_BACKGROUND_KINDS.map(kind => [kind, {
25
+ completed: 0, failed: 0, lastStartedAt: null as string | null,
26
+ lastCompletedAt: null as string | null, lastFailedAt: null as string | null,
27
+ }]));
28
+ private draining = false;
29
+ private drainTimeouts = 0;
30
+ private failureReporter: ((kind: NotificationBackgroundKind) => void) | undefined;
31
+
32
+ setFailureReporter(reporter: (kind: NotificationBackgroundKind) => void): void { this.failureReporter = reporter; }
33
+ beginDrain(): void { this.draining = true; }
34
+
35
+ track<T>(kind: NotificationBackgroundKind, run: () => Promise<T>, failed?: (value: T) => boolean): Promise<T> {
36
+ // Register before run, and allow accepted continuations to register children
37
+ // after beginDrain. Kernel admission, not this tracker, stops new producers.
38
+ const startedAt = Date.now();
39
+ const counters = this.counters.get(kind)!;
40
+ counters.lastStartedAt = new Date(startedAt).toISOString();
41
+ const work = Promise.resolve().then(run);
42
+ this.pending.set(work, { kind, startedAt });
43
+ const finish = (isFailure: boolean) => {
44
+ this.pending.delete(work);
45
+ if (isFailure) {
46
+ counters.failed++;
47
+ counters.lastFailedAt = new Date().toISOString();
48
+ try { this.failureReporter?.(kind); } catch { /* diagnostic only */ }
49
+ } else {
50
+ counters.completed++;
51
+ counters.lastCompletedAt = new Date().toISOString();
52
+ }
53
+ };
54
+ // Attach a rejection handler immediately so detached callers cannot leak an
55
+ // unhandled rejection; awaited callers still receive the original rejection.
56
+ void work.then(value => {
57
+ let isFailure = false;
58
+ try { isFailure = failed?.(value) ?? false; } catch { isFailure = true; }
59
+ finish(isFailure);
60
+ }, () => finish(true));
61
+ return work;
62
+ }
63
+
64
+ snapshot(now = Date.now()): NotificationBackgroundSnapshot {
65
+ return { draining: this.draining, drainTimeouts: this.drainTimeouts,
66
+ kinds: NOTIFICATION_BACKGROUND_KINDS.map(kind => {
67
+ let inFlight = 0, oldestStartedAt = now;
68
+ for (const work of this.pending.values()) if (work.kind === kind) {
69
+ inFlight++; oldestStartedAt = Math.min(oldestStartedAt, work.startedAt);
70
+ }
71
+ return { kind, ...this.counters.get(kind)!, inFlight,
72
+ oldestPendingAgeMs: inFlight ? Math.max(0, now - oldestStartedAt) : 0 };
73
+ }) };
74
+ }
75
+
76
+ async drain(drainMs: number): Promise<boolean> {
77
+ const deadline = Date.now() + Math.max(0, drainMs);
78
+ while (this.pending.size) {
79
+ const remaining = deadline - Date.now();
80
+ if (remaining <= 0) { this.drainTimeouts++; return false; }
81
+ let timer: ReturnType<typeof setTimeout> | undefined;
82
+ try {
83
+ const drained = await Promise.race([
84
+ Promise.allSettled([...this.pending.keys()]).then(() => true),
85
+ new Promise<boolean>(resolve => { timer = setTimeout(() => resolve(false), remaining); }),
86
+ ]);
87
+ if (!drained) { this.drainTimeouts++; return false; }
88
+ } finally { if (timer) clearTimeout(timer); }
89
+ // Recheck the live set: finishing work can register later SQL or webhook work.
90
+ }
91
+ return true;
92
+ }
93
+ }
94
+
95
+ const workByStore = new WeakMap<object, NotificationBackgroundWork>();
96
+ export function bindNotificationBackgroundWork(store: object, work: NotificationBackgroundWork): void { workByStore.set(store, work); }
97
+ export function notificationBackgroundWorkFor(store: object): NotificationBackgroundWork {
98
+ let work = workByStore.get(store);
99
+ if (!work) { work = new NotificationBackgroundWork(); workByStore.set(store, work); }
100
+ return work;
101
+ }
@@ -0,0 +1,22 @@
1
+ import type { ApprovalRequeueInput, ApprovalRequeueOutcome } from '../contracts/approval-continuation';
2
+ import type { Job } from '../contracts/types';
3
+
4
+ /** Only the state adapter may commit this patch, atomically with its queue transition. */
5
+ export function approvalRequeuePlan(job: Job | null, input: ApprovalRequeueInput): { outcome: ApprovalRequeueOutcome; patch?: Partial<Job> } {
6
+ if (!job) return { outcome: 'missing' };
7
+ if (!Number.isSafeInteger(input.approval_id) || input.approval_id <= 0 || !input.decision_key
8
+ || input.decision_key.length > 160 || job.job_id !== input.job_id || job.request_id !== input.request_id
9
+ || job.target === 'agent-tool-v1') return { outcome: 'conflict' };
10
+ const key = String(input.approval_id);
11
+ const previous = job.approval_continuation_keys?.[key];
12
+ if (previous !== undefined) return { outcome: previous === input.decision_key ? 'already_queued' : 'conflict' };
13
+ if (!['done', 'error', 'rejected'].includes(job.status)) return { outcome: 'in_flight' };
14
+ const metadata = { ...job.metadata };
15
+ delete metadata.no_delivery;
16
+ return { outcome: 'queued', patch: {
17
+ status: 'queued', attempts: 0, run_after: undefined, error: undefined,
18
+ executor_id: undefined, claimed_at: undefined, lease_until: undefined,
19
+ dispatched_at: undefined, claim_token: undefined, metadata,
20
+ approval_continuation_keys: { ...job.approval_continuation_keys, [key]: input.decision_key },
21
+ } };
22
+ }
@@ -0,0 +1,19 @@
1
+ import type { Job } from '../contracts/types';
2
+ import { deliveryReplayKey, type DeliveryRequeueInput, type DeliveryRequeueOutcome } from '../contracts/delivery-replay';
3
+
4
+ export function deliveryRequeuePlan(job: Job | null, input: DeliveryRequeueInput): { outcome: DeliveryRequeueOutcome; patch?: Partial<Job> } {
5
+ if (!job) return { outcome: 'missing' };
6
+ if (!Number.isSafeInteger(input.dlq_id) || input.dlq_id <= 0 || input.replay_key !== deliveryReplayKey(input.dlq_id)
7
+ || job.job_id !== input.job_id || job.request_id !== input.request_id || job.source !== 'delivery'
8
+ || job.target !== input.target || !job.target.endsWith('-notify')) return { outcome: 'conflict' };
9
+ const previous = job.delivery_replay_keys?.[String(input.dlq_id)];
10
+ if (previous !== undefined) return { outcome: previous === input.replay_key ? 'already_queued' : 'conflict' };
11
+ if (['queued', 'running', 'dispatched'].includes(job.status)) return { outcome: 'in_flight' };
12
+ if (job.status !== 'error') return { outcome: 'conflict' };
13
+ return { outcome: 'queued', patch: {
14
+ status: 'queued', attempts: 0, run_after: undefined, error: undefined,
15
+ executor_id: undefined, claimed_at: undefined, lease_until: undefined,
16
+ dispatched_at: undefined, claim_token: undefined,
17
+ delivery_replay_keys: { ...job.delivery_replay_keys, [String(input.dlq_id)]: input.replay_key },
18
+ } };
19
+ }
@@ -31,6 +31,8 @@ export function rowToJob(r: any): Job {
31
31
  usage: parse(r.usage),
32
32
  error: r.error ?? undefined,
33
33
  metadata: parse(r.metadata) ?? {},
34
+ approval_continuation_keys: parse(r.approval_continuation_keys),
35
+ delivery_replay_keys: parse(r.delivery_replay_keys),
34
36
  callback_url: r.callback_url ?? undefined,
35
37
  dispatch: parse(r.dispatch),
36
38
  attempts: r.attempts != null ? Number(r.attempts) : 0,
@@ -1,4 +1,6 @@
1
1
  import type { AuditEntry, Job, JobStatus } from '../contracts/types';
2
+ import type { ApprovalRequeueInput, ApprovalRequeueOutcome } from '../contracts/approval-continuation';
3
+ import type { DeliveryRequeueInput, DeliveryRequeueOutcome } from '../contracts/delivery-replay';
2
4
 
3
5
  export interface JobOperationalMetricsSnapshot {
4
6
  byStatus: Record<JobStatus, number>;
@@ -48,6 +50,10 @@ export interface RuntimeLockRepository {
48
50
  }
49
51
 
50
52
  export interface RuntimeStateStore extends JobRepository, AuditLedger, RuntimeLockRepository {
53
+ /** Atomic original-job queue transition + permanent decision marker; no substitute operation. */
54
+ requeueApprovedJobOnce?(input: ApprovalRequeueInput): Promise<ApprovalRequeueOutcome>;
55
+ /** Original failed notification child + permanent DLQ key in one state transaction. */
56
+ requeueDeliveryJobOnce?(input: DeliveryRequeueInput): Promise<DeliveryRequeueOutcome>;
51
57
  init(): Promise<void>;
52
58
  /** Kernel 释放时关闭自己拥有的资源;外部实现可不提供。 */
53
59
  close?(): Promise<void>;
@@ -1,7 +1,9 @@
1
1
  import { dt, rowToolApproval } from '../../core/config/config-codec';
2
2
  import type { ToolApproval } from '../../core/contracts/types';
3
+ import type { ApprovalContinuation, ApprovalContinuationDecisionOptions } from '../../core/contracts/approval-continuation';
3
4
 
4
5
  export class ApprovalLedger {
6
+ private continuationCursor = 0;
5
7
  constructor(private readonly poolOf: () => any) {}
6
8
 
7
9
  private get pool(): any { return this.poolOf(); }
@@ -43,6 +45,72 @@ export class ApprovalLedger {
43
45
  return r?.affectedRows === 1;
44
46
  }
45
47
 
48
+ /** Decision and immutable follow-up coordinates are a single database transaction. */
49
+ async decideWithContinuation(id: number, status: 'approved' | 'denied', decidedBy: string,
50
+ opts: ApprovalContinuationDecisionOptions): Promise<'decided' | 'same' | 'conflict'> {
51
+ const conn = await this.pool.getConnection();
52
+ try {
53
+ await conn.beginTransaction();
54
+ const [rows]: any = await conn.query('SELECT * FROM bz_tool_approvals WHERE id=? FOR UPDATE', [id]);
55
+ if (!rows[0]) { await conn.commit(); return 'conflict'; }
56
+ const approval = rowToolApproval(rows[0]);
57
+ if (approval.status !== 'pending') {
58
+ const same = approval.status === status && (approval.decision_id ?? null) === (opts.decision_id ?? null);
59
+ await conn.commit();
60
+ return same ? 'same' : 'conflict';
61
+ }
62
+ const intent: ApprovalContinuation = {
63
+ schema_version: 'bailing.approval-continuation.v1', approval_id: id,
64
+ decision_key: opts.decision_id ?? `console:${id}`, decision: status,
65
+ ...(opts.decision_id ? { decision_id: opts.decision_id } : {}),
66
+ job_id: approval.job_id, request_id: approval.request_id, args_hash: approval.args_hash,
67
+ tool: approval.tool, scope: approval.scope, by: decidedBy,
68
+ source: opts.source, auth: opts.auth, mode: opts.mode,
69
+ ...(approval.policy ? { policy: approval.policy } : {}),
70
+ ...(approval.reason ? { reason: approval.reason } : {}),
71
+ ...(approval.summary ? { summary: approval.summary } : {}),
72
+ ...(opts.comment ? { comment: opts.comment } : {}),
73
+ audit_recorded: false, completed: false,
74
+ };
75
+ await conn.query("UPDATE bz_tool_approvals SET status=?,decided_by=?,decision_id=?,decision_comment=?,decided_at=? WHERE id=? AND status='pending'",
76
+ [status, decidedBy, opts.decision_id ?? null, opts.comment ?? null, dt(), id]);
77
+ await conn.query('INSERT INTO bz_approval_continuations (approval_id,intent_json,created_at) VALUES (?,?,?)',
78
+ [id, JSON.stringify(intent), dt()]);
79
+ await conn.commit();
80
+ return 'decided';
81
+ } catch (error) {
82
+ await conn.rollback().catch(() => undefined);
83
+ if ((error as { code?: string }).code === 'ER_DUP_ENTRY') return 'conflict';
84
+ throw error;
85
+ } finally { conn.release(); }
86
+ }
87
+
88
+ async getContinuation(id: number): Promise<ApprovalContinuation | null> {
89
+ const [rows]: any = await this.pool.query('SELECT * FROM bz_approval_continuations WHERE approval_id=?', [id]);
90
+ return rows[0] ? continuationRow(rows[0]) : null;
91
+ }
92
+
93
+ async pendingContinuations(limit = 25): Promise<ApprovalContinuation[]> {
94
+ const n = Math.min(Math.max(Math.trunc(limit) || 25, 1), 100);
95
+ let [rows]: any = await this.pool.query(`SELECT * FROM bz_approval_continuations WHERE completed_at IS NULL AND approval_id>? ORDER BY approval_id LIMIT ${n}`, [this.continuationCursor]);
96
+ if (!rows.length && this.continuationCursor > 0) {
97
+ this.continuationCursor = 0;
98
+ [rows] = await this.pool.query(`SELECT * FROM bz_approval_continuations WHERE completed_at IS NULL AND approval_id>? ORDER BY approval_id LIMIT ${n}`, [0]);
99
+ }
100
+ if (rows.length) this.continuationCursor = Number(rows[rows.length - 1].approval_id);
101
+ return rows.map(continuationRow);
102
+ }
103
+
104
+ async markContinuationAuditRecorded(id: number, decisionKey: string): Promise<void> {
105
+ await this.pool.query("UPDATE bz_approval_continuations SET audit_recorded_at=COALESCE(audit_recorded_at,?) WHERE approval_id=? AND JSON_UNQUOTE(JSON_EXTRACT(intent_json,'$.decision_key'))=?",
106
+ [dt(), id, decisionKey]);
107
+ }
108
+
109
+ async completeContinuation(id: number, decisionKey: string): Promise<void> {
110
+ await this.pool.query("UPDATE bz_approval_continuations SET completed_at=COALESCE(completed_at,?) WHERE approval_id=? AND audit_recorded_at IS NOT NULL AND JSON_UNQUOTE(JSON_EXTRACT(intent_json,'$.decision_key'))=?",
111
+ [dt(), id, decisionKey]);
112
+ }
113
+
46
114
  async use(id: number): Promise<boolean> {
47
115
  const [r]: any = await this.pool.query(
48
116
  "UPDATE bz_tool_approvals SET used_at=? WHERE id=? AND status='approved' AND used_at IS NULL",
@@ -88,3 +156,10 @@ export class ApprovalLedger {
88
156
  return grouped;
89
157
  }
90
158
  }
159
+
160
+ function continuationRow(row: any): ApprovalContinuation {
161
+ const intent = typeof row.intent_json === 'string' ? JSON.parse(row.intent_json) : row.intent_json;
162
+ if (!intent || intent.schema_version !== 'bailing.approval-continuation.v1'
163
+ || intent.approval_id !== Number(row.approval_id)) throw new Error('approval_continuation_invalid');
164
+ return { ...intent, audit_recorded: row.audit_recorded_at != null, completed: row.completed_at != null };
165
+ }
@@ -1,46 +1,72 @@
1
1
  import { dt } from '../../core/config/config-codec';
2
+ import { deliveryReplayKey, type DeliveryKind, type DeliveryDlqRecord } from '../../core/contracts/delivery-replay';
3
+ import { truncateUtf8 } from '../../core/platform/http-body';
2
4
 
3
5
  export class DeliveryDlqLedger {
4
6
  constructor(private readonly poolOf: () => any) {}
5
7
 
6
8
  private get pool(): any { return this.poolOf(); }
7
9
 
8
- async record(d: { parentJobId: string; channel: string; recipient: string; content: string; error: string }): Promise<void> {
10
+ async record(d: { parentJobId: string; channel: string; recipient: string; content: string; error: string; deliveryKind?: DeliveryKind; notificationJobId?: string }): Promise<void> {
9
11
  await this.pool.query(
10
- 'INSERT INTO bz_delivery_dlq (parent_job_id,channel,recipient,content,error,resolved,created_at) VALUES (?,?,?,?,?,0,?)',
11
- [d.parentJobId.slice(0, 191), d.channel.slice(0, 191), d.recipient.slice(0, 512), String(d.content ?? '').slice(0, 60000), String(d.error ?? '').slice(0, 2000), dt()],
12
+ 'INSERT INTO bz_delivery_dlq (parent_job_id,channel,recipient,content,error,delivery_kind,notification_job_id,resolved,created_at) VALUES (?,?,?,?,?,?,?,0,?)',
13
+ [d.parentJobId.slice(0, 191), d.channel.slice(0, 191), d.recipient.slice(0, 512), truncateUtf8(String(d.content ?? ''), 60000), String(d.error ?? '').slice(0, 2000), d.deliveryKind ?? null, d.notificationJobId?.slice(0, 191) ?? null, dt()],
12
14
  );
13
15
  }
14
16
 
15
- async list(includeResolved = false, limit = 100): Promise<Array<{ id: number; parent_job_id: string; channel: string; recipient: string; content_preview: string; error: string; resolved: boolean; created_at: string; resolved_at: string | null }>> {
17
+ async list(includeResolved = false, limit = 100): Promise<Array<{ id: number; parent_job_id: string; channel: string; recipient: string; content_preview: string; error: string; resolved: boolean; created_at: string; resolved_at: string | null; delivery_kind?: DeliveryKind | null; notification_job_id?: string | null; executor_replay_key?: string | null }>> {
16
18
  const n = Math.min(Math.max(Number(limit) || 100, 1), 500);
17
19
  const [rows] = await this.pool.query(
18
- `SELECT id,parent_job_id,channel,recipient,LEFT(content,500) AS content_preview,error,resolved,created_at,resolved_at FROM bz_delivery_dlq ${includeResolved ? '' : 'WHERE resolved=0'} ORDER BY id DESC LIMIT ${n}`,
20
+ `SELECT id,parent_job_id,channel,recipient,LEFT(content,500) AS content_preview,error,resolved,created_at,resolved_at,delivery_kind,notification_job_id,executor_replay_key FROM bz_delivery_dlq ${includeResolved ? '' : 'WHERE resolved=0'} ORDER BY id DESC LIMIT ${n}`,
19
21
  );
20
22
  return (rows as any[]).map((r) => ({
21
23
  id: Number(r.id), parent_job_id: r.parent_job_id, channel: r.channel, recipient: r.recipient,
22
24
  content_preview: r.content_preview ?? '', error: r.error ?? '', resolved: !!r.resolved,
25
+ delivery_kind: r.delivery_kind, notification_job_id: r.notification_job_id, executor_replay_key: r.executor_replay_key,
23
26
  created_at: new Date(r.created_at).toISOString(), resolved_at: r.resolved_at ? new Date(r.resolved_at).toISOString() : null,
24
27
  }));
25
28
  }
26
29
 
27
- async listByParentJob(parentJobId: string, includeResolved = true, limit = 100): Promise<Array<{ id: number; parent_job_id: string; channel: string; recipient: string; content_preview: string; error: string; resolved: boolean; created_at: string; resolved_at: string | null }>> {
30
+ async listByParentJob(parentJobId: string, includeResolved = true, limit = 100): Promise<Array<{ id: number; parent_job_id: string; channel: string; recipient: string; content_preview: string; error: string; resolved: boolean; created_at: string; resolved_at: string | null; delivery_kind?: DeliveryKind | null; notification_job_id?: string | null; executor_replay_key?: string | null }>> {
28
31
  const n = Math.min(Math.max(Number(limit) || 100, 1), 500);
29
32
  const [rows] = await this.pool.query(
30
- `SELECT id,parent_job_id,channel,recipient,LEFT(content,500) AS content_preview,error,resolved,created_at,resolved_at FROM bz_delivery_dlq WHERE parent_job_id=? ${includeResolved ? '' : 'AND resolved=0'} ORDER BY id DESC LIMIT ${n}`,
33
+ `SELECT id,parent_job_id,channel,recipient,LEFT(content,500) AS content_preview,error,resolved,created_at,resolved_at,delivery_kind,notification_job_id,executor_replay_key FROM bz_delivery_dlq WHERE parent_job_id=? ${includeResolved ? '' : 'AND resolved=0'} ORDER BY id DESC LIMIT ${n}`,
31
34
  [parentJobId],
32
35
  );
33
36
  return (rows as any[]).map((r) => ({
34
37
  id: Number(r.id), parent_job_id: r.parent_job_id, channel: r.channel, recipient: r.recipient,
35
38
  content_preview: r.content_preview ?? '', error: r.error ?? '', resolved: !!r.resolved,
39
+ delivery_kind: r.delivery_kind, notification_job_id: r.notification_job_id, executor_replay_key: r.executor_replay_key,
36
40
  created_at: new Date(r.created_at).toISOString(), resolved_at: r.resolved_at ? new Date(r.resolved_at).toISOString() : null,
37
41
  }));
38
42
  }
39
43
 
40
- async get(id: number): Promise<{ id: number; channel: string; recipient: string; content: string; resolved: boolean } | null> {
41
- const [rows] = await this.pool.query('SELECT id,channel,recipient,content,resolved FROM bz_delivery_dlq WHERE id=? LIMIT 1', [id]);
44
+ async get(id: number): Promise<DeliveryDlqRecord | null> {
45
+ const [rows] = await this.pool.query('SELECT id,parent_job_id,channel,recipient,content,resolved,delivery_kind,notification_job_id,executor_replay_key FROM bz_delivery_dlq WHERE id=? LIMIT 1', [id]);
42
46
  const r = (rows as any[])[0];
43
- return r ? { id: Number(r.id), channel: r.channel, recipient: r.recipient, content: r.content ?? '', resolved: !!r.resolved } : null;
47
+ return r ? { id: Number(r.id), parent_job_id: r.parent_job_id, channel: r.channel, recipient: r.recipient,
48
+ content: r.content ?? '', resolved: !!r.resolved, delivery_kind: r.delivery_kind,
49
+ notification_job_id: r.notification_job_id, executor_replay_key: r.executor_replay_key } : null;
50
+ }
51
+
52
+ /** Stable replay identity is initialized once; it never acts as an expiring owner lease. */
53
+ async ensureExecutorReplay(id: number, notificationJobId: string): Promise<{ key: string; created: boolean } | null> {
54
+ const key = deliveryReplayKey(id);
55
+ const conn = await this.pool.getConnection();
56
+ try {
57
+ await conn.beginTransaction();
58
+ const [rows] = await conn.query('SELECT * FROM bz_delivery_dlq WHERE id=? FOR UPDATE', [id]);
59
+ const row = (rows as any[])[0];
60
+ if (!row || row.resolved) { await conn.commit(); return null; }
61
+ if (row.parent_job_id !== notificationJobId || (row.notification_job_id && row.notification_job_id !== notificationJobId)
62
+ || (row.delivery_kind && row.delivery_kind !== 'executor_target') || (row.executor_replay_key && row.executor_replay_key !== key)) throw new Error('delivery_dlq_replay_conflict');
63
+ const created = !row.executor_replay_key;
64
+ if (created) await conn.query("UPDATE bz_delivery_dlq SET delivery_kind='executor_target',notification_job_id=?,executor_replay_key=? WHERE id=?", [notificationJobId, key, id]);
65
+ await conn.commit();
66
+ return { key, created };
67
+ } catch (error) {
68
+ await conn.rollback().catch(() => undefined); throw error;
69
+ } finally { conn.release(); }
44
70
  }
45
71
 
46
72
  async resolve(id: number): Promise<void> {
@@ -53,8 +53,8 @@ export type ChatConfigRepositoryContract = Pick<ChatConfigRepository, keyof Chat
53
53
  export type RateLimitLedgerContract = Omit<Pick<RateLimitLedger, keyof RateLimitLedger>, 'consumeAll'>
54
54
  & Partial<Pick<RateLimitLedger, 'consumeAll'>>;
55
55
  export type ApprovalLedgerContract =
56
- Omit<Pick<ApprovalLedger, keyof ApprovalLedger>, 'forJobs'>
57
- & Partial<Pick<ApprovalLedger, 'forJobs'>>;
56
+ Omit<Pick<ApprovalLedger, keyof ApprovalLedger>, 'forJobs' | 'decideWithContinuation' | 'getContinuation' | 'pendingContinuations' | 'markContinuationAuditRecorded' | 'completeContinuation'>
57
+ & Partial<Pick<ApprovalLedger, 'forJobs' | 'decideWithContinuation' | 'getContinuation' | 'pendingContinuations' | 'markContinuationAuditRecorded' | 'completeContinuation'>>;
58
58
  export type ConversationLedgerContract = Pick<ConversationLedger, keyof ConversationLedger>;
59
59
  export type ExecutorLedgerContract = Pick<ExecutorLedger, keyof ExecutorLedger>;
60
60
  export type ToolCallLedgerContract = Pick<ToolCallLedger, keyof ToolCallLedger>;
@@ -63,7 +63,8 @@ export type ToolEmbeddingRepositoryContract = ToolEmbeddingRepository;
63
63
  export type KnowledgeRepositoryContract = Pick<MysqlKnowledgeRepository, keyof MysqlKnowledgeRepository>;
64
64
  export type KbDatasourceRepositoryContract = Pick<MysqlKbDatasourceRepository, keyof MysqlKbDatasourceRepository>;
65
65
  export type { InstanceBrandingRepositoryContract };
66
- export type DeliveryDlqLedgerContract = Pick<DeliveryDlqLedger, keyof DeliveryDlqLedger>;
66
+ export type DeliveryDlqLedgerContract = Pick<DeliveryDlqLedger, Exclude<keyof DeliveryDlqLedger, 'ensureExecutorReplay'>>
67
+ & Partial<Pick<DeliveryDlqLedger, 'ensureExecutorReplay'>>;
67
68
  export type ObservabilityLedgerContract =
68
69
  Omit<Pick<ObservabilityLedger, keyof ObservabilityLedger>, 'operationalMetricsSnapshot' | 'agentToolJobCandidatesForRun' | 'auditsForJobs'>
69
70
  & Partial<Pick<ObservabilityLedger, 'operationalMetricsSnapshot' | 'agentToolJobCandidatesForRun' | 'auditsForJobs'>>;