@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/README.md +80 -324
- package/docs/architecture.md +81 -5
- package/docs/laptop-testing.md +34 -8
- package/package.json +1 -1
- package/src/bridges.mjs +2 -2
- package/src/discovery.mjs +42 -3
- package/src/gateway.mjs +92 -28
- package/src/json-spans.mjs +42 -0
- package/src/management-cli.mjs +8 -2
- package/src/probe.mjs +47 -13
- package/src/session-defaults.mjs +5 -7
- package/src/session-history.mjs +279 -0
- package/src/version.mjs +1 -1
- package/src/wire.mjs +6 -2
|
@@ -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.
|
|
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
|
-
|
|
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
|
}
|