@prplkane/agentlink 0.3.0-beta.3 → 0.3.0-beta.5

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.
package/src/probe.mjs CHANGED
@@ -1,38 +1,51 @@
1
1
  import { version } from './version.mjs';
2
2
  import { spawn } from 'node:child_process';
3
3
  import { AcpFrames } from './wire.mjs';
4
- import { stopProcess } from './process.mjs';
4
+ import { finishCommand } from './child-process.mjs';
5
5
  import { error } from './profiles.mjs';
6
6
  import { describeOptions, sessionSelections } from './session-options.mjs';
7
+ import { codexKey, historyKey, historySupport, SessionHistory } from './session-history.mjs';
7
8
 
8
- // Discovery stops after initialize. Explicit option inspection continues into
9
- // one disposable session and never sends a prompt.
10
- export async function probeAcp(launch, { cwd, env = process.env, defaults, timeoutMs = 3000, signal } = {}) {
9
+ const maxMessageBytes = 1024 * 1024;
10
+
11
+ // Discovery stops after initialize. Inspection reads options directly when the
12
+ // peer supports it. Checking a different model or effort needs a disposable session.
13
+ export async function probeAcp(launch, { cwd, env = process.env, defaults, historyV1 = false, timeoutMs = 3000, signal } = {}) {
11
14
  signal?.throwIfAborted();
12
15
  const child = spawn(launch.command, [...launch.prefixArgs, ...launch.acpArgs], {
13
16
  cwd, env: { ...env, ...launch.env }, shell: false, windowsHide: true,
14
17
  detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe']
15
18
  });
16
- let timer, abort;
19
+ let timer, abort, history, finishing = false;
20
+ const send = frame => {
21
+ if (child.stdin.destroyed || child.stdin.writableEnded) return false;
22
+ child.stdin.write(frame);
23
+ return true;
24
+ };
17
25
  try {
18
26
  return await new Promise((resolve, reject) => {
19
27
  let pending, sessionId, selections, protocolVersion, sequence = 0;
20
28
  const request = (method, params) => {
21
29
  pending = method;
22
- child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: ++sequence, method, params }) + '\n');
30
+ const message = { jsonrpc: '2.0', id: ++sequence, method, params };
31
+ const source = JSON.stringify(message);
32
+ send((method === 'session/new' ? history.prepare(message, source).toString() : source) + '\n');
23
33
  };
24
34
  timer = setTimeout(() => reject(defaults ? error('OPTIONS_TIMEOUT', 'ACP option inspection timed out.') :
25
35
  error('INITIALIZE_TIMEOUT', 'ACP initialization timed out.')), timeoutMs);
26
36
  abort = () => reject(error('CANCELLED', 'ACP probe cancelled.'));
27
37
  signal?.addEventListener('abort', abort, { once: true });
28
- const frames = new AcpFrames({ maxMessageBytes: 1024 * 1024, onMessage(message) {
38
+ const frames = new AcpFrames({ maxMessageBytes, onMessage(message, source) {
29
39
  if (message.method) {
30
40
  if (defaults && Object.hasOwn(message, 'id')) child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: message.id,
31
41
  error: { code: -32601, message: 'Client operations are unavailable during option inspection.' } }) + '\n');
32
42
  return;
33
43
  }
34
- if (message.id !== sequence) return;
44
+ const annotated = history?.agentMessage(message, source);
45
+ if (finishing || annotated === null || message.id !== sequence) return;
46
+ if (annotated) message = JSON.parse(annotated.toString());
35
47
  if (message.error) {
48
+ if (annotated) return reject(error(message.error.data.code, message.error.message));
36
49
  reject(Object.assign(error(pending === 'initialize' ? 'INITIALIZE_REJECTED' : 'OPTIONS_REJECTED',
37
50
  message.error.message || 'Agent rejected ' + pending + '.'), {
38
51
  remoteCode: message.error.code
@@ -41,14 +54,19 @@ export async function probeAcp(launch, { cwd, env = process.env, defaults, timeo
41
54
  }
42
55
  const value = message.result;
43
56
  if (pending !== 'initialize') {
57
+ if (pending === 'session/options') return resolve(describeOptions(value?.configOptions));
44
58
  if (pending === 'session/new') {
45
59
  sessionId = value?.sessionId;
46
60
  if (typeof sessionId !== 'string' || !sessionId) throw error('PROTOCOL_ERROR', 'Agent did not return a session ID.');
47
61
  selections = sessionSelections(value.configOptions, defaults, protocolVersion);
48
62
  }
49
- const next = selections.next(value?.configOptions);
50
- if (next.done) resolve(describeOptions(next.value));
51
- else request('session/set_config_option', { sessionId, ...next.value });
63
+ // Keep consuming the pipe after a rejected choice so an owned archive
64
+ // can still receive its acknowledgement during teardown.
65
+ try {
66
+ const next = selections.next(value?.configOptions);
67
+ if (next.done) resolve(describeOptions(next.value));
68
+ else request('session/set_config_option', { sessionId, ...next.value });
69
+ } catch (cause) { reject(cause); }
52
70
  return;
53
71
  }
54
72
  const capabilities = value?.protocolVersion === 2 ? value.capabilities : value?.agentCapabilities;
@@ -64,10 +82,15 @@ export async function probeAcp(launch, { cwd, env = process.env, defaults, timeo
64
82
  }
65
83
  if (defaults) {
66
84
  protocolVersion = value.protocolVersion;
67
- return request('session/new', { cwd, mcpServers: [] });
85
+ const sessionCaps = protocolVersion === 2 ? capabilities.session : capabilities.sessionCapabilities;
86
+ if (sessionCaps?.options && !Object.keys(defaults).length) return request('session/options', { cwd });
87
+ history = new SessionHistory(value, send, () => {}, maxMessageBytes,
88
+ { warn: detail => process.emitWarning(detail, { code: 'SESSION_HISTORY_UNCONFIRMED' }) });
89
+ return request('session/new', { cwd, mcpServers: [], _meta: { [historyKey]: { mode: 'prefer-ephemeral' } } });
68
90
  }
69
91
  resolve({ status: 'initialize-passed', checkedAt: new Date().toISOString(),
70
92
  protocolVersion: value.protocolVersion, agentInfo, capabilities,
93
+ sessionHistory: { acpV1Strategy: value.protocolVersion === 1 ? historySupport(value).strategy : 'unknown' },
71
94
  authMethods: Array.isArray(value.authMethods) ? value.authMethods : [] });
72
95
  } });
73
96
  frames.resume();
@@ -78,7 +101,18 @@ export async function probeAcp(launch, { cwd, env = process.env, defaults, timeo
78
101
  child.stdin.on('error', cause => { if (cause.code !== 'EPIPE') reject(cause); });
79
102
  child.once('error', () => reject(error('SPAWN_FAILED', 'Could not start the configured ACP executable.')));
80
103
  child.once('exit', code => reject(error('PROCESS_EXIT', 'Agent exited during the ACP probe (' + code + ').')));
81
- request('initialize', { protocolVersion: 2, capabilities: {}, info: { name: 'agentlink-discovery', version } });
104
+ const info = { name: 'agentlink-discovery', version };
105
+ const capabilities = defaults || historyV1 ? { _meta: { [codexKey]: { version: 1 } } } : {};
106
+ request('initialize', historyV1 || (defaults && launch.protocolVersion === 1)
107
+ ? { protocolVersion: 1, clientCapabilities: capabilities, clientInfo: info }
108
+ : { protocolVersion: 2, capabilities, info });
82
109
  });
83
- } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); await stopProcess(child); }
110
+ } finally {
111
+ finishing = true;
112
+ clearTimeout(timer);
113
+ signal?.removeEventListener('abort', abort);
114
+ await history?.disconnect();
115
+ history?.dispose();
116
+ await finishCommand(child);
117
+ }
84
118
  }
package/src/process.mjs CHANGED
@@ -4,7 +4,7 @@ import { constants } from 'node:fs';
4
4
  import { basename, delimiter, dirname, extname, isAbsolute, join, resolve } from 'node:path';
5
5
  import { stripVTControlCharacters } from 'node:util';
6
6
  import { error, strings } from './profiles.mjs';
7
- import { stopProcess } from './child-process.mjs';
7
+ import { finishCommand } from './child-process.mjs';
8
8
  export { stopProcess } from './child-process.mjs';
9
9
 
10
10
  export async function resolveCommand(command, prefixArgs = [], env = process.env) {
@@ -79,7 +79,7 @@ export async function readHelp({ command, args, cwd, env = process.env, timeoutM
79
79
  child.stdin.end();
80
80
  });
81
81
  return { code, text: stripVTControlCharacters(Buffer.concat(buffers).toString('utf8')) };
82
- } finally { signal?.removeEventListener('abort', abort); await stopProcess(child); }
82
+ } finally { signal?.removeEventListener('abort', abort); await finishCommand(child); }
83
83
  }
84
84
 
85
85
  export async function runCommand(command, args, { cwd, env = process.env, timeoutMs = 180000, signal } = {}) {
@@ -107,6 +107,6 @@ export async function runCommand(command, args, { cwd, env = process.env, timeou
107
107
  });
108
108
  } finally {
109
109
  clearTimeout(timer); signal?.removeEventListener('abort', abort);
110
- await stopProcess(child);
110
+ await finishCommand(child);
111
111
  }
112
112
  }
@@ -1,4 +1,4 @@
1
- import { member, whitespace } from './json-spans.mjs';
1
+ import { member, requestKey, whitespace } from './json-spans.mjs';
2
2
  import { error } from './profiles.mjs';
3
3
  import { sessionSelections } from './session-options.mjs';
4
4
 
@@ -6,11 +6,6 @@ function field(source, name) {
6
6
  return member(source, whitespace(source, 0), name);
7
7
  }
8
8
 
9
- function requestKey(id, source) {
10
- if (typeof id === 'number' && !Number.isSafeInteger(id)) return 'number:' + source.slice(...field(source, 'id'));
11
- return JSON.stringify(id);
12
- }
13
-
14
9
  function optionsSpan(source) {
15
10
  return member(source, field(source, 'result')[0], 'configOptions');
16
11
  }
@@ -18,7 +13,8 @@ function optionsSpan(source) {
18
13
  // An upstream session/new is complete before we reuse its request ID for a
19
14
  // setter. The downstream request stays outstanding until all setters finish.
20
15
  export class SessionDefaults {
21
- constructor(send, limit) {
16
+ constructor(send, limit, onFailure) {
17
+ this.onFailure = onFailure;
22
18
  this.send = send;
23
19
  this.limit = limit;
24
20
  this.requests = new Map();
@@ -64,6 +60,7 @@ export class SessionDefaults {
64
60
  if (!state) return;
65
61
  const first = !state.selections;
66
62
  if (message.error) {
63
+ if (state.sessionId) this.onFailure?.(state.sessionId);
67
64
  this.finish(key, state);
68
65
  return; // The upstream error already carries the original caller's ID.
69
66
  }
@@ -80,6 +77,7 @@ export class SessionDefaults {
80
77
  let next;
81
78
  try { next = state.selections.next(message.result?.configOptions); }
82
79
  catch (cause) {
80
+ this.onFailure?.(state.sessionId);
83
81
  this.finish(key, state);
84
82
  return Buffer.from('{"jsonrpc":"2.0","id":' + state.id + ',"error":' +
85
83
  JSON.stringify({ code: -32602, message: cause.message, data: { code: cause.code } }) + '}');
@@ -0,0 +1,279 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { member, requestKey, setField, whitespace } from './json-spans.mjs';
3
+ import { error } from './profiles.mjs';
4
+
5
+ export const historyKey = 'agentlink.dev/session-history';
6
+ export const codexKey = 'codex.dev/session-history';
7
+ export const codexAgentName = '@agentclientprotocol/codex-acp';
8
+ const claude = '@agentclientprotocol/claude-agent-acp';
9
+ // Unadvertised vendor semantics were checked against these published packages.
10
+ const claudeSdkOptions = new Set(['0.109.0', '0.109.1', '0.110.0', '0.110.1', '0.111.0', '0.112.0']);
11
+ const codexSoftDelete = new Set(['2.7.0', '2.8.0', '2.9.0', '2.10.0', '2.11.0', '2.12.0']);
12
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
13
+ const versionOne = value => object(value) && value.version === 1;
14
+ const maxSessions = 256;
15
+ const metadataTimeoutMs = 1000;
16
+
17
+ export function clientWantsHistory(params) {
18
+ return params?.protocolVersion === 1 && versionOne(params.clientCapabilities?._meta?.[historyKey]);
19
+ }
20
+
21
+ function rawId(source) {
22
+ return source.slice(...member(source, whitespace(source, 0), 'id'));
23
+ }
24
+
25
+ function refuse(source, code, message) {
26
+ const detail = { code: -32602, message, data: { code } };
27
+ return Buffer.from('{"jsonrpc":"2.0","id":' + rawId(source) + ',"error":' + JSON.stringify(detail) + '}');
28
+ }
29
+
30
+ function responseStatus(source, status) {
31
+ try { return Buffer.from(setField(source, ['result', '_meta', historyKey], { status })); }
32
+ catch { return refuse(source, 'SESSION_HISTORY_UNCONFIRMED', 'The provider returned invalid session metadata.'); }
33
+ }
34
+
35
+ export function historySupport(result, requestedAirIndex = false) {
36
+ const v2 = result.protocolVersion === 2; // Internal option inspection also negotiates v2.
37
+ const info = v2 ? result.info : result.agentInfo;
38
+ const caps = (v2 ? result.capabilities : result.agentCapabilities) ?? {};
39
+ const sessions = (v2 ? caps.session : caps.sessionCapabilities) || {};
40
+ const isCodex = info?.name === codexAgentName;
41
+ const nativeCodex = isCodex && versionOne(caps._meta?.[codexKey]) && caps._meta[codexKey].ephemeral === true;
42
+ const nativeClaude = info?.name === claude && claudeSdkOptions.has(info.version);
43
+ const air = result._meta?.jetbrains?.air?.capabilities;
44
+ const airIndex = Array.isArray(air) && air.includes('sessionIndex');
45
+ // In AIR session-index mode, session/delete permanently erases a thread.
46
+ // The ordinary Codex ACP session/delete archives. Use the explicit archive
47
+ // extension when AIR actually advertises it.
48
+ let archiveMethod;
49
+ if (isCodex && airIndex && air.includes('sessionArchive')) archiveMethod = '_session/archive';
50
+ else if (isCodex && !airIndex && !requestedAirIndex && codexSoftDelete.has(info.version) && object(sessions.delete)) {
51
+ archiveMethod = 'session/delete';
52
+ }
53
+ const canClose = v2 || object(sessions.close);
54
+ const strategy = nativeCodex || nativeClaude ? 'ephemeral'
55
+ : archiveMethod && canClose ? 'archive-on-close' : 'provider-managed';
56
+ return { nativeCodex, nativeClaude, archiveMethod, canClose, canTitle: object(sessions.title), strategy };
57
+ }
58
+
59
+ // The caller opted in at initialize. State belongs to this one upstream connection.
60
+ // Never discover chats by enumerating history or use an ID supplied by a different caller.
61
+ export class SessionHistory {
62
+ constructor(result, send, publish, limit, { requestedAirIndex = false, warn = () => {} } = {}) {
63
+ this.warn = warn;
64
+ this.finalReplies = new Set();
65
+ this.limit = limit;
66
+ this.heldBytes = 0;
67
+ this.send = send;
68
+ this.publish = publish;
69
+ this.opening = new Set();
70
+ this.closing = new Map();
71
+ this.owned = new Map();
72
+ this.metadata = new Map();
73
+ this.prefix = 'agentlink-history-' + randomUUID() + '-';
74
+ this.sequence = 0;
75
+ Object.assign(this, historySupport(result, requestedAirIndex));
76
+ }
77
+
78
+ capability(source) {
79
+ return Buffer.from(setField(source, ['result', 'agentCapabilities', '_meta', historyKey], { version: 1, strategy: this.strategy }));
80
+ }
81
+
82
+ prepare(message, source) {
83
+ const key = requestKey(message.id, source);
84
+ const params = message.params;
85
+ if (Object.hasOwn(params, 'sessionId')) throw error('INVALID_SESSION_HISTORY', 'A temporary session must start fresh.');
86
+ const mode = params?._meta?.[historyKey]?.mode;
87
+ if (!['prefer-ephemeral', 'require-ephemeral'].includes(mode)) throw error('INVALID_SESSION_HISTORY', 'Unknown per-session history mode.');
88
+ if (mode === 'require-ephemeral' && this.strategy !== 'ephemeral') {
89
+ throw error('SESSION_HISTORY_UNSUPPORTED', 'This provider cannot confirm a session without local chat persistence.');
90
+ }
91
+ if (this.opening.size + this.owned.size >= maxSessions) throw error('MESSAGE_LIMIT', 'Too many managed sessions on this connection.');
92
+ let outgoing = setField(source, ['params', '_meta', historyKey], undefined);
93
+ if (this.nativeClaude) {
94
+ const options = params._meta?.claudeCode?.options;
95
+ const extra = options?.extraArgs ?? {};
96
+ if (options?.resume || options?.continue || options?.forkSession || options?.sessionId || options?.resumeSessionAt ||
97
+ ['resume', 'continue', 'session-id', 'fork-session', 'resume-session-at'].some(key => Object.hasOwn(extra, key))) {
98
+ throw error('INVALID_SESSION_HISTORY', 'A temporary session must start fresh.');
99
+ }
100
+ outgoing = setField(outgoing, ['params', '_meta', 'claudeCode', 'options', 'persistSession'], false);
101
+ } else if (this.nativeCodex) {
102
+ outgoing = setField(outgoing, ['params', '_meta', codexKey, 'ephemeral'], true);
103
+ }
104
+ this.opening.add(key);
105
+ return Buffer.from(outgoing);
106
+ }
107
+
108
+ forgetRequest(message, source) { this.opening.delete(requestKey(message.id, source)); }
109
+
110
+ // Use a per-connection private namespace for internal metadata requests. Replies
111
+ // arriving after their deadline are consumed too. No user prompt is replayed.
112
+ reserved(id) { return typeof id === 'string' && id.startsWith(this.prefix); }
113
+
114
+ metadataCall(method, sessionId, fields = {}) {
115
+ if (this.disposed) return Promise.resolve(false);
116
+ const id = this.prefix + ++this.sequence;
117
+ return new Promise(resolve => {
118
+ const finish = (ok, reason) => {
119
+ if (!this.metadata.delete(id)) return;
120
+ clearTimeout(timer);
121
+ if (!ok && !this.disposed) this.warn(method + ' was unconfirmed (' + reason + ').');
122
+ resolve(ok);
123
+ };
124
+ const timer = setTimeout(() => finish(false, 'timeout'), metadataTimeoutMs);
125
+ this.metadata.set(id, finish);
126
+ const frame = JSON.stringify({ jsonrpc: '2.0', id, method, params: { sessionId, ...fields } });
127
+ if (Buffer.byteLength(frame) > this.limit || !this.send(frame + '\n')) finish(false, 'unavailable transport');
128
+ });
129
+ }
130
+
131
+ async beforeClient(message, source) {
132
+ if (typeof message.method !== 'string') return;
133
+ const state = this.owned.get(message.params?.sessionId);
134
+ if (!state) return;
135
+ if (message.method === 'session/prompt' && state.status === 'archive-on-close' && this.canTitle) {
136
+ state.naming ??= this.metadataCall('session/set_title', state.sessionId, { title: 'AgentLink session' });
137
+ await state.naming;
138
+ }
139
+ const directRemoval = message.method === 'session/delete' || message.method === this.archiveMethod;
140
+ if ((message.method === 'session/close' || directRemoval) && Object.hasOwn(message, 'id')) {
141
+ if (this.closing.size >= maxSessions) throw error('MESSAGE_LIMIT', 'Too many pending session closes.');
142
+ state.pendingCloses++;
143
+ this.closing.set(requestKey(message.id, source), { state, directRemoval });
144
+ }
145
+ }
146
+
147
+ archive(state) {
148
+ if (!state.archive) {
149
+ state.attempts = (state.attempts ?? 0) + 1;
150
+ state.archive = this.metadataCall(this.archiveMethod, state.sessionId).then(ok => {
151
+ if (ok || this.ending || this.disposed || state.attempts >= 2) this.owned.delete(state.sessionId);
152
+ else state.archive = undefined; // Give a failed explicit cleanup one bounded retry at EOF.
153
+ this.checkDrain();
154
+ return ok;
155
+ });
156
+ }
157
+ return state.archive;
158
+ }
159
+
160
+ failedSetup(sessionId) {
161
+ const state = this.owned.get(sessionId);
162
+ if (!state) return;
163
+ if (state.status === 'archive-on-close') void this.archive(state);
164
+ else {
165
+ if (this.canClose) void this.metadataCall('session/close', sessionId);
166
+ this.owned.delete(sessionId);
167
+ }
168
+ }
169
+
170
+ agentMessage(message, source) {
171
+ if (message.method || !Object.hasOwn(message, 'id')) return;
172
+ if (this.reserved(message.id)) {
173
+ this.metadata.get(message.id)?.(!message.error && object(message.result), message.error?.code ?? 'invalid response');
174
+ return null;
175
+ }
176
+ const key = requestKey(message.id, source);
177
+ if (this.opening.delete(key)) {
178
+ const sessionId = message.result?.sessionId;
179
+ if (message.error) { this.checkDrain(); return; }
180
+ if (typeof sessionId !== 'string' || !sessionId || this.owned.has(sessionId)) {
181
+ this.checkDrain();
182
+ return refuse(source, 'SESSION_HISTORY_UNCONFIRMED', 'The provider did not return a distinct session ID.');
183
+ }
184
+ const state = { sessionId, status: this.strategy, pendingCloses: 0 };
185
+ if (this.canClose || state.status === 'archive-on-close') this.owned.set(sessionId, state);
186
+ if (message.result._meta != null && !object(message.result._meta)) {
187
+ this.failedSetup(sessionId);
188
+ this.checkDrain();
189
+ return refuse(source, 'SESSION_HISTORY_UNCONFIRMED', 'The provider returned invalid session metadata.');
190
+ }
191
+ if (this.nativeCodex && message.result._meta?.[codexKey]?.ephemeral !== true) {
192
+ if (this.archiveMethod) { state.status = 'archive-on-close'; void this.archive(state); }
193
+ else this.failedSetup(sessionId);
194
+ this.checkDrain();
195
+ return refuse(source, 'SESSION_HISTORY_UNCONFIRMED', 'The provider did not confirm an ephemeral thread.');
196
+ }
197
+ if (this.ending && state.status === 'archive-on-close') void this.archive(state);
198
+ this.checkDrain();
199
+ return responseStatus(source, state.status);
200
+ }
201
+ const pending = this.closing.get(key);
202
+ if (!pending) return;
203
+ this.closing.delete(key);
204
+ const { state, directRemoval } = pending;
205
+ state.pendingCloses--;
206
+ const owned = this.owned.get(state.sessionId) === state;
207
+ const canArchive = owned && state.status === 'archive-on-close' && !state.pendingCloses;
208
+ if (message.error) {
209
+ // A live client can continue after a refused close. At EOF the gateway
210
+ // still owns cleanup once the client's outstanding operations have settled.
211
+ if (this.ending && canArchive) void this.archive(state);
212
+ this.checkDrain();
213
+ return;
214
+ }
215
+ if (directRemoval) {
216
+ if (owned) this.owned.delete(state.sessionId);
217
+ this.checkDrain();
218
+ return; // The client performed its own cleanup. Preserve the original reply.
219
+ }
220
+ if (state.status === 'archive-on-close') {
221
+ if (!canArchive) {
222
+ this.checkDrain();
223
+ return responseStatus(source, 'unconfirmed');
224
+ }
225
+ const archived = this.archive(state);
226
+ const bytes = Buffer.byteLength(source) + 1;
227
+ if (this.finalReplies.size >= maxSessions || this.heldBytes + bytes > 4 * this.limit) return responseStatus(source, 'unconfirmed');
228
+ this.heldBytes += bytes;
229
+ const reply = archived.then(ok => {
230
+ this.heldBytes -= bytes;
231
+ this.finalReplies.delete(reply);
232
+ this.publish(responseStatus(source, ok ? 'archived' : 'unconfirmed'));
233
+ });
234
+ this.finalReplies.add(reply);
235
+ return null;
236
+ }
237
+ if (owned) this.owned.delete(state.sessionId);
238
+ this.checkDrain();
239
+ return responseStatus(source, state.status);
240
+ }
241
+
242
+ cleanupPending() {
243
+ return this.opening.size > 0 || this.closing.size > 0 || [...this.owned.values()].some(state => state.status === 'archive-on-close');
244
+ }
245
+
246
+ checkDrain() { if (this.ending && !this.cleanupPending()) this.drained?.(); }
247
+
248
+ // EOF can race the session/new reply. Keep stdin available briefly to archive
249
+ // just-created IDs, including when the application disappears before closing.
250
+ disconnect() { return this.teardown ??= this.drain(); }
251
+
252
+ async drain() {
253
+ if (this.disposed) return;
254
+ this.ending = true;
255
+ for (const state of this.owned.values()) {
256
+ if (state.status === 'archive-on-close' && !state.pendingCloses) void this.archive(state);
257
+ }
258
+ if (!this.cleanupPending()) return;
259
+ await new Promise(resolve => {
260
+ const timer = setTimeout(() => {
261
+ if (this.closing.size) this.warn('Client close or removal was unconfirmed at disconnect.');
262
+ resolve();
263
+ }, metadataTimeoutMs);
264
+ this.drained = () => { clearTimeout(timer); resolve(); };
265
+ });
266
+ this.drained = undefined;
267
+ }
268
+
269
+ async endOutput() {
270
+ this.dispose();
271
+ await Promise.all(this.finalReplies);
272
+ }
273
+
274
+ dispose() {
275
+ this.disposed = true;
276
+ for (const finish of this.metadata.values()) finish(false, 'connection closed');
277
+ this.drained?.();
278
+ }
279
+ }
package/src/version.mjs CHANGED
@@ -1 +1 @@
1
- export const version = '0.3.0-beta.3';
1
+ export const version = '0.3.0-beta.5';
package/src/wire.mjs CHANGED
@@ -4,7 +4,7 @@ import { error } from './profiles.mjs';
4
4
  // Validate framing, not the evolving ACP method schema. Preserve the original
5
5
  // bytes, IDs, extensions and field order. Stream backpressure bounds queued data.
6
6
  export class AcpFrames extends Transform {
7
- constructor({ maxMessageBytes = 16 * 1024 * 1024, onMessage, mapMessage } = {}) {
7
+ constructor({ maxMessageBytes = 16 * 1024 * 1024, onMessage, mapMessage, onEnd } = {}) {
8
8
  super();
9
9
  if (!Number.isSafeInteger(maxMessageBytes) || maxMessageBytes < 1) throw new TypeError('Invalid ACP frame limit.');
10
10
  this.limit = maxMessageBytes;
@@ -12,6 +12,7 @@ export class AcpFrames extends Transform {
12
12
  this.bytes = 0;
13
13
  this.onMessage = onMessage;
14
14
  this.mapMessage = mapMessage;
15
+ this.onEnd = onEnd;
15
16
  }
16
17
  async _transform(chunk, encoding, done) {
17
18
  try {
@@ -47,6 +48,9 @@ export class AcpFrames extends Transform {
47
48
  if (part.length) this.parts.push(part);
48
49
  }
49
50
  _flush(done) {
50
- done(this.bytes ? error('PROTOCOL_ERROR', 'ACP stream ended inside a message.') : undefined);
51
+ if (this.bytes) return done(error('PROTOCOL_ERROR', 'ACP stream ended inside a message.'));
52
+ const final = this.onEnd?.();
53
+ if (final?.then) final.then(() => done(), done);
54
+ else done();
51
55
  }
52
56
  }