@vite-hub/workspace 0.0.3 → 0.0.4

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 (86) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +13 -2
  3. package/dist/{ai-Ce3PtWFW.js → ai-BqCC8BpY.js} +2 -2
  4. package/dist/{ai-nmHdzjCM.d.ts → ai-CjxvGqM0.d.ts} +1 -1
  5. package/dist/ai.d.ts +2 -2
  6. package/dist/ai.js +1 -1
  7. package/dist/{asset-registry-CaG9b7tf.js → asset-registry-8QI3ML3K.js} +1 -1
  8. package/dist/chunk-2rV9d50f.js +35 -0
  9. package/dist/cloudflare.d.ts +1 -1
  10. package/dist/cloudflare.js +1 -1
  11. package/dist/collections.d.ts +2 -2
  12. package/dist/collections.js +1 -1
  13. package/dist/{config-CZLO0m9h.js → config-Bc3c4Su1.js} +213 -120
  14. package/dist/{config-CDoyls2X.js → config-CHLLWklZ.js} +9 -3
  15. package/dist/{config-3I1BnsdO.d.ts → config-DE9xlaIw.d.ts} +1 -1
  16. package/dist/{file-CHfsZpso.js → file-Bc1X7pco.js} +3 -3
  17. package/dist/{files-QRV55OCx.js → files-Q6xZjDHA.js} +20 -9
  18. package/dist/{github-CfA5vpJ5.js → github-DHnjxQIX.js} +24 -15
  19. package/dist/{glob-D0vD_wRY.js → glob-CEZKeZFC.js} +5 -4
  20. package/dist/host-DJH8cuoU.js +1030 -0
  21. package/dist/{hosted-C1-tTTTf.js → hosted-RPeJOCFz.js} +121 -31
  22. package/dist/hosted-vercel-blob-d6C8ND5j.js +23580 -0
  23. package/dist/hosted-vercel-blob.d.ts +1 -1
  24. package/dist/hosted-vercel-blob.js +1 -1
  25. package/dist/hosted.d.ts +1 -1
  26. package/dist/hosted.js +1 -1
  27. package/dist/index.d.ts +42 -51
  28. package/dist/index.js +124 -419
  29. package/dist/lifecycle-LrL3sA4n.js +316 -0
  30. package/dist/loader.d.ts +1 -1
  31. package/dist/loader.js +1 -1
  32. package/dist/metadata-target-B0tOmVW7.js +717 -0
  33. package/dist/mountx.d.ts +1 -1
  34. package/dist/nitro.d.ts +1 -1
  35. package/dist/nitro.js +1 -1
  36. package/dist/nuxt.d.ts +1 -1
  37. package/dist/nuxt.js +8 -2
  38. package/dist/{path-CNI6wKIU.js → path-Cp59koVz.js} +28 -4
  39. package/dist/{provider-C3_elpEh.js → provider-B1yLjCJJ.js} +194 -47
  40. package/dist/providers/github/store.d.ts +1 -1
  41. package/dist/providers/github/store.js +1 -1
  42. package/dist/publish.d.ts +1 -1
  43. package/dist/publish.js +2 -2
  44. package/dist/registry-D3yzt8HQ.js +127 -0
  45. package/dist/{registry-BIQVCBWI.d.ts → registry-Uj6IVxes.d.ts} +3 -3
  46. package/dist/{request-execution-u9mgUXKX.js → request-execution-B-dSFlGB.js} +8 -4
  47. package/dist/runtime/assets.d.ts +1 -1
  48. package/dist/runtime/assets.js +4 -2
  49. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  50. package/dist/runtime/empty-registry.d.ts +1 -1
  51. package/dist/runtime/state.d.ts +4 -4
  52. package/dist/runtime/state.js +10 -7
  53. package/dist/runtime/workspace.d.ts +1 -1
  54. package/dist/runtime/workspace.js +1 -1
  55. package/dist/runtime-type-iEE6BjQJ.js +34 -0
  56. package/dist/runtime.d.ts +42 -7
  57. package/dist/runtime.js +275 -82
  58. package/dist/{search-C4REyHj9.js → search-BpiCF2Tw.js} +2 -2
  59. package/dist/server.d.ts +2 -2
  60. package/dist/server.js +23 -50
  61. package/dist/{shared-jfogBrd5.js → shared-DTR1Hhma.js} +97 -39
  62. package/dist/source-metadata.d.ts +9 -2
  63. package/dist/source-metadata.js +34 -2
  64. package/dist/{state-TTqa3x3Y.d.ts → state-tYcRWEh2.d.ts} +13 -12
  65. package/dist/store-Dt_Jyys3.js +608 -0
  66. package/dist/{sync-DiuDmSGk.js → sync-DnTQwt8r.js} +6 -5
  67. package/dist/test.d.ts +1 -1
  68. package/dist/test.js +1 -1
  69. package/dist/token-CVzURBxC.js +61 -0
  70. package/dist/{types-60Yn149G.d.ts → types-CYuwjJ4V.d.ts} +94 -27
  71. package/dist/{use-CsV3oIxH.js → use-BTNDR5Rd.js} +145 -31
  72. package/dist/{use-CUFSnFCS.d.ts → use-BiHzt0xA.d.ts} +21 -4
  73. package/dist/vite-BptCrpv2.js +4526 -0
  74. package/dist/vite-CtA9guIM.d.ts +66 -0
  75. package/dist/vite.d.ts +2 -50
  76. package/dist/vite.js +2 -2
  77. package/dist/{workspace-C4k92Ow8.js → workspace-Dq08Yn72.js} +224 -529
  78. package/dist/{workspace-66SKyiec.d.ts → workspace-Xddf4G1B.d.ts} +1 -1
  79. package/package.json +15 -18
  80. package/dist/chunk-8H4AJuhK.js +0 -14
  81. package/dist/host-CAnbugpI.js +0 -370
  82. package/dist/hosted-vercel-blob-CWBILDVo.js +0 -257
  83. package/dist/lifecycle-BYoa9hVb.js +0 -176
  84. package/dist/registry-CqyDTW9Y.js +0 -74
  85. package/dist/store-Bs1SLh55.js +0 -414
  86. package/dist/vite-tbfDxtlu.js +0 -2191
package/dist/index.js CHANGED
@@ -1,18 +1,20 @@
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-Ce3PtWFW.js";
4
- import { d as fetch, g as markLiveWorkspaceSource, u as registerMcpResourcesSourceLoader } from "./config-CZLO0m9h.js";
5
- import { g as isMissingWorkspacePathError, t as createWorkspace, u as resolveWorkspaceAutoCommit } from "./workspace-C4k92Ow8.js";
6
- import { r as resolveRegisteredWorkspaceDefinition } from "./registry-CqyDTW9Y.js";
7
- import { t as useWorkspace } from "./use-CsV3oIxH.js";
1
+ import { n as __exportAll } from "./chunk-2rV9d50f.js";
2
+ import { _ as workspaceError, m as isWorkspaceConflict, s as normalizeSafeWorkspacePath } from "./path-Cp59koVz.js";
3
+ import { t as createWorkspaceTools } from "./ai-BqCC8BpY.js";
4
+ import { d as registerMcpResourcesSourceLoader, p as fetch, u as prepareWorkspaceSource, v as markLiveWorkspaceSource } from "./config-Bc3c4Su1.js";
5
+ import { n as resolveWorkspaceStoreTarget } from "./target-D4Bqb1eH.js";
6
+ import { d as resolveWorkspaceAutoCommit, t as createWorkspace } from "./workspace-Dq08Yn72.js";
7
+ import { r as resolveRegisteredWorkspaceDefinition } from "./registry-D3yzt8HQ.js";
8
+ import { t as useWorkspace } from "./use-BTNDR5Rd.js";
8
9
  import { t as withWorkspaceRuntimeOptions } from "./runtime-options-BsPSv5O7.js";
9
- import { t as file } from "./file-CHfsZpso.js";
10
- import { t as github } from "./github-CfA5vpJ5.js";
11
- import { t as glob } from "./glob-D0vD_wRY.js";
12
- import { posix } from "node:path";
10
+ import { t as file } from "./file-Bc1X7pco.js";
11
+ import { t as github } from "./github-DHnjxQIX.js";
12
+ import { t as glob } from "./glob-CEZKeZFC.js";
13
+ import { invalidateWorkspaceStore } from "./runtime/state.js";
14
+ import { sourceIgnores } from "@vite-hub/source";
13
15
  import { lookup } from "mrmime";
14
- import { markdown as markdown$1, mcpResources as mcpResources$1 } from "@vite-hub/source";
15
- import { gzipSync } from "node:zlib";
16
+ import { markdown as markdown$1 } from "@vite-hub/source/markdown";
17
+ import { mcpResources as mcpResources$1 } from "@vite-hub/source/mcp";
16
18
  //#region src/core/define.ts
17
19
  const workspaceDefinitionKeys = new Set([
18
20
  "bindings",
@@ -85,7 +87,7 @@ function mcpResources(options) {
85
87
  return markLiveWorkspaceSource(withWorkspaceRuntimeOptions({
86
88
  ...baseSource,
87
89
  async prepare(ctx) {
88
- await baseSource.prepare?.(ctx);
90
+ await prepareWorkspaceSource(baseSource, ctx);
89
91
  resetLivePaths(livePaths, resolveMountPath(options.mount, ctx), await baseSource.getKeys(ctx));
90
92
  }
91
93
  }, {
@@ -115,420 +117,123 @@ var sources_exports = /* @__PURE__ */ __exportAll({
115
117
  markdown: () => markdown,
116
118
  mcpResources: () => mcpResources
117
119
  });
118
- //#endregion
119
- //#region src/session/harness.ts
120
- const archivePath = ".vitehub-workspace.tar.gz";
121
- const tarBlockSize = 512;
122
- const workspaceReadConcurrency = 16;
123
- function isWritableWorkspaceFacade(workspace) {
124
- return "startSession" in workspace && typeof workspace.startSession === "function";
125
- }
126
- function workspaceSourceMaterializer(workspace) {
127
- if ("materializeSources" in workspace && typeof workspace.materializeSources === "function") return (options) => workspace.materializeSources(options);
128
- const materializeSources = workspace.fs.materializeSources;
129
- if (typeof materializeSources === "function") return (options) => materializeSources(options);
130
- }
131
- function sandboxPath(root, path) {
132
- return posix.join(root, path);
133
- }
134
- function shellQuote(value) {
135
- return `'${value.replace(/'/g, "'\\''")}'`;
136
- }
137
- function isGeneratedSourceDescriptorPath(path) {
138
- return path === ".vitehub" || path === ".vitehub/sources" || /^\.vitehub\/sources\/[^/]+\.json$/.test(path);
139
- }
140
- function normalizeHarnessWorkspacePath(path = "") {
141
- const descriptorPath = normalizeSafeWorkspacePath(path, {
142
- allowEmpty: true,
143
- allowReserved: true
144
- });
145
- if (isGeneratedSourceDescriptorPath(descriptorPath)) return descriptorPath;
146
- return normalizeSafeWorkspacePath(path, { allowEmpty: true });
147
- }
148
- function normalizeSessionPaths(paths) {
149
- if (paths === void 0) return void 0;
150
- const normalized = [...new Set((paths || []).map(normalizeHarnessWorkspacePath))];
151
- if (normalized.includes("")) return void 0;
152
- return normalized.sort((left, right) => left.length - right.length || left.localeCompare(right));
153
- }
154
- function isIgnoredWriteBackPath(path, ignoreWriteBackPaths) {
155
- for (const ignoredPath of ignoreWriteBackPaths) if (path === ignoredPath || path.startsWith(`${ignoredPath}/`)) return true;
156
- return false;
157
- }
158
- function isIgnoredWriteBackParent(path, ignoreWriteBackPaths) {
159
- for (const ignoredPath of ignoreWriteBackPaths) if (ignoredPath.startsWith(`${path}/`)) return true;
160
- return false;
161
- }
162
- async function runSandbox(sandbox, options) {
163
- const result = await sandbox.run(options);
164
- if (result.exitCode !== 0) throw new Error(`[vitehub] Failed to prepare Harness Workspace Session: ${result.stderr || "sandbox command failed"}`);
165
- return result;
166
- }
167
- async function withPrepareProgress(onProgress, event, fn) {
168
- const startedAt = Date.now();
169
- await onProgress?.({
170
- data: event.data,
171
- id: event.id,
172
- label: event.label,
173
- status: "started"
174
- });
175
- try {
176
- const result = await fn();
177
- await onProgress?.({
178
- data: event.data,
179
- durationMs: Date.now() - startedAt,
180
- id: event.id,
181
- label: event.label,
182
- status: "completed"
183
- });
184
- return result;
185
- } catch (error) {
186
- await onProgress?.({
187
- data: {
188
- ...event.data,
189
- error: error instanceof Error ? error.message : String(error)
190
- },
191
- durationMs: Date.now() - startedAt,
192
- error: error instanceof Error ? error.message : String(error),
193
- id: event.id,
194
- label: event.label,
195
- status: "failed"
196
- });
197
- throw error;
198
- }
199
- }
200
- function workspaceFiles(entries) {
201
- return entries.filter((entry) => entry.type === "file").sort((left, right) => left.path.localeCompare(right.path));
202
- }
203
- function workspaceDirectories(entries) {
204
- return entries.filter((entry) => entry.type === "directory").map((entry) => entry.path).sort((left, right) => left.localeCompare(right));
205
- }
206
- function addParentDirectories(directories, path) {
207
- let directory = posix.dirname(path);
208
- while (directory && directory !== ".") {
209
- directories.add(directory);
210
- directory = posix.dirname(directory);
120
+ const modelWorkspaceGlobPatternLimits = Object.freeze({
121
+ maxBytes: 2048,
122
+ maxComplexity: 1024,
123
+ maxPatterns: 16
124
+ });
125
+ function boundedAdd(left, right, limit) {
126
+ if (left > limit - right) return limit + 1;
127
+ return left + right;
128
+ }
129
+ function boundedMultiply(left, right, limit) {
130
+ if (left && right > Math.floor(limit / left)) return limit + 1;
131
+ return left * right;
132
+ }
133
+ function boundedUtf8Bytes(value, limit) {
134
+ let bytes = 0;
135
+ for (let index = 0; index < value.length; index++) {
136
+ const codePoint = value.codePointAt(index);
137
+ if (codePoint > 65535) index++;
138
+ bytes += codePoint <= 127 ? 1 : codePoint <= 2047 ? 2 : codePoint <= 65535 ? 3 : 4;
139
+ if (bytes > limit) return limit + 1;
211
140
  }
141
+ return bytes;
212
142
  }
213
- async function forEachConcurrent(items, limit, fn) {
214
- let index = 0;
215
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
216
- while (index < items.length) {
217
- const item = items[index++];
218
- if (item !== void 0) await fn(item);
143
+ function findClosingBrace(pattern, opening) {
144
+ let depth = 0;
145
+ for (let index = opening; index < pattern.length; index++) {
146
+ if (pattern[index] === "\\") {
147
+ index++;
148
+ continue;
219
149
  }
220
- }));
221
- }
222
- async function workspaceEntries(workspace, paths) {
223
- if (paths && !paths.length) return [];
224
- if (!paths) return await workspace.fs.list("", { recursive: true });
225
- const entries = /* @__PURE__ */ new Map();
226
- for (const path of paths) {
227
- const stat = await workspace.fs.stat(path).catch(() => void 0);
228
- if (!stat) continue;
229
- entries.set(stat.path, stat);
230
- if (stat.type === "directory") for (const entry of await workspace.fs.list(path, { recursive: true })) entries.set(entry.path, entry);
231
- }
232
- return [...entries.values()].sort((left, right) => left.path.localeCompare(right.path));
233
- }
234
- async function materializeWorkspaceSourcesForSession(workspace, paths, options = {}) {
235
- const materialize = workspaceSourceMaterializer(workspace);
236
- if (!materialize) return;
237
- if (paths && !paths.length) return;
238
- await Promise.all((paths || [""]).map(async (path) => {
239
- await materialize({
240
- ...options,
241
- path
242
- }).catch((error) => {
243
- if (path && isMissingWorkspacePathError(error)) return;
244
- throw error;
245
- });
246
- }));
247
- }
248
- function bytesEqual(left, right) {
249
- if (!left || left.byteLength !== right.byteLength) return false;
250
- for (let index = 0; index < left.byteLength; index++) if (left[index] !== right[index]) return false;
251
- return true;
252
- }
253
- function pathsFromFindOutput(stdout) {
254
- return stdout.split("\n").map((path) => path.trim()).filter(Boolean).map((path) => path.replace(/^\.\//, "")).filter((path) => path && path !== ".").sort((left, right) => left.localeCompare(right));
255
- }
256
- async function resetSandboxWorkDir(sandbox, sessionWorkDir, abortSignal) {
257
- const workDir = posix.normalize(sessionWorkDir);
258
- const parent = posix.dirname(workDir);
259
- const name = posix.basename(workDir);
260
- await sandbox.writeBinaryFile({
261
- abortSignal,
262
- content: new Uint8Array(),
263
- path: sandboxPath(parent, ".vitehub-reset")
264
- });
265
- await runSandbox(sandbox, {
266
- abortSignal,
267
- command: `rm -rf -- ${shellQuote(name)} && mkdir -p -- ${shellQuote(name)} && rm -f -- ${shellQuote(".vitehub-reset")}`,
268
- workingDirectory: parent
269
- });
270
- }
271
- function paddedTarContent(content) {
272
- const padding = content.byteLength % tarBlockSize ? tarBlockSize - content.byteLength % tarBlockSize : 0;
273
- if (!padding) return Buffer.from(content);
274
- return Buffer.concat([Buffer.from(content), Buffer.alloc(padding)]);
275
- }
276
- function splitTarPath(path) {
277
- if (Buffer.byteLength(path) <= 100) return { name: path };
278
- const parts = path.split("/");
279
- for (let index = 1; index < parts.length; index++) {
280
- const prefix = parts.slice(0, index).join("/");
281
- const name = parts.slice(index).join("/");
282
- if (Buffer.byteLength(prefix) <= 155 && Buffer.byteLength(name) <= 100) return {
283
- name,
284
- prefix
285
- };
286
- }
287
- throw new Error(`[vitehub] Harness Workspace Session path is too long for tar transfer: ${path}`);
288
- }
289
- function writeTarString(header, offset, length, value) {
290
- const bytes = Buffer.from(value);
291
- bytes.copy(header, offset, 0, Math.min(bytes.byteLength, length));
292
- }
293
- function writeTarOctal(header, offset, length, value) {
294
- const text = value.toString(8).padStart(length - 1, "0").slice(-(length - 1));
295
- header.write(text, offset, length - 1, "ascii");
296
- header[offset + length - 1] = 0;
297
- }
298
- function tarHeader(path, options) {
299
- const header = Buffer.alloc(tarBlockSize);
300
- const { name, prefix } = splitTarPath(path);
301
- if (options.linkName && Buffer.byteLength(options.linkName) > 100) throw new Error(`[vitehub] Harness Workspace Session symlink target is too long for tar transfer: ${path}`);
302
- writeTarString(header, 0, 100, name);
303
- writeTarOctal(header, 100, 8, options.mode);
304
- writeTarOctal(header, 108, 8, 0);
305
- writeTarOctal(header, 116, 8, 0);
306
- writeTarOctal(header, 124, 12, options.size);
307
- writeTarOctal(header, 136, 12, 0);
308
- header.fill(32, 148, 156);
309
- header[156] = options.type === "directory" ? 53 : options.type === "symlink" ? 50 : 48;
310
- if (options.linkName) writeTarString(header, 157, 100, options.linkName);
311
- writeTarString(header, 257, 6, "ustar");
312
- writeTarString(header, 263, 2, "00");
313
- if (prefix) writeTarString(header, 345, 155, prefix);
314
- let checksum = 0;
315
- for (const byte of header) checksum += byte;
316
- header.write(checksum.toString(8).padStart(6, "0"), 148, 6, "ascii");
317
- header[154] = 0;
318
- header[155] = 32;
319
- return header;
320
- }
321
- function createWorkspaceTarGz(directories, files) {
322
- const blocks = [];
323
- for (const directory of [...directories].sort((left, right) => left.localeCompare(right))) {
324
- const path = directory.endsWith("/") ? directory : `${directory}/`;
325
- blocks.push(tarHeader(path, {
326
- mode: 493,
327
- size: 0,
328
- type: "directory"
329
- }));
150
+ if (pattern[index] === "{") depth++;
151
+ else if (pattern[index] === "}" && --depth === 0) return index;
330
152
  }
331
- for (const [path, file] of [...files.entries()].sort(([left], [right]) => left.localeCompare(right))) {
332
- if (file.symlinkTarget) {
333
- blocks.push(tarHeader(path, {
334
- linkName: file.symlinkTarget,
335
- mode: 511,
336
- size: 0,
337
- type: "symlink"
338
- }));
153
+ return -1;
154
+ }
155
+ function splitBraceParts(content, separator) {
156
+ const parts = [];
157
+ let depth = 0;
158
+ let start = 0;
159
+ for (let index = 0; index < content.length; index++) {
160
+ if (content[index] === "\\") {
161
+ index++;
339
162
  continue;
340
163
  }
341
- blocks.push(tarHeader(path, {
342
- mode: 420,
343
- size: file.content.byteLength,
344
- type: "file"
345
- }));
346
- blocks.push(paddedTarContent(file.content));
347
- }
348
- blocks.push(Buffer.alloc(tarBlockSize * 2));
349
- return gzipSync(Buffer.concat(blocks));
350
- }
351
- async function extractWorkspaceArchive(sandbox, sessionWorkDir, initialTree, directories, abortSignal) {
352
- if (!initialTree.files.size && !directories.size) return;
353
- const path = sandboxPath(sessionWorkDir, archivePath);
354
- await sandbox.writeBinaryFile({
355
- abortSignal,
356
- content: createWorkspaceTarGz(directories, initialTree.files),
357
- path
358
- });
359
- await runSandbox(sandbox, {
360
- abortSignal,
361
- command: `tar -xzf ${shellQuote(archivePath)} && rm ${shellQuote(archivePath)}`,
362
- workingDirectory: sessionWorkDir
363
- });
364
- }
365
- async function initializeSandboxGitBaseline(sandbox, sessionWorkDir, abortSignal) {
366
- await runSandbox(sandbox, {
367
- abortSignal,
368
- 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",
369
- workingDirectory: sessionWorkDir
370
- });
371
- }
372
- async function listSandboxPaths(sandbox, sessionWorkDir, type, abortSignal) {
373
- const result = await runSandbox(sandbox, {
374
- abortSignal,
375
- command: `find . -type ${type} -print`,
376
- workingDirectory: sessionWorkDir
377
- });
378
- return new Set(pathsFromFindOutput(result.stdout));
379
- }
380
- async function readSandboxSymlinkTarget(sandbox, sessionWorkDir, path, abortSignal) {
381
- return (await runSandbox(sandbox, {
382
- abortSignal,
383
- command: `readlink -- ${shellQuote(path)}`,
384
- workingDirectory: sessionWorkDir
385
- })).stdout.replace(/\n$/, "");
386
- }
387
- async function copyWorkspaceToSandbox(workspace, sandbox, sessionWorkDir, abortSignal, paths, onMaterializeProgress, onProgress) {
388
- await withPrepareProgress(onProgress, {
389
- data: { paths: paths ?? null },
390
- id: "workspace.prepare.materialize",
391
- label: "Materializing workspace sources"
392
- }, async () => {
393
- await materializeWorkspaceSourcesForSession(workspace, paths, {
394
- ...abortSignal ? { abortSignal } : {},
395
- ...onMaterializeProgress ? { onProgress: onMaterializeProgress } : {}
396
- });
397
- });
398
- const entries = await withPrepareProgress(onProgress, {
399
- data: { paths: paths ?? null },
400
- id: "workspace.prepare.entries",
401
- label: "Resolving workspace entries"
402
- }, async () => await workspaceEntries(workspace, paths));
403
- const directoriesToCreate = new Set(workspaceDirectories(entries));
404
- const initialTree = {
405
- archiveDirectories: directoriesToCreate,
406
- directories: new Set(workspaceDirectories(entries)),
407
- files: /* @__PURE__ */ new Map()
408
- };
409
- const files = workspaceFiles(entries);
410
- for (const entry of files) addParentDirectories(directoriesToCreate, entry.path);
411
- await withPrepareProgress(onProgress, {
412
- data: { files: files.length },
413
- id: "workspace.prepare.read-files",
414
- label: "Reading workspace files"
415
- }, async () => {
416
- await forEachConcurrent(files, workspaceReadConcurrency, async (entry) => {
417
- const bytes = contentToBytes(await workspace.fs.readFile(entry.path, { encoding: "binary" }));
418
- initialTree.files.set(entry.path, {
419
- content: bytes,
420
- mediaType: entry.mediaType,
421
- symlinkTarget: entry.metadata?.gitMode === "120000" ? typeof entry.metadata.symlinkTarget === "string" ? entry.metadata.symlinkTarget : new TextDecoder().decode(bytes) : void 0
422
- });
423
- });
424
- });
425
- await withPrepareProgress(onProgress, {
426
- id: "workspace.prepare.reset-sandbox",
427
- label: "Resetting sandbox workspace"
428
- }, async () => {
429
- await resetSandboxWorkDir(sandbox, sessionWorkDir, abortSignal);
430
- });
431
- await withPrepareProgress(onProgress, {
432
- data: {
433
- directories: directoriesToCreate.size,
434
- files: initialTree.files.size
435
- },
436
- id: "workspace.prepare.extract-archive",
437
- label: "Extracting workspace archive"
438
- }, async () => {
439
- await extractWorkspaceArchive(sandbox, sessionWorkDir, initialTree, directoriesToCreate, abortSignal);
440
- });
441
- await withPrepareProgress(onProgress, {
442
- id: "workspace.prepare.git-status",
443
- label: "Preparing workspace status"
444
- }, async () => {
445
- await initializeSandboxGitBaseline(sandbox, sessionWorkDir, abortSignal);
446
- });
447
- return initialTree;
448
- }
449
- async function copySandboxChangesToWorkspace(session, definition, sandbox, sessionWorkDir, initialTree, abortSignal, ignoreWriteBackPaths, commit, onWriteBack) {
450
- if (!sandbox.readBinaryFile) throw new Error("[vitehub] Harness Workspace Session write mode requires sandbox.readBinaryFile.");
451
- const ignoredWriteBackPaths = new Set([...ignoreWriteBackPaths, ".git"]);
452
- const sandboxDirectories = await listSandboxPaths(sandbox, sessionWorkDir, "d", abortSignal);
453
- const sandboxFiles = await listSandboxPaths(sandbox, sessionWorkDir, "f", abortSignal);
454
- const sandboxSymlinks = await listSandboxPaths(sandbox, sessionWorkDir, "l", abortSignal);
455
- const sandboxFileEntries = new Set([...sandboxFiles, ...sandboxSymlinks]);
456
- for (const path of initialTree.files.keys()) {
457
- if (isIgnoredWriteBackPath(path, ignoredWriteBackPaths)) continue;
458
- if (!sandboxFileEntries.has(path)) await session.rm(path, { force: true });
459
- }
460
- for (const path of [...initialTree.directories].sort((left, right) => right.length - left.length)) {
461
- if (isIgnoredWriteBackPath(path, ignoredWriteBackPaths)) continue;
462
- if (isIgnoredWriteBackParent(path, ignoredWriteBackPaths)) continue;
463
- if (!sandboxDirectories.has(path)) await session.rm(path, {
464
- force: true,
465
- recursive: true
466
- });
467
- }
468
- for (const path of sandboxDirectories) {
469
- if (isIgnoredWriteBackPath(path, ignoredWriteBackPaths)) continue;
470
- if (!initialTree.directories.has(path) && isIgnoredWriteBackParent(path, ignoredWriteBackPaths)) continue;
471
- if (initialTree.archiveDirectories.has(path)) continue;
472
- await session.mkdir(path, { recursive: true });
164
+ if (content[index] === "{") depth++;
165
+ else if (content[index] === "}") depth--;
166
+ else if (depth === 0 && content.startsWith(separator, index)) {
167
+ parts.push(content.slice(start, index));
168
+ index += separator.length - 1;
169
+ start = index + 1;
170
+ }
473
171
  }
474
- for (const path of sandboxFiles) {
475
- if (isIgnoredWriteBackPath(path, ignoredWriteBackPaths)) continue;
476
- const initial = initialTree.files.get(path);
477
- const content = await sandbox.readBinaryFile({
478
- abortSignal,
479
- path: sandboxPath(sessionWorkDir, path)
480
- });
481
- if (!content || !initial?.symlinkTarget && bytesEqual(initial?.content, content)) continue;
482
- await session.writeFile(path, content, { mediaType: initial?.mediaType || lookup(path) || void 0 });
172
+ parts.push(content.slice(start));
173
+ return parts;
174
+ }
175
+ function sequenceComplexity(content, limit) {
176
+ const parts = splitBraceParts(content, "..");
177
+ if (parts.length < 2 || parts.length > 3) return void 0;
178
+ const [rawStart, rawEnd, rawStep] = parts;
179
+ const numeric = /^-?\d+$/;
180
+ let start;
181
+ let end;
182
+ if (numeric.test(rawStart) && numeric.test(rawEnd)) {
183
+ start = Number(rawStart);
184
+ end = Number(rawEnd);
185
+ } else if (rawStart?.length === 1 && rawEnd?.length === 1) {
186
+ start = rawStart.codePointAt(0);
187
+ end = rawEnd.codePointAt(0);
188
+ } else return;
189
+ const step = rawStep === void 0 ? 1 : Math.abs(Number(rawStep));
190
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || !Number.isSafeInteger(step) || step === 0) return limit + 1;
191
+ return Math.floor(Math.abs(end - start) / step) + 1;
192
+ }
193
+ function patternComplexity(pattern, limit) {
194
+ let complexity = 1;
195
+ for (let index = 0; index < pattern.length; index++) {
196
+ if (pattern[index] === "\\") {
197
+ index++;
198
+ continue;
199
+ }
200
+ if (pattern[index] === "}") return limit + 1;
201
+ if (pattern[index] !== "{") continue;
202
+ const closing = findClosingBrace(pattern, index);
203
+ if (closing === -1) return limit + 1;
204
+ const content = pattern.slice(index + 1, closing);
205
+ if (!content) return limit + 1;
206
+ if (content.includes("{") || content.includes("}")) return limit + 1;
207
+ const alternatives = splitBraceParts(content, ",");
208
+ let braceComplexity;
209
+ if (alternatives.length > 1) {
210
+ braceComplexity = 0;
211
+ for (const alternative of alternatives) {
212
+ braceComplexity = boundedAdd(braceComplexity, patternComplexity(alternative, limit), limit);
213
+ if (braceComplexity > limit) break;
214
+ }
215
+ } else braceComplexity = sequenceComplexity(content, limit) ?? patternComplexity(content, limit);
216
+ complexity = boundedMultiply(complexity, braceComplexity, limit);
217
+ if (complexity > limit) return complexity;
218
+ index = closing;
483
219
  }
484
- for (const path of sandboxSymlinks) {
485
- if (isIgnoredWriteBackPath(path, ignoredWriteBackPaths)) continue;
486
- const initial = initialTree.files.get(path);
487
- const target = await readSandboxSymlinkTarget(sandbox, sessionWorkDir, path, abortSignal);
488
- if (initial?.symlinkTarget === target) continue;
489
- await session.writeFile(path, contentToBytes(target), { metadata: { gitMode: "120000" } });
220
+ return complexity;
221
+ }
222
+ function assertModelWorkspaceGlobPattern(pattern, limits = modelWorkspaceGlobPatternLimits) {
223
+ const patterns = Array.isArray(pattern) ? pattern : [pattern];
224
+ if (patterns.length > limits.maxPatterns) throw new TypeError(`[vitehub] Workspace glob accepts at most ${limits.maxPatterns} model-facing patterns.`);
225
+ let bytes = 0;
226
+ for (const item of patterns) {
227
+ bytes = boundedAdd(bytes, boundedUtf8Bytes(item, limits.maxBytes), limits.maxBytes);
228
+ if (bytes > limits.maxBytes) break;
490
229
  }
491
- const diff = await session.diff();
492
- if (!diff.entries.length) return;
493
- if (commit) {
494
- const commitOptions = commit(diff);
495
- if (!commitOptions) return;
496
- await session.commit({ message: commitOptions.message || "harness-workspace-session" });
497
- await onWriteBack?.(diff);
498
- return;
230
+ if (bytes > limits.maxBytes) throw new TypeError(`[vitehub] Workspace glob pattern input exceeds the model-facing limit of ${limits.maxBytes} bytes.`);
231
+ let complexity = 0;
232
+ for (const item of patterns) {
233
+ const normalized = item.replace(/\\/g, "/");
234
+ complexity = boundedAdd(complexity, patternComplexity(normalized, limits.maxComplexity), limits.maxComplexity);
235
+ if (complexity > limits.maxComplexity) throw new TypeError(`[vitehub] Workspace glob pattern complexity exceeds the model-facing limit of ${limits.maxComplexity} expansions.`);
499
236
  }
500
- const autoCommit = definition ? resolveWorkspaceAutoCommit(definition, diff) : void 0;
501
- if (definition && !autoCommit) return;
502
- await session.commit({ message: autoCommit?.message || "harness-workspace-session" });
503
- await onWriteBack?.(diff);
504
- }
505
- async function prepareHarnessWorkspaceSession(workspace, options) {
506
- const paths = normalizeSessionPaths(options.paths);
507
- const ignoreWriteBackPaths = new Set((options.ignoreWriteBackPaths || []).map(normalizeHarnessWorkspacePath));
508
- const initialTree = await copyWorkspaceToSandbox(workspace, options.session, options.sessionWorkDir, options.abortSignal, paths, options.onMaterializeProgress, options.onProgress);
509
- const sessionOptions = paths ? { paths } : void 0;
510
- const workspaceSession = isWritableWorkspaceFacade(workspace) && (paths === void 0 || paths.length) ? await withPrepareProgress(options.onProgress, {
511
- data: { paths: paths ?? null },
512
- id: "workspace.prepare.start-session",
513
- label: "Starting workspace write session"
514
- }, async () => await workspace.startSession(sessionOptions)) : void 0;
515
- return {
516
- async close(error) {
517
- try {
518
- if (!error && workspaceSession) await copySandboxChangesToWorkspace(workspaceSession, options.definition, options.session, options.sessionWorkDir, initialTree, options.abortSignal, ignoreWriteBackPaths, options.commit, options.onWriteBack);
519
- } finally {
520
- await workspaceSession?.close();
521
- }
522
- },
523
- async refreshGitBaseline() {
524
- await withPrepareProgress(options.onProgress, {
525
- id: "workspace.prepare.git-status",
526
- label: "Preparing workspace status"
527
- }, async () => {
528
- await initializeSandboxGitBaseline(options.session, options.sessionWorkDir, options.abortSignal);
529
- });
530
- }
531
- };
532
237
  }
533
238
  //#endregion
534
- export { createWorkspace, createWorkspaceTools, custom, defineWorkspace, fetch, file, github, glob, markdown, mcpResources, prepareHarnessWorkspaceSession, resolveRegisteredWorkspaceDefinition, resolveWorkspaceAutoCommit, sources_exports as source, useWorkspace };
239
+ export { assertModelWorkspaceGlobPattern, createWorkspace, createWorkspaceTools, custom, defineWorkspace, fetch, file, github, glob, invalidateWorkspaceStore, isWorkspaceConflict, markdown, mcpResources, modelWorkspaceGlobPatternLimits, normalizeSafeWorkspacePath, resolveRegisteredWorkspaceDefinition, resolveWorkspaceAutoCommit, resolveWorkspaceStoreTarget, sources_exports as source, sourceIgnores, useWorkspace };