@vite-hub/workspace 0.0.1 → 0.0.3

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 (95) hide show
  1. package/README.md +225 -17
  2. package/dist/{ai-Bk3LLnit.js → ai-Ce3PtWFW.js} +160 -29
  3. package/dist/ai-nmHdzjCM.d.ts +162 -0
  4. package/dist/ai.d.ts +2 -85
  5. package/dist/ai.js +1 -1
  6. package/dist/asset-registry-CaG9b7tf.js +19 -0
  7. package/dist/cloudflare.d.ts +18 -0
  8. package/dist/cloudflare.js +2 -0
  9. package/dist/collections/client.d.ts +39 -0
  10. package/dist/collections/client.js +137 -0
  11. package/dist/collections.d.ts +59 -0
  12. package/dist/collections.js +159 -0
  13. package/dist/config-3I1BnsdO.d.ts +28 -0
  14. package/dist/config-CDoyls2X.js +30 -0
  15. package/dist/config-CZLO0m9h.js +7811 -0
  16. package/dist/file-CHfsZpso.js +23 -0
  17. package/dist/{files-DbsIjBya.js → files-QRV55OCx.js} +6 -5
  18. package/dist/github-CfA5vpJ5.js +189 -0
  19. package/dist/glob-D0vD_wRY.js +17 -0
  20. package/dist/host-CAnbugpI.js +370 -0
  21. package/dist/hosted-C1-tTTTf.js +581 -0
  22. package/dist/{providers/vercel/blob-store.js → hosted-vercel-blob-CWBILDVo.js} +100 -19
  23. package/dist/hosted-vercel-blob.d.ts +15 -0
  24. package/dist/hosted-vercel-blob.js +2 -0
  25. package/dist/hosted.d.ts +18 -0
  26. package/dist/hosted.js +2 -0
  27. package/dist/index.d.ts +129 -102
  28. package/dist/index.js +477 -599
  29. package/dist/lifecycle-BYoa9hVb.js +176 -0
  30. package/dist/loader.d.ts +1 -1
  31. package/dist/loader.js +1 -1
  32. package/dist/mountx.d.ts +10 -0
  33. package/dist/mountx.js +143 -0
  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-C3_elpEh.js} +142 -37
  40. package/dist/providers/github/store.d.ts +6 -0
  41. package/dist/providers/github/store.js +2 -0
  42. package/dist/publish.d.ts +3 -2
  43. package/dist/publish.js +48 -142
  44. package/dist/{registry-D4Qzq26I.d.ts → registry-BIQVCBWI.d.ts} +3 -2
  45. package/dist/registry-CqyDTW9Y.js +74 -0
  46. package/dist/request-execution-u9mgUXKX.js +80 -0
  47. package/dist/runtime/assets.d.ts +2 -1
  48. package/dist/runtime/assets.js +5 -5
  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 -21
  52. package/dist/runtime/state.js +7 -4
  53. package/dist/runtime/workspace.d.ts +2 -0
  54. package/dist/runtime/workspace.js +2 -0
  55. package/dist/runtime-options-BsPSv5O7.js +13 -0
  56. package/dist/runtime.d.ts +38 -0
  57. package/dist/runtime.js +626 -0
  58. package/dist/{search-DtaEyjpO.js → search-C4REyHj9.js} +2 -2
  59. package/dist/server.d.ts +65 -0
  60. package/dist/server.js +355 -0
  61. package/dist/shared-jfogBrd5.js +273 -0
  62. package/dist/source-metadata.d.ts +2 -0
  63. package/dist/source-metadata.js +2 -0
  64. package/dist/state-TTqa3x3Y.d.ts +25 -0
  65. package/dist/store-Bs1SLh55.js +414 -0
  66. package/dist/sync-DiuDmSGk.js +269 -0
  67. package/dist/target-D4Bqb1eH.js +11 -0
  68. package/dist/test.d.ts +1 -1
  69. package/dist/test.js +1 -1
  70. package/dist/types-60Yn149G.d.ts +612 -0
  71. package/dist/use-CUFSnFCS.d.ts +86 -0
  72. package/dist/use-CsV3oIxH.js +336 -0
  73. package/dist/vite-tbfDxtlu.js +2191 -0
  74. package/dist/vite.d.ts +33 -5
  75. package/dist/vite.js +2 -131
  76. package/dist/workspace-66SKyiec.d.ts +6 -0
  77. package/dist/workspace-C4k92Ow8.js +1460 -0
  78. package/package.json +143 -62
  79. package/dist/asset-registry-CMuQbyvl.js +0 -14
  80. package/dist/cloudflare-env-DL94Uvpz.js +0 -12
  81. package/dist/config-CvS-7sre.js +0 -49
  82. package/dist/errors-BUL8SoFS.js +0 -21
  83. package/dist/lifecycle-uD82JeGh.js +0 -92
  84. package/dist/module-8LZUMEXC.js +0 -922
  85. package/dist/path-BVv9OXhg.js +0 -63
  86. package/dist/providers/cloudflare/artifacts-store.d.ts +0 -6
  87. package/dist/providers/cloudflare/artifacts-store.js +0 -384
  88. package/dist/providers/vercel/blob-store.d.ts +0 -6
  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/utils-BtAm_K5P.js +0 -51
  95. /package/dist/{chunk-DrSxFLj_.js → chunk-8H4AJuhK.js} +0 -0
package/README.md CHANGED
@@ -4,7 +4,6 @@
4
4
  <a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/badge/ViteHub-vitehub.dev-646cff?style=flat-square"></a>
5
5
  <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-ready-3178c6?style=flat-square">
6
6
  <img alt="Vite" src="https://img.shields.io/badge/Vite-discovery-646cff?style=flat-square">
7
- <img alt="Nitro" src="https://img.shields.io/badge/Nitro-runtime-00dc82?style=flat-square">
8
7
  </p>
9
8
 
10
9
  `@vite-hub/workspace` gives agents and server code a file-system context they can read, diff, and, when opened in write mode, update.
@@ -12,9 +11,12 @@
12
11
  ## Install
13
12
 
14
13
  ```sh
15
- pnpm add @vite-hub/workspace
14
+ pnpm add @vite-hub/workspace vite nitro h3
15
+ pnpm add -D typescript @types/node
16
16
  ```
17
17
 
18
+ Use `skipLibCheck: true` in app TypeScript configs while ViteHub depends on runtime packages with ambient provider declarations.
19
+
18
20
  ## Minimal API
19
21
 
20
22
  ```text
@@ -23,14 +25,15 @@ server/
23
25
  docs/
24
26
  README.md
25
27
  config.ts
26
- api/
27
- docs.get.ts
28
+ routes/
29
+ docs.get.ts
30
+ nitro.config.ts
28
31
  vite.config.ts
29
32
  ```
30
33
 
31
34
  ```ts
32
35
  // server/workspaces/docs/config.ts
33
- import { defineWorkspace, source } from "@vite-hub/workspace"
36
+ import { defineWorkspace, file, github } from "@vite-hub/workspace"
34
37
 
35
38
  export default defineWorkspace({
36
39
  store: {
@@ -38,36 +41,204 @@ export default defineWorkspace({
38
41
  root: ".vitehub/workspaces/docs",
39
42
  },
40
43
  sources: {
41
- readme: source.file("README.md"),
42
- vitehubDocs: source.github({
44
+ readme: file({ path: "README.md", sync: true }),
45
+ vitehubDocs: github({
43
46
  repo: "vite-hub/vitehub",
44
47
  root: "docs/content/docs",
48
+ instructions: "Use this source for public ViteHub documentation.",
45
49
  }),
46
- guide: source.file({
50
+ guide: file({
47
51
  workspacePath: "guide.md",
48
52
  content: "# Guide\n",
53
+ instructions: "Use this source for local guide notes.",
49
54
  }),
50
55
  },
51
56
  })
52
57
  ```
53
58
 
54
59
  ```ts
55
- // server/api/docs.get.ts
60
+ // routes/docs.get.ts
56
61
  import { useWorkspace } from "@vite-hub/workspace"
57
62
  import { defineEventHandler } from "h3"
58
63
 
59
64
  export default defineEventHandler(async () => {
60
65
  const workspace = useWorkspace("docs", { mode: "write" })
61
-
62
- await workspace.fs.writeFile("generated/notes.md", "Generated by ViteHub\n")
66
+ const sync = await workspace.sync({ sources: "all", details: "paths" })
63
67
 
64
68
  return {
69
+ sync,
65
70
  files: await workspace.fs.glob("**/*.md"),
66
- diff: await workspace.diff(),
71
+ readme: await workspace.fs.readFile("README.md", { encoding: "utf8" }),
72
+ }
73
+ })
74
+ ```
75
+
76
+ Serve a constrained Workspace subtree without custom route plumbing:
77
+
78
+ ```ts
79
+ // server/api/data/[...path].get.ts
80
+ import { defineWorkspaceFileHandler } from "@vite-hub/workspace/server"
81
+
82
+ export default defineWorkspaceFileHandler({
83
+ workspace: "docs",
84
+ root: "data",
85
+ allow: ["data/**/*.json", "data/**/*.md"],
86
+ cacheControl: "public, max-age=60",
87
+ })
88
+ ```
89
+
90
+ ## JSON collections
91
+
92
+ Query a generated JSON-object array without sending the complete index to the browser. The handler keeps filter, search, projection, sort, facet, and item lookup fields under server control, and every list response is capped by `maxLimit`.
93
+
94
+ ```ts
95
+ // server/api/articles.get.ts
96
+ import { defineWorkspaceCollectionHandler } from "@vite-hub/workspace/server"
97
+
98
+ export default defineWorkspaceCollectionHandler({
99
+ facets: ["category"],
100
+ filters: ["category", "authors.name"],
101
+ item: { key: "slug" },
102
+ maxLimit: 100,
103
+ path: "data/articles.json",
104
+ searchFields: ["title", "summary"],
105
+ select: ["slug", "title", "category"],
106
+ sort: { field: "title", direction: "asc" },
107
+ workspace: "content",
108
+ })
109
+ ```
110
+
111
+ Nuxt auto-imports the Vue composables when this module is installed. Plain Vue apps can import them directly from `@vite-hub/workspace/collections/client`.
112
+ Default immediate requests start during browser setup so relative endpoints do not escape Nuxt's server request context. Inject `request` and call `refresh()` when an application needs SSR loading.
113
+
114
+ ```ts
115
+ const articles = useWorkspaceCollection("/api/articles", {
116
+ limit: 25,
117
+ query: computed(() => ({
118
+ "filter.category": selectedCategory.value || undefined,
119
+ search: search.value || undefined,
120
+ })),
121
+ })
122
+
123
+ const article = useWorkspaceCollectionItem("/api/articles", selectedSlug)
124
+ ```
125
+
126
+ Use `empty.<field>=true` to filter for records without scalar values at an allowed field.
127
+
128
+ Collection queries parse the JSON array in the server runtime. Use this for deliberately small generated indexes; use a database when the server cannot reasonably hold and query the full source array in memory.
129
+
130
+ ```ts
131
+ // nitro.config.ts
132
+ import { createWorkspaceNitroConfig } from "@vite-hub/workspace/nitro"
133
+
134
+ export default createWorkspaceNitroConfig()
135
+ ```
136
+
137
+ ```ts
138
+ // vite.config.ts
139
+ import { hubWorkspace } from "@vite-hub/workspace/vite"
140
+ import { defineConfig } from "vite"
141
+
142
+ export default defineConfig({
143
+ plugins: [hubWorkspace()],
144
+ })
145
+ ```
146
+
147
+ Use named Workspace Source Binding helpers such as `file()` and `github()`. The lower-level Source registry lives in `@vite-hub/source`; install and import it directly only when you use that package's registry APIs.
148
+
149
+ ## Box sessions
150
+
151
+ Workspace definitions are runtime-free. To run generated code, open a [`@vite-hub/box`](../box/README.md) session and pass it to `workspace.startSession({ host: boxSession })`. Workspace materializes files into the host and still owns diff, commit, and rollback; closing without commit restores the host tree from authoritative Workspace state. Box owns execution and the host lifecycle.
152
+
153
+ Use `startSession({ attach: true, host })` only when another integration already owns the live materialized tree. Attached Sessions preserve that baseline without rematerializing the tree and roll back only their own uncommitted changes on close.
154
+
155
+ ## MountX projection
156
+
157
+ Use the `@vite-hub/workspace/mountx` integration when an Agent, editor, CLI, or VM needs a real filesystem instead of Workspace methods. The adapter keeps Workspace Session diff and commit semantics in ViteHub while MountX owns the host transport.
158
+
159
+ Install MountX directly before importing its transport entry points:
160
+
161
+ ```bash
162
+ pnpm add mountx@0.0.2
163
+ ```
164
+
165
+ ```ts
166
+ import { createWorkspaceDriver } from "@vite-hub/workspace/mountx"
167
+ import { mount } from "mountx/auto"
168
+
169
+ const session = await workspace.startSession()
170
+
171
+ try {
172
+ const mounted = await mount(createWorkspaceDriver(session), "/tmp/vitehub-docs")
173
+
174
+ try {
175
+ // Programs can now use /tmp/vitehub-docs as an ordinary directory.
176
+ }
177
+ finally {
178
+ await mounted.unmount()
67
179
  }
180
+
181
+ await session.commit({ message: "accept projected changes" })
182
+ }
183
+ finally {
184
+ await session.close()
185
+ }
186
+ ```
187
+
188
+ The same driver works with MountX's 9P and NFSv4.1 servers for Linux guests, or its S3 gateway for S3-compatible clients. Use `{ readOnly: true }` when the consumer only needs inspection. The adapter uses MountX's unstorage driver, so it does not project or persist empty directories, and filenames cannot contain `:`, `?`, or end in `$`. Renames use copy then delete and are not atomic. Executable Git files retain their execute bits; Git symlinks are rejected because the unstorage driver cannot preserve symlink semantics. MountX is still alpha and unaudited, so keep network transports loopback-only unless the surrounding sandbox or network is the explicit security boundary.
189
+
190
+ Harness-backed Agents use the Workspace Package to prepare Harness Workspace Sessions for `defineAgent({ driver: { harness }, workspace })`. The Agent Package keeps the harness inside the Agent Driver boundary, Capabilities keep tools and Skills opt-in, and Workspace owns materializing the selected Workspace Scope plus write-mode sync back through Workspace rules.
191
+
192
+ ## Vite Integration
193
+
194
+ Use `hubWorkspace()` in Vite to discover workspace definitions, emit the workspace manifest for local development, and make the runtime store available to server code.
195
+
196
+ ## Publishing current state
197
+
198
+ `workspace.snapshot()` creates a durable Store snapshot, then runs every configured Workspace publisher. Use `workspace.publish()` when the current Store contents should be published without advancing the Store's snapshot history:
199
+
200
+ ```ts
201
+ const workspace = useWorkspace("docs", { mode: "write" })
202
+
203
+ await workspace.publish({ name: "chore: publish docs" })
204
+ ```
205
+
206
+ Publishers receive a transient snapshot-shaped view of the current Store entries. `PublishContext.durable` is `false` for this direct lifecycle and `true` for snapshot-driven publication. Repeated publication remains a no-op when a publisher, such as the GitHub publisher, already has the same content.
207
+
208
+ A GitHub publisher cannot publish directly to the repository and branch backing the active GitHub Store because that would move the Store branch behind its loaded baseline. Use `workspace.snapshot()` for that branch, or configure the publisher with a different repository or branch.
209
+
210
+ ## Hosted Cloudflare runtime
211
+
212
+ Nuxt apps can install the Workspace Nuxt module so hosted Workspace runtime setup is generated by the Vite Integration and merged into Nuxt's top-level Nitro config:
213
+
214
+ ```ts
215
+ export default defineNuxtConfig({
216
+ modules: ["@vite-hub/workspace/nuxt"],
217
+ vite: {
218
+ workspace: {
219
+ store: {
220
+ provider: "github",
221
+ repository: "owner/repo",
222
+ branch: "main",
223
+ root: ".vitehub/workspaces/docs",
224
+ },
225
+ },
226
+ },
68
227
  })
69
228
  ```
70
229
 
230
+ Cloudflare-hosted apps outside Nuxt can install the public runtime setup instead of importing internal runtime state or store adapters:
231
+
232
+ ```ts
233
+ import { configureCloudflareWorkspaceRuntime } from "@vite-hub/workspace/cloudflare"
234
+
235
+ configureCloudflareWorkspaceRuntime()
236
+ ```
237
+
238
+ `useWorkspace()` will then resolve `cloudflare-artifacts` Workspace Stores from the configured runtime store or the Workspace Definition's `store` option.
239
+
240
+ Select Cloudflare Artifacts explicitly when a Cloudflare Worker needs durable, versioned Workspace state:
241
+
71
242
  ```ts
72
243
  // vite.config.ts
73
244
  import { hubWorkspace } from "@vite-hub/workspace/vite"
@@ -75,17 +246,54 @@ import { defineConfig } from "vite"
75
246
 
76
247
  export default defineConfig({
77
248
  plugins: [hubWorkspace()],
249
+ workspace: {
250
+ store: {
251
+ provider: "cloudflare-artifacts",
252
+ binding: "WORKSPACE_ARTIFACTS",
253
+ namespace: "vitehub",
254
+ },
255
+ },
256
+ })
257
+ ```
258
+
259
+ The Vite Integration writes matching module-level and discovered definition-level Artifacts bindings into generated Cloudflare Provider Output. Each named Workspace uses its own repository by default, and a successful `workspace.snapshot()` pushes a Git commit whose SHA is the snapshot id. The Worker adapter keeps its checkout in isolate memory, so use it for deliberately small Workspaces. Cloudflare Artifacts is currently a closed beta and is not available on Workers Free; Cloudflare hosting therefore continues to default to the `memory` Store.
260
+
261
+ Artifacts repositories are private Git storage, not public attachment hosting. Use `@vite-hub/blob` with R2 or another Blob provider when an Agent needs a stable public delivery URL.
262
+
263
+ ## GitHub-backed persistence
264
+
265
+ Use the GitHub Workspace Store when a hosted runtime needs durable Workspace file-tree state without a provider-specific artifact store:
266
+
267
+ ```ts
268
+ export default defineWorkspace({
269
+ store: {
270
+ provider: "github",
271
+ repository: "owner/repo",
272
+ branch: "main",
273
+ root: ".vitehub/workspaces/<workspace>",
274
+ },
78
275
  })
79
276
  ```
80
277
 
81
- ## Sandbox sessions
278
+ Set `WORKSPACE_GITHUB_TOKEN`, `VITEHUB_WORKSPACE_GITHUB_TOKEN`, `GITHUB_TOKEN`, or a `GITHUB_TOKEN` runtime binding with permission to read and write the repository contents. Reads and snapshots call the GitHub API, so this Store trades provider independence for GitHub API latency and rate limits. `workspace.snapshot()` writes changed Workspace Store files as a GitHub commit. If the target branch moves after the Workspace Store loaded local changes, snapshot fails with a conflict so the caller can retry from a fresh Workspace Store.
279
+
280
+ Publish a Workspace snapshot into an existing GitHub repository with the GitHub publisher:
82
281
 
83
- Need the workspace to run generated code instead of only reading and writing files? Pair it with [`@vite-hub/sandbox`](../sandbox/README.md) so sessions can execute inside an isolated provider runtime.
282
+ ```ts
283
+ import { github } from "@vite-hub/workspace/publish"
84
284
 
85
- ## Vite and Nitro
285
+ export default defineWorkspace({
286
+ publish: [github({
287
+ repository: "owner/repo",
288
+ branch: "main",
289
+ root: "generated/docs",
290
+ deleteUntracked: false,
291
+ })],
292
+ })
293
+ ```
86
294
 
87
- Nitro workspaces live under `server/workspaces/**`; an agent can also colocate one at `server/agents/<name>/config.ts` by adding `workspace` to its `defineAgent()` call. Vite emits the workspace manifest for local development, and `@vite-hub/workspace/nitro` registers the runtime store.
295
+ By default, the publisher treats `root` as an exact mirror and deletes remote paths that are absent from the Workspace snapshot. Set `deleteUntracked: false` when the publisher owns only part of `root`; Workspace files are still created and updated, while every remote-only path remains on GitHub, including files from earlier snapshots.
88
296
 
89
- Built on [`@vite-hub/source`](../source/README.md), [`@vite-hub/shell`](../shell/README.md), [files-sdk](https://files-sdk.dev/), and [isomorphic-git](https://isomorphic-git.org/).
297
+ Built on [`@vite-hub/source`](../source/README.md) and [isomorphic-git](https://isomorphic-git.org/). Shell-backed Workspace tools load `@vite-hub/shell` only when the shell tool executes.
90
298
 
91
299
  Learn more at [vitehub.dev](https://vitehub.dev).
@@ -1,19 +1,19 @@
1
- import { t as WorkspaceError } from "./errors-BUL8SoFS.js";
2
- import { cleanWorkspaceShellPath, createReadonlyWorkspaceFs, runWorkspaceInspectionCommand } from "@vite-hub/shell/workspace";
1
+ import { f as isWorkspaceError, o as normalizeSafeWorkspacePath, p as workspaceError } from "./path-CNI6wKIU.js";
2
+ import { r as getWorkspaceSourceRequestExecution } from "./request-execution-u9mgUXKX.js";
3
3
  import { posix } from "node:path";
4
4
  //#region src/fs-ops.ts
5
5
  async function ensureMissingOrReplaceable(workspace, path, overwrite = false) {
6
6
  if (!await workspace.exists(path)) return;
7
- if (!overwrite) throw new WorkspaceError(`[vitehub] Workspace path already exists: ${path}.`);
7
+ if (!overwrite) throw workspaceError(`[vitehub] Workspace path already exists: ${path}.`);
8
8
  await workspace.rm(path, {
9
9
  recursive: true,
10
10
  force: true
11
11
  });
12
12
  }
13
13
  async function copyWorkspacePath(workspace, from, to, overwrite = false) {
14
- if (from === to) throw new WorkspaceError("[vitehub] Source and destination must be different.");
14
+ if (from === to) throw workspaceError("[vitehub] Source and destination must be different.");
15
15
  const source = await workspace.stat(from);
16
- if (source.type === "directory" && to.startsWith(`${from}/`)) throw new WorkspaceError("[vitehub] Destination cannot be nested inside the source directory.");
16
+ if (source.type === "directory" && to.startsWith(`${from}/`)) throw workspaceError("[vitehub] Destination cannot be nested inside the source directory.");
17
17
  await ensureMissingOrReplaceable(workspace, to, overwrite);
18
18
  if (source.type === "file") {
19
19
  const content = await workspace.readFile(from, { encoding: "binary" });
@@ -34,11 +34,47 @@ async function appendWorkspaceFile(workspace, path, content) {
34
34
  try {
35
35
  current = String(await workspace.readFile(path));
36
36
  } catch (error) {
37
- if (!(error instanceof WorkspaceError)) throw error;
37
+ if (!isWorkspaceError(error)) throw error;
38
38
  }
39
39
  await workspace.writeFile(path, `${current}${content}`);
40
40
  }
41
41
  //#endregion
42
+ //#region src/runtime/dependency-loaders.ts
43
+ const shellWorkspaceSpecifier = "@vite-hub/shell/workspace";
44
+ const defaultWorkspaceDependencyRuntimeLoaders = { shellWorkspace: () => import(
45
+ /* @vite-ignore */
46
+ shellWorkspaceSpecifier
47
+ ) };
48
+ function workspaceDependencyRuntimeLoadersKey() {
49
+ return Symbol.for("vitehub.workspace.dependencyRuntimeLoaders");
50
+ }
51
+ function workspaceDependencyRuntimeLoadersGlobal() {
52
+ return globalThis;
53
+ }
54
+ function setWorkspaceDependencyRuntimeLoaders(loaders) {
55
+ workspaceDependencyRuntimeLoadersGlobal()[workspaceDependencyRuntimeLoadersKey()] = loaders ? {
56
+ ...defaultWorkspaceDependencyRuntimeLoaders,
57
+ ...loaders
58
+ } : void 0;
59
+ }
60
+ function getWorkspaceDependencyRuntimeLoaders() {
61
+ return workspaceDependencyRuntimeLoadersGlobal()[workspaceDependencyRuntimeLoadersKey()] ?? defaultWorkspaceDependencyRuntimeLoaders;
62
+ }
63
+ async function loadWorkspaceShellModule() {
64
+ try {
65
+ return await getWorkspaceDependencyRuntimeLoaders().shellWorkspace();
66
+ } catch (error) {
67
+ if (isMissingWorkspaceShellError(error)) throw workspaceError("[vitehub] Install @vite-hub/shell to use Workspace Tools shell commands.", { cause: error });
68
+ throw error;
69
+ }
70
+ }
71
+ function isMissingWorkspaceShellError(error) {
72
+ if (!(error instanceof Error)) return false;
73
+ const code = error.code;
74
+ if (code !== "ERR_MODULE_NOT_FOUND" && code !== "MODULE_NOT_FOUND") return false;
75
+ return error.message.includes("Cannot find package '@vite-hub/shell'") || error.message.includes("Cannot find module '@vite-hub/shell'") || error.message.includes("Cannot find module '@vite-hub/shell/workspace'") || error.message.includes("tried to access @vite-hub/shell") && (error.message.includes("isn't declared") || error.message.includes("isn't provided"));
76
+ }
77
+ //#endregion
42
78
  //#region src/ai.ts
43
79
  const defaultMaxOutputLength = 3e4;
44
80
  const workspaceMountPoint = "/workspace";
@@ -61,6 +97,73 @@ function tool(definition) {
61
97
  function isWorkspace(input) {
62
98
  return "sync" in input;
63
99
  }
100
+ function getWorkspaceSessionStarter(input) {
101
+ return typeof input.startSession === "function" ? input : void 0;
102
+ }
103
+ function createWorkspaceSessionShellProvider(starter) {
104
+ return {
105
+ boundary: {
106
+ cwd: true,
107
+ env: true,
108
+ filesystem: {
109
+ mountPoint: workspaceMountPoint,
110
+ writable: true
111
+ },
112
+ network: "unknown",
113
+ processes: {
114
+ background: false,
115
+ interactive: false
116
+ },
117
+ streaming: false,
118
+ timeout: {
119
+ enforcedBy: "provider",
120
+ supported: true
121
+ }
122
+ },
123
+ async exec(command, execOptions = {}) {
124
+ const session = await starter.startSession({ paths: execOptions.workspacePaths });
125
+ let observation;
126
+ try {
127
+ const result = await session.exec("sh", ["-lc", command], {
128
+ cwd: execOptions.cwd || workspaceMountPoint,
129
+ env: execOptions.env,
130
+ timeout: execOptions.timeout
131
+ });
132
+ execOptions.onStdout?.(result.stdout);
133
+ execOptions.onStderr?.(result.stderr);
134
+ const timedOut = result.exitCode === 124 && /timed out/i.test(result.stderr);
135
+ observation = {
136
+ command,
137
+ cwd: execOptions.cwd,
138
+ event: timedOut ? "command_timed_out" : "command_finished",
139
+ exitCode: result.exitCode,
140
+ stderr: result.stderr,
141
+ stdout: result.stdout,
142
+ timedOut
143
+ };
144
+ } catch (error) {
145
+ try {
146
+ await session.close();
147
+ } catch (closeError) {
148
+ throw new AggregateError([error, closeError], "[vitehub] Workspace shell execution failed and session cleanup also failed.");
149
+ }
150
+ throw error;
151
+ }
152
+ await session.close();
153
+ return observation;
154
+ }
155
+ };
156
+ }
157
+ async function resolveExecutionProvider(provider) {
158
+ return typeof provider === "function" ? await provider() : provider;
159
+ }
160
+ function isUnavailableWorkspaceSession(error) {
161
+ const message = error instanceof Error ? error.message : String(error);
162
+ return message.includes("Workspace exec requires an executable runtime") || message.includes("Workspace exec requires a Box session host") || message.includes("Workspace") && message.includes("is not registered");
163
+ }
164
+ function cleanWorkspaceShellPath(path) {
165
+ return normalizeSafeWorkspacePath(path.replace(/^\/workspace(?:\/|$)/, ""), { allowEmpty: true });
166
+ }
64
167
  function cleanMutationPath(path) {
65
168
  const normalized = cleanWorkspaceShellPath(path);
66
169
  if (!normalized) throw new Error("[vitehub] Workspace root is not a valid mutation target.");
@@ -99,34 +202,61 @@ function shellCommandsFor(operations) {
99
202
  if (operations.search) commands.push("grep", "rg");
100
203
  return commands;
101
204
  }
102
- function describeShellCommands(commands) {
205
+ function describeShellCommands(commands, options = {}) {
103
206
  const supported = new Set(commands);
207
+ const available = [
208
+ supported.has("pwd") && "`pwd`",
209
+ supported.has("ls") && "`ls`",
210
+ supported.has("find") && "`find`",
211
+ (supported.has("rg") || supported.has("grep")) && "`rg [-i] pattern [path...]`, `grep -ri pattern [path...]`",
212
+ supported.has("cat") && "`cat`",
213
+ supported.has("head") && "`head`",
214
+ supported.has("tail") && "`tail`",
215
+ supported.has("wc") && "`wc`",
216
+ options.sourceRequests && "controlled `curl` for API-backed Sources listed under `.vitehub/sources/*.json`"
217
+ ].filter(Boolean);
218
+ const examples = [
219
+ supported.has("rg") && supported.has("head") && "`rg 'siff|PLC' ingestion forecasting-engine | head -n 20`",
220
+ supported.has("rg") && !supported.has("head") && "`rg 'siff|PLC' ingestion forecasting-engine`",
221
+ supported.has("find") && "`find ingestion -type f -name '*.sql'`",
222
+ supported.has("cat") && supported.has("head") && "`cat forecasting-engine/README.md | head -n 40`",
223
+ options.sourceRequests && "`curl --json '{\"region\":\"eu\"}' https://example.com/api/source`"
224
+ ].filter(Boolean);
104
225
  return [
105
- "Run a real Bash-compatible workspace shell command over files mounted at `/workspace`.",
106
- `Available workspace commands include: ${[
107
- supported.has("pwd") && "`pwd`",
108
- supported.has("ls") && "`ls`",
109
- supported.has("find") && "`find`",
110
- (supported.has("rg") || supported.has("grep")) && "`rg [-i] pattern [path...]`, `grep -ri pattern [path...]`",
111
- supported.has("cat") && "`cat`",
112
- supported.has("head") && "`head`",
113
- supported.has("tail") && "`tail`",
114
- supported.has("wc") && "`wc`"
115
- ].filter(Boolean).join(", ")}.`,
116
- "Pipes, redirects, chaining, quoted patterns, and multiline shell scripts are supported by the shell runtime.",
117
- "The workspace filesystem controls whether writes are allowed; read-only tools reject mutation commands at execution time.",
118
- "Do not use shell commands such as `echo` to compose assistant replies; answer conversational messages directly.",
119
- "Examples: `rg 'siff|PLC' ingestion forecasting-engine | head -n 20`; `find ingestion -type f -name '*.sql'`; `cat forecasting-engine/README.md | head -n 40`."
120
- ].join(" ");
226
+ "Inspect files in `/workspace` with a Bash-compatible shell.",
227
+ `Use these commands: ${available.join(", ")}.`,
228
+ options.sourceRequests && "For controlled `curl`, inspect the matching `.vitehub/sources/<sourceKey>.json` descriptor first; ViteHub validates the request against the Source Request Shape and injects Source credentials.",
229
+ "Pipes, redirects, chaining, quoted patterns, and multiline scripts are supported.",
230
+ "Skip unsupported helpers such as `xargs`, `awk`, `sed`, `sort`, `cut`, or `python`.",
231
+ "Answer conversational messages directly; do not use shell commands such as `echo` to compose replies.",
232
+ examples.length && `Examples: ${examples.join("; ")}.`
233
+ ].filter(Boolean).join(" ");
121
234
  }
122
235
  async function runShellCommand(input, command, options) {
123
- return await runWorkspaceInspectionCommand(input, command, {
236
+ const networkGrants = getWorkspaceSourceRequestExecution(input);
237
+ const { createReadonlyWorkspaceFs, runWorkspaceInspectionCommand } = await loadWorkspaceShellModule();
238
+ const inspectionOptions = {
124
239
  broadSearchPaths: options.broadSearchPaths,
125
- commands: options.commands,
240
+ commands: networkGrants ? [...options.commands, "curl"] : options.commands,
126
241
  cwd: options.cwd,
127
242
  fs: createReadonlyWorkspaceFs(input),
128
243
  maxOutputLength: options.maxOutputLength,
244
+ networkGrants,
129
245
  timeout: options.timeout
246
+ };
247
+ const starter = getWorkspaceSessionStarter(input);
248
+ if (starter) try {
249
+ return await runWorkspaceInspectionCommand(input, command, {
250
+ ...inspectionOptions,
251
+ provider: createWorkspaceSessionShellProvider(starter)
252
+ });
253
+ } catch (error) {
254
+ if (!isUnavailableWorkspaceSession(error)) throw error;
255
+ }
256
+ const provider = await resolveExecutionProvider(options.executionProvider);
257
+ return await runWorkspaceInspectionCommand(input, command, {
258
+ ...inspectionOptions,
259
+ ...provider ? { provider } : {}
130
260
  });
131
261
  }
132
262
  function sizeOf(content) {
@@ -288,6 +418,7 @@ function createWorkspaceTools(input, options = {}) {
288
418
  broadSearchPaths: options.broadSearchPaths || [],
289
419
  commands: shellCommandsFor(resolveReadOperations(options.operations)),
290
420
  cwd: options.cwd || workspaceMountPoint,
421
+ executionProvider: options.executionProvider,
291
422
  materialize: resolveReadOperations(options.operations).materialize,
292
423
  maxShellCalls: options.maxShellCalls,
293
424
  maxOutputLength: options.maxOutputLength || defaultMaxOutputLength,
@@ -297,10 +428,10 @@ function createWorkspaceTools(input, options = {}) {
297
428
  let shellCalls = 0;
298
429
  const writeEnabled = Object.values(resolved.write).some(Boolean);
299
430
  if (!resolved.commands.length && !resolved.materialize && !writeEnabled) throw new TypeError("[vitehub] createWorkspaceTools requires at least one enabled workspace operation.");
300
- if (writeEnabled && !isWorkspace(input)) throw new TypeError("[vitehub] Write operations require a mutable Workspace. Use useWorkspace(name, { mode: \"write\" }).tools.write().");
431
+ if (writeEnabled && !isWorkspace(input)) throw new TypeError("[vitehub] Write operations require a mutable Workspace. A useWorkspace(name, { mode: \"write\" }).tools.write() call provides one.");
301
432
  const result = {};
302
433
  if (resolved.commands.length) result.shell = tool({
303
- description: describeShellCommands(resolved.commands),
434
+ description: describeShellCommands(resolved.commands, { sourceRequests: Boolean(getWorkspaceSourceRequestExecution(input)) }),
304
435
  inputSchema: jsonSchema({
305
436
  additionalProperties: false,
306
437
  properties: { command: {
@@ -316,7 +447,7 @@ function createWorkspaceTools(input, options = {}) {
316
447
  cwd: resolved.cwd,
317
448
  event: "policy_denied",
318
449
  exitCode: 126,
319
- stderr: `[vitehub] Workspace shell command budget exhausted after ${resolved.maxShellCalls} calls. Answer from the evidence already collected instead of running more shell commands.\n`,
450
+ stderr: `[vitehub] Workspace shell command budget exhausted after ${resolved.maxShellCalls} calls. The Workspace Tools shell call budget is exhausted for this run.\n`,
320
451
  stdout: ""
321
452
  };
322
453
  shellCalls += 1;
@@ -349,4 +480,4 @@ function createWorkspaceTools(input, options = {}) {
349
480
  return result;
350
481
  }
351
482
  //#endregion
352
- export { appendWorkspaceFile as n, copyWorkspacePath as r, createWorkspaceTools as t };
483
+ export { copyWorkspacePath as a, appendWorkspaceFile as i, getWorkspaceDependencyRuntimeLoaders as n, setWorkspaceDependencyRuntimeLoaders as r, createWorkspaceTools as t };