@bevel-software/platform-core-backend 0.23.0 → 0.25.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 (238) 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 +13 -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 +95 -1
  64. package/dist/modules/database/migrate.d.ts.map +1 -1
  65. package/dist/modules/database/migrate.js +390 -2
  66. package/dist/modules/database/migrate.js.map +1 -1
  67. package/dist/modules/kb-fs/locking-filesystem.d.ts +17 -0
  68. package/dist/modules/kb-fs/locking-filesystem.d.ts.map +1 -1
  69. package/dist/modules/kb-fs/locking-filesystem.js +29 -0
  70. package/dist/modules/kb-fs/locking-filesystem.js.map +1 -1
  71. package/dist/modules/mcp/mcp.service.d.ts +8 -0
  72. package/dist/modules/mcp/mcp.service.d.ts.map +1 -1
  73. package/dist/modules/mcp/mcp.service.js +38 -8
  74. package/dist/modules/mcp/mcp.service.js.map +1 -1
  75. package/dist/modules/plugins/join-request-records.store.d.ts.map +1 -1
  76. package/dist/modules/plugins/join-request-records.store.js +7 -4
  77. package/dist/modules/plugins/join-request-records.store.js.map +1 -1
  78. package/dist/modules/tool-auth/external-api-key.service.d.ts.map +1 -1
  79. package/dist/modules/tool-auth/external-api-key.service.js +8 -2
  80. package/dist/modules/tool-auth/external-api-key.service.js.map +1 -1
  81. package/dist/modules/tool-manuals/tool-manuals.service.d.ts.map +1 -1
  82. package/dist/modules/tool-manuals/tool-manuals.service.js +30 -0
  83. package/dist/modules/tool-manuals/tool-manuals.service.js.map +1 -1
  84. package/dist/modules/tool-manuals/tool-manuals.tools.d.ts.map +1 -1
  85. package/dist/modules/tool-manuals/tool-manuals.tools.js +42 -31
  86. package/dist/modules/tool-manuals/tool-manuals.tools.js.map +1 -1
  87. package/dist/modules/tool-registry/description-length.d.ts +80 -0
  88. package/dist/modules/tool-registry/description-length.d.ts.map +1 -0
  89. package/dist/modules/tool-registry/description-length.js +108 -0
  90. package/dist/modules/tool-registry/description-length.js.map +1 -0
  91. package/dist/modules/workflow/git/git.service.d.ts +25 -0
  92. package/dist/modules/workflow/git/git.service.d.ts.map +1 -1
  93. package/dist/modules/workflow/git/git.service.js +40 -1
  94. package/dist/modules/workflow/git/git.service.js.map +1 -1
  95. package/dist/modules/workflow/pending-commits.service.d.ts.map +1 -1
  96. package/dist/modules/workflow/pending-commits.service.js +5 -1
  97. package/dist/modules/workflow/pending-commits.service.js.map +1 -1
  98. package/dist/modules/workflow/recovery-bot.d.ts.map +1 -1
  99. package/dist/modules/workflow/recovery-bot.js +7 -3
  100. package/dist/modules/workflow/recovery-bot.js.map +1 -1
  101. package/dist/modules/workflow/review-workflow/review-workflow.service.d.ts.map +1 -1
  102. package/dist/modules/workflow/review-workflow/review-workflow.service.js +12 -3
  103. package/dist/modules/workflow/review-workflow/review-workflow.service.js.map +1 -1
  104. package/dist/modules/workflow/workflow.service.d.ts.map +1 -1
  105. package/dist/modules/workflow/workflow.service.js +4 -1
  106. package/dist/modules/workflow/workflow.service.js.map +1 -1
  107. package/dist/modules/workspace/agent-upload.routes.d.ts +77 -0
  108. package/dist/modules/workspace/agent-upload.routes.d.ts.map +1 -0
  109. package/dist/modules/workspace/agent-upload.routes.js +210 -0
  110. package/dist/modules/workspace/agent-upload.routes.js.map +1 -0
  111. package/dist/modules/workspace/agent-upload.store.d.ts +284 -0
  112. package/dist/modules/workspace/agent-upload.store.d.ts.map +1 -0
  113. package/dist/modules/workspace/agent-upload.store.js +553 -0
  114. package/dist/modules/workspace/agent-upload.store.js.map +1 -0
  115. package/dist/modules/workspace/startup/steps/seed-tree.d.ts.map +1 -1
  116. package/dist/modules/workspace/startup/steps/seed-tree.js +3 -3
  117. package/dist/modules/workspace/startup/steps/seed-tree.js.map +1 -1
  118. package/dist/modules/workspace/startup/steps/template-source.d.ts +40 -0
  119. package/dist/modules/workspace/startup/steps/template-source.d.ts.map +1 -1
  120. package/dist/modules/workspace/startup/steps/template-source.js +46 -4
  121. package/dist/modules/workspace/startup/steps/template-source.js.map +1 -1
  122. package/dist/modules/workspace/upload-limits.d.ts +13 -0
  123. package/dist/modules/workspace/upload-limits.d.ts.map +1 -0
  124. package/dist/modules/workspace/upload-limits.js +13 -0
  125. package/dist/modules/workspace/upload-limits.js.map +1 -0
  126. package/dist/modules/workspace/workspace.routes.d.ts.map +1 -1
  127. package/dist/modules/workspace/workspace.routes.js +1 -1
  128. package/dist/modules/workspace/workspace.routes.js.map +1 -1
  129. package/dist/modules/workspace/workspace.service.d.ts +13 -0
  130. package/dist/modules/workspace/workspace.service.d.ts.map +1 -1
  131. package/dist/modules/workspace/workspace.service.js +61 -33
  132. package/dist/modules/workspace/workspace.service.js.map +1 -1
  133. package/dist/modules/workspace/workspace.tools.d.ts +11 -9
  134. package/dist/modules/workspace/workspace.tools.d.ts.map +1 -1
  135. package/dist/modules/workspace/workspace.tools.js +570 -134
  136. package/dist/modules/workspace/workspace.tools.js.map +1 -1
  137. package/dist/modules/workspace/write-denial.d.ts +0 -6
  138. package/dist/modules/workspace/write-denial.d.ts.map +1 -1
  139. package/dist/modules/workspace/write-denial.js +0 -6
  140. package/dist/modules/workspace/write-denial.js.map +1 -1
  141. package/dist/modules/workspace/zip-entry-rules.d.ts +114 -0
  142. package/dist/modules/workspace/zip-entry-rules.d.ts.map +1 -0
  143. package/dist/modules/workspace/zip-entry-rules.js +154 -0
  144. package/dist/modules/workspace/zip-entry-rules.js.map +1 -0
  145. package/dist/shared/column-crypto.d.ts +194 -0
  146. package/dist/shared/column-crypto.d.ts.map +1 -0
  147. package/dist/shared/column-crypto.js +144 -0
  148. package/dist/shared/column-crypto.js.map +1 -0
  149. package/dist/shared/token-crypto.d.ts.map +1 -1
  150. package/dist/shared/token-crypto.js +25 -1
  151. package/dist/shared/token-crypto.js.map +1 -1
  152. package/dist/tenancy/static-tenant-source.d.ts.map +1 -1
  153. package/dist/tenancy/static-tenant-source.js +1 -0
  154. package/dist/tenancy/static-tenant-source.js.map +1 -1
  155. package/dist/tenancy/tenant-secrets.d.ts +5 -1
  156. package/dist/tenancy/tenant-secrets.d.ts.map +1 -1
  157. package/dist/tenancy/tenant-secrets.js +4 -0
  158. package/dist/tenancy/tenant-secrets.js.map +1 -1
  159. package/kb-template/AGENTS.md +42 -0
  160. package/migrations/0016_pii_encryption.sql +20 -0
  161. package/migrations/meta/0016_snapshot.json +2327 -0
  162. package/migrations/meta/_journal.json +7 -0
  163. package/package.json +3 -3
  164. package/src/core/__tests__/lifecycle.test.ts +71 -4
  165. package/src/core/create-core-server.ts +21 -3
  166. package/src/core/create-core-services.ts +27 -1
  167. package/src/core/lifecycle.ts +19 -0
  168. package/src/core-config.ts +18 -0
  169. package/src/index.ts +25 -0
  170. package/src/modules/access/__tests__/users-db-double.ts +21 -12
  171. package/src/modules/access/access.routes.ts +4 -1
  172. package/src/modules/access/directory-sync-bot.ts +7 -3
  173. package/src/modules/agent-instructions/__tests__/agent-instructions.route.test.ts +8 -4
  174. package/src/modules/agent-instructions/__tests__/compose.test.ts +19 -10
  175. package/src/modules/agent-instructions/__tests__/shared-file-rules.test.ts +238 -0
  176. package/src/modules/agent-instructions/agent-instructions.routes.ts +12 -2
  177. package/src/modules/agent-instructions/compose.ts +50 -7
  178. package/src/modules/agent-instructions/index.ts +12 -0
  179. package/src/modules/agent-instructions/shared-file-rules.ts +314 -0
  180. package/src/modules/audit/agent-audit.service.ts +4 -2
  181. package/src/modules/auth/__tests__/account-deactivation.test.ts +2 -1
  182. package/src/modules/auth/__tests__/account-erasure.approval-gate.test.ts +6 -2
  183. package/src/modules/auth/__tests__/account.routes.test.ts +6 -3
  184. package/src/modules/auth/__tests__/auth.service.test.ts +3 -1
  185. package/src/modules/auth/account-erasure.service.ts +69 -18
  186. package/src/modules/auth/auth.service.ts +33 -23
  187. package/src/modules/code-mode/__tests__/chain-runtime.e2e.test.ts +335 -0
  188. package/src/modules/code-mode/__tests__/code-mode.tool.test.ts +46 -2
  189. package/src/modules/code-mode/code-mode.tool.ts +80 -34
  190. package/src/modules/database/__tests__/connection.test.ts +12 -0
  191. package/src/modules/database/__tests__/pii-backfill.pg.test.ts +780 -0
  192. package/src/modules/database/connection.ts +117 -0
  193. package/src/modules/database/core-schema.ts +81 -31
  194. package/src/modules/database/migrate.ts +540 -2
  195. package/src/modules/kb-fs/__tests__/locking-filesystem.test.ts +93 -0
  196. package/src/modules/kb-fs/locking-filesystem.ts +37 -0
  197. package/src/modules/mcp/__tests__/mcp.e2e.test.ts +4 -3
  198. package/src/modules/mcp/__tests__/mcp.service.test.ts +47 -7
  199. package/src/modules/mcp/mcp.service.ts +46 -7
  200. package/src/modules/plugins/join-request-records.store.ts +7 -4
  201. package/src/modules/tool-auth/external-api-key.service.ts +8 -2
  202. package/src/modules/tool-manuals/__tests__/tool-manuals.service.test.ts +151 -0
  203. package/src/modules/tool-manuals/tool-manuals.service.ts +37 -0
  204. package/src/modules/tool-manuals/tool-manuals.tools.ts +44 -31
  205. package/src/modules/tool-registry/__tests__/tool-description-length.test.ts +378 -0
  206. package/src/modules/tool-registry/description-length.ts +111 -0
  207. package/src/modules/workflow/git/__tests__/git.service.prFetchFailure.test.ts +170 -0
  208. package/src/modules/workflow/git/git.service.ts +47 -1
  209. package/src/modules/workflow/pending-commits.service.ts +5 -1
  210. package/src/modules/workflow/recovery-bot.ts +7 -3
  211. package/src/modules/workflow/review-workflow/__tests__/carry-approvals-forward.test.ts +4 -0
  212. package/src/modules/workflow/review-workflow/__tests__/erase-approver.test.ts +25 -3
  213. package/src/modules/workflow/review-workflow/review-workflow.service.ts +12 -3
  214. package/src/modules/workflow/workflow.service.ts +4 -1
  215. package/src/modules/workspace/__tests__/agent-uploads.test.ts +1604 -0
  216. package/src/modules/workspace/__tests__/escape-sequences.routes.test.ts +24 -14
  217. package/src/modules/workspace/__tests__/workspace.service.any-workspace-credentials.test.ts +156 -0
  218. package/src/modules/workspace/__tests__/workspace.service.replaced-repository.test.ts +77 -1
  219. package/src/modules/workspace/__tests__/workspace.service.test.ts +57 -0
  220. package/src/modules/workspace/__tests__/workspace.tools.agents-file.test.ts +39 -36
  221. package/src/modules/workspace/__tests__/workspace.tools.test.ts +196 -46
  222. package/src/modules/workspace/agent-upload.routes.ts +214 -0
  223. package/src/modules/workspace/agent-upload.store.ts +668 -0
  224. package/src/modules/workspace/startup/steps/__tests__/steps.test.ts +9 -9
  225. package/src/modules/workspace/startup/steps/seed-tree.ts +3 -6
  226. package/src/modules/workspace/startup/steps/template-source.ts +53 -5
  227. package/src/modules/workspace/upload-limits.ts +12 -0
  228. package/src/modules/workspace/workspace.routes.ts +1 -2
  229. package/src/modules/workspace/workspace.service.ts +63 -37
  230. package/src/modules/workspace/workspace.tools.ts +647 -148
  231. package/src/modules/workspace/write-denial.ts +0 -8
  232. package/src/modules/workspace/zip-entry-rules.ts +173 -0
  233. package/src/shared/__tests__/column-crypto.test.ts +217 -0
  234. package/src/shared/column-crypto.ts +218 -0
  235. package/src/shared/token-crypto.ts +28 -1
  236. package/src/tenancy/__tests__/static-tenant-source.test.ts +4 -0
  237. package/src/tenancy/static-tenant-source.ts +1 -0
  238. package/src/tenancy/tenant-secrets.ts +5 -1
@@ -0,0 +1,668 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { promises as fs } from 'node:fs';
3
+ import path from 'node:path';
4
+ import AdmZip from 'adm-zip';
5
+ import { logger } from '../../shared/logging.js';
6
+ import { MAX_UPLOAD_BYTES } from './upload-limits.js';
7
+
8
+ const log = logger('agent-uploads');
9
+
10
+ /** How long an issued token, and the bytes sent against it, stay usable. */
11
+ export const UPLOAD_TOKEN_TTL_MS = 15 * 60 * 1000; // 15 minutes
12
+
13
+ /** How often the store looks for tokens that have expired. */
14
+ const SWEEP_INTERVAL_MS = 60 * 1000;
15
+
16
+ /**
17
+ * How long past its expiry a CLAIMED record is pinned against the sweep.
18
+ *
19
+ * An apply holds its claim while it resolves the branch (which may clone),
20
+ * reads the bytes, judges every path and commits — work that can outlast a
21
+ * token whose TTL was nearly up when the apply started. Deleting the source
22
+ * mid-apply would make the commit land short with no refusal naming the
23
+ * reason, so a claim keeps its bytes alive. The grace is what stops that from
24
+ * being forever: an apply that neither consumed nor released within it has
25
+ * died with its process (the record is in memory, so there is no third
26
+ * possibility), and the bytes are reclaimed.
27
+ */
28
+ const CLAIM_GRACE_MS = 10 * 60 * 1000; // 10 minutes
29
+
30
+ /**
31
+ * THE one refusal for every way a token can fail to be usable: it was never
32
+ * issued, it has already been applied, it has expired, or it belongs to
33
+ * somebody else. One sentence for all four, deliberately — an answer that
34
+ * distinguished "no such token" from "not yours" would let anyone holding a
35
+ * guess learn which guesses exist, and the token is the whole credential this
36
+ * route has.
37
+ */
38
+ export const UPLOAD_TOKEN_REFUSAL =
39
+ 'That upload token cannot be used: it is unknown, already applied, expired, or was issued to someone else. ' +
40
+ 'Call `request_file_upload` for a new one.';
41
+
42
+ /**
43
+ * How many tokens one user may hold open at once.
44
+ *
45
+ * A token is permission to put the deployment's whole upload limit on its
46
+ * disk for a TTL, and to hold a connection open while it arrives. Without a
47
+ * bound, one caller asks for a hundred and sends against all of them
48
+ * together. Ten is far more than the route's own use needs — one token carries
49
+ * a zip of any number of files — and a token is given back the moment it is
50
+ * applied or expires.
51
+ */
52
+ export const MAX_OPEN_UPLOADS_PER_USER = 10;
53
+
54
+ /** The refusal an over-limit upload gets, naming the limit that applied. */
55
+ export function overLimit(bytes: number, maxBytes: number): string {
56
+ return (
57
+ `That upload is ${bytes} bytes, over this deployment's ${maxBytes} byte upload limit. ` +
58
+ 'Send a smaller file, or split it across several uploads.'
59
+ );
60
+ }
61
+
62
+ /** What an upload with no body is told. */
63
+ const EMPTY_UPLOAD =
64
+ 'That upload carried no bytes. Send the file as the request body — e.g. ' +
65
+ '`curl -X POST --data-binary @<file> "<uploadUrl>?filename=<name>"`.';
66
+
67
+ /** A refusal with the HTTP status the upload route and the apply tool both answer. */
68
+ export class UploadTokenError extends Error {
69
+ constructor(
70
+ message: string,
71
+ readonly status: number,
72
+ ) {
73
+ super(message);
74
+ this.name = 'UploadTokenError';
75
+ }
76
+ }
77
+
78
+ /** What `request_file_upload` answers: where to send the bytes, and the terms. */
79
+ export interface IssuedUpload {
80
+ /** The absolute URL the bytes are POSTed to. Carries the token in its path. */
81
+ uploadUrl: string;
82
+ /**
83
+ * The token itself — what `apply_file_upload` takes, and the credential the
84
+ * upload route is authenticated by.
85
+ *
86
+ * Named separately from `uploadUrl` for two reasons: the apply needs it on
87
+ * its own, and the route takes it either way round. The bytes can go to
88
+ * `uploadUrl`, which carries the token in its last path segment, or to that
89
+ * address WITHOUT that segment with the token in the `x-upload-token`
90
+ * header — the spelling for a caller that would rather its credential not
91
+ * land in an access log or a shell history on the way.
92
+ */
93
+ token: string;
94
+ /** ISO-8601 instant after which the token and any bytes sent with it are gone. */
95
+ expiresAt: string;
96
+ /** Seconds from now until `expiresAt`, so a caller need not parse the date. */
97
+ expiresInSeconds: number;
98
+ /** The largest upload this deployment accepts, in bytes. */
99
+ maxBytes: number;
100
+ }
101
+
102
+ /** What the upload route answers, and what `apply_file_upload` reads back. */
103
+ export interface ReceivedUpload {
104
+ /** The name the sender gave the file. For a single file, the name it lands under. */
105
+ filename: string;
106
+ bytes: number;
107
+ /** `zip` when the name ends in `.zip` and the bytes parse as an archive. */
108
+ kind: 'file' | 'zip';
109
+ /** Present for a zip: how many members the archive holds. */
110
+ entries?: number;
111
+ }
112
+
113
+ /** A received upload, with the bytes on disk, as `apply_file_upload` claims it. */
114
+ export interface ClaimedUpload extends ReceivedUpload {
115
+ /** Absolute path of the stored bytes — OUTSIDE every workspace. */
116
+ absolutePath: string;
117
+ }
118
+
119
+ interface UploadRecord {
120
+ /** The file name under the store's root. Never derived from the sender's name. */
121
+ id: string;
122
+ userId: string;
123
+ expiresAt: number;
124
+ received?: ReceivedUpload;
125
+ /**
126
+ * Taken by an upload that is still writing its bytes. Set BEFORE the first
127
+ * `await` in {@link AgentUploadStore.receive}, so two uploads arriving at
128
+ * once cannot both pass the one-file-per-token check and then race each
129
+ * other's bytes onto the same path. Cleared only when a receive fails.
130
+ */
131
+ attaching: boolean;
132
+ /** Held by an apply that is running: a second apply finds the token in use. */
133
+ claimed: boolean;
134
+ /**
135
+ * When the apply holding this record claimed it. An expired record that is
136
+ * CLAIMED is pinned rather than swept — the apply is reading those bytes —
137
+ * until the claim itself looks abandoned (see {@link CLAIM_GRACE_MS}).
138
+ */
139
+ claimedAt?: number;
140
+ }
141
+
142
+ export interface AgentUploadStoreOptions {
143
+ /** Directory the bytes are written to. A sibling of `workspacesRoot`, never inside one. */
144
+ root: string;
145
+ /** Absolute base URL of this deployment's API, e.g. `https://core.example.com`. */
146
+ publicBaseUrl: string;
147
+ /** Token prefix, so a leaked credential can be recognised by shape. */
148
+ tokenPrefix?: string;
149
+ ttlMs?: number;
150
+ maxBytes?: number;
151
+ /** How many tokens one user may hold open at once. Defaults to {@link MAX_OPEN_UPLOADS_PER_USER}. */
152
+ maxOpenPerUser?: number;
153
+ /**
154
+ * How the staging root is listed. Test seam — defaults to `fs.readdir`.
155
+ *
156
+ * The ONE thing about the sweep a suite needs to control. Whether a token
157
+ * issued and uploaded while the sweep is running survives depends on the
158
+ * order of two steps inside {@link AgentUploadStore.sweepNow} — the listing
159
+ * and the live-id set — and the gap between them is a filesystem round-trip
160
+ * no test can otherwise sit inside. Given a listing it can hold open, a test
161
+ * can put a whole upload in that gap and assert the bytes are still there.
162
+ */
163
+ listRoot?: (root: string) => Promise<string[]>;
164
+ }
165
+
166
+ /**
167
+ * The upload tokens an agent lands files with, and the bytes sent against
168
+ * them.
169
+ *
170
+ * An agent that wants to put 27 files on a branch has no way to do it through
171
+ * a tool argument: the content would have to pass through the model, which
172
+ * truncates, mangles escape characters and cannot carry a PNG at all. So the
173
+ * bytes take a route of their own — this store issues a one-time token, the
174
+ * upload route attaches bytes to it, and `apply_file_upload` lands them.
175
+ *
176
+ * Three properties the whole design rests on, because the upload route is the
177
+ * one endpoint on this server that authenticates by a token alone:
178
+ *
179
+ * - **Unguessable.** 32 random bytes, base64url. Nothing about the token is
180
+ * derived from the user, the time or a counter.
181
+ * - **Never stored in the clear.** Records are keyed by the token's SHA-256,
182
+ * so the store's own memory (and anything that dumps it) holds no usable
183
+ * credential.
184
+ * - **Bound and single-use.** A record carries the id of the user it was
185
+ * issued to and is consumed by the apply that lands it; a second apply, an
186
+ * apply by anyone else, and an apply after the expiry all meet
187
+ * {@link UPLOAD_TOKEN_REFUSAL}.
188
+ *
189
+ * And the bytes land in `root` — a directory beside the workspaces root, not
190
+ * inside one. No file tool can reach it: every workspace path is resolved
191
+ * against a branch's checkout, so there is no spelling of a tool argument that
192
+ * names a file in here. An upload nobody applies is deleted when its token
193
+ * expires (see {@link startSweeping}), so an abandoned drop costs disk for at
194
+ * most one TTL.
195
+ */
196
+ export class AgentUploadStore {
197
+ private readonly records = new Map<string, UploadRecord>();
198
+ private readonly root: string;
199
+ private readonly publicBaseUrl: string;
200
+ private readonly tokenPrefix: string;
201
+ private readonly ttlMs: number;
202
+ private readonly listRoot: (root: string) => Promise<string[]>;
203
+ readonly maxBytes: number;
204
+ private readonly maxOpenPerUser: number;
205
+ private sweepTimer: ReturnType<typeof setInterval> | null = null;
206
+ /** The sweep in flight, so a shutdown can wait for it — see {@link drainSweep}. */
207
+ private sweeping: Promise<void> | null = null;
208
+ /** Set by {@link stopSweeping}: no further sweep deletes anything. */
209
+ private stopped = false;
210
+
211
+ constructor(options: AgentUploadStoreOptions) {
212
+ this.root = options.root;
213
+ this.publicBaseUrl = options.publicBaseUrl.replace(/\/+$/, '');
214
+ this.tokenPrefix = options.tokenPrefix ?? '';
215
+ this.ttlMs = options.ttlMs ?? UPLOAD_TOKEN_TTL_MS;
216
+ this.listRoot = options.listRoot ?? ((root) => fs.readdir(root));
217
+ this.maxBytes = options.maxBytes ?? MAX_UPLOAD_BYTES;
218
+ this.maxOpenPerUser = options.maxOpenPerUser ?? MAX_OPEN_UPLOADS_PER_USER;
219
+ }
220
+
221
+ /** The URL a token's bytes are sent to. The one spelling of this route's address. */
222
+ uploadUrlFor(token: string): string {
223
+ return `${this.publicBaseUrl}/api/agent/uploads/${encodeURIComponent(token)}`;
224
+ }
225
+
226
+ /**
227
+ * Mint a token for `user` and answer the terms it is good for. Nothing is
228
+ * written to disk yet — a token nobody uploads against costs one map entry
229
+ * until the sweep drops it.
230
+ */
231
+ issue(user: { id: string }): IssuedUpload {
232
+ // Counted over what the user still HOLDS: a token that can still be used,
233
+ // and one whose expiry has passed but whose work has not ended — an upload
234
+ // still arriving, an apply still reading. Those keep a connection or a file
235
+ // open exactly as a live token does, so letting them fall out of the count
236
+ // at expiry would let a caller keep ten slow uploads going and ask for ten
237
+ // more. An expired record that is doing nothing is waiting for the sweep,
238
+ // and is not one the user holds.
239
+ const now = Date.now();
240
+ let open = 0;
241
+ for (const record of this.records.values()) {
242
+ if (record.userId !== user.id) continue;
243
+ if (record.expiresAt > now || this.pinned(record, now)) open += 1;
244
+ }
245
+ if (open >= this.maxOpenPerUser) {
246
+ throw new UploadTokenError(
247
+ `You already hold ${open} upload tokens, the most one user may have open at once. Apply one of them with ` +
248
+ '`apply_file_upload`, or wait for one to expire, then ask again. One token carries a zip of any number of files.',
249
+ 429,
250
+ );
251
+ }
252
+ const token = this.tokenPrefix + randomBytes(32).toString('base64url');
253
+ const expiresAt = Date.now() + this.ttlMs;
254
+ this.records.set(hash(token), {
255
+ id: `upload-${Date.now()}-${randomBytes(8).toString('hex')}`,
256
+ userId: user.id,
257
+ expiresAt,
258
+ attaching: false,
259
+ claimed: false,
260
+ });
261
+ // AFTER the record exists, not before. The first sweep runs the moment the
262
+ // timer starts, and started from an empty map it would be a sweep that
263
+ // believes nothing is live — this token's own id included.
264
+ this.startSweeping();
265
+ return {
266
+ uploadUrl: this.uploadUrlFor(token),
267
+ token,
268
+ expiresAt: new Date(expiresAt).toISOString(),
269
+ expiresInSeconds: Math.round(this.ttlMs / 1000),
270
+ maxBytes: this.maxBytes,
271
+ };
272
+ }
273
+
274
+ /**
275
+ * Store the bytes of `body` against `token` and say what was received. One
276
+ * file per token: a second upload against the same token is refused, so a
277
+ * token cannot be used to keep replacing bytes an apply is about to land.
278
+ *
279
+ * WRITTEN AS THEY ARRIVE, never gathered first. The body is up to the
280
+ * deployment's whole upload limit, and this is the one route a caller can
281
+ * send to without a session: held in memory, a handful of uploads at once
282
+ * cost the process several times that limit each (the chunks, the buffer
283
+ * they were joined into, the archive read over it). Streamed, an upload in
284
+ * flight costs one chunk.
285
+ *
286
+ * A name ending in `.zip` is read as an archive HERE, once the bytes are on
287
+ * disk, so the answer can carry the entry count and so a corrupt archive is
288
+ * refused while the caller is still holding the file — rather than at apply
289
+ * time, when its token would already be spent.
290
+ */
291
+ async receive(
292
+ token: string,
293
+ filename: string,
294
+ body: AsyncIterable<Buffer | string>,
295
+ ): Promise<ReceivedUpload> {
296
+ const record = this.openRecord(token);
297
+ // RESERVED FIRST, before any `await`: two uploads arriving at once would
298
+ // otherwise both find the token open, both write, and the apply would land
299
+ // whichever set of bytes finished last — against a token whose answer
300
+ // described the other one.
301
+ record.attaching = true;
302
+ const stored = path.join(this.root, record.id);
303
+ let bytes = 0;
304
+ const received: ReceivedUpload = { filename, bytes: 0, kind: 'file' };
305
+ try {
306
+ await fs.mkdir(this.root, { recursive: true });
307
+ const file = await fs.open(stored, 'w');
308
+ try {
309
+ for await (const chunk of body) {
310
+ const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
311
+ bytes += buf.byteLength;
312
+ // The real total, counted as it arrives: a `content-length` is the
313
+ // sender's claim, and a chunked body makes none.
314
+ if (bytes > this.maxBytes) throw new UploadTokenError(overLimit(bytes, this.maxBytes), 413);
315
+ // To the last byte: one `write` may put down only part of what it
316
+ // was handed and say so in `bytesWritten`, and a chunk counted as
317
+ // received while half of it is on disk would land a file shorter
318
+ // than the size the answer names.
319
+ for (let written = 0; written < buf.byteLength; ) {
320
+ written += (await file.write(buf, written, buf.byteLength - written)).bytesWritten;
321
+ }
322
+ }
323
+ } finally {
324
+ await file.close();
325
+ }
326
+ if (bytes === 0) throw new UploadTokenError(EMPTY_UPLOAD, 400);
327
+ received.bytes = bytes;
328
+ if (filename.toLowerCase().endsWith('.zip')) {
329
+ try {
330
+ received.entries = new AdmZip(stored).getEntries().length;
331
+ } catch (err) {
332
+ throw new UploadTokenError(
333
+ `"${filename}" is not a readable .zip archive: ${err instanceof Error ? err.message : String(err)}`,
334
+ 422,
335
+ );
336
+ }
337
+ received.kind = 'zip';
338
+ }
339
+ } catch (err) {
340
+ // Nothing was received, so the token is open again: the sender may retry
341
+ // with the same one rather than ask for another. Whatever part of the
342
+ // body reached the disk goes now, rather than at the next sweep.
343
+ await this.remove(record.id);
344
+ record.attaching = false;
345
+ throw err;
346
+ }
347
+ // THE TTL MAY HAVE PASSED while the bytes were arriving — a 40 MB upload
348
+ // over a slow link takes real time, and the token was issued before it
349
+ // started. The record was pinned against the sweep throughout (see
350
+ // {@link pinned}), so neither it nor the file could be deleted under the
351
+ // write; but an expired token cannot be applied, so answering "received"
352
+ // would hand the sender a success it can do nothing with. The refusal is
353
+ // the honest answer, and the bytes go with it rather than waiting for a
354
+ // sweep to notice.
355
+ if (record.expiresAt <= Date.now()) {
356
+ this.records.delete(hash(token));
357
+ await this.remove(record.id);
358
+ throw new UploadTokenError(UPLOAD_TOKEN_REFUSAL, 404);
359
+ }
360
+ record.received = received;
361
+ return received;
362
+ }
363
+
364
+ /**
365
+ * Refuse `token` if it cannot accept bytes — unknown, expired, somebody
366
+ * else's doing, or already holding a file — and answer its record if it can.
367
+ *
368
+ * Exists as its own step so the upload route can ask BEFORE it reads the
369
+ * body. The route is the one endpoint here authenticated by a token alone,
370
+ * and buffering up to the deployment's whole upload limit for an invented
371
+ * token would let a handful of concurrent requests spend the process's
372
+ * memory on bytes that were never going to be stored.
373
+ */
374
+ assertOpen(token: string): void {
375
+ this.openRecord(token);
376
+ }
377
+
378
+ /** {@link assertOpen}, with the record it found — the store's own view of it. */
379
+ private openRecord(token: string): UploadRecord {
380
+ const record = this.find(token);
381
+ if (record.received !== undefined || record.attaching) {
382
+ throw new UploadTokenError(UPLOAD_TOKEN_REFUSAL, 404);
383
+ }
384
+ return record;
385
+ }
386
+
387
+ /**
388
+ * Hold `token` for an apply by `userId`, and answer where its bytes are.
389
+ *
390
+ * A CLAIM rather than a consume, because an apply can be refused whole —
391
+ * the destination is on a protected branch the caller may not write, the
392
+ * archive turned out unreadable — and a token spent on a refusal would make
393
+ * the agent send the same 40 MB again to try a different destination. The
394
+ * claim is what keeps it single-use meanwhile: a second apply arriving while
395
+ * the first runs finds the token in use and is refused. The caller
396
+ * {@link consume}s it once an answer exists, or {@link release}s it on a
397
+ * refusal that landed nothing.
398
+ */
399
+ claim(token: string, userId: string): ClaimedUpload {
400
+ const record = this.find(token);
401
+ if (record.userId !== userId || record.claimed || record.received === undefined) {
402
+ throw new UploadTokenError(UPLOAD_TOKEN_REFUSAL, 404);
403
+ }
404
+ record.claimed = true;
405
+ record.claimedAt = Date.now();
406
+ return { ...record.received, absolutePath: path.join(this.root, record.id) };
407
+ }
408
+
409
+ /** Give a claimed token back, unused — the apply refused without landing anything. */
410
+ release(token: string): void {
411
+ const record = this.records.get(hash(token));
412
+ if (record) {
413
+ record.claimed = false;
414
+ record.claimedAt = undefined;
415
+ }
416
+ }
417
+
418
+ /** Spend the token and delete its bytes. Idempotent. */
419
+ async consume(token: string): Promise<void> {
420
+ const key = hash(token);
421
+ const record = this.records.get(key);
422
+ if (!record) return;
423
+ this.records.delete(key);
424
+ await this.remove(record.id);
425
+ }
426
+
427
+ /**
428
+ * Delete every record whose token has expired, with the bytes it was
429
+ * holding — then delete any file in the root that no LIVE record claims and
430
+ * that has outlived every token that could name it.
431
+ *
432
+ * The second half is what makes the first one true. A process killed between
433
+ * the write and the apply leaves a file no map will ever mention again, and
434
+ * sweeping by what the records DON'T name is the honest reading of the
435
+ * promise: an upload nobody applied does not stay. By AGE rather than at
436
+ * once, because a file this map does not name may be another process's (see
437
+ * the loop below).
438
+ *
439
+ * ONE record is kept past its expiry: one an apply has CLAIMED. Those bytes
440
+ * are being read right now, and a sweep that deleted them would make the
441
+ * commit land short of what the answer promised. The pin lasts
442
+ * {@link CLAIM_GRACE_MS}, after which a claim nobody consumed or released
443
+ * belongs to a dead process and is reclaimed.
444
+ */
445
+ async sweepNow(): Promise<void> {
446
+ if (this.stopped) return;
447
+ const now = Date.now();
448
+ for (const [key, record] of [...this.records]) {
449
+ if (record.expiresAt > now) continue;
450
+ if (this.pinned(record, now)) continue;
451
+ this.records.delete(key);
452
+ await this.remove(record.id);
453
+ }
454
+ let names: string[];
455
+ try {
456
+ names = await this.listRoot(this.root);
457
+ } catch {
458
+ return; // root not created yet, or unreadable — nothing to reclaim
459
+ }
460
+ // Every id a live record is holding — including one whose bytes have not
461
+ // arrived yet, so an upload in flight is never swept out from under itself,
462
+ // and one an apply has pinned past its expiry.
463
+ //
464
+ // Read AFTER the directory, never before. The gap between the two is a
465
+ // real one — the readdir is a filesystem round-trip, and this process
466
+ // serves other requests across it — so a token issued and uploaded during
467
+ // that gap would appear in `names` while a set taken earlier had never
468
+ // heard of it, and the sweep would delete bytes somebody had just been
469
+ // told were received. Taken afterwards, the set is a superset of what the
470
+ // listing could possibly name.
471
+ const live = new Set([...this.records.values()].map((r) => r.id));
472
+ for (const name of names) {
473
+ // Asked again per name: a stop (an evicted tenant, a shutdown) that
474
+ // landed while this sweep was reading the directory must not go on to
475
+ // delete files a replacement store may already have issued ids for.
476
+ if (this.stopped) return;
477
+ if (live.has(name)) continue;
478
+ // A file this map does not name is not necessarily nobody's. The records
479
+ // are ONE PROCESS's memory, and two processes share this directory
480
+ // whenever a deployment restarts by starting the new one before the old
481
+ // one has stopped: to each, the other's uploads are files no record
482
+ // names. So such a file goes only once it is older than any token could
483
+ // still be good for — its TTL, and the grace an apply holding it is
484
+ // given. A process that died leaves its files for that long and no
485
+ // longer; a process that is alive never loses one in use.
486
+ if (await this.outlivedEveryToken(name, now)) await this.remove(name);
487
+ }
488
+ }
489
+
490
+ /**
491
+ * Whether the stored file `name` is older than any token that could still be
492
+ * naming it, in this process or another. A file that cannot be examined is
493
+ * left for the next sweep rather than judged.
494
+ */
495
+ private async outlivedEveryToken(name: string, now: number): Promise<boolean> {
496
+ try {
497
+ const { mtimeMs } = await fs.stat(path.join(this.root, name));
498
+ return now - mtimeMs > this.ttlMs + CLAIM_GRACE_MS;
499
+ } catch {
500
+ return false;
501
+ }
502
+ }
503
+
504
+ /**
505
+ * Whether an expired record is held open by work that is still running:
506
+ * an UPLOAD still writing its bytes, or an APPLY still reading them.
507
+ *
508
+ * Both windows can outlast a TTL — a large upload over a slow link, an apply
509
+ * that clones a branch before it reads — and in both the record's own file is
510
+ * being written or read right now. A sweep that deleted either would leave a
511
+ * file no map mentions (the upload writes after the delete) or an apply
512
+ * reading a path that has gone. The apply's pin has a grace, because a claim
513
+ * can be abandoned by a process that dies; the upload's needs none, because
514
+ * `receive` always ends — it clears `attaching` on failure and sets
515
+ * `received` on success, and one whose TTL passed meanwhile deletes the
516
+ * record itself rather than leaving it pinned.
517
+ */
518
+ private pinned(record: UploadRecord, now: number): boolean {
519
+ if (record.attaching && record.received === undefined) return true;
520
+ return record.claimed && now - (record.claimedAt ?? now) < CLAIM_GRACE_MS;
521
+ }
522
+
523
+ /**
524
+ * Sweep now, and keep sweeping. Started by the first {@link issue} rather
525
+ * than at boot, so a deployment nobody uploads to runs no timer; idempotent,
526
+ * and the timer is `unref`'d because nothing here is worth keeping a process
527
+ * alive for — the records are in memory and go with it.
528
+ *
529
+ * The first sweep runs IMMEDIATELY, not one interval later, because the
530
+ * records are in memory: a process that restarted holds no record of what
531
+ * the previous one stored, and what that one left behind long enough ago
532
+ * has no reason to wait a further interval.
533
+ */
534
+ startSweeping(intervalMs: number = SWEEP_INTERVAL_MS): void {
535
+ if (this.sweepTimer) return;
536
+ this.stopped = false;
537
+ this.sweep();
538
+ this.sweepTimer = setInterval(() => this.sweep(), intervalMs);
539
+ this.sweepTimer.unref?.();
540
+ }
541
+
542
+ /**
543
+ * Stop sweeping, for good: the timer is cleared AND a sweep already running
544
+ * abandons the rest of its work.
545
+ *
546
+ * Both halves matter when a graph is stopped — a tenant evicted, the process
547
+ * shutting down. The root is this tenant's, and a reactivation builds a new
548
+ * store over the same directory with an empty record map: a sweep left
549
+ * running from the old store would find the new store's files named by no
550
+ * record of ITS own and delete them, under an apply that is about to read
551
+ * them. {@link drainSweep} is how a caller waits for the abandonment to
552
+ * actually have happened.
553
+ */
554
+ stopSweeping(): void {
555
+ this.stopped = true;
556
+ if (this.sweepTimer) clearInterval(this.sweepTimer);
557
+ this.sweepTimer = null;
558
+ }
559
+
560
+ /** Wait for the sweep in flight, if any. Pairs with {@link stopSweeping} on shutdown. */
561
+ async drainSweep(): Promise<void> {
562
+ await this.sweeping;
563
+ }
564
+
565
+ /** One sweep, with its failure logged and its promise kept for {@link drainSweep}. */
566
+ private sweep(): void {
567
+ const running = this.sweepNow()
568
+ .catch((err: unknown) => {
569
+ log.warn('could not sweep expired uploads:', { err });
570
+ })
571
+ .finally(() => {
572
+ if (this.sweeping === running) this.sweeping = null;
573
+ });
574
+ this.sweeping = running;
575
+ }
576
+
577
+ /** The live record for `token`, or the one refusal. Expiry is judged here. */
578
+ private find(token: string): UploadRecord {
579
+ const key = hash(token);
580
+ const record = this.records.get(key);
581
+ if (!record) throw new UploadTokenError(UPLOAD_TOKEN_REFUSAL, 404);
582
+ const now = Date.now();
583
+ if (record.expiresAt <= now) {
584
+ // Expired either way — but a record an apply is still reading keeps its
585
+ // bytes (and its map entry) until that apply ends, for the reason
586
+ // {@link sweepNow} gives. The refusal is the same; only the deletion waits.
587
+ if (!this.pinned(record, now)) {
588
+ this.records.delete(key);
589
+ void this.remove(record.id);
590
+ }
591
+ throw new UploadTokenError(UPLOAD_TOKEN_REFUSAL, 404);
592
+ }
593
+ return record;
594
+ }
595
+
596
+ /** Best-effort delete of one stored upload. Never throws. */
597
+ private async remove(id: string): Promise<void> {
598
+ try {
599
+ await fs.rm(path.join(this.root, id), { force: true });
600
+ } catch (err) {
601
+ log.warn(`could not delete the stored upload "${id}":`, { err });
602
+ }
603
+ }
604
+ }
605
+
606
+ function hash(token: string): string {
607
+ return createHash('sha256').update(token).digest('hex');
608
+ }
609
+
610
+ /**
611
+ * Refuse a boot whose upload root is not OUTSIDE every workspace.
612
+ *
613
+ * The whole safety of this route rests on where the bytes land: they are a
614
+ * buffer somebody sent, judged by nothing until `apply_file_upload` judges each
615
+ * path against a branch. A root configured inside `workspacesRoot` would put
616
+ * that unjudged buffer where the file tools read — `read_file`, `grep`, the
617
+ * download route — bypassing the access and platform-file rules the apply
618
+ * exists to apply. The invariant is documented on `AGENT_UPLOADS_ROOT`; this is
619
+ * it checked, at boot, naming the variable, rather than trusted.
620
+ *
621
+ * Both directions and both spellings: equal paths, either containing the
622
+ * other, and the real paths, so a root that is a LINK into the workspaces tree
623
+ * is refused too.
624
+ */
625
+ export async function assertUploadsRootOutsideWorkspaces(
626
+ uploadsRoot: string,
627
+ workspacesRoot: string,
628
+ ): Promise<void> {
629
+ for (const [uploads, workspaces] of [
630
+ [path.resolve(uploadsRoot), path.resolve(workspacesRoot)],
631
+ [await realBase(uploadsRoot), await realBase(workspacesRoot)],
632
+ ]) {
633
+ if (uploads === workspaces || contains(workspaces, uploads) || contains(uploads, workspaces)) {
634
+ throw new Error(
635
+ `AGENT_UPLOADS_ROOT ("${uploadsRoot}") must be outside WORKSPACES_ROOT ("${workspacesRoot}"): uploaded ` +
636
+ 'bytes are staged there before any access or platform-file rule has judged them, so a root inside a ' +
637
+ 'workspace would let the file tools read them. Point it at a sibling directory.',
638
+ );
639
+ }
640
+ }
641
+ }
642
+
643
+ /** Whether `child` is inside `parent`. Paths already resolved. */
644
+ function contains(parent: string, child: string): boolean {
645
+ return child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep);
646
+ }
647
+
648
+ /**
649
+ * `dir` with every link on it resolved — as far as it exists. Neither root is
650
+ * required to exist yet (the store makes its own on the first upload), so the
651
+ * deepest existing ancestor is resolved and the missing rest joined back on:
652
+ * a link anywhere along the part that DOES exist is what could redirect the
653
+ * one into the other.
654
+ */
655
+ async function realBase(dir: string): Promise<string> {
656
+ let existing = path.resolve(dir);
657
+ const rest: string[] = [];
658
+ for (;;) {
659
+ try {
660
+ return path.join(await fs.realpath(existing), ...rest);
661
+ } catch {
662
+ const up = path.dirname(existing);
663
+ if (up === existing) return path.join(existing, ...rest);
664
+ rest.unshift(path.basename(existing));
665
+ existing = up;
666
+ }
667
+ }
668
+ }