@nextclaw/nextclaw-ncp-runtime-codex-sdk 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,9 @@
1
+ # @nextclaw/nextclaw-ncp-runtime-codex-sdk
2
+
3
+ Optional NCP runtime adapter backed by OpenAI official `@openai/codex-sdk`.
4
+
5
+ ## Build
6
+
7
+ ```bash
8
+ pnpm -C packages/extensions/nextclaw-ncp-runtime-codex-sdk build
9
+ ```
@@ -0,0 +1,11 @@
1
+ async function loadCodexConstructor() {
2
+ const mod = await import("@openai/codex-sdk");
3
+ if (!mod || typeof mod.Codex !== "function") {
4
+ throw new Error("[codex-ncp-runtime] failed to load Codex constructor from @openai/codex-sdk");
5
+ }
6
+ return mod.Codex;
7
+ }
8
+
9
+ module.exports = {
10
+ loadCodexConstructor,
11
+ };
@@ -0,0 +1,23 @@
1
+ import { ThreadEvent } from '@openai/codex-sdk';
2
+ import { NcpEndpointEvent } from '@nextclaw/ncp';
3
+
4
+ type ItemTextSnapshot = {
5
+ text: string;
6
+ started: boolean;
7
+ };
8
+ type ToolSnapshot = {
9
+ started: boolean;
10
+ argsEmitted: boolean;
11
+ ended: boolean;
12
+ };
13
+ declare function mapCodexItemEvent(params: {
14
+ sessionId: string;
15
+ messageId: string;
16
+ event: Extract<ThreadEvent, {
17
+ type: "item.started" | "item.updated" | "item.completed";
18
+ }>;
19
+ itemTextById: Map<string, ItemTextSnapshot>;
20
+ toolStateById: Map<string, ToolSnapshot>;
21
+ }): AsyncGenerator<NcpEndpointEvent>;
22
+
23
+ export { type ItemTextSnapshot, type ToolSnapshot, mapCodexItemEvent };
@@ -0,0 +1,232 @@
1
+ import { NcpEventType } from "@nextclaw/ncp";
2
+ function buildToolDescriptor(item) {
3
+ switch (item.type) {
4
+ case "mcp_tool_call":
5
+ return {
6
+ toolName: item.server ? `mcp:${item.server}.${item.tool}` : `mcp:${item.tool}`,
7
+ args: item.arguments
8
+ };
9
+ case "command_execution":
10
+ return {
11
+ toolName: "command_execution",
12
+ args: {
13
+ command: item.command
14
+ }
15
+ };
16
+ case "web_search":
17
+ return {
18
+ toolName: "web_search",
19
+ args: {
20
+ query: item.query
21
+ }
22
+ };
23
+ case "file_change":
24
+ return {
25
+ toolName: "file_change",
26
+ args: {
27
+ changes: item.changes
28
+ }
29
+ };
30
+ case "todo_list":
31
+ return {
32
+ toolName: "todo_list",
33
+ args: {
34
+ items: item.items
35
+ }
36
+ };
37
+ case "error":
38
+ return {
39
+ toolName: "error",
40
+ args: {
41
+ message: item.message
42
+ }
43
+ };
44
+ }
45
+ }
46
+ function buildToolResult(item) {
47
+ switch (item.type) {
48
+ case "mcp_tool_call":
49
+ return item.status === "failed" ? { ok: false, error: item.error ?? { message: "MCP tool call failed." } } : {
50
+ ok: item.status === "completed",
51
+ status: item.status,
52
+ result: item.result ?? null
53
+ };
54
+ case "command_execution":
55
+ return {
56
+ status: item.status,
57
+ command: item.command,
58
+ aggregated_output: item.aggregated_output,
59
+ ...typeof item.exit_code === "number" ? { exit_code: item.exit_code } : {}
60
+ };
61
+ case "web_search":
62
+ return {
63
+ status: "completed",
64
+ query: item.query
65
+ };
66
+ case "file_change":
67
+ return {
68
+ status: item.status,
69
+ changes: item.changes
70
+ };
71
+ case "todo_list":
72
+ return {
73
+ status: "completed",
74
+ items: item.items
75
+ };
76
+ case "error":
77
+ return {
78
+ ok: false,
79
+ error: {
80
+ message: item.message
81
+ }
82
+ };
83
+ }
84
+ }
85
+ function stringifyToolArgs(args) {
86
+ try {
87
+ return JSON.stringify(args ?? {});
88
+ } catch {
89
+ return JSON.stringify({
90
+ __serialization_error__: "tool arguments are not JSON serializable"
91
+ });
92
+ }
93
+ }
94
+ function isToolLikeItem(item) {
95
+ return item.type === "mcp_tool_call" || item.type === "command_execution" || item.type === "web_search" || item.type === "file_change" || item.type === "todo_list" || item.type === "error";
96
+ }
97
+ async function* mapCodexItemEvent(params) {
98
+ const { sessionId, messageId, event, itemTextById, toolStateById } = params;
99
+ const { item } = event;
100
+ if (item.type === "agent_message") {
101
+ const currentText = item.text ?? "";
102
+ const previous2 = itemTextById.get(item.id) ?? { text: "", started: false };
103
+ if (!previous2.started) {
104
+ yield {
105
+ type: NcpEventType.MessageTextStart,
106
+ payload: {
107
+ sessionId,
108
+ messageId
109
+ }
110
+ };
111
+ }
112
+ if (currentText.length > previous2.text.length) {
113
+ const delta = currentText.slice(previous2.text.length);
114
+ yield {
115
+ type: NcpEventType.MessageTextDelta,
116
+ payload: {
117
+ sessionId,
118
+ messageId,
119
+ delta
120
+ }
121
+ };
122
+ }
123
+ itemTextById.set(item.id, {
124
+ text: currentText,
125
+ started: true
126
+ });
127
+ if (event.type === "item.completed") {
128
+ yield {
129
+ type: NcpEventType.MessageTextEnd,
130
+ payload: {
131
+ sessionId,
132
+ messageId
133
+ }
134
+ };
135
+ }
136
+ return;
137
+ }
138
+ if (item.type === "reasoning") {
139
+ const currentText = item.text ?? "";
140
+ const previous2 = itemTextById.get(item.id) ?? { text: "", started: false };
141
+ if (!previous2.started) {
142
+ yield {
143
+ type: NcpEventType.MessageReasoningStart,
144
+ payload: {
145
+ sessionId,
146
+ messageId
147
+ }
148
+ };
149
+ }
150
+ if (currentText.length > previous2.text.length) {
151
+ const delta = currentText.slice(previous2.text.length);
152
+ yield {
153
+ type: NcpEventType.MessageReasoningDelta,
154
+ payload: {
155
+ sessionId,
156
+ messageId,
157
+ delta
158
+ }
159
+ };
160
+ }
161
+ itemTextById.set(item.id, {
162
+ text: currentText,
163
+ started: true
164
+ });
165
+ if (event.type === "item.completed") {
166
+ yield {
167
+ type: NcpEventType.MessageReasoningEnd,
168
+ payload: {
169
+ sessionId,
170
+ messageId
171
+ }
172
+ };
173
+ }
174
+ return;
175
+ }
176
+ if (!isToolLikeItem(item)) {
177
+ return;
178
+ }
179
+ const previous = toolStateById.get(item.id) ?? {
180
+ started: false,
181
+ argsEmitted: false,
182
+ ended: false
183
+ };
184
+ const descriptor = buildToolDescriptor(item);
185
+ if (!previous.started) {
186
+ yield {
187
+ type: NcpEventType.MessageToolCallStart,
188
+ payload: {
189
+ sessionId,
190
+ messageId,
191
+ toolCallId: item.id,
192
+ toolName: descriptor.toolName
193
+ }
194
+ };
195
+ previous.started = true;
196
+ }
197
+ if (!previous.argsEmitted) {
198
+ yield {
199
+ type: NcpEventType.MessageToolCallArgs,
200
+ payload: {
201
+ sessionId,
202
+ toolCallId: item.id,
203
+ args: stringifyToolArgs(descriptor.args)
204
+ }
205
+ };
206
+ previous.argsEmitted = true;
207
+ }
208
+ if (!previous.ended) {
209
+ yield {
210
+ type: NcpEventType.MessageToolCallEnd,
211
+ payload: {
212
+ sessionId,
213
+ toolCallId: item.id
214
+ }
215
+ };
216
+ previous.ended = true;
217
+ }
218
+ if (event.type === "item.updated" || event.type === "item.completed") {
219
+ yield {
220
+ type: NcpEventType.MessageToolCallResult,
221
+ payload: {
222
+ sessionId,
223
+ toolCallId: item.id,
224
+ content: buildToolResult(item)
225
+ }
226
+ };
227
+ }
228
+ toolStateById.set(item.id, previous);
229
+ }
230
+ export {
231
+ mapCodexItemEvent
232
+ };
@@ -0,0 +1,32 @@
1
+ import { CodexOptions, ThreadOptions } from '@openai/codex-sdk';
2
+ import { NcpAgentRuntime, NcpAgentRunInput, NcpAgentRunOptions, NcpEndpointEvent } from '@nextclaw/ncp';
3
+
4
+ type CodexSdkNcpAgentRuntimeConfig = {
5
+ sessionId: string;
6
+ apiKey: string;
7
+ apiBase?: string;
8
+ model?: string;
9
+ threadId?: string | null;
10
+ codexPathOverride?: string;
11
+ env?: Record<string, string>;
12
+ cliConfig?: CodexOptions["config"];
13
+ threadOptions?: ThreadOptions;
14
+ sessionMetadata?: Record<string, unknown>;
15
+ setSessionMetadata?: (nextMetadata: Record<string, unknown>) => void;
16
+ inputBuilder?: (input: NcpAgentRunInput) => Promise<string> | string;
17
+ };
18
+ declare class CodexSdkNcpAgentRuntime implements NcpAgentRuntime {
19
+ private readonly config;
20
+ private codexPromise;
21
+ private thread;
22
+ private threadId;
23
+ private readonly sessionMetadata;
24
+ constructor(config: CodexSdkNcpAgentRuntimeConfig);
25
+ run(input: NcpAgentRunInput, options?: NcpAgentRunOptions): AsyncGenerator<NcpEndpointEvent>;
26
+ private getCodex;
27
+ private resolveThread;
28
+ private buildTurnInput;
29
+ private updateThreadId;
30
+ }
31
+
32
+ export { CodexSdkNcpAgentRuntime, type CodexSdkNcpAgentRuntimeConfig };
package/dist/index.js ADDED
@@ -0,0 +1,227 @@
1
+ import { createRequire } from "node:module";
2
+ import { NcpEventType } from "@nextclaw/ncp";
3
+ import {
4
+ mapCodexItemEvent
5
+ } from "./codex-sdk-ncp-event-mapper.js";
6
+ const require2 = createRequire(import.meta.url);
7
+ const codexLoader = require2("../codex-sdk-loader.cjs");
8
+ function createId(prefix) {
9
+ return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
10
+ }
11
+ function readUserText(input) {
12
+ for (let index = input.messages.length - 1; index >= 0; index -= 1) {
13
+ const message = input.messages[index];
14
+ if (message?.role !== "user") {
15
+ continue;
16
+ }
17
+ const text = message.parts.filter((part) => part.type === "text").map((part) => part.text).join("").trim();
18
+ if (text) {
19
+ return text;
20
+ }
21
+ }
22
+ return "";
23
+ }
24
+ function toAbortError(reason) {
25
+ if (reason instanceof Error) {
26
+ return reason;
27
+ }
28
+ const message = typeof reason === "string" && reason.trim() ? reason.trim() : "operation aborted";
29
+ const error = new Error(message);
30
+ error.name = "AbortError";
31
+ return error;
32
+ }
33
+ class CodexSdkNcpAgentRuntime {
34
+ constructor(config) {
35
+ this.config = config;
36
+ this.threadId = config.threadId?.trim() || null;
37
+ this.sessionMetadata = {
38
+ ...config.sessionMetadata ? structuredClone(config.sessionMetadata) : {}
39
+ };
40
+ }
41
+ codexPromise = null;
42
+ thread = null;
43
+ threadId;
44
+ sessionMetadata;
45
+ async *run(input, options) {
46
+ const messageId = createId("codex-message");
47
+ const runId = createId("codex-run");
48
+ const itemTextById = /* @__PURE__ */ new Map();
49
+ const toolStateById = /* @__PURE__ */ new Map();
50
+ let finished = false;
51
+ yield {
52
+ type: NcpEventType.RunStarted,
53
+ payload: {
54
+ sessionId: input.sessionId,
55
+ messageId,
56
+ runId
57
+ }
58
+ };
59
+ yield {
60
+ type: NcpEventType.RunMetadata,
61
+ payload: {
62
+ sessionId: input.sessionId,
63
+ messageId,
64
+ runId,
65
+ metadata: {
66
+ kind: "ready",
67
+ runId,
68
+ sessionId: input.sessionId,
69
+ supportsAbort: true
70
+ }
71
+ }
72
+ };
73
+ const thread = await this.resolveThread();
74
+ const turnInput = await this.buildTurnInput(input);
75
+ const streamed = await thread.runStreamed(turnInput, {
76
+ ...options?.signal ? { signal: options.signal } : {}
77
+ });
78
+ try {
79
+ for await (const event of streamed.events) {
80
+ if (options?.signal?.aborted) {
81
+ throw toAbortError(options.signal.reason);
82
+ }
83
+ if (event.type === "thread.started") {
84
+ this.updateThreadId(event.thread_id);
85
+ continue;
86
+ }
87
+ if (event.type === "turn.failed") {
88
+ yield {
89
+ type: NcpEventType.RunError,
90
+ payload: {
91
+ sessionId: input.sessionId,
92
+ messageId,
93
+ runId,
94
+ error: event.error.message
95
+ }
96
+ };
97
+ finished = true;
98
+ return;
99
+ }
100
+ if (event.type === "error") {
101
+ yield {
102
+ type: NcpEventType.RunError,
103
+ payload: {
104
+ sessionId: input.sessionId,
105
+ messageId,
106
+ runId,
107
+ error: event.message
108
+ }
109
+ };
110
+ finished = true;
111
+ return;
112
+ }
113
+ if (event.type === "item.started" || event.type === "item.updated" || event.type === "item.completed") {
114
+ yield* mapCodexItemEvent({
115
+ sessionId: input.sessionId,
116
+ messageId,
117
+ event,
118
+ itemTextById,
119
+ toolStateById
120
+ });
121
+ continue;
122
+ }
123
+ if (event.type === "turn.completed") {
124
+ yield {
125
+ type: NcpEventType.RunMetadata,
126
+ payload: {
127
+ sessionId: input.sessionId,
128
+ messageId,
129
+ runId,
130
+ metadata: {
131
+ kind: "final",
132
+ sessionId: input.sessionId
133
+ }
134
+ }
135
+ };
136
+ yield {
137
+ type: NcpEventType.RunFinished,
138
+ payload: {
139
+ sessionId: input.sessionId,
140
+ messageId,
141
+ runId
142
+ }
143
+ };
144
+ finished = true;
145
+ return;
146
+ }
147
+ }
148
+ if (!finished) {
149
+ yield {
150
+ type: NcpEventType.RunMetadata,
151
+ payload: {
152
+ sessionId: input.sessionId,
153
+ messageId,
154
+ runId,
155
+ metadata: {
156
+ kind: "final",
157
+ sessionId: input.sessionId
158
+ }
159
+ }
160
+ };
161
+ yield {
162
+ type: NcpEventType.RunFinished,
163
+ payload: {
164
+ sessionId: input.sessionId,
165
+ messageId,
166
+ runId
167
+ }
168
+ };
169
+ }
170
+ } catch (error) {
171
+ if (options?.signal?.aborted) {
172
+ throw toAbortError(options.signal.reason);
173
+ }
174
+ throw error;
175
+ }
176
+ }
177
+ async getCodex() {
178
+ if (!this.codexPromise) {
179
+ this.codexPromise = codexLoader.loadCodexConstructor().then(
180
+ (Ctor) => new Ctor({
181
+ apiKey: this.config.apiKey,
182
+ baseUrl: this.config.apiBase,
183
+ ...this.config.codexPathOverride ? { codexPathOverride: this.config.codexPathOverride } : {},
184
+ ...this.config.env ? { env: this.config.env } : {},
185
+ ...this.config.cliConfig ? { config: this.config.cliConfig } : {}
186
+ })
187
+ );
188
+ }
189
+ return this.codexPromise;
190
+ }
191
+ async resolveThread() {
192
+ if (this.thread) {
193
+ return this.thread;
194
+ }
195
+ const codex = await this.getCodex();
196
+ const threadOptions = {
197
+ ...this.config.threadOptions,
198
+ ...this.config.model ? { model: this.config.model } : {}
199
+ };
200
+ this.thread = this.threadId ? codex.resumeThread(this.threadId, threadOptions) : codex.startThread(threadOptions);
201
+ return this.thread;
202
+ }
203
+ async buildTurnInput(input) {
204
+ if (this.config.inputBuilder) {
205
+ return await this.config.inputBuilder(input);
206
+ }
207
+ return readUserText(input);
208
+ }
209
+ updateThreadId(nextThreadId) {
210
+ const normalizedThreadId = nextThreadId.trim();
211
+ if (!normalizedThreadId || normalizedThreadId === this.threadId) {
212
+ return;
213
+ }
214
+ this.threadId = normalizedThreadId;
215
+ const nextMetadata = {
216
+ ...this.sessionMetadata,
217
+ session_type: "codex",
218
+ codex_thread_id: normalizedThreadId
219
+ };
220
+ this.sessionMetadata.codex_thread_id = normalizedThreadId;
221
+ this.sessionMetadata.session_type = "codex";
222
+ this.config.setSessionMetadata?.(nextMetadata);
223
+ }
224
+ }
225
+ export {
226
+ CodexSdkNcpAgentRuntime
227
+ };
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@nextclaw/nextclaw-ncp-runtime-codex-sdk",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "description": "Optional NCP runtime adapter backed by OpenAI Codex SDK.",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "codex-sdk-loader.cjs",
16
+ "README.md"
17
+ ],
18
+ "dependencies": {
19
+ "@openai/codex-sdk": "^0.107.0",
20
+ "@nextclaw/ncp": "0.3.0"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^20.17.6",
24
+ "tsup": "^8.3.5",
25
+ "typescript": "^5.6.3"
26
+ },
27
+ "scripts": {
28
+ "build": "tsup --config tsup.config.ts",
29
+ "lint": "eslint .",
30
+ "tsc": "tsc -p tsconfig.json"
31
+ }
32
+ }