@prplkane/agentlink 0.3.0-beta.4 → 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/discovery.mjs CHANGED
@@ -6,6 +6,7 @@ import { probeAcp } from './probe.mjs';
6
6
  import { providers } from './providers.mjs';
7
7
  import { error, strings } from './profiles.mjs';
8
8
  import { readHelp, resolveCommand } from './process.mjs';
9
+ import { codexAgentName } from './session-history.mjs';
9
10
 
10
11
  function knownRecipe(provider, executableName) {
11
12
  if (provider !== undefined) {
@@ -52,8 +53,46 @@ export function inspectHelp(text) {
52
53
  return { candidates, subcommands: [...new Set(subcommands)].slice(0, 2) };
53
54
  }
54
55
 
55
- export async function verifyAgent(launch, { cwd, env = process.env, timeoutMs = 3000, signal } = {}) {
56
- return probeAcp(launch, { cwd, env, timeoutMs, signal });
56
+ async function codexExecEphemeral(launch, { cwd, env, timeoutMs, maxBytes, signal }) {
57
+ // The stock adapter's "cli" subcommand uses its own bundled Codex. When an
58
+ // operator selects CODEX_PATH, run that executable directly without a shell.
59
+ const key = process.platform === 'win32' ? Object.keys(env).sort().find(key => key.toUpperCase() === 'CODEX_PATH') : 'CODEX_PATH';
60
+ const override = key && env[key];
61
+ try {
62
+ const executable = override && /[/\\]/.test(override) ? resolve(cwd, override) : override;
63
+ const direct = executable ? await resolveCommand(executable, [], env) : undefined;
64
+ const args = direct ? direct.prefixArgs : [...launch.prefixArgs, ...launch.acpArgs, 'cli'];
65
+ const { code, text } = await readHelp({ command: direct?.command ?? launch.command, args: [...args, 'exec', '--help'],
66
+ cwd, env, timeoutMs, maxBytes, signal });
67
+ const options = text.split(/^Options:[ \t]*\r?$/m)[1]?.split(/^\S/m, 1)[0];
68
+ if (code !== 0 || !/^Usage:[ \t]+codex(?:\.exe)?[ \t]+exec(?:[ \t]|$)/m.test(text) || !options?.trim()) return 'unknown';
69
+ return /^[ \t]{1,8}(?:-\w,[ \t]+)?--ephemeral(?:[ \t]{2,}[^\r\n]*)?[ \t]*\r?$/m.test(options) ? 'advertised' : 'not-advertised';
70
+ } catch (cause) {
71
+ if (signal?.aborted) throw cause;
72
+ return 'unknown';
73
+ }
74
+ }
75
+
76
+ export async function verifyAgent(launch, { cwd = process.cwd(), env = process.env, timeoutMs = 3000, maxHelpBytes = 65536, signal } = {}) {
77
+ const options = { cwd, env, timeoutMs, signal };
78
+ const verification = await probeAcp(launch, options);
79
+ const codex = verification.agentInfo.name === codexAgentName;
80
+ // Apps negotiate history on v1. A v2 result or a Codex downgrade that
81
+ // never received the v1 opt-in cannot establish what that client will see.
82
+ if (verification.protocolVersion === 2 || codex) {
83
+ try {
84
+ verification.sessionHistory = (await probeAcp(launch, { ...options, historyV1: true })).sessionHistory;
85
+ } catch (cause) {
86
+ if (signal?.aborted) throw cause;
87
+ verification.sessionHistory.acpV1Strategy = 'unknown';
88
+ }
89
+ }
90
+ if (codex) {
91
+ verification.sessionHistory.codexExecEphemeral = await codexExecEphemeral(launch, {
92
+ ...options, env: { ...env, ...launch.env }, maxBytes: maxHelpBytes
93
+ });
94
+ }
95
+ return verification;
57
96
  }
58
97
 
59
98
  export async function inProbeDirectory(callback) {
@@ -101,7 +140,7 @@ export async function discoverAgent({ command, prefixArgs = [], acpArgs, provide
101
140
  if (helpArgs) candidate.discovery.helpArgs = [...helpArgs];
102
141
  if (help) candidate.discovery.helpSha256 = createHash('sha256').update(help).digest('hex');
103
142
  try {
104
- candidate.verification = verify ? await verifyAgent(candidate, { cwd, env, timeoutMs, signal }) : { status: 'pending' };
143
+ candidate.verification = verify ? await verifyAgent(candidate, { cwd, env, timeoutMs, maxHelpBytes, signal }) : { status: 'pending' };
105
144
  candidate.protocolVersion = candidate.verification.protocolVersion || 1;
106
145
  return candidate;
107
146
  } catch (cause) {
package/src/gateway.mjs CHANGED
@@ -4,16 +4,16 @@ import { AcpFrames } from './wire.mjs';
4
4
  import { stopProcess } from './child-process.mjs';
5
5
  import { error, strings } from './profiles.mjs';
6
6
  import { authMarker, terminalAuthReply } from './terminal-auth.mjs';
7
- import { member, whitespace } from './json-spans.mjs';
7
+ import { member, requestKey, setField, whitespace } from './json-spans.mjs';
8
+ import { clientWantsHistory, codexKey, historyKey, SessionHistory } from './session-history.mjs';
8
9
 
9
10
  // The reply to a session/new that AgentLink could not prepare, for example
10
11
  // because the profile file was unreadable at that moment. The request ID is
11
12
  // copied as raw text so large numeric IDs keep their exact bytes.
12
13
  function sessionSetupError(source, cause) {
13
14
  const id = source.slice(...member(source, whitespace(source, 0), 'id'));
14
- // The request itself was valid, so this is an internal error (-32603), not
15
- // invalid params. data.code carries the stable AgentLink or OS error code.
16
- const detail = { code: -32603, message: 'AgentLink could not prepare this session: ' + cause.message,
15
+ const historyError = ['INVALID_SESSION_HISTORY', 'SESSION_HISTORY_UNSUPPORTED', 'INVALID_REQUEST_ID'].includes(cause.code);
16
+ const detail = { code: historyError ? -32602 : -32603, message: 'AgentLink could not prepare this session: ' + cause.message,
17
17
  data: { code: cause.code || 'SESSION_SETUP_FAILED' } };
18
18
  return Buffer.from('{"jsonrpc":"2.0","id":' + id + ',"error":' + JSON.stringify(detail) + '}\n');
19
19
  }
@@ -39,15 +39,21 @@ export async function runGateway(launch, { cwd = process.cwd(), env = process.en
39
39
  cwd, env: terminal ? { ...launch.env, ...env } : { ...env, ...launch.env }, shell: false, windowsHide: !terminal,
40
40
  detached: process.platform !== 'win32', stdio: terminal ? 'inherit' : ['pipe', 'pipe', 'pipe']
41
41
  });
42
- let failure, inputTimer, closing = false;
42
+ let failure, inputTimer, history, closing = false;
43
43
  const pumps = new AbortController();
44
44
  let stopPromise;
45
45
  const stop = () => stopPromise ??= stopProcess(child).catch(cause => { failure ??= cause; });
46
46
  const fail = cause => {
47
- failure ??= cause;
48
- pumps.abort();
49
- if (!terminal) output.destroy(); // end:false may have settled before its last write callback.
50
- void stop();
47
+ if (failure) return;
48
+ failure = cause;
49
+ const halt = () => {
50
+ pumps.abort();
51
+ if (!terminal) output.destroy(); // Interrupt blocked final writes.
52
+ void stop();
53
+ };
54
+ if (!history) return halt();
55
+ input.pause();
56
+ void history.disconnect().finally(halt);
51
57
  };
52
58
  const aborted = () => fail(error('CANCELLED', 'AgentLink connection was terminated.'));
53
59
  signal?.addEventListener('abort', aborted, { once: true });
@@ -59,35 +65,75 @@ export async function runGateway(launch, { cwd = process.cwd(), env = process.en
59
65
  let inputPump = Promise.resolve();
60
66
  let outputFrames;
61
67
  if (!terminal) {
62
- let defaultsRelay, protocolVersion, refusal;
68
+ let defaultsRelay, protocolVersion, refusal, prepared, awaitingHistory = false, outputClosed = false;
69
+ const send = frame => {
70
+ if (closing || child.stdin.destroyed || child.stdin.writableEnded) return false;
71
+ child.stdin.write(frame);
72
+ return true;
73
+ };
74
+ const publish = frame => {
75
+ if (!closing && !outputClosed && !outputFrames.destroyed) outputFrames.push(frame);
76
+ };
77
+ function rejectRequest(source, cause) {
78
+ refusal = sessionSetupError(source, cause);
79
+ diagnostics.write((cause.code || 'SESSION_SETUP_FAILED') + ': ' + cause.message + '\n');
80
+ }
63
81
  async function prepareSession(message, source) {
64
82
  try {
83
+ if (Object.hasOwn(message.params?._meta ?? {}, historyKey)) {
84
+ if (!history) throw error('SESSION_HISTORY_UNSUPPORTED', 'Per-session history requires ACP v1 negotiation.');
85
+ prepared = history.prepare(message, source);
86
+ }
65
87
  const defaults = readDefaults ? await readDefaults() : launch.defaults;
66
88
  if (!defaults || !Object.keys(defaults).length) return;
67
89
  if (!defaultsRelay) {
68
90
  const { SessionDefaults } = await import('./session-defaults.mjs');
69
- defaultsRelay = new SessionDefaults(frame => child.stdin.write(frame), maxMessageBytes);
91
+ defaultsRelay = new SessionDefaults(send, maxMessageBytes, sessionId => history?.failedSetup(sessionId));
70
92
  }
71
93
  defaultsRelay.expectSession(message, source, defaults, protocolVersion);
72
94
  } catch (cause) {
73
95
  // Only this creation fails. The bridge never sees it, and the other
74
96
  // sessions on this connection keep running.
75
- refusal = sessionSetupError(source, cause);
76
- // The client may not show error details, so the reason also goes to the log.
77
- diagnostics.write((cause.code || 'SESSION_SETUP_FAILED') + ': ' + cause.message + '\n');
97
+ history?.forgetRequest(message, source);
98
+ rejectRequest(source, cause);
78
99
  }
79
100
  }
80
- const initializeIds = new Set();
101
+ const initializeIds = new Map();
81
102
  inputPump = pipeline(input, new AcpFrames({ maxMessageBytes, onMessage(message, source) {
82
- if (message.method === 'session/new' && Object.hasOwn(message, 'id')) return prepareSession(message, source);
83
- if (message.method === 'initialize' && Object.hasOwn(message, 'id')) initializeIds.add(message.id);
103
+ if (failure) return;
104
+ if (message.method && history?.reserved(message.id)) {
105
+ return rejectRequest(source, error('INVALID_REQUEST_ID', 'This request ID is reserved by the gateway.'));
106
+ }
107
+ if (message.method === 'initialize' && Object.hasOwn(message, 'id')) {
108
+ const wants = clientWantsHistory(message.params);
109
+ // Changing upstream AIR capabilities on a live connection can turn an
110
+ // archive into permanent deletion. A negotiated client initializes once.
111
+ if (history || awaitingHistory || (wants && (protocolVersion || initializeIds.size))) {
112
+ return rejectRequest(source, error('INVALID_SESSION_HISTORY', 'History negotiation requires a fresh connection.'));
113
+ }
114
+ awaitingHistory = wants;
115
+ const air = message.params?.clientCapabilities?._meta?.jetbrains?.air?.capabilities;
116
+ initializeIds.set(requestKey(message.id, source), { wants, airIndex: Array.isArray(air) && air.includes('sessionIndex') });
117
+ if (wants) {
118
+ const upstream = setField(source, ['params', 'clientCapabilities', '_meta', historyKey], undefined);
119
+ prepared = Buffer.from(setField(upstream, ['params', 'clientCapabilities', '_meta', codexKey], { version: 1 }));
120
+ }
121
+ } else if (message.method === 'session/new' && Object.hasOwn(message, 'id')) {
122
+ return prepareSession(message, source);
123
+ } else if (history && message.method) {
124
+ return history.beforeClient(message, source).catch(cause => rejectRequest(source, cause));
125
+ }
84
126
  }, mapMessage() {
85
- if (!refusal) return;
86
- // Reply through the output pump so the frame keeps its place in the stream.
87
- if (!outputFrames.writableEnded && !outputFrames.destroyed) outputFrames.push(refusal);
127
+ const frame = prepared;
128
+ prepared = undefined;
129
+ if (failure) return null;
130
+ if (!refusal) return frame;
131
+ publish(refusal);
88
132
  refusal = undefined;
89
133
  return null;
90
- } }), child.stdin, { signal: pumps.signal }).then(() => {
134
+ } }), child.stdin, { end: false, signal: pumps.signal }).then(async () => {
135
+ await history?.disconnect();
136
+ if (!child.stdin.destroyed && !child.stdin.writableEnded) child.stdin.end();
91
137
  if (!closing && child.exitCode === null && child.signalCode === null) {
92
138
  inputTimer = setTimeout(() => { void stop(); }, eofGraceMs);
93
139
  }
@@ -99,13 +145,30 @@ export async function runGateway(launch, { cwd = process.cwd(), env = process.en
99
145
  if (child.exitCode === null && child.signalCode === null) inputTimer = setTimeout(() => fail(cause), pipeGraceMs);
100
146
  } else fail(cause);
101
147
  });
102
- outputFrames = new AcpFrames({ maxMessageBytes, mapMessage(message, source) {
103
- if (message.method || !initializeIds.delete(message.id)) return defaultsRelay?.agentMessage(message, source);
104
- protocolVersion = message.result?.protocolVersion;
105
- if (!Array.isArray(message.result?.authMethods)) return;
106
- // The client relaunches AgentLink, not the underlying executable. A marker
107
- // identifies terminal auth even when the upstream method has only env.
108
- return terminalAuthReply(message, source);
148
+ outputFrames = new AcpFrames({ maxMessageBytes, async onEnd() {
149
+ await history?.endOutput();
150
+ outputClosed = true;
151
+ }, mapMessage(message, source) {
152
+ const key = !message.method && initializeIds.size ? requestKey(message.id, source) : undefined;
153
+ if (initializeIds.has(key)) {
154
+ const { wants, airIndex } = initializeIds.get(key);
155
+ initializeIds.delete(key);
156
+ if (wants) awaitingHistory = false;
157
+ protocolVersion = message.result?.protocolVersion;
158
+ const auth = terminalAuthReply(message, source);
159
+ const caps = message.result?.agentCapabilities;
160
+ if (wants && protocolVersion === 1 && (caps == null || typeof caps === 'object' && !Array.isArray(caps))) {
161
+ history ??= new SessionHistory(message.result, send, body => publish(Buffer.concat([body, Buffer.from('\n')])), maxMessageBytes,
162
+ { requestedAirIndex: airIndex, warn: detail => diagnostics.write('SESSION_HISTORY_UNCONFIRMED: ' + detail + '\n') });
163
+ return history.capability(auth?.toString() ?? source);
164
+ }
165
+ return auth;
166
+ }
167
+ const annotated = history?.agentMessage(message, source);
168
+ if (annotated === null || !defaultsRelay) return annotated;
169
+ if (annotated) { source = annotated.toString(); message = JSON.parse(source); }
170
+ const configured = defaultsRelay.agentMessage(message, source);
171
+ return configured === undefined ? annotated : configured;
109
172
  } });
110
173
  outputPump = pipeline(child.stdout, outputFrames, output, { end: false, signal: pumps.signal })
111
174
  .catch(cause => { if (!closing) fail(cause); });
@@ -138,6 +201,7 @@ export async function runGateway(launch, { cwd = process.cwd(), env = process.en
138
201
  return { exitCode };
139
202
  } finally {
140
203
  closing = true;
204
+ history?.dispose();
141
205
  clearTimeout(inputTimer); clearTimeout(flushTimer);
142
206
  signal?.removeEventListener('abort', aborted);
143
207
  diagnostics.off('error', fail);
@@ -16,6 +16,48 @@ export function valueEnd(text, start) {
16
16
  }
17
17
  return text.length;
18
18
  }
19
+ // Match requests without rounding JSON integers beyond JavaScript's safe range.
20
+ export function requestKey(id, source) {
21
+ if (typeof id === 'number' && !Number.isSafeInteger(id)) return 'number:' + source.slice(...member(source, whitespace(source, 0), 'id'));
22
+ return JSON.stringify(id);
23
+ }
24
+
25
+ function withoutMember(source, at, name) {
26
+ const parts = [];
27
+ let start = at + 1, key = whitespace(source, start);
28
+ while (source[key] !== '}') {
29
+ const keyEnd = valueEnd(source, key);
30
+ const value = whitespace(source, whitespace(source, keyEnd) + 1);
31
+ const end = whitespace(source, valueEnd(source, value));
32
+ if (JSON.parse(source.slice(key, keyEnd)) !== name) parts.push(source.slice(start, end));
33
+ if (source[end] === '}') return source.slice(0, at + 1) + parts.join(',') + source.slice(end);
34
+ start = end + 1;
35
+ key = whitespace(source, start);
36
+ }
37
+ return source;
38
+ }
39
+
40
+ // Set a nested metadata field without reserializing its siblings, which may
41
+ // contain opaque identifiers or large integers. Missing ancestors are objects.
42
+ export function setField(source, path, value) {
43
+ let at = whitespace(source, 0);
44
+ for (const [index, name] of path.entries()) {
45
+ if (source[at] !== '{') throw new TypeError('Expected an ACP metadata object.');
46
+ const span = member(source, at, name);
47
+ if (!span || (index < path.length - 1 && source.startsWith('null', span[0]))) {
48
+ if (value === undefined) return source;
49
+ let tree = value;
50
+ for (let i = path.length - 1; i > index; i--) tree = { [path[i]]: tree };
51
+ if (span) return source.slice(0, span[0]) + JSON.stringify(tree) + source.slice(span[1]);
52
+ const comma = source[whitespace(source, at + 1)] === '}' ? '' : ',';
53
+ return source.slice(0, at + 1) + JSON.stringify(name) + ':' + JSON.stringify(tree) + comma + source.slice(at + 1);
54
+ }
55
+ if (index === path.length - 1) return value === undefined ? withoutMember(source, at, name)
56
+ : source.slice(0, span[0]) + JSON.stringify(value) + source.slice(span[1]);
57
+ at = span[0];
58
+ }
59
+ }
60
+
19
61
  export function member(text, start, name) {
20
62
  if (text[start] !== '{') return;
21
63
  let found, at = whitespace(text, start + 1);
@@ -171,8 +171,14 @@ export async function runManagement(argv, { signal, cliURL } = {}) {
171
171
  result.checks.map(check => check.status + '\t' + check.scope + ' ' + check.name +
172
172
  (check.message ? ': ' + check.message : '')).join('\n') + '\n');
173
173
  else if (action === 'remove') process.stdout.write('Removed ' + first + '.\n');
174
- else process.stdout.write((result.name || first) + ': ' + result.verification.status +
175
- (action === 'check' ? '\n' : '\nSaved ' + manager.store.path(result.name) + '\n'));
174
+ else {
175
+ const { status, sessionHistory } = result.verification;
176
+ const lines = [(result.name || first) + ': ' + status];
177
+ if (sessionHistory) lines.push('ACP v1 session history: ' + sessionHistory.acpV1Strategy);
178
+ if (sessionHistory?.codexExecEphemeral) lines.push('Codex exec --ephemeral: ' + sessionHistory.codexExecEphemeral);
179
+ if (action !== 'check') lines.push('Saved ' + manager.store.path(result.name));
180
+ process.stdout.write(lines.join('\n') + '\n');
181
+ }
176
182
  }
177
183
  } catch (cause) {
178
184
  const detail = { code: cause.code || 'INVALID_ARGUMENT', message: cause.message };
package/src/probe.mjs CHANGED
@@ -4,35 +4,48 @@ import { AcpFrames } from './wire.mjs';
4
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 finishCommand(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
  }
@@ -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 } }) + '}');