code60-transmission-server 0.1.0-staging.13 → 0.1.0-staging.16

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 (104) hide show
  1. package/INTENT.md +47 -0
  2. package/README.md +36 -345
  3. package/dist/src/acp.js +115 -0
  4. package/dist/src/contract.js +60 -0
  5. package/dist/src/engine.js +481 -0
  6. package/dist/src/main.js +70 -25
  7. package/dist/src/repository.js +94 -0
  8. package/dist/src/service.js +184 -0
  9. package/package.json +16 -35
  10. package/reference/openapi.json +423 -0
  11. package/README.engine.md +0 -463
  12. package/dist/src/broker/filesystem.js +0 -385
  13. package/dist/src/broker/index.js +0 -777
  14. package/dist/src/broker/native/README.md +0 -207
  15. package/dist/src/broker/native/build.js +0 -46
  16. package/dist/src/broker/native/command-helper.c +0 -93
  17. package/dist/src/broker/native/fs-helper.c +0 -529
  18. package/dist/src/broker/native/git-helper.c +0 -205
  19. package/dist/src/broker/policy.js +0 -149
  20. package/dist/src/broker/startup-lock.js +0 -14
  21. package/dist/src/broker/types.js +0 -11
  22. package/dist/src/cli/configure.js +0 -208
  23. package/dist/src/cli/daemon.js +0 -369
  24. package/dist/src/cli/helpers.js +0 -112
  25. package/dist/src/cli/main.js +0 -189
  26. package/dist/src/cli/runtime-build.js +0 -38
  27. package/dist/src/config/coding-policy.js +0 -4
  28. package/dist/src/config/deployment.js +0 -183
  29. package/dist/src/config/documents.js +0 -29
  30. package/dist/src/config/profile-validation.js +0 -129
  31. package/dist/src/config/schema-graph.js +0 -237
  32. package/dist/src/config/schema-loader.js +0 -185
  33. package/dist/src/config/validation-pool.js +0 -105
  34. package/dist/src/config/validation-protocol.js +0 -1
  35. package/dist/src/config/validation-worker.js +0 -106
  36. package/dist/src/config/workflow-language.js +0 -9
  37. package/dist/src/config/workflow-schema.json +0 -545
  38. package/dist/src/config/workflow-types.js +0 -1
  39. package/dist/src/config/workflow-validation.js +0 -95
  40. package/dist/src/engine/budgets.js +0 -50
  41. package/dist/src/engine/clocks.js +0 -27
  42. package/dist/src/engine/commands.js +0 -477
  43. package/dist/src/engine/contracts.js +0 -11
  44. package/dist/src/engine/drain-state.js +0 -31
  45. package/dist/src/engine/effective-permissions.js +0 -120
  46. package/dist/src/engine/instruction-pins.js +0 -205
  47. package/dist/src/engine/retries.js +0 -50
  48. package/dist/src/engine/state.js +0 -1
  49. package/dist/src/engine/timing.js +0 -23
  50. package/dist/src/engine/tool-observations.js +0 -87
  51. package/dist/src/engine/workflow-engine.js +0 -1864
  52. package/dist/src/mcp/catalog.js +0 -71
  53. package/dist/src/mcp/main.js +0 -26
  54. package/dist/src/mcp/server.js +0 -177
  55. package/dist/src/runtime/codex-app-server.js +0 -91
  56. package/dist/src/runtime/codex-executable.js +0 -50
  57. package/dist/src/runtime/containment.js +0 -82
  58. package/dist/src/runtime/engine-driver.js +0 -221
  59. package/dist/src/runtime/json-line-writer.js +0 -192
  60. package/dist/src/runtime/pinned-instruction-sources.js +0 -24
  61. package/dist/src/runtime/protocol-client.js +0 -264
  62. package/dist/src/runtime/protocol-pool.js +0 -183
  63. package/dist/src/runtime/protocol-projection.js +0 -393
  64. package/dist/src/runtime/protocol-types.js +0 -1
  65. package/dist/src/runtime/protocol-worker.js +0 -18
  66. package/dist/src/runtime/provider-bridge.js +0 -290
  67. package/dist/src/runtime/provider-credentials.js +0 -41
  68. package/dist/src/runtime/provider-transport.js +0 -406
  69. package/dist/src/runtime/runtime-broker.js +0 -213
  70. package/dist/src/runtime/workspace-instructions.js +0 -120
  71. package/dist/src/runtime/workspace-view.js +0 -74
  72. package/dist/src/server/api-contract.json +0 -11637
  73. package/dist/src/server/api-types.js +0 -1
  74. package/dist/src/server/application.js +0 -44
  75. package/dist/src/server/auth.js +0 -67
  76. package/dist/src/server/broker-handlers.js +0 -242
  77. package/dist/src/server/coding.js +0 -281
  78. package/dist/src/server/control-plane.js +0 -50
  79. package/dist/src/server/deployment.js +0 -249
  80. package/dist/src/server/errors.js +0 -22
  81. package/dist/src/server/history-handlers.js +0 -130
  82. package/dist/src/server/http.js +0 -124
  83. package/dist/src/server/paging.js +0 -56
  84. package/dist/src/server/publication.js +0 -119
  85. package/dist/src/server/tool-event-handler.js +0 -77
  86. package/dist/src/server/workspace-handlers.js +0 -34
  87. package/dist/src/storage/coordinator.js +0 -224
  88. package/dist/src/storage/startup-lock.js +0 -71
  89. package/dist/src/storage/store.js +0 -167
  90. package/dist/src/tools/check-worker.js +0 -81
  91. package/dist/src/tools/checks.js +0 -117
  92. package/dist/src/tools/command-check.js +0 -34
  93. package/dist/src/tools/commands.js +0 -312
  94. package/dist/src/tools/developer.js +0 -355
  95. package/dist/src/tools/dns.js +0 -248
  96. package/dist/src/tools/http-contract.js +0 -38
  97. package/dist/src/tools/http.js +0 -358
  98. package/dist/src/tools/index.js +0 -194
  99. package/dist/src/tools/worker-check.js +0 -73
  100. package/dist/src/workspaces/git.js +0 -227
  101. package/dist/src/workspaces/index.js +0 -937
  102. package/dist/src/workspaces/source.js +0 -295
  103. package/examples/deployment.local.json +0 -22
  104. package/scripts/postinstall.mjs +0 -26
@@ -1,369 +0,0 @@
1
- import { spawn, spawnSync } from 'node:child_process';
2
- import { randomBytes } from 'node:crypto';
3
- import { chmodSync, closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
4
- import { homedir } from 'node:os';
5
- import { dirname, isAbsolute, join } from 'node:path';
6
- import { setTimeout as delay } from 'node:timers/promises';
7
- import { readOperatorToken, readPrivateFile } from '../config/deployment.js';
8
- import { assertRuntimeBuild } from './runtime-build.js';
9
- const LSOF_ENV = { PATH: '/usr/bin:/bin', LC_ALL: 'C' };
10
- export function defaultStateDirectory() {
11
- return join(homedir(), 'Library', 'Application Support', 'Code60 Transmission', 'state');
12
- }
13
- function assertAbsoluteSafePath(path, label) {
14
- if (!isAbsolute(path) || /[\0\r\n]/.test(path)) {
15
- throw new Error(`${label} must be an absolute path without control characters.`);
16
- }
17
- }
18
- function assertPrivateStateDirectory(path) {
19
- const info = lstatSync(path);
20
- if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== process.geteuid?.() || (info.mode & 0o077)) {
21
- throw new Error(`Expected a private, user-owned directory (mode 0700) at ${path}.`);
22
- }
23
- return realpathSync(path);
24
- }
25
- export function initializeStateDirectory(stateDir, templateConfigPath) {
26
- assertAbsoluteSafePath(stateDir, 'State directory');
27
- mkdirSync(dirname(stateDir), { recursive: true });
28
- if (!existsSync(stateDir)) {
29
- // Publish both private inputs atomically so simultaneous first connections never race.
30
- const stage = mkdtempSync(stateDir + '.');
31
- try {
32
- chmodSync(stage, 0o700);
33
- writeFileSync(join(stage, 'configuration.json'), readFileSync(templateConfigPath), { mode: 0o600 });
34
- writeFileSync(join(stage, 'operator.token'), randomBytes(32).toString('base64url') + '\n', { mode: 0o600 });
35
- try {
36
- renameSync(stage, stateDir);
37
- }
38
- catch (error) {
39
- const code = error.code;
40
- if (code !== 'ENOTEMPTY' && code !== 'EEXIST')
41
- throw error;
42
- }
43
- }
44
- finally {
45
- rmSync(stage, { recursive: true, force: true });
46
- }
47
- }
48
- const physical = assertPrivateStateDirectory(stateDir);
49
- if (readdirSync(physical).length === 0) {
50
- for (const [name, content] of [
51
- ['configuration.json', readFileSync(templateConfigPath)],
52
- ['operator.token', randomBytes(32).toString('base64url') + '\n'],
53
- ]) {
54
- try {
55
- writeFileSync(join(physical, name), content, { mode: 0o600, flag: 'wx' });
56
- }
57
- catch (error) {
58
- if (error.code !== 'EEXIST')
59
- throw error;
60
- }
61
- }
62
- }
63
- const configurationFile = join(physical, 'configuration.json');
64
- const operatorTokenFile = join(physical, 'operator.token');
65
- if (!existsSync(configurationFile)) {
66
- throw new Error(`Missing private deployment configuration at ${configurationFile}.`);
67
- }
68
- if (!existsSync(operatorTokenFile)) {
69
- throw new Error(`Missing private operator token at ${operatorTokenFile}.`);
70
- }
71
- // Validate the private token file early before spawning a background daemon.
72
- readOperatorToken(operatorTokenFile);
73
- return {
74
- stateDirectory: physical,
75
- configurationFile,
76
- operatorTokenFile,
77
- logFile: join(physical, 'engine.log'),
78
- };
79
- }
80
- export function readConfiguredListenPort(configurationFile) {
81
- const bytes = readPrivateFile(configurationFile, 262_144);
82
- let parsed;
83
- try {
84
- parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
85
- }
86
- catch (error) {
87
- if (error instanceof SyntaxError)
88
- throw new Error(`Invalid JSON in ${configurationFile}.`);
89
- throw error;
90
- }
91
- const port = parsed && typeof parsed === 'object' ? parsed.listenPort : undefined;
92
- if (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535) {
93
- throw new Error(`Invalid listenPort in ${configurationFile}.`);
94
- }
95
- return port;
96
- }
97
- function runLsof(args) {
98
- const result = spawnSync('/usr/sbin/lsof', args, {
99
- encoding: 'utf8',
100
- timeout: 5_000,
101
- maxBuffer: 2 * 1_048_576,
102
- env: LSOF_ENV,
103
- });
104
- return { status: result.status, stdout: result.stdout ?? '' };
105
- }
106
- function parseLsofPidNames(stdout) {
107
- const entries = [];
108
- let current;
109
- for (const line of stdout.split('\n')) {
110
- if (line.startsWith('p')) {
111
- const pid = Number(line.slice(1));
112
- if (Number.isInteger(pid) && pid > 0) {
113
- current = { pid, names: [] };
114
- entries.push(current);
115
- }
116
- else {
117
- current = undefined;
118
- }
119
- }
120
- else if (line.startsWith('n') && current) {
121
- current.names.push(line.slice(1));
122
- }
123
- }
124
- return entries;
125
- }
126
- export function isPidListeningOnPort(pid, port) {
127
- const result = runLsof(['-nP', '-a', '-p', String(pid), `-iTCP@127.0.0.1:${port}`, '-sTCP:LISTEN', '-Fn']);
128
- return result.status === 0 && result.stdout.split('\n').includes(`n127.0.0.1:${port}`);
129
- }
130
- export function doesPidHoldFile(pid, filePath) {
131
- const result = runLsof(['-nP', '-a', '-p', String(pid), '-Fn', '--', filePath]);
132
- return result.status === 0 && result.stdout.split('\n').includes(`n${filePath}`);
133
- }
134
- function findLoopbackListenPortForPid(pid) {
135
- const result = runLsof(['-nP', '-a', '-p', String(pid), '-iTCP@127.0.0.1', '-sTCP:LISTEN', '-Fn']);
136
- if (result.status !== 0)
137
- return undefined;
138
- for (const line of result.stdout.split('\n')) {
139
- const match = /^n127\.0\.0\.1:([0-9]+)$/.exec(line);
140
- if (match) {
141
- const port = Number(match[1]);
142
- if (Number.isInteger(port) && port >= 1 && port <= 65535)
143
- return port;
144
- }
145
- }
146
- return undefined;
147
- }
148
- export function findLockHolderPids(lockPath) {
149
- if (!existsSync(lockPath))
150
- return [];
151
- const uid = process.geteuid?.();
152
- if (uid === undefined)
153
- return [];
154
- const result = runLsof(['-nP', '-a', '-u', String(uid), '-Fp', '--', lockPath]);
155
- if (result.status !== 0)
156
- return [];
157
- const pids = new Set();
158
- for (const line of result.stdout.split('\n')) {
159
- const match = /^p([0-9]+)$/.exec(line);
160
- if (match)
161
- pids.add(Number(match[1]));
162
- }
163
- return [...pids];
164
- }
165
- /**
166
- * Verifies at the OS level that a current-user process both listens on the loopback port
167
- * and holds this state directory's startup.lock — never transmitting the operator token to
168
- * an unverified listener.
169
- */
170
- export function findRunningEngine(stateDir, listenPort) {
171
- if (!existsSync(stateDir))
172
- return undefined;
173
- let physical;
174
- try {
175
- physical = realpathSync(stateDir);
176
- }
177
- catch {
178
- return undefined;
179
- }
180
- const lockPath = join(physical, 'startup.lock');
181
- if (!existsSync(lockPath))
182
- return undefined;
183
- const uid = process.geteuid?.();
184
- if (uid === undefined)
185
- return undefined;
186
- if (listenPort !== undefined) {
187
- const result = runLsof(['-nP', '-a', '-u', String(uid), `-iTCP@127.0.0.1:${listenPort}`, '-sTCP:LISTEN', '-Fpn']);
188
- if (result.status !== 0)
189
- return undefined;
190
- const expected = `127.0.0.1:${listenPort}`;
191
- for (const entry of parseLsofPidNames(result.stdout)) {
192
- if (entry.names.includes(expected) && doesPidHoldFile(entry.pid, lockPath)) {
193
- return { pid: entry.pid, port: listenPort };
194
- }
195
- }
196
- return undefined;
197
- }
198
- for (const pid of findLockHolderPids(lockPath)) {
199
- const port = findLoopbackListenPortForPid(pid);
200
- if (port !== undefined)
201
- return { pid, port };
202
- }
203
- return undefined;
204
- }
205
- function openPrivateLogFile(logFile) {
206
- const fd = openSync(logFile, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
207
- try {
208
- const stat = fstatSync(fd);
209
- if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.geteuid?.() || (stat.mode & 0o077)) {
210
- throw new Error(`Engine log must be a private, user-owned regular file at ${logFile}.`);
211
- }
212
- return fd;
213
- }
214
- catch (error) {
215
- closeSync(fd);
216
- throw error;
217
- }
218
- }
219
- function isPidAlive(pid) {
220
- try {
221
- process.kill(pid, 0);
222
- return true;
223
- }
224
- catch (error) {
225
- if (error.code === 'ESRCH')
226
- return false;
227
- return true;
228
- }
229
- }
230
- export async function ensureEngineRunning(options) {
231
- const { statePaths, listenPort, fsHelperPath, gitHelperPath, cliEntrypoint } = options;
232
- const { stateDirectory, configurationFile, logFile } = statePaths;
233
- const lockPath = join(stateDirectory, 'startup.lock');
234
- const already = findRunningEngine(stateDirectory, listenPort);
235
- if (already) {
236
- assertRuntimeBuild(stateDirectory, already.pid);
237
- return { ...already, started: false };
238
- }
239
- const otherPort = findRunningEngine(stateDirectory);
240
- if (otherPort && otherPort.port !== listenPort) {
241
- throw new Error(`Engine for ${stateDirectory} is already running on 127.0.0.1:${otherPort.port} (PID ${otherPort.pid}). ` +
242
- `Stop it with "code60 stop" before switching to port ${listenPort}.`);
243
- }
244
- const logFd = openPrivateLogFile(logFile);
245
- let childPid;
246
- let childExited = false;
247
- let child;
248
- try {
249
- child = spawn(process.execPath, [
250
- cliEntrypoint,
251
- 'engine',
252
- '--state-directory', stateDirectory,
253
- '--fs-helper', fsHelperPath,
254
- '--git-helper', gitHelperPath,
255
- ], {
256
- detached: true,
257
- stdio: ['ignore', 'ignore', logFd],
258
- });
259
- childPid = child.pid;
260
- child.once('exit', () => { childExited = true; });
261
- child.once('error', () => { childExited = true; });
262
- child.unref();
263
- }
264
- finally {
265
- closeSync(logFd);
266
- }
267
- const deadline = Date.now() + (options.timeoutMs ?? 15_000);
268
- try {
269
- while (Date.now() < deadline) {
270
- if (childPid !== undefined && !childExited && isPidListeningOnPort(childPid, listenPort) && doesPidHoldFile(childPid, lockPath)) {
271
- return { pid: childPid, port: listenPort, started: true };
272
- }
273
- const winner = findRunningEngine(stateDirectory, listenPort);
274
- if (winner) {
275
- assertRuntimeBuild(stateDirectory, winner.pid);
276
- return { ...winner, started: winner.pid === childPid };
277
- }
278
- if (childPid !== undefined && !isPidAlive(childPid)) {
279
- childExited = true;
280
- }
281
- if (childExited) {
282
- const lockHolders = findLockHolderPids(lockPath);
283
- if (lockHolders.length === 0)
284
- break;
285
- const mismatch = findRunningEngine(stateDirectory);
286
- if (mismatch && mismatch.port !== listenPort) {
287
- throw new Error(`Engine for ${stateDirectory} is already running on 127.0.0.1:${mismatch.port} (PID ${mismatch.pid}). ` +
288
- `Stop it with "code60 stop" before switching to port ${listenPort}.`);
289
- }
290
- }
291
- await delay(100);
292
- }
293
- throw new Error(`Engine did not open 127.0.0.1:${listenPort}. Check ${configurationFile} and ${logFile}.`);
294
- }
295
- finally {
296
- child?.removeAllListeners('exit');
297
- child?.removeAllListeners('error');
298
- }
299
- }
300
- export function getEngineStatus(stateDir) {
301
- assertAbsoluteSafePath(stateDir, 'State directory');
302
- if (!existsSync(stateDir)) {
303
- return {
304
- initialized: false,
305
- state: 'stopped',
306
- stateDirectory: stateDir,
307
- configurationFile: join(stateDir, 'configuration.json'),
308
- };
309
- }
310
- const physical = assertPrivateStateDirectory(stateDir);
311
- const configurationFile = join(physical, 'configuration.json');
312
- let configuredPort;
313
- if (existsSync(configurationFile)) {
314
- try {
315
- configuredPort = readConfiguredListenPort(configurationFile);
316
- }
317
- catch {
318
- // Leave configuredPort undefined if the configuration file is incomplete/invalid.
319
- }
320
- }
321
- const running = (configuredPort !== undefined ? findRunningEngine(physical, configuredPort) : undefined)
322
- ?? findRunningEngine(physical);
323
- return {
324
- initialized: existsSync(configurationFile) && existsSync(join(physical, 'operator.token')),
325
- state: running ? 'running' : 'stopped',
326
- stateDirectory: physical,
327
- configurationFile,
328
- ...(configuredPort !== undefined ? { configuredPort } : {}),
329
- ...(running ? { listenPort: running.port, pid: running.pid } : {}),
330
- };
331
- }
332
- export async function stopEngine(stateDir, timeoutMs = 10_000) {
333
- assertAbsoluteSafePath(stateDir, 'State directory');
334
- if (!existsSync(stateDir))
335
- return { stopped: false };
336
- const physical = assertPrivateStateDirectory(stateDir);
337
- const configurationFile = join(physical, 'configuration.json');
338
- let configuredPort;
339
- if (existsSync(configurationFile)) {
340
- try {
341
- configuredPort = readConfiguredListenPort(configurationFile);
342
- }
343
- catch {
344
- // Fall back to any-port lock discovery.
345
- }
346
- }
347
- const running = (configuredPort !== undefined ? findRunningEngine(physical, configuredPort) : undefined)
348
- ?? findRunningEngine(physical);
349
- if (!running)
350
- return { stopped: false };
351
- const lockPath = join(physical, 'startup.lock');
352
- try {
353
- process.kill(running.pid, 'SIGTERM');
354
- }
355
- catch (error) {
356
- if (error.code === 'ESRCH') {
357
- return { stopped: true, pid: running.pid, port: running.port };
358
- }
359
- throw error;
360
- }
361
- const deadline = Date.now() + timeoutMs;
362
- while (Date.now() < deadline) {
363
- if (!isPidAlive(running.pid) && findLockHolderPids(lockPath).length === 0) {
364
- return { stopped: true, pid: running.pid, port: running.port };
365
- }
366
- await delay(100);
367
- }
368
- throw new Error(`Engine PID ${running.pid} did not stop within ${timeoutMs}ms. Active work may still be draining; check ${join(physical, 'engine.log')}.`);
369
- }
@@ -1,112 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { accessSync, constants, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
3
- import { dirname, isAbsolute, join } from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import { buildFilesystemHelper, buildGitHelper, buildCommandHelper } from '../broker/native/build.js';
6
- export function packageRoot() {
7
- let current = import.meta.dirname;
8
- for (let depth = 0; depth < 5; depth++) {
9
- const manifest = join(current, 'package.json');
10
- if (existsSync(manifest)) {
11
- try {
12
- const parsed = JSON.parse(readFileSync(manifest, 'utf8'));
13
- if (parsed.name === 'code60-transmission-server')
14
- return current;
15
- }
16
- catch {
17
- // Continue walking upward if an unrelated package.json cannot be parsed.
18
- }
19
- }
20
- const parent = dirname(current);
21
- if (parent === current)
22
- break;
23
- current = parent;
24
- }
25
- throw new Error('Could not locate code60-transmission-server package root.');
26
- }
27
- export function packageVersion() {
28
- const parsed = JSON.parse(readFileSync(join(packageRoot(), 'package.json'), 'utf8'));
29
- return typeof parsed.version === 'string' ? parsed.version : '0.0.0';
30
- }
31
- export function defaultTemplateConfigurationPath() {
32
- const root = packageRoot(), source = join(root, 'examples', 'deployment.local.json');
33
- return existsSync(source) ? source : join(root, 'deployment.local.json');
34
- }
35
- /** Matches the exact trust invariants enforced by startup-lock.ts, filesystem.ts, and git.ts. */
36
- export function isTrustedHelper(helperPath) {
37
- if (!isAbsolute(helperPath) || /[\0\r\n]/.test(helperPath))
38
- return false;
39
- try {
40
- const parent = lstatSync(dirname(helperPath));
41
- if (!parent.isDirectory() || parent.isSymbolicLink())
42
- return false;
43
- const stat = lstatSync(helperPath);
44
- if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 ||
45
- stat.uid !== process.geteuid?.() || (stat.mode & 0o6022)) {
46
- return false;
47
- }
48
- accessSync(helperPath, constants.X_OK);
49
- return true;
50
- }
51
- catch {
52
- return false;
53
- }
54
- }
55
- function ensurePrivateDirectory(path) {
56
- mkdirSync(path, { mode: 0o700, recursive: true });
57
- const stat = lstatSync(path);
58
- if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.geteuid?.() || (stat.mode & 0o077)) {
59
- throw new Error(`Expected a private, user-owned directory at ${path}.`);
60
- }
61
- return realpathSync(path);
62
- }
63
- function nativeSourceDigest(nativeDir) {
64
- const hash = createHash('sha256');
65
- hash.update(process.arch);
66
- hash.update('\0');
67
- hash.update(readFileSync(join(nativeDir, 'fs-helper.c')));
68
- hash.update('\0');
69
- hash.update(readFileSync(join(nativeDir, 'git-helper.c')));
70
- hash.update('\0');
71
- hash.update(readFileSync(join(nativeDir, 'command-helper.c')));
72
- return hash.digest('hex').slice(0, 16);
73
- }
74
- export function resolveNativeHelpers(stateDir, options = {}) {
75
- const nativeDir = fileURLToPath(new URL('../broker/native/', import.meta.url));
76
- const candidateDir = options.packageHelperDirectory ?? join(nativeDir, '.build');
77
- const packagedFs = join(candidateDir, 'fs-helper');
78
- const packagedGit = join(candidateDir, 'git-helper');
79
- if (isTrustedHelper(packagedFs) && isTrustedHelper(packagedGit) && isTrustedHelper(join(candidateDir, 'command-helper'))) {
80
- return {
81
- fsHelperPath: realpathSync(packagedFs),
82
- gitHelperPath: realpathSync(packagedGit),
83
- builtOnDemand: false,
84
- };
85
- }
86
- const helpersRoot = ensurePrivateDirectory(join(stateDir, 'helpers'));
87
- const targetDir = ensurePrivateDirectory(join(helpersRoot, `${process.arch}-${nativeSourceDigest(nativeDir)}`));
88
- const fsTarget = join(targetDir, 'fs-helper');
89
- const gitTarget = join(targetDir, 'git-helper');
90
- const commandTarget = join(targetDir, 'command-helper');
91
- let builtOnDemand = false;
92
- if (!isTrustedHelper(fsTarget)) {
93
- buildFilesystemHelper({ outputDirectory: targetDir });
94
- builtOnDemand = true;
95
- }
96
- if (!isTrustedHelper(gitTarget)) {
97
- buildGitHelper({ outputDirectory: targetDir });
98
- builtOnDemand = true;
99
- }
100
- if (!isTrustedHelper(commandTarget)) {
101
- buildCommandHelper({ outputDirectory: targetDir });
102
- builtOnDemand = true;
103
- }
104
- if (!isTrustedHelper(fsTarget) || !isTrustedHelper(gitTarget) || !isTrustedHelper(commandTarget)) {
105
- throw new Error(`Compiled native helpers in ${targetDir} failed trust validation.`);
106
- }
107
- return {
108
- fsHelperPath: realpathSync(fsTarget),
109
- gitHelperPath: realpathSync(gitTarget),
110
- builtOnDemand,
111
- };
112
- }
@@ -1,189 +0,0 @@
1
- #!/usr/bin/env node
2
- import { configurationCli } from './configure.js';
3
- import { realpathSync } from 'node:fs';
4
- import { isAbsolute } from 'node:path';
5
- import { fileURLToPath } from 'node:url';
6
- import { parseArgs } from 'node:util';
7
- import { main as runEngineMain } from '../main.js';
8
- import { main as runMcpBridge } from '../mcp/main.js';
9
- import { defaultStateDirectory, ensureEngineRunning, getEngineStatus, initializeStateDirectory, readConfiguredListenPort, stopEngine, } from './daemon.js';
10
- import { defaultTemplateConfigurationPath, packageVersion, resolveNativeHelpers } from './helpers.js';
11
- const USAGE = `Usage:
12
- code60-transmission-server [mcp] [--state-directory <abs-path>]
13
- code60-transmission-server [mcp] --port <port> --operator-token-file <abs-path>
14
- code60-transmission-server engine [--state-directory <abs-path>]
15
- code60-transmission-server status [--state-directory <abs-path>]
16
- code60-transmission-server stop [--state-directory <abs-path>]
17
- code60-transmission-server mcp-config [--state-directory <abs-path>]
18
- code60-transmission-server configure | doctor [options]
19
- code60-transmission-server --help | --version
20
- `;
21
- const COMMANDS = new Set(['mcp', 'engine', 'status', 'stop', 'mcp-config']);
22
- export function parseCliArguments(argv) {
23
- let command = 'mcp';
24
- let rest = [...argv];
25
- if (rest[0] && !rest[0].startsWith('-')) {
26
- if (!COMMANDS.has(rest[0])) {
27
- throw new Error(`Unknown command "${rest[0]}".\n\n${USAGE}`);
28
- }
29
- command = rest[0];
30
- rest = rest.slice(1);
31
- }
32
- const { values, positionals } = parseArgs({
33
- args: rest,
34
- allowPositionals: false,
35
- options: {
36
- help: { type: 'boolean', short: 'h' },
37
- version: { type: 'boolean', short: 'v' },
38
- 'state-directory': { type: 'string' },
39
- port: { type: 'string' },
40
- 'operator-token-file': { type: 'string' },
41
- 'fs-helper': { type: 'string' },
42
- 'git-helper': { type: 'string' },
43
- toolset: { type: 'string' },
44
- },
45
- });
46
- if (positionals.length > 0) {
47
- throw new Error(`Unexpected arguments.\n\n${USAGE}`);
48
- }
49
- if (values.help)
50
- return { command: 'help' };
51
- if (values.version)
52
- return { command: 'version' };
53
- const stateDirectory = values['state-directory'];
54
- const port = values.port;
55
- const operatorTokenFile = values['operator-token-file'];
56
- const fsHelperPath = values['fs-helper'];
57
- const gitHelperPath = values['git-helper'];
58
- if (stateDirectory !== undefined && (!isAbsolute(stateDirectory) || /[\0\r\n]/.test(stateDirectory))) {
59
- throw new Error('--state-directory must be an absolute path.');
60
- }
61
- if ((port !== undefined || operatorTokenFile !== undefined) && command !== 'mcp') {
62
- throw new Error('--port and --operator-token-file are only supported with the mcp command.');
63
- }
64
- if ((port !== undefined || operatorTokenFile !== undefined) && stateDirectory !== undefined) {
65
- throw new Error('Cannot combine --state-directory with --port or --operator-token-file.');
66
- }
67
- if ((port !== undefined) !== (operatorTokenFile !== undefined)) {
68
- throw new Error('Supply both --port and --operator-token-file for direct bridge mode.');
69
- }
70
- if ((fsHelperPath !== undefined || gitHelperPath !== undefined) && command !== 'engine') {
71
- throw new Error('--fs-helper and --git-helper are only supported with the engine command.');
72
- }
73
- if ((fsHelperPath !== undefined) !== (gitHelperPath !== undefined)) {
74
- throw new Error('Supply both --fs-helper and --git-helper together.');
75
- }
76
- return {
77
- command,
78
- ...(values.toolset ? { toolset: (() => { if (!['coding', 'admin'].includes(values.toolset))
79
- throw new Error('Invalid --toolset.'); return values.toolset; })() } : {}),
80
- ...(stateDirectory !== undefined ? { stateDirectory } : {}),
81
- ...(port !== undefined ? { port } : {}),
82
- ...(operatorTokenFile !== undefined ? { operatorTokenFile } : {}),
83
- ...(fsHelperPath !== undefined ? { fsHelperPath } : {}),
84
- ...(gitHelperPath !== undefined ? { gitHelperPath } : {}),
85
- };
86
- }
87
- export function formatMcpConfig(stateDirectory) {
88
- const args = ['-y', `code60-transmission-server@${packageVersion()}`];
89
- if (stateDirectory !== undefined) {
90
- args.push('--state-directory', stateDirectory);
91
- }
92
- return {
93
- mcpServers: {
94
- code60: {
95
- command: 'npx',
96
- args,
97
- },
98
- },
99
- };
100
- }
101
- function assertMacOS() {
102
- if (process.platform !== 'darwin') {
103
- throw new Error('Code60 Transmission Server requires macOS for native workspace and runtime containment.');
104
- }
105
- }
106
- export async function runCli(argv = process.argv.slice(2)) {
107
- process.umask(0o077);
108
- if (['configure', 'doctor'].includes(argv[0] ?? '')) {
109
- await configurationCli(argv);
110
- return;
111
- }
112
- const parsed = parseCliArguments(argv);
113
- if (parsed.command === 'help') {
114
- process.stdout.write(USAGE);
115
- return;
116
- }
117
- if (parsed.command === 'version') {
118
- process.stdout.write(`${packageVersion()}\n`);
119
- return;
120
- }
121
- if (parsed.command === 'mcp-config') {
122
- process.stdout.write(`${JSON.stringify(formatMcpConfig(parsed.stateDirectory), null, 2)}\n`);
123
- return;
124
- }
125
- // Direct stdio bridge mode to an already-running engine.
126
- if (parsed.command === 'mcp' && parsed.port !== undefined && parsed.operatorTokenFile !== undefined) {
127
- await runMcpBridge(['--port', parsed.port, '--operator-token-file', parsed.operatorTokenFile, '--toolset', parsed.toolset ?? 'coding']);
128
- return;
129
- }
130
- assertMacOS();
131
- const stateDir = parsed.stateDirectory ?? defaultStateDirectory();
132
- if (parsed.command === 'status') {
133
- process.stdout.write(`${JSON.stringify(getEngineStatus(stateDir), null, 2)}\n`);
134
- return;
135
- }
136
- if (parsed.command === 'stop') {
137
- const result = await stopEngine(stateDir);
138
- if (result.stopped) {
139
- process.stdout.write(`Stopped Code60 Transmission engine (PID ${result.pid}, port ${result.port}).\n`);
140
- }
141
- else {
142
- process.stdout.write(`Code60 Transmission engine is not running for ${stateDir}.\n`);
143
- }
144
- return;
145
- }
146
- const statePaths = initializeStateDirectory(stateDir, defaultTemplateConfigurationPath());
147
- if (parsed.command === 'engine') {
148
- const helpers = parsed.fsHelperPath !== undefined && parsed.gitHelperPath !== undefined
149
- ? { fsHelperPath: parsed.fsHelperPath, gitHelperPath: parsed.gitHelperPath }
150
- : resolveNativeHelpers(statePaths.stateDirectory);
151
- await runEngineMain([
152
- '--state-directory', statePaths.stateDirectory,
153
- '--configuration', statePaths.configurationFile,
154
- '--operator-token-file', statePaths.operatorTokenFile,
155
- '--fs-helper', helpers.fsHelperPath,
156
- '--git-helper', helpers.gitHelperPath,
157
- ]);
158
- return;
159
- }
160
- // Managed MCP mode: ensure shared detached background engine is running, then attach stdio bridge.
161
- const listenPort = readConfiguredListenPort(statePaths.configurationFile);
162
- const helpers = resolveNativeHelpers(statePaths.stateDirectory);
163
- const cliEntrypoint = realpathSync(fileURLToPath(import.meta.url));
164
- await ensureEngineRunning({
165
- statePaths,
166
- listenPort,
167
- fsHelperPath: helpers.fsHelperPath,
168
- gitHelperPath: helpers.gitHelperPath,
169
- cliEntrypoint,
170
- });
171
- await runMcpBridge(['--port', String(listenPort), '--operator-token-file', statePaths.operatorTokenFile, '--toolset', parsed.toolset ?? 'coding']);
172
- }
173
- function isDirectExecution() {
174
- if (!process.argv[1])
175
- return false;
176
- try {
177
- return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
178
- }
179
- catch {
180
- return false;
181
- }
182
- }
183
- if (isDirectExecution()) {
184
- void runCli().catch(error => {
185
- const message = error instanceof Error ? error.message : 'Code60 CLI failed.';
186
- process.stderr.write(`${message}\n`);
187
- process.exitCode = 1;
188
- });
189
- }