bailinghub 0.7.0 → 0.8.0
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/README.en.md +6 -9
- package/README.md +6 -9
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
- package/docs/AGENT_CLIENT_RUNTIME_API.md +34 -0
- package/docs/AGENT_TASK_CONTROL.en.md +25 -0
- package/docs/AGENT_TASK_CONTROL.md +94 -0
- package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
- package/docs/CHANGELOG.en.md +11 -1
- package/docs/CHANGELOG.md +11 -1
- package/docs/COMPATIBILITY.en.md +2 -0
- package/docs/CONTRACT.en.md +2 -0
- package/docs/CONTRACT.md +2 -0
- package/docs/GENERATED_ARTIFACTS.en.md +46 -0
- package/docs/GENERATED_ARTIFACTS.md +108 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/INVOCATION_RECEIPTS.md +111 -0
- package/docs/README.en.md +3 -0
- package/docs/README.md +3 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +2 -2
- package/docs/RELEASE_NOTES_NEXT.md +2 -2
- package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
- package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
- package/docs/TOOL_RATE_LIMITS.md +50 -0
- package/docs/UPGRADE_v0.8.0.en.md +71 -0
- package/docs/UPGRADE_v0.8.0.md +73 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +2 -0
- package/package.json +1 -1
- package/schemas/config/route.schema.json +1 -0
- package/schemas/config/tool-provider.schema.json +2 -1
- package/scripts/check-doc-links.mjs +1 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/e2e-console.mjs +32 -2
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +1 -0
- package/scripts/verify-github-repo.mjs +1 -0
- package/sql/060_agent_artifacts.sql +11 -0
- package/sql/061_tool_rate_limit_policies.sql +3 -0
- package/sql/062_agent_task_control.sql +92 -0
- package/src/adapters/storage/object-storage.ts +15 -3
- package/src/adapters/storage/oss-signature.test.ts +40 -0
- package/src/adapters/storage/oss-signature.ts +21 -0
- package/src/app/agent-artifacts.test.ts +165 -0
- package/src/app/agent-artifacts.ts +85 -0
- package/src/app/agent-client-runtime.test.ts +76 -1
- package/src/app/agent-client-runtime.ts +13 -0
- package/src/app/agent-invocation-snapshot.ts +35 -0
- package/src/app/agent-task-control.ts +187 -0
- package/src/app/agent-task-runtime.ts +68 -0
- package/src/app/agent-tool-invocations.test.ts +329 -1
- package/src/app/agent-tool-invocations.ts +223 -10
- package/src/app/agent-tool-job.test.ts +11 -1
- package/src/app/agent-tool-job.ts +8 -1
- package/src/app/builtin-tools.ts +4 -0
- package/src/app/oss-edition.ts +1 -0
- package/src/app/tool-approvals.ts +4 -0
- package/src/app/tool-assembly.ts +5 -0
- package/src/core/config/artifact-config.ts +15 -0
- package/src/core/config/config-codec.ts +3 -1
- package/src/core/config/config-models.ts +11 -1
- package/src/core/config/route-config.ts +3 -2
- package/src/core/contracts/tool-rate-limits.test.ts +59 -0
- package/src/core/contracts/tool-rate-limits.ts +48 -0
- package/src/core/contracts/tools.ts +122 -43
- package/src/core/contracts/types.ts +3 -1
- package/src/core/runtime/agent-task-control.test.ts +114 -0
- package/src/core/runtime/agent-task-control.ts +227 -0
- package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -0
- package/src/infrastructure/config/config-agent-client-runtime-repository.ts +7 -1
- package/src/infrastructure/config/config-agent-task-control-journal-mysql.test.ts +315 -0
- package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
- package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
- package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
- package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -0
- package/src/infrastructure/config/config-storage-bucket-repository.ts +2 -2
- package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
- package/src/infrastructure/config/configstore.ts +9 -1
- package/src/routes/admin-agent-tasks.ts +32 -0
- package/src/routes/admin-tool-providers.test.ts +22 -0
- package/src/routes/admin-tool-providers.ts +9 -1
- package/src/routes/admin.ts +3 -0
- package/src/routes/agent-api.test.ts +76 -0
- package/src/routes/agent-api.ts +42 -1
- package/src/routes/agent-artifacts.ts +29 -0
- package/src/routes/agent-task-control-http-mysql.test.ts +246 -0
- package/src/routes/private.ts +1 -0
- package/src/routes/run.ts +2 -1
- package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
- package/web/console/assets/{Accounts-ChL9k-XA.js → Accounts-BRCR3O0P.js} +1 -1
- package/web/console/assets/AgentClients-Bf7sUUs_.js +1 -0
- package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
- package/web/console/assets/AgentTasks--bqL_QKg.js +2 -0
- package/web/console/assets/AgentTasks-C8ox3TyS.css +1 -0
- package/web/console/assets/{Approvals-Bs6FGbp2.js → Approvals-BIbZvInm.js} +1 -1
- package/web/console/assets/{Audit-4WWYhkFM.js → Audit-KyPSmBdZ.js} +1 -1
- package/web/console/assets/{BrandLockup-D2GhCipL.js → BrandLockup-Sv5DU2G6.js} +1 -1
- package/web/console/assets/{Channels-CmoGpiCJ.js → Channels-B9n4fbxg.js} +1 -1
- package/web/console/assets/{ChatEntries-BFRMtwta.js → ChatEntries-xsOCUXi_.js} +1 -1
- package/web/console/assets/{Clients-DGkkSXyA.js → Clients-CI3DBDHf.js} +1 -1
- package/web/console/assets/{Cost-BmGt0MfS.js → Cost-JgNXQPlN.js} +1 -1
- package/web/console/assets/{Credentials-CR-sYINT.js → Credentials-B5UUUdt0.js} +1 -1
- package/web/console/assets/{Diagnostics-DAPbKSJp.js → Diagnostics-BMGciWQb.js} +1 -1
- package/web/console/assets/{Executors-CgpiT3o8.js → Executors-CRbboOCZ.js} +1 -1
- package/web/console/assets/{Kb-Cm9dVSQw.js → Kb-CgLNGjRp.js} +1 -1
- package/web/console/assets/{Login-CyUcsTZ_.js → Login-C52JmXzx.js} +1 -1
- package/web/console/assets/{Projects-DldFPgWg.js → Projects-CDOvHPVS.js} +1 -1
- package/web/console/assets/{Routes-DubfjlBD.js → Routes-X9vHLpKW.js} +1 -1
- package/web/console/assets/{Runs-1hxgkuR4.js → Runs-DYNDXsqk.js} +1 -1
- package/web/console/assets/{Setup-DBLOnI2_.js → Setup-B91P6i1x.js} +1 -1
- package/web/console/assets/Shell-Bj6C8Hgo.css +1 -0
- package/web/console/assets/Shell-BsRa7bQQ.js +1 -0
- package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
- package/web/console/assets/StorageBuckets-DkuDM0oX.js +1 -0
- package/web/console/assets/{SystemSettings-cDkudo2y.js → SystemSettings-B7Mqj3k1.js} +1 -1
- package/web/console/assets/{SystemStatus-DZd6s8OX.js → SystemStatus-Db93b6dc.js} +1 -1
- package/web/console/assets/{Targets-DYNGq1NU.js → Targets-CuuIYeZO.js} +1 -1
- package/web/console/assets/Tools-CHiqz9XZ.js +2 -0
- package/web/console/assets/Tools-DU8ei6sd.css +1 -0
- package/web/console/assets/index-UGvfF3Xr.js +2 -0
- package/web/console/assets/{request-B7MLvOqo.js → request-DeGya810.js} +1 -1
- package/web/console/assets/{schema-CMuwjYdJ.js → schema-BqlqLw1R.js} +1 -1
- package/web/console/index.html +1 -1
- package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
- package/web-admin/src/components/AgentSetupPanel.vue +13 -0
- package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
- package/web-admin/src/layout/Shell.vue +1 -1
- package/web-admin/src/pages/AgentClients.vue +3 -1
- package/web-admin/src/pages/AgentTasks.vue +281 -0
- package/web-admin/src/pages/StorageBuckets.vue +6 -6
- package/web-admin/src/pages/Tools.vue +53 -4
- package/web-admin/src/router.ts +2 -0
- package/web/console/assets/AgentClients-Bs7UgVDj.js +0 -1
- package/web/console/assets/AgentClients-DkgPTEbq.css +0 -1
- package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
- package/web/console/assets/Shell-gJ5Vz_E7.js +0 -1
- package/web/console/assets/StorageBuckets-DkDW16tj.js +0 -1
- package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
- package/web/console/assets/Tools-A20oaMaQ.css +0 -1
- package/web/console/assets/Tools-DpWM59vV.js +0 -2
- package/web/console/assets/index-DGqs28gI.js +0 -2
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { effectiveToolRateLimit, normalizeToolRateLimitPolicies } from './tool-rate-limits';
|
|
4
|
+
import { LocalSlidingWindowRateLimiter } from './tools';
|
|
5
|
+
|
|
6
|
+
test('120/hour permits a burst and remains occupied after one minute; windows expire exactly', () => {
|
|
7
|
+
let now = 0;
|
|
8
|
+
const limiter = new LocalSlidingWindowRateLimiter(() => now);
|
|
9
|
+
for (let n = 0; n < 120; n++) assert.equal(limiter.consume('tool:store:images', 120, 3600), false);
|
|
10
|
+
assert.equal(limiter.consume('tool:store:images', 120, 3600), true);
|
|
11
|
+
now = 60_001;
|
|
12
|
+
assert.equal(limiter.consume('tool:store:images', 120, 3600), true);
|
|
13
|
+
// A second user's different session still hits the same provider/tool bucket; a different provider does not.
|
|
14
|
+
assert.equal(limiter.consume('tool:another:images', 120, 3600), false);
|
|
15
|
+
now = 3_600_000;
|
|
16
|
+
assert.equal(limiter.consume('tool:store:images', 120, 3600), false);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test('all supported windows and disabled limits retain their original units', () => {
|
|
20
|
+
for (const windowSec of [1, 60, 3600, 86400]) {
|
|
21
|
+
let now = 0;
|
|
22
|
+
const limiter = new LocalSlidingWindowRateLimiter(() => now);
|
|
23
|
+
assert.equal(limiter.consume('tool', 2, windowSec), false);
|
|
24
|
+
assert.equal(limiter.consume('tool', 2, windowSec), false);
|
|
25
|
+
now = windowSec * 1000 - 1;
|
|
26
|
+
assert.deepEqual(limiter.consumeAll([{ bucket: 'tool', limit: 2, windowSec }]), { limited: true, bucket: 'tool', retryAfterMs: 1 });
|
|
27
|
+
now++;
|
|
28
|
+
assert.equal(limiter.consume('tool', 2, windowSec), false);
|
|
29
|
+
assert.equal(limiter.consume('tool', 0, windowSec), false);
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('rejecting either gate never burns quota in the other gate', () => {
|
|
34
|
+
for (const blocked of ['tool', 'provider']) {
|
|
35
|
+
const limiter = new LocalSlidingWindowRateLimiter(() => 0);
|
|
36
|
+
limiter.consume(blocked, 1);
|
|
37
|
+
const other = blocked === 'tool' ? 'provider' : 'tool';
|
|
38
|
+
for (let n = 0; n < 5; n++) assert.equal(limiter.consumeAll([
|
|
39
|
+
{ bucket: 'tool', limit: 1, windowSec: 60 }, { bucket: 'provider', limit: 1, windowSec: 60 },
|
|
40
|
+
]).limited, true);
|
|
41
|
+
assert.equal(limiter.consume(other, 1), false);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('default, per-tool overrides and inheritance preserve raw declaration without changing it', () => {
|
|
46
|
+
const tool = { name: 'images_update', rateLimit: { count: 120, window: '1h' as const }, rateLimitPerMin: 2 };
|
|
47
|
+
const original = structuredClone(tool);
|
|
48
|
+
assert.equal(effectiveToolRateLimit(tool).window_sec, 3600);
|
|
49
|
+
const policies = normalizeToolRateLimitPolicies({ default: { mode: 'disabled' }, overrides: { images_update: { mode: 'inherit' } } });
|
|
50
|
+
assert.equal(effectiveToolRateLimit(tool, policies).count, 120);
|
|
51
|
+
assert.equal(effectiveToolRateLimit({ ...tool, name: 'another' }, policies).enabled, false);
|
|
52
|
+
policies.overrides.images_update = { mode: 'custom', count: 1000, window: '1m' };
|
|
53
|
+
assert.equal(effectiveToolRateLimit(tool, policies).count, 1000);
|
|
54
|
+
assert.deepEqual(tool, original);
|
|
55
|
+
for (const count of [0, -1, 1.5, '120', Infinity, 1000001]) {
|
|
56
|
+
assert.throws(() => normalizeToolRateLimitPolicies({ default: { mode: 'custom', count, window: '1h' } }));
|
|
57
|
+
}
|
|
58
|
+
assert.throws(() => normalizeToolRateLimitPolicies({ default: { mode: 'disabled', count: 120 } }));
|
|
59
|
+
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { ToolDefinition, ToolRateLimitWindow } from './tool-definition';
|
|
2
|
+
|
|
3
|
+
export type ToolRateLimitPolicy = { mode: 'inherit' | 'disabled' } | { mode: 'custom'; count: number; window: ToolRateLimitWindow };
|
|
4
|
+
export interface ToolRateLimitPolicies {
|
|
5
|
+
default: ToolRateLimitPolicy;
|
|
6
|
+
overrides: Record<string, ToolRateLimitPolicy>;
|
|
7
|
+
}
|
|
8
|
+
export interface RateLimitRequest { bucket: string; limit: number; windowSec: number }
|
|
9
|
+
export interface RateLimitDecision { limited: boolean; bucket?: string; retryAfterMs?: number }
|
|
10
|
+
export const RATE_WINDOW_SECONDS = { '1s': 1, '1m': 60, '1h': 3600, '1d': 86400 } as const;
|
|
11
|
+
|
|
12
|
+
/** Omitted configuration preserves the published business declaration. Never rewrite the spec. */
|
|
13
|
+
export function normalizeToolRateLimitPolicies(raw: unknown): ToolRateLimitPolicies {
|
|
14
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('tool_rate_limits 必须是对象');
|
|
15
|
+
const value = raw as Record<string, unknown>;
|
|
16
|
+
if (Object.keys(value).some((key) => !['default', 'overrides'].includes(key))) throw new Error('tool_rate_limits 包含未知字段');
|
|
17
|
+
const policy = (v: unknown): ToolRateLimitPolicy => {
|
|
18
|
+
if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('单工具限额策略必须是对象');
|
|
19
|
+
const p = v as Record<string, unknown>;
|
|
20
|
+
if (p.mode === 'inherit' || p.mode === 'disabled') {
|
|
21
|
+
if (Object.keys(p).some((key) => key !== 'mode')) throw new Error('继承或关闭策略不应包含自定义限额');
|
|
22
|
+
return { mode: p.mode };
|
|
23
|
+
}
|
|
24
|
+
if (p.mode !== 'custom' || !Number.isSafeInteger(p.count) || Number(p.count) < 1 || Number(p.count) > 1_000_000
|
|
25
|
+
|| typeof p.window !== 'string' || !Object.hasOwn(RATE_WINDOW_SECONDS, p.window)
|
|
26
|
+
|| Object.keys(p).some((key) => !['mode', 'count', 'window'].includes(key))) {
|
|
27
|
+
throw new Error('自定义限额需为 1–1000000 的整数,窗口为 1s/1m/1h/1d');
|
|
28
|
+
}
|
|
29
|
+
return { mode: 'custom', count: Number(p.count), window: p.window as ToolRateLimitWindow };
|
|
30
|
+
};
|
|
31
|
+
const overrides = value.overrides ?? {};
|
|
32
|
+
if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides) || Object.keys(overrides).length > 1000) throw new Error('单工具覆盖最多 1000 项');
|
|
33
|
+
const entries = Object.entries(overrides).map(([name, v]) => {
|
|
34
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(name)) throw new Error('单工具覆盖需使用有效的工具名');
|
|
35
|
+
return [name, policy(v)] as const;
|
|
36
|
+
});
|
|
37
|
+
return { default: policy(value.default ?? { mode: 'inherit' }), overrides: Object.fromEntries(entries) };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function effectiveToolRateLimit(tool: Pick<ToolDefinition, 'name' | 'rateLimit' | 'rateLimitPerMin'>, policies?: ToolRateLimitPolicies) {
|
|
41
|
+
const override = policies?.overrides && Object.hasOwn(policies.overrides, tool.name) ? policies.overrides[tool.name] : undefined;
|
|
42
|
+
const policy = override ?? policies?.default ?? { mode: 'inherit' };
|
|
43
|
+
const source = policy.mode === 'inherit' ? 'declaration' : override ? 'tool_override' : 'provider_default';
|
|
44
|
+
const limit = policy.mode === 'disabled' ? null : policy.mode === 'custom' ? policy
|
|
45
|
+
: tool.rateLimit ?? (tool.rateLimitPerMin > 0 ? { count: tool.rateLimitPerMin, window: '1m' as const } : null);
|
|
46
|
+
return { enabled: !!limit && limit.count > 0, count: limit?.count ?? 0, window: limit?.window ?? null,
|
|
47
|
+
window_sec: limit ? RATE_WINDOW_SECONDS[limit.window] : 0, source, scope: 'tool_provider_shared' as const };
|
|
48
|
+
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
+
import { effectiveToolRateLimit, type RateLimitRequest, type RateLimitDecision } from './tool-rate-limits';
|
|
1
2
|
// 工具插座运行时治理核心——设计与安全边界见 docs/TOOLS_DESIGN.md
|
|
2
3
|
// 职责:消费 ToolDefinition → 白名单/主体/审批/限流/审计/签名 → 给大脑可调用的运行时句柄。
|
|
3
4
|
// 中枢只做 reach(白名单/风险闸/限流/签名/审计);authority(这个人能不能做)永远由业务侧验签后裁决。
|
|
4
5
|
import { createHash, createHmac } from 'node:crypto';
|
|
6
|
+
import { AgentTaskControlError } from '../runtime/agent-task-control';
|
|
5
7
|
import type { ToolProvider } from './types';
|
|
6
8
|
import { schemaAtPath, schemaTypes, valueMatchesSchemaType, type ToolConfirmCondition, type ToolDefinition } from './tool-definition';
|
|
7
9
|
import { toolSummary } from './tool-definition';
|
|
@@ -233,44 +235,39 @@ function modelFacingToolResponse(fullText: string, status: number, truncateBytes
|
|
|
233
235
|
|
|
234
236
|
// ---- 限流(进程内滑窗,三层:每任务 max_calls 由调用方计数 / 每工具 ACC execution.rate_limit / 工具源总闸)----
|
|
235
237
|
export class LocalSlidingWindowRateLimiter {
|
|
236
|
-
private readonly buckets = new Map<string, number[]>();
|
|
238
|
+
private readonly buckets = new Map<string, { timestamps: number[]; windowMs: number }>();
|
|
237
239
|
private lastSweepAt = 0;
|
|
238
|
-
|
|
239
240
|
constructor(private readonly now: () => number = Date.now) {}
|
|
240
241
|
|
|
241
|
-
consume(key: string,
|
|
242
|
-
|
|
242
|
+
consume(key: string, limit: number, windowSec = 60): boolean {
|
|
243
|
+
return this.consumeAll([{ bucket: key, limit, windowSec }]).limited;
|
|
244
|
+
}
|
|
245
|
+
consumeAll(requests: RateLimitRequest[]): RateLimitDecision {
|
|
243
246
|
const now = this.now();
|
|
244
|
-
this.
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
247
|
+
if (now - this.lastSweepAt >= 60_000) {
|
|
248
|
+
this.lastSweepAt = now;
|
|
249
|
+
for (const [key, bucket] of this.buckets) {
|
|
250
|
+
if (!bucket.timestamps.some((ts) => now - ts < bucket.windowMs)) this.buckets.delete(key);
|
|
251
|
+
}
|
|
249
252
|
}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
if (now - this.lastSweepAt < 60_000) return;
|
|
261
|
-
this.lastSweepAt = now;
|
|
262
|
-
for (const [key, timestamps] of this.buckets) {
|
|
263
|
-
const active = timestamps.filter((timestamp) => now - timestamp < 60_000);
|
|
264
|
-
if (active.length) this.buckets.set(key, active);
|
|
265
|
-
else this.buckets.delete(key);
|
|
253
|
+
const active = requests.filter((r) => r.limit > 0).map((r) => {
|
|
254
|
+
const windowMs = r.windowSec * 1000;
|
|
255
|
+
const timestamps = (this.buckets.get(r.bucket)?.timestamps ?? []).filter((ts) => now - ts < windowMs);
|
|
256
|
+
return { ...r, windowMs, timestamps };
|
|
257
|
+
});
|
|
258
|
+
for (const r of active) {
|
|
259
|
+
if (r.timestamps.length >= r.limit) {
|
|
260
|
+
const expires = r.timestamps[r.timestamps.length - r.limit]! + r.windowMs;
|
|
261
|
+
return { limited: true, bucket: r.bucket, retryAfterMs: Math.max(1, expires - now) };
|
|
262
|
+
}
|
|
266
263
|
}
|
|
264
|
+
// Check every gate before charging any of them.
|
|
265
|
+
for (const r of active) this.buckets.set(r.bucket, { timestamps: [...r.timestamps, now], windowMs: r.windowMs });
|
|
266
|
+
return { limited: false };
|
|
267
267
|
}
|
|
268
|
+
bucketCount(): number { return this.buckets.size; }
|
|
268
269
|
}
|
|
269
|
-
|
|
270
270
|
const localRateLimiter = new LocalSlidingWindowRateLimiter();
|
|
271
|
-
function allowRate(key: string, perMin: number): boolean {
|
|
272
|
-
return !localRateLimiter.consume(key, perMin);
|
|
273
|
-
}
|
|
274
271
|
|
|
275
272
|
/** 渐进式披露阈值:白名单内工具数 ≤ 此值全量内联(省一次往返);超过则目录+按需取定义(防几百个工具定义灌爆上下文)。 */
|
|
276
273
|
export const TOOL_INLINE_MAX = 12;
|
|
@@ -315,12 +312,22 @@ export type ToolGovernanceState =
|
|
|
315
312
|
| 'reconciliation_required';
|
|
316
313
|
|
|
317
314
|
/** 工具调用的受治理结果;旧调用方仍可只读 ok/text/status。 */
|
|
315
|
+
export interface ToolRateLimitFeedback {
|
|
316
|
+
level: 'tool' | 'provider';
|
|
317
|
+
count: number;
|
|
318
|
+
window_sec: number;
|
|
319
|
+
scope: 'tool_provider_shared';
|
|
320
|
+
source: string;
|
|
321
|
+
}
|
|
322
|
+
|
|
318
323
|
export interface ToolInvokeResult {
|
|
319
324
|
ok: boolean;
|
|
320
325
|
text: string;
|
|
321
326
|
status: number;
|
|
322
327
|
governance_state?: ToolGovernanceState;
|
|
323
328
|
auto_retry_allowed?: boolean;
|
|
329
|
+
retry_after_ms?: number;
|
|
330
|
+
rate_limit?: ToolRateLimitFeedback;
|
|
324
331
|
approval_id?: number;
|
|
325
332
|
}
|
|
326
333
|
|
|
@@ -385,6 +392,8 @@ export interface ApprovalDeps {
|
|
|
385
392
|
continuationMode?: 'rerun' | 'resume';
|
|
386
393
|
/** 查"已批准且未消费"的同快照审批单并原子消费;消费成功返回单号,否则 null */
|
|
387
394
|
consumeApproved(tool: string, hash: string): Promise<number | null>;
|
|
395
|
+
/** Managed tasks only: observation without consuming; final permit transaction consumes it. */
|
|
396
|
+
peekApproved?(tool: string, hash: string): Promise<number | null>;
|
|
388
397
|
/** 查同快照 pending 单(去重:同一调用别重复开单) */
|
|
389
398
|
findPending(tool: string, hash: string): Promise<number | null>;
|
|
390
399
|
/** 查本任务同工具"已批准未消费"单(不限参数)——重跑时大脑参数漂移的纠偏依据 */
|
|
@@ -420,6 +429,14 @@ export interface ToolRuntimeDeps {
|
|
|
420
429
|
truncateBytes: number; // 工具结果回流截断(默认 8192)
|
|
421
430
|
approvedNote?: string; // 重跑时已批准调用清单提示
|
|
422
431
|
approvals?: ApprovalDeps; // 不注入 = high/confirm 一律拦
|
|
432
|
+
/** A trusted assembly supplies these hooks; model parameters cannot create a task or permit. */
|
|
433
|
+
taskControl?: {
|
|
434
|
+
prepare(input: { tool: string; argsHash: string; readonly: boolean; approvalRequired: boolean }): Promise<void>;
|
|
435
|
+
grant(input: { tool: string; argsHash: string; scope: string; idempotencyKey: string; approvalId?: number }): Promise<boolean>;
|
|
436
|
+
settle(outcome: 'unknown' | 'confirmed_dispatched', response?: { ok: boolean; status: number; text: string }, evidenceDegraded?: boolean): Promise<void>;
|
|
437
|
+
};
|
|
438
|
+
/** Recheck sticky task enrollment for legacy Agent/engine/executor entrypoints before outbound I/O. */
|
|
439
|
+
beforeDispatch?: () => Promise<void>;
|
|
423
440
|
audit(event: string, detail: Record<string, unknown>): Promise<void>; // 写审计;抛错=调用不放行(fail-closed)
|
|
424
441
|
/** 工具语义检索(装配层注入;不注入 = 不启用检索,退回 progressive):一句意图 → 召回工具名(已是双闸内、按相关度排序)。
|
|
425
442
|
* 返回 null = 检索运行时不可用(索引/凭证/embedding 临时挂)→ retrieve() 透传 null 让适配器降级。本层不碰 embedding,只收名单。 */
|
|
@@ -437,6 +454,7 @@ export interface ToolRuntimeDeps {
|
|
|
437
454
|
};
|
|
438
455
|
/** 集中限速器:返回 true = 已触发限流;不注入时退回进程内滑窗。 */
|
|
439
456
|
rateLimit?: (bucket: string, limit: number, windowSec: number) => Promise<boolean>;
|
|
457
|
+
rateLimitAll?: (requests: RateLimitRequest[]) => Promise<RateLimitDecision>;
|
|
440
458
|
}
|
|
441
459
|
|
|
442
460
|
export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
@@ -508,7 +526,7 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
508
526
|
// 闸1.8:幂等账本——同 job 内"副作用工具"(非只读、非声明幂等)已执行过的相同调用,重试/崩溃恢复重跑时直接返回上次结果,
|
|
509
527
|
// 不重复执行(防写操作重复扣款)。放在审批闸之前:否则重跑时已消费的审批单会被当成"无批准"再次触发待审批,把重跑卡死。
|
|
510
528
|
const sideEffecting = !t.readonly && !t.idempotent;
|
|
511
|
-
if (sideEffecting && !d.idempotency) {
|
|
529
|
+
if ((sideEffecting || d.taskControl) && !d.idempotency) {
|
|
512
530
|
await d.audit('tool_blocked', {
|
|
513
531
|
tool: name,
|
|
514
532
|
scope: t.scope,
|
|
@@ -520,7 +538,7 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
520
538
|
text: `工具 ${name} 会产生业务副作用,但当前运行时未配置持久化执行日志,请求未发出。`,
|
|
521
539
|
};
|
|
522
540
|
}
|
|
523
|
-
const idemHash = sideEffecting ? argsHash(callArgs) : '';
|
|
541
|
+
const idemHash = sideEffecting || d.taskControl ? argsHash(callArgs) : '';
|
|
524
542
|
const idemKey = idemHash ? toolCallIdempotencyKey(d.jobId, name, idemHash, d.onBehalfOf) : '';
|
|
525
543
|
if (idemHash) {
|
|
526
544
|
let existing: ToolExecutionJournalEntry | null;
|
|
@@ -557,19 +575,34 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
557
575
|
}
|
|
558
576
|
// 前置调度闸:任何可重试的限流都必须发生在审批单消费前。
|
|
559
577
|
// 请求尚未出站,不能把 429 伪装成业务拒绝,也不能白白用掉人工批准。
|
|
560
|
-
const
|
|
561
|
-
|
|
562
|
-
:
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
if (
|
|
578
|
+
const effective = effectiveToolRateLimit(t, d.provider.tool_rate_limits);
|
|
579
|
+
const gates: RateLimitRequest[] = [
|
|
580
|
+
{ bucket: `tool:${d.provider.name}:${name}`, limit: effective.enabled ? effective.count : 0, windowSec: effective.window_sec || 60 },
|
|
581
|
+
{ bucket: `provider:${d.provider.name}`, limit: d.provider.rate_limit_per_min, windowSec: 60 },
|
|
582
|
+
].filter((gate) => gate.limit > 0);
|
|
583
|
+
let limitDecision: RateLimitDecision;
|
|
584
|
+
if (d.rateLimitAll) limitDecision = await d.rateLimitAll(gates);
|
|
585
|
+
else if (d.rateLimit) {
|
|
586
|
+
// Compatibility for external runtime assemblers that implement only the legacy single gate callback.
|
|
587
|
+
limitDecision = { limited: false };
|
|
588
|
+
for (const gate of gates) {
|
|
589
|
+
if (await d.rateLimit(gate.bucket, gate.limit, gate.windowSec)) {
|
|
590
|
+
limitDecision = { limited: true, bucket: gate.bucket, retryAfterMs: gate.windowSec * 1000 };
|
|
591
|
+
break;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
} else limitDecision = localRateLimiter.consumeAll(gates);
|
|
595
|
+
if (limitDecision.limited) {
|
|
596
|
+
const gate = gates.find((candidate) => candidate.bucket === limitDecision.bucket) ?? gates[0]!;
|
|
597
|
+
const level = gate.bucket.startsWith('provider:') ? 'provider' : 'tool';
|
|
567
598
|
return {
|
|
568
599
|
ok: false,
|
|
569
|
-
text: `工具 ${name}
|
|
600
|
+
text: `工具 ${name} 达到${level === 'tool' ? '单工具' : '工具源总'}限额(该工具源下的用户与会话共享)。调用未派发;等待后通过原 invocation_id 恢复,不要创建新调用。`,
|
|
570
601
|
status: 429,
|
|
571
602
|
governance_state: 'rejected_before_dispatch',
|
|
572
603
|
auto_retry_allowed: true,
|
|
604
|
+
retry_after_ms: limitDecision.retryAfterMs ?? gate.windowSec * 1000,
|
|
605
|
+
rate_limit: { level, count: gate.limit, window_sec: gate.windowSec, scope: 'tool_provider_shared', source: level === 'tool' ? effective.source : 'provider_total' },
|
|
573
606
|
};
|
|
574
607
|
}
|
|
575
608
|
// 闸2:风险闸 + 审批车道(B 方案:先撤再来)。high / confirm-required 的调用:
|
|
@@ -583,13 +616,16 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
583
616
|
}
|
|
584
617
|
const confirmHit = confirmCheck.hit;
|
|
585
618
|
const needsApproval = t.risk === 'high' || t.confirmRequired || !!confirmHit;
|
|
619
|
+
if (d.taskControl) await d.taskControl.prepare({ tool: name, argsHash: argsHash(callArgs),
|
|
620
|
+
readonly: t.readonly, approvalRequired: needsApproval });
|
|
586
621
|
if (needsApproval) {
|
|
587
622
|
if (!d.approvals) { // 未接审批车道(理论不发生,server 总会注入):一律拦
|
|
588
623
|
await d.audit('tool_blocked', { tool: name, scope: t.scope, reason: approvalReason(t, confirmHit) }).catch(() => undefined);
|
|
589
624
|
return { ok: false, text: `工具 ${name} 属于需人工确认的高风险操作,当前不允许自动执行。请告知用户走人工流程。`, status: 0, governance_state: 'rejected_before_dispatch', auto_retry_allowed: false };
|
|
590
625
|
}
|
|
591
626
|
const hash = argsHash(callArgs);
|
|
592
|
-
|
|
627
|
+
if (d.taskControl && !d.approvals.peekApproved) throw new AgentTaskControlError('TASK_UNSUPPORTED');
|
|
628
|
+
approvalId = d.taskControl ? await d.approvals.peekApproved!(name, hash) : await d.approvals.consumeApproved(name, hash);
|
|
593
629
|
if (approvalId === null) {
|
|
594
630
|
const pendingId = await d.approvals.findPending(name, hash);
|
|
595
631
|
if (pendingId !== null) {
|
|
@@ -655,7 +691,17 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
655
691
|
...(approvalId !== null ? { approval_id: approvalId } : {}),
|
|
656
692
|
});
|
|
657
693
|
|
|
658
|
-
if (
|
|
694
|
+
if (d.beforeDispatch) await d.beforeDispatch();
|
|
695
|
+
if (d.taskControl) {
|
|
696
|
+
const fresh = await d.taskControl.grant({ tool: name, argsHash: idemHash, scope: t.scope,
|
|
697
|
+
idempotencyKey: idemKey, ...(approvalId !== null ? { approvalId } : {}) });
|
|
698
|
+
if (!fresh) {
|
|
699
|
+
const existing = await d.idempotency!.get(name, idemHash);
|
|
700
|
+
if (existing?.state === 'completed') return { ok: existing.ok, text: existing.text, status: existing.status };
|
|
701
|
+
return { ok: false, text: 'The original task invocation already owns a dispatch attempt. Inspect the original invocation; do not replay it.',
|
|
702
|
+
status: 0, governance_state: 'reconciliation_required', auto_retry_allowed: false };
|
|
703
|
+
}
|
|
704
|
+
} else if (idemHash) {
|
|
659
705
|
let reserved: { inserted: boolean; entry: ToolExecutionJournalEntry };
|
|
660
706
|
try {
|
|
661
707
|
reserved = await d.idempotency!.reserve(name, t.scope, idemHash, idemKey);
|
|
@@ -722,6 +768,7 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
722
768
|
} catch (e) {
|
|
723
769
|
const error = e instanceof Error && e.name === 'TimeoutError' ? `超时(${timeoutMs}ms)` : String(e);
|
|
724
770
|
fullText = `调用结果不确定:${error}`;
|
|
771
|
+
if (d.taskControl) await d.taskControl.settle('unknown').catch(() => undefined);
|
|
725
772
|
if (idemHash) {
|
|
726
773
|
await d.idempotency!.markUncertain(name, idemHash, error).catch(() => undefined);
|
|
727
774
|
executionUncertainty = {
|
|
@@ -741,12 +788,29 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
741
788
|
}).catch(() => undefined);
|
|
742
789
|
return { ok: false, text: executionUncertainty.message, status: 0, governance_state: 'reconciliation_required', auto_retry_allowed: false };
|
|
743
790
|
}
|
|
791
|
+
// fetch (including response body consumption) has already been attempted. Readonly or
|
|
792
|
+
// declared-idempotent tools do not use the execution journal, but a missing response
|
|
793
|
+
// still cannot prove that dispatch was rejected. Agent invocations persist this state
|
|
794
|
+
// and resume the original result instead of dispatching a replacement call.
|
|
795
|
+
await d.audit('tool_reconciliation_required', {
|
|
796
|
+
tool: name,
|
|
797
|
+
scope: t.scope,
|
|
798
|
+
state: 'uncertain',
|
|
799
|
+
reason: error,
|
|
800
|
+
}).catch(() => undefined);
|
|
801
|
+
return {
|
|
802
|
+
ok: false,
|
|
803
|
+
text: `工具 ${name} 的请求已尝试发出,但未取得可信响应,执行结果未知。禁止自动重试或新建调用;请恢复原调用,必要时人工核实结果。`,
|
|
804
|
+
status: 0,
|
|
805
|
+
governance_state: 'reconciliation_required',
|
|
806
|
+
auto_retry_allowed: false,
|
|
807
|
+
};
|
|
744
808
|
}
|
|
745
809
|
// 回流给模型的:受上下文预算 truncateBytes 截断(与审计留存解耦)
|
|
746
810
|
const text = modelFacingToolResponse(fullText, status, d.truncateBytes, responseContentType);
|
|
747
811
|
const ok = status >= 200 && status < 300;
|
|
748
812
|
const retText = text || `(HTTP ${status} 空响应)`;
|
|
749
|
-
if (idemHash) {
|
|
813
|
+
if (idemHash && !d.taskControl) {
|
|
750
814
|
try {
|
|
751
815
|
await d.idempotency!.recordResponse(name, idemHash, { ok, status, text: retText });
|
|
752
816
|
} catch (error) {
|
|
@@ -782,6 +846,13 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
782
846
|
...respLog,
|
|
783
847
|
});
|
|
784
848
|
} catch (error) {
|
|
849
|
+
if (d.taskControl) {
|
|
850
|
+
await d.taskControl.settle('confirmed_dispatched', { ok, status, text: retText }, true).catch(() => undefined);
|
|
851
|
+
executionUncertainty = { state: 'evidence_degraded', tool: name, scope: t.scope, idempotency_key: idemKey,
|
|
852
|
+
reason: 'The business response was received, but its audit evidence could not be completed.',
|
|
853
|
+
message: 'The original operation may have completed; inspect its original receipt. Do not submit a replacement operation.' };
|
|
854
|
+
return { ok: false, text: executionUncertainty.message, status: 0, governance_state: 'reconciliation_required', auto_retry_allowed: false };
|
|
855
|
+
}
|
|
785
856
|
if (idemHash) {
|
|
786
857
|
const reason = `业务响应已收到,但结果审计写入失败:${String(error).slice(0, 300)}`;
|
|
787
858
|
await d.idempotency!.markEvidenceDegraded(name, idemHash, reason).catch(() => undefined);
|
|
@@ -797,7 +868,15 @@ export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
|
797
868
|
}
|
|
798
869
|
throw error;
|
|
799
870
|
}
|
|
800
|
-
if (
|
|
871
|
+
if (d.taskControl) {
|
|
872
|
+
try { await d.taskControl.settle('confirmed_dispatched', { ok, status, text: retText }); }
|
|
873
|
+
catch {
|
|
874
|
+
executionUncertainty = { state: 'uncertain', tool: name, scope: t.scope, idempotency_key: idemKey,
|
|
875
|
+
reason: 'The response was received but task settlement was not confirmed.',
|
|
876
|
+
message: 'Task settlement is unconfirmed. Inspect the original invocation; do not repeat the business operation.' };
|
|
877
|
+
return { ok: false, text: executionUncertainty.message, status: 0, governance_state: 'reconciliation_required', auto_retry_allowed: false };
|
|
878
|
+
}
|
|
879
|
+
} else if (idemHash) {
|
|
801
880
|
try {
|
|
802
881
|
await d.idempotency!.complete(name, idemHash);
|
|
803
882
|
} catch (error) {
|
|
@@ -301,6 +301,7 @@ export interface Route {
|
|
|
301
301
|
instructions?: string;
|
|
302
302
|
active_tool_limit?: number;
|
|
303
303
|
system_info?: AgentSystemInfo;
|
|
304
|
+
artifact_upload?: import('../config/artifact-config').AgentArtifactConfig;
|
|
304
305
|
};
|
|
305
306
|
budget?: Record<string, unknown>; // 成本预算闸:{window/window_hours, hard_cost_usd?, hard_tokens?, ...}
|
|
306
307
|
description?: string;
|
|
@@ -343,7 +344,7 @@ export interface ChatAppearance {
|
|
|
343
344
|
/** 媒体存储登记:聊天上传的图片/语音/附件落盘或落桶取永久 URL。local 开箱即用;业务桶=业务 CDN、加商品零转存。secret_key 不回显。 */
|
|
344
345
|
export interface StorageBucket {
|
|
345
346
|
name: string;
|
|
346
|
-
kind: 'local' | 'cos' | 'oss' | 's3'; // 当前实现 local/cos
|
|
347
|
+
kind: 'local' | 'cos' | 'oss' | 's3'; // 当前实现 local/cos/oss
|
|
347
348
|
region: string; // ap-shanghai
|
|
348
349
|
bucket: string; // 桶名(COS 带 appid 后缀)
|
|
349
350
|
endpoint?: string; // 自定义 endpoint;留空按 kind+region 拼
|
|
@@ -420,6 +421,7 @@ export interface ToolApproval {
|
|
|
420
421
|
|
|
421
422
|
/** 工具源:业务系统的 Agent 可调接口清单(OpenAPI + x-agent-capability 契约)。secret 用于 v2 调用签名,不回显。 */
|
|
422
423
|
export interface ToolProvider {
|
|
424
|
+
tool_rate_limits?: import('./tool-rate-limits').ToolRateLimitPolicies;
|
|
423
425
|
name: string;
|
|
424
426
|
base_url: string;
|
|
425
427
|
spec_source: 'url' | 'inline';
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import {
|
|
4
|
+
AgentTaskControlError, agentTaskHash, assertTaskCanDispatch, assertTaskWriteCapacity, compareTaskStrings,
|
|
5
|
+
normalizeAgentTaskMembers, normalizeAgentTaskPolicy, taskText, taskUuid, transitionAgentTask, validateTaskInvocation,
|
|
6
|
+
type AgentControlledTask, type AgentTaskMemberInput,
|
|
7
|
+
} from './agent-task-control';
|
|
8
|
+
|
|
9
|
+
const SESSION = 'abcdefab-abcd-4abc-8abc-abcdefabcdef';
|
|
10
|
+
const TASK = '11111111-1111-4111-8111-111111111111';
|
|
11
|
+
const NOW = '2026-09-16T01:00:00.000Z';
|
|
12
|
+
const policy = () => ({ maxWriteCalls: 2, maxConcurrent: 1, expiresAt: null });
|
|
13
|
+
const member = (sessionId = SESSION): AgentTaskMemberInput => ({ sessionId, clientAppId: 'example-shop',
|
|
14
|
+
route: 'shop', clientConversationId: 'conversation-1', allowedTools: ['product_update', 'product_lookup'] });
|
|
15
|
+
const task = (): AgentControlledTask => ({ taskId: TASK, state: 'active', revision: 3, ledgerSequence: 12,
|
|
16
|
+
policy: policy(), members: [{ ...member(), identityHash: 'a'.repeat(64) }], scopeHash: 'b'.repeat(64),
|
|
17
|
+
writeReserved: 0, writeConsumed: 0, activePermits: 0, createdBy: 'admin-1', createdAt: NOW, updatedAt: NOW });
|
|
18
|
+
const rejectsCode = (work: () => unknown, code: string) => assert.throws(work,
|
|
19
|
+
(error) => error instanceof AgentTaskControlError && error.code === code);
|
|
20
|
+
|
|
21
|
+
test('task policy: no implicit low write limit; zero, bounded and explicitly unlimited remain distinct', () => {
|
|
22
|
+
assert.deepEqual(normalizeAgentTaskPolicy(policy()), policy());
|
|
23
|
+
assert.equal(normalizeAgentTaskPolicy({ ...policy(), maxWriteCalls: 0 }).maxWriteCalls, 0);
|
|
24
|
+
assert.equal(normalizeAgentTaskPolicy({ ...policy(), maxWriteCalls: null }).maxWriteCalls, null);
|
|
25
|
+
for (const invalid of [-1, 0.5, NaN, '120', undefined, Number.MAX_SAFE_INTEGER]) {
|
|
26
|
+
rejectsCode(() => normalizeAgentTaskPolicy({ ...policy(), maxWriteCalls: invalid } as any), 'TASK_INVALID_INPUT');
|
|
27
|
+
}
|
|
28
|
+
for (const invalid of [0, -1, 0.5, '2', null]) {
|
|
29
|
+
rejectsCode(() => normalizeAgentTaskPolicy({ ...policy(), maxConcurrent: invalid } as any), 'TASK_INVALID_INPUT');
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('task expiration rejects impossible calendar dates instead of silently extending the deadline', () => {
|
|
34
|
+
for (const expiresAt of ['2026-02-30T12:00:00Z', '2026-02-29T12:00:00Z', '2026-01-01T24:00:00Z',
|
|
35
|
+
'2026-09-16T01:00:00+08:00', '0001-01-01T00:00:00Z', 'invalid']) {
|
|
36
|
+
rejectsCode(() => normalizeAgentTaskPolicy({ ...policy(), expiresAt }), 'TASK_INVALID_INPUT');
|
|
37
|
+
}
|
|
38
|
+
assert.equal(normalizeAgentTaskPolicy({ ...policy(), expiresAt: '2028-02-29T12:00:00.1Z' }).expiresAt,
|
|
39
|
+
'2028-02-29T12:00:00.100Z');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('task members use exact runtime conversation identifiers and independent copies', () => {
|
|
43
|
+
const a = member();
|
|
44
|
+
const b = member('22222222-2222-4222-8222-222222222222');
|
|
45
|
+
const normalized = normalizeAgentTaskMembers([a, b]);
|
|
46
|
+
assert.deepEqual(normalized, normalizeAgentTaskMembers([b, a]));
|
|
47
|
+
assert.deepEqual(normalized.find((item) => item.sessionId === SESSION)!.allowedTools, ['product_lookup', 'product_update']);
|
|
48
|
+
a.allowedTools.push('another_tool'); a.clientConversationId = 'another-conversation';
|
|
49
|
+
assert.equal(normalized.some((item) => item.allowedTools.includes('another_tool')), false);
|
|
50
|
+
for (const clientConversationId of [' conversation-1', 'conversation-1 ', 'é', 'e\u0301', '', 'x\n']) {
|
|
51
|
+
rejectsCode(() => normalizeAgentTaskMembers([{ ...member(), clientConversationId }]), 'TASK_INVALID_INPUT');
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('task canonical hashes are independent of locale collation and object insertion order', () => {
|
|
56
|
+
assert.notEqual(compareTaskStrings('é', 'e\u0301'), 0);
|
|
57
|
+
assert.equal(agentTaskHash({ é: 1, 'e\u0301': 2 }), agentTaskHash({ 'e\u0301': 2, é: 1 }));
|
|
58
|
+
assert.notEqual(agentTaskHash({ é: 1 }), agentTaskHash({ 'e\u0301': 1 }));
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('task identifiers cannot obtain a second enforcement identity through UUID casing', () => {
|
|
62
|
+
assert.equal(taskUuid(SESSION.toUpperCase()), SESSION);
|
|
63
|
+
assert.equal(normalizeAgentTaskMembers([member(SESSION.toUpperCase())])[0]!.sessionId, SESSION);
|
|
64
|
+
rejectsCode(() => normalizeAgentTaskMembers([member(SESSION), member(SESSION.toUpperCase())]), 'TASK_INVALID_INPUT');
|
|
65
|
+
rejectsCode(() => taskText('\ud800', 128), 'TASK_INVALID_INPUT');
|
|
66
|
+
assert.equal(taskText('admin-😀', 128), 'admin-😀');
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('task policy and members reject unsupported limits, unbounded tools and conversation bodies', () => {
|
|
70
|
+
rejectsCode(() => normalizeAgentTaskPolicy({ ...policy(), maxProducts: 10 } as any), 'TASK_INVALID_INPUT');
|
|
71
|
+
rejectsCode(() => normalizeAgentTaskMembers([{ ...member(), accessToken: 'synthetic-credential' } as any]), 'TASK_INVALID_INPUT');
|
|
72
|
+
rejectsCode(() => normalizeAgentTaskMembers([{ ...member(), body: 'Synthetic conversation' } as any]), 'TASK_INVALID_INPUT');
|
|
73
|
+
for (const allowedTools of [[], ['*'], ['product_lookup', 'product_lookup'], ['invalid-tool']]) {
|
|
74
|
+
rejectsCode(() => normalizeAgentTaskMembers([{ ...member(), allowedTools }]), 'TASK_INVALID_INPUT');
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('cumulative write availability includes reserved and consumed calls, not only successful calls', () => {
|
|
79
|
+
const current = task(); current.writeReserved = 1; current.writeConsumed = 1;
|
|
80
|
+
rejectsCode(() => assertTaskWriteCapacity(current), 'TASK_WRITE_BUDGET_EXHAUSTED');
|
|
81
|
+
current.writeReserved = 0; assertTaskWriteCapacity(current);
|
|
82
|
+
current.policy.maxWriteCalls = 0;
|
|
83
|
+
rejectsCode(() => assertTaskWriteCapacity(current), 'TASK_WRITE_BUDGET_EXHAUSTED');
|
|
84
|
+
current.policy.maxWriteCalls = null; assertTaskWriteCapacity(current);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('pause, block and cancellation cannot grant new dispatch; expiry does not reset the budget', () => {
|
|
88
|
+
for (const [state, code] of [['paused', 'TASK_PAUSED'], ['blocked', 'TASK_SCOPE_BLOCKED'], ['cancelled', 'TASK_CANCELLED']] as const) {
|
|
89
|
+
rejectsCode(() => assertTaskCanDispatch({ ...task(), state }, NOW), code);
|
|
90
|
+
}
|
|
91
|
+
const current = task(); current.writeConsumed = 1; current.policy.expiresAt = NOW;
|
|
92
|
+
rejectsCode(() => assertTaskCanDispatch(current, NOW), 'TASK_EXPIRED');
|
|
93
|
+
assert.equal(current.writeConsumed, 1);
|
|
94
|
+
current.policy.expiresAt = '2026-09-16T01:00:00.001Z'; assertTaskCanDispatch(current, NOW);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('cancellation is terminal; a blocked task must first be explicitly paused before resume', () => {
|
|
98
|
+
for (const state of ['active', 'paused', 'blocked'] as const) assert.equal(transitionAgentTask(state, 'cancel'), 'cancelled');
|
|
99
|
+
for (const action of ['pause', 'resume', 'cancel'] as const) {
|
|
100
|
+
rejectsCode(() => transitionAgentTask('cancelled', action), 'TASK_CANCELLED');
|
|
101
|
+
}
|
|
102
|
+
rejectsCode(() => transitionAgentTask('blocked', 'resume'), 'TASK_CONTROL_CONFLICT');
|
|
103
|
+
assert.equal(transitionAgentTask(transitionAgentTask('blocked', 'pause'), 'resume'), 'active');
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('invocation input requires an explicit trusted read/write classification and exact coordinates', () => {
|
|
107
|
+
const original = { taskId: TASK, sessionId: SESSION, invocationId: 'c'.repeat(64), runId: TASK, jobId: TASK,
|
|
108
|
+
tool: 'product_update', argsHash: 'd'.repeat(64), executionFingerprint: 'e'.repeat(64), readonly: false, approvalRequired: true };
|
|
109
|
+
assert.deepEqual(validateTaskInvocation(original), original);
|
|
110
|
+
rejectsCode(() => validateTaskInvocation({ ...original, readonly: undefined } as any), 'TASK_INVALID_INPUT');
|
|
111
|
+
rejectsCode(() => validateTaskInvocation({ ...original, arguments: { id: 1 } } as any), 'TASK_INVALID_INPUT');
|
|
112
|
+
rejectsCode(() => validateTaskInvocation({ ...original, idempotent: true } as any), 'TASK_INVALID_INPUT');
|
|
113
|
+
rejectsCode(() => validateTaskInvocation({ ...original, invocationId: 'replacement-id' }), 'TASK_INVALID_INPUT');
|
|
114
|
+
});
|