stitchkit 0.128.0 → 0.130.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/CHANGELOG.md +83 -0
- package/dist/agent-executor/acp/v1-connect.d.ts +87 -19
- package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-driver.d.ts +4 -2
- package/dist/agent-executor/acp/v1-driver.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-handlers.d.ts +56 -0
- package/dist/agent-executor/acp/v1-handlers.d.ts.map +1 -0
- package/dist/agent-executor/acp/v1-map.d.ts +13 -2
- package/dist/agent-executor/acp/v1-map.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-permission.d.ts +44 -0
- package/dist/agent-executor/acp/v1-permission.d.ts.map +1 -0
- package/dist/agent-executor/acp/v1-protocol.d.ts +63 -10
- package/dist/agent-executor/acp/v1-protocol.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-session.d.ts +34 -7
- package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
- package/dist/agent-executor/acp/v1-turn.d.ts +51 -13
- package/dist/agent-executor/acp/v1-turn.d.ts.map +1 -1
- package/dist/agent-executor/claude/classify.d.ts +10 -0
- package/dist/agent-executor/claude/classify.d.ts.map +1 -1
- package/dist/agent-executor/claude/cli-driver.d.ts +4 -1
- package/dist/agent-executor/claude/cli-driver.d.ts.map +1 -1
- package/dist/agent-executor/claude/events.d.ts +146 -0
- package/dist/agent-executor/claude/events.d.ts.map +1 -0
- package/dist/agent-executor/claude/limits.d.ts +7 -1
- package/dist/agent-executor/claude/limits.d.ts.map +1 -1
- package/dist/agent-executor/claude/protocol.d.ts +49 -9
- package/dist/agent-executor/claude/protocol.d.ts.map +1 -1
- package/dist/agent-executor/claude/session.d.ts +2 -0
- package/dist/agent-executor/claude/session.d.ts.map +1 -1
- package/dist/agent-executor/claude/transcript.d.ts +2 -2
- package/dist/agent-executor/claude/transcript.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/controls.d.ts +28 -0
- package/dist/agent-executor/claude-sdk/controls.d.ts.map +1 -0
- package/dist/agent-executor/claude-sdk/driver.d.ts +208 -4
- package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/probe.d.ts +29 -0
- package/dist/agent-executor/claude-sdk/probe.d.ts.map +1 -0
- package/dist/agent-executor/claude-sdk/query-loop.d.ts +94 -0
- package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -0
- package/dist/agent-executor/claude-sdk/query-options.d.ts +29 -0
- package/dist/agent-executor/claude-sdk/query-options.d.ts.map +1 -0
- package/dist/agent-executor/claude-sdk/session.d.ts +5 -5
- package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
- package/dist/agent-executor/claude-sdk/turn-usage.d.ts +81 -0
- package/dist/agent-executor/claude-sdk/turn-usage.d.ts.map +1 -0
- package/dist/agent-executor/codex/classify.d.ts +4 -0
- package/dist/agent-executor/codex/classify.d.ts.map +1 -1
- package/dist/agent-executor/codex/connect.d.ts +46 -0
- package/dist/agent-executor/codex/connect.d.ts.map +1 -0
- package/dist/agent-executor/codex/control-client.d.ts +168 -0
- package/dist/agent-executor/codex/control-client.d.ts.map +1 -0
- package/dist/agent-executor/codex/driver.d.ts +71 -10
- package/dist/agent-executor/codex/driver.d.ts.map +1 -1
- package/dist/agent-executor/codex/handlers.d.ts +47 -0
- package/dist/agent-executor/codex/handlers.d.ts.map +1 -0
- package/dist/agent-executor/codex/limits.d.ts +11 -2
- package/dist/agent-executor/codex/limits.d.ts.map +1 -1
- package/dist/agent-executor/codex/protocol.d.ts +173 -4
- package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
- package/dist/agent-executor/codex/request-answers.d.ts +101 -0
- package/dist/agent-executor/codex/request-answers.d.ts.map +1 -0
- package/dist/agent-executor/codex/session-controls.d.ts +195 -0
- package/dist/agent-executor/codex/session-controls.d.ts.map +1 -0
- package/dist/agent-executor/codex/session.d.ts +55 -37
- package/dist/agent-executor/codex/session.d.ts.map +1 -1
- package/dist/agent-executor/codex/shared-server.d.ts +29 -0
- package/dist/agent-executor/codex/shared-server.d.ts.map +1 -0
- package/dist/agent-executor/codex/shared-thread.d.ts +46 -0
- package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -0
- package/dist/agent-executor/codex/thread-controls.d.ts +128 -0
- package/dist/agent-executor/codex/thread-controls.d.ts.map +1 -0
- package/dist/agent-executor/codex/turn-input.d.ts +30 -0
- package/dist/agent-executor/codex/turn-input.d.ts.map +1 -0
- package/dist/agent-executor/codex/unix-socket-target.d.ts +26 -0
- package/dist/agent-executor/codex/unix-socket-target.d.ts.map +1 -0
- package/dist/agent-executor/codex/unix-socket.d.ts +26 -0
- package/dist/agent-executor/codex/unix-socket.d.ts.map +1 -0
- package/dist/agent-executor/codex/ws-frame.d.ts +15 -0
- package/dist/agent-executor/codex/ws-frame.d.ts.map +1 -0
- package/dist/agent-executor/contract.d.ts +79 -0
- package/dist/agent-executor/contract.d.ts.map +1 -1
- package/dist/agent-executor/engine-process.d.ts +9 -0
- package/dist/agent-executor/engine-process.d.ts.map +1 -1
- package/dist/agent-executor/engine.d.ts +6 -2
- package/dist/agent-executor/engine.d.ts.map +1 -1
- package/dist/agent-executor/executor-contract.d.ts +54 -0
- package/dist/agent-executor/executor-contract.d.ts.map +1 -1
- package/dist/agent-executor/handoff-schemas.d.ts +407 -0
- package/dist/agent-executor/handoff-schemas.d.ts.map +1 -0
- package/dist/agent-executor/handoff.d.ts +12 -0
- package/dist/agent-executor/handoff.d.ts.map +1 -0
- package/dist/agent-executor/hello.d.ts +80 -0
- package/dist/agent-executor/hello.d.ts.map +1 -1
- package/dist/agent-executor/image-input.d.ts +22 -0
- package/dist/agent-executor/image-input.d.ts.map +1 -1
- package/dist/agent-executor/projection.d.ts +2 -2
- package/dist/agent-executor/projection.d.ts.map +1 -1
- package/dist/agent-executor/session-primitives.d.ts +10 -1
- package/dist/agent-executor/session-primitives.d.ts.map +1 -1
- package/dist/agent-executor/testing/conformance.d.ts.map +1 -1
- package/dist/agent-executor/testing/replay-driver.d.ts +41 -0
- package/dist/agent-executor/testing/replay-driver.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-gate.d.ts +11 -0
- package/dist/agent-executor/testing/replay-gate.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-runner.d.ts +27 -0
- package/dist/agent-executor/testing/replay-runner.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-scenarios.d.ts +21 -0
- package/dist/agent-executor/testing/replay-scenarios.d.ts.map +1 -0
- package/dist/agent-executor/testing/replay-transcript.d.ts +296 -0
- package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -0
- package/dist/agent-executor/vocabulary.d.ts +135 -0
- package/dist/agent-executor/vocabulary.d.ts.map +1 -1
- package/dist/agent-runtime/branch-observations.d.ts +5 -5
- package/dist/agent-runtime/deferred-tool-selection.d.ts.map +1 -1
- package/dist/agent-runtime/sql-rows.d.ts +10 -10
- package/dist/agent-runtime/terminal-commit.d.ts +10 -10
- package/dist/entrypoints/agent-executor/acp.d.ts +4 -1
- package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/acp.js +852 -219
- package/dist/entrypoints/agent-executor/claude-sdk.d.ts +5 -1
- package/dist/entrypoints/agent-executor/claude-sdk.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/claude-sdk.js +1075 -136
- package/dist/entrypoints/agent-executor/claude.js +48 -23
- package/dist/entrypoints/agent-executor/codex.d.ts +11 -0
- package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/codex.js +3067 -388
- package/dist/entrypoints/agent-executor/testing.d.ts +4 -0
- package/dist/entrypoints/agent-executor/testing.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor/testing.js +1002 -2
- package/dist/entrypoints/agent-executor.d.ts +4 -2
- package/dist/entrypoints/agent-executor.d.ts.map +1 -1
- package/dist/entrypoints/agent-executor.js +416 -28
- package/dist/entrypoints/agent-runtime/browser.js +1 -1
- package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
- package/dist/entrypoints/agent-runtime/harness.js +8 -8
- package/dist/entrypoints/agent-runtime/openrouter.js +2 -2
- package/dist/entrypoints/agent-runtime/postgres.js +6 -6
- package/dist/entrypoints/agent-runtime/realtime.js +4 -4
- package/dist/entrypoints/agent-runtime/sandbox.js +5 -5
- package/dist/entrypoints/agent-runtime/sqlite/bun.js +6 -6
- package/dist/entrypoints/agent-runtime/sqlite/node.js +6 -6
- package/dist/entrypoints/agent-runtime/testing.js +5 -5
- package/dist/entrypoints/agent-runtime.js +21 -40
- package/dist/entrypoints/application/directory-inbox.js +2 -2
- package/dist/entrypoints/application/opentelemetry.js +2 -2
- package/dist/entrypoints/application.js +2 -2
- package/dist/entrypoints/cli/publish.js +3 -3
- package/dist/entrypoints/cli.js +8 -8
- package/dist/entrypoints/contract.js +2 -2
- package/dist/entrypoints/files/packaging.js +2 -2
- package/dist/entrypoints/files.js +7 -7
- package/dist/entrypoints/handler.js +4 -4
- package/dist/entrypoints/http.js +5 -5
- package/dist/entrypoints/index.js +7 -7
- package/dist/entrypoints/node.js +5 -5
- package/dist/entrypoints/observability.js +4 -4
- package/dist/entrypoints/primitives.js +2 -2
- package/dist/entrypoints/process.js +5 -5
- package/dist/entrypoints/react.js +1 -1
- package/dist/entrypoints/remote.js +2 -2
- package/dist/entrypoints/server.js +6 -6
- package/dist/entrypoints/service-host/macos.js +5 -5
- package/dist/entrypoints/service-host.js +7 -7
- package/dist/entrypoints/spend.js +1 -1
- package/dist/entrypoints/sync/postgres.js +1 -1
- package/dist/entrypoints/sync.js +2 -2
- package/dist/entrypoints/telegram.js +2 -2
- package/dist/entrypoints/testing.js +5 -5
- package/dist/entrypoints/tools/agent.js +5 -5
- package/dist/entrypoints/tools/connections.js +2 -2
- package/dist/entrypoints/tools/invoker.js +4 -4
- package/dist/entrypoints/tools/mcp.d.ts +1 -0
- package/dist/entrypoints/tools/mcp.d.ts.map +1 -1
- package/dist/entrypoints/tools/mcp.js +5 -5
- package/dist/entrypoints/tools/toolkit.js +8 -8
- package/dist/entrypoints/tools.js +12 -12
- package/dist/entrypoints/tracking/contract.js +1 -1
- package/dist/entrypoints/xlsx.js +1 -1
- package/dist/{index-prf6ayhf.js → index-13wmzpa6.js} +1 -1
- package/dist/{index-n7f89hjw.js → index-17qgm6xe.js} +3 -3
- package/dist/{index-wv8dqy7q.js → index-205456mf.js} +1 -1
- package/dist/{index-pwskmywy.js → index-21cfxc4z.js} +1 -1
- package/dist/{index-13dnv6d0.js → index-2s8sy57y.js} +37 -104
- package/dist/{index-d4svrknj.js → index-39c2hj6h.js} +2 -2
- package/dist/{index-sfzfd2m2.js → index-39rmc00v.js} +1 -1
- package/dist/{index-ky3ardqn.js → index-3fym4j8n.js} +1 -1
- package/dist/{index-c5gp2gh6.js → index-5tdc0q43.js} +1 -1
- package/dist/{index-3ypvpkwr.js → index-669374qc.js} +1 -1
- package/dist/{index-5jyjb4s0.js → index-80acsm27.js} +1 -1
- package/dist/{index-xmr47znh.js → index-827bgv33.js} +1 -1
- package/dist/{index-v1mxss62.js → index-93n6jwy0.js} +3 -3
- package/dist/{index-d54npte7.js → index-9kpxz49v.js} +2 -2
- package/dist/{index-xv9jb84s.js → index-9sfhje6y.js} +3 -3
- package/dist/{index-9y0afd5f.js → index-apf5g7y9.js} +1 -1
- package/dist/{index-bh4pmtr9.js → index-dbp6xemn.js} +78 -8
- package/dist/{index-g3e57qj6.js → index-dcsxj68j.js} +2 -2
- package/dist/{index-waa6t4zx.js → index-dnzxxf8a.js} +1 -1
- package/dist/{index-gf92hc87.js → index-fgahdc7s.js} +2 -2
- package/dist/{index-kzavdze2.js → index-gr0kxymw.js} +5 -1
- package/dist/{index-e06z0tkb.js → index-gya4hwh3.js} +2 -2
- package/dist/{index-gzny6zsw.js → index-hab790s6.js} +5 -5
- package/dist/{index-bz3gn6cs.js → index-j0ef04jw.js} +2 -2
- package/dist/{index-rhb33thr.js → index-jcge9tx3.js} +1 -1
- package/dist/{index-4qvyhn23.js → index-jrn3prgm.js} +1 -1
- package/dist/index-kne9g2c5.js +30 -0
- package/dist/{index-pn5b11ce.js → index-mkfhpk11.js} +1 -1
- package/dist/{index-1qwrczr1.js → index-mttkdm5a.js} +1 -1
- package/dist/{index-rxnyygke.js → index-n3bm7zqq.js} +1 -1
- package/dist/{index-6wp4dn9d.js → index-p06z7g7w.js} +3 -3
- package/dist/{index-kt6dh1n6.js → index-p16q492v.js} +1 -1
- package/dist/index-p1qmpq0p.js +1300 -0
- package/dist/{index-t7wa7k12.js → index-pp97q86a.js} +1 -1
- package/dist/{index-39n02e0q.js → index-psye60qn.js} +1 -1
- package/dist/{index-5ptwb6ka.js → index-pzhqydxb.js} +1 -1
- package/dist/{index-7kfcb576.js → index-qa2jjb65.js} +1 -1
- package/dist/{index-rzeezh79.js → index-qhjmmsm2.js} +2 -2
- package/dist/{index-7grgs8cx.js → index-qpzyahe3.js} +2 -2
- package/dist/{index-jfecdk1e.js → index-r97ppg0g.js} +2 -2
- package/dist/{index-bmaz3jzy.js → index-rjs94dny.js} +1 -1
- package/dist/{index-5v5vg85s.js → index-rxh3qy4x.js} +32 -5
- package/dist/{index-en8e5zsj.js → index-ryxb427v.js} +1 -1
- package/dist/{index-y065r8g5.js → index-sd4e5x5j.js} +7 -7
- package/dist/{index-g56ht6qf.js → index-t3qcac2a.js} +1 -1
- package/dist/{index-m18xm96h.js → index-v759mzed.js} +156 -6
- package/dist/{index-4j8efqr3.js → index-x2fb37t0.js} +2 -2
- package/dist/{index-cbhxhma2.js → index-x5ayy5bn.js} +1 -0
- package/dist/index-y0a4gt1s.js +142 -0
- package/dist/{index-wavv538x.js → index-ybdq8kk2.js} +3 -3
- package/dist/{index-4gk6k3zc.js → index-ycr4pk0z.js} +1 -1
- package/dist/{index-0tyt97nk.js → index-yrr3n391.js} +1 -1
- package/dist/{index-v37b2cd6.js → index-z20pdxeb.js} +2 -2
- package/dist/{index-8x22nprv.js → index-z9d74jmb.js} +3 -3
- package/dist/{index-3tnwtz38.js → index-zhshhxew.js} +1 -1
- package/dist/{index-hj1zq7mh.js → index-znd1b57f.js} +3 -3
- package/dist/internal/positive-integer.d.ts +2 -0
- package/dist/internal/positive-integer.d.ts.map +1 -1
- package/dist/internal/unix-socket.d.ts +7 -0
- package/dist/internal/unix-socket.d.ts.map +1 -1
- package/dist/tools/internal/rank-tools.d.ts +10 -0
- package/dist/tools/internal/rank-tools.d.ts.map +1 -0
- package/dist/tools/mcp/handler.d.ts +7 -3
- package/dist/tools/mcp/handler.d.ts.map +1 -1
- package/dist/tools/mcp/lazy-discovery.d.ts +47 -0
- package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -0
- package/dist/tools/mcp/mount.d.ts +7 -0
- package/dist/tools/mcp/mount.d.ts.map +1 -1
- package/dist/tools/mcp/register.d.ts +2 -2
- package/dist/tools/mcp/register.d.ts.map +1 -1
- package/llms/agent-executor-acp.txt +7 -8
- package/llms/agent-executor-claude-sdk.txt +15 -10
- package/llms/agent-executor-claude.txt +1 -1
- package/llms/agent-executor-codex.txt +13 -3
- package/llms/agent-executor-testing.txt +5 -1
- package/llms/agent-executor.txt +9 -8
- package/llms/stitchkit.txt +74 -74
- package/llms/tools-mcp.txt +3 -2
- package/llms/tools.txt +24 -0
- package/llms/{upgrading-0.128.0.txt → upgrading-0.128.0-0.130.0.txt} +58 -3
- package/llms/upgrading.txt +1 -1
- package/llms-full.txt +206 -107
- package/llms.txt +10 -10
- package/package.json +1 -1
- package/dist/index-0gqs8ght.js +0 -558
|
@@ -4,10 +4,10 @@ import {
|
|
|
4
4
|
PlanWindowSchema2,
|
|
5
5
|
engineProfile,
|
|
6
6
|
engineEnvironment2
|
|
7
|
-
} from "../../index-
|
|
7
|
+
} from "../../index-dbp6xemn.js";
|
|
8
8
|
import"../../index-09f7w2qq.js";
|
|
9
9
|
import"../../index-v59pxmf1.js";
|
|
10
|
-
import"../../index-
|
|
10
|
+
import"../../index-qa2jjb65.js";
|
|
11
11
|
import"../../index-6kec3b14.js";
|
|
12
12
|
import {
|
|
13
13
|
nonEmptyString,
|
|
@@ -19,119 +19,250 @@ import {
|
|
|
19
19
|
stopConnection,
|
|
20
20
|
withEphemeralConnection,
|
|
21
21
|
safeJsonValue,
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
invokeSafely,
|
|
23
|
+
emitStartupPhase,
|
|
24
|
+
clampUniqueWindowName,
|
|
24
25
|
holdEngineRequest,
|
|
25
26
|
answerEngineRequest,
|
|
26
27
|
drainEngineRequests,
|
|
27
28
|
endEngineTurn,
|
|
28
29
|
loseEngineTurn
|
|
29
|
-
} from "../../index-
|
|
30
|
+
} from "../../index-2s8sy57y.js";
|
|
31
|
+
import"../../index-673drwkn.js";
|
|
32
|
+
import"../../index-vmbxj75t.js";
|
|
30
33
|
import {
|
|
31
34
|
JsonRpcError2,
|
|
32
35
|
JSON_RPC_METHOD_NOT_FOUND2,
|
|
33
36
|
createJsonRpcPeer2
|
|
34
37
|
} from "../../index-1q0n6zek.js";
|
|
35
|
-
import
|
|
38
|
+
import {
|
|
39
|
+
validateImageOptions,
|
|
40
|
+
inlineOrderedParts,
|
|
41
|
+
guardedTurnStarter
|
|
42
|
+
} from "../../index-y0a4gt1s.js";
|
|
43
|
+
import"../../index-pzhqydxb.js";
|
|
36
44
|
import {
|
|
37
45
|
spawnEngineProcess2
|
|
38
|
-
} from "../../index-
|
|
39
|
-
import"../../index-
|
|
46
|
+
} from "../../index-rxh3qy4x.js";
|
|
47
|
+
import"../../index-3fym4j8n.js";
|
|
40
48
|
import {
|
|
41
49
|
planLimitsReadFailed2,
|
|
42
50
|
mergeRateLimitEvent2
|
|
43
|
-
} from "../../index-
|
|
51
|
+
} from "../../index-jrn3prgm.js";
|
|
52
|
+
import {
|
|
53
|
+
assertUnixSocketPathLength,
|
|
54
|
+
assertExpectedOwnerUid,
|
|
55
|
+
unixSocketDirectoryViolation
|
|
56
|
+
} from "../../index-hab790s6.js";
|
|
57
|
+
import {
|
|
58
|
+
errnoOf
|
|
59
|
+
} from "../../index-jj9228tt.js";
|
|
60
|
+
import {
|
|
61
|
+
isPositiveSafeInteger,
|
|
62
|
+
assertPositiveSafeInteger,
|
|
63
|
+
assertNonNegativeSafeInteger
|
|
64
|
+
} from "../../index-gr0kxymw.js";
|
|
65
|
+
import {
|
|
66
|
+
isRecord
|
|
67
|
+
} from "../../index-ps3djm8d.js";
|
|
68
|
+
import {
|
|
69
|
+
assertTimerMs,
|
|
70
|
+
withSignalDeadline
|
|
71
|
+
} from "../../index-agy5fqgf.js";
|
|
72
|
+
import {
|
|
73
|
+
abortReason,
|
|
74
|
+
raceAbort
|
|
75
|
+
} from "../../index-rptj3qnc.js";
|
|
44
76
|
|
|
45
|
-
// src/agent-executor/codex/
|
|
77
|
+
// src/agent-executor/codex/protocol.ts
|
|
46
78
|
import { z } from "zod";
|
|
47
|
-
var
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
79
|
+
var CodexCollaborationModeSchema = z.strictObject({
|
|
80
|
+
mode: z.enum(["plan", "default"]),
|
|
81
|
+
settings: z.strictObject({
|
|
82
|
+
model: z.string().min(1),
|
|
83
|
+
reasoning_effort: z.string().min(1).nullable().optional(),
|
|
84
|
+
developer_instructions: z.string().nullable().optional()
|
|
85
|
+
})
|
|
51
86
|
});
|
|
52
|
-
var
|
|
53
|
-
|
|
54
|
-
|
|
87
|
+
var CodexThreadItemSchema = z.looseObject({
|
|
88
|
+
type: z.string(),
|
|
89
|
+
id: z.string().min(1)
|
|
55
90
|
});
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
for (const name of ["primary", "secondary"]) {
|
|
62
|
-
const window = parsed.data[name];
|
|
63
|
-
if (window === null || window === undefined)
|
|
64
|
-
continue;
|
|
65
|
-
const resetsAt = epochSecondsToIso(window.resetsAt);
|
|
66
|
-
windows.push(PlanWindowSchema2.parse({
|
|
67
|
-
name,
|
|
68
|
-
usedPercent: Math.min(100, window.usedPercent),
|
|
69
|
-
...resetsAt !== undefined && { resetsAt }
|
|
70
|
-
}));
|
|
71
|
-
}
|
|
72
|
-
return windows;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// src/agent-executor/codex/protocol.ts
|
|
76
|
-
import { z as z2 } from "zod";
|
|
77
|
-
var CodexThreadItemSchema = z2.looseObject({
|
|
78
|
-
type: z2.string(),
|
|
79
|
-
id: z2.string().min(1)
|
|
91
|
+
var CodexTurnSchema = z.looseObject({
|
|
92
|
+
id: z.string().min(1),
|
|
93
|
+
status: z.enum(["completed", "interrupted", "failed", "inProgress"]),
|
|
94
|
+
error: z.looseObject({ message: z.string(), codexErrorInfo: z.json().nullable().optional() }).nullable().optional(),
|
|
95
|
+
items: z.array(z.looseObject({ type: z.string(), clientId: z.string().nullable().optional() })).optional()
|
|
80
96
|
});
|
|
81
|
-
var
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
97
|
+
var CodexTokenUsageBreakdownSchema = z.looseObject({
|
|
98
|
+
inputTokens: z.int().nonnegative().optional(),
|
|
99
|
+
outputTokens: z.int().nonnegative().optional(),
|
|
100
|
+
cachedInputTokens: z.int().nonnegative().optional(),
|
|
101
|
+
cacheWriteInputTokens: z.int().nonnegative().optional(),
|
|
102
|
+
reasoningOutputTokens: z.int().nonnegative().optional(),
|
|
103
|
+
totalTokens: z.int().nonnegative().optional()
|
|
86
104
|
});
|
|
87
105
|
var CodexNotificationParams = {
|
|
88
|
-
"item/agentMessage/delta":
|
|
89
|
-
"item/reasoning/textDelta":
|
|
90
|
-
"item/reasoning/summaryTextDelta":
|
|
91
|
-
"item/started":
|
|
92
|
-
"item/completed":
|
|
93
|
-
"turn/completed":
|
|
94
|
-
"thread/tokenUsage/updated":
|
|
95
|
-
tokenUsage:
|
|
96
|
-
last:
|
|
97
|
-
inputTokens:
|
|
98
|
-
outputTokens:
|
|
99
|
-
cachedInputTokens:
|
|
100
|
-
|
|
106
|
+
"item/agentMessage/delta": z.looseObject({ itemId: z.string(), delta: z.string() }),
|
|
107
|
+
"item/reasoning/textDelta": z.looseObject({ itemId: z.string(), delta: z.string() }),
|
|
108
|
+
"item/reasoning/summaryTextDelta": z.looseObject({ itemId: z.string(), delta: z.string() }),
|
|
109
|
+
"item/started": z.looseObject({ item: CodexThreadItemSchema }),
|
|
110
|
+
"item/completed": z.looseObject({ item: CodexThreadItemSchema }),
|
|
111
|
+
"turn/completed": z.looseObject({ turn: CodexTurnSchema }),
|
|
112
|
+
"thread/tokenUsage/updated": z.looseObject({
|
|
113
|
+
tokenUsage: z.looseObject({
|
|
114
|
+
last: z.looseObject({
|
|
115
|
+
inputTokens: z.int().nonnegative(),
|
|
116
|
+
outputTokens: z.int().nonnegative(),
|
|
117
|
+
cachedInputTokens: z.int().nonnegative().optional(),
|
|
118
|
+
cacheWriteInputTokens: z.int().nonnegative().optional(),
|
|
119
|
+
reasoningOutputTokens: z.int().nonnegative().optional(),
|
|
120
|
+
totalTokens: z.int().nonnegative().optional()
|
|
121
|
+
}),
|
|
122
|
+
total: CodexTokenUsageBreakdownSchema.optional(),
|
|
123
|
+
modelContextWindow: z.int().nonnegative().nullable().optional()
|
|
101
124
|
})
|
|
102
125
|
}),
|
|
103
|
-
"serverRequest/resolved":
|
|
104
|
-
"account/rateLimits/updated":
|
|
126
|
+
"serverRequest/resolved": z.looseObject({ requestId: z.union([z.string(), z.int()]) }),
|
|
127
|
+
"account/rateLimits/updated": z.looseObject({
|
|
128
|
+
rateLimits: z.json(),
|
|
129
|
+
rateLimitsByLimitId: z.json().optional()
|
|
130
|
+
})
|
|
105
131
|
};
|
|
106
|
-
var CodexApprovalParamsSchema =
|
|
107
|
-
itemId:
|
|
108
|
-
command:
|
|
109
|
-
|
|
132
|
+
var CodexApprovalParamsSchema = z.looseObject({
|
|
133
|
+
itemId: z.string(),
|
|
134
|
+
command: z.string().nullable().optional(),
|
|
135
|
+
cwd: z.string().nullable().optional(),
|
|
136
|
+
reason: z.string().nullable().optional(),
|
|
137
|
+
grantRoot: z.string().nullable().optional(),
|
|
138
|
+
kind: z.string().nullable().optional(),
|
|
139
|
+
approvalId: z.string().nullable().optional(),
|
|
140
|
+
commandActions: z.array(z.json()).nullable().optional(),
|
|
141
|
+
availableDecisions: z.array(z.json()).nullable().optional()
|
|
142
|
+
});
|
|
143
|
+
var CodexUserInputOptionSchema = z.looseObject({
|
|
144
|
+
label: z.string(),
|
|
145
|
+
description: z.string()
|
|
146
|
+
});
|
|
147
|
+
var CodexUserInputQuestionSchema = z.looseObject({
|
|
148
|
+
id: z.string(),
|
|
149
|
+
question: z.string(),
|
|
150
|
+
header: z.string(),
|
|
151
|
+
isOther: z.boolean().optional(),
|
|
152
|
+
isSecret: z.boolean().optional(),
|
|
153
|
+
options: z.array(CodexUserInputOptionSchema).nullable().optional()
|
|
154
|
+
});
|
|
155
|
+
var CodexUserInputParamsSchema = z.looseObject({
|
|
156
|
+
itemId: z.string(),
|
|
157
|
+
questions: z.array(CodexUserInputQuestionSchema)
|
|
110
158
|
});
|
|
111
|
-
var
|
|
112
|
-
|
|
113
|
-
|
|
159
|
+
var CodexUserInputAnswersSchema = z.record(z.string(), z.strictObject({ answers: z.array(z.string()) }));
|
|
160
|
+
var CodexPermissionProfileSchema = z.looseObject({
|
|
161
|
+
fileSystem: z.json().nullable().optional(),
|
|
162
|
+
network: z.json().nullable().optional()
|
|
114
163
|
});
|
|
115
|
-
var
|
|
116
|
-
|
|
117
|
-
|
|
164
|
+
var CodexPermissionsApprovalParamsSchema = z.looseObject({
|
|
165
|
+
threadId: z.string(),
|
|
166
|
+
turnId: z.string(),
|
|
167
|
+
itemId: z.string(),
|
|
168
|
+
cwd: z.string(),
|
|
169
|
+
permissions: CodexPermissionProfileSchema,
|
|
170
|
+
startedAtMs: z.number().int(),
|
|
171
|
+
reason: z.string().nullable().optional(),
|
|
172
|
+
environmentId: z.string().nullable().optional()
|
|
118
173
|
});
|
|
119
|
-
var
|
|
120
|
-
|
|
174
|
+
var CodexMcpElicitationBaseFields = {
|
|
175
|
+
serverName: z.string(),
|
|
176
|
+
threadId: z.string(),
|
|
177
|
+
turnId: z.string().nullable().optional(),
|
|
178
|
+
environmentId: z.string().nullable().optional(),
|
|
179
|
+
message: z.string(),
|
|
180
|
+
_meta: z.json().optional()
|
|
181
|
+
};
|
|
182
|
+
var CodexMcpElicitationFormSchemaSchema = z.looseObject({
|
|
183
|
+
type: z.literal("object"),
|
|
184
|
+
properties: z.record(z.string(), z.json()),
|
|
185
|
+
required: z.array(z.string()).nullable().optional(),
|
|
186
|
+
$schema: z.string().nullable().optional()
|
|
187
|
+
});
|
|
188
|
+
var CodexMcpElicitationParamsSchema = z.discriminatedUnion("mode", [
|
|
189
|
+
z.looseObject({
|
|
190
|
+
...CodexMcpElicitationBaseFields,
|
|
191
|
+
mode: z.literal("form"),
|
|
192
|
+
requestedSchema: CodexMcpElicitationFormSchemaSchema
|
|
193
|
+
}),
|
|
194
|
+
z.looseObject({
|
|
195
|
+
...CodexMcpElicitationBaseFields,
|
|
196
|
+
mode: z.literal("openai/form"),
|
|
197
|
+
requestedSchema: z.json()
|
|
198
|
+
}),
|
|
199
|
+
z.looseObject({
|
|
200
|
+
...CodexMcpElicitationBaseFields,
|
|
201
|
+
mode: z.literal("openaiForm"),
|
|
202
|
+
requestedSchema: z.json()
|
|
203
|
+
}),
|
|
204
|
+
z.looseObject({
|
|
205
|
+
...CodexMcpElicitationBaseFields,
|
|
206
|
+
mode: z.literal("url"),
|
|
207
|
+
elicitationId: z.string(),
|
|
208
|
+
url: z.string()
|
|
209
|
+
})
|
|
210
|
+
]);
|
|
211
|
+
var CodexMcpElicitationAnswerSchema = z.strictObject({
|
|
212
|
+
action: z.enum(["accept", "decline", "cancel"]),
|
|
213
|
+
content: z.json().optional(),
|
|
214
|
+
_meta: z.json().optional()
|
|
121
215
|
});
|
|
122
|
-
var
|
|
123
|
-
|
|
124
|
-
|
|
216
|
+
var CodexThreadContextSchema = z.object({
|
|
217
|
+
model: z.string().optional(),
|
|
218
|
+
modelProvider: z.string().optional(),
|
|
219
|
+
reasoningEffort: z.string().nullable().optional(),
|
|
220
|
+
approvalPolicy: z.json().optional(),
|
|
221
|
+
sandbox: z.json().optional(),
|
|
222
|
+
cwd: z.string().optional(),
|
|
223
|
+
runtimeWorkspaceRoots: z.array(z.string()).readonly().optional()
|
|
224
|
+
});
|
|
225
|
+
var CodexStartedThreadSchema = CodexThreadContextSchema.extend({
|
|
226
|
+
thread: z.looseObject({ id: z.string().min(1) })
|
|
227
|
+
}).loose();
|
|
228
|
+
function extractCodexThreadContext(parsed) {
|
|
229
|
+
return {
|
|
230
|
+
...parsed.model !== undefined && { model: parsed.model },
|
|
231
|
+
...parsed.modelProvider !== undefined && { modelProvider: parsed.modelProvider },
|
|
232
|
+
...parsed.reasoningEffort !== undefined && { reasoningEffort: parsed.reasoningEffort },
|
|
233
|
+
...parsed.approvalPolicy !== undefined && { approvalPolicy: parsed.approvalPolicy },
|
|
234
|
+
...parsed.sandbox !== undefined && { sandbox: parsed.sandbox },
|
|
235
|
+
...parsed.cwd !== undefined && { cwd: parsed.cwd },
|
|
236
|
+
...parsed.runtimeWorkspaceRoots !== undefined && {
|
|
237
|
+
runtimeWorkspaceRoots: parsed.runtimeWorkspaceRoots
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
var CodexStartedTurnSchema = z.looseObject({
|
|
242
|
+
turn: z.looseObject({ id: z.string().min(1) })
|
|
243
|
+
});
|
|
244
|
+
var CodexTurnSteerResponseSchema = z.looseObject({
|
|
245
|
+
turnId: z.string().min(1)
|
|
246
|
+
});
|
|
247
|
+
var CodexListedTurnItemSchema = z.looseObject({
|
|
248
|
+
type: z.string(),
|
|
249
|
+
clientId: z.string().nullable().optional()
|
|
125
250
|
});
|
|
126
251
|
var CodexListedTurnSchema = CodexTurnSchema.extend({
|
|
127
|
-
items:
|
|
128
|
-
itemsView:
|
|
252
|
+
items: z.array(CodexListedTurnItemSchema),
|
|
253
|
+
itemsView: z.literal("full").optional()
|
|
254
|
+
});
|
|
255
|
+
var CodexTurnsPageSchema = z.looseObject({
|
|
256
|
+
data: z.array(CodexListedTurnSchema),
|
|
257
|
+
nextCursor: z.string().nullable().optional()
|
|
129
258
|
});
|
|
130
|
-
var
|
|
131
|
-
|
|
132
|
-
|
|
259
|
+
var CodexThreadRevertResponseSchema = z.looseObject({
|
|
260
|
+
thread: z.looseObject({ id: z.string().min(1) }),
|
|
261
|
+
turnsBackwardsCursor: z.string().nullable().optional(),
|
|
262
|
+
itemsBackwardsCursor: z.string().nullable().optional()
|
|
133
263
|
});
|
|
134
264
|
var CODEX_OPTED_OUT_NOTIFICATIONS = [
|
|
265
|
+
"app/list/updated",
|
|
135
266
|
"item/commandExecution/outputDelta",
|
|
136
267
|
"item/fileChange/outputDelta",
|
|
137
268
|
"item/fileChange/patchUpdated",
|
|
@@ -144,56 +275,1487 @@ var CODEX_QUIET_NOTIFICATIONS = new Set([
|
|
|
144
275
|
...CODEX_OPTED_OUT_NOTIFICATIONS,
|
|
145
276
|
"thread/started",
|
|
146
277
|
"thread/status/changed",
|
|
278
|
+
"thread/readState/changed",
|
|
279
|
+
"thread/archived",
|
|
280
|
+
"thread/deleted",
|
|
281
|
+
"thread/unarchived",
|
|
282
|
+
"thread/closed",
|
|
283
|
+
"thread/reverted",
|
|
284
|
+
"thread/name/updated",
|
|
285
|
+
"thread/section/changed",
|
|
286
|
+
"thread/attachment/updated",
|
|
287
|
+
"thread/goal/updated",
|
|
288
|
+
"thread/prediction/updated",
|
|
289
|
+
"thread/goal/cleared",
|
|
290
|
+
"thread/queue/changed",
|
|
291
|
+
"project/changed",
|
|
292
|
+
"thread/project/updated",
|
|
293
|
+
"thread/environment/connected",
|
|
294
|
+
"thread/environment/disconnected",
|
|
295
|
+
"thread/settings/updated",
|
|
296
|
+
"thread/compacted",
|
|
147
297
|
"turn/started",
|
|
148
298
|
"turn/plan/updated",
|
|
299
|
+
"turn/moderationMetadata",
|
|
149
300
|
"item/plan/delta",
|
|
301
|
+
"item/commandExecution/terminalInteraction",
|
|
302
|
+
"item/mcpToolCall/progress",
|
|
303
|
+
"item/autoApprovalReview/started",
|
|
304
|
+
"item/autoApprovalReview/completed",
|
|
305
|
+
"autoApprovalReview/strictReviewRequired",
|
|
150
306
|
"item/reasoning/summaryPartAdded",
|
|
151
307
|
"hook/started",
|
|
152
308
|
"hook/completed",
|
|
153
309
|
"warning",
|
|
310
|
+
"guardianWarning",
|
|
311
|
+
"deprecationNotice",
|
|
312
|
+
"configWarning",
|
|
313
|
+
"windows/worldWritableWarning",
|
|
154
314
|
"account/updated",
|
|
155
|
-
"
|
|
156
|
-
"thread/settings/updated",
|
|
157
|
-
"thread/compacted",
|
|
315
|
+
"account/gatewayOAuth/changed",
|
|
158
316
|
"model/rerouted",
|
|
317
|
+
"model/verification",
|
|
318
|
+
"model/safetyBuffering/updated",
|
|
319
|
+
"modelProvider/authRecoveryStarted",
|
|
320
|
+
"modelProvider/authRecoveryCompleted",
|
|
159
321
|
"error"
|
|
160
322
|
]);
|
|
161
323
|
var CODEX_APPROVAL_REQUESTS = new Set([
|
|
162
324
|
"item/commandExecution/requestApproval",
|
|
163
325
|
"item/fileChange/requestApproval"
|
|
164
326
|
]);
|
|
327
|
+
var CODEX_PERMISSIONS_APPROVAL_REQUEST = "item/permissions/requestApproval";
|
|
165
328
|
var CODEX_INPUT_REQUEST = "item/tool/requestUserInput";
|
|
329
|
+
var CODEX_ELICITATION_REQUEST = "mcpServer/elicitation/request";
|
|
166
330
|
var CODEX_APPROVAL_DECISION = {
|
|
167
331
|
approve: "accept",
|
|
332
|
+
approveForSession: "acceptForSession",
|
|
168
333
|
deny: "decline",
|
|
169
334
|
interrupted: "cancel"
|
|
170
335
|
};
|
|
171
336
|
|
|
337
|
+
// src/agent-executor/codex/unix-socket.ts
|
|
338
|
+
import { createHash, randomBytes as randomBytes2 } from "node:crypto";
|
|
339
|
+
import { createConnection } from "node:net";
|
|
340
|
+
|
|
341
|
+
// src/agent-executor/codex/unix-socket-target.ts
|
|
342
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
343
|
+
import { dirname } from "node:path";
|
|
344
|
+
class CodexUnixSocketError extends Error {
|
|
345
|
+
kind;
|
|
346
|
+
socketPath;
|
|
347
|
+
constructor(kind, socketPath, message, options) {
|
|
348
|
+
super(message, options);
|
|
349
|
+
this.kind = kind;
|
|
350
|
+
this.socketPath = socketPath;
|
|
351
|
+
this.name = "CodexUnixSocketError";
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function validateCodexUnixSocketPath(socketPath, caller) {
|
|
355
|
+
if (typeof socketPath !== "string" || socketPath.length === 0) {
|
|
356
|
+
throw new TypeError(`[stitchkit] ${caller}: unix socketPath must be a non-empty string`);
|
|
357
|
+
}
|
|
358
|
+
if (!socketPath.startsWith("/")) {
|
|
359
|
+
throw new TypeError(`[stitchkit] ${caller}: unix socketPath must be an absolute path starting with "/", received ${JSON.stringify(socketPath)}`);
|
|
360
|
+
}
|
|
361
|
+
if (/[\0\r\n\s?#]/.test(socketPath)) {
|
|
362
|
+
throw new TypeError(`[stitchkit] ${caller}: unix socketPath contains forbidden characters (whitespace, NUL, ?, or #)`);
|
|
363
|
+
}
|
|
364
|
+
assertUnixSocketPathLength(socketPath, caller);
|
|
365
|
+
}
|
|
366
|
+
function lstatTarget(targetPath, label, socketPath, caller) {
|
|
367
|
+
try {
|
|
368
|
+
return lstatSync(targetPath, { throwIfNoEntry: false });
|
|
369
|
+
} catch (error) {
|
|
370
|
+
if (errnoOf(error) === "ENOENT")
|
|
371
|
+
return;
|
|
372
|
+
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: failed to inspect unix socket ${label} "${targetPath}"`, { cause: error });
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
function assertPrivateDirStats(dir, requiredUid, socketPath, caller) {
|
|
376
|
+
const stats = lstatTarget(dir, "directory", socketPath, caller);
|
|
377
|
+
if (stats === undefined)
|
|
378
|
+
return "absent";
|
|
379
|
+
const violation = unixSocketDirectoryViolation(dir, stats, caller, requiredUid);
|
|
380
|
+
if (violation !== undefined) {
|
|
381
|
+
throw new CodexUnixSocketError("target-refused", socketPath, violation);
|
|
382
|
+
}
|
|
383
|
+
return "present";
|
|
384
|
+
}
|
|
385
|
+
function assertCodexUnixListenTargetAvailable(socketPath, caller) {
|
|
386
|
+
const dir = dirname(socketPath);
|
|
387
|
+
const requiredUid = typeof process.getuid === "function" ? process.getuid() : undefined;
|
|
388
|
+
if (assertPrivateDirStats(dir, requiredUid, socketPath, caller) === "absent") {
|
|
389
|
+
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: unix socket directory "${dir}" does not exist`);
|
|
390
|
+
}
|
|
391
|
+
const existing = lstatTarget(socketPath, "path", socketPath, caller);
|
|
392
|
+
if (existing !== undefined) {
|
|
393
|
+
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: unix socket path "${socketPath}" already exists — choose a fresh socket path or remove the stale socket first`);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
function assertCodexUnixSocketClientTarget(socketPath, caller, expectedOwnerUid) {
|
|
397
|
+
assertExpectedOwnerUid(expectedOwnerUid, caller);
|
|
398
|
+
const requiredUid = expectedOwnerUid !== undefined ? expectedOwnerUid : typeof process.getuid === "function" ? process.getuid() : undefined;
|
|
399
|
+
if (assertPrivateDirStats(dirname(socketPath), requiredUid, socketPath, caller) === "absent") {
|
|
400
|
+
return "absent";
|
|
401
|
+
}
|
|
402
|
+
const stats = lstatTarget(socketPath, "path", socketPath, caller);
|
|
403
|
+
if (stats === undefined)
|
|
404
|
+
return "absent";
|
|
405
|
+
if (requiredUid !== undefined && stats.uid !== requiredUid) {
|
|
406
|
+
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: unix socket "${socketPath}" is owned by uid ${stats.uid}, expected ${requiredUid}`);
|
|
407
|
+
}
|
|
408
|
+
if (stats.isSymbolicLink()) {
|
|
409
|
+
let resolved;
|
|
410
|
+
try {
|
|
411
|
+
resolved = realpathSync(socketPath);
|
|
412
|
+
} catch (error) {
|
|
413
|
+
if (errnoOf(error) === "ENOENT")
|
|
414
|
+
return "absent";
|
|
415
|
+
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: failed to resolve unix socket symlink "${socketPath}"`, { cause: error });
|
|
416
|
+
}
|
|
417
|
+
if (assertPrivateDirStats(dirname(resolved), requiredUid, socketPath, caller) === "absent") {
|
|
418
|
+
return "absent";
|
|
419
|
+
}
|
|
420
|
+
const targetStats = lstatTarget(resolved, "resolved target", socketPath, caller);
|
|
421
|
+
if (targetStats === undefined)
|
|
422
|
+
return "absent";
|
|
423
|
+
if (!targetStats.isSocket()) {
|
|
424
|
+
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: resolved unix socket target "${resolved}" is not a socket`);
|
|
425
|
+
}
|
|
426
|
+
if (requiredUid !== undefined && targetStats.uid !== requiredUid) {
|
|
427
|
+
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: resolved unix socket target "${resolved}" is owned by uid ${targetStats.uid}, expected ${requiredUid}`);
|
|
428
|
+
}
|
|
429
|
+
return "present";
|
|
430
|
+
}
|
|
431
|
+
if (!stats.isSocket()) {
|
|
432
|
+
throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: "${socketPath}" is not a unix socket`);
|
|
433
|
+
}
|
|
434
|
+
return "present";
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// src/agent-executor/codex/ws-frame.ts
|
|
438
|
+
import { randomBytes } from "node:crypto";
|
|
439
|
+
var MAX_WS_FRAGMENTS = 1024;
|
|
440
|
+
var MAX_CONTROL_PAYLOAD_BYTES = 125;
|
|
441
|
+
function maskedWsFrameByteLength(payloadBytes) {
|
|
442
|
+
const headerLen = payloadBytes < 126 ? 2 : payloadBytes <= 65535 ? 4 : 10;
|
|
443
|
+
return headerLen + 4 + payloadBytes;
|
|
444
|
+
}
|
|
445
|
+
function encodeMaskedWsFrame(opcode, payload) {
|
|
446
|
+
const len = payload.byteLength;
|
|
447
|
+
const headerLen = len < 126 ? 2 : len <= 65535 ? 4 : 10;
|
|
448
|
+
const frame = Buffer.allocUnsafe(headerLen + 4 + len);
|
|
449
|
+
frame[0] = 128 | opcode & 15;
|
|
450
|
+
if (len < 126) {
|
|
451
|
+
frame[1] = 128 | len;
|
|
452
|
+
} else if (len <= 65535) {
|
|
453
|
+
frame[1] = 128 | 126;
|
|
454
|
+
frame.writeUInt16BE(len, 2);
|
|
455
|
+
} else {
|
|
456
|
+
frame[1] = 128 | 127;
|
|
457
|
+
const hi = Math.floor(len / 4294967296);
|
|
458
|
+
const lo = len >>> 0;
|
|
459
|
+
frame.writeUInt32BE(hi, 2);
|
|
460
|
+
frame.writeUInt32BE(lo, 6);
|
|
461
|
+
}
|
|
462
|
+
const mask = randomBytes(4);
|
|
463
|
+
frame[headerLen] = mask[0] ?? 0;
|
|
464
|
+
frame[headerLen + 1] = mask[1] ?? 0;
|
|
465
|
+
frame[headerLen + 2] = mask[2] ?? 0;
|
|
466
|
+
frame[headerLen + 3] = mask[3] ?? 0;
|
|
467
|
+
const bodyOffset = headerLen + 4;
|
|
468
|
+
for (let i = 0;i < len; i += 1) {
|
|
469
|
+
frame[bodyOffset + i] = (payload[i] ?? 0) ^ (mask[i & 3] ?? 0);
|
|
470
|
+
}
|
|
471
|
+
return frame;
|
|
472
|
+
}
|
|
473
|
+
function createByteQueue() {
|
|
474
|
+
const chunks = [];
|
|
475
|
+
let headOffset = 0;
|
|
476
|
+
let total = 0;
|
|
477
|
+
return {
|
|
478
|
+
get length() {
|
|
479
|
+
return total;
|
|
480
|
+
},
|
|
481
|
+
push(chunk) {
|
|
482
|
+
if (chunk.byteLength === 0)
|
|
483
|
+
return;
|
|
484
|
+
chunks.push(chunk);
|
|
485
|
+
total += chunk.byteLength;
|
|
486
|
+
},
|
|
487
|
+
peekBytes(count) {
|
|
488
|
+
const first = chunks[0];
|
|
489
|
+
if (first !== undefined && first.byteLength - headOffset >= count) {
|
|
490
|
+
return first.subarray(headOffset, headOffset + count);
|
|
491
|
+
}
|
|
492
|
+
const out = Buffer.allocUnsafe(count);
|
|
493
|
+
let written = 0;
|
|
494
|
+
let idx = 0;
|
|
495
|
+
let off = headOffset;
|
|
496
|
+
while (written < count && idx < chunks.length) {
|
|
497
|
+
const cur = chunks[idx];
|
|
498
|
+
if (cur === undefined)
|
|
499
|
+
break;
|
|
500
|
+
const take = Math.min(cur.byteLength - off, count - written);
|
|
501
|
+
cur.copy(out, written, off, off + take);
|
|
502
|
+
written += take;
|
|
503
|
+
idx += 1;
|
|
504
|
+
off = 0;
|
|
505
|
+
}
|
|
506
|
+
return out;
|
|
507
|
+
},
|
|
508
|
+
consume(count) {
|
|
509
|
+
const out = Buffer.allocUnsafe(count);
|
|
510
|
+
let written = 0;
|
|
511
|
+
while (written < count && chunks.length > 0) {
|
|
512
|
+
const cur = chunks[0];
|
|
513
|
+
if (cur === undefined)
|
|
514
|
+
break;
|
|
515
|
+
const avail = cur.byteLength - headOffset;
|
|
516
|
+
const take = Math.min(avail, count - written);
|
|
517
|
+
cur.copy(out, written, headOffset, headOffset + take);
|
|
518
|
+
written += take;
|
|
519
|
+
total -= take;
|
|
520
|
+
if (take === avail) {
|
|
521
|
+
chunks.shift();
|
|
522
|
+
headOffset = 0;
|
|
523
|
+
} else {
|
|
524
|
+
headOffset += take;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
return out;
|
|
528
|
+
},
|
|
529
|
+
skip(count) {
|
|
530
|
+
let left = count;
|
|
531
|
+
while (left > 0 && chunks.length > 0) {
|
|
532
|
+
const cur = chunks[0];
|
|
533
|
+
if (cur === undefined)
|
|
534
|
+
break;
|
|
535
|
+
const avail = cur.byteLength - headOffset;
|
|
536
|
+
if (left >= avail) {
|
|
537
|
+
chunks.shift();
|
|
538
|
+
headOffset = 0;
|
|
539
|
+
total -= avail;
|
|
540
|
+
left -= avail;
|
|
541
|
+
} else {
|
|
542
|
+
headOffset += left;
|
|
543
|
+
total -= left;
|
|
544
|
+
left = 0;
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
},
|
|
548
|
+
clear() {
|
|
549
|
+
chunks.length = 0;
|
|
550
|
+
headOffset = 0;
|
|
551
|
+
total = 0;
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
function createWsFrameDecoder(handlers) {
|
|
556
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
557
|
+
const queue = createByteQueue();
|
|
558
|
+
let fragments;
|
|
559
|
+
let fragmentBytes = 0;
|
|
560
|
+
let stopped = false;
|
|
561
|
+
const fail = (message) => {
|
|
562
|
+
stopped = true;
|
|
563
|
+
queue.clear();
|
|
564
|
+
fragments = undefined;
|
|
565
|
+
fragmentBytes = 0;
|
|
566
|
+
handlers.onProtocolError(message);
|
|
567
|
+
};
|
|
568
|
+
return {
|
|
569
|
+
push(chunk) {
|
|
570
|
+
if (stopped || chunk.byteLength === 0)
|
|
571
|
+
return;
|
|
572
|
+
queue.push(chunk);
|
|
573
|
+
while (!stopped && queue.length >= 2) {
|
|
574
|
+
const head2 = queue.peekBytes(2);
|
|
575
|
+
const b0 = head2[0] ?? 0;
|
|
576
|
+
const b1 = head2[1] ?? 0;
|
|
577
|
+
if ((b0 & 112) !== 0)
|
|
578
|
+
return fail("Server WebSocket frame set reserved RSV bits");
|
|
579
|
+
if ((b1 & 128) !== 0)
|
|
580
|
+
return fail("Server WebSocket frame must not be masked");
|
|
581
|
+
const fin = (b0 & 128) !== 0;
|
|
582
|
+
const opcode = b0 & 15;
|
|
583
|
+
const len7 = b1 & 127;
|
|
584
|
+
let headerLen = 2;
|
|
585
|
+
let payloadLen = len7;
|
|
586
|
+
if (len7 === 126) {
|
|
587
|
+
if (queue.length < 4)
|
|
588
|
+
break;
|
|
589
|
+
headerLen = 4;
|
|
590
|
+
payloadLen = queue.peekBytes(4).readUInt16BE(2);
|
|
591
|
+
} else if (len7 === 127) {
|
|
592
|
+
if (queue.length < 10)
|
|
593
|
+
break;
|
|
594
|
+
headerLen = 10;
|
|
595
|
+
const head10 = queue.peekBytes(10);
|
|
596
|
+
const hi = head10.readUInt32BE(2);
|
|
597
|
+
const lo = head10.readUInt32BE(6);
|
|
598
|
+
if ((hi & 2147483648) !== 0)
|
|
599
|
+
return fail("WebSocket 64-bit frame length has MSB set");
|
|
600
|
+
payloadLen = hi * 4294967296 + lo;
|
|
601
|
+
}
|
|
602
|
+
if (opcode >= 8) {
|
|
603
|
+
if (!fin)
|
|
604
|
+
return fail("Control WebSocket frame must not be fragmented");
|
|
605
|
+
if (payloadLen > MAX_CONTROL_PAYLOAD_BYTES) {
|
|
606
|
+
return fail(`Control WebSocket frame payload (${payloadLen} bytes) exceeds 125 bytes`);
|
|
607
|
+
}
|
|
608
|
+
if (opcode !== 8 && opcode !== 9 && opcode !== 10) {
|
|
609
|
+
return fail(`Unsupported WebSocket control opcode 0x${opcode.toString(16)}`);
|
|
610
|
+
}
|
|
611
|
+
} else {
|
|
612
|
+
if (opcode !== 0 && opcode !== 1) {
|
|
613
|
+
return fail(`Unsupported WebSocket data opcode 0x${opcode.toString(16)}`);
|
|
614
|
+
}
|
|
615
|
+
if (!Number.isSafeInteger(payloadLen) || payloadLen > handlers.maxFrameBytes) {
|
|
616
|
+
return fail(`WebSocket frame payload (${payloadLen} bytes) exceeds maxFrameBytes (${handlers.maxFrameBytes})`);
|
|
617
|
+
}
|
|
618
|
+
if (opcode === 1 && fragments !== undefined) {
|
|
619
|
+
return fail("Interleaved WebSocket text frame during fragmented message");
|
|
620
|
+
}
|
|
621
|
+
if (opcode === 0 && fragments === undefined) {
|
|
622
|
+
return fail("Unexpected WebSocket continuation frame without an active message");
|
|
623
|
+
}
|
|
624
|
+
if (fragments !== undefined) {
|
|
625
|
+
if (fragments.length + 1 > MAX_WS_FRAGMENTS) {
|
|
626
|
+
return fail(`Fragmented WebSocket message exceeded ${MAX_WS_FRAGMENTS} frames`);
|
|
627
|
+
}
|
|
628
|
+
if (fragmentBytes + payloadLen > handlers.maxFrameBytes) {
|
|
629
|
+
return fail(`Fragmented WebSocket message exceeded maxFrameBytes (${handlers.maxFrameBytes})`);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
if (queue.length < headerLen + payloadLen)
|
|
634
|
+
break;
|
|
635
|
+
queue.skip(headerLen);
|
|
636
|
+
const payload = queue.consume(payloadLen);
|
|
637
|
+
if (opcode === 9) {
|
|
638
|
+
handlers.onPing(payload);
|
|
639
|
+
} else if (opcode === 10) {} else if (opcode === 8) {
|
|
640
|
+
if (payload.byteLength === 1)
|
|
641
|
+
return fail("WebSocket close frame payload cannot be 1 byte");
|
|
642
|
+
const code = payload.byteLength >= 2 ? payload.readUInt16BE(0) : undefined;
|
|
643
|
+
let reason = "";
|
|
644
|
+
if (payload.byteLength > 2) {
|
|
645
|
+
try {
|
|
646
|
+
reason = utf8.decode(payload.subarray(2));
|
|
647
|
+
} catch {
|
|
648
|
+
return fail("WebSocket close frame reason is not valid UTF-8");
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
stopped = true;
|
|
652
|
+
queue.clear();
|
|
653
|
+
fragments = undefined;
|
|
654
|
+
fragmentBytes = 0;
|
|
655
|
+
handlers.onClose(code, reason);
|
|
656
|
+
return;
|
|
657
|
+
} else if (opcode === 1) {
|
|
658
|
+
if (fin) {
|
|
659
|
+
let text;
|
|
660
|
+
try {
|
|
661
|
+
text = utf8.decode(payload);
|
|
662
|
+
} catch {
|
|
663
|
+
return fail("WebSocket text frame is not valid UTF-8");
|
|
664
|
+
}
|
|
665
|
+
handlers.onMessage(text);
|
|
666
|
+
} else {
|
|
667
|
+
fragments = [payload];
|
|
668
|
+
fragmentBytes = payload.byteLength;
|
|
669
|
+
}
|
|
670
|
+
} else if (opcode === 0 && fragments !== undefined) {
|
|
671
|
+
fragments.push(payload);
|
|
672
|
+
fragmentBytes += payload.byteLength;
|
|
673
|
+
if (fin) {
|
|
674
|
+
const combined = Buffer.concat(fragments, fragmentBytes);
|
|
675
|
+
fragments = undefined;
|
|
676
|
+
fragmentBytes = 0;
|
|
677
|
+
let text;
|
|
678
|
+
try {
|
|
679
|
+
text = utf8.decode(combined);
|
|
680
|
+
} catch {
|
|
681
|
+
return fail("Reassembled WebSocket text message is not valid UTF-8");
|
|
682
|
+
}
|
|
683
|
+
handlers.onMessage(text);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// src/agent-executor/codex/unix-socket.ts
|
|
692
|
+
var WS_MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
693
|
+
var MAX_HANDSHAKE_HEADER_BYTES = 64 * 1024;
|
|
694
|
+
var DEFAULT_HANDSHAKE_TIMEOUT_MS = 15000;
|
|
695
|
+
var DEFAULT_MAX_FRAME_BYTES = 16 * 1024 * 1024;
|
|
696
|
+
var DEFAULT_MAX_PENDING_WRITE_BYTES = 16 * 1024 * 1024;
|
|
697
|
+
var CLOSE_GRACE_MS = 250;
|
|
698
|
+
function validateHandshakeResponse(headerText, expectedAccept, socketPath) {
|
|
699
|
+
const lines = headerText.split(`\r
|
|
700
|
+
`);
|
|
701
|
+
const statusLine = lines[0] ?? "";
|
|
702
|
+
if (!/^HTTP\/1\.1 101(?:\s|$)/.test(statusLine)) {
|
|
703
|
+
throw new CodexUnixSocketError("upgrade-refused", socketPath, `Codex Unix socket WebSocket upgrade failed: ${statusLine || "empty response"}`);
|
|
704
|
+
}
|
|
705
|
+
const headers = new Map;
|
|
706
|
+
for (let i = 1;i < lines.length; i += 1) {
|
|
707
|
+
const line = lines[i] ?? "";
|
|
708
|
+
if (line.length === 0)
|
|
709
|
+
continue;
|
|
710
|
+
const colon = line.indexOf(":");
|
|
711
|
+
if (colon <= 0) {
|
|
712
|
+
throw new CodexUnixSocketError("upgrade-refused", socketPath, "Codex Unix socket upgrade response contained a malformed HTTP header line");
|
|
713
|
+
}
|
|
714
|
+
const key = line.slice(0, colon).trim().toLowerCase();
|
|
715
|
+
const value = line.slice(colon + 1).trim();
|
|
716
|
+
const existing = headers.get(key);
|
|
717
|
+
headers.set(key, existing === undefined ? value : `${existing}, ${value}`);
|
|
718
|
+
}
|
|
719
|
+
if ((headers.get("upgrade") ?? "").toLowerCase() !== "websocket") {
|
|
720
|
+
throw new CodexUnixSocketError("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Upgrade: websocket" header');
|
|
721
|
+
}
|
|
722
|
+
const connectionTokens = (headers.get("connection") ?? "").toLowerCase().split(",").map((token) => token.trim());
|
|
723
|
+
if (!connectionTokens.includes("upgrade")) {
|
|
724
|
+
throw new CodexUnixSocketError("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Connection: upgrade" header');
|
|
725
|
+
}
|
|
726
|
+
if (headers.get("sec-websocket-accept") !== expectedAccept) {
|
|
727
|
+
throw new CodexUnixSocketError("upgrade-refused", socketPath, "Codex Unix socket upgrade response returned an invalid Sec-WebSocket-Accept header");
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
function classifyConnectError(error, socketPath) {
|
|
731
|
+
const code = errnoOf(error);
|
|
732
|
+
if (code === "ENOENT") {
|
|
733
|
+
return new CodexUnixSocketError("endpoint-absent", socketPath, `Codex Unix socket "${socketPath}" does not exist`, { cause: error });
|
|
734
|
+
}
|
|
735
|
+
if (code === "ECONNREFUSED") {
|
|
736
|
+
return new CodexUnixSocketError("endpoint-not-listening", socketPath, `Codex Unix socket "${socketPath}" refused connection`, { cause: error });
|
|
737
|
+
}
|
|
738
|
+
return new CodexUnixSocketError("connection-lost", socketPath, `Failed to connect to Codex Unix socket "${socketPath}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
739
|
+
}
|
|
740
|
+
function performWsUpgrade(input) {
|
|
741
|
+
const wsKey = randomBytes2(16).toString("base64");
|
|
742
|
+
const expectedAccept = createHash("sha1").update(`${wsKey}${WS_MAGIC_GUID}`).digest("base64");
|
|
743
|
+
return withSignalDeadline(input.handshakeTimeoutMs, input.signal, () => new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket WebSocket handshake timed out after ${input.handshakeTimeoutMs} ms`), (handshakeSignal) => new Promise((resolve, reject) => {
|
|
744
|
+
let settled = false;
|
|
745
|
+
let handshakeBuf = Buffer.alloc(0);
|
|
746
|
+
const sock = createConnection({ path: input.socketPath });
|
|
747
|
+
const cleanup = () => {
|
|
748
|
+
handshakeSignal.removeEventListener("abort", onAbort);
|
|
749
|
+
sock.off("connect", onConnect);
|
|
750
|
+
sock.off("data", onData);
|
|
751
|
+
sock.off("error", onError);
|
|
752
|
+
sock.off("close", onClose);
|
|
753
|
+
};
|
|
754
|
+
const fail = (error) => {
|
|
755
|
+
if (settled)
|
|
756
|
+
return;
|
|
757
|
+
settled = true;
|
|
758
|
+
cleanup();
|
|
759
|
+
sock.destroy();
|
|
760
|
+
reject(error);
|
|
761
|
+
};
|
|
762
|
+
const onAbort = () => fail(abortReason(handshakeSignal));
|
|
763
|
+
const onConnect = () => {
|
|
764
|
+
sock.write(`GET /rpc HTTP/1.1\r
|
|
765
|
+
Host: localhost\r
|
|
766
|
+
Upgrade: websocket\r
|
|
767
|
+
Connection: Upgrade\r
|
|
768
|
+
Sec-WebSocket-Key: ${wsKey}\r
|
|
769
|
+
Sec-WebSocket-Version: 13\r
|
|
770
|
+
\r
|
|
771
|
+
`);
|
|
772
|
+
};
|
|
773
|
+
const onData = (chunk) => {
|
|
774
|
+
const combinedLen = handshakeBuf.byteLength + chunk.byteLength;
|
|
775
|
+
if (handshakeBuf.byteLength > MAX_HANDSHAKE_HEADER_BYTES) {
|
|
776
|
+
fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
|
|
777
|
+
return;
|
|
778
|
+
}
|
|
779
|
+
const nextBuf = handshakeBuf.byteLength === 0 ? chunk : Buffer.concat([handshakeBuf, chunk]);
|
|
780
|
+
const boundary = nextBuf.indexOf(`\r
|
|
781
|
+
\r
|
|
782
|
+
`);
|
|
783
|
+
if (boundary === -1) {
|
|
784
|
+
if (combinedLen > MAX_HANDSHAKE_HEADER_BYTES) {
|
|
785
|
+
fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
handshakeBuf = nextBuf;
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
if (boundary > MAX_HANDSHAKE_HEADER_BYTES) {
|
|
792
|
+
fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
const headerText = nextBuf.subarray(0, boundary).toString("latin1");
|
|
796
|
+
const rest = Buffer.from(nextBuf.subarray(boundary + 4));
|
|
797
|
+
try {
|
|
798
|
+
validateHandshakeResponse(headerText, expectedAccept, input.socketPath);
|
|
799
|
+
} catch (error) {
|
|
800
|
+
fail(error);
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
settled = true;
|
|
804
|
+
sock.pause();
|
|
805
|
+
cleanup();
|
|
806
|
+
resolve({ socket: sock, trailing: rest });
|
|
807
|
+
};
|
|
808
|
+
const onError = (error) => fail(classifyConnectError(error, input.socketPath));
|
|
809
|
+
const onClose = () => fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, "Codex Unix socket closed before completing WebSocket upgrade"));
|
|
810
|
+
handshakeSignal.addEventListener("abort", onAbort, { once: true });
|
|
811
|
+
sock.once("connect", onConnect);
|
|
812
|
+
sock.on("data", onData);
|
|
813
|
+
sock.once("error", onError);
|
|
814
|
+
sock.once("close", onClose);
|
|
815
|
+
}));
|
|
816
|
+
}
|
|
817
|
+
async function connectCodexUnixSocket(input) {
|
|
818
|
+
validateCodexUnixSocketPath(input.socketPath, "connectCodexUnixSocket");
|
|
819
|
+
assertTimerMs("handshakeTimeoutMs", input.handshakeTimeoutMs);
|
|
820
|
+
assertPositiveSafeInteger("maxFrameBytes", input.maxFrameBytes);
|
|
821
|
+
assertPositiveSafeInteger("maxPendingWriteBytes", input.maxPendingWriteBytes);
|
|
822
|
+
input.signal.throwIfAborted();
|
|
823
|
+
input.connectSignal?.throwIfAborted();
|
|
824
|
+
const targetState = assertCodexUnixSocketClientTarget(input.socketPath, "connectCodexUnixSocket", input.expectedOwnerUid);
|
|
825
|
+
if (targetState === "absent") {
|
|
826
|
+
throw new CodexUnixSocketError("endpoint-absent", input.socketPath, `Codex Unix socket "${input.socketPath}" does not exist`);
|
|
827
|
+
}
|
|
828
|
+
const maxFrameBytes = input.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
|
|
829
|
+
const maxPendingWriteBytes = input.maxPendingWriteBytes ?? DEFAULT_MAX_PENDING_WRITE_BYTES;
|
|
830
|
+
const { socket, trailing } = await performWsUpgrade({
|
|
831
|
+
socketPath: input.socketPath,
|
|
832
|
+
signal: input.connectSignal ?? input.signal,
|
|
833
|
+
handshakeTimeoutMs: input.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS
|
|
834
|
+
});
|
|
835
|
+
if (input.signal.aborted) {
|
|
836
|
+
socket.destroy();
|
|
837
|
+
throw abortReason(input.signal);
|
|
838
|
+
}
|
|
839
|
+
if (socket.destroyed) {
|
|
840
|
+
throw new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed during WebSocket upgrade`);
|
|
841
|
+
}
|
|
842
|
+
let closed = false;
|
|
843
|
+
let closeSent = false;
|
|
844
|
+
const closedDeferred = Promise.withResolvers();
|
|
845
|
+
const finishClosed = (error) => {
|
|
846
|
+
if (closed)
|
|
847
|
+
return;
|
|
848
|
+
closed = true;
|
|
849
|
+
input.signal.removeEventListener("abort", onSignalAbort);
|
|
850
|
+
closedDeferred.resolve();
|
|
851
|
+
input.onClose(error);
|
|
852
|
+
};
|
|
853
|
+
const sendControlFrame = (opcode, payload) => {
|
|
854
|
+
if (closed || socket.destroyed || !socket.writable)
|
|
855
|
+
return;
|
|
856
|
+
const frameBytes = maskedWsFrameByteLength(payload.byteLength);
|
|
857
|
+
if (socket.writableLength + frameBytes > maxPendingWriteBytes)
|
|
858
|
+
return;
|
|
859
|
+
socket.write(encodeMaskedWsFrame(opcode, payload));
|
|
860
|
+
};
|
|
861
|
+
const closeGracefully = async () => {
|
|
862
|
+
if (closed)
|
|
863
|
+
return closedDeferred.promise;
|
|
864
|
+
if (!closeSent && socket.writable && !socket.destroyed) {
|
|
865
|
+
closeSent = true;
|
|
866
|
+
const closeBody = Buffer.allocUnsafe(2);
|
|
867
|
+
closeBody.writeUInt16BE(1000, 0);
|
|
868
|
+
try {
|
|
869
|
+
sendControlFrame(8, closeBody);
|
|
870
|
+
} catch {}
|
|
871
|
+
socket.end();
|
|
872
|
+
}
|
|
873
|
+
const grace = setTimeout(() => {
|
|
874
|
+
if (!socket.destroyed)
|
|
875
|
+
socket.destroy();
|
|
876
|
+
}, CLOSE_GRACE_MS);
|
|
877
|
+
grace.unref?.();
|
|
878
|
+
try {
|
|
879
|
+
await closedDeferred.promise;
|
|
880
|
+
} finally {
|
|
881
|
+
clearTimeout(grace);
|
|
882
|
+
}
|
|
883
|
+
};
|
|
884
|
+
const onSignalAbort = () => {
|
|
885
|
+
const err = new CodexUnixSocketError("connection-lost", input.socketPath, "Codex Unix socket connection aborted", { cause: abortReason(input.signal) });
|
|
886
|
+
socket.destroy();
|
|
887
|
+
finishClosed(err);
|
|
888
|
+
};
|
|
889
|
+
input.signal.addEventListener("abort", onSignalAbort, { once: true });
|
|
890
|
+
const decoder = createWsFrameDecoder({
|
|
891
|
+
maxFrameBytes,
|
|
892
|
+
onMessage: input.onMessage,
|
|
893
|
+
onPing: (payload) => sendControlFrame(10, payload),
|
|
894
|
+
onClose: (code, reason) => {
|
|
895
|
+
if (!closeSent) {
|
|
896
|
+
closeSent = true;
|
|
897
|
+
sendControlFrame(8, Buffer.alloc(0));
|
|
898
|
+
}
|
|
899
|
+
socket.end();
|
|
900
|
+
const suffix = reason.length > 0 ? `: ${reason}` : "";
|
|
901
|
+
finishClosed(new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket closed by peer (${code ?? "no-code"})${suffix}`));
|
|
902
|
+
},
|
|
903
|
+
onProtocolError: (message) => {
|
|
904
|
+
const err = new CodexUnixSocketError("connection-lost", input.socketPath, message);
|
|
905
|
+
socket.destroy();
|
|
906
|
+
finishClosed(err);
|
|
907
|
+
}
|
|
908
|
+
});
|
|
909
|
+
socket.on("data", (chunk) => decoder.push(chunk));
|
|
910
|
+
socket.on("error", (error) => {
|
|
911
|
+
finishClosed(new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket error: ${error.message}`, { cause: error }));
|
|
912
|
+
});
|
|
913
|
+
socket.on("close", () => {
|
|
914
|
+
finishClosed(new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed`));
|
|
915
|
+
});
|
|
916
|
+
if (trailing.byteLength > 0)
|
|
917
|
+
decoder.push(trailing);
|
|
918
|
+
if (!closed && !socket.destroyed)
|
|
919
|
+
socket.resume();
|
|
920
|
+
return {
|
|
921
|
+
send(text) {
|
|
922
|
+
if (closed || socket.destroyed || !socket.writable) {
|
|
923
|
+
throw new CodexUnixSocketError("connection-lost", input.socketPath, "Codex Unix socket connection is closed");
|
|
924
|
+
}
|
|
925
|
+
const payloadBytes = Buffer.byteLength(text, "utf8");
|
|
926
|
+
const frameBytes = maskedWsFrameByteLength(payloadBytes);
|
|
927
|
+
if (socket.writableLength + frameBytes > maxPendingWriteBytes) {
|
|
928
|
+
throw new RangeError(`Codex Unix socket outbound queue exceeded ${maxPendingWriteBytes} bytes (${frameBytes} bytes needed)`);
|
|
929
|
+
}
|
|
930
|
+
socket.write(encodeMaskedWsFrame(1, Buffer.from(text, "utf8")));
|
|
931
|
+
},
|
|
932
|
+
close: () => closeGracefully(),
|
|
933
|
+
closed: closedDeferred.promise
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// src/agent-executor/codex/connect.ts
|
|
938
|
+
var BOOTSTRAP_MS = 45000;
|
|
939
|
+
var REQUEST_MS = 60000;
|
|
940
|
+
var DEFAULT_LISTEN_TIMEOUT_MS = 15000;
|
|
941
|
+
var POLL_INITIAL_MS = 15;
|
|
942
|
+
var POLL_MAX_MS = 50;
|
|
943
|
+
function validateCodexTransportAndArgs(config) {
|
|
944
|
+
if (config.serverArgs !== undefined) {
|
|
945
|
+
if (!Array.isArray(config.serverArgs)) {
|
|
946
|
+
throw new TypeError("[stitchkit] createCodexDriver: serverArgs must be an array of strings");
|
|
947
|
+
}
|
|
948
|
+
for (const arg of config.serverArgs) {
|
|
949
|
+
if (typeof arg !== "string") {
|
|
950
|
+
throw new TypeError("[stitchkit] createCodexDriver: every serverArgs entry must be a string");
|
|
951
|
+
}
|
|
952
|
+
if (arg === "--listen" || arg === "--stdio" || arg.startsWith("--listen=") || arg.startsWith("--stdio=")) {
|
|
953
|
+
throw new TypeError(`[stitchkit] createCodexDriver: serverArgs must not include "${arg}"; configure transport via config.transport instead`);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
const transport = config.transport;
|
|
958
|
+
if (transport === undefined || transport.kind === "stdio")
|
|
959
|
+
return;
|
|
960
|
+
if (transport.kind === "unix-listen") {
|
|
961
|
+
validateCodexUnixSocketPath(transport.socketPath, "createCodexDriver");
|
|
962
|
+
assertTimerMs("listenTimeoutMs", transport.listenTimeoutMs);
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
if (transport.kind === "unix-connect") {
|
|
966
|
+
validateCodexUnixSocketPath(transport.socketPath, "createCodexDriver");
|
|
967
|
+
assertExpectedOwnerUid(transport.expectedOwnerUid, "createCodexDriver");
|
|
968
|
+
if ((config.serverArgs?.length ?? 0) > 0) {
|
|
969
|
+
throw new TypeError('[stitchkit] createCodexDriver: serverArgs cannot be used with transport kind "unix-connect"');
|
|
970
|
+
}
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
throw new TypeError(`[stitchkit] createCodexDriver: unsupported transport kind ${JSON.stringify(Reflect.get(Object(transport), "kind"))}`);
|
|
974
|
+
}
|
|
975
|
+
async function initializeCodexPeer(peer, version) {
|
|
976
|
+
await peer.request("initialize", {
|
|
977
|
+
clientInfo: { name: "stitchkit-agent-executor", version },
|
|
978
|
+
capabilities: {
|
|
979
|
+
experimentalApi: true,
|
|
980
|
+
optOutNotificationMethods: CODEX_OPTED_OUT_NOTIFICATIONS
|
|
981
|
+
}
|
|
982
|
+
}, { timeoutMs: BOOTSTRAP_MS });
|
|
983
|
+
peer.notify("initialized");
|
|
984
|
+
}
|
|
985
|
+
function sleepAbortable(ms, signal) {
|
|
986
|
+
if (signal.aborted)
|
|
987
|
+
return Promise.reject(abortReason(signal));
|
|
988
|
+
return new Promise((resolve, reject) => {
|
|
989
|
+
const timer = setTimeout(() => {
|
|
990
|
+
signal.removeEventListener("abort", onAbort);
|
|
991
|
+
resolve();
|
|
992
|
+
}, ms);
|
|
993
|
+
const onAbort = () => {
|
|
994
|
+
clearTimeout(timer);
|
|
995
|
+
reject(abortReason(signal));
|
|
996
|
+
};
|
|
997
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
async function dialWithEngineRace(input) {
|
|
1001
|
+
const exitAbort = new AbortController;
|
|
1002
|
+
let exitedEarly;
|
|
1003
|
+
input.engine.result.then((res) => {
|
|
1004
|
+
const detail = input.engine.stderrTail().slice(-2000).trim();
|
|
1005
|
+
exitedEarly = new Error(`Codex app-server exited before listening on "${input.socketPath}" (code ${res.exitCode ?? "signal"})${detail.length > 0 ? `: ${detail}` : ""}`);
|
|
1006
|
+
exitAbort.abort(exitedEarly);
|
|
1007
|
+
}, (error) => {
|
|
1008
|
+
const detail = input.engine.stderrTail().slice(-2000).trim();
|
|
1009
|
+
exitedEarly = new Error(`Codex app-server failed before listening on "${input.socketPath}": ${error instanceof Error ? error.message : String(error)}${detail.length > 0 ? ` (${detail})` : ""}`, { cause: error });
|
|
1010
|
+
exitAbort.abort(exitedEarly);
|
|
1011
|
+
});
|
|
1012
|
+
return withSignalDeadline(input.listenTimeoutMs, input.signal, () => new CodexUnixSocketError("endpoint-absent", input.socketPath, `Codex app-server did not listen on "${input.socketPath}" within ${input.listenTimeoutMs} ms`), async (deadlineSignal) => {
|
|
1013
|
+
let delayMs = POLL_INITIAL_MS;
|
|
1014
|
+
for (;; ) {
|
|
1015
|
+
if (exitedEarly !== undefined)
|
|
1016
|
+
throw exitedEarly;
|
|
1017
|
+
deadlineSignal.throwIfAborted();
|
|
1018
|
+
try {
|
|
1019
|
+
return await raceAbort(connectCodexUnixSocket({
|
|
1020
|
+
socketPath: input.socketPath,
|
|
1021
|
+
signal: input.signal,
|
|
1022
|
+
connectSignal: deadlineSignal,
|
|
1023
|
+
...input.maxFrameBytes !== undefined && { maxFrameBytes: input.maxFrameBytes },
|
|
1024
|
+
onMessage: input.onMessage,
|
|
1025
|
+
onClose: input.onClose
|
|
1026
|
+
}), exitAbort.signal, (lateClient) => {
|
|
1027
|
+
lateClient.close().catch(() => {
|
|
1028
|
+
return;
|
|
1029
|
+
});
|
|
1030
|
+
});
|
|
1031
|
+
} catch (error) {
|
|
1032
|
+
if (exitedEarly !== undefined)
|
|
1033
|
+
throw exitedEarly;
|
|
1034
|
+
const retryable = error instanceof CodexUnixSocketError && (error.kind === "endpoint-absent" || error.kind === "endpoint-not-listening");
|
|
1035
|
+
if (!retryable)
|
|
1036
|
+
throw error;
|
|
1037
|
+
await raceAbort(sleepAbortable(delayMs, deadlineSignal), exitAbort.signal);
|
|
1038
|
+
delayMs = Math.min(POLL_MAX_MS, Math.round(delayMs * 1.5));
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd = () => {
|
|
1044
|
+
return;
|
|
1045
|
+
}, onStartupPhase) {
|
|
1046
|
+
const transport = config.transport ?? { kind: "stdio" };
|
|
1047
|
+
const extraArgs = config.serverArgs ?? [];
|
|
1048
|
+
if (transport.kind === "stdio") {
|
|
1049
|
+
const env = engineEnvironment2(profile, config.ambient);
|
|
1050
|
+
let endedError;
|
|
1051
|
+
let ready = false;
|
|
1052
|
+
const peer = createJsonRpcPeer2({
|
|
1053
|
+
header: "omitted",
|
|
1054
|
+
requestTimeoutMs: REQUEST_MS,
|
|
1055
|
+
send: (line) => engine.send(line),
|
|
1056
|
+
...handlers
|
|
1057
|
+
});
|
|
1058
|
+
const finishEnd = (error) => {
|
|
1059
|
+
if (endedError !== undefined)
|
|
1060
|
+
return;
|
|
1061
|
+
endedError = error;
|
|
1062
|
+
peer.close(error);
|
|
1063
|
+
if (ready)
|
|
1064
|
+
onEnd(error);
|
|
1065
|
+
};
|
|
1066
|
+
emitStartupPhase(onStartupPhase, "spawning");
|
|
1067
|
+
const engine = spawnEngineProcess2({
|
|
1068
|
+
executable: config.executable,
|
|
1069
|
+
args: [...config.prefix, "app-server", ...extraArgs],
|
|
1070
|
+
cwd,
|
|
1071
|
+
env,
|
|
1072
|
+
signal,
|
|
1073
|
+
...config.maxLineBytes !== undefined && { maxLineBytes: config.maxLineBytes }
|
|
1074
|
+
});
|
|
1075
|
+
const reading = (async () => {
|
|
1076
|
+
try {
|
|
1077
|
+
for await (const line of engine.lines)
|
|
1078
|
+
peer.receive(line);
|
|
1079
|
+
finishEnd(new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`));
|
|
1080
|
+
} catch (error) {
|
|
1081
|
+
const failed = error instanceof Error ? error : new Error(String(error));
|
|
1082
|
+
finishEnd(failed);
|
|
1083
|
+
await engine.stop().catch(() => {
|
|
1084
|
+
return;
|
|
1085
|
+
});
|
|
1086
|
+
}
|
|
1087
|
+
})();
|
|
1088
|
+
try {
|
|
1089
|
+
emitStartupPhase(onStartupPhase, "initializing");
|
|
1090
|
+
await initializeCodexPeer(peer, config.version);
|
|
1091
|
+
const providerPid = await engine.pidReady ?? engine.pid;
|
|
1092
|
+
if (endedError !== undefined)
|
|
1093
|
+
throw endedError;
|
|
1094
|
+
ready = true;
|
|
1095
|
+
return { engine, peer, reading, providerPid };
|
|
1096
|
+
} catch (error) {
|
|
1097
|
+
await stopConnection({ engine, reading }, { error });
|
|
1098
|
+
throw error;
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
let wsClient;
|
|
1102
|
+
let spawnedEngine;
|
|
1103
|
+
let endedError;
|
|
1104
|
+
let ready = false;
|
|
1105
|
+
const peer = createJsonRpcPeer2({
|
|
1106
|
+
header: "omitted",
|
|
1107
|
+
requestTimeoutMs: REQUEST_MS,
|
|
1108
|
+
send: (line) => {
|
|
1109
|
+
if (wsClient === undefined) {
|
|
1110
|
+
throw new Error("Codex Unix socket transport is not connected");
|
|
1111
|
+
}
|
|
1112
|
+
wsClient.send(line);
|
|
1113
|
+
},
|
|
1114
|
+
...handlers
|
|
1115
|
+
});
|
|
1116
|
+
const finishEnd = (error) => {
|
|
1117
|
+
if (endedError !== undefined)
|
|
1118
|
+
return;
|
|
1119
|
+
endedError = error;
|
|
1120
|
+
peer.close(error);
|
|
1121
|
+
if (ready)
|
|
1122
|
+
onEnd(error);
|
|
1123
|
+
};
|
|
1124
|
+
const onMessage = (line) => {
|
|
1125
|
+
try {
|
|
1126
|
+
peer.receive(line);
|
|
1127
|
+
} catch (error) {
|
|
1128
|
+
const failed = error instanceof Error ? error : new Error(String(error));
|
|
1129
|
+
finishEnd(failed);
|
|
1130
|
+
wsClient?.close().catch(() => {
|
|
1131
|
+
return;
|
|
1132
|
+
});
|
|
1133
|
+
spawnedEngine?.stop().catch(() => {
|
|
1134
|
+
return;
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
};
|
|
1138
|
+
const onClose = (error) => {
|
|
1139
|
+
finishEnd(error);
|
|
1140
|
+
};
|
|
1141
|
+
if (transport.kind === "unix-listen") {
|
|
1142
|
+
assertCodexUnixListenTargetAvailable(transport.socketPath, "createCodexDriver");
|
|
1143
|
+
const env = engineEnvironment2(profile, config.ambient);
|
|
1144
|
+
emitStartupPhase(onStartupPhase, "spawning");
|
|
1145
|
+
spawnedEngine = spawnEngineProcess2({
|
|
1146
|
+
executable: config.executable,
|
|
1147
|
+
args: [
|
|
1148
|
+
...config.prefix,
|
|
1149
|
+
"app-server",
|
|
1150
|
+
"--listen",
|
|
1151
|
+
`unix://${transport.socketPath}`,
|
|
1152
|
+
...extraArgs
|
|
1153
|
+
],
|
|
1154
|
+
cwd,
|
|
1155
|
+
env,
|
|
1156
|
+
signal,
|
|
1157
|
+
stdoutMode: "drain",
|
|
1158
|
+
...config.maxLineBytes !== undefined && { maxLineBytes: config.maxLineBytes }
|
|
1159
|
+
});
|
|
1160
|
+
try {
|
|
1161
|
+
wsClient = await dialWithEngineRace({
|
|
1162
|
+
socketPath: transport.socketPath,
|
|
1163
|
+
listenTimeoutMs: transport.listenTimeoutMs ?? DEFAULT_LISTEN_TIMEOUT_MS,
|
|
1164
|
+
...config.maxLineBytes !== undefined && { maxFrameBytes: config.maxLineBytes },
|
|
1165
|
+
signal,
|
|
1166
|
+
engine: spawnedEngine,
|
|
1167
|
+
onMessage,
|
|
1168
|
+
onClose
|
|
1169
|
+
});
|
|
1170
|
+
} catch (error) {
|
|
1171
|
+
peer.close(error);
|
|
1172
|
+
await spawnedEngine.stop().catch(() => {
|
|
1173
|
+
return;
|
|
1174
|
+
});
|
|
1175
|
+
throw error;
|
|
1176
|
+
}
|
|
1177
|
+
} else {
|
|
1178
|
+
try {
|
|
1179
|
+
wsClient = await connectCodexUnixSocket({
|
|
1180
|
+
socketPath: transport.socketPath,
|
|
1181
|
+
...transport.expectedOwnerUid !== undefined && {
|
|
1182
|
+
expectedOwnerUid: transport.expectedOwnerUid
|
|
1183
|
+
},
|
|
1184
|
+
signal,
|
|
1185
|
+
...config.maxLineBytes !== undefined && { maxFrameBytes: config.maxLineBytes },
|
|
1186
|
+
onMessage,
|
|
1187
|
+
onClose
|
|
1188
|
+
});
|
|
1189
|
+
} catch (error) {
|
|
1190
|
+
peer.close(error);
|
|
1191
|
+
throw error;
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
const activeWs = wsClient;
|
|
1195
|
+
const compositeEngine = {
|
|
1196
|
+
async stop() {
|
|
1197
|
+
try {
|
|
1198
|
+
await activeWs.close();
|
|
1199
|
+
} finally {
|
|
1200
|
+
if (spawnedEngine !== undefined)
|
|
1201
|
+
await spawnedEngine.stop();
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
};
|
|
1205
|
+
const reading = activeWs.closed;
|
|
1206
|
+
try {
|
|
1207
|
+
if (endedError !== undefined)
|
|
1208
|
+
throw endedError;
|
|
1209
|
+
emitStartupPhase(onStartupPhase, "initializing");
|
|
1210
|
+
await initializeCodexPeer(peer, config.version);
|
|
1211
|
+
if (endedError !== undefined)
|
|
1212
|
+
throw endedError;
|
|
1213
|
+
const providerPid = spawnedEngine !== undefined ? await spawnedEngine.pidReady ?? spawnedEngine.pid : undefined;
|
|
1214
|
+
if (endedError !== undefined)
|
|
1215
|
+
throw endedError;
|
|
1216
|
+
ready = true;
|
|
1217
|
+
return { engine: compositeEngine, peer, reading, providerPid };
|
|
1218
|
+
} catch (error) {
|
|
1219
|
+
await stopConnection({ engine: compositeEngine, reading }, { error });
|
|
1220
|
+
throw error;
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
// src/agent-executor/codex/limits.ts
|
|
1225
|
+
import { z as z2 } from "zod";
|
|
1226
|
+
var MAX_WINDOW_NAME_CHARS = 256;
|
|
1227
|
+
var MAX_PLAN_WINDOWS = 32;
|
|
1228
|
+
var WindowSchema = z2.looseObject({
|
|
1229
|
+
usedPercent: z2.number().min(0),
|
|
1230
|
+
windowDurationMins: z2.number().positive().nullable().optional(),
|
|
1231
|
+
resetsAt: z2.number().nonnegative().nullable().optional()
|
|
1232
|
+
});
|
|
1233
|
+
var SnapshotSchema = z2.looseObject({
|
|
1234
|
+
limitId: z2.string().nullable().optional(),
|
|
1235
|
+
limitName: z2.string().nullable().optional(),
|
|
1236
|
+
primary: WindowSchema.nullable().optional(),
|
|
1237
|
+
secondary: WindowSchema.nullable().optional()
|
|
1238
|
+
});
|
|
1239
|
+
function positiveSafeInt(value) {
|
|
1240
|
+
return isPositiveSafeInteger(value) ? value : undefined;
|
|
1241
|
+
}
|
|
1242
|
+
function clampLabel(value) {
|
|
1243
|
+
const trimmed = nonEmptyString(value)?.trim();
|
|
1244
|
+
if (trimmed === undefined)
|
|
1245
|
+
return;
|
|
1246
|
+
return trimmed.slice(0, MAX_WINDOW_NAME_CHARS);
|
|
1247
|
+
}
|
|
1248
|
+
function appendBucketWindows(out, seenNames, bucketId, seedKey, snapshot) {
|
|
1249
|
+
const label = clampLabel(snapshot.limitName);
|
|
1250
|
+
const primary = snapshot.primary ?? undefined;
|
|
1251
|
+
const secondary = snapshot.secondary ?? undefined;
|
|
1252
|
+
const primaryMins = positiveSafeInt(primary?.windowDurationMins);
|
|
1253
|
+
const secondaryMins = positiveSafeInt(secondary?.windowDurationMins);
|
|
1254
|
+
const duplicateDuration = primary !== undefined && secondary !== undefined && primaryMins !== undefined && primaryMins === secondaryMins;
|
|
1255
|
+
const slots = [
|
|
1256
|
+
["primary", primary, primaryMins],
|
|
1257
|
+
["secondary", secondary, secondaryMins]
|
|
1258
|
+
];
|
|
1259
|
+
for (const [slot, window, mins] of slots) {
|
|
1260
|
+
if (window === undefined || out.length >= MAX_PLAN_WINDOWS)
|
|
1261
|
+
continue;
|
|
1262
|
+
const suffix = mins === undefined ? `:${slot}` : duplicateDuration ? `:${mins}m:${slot}` : `:${mins}m`;
|
|
1263
|
+
const name = clampUniqueWindowName(bucketId, suffix, seenNames, `${seedKey}:${bucketId}:${slot}`, MAX_WINDOW_NAME_CHARS);
|
|
1264
|
+
const resetsAt = window.resetsAt !== undefined && window.resetsAt !== null && window.resetsAt > 0 ? epochSecondsToIso(window.resetsAt) : undefined;
|
|
1265
|
+
out.push(PlanWindowSchema2.parse({
|
|
1266
|
+
name,
|
|
1267
|
+
usedPercent: Math.min(100, window.usedPercent),
|
|
1268
|
+
...resetsAt !== undefined && { resetsAt },
|
|
1269
|
+
...mins !== undefined && { windowDurationMins: mins },
|
|
1270
|
+
...label !== undefined && { label }
|
|
1271
|
+
}));
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
function isPlainRecord(value) {
|
|
1275
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1276
|
+
}
|
|
1277
|
+
function codexPlanWindows(reported) {
|
|
1278
|
+
const windows = [];
|
|
1279
|
+
const seenNames = new Set;
|
|
1280
|
+
if (isPlainRecord(reported) && (("rateLimits" in reported) || ("rateLimitsByLimitId" in reported))) {
|
|
1281
|
+
const seenLimitIds = new Set;
|
|
1282
|
+
const rawById = reported.rateLimitsByLimitId;
|
|
1283
|
+
if (isPlainRecord(rawById)) {
|
|
1284
|
+
for (const mapKey of Object.keys(rawById).sort((a, b) => a.localeCompare(b))) {
|
|
1285
|
+
const parsed = SnapshotSchema.safeParse(rawById[mapKey]);
|
|
1286
|
+
if (!parsed.success)
|
|
1287
|
+
continue;
|
|
1288
|
+
const limitId = nonEmptyString(parsed.data.limitId)?.trim() ?? nonEmptyString(mapKey)?.trim() ?? "limit";
|
|
1289
|
+
seenLimitIds.add(limitId);
|
|
1290
|
+
appendBucketWindows(windows, seenNames, limitId, mapKey, parsed.data);
|
|
1291
|
+
if (windows.length >= MAX_PLAN_WINDOWS)
|
|
1292
|
+
return windows;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
if (windows.length < MAX_PLAN_WINDOWS && reported.rateLimits !== undefined) {
|
|
1296
|
+
const parsedSingle = SnapshotSchema.safeParse(reported.rateLimits);
|
|
1297
|
+
if (parsedSingle.success) {
|
|
1298
|
+
const explicitId = nonEmptyString(parsedSingle.data.limitId)?.trim();
|
|
1299
|
+
const shouldIncludeSingle = seenLimitIds.size === 0 || explicitId !== undefined && !seenLimitIds.has(explicitId);
|
|
1300
|
+
if (shouldIncludeSingle) {
|
|
1301
|
+
appendBucketWindows(windows, seenNames, explicitId ?? "limit", explicitId ?? "rateLimits", parsedSingle.data);
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
return windows;
|
|
1306
|
+
}
|
|
1307
|
+
const single = SnapshotSchema.safeParse(reported);
|
|
1308
|
+
if (!single.success)
|
|
1309
|
+
return [];
|
|
1310
|
+
const limitId = nonEmptyString(single.data.limitId)?.trim() ?? "limit";
|
|
1311
|
+
appendBucketWindows(windows, seenNames, limitId, limitId, single.data);
|
|
1312
|
+
return windows;
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
// src/agent-executor/codex/thread-controls.ts
|
|
1316
|
+
var MAX_UINT32 = 4294967295;
|
|
1317
|
+
var MAX_THREAD_LIST_IDS = 100;
|
|
1318
|
+
function assertNonEmptyThreadId(threadId, caller) {
|
|
1319
|
+
if (typeof threadId !== "string" || threadId.trim().length === 0) {
|
|
1320
|
+
throw new TypeError(`[stitchkit] ${caller}: threadId must be a non-empty string`);
|
|
1321
|
+
}
|
|
1322
|
+
return threadId;
|
|
1323
|
+
}
|
|
1324
|
+
function assertRequiredNonEmptyString(value, field, caller) {
|
|
1325
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1326
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
|
|
1327
|
+
}
|
|
1328
|
+
return value;
|
|
1329
|
+
}
|
|
1330
|
+
function assertOptionalNonEmptyString(value, field, caller) {
|
|
1331
|
+
if (value === undefined)
|
|
1332
|
+
return;
|
|
1333
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1334
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must be a non-empty string`);
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
function assertOptionalLimit(limit, caller) {
|
|
1338
|
+
if (limit === undefined || limit === null)
|
|
1339
|
+
return;
|
|
1340
|
+
assertNonNegativeSafeInteger(`[stitchkit] ${caller}: limit`, limit, TypeError);
|
|
1341
|
+
if (limit > MAX_UINT32) {
|
|
1342
|
+
throw new TypeError(`[stitchkit] ${caller}: limit must not exceed ${MAX_UINT32}`);
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
function assertBoundedThreadIdFilter(ids, field, caller) {
|
|
1346
|
+
if (ids === undefined || ids === null)
|
|
1347
|
+
return ids;
|
|
1348
|
+
if (!Array.isArray(ids)) {
|
|
1349
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must be an array of strings`);
|
|
1350
|
+
}
|
|
1351
|
+
if (ids.length > MAX_THREAD_LIST_IDS) {
|
|
1352
|
+
throw new TypeError(`[stitchkit] ${caller}: ${field} must contain at most ${MAX_THREAD_LIST_IDS} entries`);
|
|
1353
|
+
}
|
|
1354
|
+
for (const id of ids) {
|
|
1355
|
+
if (typeof id !== "string" || id.trim().length === 0) {
|
|
1356
|
+
throw new TypeError(`[stitchkit] ${caller}: every ${field} entry must be a non-empty string`);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
return [...ids];
|
|
1360
|
+
}
|
|
1361
|
+
function validateGitInfoUpdate(gitInfo, caller) {
|
|
1362
|
+
if (gitInfo === undefined)
|
|
1363
|
+
return;
|
|
1364
|
+
if (gitInfo === null)
|
|
1365
|
+
return null;
|
|
1366
|
+
if (typeof gitInfo !== "object" || Array.isArray(gitInfo)) {
|
|
1367
|
+
throw new TypeError(`[stitchkit] ${caller}: gitInfo must be a plain object or null`);
|
|
1368
|
+
}
|
|
1369
|
+
const normalized = {};
|
|
1370
|
+
for (const field of ["branch", "originUrl", "sha"]) {
|
|
1371
|
+
const value = gitInfo[field];
|
|
1372
|
+
if (value === undefined)
|
|
1373
|
+
continue;
|
|
1374
|
+
if (value === null) {
|
|
1375
|
+
normalized[field] = null;
|
|
1376
|
+
continue;
|
|
1377
|
+
}
|
|
1378
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
1379
|
+
throw new TypeError(`[stitchkit] ${caller}: gitInfo.${field} must be a non-empty string or null`);
|
|
1380
|
+
}
|
|
1381
|
+
normalized[field] = value;
|
|
1382
|
+
}
|
|
1383
|
+
return normalized;
|
|
1384
|
+
}
|
|
1385
|
+
function normalizeListThreadsCwd(cwd) {
|
|
1386
|
+
if (cwd === undefined || cwd === null || typeof cwd === "string")
|
|
1387
|
+
return cwd;
|
|
1388
|
+
return [...cwd];
|
|
1389
|
+
}
|
|
1390
|
+
function buildListThreadsPayload(params) {
|
|
1391
|
+
const caller = "CodexControlClient.listThreads";
|
|
1392
|
+
assertOptionalLimit(params?.limit, caller);
|
|
1393
|
+
const includedThreadIds = assertBoundedThreadIdFilter(params?.includedThreadIds, "includedThreadIds", caller);
|
|
1394
|
+
const excludedThreadIds = assertBoundedThreadIdFilter(params?.excludedThreadIds, "excludedThreadIds", caller);
|
|
1395
|
+
const cwd = normalizeListThreadsCwd(params?.cwd);
|
|
1396
|
+
return {
|
|
1397
|
+
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1398
|
+
...params?.limit !== undefined && { limit: params.limit },
|
|
1399
|
+
...params?.sortKey !== undefined && { sortKey: params.sortKey },
|
|
1400
|
+
...params?.sortDirection !== undefined && { sortDirection: params.sortDirection },
|
|
1401
|
+
...params?.modelProviders !== undefined && {
|
|
1402
|
+
modelProviders: params.modelProviders === null ? null : [...params.modelProviders]
|
|
1403
|
+
},
|
|
1404
|
+
...params?.sourceKinds !== undefined && {
|
|
1405
|
+
sourceKinds: params.sourceKinds === null ? null : [...params.sourceKinds]
|
|
1406
|
+
},
|
|
1407
|
+
...params?.archived !== undefined && { archived: params.archived },
|
|
1408
|
+
...cwd !== undefined && { cwd },
|
|
1409
|
+
...params?.searchTerm !== undefined && { searchTerm: params.searchTerm },
|
|
1410
|
+
...params?.sectionId !== undefined && { sectionId: params.sectionId },
|
|
1411
|
+
...includedThreadIds !== undefined && {
|
|
1412
|
+
includedThreadIds: includedThreadIds === null ? null : [...includedThreadIds]
|
|
1413
|
+
},
|
|
1414
|
+
...excludedThreadIds !== undefined && {
|
|
1415
|
+
excludedThreadIds: excludedThreadIds === null ? null : [...excludedThreadIds]
|
|
1416
|
+
},
|
|
1417
|
+
...params?.originators !== undefined && {
|
|
1418
|
+
originators: params.originators === null ? null : [...params.originators]
|
|
1419
|
+
},
|
|
1420
|
+
...params?.currentAccountOnly !== undefined && {
|
|
1421
|
+
currentAccountOnly: params.currentAccountOnly
|
|
1422
|
+
},
|
|
1423
|
+
...params?.useStateDbOnly !== undefined && { useStateDbOnly: params.useStateDbOnly }
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
function createCodexThreadControlMethods(call) {
|
|
1427
|
+
return {
|
|
1428
|
+
async revertThread(params) {
|
|
1429
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.revertThread");
|
|
1430
|
+
const beforeTurnId = assertRequiredNonEmptyString(params.beforeTurnId, "beforeTurnId", "CodexControlClient.revertThread");
|
|
1431
|
+
const rawReply = await call("thread/revert", { threadId, beforeTurnId });
|
|
1432
|
+
const parsed = CodexThreadRevertResponseSchema.parse(rawReply);
|
|
1433
|
+
return {
|
|
1434
|
+
thread: safeJsonValue(parsed.thread),
|
|
1435
|
+
turnsBackwardsCursor: parsed.turnsBackwardsCursor ?? null,
|
|
1436
|
+
itemsBackwardsCursor: parsed.itemsBackwardsCursor ?? null
|
|
1437
|
+
};
|
|
1438
|
+
},
|
|
1439
|
+
async injectItems(params) {
|
|
1440
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.injectItems");
|
|
1441
|
+
if (!Array.isArray(params.items)) {
|
|
1442
|
+
throw new TypeError("[stitchkit] CodexControlClient.injectItems: items must be an array");
|
|
1443
|
+
}
|
|
1444
|
+
const items = params.items.map((item) => safeJsonValue(item));
|
|
1445
|
+
return call("thread/inject_items", { threadId, items });
|
|
1446
|
+
},
|
|
1447
|
+
async unsubscribeThread(params) {
|
|
1448
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unsubscribeThread");
|
|
1449
|
+
return call("thread/unsubscribe", { threadId });
|
|
1450
|
+
},
|
|
1451
|
+
async listThreads(params) {
|
|
1452
|
+
return call("thread/list", buildListThreadsPayload(params));
|
|
1453
|
+
},
|
|
1454
|
+
async listLoadedThreads(params) {
|
|
1455
|
+
assertOptionalLimit(params?.limit, "CodexControlClient.listLoadedThreads");
|
|
1456
|
+
return call("thread/loaded/list", {
|
|
1457
|
+
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1458
|
+
...params?.limit !== undefined && { limit: params.limit }
|
|
1459
|
+
});
|
|
1460
|
+
},
|
|
1461
|
+
async archiveThread(params) {
|
|
1462
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.archiveThread");
|
|
1463
|
+
return call("thread/archive", { threadId });
|
|
1464
|
+
},
|
|
1465
|
+
async unarchiveThread(params) {
|
|
1466
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.unarchiveThread");
|
|
1467
|
+
return call("thread/unarchive", { threadId });
|
|
1468
|
+
},
|
|
1469
|
+
async updateThreadMetadata(params) {
|
|
1470
|
+
const caller = "CodexControlClient.updateThreadMetadata";
|
|
1471
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1472
|
+
const gitInfo = validateGitInfoUpdate(params.gitInfo, caller);
|
|
1473
|
+
return call("thread/metadata/update", {
|
|
1474
|
+
threadId,
|
|
1475
|
+
...gitInfo !== undefined && { gitInfo }
|
|
1476
|
+
});
|
|
1477
|
+
},
|
|
1478
|
+
async setThreadName(params) {
|
|
1479
|
+
const caller = "CodexControlClient.setThreadName";
|
|
1480
|
+
const threadId = assertNonEmptyThreadId(params.threadId, caller);
|
|
1481
|
+
const name = assertRequiredNonEmptyString(params.name, "name", caller);
|
|
1482
|
+
return call("thread/name/set", { threadId, name });
|
|
1483
|
+
}
|
|
1484
|
+
};
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
// src/agent-executor/codex/control-client.ts
|
|
1488
|
+
function assertOptionalItemsCursor(cursor, caller) {
|
|
1489
|
+
if (cursor === undefined)
|
|
1490
|
+
return;
|
|
1491
|
+
if (typeof cursor === "string") {
|
|
1492
|
+
if (cursor.trim().length === 0) {
|
|
1493
|
+
throw new TypeError(`[stitchkit] ${caller}: cursor must be a non-empty string`);
|
|
1494
|
+
}
|
|
1495
|
+
return;
|
|
1496
|
+
}
|
|
1497
|
+
if (typeof cursor !== "object" || cursor === null || cursor.type !== "item" || typeof cursor.itemId !== "string" || cursor.itemId.trim().length === 0) {
|
|
1498
|
+
throw new TypeError(`[stitchkit] ${caller}: item cursor must have type "item" and a non-empty itemId`);
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
function createCodexControlClient(input) {
|
|
1502
|
+
const call = async (method, params) => {
|
|
1503
|
+
input.ensureAlive();
|
|
1504
|
+
return input.peer.request(method, params);
|
|
1505
|
+
};
|
|
1506
|
+
return {
|
|
1507
|
+
readConfig(params) {
|
|
1508
|
+
return call("config/read", {
|
|
1509
|
+
...params?.cwd !== undefined && { cwd: params.cwd },
|
|
1510
|
+
...params?.includeLayers !== undefined && { includeLayers: params.includeLayers }
|
|
1511
|
+
});
|
|
1512
|
+
},
|
|
1513
|
+
async readThread(params) {
|
|
1514
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.readThread");
|
|
1515
|
+
return call("thread/read", {
|
|
1516
|
+
threadId,
|
|
1517
|
+
...params.includeTurns !== undefined && { includeTurns: params.includeTurns }
|
|
1518
|
+
});
|
|
1519
|
+
},
|
|
1520
|
+
listCollaborationModes() {
|
|
1521
|
+
return call("collaborationMode/list", {});
|
|
1522
|
+
},
|
|
1523
|
+
async listTurns(params) {
|
|
1524
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.listTurns");
|
|
1525
|
+
assertOptionalLimit(params.limit, "CodexControlClient.listTurns");
|
|
1526
|
+
return call("thread/turns/list", {
|
|
1527
|
+
threadId,
|
|
1528
|
+
...params.cursor !== undefined && { cursor: params.cursor },
|
|
1529
|
+
...params.limit !== undefined && { limit: params.limit },
|
|
1530
|
+
...params.itemsView !== undefined && { itemsView: params.itemsView },
|
|
1531
|
+
...params.sortDirection !== undefined && { sortDirection: params.sortDirection }
|
|
1532
|
+
});
|
|
1533
|
+
},
|
|
1534
|
+
async listItems(params) {
|
|
1535
|
+
const threadId = assertNonEmptyThreadId(params.threadId, "CodexControlClient.listItems");
|
|
1536
|
+
assertOptionalLimit(params.limit, "CodexControlClient.listItems");
|
|
1537
|
+
assertOptionalNonEmptyString(params.turnId, "turnId", "CodexControlClient.listItems");
|
|
1538
|
+
assertOptionalItemsCursor(params.cursor, "CodexControlClient.listItems");
|
|
1539
|
+
return call("thread/items/list", {
|
|
1540
|
+
threadId,
|
|
1541
|
+
...params.turnId !== undefined && { turnId: params.turnId },
|
|
1542
|
+
...params.cursor !== undefined && { cursor: safeJsonValue(params.cursor) },
|
|
1543
|
+
...params.limit !== undefined && { limit: params.limit },
|
|
1544
|
+
...params.sortDirection !== undefined && { sortDirection: params.sortDirection },
|
|
1545
|
+
...params.deferOutput !== undefined && {
|
|
1546
|
+
deferOutput: safeJsonValue(params.deferOutput)
|
|
1547
|
+
}
|
|
1548
|
+
});
|
|
1549
|
+
},
|
|
1550
|
+
listMcpServerStatus(params) {
|
|
1551
|
+
return call("mcpServerStatus/list", {
|
|
1552
|
+
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1553
|
+
...params?.limit !== undefined && { limit: params.limit },
|
|
1554
|
+
...params?.threadId !== undefined && { threadId: params.threadId },
|
|
1555
|
+
...params?.serverName !== undefined && { serverName: params.serverName },
|
|
1556
|
+
...params?.detail !== undefined && { detail: params.detail }
|
|
1557
|
+
});
|
|
1558
|
+
},
|
|
1559
|
+
listSkills(params) {
|
|
1560
|
+
return call("skills/list", {
|
|
1561
|
+
...params?.cwds !== undefined && { cwds: [...params.cwds] },
|
|
1562
|
+
...params?.forceReload !== undefined && { forceReload: params.forceReload }
|
|
1563
|
+
});
|
|
1564
|
+
},
|
|
1565
|
+
listModels(params) {
|
|
1566
|
+
return call("model/list", {
|
|
1567
|
+
...params?.cursor !== undefined && { cursor: params.cursor },
|
|
1568
|
+
...params?.limit !== undefined && { limit: params.limit },
|
|
1569
|
+
...params?.includeHidden !== undefined && { includeHidden: params.includeHidden },
|
|
1570
|
+
...params?.modelProvider !== undefined && { modelProvider: params.modelProvider }
|
|
1571
|
+
});
|
|
1572
|
+
},
|
|
1573
|
+
readAccount(params) {
|
|
1574
|
+
return call("account/read", {
|
|
1575
|
+
...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
|
|
1576
|
+
});
|
|
1577
|
+
},
|
|
1578
|
+
readRateLimits() {
|
|
1579
|
+
return call("account/rateLimits/read");
|
|
1580
|
+
},
|
|
1581
|
+
...createCodexThreadControlMethods(call)
|
|
1582
|
+
};
|
|
1583
|
+
}
|
|
1584
|
+
function bindCodexSessionThreadControls(controlClient, threadId) {
|
|
1585
|
+
return {
|
|
1586
|
+
readThread(params) {
|
|
1587
|
+
return controlClient.readThread({
|
|
1588
|
+
...params,
|
|
1589
|
+
threadId: params?.threadId ?? threadId
|
|
1590
|
+
});
|
|
1591
|
+
},
|
|
1592
|
+
listTurns(params) {
|
|
1593
|
+
return controlClient.listTurns({
|
|
1594
|
+
...params,
|
|
1595
|
+
threadId: params?.threadId ?? threadId
|
|
1596
|
+
});
|
|
1597
|
+
},
|
|
1598
|
+
listItems(params) {
|
|
1599
|
+
return controlClient.listItems({
|
|
1600
|
+
...params,
|
|
1601
|
+
threadId: params?.threadId ?? threadId
|
|
1602
|
+
});
|
|
1603
|
+
},
|
|
1604
|
+
revertThread(params) {
|
|
1605
|
+
return controlClient.revertThread({
|
|
1606
|
+
...params,
|
|
1607
|
+
threadId: params.threadId ?? threadId
|
|
1608
|
+
});
|
|
1609
|
+
},
|
|
1610
|
+
injectItems(params) {
|
|
1611
|
+
return controlClient.injectItems({
|
|
1612
|
+
...params,
|
|
1613
|
+
threadId: params.threadId ?? threadId
|
|
1614
|
+
});
|
|
1615
|
+
},
|
|
1616
|
+
unsubscribeThread(params) {
|
|
1617
|
+
return controlClient.unsubscribeThread({
|
|
1618
|
+
threadId: params?.threadId ?? threadId
|
|
1619
|
+
});
|
|
1620
|
+
},
|
|
1621
|
+
archiveThread(params) {
|
|
1622
|
+
return controlClient.archiveThread({
|
|
1623
|
+
threadId: params?.threadId ?? threadId
|
|
1624
|
+
});
|
|
1625
|
+
},
|
|
1626
|
+
unarchiveThread(params) {
|
|
1627
|
+
return controlClient.unarchiveThread({
|
|
1628
|
+
threadId: params?.threadId ?? threadId
|
|
1629
|
+
});
|
|
1630
|
+
},
|
|
1631
|
+
updateThreadMetadata(params) {
|
|
1632
|
+
return controlClient.updateThreadMetadata({
|
|
1633
|
+
...params,
|
|
1634
|
+
threadId: params?.threadId ?? threadId
|
|
1635
|
+
});
|
|
1636
|
+
},
|
|
1637
|
+
setThreadName(params) {
|
|
1638
|
+
return controlClient.setThreadName({
|
|
1639
|
+
...params,
|
|
1640
|
+
threadId: params.threadId ?? threadId
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
};
|
|
1644
|
+
}
|
|
1645
|
+
|
|
172
1646
|
// src/agent-executor/codex/classify.ts
|
|
173
1647
|
var raw = (type) => ({ source: "codex", type });
|
|
174
|
-
var
|
|
1648
|
+
var CODEX_TOOL_ITEMS = new Set([
|
|
175
1649
|
"commandExecution",
|
|
176
1650
|
"fileChange",
|
|
177
1651
|
"mcpToolCall",
|
|
178
1652
|
"dynamicToolCall",
|
|
179
|
-
"
|
|
1653
|
+
"collabAgentToolCall",
|
|
1654
|
+
"webSearch",
|
|
1655
|
+
"imageView",
|
|
1656
|
+
"sleep",
|
|
1657
|
+
"imageGeneration",
|
|
1658
|
+
"functionCallOutput"
|
|
1659
|
+
]);
|
|
1660
|
+
var STATUSLESS_TOOL_ITEMS = new Set([
|
|
1661
|
+
"webSearch",
|
|
1662
|
+
"imageView",
|
|
1663
|
+
"sleep",
|
|
1664
|
+
"functionCallOutput"
|
|
180
1665
|
]);
|
|
181
|
-
var
|
|
1666
|
+
var CODEX_CONTENT_ITEMS = new Set([
|
|
182
1667
|
"agentMessage",
|
|
183
1668
|
"reasoning",
|
|
184
1669
|
"userMessage",
|
|
185
1670
|
"plan",
|
|
186
1671
|
"contextCompaction",
|
|
187
|
-
"hookPrompt"
|
|
1672
|
+
"hookPrompt",
|
|
1673
|
+
"subAgentActivity",
|
|
1674
|
+
"enteredReviewMode",
|
|
1675
|
+
"exitedReviewMode"
|
|
188
1676
|
]);
|
|
1677
|
+
var KNOWN_CODEX_ERROR_CODES = new Set([
|
|
1678
|
+
"contextWindowExceeded",
|
|
1679
|
+
"sessionBudgetExceeded",
|
|
1680
|
+
"usageLimitExceeded",
|
|
1681
|
+
"rateLimitExceeded",
|
|
1682
|
+
"flexUnavailable",
|
|
1683
|
+
"serverOverloaded",
|
|
1684
|
+
"modelNotFound",
|
|
1685
|
+
"policyCapacityUnavailable",
|
|
1686
|
+
"cyberPolicy",
|
|
1687
|
+
"bioPolicy",
|
|
1688
|
+
"misalignmentPolicyViolation",
|
|
1689
|
+
"tooManyDenials",
|
|
1690
|
+
"internalServerError",
|
|
1691
|
+
"unauthorized",
|
|
1692
|
+
"badRequest",
|
|
1693
|
+
"threadRollbackFailed",
|
|
1694
|
+
"sandboxError",
|
|
1695
|
+
"other",
|
|
1696
|
+
"inferenceHookDenied"
|
|
1697
|
+
]);
|
|
1698
|
+
var KNOWN_CODEX_ERROR_OBJECT_KEYS = new Set([
|
|
1699
|
+
"httpConnectionFailed",
|
|
1700
|
+
"responseStreamConnectionFailed",
|
|
1701
|
+
"responseStreamDisconnected",
|
|
1702
|
+
"responseTooManyFailedAttempts",
|
|
1703
|
+
"activeTurnNotSteerable"
|
|
1704
|
+
]);
|
|
1705
|
+
var MAX_ERROR_INFO_SUMMARY_CHARS = 512;
|
|
189
1706
|
function toolName(item) {
|
|
190
|
-
|
|
191
|
-
|
|
1707
|
+
if (item.type === "mcpToolCall" || item.type === "dynamicToolCall" || item.type === "collabAgentToolCall") {
|
|
1708
|
+
return nonEmptyString(Reflect.get(item, "tool")) ?? item.type;
|
|
1709
|
+
}
|
|
1710
|
+
if (item.type === "functionCallOutput") {
|
|
1711
|
+
return nonEmptyString(Reflect.get(item, "name")) ?? item.type;
|
|
1712
|
+
}
|
|
1713
|
+
return item.type;
|
|
192
1714
|
}
|
|
193
1715
|
function toolInput(item) {
|
|
194
1716
|
const { id: _id, type: _type, status: _status, aggregatedOutput: _output, ...rest } = item;
|
|
195
1717
|
return safeJsonValue(rest);
|
|
196
1718
|
}
|
|
1719
|
+
function isKnownCodexErrorInfo(info) {
|
|
1720
|
+
if (typeof info === "string")
|
|
1721
|
+
return KNOWN_CODEX_ERROR_CODES.has(info);
|
|
1722
|
+
if (typeof info === "object" && info !== null && !Array.isArray(info)) {
|
|
1723
|
+
const keys = Object.keys(info);
|
|
1724
|
+
return keys.length === 1 && keys[0] !== undefined && KNOWN_CODEX_ERROR_OBJECT_KEYS.has(keys[0]);
|
|
1725
|
+
}
|
|
1726
|
+
return false;
|
|
1727
|
+
}
|
|
1728
|
+
function formatCodexErrorInfo(info) {
|
|
1729
|
+
if (info === null || info === undefined)
|
|
1730
|
+
return;
|
|
1731
|
+
if (typeof info === "string") {
|
|
1732
|
+
const trimmed = info.trim();
|
|
1733
|
+
return trimmed.length > 0 ? trimmed.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS) : undefined;
|
|
1734
|
+
}
|
|
1735
|
+
try {
|
|
1736
|
+
const serialized = JSON.stringify(safeJsonValue(info));
|
|
1737
|
+
if (serialized === undefined || serialized.length === 0)
|
|
1738
|
+
return;
|
|
1739
|
+
return serialized.length > MAX_ERROR_INFO_SUMMARY_CHARS ? `${serialized.slice(0, MAX_ERROR_INFO_SUMMARY_CHARS - 1)}…` : serialized;
|
|
1740
|
+
} catch {
|
|
1741
|
+
return String(info).slice(0, MAX_ERROR_INFO_SUMMARY_CHARS);
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
function codexFailureMessage(turn) {
|
|
1745
|
+
const rawMessage = turn.error?.message.trim() ?? "";
|
|
1746
|
+
const info = turn.error?.codexErrorInfo;
|
|
1747
|
+
const infoSummary = formatCodexErrorInfo(info);
|
|
1748
|
+
if (rawMessage.length > 0) {
|
|
1749
|
+
if (infoSummary !== undefined && !isKnownCodexErrorInfo(info) && !rawMessage.includes(infoSummary)) {
|
|
1750
|
+
return `${rawMessage} (${infoSummary})`;
|
|
1751
|
+
}
|
|
1752
|
+
return rawMessage;
|
|
1753
|
+
}
|
|
1754
|
+
if (infoSummary !== undefined) {
|
|
1755
|
+
return `Codex ended the turn ${turn.status} (${infoSummary})`;
|
|
1756
|
+
}
|
|
1757
|
+
return `Codex ended the turn ${turn.status}`;
|
|
1758
|
+
}
|
|
197
1759
|
function httpStatusOf(value, depth = 0) {
|
|
198
1760
|
if (depth > 3 || typeof value !== "object" || value === null)
|
|
199
1761
|
return;
|
|
@@ -219,6 +1781,53 @@ function failureKind(info) {
|
|
|
219
1781
|
return "rateLimited";
|
|
220
1782
|
return "restartRecommended";
|
|
221
1783
|
}
|
|
1784
|
+
function normalizeCodexTokenTotals(rawTotals) {
|
|
1785
|
+
if (rawTotals === undefined)
|
|
1786
|
+
return;
|
|
1787
|
+
const normalized = {
|
|
1788
|
+
...rawTotals.inputTokens !== undefined && { inputTokens: rawTotals.inputTokens },
|
|
1789
|
+
...rawTotals.outputTokens !== undefined && { outputTokens: rawTotals.outputTokens },
|
|
1790
|
+
...rawTotals.cachedInputTokens !== undefined && {
|
|
1791
|
+
cachedInputTokens: rawTotals.cachedInputTokens
|
|
1792
|
+
},
|
|
1793
|
+
...rawTotals.cacheWriteInputTokens !== undefined && {
|
|
1794
|
+
cacheCreationInputTokens: rawTotals.cacheWriteInputTokens
|
|
1795
|
+
},
|
|
1796
|
+
...rawTotals.reasoningOutputTokens !== undefined && {
|
|
1797
|
+
thinkingTokens: rawTotals.reasoningOutputTokens
|
|
1798
|
+
},
|
|
1799
|
+
...rawTotals.totalTokens !== undefined && { totalTokens: rawTotals.totalTokens }
|
|
1800
|
+
};
|
|
1801
|
+
return Object.keys(normalized).length > 0 ? normalized : undefined;
|
|
1802
|
+
}
|
|
1803
|
+
function classifyCodexTokenUsage(params, base) {
|
|
1804
|
+
const { last, total } = CodexNotificationParams["thread/tokenUsage/updated"].parse(params).tokenUsage;
|
|
1805
|
+
const normalizedTotal = normalizeCodexTokenTotals(total);
|
|
1806
|
+
return {
|
|
1807
|
+
kind: "deltas",
|
|
1808
|
+
deltas: [
|
|
1809
|
+
{
|
|
1810
|
+
type: "usage",
|
|
1811
|
+
...base,
|
|
1812
|
+
itemId: "usage",
|
|
1813
|
+
raw: raw("thread/tokenUsage/updated"),
|
|
1814
|
+
inputTokens: last.inputTokens,
|
|
1815
|
+
outputTokens: last.outputTokens,
|
|
1816
|
+
...last.cachedInputTokens !== undefined && {
|
|
1817
|
+
cachedInputTokens: last.cachedInputTokens
|
|
1818
|
+
},
|
|
1819
|
+
...last.cacheWriteInputTokens !== undefined && {
|
|
1820
|
+
cacheCreationInputTokens: last.cacheWriteInputTokens
|
|
1821
|
+
},
|
|
1822
|
+
...last.reasoningOutputTokens !== undefined && {
|
|
1823
|
+
thinkingTokens: last.reasoningOutputTokens
|
|
1824
|
+
},
|
|
1825
|
+
...last.totalTokens !== undefined && { totalTokens: last.totalTokens },
|
|
1826
|
+
...normalizedTotal !== undefined && { total: normalizedTotal }
|
|
1827
|
+
}
|
|
1828
|
+
]
|
|
1829
|
+
};
|
|
1830
|
+
}
|
|
222
1831
|
function classifyCodexNotification(method, params, state) {
|
|
223
1832
|
const base = { turnId: state.turnId };
|
|
224
1833
|
switch (method) {
|
|
@@ -242,9 +1851,9 @@ function classifyCodexNotification(method, params, state) {
|
|
|
242
1851
|
case "item/started":
|
|
243
1852
|
case "item/completed": {
|
|
244
1853
|
const { item } = CodexNotificationParams[method].parse(params);
|
|
245
|
-
if (
|
|
1854
|
+
if (CODEX_CONTENT_ITEMS.has(item.type))
|
|
246
1855
|
return { kind: "ignore", reason: `${method} ${item.type}` };
|
|
247
|
-
if (!
|
|
1856
|
+
if (!CODEX_TOOL_ITEMS.has(item.type)) {
|
|
248
1857
|
return {
|
|
249
1858
|
kind: "unhandled",
|
|
250
1859
|
delta: {
|
|
@@ -274,8 +1883,10 @@ function classifyCodexNotification(method, params, state) {
|
|
|
274
1883
|
};
|
|
275
1884
|
}
|
|
276
1885
|
const status = Reflect.get(item, "status");
|
|
277
|
-
const
|
|
278
|
-
const
|
|
1886
|
+
const failure = Reflect.get(item, "failure");
|
|
1887
|
+
const output = failure ?? Reflect.get(item, "aggregatedOutput") ?? Reflect.get(item, "output") ?? Reflect.get(item, "savedPath") ?? Reflect.get(item, "fileId") ?? Reflect.get(item, "result") ?? Reflect.get(item, "results") ?? Reflect.get(item, "contentItems") ?? Reflect.get(item, "changes") ?? Reflect.get(item, "agentsStates") ?? Reflect.get(item, "error");
|
|
1888
|
+
const hasFailure = failure !== undefined && failure !== null;
|
|
1889
|
+
const outcome = !hasFailure && (status === "completed" || STATUSLESS_TOOL_ITEMS.has(item.type) && status === undefined) ? "success" : status === "declined" || status === "interrupted" ? "interrupted" : "error";
|
|
279
1890
|
return {
|
|
280
1891
|
kind: "deltas",
|
|
281
1892
|
deltas: [
|
|
@@ -305,41 +1916,29 @@ function classifyCodexNotification(method, params, state) {
|
|
|
305
1916
|
itemId: "failure",
|
|
306
1917
|
raw: raw(method),
|
|
307
1918
|
kind: failureKind(turn.error?.codexErrorInfo),
|
|
308
|
-
message: turn
|
|
1919
|
+
message: codexFailureMessage(turn)
|
|
309
1920
|
});
|
|
310
1921
|
}
|
|
311
1922
|
deltas.push({ type: "turn-end", ...base, itemId: "end", raw: raw(method), outcome });
|
|
312
1923
|
return { kind: "end", deltas, outcome };
|
|
313
1924
|
}
|
|
314
|
-
case "thread/tokenUsage/updated":
|
|
315
|
-
|
|
316
|
-
return {
|
|
317
|
-
kind: "deltas",
|
|
318
|
-
deltas: [
|
|
319
|
-
{
|
|
320
|
-
type: "usage",
|
|
321
|
-
...base,
|
|
322
|
-
itemId: "usage",
|
|
323
|
-
raw: raw(method),
|
|
324
|
-
inputTokens: last.inputTokens,
|
|
325
|
-
outputTokens: last.outputTokens,
|
|
326
|
-
...last.cachedInputTokens !== undefined && {
|
|
327
|
-
cachedInputTokens: last.cachedInputTokens
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
]
|
|
331
|
-
};
|
|
332
|
-
}
|
|
1925
|
+
case "thread/tokenUsage/updated":
|
|
1926
|
+
return classifyCodexTokenUsage(params, base);
|
|
333
1927
|
case "serverRequest/resolved":
|
|
334
1928
|
return {
|
|
335
1929
|
kind: "resolved",
|
|
336
1930
|
requestId: String(CodexNotificationParams[method].parse(params).requestId)
|
|
337
1931
|
};
|
|
338
|
-
case "account/rateLimits/updated":
|
|
1932
|
+
case "account/rateLimits/updated": {
|
|
1933
|
+
const parsed = CodexNotificationParams[method].parse(params);
|
|
339
1934
|
return {
|
|
340
1935
|
kind: "limits",
|
|
341
|
-
rateLimits:
|
|
1936
|
+
rateLimits: parsed.rateLimitsByLimitId !== undefined ? {
|
|
1937
|
+
rateLimits: parsed.rateLimits,
|
|
1938
|
+
rateLimitsByLimitId: parsed.rateLimitsByLimitId
|
|
1939
|
+
} : parsed.rateLimits
|
|
342
1940
|
};
|
|
1941
|
+
}
|
|
343
1942
|
default:
|
|
344
1943
|
if (CODEX_QUIET_NOTIFICATIONS.has(method))
|
|
345
1944
|
return { kind: "ignore", reason: method };
|
|
@@ -357,335 +1956,1433 @@ function classifyCodexNotification(method, params, state) {
|
|
|
357
1956
|
}
|
|
358
1957
|
}
|
|
359
1958
|
|
|
360
|
-
// src/agent-executor/codex/
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
const
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
args: [...config.prefix, "app-server"],
|
|
376
|
-
cwd,
|
|
377
|
-
env,
|
|
378
|
-
signal,
|
|
379
|
-
...config.maxLineBytes !== undefined && { maxLineBytes: config.maxLineBytes }
|
|
380
|
-
});
|
|
381
|
-
const reading = (async () => {
|
|
382
|
-
try {
|
|
383
|
-
for await (const line of engine.lines)
|
|
384
|
-
peer.receive(line);
|
|
385
|
-
const ended = new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`);
|
|
386
|
-
peer.close(ended);
|
|
387
|
-
onEnd(ended);
|
|
388
|
-
} catch (error) {
|
|
389
|
-
const failed = error instanceof Error ? error : new Error(String(error));
|
|
390
|
-
peer.close(failed);
|
|
391
|
-
onEnd(failed);
|
|
392
|
-
await engine.stop().catch(() => {
|
|
393
|
-
return;
|
|
394
|
-
});
|
|
395
|
-
}
|
|
396
|
-
})();
|
|
397
|
-
try {
|
|
398
|
-
await peer.request("initialize", {
|
|
399
|
-
clientInfo: { name: "stitchkit-agent-executor", version: config.version },
|
|
400
|
-
capabilities: {
|
|
401
|
-
experimentalApi: true,
|
|
402
|
-
optOutNotificationMethods: CODEX_OPTED_OUT_NOTIFICATIONS
|
|
403
|
-
}
|
|
404
|
-
}, { timeoutMs: BOOTSTRAP_MS });
|
|
405
|
-
peer.notify("initialized");
|
|
406
|
-
return { engine, peer, reading };
|
|
407
|
-
} catch (error) {
|
|
408
|
-
await stopConnection({ engine, reading }, { error });
|
|
409
|
-
throw error;
|
|
1959
|
+
// src/agent-executor/codex/request-answers.ts
|
|
1960
|
+
function isKnownCodexRequestMethod(method) {
|
|
1961
|
+
return CODEX_APPROVAL_REQUESTS.has(method) || method === CODEX_PERMISSIONS_APPROVAL_REQUEST || method === CODEX_INPUT_REQUEST || method === CODEX_ELICITATION_REQUEST;
|
|
1962
|
+
}
|
|
1963
|
+
function externalCodexTurnIdOf(params) {
|
|
1964
|
+
if (typeof params !== "object" || params === null)
|
|
1965
|
+
return "external";
|
|
1966
|
+
const direct = nonEmptyString(Reflect.get(params, "turnId"));
|
|
1967
|
+
if (direct !== undefined)
|
|
1968
|
+
return direct;
|
|
1969
|
+
const turn = Reflect.get(params, "turn");
|
|
1970
|
+
if (typeof turn === "object" && turn !== null) {
|
|
1971
|
+
const nested = nonEmptyString(Reflect.get(turn, "id"));
|
|
1972
|
+
if (nested !== undefined)
|
|
1973
|
+
return nested;
|
|
410
1974
|
}
|
|
1975
|
+
return "external";
|
|
411
1976
|
}
|
|
412
|
-
function
|
|
1977
|
+
function parseCodexApprovalRequest(method, params) {
|
|
413
1978
|
const asked = CodexApprovalParamsSchema.parse(params);
|
|
414
1979
|
const callId = nonEmptyString(asked.itemId);
|
|
1980
|
+
const metadata = {};
|
|
1981
|
+
if (typeof asked.command === "string")
|
|
1982
|
+
metadata.command = asked.command;
|
|
1983
|
+
if (typeof asked.cwd === "string")
|
|
1984
|
+
metadata.cwd = asked.cwd;
|
|
1985
|
+
if (typeof asked.reason === "string")
|
|
1986
|
+
metadata.reason = asked.reason;
|
|
1987
|
+
if (typeof asked.grantRoot === "string")
|
|
1988
|
+
metadata.grantRoot = asked.grantRoot;
|
|
1989
|
+
if (typeof asked.kind === "string")
|
|
1990
|
+
metadata.kind = asked.kind;
|
|
1991
|
+
if (typeof asked.approvalId === "string")
|
|
1992
|
+
metadata.approvalId = asked.approvalId;
|
|
1993
|
+
if (asked.commandActions != null)
|
|
1994
|
+
metadata.commandActions = asked.commandActions;
|
|
1995
|
+
if (asked.availableDecisions != null)
|
|
1996
|
+
metadata.availableDecisions = asked.availableDecisions;
|
|
1997
|
+
const input = Object.keys(metadata).length > 0 ? safeJsonValue(metadata) : undefined;
|
|
1998
|
+
const detail = {
|
|
1999
|
+
method,
|
|
2000
|
+
...typeof asked.kind === "string" && { kind: asked.kind },
|
|
2001
|
+
...Array.isArray(asked.availableDecisions) && {
|
|
2002
|
+
availableDecisions: asked.availableDecisions
|
|
2003
|
+
}
|
|
2004
|
+
};
|
|
415
2005
|
return {
|
|
416
|
-
|
|
417
|
-
|
|
2006
|
+
detail,
|
|
2007
|
+
deltaFields: {
|
|
2008
|
+
...callId !== undefined && { callId },
|
|
2009
|
+
...typeof asked.command === "string" && { prompt: asked.command },
|
|
2010
|
+
...input !== undefined && { input }
|
|
2011
|
+
}
|
|
418
2012
|
};
|
|
419
2013
|
}
|
|
420
|
-
function
|
|
2014
|
+
function parseCodexInputRequest(params) {
|
|
421
2015
|
const asked = CodexUserInputParamsSchema.parse(params);
|
|
422
2016
|
const callId = nonEmptyString(asked.itemId);
|
|
2017
|
+
const questions = asked.questions.map((question) => ({
|
|
2018
|
+
id: question.id,
|
|
2019
|
+
header: question.header,
|
|
2020
|
+
question: question.question,
|
|
2021
|
+
...question.options !== undefined && {
|
|
2022
|
+
options: question.options === null ? null : question.options.map((option) => ({
|
|
2023
|
+
label: option.label,
|
|
2024
|
+
description: option.description
|
|
2025
|
+
}))
|
|
2026
|
+
},
|
|
2027
|
+
...question.isOther !== undefined && { isOther: question.isOther },
|
|
2028
|
+
...question.isSecret !== undefined && { isSecret: question.isSecret }
|
|
2029
|
+
}));
|
|
2030
|
+
const detail = { method: CODEX_INPUT_REQUEST };
|
|
2031
|
+
return {
|
|
2032
|
+
detail,
|
|
2033
|
+
deltaFields: {
|
|
2034
|
+
...callId !== undefined && { callId },
|
|
2035
|
+
input: safeJsonValue(questions)
|
|
2036
|
+
}
|
|
2037
|
+
};
|
|
2038
|
+
}
|
|
2039
|
+
function parseCodexPermissionsRequest(params) {
|
|
2040
|
+
const asked = CodexPermissionsApprovalParamsSchema.parse(params);
|
|
2041
|
+
const callId = nonEmptyString(asked.itemId);
|
|
2042
|
+
const permissions = safeJsonValue(asked.permissions);
|
|
2043
|
+
const metadata = {
|
|
2044
|
+
threadId: asked.threadId,
|
|
2045
|
+
turnId: asked.turnId,
|
|
2046
|
+
cwd: asked.cwd,
|
|
2047
|
+
permissions,
|
|
2048
|
+
startedAtMs: asked.startedAtMs
|
|
2049
|
+
};
|
|
2050
|
+
if (typeof asked.reason === "string")
|
|
2051
|
+
metadata.reason = asked.reason;
|
|
2052
|
+
if (typeof asked.environmentId === "string")
|
|
2053
|
+
metadata.environmentId = asked.environmentId;
|
|
2054
|
+
const detail = {
|
|
2055
|
+
method: CODEX_PERMISSIONS_APPROVAL_REQUEST,
|
|
2056
|
+
permissions
|
|
2057
|
+
};
|
|
2058
|
+
return {
|
|
2059
|
+
detail,
|
|
2060
|
+
deltaFields: {
|
|
2061
|
+
...callId !== undefined && { callId },
|
|
2062
|
+
...typeof asked.reason === "string" && { prompt: asked.reason },
|
|
2063
|
+
input: safeJsonValue(metadata)
|
|
2064
|
+
}
|
|
2065
|
+
};
|
|
2066
|
+
}
|
|
2067
|
+
function parseCodexElicitationRequest(params) {
|
|
2068
|
+
const asked = CodexMcpElicitationParamsSchema.parse(params);
|
|
2069
|
+
const toolName = nonEmptyString(asked.serverName);
|
|
2070
|
+
const callId = asked.mode === "url" ? nonEmptyString(asked.elicitationId) : undefined;
|
|
2071
|
+
const metadata = {
|
|
2072
|
+
serverName: asked.serverName,
|
|
2073
|
+
threadId: asked.threadId,
|
|
2074
|
+
mode: asked.mode,
|
|
2075
|
+
message: asked.message
|
|
2076
|
+
};
|
|
2077
|
+
if (asked.turnId !== undefined)
|
|
2078
|
+
metadata.turnId = asked.turnId;
|
|
2079
|
+
if (asked.environmentId !== undefined)
|
|
2080
|
+
metadata.environmentId = asked.environmentId;
|
|
2081
|
+
if (asked._meta !== undefined)
|
|
2082
|
+
metadata._meta = asked._meta;
|
|
2083
|
+
if (asked.mode === "url") {
|
|
2084
|
+
metadata.elicitationId = asked.elicitationId;
|
|
2085
|
+
metadata.url = asked.url;
|
|
2086
|
+
} else {
|
|
2087
|
+
metadata.requestedSchema = asked.requestedSchema;
|
|
2088
|
+
}
|
|
2089
|
+
const detail = {
|
|
2090
|
+
method: CODEX_ELICITATION_REQUEST,
|
|
2091
|
+
elicitationMode: asked.mode
|
|
2092
|
+
};
|
|
2093
|
+
return {
|
|
2094
|
+
detail,
|
|
2095
|
+
deltaFields: {
|
|
2096
|
+
...callId !== undefined && { callId },
|
|
2097
|
+
...toolName !== undefined && { toolName },
|
|
2098
|
+
prompt: asked.message,
|
|
2099
|
+
input: safeJsonValue(metadata)
|
|
2100
|
+
}
|
|
2101
|
+
};
|
|
2102
|
+
}
|
|
2103
|
+
function parseCodexServerRequest(method, params) {
|
|
2104
|
+
if (CODEX_APPROVAL_REQUESTS.has(method)) {
|
|
2105
|
+
return { kind: "approval", ...parseCodexApprovalRequest(method, params) };
|
|
2106
|
+
}
|
|
2107
|
+
if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
2108
|
+
return { kind: "approval", ...parseCodexPermissionsRequest(params) };
|
|
2109
|
+
}
|
|
2110
|
+
if (method === CODEX_ELICITATION_REQUEST) {
|
|
2111
|
+
return { kind: "input", ...parseCodexElicitationRequest(params) };
|
|
2112
|
+
}
|
|
2113
|
+
return { kind: "input", ...parseCodexInputRequest(params) };
|
|
2114
|
+
}
|
|
2115
|
+
function codexStoppedAnswer(method) {
|
|
2116
|
+
if (CODEX_APPROVAL_REQUESTS.has(method)) {
|
|
2117
|
+
return { decision: CODEX_APPROVAL_DECISION.interrupted };
|
|
2118
|
+
}
|
|
2119
|
+
if (method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
2120
|
+
return { permissions: {} };
|
|
2121
|
+
}
|
|
2122
|
+
if (method === CODEX_ELICITATION_REQUEST) {
|
|
2123
|
+
return { action: "cancel" };
|
|
2124
|
+
}
|
|
2125
|
+
return { answers: {} };
|
|
2126
|
+
}
|
|
2127
|
+
var codexStopped = (waiting) => codexStoppedAnswer(waiting.detail.method);
|
|
2128
|
+
function buildCodexRequestAnswer(detail, rawReply) {
|
|
2129
|
+
const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
|
|
2130
|
+
if (CODEX_APPROVAL_REQUESTS.has(detail.method)) {
|
|
2131
|
+
if (reply.kind === "input") {
|
|
2132
|
+
throw new TypeError("A Codex approval is approved or denied, not answered with input");
|
|
2133
|
+
}
|
|
2134
|
+
if (reply.kind === "approve" && reply.updatedInput !== undefined) {
|
|
2135
|
+
throw new TypeError("Codex approval requests do not support updatedInput");
|
|
2136
|
+
}
|
|
2137
|
+
const decision = reply.kind === "approve" ? reply.scope === "session" ? CODEX_APPROVAL_DECISION.approveForSession : CODEX_APPROVAL_DECISION.approve : reply.interrupt === true ? CODEX_APPROVAL_DECISION.interrupted : CODEX_APPROVAL_DECISION.deny;
|
|
2138
|
+
if (detail.kind === "humanCommand" && decision === CODEX_APPROVAL_DECISION.approveForSession) {
|
|
2139
|
+
throw new TypeError("Codex humanCommand approval does not allow acceptForSession");
|
|
2140
|
+
}
|
|
2141
|
+
if (detail.availableDecisions !== undefined) {
|
|
2142
|
+
const allowed = detail.availableDecisions.some((entry) => entry === decision);
|
|
2143
|
+
if (!allowed) {
|
|
2144
|
+
throw new TypeError(`Codex approval request does not offer decision ${JSON.stringify(decision)}`);
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
return { decision };
|
|
2148
|
+
}
|
|
2149
|
+
if (detail.method === CODEX_PERMISSIONS_APPROVAL_REQUEST) {
|
|
2150
|
+
if (reply.kind === "input") {
|
|
2151
|
+
throw new TypeError("A Codex permissions approval is approved or denied, not answered with input");
|
|
2152
|
+
}
|
|
2153
|
+
if (reply.kind === "approve") {
|
|
2154
|
+
if (reply.updatedInput !== undefined) {
|
|
2155
|
+
throw new TypeError("Codex permissions approval requests do not support updatedInput");
|
|
2156
|
+
}
|
|
2157
|
+
return {
|
|
2158
|
+
permissions: detail.permissions ?? {},
|
|
2159
|
+
scope: reply.scope === "session" ? "session" : "turn"
|
|
2160
|
+
};
|
|
2161
|
+
}
|
|
2162
|
+
if (reply.interrupt === true) {
|
|
2163
|
+
throw new TypeError("Codex permissions approval requests do not support interrupt on deny");
|
|
2164
|
+
}
|
|
2165
|
+
return { permissions: {} };
|
|
2166
|
+
}
|
|
2167
|
+
if (detail.method === CODEX_ELICITATION_REQUEST) {
|
|
2168
|
+
if (reply.kind === "approve") {
|
|
2169
|
+
throw new TypeError("A Codex MCP elicitation request is answered with input or deny, not approve");
|
|
2170
|
+
}
|
|
2171
|
+
if (reply.kind === "deny") {
|
|
2172
|
+
return {
|
|
2173
|
+
action: detail.elicitationMode === "url" || reply.interrupt === true ? "cancel" : "decline"
|
|
2174
|
+
};
|
|
2175
|
+
}
|
|
2176
|
+
const parsed = CodexMcpElicitationAnswerSchema.parse(reply.value);
|
|
2177
|
+
return {
|
|
2178
|
+
action: parsed.action,
|
|
2179
|
+
...parsed.content !== undefined && { content: parsed.content },
|
|
2180
|
+
...parsed._meta !== undefined && { _meta: parsed._meta }
|
|
2181
|
+
};
|
|
2182
|
+
}
|
|
2183
|
+
if (reply.kind !== "input") {
|
|
2184
|
+
throw new TypeError("A Codex input request is answered with input");
|
|
2185
|
+
}
|
|
2186
|
+
return { answers: CodexUserInputAnswersSchema.parse(reply.value) };
|
|
2187
|
+
}
|
|
2188
|
+
function answerActiveCodexTurnRequest(turn, interactionId, rawReply) {
|
|
2189
|
+
const waiting = turn.pending.get(interactionId);
|
|
2190
|
+
if (waiting === undefined) {
|
|
2191
|
+
throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
|
|
2192
|
+
}
|
|
2193
|
+
const answer = buildCodexRequestAnswer(waiting.detail, rawReply);
|
|
2194
|
+
answerEngineRequest(turn, interactionId, answer);
|
|
2195
|
+
}
|
|
2196
|
+
function answerCodexSessionRequest(input) {
|
|
2197
|
+
if (input.turn?.pending.has(input.interactionId)) {
|
|
2198
|
+
answerActiveCodexTurnRequest(input.turn, input.interactionId, input.reply);
|
|
2199
|
+
return;
|
|
2200
|
+
}
|
|
2201
|
+
const external = input.externalPending.get(input.interactionId);
|
|
2202
|
+
if (external === undefined || input.expectedEntry !== undefined && external !== input.expectedEntry) {
|
|
2203
|
+
throw new TypeError(`Unknown interaction ${input.interactionId} for this Codex connection`);
|
|
2204
|
+
}
|
|
2205
|
+
const answer = buildCodexRequestAnswer(external.detail, input.reply);
|
|
2206
|
+
input.externalPending.delete(input.interactionId);
|
|
2207
|
+
external.resolve(answer);
|
|
2208
|
+
}
|
|
2209
|
+
|
|
2210
|
+
// src/agent-executor/codex/handlers.ts
|
|
2211
|
+
var JSON_RPC_INTERNAL_ERROR = -32603;
|
|
2212
|
+
var MAX_EXTERNAL_PENDING_REQUESTS = 256;
|
|
2213
|
+
function emitCodexNotification(state, method, params, duringActiveTurn, deltas) {
|
|
2214
|
+
if (state.onNotification === undefined)
|
|
2215
|
+
return;
|
|
2216
|
+
invokeSafely(() => state.onNotification?.({ method, params, duringActiveTurn, deltas }));
|
|
2217
|
+
}
|
|
2218
|
+
function handleCodexNotification(state, method, params) {
|
|
2219
|
+
const turn = state.getTurn();
|
|
2220
|
+
const duringActiveTurn = turn !== undefined;
|
|
2221
|
+
const effectiveTurnId = turn?.state.turnId ?? externalCodexTurnIdOf(params);
|
|
2222
|
+
let verdict;
|
|
2223
|
+
try {
|
|
2224
|
+
verdict = classifyCodexNotification(method, params, turn?.state ?? { turnId: effectiveTurnId, interruptRequested: false });
|
|
2225
|
+
} catch (error) {
|
|
2226
|
+
const errorDelta = {
|
|
2227
|
+
type: "error",
|
|
2228
|
+
turnId: effectiveTurnId,
|
|
2229
|
+
itemId: `unhandled:${method}`,
|
|
2230
|
+
raw: { source: "codex", type: method },
|
|
2231
|
+
kind: "unhandled",
|
|
2232
|
+
message: `Codex notification ${method} did not match schema: ${error instanceof Error ? error.message : String(error)}`
|
|
2233
|
+
};
|
|
2234
|
+
if (turn !== undefined)
|
|
2235
|
+
offerTurnDelta(turn.channel, errorDelta);
|
|
2236
|
+
emitCodexNotification(state, method, params, duringActiveTurn, [errorDelta]);
|
|
2237
|
+
return;
|
|
2238
|
+
}
|
|
2239
|
+
switch (verdict.kind) {
|
|
2240
|
+
case "limits":
|
|
2241
|
+
try {
|
|
2242
|
+
state.limits.set(state.profileId, mergeRateLimitEvent2({
|
|
2243
|
+
previous: state.limits.get(state.profileId),
|
|
2244
|
+
windows: codexPlanWindows(verdict.rateLimits),
|
|
2245
|
+
now: new Date
|
|
2246
|
+
}));
|
|
2247
|
+
emitCodexNotification(state, method, params, duringActiveTurn, []);
|
|
2248
|
+
} catch (error) {
|
|
2249
|
+
const errorDelta = {
|
|
2250
|
+
type: "error",
|
|
2251
|
+
turnId: effectiveTurnId,
|
|
2252
|
+
itemId: `unhandled:${method}`,
|
|
2253
|
+
raw: { source: "codex", type: method },
|
|
2254
|
+
kind: "unhandled",
|
|
2255
|
+
message: `Codex rate-limit update could not be merged: ${error instanceof Error ? error.message : String(error)}`
|
|
2256
|
+
};
|
|
2257
|
+
if (turn !== undefined)
|
|
2258
|
+
offerTurnDelta(turn.channel, errorDelta);
|
|
2259
|
+
emitCodexNotification(state, method, params, duringActiveTurn, [errorDelta]);
|
|
2260
|
+
}
|
|
2261
|
+
return;
|
|
2262
|
+
case "resolved": {
|
|
2263
|
+
const resolvedTurn = turn?.pending.delete(verdict.requestId) === true;
|
|
2264
|
+
const externalEntry = state.externalPending.get(verdict.requestId);
|
|
2265
|
+
const resolvedExternal = externalEntry !== undefined;
|
|
2266
|
+
if (resolvedExternal)
|
|
2267
|
+
state.externalPending.delete(verdict.requestId);
|
|
2268
|
+
const resolvedDelta = {
|
|
2269
|
+
type: "request-resolved",
|
|
2270
|
+
turnId: resolvedTurn ? turn?.state.turnId ?? effectiveTurnId : externalEntry?.turnId ?? effectiveTurnId,
|
|
2271
|
+
itemId: `resolved:${verdict.requestId}`,
|
|
2272
|
+
raw: { source: "codex", type: "serverRequest/resolved" },
|
|
2273
|
+
interactionId: verdict.requestId
|
|
2274
|
+
};
|
|
2275
|
+
if (resolvedTurn && turn !== undefined)
|
|
2276
|
+
offerTurnDelta(turn.channel, resolvedDelta);
|
|
2277
|
+
emitCodexNotification(state, method, params, duringActiveTurn, resolvedTurn || resolvedExternal ? [resolvedDelta] : []);
|
|
2278
|
+
return;
|
|
2279
|
+
}
|
|
2280
|
+
case "deltas":
|
|
2281
|
+
case "unhandled": {
|
|
2282
|
+
const emitted = verdict.kind === "deltas" ? verdict.deltas : [verdict.delta];
|
|
2283
|
+
if (turn !== undefined) {
|
|
2284
|
+
for (const delta of emitted)
|
|
2285
|
+
offerTurnDelta(turn.channel, delta);
|
|
2286
|
+
}
|
|
2287
|
+
emitCodexNotification(state, method, params, duringActiveTurn, emitted);
|
|
2288
|
+
return;
|
|
2289
|
+
}
|
|
2290
|
+
case "end":
|
|
2291
|
+
endEngineTurn(turn, codexStopped, verdict.deltas);
|
|
2292
|
+
state.clearTurn();
|
|
2293
|
+
emitCodexNotification(state, method, params, duringActiveTurn, verdict.deltas);
|
|
2294
|
+
return;
|
|
2295
|
+
case "ignore":
|
|
2296
|
+
emitCodexNotification(state, method, params, duringActiveTurn, []);
|
|
2297
|
+
return;
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
function handleCodexRequest(state, method, params, id) {
|
|
2301
|
+
const turn = state.getTurn();
|
|
2302
|
+
if (!isKnownCodexRequestMethod(method)) {
|
|
2303
|
+
if (turn !== undefined) {
|
|
2304
|
+
offerTurnDelta(turn.channel, {
|
|
2305
|
+
type: "error",
|
|
2306
|
+
turnId: turn.state.turnId,
|
|
2307
|
+
itemId: `unhandled-request:${id}`,
|
|
2308
|
+
raw: { source: "codex", type: method },
|
|
2309
|
+
kind: "unhandled",
|
|
2310
|
+
message: `Codex request ${method} is not known to this driver; refused`
|
|
2311
|
+
});
|
|
2312
|
+
}
|
|
2313
|
+
throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
|
|
2314
|
+
}
|
|
2315
|
+
const interactionId = String(id);
|
|
2316
|
+
if (turn !== undefined) {
|
|
2317
|
+
const parsed = parseCodexServerRequest(method, params);
|
|
2318
|
+
return new Promise((resolve) => {
|
|
2319
|
+
holdEngineRequest(turn, {
|
|
2320
|
+
interactionId,
|
|
2321
|
+
detail: parsed.detail,
|
|
2322
|
+
answeredBy: { source: "codex", type: method },
|
|
2323
|
+
delta: () => ({
|
|
2324
|
+
type: "request",
|
|
2325
|
+
turnId: turn.state.turnId,
|
|
2326
|
+
itemId: `request:${interactionId}`,
|
|
2327
|
+
raw: { source: "codex", type: method },
|
|
2328
|
+
interactionId,
|
|
2329
|
+
kind: parsed.kind,
|
|
2330
|
+
...parsed.deltaFields
|
|
2331
|
+
}),
|
|
2332
|
+
refusal: codexStoppedAnswer(method),
|
|
2333
|
+
resolve
|
|
2334
|
+
});
|
|
2335
|
+
});
|
|
2336
|
+
}
|
|
2337
|
+
const observer = state.onServerRequest;
|
|
2338
|
+
if (observer === undefined) {
|
|
2339
|
+
throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
|
|
2340
|
+
}
|
|
2341
|
+
if (state.externalPending.size >= MAX_EXTERNAL_PENDING_REQUESTS) {
|
|
2342
|
+
throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Too many pending external Codex server requests (limit ${MAX_EXTERNAL_PENDING_REQUESTS})`);
|
|
2343
|
+
}
|
|
2344
|
+
if (state.externalPending.has(interactionId)) {
|
|
2345
|
+
throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Duplicate pending external Codex server request ${interactionId}`);
|
|
2346
|
+
}
|
|
2347
|
+
const parsed = parseCodexServerRequest(method, params);
|
|
2348
|
+
const turnId = externalCodexTurnIdOf(params);
|
|
2349
|
+
const delta = {
|
|
2350
|
+
type: "request",
|
|
2351
|
+
turnId,
|
|
2352
|
+
itemId: `request:${interactionId}`,
|
|
2353
|
+
raw: { source: "codex", type: method },
|
|
2354
|
+
interactionId,
|
|
2355
|
+
kind: parsed.kind,
|
|
2356
|
+
...parsed.deltaFields
|
|
2357
|
+
};
|
|
2358
|
+
return new Promise((resolve, reject) => {
|
|
2359
|
+
const entry = { detail: parsed.detail, turnId, resolve };
|
|
2360
|
+
state.externalPending.set(interactionId, entry);
|
|
2361
|
+
const onObserverError = (error) => {
|
|
2362
|
+
if (state.externalPending.get(interactionId) !== entry)
|
|
2363
|
+
return;
|
|
2364
|
+
state.externalPending.delete(interactionId);
|
|
2365
|
+
if (error instanceof JsonRpcError2)
|
|
2366
|
+
reject(error);
|
|
2367
|
+
};
|
|
2368
|
+
try {
|
|
2369
|
+
const outcome = observer({
|
|
2370
|
+
interactionId,
|
|
2371
|
+
method,
|
|
2372
|
+
params,
|
|
2373
|
+
delta,
|
|
2374
|
+
async respond(reply) {
|
|
2375
|
+
answerCodexSessionRequest({
|
|
2376
|
+
turn: undefined,
|
|
2377
|
+
externalPending: state.externalPending,
|
|
2378
|
+
expectedEntry: entry,
|
|
2379
|
+
interactionId,
|
|
2380
|
+
reply
|
|
2381
|
+
});
|
|
2382
|
+
}
|
|
2383
|
+
});
|
|
2384
|
+
if (typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function") {
|
|
2385
|
+
Promise.resolve(outcome).catch(onObserverError);
|
|
2386
|
+
}
|
|
2387
|
+
} catch (error) {
|
|
2388
|
+
onObserverError(error);
|
|
2389
|
+
}
|
|
2390
|
+
});
|
|
2391
|
+
}
|
|
2392
|
+
function createCodexHandlers(state) {
|
|
2393
|
+
return {
|
|
2394
|
+
onNotification: (method, params) => handleCodexNotification(state, method, params),
|
|
2395
|
+
onRequest: (method, params, id) => handleCodexRequest(state, method, params, id)
|
|
2396
|
+
};
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
// src/agent-executor/codex/turn-input.ts
|
|
2400
|
+
import { z as z3 } from "zod";
|
|
2401
|
+
var NonEmptyNoNulStringSchema = z3.string().min(1).refine((value) => value.trim().length > 0 && !value.includes("\x00"), {
|
|
2402
|
+
message: "must be a non-empty string without NUL bytes"
|
|
2403
|
+
});
|
|
2404
|
+
var CodexSkillInputSchema = z3.strictObject({
|
|
2405
|
+
type: z3.literal("skill"),
|
|
2406
|
+
name: NonEmptyNoNulStringSchema,
|
|
2407
|
+
path: NonEmptyNoNulStringSchema
|
|
2408
|
+
});
|
|
2409
|
+
function validateSkillInput(part) {
|
|
2410
|
+
if (part.type !== "skill")
|
|
2411
|
+
return;
|
|
2412
|
+
const parsed = CodexSkillInputSchema.safeParse(part);
|
|
2413
|
+
if (!parsed.success) {
|
|
2414
|
+
throw new TypeError("Codex skill input name and path must be non-empty strings without NUL bytes");
|
|
2415
|
+
}
|
|
2416
|
+
return { type: "skill", name: parsed.data.name, path: parsed.data.path };
|
|
2417
|
+
}
|
|
2418
|
+
function inlineCodexParts(parts, options) {
|
|
2419
|
+
return inlineOrderedParts(parts, {
|
|
2420
|
+
...options,
|
|
2421
|
+
acceptedDescription: "text, images, and skills",
|
|
2422
|
+
validateExtra: validateSkillInput
|
|
2423
|
+
});
|
|
2424
|
+
}
|
|
2425
|
+
function codexTurnInput(parts) {
|
|
2426
|
+
if (parts.every((part) => part.type === "text")) {
|
|
2427
|
+
return [
|
|
2428
|
+
{ type: "text", text: parts.map((part) => part.text).join(`
|
|
2429
|
+
`), text_elements: [] }
|
|
2430
|
+
];
|
|
2431
|
+
}
|
|
2432
|
+
const out = [];
|
|
2433
|
+
for (const part of parts) {
|
|
2434
|
+
if (part.type === "text") {
|
|
2435
|
+
out.push({ type: "text", text: part.text, text_elements: [] });
|
|
2436
|
+
} else if (part.type === "skill") {
|
|
2437
|
+
out.push({ type: "skill", name: part.name, path: part.path });
|
|
2438
|
+
} else {
|
|
2439
|
+
out.push({ type: "image", url: `data:${part.mediaType};base64,${part.base64}` });
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
return out;
|
|
2443
|
+
}
|
|
2444
|
+
|
|
2445
|
+
// src/agent-executor/codex/session-controls.ts
|
|
2446
|
+
function validateCodexForkBounds(options, caller) {
|
|
2447
|
+
if (options.beforeTurnId !== undefined && options.lastTurnId !== undefined) {
|
|
2448
|
+
throw new TypeError(`[stitchkit] ${caller}: beforeTurnId and lastTurnId are mutually exclusive`);
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
function validateCodexPolicyOverrides(overrides, caller) {
|
|
2452
|
+
if (overrides.runtimeWorkspaceRoots !== undefined) {
|
|
2453
|
+
if (!Array.isArray(overrides.runtimeWorkspaceRoots)) {
|
|
2454
|
+
throw new TypeError(`[stitchkit] ${caller}: runtimeWorkspaceRoots must be an array of strings`);
|
|
2455
|
+
}
|
|
2456
|
+
for (const root of overrides.runtimeWorkspaceRoots) {
|
|
2457
|
+
if (typeof root !== "string" || root.trim().length === 0) {
|
|
2458
|
+
throw new TypeError(`[stitchkit] ${caller}: every runtimeWorkspaceRoots entry must be a non-empty string`);
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
}
|
|
2462
|
+
if (overrides.config !== undefined) {
|
|
2463
|
+
if (typeof overrides.config !== "object" || overrides.config === null || Array.isArray(overrides.config)) {
|
|
2464
|
+
throw new TypeError(`[stitchkit] ${caller}: config must be a plain JSON object`);
|
|
2465
|
+
}
|
|
2466
|
+
safeJsonValue(overrides.config);
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
function buildCodexThreadPolicyParams(base, overrides) {
|
|
2470
|
+
const mergedConfig = base.config !== undefined || overrides?.config !== undefined ? { ...base.config ?? {}, ...overrides?.config ?? {} } : undefined;
|
|
2471
|
+
const merged = {
|
|
2472
|
+
...base,
|
|
2473
|
+
...overrides,
|
|
2474
|
+
...mergedConfig !== undefined && { config: mergedConfig }
|
|
2475
|
+
};
|
|
2476
|
+
validateCodexPolicyOverrides(merged, "CodexSession");
|
|
2477
|
+
const params = {};
|
|
2478
|
+
if (merged.model !== undefined)
|
|
2479
|
+
params.model = merged.model;
|
|
2480
|
+
if (merged.modelProvider !== undefined)
|
|
2481
|
+
params.modelProvider = merged.modelProvider;
|
|
2482
|
+
if (merged.approvalPolicy !== undefined)
|
|
2483
|
+
params.approvalPolicy = safeJsonValue(merged.approvalPolicy);
|
|
2484
|
+
if (merged.sandbox !== undefined)
|
|
2485
|
+
params.sandbox = merged.sandbox;
|
|
2486
|
+
if (merged.developerInstructions !== undefined)
|
|
2487
|
+
params.developerInstructions = merged.developerInstructions;
|
|
2488
|
+
if (merged.runtimeWorkspaceRoots !== undefined)
|
|
2489
|
+
params.runtimeWorkspaceRoots = [...merged.runtimeWorkspaceRoots];
|
|
2490
|
+
if (merged.config !== undefined)
|
|
2491
|
+
params.config = safeJsonValue(merged.config);
|
|
2492
|
+
return params;
|
|
2493
|
+
}
|
|
2494
|
+
function validateCodexTurnStartOverrides(turnInput, activeModelProvider) {
|
|
2495
|
+
if (turnInput.modelProvider !== undefined) {
|
|
2496
|
+
if (activeModelProvider === undefined || turnInput.modelProvider !== activeModelProvider) {
|
|
2497
|
+
throw new TypeError(`Codex turn/start cannot switch modelProvider to ${JSON.stringify(turnInput.modelProvider)} (thread active provider is ${JSON.stringify(activeModelProvider ?? "unknown")})`);
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
if (turnInput.collaborationMode !== undefined) {
|
|
2501
|
+
CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
|
|
2502
|
+
}
|
|
2503
|
+
if (turnInput.approvalPolicy !== undefined) {
|
|
2504
|
+
safeJsonValue(turnInput.approvalPolicy);
|
|
2505
|
+
}
|
|
2506
|
+
if (turnInput.sandboxPolicy !== undefined) {
|
|
2507
|
+
safeJsonValue(turnInput.sandboxPolicy);
|
|
2508
|
+
}
|
|
2509
|
+
if (turnInput.runtimeWorkspaceRoots !== undefined) {
|
|
2510
|
+
validateCodexPolicyOverrides({ runtimeWorkspaceRoots: turnInput.runtimeWorkspaceRoots }, "CodexSession.startTurn");
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvider) {
|
|
2514
|
+
validateCodexTurnStartOverrides(turnInput, activeModelProvider);
|
|
2515
|
+
const params = {
|
|
2516
|
+
threadId,
|
|
2517
|
+
input: codexTurnInput(parts),
|
|
2518
|
+
clientUserMessageId: turnInput.clientId
|
|
2519
|
+
};
|
|
2520
|
+
if (turnInput.model !== undefined)
|
|
2521
|
+
params.model = turnInput.model;
|
|
2522
|
+
if (turnInput.reasoningEffort !== undefined)
|
|
2523
|
+
params.effort = turnInput.reasoningEffort;
|
|
2524
|
+
if (turnInput.collaborationMode !== undefined) {
|
|
2525
|
+
params.collaborationMode = CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
|
|
2526
|
+
}
|
|
2527
|
+
if (turnInput.approvalPolicy !== undefined) {
|
|
2528
|
+
params.approvalPolicy = safeJsonValue(turnInput.approvalPolicy);
|
|
2529
|
+
}
|
|
2530
|
+
if (turnInput.sandboxPolicy !== undefined) {
|
|
2531
|
+
params.sandboxPolicy = safeJsonValue(turnInput.sandboxPolicy);
|
|
2532
|
+
}
|
|
2533
|
+
if (turnInput.runtimeWorkspaceRoots !== undefined) {
|
|
2534
|
+
params.runtimeWorkspaceRoots = [...turnInput.runtimeWorkspaceRoots];
|
|
2535
|
+
}
|
|
2536
|
+
return params;
|
|
2537
|
+
}
|
|
2538
|
+
function createCodexSessionMutators(input) {
|
|
423
2539
|
return {
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
2540
|
+
async steerTurn(steerInput) {
|
|
2541
|
+
input.ensureAlive();
|
|
2542
|
+
const active = input.getActiveTurn();
|
|
2543
|
+
const expectedTurnId = active?.codexTurnId;
|
|
2544
|
+
if (active === undefined || expectedTurnId === undefined) {
|
|
2545
|
+
throw new Error("Cannot steer turn: no Codex turn is currently running");
|
|
2546
|
+
}
|
|
2547
|
+
if (steerInput.expectedTurnId !== undefined && steerInput.expectedTurnId !== expectedTurnId) {
|
|
2548
|
+
throw new TypeError(`Expected active Codex turn ${steerInput.expectedTurnId}, but current turn is ${expectedTurnId}`);
|
|
2549
|
+
}
|
|
2550
|
+
const parts = await inlineCodexParts(steerInput.input, {
|
|
2551
|
+
...input.imageOptions,
|
|
2552
|
+
driverLabel: "The Codex driver",
|
|
2553
|
+
signal: input.signal
|
|
2554
|
+
});
|
|
2555
|
+
input.ensureAlive();
|
|
2556
|
+
const afterAwait = input.getActiveTurn();
|
|
2557
|
+
if (afterAwait !== active || afterAwait.codexTurnId !== expectedTurnId) {
|
|
2558
|
+
throw new Error("Cannot steer turn: the active Codex turn ended before steering was sent");
|
|
2559
|
+
}
|
|
2560
|
+
const steered = CodexTurnSteerResponseSchema.parse(await input.peer.request("turn/steer", {
|
|
2561
|
+
threadId: input.threadId,
|
|
2562
|
+
expectedTurnId,
|
|
2563
|
+
input: codexTurnInput(parts),
|
|
2564
|
+
...steerInput.clientId !== undefined && {
|
|
2565
|
+
clientUserMessageId: steerInput.clientId
|
|
2566
|
+
}
|
|
2567
|
+
}));
|
|
2568
|
+
return { turnId: steered.turnId };
|
|
2569
|
+
},
|
|
2570
|
+
async forkThread(options = {}) {
|
|
2571
|
+
input.ensureAlive();
|
|
2572
|
+
validateCodexForkBounds(options, "CodexSession.forkThread");
|
|
2573
|
+
const policyParams = buildCodexThreadPolicyParams({}, options);
|
|
2574
|
+
const forked = CodexStartedThreadSchema.parse(await input.peer.request("thread/fork", {
|
|
2575
|
+
threadId: input.threadId,
|
|
2576
|
+
...policyParams,
|
|
2577
|
+
...options.cwd !== undefined && { cwd: options.cwd },
|
|
2578
|
+
...options.beforeTurnId !== undefined && { beforeTurnId: options.beforeTurnId },
|
|
2579
|
+
...options.lastTurnId !== undefined && { lastTurnId: options.lastTurnId },
|
|
2580
|
+
...options.excludeTurns !== undefined && { excludeTurns: options.excludeTurns },
|
|
2581
|
+
...options.deferGoalContinuation !== undefined && {
|
|
2582
|
+
deferGoalContinuation: options.deferGoalContinuation
|
|
2583
|
+
}
|
|
2584
|
+
}));
|
|
2585
|
+
return {
|
|
2586
|
+
nativeThreadId: forked.thread.id,
|
|
2587
|
+
threadContext: extractCodexThreadContext(forked)
|
|
2588
|
+
};
|
|
2589
|
+
},
|
|
2590
|
+
async compactThread() {
|
|
2591
|
+
input.ensureAlive();
|
|
2592
|
+
await input.peer.request("thread/compact/start", { threadId: input.threadId });
|
|
2593
|
+
}
|
|
429
2594
|
};
|
|
430
2595
|
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
2596
|
+
|
|
2597
|
+
// src/agent-executor/codex/session.ts
|
|
2598
|
+
function createCodexStartTurn(input) {
|
|
2599
|
+
return guardedTurnStarter({
|
|
2600
|
+
busyMessage: "A turn is already running in this Codex thread",
|
|
2601
|
+
check: (turnInput) => {
|
|
2602
|
+
input.ensureAlive();
|
|
2603
|
+
if (input.getTurn() !== undefined) {
|
|
2604
|
+
throw new Error("A turn is already running in this Codex thread");
|
|
2605
|
+
}
|
|
2606
|
+
validateCodexTurnStartOverrides(turnInput, input.activeModelProvider);
|
|
2607
|
+
},
|
|
2608
|
+
inline: (turnInput) => inlineCodexParts(turnInput.input, {
|
|
2609
|
+
...input.config,
|
|
2610
|
+
driverLabel: "The Codex driver",
|
|
2611
|
+
signal: input.signal
|
|
2612
|
+
}),
|
|
2613
|
+
dispatch: async (turnInput, parts) => {
|
|
2614
|
+
const turnParams = buildCodexTurnStartParams(input.threadId, turnInput, parts, input.activeModelProvider);
|
|
2615
|
+
const turn = {
|
|
2616
|
+
state: { turnId: turnInput.turnId, interruptRequested: false },
|
|
2617
|
+
channel: createTurnDeltaChannel(),
|
|
2618
|
+
pending: new Map
|
|
2619
|
+
};
|
|
2620
|
+
input.setTurn(turn);
|
|
440
2621
|
try {
|
|
441
|
-
|
|
2622
|
+
const started = await input.peer.request("turn/start", turnParams);
|
|
2623
|
+
turn.codexTurnId = CodexStartedTurnSchema.parse(started).turn.id;
|
|
442
2624
|
} catch (error) {
|
|
443
|
-
if (
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
turnId: turn.state.turnId,
|
|
447
|
-
itemId: `unhandled:${method}`,
|
|
448
|
-
raw: { source: "codex", type: method },
|
|
449
|
-
kind: "unhandled",
|
|
450
|
-
message: `Codex notification ${method} did not match schema: ${error instanceof Error ? error.message : String(error)}`
|
|
451
|
-
});
|
|
452
|
-
}
|
|
453
|
-
return;
|
|
2625
|
+
if (input.getTurn() === turn)
|
|
2626
|
+
input.setTurn(undefined);
|
|
2627
|
+
throw error;
|
|
454
2628
|
}
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
if (turn?.pending.delete(verdict.requestId)) {
|
|
465
|
-
offerTurnDelta(turn.channel, {
|
|
466
|
-
type: "request-resolved",
|
|
467
|
-
turnId: turn.state.turnId,
|
|
468
|
-
itemId: `resolved:${verdict.requestId}`,
|
|
469
|
-
raw: { source: "codex", type: "serverRequest/resolved" },
|
|
470
|
-
interactionId: verdict.requestId
|
|
2629
|
+
return {
|
|
2630
|
+
deltas: turn.channel,
|
|
2631
|
+
async interrupt() {
|
|
2632
|
+
turn.state.interruptRequested = true;
|
|
2633
|
+
drainEngineRequests(turn, codexStopped);
|
|
2634
|
+
if (turn.codexTurnId !== undefined) {
|
|
2635
|
+
await input.peer.request("turn/interrupt", {
|
|
2636
|
+
threadId: input.threadId,
|
|
2637
|
+
turnId: turn.codexTurnId
|
|
471
2638
|
});
|
|
472
2639
|
}
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
if (turn !== undefined)
|
|
477
|
-
for (const delta of verdict.kind === "deltas" ? verdict.deltas : [verdict.delta])
|
|
478
|
-
offerTurnDelta(turn.channel, delta);
|
|
479
|
-
return;
|
|
480
|
-
case "end":
|
|
481
|
-
endEngineTurn(turn, codexStopped, verdict.deltas);
|
|
482
|
-
state.clearTurn();
|
|
483
|
-
return;
|
|
484
|
-
case "ignore":
|
|
485
|
-
return;
|
|
486
|
-
}
|
|
487
|
-
},
|
|
488
|
-
onRequest(method, params, id) {
|
|
489
|
-
const turn = state.getTurn();
|
|
490
|
-
const known = CODEX_APPROVAL_REQUESTS.has(method) || method === CODEX_INPUT_REQUEST;
|
|
491
|
-
if (turn === undefined || !known) {
|
|
492
|
-
if (turn !== undefined) {
|
|
493
|
-
offerTurnDelta(turn.channel, {
|
|
494
|
-
type: "error",
|
|
495
|
-
turnId: turn.state.turnId,
|
|
496
|
-
itemId: `unhandled-request:${id}`,
|
|
497
|
-
raw: { source: "codex", type: method },
|
|
498
|
-
kind: "unhandled",
|
|
499
|
-
message: `Codex request ${method} is not known to this driver; refused`
|
|
500
|
-
});
|
|
2640
|
+
},
|
|
2641
|
+
async respond(interactionId, rawReply) {
|
|
2642
|
+
answerActiveCodexTurnRequest(turn, interactionId, rawReply);
|
|
501
2643
|
}
|
|
502
|
-
|
|
503
|
-
}
|
|
504
|
-
const interactionId = String(id);
|
|
505
|
-
const approval = CODEX_APPROVAL_REQUESTS.has(method);
|
|
506
|
-
return new Promise((resolve) => {
|
|
507
|
-
holdEngineRequest(turn, {
|
|
508
|
-
interactionId,
|
|
509
|
-
detail: { method },
|
|
510
|
-
answeredBy: { source: "codex", type: method },
|
|
511
|
-
delta: () => ({
|
|
512
|
-
type: "request",
|
|
513
|
-
turnId: turn.state.turnId,
|
|
514
|
-
itemId: `request:${interactionId}`,
|
|
515
|
-
raw: { source: "codex", type: method },
|
|
516
|
-
interactionId,
|
|
517
|
-
kind: approval ? "approval" : "input",
|
|
518
|
-
...approval ? approvalDetail(params) : inputDetail(params)
|
|
519
|
-
}),
|
|
520
|
-
refusal: codexStoppedAnswer(method),
|
|
521
|
-
resolve
|
|
522
|
-
});
|
|
523
|
-
});
|
|
2644
|
+
};
|
|
524
2645
|
}
|
|
525
|
-
};
|
|
2646
|
+
});
|
|
526
2647
|
}
|
|
527
|
-
function
|
|
528
|
-
if (
|
|
529
|
-
|
|
530
|
-
{ type: "text", text: parts.map((part) => part.text).join(`
|
|
531
|
-
`), text_elements: [] }
|
|
532
|
-
];
|
|
2648
|
+
function validateCodexOpenInput(input) {
|
|
2649
|
+
if (input.nativeThreadId !== undefined && input.forkFrom !== undefined) {
|
|
2650
|
+
throw new TypeError("[stitchkit] CodexDriver.open: nativeThreadId and forkFrom are mutually exclusive");
|
|
533
2651
|
}
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
out.push({ type: "text", text: part.text, text_elements: [] });
|
|
538
|
-
} else {
|
|
539
|
-
out.push({ type: "image", url: `data:${part.mediaType};base64,${part.base64}` });
|
|
2652
|
+
if (input.forkFrom !== undefined) {
|
|
2653
|
+
if (typeof input.forkFrom.threadId !== "string" || input.forkFrom.threadId.trim().length === 0) {
|
|
2654
|
+
throw new TypeError("[stitchkit] CodexDriver.open: forkFrom.threadId must be a non-empty string");
|
|
540
2655
|
}
|
|
2656
|
+
validateCodexForkBounds(input.forkFrom, "CodexDriver.open");
|
|
2657
|
+
validateCodexPolicyOverrides(input.forkFrom, "CodexDriver.open");
|
|
541
2658
|
}
|
|
542
|
-
|
|
2659
|
+
}
|
|
2660
|
+
function mergeOpenThreadPolicy(config, forkFrom, dynamicOverrides) {
|
|
2661
|
+
const basePolicy = {
|
|
2662
|
+
...config.model !== undefined && { model: config.model },
|
|
2663
|
+
...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
|
|
2664
|
+
...config.approvalPolicy !== undefined && { approvalPolicy: config.approvalPolicy },
|
|
2665
|
+
...config.sandbox !== undefined && { sandbox: config.sandbox },
|
|
2666
|
+
...config.developerInstructions !== undefined && {
|
|
2667
|
+
developerInstructions: config.developerInstructions
|
|
2668
|
+
},
|
|
2669
|
+
...config.runtimeWorkspaceRoots !== undefined && {
|
|
2670
|
+
runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
|
|
2671
|
+
},
|
|
2672
|
+
...config.config !== undefined && { config: config.config }
|
|
2673
|
+
};
|
|
2674
|
+
const withFork = forkFrom === undefined ? basePolicy : {
|
|
2675
|
+
...basePolicy,
|
|
2676
|
+
...forkFrom.model !== undefined && { model: forkFrom.model },
|
|
2677
|
+
...forkFrom.modelProvider !== undefined && {
|
|
2678
|
+
modelProvider: forkFrom.modelProvider
|
|
2679
|
+
},
|
|
2680
|
+
...forkFrom.approvalPolicy !== undefined && {
|
|
2681
|
+
approvalPolicy: forkFrom.approvalPolicy
|
|
2682
|
+
},
|
|
2683
|
+
...forkFrom.sandbox !== undefined && { sandbox: forkFrom.sandbox },
|
|
2684
|
+
...forkFrom.developerInstructions !== undefined && {
|
|
2685
|
+
developerInstructions: forkFrom.developerInstructions
|
|
2686
|
+
},
|
|
2687
|
+
...forkFrom.runtimeWorkspaceRoots !== undefined && {
|
|
2688
|
+
runtimeWorkspaceRoots: forkFrom.runtimeWorkspaceRoots
|
|
2689
|
+
},
|
|
2690
|
+
...basePolicy.config !== undefined || forkFrom.config !== undefined ? { config: { ...basePolicy.config ?? {}, ...forkFrom.config ?? {} } } : {}
|
|
2691
|
+
};
|
|
2692
|
+
return buildCodexThreadPolicyParams(withFork, dynamicOverrides);
|
|
2693
|
+
}
|
|
2694
|
+
function openCodexThreadRpc(peer, config, input, dynamicOverrides) {
|
|
2695
|
+
const threadParams = {
|
|
2696
|
+
cwd: input.cwd,
|
|
2697
|
+
...mergeOpenThreadPolicy(config, input.forkFrom, dynamicOverrides)
|
|
2698
|
+
};
|
|
2699
|
+
if (input.forkFrom !== undefined) {
|
|
2700
|
+
const fork = input.forkFrom;
|
|
2701
|
+
return peer.request("thread/fork", {
|
|
2702
|
+
threadId: fork.threadId,
|
|
2703
|
+
excludeTurns: fork.excludeTurns ?? true,
|
|
2704
|
+
...threadParams,
|
|
2705
|
+
...fork.beforeTurnId !== undefined && { beforeTurnId: fork.beforeTurnId },
|
|
2706
|
+
...fork.lastTurnId !== undefined && { lastTurnId: fork.lastTurnId },
|
|
2707
|
+
...fork.deferGoalContinuation !== undefined && {
|
|
2708
|
+
deferGoalContinuation: fork.deferGoalContinuation
|
|
2709
|
+
}
|
|
2710
|
+
});
|
|
2711
|
+
}
|
|
2712
|
+
if (input.nativeThreadId !== undefined) {
|
|
2713
|
+
return peer.request("thread/resume", {
|
|
2714
|
+
threadId: input.nativeThreadId,
|
|
2715
|
+
excludeTurns: true,
|
|
2716
|
+
...threadParams
|
|
2717
|
+
});
|
|
2718
|
+
}
|
|
2719
|
+
return peer.request("thread/start", threadParams);
|
|
543
2720
|
}
|
|
544
2721
|
async function openCodexSession(config, input) {
|
|
2722
|
+
validateCodexOpenInput(input);
|
|
545
2723
|
const profile = engineProfile("codex", input.profile);
|
|
546
2724
|
const linked = sessionAbort(input.signal);
|
|
2725
|
+
const externalPending = new Map;
|
|
547
2726
|
let current;
|
|
548
2727
|
let dead;
|
|
2728
|
+
let opened = false;
|
|
2729
|
+
let closing = false;
|
|
549
2730
|
let connected;
|
|
550
2731
|
try {
|
|
551
2732
|
connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
|
|
552
2733
|
profileId: profile.profileId,
|
|
553
2734
|
limits: config.limits,
|
|
2735
|
+
externalPending,
|
|
554
2736
|
getTurn: () => current,
|
|
555
2737
|
clearTurn: () => {
|
|
556
2738
|
current = undefined;
|
|
2739
|
+
},
|
|
2740
|
+
...config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
2741
|
+
...config.onServerRequest !== undefined && {
|
|
2742
|
+
onServerRequest: config.onServerRequest
|
|
557
2743
|
}
|
|
558
2744
|
}), (error) => {
|
|
2745
|
+
const shouldNotify = opened && !closing && input.signal?.aborted !== true;
|
|
559
2746
|
dead = error;
|
|
560
2747
|
const turn = current;
|
|
561
2748
|
current = undefined;
|
|
2749
|
+
externalPending.clear();
|
|
562
2750
|
loseEngineTurn(turn, codexStopped, error);
|
|
563
2751
|
linked.abort();
|
|
564
|
-
|
|
2752
|
+
if (shouldNotify)
|
|
2753
|
+
invokeSafely(() => config.onDisconnect?.(error));
|
|
2754
|
+
}, input.onStartupPhase);
|
|
565
2755
|
} catch (error) {
|
|
566
2756
|
linked.release();
|
|
567
2757
|
throw error;
|
|
568
2758
|
}
|
|
569
|
-
const { peer } = connected;
|
|
2759
|
+
const { peer, providerPid } = connected;
|
|
2760
|
+
const ensureAlive = () => {
|
|
2761
|
+
if (closing)
|
|
2762
|
+
throw new Error("The Codex session is closed");
|
|
2763
|
+
if (dead !== undefined)
|
|
2764
|
+
throw dead;
|
|
2765
|
+
};
|
|
570
2766
|
const stop = async (primary) => {
|
|
571
|
-
|
|
572
|
-
|
|
2767
|
+
closing = true;
|
|
2768
|
+
externalPending.clear();
|
|
2769
|
+
try {
|
|
2770
|
+
await stopConnection(connected, primary);
|
|
2771
|
+
} finally {
|
|
2772
|
+
linked.abort();
|
|
2773
|
+
linked.release();
|
|
2774
|
+
}
|
|
573
2775
|
};
|
|
2776
|
+
const controlClient = createCodexControlClient({ peer, ensureAlive });
|
|
574
2777
|
let threadId;
|
|
2778
|
+
let threadContext;
|
|
2779
|
+
let dynamicOverrides;
|
|
575
2780
|
try {
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
}
|
|
587
|
-
|
|
2781
|
+
if (config.prepareThread !== undefined) {
|
|
2782
|
+
dynamicOverrides = await raceAbort(Promise.resolve(config.prepareThread({
|
|
2783
|
+
controls: controlClient,
|
|
2784
|
+
cwd: input.cwd,
|
|
2785
|
+
...input.nativeThreadId !== undefined && {
|
|
2786
|
+
nativeThreadId: input.nativeThreadId
|
|
2787
|
+
},
|
|
2788
|
+
...input.forkFrom !== undefined && { forkFrom: input.forkFrom }
|
|
2789
|
+
})), linked.signal);
|
|
2790
|
+
linked.signal.throwIfAborted();
|
|
2791
|
+
}
|
|
2792
|
+
const openedReply = await openCodexThreadRpc(peer, config, input, dynamicOverrides);
|
|
2793
|
+
const parsed = CodexStartedThreadSchema.parse(openedReply);
|
|
2794
|
+
threadId = parsed.thread.id;
|
|
2795
|
+
threadContext = extractCodexThreadContext(parsed);
|
|
2796
|
+
if (config.verifyThread !== undefined) {
|
|
2797
|
+
emitStartupPhase(input.onStartupPhase, "verifying");
|
|
2798
|
+
await raceAbort(Promise.resolve(config.verifyThread({
|
|
2799
|
+
nativeThreadId: threadId,
|
|
2800
|
+
threadContext,
|
|
2801
|
+
controls: controlClient
|
|
2802
|
+
})), linked.signal);
|
|
2803
|
+
linked.signal.throwIfAborted();
|
|
2804
|
+
}
|
|
2805
|
+
if (dead !== undefined)
|
|
2806
|
+
throw dead;
|
|
2807
|
+
linked.signal.throwIfAborted();
|
|
588
2808
|
} catch (error) {
|
|
589
2809
|
await stop({ error });
|
|
590
2810
|
throw error;
|
|
591
2811
|
}
|
|
592
|
-
const
|
|
593
|
-
|
|
594
|
-
|
|
2812
|
+
const activeModelProvider = threadContext.modelProvider ?? dynamicOverrides?.modelProvider ?? input.forkFrom?.modelProvider ?? config.modelProvider;
|
|
2813
|
+
const startTurn = createCodexStartTurn({
|
|
2814
|
+
config,
|
|
2815
|
+
peer,
|
|
2816
|
+
threadId,
|
|
2817
|
+
activeModelProvider,
|
|
2818
|
+
signal: linked.signal,
|
|
2819
|
+
ensureAlive,
|
|
2820
|
+
getTurn: () => current,
|
|
2821
|
+
setTurn: (turn) => {
|
|
2822
|
+
current = turn;
|
|
2823
|
+
}
|
|
2824
|
+
});
|
|
2825
|
+
const mutators = createCodexSessionMutators({
|
|
2826
|
+
peer,
|
|
2827
|
+
threadId,
|
|
595
2828
|
imageOptions: config,
|
|
596
2829
|
signal: linked.signal,
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
2830
|
+
ensureAlive,
|
|
2831
|
+
getActiveTurn: () => current
|
|
2832
|
+
});
|
|
2833
|
+
opened = true;
|
|
2834
|
+
return {
|
|
2835
|
+
nativeThreadId: threadId,
|
|
2836
|
+
providerPid,
|
|
2837
|
+
threadContext,
|
|
2838
|
+
startTurn,
|
|
2839
|
+
async respond(interactionId, reply) {
|
|
2840
|
+
ensureAlive();
|
|
2841
|
+
answerCodexSessionRequest({ turn: current, externalPending, interactionId, reply });
|
|
602
2842
|
},
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
2843
|
+
...controlClient,
|
|
2844
|
+
...bindCodexSessionThreadControls(controlClient, threadId),
|
|
2845
|
+
...mutators,
|
|
2846
|
+
async close() {
|
|
2847
|
+
await stop();
|
|
2848
|
+
}
|
|
2849
|
+
};
|
|
2850
|
+
}
|
|
2851
|
+
async function openCodexControlConnection(config, input) {
|
|
2852
|
+
const profile = engineProfile("codex", input.profile);
|
|
2853
|
+
const linked = sessionAbort(input.signal);
|
|
2854
|
+
const externalPending = new Map;
|
|
2855
|
+
let dead;
|
|
2856
|
+
let opened = false;
|
|
2857
|
+
let closing = false;
|
|
2858
|
+
let connected;
|
|
2859
|
+
try {
|
|
2860
|
+
connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
|
|
2861
|
+
profileId: profile.profileId,
|
|
2862
|
+
limits: config.limits,
|
|
2863
|
+
externalPending,
|
|
2864
|
+
getTurn: () => {
|
|
2865
|
+
return;
|
|
2866
|
+
},
|
|
2867
|
+
clearTurn: () => {
|
|
2868
|
+
return;
|
|
2869
|
+
},
|
|
2870
|
+
...config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
2871
|
+
...config.onServerRequest !== undefined && {
|
|
2872
|
+
onServerRequest: config.onServerRequest
|
|
2873
|
+
}
|
|
2874
|
+
}), (error) => {
|
|
2875
|
+
const shouldNotify = opened && !closing && input.signal?.aborted !== true;
|
|
2876
|
+
dead = error;
|
|
2877
|
+
externalPending.clear();
|
|
2878
|
+
linked.abort();
|
|
2879
|
+
if (shouldNotify)
|
|
2880
|
+
invokeSafely(() => config.onDisconnect?.(error));
|
|
2881
|
+
}, input.onStartupPhase);
|
|
2882
|
+
} catch (error) {
|
|
2883
|
+
linked.release();
|
|
2884
|
+
throw error;
|
|
2885
|
+
}
|
|
2886
|
+
if (dead !== undefined || linked.signal.aborted) {
|
|
2887
|
+
const reason = dead ?? abortReason(linked.signal);
|
|
2888
|
+
closing = true;
|
|
2889
|
+
externalPending.clear();
|
|
2890
|
+
try {
|
|
2891
|
+
await stopConnection(connected, { error: reason });
|
|
2892
|
+
} finally {
|
|
2893
|
+
linked.abort();
|
|
2894
|
+
linked.release();
|
|
2895
|
+
}
|
|
2896
|
+
throw reason;
|
|
2897
|
+
}
|
|
2898
|
+
const ensureAlive = () => {
|
|
2899
|
+
if (closing)
|
|
2900
|
+
throw new Error("The Codex control connection is closed");
|
|
2901
|
+
if (dead !== undefined)
|
|
2902
|
+
throw dead;
|
|
2903
|
+
};
|
|
2904
|
+
const controlClient = createCodexControlClient({ peer: connected.peer, ensureAlive });
|
|
2905
|
+
opened = true;
|
|
2906
|
+
return {
|
|
2907
|
+
providerPid: connected.providerPid,
|
|
2908
|
+
...controlClient,
|
|
2909
|
+
async respond(interactionId, reply) {
|
|
2910
|
+
ensureAlive();
|
|
2911
|
+
answerCodexSessionRequest({ turn: undefined, externalPending, interactionId, reply });
|
|
2912
|
+
},
|
|
2913
|
+
async close() {
|
|
2914
|
+
closing = true;
|
|
2915
|
+
externalPending.clear();
|
|
610
2916
|
try {
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
});
|
|
616
|
-
turn.codexTurnId = CodexStartedTurnSchema.parse(started).turn.id;
|
|
617
|
-
} catch (error) {
|
|
618
|
-
if (current === turn)
|
|
619
|
-
current = undefined;
|
|
620
|
-
throw error;
|
|
2917
|
+
await stopConnection(connected);
|
|
2918
|
+
} finally {
|
|
2919
|
+
linked.abort();
|
|
2920
|
+
linked.release();
|
|
621
2921
|
}
|
|
622
|
-
return {
|
|
623
|
-
deltas: turn.channel,
|
|
624
|
-
async interrupt() {
|
|
625
|
-
turn.state.interruptRequested = true;
|
|
626
|
-
drainEngineRequests(turn, codexStopped);
|
|
627
|
-
if (turn.codexTurnId !== undefined)
|
|
628
|
-
await peer.request("turn/interrupt", { threadId, turnId: turn.codexTurnId });
|
|
629
|
-
},
|
|
630
|
-
async respond(interactionId, rawReply) {
|
|
631
|
-
const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
|
|
632
|
-
const waiting = turn.pending.get(interactionId);
|
|
633
|
-
if (waiting === undefined)
|
|
634
|
-
throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
|
|
635
|
-
if (CODEX_APPROVAL_REQUESTS.has(waiting.detail.method)) {
|
|
636
|
-
if (reply.kind === "input")
|
|
637
|
-
throw new TypeError("A Codex approval is approved or denied, not answered with input");
|
|
638
|
-
answerEngineRequest(turn, interactionId, {
|
|
639
|
-
decision: reply.kind === "approve" ? CODEX_APPROVAL_DECISION.approve : CODEX_APPROVAL_DECISION.deny
|
|
640
|
-
});
|
|
641
|
-
} else {
|
|
642
|
-
if (reply.kind !== "input")
|
|
643
|
-
throw new TypeError("A Codex input request is answered with input");
|
|
644
|
-
answerEngineRequest(turn, interactionId, {
|
|
645
|
-
answers: CodexUserInputAnswersSchema.parse(reply.value)
|
|
646
|
-
});
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
};
|
|
650
2922
|
}
|
|
2923
|
+
};
|
|
2924
|
+
}
|
|
2925
|
+
|
|
2926
|
+
// src/agent-executor/codex/shared-thread.ts
|
|
2927
|
+
var CLOSE_UNSUBSCRIBE_TIMEOUT_MS = 5000;
|
|
2928
|
+
function bestEffortUnsubscribe(state, threadId) {
|
|
2929
|
+
if (state.isServerClosing() || state.getServerDead() !== undefined) {
|
|
2930
|
+
return Promise.resolve();
|
|
2931
|
+
}
|
|
2932
|
+
return state.peer.request("thread/unsubscribe", { threadId }, { timeoutMs: CLOSE_UNSUBSCRIBE_TIMEOUT_MS }).then(() => {
|
|
2933
|
+
return;
|
|
2934
|
+
}, () => {
|
|
2935
|
+
return;
|
|
2936
|
+
});
|
|
2937
|
+
}
|
|
2938
|
+
function buildSharedThreadSession(params) {
|
|
2939
|
+
const { state, slot, threadContext, activeModelProvider, threadAbort } = params;
|
|
2940
|
+
const { threadId } = slot;
|
|
2941
|
+
const ensureThreadAlive = () => {
|
|
2942
|
+
if (slot.closed)
|
|
2943
|
+
throw new Error("The Codex session is closed");
|
|
2944
|
+
if (slot.dead !== undefined)
|
|
2945
|
+
throw slot.dead;
|
|
2946
|
+
state.ensureServerAlive();
|
|
2947
|
+
};
|
|
2948
|
+
const threadControlClient = createCodexControlClient({
|
|
2949
|
+
peer: state.peer,
|
|
2950
|
+
ensureAlive: ensureThreadAlive
|
|
2951
|
+
});
|
|
2952
|
+
const startTurn = createCodexStartTurn({
|
|
2953
|
+
config: state.config,
|
|
2954
|
+
peer: state.peer,
|
|
2955
|
+
threadId,
|
|
2956
|
+
activeModelProvider,
|
|
2957
|
+
signal: threadAbort.signal,
|
|
2958
|
+
ensureAlive: ensureThreadAlive,
|
|
2959
|
+
getTurn: () => slot.current,
|
|
2960
|
+
setTurn: (turn) => {
|
|
2961
|
+
slot.current = turn;
|
|
2962
|
+
}
|
|
2963
|
+
});
|
|
2964
|
+
const mutators = createCodexSessionMutators({
|
|
2965
|
+
peer: state.peer,
|
|
2966
|
+
threadId,
|
|
2967
|
+
imageOptions: state.config,
|
|
2968
|
+
signal: threadAbort.signal,
|
|
2969
|
+
ensureAlive: ensureThreadAlive,
|
|
2970
|
+
getActiveTurn: () => slot.current
|
|
651
2971
|
});
|
|
2972
|
+
const closeThread = async () => {
|
|
2973
|
+
if (slot.closed)
|
|
2974
|
+
return;
|
|
2975
|
+
slot.closed = true;
|
|
2976
|
+
const turn = slot.current;
|
|
2977
|
+
slot.current = undefined;
|
|
2978
|
+
slot.externalPending.clear();
|
|
2979
|
+
loseEngineTurn(turn, codexStopped, new Error("The Codex session closed"));
|
|
2980
|
+
state.threads.delete(threadId);
|
|
2981
|
+
try {
|
|
2982
|
+
await bestEffortUnsubscribe(state, threadId);
|
|
2983
|
+
} finally {
|
|
2984
|
+
threadAbort.abort();
|
|
2985
|
+
slot.releaseThreadSignal();
|
|
2986
|
+
}
|
|
2987
|
+
};
|
|
2988
|
+
threadAbort.signal.addEventListener("abort", () => {
|
|
2989
|
+
if (slot.closed)
|
|
2990
|
+
return;
|
|
2991
|
+
slot.closed = true;
|
|
2992
|
+
const reason = abortReason(threadAbort.signal);
|
|
2993
|
+
slot.dead = slot.dead ?? (reason instanceof Error ? reason : new Error(String(reason)));
|
|
2994
|
+
const turn = slot.current;
|
|
2995
|
+
slot.current = undefined;
|
|
2996
|
+
slot.externalPending.clear();
|
|
2997
|
+
loseEngineTurn(turn, codexStopped, slot.dead);
|
|
2998
|
+
state.threads.delete(threadId);
|
|
2999
|
+
slot.releaseThreadSignal();
|
|
3000
|
+
bestEffortUnsubscribe(state, threadId);
|
|
3001
|
+
}, { once: true });
|
|
652
3002
|
return {
|
|
653
3003
|
nativeThreadId: threadId,
|
|
3004
|
+
providerPid: state.providerPid,
|
|
3005
|
+
threadContext,
|
|
654
3006
|
startTurn,
|
|
655
|
-
async
|
|
656
|
-
|
|
3007
|
+
async respond(interactionId, reply) {
|
|
3008
|
+
ensureThreadAlive();
|
|
3009
|
+
answerCodexSessionRequest({
|
|
3010
|
+
turn: slot.current,
|
|
3011
|
+
externalPending: slot.externalPending,
|
|
3012
|
+
interactionId,
|
|
3013
|
+
reply
|
|
3014
|
+
});
|
|
3015
|
+
},
|
|
3016
|
+
...threadControlClient,
|
|
3017
|
+
...bindCodexSessionThreadControls(threadControlClient, threadId),
|
|
3018
|
+
...mutators,
|
|
3019
|
+
close: closeThread
|
|
3020
|
+
};
|
|
3021
|
+
}
|
|
3022
|
+
async function openSharedCodexThread(state, threadInput) {
|
|
3023
|
+
state.ensureServerAlive();
|
|
3024
|
+
validateCodexOpenInput({ ...threadInput, profile: state.profile });
|
|
3025
|
+
if (threadInput.nativeThreadId !== undefined && (state.threads.has(threadInput.nativeThreadId) || state.openingNativeThreadIds.has(threadInput.nativeThreadId))) {
|
|
3026
|
+
throw new Error(`[stitchkit] CodexSharedServer.openThread: thread ${threadInput.nativeThreadId} is already open on this shared server`);
|
|
3027
|
+
}
|
|
3028
|
+
if (state.threads.size + state.openingThreads >= state.maxThreads) {
|
|
3029
|
+
throw new RangeError(`[stitchkit] CodexSharedServer.openThread: active thread limit (${state.maxThreads}) reached`);
|
|
3030
|
+
}
|
|
3031
|
+
const threadAbort = sessionAbort(threadInput.signal);
|
|
3032
|
+
const onServerAbort = () => threadAbort.abort();
|
|
3033
|
+
state.serverSignal.addEventListener("abort", onServerAbort, { once: true });
|
|
3034
|
+
let signalReleased = false;
|
|
3035
|
+
const releaseThreadSignal = () => {
|
|
3036
|
+
if (signalReleased)
|
|
3037
|
+
return;
|
|
3038
|
+
signalReleased = true;
|
|
3039
|
+
state.serverSignal.removeEventListener("abort", onServerAbort);
|
|
3040
|
+
threadAbort.release();
|
|
3041
|
+
};
|
|
3042
|
+
state.openingThreads += 1;
|
|
3043
|
+
if (threadInput.nativeThreadId !== undefined) {
|
|
3044
|
+
state.openingNativeThreadIds.add(threadInput.nativeThreadId);
|
|
3045
|
+
}
|
|
3046
|
+
let registeredThreadId;
|
|
3047
|
+
try {
|
|
3048
|
+
threadAbort.signal.throwIfAborted();
|
|
3049
|
+
let dynamicOverrides;
|
|
3050
|
+
if (state.config.prepareThread !== undefined) {
|
|
3051
|
+
dynamicOverrides = await raceAbort(Promise.resolve(state.config.prepareThread({
|
|
3052
|
+
controls: state.controlClient,
|
|
3053
|
+
cwd: threadInput.cwd,
|
|
3054
|
+
...threadInput.nativeThreadId !== undefined && {
|
|
3055
|
+
nativeThreadId: threadInput.nativeThreadId
|
|
3056
|
+
},
|
|
3057
|
+
...threadInput.forkFrom !== undefined && { forkFrom: threadInput.forkFrom }
|
|
3058
|
+
})), threadAbort.signal);
|
|
3059
|
+
threadAbort.signal.throwIfAborted();
|
|
3060
|
+
state.ensureServerAlive();
|
|
3061
|
+
}
|
|
3062
|
+
const disposeLateOpen = (reply) => {
|
|
3063
|
+
const parsedLate = CodexStartedThreadSchema.safeParse(reply);
|
|
3064
|
+
if (parsedLate.success && !state.threads.has(parsedLate.data.thread.id)) {
|
|
3065
|
+
bestEffortUnsubscribe(state, parsedLate.data.thread.id);
|
|
3066
|
+
}
|
|
3067
|
+
};
|
|
3068
|
+
const openedReply = await raceAbort(openCodexThreadRpc(state.peer, state.config, threadInput, dynamicOverrides), threadAbort.signal, disposeLateOpen);
|
|
3069
|
+
threadAbort.signal.throwIfAborted();
|
|
3070
|
+
state.ensureServerAlive();
|
|
3071
|
+
const parsed = CodexStartedThreadSchema.parse(openedReply);
|
|
3072
|
+
const threadId = parsed.thread.id;
|
|
3073
|
+
const threadContext = extractCodexThreadContext(parsed);
|
|
3074
|
+
if (state.threads.has(threadId)) {
|
|
3075
|
+
throw new Error(`[stitchkit] CodexSharedServer.openThread: thread ${threadId} is already open on this shared server`);
|
|
3076
|
+
}
|
|
3077
|
+
const externalPending = new Map;
|
|
3078
|
+
const slot = {
|
|
3079
|
+
threadId,
|
|
3080
|
+
current: undefined,
|
|
3081
|
+
externalPending,
|
|
3082
|
+
closed: false,
|
|
3083
|
+
dead: undefined,
|
|
3084
|
+
abortThread: () => threadAbort.abort(),
|
|
3085
|
+
releaseThreadSignal,
|
|
3086
|
+
handlers: createCodexHandlers({
|
|
3087
|
+
profileId: state.profile.profileId,
|
|
3088
|
+
limits: state.config.limits,
|
|
3089
|
+
externalPending,
|
|
3090
|
+
getTurn: () => slot.current,
|
|
3091
|
+
clearTurn: () => {
|
|
3092
|
+
slot.current = undefined;
|
|
3093
|
+
},
|
|
3094
|
+
...state.config.onNotification !== undefined && {
|
|
3095
|
+
onNotification: state.config.onNotification
|
|
3096
|
+
},
|
|
3097
|
+
...state.config.onServerRequest !== undefined && {
|
|
3098
|
+
onServerRequest: state.config.onServerRequest
|
|
3099
|
+
}
|
|
3100
|
+
})
|
|
3101
|
+
};
|
|
3102
|
+
state.threads.set(threadId, slot);
|
|
3103
|
+
registeredThreadId = threadId;
|
|
3104
|
+
if (state.config.verifyThread !== undefined) {
|
|
3105
|
+
emitStartupPhase(threadInput.onStartupPhase, "verifying");
|
|
3106
|
+
await raceAbort(Promise.resolve(state.config.verifyThread({
|
|
3107
|
+
nativeThreadId: threadId,
|
|
3108
|
+
threadContext,
|
|
3109
|
+
controls: state.controlClient
|
|
3110
|
+
})), threadAbort.signal);
|
|
3111
|
+
threadAbort.signal.throwIfAborted();
|
|
3112
|
+
}
|
|
3113
|
+
state.ensureServerAlive();
|
|
3114
|
+
threadAbort.signal.throwIfAborted();
|
|
3115
|
+
if (slot.dead !== undefined)
|
|
3116
|
+
throw slot.dead;
|
|
3117
|
+
const activeModelProvider = threadContext.modelProvider ?? dynamicOverrides?.modelProvider ?? threadInput.forkFrom?.modelProvider ?? state.config.modelProvider;
|
|
3118
|
+
return buildSharedThreadSession({
|
|
3119
|
+
state,
|
|
3120
|
+
slot,
|
|
3121
|
+
threadContext,
|
|
3122
|
+
activeModelProvider,
|
|
3123
|
+
threadAbort
|
|
3124
|
+
});
|
|
3125
|
+
} catch (error) {
|
|
3126
|
+
if (registeredThreadId !== undefined) {
|
|
3127
|
+
state.threads.delete(registeredThreadId);
|
|
3128
|
+
await bestEffortUnsubscribe(state, registeredThreadId);
|
|
3129
|
+
}
|
|
3130
|
+
threadAbort.abort();
|
|
3131
|
+
releaseThreadSignal();
|
|
3132
|
+
throw error;
|
|
3133
|
+
} finally {
|
|
3134
|
+
state.openingThreads -= 1;
|
|
3135
|
+
if (threadInput.nativeThreadId !== undefined) {
|
|
3136
|
+
state.openingNativeThreadIds.delete(threadInput.nativeThreadId);
|
|
3137
|
+
}
|
|
3138
|
+
}
|
|
3139
|
+
}
|
|
3140
|
+
|
|
3141
|
+
// src/agent-executor/codex/shared-server.ts
|
|
3142
|
+
var DEFAULT_MAX_SHARED_THREADS = 32;
|
|
3143
|
+
var HARD_MAX_SHARED_THREADS = 256;
|
|
3144
|
+
function extractCodexThreadId(params) {
|
|
3145
|
+
if (!isRecord(params))
|
|
3146
|
+
return;
|
|
3147
|
+
if (typeof params.threadId === "string" && params.threadId.length > 0)
|
|
3148
|
+
return params.threadId;
|
|
3149
|
+
if (isRecord(params.thread) && typeof params.thread.id === "string" && params.thread.id.length > 0) {
|
|
3150
|
+
return params.thread.id;
|
|
3151
|
+
}
|
|
3152
|
+
if (isRecord(params.turn) && typeof params.turn.threadId === "string" && params.turn.threadId.length > 0) {
|
|
3153
|
+
return params.turn.threadId;
|
|
3154
|
+
}
|
|
3155
|
+
return;
|
|
3156
|
+
}
|
|
3157
|
+
function validateSharedServerInputs(config, input) {
|
|
3158
|
+
if (config.transport !== undefined && config.transport.kind !== "stdio") {
|
|
3159
|
+
throw new TypeError(`[stitchkit] CodexDriver.openSharedServer: shared multi-thread mode requires stdio transport (received ${JSON.stringify(config.transport.kind)})`);
|
|
3160
|
+
}
|
|
3161
|
+
const maxThreads = input.maxThreads ?? DEFAULT_MAX_SHARED_THREADS;
|
|
3162
|
+
assertPositiveSafeInteger("[stitchkit] CodexDriver.openSharedServer: maxThreads", maxThreads);
|
|
3163
|
+
if (maxThreads > HARD_MAX_SHARED_THREADS) {
|
|
3164
|
+
throw new RangeError(`[stitchkit] CodexDriver.openSharedServer: maxThreads (${maxThreads}) must not exceed ${HARD_MAX_SHARED_THREADS}`);
|
|
3165
|
+
}
|
|
3166
|
+
return maxThreads;
|
|
3167
|
+
}
|
|
3168
|
+
async function openCodexSharedServer(config, baseCapabilities, input) {
|
|
3169
|
+
const maxThreads = validateSharedServerInputs(config, input);
|
|
3170
|
+
const profile = engineProfile("codex", input.profile);
|
|
3171
|
+
const linked = sessionAbort(input.signal);
|
|
3172
|
+
const threads = new Map;
|
|
3173
|
+
const globalExternalPending = new Map;
|
|
3174
|
+
let serverDead;
|
|
3175
|
+
let serverClosing = false;
|
|
3176
|
+
let opened = false;
|
|
3177
|
+
const globalHandlers = createCodexHandlers({
|
|
3178
|
+
profileId: profile.profileId,
|
|
3179
|
+
limits: config.limits,
|
|
3180
|
+
externalPending: globalExternalPending,
|
|
3181
|
+
getTurn: () => {
|
|
3182
|
+
return;
|
|
3183
|
+
},
|
|
3184
|
+
clearTurn: () => {
|
|
3185
|
+
return;
|
|
3186
|
+
},
|
|
3187
|
+
...config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
3188
|
+
...config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest }
|
|
3189
|
+
});
|
|
3190
|
+
const failAllThreads = (error) => {
|
|
3191
|
+
for (const slot of [...threads.values()]) {
|
|
3192
|
+
slot.closed = true;
|
|
3193
|
+
slot.dead = error;
|
|
3194
|
+
const turn = slot.current;
|
|
3195
|
+
slot.current = undefined;
|
|
3196
|
+
slot.externalPending.clear();
|
|
3197
|
+
loseEngineTurn(turn, codexStopped, error);
|
|
3198
|
+
slot.abortThread();
|
|
3199
|
+
slot.releaseThreadSignal();
|
|
3200
|
+
}
|
|
3201
|
+
threads.clear();
|
|
3202
|
+
};
|
|
3203
|
+
let connected;
|
|
3204
|
+
try {
|
|
3205
|
+
connected = await connectCodex(config, profile, input.cwd, linked.signal, {
|
|
3206
|
+
onNotification(method, params) {
|
|
3207
|
+
if (method === "account/rateLimits/updated") {
|
|
3208
|
+
invokeSafely(() => globalHandlers.onNotification(method, params));
|
|
3209
|
+
return;
|
|
3210
|
+
}
|
|
3211
|
+
const targetId = extractCodexThreadId(params);
|
|
3212
|
+
const slot = targetId !== undefined ? threads.get(targetId) : undefined;
|
|
3213
|
+
if (slot !== undefined) {
|
|
3214
|
+
invokeSafely(() => slot.handlers.onNotification(method, params));
|
|
3215
|
+
return;
|
|
3216
|
+
}
|
|
3217
|
+
invokeSafely(() => globalHandlers.onNotification(method, params));
|
|
3218
|
+
},
|
|
3219
|
+
onRequest(method, params, id) {
|
|
3220
|
+
const targetId = extractCodexThreadId(params);
|
|
3221
|
+
const slot = targetId !== undefined ? threads.get(targetId) : undefined;
|
|
3222
|
+
if (slot !== undefined)
|
|
3223
|
+
return slot.handlers.onRequest(method, params, id);
|
|
3224
|
+
return globalHandlers.onRequest(method, params, id);
|
|
3225
|
+
}
|
|
3226
|
+
}, (error) => {
|
|
3227
|
+
const shouldNotify = opened && !serverClosing && input.signal?.aborted !== true;
|
|
3228
|
+
serverDead = error;
|
|
3229
|
+
globalExternalPending.clear();
|
|
3230
|
+
failAllThreads(error);
|
|
3231
|
+
linked.abort();
|
|
3232
|
+
if (shouldNotify)
|
|
3233
|
+
invokeSafely(() => config.onDisconnect?.(error));
|
|
3234
|
+
}, input.onStartupPhase);
|
|
3235
|
+
} catch (error) {
|
|
3236
|
+
linked.release();
|
|
3237
|
+
throw error;
|
|
3238
|
+
}
|
|
3239
|
+
const { peer, providerPid } = connected;
|
|
3240
|
+
const ensureServerAlive = () => {
|
|
3241
|
+
if (serverClosing)
|
|
3242
|
+
throw new Error("The Codex shared server is closed");
|
|
3243
|
+
if (serverDead !== undefined)
|
|
3244
|
+
throw serverDead;
|
|
3245
|
+
};
|
|
3246
|
+
const controlClient = createCodexControlClient({ peer, ensureAlive: ensureServerAlive });
|
|
3247
|
+
const sharedCapabilities = {
|
|
3248
|
+
...baseCapabilities,
|
|
3249
|
+
multiThreadPerProcess: true
|
|
3250
|
+
};
|
|
3251
|
+
const state = {
|
|
3252
|
+
config,
|
|
3253
|
+
profile,
|
|
3254
|
+
peer,
|
|
3255
|
+
providerPid,
|
|
3256
|
+
maxThreads,
|
|
3257
|
+
controlClient,
|
|
3258
|
+
serverSignal: linked.signal,
|
|
3259
|
+
threads,
|
|
3260
|
+
openingNativeThreadIds: new Set,
|
|
3261
|
+
openingThreads: 0,
|
|
3262
|
+
isServerClosing: () => serverClosing,
|
|
3263
|
+
getServerDead: () => serverDead,
|
|
3264
|
+
ensureServerAlive
|
|
3265
|
+
};
|
|
3266
|
+
const closeServer = async () => {
|
|
3267
|
+
if (serverClosing)
|
|
3268
|
+
return;
|
|
3269
|
+
serverClosing = true;
|
|
3270
|
+
globalExternalPending.clear();
|
|
3271
|
+
failAllThreads(new Error("The Codex shared server closed"));
|
|
3272
|
+
try {
|
|
3273
|
+
await stopConnection(connected);
|
|
3274
|
+
} finally {
|
|
3275
|
+
linked.abort();
|
|
3276
|
+
linked.release();
|
|
657
3277
|
}
|
|
658
3278
|
};
|
|
3279
|
+
opened = true;
|
|
3280
|
+
return {
|
|
3281
|
+
providerPid,
|
|
3282
|
+
maxThreads,
|
|
3283
|
+
get activeThreadCount() {
|
|
3284
|
+
return threads.size;
|
|
3285
|
+
},
|
|
3286
|
+
capabilities: sharedCapabilities,
|
|
3287
|
+
...controlClient,
|
|
3288
|
+
openThread: (threadInput) => openSharedCodexThread(state, threadInput),
|
|
3289
|
+
close: closeServer
|
|
3290
|
+
};
|
|
659
3291
|
}
|
|
660
3292
|
|
|
661
3293
|
// src/agent-executor/codex/driver.ts
|
|
662
3294
|
var MAX_HISTORY_PAGES = 256;
|
|
663
3295
|
var FIND_INPUT_MAX_LINE_BYTES = 64 * 1024 * 1024;
|
|
3296
|
+
async function findCodexClientInput(peer, nativeThreadId, clientId) {
|
|
3297
|
+
const seen = new Set;
|
|
3298
|
+
let cursor;
|
|
3299
|
+
for (let pageNumber = 0;pageNumber < MAX_HISTORY_PAGES; pageNumber += 1) {
|
|
3300
|
+
const page = CodexTurnsPageSchema.parse(await peer.request("thread/turns/list", {
|
|
3301
|
+
threadId: nativeThreadId,
|
|
3302
|
+
limit: 50,
|
|
3303
|
+
itemsView: "full",
|
|
3304
|
+
...cursor !== undefined && { cursor }
|
|
3305
|
+
}));
|
|
3306
|
+
if (page.data.some((turn) => turn.items.some((item) => item.type === "userMessage" && item.clientId === clientId))) {
|
|
3307
|
+
return true;
|
|
3308
|
+
}
|
|
3309
|
+
const next = page.nextCursor;
|
|
3310
|
+
if (next === null || next === undefined)
|
|
3311
|
+
return false;
|
|
3312
|
+
if (seen.has(next)) {
|
|
3313
|
+
throw new Error(`Codex thread/turns/list repeated cursor ${JSON.stringify(next)} before history ended`);
|
|
3314
|
+
}
|
|
3315
|
+
seen.add(next);
|
|
3316
|
+
cursor = next;
|
|
3317
|
+
}
|
|
3318
|
+
throw new Error(`Codex thread/turns/list exceeded ${MAX_HISTORY_PAGES} pages without reaching the end of history`);
|
|
3319
|
+
}
|
|
664
3320
|
function createCodexDriver(config = {}) {
|
|
665
3321
|
validateImageOptions(config);
|
|
3322
|
+
validateCodexTransportAndArgs(config);
|
|
3323
|
+
validateCodexPolicyOverrides(config, "createCodexDriver");
|
|
666
3324
|
const executable = config.executable ?? "codex";
|
|
667
3325
|
const prefix = config.prefixArgs ?? [];
|
|
668
3326
|
const ambient = config.ambient ?? process.env;
|
|
669
3327
|
const limits = new Map;
|
|
670
3328
|
let version = "unknown";
|
|
671
|
-
const
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
3329
|
+
const capabilities = {
|
|
3330
|
+
runtimePolicyEnforcement: "native",
|
|
3331
|
+
sessionApproval: true,
|
|
3332
|
+
interruptOnDeny: true,
|
|
3333
|
+
updatedToolInput: false,
|
|
3334
|
+
structuredInput: true,
|
|
3335
|
+
steer: true,
|
|
3336
|
+
fork: true,
|
|
3337
|
+
revert: true,
|
|
3338
|
+
compact: true,
|
|
3339
|
+
injectItems: true,
|
|
3340
|
+
backgroundWorkOutlivesTurn: false,
|
|
3341
|
+
multiThreadPerProcess: false,
|
|
3342
|
+
images: config.resolveFile !== undefined,
|
|
3343
|
+
planLimits: "pull"
|
|
3344
|
+
};
|
|
3345
|
+
const session = (options) => {
|
|
3346
|
+
const transport = options?.forceStdioForListen && config.transport?.kind === "unix-listen" ? { kind: "stdio" } : config.transport;
|
|
3347
|
+
return {
|
|
3348
|
+
executable,
|
|
3349
|
+
prefix,
|
|
3350
|
+
...transport !== undefined && { transport },
|
|
3351
|
+
...config.serverArgs !== undefined && { serverArgs: config.serverArgs },
|
|
3352
|
+
...config.model !== undefined && { model: config.model },
|
|
3353
|
+
...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
|
|
3354
|
+
approvalPolicy: config.approvalPolicy ?? "on-request",
|
|
3355
|
+
sandbox: config.sandbox ?? "workspace-write",
|
|
3356
|
+
...config.developerInstructions !== undefined && {
|
|
3357
|
+
developerInstructions: config.developerInstructions
|
|
3358
|
+
},
|
|
3359
|
+
...config.runtimeWorkspaceRoots !== undefined && {
|
|
3360
|
+
runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
|
|
3361
|
+
},
|
|
3362
|
+
...config.config !== undefined && { config: config.config },
|
|
3363
|
+
...config.prepareThread !== undefined && { prepareThread: config.prepareThread },
|
|
3364
|
+
...config.verifyThread !== undefined && { verifyThread: config.verifyThread },
|
|
3365
|
+
...!options?.ephemeralProbe && config.onNotification !== undefined && { onNotification: config.onNotification },
|
|
3366
|
+
...!options?.ephemeralProbe && config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest },
|
|
3367
|
+
...!options?.ephemeralProbe && config.onDisconnect !== undefined && { onDisconnect: config.onDisconnect },
|
|
3368
|
+
ambient,
|
|
3369
|
+
limits,
|
|
3370
|
+
version,
|
|
3371
|
+
...config.resolveFile !== undefined && { resolveFile: config.resolveFile },
|
|
3372
|
+
...config.maxImageBytes !== undefined && { maxImageBytes: config.maxImageBytes },
|
|
3373
|
+
...options?.maxLineBytes !== undefined && { maxLineBytes: options.maxLineBytes }
|
|
3374
|
+
};
|
|
3375
|
+
};
|
|
684
3376
|
const cli = (profile, args) => runEngineCli({ executable, prefix, args, profile, ambient });
|
|
685
|
-
const ask = (profile, cwd, question, maxLineBytes) => withEphemeralConnection((signal) => connectCodex(session(
|
|
3377
|
+
const ask = (profile, cwd, question, maxLineBytes) => withEphemeralConnection((signal) => connectCodex(session({
|
|
3378
|
+
...maxLineBytes !== undefined && { maxLineBytes },
|
|
3379
|
+
forceStdioForListen: true,
|
|
3380
|
+
ephemeralProbe: true
|
|
3381
|
+
}), engineProfile("codex", profile), cwd, signal), (connection) => question(connection.peer));
|
|
686
3382
|
return {
|
|
687
3383
|
engine: "codex",
|
|
688
3384
|
reconcile: "client-id",
|
|
3385
|
+
capabilities,
|
|
689
3386
|
async info() {
|
|
690
3387
|
const probe = {
|
|
691
3388
|
profileId: "version-probe",
|
|
@@ -699,7 +3396,8 @@ function createCodexDriver(config = {}) {
|
|
|
699
3396
|
engine: "codex",
|
|
700
3397
|
version,
|
|
701
3398
|
reconcile: "client-id",
|
|
702
|
-
models: { answer: "not-asked" }
|
|
3399
|
+
models: { answer: "not-asked" },
|
|
3400
|
+
capabilities
|
|
703
3401
|
};
|
|
704
3402
|
},
|
|
705
3403
|
async status(profile) {
|
|
@@ -714,7 +3412,7 @@ ${decoder.decode(loginResult.stderr)}`.trim();
|
|
|
714
3412
|
if (credential === "subscription") {
|
|
715
3413
|
try {
|
|
716
3414
|
const answer = await ask(parsed, process.cwd(), (peer) => peer.request("account/rateLimits/read"));
|
|
717
|
-
const windows = codexPlanWindows(
|
|
3415
|
+
const windows = codexPlanWindows(answer);
|
|
718
3416
|
planLimits = mergeRateLimitEvent2({ previous: planLimits, windows, now: new Date });
|
|
719
3417
|
limits.set(parsed.profileId, planLimits);
|
|
720
3418
|
} catch (error) {
|
|
@@ -738,32 +3436,11 @@ ${decoder.decode(loginResult.stderr)}`.trim();
|
|
|
738
3436
|
};
|
|
739
3437
|
},
|
|
740
3438
|
async findInput(input) {
|
|
741
|
-
return ask(input.profile, input.cwd,
|
|
742
|
-
const seen = new Set;
|
|
743
|
-
let cursor;
|
|
744
|
-
for (let pageNumber = 0;pageNumber < MAX_HISTORY_PAGES; pageNumber += 1) {
|
|
745
|
-
const page = CodexTurnsPageSchema.parse(await peer.request("thread/turns/list", {
|
|
746
|
-
threadId: input.nativeThreadId,
|
|
747
|
-
limit: 50,
|
|
748
|
-
itemsView: "full",
|
|
749
|
-
...cursor !== undefined && { cursor }
|
|
750
|
-
}));
|
|
751
|
-
if (page.data.some((turn) => turn.items.some((item) => item.type === "userMessage" && item.clientId === input.clientId))) {
|
|
752
|
-
return true;
|
|
753
|
-
}
|
|
754
|
-
const next = page.nextCursor;
|
|
755
|
-
if (next === null || next === undefined)
|
|
756
|
-
return false;
|
|
757
|
-
if (seen.has(next)) {
|
|
758
|
-
throw new Error(`Codex thread/turns/list repeated cursor ${JSON.stringify(next)} before history ended`);
|
|
759
|
-
}
|
|
760
|
-
seen.add(next);
|
|
761
|
-
cursor = next;
|
|
762
|
-
}
|
|
763
|
-
throw new Error(`Codex thread/turns/list exceeded ${MAX_HISTORY_PAGES} pages without reaching the end of history`);
|
|
764
|
-
}, FIND_INPUT_MAX_LINE_BYTES);
|
|
3439
|
+
return ask(input.profile, input.cwd, (peer) => findCodexClientInput(peer, input.nativeThreadId, input.clientId), FIND_INPUT_MAX_LINE_BYTES);
|
|
765
3440
|
},
|
|
766
|
-
open: (input) => openCodexSession(session(), input)
|
|
3441
|
+
open: (input) => openCodexSession(session(), input),
|
|
3442
|
+
connectControl: (input) => openCodexControlConnection(session(), input),
|
|
3443
|
+
openSharedServer: (input) => openCodexSharedServer(session(), capabilities, input)
|
|
767
3444
|
};
|
|
768
3445
|
}
|
|
769
3446
|
// src/agent-executor/codex/scenarios.ts
|
|
@@ -852,6 +3529,8 @@ var codexFakeScenarios = {
|
|
|
852
3529
|
crash: () => steps(text("dying "), { do: "crash" })
|
|
853
3530
|
};
|
|
854
3531
|
export {
|
|
3532
|
+
CodexSkillInputSchema,
|
|
3533
|
+
CodexUnixSocketError,
|
|
855
3534
|
codexFakeScenarios,
|
|
856
3535
|
codexPlanWindows,
|
|
857
3536
|
createCodexDriver
|