@theopenbee/engine-codex 0.0.0-stage → 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 +21 -0
- package/README.md +85 -2
- package/dist/codex.d.ts +20 -0
- package/dist/codex.js +407 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -0
- package/openbee.plugin.json +16 -0
- package/package.json +44 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TENGYONGZHI
|
|
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
CHANGED
|
@@ -1,3 +1,86 @@
|
|
|
1
|
-
#
|
|
1
|
+
# openbee Codex engine
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An [openbee](https://github.com/theopenbee/openbee) engine plugin that runs tasks with [OpenAI Codex](https://www.npmjs.com/package/@openai/codex). It is built on [`@theopenbee/engine-sdk`](https://www.npmjs.com/package/@theopenbee/engine-sdk).
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
You install Codex and log in to it yourself. The plugin only starts it.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm i -g @openai/codex
|
|
11
|
+
codex login
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Codex is started with openbee's environment, including the variables set in openbee's **Env** settings.
|
|
15
|
+
|
|
16
|
+
The plugin itself needs Node.js 20 or newer (or Bun).
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
openbee plugin install codex
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Or from npm by package name:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
openbee plugin install @theopenbee/engine-codex
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Or from a local checkout:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
git clone https://github.com/theopenbee/engine-codex.git
|
|
34
|
+
cd engine-codex
|
|
35
|
+
npm install
|
|
36
|
+
openbee plugin install "$(pwd)"
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Then enable the plugin, and pick `codex` as the default engine or per worker.
|
|
40
|
+
|
|
41
|
+
## Settings
|
|
42
|
+
|
|
43
|
+
| Setting | Description |
|
|
44
|
+
|---|---|
|
|
45
|
+
| `path` | Path to the `codex` executable. Leave empty to use `codex` from `PATH`. |
|
|
46
|
+
|
|
47
|
+
The plugin checks the setting when it is enabled: it runs `codex --version` and shows the version, or the reason it failed (for example `codex not found on PATH`).
|
|
48
|
+
|
|
49
|
+
## Sessions
|
|
50
|
+
|
|
51
|
+
Codex names its conversations (threads) itself, so the plugin keeps a small mapping from each openbee session id to the Codex thread id. The mapping files live in `~/.openbee/.codex/sessions/`, one file per session, holding only the thread id. openbee never deletes this directory, so conversations survive uninstalling the plugin and conversations that were started before the plugin was installed keep working.
|
|
52
|
+
|
|
53
|
+
The mapping is written as soon as Codex announces the thread, so a run that is stopped or fails halfway can still be resumed. If a mapping is missing when a conversation should resume, the plugin logs a warning and starts a new Codex thread. If a mapping exists but Codex no longer has that thread, the run fails with Codex's own message; the plugin does not retry.
|
|
54
|
+
|
|
55
|
+
Token usage is read from Codex's own session files, `~/.codex/sessions/` (or `$CODEX_HOME/sessions/` when `CODEX_HOME` is set in openbee's environment), found through the mapping, and summed per model.
|
|
56
|
+
|
|
57
|
+
## How it runs Codex
|
|
58
|
+
|
|
59
|
+
New conversation, with the prompt on standard input:
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
codex exec - --json --dangerously-bypass-approvals-and-sandbox [mcp -c options] [extra args]
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Later turns, with the prompt as the last argument:
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
codex exec resume <thread id> --json --dangerously-bypass-approvals-and-sandbox <prompt> [mcp -c options] [extra args]
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
- When openbee provides its MCP server, the plugin adds `-c mcp_servers.<name>.url="<url>"` and `-c mcp_servers.<name>.bearer_token_env_var="<key variable>"`. Codex reads the API key from its environment, so the key never appears on the command line.
|
|
72
|
+
- The result is the text of the last `agent_message` item Codex completed. A non-zero exit code is reported as a failed run (`codex exited with code N`), followed by the last line Codex wrote to standard error when there is one.
|
|
73
|
+
- Codex's output is written to the run's log file as it arrives.
|
|
74
|
+
|
|
75
|
+
## Development
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
npm install
|
|
79
|
+
npm test
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`npm install` also builds `dist/`; run `npm run build` after changing `src/`. The end-to-end tests run the plugin against a fake `codex` script, under Node and under Bun when it is installed (`bun` on `PATH` or `~/.openbee/runtime/bun-*/bun`).
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
MIT
|
package/dist/codex.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Engine, RunParams, TokenUsage } from "@theopenbee/engine-sdk";
|
|
2
|
+
type McpParams = NonNullable<RunParams["mcp"]>;
|
|
3
|
+
export declare function goQuote(value: string): string;
|
|
4
|
+
export declare function mcpArgs(mcp: McpParams | undefined): string[];
|
|
5
|
+
export declare function buildArgs(threadId: string, resume: boolean, prompt: string, extraArgs: string[]): string[];
|
|
6
|
+
export declare function threadIdFromLine(line: string): string;
|
|
7
|
+
export declare function extractResultFromLog(logPath: string): Promise<string>;
|
|
8
|
+
export declare class SessionStore {
|
|
9
|
+
readonly dir: string;
|
|
10
|
+
constructor(dir: string);
|
|
11
|
+
get(sessionId: string): string | undefined;
|
|
12
|
+
set(sessionId: string, threadId: string): void;
|
|
13
|
+
}
|
|
14
|
+
export declare function openSessionStore(dir: string): SessionStore;
|
|
15
|
+
export declare function codexBaseDir(env?: NodeJS.ProcessEnv, home?: string): string;
|
|
16
|
+
export declare function findCodexSessionFile(codexBase: string, threadId: string): string | undefined;
|
|
17
|
+
export declare function collectUsage(store: SessionStore, codexBase: string, sessionIds: string[]): Promise<Record<string, TokenUsage[]>>;
|
|
18
|
+
export declare function failureText(code: number | null, signal: NodeJS.Signals | null, stderrTail: string): string;
|
|
19
|
+
export declare const engine: Engine;
|
|
20
|
+
export {};
|
package/dist/codex.js
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
import { createReadStream, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline";
|
|
5
|
+
import { cliVersion, findCli, log, spawnCli } from "@theopenbee/engine-sdk";
|
|
6
|
+
function isObject(value) {
|
|
7
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8
|
+
}
|
|
9
|
+
function errorMessage(err) {
|
|
10
|
+
return err instanceof Error ? err.message : String(err);
|
|
11
|
+
}
|
|
12
|
+
function isMissing(err) {
|
|
13
|
+
const code = err?.code;
|
|
14
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
15
|
+
}
|
|
16
|
+
function isPlainFileName(id) {
|
|
17
|
+
return typeof id === "string" && id !== "" && id !== "." && id !== ".." && !/[\\/\0]/.test(id);
|
|
18
|
+
}
|
|
19
|
+
function isFile(path) {
|
|
20
|
+
try {
|
|
21
|
+
return statSync(path).isFile();
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function numberOrZero(value) {
|
|
28
|
+
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
|
29
|
+
}
|
|
30
|
+
function hex(value, digits) {
|
|
31
|
+
return value.toString(16).padStart(digits, "0");
|
|
32
|
+
}
|
|
33
|
+
const GO_SIMPLE_ESCAPES = {
|
|
34
|
+
0x07: "\\a",
|
|
35
|
+
0x08: "\\b",
|
|
36
|
+
0x0c: "\\f",
|
|
37
|
+
0x0a: "\\n",
|
|
38
|
+
0x0d: "\\r",
|
|
39
|
+
0x09: "\\t",
|
|
40
|
+
0x0b: "\\v",
|
|
41
|
+
};
|
|
42
|
+
const GO_PRINTABLE = /^[\p{L}\p{M}\p{N}\p{P}\p{S}]$/u;
|
|
43
|
+
function isGoPrintable(codePoint, char) {
|
|
44
|
+
return codePoint === 0x20 || (codePoint > 0x20 && GO_PRINTABLE.test(char));
|
|
45
|
+
}
|
|
46
|
+
export function goQuote(value) {
|
|
47
|
+
let out = '"';
|
|
48
|
+
for (const original of value) {
|
|
49
|
+
let codePoint = original.codePointAt(0) ?? 0xfffd;
|
|
50
|
+
if (codePoint >= 0xd800 && codePoint <= 0xdfff)
|
|
51
|
+
codePoint = 0xfffd;
|
|
52
|
+
const char = String.fromCodePoint(codePoint);
|
|
53
|
+
if (char === '"' || char === "\\") {
|
|
54
|
+
out += `\\${char}`;
|
|
55
|
+
}
|
|
56
|
+
else if (isGoPrintable(codePoint, char)) {
|
|
57
|
+
out += char;
|
|
58
|
+
}
|
|
59
|
+
else if (GO_SIMPLE_ESCAPES[codePoint] !== undefined) {
|
|
60
|
+
out += GO_SIMPLE_ESCAPES[codePoint];
|
|
61
|
+
}
|
|
62
|
+
else if (codePoint < 0x20 || codePoint === 0x7f) {
|
|
63
|
+
out += `\\x${hex(codePoint, 2)}`;
|
|
64
|
+
}
|
|
65
|
+
else if (codePoint < 0x10000) {
|
|
66
|
+
out += `\\u${hex(codePoint, 4)}`;
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
out += `\\U${hex(codePoint, 8)}`;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return `${out}"`;
|
|
73
|
+
}
|
|
74
|
+
export function mcpArgs(mcp) {
|
|
75
|
+
if (!mcp?.url)
|
|
76
|
+
return [];
|
|
77
|
+
const prefix = `mcp_servers.${mcp.name}.`;
|
|
78
|
+
return ["-c", `${prefix}url=${goQuote(mcp.url)}`, "-c", `${prefix}bearer_token_env_var=${goQuote(mcp.api_key_env)}`];
|
|
79
|
+
}
|
|
80
|
+
export function buildArgs(threadId, resume, prompt, extraArgs) {
|
|
81
|
+
const base = resume && threadId !== ""
|
|
82
|
+
? ["exec", "resume", threadId, "--json", "--dangerously-bypass-approvals-and-sandbox"]
|
|
83
|
+
: ["exec", "-", "--json", "--dangerously-bypass-approvals-and-sandbox"];
|
|
84
|
+
if (resume && threadId !== "" && prompt !== "")
|
|
85
|
+
base.push(prompt);
|
|
86
|
+
return [...base, ...extraArgs];
|
|
87
|
+
}
|
|
88
|
+
export function threadIdFromLine(line) {
|
|
89
|
+
const text = line.trim();
|
|
90
|
+
if (!text.startsWith("{"))
|
|
91
|
+
return "";
|
|
92
|
+
let event;
|
|
93
|
+
try {
|
|
94
|
+
event = JSON.parse(text);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return "";
|
|
98
|
+
}
|
|
99
|
+
if (isObject(event) && event.type === "thread.started" && typeof event.thread_id === "string")
|
|
100
|
+
return event.thread_id;
|
|
101
|
+
return "";
|
|
102
|
+
}
|
|
103
|
+
export async function extractResultFromLog(logPath) {
|
|
104
|
+
let lastText = "";
|
|
105
|
+
const stream = createReadStream(logPath, { encoding: "utf8" });
|
|
106
|
+
const lines = createInterface({ input: stream, crlfDelay: Infinity });
|
|
107
|
+
try {
|
|
108
|
+
for await (const raw of lines) {
|
|
109
|
+
const text = raw.trim();
|
|
110
|
+
if (!text.startsWith("{"))
|
|
111
|
+
continue;
|
|
112
|
+
let event;
|
|
113
|
+
try {
|
|
114
|
+
event = JSON.parse(text);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (!isObject(event) || event.type !== "item.completed" || !isObject(event.item))
|
|
120
|
+
continue;
|
|
121
|
+
const item = event.item;
|
|
122
|
+
if (item.type === "agent_message" && typeof item.text === "string" && item.text !== "")
|
|
123
|
+
lastText = item.text;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return lastText;
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
lines.close();
|
|
131
|
+
stream.destroy();
|
|
132
|
+
}
|
|
133
|
+
return lastText;
|
|
134
|
+
}
|
|
135
|
+
export class SessionStore {
|
|
136
|
+
dir;
|
|
137
|
+
constructor(dir) {
|
|
138
|
+
this.dir = dir;
|
|
139
|
+
}
|
|
140
|
+
get(sessionId) {
|
|
141
|
+
if (!isPlainFileName(sessionId))
|
|
142
|
+
return undefined;
|
|
143
|
+
let data;
|
|
144
|
+
try {
|
|
145
|
+
data = readFileSync(join(this.dir, sessionId), "utf8");
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
const threadId = data.trim();
|
|
151
|
+
return threadId === "" ? undefined : threadId;
|
|
152
|
+
}
|
|
153
|
+
set(sessionId, threadId) {
|
|
154
|
+
if (!isPlainFileName(sessionId))
|
|
155
|
+
throw new Error(`invalid session id ${JSON.stringify(sessionId)}`);
|
|
156
|
+
const dest = join(this.dir, sessionId);
|
|
157
|
+
const tmp = `${dest}.tmp`;
|
|
158
|
+
try {
|
|
159
|
+
writeFileSync(tmp, threadId);
|
|
160
|
+
}
|
|
161
|
+
catch (err) {
|
|
162
|
+
rmSync(tmp, { force: true });
|
|
163
|
+
throw new Error(`write temp session file: ${errorMessage(err)}`);
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
renameSync(tmp, dest);
|
|
167
|
+
}
|
|
168
|
+
catch (err) {
|
|
169
|
+
rmSync(tmp, { force: true });
|
|
170
|
+
throw new Error(`rename session file: ${errorMessage(err)}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
export function openSessionStore(dir) {
|
|
175
|
+
try {
|
|
176
|
+
mkdirSync(dir, { recursive: true });
|
|
177
|
+
}
|
|
178
|
+
catch (err) {
|
|
179
|
+
throw new Error(`create sessions dir: ${errorMessage(err)}`);
|
|
180
|
+
}
|
|
181
|
+
return new SessionStore(dir);
|
|
182
|
+
}
|
|
183
|
+
export function codexBaseDir(env = process.env, home = homedir()) {
|
|
184
|
+
return env.CODEX_HOME || join(home, ".codex");
|
|
185
|
+
}
|
|
186
|
+
function listSessionFiles(dir, out) {
|
|
187
|
+
let entries;
|
|
188
|
+
try {
|
|
189
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
190
|
+
}
|
|
191
|
+
catch (err) {
|
|
192
|
+
if (!isMissing(err))
|
|
193
|
+
log.warn(`reading ${dir} failed: ${errorMessage(err)}`);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
197
|
+
for (const entry of entries) {
|
|
198
|
+
const path = join(dir, entry.name);
|
|
199
|
+
if (entry.isDirectory())
|
|
200
|
+
listSessionFiles(path, out);
|
|
201
|
+
else if (entry.name.endsWith(".jsonl"))
|
|
202
|
+
out.push({ name: entry.name, path });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
class SessionFiles {
|
|
206
|
+
sessionsDir;
|
|
207
|
+
listing;
|
|
208
|
+
constructor(codexBase) {
|
|
209
|
+
this.sessionsDir = join(codexBase, "sessions");
|
|
210
|
+
}
|
|
211
|
+
find(threadId) {
|
|
212
|
+
if (!isPlainFileName(threadId))
|
|
213
|
+
return undefined;
|
|
214
|
+
const flat = join(this.sessionsDir, `${threadId}.jsonl`);
|
|
215
|
+
if (isFile(flat))
|
|
216
|
+
return flat;
|
|
217
|
+
if (!this.listing) {
|
|
218
|
+
this.listing = [];
|
|
219
|
+
listSessionFiles(this.sessionsDir, this.listing);
|
|
220
|
+
}
|
|
221
|
+
return this.listing.find((file) => file.name.includes(threadId))?.path;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
export function findCodexSessionFile(codexBase, threadId) {
|
|
225
|
+
return new SessionFiles(codexBase).find(threadId);
|
|
226
|
+
}
|
|
227
|
+
function readCounts(value) {
|
|
228
|
+
if (!isObject(value))
|
|
229
|
+
return undefined;
|
|
230
|
+
return {
|
|
231
|
+
input: numberOrZero(value.input_tokens),
|
|
232
|
+
output: numberOrZero(value.output_tokens),
|
|
233
|
+
cached: numberOrZero(value.cached_input_tokens),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
function addCounts(target, counts) {
|
|
237
|
+
target.input_tokens += counts.input;
|
|
238
|
+
target.output_tokens += counts.output;
|
|
239
|
+
target.cache_read_tokens += counts.cached;
|
|
240
|
+
}
|
|
241
|
+
function stringOrEmpty(value) {
|
|
242
|
+
return typeof value === "string" ? value : "";
|
|
243
|
+
}
|
|
244
|
+
function resolveModel(info, currentModel) {
|
|
245
|
+
const metadata = isObject(info.metadata) ? info.metadata : {};
|
|
246
|
+
return stringOrEmpty(info.model) || stringOrEmpty(info.model_name) || stringOrEmpty(metadata.model) || currentModel;
|
|
247
|
+
}
|
|
248
|
+
async function parseSessionFile(path) {
|
|
249
|
+
const totals = new Map();
|
|
250
|
+
const previous = new Map();
|
|
251
|
+
let currentModel = "";
|
|
252
|
+
const stream = createReadStream(path, { encoding: "utf8" });
|
|
253
|
+
const lines = createInterface({ input: stream, crlfDelay: Infinity });
|
|
254
|
+
try {
|
|
255
|
+
for await (const raw of lines) {
|
|
256
|
+
let event;
|
|
257
|
+
try {
|
|
258
|
+
event = JSON.parse(raw);
|
|
259
|
+
}
|
|
260
|
+
catch {
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
if (!isObject(event))
|
|
264
|
+
continue;
|
|
265
|
+
const payload = isObject(event.payload) ? event.payload : {};
|
|
266
|
+
if (event.type === "turn_context") {
|
|
267
|
+
const model = stringOrEmpty(payload.model);
|
|
268
|
+
if (model !== "")
|
|
269
|
+
currentModel = model;
|
|
270
|
+
}
|
|
271
|
+
else if (event.type === "event_msg") {
|
|
272
|
+
const payloadType = stringOrEmpty(payload.type);
|
|
273
|
+
if (payloadType !== "" && payloadType !== "token_count")
|
|
274
|
+
continue;
|
|
275
|
+
const info = isObject(payload.info) ? payload.info : isObject(event.info) ? event.info : undefined;
|
|
276
|
+
if (!info)
|
|
277
|
+
continue;
|
|
278
|
+
const model = resolveModel(info, currentModel);
|
|
279
|
+
if (model === "")
|
|
280
|
+
continue;
|
|
281
|
+
let usage = totals.get(model);
|
|
282
|
+
if (!usage) {
|
|
283
|
+
usage = { model, input_tokens: 0, output_tokens: 0, cache_creation_tokens: 0, cache_read_tokens: 0 };
|
|
284
|
+
totals.set(model, usage);
|
|
285
|
+
}
|
|
286
|
+
const prev = previous.get(model) ?? { input: 0, output: 0, cached: 0 };
|
|
287
|
+
previous.set(model, prev);
|
|
288
|
+
const last = readCounts(info.last_token_usage);
|
|
289
|
+
const total = readCounts(info.total_token_usage);
|
|
290
|
+
if (last) {
|
|
291
|
+
addCounts(usage, last);
|
|
292
|
+
if (total) {
|
|
293
|
+
previous.set(model, total);
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
prev.input += last.input;
|
|
297
|
+
prev.output += last.output;
|
|
298
|
+
prev.cached += last.cached;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
else if (total) {
|
|
302
|
+
addCounts(usage, { input: total.input - prev.input, output: total.output - prev.output, cached: total.cached - prev.cached });
|
|
303
|
+
previous.set(model, total);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
finally {
|
|
309
|
+
lines.close();
|
|
310
|
+
stream.destroy();
|
|
311
|
+
}
|
|
312
|
+
return [...totals.values()];
|
|
313
|
+
}
|
|
314
|
+
export async function collectUsage(store, codexBase, sessionIds) {
|
|
315
|
+
const files = new SessionFiles(codexBase);
|
|
316
|
+
const found = new Map();
|
|
317
|
+
for (const id of sessionIds) {
|
|
318
|
+
if (found.has(id))
|
|
319
|
+
continue;
|
|
320
|
+
const threadId = store.get(id);
|
|
321
|
+
if (threadId === undefined)
|
|
322
|
+
continue;
|
|
323
|
+
const path = files.find(threadId);
|
|
324
|
+
if (!path)
|
|
325
|
+
continue;
|
|
326
|
+
try {
|
|
327
|
+
found.set(id, await parseSessionFile(path));
|
|
328
|
+
}
|
|
329
|
+
catch (err) {
|
|
330
|
+
log.warn(`reading codex session file for ${id} failed: ${errorMessage(err)}`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return Object.fromEntries(found);
|
|
334
|
+
}
|
|
335
|
+
function lastNonEmptyLine(text) {
|
|
336
|
+
const lines = text.split("\n");
|
|
337
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
338
|
+
const line = lines[i].trim();
|
|
339
|
+
if (line !== "")
|
|
340
|
+
return line;
|
|
341
|
+
}
|
|
342
|
+
return "";
|
|
343
|
+
}
|
|
344
|
+
export function failureText(code, signal, stderrTail) {
|
|
345
|
+
const base = code === null ? `codex was terminated by signal ${signal ?? "unknown"}` : `codex exited with code ${code}`;
|
|
346
|
+
const detail = lastNonEmptyLine(stderrTail);
|
|
347
|
+
return detail === "" ? base : `${base}: ${detail}`;
|
|
348
|
+
}
|
|
349
|
+
function resolveThread(store, sessionId, resume) {
|
|
350
|
+
if (!resume)
|
|
351
|
+
return { threadId: "", resume: false };
|
|
352
|
+
const threadId = store.get(sessionId);
|
|
353
|
+
if (threadId === undefined) {
|
|
354
|
+
log.warn(`codex session mapping not found for ${JSON.stringify(sessionId)}, starting a new session`);
|
|
355
|
+
return { threadId: "", resume: false };
|
|
356
|
+
}
|
|
357
|
+
return { threadId, resume: true };
|
|
358
|
+
}
|
|
359
|
+
export const engine = {
|
|
360
|
+
async check(req) {
|
|
361
|
+
const path = findCli(req.config, "codex");
|
|
362
|
+
return { version: await cliVersion(path), path };
|
|
363
|
+
},
|
|
364
|
+
async run(req) {
|
|
365
|
+
const params = req.params;
|
|
366
|
+
const command = findCli(req.config, "codex");
|
|
367
|
+
const store = openSessionStore(join(req.state_dir, "sessions"));
|
|
368
|
+
const thread = resolveThread(store, params.session_id, params.resume);
|
|
369
|
+
const args = buildArgs(thread.threadId, thread.resume, params.prompt, [...mcpArgs(params.mcp), ...(params.extra_args ?? [])]);
|
|
370
|
+
let awaitingThread = !thread.resume;
|
|
371
|
+
let outcome;
|
|
372
|
+
try {
|
|
373
|
+
outcome = await spawnCli({
|
|
374
|
+
command,
|
|
375
|
+
args,
|
|
376
|
+
cwd: params.work_dir,
|
|
377
|
+
input: thread.resume ? undefined : params.prompt,
|
|
378
|
+
logPath: params.log_path,
|
|
379
|
+
onStdoutLine(line) {
|
|
380
|
+
if (awaitingThread) {
|
|
381
|
+
const threadId = threadIdFromLine(line);
|
|
382
|
+
if (threadId !== "") {
|
|
383
|
+
awaitingThread = false;
|
|
384
|
+
try {
|
|
385
|
+
store.set(params.session_id, threadId);
|
|
386
|
+
}
|
|
387
|
+
catch (err) {
|
|
388
|
+
log.error(`store codex session ${JSON.stringify(params.session_id)} failed: ${errorMessage(err)}`);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return line;
|
|
393
|
+
},
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
catch (err) {
|
|
397
|
+
throw new Error(`start codex: ${errorMessage(err)}`);
|
|
398
|
+
}
|
|
399
|
+
const text = await extractResultFromLog(params.log_path);
|
|
400
|
+
if (outcome.code !== 0)
|
|
401
|
+
return { text, error: failureText(outcome.code, outcome.signal, outcome.stderrTail) };
|
|
402
|
+
return { text };
|
|
403
|
+
},
|
|
404
|
+
async usage(req) {
|
|
405
|
+
return collectUsage(new SessionStore(join(req.state_dir, "sessions")), codexBaseDir(), req.params.session_ids ?? []);
|
|
406
|
+
},
|
|
407
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"protocol_version": 1,
|
|
3
|
+
"type": "engine",
|
|
4
|
+
"id": "codex",
|
|
5
|
+
"name": { "en": "Codex", "zh": "Codex" },
|
|
6
|
+
"description": { "en": "Runs tasks with OpenAI Codex", "zh": "用 OpenAI Codex 执行任务" },
|
|
7
|
+
"command": ["node", "dist/index.js"],
|
|
8
|
+
"config": [
|
|
9
|
+
{
|
|
10
|
+
"key": "path",
|
|
11
|
+
"type": "string",
|
|
12
|
+
"label": { "en": "Codex path", "zh": "Codex 路径" },
|
|
13
|
+
"help": { "en": "Leave empty to use codex on PATH", "zh": "留空则使用 PATH 里的 codex" }
|
|
14
|
+
}
|
|
15
|
+
]
|
|
16
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theopenbee/engine-codex",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Codex engine plugin for openbee",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"openbee",
|
|
7
|
+
"openbee-plugin",
|
|
8
|
+
"openbee-engine",
|
|
9
|
+
"codex",
|
|
10
|
+
"openai"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/theopenbee/engine-codex.git"
|
|
16
|
+
},
|
|
17
|
+
"homepage": "https://github.com/theopenbee/engine-codex#readme",
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/theopenbee/engine-codex/issues"
|
|
20
|
+
},
|
|
21
|
+
"type": "module",
|
|
22
|
+
"main": "./dist/index.js",
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"openbee.plugin.json"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=20"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public",
|
|
32
|
+
"registry": "https://registry.npmjs.org/"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"build": "tsc -p tsconfig.json",
|
|
36
|
+
"test": "node --test test/*.test.mjs",
|
|
37
|
+
"prepare": "npm run build"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@theopenbee/engine-sdk": "file:../engine-sdk"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@types/node": "^22.10.0",
|
|
44
|
+
"typescript": "^5.7.0"
|
|
45
|
+
}
|
|
46
|
+
}
|