bailinghub 0.9.1 → 0.9.2

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 (74) 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 +59 -0
  7. package/docs/CORE_RELIABILITY.md +59 -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 +22 -14
  11. package/docs/IMPLEMENTATION_STATUS.md +23 -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/README.en.md +5 -0
  21. package/docs/README.md +5 -0
  22. package/docs/RELEASE_NOTES_v0.9.2.en.md +45 -0
  23. package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
  24. package/docs/UPGRADE_v0.9.2.en.md +62 -0
  25. package/docs/UPGRADE_v0.9.2.md +62 -0
  26. package/package.json +7 -3
  27. package/scripts/check-doc-links.mjs +2 -0
  28. package/scripts/check-image-tags.sh +1 -1
  29. package/scripts/check-release-consistency.test.mjs +2 -2
  30. package/scripts/doctor-deployment.test.ts +419 -0
  31. package/scripts/doctor-deployment.ts +357 -0
  32. package/scripts/doctor.ts +8 -1
  33. package/scripts/install-secrets.test.mjs +185 -0
  34. package/scripts/install.sh +10 -6
  35. package/scripts/publish-images.sh +1 -1
  36. package/scripts/release-audit.mjs +4 -0
  37. package/scripts/verify-github-repo.mjs +4 -0
  38. package/sql/065_usage_reconciliation_scan.sql +4 -0
  39. package/sql/066_approval_continuations.sql +15 -0
  40. package/sql/README.md +9 -0
  41. package/src/app/approval-continuations.mysql.test.ts +138 -0
  42. package/src/app/approval-continuations.test.ts +325 -0
  43. package/src/app/approval-continuations.ts +107 -0
  44. package/src/app/http-server.ts +3 -0
  45. package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
  46. package/src/app/kernel.ts +13 -0
  47. package/src/app/runtime-evidence-maintenance.test.ts +55 -0
  48. package/src/app/runtime-lifecycle-default.ts +7 -0
  49. package/src/app/runtime-lifecycle.ts +39 -0
  50. package/src/core/contracts/approval-continuation.ts +43 -0
  51. package/src/core/contracts/types.ts +2 -0
  52. package/src/core/state/approval-continuation.ts +22 -0
  53. package/src/core/state/state-codec.ts +1 -0
  54. package/src/core/state/state-contracts.ts +3 -0
  55. package/src/infrastructure/config/config-approval-ledger.ts +75 -0
  56. package/src/infrastructure/config/configstore.ts +2 -2
  57. package/src/infrastructure/state/state-jsonl.ts +41 -11
  58. package/src/infrastructure/state/state-mysql.ts +27 -0
  59. package/src/modules/usage/billing-reconciliation.mysql.test.ts +163 -0
  60. package/src/modules/usage/billing-reconciliation.test.ts +71 -0
  61. package/src/modules/usage/billing-repository.ts +54 -11
  62. package/src/modules/usage/maintenance.test.ts +62 -0
  63. package/src/modules/usage/maintenance.ts +31 -0
  64. package/src/modules/usage/model-gateway.ts +2 -1
  65. package/src/routes/admin-default.ts +2 -2
  66. package/src/routes/admin-runtime-default.ts +2 -2
  67. package/src/routes/admin-runtime.test.ts +1 -1
  68. package/src/routes/admin-runtime.ts +25 -18
  69. package/src/routes/admin.ts +1 -1
  70. package/src/routes/approvals-default.ts +2 -2
  71. package/src/routes/approvals.ts +30 -33
  72. package/src/routes/critical-routes.test.ts +16 -3
  73. package/src/test-support/approval-continuation-crash-child.ts +24 -0
  74. package/src/test-support/model-process-crash-child.ts +78 -0
@@ -61,6 +61,14 @@ function publicRawUsage(raw: Record<string, unknown> | null): Record<string, unk
61
61
  return out;
62
62
  }
63
63
  const RESULT_RETENTION_MS = 7 * 86_400_000;
64
+ // Settlement never needs the model result body (images may contain MiB of Base64).
65
+ const SETTLEMENT_COLUMNS = `id,operation_id,account_id,user_id,session_id,service_id,conversation_id,turn_id,
66
+ request_hash,revision,state,result_state,billing_state,service_revision,service_json,model,fence,grant_id,
67
+ grant_revision,grant_json,billing_rate_json,period_start,period_end,result_hash,usage_json,raw_usage_json,
68
+ execution_key,reference_cost_usd,billed_usd,overage_usd,cancelled_at,resolution,created_at,updated_at,NULL AS result_json`;
69
+ export interface UsageReconciliationProgress {
70
+ scanned: number; settled: number; deferred: number; failed: number; hasMore: boolean;
71
+ }
64
72
 
65
73
  /** Current plan models share the account grant's original allowance and periods. */
66
74
  export class BillingRepository {
@@ -300,11 +308,11 @@ export class BillingRepository {
300
308
  return { ...request((await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=?', [id]))[0]!), created: true };
301
309
  });
302
310
  }
303
- private async locked(c: PoolConnection, id: string): Promise<Row> {
311
+ private async locked(c: PoolConnection, id: string, resultBody = true): Promise<Row> {
304
312
  const hint = (await rows(c, 'SELECT account_id FROM bz_usage_billing_requests WHERE id=?', [billingKey(id)]))[0];
305
313
  usageAssert(hint, 'USAGE_OPERATION_NOT_FOUND', 'Original model request not found.', 404);
306
314
  await this.lockAccount(c, hint.account_id);
307
- return (await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=? FOR UPDATE', [id]))[0]!;
315
+ return (await rows(c, `SELECT ${resultBody ? '*' : SETTLEMENT_COLUMNS} FROM bz_usage_billing_requests WHERE id=? FOR UPDATE`, [id]))[0]!;
308
316
  }
309
317
  async commitDispatch(id: string, actor: UsageActor): Promise<BillingRequest> {
310
318
  return this.repository.withTransaction(async c => {
@@ -371,15 +379,16 @@ export class BillingRepository {
371
379
  private async settleRecorded(recorded: BillingRequest): Promise<BillingRequest> {
372
380
  try {
373
381
  return await this.repository.withTransaction(async c => {
374
- const r = await this.locked(c, recorded.id);
382
+ const r = await this.locked(c, recorded.id, false);
383
+ const receipt = (row: Row): BillingRequest => ({ ...request(row), response: recorded.response });
375
384
  usageAssert(r.fence === recorded.fence, 'USAGE_FENCE_CONFLICT', 'Settlement does not match the original dispatch.');
376
- if (r.billing_state === 'settled' || (!r.usage_json && !r.raw_usage_json) || !r.result_hash) return request(r);
385
+ if (r.billing_state === 'settled' || (!r.usage_json && !r.raw_usage_json) || !r.result_hash) return receipt(r);
377
386
  const measured = r.usage_json ? tokenUsage(json(r.usage_json)) : null;
378
387
  const p = (await rows(c, 'SELECT * FROM bz_usage_billing_periods WHERE grant_id=? AND period_start=? FOR UPDATE', [r.grant_id, r.period_start]))[0];
379
388
  usageAssert(p, 'METERING_UNAVAILABLE', 'The original allowance pool is unavailable.', 503);
380
389
  const rate = request(r).billingRate;
381
390
  const referenceCost = calculateReferenceCost(rate.price, { ...(json<Record<string, unknown>>(r.raw_usage_json) ?? {}), ...(measured ?? {}) });
382
- if (referenceCost === null) return request(r);
391
+ if (referenceCost === null) return receipt(r);
383
392
  const charged = billedUsdMicros(referenceCost, rate.multiplier);
384
393
  const before = usdMicros(p.consumed_usd), after = before + charged, quota = usdMicros(p.allowance_usd);
385
394
  const overage = positivePart(after - quota) - positivePart(before - quota), now = await this.now(c);
@@ -390,7 +399,7 @@ export class BillingRepository {
390
399
  await c.query('INSERT INTO bz_usage_billing_ledger(request_id,account_id,grant_id,period_start,input_tokens,output_tokens,reference_cost_usd,billed_usd,overage_usd,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)',
391
400
  [r.id, r.account_id, r.grant_id, r.period_start, measured?.inputTokens ?? null, measured?.outputTokens ?? null, referenceCost, chargedValue, overageValue, now]);
392
401
  await c.query("UPDATE bz_usage_billing_requests SET billing_state='settled',reference_cost_usd=?,billed_usd=?,overage_usd=?,resolution='actual_usage',revision=revision+1,updated_at=? WHERE id=?", [referenceCost, chargedValue, overageValue, now, r.id]);
393
- return request((await rows(c, 'SELECT * FROM bz_usage_billing_requests WHERE id=?', [r.id]))[0]!);
402
+ return receipt((await rows(c, `SELECT ${SETTLEMENT_COLUMNS} FROM bz_usage_billing_requests WHERE id=?`, [r.id]))[0]!);
394
403
  });
395
404
  } catch (e) {
396
405
  if (e instanceof UsageError && e.status < 500) throw e;
@@ -402,11 +411,45 @@ export class BillingRepository {
402
411
  integer(now, 'now');
403
412
  await this.repository.getPool().query('UPDATE bz_usage_billing_requests SET result_json=NULL WHERE created_at<? AND result_json IS NOT NULL AND result_hash IS NOT NULL LIMIT 500', [now - RESULT_RETENTION_MS]);
404
413
  }
405
- async reconcilePendingUsage(): Promise<void> {
406
- // Only previously saved supplier evidence may settle in maintenance. This
407
- // path has no credentials/provider transport and cannot create model work.
408
- const pending = await rows(this.repository.getPool(), "SELECT * FROM bz_usage_billing_requests WHERE billing_state='pending' AND (usage_json IS NOT NULL OR raw_usage_json IS NOT NULL) AND result_hash IS NOT NULL AND fence IS NOT NULL ORDER BY updated_at,id LIMIT 50");
409
- for (const row of pending) await this.settleRecorded(request(row));
414
+ private reconciliationCursor: { updatedAt: number; id: string } | null = null;
415
+ private reconciliationFlight: Promise<void> | null = null;
416
+ private reconciliationProgress: UsageReconciliationProgress = { scanned: 0, settled: 0, deferred: 0, failed: 0, hasMore: false };
417
+ getReconciliationProgress(): UsageReconciliationProgress { return { ...this.reconciliationProgress }; }
418
+ reconcilePendingUsage(): Promise<void> {
419
+ if (this.reconciliationFlight) return this.reconciliationFlight;
420
+ const work = this.reconcilePage();
421
+ this.reconciliationFlight = work;
422
+ void work.finally(() => { if (this.reconciliationFlight === work) this.reconciliationFlight = null; }).catch(() => {});
423
+ return work;
424
+ }
425
+ private async reconcilePage(): Promise<void> {
426
+ // Only durable supplier evidence is read. The constant-size owner cursor
427
+ // advances past unpriceable/failing records; no row can pin the oldest page.
428
+ // A new owner starts from the beginning, then makes the same bounded progress.
429
+ const progress: UsageReconciliationProgress = { scanned: 0, settled: 0, deferred: 0, failed: 0, hasMore: false };
430
+ this.reconciliationProgress = progress;
431
+ const scan = () => {
432
+ const cursor = this.reconciliationCursor;
433
+ return rows(this.repository.getPool(), `SELECT id,updated_at FROM bz_usage_billing_requests
434
+ WHERE billing_state='pending' AND (usage_json IS NOT NULL OR raw_usage_json IS NOT NULL)
435
+ AND result_hash IS NOT NULL AND fence IS NOT NULL
436
+ ${cursor ? 'AND (updated_at>? OR (updated_at=? AND id>?))' : ''}
437
+ ORDER BY updated_at,id LIMIT 50`, cursor ? [cursor.updatedAt, cursor.updatedAt, cursor.id] : []);
438
+ };
439
+ let pending = await scan();
440
+ if (!pending.length && this.reconciliationCursor) { this.reconciliationCursor = null; pending = await scan(); }
441
+ for (const item of pending) {
442
+ this.reconciliationCursor = { updatedAt: Number(item.updated_at), id: String(item.id) };
443
+ progress.scanned++;
444
+ try {
445
+ const row = (await rows(this.repository.getPool(), `SELECT ${SETTLEMENT_COLUMNS} FROM bz_usage_billing_requests WHERE id=?`, [item.id]))[0];
446
+ if (!row || row.billing_state !== 'pending') continue;
447
+ const result = await this.settleRecorded(request(row));
448
+ if (result.billingState === 'settled') progress.settled++; else progress.deferred++;
449
+ } catch { progress.failed++; } // One poison row never prevents subsequent original evidence from settling.
450
+ }
451
+ progress.hasMore = pending.length === 50;
452
+ if (!progress.hasMore) this.reconciliationCursor = null;
410
453
  }
411
454
  /** Persist a terminal rejection independently of settlement; never dispatch again. */
412
455
  async recordProviderFailure(id: string, fence: string, failure: ProviderFailure): Promise<BillingRequest> {
@@ -0,0 +1,62 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { UsageRepository } from './repository';
4
+ import { getBillingRepository } from './billing-repository';
5
+ import { runUsageMaintenanceFor } from './maintenance';
6
+
7
+ function owner() {
8
+ const repository = new UsageRepository(() => { throw new Error('No database is used in this synthetic port test'); });
9
+ const tokens = getBillingRepository(repository);
10
+ tokens.ready = async () => true;
11
+ return { repository, tokens };
12
+ }
13
+ test('startup/tick/HTTP share one registered reconciliation and close drains it', async () => {
14
+ const { repository, tokens } = owner();
15
+ let release!: () => void, calls = 0;
16
+ tokens.reconcilePendingUsage = async () => { calls++; await new Promise<void>(resolve => { release = resolve; }); };
17
+ const first = runUsageMaintenanceFor(repository, 1);
18
+ assert.equal(runUsageMaintenanceFor(repository, 1), first);
19
+ await new Promise(resolve => setImmediate(resolve));
20
+ assert.equal(calls, 1);
21
+ repository.backgroundWork.beginDrain();
22
+ assert.equal(await repository.backgroundWork.drain(1), false);
23
+ await runUsageMaintenanceFor(repository, 100000);
24
+ assert.equal(calls, 1);
25
+ release(); await first;
26
+ assert.equal(await repository.backgroundWork.drain(1000), true);
27
+ });
28
+ test('one owner failure backs off safely while a different owner progresses', async () => {
29
+ const one = owner(), two = owner();
30
+ let failing = true, attempts = 0, independent = 0;
31
+ const warnings: string[] = [];
32
+ one.repository.backgroundWork.setFailureReporter(kind => warnings.push(kind));
33
+ one.tokens.reconcilePendingUsage = async () => { attempts++; if (failing) throw new Error('SYNTHETIC_PRIVATE_SQL_MUST_NOT_ESCAPE'); };
34
+ two.tokens.reconcilePendingUsage = async () => { independent++; };
35
+ await runUsageMaintenanceFor(one.repository, 1000);
36
+ await runUsageMaintenanceFor(one.repository, 60999);
37
+ await runUsageMaintenanceFor(two.repository, 1000);
38
+ assert.equal(attempts, 1); assert.equal(independent, 1);
39
+ assert.deepEqual(warnings, ['usage-reconciliation']);
40
+ failing = false;
41
+ await runUsageMaintenanceFor(one.repository, 61000);
42
+ await runUsageMaintenanceFor(one.repository, 61001);
43
+ assert.equal(attempts, 3); // A successful scan clears failure backoff.
44
+ });
45
+ test('optional usage absence and a missing repository do not create model work', async () => {
46
+ const { repository, tokens } = owner(); let calls = 0;
47
+ tokens.ready = async () => false;
48
+ tokens.reconcilePendingUsage = async () => { calls++; };
49
+ await runUsageMaintenanceFor(null);
50
+ await runUsageMaintenanceFor(repository);
51
+ assert.equal(calls, 0);
52
+ });
53
+
54
+ test('a slow SQL failure starts its bounded retry delay at failure completion', async () => {
55
+ const { repository, tokens } = owner(); let clock = 1, attempts = 0, fail = true;
56
+ tokens.reconcilePendingUsage = async () => { attempts++; if (fail) { clock = 120000; throw new Error('Synthetic slow SQL failure'); } };
57
+ await runUsageMaintenanceFor(repository, () => clock);
58
+ fail = false; clock = 179999;
59
+ await runUsageMaintenanceFor(repository, () => clock); assert.equal(attempts, 1);
60
+ clock = 180000;
61
+ await runUsageMaintenanceFor(repository, () => clock); assert.equal(attempts, 2);
62
+ });
@@ -0,0 +1,31 @@
1
+ import { getBillingRepository } from './billing-repository';
2
+ import type { UsageRepository } from './repository';
3
+
4
+ const RETRY_MIN_MS = 60_000;
5
+ const RETRY_MAX_MS = 5 * 60_000;
6
+ interface MaintenanceState { flight: Promise<void> | null; retryAt: number; failures: number }
7
+ const owners = new WeakMap<UsageRepository, MaintenanceState>();
8
+
9
+ /** Shared startup/tick/HTTP fallback port. No timer, credentials or provider transport. */
10
+ export function runUsageMaintenanceFor(repository: UsageRepository | null, clock: number | (() => number) = () => performance.now()): Promise<void> {
11
+ if (!repository || !repository.backgroundWork.acceptingRequests) return Promise.resolve();
12
+ const now = typeof clock === 'function' ? clock : () => clock;
13
+ let state = owners.get(repository);
14
+ if (!state) { state = { flight: null, retryAt: 0, failures: 0 }; owners.set(repository, state); }
15
+ if (state.flight) return state.flight;
16
+ if (now() < state.retryAt) return Promise.resolve();
17
+ const owner = state, tokens = getBillingRepository(repository);
18
+ const work = repository.backgroundWork.startMaintenance('usage-reconciliation', async () => {
19
+ // Optional usage remains optional; initialize a Kernel without installing it.
20
+ if (await tokens.ready()) await tokens.reconcilePendingUsage();
21
+ });
22
+ if (!work) return Promise.resolve();
23
+ owner.flight = work.then(() => {
24
+ owner.failures = 0; owner.retryAt = 0;
25
+ }, () => {
26
+ // The registry reports only the fixed work kind. No raw DB/provider error escapes.
27
+ owner.failures = Math.min(owner.failures + 1, 4);
28
+ owner.retryAt = now() + Math.min(RETRY_MAX_MS, RETRY_MIN_MS * 2 ** (owner.failures - 1));
29
+ }).finally(() => { owner.flight = null; });
30
+ return owner.flight;
31
+ }
@@ -13,6 +13,7 @@ import { authenticateUsageRequest, getUsageIdentity, usageFields, usageString, t
13
13
  import { usageHttpError } from './http';
14
14
  import { canonicalJson, executeProvider, normalizeModelRequest, providerBody, type UsageModelRequest } from './provider';
15
15
  import { UsageStreamWriter } from './stream-http';
16
+ import { runUsageMaintenanceFor } from './maintenance';
16
17
  import { getBillingRepository } from './billing-repository';
17
18
  import type { UsageRepository } from './repository';
18
19
  import { referencePricing } from './pricing';
@@ -36,7 +37,7 @@ function scheduleResponseCleanup(repository: UsageRepository): void {
36
37
  // cleanup is retried on later traffic; expired bodies are never returned meanwhile.
37
38
  const tokens = getBillingRepository(repository);
38
39
  void repository.backgroundWork.startMaintenance('response-cleanup', () => tokens.cleanupExpiredResponses(now))?.catch(() => {});
39
- void repository.backgroundWork.startMaintenance('usage-reconciliation', () => tokens.reconcilePendingUsage())?.catch(() => {});
40
+ void runUsageMaintenanceFor(repository);
40
41
  }
41
42
 
42
43
  export const MODEL_GATEWAY_CAPABILITIES = {
@@ -2,7 +2,7 @@
2
2
  // 自定义部署应使用 admin.ts 的 handleAdminApiFor(deps, ...)。
3
3
  import type { IncomingMessage, ServerResponse } from 'node:http';
4
4
  import { channelSend } from '../app/channels-default';
5
- import { requeueForRerun } from '../app/engine-default';
5
+ import { kickInhubScheduler, requeueForRerun } from '../app/engine-default';
6
6
  import { now, sleep } from '../app/http';
7
7
  import { cfg, cfgStore, edition, isPaused, kbService, kbSync, queue, store, targetRegistry, toolIndex } from '../app/runtime';
8
8
  import type { Principal } from '../app/auth';
@@ -25,7 +25,7 @@ export function defaultAdminApiDeps(): AdminApiDeps {
25
25
  sleep,
26
26
  queueStats: () => queue.stats(),
27
27
  channelSend,
28
- engineRuntime: { requeueForRerun },
28
+ engineRuntime: { requeueForRerun, kickInhubScheduler },
29
29
  refreshTargets,
30
30
  targetRegistry,
31
31
  demoDataset: cfgStore ? new DemoDatasetService(cfgStore, cfg.demoDataset) : null,
@@ -2,7 +2,7 @@
2
2
  // 自定义部署应使用 admin-runtime.ts 的 handleAdminRuntimeApiFor(deps, ...)。
3
3
  import type { IncomingMessage, ServerResponse } from 'node:http';
4
4
  import { channelSend } from '../app/channels-default';
5
- import { requeueForRerun } from '../app/engine-default';
5
+ import { requeueForRerun, kickInhubScheduler } from '../app/engine-default';
6
6
  import { now } from '../app/http';
7
7
  import { cfgStore, isPaused, queue, store } from '../app/runtime';
8
8
  import type { Principal } from '../app/auth';
@@ -16,7 +16,7 @@ export function defaultAdminRuntimeApiDeps(): AdminRuntimeApiDeps {
16
16
  isPaused,
17
17
  queueStats: () => queue.stats(),
18
18
  channelSend,
19
- engineRuntime: { requeueForRerun },
19
+ engineRuntime: { requeueForRerun, kickInhubScheduler },
20
20
  };
21
21
  }
22
22
 
@@ -136,7 +136,7 @@ function depsFor(agentRun = run()) {
136
136
  isPaused: () => false,
137
137
  queueStats: () => ({}),
138
138
  channelSend: async () => ({ ok: true as const }),
139
- engineRuntime: { requeueForRerun: async () => undefined },
139
+ engineRuntime: { requeueForRerun: async () => undefined, kickInhubScheduler: () => undefined },
140
140
  };
141
141
  }
142
142
 
@@ -13,6 +13,7 @@ import type { AgentClientRunRecord } from '../infrastructure/config/config-agent
13
13
  import type { Principal } from '../app/auth';
14
14
  import type { ChannelMessage, ChannelSendResult } from '../app/channels';
15
15
  import { isAgentToolInvocationJob } from '../app/agent-tool-job';
16
+ import { continueApprovalDecisionFor, supportsApprovalContinuations } from '../app/approval-continuations';
16
17
 
17
18
  export type AdminChannelSender = (channelName: string, recipient: string, message: string | ChannelMessage) => Promise<ChannelSendResult>;
18
19
 
@@ -152,7 +153,7 @@ export interface AdminRuntimeApiDeps {
152
153
  isPaused: () => boolean;
153
154
  queueStats: () => unknown;
154
155
  channelSend: AdminChannelSender;
155
- engineRuntime: Pick<EngineRuntime, 'requeueForRerun'>;
156
+ engineRuntime: Pick<EngineRuntime, 'requeueForRerun' | 'kickInhubScheduler'>;
156
157
  }
157
158
 
158
159
  export async function handleAdminRuntimeApiFor(
@@ -475,27 +476,33 @@ export async function handleAdminRuntimeApiFor(
475
476
  const action = mApproval[2] as 'approve' | 'deny';
476
477
  const appr = await configStore.approvals.get(id);
477
478
  if (!appr) { send(res, 404, { error: '审批单不存在' }); return true; }
478
- if (appr.status !== 'pending') { send(res, 400, { error: `审批单已是 ${appr.status},不可重复裁决` }); return true; }
479
+ const decision = action === 'approve' ? 'approved' : 'denied';
480
+ if (appr.status !== 'pending' && (appr.status !== decision || appr.decision_id)) {
481
+ send(res, 409, { error: `审批单已是 ${appr.status},不可重复裁决` }); return true;
482
+ }
479
483
  const by = principal.kind === 'admin' ? principal.username ?? 'token' : '?';
480
- if (!(await configStore.approvals.decide(id, action === 'approve' ? 'approved' : 'denied', by))) {
481
- send(res, 409, { error: '审批单状态已变化,请刷新后重试' });
482
- return true;
484
+ const continuationDeps = { configStore, stateStore, engineRuntime: deps.engineRuntime, now: deps.now };
485
+ if (!supportsApprovalContinuations(continuationDeps)) {
486
+ send(res, 503, { error: '审批持久续办需要配套状态与配置仓储', code: 'approval_continuations_unavailable' }); return true;
483
487
  }
484
- await stateStore.appendAudit({
485
- ts: deps.now(), job_id: appr.job_id, request_id: appr.request_id,
486
- event: action === 'approve' ? 'tool_approved' : 'tool_denied',
487
- detail: { approval_id: id, tool: appr.tool, scope: appr.scope, by, policy: appr.policy, reason: appr.reason, summary: appr.summary },
488
- });
489
- // 批准 → 自动重跑原任务(任务在途则不动:运行中会自然消费批准单)
490
- let rerun = false;
491
- if (action === 'approve') {
488
+ let recorded: 'decided' | 'same' | 'conflict';
489
+ try {
492
490
  const job = await stateStore.getJob(appr.job_id);
493
- if (job && !isAgentToolInvocationJob(job) && (job.status === 'done' || job.status === 'error' || job.status === 'rejected')) {
494
- await deps.engineRuntime.requeueForRerun(job, by, `approval_${id}`);
495
- rerun = true;
496
- }
491
+ if (!job) { send(res, 404, { error: '审批单关联任务不存在' }); return true; }
492
+ recorded = await configStore.approvals.decideWithContinuation!(id, decision, by, {
493
+ source: 'console', auth: 'admin-console', mode: isAgentToolInvocationJob(job) ? 'manual' : 'rerun',
494
+ });
495
+ } catch {
496
+ send(res, 503, { error: '审批决策持久化暂不可用,请重试原审批单', code: 'approval_continuations_unavailable' }); return true;
497
+ }
498
+ if (recorded === 'conflict') { send(res, 409, { error: '审批单状态已变化,请刷新后重试' }); return true; }
499
+ try {
500
+ const continued = await continueApprovalDecisionFor(continuationDeps, id);
501
+ send(res, 200, { ok: true, id, status: decision, idempotent: recorded === 'same',
502
+ rerun: continued.rerun, continuation_pending: continued.pending });
503
+ } catch {
504
+ send(res, 503, { error: '审批决策已保存,原任务续办等待恢复', decision_recorded: true, continuation_pending: true });
497
505
  }
498
- send(res, 200, { ok: true, id, status: action === 'approve' ? 'approved' : 'denied', rerun });
499
506
  return true;
500
507
  }
501
508
 
@@ -50,7 +50,7 @@ export interface AdminApiDeps {
50
50
  sleep: (ms: number) => Promise<void>;
51
51
  queueStats: () => unknown;
52
52
  channelSend: AdminChannelSender;
53
- engineRuntime: Pick<EngineRuntime, 'requeueForRerun'>;
53
+ engineRuntime: Pick<EngineRuntime, 'requeueForRerun' | 'kickInhubScheduler'>;
54
54
  refreshTargets: typeof refreshTargets;
55
55
  targetRegistry?: TargetRegistry;
56
56
  /** Trusted same-origin mount prefix used by the self-smoke loopback client. */
@@ -3,7 +3,7 @@
3
3
  import type { IncomingMessage, ServerResponse } from 'node:http';
4
4
  import { cfg, cfgStore, store } from '../app/runtime';
5
5
  import { now, sleep } from '../app/http';
6
- import { requeueForRerun } from '../app/engine-default';
6
+ import { kickInhubScheduler } from '../app/engine-default';
7
7
  import { outboundRuntimeDepsFor, secretForJobWithDeps } from '../app/outbound';
8
8
  import type { Job } from '../core/contracts/types';
9
9
  import { handleApprovalDecisionFor, type ApprovalDecisionDeps } from './approvals';
@@ -23,7 +23,7 @@ export function defaultApprovalDecisionDeps(): ApprovalDecisionDeps {
23
23
  now,
24
24
  sleep,
25
25
  secretForJob: (job: Job): Promise<string> => secretForJobWithDeps(outboundDeps, job),
26
- engineRuntime: { requeueForRerun },
26
+ engineRuntime: { kickInhubScheduler },
27
27
  };
28
28
  }
29
29
 
@@ -11,6 +11,7 @@ import type { AppConfig } from '../core/config/config';
11
11
  import type { RuntimeStateStore } from '../core/state/state-contracts';
12
12
  import type { ConfigStoreContract } from '../infrastructure/config/configstore';
13
13
  import { isAgentToolInvocationJob } from '../app/agent-tool-job';
14
+ import { continueApprovalDecisionFor, supportsApprovalContinuations } from '../app/approval-continuations';
14
15
 
15
16
  export interface ApprovalDecisionDeps {
16
17
  cfg: AppConfig;
@@ -19,7 +20,7 @@ export interface ApprovalDecisionDeps {
19
20
  now: () => string;
20
21
  sleep: (ms: number) => Promise<void>;
21
22
  secretForJob: (job: Job) => Promise<string>;
22
- engineRuntime: Pick<EngineRuntime, 'requeueForRerun'>;
23
+ engineRuntime: Pick<EngineRuntime, 'kickInhubScheduler'>;
23
24
  }
24
25
 
25
26
  async function clientOwnsJob(configStore: ConfigStoreContract | null, client: Client, job: Job): Promise<boolean> {
@@ -75,7 +76,14 @@ export async function handleApprovalDecisionFor(deps: ApprovalDecisionDeps, req:
75
76
  const sameDecision = approval.status === decision.decision && approval.decision_id === decision.decision_id;
76
77
  if (approval.status !== 'pending') {
77
78
  if (sameDecision) {
78
- send(res, 200, { ok: true, id: approvalId, status: approval.status, decision_id: decision.decision_id, idempotent: true, rerun: false });
79
+ try {
80
+ const continued = supportsApprovalContinuations(deps)
81
+ ? await continueApprovalDecisionFor(deps, approvalId) : { rerun: false, pending: false };
82
+ send(res, 200, { ok: true, id: approvalId, status: approval.status, decision_id: decision.decision_id, idempotent: true,
83
+ rerun: continued.rerun, continuation_pending: continued.pending });
84
+ } catch {
85
+ send(res, 503, { error: '审批决策已保存,原任务续办等待恢复', decision_recorded: true, continuation_pending: true });
86
+ }
79
87
  return;
80
88
  }
81
89
  send(res, 409, { error: `审批单已是 ${approval.status},不可重复裁决`, status: approval.status, decision_id: approval.decision_id }); return;
@@ -86,38 +94,27 @@ export async function handleApprovalDecisionFor(deps: ApprovalDecisionDeps, req:
86
94
  send(res, 409, { error: 'decision_id 已用于其他审批单', decision_id: decision.decision_id, approval_id: existingDecision.id }); return;
87
95
  }
88
96
 
89
- if (!await deps.configStore.approvals.decide(approvalId, decision.decision, decision.approver, { decision_id: decision.decision_id, comment: decision.comment })) {
97
+ if (!supportsApprovalContinuations(deps)) {
98
+ send(res, 503, { error: '审批持久续办需要配套状态与配置仓储', code: 'approval_continuations_unavailable' }); return;
99
+ }
100
+ let recorded: 'decided' | 'same' | 'conflict';
101
+ try {
102
+ recorded = await deps.configStore.approvals.decideWithContinuation!(approvalId, decision.decision, decision.approver, {
103
+ decision_id: decision.decision_id, comment: decision.comment, source: 'external', auth: byAuth,
104
+ mode: isAgentToolInvocationJob(job) ? 'manual' : 'rerun',
105
+ });
106
+ } catch {
107
+ send(res, 503, { error: '审批决策持久化暂不可用,请使用原 decision_id 重试', code: 'approval_continuations_unavailable' }); return;
108
+ }
109
+ if (recorded === 'conflict') {
90
110
  send(res, 409, { error: '审批单状态已变化,请刷新后重试' }); return;
91
111
  }
92
-
93
- await deps.stateStore.appendAudit({
94
- ts: deps.now(),
95
- job_id: approval.job_id,
96
- request_id: approval.request_id,
97
- event: decision.decision === 'approved' ? 'tool_approved_external' : 'tool_denied_external',
98
- detail: {
99
- approval_id: approvalId,
100
- decision_id: decision.decision_id,
101
- tool: approval.tool,
102
- scope: approval.scope,
103
- by: decision.approver,
104
- auth: byAuth,
105
- policy: approval.policy,
106
- reason: approval.reason,
107
- summary: approval.summary,
108
- ...(decision.comment ? { comment: decision.comment } : {}),
109
- },
110
- });
111
-
112
- let rerun = false;
113
- if (decision.decision === 'approved') {
114
- const latest = await deps.stateStore.getJob(approval.job_id);
115
- // Agent 直调没有中枢模型这一层;批准后由原本地 Agent 持 invocation_id
116
- // 续执行冻结快照。绝不得把 synthetic Job 重排进 LLM 调度器。
117
- if (latest && !isAgentToolInvocationJob(latest) && (latest.status === 'done' || latest.status === 'error' || latest.status === 'rejected')) {
118
- await deps.engineRuntime.requeueForRerun(latest, decision.approver, `approval_${approvalId}`);
119
- rerun = true;
120
- }
112
+ try {
113
+ // Direct Agent invocations only retain a manual original-ID continuation.
114
+ const continued = await continueApprovalDecisionFor(deps, approvalId);
115
+ send(res, 200, { ok: true, id: approvalId, status: decision.decision, decision_id: decision.decision_id,
116
+ idempotent: recorded === 'same', rerun: continued.rerun, continuation_pending: continued.pending });
117
+ } catch {
118
+ send(res, 503, { error: '审批决策已保存,原任务续办等待恢复', decision_recorded: true, continuation_pending: true });
121
119
  }
122
- send(res, 200, { ok: true, id: approvalId, status: decision.decision, decision_id: decision.decision_id, idempotent: false, rerun });
123
120
  }
@@ -408,7 +408,7 @@ function approvalDeps(item: ToolApproval): ApprovalDecisionDeps {
408
408
  now: () => '2026-01-01T00:00:00.000Z',
409
409
  sleep: async () => undefined,
410
410
  secretForJob: async () => 'approval-secret',
411
- engineRuntime: { requeueForRerun: async () => { throw new Error('rerun should not be called'); } },
411
+ engineRuntime: { kickInhubScheduler: () => { throw new Error('rerun should not be called'); } },
412
412
  };
413
413
  }
414
414
 
@@ -443,6 +443,7 @@ test('审批决策: 同一 decision_id 的同一决策幂等返回', async () =>
443
443
  test('审批决策: 普通任务伪造 direct metadata 仍按原模型任务重跑', async () => {
444
444
  let reruns = 0;
445
445
  const item = approval();
446
+ let intent: any = null;
446
447
  const forged = job({
447
448
  status: 'done',
448
449
  target: 'llm',
@@ -470,17 +471,29 @@ test('审批决策: 普通任务伪造 direct metadata 仍按原模型任务重
470
471
  approvals: {
471
472
  get: async () => item,
472
473
  getByDecisionId: async () => null,
473
- decide: async () => true,
474
+ decideWithContinuation: async (_id: number, status: string, by: string, opts: any) => {
475
+ item.status = status as ToolApproval['status']; item.decision_id = opts.decision_id;
476
+ intent = { schema_version: 'bailing.approval-continuation.v1', approval_id: item.id,
477
+ decision_key: opts.decision_id, decision_id: opts.decision_id, decision: status,
478
+ job_id: item.job_id, request_id: item.request_id, args_hash: item.args_hash,
479
+ tool: item.tool, scope: item.scope, by, ...opts, audit_recorded: false, completed: false };
480
+ return 'decided';
481
+ },
482
+ getContinuation: async () => intent,
483
+ pendingContinuations: async () => intent ? [intent] : [],
484
+ markContinuationAuditRecorded: async () => { intent.audit_recorded = true; },
485
+ completeContinuation: async () => { intent.completed = true; },
474
486
  },
475
487
  } as unknown as ConfigStoreContract,
476
488
  stateStore: {
477
489
  getJob: async () => forged,
478
490
  appendAudit: async () => undefined,
491
+ requeueApprovedJobOnce: async () => { reruns++; return 'queued'; },
479
492
  } as unknown as RuntimeStateStore,
480
493
  now: () => '2026-01-01T00:00:00.000Z',
481
494
  sleep: async () => undefined,
482
495
  secretForJob: async () => 'approval-secret',
483
- engineRuntime: { requeueForRerun: async () => { reruns++; } },
496
+ engineRuntime: { kickInhubScheduler: () => undefined },
484
497
  };
485
498
  const res = new FakeResponse();
486
499
  await handleApprovalDecisionFor(
@@ -0,0 +1,24 @@
1
+ // Isolated synthetic test worker. Credentials/configuration arrive over IPC only.
2
+ import { createPool } from 'mysql2/promise';
3
+ import { ApprovalLedger } from '../infrastructure/config/config-approval-ledger';
4
+ import { MysqlStore } from '../infrastructure/state/state-mysql';
5
+ import type { AppConfig } from '../core/config/config';
6
+
7
+ process.once('message', async (input: { mysql: AppConfig['state']['mysql']; approvalId: number;
8
+ jobId: string; requestId: string; stage: 'after-decision' | 'after-queue'; decisionId: string }) => {
9
+ try {
10
+ const pool = createPool({ ...input.mysql, timezone: 'Z' });
11
+ const ledger = new ApprovalLedger(() => pool);
12
+ const store = new MysqlStore(input.mysql, { get: async () => pool, close: async () => pool.end() });
13
+ await store.init();
14
+ await ledger.decideWithContinuation(input.approvalId, 'approved', 'synthetic-operator', {
15
+ decision_id: input.decisionId, source: 'external', auth: 'fixture', mode: 'rerun',
16
+ });
17
+ if (input.stage === 'after-queue') await store.requeueApprovedJobOnce({
18
+ job_id: input.jobId, request_id: input.requestId, approval_id: input.approvalId, decision_key: input.decisionId, decision_id: input.decisionId,
19
+ });
20
+ process.send?.({ stage: input.stage, pid: process.pid }, () => process.kill(process.pid, 'SIGKILL'));
21
+ } catch {
22
+ process.send?.({ error: 'synthetic_worker_failed' }, () => process.exit(1));
23
+ }
24
+ });
@@ -0,0 +1,78 @@
1
+ /** Test-only process entrypoint. Configuration arrives over IPC, never from a deployment file. */
2
+ import { createServer } from 'node:http';
3
+ import type { AddressInfo } from 'node:net';
4
+ import type { PoolConnection } from 'mysql2/promise';
5
+ import type { AppConfig } from '../core/config/config';
6
+ import { UsageRepository } from '../modules/usage/repository';
7
+ import { createBailingHubKernel } from '../app/kernel';
8
+
9
+ export type CrashStage = 'admitted' | 'dispatch' | 'result' | 'settlement';
10
+ export type CrashPoint = `${CrashStage}:${'before' | 'after'}`;
11
+ export interface CrashChildInit { type: 'init'; config: AppConfig; instanceKey: string; point?: CrashPoint }
12
+
13
+ export function transactionStage(sql: string): CrashStage | undefined {
14
+ if (/INSERT INTO bz_usage_billing_requests\(/i.test(sql)) return 'admitted';
15
+ if (/UPDATE bz_usage_billing_requests SET state='dispatch_committed'/i.test(sql)) return 'dispatch';
16
+ if (/UPDATE bz_usage_billing_requests SET state=\?,result_state=\?,result_json=\?/i.test(sql)) return 'result';
17
+ if (/INSERT INTO bz_usage_billing_ledger\(/i.test(sql)) return 'settlement';
18
+ return undefined;
19
+ }
20
+
21
+ function installCrashBarrier(point: CrashPoint) {
22
+ const transaction = UsageRepository.prototype.withTransaction;
23
+ let entered = false;
24
+ const pause = async () => {
25
+ entered = true;
26
+ process.send?.({ type: 'fault', point, pid: process.pid });
27
+ await new Promise<void>(() => { /* Only SIGKILL may cross this test barrier. */ });
28
+ };
29
+ UsageRepository.prototype.withTransaction = function<T>(fn: (c: PoolConnection) => Promise<T>): Promise<T> {
30
+ return transaction.call(this, async (connection: PoolConnection) => {
31
+ const originalQuery = connection.query, originalCommit = connection.commit, originalRelease = connection.release;
32
+ let stage: CrashStage | undefined;
33
+ connection.query = (async (...args: unknown[]) => {
34
+ const result = await (originalQuery as (...args: unknown[]) => Promise<unknown>).apply(connection, args);
35
+ if (typeof args[0] === 'string') stage = transactionStage(args[0]) ?? stage;
36
+ return result;
37
+ }) as PoolConnection['query'];
38
+ connection.commit = async () => {
39
+ if (!entered && point === `${stage}:before`) await pause();
40
+ await originalCommit.call(connection);
41
+ if (!entered && point === `${stage}:after`) await pause();
42
+ };
43
+ connection.release = () => {
44
+ connection.query = originalQuery;
45
+ connection.commit = originalCommit;
46
+ connection.release = originalRelease;
47
+ originalRelease.call(connection);
48
+ };
49
+ return fn(connection);
50
+ }) as Promise<T>;
51
+ };
52
+ }
53
+
54
+ let initialized = false;
55
+ process.on('message', (message: CrashChildInit | { type: 'shutdown' }) => {
56
+ if (message.type !== 'init' || initialized) return;
57
+ initialized = true;
58
+ void (async () => {
59
+ if (message.point) installCrashBarrier(message.point);
60
+ const kernel = createBailingHubKernel({ instanceKey: message.instanceKey, config: message.config,
61
+ schedulerMode: 'managed', bootstrapLocalAdmin: false, logger: { log() {}, warn() {}, error() {} } });
62
+ await kernel.initialize();
63
+ const server = createServer((req, res) => { void kernel.handle(req, res).catch(error => res.destroy(error)); });
64
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
65
+ process.send?.({ type: 'ready', base: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, pid: process.pid });
66
+ process.on('message', next => {
67
+ if ((next as { type?: string }).type !== 'shutdown') return;
68
+ void (async () => {
69
+ server.close(); server.closeAllConnections();
70
+ await kernel.close(5000);
71
+ process.exit(0);
72
+ })().catch(() => process.exit(1));
73
+ });
74
+ })().catch(error => {
75
+ process.send?.({ type: 'error', message: error instanceof Error ? error.message : 'Synthetic child failed' });
76
+ process.exit(1);
77
+ });
78
+ });