@nextclaw/ncp-http-agent-client 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NextClaw contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # @nextclaw/ncp-http-agent-client
2
+
3
+ HTTP/SSE transport adapter implementing `NcpAgentClientEndpoint` for agent scenarios.
4
+
5
+ ## Build
6
+
7
+ ```bash
8
+ pnpm -C packages/nextclaw-ncp-http-agent-client build
9
+ ```
10
+
11
+ ## API
12
+
13
+ - `new NcpHttpAgentClientEndpoint(options)`
@@ -0,0 +1,36 @@
1
+ import { NcpAgentClientEndpoint, NcpEndpointManifest, NcpEndpointEvent, NcpEndpointSubscriber, NcpRequestEnvelope, NcpResumeRequestPayload, NcpMessageAbortPayload } from '@nextclaw/ncp';
2
+
3
+ type FetchLike = (input: URL | string | Request, init?: RequestInit) => Promise<Response>;
4
+
5
+ type NcpHttpAgentClientOptions = {
6
+ baseUrl: string;
7
+ basePath?: string;
8
+ endpointId?: string;
9
+ headers?: Record<string, string>;
10
+ fetchImpl?: FetchLike;
11
+ };
12
+ declare class NcpHttpAgentClientEndpoint implements NcpAgentClientEndpoint {
13
+ readonly manifest: NcpEndpointManifest;
14
+ private readonly baseUrl;
15
+ private readonly basePath;
16
+ private readonly fetchImpl;
17
+ private readonly defaultHeaders;
18
+ private readonly subscribers;
19
+ private readonly activeControllers;
20
+ private started;
21
+ constructor(options: NcpHttpAgentClientOptions);
22
+ start(): Promise<void>;
23
+ stop(): Promise<void>;
24
+ emit(event: NcpEndpointEvent): Promise<void>;
25
+ subscribe(listener: NcpEndpointSubscriber): () => void;
26
+ send(envelope: NcpRequestEnvelope): Promise<void>;
27
+ resume(payload: NcpResumeRequestPayload): Promise<void>;
28
+ abort(payload?: NcpMessageAbortPayload): Promise<void>;
29
+ private ensureStarted;
30
+ private publish;
31
+ private resolveUrl;
32
+ private streamRequest;
33
+ private handleSseFrame;
34
+ }
35
+
36
+ export { NcpHttpAgentClientEndpoint, type NcpHttpAgentClientOptions };
package/dist/index.js ADDED
@@ -0,0 +1,419 @@
1
+ // src/sse.ts
2
+ function parseSseFrame(frameText) {
3
+ const lines = frameText.split(/\r?\n/);
4
+ let eventName = "message";
5
+ const dataLines = [];
6
+ for (const rawLine of lines) {
7
+ const line = rawLine.trimEnd();
8
+ if (!line || line.startsWith(":")) {
9
+ continue;
10
+ }
11
+ if (line.startsWith("event:")) {
12
+ eventName = line.slice(6).trim() || "message";
13
+ continue;
14
+ }
15
+ if (line.startsWith("data:")) {
16
+ dataLines.push(line.slice(5).trimStart());
17
+ }
18
+ }
19
+ if (dataLines.length === 0) {
20
+ return null;
21
+ }
22
+ return {
23
+ event: eventName,
24
+ data: dataLines.join("\n")
25
+ };
26
+ }
27
+ async function* consumeSseStream(stream) {
28
+ const reader = stream.getReader();
29
+ const decoder = new TextDecoder();
30
+ let buffer = "";
31
+ try {
32
+ while (true) {
33
+ const { value, done } = await reader.read();
34
+ if (done) {
35
+ break;
36
+ }
37
+ buffer += decoder.decode(value, { stream: true });
38
+ const { frames: frames2, rest } = drainFrames(buffer);
39
+ buffer = rest;
40
+ for (const frame of frames2) {
41
+ yield frame;
42
+ }
43
+ }
44
+ buffer += decoder.decode();
45
+ const { frames } = drainFrames(buffer, true);
46
+ for (const frame of frames) {
47
+ yield frame;
48
+ }
49
+ } finally {
50
+ reader.releaseLock();
51
+ }
52
+ }
53
+ function drainFrames(rawBuffer, flush = false) {
54
+ const parts = rawBuffer.split(/\r?\n\r?\n/);
55
+ const rest = parts.pop() ?? "";
56
+ const frames = [];
57
+ for (const part of parts) {
58
+ const frame = parseSseFrame(part);
59
+ if (frame) {
60
+ frames.push(frame);
61
+ }
62
+ }
63
+ if (flush && rest.trim()) {
64
+ const frame = parseSseFrame(rest);
65
+ if (frame) {
66
+ frames.push(frame);
67
+ }
68
+ return { frames, rest: "" };
69
+ }
70
+ return { frames, rest };
71
+ }
72
+
73
+ // src/utils.ts
74
+ var DEFAULT_BASE_PATH = "/ncp/agent";
75
+ var DEFAULT_ENDPOINT_ID = "ncp-http-agent-client";
76
+ var NcpHttpAgentClientError = class extends Error {
77
+ ncpError;
78
+ alreadyPublished;
79
+ constructor(ncpError, alreadyPublished = false) {
80
+ super(ncpError.message);
81
+ this.name = `NcpHttpAgentClientError(${ncpError.code})`;
82
+ this.ncpError = ncpError;
83
+ this.alreadyPublished = alreadyPublished;
84
+ }
85
+ };
86
+ function toBaseUrl(baseUrl) {
87
+ const trimmed = baseUrl.trim();
88
+ if (!trimmed) {
89
+ throw new Error("NcpHttpAgentClient requires a non-empty baseUrl.");
90
+ }
91
+ return new URL(trimmed);
92
+ }
93
+ function resolveFetchImpl(fetchImpl) {
94
+ if (fetchImpl) {
95
+ return fetchImpl;
96
+ }
97
+ if (typeof globalThis.fetch === "function") {
98
+ return globalThis.fetch.bind(globalThis);
99
+ }
100
+ throw new Error("No fetch implementation found. Pass options.fetchImpl explicitly.");
101
+ }
102
+ function normalizeBasePath(basePath) {
103
+ const raw = (basePath ?? DEFAULT_BASE_PATH).trim();
104
+ if (!raw) {
105
+ return DEFAULT_BASE_PATH;
106
+ }
107
+ const withSlash = raw.startsWith("/") ? raw : `/${raw}`;
108
+ return withSlash.endsWith("/") ? withSlash.slice(0, -1) : withSlash;
109
+ }
110
+ async function safeReadText(response) {
111
+ try {
112
+ const text = await response.text();
113
+ return text.trim();
114
+ } catch {
115
+ return "";
116
+ }
117
+ }
118
+ function toNcpError(error) {
119
+ if (isNcpHttpAgentClientError(error)) {
120
+ return error.ncpError;
121
+ }
122
+ if (isNcpError(error)) {
123
+ return error;
124
+ }
125
+ const message = error instanceof Error ? error.message : String(error ?? "Unknown error");
126
+ return {
127
+ code: normalizeErrorCode(void 0),
128
+ message,
129
+ ...error instanceof Error && error.stack ? { details: { stack: error.stack } } : {}
130
+ };
131
+ }
132
+ function ncpErrorToError(error, options = {}) {
133
+ return new NcpHttpAgentClientError(error, options.alreadyPublished ?? false);
134
+ }
135
+ function isNcpError(value) {
136
+ return isRecord(value) && typeof value.code === "string" && typeof value.message === "string";
137
+ }
138
+ function isRecord(value) {
139
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
140
+ }
141
+ function isNcpHttpAgentClientError(error) {
142
+ return error instanceof NcpHttpAgentClientError;
143
+ }
144
+ var ERROR_CODE_MAP = {
145
+ "config-error": "config-error",
146
+ "auth-error": "auth-error",
147
+ "runtime-error": "runtime-error",
148
+ "timeout-error": "timeout-error",
149
+ "abort-error": "abort-error"
150
+ };
151
+ function normalizeErrorCode(code) {
152
+ if (!code) {
153
+ return "runtime-error";
154
+ }
155
+ const mapped = ERROR_CODE_MAP[code];
156
+ if (mapped) {
157
+ return mapped;
158
+ }
159
+ const lowered = code.toLowerCase();
160
+ if (lowered.includes("timeout")) return "timeout-error";
161
+ if (lowered.includes("abort") || lowered.includes("cancel")) return "abort-error";
162
+ if (lowered.includes("auth")) return "auth-error";
163
+ if (lowered.includes("config")) return "config-error";
164
+ return "runtime-error";
165
+ }
166
+
167
+ // src/parsers.ts
168
+ function parseNcpEvent(rawData) {
169
+ const parsed = parseJsonRecord(rawData);
170
+ if (!parsed) {
171
+ return null;
172
+ }
173
+ if (typeof parsed.type !== "string" || !parsed.type.trim()) {
174
+ return null;
175
+ }
176
+ return parsed;
177
+ }
178
+ function parseNcpError(rawData) {
179
+ const parsed = parseJsonRecord(rawData);
180
+ if (!parsed) {
181
+ return {
182
+ code: "runtime-error",
183
+ message: rawData || "Unknown stream error."
184
+ };
185
+ }
186
+ const inputCode = typeof parsed.code === "string" ? parsed.code : void 0;
187
+ const normalizedCode = normalizeErrorCode(inputCode);
188
+ const details = isRecord(parsed.details) ? parsed.details : {};
189
+ if (inputCode && inputCode !== normalizedCode) {
190
+ details.originalCode = inputCode;
191
+ }
192
+ return {
193
+ code: normalizedCode,
194
+ message: typeof parsed.message === "string" && parsed.message ? parsed.message : "Unknown stream error.",
195
+ ...Object.keys(details).length > 0 ? { details } : {}
196
+ };
197
+ }
198
+ function parseJsonRecord(value) {
199
+ try {
200
+ const parsed = JSON.parse(value);
201
+ return isRecord(parsed) ? parsed : null;
202
+ } catch {
203
+ return null;
204
+ }
205
+ }
206
+
207
+ // src/client.ts
208
+ var SUPPORTED_PART_TYPES = [
209
+ "text",
210
+ "file",
211
+ "source",
212
+ "step-start",
213
+ "reasoning",
214
+ "tool-invocation",
215
+ "card",
216
+ "rich-text",
217
+ "action",
218
+ "extension"
219
+ ];
220
+ var NcpHttpAgentClientEndpoint = class {
221
+ manifest;
222
+ baseUrl;
223
+ basePath;
224
+ fetchImpl;
225
+ defaultHeaders;
226
+ subscribers = /* @__PURE__ */ new Set();
227
+ activeControllers = /* @__PURE__ */ new Set();
228
+ started = false;
229
+ constructor(options) {
230
+ this.baseUrl = toBaseUrl(options.baseUrl);
231
+ this.basePath = normalizeBasePath(options.basePath);
232
+ this.fetchImpl = resolveFetchImpl(options.fetchImpl);
233
+ this.defaultHeaders = options.headers ?? {};
234
+ this.manifest = {
235
+ endpointKind: "custom",
236
+ endpointId: options.endpointId?.trim() || DEFAULT_ENDPOINT_ID,
237
+ version: "0.1.0",
238
+ supportsStreaming: true,
239
+ supportsAbort: true,
240
+ supportsProactiveMessages: false,
241
+ supportsSessionResume: true,
242
+ supportedPartTypes: SUPPORTED_PART_TYPES,
243
+ expectedLatency: "seconds",
244
+ metadata: { transport: "http+sse", scope: "agent" }
245
+ };
246
+ }
247
+ async start() {
248
+ if (this.started) {
249
+ return;
250
+ }
251
+ this.started = true;
252
+ this.publish({ type: "endpoint.ready" });
253
+ }
254
+ async stop() {
255
+ if (!this.started) {
256
+ return;
257
+ }
258
+ this.started = false;
259
+ for (const controller of this.activeControllers) {
260
+ controller.abort();
261
+ }
262
+ this.activeControllers.clear();
263
+ }
264
+ async emit(event) {
265
+ switch (event.type) {
266
+ case "message.request":
267
+ await this.send(event.payload);
268
+ return;
269
+ case "message.resume-request":
270
+ await this.resume(event.payload);
271
+ return;
272
+ case "message.abort":
273
+ await this.abort(event.payload);
274
+ return;
275
+ default:
276
+ this.publish(event);
277
+ return;
278
+ }
279
+ }
280
+ subscribe(listener) {
281
+ this.subscribers.add(listener);
282
+ return () => {
283
+ this.subscribers.delete(listener);
284
+ };
285
+ }
286
+ async send(envelope) {
287
+ await this.ensureStarted();
288
+ await this.streamRequest({
289
+ path: "/send",
290
+ method: "POST",
291
+ body: envelope
292
+ });
293
+ }
294
+ async resume(payload) {
295
+ await this.ensureStarted();
296
+ const query = new URLSearchParams({
297
+ sessionId: payload.sessionId,
298
+ remoteRunId: payload.remoteRunId
299
+ });
300
+ if (typeof payload.fromEventIndex === "number" && Number.isFinite(payload.fromEventIndex)) {
301
+ query.set("fromEventIndex", String(Math.max(0, Math.trunc(payload.fromEventIndex))));
302
+ }
303
+ await this.streamRequest({
304
+ path: `/reconnect?${query.toString()}`,
305
+ method: "GET"
306
+ });
307
+ }
308
+ async abort(payload = {}) {
309
+ await this.ensureStarted();
310
+ const controller = new AbortController();
311
+ this.activeControllers.add(controller);
312
+ try {
313
+ const response = await this.fetchImpl(this.resolveUrl("/abort"), {
314
+ method: "POST",
315
+ headers: {
316
+ ...this.defaultHeaders,
317
+ "content-type": "application/json",
318
+ accept: "application/json"
319
+ },
320
+ body: JSON.stringify(payload),
321
+ signal: controller.signal
322
+ });
323
+ if (!response.ok) {
324
+ throw new Error(
325
+ `Abort request failed with HTTP ${response.status}: ${await safeReadText(response)}`
326
+ );
327
+ }
328
+ } catch (error) {
329
+ if (controller.signal.aborted) {
330
+ return;
331
+ }
332
+ const ncpError = toNcpError(error);
333
+ this.publish({ type: "endpoint.error", payload: ncpError });
334
+ throw ncpErrorToError(ncpError);
335
+ } finally {
336
+ this.activeControllers.delete(controller);
337
+ }
338
+ }
339
+ async ensureStarted() {
340
+ if (!this.started) {
341
+ await this.start();
342
+ }
343
+ }
344
+ publish(event) {
345
+ for (const subscriber of this.subscribers) {
346
+ subscriber(event);
347
+ }
348
+ }
349
+ resolveUrl(path) {
350
+ return new URL(`${this.basePath}${path}`, this.baseUrl);
351
+ }
352
+ async streamRequest(options) {
353
+ const controller = new AbortController();
354
+ this.activeControllers.add(controller);
355
+ try {
356
+ const response = await this.fetchImpl(this.resolveUrl(options.path), {
357
+ method: options.method,
358
+ headers: {
359
+ ...this.defaultHeaders,
360
+ accept: "text/event-stream",
361
+ ...options.body !== void 0 ? { "content-type": "application/json" } : {}
362
+ },
363
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
364
+ signal: controller.signal
365
+ });
366
+ if (!response.ok) {
367
+ throw new Error(
368
+ `NCP stream request failed with HTTP ${response.status}: ${await safeReadText(response)}`
369
+ );
370
+ }
371
+ if (!response.body) {
372
+ throw new Error("NCP stream response has no body.");
373
+ }
374
+ for await (const frame of consumeSseStream(response.body)) {
375
+ if (controller.signal.aborted) {
376
+ return;
377
+ }
378
+ this.handleSseFrame(frame);
379
+ }
380
+ } catch (error) {
381
+ if (controller.signal.aborted) {
382
+ return;
383
+ }
384
+ if (isNcpHttpAgentClientError(error)) {
385
+ throw error;
386
+ }
387
+ const ncpError = toNcpError(error);
388
+ this.publish({ type: "endpoint.error", payload: ncpError });
389
+ throw ncpErrorToError(ncpError);
390
+ } finally {
391
+ this.activeControllers.delete(controller);
392
+ }
393
+ }
394
+ handleSseFrame(frame) {
395
+ if (frame.event === "ncp-event") {
396
+ const event = parseNcpEvent(frame.data);
397
+ if (!event) {
398
+ this.publish({
399
+ type: "endpoint.error",
400
+ payload: {
401
+ code: "runtime-error",
402
+ message: "Received malformed ncp-event frame."
403
+ }
404
+ });
405
+ return;
406
+ }
407
+ this.publish(event);
408
+ return;
409
+ }
410
+ if (frame.event === "error") {
411
+ const ncpError = parseNcpError(frame.data);
412
+ this.publish({ type: "endpoint.error", payload: ncpError });
413
+ throw ncpErrorToError(ncpError, { alreadyPublished: true });
414
+ }
415
+ }
416
+ };
417
+ export {
418
+ NcpHttpAgentClientEndpoint
419
+ };
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@nextclaw/ncp-http-agent-client",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "description": "HTTP/SSE client transport adapter for NCP agent endpoints.",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "development": "./src/index.ts",
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "dependencies": {
18
+ "@nextclaw/ncp": "0.1.0"
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^20.17.6",
22
+ "@typescript-eslint/eslint-plugin": "^7.18.0",
23
+ "@typescript-eslint/parser": "^7.18.0",
24
+ "eslint": "^8.57.1",
25
+ "eslint-config-prettier": "^9.1.0",
26
+ "prettier": "^3.3.3",
27
+ "tsup": "^8.3.5",
28
+ "typescript": "^5.6.3",
29
+ "vitest": "^2.1.2"
30
+ },
31
+ "scripts": {
32
+ "build": "tsup src/index.ts --format esm --dts --out-dir dist",
33
+ "lint": "eslint .",
34
+ "tsc": "tsc -p tsconfig.json",
35
+ "test": "vitest run"
36
+ }
37
+ }