code60-transmission-server 0.0.0-stage → 0.1.0-staging.2

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 (88) hide show
  1. package/LICENSE +180 -0
  2. package/README.engine.md +401 -0
  3. package/README.md +291 -2
  4. package/dist/src/broker/filesystem.js +385 -0
  5. package/dist/src/broker/index.js +734 -0
  6. package/dist/src/broker/native/README.md +192 -0
  7. package/dist/src/broker/native/build.js +43 -0
  8. package/dist/src/broker/native/fs-helper.c +529 -0
  9. package/dist/src/broker/native/git-helper.c +205 -0
  10. package/dist/src/broker/policy.js +149 -0
  11. package/dist/src/broker/startup-lock.js +14 -0
  12. package/dist/src/broker/types.js +11 -0
  13. package/dist/src/cli/daemon.js +365 -0
  14. package/dist/src/cli/helpers.js +104 -0
  15. package/dist/src/cli/main.js +180 -0
  16. package/dist/src/config/deployment.js +163 -0
  17. package/dist/src/config/documents.js +29 -0
  18. package/dist/src/config/profile-validation.js +123 -0
  19. package/dist/src/config/schema-graph.js +237 -0
  20. package/dist/src/config/schema-loader.js +185 -0
  21. package/dist/src/config/validation-pool.js +105 -0
  22. package/dist/src/config/validation-protocol.js +1 -0
  23. package/dist/src/config/validation-worker.js +106 -0
  24. package/dist/src/config/workflow-language.js +9 -0
  25. package/dist/src/config/workflow-schema.json +534 -0
  26. package/dist/src/config/workflow-types.js +1 -0
  27. package/dist/src/config/workflow-validation.js +95 -0
  28. package/dist/src/engine/budgets.js +50 -0
  29. package/dist/src/engine/clocks.js +27 -0
  30. package/dist/src/engine/commands.js +441 -0
  31. package/dist/src/engine/contracts.js +11 -0
  32. package/dist/src/engine/drain-state.js +31 -0
  33. package/dist/src/engine/effective-permissions.js +120 -0
  34. package/dist/src/engine/instruction-pins.js +205 -0
  35. package/dist/src/engine/retries.js +50 -0
  36. package/dist/src/engine/state.js +1 -0
  37. package/dist/src/engine/timing.js +23 -0
  38. package/dist/src/engine/tool-observations.js +87 -0
  39. package/dist/src/engine/workflow-engine.js +1807 -0
  40. package/dist/src/main.js +25 -0
  41. package/dist/src/mcp/catalog.js +71 -0
  42. package/dist/src/mcp/main.js +24 -0
  43. package/dist/src/mcp/server.js +104 -0
  44. package/dist/src/runtime/codex-app-server.js +91 -0
  45. package/dist/src/runtime/containment.js +82 -0
  46. package/dist/src/runtime/engine-driver.js +212 -0
  47. package/dist/src/runtime/json-line-writer.js +192 -0
  48. package/dist/src/runtime/pinned-instruction-sources.js +24 -0
  49. package/dist/src/runtime/protocol-client.js +264 -0
  50. package/dist/src/runtime/protocol-pool.js +183 -0
  51. package/dist/src/runtime/protocol-projection.js +393 -0
  52. package/dist/src/runtime/protocol-types.js +1 -0
  53. package/dist/src/runtime/protocol-worker.js +18 -0
  54. package/dist/src/runtime/provider-bridge.js +288 -0
  55. package/dist/src/runtime/provider-credentials.js +41 -0
  56. package/dist/src/runtime/provider-transport.js +404 -0
  57. package/dist/src/runtime/runtime-broker.js +213 -0
  58. package/dist/src/runtime/workspace-instructions.js +120 -0
  59. package/dist/src/runtime/workspace-view.js +74 -0
  60. package/dist/src/server/api-contract.json +11078 -0
  61. package/dist/src/server/api-types.js +1 -0
  62. package/dist/src/server/application.js +38 -0
  63. package/dist/src/server/auth.js +67 -0
  64. package/dist/src/server/broker-handlers.js +242 -0
  65. package/dist/src/server/control-plane.js +50 -0
  66. package/dist/src/server/deployment.js +237 -0
  67. package/dist/src/server/errors.js +22 -0
  68. package/dist/src/server/history-handlers.js +113 -0
  69. package/dist/src/server/http.js +124 -0
  70. package/dist/src/server/paging.js +56 -0
  71. package/dist/src/server/publication.js +119 -0
  72. package/dist/src/server/tool-event-handler.js +77 -0
  73. package/dist/src/server/workspace-handlers.js +34 -0
  74. package/dist/src/storage/coordinator.js +224 -0
  75. package/dist/src/storage/startup-lock.js +71 -0
  76. package/dist/src/storage/store.js +167 -0
  77. package/dist/src/tools/check-worker.js +81 -0
  78. package/dist/src/tools/checks.js +106 -0
  79. package/dist/src/tools/dns.js +248 -0
  80. package/dist/src/tools/http-contract.js +38 -0
  81. package/dist/src/tools/http.js +358 -0
  82. package/dist/src/tools/index.js +177 -0
  83. package/dist/src/tools/worker-check.js +73 -0
  84. package/dist/src/workspaces/git.js +227 -0
  85. package/dist/src/workspaces/index.js +715 -0
  86. package/examples/deployment.local.json +22 -0
  87. package/package.json +68 -4
  88. package/scripts/postinstall.mjs +25 -0
@@ -0,0 +1,192 @@
1
+ function* stringParts(value) {
2
+ yield '"';
3
+ // Keep valid pairs together for byte-for-byte JSON.stringify compatibility,
4
+ // while preserving lone surrogates as JSON escapes.
5
+ for (let offset = 0; offset < value.length;) {
6
+ let end = Math.min(offset + 8192, value.length);
7
+ if (end < value.length && value.charCodeAt(end - 1) >= 0xd800 && value.charCodeAt(end - 1) <= 0xdbff &&
8
+ value.charCodeAt(end) >= 0xdc00 && value.charCodeAt(end) <= 0xdfff)
9
+ end--;
10
+ yield JSON.stringify(value.slice(offset, end)).slice(1, -1);
11
+ offset = end;
12
+ }
13
+ yield '"';
14
+ }
15
+ /** Strict JSON data only, without arbitrary getters/toJSON or a second full
16
+ * serialized copy. Iterative traversal does not use the JavaScript call stack. */
17
+ export function* jsonLineParts(value) {
18
+ const stack = [{ kind: 'value', value }], ancestors = new Set();
19
+ while (stack.length) {
20
+ const frame = stack.at(-1);
21
+ if (frame.kind === 'value') {
22
+ stack.pop();
23
+ const item = frame.value;
24
+ if (item === null) {
25
+ yield 'null';
26
+ continue;
27
+ }
28
+ if (typeof item === 'string') {
29
+ yield* stringParts(item);
30
+ continue;
31
+ }
32
+ if (typeof item === 'boolean') {
33
+ yield String(item);
34
+ continue;
35
+ }
36
+ if (typeof item === 'number' && Number.isFinite(item)) {
37
+ yield JSON.stringify(item);
38
+ continue;
39
+ }
40
+ if (!item || typeof item !== 'object' || ancestors.has(item))
41
+ throw new Error('non_json_protocol_value');
42
+ const array = Array.isArray(item), prototype = Object.getPrototypeOf(item);
43
+ if (!array && prototype !== Object.prototype && prototype !== null)
44
+ throw new Error('non_json_protocol_value');
45
+ ancestors.add(item);
46
+ stack.push(array ? { kind: 'array', value: item, index: 0 } :
47
+ { kind: 'object', value: item, keys: Object.keys(item), index: 0, emitted: 0 });
48
+ yield array ? '[' : '{';
49
+ }
50
+ else if (frame.kind === 'array') {
51
+ if (frame.index === frame.value.length) {
52
+ stack.pop();
53
+ ancestors.delete(frame.value);
54
+ yield ']';
55
+ continue;
56
+ }
57
+ if (frame.index)
58
+ yield ',';
59
+ const descriptor = Object.getOwnPropertyDescriptor(frame.value, String(frame.index++));
60
+ if (descriptor && !Object.hasOwn(descriptor, 'value'))
61
+ throw new Error('non_json_protocol_value');
62
+ stack.push({ kind: 'value', value: descriptor?.value === undefined ? null : descriptor.value });
63
+ }
64
+ else {
65
+ if (frame.index === frame.keys.length) {
66
+ stack.pop();
67
+ ancestors.delete(frame.value);
68
+ yield '}';
69
+ continue;
70
+ }
71
+ const key = frame.keys[frame.index++], descriptor = Object.getOwnPropertyDescriptor(frame.value, key);
72
+ if (!Object.hasOwn(descriptor, 'value'))
73
+ throw new Error('non_json_protocol_value');
74
+ if (descriptor.value === undefined)
75
+ continue;
76
+ if (frame.emitted++)
77
+ yield ',';
78
+ yield* stringParts(key);
79
+ yield ':';
80
+ stack.push({ kind: 'value', value: descriptor.value });
81
+ }
82
+ }
83
+ yield '\n';
84
+ }
85
+ /** One ordered byte stream. Each promise includes callback AND drain, not just
86
+ * acceptance into a userland buffer. Failure latches before notifying callers. */
87
+ export class JsonLineWriter {
88
+ stream;
89
+ onFailure;
90
+ maxPending;
91
+ #tail = Promise.resolve();
92
+ #failure;
93
+ #waiters = new Set();
94
+ #pending = 0;
95
+ constructor(stream, onFailure = () => { }, maxPending = 64) {
96
+ this.stream = stream;
97
+ this.onFailure = onFailure;
98
+ this.maxPending = maxPending;
99
+ if (!Number.isSafeInteger(maxPending) || maxPending < 1)
100
+ throw new Error('invalid_protocol_output_capacity');
101
+ stream.on('error', this.#error);
102
+ stream.on('close', this.#closed);
103
+ }
104
+ get pending() { return this.#pending; }
105
+ #error = (error) => this.fail(error);
106
+ #closed = () => this.fail(new Error('protocol_output_closed'));
107
+ fail(error) {
108
+ if (this.#failure)
109
+ return;
110
+ this.#failure = error;
111
+ for (const reject of this.#waiters)
112
+ reject(error);
113
+ this.#waiters.clear();
114
+ try {
115
+ this.onFailure(error);
116
+ }
117
+ catch { /* Failure must remain latched. */ }
118
+ }
119
+ write(value) {
120
+ if (this.#failure)
121
+ return Promise.reject(this.#failure);
122
+ if (this.#pending >= this.maxPending) {
123
+ const error = new Error('protocol_output_capacity');
124
+ this.fail(error);
125
+ return Promise.reject(error);
126
+ }
127
+ this.#pending++;
128
+ const task = this.#tail.then(async () => {
129
+ if (this.#failure)
130
+ throw this.#failure;
131
+ let quantum = 0;
132
+ try {
133
+ for (const part of jsonLineParts(value)) {
134
+ if (this.#failure)
135
+ throw this.#failure;
136
+ await this.#part(part);
137
+ if (++quantum === 64) {
138
+ quantum = 0;
139
+ await new Promise(resolve => setImmediate(resolve));
140
+ }
141
+ }
142
+ }
143
+ catch (error) {
144
+ this.fail(error instanceof Error ? error : new Error('protocol_output_failed'));
145
+ throw this.#failure;
146
+ }
147
+ });
148
+ this.#tail = task.then(() => { this.#pending--; }, () => { this.#pending--; });
149
+ return task;
150
+ }
151
+ #part(part) {
152
+ if (this.#failure)
153
+ return Promise.reject(this.#failure);
154
+ return new Promise((resolve, reject) => {
155
+ let callback = false, drained = false, accepted, settled = false;
156
+ const clean = () => { this.stream.removeListener('drain', drain); this.#waiters.delete(fail); };
157
+ const fail = (error) => { if (settled)
158
+ return; settled = true; clean(); reject(error); };
159
+ const finish = () => { if (!settled && callback && accepted !== undefined && (accepted || drained)) {
160
+ settled = true;
161
+ clean();
162
+ resolve();
163
+ } };
164
+ const drain = () => { drained = true; finish(); };
165
+ this.#waiters.add(fail);
166
+ this.stream.once('drain', drain);
167
+ try {
168
+ accepted = this.stream.write(part, 'utf8', error => {
169
+ if (error) {
170
+ this.fail(error);
171
+ fail(error);
172
+ return;
173
+ }
174
+ callback = true;
175
+ finish();
176
+ });
177
+ finish();
178
+ }
179
+ catch (error) {
180
+ const failure = error instanceof Error ? error : new Error('protocol_output_failed');
181
+ this.fail(failure);
182
+ fail(failure);
183
+ }
184
+ });
185
+ }
186
+ async close() {
187
+ this.fail(new Error('protocol_output_closed'));
188
+ await this.#tail;
189
+ // This writer owns this stream for its lifetime. A late callback/error
190
+ // after close must remain observed; the stream/writer cycle is collectible.
191
+ }
192
+ }
@@ -0,0 +1,24 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { basename, dirname } from 'node:path';
3
+ import { verifyWorkspaceInstructionSnapshot } from './workspace-view.js';
4
+ const hash = (content) => createHash('sha256').update(content, 'utf8').digest('hex');
5
+ /** Derive scoped USER guidance from the owner's immutable leased snapshot.
6
+ * No host directory discovery, symlink traversal, home read, or source reread
7
+ * occurs during recovery. Authored source bytes use the same snapshot. */
8
+ export function workspaceInstructionsFromSources(sources) {
9
+ const files = [];
10
+ for (const source of sources) {
11
+ if (!['AGENTS.md', 'AGENTS.override.md'].includes(basename(source.path)))
12
+ continue;
13
+ if (files.length >= 256 || source.content.length > 1_048_576)
14
+ throw new Error('workspace_instruction_limit');
15
+ const content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(source.content);
16
+ files.push({ path: source.path, resolvedPath: source.path, content, sha256: hash(content), selected: false });
17
+ }
18
+ const selected = files.map(file => ({ ...file, selected: !!file.content.trim() &&
19
+ (basename(file.path) === 'AGENTS.override.md' || !files.some(other => dirname(other.path) === dirname(file.path) &&
20
+ basename(other.path) === 'AGENTS.override.md' && other.content.trim())) })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
21
+ const snapshot = { files: selected, digest: hash(JSON.stringify(selected)) };
22
+ verifyWorkspaceInstructionSnapshot(snapshot);
23
+ return snapshot;
24
+ }
@@ -0,0 +1,264 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { createHash } from 'node:crypto';
3
+ import { JsonLineWriter } from './json-line-writer.js';
4
+ import { protocolPool } from './protocol-pool.js';
5
+ const diagnosticMethods = new Set(['item/tool/call', 'turn/completed', 'turn/started', 'item/started', 'item/completed',
6
+ 'item/agentMessage/delta', 'thread/started', 'thread/status/changed']);
7
+ const safeFailures = new Set(['invalid_protocol_json', 'invalid_protocol_utf8', 'invalid_protocol_envelope', 'truncated_protocol_frame',
8
+ 'unproven_protocol_echo_projection', 'protocol_resource_limit', 'protocol_decoder_capacity', 'protocol_decoder_queue_timeout',
9
+ 'protocol_worker_unavailable', 'protocol_worker_resource_failure', 'protocol_worker_exited', 'protocol_worker_timeout',
10
+ 'protocol_chunk_resource_limit', 'unexpected_protocol_worker_reply', 'protocol_output_capacity', 'protocol_output_closed',
11
+ 'non_json_protocol_value', 'runtime_process_error', 'runtime_process_exited', 'runtime_request_timeout',
12
+ 'runtime_request_capacity', 'duplicate_runtime_request_id', 'protocol_output_ended', 'runtime_stderr_resource_failure']);
13
+ /** Pure stream/process-port client. This class never spawns a process or grants
14
+ * network/filesystem authority. Containment remains the outer owner's job. */
15
+ export class CodexProtocolClient extends EventEmitter {
16
+ child;
17
+ exited;
18
+ #writer;
19
+ #readTask;
20
+ #pool;
21
+ #lease;
22
+ #decoding = 0;
23
+ #id = 0;
24
+ #pending = new Map();
25
+ #requests = new Set();
26
+ #capacity = new Set();
27
+ #fatal;
28
+ #closing;
29
+ #closed = false;
30
+ #trace = [];
31
+ #initializeTrace;
32
+ #traceBytes = 0;
33
+ #stderrBytes = 0;
34
+ #stderrHash = createHash('sha256');
35
+ limits;
36
+ constructor(child, options = {}) {
37
+ super();
38
+ this.child = child;
39
+ this.#pool = options.pool ?? protocolPool();
40
+ this.limits = Object.freeze({ requestTimeoutMs: options.requestTimeoutMs ?? 15000, killGraceMs: options.killGraceMs ?? 1000,
41
+ maxTraceBytes: options.maxTraceBytes ?? 65536, maxOutstandingRequests: options.maxOutstandingRequests ?? 16 });
42
+ if (!Object.values(this.limits).every(value => Number.isSafeInteger(value) && value > 0) ||
43
+ this.limits.requestTimeoutMs > 2_147_483_647 || this.limits.killGraceMs > 2_147_483_647)
44
+ throw new Error('invalid_protocol_client_bounds');
45
+ this.exited = child.exitCode !== null || child.signalCode !== null ? Promise.resolve() :
46
+ new Promise(resolve => { child.once('exit', () => resolve()); child.once('close', () => resolve()); });
47
+ this.#writer = new JsonLineWriter(child.stdin, error => { if (!this.#closing)
48
+ this.#fail(error); });
49
+ child.stderr.on('data', (chunk) => {
50
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
51
+ this.#stderrBytes += bytes.length;
52
+ this.#stderrHash.update(bytes);
53
+ if (!Number.isSafeInteger(this.#stderrBytes))
54
+ this.#fail(new Error('runtime_stderr_resource_failure'));
55
+ });
56
+ child.on('error', () => this.#fail(new Error('runtime_process_error')));
57
+ child.on('exit', () => { if (!this.#closing)
58
+ this.#fail(new Error('runtime_process_exited')); });
59
+ this.#readTask = this.#read();
60
+ }
61
+ get activeWork() { return this.#decoding + this.#writer.pending + (this.#closing && !this.#closed ? 1 : 0); }
62
+ get trace() { return Object.freeze([...this.#trace]); }
63
+ get traceBytes() { return this.#traceBytes; }
64
+ get stderr() {
65
+ return this.#stderrBytes ? `[runtime stderr redacted; bytes=${this.#stderrBytes}; sha256=${this.#stderrHash.copy().digest('hex')}]` : '';
66
+ }
67
+ #record(frame) {
68
+ const message = frame.message, entry = { bytes: frame.bytes, sha256: frame.sha256, echoes: frame.echoes.length };
69
+ if (typeof message.id === 'number' && this.#pending.has(message.id))
70
+ entry.id = message.id;
71
+ if (typeof message.method === 'string' && diagnosticMethods.has(message.method))
72
+ entry.method = message.method;
73
+ const userAgent = message.result?.userAgent;
74
+ if (entry.id === 1 && typeof userAgent === 'string' && Buffer.byteLength(userAgent) <= 512)
75
+ entry.result = Object.freeze({ userAgent });
76
+ const bytes = Buffer.byteLength(JSON.stringify(entry));
77
+ if (bytes > this.limits.maxTraceBytes)
78
+ return;
79
+ while (this.#trace.length && this.#traceBytes + bytes > this.limits.maxTraceBytes) {
80
+ const index = this.#trace.findIndex(value => value !== this.#initializeTrace);
81
+ if (index === -1)
82
+ return;
83
+ this.#traceBytes -= Buffer.byteLength(JSON.stringify(this.#trace.splice(index, 1)[0]));
84
+ }
85
+ const frozen = Object.freeze(entry);
86
+ this.#trace.push(frozen);
87
+ this.#traceBytes += bytes;
88
+ if (entry.id === 1 && entry.result !== undefined)
89
+ this.#initializeTrace = frozen;
90
+ }
91
+ async #read() {
92
+ try {
93
+ for await (const data of this.child.stdout) {
94
+ const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);
95
+ for (let offset = 0; offset < chunk.length && !this.#closing; offset += 65536) {
96
+ if (!this.#lease) {
97
+ this.#decoding++;
98
+ this.#lease = await this.#pool.acquire();
99
+ }
100
+ const result = await this.#lease.write(chunk.subarray(offset, offset + 65536));
101
+ // Keep the worker physically counted through complete-frame delivery.
102
+ if (result.atBoundary) {
103
+ await this.#lease.finish();
104
+ this.#lease = undefined;
105
+ this.#decoding--;
106
+ }
107
+ for (const frame of result.frames) {
108
+ if (this.#closing)
109
+ break;
110
+ this.#record(frame);
111
+ await this.#dispatch(frame.message);
112
+ }
113
+ }
114
+ }
115
+ if (!this.#closing) {
116
+ if (this.#lease)
117
+ await this.#lease.finish();
118
+ throw new Error('protocol_output_ended');
119
+ }
120
+ }
121
+ catch (error) {
122
+ if (!this.#closing)
123
+ this.#fail(error instanceof Error ? error : new Error('protocol_input_failed'));
124
+ }
125
+ finally {
126
+ if (this.#lease) {
127
+ await this.#lease.abort();
128
+ this.#lease = undefined;
129
+ }
130
+ this.#decoding = 0;
131
+ }
132
+ }
133
+ async #dispatch(message) {
134
+ if (typeof message.id === 'number' && message.method === undefined) {
135
+ const pending = this.#pending.get(message.id);
136
+ if (!pending)
137
+ return;
138
+ await pending.sent;
139
+ if (this.#closing)
140
+ return;
141
+ this.#pending.delete(message.id);
142
+ clearTimeout(pending.timer);
143
+ if (message.error)
144
+ pending.reject(new Error('runtime_request_rejected'));
145
+ else
146
+ pending.resolve(message.result);
147
+ // Finish the acknowledged call's promise chain before a same-batch tool
148
+ // request can observe its thread/turn as not yet acknowledged.
149
+ await new Promise(resolve => setImmediate(resolve));
150
+ }
151
+ else if (typeof message.method === 'string' && message.id !== undefined) {
152
+ if (this.#requests.has(message.id))
153
+ throw new Error('duplicate_runtime_request_id');
154
+ // Backpressure limits CONCURRENT requests, not authored total tool calls.
155
+ while (this.#requests.size >= this.limits.maxOutstandingRequests && !this.#closing)
156
+ await new Promise(resolve => this.#capacity.add(resolve));
157
+ if (this.#closing)
158
+ return;
159
+ this.#requests.add(message.id);
160
+ this.emit('serverRequest', message);
161
+ }
162
+ else
163
+ this.emit('notification', message);
164
+ }
165
+ #rejectPending(error) {
166
+ for (const pending of this.#pending.values()) {
167
+ clearTimeout(pending.timer);
168
+ pending.reject(error);
169
+ }
170
+ this.#pending.clear();
171
+ }
172
+ #fail(error) {
173
+ if (this.#fatal || this.#closing)
174
+ return;
175
+ const failure = new Error(safeFailures.has(error.message) ? error.message : 'runtime_transport_failure');
176
+ this.#fatal = failure;
177
+ this.#rejectPending(failure);
178
+ try {
179
+ this.emit('protocolFailure', failure);
180
+ }
181
+ catch { /* Preserve fatal latch and physical cleanup even if an observer fails. */ }
182
+ void this.close().catch(() => { });
183
+ }
184
+ #send(message) {
185
+ if (this.#fatal || this.#closing)
186
+ return Promise.reject(this.#fatal ?? new Error('runtime_closed'));
187
+ return this.#writer.write(message);
188
+ }
189
+ #request(method, params) {
190
+ if (this.#fatal || this.#closing)
191
+ return Promise.reject(this.#fatal ?? new Error('runtime_closed'));
192
+ if (this.#pending.size >= this.limits.maxOutstandingRequests) {
193
+ const error = new Error('runtime_request_capacity');
194
+ this.#fail(error);
195
+ return Promise.reject(error);
196
+ }
197
+ const id = ++this.#id;
198
+ const response = new Promise((resolve, reject) => {
199
+ const timer = setTimeout(() => this.#fail(new Error('runtime_request_timeout')), this.limits.requestTimeoutMs);
200
+ this.#pending.set(id, { resolve, reject, timer, sent: Promise.resolve() });
201
+ });
202
+ const sent = this.#send({ id, method, params });
203
+ const pending = this.#pending.get(id);
204
+ if (pending)
205
+ pending.sent = sent;
206
+ return Promise.all([sent, response]).then(([, result]) => result);
207
+ }
208
+ async initialize() {
209
+ const result = await this.#request('initialize', { clientInfo: { name: 'code60-local-pilot', version: '0.1.0' }, capabilities: { experimentalApi: true } });
210
+ await this.#send({ method: 'initialized', params: {} });
211
+ return result;
212
+ }
213
+ startThread(params) { return this.#request('thread/start', params); }
214
+ startTurn(params) { return this.#request('turn/start', params); }
215
+ async answerRequest(id, result) {
216
+ if (!this.#requests.has(id))
217
+ throw new Error('unknown_runtime_request_id');
218
+ await this.#send({ id, result });
219
+ this.#requests.delete(id);
220
+ for (const resolve of this.#capacity)
221
+ resolve();
222
+ this.#capacity.clear();
223
+ }
224
+ async denyUnknownRequest(id) {
225
+ if (!this.#requests.has(id))
226
+ throw new Error('unknown_runtime_request_id');
227
+ await this.#send({ id, error: { code: -32601, message: 'Unsupported runtime request, denied' } });
228
+ this.#requests.delete(id);
229
+ for (const resolve of this.#capacity)
230
+ resolve();
231
+ this.#capacity.clear();
232
+ }
233
+ close() {
234
+ if (this.#closing)
235
+ return this.#closing;
236
+ // Install the barrier synchronously before stream failure can reenter.
237
+ let complete, failed;
238
+ this.#closing = new Promise((resolve, reject) => { complete = resolve; failed = reject; });
239
+ void (async () => {
240
+ this.#rejectPending(this.#fatal ?? new Error('runtime_closed'));
241
+ for (const resolve of this.#capacity)
242
+ resolve();
243
+ this.#capacity.clear();
244
+ const writes = this.#writer.close();
245
+ this.child.stdout.destroy();
246
+ this.child.stdin.destroy();
247
+ let timer;
248
+ try {
249
+ if (this.child.exitCode === null && this.child.signalCode === null && this.child.pid !== undefined) {
250
+ this.child.kill('SIGTERM');
251
+ timer = setTimeout(() => { this.child.kill('SIGKILL'); }, this.limits.killGraceMs);
252
+ }
253
+ await Promise.all([this.exited, this.#readTask, writes]);
254
+ this.#requests.clear();
255
+ this.#closed = true;
256
+ }
257
+ finally {
258
+ if (timer)
259
+ clearTimeout(timer);
260
+ }
261
+ })().then(complete, failed);
262
+ return this.#closing;
263
+ }
264
+ }
@@ -0,0 +1,183 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ /** One bounded pure worker owns a partial frame/batch until independent exit.
3
+ * Acknowledged partial progress never makes its physical-work barrier vanish. */
4
+ export class ProtocolDecoderLease {
5
+ worker;
6
+ release;
7
+ #error;
8
+ #pending;
9
+ #exit;
10
+ #stop;
11
+ #finished = false;
12
+ #released = false;
13
+ #timer;
14
+ constructor(worker, timeoutMs, release) {
15
+ this.worker = worker;
16
+ this.release = release;
17
+ this.#exit = new Promise(resolve => worker.once('exit', () => {
18
+ if (!this.#finished && !this.#error)
19
+ this.#fail(new Error('protocol_worker_exited'));
20
+ resolve();
21
+ }));
22
+ worker.on('message', (message) => {
23
+ if (message.type === 'failed') {
24
+ this.#fail(new Error(message.code));
25
+ return;
26
+ }
27
+ if (message.type === 'finished')
28
+ this.#finished = true;
29
+ const pending = this.#pending;
30
+ this.#pending = undefined;
31
+ if (!pending) {
32
+ this.#fail(new Error('unexpected_protocol_worker_reply'));
33
+ return;
34
+ }
35
+ pending.resolve(message);
36
+ });
37
+ worker.on('error', () => this.#fail(new Error('protocol_worker_resource_failure')));
38
+ this.#timer = setTimeout(() => { void this.abort(new Error('protocol_worker_timeout')); }, timeoutMs);
39
+ }
40
+ #fail(error) {
41
+ this.#error ??= error;
42
+ const pending = this.#pending;
43
+ this.#pending = undefined;
44
+ pending?.reject(this.#error);
45
+ }
46
+ async #request(message) {
47
+ try {
48
+ if (this.#error)
49
+ throw this.#error;
50
+ if (this.#pending || this.#finished || this.#released)
51
+ throw new Error('protocol_worker_unavailable');
52
+ return await new Promise((resolve, reject) => {
53
+ this.#pending = { resolve, reject };
54
+ if (message.type === 'write')
55
+ this.worker.postMessage(message, [message.chunk.buffer]);
56
+ else
57
+ this.worker.postMessage(message);
58
+ });
59
+ }
60
+ catch (error) {
61
+ const failure = error instanceof Error ? error : new Error('protocol_worker_failed');
62
+ await this.abort(failure);
63
+ throw failure;
64
+ }
65
+ }
66
+ async write(chunk) {
67
+ if (chunk.byteLength > 65536)
68
+ throw new Error('protocol_chunk_resource_limit');
69
+ // Transfer ONLY a fresh owned allocation, never a shared/pooled pipe slab.
70
+ const reply = await this.#request({ type: 'write', chunk: Uint8Array.from(chunk) });
71
+ if (reply.type !== 'frames') {
72
+ await this.abort(new Error('unexpected_protocol_worker_reply'));
73
+ throw new Error('unexpected_protocol_worker_reply');
74
+ }
75
+ return reply;
76
+ }
77
+ #release() {
78
+ if (this.#released)
79
+ return;
80
+ this.#released = true;
81
+ clearTimeout(this.#timer);
82
+ this.release();
83
+ }
84
+ async finish() {
85
+ try {
86
+ const result = await this.#request({ type: 'finish' });
87
+ if (result.type !== 'finished')
88
+ throw new Error('unexpected_protocol_worker_reply');
89
+ await this.#exit;
90
+ if (this.#error)
91
+ throw this.#error;
92
+ this.#release();
93
+ }
94
+ catch (error) {
95
+ const failure = error instanceof Error ? error : new Error('protocol_worker_failed');
96
+ await this.abort(failure);
97
+ throw failure;
98
+ }
99
+ }
100
+ abort(error = new Error('protocol_decoder_closed')) {
101
+ return this.#stop ??= (async () => {
102
+ this.#fail(error);
103
+ // Rejected terminate is NOT physical exit proof.
104
+ await Promise.all([this.#exit, this.worker.terminate().catch(() => this.#exit)]);
105
+ this.#release();
106
+ })();
107
+ }
108
+ }
109
+ export class ProtocolPool {
110
+ coordinator;
111
+ #active = new Set();
112
+ #queue = [];
113
+ #closed = false;
114
+ options;
115
+ constructor(coordinator, options = { concurrency: 2, maxQueued: 64, timeoutMs: 2000, memoryMb: 128, maxDepth: 256 }) {
116
+ this.coordinator = coordinator;
117
+ if (!Object.values(options).every(value => Number.isSafeInteger(value) && value > 0) || options.timeoutMs > 2_147_483_647)
118
+ throw new Error('invalid_protocol_worker_bounds');
119
+ this.options = Object.freeze({ ...options });
120
+ }
121
+ get active() { return this.#active.size; }
122
+ get queued() { return this.#queue.length; }
123
+ acquire() {
124
+ this.coordinator?.assertOutsideTransaction();
125
+ if (this.#closed || this.#queue.length >= this.options.maxQueued)
126
+ return Promise.reject(new Error('protocol_decoder_capacity'));
127
+ return new Promise((resolve, reject) => {
128
+ const waiting = { resolve, reject, deadline: performance.now() + this.options.timeoutMs,
129
+ timer: setTimeout(() => {
130
+ this.#queue = this.#queue.filter(item => item !== waiting);
131
+ reject(new Error('protocol_decoder_queue_timeout'));
132
+ }, this.options.timeoutMs) };
133
+ this.#queue.push(waiting);
134
+ this.#pump();
135
+ });
136
+ }
137
+ #pump() {
138
+ while (!this.#closed && this.#active.size < this.options.concurrency && this.#queue.length) {
139
+ const waiting = this.#queue.shift();
140
+ clearTimeout(waiting.timer);
141
+ const remaining = waiting.deadline - performance.now();
142
+ if (remaining <= 0) {
143
+ waiting.reject(new Error('protocol_decoder_queue_timeout'));
144
+ continue;
145
+ }
146
+ let worker;
147
+ try {
148
+ const url = new URL(import.meta.url.endsWith('.ts') ? '../../dist/src/runtime/protocol-worker.js' : './protocol-worker.js', import.meta.url);
149
+ worker = new Worker(url, { workerData: { maxDepth: this.options.maxDepth }, execArgv: [],
150
+ env: { PATH: '/usr/bin:/bin', LC_ALL: 'C' },
151
+ resourceLimits: { maxOldGenerationSizeMb: this.options.memoryMb, maxYoungGenerationSizeMb: 16, stackSizeMb: 4 } });
152
+ }
153
+ catch {
154
+ waiting.reject(new Error('protocol_worker_unavailable'));
155
+ continue;
156
+ }
157
+ const lease = new ProtocolDecoderLease(worker, Math.ceil(remaining), () => { this.#active.delete(lease); this.#pump(); });
158
+ this.#active.add(lease);
159
+ waiting.resolve(lease);
160
+ }
161
+ }
162
+ async close() {
163
+ this.coordinator?.assertOutsideTransaction();
164
+ this.#closed = true;
165
+ for (const item of this.#queue.splice(0)) {
166
+ clearTimeout(item.timer);
167
+ item.reject(new Error('protocol_decoder_closed'));
168
+ }
169
+ await Promise.all([...this.#active].map(lease => lease.abort()));
170
+ }
171
+ }
172
+ const pools = new WeakMap();
173
+ let standalone;
174
+ export function protocolPool(coordinator) {
175
+ if (!coordinator)
176
+ return standalone ??= new ProtocolPool();
177
+ let pool = pools.get(coordinator);
178
+ if (!pool) {
179
+ pool = new ProtocolPool(coordinator);
180
+ pools.set(coordinator, pool);
181
+ }
182
+ return pool;
183
+ }