bailinghub 0.9.0 → 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.
- package/.dockerignore +6 -0
- package/.npmignore +6 -0
- package/CONTRIBUTING.md +4 -0
- package/GOVERNANCE.md +9 -0
- package/README.en.md +7 -6
- package/README.md +7 -6
- package/SECURITY.md +8 -2
- package/THIRD_PARTY_NOTICES.md +17 -17
- package/docker-compose.images.yml +2 -2
- package/docs/CHANGELOG.en.md +22 -1
- package/docs/CHANGELOG.md +22 -1
- package/docs/COMPATIBILITY.en.md +4 -0
- package/docs/CORE_RELIABILITY.en.md +59 -0
- package/docs/CORE_RELIABILITY.md +59 -0
- package/docs/DEPLOYMENT_DIAGNOSTICS.en.md +78 -0
- package/docs/DEPLOYMENT_DIAGNOSTICS.md +78 -0
- package/docs/IMPLEMENTATION_STATUS.en.md +81 -0
- package/docs/IMPLEMENTATION_STATUS.md +81 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/KERNEL_HOST_API.en.md +20 -0
- package/docs/KERNEL_HOST_API.md +20 -0
- package/docs/MODEL_BILLING.en.md +4 -0
- package/docs/MODEL_BILLING.md +4 -0
- package/docs/MODEL_PROCESS_RECOVERY.en.md +32 -0
- package/docs/MODEL_PROCESS_RECOVERY.md +37 -0
- package/docs/README.en.md +8 -0
- package/docs/README.md +8 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +3 -3
- package/docs/RELEASE_NOTES_NEXT.md +3 -3
- package/docs/RELEASE_NOTES_v0.9.1.en.md +38 -0
- package/docs/RELEASE_NOTES_v0.9.1.md +38 -0
- package/docs/RELEASE_NOTES_v0.9.2.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.2.md +45 -0
- package/docs/UPGRADE_v0.9.1.en.md +39 -0
- package/docs/UPGRADE_v0.9.1.md +39 -0
- package/docs/UPGRADE_v0.9.2.en.md +62 -0
- package/docs/UPGRADE_v0.9.2.md +62 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +4 -0
- package/package.json +10 -5
- package/scripts/check-doc-links.mjs +4 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/dependency-audit.mjs +134 -0
- package/scripts/dependency-audit.test.mjs +125 -0
- package/scripts/doctor-deployment.test.ts +419 -0
- package/scripts/doctor-deployment.ts +357 -0
- package/scripts/doctor.ts +8 -1
- package/scripts/install-secrets.test.mjs +185 -0
- package/scripts/install.sh +10 -6
- package/scripts/osps-results.py +114 -0
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +5 -0
- package/scripts/verify-github-repo.mjs +5 -0
- package/security/dependency-audit-exceptions.json +192 -0
- package/sql/065_usage_reconciliation_scan.sql +4 -0
- package/sql/066_approval_continuations.sql +15 -0
- package/sql/README.md +9 -0
- package/src/app/approval-continuations.mysql.test.ts +138 -0
- package/src/app/approval-continuations.test.ts +325 -0
- package/src/app/approval-continuations.ts +107 -0
- package/src/app/http-server.ts +3 -0
- package/src/app/kernel-model-process-crash.mysql.test.ts +377 -0
- package/src/app/kernel-usage-lifecycle.mysql.test.ts +325 -0
- package/src/app/kernel.ts +23 -0
- package/src/app/runtime-evidence-maintenance.test.ts +55 -0
- package/src/app/runtime-lifecycle-default.ts +7 -0
- package/src/app/runtime-lifecycle.ts +39 -0
- package/src/core/contracts/approval-continuation.ts +43 -0
- package/src/core/contracts/types.ts +2 -0
- package/src/core/state/approval-continuation.ts +22 -0
- package/src/core/state/state-codec.ts +1 -0
- package/src/core/state/state-contracts.ts +3 -0
- package/src/infrastructure/config/config-approval-ledger.ts +75 -0
- package/src/infrastructure/config/configstore.ts +2 -2
- package/src/infrastructure/state/state-jsonl.ts +41 -11
- package/src/infrastructure/state/state-mysql.ts +27 -0
- package/src/modules/usage/background-work.test.ts +144 -0
- package/src/modules/usage/background-work.ts +50 -0
- package/src/modules/usage/billing-reconciliation.mysql.test.ts +163 -0
- package/src/modules/usage/billing-reconciliation.test.ts +71 -0
- package/src/modules/usage/billing-repository.ts +60 -15
- package/src/modules/usage/maintenance.test.ts +62 -0
- package/src/modules/usage/maintenance.ts +31 -0
- package/src/modules/usage/model-gateway.ts +11 -3
- package/src/modules/usage/model-tool-gateway.mysql.test.ts +1 -1
- package/src/modules/usage/pricing.ts +3 -2
- package/src/modules/usage/repository.ts +2 -0
- package/src/modules/usage/test-harness.ts +2 -1
- package/src/routes/admin-default.ts +2 -2
- package/src/routes/admin-runtime-default.ts +2 -2
- package/src/routes/admin-runtime.test.ts +1 -1
- package/src/routes/admin-runtime.ts +25 -18
- package/src/routes/admin.ts +1 -1
- package/src/routes/approvals-default.ts +2 -2
- package/src/routes/approvals.ts +30 -33
- package/src/routes/critical-routes.test.ts +16 -3
- package/src/test-support/approval-continuation-crash-child.ts +24 -0
- package/src/test-support/model-process-crash-child.ts +78 -0
- package/web/console/assets/{Accounts-DnddhY6t.js → Accounts-DKhw_QLr.js} +1 -1
- package/web/console/assets/{AgentClients-VInbD7JS.js → AgentClients-CM4_5HaA.js} +1 -1
- package/web/console/assets/{AgentTasks-B-1XklBg.js → AgentTasks-CkQgZTU5.js} +1 -1
- package/web/console/assets/{Approvals-34qUPHf0.js → Approvals-B9O9TkbO.js} +1 -1
- package/web/console/assets/{Audit-BbVgkSm2.js → Audit-2vDC1SPu.js} +1 -1
- package/web/console/assets/{BrandLockup-DgscF28e.js → BrandLockup-BgASiRSE.js} +1 -1
- package/web/console/assets/{Channels-Bp-yuk8d.js → Channels-A-GvkNBt.js} +1 -1
- package/web/console/assets/{ChatEntries-C9Ft60TS.js → ChatEntries-BLxymI67.js} +1 -1
- package/web/console/assets/{Clients-NPldD-DD.js → Clients-DeNlmvS6.js} +1 -1
- package/web/console/assets/{Cost-DZcuB-EB.js → Cost-CBq_L4Kz.js} +1 -1
- package/web/console/assets/{Credentials-RTT7N6zl.js → Credentials-DmtbctNj.js} +1 -1
- package/web/console/assets/{Diagnostics-_LeK8cce.js → Diagnostics-BbcRDiA-.js} +1 -1
- package/web/console/assets/{Executors-Bi7H8rIm.js → Executors-gGgmQrDt.js} +1 -1
- package/web/console/assets/{HelpTip-BfyWrxCE.js → HelpTip-Dtdt2tKR.js} +1 -1
- package/web/console/assets/{Kb-BHamz8NP.js → Kb-lgY6OXUz.js} +2 -2
- package/web/console/assets/{Login-C1rJR-6w.js → Login-DA6BASZd.js} +1 -1
- package/web/console/assets/{Projects-BRA4a48v.js → Projects-DEbmB_sT.js} +1 -1
- package/web/console/assets/{Routes-CTC7U-fQ.js → Routes-qS6LLoyS.js} +1 -1
- package/web/console/assets/{Runs-B_fa_BlD.js → Runs-DG-VLRSc.js} +1 -1
- package/web/console/assets/{Setup-C1_d0mFy.js → Setup-DEpVF5uw.js} +1 -1
- package/web/console/assets/{Shell-CHEV6RGC.js → Shell-DgoPgK1E.js} +1 -1
- package/web/console/assets/{StorageBuckets-DlG3ojhA.js → StorageBuckets-DJtNN769.js} +1 -1
- package/web/console/assets/{SystemSettings-DYo2gg6d.js → SystemSettings-0DEUgeTR.js} +1 -1
- package/web/console/assets/{SystemStatus-DKCoUZlq.js → SystemStatus-CR1phiPE.js} +1 -1
- package/web/console/assets/{Targets-CdkG6BPR.js → Targets-D65l-IMB.js} +1 -1
- package/web/console/assets/{Tools-DVpCt0ox.js → Tools-DqtrINrN.js} +1 -1
- package/web/console/assets/{Usage-DWCpLugC.js → Usage-B5njXNjx.js} +1 -1
- package/web/console/assets/{UsageAccess-B_Xq7ARW.js → UsageAccess-ChnB4pjb.js} +1 -1
- package/web/console/assets/{UsageHelp-t5ZG_f-e.js → UsageHelp-BBKIvbQ5.js} +1 -1
- package/web/console/assets/{index-C6W4LWVV.js → index-65JiiUr4.js} +1 -1
- package/web/console/assets/{index-H1kfa0Mj.js → index-sLKrJd_p.js} +2 -2
- package/web/console/assets/{request-DLsP1_ot.js → request-BpaimqEb.js} +1 -1
- package/web/console/assets/{schema-BLOHvAJQ.js → schema-D0Z4kFCZ.js} +1 -1
- package/web/console/assets/{util-CGVh2Jvr.js → util-DZYfJ5Zo.js} +1 -1
- package/web/console/assets/{vendor-element-BD089KxE.js → vendor-element-8cVcdt5T.js} +1 -1
- package/web/console/assets/{vendor-mammoth-Bv-CZhmH.js → vendor-mammoth-CnDA23N0.js} +1 -1
- package/web/console/assets/vendor-vue-Co7x2FW6.js +29 -0
- package/web/console/index.html +3 -3
- package/web-admin/package-lock.json +83 -85
- package/web/console/assets/vendor-vue-B2uhHUfE.js +0 -29
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import type { UsageRepository } from './repository';
|
|
4
|
+
import { BillingRepository } from './billing-repository';
|
|
5
|
+
|
|
6
|
+
const price = { source: 'openrouter', currency: 'USD', modelId: 'synthetic', endpointId: 'synthetic', fetchedAt: 1,
|
|
7
|
+
lines: [{ billable: 'output_image', unit: 'image', costUsd: '0.1' }] };
|
|
8
|
+
function fixture(count = 51) {
|
|
9
|
+
const records: Record<string, any>[] = Array.from({ length: count }, (_, n) => ({
|
|
10
|
+
id: `request-${String(n).padStart(2, '0')}`, operation_id: `op-${n}`, account_id: 'account', user_id: 'user', session_id: 'session',
|
|
11
|
+
service_id: 'model', conversation_id: null, turn_id: null, request_hash: 'a'.repeat(64), revision: 1, state: 'completed',
|
|
12
|
+
result_state: 'complete', billing_state: 'pending', service_json: {}, service_revision: 1, model: 'synthetic', fence: 'same-fence',
|
|
13
|
+
billing_rate_json: { planId: 'plan', planRevision: 1, multiplier: 1, price }, grant_id: 'grant', grant_revision: 1,
|
|
14
|
+
grant_json: { mode: 'credits', priceUsd: 100, duration: { unit: 'forever', count: 0 } }, period_start: 1, period_end: null,
|
|
15
|
+
result_json: 'INVALID_RESULT_JSON_MUST_NEVER_BE_READ', result_hash: 'b'.repeat(64), usage_json: null,
|
|
16
|
+
raw_usage_json: n === count - 1 ? { requestCount: 1, outputImageCount: 1 } : { requestCount: 1 },
|
|
17
|
+
reference_cost_usd: null, billed_usd: null, overage_usd: null, cancelled_at: null, created_at: n, updated_at: 1,
|
|
18
|
+
}));
|
|
19
|
+
const ledger: string[] = [], attempts: string[] = [], statements: string[] = [];
|
|
20
|
+
const period = { allowance_usd: '100', consumed_usd: '0' };
|
|
21
|
+
const executor = { async query(sql: string, args: any[] = []): Promise<any> {
|
|
22
|
+
statements.push(sql);
|
|
23
|
+
if (sql.includes('ORDER BY updated_at,id LIMIT 50')) {
|
|
24
|
+
let selected = records.filter(r => r.billing_state === 'pending');
|
|
25
|
+
if (args.length) selected = selected.filter(r => r.updated_at > args[0] || (r.updated_at === args[1] && r.id > args[2]));
|
|
26
|
+
return [selected.sort((a, b) => a.updated_at - b.updated_at || a.id.localeCompare(b.id)).slice(0, 50).map(r => ({ id: r.id, updated_at: r.updated_at }))];
|
|
27
|
+
}
|
|
28
|
+
if (sql.startsWith('SELECT account_id FROM bz_usage_billing_requests')) return [[records.find(r => r.id === args[0])]];
|
|
29
|
+
if (sql.startsWith('SELECT * FROM bz_usage_accounts')) return [[{ id: 'account', state: 'active' }]];
|
|
30
|
+
if (sql.includes('NULL AS result_json') && sql.includes('FROM bz_usage_billing_requests WHERE id=?')) {
|
|
31
|
+
if (sql.includes('FOR UPDATE')) attempts.push(args[0]);
|
|
32
|
+
const record = records.find(r => r.id === args[0]);
|
|
33
|
+
return [record ? [{ ...record, result_json: null }] : []];
|
|
34
|
+
}
|
|
35
|
+
if (sql.startsWith('SELECT * FROM bz_usage_billing_periods')) return [[period]];
|
|
36
|
+
if (sql.startsWith('SELECT CAST(UNIX_TIMESTAMP')) return [[{ ms: 1000 }]];
|
|
37
|
+
if (sql.startsWith('UPDATE bz_usage_billing_periods')) { period.consumed_usd = args[0]; return [{}]; }
|
|
38
|
+
if (sql.startsWith('INSERT INTO bz_usage_billing_ledger')) { ledger.push(args[0]); return [{}]; }
|
|
39
|
+
if (sql.startsWith("UPDATE bz_usage_billing_requests SET billing_state='settled'")) {
|
|
40
|
+
Object.assign(records.find(r => r.id === args[4])!, { billing_state: 'settled', reference_cost_usd: args[0], billed_usd: args[1], overage_usd: args[2], updated_at: args[3] });
|
|
41
|
+
return [{}];
|
|
42
|
+
}
|
|
43
|
+
throw new Error('Unexpected synthetic statement');
|
|
44
|
+
} };
|
|
45
|
+
const repository = { getPool: () => executor, withTransaction: async (fn: (c: any) => Promise<any>) => fn(executor) } as unknown as UsageRepository;
|
|
46
|
+
return { tokens: new BillingRepository(repository), records, ledger, attempts, statements, period };
|
|
47
|
+
}
|
|
48
|
+
test('fifty unpriceable originals cannot starve the fifty-first payable result, including equal timestamps', async () => {
|
|
49
|
+
const h = fixture();
|
|
50
|
+
await h.tokens.reconcilePendingUsage();
|
|
51
|
+
assert.equal(h.ledger.length, 0); assert.equal(h.tokens.getReconciliationProgress().scanned, 50);
|
|
52
|
+
await h.tokens.reconcilePendingUsage();
|
|
53
|
+
assert.deepEqual(h.ledger, ['request-50']); assert.equal(h.records[50]!.billed_usd, '0.1');
|
|
54
|
+
await h.tokens.reconcilePendingUsage();
|
|
55
|
+
assert.equal(h.ledger.length, 1); assert.equal(h.period.consumed_usd, '0.1');
|
|
56
|
+
assert.equal(h.records.filter(r => r.billing_state === 'pending').length, 50);
|
|
57
|
+
assert(h.statements.every(sql => !sql.startsWith('SELECT * FROM bz_usage_billing_requests')));
|
|
58
|
+
});
|
|
59
|
+
test('one malformed record does not stop a later valid receipt and progress contains no evidence bodies', async () => {
|
|
60
|
+
const h = fixture(2); h.records[0]!.billing_rate_json = 'SYNTHETIC_MALFORMED_JSON';
|
|
61
|
+
await h.tokens.reconcilePendingUsage();
|
|
62
|
+
assert.deepEqual(h.ledger, ['request-01']);
|
|
63
|
+
assert.deepEqual(h.tokens.getReconciliationProgress(), { scanned: 2, settled: 1, deferred: 0, failed: 1, hasMore: false });
|
|
64
|
+
});
|
|
65
|
+
test('concurrent reconciliation shares one page rather than skipping its cursor', async () => {
|
|
66
|
+
const h = fixture();
|
|
67
|
+
const first = h.tokens.reconcilePendingUsage();
|
|
68
|
+
assert.equal(h.tokens.reconcilePendingUsage(), first);
|
|
69
|
+
await first;
|
|
70
|
+
assert.equal(h.attempts.length, 50);
|
|
71
|
+
});
|
|
@@ -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,
|
|
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 => {
|
|
@@ -355,29 +363,32 @@ export class BillingRepository {
|
|
|
355
363
|
return recorded.billingState === 'pending' && (recorded.usage || recorded.rawUsage) ? this.settleRecorded(recorded) : recorded;
|
|
356
364
|
}
|
|
357
365
|
private readonly settlements = new Map<string, Promise<void>>();
|
|
358
|
-
scheduleSettlement(operationId: string, actor: UsageActor): void {
|
|
366
|
+
scheduleSettlement(operationId: string, actor: UsageActor): Promise<void> {
|
|
359
367
|
const key = operationIdKey(actor, operationId);
|
|
360
|
-
|
|
361
|
-
|
|
368
|
+
const existing = this.settlements.get(key);
|
|
369
|
+
if (existing) return existing;
|
|
370
|
+
const work = this.repository.backgroundWork.track('settlement', async () => {
|
|
362
371
|
const r = await this.findRequest(actor, operationId);
|
|
363
372
|
if (r?.billingState === 'pending' && (r.usage || r.rawUsage) && r.resultHash) await this.settleRecorded(r);
|
|
364
373
|
}).catch(() => { /* Durable pending evidence is retried by maintenance. */ })
|
|
365
374
|
.finally(() => { this.settlements.delete(key); });
|
|
366
375
|
this.settlements.set(key, work);
|
|
376
|
+
return work;
|
|
367
377
|
}
|
|
368
|
-
async drainSettlements(): Promise<void> { await Promise.allSettled([...this.settlements.values()]); }
|
|
378
|
+
async drainSettlements(): Promise<void> { while (this.settlements.size) await Promise.allSettled([...this.settlements.values()]); }
|
|
369
379
|
private async settleRecorded(recorded: BillingRequest): Promise<BillingRequest> {
|
|
370
380
|
try {
|
|
371
381
|
return await this.repository.withTransaction(async c => {
|
|
372
|
-
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 });
|
|
373
384
|
usageAssert(r.fence === recorded.fence, 'USAGE_FENCE_CONFLICT', 'Settlement does not match the original dispatch.');
|
|
374
|
-
if (r.billing_state === 'settled' || (!r.usage_json && !r.raw_usage_json) || !r.result_hash) return
|
|
385
|
+
if (r.billing_state === 'settled' || (!r.usage_json && !r.raw_usage_json) || !r.result_hash) return receipt(r);
|
|
375
386
|
const measured = r.usage_json ? tokenUsage(json(r.usage_json)) : null;
|
|
376
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];
|
|
377
388
|
usageAssert(p, 'METERING_UNAVAILABLE', 'The original allowance pool is unavailable.', 503);
|
|
378
389
|
const rate = request(r).billingRate;
|
|
379
390
|
const referenceCost = calculateReferenceCost(rate.price, { ...(json<Record<string, unknown>>(r.raw_usage_json) ?? {}), ...(measured ?? {}) });
|
|
380
|
-
if (referenceCost === null) return
|
|
391
|
+
if (referenceCost === null) return receipt(r);
|
|
381
392
|
const charged = billedUsdMicros(referenceCost, rate.multiplier);
|
|
382
393
|
const before = usdMicros(p.consumed_usd), after = before + charged, quota = usdMicros(p.allowance_usd);
|
|
383
394
|
const overage = positivePart(after - quota) - positivePart(before - quota), now = await this.now(c);
|
|
@@ -388,7 +399,7 @@ export class BillingRepository {
|
|
|
388
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(?,?,?,?,?,?,?,?,?,?)',
|
|
389
400
|
[r.id, r.account_id, r.grant_id, r.period_start, measured?.inputTokens ?? null, measured?.outputTokens ?? null, referenceCost, chargedValue, overageValue, now]);
|
|
390
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]);
|
|
391
|
-
return
|
|
402
|
+
return receipt((await rows(c, `SELECT ${SETTLEMENT_COLUMNS} FROM bz_usage_billing_requests WHERE id=?`, [r.id]))[0]!);
|
|
392
403
|
});
|
|
393
404
|
} catch (e) {
|
|
394
405
|
if (e instanceof UsageError && e.status < 500) throw e;
|
|
@@ -400,11 +411,45 @@ export class BillingRepository {
|
|
|
400
411
|
integer(now, 'now');
|
|
401
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]);
|
|
402
413
|
}
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
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;
|
|
408
453
|
}
|
|
409
454
|
/** Persist a terminal rejection independently of settlement; never dispatch again. */
|
|
410
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';
|
|
@@ -28,13 +29,15 @@ export interface UsageGatewayDeps {
|
|
|
28
29
|
|
|
29
30
|
const responseCleanup = new WeakMap<UsageRepository, number>();
|
|
30
31
|
function scheduleResponseCleanup(repository: UsageRepository): void {
|
|
32
|
+
if (!repository.backgroundWork.acceptingRequests) return;
|
|
31
33
|
const now = Date.now();
|
|
32
34
|
if (now - (responseCleanup.get(repository) ?? 0) < 60_000) return;
|
|
33
35
|
responseCleanup.set(repository, now);
|
|
34
36
|
// Bounded maintenance is independent of admission and model delivery. A failed
|
|
35
37
|
// cleanup is retried on later traffic; expired bodies are never returned meanwhile.
|
|
36
38
|
const tokens = getBillingRepository(repository);
|
|
37
|
-
void
|
|
39
|
+
void repository.backgroundWork.startMaintenance('response-cleanup', () => tokens.cleanupExpiredResponses(now))?.catch(() => {});
|
|
40
|
+
void runUsageMaintenanceFor(repository);
|
|
38
41
|
}
|
|
39
42
|
|
|
40
43
|
export const MODEL_GATEWAY_CAPABILITIES = {
|
|
@@ -95,7 +98,7 @@ export async function runModelRequest(deps: UsageGatewayDeps, actor: UsageSessio
|
|
|
95
98
|
usageAssert(previous.requestHash === requestHash, 'USAGE_IDEMPOTENCY_CONFLICT', '原请求标识已关联其他内容。');
|
|
96
99
|
return tokens.view(previous);
|
|
97
100
|
}
|
|
98
|
-
usageAssert(!deps.isPaused?.(), 'USAGE_SERVICE_PAUSED', '模型服务维护中;原请求结果仍可查询。', 503);
|
|
101
|
+
usageAssert(repository.backgroundWork.acceptingRequests && !deps.isPaused?.(), 'USAGE_SERVICE_PAUSED', '模型服务维护中;原请求结果仍可查询。', 503);
|
|
99
102
|
const current = await tokens.summary(actor.accountId);
|
|
100
103
|
usageAssert(current.grant, 'SERVICE_NOT_ENTITLED', '尚未开通套餐。', 403);
|
|
101
104
|
if (!modelAllowedServices(actor, current.plan?.serviceIds ?? []).includes(serviceId))
|
|
@@ -144,7 +147,12 @@ export async function runModelRequest(deps: UsageGatewayDeps, actor: UsageSessio
|
|
|
144
147
|
};
|
|
145
148
|
if (toolRequest) {
|
|
146
149
|
// Return the durable dispatch record promptly. Disconnecting never regenerates an image.
|
|
147
|
-
void
|
|
150
|
+
void repository.backgroundWork.track('model-completion', async () => {
|
|
151
|
+
const result = await complete();
|
|
152
|
+
// The accepted parent remains live through the late-created settlement.
|
|
153
|
+
// Delivery still returns 202 immediately; close must drain both stages.
|
|
154
|
+
await tokens.scheduleSettlement(result.operation_id, actor);
|
|
155
|
+
}).catch(()=>{});
|
|
148
156
|
return tokens.view(request);
|
|
149
157
|
}
|
|
150
158
|
return complete();
|
|
@@ -61,7 +61,7 @@ async function fixture(options: {response?: () => Response | Promise<Response>}
|
|
|
61
61
|
throw new Error('Synthetic image operation did not settle');
|
|
62
62
|
}
|
|
63
63
|
return {...h,image,excluded,pending,user,calls,input,request,release,settled,
|
|
64
|
-
async close(){release();
|
|
64
|
+
async close(){release();server.close();server.closeAllConnections();h.repository.backgroundWork.beginDrain();assert.equal(await h.repository.backgroundWork.drain(5000),true,'Synthetic model-tool background drain timed out');await h.close();},
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
67
|
|
|
@@ -167,7 +167,7 @@ export class ReferencePricing {
|
|
|
167
167
|
}
|
|
168
168
|
private async refresh(kind: 'chat'|'image', modelId?: string): Promise<Catalog> {
|
|
169
169
|
const key = this.key(kind,modelId), pending = this.flights.get(key); if (pending) return pending;
|
|
170
|
-
const job = (async () => {
|
|
170
|
+
const job = this.repository.backgroundWork.startMaintenance('reference-price-refresh', async () => {
|
|
171
171
|
const prefix = kind === 'image' ? 'images/models' : 'models';
|
|
172
172
|
const encoded = modelId?.split('/').map(encodeURIComponent).join('/');
|
|
173
173
|
const value = await this.fetchJson(modelId ? `${prefix}/${encoded}/endpoints` : prefix);
|
|
@@ -189,7 +189,8 @@ export class ReferencePricing {
|
|
|
189
189
|
items = items.filter((x:any) => items.filter((y:any)=>y.id===x.id).length===1);
|
|
190
190
|
}
|
|
191
191
|
const result = {items,fetchedAt}; await this.save(key,result); return result;
|
|
192
|
-
})
|
|
192
|
+
});
|
|
193
|
+
usageAssert(job, 'USAGE_PRICE_UNAVAILABLE', '参考价格同步已停止,请稍后重试。', 503);
|
|
193
194
|
this.flights.set(key,job); try {return await job;} finally {this.flights.delete(key);}
|
|
194
195
|
}
|
|
195
196
|
async catalog(kind:'chat'|'image', modelId?: string, force=false): Promise<Catalog> {
|
|
@@ -5,6 +5,7 @@ import type { Pool, PoolConnection, RowDataPacket } from "mysql2/promise";
|
|
|
5
5
|
import type { CreateUsageAccountInput, UsageAccount, UsageActor, UsageActorValidator, UsageService, UsageServiceConfig } from "./contracts";
|
|
6
6
|
import { integer, assertKnownFields } from "./validation";
|
|
7
7
|
import { usageAssert } from "./errors";
|
|
8
|
+
import { UsageBackgroundWork } from './background-work';
|
|
8
9
|
type Row = Record<string, any>;
|
|
9
10
|
// Impact previews derive account models from each current grant's plan.
|
|
10
11
|
function serviceReferenceSources(id: string) {
|
|
@@ -79,6 +80,7 @@ function service(r: Row): UsageService {
|
|
|
79
80
|
};
|
|
80
81
|
}
|
|
81
82
|
export class UsageRepository {
|
|
83
|
+
readonly backgroundWork = new UsageBackgroundWork();
|
|
82
84
|
private validator: UsageActorValidator | undefined;
|
|
83
85
|
constructor(private readonly pool: () => Pool) {}
|
|
84
86
|
getPool(): Pool {
|
|
@@ -100,7 +100,8 @@ export async function createUsageTestHarness() {
|
|
|
100
100
|
setPaused(value: boolean) { paused = value; },
|
|
101
101
|
async close() {
|
|
102
102
|
state.release?.(); hub.close(); hub.closeAllConnections(); provider.close(); provider.closeAllConnections();
|
|
103
|
-
|
|
103
|
+
repository.backgroundWork.beginDrain();
|
|
104
|
+
if (!await repository.backgroundWork.drain(5000)) throw new Error('Synthetic usage background drain timed out');
|
|
104
105
|
await pool.end();
|
|
105
106
|
// Only the random database created by this fixture is removed; no shared or configured DB is touched.
|
|
106
107
|
await adminPool.query(`DROP DATABASE \`${dbName}\``); await adminPool.end();
|
|
@@ -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
|
-
|
|
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
|
-
|
|
481
|
-
|
|
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
|
-
|
|
485
|
-
|
|
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 (
|
|
494
|
-
|
|
495
|
-
|
|
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
|
|
package/src/routes/admin.ts
CHANGED
|
@@ -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 {
|
|
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: {
|
|
26
|
+
engineRuntime: { kickInhubScheduler },
|
|
27
27
|
};
|
|
28
28
|
}
|
|
29
29
|
|