code60-transmission-server 0.1.0-staging.4 → 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.
package/README.md CHANGED
@@ -31,6 +31,19 @@ source changes become the baseline. Workers can inspect/edit source, run builds
31
31
  and tests, ask questions, and receive `send_task_message` guidance. Inspect
32
32
  `get_run` and `get_coding_task_result` for the diff and executable check evidence.
33
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.
34
47
  Tasks without executable checks explicitly report `unverified`.
35
48
 
36
49
  Use `--toolset admin` to advertise the complete workflow/profile administration
@@ -16,9 +16,12 @@ import Database from 'better-sqlite3';
16
16
  import { SqliteCoordinator } from '../storage/coordinator.js';
17
17
  import { ProviderTransport } from '../runtime/provider-transport.js';
18
18
  import { ProviderCredentials } from '../runtime/provider-credentials.js';
19
+ import { missingCodingPermissions } from '../config/coding-policy.js';
20
+ import { assertRuntimeBuild } from './runtime-build.js';
19
21
  const usage = `Usage:
20
22
  code60 configure [--state-directory PATH] [--executable PATH] [--provider openrouter|openai|local] [--endpoint HTTPS_URL] [--model MODEL] [--credential-file PATH] [--toolchain PATH ...]
21
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.
22
25
  Credentials are read from an existing private file, never from command arguments or ambient logins.
23
26
  `;
24
27
  const which = (name) => { try {
@@ -29,11 +32,13 @@ catch {
29
32
  } };
30
33
  export async function configurationCli(argv) {
31
34
  const command = argv[0];
32
- const { values } = parseArgs({ args: argv.slice(1), options: { help: { type: 'boolean' }, 'state-directory': { type: 'string' }, 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' } } });
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' } } });
33
36
  if (values.help) {
34
37
  process.stdout.write(usage);
35
38
  return;
36
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.');
37
42
  const paths = initializeStateDirectory(values['state-directory'] ?? defaultStateDirectory(), defaultTemplateConfigurationPath());
38
43
  if (command === 'configure') {
39
44
  if (findRunningEngine(paths.stateDirectory))
@@ -41,33 +46,35 @@ export async function configurationCli(argv) {
41
46
  const config = JSON.parse(readFileSync(paths.configurationFile, 'utf8'));
42
47
  const readline = process.stdin.isTTY ? createInterface({ input: process.stdin, output: process.stdout }) : undefined;
43
48
  try {
44
- const ask = async (label, value) => value ?? (readline ? (await readline.question(label + ': ')).trim() : undefined);
45
- const executable = await ask('Absolute Codex executable path', values.executable ?? (existsSync(config.runtime.executable) ? config.runtime.executable : which('codex')));
46
- if (!executable || !isAbsolute(executable))
47
- throw new Error('Supply --executable with the absolute Codex executable path.');
48
- accessSync(executable, constants.X_OK);
49
- const provider = await ask('Provider (openrouter, openai, local)', values.provider ?? config.providers?.[0]?.id) ?? 'openrouter';
50
- const model = await ask('Model ID', values.model ?? config.providers?.[0]?.models[0]?.id);
51
- if (!model)
52
- throw new Error('Supply --model with your provider’s model ID.');
53
- config.runtime = { ...config.runtime, enabled: true, executable: realpathSync(executable), models: [{ id: model, effortLevels: ['low'] }] };
54
- if (provider === 'local') {
55
- delete config.providers;
56
- delete config.providerCredentials;
57
- }
58
- else {
59
- const endpoint = values.endpoint ?? (provider === 'openai' ? 'https://api.openai.com/v1/responses' : provider === 'openrouter' ? 'https://openrouter.ai/api/v1/responses' : undefined);
60
- if (!endpoint || new URL(endpoint).protocol !== 'https:')
61
- throw new Error('Select openai/openrouter or supply --endpoint with a fixed HTTPS Responses URL.');
62
- const credentialFile = await ask('Absolute private credential-file path', values['credential-file'] ?? config.providerCredentials?.[0]?.file);
63
- if (!credentialFile)
64
- throw new Error('Supply --credential-file with an existing owned mode-0600 API-key file.');
65
- readPrivateFile(credentialFile, 8192);
66
- const resolver = getServers().find(server => isIP(server)) ?? '8.8.8.8';
67
- 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: [
68
- { 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' }
69
- ] } }];
70
- config.providerCredentials = [{ referenceId: 'coding-provider', version: 'configured-v1', providerId: provider, origin: new URL(endpoint).origin, file: realpathSync(credentialFile) }];
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
+ }
71
78
  }
72
79
  const discovered = ['node', 'npm', 'pnpm', 'yarn', 'bun', 'python3', 'cargo', 'go'].flatMap(name => {
73
80
  const path = which(name);
@@ -80,6 +87,7 @@ export async function configurationCli(argv) {
80
87
  config.deploymentPolicy = { defaultEffect: 'deny', rules: [...config.deploymentPolicy.rules,
81
88
  ...[...DEVELOPER_DEFINITIONS.keys()].map(toolId => ({ kind: 'tool', toolId, effect: 'allow' })),
82
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()];
83
91
  config.contextBytes = 65_536;
84
92
  const temporary = paths.configurationFile + `.${process.pid}.${Date.now()}.pending`;
85
93
  writeFileSync(temporary, JSON.stringify(config, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
@@ -106,6 +114,16 @@ export async function configurationCli(argv) {
106
114
  try {
107
115
  const config = await loadDeploymentConfiguration(paths.configurationFile, pool);
108
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
+ }
109
127
  try {
110
128
  resolveNativeHelpers(paths.stateDirectory);
111
129
  checks.push({ name: 'native_helpers', status: 'pass' });
@@ -128,6 +146,8 @@ export async function configurationCli(argv) {
128
146
  rmSync(state, { recursive: true, force: true });
129
147
  }
130
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.` } : {}) });
131
151
  if (values.repository) {
132
152
  const { SourceRepository } = await import('../workspaces/source.js');
133
153
  try {
@@ -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)) {
@@ -85,7 +85,7 @@ export function parseCliArguments(argv) {
85
85
  };
86
86
  }
87
87
  export function formatMcpConfig(stateDirectory) {
88
- const args = ['-y', 'code60-transmission-server'];
88
+ const args = ['-y', `code60-transmission-server@${packageVersion()}`];
89
89
  if (stateDirectory !== undefined) {
90
90
  args.push('--state-directory', stateDirectory);
91
91
  }
@@ -0,0 +1,38 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
3
+ import { join, relative } from 'node:path';
4
+ import { packageRoot, packageVersion } from './helpers.js';
5
+ /** Compare installed engine code, including native containment sources, rather
6
+ * than just semver: a staging build and a checkout can share a version. */
7
+ export function runtimeBuildId() {
8
+ const hash = createHash('sha256'), packaged = packageRoot(), root = existsSync(join(packaged, 'dist', 'src')) ? join(packaged, 'dist', 'src') : join(packaged, 'src');
9
+ const visit = (directory) => {
10
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
11
+ const path = join(directory, entry.name);
12
+ if (entry.isDirectory() && entry.name !== '.build')
13
+ visit(path);
14
+ else if (entry.isFile() && /\.(js|json|c)$/.test(entry.name)) {
15
+ hash.update(relative(root, path));
16
+ hash.update('\0');
17
+ hash.update(readFileSync(path));
18
+ hash.update('\0');
19
+ }
20
+ }
21
+ };
22
+ visit(root);
23
+ hash.update(packageVersion());
24
+ return hash.digest('hex');
25
+ }
26
+ export function recordRuntimeBuild(stateDirectory) {
27
+ // Called only after acquiring the exclusive startup lock, before listening.
28
+ writeFileSync(join(stateDirectory, 'engine-runtime.json'), JSON.stringify({ pid: process.pid, version: packageVersion(), buildId: runtimeBuildId() }), { mode: 0o600 });
29
+ }
30
+ export function assertRuntimeBuild(stateDirectory, pid) {
31
+ try {
32
+ const current = JSON.parse(readFileSync(join(stateDirectory, 'engine-runtime.json'), 'utf8'));
33
+ if (current.pid === pid && current.buildId === runtimeBuildId())
34
+ return;
35
+ }
36
+ catch { /* Older engines have no build record. */ }
37
+ throw new Error(`Engine upgrade required for ${stateDirectory} (PID ${pid}). Stop it with code60 stop --state-directory ${JSON.stringify(stateDirectory)}, then reconnect using this installation. Existing runs and configuration are preserved; an upgrade never silently replaces an active engine.`);
38
+ }
@@ -0,0 +1,4 @@
1
+ import { evaluatePolicy } from '../broker/policy.js';
2
+ export function missingCodingPermissions(policy) {
3
+ return ['read_file', 'write_file', 'run_command'].filter(toolId => evaluatePolicy(policy, toolId, [{ kind: 'filesystem', root: 'workspace', path: '.', operation: toolId === 'read_file' ? 'read' : 'write', identityDigest: 'sha256:' + '0'.repeat(64) }]) === 'deny');
4
+ }
@@ -252,7 +252,11 @@ export class RunCommands {
252
252
  }
253
253
  for (const { value } of this.store.list('sessions', { runId: run.id, limit: Number.MAX_SAFE_INTEGER }))
254
254
  this.options.auth.revokeSession(value.id);
255
- this.updateRun(run.id, { state: 'pausing', executionControl: { status: 'pausing', inFlightWork: this.options.work(run.id) } });
255
+ const now = this.now();
256
+ this.updateRun(run.id, { state: 'pausing', executionControl: { status: 'pausing',
257
+ continuationState: run.executionControl.continuationState ?? (['pausing', 'paused', 'resuming'].includes(run.state) ? 'interrupted' : run.state),
258
+ pauseOperationId: operation.id, requestedAt: new Date(now).toISOString(),
259
+ graceDeadlineAt: new Date(now + durationMs(run.policy.pauseGracePeriod ?? '30s')).toISOString(), inFlightWork: this.options.work(run.id) } });
256
260
  return this.operationReceipt(operation);
257
261
  });
258
262
  }
@@ -1774,7 +1774,7 @@ export class WorkflowEngine {
1774
1774
  }
1775
1775
  this.supersede(runId);
1776
1776
  this.commands.updateRun(runId, { state: 'cancelled', completedAt: new Date(this.commands.now()).toISOString(),
1777
- executionControl: { status: 'paused', inFlightWork: [] } });
1777
+ executionControl: { ...this.store.get('runs', runId).executionControl, status: 'paused', pausedAt: new Date(this.commands.now()).toISOString(), inFlightWork: [] } });
1778
1778
  this.operationState(operationId, 'succeeded');
1779
1779
  this.updateClocks(runId);
1780
1780
  });
package/dist/src/main.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { pathToFileURL } from 'node:url';
2
2
  import { openDeployment, parseStartupArguments } from './server/deployment.js';
3
+ import { recordRuntimeBuild } from './cli/runtime-build.js';
3
4
  /** No environment/home discovery, ambient credentials, shell, auto-build, or
4
5
  * automatic provider login. Every input path must be explicitly supplied. */
5
6
  export async function main(argv = process.argv.slice(2)) {
6
- const deployment = await openDeployment(parseStartupArguments(argv));
7
+ const input = parseStartupArguments(argv);
8
+ const deployment = await openDeployment(input);
7
9
  let stopping;
8
10
  const stop = () => {
9
11
  stopping ??= deployment.close().catch(() => { process.stderr.write('Engine shutdown requires reconciliation.\n'); process.exitCode = 1; });
@@ -11,6 +13,7 @@ export async function main(argv = process.argv.slice(2)) {
11
13
  process.once('SIGINT', stop);
12
14
  process.once('SIGTERM', stop);
13
15
  try {
16
+ recordRuntimeBuild(input.stateDirectory);
14
17
  await deployment.listen();
15
18
  }
16
19
  catch (error) {
@@ -94,10 +94,20 @@ export function createWorkflowServer(port, token, toolset = 'admin') {
94
94
  inputSchema: { type: 'object', properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true } },
95
95
  ];
96
96
  const codingNames = new Set(['get_coding_readiness', 'start_coding_task', 'get_run', 'get_coding_task_result', 'list_run_events', 'send_task_message', 'list_task_questions', 'answer_task_question', 'list_run_approvals', 'get_approval', 'decide_approval', 'pause_run', 'resume_run', 'cancel_run', 'recover_run', 'get_operation']);
97
+ const managedControls = new Set(['pause_run', 'resume_run', 'cancel_run', ...(toolset === 'coding' ? ['decide_approval'] : [])]);
97
98
  const codingInstructions = 'Use get_coding_readiness first, then start_coding_task with a task description, repositoryPath or workspaceId, and a stable idempotencyKey. Coding tasks run in the current folder, preserve existing edits, and leave the result uncommitted. Follow get_run/list_run_events; answer pending questions and inspect get_coding_task_result for the run-only diff and check evidence. If checks are absent the result explicitly says unverified. Send guidance with send_task_message. Low-level workflow administration remains available with --toolset admin.';
98
99
  const server = new Server({ name: 'code60-workflows', version: '0.1.0' }, { capabilities: { tools: {}, resources: {} }, instructions: toolset === 'coding' ? codingInstructions : instructions });
99
- server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: toolset === 'admin' ? [...discoveryTools, ...Array.from(catalog.values(), entry => entry.tool)] : [...catalog.values()].filter(entry => codingNames.has(entry.tool.name)).map(entry => { const tool = structuredClone(entry.tool); if (['pause_run', 'resume_run', 'cancel_run', 'decide_approval'].includes(tool.name))
100
- tool.inputSchema.required = tool.inputSchema.required?.filter(name => name !== 'ifMatch') ?? []; return tool; }) }));
100
+ server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [
101
+ ...(toolset === 'admin' ? discoveryTools : []),
102
+ ...[...catalog.values()].filter(entry => toolset === 'admin' || codingNames.has(entry.tool.name)).map(entry => {
103
+ const tool = structuredClone(entry.tool);
104
+ if (managedControls.has(tool.name)) {
105
+ tool.inputSchema.required = tool.inputSchema.required?.filter(name => name !== 'ifMatch') ?? [];
106
+ tool.description += ' Omit ifMatch to let the bridge refresh versions during active execution; supply it for an exact conditional write.';
107
+ }
108
+ return tool;
109
+ }),
110
+ ] }));
101
111
  server.setRequestHandler(CallToolRequestSchema, ({ params }, { signal }) => {
102
112
  if (params.name === 'get_workflow_schema' || params.name === 'get_workflow_example') {
103
113
  if (Object.keys(params.arguments ?? {}).length)
@@ -108,14 +118,20 @@ export function createWorkflowServer(port, token, toolset = 'admin') {
108
118
  if (!entry)
109
119
  throw new McpError(ErrorCode.InvalidParams, 'Unknown Code60 operator tool.');
110
120
  const args = params.arguments ?? {};
111
- if (toolset === 'coding' && args.ifMatch === undefined && ['pause_run', 'resume_run', 'cancel_run', 'decide_approval'].includes(params.name)) {
121
+ if (args.ifMatch === undefined && managedControls.has(params.name)) {
112
122
  return (async () => {
113
123
  const target = params.name === 'decide_approval' ? catalog.get('get_approval') : catalog.get('get_run');
114
- const read = await callEngine(target, params.name === 'decide_approval' ? { approvalId: args.approvalId } : { runId: args.runId }, port, token, signal);
115
- const receipt = read.structuredContent;
116
- if (read.isError || !receipt?.etag)
117
- return read;
118
- return callEngine(entry, { ...args, ifMatch: receipt.etag }, port, token, signal);
124
+ for (let attempt = 0;; attempt++) {
125
+ const read = await callEngine(target, params.name === 'decide_approval' ? { approvalId: args.approvalId } : { runId: args.runId }, port, token, signal);
126
+ const receipt = read.structuredContent;
127
+ if (read.isError || !receipt?.etag)
128
+ return read;
129
+ const written = await callEngine(entry, { ...args, ifMatch: receipt.etag }, port, token, signal);
130
+ // A failed precondition has no receipt or side effects. Retain the
131
+ // caller's key/body, and never retry an uncertain transport outcome.
132
+ if (written.structuredContent?.status !== 412 || attempt >= 15 || signal.aborted)
133
+ return written;
134
+ }
119
135
  })();
120
136
  }
121
137
  return callEngine(entry, args, port, token, signal);
@@ -4,10 +4,11 @@ import { randomUUID, createHash } from 'node:crypto';
4
4
  import { DEVELOPER_DEFINITIONS } from '../tools/developer.js';
5
5
  import { createCommandCheck } from '../tools/command-check.js';
6
6
  import { ContainedCodexAppServer, pilotCodexConfig } from '../runtime/codex-app-server.js';
7
- import { canonical, evaluatePolicy } from '../broker/policy.js';
7
+ import { canonical } from '../broker/policy.js';
8
8
  import { ApiError } from './errors.js';
9
9
  import { isTrustedHelper } from '../cli/helpers.js';
10
10
  import { commandIdentity } from './control-plane.js';
11
+ import { missingCodingPermissions } from '../config/coding-policy.js';
11
12
  export const CODING_MIGRATION = { id: 'coding.v1', sql: `
12
13
  CREATE INDEX coding_command_run ON engine_private(json_extract(body,'$.runId')) WHERE scope='command';
13
14
  CREATE INDEX coding_question_run ON engine_private(json_extract(body,'$.runId')) WHERE scope='worker_question';
@@ -32,9 +33,8 @@ export function codingReadiness(configuration, runner) {
32
33
  issues.push({ code: 'commands_disabled', action: 'Run code60 configure to enable the coding command preset.' });
33
34
  if (runner && !isTrustedHelper(runner.options.workspaces.commandHelperPath))
34
35
  issues.push({ code: 'command_supervisor_unavailable', action: 'Build or reinstall Code60 native helpers.' });
35
- for (const toolId of ['read_file', 'write_file', 'run_command'])
36
- if (evaluatePolicy(configuration.deploymentPolicy, toolId, [{ kind: 'filesystem', root: 'workspace', path: '.', operation: toolId === 'read_file' ? 'read' : 'write', identityDigest: 'sha256:' + '0'.repeat(64) }]) === 'deny')
37
- issues.push({ code: 'coding_permissions_missing', action: 'Run code60 configure to grant the coding preset at deployment level.' });
36
+ if (missingCodingPermissions(configuration.deploymentPolicy).length)
37
+ issues.push({ code: 'coding_permissions_missing', action: 'Stop the engine and run code60 configure --coding-only to grant the coding preset without replacing provider settings.' });
38
38
  for (const credential of configuration.providerCredentials ?? [])
39
39
  try {
40
40
  accessSync(credential.file, constants.R_OK);
@@ -2,8 +2,22 @@ import { EngineStore } from '../storage/store.js';
2
2
  import { AuthService } from './auth.js';
3
3
  import { Paging } from './paging.js';
4
4
  import { ApiError } from './errors.js';
5
+ import { durationMs } from '../engine/timing.js';
5
6
  export function historyHandlers(store, auth, paging) {
6
7
  const handlers = new Map();
8
+ const publicRun = (value) => {
9
+ if (value.state !== 'cancelled' || value.executionControl.status !== 'paused' || value.executionControl.pausedAt)
10
+ return value;
11
+ // Older cancellations discarded the pause metadata required by the wire
12
+ // schema. Project it from the durable cancellation receipt without rewriting
13
+ // historical records or inventing a resumable continuation for a terminal run.
14
+ const operation = store.list('operations', { runId: value.id, limit: Number.MAX_SAFE_INTEGER }).map(r => r.value).find(op => op.kind === 'cancel');
15
+ if (!operation)
16
+ return value;
17
+ return { ...value, executionControl: { continuationState: 'interrupted', pauseOperationId: operation.id, requestedAt: operation.createdAt,
18
+ graceDeadlineAt: new Date(Date.parse(operation.createdAt) + durationMs(value.policy.pauseGracePeriod ?? '30s')).toISOString(),
19
+ ...value.executionControl, pausedAt: value.completedAt ?? operation.updatedAt } };
20
+ };
7
21
  const run = (context, id) => {
8
22
  const value = store.get('runs', id);
9
23
  auth.assertWorkspace(context.principal, value.workspaceId);
@@ -24,7 +38,7 @@ export function historyHandlers(store, auth, paging) {
24
38
  return store.coordinator.db.prepare(`SELECT body,seq FROM engine_resources WHERE kind='runs' AND seq>?
25
39
  AND (EXISTS(SELECT 1 FROM json_each(?) WHERE value='*') OR json_extract(body,'$.workspaceId') IN (SELECT value FROM json_each(?)))
26
40
  ORDER BY seq LIMIT ?`).all(after, scope, scope, limit)
27
- .map(row => ({ value: JSON.parse(row.body), seq: row.seq }));
41
+ .map(row => ({ value: publicRun(JSON.parse(row.body)), seq: row.seq }));
28
42
  }) }));
29
43
  const collections = [
30
44
  ['listRunStepExecutions', 'steps'], ['listRunSessions', 'sessions'], ['listRunSubmissions', 'submissions'],
@@ -49,7 +63,7 @@ export function historyHandlers(store, auth, paging) {
49
63
  run(context, runId);
50
64
  if (context.principal.audience === 'adapter' && (kind !== 'artifacts' || !access(context, runId).inputArtifactIds.includes(id)))
51
65
  throw new ApiError(403, 'assignment_forbidden', 'Artifact is not in the current assignment.');
52
- return { status: 200, headers: { ETag: store.etag(kind, id) }, body };
66
+ return { status: 200, headers: { ETag: store.etag(kind, id) }, body: kind === 'runs' ? publicRun(body) : body };
53
67
  });
54
68
  handlers.set('getSessionAssignment', context => {
55
69
  if (context.principal.audience !== 'adapter' || context.principal.sessionId !== context.params.sessionId)
@@ -1,12 +1,15 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { closeSync, constants, existsSync, mkdirSync, openSync, readSync, realpathSync, writeFileSync, writeSync } from 'node:fs';
3
+ import { closeSync, constants, existsSync, mkdirSync, openSync, readSync, realpathSync, statSync, writeFileSync, writeSync } from 'node:fs';
4
4
  import { basename, dirname, join } from 'node:path';
5
5
  import { SourceRepository, within } from '../workspaces/source.js';
6
6
  import { BrokerError } from '../broker/types.js';
7
7
  import { digest } from '../broker/policy.js';
8
8
  import { isTrustedHelper } from '../cli/helpers.js';
9
9
  export const DEFAULT_COMMAND_SETTINGS = { enabled: false, network: 'outbound', toolchainPaths: [], generatedPaths: ['node_modules', 'dist', 'build', 'coverage', '.cache', '.next', 'target', '.venv', 'tsconfig.tsbuildinfo', '.eslintcache'], timeoutMs: 600_000, maxOutputBytes: 67_108_864 };
10
+ /** A trusted refusal before any command intent, source gate, or process exists. */
11
+ export class CommandAdmissionError extends BrokerError {
12
+ }
10
13
  const quote = (s) => JSON.stringify(s);
11
14
  const groupAlive = (pid) => { try {
12
15
  process.kill(-pid, 0);
@@ -24,7 +27,7 @@ export function assertCommandScope(binding, readOnly) {
24
27
  for (const operation of operations) {
25
28
  if (!rules.some(r => r.kind === 'filesystem' && r.path === '.' && r.recursive && r.effect !== 'deny' && r.operations.includes(operation)) ||
26
29
  rules.some(r => r.kind === 'filesystem' && r.operations.includes(operation) && (r.effect === 'deny' || r.path !== '.' && r.effect === 'require_approval')))
27
- throw new BrokerError('command_requires_whole_workspace_scope', 403);
30
+ throw new CommandAdmissionError('command_requires_whole_workspace_scope', 403);
28
31
  }
29
32
  }
30
33
  }
@@ -73,25 +76,38 @@ export class CommandRunner {
73
76
  }
74
77
  async start(binding, request) {
75
78
  if (binding.role !== 'worker' && !request.readOnly)
76
- throw new BrokerError('project_read_only', 403);
79
+ throw new CommandAdmissionError('project_read_only', 403);
77
80
  if (!this.settings.enabled)
78
- throw new BrokerError('commands_not_configured', 422);
81
+ throw new CommandAdmissionError('commands_not_configured', 422);
79
82
  if (!isTrustedHelper(this.options.workspaces.commandHelperPath))
80
- throw new BrokerError('command_supervisor_unavailable', 422);
83
+ throw new CommandAdmissionError('command_supervisor_unavailable', 422);
81
84
  assertCommandScope(binding, request.readOnly ?? false);
82
85
  if (typeof request.command !== 'string' || !request.command.trim() || request.command.length > 65_536 || request.command.includes('\0'))
83
- throw new BrokerError('invalid_command', 400);
86
+ throw new CommandAdmissionError('invalid_command', 400);
84
87
  const timeoutMs = request.timeoutMs ?? this.settings.timeoutMs;
85
88
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 86_400_000)
86
- throw new BrokerError('invalid_command_timeout', 400);
89
+ throw new CommandAdmissionError('invalid_command_timeout', 400);
87
90
  if (request.env && Object.entries(request.env).some(([k, v]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) || typeof v !== 'string' || v.includes('\0') || /^(HOME|CODEX_HOME|XDG_.*|TMPDIR|DYLD_.*|LD_.*|PATH|GIT_.*)$/i.test(k)))
88
- throw new BrokerError('invalid_command_environment', 400);
91
+ throw new CommandAdmissionError('invalid_command_environment', 400);
89
92
  const repository = this.options.workspaces.sourceRepository(binding.runId);
90
93
  if (!repository)
91
- throw new BrokerError('source_tracking_required', 422);
92
- const cwd = repository.safePath(request.cwd ?? '.', false, true), readOnly = request.readOnly ?? false;
94
+ throw new CommandAdmissionError('source_tracking_required', 422);
95
+ let cwd;
96
+ try {
97
+ cwd = repository.safePath(request.cwd ?? '.', false, true);
98
+ if (!statSync(cwd).isDirectory())
99
+ throw new CommandAdmissionError('command_cwd_not_directory', 422);
100
+ }
101
+ catch (error) {
102
+ if (['ENOENT', 'ENOTDIR'].includes(error.code ?? ''))
103
+ throw new CommandAdmissionError('command_cwd_not_found', 422);
104
+ if (['EACCES', 'EPERM'].includes(error.code ?? ''))
105
+ throw new CommandAdmissionError('command_cwd_forbidden', 403);
106
+ throw error;
107
+ }
108
+ const readOnly = request.readOnly ?? false;
93
109
  if (this.records(binding.runId).some(r => r.state === 'running' && (!readOnly || !r.readOnly)))
94
- throw new BrokerError('workspace_command_active');
110
+ throw new CommandAdmissionError('workspace_command_active');
95
111
  const id = randomUUID(), state = join(this.options.directory, id);
96
112
  mkdirSync(state, { mode: 0o700 });
97
113
  mkdirSync(join(state, 'tmp'), { mode: 0o700 });
@@ -4,7 +4,7 @@ import { dirname, join, relative } from 'node:path';
4
4
  import { Ajv2020 } from 'ajv/dist/2020.js';
5
5
  import { digest } from '../broker/policy.js';
6
6
  import { BrokerError } from '../broker/types.js';
7
- import { assertCommandScope, CommandRunner } from './commands.js';
7
+ import { assertCommandScope, CommandAdmissionError, CommandRunner } from './commands.js';
8
8
  const str = { type: 'string' }, num = { type: 'integer', minimum: 0 }, bool = { type: 'boolean' };
9
9
  const schema = (properties, required = []) => ({ type: 'object', properties: properties, required, additionalProperties: false });
10
10
  export const DEVELOPER_DEFINITIONS = new Map([
@@ -17,7 +17,7 @@ export const DEVELOPER_DEFINITIONS = new Map([
17
17
  ['delete_file', { description: 'Delete one assigned regular source file.', inputSchema: schema({ path: str, root: str }, ['path']) }],
18
18
  ['move_file', { description: 'Move one source file to an absent destination within the assigned root.', inputSchema: schema({ path: str, destination: str, root: str }, ['path', 'destination']) }],
19
19
  ['get_diff', { description: 'Read the run’s baseline-relative diff. Pre-existing edits are excluded. Use the returned byte cursor for more.', inputSchema: schema({ cursor: num, limit: { type: 'integer', minimum: 1, maximum: 262144 } }) }],
20
- ['run_command', { description: 'Run a shell command in the sandboxed project. Await by default; background returns a command ID. Await/stop writing commands before editing or submitting. Network follows deployment settings.', inputSchema: schema({ command: { type: 'string', minLength: 1, maxLength: 65536 }, cwd: str, env: { type: 'object', additionalProperties: str }, timeoutMs: { type: 'integer', minimum: 1, maximum: 86400000 }, readOnly: bool, background: bool }, ['command']) }],
20
+ ['run_command', { description: 'Run a shell command in the sandboxed project. Await by default; background returns a command ID. Await/stop writing commands before editing or submitting. Network follows deployment settings.', inputSchema: schema({ command: { type: 'string', minLength: 1, maxLength: 65536 }, cwd: { ...str, description: 'Existing directory relative to the registered project root. Omit or use "." for that root; "workspace" means a subdirectory literally named workspace. Missing directories return command_cwd_not_found.' }, env: { type: 'object', additionalProperties: str }, timeoutMs: { type: 'integer', minimum: 1, maximum: 86400000 }, readOnly: { ...bool, description: 'Set true for source read-only commands; required for verifier sessions.' }, background: bool }, ['command']) }],
21
21
  ['read_command_output', { description: 'Read paginated stdout/stderr and current exit status for your command.', inputSchema: schema({ commandId: str, stream: { enum: ['stdout', 'stderr'] }, cursor: num, limit: { type: 'integer', minimum: 1, maximum: 262144 } }, ['commandId']) }],
22
22
  ['write_command_input', { description: 'Write text to your running command. Set end=true after the final input to send EOF.', inputSchema: schema({ commandId: str, text: { type: 'string', maxLength: 65536 }, end: bool }, ['commandId', 'text']) }],
23
23
  ['stop_command', { description: 'Stop your command and wait for process/output settlement before returning.', inputSchema: schema({ commandId: str }, ['commandId']) }],
@@ -146,8 +146,15 @@ export class DeveloperTools {
146
146
  this.options.resolveContext(binding);
147
147
  const result = (data) => ({ success: true, text: typeof data === 'string' ? data : JSON.stringify(data) });
148
148
  if (name === 'run_command') {
149
- const record = await this.options.runner.start(binding, args);
150
- return { success: record.state === 'running' || record.state === 'completed', text: JSON.stringify({ ...record, stdout: this.options.runner.output(record.id).text, stderr: this.options.runner.output(record.id, 'stderr').text }) };
149
+ try {
150
+ const record = await this.options.runner.start(binding, args);
151
+ return { success: record.state === 'running' || record.state === 'completed', text: JSON.stringify({ ...record, stdout: this.options.runner.output(record.id).text, stderr: this.options.runner.output(record.id, 'stderr').text }) };
152
+ }
153
+ catch (error) {
154
+ if (!(error instanceof CommandAdmissionError))
155
+ throw error;
156
+ return { success: false, text: JSON.stringify({ code: error.code, commandStarted: false, recovery: error.code === 'workspace_command_active' ? 'Read or stop the existing command before starting another writer.' : error.code.startsWith('command_cwd_') ? 'Use an existing project-relative directory; omit cwd or use "." for the project root.' : 'Review command arguments and the capabilities reported by get_capabilities.' }) };
157
+ }
151
158
  }
152
159
  if (name === 'read_command_output')
153
160
  return result(this.options.runner.output(String(args.commandId), args.stream, args.cursor, args.limit, binding));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "code60-transmission-server",
3
- "version": "0.1.0-staging.4",
3
+ "version": "0.1.0-staging.6",
4
4
  "description": "Local workflow server and stdio MCP launcher for bounded coding-agent steps against Git workspaces.",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [