code60-transmission-server 0.1.0-staging.3 → 0.1.0-staging.6

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 (36) hide show
  1. package/README.engine.md +64 -2
  2. package/README.md +66 -5
  3. package/dist/src/broker/native/README.md +15 -0
  4. package/dist/src/broker/native/build.js +3 -0
  5. package/dist/src/broker/native/command-helper.c +93 -0
  6. package/dist/src/cli/configure.js +193 -0
  7. package/dist/src/cli/daemon.js +5 -1
  8. package/dist/src/cli/helpers.js +12 -4
  9. package/dist/src/cli/main.js +12 -3
  10. package/dist/src/cli/runtime-build.js +38 -0
  11. package/dist/src/config/coding-policy.js +4 -0
  12. package/dist/src/config/deployment.js +26 -10
  13. package/dist/src/config/workflow-schema.json +11 -0
  14. package/dist/src/engine/commands.js +35 -4
  15. package/dist/src/engine/workflow-engine.js +70 -15
  16. package/dist/src/main.js +4 -1
  17. package/dist/src/mcp/main.js +4 -2
  18. package/dist/src/mcp/server.js +37 -6
  19. package/dist/src/runtime/engine-driver.js +11 -2
  20. package/dist/src/runtime/provider-bridge.js +4 -2
  21. package/dist/src/runtime/provider-transport.js +7 -5
  22. package/dist/src/server/api-contract.json +530 -2
  23. package/dist/src/server/application.js +9 -3
  24. package/dist/src/server/coding.js +254 -0
  25. package/dist/src/server/deployment.js +18 -6
  26. package/dist/src/server/history-handlers.js +16 -2
  27. package/dist/src/server/workspace-handlers.js +1 -1
  28. package/dist/src/tools/checks.js +12 -1
  29. package/dist/src/tools/command-check.js +34 -0
  30. package/dist/src/tools/commands.js +310 -0
  31. package/dist/src/tools/developer.js +351 -0
  32. package/dist/src/tools/index.js +19 -2
  33. package/dist/src/workspaces/index.js +244 -22
  34. package/dist/src/workspaces/source.js +295 -0
  35. package/package.json +4 -2
  36. package/scripts/postinstall.mjs +2 -1
package/README.engine.md CHANGED
@@ -298,8 +298,70 @@ the workflow's schema-fetch deadline. An explicitly configured `schemaHttp`
298
298
  `timeoutMs` is a deployment transport bound and must cover permitted fetch times.
299
299
 
300
300
  Named checks are deployment registrations with `id`, `description`, `version`
301
- and one fixed `predicate`: `text_includes`, `json_pointer_equals` or `json_schema`.
302
- There is no shell, arbitrary script/module loading or model-authored check code.
301
+ and either a fixed artifact `predicate` or a `command` with optional `cwd`, `env`
302
+ and `timeoutMs`. Command checks execute through the broker-owned command runner,
303
+ with source read-only. Declared generated/cache paths require profile and
304
+ deployment write authority; a read-only profile does not gain cache write access.
305
+ Passing evidence is pinned to the exact source revision and command definition. Changing source
306
+ requires fresh checks. Model-authored commands do not become acceptance checks.
307
+
308
+ ## Coding tasks
309
+
310
+ `POST /coding-tasks` accepts `task`, `repositoryPath` or `workspaceId`, optional
311
+ immutable `inputs`/`inputArtifacts`, a profile version, and command-check overrides.
312
+ The caller's idempotency key covers workspace/profile/workflow/run setup, including
313
+ reconnects. The default preset detects package-manager scripts named `typecheck`,
314
+ `lint`, `test`, and `build` and runs them with `CI=1`. Supply explicit commands for
315
+ other ecosystems or scripts that need noninteractive flags. Dependencies can be
316
+ installed by the worker; ignored dependency trees are not source checkpoints.
317
+
318
+ `GET /readiness` reports local setup, an actual contained app-server handshake,
319
+ command capabilities, quotas, and separately unverified provider authentication.
320
+ Use `code60 configure` and `code60 doctor` for setup. `commands.enabled` is false
321
+ for existing deployments unless configured. New coding configurations enable
322
+ general outbound access; `commands.network: none` selects offline execution.
323
+
324
+ `GET /runs/{runId}/result` returns the run-only diff, changed files, command logs,
325
+ check evidence, diagnostics, and `verified`, `pending_or_failed`, or `unverified`
326
+ status. Patch/output cursors count bytes and support bounded reads. Command output
327
+ also includes Base64 bytes for exact reconstruction across UTF-8 boundaries.
328
+ To inspect a command log, call `get_coding_task_result` with `runId`, `commandId`,
329
+ `stream`, `outputCursor`, and `outputLimit`; the HTTP result endpoint accepts
330
+ the same query parameters. Pending questions survive daemon shutdown; answer
331
+ them before recovering the interrupted conversation. Answers remain available
332
+ to the replacement worker through its context manifest.
333
+ `sourceQuotas`, command deadlines/output limits, and `contextBytes` are explicit
334
+ deployment settings. Supplemental model context defaults to 64 KiB; retrieval
335
+ tools expose pinned artifacts, schemas, history, messages, and immutable inputs.
336
+
337
+ New HTTP workspace registrations use Git-aware manifests by default. Linked
338
+ worktrees and binary/symlink source entries are supported. Historical checkpoints
339
+ remain readable. Starting a coding task upgrades an
340
+ existing idle registration to Git-aware tracking without changing working files;
341
+ active leases cannot be upgraded. Declared generated paths exclude untracked
342
+ output even when the project has no matching ignore rule; tracked files always
343
+ remain source. `sourceTracking: false` explicitly selects the legacy native format.
344
+ An existing commit is required. Submodules and unsupported entry types fail
345
+ preflight rather than being silently omitted.
346
+
347
+ `POST /runs/{runId}/messages` queues steering before acceptance. Worker questions
348
+ appear in `/runs/{runId}/questions` and the run's `inputWait`; answer through
349
+ `POST /questions/{questionId}/answers`. Questions retain the conversation and
350
+ freeze execution accounting without consuming submissions. Absolute authored
351
+ deadlines remain hard bounds. Restarted conversations require explicit recovery.
352
+
353
+ Coding tasks default to `resultMode: working_tree`, preserving HEAD and the
354
+ index. The starting dirty source state is the rollback baseline; ignored caches
355
+ are retained. Explicit `resultMode: commit` requires a clean source baseline.
356
+ Legacy commit-based workflows keep their original default.
357
+
358
+ If command settlement is uncertain, inspect the result's recovery preview and
359
+ provide `commandResolution: { sourceDigest, action }` to `recover_run` (or the
360
+ HTTP recovery endpoint). `action` is `preserve_changes` or `rollback`. The engine
361
+ requires stopped processes, the exact current preview digest, and unchanged Git
362
+ metadata before adopting or restoring command changes. It never resends the old
363
+ command automatically. Concurrent external edits during writing commands cannot
364
+ be reliably attributed; pause/stop commands before editing the project elsewhere.
303
365
 
304
366
  ## Ownership and recovery
305
367
 
package/README.md CHANGED
@@ -2,10 +2,59 @@
2
2
 
3
3
  A local workflow server for running bounded coding-agent steps against a Git
4
4
  workspace. It stores workflow state, approvals and tool authority in SQLite,
5
- brokers file/network access, and accepts evaluated results as Git commits.
5
+ brokers file, command and network access, and returns verified coding changes
6
+ as an uncommitted diff. Low-level workflows also support Git commit results.
7
+
8
+ From this checkout, run `npm run build`, then use `node dist/src/cli/main.js`
9
+ in place of `npx -y code60-transmission-server` in the commands below.
6
10
 
7
11
  ## Run with npx (MCP)
8
12
 
13
+ For coding tasks, configure the installed Codex executable, provider/model, and
14
+ an existing private API-key file once:
15
+
16
+ ```sh
17
+ npx -y code60-transmission-server configure --executable /absolute/path/to/codex --provider openrouter --model openai/gpt-5.3-codex --credential-file /absolute/path/to/provider.token
18
+ npx -y code60-transmission-server doctor --repository /absolute/path/to/project
19
+ ```
20
+
21
+ `configure` also offers interactive prompts when run in a terminal. It enables
22
+ brokered commands with outbound networking and discovers installed toolchain
23
+ directories. It does not import your Codex login or ambient API keys.
24
+ `doctor --check-provider` explicitly makes a small billable model request;
25
+ ordinary readiness checks do not claim that provider authentication was verified.
26
+
27
+ The default MCP toolset is the compact coding interface. Call
28
+ `get_coding_readiness`, then `start_coding_task` with a stable `idempotencyKey`
29
+ and `body: { repositoryPath, task }`. Existing staged, unstaged, and untracked
30
+ source changes become the baseline. Workers can inspect/edit source, run builds
31
+ and tests, ask questions, and receive `send_task_message` guidance. Inspect
32
+ `get_run` and `get_coding_task_result` for the diff and executable check evidence.
33
+ Successful coding tasks leave HEAD and staging unchanged and edits uncommitted.
34
+
35
+ For an existing deployment, stop its daemon and run `code60 configure --coding-only`
36
+ to enable coding tools and outbound commands while preserving its provider,
37
+ model, credential references, and runtime settings. Profile permissions and
38
+ deployment permissions both apply: a profile cannot override a deployment deny.
39
+ `doctor` reports missing deployment grants before a task spends model tokens.
40
+
41
+ After upgrading, stop the old daemon and reconnect your MCP client. The launcher
42
+ detects mismatched engine builds and reports the restart command; it preserves
43
+ runs and never automatically replaces a running engine. `mcp-config` pins the
44
+ installed package version, including prereleases, so a staging installation does
45
+ not silently generate a client configuration for the stable release. Select
46
+ `code60-transmission-server@staging` explicitly when testing the staging release.
47
+ Tasks without executable checks explicitly report `unverified`.
48
+
49
+ Use `--toolset admin` to advertise the complete workflow/profile administration
50
+ catalog. Existing low-level calls remain dispatchable in either toolset. Their
51
+ default result mode remains automatic commits; select `resultMode: working_tree`
52
+ to accept a revision without committing. Commit mode requires clean source.
53
+
54
+ The [coding-task example](examples/coding-task/README.md) demonstrates a real bug
55
+ reproduction, fix, regression test, build, and preservation of existing work:
56
+ `npm run example:coding-task`.
57
+
9
58
  On macOS with Node.js **24.22.0 or newer in the 24.x line** and Xcode Command
10
59
  Line Tools (`/usr/bin/clang` and Git), any MCP client can start and connect to
11
60
  the server directly via `npx` — no separate daemon startup is required:
@@ -71,6 +120,10 @@ leave the arguments empty. The first connection creates a private operator
71
120
  token and configuration and starts one engine in your macOS login session.
72
121
  Each client gets its own bridge. The engine stays running after clients close.
73
122
 
123
+ The installed launcher also supports `configure`, `doctor`, `status`, and
124
+ `stop`. Run `code60 stop` before reconfiguring a running installation, then
125
+ reconnect the MCP client. Use `code60 mcp --toolset admin` for the full catalog.
126
+
74
127
  Private configuration, token, database, and engine log live together in
75
128
  `~/Library/Application Support/Code60 Transmission/state/`, outside the installed
76
129
  `app/` directory. The default API port is `31260`. If that port is in use,
@@ -277,10 +330,18 @@ See [validation details](README.engine.md#validation) for focused checks.
277
330
  their own validation; the normal automated suite uses synthetic providers.
278
331
  - Single host, one coordinator per state directory, loopback API only. No
279
332
  multi-host service, public ingress or browser login is supplied.
280
- - Initial broker tools: `read_file`, `write_file`, `list_files`, `search_files`,
281
- `move_file`, `delete_file`, and `http_request`, subject to profile and outer
282
- deployment policy. No shell/process tool, arbitrary Git commands, browser/UI
283
- tools, directory move/delete, or unrestricted host/network access.
333
+ - Broker tools include file/range reads, precise edits, directory creation,
334
+ paginated search/diffs, sandboxed commands and their input/output/stop controls,
335
+ questions, context retrieval, and `http_request`. Profile and deployment policy
336
+ both apply. Commands may use configured toolchains and outbound networking;
337
+ host credentials, engine state, and command writes to Git metadata are denied.
338
+ - Git-aware source tracking excludes ignored dependencies/build output and uses
339
+ streamed content-addressed checkpoints. Default source quotas are 100,000
340
+ entries, 1 GiB per file, and 10 GiB of unique source content per run. Configure
341
+ `sourceQuotas` to change these explicit operational bounds.
342
+ - Working-folder runs require exclusive source editing while commands execute.
343
+ Same-user external filesystem races are not a mandatory isolation boundary;
344
+ detected conflicts and uncertain commands retain their leases for recovery.
284
345
  - Containment is macOS-only. Preserved-image test success does not establish
285
346
  clean-build, sanitizer or cross-platform support.
286
347
 
@@ -1,5 +1,20 @@
1
1
  # Descriptor-relative filesystem helper
2
2
 
3
+ The native directory also contains `command-helper`, the macOS command
4
+ supervisor. It starts the command behind a handshake, verifies two unique
5
+ sandbox policy probes, and enumerates processes carrying that inherited policy
6
+ identity. This includes children that detach or become reparented. Cancellation
7
+ signals those processes and escalates to SIGKILL; the supervisor retains the
8
+ startup barrier until settlement. Private fd4 carries settlement proof; command
9
+ children cannot write to it. Missing proof retains an uncertain lease.
10
+
11
+ This uses macOS `libproc` and the sandbox policy-query SPI (as also used by
12
+ [WebKit](https://github.com/WebKit/WebKit/blob/main/Source/WebCore/testing/Internals.cpp)).
13
+ It requires a supported host implementation and fails closed when the policy
14
+ identity cannot be confirmed. Automatic kqueue `NOTE_TRACK` is unavailable on
15
+ supported macOS. Process enumeration and source-boundary checks do not provide
16
+ isolation from a hostile same-user host process.
17
+
3
18
  This is a small unprivileged POSIX helper for the TypeScript broker, not a general
4
19
  shell, filesystem daemon, sandbox, or server. The catalog implements **read_file**,
5
20
  **write_file**, **list_files**, **search_files**, **delete_file** and **move_file**.
@@ -9,6 +9,9 @@ export function buildFilesystemHelper(options = {}) {
9
9
  export function buildGitHelper(options = {}) {
10
10
  return build("git", options);
11
11
  }
12
+ export function buildCommandHelper(options = {}) {
13
+ return build("command", options);
14
+ }
12
15
  function build(kind, options) {
13
16
  const directory = fileURLToPath(new URL("./", import.meta.url));
14
17
  const outDir = options.outputDirectory ?? join(directory, ".build");
@@ -0,0 +1,93 @@
1
+ /* macOS command supervisor. Each command has two random sandbox policy probes:
2
+ * allow one Mach name, deny the other. Unsandboxed processes allow both; other
3
+ * sandboxes deny both. Descendants inherit this identity across exec/setsid and
4
+ * reparenting. No service is registered or contacted by these policy probes.
5
+ * fd4 is a parent-only engine status pipe; fd3 retains the startup barrier.
6
+ * Neither descriptor is inherited by the sandboxed worker.
7
+ */
8
+ #include <sys/wait.h>
9
+ #include <sys/proc_info.h>
10
+ #include <libproc.h>
11
+ #include <unistd.h>
12
+ #include <signal.h>
13
+ #include <errno.h>
14
+ #include <stdio.h>
15
+ #include <stdlib.h>
16
+ #include <fcntl.h>
17
+ #include <dlfcn.h>
18
+ #include <time.h>
19
+ #include <poll.h>
20
+ #include <string.h>
21
+
22
+ typedef int (*check_fn)(pid_t, const char *, int, ...);
23
+ static check_fn policy_check;
24
+ static int probe_flags;
25
+ static volatile sig_atomic_t stopping;
26
+ static void stop_handler(int signo) { (void)signo; stopping = 1; }
27
+ static long long millis(void) { struct timespec t; if (clock_gettime(CLOCK_MONOTONIC, &t)) return 0; return (long long)t.tv_sec * 1000 + t.tv_nsec / 1000000; }
28
+ static int marked(pid_t pid, const char *allow, const char *deny) {
29
+ return policy_check(pid, "mach-lookup", probe_flags, allow) == 0 && policy_check(pid, "mach-lookup", probe_flags, deny) == 1;
30
+ }
31
+ static void proof(int settled, int code) { (void)dprintf(4, "{\"settled\":%s,\"exitCode\":%d}\n", settled ? "true" : "false", code); }
32
+ int main(int argc, char **argv) {
33
+ if (argc > 2 && !strcmp(argv[1], "--worker")) {
34
+ char byte = 'R'; if (write(5, &byte, 1) != 1 || read(6, &byte, 1) != 1) return 125;
35
+ close(5); close(6); signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL);
36
+ execv(argv[2], argv + 2); return 127;
37
+ }
38
+ if (argc < 3 || argv[2][0] != '/') return 125;
39
+ const pid_t owner = getppid(); if (owner <= 1) return 125;
40
+ policy_check = (check_fn)dlsym(RTLD_DEFAULT, "sandbox_check");
41
+ const int *no_report = (const int *)dlsym(RTLD_DEFAULT, "SANDBOX_CHECK_NO_REPORT");
42
+ if (!policy_check || !no_report) { proof(0, 125); return 125; }
43
+ probe_flags = 2 | *no_report; /* SANDBOX_FILTER_GLOBAL_NAME */
44
+ char allow[256], deny[256];
45
+ if (snprintf(allow, sizeof(allow), "code60.command.%s.allow", argv[1]) >= (int)sizeof(allow) || snprintf(deny, sizeof(deny), "code60.command.%s.deny", argv[1]) >= (int)sizeof(deny)) return 125;
46
+ struct sigaction action = {0}; action.sa_handler = stop_handler; sigemptyset(&action.sa_mask);
47
+ if (sigaction(SIGTERM, &action, NULL) || sigaction(SIGINT, &action, NULL)) return 125;
48
+ if (dprintf(4, "{\"ready\":true}\n") < 0) return 125;
49
+ int ready[2], gate[2]; if (pipe(ready) || pipe(gate)) return 125;
50
+ pid_t child = fork(); if (child < 0) return 125;
51
+ if (!child) {
52
+ int r = fcntl(ready[1], F_DUPFD, 10), g = fcntl(gate[0], F_DUPFD, 10); if (r < 0 || g < 0) _exit(125);
53
+ close(ready[0]); close(ready[1]); close(gate[0]); close(gate[1]); close(4); close(3);
54
+ if (dup2(r, 5) != 5 || dup2(g, 6) != 6) _exit(125); close(r); close(g);
55
+ signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL); execv(argv[2], argv + 2); _exit(127);
56
+ }
57
+ close(ready[1]); close(gate[0]);
58
+ int status = 0, exited = 0, uncertain = 0, confirmed = 0; long long started = millis(), stop_at = 0;
59
+ while (!confirmed) {
60
+ if (getppid() != owner) { stopping = 1; break; }
61
+ struct pollfd p = { .fd = ready[0], .events = POLLIN }; int n = poll(&p, 1, 20);
62
+ if (n > 0 && (p.revents & POLLIN)) { char byte; if (read(ready[0], &byte, 1) == 1 && marked(child, allow, deny)) confirmed = 1; else uncertain = 1; break; }
63
+ pid_t waited = waitpid(child, &status, WNOHANG); if (waited == child) { exited = 1; break; }
64
+ if (stopping) break; /* The worker is still gated; no command has run. */
65
+ if (millis() - started > 10000 || (n < 0 && errno != EINTR)) { uncertain = 1; break; }
66
+ }
67
+ close(ready[0]); if (confirmed) { char byte = 'G'; if (write(gate[1], &byte, 1) != 1) uncertain = 1; } close(gate[1]);
68
+ if (!confirmed && !exited) { kill(child, SIGKILL); waitpid(child, &status, 0); exited = 1; }
69
+ int capacity = 4096, empty = 0; pid_t *pids = calloc((size_t)capacity, sizeof(pid_t)); if (!pids) uncertain = 1;
70
+ while (confirmed && pids) {
71
+ if (getppid() != owner) stopping = 1;
72
+ int needed = proc_listallpids(NULL, 0); if (needed < 0) { uncertain = 1; break; }
73
+ if (needed + 256 > capacity) { capacity = needed + 1024; pid_t *next = realloc(pids, (size_t)capacity * sizeof(pid_t)); if (!next) { uncertain = 1; break; } pids = next; }
74
+ int n = proc_listallpids(pids, capacity * (int)sizeof(pid_t)); if (n < 0 || n >= capacity) { uncertain = 1; break; }
75
+ if (stopping && !stop_at) stop_at = millis();
76
+ int active = 0;
77
+ for (int i = 0; i < n; i++) {
78
+ struct proc_bsdinfo info; if (pids[i] <= 1 || pids[i] == getpid()) continue;
79
+ if (proc_pidinfo(pids[i], PROC_PIDTBSDINFO, 0, &info, sizeof(info)) != sizeof(info) || info.pbi_uid != geteuid() || info.pbi_status == 5) continue;
80
+ if (!marked(pids[i], allow, deny)) continue;
81
+ active++; if (stopping) { /* Recheck the label immediately before signaling. */
82
+ if (marked(pids[i], allow, deny)) kill(pids[i], millis() - stop_at < 400 ? SIGTERM : SIGKILL);
83
+ }
84
+ }
85
+ if (!exited && waitpid(child, &status, WNOHANG) == child) exited = 1;
86
+ if (exited && !active) { if (++empty == 3) break; } else empty = 0;
87
+ struct timespec delay = { .tv_sec = 0, .tv_nsec = 20000000 }; nanosleep(&delay, NULL);
88
+ }
89
+ free(pids);
90
+ if (!exited) { kill(child, SIGKILL); while (waitpid(child, &status, 0) < 0) if (errno != EINTR) break; }
91
+ int code = WIFEXITED(status) ? WEXITSTATUS(status) : 128 + (WIFSIGNALED(status) ? WTERMSIG(status) : 0);
92
+ proof(!uncertain, code); return uncertain ? 125 : 0;
93
+ }
@@ -0,0 +1,193 @@
1
+ import { accessSync, constants, existsSync, lstatSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync, renameSync } from 'node:fs';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { getServers } from 'node:dns';
4
+ import { isIP } from 'node:net';
5
+ import { basename, dirname, isAbsolute, join } from 'node:path';
6
+ import { parseArgs } from 'node:util';
7
+ import { createInterface } from 'node:readline/promises';
8
+ import { defaultStateDirectory, initializeStateDirectory, findRunningEngine } from './daemon.js';
9
+ import { defaultTemplateConfigurationPath, resolveNativeHelpers } from './helpers.js';
10
+ import { loadDeploymentConfiguration, readPrivateFile } from '../config/deployment.js';
11
+ import { DEVELOPER_DEFINITIONS } from '../tools/developer.js';
12
+ import { DEFAULT_COMMAND_SETTINGS } from '../tools/commands.js';
13
+ import { ContainedCodexAppServer, pilotCodexConfig } from '../runtime/codex-app-server.js';
14
+ import { ValidationPool } from '../config/validation-pool.js';
15
+ import Database from 'better-sqlite3';
16
+ import { SqliteCoordinator } from '../storage/coordinator.js';
17
+ import { ProviderTransport } from '../runtime/provider-transport.js';
18
+ import { ProviderCredentials } from '../runtime/provider-credentials.js';
19
+ import { missingCodingPermissions } from '../config/coding-policy.js';
20
+ import { assertRuntimeBuild } from './runtime-build.js';
21
+ const usage = `Usage:
22
+ code60 configure [--state-directory PATH] [--executable PATH] [--provider openrouter|openai|local] [--endpoint HTTPS_URL] [--model MODEL] [--credential-file PATH] [--toolchain PATH ...]
23
+ code60 doctor [--state-directory PATH] [--repository PATH] [--check-provider]
24
+ Use configure --coding-only to enable coding tools and commands while preserving all runtime, provider, model, and credential settings.
25
+ Credentials are read from an existing private file, never from command arguments or ambient logins.
26
+ `;
27
+ const which = (name) => { try {
28
+ return realpathSync(execFileSync('/usr/bin/which', [name], { encoding: 'utf8', timeout: 3000 }).trim());
29
+ }
30
+ catch {
31
+ return undefined;
32
+ } };
33
+ export async function configurationCli(argv) {
34
+ const command = argv[0];
35
+ const { values } = parseArgs({ args: argv.slice(1), options: { help: { type: 'boolean' }, 'state-directory': { type: 'string' }, 'coding-only': { type: 'boolean' }, executable: { type: 'string' }, provider: { type: 'string' }, endpoint: { type: 'string' }, model: { type: 'string' }, 'credential-file': { type: 'string' }, toolchain: { type: 'string', multiple: true }, repository: { type: 'string' }, 'check-provider': { type: 'boolean' } } });
36
+ if (values.help) {
37
+ process.stdout.write(usage);
38
+ return;
39
+ }
40
+ if (values['coding-only'] && (command !== 'configure' || ['executable', 'provider', 'endpoint', 'model', 'credential-file'].some(key => values[key] !== undefined)))
41
+ throw new Error('--coding-only preserves provider/runtime settings; do not combine it with provider or runtime selection flags.');
42
+ const paths = initializeStateDirectory(values['state-directory'] ?? defaultStateDirectory(), defaultTemplateConfigurationPath());
43
+ if (command === 'configure') {
44
+ if (findRunningEngine(paths.stateDirectory))
45
+ throw new Error('Stop this state directory’s engine with code60 stop before changing its configuration.');
46
+ const config = JSON.parse(readFileSync(paths.configurationFile, 'utf8'));
47
+ const readline = process.stdin.isTTY ? createInterface({ input: process.stdin, output: process.stdout }) : undefined;
48
+ try {
49
+ if (!values['coding-only']) {
50
+ const ask = async (label, value) => value ?? (readline ? (await readline.question(label + ': ')).trim() : undefined);
51
+ const executable = await ask('Absolute Codex executable path', values.executable ?? (existsSync(config.runtime.executable) ? config.runtime.executable : which('codex')));
52
+ if (!executable || !isAbsolute(executable))
53
+ throw new Error('Supply --executable with the absolute Codex executable path.');
54
+ accessSync(executable, constants.X_OK);
55
+ const provider = await ask('Provider (openrouter, openai, local)', values.provider ?? config.providers?.[0]?.id) ?? 'openrouter';
56
+ const model = await ask('Model ID', values.model ?? config.providers?.[0]?.models[0]?.id);
57
+ if (!model)
58
+ throw new Error('Supply --model with your provider’s model ID.');
59
+ config.runtime = { ...config.runtime, enabled: true, executable: realpathSync(executable), models: [{ id: model, effortLevels: ['low'] }] };
60
+ if (provider === 'local') {
61
+ delete config.providers;
62
+ delete config.providerCredentials;
63
+ }
64
+ else {
65
+ const endpoint = values.endpoint ?? (provider === 'openai' ? 'https://api.openai.com/v1/responses' : provider === 'openrouter' ? 'https://openrouter.ai/api/v1/responses' : undefined);
66
+ if (!endpoint || new URL(endpoint).protocol !== 'https:')
67
+ throw new Error('Select openai/openrouter or supply --endpoint with a fixed HTTPS Responses URL.');
68
+ const credentialFile = await ask('Absolute private credential-file path', values['credential-file'] ?? config.providerCredentials?.[0]?.file);
69
+ if (!credentialFile)
70
+ throw new Error('Supply --credential-file with an existing owned mode-0600 API-key file.');
71
+ readPrivateFile(credentialFile, 8192);
72
+ const resolver = getServers().find(server => isIP(server)) ?? '8.8.8.8';
73
+ config.providers = [{ id: provider, endpoint, maxRequestBytes: 67_108_864, timeoutMs: 120_000, dnsResolvers: [{ address: resolver, port: 53 }], models: [{ id: model, effortLevels: ['low'], defaultEffort: 'low' }], networkPolicy: { defaultEffect: 'deny', rules: [
74
+ { kind: 'network', protocol: 'https', host: '*', port: 443, effect: 'allow' }, { kind: 'network', protocol: 'udp', host: resolver, port: 53, effect: 'allow' }, { kind: 'network', protocol: 'tcp', host: resolver, port: 53, effect: 'allow' }
75
+ ] } }];
76
+ config.providerCredentials = [{ referenceId: 'coding-provider', version: 'configured-v1', providerId: provider, origin: new URL(endpoint).origin, file: realpathSync(credentialFile) }];
77
+ }
78
+ }
79
+ const discovered = ['node', 'npm', 'pnpm', 'yarn', 'bun', 'python3', 'cargo', 'go'].flatMap(name => {
80
+ const path = which(name);
81
+ if (!path)
82
+ return [];
83
+ const bin = dirname(path);
84
+ return [bin, ...(['node', 'python3', 'go'].includes(name) && basename(bin) === 'bin' || ['npm', 'pnpm', 'yarn'].includes(name) ? [dirname(bin)] : [])];
85
+ });
86
+ config.commands = { ...DEFAULT_COMMAND_SETTINGS, ...config.commands, enabled: true, network: 'outbound', toolchainPaths: [...new Set([...(config.commands?.toolchainPaths ?? []), ...discovered, ...(values.toolchain ?? [])])].map(p => realpathSync(p)) };
87
+ config.deploymentPolicy = { defaultEffect: 'deny', rules: [...config.deploymentPolicy.rules,
88
+ ...[...DEVELOPER_DEFINITIONS.keys()].map(toolId => ({ kind: 'tool', toolId, effect: 'allow' })),
89
+ { kind: 'filesystem', root: 'workspace', path: '.', recursive: true, operations: ['read', 'write', 'delete'], effect: 'allow' }] };
90
+ config.deploymentPolicy.rules = [...new Map(config.deploymentPolicy.rules.map(rule => [JSON.stringify(rule), rule])).values()];
91
+ config.contextBytes = 65_536;
92
+ const temporary = paths.configurationFile + `.${process.pid}.${Date.now()}.pending`;
93
+ writeFileSync(temporary, JSON.stringify(config, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
94
+ const db = new Database(':memory:'), pool = new ValidationPool(new SqliteCoordinator(db));
95
+ try {
96
+ await loadDeploymentConfiguration(temporary, pool);
97
+ renameSync(temporary, paths.configurationFile);
98
+ }
99
+ finally {
100
+ await pool.close();
101
+ db.close();
102
+ if (existsSync(temporary))
103
+ rmSync(temporary);
104
+ }
105
+ process.stdout.write(`Configured coding tasks in ${paths.configurationFile}. Run code60 doctor, then reconnect your MCP client.\n`);
106
+ }
107
+ finally {
108
+ readline?.close();
109
+ }
110
+ return;
111
+ }
112
+ const db = new Database(':memory:'), coordinator = new SqliteCoordinator(db), pool = new ValidationPool(coordinator);
113
+ const checks = [];
114
+ try {
115
+ const config = await loadDeploymentConfiguration(paths.configurationFile, pool);
116
+ checks.push({ name: 'configuration', status: 'pass' });
117
+ const running = findRunningEngine(paths.stateDirectory);
118
+ if (running) {
119
+ try {
120
+ assertRuntimeBuild(paths.stateDirectory, running.pid);
121
+ checks.push({ name: 'running_engine_version', status: 'pass' });
122
+ }
123
+ catch (error) {
124
+ checks.push({ name: 'running_engine_version', status: 'fail', detail: error.message });
125
+ }
126
+ }
127
+ try {
128
+ resolveNativeHelpers(paths.stateDirectory);
129
+ checks.push({ name: 'native_helpers', status: 'pass' });
130
+ }
131
+ catch {
132
+ checks.push({ name: 'native_helpers', status: 'fail', detail: 'Build or reinstall the native helpers; Xcode Command Line Tools are required for compilation.' });
133
+ }
134
+ const state = mkdtempSync(join(paths.stateDirectory, 'doctor-'));
135
+ let client;
136
+ try {
137
+ client = new ContainedCodexAppServer({ executable: config.runtime.executable, stateDirectory: state, modelPort: config.runtime.modelPort, config: pilotCodexConfig(config.runtime.modelPort) });
138
+ await client.initialize();
139
+ checks.push({ name: 'contained_app_server_handshake', status: 'pass' });
140
+ }
141
+ catch {
142
+ checks.push({ name: 'contained_app_server_handshake', status: 'fail', detail: 'Check the executable, Codex app-server compatibility, and macOS sandbox support.' });
143
+ }
144
+ finally {
145
+ await client?.close();
146
+ rmSync(state, { recursive: true, force: true });
147
+ }
148
+ checks.push({ name: 'command_execution', status: config.commands?.enabled ? 'pass' : 'fail', detail: 'Brokered commands require the configured coding preset.' });
149
+ const missing = missingCodingPermissions(config.deploymentPolicy);
150
+ checks.push({ name: 'coding_permissions', status: missing.length ? 'fail' : 'pass', ...(missing.length ? { detail: `Deployment policy denies ${missing.join(', ')}. Stop the engine and run code60 configure --coding-only. Profile permissions cannot override deployment denials.` } : {}) });
151
+ if (values.repository) {
152
+ const { SourceRepository } = await import('../workspaces/source.js');
153
+ try {
154
+ const repository = new SourceRepository(values.repository);
155
+ repository.head();
156
+ const entries = repository.sourceEntries();
157
+ checks.push({ name: 'repository', status: 'pass', detail: `${entries.length} source entries; ignored dependencies excluded; dirty edits are supported.` });
158
+ }
159
+ catch {
160
+ checks.push({ name: 'repository', status: 'fail', detail: 'Use a supported repository root with an existing commit; resolve unfinished Git operations.' });
161
+ }
162
+ }
163
+ if (values['check-provider']) {
164
+ const provider = config.providers?.[0], file = config.providerCredentials?.find(c => c.providerId === provider?.id);
165
+ if (!provider || !file)
166
+ checks.push({ name: 'provider_authentication', status: 'fail', detail: 'Configure an HTTPS provider and credential reference first.' });
167
+ else {
168
+ const credentials = new ProviderCredentials(config.providerCredentials ?? [], readPrivateFile), credential = credentials.describe(file.referenceId, provider.id, new URL(provider.endpoint).origin);
169
+ const transport = new ProviderTransport({ coordinator, endpoint: provider.endpoint, networkPolicy: provider.networkPolicy, ...(provider.dnsResolvers ? { dnsResolvers: provider.dnsResolvers } : {}), timeoutMs: provider.timeoutMs ?? 120_000 });
170
+ const bytes = Buffer.from(JSON.stringify({ model: provider.models[0].id, input: 'Reply OK.', reasoning: { effort: provider.models[0].defaultEffort }, max_output_tokens: 32 }));
171
+ try {
172
+ await transport.post({ body: (async function* () { yield bytes; })(), contentLength: bytes.length, signal: AbortSignal.timeout(provider.timeoutMs ?? 120_000), credential, admit: () => { }, resolveCredential: () => credentials.resolve(credential, provider.id), onHeaders: () => { }, onChunk: async () => { } });
173
+ checks.push({ name: 'provider_authentication', status: 'pass' });
174
+ }
175
+ catch (error) {
176
+ checks.push({ name: 'provider_authentication', status: 'fail', detail: error instanceof Error ? error.message : 'Provider probe failed.' });
177
+ }
178
+ finally {
179
+ await transport.close();
180
+ }
181
+ }
182
+ }
183
+ else
184
+ checks.push({ name: 'provider_authentication', status: 'not_checked', detail: 'Use --check-provider for an explicit billable model probe.' });
185
+ process.stdout.write(JSON.stringify({ ready: checks.every(c => c.status !== 'fail'), checks }, null, 2) + '\n');
186
+ if (checks.some(c => c.status === 'fail'))
187
+ process.exitCode = 1;
188
+ }
189
+ finally {
190
+ await pool.close();
191
+ db.close();
192
+ }
193
+ }
@@ -5,6 +5,7 @@ import { homedir } from 'node:os';
5
5
  import { dirname, isAbsolute, join } from 'node:path';
6
6
  import { setTimeout as delay } from 'node:timers/promises';
7
7
  import { readOperatorToken, readPrivateFile } from '../config/deployment.js';
8
+ import { assertRuntimeBuild } from './runtime-build.js';
8
9
  const LSOF_ENV = { PATH: '/usr/bin:/bin', LC_ALL: 'C' };
9
10
  export function defaultStateDirectory() {
10
11
  return join(homedir(), 'Library', 'Application Support', 'Code60 Transmission', 'state');
@@ -231,8 +232,10 @@ export async function ensureEngineRunning(options) {
231
232
  const { stateDirectory, configurationFile, logFile } = statePaths;
232
233
  const lockPath = join(stateDirectory, 'startup.lock');
233
234
  const already = findRunningEngine(stateDirectory, listenPort);
234
- if (already)
235
+ if (already) {
236
+ assertRuntimeBuild(stateDirectory, already.pid);
235
237
  return { ...already, started: false };
238
+ }
236
239
  const otherPort = findRunningEngine(stateDirectory);
237
240
  if (otherPort && otherPort.port !== listenPort) {
238
241
  throw new Error(`Engine for ${stateDirectory} is already running on 127.0.0.1:${otherPort.port} (PID ${otherPort.pid}). ` +
@@ -269,6 +272,7 @@ export async function ensureEngineRunning(options) {
269
272
  }
270
273
  const winner = findRunningEngine(stateDirectory, listenPort);
271
274
  if (winner) {
275
+ assertRuntimeBuild(stateDirectory, winner.pid);
272
276
  return { ...winner, started: winner.pid === childPid };
273
277
  }
274
278
  if (childPid !== undefined && !isPidAlive(childPid)) {
@@ -2,7 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { accessSync, constants, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
3
3
  import { dirname, isAbsolute, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { buildFilesystemHelper, buildGitHelper } from '../broker/native/build.js';
5
+ import { buildFilesystemHelper, buildGitHelper, buildCommandHelper } from '../broker/native/build.js';
6
6
  export function packageRoot() {
7
7
  let current = import.meta.dirname;
8
8
  for (let depth = 0; depth < 5; depth++) {
@@ -29,7 +29,8 @@ export function packageVersion() {
29
29
  return typeof parsed.version === 'string' ? parsed.version : '0.0.0';
30
30
  }
31
31
  export function defaultTemplateConfigurationPath() {
32
- return join(packageRoot(), 'examples', 'deployment.local.json');
32
+ const root = packageRoot(), source = join(root, 'examples', 'deployment.local.json');
33
+ return existsSync(source) ? source : join(root, 'deployment.local.json');
33
34
  }
34
35
  /** Matches the exact trust invariants enforced by startup-lock.ts, filesystem.ts, and git.ts. */
35
36
  export function isTrustedHelper(helperPath) {
@@ -66,6 +67,8 @@ function nativeSourceDigest(nativeDir) {
66
67
  hash.update(readFileSync(join(nativeDir, 'fs-helper.c')));
67
68
  hash.update('\0');
68
69
  hash.update(readFileSync(join(nativeDir, 'git-helper.c')));
70
+ hash.update('\0');
71
+ hash.update(readFileSync(join(nativeDir, 'command-helper.c')));
69
72
  return hash.digest('hex').slice(0, 16);
70
73
  }
71
74
  export function resolveNativeHelpers(stateDir, options = {}) {
@@ -73,7 +76,7 @@ export function resolveNativeHelpers(stateDir, options = {}) {
73
76
  const candidateDir = options.packageHelperDirectory ?? join(nativeDir, '.build');
74
77
  const packagedFs = join(candidateDir, 'fs-helper');
75
78
  const packagedGit = join(candidateDir, 'git-helper');
76
- if (isTrustedHelper(packagedFs) && isTrustedHelper(packagedGit)) {
79
+ if (isTrustedHelper(packagedFs) && isTrustedHelper(packagedGit) && isTrustedHelper(join(candidateDir, 'command-helper'))) {
77
80
  return {
78
81
  fsHelperPath: realpathSync(packagedFs),
79
82
  gitHelperPath: realpathSync(packagedGit),
@@ -84,6 +87,7 @@ export function resolveNativeHelpers(stateDir, options = {}) {
84
87
  const targetDir = ensurePrivateDirectory(join(helpersRoot, `${process.arch}-${nativeSourceDigest(nativeDir)}`));
85
88
  const fsTarget = join(targetDir, 'fs-helper');
86
89
  const gitTarget = join(targetDir, 'git-helper');
90
+ const commandTarget = join(targetDir, 'command-helper');
87
91
  let builtOnDemand = false;
88
92
  if (!isTrustedHelper(fsTarget)) {
89
93
  buildFilesystemHelper({ outputDirectory: targetDir });
@@ -93,7 +97,11 @@ export function resolveNativeHelpers(stateDir, options = {}) {
93
97
  buildGitHelper({ outputDirectory: targetDir });
94
98
  builtOnDemand = true;
95
99
  }
96
- if (!isTrustedHelper(fsTarget) || !isTrustedHelper(gitTarget)) {
100
+ if (!isTrustedHelper(commandTarget)) {
101
+ buildCommandHelper({ outputDirectory: targetDir });
102
+ builtOnDemand = true;
103
+ }
104
+ if (!isTrustedHelper(fsTarget) || !isTrustedHelper(gitTarget) || !isTrustedHelper(commandTarget)) {
97
105
  throw new Error(`Compiled native helpers in ${targetDir} failed trust validation.`);
98
106
  }
99
107
  return {
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { configurationCli } from './configure.js';
2
3
  import { realpathSync } from 'node:fs';
3
4
  import { isAbsolute } from 'node:path';
4
5
  import { fileURLToPath } from 'node:url';
@@ -14,6 +15,7 @@ const USAGE = `Usage:
14
15
  code60-transmission-server status [--state-directory <abs-path>]
15
16
  code60-transmission-server stop [--state-directory <abs-path>]
16
17
  code60-transmission-server mcp-config [--state-directory <abs-path>]
18
+ code60-transmission-server configure | doctor [options]
17
19
  code60-transmission-server --help | --version
18
20
  `;
19
21
  const COMMANDS = new Set(['mcp', 'engine', 'status', 'stop', 'mcp-config']);
@@ -38,6 +40,7 @@ export function parseCliArguments(argv) {
38
40
  'operator-token-file': { type: 'string' },
39
41
  'fs-helper': { type: 'string' },
40
42
  'git-helper': { type: 'string' },
43
+ toolset: { type: 'string' },
41
44
  },
42
45
  });
43
46
  if (positionals.length > 0) {
@@ -72,6 +75,8 @@ export function parseCliArguments(argv) {
72
75
  }
73
76
  return {
74
77
  command,
78
+ ...(values.toolset ? { toolset: (() => { if (!['coding', 'admin'].includes(values.toolset))
79
+ throw new Error('Invalid --toolset.'); return values.toolset; })() } : {}),
75
80
  ...(stateDirectory !== undefined ? { stateDirectory } : {}),
76
81
  ...(port !== undefined ? { port } : {}),
77
82
  ...(operatorTokenFile !== undefined ? { operatorTokenFile } : {}),
@@ -80,7 +85,7 @@ export function parseCliArguments(argv) {
80
85
  };
81
86
  }
82
87
  export function formatMcpConfig(stateDirectory) {
83
- const args = ['-y', 'code60-transmission-server'];
88
+ const args = ['-y', `code60-transmission-server@${packageVersion()}`];
84
89
  if (stateDirectory !== undefined) {
85
90
  args.push('--state-directory', stateDirectory);
86
91
  }
@@ -100,6 +105,10 @@ function assertMacOS() {
100
105
  }
101
106
  export async function runCli(argv = process.argv.slice(2)) {
102
107
  process.umask(0o077);
108
+ if (['configure', 'doctor'].includes(argv[0] ?? '')) {
109
+ await configurationCli(argv);
110
+ return;
111
+ }
103
112
  const parsed = parseCliArguments(argv);
104
113
  if (parsed.command === 'help') {
105
114
  process.stdout.write(USAGE);
@@ -115,7 +124,7 @@ export async function runCli(argv = process.argv.slice(2)) {
115
124
  }
116
125
  // Direct stdio bridge mode to an already-running engine.
117
126
  if (parsed.command === 'mcp' && parsed.port !== undefined && parsed.operatorTokenFile !== undefined) {
118
- await runMcpBridge(['--port', parsed.port, '--operator-token-file', parsed.operatorTokenFile]);
127
+ await runMcpBridge(['--port', parsed.port, '--operator-token-file', parsed.operatorTokenFile, '--toolset', parsed.toolset ?? 'coding']);
119
128
  return;
120
129
  }
121
130
  assertMacOS();
@@ -159,7 +168,7 @@ export async function runCli(argv = process.argv.slice(2)) {
159
168
  gitHelperPath: helpers.gitHelperPath,
160
169
  cliEntrypoint,
161
170
  });
162
- await runMcpBridge(['--port', String(listenPort), '--operator-token-file', statePaths.operatorTokenFile]);
171
+ await runMcpBridge(['--port', String(listenPort), '--operator-token-file', statePaths.operatorTokenFile, '--toolset', parsed.toolset ?? 'coding']);
163
172
  }
164
173
  function isDirectExecution() {
165
174
  if (!process.argv[1])