@vite-hub/workspace 0.0.1 → 0.0.2

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 (94) hide show
  1. package/README.md +190 -17
  2. package/dist/{ai-Bk3LLnit.js → ai-Cztw4eLk.js} +149 -29
  3. package/dist/ai-hFdsvDHC.d.ts +162 -0
  4. package/dist/ai.d.ts +2 -85
  5. package/dist/ai.js +1 -1
  6. package/dist/artifacts-store-BAV9jZpd.js +555 -0
  7. package/dist/asset-registry-CaG9b7tf.js +19 -0
  8. package/dist/cli.d.ts +31 -0
  9. package/dist/cli.js +303 -0
  10. package/dist/cloudflare-env-CKxUs2fa.js +20 -0
  11. package/dist/cloudflare.d.ts +16 -0
  12. package/dist/cloudflare.js +3 -0
  13. package/dist/collections/client.d.ts +39 -0
  14. package/dist/collections/client.js +137 -0
  15. package/dist/collections.d.ts +59 -0
  16. package/dist/collections.js +159 -0
  17. package/dist/config--r5unwPc.js +7811 -0
  18. package/dist/config-Ca5DM8fF.d.ts +28 -0
  19. package/dist/config-DCQ6y30R.js +30 -0
  20. package/dist/file-B2q9NE18.js +24 -0
  21. package/dist/{files-DbsIjBya.js → files-xy0le-_U.js} +6 -5
  22. package/dist/github-lIO6-2sH.js +194 -0
  23. package/dist/glob-DeH0dzZX.js +23 -0
  24. package/dist/host-I-_vDs05.js +370 -0
  25. package/dist/hosted-vercel-blob.d.ts +15 -0
  26. package/dist/hosted-vercel-blob.js +26 -0
  27. package/dist/hosted.d.ts +18 -0
  28. package/dist/hosted.js +30 -0
  29. package/dist/index.d.ts +137 -102
  30. package/dist/index.js +479 -594
  31. package/dist/lifecycle-Lhk3dAMt.js +176 -0
  32. package/dist/loader.d.ts +1 -1
  33. package/dist/loader.js +1 -1
  34. package/dist/nitro.d.ts +2 -31
  35. package/dist/nitro.js +2 -2
  36. package/dist/nuxt.d.ts +26 -0
  37. package/dist/nuxt.js +36 -0
  38. package/dist/path-CNI6wKIU.js +115 -0
  39. package/dist/{provider-BZuKAV4e.js → provider-CeQciesl.js} +142 -37
  40. package/dist/providers/cloudflare/artifacts-store.d.ts +1 -1
  41. package/dist/providers/cloudflare/artifacts-store.js +1 -383
  42. package/dist/providers/github/store.d.ts +6 -0
  43. package/dist/providers/github/store.js +362 -0
  44. package/dist/providers/vercel/blob-store.d.ts +1 -1
  45. package/dist/providers/vercel/blob-store.js +77 -18
  46. package/dist/publish.d.ts +3 -2
  47. package/dist/publish.js +48 -142
  48. package/dist/registry-C7DMdBXN.js +74 -0
  49. package/dist/{registry-D4Qzq26I.d.ts → registry-CoC9JxVt.d.ts} +3 -2
  50. package/dist/request-execution-C8qRcReq.js +80 -0
  51. package/dist/runtime/assets.d.ts +2 -1
  52. package/dist/runtime/assets.js +5 -5
  53. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  54. package/dist/runtime/empty-registry.d.ts +1 -1
  55. package/dist/runtime/state.d.ts +4 -21
  56. package/dist/runtime/state.js +7 -4
  57. package/dist/runtime/workspace.d.ts +2 -0
  58. package/dist/runtime/workspace.js +2 -0
  59. package/dist/runtime.d.ts +38 -0
  60. package/dist/runtime.js +643 -0
  61. package/dist/{search-DtaEyjpO.js → search-C4REyHj9.js} +2 -2
  62. package/dist/server.d.ts +65 -0
  63. package/dist/server.js +355 -0
  64. package/dist/shared-BRycRSbo.js +255 -0
  65. package/dist/source-metadata.d.ts +2 -0
  66. package/dist/source-metadata.js +2 -0
  67. package/dist/state-DSAHEsq6.d.ts +25 -0
  68. package/dist/sync-DO42ypji.js +269 -0
  69. package/dist/target-D4Bqb1eH.js +11 -0
  70. package/dist/test.d.ts +1 -1
  71. package/dist/test.js +1 -1
  72. package/dist/types-DHkae7Cb.d.ts +628 -0
  73. package/dist/use-D16tf8Ph.d.ts +86 -0
  74. package/dist/use-d_PlAdOu.js +353 -0
  75. package/dist/{utils-BtAm_K5P.js → utils-BPdaCyI6.js} +7 -3
  76. package/dist/vite-NWC9mFjI.js +1882 -0
  77. package/dist/vite.d.ts +33 -5
  78. package/dist/vite.js +2 -131
  79. package/dist/workspace-f2DBLmPZ.d.ts +6 -0
  80. package/dist/workspace-n4wBmdaM.js +1476 -0
  81. package/package.json +158 -62
  82. package/dist/asset-registry-CMuQbyvl.js +0 -14
  83. package/dist/cloudflare-env-DL94Uvpz.js +0 -12
  84. package/dist/config-CvS-7sre.js +0 -49
  85. package/dist/errors-BUL8SoFS.js +0 -21
  86. package/dist/lifecycle-uD82JeGh.js +0 -92
  87. package/dist/module-8LZUMEXC.js +0 -922
  88. package/dist/path-BVv9OXhg.js +0 -63
  89. package/dist/registry-Cnr0NoKv.js +0 -932
  90. package/dist/runtime/nitro-plugin.d.ts +0 -6
  91. package/dist/runtime/nitro-plugin.js +0 -14
  92. package/dist/sandbox-DtGXCWRq.js +0 -198
  93. package/dist/types-CwNcWTdt.d.ts +0 -378
  94. /package/dist/{chunk-DrSxFLj_.js → chunk-8H4AJuhK.js} +0 -0
package/dist/index.js CHANGED
@@ -1,656 +1,541 @@
1
- import { t as __exportAll } from "./chunk-DrSxFLj_.js";
2
- import { n as WorkspaceNotFoundError } from "./errors-BUL8SoFS.js";
3
- import { n as appendWorkspaceFile, r as copyWorkspacePath, t as createWorkspaceTools } from "./ai-Bk3LLnit.js";
4
- import { a as normalizeSafeWorkspacePattern, i as normalizeSafeWorkspacePath } from "./path-BVv9OXhg.js";
5
- import { n as markLiveWorkspaceSource } from "./config-CvS-7sre.js";
6
- import { t as getActiveCloudflareBinding } from "./cloudflare-env-DL94Uvpz.js";
7
- import { a as resolveWorkspaceAutoCommit, r as useRegisteredWorkspace } from "./registry-Cnr0NoKv.js";
8
- import { n as useWorkspaceAssets } from "./asset-registry-CMuQbyvl.js";
1
+ import { t as __exportAll } from "./chunk-8H4AJuhK.js";
2
+ import { o as normalizeSafeWorkspacePath, p as workspaceError, r as contentToBytes } from "./path-CNI6wKIU.js";
3
+ import { t as createWorkspaceTools } from "./ai-Cztw4eLk.js";
4
+ import { d as fetch, g as markLiveWorkspaceSource, u as registerMcpResourcesSourceLoader } from "./config--r5unwPc.js";
5
+ import { g as isMissingWorkspacePathError, t as createWorkspace, u as resolveWorkspaceAutoCommit } from "./workspace-n4wBmdaM.js";
6
+ import { r as resolveRegisteredWorkspaceDefinition } from "./registry-C7DMdBXN.js";
7
+ import { t as useWorkspace } from "./use-d_PlAdOu.js";
8
+ import { t as file } from "./file-B2q9NE18.js";
9
+ import { t as github } from "./github-lIO6-2sH.js";
10
+ import { t as glob } from "./glob-DeH0dzZX.js";
9
11
  import { posix } from "node:path";
10
- import { file, github, glob, markdown } from "@vite-hub/source";
12
+ import { lookup } from "mrmime";
13
+ import { markdown as markdown$1 } from "@vite-hub/source/sources/markdown";
14
+ import { mcpResources as mcpResources$1 } from "@vite-hub/source/sources/mcp-resources";
15
+ import { gzipSync } from "node:zlib";
11
16
  //#region src/core/define.ts
17
+ const workspaceDefinitionKeys = new Set([
18
+ "bindings",
19
+ "commit",
20
+ "hooks",
21
+ "loaders",
22
+ "plugins",
23
+ "publish",
24
+ "rootDir",
25
+ "rules",
26
+ "sourceRootDir",
27
+ "sources",
28
+ "store"
29
+ ]);
30
+ function assertWorkspaceDefinitionKeys(definition) {
31
+ const unsupported = Object.keys(definition).filter((key) => !workspaceDefinitionKeys.has(key));
32
+ if (!unsupported.length) return;
33
+ throw new TypeError(`[vitehub] defineWorkspace does not support option${unsupported.length === 1 ? "" : "s"}: ${unsupported.join(", ")}.`);
34
+ }
12
35
  function defineWorkspace(definition) {
13
36
  if (!definition || typeof definition !== "object") throw new TypeError("[vitehub] defineWorkspace requires a workspace definition.");
14
37
  if ("name" in definition) throw new TypeError("[vitehub] Workspace names are inferred from definition filenames.");
38
+ assertWorkspaceDefinitionKeys(definition);
15
39
  return definition;
16
40
  }
17
41
  //#endregion
18
42
  //#region src/sources/custom.ts
19
43
  function custom(source) {
20
- return source;
21
- }
22
- //#endregion
23
- //#region src/sources/file.ts
24
- function file$1(input) {
25
- const options = typeof input === "string" ? { path: input } : input;
26
- const mount = typeof options.mount === "object" && options.mount && !("path" in options.mount) ? {
27
- ...options.mount,
28
- path: ""
29
- } : options.mount ?? "";
30
- return {
31
- ...file(options),
32
- cache: options.cache,
33
- materialize: options.materialize,
34
- mount,
35
- validate: options.validate
36
- };
37
- }
38
- //#endregion
39
- //#region ../internal/src/http-request.ts
40
- async function executeHttpRequest(definition, options = {}) {
41
- const normalized = normalizeHttpRequest(definition);
42
- const responseType = options.responseType || "json";
43
- const response = await fetchWithRetry(normalized);
44
- const decoded = await decodeResponse(response, responseType);
45
- return {
46
- data: options.schema ? await parseStandardSchema(options.schema, decoded, "HTTP response") : decoded,
47
- mediaType: response.headers.get("content-type") || void 0,
48
- status: response.status,
49
- summary: redactedHttpRequestSummary(normalized, responseType)
50
- };
51
- }
52
- async function fetchWithRetry(definition) {
53
- const attempts = definition.method === "GET" || definition.method === "HEAD" ? 2 : 1;
54
- let lastError;
55
- for (let attempt = 1; attempt <= attempts; attempt += 1) try {
56
- return await fetchOnce(definition);
57
- } catch (error) {
58
- lastError = error;
59
- if (attempt === attempts) break;
60
- }
61
- throw lastError;
62
- }
63
- async function fetchOnce(definition) {
64
- const headers = new Headers(definition.headers);
65
- const body = serializeRequestBody(definition.body, headers);
66
- const controller = definition.timeout ? new AbortController() : void 0;
67
- const timeout = controller ? setTimeout(() => controller.abort(), definition.timeout) : void 0;
68
- try {
69
- const response = await fetch(urlWithQuery(definition).toString(), {
70
- body,
71
- headers,
72
- method: definition.method,
73
- signal: controller?.signal
74
- });
75
- if (!response.ok) throw new Error(`[vitehub] HTTP request failed with status ${response.status}.`);
76
- return response;
77
- } finally {
78
- if (timeout) clearTimeout(timeout);
79
- }
80
- }
81
- function serializeRequestBody(body, headers) {
82
- if (typeof body === "undefined") return void 0;
83
- if (typeof body === "string" || body instanceof Uint8Array || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || typeof Blob !== "undefined" && body instanceof Blob || typeof FormData !== "undefined" && body instanceof FormData || typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams || typeof ReadableStream !== "undefined" && body instanceof ReadableStream) return body;
84
- if (!headers.has("content-type")) headers.set("content-type", "application/json");
85
- return JSON.stringify(body);
86
- }
87
- function urlWithQuery(definition) {
88
- const url = new URL(definition.url);
89
- if (!definition.query) return url;
90
- for (const [key, value] of Object.entries(definition.query)) {
91
- if (typeof value === "undefined") continue;
92
- if (Array.isArray(value)) {
93
- for (const item of value) if (typeof item !== "undefined") url.searchParams.append(key, queryValue(item));
94
- continue;
95
- }
96
- url.searchParams.set(key, queryValue(value));
97
- }
98
- return url;
99
- }
100
- function queryValue(value) {
101
- if (value === null) return "";
102
- if (typeof value === "string") return value;
103
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
104
- return JSON.stringify(value);
105
- }
106
- async function decodeResponse(response, responseType) {
107
- if (responseType === "text") return await response.text();
108
- if (responseType === "arrayBuffer") return await response.arrayBuffer();
109
- if (responseType === "blob") return await response.blob();
110
- const text = await response.text();
111
- return text ? JSON.parse(text) : void 0;
112
- }
113
- function normalizeHttpRequest(definition) {
114
- const method = (definition.method || "GET").toUpperCase();
115
- if (method !== "GET" && method !== "HEAD" && method !== "POST") throw new TypeError(`[vitehub] HTTP request method "${method}" is not supported. Use GET, HEAD, or POST.`);
44
+ if (!("files" in source) || !Array.isArray(source.files)) return source;
45
+ const { files: inputFiles, ...options } = source;
46
+ const files = inputFiles.map((file) => ({
47
+ ...file,
48
+ path: normalizeSafeWorkspacePath(file.path)
49
+ }));
116
50
  return {
117
- ...definition,
118
- method,
119
- url: definition.url instanceof URL ? definition.url : new URL(definition.url)
120
- };
121
- }
122
- async function parseStandardSchema(schema, value, label) {
123
- const result = await schema["~standard"].validate(value);
124
- if ("issues" in result && result.issues && result.issues.length > 0) throw new Error(`[vitehub] Invalid ${label}: ${formatIssues(result.issues)}`);
125
- if (!("value" in result)) throw new Error(`[vitehub] Invalid ${label}: ${formatIssues(result.issues)}`);
126
- return result.value;
127
- }
128
- function redactedHttpRequestSummary(definition, responseType) {
129
- return {
130
- hasBody: typeof definition.body !== "undefined",
131
- hasQuery: Boolean(definition.query && Object.keys(definition.query).length),
132
- headers: definition.headers && Object.keys(definition.headers).length ? "redacted" : "none",
133
- method: definition.method,
134
- responseType,
135
- url: `${definition.url.origin}${definition.url.pathname}`
136
- };
137
- }
138
- function formatIssues(issues) {
139
- if (Array.isArray(issues)) return issues.map((issue) => typeof issue === "string" ? issue : JSON.stringify(issue)).join("; ");
140
- return typeof issues === "string" ? issues : JSON.stringify(issues);
141
- }
142
- //#endregion
143
- //#region src/sources/fetch.ts
144
- function fetch$1(options) {
145
- const responseType = normalizePublicResponseType(options.responseType || "json");
146
- const workspacePath = normalizeSafeWorkspacePath(options.path || deriveWorkspacePath(options.url, responseType), { allowEmpty: false });
147
- const mountPath = posix.dirname(workspacePath) === "." ? "" : posix.dirname(workspacePath);
148
- const key = mountPath ? workspacePath.slice(mountPath.length + 1) : workspacePath;
149
- return markLiveWorkspaceSource({
150
- cache: options.cache ?? false,
151
- fingerprint: {
152
- method: options.method,
153
- path: workspacePath,
154
- responseType,
155
- url: String(options.url)
156
- },
157
- materialize: "lazy",
158
- mount: mountPath,
51
+ ...options,
159
52
  async getKeys() {
160
- return [key];
53
+ return files.map((file) => file.path);
161
54
  },
162
- async getItem(sourcePath) {
163
- if (sourcePath !== key) throw new Error(`[vitehub] Fetch source item does not exist: ${sourcePath}.`);
164
- const request = typeof options.request === "function" ? await options.request() : options.request;
165
- const result = await executeHttpRequest({
166
- ...request,
167
- method: request?.method ?? options.method,
168
- url: options.url
169
- }, {
170
- responseType,
171
- schema: options.schema
172
- });
55
+ async getItem(key, context) {
56
+ const file = files.find((file) => file.path === key);
57
+ if (!file) throw workspaceError(`[vitehub] Custom Workspace Source file does not exist: ${key}.`);
58
+ const { content, ...item } = file;
173
59
  return {
60
+ ...item,
61
+ content: typeof content === "function" ? await content(context) : content,
174
62
  key,
175
- path: key,
176
- content: serializeFetchSourceContent(options.transform ? await options.transform(result.data) : result.data, responseType),
177
- mediaType: result.mediaType ?? mediaTypeFor(responseType),
178
- metadata: {
179
- request: result.summary,
180
- status: result.status
181
- }
182
- };
183
- },
184
- async getMeta(sourcePath) {
185
- if (sourcePath !== key) return void 0;
186
- return {
187
- mediaType: mediaTypeFor(responseType),
188
- request: {
189
- method: options.method || "GET",
190
- responseType,
191
- url: redactedUrl(options.url)
192
- }
63
+ mediaType: item.mediaType || lookup(key) || void 0
193
64
  };
194
65
  }
195
- }, { [workspacePath]: key });
196
- }
197
- function normalizePublicResponseType(responseType) {
198
- if (responseType !== "json" && responseType !== "text") throw new TypeError(`[vitehub] source.fetch() responseType "${responseType}" is not supported in v1. Use json or text.`);
199
- return responseType;
200
- }
201
- function deriveWorkspacePath(url, responseType) {
202
- const parsed = url instanceof URL ? url : new URL(url);
203
- if (parsed.search) throw new Error("[vitehub] source.fetch() requires an explicit path when the URL includes query parameters.");
204
- let path = normalizeSafeWorkspacePath(decodeURI(parsed.pathname).replace(/^\/+/, ""), { allowEmpty: false });
205
- if (!posix.extname(path)) path = `${path}.${responseType === "json" ? "json" : "txt"}`;
206
- return path;
207
- }
208
- function serializeFetchSourceContent(value, responseType) {
209
- if (value instanceof Uint8Array) return value;
210
- if (responseType === "json") return JSON.stringify(value, null, 2) ?? "null";
211
- if (typeof value === "string") return value;
212
- return typeof value === "undefined" ? "" : String(value);
213
- }
214
- function mediaTypeFor(responseType) {
215
- return responseType === "json" ? "application/json" : "text/plain";
216
- }
217
- function redactedUrl(url) {
218
- const parsed = url instanceof URL ? url : new URL(url);
219
- return `${parsed.origin}${parsed.pathname}`;
220
- }
221
- //#endregion
222
- //#region src/env.ts
223
- let viteLoadEnv;
224
- async function resolveWorkspaceEnv(rootDir, name) {
225
- return (await loadWorkspaceEnv(rootDir))?.[name];
226
- }
227
- async function loadWorkspaceEnv(rootDir) {
228
- return await loadViteEnv(rootDir);
229
- }
230
- async function loadViteEnv(rootDir) {
231
- if (viteLoadEnv === null) return;
232
- if (!viteLoadEnv) try {
233
- viteLoadEnv = (await import(
234
- /* @vite-ignore */
235
- "vite"
236
- )).loadEnv;
237
- } catch {
238
- viteLoadEnv = null;
239
- return;
240
- }
241
- return viteLoadEnv("", rootDir, "");
242
- }
243
- //#endregion
244
- //#region src/sources/github.ts
245
- function github$1(options) {
246
- const resolvedOptions = {
247
- ...options,
248
- mount: options.mount ?? inferRepositoryMount(options.repo)
249
- };
250
- const baseSource = github({
251
- ...resolvedOptions,
252
- auth: createGitHubAuthResolver(resolvedOptions.auth)
253
- });
254
- const sourceByRootAndToken = /* @__PURE__ */ new Map();
255
- async function getSourceForRoot(rootDir) {
256
- const envFileToken = await resolveWorkspaceEnv(rootDir, "GITHUB_TOKEN");
257
- const cacheKey = `${rootDir}\0${envFileToken ?? ""}`;
258
- const cachedSource = sourceByRootAndToken.get(cacheKey);
259
- if (cachedSource) return cachedSource;
260
- const source = github({
261
- ...resolvedOptions,
262
- auth: createGitHubAuthResolver(resolvedOptions.auth, envFileToken)
263
- });
264
- sourceByRootAndToken.set(cacheKey, source);
265
- return source;
266
- }
267
- return {
268
- ...baseSource,
269
- cache: resolvedOptions.cache,
270
- fingerprint: {
271
- exclude: resolvedOptions.exclude,
272
- include: resolvedOptions.include,
273
- ref: resolvedOptions.ref,
274
- repo: resolvedOptions.repo,
275
- root: resolvedOptions.root
276
- },
277
- materialize: resolvedOptions.materialize,
278
- mount: resolvedOptions.mount,
279
- validate: resolvedOptions.validate,
280
- async prepare(ctx) {
281
- await (await getSourceForRoot(ctx.rootDir)).prepare?.(ctx);
282
- },
283
- async getKeys(ctx) {
284
- return await (await getSourceForRoot(ctx.rootDir)).getKeys(ctx);
285
- },
286
- async getItem(key, ctx) {
287
- return await (await getSourceForRoot(ctx.rootDir)).getItem(key, ctx);
288
- },
289
- async getItems(ctx) {
290
- const source = await getSourceForRoot(ctx.rootDir);
291
- return await source.getItems?.(ctx) ?? await Promise.all((await source.getKeys(ctx)).map((key) => source.getItem(key, ctx)));
292
- },
293
- async getMeta(key, ctx) {
294
- return await (await getSourceForRoot(ctx.rootDir)).getMeta?.(key, ctx);
295
- },
296
- async search(query, ctx) {
297
- return await (await getSourceForRoot(ctx.rootDir)).search?.(query, ctx) ?? [];
298
- }
299
66
  };
300
67
  }
301
- function inferRepositoryMount(repo) {
302
- return repo?.split("/").filter(Boolean).at(-1);
303
- }
304
- function createGitHubAuthResolver(auth, envFileToken) {
305
- return () => {
306
- return resolveGitHubAuth(auth) || getActiveCloudflareBinding("GITHUB_TOKEN") || process.env.GITHUB_TOKEN || envFileToken;
307
- };
308
- }
309
- function resolveGitHubAuth(auth) {
310
- return typeof auth === "function" ? auth() : auth;
311
- }
312
68
  //#endregion
313
- //#region src/sources/glob.ts
314
- function glob$1(options) {
69
+ //#region src/sources/markdown.ts
70
+ function markdown(options) {
71
+ const key = normalizeSafeWorkspacePath(options.workspacePath || options.path || "");
315
72
  return {
316
- ...glob({
317
- ...options,
318
- keyCache: options.keyCache ?? !isLazySource(options)
319
- }),
73
+ ...markdown$1(options),
320
74
  cache: options.cache,
321
75
  materialize: options.materialize,
322
76
  mount: options.mount,
77
+ probeKeys: options.probeKeys || [key],
78
+ sync: options.sync,
323
79
  validate: options.validate
324
80
  };
325
81
  }
326
- function isLazySource(options) {
327
- if (options.materialize === "lazy") return true;
328
- return typeof options.mount === "object" && options.mount?.materialize === "lazy";
329
- }
330
82
  //#endregion
331
- //#region src/sources/markdown.ts
332
- function markdown$1(options) {
333
- return {
334
- ...markdown(options),
83
+ //#region src/sources/mcp-resources.ts
84
+ function mcpResources(options) {
85
+ const livePaths = {};
86
+ const baseSource = mcpResources$1({
87
+ ...options,
88
+ cache: options.cache
89
+ });
90
+ return markLiveWorkspaceSource({
91
+ ...baseSource,
335
92
  cache: options.cache,
336
- materialize: options.materialize,
93
+ materialize: options.materialize || (options.sync ? "none" : "lazy"),
337
94
  mount: options.mount,
95
+ async prepare(ctx) {
96
+ await baseSource.prepare?.(ctx);
97
+ resetLivePaths(livePaths, resolveMountPath(options.mount, ctx), await baseSource.getKeys(ctx));
98
+ },
99
+ sync: options.sync,
338
100
  validate: options.validate
339
- };
101
+ }, livePaths);
102
+ }
103
+ registerMcpResourcesSourceLoader((input) => mcpResources(input));
104
+ function resolveMountPath(mount, ctx) {
105
+ return normalizeSafeWorkspacePath((typeof mount === "string" ? mount : mount?.path) ?? ctx.mountPath ?? ctx.source ?? "", { allowEmpty: true });
106
+ }
107
+ function resetLivePaths(paths, mountPath, keys) {
108
+ for (const path of Object.keys(paths)) delete paths[path];
109
+ for (const key of keys) {
110
+ const path = normalizeSafeWorkspacePath(`${mountPath}/${key}`.replace(/\/+/g, "/"), { allowEmpty: false });
111
+ paths[path] = key;
112
+ }
340
113
  }
341
114
  //#endregion
342
115
  //#region src/sources/index.ts
343
116
  var sources_exports = /* @__PURE__ */ __exportAll({
344
117
  custom: () => custom,
345
- fetch: () => fetch$1,
346
- file: () => file$1,
347
- github: () => github$1,
348
- glob: () => glob$1,
349
- markdown: () => markdown$1
118
+ fetch: () => fetch,
119
+ file: () => file,
120
+ github: () => github,
121
+ glob: () => glob,
122
+ markdown: () => markdown,
123
+ mcpResources: () => mcpResources
350
124
  });
351
125
  //#endregion
352
- //#region src/core/use.ts
353
- function normalizePath(path, allowEmpty = false) {
354
- return normalizeSafeWorkspacePath(path, { allowEmpty });
355
- }
356
- function normalizeListPath(path = "") {
357
- return normalizePath(path, true);
358
- }
359
- function normalizePattern(pattern) {
360
- return Array.isArray(pattern) ? pattern.map(normalizeSafeWorkspacePattern) : normalizeSafeWorkspacePattern(pattern);
361
- }
362
- function createLazyWorkspace(name) {
363
- let workspacePromise;
364
- let syncPromise;
365
- async function resolveWorkspace() {
366
- workspacePromise ||= useRegisteredWorkspace(name);
367
- return await workspacePromise;
368
- }
369
- async function resolveSyncedWorkspace() {
370
- const workspace = await resolveWorkspace();
371
- if (!syncPromise) {
372
- const next = workspace.sync();
373
- syncPromise = next;
374
- next.catch(() => {
375
- syncPromise = void 0;
376
- });
377
- }
378
- await syncPromise;
379
- return workspace;
380
- }
381
- const workspace = {
382
- name,
383
- async sync(options) {
384
- const next = (await resolveWorkspace()).sync(options);
385
- syncPromise = next;
386
- next.catch(() => {
387
- syncPromise = void 0;
388
- });
389
- await next;
390
- },
391
- async readFile(path, options) {
392
- return await (await resolveSyncedWorkspace()).readFile(normalizePath(path), options);
393
- },
394
- async writeFile(path, content, options) {
395
- await (await resolveSyncedWorkspace()).writeFile(normalizePath(path), content, options);
396
- },
397
- async list(path, options) {
398
- return await (await resolveSyncedWorkspace()).list(path ? normalizeListPath(path) : "", options);
399
- },
400
- async glob(pattern, options) {
401
- return await (await resolveSyncedWorkspace()).glob(normalizePattern(pattern), options);
402
- },
403
- async search(query) {
404
- return await (await resolveSyncedWorkspace()).search({
405
- ...query,
406
- cwd: query.cwd ? normalizeListPath(query.cwd) : query.cwd,
407
- paths: query.paths?.map((path) => normalizeListPath(path))
408
- });
409
- },
410
- async stat(path) {
411
- return await (await resolveSyncedWorkspace()).stat(normalizePath(path));
412
- },
413
- async exists(path) {
414
- return await (await resolveSyncedWorkspace()).exists(normalizePath(path));
415
- },
416
- async mkdir(path, options) {
417
- await (await resolveSyncedWorkspace()).mkdir(normalizePath(path), options);
418
- },
419
- async rm(path, options) {
420
- await (await resolveSyncedWorkspace()).rm(normalizePath(path), options);
421
- },
422
- async materializeSources(options) {
423
- return await (await resolveSyncedWorkspace()).materializeSources?.(options) ?? {
424
- bytes: 0,
425
- directories: 0,
426
- durationMs: 0,
427
- files: 0,
428
- path: options?.path || "",
429
- sources: []
430
- };
431
- },
432
- async snapshot(options) {
433
- return await (await resolveSyncedWorkspace()).snapshot(options);
434
- },
435
- async diff(options) {
436
- return await (await resolveSyncedWorkspace()).diff(options);
437
- },
438
- async startSession(options) {
439
- return await (await resolveSyncedWorkspace()).startSession(options);
440
- },
441
- mount(options) {
442
- return {
443
- workspace,
444
- mode: options?.mode || "read-only",
445
- target: options?.target || "/workspace",
446
- async diff() {
447
- return await (await resolveSyncedWorkspace()).mount(options).diff();
448
- },
449
- async commit(commitOptions) {
450
- await (await resolveSyncedWorkspace()).mount(options).commit(commitOptions);
451
- },
452
- async export() {
453
- return await (await resolveSyncedWorkspace()).mount(options).export();
454
- }
455
- };
456
- }
457
- };
458
- return workspace;
459
- }
460
- function createWritableFs(workspace) {
461
- return {
462
- readFile: async (path, options) => await workspace.readFile(normalizePath(path), options),
463
- writeFile: async (path, content, options) => await workspace.writeFile(normalizePath(path), content, options),
464
- appendFile: async (path, content) => await appendWorkspaceFile(workspace, normalizePath(path), content),
465
- stat: async (path) => await workspace.stat(normalizePath(path)),
466
- exists: async (path) => await workspace.exists(normalizePath(path)),
467
- list: async (path, options) => await workspace.list(path ? normalizeListPath(path) : "", options),
468
- glob: async (pattern, options) => await workspace.glob(normalizePattern(pattern), options),
469
- search: async (query) => await workspace.search({
470
- ...query,
471
- cwd: query.cwd ? normalizeListPath(query.cwd) : query.cwd,
472
- paths: query.paths?.map((path) => normalizeListPath(path))
473
- }),
474
- mkdir: async (path, options) => await workspace.mkdir(normalizePath(path), options),
475
- rm: async (path, options) => await workspace.rm(normalizePath(path), options),
476
- movePath: async (from, to, options) => {
477
- const source = normalizePath(from);
478
- await copyWorkspacePath(workspace, source, normalizePath(to), options?.overwrite);
479
- await workspace.rm(source, {
480
- recursive: true,
481
- force: true
482
- });
483
- },
484
- copyPath: async (from, to, options) => await copyWorkspacePath(workspace, normalizePath(from), normalizePath(to), options?.overwrite)
485
- };
486
- }
487
- function useOptionalWorkspaceAssets(name) {
126
+ //#region src/session/harness.ts
127
+ const archivePath = ".vitehub-workspace.tar.gz";
128
+ const tarBlockSize = 512;
129
+ const workspaceReadConcurrency = 16;
130
+ function isWritableWorkspaceFacade(workspace) {
131
+ return "startSession" in workspace && typeof workspace.startSession === "function";
132
+ }
133
+ function workspaceSourceMaterializer(workspace) {
134
+ if ("materializeSources" in workspace && typeof workspace.materializeSources === "function") return (options) => workspace.materializeSources(options);
135
+ const materializeSources = workspace.fs.materializeSources;
136
+ if (typeof materializeSources === "function") return (options) => materializeSources(options);
137
+ }
138
+ function sandboxPath(root, path) {
139
+ return posix.join(root, path);
140
+ }
141
+ function shellQuote(value) {
142
+ return `'${value.replace(/'/g, "'\\''")}'`;
143
+ }
144
+ function isGeneratedSourceDescriptorPath(path) {
145
+ return path === ".vitehub" || path === ".vitehub/sources" || /^\.vitehub\/sources\/[^/]+\.json$/.test(path);
146
+ }
147
+ function normalizeHarnessWorkspacePath(path = "") {
148
+ const descriptorPath = normalizeSafeWorkspacePath(path, {
149
+ allowEmpty: true,
150
+ allowReserved: true
151
+ });
152
+ if (isGeneratedSourceDescriptorPath(descriptorPath)) return descriptorPath;
153
+ return normalizeSafeWorkspacePath(path, { allowEmpty: true });
154
+ }
155
+ function normalizeSessionPaths(paths) {
156
+ if (paths === void 0) return void 0;
157
+ const normalized = [...new Set((paths || []).map(normalizeHarnessWorkspacePath))];
158
+ if (normalized.includes("")) return void 0;
159
+ return normalized.sort((left, right) => left.length - right.length || left.localeCompare(right));
160
+ }
161
+ function isIgnoredWriteBackPath(path, ignoreWriteBackPaths) {
162
+ for (const ignoredPath of ignoreWriteBackPaths) if (path === ignoredPath || path.startsWith(`${ignoredPath}/`)) return true;
163
+ return false;
164
+ }
165
+ function isIgnoredWriteBackParent(path, ignoreWriteBackPaths) {
166
+ for (const ignoredPath of ignoreWriteBackPaths) if (ignoredPath.startsWith(`${path}/`)) return true;
167
+ return false;
168
+ }
169
+ async function runSandbox(sandbox, options) {
170
+ const result = await sandbox.run(options);
171
+ if (result.exitCode !== 0) throw new Error(`[vitehub] Failed to prepare Harness Workspace Session: ${result.stderr || "sandbox command failed"}`);
172
+ return result;
173
+ }
174
+ async function withPrepareProgress(onProgress, event, fn) {
175
+ const startedAt = Date.now();
176
+ await onProgress?.({
177
+ data: event.data,
178
+ id: event.id,
179
+ label: event.label,
180
+ status: "started"
181
+ });
488
182
  try {
489
- return useWorkspaceAssets(name);
183
+ const result = await fn();
184
+ await onProgress?.({
185
+ data: event.data,
186
+ durationMs: Date.now() - startedAt,
187
+ id: event.id,
188
+ label: event.label,
189
+ status: "completed"
190
+ });
191
+ return result;
490
192
  } catch (error) {
491
- if (error instanceof WorkspaceNotFoundError) return void 0;
193
+ await onProgress?.({
194
+ data: {
195
+ ...event.data,
196
+ error: error instanceof Error ? error.message : String(error)
197
+ },
198
+ durationMs: Date.now() - startedAt,
199
+ error: error instanceof Error ? error.message : String(error),
200
+ id: event.id,
201
+ label: event.label,
202
+ status: "failed"
203
+ });
492
204
  throw error;
493
205
  }
494
206
  }
495
- async function ignoreMissingWorkspace(operation) {
496
- try {
497
- return await operation();
498
- } catch (error) {
499
- if (isMissingWorkspaceRead(error)) return void 0;
500
- throw error;
207
+ function workspaceFiles(entries) {
208
+ return entries.filter((entry) => entry.type === "file").sort((left, right) => left.path.localeCompare(right.path));
209
+ }
210
+ function workspaceDirectories(entries) {
211
+ return entries.filter((entry) => entry.type === "directory").map((entry) => entry.path).sort((left, right) => left.localeCompare(right));
212
+ }
213
+ function addParentDirectories(directories, path) {
214
+ let directory = posix.dirname(path);
215
+ while (directory && directory !== ".") {
216
+ directories.add(directory);
217
+ directory = posix.dirname(directory);
501
218
  }
502
219
  }
503
- function isMissingWorkspaceRead(error) {
504
- return error instanceof WorkspaceNotFoundError || error instanceof Error && error.message.includes("Workspace file does not exist:") || error instanceof Error && error.message.includes("Workspace path does not exist:");
220
+ async function forEachConcurrent(items, limit, fn) {
221
+ let index = 0;
222
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
223
+ while (index < items.length) {
224
+ const item = items[index++];
225
+ if (item !== void 0) await fn(item);
226
+ }
227
+ }));
505
228
  }
506
- function mergeEntries(primary = [], fallback = []) {
229
+ async function workspaceEntries(workspace, paths) {
230
+ if (paths && !paths.length) return [];
231
+ if (!paths) return await workspace.fs.list("", { recursive: true });
507
232
  const entries = /* @__PURE__ */ new Map();
508
- for (const entry of fallback) entries.set(entry.path, entry);
509
- for (const entry of primary) entries.set(entry.path, entry);
233
+ for (const path of paths) {
234
+ const stat = await workspace.fs.stat(path).catch(() => void 0);
235
+ if (!stat) continue;
236
+ entries.set(stat.path, stat);
237
+ if (stat.type === "directory") for (const entry of await workspace.fs.list(path, { recursive: true })) entries.set(entry.path, entry);
238
+ }
510
239
  return [...entries.values()].sort((left, right) => left.path.localeCompare(right.path));
511
240
  }
512
- function mergeSearchHits(primary = [], fallback = []) {
513
- const seen = /* @__PURE__ */ new Set();
514
- return [...primary, ...fallback].filter((hit) => {
515
- const key = `${hit.path}:${hit.line}:${hit.column}:${hit.text}`;
516
- if (seen.has(key)) return false;
517
- seen.add(key);
518
- return true;
241
+ async function materializeWorkspaceSourcesForSession(workspace, paths, options = {}) {
242
+ const materialize = workspaceSourceMaterializer(workspace);
243
+ if (!materialize) return;
244
+ if (paths && !paths.length) return;
245
+ await Promise.all((paths || [""]).map(async (path) => {
246
+ await materialize({
247
+ ...options,
248
+ path
249
+ }).catch((error) => {
250
+ if (path && isMissingWorkspacePathError(error)) return;
251
+ throw error;
252
+ });
253
+ }));
254
+ }
255
+ function bytesEqual(left, right) {
256
+ if (!left || left.byteLength !== right.byteLength) return false;
257
+ for (let index = 0; index < left.byteLength; index++) if (left[index] !== right[index]) return false;
258
+ return true;
259
+ }
260
+ function pathsFromFindOutput(stdout) {
261
+ return stdout.split("\n").map((path) => path.trim()).filter(Boolean).map((path) => path.replace(/^\.\//, "")).filter((path) => path && path !== ".").sort((left, right) => left.localeCompare(right));
262
+ }
263
+ async function resetSandboxWorkDir(sandbox, sessionWorkDir, abortSignal) {
264
+ const workDir = posix.normalize(sessionWorkDir);
265
+ const parent = posix.dirname(workDir);
266
+ const name = posix.basename(workDir);
267
+ await sandbox.writeBinaryFile({
268
+ abortSignal,
269
+ content: new Uint8Array(),
270
+ path: sandboxPath(parent, ".vitehub-reset")
271
+ });
272
+ await runSandbox(sandbox, {
273
+ abortSignal,
274
+ command: `rm -rf -- ${shellQuote(name)} && mkdir -p -- ${shellQuote(name)} && rm -f -- ${shellQuote(".vitehub-reset")}`,
275
+ workingDirectory: parent
519
276
  });
520
277
  }
521
- function createReadonlyFs(name, workspace) {
522
- const assets = useOptionalWorkspaceAssets(name);
523
- return {
524
- readFile: async (path, options) => {
525
- const normalized = normalizePath(path);
526
- try {
527
- return await workspace.readFile(normalized, options);
528
- } catch (error) {
529
- if (assets && isMissingWorkspaceRead(error)) return await assets.readFile(normalized, options);
530
- throw error;
531
- }
532
- },
533
- stat: async (path) => {
534
- const normalized = normalizePath(path);
535
- try {
536
- return await workspace.stat(normalized);
537
- } catch (error) {
538
- if (assets && isMissingWorkspaceRead(error)) return await assets.stat(normalized);
539
- throw error;
540
- }
541
- },
542
- exists: async (path) => {
543
- const normalized = normalizePath(path);
544
- return await ignoreMissingWorkspace(() => workspace.exists(normalized)) ?? (assets ? await assets.exists(normalized) : false);
545
- },
546
- list: async (path, options) => {
547
- const normalized = path ? normalizeListPath(path) : "";
548
- const workspaceEntries = await ignoreMissingWorkspace(() => workspace.list(normalized, options)) ?? [];
549
- if (normalized && workspaceEntries.length) return workspaceEntries;
550
- let assetEntries = assets ? await assets.list(normalized, options) : [];
551
- if (!normalized && options?.recursive && workspaceEntries.length) {
552
- const workspaceRoots = new Set(workspaceEntries.filter((entry) => entry.type === "directory").map((entry) => entry.path.split("/")[0]));
553
- assetEntries = assetEntries.filter((entry) => !workspaceRoots.has(entry.path.split("/")[0]));
554
- }
555
- return mergeEntries(assetEntries, workspaceEntries);
556
- },
557
- glob: async (pattern, options) => {
558
- const normalized = normalizePattern(pattern);
559
- return mergeEntries(assets ? await assets.glob(normalized, options) : [], await ignoreMissingWorkspace(() => workspace.glob(normalized, options)) ?? []);
560
- },
561
- search: async (query) => {
562
- const normalized = {
563
- ...query,
564
- cwd: query.cwd ? normalizeListPath(query.cwd) : query.cwd,
565
- paths: query.paths?.map((path) => normalizeListPath(path))
566
- };
567
- const limit = normalized.limit ?? 100;
568
- return mergeSearchHits(assets ? await assets.search(normalized) : [], await ignoreMissingWorkspace(() => workspace.search(normalized)) ?? []).slice(0, limit);
569
- },
570
- materializeSources: async (options) => await workspace.materializeSources?.(options) ?? {
571
- bytes: 0,
572
- directories: 0,
573
- durationMs: 0,
574
- files: 0,
575
- path: options?.path || "",
576
- sources: []
278
+ function paddedTarContent(content) {
279
+ const padding = content.byteLength % tarBlockSize ? tarBlockSize - content.byteLength % tarBlockSize : 0;
280
+ if (!padding) return Buffer.from(content);
281
+ return Buffer.concat([Buffer.from(content), Buffer.alloc(padding)]);
282
+ }
283
+ function splitTarPath(path) {
284
+ if (Buffer.byteLength(path) <= 100) return { name: path };
285
+ const parts = path.split("/");
286
+ for (let index = 1; index < parts.length; index++) {
287
+ const prefix = parts.slice(0, index).join("/");
288
+ const name = parts.slice(index).join("/");
289
+ if (Buffer.byteLength(prefix) <= 155 && Buffer.byteLength(name) <= 100) return {
290
+ name,
291
+ prefix
292
+ };
293
+ }
294
+ throw new Error(`[vitehub] Harness Workspace Session path is too long for tar transfer: ${path}`);
295
+ }
296
+ function writeTarString(header, offset, length, value) {
297
+ const bytes = Buffer.from(value);
298
+ bytes.copy(header, offset, 0, Math.min(bytes.byteLength, length));
299
+ }
300
+ function writeTarOctal(header, offset, length, value) {
301
+ const text = value.toString(8).padStart(length - 1, "0").slice(-(length - 1));
302
+ header.write(text, offset, length - 1, "ascii");
303
+ header[offset + length - 1] = 0;
304
+ }
305
+ function tarHeader(path, options) {
306
+ const header = Buffer.alloc(tarBlockSize);
307
+ const { name, prefix } = splitTarPath(path);
308
+ if (options.linkName && Buffer.byteLength(options.linkName) > 100) throw new Error(`[vitehub] Harness Workspace Session symlink target is too long for tar transfer: ${path}`);
309
+ writeTarString(header, 0, 100, name);
310
+ writeTarOctal(header, 100, 8, options.mode);
311
+ writeTarOctal(header, 108, 8, 0);
312
+ writeTarOctal(header, 116, 8, 0);
313
+ writeTarOctal(header, 124, 12, options.size);
314
+ writeTarOctal(header, 136, 12, 0);
315
+ header.fill(32, 148, 156);
316
+ header[156] = options.type === "directory" ? 53 : options.type === "symlink" ? 50 : 48;
317
+ if (options.linkName) writeTarString(header, 157, 100, options.linkName);
318
+ writeTarString(header, 257, 6, "ustar");
319
+ writeTarString(header, 263, 2, "00");
320
+ if (prefix) writeTarString(header, 345, 155, prefix);
321
+ let checksum = 0;
322
+ for (const byte of header) checksum += byte;
323
+ header.write(checksum.toString(8).padStart(6, "0"), 148, 6, "ascii");
324
+ header[154] = 0;
325
+ header[155] = 32;
326
+ return header;
327
+ }
328
+ function createWorkspaceTarGz(directories, files) {
329
+ const blocks = [];
330
+ for (const directory of [...directories].sort((left, right) => left.localeCompare(right))) {
331
+ const path = directory.endsWith("/") ? directory : `${directory}/`;
332
+ blocks.push(tarHeader(path, {
333
+ mode: 493,
334
+ size: 0,
335
+ type: "directory"
336
+ }));
337
+ }
338
+ for (const [path, file] of [...files.entries()].sort(([left], [right]) => left.localeCompare(right))) {
339
+ if (file.symlinkTarget) {
340
+ blocks.push(tarHeader(path, {
341
+ linkName: file.symlinkTarget,
342
+ mode: 511,
343
+ size: 0,
344
+ type: "symlink"
345
+ }));
346
+ continue;
577
347
  }
578
- };
348
+ blocks.push(tarHeader(path, {
349
+ mode: 420,
350
+ size: file.content.byteLength,
351
+ type: "file"
352
+ }));
353
+ blocks.push(paddedTarContent(file.content));
354
+ }
355
+ blocks.push(Buffer.alloc(tarBlockSize * 2));
356
+ return gzipSync(Buffer.concat(blocks));
357
+ }
358
+ async function extractWorkspaceArchive(sandbox, sessionWorkDir, initialTree, directories, abortSignal) {
359
+ if (!initialTree.files.size && !directories.size) return;
360
+ const path = sandboxPath(sessionWorkDir, archivePath);
361
+ await sandbox.writeBinaryFile({
362
+ abortSignal,
363
+ content: createWorkspaceTarGz(directories, initialTree.files),
364
+ path
365
+ });
366
+ await runSandbox(sandbox, {
367
+ abortSignal,
368
+ command: `tar -xzf ${shellQuote(archivePath)} && rm ${shellQuote(archivePath)}`,
369
+ workingDirectory: sessionWorkDir
370
+ });
579
371
  }
580
- function toReadOperations(options) {
581
- return {
582
- list: options?.list,
583
- materialize: options?.materialize ?? true,
584
- read: options?.read,
585
- search: options?.search
586
- };
372
+ async function initializeSandboxGitBaseline(sandbox, sessionWorkDir, abortSignal) {
373
+ await runSandbox(sandbox, {
374
+ abortSignal,
375
+ command: "if command -v git >/dev/null 2>&1; then git init -q && git config user.email vitehub@example.invalid && git config user.name ViteHub && git add -A -f && git commit --allow-empty --no-gpg-sign --no-verify -qm workspace-baseline || true; fi",
376
+ workingDirectory: sessionWorkDir
377
+ });
587
378
  }
588
- function toWriteOperations(options) {
589
- return {
590
- ...toReadOperations(options),
591
- write: {
592
- appendFile: options?.appendFile !== false,
593
- copyPath: options?.copyPath !== false,
594
- deletePath: options?.deletePath !== false,
595
- makeDir: options?.makeDir !== false,
596
- movePath: options?.movePath !== false,
597
- writeFile: options?.writeFile !== false
598
- }
379
+ async function listSandboxPaths(sandbox, sessionWorkDir, type, abortSignal) {
380
+ const result = await runSandbox(sandbox, {
381
+ abortSignal,
382
+ command: `find . -type ${type} -print`,
383
+ workingDirectory: sessionWorkDir
384
+ });
385
+ return new Set(pathsFromFindOutput(result.stdout));
386
+ }
387
+ async function readSandboxSymlinkTarget(sandbox, sessionWorkDir, path, abortSignal) {
388
+ return (await runSandbox(sandbox, {
389
+ abortSignal,
390
+ command: `readlink -- ${shellQuote(path)}`,
391
+ workingDirectory: sessionWorkDir
392
+ })).stdout.replace(/\n$/, "");
393
+ }
394
+ async function copyWorkspaceToSandbox(workspace, sandbox, sessionWorkDir, abortSignal, paths, onMaterializeProgress, onProgress) {
395
+ await withPrepareProgress(onProgress, {
396
+ data: { paths: paths ?? null },
397
+ id: "workspace.prepare.materialize",
398
+ label: "Materializing workspace sources"
399
+ }, async () => {
400
+ await materializeWorkspaceSourcesForSession(workspace, paths, {
401
+ ...abortSignal ? { abortSignal } : {},
402
+ ...onMaterializeProgress ? { onProgress: onMaterializeProgress } : {}
403
+ });
404
+ });
405
+ const entries = await withPrepareProgress(onProgress, {
406
+ data: { paths: paths ?? null },
407
+ id: "workspace.prepare.entries",
408
+ label: "Resolving workspace entries"
409
+ }, async () => await workspaceEntries(workspace, paths));
410
+ const directoriesToCreate = new Set(workspaceDirectories(entries));
411
+ const initialTree = {
412
+ archiveDirectories: directoriesToCreate,
413
+ directories: new Set(workspaceDirectories(entries)),
414
+ files: /* @__PURE__ */ new Map()
599
415
  };
600
- }
601
- function createDefaultToolSet(createTools) {
602
- return createTools();
603
- }
604
- function emptyTools() {
605
- return {};
606
- }
607
- function useWorkspace(name, options) {
608
- if (options?.mode === "write") {
609
- const workspace = createLazyWorkspace(name);
610
- const createTools = (opts) => createWorkspaceTools(workspace, {
611
- broadSearchPaths: opts?.broadSearchPaths,
612
- cwd: opts?.cwd,
613
- maxShellCalls: opts?.maxShellCalls,
614
- maxOutputLength: opts?.maxOutputLength,
615
- operations: toWriteOperations(opts),
616
- timeout: opts?.timeout
416
+ const files = workspaceFiles(entries);
417
+ for (const entry of files) addParentDirectories(directoriesToCreate, entry.path);
418
+ await withPrepareProgress(onProgress, {
419
+ data: { files: files.length },
420
+ id: "workspace.prepare.read-files",
421
+ label: "Reading workspace files"
422
+ }, async () => {
423
+ await forEachConcurrent(files, workspaceReadConcurrency, async (entry) => {
424
+ const bytes = contentToBytes(await workspace.fs.readFile(entry.path, { encoding: "binary" }));
425
+ initialTree.files.set(entry.path, {
426
+ content: bytes,
427
+ mediaType: entry.mediaType,
428
+ symlinkTarget: entry.metadata?.gitMode === "120000" ? typeof entry.metadata.symlinkTarget === "string" ? entry.metadata.symlinkTarget : new TextDecoder().decode(bytes) : void 0
429
+ });
617
430
  });
618
- const createReadTools = (opts) => createWorkspaceTools(createReadonlyFs(name, workspace), {
619
- broadSearchPaths: opts?.broadSearchPaths,
620
- cwd: opts?.cwd,
621
- maxShellCalls: opts?.maxShellCalls,
622
- maxOutputLength: opts?.maxOutputLength,
623
- operations: toReadOperations(opts),
624
- timeout: opts?.timeout
431
+ });
432
+ await withPrepareProgress(onProgress, {
433
+ id: "workspace.prepare.reset-sandbox",
434
+ label: "Resetting sandbox workspace"
435
+ }, async () => {
436
+ await resetSandboxWorkDir(sandbox, sessionWorkDir, abortSignal);
437
+ });
438
+ await withPrepareProgress(onProgress, {
439
+ data: {
440
+ directories: directoriesToCreate.size,
441
+ files: initialTree.files.size
442
+ },
443
+ id: "workspace.prepare.extract-archive",
444
+ label: "Extracting workspace archive"
445
+ }, async () => {
446
+ await extractWorkspaceArchive(sandbox, sessionWorkDir, initialTree, directoriesToCreate, abortSignal);
447
+ });
448
+ await withPrepareProgress(onProgress, {
449
+ id: "workspace.prepare.git-status",
450
+ label: "Preparing workspace status"
451
+ }, async () => {
452
+ await initializeSandboxGitBaseline(sandbox, sessionWorkDir, abortSignal);
453
+ });
454
+ return initialTree;
455
+ }
456
+ async function copySandboxChangesToWorkspace(session, definition, sandbox, sessionWorkDir, initialTree, abortSignal, ignoreWriteBackPaths, commit, onWriteBack) {
457
+ if (!sandbox.readBinaryFile) throw new Error("[vitehub] Harness Workspace Session write mode requires sandbox.readBinaryFile.");
458
+ const ignoredWriteBackPaths = new Set([...ignoreWriteBackPaths, ".git"]);
459
+ const sandboxDirectories = await listSandboxPaths(sandbox, sessionWorkDir, "d", abortSignal);
460
+ const sandboxFiles = await listSandboxPaths(sandbox, sessionWorkDir, "f", abortSignal);
461
+ const sandboxSymlinks = await listSandboxPaths(sandbox, sessionWorkDir, "l", abortSignal);
462
+ const sandboxFileEntries = new Set([...sandboxFiles, ...sandboxSymlinks]);
463
+ for (const path of initialTree.files.keys()) {
464
+ if (isIgnoredWriteBackPath(path, ignoredWriteBackPaths)) continue;
465
+ if (!sandboxFileEntries.has(path)) await session.rm(path, { force: true });
466
+ }
467
+ for (const path of [...initialTree.directories].sort((left, right) => right.length - left.length)) {
468
+ if (isIgnoredWriteBackPath(path, ignoredWriteBackPaths)) continue;
469
+ if (isIgnoredWriteBackParent(path, ignoredWriteBackPaths)) continue;
470
+ if (!sandboxDirectories.has(path)) await session.rm(path, {
471
+ force: true,
472
+ recursive: true
625
473
  });
626
- const tools = createDefaultToolSet(createTools);
627
- tools.inspect = createReadTools;
628
- tools.write = createTools;
629
- tools.none = emptyTools;
630
- return {
631
- diff: async (options) => await workspace.diff(options),
632
- fs: createWritableFs(workspace),
633
- snapshot: async (options) => await workspace.snapshot(options),
634
- startSession: async (options) => await workspace.startSession(options),
635
- tools
636
- };
637
474
  }
638
- const fs = createReadonlyFs(name, createLazyWorkspace(name));
639
- const createTools = (opts) => createWorkspaceTools(fs, {
640
- broadSearchPaths: opts?.broadSearchPaths,
641
- cwd: opts?.cwd,
642
- maxShellCalls: opts?.maxShellCalls,
643
- maxOutputLength: opts?.maxOutputLength,
644
- operations: toReadOperations(opts),
645
- timeout: opts?.timeout
646
- });
647
- const tools = createDefaultToolSet(createTools);
648
- tools.inspect = createTools;
649
- tools.none = emptyTools;
475
+ for (const path of sandboxDirectories) {
476
+ if (isIgnoredWriteBackPath(path, ignoredWriteBackPaths)) continue;
477
+ if (!initialTree.directories.has(path) && isIgnoredWriteBackParent(path, ignoredWriteBackPaths)) continue;
478
+ if (initialTree.archiveDirectories.has(path)) continue;
479
+ await session.mkdir(path, { recursive: true });
480
+ }
481
+ for (const path of sandboxFiles) {
482
+ if (isIgnoredWriteBackPath(path, ignoredWriteBackPaths)) continue;
483
+ const initial = initialTree.files.get(path);
484
+ const content = await sandbox.readBinaryFile({
485
+ abortSignal,
486
+ path: sandboxPath(sessionWorkDir, path)
487
+ });
488
+ if (!content || !initial?.symlinkTarget && bytesEqual(initial?.content, content)) continue;
489
+ await session.writeFile(path, content, { mediaType: initial?.mediaType || lookup(path) || void 0 });
490
+ }
491
+ for (const path of sandboxSymlinks) {
492
+ if (isIgnoredWriteBackPath(path, ignoredWriteBackPaths)) continue;
493
+ const initial = initialTree.files.get(path);
494
+ const target = await readSandboxSymlinkTarget(sandbox, sessionWorkDir, path, abortSignal);
495
+ if (initial?.symlinkTarget === target) continue;
496
+ await session.writeFile(path, contentToBytes(target), { metadata: { gitMode: "120000" } });
497
+ }
498
+ const diff = await session.diff();
499
+ if (!diff.entries.length) return;
500
+ if (commit) {
501
+ const commitOptions = commit(diff);
502
+ if (!commitOptions) return;
503
+ await session.commit({ message: commitOptions.message || "harness-workspace-session" });
504
+ await onWriteBack?.(diff);
505
+ return;
506
+ }
507
+ const autoCommit = definition ? resolveWorkspaceAutoCommit(definition, diff) : void 0;
508
+ if (definition && !autoCommit) return;
509
+ await session.commit({ message: autoCommit?.message || "harness-workspace-session" });
510
+ await onWriteBack?.(diff);
511
+ }
512
+ async function prepareHarnessWorkspaceSession(workspace, options) {
513
+ const paths = normalizeSessionPaths(options.paths);
514
+ const ignoreWriteBackPaths = new Set((options.ignoreWriteBackPaths || []).map(normalizeHarnessWorkspacePath));
515
+ const initialTree = await copyWorkspaceToSandbox(workspace, options.session, options.sessionWorkDir, options.abortSignal, paths, options.onMaterializeProgress, options.onProgress);
516
+ const sessionOptions = paths ? { paths } : void 0;
517
+ const workspaceSession = isWritableWorkspaceFacade(workspace) && (paths === void 0 || paths.length) ? await withPrepareProgress(options.onProgress, {
518
+ data: { paths: paths ?? null },
519
+ id: "workspace.prepare.start-session",
520
+ label: "Starting workspace write session"
521
+ }, async () => await workspace.startSession(sessionOptions)) : void 0;
650
522
  return {
651
- fs,
652
- tools
523
+ async close(error) {
524
+ try {
525
+ if (!error && workspaceSession) await copySandboxChangesToWorkspace(workspaceSession, options.definition, options.session, options.sessionWorkDir, initialTree, options.abortSignal, ignoreWriteBackPaths, options.commit, options.onWriteBack);
526
+ } finally {
527
+ await workspaceSession?.close();
528
+ }
529
+ },
530
+ async refreshGitBaseline() {
531
+ await withPrepareProgress(options.onProgress, {
532
+ id: "workspace.prepare.git-status",
533
+ label: "Preparing workspace status"
534
+ }, async () => {
535
+ await initializeSandboxGitBaseline(options.session, options.sessionWorkDir, options.abortSignal);
536
+ });
537
+ }
653
538
  };
654
539
  }
655
540
  //#endregion
656
- export { createWorkspaceTools, defineWorkspace, resolveWorkspaceAutoCommit, sources_exports as source, useWorkspace };
541
+ export { createWorkspace, createWorkspaceTools, custom, defineWorkspace, fetch, file, github, glob, markdown, mcpResources, prepareHarnessWorkspaceSession, resolveRegisteredWorkspaceDefinition, resolveWorkspaceAutoCommit, sources_exports as source, useWorkspace };