@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
package/dist/index.js CHANGED
@@ -1,26 +1,29 @@
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";
8
- 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";
1
+ import { n as __exportAll } from "./rolldown-runtime-B4iAMlE-.js";
2
+ import { r as isWorkspaceConflict, s as workspaceError, t as normalizeSafeWorkspacePath } from "./path-DrSIenjj.js";
3
+ import { n as resolveWorkspaceStoreTarget } from "./target-D4Bqb1eH.js";
4
+ import { t as createWorkspaceTools } from "./ai-BZyLwULx.js";
5
+ import { d as withWorkspaceRuntimeOptions, m as fetch, u as ownSourceOption } from "./config-B7dmzDX3.js";
6
+ import { t as workspaceErrorDiagnostics } from "./error-diagnostics-DY5GP47p.js";
7
+ import { g as registerWorkspacePlugin, h as resolveWorkspaceAutoCommit } from "./utils-Blrh4N2n.js";
8
+ import { t as createWorkspace } from "./workspace-6pxkOuxr.js";
9
+ import { t as file } from "./file-C0_aPWSS.js";
10
+ import { t as github } from "./github-CPxHtFB7.js";
11
+ import { t as glob } from "./glob--XcLlcml.js";
12
+ import { t as mcpResources } from "./mcp-resources-BREFCmtn.js";
13
+ import { r as resolveRegisteredWorkspaceDefinition } from "./registry-Bp-8UUfG.js";
14
+ import { t as useWorkspace } from "./use-BQj7nSz6.js";
15
+ import { invalidateWorkspaceStore } from "./runtime/state.js";
16
+ import { hasRuntimeType } from "@vite-hub/runtime/internal/runtime-type";
17
+ import { array, sourceIgnores } from "@vite-hub/source";
13
18
  import { lookup } from "mrmime";
14
- import { markdown as markdown$1, mcpResources as mcpResources$1 } from "@vite-hub/source";
15
- import { gzipSync } from "node:zlib";
19
+ import { markdown as markdown$1 } from "@vite-hub/source/markdown";
16
20
  //#region src/core/define.ts
17
- const workspaceDefinitionKeys = new Set([
21
+ const workspaceDefinitionKeys = /* @__PURE__ */ new Set([
18
22
  "bindings",
19
23
  "commit",
20
24
  "hooks",
21
25
  "loaders",
22
26
  "plugins",
23
- "publish",
24
27
  "rootDir",
25
28
  "rules",
26
29
  "sourceRootDir",
@@ -30,18 +33,18 @@ const workspaceDefinitionKeys = new Set([
30
33
  function assertWorkspaceDefinitionKeys(definition) {
31
34
  const unsupported = Object.keys(definition).filter((key) => !workspaceDefinitionKeys.has(key));
32
35
  if (!unsupported.length) return;
33
- throw new TypeError(`[vitehub] defineWorkspace does not support option${unsupported.length === 1 ? "" : "s"}: ${unsupported.join(", ")}.`);
36
+ throw workspaceErrorDiagnostics.WORKSPACE_R0015({ message: `[vitehub] defineWorkspace does not support option${unsupported.length === 1 ? "" : "s"}: ${unsupported.join(", ")}.` });
34
37
  }
35
38
  function defineWorkspace(definition) {
36
- if (!definition || typeof definition !== "object") throw new TypeError("[vitehub] defineWorkspace requires a workspace definition.");
37
- if ("name" in definition) throw new TypeError("[vitehub] Workspace names are inferred from definition filenames.");
39
+ if (!definition || typeof definition !== "object") throw workspaceErrorDiagnostics.WORKSPACE_R0016({ message: "[vitehub] defineWorkspace requires a workspace definition." });
40
+ if ("name" in definition) throw workspaceErrorDiagnostics.WORKSPACE_R0017({ message: "[vitehub] Workspace names are inferred from definition filenames." });
38
41
  assertWorkspaceDefinitionKeys(definition);
39
42
  return definition;
40
43
  }
41
44
  //#endregion
42
45
  //#region src/sources/custom.ts
43
46
  function custom(source) {
44
- if (!("files" in source) || !Array.isArray(source.files)) return source;
47
+ if (!Object.hasOwn(source, "files") || !Array.isArray(source.files)) return source;
45
48
  const { files: inputFiles, ...options } = source;
46
49
  const files = inputFiles.map((file) => ({
47
50
  ...file,
@@ -68,43 +71,15 @@ function custom(source) {
68
71
  //#endregion
69
72
  //#region src/sources/markdown.ts
70
73
  function markdown(options) {
71
- const key = normalizeSafeWorkspacePath(options.workspacePath || options.path || "");
74
+ const workspacePath = Object.hasOwn(options, "workspacePath") && options.workspacePath ? options.workspacePath : Object.hasOwn(options, "path") && options.path ? options.path : "";
75
+ const key = normalizeSafeWorkspacePath(workspacePath);
76
+ const source = markdown$1(options);
72
77
  return {
73
- ...withWorkspaceRuntimeOptions(markdown$1(options), options),
74
- probeKeys: options.probeKeys || [key]
78
+ ...withWorkspaceRuntimeOptions(source, options),
79
+ probeKeys: ownSourceOption(options, "probeKeys") || [key]
75
80
  };
76
81
  }
77
82
  //#endregion
78
- //#region src/sources/mcp-resources.ts
79
- function mcpResources(options) {
80
- const livePaths = {};
81
- const baseSource = mcpResources$1({
82
- ...options,
83
- cache: options.cache
84
- });
85
- return markLiveWorkspaceSource(withWorkspaceRuntimeOptions({
86
- ...baseSource,
87
- async prepare(ctx) {
88
- await baseSource.prepare?.(ctx);
89
- resetLivePaths(livePaths, resolveMountPath(options.mount, ctx), await baseSource.getKeys(ctx));
90
- }
91
- }, {
92
- ...options,
93
- materialize: options.materialize || (options.sync ? "none" : "lazy")
94
- }), livePaths);
95
- }
96
- registerMcpResourcesSourceLoader((input) => mcpResources(input));
97
- function resolveMountPath(mount, ctx) {
98
- return normalizeSafeWorkspacePath((typeof mount === "string" ? mount : mount?.path) ?? ctx.mountPath ?? ctx.source ?? "", { allowEmpty: true });
99
- }
100
- function resetLivePaths(paths, mountPath, keys) {
101
- for (const path of Object.keys(paths)) delete paths[path];
102
- for (const key of keys) {
103
- const path = normalizeSafeWorkspacePath(`${mountPath}/${key}`.replace(/\/+/g, "/"), { allowEmpty: false });
104
- paths[path] = key;
105
- }
106
- }
107
- //#endregion
108
83
  //#region src/sources/index.ts
109
84
  var sources_exports = /* @__PURE__ */ __exportAll({
110
85
  custom: () => custom,
@@ -116,419 +91,149 @@ var sources_exports = /* @__PURE__ */ __exportAll({
116
91
  mcpResources: () => mcpResources
117
92
  });
118
93
  //#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);
211
- }
212
- }
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);
219
- }
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
94
+ //#region src/collection.ts
95
+ async function openWorkspace(input) {
96
+ if (hasRuntimeType(input, "function")) return await input();
97
+ if (hasRuntimeType(input, "string")) return useWorkspace(input);
98
+ return input;
99
+ }
100
+ function workspaceFile(options) {
101
+ const { path, schema, workspace: input, ...query } = options;
102
+ const load = async ({ signal }) => {
103
+ const workspace = await openWorkspace(input);
104
+ const stat = await workspace.fs.stat(path);
105
+ if (stat.type !== "file") throw workspaceErrorDiagnostics.WORKSPACE_R0010({ path });
106
+ const raw = await workspace.fs.readFile(path, { encoding: "utf8" });
107
+ signal?.throwIfAborted();
108
+ const items = JSON.parse(raw);
109
+ if (!Array.isArray(items)) throw workspaceErrorDiagnostics.WORKSPACE_R0011({ path });
110
+ return {
111
+ digest: stat.digest || void 0,
112
+ items
285
113
  };
114
+ };
115
+ return schema ? array(load, {
116
+ ...query,
117
+ schema
118
+ }) : array(load, query);
119
+ }
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;
286
140
  }
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;
141
+ return bytes;
320
142
  }
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
- }));
330
- }
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
- }));
143
+ function findClosingBrace(pattern, opening) {
144
+ let depth = 0;
145
+ for (let index = opening; index < pattern.length; index++) {
146
+ if (pattern[index] === "\\") {
147
+ index++;
339
148
  continue;
340
149
  }
341
- blocks.push(tarHeader(path, {
342
- mode: 420,
343
- size: file.content.byteLength,
344
- type: "file"
345
- }));
346
- blocks.push(paddedTarContent(file.content));
150
+ if (pattern[index] === "{") depth++;
151
+ else if (pattern[index] === "}" && --depth === 0) return index;
347
152
  }
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 });
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++;
162
+ continue;
163
+ }
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 workspaceErrorDiagnostics.WORKSPACE_R0018({ message: `[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 workspaceErrorDiagnostics.WORKSPACE_R0019({ message: `[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 workspaceErrorDiagnostics.WORKSPACE_R0020({ message: `[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, registerWorkspacePlugin, resolveRegisteredWorkspaceDefinition, resolveWorkspaceAutoCommit, resolveWorkspaceStoreTarget, sources_exports as source, sourceIgnores, useWorkspace, workspaceFile };