@apnex/network-adapter 0.1.0

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 (52) hide show
  1. package/dist/hub-error.d.ts +42 -0
  2. package/dist/hub-error.js +74 -0
  3. package/dist/hub-error.js.map +1 -0
  4. package/dist/index.d.ts +29 -0
  5. package/dist/index.js +31 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/kernel/agent-client.d.ts +192 -0
  8. package/dist/kernel/agent-client.js +44 -0
  9. package/dist/kernel/agent-client.js.map +1 -0
  10. package/dist/kernel/event-router.d.ts +49 -0
  11. package/dist/kernel/event-router.js +150 -0
  12. package/dist/kernel/event-router.js.map +1 -0
  13. package/dist/kernel/handshake.d.ts +161 -0
  14. package/dist/kernel/handshake.js +257 -0
  15. package/dist/kernel/handshake.js.map +1 -0
  16. package/dist/kernel/instance.d.ts +40 -0
  17. package/dist/kernel/instance.js +79 -0
  18. package/dist/kernel/instance.js.map +1 -0
  19. package/dist/kernel/mcp-agent-client.d.ts +139 -0
  20. package/dist/kernel/mcp-agent-client.js +505 -0
  21. package/dist/kernel/mcp-agent-client.js.map +1 -0
  22. package/dist/kernel/poll-backstop.d.ts +108 -0
  23. package/dist/kernel/poll-backstop.js +243 -0
  24. package/dist/kernel/poll-backstop.js.map +1 -0
  25. package/dist/kernel/session-claim.d.ts +67 -0
  26. package/dist/kernel/session-claim.js +106 -0
  27. package/dist/kernel/session-claim.js.map +1 -0
  28. package/dist/kernel/state-sync.d.ts +43 -0
  29. package/dist/kernel/state-sync.js +85 -0
  30. package/dist/kernel/state-sync.js.map +1 -0
  31. package/dist/logger.d.ts +82 -0
  32. package/dist/logger.js +114 -0
  33. package/dist/logger.js.map +1 -0
  34. package/dist/notification-log.d.ts +29 -0
  35. package/dist/notification-log.js +66 -0
  36. package/dist/notification-log.js.map +1 -0
  37. package/dist/prompt-format.d.ts +38 -0
  38. package/dist/prompt-format.js +220 -0
  39. package/dist/prompt-format.js.map +1 -0
  40. package/dist/tool-manager/dispatcher.d.ts +180 -0
  41. package/dist/tool-manager/dispatcher.js +379 -0
  42. package/dist/tool-manager/dispatcher.js.map +1 -0
  43. package/dist/tool-manager/tool-catalog-cache.d.ts +85 -0
  44. package/dist/tool-manager/tool-catalog-cache.js +137 -0
  45. package/dist/tool-manager/tool-catalog-cache.js.map +1 -0
  46. package/dist/wire/mcp-transport.d.ts +120 -0
  47. package/dist/wire/mcp-transport.js +447 -0
  48. package/dist/wire/mcp-transport.js.map +1 -0
  49. package/dist/wire/transport.d.ts +174 -0
  50. package/dist/wire/transport.js +43 -0
  51. package/dist/wire/transport.js.map +1 -0
  52. package/package.json +32 -0
@@ -0,0 +1,139 @@
1
+ /**
2
+ * McpAgentClient — Layer-7 `IAgentClient` implementation built on top
3
+ * of `McpTransport`.
4
+ *
5
+ * Phase 3 of the L4/L7 refactor. This class owns everything that
6
+ * `McpConnectionManager` + `UniversalClientAdapter` together own today:
7
+ *
8
+ * - The session FSM (disconnected → connecting → synchronizing →
9
+ * streaming → reconnecting).
10
+ * - Role registration. Plain `register_role` when `handshake` is omitted;
11
+ * the full enriched handshake via `performHandshake` when `handshake`
12
+ * is supplied.
13
+ * - State sync on entry to `synchronizing` (`get_task` +
14
+ * `get_pending_actions` via `performStateSync`).
15
+ * - `session_invalid` retry-once on `call()`: close the wire, reopen,
16
+ * re-handshake, retry the failed call exactly once on the fresh
17
+ * session.
18
+ * - Hub-event dedup, classification (actionable / informational /
19
+ * unhandled), and routing into the shim callbacks.
20
+ * - SyncBuffer: hub-events that arrive while the session is
21
+ * `synchronizing` or `reconnecting` are buffered and flushed on
22
+ * entry to `streaming`, so shims never observe events from a
23
+ * half-bound session.
24
+ *
25
+ * It is NOT responsible for wire framing, SSE watchdogs, heartbeat
26
+ * POSTs, or HTTP retries. Those live in the `McpTransport` below, which
27
+ * this class either constructs (if a `TransportConfig` is passed) or
28
+ * accepts by injection (so tests can swap in a fake transport).
29
+ *
30
+ * Runtime note: no existing consumer uses this class yet. Phase 4 will
31
+ * swap `UniversalClientAdapter` over to this surface and delete the
32
+ * `McpConnectionManager` path. Until then, `McpConnectionManager` stays
33
+ * intact and this class lives alongside it.
34
+ */
35
+ import type { IAgentClient, AgentClientConfig, AgentClientCallbacks, AgentClientMetrics, SessionState } from "./agent-client.js";
36
+ import type { ITransport, TransportConfig } from "../wire/transport.js";
37
+ import type { CognitivePipeline, Tool as CognitiveTool } from "@apnex/cognitive-layer";
38
+ export interface McpAgentClientOptions {
39
+ /**
40
+ * Explicit transport instance. Caller retains ownership — `stop()`
41
+ * will NOT close a transport passed this way, to keep injection
42
+ * ergonomic for tests. Mutually exclusive with `transportConfig`.
43
+ *
44
+ * Typed as `ITransport` so test harnesses can plug in a loopback
45
+ * transport (or any future non-MCP wire) without touching this class.
46
+ */
47
+ transport?: ITransport;
48
+ /**
49
+ * Transport config. When set, the AgentClient constructs its own
50
+ * `McpTransport` and closes it on `stop()`.
51
+ */
52
+ transportConfig?: TransportConfig;
53
+ /** Dedup cache size. Default 100, matching `UniversalClientAdapter`. */
54
+ dedupCacheSize?: number;
55
+ /**
56
+ * Opt-in cognitive-layer pipeline (ADR-018 / `@apnex/cognitive-layer`).
57
+ * When provided, every `call()` is wrapped through the pipeline's
58
+ * `runToolCall` phase with the raw transport request as the terminal;
59
+ * thrown errors are routed through `runToolError`. Omit for legacy
60
+ * behavior (zero cost — no pipeline overhead). Use
61
+ * `CognitivePipeline.standard({...})` for the ADR-018 canonical stack.
62
+ */
63
+ cognitive?: CognitivePipeline;
64
+ /**
65
+ * Legacy-compatible mode: when true, `runSynchronizingPhase` performs
66
+ * the handshake(s) but does NOT run `performStateSync` or advance the
67
+ * FSM out of `synchronizing`. The caller must drive `completeSync()`
68
+ * manually — used by shims that own their own state-sync pipeline.
69
+ *
70
+ * Default false: full auto-sync (handshake → state sync → streaming).
71
+ */
72
+ manualSync?: boolean;
73
+ }
74
+ export declare class McpAgentClient implements IAgentClient {
75
+ private readonly cfg;
76
+ private readonly log;
77
+ private readonly transport;
78
+ private readonly ownsTransport;
79
+ private readonly manualSync;
80
+ private readonly dedup;
81
+ private readonly cognitive?;
82
+ private _state;
83
+ private callbacks;
84
+ private syncBuffer;
85
+ private synchronizingInFlight;
86
+ private sessionReconnecting;
87
+ private stopped;
88
+ private _agentId?;
89
+ private _sessionEpoch?;
90
+ private _lastEpoch;
91
+ private totalHandshakes;
92
+ private totalSessionInvalidRetries;
93
+ private dedupDropCount;
94
+ private lastEventId;
95
+ constructor(config: AgentClientConfig, options?: McpAgentClientOptions);
96
+ get state(): SessionState;
97
+ get isConnected(): boolean;
98
+ start(): Promise<void>;
99
+ stop(): Promise<void>;
100
+ call(method: string, params: Record<string, unknown>): Promise<unknown>;
101
+ /**
102
+ * Route `tools/list` through the cognitive pipeline when one is
103
+ * configured; otherwise fall through to `transport.listToolsRaw()`
104
+ * directly (shim-compatible signature). Enables
105
+ * `ToolDescriptionEnricher` and any future list-tools middleware
106
+ * to observe the tool-surface request before it reaches the Hub
107
+ * client. Shims that previously reached into `getTransport()
108
+ * .listToolsRaw()` should migrate to this method.
109
+ */
110
+ listTools(): Promise<CognitiveTool[]>;
111
+ /**
112
+ * Raw transport call with the session_invalid retry-once semantics.
113
+ * Separated from `call()` so the cognitive pipeline wraps this whole
114
+ * retry-capable primitive (cache/dedup/circuit all observe one logical
115
+ * invocation regardless of internal session-cycling).
116
+ */
117
+ private rawCall;
118
+ listMethods(): Promise<string[]>;
119
+ setCallbacks(callbacks: AgentClientCallbacks): void;
120
+ getSessionId(): string | undefined;
121
+ getMetrics(): AgentClientMetrics;
122
+ getTransport(): ITransport;
123
+ private transition;
124
+ private handleWireEvent;
125
+ private mapWireCause;
126
+ private runSynchronizingPhase;
127
+ /**
128
+ * Public sync-completion hook. Only meaningful when the client was
129
+ * constructed with `manualSync: true`: the caller drives the
130
+ * synchronizing → streaming transition after its own state sync is
131
+ * done. Called automatically under `manualSync: false`.
132
+ */
133
+ completeSync(): void;
134
+ private runHandshake;
135
+ private completeSyncInternal;
136
+ private reconnectSession;
137
+ private handleHubEvent;
138
+ private routeEvent;
139
+ }
@@ -0,0 +1,505 @@
1
+ /**
2
+ * McpAgentClient — Layer-7 `IAgentClient` implementation built on top
3
+ * of `McpTransport`.
4
+ *
5
+ * Phase 3 of the L4/L7 refactor. This class owns everything that
6
+ * `McpConnectionManager` + `UniversalClientAdapter` together own today:
7
+ *
8
+ * - The session FSM (disconnected → connecting → synchronizing →
9
+ * streaming → reconnecting).
10
+ * - Role registration. Plain `register_role` when `handshake` is omitted;
11
+ * the full enriched handshake via `performHandshake` when `handshake`
12
+ * is supplied.
13
+ * - State sync on entry to `synchronizing` (`get_task` +
14
+ * `get_pending_actions` via `performStateSync`).
15
+ * - `session_invalid` retry-once on `call()`: close the wire, reopen,
16
+ * re-handshake, retry the failed call exactly once on the fresh
17
+ * session.
18
+ * - Hub-event dedup, classification (actionable / informational /
19
+ * unhandled), and routing into the shim callbacks.
20
+ * - SyncBuffer: hub-events that arrive while the session is
21
+ * `synchronizing` or `reconnecting` are buffered and flushed on
22
+ * entry to `streaming`, so shims never observe events from a
23
+ * half-bound session.
24
+ *
25
+ * It is NOT responsible for wire framing, SSE watchdogs, heartbeat
26
+ * POSTs, or HTTP retries. Those live in the `McpTransport` below, which
27
+ * this class either constructs (if a `TransportConfig` is passed) or
28
+ * accepts by injection (so tests can swap in a fake transport).
29
+ *
30
+ * Runtime note: no existing consumer uses this class yet. Phase 4 will
31
+ * swap `UniversalClientAdapter` over to this surface and delete the
32
+ * `McpConnectionManager` path. Until then, `McpConnectionManager` stays
33
+ * intact and this class lives alongside it.
34
+ */
35
+ import { McpTransport } from "../wire/mcp-transport.js";
36
+ import { normalizeToILogger } from "../logger.js";
37
+ import { parseHubEvent, classifyEvent, createDedupFilter, } from "./event-router.js";
38
+ import { performHandshake } from "./handshake.js";
39
+ import { HubReturnedError, isErrorEnvelope } from "../hub-error.js";
40
+ import { performStateSync } from "./state-sync.js";
41
+ // Same list as McpConnectionManager. Matched case-insensitively.
42
+ const SESSION_INVALID_PATTERNS = [
43
+ "No valid session ID",
44
+ "Bad Request",
45
+ "Session not found",
46
+ "invalid session",
47
+ ];
48
+ function isSessionInvalidError(err) {
49
+ const msg = String(err).toLowerCase();
50
+ return SESSION_INVALID_PATTERNS.some((p) => msg.includes(p.toLowerCase()));
51
+ }
52
+ export class McpAgentClient {
53
+ cfg;
54
+ log;
55
+ transport;
56
+ ownsTransport;
57
+ manualSync;
58
+ dedup;
59
+ cognitive;
60
+ _state = "disconnected";
61
+ callbacks = {};
62
+ // Events buffered during non-streaming states so shims don't see
63
+ // traffic from a half-bound session.
64
+ syncBuffer = [];
65
+ // Re-entrancy guard on the synchronizing phase — the transport can
66
+ // emit `reconnected` mid-handshake in pathological cases and we must
67
+ // not double-run.
68
+ synchronizingInFlight = false;
69
+ // True while `reconnectSession()` is manually cycling the wire for a
70
+ // session_invalid retry. Suppresses the `closed` wire event from
71
+ // flipping the session FSM to `disconnected` — we handle FSM
72
+ // transitions ourselves in that path.
73
+ sessionReconnecting = false;
74
+ // True once `stop()` is called. Suppresses handleWireEvent work.
75
+ stopped = false;
76
+ // Session identity + metrics.
77
+ _agentId;
78
+ _sessionEpoch;
79
+ _lastEpoch = 0;
80
+ totalHandshakes = 0;
81
+ totalSessionInvalidRetries = 0;
82
+ dedupDropCount = 0;
83
+ // Mission-56 W2.2: most-recent Hub event id observed on the SSE
84
+ // stream. Surfaced to the wire layer via the `getLastEventId`
85
+ // TransportConfig hook so reconnects send the canonical
86
+ // `Last-Event-ID` header to drive Hub-side W1b backfill replay.
87
+ lastEventId;
88
+ constructor(config, options = {}) {
89
+ this.cfg = config;
90
+ this.log = normalizeToILogger(config.logger, "McpAgentClient");
91
+ this.manualSync = options.manualSync ?? false;
92
+ this.dedup = createDedupFilter(options.dedupCacheSize ?? 100);
93
+ this.cognitive = options.cognitive;
94
+ if (options.transport && options.transportConfig) {
95
+ throw new Error("McpAgentClient: pass `transport` OR `transportConfig`, not both");
96
+ }
97
+ if (options.transport) {
98
+ this.transport = options.transport;
99
+ this.ownsTransport = false;
100
+ }
101
+ else if (options.transportConfig) {
102
+ this.transport = new McpTransport({
103
+ ...options.transportConfig,
104
+ logger: config.logger ?? options.transportConfig.logger,
105
+ // Caller-supplied provider wins; otherwise the kernel's tracked
106
+ // lastEventId backs the SSE Last-Event-ID header on reconnect.
107
+ getLastEventId: options.transportConfig.getLastEventId ?? (() => this.lastEventId),
108
+ });
109
+ this.ownsTransport = true;
110
+ }
111
+ else {
112
+ throw new Error("McpAgentClient: either `transport` or `transportConfig` is required");
113
+ }
114
+ this.transport.onWireEvent((e) => this.handleWireEvent(e));
115
+ }
116
+ // ── IAgentClient: public surface ────────────────────────────────────
117
+ get state() {
118
+ return this._state;
119
+ }
120
+ get isConnected() {
121
+ return this._state === "streaming";
122
+ }
123
+ async start() {
124
+ if (this._state !== "disconnected") {
125
+ this.log.log("agent.start.ignored", { state: this._state }, `start() ignored in state=${this._state}`);
126
+ return;
127
+ }
128
+ this.stopped = false;
129
+ this.transition("connecting");
130
+ try {
131
+ await this.transport.connect();
132
+ }
133
+ catch (err) {
134
+ this.log.log("agent.start.failed", { error: String(err) }, `start: transport.connect failed: ${err}`);
135
+ this.transition("disconnected");
136
+ throw err;
137
+ }
138
+ // Wire is up. Now run the session bring-up. Rethrow on first-boot
139
+ // so a non-retriable handshake failure (e.g. 401) propagates out
140
+ // of `start()` instead of best-efforting into streaming on a
141
+ // broken session. Wire-reconnect re-entry keeps the best-effort
142
+ // path because a transient reconnect failure should not tear
143
+ // the shim down.
144
+ await this.runSynchronizingPhase({ rethrowOnFailure: true });
145
+ }
146
+ async stop() {
147
+ this.stopped = true;
148
+ this.syncBuffer.length = 0;
149
+ if (this.ownsTransport) {
150
+ await this.transport.close();
151
+ }
152
+ this.transition("disconnected");
153
+ this.dedup.clear();
154
+ }
155
+ async call(method, params) {
156
+ if (this._state !== "streaming" && this._state !== "synchronizing") {
157
+ throw new Error(`McpAgentClient.call: session state=${this._state}`);
158
+ }
159
+ // Legacy path: no cognitive pipeline configured. Zero-cost passthrough.
160
+ if (!this.cognitive) {
161
+ return this.rawCall(method, params);
162
+ }
163
+ // Cognitive path (ADR-018): wrap raw call through the pipeline.
164
+ // runToolCall threads every registered middleware's onToolCall around
165
+ // the terminal; runToolError routes any thrown error through the
166
+ // error phase (ErrorNormalizer, etc.) with a re-throw fallback.
167
+ const startedAt = Date.now();
168
+ const ctx = {
169
+ tool: method,
170
+ args: params,
171
+ sessionId: this.transport.getSessionId() ?? "",
172
+ agentId: this._agentId,
173
+ startedAt,
174
+ tags: {},
175
+ };
176
+ try {
177
+ return await this.cognitive.runToolCall(ctx, async (c) => {
178
+ const result = await this.rawCall(c.tool, c.args);
179
+ // Hub-layer application errors come back as `{isError, content}`
180
+ // envelopes — NOT thrown. For ErrorNormalizer (and any other
181
+ // onToolError middleware) to observe them, convert to a throw
182
+ // HERE. Legacy (non-cognitive) call path preserves the
183
+ // envelope-as-return-value contract unchanged.
184
+ if (isErrorEnvelope(result)) {
185
+ throw new HubReturnedError(result);
186
+ }
187
+ return result;
188
+ });
189
+ }
190
+ catch (err) {
191
+ const errCtx = {
192
+ tool: method,
193
+ args: params,
194
+ sessionId: ctx.sessionId,
195
+ agentId: this._agentId,
196
+ error: err,
197
+ durationMs: Date.now() - startedAt,
198
+ startedAt,
199
+ tags: ctx.tags,
200
+ };
201
+ // Error phase: any middleware may transform the error into a
202
+ // recovered value; fallback terminal re-throws.
203
+ return await this.cognitive.runToolError(errCtx, async () => {
204
+ throw err;
205
+ });
206
+ }
207
+ }
208
+ /**
209
+ * Route `tools/list` through the cognitive pipeline when one is
210
+ * configured; otherwise fall through to `transport.listToolsRaw()`
211
+ * directly (shim-compatible signature). Enables
212
+ * `ToolDescriptionEnricher` and any future list-tools middleware
213
+ * to observe the tool-surface request before it reaches the Hub
214
+ * client. Shims that previously reached into `getTransport()
215
+ * .listToolsRaw()` should migrate to this method.
216
+ */
217
+ async listTools() {
218
+ const raw = await this.transport.listToolsRaw();
219
+ const tools = raw;
220
+ if (!this.cognitive)
221
+ return tools;
222
+ const ctx = {
223
+ sessionId: this.transport.getSessionId() ?? "",
224
+ agentId: this._agentId,
225
+ startedAt: Date.now(),
226
+ tags: {},
227
+ };
228
+ return this.cognitive.runListTools(ctx, async () => tools);
229
+ }
230
+ /**
231
+ * Raw transport call with the session_invalid retry-once semantics.
232
+ * Separated from `call()` so the cognitive pipeline wraps this whole
233
+ * retry-capable primitive (cache/dedup/circuit all observe one logical
234
+ * invocation regardless of internal session-cycling).
235
+ */
236
+ async rawCall(method, params) {
237
+ try {
238
+ return await this.transport.request(method, params);
239
+ }
240
+ catch (err) {
241
+ if (!isSessionInvalidError(err))
242
+ throw err;
243
+ this.totalSessionInvalidRetries++;
244
+ this.log.log("agent.session.invalid_retry", { method }, `call(${method}): session_invalid — cycling session`);
245
+ await this.reconnectSession("session_invalid");
246
+ // Retry exactly once on the fresh session.
247
+ return await this.transport.request(method, params);
248
+ }
249
+ }
250
+ async listMethods() {
251
+ return this.transport.listMethods();
252
+ }
253
+ setCallbacks(callbacks) {
254
+ this.callbacks = callbacks;
255
+ }
256
+ getSessionId() {
257
+ return this.transport.getSessionId();
258
+ }
259
+ getMetrics() {
260
+ return {
261
+ sessionState: this._state,
262
+ agentId: this._agentId,
263
+ sessionEpoch: this._sessionEpoch,
264
+ totalHandshakes: this.totalHandshakes,
265
+ totalSessionInvalidRetries: this.totalSessionInvalidRetries,
266
+ dedupDropCount: this.dedupDropCount,
267
+ };
268
+ }
269
+ getTransport() {
270
+ return this.transport;
271
+ }
272
+ // ── Internal: FSM and wire-event glue ───────────────────────────────
273
+ transition(to, reason) {
274
+ if (this._state === to)
275
+ return;
276
+ const from = this._state;
277
+ this._state = to;
278
+ this.log.log("agent.session.state", { from, to, reason }, `session ${from} → ${to}${reason ? ` (${reason})` : ""}`);
279
+ try {
280
+ this.callbacks.onStateChange?.(to, from, reason);
281
+ }
282
+ catch (err) {
283
+ this.log.log("agent.state.handler_error", { error: String(err) }, `onStateChange handler error: ${err}`);
284
+ }
285
+ }
286
+ handleWireEvent(event) {
287
+ if (this.stopped)
288
+ return;
289
+ switch (event.type) {
290
+ case "push":
291
+ if (event.method === "hub-event")
292
+ this.handleHubEvent(event.payload);
293
+ return;
294
+ case "reconnecting":
295
+ // Map wire cause to session reconnect reason with the same
296
+ // vocabulary the legacy manager used. `peer_closed` and
297
+ // `wire_error` both fall under the "sse_watchdog" bucket
298
+ // because the session-level FSM doesn't distinguish them.
299
+ this.transition("reconnecting", this.mapWireCause(event.cause));
300
+ return;
301
+ case "reconnected":
302
+ // Transport brought up a fresh wire. Re-run the session
303
+ // bring-up on it.
304
+ void this.runSynchronizingPhase();
305
+ return;
306
+ case "closed":
307
+ if (this.sessionReconnecting)
308
+ return;
309
+ this.transition("disconnected");
310
+ return;
311
+ }
312
+ }
313
+ mapWireCause(cause) {
314
+ switch (cause) {
315
+ case "heartbeat_failed":
316
+ return "heartbeat_failed";
317
+ case "sse_never_opened":
318
+ return "sse_never_opened";
319
+ case "sse_watchdog":
320
+ case "peer_closed":
321
+ case "wire_error":
322
+ default:
323
+ return "sse_watchdog";
324
+ }
325
+ }
326
+ // ── Internal: session bring-up (handshake + sync) ───────────────────
327
+ async runSynchronizingPhase(opts = {}) {
328
+ if (this.synchronizingInFlight) {
329
+ this.log.log("agent.sync.in_flight", undefined, "runSynchronizingPhase: already in flight — skipping");
330
+ return;
331
+ }
332
+ this.synchronizingInFlight = true;
333
+ try {
334
+ this.transition("synchronizing");
335
+ await this.runHandshake();
336
+ if (this.manualSync) {
337
+ // Caller owns sync. Stay in synchronizing until completeSync().
338
+ return;
339
+ }
340
+ // State sync. `performStateSync` calls `completeSync` on success
341
+ // AND on the failure path, so we always exit synchronizing.
342
+ await performStateSync({
343
+ executeTool: (n, a) => this.transport.request(n, a),
344
+ completeSync: () => this.completeSyncInternal(),
345
+ log: this.log,
346
+ onPendingTask: this.cfg.handshake?.onPendingTask,
347
+ onPendingActionItem: this.cfg.handshake?.onPendingActionItem,
348
+ });
349
+ }
350
+ catch (err) {
351
+ this.log.log("agent.sync.failed", { error: String(err) }, `runSynchronizingPhase failed: ${err}`);
352
+ if (opts.rethrowOnFailure) {
353
+ // First-boot path: propagate to `start()`. Leave the session
354
+ // in `disconnected` so the shim sees a clean failure surface.
355
+ this.transition("disconnected");
356
+ throw err;
357
+ }
358
+ if (!this.manualSync) {
359
+ // Best-effort: flush buffer and move to streaming anyway so the
360
+ // shim isn't stuck. A subsequent wire death will re-drive this.
361
+ this.completeSyncInternal();
362
+ }
363
+ }
364
+ finally {
365
+ this.synchronizingInFlight = false;
366
+ }
367
+ }
368
+ /**
369
+ * Public sync-completion hook. Only meaningful when the client was
370
+ * constructed with `manualSync: true`: the caller drives the
371
+ * synchronizing → streaming transition after its own state sync is
372
+ * done. Called automatically under `manualSync: false`.
373
+ */
374
+ completeSync() {
375
+ this.completeSyncInternal();
376
+ }
377
+ async runHandshake() {
378
+ const handshake = this.cfg.handshake;
379
+ // Bare `register_role` first — proves the wire is alive and the
380
+ // session is bound before spending round-trips on the enriched
381
+ // payload. This ordering is invariant: the enriched handshake below
382
+ // re-registers on the same session to stamp its semantics onto it.
383
+ //
384
+ // Labels are intentionally NOT forwarded here: the Hub's legacy
385
+ // bare-path handler drops them silently (it doesn't create an Agent
386
+ // entity). Labels must ride the enriched payload below so they
387
+ // persist on the Agent and subsequent task.labels / dispatch
388
+ // selectors pick them up.
389
+ await this.transport.request("register_role", { role: this.cfg.role });
390
+ this.totalHandshakes++;
391
+ this.log.log("agent.handshake.plain_ok", { role: this.cfg.role }, `registered as ${this.cfg.role} (plain)`);
392
+ if (!handshake)
393
+ return;
394
+ const result = await performHandshake({
395
+ executeTool: (n, a) => this.transport.request(n, a),
396
+ config: {
397
+ role: this.cfg.role,
398
+ globalInstanceId: handshake.globalInstanceId,
399
+ clientInfo: handshake.getClientInfo(),
400
+ proxyName: handshake.proxyName,
401
+ proxyVersion: handshake.proxyVersion,
402
+ transport: handshake.transport,
403
+ sdkVersion: handshake.sdkVersion,
404
+ llmModel: handshake.llmModel,
405
+ labels: this.cfg.labels,
406
+ wakeEndpoint: handshake.wakeEndpoint,
407
+ receiptSla: handshake.receiptSla,
408
+ },
409
+ previousEpoch: this._lastEpoch,
410
+ log: this.log,
411
+ onFatalHalt: handshake.onFatalHalt,
412
+ });
413
+ this.totalHandshakes++;
414
+ if (result.response) {
415
+ this._lastEpoch = result.epoch;
416
+ this._sessionEpoch = result.response.sessionEpoch;
417
+ this._agentId = result.response.agentId;
418
+ if (handshake.onHandshakeComplete) {
419
+ try {
420
+ handshake.onHandshakeComplete(result.response);
421
+ }
422
+ catch (err) {
423
+ this.log.log("agent.handshake.handler_error", { error: String(err) }, `onHandshakeComplete handler error: ${err}`);
424
+ }
425
+ }
426
+ }
427
+ }
428
+ completeSyncInternal() {
429
+ if (this._state !== "synchronizing")
430
+ return;
431
+ const buffered = this.syncBuffer.splice(0);
432
+ this.transition("streaming");
433
+ if (buffered.length > 0) {
434
+ this.log.log("agent.sync.flush", { count: buffered.length }, `flushing ${buffered.length} buffered event(s)`);
435
+ for (const ev of buffered)
436
+ this.routeEvent(ev);
437
+ }
438
+ }
439
+ // ── Internal: session-invalid reconnect ─────────────────────────────
440
+ async reconnectSession(reason) {
441
+ this.sessionReconnecting = true;
442
+ try {
443
+ this.transition("reconnecting", reason);
444
+ await this.transport.close();
445
+ await this.transport.connect();
446
+ }
447
+ finally {
448
+ this.sessionReconnecting = false;
449
+ }
450
+ // Synchronously (well, awaited) run the bring-up before returning
451
+ // so the retry-in-call() sees a bound session.
452
+ await this.runSynchronizingPhase();
453
+ }
454
+ // ── Internal: hub-event intake ──────────────────────────────────────
455
+ handleHubEvent(payload) {
456
+ if (!payload || typeof payload !== "object")
457
+ return;
458
+ const parsed = parseHubEvent(payload);
459
+ if (this.dedup.isDuplicate(parsed)) {
460
+ this.dedupDropCount++;
461
+ return;
462
+ }
463
+ const event = {
464
+ id: parsed.id,
465
+ event: parsed.event,
466
+ data: parsed.data,
467
+ timestamp: parsed.timestamp,
468
+ };
469
+ // Mission-56 W2.2: the Hub stamps every SSE event's `id:` field
470
+ // with a Message ID (ULID monotonic) — track the most-recent one
471
+ // so a subsequent reconnect's Last-Event-ID header can drive the
472
+ // Hub W1b backfill replay. Skip when no id was present on the
473
+ // event (legacy / non-Hub events).
474
+ if (event.id !== undefined) {
475
+ this.lastEventId = String(event.id);
476
+ }
477
+ // Buffer during any non-streaming state so shims don't see events
478
+ // from a half-bound (or torn-down) session.
479
+ if (this._state !== "streaming") {
480
+ this.syncBuffer.push(event);
481
+ return;
482
+ }
483
+ this.routeEvent(event);
484
+ }
485
+ routeEvent(event) {
486
+ const disposition = classifyEvent(event.event, this.cfg.role);
487
+ try {
488
+ switch (disposition) {
489
+ case "actionable":
490
+ this.callbacks.onActionableEvent?.(event);
491
+ return;
492
+ case "informational":
493
+ this.callbacks.onInformationalEvent?.(event);
494
+ return;
495
+ case "unhandled":
496
+ this.log.log("agent.event.unhandled", { event: event.event }, `unhandled event: ${event.event}`);
497
+ return;
498
+ }
499
+ }
500
+ catch (err) {
501
+ this.log.log("agent.route.handler_error", { error: String(err) }, `route handler error: ${err}`);
502
+ }
503
+ }
504
+ }
505
+ //# sourceMappingURL=mcp-agent-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-agent-client.js","sourceRoot":"","sources":["../../src/kernel/mcp-agent-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAmBH,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EACL,aAAa,EACb,aAAa,EACb,iBAAiB,GAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,eAAe,E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