@agentrq/codex-gateway 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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,186 @@
1
+ # @agentrq/codex-gateway
2
+
3
+ MCP bridge CLI that connects [OpenAI Codex](https://github.com/openai/codex) to [agentrq](https://agentrq.com) workspaces.
4
+
5
+ > [!WARNING]
6
+ > **Pre-Alpha**: This project is in early development. APIs, configurations, and behaviors are subject to change without notice.
7
+
8
+ ## Overview
9
+
10
+ `@agentrq/codex-gateway` bridges the [Model Context Protocol (MCP)](https://modelcontextprotocol.io) with the [Codex app-server protocol](https://github.com/openai/codex/blob/main/codex-rs/app-server/README.md) (JSON-RPC 2.0 over stdio).
11
+
12
+ It automates task execution by:
13
+
14
+ 1. Loading your workspace's `.mcp.json` configuration.
15
+ 2. Connecting to the agentrq MCP server.
16
+ 3. Spawning `codex app-server` as a subprocess.
17
+ 4. Routing tasks from agentrq to Codex threads/turns.
18
+ 5. Collecting agent replies and sending them back to agentrq.
19
+ 6. Auto-reconnecting the MCP transport on disconnection.
20
+
21
+ ## Prerequisites
22
+
23
+ - **Node.js** >= 20
24
+ - **OpenAI Codex CLI** (`npm install -g @openai/codex`)
25
+ - An [agentrq](https://agentrq.com) workspace with an HTTP MCP server
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ npm install -g @agentrq/codex-gateway
31
+ ```
32
+
33
+ ## Setup
34
+
35
+ ### 1. Configure agentrq MCP server for Codex (project-level)
36
+
37
+ Codex reads project-level MCP server config from `.codex/config.toml`. Create this file so the Codex agent can use agentrq tools directly during task execution (replace `<WORKSPACEID>` and `<TOKEN>` with your values from the agentrq dashboard):
38
+
39
+ ```bash
40
+ mkdir -p .codex
41
+ cat >> .codex/config.toml << 'EOF'
42
+
43
+ [mcp_servers.agentrq-workspace]
44
+ url = "https://<WORKSPACEID>.mcp.agentrq.com/mcp?token=<TOKEN>"
45
+ EOF
46
+ ```
47
+
48
+ ### 2. Configure the gateway's agentrq connection
49
+
50
+ Create a `.mcp.json` in your project root so `codex-gateway` can connect to the same agentrq workspace:
51
+
52
+ ```json
53
+ {
54
+ "mcpServers": {
55
+ "agentrq": {
56
+ "type": "http",
57
+ "url": "https://<WORKSPACEID>.mcp.agentrq.com/mcp?token=<TOKEN>"
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ > **Note:** `.mcp.json` is used by `codex-gateway` to receive tasks. `.codex/config.toml` is used by the Codex agent itself to call agentrq tools (e.g. `reply`, `updateTaskStatus`) during execution.
64
+
65
+ ## Usage
66
+
67
+ Run `codex-gateway` from your agentrq workspace root (the directory containing `.mcp.json`):
68
+
69
+ ```bash
70
+ # Default: runs `codex app-server`
71
+ codex-gateway
72
+
73
+ # Custom codex command
74
+ codex-gateway -- codex app-server
75
+ ```
76
+
77
+ ### Environment Variables
78
+
79
+ | Variable | Description | Default |
80
+ |---|---|---|
81
+ | `CODEX_MODEL` | Override the model used for all threads/turns | _(codex default)_ |
82
+
83
+ ### Configuration
84
+
85
+ `codex-gateway` searches for `.mcp.json` starting in the current working directory and up to 3 parent directories.
86
+
87
+ Example `.mcp.json`:
88
+
89
+ ```json
90
+ {
91
+ "mcpServers": {
92
+ "agentrq": {
93
+ "type": "http",
94
+ "url": "https://your-workspace.mcp.agentrq.com?token=..."
95
+ }
96
+ }
97
+ }
98
+ ```
99
+
100
+ `codex-gateway` prefers servers with `agentrq` in the name; falls back to the first HTTP server with a `url`.
101
+
102
+ ## How It Works
103
+
104
+ ```
105
+ ┌──────────────────────────┐ JSON-RPC 2.0 / JSONL ┌─────────────────┐
106
+ │ codex app-server │ ◄─────────────────────────► │ │
107
+ │ (OpenAI Codex agent) │ │ codex-gateway │
108
+ └──────────────────────────┘ │ │
109
+ │ MCP Bridge │
110
+ │ │
111
+ ┌───────────────────┤ │
112
+ │ │ │
113
+ ▼ └─────────────────┘
114
+ ┌───────────────────────────┐
115
+ │ agentrq MCP Server │
116
+ │ (HTTP / StreamableHTTP) │
117
+ └───────────────────────────┘
118
+ ```
119
+
120
+ ### Flow
121
+
122
+ 1. **Config Loading** — Reads `.mcp.json` to find the agentrq MCP server.
123
+ 2. **MCP Connection** — Establishes a `StreamableHTTPClientTransport` with automatic retry and reconnection.
124
+ 3. **Codex Spawning** — Launches `codex app-server` via stdio.
125
+ 4. **Handshake** — Sends `initialize` + `initialized` to the Codex app-server.
126
+ 5. **Task Routing** — When a task arrives from agentrq:
127
+ - Extracts `chat_id` as the task identifier.
128
+ - Creates a new Codex thread for the chat (or reuses one if the same `chat_id` arrives again).
129
+ - Starts a turn with the task content.
130
+ - Streams `item/agentMessage/delta` notifications into a reply buffer.
131
+ 6. **Reply** — When `turn/completed` fires, sends the buffered text back via agentrq's `reply` tool.
132
+ 7. **Recursive Execution** — After each task, checks for the next pending task automatically.
133
+
134
+ ### Key Components
135
+
136
+ | File | Description |
137
+ |---|---|
138
+ | `src/index.ts` | Entry point; orchestrates config loading, MCP connection, Codex spawning, and task lifecycle. |
139
+ | `src/codexClient.ts` | JSON-RPC 2.0 client for the Codex app-server — handles JSONL I/O, request correlation, and turn completion. |
140
+ | `src/mcpClient.ts` | `EventEmitter`-based MCP client with auto-reconnection, notification handling, and tool call dispatch. |
141
+ | `src/config.ts` | Parses `.mcp.json` from the current directory tree up to 3 levels deep. |
142
+ | `src/taskIdentity.ts` | Extracts `chat_id` from MCP notification metadata or task text. |
143
+
144
+ ## Development
145
+
146
+ ```bash
147
+ # Install dependencies
148
+ npm install
149
+
150
+ # Run in development mode
151
+ npm run dev
152
+
153
+ # Type-check
154
+ npm run typecheck
155
+
156
+ # Run tests
157
+ npm test
158
+ ```
159
+
160
+ ## Contributing
161
+
162
+ Contributions are welcome! Please feel free to submit pull requests or open issues.
163
+
164
+ 1. Fork the repository
165
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
166
+ 3. Commit your changes (`git commit -m 'Add: amazing feature'`)
167
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
168
+ 5. Open a Pull Request
169
+
170
+ ## Contributing License
171
+
172
+ By contributing to this project, you agree that your contributions will be licensed under the project's Apache License 2.0.
173
+
174
+ ---
175
+
176
+ ## License
177
+
178
+ Apache License 2.0
179
+
180
+ Copyright (c) 2026 Contextual, Inc.
181
+
182
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
183
+
184
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
185
+
186
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,290 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { CodexClient } from "../codexClient.js";
3
+ describe("CodexClient", () => {
4
+ let client;
5
+ let mockWrite;
6
+ beforeEach(() => {
7
+ client = new CodexClient();
8
+ mockWrite = vi.fn();
9
+ client.stdin = { write: mockWrite };
10
+ });
11
+ describe("_handleMessage", () => {
12
+ it("should resolve a pending request on success response", async () => {
13
+ const resultPromise = client._request("test-method");
14
+ const requestId = client.nextId - 1;
15
+ client._handleMessage({ id: requestId, result: { foo: "bar" } });
16
+ const result = await resultPromise;
17
+ expect(result).toEqual({ foo: "bar" });
18
+ });
19
+ it("should reject a pending request on error response", async () => {
20
+ const resultPromise = client._request("test-method");
21
+ const requestId = client.nextId - 1;
22
+ client._handleMessage({
23
+ id: requestId,
24
+ error: { code: -32600, message: "Invalid request" },
25
+ });
26
+ await expect(resultPromise).rejects.toThrow("Invalid request (code -32600)");
27
+ });
28
+ it("should emit notification event for messages without id", () => {
29
+ const handler = vi.fn();
30
+ client.on("notification:turn/completed", handler);
31
+ client._handleMessage({
32
+ method: "turn/completed",
33
+ params: { threadId: "t1", turn: { id: "turn1", status: "completed" } },
34
+ });
35
+ expect(handler).toHaveBeenCalledWith({
36
+ threadId: "t1",
37
+ turn: { id: "turn1", status: "completed" },
38
+ });
39
+ });
40
+ it("should emit notification with undefined params when absent", () => {
41
+ const handler = vi.fn();
42
+ client.on("notification:initialized", handler);
43
+ client._handleMessage({ method: "initialized" });
44
+ expect(handler).toHaveBeenCalledWith(undefined);
45
+ });
46
+ it("should not throw for unrecognized responses (no pending request)", () => {
47
+ expect(() => {
48
+ client._handleMessage({ id: 999, result: "orphan" });
49
+ }).not.toThrow();
50
+ });
51
+ it("should emit server-request event for messages with both id and method", () => {
52
+ const handler = vi.fn();
53
+ client.on("server-request:item/commandExecution/requestApproval", handler);
54
+ client._handleMessage({
55
+ id: 0,
56
+ method: "item/commandExecution/requestApproval",
57
+ params: { reason: "Allow Codex to run `rm -rf dist/`?", command: "rm -rf dist/" },
58
+ });
59
+ expect(handler).toHaveBeenCalledWith({
60
+ id: 0,
61
+ params: { reason: "Allow Codex to run `rm -rf dist/`?", command: "rm -rf dist/" },
62
+ });
63
+ });
64
+ it("should not treat server-request as a pending request resolution", async () => {
65
+ const resultPromise = client._request("some-method");
66
+ const reqId = client.nextId - 1;
67
+ // A server-initiated request with the same id should not resolve our pending request
68
+ client._handleMessage({ id: reqId, method: "elicitation/create", params: {} });
69
+ // The pending request should still be pending (not resolved or rejected)
70
+ let settled = false;
71
+ resultPromise.then(() => { settled = true; }).catch(() => { settled = true; });
72
+ await new Promise((r) => setTimeout(r, 10));
73
+ expect(settled).toBe(false);
74
+ // Clean up
75
+ client._handleMessage({ id: reqId, result: {} });
76
+ await resultPromise;
77
+ });
78
+ it("should remove pending request after resolution", async () => {
79
+ const resultPromise = client._request("some-method");
80
+ const id = client.nextId - 1;
81
+ client._handleMessage({ id, result: {} });
82
+ await resultPromise;
83
+ expect(client.pendingRequests.has(id)).toBe(false);
84
+ });
85
+ });
86
+ describe("_request", () => {
87
+ it("should write JSON-RPC request to stdin with incrementing id", () => {
88
+ client._request("test-method", { key: "value" });
89
+ expect(mockWrite).toHaveBeenCalledWith(expect.stringContaining('"method":"test-method"'));
90
+ expect(mockWrite).toHaveBeenCalledWith(expect.stringContaining('"key":"value"'));
91
+ const written = mockWrite.mock.calls[0][0];
92
+ expect(written.endsWith("\n")).toBe(true);
93
+ });
94
+ it("should omit params field when not provided", () => {
95
+ client._request("no-params-method");
96
+ const written = mockWrite.mock.calls[0][0];
97
+ const parsed = JSON.parse(written);
98
+ expect(parsed.params).toBeUndefined();
99
+ });
100
+ });
101
+ describe("_sendNotification", () => {
102
+ it("should write notification without id", () => {
103
+ client._sendNotification("initialized");
104
+ const written = mockWrite.mock.calls[0][0];
105
+ const parsed = JSON.parse(written);
106
+ expect(parsed.method).toBe("initialized");
107
+ expect(parsed.id).toBeUndefined();
108
+ });
109
+ });
110
+ describe("_sendResponse", () => {
111
+ it("should write response with id and result", () => {
112
+ client._sendResponse(42, { action: "accept" });
113
+ const written = mockWrite.mock.calls[0][0];
114
+ const parsed = JSON.parse(written);
115
+ expect(parsed.id).toBe(42);
116
+ expect(parsed.result).toEqual({ action: "accept" });
117
+ expect(parsed.method).toBeUndefined();
118
+ });
119
+ });
120
+ describe("startThread", () => {
121
+ it("should call thread/start and return threadId", async () => {
122
+ const requestSpy = vi
123
+ .spyOn(client, "_request")
124
+ .mockResolvedValue({ thread: { id: "thr_abc" } });
125
+ const threadId = await client.startThread({
126
+ cwd: "/project",
127
+ model: "o4-mini",
128
+ });
129
+ expect(threadId).toBe("thr_abc");
130
+ expect(requestSpy).toHaveBeenCalledWith("thread/start", expect.objectContaining({
131
+ cwd: "/project",
132
+ model: "o4-mini",
133
+ approvalPolicy: "on-request",
134
+ sandbox: "read-only",
135
+ }));
136
+ });
137
+ it("should use defaults when no params provided", async () => {
138
+ const requestSpy = vi
139
+ .spyOn(client, "_request")
140
+ .mockResolvedValue({ thread: { id: "thr_default" } });
141
+ await client.startThread();
142
+ expect(requestSpy).toHaveBeenCalledWith("thread/start", expect.objectContaining({
143
+ approvalPolicy: "on-request",
144
+ sandbox: "read-only",
145
+ }));
146
+ const params = requestSpy.mock.calls[0][1];
147
+ expect(params.model).toBeUndefined();
148
+ });
149
+ it("should respect custom approvalPolicy", async () => {
150
+ const requestSpy = vi
151
+ .spyOn(client, "_request")
152
+ .mockResolvedValue({ thread: { id: "thr_xyz" } });
153
+ await client.startThread({ approvalPolicy: "on-request" });
154
+ expect(requestSpy).toHaveBeenCalledWith("thread/start", expect.objectContaining({ approvalPolicy: "on-request" }));
155
+ });
156
+ it("should respect custom sandbox mode", async () => {
157
+ const requestSpy = vi
158
+ .spyOn(client, "_request")
159
+ .mockResolvedValue({ thread: { id: "thr_xyz" } });
160
+ await client.startThread({ sandbox: "danger-full-access" });
161
+ expect(requestSpy).toHaveBeenCalledWith("thread/start", expect.objectContaining({ sandbox: "danger-full-access" }));
162
+ });
163
+ });
164
+ describe("startTurn", () => {
165
+ it("should call turn/start with text input and return turnId", async () => {
166
+ const requestSpy = vi
167
+ .spyOn(client, "_request")
168
+ .mockResolvedValue({ turn: { id: "turn_xyz" } });
169
+ const turnId = await client.startTurn("thr_abc", "Do something", "o4-mini");
170
+ expect(turnId).toBe("turn_xyz");
171
+ expect(requestSpy).toHaveBeenCalledWith("turn/start", {
172
+ threadId: "thr_abc",
173
+ input: [{ type: "text", text: "Do something" }],
174
+ model: "o4-mini",
175
+ });
176
+ });
177
+ it("should omit model when not provided", async () => {
178
+ const requestSpy = vi
179
+ .spyOn(client, "_request")
180
+ .mockResolvedValue({ turn: { id: "turn_nomodel" } });
181
+ await client.startTurn("thr_abc", "Do something");
182
+ const params = requestSpy.mock.calls[0][1];
183
+ expect(params.model).toBeUndefined();
184
+ });
185
+ });
186
+ describe("waitForTurnCompletion", () => {
187
+ it("should resolve with 'completed' when turn/completed arrives", async () => {
188
+ const completionPromise = client.waitForTurnCompletion("thr_1", "turn_1");
189
+ client.emit("notification:turn/completed", {
190
+ threadId: "thr_1",
191
+ turn: { id: "turn_1", status: "completed" },
192
+ });
193
+ const status = await completionPromise;
194
+ expect(status).toBe("completed");
195
+ });
196
+ it("should resolve with 'interrupted' status", async () => {
197
+ const completionPromise = client.waitForTurnCompletion("thr_1", "turn_1");
198
+ client.emit("notification:turn/completed", {
199
+ threadId: "thr_1",
200
+ turn: { id: "turn_1", status: "interrupted" },
201
+ });
202
+ const status = await completionPromise;
203
+ expect(status).toBe("interrupted");
204
+ });
205
+ it("should reject when turn status is failed", async () => {
206
+ const completionPromise = client.waitForTurnCompletion("thr_1", "turn_1");
207
+ client.emit("notification:turn/completed", {
208
+ threadId: "thr_1",
209
+ turn: {
210
+ id: "turn_1",
211
+ status: "failed",
212
+ error: { message: "Something went wrong" },
213
+ },
214
+ });
215
+ await expect(completionPromise).rejects.toThrow("Something went wrong");
216
+ });
217
+ it("should reject with generic message when error is null", async () => {
218
+ const completionPromise = client.waitForTurnCompletion("thr_1", "turn_1");
219
+ client.emit("notification:turn/completed", {
220
+ threadId: "thr_1",
221
+ turn: { id: "turn_1", status: "failed", error: null },
222
+ });
223
+ await expect(completionPromise).rejects.toThrow("unknown error");
224
+ });
225
+ it("should ignore notifications for other threads", async () => {
226
+ let resolved = false;
227
+ const completionPromise = client
228
+ .waitForTurnCompletion("thr_target", "turn_1")
229
+ .then(() => {
230
+ resolved = true;
231
+ });
232
+ client.emit("notification:turn/completed", {
233
+ threadId: "thr_OTHER",
234
+ turn: { id: "turn_1", status: "completed" },
235
+ });
236
+ await new Promise((r) => setTimeout(r, 10));
237
+ expect(resolved).toBe(false);
238
+ // Resolve correctly
239
+ client.emit("notification:turn/completed", {
240
+ threadId: "thr_target",
241
+ turn: { id: "turn_1", status: "completed" },
242
+ });
243
+ await completionPromise;
244
+ });
245
+ it("should ignore notifications for other turn IDs", async () => {
246
+ let resolved = false;
247
+ const completionPromise = client
248
+ .waitForTurnCompletion("thr_1", "turn_target")
249
+ .then(() => {
250
+ resolved = true;
251
+ });
252
+ client.emit("notification:turn/completed", {
253
+ threadId: "thr_1",
254
+ turn: { id: "turn_OTHER", status: "completed" },
255
+ });
256
+ await new Promise((r) => setTimeout(r, 10));
257
+ expect(resolved).toBe(false);
258
+ client.emit("notification:turn/completed", {
259
+ threadId: "thr_1",
260
+ turn: { id: "turn_target", status: "completed" },
261
+ });
262
+ await completionPromise;
263
+ });
264
+ it("should remove listener after completion", async () => {
265
+ const completionPromise = client.waitForTurnCompletion("thr_1", "turn_1");
266
+ client.emit("notification:turn/completed", {
267
+ threadId: "thr_1",
268
+ turn: { id: "turn_1", status: "completed" },
269
+ });
270
+ await completionPromise;
271
+ expect(client.listenerCount("notification:turn/completed")).toBe(0);
272
+ });
273
+ });
274
+ describe("close", () => {
275
+ it("should kill the process and clear state", () => {
276
+ const mockKill = vi.fn();
277
+ client.process = { kill: mockKill };
278
+ client.stdin = { write: vi.fn() };
279
+ client.close();
280
+ expect(mockKill).toHaveBeenCalled();
281
+ expect(client.process).toBeNull();
282
+ expect(client.stdin).toBeNull();
283
+ });
284
+ it("should not throw when process is already null", () => {
285
+ client.process = null;
286
+ expect(() => client.close()).not.toThrow();
287
+ });
288
+ });
289
+ });
290
+ //# sourceMappingURL=codexClient.test.js.map