code60-transmission-server 0.1.0 → 0.1.1

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