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

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 (98) hide show
  1. package/LICENSE +180 -0
  2. package/README.engine.md +463 -0
  3. package/README.md +376 -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 +207 -0
  7. package/dist/src/broker/native/build.js +46 -0
  8. package/dist/src/broker/native/command-helper.c +93 -0
  9. package/dist/src/broker/native/fs-helper.c +529 -0
  10. package/dist/src/broker/native/git-helper.c +205 -0
  11. package/dist/src/broker/policy.js +149 -0
  12. package/dist/src/broker/startup-lock.js +14 -0
  13. package/dist/src/broker/types.js +11 -0
  14. package/dist/src/cli/configure.js +208 -0
  15. package/dist/src/cli/daemon.js +369 -0
  16. package/dist/src/cli/helpers.js +112 -0
  17. package/dist/src/cli/main.js +189 -0
  18. package/dist/src/cli/runtime-build.js +38 -0
  19. package/dist/src/config/coding-policy.js +4 -0
  20. package/dist/src/config/deployment.js +183 -0
  21. package/dist/src/config/documents.js +29 -0
  22. package/dist/src/config/profile-validation.js +129 -0
  23. package/dist/src/config/schema-graph.js +237 -0
  24. package/dist/src/config/schema-loader.js +185 -0
  25. package/dist/src/config/validation-pool.js +105 -0
  26. package/dist/src/config/validation-protocol.js +1 -0
  27. package/dist/src/config/validation-worker.js +106 -0
  28. package/dist/src/config/workflow-language.js +9 -0
  29. package/dist/src/config/workflow-schema.json +545 -0
  30. package/dist/src/config/workflow-types.js +1 -0
  31. package/dist/src/config/workflow-validation.js +95 -0
  32. package/dist/src/engine/budgets.js +50 -0
  33. package/dist/src/engine/clocks.js +27 -0
  34. package/dist/src/engine/commands.js +477 -0
  35. package/dist/src/engine/contracts.js +11 -0
  36. package/dist/src/engine/drain-state.js +31 -0
  37. package/dist/src/engine/effective-permissions.js +120 -0
  38. package/dist/src/engine/instruction-pins.js +205 -0
  39. package/dist/src/engine/retries.js +50 -0
  40. package/dist/src/engine/state.js +1 -0
  41. package/dist/src/engine/timing.js +23 -0
  42. package/dist/src/engine/tool-observations.js +87 -0
  43. package/dist/src/engine/workflow-engine.js +1862 -0
  44. package/dist/src/main.js +28 -0
  45. package/dist/src/mcp/catalog.js +71 -0
  46. package/dist/src/mcp/main.js +26 -0
  47. package/dist/src/mcp/server.js +177 -0
  48. package/dist/src/runtime/codex-app-server.js +91 -0
  49. package/dist/src/runtime/codex-executable.js +50 -0
  50. package/dist/src/runtime/containment.js +82 -0
  51. package/dist/src/runtime/engine-driver.js +221 -0
  52. package/dist/src/runtime/json-line-writer.js +192 -0
  53. package/dist/src/runtime/pinned-instruction-sources.js +24 -0
  54. package/dist/src/runtime/protocol-client.js +264 -0
  55. package/dist/src/runtime/protocol-pool.js +183 -0
  56. package/dist/src/runtime/protocol-projection.js +393 -0
  57. package/dist/src/runtime/protocol-types.js +1 -0
  58. package/dist/src/runtime/protocol-worker.js +18 -0
  59. package/dist/src/runtime/provider-bridge.js +290 -0
  60. package/dist/src/runtime/provider-credentials.js +41 -0
  61. package/dist/src/runtime/provider-transport.js +406 -0
  62. package/dist/src/runtime/runtime-broker.js +213 -0
  63. package/dist/src/runtime/workspace-instructions.js +120 -0
  64. package/dist/src/runtime/workspace-view.js +74 -0
  65. package/dist/src/server/api-contract.json +11629 -0
  66. package/dist/src/server/api-types.js +1 -0
  67. package/dist/src/server/application.js +44 -0
  68. package/dist/src/server/auth.js +67 -0
  69. package/dist/src/server/broker-handlers.js +242 -0
  70. package/dist/src/server/coding.js +281 -0
  71. package/dist/src/server/control-plane.js +50 -0
  72. package/dist/src/server/deployment.js +249 -0
  73. package/dist/src/server/errors.js +22 -0
  74. package/dist/src/server/history-handlers.js +127 -0
  75. package/dist/src/server/http.js +124 -0
  76. package/dist/src/server/paging.js +56 -0
  77. package/dist/src/server/publication.js +119 -0
  78. package/dist/src/server/tool-event-handler.js +77 -0
  79. package/dist/src/server/workspace-handlers.js +34 -0
  80. package/dist/src/storage/coordinator.js +224 -0
  81. package/dist/src/storage/startup-lock.js +71 -0
  82. package/dist/src/storage/store.js +167 -0
  83. package/dist/src/tools/check-worker.js +81 -0
  84. package/dist/src/tools/checks.js +117 -0
  85. package/dist/src/tools/command-check.js +34 -0
  86. package/dist/src/tools/commands.js +312 -0
  87. package/dist/src/tools/developer.js +353 -0
  88. package/dist/src/tools/dns.js +248 -0
  89. package/dist/src/tools/http-contract.js +38 -0
  90. package/dist/src/tools/http.js +358 -0
  91. package/dist/src/tools/index.js +194 -0
  92. package/dist/src/tools/worker-check.js +73 -0
  93. package/dist/src/workspaces/git.js +227 -0
  94. package/dist/src/workspaces/index.js +937 -0
  95. package/dist/src/workspaces/source.js +295 -0
  96. package/examples/deployment.local.json +22 -0
  97. package/package.json +71 -4
  98. package/scripts/postinstall.mjs +26 -0
@@ -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
+ }