@nextclaw/ncp-agent-runtime 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.
@@ -0,0 +1,72 @@
1
+ import { NcpContextBuilder, NcpToolRegistry, NcpAgentRunInput, NcpContextPrepareOptions, NcpLLMApiInput, NcpRoundBuffer, NcpToolCallResult, NcpStreamEncoder, OpenAIChatChunk, NcpEncodeContext, NcpEndpointEvent, NcpTool, NcpToolDefinition, NcpLLMApi, NcpLLMApiOptions, NcpAgentRuntime, NcpAgentConversationStateManager, NcpAgentRunOptions } from '@nextclaw/ncp';
2
+
3
+ declare class DefaultNcpContextBuilder implements NcpContextBuilder {
4
+ private readonly toolRegistry?;
5
+ constructor(toolRegistry?: NcpToolRegistry | undefined);
6
+ prepare: (input: NcpAgentRunInput, options?: NcpContextPrepareOptions) => NcpLLMApiInput;
7
+ }
8
+
9
+ declare class DefaultNcpRoundBuffer implements NcpRoundBuffer {
10
+ private text;
11
+ private readonly toolCalls;
12
+ private pending;
13
+ appendText: (delta: string) => void;
14
+ getText: () => string;
15
+ appendToolCall: (result: NcpToolCallResult) => void;
16
+ getToolCalls: () => ReadonlyArray<NcpToolCallResult>;
17
+ startToolCall: (toolCallId: string, toolName: string) => void;
18
+ appendToolCallArgs: (args: unknown) => void;
19
+ consumePendingToolCall: () => {
20
+ toolCallId: string;
21
+ toolName: string;
22
+ args: unknown;
23
+ } | null;
24
+ clear: () => void;
25
+ }
26
+
27
+ /**
28
+ * Converts LLM stream chunks to NCP events (text, reasoning, tool calls).
29
+ * Does not emit RunFinished; that is the runtime's responsibility after the loop completes.
30
+ */
31
+ declare class DefaultNcpStreamEncoder implements NcpStreamEncoder {
32
+ encode: (stream: AsyncIterable<OpenAIChatChunk>, context: NcpEncodeContext) => AsyncGenerator<NcpEndpointEvent>;
33
+ }
34
+
35
+ declare class DefaultNcpToolRegistry implements NcpToolRegistry {
36
+ private readonly tools;
37
+ constructor(tools?: ReadonlyArray<NcpTool>);
38
+ register: (tool: NcpTool) => void;
39
+ listTools: () => ReadonlyArray<NcpTool>;
40
+ getTool: (name: string) => NcpTool | undefined;
41
+ getToolDefinitions: () => ReadonlyArray<NcpToolDefinition>;
42
+ execute: (_toolCallId: string, toolName: string, args: unknown) => Promise<unknown>;
43
+ }
44
+
45
+ declare class EchoNcpLLMApi implements NcpLLMApi {
46
+ generate: (input: NcpLLMApiInput, options?: NcpLLMApiOptions) => AsyncGenerator<OpenAIChatChunk>;
47
+ }
48
+
49
+ type DefaultNcpAgentRuntimeConfig = {
50
+ contextBuilder: NcpContextBuilder;
51
+ llmApi: NcpLLMApi;
52
+ toolRegistry: NcpToolRegistry;
53
+ stateManager: NcpAgentConversationStateManager;
54
+ streamEncoder?: NcpStreamEncoder;
55
+ };
56
+ declare class DefaultNcpAgentRuntime implements NcpAgentRuntime {
57
+ private readonly contextBuilder;
58
+ private readonly llmApi;
59
+ private readonly toolRegistry;
60
+ private readonly stateManager;
61
+ private readonly streamEncoder;
62
+ constructor(config: DefaultNcpAgentRuntimeConfig);
63
+ run: (this: DefaultNcpAgentRuntime, input: NcpAgentRunInput, options?: NcpAgentRunOptions) => AsyncGenerator<NcpEndpointEvent>;
64
+ /**
65
+ * Agent loop: LLM stream → encoder events → tool execution (if any) → next round or finish.
66
+ * RunFinished is emitted only when the entire loop completes (no more tool calls).
67
+ * The stream encoder does not emit RunFinished; it only converts chunks to NCP events.
68
+ */
69
+ private runLoop;
70
+ }
71
+
72
+ export { DefaultNcpAgentRuntime, type DefaultNcpAgentRuntimeConfig, DefaultNcpContextBuilder, DefaultNcpRoundBuffer, DefaultNcpStreamEncoder, DefaultNcpToolRegistry, EchoNcpLLMApi };
package/dist/index.js ADDED
@@ -0,0 +1,454 @@
1
+ // src/context-builder.ts
2
+ function messageToOpenAI(msg) {
3
+ const role = msg.role;
4
+ const parts = msg.parts ?? [];
5
+ if (role === "user" || role === "system") {
6
+ const text = parts.filter((p) => p.type === "text").map((p) => p.text).join("");
7
+ return [{ role, content: text }];
8
+ }
9
+ if (role === "assistant") {
10
+ const texts = [];
11
+ const toolInvocations = [];
12
+ for (const p of parts) {
13
+ if (p.type === "text") {
14
+ texts.push(p.text);
15
+ }
16
+ if (p.type === "tool-invocation" && p.state === "result" && p.result !== void 0) {
17
+ toolInvocations.push({
18
+ toolCallId: p.toolCallId ?? "",
19
+ toolName: p.toolName,
20
+ args: p.args ?? {},
21
+ result: p.result
22
+ });
23
+ }
24
+ }
25
+ const text = texts.join("");
26
+ const out = [];
27
+ if (toolInvocations.length > 0) {
28
+ out.push({
29
+ role: "assistant",
30
+ content: text || null,
31
+ tool_calls: toolInvocations.map((t) => ({
32
+ id: t.toolCallId,
33
+ type: "function",
34
+ function: {
35
+ name: t.toolName,
36
+ arguments: typeof t.args === "string" ? t.args : JSON.stringify(t.args ?? {})
37
+ }
38
+ }))
39
+ });
40
+ for (const t of toolInvocations) {
41
+ out.push({
42
+ role: "tool",
43
+ content: typeof t.result === "string" ? t.result : JSON.stringify(t.result),
44
+ tool_call_id: t.toolCallId
45
+ });
46
+ }
47
+ } else {
48
+ out.push({ role: "assistant", content: text });
49
+ }
50
+ return out;
51
+ }
52
+ return [];
53
+ }
54
+ var DefaultNcpContextBuilder = class {
55
+ constructor(toolRegistry) {
56
+ this.toolRegistry = toolRegistry;
57
+ }
58
+ prepare = (input, options) => {
59
+ const maxMessages = options?.maxMessages ?? 50;
60
+ const sessionMessages = options?.sessionMessages ?? [];
61
+ const systemPrompt = options?.systemPrompt;
62
+ const messages = [];
63
+ if (systemPrompt) {
64
+ messages.push({ role: "system", content: systemPrompt });
65
+ }
66
+ for (const msg of sessionMessages.slice(-maxMessages)) {
67
+ messages.push(...messageToOpenAI(msg));
68
+ }
69
+ for (const msg of input.messages) {
70
+ messages.push(...messageToOpenAI(msg));
71
+ }
72
+ const tools = this.toolRegistry ? this.toolRegistry.getToolDefinitions().map((d) => ({
73
+ type: "function",
74
+ function: {
75
+ name: d.name,
76
+ description: d.description,
77
+ parameters: d.parameters
78
+ }
79
+ })) : void 0;
80
+ return {
81
+ messages,
82
+ tools: tools && tools.length > 0 ? tools : void 0
83
+ };
84
+ };
85
+ };
86
+
87
+ // src/round-buffer.ts
88
+ var DefaultNcpRoundBuffer = class {
89
+ text = "";
90
+ toolCalls = [];
91
+ pending = null;
92
+ appendText = (delta) => {
93
+ this.text += delta;
94
+ };
95
+ getText = () => {
96
+ return this.text;
97
+ };
98
+ appendToolCall = (result) => {
99
+ this.toolCalls.push(result);
100
+ };
101
+ getToolCalls = () => {
102
+ return [...this.toolCalls];
103
+ };
104
+ startToolCall = (toolCallId, toolName) => {
105
+ this.pending = { toolCallId, toolName, args: void 0 };
106
+ };
107
+ appendToolCallArgs = (args) => {
108
+ if (this.pending) this.pending.args = args;
109
+ };
110
+ consumePendingToolCall = () => {
111
+ const p = this.pending;
112
+ this.pending = null;
113
+ return p;
114
+ };
115
+ clear = () => {
116
+ this.text = "";
117
+ this.toolCalls.length = 0;
118
+ this.pending = null;
119
+ };
120
+ };
121
+
122
+ // src/stream-encoder.ts
123
+ import {
124
+ NcpEventType as NcpEventType2
125
+ } from "@nextclaw/ncp";
126
+
127
+ // src/stream-encoder.utils.ts
128
+ import { NcpEventType } from "@nextclaw/ncp";
129
+ function getToolCallIndex(toolDelta, fallback) {
130
+ const idx = toolDelta.index;
131
+ return typeof idx === "number" && Number.isFinite(idx) ? idx : fallback;
132
+ }
133
+ function applyToolDelta(current, toolDelta) {
134
+ const next = { ...current, argumentsText: current.argumentsText };
135
+ if (typeof toolDelta.id === "string" && toolDelta.id.trim()) {
136
+ next.id = toolDelta.id;
137
+ }
138
+ const fn = toolDelta.function;
139
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
140
+ if (typeof fn.name === "string" && fn.name.trim()) {
141
+ next.name = fn.name.trim();
142
+ }
143
+ if (typeof fn.arguments === "string" && fn.arguments.length > 0) {
144
+ next.argumentsText += fn.arguments;
145
+ }
146
+ }
147
+ return next;
148
+ }
149
+ function* emitTextDeltas(delta, ctx, state) {
150
+ const content = delta.content;
151
+ if (typeof content !== "string" || content.length === 0) return state;
152
+ if (!state.textStarted) {
153
+ yield { type: NcpEventType.MessageTextStart, payload: ctx };
154
+ yield { type: NcpEventType.MessageTextDelta, payload: { ...ctx, delta: content } };
155
+ return { textStarted: true };
156
+ }
157
+ yield { type: NcpEventType.MessageTextDelta, payload: { ...ctx, delta: content } };
158
+ return state;
159
+ }
160
+ function* emitReasoningDelta(delta, ctx) {
161
+ const reasoning = delta.reasoning_content ?? delta.reasoning;
162
+ if (typeof reasoning !== "string" || !reasoning) return;
163
+ yield { type: NcpEventType.MessageReasoningDelta, payload: { ...ctx, delta: reasoning } };
164
+ }
165
+ function* emitToolCallDeltas(delta, buffers, sessionId) {
166
+ const toolDeltas = delta.tool_calls;
167
+ if (!Array.isArray(toolDeltas)) return;
168
+ for (const toolDelta of toolDeltas) {
169
+ const index = getToolCallIndex(toolDelta, buffers.size);
170
+ const prev = buffers.get(index) ?? { argumentsText: "" };
171
+ const current = applyToolDelta(prev, toolDelta);
172
+ if (current.id && current.name && !current.emittedStart) {
173
+ yield {
174
+ type: NcpEventType.MessageToolCallStart,
175
+ payload: { sessionId, toolCallId: current.id, toolName: current.name }
176
+ };
177
+ buffers.set(index, { ...current, emittedStart: true });
178
+ } else {
179
+ buffers.set(index, current);
180
+ }
181
+ }
182
+ }
183
+ function* flushToolCalls(buffers, sessionId) {
184
+ const ordered = Array.from(buffers.entries()).sort(([a], [b]) => a - b);
185
+ for (const [, buf] of ordered) {
186
+ if (!buf.id || !buf.name) continue;
187
+ yield {
188
+ type: NcpEventType.MessageToolCallArgs,
189
+ payload: { sessionId, toolCallId: buf.id, args: buf.argumentsText }
190
+ };
191
+ yield {
192
+ type: NcpEventType.MessageToolCallEnd,
193
+ payload: { sessionId, toolCallId: buf.id }
194
+ };
195
+ }
196
+ }
197
+
198
+ // src/stream-encoder.ts
199
+ var DefaultNcpStreamEncoder = class {
200
+ encode = async function* (stream, context) {
201
+ const { sessionId, messageId } = context;
202
+ let state = { textStarted: false };
203
+ const toolCallBuffers = /* @__PURE__ */ new Map();
204
+ for await (const chunk of stream) {
205
+ const choice = chunk.choices?.[0];
206
+ if (!choice) continue;
207
+ const delta = choice.delta;
208
+ if (delta) {
209
+ const nextState = yield* emitTextDeltas(delta, { sessionId, messageId }, state);
210
+ state = nextState;
211
+ yield* emitReasoningDelta(delta, { sessionId, messageId });
212
+ yield* emitToolCallDeltas(delta, toolCallBuffers, sessionId);
213
+ }
214
+ const finishReason = choice.finish_reason;
215
+ if (typeof finishReason === "string" && finishReason.trim().length > 0) {
216
+ yield* flushToolCalls(toolCallBuffers, sessionId);
217
+ if (state.textStarted) {
218
+ yield { type: NcpEventType2.MessageTextEnd, payload: { sessionId, messageId } };
219
+ }
220
+ }
221
+ }
222
+ };
223
+ };
224
+
225
+ // src/tool-registry.ts
226
+ var DefaultNcpToolRegistry = class {
227
+ tools = /* @__PURE__ */ new Map();
228
+ constructor(tools = []) {
229
+ for (const t of tools) {
230
+ this.tools.set(t.name, t);
231
+ }
232
+ }
233
+ register = (tool) => {
234
+ this.tools.set(tool.name, tool);
235
+ };
236
+ listTools = () => {
237
+ return [...this.tools.values()];
238
+ };
239
+ getTool = (name) => {
240
+ return this.tools.get(name);
241
+ };
242
+ getToolDefinitions = () => {
243
+ return this.listTools().map((t) => ({
244
+ name: t.name,
245
+ description: t.description,
246
+ parameters: t.parameters
247
+ }));
248
+ };
249
+ execute = async (_toolCallId, toolName, args) => {
250
+ const tool = this.tools.get(toolName);
251
+ return tool ? await tool.execute(args) : void 0;
252
+ };
253
+ };
254
+
255
+ // src/llm-api-echo.ts
256
+ function getLastUserContent(messages) {
257
+ for (let i = messages.length - 1; i >= 0; i--) {
258
+ const m = messages[i];
259
+ if (m.role !== "user") continue;
260
+ if (typeof m.content === "string") return m.content;
261
+ if (Array.isArray(m.content)) {
262
+ return m.content.map((p) => p.type === "text" ? p.text : "").join("");
263
+ }
264
+ }
265
+ return "";
266
+ }
267
+ var EchoNcpLLMApi = class {
268
+ generate = async function* (input, options) {
269
+ const text = getLastUserContent(input.messages);
270
+ const signal = options?.signal;
271
+ for (const char of text) {
272
+ if (signal?.aborted) break;
273
+ yield {
274
+ choices: [{ index: 0, delta: { content: char } }]
275
+ };
276
+ }
277
+ yield {
278
+ choices: [
279
+ {
280
+ index: 0,
281
+ delta: {},
282
+ finish_reason: "stop"
283
+ }
284
+ ],
285
+ usage: { prompt_tokens: 0, completion_tokens: text.length, total_tokens: text.length }
286
+ };
287
+ };
288
+ };
289
+
290
+ // src/runtime.ts
291
+ import {
292
+ NcpEventType as NcpEventType3
293
+ } from "@nextclaw/ncp";
294
+
295
+ // src/utils.ts
296
+ function genId() {
297
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 11)}`;
298
+ }
299
+ function parseToolArgs(args) {
300
+ if (typeof args === "string") {
301
+ try {
302
+ return JSON.parse(args);
303
+ } catch {
304
+ return args;
305
+ }
306
+ }
307
+ return args;
308
+ }
309
+ function appendToolRoundToInput(input, text, toolResults) {
310
+ const assistantMsg = {
311
+ role: "assistant",
312
+ content: text || null,
313
+ tool_calls: toolResults.map((tr) => ({
314
+ id: tr.toolCallId,
315
+ type: "function",
316
+ function: {
317
+ name: tr.toolName,
318
+ arguments: typeof tr.args === "string" ? tr.args : JSON.stringify(tr.args ?? {})
319
+ }
320
+ }))
321
+ };
322
+ const toolMsgs = toolResults.map((tr) => ({
323
+ role: "tool",
324
+ content: typeof tr.result === "string" ? tr.result : JSON.stringify(tr.result ?? {}),
325
+ tool_call_id: tr.toolCallId
326
+ }));
327
+ return {
328
+ ...input,
329
+ messages: [...input.messages, assistantMsg, ...toolMsgs]
330
+ };
331
+ }
332
+
333
+ // src/runtime.ts
334
+ var DefaultNcpAgentRuntime = class {
335
+ contextBuilder;
336
+ llmApi;
337
+ toolRegistry;
338
+ stateManager;
339
+ streamEncoder;
340
+ constructor(config) {
341
+ this.contextBuilder = config.contextBuilder;
342
+ this.llmApi = config.llmApi;
343
+ this.toolRegistry = config.toolRegistry;
344
+ this.stateManager = config.stateManager;
345
+ this.streamEncoder = config.streamEncoder ?? new DefaultNcpStreamEncoder();
346
+ }
347
+ run = async function* (input, options) {
348
+ const ctx = {
349
+ messageId: genId(),
350
+ runId: genId(),
351
+ sessionId: input.sessionId,
352
+ correlationId: input.correlationId
353
+ };
354
+ const sessionMessages = this.stateManager.getSnapshot().messages;
355
+ const modelInput = this.contextBuilder.prepare(input, {
356
+ sessionMessages
357
+ });
358
+ for (const msg of input.messages) {
359
+ const messageSent = {
360
+ type: NcpEventType3.MessageSent,
361
+ payload: { sessionId: input.sessionId, message: msg }
362
+ };
363
+ await this.stateManager.dispatch(messageSent);
364
+ }
365
+ const runStarted = {
366
+ type: NcpEventType3.RunStarted,
367
+ payload: { sessionId: ctx.sessionId, messageId: ctx.messageId, runId: ctx.runId }
368
+ };
369
+ await this.stateManager.dispatch(runStarted);
370
+ yield runStarted;
371
+ for await (const event of this.runLoop(modelInput, ctx, options)) {
372
+ await this.stateManager.dispatch(event);
373
+ yield event;
374
+ }
375
+ };
376
+ /**
377
+ * Agent loop: LLM stream → encoder events → tool execution (if any) → next round or finish.
378
+ * RunFinished is emitted only when the entire loop completes (no more tool calls).
379
+ * The stream encoder does not emit RunFinished; it only converts chunks to NCP events.
380
+ */
381
+ async *runLoop(llmInput, ctx, options) {
382
+ const roundBuffer = new DefaultNcpRoundBuffer();
383
+ let currentInput = llmInput;
384
+ let done = false;
385
+ while (!done && !options?.signal?.aborted) {
386
+ roundBuffer.clear();
387
+ const stream = this.llmApi.generate(currentInput, { signal: options?.signal });
388
+ for await (const event of this.streamEncoder.encode(stream, ctx)) {
389
+ yield event;
390
+ switch (event.type) {
391
+ case NcpEventType3.MessageToolCallStart:
392
+ roundBuffer.startToolCall(event.payload.toolCallId, event.payload.toolName);
393
+ break;
394
+ case NcpEventType3.MessageToolCallArgs:
395
+ roundBuffer.appendToolCallArgs(event.payload.args);
396
+ break;
397
+ case NcpEventType3.MessageToolCallEnd: {
398
+ const pending = roundBuffer.consumePendingToolCall();
399
+ if (pending) {
400
+ const parsedArgs = parseToolArgs(pending.args);
401
+ const result = await this.toolRegistry.execute(
402
+ pending.toolCallId,
403
+ pending.toolName,
404
+ parsedArgs
405
+ );
406
+ roundBuffer.appendToolCall({
407
+ toolCallId: pending.toolCallId,
408
+ toolName: pending.toolName,
409
+ args: parsedArgs,
410
+ result
411
+ });
412
+ yield {
413
+ type: NcpEventType3.MessageToolCallResult,
414
+ payload: {
415
+ sessionId: ctx.sessionId,
416
+ toolCallId: pending.toolCallId,
417
+ content: result
418
+ }
419
+ };
420
+ }
421
+ break;
422
+ }
423
+ case NcpEventType3.MessageTextDelta:
424
+ roundBuffer.appendText(event.payload.delta);
425
+ break;
426
+ default:
427
+ break;
428
+ }
429
+ }
430
+ const toolResults = roundBuffer.getToolCalls();
431
+ if (toolResults.length === 0) {
432
+ yield {
433
+ type: NcpEventType3.RunFinished,
434
+ payload: { sessionId: ctx.sessionId, messageId: ctx.messageId, runId: ctx.runId }
435
+ };
436
+ done = true;
437
+ break;
438
+ }
439
+ currentInput = appendToolRoundToInput(
440
+ currentInput,
441
+ roundBuffer.getText(),
442
+ toolResults
443
+ );
444
+ }
445
+ }
446
+ };
447
+ export {
448
+ DefaultNcpAgentRuntime,
449
+ DefaultNcpContextBuilder,
450
+ DefaultNcpRoundBuffer,
451
+ DefaultNcpStreamEncoder,
452
+ DefaultNcpToolRegistry,
453
+ EchoNcpLLMApi
454
+ };
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@nextclaw/ncp-agent-runtime",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "description": "Default agent runtime implementation built on NCP interfaces.",
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.1"
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^20.17.6",
22
+ "prettier": "^3.3.3",
23
+ "tsup": "^8.3.5",
24
+ "typescript": "^5.6.3"
25
+ },
26
+ "scripts": {
27
+ "build": "tsup src/index.ts --format esm --dts --out-dir dist",
28
+ "lint": "eslint .",
29
+ "tsc": "tsc -p tsconfig.json"
30
+ }
31
+ }