@tangle-network/agent-app 0.60.250 → 0.60.251

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 (222) hide show
  1. package/dist/DesignCanvas-L6J72JQ2.js +15 -0
  2. package/dist/DesignCanvasEditor-QFQD63MR.js +18 -0
  3. package/dist/agent-enrollment/drizzle.js +3 -3
  4. package/dist/agent-enrollment/index.js +3 -3
  5. package/dist/app-auth/drizzle.d.ts +561 -0
  6. package/dist/app-auth/drizzle.js +72 -0
  7. package/dist/app-auth/drizzle.js.map +1 -0
  8. package/dist/app-auth/index.js +5 -3
  9. package/dist/app-auth/index.js.map +1 -1
  10. package/dist/app-oauth/drizzle.d.ts +2080 -0
  11. package/dist/app-oauth/drizzle.js +161 -0
  12. package/dist/app-oauth/drizzle.js.map +1 -0
  13. package/dist/app-oauth/index.d.ts +4 -0
  14. package/dist/app-oauth/index.js +8 -222
  15. package/dist/app-oauth/index.js.map +1 -1
  16. package/dist/app-oauth/issuer.d.ts +133 -0
  17. package/dist/app-oauth/issuer.js +247 -0
  18. package/dist/app-oauth/issuer.js.map +1 -0
  19. package/dist/assistant/index.js +13 -13
  20. package/dist/chat-react/index.js +4 -4
  21. package/dist/chat-routes/index.js +37 -67
  22. package/dist/chat-routes/index.js.map +1 -1
  23. package/dist/chat-routes/promote-file-part.d.ts +2 -3
  24. package/dist/chat-store/index.js +4 -4
  25. package/dist/{chunk-MY3EJJ6Y.js → chunk-4FEH6266.js} +2 -2
  26. package/dist/{chunk-5Y7Z5G3Y.js → chunk-4GCPADYG.js} +20 -336
  27. package/dist/chunk-4GCPADYG.js.map +1 -0
  28. package/dist/{chunk-X556WVBG.js → chunk-4ZSLX3LY.js} +2 -2
  29. package/dist/chunk-57XPEL7X.js +26 -0
  30. package/dist/chunk-57XPEL7X.js.map +1 -0
  31. package/dist/chunk-6Z7TZVKZ.js +26 -0
  32. package/dist/chunk-6Z7TZVKZ.js.map +1 -0
  33. package/dist/{chunk-7KKOFMLD.js → chunk-AWIQQEFP.js} +1 -1
  34. package/dist/chunk-AWIQQEFP.js.map +1 -0
  35. package/dist/{chunk-VBKP2NLI.js → chunk-BTKI4XMM.js} +2 -2
  36. package/dist/{chunk-63QAQP7I.js → chunk-CNBVWPQC.js} +7 -7
  37. package/dist/{chunk-FENBDSIW.js → chunk-CQGEGPY7.js} +75 -3
  38. package/dist/chunk-CQGEGPY7.js.map +1 -0
  39. package/dist/chunk-CTREXL3O.js +335 -0
  40. package/dist/chunk-CTREXL3O.js.map +1 -0
  41. package/dist/chunk-DLWO3J7D.js +238 -0
  42. package/dist/chunk-DLWO3J7D.js.map +1 -0
  43. package/dist/{chunk-LWSJK546.js → chunk-DSMGS4IV.js} +5 -5
  44. package/dist/{chunk-LWSJK546.js.map → chunk-DSMGS4IV.js.map} +1 -1
  45. package/dist/{chunk-A3KPDLSF.js → chunk-EFPIHR6F.js} +18 -18
  46. package/dist/chunk-FRAICFTZ.js +191 -0
  47. package/dist/chunk-FRAICFTZ.js.map +1 -0
  48. package/dist/chunk-GS7VWV26.js +61 -0
  49. package/dist/chunk-GS7VWV26.js.map +1 -0
  50. package/dist/{chunk-NMSAZFRL.js → chunk-H5GQMLHA.js} +2 -2
  51. package/dist/{chunk-OQE6WMDP.js → chunk-HN6MZ2XL.js} +5 -5
  52. package/dist/chunk-HY57QRRW.js +11 -0
  53. package/dist/chunk-HY57QRRW.js.map +1 -0
  54. package/dist/{chunk-TCGZFSN5.js → chunk-KH4QSBNI.js} +2 -2
  55. package/dist/{chunk-JH3CKHF4.js → chunk-KJODHPWM.js} +8 -8
  56. package/dist/chunk-LSBI5MWS.js +66 -0
  57. package/dist/chunk-LSBI5MWS.js.map +1 -0
  58. package/dist/chunk-MDRH3SDA.js +106 -0
  59. package/dist/chunk-MDRH3SDA.js.map +1 -0
  60. package/dist/{chunk-VBWYH7UZ.js → chunk-NHYRIM4I.js} +3 -3
  61. package/dist/{chunk-BYP54FMI.js → chunk-O2RCDK5D.js} +30 -15
  62. package/dist/{chunk-BYP54FMI.js.map → chunk-O2RCDK5D.js.map} +1 -1
  63. package/dist/{chunk-EWOJATDS.js → chunk-PDD5A43Y.js} +3 -3
  64. package/dist/{chunk-23JUSUUB.js → chunk-RZLCBWGG.js} +2 -2
  65. package/dist/chunk-SFZELD6V.js +52 -0
  66. package/dist/chunk-SFZELD6V.js.map +1 -0
  67. package/dist/{chunk-Y4W6GK5X.js → chunk-UGFCLD32.js} +2 -2
  68. package/dist/{chunk-ZGUXI5SI.js → chunk-VUBJZEZB.js} +2 -2
  69. package/dist/{chunk-LQYIBL3G.js → chunk-WL7PZK7Q.js} +71 -1
  70. package/dist/chunk-WL7PZK7Q.js.map +1 -0
  71. package/dist/{chunk-7HZCFG2A.js → chunk-WP2GYFZ4.js} +38 -1
  72. package/dist/chunk-WP2GYFZ4.js.map +1 -0
  73. package/dist/{chunk-JK7R7BZQ.js → chunk-ZWJ3SZ2G.js} +2 -2
  74. package/dist/crypto/digest.d.ts +2 -0
  75. package/dist/crypto/index.d.ts +1 -0
  76. package/dist/crypto/index.js +6 -2
  77. package/dist/design-canvas/index.js +5 -3
  78. package/dist/design-canvas/index.js.map +1 -1
  79. package/dist/design-canvas-react/engine.js +7 -5
  80. package/dist/design-canvas-react/index.js +14 -12
  81. package/dist/design-canvas-react/index.js.map +1 -1
  82. package/dist/design-canvas-react/lazy.js +1 -1
  83. package/dist/eval/index.d.ts +4 -0
  84. package/dist/eval/index.js +125 -0
  85. package/dist/eval/index.js.map +1 -1
  86. package/dist/eval/persona-driver.d.ts +37 -0
  87. package/dist/eval/research-plan.d.ts +25 -0
  88. package/dist/eval/research-plan.js +55 -0
  89. package/dist/eval/research-plan.js.map +1 -0
  90. package/dist/eval/scorecard.d.ts +38 -0
  91. package/dist/forms/blank.d.ts +2 -2
  92. package/dist/forms/index.js +4 -5
  93. package/dist/forms/index.js.map +1 -1
  94. package/dist/hosted-agent/application.js +2 -2
  95. package/dist/interactions/index.js +3 -3
  96. package/dist/knowledge/prelaunch-audit.d.ts +17 -0
  97. package/dist/knowledge/prelaunch-audit.js +67 -0
  98. package/dist/knowledge/prelaunch-audit.js.map +1 -0
  99. package/dist/media/drizzle.d.ts +207 -0
  100. package/dist/media/drizzle.js +26 -0
  101. package/dist/media/drizzle.js.map +1 -0
  102. package/dist/media/generate-request.d.ts +53 -0
  103. package/dist/media/generation-record.d.ts +68 -0
  104. package/dist/media/index.d.ts +13 -0
  105. package/dist/media/index.js +653 -0
  106. package/dist/media/index.js.map +1 -0
  107. package/dist/media/model-catalog.d.ts +109 -0
  108. package/dist/media/router-client.d.ts +40 -0
  109. package/dist/media/router-generation.d.ts +44 -0
  110. package/dist/media/speech-script.d.ts +20 -0
  111. package/dist/openui/index.js +1 -1
  112. package/dist/operator/index.js +4 -5
  113. package/dist/operator/index.js.map +1 -1
  114. package/dist/plans/decision.d.ts +48 -0
  115. package/dist/plans/drizzle.d.ts +25 -0
  116. package/dist/plans/drizzle.js +97 -0
  117. package/dist/plans/drizzle.js.map +1 -0
  118. package/dist/plans/index.d.ts +1 -1
  119. package/dist/plans/index.js +11 -3
  120. package/dist/platform/billing-config.d.ts +22 -0
  121. package/dist/platform/billing-config.js +36 -0
  122. package/dist/platform/billing-config.js.map +1 -0
  123. package/dist/platform/index.js +13 -11
  124. package/dist/platform/index.js.map +1 -1
  125. package/dist/preset-cloudflare/index.js +2 -1
  126. package/dist/preset-cloudflare/index.js.map +1 -1
  127. package/dist/profile/index.js +4 -5
  128. package/dist/profile/index.js.map +1 -1
  129. package/dist/public-consultation/index.d.ts +1 -1
  130. package/dist/public-consultation/index.js +13 -11
  131. package/dist/public-consultation/index.js.map +1 -1
  132. package/dist/runtime/telemetry-cap.d.ts +24 -0
  133. package/dist/runtime/telemetry-cap.js +36 -0
  134. package/dist/runtime/telemetry-cap.js.map +1 -0
  135. package/dist/sandbox/index.js +12 -9
  136. package/dist/sequences/index.js +4 -2
  137. package/dist/sequences/index.js.map +1 -1
  138. package/dist/skills-placement/box.d.ts +50 -0
  139. package/dist/skills-placement/box.js +204 -0
  140. package/dist/skills-placement/box.js.map +1 -0
  141. package/dist/skills-placement/index.js +8 -96
  142. package/dist/skills-placement/index.js.map +1 -1
  143. package/dist/spend/budget.d.ts +13 -0
  144. package/dist/spend/drizzle.d.ts +55 -0
  145. package/dist/spend/drizzle.js +131 -0
  146. package/dist/spend/drizzle.js.map +1 -0
  147. package/dist/spend/index.d.ts +2 -1
  148. package/dist/spend/index.js +77 -58
  149. package/dist/spend/index.js.map +1 -1
  150. package/dist/spend/platform-settlements.d.ts +46 -0
  151. package/dist/stream/index.js +19 -19
  152. package/dist/studio/generated-media/index.d.ts +6 -0
  153. package/dist/studio/generated-media/index.js +590 -0
  154. package/dist/studio/generated-media/index.js.map +1 -0
  155. package/dist/studio/generated-media/output.d.ts +27 -0
  156. package/dist/studio/generated-media/store.d.ts +175 -0
  157. package/dist/studio-react/download-generations.d.ts +7 -0
  158. package/dist/studio-react/index.d.ts +1 -0
  159. package/dist/studio-react/index.js +85 -0
  160. package/dist/studio-react/index.js.map +1 -1
  161. package/dist/studio-react/use-studio-route.d.ts +44 -0
  162. package/dist/teams/invitations-api.d.ts +4 -0
  163. package/dist/teams/invitations-api.js +44 -32
  164. package/dist/teams/invitations-api.js.map +1 -1
  165. package/dist/theme/dom.d.ts +22 -0
  166. package/dist/theme/dom.js +18 -0
  167. package/dist/theme/dom.js.map +1 -0
  168. package/dist/vault/collaboration.d.ts +83 -0
  169. package/dist/vault/collaboration.js +215 -0
  170. package/dist/vault/collaboration.js.map +1 -0
  171. package/dist/vault/server.js +6 -53
  172. package/dist/vault/server.js.map +1 -1
  173. package/dist/vault/store/coordinator.d.ts +64 -0
  174. package/dist/vault/store/index.d.ts +12 -0
  175. package/dist/vault/store/index.js +1202 -0
  176. package/dist/vault/store/index.js.map +1 -0
  177. package/dist/vault/store/paths.d.ts +65 -0
  178. package/dist/vault/store/revisions.d.ts +211 -0
  179. package/dist/vault/store/sandbox-sync.d.ts +74 -0
  180. package/dist/vault/store/store.d.ts +161 -0
  181. package/dist/vault/store/tree.d.ts +11 -0
  182. package/dist/web/entry-server.d.ts +7 -0
  183. package/dist/web/entry-server.js +29 -0
  184. package/dist/web/entry-server.js.map +1 -0
  185. package/dist/web/fetch-guard.d.ts +6 -0
  186. package/dist/web/index.d.ts +3 -0
  187. package/dist/web/index.js +20 -4
  188. package/dist/web/mime.d.ts +16 -0
  189. package/dist/web/rate-limit.d.ts +25 -0
  190. package/dist/web/timeout.d.ts +9 -0
  191. package/dist/web-react/agent-profile-editor.js +3 -3
  192. package/dist/web-react/api-access-panel.d.ts +4 -2
  193. package/dist/web-react/document.d.ts +41 -0
  194. package/dist/web-react/document.js +103 -0
  195. package/dist/web-react/document.js.map +1 -0
  196. package/dist/web-react/index.js +31 -31
  197. package/dist/workspace-react/index.js +5 -5
  198. package/package.json +95 -4
  199. package/dist/DesignCanvas-OW3W2QXW.js +0 -13
  200. package/dist/DesignCanvasEditor-TCHZF25W.js +0 -16
  201. package/dist/chunk-5Y7Z5G3Y.js.map +0 -1
  202. package/dist/chunk-7HZCFG2A.js.map +0 -1
  203. package/dist/chunk-7KKOFMLD.js.map +0 -1
  204. package/dist/chunk-FENBDSIW.js.map +0 -1
  205. package/dist/chunk-LQYIBL3G.js.map +0 -1
  206. /package/dist/{DesignCanvas-OW3W2QXW.js.map → DesignCanvas-L6J72JQ2.js.map} +0 -0
  207. /package/dist/{DesignCanvasEditor-TCHZF25W.js.map → DesignCanvasEditor-QFQD63MR.js.map} +0 -0
  208. /package/dist/{chunk-MY3EJJ6Y.js.map → chunk-4FEH6266.js.map} +0 -0
  209. /package/dist/{chunk-X556WVBG.js.map → chunk-4ZSLX3LY.js.map} +0 -0
  210. /package/dist/{chunk-VBKP2NLI.js.map → chunk-BTKI4XMM.js.map} +0 -0
  211. /package/dist/{chunk-63QAQP7I.js.map → chunk-CNBVWPQC.js.map} +0 -0
  212. /package/dist/{chunk-A3KPDLSF.js.map → chunk-EFPIHR6F.js.map} +0 -0
  213. /package/dist/{chunk-NMSAZFRL.js.map → chunk-H5GQMLHA.js.map} +0 -0
  214. /package/dist/{chunk-OQE6WMDP.js.map → chunk-HN6MZ2XL.js.map} +0 -0
  215. /package/dist/{chunk-TCGZFSN5.js.map → chunk-KH4QSBNI.js.map} +0 -0
  216. /package/dist/{chunk-JH3CKHF4.js.map → chunk-KJODHPWM.js.map} +0 -0
  217. /package/dist/{chunk-VBWYH7UZ.js.map → chunk-NHYRIM4I.js.map} +0 -0
  218. /package/dist/{chunk-EWOJATDS.js.map → chunk-PDD5A43Y.js.map} +0 -0
  219. /package/dist/{chunk-23JUSUUB.js.map → chunk-RZLCBWGG.js.map} +0 -0
  220. /package/dist/{chunk-Y4W6GK5X.js.map → chunk-UGFCLD32.js.map} +0 -0
  221. /package/dist/{chunk-ZGUXI5SI.js.map → chunk-VUBJZEZB.js.map} +0 -0
  222. /package/dist/{chunk-JK7R7BZQ.js.map → chunk-ZWJ3SZ2G.js.map} +0 -0
@@ -0,0 +1,215 @@
1
+ import {
2
+ workspaceRoleToCollaborationAccess
3
+ } from "../chunk-6XIAPIW6.js";
4
+
5
+ // src/vault/collaboration.ts
6
+ import { createHash } from "crypto";
7
+ import {
8
+ buildCollaborationDocumentId,
9
+ parseCollaborationDocumentId
10
+ } from "@tangle-network/sandbox";
11
+ import { ProductTokenIssuer } from "@tangle-network/sandbox/auth";
12
+ function getCollaborationServerUrl(env) {
13
+ const url = env.COLLABORATION_SERVER_URL?.trim();
14
+ return url ? url.replace(/\/+$/, "") : null;
15
+ }
16
+ function isCollaborationConfigured(env) {
17
+ return Boolean(env.ORCHESTRATOR_SIGNING_SECRET && getCollaborationServerUrl(env));
18
+ }
19
+ function createIssuer(productId, env) {
20
+ if (!env.ORCHESTRATOR_SIGNING_SECRET) {
21
+ throw new Error("Missing ORCHESTRATOR_SIGNING_SECRET");
22
+ }
23
+ return new ProductTokenIssuer({
24
+ productId,
25
+ signingSecret: env.ORCHESTRATOR_SIGNING_SECRET,
26
+ ttlMinutes: {
27
+ free: 30,
28
+ pro: 120,
29
+ enterprise: 240
30
+ }
31
+ });
32
+ }
33
+ function buildEditorSessionId(workspaceId, viewer) {
34
+ return `collab:${workspaceId}:${viewer.id}`;
35
+ }
36
+ function createSnapshotVersion(content) {
37
+ return createHash("sha256").update(content).digest("hex").slice(0, 16);
38
+ }
39
+ async function buildVaultCollaborationBootstrap(params) {
40
+ const { productId, env, readFile, workspaceId, relativePath, viewer, access = "read" } = params;
41
+ const websocketUrl = getCollaborationServerUrl(env);
42
+ if (!websocketUrl) {
43
+ throw new Error("Collaboration server is not configured");
44
+ }
45
+ const file = await readFile(workspaceId, relativePath);
46
+ const documentId = buildCollaborationDocumentId({
47
+ workspaceId,
48
+ relativePath
49
+ });
50
+ const { token, expiresAt } = createIssuer(productId, env).issueCollaboration({
51
+ userId: viewer.id,
52
+ sessionId: buildEditorSessionId(workspaceId, viewer),
53
+ projectId: workspaceId,
54
+ documentId,
55
+ access,
56
+ tier: "pro"
57
+ });
58
+ return {
59
+ documentId,
60
+ transport: {
61
+ websocketUrl,
62
+ token,
63
+ expiresAt
64
+ },
65
+ permissions: {
66
+ access,
67
+ canSnapshot: access === "write"
68
+ },
69
+ source: "filesystem",
70
+ initialContent: file.body,
71
+ snapshotVersion: createSnapshotVersion(file.content)
72
+ };
73
+ }
74
+ function refreshVaultCollaborationToken(params) {
75
+ const { productId, env, workspaceId, documentId, viewer, access = "read" } = params;
76
+ const ref = parseCollaborationDocumentId(documentId);
77
+ if (!ref || ref.workspaceId !== workspaceId) {
78
+ throw new Error("Document does not belong to workspace");
79
+ }
80
+ const { token, expiresAt } = createIssuer(productId, env).issueCollaboration({
81
+ userId: viewer.id,
82
+ sessionId: buildEditorSessionId(workspaceId, viewer),
83
+ projectId: workspaceId,
84
+ documentId,
85
+ access,
86
+ tier: "pro"
87
+ });
88
+ return {
89
+ token,
90
+ expiresAt,
91
+ access
92
+ };
93
+ }
94
+ async function saveVaultCollaborationSnapshot(params) {
95
+ const { readFile, workspaceId, relativePath, documentId } = params;
96
+ const ref = parseCollaborationDocumentId(documentId);
97
+ if (!ref || ref.workspaceId !== workspaceId || ref.relativePath !== relativePath) {
98
+ throw new Error("Document does not match requested file");
99
+ }
100
+ const file = await readFile(workspaceId, relativePath);
101
+ return {
102
+ snapshotVersion: createSnapshotVersion(file.content),
103
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
104
+ };
105
+ }
106
+ function createVaultCollaborationRoutes(config) {
107
+ const { productId, readFile } = config;
108
+ async function admit({ request, context }) {
109
+ const session = await config.requireUser(request);
110
+ const env = config.resolveEnv(context);
111
+ if (!isCollaborationConfigured(env)) {
112
+ return Response.json(
113
+ { error: "Collaboration is not configured for this deployment" },
114
+ { status: 503 }
115
+ );
116
+ }
117
+ return { session, env };
118
+ }
119
+ function viewerOf(user) {
120
+ return { id: user.id, name: user.name, email: user.email };
121
+ }
122
+ async function bootstrap(args) {
123
+ const admitted = await admit(args);
124
+ if (admitted instanceof Response) return admitted;
125
+ const { session, env } = admitted;
126
+ const body = await args.request.json();
127
+ if (!body.workspaceId || !body.relativePath) {
128
+ return Response.json({ error: "Missing workspaceId or relativePath" }, { status: 400 });
129
+ }
130
+ const access = await config.getWorkspaceAccess(body.workspaceId, session.user.id);
131
+ if (!access) {
132
+ return Response.json({ error: "Workspace not found" }, { status: 404 });
133
+ }
134
+ try {
135
+ const result = await buildVaultCollaborationBootstrap({
136
+ productId,
137
+ env,
138
+ readFile,
139
+ workspaceId: access.workspace.id,
140
+ relativePath: body.relativePath,
141
+ viewer: viewerOf(session.user),
142
+ access: workspaceRoleToCollaborationAccess(access.role)
143
+ });
144
+ return Response.json(result);
145
+ } catch (error) {
146
+ const message = error instanceof Error ? error.message : "Failed to bootstrap collaboration";
147
+ const status = message.includes("not found") ? 404 : 400;
148
+ return Response.json({ error: message }, { status });
149
+ }
150
+ }
151
+ async function token(args) {
152
+ const admitted = await admit(args);
153
+ if (admitted instanceof Response) return admitted;
154
+ const { session, env } = admitted;
155
+ const body = await args.request.json();
156
+ if (!body.workspaceId || !body.documentId) {
157
+ return Response.json({ error: "Missing workspaceId or documentId" }, { status: 400 });
158
+ }
159
+ const access = await config.getWorkspaceAccess(body.workspaceId, session.user.id);
160
+ if (!access) {
161
+ return Response.json({ error: "Workspace not found" }, { status: 404 });
162
+ }
163
+ try {
164
+ const refreshed = refreshVaultCollaborationToken({
165
+ productId,
166
+ env,
167
+ workspaceId: access.workspace.id,
168
+ documentId: body.documentId,
169
+ viewer: viewerOf(session.user),
170
+ access: workspaceRoleToCollaborationAccess(access.role)
171
+ });
172
+ return Response.json(refreshed);
173
+ } catch (error) {
174
+ const message = error instanceof Error ? error.message : "Failed to refresh collaboration token";
175
+ return Response.json({ error: message }, { status: 400 });
176
+ }
177
+ }
178
+ async function snapshot(args) {
179
+ const admitted = await admit(args);
180
+ if (admitted instanceof Response) return admitted;
181
+ const { session } = admitted;
182
+ const body = await args.request.json();
183
+ if (!body.workspaceId || !body.relativePath || !body.documentId) {
184
+ return Response.json(
185
+ { error: "Missing workspaceId, relativePath, or documentId" },
186
+ { status: 400 }
187
+ );
188
+ }
189
+ const access = await config.getWorkspaceAccess(body.workspaceId, session.user.id, "editor");
190
+ if (!access) {
191
+ return Response.json({ error: "Workspace not found" }, { status: 404 });
192
+ }
193
+ try {
194
+ const saved = await saveVaultCollaborationSnapshot({
195
+ readFile,
196
+ workspaceId: access.workspace.id,
197
+ relativePath: body.relativePath,
198
+ documentId: body.documentId
199
+ });
200
+ return Response.json(saved);
201
+ } catch (error) {
202
+ const message = error instanceof Error ? error.message : "Failed to save collaboration snapshot";
203
+ return Response.json({ error: message }, { status: 400 });
204
+ }
205
+ }
206
+ return { bootstrap, token, snapshot };
207
+ }
208
+ export {
209
+ buildVaultCollaborationBootstrap,
210
+ createVaultCollaborationRoutes,
211
+ isCollaborationConfigured,
212
+ refreshVaultCollaborationToken,
213
+ saveVaultCollaborationSnapshot
214
+ };
215
+ //# sourceMappingURL=collaboration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/vault/collaboration.ts"],"sourcesContent":["/**\n * Live co-editing of vault files: bootstrap, token refresh and snapshot\n * routes over the sandbox collaboration server. Each product supplies its\n * product id, how to read a vault file, and its own request auth and\n * workspace access lookup; the token policy and route contract live here once.\n */\nimport { createHash } from 'node:crypto'\nimport {\n buildCollaborationDocumentId,\n parseCollaborationDocumentId,\n type CollaborationBootstrapResponse,\n type CollaborationTokenRefreshResponse,\n type SaveCollaborationSnapshotResponse,\n} from '@tangle-network/sandbox'\nimport { ProductTokenIssuer } from '@tangle-network/sandbox/auth'\nimport { workspaceRoleToCollaborationAccess, type WorkspaceRole } from '../teams/roles'\n\nexport type CollaborationAccess = 'read' | 'write'\n\nexport interface CollaborationViewer {\n id: string\n name?: string | null\n email?: string | null\n}\n\n/** The deployment settings collaboration needs, read from the worker env. */\nexport interface CollaborationEnv {\n COLLABORATION_SERVER_URL?: string\n ORCHESTRATOR_SIGNING_SECRET?: string\n}\n\n/** The vault file fields collaboration reads: `body` seeds the editor, and\n * the full `content` (frontmatter included) versions the snapshot. */\nexport interface CollaborationVaultFile {\n body: string\n content: string\n}\n\nexport type ReadCollaborationVaultFile = (\n workspaceId: string,\n relativePath: string,\n) => Promise<CollaborationVaultFile>\n\nfunction getCollaborationServerUrl(env: CollaborationEnv): string | null {\n const url = env.COLLABORATION_SERVER_URL?.trim()\n return url ? url.replace(/\\/+$/, '') : null\n}\n\nexport function isCollaborationConfigured(env: CollaborationEnv): boolean {\n return Boolean(env.ORCHESTRATOR_SIGNING_SECRET && getCollaborationServerUrl(env))\n}\n\nfunction createIssuer(productId: string, env: CollaborationEnv) {\n if (!env.ORCHESTRATOR_SIGNING_SECRET) {\n throw new Error('Missing ORCHESTRATOR_SIGNING_SECRET')\n }\n\n return new ProductTokenIssuer({\n productId,\n signingSecret: env.ORCHESTRATOR_SIGNING_SECRET,\n ttlMinutes: {\n free: 30,\n pro: 120,\n enterprise: 240,\n },\n })\n}\n\nfunction buildEditorSessionId(workspaceId: string, viewer: CollaborationViewer): string {\n return `collab:${workspaceId}:${viewer.id}`\n}\n\nfunction createSnapshotVersion(content: string): string {\n return createHash('sha256').update(content).digest('hex').slice(0, 16)\n}\n\nexport async function buildVaultCollaborationBootstrap(params: {\n productId: string\n env: CollaborationEnv\n readFile: ReadCollaborationVaultFile\n workspaceId: string\n relativePath: string\n viewer: CollaborationViewer\n access?: CollaborationAccess\n}): Promise<CollaborationBootstrapResponse> {\n const { productId, env, readFile, workspaceId, relativePath, viewer, access = 'read' } = params\n const websocketUrl = getCollaborationServerUrl(env)\n\n if (!websocketUrl) {\n throw new Error('Collaboration server is not configured')\n }\n\n const file = await readFile(workspaceId, relativePath)\n const documentId = buildCollaborationDocumentId({\n workspaceId,\n relativePath,\n })\n const { token, expiresAt } = createIssuer(productId, env).issueCollaboration({\n userId: viewer.id,\n sessionId: buildEditorSessionId(workspaceId, viewer),\n projectId: workspaceId,\n documentId,\n access,\n tier: 'pro',\n })\n\n return {\n documentId,\n transport: {\n websocketUrl,\n token,\n expiresAt,\n },\n permissions: {\n access,\n canSnapshot: access === 'write',\n },\n source: 'filesystem',\n initialContent: file.body,\n snapshotVersion: createSnapshotVersion(file.content),\n }\n}\n\nexport function refreshVaultCollaborationToken(params: {\n productId: string\n env: CollaborationEnv\n workspaceId: string\n documentId: string\n viewer: CollaborationViewer\n access?: CollaborationAccess\n}): CollaborationTokenRefreshResponse {\n const { productId, env, workspaceId, documentId, viewer, access = 'read' } = params\n const ref = parseCollaborationDocumentId(documentId)\n\n if (!ref || ref.workspaceId !== workspaceId) {\n throw new Error('Document does not belong to workspace')\n }\n\n const { token, expiresAt } = createIssuer(productId, env).issueCollaboration({\n userId: viewer.id,\n sessionId: buildEditorSessionId(workspaceId, viewer),\n projectId: workspaceId,\n documentId,\n access,\n tier: 'pro',\n })\n\n return {\n token,\n expiresAt,\n access,\n }\n}\n\nexport async function saveVaultCollaborationSnapshot(params: {\n readFile: ReadCollaborationVaultFile\n workspaceId: string\n relativePath: string\n documentId: string\n}): Promise<SaveCollaborationSnapshotResponse> {\n const { readFile, workspaceId, relativePath, documentId } = params\n const ref = parseCollaborationDocumentId(documentId)\n\n if (!ref || ref.workspaceId !== workspaceId || ref.relativePath !== relativePath) {\n throw new Error('Document does not match requested file')\n }\n\n const file = await readFile(workspaceId, relativePath)\n return {\n snapshotVersion: createSnapshotVersion(file.content),\n savedAt: new Date().toISOString(),\n }\n}\n\n/** The signed-in user a collaboration route acts for. */\nexport interface CollaborationSessionUser {\n id: string\n name?: string | null\n email?: string | null\n}\n\nexport interface CollaborationWorkspaceAccess {\n workspace: { id: string }\n role: WorkspaceRole\n}\n\nexport interface VaultCollaborationRoutesConfig<Context> {\n /** Product id the collaboration tokens are issued for. */\n productId: string\n /** Authenticate the request; throw the product's own 401 response. */\n requireUser: (request: Request) => Promise<{ user: CollaborationSessionUser }>\n /** Read the worker env from the route context. */\n resolveEnv: (context: Context) => CollaborationEnv\n /** Resolve the user's membership; `minRole` is the least role the route needs. */\n getWorkspaceAccess: (\n workspaceId: string,\n userId: string,\n minRole?: 'editor',\n ) => Promise<CollaborationWorkspaceAccess | null>\n readFile: ReadCollaborationVaultFile\n}\n\ninterface CollaborationRouteArgs<Context> {\n request: Request\n context: Context\n}\n\n/**\n * The three collaboration route actions. Viewers get read-only sessions;\n * snapshots need editor access. A missing file answers 404 on bootstrap.\n */\nexport function createVaultCollaborationRoutes<Context>(config: VaultCollaborationRoutesConfig<Context>) {\n const { productId, readFile } = config\n\n async function admit({ request, context }: CollaborationRouteArgs<Context>) {\n const session = await config.requireUser(request)\n const env = config.resolveEnv(context)\n if (!isCollaborationConfigured(env)) {\n return Response.json(\n { error: 'Collaboration is not configured for this deployment' },\n { status: 503 },\n )\n }\n return { session, env }\n }\n\n function viewerOf(user: CollaborationSessionUser): CollaborationViewer {\n return { id: user.id, name: user.name, email: user.email }\n }\n\n async function bootstrap(args: CollaborationRouteArgs<Context>): Promise<Response> {\n const admitted = await admit(args)\n if (admitted instanceof Response) return admitted\n const { session, env } = admitted\n\n const body = await args.request.json() as {\n workspaceId?: string\n relativePath?: string\n }\n\n if (!body.workspaceId || !body.relativePath) {\n return Response.json({ error: 'Missing workspaceId or relativePath' }, { status: 400 })\n }\n\n const access = await config.getWorkspaceAccess(body.workspaceId, session.user.id)\n if (!access) {\n return Response.json({ error: 'Workspace not found' }, { status: 404 })\n }\n\n try {\n const result = await buildVaultCollaborationBootstrap({\n productId,\n env,\n readFile,\n workspaceId: access.workspace.id,\n relativePath: body.relativePath,\n viewer: viewerOf(session.user),\n access: workspaceRoleToCollaborationAccess(access.role),\n })\n return Response.json(result)\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to bootstrap collaboration'\n const status = message.includes('not found') ? 404 : 400\n return Response.json({ error: message }, { status })\n }\n }\n\n async function token(args: CollaborationRouteArgs<Context>): Promise<Response> {\n const admitted = await admit(args)\n if (admitted instanceof Response) return admitted\n const { session, env } = admitted\n\n const body = await args.request.json() as {\n workspaceId?: string\n documentId?: string\n }\n\n if (!body.workspaceId || !body.documentId) {\n return Response.json({ error: 'Missing workspaceId or documentId' }, { status: 400 })\n }\n\n const access = await config.getWorkspaceAccess(body.workspaceId, session.user.id)\n if (!access) {\n return Response.json({ error: 'Workspace not found' }, { status: 404 })\n }\n\n try {\n const refreshed = refreshVaultCollaborationToken({\n productId,\n env,\n workspaceId: access.workspace.id,\n documentId: body.documentId,\n viewer: viewerOf(session.user),\n access: workspaceRoleToCollaborationAccess(access.role),\n })\n return Response.json(refreshed)\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to refresh collaboration token'\n return Response.json({ error: message }, { status: 400 })\n }\n }\n\n async function snapshot(args: CollaborationRouteArgs<Context>): Promise<Response> {\n const admitted = await admit(args)\n if (admitted instanceof Response) return admitted\n const { session } = admitted\n\n const body = await args.request.json() as {\n workspaceId?: string\n relativePath?: string\n documentId?: string\n }\n\n if (!body.workspaceId || !body.relativePath || !body.documentId) {\n return Response.json(\n { error: 'Missing workspaceId, relativePath, or documentId' },\n { status: 400 },\n )\n }\n\n const access = await config.getWorkspaceAccess(body.workspaceId, session.user.id, 'editor')\n if (!access) {\n return Response.json({ error: 'Workspace not found' }, { status: 404 })\n }\n\n try {\n const saved = await saveVaultCollaborationSnapshot({\n readFile,\n workspaceId: access.workspace.id,\n relativePath: body.relativePath,\n documentId: body.documentId,\n })\n return Response.json(saved)\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to save collaboration snapshot'\n return Response.json({ error: message }, { status: 400 })\n }\n }\n\n return { bootstrap, token, snapshot }\n}\n"],"mappings":";;;;;AAMA,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AACP,SAAS,0BAA0B;AA6BnC,SAAS,0BAA0B,KAAsC;AACvE,QAAM,MAAM,IAAI,0BAA0B,KAAK;AAC/C,SAAO,MAAM,IAAI,QAAQ,QAAQ,EAAE,IAAI;AACzC;AAEO,SAAS,0BAA0B,KAAgC;AACxE,SAAO,QAAQ,IAAI,+BAA+B,0BAA0B,GAAG,CAAC;AAClF;AAEA,SAAS,aAAa,WAAmB,KAAuB;AAC9D,MAAI,CAAC,IAAI,6BAA6B;AACpC,UAAM,IAAI,MAAM,qCAAqC;AAAA,EACvD;AAEA,SAAO,IAAI,mBAAmB;AAAA,IAC5B;AAAA,IACA,eAAe,IAAI;AAAA,IACnB,YAAY;AAAA,MACV,MAAM;AAAA,MACN,KAAK;AAAA,MACL,YAAY;AAAA,IACd;AAAA,EACF,CAAC;AACH;AAEA,SAAS,qBAAqB,aAAqB,QAAqC;AACtF,SAAO,UAAU,WAAW,IAAI,OAAO,EAAE;AAC3C;AAEA,SAAS,sBAAsB,SAAyB;AACtD,SAAO,WAAW,QAAQ,EAAE,OAAO,OAAO,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE;AACvE;AAEA,eAAsB,iCAAiC,QAQX;AAC1C,QAAM,EAAE,WA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RATIO = 0.75;
3
- var VAULT_DELETION_REFUSAL_MIN_LIVE_FILES = 10;
4
- function assessVaultDeletionBatch(input) {
5
- const refusalRatio = input.policy?.refusalRatio ?? VAULT_DELETION_REFUSAL_RATIO;
6
- const minLiveFiles = input.policy?.minLiveFiles ?? VAULT_DELETION_REFUSAL_MIN_LIVE_FILES;
7
- if (!Number.isFinite(refusalRatio) || refusalRatio <= 0 || refusalRatio > 1) {
8
- throw new RangeError(
9
- `vault deletion policy refusalRatio must be a finite number in (0, 1], got ${refusalRatio}`
10
- );
11
- }
12
- if (!Number.isFinite(minLiveFiles) || minLiveFiles < 0) {
13
- throw new RangeError(
14
- `vault deletion policy minLiveFiles must be a finite number >= 0, got ${minLiveFiles}`
15
- );
16
- }
17
- const manifestEmpty = input.manifestEmpty ?? false;
18
- const baselineLive = input.baselinePaths.length;
19
- const proposedSet = new Set(input.proposedDeletions);
20
- const wouldDeletePaths = manifestEmpty ? [...input.baselinePaths].sort() : input.baselinePaths.filter((p) => proposedSet.has(p)).sort();
21
- const wouldDelete = wouldDeletePaths.length;
22
- const deletionRatio = baselineLive > 0 ? wouldDelete / baselineLive : 0;
23
- const refusesEmptyManifest = manifestEmpty && baselineLive > 0;
24
- const refusesAllFiles = wouldDelete > 0 && wouldDelete === baselineLive;
25
- const refusesBlastRadius = wouldDelete > 0 && baselineLive >= minLiveFiles && deletionRatio >= refusalRatio;
26
- const reason = refusesEmptyManifest ? "empty-manifest" : refusesAllFiles ? "all-files" : refusesBlastRadius ? "ratio-exceeded" : void 0;
27
- return {
28
- allowed: reason === void 0,
29
- reason,
30
- deletionRatio,
31
- wouldDelete,
32
- wouldDeletePaths,
33
- baselineLive
34
- };
35
- }
36
- function compareIncarnationBaseline(baselineId, current) {
37
- const currentId = current.filesystemIncarnationId;
38
- const provenance = current.filesystemIncarnationProvenance;
39
- const isValidProvenance = provenance === "fresh" || provenance === "restored" || provenance === "unknown";
40
- if (typeof currentId !== "string" || currentId.length === 0 || !isValidProvenance) {
41
- return { verdict: "unidentified" };
42
- }
43
- if (current.filesystemIncarnationReadiness !== "ready") {
44
- return { verdict: "not-ready", readiness: current.filesystemIncarnationReadiness };
45
- }
46
- if (baselineId === void 0) {
47
- return { verdict: "no-baseline" };
48
- }
49
- if (baselineId !== currentId) {
50
- return { verdict: "mismatch", baselineId, currentId };
51
- }
52
- return { verdict: "match" };
53
- }
1
+ import {
2
+ VAULT_DELETION_REFUSAL_MIN_LIVE_FILES,
3
+ VAULT_DELETION_REFUSAL_RATIO,
4
+ assessVaultDeletionBatch,
5
+ compareIncarnationBaseline
6
+ } from "../chunk-GS7VWV26.js";
54
7
  export {
55
8
  VAULT_DELETION_REFUSAL_MIN_LIVE_FILES,
56
9
  VAULT_DELETION_REFUSAL_RATIO,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/vault/server.ts"],"sourcesContent":["/**\n * Server-only policy sibling of the React `./vault` client surface. Pure\n * decision logic — no I/O, no logging, ZERO imports — extracted from\n * gtm-agent's local guard (gtm#612) after it lost 48 production vault files:\n * a half-mounted sandbox scanned cleanly and reconciliation derived a\n * mass-deletion batch from an empty manifest. The #265/#332 audit ruled both\n * checks here universal shell mechanism, not gtm-specific, so they live here\n * once instead of being re-forked per product.\n *\n * Two independent checks:\n * - `assessVaultDeletionBatch` — blast-radius refusal. Given the live\n * baseline and what a reconciliation pass proposes to delete, decide\n * whether the batch is safe to apply or must be refused. Refusal is a\n * SUCCESSFUL outcome, not a thrown error: content changes still apply,\n * only the deletions are withheld. What to do with a refusal (log, alert,\n * retry the scan) stays the caller's job.\n * - `compareIncarnationBaseline` — filesystem-incarnation comparison. Given\n * a recorded baseline incarnation id and the sandbox's current identity\n * fields, decide whether the sandbox filesystem is the same one the\n * baseline was captured against, fail-closed on anything not clearly\n * identified and ready.\n *\n * Both are pure functions over caller-supplied data: no manifest reads, no\n * sandbox calls, no console output. The caller pre-filters tombstoned\n * entries (this module only ever sees the LIVE path set) and owns everything\n * that happens after a verdict comes back.\n */\n\n/** Refuse a deletion batch once it would remove at least this fraction of the\n * live baseline (both this and `VAULT_DELETION_REFUSAL_MIN_LIVE_FILES` must\n * hold — a tiny vault can lose all its files without tripping this ratio\n * gate; `refusesAllFiles` catches that case separately). */\nexport const VAULT_DELETION_REFUSAL_RATIO = 0.75\n\n/** The blast-radius ratio gate only engages once the live baseline is at\n * least this large, so a 2-file vault losing 1 file (50%) is not refused on\n * ratio alone. */\nexport const VAULT_DELETION_REFUSAL_MIN_LIVE_FILES = 10\n\n/** Overrides for `assessVaultDeletionBatch`'s two thresholds. Both default to\n * the exported constants above. Values are validated fail-loud:\n * `refusalRatio` must be finite and in (0, 1] — `NaN` (a config parse\n * failure) would make `deletionRatio >= refusalRatio` always false and silently\n * disable the guard, and `0` would refuse a zero-deletion batch; and\n * `minLiveFiles` must be finite and >= 0. Invalid values throw `RangeError`\n * instead of running with a guard that cannot fire (or cannot pass). */\nexport interface VaultDeletionPolicy {\n refusalRatio?: number\n minLiveFiles?: number\n}\n\nexport interface VaultDeletionAssessment {\n /** True when no refusal reason fired. */\n allowed: boolean\n /** Precedence when multiple reasons would fire: `empty-manifest` beats\n * `all-files` beats `ratio-exceeded` (most specific first — an empty scan\n * IS an all-files deletion, but the diagnostic that matters is \"the scan\n * came back empty\", not \"it deleted everything\"). Undefined when allowed. */\n reason?: 'empty-manifest' | 'all-files' | 'ratio-exceeded'\n /** wouldDelete / baselineLive, or 0 when the baseline is itself empty. */\n deletionRatio: number\n wouldDelete: number\n /** The paths that would be deleted, sorted — mirrors gtm's `.sort()` so log\n * output and any snapshot fixture are byte-stable. */\n wouldDeletePaths: string[]\n baselineLive: number\n}\n\n/**\n * Decide whether a reconciliation pass's proposed deletions are safe to\n * apply against the live baseline.\n *\n * `manifestEmpty: true` means the filesystem scan that produced\n * `proposedDeletions` came back with nothing — the caller could not have\n * derived a meaningful proposed-deletions list, so this treats the FULL live\n * baseline as would-delete regardless of what `proposedDeletions` contains.\n * That is what distinguishes `'empty-manifest'` from `'all-files'`: an empty\n * scan structurally implies every baseline path would be deleted, but the\n * diagnostic that matters to a caller is \"the scan was empty\", not merely\n * \"everything would go\".\n */\nexport function assessVaultDeletionBatch(input: {\n /** LIVE (non-tombstoned) baseline path set — the caller pre-filters, as gtm does. */\n baselinePaths: readonly string[]\n /** Paths a reconciliation pass proposes to delete; intersected with `baselinePaths` internally. */\n proposedDeletions: readonly string[]\n manifestEmpty?: boolean\n policy?: VaultDeletionPolicy\n}): VaultDeletionAssessment {\n const refusalRatio = input.policy?.refusalRatio ?? VAULT_DELETION_REFUSAL_RATIO\n const minLiveFiles = input.policy?.minLiveFiles ?? VAULT_DELETION_REFUSAL_MIN_LIVE_FILES\n if (!Number.isFinite(refusalRatio) || refusalRatio <= 0 || refusalRatio > 1) {\n throw new RangeError(\n `vault deletion policy refusalRatio must be a finite number in (0, 1], got ${refusalRatio}`,\n )\n }\n if (!Number.isFinite(minLiveFiles) || minLiveFiles < 0) {\n throw new RangeError(\n `vault deletion policy minLiveFiles must be a finite number >= 0, got ${minLiveFiles}`,\n )\n }\n const manifestEmpty = input.manifestEmpty ?? false\n\n const baselineLive = input.baselinePaths.length\n const proposedSet = new Set(input.proposedDeletions)\n const wouldDeletePaths = manifestEmpty\n ? [...input.baselinePaths].sort()\n : input.baselinePaths.filter((p) => proposedSet.has(p)).sort()\n const wouldDelete = wouldDeletePaths.length\n const deletionRatio = baselineLive > 0 ? wouldDelete / baselineLive : 0\n\n const refusesEmptyManifest = manifestEmpty && baselineLive > 0\n const refusesAllFiles = wouldDelete > 0 && wouldDelete === baselineLive\n // `wouldDelete > 0` is unreachable-false under the validated policy domain\n // (a positive refusalRatio can never be met by a 0 ratio) — it is here so\n // the ratio branch stays safe on its own terms, independent of the\n // validation above ever being relaxed.\n const refusesBlastRadius = wouldDelete > 0\n && baselineLive >= minLiveFiles\n && deletionRatio >= refusalRatio\n\n const reason = refusesEmptyManifest\n ? ('empty-manifest' as const)\n : refusesAllFiles\n ? ('all-files' as const)\n : refusesBlastRadius\n ? ('ratio-exceeded' as const)\n : undefined\n\n return {\n allowed: reason === undefined,\n reason,\n deletionRatio,\n wouldDelete,\n wouldDeletePaths,\n baselineLive,\n }\n}\n\n/** The subset of a sandbox's filesystem-incarnation identity this module\n * needs. A product's real incarnation type is structurally compatible —\n * no import required. */\nexport interface FilesystemIncarnationLike {\n filesystemIncarnationId?: string\n filesystemIncarnationProvenance?: 'fresh' | 'restored' | 'unknown'\n filesystemIncarnationReadiness?: 'transitioning' | 'ready'\n}\n\n/**\n * Result of comparing a recorded baseline incarnation id against the\n * sandbox's current identity. A discriminated union over `verdict` so a\n * caller's `switch` gets compile-time coverage instead of a stringly-typed\n * status it can forget to branch on.\n */\nexport type IncarnationComparison =\n | { verdict: 'match' }\n | { verdict: 'mismatch'; baselineId: string; currentId: string }\n | { verdict: 'not-ready'; readiness: string | undefined }\n | { verdict: 'unidentified' }\n | { verdict: 'no-baseline' }\n\n/**\n * Compare a recorded baseline filesystem-incarnation id against a sandbox's\n * current incarnation fields. Check order mirrors gtm's gate sequence and is\n * itself a tested fail-closed property — each earlier check short-circuits\n * the ones after it, so a box with BOTH bad readiness and a mismatched id\n * resolves `'not-ready'`, never `'mismatch'`:\n *\n * 1. `unidentified` — the current id is missing/empty, or the provenance is\n * not one of `fresh`/`restored`/`unknown`.\n * 2. `not-ready` — readiness is anything other than the literal string\n * `'ready'` (this also catches `undefined`).\n * 3. `no-baseline` — no baseline id was ever recorded to compare against.\n * 4. `mismatch` — the baseline id and current id disagree.\n * 5. `match` — same incarnation.\n */\nexport function compareIncarnationBaseline(\n baselineId: string | undefined,\n current: FilesystemIncarnationLike,\n): IncarnationComparison {\n const currentId = current.filesystemIncarnationId\n const provenance = current.filesystemIncarnationProvenance\n const isValidProvenance = provenance === 'fresh' || provenance === 'restored' || provenance === 'unknown'\n\n if (typeof currentId !== 'string' || currentId.length === 0 || !isValidProvenance) {\n return { verdict: 'unidentified' }\n }\n\n if (current.filesystemIncarnationReadiness !== 'ready') {\n return { verdict: 'not-ready', readiness: current.filesystemIncarnationReadiness }\n }\n\n if (baselineId === undefined) {\n return { verdict: 'no-baseline' }\n }\n\n if (baselineId !== currentId) {\n return { verdict: 'mismatch', baselineId, currentId }\n }\n\n return { verdict: 'match' }\n}\n"],"mappings":";AAgCO,IAAM,+BAA+B;AAKrC,IAAM,wCAAwC;AA4C9C,SAAS,yBAAyB,OAOb;AAC1B,QAAM,eAAe,MAAM,QAAQ,gBAAgB;AACnD,QAAM,eAAe,MAAM,QAAQ,gBAAgB;AACnD,MAAI,CAAC,OAAO,SAAS,YAAY,KAAK,gBAAgB,KAAK,eAAe,GAAG;AAC3E,UAAM,IAAI;AAAA,MACR,6EAA6E,YAAY;AAAA,IAC3F;AAAA,EACF;AACA,MAAI,CAAC,OAAO,SAAS,YAAY,KAAK,eAAe,GAAG;AACtD,UAAM,IAAI;AAAA,MACR,wEAAwE,YAAY;AAAA,IACtF;AAAA,EACF;AACA,QAAM,gBAAgB,MAAM,iBAAiB;AAE7C,QAAM,eAAe,MAAM,cAAc;AACzC,QAAM,cAAc,IAAI,IAAI,MAAM,iBAAiB;AACnD,QAAM,mBAAmB,gBACrB,CAAC,GAAG,MAAM,aAAa,EAAE,KAAK,IAC9B,MAAM,cAAc,OAAO,CAAC,MAAM,YAAY,IAAI,CAAC,CAAC,EAAE,KAAK;AAC/D,QAAM,cAAc,iBAAiB;AACrC,QAAM,gBAAgB,eAAe,IAAI,cAAc,eAAe;AAEtE,QAAM,uBAAuB,iBAAiB,eAAe;AAC7D,QAAM,kBAAkB,cAAc,KAAK,gBAAgB;AAK3D,QAAM,qBAAqB,cAAc,KACpC,gBAAgB,gBAChB,iBAAiB;AAEtB,QAAM,SAAS,uBACV,mBACD,kBACG,cACD,qBACG,mBACD;AAER,SAAO;AAAA,IACL,SAAS,WAAW;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAuCO,SAAS,2BACd,YACA,SACuB;AACvB,QAAM,YAAY,QAAQ;AAC1B,QAAM,aAAa,QAAQ;AAC3B,QAAM,oBAAoB,eAAe,WAAW,eAAe,cAAc,eAAe;AAEhG,MAAI,OAAO,cAAc,YAAY,UAAU,WAAW,KAAK,CAAC,mBAAmB;AACjF,WAAO,EAAE,SAAS,eAAe;AAAA,EACnC;AAEA,MAAI,QAAQ,mCAAmC,SAAS;AACtD,WAAO,EAAE,SAAS,aAAa,WAAW,QAAQ,+BAA+B;AAAA,EACnF;AAEA,MAAI,eAAe,QAAW;AAC5B,WAAO,EAAE,SAAS,cAAc;AAAA,EAClC;AAEA,MAAI,eAAe,WAAW;AAC5B,WAAO,EAAE,SAAS,YAAY,YAAY,UAAU;AAAA,EACtD;AAEA,SAAO,EAAE,SAAS,QAAQ;AAC5B;","names":[]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The Vault's single writer, hosted in a workspace's Durable Object. It
3
+ * serializes mutations, answers head reads and listings after every queued
4
+ * mutation, and fences each committed revision until KV shows it.
5
+ *
6
+ * KV point reads and listings lag their own writes independently, so a
7
+ * revision this coordinator just committed can be missing from either. A
8
+ * visibility fence records the committed truth for that window: head reads
9
+ * wait for the fenced revision, and listings report it in place of what KV
10
+ * lists. A fence retires once both surfaces have shown it.
11
+ *
12
+ * The product's Durable Object routes `/vault/mutate`, `/vault/head/get` and
13
+ * `/vault/head/list` to the handlers here and owns every other route.
14
+ */
15
+ import type { KVStore } from '../../store';
16
+ import { VaultPathError } from './paths';
17
+ import { VaultReadConvergenceError, type VaultHeadState, type VaultMutationPolicy, type VaultMutationRequest, type VaultMutationResult, type VaultVisibilityFence } from './revisions';
18
+ /** The Durable Object storage calls the coordinator makes; Cloudflare's storage satisfies it. */
19
+ export interface VaultCoordinatorStorage {
20
+ get<T>(key: string): Promise<T | undefined>;
21
+ put<T>(key: string, value: T): Promise<void>;
22
+ delete(key: string): Promise<void | boolean>;
23
+ list<T>(options: {
24
+ prefix: string;
25
+ }): Promise<Map<string, T>>;
26
+ }
27
+ /** Sizes of one head listing, for products that watch Durable Object memory. */
28
+ export interface VaultHeadListStats {
29
+ workspaceId: string;
30
+ fences: number;
31
+ headKeys: number;
32
+ entries: number;
33
+ paged: boolean;
34
+ }
35
+ export interface VaultCoordinatorOptions {
36
+ storage: VaultCoordinatorStorage;
37
+ kv: KVStore;
38
+ /** Writer rules every mutation applies; the store's local path must apply the same ones. */
39
+ mutationPolicy?: VaultMutationPolicy;
40
+ /**
41
+ * Runs each queued mutation. `apply` commits the batch and fences what it
42
+ * applied; throw before calling it to refuse the mutation, or do product work
43
+ * around it. Defaults to calling `apply`.
44
+ */
45
+ aroundMutation?: (request: VaultMutationRequest, apply: () => Promise<VaultMutationResult>) => Promise<VaultMutationResult>;
46
+ onHeadList?: (stats: VaultHeadListStats) => void;
47
+ }
48
+ export declare function vaultCoordinatorJson(body: unknown, status?: number): Response;
49
+ /** The 503 body a client turns back into `VaultReadConvergenceError`. */
50
+ export declare function vaultConvergenceResponse(error: VaultReadConvergenceError): Response;
51
+ /** The 400 body a client turns back into the typed `VaultPathError`. */
52
+ export declare function vaultPathErrorResponse(error: VaultPathError): Response;
53
+ /** Create the coordinator for one workspace Durable Object. */
54
+ export declare function createVaultCoordinator(options: VaultCoordinatorOptions): {
55
+ exclusive: <T>(work: () => Promise<T>) => Promise<T>;
56
+ settled: () => Promise<void>;
57
+ readVaultFence: (path: string) => Promise<VaultVisibilityFence | null>;
58
+ observeVaultFence: (fence: VaultVisibilityFence, surface: 'head' | 'list') => Promise<void>;
59
+ readVaultHeadFenced: (workspaceId: string, path: string) => Promise<VaultHeadState>;
60
+ handleVaultHeadGet: (request: Request) => Promise<Response>;
61
+ handleVaultHeadList: (request: Request) => Promise<Response>;
62
+ handleVaultMutation: (request: Request) => Promise<Response>;
63
+ };
64
+ export type VaultCoordinator = ReturnType<typeof createVaultCoordinator>;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Server-only Vault storage engine: path rules and KV key layout, the
3
+ * revision model, the file store a product binds per request, and the
4
+ * coordinator its workspace Durable Object hosts. Products supply their
5
+ * frontmatter codec and the rules around a write through typed config.
6
+ */
7
+ export * from './paths';
8
+ export * from './revisions';
9
+ export * from './tree';
10
+ export * from './store';
11
+ export * from './coordinator';
12
+ export * from './sandbox-sync';