bailinghub 0.7.0 → 0.9.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 +7 -9
- package/README.md +7 -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/ARCHITECTURE.md +1 -1
- package/docs/CHANGELOG.en.md +22 -1
- package/docs/CHANGELOG.md +22 -1
- package/docs/COMPATIBILITY.en.md +6 -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/MODEL_BILLING.en.md +123 -0
- package/docs/MODEL_BILLING.md +125 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
- package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
- package/docs/README.en.md +7 -0
- package/docs/README.md +7 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
- package/docs/RELEASE_NOTES_NEXT.md +4 -2
- package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
- package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
- package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.9.0.md +45 -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/UPGRADE_v0.9.0.en.md +54 -0
- package/docs/UPGRADE_v0.9.0.md +54 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +6 -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 +5 -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-runtime-test.mjs +6 -0
- package/scripts/verify-billing-install-upgrade.mjs +225 -0
- package/scripts/verify-github-repo.mjs +2 -0
- package/sdk/node/README.md +17 -0
- package/sdk/node/examples/billing.mjs +21 -0
- package/sdk/node/package.json +5 -1
- package/sdk/node/src/index.mjs +2 -0
- package/sdk/node/src/usage.d.mts +74 -0
- package/sdk/node/src/usage.mjs +62 -0
- package/sdk/node/tests/usage-types.mts +23 -0
- package/sdk/node/tests/usage.test.mjs +81 -0
- package/sdk/php7/README.md +19 -2
- package/sdk/php7/examples/billing.php +27 -0
- package/sdk/php7/examples/well-known.php +1 -1
- package/sdk/php7/src/ToolSpec.php +1 -1
- package/sdk/php7/src/UsageClient.php +95 -0
- package/sdk/php7/src/UsageClientException.php +22 -0
- package/sdk/php7/tests/billing-core-http.php +59 -0
- package/sdk/php7/tests/usage-client.php +78 -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/063_usage_model_billing.sql +153 -0
- package/sql/064_period_plan_allowance.sql +25 -0
- package/sql/README.en.md +12 -4
- package/sql/README.md +14 -6
- 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/auth.ts +2 -0
- package/src/app/builtin-tools.ts +4 -0
- package/src/app/oss-edition.ts +2 -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 +15 -1
- package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
- package/src/modules/usage/billing-contracts.ts +59 -0
- package/src/modules/usage/billing-decimal.test.ts +22 -0
- package/src/modules/usage/billing-decimal.ts +36 -0
- package/src/modules/usage/billing-external.ts +39 -0
- package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
- package/src/modules/usage/billing-ledger.test.ts +51 -0
- package/src/modules/usage/billing-ledger.ts +104 -0
- package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
- package/src/modules/usage/billing-presentation.test.ts +49 -0
- package/src/modules/usage/billing-presentation.ts +34 -0
- package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
- package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
- package/src/modules/usage/billing-repository.ts +463 -0
- package/src/modules/usage/contracts.ts +49 -0
- package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
- package/src/modules/usage/errors.ts +19 -0
- package/src/modules/usage/http.ts +85 -0
- package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
- package/src/modules/usage/identity.mysql.test.ts +120 -0
- package/src/modules/usage/identity.ts +303 -0
- package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
- package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
- package/src/modules/usage/model-gateway.ts +229 -0
- package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
- package/src/modules/usage/model-tool-provider.test.ts +37 -0
- package/src/modules/usage/model-tool-provider.ts +110 -0
- package/src/modules/usage/model-tools.test.ts +36 -0
- package/src/modules/usage/model-tools.ts +62 -0
- package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
- package/src/modules/usage/period.test.ts +26 -0
- package/src/modules/usage/period.ts +96 -0
- package/src/modules/usage/pricing.test.ts +178 -0
- package/src/modules/usage/pricing.ts +228 -0
- package/src/modules/usage/provider-failure.ts +37 -0
- package/src/modules/usage/provider-stream.test.ts +85 -0
- package/src/modules/usage/provider-stream.ts +77 -0
- package/src/modules/usage/provider.test.ts +67 -0
- package/src/modules/usage/provider.ts +142 -0
- package/src/modules/usage/repository.ts +539 -0
- package/src/modules/usage/service-availability.mysql.test.ts +68 -0
- package/src/modules/usage/service-availability.ts +13 -0
- package/src/modules/usage/service-delete.mysql.test.ts +87 -0
- package/src/modules/usage/stream-http.ts +32 -0
- package/src/modules/usage/test-harness.ts +108 -0
- package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
- package/src/modules/usage/usage-deletion.ts +119 -0
- package/src/modules/usage/validation.test.ts +18 -0
- package/src/modules/usage/validation.ts +33 -0
- package/src/routes/admin-agent-tasks.ts +32 -0
- package/src/routes/admin-billing-usage.ts +73 -0
- package/src/routes/admin-tool-providers.test.ts +22 -0
- package/src/routes/admin-tool-providers.ts +9 -1
- package/src/routes/admin-usage.ts +147 -0
- package/src/routes/admin.ts +7 -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 +9 -0
- package/src/routes/run.ts +2 -1
- package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/Accounts-Bervi5JU.css +1 -0
- package/web/console/assets/Accounts-DnddhY6t.js +3 -0
- package/web/console/assets/AgentClients-VInbD7JS.js +1 -0
- package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
- package/web/console/assets/AgentTasks-B-1XklBg.js +2 -0
- package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
- package/web/console/assets/{Approvals-Bs6FGbp2.js → Approvals-34qUPHf0.js} +1 -1
- package/web/console/assets/{Audit-4WWYhkFM.js → Audit-BbVgkSm2.js} +1 -1
- package/web/console/assets/{BrandLockup-D2GhCipL.js → BrandLockup-DgscF28e.js} +1 -1
- package/web/console/assets/{Channels-CmoGpiCJ.js → Channels-Bp-yuk8d.js} +1 -1
- package/web/console/assets/{ChatEntries-BFRMtwta.js → ChatEntries-C9Ft60TS.js} +1 -1
- package/web/console/assets/{Clients-DGkkSXyA.js → Clients-NPldD-DD.js} +1 -1
- package/web/console/assets/{Cost-BmGt0MfS.js → Cost-DZcuB-EB.js} +1 -1
- package/web/console/assets/{Credentials-CR-sYINT.js → Credentials-RTT7N6zl.js} +1 -1
- package/web/console/assets/{Diagnostics-DAPbKSJp.js → Diagnostics-_LeK8cce.js} +1 -1
- package/web/console/assets/{Executors-CgpiT3o8.js → Executors-Bi7H8rIm.js} +1 -1
- package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-BfyWrxCE.js} +1 -1
- package/web/console/assets/{Kb-Cm9dVSQw.js → Kb-BHamz8NP.js} +2 -2
- package/web/console/assets/{Login-CyUcsTZ_.js → Login-C1rJR-6w.js} +1 -1
- package/web/console/assets/{Projects-DldFPgWg.js → Projects-BRA4a48v.js} +1 -1
- package/web/console/assets/Routes-CTC7U-fQ.js +124 -0
- package/web/console/assets/Routes-CyXV4Pba.css +1 -0
- package/web/console/assets/{Runs-1hxgkuR4.js → Runs-B_fa_BlD.js} +1 -1
- package/web/console/assets/{Setup-DBLOnI2_.js → Setup-C1_d0mFy.js} +1 -1
- package/web/console/assets/Shell-CHEV6RGC.js +1 -0
- package/web/console/assets/Shell-ykb-tUfo.css +1 -0
- package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
- package/web/console/assets/StorageBuckets-DlG3ojhA.js +1 -0
- package/web/console/assets/{SystemSettings-cDkudo2y.js → SystemSettings-DYo2gg6d.js} +1 -1
- package/web/console/assets/{SystemStatus-DZd6s8OX.js → SystemStatus-DKCoUZlq.js} +1 -1
- package/web/console/assets/{Targets-DYNGq1NU.js → Targets-CdkG6BPR.js} +1 -1
- package/web/console/assets/Tools-DU8ei6sd.css +1 -0
- package/web/console/assets/Tools-DVpCt0ox.js +2 -0
- package/web/console/assets/Usage-CAeDGjrb.css +1 -0
- package/web/console/assets/Usage-DWCpLugC.js +1 -0
- package/web/console/assets/UsageAccess-B_Xq7ARW.js +1 -0
- package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
- package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
- package/web/console/assets/UsageHelp-t5ZG_f-e.js +1 -0
- package/web/console/assets/{index-QnmD7N7F.js → index-C6W4LWVV.js} +1 -1
- package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
- package/web/console/assets/index-H1kfa0Mj.js +2 -0
- package/web/console/assets/{request-B7MLvOqo.js → request-DLsP1_ot.js} +1 -1
- package/web/console/assets/{schema-CMuwjYdJ.js → schema-BLOHvAJQ.js} +1 -1
- package/web/console/assets/{util-4bN2dv7B.js → util-CGVh2Jvr.js} +1 -1
- package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-BD089KxE.js} +1 -1
- package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-Bv-CZhmH.js} +1 -1
- package/web/console/index.html +3 -3
- package/web-admin/README.md +17 -0
- 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/components/UsageDeletionPreview.vue +44 -0
- package/web-admin/src/components/UsageHelp.vue +72 -0
- package/web-admin/src/components/UsageServiceReferences.vue +169 -0
- package/web-admin/src/layout/Shell.vue +23 -6
- package/web-admin/src/pages/Accounts.vue +3 -3
- package/web-admin/src/pages/AgentClients.vue +3 -1
- package/web-admin/src/pages/AgentTasks.vue +281 -0
- package/web-admin/src/pages/Routes.vue +5 -1
- package/web-admin/src/pages/StorageBuckets.vue +6 -6
- package/web-admin/src/pages/Tools.vue +53 -4
- package/web-admin/src/pages/Usage.vue +2470 -0
- package/web-admin/src/pages/UsageAccess.vue +1147 -0
- package/web-admin/src/router.ts +10 -4
- package/web-admin/src/styles/base.css +57 -0
- package/web-admin/src/table-widths.ts +16 -1
- package/web-admin/src/usage-deletion.ts +40 -0
- package/web-admin/src/usage-management.ts +13 -0
- package/web-admin/src/usage-presentation.test.ts +21 -0
- package/web-admin/src/usage-presentation.ts +107 -0
- package/web-admin/src/usage-price-preview.test.ts +60 -0
- package/web-admin/src/usage-price-preview.ts +54 -0
- package/web-admin/tests/token-usage.browser.mjs +773 -0
- package/web-admin/tests/usage-access.browser.mjs +398 -0
- package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
- package/web/console/assets/Accounts-ChL9k-XA.js +0 -3
- package/web/console/assets/AgentClients-Bs7UgVDj.js +0 -1
- package/web/console/assets/AgentClients-DkgPTEbq.css +0 -1
- package/web/console/assets/Routes-DkMIjMQA.css +0 -1
- package/web/console/assets/Routes-DubfjlBD.js +0 -124
- 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
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { openInvocationArguments, sealInvocationArguments } from './agent-invocation-snapshot';
|
|
2
|
+
import { bindingForTask, resolveAgentTaskRunFor } from './agent-task-control';
|
|
3
|
+
import { taskAssert } from '../core/runtime/agent-task-control';
|
|
4
|
+
import type { ToolRateLimitFeedback } from '../core/contracts/tools';
|
|
1
5
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
6
|
import { agentDirectToolsConfig } from '../core/config/tools-config';
|
|
3
7
|
import type { ToolDefinition } from '../core/contracts/tool-definition';
|
|
@@ -12,7 +16,7 @@ import type { AgentClientRunRecord } from '../infrastructure/config/config-agent
|
|
|
12
16
|
import type { ToolProxyDeps } from './tool-proxy';
|
|
13
17
|
import {
|
|
14
18
|
AGENT_TOOL_JOB_MARKER,
|
|
15
|
-
|
|
19
|
+
agentToolJobSource,
|
|
16
20
|
AGENT_TOOL_JOB_TARGET,
|
|
17
21
|
isAgentToolInvocationJob,
|
|
18
22
|
} from './agent-tool-job';
|
|
@@ -26,6 +30,8 @@ const INVOCATION_LOCK_TTL_MS = 15 * 60_000;
|
|
|
26
30
|
|
|
27
31
|
export const AGENT_TOOL_CATALOG_SCHEMA = 'bailing.agent-tool-catalog.v1';
|
|
28
32
|
export const AGENT_TOOL_INVOCATION_SCHEMA = 'bailing.agent-tool-invocation.v1';
|
|
33
|
+
export const AGENT_INVOCATION_RECEIPT_SCHEMA = 'bailing.agent-invocation-receipt.v1';
|
|
34
|
+
export const AGENT_INVOCATION_INSPECTION_SCHEMA = 'bailing.agent-invocation-inspection-capabilities.v1';
|
|
29
35
|
const AGENT_TOOL_EXECUTION_FINGERPRINT_SCHEMA = 'bailing.agent-tool-execution.v1';
|
|
30
36
|
|
|
31
37
|
export type AgentToolInvocationState =
|
|
@@ -61,12 +67,28 @@ export interface AgentToolCatalog {
|
|
|
61
67
|
}
|
|
62
68
|
|
|
63
69
|
export const AGENT_TOOL_SEARCH_SCHEMA = 'bailing.agent-capability-search.v1';
|
|
70
|
+
export interface AgentToolDiscovery {
|
|
71
|
+
mode: 'ranked_candidates';
|
|
72
|
+
scope: 'current_authorization';
|
|
73
|
+
returned_count: number;
|
|
74
|
+
authorized_total: number;
|
|
75
|
+
matched_total: null;
|
|
76
|
+
matched_total_exact: false;
|
|
77
|
+
limit: number;
|
|
78
|
+
truncated: boolean;
|
|
79
|
+
has_more: boolean;
|
|
80
|
+
truncation_scope: 'authorized_catalog';
|
|
81
|
+
pagination: 'unsupported';
|
|
82
|
+
}
|
|
83
|
+
|
|
64
84
|
export interface AgentToolSearchResult {
|
|
65
85
|
schema_version: typeof AGENT_TOOL_SEARCH_SCHEMA;
|
|
66
86
|
route: string;
|
|
67
87
|
capability_revision: string;
|
|
68
88
|
query: string;
|
|
69
89
|
tools: AgentToolCatalogItem[];
|
|
90
|
+
/** Optional for compatibility with earlier v1 responses; counts share this result's authorized surface. */
|
|
91
|
+
discovery?: AgentToolDiscovery;
|
|
70
92
|
}
|
|
71
93
|
|
|
72
94
|
export interface AgentToolInvocationResult {
|
|
@@ -77,11 +99,38 @@ export interface AgentToolInvocationResult {
|
|
|
77
99
|
state: AgentToolInvocationState;
|
|
78
100
|
ok: boolean;
|
|
79
101
|
auto_retry_allowed: boolean;
|
|
102
|
+
retry_after_ms?: number;
|
|
103
|
+
rate_limit?: ToolRateLimitFeedback;
|
|
80
104
|
text: string;
|
|
81
105
|
business_status?: number;
|
|
82
106
|
approval_id?: number;
|
|
83
107
|
}
|
|
84
108
|
|
|
109
|
+
/** Observations of the original call, never permission to dispatch or replay it. */
|
|
110
|
+
export interface AgentInvocationReceipt {
|
|
111
|
+
schema_version: typeof AGENT_INVOCATION_RECEIPT_SCHEMA;
|
|
112
|
+
read_only: true;
|
|
113
|
+
business_operation_performed: false;
|
|
114
|
+
invocation_id: string;
|
|
115
|
+
agent_run_id: string;
|
|
116
|
+
route: string;
|
|
117
|
+
tool: string;
|
|
118
|
+
observed_at: string;
|
|
119
|
+
result: AgentToolInvocationResult | null;
|
|
120
|
+
result_source: 'job' | 'journal' | 'none';
|
|
121
|
+
dispatch_state: 'not_dispatched' | 'attempted' | 'unknown';
|
|
122
|
+
approval: { status: 'none' | 'pending' | 'approved' | 'denied'; approval_id?: number };
|
|
123
|
+
journal_state: 'absent' | 'dispatching' | 'response_recorded' | 'completed' | 'uncertain' | 'evidence_degraded' | 'unknown';
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function agentInvocationInspectionCapabilities() {
|
|
127
|
+
return {
|
|
128
|
+
schema_version: AGENT_INVOCATION_INSPECTION_SCHEMA,
|
|
129
|
+
receipt_schema: AGENT_INVOCATION_RECEIPT_SCHEMA,
|
|
130
|
+
read_only: true as const,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
85
134
|
export class AgentToolApiError extends Error {
|
|
86
135
|
constructor(
|
|
87
136
|
readonly statusCode: number,
|
|
@@ -282,7 +331,7 @@ function probeJob(auth: AgentToolAuthContext, route: Route, now: string): Job {
|
|
|
282
331
|
target: AGENT_TOOL_JOB_TARGET,
|
|
283
332
|
profile: route.profile,
|
|
284
333
|
project: route.project ?? '',
|
|
285
|
-
source:
|
|
334
|
+
source: agentToolJobSource(auth.client.app_id),
|
|
286
335
|
client_app_id: auth.client.app_id,
|
|
287
336
|
agent_session_id: auth.session.session_id,
|
|
288
337
|
on_behalf_of: auth.session.on_behalf_of,
|
|
@@ -426,12 +475,27 @@ export async function searchAgentToolsFor(
|
|
|
426
475
|
|| a.name.localeCompare(b.name));
|
|
427
476
|
}
|
|
428
477
|
}
|
|
478
|
+
const tools = ordered.slice(0, limit);
|
|
479
|
+
const truncated = surface.tools.length > tools.length;
|
|
429
480
|
return {
|
|
430
481
|
schema_version: AGENT_TOOL_SEARCH_SCHEMA,
|
|
431
482
|
route: surface.route.route_key,
|
|
432
483
|
capability_revision: surface.revision,
|
|
433
484
|
query: cleanQuery,
|
|
434
|
-
tools
|
|
485
|
+
tools,
|
|
486
|
+
discovery: {
|
|
487
|
+
mode: 'ranked_candidates',
|
|
488
|
+
scope: 'current_authorization',
|
|
489
|
+
returned_count: tools.length,
|
|
490
|
+
authorized_total: surface.tools.length,
|
|
491
|
+
matched_total: null,
|
|
492
|
+
matched_total_exact: false,
|
|
493
|
+
limit,
|
|
494
|
+
truncated,
|
|
495
|
+
has_more: truncated,
|
|
496
|
+
truncation_scope: 'authorized_catalog',
|
|
497
|
+
pagination: 'unsupported',
|
|
498
|
+
},
|
|
435
499
|
};
|
|
436
500
|
}
|
|
437
501
|
|
|
@@ -462,6 +526,8 @@ function publicResult(input: {
|
|
|
462
526
|
ok: boolean;
|
|
463
527
|
text: string;
|
|
464
528
|
autoRetryAllowed?: boolean;
|
|
529
|
+
retryAfterMs?: number;
|
|
530
|
+
rateLimit?: ToolRateLimitFeedback;
|
|
465
531
|
businessStatus?: number;
|
|
466
532
|
approvalId?: number;
|
|
467
533
|
}): AgentToolInvocationResult {
|
|
@@ -474,12 +540,14 @@ function publicResult(input: {
|
|
|
474
540
|
ok: input.ok,
|
|
475
541
|
auto_retry_allowed: input.autoRetryAllowed ?? false,
|
|
476
542
|
text: safeText(input.text, 8192),
|
|
543
|
+
...(input.retryAfterMs !== undefined ? { retry_after_ms: input.retryAfterMs } : {}),
|
|
544
|
+
...(input.rateLimit ? { rate_limit: input.rateLimit } : {}),
|
|
477
545
|
...(input.businessStatus !== undefined ? { business_status: input.businessStatus } : {}),
|
|
478
546
|
...(input.approvalId !== undefined ? { approval_id: input.approvalId } : {}),
|
|
479
547
|
};
|
|
480
548
|
}
|
|
481
549
|
|
|
482
|
-
function isStableInvocationResult(result: AgentToolInvocationResult | null): result is AgentToolInvocationResult {
|
|
550
|
+
function isStableInvocationResult(result: AgentToolInvocationResult | null): result is AgentToolInvocationResult & { auto_retry_allowed: false } {
|
|
483
551
|
return !!result
|
|
484
552
|
&& !['in_progress', 'awaiting_approval'].includes(result.state)
|
|
485
553
|
&& result.auto_retry_allowed !== true;
|
|
@@ -561,7 +629,7 @@ function syntheticJob(
|
|
|
561
629
|
target: AGENT_TOOL_JOB_TARGET,
|
|
562
630
|
profile: surface.route.profile,
|
|
563
631
|
project: surface.route.project ?? '',
|
|
564
|
-
source:
|
|
632
|
+
source: agentToolJobSource(auth.client.app_id),
|
|
565
633
|
client_app_id: auth.client.app_id,
|
|
566
634
|
agent_session_id: auth.session.session_id,
|
|
567
635
|
on_behalf_of: auth.session.on_behalf_of,
|
|
@@ -572,6 +640,7 @@ function syntheticJob(
|
|
|
572
640
|
metadata: {
|
|
573
641
|
agent_tool_job_marker: AGENT_TOOL_JOB_MARKER,
|
|
574
642
|
agent_tool_call_v1: true,
|
|
643
|
+
agent_dispatch_attempted: false,
|
|
575
644
|
agent_invocation_id: input.invocation_id,
|
|
576
645
|
agent_run_id: input.agent_run_id,
|
|
577
646
|
agent_route: input.route,
|
|
@@ -616,7 +685,15 @@ function fromJournal(input: FrozenInvocationCoordinates, tool: string, entry: To
|
|
|
616
685
|
}
|
|
617
686
|
|
|
618
687
|
async function persistResult(deps: ToolProxyDeps, job: Job, result: AgentToolInvocationResult): Promise<void> {
|
|
619
|
-
|
|
688
|
+
const managed = Boolean(job.metadata.agent_task_binding || job.metadata.agent_task_id);
|
|
689
|
+
const metadata = { ...job.metadata };
|
|
690
|
+
if (isStableInvocationResult(result)) delete metadata.agent_frozen_arguments;
|
|
691
|
+
// Task transactions own the dispatch fence and permit metadata. A stale in-memory job must never overwrite it.
|
|
692
|
+
const saved = await deps.stateStore.updateJob(job.job_id, { ...(managed ? {} : { metadata }), status: 'done', result: { ...result }, error: undefined });
|
|
693
|
+
if (!saved) throw new AgentToolApiError(503, 'invocation_storage_unavailable', 'The original invocation state could not be saved.');
|
|
694
|
+
if (managed && isStableInvocationResult(result)) await deps.configStore!.agentTaskControl!.clearFrozenArguments(job.job_id);
|
|
695
|
+
job.metadata = metadata;
|
|
696
|
+
job.result = { ...result };
|
|
620
697
|
await deps.stateStore.appendAudit({
|
|
621
698
|
ts: deps.now(), job_id: job.job_id, request_id: job.request_id, event: 'agent_tool_invocation_state',
|
|
622
699
|
detail: { invocation_id: result.invocation_id, route: result.route, tool: result.tool, state: result.state, ok: result.ok, business_status: result.business_status ?? null },
|
|
@@ -638,7 +715,7 @@ async function invokeExisting(
|
|
|
638
715
|
if (!surface.context.allowed.some((candidate) => candidate.name === tool)) {
|
|
639
716
|
throw new AgentToolApiError(409, 'capability_changed', 'The tool is no longer available; refresh the capability catalog.');
|
|
640
717
|
}
|
|
641
|
-
const journal = await deps.configStore!.toolCalls.get(job.job_id, tool, hash)
|
|
718
|
+
const journal = await deps.configStore!.toolCalls.get(job.job_id, tool, hash);
|
|
642
719
|
if (journal) {
|
|
643
720
|
const result = fromJournal(input, tool, journal);
|
|
644
721
|
await persistResult(deps, job, result);
|
|
@@ -646,6 +723,11 @@ async function invokeExisting(
|
|
|
646
723
|
}
|
|
647
724
|
const approval = await currentApproval(deps.configStore!, job, tool, hash);
|
|
648
725
|
if (approval?.status === 'denied') {
|
|
726
|
+
if (job.metadata.agent_task_binding || job.metadata.agent_task_id) {
|
|
727
|
+
const original = await deps.configStore!.agentTaskControl!.findInvocation(auth.session.session_id, input.invocation_id);
|
|
728
|
+
if (original) await deps.configStore!.agentTaskControl!.releaseReservation({ taskId: original.taskId,
|
|
729
|
+
sessionId: auth.session.session_id, invocationId: input.invocation_id, reason: 'approval_denied', approvalId: approval.id });
|
|
730
|
+
}
|
|
649
731
|
const result = publicResult({ invocationId: input.invocation_id, route: input.route, tool, state: 'denied', ok: false, text: 'The governed tool invocation was denied.' });
|
|
650
732
|
await persistResult(deps, job, result);
|
|
651
733
|
return result;
|
|
@@ -655,6 +737,16 @@ async function invokeExisting(
|
|
|
655
737
|
await persistResult(deps, job, result);
|
|
656
738
|
return result;
|
|
657
739
|
}
|
|
740
|
+
// Only an affirmative pre-dispatch result permits another dispatch attempt.
|
|
741
|
+
// A persisted in-progress attempt without a terminal journal may have reached the business system.
|
|
742
|
+
if (job.metadata.agent_dispatch_attempted !== false && cached?.state === 'in_progress') {
|
|
743
|
+
const result = publicResult({ invocationId: input.invocation_id, route: input.route, tool, state: 'reconciliation_required', ok: false, text: 'The original dispatch outcome is unknown; reconcile the original invocation. Do not submit a new write.' });
|
|
744
|
+
await persistResult(deps, job, result);
|
|
745
|
+
return result;
|
|
746
|
+
}
|
|
747
|
+
if (!args && ((cached?.state === 'rejected_before_dispatch' && cached.auto_retry_allowed) || job.metadata.agent_dispatch_attempted === false)) {
|
|
748
|
+
args = openInvocationArguments(job, deps.cfg.server.token);
|
|
749
|
+
}
|
|
658
750
|
if (!args && approval?.status === 'approved' && approval.args_json) {
|
|
659
751
|
try {
|
|
660
752
|
const parsed: unknown = JSON.parse(approval.args_json);
|
|
@@ -674,6 +766,11 @@ async function invokeExisting(
|
|
|
674
766
|
if (!runtime || runtime === 'subject_locked') {
|
|
675
767
|
throw new AgentToolApiError(409, 'capability_changed', 'The tool surface is no longer available; refresh the capability catalog.');
|
|
676
768
|
}
|
|
769
|
+
if (!job.metadata.agent_task_binding && !job.metadata.agent_task_id) {
|
|
770
|
+
job = { ...job, metadata: { ...job.metadata, agent_dispatch_attempted: true } };
|
|
771
|
+
}
|
|
772
|
+
// Persist the attempt fence before allowing HTTP dispatch, including resumed idempotent writes.
|
|
773
|
+
await persistResult(deps, job, publicResult({ invocationId: input.invocation_id, route: input.route, tool, state: 'in_progress', ok: false, text: 'The original governed invocation is in progress.' }));
|
|
677
774
|
const out = await runtime.invoke(tool, args);
|
|
678
775
|
const uncertainty = runtime.executionUncertainty();
|
|
679
776
|
const state: AgentToolInvocationState = uncertainty || out.governance_state === 'reconciliation_required'
|
|
@@ -693,6 +790,8 @@ async function invokeExisting(
|
|
|
693
790
|
ok: out.ok,
|
|
694
791
|
text: out.text,
|
|
695
792
|
autoRetryAllowed: out.auto_retry_allowed ?? false,
|
|
793
|
+
retryAfterMs: out.retry_after_ms,
|
|
794
|
+
rateLimit: out.rate_limit,
|
|
696
795
|
...(out.status > 0 && out.governance_state !== 'rejected_before_dispatch' ? { businessStatus: out.status } : {}),
|
|
697
796
|
...(out.approval_id !== undefined ? { approvalId: out.approval_id } : {}),
|
|
698
797
|
});
|
|
@@ -702,6 +801,7 @@ async function invokeExisting(
|
|
|
702
801
|
|
|
703
802
|
export async function invokeAgentToolFor(deps: ToolProxyDeps, auth: AgentToolAuthContext, input: InvokeAgentToolInput): Promise<AgentToolInvocationResult> {
|
|
704
803
|
assertInvocationInput(input);
|
|
804
|
+
input = { ...input, arguments: JSON.parse(JSON.stringify(input.arguments)) as Record<string, unknown> };
|
|
705
805
|
const runtimeRun = await deps.configStore?.agentClientRuntime?.findRunForInvocation(input.agent_run_id) ?? null;
|
|
706
806
|
if (runtimeRun && (
|
|
707
807
|
runtimeRun.session_id !== auth.session.session_id
|
|
@@ -722,6 +822,8 @@ export async function invokeAgentToolFor(deps: ToolProxyDeps, auth: AgentToolAut
|
|
|
722
822
|
if (job && !sameInvocation(job, auth, { ...input, args_hash: hash })) {
|
|
723
823
|
throw new AgentToolApiError(409, 'invocation_conflict', 'The invocation_id is already bound to a different call.');
|
|
724
824
|
}
|
|
825
|
+
const task = await resolveAgentTaskRunFor(deps.configStore, auth, input.agent_run_id, input.route, !job);
|
|
826
|
+
taskAssert(task || !(runtimeRun?.context?.task_binding || job?.metadata.agent_task_binding || job?.metadata.agent_task_id), 'TASK_UNSUPPORTED');
|
|
725
827
|
if (job) await resolveDirectRoute(deps, auth, input.route);
|
|
726
828
|
const cached = job ? parseInvocationResult(job) : null;
|
|
727
829
|
let surface: AgentToolSurface | null = null;
|
|
@@ -732,9 +834,6 @@ export async function invokeAgentToolFor(deps: ToolProxyDeps, auth: AgentToolAut
|
|
|
732
834
|
}
|
|
733
835
|
surface = await resolveSurface(deps, auth, input.route);
|
|
734
836
|
if (!job) {
|
|
735
|
-
if (await rateLimitedFor(deps.configStore, auth.client)) {
|
|
736
|
-
return publicResult({ invocationId: input.invocation_id, route: input.route, tool: input.tool, state: 'rejected_before_dispatch', ok: false, text: 'The Agent client rate limit was exceeded.', autoRetryAllowed: true });
|
|
737
|
-
}
|
|
738
837
|
if (surface.revision !== input.capability_revision) {
|
|
739
838
|
throw new AgentToolApiError(409, 'capability_changed', 'The capability catalog changed; refresh tools before calling.');
|
|
740
839
|
}
|
|
@@ -744,11 +843,18 @@ export async function invokeAgentToolFor(deps: ToolProxyDeps, auth: AgentToolAut
|
|
|
744
843
|
throw new AgentToolApiError(404, 'tool_not_found', 'The tool is not available in the current capability catalog.');
|
|
745
844
|
}
|
|
746
845
|
job = syntheticJob(auth, surface, input, hash, toolFingerprint, runtimeRun, deps.now());
|
|
846
|
+
if (task) job.metadata.agent_task_binding = bindingForTask(task);
|
|
847
|
+
job.metadata.agent_frozen_arguments = sealInvocationArguments(job, input.arguments, deps.cfg.server.token);
|
|
747
848
|
await deps.stateStore.createJob(job);
|
|
748
849
|
await deps.stateStore.appendAudit({
|
|
749
850
|
ts: deps.now(), job_id: job.job_id, request_id: job.request_id, event: 'agent_tool_invocation_created',
|
|
750
851
|
detail: { invocation_id: input.invocation_id, agent_run_id: input.agent_run_id, agent_thread_id: runtimeRun?.thread_id ?? null, route: input.route, tool: input.tool, args_hash: hash, execution_fingerprint: toolFingerprint, client_app_id: auth.client.app_id, agent_session_id: auth.session.session_id },
|
|
751
852
|
});
|
|
853
|
+
if (await rateLimitedFor(deps.configStore, auth.client)) {
|
|
854
|
+
const result = publicResult({ invocationId: input.invocation_id, route: input.route, tool: input.tool, state: 'rejected_before_dispatch', ok: false, text: 'The Agent client shared rate limit was exceeded; resume this invocation after waiting.', autoRetryAllowed: true, retryAfterMs: 60_000 });
|
|
855
|
+
await persistResult(deps, job, result);
|
|
856
|
+
return result;
|
|
857
|
+
}
|
|
752
858
|
} else {
|
|
753
859
|
assertCurrentToolExecution(job, surface, input.tool);
|
|
754
860
|
if (await rateLimitedFor(deps.configStore, auth.client)) {
|
|
@@ -778,6 +884,8 @@ export async function resumeAgentToolFor(deps: ToolProxyDeps, auth: AgentToolAut
|
|
|
778
884
|
throw new AgentToolApiError(404, 'invocation_not_found', 'The governed invocation was not found.');
|
|
779
885
|
}
|
|
780
886
|
const route = String(job.metadata['agent_route'] ?? '');
|
|
887
|
+
const task = await resolveAgentTaskRunFor(deps.configStore, auth, String(job.metadata.agent_run_id ?? ''), route, false);
|
|
888
|
+
taskAssert(task || !(job.metadata.agent_task_binding || job.metadata.agent_task_id), 'TASK_UNSUPPORTED');
|
|
781
889
|
const capabilityRevision = String(job.metadata['agent_capability_revision'] ?? '');
|
|
782
890
|
const tool = String(job.metadata['agent_tool'] ?? '');
|
|
783
891
|
const hash = String(job.metadata['agent_args_hash'] ?? '');
|
|
@@ -805,3 +913,108 @@ export async function resumeAgentToolFor(deps: ToolProxyDeps, auth: AgentToolAut
|
|
|
805
913
|
await deps.stateStore.releaseRuntimeLock(lockKey, owner).catch(() => undefined);
|
|
806
914
|
}
|
|
807
915
|
}
|
|
916
|
+
|
|
917
|
+
/** An allowlisted result copy. Stored JSON is data, including when its schema marker is valid. */
|
|
918
|
+
function receiptResult(job: Job): AgentToolInvocationResult | null {
|
|
919
|
+
const saved = parseInvocationResult(job);
|
|
920
|
+
if (!saved) return null;
|
|
921
|
+
const limit = saved.rate_limit;
|
|
922
|
+
const rateLimit = isRecord(limit)
|
|
923
|
+
&& (limit['level'] === 'tool' || limit['level'] === 'provider')
|
|
924
|
+
&& Number.isSafeInteger(limit['count']) && Number(limit['count']) > 0
|
|
925
|
+
&& Number.isSafeInteger(limit['window_sec']) && Number(limit['window_sec']) > 0
|
|
926
|
+
&& limit['scope'] === 'tool_provider_shared' && typeof limit['source'] === 'string'
|
|
927
|
+
? {
|
|
928
|
+
level: limit['level'], count: Number(limit['count']), window_sec: Number(limit['window_sec']),
|
|
929
|
+
scope: 'tool_provider_shared' as const, source: safeText(limit['source'], 128),
|
|
930
|
+
} : undefined;
|
|
931
|
+
return publicResult({
|
|
932
|
+
invocationId: saved.invocation_id, route: saved.route, tool: saved.tool, state: saved.state,
|
|
933
|
+
ok: saved.ok, text: saved.text, autoRetryAllowed: saved.auto_retry_allowed,
|
|
934
|
+
...(Number.isSafeInteger(saved.retry_after_ms) && Number(saved.retry_after_ms) >= 0 ? { retryAfterMs: saved.retry_after_ms } : {}),
|
|
935
|
+
...(rateLimit ? { rateLimit } : {}),
|
|
936
|
+
...(saved.business_status !== undefined ? { businessStatus: saved.business_status } : {}),
|
|
937
|
+
...(saved.approval_id !== undefined ? { approvalId: saved.approval_id } : {}),
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/**
|
|
942
|
+
* Reads local evidence only. In particular this must not call invokeExisting: resume may
|
|
943
|
+
* consume an approved request and perform its first business dispatch.
|
|
944
|
+
* The observations are not an atomic dispatch decision and confer no permission to replay.
|
|
945
|
+
*/
|
|
946
|
+
export async function inspectAgentToolInvocationFor(
|
|
947
|
+
deps: ToolProxyDeps, auth: AgentToolAuthContext, input: ResumeAgentToolInput,
|
|
948
|
+
): Promise<AgentInvocationReceipt> {
|
|
949
|
+
if (!INVOCATION_RE.test(input.invocation_id)) {
|
|
950
|
+
throw new AgentToolApiError(400, 'invalid_request', 'The original invocation identifier is invalid.');
|
|
951
|
+
}
|
|
952
|
+
if (!deps.configStore) throw new AgentToolApiError(503, 'agent_tools_unavailable', 'Invocation inspection requires the control plane.');
|
|
953
|
+
const requestId = invocationRequestId(auth.session.session_id, input.invocation_id);
|
|
954
|
+
const stored = await deps.stateStore.findByRequestId(requestId);
|
|
955
|
+
if (!stored || !isAgentToolInvocationJob(stored)
|
|
956
|
+
|| stored.agent_session_id !== auth.session.session_id || stored.client_app_id !== auth.client.app_id) {
|
|
957
|
+
throw new AgentToolApiError(404, 'invocation_not_found', 'The original governed invocation was not found.');
|
|
958
|
+
}
|
|
959
|
+
// Freeze the observation even for in-memory repository implementations.
|
|
960
|
+
const job = JSON.parse(JSON.stringify(stored)) as Job;
|
|
961
|
+
const metadata = job.metadata;
|
|
962
|
+
const route = String(metadata['agent_route'] ?? '');
|
|
963
|
+
const tool = String(metadata['agent_tool'] ?? '');
|
|
964
|
+
const runId = String(metadata['agent_run_id'] ?? '');
|
|
965
|
+
const revision = String(metadata['agent_capability_revision'] ?? '');
|
|
966
|
+
const hash = String(metadata['agent_args_hash'] ?? '');
|
|
967
|
+
const originalPrincipal = metadata['principal'];
|
|
968
|
+
if (job.request_id !== requestId || !ROUTE_RE.test(route) || !AGENT_RUN_RE.test(runId)
|
|
969
|
+
|| !REVISION_RE.test(revision) || !REVISION_RE.test(hash) || !/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(tool)
|
|
970
|
+
|| job.session_id !== runId || job.on_behalf_of !== auth.session.on_behalf_of
|
|
971
|
+
|| !isRecord(originalPrincipal) || originalPrincipal['id'] !== auth.session.principal.id
|
|
972
|
+
|| originalPrincipal['tenant'] !== auth.session.principal.tenant
|
|
973
|
+
|| !sameInvocation(job, auth, { invocation_id: input.invocation_id, route, tool, args_hash: hash, capability_revision: revision, agent_run_id: runId })) {
|
|
974
|
+
throw new AgentToolApiError(409, 'invocation_conflict', 'The original invocation binding could not be verified.');
|
|
975
|
+
}
|
|
976
|
+
const runtimeRun = await deps.configStore.agentClientRuntime?.findRunForInvocation(runId) ?? null;
|
|
977
|
+
const task = await resolveAgentTaskRunFor(deps.configStore, auth, runId, route, false);
|
|
978
|
+
taskAssert(task || !(runtimeRun?.context?.task_binding || metadata.agent_task_binding || metadata.agent_task_id), 'TASK_UNSUPPORTED');
|
|
979
|
+
if (runtimeRun && (runtimeRun.run_id !== runId || runtimeRun.session_id !== auth.session.session_id
|
|
980
|
+
|| runtimeRun.client_app_id !== auth.client.app_id || runtimeRun.route_key !== route
|
|
981
|
+
|| (job.thread_id !== undefined && runtimeRun.thread_id !== job.thread_id))) {
|
|
982
|
+
throw new AgentToolApiError(409, 'agent_run_conflict', 'The original runtime run belongs to a different binding.');
|
|
983
|
+
}
|
|
984
|
+
// Current authorization is required, but the historical execution/schema fingerprint
|
|
985
|
+
// need not remain current merely to inspect a result. No business context or run is created.
|
|
986
|
+
const surface = await resolveSurface(deps, auth, route);
|
|
987
|
+
assertCurrentToolAuthorized(surface, tool);
|
|
988
|
+
const journal = await deps.configStore.toolCalls.get(job.job_id, tool, hash);
|
|
989
|
+
const current = await currentApproval(deps.configStore, job, tool, hash);
|
|
990
|
+
if (current && (!['pending', 'approved', 'denied'].includes(current.status)
|
|
991
|
+
|| !Number.isSafeInteger(current.id) || current.id < 1)) {
|
|
992
|
+
throw new AgentToolApiError(503, 'invocation_record_invalid', 'The original approval record could not be verified.');
|
|
993
|
+
}
|
|
994
|
+
const journalStates = ['dispatching', 'response_recorded', 'completed', 'uncertain', 'evidence_degraded'];
|
|
995
|
+
const journalState: AgentInvocationReceipt['journal_state'] = !journal ? 'absent'
|
|
996
|
+
: journalStates.includes(journal.state) ? journal.state : 'unknown';
|
|
997
|
+
let result = receiptResult(job);
|
|
998
|
+
let resultSource: AgentInvocationReceipt['result_source'] = result ? 'job' : 'none';
|
|
999
|
+
if (journal) {
|
|
1000
|
+
resultSource = 'journal';
|
|
1001
|
+
result = journalState === 'completed' && typeof journal.ok === 'boolean'
|
|
1002
|
+
&& Number.isSafeInteger(journal.status) && journal.status > 0 && typeof journal.text === 'string'
|
|
1003
|
+
? publicResult({ invocationId: input.invocation_id, route, tool,
|
|
1004
|
+
state: journal.ok ? 'executed' : 'business_rejected', ok: journal.ok, text: journal.text, businessStatus: journal.status })
|
|
1005
|
+
: publicResult({ invocationId: input.invocation_id, route, tool, state: 'reconciliation_required', ok: false,
|
|
1006
|
+
text: 'The original execution journal has not confirmed a completed outcome. Inspect the original record; do not repeat the business operation.' });
|
|
1007
|
+
}
|
|
1008
|
+
const dispatchState: AgentInvocationReceipt['dispatch_state'] = journalState === 'unknown' ? 'unknown'
|
|
1009
|
+
: journal || result?.state === 'executed' || result?.state === 'business_rejected' ? 'attempted'
|
|
1010
|
+
: result && ['awaiting_approval', 'denied', 'rejected_before_dispatch'].includes(result.state) ? 'not_dispatched'
|
|
1011
|
+
: metadata['agent_dispatch_attempted'] === false ? 'not_dispatched'
|
|
1012
|
+
: metadata['agent_dispatch_attempted'] === true ? 'attempted' : 'unknown';
|
|
1013
|
+
return {
|
|
1014
|
+
schema_version: AGENT_INVOCATION_RECEIPT_SCHEMA, read_only: true, business_operation_performed: false,
|
|
1015
|
+
invocation_id: input.invocation_id, agent_run_id: runId, route, tool, observed_at: deps.now(),
|
|
1016
|
+
result, result_source: resultSource, dispatch_state: dispatchState,
|
|
1017
|
+
approval: current ? { status: current.status, approval_id: current.id } : { status: 'none' },
|
|
1018
|
+
journal_state: journalState,
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
@@ -1,7 +1,17 @@
|
|
|
1
1
|
import assert from 'node:assert/strict';
|
|
2
2
|
import test from 'node:test';
|
|
3
3
|
import type { Job } from '../core/contracts/types';
|
|
4
|
-
import { AGENT_TOOL_JOB_MARKER, isAgentToolInvocationJob } from './agent-tool-job';
|
|
4
|
+
import { AGENT_TOOL_JOB_MARKER, agentToolJobSource, isAgentToolInvocationJob } from './agent-tool-job';
|
|
5
|
+
|
|
6
|
+
test('Agent source labels fit the existing column and preserve exact Client binding', () => {
|
|
7
|
+
assert.equal(agentToolJobSource('example-business'), 'agent-tool:example-business');
|
|
8
|
+
for (const length of [21, 22, 32, 64]) {
|
|
9
|
+
const client = 'a'.repeat(length);
|
|
10
|
+
const job = { ...directJob(), client_app_id: client, source: agentToolJobSource(client) };
|
|
11
|
+
assert.ok(job.source.length <= 32); assert.equal(isAgentToolInvocationJob(job), true);
|
|
12
|
+
assert.equal(isAgentToolInvocationJob({ ...job, client_app_id: `${client.slice(0, -1)}b` }), false);
|
|
13
|
+
}
|
|
14
|
+
});
|
|
5
15
|
|
|
6
16
|
function directJob(): Job {
|
|
7
17
|
const route = 'tenant-agent';
|
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
import type { Job } from '../core/contracts/types';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
2
3
|
|
|
3
4
|
export const AGENT_TOOL_JOB_TARGET = 'agent-tool-v1';
|
|
4
5
|
export const AGENT_TOOL_JOB_SOURCE_PREFIX = 'agent-tool:';
|
|
5
6
|
export const AGENT_TOOL_JOB_MARKER = 'bailing.agent-tool-job.v1';
|
|
6
7
|
|
|
8
|
+
/** bz_jobs.source is a 32-character origin label; the full identity stays in client_app_id. */
|
|
9
|
+
export function agentToolJobSource(clientAppId: string): string {
|
|
10
|
+
const original = `${AGENT_TOOL_JOB_SOURCE_PREFIX}${clientAppId}`;
|
|
11
|
+
return original.length <= 32 ? original : `${AGENT_TOOL_JOB_SOURCE_PREFIX}${createHash('sha256').update(clientAppId).digest('hex').slice(0, 32 - AGENT_TOOL_JOB_SOURCE_PREFIX.length)}`;
|
|
12
|
+
}
|
|
13
|
+
|
|
7
14
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
8
15
|
const HEX_64_RE = /^[a-f0-9]{64}$/;
|
|
9
16
|
const REQUEST_ID_RE = /^agent-tool:[a-f0-9]{64}$/;
|
|
@@ -24,7 +31,7 @@ export function isAgentToolInvocationJob(job: Job | null | undefined): boolean {
|
|
|
24
31
|
return job.target === AGENT_TOOL_JOB_TARGET
|
|
25
32
|
&& REQUEST_ID_RE.test(job.request_id)
|
|
26
33
|
&& !!clientAppId
|
|
27
|
-
&& job.source === `${AGENT_TOOL_JOB_SOURCE_PREFIX}${clientAppId}`
|
|
34
|
+
&& (job.source === agentToolJobSource(clientAppId) || job.source === `${AGENT_TOOL_JOB_SOURCE_PREFIX}${clientAppId}`)
|
|
28
35
|
&& UUID_RE.test(agentSessionId)
|
|
29
36
|
&& !!job.on_behalf_of
|
|
30
37
|
&& metadata['agent_tool_job_marker'] === AGENT_TOOL_JOB_MARKER
|
package/src/app/auth.ts
CHANGED
|
@@ -33,6 +33,8 @@ export const ROLE_PERMS: Record<string, string[]> = {
|
|
|
33
33
|
admin: ['*'],
|
|
34
34
|
kb_editor: ['kb:read', 'kb:write'], // 客服/运维:维护知识库
|
|
35
35
|
viewer: ['runs:read'], // 只读看任务
|
|
36
|
+
usage_operator: ['usage:read', 'usage:write', 'usage:adjust'], // 不授予业务正文或模型密钥访问权
|
|
37
|
+
usage_auditor: ['usage:read'], // 消费元数据,只读
|
|
36
38
|
};
|
|
37
39
|
export function permsOf(p: Principal): string[] {
|
|
38
40
|
if (p.kind !== 'admin') return [];
|
package/src/app/builtin-tools.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
import { sendMessageConfig } from '../core/config/tools-config';
|
|
20
20
|
import { SEND_TOOL_NAME, type BuiltinToolDef } from '../core/targets/adapter';
|
|
21
21
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
22
|
+
import { assertTaskLegacyJobAllowedFor } from './agent-task-runtime';
|
|
22
23
|
|
|
23
24
|
export { SEND_MAX_CALLS, SEND_TOOL_NAME } from '../core/targets/adapter';
|
|
24
25
|
|
|
@@ -94,6 +95,8 @@ export async function runSendMessageFor(
|
|
|
94
95
|
) => Promise<ChannelSendResult> = channelSendFor,
|
|
95
96
|
): Promise<BuiltinSendResult> {
|
|
96
97
|
if (!config) return { ok: false, text: '发送失败:中枢无 mysql 后端。' };
|
|
98
|
+
try { await assertTaskLegacyJobAllowedFor(config, job); }
|
|
99
|
+
catch { return { ok: false, text: 'TASK_REQUIRED: 此授权的业务执行必须经过原任务控制范围,消息未发送。' }; }
|
|
97
100
|
if (!allowedChannels.length) return { ok: false, text: '本路由未开放任何可主动发送的渠道,无法发送。' };
|
|
98
101
|
// 渠道:显式 channel 必须在白名单内;不给且只有一个允许渠道 → 默认它
|
|
99
102
|
const reqCh = String(args['channel'] ?? '').trim();
|
|
@@ -183,6 +186,7 @@ export async function runSendMessageFor(
|
|
|
183
186
|
}
|
|
184
187
|
|
|
185
188
|
try {
|
|
189
|
+
await assertTaskLegacyJobAllowedFor(config, job);
|
|
186
190
|
const reserved = await config.toolCalls.reserve(job.job_id, SEND_TOOL_NAME, scope, idemHash, idemKey);
|
|
187
191
|
if (!reserved.inserted) {
|
|
188
192
|
if (reserved.entry.state === 'completed') {
|
package/src/app/oss-edition.ts
CHANGED
|
@@ -84,6 +84,7 @@ export function createOssEdition(cfg: AppConfig, options: {
|
|
|
84
84
|
'routes',
|
|
85
85
|
'clients',
|
|
86
86
|
'agent-clients',
|
|
87
|
+
'agent-tasks',
|
|
87
88
|
'chat',
|
|
88
89
|
'channels',
|
|
89
90
|
'targets',
|
|
@@ -95,6 +96,7 @@ export function createOssEdition(cfg: AppConfig, options: {
|
|
|
95
96
|
'runs',
|
|
96
97
|
'executors',
|
|
97
98
|
'cost',
|
|
99
|
+
'usage',
|
|
98
100
|
'approvals',
|
|
99
101
|
'system',
|
|
100
102
|
'settings',
|
|
@@ -43,6 +43,10 @@ export function approvalDepsForStores(
|
|
|
43
43
|
if (!a) return null;
|
|
44
44
|
return (await cs.approvals.use(a.id)) ? a.id : null;
|
|
45
45
|
},
|
|
46
|
+
async peekApproved(tool, hash) {
|
|
47
|
+
const a = await cs.approvals.find(job.job_id, tool, hash, 'approved');
|
|
48
|
+
return a?.id ?? null;
|
|
49
|
+
},
|
|
46
50
|
async findApprovedAnyArgs(tool) {
|
|
47
51
|
const rows = await cs.approvals.approvedUnusedForJob(job.job_id).catch(() => []);
|
|
48
52
|
const a = rows.find((r) => r.tool === tool);
|
package/src/app/tool-assembly.ts
CHANGED
|
@@ -7,6 +7,7 @@ import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
|
7
7
|
import type { ToolIndexService } from '../services/tools-index';
|
|
8
8
|
import type { AppConfig } from '../core/config/config';
|
|
9
9
|
import { defaultTargetRegistry, type TargetRegistry } from '../core/targets/registry';
|
|
10
|
+
import { taskRuntimeFor } from './agent-task-runtime';
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* 工具插座装配:已过双闸的清单 → 受治理的工具运行时。
|
|
@@ -44,6 +45,7 @@ export async function assembleResolvedToolRuntimeFor(
|
|
|
44
45
|
targetRegistry: TargetRegistry = defaultTargetRegistry,
|
|
45
46
|
): Promise<ToolRuntime | 'subject_locked' | undefined> {
|
|
46
47
|
if (!r.allowed.length) return 'subject_locked';
|
|
48
|
+
const taskRuntime = await taskRuntimeFor(config, state, job);
|
|
47
49
|
const maxCalls = maxCallsOf(r.toolsCfg);
|
|
48
50
|
const retrievalMode = r.allowed.length > TOOL_INLINE_MAX;
|
|
49
51
|
const approvedNote = await approvedNoteForJobFor(config, job.job_id);
|
|
@@ -80,6 +82,8 @@ export async function assembleResolvedToolRuntimeFor(
|
|
|
80
82
|
jobId: job.job_id,
|
|
81
83
|
clientAppId: job.client_app_id ?? '',
|
|
82
84
|
truncateBytes: 8192,
|
|
85
|
+
taskControl: taskRuntime.taskControl,
|
|
86
|
+
beforeDispatch: taskRuntime.beforeDispatch,
|
|
83
87
|
approvals: approvalDepsForStores(config, state, job, provider, r.toolsCfg, sourceCfg, appConfig, nowFn, sleepFn, targetRegistry),
|
|
84
88
|
retrieveNames,
|
|
85
89
|
retrievalMode,
|
|
@@ -91,6 +95,7 @@ export async function assembleResolvedToolRuntimeFor(
|
|
|
91
95
|
markUncertain: (tool, hash, error) => config.toolCalls.markUncertain(job.job_id, tool, hash, error),
|
|
92
96
|
markEvidenceDegraded: (tool, hash, error) => config.toolCalls.markEvidenceDegraded(job.job_id, tool, hash, error),
|
|
93
97
|
} : undefined,
|
|
98
|
+
rateLimitAll: config?.rateLimits?.consumeAll ? (requests) => config.rateLimits.consumeAll!(requests) : undefined,
|
|
94
99
|
rateLimit: config ? (bucket, limit, windowSec) => config.rateLimits.consume(bucket, limit, windowSec) : undefined,
|
|
95
100
|
audit: async (event, detail) => {
|
|
96
101
|
await state.appendAudit({ ts: nowFn(), job_id: job.job_id, request_id: job.request_id, event, detail });
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const ARTIFACT_MIMES = ['image/png', 'image/jpeg', 'image/webp'] as const;
|
|
2
|
+
export const ARTIFACT_MAX_BYTES = 6 * 1024 * 1024;
|
|
3
|
+
export interface AgentArtifactConfig { enabled: boolean; bucket?: string; max_bytes?: number; allowed_mimes?: string[] }
|
|
4
|
+
export function validateArtifactConfig(value: unknown): string | null {
|
|
5
|
+
if (value === undefined) return null;
|
|
6
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return 'artifact_upload 必须是对象';
|
|
7
|
+
const v = value as Record<string, unknown>;
|
|
8
|
+
if (Object.keys(v).some(k => !['enabled', 'bucket', 'max_bytes', 'allowed_mimes'].includes(k))) return 'artifact_upload 包含未声明字段';
|
|
9
|
+
if (typeof v.enabled !== 'boolean') return 'artifact_upload.enabled 必须是布尔值';
|
|
10
|
+
if (v.bucket !== undefined && (typeof v.bucket !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(v.bucket))) return 'artifact_upload.bucket 必须是存储登记名';
|
|
11
|
+
if (v.enabled && !v.bucket) return '启用生成图片上传时必须明确选择媒体存储';
|
|
12
|
+
if (v.max_bytes !== undefined && (!Number.isInteger(v.max_bytes) || Number(v.max_bytes) < 1 || Number(v.max_bytes) > ARTIFACT_MAX_BYTES)) return '图片大小上限必须在 1 字节至 6 MiB 之间';
|
|
13
|
+
if (v.allowed_mimes !== undefined && (!Array.isArray(v.allowed_mimes) || !v.allowed_mimes.length || v.allowed_mimes.some(m => !(ARTIFACT_MIMES as readonly unknown[]).includes(m)))) return '支持的图片类型为 PNG、JPEG、WebP';
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { normalizeToolRateLimitPolicies } from '../contracts/tool-rate-limits';
|
|
1
2
|
import type { PageRule } from '../platform/pagecontext';
|
|
2
3
|
import type { AlertRule, Channel, ChatEntry, Client, Credential, ExecutorToken, ProjectReg, Route, StorageBucket, TargetDef, ToolApproval, ToolProvider, TraceSeverity, TraceStage } from '../contracts/types';
|
|
3
4
|
|
|
@@ -155,6 +156,7 @@ export function rowToolProvider(r: any): ToolProvider {
|
|
|
155
156
|
: undefined;
|
|
156
157
|
return {
|
|
157
158
|
name: r.name, base_url: r.base_url,
|
|
159
|
+
tool_rate_limits: r.tool_rate_limits_json ? normalizeToolRateLimitPolicies(parseOptionalJson(r.tool_rate_limits_json)) : undefined,
|
|
158
160
|
spec_source: specSource,
|
|
159
161
|
spec_access_policy: specAccessPolicy,
|
|
160
162
|
spec_url: r.spec_url ?? undefined, spec_json: r.spec_json ?? undefined,
|
|
@@ -189,7 +191,7 @@ export function rowCredential(r: any): Credential {
|
|
|
189
191
|
|
|
190
192
|
export function rowStorageBucket(r: any): StorageBucket {
|
|
191
193
|
return {
|
|
192
|
-
name: r.name, kind: (r.kind === 'oss' ? 'oss' : r.kind === 's3' ? 's3' : 'cos'),
|
|
194
|
+
name: r.name, kind: (r.kind === 'local' ? 'local' : r.kind === 'oss' ? 'oss' : r.kind === 's3' ? 's3' : 'cos'),
|
|
193
195
|
region: r.region ?? '', bucket: r.bucket, endpoint: r.endpoint ?? undefined,
|
|
194
196
|
access_key: r.access_key, secret_key: r.secret_key,
|
|
195
197
|
public_base_url: r.public_base_url ?? '', path_prefix: r.path_prefix ?? 'bailing/chat',
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { normalizeToolRateLimitPolicies } from '../contracts/tool-rate-limits';
|
|
1
2
|
import { randomUUID } from 'node:crypto';
|
|
2
3
|
import { validateBudgetPolicy } from '../runtime/budget-runtime';
|
|
3
4
|
import type { PageRule } from '../platform/pagecontext';
|
|
@@ -147,6 +148,7 @@ export function prepareStorageBucketConfig(input: Partial<StorageBucket>): Prepa
|
|
|
147
148
|
const publicBaseUrl = str(input.public_base_url).replace(/\/+$/, '');
|
|
148
149
|
if (kind !== 'local' && !publicBaseUrl) return fail('公开访问域名 public_base_url 必填(拼最终媒体 URL 用)');
|
|
149
150
|
const region = str(input.region);
|
|
151
|
+
if (kind === 'oss' && !region) return fail('OSS 必须填地域 region(如 cn-shanghai)');
|
|
150
152
|
if (kind === 'cos' && !region) return fail('COS 必须填地域 region(如 ap-shanghai)');
|
|
151
153
|
return {
|
|
152
154
|
ok: true,
|
|
@@ -372,6 +374,13 @@ export function prepareToolProviderConfig(
|
|
|
372
374
|
: requestedSpecAccessPolicy
|
|
373
375
|
? requestedSpecAccessPolicy as ToolProvider['spec_access_policy']
|
|
374
376
|
: old?.spec_source === 'url' ? oldSpecAccessPolicy : 'signed_required';
|
|
377
|
+
let toolRateLimits = old?.tool_rate_limits;
|
|
378
|
+
if (input.tool_rate_limits !== undefined) {
|
|
379
|
+
try { toolRateLimits = normalizeToolRateLimitPolicies(input.tool_rate_limits); }
|
|
380
|
+
catch (error) { return fail((error as Error).message); }
|
|
381
|
+
}
|
|
382
|
+
const providerLimit = Number(input.rate_limit_per_min ?? old?.rate_limit_per_min ?? 120);
|
|
383
|
+
if (!Number.isSafeInteger(providerLimit) || providerLimit < 0 || providerLimit > 1_000_000) return fail('工具源总限额需为 0–1000000 的整数,0=关闭');
|
|
375
384
|
const autoRefreshMin = Math.min(Math.max(Number(input.auto_refresh_min ?? old?.auto_refresh_min ?? 0) || 0, 0), 1440);
|
|
376
385
|
const enabled = input.enabled !== false;
|
|
377
386
|
|
|
@@ -423,7 +432,8 @@ export function prepareToolProviderConfig(
|
|
|
423
432
|
secret,
|
|
424
433
|
log_payload: input.log_payload !== false,
|
|
425
434
|
timeout_ms: Math.min(Math.max(Number(input.timeout_ms ?? old?.timeout_ms ?? 10000) || 10000, 1000), 60000),
|
|
426
|
-
rate_limit_per_min:
|
|
435
|
+
rate_limit_per_min: providerLimit,
|
|
436
|
+
tool_rate_limits: toolRateLimits,
|
|
427
437
|
auto_refresh_min: autoRefreshMin,
|
|
428
438
|
enabled,
|
|
429
439
|
description: optionalStr(input.description),
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { validateArtifactConfig } from './artifact-config';
|
|
1
2
|
import type { AgentSystemInfo, Route, SessionPolicy, TargetKind } from '../contracts/types';
|
|
2
3
|
import { validateRouteToolsConfig, type ToolProviderExists } from './tools-config';
|
|
3
4
|
import { normalizeTargetConfig, validateTargetConfig } from './target-config';
|
|
@@ -196,14 +197,14 @@ function validateAgentClientConfig(v: unknown): string | null {
|
|
|
196
197
|
if (v === undefined || v === null) return null;
|
|
197
198
|
const cfg = record(v);
|
|
198
199
|
if (!cfg) return 'agent_client 必须是对象';
|
|
199
|
-
const known = new Set(['enabled', 'instructions', 'active_tool_limit', 'system_info']);
|
|
200
|
+
const known = new Set(['enabled', 'instructions', 'active_tool_limit', 'system_info', 'artifact_upload']);
|
|
200
201
|
const unknown = Object.keys(cfg).filter((key) => !known.has(key));
|
|
201
202
|
if (unknown.length) return `agent_client 包含未声明字段: ${unknown.join(',')}`;
|
|
202
203
|
if (cfg.enabled !== undefined && typeof cfg.enabled !== 'boolean') return 'agent_client.enabled 必须是布尔值';
|
|
203
204
|
if (cfg.instructions !== undefined && (typeof cfg.instructions !== 'string' || cfg.instructions.length > 20_000)) {
|
|
204
205
|
return 'agent_client.instructions 必须是最长 20000 字符的字符串';
|
|
205
206
|
}
|
|
206
|
-
return (cfg.system_info === undefined ? null : validateAgentSystemInfo(cfg.system_info))
|
|
207
|
+
return validateArtifactConfig(cfg.artifact_upload) ?? (cfg.system_info === undefined ? null : validateAgentSystemInfo(cfg.system_info))
|
|
207
208
|
?? intInRange(cfg.active_tool_limit, 'agent_client.active_tool_limit', 1, 12);
|
|
208
209
|
}
|
|
209
210
|
|