@bevel-software/platform-core-backend 0.23.0 → 0.24.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 (227) hide show
  1. package/dist/core/create-core-server.d.ts.map +1 -1
  2. package/dist/core/create-core-server.js +17 -3
  3. package/dist/core/create-core-server.js.map +1 -1
  4. package/dist/core/create-core-services.d.ts +3 -0
  5. package/dist/core/create-core-services.d.ts.map +1 -1
  6. package/dist/core/create-core-services.js +25 -1
  7. package/dist/core/create-core-services.js.map +1 -1
  8. package/dist/core/lifecycle.d.ts +12 -0
  9. package/dist/core/lifecycle.d.ts.map +1 -1
  10. package/dist/core/lifecycle.js +10 -0
  11. package/dist/core/lifecycle.js.map +1 -1
  12. package/dist/core-config.d.ts +16 -0
  13. package/dist/core-config.d.ts.map +1 -1
  14. package/dist/core-config.js +17 -0
  15. package/dist/core-config.js.map +1 -1
  16. package/dist/index.d.ts +3 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +10 -2
  19. package/dist/index.js.map +1 -1
  20. package/dist/modules/access/access.routes.d.ts.map +1 -1
  21. package/dist/modules/access/access.routes.js +4 -1
  22. package/dist/modules/access/access.routes.js.map +1 -1
  23. package/dist/modules/access/directory-sync-bot.d.ts.map +1 -1
  24. package/dist/modules/access/directory-sync-bot.js +7 -3
  25. package/dist/modules/access/directory-sync-bot.js.map +1 -1
  26. package/dist/modules/agent-instructions/agent-instructions.routes.d.ts +8 -1
  27. package/dist/modules/agent-instructions/agent-instructions.routes.d.ts.map +1 -1
  28. package/dist/modules/agent-instructions/agent-instructions.routes.js +8 -2
  29. package/dist/modules/agent-instructions/agent-instructions.routes.js.map +1 -1
  30. package/dist/modules/agent-instructions/compose.d.ts +38 -6
  31. package/dist/modules/agent-instructions/compose.d.ts.map +1 -1
  32. package/dist/modules/agent-instructions/compose.js +39 -6
  33. package/dist/modules/agent-instructions/compose.js.map +1 -1
  34. package/dist/modules/agent-instructions/index.d.ts +2 -1
  35. package/dist/modules/agent-instructions/index.d.ts.map +1 -1
  36. package/dist/modules/agent-instructions/index.js +2 -1
  37. package/dist/modules/agent-instructions/index.js.map +1 -1
  38. package/dist/modules/agent-instructions/shared-file-rules.d.ts +115 -0
  39. package/dist/modules/agent-instructions/shared-file-rules.d.ts.map +1 -0
  40. package/dist/modules/agent-instructions/shared-file-rules.js +272 -0
  41. package/dist/modules/agent-instructions/shared-file-rules.js.map +1 -0
  42. package/dist/modules/audit/agent-audit.service.d.ts.map +1 -1
  43. package/dist/modules/audit/agent-audit.service.js +4 -2
  44. package/dist/modules/audit/agent-audit.service.js.map +1 -1
  45. package/dist/modules/auth/account-erasure.service.d.ts.map +1 -1
  46. package/dist/modules/auth/account-erasure.service.js +57 -16
  47. package/dist/modules/auth/account-erasure.service.js.map +1 -1
  48. package/dist/modules/auth/auth.service.d.ts.map +1 -1
  49. package/dist/modules/auth/auth.service.js +25 -15
  50. package/dist/modules/auth/auth.service.js.map +1 -1
  51. package/dist/modules/code-mode/code-mode.tool.d.ts +20 -2
  52. package/dist/modules/code-mode/code-mode.tool.d.ts.map +1 -1
  53. package/dist/modules/code-mode/code-mode.tool.js +66 -35
  54. package/dist/modules/code-mode/code-mode.tool.js.map +1 -1
  55. package/dist/modules/database/connection.d.ts +16 -0
  56. package/dist/modules/database/connection.d.ts.map +1 -1
  57. package/dist/modules/database/connection.js +117 -0
  58. package/dist/modules/database/connection.js.map +1 -1
  59. package/dist/modules/database/core-schema.d.ts +296 -96
  60. package/dist/modules/database/core-schema.d.ts.map +1 -1
  61. package/dist/modules/database/core-schema.js +81 -31
  62. package/dist/modules/database/core-schema.js.map +1 -1
  63. package/dist/modules/database/migrate.d.ts +8 -0
  64. package/dist/modules/database/migrate.d.ts.map +1 -1
  65. package/dist/modules/database/migrate.js +271 -1
  66. package/dist/modules/database/migrate.js.map +1 -1
  67. package/dist/modules/mcp/mcp.service.d.ts +8 -0
  68. package/dist/modules/mcp/mcp.service.d.ts.map +1 -1
  69. package/dist/modules/mcp/mcp.service.js +38 -8
  70. package/dist/modules/mcp/mcp.service.js.map +1 -1
  71. package/dist/modules/plugins/join-request-records.store.d.ts.map +1 -1
  72. package/dist/modules/plugins/join-request-records.store.js +7 -4
  73. package/dist/modules/plugins/join-request-records.store.js.map +1 -1
  74. package/dist/modules/tool-auth/external-api-key.service.d.ts.map +1 -1
  75. package/dist/modules/tool-auth/external-api-key.service.js +8 -2
  76. package/dist/modules/tool-auth/external-api-key.service.js.map +1 -1
  77. package/dist/modules/tool-manuals/tool-manuals.tools.d.ts.map +1 -1
  78. package/dist/modules/tool-manuals/tool-manuals.tools.js +42 -31
  79. package/dist/modules/tool-manuals/tool-manuals.tools.js.map +1 -1
  80. package/dist/modules/tool-registry/description-length.d.ts +80 -0
  81. package/dist/modules/tool-registry/description-length.d.ts.map +1 -0
  82. package/dist/modules/tool-registry/description-length.js +108 -0
  83. package/dist/modules/tool-registry/description-length.js.map +1 -0
  84. package/dist/modules/workflow/git/git.service.d.ts +25 -0
  85. package/dist/modules/workflow/git/git.service.d.ts.map +1 -1
  86. package/dist/modules/workflow/git/git.service.js +40 -1
  87. package/dist/modules/workflow/git/git.service.js.map +1 -1
  88. package/dist/modules/workflow/pending-commits.service.d.ts.map +1 -1
  89. package/dist/modules/workflow/pending-commits.service.js +5 -1
  90. package/dist/modules/workflow/pending-commits.service.js.map +1 -1
  91. package/dist/modules/workflow/recovery-bot.d.ts.map +1 -1
  92. package/dist/modules/workflow/recovery-bot.js +7 -3
  93. package/dist/modules/workflow/recovery-bot.js.map +1 -1
  94. package/dist/modules/workflow/review-workflow/review-workflow.service.d.ts.map +1 -1
  95. package/dist/modules/workflow/review-workflow/review-workflow.service.js +12 -3
  96. package/dist/modules/workflow/review-workflow/review-workflow.service.js.map +1 -1
  97. package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
  98. package/dist/modules/workflow/workflow.service.js +4 -1
  99. package/dist/modules/workflow/workflow.service.js.map +1 -1
  100. package/dist/modules/workspace/agent-upload.routes.d.ts +77 -0
  101. package/dist/modules/workspace/agent-upload.routes.d.ts.map +1 -0
  102. package/dist/modules/workspace/agent-upload.routes.js +210 -0
  103. package/dist/modules/workspace/agent-upload.routes.js.map +1 -0
  104. package/dist/modules/workspace/agent-upload.store.d.ts +284 -0
  105. package/dist/modules/workspace/agent-upload.store.d.ts.map +1 -0
  106. package/dist/modules/workspace/agent-upload.store.js +553 -0
  107. package/dist/modules/workspace/agent-upload.store.js.map +1 -0
  108. package/dist/modules/workspace/startup/steps/seed-tree.d.ts.map +1 -1
  109. package/dist/modules/workspace/startup/steps/seed-tree.js +3 -3
  110. package/dist/modules/workspace/startup/steps/seed-tree.js.map +1 -1
  111. package/dist/modules/workspace/startup/steps/template-source.d.ts +40 -0
  112. package/dist/modules/workspace/startup/steps/template-source.d.ts.map +1 -1
  113. package/dist/modules/workspace/startup/steps/template-source.js +46 -4
  114. package/dist/modules/workspace/startup/steps/template-source.js.map +1 -1
  115. package/dist/modules/workspace/upload-limits.d.ts +13 -0
  116. package/dist/modules/workspace/upload-limits.d.ts.map +1 -0
  117. package/dist/modules/workspace/upload-limits.js +13 -0
  118. package/dist/modules/workspace/upload-limits.js.map +1 -0
  119. package/dist/modules/workspace/workspace.routes.d.ts.map +1 -1
  120. package/dist/modules/workspace/workspace.routes.js +1 -1
  121. package/dist/modules/workspace/workspace.routes.js.map +1 -1
  122. package/dist/modules/workspace/workspace.service.d.ts +13 -0
  123. package/dist/modules/workspace/workspace.service.d.ts.map +1 -1
  124. package/dist/modules/workspace/workspace.service.js +61 -33
  125. package/dist/modules/workspace/workspace.service.js.map +1 -1
  126. package/dist/modules/workspace/workspace.tools.d.ts +11 -9
  127. package/dist/modules/workspace/workspace.tools.d.ts.map +1 -1
  128. package/dist/modules/workspace/workspace.tools.js +512 -113
  129. package/dist/modules/workspace/workspace.tools.js.map +1 -1
  130. package/dist/modules/workspace/write-denial.d.ts +0 -6
  131. package/dist/modules/workspace/write-denial.d.ts.map +1 -1
  132. package/dist/modules/workspace/write-denial.js +0 -6
  133. package/dist/modules/workspace/write-denial.js.map +1 -1
  134. package/dist/modules/workspace/zip-entry-rules.d.ts +114 -0
  135. package/dist/modules/workspace/zip-entry-rules.d.ts.map +1 -0
  136. package/dist/modules/workspace/zip-entry-rules.js +154 -0
  137. package/dist/modules/workspace/zip-entry-rules.js.map +1 -0
  138. package/dist/shared/column-crypto.d.ts +194 -0
  139. package/dist/shared/column-crypto.d.ts.map +1 -0
  140. package/dist/shared/column-crypto.js +144 -0
  141. package/dist/shared/column-crypto.js.map +1 -0
  142. package/dist/shared/token-crypto.d.ts.map +1 -1
  143. package/dist/shared/token-crypto.js +25 -1
  144. package/dist/shared/token-crypto.js.map +1 -1
  145. package/dist/tenancy/static-tenant-source.d.ts.map +1 -1
  146. package/dist/tenancy/static-tenant-source.js +1 -0
  147. package/dist/tenancy/static-tenant-source.js.map +1 -1
  148. package/dist/tenancy/tenant-secrets.d.ts +5 -1
  149. package/dist/tenancy/tenant-secrets.d.ts.map +1 -1
  150. package/dist/tenancy/tenant-secrets.js +4 -0
  151. package/dist/tenancy/tenant-secrets.js.map +1 -1
  152. package/kb-template/AGENTS.md +2 -0
  153. package/migrations/0016_pii_encryption.sql +20 -0
  154. package/migrations/meta/0016_snapshot.json +2327 -0
  155. package/migrations/meta/_journal.json +7 -0
  156. package/package.json +3 -3
  157. package/src/core/__tests__/lifecycle.test.ts +71 -4
  158. package/src/core/create-core-server.ts +21 -3
  159. package/src/core/create-core-services.ts +27 -1
  160. package/src/core/lifecycle.ts +19 -0
  161. package/src/core-config.ts +18 -0
  162. package/src/index.ts +18 -0
  163. package/src/modules/access/__tests__/users-db-double.ts +21 -12
  164. package/src/modules/access/access.routes.ts +4 -1
  165. package/src/modules/access/directory-sync-bot.ts +7 -3
  166. package/src/modules/agent-instructions/__tests__/agent-instructions.route.test.ts +8 -4
  167. package/src/modules/agent-instructions/__tests__/compose.test.ts +19 -10
  168. package/src/modules/agent-instructions/__tests__/shared-file-rules.test.ts +238 -0
  169. package/src/modules/agent-instructions/agent-instructions.routes.ts +12 -2
  170. package/src/modules/agent-instructions/compose.ts +50 -7
  171. package/src/modules/agent-instructions/index.ts +12 -0
  172. package/src/modules/agent-instructions/shared-file-rules.ts +314 -0
  173. package/src/modules/audit/agent-audit.service.ts +4 -2
  174. package/src/modules/auth/__tests__/account-deactivation.test.ts +2 -1
  175. package/src/modules/auth/__tests__/account-erasure.approval-gate.test.ts +6 -2
  176. package/src/modules/auth/__tests__/account.routes.test.ts +6 -3
  177. package/src/modules/auth/__tests__/auth.service.test.ts +3 -1
  178. package/src/modules/auth/account-erasure.service.ts +69 -18
  179. package/src/modules/auth/auth.service.ts +33 -23
  180. package/src/modules/code-mode/__tests__/chain-runtime.e2e.test.ts +335 -0
  181. package/src/modules/code-mode/__tests__/code-mode.tool.test.ts +46 -2
  182. package/src/modules/code-mode/code-mode.tool.ts +80 -34
  183. package/src/modules/database/__tests__/connection.test.ts +12 -0
  184. package/src/modules/database/__tests__/pii-backfill.pg.test.ts +561 -0
  185. package/src/modules/database/connection.ts +117 -0
  186. package/src/modules/database/core-schema.ts +81 -31
  187. package/src/modules/database/migrate.ts +353 -1
  188. package/src/modules/mcp/__tests__/mcp.e2e.test.ts +4 -3
  189. package/src/modules/mcp/__tests__/mcp.service.test.ts +47 -7
  190. package/src/modules/mcp/mcp.service.ts +46 -7
  191. package/src/modules/plugins/join-request-records.store.ts +7 -4
  192. package/src/modules/tool-auth/external-api-key.service.ts +8 -2
  193. package/src/modules/tool-manuals/tool-manuals.tools.ts +44 -31
  194. package/src/modules/tool-registry/__tests__/tool-description-length.test.ts +378 -0
  195. package/src/modules/tool-registry/description-length.ts +111 -0
  196. package/src/modules/workflow/git/__tests__/git.service.prFetchFailure.test.ts +170 -0
  197. package/src/modules/workflow/git/git.service.ts +47 -1
  198. package/src/modules/workflow/pending-commits.service.ts +5 -1
  199. package/src/modules/workflow/recovery-bot.ts +7 -3
  200. package/src/modules/workflow/review-workflow/__tests__/carry-approvals-forward.test.ts +4 -0
  201. package/src/modules/workflow/review-workflow/__tests__/erase-approver.test.ts +25 -3
  202. package/src/modules/workflow/review-workflow/review-workflow.service.ts +12 -3
  203. package/src/modules/workflow/workflow.service.ts +4 -1
  204. package/src/modules/workspace/__tests__/agent-uploads.test.ts +1604 -0
  205. package/src/modules/workspace/__tests__/escape-sequences.routes.test.ts +24 -14
  206. package/src/modules/workspace/__tests__/workspace.service.any-workspace-credentials.test.ts +156 -0
  207. package/src/modules/workspace/__tests__/workspace.service.replaced-repository.test.ts +77 -1
  208. package/src/modules/workspace/__tests__/workspace.service.test.ts +57 -0
  209. package/src/modules/workspace/__tests__/workspace.tools.agents-file.test.ts +39 -36
  210. package/src/modules/workspace/__tests__/workspace.tools.test.ts +84 -45
  211. package/src/modules/workspace/agent-upload.routes.ts +214 -0
  212. package/src/modules/workspace/agent-upload.store.ts +668 -0
  213. package/src/modules/workspace/startup/steps/__tests__/steps.test.ts +9 -9
  214. package/src/modules/workspace/startup/steps/seed-tree.ts +3 -6
  215. package/src/modules/workspace/startup/steps/template-source.ts +53 -5
  216. package/src/modules/workspace/upload-limits.ts +12 -0
  217. package/src/modules/workspace/workspace.routes.ts +1 -2
  218. package/src/modules/workspace/workspace.service.ts +63 -37
  219. package/src/modules/workspace/workspace.tools.ts +588 -127
  220. package/src/modules/workspace/write-denial.ts +0 -8
  221. package/src/modules/workspace/zip-entry-rules.ts +173 -0
  222. package/src/shared/__tests__/column-crypto.test.ts +217 -0
  223. package/src/shared/column-crypto.ts +218 -0
  224. package/src/shared/token-crypto.ts +28 -1
  225. package/src/tenancy/__tests__/static-tenant-source.test.ts +4 -0
  226. package/src/tenancy/static-tenant-source.ts +1 -0
  227. package/src/tenancy/tenant-secrets.ts +5 -1
@@ -141,7 +141,7 @@ export class AuthService {
141
141
  const [existing] = await this.db
142
142
  .select({ id: users.id })
143
143
  .from(users)
144
- .where(eq(users.email, normalizedEmail))
144
+ .where(eq(users.emailBidx, normalizedEmail))
145
145
  .limit(1);
146
146
  if (existing) return;
147
147
  const verdict = await this.admission.canProvision(normalizedEmail, reason);
@@ -153,8 +153,13 @@ export class AuthService {
153
153
  if (verdict.waitForAdmin && reason === 'sso') {
154
154
  await this.db
155
155
  .insert(users)
156
- .values({ email: normalizedEmail, name: normalizedEmail.split('@')[0] || normalizedEmail, deactivatedAt: new Date() })
157
- .onConflictDoNothing({ target: users.email });
156
+ .values({
157
+ email: normalizedEmail,
158
+ emailBidx: normalizedEmail,
159
+ name: normalizedEmail.split('@')[0] || normalizedEmail,
160
+ deactivatedAt: new Date(),
161
+ })
162
+ .onConflictDoNothing({ target: users.emailBidx });
158
163
  throw new AccountAdmissionRefusedError(verdict.message, { waitingForAdmin: true });
159
164
  }
160
165
  throw new AccountAdmissionRefusedError(verdict.message);
@@ -198,11 +203,12 @@ export class AuthService {
198
203
  // address's — one round trip short — and repeated timings would then
199
204
  // disclose which email the deployment configured as `ADMIN_EMAIL`. The
200
205
  // decoy hash already buys that uniformity for the scrypt half; this keeps
201
- // the database half uniform too.
206
+ // the database half uniform too. Through the blind index: `email` is
207
+ // randomized ciphertext.
202
208
  const [user] = await this.db
203
209
  .select()
204
210
  .from(users)
205
- .where(eq(users.email, normalizedEmail))
211
+ .where(eq(users.emailBidx, normalizedEmail))
206
212
  .limit(1);
207
213
 
208
214
  if (this.isEnvAdminEmail(normalizedEmail)) {
@@ -319,9 +325,9 @@ export class AuthService {
319
325
  await this.assertAdmitted(normalizedEmail, 'admin-create');
320
326
  const [created] = await this.db
321
327
  .insert(users)
322
- .values({ email: normalizedEmail, name: displayName })
328
+ .values({ email: normalizedEmail, emailBidx: normalizedEmail, name: displayName })
323
329
  .onConflictDoUpdate({
324
- target: users.email,
330
+ target: users.emailBidx,
325
331
  set: suppliedName ? { name: suppliedName, updatedAt: new Date() } : { updatedAt: new Date() },
326
332
  })
327
333
  .returning();
@@ -341,9 +347,9 @@ export class AuthService {
341
347
  // fallback. `returning()` yields the authoritative row either way.
342
348
  const [row] = await this.db
343
349
  .insert(users)
344
- .values({ email: normalizedEmail, name: displayName, passwordHash })
350
+ .values({ email: normalizedEmail, emailBidx: normalizedEmail, name: displayName, passwordHash })
345
351
  .onConflictDoUpdate({
346
- target: users.email,
352
+ target: users.emailBidx,
347
353
  set: suppliedName
348
354
  ? { passwordHash, name: suppliedName, updatedAt: new Date() }
349
355
  : { passwordHash, updatedAt: new Date() },
@@ -462,17 +468,21 @@ export class AuthService {
462
468
  createdAt: Date;
463
469
  }>
464
470
  > {
465
- const rows = await this.db.select().from(users).orderBy(users.email);
466
- return rows.map((row) => ({
467
- id: row.id,
468
- email: row.email,
469
- name: row.name,
470
- hasPassword: row.passwordHash != null,
471
- isEnvAdmin: this.reportsAsEnvAdmin(row.email),
472
- deactivatedAt: row.deactivatedAt,
473
- isSystem: SYSTEM_ACCOUNT_EMAILS.includes(row.email),
474
- createdAt: row.createdAt,
475
- }));
471
+ // Sorted in-process: `email` is ciphertext in the database, so ORDER BY
472
+ // would sort by IV noise. The table is one row per team member.
473
+ const rows = await this.db.select().from(users);
474
+ return rows
475
+ .map((row) => ({
476
+ id: row.id,
477
+ email: row.email,
478
+ name: row.name,
479
+ hasPassword: row.passwordHash != null,
480
+ isEnvAdmin: this.reportsAsEnvAdmin(row.email),
481
+ deactivatedAt: row.deactivatedAt,
482
+ isSystem: SYSTEM_ACCOUNT_EMAILS.includes(row.email),
483
+ createdAt: row.createdAt,
484
+ }))
485
+ .sort((a, b) => a.email.localeCompare(b.email));
476
486
  }
477
487
 
478
488
  private assertPasswordPolicy(password: string): void {
@@ -509,8 +519,8 @@ export class AuthService {
509
519
  private async upsertUserByEmail(email: string, name: string) {
510
520
  const [user] = await this.db
511
521
  .insert(users)
512
- .values({ email, name })
513
- .onConflictDoUpdate({ target: users.email, set: { updatedAt: new Date() } })
522
+ .values({ email, emailBidx: email, name })
523
+ .onConflictDoUpdate({ target: users.emailBidx, set: { updatedAt: new Date() } })
514
524
  .returning();
515
525
  return user;
516
526
  }
@@ -686,7 +696,7 @@ export class AuthService {
686
696
  const [user] = await this.db
687
697
  .select()
688
698
  .from(users)
689
- .where(eq(users.email, canonicalEmail(email ?? '')))
699
+ .where(eq(users.emailBidx, canonicalEmail(email ?? '')))
690
700
  .limit(1);
691
701
 
692
702
  if (!user) return null;
@@ -0,0 +1,335 @@
1
+ import { describe, expect, it, vi, beforeAll, afterAll } from 'vitest';
2
+ import '@utcp/direct-call';
3
+ import { addFunctionToUtcpDirectCall } from '@utcp/direct-call';
4
+ import { CodeModeUtcpClient } from '@utcp/code-mode';
5
+ import { codeModeMetaTools, dispatchMetaTool } from '@bevel-software/platform-mcp-core';
6
+ import { createCallToolChainTool } from '../code-mode.tool.js';
7
+
8
+ /**
9
+ * Every Scenario of the Specification, against a REAL `isolated-vm` isolate.
10
+ *
11
+ * mcp-core pins the runtime's pieces one by one, which is where the arithmetic
12
+ * belongs. What it cannot show is that a chain can actually REACH `atob`, that
13
+ * `while(true){}` really is answered rather than dropped, and that the
14
+ * connection survives it — all three are properties of the isolate and of the
15
+ * runner's own resolved shape, and a mock of `callToolChain` would be asserting
16
+ * our belief about `@utcp/code-mode` rather than its behaviour. So this file
17
+ * registers a live manual and runs real chains through the shipping tool.
18
+ */
19
+
20
+ const NAMESPACE = 'KNOWLEDGE_BASE';
21
+ let client: CodeModeUtcpClient;
22
+
23
+ /**
24
+ * The manual is shaped exactly as `toolDef` shapes a real knowledge-base tool:
25
+ * flat arguments wrapped under one required `body`, `branch` required inside it
26
+ * with no `default` and no `enum`, and a handler that REFUSES a call without it
27
+ * the way the route does. That refusal is the point — it is what turned a
28
+ * plausible-looking example into `400 … \`branch\` is required`, and a fixture
29
+ * that accepted anything would have let the example through again.
30
+ */
31
+ function kbTool(name: string, required: string[], callable: string) {
32
+ const properties: Record<string, unknown> = {
33
+ branch: { type: 'string', minLength: 1, description: 'The branch this operates on.' },
34
+ path: { type: 'string', description: 'The path to read.' },
35
+ };
36
+ return {
37
+ name,
38
+ description: `A live ${name}, so the namespace is a real object.`,
39
+ inputs: {
40
+ type: 'object',
41
+ properties: {
42
+ body:
43
+ required.length === 0
44
+ ? { type: 'object', properties: {}, additionalProperties: false }
45
+ : {
46
+ type: 'object',
47
+ properties: Object.fromEntries(required.map((k) => [k, properties[k]])),
48
+ required,
49
+ additionalProperties: false,
50
+ },
51
+ },
52
+ required: ['body'],
53
+ additionalProperties: false,
54
+ },
55
+ outputs: { type: 'object', properties: {} },
56
+ tool_call_template: { call_template_type: 'direct-call', callable_name: callable },
57
+ };
58
+ }
59
+
60
+ /**
61
+ * The real `read_file` handler, as a named installer rather than an inline
62
+ * closure, because a test that swaps it has to put THIS back. Restoring a
63
+ * permissive stand-in instead silently disarmed the branch check for every
64
+ * test that ran afterwards — which is how a test for the missing-argument
65
+ * failure passed while asserting the opposite.
66
+ *
67
+ * Note the unwrapping: the direct-call protocol hands the callable the inner
68
+ * `body` object, so what arrives is `{ branch, path }`, not `{ body: … }`.
69
+ */
70
+ function installReadFile(): void {
71
+ addFunctionToUtcpDirectCall('e2e_read_file', async (args: unknown) => {
72
+ const given = (args ?? {}) as Record<string, unknown>;
73
+ const body = (given.body as Record<string, unknown> | undefined) ?? given;
74
+ // The server's own refusal, reproduced: identity never implies a
75
+ // workspace, so `branch` always comes from the argument.
76
+ if (!body.branch) throw new Error('HTTP 400: `branch` is required');
77
+ if (!body.path) throw new Error('HTTP 400: `path` is required');
78
+ return { content: 'live' };
79
+ });
80
+ }
81
+
82
+ beforeAll(async () => {
83
+ addFunctionToUtcpDirectCall('e2e_manual', async () => ({
84
+ utcp_version: '1.0.0',
85
+ manual_version: '1.0.0',
86
+ tools: [
87
+ kbTool('read_file', ['branch', 'path'], 'e2e_read_file'),
88
+ kbTool('start_session', [], 'e2e_start_session'),
89
+ ],
90
+ }));
91
+ installReadFile();
92
+ addFunctionToUtcpDirectCall('e2e_start_session', async () => ({ sessionId: 's-1' }));
93
+ client = await CodeModeUtcpClient.create(process.cwd(), null);
94
+ const registered = await client.registerManual({
95
+ name: NAMESPACE,
96
+ call_template_type: 'direct-call',
97
+ callable_name: 'e2e_manual',
98
+ } as never);
99
+ expect(registered.success).toBe(true);
100
+ }, 60_000);
101
+
102
+ afterAll(async () => {
103
+ await client?.close();
104
+ });
105
+
106
+ type ChainResult = {
107
+ success: boolean;
108
+ result?: unknown;
109
+ error?: string;
110
+ logs?: string[];
111
+ };
112
+
113
+ /** This client's catalog, in the shape the description builder takes. */
114
+ async function catalog(): Promise<{ utcpName: string; inputSchema: unknown }[]> {
115
+ return (await client.config.tool_repository.getTools()).map((t) => ({
116
+ utcpName: t.name,
117
+ inputSchema: t.inputs,
118
+ }));
119
+ }
120
+
121
+ /** The shipping Mastra tool, run for real against the LIVE catalog. */
122
+ async function chain(code: string, timeout?: number): Promise<ChainResult> {
123
+ const tool = createCallToolChainTool(
124
+ client,
125
+ { write: vi.fn() } as never,
126
+ NAMESPACE,
127
+ await catalog(),
128
+ ) as unknown as {
129
+ execute: (input: { code: string; timeout?: number }) => Promise<ChainResult>;
130
+ };
131
+ return tool.execute({ code, ...(timeout === undefined ? {} : { timeout }) });
132
+ }
133
+
134
+ /** The same chain through the MCP surfaces' dispatcher. */
135
+ async function mcpChain(code: string, timeout?: number): Promise<{ isError?: boolean; text: string }> {
136
+ const res = await dispatchMetaTool(client, 'call_tool_chain', {
137
+ code,
138
+ ...(timeout === undefined ? {} : { timeout }),
139
+ });
140
+ return { isError: res.isError as boolean | undefined, text: (res.content[0] as { text: string }).text };
141
+ }
142
+
143
+ describe('the chain runtime, in a real isolate', () => {
144
+ it('has atob, and it decodes', async () => {
145
+ expect(await chain("return atob('SGVsbG8=')")).toMatchObject({ success: true, result: 'Hello' });
146
+ });
147
+
148
+ it('round-trips UTF-8 text through TextEncoder and TextDecoder', async () => {
149
+ const out = await chain("return new TextDecoder().decode(new TextEncoder().encode('über'))");
150
+ expect(out).toMatchObject({ success: true, result: 'über' });
151
+ });
152
+
153
+ it('has all four globals as functions', async () => {
154
+ const out = await chain(
155
+ 'return [typeof atob, typeof btoa, typeof TextEncoder, typeof TextDecoder]',
156
+ );
157
+ expect(out.result).toEqual(['function', 'function', 'function', 'function']);
158
+ });
159
+
160
+ it('encodes the bytes a browser encodes, and base64s them', async () => {
161
+ const out = await chain(
162
+ "const b = new TextEncoder().encode('über'); return [Array.from(b), btoa(String.fromCharCode.apply(null, Array.from(b)))]",
163
+ );
164
+ expect(out.result).toEqual([[195, 188, 98, 101, 114], 'w7xiZXI=']);
165
+ });
166
+
167
+ it('decodes base64 back into UTF-8 text', async () => {
168
+ const out = await chain(
169
+ "const s = atob('w7xiZXI='); const b = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) b[i] = s.charCodeAt(i); return new TextDecoder().decode(b)",
170
+ );
171
+ expect(out).toMatchObject({ success: true, result: 'über' });
172
+ });
173
+
174
+ it('offers them on the MCP surfaces too', async () => {
175
+ const out = await mcpChain("return atob('SGVsbG8=')");
176
+ expect(out.isError).toBeFalsy();
177
+ expect(JSON.parse(out.text)).toMatchObject({ success: true, result: 'Hello' });
178
+ });
179
+ });
180
+
181
+ describe('a chain that outlives its timeout, in a real isolate', () => {
182
+ it('is answered with a timeout error, and the connection stays usable', async () => {
183
+ const out = await chain('while(true){}', 1_000);
184
+ expect(out.success).toBe(false);
185
+ expect(out.error).toContain('timed out after 1000 ms');
186
+ expect(out.error).toContain('`timeout`');
187
+ expect(out.error).toContain('120000');
188
+ // The Scenario's second half: the NEXT call on the same connection works.
189
+ expect(await chain("return KNOWLEDGE_BASE.read_file({ body: { branch: 'main', path: 'x' } })")).toMatchObject({
190
+ success: true,
191
+ result: { content: 'live' },
192
+ });
193
+ }, 30_000);
194
+
195
+ it('is answered the same way on the MCP surfaces, which then serve the next call', async () => {
196
+ const timedOut = await mcpChain('while(true){}', 1_000);
197
+ expect(timedOut.isError).toBe(true);
198
+ expect(timedOut.text).toContain('timed out after 1000 ms');
199
+ expect(timedOut.text).toContain('120000');
200
+ const next = await mcpChain("return KNOWLEDGE_BASE.read_file({ body: { branch: 'main', path: 'x' } })");
201
+ expect(next.isError).toBeFalsy();
202
+ expect(JSON.parse(next.text)).toMatchObject({ success: true });
203
+ // And a plain tool listing still answers, so nothing about the session died.
204
+ const listed = await dispatchMetaTool(client, 'list_tools', {});
205
+ expect((listed.content[0] as { text: string }).text).toContain('KNOWLEDGE_BASE.read_file');
206
+ }, 30_000);
207
+ });
208
+
209
+ describe('a chain that fails some other way, in a real isolate', () => {
210
+ it('is told which namespaces exist when it names one that does not', async () => {
211
+ const out = await chain("return WRONG.read_file({ path: 'x' })");
212
+ expect(out.success).toBe(false);
213
+ expect(out.error).toContain('WRONG is not defined');
214
+ expect(out.error).toContain('KNOWLEDGE_BASE');
215
+ expect(out.error).toContain('list_tools');
216
+ });
217
+
218
+ it('is answered with its own reason when the chain throws', async () => {
219
+ const out = await chain("throw new Error('the chain said no')");
220
+ expect(out.success).toBe(false);
221
+ expect(out.error).toContain('the chain said no');
222
+ });
223
+
224
+ it('is answered with the tool\'s reason when a tool inside it throws', async () => {
225
+ addFunctionToUtcpDirectCall('e2e_read_file', async () => {
226
+ throw new Error("You don't have read access to \"Secret.md\"");
227
+ });
228
+ try {
229
+ const out = await chain("return KNOWLEDGE_BASE.read_file({ body: { branch: 'main', path: 'Secret.md' } })");
230
+ expect(out.success).toBe(false);
231
+ expect(out.error).toContain('read access');
232
+ } finally {
233
+ // The REAL handler back, branch check included — see `installReadFile`.
234
+ installReadFile();
235
+ }
236
+ });
237
+
238
+ it('is answered with the compiler\'s own complaint rather than an empty success', async () => {
239
+ const out = await chain('return (((');
240
+ expect(out.success).toBe(false);
241
+ expect(out.error).toMatch(/Unexpected token/);
242
+ });
243
+
244
+ it('reports a failure against the chain\'s OWN line numbers, the prelude notwithstanding', async () => {
245
+ // The single-line prelude earns its keep here: the stack must name the
246
+ // line of the agent's code, not a line of a runtime it cannot see.
247
+ const out = await chain('const a = 1;\nconst b = 2;\nreturn WRONG.go();');
248
+ expect(out.success).toBe(false);
249
+ const noPrelude = await client.callToolChain('const a = 1;\nconst b = 2;\nreturn WRONG.go();', 10_000);
250
+ const line = (s: string) => /<isolated-vm>:(\d+):/.exec(s)?.[1];
251
+ expect(line(noPrelude.logs.join('\n'))).toBeDefined();
252
+ // Same reported line with and without the prelude in front of the chain.
253
+ const withPrelude = await client.callToolChain(
254
+ (await import('@bevel-software/platform-mcp-core')).withChainRuntime(
255
+ 'const a = 1;\nconst b = 2;\nreturn WRONG.go();',
256
+ ),
257
+ 10_000,
258
+ );
259
+ expect(line(withPrelude.logs.join('\n'))).toBe(line(noPrelude.logs.join('\n')));
260
+ }, 30_000);
261
+ });
262
+
263
+ describe('a chain that succeeds, in a real isolate', () => {
264
+ it('still calls its tools and returns its value', async () => {
265
+ const out = await chain(
266
+ "const a = KNOWLEDGE_BASE.read_file({ body: { branch: 'main', path: 'x' } }); return { seen: a.content, b64: btoa(a.content) };",
267
+ );
268
+ expect(out).toMatchObject({ success: true, result: { seen: 'live', b64: 'bGl2ZQ==' } });
269
+ });
270
+
271
+ it('can still return null without being read as a failure', async () => {
272
+ expect(await chain('return null')).toMatchObject({ success: true, result: null });
273
+ });
274
+ });
275
+
276
+ /**
277
+ * The acceptance criterion itself: an agent that copies the example call out of
278
+ * the description gets a WORKING call. Run verbatim, in a real isolate, against
279
+ * a manual that refuses a call without `branch` exactly as the route does.
280
+ *
281
+ * This is the test whose absence shipped the bug. The unit tests checked that
282
+ * the example's NAME came from the catalog; nothing executed it, so nobody
283
+ * noticed the arguments beside the name were fixed text omitting a required
284
+ * one. Here the example is extracted from the generated description and run.
285
+ */
286
+ describe('the example call in the description, copied verbatim', () => {
287
+ async function printedExample(): Promise<string> {
288
+ const tool = createCallToolChainTool(
289
+ client,
290
+ { write: vi.fn() } as never,
291
+ NAMESPACE,
292
+ await catalog(),
293
+ ) as unknown as { description: string };
294
+ const printed = /works exactly as written: `return ([^`]+);`/.exec(tool.description);
295
+ expect(printed, 'the description printed no example call').not.toBeNull();
296
+ return printed![1]!;
297
+ }
298
+
299
+ it('runs, and returns a value rather than an error', async () => {
300
+ const example = await printedExample();
301
+ const out = await chain(`return ${example};`);
302
+ expect(out.success).toBe(true);
303
+ expect(out.error).toBeUndefined();
304
+ expect(out.result).not.toBeNull();
305
+ });
306
+
307
+ it('runs on the MCP surfaces too, from the description THEY serve', async () => {
308
+ const chainTool = codeModeMetaTools(NAMESPACE, await catalog()).find(
309
+ (t) => t.name === 'call_tool_chain',
310
+ )!;
311
+ const printed = /works exactly as written: `return ([^`]+);`/.exec(chainTool.description!);
312
+ expect(printed).not.toBeNull();
313
+ const out = await mcpChain(`return ${printed![1]!};`);
314
+ expect(out.isError).toBeFalsy();
315
+ expect(JSON.parse(out.text)).toMatchObject({ success: true });
316
+ });
317
+
318
+ /**
319
+ * The fixture has teeth. If a missing `branch` were quietly accepted, the
320
+ * test above would pass for the wrong reason and the regression would be
321
+ * invisible again — so prove the refusal is real.
322
+ */
323
+ it('fails when a required argument is dropped, which is what the old example did', async () => {
324
+ const out = await chain("return KNOWLEDGE_BASE.read_file({ body: { path: 'x' } })");
325
+ expect(out.success).toBe(false);
326
+ expect(out.error).toContain('`branch` is required');
327
+ });
328
+
329
+ it('names a tool the catalog actually has, in the form the runtime binds', async () => {
330
+ const example = await printedExample();
331
+ const name = /^([\w.$]+)\(/.exec(example)![1]!;
332
+ const bound = await chain(`return typeof ${name};`);
333
+ expect(bound).toMatchObject({ success: true, result: 'function' });
334
+ });
335
+ });
@@ -86,7 +86,7 @@ describe('call_tool_chain image scrub', () => {
86
86
  callToolChain: vi.fn(async () => ({ result: { pic: sentinel, ok: true }, logs: [] as string[] })),
87
87
  } as unknown as CodeModeUtcpClient;
88
88
  const spill = { write: vi.fn(async () => ({ ref: '__tool_chain_spill__/x.json', bytes: 1 })) };
89
- const tool = createCallToolChainTool(chainClient, spill as never) as unknown as {
89
+ const tool = createCallToolChainTool(chainClient, spill as never, 'KNOWLEDGE_BASE') as unknown as {
90
90
  execute: (input: { code: string }) => Promise<unknown>;
91
91
  };
92
92
  const out = JSON.stringify(await tool.execute({ code: 'return 1' }));
@@ -98,6 +98,50 @@ describe('call_tool_chain image scrub', () => {
98
98
  });
99
99
  });
100
100
 
101
+ /**
102
+ * `call_tool_chain` promises a STRUCTURED answer for every outcome. The work
103
+ * past the runner is still fallible — the spill store writes to disk, and
104
+ * `JSON.stringify` can meet a value it cannot serialize — and an exception
105
+ * escaping `execute` reaches the agent as an unhandled tool failure, which is
106
+ * the dropped call this ticket is about.
107
+ */
108
+ describe('call_tool_chain when the result cannot be delivered', () => {
109
+ async function runWith(spill: { write: (json: string) => Promise<{ ref: string; bytes: number }> }, result: unknown) {
110
+ const { createCallToolChainTool } = await import('../code-mode.tool.js');
111
+ const chainClient = {
112
+ callToolChain: vi.fn(async () => ({ result, logs: ['[LOG] halfway'] as string[] })),
113
+ } as unknown as CodeModeUtcpClient;
114
+ const tool = createCallToolChainTool(chainClient, spill as never, 'KNOWLEDGE_BASE') as unknown as {
115
+ execute: (input: { code: string; max_output_size?: number }) => Promise<{
116
+ success: boolean;
117
+ error?: string;
118
+ logs?: string[];
119
+ }>;
120
+ };
121
+ return tool.execute({ code: 'return 1', max_output_size: 1_000 });
122
+ }
123
+
124
+ it('answers with the reason when the spill store cannot write', async () => {
125
+ const out = await runWith(
126
+ { write: vi.fn(async () => Promise.reject(new Error('ENOSPC: no space left on device'))) },
127
+ 'x'.repeat(2_000),
128
+ );
129
+ expect(out.success).toBe(false);
130
+ expect(out.error).toContain('ENOSPC');
131
+ // The chain itself ran, so its logs are the only trace of the work left.
132
+ expect(out.logs).toEqual(['[LOG] halfway']);
133
+ });
134
+
135
+ it('answers with the reason when the chain\'s value cannot be serialized', async () => {
136
+ // A BigInt, not a cycle: `omitImagePayloads` already replaces a cycle with
137
+ // `"[Circular]"`, so a cyclic result serializes fine and is not this case.
138
+ const out = await runWith({ write: vi.fn(async () => ({ ref: 'r', bytes: 1 })) }, { n: 1n });
139
+ expect(out.success).toBe(false);
140
+ expect(out.error).toMatch(/could not be returned/);
141
+ expect(out.error).toMatch(/BigInt/);
142
+ });
143
+ });
144
+
101
145
  /**
102
146
  * `merge_change_request` is retired from every agent tool set, the in-app
103
147
  * chat's included. A chain still calling it gets who merges now, not the
@@ -108,7 +152,7 @@ describe('call_tool_chain and a retired tool', () => {
108
152
 
109
153
  async function runWith(chainClient: CodeModeUtcpClient, code: string) {
110
154
  const { createCallToolChainTool } = await import('../code-mode.tool.js');
111
- const tool = createCallToolChainTool(chainClient, { write: vi.fn() } as never) as unknown as {
155
+ const tool = createCallToolChainTool(chainClient, { write: vi.fn() } as never, 'KNOWLEDGE_BASE') as unknown as {
112
156
  execute: (input: { code: string }) => Promise<{ success: boolean; error?: string; result?: unknown }>;
113
157
  };
114
158
  return tool.execute({ code });