bailinghub 0.6.1 → 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 +8 -7
- package/README.md +7 -7
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_AUTH_API.en.md +112 -1
- package/docs/AGENT_AUTH_API.md +99 -1
- package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
- package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
- package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
- package/docs/AGENT_CLIENT_RUNTIME_API.md +38 -1
- package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
- package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
- package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
- package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
- package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
- package/docs/AGENT_SYSTEM_INFO.md +97 -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 +24 -1
- package/docs/CHANGELOG.md +24 -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/LOCAL_AGENT_SETUP.en.md +116 -0
- package/docs/LOCAL_AGENT_SETUP.md +116 -0
- package/docs/README.en.md +9 -0
- package/docs/README.md +9 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
- package/docs/RELEASE_NOTES_NEXT.md +3 -0
- package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
- package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
- package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
- package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
- package/docs/SDK.en.md +31 -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/user-guide/conversations.en.md +4 -2
- package/docs/user-guide/conversations.md +4 -2
- 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 +16 -2
- package/schemas/config/tool-provider.schema.json +2 -1
- package/scripts/check-doc-links.mjs +2 -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 +2 -0
- package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
- package/scripts/sdk-runtime-test.mjs +5 -2
- package/scripts/verify-github-repo.mjs +2 -0
- package/sdk/php/README.md +29 -0
- package/sdk/php/src/AgentAuth.php +100 -4
- package/sdk/php/src/HubClient.php +2 -1
- package/sdk/php7/README.md +31 -0
- package/sdk/php7/src/AgentAuth.php +99 -4
- package/sdk/php7/src/HubClient.php +2 -1
- package/sql/058_agent_conversation_member_bindings.sql +9 -0
- package/sql/059_agent_subject_display.sql +5 -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/sql/README.en.md +15 -0
- package/sql/README.md +25 -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-conversation-audit.ts +20 -0
- package/src/app/agent-invocation-snapshot.ts +35 -0
- package/src/app/agent-system-info.ts +41 -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 +239 -14
- 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/agent-setup.ts +37 -0
- package/src/core/config/artifact-config.ts +15 -0
- package/src/core/config/client-agent-setup.ts +25 -0
- package/src/core/config/config-codec.ts +3 -1
- package/src/core/config/config-models.ts +11 -1
- package/src/core/config/config-schema.test.ts +11 -0
- package/src/core/config/route-config.test.ts +28 -0
- package/src/core/config/route-config.ts +44 -4
- package/src/core/contracts/agent-subject-display.test.ts +19 -0
- package/src/core/contracts/agent-subject-display.ts +36 -0
- 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 +18 -1
- package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
- package/src/core/runtime/agent-conversation-audit.ts +39 -0
- 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-auth-business-sessions.test.ts +120 -0
- package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
- package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
- package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
- package/src/infrastructure/config/config-agent-client-runtime-repository.ts +7 -1
- package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
- package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
- package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
- 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-client-repository.ts +21 -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-route-agent-setup.test.ts +59 -0
- package/src/infrastructure/config/config-route-repository.ts +24 -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 +16 -4
- package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
- package/src/routes/admin-access.ts +37 -0
- package/src/routes/admin-agent-clients.ts +11 -0
- package/src/routes/admin-agent-setup.test.ts +130 -0
- package/src/routes/admin-agent-setup.ts +68 -0
- package/src/routes/admin-agent-tasks.ts +32 -0
- package/src/routes/admin-client-agent-setup.test.ts +93 -0
- package/src/routes/admin-dispatch-config.ts +2 -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 +49 -1
- package/src/routes/agent-artifacts.ts +29 -0
- package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
- package/src/routes/agent-auth-lifecycle.test.ts +193 -0
- package/src/routes/agent-auth.test.ts +1 -1
- package/src/routes/agent-auth.ts +206 -16
- package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
- package/src/routes/agent-conversation-audit.ts +8 -2
- package/src/routes/agent-subject-display-http.test.ts +145 -0
- package/src/routes/agent-system-info.test.ts +132 -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-auth-business-query-fixture.ts +43 -0
- package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
- package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
- package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
- package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
- package/web/connect/bailing-connect-php.tgz +0 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/{Accounts-Ca_VnSu9.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-CMvPWacY.js → Approvals-BIbZvInm.js} +1 -1
- package/web/console/assets/{Audit-CIRqOCnL.js → Audit-KyPSmBdZ.js} +1 -1
- package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-Sv5DU2G6.js} +1 -1
- package/web/console/assets/{Channels-CApxH2TB.js → Channels-B9n4fbxg.js} +1 -1
- package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-xsOCUXi_.js} +1 -1
- package/web/console/assets/Clients-CI3DBDHf.js +3 -0
- package/web/console/assets/Clients-CSHIsaWU.css +1 -0
- package/web/console/assets/{Cost-BbhlQFP8.js → Cost-JgNXQPlN.js} +1 -1
- package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-B5UUUdt0.js} +1 -1
- package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-BMGciWQb.js} +1 -1
- package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CRbboOCZ.js} +1 -1
- package/web/console/assets/{Kb-DLZSAFWP.js → Kb-CgLNGjRp.js} +1 -1
- package/web/console/assets/{Login-DiTjPWmN.js → Login-C52JmXzx.js} +1 -1
- package/web/console/assets/{Projects-CXcVCgCD.js → Projects-CDOvHPVS.js} +1 -1
- package/web/console/assets/Routes-DkMIjMQA.css +1 -0
- package/web/console/assets/Routes-X9vHLpKW.js +124 -0
- package/web/console/assets/Runs-CvGTV8I-.css +1 -0
- package/web/console/assets/Runs-DYNDXsqk.js +3 -0
- package/web/console/assets/{Setup-FqoCKmfZ.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-gTQAazu7.js → SystemSettings-B7Mqj3k1.js} +1 -1
- package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-Db93b6dc.js} +1 -1
- package/web/console/assets/{Targets-CZmDcjsE.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-r7GHVJzw.js → request-DeGya810.js} +1 -1
- package/web/console/assets/{schema-BVn_hB7M.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/scripts/subject-display-ui.mjs +78 -0
- package/web-admin/src/components/AgentSetupPanel.vue +275 -0
- package/web-admin/src/components/ClientConversations.vue +21 -4
- package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
- package/web-admin/src/components/conversation-audit.ts +20 -0
- package/web-admin/src/layout/Shell.vue +1 -1
- package/web-admin/src/pages/AgentClients.vue +99 -23
- package/web-admin/src/pages/AgentTasks.vue +281 -0
- package/web-admin/src/pages/Clients.vue +4 -1
- package/web-admin/src/pages/Routes.vue +10 -1
- 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-admin/tests/conversation-audit.fixture.mjs +13 -10
- package/web-admin/tests/conversation-audit.test.mjs +63 -1
- package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
- package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
- package/web/console/assets/Clients-BSA1rlTB.js +0 -3
- package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
- package/web/console/assets/Routes-CXGl9SMM.css +0 -1
- package/web/console/assets/Routes-DN9_d9Po.js +0 -124
- package/web/console/assets/Runs-Cwbe6thL.js +0 -3
- package/web/console/assets/Runs-D8UmjP5G.css +0 -1
- package/web/console/assets/Shell-BEqpONiy.js +0 -1
- package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
- package/web/console/assets/StorageBuckets-CkORbYXY.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-CIHInlHL.js +0 -2
- package/web/console/assets/index-BkLbd7Cc.js +0 -2
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
3
|
+
import type { AgentToolAuthContext } from './agent-tool-invocations';
|
|
4
|
+
import {
|
|
5
|
+
AgentTaskControlError, assertTaskCanDispatch, taskAssert, taskDigest, taskInteger, taskText, taskUuid,
|
|
6
|
+
normalizeAgentTaskMembers, normalizeAgentTaskPolicy,
|
|
7
|
+
type AgentControlledTask, type AgentTaskMember, type AgentTaskMemberInput, type AgentTaskInvocation,
|
|
8
|
+
} from '../core/runtime/agent-task-control';
|
|
9
|
+
|
|
10
|
+
export const AGENT_TASK_SCHEMA = 'bailing.agent-task.v1';
|
|
11
|
+
export const AGENT_TASK_BINDING_SCHEMA = 'bailing.agent-task-binding.v1';
|
|
12
|
+
export const AGENT_TASK_CAPABILITIES_SCHEMA = 'bailing.agent-task-control-capabilities.v1';
|
|
13
|
+
export interface AgentTaskBinding {
|
|
14
|
+
schema_version: typeof AGENT_TASK_BINDING_SCHEMA;
|
|
15
|
+
task_id: string;
|
|
16
|
+
scope_hash: string;
|
|
17
|
+
}
|
|
18
|
+
function record(value: unknown): Record<string, unknown> {
|
|
19
|
+
taskAssert(value && typeof value === 'object' && !Array.isArray(value), 'TASK_INVALID_INPUT');
|
|
20
|
+
return value as Record<string, unknown>;
|
|
21
|
+
}
|
|
22
|
+
function exact(value: unknown, fields: string[]): Record<string, unknown> {
|
|
23
|
+
const result = record(value);
|
|
24
|
+
taskAssert(Object.keys(result).length === fields.length && fields.every((key) => Object.hasOwn(result, key)), 'TASK_INVALID_INPUT');
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
export function parseAgentTaskBinding(value: unknown): AgentTaskBinding {
|
|
28
|
+
const body = exact(value, ['schema_version', 'task_id', 'scope_hash']);
|
|
29
|
+
taskAssert(body.schema_version === AGENT_TASK_BINDING_SCHEMA, 'TASK_UNSUPPORTED');
|
|
30
|
+
return { schema_version: AGENT_TASK_BINDING_SCHEMA, task_id: taskUuid(body.task_id), scope_hash: taskDigest(body.scope_hash) };
|
|
31
|
+
}
|
|
32
|
+
export function bindingForTask(task: AgentControlledTask): AgentTaskBinding {
|
|
33
|
+
return { schema_version: AGENT_TASK_BINDING_SCHEMA, task_id: task.taskId, scope_hash: task.scopeHash };
|
|
34
|
+
}
|
|
35
|
+
export async function taskRepository(store: ConfigStoreContract | null) {
|
|
36
|
+
const repo = store?.agentTaskControl;
|
|
37
|
+
taskAssert(repo && await repo.supportsTaskControl(), 'TASK_UNSUPPORTED');
|
|
38
|
+
return repo;
|
|
39
|
+
}
|
|
40
|
+
export async function agentTaskCapabilitiesFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext, runtimeWired: boolean) {
|
|
41
|
+
const repo = store?.agentTaskControl;
|
|
42
|
+
const available = Boolean(repo && await repo.supportsTaskControl());
|
|
43
|
+
const supported = Boolean(runtimeWired && store?.agentClientRuntime && available);
|
|
44
|
+
const marker = available ? await repo!.getEnforcement(auth.session.session_id) : null;
|
|
45
|
+
return { schema_version: AGENT_TASK_CAPABILITIES_SCHEMA, supported, mode: marker ? 'required' : 'optional',
|
|
46
|
+
task_schema: AGENT_TASK_SCHEMA, metering: 'write_invocation', same_hub_only: true,
|
|
47
|
+
controls: ['pause', 'resume', 'cancel'], inspect_invocation: supported };
|
|
48
|
+
}
|
|
49
|
+
function memberView(member: AgentTaskMember) {
|
|
50
|
+
return { session_id: member.sessionId, client_app_id: member.clientAppId, workspace: member.route,
|
|
51
|
+
client_conversation_id: member.clientConversationId, allowed_tools: [...member.allowedTools] };
|
|
52
|
+
}
|
|
53
|
+
function commonView(task: AgentControlledTask) {
|
|
54
|
+
return { schema_version: AGENT_TASK_SCHEMA, task_id: task.taskId, state: task.state,
|
|
55
|
+
revision: task.revision, ledger_sequence: task.ledgerSequence, scope_hash: task.scopeHash, member_count: task.members.length,
|
|
56
|
+
policy: { max_write_calls: task.policy.maxWriteCalls, max_concurrent: task.policy.maxConcurrent, expires_at: task.policy.expiresAt },
|
|
57
|
+
counters: { write_reserved: task.writeReserved, write_consumed: task.writeConsumed, active_permits: task.activePermits },
|
|
58
|
+
metering: 'write_invocation', snapshot_is_dispatch_permission: false };
|
|
59
|
+
}
|
|
60
|
+
export function adminTaskView(task: AgentControlledTask) {
|
|
61
|
+
return { ...commonView(task), members: task.members.map(memberView), created_at: task.createdAt, updated_at: task.updatedAt };
|
|
62
|
+
}
|
|
63
|
+
export async function inspectAgentTaskFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext,
|
|
64
|
+
id: string, workspace: string, conversation: string) {
|
|
65
|
+
const repo = await taskRepository(store);
|
|
66
|
+
const member = { sessionId: auth.session.session_id, clientAppId: auth.client.app_id,
|
|
67
|
+
route: taskText(workspace, 64), clientConversationId: taskText(conversation, 128) };
|
|
68
|
+
const task = await repo.validateMember(taskUuid(id), member);
|
|
69
|
+
const selected = task.members.find((item) => item.sessionId === member.sessionId && item.clientAppId === member.clientAppId
|
|
70
|
+
&& item.route === member.route && item.clientConversationId === member.clientConversationId);
|
|
71
|
+
taskAssert(selected, 'TASK_MEMBER_MISMATCH');
|
|
72
|
+
return { ...commonView(task), member: memberView(selected) };
|
|
73
|
+
}
|
|
74
|
+
/** Before any message/context/run is created; no default task and no auto enrollment. */
|
|
75
|
+
export async function admitAgentTaskTurnFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext,
|
|
76
|
+
workspace: string, conversation: string, rawBinding: unknown): Promise<AgentControlledTask | null> {
|
|
77
|
+
const repo = store?.agentTaskControl;
|
|
78
|
+
if (rawBinding === undefined) {
|
|
79
|
+
if (repo && await repo.supportsTaskControl()) taskAssert(!await repo.getEnforcement(auth.session.session_id), 'TASK_REQUIRED');
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
const binding = parseAgentTaskBinding(rawBinding);
|
|
83
|
+
const available = await taskRepository(store);
|
|
84
|
+
const task = await available.validateMember(binding.task_id, { sessionId: auth.session.session_id,
|
|
85
|
+
clientAppId: auth.client.app_id, route: workspace, clientConversationId: conversation }, binding.scope_hash);
|
|
86
|
+
assertTaskCanDispatch(task, new Date().toISOString());
|
|
87
|
+
return task;
|
|
88
|
+
}
|
|
89
|
+
/** Check the original run for new calls and existing invocation recovery, never trust metadata supplied by the model. */
|
|
90
|
+
export async function resolveAgentTaskRunFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext,
|
|
91
|
+
runId: string, workspace: string, requireActiveRun: boolean): Promise<AgentControlledTask | null> {
|
|
92
|
+
const repo = store?.agentTaskControl;
|
|
93
|
+
if (!repo || !await repo.supportsTaskControl()) return null;
|
|
94
|
+
const task = await repo.findTaskForRun(runId, auth.session.session_id);
|
|
95
|
+
if (!task) {
|
|
96
|
+
taskAssert(!await repo.getEnforcement(auth.session.session_id), 'TASK_REQUIRED');
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
const run = await store!.agentClientRuntime?.findRunForInvocation(runId);
|
|
100
|
+
taskAssert(run && run.session_id === auth.session.session_id && run.client_app_id === auth.client.app_id
|
|
101
|
+
&& run.route_key === workspace, 'TASK_BINDING_CONFLICT');
|
|
102
|
+
if (requireActiveRun) taskAssert(run.status === 'context_ready' && !run.completed_at, 'TASK_RUN_INACTIVE');
|
|
103
|
+
return repo.validateMember(task.taskId, { sessionId: auth.session.session_id, clientAppId: auth.client.app_id,
|
|
104
|
+
route: workspace, clientConversationId: run.client_conversation_id }, task.scopeHash);
|
|
105
|
+
}
|
|
106
|
+
export async function assertAgentLegacyTaskAllowedFor(store: ConfigStoreContract | null, sessionId: string): Promise<void> {
|
|
107
|
+
const repo = store?.agentTaskControl;
|
|
108
|
+
if (repo && await repo.supportsTaskControl()) await repo.assertUnmanagedDispatch(sessionId);
|
|
109
|
+
}
|
|
110
|
+
function policyFromWire(raw: unknown) {
|
|
111
|
+
const p = exact(raw, ['max_write_calls', 'max_concurrent', 'expires_at']);
|
|
112
|
+
return normalizeAgentTaskPolicy({ maxWriteCalls: p.max_write_calls as number | null,
|
|
113
|
+
maxConcurrent: p.max_concurrent as number, expiresAt: p.expires_at as string | null });
|
|
114
|
+
}
|
|
115
|
+
function membersFromWire(raw: unknown): AgentTaskMemberInput[] {
|
|
116
|
+
taskAssert(Array.isArray(raw), 'TASK_INVALID_INPUT');
|
|
117
|
+
return normalizeAgentTaskMembers(raw.map((item) => {
|
|
118
|
+
const m = exact(item, ['session_id', 'client_app_id', 'workspace', 'client_conversation_id', 'allowed_tools']);
|
|
119
|
+
return { sessionId: m.session_id as string, clientAppId: m.client_app_id as string, route: m.workspace as string,
|
|
120
|
+
clientConversationId: m.client_conversation_id as string, allowedTools: m.allowed_tools as string[] };
|
|
121
|
+
}));
|
|
122
|
+
}
|
|
123
|
+
/** The authenticated admin and request ID define a stable server-generated task identity. */
|
|
124
|
+
function taskIdForRequest(actor: string, requestId: string): string {
|
|
125
|
+
const hex = createHash('sha256').update(JSON.stringify(['bailing.agent-task-create.v1', actor, requestId])).digest('hex');
|
|
126
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
|
|
127
|
+
}
|
|
128
|
+
export async function createAdminAgentTaskFor(store: ConfigStoreContract | null, actor: string, raw: unknown) {
|
|
129
|
+
const body = exact(raw, ['request_id', 'members', 'policy']);
|
|
130
|
+
actor = taskText(actor, 191);
|
|
131
|
+
const requestId = taskText(body.request_id, 128);
|
|
132
|
+
const repo = await taskRepository(store);
|
|
133
|
+
const task = await repo.createAdminTask({ taskId: taskIdForRequest(actor, requestId), actor, requestId,
|
|
134
|
+
members: membersFromWire(body.members), policy: policyFromWire(body.policy) });
|
|
135
|
+
return adminTaskView(task);
|
|
136
|
+
}
|
|
137
|
+
function pagination(query: URLSearchParams) {
|
|
138
|
+
const limit = query.has('limit') ? taskInteger(Number(query.get('limit')), 1, 100) : 30;
|
|
139
|
+
const before = query.get('before') ?? undefined;
|
|
140
|
+
if (before) taskUuid(before);
|
|
141
|
+
return { limit, ...(before ? { before } : {}) };
|
|
142
|
+
}
|
|
143
|
+
export async function listAdminAgentTasksFor(store: ConfigStoreContract | null, query: URLSearchParams) {
|
|
144
|
+
const page = await (await taskRepository(store)).listTasks(pagination(query));
|
|
145
|
+
return { items: page.items.map(adminTaskView), next_cursor: page.nextCursor };
|
|
146
|
+
}
|
|
147
|
+
function invocationView(value: AgentTaskInvocation) {
|
|
148
|
+
return { session_id: value.sessionId, invocation_id: value.invocationId, run_id: value.runId, job_id: value.jobId,
|
|
149
|
+
tool: value.tool, readonly: value.readonly, budget_state: value.budgetState, permit_state: value.permitState,
|
|
150
|
+
outcome: value.outcome, terminal: value.terminal, attempt: value.attempt, approval_id: value.approvalId };
|
|
151
|
+
}
|
|
152
|
+
export async function getAdminAgentTaskFor(store: ConfigStoreContract | null, id: string, query: URLSearchParams) {
|
|
153
|
+
const repo = await taskRepository(store);
|
|
154
|
+
const task = await repo.getTask(taskUuid(id));
|
|
155
|
+
taskAssert(task, 'TASK_NOT_FOUND');
|
|
156
|
+
const invocations = await repo.listInvocations(task.taskId, pagination(query));
|
|
157
|
+
return { task: adminTaskView(task), invocations: invocations.items.map(invocationView), next_cursor: invocations.nextCursor };
|
|
158
|
+
}
|
|
159
|
+
export async function controlAdminAgentTaskFor(store: ConfigStoreContract | null, actor: string, id: string, raw: unknown) {
|
|
160
|
+
const body = exact(raw, ['request_id', 'expected_revision', 'action']);
|
|
161
|
+
taskAssert(['pause', 'resume', 'cancel'].includes(String(body.action)), 'TASK_INVALID_INPUT');
|
|
162
|
+
const result = await (await taskRepository(store)).controlTask({ taskId: taskUuid(id), actor: taskText(actor, 191),
|
|
163
|
+
requestId: taskText(body.request_id, 128), expectedRevision: taskInteger(body.expected_revision, 1),
|
|
164
|
+
action: body.action as 'pause' | 'resume' | 'cancel' });
|
|
165
|
+
return adminTaskView(result);
|
|
166
|
+
}
|
|
167
|
+
export function taskErrorStatus(error: AgentTaskControlError): number {
|
|
168
|
+
if (error.code === 'TASK_INVALID_INPUT') return 400;
|
|
169
|
+
if (error.code === 'TASK_NOT_FOUND') return 404;
|
|
170
|
+
if (error.code === 'TASK_UNSUPPORTED') return 501;
|
|
171
|
+
if (error.code === 'TASK_UNAVAILABLE') return 503;
|
|
172
|
+
return 409;
|
|
173
|
+
}
|
|
174
|
+
/** Keep storage-integrity details private; uncertain original attempts must never look safe to repeat. */
|
|
175
|
+
export function publicAgentTaskError(error: AgentTaskControlError): AgentTaskControlError {
|
|
176
|
+
if (['TASK_ORIGINAL_ALREADY_ATTEMPTED', 'TASK_PERMIT_CONFLICT', 'TASK_JOURNAL_CONFLICT', 'TASK_DISPATCH_UNCERTAIN'].includes(error.code)) {
|
|
177
|
+
return new AgentTaskControlError('TASK_DISPATCH_UNCERTAIN');
|
|
178
|
+
}
|
|
179
|
+
if (['TASK_RUN_CONFLICT', 'TASK_RUN_TASK_CONFLICT', 'TASK_INVOCATION_CONFLICT'].includes(error.code)) {
|
|
180
|
+
return new AgentTaskControlError('TASK_BINDING_CONFLICT');
|
|
181
|
+
}
|
|
182
|
+
const publicCodes = ['TASK_REQUIRED', 'TASK_UNSUPPORTED', 'TASK_SCOPE_BLOCKED', 'TASK_MEMBER_MISMATCH',
|
|
183
|
+
'TASK_BINDING_CONFLICT', 'TASK_PAUSED', 'TASK_CANCELLED', 'TASK_EXPIRED', 'TASK_WRITE_BUDGET_EXHAUSTED',
|
|
184
|
+
'TASK_CONCURRENCY_EXHAUSTED', 'TASK_TOOL_NOT_ALLOWED', 'TASK_REVISION_CONFLICT', 'TASK_RECORD_INVALID',
|
|
185
|
+
'TASK_UNAVAILABLE', 'TASK_NOT_FOUND', 'TASK_RUN_INACTIVE', 'TASK_INVALID_INPUT'];
|
|
186
|
+
return publicCodes.includes(error.code) ? error : new AgentTaskControlError('TASK_RECORD_INVALID');
|
|
187
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { ToolRuntimeDeps } from '../core/contracts/tools';
|
|
2
|
+
import type { Job } from '../core/contracts/types';
|
|
3
|
+
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
4
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
5
|
+
import { AgentTaskControlError, taskAssert, taskDigest, taskUuid, type AgentControlledTask } from '../core/runtime/agent-task-control';
|
|
6
|
+
import { isAgentToolInvocationJob } from './agent-tool-job';
|
|
7
|
+
import { assertAgentLegacyTaskAllowedFor } from './agent-task-control';
|
|
8
|
+
|
|
9
|
+
/** Only an original runtime run can supply a task. Model arguments and arbitrary job metadata cannot enroll one. */
|
|
10
|
+
export async function taskRuntimeFor(config: ConfigStoreContract | null, state: RuntimeStateStore, job: Job): Promise<{
|
|
11
|
+
task: AgentControlledTask | null;
|
|
12
|
+
taskControl?: ToolRuntimeDeps['taskControl'];
|
|
13
|
+
beforeDispatch?: () => Promise<void>;
|
|
14
|
+
}> {
|
|
15
|
+
const hasBinding = Boolean(job.metadata.agent_task_binding || job.metadata.agent_task_id);
|
|
16
|
+
if (!job.agent_session_id) { taskAssert(!hasBinding, 'TASK_BINDING_CONFLICT'); return { task: null }; }
|
|
17
|
+
const repo = config?.agentTaskControl;
|
|
18
|
+
if (!repo || !await repo.supportsTaskControl()) {
|
|
19
|
+
taskAssert(!hasBinding, 'TASK_UNSUPPORTED');
|
|
20
|
+
return { task: null };
|
|
21
|
+
}
|
|
22
|
+
const task = isAgentToolInvocationJob(job) ? await repo.findTaskForRun(job.session_id!, job.agent_session_id) : null;
|
|
23
|
+
if (!task) {
|
|
24
|
+
taskAssert(!hasBinding, 'TASK_BINDING_CONFLICT');
|
|
25
|
+
await assertAgentLegacyTaskAllowedFor(config, job.agent_session_id);
|
|
26
|
+
return { task: null, beforeDispatch: () => assertAgentLegacyTaskAllowedFor(config, job.agent_session_id!) };
|
|
27
|
+
}
|
|
28
|
+
taskAssert(isAgentToolInvocationJob(job), 'TASK_UNSUPPORTED');
|
|
29
|
+
const sessionId = taskUuid(job.agent_session_id);
|
|
30
|
+
const invocationId = taskDigest(job.metadata.agent_invocation_id);
|
|
31
|
+
const runId = taskUuid(job.session_id);
|
|
32
|
+
let permitId: string | null = null;
|
|
33
|
+
return { task, taskControl: {
|
|
34
|
+
async prepare(input) {
|
|
35
|
+
taskAssert(input.tool === job.metadata.agent_tool && input.argsHash === job.metadata.agent_args_hash, 'TASK_INVOCATION_CONFLICT');
|
|
36
|
+
const contract = { schema_version: 'bailing.agent-task-tool-contract.v1', readonly: input.readonly,
|
|
37
|
+
approval_required: input.approvalRequired, args_hash: input.argsHash,
|
|
38
|
+
execution_fingerprint: taskDigest(job.metadata.agent_execution_fingerprint) };
|
|
39
|
+
await repo.freezeInvocationContract(job.job_id, contract);
|
|
40
|
+
await repo.reserveInvocation({ taskId: task.taskId, sessionId, invocationId, runId, jobId: job.job_id,
|
|
41
|
+
tool: input.tool, argsHash: input.argsHash, executionFingerprint: taskDigest(job.metadata.agent_execution_fingerprint),
|
|
42
|
+
readonly: input.readonly, approvalRequired: input.approvalRequired });
|
|
43
|
+
},
|
|
44
|
+
async grant(input) {
|
|
45
|
+
taskAssert(input.tool === job.metadata.agent_tool && input.argsHash === job.metadata.agent_args_hash, 'TASK_INVOCATION_CONFLICT');
|
|
46
|
+
const result = await repo.grantDispatchPermit({ taskId: task.taskId, sessionId, invocationId, retryOriginal: true,
|
|
47
|
+
...(input.approvalId === undefined ? {} : { approvalId: input.approvalId }),
|
|
48
|
+
journal: { scope: input.scope, idempotencyKey: input.idempotencyKey } }).catch((error: unknown) => {
|
|
49
|
+
if (error instanceof AgentTaskControlError) throw error;
|
|
50
|
+
throw new AgentTaskControlError('TASK_DISPATCH_UNCERTAIN');
|
|
51
|
+
});
|
|
52
|
+
if (result.fresh) { taskAssert(result.invocation.permitId, 'TASK_RECORD_INVALID'); permitId = result.invocation.permitId; }
|
|
53
|
+
return result.fresh;
|
|
54
|
+
},
|
|
55
|
+
async settle(outcome, response, evidenceDegraded) {
|
|
56
|
+
taskAssert(permitId, 'TASK_PERMIT_CONFLICT');
|
|
57
|
+
await repo.settlePermit({ taskId: task.taskId, sessionId, invocationId, permitId, outcome,
|
|
58
|
+
terminal: outcome === 'confirmed_dispatched', ...(response ? { response } : {}),
|
|
59
|
+
...(evidenceDegraded ? { evidenceDegraded: true } : {}) });
|
|
60
|
+
},
|
|
61
|
+
} };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Legacy model/builtin jobs must not bypass an enrolled Session's task gate. */
|
|
65
|
+
export async function assertTaskLegacyJobAllowedFor(config: ConfigStoreContract | null, job: Job): Promise<void> {
|
|
66
|
+
taskAssert(!job.metadata.agent_task_binding && !job.metadata.agent_task_id, 'TASK_UNSUPPORTED');
|
|
67
|
+
if (job.agent_session_id) await assertAgentLegacyTaskAllowedFor(config, job.agent_session_id);
|
|
68
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import assert from 'node:assert/strict';
|
|
2
2
|
import { createServer, type Server } from 'node:http';
|
|
3
3
|
import test from 'node:test';
|
|
4
|
+
import { LocalSlidingWindowRateLimiter } from '../core/contracts/tools';
|
|
4
5
|
import type { AppConfig } from '../core/config/config';
|
|
5
6
|
import type { ToolExecutionJournalEntry } from '../core/contracts/tools';
|
|
6
7
|
import type { AgentSession, Client, Job, Route, ToolApproval, ToolProvider } from '../core/contracts/types';
|
|
@@ -10,6 +11,7 @@ import type { AgentClientRunRecord } from '../infrastructure/config/config-agent
|
|
|
10
11
|
import {
|
|
11
12
|
AgentToolApiError,
|
|
12
13
|
invokeAgentToolFor,
|
|
14
|
+
inspectAgentToolInvocationFor,
|
|
13
15
|
listAgentToolsFor,
|
|
14
16
|
resumeAgentToolFor,
|
|
15
17
|
type AgentToolAuthContext,
|
|
@@ -179,9 +181,10 @@ function fixture(baseUrl: string) {
|
|
|
179
181
|
deps,
|
|
180
182
|
state,
|
|
181
183
|
approvals,
|
|
184
|
+
calls,
|
|
182
185
|
setRoute: (value: Route) => { currentRoute = value; },
|
|
183
186
|
setSpec: (value: string) => { currentSpec = value; },
|
|
184
|
-
setToolRateLimited: (value: boolean) => { toolRateLimited = value; },
|
|
187
|
+
setToolRateLimited: (value: boolean) => { toolRateLimited = value; provider.tool_rate_limits = { default: { mode: 'custom', count: 120, window: '1h' }, overrides: {} }; },
|
|
185
188
|
setRuntimeRun: (value: AgentClientRunRecord | null) => { runtimeRun = value; },
|
|
186
189
|
};
|
|
187
190
|
}
|
|
@@ -197,6 +200,170 @@ function runtimeRun(overrides: Partial<AgentClientRunRecord> = {}): AgentClientR
|
|
|
197
200
|
};
|
|
198
201
|
}
|
|
199
202
|
|
|
203
|
+
async function pendingReceiptFixture() {
|
|
204
|
+
const fx = fixture('https://business.invalid');
|
|
205
|
+
fx.setRoute(routeWithForcedApproval());
|
|
206
|
+
fx.setRuntimeRun(runtimeRun());
|
|
207
|
+
const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
|
|
208
|
+
const input = {
|
|
209
|
+
invocation_id: invocationId('a'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
|
|
210
|
+
agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 1, name: 'Synthetic' },
|
|
211
|
+
};
|
|
212
|
+
const result = await invokeAgentToolFor(fx.deps, auth(), input);
|
|
213
|
+
assert.equal(result.state, 'awaiting_approval');
|
|
214
|
+
const job = [...fx.state.jobs.values()][0]!;
|
|
215
|
+
return { ...fx, input, result, job };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function forbidReceiptMutations(fx: Awaited<ReturnType<typeof pendingReceiptFixture>>) {
|
|
219
|
+
const snapshot = () => JSON.stringify({ jobs: [...fx.state.jobs], approvals: fx.approvals, calls: [...fx.calls], audits: fx.state.audits });
|
|
220
|
+
const before = snapshot();
|
|
221
|
+
const forbidden = async () => { throw new Error('inspection_attempted_mutation'); };
|
|
222
|
+
fx.state.createJob = forbidden;
|
|
223
|
+
fx.state.updateJob = forbidden;
|
|
224
|
+
fx.state.appendAudit = forbidden;
|
|
225
|
+
fx.state.acquireRuntimeLock = forbidden;
|
|
226
|
+
fx.state.releaseRuntimeLock = forbidden;
|
|
227
|
+
fx.deps.configStore!.approvals.use = forbidden;
|
|
228
|
+
fx.deps.configStore!.approvals.create = forbidden;
|
|
229
|
+
fx.deps.configStore!.rateLimits.consume = forbidden;
|
|
230
|
+
fx.deps.configStore!.toolCalls.reserve = forbidden;
|
|
231
|
+
fx.deps.configStore!.toolCalls.complete = forbidden;
|
|
232
|
+
fx.deps.configStore!.toolCalls.recordResponse = forbidden;
|
|
233
|
+
// Inspection needs no original encrypted arguments or server decryption secret.
|
|
234
|
+
fx.deps.cfg.server.token = 'synthetic-rotated-key';
|
|
235
|
+
return () => assert.equal(snapshot(), before, 'inspection must not alter original execution evidence');
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
test('Agent receipt: approved original remains undispatched across repeated read-only inspections', async () => {
|
|
239
|
+
const fx = await pendingReceiptFixture();
|
|
240
|
+
fx.approvals[0]!.status = 'approved';
|
|
241
|
+
const unchanged = forbidReceiptMutations(fx);
|
|
242
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
243
|
+
const receipt = await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input);
|
|
244
|
+
assert.equal(receipt.schema_version, 'bailing.agent-invocation-receipt.v1');
|
|
245
|
+
assert.equal(receipt.read_only, true);
|
|
246
|
+
assert.equal(receipt.business_operation_performed, false);
|
|
247
|
+
assert.equal(receipt.agent_run_id, AGENT_RUN_ID);
|
|
248
|
+
assert.equal(receipt.invocation_id, fx.input.invocation_id);
|
|
249
|
+
assert.equal(receipt.dispatch_state, 'not_dispatched');
|
|
250
|
+
assert.equal(receipt.journal_state, 'absent');
|
|
251
|
+
assert.deepEqual(receipt.result, fx.result);
|
|
252
|
+
assert.deepEqual(receipt.approval, { status: 'approved', approval_id: 1 });
|
|
253
|
+
assert.equal(fx.approvals[0]!.used_at, undefined);
|
|
254
|
+
}
|
|
255
|
+
unchanged();
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
test('Agent receipt: completed journal supersedes a stale job without persisting or dispatching', async () => {
|
|
259
|
+
const fx = await pendingReceiptFixture();
|
|
260
|
+
fx.calls.set(`${fx.job.job_id}\0staff_edit\0${fx.job.metadata.agent_args_hash}`, {
|
|
261
|
+
state: 'completed', ok: true, status: 200, text: 'Synthetic completion', idempotencyKey: 'synthetic-original-key',
|
|
262
|
+
});
|
|
263
|
+
const unchanged = forbidReceiptMutations(fx);
|
|
264
|
+
const receipt = await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input);
|
|
265
|
+
assert.equal(receipt.result_source, 'journal');
|
|
266
|
+
assert.equal(receipt.journal_state, 'completed');
|
|
267
|
+
assert.equal(receipt.result?.state, 'executed');
|
|
268
|
+
assert.equal(receipt.result?.auto_retry_allowed, false);
|
|
269
|
+
assert.equal(receipt.dispatch_state, 'attempted');
|
|
270
|
+
assert.equal(receipt.result?.text, 'Synthetic completion');
|
|
271
|
+
assert.equal(JSON.stringify(receipt).includes('synthetic-original-key'), false);
|
|
272
|
+
unchanged();
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
test('Agent receipt: unresolved or malformed journal never grants a repeat operation', async (t) => {
|
|
276
|
+
for (const state of ['dispatching', 'response_recorded', 'uncertain', 'evidence_degraded', 'unexpected'] as const) {
|
|
277
|
+
await t.test(state, async () => {
|
|
278
|
+
const fx = await pendingReceiptFixture();
|
|
279
|
+
fx.calls.set(`${fx.job.job_id}\0staff_edit\0${fx.job.metadata.agent_args_hash}`, {
|
|
280
|
+
state, ok: true, status: 200, text: 'Unconfirmed synthetic content', idempotencyKey: 'synthetic-original-key',
|
|
281
|
+
} as ToolExecutionJournalEntry);
|
|
282
|
+
const unchanged = forbidReceiptMutations(fx);
|
|
283
|
+
const receipt = await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input);
|
|
284
|
+
assert.equal(receipt.journal_state, state === 'unexpected' ? 'unknown' : state);
|
|
285
|
+
assert.equal(receipt.result_source, 'journal');
|
|
286
|
+
assert.equal(receipt.result?.state, 'reconciliation_required');
|
|
287
|
+
assert.equal(receipt.result?.auto_retry_allowed, false);
|
|
288
|
+
assert.equal(receipt.business_operation_performed, false);
|
|
289
|
+
assert.equal(JSON.stringify(receipt).includes('Unconfirmed synthetic content'), false);
|
|
290
|
+
unchanged();
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
test('Agent receipt: result JSON is allowlisted and invalid schema stays unknown', async () => {
|
|
296
|
+
const fx = await pendingReceiptFixture();
|
|
297
|
+
fx.job.result = { ...fx.result, private_data: 'synthetic-hidden', rate_limit: {
|
|
298
|
+
level: 'tool', count: 120, window_sec: 3600, scope: 'tool_provider_shared', source: 'override', token: 'synthetic-secret',
|
|
299
|
+
} };
|
|
300
|
+
const receipt = await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input);
|
|
301
|
+
assert.equal(JSON.stringify(receipt).includes('synthetic-hidden'), false);
|
|
302
|
+
assert.equal(JSON.stringify(receipt).includes('synthetic-secret'), false);
|
|
303
|
+
assert.equal(JSON.stringify(receipt).includes('agent_frozen_arguments'), false);
|
|
304
|
+
fx.job.result = { ...fx.result, schema_version: 'unknown-schema' };
|
|
305
|
+
delete fx.job.metadata.agent_dispatch_attempted;
|
|
306
|
+
const unchanged = forbidReceiptMutations(fx);
|
|
307
|
+
const unknown = await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input);
|
|
308
|
+
assert.equal(unknown.result, null);
|
|
309
|
+
assert.equal(unknown.result_source, 'none');
|
|
310
|
+
assert.equal(unknown.dispatch_state, 'unknown');
|
|
311
|
+
unchanged();
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
test('Agent receipt: capability declaration changes do not require historical execution fingerprints', async () => {
|
|
315
|
+
const fx = await pendingReceiptFixture();
|
|
316
|
+
const changed = JSON.parse(spec());
|
|
317
|
+
changed.paths['/staff/edit'].post.summary = 'Updated synthetic description';
|
|
318
|
+
changed.paths['/staff/edit'].post.requestBody.content['application/json'].schema.properties.note = { type: 'string' };
|
|
319
|
+
fx.setSpec(JSON.stringify(changed));
|
|
320
|
+
const unchanged = forbidReceiptMutations(fx);
|
|
321
|
+
assert.equal((await inspectAgentToolInvocationFor(fx.deps, auth(), fx.input)).result?.state, 'awaiting_approval');
|
|
322
|
+
unchanged();
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
test('Agent receipt: current tool revocation still forbids access to original result content', async () => {
|
|
326
|
+
const fx = await pendingReceiptFixture();
|
|
327
|
+
const changed = routeWithForcedApproval();
|
|
328
|
+
changed.tools = { ...changed.tools, agent_direct: { enabled: true, write_tools: [] } };
|
|
329
|
+
fx.setRoute(changed);
|
|
330
|
+
const unchanged = forbidReceiptMutations(fx);
|
|
331
|
+
await assert.rejects(inspectAgentToolInvocationFor(fx.deps, auth(), fx.input),
|
|
332
|
+
(error) => error instanceof AgentToolApiError && error.code === 'capability_changed');
|
|
333
|
+
unchanged();
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
test('Agent receipt: original session, client, principal, route and run bindings cannot be changed', async (t) => {
|
|
337
|
+
for (const drift of ['session', 'client', 'principal', 'tenant', 'on_behalf_of', 'run', 'route', 'thread'] as const) {
|
|
338
|
+
await t.test(drift, async () => {
|
|
339
|
+
const fx = await pendingReceiptFixture();
|
|
340
|
+
const caller = auth();
|
|
341
|
+
if (drift === 'session') caller.session.session_id = '33333333-3333-4333-8333-333333333333';
|
|
342
|
+
if (drift === 'client') caller.client.app_id = 'another-client';
|
|
343
|
+
if (drift === 'principal') caller.session.principal.id = 'another-user';
|
|
344
|
+
if (drift === 'tenant') caller.session.principal.tenant = 'another-tenant';
|
|
345
|
+
if (drift === 'on_behalf_of') caller.session.on_behalf_of = 'another-subject';
|
|
346
|
+
if (drift === 'run') fx.setRuntimeRun(runtimeRun({ session_id: '33333333-3333-4333-8333-333333333333' }));
|
|
347
|
+
if (drift === 'route') fx.setRuntimeRun(runtimeRun({ route_key: 'another-route' }));
|
|
348
|
+
if (drift === 'thread') fx.setRuntimeRun(runtimeRun({ thread_id: 99 }));
|
|
349
|
+
const unchanged = forbidReceiptMutations(fx);
|
|
350
|
+
await assert.rejects(inspectAgentToolInvocationFor(fx.deps, caller, fx.input),
|
|
351
|
+
(error) => error instanceof AgentToolApiError && ['invocation_not_found', 'invocation_conflict', 'agent_run_conflict'].includes(error.code));
|
|
352
|
+
unchanged();
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
test('Agent receipt: absent original or malformed identifier never creates substitute evidence', async () => {
|
|
358
|
+
const fx = await pendingReceiptFixture();
|
|
359
|
+
const unchanged = forbidReceiptMutations(fx);
|
|
360
|
+
await assert.rejects(inspectAgentToolInvocationFor(fx.deps, auth(), { invocation_id: invocationId('b') }),
|
|
361
|
+
(error) => error instanceof AgentToolApiError && error.statusCode === 404 && error.code === 'invocation_not_found');
|
|
362
|
+
await assert.rejects(inspectAgentToolInvocationFor(fx.deps, auth(), { invocation_id: 'bad-id' }),
|
|
363
|
+
(error) => error instanceof AgentToolApiError && error.statusCode === 400);
|
|
364
|
+
unchanged();
|
|
365
|
+
});
|
|
366
|
+
|
|
200
367
|
test('Agent direct: 本地投影只含只读与精确写工具,写工具默认继承 ACC 审批声明', async (t) => {
|
|
201
368
|
let businessCalls = 0;
|
|
202
369
|
const business = createServer(async (req, res) => {
|
|
@@ -440,6 +607,167 @@ test('Agent direct: 工具限流不消费批准,同 invocation 可安全重试
|
|
|
440
607
|
assert.equal(businessCalls, 1);
|
|
441
608
|
});
|
|
442
609
|
|
|
610
|
+
test('Agent direct: transport uncertainty and lost client receipts resume the original result without redispatch', async (t) => {
|
|
611
|
+
for (const kind of ['readonly', 'idempotent_write', 'non_idempotent_write'] as const) {
|
|
612
|
+
for (const failure of ['fetch_rejected', 'response_body_lost', 'client_receipt_lost'] as const) {
|
|
613
|
+
await t.test(`${kind}: ${failure}`, async (t) => {
|
|
614
|
+
let attempts = 0;
|
|
615
|
+
t.mock.method(globalThis, 'fetch', async () => {
|
|
616
|
+
attempts++;
|
|
617
|
+
if (failure === 'fetch_rejected') throw new TypeError('synthetic transport failure');
|
|
618
|
+
if (failure === 'client_receipt_lost') return new Response('{"ok":true}', { status: 200 });
|
|
619
|
+
return { status: 200, text: async () => { throw new TypeError('synthetic response body loss'); } } as unknown as Response;
|
|
620
|
+
});
|
|
621
|
+
const fx = fixture('https://business.invalid');
|
|
622
|
+
if (kind === 'idempotent_write') {
|
|
623
|
+
const declaration = JSON.parse(spec());
|
|
624
|
+
declaration.paths['/staff/edit'].post['x-agent-capability'].execution = { readonly: false, idempotent: true };
|
|
625
|
+
fx.setSpec(JSON.stringify(declaration));
|
|
626
|
+
}
|
|
627
|
+
const caller = auth();
|
|
628
|
+
const catalog = await listAgentToolsFor(fx.deps, caller, 'tenant-agent');
|
|
629
|
+
const tool = kind === 'readonly' ? 'staff_list' : 'staff_edit';
|
|
630
|
+
const definition = catalog.tools.find((item) => item.name === tool)!;
|
|
631
|
+
assert.equal(definition.readonly, kind === 'readonly');
|
|
632
|
+
assert.equal(definition.idempotent, kind !== 'non_idempotent_write');
|
|
633
|
+
const input = {
|
|
634
|
+
invocation_id: invocationId('a'), route: 'tenant-agent', capability_revision: catalog.capability_revision,
|
|
635
|
+
agent_run_id: AGENT_RUN_ID, tool,
|
|
636
|
+
arguments: kind === 'readonly' ? { keyword: 'Synthetic' } : { id: 1, name: 'Synthetic' },
|
|
637
|
+
};
|
|
638
|
+
// For a lost client receipt the business result is already persisted; the client only
|
|
639
|
+
// retains its invocation ID and must recover it instead of submitting another operation.
|
|
640
|
+
const first = await invokeAgentToolFor(fx.deps, caller, input);
|
|
641
|
+
const confirmed = failure === 'client_receipt_lost';
|
|
642
|
+
assert.equal(first.state, confirmed ? 'executed' : 'reconciliation_required');
|
|
643
|
+
assert.equal(first.auto_retry_allowed, false);
|
|
644
|
+
assert.equal(first.ok, confirmed);
|
|
645
|
+
assert.equal(first.business_status, confirmed ? 200 : undefined, 'only a trusted business response confirms business status');
|
|
646
|
+
assert.equal(attempts, 1);
|
|
647
|
+
|
|
648
|
+
assert.deepEqual(await resumeAgentToolFor(fx.deps, caller, { invocation_id: input.invocation_id }), first);
|
|
649
|
+
assert.deepEqual(await invokeAgentToolFor(fx.deps, caller, input), first);
|
|
650
|
+
assert.equal(attempts, 1, 'resume and same-invocation replay must never dispatch a replacement request');
|
|
651
|
+
assert.equal(fx.state.jobs.size, 1);
|
|
652
|
+
|
|
653
|
+
caller.session.allowed_routes = [];
|
|
654
|
+
await assert.rejects(
|
|
655
|
+
resumeAgentToolFor(fx.deps, caller, { invocation_id: input.invocation_id }),
|
|
656
|
+
(error) => error instanceof AgentToolApiError && error.code === 'route_not_allowed',
|
|
657
|
+
);
|
|
658
|
+
assert.equal(attempts, 1, 'uncertainty never bypasses the current authorization boundary');
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
});
|
|
663
|
+
|
|
664
|
+
test('Agent direct: an unapproved rate-limited write resumes its sealed original arguments after restart and lost ACK', async (t) => {
|
|
665
|
+
const received: unknown[] = [];
|
|
666
|
+
const business = createServer(async (req, res) => {
|
|
667
|
+
let raw = ''; for await (const chunk of req) raw += String(chunk);
|
|
668
|
+
received.push(JSON.parse(raw));
|
|
669
|
+
res.writeHead(200, { 'content-type': 'application/json' }); res.end('{"ok":true}');
|
|
670
|
+
});
|
|
671
|
+
const port = await listen(business); t.after(() => close(business));
|
|
672
|
+
const fx = fixture(`http://127.0.0.1:${port}`);
|
|
673
|
+
fx.setToolRateLimited(true);
|
|
674
|
+
const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
|
|
675
|
+
const invocation_id = invocationId('9');
|
|
676
|
+
const limited = await invokeAgentToolFor(fx.deps, auth(), {
|
|
677
|
+
invocation_id, route: 'tenant-agent', capability_revision: catalog.capability_revision,
|
|
678
|
+
agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: 'Synthetic name' },
|
|
679
|
+
});
|
|
680
|
+
assert.equal(limited.state, 'rejected_before_dispatch');
|
|
681
|
+
assert.equal(limited.retry_after_ms, 3_600_000);
|
|
682
|
+
assert.equal(limited.rate_limit?.scope, 'tool_provider_shared');
|
|
683
|
+
assert.equal(received.length, 0);
|
|
684
|
+
assert.equal(fx.approvals.length, 0);
|
|
685
|
+
assert.doesNotMatch(JSON.stringify([...fx.state.jobs.values()]), /Synthetic name/);
|
|
686
|
+
assert.equal((await resumeAgentToolFor(fx.deps, auth(), { invocation_id })).auto_retry_allowed, true);
|
|
687
|
+
// New coordinator, JSON round trip of the persisted jobs, original Session/run/invocation.
|
|
688
|
+
const restarted = fixture(`http://127.0.0.1:${port}`);
|
|
689
|
+
for (const job of fx.state.jobs.values()) await restarted.state.createJob(JSON.parse(JSON.stringify(job)));
|
|
690
|
+
const result = await resumeAgentToolFor(restarted.deps, auth(), { invocation_id });
|
|
691
|
+
assert.equal(result.state, 'executed');
|
|
692
|
+
assert.deepEqual(received, [{ id: 7, name: 'Synthetic name' }]);
|
|
693
|
+
assert.deepEqual(await resumeAgentToolFor(restarted.deps, auth(), { invocation_id }), result);
|
|
694
|
+
assert.equal(received.length, 1);
|
|
695
|
+
assert.ok([...restarted.state.jobs.values()].every((job) => !job.metadata.agent_frozen_arguments));
|
|
696
|
+
});
|
|
697
|
+
|
|
698
|
+
test('Agent direct: the third burst write under 120/hour reaches business; closing Hub tool limits keeps the provider gate', async (t) => {
|
|
699
|
+
let calls = 0;
|
|
700
|
+
t.mock.method(globalThis, 'fetch', async () => { calls++; return new Response('{"ok":true}'); });
|
|
701
|
+
const fx = fixture('https://business.invalid');
|
|
702
|
+
const definition = JSON.parse(spec());
|
|
703
|
+
definition.paths['/staff/edit'].post['x-agent-capability'].execution = { rate_limit: { count: 120, window: '1h' } };
|
|
704
|
+
fx.setSpec(JSON.stringify(definition));
|
|
705
|
+
const limiter = new LocalSlidingWindowRateLimiter(() => 0);
|
|
706
|
+
fx.deps.configStore!.rateLimits.consumeAll = async (gates) => limiter.consumeAll(gates);
|
|
707
|
+
const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
|
|
708
|
+
const invoke = (id: string) => invokeAgentToolFor(fx.deps, auth(), { invocation_id: invocationId(id), route: 'tenant-agent', capability_revision: catalog.capability_revision,
|
|
709
|
+
agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: id } });
|
|
710
|
+
for (const id of ['1', '2', '3']) assert.equal((await invoke(id)).state, 'executed');
|
|
711
|
+
assert.equal(calls, 3);
|
|
712
|
+
const provider = (await fx.deps.configStore!.toolProviders.get('example-business'))!;
|
|
713
|
+
provider.tool_rate_limits = { default: { mode: 'disabled' }, overrides: {} };
|
|
714
|
+
provider.rate_limit_per_min = 1;
|
|
715
|
+
assert.equal((await invoke('4')).state, 'executed');
|
|
716
|
+
const blocked = await invoke('5');
|
|
717
|
+
assert.equal(blocked.rate_limit?.level, 'provider');
|
|
718
|
+
assert.equal(calls, 4);
|
|
719
|
+
provider.rate_limit_per_min = 0;
|
|
720
|
+
assert.equal((await resumeAgentToolFor(fx.deps, auth(), { invocation_id: invocationId('5') })).state, 'executed');
|
|
721
|
+
assert.equal(calls, 5);
|
|
722
|
+
});
|
|
723
|
+
|
|
724
|
+
test('Agent direct: corrupt snapshot and uncertain dispatch fence never replay a write', async (t) => {
|
|
725
|
+
for (const failure of ['corrupt_snapshot', 'rotated_key', 'dispatch_in_progress', 'journal_unavailable'] as const) {
|
|
726
|
+
await t.test(failure, async (t) => {
|
|
727
|
+
let calls = 0;
|
|
728
|
+
t.mock.method(globalThis, 'fetch', async () => { calls++; return new Response('{"ok":true}'); });
|
|
729
|
+
const fx = fixture('https://business.invalid'); fx.setToolRateLimited(true);
|
|
730
|
+
const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
|
|
731
|
+
const invocation_id = invocationId('8');
|
|
732
|
+
await invokeAgentToolFor(fx.deps, auth(), { invocation_id, route: 'tenant-agent', capability_revision: catalog.capability_revision,
|
|
733
|
+
agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: 'Synthetic name' } });
|
|
734
|
+
fx.setToolRateLimited(false);
|
|
735
|
+
const job = [...fx.state.jobs.values()][0]!;
|
|
736
|
+
if (failure === 'corrupt_snapshot') job.metadata.agent_frozen_arguments = 'v1.invalid.snapshot';
|
|
737
|
+
if (failure === 'rotated_key') fx.deps.cfg.server.token = 'rotated-synthetic-key';
|
|
738
|
+
if (failure === 'dispatch_in_progress') {
|
|
739
|
+
job.metadata.agent_dispatch_attempted = true;
|
|
740
|
+
job.result = { ...job.result, state: 'in_progress', auto_retry_allowed: false };
|
|
741
|
+
}
|
|
742
|
+
if (failure === 'journal_unavailable') {
|
|
743
|
+
fx.deps.configStore!.toolCalls.get = async () => { throw new Error('synthetic_storage_unavailable'); };
|
|
744
|
+
await assert.rejects(resumeAgentToolFor(fx.deps, auth(), { invocation_id }), /synthetic_storage_unavailable/);
|
|
745
|
+
} else {
|
|
746
|
+
const result = await resumeAgentToolFor(fx.deps, auth(), { invocation_id });
|
|
747
|
+
assert.equal(result.auto_retry_allowed, false);
|
|
748
|
+
assert.equal(result.state, failure === 'dispatch_in_progress' ? 'reconciliation_required' : 'rejected_before_dispatch');
|
|
749
|
+
}
|
|
750
|
+
assert.equal(calls, 0);
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
});
|
|
754
|
+
|
|
755
|
+
test('Agent direct: failure to persist the dispatch fence makes zero business requests and remains recoverable', async (t) => {
|
|
756
|
+
let calls = 0;
|
|
757
|
+
t.mock.method(globalThis, 'fetch', async () => { calls++; return new Response('{"ok":true}'); });
|
|
758
|
+
const fx = fixture('https://business.invalid');
|
|
759
|
+
const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
|
|
760
|
+
const update = t.mock.method(fx.state, 'updateJob', async () => null);
|
|
761
|
+
const invocation_id = invocationId('7');
|
|
762
|
+
await assert.rejects(invokeAgentToolFor(fx.deps, auth(), { invocation_id, route: 'tenant-agent', capability_revision: catalog.capability_revision,
|
|
763
|
+
agent_run_id: AGENT_RUN_ID, tool: 'staff_edit', arguments: { id: 7, name: 'Synthetic' } }),
|
|
764
|
+
(error) => error instanceof AgentToolApiError && error.code === 'invocation_storage_unavailable');
|
|
765
|
+
assert.equal(calls, 0);
|
|
766
|
+
update.mock.restore();
|
|
767
|
+
assert.equal((await resumeAgentToolFor(fx.deps, auth(), { invocation_id })).state, 'executed');
|
|
768
|
+
assert.equal(calls, 1);
|
|
769
|
+
});
|
|
770
|
+
|
|
443
771
|
test('Agent direct: capability revision 变更、参数漂移和未开启路由均失败关闭', async () => {
|
|
444
772
|
const fx = fixture('https://business.invalid');
|
|
445
773
|
const catalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
|