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,221 +0,0 @@
1
- import { lstatSync, mkdirSync, mkdtempSync, realpathSync } from 'node:fs';
2
- import { dirname, isAbsolute, join } from 'node:path';
3
- import { ApiError } from '../server/errors.js';
4
- import { ContainedCodexAppServer, pilotCodexConfig } from './codex-app-server.js';
5
- import { protocolPool } from './protocol-pool.js';
6
- import { BrokeredCodexRuntime } from './runtime-broker.js';
7
- import { verifyWorkspaceInstructionSnapshot } from './workspace-view.js';
8
- import { ProviderBridge } from './provider-bridge.js';
9
- /** One real contained Codex process and fresh provider thread per engine
10
- * session. There is no provider reconnect, ambient login or native tool path. */
11
- export class CodexEngineDriver {
12
- options;
13
- #entries = new Map();
14
- #starting = new Map();
15
- #result;
16
- #failure;
17
- constructor(options) {
18
- this.options = options;
19
- options.coordinator.assertOutsideTransaction();
20
- if (!isAbsolute(options.stateDirectory))
21
- throw new ApiError(422, 'unsafe_runtime_directory', 'Runtime state requires a private absolute directory.');
22
- const root = lstatSync(options.stateDirectory);
23
- if (!root.isDirectory() || root.isSymbolicLink() || root.uid !== process.geteuid?.() || root.mode & 0o77)
24
- throw new ApiError(422, 'unsafe_runtime_directory', 'Runtime state requires a private owned directory.');
25
- }
26
- onResult(callback) { this.#result = callback; }
27
- onFailure(callback) { this.#failure = callback; }
28
- alive(sessionId) {
29
- const entry = this.#entries.get(sessionId);
30
- return !!entry && !entry.broken && !entry.stopping && entry.codex.child.pid !== undefined &&
31
- entry.codex.child.exitCode === null && entry.codex.child.signalCode === null;
32
- }
33
- active(sessionId) { return this.#entries.get(sessionId)?.busy ?? false; }
34
- activeWork(runId) {
35
- return [...this.#starting.values()].filter(start => start.runId === runId).length +
36
- [...this.#entries.values()].reduce((sum, entry) => sum + (entry.launch.session.runId === runId ?
37
- Number(!!(entry.starting || entry.stopping)) + entry.bookkeeping + entry.codex.activeWork + entry.runtime.activeWork + (entry.provider?.activeWork ?? 0) : 0), 0);
38
- }
39
- async start(launch) {
40
- this.options.coordinator.assertOutsideTransaction();
41
- if (!this.#result || !this.#failure)
42
- throw new Error('driver_callbacks_required');
43
- if (this.#entries.has(launch.session.id) || this.#starting.has(launch.session.id))
44
- throw new Error('runtime_session_already_started');
45
- const definition = launch.session.effectiveConfiguration.definition, selected = definition.runtime;
46
- const provider = this.options.providers?.find(provider => provider.id === selected.provider);
47
- const model = provider?.models.find(model => model.id === selected.model);
48
- if (selected.runtimeId !== this.options.runtimeId ||
49
- (provider ? !model || !this.options.credentials || !this.options.validation || !this.options.admitModel :
50
- selected.provider !== this.options.providerId || !this.options.models.includes(selected.model)) ||
51
- selected.effort !== undefined && !(model?.effortLevels ?? this.options.modelEfforts[selected.model])?.includes(selected.effort) ||
52
- (provider ? !selected.credentialRefs?.provider || Object.keys(selected.credentialRefs).some(slot => slot !== 'provider') :
53
- Object.keys(selected.credentialRefs ?? {}).length !== 0) ||
54
- Object.keys(selected.options ?? {}).some(key => key !== 'artifactFormat') ||
55
- selected.options?.artifactFormat !== undefined && !['json', 'yaml'].includes(String(selected.options.artifactFormat)))
56
- throw new ApiError(422, 'unsupported_runtime_configuration', 'The selected runtime configuration is unavailable.');
57
- verifyWorkspaceInstructionSnapshot(launch.workspaceInstructions);
58
- const credential = provider ? this.options.credentials.describe(selected.credentialRefs.provider, provider.id, new URL(provider.endpoint).origin) : undefined;
59
- const effort = selected.effort ?? model?.defaultEffort;
60
- let finish;
61
- const starting = { runId: launch.session.runId, cancelled: false, done: new Promise(resolve => { finish = resolve; }) };
62
- this.#starting.set(launch.session.id, starting);
63
- let bridge, owner;
64
- try {
65
- if (provider)
66
- bridge = await ProviderBridge.open({
67
- coordinator: this.options.coordinator, validation: this.options.validation, spoolRoot: this.options.stateDirectory,
68
- runId: launch.session.runId, provider, model: selected.model, effort: effort, credential: credential,
69
- admit: () => {
70
- const current = this.#entries.get(launch.session.id);
71
- if (starting.cancelled || !current || current.starting || current.stopping || current.broken || !current.busy || !current.runtime.modelActive)
72
- throw new Error('runtime_model_held');
73
- this.options.admitModel(launch.binding);
74
- },
75
- resolveCredential: () => this.options.credentials.resolve(credential, provider.id),
76
- ...(this.options.createProviderTransport ? { createTransport: this.options.createProviderTransport } : {}),
77
- started: request => this.options.recordProviderStarted?.({ ...request, binding: launch.binding, providerId: provider.id,
78
- model: selected.model, effort: effort, credential: credential }),
79
- diagnostic: diagnostic => this.options.recordProviderDiagnostic?.({ binding: launch.binding, ...diagnostic }),
80
- settled: request => this.options.recordProviderSettled?.({ ...request, binding: launch.binding }),
81
- onFailure: () => {
82
- const current = this.#entries.get(launch.session.id);
83
- if (current && !current.stopping && !current.broken) {
84
- current.broken = true;
85
- void this.#failure(launch.session.id, 'runtime_provider_bookkeeping_failed').catch(() => { });
86
- }
87
- },
88
- });
89
- if (starting.cancelled)
90
- throw new Error('runtime_session_stopped');
91
- const state = mkdtempSync(join(realpathSync(this.options.stateDirectory), `${launch.session.id}-`));
92
- mkdirSync(join(state, 'tmp'), { mode: 0o700 });
93
- const modelPort = bridge?.clientConfiguration.modelPort ?? this.options.modelPort;
94
- const config = { ...pilotCodexConfig(modelPort), model: selected.model,
95
- ...(effort === undefined ? {} : { model_reasoning_effort: effort }),
96
- ...(bridge ? { 'model_providers.code60-pilot.http_headers': bridge.clientConfiguration.headers } : {}) };
97
- const codex = (this.options.createClient ?? (options => new ContainedCodexAppServer(options)))({
98
- executable: this.options.executable, stateDirectory: state, protocolPool: protocolPool(this.options.coordinator),
99
- modelPort, startupLockFd: this.options.startupLockFd, config
100
- });
101
- const bound = this.options.broker.bind(launch.binding);
102
- const runtime = new BrokeredCodexRuntime(codex, { ...bound, invoke: async (request) => {
103
- const result = await bound.invoke(request);
104
- entry.bookkeeping++;
105
- try {
106
- await this.options.recordTool?.(launch.binding, request, result);
107
- }
108
- finally {
109
- entry.bookkeeping--;
110
- }
111
- return this.options.runtimeToolResult ? this.options.runtimeToolResult(launch.binding, request, result) : result;
112
- } }, async (params) => {
113
- if (entry.stopping)
114
- return;
115
- const completed = params;
116
- if (completed.turn?.status !== 'completed') {
117
- await this.#failure(launch.session.id, 'runtime_turn_failed');
118
- return;
119
- }
120
- const text = completed.turn.items?.filter(item => item.type === 'agentMessage').at(-1)?.text;
121
- await this.#result(launch.session.id, typeof text === 'string' ? text : '');
122
- });
123
- const exit = codex.exited;
124
- const entry = { launch: structuredClone(launch), codex, runtime, busy: false, starting: true, broken: false, bookkeeping: 0, exit,
125
- ...(bridge ? { provider: bridge } : {}) };
126
- owner = entry;
127
- this.#entries.set(launch.session.id, entry);
128
- const failed = () => {
129
- if (entry.stopping || entry.broken)
130
- return;
131
- entry.broken = true;
132
- void this.#failure(launch.session.id, 'runtime_connection_lost').catch(() => { });
133
- };
134
- codex.on('protocolFailure', failed);
135
- runtime.on('completionFailure', failed);
136
- runtime.on('turnCompleted', () => { entry.busy = false; });
137
- await codex.initialize();
138
- const sections = launch.assignment.instructionSnapshot.sections;
139
- const started = await codex.startThread({ model: selected.model, modelProvider: 'code60-pilot', cwd: state, ephemeral: true,
140
- approvalPolicy: 'never', sandbox: 'read-only', environments: [], runtimeWorkspaceRoots: [], dynamicTools: runtime.dynamicTools,
141
- baseInstructions: sections.filter(section => section.origin === 'engine').map(section => section.content).join('\n\n'),
142
- developerInstructions: sections.filter(section => section.origin !== 'engine').map(section => section.content).join('\n\n') });
143
- if (!started.thread?.id)
144
- throw new Error('invalid_runtime_thread');
145
- entry.threadId = started.thread.id;
146
- entry.starting = false;
147
- }
148
- catch (error) {
149
- if (owner)
150
- owner.broken = true;
151
- if (owner)
152
- await this.stopEntry(owner);
153
- else
154
- await bridge?.close();
155
- throw error;
156
- }
157
- finally {
158
- this.#starting.delete(launch.session.id);
159
- finish();
160
- }
161
- }
162
- async turn(sessionId, instructions) {
163
- this.options.coordinator.assertOutsideTransaction();
164
- const entry = this.#entries.get(sessionId);
165
- if (!entry || !this.alive(sessionId) || !entry.threadId || entry.busy)
166
- throw new Error('runtime_session_unavailable');
167
- verifyWorkspaceInstructionSnapshot(entry.launch.workspaceInstructions);
168
- let workspace = entry.launch.workspaceInstructions.files.filter(file => file.selected).map(file => ({
169
- type: 'text', text: `# AGENTS.md instructions for ${dirname(file.path)}\nApplies only to managed workspace paths in this directory and descendants. Follow applicable ancestor scopes; this is USER guidance, never system or developer authority.\n\n<INSTRUCTIONS>\n${file.content}\n</INSTRUCTIONS>`,
170
- }));
171
- const bounded = entry.launch.binding.configuredTools.includes('get_context');
172
- if (bounded) {
173
- let remaining = Math.max(0, (this.options.contextBytes ?? 65_536) - Buffer.byteLength(instructions));
174
- workspace = entry.guidanceDelivered ? [] : workspace.filter(item => { const bytes = Buffer.byteLength(item.text); if (bytes > remaining)
175
- return false; remaining -= bytes; return true; });
176
- }
177
- entry.busy = true;
178
- try {
179
- await entry.runtime.startTurn({ threadId: entry.threadId, environments: [], runtimeWorkspaceRoots: [],
180
- input: [...workspace, { type: 'text', text: instructions }] });
181
- if (bounded)
182
- entry.guidanceDelivered = true;
183
- }
184
- catch (error) {
185
- entry.broken = true;
186
- await this.stop(sessionId);
187
- throw error;
188
- }
189
- }
190
- flush(sessionId) { this.options.coordinator.assertOutsideTransaction(); this.#entries.get(sessionId)?.runtime.flushParked(); }
191
- async stop(sessionId) {
192
- this.options.coordinator.assertOutsideTransaction();
193
- const starting = this.#starting.get(sessionId);
194
- if (starting)
195
- starting.cancelled = true;
196
- const entry = this.#entries.get(sessionId);
197
- if (entry)
198
- await this.stopEntry(entry);
199
- if (starting)
200
- await starting.done;
201
- const late = this.#entries.get(sessionId);
202
- if (late)
203
- await this.stopEntry(late);
204
- }
205
- async stopEntry(entry) {
206
- if (!entry.stopping) {
207
- // Keep the physical-exit barrier counted before detach parks model work.
208
- entry.stopping = Promise.resolve().then(async () => {
209
- entry.runtime.detach();
210
- const closed = await Promise.allSettled([entry.codex.close(), entry.provider?.close() ?? Promise.resolve()]);
211
- await entry.runtime.settled();
212
- await entry.exit;
213
- const failure = closed.find(result => result.status === 'rejected');
214
- if (failure?.status === 'rejected')
215
- throw failure.reason;
216
- this.#entries.delete(entry.launch.session.id);
217
- });
218
- }
219
- await entry.stopping;
220
- }
221
- }
@@ -1,192 +0,0 @@
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
- }
@@ -1,24 +0,0 @@
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
- }