bailinghub 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/README.en.md +8 -7
  2. package/README.md +7 -7
  3. package/docker-compose.images.yml +2 -2
  4. package/docs/AGENT_AUTH_API.en.md +112 -1
  5. package/docs/AGENT_AUTH_API.md +99 -1
  6. package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
  7. package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
  8. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +46 -0
  9. package/docs/AGENT_CLIENT_RUNTIME_API.md +38 -1
  10. package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
  11. package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
  12. package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
  13. package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
  14. package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
  15. package/docs/AGENT_SYSTEM_INFO.md +97 -0
  16. package/docs/AGENT_TASK_CONTROL.en.md +25 -0
  17. package/docs/AGENT_TASK_CONTROL.md +94 -0
  18. package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
  19. package/docs/CHANGELOG.en.md +24 -1
  20. package/docs/CHANGELOG.md +24 -1
  21. package/docs/COMPATIBILITY.en.md +2 -0
  22. package/docs/CONTRACT.en.md +2 -0
  23. package/docs/CONTRACT.md +2 -0
  24. package/docs/GENERATED_ARTIFACTS.en.md +46 -0
  25. package/docs/GENERATED_ARTIFACTS.md +108 -0
  26. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  27. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  28. package/docs/INVOCATION_RECEIPTS.md +111 -0
  29. package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
  30. package/docs/LOCAL_AGENT_SETUP.md +116 -0
  31. package/docs/README.en.md +9 -0
  32. package/docs/README.md +9 -0
  33. package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
  34. package/docs/RELEASE_NOTES_NEXT.md +3 -0
  35. package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
  36. package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
  37. package/docs/RELEASE_NOTES_v0.8.0.en.md +40 -0
  38. package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
  39. package/docs/SDK.en.md +31 -0
  40. package/docs/TOOL_RATE_LIMITS.md +50 -0
  41. package/docs/UPGRADE_v0.8.0.en.md +71 -0
  42. package/docs/UPGRADE_v0.8.0.md +73 -0
  43. package/docs/user-guide/conversations.en.md +4 -2
  44. package/docs/user-guide/conversations.md +4 -2
  45. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +2 -0
  46. package/package.json +1 -1
  47. package/schemas/config/route.schema.json +16 -2
  48. package/schemas/config/tool-provider.schema.json +2 -1
  49. package/scripts/check-doc-links.mjs +2 -0
  50. package/scripts/check-image-tags.sh +1 -1
  51. package/scripts/check-release-consistency.test.mjs +2 -2
  52. package/scripts/e2e-console.mjs +32 -2
  53. package/scripts/install.sh +1 -1
  54. package/scripts/publish-images.sh +1 -1
  55. package/scripts/release-audit.mjs +2 -0
  56. package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
  57. package/scripts/sdk-runtime-test.mjs +5 -2
  58. package/scripts/verify-github-repo.mjs +2 -0
  59. package/sdk/php/README.md +29 -0
  60. package/sdk/php/src/AgentAuth.php +100 -4
  61. package/sdk/php/src/HubClient.php +2 -1
  62. package/sdk/php7/README.md +31 -0
  63. package/sdk/php7/src/AgentAuth.php +99 -4
  64. package/sdk/php7/src/HubClient.php +2 -1
  65. package/sql/058_agent_conversation_member_bindings.sql +9 -0
  66. package/sql/059_agent_subject_display.sql +5 -0
  67. package/sql/060_agent_artifacts.sql +11 -0
  68. package/sql/061_tool_rate_limit_policies.sql +3 -0
  69. package/sql/062_agent_task_control.sql +92 -0
  70. package/sql/README.en.md +15 -0
  71. package/sql/README.md +25 -0
  72. package/src/adapters/storage/object-storage.ts +15 -3
  73. package/src/adapters/storage/oss-signature.test.ts +40 -0
  74. package/src/adapters/storage/oss-signature.ts +21 -0
  75. package/src/app/agent-artifacts.test.ts +165 -0
  76. package/src/app/agent-artifacts.ts +85 -0
  77. package/src/app/agent-client-runtime.test.ts +76 -1
  78. package/src/app/agent-client-runtime.ts +13 -0
  79. package/src/app/agent-conversation-audit.ts +20 -0
  80. package/src/app/agent-invocation-snapshot.ts +35 -0
  81. package/src/app/agent-system-info.ts +41 -0
  82. package/src/app/agent-task-control.ts +187 -0
  83. package/src/app/agent-task-runtime.ts +68 -0
  84. package/src/app/agent-tool-invocations.test.ts +329 -1
  85. package/src/app/agent-tool-invocations.ts +239 -14
  86. package/src/app/agent-tool-job.test.ts +11 -1
  87. package/src/app/agent-tool-job.ts +8 -1
  88. package/src/app/builtin-tools.ts +4 -0
  89. package/src/app/oss-edition.ts +1 -0
  90. package/src/app/tool-approvals.ts +4 -0
  91. package/src/app/tool-assembly.ts +5 -0
  92. package/src/core/config/agent-setup.ts +37 -0
  93. package/src/core/config/artifact-config.ts +15 -0
  94. package/src/core/config/client-agent-setup.ts +25 -0
  95. package/src/core/config/config-codec.ts +3 -1
  96. package/src/core/config/config-models.ts +11 -1
  97. package/src/core/config/config-schema.test.ts +11 -0
  98. package/src/core/config/route-config.test.ts +28 -0
  99. package/src/core/config/route-config.ts +44 -4
  100. package/src/core/contracts/agent-subject-display.test.ts +19 -0
  101. package/src/core/contracts/agent-subject-display.ts +36 -0
  102. package/src/core/contracts/tool-rate-limits.test.ts +59 -0
  103. package/src/core/contracts/tool-rate-limits.ts +48 -0
  104. package/src/core/contracts/tools.ts +122 -43
  105. package/src/core/contracts/types.ts +18 -1
  106. package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
  107. package/src/core/runtime/agent-conversation-audit.ts +39 -0
  108. package/src/core/runtime/agent-task-control.test.ts +114 -0
  109. package/src/core/runtime/agent-task-control.ts +227 -0
  110. package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -0
  111. package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
  112. package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
  113. package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
  114. package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
  115. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +7 -1
  116. package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
  117. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
  118. package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
  119. package/src/infrastructure/config/config-agent-task-control-journal-mysql.test.ts +315 -0
  120. package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
  121. package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
  122. package/src/infrastructure/config/config-client-repository.ts +21 -0
  123. package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
  124. package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -0
  125. package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
  126. package/src/infrastructure/config/config-route-repository.ts +24 -0
  127. package/src/infrastructure/config/config-storage-bucket-repository.ts +2 -2
  128. package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
  129. package/src/infrastructure/config/configstore.ts +16 -4
  130. package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
  131. package/src/routes/admin-access.ts +37 -0
  132. package/src/routes/admin-agent-clients.ts +11 -0
  133. package/src/routes/admin-agent-setup.test.ts +130 -0
  134. package/src/routes/admin-agent-setup.ts +68 -0
  135. package/src/routes/admin-agent-tasks.ts +32 -0
  136. package/src/routes/admin-client-agent-setup.test.ts +93 -0
  137. package/src/routes/admin-dispatch-config.ts +2 -0
  138. package/src/routes/admin-tool-providers.test.ts +22 -0
  139. package/src/routes/admin-tool-providers.ts +9 -1
  140. package/src/routes/admin.ts +3 -0
  141. package/src/routes/agent-api.test.ts +76 -0
  142. package/src/routes/agent-api.ts +49 -1
  143. package/src/routes/agent-artifacts.ts +29 -0
  144. package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
  145. package/src/routes/agent-auth-lifecycle.test.ts +193 -0
  146. package/src/routes/agent-auth.test.ts +1 -1
  147. package/src/routes/agent-auth.ts +206 -16
  148. package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
  149. package/src/routes/agent-conversation-audit.ts +8 -2
  150. package/src/routes/agent-subject-display-http.test.ts +145 -0
  151. package/src/routes/agent-system-info.test.ts +132 -0
  152. package/src/routes/agent-task-control-http-mysql.test.ts +246 -0
  153. package/src/routes/private.ts +1 -0
  154. package/src/routes/run.ts +2 -1
  155. package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
  156. package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
  157. package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
  158. package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
  159. package/src/test-support/agent-task-control-mysql-fixture.ts +75 -0
  160. package/web/connect/bailing-connect-php.tgz +0 -0
  161. package/web/connect/bailing-connect-php7.tgz +0 -0
  162. package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-BRCR3O0P.js} +1 -1
  163. package/web/console/assets/AgentClients-Bf7sUUs_.js +1 -0
  164. package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
  165. package/web/console/assets/AgentTasks--bqL_QKg.js +2 -0
  166. package/web/console/assets/AgentTasks-C8ox3TyS.css +1 -0
  167. package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-BIbZvInm.js} +1 -1
  168. package/web/console/assets/{Audit-CIRqOCnL.js → Audit-KyPSmBdZ.js} +1 -1
  169. package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-Sv5DU2G6.js} +1 -1
  170. package/web/console/assets/{Channels-CApxH2TB.js → Channels-B9n4fbxg.js} +1 -1
  171. package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-xsOCUXi_.js} +1 -1
  172. package/web/console/assets/Clients-CI3DBDHf.js +3 -0
  173. package/web/console/assets/Clients-CSHIsaWU.css +1 -0
  174. package/web/console/assets/{Cost-BbhlQFP8.js → Cost-JgNXQPlN.js} +1 -1
  175. package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-B5UUUdt0.js} +1 -1
  176. package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-BMGciWQb.js} +1 -1
  177. package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CRbboOCZ.js} +1 -1
  178. package/web/console/assets/{Kb-DLZSAFWP.js → Kb-CgLNGjRp.js} +1 -1
  179. package/web/console/assets/{Login-DiTjPWmN.js → Login-C52JmXzx.js} +1 -1
  180. package/web/console/assets/{Projects-CXcVCgCD.js → Projects-CDOvHPVS.js} +1 -1
  181. package/web/console/assets/Routes-DkMIjMQA.css +1 -0
  182. package/web/console/assets/Routes-X9vHLpKW.js +124 -0
  183. package/web/console/assets/Runs-CvGTV8I-.css +1 -0
  184. package/web/console/assets/Runs-DYNDXsqk.js +3 -0
  185. package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-B91P6i1x.js} +1 -1
  186. package/web/console/assets/Shell-Bj6C8Hgo.css +1 -0
  187. package/web/console/assets/Shell-BsRa7bQQ.js +1 -0
  188. package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
  189. package/web/console/assets/StorageBuckets-DkuDM0oX.js +1 -0
  190. package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-B7Mqj3k1.js} +1 -1
  191. package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-Db93b6dc.js} +1 -1
  192. package/web/console/assets/{Targets-CZmDcjsE.js → Targets-CuuIYeZO.js} +1 -1
  193. package/web/console/assets/Tools-CHiqz9XZ.js +2 -0
  194. package/web/console/assets/Tools-DU8ei6sd.css +1 -0
  195. package/web/console/assets/index-UGvfF3Xr.js +2 -0
  196. package/web/console/assets/{request-r7GHVJzw.js → request-DeGya810.js} +1 -1
  197. package/web/console/assets/{schema-BVn_hB7M.js → schema-BqlqLw1R.js} +1 -1
  198. package/web/console/index.html +1 -1
  199. package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
  200. package/web-admin/scripts/subject-display-ui.mjs +78 -0
  201. package/web-admin/src/components/AgentSetupPanel.vue +275 -0
  202. package/web-admin/src/components/ClientConversations.vue +21 -4
  203. package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
  204. package/web-admin/src/components/conversation-audit.ts +20 -0
  205. package/web-admin/src/layout/Shell.vue +1 -1
  206. package/web-admin/src/pages/AgentClients.vue +99 -23
  207. package/web-admin/src/pages/AgentTasks.vue +281 -0
  208. package/web-admin/src/pages/Clients.vue +4 -1
  209. package/web-admin/src/pages/Routes.vue +10 -1
  210. package/web-admin/src/pages/StorageBuckets.vue +6 -6
  211. package/web-admin/src/pages/Tools.vue +53 -4
  212. package/web-admin/src/router.ts +2 -0
  213. package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
  214. package/web-admin/tests/conversation-audit.test.mjs +63 -1
  215. package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
  216. package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
  217. package/web/console/assets/Clients-BSA1rlTB.js +0 -3
  218. package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
  219. package/web/console/assets/Routes-CXGl9SMM.css +0 -1
  220. package/web/console/assets/Routes-DN9_d9Po.js +0 -124
  221. package/web/console/assets/Runs-Cwbe6thL.js +0 -3
  222. package/web/console/assets/Runs-D8UmjP5G.css +0 -1
  223. package/web/console/assets/Shell-BEqpONiy.js +0 -1
  224. package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
  225. package/web/console/assets/StorageBuckets-CkORbYXY.js +0 -1
  226. package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
  227. package/web/console/assets/Tools-A20oaMaQ.css +0 -1
  228. package/web/console/assets/Tools-CIHInlHL.js +0 -2
  229. package/web/console/assets/index-BkLbd7Cc.js +0 -2
@@ -0,0 +1,132 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { Readable } from 'node:stream';
4
+ import type { IncomingMessage, ServerResponse } from 'node:http';
5
+ import type { AgentSession, Client, Route } from '../core/contracts/types';
6
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
7
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
8
+ import type { ToolProxyDeps } from '../app/tool-proxy';
9
+ import { AgentToolApiError, listAgentToolsFor } from '../app/agent-tool-invocations';
10
+ import { handleAgentApiHttpFor } from './agent-api';
11
+
12
+ class Response {
13
+ statusCode = 0;
14
+ headers: Record<string, unknown> = {};
15
+ body = '';
16
+ setHeader(name: string, value: unknown) { this.headers[name] = value; }
17
+ writeHead(code: number, headers: Record<string, unknown> = {}) { this.statusCode = code; Object.assign(this.headers, headers); }
18
+ end(value = '') { this.body = String(value); }
19
+ json() { return JSON.parse(this.body); }
20
+ }
21
+
22
+ function fixture() {
23
+ const token = `bha_${'s'.repeat(43)}`;
24
+ const client: Client = {
25
+ app_id: 'helpdesk-client', name: 'Helpdesk Client', token: 'not-returned', enabled: true,
26
+ agent_authorize_url: 'https://helpdesk.example.com/authorize', allowed_routes: ['helpdesk'], allowed_channels: [], rate_limit_per_min: 0,
27
+ };
28
+ const session: AgentSession = {
29
+ session_id: '123e4567-e89b-42d3-a456-426614174000', client_app_id: client.app_id, device_label: 'Untrusted account label',
30
+ principal: { id: 'operator-1', tenant: 'tenant-a', roles: ['staff'] }, on_behalf_of: 'tenant-a:operator-1', allowed_routes: ['helpdesk'],
31
+ created_at: '2026-01-01T00:00:00.000Z', access_expires_at: '2099-01-01T00:00:00.000Z', refresh_expires_at: '2099-01-30T00:00:00.000Z',
32
+ };
33
+ const route: Route = {
34
+ route_key: 'helpdesk', name: 'Internal routing label', enabled: true, target: 'llm', target_config: { system_prompt: 'hidden rules', credential: 'hidden-credential' },
35
+ profile: 'general', session_policy: 'new', audience: { enabled: true, roles: ['staff'], clients: ['helpdesk-client'] },
36
+ agent_client: { enabled: true, instructions: 'hidden local rules', system_info: {
37
+ name: 'Helpdesk', summary: 'Manages customer support tickets.', domains: ['Ticket triage'], boundaries: ['Inventory changes belong to another system.'],
38
+ } },
39
+ tools: { sources: [{ provider: 'helpdesk-tools', allow: ['*'] }], agent_direct: { enabled: true } },
40
+ memory: { recent_messages: 12 }, knowledge: { kb_id: 'hidden-knowledge' },
41
+ };
42
+ let active = true;
43
+ const reads: string[] = [];
44
+ const unexpected = new Proxy({}, { get: (_object, property) => { throw new Error(`Unexpected service access: ${String(property)}`); } });
45
+ const configStore = {
46
+ agentAuth: { getSessionByAccessHash: async () => active ? session : null },
47
+ clients: { get: async () => client },
48
+ routes: { get: async (key: string) => { reads.push(key); return key === route.route_key ? route : null; }, list: () => { throw new Error('Must not enumerate routes'); } },
49
+ toolProviders: unexpected, conversations: unexpected, agentClientRuntime: unexpected,
50
+ } as unknown as ConfigStoreContract;
51
+ async function get(workspace = 'helpdesk', bearer = token) {
52
+ let bodyReads = 0;
53
+ const req = new Readable({ read() { bodyReads++; this.push(null); } }) as IncomingMessage;
54
+ req.method = 'GET'; req.headers = { authorization: `Bearer ${bearer}` };
55
+ const res = new Response();
56
+ await handleAgentApiHttpFor({
57
+ configStore, stateStore: unexpected as RuntimeStateStore, isPaused: () => false,
58
+ handleRun: async () => { throw new Error('Must not start run'); },
59
+ // Deliberately no toolProxyDeps: product descriptions do not load a tool runtime.
60
+ }, req, res as unknown as ServerResponse, new URL(`https://hub.example.com/agent-api/v1/workspaces/${workspace}/system-info`));
61
+ assert.equal(bodyReads, 0);
62
+ return res;
63
+ }
64
+ return { route, client, session, configStore, reads, get, revoke: () => { active = false; } };
65
+ }
66
+
67
+ test('system-info reads only the selected binding before tools, body or business runs', async () => {
68
+ const f = fixture();
69
+ const res = await f.get();
70
+ assert.equal(res.statusCode, 200);
71
+ assert.equal(res.headers['cache-control'], 'no-store');
72
+ assert.deepEqual(res.json(), {
73
+ schema_version: 'bailing.agent-system-info.v1',
74
+ binding: { client_app_id: f.client.app_id, session_id: f.session.session_id, workspace: 'helpdesk' },
75
+ metadata_status: 'configured', revision: res.json().revision, system: f.route.agent_client!.system_info,
76
+ tool_status: 'not_loaded', availability: 'unknown',
77
+ });
78
+ assert.match(res.json().revision, /^[a-f0-9]{64}$/);
79
+ assert.deepEqual(f.reads, ['helpdesk']);
80
+ assert.doesNotMatch(res.body, /not-returned|hidden|Untrusted account label|Internal routing label/);
81
+ const same = await f.get();
82
+ assert.equal(same.json().revision, res.json().revision);
83
+ f.route.agent_client!.system_info!.summary = 'Supports ticket review and response drafts.';
84
+ assert.notEqual((await f.get()).json().revision, res.json().revision);
85
+ });
86
+
87
+ test('system-info remains readable with runtime/direct switches off, without enabling tools', async () => {
88
+ const f = fixture();
89
+ f.route.agent_client!.enabled = false;
90
+ let response = await f.get();
91
+ assert.equal(response.statusCode, 200);
92
+ assert.equal(response.json().metadata_status, 'configured');
93
+ assert.equal(response.json().unavailable_reason, 'agent_client_disabled');
94
+ f.route.agent_client!.enabled = true;
95
+ f.route.tools!.agent_direct = { enabled: false };
96
+ response = await f.get();
97
+ assert.equal(response.json().availability, 'unavailable');
98
+ assert.equal(response.json().unavailable_reason, 'agent_direct_disabled');
99
+ await assert.rejects(listAgentToolsFor({ configStore: f.configStore } as ToolProxyDeps, f, 'helpdesk'),
100
+ (error) => error instanceof AgentToolApiError && error.code === 'agent_direct_disabled');
101
+ });
102
+
103
+ test('system-info missing or malformed metadata stays unknown rather than inventing identity', async () => {
104
+ const f = fixture();
105
+ delete f.route.agent_client!.system_info;
106
+ const res = await f.get();
107
+ assert.equal(res.statusCode, 200);
108
+ assert.equal(res.json().metadata_status, 'missing');
109
+ assert.equal(res.json().system, null);
110
+ assert.equal(res.json().revision, null);
111
+ f.route.agent_client!.system_info = { name: 'Helpdesk', summary: '', domains: [], boundaries: [] };
112
+ assert.equal((await f.get()).json().metadata_status, 'missing');
113
+ });
114
+
115
+ test('system-info rejects unselected routes and wrong Client/Session/audience without metadata', async () => {
116
+ for (const mutation of ['client-route', 'session-route', 'client-binding', 'audience', 'revoked', 'disabled-route'] as const) {
117
+ const f = fixture();
118
+ if (mutation === 'client-route') f.client.allowed_routes = [];
119
+ if (mutation === 'session-route') f.session.allowed_routes = [];
120
+ if (mutation === 'client-binding') f.client.app_id = 'another-client';
121
+ if (mutation === 'audience') f.session.principal.roles = [];
122
+ if (mutation === 'revoked') f.revoke();
123
+ if (mutation === 'disabled-route') f.route.enabled = false;
124
+ const res = await f.get();
125
+ assert.equal(res.statusCode, mutation === 'revoked' ? 401 : mutation === 'disabled-route' ? 404 : 403, mutation);
126
+ assert.doesNotMatch(res.body, /Manages customer|Ticket triage/);
127
+ }
128
+ const f = fixture();
129
+ const res = await f.get('inventory');
130
+ assert.equal(res.statusCode, 403);
131
+ assert.deepEqual(f.reads, []);
132
+ });
@@ -0,0 +1,246 @@
1
+ import assert from 'node:assert/strict';
2
+ import { randomBytes, randomUUID } from 'node:crypto';
3
+ import { createServer, type Server } from 'node:http';
4
+ import test from 'node:test';
5
+ import type { AppConfig } from '../core/config/config';
6
+ import type { Principal } from '../app/auth';
7
+ import { send } from '../app/http';
8
+ import { ConfigStore } from '../infrastructure/config/configstore';
9
+ import { MysqlStore } from '../infrastructure/state/state-mysql';
10
+ import type { ToolProxyDeps } from '../app/tool-proxy';
11
+ import { handleAgentApiHttpFor } from './agent-api';
12
+ import { handleAdminAgentTasksApiFor } from './admin-agent-tasks';
13
+ import { tokenHash } from './agent-auth';
14
+ import { openTaskMysqlFixture, seedTaskMysqlMembers, taskMysqlConfigPath } from '../test-support/agent-task-control-mysql-fixture';
15
+
16
+ const listen = (server: Server) => new Promise<string>((resolve) => server.listen(0, '127.0.0.1', () => {
17
+ const address = server.address(); assert.ok(address && typeof address === 'object'); resolve(`http://127.0.0.1:${address.port}`);
18
+ }));
19
+ const close = (server: Server) => new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
20
+ const id = () => randomBytes(32).toString('hex');
21
+ const tools = ['product_update', 'inventory_read', 'product_review'];
22
+ function spec() {
23
+ const operation = (name: string, write: boolean, approval: boolean) => ({
24
+ operationId: name, summary: name,
25
+ 'x-agent-capability': { version: 1, enabled: true, scope: write ? 'products.write' : 'inventory.read', subject: { required: true },
26
+ ...(approval ? { risk: { level: 'high' } } : {}) },
27
+ ...(write ? { requestBody: { content: { 'application/json': { schema: { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'], additionalProperties: false } } } } }
28
+ : { parameters: [{ name: 'id', in: 'query', schema: { type: 'integer' } }] }),
29
+ });
30
+ return JSON.stringify({ openapi: '3.0.0', info: { title: 'Example shop and inventory', version: '1' }, paths: {
31
+ '/product': { post: operation('product_update', true, false) },
32
+ '/inventory': { get: operation('inventory_read', false, false) },
33
+ '/review': { post: operation('product_review', true, true) },
34
+ } });
35
+ }
36
+
37
+ test('task control gates real HTTP dispatch through the persisted Core runtime', { skip: !taskMysqlConfigPath }, async (t) => {
38
+ const pool = await openTaskMysqlFixture();
39
+ const owner = { get: async () => pool, close: async () => undefined };
40
+ const config = new ConfigStore({} as AppConfig['state']['mysql'], owner);
41
+ const state = new MysqlStore({} as AppConfig['state']['mysql'], owner);
42
+ await config.init(); await state.init();
43
+ const requests: Array<{ url: string; subject: string }> = [];
44
+ let dropResponse = false;
45
+ let holdBusinessResponse: Promise<void> | null = null;
46
+ let dropCoreAck = false;
47
+ const business = createServer(async (req, res) => {
48
+ requests.push({ url: req.url ?? '', subject: String(req.headers['x-agent-on-behalf-of'] ?? '') });
49
+ if (dropResponse) { req.socket.destroy(); return; }
50
+ if (holdBusinessResponse) await holdBusinessResponse;
51
+ send(res, 200, { ok: true, synthetic: true });
52
+ });
53
+ const businessUrl = await listen(business);
54
+ const cfg = { brand: { name: 'BailingHub' }, server: { token: 'synthetic-test-server-secret' } } as AppConfig;
55
+ const toolProxyDeps: ToolProxyDeps = { cfg, configStore: config, stateStore: state, toolIndex: null,
56
+ now: () => new Date().toISOString(), sleep: async () => undefined };
57
+ let legacyRuns = 0;
58
+ const core = createServer(async (req, res) => {
59
+ try {
60
+ const url = new URL(req.url!, 'http://127.0.0.1');
61
+ if (dropCoreAck && url.pathname === '/agent-api/v1/tool-invocations' && req.method === 'POST') {
62
+ dropCoreAck = false;
63
+ res.end = (() => { res.destroy(); return res; }) as typeof res.end;
64
+ }
65
+ if (url.pathname.startsWith('/admin/')) {
66
+ const principal: Principal = req.headers.authorization === 'Bearer synthetic-admin'
67
+ ? { kind: 'admin', via: 'token' } : { kind: 'admin', via: 'session', role: 'viewer' };
68
+ if (await handleAdminAgentTasksApiFor(config, req.method!, url.pathname, req, res, principal)) return;
69
+ }
70
+ if (await handleAgentApiHttpFor({ configStore: config, stateStore: state, isPaused: () => false, toolProxyDeps,
71
+ handleRun: async (_req, result) => { legacyRuns++; send(result, 200, {}); } }, req, res, url)) return;
72
+ send(res, 404, { error: 'not_found' });
73
+ } catch (error) { send(res, 500, { error: error instanceof Error ? error.message : 'test_server_error' }); }
74
+ });
75
+ const coreUrl = await listen(core);
76
+ const request = async (path: string, bearer: string, body?: unknown) => {
77
+ const response = await fetch(`${coreUrl}${path}`, { method: body === undefined ? 'GET' : 'POST',
78
+ headers: { authorization: `Bearer ${bearer}`, 'content-type': 'application/json' }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
79
+ return { status: response.status, body: await response.json() as any };
80
+ };
81
+ const setup = async (maxWrites: number | null = 2, longClientId = false) => {
82
+ const members = await seedTaskMysqlMembers(pool);
83
+ const bearers: string[] = [];
84
+ for (const member of members) {
85
+ if (longClientId) {
86
+ const fullId = `business-${id()}`.slice(0, 64);
87
+ await pool.query('UPDATE bz_clients SET app_id=? WHERE app_id=?', [fullId, member.clientAppId]);
88
+ await pool.query('UPDATE bz_agent_sessions SET client_app_id=? WHERE session_id=?', [fullId, member.sessionId]);
89
+ await pool.query('UPDATE bz_agent_client_runs SET client_app_id=? WHERE run_id=?', [fullId, member.runId]);
90
+ member.clientAppId = fullId;
91
+ }
92
+ const bearer = `bha_${randomBytes(32).toString('base64url')}`; bearers.push(bearer);
93
+ await pool.query('UPDATE bz_agent_sessions SET access_token_hash=? WHERE session_id=?', [tokenHash(bearer), member.sessionId]);
94
+ await config.toolProviders.upsert({ name: member.clientAppId, base_url: businessUrl, secret: 'synthetic-provider-secret',
95
+ enabled: true, spec_source: 'inline', spec_json: spec(), log_payload: false, timeout_ms: 1000, rate_limit_per_min: 0, auto_refresh_min: 0 });
96
+ const route = (await config.routes.get(member.route))!;
97
+ await config.routes.upsert({ ...route, permission: 'full', audience: { enabled: true, roles: ['manager'], clients: [member.clientAppId] },
98
+ tools: { sources: [{ provider: member.clientAppId, allow: ['products.write', 'inventory.read'] }], max_calls: 12,
99
+ agent_direct: { enabled: true, write_tools: ['product_update', 'product_review'] } }, agent_client: { enabled: true } });
100
+ }
101
+ const body = { request_id: randomUUID(), members: members.map((m) => ({ session_id: m.sessionId, client_app_id: m.clientAppId,
102
+ workspace: m.route, client_conversation_id: m.clientConversationId, allowed_tools: tools })),
103
+ policy: { max_write_calls: maxWrites, max_concurrent: 2, expires_at: null } };
104
+ const created = await request('/admin/api/agent-tasks', 'synthetic-admin', body);
105
+ assert.equal(created.status, 200, JSON.stringify(created.body));
106
+ const task = created.body;
107
+ const binding = { schema_version: 'bailing.agent-task-binding.v1', task_id: task.task_id, scope_hash: task.scope_hash };
108
+ const turnBody = (index = 0) => ({ client_conversation_id: members[index]!.clientConversationId, client_turn_id: randomUUID(),
109
+ user_message_id: randomUUID(), user_input: 'synthetic product task', task_binding: binding });
110
+ const turn = async (index = 0) => {
111
+ const result = await request(`/agent-api/v1/workspaces/${members[index]!.route}/turns`, bearers[index]!, turnBody(index));
112
+ assert.equal(result.status, 200, JSON.stringify(result.body)); assert.deepEqual(result.body.task_binding, binding); return result.body;
113
+ };
114
+ const invoke = async (context: any, tool = 'product_update', index = 0, invocationId = id()) => {
115
+ const input = { invocation_id: invocationId, route: members[index]!.route, capability_revision: context.capability_revision,
116
+ agent_run_id: context.run_id, tool, arguments: { id: 1 } };
117
+ return { ...await request('/agent-api/v1/tool-invocations', bearers[index]!, input), input };
118
+ };
119
+ const detail = () => request(`/admin/api/agent-tasks/${task.task_id}`, 'synthetic-admin');
120
+ const control = async (action: string) => {
121
+ const current = (await detail()).body.task;
122
+ const result = await request(`/admin/api/agent-tasks/${task.task_id}/control`, 'synthetic-admin', {
123
+ request_id: randomUUID(), expected_revision: current.revision, action });
124
+ assert.equal(result.status, 200, JSON.stringify(result.body)); return result.body;
125
+ };
126
+ return { members, bearers, task, body, binding, turnBody, turn, invoke, detail, control };
127
+ };
128
+ try {
129
+ await t.test('admin scope creation is idempotent, snapshots disclose only the original member, and omission cannot bypass task admission', async () => {
130
+ const fx = await setup();
131
+ assert.equal((await request('/admin/api/agent-tasks', 'synthetic-admin', fx.body)).body.task_id, fx.task.task_id);
132
+ assert.equal((await request('/admin/api/agent-tasks', fx.bearers[0]!, fx.body)).status, 403);
133
+ const capabilities = await request('/agent-api/v1/task-control/capabilities', fx.bearers[0]!);
134
+ assert.equal(capabilities.body.supported, true); assert.equal(capabilities.body.mode, 'required');
135
+ const snapshot = await request(`/agent-api/v1/tasks/${fx.task.task_id}?workspace=${fx.members[0]!.route}&client_conversation_id=${fx.members[0]!.clientConversationId}`, fx.bearers[0]!);
136
+ assert.equal(snapshot.status, 200); assert.equal(snapshot.body.member_count, 2);
137
+ assert.equal(snapshot.body.member.session_id, fx.members[0]!.sessionId);
138
+ assert.equal(JSON.stringify(snapshot.body).includes(fx.members[1]!.sessionId), false);
139
+ assert.equal(JSON.stringify(snapshot.body).includes('identityHash'), false);
140
+ const { task_binding: _binding, ...withoutTask } = fx.turnBody();
141
+ const omitted = await request(`/agent-api/v1/workspaces/${fx.members[0]!.route}/turns`, fx.bearers[0]!, withoutTask);
142
+ assert.equal(omitted.body.error, 'TASK_REQUIRED');
143
+ const legacy = await request('/agent-api/v1/run', fx.bearers[0]!, {});
144
+ assert.equal(legacy.body.error, 'TASK_REQUIRED'); assert.equal(legacyRuns, 0);
145
+ const [rows]: any = await pool.query('SELECT COUNT(*) AS n FROM bz_agent_client_runs WHERE client_turn_id=?', [withoutTask.client_turn_id]);
146
+ assert.equal(Number(rows[0].n), 0);
147
+ });
148
+ await t.test('two systems and new turns share cumulative writes; readonly calls do not spend write budget; fences survive result persistence', async () => {
149
+ const fx = await setup(2); const before = requests.length;
150
+ const a = await fx.turn(0), b = await fx.turn(1);
151
+ for (const [context, index] of [[a, 0], [b, 1]] as const) {
152
+ const result = await fx.invoke(context, 'product_update', index);
153
+ assert.equal(result.body.state, 'executed', JSON.stringify(result.body));
154
+ const duplicate = await request('/agent-api/v1/tool-invocations', fx.bearers[index]!, result.input);
155
+ assert.equal(duplicate.body.state, 'executed');
156
+ }
157
+ const next = await fx.turn(0);
158
+ assert.equal((await fx.invoke(next)).body.error, 'TASK_WRITE_BUDGET_EXHAUSTED');
159
+ assert.equal((await fx.invoke(next, 'inventory_read')).body.state, 'executed');
160
+ assert.equal(requests.length - before, 3);
161
+ const detail = (await fx.detail()).body;
162
+ assert.equal(detail.task.counters.write_consumed, 2); assert.equal(detail.task.counters.write_reserved, 0);
163
+ assert.equal(detail.task.counters.active_permits, 0);
164
+ for (const invocation of detail.invocations) {
165
+ const job = (await state.getJob(invocation.job_id))!;
166
+ assert.equal(job.metadata.agent_task_id, fx.task.task_id); assert.equal(job.metadata.agent_dispatch_attempted, true);
167
+ assert.ok(job.metadata.agent_task_permit_id); assert.equal(job.metadata.agent_frozen_arguments, undefined);
168
+ }
169
+ });
170
+ await t.test('approval only reserves; paused resume cannot consume approval; inspection is read only; explicit original resume dispatches once', async () => {
171
+ const fx = await setup(1); const before = requests.length;
172
+ const context = await fx.turn(); const result = await fx.invoke(context, 'product_review');
173
+ assert.equal(result.body.state, 'awaiting_approval', JSON.stringify(result.body));
174
+ const approvalId = result.body.approval_id;
175
+ assert.equal((await fx.detail()).body.task.counters.write_reserved, 1);
176
+ await pool.query("UPDATE bz_tool_approvals SET status='approved' WHERE id=?", [approvalId]);
177
+ await fx.control('pause');
178
+ const path = `/agent-api/v1/tool-invocations/${result.input.invocation_id}`;
179
+ const receipt = await request(`${path}/receipt`, fx.bearers[0]!);
180
+ assert.equal(receipt.body.read_only, true, JSON.stringify(receipt)); assert.equal(receipt.body.approval.status, 'approved');
181
+ const paused = await request(`${path}/resume`, fx.bearers[0]!, {});
182
+ assert.equal(paused.body.error, 'TASK_PAUSED', JSON.stringify(paused.body));
183
+ const [rows]: any = await pool.query('SELECT used_at FROM bz_tool_approvals WHERE id=?', [approvalId]);
184
+ assert.equal(rows[0].used_at, null); assert.equal(requests.length, before);
185
+ await fx.control('resume');
186
+ const resumed = await request(`${path}/resume`, fx.bearers[0]!, {});
187
+ assert.equal(resumed.body.state, 'executed', JSON.stringify(resumed.body));
188
+ assert.equal((await request(`${path}/resume`, fx.bearers[0]!, {})).body.state, 'executed');
189
+ assert.equal(requests.length, before + 1);
190
+ assert.equal((await fx.detail()).body.task.counters.write_consumed, 1);
191
+ });
192
+ await t.test('lost business response holds the original reservation and permit; resume never duplicates the write', async () => {
193
+ const fx = await setup(1); const before = requests.length; const context = await fx.turn();
194
+ dropResponse = true;
195
+ const result = await fx.invoke(context); dropResponse = false;
196
+ assert.equal(result.body.state, 'reconciliation_required', JSON.stringify(result.body));
197
+ const retried = await request(`/agent-api/v1/tool-invocations/${result.input.invocation_id}/resume`, fx.bearers[0]!, {});
198
+ assert.equal(retried.body.state, 'reconciliation_required'); assert.equal(requests.length, before + 1);
199
+ const counters = (await fx.detail()).body.task.counters;
200
+ assert.equal(counters.write_reserved, 1); assert.equal(counters.write_consumed, 0); assert.equal(counters.active_permits, 1);
201
+ });
202
+ await t.test('revoking any original member blocks dispatch in the other system; cancel does not unenroll the Session', async () => {
203
+ const fx = await setup(); const before = requests.length; const context = await fx.turn();
204
+ await pool.query('UPDATE bz_agent_sessions SET revoked_at=NOW() WHERE session_id=?', [fx.members[1]!.sessionId]);
205
+ assert.equal((await fx.invoke(context)).body.error, 'TASK_SCOPE_BLOCKED');
206
+ assert.equal(requests.length, before); assert.equal((await fx.detail()).body.task.state, 'blocked');
207
+ await fx.control('cancel');
208
+ const { task_binding: _binding, ...withoutTask } = fx.turnBody();
209
+ assert.equal((await request(`/agent-api/v1/workspaces/${fx.members[0]!.route}/turns`, fx.bearers[0]!, withoutTask)).body.error, 'TASK_REQUIRED');
210
+ });
211
+ await t.test('a lost Core acknowledgement is recovered from the original journal without a second business request', async () => {
212
+ const fx = await setup(1); const context = await fx.turn(); const before = requests.length;
213
+ const invocationId = id(); dropCoreAck = true;
214
+ await assert.rejects(fx.invoke(context, 'product_update', 0, invocationId));
215
+ const receipt = await request(`/agent-api/v1/tool-invocations/${invocationId}/receipt`, fx.bearers[0]!);
216
+ assert.equal(receipt.body.result.state, 'executed', JSON.stringify(receipt));
217
+ assert.equal((await request(`/agent-api/v1/tool-invocations/${invocationId}/resume`, fx.bearers[0]!, {})).body.state, 'executed');
218
+ assert.equal(requests.length, before + 1); assert.equal((await fx.detail()).body.task.counters.write_consumed, 1);
219
+ });
220
+ await t.test('maximum-length client IDs dispatch and inspect without losing the full authorization identity', async () => {
221
+ const fx = await setup(1, true); const context = await fx.turn(); const before = requests.length;
222
+ const result = await fx.invoke(context);
223
+ assert.equal(result.body.state, 'executed', JSON.stringify(result.body)); assert.equal(requests.length, before + 1);
224
+ const invocation = (await fx.detail()).body.invocations[0]; const job = (await state.getJob(invocation.job_id))!;
225
+ assert.equal(job.source.length, 32); assert.equal(job.client_app_id, fx.members[0]!.clientAppId); assert.equal(job.client_app_id!.length, 64);
226
+ const receipt = await request(`/agent-api/v1/tool-invocations/${result.input.invocation_id}/receipt`, fx.bearers[0]!);
227
+ assert.equal(receipt.body.result.state, 'executed', JSON.stringify(receipt.body));
228
+ });
229
+ await t.test('read and write share concurrency; cancel retains prior permits and accepts their late receipts', async () => {
230
+ const fx = await setup(4); const context = await fx.turn(); const before = requests.length;
231
+ let release!: () => void; holdBusinessResponse = new Promise<void>((resolve) => { release = resolve; });
232
+ const pending = [fx.invoke(context), fx.invoke(context, 'inventory_read')];
233
+ try {
234
+ for (let i = 0; requests.length < before + 2 && i < 100; i++) await new Promise((resolve) => setTimeout(resolve, 5));
235
+ assert.equal(requests.length, before + 2);
236
+ assert.equal((await fx.invoke(context, 'inventory_read')).body.error, 'TASK_CONCURRENCY_EXHAUSTED');
237
+ assert.equal((await fx.detail()).body.task.counters.active_permits, 2);
238
+ await fx.control('cancel');
239
+ } finally { holdBusinessResponse = null; release(); }
240
+ const results = await Promise.all(pending); results.forEach((result) => assert.equal(result.body.state, 'executed', JSON.stringify(result.body)));
241
+ const detail = (await fx.detail()).body.task;
242
+ assert.equal(detail.state, 'cancelled'); assert.equal(detail.counters.active_permits, 0); assert.equal(detail.counters.write_consumed, 1);
243
+ assert.equal((await fx.invoke(context)).body.error, 'TASK_CANCELLED'); assert.equal(requests.length, before + 2);
244
+ });
245
+ } finally { await close(core); await close(business); await pool.end(); }
246
+ });
@@ -121,6 +121,7 @@ export async function handlePrivateHttpFor(deps: PrivateHttpDeps, req: IncomingM
121
121
  handleRun: deps.handleRun,
122
122
  toolProxyDeps: toolProxyDeps(deps),
123
123
  kbService: deps.kbService,
124
+ artifactRoot: deps.cfg.runtimeRoot ?? deps.cfg.root,
124
125
  }, req, res, url)) return;
125
126
 
126
127
  if (method === 'POST' && path === '/admin/login') {
package/src/routes/run.ts CHANGED
@@ -36,7 +36,8 @@ function agentAllowsRoute(principal: Extract<Principal, { kind: 'agent' }>, rout
36
36
  }
37
37
 
38
38
  function agentUserMetadata(value: Record<string, unknown>): Record<string, unknown> {
39
- return Object.fromEntries(Object.entries(value).filter(([key]) => !AGENT_RESERVED_METADATA_FIELDS.has(key)));
39
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !AGENT_RESERVED_METADATA_FIELDS.has(key)
40
+ && !key.startsWith('agent_task') && key !== 'task_binding' && key !== 'task_id'));
40
41
  }
41
42
 
42
43
  function agentSubjectScope(principal: Extract<Principal, { kind: 'agent' }>): string {
@@ -0,0 +1,43 @@
1
+ import assert from 'node:assert/strict';
2
+
3
+ type Row = Record<string, any>;
4
+
5
+ /** Narrow in-memory SELECT evaluator shared by repository and loopback HTTP tests. */
6
+ export function evaluateBusinessSessionQuery(sessions: Row[], authorizations: Row[], sql: string, params: unknown[]): any[] {
7
+ assert.match(sql, /FROM bz_agent_sessions s WHERE s\.client_app_id=\?/);
8
+ assert.doesNotMatch(sql, /SELECT s\.\*|access_token_hash|refresh_token/);
9
+ let index = 0;
10
+ let found: Row[] = sessions.map((row): Row => ({ ...row, principal_json: typeof row.principal_json === 'string' ? JSON.parse(row.principal_json) : row.principal_json })).filter((row) => row.client_app_id === params[index]);
11
+ index++;
12
+ if (sql.includes('AND s.session_id=?')) { const id = params[index++]; found = found.filter((row) => row.session_id === id); }
13
+ if (sql.includes('matched.authorization_id=?')) {
14
+ const id = params[index++];
15
+ found = found.filter((row) => authorizations.some((item) => item.authorization_id === id && item.session_id === row.session_id && item.client_app_id === row.client_app_id && item.status === 'consumed'));
16
+ }
17
+ if (sql.includes('BINARY s.on_behalf_of=BINARY ?')) { const subject = params[index++]; found = found.filter((row) => row.on_behalf_of === subject); }
18
+ if (sql.includes("BINARY JSON_UNQUOTE(JSON_EXTRACT(s.principal_json,'$.id'))=BINARY ?")) {
19
+ const id = params[index++]; found = found.filter((row) => row.principal_json.id === id);
20
+ }
21
+ if (sql.includes("JSON_EXTRACT(s.principal_json,'$.tenant')")) {
22
+ const tenant = params[index++]; found = found.filter((row) => (row.principal_json.tenant ?? '') === tenant);
23
+ }
24
+ if (sql.includes('s.revoked_at IS NULL AND s.refresh_expires_at>?')) {
25
+ const now = String(params[index++]); found = found.filter((row) => !row.revoked_at && row.refresh_expires_at > now);
26
+ } else if (sql.includes('s.revoked_at IS NULL AND s.refresh_expires_at<=?')) {
27
+ const now = String(params[index++]); found = found.filter((row) => !row.revoked_at && row.refresh_expires_at <= now);
28
+ } else if (sql.includes('s.revoked_at IS NOT NULL')) found = found.filter((row) => row.revoked_at);
29
+ if (sql.includes('(s.created_at<? OR (s.created_at=? AND s.session_id<?))')) {
30
+ const created = params[index++]; assert.equal(params[index++], created); const id = params[index++];
31
+ found = found.filter((row) => row.created_at < String(created) || (row.created_at === created && row.session_id < String(id)));
32
+ }
33
+ if (sql.includes('ORDER BY')) {
34
+ assert.match(sql, /ORDER BY s\.created_at DESC,s\.session_id DESC LIMIT \?$/);
35
+ found.sort((a, b) => b.created_at.localeCompare(a.created_at) || b.session_id.localeCompare(a.session_id));
36
+ found = found.slice(0, Number(params[index++]));
37
+ } else found = found.slice(0, 1);
38
+ assert.equal(index, params.length, 'every SQL placeholder has an explicitly consumed value');
39
+ return [found.map((row) => {
40
+ const links = authorizations.filter((item) => item.client_app_id === row.client_app_id && item.session_id === row.session_id && item.status === 'consumed');
41
+ return { ...structuredClone(row), cursor_created_at: `${row.created_at.replace(' ', 'T')}.000Z`, authorization_id: links.length === 1 ? links[0]!.authorization_id : null };
42
+ }), []];
43
+ }