codex-grok-bridge 1.8.0 → 1.8.2
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/CHANGELOG.md +11 -0
- package/README.md +50 -2
- package/package.json +1 -1
- package/scripts/codex-wrapper.mjs +22 -9
- package/scripts/install-codex-grok-app.ps1 +30 -0
- package/scripts/install-codex-grok-app.sh +26 -0
- package/src/rollout.mjs +137 -0
- package/src/tools.mjs +99 -2
- package/src/voice.mjs +51 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.8.2 — 2026-10-06
|
|
4
|
+
|
|
5
|
+
- Tracked Codex CLI is 0.160.1 (https://github.com/openai/codex/releases/tag/rust-v0.160.1). No protocol change.
|
|
6
|
+
|
|
7
|
+
## 1.8.1 — 2026-10-03
|
|
8
|
+
|
|
9
|
+
- Grok reasoning ciphertext is removed from the stream back to Codex, so a later switch to an OpenAI model does not try to decrypt a Grok reasoning blob. This was already on main after 1.8.0 and was not in the 1.8.0 npm tarball.
|
|
10
|
+
- The Linux and Windows installers install `opusscript@0.1.1` and `werift@0.24.4` into the bridge directory.
|
|
11
|
+
- App-server startup survives a missing voice package. `opusscript` and `werift` load with dynamic import, so a missing module does not exit before Codex reads organization settings.
|
|
12
|
+
- Local JSON Schema `$ref` values (`#/$defs` and `#/definitions`) are inlined before tool parameters are sent to Grok.
|
|
13
|
+
|
|
3
14
|
## 1.8.0 — 2026-10-02
|
|
4
15
|
|
|
5
16
|
- When xAI rejects a Codex voice offer on `POST /v1/realtime/calls` or `POST /v1/live`, the bridge reads the SDP part of the multipart body, whether the parts use CRLF or LF, and answers locally with werift. Opus is used when that is the offered codec. Audio is bridged to the xAI voice socket. The sideband for that answered call stays on the bridge. An offer the local peer cannot answer stays the upstream response. An offer xAI accepts is still forwarded. Codex cloud tasks are not in this package.
|
package/README.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# codex-grok-bridge
|
|
2
2
|
|
|
3
|
+
The Codex weekly limit is spent. Grok is still there.
|
|
4
|
+
The harness stays. Only the model changes.
|
|
5
|
+
|
|
6
|
+
When the limit stops you, switch the model to Grok 4.7 and continue the same thread.
|
|
7
|
+
Tools, sandbox, MCP, and the thread stay with Codex. Inference uses the Grok subscription.
|
|
8
|
+
No API key. One `grok login`. The second subscription after the weekly allowance is gone.
|
|
9
|
+
|
|
10
|
+
The stock app stays untouched. Another window opens.
|
|
11
|
+
On the rest of a week blocked on GPT, switch to Grok and keep committing in the same repo.
|
|
12
|
+
Same repo, same permissions, different model. From then on you spend the Grok subscription allowance.
|
|
13
|
+
Don't buy credits. Use the SuperGrok you already have, inside Codex.
|
|
14
|
+
Inference goes to xAI. Tools, permissions, and threads stay with Codex.
|
|
15
|
+
|
|
3
16
|
Run **Grok 4.7 as the model inside Codex**. Codex still owns tools, permissions,
|
|
4
17
|
history and MCP. `grok-4.6` stays on the model list so existing threads still
|
|
5
18
|
resolve. Inference uses the installed `grok` CLI login session — not an
|
|
@@ -42,6 +55,17 @@ the bridge runs. See Release history.
|
|
|
42
55
|
|
|
43
56
|
What each recent version added. Older cuts are in `CHANGELOG.md`.
|
|
44
57
|
|
|
58
|
+
### 1.8.2 — 2026-10-06
|
|
59
|
+
|
|
60
|
+
- Tracked Codex CLI is 0.160.1 (https://github.com/openai/codex/releases/tag/rust-v0.160.1). No protocol change.
|
|
61
|
+
|
|
62
|
+
### 1.8.1 — 2026-10-03
|
|
63
|
+
|
|
64
|
+
- Grok reasoning ciphertext is removed from the stream back to Codex, so a later switch to an OpenAI model does not try to decrypt a Grok reasoning blob. This was already on main after 1.8.0 and was not in the 1.8.0 npm tarball.
|
|
65
|
+
- The Linux and Windows installers install `opusscript@0.1.1` and `werift@0.24.4` into the bridge directory.
|
|
66
|
+
- App-server startup survives a missing voice package. `opusscript` and `werift` load with dynamic import, so a missing module does not exit before Codex reads organization settings.
|
|
67
|
+
- Local JSON Schema `$ref` values (`#/$defs` and `#/definitions`) are inlined before tool parameters are sent to Grok.
|
|
68
|
+
|
|
45
69
|
### 1.8.0 — 2026-10-02
|
|
46
70
|
|
|
47
71
|
- When xAI rejects a Codex voice offer, the bridge reads the SDP part of the multipart body (CRLF or LF) and answers locally with werift, including Opus when that is the offered codec. Audio is bridged to the xAI voice socket, and that call's sideband stays on the bridge. An offer xAI accepts is still forwarded. Codex cloud tasks are not in this package.
|
|
@@ -233,7 +257,7 @@ multi-call turn can continue its own reasoning. The upstream has been observed
|
|
|
233
257
|
to accept this shape. The same pass keeps only the fields Grok’s Responses
|
|
234
258
|
input accepts on each item and content part — `status`, unknown Codex keys,
|
|
235
259
|
and every `internal_*` field are dropped so a new client field cannot 422 the
|
|
236
|
-
upstream.
|
|
260
|
+
upstream. The same ciphertext is removed from the stream back to Codex, so a later switch to an OpenAI model does not try to decrypt a Grok reasoning blob. A thread that already stored those items still has them.
|
|
237
261
|
|
|
238
262
|
### Concurrency
|
|
239
263
|
|
|
@@ -431,6 +455,19 @@ responses. Codex’s and Grok’s own retention policies still apply.
|
|
|
431
455
|
|
|
432
456
|
# 한국어
|
|
433
457
|
|
|
458
|
+
Codex 위클리는 끝났고, Grok은 남아 있다.
|
|
459
|
+
하네스는 그대로 두고, 머리만 바꾼다.
|
|
460
|
+
|
|
461
|
+
한도가 막히면 모델을 Grok 4.7로 바꿔 같은 스레드를 이어갑니다.
|
|
462
|
+
도구, 샌드박스, MCP, 스레드는 Codex가 그대로 둡니다. 추론만 Grok 구독입니다.
|
|
463
|
+
API 키는 없습니다. `grok login` 한 번이면 됩니다. 위클리가 빈 뒤의 두 번째 구독입니다.
|
|
464
|
+
|
|
465
|
+
앱은 건드리지 않습니다. 창만 하나 더 엽니다.
|
|
466
|
+
GPT로 막힌 주의 나머지 날은, Grok으로 바꿔 같은 레포에서 커밋을 이어갑니다.
|
|
467
|
+
같은 레포, 같은 권한, 다른 모델. 그때부터는 Grok 구독 한도를 씁니다.
|
|
468
|
+
크레딧을 사지 않습니다. 남아 있는 SuperGrok을 Codex 안에서 씁니다.
|
|
469
|
+
추론은 xAI로 가고, 도구와 권한과 스레드는 Codex에 남습니다.
|
|
470
|
+
|
|
434
471
|
## 이게 뭔가
|
|
435
472
|
|
|
436
473
|
Grok 4.7을 Codex 모델 목록에 넣고, Codex의 `/v1/responses`를
|
|
@@ -455,6 +492,17 @@ Codex `web_search`는 브리지가 실행하는 함수가 아니라 xAI 서버
|
|
|
455
492
|
|
|
456
493
|
최근 버전이 더한 것입니다. 그 이전은 `CHANGELOG.md`에 있습니다.
|
|
457
494
|
|
|
495
|
+
### 1.8.2 — 2026-10-06
|
|
496
|
+
|
|
497
|
+
- 추적하는 Codex CLI는 0.160.1입니다 (https://github.com/openai/codex/releases/tag/rust-v0.160.1). 프로토콜 변경은 없습니다.
|
|
498
|
+
|
|
499
|
+
### 1.8.1 — 2026-10-03
|
|
500
|
+
|
|
501
|
+
- Grok reasoning 암호문을 Codex로 돌아가는 스트림에서 빼서, 나중에 OpenAI 모델로 바꿔도 Grok reasoning blob을 복호화하려 하지 않습니다. 이 변경은 1.8.0 이후 main에 있었고 1.8.0 npm 패키지에는 없었습니다.
|
|
502
|
+
- Linux와 Windows 설치 스크립트가 `opusscript@0.1.1`과 `werift@0.24.4`를 브리지 디렉터리에 설치합니다.
|
|
503
|
+
- 음성 패키지가 없어도 앱 서버가 뜹니다. `opusscript`와 `werift`는 dynamic import로 불러서, 모듈이 없어도 Codex가 organization settings를 읽기 전에 프로세스가 나가지 않습니다.
|
|
504
|
+
- 로컬 JSON Schema `$ref`(`#/$defs`, `#/definitions`)는 도구 파라미터를 Grok에 보내기 전에 풀어 넣습니다.
|
|
505
|
+
|
|
458
506
|
### 1.8.0 — 2026-10-02
|
|
459
507
|
|
|
460
508
|
- xAI가 Codex 음성 offer를 거절하면 브리지가 multipart 본문의 SDP를 읽습니다. 파트 구분이 CRLF든 LF든 같습니다. werift로 로컬에서 답하고, offer가 Opus이면 Opus로 답합니다. 오디오는 xAI 음성 소켓으로 잇고, 그 통화의 sideband는 브리지에 남습니다. xAI가 수락한 offer는 그대로 넘깁니다. Codex 클라우드 작업은 이 패키지에 없습니다.
|
|
@@ -636,7 +684,7 @@ Codex `reasoning` 항목의 평문 요약은 상류로 전달합니다. 요약
|
|
|
636
684
|
턴에서 모델이 자기 추론을 이어받게 하기 위한 것이며, 상류가 이 형태를 수락하는
|
|
637
685
|
것을 확인했습니다. 같은 과정에서 아이템과 content part는 Grok Responses가
|
|
638
686
|
받는 필드만 남깁니다. `status`, 알 수 없는 Codex 키, `internal_*` 필드는
|
|
639
|
-
버려서 새 클라이언트 필드가 상류 422를 내지 않게 합니다.
|
|
687
|
+
버려서 새 클라이언트 필드가 상류 422를 내지 않게 합니다. 응답으로 돌아가는 암호문도 빼서, 나중에 OpenAI 모델로 바꿔도 Grok 추론 blob을 복호화하려 하지 않습니다. 이미 저장된 스레드는 그 항목이 남아 있습니다.
|
|
640
688
|
|
|
641
689
|
### 동시성
|
|
642
690
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codex-grok-bridge",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.2",
|
|
4
4
|
"description": "Run Grok 4.7 as the model inside Codex, with Codex still owning tools, permissions, history and MCP. Uses the grok login session, not an API key.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -5,16 +5,23 @@ import { randomUUID } from "node:crypto";
|
|
|
5
5
|
import { startRuntime } from "../src/runtime.mjs";
|
|
6
6
|
import { Router } from "../src/router.mjs";
|
|
7
7
|
import { resolveCodexBinary } from "../src/paths.mjs";
|
|
8
|
+
import { codexHomeFromEnv, migrateResumePath, migrateSessionRollouts } from "../src/rollout.mjs";
|
|
8
9
|
|
|
9
10
|
const binary = resolveCodexBinary();
|
|
10
11
|
const args = process.argv.slice(2);
|
|
12
|
+
function spawnResolved(file, fileArgs, options) {
|
|
13
|
+
if (file.endsWith(".mjs"))
|
|
14
|
+
return spawn(process.execPath, [file, ...fileArgs], options);
|
|
15
|
+
return spawn(file, fileArgs, options);
|
|
16
|
+
}
|
|
11
17
|
if (!args.includes("app-server")) {
|
|
12
|
-
const child =
|
|
18
|
+
const child = spawnResolved(binary, args, { stdio: "inherit" });
|
|
13
19
|
child.on("exit", (code) => process.exit(code ?? 1));
|
|
14
20
|
} else {
|
|
15
21
|
const runtime = await startRuntime();
|
|
16
22
|
const router = new Router(runtime.catalogPath);
|
|
17
|
-
|
|
23
|
+
await migrateSessionRollouts(codexHomeFromEnv());
|
|
24
|
+
const child = spawnResolved(binary, [...args, ...runtime.args], {
|
|
18
25
|
stdio: ["pipe", "pipe", "inherit"],
|
|
19
26
|
env: { ...process.env, CODEX_GROK_BRIDGE_TOKEN: runtime.token },
|
|
20
27
|
});
|
|
@@ -23,7 +30,10 @@ if (!args.includes("app-server")) {
|
|
|
23
30
|
const pending = new Map();
|
|
24
31
|
const timedOut = new Set();
|
|
25
32
|
const queues = new Map();
|
|
26
|
-
const write = (message) =>
|
|
33
|
+
const write = async (message) => {
|
|
34
|
+
await migrateResumePath(message);
|
|
35
|
+
child.stdin.write(JSON.stringify(router.outgoing(message)) + "\n");
|
|
36
|
+
};
|
|
27
37
|
const rpc = (method, params) => new Promise((resolve, reject) => {
|
|
28
38
|
const id = `grok-bridge-${randomUUID()}`;
|
|
29
39
|
const timer = setTimeout(() => {
|
|
@@ -36,7 +46,12 @@ if (!args.includes("app-server")) {
|
|
|
36
46
|
clearTimeout(timer);
|
|
37
47
|
message.error ? reject(new Error(message.error.message)) : resolve(message.result);
|
|
38
48
|
});
|
|
39
|
-
write({ id, method, params })
|
|
49
|
+
write({ id, method, params }).catch((error) => {
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
pending.delete(id);
|
|
52
|
+
router.pending.delete(id);
|
|
53
|
+
reject(error);
|
|
54
|
+
});
|
|
40
55
|
});
|
|
41
56
|
const input = createInterface({ input: process.stdin });
|
|
42
57
|
input.on("line", (line) => {
|
|
@@ -49,19 +64,17 @@ if (!args.includes("app-server")) {
|
|
|
49
64
|
}
|
|
50
65
|
const threadId = message.method && message.params?.threadId;
|
|
51
66
|
if (!threadId) {
|
|
52
|
-
|
|
53
|
-
write(message);
|
|
54
|
-
} catch {
|
|
67
|
+
write(message).catch(() => {
|
|
55
68
|
process.stderr.write("Grok wrapper: app-server is not writable\n");
|
|
56
69
|
if (message.id !== undefined)
|
|
57
70
|
send({ id: message.id, error: { code: -32603, message: "app-server is not writable" } });
|
|
58
|
-
}
|
|
71
|
+
});
|
|
59
72
|
return;
|
|
60
73
|
}
|
|
61
74
|
const next = (queues.get(threadId) ?? Promise.resolve())
|
|
62
75
|
.then(async () => {
|
|
63
76
|
await router.prepare(message, rpc);
|
|
64
|
-
write(message);
|
|
77
|
+
await write(message);
|
|
65
78
|
})
|
|
66
79
|
.catch((error) => {
|
|
67
80
|
if (message.id !== undefined)
|
|
@@ -52,6 +52,36 @@ function Resolve-NodeExe {
|
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
$Node = Resolve-NodeExe
|
|
55
|
+
$npm = Join-Path (Split-Path -Parent $Node) "npm.cmd"
|
|
56
|
+
if (-not (Test-Path -LiteralPath $npm)) {
|
|
57
|
+
$npmSh = Join-Path (Split-Path -Parent $Node) "npm"
|
|
58
|
+
if (Test-Path -LiteralPath $npmSh) { $npm = $npmSh }
|
|
59
|
+
else {
|
|
60
|
+
$npmCmd = Get-Command npm -ErrorAction SilentlyContinue
|
|
61
|
+
if ($npmCmd -and $npmCmd.Source) { $npm = $npmCmd.Source }
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (-not $npm -or -not (Test-Path -LiteralPath $npm)) {
|
|
65
|
+
Write-Error "no npm on PATH; voice packages were not installed"
|
|
66
|
+
}
|
|
67
|
+
@"
|
|
68
|
+
{
|
|
69
|
+
"name": "codex-grok-bridge-runtime",
|
|
70
|
+
"private": true,
|
|
71
|
+
"dependencies": {
|
|
72
|
+
"opusscript": "0.1.1",
|
|
73
|
+
"werift": "0.24.4"
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
"@ | Set-Content -Path (Join-Path $App "package.json") -Encoding ASCII
|
|
77
|
+
Push-Location $App
|
|
78
|
+
try {
|
|
79
|
+
& $npm install --omit=dev --no-fund --no-audit
|
|
80
|
+
if ($LASTEXITCODE -ne 0) { Write-Error "npm install of opusscript and werift failed" }
|
|
81
|
+
} finally {
|
|
82
|
+
Pop-Location
|
|
83
|
+
}
|
|
84
|
+
|
|
55
85
|
$Launcher = Join-Path $App "codex-grok-desktop.cmd"
|
|
56
86
|
@"
|
|
57
87
|
@echo off
|
|
@@ -94,6 +94,32 @@ for dir in scripts src; do
|
|
|
94
94
|
done
|
|
95
95
|
[ "$status" -eq 0 ] || { echo "bundle did not match the checkout" >&2; exit 1; }
|
|
96
96
|
|
|
97
|
+
install_voice_runtime() {
|
|
98
|
+
node_bin="${NODE:-$(command -v node || true)}"
|
|
99
|
+
[ -n "$node_bin" ] || { echo "no node on PATH; set NODE=/path/to/node" >&2; exit 1; }
|
|
100
|
+
npm_bin=""
|
|
101
|
+
node_dir="$(dirname "$node_bin")"
|
|
102
|
+
if [ -x "$node_dir/npm" ]; then
|
|
103
|
+
npm_bin="$node_dir/npm"
|
|
104
|
+
elif command -v npm >/dev/null 2>&1; then
|
|
105
|
+
npm_bin="$(command -v npm)"
|
|
106
|
+
fi
|
|
107
|
+
[ -n "$npm_bin" ] || { echo "no npm on PATH; voice packages were not installed" >&2; exit 1; }
|
|
108
|
+
cat > "$BRIDGE/package.json" <<'EOF'
|
|
109
|
+
{
|
|
110
|
+
"name": "codex-grok-bridge-runtime",
|
|
111
|
+
"private": true,
|
|
112
|
+
"dependencies": {
|
|
113
|
+
"opusscript": "0.1.1",
|
|
114
|
+
"werift": "0.24.4"
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
EOF
|
|
118
|
+
(cd "$BRIDGE" && "$npm_bin" install --omit=dev --no-fund --no-audit)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
install_voice_runtime
|
|
122
|
+
|
|
97
123
|
write_linux_wrapper() {
|
|
98
124
|
NODE="${NODE:-$(command -v node || true)}"
|
|
99
125
|
[ -n "$NODE" ] || { echo "no node on PATH; set NODE=/path/to/node" >&2; exit 1; }
|
package/src/rollout.mjs
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { isDeepStrictEqual } from "node:util";
|
|
5
|
+
import { stripEncryptedReasoning } from "./tools.mjs";
|
|
6
|
+
|
|
7
|
+
export function codexHomeFromEnv(env = process.env, home = homedir()) {
|
|
8
|
+
return env.CODEX_HOME || path.join(home, ".codex");
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function isSkippedHistoryPath(file) {
|
|
12
|
+
const resolved = path.resolve(file);
|
|
13
|
+
const parts = resolved.split(path.sep);
|
|
14
|
+
return parts.includes(".grok") || path.basename(resolved) === "auth.json";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function recordedProvider(record) {
|
|
18
|
+
if (!record || typeof record !== "object" || Array.isArray(record)) return null;
|
|
19
|
+
const modelProvider = typeof record.model_provider === "string" ? record.model_provider : "";
|
|
20
|
+
const model = typeof record.model === "string" ? record.model : "";
|
|
21
|
+
if (modelProvider === "grok_build_cli" || model.startsWith("grok-")) return "grok_build_cli";
|
|
22
|
+
return modelProvider || null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// session_meta sets the provider from model_provider. A later line that names
|
|
26
|
+
// grok_build_cli, or a model starting with grok-, switches to Grok. Anything
|
|
27
|
+
// else, including unknown, is not Grok.
|
|
28
|
+
function providerAfter(current, value) {
|
|
29
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return current;
|
|
30
|
+
const payload =
|
|
31
|
+
value.payload && typeof value.payload === "object" && !Array.isArray(value.payload)
|
|
32
|
+
? value.payload
|
|
33
|
+
: null;
|
|
34
|
+
if (value.type === "session_meta") {
|
|
35
|
+
const provider = payload && typeof payload.model_provider === "string" ? payload.model_provider : "";
|
|
36
|
+
return provider || current;
|
|
37
|
+
}
|
|
38
|
+
return recordedProvider(payload) ?? recordedProvider(value) ?? current;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function isGrokProvider(provider) {
|
|
42
|
+
return provider === "grok_build_cli" || (typeof provider === "string" && provider.startsWith("grok-"));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Lines with no ciphertext stay the original string, including non-JSON lines.
|
|
46
|
+
// OpenAI and unknown items keep encrypted_content. The file is rewritten only
|
|
47
|
+
// when a Grok item actually loses a ciphertext field.
|
|
48
|
+
export function rewriteRolloutText(text) {
|
|
49
|
+
if (!text.includes("encrypted_content") && !text.includes("encrypted_function_args"))
|
|
50
|
+
return text;
|
|
51
|
+
const lines = text.split("\n");
|
|
52
|
+
let provider = null;
|
|
53
|
+
let changed = false;
|
|
54
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
55
|
+
const line = lines[i];
|
|
56
|
+
if (!line) continue;
|
|
57
|
+
let value;
|
|
58
|
+
try {
|
|
59
|
+
value = JSON.parse(line);
|
|
60
|
+
} catch {
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
provider = providerAfter(provider, value);
|
|
64
|
+
if (!isGrokProvider(provider)) continue;
|
|
65
|
+
const copy = structuredClone(value);
|
|
66
|
+
stripEncryptedReasoning(copy);
|
|
67
|
+
if (isDeepStrictEqual(value, copy)) continue;
|
|
68
|
+
lines[i] = JSON.stringify(copy);
|
|
69
|
+
changed = true;
|
|
70
|
+
}
|
|
71
|
+
return changed ? lines.join("\n") : text;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function migrateRolloutFile(file) {
|
|
75
|
+
if (typeof file !== "string" || !file || isSkippedHistoryPath(file)) return false;
|
|
76
|
+
let first;
|
|
77
|
+
try {
|
|
78
|
+
first = await readFile(file);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (error.code === "ENOENT") return false;
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
const next = rewriteRolloutText(first.toString("utf8"));
|
|
84
|
+
if (next === first.toString("utf8")) return false;
|
|
85
|
+
const mode = (await stat(file)).mode & 0o777;
|
|
86
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
87
|
+
await writeFile(tmp, next, { mode });
|
|
88
|
+
const again = await readFile(file);
|
|
89
|
+
if (!again.equals(first)) {
|
|
90
|
+
await rm(tmp, { force: true });
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
await rename(tmp, file);
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function walkRollouts(dir, visit) {
|
|
98
|
+
let entries;
|
|
99
|
+
try {
|
|
100
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (error.code === "ENOENT") return;
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
for (const entry of entries) {
|
|
106
|
+
if (entry.name === "auth.json" || entry.name === ".grok") continue;
|
|
107
|
+
const full = path.join(dir, entry.name);
|
|
108
|
+
if (entry.isSymbolicLink()) continue;
|
|
109
|
+
if (entry.isDirectory()) await walkRollouts(full, visit);
|
|
110
|
+
else if (
|
|
111
|
+
entry.isFile() &&
|
|
112
|
+
entry.name.startsWith("rollout-") &&
|
|
113
|
+
entry.name.endsWith(".jsonl")
|
|
114
|
+
)
|
|
115
|
+
await visit(full);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function migrateSessionRollouts(codexHome) {
|
|
120
|
+
if (isSkippedHistoryPath(codexHome)) return;
|
|
121
|
+
const sessions = path.join(path.resolve(codexHome), "sessions");
|
|
122
|
+
await walkRollouts(sessions, async (file) => {
|
|
123
|
+
try {
|
|
124
|
+
await migrateRolloutFile(file);
|
|
125
|
+
} catch {
|
|
126
|
+
process.stderr.write("Grok wrapper: could not rewrite a rollout\n");
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export async function migrateResumePath(message) {
|
|
132
|
+
const method = message?.method;
|
|
133
|
+
const file = message?.params?.path;
|
|
134
|
+
if (method !== "thread/resume" && method !== "thread/fork") return false;
|
|
135
|
+
if (typeof file !== "string" || !file) return false;
|
|
136
|
+
return migrateRolloutFile(file);
|
|
137
|
+
}
|
package/src/tools.mjs
CHANGED
|
@@ -163,22 +163,100 @@ function emitObjectParameters(source, overrides = {}) {
|
|
|
163
163
|
return next;
|
|
164
164
|
}
|
|
165
165
|
|
|
166
|
+
function decodeJsonPointerToken(token) {
|
|
167
|
+
return token.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// `#/$defs/Name` and `#/definitions/Name` are document-local. Grok rejects
|
|
171
|
+
// those pointers, so the copy sent upstream has the target schema inlined.
|
|
172
|
+
function definitionPointer(ref) {
|
|
173
|
+
if (typeof ref !== "string" || !ref.startsWith("#/")) return null;
|
|
174
|
+
const tokens = ref.slice(2).split("/").map(decodeJsonPointerToken);
|
|
175
|
+
if (tokens.length < 2) return null;
|
|
176
|
+
if (tokens[0] !== "$defs" && tokens[0] !== "definitions") return null;
|
|
177
|
+
return tokens;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function readPointer(root, tokens) {
|
|
181
|
+
let node = root;
|
|
182
|
+
for (const token of tokens) {
|
|
183
|
+
if (Array.isArray(node)) {
|
|
184
|
+
if (!/^(0|[1-9]\d*)$/.test(token)) return undefined;
|
|
185
|
+
node = node[Number(token)];
|
|
186
|
+
} else if (
|
|
187
|
+
plainObject(node) &&
|
|
188
|
+
Object.prototype.hasOwnProperty.call(node, token)
|
|
189
|
+
) {
|
|
190
|
+
node = node[token];
|
|
191
|
+
} else {
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return node;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function inlineLocalSchemaRefs(schema) {
|
|
199
|
+
function resolve(ref, trail) {
|
|
200
|
+
const tokens = definitionPointer(ref);
|
|
201
|
+
if (!tokens || trail.includes(ref))
|
|
202
|
+
throw new Error(`Unresolvable schema $ref: ${ref}`);
|
|
203
|
+
const target = readPointer(schema, tokens);
|
|
204
|
+
if (target === undefined)
|
|
205
|
+
throw new Error(`Unresolvable schema $ref: ${ref}`);
|
|
206
|
+
return walk(structuredClone(target), trail.concat(ref));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function walk(node, trail) {
|
|
210
|
+
if (Array.isArray(node)) return node.map((item) => walk(item, trail));
|
|
211
|
+
if (!plainObject(node)) return node;
|
|
212
|
+
if (Object.prototype.hasOwnProperty.call(node, "$ref")) {
|
|
213
|
+
if (typeof node.$ref !== "string")
|
|
214
|
+
throw new Error("Unresolvable schema $ref");
|
|
215
|
+
const resolved = resolve(node.$ref, trail);
|
|
216
|
+
const rest = {};
|
|
217
|
+
for (const [key, value] of Object.entries(node)) {
|
|
218
|
+
if (key !== "$ref") rest[key] = value;
|
|
219
|
+
}
|
|
220
|
+
if (Object.keys(rest).length === 0) return resolved;
|
|
221
|
+
if (!plainObject(resolved))
|
|
222
|
+
throw new Error(`Unresolvable schema $ref: ${node.$ref}`);
|
|
223
|
+
return walk({ ...resolved, ...rest }, trail);
|
|
224
|
+
}
|
|
225
|
+
const next = {};
|
|
226
|
+
for (const [key, value] of Object.entries(node)) {
|
|
227
|
+
if (key === "$defs" || key === "definitions") continue;
|
|
228
|
+
next[key] = walk(value, trail);
|
|
229
|
+
}
|
|
230
|
+
return next;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return walk(schema, []);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function emitsObjectParameters(schema) {
|
|
237
|
+
return (
|
|
238
|
+
schema.type === "object" ||
|
|
239
|
+
(schema.type == null && plainObject(schema.properties))
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
166
243
|
function usableParameters(parameters) {
|
|
167
244
|
if (!parameters || typeof parameters !== "object" || Array.isArray(parameters))
|
|
168
245
|
return OBJECT_SCHEMA;
|
|
246
|
+
parameters = inlineLocalSchemaRefs(parameters);
|
|
169
247
|
const variants = Array.isArray(parameters.oneOf)
|
|
170
248
|
? parameters.oneOf
|
|
171
249
|
: Array.isArray(parameters.anyOf)
|
|
172
250
|
? parameters.anyOf
|
|
173
251
|
: null;
|
|
174
252
|
if (!variants) {
|
|
175
|
-
return parameters
|
|
253
|
+
return emitsObjectParameters(parameters)
|
|
176
254
|
? emitObjectParameters(parameters)
|
|
177
255
|
: OBJECT_SCHEMA;
|
|
178
256
|
}
|
|
179
257
|
const fragments = variants.filter(isObjectFragment);
|
|
180
258
|
if (fragments.length === 0) {
|
|
181
|
-
return parameters
|
|
259
|
+
return emitsObjectParameters(parameters)
|
|
182
260
|
? emitObjectParameters(parameters)
|
|
183
261
|
: OBJECT_SCHEMA;
|
|
184
262
|
}
|
|
@@ -879,6 +957,24 @@ function originForResponseName(map, name) {
|
|
|
879
957
|
return found;
|
|
880
958
|
}
|
|
881
959
|
|
|
960
|
+
// Grok ciphertext is not an OpenAI reasoning blob. If Codex stores it, a later
|
|
961
|
+
// switch to an OpenAI model fails with "could not be decrypted or parsed".
|
|
962
|
+
export function stripEncryptedReasoning(node) {
|
|
963
|
+
if (!node || typeof node !== "object") return;
|
|
964
|
+
if (Array.isArray(node)) {
|
|
965
|
+
for (let i = node.length - 1; i >= 0; i -= 1) {
|
|
966
|
+
const part = node[i];
|
|
967
|
+
if (part && typeof part === "object" && part.type === "encrypted_content")
|
|
968
|
+
node.splice(i, 1);
|
|
969
|
+
else stripEncryptedReasoning(part);
|
|
970
|
+
}
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
delete node.encrypted_content;
|
|
974
|
+
delete node.encrypted_function_args;
|
|
975
|
+
for (const value of Object.values(node)) stripEncryptedReasoning(value);
|
|
976
|
+
}
|
|
977
|
+
|
|
882
978
|
function rewriteResponseItem(node, map, state) {
|
|
883
979
|
if (!node || typeof node !== "object") return;
|
|
884
980
|
const origin =
|
|
@@ -930,6 +1026,7 @@ const USAGE_EVENTS = new Set(["response.completed", "response.incomplete"]);
|
|
|
930
1026
|
|
|
931
1027
|
function rewriteResponseEvent(value, map, state) {
|
|
932
1028
|
if (!value || typeof value !== "object") return value;
|
|
1029
|
+
stripEncryptedReasoning(value);
|
|
933
1030
|
if (
|
|
934
1031
|
USAGE_EVENTS.has(value.type) &&
|
|
935
1032
|
value.response &&
|
package/src/voice.mjs
CHANGED
|
@@ -1,13 +1,51 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
2
|
+
|
|
3
|
+
let OpusScript;
|
|
4
|
+
let MediaStreamTrack;
|
|
5
|
+
let RTCPeerConnection;
|
|
6
|
+
let RtpHeader;
|
|
7
|
+
let RtpPacket;
|
|
8
|
+
let useOPUS;
|
|
9
|
+
let usePCMU;
|
|
10
|
+
let voicePackagesError;
|
|
11
|
+
|
|
12
|
+
try {
|
|
13
|
+
const opusMod = await import("opusscript");
|
|
14
|
+
const weriftMod = await import("werift");
|
|
15
|
+
OpusScript = opusMod.default ?? opusMod;
|
|
16
|
+
({ MediaStreamTrack, RTCPeerConnection, RtpHeader, RtpPacket, useOPUS, usePCMU } = weriftMod);
|
|
17
|
+
if (
|
|
18
|
+
typeof OpusScript !== "function" ||
|
|
19
|
+
typeof MediaStreamTrack !== "function" ||
|
|
20
|
+
typeof RTCPeerConnection !== "function" ||
|
|
21
|
+
typeof RtpHeader !== "function" ||
|
|
22
|
+
typeof RtpPacket !== "function" ||
|
|
23
|
+
typeof useOPUS !== "function" ||
|
|
24
|
+
typeof usePCMU !== "function"
|
|
25
|
+
) {
|
|
26
|
+
throw new Error("opusscript or werift did not export the voice runtime");
|
|
27
|
+
}
|
|
28
|
+
} catch (error) {
|
|
29
|
+
OpusScript = undefined;
|
|
30
|
+
MediaStreamTrack = undefined;
|
|
31
|
+
RTCPeerConnection = undefined;
|
|
32
|
+
RtpHeader = undefined;
|
|
33
|
+
RtpPacket = undefined;
|
|
34
|
+
useOPUS = undefined;
|
|
35
|
+
usePCMU = undefined;
|
|
36
|
+
voicePackagesError = error;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function voicePackages() {
|
|
40
|
+
if (OpusScript && MediaStreamTrack && RTCPeerConnection && RtpHeader && RtpPacket && useOPUS && usePCMU) {
|
|
41
|
+
return { OpusScript, MediaStreamTrack, RTCPeerConnection, RtpHeader, RtpPacket, useOPUS, usePCMU };
|
|
42
|
+
}
|
|
43
|
+
const detail = voicePackagesError instanceof Error ? voicePackagesError.message : "missing";
|
|
44
|
+
throw new Error(
|
|
45
|
+
`Voice needs opusscript and werift installed in the bridge directory (${detail}). Re-run the Codex Grok installer.`,
|
|
46
|
+
voicePackagesError instanceof Error ? { cause: voicePackagesError } : undefined,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
11
49
|
|
|
12
50
|
export const VOICE_SOCKET_URL = "wss://api.x.ai/v1/realtime?model=grok-voice-latest";
|
|
13
51
|
|
|
@@ -25,6 +63,7 @@ const sessionsById = new Map();
|
|
|
25
63
|
const OPUS_FRAME = 960;
|
|
26
64
|
|
|
27
65
|
function peerConfig() {
|
|
66
|
+
const { useOPUS, usePCMU } = voicePackages();
|
|
28
67
|
return {
|
|
29
68
|
iceServers: [],
|
|
30
69
|
iceUseIpv4: true,
|
|
@@ -188,6 +227,7 @@ export function audioCodecFromSdp(sdp) {
|
|
|
188
227
|
}
|
|
189
228
|
|
|
190
229
|
function createOpus() {
|
|
230
|
+
const { OpusScript } = voicePackages();
|
|
191
231
|
return new OpusScript(48000, 2, OpusScript.Application.VOIP);
|
|
192
232
|
}
|
|
193
233
|
|
|
@@ -423,6 +463,7 @@ export function playoutGap(state, now) {
|
|
|
423
463
|
|
|
424
464
|
function writeAudio(track, state, payload, clockStep, forceMarker = false) {
|
|
425
465
|
if (payload.length === 0) return;
|
|
466
|
+
const { RtpHeader, RtpPacket } = voicePackages();
|
|
426
467
|
const now = Date.now();
|
|
427
468
|
const extra = playoutGap(state, now);
|
|
428
469
|
const sequence = (state.sequence + 1) & 0xffff;
|
|
@@ -1213,6 +1254,7 @@ export async function answerVoiceCall({
|
|
|
1213
1254
|
developerContext = "",
|
|
1214
1255
|
initialItems,
|
|
1215
1256
|
}) {
|
|
1257
|
+
const { MediaStreamTrack, RTCPeerConnection } = voicePackages();
|
|
1216
1258
|
const pc = new RTCPeerConnection(peerConfig());
|
|
1217
1259
|
const track = new MediaStreamTrack({ kind: "audio" });
|
|
1218
1260
|
let socket;
|