code60-transmission-server 0.0.0-stage → 0.1.0-staging.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 (88) hide show
  1. package/LICENSE +180 -0
  2. package/README.engine.md +401 -0
  3. package/README.md +291 -2
  4. package/dist/src/broker/filesystem.js +385 -0
  5. package/dist/src/broker/index.js +734 -0
  6. package/dist/src/broker/native/README.md +192 -0
  7. package/dist/src/broker/native/build.js +43 -0
  8. package/dist/src/broker/native/fs-helper.c +529 -0
  9. package/dist/src/broker/native/git-helper.c +205 -0
  10. package/dist/src/broker/policy.js +149 -0
  11. package/dist/src/broker/startup-lock.js +14 -0
  12. package/dist/src/broker/types.js +11 -0
  13. package/dist/src/cli/daemon.js +365 -0
  14. package/dist/src/cli/helpers.js +104 -0
  15. package/dist/src/cli/main.js +180 -0
  16. package/dist/src/config/deployment.js +163 -0
  17. package/dist/src/config/documents.js +29 -0
  18. package/dist/src/config/profile-validation.js +123 -0
  19. package/dist/src/config/schema-graph.js +237 -0
  20. package/dist/src/config/schema-loader.js +185 -0
  21. package/dist/src/config/validation-pool.js +105 -0
  22. package/dist/src/config/validation-protocol.js +1 -0
  23. package/dist/src/config/validation-worker.js +106 -0
  24. package/dist/src/config/workflow-language.js +9 -0
  25. package/dist/src/config/workflow-schema.json +534 -0
  26. package/dist/src/config/workflow-types.js +1 -0
  27. package/dist/src/config/workflow-validation.js +95 -0
  28. package/dist/src/engine/budgets.js +50 -0
  29. package/dist/src/engine/clocks.js +27 -0
  30. package/dist/src/engine/commands.js +441 -0
  31. package/dist/src/engine/contracts.js +11 -0
  32. package/dist/src/engine/drain-state.js +31 -0
  33. package/dist/src/engine/effective-permissions.js +120 -0
  34. package/dist/src/engine/instruction-pins.js +205 -0
  35. package/dist/src/engine/retries.js +50 -0
  36. package/dist/src/engine/state.js +1 -0
  37. package/dist/src/engine/timing.js +23 -0
  38. package/dist/src/engine/tool-observations.js +87 -0
  39. package/dist/src/engine/workflow-engine.js +1807 -0
  40. package/dist/src/main.js +25 -0
  41. package/dist/src/mcp/catalog.js +71 -0
  42. package/dist/src/mcp/main.js +24 -0
  43. package/dist/src/mcp/server.js +104 -0
  44. package/dist/src/runtime/codex-app-server.js +91 -0
  45. package/dist/src/runtime/containment.js +82 -0
  46. package/dist/src/runtime/engine-driver.js +212 -0
  47. package/dist/src/runtime/json-line-writer.js +192 -0
  48. package/dist/src/runtime/pinned-instruction-sources.js +24 -0
  49. package/dist/src/runtime/protocol-client.js +264 -0
  50. package/dist/src/runtime/protocol-pool.js +183 -0
  51. package/dist/src/runtime/protocol-projection.js +393 -0
  52. package/dist/src/runtime/protocol-types.js +1 -0
  53. package/dist/src/runtime/protocol-worker.js +18 -0
  54. package/dist/src/runtime/provider-bridge.js +288 -0
  55. package/dist/src/runtime/provider-credentials.js +41 -0
  56. package/dist/src/runtime/provider-transport.js +404 -0
  57. package/dist/src/runtime/runtime-broker.js +213 -0
  58. package/dist/src/runtime/workspace-instructions.js +120 -0
  59. package/dist/src/runtime/workspace-view.js +74 -0
  60. package/dist/src/server/api-contract.json +11078 -0
  61. package/dist/src/server/api-types.js +1 -0
  62. package/dist/src/server/application.js +38 -0
  63. package/dist/src/server/auth.js +67 -0
  64. package/dist/src/server/broker-handlers.js +242 -0
  65. package/dist/src/server/control-plane.js +50 -0
  66. package/dist/src/server/deployment.js +237 -0
  67. package/dist/src/server/errors.js +22 -0
  68. package/dist/src/server/history-handlers.js +113 -0
  69. package/dist/src/server/http.js +124 -0
  70. package/dist/src/server/paging.js +56 -0
  71. package/dist/src/server/publication.js +119 -0
  72. package/dist/src/server/tool-event-handler.js +77 -0
  73. package/dist/src/server/workspace-handlers.js +34 -0
  74. package/dist/src/storage/coordinator.js +224 -0
  75. package/dist/src/storage/startup-lock.js +71 -0
  76. package/dist/src/storage/store.js +167 -0
  77. package/dist/src/tools/check-worker.js +81 -0
  78. package/dist/src/tools/checks.js +106 -0
  79. package/dist/src/tools/dns.js +248 -0
  80. package/dist/src/tools/http-contract.js +38 -0
  81. package/dist/src/tools/http.js +358 -0
  82. package/dist/src/tools/index.js +177 -0
  83. package/dist/src/tools/worker-check.js +73 -0
  84. package/dist/src/workspaces/git.js +227 -0
  85. package/dist/src/workspaces/index.js +715 -0
  86. package/examples/deployment.local.json +22 -0
  87. package/package.json +68 -4
  88. package/scripts/postinstall.mjs +25 -0
package/README.md CHANGED
@@ -1,3 +1,292 @@
1
- # Temporary Holding Version
1
+ # Code60 Transmission Server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A local workflow server for running bounded coding-agent steps against a Git
4
+ workspace. It stores workflow state, approvals and tool authority in SQLite,
5
+ brokers file/network access, and accepts evaluated results as Git commits.
6
+
7
+ ## Run with npx (MCP)
8
+
9
+ On macOS with Node.js **24.22.0 or newer in the 24.x line** and Xcode Command
10
+ Line Tools (`/usr/bin/clang` and Git), any MCP client can start and connect to
11
+ the server directly via `npx` — no separate daemon startup is required:
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "code60": {
17
+ "command": "npx",
18
+ "args": ["-y", "code60-transmission-server"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ Or print the ready-to-paste client entry from Terminal:
25
+
26
+ ```sh
27
+ npx -y code60-transmission-server mcp-config
28
+ ```
29
+
30
+ On first connection, the launcher compiles the native macOS containment helpers
31
+ (during install or on demand into a private user-owned directory), creates a
32
+ private `0700` state directory at
33
+ `~/Library/Application Support/Code60 Transmission/state` with `0600`
34
+ `configuration.json` and `operator.token`, and starts one shared detached
35
+ background engine for that state directory. Multiple MCP clients share the same
36
+ engine, and closing an MCP client leaves the engine running so active runs are
37
+ not interrupted. Pass `--state-directory /absolute/path` to isolate an
38
+ independent state directory.
39
+
40
+ Inspect or stop the background engine at any time:
41
+
42
+ ```sh
43
+ npx -y code60-transmission-server status
44
+ npx -y code60-transmission-server stop
45
+ ```
46
+
47
+ The default state directory and port (`31260`) are shared cleanly with the
48
+ macOS `.pkg` installer below. Before changing `configuration.json` or upgrading
49
+ to a new package version, let active runs finish, run `stop`, and reconnect.
50
+ Registered workspaces must be standalone Git repositories prepared normally on
51
+ disk (with a real `.git` directory, at least one commit, and no hardlinked
52
+ `.git/objects` files—do not initialize repositories inside a sandbox that
53
+ forbids deleting files, and use `git clone --no-hardlinks` for local clones).
54
+
55
+ ## Install on macOS
56
+
57
+ Open the Code60 Transmission `.pkg` for your Mac's architecture. It installs
58
+ the engine, stdio MCP bridge, Node.js, SQLite binding, and both native helpers
59
+ for your macOS account. Both the engine and bridge use the bundled Node runtime.
60
+ The package targets macOS 14 or newer.
61
+
62
+ To get the connection settings for your desktop MCP client, run this command in Terminal.
63
+
64
+ ```sh
65
+ "$HOME/Library/Application Support/Code60 Transmission/app/code60" mcp-config
66
+ ```
67
+
68
+ Copy the printed server entry into your client's MCP settings. For a client
69
+ with separate fields, use the printed absolute path as its stdio command and
70
+ leave the arguments empty. The first connection creates a private operator
71
+ token and configuration and starts one engine in your macOS login session.
72
+ Each client gets its own bridge. The engine stays running after clients close.
73
+
74
+ Private configuration, token, database, and engine log live together in
75
+ `~/Library/Application Support/Code60 Transmission/state/`, outside the installed
76
+ `app/` directory. The default API port is `31260`. If that port is in use,
77
+ set `listenPort` in `state/configuration.json` to a free port and reconnect.
78
+ The bridge reads the same setting. The initial deployment supports operator
79
+ setup. To run coding-agent steps, configure the Codex CLI and a model provider
80
+ as described in [Configure and run](#configure-and-run). Git workspace operations
81
+ use Apple's Command Line Tools Git and your configured author identity.
82
+
83
+ Before an upgrade or a configuration reload, let active runs finish, disconnect
84
+ the clients, and stop the loaded engine.
85
+
86
+ ```sh
87
+ launchctl bootout "gui/$(id -u)/com.codemanufactory.code60.transmission"
88
+ ```
89
+
90
+ Install the new package or edit the private configuration, then reconnect.
91
+ Reinstalling updates the application and preserves the private state.
92
+
93
+ ## Build the macOS installer
94
+
95
+ On a build Mac of the target architecture, use the official unpacked Node
96
+ 24.22.0 or newer 24.x distribution (including its `LICENSE`), npm, and Apple's
97
+ Command Line Tools.
98
+
99
+ ```sh
100
+ npm ci
101
+ npm run package:macos
102
+ ```
103
+
104
+ The output is `dist/installers/Code60-Transmission-<version>-<arch>.pkg`.
105
+ The build stages a fresh TypeScript compilation, native helpers, and locked
106
+ production dependencies. It checks architecture, deployment targets, dynamic
107
+ library paths, and the bundled SQLite binding. The default build is unsigned
108
+ for local testing. For a public release, set `APPLICATION_SIGN_IDENTITY` and
109
+ `INSTALLER_SIGN_IDENTITY` to your Developer ID Application and Installer
110
+ identities, and set `NOTARY_PROFILE` to your notarytool Keychain profile.
111
+ The same build command then signs the native code and package, submits it to
112
+ Apple, staples the ticket, and checks Gatekeeper acceptance.
113
+
114
+ In a separate macOS login account with port 31260 available and no installed
115
+ Transmission engine, run `node scripts/smoke-macos-package.mjs /absolute/path/to/the.pkg`.
116
+ It checks the installer domain and exercises the extracted payload with two MCP
117
+ clients and a real per-user engine, then removes its temporary service and files.
118
+
119
+ ## Requirements for building from source
120
+
121
+ - macOS, for the native containment used by the runtime and helpers.
122
+ - Node.js **24.22.0 or newer in the 24.x line**, and npm.
123
+ - An installed Codex CLI with `app-server` support.
124
+ - Xcode Command Line Tools (`/usr/bin/clang`), including a C toolchain, and Git
125
+ with your existing author identity available for workspace commits.
126
+
127
+ ## Install and build
128
+
129
+ From the checkout:
130
+
131
+ ```sh
132
+ npm ci
133
+ npm run build
134
+ ```
135
+
136
+ The build emits TypeScript **and compiles both C helpers** into
137
+ `dist/src/broker/native/.build/`. Starting the server does not build them.
138
+
139
+ ## Configure and run
140
+
141
+ For a complete first run with a real model, follow
142
+ [the hello-world example](examples/hello-world/README.md). After building and
143
+ setting `OPENROUTER_API_KEY`, run `npm run example:hello-world`. It creates its
144
+ own disposable Git workspace and private configuration, runs the workflow,
145
+ checks the artifact and acceptance commit, and stops the server.
146
+
147
+ Start with [examples/deployment.local.json](examples/deployment.local.json).
148
+ It contains no secrets, leaves the runtime disabled, and denies all tool access.
149
+ Uppercase `REPLACE_WITH_...` values are placeholders. Before enabling the runtime,
150
+ set your Codex executable's absolute path, the local model ID/effort, and an unused
151
+ loopback model port served by an owned Responses-compatible synthetic provider.
152
+ No model provider is started for you.
153
+
154
+ Keep state and private files outside the checkout. For a **new** state directory:
155
+
156
+ ```sh
157
+ ROOT="$(pwd -P)"
158
+ STATE="$HOME/code60-engine-state"
159
+ mkdir -m 700 "$STATE" &&
160
+ install -m 600 examples/deployment.local.json "$STATE/configuration.json" &&
161
+ node --input-type=module -e 'import { randomBytes } from "node:crypto"; import { writeFileSync } from "node:fs"; writeFileSync(process.argv[1], randomBytes(32).toString("base64url") + "\n", { mode: 0o600, flag: "wx" });' "$STATE/operator.token"
162
+ ```
163
+
164
+ Edit that private configuration copy. Keep it and the token owned by your user,
165
+ mode `0600`, without symlinks or hardlinks. The state directory must be `0700`.
166
+ Never put the token in configuration JSON, command arguments or Git.
167
+
168
+ ```sh
169
+ npm start -- \
170
+ --state-directory "$STATE" \
171
+ --fs-helper "$ROOT/dist/src/broker/native/.build/fs-helper" \
172
+ --git-helper "$ROOT/dist/src/broker/native/.build/git-helper" \
173
+ --configuration "$STATE/configuration.json" \
174
+ --operator-token-file "$STATE/operator.token"
175
+ ```
176
+
177
+ All five paths must be absolute. With the example ports, the authenticated API
178
+ is at `http://127.0.0.1:31260/api/v1`. There is no unauthenticated health route or
179
+ automatic login. Read the private token in your API client, then follow the
180
+ [operator walkthrough and recovery rules](README.engine.md#operator-api-walkthrough)
181
+ to register an explicitly authorized Git workspace, publish profiles/workflows,
182
+ and start a run. The disabled example supports API setup, not agent execution.
183
+
184
+ ## Connect an agent over MCP
185
+
186
+ Start the Transmission Server with your private deployment configuration, then
187
+ configure your MCP client to launch the built stdio bridge. For clients that use
188
+ an `mcpServers` configuration, replace both absolute paths and use the engine's
189
+ configured port.
190
+
191
+ ```json
192
+ {
193
+ "mcpServers": {
194
+ "code60": {
195
+ "command": "node",
196
+ "args": [
197
+ "/absolute/path/to/code60-transmission-server/dist/src/mcp/main.js",
198
+ "--port", "31260",
199
+ "--operator-token-file", "/absolute/path/to/private/operator.token"
200
+ ]
201
+ }
202
+ }
203
+ }
204
+ ```
205
+
206
+ The client launches one bridge per connection. The bridge reads the private token
207
+ file on startup and authenticates to the engine on IPv4 loopback. The agent can
208
+ exercise the configured operator’s authority, including approval decisions and
209
+ recovery. Workspace registration requires an unrestricted operator. To execute
210
+ agent steps, enable and configure the deployment runtime.
211
+
212
+ 1. Discover runtimes and named checks, then register an authorized worktree with
213
+ `create_workspace`. Publish a worker with `create_agent_profile`.
214
+ 2. Read the MCP resources `code60://workflow/schema` and
215
+ `code60://workflow/example`. Replace the example’s worker placeholder with
216
+ the profile’s `latestVersionId`. Pass the YAML or JSON source and any bundled
217
+ resources to `validate_workflow`, then publish with `create_workflow`.
218
+ 3. Call `create_run` with a unique `idempotencyKey` and a `body` containing
219
+ `workspaceId` and the workflow’s `latestVersionId` as `workflowVersionId`.
220
+ Save the returned `body.id`. A 202 response means the engine admitted the run.
221
+ 4. Read `get_run` or call `list_run_events` with `runId`, `follow: true`,
222
+ and `waitSeconds: 30`. Reuse each `body.nextCursor` as `cursor` on the next
223
+ poll, including after reconnecting. Inspect approvals, blocks, and artifacts
224
+ through their list and get tools. Closing the MCP client leaves the engine
225
+ running.
226
+
227
+ Tools return the HTTP `status` and engine `body` in structured content and text,
228
+ plus `etag`, `location`, and `idempotentReplay` when available. All POST tools
229
+ take `body` and `idempotencyKey`. Reuse the same arguments after a lost response.
230
+ For a conditional command, pass the target read’s `etag` as `ifMatch`. On a
231
+ stale-version error, reread the target before making a new decision. Poll
232
+ `get_operation` for asynchronous operator commands.
233
+
234
+ ## Workflow examples
235
+
236
+ - [Hello world](examples/hello-world/README.md): run a real agent, validate its
237
+ artifact, and verify the accepted Git commit. Run `npm run example:hello-world`.
238
+ - [Pull request lifecycle](examples/pull-request/README.md): clone the disposable
239
+ GitHub repository, create a worktree, make an agent change, push/open/merge a
240
+ PR, and delete the worktree. Run `npm run example:pull-request`.
241
+
242
+ ## Browse the API specification
243
+
244
+ With Docker running, start Swagger UI:
245
+
246
+ ```sh
247
+ npm run docs:api
248
+ ```
249
+
250
+ Open [http://localhost:8080](http://localhost:8080) to browse the OpenAPI specification.
251
+ The API server does not need to be running. Press Ctrl+C to stop the viewer and
252
+ remove its container. The first run downloads the Swagger UI image.
253
+
254
+ ## Tests
255
+
256
+ ```sh
257
+ npm run typecheck
258
+ npm test -- --maxWorkers=1
259
+ ```
260
+
261
+ `npm test` builds its own native helpers before running the suite, including the
262
+ normal-entrypoint and restart tests. Installed-runtime tests use
263
+ `CODE60_CODEX_EXECUTABLE` (an explicit absolute executable path) first, otherwise
264
+ look for `codex` on `PATH`; absence is a clear test failure, not a silent skip.
265
+ No Codex configuration or credentials are read by that lookup. To run just the
266
+ runtime pilot, use `npm run test:pilot -- --maxWorkers=1`. Run native builds/tests
267
+ serially. Preserved-image mode is optional, not needed for a fresh clone.
268
+ See [validation details](README.engine.md#validation) for focused checks.
269
+
270
+ ## Limits
271
+
272
+ - The [hello-world example](examples/hello-world/README.md) has live validation
273
+ through OpenRouter with GPT-5.3-Codex. Other provider/model combinations need
274
+ their own validation; the normal automated suite uses synthetic providers.
275
+ - Single host, one coordinator per state directory, loopback API only. No
276
+ multi-host service, public ingress or browser login is supplied.
277
+ - Initial broker tools: `read_file`, `write_file`, `list_files`, `search_files`,
278
+ `move_file`, `delete_file`, and `http_request`, subject to profile and outer
279
+ deployment policy. No shell/process tool, arbitrary Git commands, browser/UI
280
+ tools, directory move/delete, or unrestricted host/network access.
281
+ - Containment is macOS-only. Preserved-image test success does not establish
282
+ clean-build, sanitizer or cross-platform support.
283
+
284
+ See [README.engine.md](README.engine.md) for configuration, API, authorization,
285
+ instruction pinning, deadlines and recovery details.
286
+
287
+ ## Repository skills
288
+
289
+ Use `$add-workflow-example` to add or revise a runnable example with setup
290
+ instructions and end-to-end verification. The
291
+ [repository skill](.agents/skills/add-workflow-example/SKILL.md) describes the
292
+ required implementation and evidence.
@@ -0,0 +1,385 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { closeSync, constants, fstatSync, lstatSync, openSync } from "node:fs";
4
+ import { dirname, isAbsolute } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { BrokerError } from "./types.js";
7
+ import { digest, relativePath } from "./policy.js";
8
+ import { startupLockIdentity } from "./startup-lock.js";
9
+ const MAX_DATA = 1_048_576;
10
+ const MAX_PATH = 4096;
11
+ const MAX_ID = 8192;
12
+ const environment = Object.freeze({ PATH: "/usr/bin:/bin", LC_ALL: "C" });
13
+ const decoder = new TextDecoder("utf-8", { fatal: true });
14
+ export class FilesystemHelperError extends Error {
15
+ code;
16
+ uncertain;
17
+ constructor(code, uncertain) {
18
+ super(`filesystem:${code}`);
19
+ this.code = code;
20
+ this.uncertain = uncertain;
21
+ }
22
+ }
23
+ /** Fixed six-tool catalog using actual descriptor-relative native operations.
24
+ * No model-controlled root, flags, helper executable, shell or environment.
25
+ * Node path validation is only input validation, never the access enforcement. */
26
+ export class NativeFilesystemRoot {
27
+ options;
28
+ rootIdentity;
29
+ protectedDescriptors;
30
+ ownedDescriptors;
31
+ protectedIdentities;
32
+ lockIdentity;
33
+ closed = false;
34
+ constructor(options) {
35
+ this.options = Object.freeze({ ...options, protectedRootFds: Object.freeze([...(options.protectedRootFds ?? [])]) });
36
+ this.lockIdentity = options.startupLockFd === undefined ? undefined : startupLockIdentity(options.startupLockFd);
37
+ if (!Number.isInteger(options.rootFd) || options.rootFd < 0 ||
38
+ !["workspace", "scratch", "deployment"].includes(options.root) ||
39
+ (options.root === "deployment" ? !options.rootId : options.rootId !== undefined))
40
+ throw new BrokerError("invalid_filesystem_root", 422);
41
+ const root = fstatSync(options.rootFd, { bigint: true });
42
+ if (!root.isDirectory())
43
+ throw new BrokerError("invalid_filesystem_root", 422);
44
+ this.rootIdentity = `${root.dev}:${root.ino}`;
45
+ if (!isAbsolute(options.helperPath))
46
+ throw new BrokerError("untrusted_filesystem_helper", 422);
47
+ const executable = lstatSync(options.helperPath);
48
+ if (!executable.isFile() || executable.isSymbolicLink() || executable.nlink !== 1 ||
49
+ executable.uid !== process.geteuid?.() || (executable.mode & 0o6022))
50
+ throw new BrokerError("untrusted_filesystem_helper", 422);
51
+ const owned = [];
52
+ try {
53
+ // Protect actual engine installation and helper directory, not caller path spelling.
54
+ for (const path of [fileURLToPath(new URL("../../", import.meta.url)), dirname(options.helperPath)]) {
55
+ owned.push(openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW));
56
+ }
57
+ const protectedDescriptors = [...owned, ...(options.protectedRootFds ?? []),
58
+ ...(options.quarantineFd === undefined ? [] : [options.quarantineFd])];
59
+ if (protectedDescriptors.length > 64)
60
+ throw new BrokerError("too_many_protected_roots", 422);
61
+ this.protectedIdentities = protectedDescriptors.map(fd => {
62
+ const s = fstatSync(fd, { bigint: true });
63
+ if (!s.isDirectory())
64
+ throw new BrokerError("invalid_protected_root", 422);
65
+ return `${s.dev}:${s.ino}`;
66
+ });
67
+ this.ownedDescriptors = owned;
68
+ this.protectedDescriptors = protectedDescriptors;
69
+ this.run(5, "");
70
+ }
71
+ catch (error) {
72
+ for (const fd of owned)
73
+ closeSync(fd);
74
+ throw error;
75
+ }
76
+ }
77
+ close() {
78
+ if (!this.closed)
79
+ for (const fd of this.ownedDescriptors)
80
+ closeSync(fd);
81
+ this.closed = true;
82
+ } // Borrowed root/protected FDs remain engine-owned.
83
+ run(operation, path, identity = "", content = Buffer.alloc(0)) {
84
+ if (this.closed)
85
+ throw new BrokerError("filesystem_root_closed");
86
+ if (this.options.startupLockFd !== undefined && startupLockIdentity(this.options.startupLockFd) !== this.lockIdentity) {
87
+ throw new BrokerError("startup_lock_changed");
88
+ }
89
+ const root = fstatSync(this.options.rootFd, { bigint: true });
90
+ if (!root.isDirectory() || `${root.dev}:${root.ino}` !== this.rootIdentity)
91
+ throw new BrokerError("filesystem_root_changed");
92
+ for (let i = 0; i < this.protectedDescriptors.length; i++) {
93
+ const s = fstatSync(this.protectedDescriptors[i], { bigint: true });
94
+ if (!s.isDirectory() || `${s.dev}:${s.ino}` !== this.protectedIdentities[i])
95
+ throw new BrokerError("protected_root_changed");
96
+ }
97
+ const pathBytes = Buffer.from(path, "utf8"), identityBytes = Buffer.from(identity, "utf8");
98
+ if ((operation !== 5 && !pathBytes.length) || pathBytes.length > MAX_PATH ||
99
+ identityBytes.length > (operation === 7 ? MAX_DATA : MAX_ID - 1) || content.length > MAX_DATA) {
100
+ throw new BrokerError("filesystem_request_too_large", 422);
101
+ }
102
+ const header = Buffer.alloc(24);
103
+ header.write("C60F", 0, "ascii");
104
+ header[4] = 1;
105
+ header[5] = operation;
106
+ header[6] = this.protectedDescriptors.length;
107
+ header[7] = this.options.quarantineFd === undefined ? 0 : 1;
108
+ header.writeUInt32BE(pathBytes.length, 8);
109
+ header.writeUInt32BE(identityBytes.length, 12);
110
+ header.writeUInt32BE(content.length, 16);
111
+ const response = spawnSync(this.options.helperPath, [], {
112
+ input: Buffer.concat([header, pathBytes, identityBytes, content]),
113
+ stdio: ["pipe", "pipe", "pipe", this.options.rootFd, ...this.protectedDescriptors,
114
+ ...(this.options.startupLockFd === undefined ? [] : [this.options.startupLockFd])],
115
+ env: environment, timeout: 3000, maxBuffer: MAX_DATA + MAX_ID + 32,
116
+ });
117
+ if (response.error || response.status !== 0 || response.signal || response.stderr?.length) {
118
+ throw new FilesystemHelperError("helper_interrupted", [4, 9, 11].includes(operation));
119
+ }
120
+ const out = response.stdout;
121
+ if (!out || out.length < 16 || out.toString("ascii", 0, 4) !== "C60R" || out[4] !== 1 ||
122
+ out[6] || out[7] || out.readUInt32BE(12) || out.readUInt32BE(8) !== out.length - 16) {
123
+ throw new FilesystemHelperError("invalid_helper_response", [4, 9, 11].includes(operation));
124
+ }
125
+ const payload = out.subarray(16), status = out[5];
126
+ if (status !== 0)
127
+ throw new FilesystemHelperError(payload.toString("ascii"), status === 7);
128
+ return payload;
129
+ }
130
+ /** Engine-only raw snapshot APIs. Never exported in model/session views. */
131
+ inspectTree(path = ".") {
132
+ return this.tree(path).entries;
133
+ }
134
+ tree(path) {
135
+ relativePath(path);
136
+ const raw = decoder.decode(this.run(6, path));
137
+ const entries = JSON.parse(raw);
138
+ if (!Array.isArray(entries) || entries.length > 1024 || entries.some(entry => !entry || typeof entry.path !== "string" || !["file", "directory"].includes(entry.type) || typeof entry.identity !== "string")) {
139
+ throw new FilesystemHelperError("invalid_tree_response", false);
140
+ }
141
+ return { raw, entries };
142
+ }
143
+ readBytes(path, identity) {
144
+ relativePath(path);
145
+ return this.run(2, path, identity ?? this.run(1, path).toString("ascii"));
146
+ }
147
+ writeBytes(path, content, identity) {
148
+ relativePath(path);
149
+ this.run(4, path, identity ?? this.run(3, path).toString("ascii"), content);
150
+ }
151
+ absentIdentity(path) {
152
+ const identity = this.run(3, relativePath(path)).toString("ascii");
153
+ if (!identity.endsWith("|absent"))
154
+ throw new FilesystemHelperError("unexpected_existing_target", false);
155
+ return identity;
156
+ }
157
+ makeDirectory(path) {
158
+ relativePath(path);
159
+ this.run(15, path, this.run(3, path).toString("ascii"));
160
+ }
161
+ setMode(path, mode) {
162
+ relativePath(path);
163
+ if (!Number.isInteger(mode) || mode < 0 || mode > 0o777 || (mode & 0o22))
164
+ throw new BrokerError("unsafe_mode", 422);
165
+ const data = Buffer.alloc(4);
166
+ data.writeUInt32BE(mode);
167
+ this.run(16, path, this.run(17, path).toString("ascii"), data);
168
+ }
169
+ remove(path, directory = false, expectedIdentity) {
170
+ relativePath(path);
171
+ const identity = expectedIdentity ?? this.run(directory ? 13 : 8, path).toString("ascii");
172
+ this.run(directory ? 14 : 9, path, identity, Buffer.from(`q-${randomUUID()}`));
173
+ }
174
+ resource(path, operation, identity) {
175
+ return { kind: "filesystem", root: this.options.root,
176
+ ...(this.options.rootId === undefined ? {} : { rootId: this.options.rootId }),
177
+ path, operation, identityDigest: digest(identity) };
178
+ }
179
+ treeEffect(input, searching) {
180
+ if (!input || typeof input !== "object" || Array.isArray(input) ||
181
+ Object.keys(input).some(k => !["path", ...(searching ? ["query", "caseSensitive"] : [])].includes(k)) ||
182
+ (input.path !== undefined && typeof input.path !== "string") ||
183
+ (searching && (typeof input.query !== "string" || !input.query || input.query.length > 256)) ||
184
+ (input.caseSensitive !== undefined && typeof input.caseSensitive !== "boolean"))
185
+ throw new BrokerError("invalid_tool_arguments", 400);
186
+ const path = relativePath(input.path ?? ".");
187
+ const initial = this.tree(path);
188
+ const resources = (entries) => entries.map(entry => this.resource(entry.path, "read", entry.identity));
189
+ let used = false;
190
+ return {
191
+ resources: resources(initial.entries),
192
+ revalidate: () => {
193
+ try {
194
+ return resources(this.tree(path).entries);
195
+ }
196
+ catch {
197
+ return [this.resource(path, "read", "unresolvable-tree")];
198
+ }
199
+ },
200
+ execute: () => {
201
+ if (used)
202
+ throw new BrokerError("effect_already_used");
203
+ used = true;
204
+ try {
205
+ this.run(7, path, initial.raw);
206
+ if (!searching)
207
+ return { success: true, text: JSON.stringify(initial.entries.map(({ path, type }) => ({ path, type }))) };
208
+ const matches = [], binaryFilesSkipped = [];
209
+ const query = input.caseSensitive ? input.query : input.query.toLowerCase();
210
+ let bytes = 0, truncated = false;
211
+ // Every file examined was declared and authorized, including files
212
+ // with no matches. No content is read during prepare/revalidate.
213
+ for (const entry of initial.entries)
214
+ if (entry.type === "file") {
215
+ const content = this.readBytes(entry.path, entry.identity);
216
+ bytes += content.length;
217
+ if (bytes > 16 * MAX_DATA)
218
+ throw new FilesystemHelperError("search_too_large", false);
219
+ let text;
220
+ try {
221
+ text = decoder.decode(content);
222
+ }
223
+ catch {
224
+ binaryFilesSkipped.push(entry.path);
225
+ continue;
226
+ }
227
+ text.split("\n").forEach((line, index) => {
228
+ if ((input.caseSensitive ? line : line.toLowerCase()).includes(query)) {
229
+ if (matches.length < 1000)
230
+ matches.push({ path: entry.path, line: index + 1, text: line.slice(0, 4096) });
231
+ else
232
+ truncated = true;
233
+ }
234
+ });
235
+ }
236
+ this.run(7, path, initial.raw);
237
+ return { success: true, text: JSON.stringify({ matches, binaryFilesSkipped, truncated }) };
238
+ }
239
+ catch (error) {
240
+ if (error instanceof FilesystemHelperError && !error.uncertain)
241
+ return { success: false, text: error.message };
242
+ throw error;
243
+ }
244
+ },
245
+ };
246
+ }
247
+ namespaceEffect(input, moving) {
248
+ if (this.options.quarantineFd === undefined)
249
+ throw new BrokerError("filesystem_quarantine_required", 422);
250
+ if (!input || typeof input !== "object" || Array.isArray(input) ||
251
+ Object.keys(input).some(k => !["path", ...(moving ? ["destination"] : [])].includes(k)) ||
252
+ typeof input.path !== "string" || (moving && typeof input.destination !== "string"))
253
+ throw new BrokerError("invalid_tool_arguments", 400);
254
+ const path = relativePath(input.path), destination = moving ? relativePath(input.destination) : "";
255
+ const data = Buffer.from(destination), probe = moving ? 10 : 8;
256
+ const identity = this.run(probe, path, "", data).toString("ascii");
257
+ const resources = (actual) => {
258
+ const [source, target] = actual.split("\n");
259
+ return [this.resource(path, "delete", source), ...(moving ? [this.resource(destination, "write", target)] : [])];
260
+ };
261
+ let used = false;
262
+ return {
263
+ resources: resources(identity),
264
+ revalidate: () => {
265
+ try {
266
+ return resources(this.run(probe, path, "", data).toString("ascii"));
267
+ }
268
+ catch {
269
+ return [this.resource(path, "delete", "unresolvable-namespace")];
270
+ }
271
+ },
272
+ execute: () => {
273
+ if (used)
274
+ throw new BrokerError("effect_already_used");
275
+ used = true;
276
+ const token = Buffer.from(`q-${randomUUID()}`);
277
+ let content = token;
278
+ if (moving) {
279
+ const header = Buffer.alloc(4);
280
+ header.writeUInt32BE(data.length);
281
+ content = Buffer.concat([header, data, token]);
282
+ }
283
+ try {
284
+ this.run(moving ? 11 : 9, path, identity, content);
285
+ return { success: true, text: moving ? "File moved." : "File deleted." };
286
+ }
287
+ catch (error) {
288
+ if (error instanceof FilesystemHelperError && !error.uncertain)
289
+ return { success: false, text: error.message };
290
+ throw error;
291
+ }
292
+ },
293
+ };
294
+ }
295
+ arguments(input, writing) {
296
+ if (!input || typeof input !== "object" || Array.isArray(input) ||
297
+ Object.keys(input).some(k => !["path", ...(writing ? ["content"] : [])].includes(k)) ||
298
+ typeof input.path !== "string" || (writing && typeof input.content !== "string")) {
299
+ throw new BrokerError("invalid_tool_arguments", 400);
300
+ }
301
+ const path = relativePath(input.path);
302
+ if (path === "." || decoder.decode(Buffer.from(path)) !== path)
303
+ throw new BrokerError("invalid_tool_arguments", 400);
304
+ const content = writing ? Buffer.from(input.content, "utf8") : Buffer.alloc(0);
305
+ if ((writing && decoder.decode(content) !== input.content) || content.length > MAX_DATA)
306
+ throw new BrokerError("invalid_tool_arguments", 400);
307
+ return { path, content };
308
+ }
309
+ prepare(input, writing) {
310
+ const { path, content } = this.arguments(input, writing);
311
+ const probe = writing ? 3 : 1;
312
+ let identity;
313
+ try {
314
+ identity = this.run(probe, path).toString("ascii");
315
+ }
316
+ catch (error) {
317
+ if (error instanceof FilesystemHelperError)
318
+ throw new BrokerError(`filesystem_${error.code}`, 422);
319
+ throw error;
320
+ }
321
+ const resource = (actual) => ({
322
+ kind: "filesystem", root: this.options.root,
323
+ ...(this.options.rootId === undefined ? {} : { rootId: this.options.rootId }),
324
+ path, operation: writing ? "write" : "read", identityDigest: digest(actual),
325
+ });
326
+ return {
327
+ resources: [resource(identity)],
328
+ revalidate: () => {
329
+ try {
330
+ return [resource(this.run(probe, path).toString("ascii"))];
331
+ }
332
+ catch (error) {
333
+ // An unresolvable target can never revive an earlier allowed handle.
334
+ // Returning a distinct trusted failed-resolution identity makes the
335
+ // core durably invalidate the old action before any effect dispatch.
336
+ if (error instanceof FilesystemHelperError)
337
+ return [resource(`unresolvable:${error.code}`)];
338
+ throw error;
339
+ }
340
+ },
341
+ execute: () => {
342
+ try {
343
+ const result = this.run(writing ? 4 : 2, path, identity, content);
344
+ if (writing)
345
+ return { success: true, text: "File written." };
346
+ try {
347
+ return { success: true, text: decoder.decode(result) };
348
+ }
349
+ catch {
350
+ return { success: false, text: "filesystem:invalid_utf8" };
351
+ }
352
+ }
353
+ catch (error) {
354
+ if (error instanceof FilesystemHelperError && !error.uncertain)
355
+ return { success: false, text: error.message };
356
+ throw error;
357
+ }
358
+ },
359
+ };
360
+ }
361
+ catalog() {
362
+ return new Map([...filesystemToolDefinitions()].filter(([name]) => this.options.quarantineFd !== undefined || !["delete_file", "move_file"].includes(name)).map(([name, definition]) => [name, { ...definition, prepare: (input) => name === "read_file" || name === "write_file" ? this.prepare(input, name === "write_file") :
363
+ name === "list_files" || name === "search_files" ? this.treeEffect(input, name === "search_files") : this.namespaceEffect(input, name === "move_file") }]));
364
+ }
365
+ }
366
+ /** Pure metadata for runtime discovery before any workspace/session exists. */
367
+ export function filesystemToolDefinitions() {
368
+ return new Map([
369
+ ["read_file", { name: "read_file", description: "Read a UTF-8 regular file under the assigned root.",
370
+ inputSchema: { type: "object", properties: { path: { type: "string" } }, required: ["path"], additionalProperties: false } }],
371
+ ["write_file", { name: "write_file", description: "Write UTF-8 content to one regular file under the assigned root.",
372
+ inputSchema: { type: "object", properties: { path: { type: "string" }, content: { type: "string" } },
373
+ required: ["path", "content"], additionalProperties: false } }],
374
+ ["list_files", { name: "list_files", description: "List a bounded recursive regular-file/directory tree; excludes .git and rejects unsafe entries.",
375
+ inputSchema: { type: "object", properties: { path: { type: "string" } }, additionalProperties: false } }],
376
+ ["search_files", { name: "search_files", description: "Search UTF-8 files for a literal substring, authorizing every examined file first.",
377
+ inputSchema: { type: "object", properties: { path: { type: "string" }, query: { type: "string", minLength: 1, maxLength: 256 },
378
+ caseSensitive: { type: "boolean" } }, required: ["query"], additionalProperties: false } }],
379
+ ["delete_file", { name: "delete_file", description: "Delete one regular file using verified private quarantine capture.",
380
+ inputSchema: { type: "object", properties: { path: { type: "string" } }, required: ["path"], additionalProperties: false } }],
381
+ ["move_file", { name: "move_file", description: "Move one regular file to an absent name. Never overwrite an existing destination.",
382
+ inputSchema: { type: "object", properties: { path: { type: "string" }, destination: { type: "string" } },
383
+ required: ["path", "destination"], additionalProperties: false } }],
384
+ ]);
385
+ }