bailinghub 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/README.en.md +6 -9
  2. package/README.md +6 -9
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
  5. package/docs/AGENT_CLIENT_RUNTIME_API.md +34 -0
  6. package/docs/AGENT_TASK_CONTROL.en.md +25 -0
  7. package/docs/AGENT_TASK_CONTROL.md +94 -0
  8. package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
  9. package/docs/CHANGELOG.en.md +11 -1
  10. package/docs/CHANGELOG.md +11 -1
  11. package/docs/COMPATIBILITY.en.md +2 -0
  12. package/docs/CONTRACT.en.md +2 -0
  13. package/docs/CONTRACT.md +2 -0
  14. package/docs/GENERATED_ARTIFACTS.en.md +46 -0
  15. package/docs/GENERATED_ARTIFACTS.md +108 -0
  16. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  17. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  18. package/docs/INVOCATION_RECEIPTS.md +111 -0
  19. package/docs/README.en.md +3 -0
  20. package/docs/README.md +3 -0
  21. package/docs/RELEASE_NOTES_NEXT.en.md +2 -2
  22. package/docs/RELEASE_NOTES_NEXT.md +2 -2
  23. package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
  24. package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
  25. package/docs/TOOL_RATE_LIMITS.md +50 -0
  26. package/docs/UPGRADE_v0.8.0.en.md +71 -0
  27. package/docs/UPGRADE_v0.8.0.md +73 -0
  28. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +2 -0
  29. package/package.json +1 -1
  30. package/schemas/config/route.schema.json +1 -0
  31. package/schemas/config/tool-provider.schema.json +2 -1
  32. package/scripts/check-doc-links.mjs +1 -0
  33. package/scripts/check-image-tags.sh +1 -1
  34. package/scripts/check-release-consistency.test.mjs +2 -2
  35. package/scripts/e2e-console.mjs +32 -2
  36. package/scripts/install.sh +1 -1
  37. package/scripts/publish-images.sh +1 -1
  38. package/scripts/release-audit.mjs +1 -0
  39. package/scripts/verify-github-repo.mjs +1 -0
  40. package/sql/060_agent_artifacts.sql +11 -0
  41. package/sql/061_tool_rate_limit_policies.sql +3 -0
  42. package/sql/062_agent_task_control.sql +92 -0
  43. package/src/adapters/storage/object-storage.ts +15 -3
  44. package/src/adapters/storage/oss-signature.test.ts +40 -0
  45. package/src/adapters/storage/oss-signature.ts +21 -0
  46. package/src/app/agent-artifacts.test.ts +165 -0
  47. package/src/app/agent-artifacts.ts +85 -0
  48. package/src/app/agent-client-runtime.test.ts +76 -1
  49. package/src/app/agent-client-runtime.ts +13 -0
  50. package/src/app/agent-invocation-snapshot.ts +35 -0
  51. package/src/app/agent-task-control.ts +187 -0
  52. package/src/app/agent-task-runtime.ts +68 -0
  53. package/src/app/agent-tool-invocations.test.ts +329 -1
  54. package/src/app/agent-tool-invocations.ts +223 -10
  55. package/src/app/agent-tool-job.test.ts +11 -1
  56. package/src/app/agent-tool-job.ts +8 -1
  57. package/src/app/builtin-tools.ts +4 -0
  58. package/src/app/oss-edition.ts +1 -0
  59. package/src/app/tool-approvals.ts +4 -0
  60. package/src/app/tool-assembly.ts +5 -0
  61. package/src/core/config/artifact-config.ts +15 -0
  62. package/src/core/config/config-codec.ts +3 -1
  63. package/src/core/config/config-models.ts +11 -1
  64. package/src/core/config/route-config.ts +3 -2
  65. package/src/core/contracts/tool-rate-limits.test.ts +59 -0
  66. package/src/core/contracts/tool-rate-limits.ts +48 -0
  67. package/src/core/contracts/tools.ts +122 -43
  68. package/src/core/contracts/types.ts +3 -1
  69. package/src/core/runtime/agent-task-control.test.ts +114 -0
  70. package/src/core/runtime/agent-task-control.ts +227 -0
  71. package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -0
  72. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +7 -1
  73. package/src/infrastructure/config/config-agent-task-control-journal-mysql.test.ts +315 -0
  74. package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
  75. package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
  76. package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
  77. package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -0
  78. package/src/infrastructure/config/config-storage-bucket-repository.ts +2 -2
  79. package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
  80. package/src/infrastructure/config/configstore.ts +9 -1
  81. package/src/routes/admin-agent-tasks.ts +32 -0
  82. package/src/routes/admin-tool-providers.test.ts +22 -0
  83. package/src/routes/admin-tool-providers.ts +9 -1
  84. package/src/routes/admin.ts +3 -0
  85. package/src/routes/agent-api.test.ts +76 -0
  86. package/src/routes/agent-api.ts +42 -1
  87. package/src/routes/agent-artifacts.ts +29 -0
  88. package/src/routes/agent-task-control-http-mysql.test.ts +246 -0
  89. package/src/routes/private.ts +1 -0
  90. package/src/routes/run.ts +2 -1
  91. package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
  92. package/web/console/assets/{Accounts-ChL9k-XA.js → Accounts-BRCR3O0P.js} +1 -1
  93. package/web/console/assets/AgentClients-Bf7sUUs_.js +1 -0
  94. package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
  95. package/web/console/assets/AgentTasks--bqL_QKg.js +2 -0
  96. package/web/console/assets/AgentTasks-C8ox3TyS.css +1 -0
  97. package/web/console/assets/{Approvals-Bs6FGbp2.js → Approvals-BIbZvInm.js} +1 -1
  98. package/web/console/assets/{Audit-4WWYhkFM.js → Audit-KyPSmBdZ.js} +1 -1
  99. package/web/console/assets/{BrandLockup-D2GhCipL.js → BrandLockup-Sv5DU2G6.js} +1 -1
  100. package/web/console/assets/{Channels-CmoGpiCJ.js → Channels-B9n4fbxg.js} +1 -1
  101. package/web/console/assets/{ChatEntries-BFRMtwta.js → ChatEntries-xsOCUXi_.js} +1 -1
  102. package/web/console/assets/{Clients-DGkkSXyA.js → Clients-CI3DBDHf.js} +1 -1
  103. package/web/console/assets/{Cost-BmGt0MfS.js → Cost-JgNXQPlN.js} +1 -1
  104. package/web/console/assets/{Credentials-CR-sYINT.js → Credentials-B5UUUdt0.js} +1 -1
  105. package/web/console/assets/{Diagnostics-DAPbKSJp.js → Diagnostics-BMGciWQb.js} +1 -1
  106. package/web/console/assets/{Executors-CgpiT3o8.js → Executors-CRbboOCZ.js} +1 -1
  107. package/web/console/assets/{Kb-Cm9dVSQw.js → Kb-CgLNGjRp.js} +1 -1
  108. package/web/console/assets/{Login-CyUcsTZ_.js → Login-C52JmXzx.js} +1 -1
  109. package/web/console/assets/{Projects-DldFPgWg.js → Projects-CDOvHPVS.js} +1 -1
  110. package/web/console/assets/{Routes-DubfjlBD.js → Routes-X9vHLpKW.js} +1 -1
  111. package/web/console/assets/{Runs-1hxgkuR4.js → Runs-DYNDXsqk.js} +1 -1
  112. package/web/console/assets/{Setup-DBLOnI2_.js → Setup-B91P6i1x.js} +1 -1
  113. package/web/console/assets/Shell-Bj6C8Hgo.css +1 -0
  114. package/web/console/assets/Shell-BsRa7bQQ.js +1 -0
  115. package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
  116. package/web/console/assets/StorageBuckets-DkuDM0oX.js +1 -0
  117. package/web/console/assets/{SystemSettings-cDkudo2y.js → SystemSettings-B7Mqj3k1.js} +1 -1
  118. package/web/console/assets/{SystemStatus-DZd6s8OX.js → SystemStatus-Db93b6dc.js} +1 -1
  119. package/web/console/assets/{Targets-DYNGq1NU.js → Targets-CuuIYeZO.js} +1 -1
  120. package/web/console/assets/Tools-CHiqz9XZ.js +2 -0
  121. package/web/console/assets/Tools-DU8ei6sd.css +1 -0
  122. package/web/console/assets/index-UGvfF3Xr.js +2 -0
  123. package/web/console/assets/{request-B7MLvOqo.js → request-DeGya810.js} +1 -1
  124. package/web/console/assets/{schema-CMuwjYdJ.js → schema-BqlqLw1R.js} +1 -1
  125. package/web/console/index.html +1 -1
  126. package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
  127. package/web-admin/src/components/AgentSetupPanel.vue +13 -0
  128. package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
  129. package/web-admin/src/layout/Shell.vue +1 -1
  130. package/web-admin/src/pages/AgentClients.vue +3 -1
  131. package/web-admin/src/pages/AgentTasks.vue +281 -0
  132. package/web-admin/src/pages/StorageBuckets.vue +6 -6
  133. package/web-admin/src/pages/Tools.vue +53 -4
  134. package/web-admin/src/router.ts +2 -0
  135. package/web/console/assets/AgentClients-Bs7UgVDj.js +0 -1
  136. package/web/console/assets/AgentClients-DkgPTEbq.css +0 -1
  137. package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
  138. package/web/console/assets/Shell-gJ5Vz_E7.js +0 -1
  139. package/web/console/assets/StorageBuckets-DkDW16tj.js +0 -1
  140. package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
  141. package/web/console/assets/Tools-A20oaMaQ.css +0 -1
  142. package/web/console/assets/Tools-DpWM59vV.js +0 -2
  143. 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
- AGENT_TOOL_JOB_SOURCE_PREFIX,
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: `${AGENT_TOOL_JOB_SOURCE_PREFIX}${auth.client.app_id}`,
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: ordered.slice(0, limit),
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: `${AGENT_TOOL_JOB_SOURCE_PREFIX}${auth.client.app_id}`,
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
- await deps.stateStore.updateJob(job.job_id, { status: 'done', result: { ...result }, error: undefined });
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).catch(() => null);
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
@@ -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') {
@@ -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',
@@ -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);
@@ -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: Math.max(Number(input.rate_limit_per_min ?? old?.rate_limit_per_min ?? 120) || 0, 0),
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