@vite-hub/workspace 0.0.3 → 0.1.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 (129) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +236 -58
  3. package/dist/{ai-nmHdzjCM.d.ts → ai-BW2ZhizI.d.ts} +22 -7
  4. package/dist/{ai-Ce3PtWFW.js → ai-BZyLwULx.js} +147 -66
  5. package/dist/ai.d.ts +2 -2
  6. package/dist/ai.js +1 -1
  7. package/dist/{asset-registry-CaG9b7tf.js → asset-registry-DfBV5kmw.js} +3 -2
  8. package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +19 -0
  9. package/dist/blob-database.d.ts +521 -0
  10. package/dist/blob-database.js +601 -0
  11. package/dist/cloudflare.d.ts +5 -6
  12. package/dist/cloudflare.js +1 -1
  13. package/dist/config-B7dmzDX3.js +1112 -0
  14. package/dist/{config-3I1BnsdO.d.ts → config-DLKdaFWN.d.ts} +1 -2
  15. package/dist/error-diagnostics-A_8Kp-48.js +116 -0
  16. package/dist/error-diagnostics-DY5GP47p.js +96 -0
  17. package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +354 -0
  18. package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +214 -0
  19. package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +527 -0
  20. package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +248 -0
  21. package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +179 -0
  22. package/dist/file-C0_aPWSS.js +26 -0
  23. package/dist/file-metadata-CxDy-E2H.js +58 -0
  24. package/dist/{files-QRV55OCx.js → files-C7Px8uaC.js} +21 -10
  25. package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +2278 -0
  26. package/dist/{github-CfA5vpJ5.js → github-CPxHtFB7.js} +36 -34
  27. package/dist/github-DtncTfmv-Du2S8lGF.js +4159 -0
  28. package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +2530 -0
  29. package/dist/glob--XcLlcml.js +22 -0
  30. package/dist/glob--kNYDbfU.js +30 -0
  31. package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +489 -0
  32. package/dist/host-CFnrTXTK.js +1086 -0
  33. package/dist/{hosted-C1-tTTTf.js → hosted-acMA5XyL.js} +216 -43
  34. package/dist/hosted-vercel-blob-DKntsHaf.js +12603 -0
  35. package/dist/hosted-vercel-blob.d.ts +5 -6
  36. package/dist/hosted-vercel-blob.js +1 -1
  37. package/dist/hosted.d.ts +6 -7
  38. package/dist/hosted.js +1 -1
  39. package/dist/index.d.ts +76 -64
  40. package/dist/index.js +162 -457
  41. package/dist/inspect-BoObD2cJ.js +167 -0
  42. package/dist/internal/path.d.ts +2 -0
  43. package/dist/internal/path.js +2 -0
  44. package/dist/lifecycle-BwZ7c9hb.js +596 -0
  45. package/dist/loader.d.ts +5 -6
  46. package/dist/loader.js +3 -2
  47. package/dist/mcp-resources-BREFCmtn.js +39 -0
  48. package/dist/memory-BbwOqDXl.js +248 -0
  49. package/dist/metadata-target-DZEZQGHA.js +1588 -0
  50. package/dist/mountx.d.ts +4 -6
  51. package/dist/mountx.js +10 -8
  52. package/dist/nitro.d.ts +1 -1
  53. package/dist/nitro.js +1 -1
  54. package/dist/nuxt.d.ts +13 -12
  55. package/dist/nuxt.js +10 -8
  56. package/dist/operations-BcpWr41m.js +159 -0
  57. package/dist/operations-CGqY1XeG.js +965 -0
  58. package/dist/operations-DnOwKsJT.d.ts +136 -0
  59. package/dist/operations.d.ts +53 -0
  60. package/dist/operations.js +2 -0
  61. package/dist/{path-CNI6wKIU.js → path-CNAwN7pw.js} +34 -35
  62. package/dist/path-DrSIenjj.js +59 -0
  63. package/dist/path-zHxQUbqa.d.ts +9 -0
  64. package/dist/plugins-DqQ8b4T5.d.ts +10 -0
  65. package/dist/provider-kXjfli9u.js +1457 -0
  66. package/dist/providers/github/store.d.ts +3 -5
  67. package/dist/providers/github/store.js +1 -1
  68. package/dist/registry-Bp-8UUfG.js +129 -0
  69. package/dist/{registry-BIQVCBWI.d.ts → registry-Cg1TJVVZ.d.ts} +3 -4
  70. package/dist/{request-execution-u9mgUXKX.js → request-execution-Dk9rY-Yh.js} +24 -20
  71. package/dist/rolldown-runtime-B4iAMlE-.js +35 -0
  72. package/dist/runtime/assets.d.ts +3 -5
  73. package/dist/runtime/assets.js +9 -6
  74. package/dist/runtime/empty-assets-registry.d.ts +1 -2
  75. package/dist/runtime/empty-registry.d.ts +1 -2
  76. package/dist/runtime/state.d.ts +4 -4
  77. package/dist/runtime/state.js +10 -7
  78. package/dist/runtime/workspace.d.ts +1 -1
  79. package/dist/runtime/workspace.js +1 -1
  80. package/dist/runtime.d.ts +84 -15
  81. package/dist/runtime.js +561 -108
  82. package/dist/{search-C4REyHj9.js → search-CrTmXj5h.js} +10 -9
  83. package/dist/server-BNQ-Nbjj.js +290 -0
  84. package/dist/server.d.ts +22 -34
  85. package/dist/server.js +2 -355
  86. package/dist/shared-DalXdP0i.js +2158 -0
  87. package/dist/source-metadata.d.ts +7 -1
  88. package/dist/source-metadata.js +34 -2
  89. package/dist/{state-TTqa3x3Y.d.ts → state-B8zbLi5t.d.ts} +14 -13
  90. package/dist/store-CXgmu-uw.js +1729 -0
  91. package/dist/{sync-DiuDmSGk.js → sync-CN6ec-5M.js} +62 -41
  92. package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +125 -0
  93. package/dist/test.d.ts +1 -1
  94. package/dist/test.js +1 -1
  95. package/dist/token-CO62GglH.js +61 -0
  96. package/dist/{types-60Yn149G.d.ts → types-DeK9GIxy.d.ts} +348 -49
  97. package/dist/{use-CsV3oIxH.js → use-BQj7nSz6.js} +200 -45
  98. package/dist/{use-CUFSnFCS.d.ts → use-DhwhbAVV.d.ts} +34 -12
  99. package/dist/utils-Blrh4N2n.js +545 -0
  100. package/dist/vite-BEvgU2GY.js +20909 -0
  101. package/dist/vite-CcZmMQ7S.d.ts +476 -0
  102. package/dist/vite.d.ts +2 -50
  103. package/dist/vite.js +2 -2
  104. package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +1565 -0
  105. package/dist/workspace-6pxkOuxr.js +1286 -0
  106. package/dist/workspace-BWJQBK1u.d.ts +7 -0
  107. package/package.json +90 -59
  108. package/dist/chunk-8H4AJuhK.js +0 -14
  109. package/dist/collections/client.d.ts +0 -39
  110. package/dist/collections/client.js +0 -137
  111. package/dist/collections.d.ts +0 -59
  112. package/dist/collections.js +0 -159
  113. package/dist/config-CDoyls2X.js +0 -30
  114. package/dist/config-CZLO0m9h.js +0 -7811
  115. package/dist/file-CHfsZpso.js +0 -23
  116. package/dist/glob-D0vD_wRY.js +0 -17
  117. package/dist/host-CAnbugpI.js +0 -370
  118. package/dist/hosted-vercel-blob-CWBILDVo.js +0 -257
  119. package/dist/lifecycle-BYoa9hVb.js +0 -176
  120. package/dist/provider-C3_elpEh.js +0 -599
  121. package/dist/publish.d.ts +0 -35
  122. package/dist/publish.js +0 -112
  123. package/dist/registry-CqyDTW9Y.js +0 -74
  124. package/dist/runtime-options-BsPSv5O7.js +0 -13
  125. package/dist/shared-jfogBrd5.js +0 -273
  126. package/dist/store-Bs1SLh55.js +0 -414
  127. package/dist/vite-tbfDxtlu.js +0 -2191
  128. package/dist/workspace-66SKyiec.d.ts +0 -6
  129. package/dist/workspace-C4k92Ow8.js +0 -1460
@@ -0,0 +1,1086 @@
1
+ import { n as __exportAll } from "./rolldown-runtime-B4iAMlE-.js";
2
+ import { a as workspaceConflict, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
3
+ import { a as isExcludedWorkspacePath, f as sha256, i as decodeFile, l as normalizeWorkspacePath, r as contentToBytes } from "./path-CNAwN7pw.js";
4
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-DY5GP47p.js";
5
+ import { n as createSnapshotFromEntries, r as diffSnapshots } from "./utils-Blrh4N2n.js";
6
+ import { r as resolveWorkspaceRevisionMaterializer } from "./store-CXgmu-uw.js";
7
+ import { _ as filterSessionDiff, b as scopedSearchQuery, g as assertPathInSessionScope, h as assertDiffInsideSessionPaths, v as filterSessionEntries, y as isMissingWorkspacePathError } from "./workspace-6pxkOuxr.js";
8
+ import { posix } from "node:path";
9
+ import { randomUUID } from "node:crypto";
10
+ import { normalizeExecutionAuthority } from "@vite-hub/runtime";
11
+ //#region src/session/progress.ts
12
+ async function withWorkspaceProgress(onProgress, event, fn) {
13
+ const startedAt = Date.now();
14
+ await onProgress?.({
15
+ data: event.data,
16
+ id: event.id,
17
+ label: event.label,
18
+ status: "started"
19
+ });
20
+ try {
21
+ const result = await fn();
22
+ await onProgress?.({
23
+ data: event.data,
24
+ durationMs: Date.now() - startedAt,
25
+ id: event.id,
26
+ label: event.label,
27
+ status: "completed"
28
+ });
29
+ return result;
30
+ } catch (error) {
31
+ const message = error instanceof Error ? error.message : String(error);
32
+ await onProgress?.({
33
+ data: {
34
+ ...event.data,
35
+ error: message
36
+ },
37
+ durationMs: Date.now() - startedAt,
38
+ error: message,
39
+ id: event.id,
40
+ label: event.label,
41
+ status: "failed"
42
+ });
43
+ throw error;
44
+ }
45
+ }
46
+ //#endregion
47
+ //#region src/session/host.ts
48
+ var host_exports = /* @__PURE__ */ __exportAll({ createHostedWorkspaceSession: () => createHostedWorkspaceSession });
49
+ const publicationQueues = /* @__PURE__ */ new WeakMap();
50
+ const defaultHostInspectionConcurrency = 16;
51
+ const hostInspectionLimiters = /* @__PURE__ */ new WeakMap();
52
+ const hostMaterializationLimiters = /* @__PURE__ */ new WeakMap();
53
+ function resolveHostInspectionConcurrency(host) {
54
+ const concurrency = host.inspectionConcurrency ?? defaultHostInspectionConcurrency;
55
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw workspaceError("[vitehub] Workspace host inspectionConcurrency must be a positive integer.");
56
+ return concurrency;
57
+ }
58
+ function resolveHostMaterializationConcurrency(host) {
59
+ const concurrency = host.materializationConcurrency ?? 1;
60
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw workspaceError("[vitehub] Workspace host materializationConcurrency must be a positive integer.");
61
+ return concurrency;
62
+ }
63
+ async function mapHostMaterialization(host, values, visit, signal) {
64
+ const concurrency = resolveHostMaterializationConcurrency(host);
65
+ let limit = hostMaterializationLimiters.get(host);
66
+ if (!limit) {
67
+ limit = createHostLimiter(concurrency);
68
+ hostMaterializationLimiters.set(host, limit);
69
+ }
70
+ let next = 0;
71
+ let failed = false;
72
+ let failure;
73
+ const workers = Array.from({ length: Math.min(values.length, concurrency) }, async () => {
74
+ while (!failed) {
75
+ signal?.throwIfAborted();
76
+ const index = next++;
77
+ if (index >= values.length) return;
78
+ try {
79
+ await limit(async () => {
80
+ if (failed) return;
81
+ signal?.throwIfAborted();
82
+ try {
83
+ await visit(values[index]);
84
+ } catch (error) {
85
+ if (!failed) failure = error;
86
+ failed = true;
87
+ }
88
+ }, signal);
89
+ } catch (error) {
90
+ if (!failed) failure = error;
91
+ failed = true;
92
+ }
93
+ }
94
+ });
95
+ await Promise.allSettled(workers);
96
+ if (failed) throw failure;
97
+ signal?.throwIfAborted();
98
+ }
99
+ function resolveHostInspectionLimiter(host) {
100
+ const existing = hostInspectionLimiters.get(host);
101
+ if (existing) return existing;
102
+ const limit = createHostLimiter(resolveHostInspectionConcurrency(host));
103
+ hostInspectionLimiters.set(host, limit);
104
+ return limit;
105
+ }
106
+ function createHostLimiter(concurrency) {
107
+ let active = 0;
108
+ const queued = [];
109
+ const run = async (inspect, signal) => {
110
+ signal?.throwIfAborted();
111
+ if (active < concurrency) active++;
112
+ else await new Promise((resolve, reject) => {
113
+ const entry = { grant: () => {
114
+ signal?.removeEventListener("abort", abort);
115
+ active++;
116
+ resolve();
117
+ } };
118
+ const abort = () => {
119
+ const index = queued.indexOf(entry);
120
+ if (index < 0) return;
121
+ queued.splice(index, 1);
122
+ reject(signal?.reason);
123
+ };
124
+ signal?.addEventListener("abort", abort, { once: true });
125
+ queued.push(entry);
126
+ if (signal?.aborted) abort();
127
+ });
128
+ try {
129
+ return await inspect();
130
+ } finally {
131
+ active--;
132
+ queued.shift()?.grant();
133
+ }
134
+ };
135
+ return run;
136
+ }
137
+ function inspectHost(host, inspect, signal, batch) {
138
+ return resolveHostInspectionLimiter(host)(async () => {
139
+ batch?.assertActive();
140
+ try {
141
+ return await inspect();
142
+ } catch (error) {
143
+ batch?.fail(error);
144
+ throw error;
145
+ }
146
+ }, signal);
147
+ }
148
+ async function mapHostInspections(host, values, visit, _signal) {
149
+ const results = [];
150
+ let next = 0;
151
+ let failed = false;
152
+ let failure;
153
+ const assertActive = () => {
154
+ if (failed) throw failure;
155
+ };
156
+ const fail = (error) => {
157
+ if (!failed) failure = error;
158
+ failed = true;
159
+ };
160
+ const batch = {
161
+ assertActive,
162
+ fail
163
+ };
164
+ const workers = Array.from({ length: Math.min(values.length, resolveHostInspectionConcurrency(host)) }, async () => {
165
+ while (!failed) {
166
+ const index = next++;
167
+ if (index >= values.length) return;
168
+ try {
169
+ results[index] = await visit(values[index], batch);
170
+ } catch (error) {
171
+ fail(error);
172
+ }
173
+ }
174
+ });
175
+ await Promise.all(workers);
176
+ if (failed) throw failure;
177
+ return results;
178
+ }
179
+ async function waitForOperation(operation, signal) {
180
+ signal?.throwIfAborted();
181
+ if (!signal) return await operation;
182
+ return await new Promise((resolve, reject) => {
183
+ const abort = () => reject(signal.reason);
184
+ signal.addEventListener("abort", abort, { once: true });
185
+ operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
186
+ });
187
+ }
188
+ async function withWorkspacePublication(key, signal, publish) {
189
+ const previous = publicationQueues.get(key) || Promise.resolve();
190
+ let release;
191
+ const current = new Promise((resolve) => {
192
+ release = resolve;
193
+ });
194
+ publicationQueues.set(key, current);
195
+ try {
196
+ await waitForOperation(previous, signal);
197
+ } catch (error) {
198
+ previous.finally(release);
199
+ throw error;
200
+ }
201
+ try {
202
+ return await publish();
203
+ } finally {
204
+ release();
205
+ if (publicationQueues.get(key) === current) publicationQueues.delete(key);
206
+ }
207
+ }
208
+ function normalizeTarget(target = "/workspace") {
209
+ const normalized = posix.resolve("/", target.replace(/\\/g, "/"));
210
+ if (normalized === "/") throw workspaceError("[vitehub] Workspace session target cannot be the host root.");
211
+ return normalized;
212
+ }
213
+ function normalizeSearchRoot(path) {
214
+ const normalized = posix.normalize(path.replace(/\\/g, "/"));
215
+ return normalized === "." ? "" : normalizeSafeWorkspacePath(normalized, { allowEmpty: true });
216
+ }
217
+ function normalizeReadableSessionPath(path) {
218
+ const normalized = normalizeSafeWorkspacePath(path, { allowReserved: true });
219
+ if (/^\.vitehub\/sources\/[^/]+\.json$/.test(normalized)) return normalized;
220
+ return normalizeSafeWorkspacePath(path);
221
+ }
222
+ function toHostPath(root, path = "") {
223
+ const normalized = normalizeSafeWorkspacePath(path, {
224
+ allowEmpty: true,
225
+ allowReserved: true
226
+ });
227
+ return normalized ? posix.join(root, normalized) : root;
228
+ }
229
+ function toHostCwd(root, cwd) {
230
+ if (cwd === void 0) return root;
231
+ if (!posix.isAbsolute(cwd)) return toHostPath(root, cwd);
232
+ const normalized = posix.normalize(cwd);
233
+ if (normalized === root || normalized.startsWith(`${root}/`)) return normalized;
234
+ if (normalized === "/workspace" || normalized.startsWith("/workspace/")) return toHostPath(root, normalized === "/workspace" ? "" : normalized.slice(11));
235
+ throw workspaceError(`[vitehub] Workspace exec cwd must stay inside ${root}: ${cwd}.`);
236
+ }
237
+ function fromHostPath(root, path) {
238
+ const normalizedRoot = root.replace(/\/+$/, "");
239
+ const normalizedPath = posix.resolve(root, path).replace(/\/+$/, "");
240
+ if (normalizedPath === normalizedRoot) return "";
241
+ if (!normalizedPath.startsWith(`${normalizedRoot}/`)) throw workspaceError(`[vitehub] Workspace host returned a path outside ${root}: ${path}.`);
242
+ return normalizeSafeWorkspacePath(normalizedPath.slice(normalizedRoot.length + 1), { allowReserved: true });
243
+ }
244
+ function isGitSymlinkEntry(entry) {
245
+ return entry.metadata?.gitMode === "120000";
246
+ }
247
+ function hasSymlinkParent(path, symlinks) {
248
+ let parent = posix.dirname(path);
249
+ while (parent && parent !== "." && parent !== "/") {
250
+ if (symlinks.has(parent)) return true;
251
+ parent = posix.dirname(parent);
252
+ }
253
+ return false;
254
+ }
255
+ function isSafeHostSymlink(root, path, target) {
256
+ if (posix.isAbsolute(target)) return false;
257
+ const resolved = posix.resolve(posix.dirname(toHostPath(root, path)), target);
258
+ return resolved === root || resolved.startsWith(`${root}/`);
259
+ }
260
+ async function isHostPath(host, path, flag, abortSignal) {
261
+ abortSignal?.throwIfAborted();
262
+ return (await inspectHost(host, async () => await host.exec("test", [flag, path], { signal: abortSignal }), abortSignal)).code === 0;
263
+ }
264
+ async function assertHostWorkspaceRoot(host, root, abortSignal) {
265
+ if (await isHostPath(host, root, "-L", abortSignal) || !await isHostPath(host, root, "-d", abortSignal)) throw workspaceError(`[vitehub] Workspace host root must be a directory: ${root}.`);
266
+ }
267
+ async function ensureHostWorkspaceRoot(host, root, abortSignal) {
268
+ const symlink = await isHostPath(host, root, "-L", abortSignal);
269
+ if (!symlink && await isHostPath(host, root, "-d", abortSignal)) return false;
270
+ if (symlink || await inspectHost(host, async () => await host.files.exists(root, { signal: abortSignal }), abortSignal)) await host.files.remove(root, {
271
+ recursive: false,
272
+ signal: abortSignal
273
+ });
274
+ await host.files.mkdir(root, {
275
+ recursive: true,
276
+ signal: abortSignal
277
+ });
278
+ await assertHostWorkspaceRoot(host, root, abortSignal);
279
+ return true;
280
+ }
281
+ async function removeHostSymlinkAncestors(host, root, path, abortSignal) {
282
+ let ancestor = root;
283
+ for (const component of fromHostPath(root, path).split("/").slice(0, -1)) {
284
+ ancestor = posix.join(ancestor, component);
285
+ abortSignal?.throwIfAborted();
286
+ if (!await isHostPath(host, ancestor, "-L", abortSignal)) continue;
287
+ await host.files.remove(ancestor, {
288
+ recursive: false,
289
+ signal: abortSignal
290
+ });
291
+ if (await isHostPath(host, ancestor, "-L", abortSignal)) throw workspaceError(`[vitehub] Failed to remove Workspace symlink ancestor: ${ancestor}.`);
292
+ return;
293
+ }
294
+ }
295
+ async function removeHostPath(host, root, path, recursive, abortSignal) {
296
+ abortSignal?.throwIfAborted();
297
+ await removeHostSymlinkAncestors(host, root, path, abortSignal);
298
+ await host.files.remove(path, {
299
+ recursive: await isHostPath(host, path, "-L", abortSignal) ? false : recursive,
300
+ signal: abortSignal
301
+ });
302
+ }
303
+ async function assertNoHostSymlinkParent(host, root, target, abortSignal) {
304
+ const path = fromHostPath(root, target);
305
+ if (hasSymlinkParent(path, new Set((await listHostEntries(host, root, "", true, void 0, false, [], abortSignal)).filter(isGitSymlinkEntry).map((entry) => entry.path)))) throw workspaceError(`[vitehub] Workspace host path crosses a symlink parent: ${path}.`);
306
+ }
307
+ function toWorkspaceEntry(root, entry) {
308
+ return {
309
+ metadata: entry.type === "symlink" ? { gitMode: "120000" } : entry.type === "file" && entry.executable ? { gitMode: "100755" } : void 0,
310
+ path: fromHostPath(root, entry.path),
311
+ size: entry.size,
312
+ type: entry.type === "directory" ? "directory" : "file"
313
+ };
314
+ }
315
+ async function ensureHostParent(host, path, abortSignal) {
316
+ const parent = posix.dirname(path);
317
+ if (parent && parent !== "." && parent !== "/") await host.files.mkdir(parent, {
318
+ recursive: true,
319
+ signal: abortSignal
320
+ });
321
+ }
322
+ async function readHostSymlinkTarget(host, root, path, abortSignal, batch) {
323
+ return await inspectHost(host, async () => {
324
+ const result = await host.exec("readlink", [fromHostPath(root, path)], {
325
+ cwd: root,
326
+ signal: abortSignal
327
+ });
328
+ if (result.code !== 0) throw workspaceError(`[vitehub] Failed to read workspace symlink: ${path}.`, { cause: workspaceErrorDiagnostics.WORKSPACE_R0044({ message: result.stderr || "readlink failed" }) });
329
+ return result.stdout.replace(/\n$/, "");
330
+ }, abortSignal, batch);
331
+ }
332
+ async function writeHostSymlink(host, root, path, target, abortSignal) {
333
+ await removeHostPath(host, root, path, false, abortSignal);
334
+ const result = await host.exec("ln", [
335
+ "-s",
336
+ target,
337
+ fromHostPath(root, path)
338
+ ], {
339
+ cwd: root,
340
+ signal: abortSignal
341
+ });
342
+ if (result.code !== 0) throw workspaceError(`[vitehub] Failed to create workspace symlink: ${path}. ${result.stderr || "ln failed"}`);
343
+ }
344
+ async function readHostFile(host, root, path, abortSignal) {
345
+ await assertHostWorkspaceRoot(host, root, abortSignal);
346
+ if (!await inspectHost(host, async () => await host.files.exists(path, { signal: abortSignal }), abortSignal)) return void 0;
347
+ const content = await inspectHost(host, async () => await host.files.read(path, { signal: abortSignal }), abortSignal);
348
+ return content ? {
349
+ content,
350
+ path: fromHostPath(root, path)
351
+ } : void 0;
352
+ }
353
+ function gitMetadataRoot(path) {
354
+ const parts = path.split("/");
355
+ const index = parts.findIndex((part) => part.toLowerCase() === ".git");
356
+ return index === -1 ? void 0 : parts.slice(0, index + 1).join("/");
357
+ }
358
+ async function removeHostGitMetadata(host, root, signal) {
359
+ const directories = [""];
360
+ for (let index = 0; index < directories.length; index++) {
361
+ signal?.throwIfAborted();
362
+ const directory = directories[index];
363
+ for (const entry of await inspectHost(host, async () => await host.files.list(toHostPath(root, directory), { signal }), signal)) {
364
+ const path = fromHostPath(root, entry.path);
365
+ const gitRoot = gitMetadataRoot(path);
366
+ if (gitRoot) await removeHostPath(host, root, toHostPath(root, gitRoot), true, signal);
367
+ else if (entry.type === "directory") directories.push(path);
368
+ }
369
+ }
370
+ }
371
+ async function listHostEntries(host, root, path = "", recursive = false, include, includeGit = false, excluded = [], abortSignal) {
372
+ abortSignal?.throwIfAborted();
373
+ await assertHostWorkspaceRoot(host, root, abortSignal);
374
+ const workspacePath = normalizeSafeWorkspacePath(path, {
375
+ allowEmpty: true,
376
+ allowReserved: true
377
+ });
378
+ if (isExcludedWorkspacePath(workspacePath, excluded)) return [];
379
+ const hostExcluded = excluded.map((item) => toHostPath(root, normalizeWorkspacePath(item)));
380
+ return (await mapHostInspections(host, (await inspectHost(host, async () => await host.files.list(toHostPath(root, workspacePath), {
381
+ exclude: hostExcluded,
382
+ recursive,
383
+ signal: abortSignal
384
+ }), abortSignal)).map((entry) => ({
385
+ executable: entry.executable,
386
+ workspaceEntry: toWorkspaceEntry(root, entry)
387
+ })).filter(({ workspaceEntry }) => !isExcludedWorkspacePath(workspaceEntry.path, excluded) && (!include || include(workspaceEntry))), async ({ executable, workspaceEntry }, batch) => {
388
+ abortSignal?.throwIfAborted();
389
+ if (workspaceEntry.type !== "file" || isGitSymlinkEntry(workspaceEntry)) return workspaceEntry;
390
+ if (executable !== void 0) return workspaceEntry;
391
+ return (await inspectHost(host, async () => await host.exec("test", ["-x", workspaceEntry.path], {
392
+ cwd: root,
393
+ signal: abortSignal
394
+ }), abortSignal, batch)).code === 0 ? {
395
+ ...workspaceEntry,
396
+ metadata: {
397
+ ...workspaceEntry.metadata,
398
+ gitMode: "100755"
399
+ }
400
+ } : workspaceEntry;
401
+ }, abortSignal)).filter((entry) => entry.path && (includeGit || !gitMetadataRoot(entry.path))).sort((left, right) => left.path.localeCompare(right.path));
402
+ }
403
+ async function makeHostFileExecutable(host, root, path, abortSignal) {
404
+ const result = await host.exec("chmod", ["+x", fromHostPath(root, path)], {
405
+ cwd: root,
406
+ signal: abortSignal
407
+ });
408
+ if (result.code !== 0) throw workspaceError(`[vitehub] Failed to preserve executable Workspace file: ${path}. ${result.stderr || "chmod failed"}`);
409
+ }
410
+ async function snapshotHost(host, root, name, abortSignal) {
411
+ return (await captureHostState(host, root, name, abortSignal)).snapshot;
412
+ }
413
+ async function captureHostState(host, root, name, abortSignal) {
414
+ abortSignal?.throwIfAborted();
415
+ if (await isHostPath(host, root, "-L", abortSignal)) throw workspaceError(`[vitehub] Workspace host root must be a directory: ${root}.`);
416
+ if (!await inspectHost(host, async () => await host.files.exists(root, { signal: abortSignal }), abortSignal)) return {
417
+ contents: /* @__PURE__ */ new Map(),
418
+ snapshot: await createSnapshotFromEntries([], name)
419
+ };
420
+ return await captureHostEntriesState(host, root, await listHostEntries(host, root, "", true, void 0, false, [], abortSignal), name, abortSignal);
421
+ }
422
+ async function captureHostEntriesState(host, root, entries, name, abortSignal) {
423
+ const contents = /* @__PURE__ */ new Map();
424
+ const files = await mapHostInspections(host, entries, async (entry, batch) => {
425
+ abortSignal?.throwIfAborted();
426
+ if (entry.type !== "file") return entry;
427
+ const content = isGitSymlinkEntry(entry) ? await readHostSymlinkTarget(host, root, toHostPath(root, entry.path), abortSignal, batch) : await inspectHost(host, async () => {
428
+ const content = await host.files.read(toHostPath(root, entry.path), { signal: abortSignal });
429
+ if (content === null) throw workspaceError(`[vitehub] Workspace host file disappeared while snapshotting: ${entry.path}.`);
430
+ return content;
431
+ }, abortSignal, batch);
432
+ contents.set(entry.path, content);
433
+ return {
434
+ ...entry,
435
+ digest: await sha256(content),
436
+ size: contentToBytes(content).byteLength
437
+ };
438
+ }, abortSignal);
439
+ return {
440
+ contents,
441
+ snapshot: await createSnapshotFromEntries(files, name)
442
+ };
443
+ }
444
+ function isInsideExcludedWriteBackPath(path, excluded) {
445
+ return Boolean(gitMetadataRoot(path)) || excluded.some((item) => path === item || path.startsWith(`${item}/`));
446
+ }
447
+ async function captureExcludedHostState(host, root, excluded, abortSignal) {
448
+ abortSignal?.throwIfAborted();
449
+ if (await isHostPath(host, root, "-L", abortSignal)) throw workspaceError(`[vitehub] Workspace host root must be a directory: ${root}.`);
450
+ if (!await inspectHost(host, async () => await host.files.exists(root, { signal: abortSignal }), abortSignal)) return await captureHostEntriesState(host, root, [], "host-excluded", abortSignal);
451
+ return await captureHostEntriesState(host, root, await listHostEntries(host, root, "", true, (entry) => isInsideExcludedWriteBackPath(entry.path, excluded), true, [], abortSignal), "host-excluded", abortSignal);
452
+ }
453
+ function mergeExcludedHostState(before, materialized, excluded) {
454
+ const beforePaths = Object.keys(before.snapshot.entries);
455
+ const occupiedRoots = [.../* @__PURE__ */ new Set([...excluded.filter((root) => beforePaths.some((path) => path === root || path.startsWith(`${root}/`))), ...beforePaths.map(gitMetadataRoot).filter((path) => Boolean(path))])];
456
+ const entries = Object.fromEntries([...Object.entries(materialized.snapshot.entries).filter(([path]) => !occupiedRoots.some((root) => path === root || path.startsWith(`${root}/`))), ...Object.entries(before.snapshot.entries)]);
457
+ const contents = new Map(materialized.contents);
458
+ for (const root of occupiedRoots) for (const path of contents.keys()) if (path === root || path.startsWith(`${root}/`)) contents.delete(path);
459
+ for (const [path, content] of before.contents) contents.set(path, content);
460
+ return {
461
+ contents,
462
+ snapshot: {
463
+ ...materialized.snapshot,
464
+ entries
465
+ }
466
+ };
467
+ }
468
+ async function restoreExcludedHostState(host, root, excluded, state, abortSignal) {
469
+ const currentGitRoots = (await listHostEntries(host, root, "", true, (entry) => Boolean(gitMetadataRoot(entry.path)), true, [], abortSignal)).map((entry) => gitMetadataRoot(entry.path));
470
+ const excludedRoots = [.../* @__PURE__ */ new Set([...excluded, ...currentGitRoots])];
471
+ const roots = excludedRoots.filter((path, index) => !excludedRoots.some((parent, parentIndex) => parentIndex !== index && path.startsWith(`${parent}/`)));
472
+ for (const path of roots.sort((left, right) => right.length - left.length)) {
473
+ abortSignal?.throwIfAborted();
474
+ await removeHostPath(host, root, toHostPath(root, path), true, abortSignal);
475
+ }
476
+ const entries = Object.entries(state.snapshot.entries).sort(([left], [right]) => left.split("/").length - right.split("/").length);
477
+ for (const [path, entry] of entries) {
478
+ abortSignal?.throwIfAborted();
479
+ const target = toHostPath(root, path);
480
+ await removeHostSymlinkAncestors(host, root, target, abortSignal);
481
+ if (entry.type === "directory") {
482
+ await host.files.mkdir(target, {
483
+ recursive: true,
484
+ signal: abortSignal
485
+ });
486
+ continue;
487
+ }
488
+ const content = state.contents.get(path);
489
+ if (content === void 0) continue;
490
+ await ensureHostParent(host, target, abortSignal);
491
+ if (entry.metadata?.gitMode === "120000") await writeHostSymlink(host, root, target, String(content), abortSignal);
492
+ else {
493
+ await host.files.write(target, contentToBytes(content), { signal: abortSignal });
494
+ if (entry.metadata?.gitMode === "100755") await makeHostFileExecutable(host, root, target, abortSignal);
495
+ }
496
+ }
497
+ }
498
+ async function restoreAttachedHost(host, root, diff, state, abortSignal) {
499
+ const changed = [...new Set(diff.entries.map((entry) => entry.path))];
500
+ for (const path of changed.sort((left, right) => right.length - left.length)) {
501
+ abortSignal?.throwIfAborted();
502
+ await removeHostPath(host, root, toHostPath(root, path), true, abortSignal);
503
+ }
504
+ const baselineEntries = changed.map((path) => [path, state.snapshot.entries[path]]).filter((entry) => Boolean(entry[1])).sort(([left], [right]) => left.split("/").length - right.split("/").length);
505
+ for (const [path, entry] of baselineEntries) {
506
+ abortSignal?.throwIfAborted();
507
+ const target = toHostPath(root, path);
508
+ await removeHostSymlinkAncestors(host, root, target, abortSignal);
509
+ if (entry.type === "directory") {
510
+ await host.files.mkdir(target, {
511
+ recursive: true,
512
+ signal: abortSignal
513
+ });
514
+ continue;
515
+ }
516
+ const content = state.contents.get(path);
517
+ if (content === void 0) continue;
518
+ await ensureHostParent(host, target, abortSignal);
519
+ if (entry.metadata?.gitMode === "120000") await writeHostSymlink(host, root, target, String(content), abortSignal);
520
+ else {
521
+ await host.files.write(target, contentToBytes(content), { signal: abortSignal });
522
+ if (entry.metadata?.gitMode === "100755") await makeHostFileExecutable(host, root, target, abortSignal);
523
+ }
524
+ }
525
+ }
526
+ async function resetHostWorkspaceRoot(host, root, abortSignal) {
527
+ if (await ensureHostWorkspaceRoot(host, root, abortSignal)) return;
528
+ for (const entry of await inspectHost(host, async () => await host.files.list(root, { signal: abortSignal }), abortSignal)) {
529
+ abortSignal?.throwIfAborted();
530
+ await removeHostPath(host, root, entry.path, true, abortSignal);
531
+ }
532
+ }
533
+ function isExcludedWriteBackPath(path, excluded) {
534
+ return Boolean(gitMetadataRoot(path)) || excluded.some((item) => path === item || path.startsWith(`${item}/`) || item.startsWith(`${path}/`));
535
+ }
536
+ const defaultExcludedSessionPaths = [
537
+ ".agent-runs",
538
+ ".git",
539
+ ".vitehub"
540
+ ];
541
+ function isExcludedSessionSourcePath(path) {
542
+ if (path === ".vitehub/sources" || path.startsWith(".vitehub/sources/")) return false;
543
+ return isExcludedWriteBackPath(path, defaultExcludedSessionPaths);
544
+ }
545
+ function filterWriteBackDiff(diff, excluded) {
546
+ return {
547
+ ...diff,
548
+ entries: diff.entries.filter((entry) => !isExcludedWriteBackPath(entry.path, excluded))
549
+ };
550
+ }
551
+ function normalizeSessionPaths(options) {
552
+ if (options?.paths === void 0) return void 0;
553
+ const paths = [...new Set(options.paths.map((path) => normalizeSafeWorkspacePath(path, {
554
+ allowEmpty: true,
555
+ allowReserved: true
556
+ })))];
557
+ if (paths.includes("")) return void 0;
558
+ return paths.sort((left, right) => left.length - right.length || left.localeCompare(right));
559
+ }
560
+ async function sessionEntries(workspace, options) {
561
+ const paths = normalizeSessionPaths(options);
562
+ const entries = /* @__PURE__ */ new Map();
563
+ const directories = paths ? [] : [""];
564
+ if (paths) for (const path of paths) {
565
+ const excluded = isExcludedSessionSourcePath(path);
566
+ if (excluded && path !== ".vitehub") continue;
567
+ const stat = await workspace.stat(path).catch((error) => {
568
+ if (isMissingWorkspacePathError(error)) return void 0;
569
+ throw error;
570
+ });
571
+ if (!stat) continue;
572
+ if (!excluded) entries.set(stat.path, stat);
573
+ if (stat.type === "directory") directories.push(stat.path);
574
+ }
575
+ const visited = /* @__PURE__ */ new Set();
576
+ for (let index = 0; index < directories.length; index++) {
577
+ const directory = directories[index];
578
+ if (visited.has(directory)) continue;
579
+ visited.add(directory);
580
+ for (const entry of await workspace.list(directory)) {
581
+ const excluded = isExcludedSessionSourcePath(entry.path);
582
+ if (!excluded) entries.set(entry.path, entry);
583
+ if (entry.type === "directory" && (!excluded || entry.path === ".vitehub")) directories.push(entry.path);
584
+ }
585
+ }
586
+ return [...entries.values()].sort((left, right) => left.path.localeCompare(right.path));
587
+ }
588
+ async function extractRevisionArchive(host, root, materialization, signal) {
589
+ const stagingRoot = posix.join(root, `.vitehub-workspace-${randomUUID()}`);
590
+ const archive = posix.join(stagingRoot, "revision.tar.gz");
591
+ const staging = posix.join(stagingRoot, "extracted");
592
+ await host.files.mkdir(stagingRoot, {
593
+ recursive: true,
594
+ signal
595
+ });
596
+ await host.files.write(archive, materialization.archive, { signal });
597
+ await host.files.mkdir(staging, {
598
+ recursive: true,
599
+ signal
600
+ });
601
+ try {
602
+ const listed = await inspectHost(host, async () => await host.exec("tar", ["-tzf", archive], { signal }), signal);
603
+ if (listed.code !== 0) throw workspaceError(`[vitehub] Failed to inspect Workspace revision ${materialization.revision}: ${listed.stderr || "tar failed"}`);
604
+ const unsafeMember = listed.stdout.split("\n").filter(Boolean).find((member) => {
605
+ if (member.startsWith("/") || member.includes("\0")) return true;
606
+ return member.replace(/\/+$/, "").split("/").includes("..");
607
+ });
608
+ if (unsafeMember) throw workspaceError(`[vitehub] Workspace revision archive contains an unsafe path: ${unsafeMember}.`);
609
+ const extracted = await host.exec("tar", [
610
+ "-xzf",
611
+ archive,
612
+ "-C",
613
+ staging
614
+ ], { signal });
615
+ if (extracted.code !== 0) throw workspaceError(`[vitehub] Failed to extract Workspace revision ${materialization.revision}: ${extracted.stderr || "tar failed"}`);
616
+ const roots = (await inspectHost(host, async () => await host.files.list(staging, { signal }), signal)).filter((entry) => entry.type === "directory");
617
+ if (roots.length !== 1) throw workspaceError(`[vitehub] Workspace revision archive must contain one repository root.`);
618
+ const archiveRoot = normalizeSafeWorkspacePath(materialization.root, {
619
+ allowEmpty: true,
620
+ allowReserved: true
621
+ });
622
+ let source = roots[0].path;
623
+ let validSource = true;
624
+ for (const component of archiveRoot.split("/").filter(Boolean)) {
625
+ source = posix.join(source, component);
626
+ if ((await inspectHost(host, async () => await host.exec("test", ["-L", source], { signal }), signal)).code === 0) throw workspaceError(`[vitehub] Workspace revision archive root must not contain symlinks: ${materialization.root}.`);
627
+ if ((await inspectHost(host, async () => await host.exec("test", ["-d", source], { signal }), signal)).code !== 0) {
628
+ validSource = false;
629
+ break;
630
+ }
631
+ }
632
+ if (!validSource && materialization.files > 0) throw workspaceError(`[vitehub] Workspace revision archive is missing ${materialization.root || "its repository root"}.`);
633
+ if (!validSource) return;
634
+ const paths = materialization.paths;
635
+ if (!paths) {
636
+ const copied = await host.exec("cp", [
637
+ "-a",
638
+ `${source}/.`,
639
+ root
640
+ ], { signal });
641
+ if (copied.code !== 0) throw workspaceError(`[vitehub] Failed to materialize Workspace revision ${materialization.revision}: ${copied.stderr || "copy failed"}`);
642
+ } else for (const path of paths) {
643
+ const selected = posix.join(source, path);
644
+ if (!await inspectHost(host, async () => await host.files.exists(selected, { signal }), signal)) continue;
645
+ const destination = toHostPath(root, posix.dirname(path) === "." ? "" : posix.dirname(path));
646
+ await host.files.mkdir(destination, {
647
+ recursive: true,
648
+ signal
649
+ });
650
+ const copied = await host.exec("cp", [
651
+ "-a",
652
+ selected,
653
+ destination
654
+ ], { signal });
655
+ if (copied.code !== 0) throw workspaceError(`[vitehub] Failed to materialize Workspace revision ${materialization.revision}: ${copied.stderr || "copy failed"}`);
656
+ }
657
+ } finally {
658
+ await removeHostPath(host, root, stagingRoot, true, signal);
659
+ }
660
+ }
661
+ async function sanitizeHostSymlinks(host, root, abortSignal) {
662
+ const symlinks = (await listHostEntries(host, root, "", true, void 0, false, [], abortSignal)).filter(isGitSymlinkEntry);
663
+ for (const entry of symlinks) {
664
+ abortSignal?.throwIfAborted();
665
+ const path = toHostPath(root, entry.path);
666
+ const target = await readHostSymlinkTarget(host, root, path, abortSignal);
667
+ if (isSafeHostSymlink(root, entry.path, target)) continue;
668
+ await host.files.remove(path, {
669
+ recursive: false,
670
+ signal: abortSignal
671
+ });
672
+ await host.files.write(path, contentToBytes(target), { signal: abortSignal });
673
+ }
674
+ }
675
+ async function materializeWorkspace(workspace, host, root, options, useRevisionMaterializer = true, onHostMutation, captureSnapshot = true) {
676
+ const abortSignal = options?.abortSignal;
677
+ abortSignal?.throwIfAborted();
678
+ const paths = normalizeSessionPaths(options);
679
+ const materializer = useRevisionMaterializer ? resolveWorkspaceRevisionMaterializer(workspace) : void 0;
680
+ const revision = materializer ? await withWorkspaceProgress(options?.onProgress, {
681
+ data: { paths: paths ?? null },
682
+ id: "workspace.prepare.revision",
683
+ label: "Resolving workspace revision"
684
+ }, async () => await materializer.materializeRevision({
685
+ abortSignal: options?.abortSignal,
686
+ paths
687
+ })) : void 0;
688
+ await withWorkspaceProgress(options?.onProgress, {
689
+ id: "workspace.prepare.reset-sandbox",
690
+ label: "Resetting sandbox workspace"
691
+ }, async () => {
692
+ onHostMutation?.();
693
+ await resetHostWorkspaceRoot(host, root, abortSignal);
694
+ });
695
+ abortSignal?.throwIfAborted();
696
+ if (revision?.archive) {
697
+ await withWorkspaceProgress(options?.onProgress, {
698
+ data: {
699
+ bytes: revision.archive.byteLength,
700
+ files: revision.files,
701
+ revision: revision.revision
702
+ },
703
+ id: "workspace.prepare.extract-archive",
704
+ label: "Extracting workspace revision"
705
+ }, async () => await extractRevisionArchive(host, root, {
706
+ ...revision,
707
+ archive: revision.archive
708
+ }, options?.abortSignal));
709
+ abortSignal?.throwIfAborted();
710
+ await Promise.all(defaultExcludedSessionPaths.map((path) => removeHostPath(host, root, toHostPath(root, path), true, abortSignal)));
711
+ await removeHostGitMetadata(host, root, abortSignal);
712
+ abortSignal?.throwIfAborted();
713
+ await sanitizeHostSymlinks(host, root, abortSignal);
714
+ abortSignal?.throwIfAborted();
715
+ const snapshot = captureSnapshot ? options?.writeBack === false ? await createSnapshotFromEntries(await listHostEntries(host, root, "", true, void 0, false, [], abortSignal), "host-open") : await snapshotHost(host, root, "host-open", abortSignal) : void 0;
716
+ abortSignal?.throwIfAborted();
717
+ return {
718
+ revision: revision.revision,
719
+ snapshot
720
+ };
721
+ }
722
+ const entries = await withWorkspaceProgress(options?.onProgress, {
723
+ data: { paths: paths ?? null },
724
+ id: "workspace.prepare.entries",
725
+ label: "Resolving workspace entries"
726
+ }, async () => await sessionEntries(workspace, options));
727
+ const symlinks = new Set(entries.filter(isGitSymlinkEntry).map((entry) => entry.path));
728
+ const nested = entries.find((entry) => hasSymlinkParent(entry.path, symlinks));
729
+ if (nested) throw workspaceError(`[vitehub] Workspace path crosses a symlink parent: ${nested.path}.`);
730
+ for (const entry of entries.filter((entry) => entry.type === "directory")) {
731
+ abortSignal?.throwIfAborted();
732
+ await host.files.mkdir(toHostPath(root, entry.path), {
733
+ recursive: true,
734
+ signal: abortSignal
735
+ });
736
+ abortSignal?.throwIfAborted();
737
+ }
738
+ await withWorkspaceProgress(options?.onProgress, {
739
+ data: {
740
+ bytes: entries.reduce((total, entry) => total + (entry.size || 0), 0),
741
+ files: entries.filter((entry) => entry.type === "file").length
742
+ },
743
+ id: "workspace.prepare.read-files",
744
+ label: "Reading workspace files"
745
+ }, async () => {
746
+ abortSignal?.throwIfAborted();
747
+ await mapHostMaterialization(host, entries.filter((entry) => entry.type === "file"), async (entry) => {
748
+ abortSignal?.throwIfAborted();
749
+ const target = toHostPath(root, entry.path);
750
+ await ensureHostParent(host, target, abortSignal);
751
+ if (isGitSymlinkEntry(entry)) {
752
+ const symlinkTarget = typeof entry.metadata?.symlinkTarget === "string" ? entry.metadata.symlinkTarget : new TextDecoder().decode(contentToBytes(await workspace.readFile(entry.path, { encoding: "binary" })));
753
+ if (isSafeHostSymlink(root, entry.path, symlinkTarget)) await writeHostSymlink(host, root, target, symlinkTarget, abortSignal);
754
+ else await host.files.write(target, contentToBytes(symlinkTarget), { signal: abortSignal });
755
+ } else {
756
+ const content = contentToBytes(await workspace.readFile(entry.path, { encoding: "binary" }));
757
+ await host.files.write(target, content, { signal: abortSignal });
758
+ if (entry.metadata?.gitMode === "100755") await makeHostFileExecutable(host, root, target, abortSignal);
759
+ }
760
+ abortSignal?.throwIfAborted();
761
+ }, abortSignal);
762
+ });
763
+ if (revision && await materializer?.currentRevision({ abortSignal: options?.abortSignal }) !== revision.revision) throw workspaceConflict(`[vitehub] Workspace revision changed while this Session materialized: ${revision.revision}.`);
764
+ const snapshot = captureSnapshot ? options?.writeBack === false ? await createSnapshotFromEntries(entries, "host-open") : await snapshotHost(host, root, "host-open", abortSignal) : void 0;
765
+ return {
766
+ revision: revision?.revision,
767
+ snapshot
768
+ };
769
+ }
770
+ async function commitHostChanges(workspace, diff, contents, mediaTypes, message) {
771
+ for (const entry of diff.entries) {
772
+ if (entry.after?.type === "directory") {
773
+ if (entry.before?.type === "file") await workspace.rm(entry.path, { force: true });
774
+ await workspace.mkdir(entry.path, { recursive: true });
775
+ continue;
776
+ }
777
+ if (entry.type === "removed") {
778
+ await workspace.rm(entry.path, {
779
+ force: true,
780
+ recursive: true
781
+ });
782
+ continue;
783
+ }
784
+ if (entry.after?.type !== "file") continue;
785
+ if (entry.before?.type === "directory") await workspace.rm(entry.path, {
786
+ force: true,
787
+ recursive: true
788
+ });
789
+ const before = entry.before?.type === "file" ? await workspace.stat(entry.path).catch(() => void 0) : void 0;
790
+ const content = contents.get(entry.path);
791
+ if (content !== void 0) await workspace.writeFile(entry.path, content, {
792
+ mediaType: mediaTypes.get(entry.path) || before?.mediaType,
793
+ metadata: entry.after.metadata
794
+ });
795
+ }
796
+ return await workspace.snapshot({ name: message || "host-commit" });
797
+ }
798
+ async function createHostedWorkspaceSession(workspace, options) {
799
+ const host = options.host;
800
+ let executionAuthority;
801
+ try {
802
+ executionAuthority = normalizeExecutionAuthority(host.executionAuthority);
803
+ } catch {
804
+ throw workspaceErrorDiagnostics.WORKSPACE_R0045({ message: "[vitehub] Workspace session host must declare executionAuthority." });
805
+ }
806
+ resolveHostInspectionConcurrency(host);
807
+ resolveHostMaterializationConcurrency(host);
808
+ if (options.attach && options.disposableTarget) throw workspaceError("[vitehub] Workspace Session attach and disposableTarget cannot be combined.");
809
+ const root = normalizeTarget(options.target);
810
+ const sessionPaths = normalizeSessionPaths(options);
811
+ const excludedWriteBackPaths = [...defaultExcludedSessionPaths, ...(options.writeBack && options.writeBack.exclude || []).map((path) => normalizeSafeWorkspacePath(path, { allowReserved: true }))];
812
+ let closed = false;
813
+ const existingExcludedState = await captureExcludedHostState(host, root, excludedWriteBackPaths, options.abortSignal);
814
+ let attachedState = options.attach ? await captureHostState(host, root, "host-attach", options.abortSignal) : void 0;
815
+ let materialization;
816
+ let materializedExcludedState;
817
+ let setupMutatedHost = false;
818
+ try {
819
+ materialization = attachedState ? { snapshot: attachedState.snapshot } : await materializeWorkspace(workspace, host, root, options, true, () => {
820
+ setupMutatedHost = true;
821
+ });
822
+ if (!attachedState) materializedExcludedState = await captureExcludedHostState(host, root, excludedWriteBackPaths, options.abortSignal);
823
+ } catch (error) {
824
+ if (attachedState || !setupMutatedHost || options.disposableTarget) throw error;
825
+ try {
826
+ host.detachAbortSignal?.();
827
+ await materializeWorkspace(workspace, host, root, {
828
+ ...options,
829
+ abortSignal: void 0,
830
+ onProgress: void 0
831
+ }, false, void 0, false);
832
+ await restoreExcludedHostState(host, root, excludedWriteBackPaths, existingExcludedState);
833
+ } catch (restoreError) {
834
+ throw new AggregateError([error, restoreError], "[vitehub] Workspace Session setup and excluded-state restoration failed.");
835
+ }
836
+ throw error;
837
+ }
838
+ let baseline = materialization.snapshot;
839
+ let baseRevision = materialization.revision;
840
+ const excludedState = attachedState ? existingExcludedState : mergeExcludedHostState(existingExcludedState, materializedExcludedState, excludedWriteBackPaths);
841
+ const mediaTypes = /* @__PURE__ */ new Map();
842
+ function assertOpen() {
843
+ if (closed) throw workspaceError("[vitehub] Workspace host session is already closed.");
844
+ }
845
+ async function currentDiff(abortSignal) {
846
+ assertOpen();
847
+ return filterWriteBackDiff(diffSnapshots(baseline, await snapshotHost(host, root, "host-diff", abortSignal)), excludedWriteBackPaths);
848
+ }
849
+ return {
850
+ executionAuthority,
851
+ async readFile(path, readOptions) {
852
+ assertOpen();
853
+ const target = toHostPath(root, assertPathInSessionScope(normalizeReadableSessionPath(path), sessionPaths, { masked: true }));
854
+ const file = await readHostFile(host, root, target);
855
+ if (!file) throw workspaceError(`[vitehub] Workspace file does not exist: ${path}.`);
856
+ return decodeFile(file.content, readOptions);
857
+ },
858
+ async writeFile(path, content, writeOptions) {
859
+ assertOpen();
860
+ const target = toHostPath(root, assertPathInSessionScope(normalizeSafeWorkspacePath(path), sessionPaths));
861
+ await assertNoHostSymlinkParent(host, root, target);
862
+ await ensureHostParent(host, target);
863
+ await removeHostPath(host, root, target, true);
864
+ const symlinkTarget = writeOptions?.metadata?.gitMode === "120000" ? new TextDecoder().decode(contentToBytes(content)) : void 0;
865
+ if (symlinkTarget !== void 0 && isSafeHostSymlink(root, fromHostPath(root, target), symlinkTarget)) await writeHostSymlink(host, root, target, symlinkTarget);
866
+ else {
867
+ await host.files.write(target, contentToBytes(content));
868
+ const workspacePath = fromHostPath(root, target);
869
+ if (writeOptions?.metadata?.gitMode === "100755" || baseline.entries[workspacePath]?.metadata?.gitMode === "100755") await makeHostFileExecutable(host, root, target);
870
+ }
871
+ const workspacePath = fromHostPath(root, target);
872
+ if (writeOptions?.mediaType) mediaTypes.set(workspacePath, writeOptions.mediaType);
873
+ else mediaTypes.delete(workspacePath);
874
+ },
875
+ async mkdir(path, mkdirOptions = {}) {
876
+ assertOpen();
877
+ const target = assertPathInSessionScope(normalizeSafeWorkspacePath(path, { allowEmpty: true }), sessionPaths, { mkdir: true });
878
+ const hostTarget = toHostPath(root, target);
879
+ await assertNoHostSymlinkParent(host, root, hostTarget);
880
+ await host.files.mkdir(hostTarget, { recursive: mkdirOptions.recursive });
881
+ },
882
+ async rm(path, rmOptions) {
883
+ assertOpen();
884
+ const workspacePath = assertPathInSessionScope(normalizeSafeWorkspacePath(path), sessionPaths);
885
+ const target = toHostPath(root, workspacePath);
886
+ await assertNoHostSymlinkParent(host, root, target);
887
+ await removeHostPath(host, root, target, Boolean(rmOptions?.recursive));
888
+ mediaTypes.delete(normalizeWorkspacePath(workspacePath));
889
+ },
890
+ async list(path = "", listOptions = {}) {
891
+ assertOpen();
892
+ return filterSessionEntries(await listHostEntries(host, root, path, listOptions.recursive, void 0, false, listOptions.exclude), sessionPaths);
893
+ },
894
+ async glob(pattern, globOptions) {
895
+ assertOpen();
896
+ const patterns = Array.isArray(pattern) ? pattern : [pattern];
897
+ const cwd = normalizeSearchRoot(globOptions?.cwd || "");
898
+ const { matchesAny } = await import("./path-CNAwN7pw.js").then((n) => n.u);
899
+ return filterSessionEntries(await listHostEntries(host, root, "", true), sessionPaths).filter((entry) => {
900
+ if (entry.type !== "file") return false;
901
+ if (!cwd) return patterns.some((item) => matchesAny(entry.path, item));
902
+ if (!entry.path.startsWith(`${cwd}/`)) return false;
903
+ const relative = entry.path.slice(cwd.length + 1);
904
+ return patterns.some((item) => matchesAny(relative, item));
905
+ });
906
+ },
907
+ async search(query) {
908
+ assertOpen();
909
+ const { searchText } = await import("./search-CrTmXj5h.js").then((n) => n.n);
910
+ const scoped = scopedSearchQuery(query, sessionPaths, normalizeSearchRoot);
911
+ if (!scoped) return [];
912
+ const scopedSearchRoots = [...new Set((scoped.paths?.length ? scoped.paths : [scoped.cwd || ""]).map(normalizeSearchRoot))].filter(Boolean);
913
+ const limit = scoped.limit ?? 100;
914
+ const hits = [];
915
+ for (const entry of filterSessionEntries(await listHostEntries(host, root, "", true), sessionPaths).filter((item) => item.type === "file")) {
916
+ if (scopedSearchRoots.length && !scopedSearchRoots.some((path) => entry.path === path || entry.path.startsWith(`${path}/`))) continue;
917
+ const content = await inspectHost(host, async () => await host.files.read(toHostPath(root, entry.path)));
918
+ if (content === null) continue;
919
+ const text = new TextDecoder().decode(content);
920
+ hits.push(...searchText(entry.path, text, {
921
+ ...scoped,
922
+ limit: limit - hits.length
923
+ }));
924
+ if (hits.length >= limit) break;
925
+ }
926
+ return hits;
927
+ },
928
+ async diff(diffOptions) {
929
+ if (options.writeBack === false) throw workspaceError("[vitehub] Workspace Session diff is unavailable when writeBack is false.");
930
+ return filterSessionDiff(await currentDiff(diffOptions?.abortSignal), sessionPaths);
931
+ },
932
+ async commit(commitOptions) {
933
+ assertOpen();
934
+ if (options.writeBack === false) throw workspaceError("[vitehub] Workspace Session commit is unavailable when writeBack is false.");
935
+ const abortSignal = commitOptions?.abortSignal ?? options.abortSignal;
936
+ abortSignal?.throwIfAborted();
937
+ const capturedState = await captureHostState(host, root, commitOptions?.message || "host-commit", abortSignal);
938
+ const diff = filterWriteBackDiff(diffSnapshots(baseline, capturedState.snapshot), excludedWriteBackPaths);
939
+ if (!diff.entries.length) return;
940
+ assertDiffInsideSessionPaths(diff, sessionPaths);
941
+ const publicationDiff = {
942
+ ...diff,
943
+ entries: diff.entries.map((entry) => {
944
+ const content = capturedState.contents.get(entry.path);
945
+ if (entry.after?.metadata?.gitMode !== "120000" || content === void 0 || isSafeHostSymlink(root, entry.path, String(content))) return entry;
946
+ return {
947
+ ...entry,
948
+ after: {
949
+ ...entry.after,
950
+ metadata: void 0
951
+ }
952
+ };
953
+ })
954
+ };
955
+ const sanitizedPaths = publicationDiff.entries.filter((entry, index) => entry.after?.metadata?.gitMode !== diff.entries[index]?.after?.metadata?.gitMode);
956
+ const sanitizedPathNames = new Set(sanitizedPaths.map((entry) => entry.path));
957
+ const sanitizedCapturedSnapshot = sanitizedPaths.length ? await createSnapshotFromEntries(Object.entries(capturedState.snapshot.entries).map(([path, entry]) => ({
958
+ path,
959
+ ...entry,
960
+ ...sanitizedPathNames.has(path) ? { metadata: void 0 } : {}
961
+ })), commitOptions?.message || "host-commit") : capturedState.snapshot;
962
+ const revisionMaterializer = resolveWorkspaceRevisionMaterializer(workspace);
963
+ await withWorkspacePublication(revisionMaterializer || workspace, abortSignal, async () => {
964
+ abortSignal?.throwIfAborted();
965
+ if (baseRevision && await revisionMaterializer?.currentRevision({ abortSignal }) !== baseRevision) throw workspaceConflict(`[vitehub] Workspace revision changed after this Session materialized: ${baseRevision}.`);
966
+ const nextAttachedState = options.attach ? {
967
+ ...capturedState,
968
+ snapshot: sanitizedCapturedSnapshot
969
+ } : void 0;
970
+ const nextBaseline = nextAttachedState?.snapshot || await createSnapshotFromEntries(Object.entries(baseline.entries).filter(([path]) => !publicationDiff.entries.some((entry) => entry.path === path && !entry.after)).map(([path, entry]) => {
971
+ return {
972
+ path,
973
+ ...publicationDiff.entries.find((item) => item.path === path)?.after || entry
974
+ };
975
+ }).concat(publicationDiff.entries.filter((entry) => entry.after && !baseline.entries[entry.path]).map((entry) => ({
976
+ path: entry.path,
977
+ ...entry.after
978
+ }))), commitOptions?.message || "host-commit");
979
+ for (const entry of sanitizedPaths) {
980
+ abortSignal?.throwIfAborted();
981
+ const content = capturedState.contents.get(entry.path);
982
+ if (content === void 0) continue;
983
+ const target = toHostPath(root, entry.path);
984
+ await removeHostPath(host, root, target, false);
985
+ await host.files.write(target, contentToBytes(content));
986
+ }
987
+ try {
988
+ await commitHostChanges(workspace, publicationDiff, capturedState.contents, mediaTypes, commitOptions?.message);
989
+ } catch (error) {
990
+ if (baseRevision) try {
991
+ await workspace.rebase({ takeRemote: diff.entries.map((entry) => entry.path) });
992
+ } catch (rollbackError) {
993
+ throw new AggregateError([error, rollbackError], "[vitehub] Workspace publication and rollback failed.");
994
+ }
995
+ throw error;
996
+ }
997
+ if (baseRevision) baseRevision = await revisionMaterializer.currentRevision({ refresh: false });
998
+ if (nextAttachedState) attachedState = nextAttachedState;
999
+ baseline = nextBaseline;
1000
+ });
1001
+ },
1002
+ async exec(command, args = [], execOptions = {}) {
1003
+ assertOpen();
1004
+ const result = await host.exec(command, args, {
1005
+ cwd: toHostCwd(root, execOptions.cwd),
1006
+ env: execOptions.env,
1007
+ signal: execOptions.abortSignal,
1008
+ timeout: execOptions.timeout
1009
+ });
1010
+ return {
1011
+ args,
1012
+ command,
1013
+ exitCode: result.code,
1014
+ stderr: result.stderr,
1015
+ stdout: result.stdout
1016
+ };
1017
+ },
1018
+ async close(closeOptions) {
1019
+ if (closed) return;
1020
+ const abortSignal = closeOptions?.abortSignal;
1021
+ abortSignal?.throwIfAborted();
1022
+ host.detachAbortSignal?.();
1023
+ if (options.disposableTarget) {
1024
+ closed = true;
1025
+ return;
1026
+ }
1027
+ await ensureHostWorkspaceRoot(host, root, abortSignal);
1028
+ if (options.writeBack === false && !options.attach) {
1029
+ await materializeWorkspace(workspace, host, root, {
1030
+ ...options,
1031
+ abortSignal,
1032
+ onProgress: void 0
1033
+ }, true, void 0, false);
1034
+ await restoreExcludedHostState(host, root, excludedWriteBackPaths, excludedState, abortSignal);
1035
+ closed = true;
1036
+ return;
1037
+ }
1038
+ let diff;
1039
+ let restoreError;
1040
+ let revisionChanged = false;
1041
+ if (options.attach && attachedState) {
1042
+ const attachedDiff = filterSessionDiff(diffSnapshots(baseline, await snapshotHost(host, root, "host-close", abortSignal)), sessionPaths);
1043
+ let attachedRestoreError;
1044
+ try {
1045
+ await restoreAttachedHost(host, root, attachedDiff, attachedState, abortSignal);
1046
+ } catch (error) {
1047
+ attachedRestoreError = error;
1048
+ }
1049
+ try {
1050
+ await restoreExcludedHostState(host, root, excludedWriteBackPaths, excludedState, abortSignal);
1051
+ } catch (excludedError) {
1052
+ if (attachedRestoreError) throw new AggregateError([attachedRestoreError, excludedError], "[vitehub] Attached Workspace Session restoration and excluded-state restoration failed.");
1053
+ throw excludedError;
1054
+ }
1055
+ if (attachedRestoreError) throw attachedRestoreError;
1056
+ } else try {
1057
+ diff = await currentDiff(abortSignal);
1058
+ const revisionMaterializer = resolveWorkspaceRevisionMaterializer(workspace);
1059
+ revisionChanged = Boolean(baseRevision && await revisionMaterializer?.currentRevision({ abortSignal }) !== baseRevision);
1060
+ } catch (error) {
1061
+ restoreError = error;
1062
+ }
1063
+ abortSignal?.throwIfAborted();
1064
+ try {
1065
+ if (!restoreError && (diff?.entries.length || revisionChanged)) await materializeWorkspace(workspace, host, root, {
1066
+ ...options,
1067
+ abortSignal,
1068
+ onProgress: void 0
1069
+ }, true, void 0, false);
1070
+ } catch (error) {
1071
+ restoreError = error;
1072
+ }
1073
+ abortSignal?.throwIfAborted();
1074
+ try {
1075
+ if (!options.attach) await restoreExcludedHostState(host, root, excludedWriteBackPaths, excludedState, abortSignal);
1076
+ } catch (excludedError) {
1077
+ if (restoreError) throw new AggregateError([restoreError, excludedError], "[vitehub] Workspace Session restoration and excluded-state restoration failed.");
1078
+ throw excludedError;
1079
+ }
1080
+ if (restoreError) throw restoreError;
1081
+ closed = true;
1082
+ }
1083
+ };
1084
+ }
1085
+ //#endregion
1086
+ export { host_exports as n, withWorkspaceProgress as r, createHostedWorkspaceSession as t };