@chroxy/server 0.10.0 → 0.11.10
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/CONFIG.md +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +109 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +223 -60
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +100 -10
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +82 -12
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +70 -36
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +301 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +485 -29
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
|
@@ -1,18 +1,141 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { assistantResponseText } from './assistant-response.js'
|
|
2
|
+
import { mkdirSync, writeFileSync, rmSync } from 'fs'
|
|
3
|
+
import { randomUUID } from 'crypto'
|
|
2
4
|
import { tmpdir } from 'os'
|
|
3
|
-
import { join, basename, extname } from 'path'
|
|
4
|
-
import { BaseSession, buildBaseSessionOpts } from './base-session.js'
|
|
5
|
+
import { join, basename, extname, posix as posixPath, win32 as win32Path } from 'path'
|
|
6
|
+
import { BaseSession, buildBaseSessionOpts, DEFAULT_RESULT_TIMEOUT_MS, reportInputAdmission } from './base-session.js'
|
|
7
|
+
import { CODEX_APPSERVER_CUSTOMIZATION } from './provider-customization.js'
|
|
8
|
+
import { sweepStaleOwnedDirs, ensureOwnedBaseDir, OWNER_PID_FILE } from './utils/stale-session-dirs.js'
|
|
9
|
+
import { isOperatorTimeoutInRange } from './duration.js'
|
|
10
|
+
import { nonNegInt, synthesizeModelUsage } from './usage-normalize.js'
|
|
5
11
|
import { CodexSession, resolveCodexSandbox } from './codex-session.js'
|
|
6
12
|
import { CodexAppServerClient } from './codex-app-server-client.js'
|
|
13
|
+
import { parseCodexUserAgent, capabilitiesForVersion, parseSemver, compareSemver } from './codex-protocol-capabilities.js'
|
|
14
|
+
import { findNewestBundledCodexClient } from './codex-bundled-client.js'
|
|
15
|
+
import {
|
|
16
|
+
MODEL_UNSUPPORTED_CODE, detectModelRejection, codexClientKey, recordModelRejection,
|
|
17
|
+
rejectedDefaultFor, rejectedModelsFor, suggestFallbackModel,
|
|
18
|
+
} from './codex-model-rejections.js'
|
|
7
19
|
import { PermissionManager, wirePermissionManager } from './permission-manager.js'
|
|
8
20
|
import { materializeAttachments, buildAttachmentsPromptSuffix } from './claude-tui-attachments.js'
|
|
9
21
|
import { buildSpawnEnv } from './utils/spawn-env.js'
|
|
22
|
+
import { maybeRatchetContextWindow } from './utils/context-window-learn.js'
|
|
23
|
+
import { getRegistryForProvider } from './models.js'
|
|
24
|
+
import { labelBinarySpawnFailure } from './utils/verify-binary.js'
|
|
10
25
|
import { createLogger, loggerForSession } from './logger.js'
|
|
26
|
+
import { USAGE_LIMIT_CODE } from './claude-tui/usage-limit.js'
|
|
27
|
+
import { NATIVE_RESUME_DRIVER, NATIVE_RESUME_VERSION, nativeRestoreError, nativeMachineId, bindNativeOwnership, validateLocator, validateEcho, policyNoBroader, writeBindings, resumeParams, sandboxMode } from './codex-native-resume.js'
|
|
11
28
|
|
|
12
29
|
// Image extensions codex can attach for VISION via a `localImage` input item.
|
|
13
30
|
const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.svg'])
|
|
14
31
|
|
|
32
|
+
// #6638: cap on cached fileChange diffs (itemId → changes). A turn deletes each on
|
|
33
|
+
// completion and clears the map at turn end, so this only bites a pathological
|
|
34
|
+
// flood of un-completed fileChange items.
|
|
35
|
+
const MAX_PENDING_FILE_CHANGES = 500
|
|
36
|
+
|
|
37
|
+
// #6684: cap the rendered mcpToolCall result text. A connector tool can return an
|
|
38
|
+
// arbitrarily large content array / structuredContent blob; bound it so a single
|
|
39
|
+
// tool_result can't balloon the transcript or the persisted history ring.
|
|
40
|
+
const MAX_MCP_RESULT_CHARS = 10_000
|
|
41
|
+
|
|
42
|
+
// #8710: cap on the ids of codex turns codex itself has ended (see
|
|
43
|
+
// `_noteNativeTurnEnded`). Stragglers only trail the last turn or two.
|
|
44
|
+
const MAX_ENDED_NATIVE_TURN_IDS = 32
|
|
45
|
+
|
|
46
|
+
// #7729/#8710: notifications about the SESSION rather than a turn, and their
|
|
47
|
+
// handlers. One table, so the three places that must agree on the set — with a
|
|
48
|
+
// turn open, with none, and for a turn that has already ended — cannot drift.
|
|
49
|
+
const SESSION_SCOPED_HANDLERS = new Map([
|
|
50
|
+
['thread/tokenUsage/updated', (session, params) => session._onTokenUsage(params)],
|
|
51
|
+
// #7729 — codex moved this thread to another model server-side.
|
|
52
|
+
['model/rerouted', (session, params) => session._onModelRerouted(params)],
|
|
53
|
+
])
|
|
54
|
+
|
|
55
|
+
// #6629: bounded backstop for codex's OWN response-stream reconnect loop. #6623
|
|
56
|
+
// keeps the turn OPEN on a transient `Reconnecting... N/M` error so codex can
|
|
57
|
+
// recover, and the only pre-existing backstop was the 30-min result timeout.
|
|
58
|
+
// But a pending permission prompt CLEARS that timer outright
|
|
59
|
+
// (`_pauseResultTimeoutForPermission` → `_clearResultTimeout`), and it is only
|
|
60
|
+
// re-armed when the NEXT notification arrives (`_resetResultTimeout`, run at the
|
|
61
|
+
// top of `_onNotification`). A codex approval is a server→client REQUEST, not a
|
|
62
|
+
// notification, so it never re-arms anything. So the exact #6629 situation — a
|
|
63
|
+
// shell-escalation prompt pending, then the response stream wedges mid-reconnect
|
|
64
|
+
// with no further notifications — leaves NO active result timeout at all, and the
|
|
65
|
+
// session hangs in "Working..." indefinitely. This watchdog is the independent
|
|
66
|
+
// backstop for that gap: armed on a transient reconnect notification, NOT touched
|
|
67
|
+
// by the permission pause, disarmed the moment codex makes any real forward
|
|
68
|
+
// progress, and — if codex neither recovers nor emits its terminal give-up —
|
|
69
|
+
// fails the turn cleanly (clears busy + sweeps orphan tool_starts) with
|
|
70
|
+
// `error{code:'stream_stall'}` so the client shows its existing retry affordance
|
|
71
|
+
// instead of a stale spinner. 2 min comfortably clears codex's bounded N/5 retry
|
|
72
|
+
// cycle while bounding the worst-case stale state far below the 30-min default.
|
|
73
|
+
const RECONNECT_WATCHDOG_MS = 2 * 60 * 1000
|
|
74
|
+
|
|
75
|
+
// #6856: dedicated HARD CAP on how long a codex turn may stay in the transient-
|
|
76
|
+
// reconnect-SUPPRESSED state opened by #6854. The #6629 watchdog above is a
|
|
77
|
+
// SILENCE detector — it is RE-ARMED on every `Reconnecting...` tick, so it only
|
|
78
|
+
// fires after codex goes QUIET for a full window. That leaves one path still
|
|
79
|
+
// unbounded-but-slow: a codex that emits reconnect notifications FOREVER (never
|
|
80
|
+
// recovering, never silent, never emitting a terminal give-up). Each tick runs
|
|
81
|
+
// `_resetResultTimeout` (pushing the 30-min result timeout out) AND re-arms the
|
|
82
|
+
// silence watchdog — so BOTH backstops keep sliding forward and the turn stays
|
|
83
|
+
// "Working..." far longer than it should. This deadline is armed ONCE the moment
|
|
84
|
+
// the turn first enters suppression and is deliberately NOT re-armed on later
|
|
85
|
+
// reconnect ticks, so a never-ending reconnect storm fails on a fixed bound. It
|
|
86
|
+
// is cleared the instant codex makes genuine forward progress (any non-`error`
|
|
87
|
+
// notification) or the turn ends. 5 min sits above codex's bounded N/5 retry
|
|
88
|
+
// burst AND above the 2-min silence watchdog (so the faster silence path still
|
|
89
|
+
// wins its own case), while capping the worst case 6x below the 30-min result
|
|
90
|
+
// timeout. Override via `reconnectDeadlineMs` opt / CHROXY_CODEX_RECONNECT_DEADLINE_MS,
|
|
91
|
+
// clamped to the window below (#6967) so an override can't break either invariant.
|
|
92
|
+
const RECONNECT_DEADLINE_MS = 5 * 60 * 1000
|
|
93
|
+
|
|
94
|
+
// #6967: the operator override is CLAMPED to the window the #6856 design depends
|
|
95
|
+
// on, not merely checked for finite/positive. Two invariants define that window:
|
|
96
|
+
//
|
|
97
|
+
// FLOOR (exclusive) — the deadline must sit ABOVE the #6629 silence watchdog.
|
|
98
|
+
// Below it, the deadline would beat the silence path to every wedge and the
|
|
99
|
+
// watchdog's "codex went quiet" case could never win on its own; and above
|
|
100
|
+
// codex's bounded N/5 retry burst, a sub-watchdog deadline would kill turns
|
|
101
|
+
// codex was about to recover on its own. `CHROXY_CODEX_RECONNECT_DEADLINE_MS=1000`
|
|
102
|
+
// used to be accepted verbatim and fired near-instantly.
|
|
103
|
+
// CEILING (exclusive) — the deadline must sit BELOW the default result timeout.
|
|
104
|
+
// Its entire purpose is being a strictly-shorter bound than that timeout; at
|
|
105
|
+
// or past it the deadline is dead code (the result timeout fires first).
|
|
106
|
+
//
|
|
107
|
+
// `isOperatorTimeoutInRange` runs first so this shares the finite/positive/<=24h
|
|
108
|
+
// guard rail (and its typo warning) with `resultTimeoutMs` & friends; the window
|
|
109
|
+
// check then narrows it to this timer's own bounds.
|
|
110
|
+
const RECONNECT_DEADLINE_FLOOR_MS = RECONNECT_WATCHDOG_MS
|
|
111
|
+
const RECONNECT_DEADLINE_CEILING_MS = DEFAULT_RESULT_TIMEOUT_MS
|
|
112
|
+
|
|
113
|
+
// #6856/#6967: resolve the reconnect-suppression deadline. The opt wins over the
|
|
114
|
+
// env var, but only when it is itself VALID — an out-of-range opt falls through
|
|
115
|
+
// to the env candidate rather than shadowing it. Anything outside the window
|
|
116
|
+
// above (including a non-finite value: unset env → NaN, garbage → NaN, and
|
|
117
|
+
// 0/negative) falls back to the default. Returns ms.
|
|
118
|
+
function resolveReconnectDeadlineMs(optValue, logger = log) {
|
|
119
|
+
for (const candidate of [optValue, Number(process.env.CHROXY_CODEX_RECONNECT_DEADLINE_MS)]) {
|
|
120
|
+
if (!isOperatorTimeoutInRange(candidate, { name: 'reconnectDeadlineMs', log: logger })) continue
|
|
121
|
+
if (candidate > RECONNECT_DEADLINE_FLOOR_MS && candidate < RECONNECT_DEADLINE_CEILING_MS) return candidate
|
|
122
|
+
// Same defensive shape as isOperatorTimeoutInRange's own warn — a stubbed
|
|
123
|
+
// logger without .warn must not turn a rejected override into a throw.
|
|
124
|
+
if (logger && typeof logger.warn === 'function') {
|
|
125
|
+
logger.warn(
|
|
126
|
+
`reconnectDeadlineMs ${candidate} is outside the supported window ` +
|
|
127
|
+
`(${RECONNECT_DEADLINE_FLOOR_MS}ms < value < ${RECONNECT_DEADLINE_CEILING_MS}ms); ` +
|
|
128
|
+
`falling back to the ${RECONNECT_DEADLINE_MS}ms default`,
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return RECONNECT_DEADLINE_MS
|
|
133
|
+
}
|
|
134
|
+
|
|
15
135
|
const log = createLogger('codex-app-server')
|
|
136
|
+
const CODEX_FIRST_PARTY_API_BASE_URL = 'https://api.openai.com/v1'
|
|
137
|
+
const CODEX_FIRST_PARTY_CHATGPT_BASE_URL = 'https://chatgpt.com/backend-api/'
|
|
138
|
+
const CODEX_FIRST_PARTY_NATIVE_BASE_URL = 'https://chatgpt.com/backend-api/codex'
|
|
16
139
|
|
|
17
140
|
/**
|
|
18
141
|
* Codex session driven through the `codex app-server` JSON-RPC protocol
|
|
@@ -24,9 +147,9 @@ const log = createLogger('codex-app-server')
|
|
|
24
147
|
* notifications onto Chroxy's standard event contract.
|
|
25
148
|
*
|
|
26
149
|
* PHASE 2 (#6605) surfaces codex's APPROVALS through Chroxy's permission
|
|
27
|
-
* pipeline. `approvalPolicy` is
|
|
28
|
-
*
|
|
29
|
-
* or editing a file; the server → client approval RPC
|
|
150
|
+
* pipeline. `approvalPolicy` is `on-request` in EVERY permission mode (#8619:
|
|
151
|
+
* Auto included — `never` would emit no approval RPC at all), so codex asks
|
|
152
|
+
* before running a command or editing a file; the server → client approval RPC
|
|
30
153
|
* (`item/commandExecution/requestApproval` / `item/fileChange/requestApproval`)
|
|
31
154
|
* is routed into a PermissionManager exactly like SdkSession's `canUseTool`
|
|
32
155
|
* bridge — it emits `permission_request`, waits for the user's
|
|
@@ -45,6 +168,44 @@ const log = createLogger('codex-app-server')
|
|
|
45
168
|
* CodexSession's statics so both paths report identically.
|
|
46
169
|
*/
|
|
47
170
|
export class CodexAppServerSession extends BaseSession {
|
|
171
|
+
static canonicalAssistantResponses = true
|
|
172
|
+
|
|
173
|
+
static get customizationDescriptor() { return CODEX_APPSERVER_CUSTOMIZATION }
|
|
174
|
+
static get inputRequiresReady() { return true }
|
|
175
|
+
|
|
176
|
+
get providerBinaryVersion() { return this.codexVersion || 'unknown' }
|
|
177
|
+
// #8609 — WHICH codex this session launched, and a newer bundled one it did not.
|
|
178
|
+
get providerBinaryPath() { return this._spawnedBinary || null }
|
|
179
|
+
get providerNewerBinary() { return this._newerBinary }
|
|
180
|
+
/** #8909 — models the backend refused for this session's client + auth route (read live from the ledger). */
|
|
181
|
+
get providerRejectedModels() {
|
|
182
|
+
return this.codexVersion ? [...rejectedModelsFor(this._clientKey())] : []
|
|
183
|
+
}
|
|
184
|
+
get providerRuntimeCapabilities() {
|
|
185
|
+
return {
|
|
186
|
+
...(this.codexCapabilities || {}),
|
|
187
|
+
nativeResume: this._nativeResumeCapability,
|
|
188
|
+
// This is the exact admission boundary used by sendMessage below. Busy is
|
|
189
|
+
// deliberately excluded: an established busy session accepts follow-ups
|
|
190
|
+
// through BaseSession's existing outgoing queue.
|
|
191
|
+
inputReady: Boolean(this._processReady && this._client),
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
static get nativeResumeDriver() { return NATIVE_RESUME_DRIVER }
|
|
195
|
+
|
|
196
|
+
get nativeResumeState() {
|
|
197
|
+
if (!this._nativeLocator) return this._nativeResumeSaved ? structuredClone(this._nativeResumeSaved) : null
|
|
198
|
+
return {
|
|
199
|
+
...structuredClone(this._nativeLocator),
|
|
200
|
+
permissionMode: this.permissionMode,
|
|
201
|
+
model: { requested: this.model || null, observed: this.bootedModel, provider: this._nativeLocator.model.provider },
|
|
202
|
+
effort: { requested: this._reasoningEffortOverride, observed: this._bootedReasoningEffort },
|
|
203
|
+
settingsVerified: !this._nativeSettingsUnverified,
|
|
204
|
+
skillsPrepended: this._skillsPrepended,
|
|
205
|
+
threadTotals: this._threadTotals ? { ...this._threadTotals } : null,
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
48
209
|
// -- Provider identity (delegated to CodexSession so both paths agree) --
|
|
49
210
|
static get providerName() { return 'codex' }
|
|
50
211
|
static get displayLabel() { return 'OpenAI Codex (app-server)' }
|
|
@@ -59,19 +220,80 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
59
220
|
static getAllowedModels() { return CodexSession.getAllowedModels() }
|
|
60
221
|
static getFallbackModels() { return CodexSession.getFallbackModels() }
|
|
61
222
|
static getModelMetadata(id) { return CodexSession.getModelMetadata(id) }
|
|
223
|
+
// #7731 — delegated for the same reason `refreshModels` is: `getProvider('codex')`
|
|
224
|
+
// resolves THIS class, so a declaration that lives only on CodexSession is
|
|
225
|
+
// invisible to anything that asks the provider registry.
|
|
226
|
+
static get deprecatedSeedModelIds() { return CodexSession.deprecatedSeedModelIds }
|
|
227
|
+
// #7726 — REQUIRED, not decorative. `providers.js` registers
|
|
228
|
+
// `PROVIDERS['codex'] = CodexSession` with the models registry, but
|
|
229
|
+
// `getProvider('codex')` returns THIS class (#6616) and that is what
|
|
230
|
+
// `scheduleProviderModelsRefresh` (ws-history.js) resolves and calls. A
|
|
231
|
+
// `refreshModels` that exists only on CodexSession is therefore never
|
|
232
|
+
// invoked, and the symptom is a picker that looks like flaky discovery
|
|
233
|
+
// rather than a wiring bug.
|
|
234
|
+
static refreshModels(deps) { return CodexSession.refreshModels(deps) }
|
|
235
|
+
// Explicit connection routes are supported only on app-server because its
|
|
236
|
+
// account/read RPC can prove the active auth method before thread/start.
|
|
237
|
+
static get agentConnectionRoutes() { return ['native', 'api'] }
|
|
238
|
+
static get agentConnectionCredentialKey() { return 'OPENAI_API_KEY' }
|
|
62
239
|
|
|
63
240
|
static get capabilities() {
|
|
64
241
|
return {
|
|
65
242
|
// Phase 2 (#6605): approvals are surfaced through the permission pipeline.
|
|
66
243
|
permissions: true,
|
|
67
244
|
inProcessPermissions: true, // requires respondToPermission + respondToQuestion
|
|
245
|
+
// #7825/#8619: Auto is a real mode on this adapter because it does NOT
|
|
246
|
+
// map to `approvalPolicy:'never'` (which emits no requestApproval RPC and
|
|
247
|
+
// so has no pre-execution seam). Every mode keeps `on-request`, so every
|
|
248
|
+
// native approval still reaches the PermissionManager, whose auto-mode
|
|
249
|
+
// path resolves what passes the protected-path / secret-read floor and
|
|
250
|
+
// prompts on a floor hit. Keep native sandbox truth separate: every mode
|
|
251
|
+
// only surfaces approvals the native runtime requests, and sandbox-
|
|
252
|
+
// authorized tools execute without an RPC in ANY mode — so no mode can
|
|
253
|
+
// claim complete Chroxy floor interception, and `permissionFloor` stays
|
|
254
|
+
// false (enforcement `unknown`, never `chroxy`).
|
|
255
|
+
permissionFloor: false,
|
|
256
|
+
autoPermissionMode: true,
|
|
257
|
+
nativeSandbox: true,
|
|
68
258
|
modelSwitch: true,
|
|
69
259
|
permissionModeSwitch: true, // mode drives approvalPolicy + PermissionManager
|
|
70
260
|
planMode: false,
|
|
71
|
-
resume: false, //
|
|
261
|
+
resume: false, // per-session projection becomes true only after verified native resume
|
|
72
262
|
terminal: false,
|
|
73
|
-
|
|
263
|
+
// #7730 — codex has a REAL reasoning control, and this is the driver that
|
|
264
|
+
// can reach it: `model/list` advertises `supportedReasoningEfforts` per
|
|
265
|
+
// model, `thread/start` seeds one through its `config` map, and
|
|
266
|
+
// `turn/start` takes `effort` as a first-class per-turn field. The
|
|
267
|
+
// offered levels come from the ACTIVE MODEL's catalog row, never from a
|
|
268
|
+
// repo-wide list — see `setThinkingLevel` below and the per-model gate in
|
|
269
|
+
// `handlers/settings-handlers.js`.
|
|
270
|
+
thinkingLevel: true,
|
|
271
|
+
// #7725: same as the exec driver — the Claude magic keywords are not
|
|
272
|
+
// scanned for on any codex path. Explicit so #7730's `thinkingLevel`
|
|
273
|
+
// flip cannot drag the keyword highlight along with it: the composer's
|
|
274
|
+
// keyword highlight reads THIS flag, so flipping the one above lights the
|
|
275
|
+
// dropdown and nothing else.
|
|
276
|
+
thinkingKeywords: false,
|
|
277
|
+
// #8700: the level codex reports is already `thinkingLevel` itself (the
|
|
278
|
+
// booted effort when no override is set), so there is no separate report.
|
|
279
|
+
thinkingLevelEffective: false,
|
|
74
280
|
streaming: true,
|
|
281
|
+
// #6888: despite inProcessPermissions:true (this session's
|
|
282
|
+
// respondToPermission delegates to the shared PermissionManager, which DOES
|
|
283
|
+
// compute a deny message via buildDenyMessage(reason)), _routeApproval only
|
|
284
|
+
// reads `result.behavior` when building the RPC response back to codex —
|
|
285
|
+
// `result.message` is never forwarded, so the operator's deny reason is
|
|
286
|
+
// silently dropped. Explicit false (not just omitted) so this doesn't read
|
|
287
|
+
// as an oversight: tracked by #6885 ("Codex deny reason either reaches the
|
|
288
|
+
// model or is documented as unsupported"). Flip to true once that lands.
|
|
289
|
+
denyReason: false,
|
|
290
|
+
// #8301: the provider-neutral turn-input seam. `sendMessage` dispatches when
|
|
291
|
+
// idle, queues via `enqueueOutgoingMessage` when busy (flushed at turn end,
|
|
292
|
+
// cleared by `interrupt()`), and reports admission through
|
|
293
|
+
// `onInputAdmission` — so a daemon-authored line (the CI-completion wake)
|
|
294
|
+
// can travel it as an ordinary user turn. session-wake.js gates on this with
|
|
295
|
+
// strict `=== true`; absent means NOT supported. Never duck-typed.
|
|
296
|
+
daemonTurnInput: true,
|
|
75
297
|
}
|
|
76
298
|
}
|
|
77
299
|
|
|
@@ -82,35 +304,265 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
82
304
|
provider: opts.provider || 'codex',
|
|
83
305
|
model: opts.model || null,
|
|
84
306
|
}))
|
|
307
|
+
this._nativeResumeSaved = opts.nativeResume || null
|
|
308
|
+
this._nativeRestore = opts.isRestore === true || this._nativeResumeSaved !== null
|
|
309
|
+
this._nativeLocator = null
|
|
310
|
+
this._nativeResumeCapability = 'unknown'
|
|
311
|
+
this._nativeSettingsUnverified = false
|
|
312
|
+
this._nativeHostResolver = typeof opts.nativeHostResolver === 'function' ? opts.nativeHostResolver : nativeMachineId
|
|
313
|
+
this._nativeOwnerResolver = typeof opts.nativeOwnerResolver === 'function' ? opts.nativeOwnerResolver : () => process.getuid?.()
|
|
314
|
+
this._nativeResumePersist = typeof opts.nativeResumePersist === 'function' ? opts.nativeResumePersist : null
|
|
315
|
+
this._connectionAuthRoute = opts.connectionAuthRoute || null
|
|
316
|
+
this._connectionChildEnv = opts.connectionChildEnv && typeof opts.connectionChildEnv === 'object'
|
|
317
|
+
? { ...opts.connectionChildEnv }
|
|
318
|
+
: null
|
|
85
319
|
this._client = null
|
|
86
320
|
this._threadId = null
|
|
321
|
+
// #7730 — the reasoning effort, split in two on PURPOSE.
|
|
322
|
+
//
|
|
323
|
+
// `_reasoningEffortOverride` is the operator's explicit choice (a
|
|
324
|
+
// `set_thinking_level`, null until one arrives) and is the ONLY value the
|
|
325
|
+
// param builders send: seeding `thread/start` with codex's own echoed
|
|
326
|
+
// effort, or replaying it on every `turn/start`, would pin the thread to a
|
|
327
|
+
// value codex chose for itself — the same trap `_buildTurnParams` documents
|
|
328
|
+
// for `model`. `_bootedReasoningEffort` is what codex reported at
|
|
329
|
+
// `thread/start` (from the operator's `~/.codex/config.toml`), and exists
|
|
330
|
+
// so the control can SHOW the session's real effort before anyone touches
|
|
331
|
+
// it. `get thinkingLevel` composes the two in that precedence.
|
|
332
|
+
this._reasoningEffortOverride = null
|
|
333
|
+
this._bootedReasoningEffort = null
|
|
334
|
+
// #7729 — injectable JSON-RPC client factory (subclass-local opt, read off
|
|
335
|
+
// `opts` directly; NOT a BaseSession opt). Production leaves it null and
|
|
336
|
+
// start() builds a real CodexAppServerClient; a test supplies a stub so
|
|
337
|
+
// start() can be executed rather than reproduced.
|
|
338
|
+
this._clientFactory = typeof opts.clientFactory === 'function' ? opts.clientFactory : null
|
|
339
|
+
this._binaryFailureLabeler = typeof opts.binaryFailureLabeler === 'function'
|
|
340
|
+
? opts.binaryFailureLabeler
|
|
341
|
+
: labelBinarySpawnFailure
|
|
342
|
+
// #7724 — filled from the `initialize` handshake in start(). Null / all-UNKNOWN
|
|
343
|
+
// before the handshake AND after an unparseable userAgent: a cannot-check must
|
|
344
|
+
// not read as a no, so callers probe (probeMethod) instead of disabling.
|
|
345
|
+
this.codexUserAgent = null
|
|
346
|
+
this.codexVersion = null
|
|
347
|
+
this.codexCapabilities = capabilitiesForVersion(null)
|
|
348
|
+
// #8609 — a newer client bundled in a desktop app ({path, version}), found
|
|
349
|
+
// after the handshake; null when none / not newer. `bundledClientFinder` is a
|
|
350
|
+
// test seam for the app-bundle probe.
|
|
351
|
+
this._newerBinary = null
|
|
352
|
+
// #8609 — verified auth route ('native' | 'api') once the handshake has
|
|
353
|
+
// checked it; null when the connection pinned none. The backend's model
|
|
354
|
+
// rejection is route-dependent, so the rejection ledger keys on it.
|
|
355
|
+
this._observedAuthRoute = null
|
|
356
|
+
// #8609 — a start-time substitute for a rejected catalog default. Deliberately
|
|
357
|
+
// NOT `this.model`: that is the operator's explicit choice and is persisted.
|
|
358
|
+
this._defaultFallbackModel = null
|
|
359
|
+
this._findBundledClient = typeof opts.bundledClientFinder === 'function'
|
|
360
|
+
? opts.bundledClientFinder : findNewestBundledCodexClient
|
|
87
361
|
this._activeTurn = null // { messageId, turnId, didStreamStart }
|
|
362
|
+
// #8710 — codex turns codex has ended (`turn/completed`, or a terminal
|
|
363
|
+
// `error`); a notification still naming one is a straggler, not a live turn.
|
|
364
|
+
this._endedNativeTurnIds = new Set()
|
|
365
|
+
// #7769 — per-TURN, and reset in sendMessage(). It used to live for the
|
|
366
|
+
// lifetime of the session, so a turn that carried no
|
|
367
|
+
// `thread/tokenUsage/updated` re-reported the PREVIOUS turn's numbers and
|
|
368
|
+
// session-manager's `_trackUsage` accumulated them a second time.
|
|
88
369
|
this._lastUsage = null
|
|
370
|
+
// #7794 — per-turn occupancy snapshot built from the same notification.
|
|
371
|
+
this._lastOccupancy = null
|
|
372
|
+
// #7773 — codex's `tokenUsage.total` is CUMULATIVE over the thread (proven
|
|
373
|
+
// live: see _turnUsageBreakdown). These two make the per-turn figure a
|
|
374
|
+
// DELTA of it: `_threadTotals` tracks the newest cumulative breakdown seen,
|
|
375
|
+
// `_turnBaselineTotals` freezes it at turn start.
|
|
376
|
+
this._threadTotals = null
|
|
377
|
+
this._turnBaselineTotals = null
|
|
89
378
|
this._skillsPrepended = false // #6606 — inject the skills prefix once, on turn 1
|
|
90
379
|
this._turnAbort = null // per-turn AbortController — cancels pending approvals
|
|
380
|
+
this._reconnectWatchdog = null // #6629 — bounded backstop for a wedged reconnect
|
|
381
|
+
this._reconnectDeadline = null // #6856 — one-shot hard cap on total reconnect-suppression time
|
|
382
|
+
// #6856/#6967 — configurable reconnect-suppression deadline (opt / env /
|
|
383
|
+
// default), clamped to the window between the #6629 silence watchdog and the
|
|
384
|
+
// default result timeout. The out-of-range warning goes to the MODULE logger,
|
|
385
|
+
// not the usual `this._log || log`: `this._log` is the thread-scoped logger
|
|
386
|
+
// built in start() (it needs a thread id, which does not exist yet), so at
|
|
387
|
+
// construction that expression is unconditionally `log` and writing it would
|
|
388
|
+
// only imply a session scoping this warn can never have.
|
|
389
|
+
this._reconnectDeadlineMs = resolveReconnectDeadlineMs(opts.reconnectDeadlineMs)
|
|
390
|
+
// #6856 — injectable timer seam (defaults to node globals) so the reconnect
|
|
391
|
+
// deadline is unit-testable without wall-clock waits, mirroring the #6908/#6911
|
|
392
|
+
// byok-mcp-config `setTimer`/`clearTimer` pattern. Only the deadline routes
|
|
393
|
+
// through this; the #6629 silence watchdog keeps using the globals directly.
|
|
394
|
+
this._setTimer = typeof opts.setTimer === 'function' ? opts.setTimer : setTimeout
|
|
395
|
+
this._clearTimer = typeof opts.clearTimer === 'function' ? opts.clearTimer : clearTimeout
|
|
396
|
+
// #6638: per-session sandbox override (create_session `codexSandbox`) — wins
|
|
397
|
+
// over CHROXY_CODEX_SANDBOX / the default. Applied at thread start.
|
|
398
|
+
this._codexSandbox = opts.codexSandbox || null
|
|
399
|
+
// #6929 review — the sandbox actually resolved+applied to `thread/start`
|
|
400
|
+
// (set in start(), see below). null until then; getCodexSandbox() falls
|
|
401
|
+
// back to a live resolve for that (normally unreachable) pre-start window.
|
|
402
|
+
this._resolvedCodexSandbox = null
|
|
403
|
+
// #6638: fileChange item.changes cached by itemId, so a fileChange approval
|
|
404
|
+
// (whose params carry NO diff) can surface WHAT will change. Cleared per turn.
|
|
405
|
+
this._pendingFileChanges = new Map()
|
|
91
406
|
this._attachDir = null // #6609 — lazily-created temp dir for materialized attachments
|
|
92
407
|
|
|
93
408
|
// #6605 Phase 2 — surface codex approvals through the same PermissionManager
|
|
94
409
|
// bridge SdkSession uses. wirePermissionManager re-emits permission_request /
|
|
95
410
|
// permission_resolved / user_question on THIS session and back-links
|
|
96
411
|
// _pendingPermissions/_lastPermissionData for ws-permissions.js.
|
|
97
|
-
|
|
412
|
+
// #6794 — pass cwd so the protected-path floor can resolve relative tool
|
|
413
|
+
// targets (.git/.claude/.env…) against this session's working directory.
|
|
414
|
+
// #6771 — pass the durable rule store (persistent per-project allow-always).
|
|
415
|
+
this._permissions = new PermissionManager({ log, cwd: this.cwd, ruleStore: this._permissionRuleStore })
|
|
98
416
|
wirePermissionManager(this, this._permissions, {
|
|
99
417
|
onRequest: () => this._pauseResultTimeoutForPermission(),
|
|
100
418
|
onResolved: () => this._resumeResultTimeoutForPermission(),
|
|
101
419
|
})
|
|
102
420
|
}
|
|
103
421
|
|
|
104
|
-
|
|
422
|
+
/**
|
|
423
|
+
* #6901: the ACTIVE/resolved sandbox mode this thread runs under — the exact
|
|
424
|
+
* value passed to `thread/start` (see start()), which STORES the resolved
|
|
425
|
+
* value on `this._resolvedCodexSandbox` at that moment. #6929 review: this
|
|
426
|
+
* returns the stored value instead of re-resolving `CHROXY_CODEX_SANDBOX` on
|
|
427
|
+
* every call, so a later env change can't make the display drift from what
|
|
428
|
+
* this already-running thread actually got (Codex applies the sandbox once
|
|
429
|
+
* at thread start; it cannot change mid-thread). Falls back to a live
|
|
430
|
+
* resolve only in the window before start() has run (session constructed but
|
|
431
|
+
* not yet started). Surfaced by `SessionManager.listSessions()` as
|
|
432
|
+
* `SessionInfo.codexSandbox` so a client can DISPLAY the current sandbox for
|
|
433
|
+
* a running codex session. Display-only: changing it needs a new session.
|
|
434
|
+
* @returns {string} one of CODEX_SANDBOX_MODES
|
|
435
|
+
*/
|
|
436
|
+
getCodexSandbox() {
|
|
437
|
+
return this._resolvedCodexSandbox || resolveCodexSandbox(this._codexSandbox)
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
_buildChildEnv() {
|
|
441
|
+
return this._connectionChildEnv ? { ...this._connectionChildEnv } : buildSpawnEnv('codex')
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
_buildClientArgs() {
|
|
445
|
+
if (!this._connectionAuthRoute) return ['app-server']
|
|
446
|
+
if (!['native', 'api'].includes(this._connectionAuthRoute)) {
|
|
447
|
+
const err = new Error('Unsupported Codex connection authentication route. Select native or API authentication.')
|
|
448
|
+
err.code = 'CODEX_AUTH_ROUTE_UNSUPPORTED'
|
|
449
|
+
throw err
|
|
450
|
+
}
|
|
451
|
+
// #7852: openai_base_url overrides Codex's auth-dependent inference URL.
|
|
452
|
+
// Pin the ChatGPT backend for native login and the API backend for API keys;
|
|
453
|
+
// using the API URL for both sends subscription tokens to the wrong service.
|
|
454
|
+
// Keep explicit overrides so user config cannot redirect either connection.
|
|
455
|
+
const inferenceBaseUrl = this._connectionAuthRoute === 'native'
|
|
456
|
+
? CODEX_FIRST_PARTY_NATIVE_BASE_URL
|
|
457
|
+
: CODEX_FIRST_PARTY_API_BASE_URL
|
|
458
|
+
return [
|
|
459
|
+
'app-server',
|
|
460
|
+
'-c', 'model_provider="openai"',
|
|
461
|
+
'-c', `openai_base_url="${inferenceBaseUrl}"`,
|
|
462
|
+
'-c', `chatgpt_base_url="${CODEX_FIRST_PARTY_CHATGPT_BASE_URL}"`,
|
|
463
|
+
]
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
async _verifyConnectionAuthRoute() {
|
|
467
|
+
if (!this._connectionAuthRoute) return
|
|
468
|
+
const configResult = await this._client.request('config/read', { cwd: this.cwd, includeLayers: false })
|
|
469
|
+
if (configResult?.config?.model_provider !== 'openai') {
|
|
470
|
+
const err = new Error('Codex could not verify the built-in OpenAI provider for this explicit connection.')
|
|
471
|
+
err.code = 'CODEX_PROVIDER_ROUTE_UNAVAILABLE'
|
|
472
|
+
throw err
|
|
473
|
+
}
|
|
474
|
+
const result = await this._client.request('account/read', { refreshToken: false })
|
|
475
|
+
const actual = result?.account?.type === 'chatgpt'
|
|
476
|
+
? 'native'
|
|
477
|
+
: result?.account?.type === 'apiKey'
|
|
478
|
+
? 'api'
|
|
479
|
+
: 'none'
|
|
480
|
+
if (actual !== this._connectionAuthRoute) {
|
|
481
|
+
const err = new Error(
|
|
482
|
+
this._connectionAuthRoute === 'native'
|
|
483
|
+
? 'Codex native login is unavailable for this connection. Run `codex login`; API credentials are not used as a fallback.'
|
|
484
|
+
: 'Codex API authentication is unavailable for this connection. Configure OPENAI_API_KEY; native login is not used as a fallback.'
|
|
485
|
+
)
|
|
486
|
+
err.code = this._connectionAuthRoute === 'native'
|
|
487
|
+
? 'NATIVE_LOGIN_REQUIRED'
|
|
488
|
+
: 'API_AUTH_ROUTE_UNAVAILABLE'
|
|
489
|
+
throw err
|
|
490
|
+
}
|
|
491
|
+
return actual
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
_verifyStartedConnectionRoute(started, actualAuthRoute) {
|
|
495
|
+
if (!this._connectionAuthRoute) return
|
|
496
|
+
if (started?.modelProvider !== 'openai') {
|
|
497
|
+
const err = new Error('Codex started this thread with a model provider outside the explicit OpenAI connection route.')
|
|
498
|
+
err.code = 'CODEX_PROVIDER_ROUTE_MISMATCH'
|
|
499
|
+
throw err
|
|
500
|
+
}
|
|
501
|
+
if (!this.agentConnection) return
|
|
502
|
+
this.agentConnection.authentication = {
|
|
503
|
+
...this.agentConnection.authentication,
|
|
504
|
+
observed: actualAuthRoute === 'native' ? 'native' : 'api-key',
|
|
505
|
+
}
|
|
506
|
+
this.agentConnection.entitlement = actualAuthRoute === 'api'
|
|
507
|
+
? { route: 'api', status: 'available' }
|
|
508
|
+
: { route: 'subscription', status: 'unknown' }
|
|
509
|
+
this.agentConnection.readiness = {
|
|
510
|
+
state: 'ready',
|
|
511
|
+
reasonCode: null,
|
|
512
|
+
message: 'The selected authentication and first-party provider route was verified by Codex.',
|
|
513
|
+
recoveryAction: null,
|
|
514
|
+
}
|
|
515
|
+
this.agentConnection.provenance = {
|
|
516
|
+
...this.agentConnection.provenance,
|
|
517
|
+
observedAt: new Date().toISOString(),
|
|
518
|
+
}
|
|
519
|
+
}
|
|
105
520
|
|
|
106
521
|
// ------------------------------------------------------------------
|
|
107
522
|
// Lifecycle
|
|
108
523
|
// ------------------------------------------------------------------
|
|
109
524
|
|
|
110
525
|
async start() {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
526
|
+
try { return await this._startAppServer() }
|
|
527
|
+
catch (err) {
|
|
528
|
+
this._processReady = false
|
|
529
|
+
this._nativeResumeCapability = false
|
|
530
|
+
this._nativeLocator = null // retain original recipe if restore was rejected
|
|
531
|
+
try { this._client?.kill() } catch { /* already stopped */ }
|
|
532
|
+
if (this._nativeRestore && !String(err?.code || '').startsWith('CODEX_NATIVE_')) {
|
|
533
|
+
const failed = nativeRestoreError('REJECTED', 'the original native thread could not be resumed; retry it or explicitly create a new session')
|
|
534
|
+
failed.cause = err
|
|
535
|
+
throw failed
|
|
536
|
+
}
|
|
537
|
+
throw err
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
async _startAppServer() {
|
|
542
|
+
if (this._nativeRestore) validateLocator(this._nativeResumeSaved, this.permissionMode)
|
|
543
|
+
// #6929 review — resolve AND STORE here, the actual `thread/start` apply
|
|
544
|
+
// site, so getCodexSandbox() can report what this thread really got instead
|
|
545
|
+
// of re-resolving the env (and potentially drifting from it) on every call.
|
|
546
|
+
this._resolvedCodexSandbox = resolveCodexSandbox(this._codexSandbox)
|
|
547
|
+
const sandbox = this._resolvedCodexSandbox
|
|
548
|
+
// Capture the EXACT binary the client will spawn so the spawn-time backstop
|
|
549
|
+
// (#6708) verifies that path — in start()'s catch AND later in
|
|
550
|
+
// _onClientExit — rather than a fresh re-resolve.
|
|
551
|
+
//
|
|
552
|
+
// #8038: routed through the shared binary gate instead of the bare static
|
|
553
|
+
// read. app-server spawns exactly once per session (at `start()`), but that
|
|
554
|
+
// one spawn was STILL an unverified fresh resolve — `this._spawnPreflight`
|
|
555
|
+
// (wired by SessionManager whenever create-time preflight ran) was already
|
|
556
|
+
// sitting on this instance unused. A refusal here throws BEFORE
|
|
557
|
+
// `_createClient`, so no child process is spawned; SessionManager's
|
|
558
|
+
// `_handleAsyncStartFailure` handles the rejection the same way it handles
|
|
559
|
+
// any other start() failure (fresh → session_create_failed with the gate's
|
|
560
|
+
// code; restore → parked).
|
|
561
|
+
const attemptedBinary = this._gatedSpawnBinary('codex')
|
|
562
|
+
this._spawnedBinary = attemptedBinary
|
|
563
|
+
this._client = this._createClient({
|
|
564
|
+
bin: attemptedBinary,
|
|
565
|
+
args: this._buildClientArgs(),
|
|
114
566
|
cwd: this.cwd,
|
|
115
567
|
env: this._buildChildEnv(),
|
|
116
568
|
logger: log,
|
|
@@ -119,47 +571,600 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
119
571
|
this._client.on('serverRequest', (r) => this._onServerRequest(r))
|
|
120
572
|
this._client.on('exit', (e) => this._onClientExit(e))
|
|
121
573
|
|
|
122
|
-
|
|
123
|
-
|
|
574
|
+
let init
|
|
575
|
+
try {
|
|
576
|
+
// #7724 — the handshake result is the ONLY in-band version signal, and it
|
|
577
|
+
// reports the binary serving THIS session (not whatever is on PATH). It
|
|
578
|
+
// gates FEATURES only: nothing below refuses to start, and an unparseable
|
|
579
|
+
// userAgent leaves every gate UNKNOWN so callers probe rather than assume.
|
|
580
|
+
init = await this._client.initialize({ name: 'chroxy', version: '1' })
|
|
581
|
+
} catch (err) {
|
|
582
|
+
// #6708 — the app-server child is spawned inside initialize(); a missing/
|
|
583
|
+
// quarantined codex binary surfaces here as an initialize rejection (the
|
|
584
|
+
// child errors and _onError rejects the pending request). Re-verify so the
|
|
585
|
+
// session_create_failed names the quarantine + fix rather than an opaque
|
|
586
|
+
// "codex app-server exited". Only relabels when the binary is actually
|
|
587
|
+
// unhealthy; otherwise the original protocol error rethrows unchanged.
|
|
588
|
+
const labeled = this._binaryFailureLabeler({
|
|
589
|
+
attemptedPath: err?.path || this._spawnedBinary,
|
|
590
|
+
binary: 'codex',
|
|
591
|
+
prefix: 'Failed to start codex app-server',
|
|
592
|
+
})
|
|
593
|
+
if (labeled) throw new Error(labeled)
|
|
594
|
+
throw err
|
|
595
|
+
}
|
|
596
|
+
this._captureHandshake(init)
|
|
597
|
+
this._noteNewerBundledClient()
|
|
598
|
+
const actualAuthRoute = await this._verifyConnectionAuthRoute()
|
|
599
|
+
this._observedAuthRoute = actualAuthRoute || null
|
|
600
|
+
if (!this._nativeRestore) this._avoidRejectedDefaultModel()
|
|
601
|
+
if (this._nativeRestore) this._verifyNativeOwnership(init)
|
|
602
|
+
const started = await this._client.request(
|
|
603
|
+
this._nativeRestore ? 'thread/resume' : 'thread/start',
|
|
604
|
+
this._nativeRestore ? this._buildResumeParams() : this._buildThreadParams(sandbox),
|
|
605
|
+
)
|
|
606
|
+
if (this._nativeRestore) this._verifyNativeResume(started, init)
|
|
607
|
+
if (typeof started?.thread?.id !== 'string' || !started.thread.id) throw nativeRestoreError('THREAD_INVALID', 'native thread identity was missing')
|
|
608
|
+
this._verifyStartedConnectionRoute(started, actualAuthRoute)
|
|
609
|
+
this._threadId = started?.thread?.id || null
|
|
610
|
+
// #7729 — the `thread/start` RESPONSE echoes the model codex actually
|
|
611
|
+
// resolved (from ~/.codex/config.toml when chroxy sent none). Capture it
|
|
612
|
+
// BEFORE `ready` so the emitted payload — and every later session_info
|
|
613
|
+
// render — names a real model instead of the null this session is
|
|
614
|
+
// constructed with by design.
|
|
615
|
+
this._captureBootedModel(started)
|
|
616
|
+
// #7730 — and the effort it resolved, from the same response. Also BEFORE
|
|
617
|
+
// `ready`, so the very first `thinking_level_changed` replay names the
|
|
618
|
+
// operator's real `~/.codex/config.toml` setting rather than nothing.
|
|
619
|
+
this._captureBootedReasoningEffort(started)
|
|
620
|
+
if (!this._nativeRestore) this._captureNativeStart(started, init)
|
|
621
|
+
if (this._nativeLocator) {
|
|
622
|
+
this.resumeSessionId = this._threadId
|
|
623
|
+
if (this._nativeRestore && !this._nativeResumePersist) throw nativeRestoreError('PERSIST_UNAVAILABLE', 'durable native state writer is unavailable')
|
|
624
|
+
if (this._nativeResumePersist && this._nativeResumePersist() !== true) {
|
|
625
|
+
throw nativeRestoreError('PERSIST_FAILED', 'native identity could not be saved before readiness')
|
|
626
|
+
}
|
|
627
|
+
if (this._nativeRestore) this._nativeResumeCapability = true
|
|
628
|
+
}
|
|
629
|
+
this._log = loggerForSession('codex-app-server', this._threadId || 'no-thread')
|
|
630
|
+
this._processReady = true
|
|
631
|
+
;(this._log || log).info(`codex app-server ready (thread=${this._threadId} sandbox=${this.getCodexSandbox()})`)
|
|
632
|
+
// #7726 — ask THIS binary for its own model roster, on the client that is
|
|
633
|
+
// already up. Fire-and-forget on purpose: a wedged or old binary must not
|
|
634
|
+
// delay `ready`, and every failure path inside leaves the previous catalog
|
|
635
|
+
// untouched. Deliberately AFTER thread/start, so a catalog probe can never
|
|
636
|
+
// be what breaks session creation.
|
|
637
|
+
this._refreshModelCatalog()
|
|
638
|
+
// #7729 — report the model this thread is REALLY running. `this.model` is
|
|
639
|
+
// the operator's explicit override and is null whenever codex was left to
|
|
640
|
+
// pick; `bootedModel` is what it picked. Same precedence as
|
|
641
|
+
// session-manager's session_info render, so the two cannot disagree.
|
|
642
|
+
this.emit('ready', { model: this._effectiveModelId() })
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
_buildResumeParams() { return resumeParams(this._nativeResumeSaved) }
|
|
646
|
+
|
|
647
|
+
_nativeOwnership(init) {
|
|
648
|
+
return bindNativeOwnership({ cwd: this.cwd, codexHome: init?.codexHome, machineId: this._nativeHostResolver(), ownerId: this._nativeOwnerResolver() })
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
_verifyNativeOwnership(init) {
|
|
652
|
+
const saved = this._nativeResumeSaved
|
|
653
|
+
if (this.codexVersion !== NATIVE_RESUME_VERSION) throw nativeRestoreError('VERSION_UNVERIFIED', 'this serving binary has not verified the saved resume contract')
|
|
654
|
+
const current = this._nativeOwnership(init)
|
|
655
|
+
for (const key of ['hostBinding', 'storeBinding', 'codexHome', 'cwdBinding', 'cwd']) {
|
|
656
|
+
if (current[key] !== saved[key]) throw nativeRestoreError('OWNERSHIP_MISMATCH', 'the native store, machine owner or working directory has moved')
|
|
657
|
+
}
|
|
658
|
+
const writes = writeBindings(saved.sandboxPolicy, current.cwd, this._buildChildEnv())
|
|
659
|
+
if (JSON.stringify(writes) !== JSON.stringify(saved.writeBindings)) throw nativeRestoreError('WRITE_OWNERSHIP_MISMATCH', 'saved writable roots or temporary directory ownership has changed')
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
_verifyNativeResume(started, init) {
|
|
663
|
+
this._verifyNativeOwnership(init)
|
|
664
|
+
const echo = validateEcho(started), saved = this._nativeResumeSaved
|
|
665
|
+
if (echo.thread.id !== saved.threadId) throw nativeRestoreError('THREAD_MISMATCH', 'native runtime returned a different thread identity')
|
|
666
|
+
const echoedOwnership = bindNativeOwnership({ cwd: echo.cwd, codexHome: init.codexHome, machineId: this._nativeHostResolver(), ownerId: this._nativeOwnerResolver() })
|
|
667
|
+
if (echoedOwnership.cwdBinding !== saved.cwdBinding) throw nativeRestoreError('CWD_MISMATCH', 'native runtime returned a different working directory')
|
|
668
|
+
if (!policyNoBroader(echo.sandbox, saved.sandboxPolicy, saved.cwd)) throw nativeRestoreError('POLICY_BROADER', 'native sandbox rights are broader or unknown')
|
|
669
|
+
if (echo.model !== saved.model.observed || echo.modelProvider !== saved.model.provider || echo.reasoningEffort !== saved.effort.observed) throw nativeRestoreError('SETTINGS_MISMATCH', 'native model or reasoning effort changed while restoring')
|
|
670
|
+
this.model = saved.model.requested
|
|
671
|
+
this._reasoningEffortOverride = saved.effort.requested
|
|
672
|
+
this._skillsPrepended = saved.skillsPrepended
|
|
673
|
+
this._threadTotals = saved.threadTotals ? { ...saved.threadTotals } : null
|
|
674
|
+
this._nativeUsageBaselineUnknown = saved.threadTotals === null
|
|
675
|
+
this._resolvedCodexSandbox = sandboxMode(echo.sandbox)
|
|
676
|
+
this._nativeLocator = {
|
|
677
|
+
...structuredClone(saved), sandboxMode: sandboxMode(echo.sandbox), sandboxPolicy: structuredClone(echo.sandbox),
|
|
678
|
+
writeBindings: writeBindings(echo.sandbox, saved.cwd, this._buildChildEnv()), binaryVersion: this.codexVersion,
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
_captureNativeStart(started, init) {
|
|
683
|
+
try {
|
|
684
|
+
if (this.codexVersion !== NATIVE_RESUME_VERSION) throw nativeRestoreError('VERSION_UNVERIFIED', 'native restart continuity is not verified for this binary version')
|
|
685
|
+
const echo = validateEcho(started), ownership = this._nativeOwnership(init)
|
|
686
|
+
const actualCwd = bindNativeOwnership({ cwd: echo.cwd, codexHome: init.codexHome, machineId: this._nativeHostResolver(), ownerId: this._nativeOwnerResolver() })
|
|
687
|
+
if (actualCwd.cwdBinding !== ownership.cwdBinding || sandboxMode(echo.sandbox) !== this._resolvedCodexSandbox) throw nativeRestoreError('POLICY_MISMATCH', 'native cwd or sandbox differs from the requested boundary')
|
|
688
|
+
this._nativeLocator = {
|
|
689
|
+
schemaVersion: 1, provider: 'codex', driver: NATIVE_RESUME_DRIVER, binaryVersion: this.codexVersion,
|
|
690
|
+
threadId: echo.thread.id, ...ownership,
|
|
691
|
+
sandboxMode: sandboxMode(echo.sandbox), sandboxPolicy: structuredClone(echo.sandbox),
|
|
692
|
+
writeBindings: writeBindings(echo.sandbox, ownership.cwd, this._buildChildEnv()),
|
|
693
|
+
approvalPolicy: echo.approvalPolicy, approvalsReviewer: echo.approvalsReviewer, permissionMode: this.permissionMode,
|
|
694
|
+
model: { requested: this.model || null, observed: echo.model, provider: echo.modelProvider },
|
|
695
|
+
effort: { requested: this._reasoningEffortOverride, observed: echo.reasoningEffort },
|
|
696
|
+
skillsPrepended: false, threadTotals: null, settingsVerified: true,
|
|
697
|
+
}
|
|
698
|
+
} catch (err) {
|
|
699
|
+
this._nativeResumeCapability = 'unknown'
|
|
700
|
+
;(this._log || log).warn(`Codex native restart continuity unavailable (${err.code || 'CODEX_NATIVE_UNVERIFIED'}): ${err.message}`)
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
// A successful turn admits explicit choices, but it is not a settings echo.
|
|
705
|
+
// Observe native metadata; an unavailable echo leaves restart visibly blocked.
|
|
706
|
+
async _observeNativeSettings() {
|
|
707
|
+
if (!this._nativeLocator || !this._nativeSettingsUnverified) return
|
|
708
|
+
try {
|
|
709
|
+
const observedCounter = this._messageCounter
|
|
710
|
+
const response = await this._client.request('thread/read', { threadId: this._threadId, includeTurns: false })
|
|
711
|
+
if (observedCounter !== this._messageCounter || this._isBusy) return
|
|
712
|
+
const thread = response?.thread
|
|
713
|
+
if (thread?.id !== this._threadId || !this._readModelId(thread.model) || !Object.hasOwn(thread, 'reasoningEffort')) return
|
|
714
|
+
if (!(thread.reasoningEffort === null || this._readModelId(thread.reasoningEffort))) return
|
|
715
|
+
this.bootedModel = thread.model
|
|
716
|
+
this._bootedReasoningEffort = thread.reasoningEffort
|
|
717
|
+
this._nativeSettingsUnverified = false
|
|
718
|
+
this._nativeResumePersist?.()
|
|
719
|
+
} catch { /* retain unverified state rather than invent a settings echo */ }
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* #7729 — the injectable client seam. Production builds a real
|
|
724
|
+
* `CodexAppServerClient` (which spawns `codex app-server`); a test hands in a
|
|
725
|
+
* stub so `start()` itself — the param builders, the handshake capture, the
|
|
726
|
+
* model echo — is under test instead of being REPRODUCED by a test that
|
|
727
|
+
* cannot go red for start()'s own bugs. Mirrors the `spawnFn` (#7726) and
|
|
728
|
+
* `setTimer` (#6856) injectable-seam pattern already in this file.
|
|
729
|
+
*/
|
|
730
|
+
_createClient(config) {
|
|
731
|
+
return this._clientFactory ? this._clientFactory(config) : new CodexAppServerClient(config)
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/**
|
|
735
|
+
* #7729 — the `thread/start` params. Extracted VERBATIM from the inline
|
|
736
|
+
* object start() used to build; the keys, their order and the conditional
|
|
737
|
+
* `model` spread are unchanged. Extraction is what gives the effort param
|
|
738
|
+
* (#7730) and the resume branch (CDX-9) one place to land, and what lets a
|
|
739
|
+
* test assert the shape without re-typing it.
|
|
740
|
+
*
|
|
741
|
+
* @param {string} sandbox the RESOLVED sandbox mode (see start()).
|
|
742
|
+
*/
|
|
743
|
+
_buildThreadParams(sandbox) {
|
|
744
|
+
return {
|
|
124
745
|
approvalPolicy: this._approvalPolicy(), // #6605 P2 — derived from permission mode
|
|
125
746
|
cwd: this.cwd,
|
|
126
747
|
sandbox,
|
|
748
|
+
...((this.model || this._defaultFallbackModel) ? { model: this.model || this._defaultFallbackModel } : {}),
|
|
749
|
+
// #7730 — effort is seeded ASYMMETRICALLY, and this half is the one that
|
|
750
|
+
// is easy to get wrong. `thread/start` has NO top-level effort field:
|
|
751
|
+
// the value goes through the generic `config` map as
|
|
752
|
+
// `model_reasoning_effort`, exactly as `~/.codex/config.toml` spells it
|
|
753
|
+
// (verified live on codex-cli 0.154.0 — passing
|
|
754
|
+
// `{config: {model_reasoning_effort: 'xhigh'}}` made the response echo
|
|
755
|
+
// `reasoningEffort: 'xhigh'`). A top-level `effort` key here is silently
|
|
756
|
+
// IGNORED, which is why the omission has to be deliberate rather than
|
|
757
|
+
// symmetrical with `_buildTurnParams` below.
|
|
758
|
+
//
|
|
759
|
+
// Omitted entirely when the operator has chosen nothing, so codex
|
|
760
|
+
// resolves its own default from the config file and the echo tells us
|
|
761
|
+
// what it picked.
|
|
762
|
+
...(this._reasoningEffortOverride ? { config: { model_reasoning_effort: this._reasoningEffortOverride } } : {}),
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* #7729 — the `turn/start` params, extracted verbatim from sendMessage()'s
|
|
768
|
+
* inline object (same keys, same order, same conditional spread).
|
|
769
|
+
*
|
|
770
|
+
* #6608 — the CURRENT model rides every turn (turn/start accepts it) so a
|
|
771
|
+
* mid-session set_model actually takes effect, matching the exec path's
|
|
772
|
+
* per-turn model. thread/start seeds the initial model; this tracks changes.
|
|
773
|
+
* Deliberately `this.model`, NOT `_effectiveModelId()`: echoing codex's own
|
|
774
|
+
* resolved model back at it on every turn would pin a thread that codex
|
|
775
|
+
* re-routed (`model/rerouted`) to the model it moved AWAY from.
|
|
776
|
+
*
|
|
777
|
+
* @param {Array<Object>} input the codex UserInput items (see _buildTurnInput).
|
|
778
|
+
*/
|
|
779
|
+
_buildTurnParams(input) {
|
|
780
|
+
return {
|
|
781
|
+
threadId: this._threadId,
|
|
782
|
+
approvalPolicy: this._approvalPolicy(), // #6605 P2 — per-turn, tracks mode changes
|
|
783
|
+
input,
|
|
127
784
|
...(this.model ? { model: this.model } : {}),
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
785
|
+
// #7730 — the OTHER half of the asymmetry: on `turn/start`, `effort` IS a
|
|
786
|
+
// first-class param ("this turn and subsequent turns"). It rides EVERY
|
|
787
|
+
// turn, not just the one after a `set_thinking_level`, for the same
|
|
788
|
+
// reason `model` does (#6608): a mid-session change must take effect, and
|
|
789
|
+
// a thread that was seeded at start must not silently drift back to the
|
|
790
|
+
// binary's default on some later turn. `turn/settings/update` (change the
|
|
791
|
+
// effort on a RUNNING turn) exists only at codex >= 0.154.0 and is
|
|
792
|
+
// deliberately not used — "the next turn carries the new effort" needs no
|
|
793
|
+
// version gate, and a capability probe here would buy a one-turn latency
|
|
794
|
+
// difference at the price of a gate that can be wrong.
|
|
795
|
+
...(this._reasoningEffortOverride ? { effort: this._reasoningEffortOverride } : {}),
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* #7729 — the model id this session should be DESCRIBED by: the operator's
|
|
801
|
+
* explicit override when there is one, else the model codex resolved at
|
|
802
|
+
* `thread/start` (or re-routed to mid-turn), else null. Never a fabricated
|
|
803
|
+
* default — a session whose binary told us nothing still reports null, and
|
|
804
|
+
* the badge stays blank rather than lying.
|
|
805
|
+
*/
|
|
806
|
+
_effectiveModelId() {
|
|
807
|
+
return this.model || this.bootedModel || null
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/**
|
|
811
|
+
* #7729 — record the model codex resolved, from the `thread/start` response.
|
|
812
|
+
*
|
|
813
|
+
* BOTH reads are observed live. The UNTRIMMED codex-cli 0.154.0 capture
|
|
814
|
+
* (https://github.com/blamechris/chroxy/issues/7721#issuecomment-5646200933)
|
|
815
|
+
* carries the resolved model at the TOP LEVEL **and** on a nested `thread`
|
|
816
|
+
* object — `thread.model` / `thread.reasoningEffort` mirror the top-level
|
|
817
|
+
* `model` / `reasoningEffort` — and `thread` is in the generated
|
|
818
|
+
* `ThreadStartResponse.required` alongside `model`. An earlier revision of
|
|
819
|
+
* this docblock read the TRIMMED echo quoted in the #7721 body (only
|
|
820
|
+
* `{model, reasoningEffort, modelProvider, sandbox, approvalPolicy}`) and
|
|
821
|
+
* wrongly declared the nested object unobserved: cite the untrimmed capture,
|
|
822
|
+
* never the trimmed excerpt.
|
|
823
|
+
*
|
|
824
|
+
* The ordering below is deliberate and unchanged — the TOP LEVEL wins, and
|
|
825
|
+
* the nested read is the one `??` that still answers for a build carrying
|
|
826
|
+
* only the mirrored copy. That same nested object is also the SOLE source of
|
|
827
|
+
* `this._threadId` (`started?.thread?.id`, in `start()` above), which every
|
|
828
|
+
* `turn/start` and `interrupt` depends on: observed live AND schema-required,
|
|
829
|
+
* so it is neither speculative nor deletable defensive cruft.
|
|
830
|
+
*
|
|
831
|
+
* A response carrying NEITHER is a cannot-read, not a "codex cleared the
|
|
832
|
+
* model": it leaves `bootedModel` at whatever it already was — `null` for a
|
|
833
|
+
* brand-new session, or a value `SessionManager.createSession()` pre-seeded
|
|
834
|
+
* from the persisted restore snapshot before calling `start()` — and never
|
|
835
|
+
* blanks a known id (#7770; mirrors `_onModelRerouted`'s identical rule for
|
|
836
|
+
* the same field — named, deliberately, WITHOUT a line offset: the "twelve
|
|
837
|
+
* lines below" this docblock first carried was copied from #7770's body,
|
|
838
|
+
* which quoted a pre-#7729 layout, and was ~87 lines wrong on arrival. A
|
|
839
|
+
* method name survives a refactor; an offset does not). A session with no
|
|
840
|
+
* prior value stays
|
|
841
|
+
* `null`, never `undefined` — the badge, the usage split and the
|
|
842
|
+
* context-window lookup all distinguish "codex did not say" from a model
|
|
843
|
+
* id, and an `undefined` here would serialize away entirely rather than
|
|
844
|
+
* reading as a cannot-check.
|
|
845
|
+
*
|
|
846
|
+
* The three log branches split on PROVENANCE, not on the resulting
|
|
847
|
+
* truthiness. A carried-over value is not an echo, and saying "thread/start
|
|
848
|
+
* echo" over one points an operator who changed `~/.codex/config.toml` at
|
|
849
|
+
* codex's config resolution instead of at chroxy's restore snapshot — so the
|
|
850
|
+
* cannot-read still warns (naming what it kept, `_onModelRerouted`'s shape)
|
|
851
|
+
* rather than disappearing behind the success line.
|
|
852
|
+
*/
|
|
853
|
+
_captureBootedModel(started) {
|
|
854
|
+
const echoed = this._readModelId(started?.model) ?? this._readModelId(started?.thread?.model)
|
|
855
|
+
const carried = echoed ? null : this.bootedModel || null
|
|
856
|
+
this.bootedModel = echoed ?? this.bootedModel ?? null
|
|
857
|
+
if (echoed && this.agentConnection) {
|
|
858
|
+
this.agentConnection.model = { ...this.agentConnection.model, resolved: echoed }
|
|
859
|
+
}
|
|
860
|
+
if (echoed) {
|
|
861
|
+
;(this._log || log).info(`codex resolved model=${echoed} (native thread echo)`)
|
|
862
|
+
} else if (carried) {
|
|
863
|
+
;(this._log || log).warn(`codex native thread carried no model echo; keeping ${carried} (restored before start)`)
|
|
864
|
+
} else {
|
|
865
|
+
;(this._log || log).warn('codex native thread carried no model echo; the session model stays unknown rather than guessed')
|
|
866
|
+
}
|
|
867
|
+
return this.bootedModel
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/**
|
|
871
|
+
* #7729 — a non-empty string model id, or null. Kept as one helper so the
|
|
872
|
+
* echo, the reroute and any later resume branch cannot disagree about what
|
|
873
|
+
* counts as "codex named a model".
|
|
874
|
+
*/
|
|
875
|
+
_readModelId(value) {
|
|
876
|
+
return typeof value === 'string' && value.length > 0 ? value : null
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
_onModelChanged(model) {
|
|
880
|
+
if (this.agentConnection) {
|
|
881
|
+
this.agentConnection.model = {
|
|
882
|
+
...this.agentConnection.model,
|
|
883
|
+
requested: model,
|
|
884
|
+
resolved: null,
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
;(this._log || log).info(`codex requested model set to ${model ?? 'default'}; resolved model is unknown until the runtime reports it`)
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
/**
|
|
891
|
+
* #7730 — the reasoning effort this session is running at: the operator's
|
|
892
|
+
* explicit choice, else the effort codex reported at `thread/start`, else
|
|
893
|
+
* null.
|
|
894
|
+
*
|
|
895
|
+
* Overriding this getter is not cosmetic. `BaseSession.thinkingLevel` returns
|
|
896
|
+
* `undefined`, and `ws-history.js` skips the `thinking_level_changed` replay
|
|
897
|
+
* on exactly that value — so without this override the control would reset to
|
|
898
|
+
* whatever the client last had in memory on every reconnect and tab switch,
|
|
899
|
+
* which for a codex session means a level the session never entered.
|
|
900
|
+
*
|
|
901
|
+
* Null (never `undefined`) when codex named none and nobody chose one:
|
|
902
|
+
* "unknown" has to stay readable as itself rather than collapsing into the
|
|
903
|
+
* "this provider has no thinking level" case the base class expresses.
|
|
904
|
+
*/
|
|
905
|
+
get thinkingLevel() {
|
|
906
|
+
return this._reasoningEffortOverride || this._bootedReasoningEffort || null
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/**
|
|
910
|
+
* #7730 — record the operator's chosen reasoning effort.
|
|
911
|
+
*
|
|
912
|
+
* Deliberately does NOT validate the level against a roster. The
|
|
913
|
+
* authoritative membership check is `handlers/settings-handlers.js`, which is
|
|
914
|
+
* the only layer that can see the ACTIVE MODEL's catalog row (`reasoningLevels`
|
|
915
|
+
* from `model/list`); duplicating it here would be a second roster to drift,
|
|
916
|
+
* and a per-model question answered in a place that does not know the model
|
|
917
|
+
* can only be answered with a repo-wide literal — which is the whole defect
|
|
918
|
+
* #7730 removes.
|
|
919
|
+
*
|
|
920
|
+
* The effort is not pushed to codex here: it rides the NEXT `turn/start`
|
|
921
|
+
* (see `_buildTurnParams`). There is no separate "set the effort" RPC that
|
|
922
|
+
* works on an idle thread, and `turn/settings/update` only applies to a turn
|
|
923
|
+
* already running.
|
|
924
|
+
*
|
|
925
|
+
* #7786 — `null` CLEARS the override: `thinkingLevel` then shows codex's own
|
|
926
|
+
* `thread/start` echo again and `turn/start` carries no `effort`, so codex
|
|
927
|
+
* re-resolves its default from `~/.codex/config.toml`. A client reaches this
|
|
928
|
+
* with `set_thinking_level { level: null }`; the handler passes that null
|
|
929
|
+
* through without a roster check (a clear names no level). An empty string
|
|
930
|
+
* also clears, as defence in depth — the wire schema and the handler both
|
|
931
|
+
* refuse it before it gets here.
|
|
932
|
+
*/
|
|
933
|
+
setThinkingLevel(level) {
|
|
934
|
+
const next = typeof level === 'string' && level.length > 0 ? level : null
|
|
935
|
+
this._reasoningEffortOverride = next
|
|
936
|
+
;(this._log || log).info(`codex reasoning effort set to ${next ?? 'unset'} (rides the next turn/start)`)
|
|
937
|
+
return true
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
/**
|
|
941
|
+
* #7730 — record the effort codex resolved at `thread/start`.
|
|
942
|
+
*
|
|
943
|
+
* Same two reads as `_captureBootedModel`, for the same reason: the untrimmed
|
|
944
|
+
* codex-cli 0.154.0 capture
|
|
945
|
+
* (https://github.com/blamechris/chroxy/issues/7721#issuecomment-5646200933)
|
|
946
|
+
* carries `reasoningEffort` at the TOP LEVEL and mirrored on the nested
|
|
947
|
+
* `thread` object, and `ReasoningEffort` is typed there as a free non-empty
|
|
948
|
+
* STRING — so no value is validated against a list on the way in.
|
|
949
|
+
*
|
|
950
|
+
* This feeds the DISPLAY only (`get thinkingLevel`), never the param
|
|
951
|
+
* builders: it is codex's own answer, and echoing it back at codex on the
|
|
952
|
+
* next turn would pin a value the binary is free to resolve for itself. An
|
|
953
|
+
* absent echo leaves it null — the control then shows nothing rather than
|
|
954
|
+
* claiming the session is at a level nobody established.
|
|
955
|
+
*/
|
|
956
|
+
_captureBootedReasoningEffort(started) {
|
|
957
|
+
const nonEmpty = (v) => (typeof v === 'string' && v.length > 0 ? v : null)
|
|
958
|
+
const echoed = nonEmpty(started?.reasoningEffort) ?? nonEmpty(started?.thread?.reasoningEffort)
|
|
959
|
+
this._bootedReasoningEffort = echoed ?? null
|
|
960
|
+
if (this._bootedReasoningEffort) {
|
|
961
|
+
;(this._log || log).info(`codex resolved reasoning effort=${this._bootedReasoningEffort} (native thread echo)`)
|
|
962
|
+
}
|
|
963
|
+
return this._bootedReasoningEffort
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
/**
|
|
967
|
+
* #7729 — codex re-routed this thread to a different model server-side
|
|
968
|
+
* (`model/rerouted` = `{threadId, turnId, fromModel, toModel, reason}`).
|
|
969
|
+
* Track `toModel` so the badge follows the reroute instead of naming a model
|
|
970
|
+
* the thread stopped running. A notification with no usable `toModel` is a
|
|
971
|
+
* cannot-read and leaves the previous value ALONE — it must not blank a
|
|
972
|
+
* model id we already know.
|
|
973
|
+
*/
|
|
974
|
+
_onModelRerouted(params) {
|
|
975
|
+
const to = this._readModelId(params?.toModel)
|
|
976
|
+
if (!to) {
|
|
977
|
+
;(this._log || log).warn(`codex model/rerouted carried no toModel (${JSON.stringify(params ?? null).slice(0, 200)}); keeping ${this.bootedModel ?? 'unknown'}`)
|
|
978
|
+
return false
|
|
979
|
+
}
|
|
980
|
+
const from = this._readModelId(params?.fromModel) || this.bootedModel || 'unknown'
|
|
981
|
+
this.bootedModel = to
|
|
982
|
+
if (this.agentConnection) {
|
|
983
|
+
this.agentConnection.model = { ...this.agentConnection.model, resolved: to }
|
|
984
|
+
}
|
|
985
|
+
;(this._log || log).info(`codex re-routed this thread ${from} → ${to}${params?.reason ? ` (${params.reason})` : ''}`)
|
|
986
|
+
return true
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/**
|
|
990
|
+
* #7726 — refresh the codex model catalog from this live session's client.
|
|
991
|
+
*
|
|
992
|
+
* Capability-gated the #7724 way: a binary KNOWN not to serve `model/list`
|
|
993
|
+
* (a parsed version below the floor) is not asked, while UNKNOWN — an absent
|
|
994
|
+
* or unparseable userAgent — still probes, because a cannot-check must not
|
|
995
|
+
* read as a no. Any error from the call itself degrades identically
|
|
996
|
+
* (`probeMethod`), whatever JSON-RPC code it carries.
|
|
997
|
+
*
|
|
998
|
+
* #7762 — this live refresh claims the shared `'codex'` discovery slot
|
|
999
|
+
* (model-discovery.js), so `scheduleProviderModelsRefresh`'s later scheduled
|
|
1000
|
+
* call sees an unchanged change key / hits the TTL and pushes nothing —
|
|
1001
|
+
* this call is the ONLY place a change made here can reach a connected
|
|
1002
|
+
* client. On a non-empty resolved roster, emit `models_updated` exactly the
|
|
1003
|
+
* `ollama-session.js` / `anthropic-compatible-session.js` shape:
|
|
1004
|
+
* session-manager forwards it as a provider-tagged `available_models`
|
|
1005
|
+
* broadcast. A `null`/empty resolution (no change, TTL-cached, or a failed
|
|
1006
|
+
* probe) emits nothing — pushing an empty roster would blank a picker that
|
|
1007
|
+
* already has one.
|
|
1008
|
+
*
|
|
1009
|
+
* The emit runs AFTER the probe's `.catch()`, with its own try/catch:
|
|
1010
|
+
* `EventEmitter.emit` rethrows a synchronous listener throw, and inside the
|
|
1011
|
+
* guarded chain that throw would be logged as `codex model catalog refresh
|
|
1012
|
+
* failed` and flip the resolved value to `null` — attributing a downstream
|
|
1013
|
+
* forwarding bug to the codex probe, which both succeeded and wrote the
|
|
1014
|
+
* registry. Ordering the two stages so each reports its own failure is the
|
|
1015
|
+
* point; do not collapse them back into one `.then().catch()`.
|
|
1016
|
+
*
|
|
1017
|
+
* @returns {Promise<Array<Object>|null>} always resolves; never throws.
|
|
1018
|
+
*/
|
|
1019
|
+
_refreshModelCatalog() {
|
|
1020
|
+
if (!this._client) return Promise.resolve(null)
|
|
1021
|
+
if (this.codexCapabilities?.supportsModelList === false) {
|
|
1022
|
+
;(this._log || log).debug('codex model catalog skipped: this binary is below the model/list floor')
|
|
1023
|
+
return Promise.resolve(null)
|
|
1024
|
+
}
|
|
1025
|
+
return Promise.resolve()
|
|
1026
|
+
.then(() => CodexAppServerSession.refreshModels({ client: this._client }))
|
|
1027
|
+
.catch((err) => {
|
|
1028
|
+
;(this._log || log).debug(`codex model catalog refresh failed: ${err?.message || err}`)
|
|
1029
|
+
return null
|
|
1030
|
+
})
|
|
1031
|
+
.then((models) => {
|
|
1032
|
+
if (Array.isArray(models) && models.length > 0) {
|
|
1033
|
+
try {
|
|
1034
|
+
this.emit('models_updated', { models })
|
|
1035
|
+
} catch (err) {
|
|
1036
|
+
;(this._log || log).debug(`codex models_updated listener threw: ${err?.message || err}`)
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
return models
|
|
1040
|
+
})
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
/**
|
|
1044
|
+
* #7724 — record what the `initialize` handshake said about the binary serving
|
|
1045
|
+
* this session. Feature-gating ONLY: this never throws and never refuses a
|
|
1046
|
+
* session, so a binary below the protocol floor (or one whose userAgent we
|
|
1047
|
+
* cannot parse) still starts a thread and still sends turns.
|
|
1048
|
+
*/
|
|
1049
|
+
_captureHandshake(init) {
|
|
1050
|
+
const { version, raw } = parseCodexUserAgent(init?.userAgent)
|
|
1051
|
+
this.codexUserAgent = raw
|
|
1052
|
+
this.codexVersion = version
|
|
1053
|
+
this.codexCapabilities = capabilitiesForVersion(version)
|
|
1054
|
+
if (version) {
|
|
1055
|
+
;(this._log || log).info(`codex app-server handshake (version=${version} userAgent=${String(raw).slice(0, 200)})`)
|
|
1056
|
+
} else {
|
|
1057
|
+
// Not a warning about the binary — a note that the CHEAP gate is
|
|
1058
|
+
// unavailable and load-bearing features must be probed at runtime.
|
|
1059
|
+
;(this._log || log).warn(`codex app-server handshake carried no parseable version (userAgent=${raw === null ? 'absent' : String(raw).slice(0, 200)}); capabilities fall through to runtime probes`)
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
/** #8609 — the launched client's identity for the model-rejection ledger. */
|
|
1064
|
+
_clientKey() {
|
|
1065
|
+
return codexClientKey(this._spawnedBinary, this.codexVersion, this._observedAuthRoute || this._connectionAuthRoute)
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
/**
|
|
1069
|
+
* #8609 — after the handshake, note (warn once, expose in runtime info) a
|
|
1070
|
+
* client bundled in a desktop app that is newer than the one we launched.
|
|
1071
|
+
* Advisory only: never switches binaries and never throws.
|
|
1072
|
+
*/
|
|
1073
|
+
_noteNewerBundledClient() {
|
|
1074
|
+
try {
|
|
1075
|
+
const have = parseSemver(this.codexVersion)
|
|
1076
|
+
const bundled = this._findBundledClient()
|
|
1077
|
+
if (!have || !bundled || bundled.path === this._spawnedBinary) return
|
|
1078
|
+
const want = parseSemver(bundled.version)
|
|
1079
|
+
if (!want || compareSemver(want, have) <= 0) return
|
|
1080
|
+
this._newerBinary = { path: bundled.path, version: bundled.version }
|
|
1081
|
+
;(this._log || log).warn(`a newer codex client is installed: ${bundled.version} (${bundled.path}); this session launched ${this.codexVersion} (${this._spawnedBinary}) — set CHROXY_CODEX_BIN to use it`)
|
|
1082
|
+
} catch (err) {
|
|
1083
|
+
;(this._log || log).debug(`bundled codex client probe failed: ${err?.message || err}`)
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/** #8609 — the first codex-roster model this client has not had rejected. */
|
|
1088
|
+
_suggestFallbackModel(rejected) {
|
|
1089
|
+
let roster = []
|
|
1090
|
+
try { roster = CodexAppServerSession.getFallbackModels().map((m) => m.id) } catch { /* no roster */ }
|
|
1091
|
+
return suggestFallbackModel(roster, this._clientKey(), rejected ? [rejected] : [])
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
/**
|
|
1095
|
+
* #8609 — an earlier session on THIS client (same path and version) had its
|
|
1096
|
+
* default model rejected by the backend. With no explicit model, start the
|
|
1097
|
+
* thread on the fallback instead of walking into the same refusal.
|
|
1098
|
+
*/
|
|
1099
|
+
_avoidRejectedDefaultModel() {
|
|
1100
|
+
if (this.model) return
|
|
1101
|
+
const rejected = rejectedDefaultFor(this._clientKey())
|
|
1102
|
+
if (!rejected) return
|
|
1103
|
+
const fallback = this._suggestFallbackModel(rejected)
|
|
1104
|
+
if (!fallback) return
|
|
1105
|
+
this._defaultFallbackModel = fallback
|
|
1106
|
+
;(this._log || log).info(`codex model '${rejected}' was rejected for this client earlier; starting on '${fallback}' instead`)
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/**
|
|
1110
|
+
* #8609 — the backend refused the model: say so legibly (model, client,
|
|
1111
|
+
* alternative, newer client) and remember it for this client.
|
|
1112
|
+
*/
|
|
1113
|
+
_modelUnsupportedPayload(rejection) {
|
|
1114
|
+
const ran = this._effectiveModelId()
|
|
1115
|
+
// Blame the client (and remember it) ONLY when the rejection text quoted a
|
|
1116
|
+
// model id AND that is the model this turn ran. An unquoted match ("the
|
|
1117
|
+
// requested model is not supported for this endpoint") says nothing about
|
|
1118
|
+
// the client's default, and recording it would blacklist a working model.
|
|
1119
|
+
const evidence = rejection.model !== null && rejection.model === ran
|
|
1120
|
+
const model = rejection.model || ran
|
|
1121
|
+
if (evidence) recordModelRejection(this._clientKey(), model, { wasDefault: !this.model })
|
|
1122
|
+
const version = this.codexVersion || 'unknown version'
|
|
1123
|
+
const path = this._spawnedBinary || 'codex'
|
|
1124
|
+
const parts = [evidence || rejection.model
|
|
1125
|
+
? `Codex rejected model '${model}': it is not supported by the codex client this session launched (${version}, ${path}).`
|
|
1126
|
+
: `Codex reported that a model is not supported (session model: ${ran ? `'${ran}'` : 'unknown'}; codex client ${version}, ${path}).`]
|
|
1127
|
+
const fallback = this._suggestFallbackModel(model)
|
|
1128
|
+
if (fallback) parts.push(`Try '${fallback}'.`)
|
|
1129
|
+
if (this._newerBinary) {
|
|
1130
|
+
parts.push(`A newer codex client is installed: ${this._newerBinary.version} (${this._newerBinary.path}) — set CHROXY_CODEX_BIN to use it.`)
|
|
1131
|
+
}
|
|
1132
|
+
return { message: parts.join(' '), code: MODEL_UNSUPPORTED_CODE }
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
/**
|
|
1136
|
+
* #8301: `sendMessage` on a session whose app-server is not up emits a
|
|
1137
|
+
* user-visible "not started" error. A daemon wake must not cause one.
|
|
1138
|
+
* @returns {string|null}
|
|
1139
|
+
*/
|
|
1140
|
+
daemonTurnRefusal() {
|
|
1141
|
+
return (!this._processReady || !this._client) ? 'not-started' : null
|
|
139
1142
|
}
|
|
140
1143
|
|
|
141
1144
|
async sendMessage(prompt, attachments, sendOptions = {}) {
|
|
142
1145
|
if (this._isBusy) {
|
|
143
|
-
this.enqueueOutgoingMessage({ prompt, attachments, sendOptions })
|
|
1146
|
+
const queued = this.enqueueOutgoingMessage({ prompt, attachments, sendOptions })
|
|
1147
|
+
reportInputAdmission(sendOptions, queued
|
|
1148
|
+
? { status: 'queued', delivery: 'queued' }
|
|
1149
|
+
: {
|
|
1150
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1151
|
+
reason: 'queue_full', message: 'The provider input queue is full; retry after queued work advances.',
|
|
1152
|
+
})
|
|
144
1153
|
return
|
|
145
1154
|
}
|
|
146
1155
|
if (!this._processReady || !this._client) {
|
|
147
1156
|
this.emit('error', { message: 'Codex app-server session is not started' })
|
|
1157
|
+
reportInputAdmission(sendOptions, {
|
|
1158
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1159
|
+
reason: 'not_runnable', message: 'The provider session is not started.',
|
|
1160
|
+
})
|
|
148
1161
|
return
|
|
149
1162
|
}
|
|
150
|
-
|
|
151
|
-
this._messageCounter += 1
|
|
152
|
-
const messageId = `msg-${this._messageIdPrefix}-${this._messageCounter}`
|
|
153
|
-
this._currentMessageId = messageId
|
|
154
|
-
this._activeTurn = { messageId, turnId: null, didStreamStart: false }
|
|
155
|
-
// Fresh abort scope for this turn's approvals — interrupt()/destroy() abort it
|
|
156
|
-
// so a pending permission_request resolves (deny) instead of hanging the turn.
|
|
157
|
-
this._turnAbort = new AbortController()
|
|
158
|
-
this._armResultTimeout()
|
|
1163
|
+
const messageId = this._openTurn()
|
|
159
1164
|
|
|
160
1165
|
// #6606 review — mirror the exec path: prepend the combined skills prefix on
|
|
161
|
-
// the FIRST turn so runtime skills reach codex.
|
|
162
|
-
// turn
|
|
1166
|
+
// the FIRST turn so runtime skills reach codex. An acknowledgement or a
|
|
1167
|
+
// completed turn proves admission; a refused first turn retries the skills.
|
|
163
1168
|
let text = prompt || ''
|
|
164
1169
|
if (!this._skillsPrepended) {
|
|
165
1170
|
const combined = typeof this._buildCombinedSkillsPrefix === 'function' ? this._buildCombinedSkillsPrefix() : ''
|
|
@@ -172,24 +1177,65 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
172
1177
|
const input = this._buildTurnInput(text, attachments, messageId)
|
|
173
1178
|
|
|
174
1179
|
;(this._log || log).info(`codex app-server turn start (msg=${messageId} thread=${this._threadId} inputItems=${input.length})`)
|
|
1180
|
+
const dispatchedTurn = this._activeTurn
|
|
1181
|
+
const turnParams = this._buildTurnParams(input)
|
|
1182
|
+
const previouslyUnverified = this._nativeSettingsUnverified
|
|
1183
|
+
// Freeze the choices actually sent, before notifications can complete this
|
|
1184
|
+
// turn or setters select a different choice for the next one.
|
|
1185
|
+
this._nativeSettingsUnverified = previouslyUnverified || !!((turnParams.model && turnParams.model !== this.bootedModel) || (turnParams.effort && turnParams.effort !== this._bootedReasoningEffort))
|
|
175
1186
|
try {
|
|
176
|
-
const res = await this._client.request('turn/start',
|
|
177
|
-
threadId: this._threadId,
|
|
178
|
-
approvalPolicy: this._approvalPolicy(), // #6605 P2 — per-turn, tracks mode changes
|
|
179
|
-
input,
|
|
180
|
-
// #6608 — pass the CURRENT model per turn (turn/start accepts it) so a
|
|
181
|
-
// mid-session set_model actually takes effect, matching the exec path's
|
|
182
|
-
// per-turn model. thread/start seeds the initial model; this tracks changes.
|
|
183
|
-
...(this.model ? { model: this.model } : {}),
|
|
184
|
-
})
|
|
1187
|
+
const res = await this._client.request('turn/start', turnParams)
|
|
185
1188
|
this._skillsPrepended = true
|
|
186
|
-
|
|
1189
|
+
reportInputAdmission(sendOptions, { status: 'accepted', delivery: 'dispatch_started' })
|
|
1190
|
+
if (this._activeTurn === dispatchedTurn && !dispatchedTurn.turnId) dispatchedTurn.turnId = res?.turn?.id || null
|
|
187
1191
|
} catch (err) {
|
|
188
|
-
|
|
189
|
-
this.
|
|
1192
|
+
const refused = typeof err?.jsonRpcCode === 'number'
|
|
1193
|
+
if (refused && this._activeTurn === dispatchedTurn) this._nativeSettingsUnverified = previouslyUnverified
|
|
1194
|
+
const admission = refused ? {
|
|
1195
|
+
status: 'rejected', delivery: 'not_dispatched', retrySafe: true,
|
|
1196
|
+
reason: 'turn_start_failed', message: 'The provider rejected the turn before it started.',
|
|
1197
|
+
} : {
|
|
1198
|
+
status: 'uncertain', delivery: 'unknown', retrySafe: false,
|
|
1199
|
+
reason: 'turn_start_uncertain', message: 'The native turn acknowledgement was lost; it may have started. Check the original session before explicitly resending.',
|
|
1200
|
+
}
|
|
1201
|
+
reportInputAdmission(sendOptions, admission)
|
|
1202
|
+
// Only an explicit native refusal proves this turn did not start.
|
|
1203
|
+
// A transport loss must keep its uncertainty visible to every caller.
|
|
1204
|
+
this._failTurn(
|
|
1205
|
+
refused ? `Codex turn failed to start: ${err.message}` : admission.message,
|
|
1206
|
+
refused ? {} : { code: admission.reason },
|
|
1207
|
+
)
|
|
190
1208
|
}
|
|
191
1209
|
}
|
|
192
1210
|
|
|
1211
|
+
// Turn-start bookkeeping, shared by a turn the daemon sends and one codex is
|
|
1212
|
+
// running that the daemon was not tracking (#8710). Returns the messageId.
|
|
1213
|
+
_openTurn(turnId = null) {
|
|
1214
|
+
this._isBusy = true
|
|
1215
|
+
this._permissions.clearUserStopInFlight() // #8430: a new turn starts with no user Stop in flight
|
|
1216
|
+
this._messageCounter += 1
|
|
1217
|
+
const messageId = `msg-${this._messageIdPrefix}-${this._messageCounter}`
|
|
1218
|
+
this._currentMessageId = messageId
|
|
1219
|
+
this._activeTurn = { messageId, turnId, didStreamStart: false }
|
|
1220
|
+
// #7769 — clear the PREVIOUS turn's usage here, not at turn end. A
|
|
1221
|
+
// `turn/completed` that arrives with no intervening
|
|
1222
|
+
// `thread/tokenUsage/updated` must report `usage: null` ("codex told us
|
|
1223
|
+
// nothing"), never the last turn's numbers: `session-manager._trackUsage`
|
|
1224
|
+
// ADDS `result.usage` into `cumulativeUsage` once per turn, so re-reporting
|
|
1225
|
+
// is a silent double count of user-visible tokens and cost.
|
|
1226
|
+
// #7773 — and freeze the cumulative baseline this turn's delta is measured
|
|
1227
|
+
// from, in the same place, so the two can never disagree about where a turn
|
|
1228
|
+
// starts.
|
|
1229
|
+
this._lastUsage = null
|
|
1230
|
+
this._lastOccupancy = null
|
|
1231
|
+
this._turnBaselineTotals = this._threadTotals
|
|
1232
|
+
// Fresh abort scope for this turn's approvals — interrupt()/destroy() abort it
|
|
1233
|
+
// so a pending permission_request resolves (deny) instead of hanging the turn.
|
|
1234
|
+
this._turnAbort = new AbortController()
|
|
1235
|
+
this._armResultTimeout()
|
|
1236
|
+
return messageId
|
|
1237
|
+
}
|
|
1238
|
+
|
|
193
1239
|
// #6609 — build the codex `turn/start` input array from the prompt + Chroxy
|
|
194
1240
|
// attachments. codex's UserInput union natively takes file paths, so:
|
|
195
1241
|
// - binary image/document → materialized to a temp file (reused helper)
|
|
@@ -210,13 +1256,32 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
210
1256
|
// + warn on an absolute or parent-traversing path.
|
|
211
1257
|
const fileRefs = attachments.filter((a) => {
|
|
212
1258
|
if (!a || a.type !== 'file_ref' || typeof a.path !== 'string') return false
|
|
213
|
-
|
|
1259
|
+
// #7273 — `startsWith('/')` missed every Windows absolute spelling
|
|
1260
|
+
// (`C:\\x`, `\\\\host\\share\\x`, `\\\\?\\C:\\x`). The `..` half already split on
|
|
1261
|
+
// both separators; the absolute half now tests both namespaces to match.
|
|
1262
|
+
if (posixPath.isAbsolute(a.path) || win32Path.isAbsolute(a.path) || a.path.split(/[/\\]/).includes('..')) {
|
|
214
1263
|
;(this._log || log).warn(`codex attachment: skipping non-relative file_ref path "${a.path}"`)
|
|
215
1264
|
return false
|
|
216
1265
|
}
|
|
217
1266
|
return true
|
|
218
1267
|
})
|
|
219
|
-
|
|
1268
|
+
// #7373 — the attach dir lives inside a dedicated, `owner.pid`-stamped
|
|
1269
|
+
// per-session dir under ATTACH_BASE rather than a bare mkdtemp under
|
|
1270
|
+
// os.tmpdir(), so a crash leaves the boot-time sweep able to tell a
|
|
1271
|
+
// dead session's leftover attachment files from a live one's and
|
|
1272
|
+
// remove only the dead one (same shape as ClaudeTuiSession's sink
|
|
1273
|
+
// dirs and CliSession's permission-mode sidecar).
|
|
1274
|
+
if (binary.length && !this._attachDir) {
|
|
1275
|
+
const base = ensureOwnedBaseDir(CodexAppServerSession.ATTACH_BASE)
|
|
1276
|
+
const dir = join(base, `s-${randomUUID()}`)
|
|
1277
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
1278
|
+
// Stamp the owning pid so the boot-time sweep can tell a live
|
|
1279
|
+
// daemon's dir from one orphaned by a crash. Best-effort: a
|
|
1280
|
+
// missing pidfile just makes the dir sweep-eligible after a grace
|
|
1281
|
+
// window — the safe default for an orphan.
|
|
1282
|
+
try { writeFileSync(join(dir, OWNER_PID_FILE), String(process.pid)) } catch { /* best effort */ }
|
|
1283
|
+
this._attachDir = dir
|
|
1284
|
+
}
|
|
220
1285
|
const materialized = binary.length ? materializeAttachments(binary, this._attachDir, messageId) : []
|
|
221
1286
|
const refFiles = fileRefs.map((a) => ({ path: a.path, name: a.name || basename(a.path), mediaType: '', size: 0 }))
|
|
222
1287
|
const all = [...materialized, ...refFiles]
|
|
@@ -252,12 +1317,75 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
252
1317
|
// ------------------------------------------------------------------
|
|
253
1318
|
|
|
254
1319
|
_onNotification({ method, params }) {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
1320
|
+
// #8710 — a torn-down session maps nothing. The client is killed, but stdout
|
|
1321
|
+
// already read can still be dispatched, and with destroy()'s listeners gone
|
|
1322
|
+
// an `error` emitted here would throw out of the stream handler.
|
|
1323
|
+
if (this._destroying) return
|
|
1324
|
+
// #7724 — `deprecationNotice` is handled HERE, ahead of the between-turns
|
|
1325
|
+
// handling, NOT as a case in the switch below. It is a lifecycle notice
|
|
1326
|
+
// the binary can emit at any point — most plausibly right after the
|
|
1327
|
+
// handshake, when there is no active turn — and the switch is unreachable in
|
|
1328
|
+
// exactly that window. A case down there would be a handler that cannot fire
|
|
1329
|
+
// for its own main case.
|
|
1330
|
+
//
|
|
1331
|
+
// This early return DELIBERATELY bypasses `_resetResultTimeout()` and the
|
|
1332
|
+
// #6629/#6856 reconnect-backstop disarm below. Before this change a mid-turn
|
|
1333
|
+
// deprecationNotice reached `default: break` AFTER both, so it counted as
|
|
1334
|
+
// forward progress on the liveness path. It is not: the notice is emitted on
|
|
1335
|
+
// the binary's own schedule and says nothing about whether codex is still
|
|
1336
|
+
// streaming this turn, so treating it as a heartbeat would slide the result
|
|
1337
|
+
// timeout and the reconnect watchdog out on a payload that carries no
|
|
1338
|
+
// evidence of progress. A turn that has genuinely stalled must still time out.
|
|
1339
|
+
if (method === 'deprecationNotice') {
|
|
1340
|
+
this._onDeprecationNotice(params)
|
|
1341
|
+
return
|
|
1342
|
+
}
|
|
1343
|
+
// #8743 — a notification about a thread or a turn is codex doing something,
|
|
1344
|
+
// so the idle-only auto-deploy must not restart the daemon under it. That
|
|
1345
|
+
// includes the ones dropped below without an event: a sub-agent's thread, a
|
|
1346
|
+
// straggler from a turn codex already ended, anything for a turn the daemon
|
|
1347
|
+
// is not tracking. The emit() override only sees the ones that become events.
|
|
1348
|
+
// One that names neither (account rate limits, MCP or skills status) is
|
|
1349
|
+
// about the environment, may arrive on the binary's own schedule, and must
|
|
1350
|
+
// not hold a deploy off.
|
|
1351
|
+
if (this._notificationTurnId(params) || (typeof params?.threadId === 'string' && params.threadId !== '')) {
|
|
1352
|
+
this.noteProviderActivity()
|
|
1353
|
+
}
|
|
1354
|
+
if (this._isOtherThread(params)) {
|
|
1355
|
+
// #8710 — a sub-agent's thread. Its activity is evidence this turn's work
|
|
1356
|
+
// is still running (the parent is often blocked waiting on it), so it holds
|
|
1357
|
+
// off the result timeout — unless a pending permission has paused that
|
|
1358
|
+
// timer. Nothing else: it is not this thread's stream, so it neither
|
|
1359
|
+
// disarms the reconnect backstops below nor maps onto this turn's events.
|
|
1360
|
+
if (this._activeTurn && this._resultTimeout) this._armResultTimeout()
|
|
258
1361
|
return
|
|
259
1362
|
}
|
|
1363
|
+
const turnId = this._notificationTurnId(params)
|
|
1364
|
+
const sessionHandler = SESSION_SCOPED_HANDLERS.get(method)
|
|
1365
|
+
if (turnId && !sessionHandler && this._endedNativeTurnIds.has(turnId)) {
|
|
1366
|
+
// #8710 — codex already ended this turn: a straggler (a background exec
|
|
1367
|
+
// reporting after its turn, or the `turn/completed` that follows a terminal
|
|
1368
|
+
// `error`), not a live turn, and never the turn that is open now.
|
|
1369
|
+
;(this._log || log).debug(`codex app-server ${method} for ended turn ${turnId} — ignored`)
|
|
1370
|
+
return
|
|
1371
|
+
}
|
|
1372
|
+
if (!this._activeTurn) {
|
|
1373
|
+
// #7729 — a reroute and a usage update both describe the SESSION, not the
|
|
1374
|
+
// turn, so they are consumed here.
|
|
1375
|
+
if (sessionHandler) { sessionHandler(this, params); return }
|
|
1376
|
+
// #8710 — anything else is about a turn the daemon is not tracking. An
|
|
1377
|
+
// error is surfaced, and codex still reporting work opens a turn for it.
|
|
1378
|
+
if (!this._onUntrackedTurnNotification(method, params, turnId)) return
|
|
1379
|
+
}
|
|
260
1380
|
this._resetResultTimeout()
|
|
1381
|
+
// #6629/#6856 — any notification that is NOT another `error` tick is genuine
|
|
1382
|
+
// forward progress: codex's response stream is live again, so disarm BOTH the
|
|
1383
|
+
// reconnect backstops that #6623's suppression path may have armed — the #6629
|
|
1384
|
+
// silence watchdog and the #6856 one-shot suppression deadline. (A terminal
|
|
1385
|
+
// `error` clears both below on its way to _failTurn; a transient reconnect
|
|
1386
|
+
// `error` re-arms the watchdog but leaves the deadline untouched.)
|
|
1387
|
+
if (method !== 'error') { this._clearReconnectWatchdog(); this._clearReconnectDeadline() }
|
|
1388
|
+
if (sessionHandler) { sessionHandler(this, params); return }
|
|
261
1389
|
const t = this._activeTurn
|
|
262
1390
|
switch (method) {
|
|
263
1391
|
case 'turn/started':
|
|
@@ -276,23 +1404,180 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
276
1404
|
case 'item/completed':
|
|
277
1405
|
this._onItemCompleted(params?.item)
|
|
278
1406
|
break
|
|
279
|
-
case 'thread/tokenUsage/updated':
|
|
280
|
-
this._lastUsage = this._mapUsage(params)
|
|
281
|
-
break
|
|
282
1407
|
case 'turn/completed':
|
|
283
|
-
this._finishTurn(params?.turn)
|
|
1408
|
+
this._finishTurn(params?.turn, turnId)
|
|
284
1409
|
break
|
|
285
|
-
case 'error':
|
|
286
|
-
|
|
1410
|
+
case 'error': {
|
|
1411
|
+
// #6623 — codex emits transient `error` notifications WHILE its OWN retry
|
|
1412
|
+
// loop re-establishes a dropped response stream (a `Reconnecting... N/M`
|
|
1413
|
+
// message + `codexErrorInfo.responseStreamDisconnected`). This commonly
|
|
1414
|
+
// fires right after a permission / escalation round-trip stalls a shell
|
|
1415
|
+
// turn. These are NOT terminal: failing here surfaces a red provider error
|
|
1416
|
+
// and orphans the in-flight turn even though codex is still recovering and
|
|
1417
|
+
// may yet emit turn/completed. Keep the turn OPEN on a reconnect-in-progress
|
|
1418
|
+
// notification — the result timeout (re-armed by _resetResultTimeout above)
|
|
1419
|
+
// is the backstop if codex never recovers, and codex's terminal give-up
|
|
1420
|
+
// (a disconnect WITHOUT a reconnecting message) still falls through to fail.
|
|
1421
|
+
const err = this._errorPayload(params)
|
|
1422
|
+
if (this._isTransientReconnect(err)) {
|
|
1423
|
+
;(this._log || log).warn(`codex app-server response stream reconnecting (turn kept open): ${err.message || 'responseStreamDisconnected'}`)
|
|
1424
|
+
// #6629 — arm the bounded watchdog so a reconnect that NEVER recovers
|
|
1425
|
+
// (nor emits codex's terminal give-up) still reconciles the stale
|
|
1426
|
+
// working state, even when a pending permission has paused the result
|
|
1427
|
+
// timeout. Re-arms on each reconnect tick so codex's legit N/5 retry
|
|
1428
|
+
// burst doesn't trip it mid-recovery.
|
|
1429
|
+
this._armReconnectWatchdog()
|
|
1430
|
+
// #6856 — arm the one-shot suppression deadline the FIRST time this turn
|
|
1431
|
+
// enters the reconnect-suppressed state. Unlike the watchdog it is NOT
|
|
1432
|
+
// re-armed here on subsequent ticks (the guard in _armReconnectDeadline
|
|
1433
|
+
// makes a later call a no-op), so a reconnect storm that keeps ticking
|
|
1434
|
+
// forever still fails on a fixed bound instead of sliding both backstops out.
|
|
1435
|
+
this._armReconnectDeadline()
|
|
1436
|
+
break
|
|
1437
|
+
}
|
|
1438
|
+
this._clearReconnectWatchdog() // terminal error → about to fail; drop the backstops
|
|
1439
|
+
this._clearReconnectDeadline() // #6856
|
|
1440
|
+
// #8710 — codex has ended this turn: its `turn/completed` follows.
|
|
1441
|
+
this._noteNativeTurnEnded(turnId ?? t.turnId)
|
|
1442
|
+
const { message, code } = this._terminalErrorPayload(err, params)
|
|
1443
|
+
this._failTurn(message, { code })
|
|
287
1444
|
break
|
|
1445
|
+
}
|
|
288
1446
|
default:
|
|
289
1447
|
break // reasoning/plan/other items are ignored in Phase 1
|
|
290
1448
|
}
|
|
291
1449
|
}
|
|
292
1450
|
|
|
1451
|
+
/**
|
|
1452
|
+
* #8710 — every thread-scoped notification names its thread in `threadId`
|
|
1453
|
+
* (required in the v2 schema, codex-cli 0.163.0), and the app-server relays a
|
|
1454
|
+
* sub-agent's thread on its parent's connection. Trial run B2b ended its turn
|
|
1455
|
+
* on a worker's `turn/completed` 11 minutes into a turn codex ran for two
|
|
1456
|
+
* hours. An absent id is read as this thread, as every notification without
|
|
1457
|
+
* one always has been.
|
|
1458
|
+
*/
|
|
1459
|
+
_isOtherThread(params) {
|
|
1460
|
+
const id = params?.threadId
|
|
1461
|
+
return typeof id === 'string' && id !== '' && this._threadId != null && id !== this._threadId
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// #8710 — the codex turn a notification is about: `turnId` on item, error and
|
|
1465
|
+
// usage notifications, `turn.id` on turn/started and turn/completed.
|
|
1466
|
+
_notificationTurnId(params) {
|
|
1467
|
+
const id = params?.turnId ?? params?.turn?.id
|
|
1468
|
+
return typeof id === 'string' && id !== '' ? id : null
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
// #8710 — remember a turn codex itself ended, so a straggler for it is not
|
|
1472
|
+
// taken for a live turn. Bounded: only recent turns still have any in flight.
|
|
1473
|
+
_noteNativeTurnEnded(turnId) {
|
|
1474
|
+
if (typeof turnId !== 'string' || turnId === '') return
|
|
1475
|
+
this._endedNativeTurnIds.delete(turnId)
|
|
1476
|
+
this._endedNativeTurnIds.add(turnId)
|
|
1477
|
+
if (this._endedNativeTurnIds.size > MAX_ENDED_NATIVE_TURN_IDS) {
|
|
1478
|
+
this._endedNativeTurnIds.delete(this._endedNativeTurnIds.values().next().value)
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
/**
|
|
1483
|
+
* #8710 — a notification for this thread arrived with no daemon turn open.
|
|
1484
|
+
* It is about a turn the daemon is not tracking: one it gave up on itself (the
|
|
1485
|
+
* result timeout, the reconnect backstops, a lost `turn/start`
|
|
1486
|
+
* acknowledgement) or one codex runs without being asked. Before #8710 all of
|
|
1487
|
+
* it was discarded, which is how trial run B2b's last 1 h 50 min of work and
|
|
1488
|
+
* the usage-limit stop that ended it never reached a client.
|
|
1489
|
+
*
|
|
1490
|
+
* Returns true when it opened a turn, which the caller then maps as usual.
|
|
1491
|
+
*/
|
|
1492
|
+
_onUntrackedTurnNotification(method, params, turnId) {
|
|
1493
|
+
const tlog = this._log || log
|
|
1494
|
+
if (method === 'error') {
|
|
1495
|
+
const err = this._errorPayload(params)
|
|
1496
|
+
// `willRetry` (required in 0.163.0) marks codex's own retry of a turn it is
|
|
1497
|
+
// still running: not an end, and that turn's later notifications are live.
|
|
1498
|
+
if (params?.willRetry === true || this._isTransientReconnect(err)) {
|
|
1499
|
+
tlog.debug(`codex app-server retrying with no turn open: ${err.message || 'stream error'}`)
|
|
1500
|
+
return false
|
|
1501
|
+
}
|
|
1502
|
+
this._noteNativeTurnEnded(turnId)
|
|
1503
|
+
const payload = this._terminalErrorPayload(err, params)
|
|
1504
|
+
tlog.warn(`codex app-server error with no turn open (turn=${turnId}): ${payload.message}`)
|
|
1505
|
+
this.emit('error', payload)
|
|
1506
|
+
return false
|
|
1507
|
+
}
|
|
1508
|
+
if (method === 'turn/completed') {
|
|
1509
|
+
this._noteNativeTurnEnded(turnId)
|
|
1510
|
+
const turn = params?.turn
|
|
1511
|
+
if (turn?.status === 'failed') {
|
|
1512
|
+
const payload = this._terminalErrorPayload(turn.error, turn.error)
|
|
1513
|
+
tlog.warn(`codex app-server turn ${turnId} failed with no turn open: ${payload.message}`)
|
|
1514
|
+
this.emit('error', payload)
|
|
1515
|
+
} else {
|
|
1516
|
+
tlog.info(`codex app-server turn ${turnId} ended (${turn?.status || 'completed'}) with no turn open`)
|
|
1517
|
+
}
|
|
1518
|
+
return false
|
|
1519
|
+
}
|
|
1520
|
+
// Only a turn/started, or a notification naming its turn, says a turn is live.
|
|
1521
|
+
if (method !== 'turn/started' && !turnId) {
|
|
1522
|
+
tlog.debug(`codex app-server ${method} with no turn open — ignored`)
|
|
1523
|
+
return false
|
|
1524
|
+
}
|
|
1525
|
+
this._openTurn(turnId)
|
|
1526
|
+
tlog.warn(`codex app-server ${method} for turn ${turnId} with no turn open — following codex's turn`)
|
|
1527
|
+
// stream_start is what tells clients the session is busy again.
|
|
1528
|
+
this._ensureStreamStart()
|
|
1529
|
+
return true
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
/**
|
|
1533
|
+
* #8710 — what a turn-ending codex error tells the client. A usage limit
|
|
1534
|
+
* carries codex's own sentence (it names when the limit resets) and the
|
|
1535
|
+
* `usage_limit` code claude-tui sessions use for the same stop (#8400); any
|
|
1536
|
+
* other error keeps the raw payload this path has always shown, and a failed
|
|
1537
|
+
* turn that names no error says only that it failed.
|
|
1538
|
+
* `usageLimitExceeded` is the v2 `CodexErrorInfo` spelling (codex-cli 0.163.0
|
|
1539
|
+
* `generate-json-schema`).
|
|
1540
|
+
*/
|
|
1541
|
+
_terminalErrorPayload(err, raw) {
|
|
1542
|
+
if (err?.codexErrorInfo === 'usageLimitExceeded' && typeof err.message === 'string' && err.message) {
|
|
1543
|
+
return { message: err.message, code: USAGE_LIMIT_CODE }
|
|
1544
|
+
}
|
|
1545
|
+
const rejection = detectModelRejection(err, raw)
|
|
1546
|
+
if (rejection) return this._modelUnsupportedPayload(rejection)
|
|
1547
|
+
if (raw == null) return { message: 'Codex turn failed' }
|
|
1548
|
+
return { message: `Codex error: ${JSON.stringify(raw).slice(0, 200)}` }
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
/**
|
|
1552
|
+
* #7724 — surface the app-server's own deprecation notice. Logged, not
|
|
1553
|
+
* emitted: it is operator-facing information about the codex binary, not a
|
|
1554
|
+
* turn event, and the switch's default arm used to swallow it entirely.
|
|
1555
|
+
*
|
|
1556
|
+
* The params shape is `{ summary: string (required), details: string|null }`,
|
|
1557
|
+
* verified against the live codex-cli 0.154.0 binary with
|
|
1558
|
+
* `codex app-server generate-json-schema --out <dir>` →
|
|
1559
|
+
* `ServerNotification.json` → `definitions.DeprecationNoticeNotification`.
|
|
1560
|
+
* There is no `message` field. The JSON.stringify fallback is kept for a
|
|
1561
|
+
* payload that carries neither field (a fork, or a future rename), so a
|
|
1562
|
+
* notice is never swallowed — but it is the FALLBACK, not the main path.
|
|
1563
|
+
*/
|
|
1564
|
+
_onDeprecationNotice(params) {
|
|
1565
|
+
const summary = typeof params?.summary === 'string' && params.summary ? params.summary : null
|
|
1566
|
+
const details = typeof params?.details === 'string' && params.details ? params.details : null
|
|
1567
|
+
let detail
|
|
1568
|
+
if (summary) detail = details ? `${summary} — ${details}` : summary
|
|
1569
|
+
else detail = JSON.stringify(params ?? null)
|
|
1570
|
+
;(this._log || log).warn(`codex app-server deprecation notice: ${String(detail).slice(0, 500)}`)
|
|
1571
|
+
}
|
|
1572
|
+
|
|
293
1573
|
_onItemStarted(item) {
|
|
294
1574
|
if (!item) return
|
|
295
|
-
// commandExecution / fileChange / mcpToolCall map to Chroxy tools.
|
|
1575
|
+
// commandExecution / fileChange / mcpToolCall map to Chroxy tools. The
|
|
1576
|
+
// mcpToolCall EXECUTION is surfaced as a tool_start/tool_result so connector
|
|
1577
|
+
// tool calls are visible in the transcript (#6684 part 4). Note this is
|
|
1578
|
+
// transcript visibility only — a connector tool execution does not itself go
|
|
1579
|
+
// through the approval pipeline (that is the separate mcpServer/elicitation
|
|
1580
|
+
// request, #6635); see docs/design/codex-permission-model.md §8.
|
|
296
1581
|
if (item.type === 'commandExecution') {
|
|
297
1582
|
const toolUseId = item.id
|
|
298
1583
|
this.emit('tool_start', {
|
|
@@ -304,13 +1589,38 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
304
1589
|
this._trackToolStart(toolUseId, 'shell')
|
|
305
1590
|
} else if (item.type === 'fileChange') {
|
|
306
1591
|
const toolUseId = item.id
|
|
1592
|
+
const changes = item.changes ?? item.patch ?? null
|
|
307
1593
|
this.emit('tool_start', {
|
|
308
1594
|
messageId: this._activeTurn.messageId,
|
|
309
1595
|
toolUseId,
|
|
310
1596
|
tool: 'apply_patch',
|
|
311
|
-
input: { changes
|
|
1597
|
+
input: { changes },
|
|
312
1598
|
})
|
|
313
1599
|
this._trackToolStart(toolUseId, 'apply_patch')
|
|
1600
|
+
// #6638: remember the changes so a later fileChange approval (keyed by the
|
|
1601
|
+
// same itemId, but carrying no diff) can show what will change. Only cache a
|
|
1602
|
+
// non-null diff — a null-change item would just waste a slot and evict a real
|
|
1603
|
+
// diff earlier. Bounded: deleted on item completion / cleared per turn; evict
|
|
1604
|
+
// oldest at the cap.
|
|
1605
|
+
if (toolUseId != null && changes != null) {
|
|
1606
|
+
if (this._pendingFileChanges.size >= MAX_PENDING_FILE_CHANGES) {
|
|
1607
|
+
this._pendingFileChanges.delete(this._pendingFileChanges.keys().next().value)
|
|
1608
|
+
}
|
|
1609
|
+
this._pendingFileChanges.set(toolUseId, changes)
|
|
1610
|
+
}
|
|
1611
|
+
} else if (item.type === 'mcpToolCall') {
|
|
1612
|
+
// #6684: surface a connector tool EXECUTION in the transcript, labelled
|
|
1613
|
+
// `server/tool` (e.g. `github/create_issue`) so the source connector is
|
|
1614
|
+
// clear, with the call arguments as the input.
|
|
1615
|
+
const toolUseId = item.id
|
|
1616
|
+
const tool = this._mcpToolLabel(item)
|
|
1617
|
+
this.emit('tool_start', {
|
|
1618
|
+
messageId: this._activeTurn.messageId,
|
|
1619
|
+
toolUseId,
|
|
1620
|
+
tool,
|
|
1621
|
+
input: { server: item.server, tool: item.tool, arguments: item.arguments },
|
|
1622
|
+
})
|
|
1623
|
+
this._trackToolStart(toolUseId, tool)
|
|
314
1624
|
}
|
|
315
1625
|
}
|
|
316
1626
|
|
|
@@ -322,7 +1632,18 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
322
1632
|
} else if (item.type === 'fileChange') {
|
|
323
1633
|
this.emit('tool_result', { toolUseId: item.id, result: item.status ?? '' })
|
|
324
1634
|
this._trackToolResult(item.id)
|
|
1635
|
+
if (item.id != null) this._pendingFileChanges.delete(item.id) // #6638: done — release the cached diff
|
|
1636
|
+
} else if (item.type === 'mcpToolCall') {
|
|
1637
|
+
// #6684/#6712: emit the connector tool's output as a tool_result. A failed
|
|
1638
|
+
// call surfaces error.message as the result text AND flags `isError` (which
|
|
1639
|
+
// now round-trips the wire → clients style the error). Large output is
|
|
1640
|
+
// capped and flagged `truncated`.
|
|
1641
|
+
const { result, truncated } = this._summarizeMcpResult(item)
|
|
1642
|
+
const isError = item.status === 'failed' || item.error != null
|
|
1643
|
+
this.emit('tool_result', { toolUseId: item.id, result, truncated, isError })
|
|
1644
|
+
this._trackToolResult(item.id)
|
|
325
1645
|
} else if (item.type === 'agentMessage') {
|
|
1646
|
+
this.emit('assistant_response', { responseId: item.id, text: assistantResponseText(item.text) })
|
|
326
1647
|
// Fallback: if the final text never arrived as deltas (short replies can
|
|
327
1648
|
// skip the delta stream), emit it once so the message isn't lost.
|
|
328
1649
|
if (!this._activeTurn.didStreamStart && item.text) {
|
|
@@ -332,28 +1653,352 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
332
1653
|
}
|
|
333
1654
|
}
|
|
334
1655
|
|
|
1656
|
+
// #6684: `server/tool` label for an mcpToolCall (e.g. `github/create_issue`),
|
|
1657
|
+
// degrading to whichever of the two is present, else a generic `mcp`.
|
|
1658
|
+
_mcpToolLabel(item) {
|
|
1659
|
+
const server = typeof item?.server === 'string' ? item.server.trim() : ''
|
|
1660
|
+
const tool = typeof item?.tool === 'string' ? item.tool.trim() : ''
|
|
1661
|
+
if (server && tool) return `${server}/${tool}`
|
|
1662
|
+
return tool || server || 'mcp'
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
// #6684: reduce an mcpToolCall completion to a { result, truncated } tool_result
|
|
1666
|
+
// (the caller adds `isError` from the item status). Prefers the connector's
|
|
1667
|
+
// error message, then the MCP content array (text parts inline, non-text parts
|
|
1668
|
+
// as a `[type]` marker), then structuredContent, then the bare status so the
|
|
1669
|
+
// card is never blank. Text is bounded by MAX_MCP_RESULT_CHARS.
|
|
1670
|
+
_summarizeMcpResult(item) {
|
|
1671
|
+
if (item?.error && typeof item.error.message === 'string' && item.error.message) {
|
|
1672
|
+
return this._capMcpResult(item.error.message)
|
|
1673
|
+
}
|
|
1674
|
+
const content = item?.result?.content
|
|
1675
|
+
if (Array.isArray(content) && content.length > 0) {
|
|
1676
|
+
const text = content
|
|
1677
|
+
.map((c) => (c && typeof c.text === 'string' ? c.text : c && typeof c.type === 'string' ? `[${c.type}]` : null))
|
|
1678
|
+
.filter(Boolean)
|
|
1679
|
+
.join('\n')
|
|
1680
|
+
if (text) return this._capMcpResult(text)
|
|
1681
|
+
}
|
|
1682
|
+
if (item?.result?.structuredContent != null) {
|
|
1683
|
+
return this._capMcpResult(JSON.stringify(item.result.structuredContent))
|
|
1684
|
+
}
|
|
1685
|
+
return { result: item?.status ?? '', truncated: false }
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
// Cap the rendered text at MAX_MCP_RESULT_CHARS, signalling an over-cap slice via
|
|
1689
|
+
// the wire `truncated` flag (ServerToolResultSchema.truncated → store-core's
|
|
1690
|
+
// toolResultTruncated) rather than an in-band marker.
|
|
1691
|
+
_capMcpResult(text) {
|
|
1692
|
+
const s = String(text)
|
|
1693
|
+
if (s.length > MAX_MCP_RESULT_CHARS) {
|
|
1694
|
+
return { result: s.slice(0, MAX_MCP_RESULT_CHARS), truncated: true }
|
|
1695
|
+
}
|
|
1696
|
+
return { result: s, truncated: false }
|
|
1697
|
+
}
|
|
1698
|
+
|
|
335
1699
|
_ensureStreamStart() {
|
|
336
1700
|
if (this._activeTurn.didStreamStart) return
|
|
337
1701
|
this._activeTurn.didStreamStart = true
|
|
338
1702
|
this.emit('stream_start', { messageId: this._activeTurn.messageId })
|
|
339
1703
|
}
|
|
340
1704
|
|
|
1705
|
+
/**
|
|
1706
|
+
* #7729 — the one consumer of `thread/tokenUsage/updated`. It carries THREE
|
|
1707
|
+
* independent facts and they are handled separately:
|
|
1708
|
+
*
|
|
1709
|
+
* - the token breakdown, mapped onto chroxy's accounting keys — a DELTA of
|
|
1710
|
+
* the cumulative `total` since turn start (#7773);
|
|
1711
|
+
* - the context-window OCCUPANCY snapshot the meter reads (#7794);
|
|
1712
|
+
* - `tokenUsage.modelContextWindow`, which is the model's REAL window as
|
|
1713
|
+
* reported by the binary running it — authoritative, and the only source
|
|
1714
|
+
* that exists: `model/list` does not carry a window at all.
|
|
1715
|
+
*
|
|
1716
|
+
* #7773 — `_threadTotals` is advanced LAST, and deliberately after
|
|
1717
|
+
* `_mapUsage` has read it: the delta is always measured from the baseline
|
|
1718
|
+
* frozen at turn start, never from the previous notification, so N
|
|
1719
|
+
* notifications in one turn each report that turn's running sum rather than
|
|
1720
|
+
* one response's slice.
|
|
1721
|
+
*/
|
|
1722
|
+
_onTokenUsage(params) {
|
|
1723
|
+
this._lastUsage = this._mapUsage(params)
|
|
1724
|
+
this._lastOccupancy = this._buildOccupancy(params)
|
|
1725
|
+
this._applyContextWindow(params)
|
|
1726
|
+
const total = params?.tokenUsage?.total
|
|
1727
|
+
if (total && typeof total === 'object') this._threadTotals = total
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
/**
|
|
1731
|
+
* #7794 — the context-window OCCUPANCY snapshot (wire field
|
|
1732
|
+
* `contextOccupancy`, NOT the billing `usage` aggregate beside it) built from
|
|
1733
|
+
* codex's own numbers, so a codex session's context meter renders instead of
|
|
1734
|
+
* staying dashed forever.
|
|
1735
|
+
*
|
|
1736
|
+
* **The series is `tokenUsage.last`, NOT `tokenUsage.total`** — #7794's body
|
|
1737
|
+
* specifies `total.total_tokens` and that is WRONG, falsified by a live
|
|
1738
|
+
* two-turn probe against codex-cli 0.154.0 (gpt-5.5, thread
|
|
1739
|
+
* 01a09778-0c52-7c41-8d24-e4f4ff68b708):
|
|
1740
|
+
*
|
|
1741
|
+
* turn 1: total.totalTokens=14962 last.totalTokens=14962
|
|
1742
|
+
* turn 2: total.totalTokens=31920 last.totalTokens=16958 (14962+16958)
|
|
1743
|
+
*
|
|
1744
|
+
* `total` is the thread-CUMULATIVE sum of every response's usage. Metered as
|
|
1745
|
+
* occupancy it grows without bound, reads 100% of a 258400 window after ~15
|
|
1746
|
+
* turns of a real session, and can never step down after a compaction — the
|
|
1747
|
+
* exact failure #7794's own second acceptance criterion forbids. `last` is
|
|
1748
|
+
* the most recent response: `inputTokens` is the conversation as codex last
|
|
1749
|
+
* sent it and `totalTokens` is that prompt plus the reply
|
|
1750
|
+
* (14935+27=14962, 16937+21=16958), i.e. the size the NEXT turn starts from.
|
|
1751
|
+
* That follows a compaction down, which is the #6769 semantics.
|
|
1752
|
+
*
|
|
1753
|
+
* No `source` field: the protocol enum has values for the SDK control API and
|
|
1754
|
+
* byok's final-round estimate, and this is neither. Absent parses to
|
|
1755
|
+
* `source: null` client-side, which renders the value un-flagged rather than
|
|
1756
|
+
* labelled an estimate — correct, since these are the binary's own figures.
|
|
1757
|
+
*
|
|
1758
|
+
* Returns null (field omitted, clients keep their previous snapshot / dash)
|
|
1759
|
+
* for the flat legacy shape, a missing/malformed `last`, or a zero total —
|
|
1760
|
+
* never a fabricated number (#5444).
|
|
1761
|
+
*/
|
|
1762
|
+
_buildOccupancy(params) {
|
|
1763
|
+
const last = params?.tokenUsage?.last
|
|
1764
|
+
if (!last || typeof last !== 'object') return null
|
|
1765
|
+
const totalTokens = nonNegInt(last.totalTokens)
|
|
1766
|
+
if (totalTokens <= 0) return null
|
|
1767
|
+
const win = params?.tokenUsage?.modelContextWindow
|
|
1768
|
+
return {
|
|
1769
|
+
totalTokens,
|
|
1770
|
+
// Omitted rather than null when codex reported no window: the client's
|
|
1771
|
+
// ceiling resolution then falls back to the registry window, which the
|
|
1772
|
+
// ratchet may still have. `maxTokens: null` would mean the same thing to
|
|
1773
|
+
// `contextMeterCeiling`, but omitting keeps "codex said nothing" and
|
|
1774
|
+
// "codex said null" from being spelled differently on the wire.
|
|
1775
|
+
...(Number.isFinite(win) && win > 0 ? { maxTokens: win } : {}),
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
/**
|
|
1780
|
+
* #7729 — write codex's own `modelContextWindow` to the codex registry as
|
|
1781
|
+
* authoritative, falling back to the observed-tokens ratchet when the binary
|
|
1782
|
+
* did not report one.
|
|
1783
|
+
*
|
|
1784
|
+
* Three properties are deliberate:
|
|
1785
|
+
*
|
|
1786
|
+
* - **No `models_updated` emit from either path.** The reason is #7729's
|
|
1787
|
+
* AC, which rules the global broadcast out — NOT per-turn cost. The cost
|
|
1788
|
+
* argument would in fact be wrong: `if (!changed) return false` below
|
|
1789
|
+
* sits ahead of where any emit would go, so an emit would fire at most
|
|
1790
|
+
* once per model per WINDOW CHANGE, not on every token update. What it
|
|
1791
|
+
* would still be is a GLOBAL broadcast (`ws-forwarding.js` →
|
|
1792
|
+
* `available_models` to EVERY client) originated by one session's turn,
|
|
1793
|
+
* and that shape is what the AC forbids. #7728 fixed the client-side
|
|
1794
|
+
* slot, so such a broadcast is harmless — harmless is not the same as
|
|
1795
|
+
* wanted. The registry write persists via `saveCache()` and reaches
|
|
1796
|
+
* clients on the next roster refresh; closing that last hop with a
|
|
1797
|
+
* SESSION-scoped push is #7774.
|
|
1798
|
+
* - **A missing/unusable window is a cannot-check, not a zero.** 0,
|
|
1799
|
+
* negative, NaN and null all leave the registry entry exactly as it was
|
|
1800
|
+
* and fall through to the ratchet — they never write, and they never
|
|
1801
|
+
* substitute a default. A brand-new session that has not completed a turn
|
|
1802
|
+
* therefore has NO window and its meter stays dashed; fabricating one
|
|
1803
|
+
* would be worse than none (#5444).
|
|
1804
|
+
* - **`Number.isFinite` guards the call.** `registry.updateContextWindow`
|
|
1805
|
+
* tests `typeof === 'number' && > 0`, which NaN passes (`NaN <= 0` is
|
|
1806
|
+
* false) — it would then write NaN, since `x !== NaN` is always true.
|
|
1807
|
+
*
|
|
1808
|
+
* @returns {boolean} true when the registry entry changed.
|
|
1809
|
+
*/
|
|
1810
|
+
_applyContextWindow(params) {
|
|
1811
|
+
const modelId = this._effectiveModelId()
|
|
1812
|
+
// Unknown model → nothing to key the window on. The ratchet is equally
|
|
1813
|
+
// inert here (it no-ops on an id the registry does not carry), so this is
|
|
1814
|
+
// an early return, not a behaviour difference.
|
|
1815
|
+
if (!modelId) return false
|
|
1816
|
+
|
|
1817
|
+
const reported = params?.tokenUsage?.modelContextWindow
|
|
1818
|
+
if (!Number.isFinite(reported) || reported <= 0) {
|
|
1819
|
+
// Codex did not report a window on this update — fall back to the shared
|
|
1820
|
+
// learn-loop, which can only ratchet UP off an observed prompt size.
|
|
1821
|
+
// Deliberately no emit callback: see above.
|
|
1822
|
+
//
|
|
1823
|
+
// The ratchet is fed the WHOLE prompt (codex's `inputTokens`, of which
|
|
1824
|
+
// `cachedInputTokens` is a subset), NOT `_lastUsage.input_tokens` — that
|
|
1825
|
+
// is the DISJOINT uncached half _mapUsage emits for accounting, and a
|
|
1826
|
+
// cache-heavy turn still occupies the full prompt in the context window.
|
|
1827
|
+
// codex-session.js:760 warns against conflating exactly these two.
|
|
1828
|
+
const u = this._usageBreakdown(params)
|
|
1829
|
+
const promptTokens = nonNegInt(u.inputTokens ?? u.input_tokens)
|
|
1830
|
+
if (promptTokens <= 0) return false
|
|
1831
|
+
return maybeRatchetContextWindow('codex', modelId, promptTokens)
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
const registry = getRegistryForProvider('codex')
|
|
1835
|
+
if (!registry || typeof registry.updateContextWindow !== 'function') return false
|
|
1836
|
+
const changed = registry.updateContextWindow(modelId, reported)
|
|
1837
|
+
if (!changed) return false
|
|
1838
|
+
// #4413 — persist so a restart keeps the authoritative window. Idempotent
|
|
1839
|
+
// and warn-on-failure, like the ratchet's own save.
|
|
1840
|
+
if (typeof registry.saveCache === 'function') registry.saveCache()
|
|
1841
|
+
;(this._log || log).info(`codex reported context window ${reported} for ${modelId} (authoritative)`)
|
|
1842
|
+
return true
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
/**
|
|
1846
|
+
* #7729 — the LAST RESPONSE's token breakdown inside a
|
|
1847
|
+
* `thread/tokenUsage/updated` payload, for every shape this session has to
|
|
1848
|
+
* read.
|
|
1849
|
+
*
|
|
1850
|
+
* The LIVE shape is `{threadId, turnId, tokenUsage: {total, last,
|
|
1851
|
+
* modelContextWindow}}` (verified against codex-cli 0.154.0), so the
|
|
1852
|
+
* pre-existing `params.usage` read found nothing there and every token count
|
|
1853
|
+
* mapped to zero. `params.usage` keeps its precedence for any caller/build
|
|
1854
|
+
* still using the flat shape.
|
|
1855
|
+
*
|
|
1856
|
+
* #7773 — the docstring here USED to call this "the per-turn token
|
|
1857
|
+
* breakdown", which is more than `last` delivers: `last` is one model
|
|
1858
|
+
* RESPONSE, and a coding turn with N tool round-trips emits N notifications.
|
|
1859
|
+
* The per-turn figure is `_turnUsageBreakdown` below. This one keeps
|
|
1860
|
+
* one-response semantics on purpose, because the context-window RATCHET in
|
|
1861
|
+
* `_applyContextWindow` wants a single response's prompt size — summing a
|
|
1862
|
+
* turn's responses there would ratchet the learned window far above the real
|
|
1863
|
+
* one.
|
|
1864
|
+
*/
|
|
1865
|
+
_usageBreakdown(params) {
|
|
1866
|
+
return params?.usage || params?.tokenUsage?.last || params || {}
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
/**
|
|
1870
|
+
* #7773 — THIS TURN's token breakdown: `tokenUsage.total` minus the
|
|
1871
|
+
* cumulative baseline frozen at turn start.
|
|
1872
|
+
*
|
|
1873
|
+
* `total` is CUMULATIVE over the thread. Proven live on codex-cli 0.154.0
|
|
1874
|
+
* (two turns, one thread — full capture in `_buildOccupancy`): turn 2
|
|
1875
|
+
* reported `total.totalTokens = 31920` for `last.totalTokens = 16958`,
|
|
1876
|
+
* exactly turn 1's 14962 plus turn 2's 16958. So neither raw field is the
|
|
1877
|
+
* turn:
|
|
1878
|
+
*
|
|
1879
|
+
* - `total` compounds — session-manager's `_trackUsage` ADDS `result.usage`
|
|
1880
|
+
* into `cumulativeUsage` once per turn, so reporting a running total
|
|
1881
|
+
* re-counts the whole thread every turn (the #7767 rationale, correct);
|
|
1882
|
+
* - `last` DROPS — every response but the final one of the turn is thrown
|
|
1883
|
+
* away, a systematic undercount concentrated on exactly the tool-heavy
|
|
1884
|
+
* turns that dominate a coding session (#7773).
|
|
1885
|
+
*
|
|
1886
|
+
* The delta does neither, and it is what every other chroxy provider reports
|
|
1887
|
+
* (an Anthropic turn sums all of its requests).
|
|
1888
|
+
*
|
|
1889
|
+
* Measured from the TURN BASELINE rather than the previous notification, so
|
|
1890
|
+
* the value is the turn's running sum on each of N notifications and the
|
|
1891
|
+
* final one — the only one `_finishTurn` reports — is the whole turn.
|
|
1892
|
+
*
|
|
1893
|
+
* Every field is clamped at 0 by `nonNegInt`, so a `total` that moved
|
|
1894
|
+
* BACKWARDS (a resumed thread, or a future build that resets its counters
|
|
1895
|
+
* after compacting) undercounts rather than emitting a negative into an
|
|
1896
|
+
* accumulator.
|
|
1897
|
+
*
|
|
1898
|
+
* Falls through to `_usageBreakdown` when there is no `total` to difference:
|
|
1899
|
+
* the flat `params.usage` shape, and any build that stops sending `total`.
|
|
1900
|
+
*/
|
|
1901
|
+
_turnUsageBreakdown(params) {
|
|
1902
|
+
if (params?.usage) return params.usage
|
|
1903
|
+
const total = params?.tokenUsage?.total
|
|
1904
|
+
if (!total || typeof total !== 'object') return this._usageBreakdown(params)
|
|
1905
|
+
const base = this._turnBaselineTotals
|
|
1906
|
+
if (!base || typeof base !== 'object') return this._nativeUsageBaselineUnknown ? this._usageBreakdown(params) : total
|
|
1907
|
+
const delta = (key) => nonNegInt(nonNegInt(total[key]) - nonNegInt(base[key]))
|
|
1908
|
+
return {
|
|
1909
|
+
totalTokens: delta('totalTokens'),
|
|
1910
|
+
inputTokens: delta('inputTokens'),
|
|
1911
|
+
cachedInputTokens: delta('cachedInputTokens'),
|
|
1912
|
+
cacheWriteInputTokens: delta('cacheWriteInputTokens'),
|
|
1913
|
+
outputTokens: delta('outputTokens'),
|
|
1914
|
+
reasoningOutputTokens: delta('reasoningOutputTokens'),
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
|
|
341
1918
|
_mapUsage(params) {
|
|
342
|
-
const u = params
|
|
1919
|
+
const u = this._turnUsageBreakdown(params)
|
|
1920
|
+
const rawInput = nonNegInt(u.inputTokens ?? u.input_tokens)
|
|
1921
|
+
const cached = nonNegInt(u.cachedInputTokens ?? u.cached_input_tokens)
|
|
343
1922
|
return {
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
1923
|
+
// #6692: codex reports cached tokens as a SUBSET of input (OpenAI's
|
|
1924
|
+
// prompt_tokens_details convention; corroborated in-repo by the exec
|
|
1925
|
+
// path's context ratchet treating input_tokens as the full prompt —
|
|
1926
|
+
// codex-session.js). Chroxy's accounting keys are ADDITIVE (Anthropic
|
|
1927
|
+
// shape: input excludes cache reads), so split into uncached input +
|
|
1928
|
+
// cache_read. The subtraction is clamped, so a future codex build that
|
|
1929
|
+
// switched to additive reporting would undercount input rather than
|
|
1930
|
+
// go negative. Before this fix the cache count was emitted only under
|
|
1931
|
+
// `cached_input_tokens`, a key `_trackUsage` never reads — codex cache
|
|
1932
|
+
// tokens were silently dropped from cumulativeUsage.
|
|
1933
|
+
input_tokens: nonNegInt(rawInput - cached),
|
|
1934
|
+
output_tokens: nonNegInt(u.outputTokens ?? u.output_tokens),
|
|
1935
|
+
cache_read_input_tokens: cached,
|
|
1936
|
+
// Deprecated duplicate of cache_read_input_tokens — kept one release
|
|
1937
|
+
// for any external reader of the raw result payload (#6692).
|
|
1938
|
+
cached_input_tokens: cached,
|
|
1939
|
+
// #7773 — `TokenUsageBreakdown` has six fields and this maps three;
|
|
1940
|
+
// the other two are UNREAD ON PURPOSE, and a test pins each.
|
|
1941
|
+
//
|
|
1942
|
+
// - `reasoningOutputTokens` is a SUBSET of `outputTokens`, proven by
|
|
1943
|
+
// the live capture's own arithmetic: totalTokens 14962 =
|
|
1944
|
+
// inputTokens 14935 + outputTokens 27, while reasoningOutputTokens
|
|
1945
|
+
// was 20. Were it additive, totalTokens would have been 14982. So
|
|
1946
|
+
// `output_tokens` above already contains it and adding it anywhere
|
|
1947
|
+
// would double count. Surfacing it SEPARATELY for display is
|
|
1948
|
+
// #7730/#6942, not an accounting key.
|
|
1949
|
+
// - `cacheWriteInputTokens` maps to NOTHING, so
|
|
1950
|
+
// `cache_creation_input_tokens` stays absent (and `_trackUsage`
|
|
1951
|
+
// accumulates 0) for every codex session. Read 0 in every capture so
|
|
1952
|
+
// far, which means its relationship to `inputTokens` is UNPROVEN —
|
|
1953
|
+
// and under the OpenAI convention the rest of this function is built
|
|
1954
|
+
// on it is plausibly another subset, where an additive map would
|
|
1955
|
+
// double count real tokens. Absent is the fail-safe reading: it
|
|
1956
|
+
// under-reports a cost line rather than inflating one. Map it the day
|
|
1957
|
+
// a capture shows it non-zero AND shows whether totalTokens counts it
|
|
1958
|
+
// twice.
|
|
347
1959
|
}
|
|
348
1960
|
}
|
|
349
1961
|
|
|
350
|
-
|
|
1962
|
+
// #7072 -- UNVERIFIED against a live binary: a turn the operator stopped may
|
|
1963
|
+
// arrive HERE. `interrupt()` sends `turn/interrupt`; if the binary answers it
|
|
1964
|
+
// with `turn/completed` (the protocol's TurnStatus enum has an `interrupted`
|
|
1965
|
+
// value, which this method never reads) rather than an `error` notification, the
|
|
1966
|
+
// cut-off turn is reported below as a NORMAL result with no `interrupted` mark, and
|
|
1967
|
+
// an orchestration TurnDriver settles it as a success. Do not infer the binary's
|
|
1968
|
+
// behaviour from tests: #6606's C1 test only MODELS turn/completed-after-interrupt.
|
|
1969
|
+
// Pin it with a live probe before changing this.
|
|
1970
|
+
_finishTurn(turn, turnId = null) {
|
|
351
1971
|
if (!this._activeTurn) return
|
|
352
1972
|
const t = this._activeTurn
|
|
1973
|
+
// #8710 — codex ended this turn: a straggler naming it is never taken for a
|
|
1974
|
+
// live turn, or for the next one.
|
|
1975
|
+
this._noteNativeTurnEnded(turnId ?? t.turnId)
|
|
1976
|
+
// Completion can precede the RPC acknowledgement. Persist first-turn skills
|
|
1977
|
+
// admission before result listeners save the now-completed native session.
|
|
1978
|
+
this._skillsPrepended = true
|
|
353
1979
|
this._clearResultTimeout()
|
|
354
|
-
if (t.didStreamStart) this.emit('stream_end', { messageId: t.messageId })
|
|
1980
|
+
if (t.didStreamStart) this.emit('stream_end', { messageId: t.messageId, ...(turn?.status && turn.status !== 'completed' ? { interrupted: true } : {}) })
|
|
355
1981
|
this._emitResult(
|
|
356
|
-
{
|
|
1982
|
+
{
|
|
1983
|
+
cost: null,
|
|
1984
|
+
duration: turn?.durationMs ?? null,
|
|
1985
|
+
declarationEligible: turn?.status === 'completed' && !turn?.error,
|
|
1986
|
+
usage: this._lastUsage,
|
|
1987
|
+
// #6692: single-model split (codex runs one model per session; cost
|
|
1988
|
+
// is unknown at the source — pricing happens downstream).
|
|
1989
|
+
// #7729: key on the EFFECTIVE model. `this.model` is null whenever the
|
|
1990
|
+
// operator left codex to pick, and synthesizeModelUsage returns null
|
|
1991
|
+
// for a null id — so before the thread/start echo was captured, every
|
|
1992
|
+
// default codex session's per-model usage split was silently dropped.
|
|
1993
|
+
modelUsage: synthesizeModelUsage(this._effectiveModelId(), this._lastUsage),
|
|
1994
|
+
sessionId: this._threadId,
|
|
1995
|
+
// #7794 — occupancy snapshot, or the field omitted entirely when codex
|
|
1996
|
+
// sent no usable one (clients then keep their previous snapshot / the
|
|
1997
|
+
// honest dash). Wire name is contextOccupancy, NOT contextUsage: the
|
|
1998
|
+
// `usage` field above is the billing aggregate and must never be
|
|
1999
|
+
// metered against the window (#6769).
|
|
2000
|
+
...(this._lastOccupancy ? { contextOccupancy: this._lastOccupancy } : {}),
|
|
2001
|
+
},
|
|
357
2002
|
'turn_ended_with_orphan_tool_start',
|
|
358
2003
|
)
|
|
359
2004
|
this._activeTurn = null
|
|
@@ -364,22 +2009,71 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
364
2009
|
// would mis-report a LATER genuine error as a clean `stopped` (#4881 race).
|
|
365
2010
|
this._clearIntentionalStop()
|
|
366
2011
|
this._clearMessageState()
|
|
2012
|
+
// #8710 — codex reports a turn its error ended (a usage limit, among others)
|
|
2013
|
+
// as `failed`, with the error beside it. The result above keeps the turn's
|
|
2014
|
+
// usage accounted; this says the work did not finish. Normally the `error`
|
|
2015
|
+
// notification ahead of it has already failed the turn, and this
|
|
2016
|
+
// `turn/completed` never gets here.
|
|
2017
|
+
if (turn?.status === 'failed') {
|
|
2018
|
+
const payload = this._terminalErrorPayload(turn.error, turn.error)
|
|
2019
|
+
;(this._log || log).warn(`codex app-server turn failed: ${payload.message}`)
|
|
2020
|
+
this.emit('error', payload)
|
|
2021
|
+
}
|
|
2022
|
+
this._observeNativeSettings()
|
|
367
2023
|
this._maybeDequeue()
|
|
368
2024
|
}
|
|
369
2025
|
|
|
370
|
-
|
|
2026
|
+
// #6629 — `code` lets the reconnect-watchdog surface its failure as
|
|
2027
|
+
// `error{code:'stream_stall'}` so clients reuse the existing recoverable-stall
|
|
2028
|
+
// retry chip (parity with SdkSession's stall recovery) instead of rendering a
|
|
2029
|
+
// bare, non-actionable error. An intentional stop still wins and reports `stopped`.
|
|
2030
|
+
_failTurn(message, { code } = {}) {
|
|
371
2031
|
this._clearResultTimeout()
|
|
372
2032
|
const t = this._activeTurn
|
|
373
2033
|
if (t?.didStreamStart) this.emit('stream_end', { messageId: t.messageId })
|
|
374
2034
|
const wasIntentional = this._consumeIntentionalStop()
|
|
375
2035
|
if (wasIntentional) this.emit('stopped', {})
|
|
376
|
-
else this.emit('error', { message })
|
|
2036
|
+
else this.emit('error', code ? { message, code } : { message })
|
|
377
2037
|
this._activeTurn = null
|
|
378
2038
|
this._endTurnAbort()
|
|
379
2039
|
this._clearMessageState()
|
|
380
2040
|
this._maybeDequeue()
|
|
381
2041
|
}
|
|
382
2042
|
|
|
2043
|
+
// #6623 — codex's `error` notification carries the error under an `error` wrapper
|
|
2044
|
+
// in the wild ({ error: { message, codexErrorInfo, ... } }) but a bare shape
|
|
2045
|
+
// ({ message, ... }) elsewhere. Normalize to the inner error object either way so
|
|
2046
|
+
// the callers read one shape.
|
|
2047
|
+
_errorPayload(params) {
|
|
2048
|
+
return params?.error && typeof params.error === 'object' ? params.error : (params || {})
|
|
2049
|
+
}
|
|
2050
|
+
|
|
2051
|
+
// #6623 — true iff this error is codex's OWN transient response-stream reconnect
|
|
2052
|
+
// (its retry loop is still running) rather than a terminal failure. Codex tags the
|
|
2053
|
+
// retry with BOTH `codexErrorInfo.responseStreamDisconnected` AND a
|
|
2054
|
+
// `Reconnecting... N/M` message; the terminal give-up drops the reconnecting
|
|
2055
|
+
// message (or is a different error entirely), so it still fails the turn. Gating
|
|
2056
|
+
// on both keeps the suppression conservative — anything not clearly a retry falls
|
|
2057
|
+
// through to _failTurn.
|
|
2058
|
+
_isTransientReconnect(err) {
|
|
2059
|
+
const info = err?.codexErrorInfo
|
|
2060
|
+
const disconnected = info && typeof info === 'object' && info.responseStreamDisconnected != null
|
|
2061
|
+
if (!disconnected) return false
|
|
2062
|
+
return /reconnect/i.test(typeof err?.message === 'string' ? err.message : '')
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
// #6638: also release cached fileChange diffs when per-turn state is cleared
|
|
2066
|
+
// (turn end / fail / destroy), so a diff can't outlive its turn.
|
|
2067
|
+
// #7340: forward the opts to super. `turnEndedCleanly` decides whether a
|
|
2068
|
+
// confirmed-backgrounded subagent survives BaseSession's turn-end sweep;
|
|
2069
|
+
// an override that drops it silently disables the exemption.
|
|
2070
|
+
_clearMessageState(opts) {
|
|
2071
|
+
super._clearMessageState(opts)
|
|
2072
|
+
this._pendingFileChanges.clear()
|
|
2073
|
+
this._clearReconnectWatchdog() // #6629 — drop the reconnect backstop on any turn teardown
|
|
2074
|
+
this._clearReconnectDeadline() // #6856 — drop the suppression deadline on any turn teardown
|
|
2075
|
+
}
|
|
2076
|
+
|
|
383
2077
|
// Abort this turn's approval scope (any pending permission_request resolves as
|
|
384
2078
|
// a deny) and drop the controller. Safe to call with no active turn.
|
|
385
2079
|
_endTurnAbort() {
|
|
@@ -412,31 +2106,91 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
412
2106
|
if (this._resultTimeout) { clearTimeout(this._resultTimeout); this._resultTimeout = null }
|
|
413
2107
|
}
|
|
414
2108
|
|
|
2109
|
+
// #6629 — bounded reconnect watchdog. Armed when #6623 keeps a turn open on a
|
|
2110
|
+
// transient response-stream reconnect; unlike the result timeout it is NOT
|
|
2111
|
+
// paused by a pending permission, so a codex that wedges mid-reconnect (never
|
|
2112
|
+
// recovers, never emits its terminal give-up) still reconciles the stale
|
|
2113
|
+
// working state promptly. Re-armed (clear + set) on each reconnect tick so
|
|
2114
|
+
// codex's legit multi-attempt retry burst doesn't trip it — it only fires
|
|
2115
|
+
// after a full window of silence following the last thing codex said. Disarmed
|
|
2116
|
+
// by any genuine forward-progress notification (recovery) and on turn teardown.
|
|
2117
|
+
_armReconnectWatchdog() {
|
|
2118
|
+
this._clearReconnectWatchdog()
|
|
2119
|
+
this._reconnectWatchdog = setTimeout(() => {
|
|
2120
|
+
this._reconnectWatchdog = null
|
|
2121
|
+
if (!this._activeTurn) return
|
|
2122
|
+
// #6629 — INTENTIONAL that this fires even while a permission prompt is
|
|
2123
|
+
// pending. The watchdog only arms on a genuine disconnect and is disarmed by
|
|
2124
|
+
// ANY forward-progress notification, so reaching this callback means codex
|
|
2125
|
+
// emitted no ticks and made no progress for the full window — the response
|
|
2126
|
+
// stream is genuinely wedged and the turn cannot complete regardless of the
|
|
2127
|
+
// pending approval. Failing cleanly (deny the pending approval via
|
|
2128
|
+
// _endTurnAbort + surface a recoverable stall) is the actionable outcome;
|
|
2129
|
+
// deliberately NOT firing during a pending permission would just restore the
|
|
2130
|
+
// #6629 indefinite-stale-state bug (the paused result timeout is exactly what
|
|
2131
|
+
// this watchdog exists to backstop). The user can retry to continue.
|
|
2132
|
+
;(this._log || log).warn(`codex app-server response stream did not recover within ${RECONNECT_WATCHDOG_MS}ms — reconciling stale working state (#6629)`)
|
|
2133
|
+
this._failTurn('Codex response stream disconnected and did not recover — the turn was stopped. Retry to continue.', { code: 'stream_stall' })
|
|
2134
|
+
}, RECONNECT_WATCHDOG_MS)
|
|
2135
|
+
if (typeof this._reconnectWatchdog.unref === 'function') this._reconnectWatchdog.unref()
|
|
2136
|
+
}
|
|
2137
|
+
|
|
2138
|
+
_clearReconnectWatchdog() {
|
|
2139
|
+
if (this._reconnectWatchdog) { clearTimeout(this._reconnectWatchdog); this._reconnectWatchdog = null }
|
|
2140
|
+
}
|
|
2141
|
+
|
|
2142
|
+
// #6856 — one-shot HARD CAP on the transient-reconnect-suppressed state. Armed
|
|
2143
|
+
// ONCE on entering suppression; the `if (this._reconnectDeadline) return` guard
|
|
2144
|
+
// is load-bearing — a subsequent reconnect tick must NOT push the deadline out
|
|
2145
|
+
// (that re-arming is exactly the #6854 gap this closes). It is a strictly-shorter
|
|
2146
|
+
// bound than the 30-min result timeout and independent of the #6629 silence
|
|
2147
|
+
// watchdog (which keeps sliding forward on every tick). Cleared on genuine
|
|
2148
|
+
// forward progress or turn teardown. Routes through the injectable timer seam so
|
|
2149
|
+
// it is hermetically testable, and unref's the handle so a bare test/CI run
|
|
2150
|
+
// self-exits with no leaked timer (#6933).
|
|
2151
|
+
_armReconnectDeadline() {
|
|
2152
|
+
if (this._reconnectDeadline) return // already suppressed — do NOT extend the deadline
|
|
2153
|
+
this._reconnectDeadline = this._setTimer(() => {
|
|
2154
|
+
this._reconnectDeadline = null
|
|
2155
|
+
if (!this._activeTurn) return
|
|
2156
|
+
const secs = Math.round(this._reconnectDeadlineMs / 1000)
|
|
2157
|
+
;(this._log || log).warn(`codex app-server reconnect exceeded ${secs}s without recovery — failing the turn (#6856)`)
|
|
2158
|
+
this._failTurn(`Codex reconnect exceeded ${secs}s without recovery — the turn was stopped. Retry to continue.`, { code: 'stream_stall' })
|
|
2159
|
+
}, this._reconnectDeadlineMs)
|
|
2160
|
+
if (this._reconnectDeadline && typeof this._reconnectDeadline.unref === 'function') this._reconnectDeadline.unref()
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2163
|
+
_clearReconnectDeadline() {
|
|
2164
|
+
if (this._reconnectDeadline) { this._clearTimer(this._reconnectDeadline); this._reconnectDeadline = null }
|
|
2165
|
+
}
|
|
2166
|
+
|
|
415
2167
|
// ------------------------------------------------------------------
|
|
416
2168
|
// Server → client requests (approvals) — routed into the permission pipeline
|
|
417
2169
|
// ------------------------------------------------------------------
|
|
418
2170
|
|
|
419
2171
|
// Codex asks before running a command / editing a file (approvalPolicy
|
|
420
|
-
// 'on-request').
|
|
421
|
-
//
|
|
2172
|
+
// 'on-request'). All three approval families route through the PermissionManager:
|
|
2173
|
+
// command/file as decision enums, and the scope-escalation variant as a
|
|
2174
|
+
// permission-grant prompt (#6610). See docs/design/codex-permission-model.md.
|
|
422
2175
|
_onServerRequest({ id, method, params }) {
|
|
423
2176
|
if (method === 'item/commandExecution/requestApproval' || method === 'item/fileChange/requestApproval') {
|
|
424
2177
|
this._routeApproval(id, method, params)
|
|
425
2178
|
return
|
|
426
2179
|
}
|
|
427
2180
|
if (method === 'item/permissions/requestApproval') {
|
|
428
|
-
// Scope-escalation
|
|
429
|
-
//
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
//
|
|
435
|
-
//
|
|
436
|
-
//
|
|
437
|
-
//
|
|
438
|
-
|
|
439
|
-
|
|
2181
|
+
// Scope-escalation: codex wants BROADER permissions than its sandbox. Surface
|
|
2182
|
+
// it through the permission pipeline as a distinctly-worded prompt (#6610).
|
|
2183
|
+
this._routePermissionsApproval(id, params)
|
|
2184
|
+
return
|
|
2185
|
+
}
|
|
2186
|
+
if (method === 'mcpServer/elicitation/request') {
|
|
2187
|
+
// A codex MCP server (connector, e.g. GitHub) is eliciting the user — most
|
|
2188
|
+
// commonly a write/action confirmation. Previously this fell through to the
|
|
2189
|
+
// -32601 decline below, so the connector approval was silently rejected and
|
|
2190
|
+
// "missed" (#6635). Surface it as an accept/decline prompt. NOTE: structured
|
|
2191
|
+
// form-content collection and interactive url-mode flows are a follow-up —
|
|
2192
|
+
// accept currently answers with the action only, no `content`.
|
|
2193
|
+
this._routeMcpElicitation(id, params)
|
|
440
2194
|
return
|
|
441
2195
|
}
|
|
442
2196
|
;(this._log || log).warn(`codex app-server: unsupported serverRequest ${method} — declining`)
|
|
@@ -470,9 +2224,18 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
470
2224
|
// renders. `description`/`command`/`file_path` drive the human-facing prompt.
|
|
471
2225
|
_describeApproval(method, params) {
|
|
472
2226
|
if (method === 'item/fileChange/requestApproval') {
|
|
2227
|
+
// #6638: the approval params carry no diff, so correlate to the fileChange
|
|
2228
|
+
// item's cached changes (same itemId) and surface WHAT changes — a paths
|
|
2229
|
+
// summary in the description (visible with no client change) + the raw
|
|
2230
|
+
// changes for a client that renders a diff.
|
|
2231
|
+
const changes = params?.itemId != null ? this._pendingFileChanges.get(params.itemId) ?? null : null
|
|
2232
|
+
const summary = this._summarizeFileChanges(changes)
|
|
2233
|
+
const description = summary
|
|
2234
|
+
? (params?.reason ? `${params.reason} — ${summary}` : `Apply changes: ${summary}`)
|
|
2235
|
+
: (params?.reason || 'Apply file changes')
|
|
473
2236
|
return {
|
|
474
2237
|
tool: 'apply_patch',
|
|
475
|
-
input: { description
|
|
2238
|
+
input: { description, file_path: params?.grantRoot, changes },
|
|
476
2239
|
}
|
|
477
2240
|
}
|
|
478
2241
|
// item/commandExecution/requestApproval
|
|
@@ -484,6 +2247,21 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
484
2247
|
}
|
|
485
2248
|
}
|
|
486
2249
|
|
|
2250
|
+
// #6638: summarize a fileChange `changes` array (FileUpdateChange[] =
|
|
2251
|
+
// { path, kind, diff }) into a paths line for the approval prompt, e.g.
|
|
2252
|
+
// "2 files: src/a.js, src/b.js". Caps the list (+N more) so it stays bounded
|
|
2253
|
+
// for the ≤200-char prompt. Returns null when there's nothing to summarize.
|
|
2254
|
+
_summarizeFileChanges(changes) {
|
|
2255
|
+
if (!Array.isArray(changes) || changes.length === 0) return null
|
|
2256
|
+
const MAX = 3
|
|
2257
|
+
const paths = changes.map((c) => (c && typeof c.path === 'string' ? c.path : null)).filter(Boolean)
|
|
2258
|
+
if (paths.length === 0) return `${changes.length} file change(s)`
|
|
2259
|
+
const shown = paths.slice(0, MAX)
|
|
2260
|
+
const extra = paths.length - shown.length
|
|
2261
|
+
const list = shown.join(', ') + (extra > 0 ? `, +${extra} more` : '')
|
|
2262
|
+
return `${paths.length} file${paths.length === 1 ? '' : 's'}: ${list}`
|
|
2263
|
+
}
|
|
2264
|
+
|
|
487
2265
|
// The two approval families use DIFFERENT decision vocabularies (from the
|
|
488
2266
|
// app-server JSON schema): fileChange → ReviewDecision, commandExecution →
|
|
489
2267
|
// CommandExecutionApprovalDecision.
|
|
@@ -496,21 +2274,210 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
496
2274
|
return { decision: session ? 'acceptForSession' : 'accept' }
|
|
497
2275
|
}
|
|
498
2276
|
|
|
499
|
-
// '
|
|
500
|
-
//
|
|
501
|
-
//
|
|
2277
|
+
// #6610: codex's THIRD approval family — item/permissions/requestApproval — is a
|
|
2278
|
+
// scope-escalation (it wants broader filesystem/network access than its sandbox).
|
|
2279
|
+
// Unlike the command/file families the response is a permission-GRANT object
|
|
2280
|
+
// (PermissionsRequestApprovalResponse: { permissions, scope?, strictAutoReview? }),
|
|
2281
|
+
// not a decision enum, so it needs its own routing + response mapping. It still
|
|
2282
|
+
// flows through the same PermissionManager prompt (a distinctly-worded request),
|
|
2283
|
+
// so existing clients render + answer it with the normal allow/deny UI.
|
|
2284
|
+
async _routePermissionsApproval(rpcId, params) {
|
|
2285
|
+
let result
|
|
2286
|
+
try {
|
|
2287
|
+
const input = {
|
|
2288
|
+
description: this._describePermissionsRequest(params),
|
|
2289
|
+
// Structured detail for any client that wants to render the exact scope.
|
|
2290
|
+
requestedPermissions: params?.permissions ?? null,
|
|
2291
|
+
}
|
|
2292
|
+
// Sentinel suggestion → respondToPermission echoes updatedPermissions on an
|
|
2293
|
+
// "always allow", which we read as a SESSION-scoped grant (mirrors _routeApproval).
|
|
2294
|
+
const suggestions = [{ codexApproval: 'item/permissions/requestApproval' }]
|
|
2295
|
+
result = await this._permissions.handlePermission('request_permissions', input, this._turnAbort?.signal, this.permissionMode, suggestions)
|
|
2296
|
+
} catch (err) {
|
|
2297
|
+
result = { behavior: 'deny', message: err?.message || 'permission error' }
|
|
2298
|
+
}
|
|
2299
|
+
const allow = result?.behavior === 'allow'
|
|
2300
|
+
const session = allow && !!result?.updatedPermissions
|
|
2301
|
+
this._client?.respond(rpcId, this._codexPermissionsGrant(allow, session, params?.permissions))
|
|
2302
|
+
}
|
|
2303
|
+
|
|
2304
|
+
// Build the PermissionsRequestApprovalResponse. Approve → grant EXACTLY what codex
|
|
2305
|
+
// requested. RequestPermissionProfile and GrantedPermissionProfile share the same
|
|
2306
|
+
// {fileSystem?, network?} shape (the request is even additionalProperties:false), so
|
|
2307
|
+
// we reconstruct the grant from those two known fields rather than echoing the raw
|
|
2308
|
+
// request object: that grants precisely the requested scope while making a malformed
|
|
2309
|
+
// frame (an array — typeof [] === 'object' — or any unexpected key) structurally
|
|
2310
|
+
// unable to reach the wire and wedge the turn (#6612). Scope 'session' for an
|
|
2311
|
+
// "always allow" else 'turn'. Deny → an empty `permissions` object with `scope`
|
|
2312
|
+
// OMITTED (an explicit 'none' is an invalid PermissionGrantScope enum and wedges
|
|
2313
|
+
// the turn — #6612).
|
|
2314
|
+
_codexPermissionsGrant(allow, session, requestedPermissions) {
|
|
2315
|
+
if (!allow) return { permissions: {} }
|
|
2316
|
+
const src = requestedPermissions && typeof requestedPermissions === 'object' && !Array.isArray(requestedPermissions)
|
|
2317
|
+
? requestedPermissions
|
|
2318
|
+
: {}
|
|
2319
|
+
const permissions = {}
|
|
2320
|
+
if (src.fileSystem !== undefined) permissions.fileSystem = src.fileSystem
|
|
2321
|
+
if (src.network !== undefined) permissions.network = src.network
|
|
2322
|
+
return { permissions, scope: session ? 'session' : 'turn' }
|
|
2323
|
+
}
|
|
2324
|
+
|
|
2325
|
+
// Human-readable summary of the requested scope for the approval prompt, so the
|
|
2326
|
+
// operator sees WHAT codex wants to broaden before granting it. The prompt is
|
|
2327
|
+
// truncated to 200 chars downstream, so cap each list to a few entries + a
|
|
2328
|
+
// "+N more" tail (keeps the most-load-bearing detail — including the trailing
|
|
2329
|
+
// "network access" — from being sliced off) and stringify every path defensively.
|
|
2330
|
+
_describePermissionsRequest(params) {
|
|
2331
|
+
const MAX_ENTRIES = 3
|
|
2332
|
+
const summarize = (arr, render) => {
|
|
2333
|
+
const shown = arr.slice(0, MAX_ENTRIES).map(render)
|
|
2334
|
+
const extra = arr.length - shown.length
|
|
2335
|
+
return extra > 0 ? [...shown, `+${extra} more`] : shown
|
|
2336
|
+
}
|
|
2337
|
+
const parts = []
|
|
2338
|
+
const fs = params?.permissions?.fileSystem
|
|
2339
|
+
if (fs && typeof fs === 'object') {
|
|
2340
|
+
const entries = Array.isArray(fs.entries) ? fs.entries : []
|
|
2341
|
+
for (const p of summarize(entries, (e) => {
|
|
2342
|
+
const path = e?.path?.path ?? e?.path?.pattern ?? e?.path?.value?.kind ?? 'a path'
|
|
2343
|
+
return `filesystem ${e?.access ?? 'access'} → ${String(path)}`
|
|
2344
|
+
})) parts.push(p)
|
|
2345
|
+
if (Array.isArray(fs.read) && fs.read.length) parts.push(`filesystem read: ${summarize(fs.read, String).join(', ')}`)
|
|
2346
|
+
if (Array.isArray(fs.write) && fs.write.length) parts.push(`filesystem write: ${summarize(fs.write, String).join(', ')}`)
|
|
2347
|
+
}
|
|
2348
|
+
if (params?.permissions?.network?.enabled) parts.push('network access')
|
|
2349
|
+
const scope = parts.length ? parts.join('; ') : 'broader permissions'
|
|
2350
|
+
const reason = typeof params?.reason === 'string' && params.reason.trim()
|
|
2351
|
+
? ` — ${params.reason.trim()}`
|
|
2352
|
+
: ''
|
|
2353
|
+
return `Codex is requesting to broaden its sandbox permissions${reason}: ${scope}`
|
|
2354
|
+
}
|
|
2355
|
+
|
|
2356
|
+
// #6635: an MCP server (connector) is eliciting the user. Surface it as an
|
|
2357
|
+
// accept/decline prompt through the permission pipeline (was silently declined
|
|
2358
|
+
// with -32601, so a GitHub-connector write approval was "missed" and the tool
|
|
2359
|
+
// call rejected). The elicitation response is { action: accept|decline|cancel,
|
|
2360
|
+
// content? }; we answer with the action only — structured `content` collection
|
|
2361
|
+
// (form / openai/form modes) and interactive url-mode flows are a follow-up.
|
|
2362
|
+
async _routeMcpElicitation(rpcId, params) {
|
|
2363
|
+
let result
|
|
2364
|
+
try {
|
|
2365
|
+
const input = {
|
|
2366
|
+
description: this._describeMcpElicitation(params),
|
|
2367
|
+
serverName: params?.serverName ?? null,
|
|
2368
|
+
mode: params?.mode ?? null,
|
|
2369
|
+
// Surfaced so the client can show a url-mode elicitation's link.
|
|
2370
|
+
url: typeof params?.url === 'string' ? params.url : null,
|
|
2371
|
+
message: typeof params?.message === 'string' ? params.message : null,
|
|
2372
|
+
}
|
|
2373
|
+
// The sentinel is inert for this tool (unlike command/file/escalation, we
|
|
2374
|
+
// don't read updatedPermissions): an elicitation "allow" is a one-shot
|
|
2375
|
+
// accept, never a persisted rule — kept only for handlePermission symmetry.
|
|
2376
|
+
const suggestions = [{ codexApproval: 'mcpServer/elicitation/request' }]
|
|
2377
|
+
result = await this._permissions.handlePermission('mcp_elicitation', input, this._turnAbort?.signal, this.permissionMode, suggestions)
|
|
2378
|
+
} catch (err) {
|
|
2379
|
+
result = { behavior: 'deny', message: err?.message || 'permission error' }
|
|
2380
|
+
}
|
|
2381
|
+
const allow = result?.behavior === 'allow'
|
|
2382
|
+
// #6635: we can't collect structured `content` yet (#6684), so a form-mode
|
|
2383
|
+
// elicitation that REQUIRES fields is DECLINED even on allow — an action-only
|
|
2384
|
+
// accept could make the connector act on empty/default params the user never
|
|
2385
|
+
// saw. Confirmation-style (no required fields) + url-mode accept normally; a
|
|
2386
|
+
// decline is always the safe status quo (matches the pre-#6635 -32601 outcome).
|
|
2387
|
+
const action = allow && !this._elicitationRequiresContent(params) ? 'accept' : 'decline'
|
|
2388
|
+
this._client?.respond(rpcId, { action })
|
|
2389
|
+
}
|
|
2390
|
+
|
|
2391
|
+
// True when accepting would need structured `content` we can't yet collect:
|
|
2392
|
+
// `openai/form` (freeform content) or a `form` whose schema declares required
|
|
2393
|
+
// properties. `url`-mode and content-less confirmation forms return false.
|
|
2394
|
+
_elicitationRequiresContent(params) {
|
|
2395
|
+
const mode = params?.mode
|
|
2396
|
+
if (mode === 'openai/form') return true
|
|
2397
|
+
if (mode !== 'form') return false
|
|
2398
|
+
const required = params?.requestedSchema?.required
|
|
2399
|
+
return Array.isArray(required) && required.length > 0
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
// Human-readable elicitation prompt: which connector is asking, and what for.
|
|
2403
|
+
_describeMcpElicitation(params) {
|
|
2404
|
+
const server = typeof params?.serverName === 'string' && params.serverName.trim()
|
|
2405
|
+
? params.serverName.trim()
|
|
2406
|
+
: 'an MCP connector'
|
|
2407
|
+
const msg = typeof params?.message === 'string' && params.message.trim() ? params.message.trim() : ''
|
|
2408
|
+
const url = params?.mode === 'url' && typeof params?.url === 'string' && params.url.trim()
|
|
2409
|
+
? ` (opens ${params.url.trim()})`
|
|
2410
|
+
: ''
|
|
2411
|
+
// Build the two shapes explicitly rather than post-cleaning whitespace: with a
|
|
2412
|
+
// message → `connector "x" asks: <msg>`, without → `connector "x": is requesting…`.
|
|
2413
|
+
return msg
|
|
2414
|
+
? `Codex connector "${server}" asks: ${msg}${url}`
|
|
2415
|
+
: `Codex connector "${server}": is requesting your input${url}`
|
|
2416
|
+
}
|
|
2417
|
+
|
|
2418
|
+
// #8619: `on-request` in EVERY mode, Auto included. codex's own `never`
|
|
2419
|
+
// policy would emit no approval RPC, which is exactly the seam Chroxy's
|
|
2420
|
+
// protected-path / secret-read floor needs (#7825) — so Auto never maps to
|
|
2421
|
+
// it. Under Auto the PermissionManager's auto-mode path answers each request
|
|
2422
|
+
// without a prompt unless the floor reserves it for a human, which is the
|
|
2423
|
+
// same floor coverage Approve and Accept Edits have. What no mode covers is
|
|
2424
|
+
// an action the native sandbox already authorizes: codex runs those without
|
|
2425
|
+
// any RPC, in Auto as in Approve.
|
|
502
2426
|
_approvalPolicy() {
|
|
503
|
-
return
|
|
2427
|
+
return 'on-request'
|
|
504
2428
|
}
|
|
505
2429
|
|
|
506
2430
|
// In-process permission responses (capabilities.inProcessPermissions) — thin
|
|
507
2431
|
// delegators to the PermissionManager, mirroring SdkSession.
|
|
508
|
-
respondToPermission(requestId, decision, editedInput) {
|
|
509
|
-
return this._permissions.respondToPermission(requestId, decision, editedInput)
|
|
2432
|
+
respondToPermission(requestId, decision, editedInput, reason, scope) {
|
|
2433
|
+
return this._permissions.respondToPermission(requestId, decision, editedInput, reason, scope)
|
|
2434
|
+
}
|
|
2435
|
+
|
|
2436
|
+
respondToQuestion(text, answers, toolUseId) {
|
|
2437
|
+
// #8460: same shared manager, same id check as SDK/BYOK.
|
|
2438
|
+
return this._permissions.respondToQuestion(text, answers, toolUseId)
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
// #6829 — permission-rule accessors, mirroring SdkSession/ByokSession. Codex's
|
|
2442
|
+
// PermissionManager already owns a rule store (seeded per-cwd in the ctor), but
|
|
2443
|
+
// without these thin wrappers a codex session's rules were invisible on the
|
|
2444
|
+
// wire: the `permission_rules_updated` broadcast (settings-handlers.js) and the
|
|
2445
|
+
// ws-history reconnect replay (ws-history.js) both gate on `getPermissionRules`
|
|
2446
|
+
// / `getPersistentPermissionRules`, and the projectRules re-seed calls
|
|
2447
|
+
// `setPersistentPermissionRules` — so on codex an allowAlways persisted at the
|
|
2448
|
+
// enforcement layer but never broadcast, replayed, or re-seeded. Session-rule
|
|
2449
|
+
// MUTATION (`setPermissionRules`) is intentionally NOT exposed so codex keeps
|
|
2450
|
+
// advertising `sessionRules:false` in the provider picker (providers.js derives
|
|
2451
|
+
// the capability from `setPermissionRules` presence); only the durable
|
|
2452
|
+
// project-rule read/replay surface is wired.
|
|
2453
|
+
|
|
2454
|
+
/** Current session-scoped permission rules. Delegates to PermissionManager. */
|
|
2455
|
+
getPermissionRules() {
|
|
2456
|
+
if (typeof this._permissions.getRules === 'function') {
|
|
2457
|
+
return this._permissions.getRules()
|
|
2458
|
+
}
|
|
2459
|
+
return []
|
|
510
2460
|
}
|
|
511
2461
|
|
|
512
|
-
|
|
513
|
-
|
|
2462
|
+
/**
|
|
2463
|
+
* #6771/#6829 — durable (project-scoped) permission rules applied to this
|
|
2464
|
+
* session, tagged `persist:'project'`. Delegates to PermissionManager.
|
|
2465
|
+
*/
|
|
2466
|
+
getPersistentPermissionRules() {
|
|
2467
|
+
if (typeof this._permissions.getPersistentRules === 'function') {
|
|
2468
|
+
return this._permissions.getPersistentRules()
|
|
2469
|
+
}
|
|
2470
|
+
return []
|
|
2471
|
+
}
|
|
2472
|
+
|
|
2473
|
+
/**
|
|
2474
|
+
* #6771/#6829 — re-seed this session's in-memory durable rule set (no persist;
|
|
2475
|
+
* the caller owns the store write). Delegates to PermissionManager.
|
|
2476
|
+
*/
|
|
2477
|
+
setPersistentPermissionRules(rules) {
|
|
2478
|
+
if (typeof this._permissions.setPersistentRules === 'function') {
|
|
2479
|
+
this._permissions.setPersistentRules(rules)
|
|
2480
|
+
}
|
|
514
2481
|
}
|
|
515
2482
|
|
|
516
2483
|
// A permission prompt can outlast the result timeout while it waits on a human;
|
|
@@ -523,8 +2490,18 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
523
2490
|
const detail = error ? error.message : `code=${code}${signal ? ` signal=${signal}` : ''}`
|
|
524
2491
|
;(this._log || log).warn(`codex app-server exited unexpectedly (${detail})`)
|
|
525
2492
|
this._processReady = false
|
|
526
|
-
|
|
527
|
-
|
|
2493
|
+
// #6708 — app-server has no respawn, so an unexpected exit IS the terminal
|
|
2494
|
+
// signal. If the child died because its binary was quarantined/removed out
|
|
2495
|
+
// from under the running daemon, name the cause + fix instead of a bare
|
|
2496
|
+
// "exited (spawn … ENOENT)". Only relabels when the binary is unhealthy.
|
|
2497
|
+
const labeled = labelBinarySpawnFailure({
|
|
2498
|
+
attemptedPath: error?.path || this._spawnedBinary,
|
|
2499
|
+
binary: 'codex',
|
|
2500
|
+
prefix: 'Codex app-server exited',
|
|
2501
|
+
})
|
|
2502
|
+
const message = labeled || `Codex app-server exited (${detail})`
|
|
2503
|
+
if (this._activeTurn) this._failTurn(message)
|
|
2504
|
+
else this.emit('error', { message, recoverable: true })
|
|
528
2505
|
}
|
|
529
2506
|
|
|
530
2507
|
// ------------------------------------------------------------------
|
|
@@ -544,19 +2521,49 @@ export class CodexAppServerSession extends BaseSession {
|
|
|
544
2521
|
}
|
|
545
2522
|
}
|
|
546
2523
|
|
|
547
|
-
//
|
|
548
|
-
//
|
|
549
|
-
//
|
|
550
|
-
//
|
|
2524
|
+
// #3729 panic button: a switch to Auto drains the prompts already pending
|
|
2525
|
+
// as allow. `autoAllowPending` leaves a floored prompt and a sandbox-scope
|
|
2526
|
+
// escalation (`request_permissions`, NOT_DELEGABLE_TOOLS — #7975) pending for
|
|
2527
|
+
// a human, and `approvalPolicy` stays `on-request` after the switch (#8619).
|
|
551
2528
|
_onPermissionModeChanged(mode) {
|
|
552
2529
|
if (mode === 'auto') this._permissions.autoAllowPending()
|
|
553
2530
|
}
|
|
554
2531
|
|
|
2532
|
+
/**
|
|
2533
|
+
* Base dir the per-session materialized-attachment dirs live under
|
|
2534
|
+
* (#7373). Named once so `_buildTurnInput()`'s lazy creation and the boot
|
|
2535
|
+
* sweep cannot drift onto two different paths. Mirrors
|
|
2536
|
+
* `CliSession.PERMISSION_MODE_SIDECAR_BASE` and `ClaudeTuiSession.SINK_BASE`.
|
|
2537
|
+
*/
|
|
2538
|
+
static get ATTACH_BASE() { return join(tmpdir(), 'chroxy-codex-attach') }
|
|
2539
|
+
|
|
2540
|
+
/**
|
|
2541
|
+
* #7373 — boot-time sweep of materialized-attachment dirs orphaned by a
|
|
2542
|
+
* crash. destroy() removes a session's own dir, but a SIGKILL leaks it, so
|
|
2543
|
+
* a long-lived host accumulates one per crashed session that ever
|
|
2544
|
+
* materialized a binary attachment. Same ownership rule and implementation
|
|
2545
|
+
* as the claude-tui sink sweep and the claude-cli sidecar sweep — only
|
|
2546
|
+
* dirs whose `owner.pid` is DEAD are removed, so a live daemon's dirs
|
|
2547
|
+
* (including this one's) are kept and the sweep is safe to run
|
|
2548
|
+
* unconditionally at boot.
|
|
2549
|
+
*
|
|
2550
|
+
* @param {object} [logger] - logger with info/warn (defaults to module log)
|
|
2551
|
+
* @returns {{swept:number, kept:number}}
|
|
2552
|
+
*/
|
|
2553
|
+
static sweepStaleAttachDirs(logger = log) {
|
|
2554
|
+
return sweepStaleOwnedDirs(CodexAppServerSession.ATTACH_BASE, {
|
|
2555
|
+
logger,
|
|
2556
|
+
label: 'codex attach',
|
|
2557
|
+
})
|
|
2558
|
+
}
|
|
2559
|
+
|
|
555
2560
|
async destroy() {
|
|
556
2561
|
this._destroying = true
|
|
557
2562
|
this.clearOutgoingQueue({ emit: false })
|
|
558
2563
|
this._clearIntentionalStop()
|
|
559
2564
|
this._clearResultTimeout()
|
|
2565
|
+
this._clearReconnectWatchdog() // #6629 — never leave the reconnect timer armed past teardown
|
|
2566
|
+
this._clearReconnectDeadline() // #6856 — never leave the suppression deadline armed past teardown
|
|
560
2567
|
this._endTurnAbort() // resolve any in-flight approval as a deny before teardown
|
|
561
2568
|
try { this._permissions?.destroy() } catch { /* noop */ }
|
|
562
2569
|
// #6609 — drop the materialized-attachment temp dir.
|