@vite-hub/workspace 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +190 -17
  2. package/dist/{ai-Bk3LLnit.js → ai-Cztw4eLk.js} +149 -29
  3. package/dist/ai-hFdsvDHC.d.ts +162 -0
  4. package/dist/ai.d.ts +2 -85
  5. package/dist/ai.js +1 -1
  6. package/dist/artifacts-store-BAV9jZpd.js +555 -0
  7. package/dist/asset-registry-CaG9b7tf.js +19 -0
  8. package/dist/cli.d.ts +31 -0
  9. package/dist/cli.js +303 -0
  10. package/dist/cloudflare-env-CKxUs2fa.js +20 -0
  11. package/dist/cloudflare.d.ts +16 -0
  12. package/dist/cloudflare.js +3 -0
  13. package/dist/collections/client.d.ts +39 -0
  14. package/dist/collections/client.js +137 -0
  15. package/dist/collections.d.ts +59 -0
  16. package/dist/collections.js +159 -0
  17. package/dist/config--r5unwPc.js +7811 -0
  18. package/dist/config-Ca5DM8fF.d.ts +28 -0
  19. package/dist/config-DCQ6y30R.js +30 -0
  20. package/dist/file-B2q9NE18.js +24 -0
  21. package/dist/{files-DbsIjBya.js → files-xy0le-_U.js} +6 -5
  22. package/dist/github-lIO6-2sH.js +194 -0
  23. package/dist/glob-DeH0dzZX.js +23 -0
  24. package/dist/host-I-_vDs05.js +370 -0
  25. package/dist/hosted-vercel-blob.d.ts +15 -0
  26. package/dist/hosted-vercel-blob.js +26 -0
  27. package/dist/hosted.d.ts +18 -0
  28. package/dist/hosted.js +30 -0
  29. package/dist/index.d.ts +137 -102
  30. package/dist/index.js +479 -594
  31. package/dist/lifecycle-Lhk3dAMt.js +176 -0
  32. package/dist/loader.d.ts +1 -1
  33. package/dist/loader.js +1 -1
  34. package/dist/nitro.d.ts +2 -31
  35. package/dist/nitro.js +2 -2
  36. package/dist/nuxt.d.ts +26 -0
  37. package/dist/nuxt.js +36 -0
  38. package/dist/path-CNI6wKIU.js +115 -0
  39. package/dist/{provider-BZuKAV4e.js → provider-CeQciesl.js} +142 -37
  40. package/dist/providers/cloudflare/artifacts-store.d.ts +1 -1
  41. package/dist/providers/cloudflare/artifacts-store.js +1 -383
  42. package/dist/providers/github/store.d.ts +6 -0
  43. package/dist/providers/github/store.js +362 -0
  44. package/dist/providers/vercel/blob-store.d.ts +1 -1
  45. package/dist/providers/vercel/blob-store.js +77 -18
  46. package/dist/publish.d.ts +3 -2
  47. package/dist/publish.js +48 -142
  48. package/dist/registry-C7DMdBXN.js +74 -0
  49. package/dist/{registry-D4Qzq26I.d.ts → registry-CoC9JxVt.d.ts} +3 -2
  50. package/dist/request-execution-C8qRcReq.js +80 -0
  51. package/dist/runtime/assets.d.ts +2 -1
  52. package/dist/runtime/assets.js +5 -5
  53. package/dist/runtime/empty-assets-registry.d.ts +1 -1
  54. package/dist/runtime/empty-registry.d.ts +1 -1
  55. package/dist/runtime/state.d.ts +4 -21
  56. package/dist/runtime/state.js +7 -4
  57. package/dist/runtime/workspace.d.ts +2 -0
  58. package/dist/runtime/workspace.js +2 -0
  59. package/dist/runtime.d.ts +38 -0
  60. package/dist/runtime.js +643 -0
  61. package/dist/{search-DtaEyjpO.js → search-C4REyHj9.js} +2 -2
  62. package/dist/server.d.ts +65 -0
  63. package/dist/server.js +355 -0
  64. package/dist/shared-BRycRSbo.js +255 -0
  65. package/dist/source-metadata.d.ts +2 -0
  66. package/dist/source-metadata.js +2 -0
  67. package/dist/state-DSAHEsq6.d.ts +25 -0
  68. package/dist/sync-DO42ypji.js +269 -0
  69. package/dist/target-D4Bqb1eH.js +11 -0
  70. package/dist/test.d.ts +1 -1
  71. package/dist/test.js +1 -1
  72. package/dist/types-DHkae7Cb.d.ts +628 -0
  73. package/dist/use-D16tf8Ph.d.ts +86 -0
  74. package/dist/use-d_PlAdOu.js +353 -0
  75. package/dist/{utils-BtAm_K5P.js → utils-BPdaCyI6.js} +7 -3
  76. package/dist/vite-NWC9mFjI.js +1882 -0
  77. package/dist/vite.d.ts +33 -5
  78. package/dist/vite.js +2 -131
  79. package/dist/workspace-f2DBLmPZ.d.ts +6 -0
  80. package/dist/workspace-n4wBmdaM.js +1476 -0
  81. package/package.json +158 -62
  82. package/dist/asset-registry-CMuQbyvl.js +0 -14
  83. package/dist/cloudflare-env-DL94Uvpz.js +0 -12
  84. package/dist/config-CvS-7sre.js +0 -49
  85. package/dist/errors-BUL8SoFS.js +0 -21
  86. package/dist/lifecycle-uD82JeGh.js +0 -92
  87. package/dist/module-8LZUMEXC.js +0 -922
  88. package/dist/path-BVv9OXhg.js +0 -63
  89. package/dist/registry-Cnr0NoKv.js +0 -932
  90. package/dist/runtime/nitro-plugin.d.ts +0 -6
  91. package/dist/runtime/nitro-plugin.js +0 -14
  92. package/dist/sandbox-DtGXCWRq.js +0 -198
  93. package/dist/types-CwNcWTdt.d.ts +0 -378
  94. /package/dist/{chunk-DrSxFLj_.js → chunk-8H4AJuhK.js} +0 -0
package/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,99 @@ 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" }),
67
72
  }
68
73
  })
69
74
  ```
70
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
+
71
137
  ```ts
72
138
  // vite.config.ts
73
139
  import { hubWorkspace } from "@vite-hub/workspace/vite"
@@ -78,14 +144,121 @@ export default defineConfig({
78
144
  })
79
145
  ```
80
146
 
81
- ## Sandbox sessions
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
+ 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.
156
+
157
+ ## Vite Integration
158
+
159
+ Use `hubWorkspace()` in Vite to discover workspace definitions, emit the workspace manifest for local development, and make the runtime store available to server code.
160
+
161
+ ## Publishing current state
162
+
163
+ `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:
164
+
165
+ ```ts
166
+ const workspace = useWorkspace("docs", { mode: "write" })
167
+
168
+ await workspace.publish({ name: "chore: publish docs" })
169
+ ```
170
+
171
+ 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.
172
+
173
+ 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.
174
+
175
+ ## Hosted Cloudflare runtime
82
176
 
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.
177
+ 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:
84
178
 
85
- ## Vite and Nitro
179
+ ```ts
180
+ export default defineNuxtConfig({
181
+ modules: ["@vite-hub/workspace/nuxt"],
182
+ vite: {
183
+ workspace: {
184
+ store: {
185
+ provider: "github",
186
+ repository: "owner/repo",
187
+ branch: "main",
188
+ root: ".vitehub/workspaces/docs",
189
+ },
190
+ },
191
+ },
192
+ })
193
+ ```
194
+
195
+ Cloudflare-hosted apps outside Nuxt can install the public runtime setup instead of importing internal runtime state or store adapters:
196
+
197
+ ```ts
198
+ import { configureCloudflareWorkspaceRuntime } from "@vite-hub/workspace/cloudflare"
199
+
200
+ configureCloudflareWorkspaceRuntime()
201
+ ```
202
+
203
+ `useWorkspace()` will then resolve `cloudflare-artifacts` Workspace Stores from the configured runtime store or the Workspace Definition's `store` option.
204
+
205
+ Select Cloudflare Artifacts explicitly when a Cloudflare Worker needs durable, versioned Workspace state:
206
+
207
+ ```ts
208
+ // vite.config.ts
209
+ import { hubWorkspace } from "@vite-hub/workspace/vite"
210
+ import { defineConfig } from "vite"
211
+
212
+ export default defineConfig({
213
+ plugins: [hubWorkspace()],
214
+ workspace: {
215
+ store: {
216
+ provider: "cloudflare-artifacts",
217
+ binding: "WORKSPACE_ARTIFACTS",
218
+ namespace: "vitehub",
219
+ },
220
+ },
221
+ })
222
+ ```
223
+
224
+ 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.
225
+
226
+ 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.
227
+
228
+ ## GitHub-backed persistence
229
+
230
+ Use the GitHub Workspace Store when a hosted runtime needs durable Workspace file-tree state without a provider-specific artifact store:
231
+
232
+ ```ts
233
+ export default defineWorkspace({
234
+ store: {
235
+ provider: "github",
236
+ repository: "owner/repo",
237
+ branch: "main",
238
+ root: ".vitehub/workspaces/<workspace>",
239
+ },
240
+ })
241
+ ```
242
+
243
+ 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.
244
+
245
+ Publish a Workspace snapshot into an existing GitHub repository with the GitHub publisher:
246
+
247
+ ```ts
248
+ import { github } from "@vite-hub/workspace/publish"
249
+
250
+ export default defineWorkspace({
251
+ publish: [github({
252
+ repository: "owner/repo",
253
+ branch: "main",
254
+ root: "generated/docs",
255
+ deleteUntracked: false,
256
+ })],
257
+ })
258
+ ```
86
259
 
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.
260
+ 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
261
 
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/).
262
+ 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
263
 
91
264
  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-C8qRcReq.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,36 @@ 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
+ function loadWorkspaceShellModule() {
64
+ return getWorkspaceDependencyRuntimeLoaders().shellWorkspace();
65
+ }
66
+ //#endregion
42
67
  //#region src/ai.ts
43
68
  const defaultMaxOutputLength = 3e4;
44
69
  const workspaceMountPoint = "/workspace";
@@ -61,6 +86,73 @@ function tool(definition) {
61
86
  function isWorkspace(input) {
62
87
  return "sync" in input;
63
88
  }
89
+ function getWorkspaceSessionStarter(input) {
90
+ return typeof input.startSession === "function" ? input : void 0;
91
+ }
92
+ function createWorkspaceSessionShellProvider(starter) {
93
+ return {
94
+ boundary: {
95
+ cwd: true,
96
+ env: true,
97
+ filesystem: {
98
+ mountPoint: workspaceMountPoint,
99
+ writable: true
100
+ },
101
+ network: "unknown",
102
+ processes: {
103
+ background: false,
104
+ interactive: false
105
+ },
106
+ streaming: false,
107
+ timeout: {
108
+ enforcedBy: "provider",
109
+ supported: true
110
+ }
111
+ },
112
+ async exec(command, execOptions = {}) {
113
+ const session = await starter.startSession({ paths: execOptions.workspacePaths });
114
+ let observation;
115
+ try {
116
+ const result = await session.exec("sh", ["-lc", command], {
117
+ cwd: execOptions.cwd || workspaceMountPoint,
118
+ env: execOptions.env,
119
+ timeout: execOptions.timeout
120
+ });
121
+ execOptions.onStdout?.(result.stdout);
122
+ execOptions.onStderr?.(result.stderr);
123
+ const timedOut = result.exitCode === 124 && /timed out/i.test(result.stderr);
124
+ observation = {
125
+ command,
126
+ cwd: execOptions.cwd,
127
+ event: timedOut ? "command_timed_out" : "command_finished",
128
+ exitCode: result.exitCode,
129
+ stderr: result.stderr,
130
+ stdout: result.stdout,
131
+ timedOut
132
+ };
133
+ } catch (error) {
134
+ try {
135
+ await session.close();
136
+ } catch (closeError) {
137
+ throw new AggregateError([error, closeError], "[vitehub] Workspace shell execution failed and session cleanup also failed.");
138
+ }
139
+ throw error;
140
+ }
141
+ await session.close();
142
+ return observation;
143
+ }
144
+ };
145
+ }
146
+ async function resolveExecutionProvider(provider) {
147
+ return typeof provider === "function" ? await provider() : provider;
148
+ }
149
+ function isUnavailableWorkspaceSession(error) {
150
+ const message = error instanceof Error ? error.message : String(error);
151
+ 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");
152
+ }
153
+ function cleanWorkspaceShellPath(path) {
154
+ return normalizeSafeWorkspacePath(path.replace(/^\/workspace(?:\/|$)/, ""), { allowEmpty: true });
155
+ }
64
156
  function cleanMutationPath(path) {
65
157
  const normalized = cleanWorkspaceShellPath(path);
66
158
  if (!normalized) throw new Error("[vitehub] Workspace root is not a valid mutation target.");
@@ -99,34 +191,61 @@ function shellCommandsFor(operations) {
99
191
  if (operations.search) commands.push("grep", "rg");
100
192
  return commands;
101
193
  }
102
- function describeShellCommands(commands) {
194
+ function describeShellCommands(commands, options = {}) {
103
195
  const supported = new Set(commands);
196
+ const available = [
197
+ supported.has("pwd") && "`pwd`",
198
+ supported.has("ls") && "`ls`",
199
+ supported.has("find") && "`find`",
200
+ (supported.has("rg") || supported.has("grep")) && "`rg [-i] pattern [path...]`, `grep -ri pattern [path...]`",
201
+ supported.has("cat") && "`cat`",
202
+ supported.has("head") && "`head`",
203
+ supported.has("tail") && "`tail`",
204
+ supported.has("wc") && "`wc`",
205
+ options.sourceRequests && "controlled `curl` for API-backed Sources listed under `.vitehub/sources/*.json`"
206
+ ].filter(Boolean);
207
+ const examples = [
208
+ supported.has("rg") && supported.has("head") && "`rg 'siff|PLC' ingestion forecasting-engine | head -n 20`",
209
+ supported.has("rg") && !supported.has("head") && "`rg 'siff|PLC' ingestion forecasting-engine`",
210
+ supported.has("find") && "`find ingestion -type f -name '*.sql'`",
211
+ supported.has("cat") && supported.has("head") && "`cat forecasting-engine/README.md | head -n 40`",
212
+ options.sourceRequests && "`curl --json '{\"region\":\"eu\"}' https://example.com/api/source`"
213
+ ].filter(Boolean);
104
214
  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(" ");
215
+ "Inspect files in `/workspace` with a Bash-compatible shell.",
216
+ `Use these commands: ${available.join(", ")}.`,
217
+ 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.",
218
+ "Pipes, redirects, chaining, quoted patterns, and multiline scripts are supported.",
219
+ "Skip unsupported helpers such as `xargs`, `awk`, `sed`, `sort`, `cut`, or `python`.",
220
+ "Answer conversational messages directly; do not use shell commands such as `echo` to compose replies.",
221
+ examples.length && `Examples: ${examples.join("; ")}.`
222
+ ].filter(Boolean).join(" ");
121
223
  }
122
224
  async function runShellCommand(input, command, options) {
123
- return await runWorkspaceInspectionCommand(input, command, {
225
+ const networkGrants = getWorkspaceSourceRequestExecution(input);
226
+ const { createReadonlyWorkspaceFs, runWorkspaceInspectionCommand } = await loadWorkspaceShellModule();
227
+ const inspectionOptions = {
124
228
  broadSearchPaths: options.broadSearchPaths,
125
- commands: options.commands,
229
+ commands: networkGrants ? [...options.commands, "curl"] : options.commands,
126
230
  cwd: options.cwd,
127
231
  fs: createReadonlyWorkspaceFs(input),
128
232
  maxOutputLength: options.maxOutputLength,
233
+ networkGrants,
129
234
  timeout: options.timeout
235
+ };
236
+ const starter = getWorkspaceSessionStarter(input);
237
+ if (starter) try {
238
+ return await runWorkspaceInspectionCommand(input, command, {
239
+ ...inspectionOptions,
240
+ provider: createWorkspaceSessionShellProvider(starter)
241
+ });
242
+ } catch (error) {
243
+ if (!isUnavailableWorkspaceSession(error)) throw error;
244
+ }
245
+ const provider = await resolveExecutionProvider(options.executionProvider);
246
+ return await runWorkspaceInspectionCommand(input, command, {
247
+ ...inspectionOptions,
248
+ ...provider ? { provider } : {}
130
249
  });
131
250
  }
132
251
  function sizeOf(content) {
@@ -288,6 +407,7 @@ function createWorkspaceTools(input, options = {}) {
288
407
  broadSearchPaths: options.broadSearchPaths || [],
289
408
  commands: shellCommandsFor(resolveReadOperations(options.operations)),
290
409
  cwd: options.cwd || workspaceMountPoint,
410
+ executionProvider: options.executionProvider,
291
411
  materialize: resolveReadOperations(options.operations).materialize,
292
412
  maxShellCalls: options.maxShellCalls,
293
413
  maxOutputLength: options.maxOutputLength || defaultMaxOutputLength,
@@ -297,10 +417,10 @@ function createWorkspaceTools(input, options = {}) {
297
417
  let shellCalls = 0;
298
418
  const writeEnabled = Object.values(resolved.write).some(Boolean);
299
419
  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().");
420
+ 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
421
  const result = {};
302
422
  if (resolved.commands.length) result.shell = tool({
303
- description: describeShellCommands(resolved.commands),
423
+ description: describeShellCommands(resolved.commands, { sourceRequests: Boolean(getWorkspaceSourceRequestExecution(input)) }),
304
424
  inputSchema: jsonSchema({
305
425
  additionalProperties: false,
306
426
  properties: { command: {
@@ -316,7 +436,7 @@ function createWorkspaceTools(input, options = {}) {
316
436
  cwd: resolved.cwd,
317
437
  event: "policy_denied",
318
438
  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`,
439
+ stderr: `[vitehub] Workspace shell command budget exhausted after ${resolved.maxShellCalls} calls. The Workspace Tools shell call budget is exhausted for this run.\n`,
320
440
  stdout: ""
321
441
  };
322
442
  shellCalls += 1;
@@ -349,4 +469,4 @@ function createWorkspaceTools(input, options = {}) {
349
469
  return result;
350
470
  }
351
471
  //#endregion
352
- export { appendWorkspaceFile as n, copyWorkspacePath as r, createWorkspaceTools as t };
472
+ export { copyWorkspacePath as a, appendWorkspaceFile as i, getWorkspaceDependencyRuntimeLoaders as n, setWorkspaceDependencyRuntimeLoaders as r, createWorkspaceTools as t };