code60-transmission-server 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +180 -0
- package/README.engine.md +401 -0
- package/README.md +287 -2
- package/dist/src/broker/filesystem.js +385 -0
- package/dist/src/broker/index.js +734 -0
- package/dist/src/broker/native/README.md +192 -0
- package/dist/src/broker/native/build.js +43 -0
- package/dist/src/broker/native/fs-helper.c +529 -0
- package/dist/src/broker/native/git-helper.c +176 -0
- package/dist/src/broker/policy.js +149 -0
- package/dist/src/broker/startup-lock.js +14 -0
- package/dist/src/broker/types.js +11 -0
- package/dist/src/cli/daemon.js +365 -0
- package/dist/src/cli/helpers.js +104 -0
- package/dist/src/cli/main.js +180 -0
- package/dist/src/config/deployment.js +163 -0
- package/dist/src/config/documents.js +29 -0
- package/dist/src/config/profile-validation.js +123 -0
- package/dist/src/config/schema-graph.js +237 -0
- package/dist/src/config/schema-loader.js +185 -0
- package/dist/src/config/validation-pool.js +105 -0
- package/dist/src/config/validation-protocol.js +1 -0
- package/dist/src/config/validation-worker.js +106 -0
- package/dist/src/config/workflow-language.js +9 -0
- package/dist/src/config/workflow-schema.json +534 -0
- package/dist/src/config/workflow-types.js +1 -0
- package/dist/src/config/workflow-validation.js +95 -0
- package/dist/src/engine/budgets.js +50 -0
- package/dist/src/engine/clocks.js +27 -0
- package/dist/src/engine/commands.js +441 -0
- package/dist/src/engine/contracts.js +11 -0
- package/dist/src/engine/drain-state.js +31 -0
- package/dist/src/engine/effective-permissions.js +120 -0
- package/dist/src/engine/instruction-pins.js +205 -0
- package/dist/src/engine/retries.js +50 -0
- package/dist/src/engine/state.js +1 -0
- package/dist/src/engine/timing.js +23 -0
- package/dist/src/engine/tool-observations.js +87 -0
- package/dist/src/engine/workflow-engine.js +1807 -0
- package/dist/src/main.js +25 -0
- package/dist/src/mcp/catalog.js +71 -0
- package/dist/src/mcp/main.js +24 -0
- package/dist/src/mcp/server.js +103 -0
- package/dist/src/runtime/codex-app-server.js +91 -0
- package/dist/src/runtime/containment.js +82 -0
- package/dist/src/runtime/engine-driver.js +212 -0
- package/dist/src/runtime/json-line-writer.js +192 -0
- package/dist/src/runtime/pinned-instruction-sources.js +24 -0
- package/dist/src/runtime/protocol-client.js +264 -0
- package/dist/src/runtime/protocol-pool.js +183 -0
- package/dist/src/runtime/protocol-projection.js +393 -0
- package/dist/src/runtime/protocol-types.js +1 -0
- package/dist/src/runtime/protocol-worker.js +18 -0
- package/dist/src/runtime/provider-bridge.js +288 -0
- package/dist/src/runtime/provider-credentials.js +41 -0
- package/dist/src/runtime/provider-transport.js +404 -0
- package/dist/src/runtime/runtime-broker.js +213 -0
- package/dist/src/runtime/workspace-instructions.js +120 -0
- package/dist/src/runtime/workspace-view.js +74 -0
- package/dist/src/server/api-contract.json +11078 -0
- package/dist/src/server/api-types.js +1 -0
- package/dist/src/server/application.js +38 -0
- package/dist/src/server/auth.js +67 -0
- package/dist/src/server/broker-handlers.js +242 -0
- package/dist/src/server/control-plane.js +50 -0
- package/dist/src/server/deployment.js +237 -0
- package/dist/src/server/errors.js +22 -0
- package/dist/src/server/history-handlers.js +113 -0
- package/dist/src/server/http.js +124 -0
- package/dist/src/server/paging.js +56 -0
- package/dist/src/server/publication.js +119 -0
- package/dist/src/server/tool-event-handler.js +77 -0
- package/dist/src/server/workspace-handlers.js +34 -0
- package/dist/src/storage/coordinator.js +224 -0
- package/dist/src/storage/startup-lock.js +71 -0
- package/dist/src/storage/store.js +167 -0
- package/dist/src/tools/check-worker.js +81 -0
- package/dist/src/tools/checks.js +106 -0
- package/dist/src/tools/dns.js +248 -0
- package/dist/src/tools/http-contract.js +38 -0
- package/dist/src/tools/http.js +358 -0
- package/dist/src/tools/index.js +177 -0
- package/dist/src/tools/worker-check.js +73 -0
- package/dist/src/workspaces/git.js +163 -0
- package/dist/src/workspaces/index.js +715 -0
- package/examples/deployment.local.json +22 -0
- package/package.json +68 -4
- package/scripts/postinstall.mjs +25 -0
package/README.md
CHANGED
|
@@ -1,3 +1,288 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Code60 Transmission Server
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
|
|
51
|
+
## Install on macOS
|
|
52
|
+
|
|
53
|
+
Open the Code60 Transmission `.pkg` for your Mac's architecture. It installs
|
|
54
|
+
the engine, stdio MCP bridge, Node.js, SQLite binding, and both native helpers
|
|
55
|
+
for your macOS account. Both the engine and bridge use the bundled Node runtime.
|
|
56
|
+
The package targets macOS 14 or newer.
|
|
57
|
+
|
|
58
|
+
To get the connection settings for your desktop MCP client, run this command in Terminal.
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
"$HOME/Library/Application Support/Code60 Transmission/app/code60" mcp-config
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Copy the printed server entry into your client's MCP settings. For a client
|
|
65
|
+
with separate fields, use the printed absolute path as its stdio command and
|
|
66
|
+
leave the arguments empty. The first connection creates a private operator
|
|
67
|
+
token and configuration and starts one engine in your macOS login session.
|
|
68
|
+
Each client gets its own bridge. The engine stays running after clients close.
|
|
69
|
+
|
|
70
|
+
Private configuration, token, database, and engine log live together in
|
|
71
|
+
`~/Library/Application Support/Code60 Transmission/state/`, outside the installed
|
|
72
|
+
`app/` directory. The default API port is `31260`. If that port is in use,
|
|
73
|
+
set `listenPort` in `state/configuration.json` to a free port and reconnect.
|
|
74
|
+
The bridge reads the same setting. The initial deployment supports operator
|
|
75
|
+
setup. To run coding-agent steps, configure the Codex CLI and a model provider
|
|
76
|
+
as described in [Configure and run](#configure-and-run). Git workspace operations
|
|
77
|
+
use Apple's Command Line Tools Git and your configured author identity.
|
|
78
|
+
|
|
79
|
+
Before an upgrade or a configuration reload, let active runs finish, disconnect
|
|
80
|
+
the clients, and stop the loaded engine.
|
|
81
|
+
|
|
82
|
+
```sh
|
|
83
|
+
launchctl bootout "gui/$(id -u)/com.codemanufactory.code60.transmission"
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Install the new package or edit the private configuration, then reconnect.
|
|
87
|
+
Reinstalling updates the application and preserves the private state.
|
|
88
|
+
|
|
89
|
+
## Build the macOS installer
|
|
90
|
+
|
|
91
|
+
On a build Mac of the target architecture, use the official unpacked Node
|
|
92
|
+
24.22.0 or newer 24.x distribution (including its `LICENSE`), npm, and Apple's
|
|
93
|
+
Command Line Tools.
|
|
94
|
+
|
|
95
|
+
```sh
|
|
96
|
+
npm ci
|
|
97
|
+
npm run package:macos
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The output is `dist/installers/Code60-Transmission-<version>-<arch>.pkg`.
|
|
101
|
+
The build stages a fresh TypeScript compilation, native helpers, and locked
|
|
102
|
+
production dependencies. It checks architecture, deployment targets, dynamic
|
|
103
|
+
library paths, and the bundled SQLite binding. The default build is unsigned
|
|
104
|
+
for local testing. For a public release, set `APPLICATION_SIGN_IDENTITY` and
|
|
105
|
+
`INSTALLER_SIGN_IDENTITY` to your Developer ID Application and Installer
|
|
106
|
+
identities, and set `NOTARY_PROFILE` to your notarytool Keychain profile.
|
|
107
|
+
The same build command then signs the native code and package, submits it to
|
|
108
|
+
Apple, staples the ticket, and checks Gatekeeper acceptance.
|
|
109
|
+
|
|
110
|
+
In a separate macOS login account with port 31260 available and no installed
|
|
111
|
+
Transmission engine, run `node scripts/smoke-macos-package.mjs /absolute/path/to/the.pkg`.
|
|
112
|
+
It checks the installer domain and exercises the extracted payload with two MCP
|
|
113
|
+
clients and a real per-user engine, then removes its temporary service and files.
|
|
114
|
+
|
|
115
|
+
## Requirements for building from source
|
|
116
|
+
|
|
117
|
+
- macOS, for the native containment used by the runtime and helpers.
|
|
118
|
+
- Node.js **24.22.0 or newer in the 24.x line**, and npm.
|
|
119
|
+
- An installed Codex CLI with `app-server` support.
|
|
120
|
+
- Xcode Command Line Tools (`/usr/bin/clang`), including a C toolchain, and Git
|
|
121
|
+
with your existing author identity available for workspace commits.
|
|
122
|
+
|
|
123
|
+
## Install and build
|
|
124
|
+
|
|
125
|
+
From the checkout:
|
|
126
|
+
|
|
127
|
+
```sh
|
|
128
|
+
npm ci
|
|
129
|
+
npm run build
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
The build emits TypeScript **and compiles both C helpers** into
|
|
133
|
+
`dist/src/broker/native/.build/`. Starting the server does not build them.
|
|
134
|
+
|
|
135
|
+
## Configure and run
|
|
136
|
+
|
|
137
|
+
For a complete first run with a real model, follow
|
|
138
|
+
[the hello-world example](examples/hello-world/README.md). After building and
|
|
139
|
+
setting `OPENROUTER_API_KEY`, run `npm run example:hello-world`. It creates its
|
|
140
|
+
own disposable Git workspace and private configuration, runs the workflow,
|
|
141
|
+
checks the artifact and acceptance commit, and stops the server.
|
|
142
|
+
|
|
143
|
+
Start with [examples/deployment.local.json](examples/deployment.local.json).
|
|
144
|
+
It contains no secrets, leaves the runtime disabled, and denies all tool access.
|
|
145
|
+
Uppercase `REPLACE_WITH_...` values are placeholders. Before enabling the runtime,
|
|
146
|
+
set your Codex executable's absolute path, the local model ID/effort, and an unused
|
|
147
|
+
loopback model port served by an owned Responses-compatible synthetic provider.
|
|
148
|
+
No model provider is started for you.
|
|
149
|
+
|
|
150
|
+
Keep state and private files outside the checkout. For a **new** state directory:
|
|
151
|
+
|
|
152
|
+
```sh
|
|
153
|
+
ROOT="$(pwd -P)"
|
|
154
|
+
STATE="$HOME/code60-engine-state"
|
|
155
|
+
mkdir -m 700 "$STATE" &&
|
|
156
|
+
install -m 600 examples/deployment.local.json "$STATE/configuration.json" &&
|
|
157
|
+
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"
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Edit that private configuration copy. Keep it and the token owned by your user,
|
|
161
|
+
mode `0600`, without symlinks or hardlinks. The state directory must be `0700`.
|
|
162
|
+
Never put the token in configuration JSON, command arguments or Git.
|
|
163
|
+
|
|
164
|
+
```sh
|
|
165
|
+
npm start -- \
|
|
166
|
+
--state-directory "$STATE" \
|
|
167
|
+
--fs-helper "$ROOT/dist/src/broker/native/.build/fs-helper" \
|
|
168
|
+
--git-helper "$ROOT/dist/src/broker/native/.build/git-helper" \
|
|
169
|
+
--configuration "$STATE/configuration.json" \
|
|
170
|
+
--operator-token-file "$STATE/operator.token"
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
All five paths must be absolute. With the example ports, the authenticated API
|
|
174
|
+
is at `http://127.0.0.1:31260/api/v1`. There is no unauthenticated health route or
|
|
175
|
+
automatic login. Read the private token in your API client, then follow the
|
|
176
|
+
[operator walkthrough and recovery rules](README.engine.md#operator-api-walkthrough)
|
|
177
|
+
to register an explicitly authorized Git workspace, publish profiles/workflows,
|
|
178
|
+
and start a run. The disabled example supports API setup, not agent execution.
|
|
179
|
+
|
|
180
|
+
## Connect an agent over MCP
|
|
181
|
+
|
|
182
|
+
Start the Transmission Server with your private deployment configuration, then
|
|
183
|
+
configure your MCP client to launch the built stdio bridge. For clients that use
|
|
184
|
+
an `mcpServers` configuration, replace both absolute paths and use the engine's
|
|
185
|
+
configured port.
|
|
186
|
+
|
|
187
|
+
```json
|
|
188
|
+
{
|
|
189
|
+
"mcpServers": {
|
|
190
|
+
"code60": {
|
|
191
|
+
"command": "node",
|
|
192
|
+
"args": [
|
|
193
|
+
"/absolute/path/to/code60-transmission-server/dist/src/mcp/main.js",
|
|
194
|
+
"--port", "31260",
|
|
195
|
+
"--operator-token-file", "/absolute/path/to/private/operator.token"
|
|
196
|
+
]
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
The client launches one bridge per connection. The bridge reads the private token
|
|
203
|
+
file on startup and authenticates to the engine on IPv4 loopback. The agent can
|
|
204
|
+
exercise the configured operator’s authority, including approval decisions and
|
|
205
|
+
recovery. Workspace registration requires an unrestricted operator. To execute
|
|
206
|
+
agent steps, enable and configure the deployment runtime.
|
|
207
|
+
|
|
208
|
+
1. Discover runtimes and named checks, then register an authorized worktree with
|
|
209
|
+
`create_workspace`. Publish a worker with `create_agent_profile`.
|
|
210
|
+
2. Read the MCP resources `code60://workflow/schema` and
|
|
211
|
+
`code60://workflow/example`. Replace the example’s worker placeholder with
|
|
212
|
+
the profile’s `latestVersionId`. Pass the YAML or JSON source and any bundled
|
|
213
|
+
resources to `validate_workflow`, then publish with `create_workflow`.
|
|
214
|
+
3. Call `create_run` with a unique `idempotencyKey` and a `body` containing
|
|
215
|
+
`workspaceId` and the workflow’s `latestVersionId` as `workflowVersionId`.
|
|
216
|
+
Save the returned `body.id`. A 202 response means the engine admitted the run.
|
|
217
|
+
4. Read `get_run` or call `list_run_events` with `runId`, `follow: true`,
|
|
218
|
+
and `waitSeconds: 30`. Reuse each `body.nextCursor` as `cursor` on the next
|
|
219
|
+
poll, including after reconnecting. Inspect approvals, blocks, and artifacts
|
|
220
|
+
through their list and get tools. Closing the MCP client leaves the engine
|
|
221
|
+
running.
|
|
222
|
+
|
|
223
|
+
Tools return the HTTP `status` and engine `body` in structured content and text,
|
|
224
|
+
plus `etag`, `location`, and `idempotentReplay` when available. All POST tools
|
|
225
|
+
take `body` and `idempotencyKey`. Reuse the same arguments after a lost response.
|
|
226
|
+
For a conditional command, pass the target read’s `etag` as `ifMatch`. On a
|
|
227
|
+
stale-version error, reread the target before making a new decision. Poll
|
|
228
|
+
`get_operation` for asynchronous operator commands.
|
|
229
|
+
|
|
230
|
+
## Workflow examples
|
|
231
|
+
|
|
232
|
+
- [Hello world](examples/hello-world/README.md): run a real agent, validate its
|
|
233
|
+
artifact, and verify the accepted Git commit. Run `npm run example:hello-world`.
|
|
234
|
+
- [Pull request lifecycle](examples/pull-request/README.md): clone the disposable
|
|
235
|
+
GitHub repository, create a worktree, make an agent change, push/open/merge a
|
|
236
|
+
PR, and delete the worktree. Run `npm run example:pull-request`.
|
|
237
|
+
|
|
238
|
+
## Browse the API specification
|
|
239
|
+
|
|
240
|
+
With Docker running, start Swagger UI:
|
|
241
|
+
|
|
242
|
+
```sh
|
|
243
|
+
npm run docs:api
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Open [http://localhost:8080](http://localhost:8080) to browse the OpenAPI specification.
|
|
247
|
+
The API server does not need to be running. Press Ctrl+C to stop the viewer and
|
|
248
|
+
remove its container. The first run downloads the Swagger UI image.
|
|
249
|
+
|
|
250
|
+
## Tests
|
|
251
|
+
|
|
252
|
+
```sh
|
|
253
|
+
npm run typecheck
|
|
254
|
+
npm test -- --maxWorkers=1
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
`npm test` builds its own native helpers before running the suite, including the
|
|
258
|
+
normal-entrypoint and restart tests. Installed-runtime tests use
|
|
259
|
+
`CODE60_CODEX_EXECUTABLE` (an explicit absolute executable path) first, otherwise
|
|
260
|
+
look for `codex` on `PATH`; absence is a clear test failure, not a silent skip.
|
|
261
|
+
No Codex configuration or credentials are read by that lookup. To run just the
|
|
262
|
+
runtime pilot, use `npm run test:pilot -- --maxWorkers=1`. Run native builds/tests
|
|
263
|
+
serially. Preserved-image mode is optional, not needed for a fresh clone.
|
|
264
|
+
See [validation details](README.engine.md#validation) for focused checks.
|
|
265
|
+
|
|
266
|
+
## Limits
|
|
267
|
+
|
|
268
|
+
- The [hello-world example](examples/hello-world/README.md) has live validation
|
|
269
|
+
through OpenRouter with GPT-5.3-Codex. Other provider/model combinations need
|
|
270
|
+
their own validation; the normal automated suite uses synthetic providers.
|
|
271
|
+
- Single host, one coordinator per state directory, loopback API only. No
|
|
272
|
+
multi-host service, public ingress or browser login is supplied.
|
|
273
|
+
- Initial broker tools: `read_file`, `write_file`, `list_files`, `search_files`,
|
|
274
|
+
`move_file`, `delete_file`, and `http_request`, subject to profile and outer
|
|
275
|
+
deployment policy. No shell/process tool, arbitrary Git commands, browser/UI
|
|
276
|
+
tools, directory move/delete, or unrestricted host/network access.
|
|
277
|
+
- Containment is macOS-only. Preserved-image test success does not establish
|
|
278
|
+
clean-build, sanitizer or cross-platform support.
|
|
279
|
+
|
|
280
|
+
See [README.engine.md](README.engine.md) for configuration, API, authorization,
|
|
281
|
+
instruction pinning, deadlines and recovery details.
|
|
282
|
+
|
|
283
|
+
## Repository skills
|
|
284
|
+
|
|
285
|
+
Use `$add-workflow-example` to add or revise a runnable example with setup
|
|
286
|
+
instructions and end-to-end verification. The
|
|
287
|
+
[repository skill](.agents/skills/add-workflow-example/SKILL.md) describes the
|
|
288
|
+
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
|
+
}
|