@otto-code/server 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +31 -0
- package/README.md +111 -0
- package/dist/scripts/dev-runner.js +37 -0
- package/dist/scripts/mcp-stdio-socket-bridge-cli.mjs +62 -0
- package/dist/scripts/supervisor-entrypoint.js +141 -0
- package/dist/scripts/supervisor-log-config.js +31 -0
- package/dist/scripts/supervisor.js +252 -0
- package/dist/server/executable-resolution/executable-resolution.d.ts +10 -0
- package/dist/server/executable-resolution/executable-resolution.js +118 -0
- package/dist/server/executable-resolution/windows.d.ts +18 -0
- package/dist/server/executable-resolution/windows.js +65 -0
- package/dist/server/server/agent/activity-curator.d.ts +28 -0
- package/dist/server/server/agent/activity-curator.js +227 -0
- package/dist/server/server/agent/agent-archive.d.ts +11 -0
- package/dist/server/server/agent/agent-archive.js +16 -0
- package/dist/server/server/agent/agent-loading.d.ts +14 -0
- package/dist/server/server/agent/agent-loading.js +54 -0
- package/dist/server/server/agent/agent-manager.d.ts +470 -0
- package/dist/server/server/agent/agent-manager.js +3049 -0
- package/dist/server/server/agent/agent-personalities.d.ts +59 -0
- package/dist/server/server/agent/agent-personalities.js +103 -0
- package/dist/server/server/agent/agent-projections.d.ts +35 -0
- package/dist/server/server/agent/agent-projections.js +488 -0
- package/dist/server/server/agent/agent-prompt.d.ts +76 -0
- package/dist/server/server/agent/agent-prompt.js +230 -0
- package/dist/server/server/agent/agent-response-loop.d.ts +72 -0
- package/dist/server/server/agent/agent-response-loop.js +333 -0
- package/dist/server/server/agent/agent-sdk-types.d.ts +736 -0
- package/dist/server/server/agent/agent-sdk-types.js +22 -0
- package/dist/server/server/agent/agent-storage.d.ts +147 -0
- package/dist/server/server/agent/agent-storage.js +326 -0
- package/dist/server/server/agent/agent-stream-coalescer.d.ts +41 -0
- package/dist/server/server/agent/agent-stream-coalescer.js +166 -0
- package/dist/server/server/agent/agent-timeline-store-types.d.ts +50 -0
- package/dist/server/server/agent/agent-timeline-store-types.js +2 -0
- package/dist/server/server/agent/agent-timeline-store.d.ts +27 -0
- package/dist/server/server/agent/agent-timeline-store.js +230 -0
- package/dist/server/server/agent/audio-utils.d.ts +3 -0
- package/dist/server/server/agent/audio-utils.js +19 -0
- package/dist/server/server/agent/create-agent/create.d.ts +91 -0
- package/dist/server/server/agent/create-agent/create.js +370 -0
- package/dist/server/server/agent/create-agent-lifecycle-dispatch.d.ts +54 -0
- package/dist/server/server/agent/create-agent-lifecycle-dispatch.js +152 -0
- package/dist/server/server/agent/create-agent-mode.d.ts +13 -0
- package/dist/server/server/agent/create-agent-mode.js +62 -0
- package/dist/server/server/agent/create-agent-title.d.ts +10 -0
- package/dist/server/server/agent/create-agent-title.js +34 -0
- package/dist/server/server/agent/dictation-debug.d.ts +13 -0
- package/dist/server/server/agent/dictation-debug.js +50 -0
- package/dist/server/server/agent/effort-levels.d.ts +2 -0
- package/dist/server/server/agent/effort-levels.js +7 -0
- package/dist/server/server/agent/foreground-run-state.d.ts +50 -0
- package/dist/server/server/agent/foreground-run-state.js +160 -0
- package/dist/server/server/agent/import-sessions.d.ts +47 -0
- package/dist/server/server/agent/import-sessions.js +145 -0
- package/dist/server/server/agent/lifecycle-command.d.ts +73 -0
- package/dist/server/server/agent/lifecycle-command.js +92 -0
- package/dist/server/server/agent/mcp-server.d.ts +5 -0
- package/dist/server/server/agent/mcp-server.js +66 -0
- package/dist/server/server/agent/mcp-shared.d.ts +192 -0
- package/dist/server/server/agent/mcp-shared.js +201 -0
- package/dist/server/server/agent/pcm16-resampler.d.ts +14 -0
- package/dist/server/server/agent/pcm16-resampler.js +63 -0
- package/dist/server/server/agent/permission-response.d.ts +15 -0
- package/dist/server/server/agent/permission-response.js +14 -0
- package/dist/server/server/agent/personality-stats-store.d.ts +23 -0
- package/dist/server/server/agent/personality-stats-store.js +65 -0
- package/dist/server/server/agent/prompt-attachments.d.ts +7 -0
- package/dist/server/server/agent/prompt-attachments.js +117 -0
- package/dist/server/server/agent/provider-history-timestamps.d.ts +2 -0
- package/dist/server/server/agent/provider-history-timestamps.js +16 -0
- package/dist/server/server/agent/provider-launch-config.d.ts +43 -0
- package/dist/server/server/agent/provider-launch-config.js +167 -0
- package/dist/server/server/agent/provider-notices.d.ts +3 -0
- package/dist/server/server/agent/provider-notices.js +5 -0
- package/dist/server/server/agent/provider-registry.d.ts +41 -0
- package/dist/server/server/agent/provider-registry.js +532 -0
- package/dist/server/server/agent/provider-session-import.d.ts +10 -0
- package/dist/server/server/agent/provider-session-import.js +49 -0
- package/dist/server/server/agent/provider-snapshot-manager.d.ts +142 -0
- package/dist/server/server/agent/provider-snapshot-manager.js +690 -0
- package/dist/server/server/agent/providers/acp-agent.d.ts +353 -0
- package/dist/server/server/agent/providers/acp-agent.js +2439 -0
- package/dist/server/server/agent/providers/claude/agent.d.ts +66 -0
- package/dist/server/server/agent/providers/claude/agent.js +4535 -0
- package/dist/server/server/agent/providers/claude/feature-definitions.d.ts +8 -0
- package/dist/server/server/agent/providers/claude/feature-definitions.js +24 -0
- package/dist/server/server/agent/providers/claude/model-manifest.d.ts +90 -0
- package/dist/server/server/agent/providers/claude/model-manifest.js +205 -0
- package/dist/server/server/agent/providers/claude/models.d.ts +11 -0
- package/dist/server/server/agent/providers/claude/models.js +97 -0
- package/dist/server/server/agent/providers/claude/partial-json.d.ts +5 -0
- package/dist/server/server/agent/providers/claude/partial-json.js +306 -0
- package/dist/server/server/agent/providers/claude/project-dir.d.ts +6 -0
- package/dist/server/server/agent/providers/claude/project-dir.js +57 -0
- package/dist/server/server/agent/providers/claude/query.d.ts +17 -0
- package/dist/server/server/agent/providers/claude/query.js +86 -0
- package/dist/server/server/agent/providers/claude/rewind.d.ts +30 -0
- package/dist/server/server/agent/providers/claude/rewind.js +30 -0
- package/dist/server/server/agent/providers/claude/sidechain-tracker.d.ts +22 -0
- package/dist/server/server/agent/providers/claude/sidechain-tracker.js +232 -0
- package/dist/server/server/agent/providers/claude/task-notification-tool-call.d.ts +35 -0
- package/dist/server/server/agent/providers/claude/task-notification-tool-call.js +272 -0
- package/dist/server/server/agent/providers/claude/test-rewind-claude-sdk.d.ts +24 -0
- package/dist/server/server/agent/providers/claude/test-rewind-claude-sdk.js +23 -0
- package/dist/server/server/agent/providers/claude/tool-call-detail-parser.d.ts +3 -0
- package/dist/server/server/agent/providers/claude/tool-call-detail-parser.js +130 -0
- package/dist/server/server/agent/providers/claude/tool-call-mapper.d.ts +16 -0
- package/dist/server/server/agent/providers/claude/tool-call-mapper.js +129 -0
- package/dist/server/server/agent/providers/codex/app-server-transport.d.ts +90 -0
- package/dist/server/server/agent/providers/codex/app-server-transport.js +262 -0
- package/dist/server/server/agent/providers/codex/rewind.d.ts +21 -0
- package/dist/server/server/agent/providers/codex/rewind.js +46 -0
- package/dist/server/server/agent/providers/codex/test-utils/fake-app-server.d.ts +36 -0
- package/dist/server/server/agent/providers/codex/test-utils/fake-app-server.js +217 -0
- package/dist/server/server/agent/providers/codex/tool-call-detail-parser.d.ts +12 -0
- package/dist/server/server/agent/providers/codex/tool-call-detail-parser.js +104 -0
- package/dist/server/server/agent/providers/codex/tool-call-mapper.d.ts +24 -0
- package/dist/server/server/agent/providers/codex/tool-call-mapper.js +830 -0
- package/dist/server/server/agent/providers/codex-app-server-agent.d.ts +308 -0
- package/dist/server/server/agent/providers/codex-app-server-agent.js +4515 -0
- package/dist/server/server/agent/providers/codex-feature-definitions.d.ts +11 -0
- package/dist/server/server/agent/providers/codex-feature-definitions.js +45 -0
- package/dist/server/server/agent/providers/copilot-acp-agent.d.ts +26 -0
- package/dist/server/server/agent/providers/copilot-acp-agent.js +188 -0
- package/dist/server/server/agent/providers/cursor-acp-agent.d.ts +15 -0
- package/dist/server/server/agent/providers/cursor-acp-agent.js +18 -0
- package/dist/server/server/agent/providers/diagnostic-utils.d.ts +36 -0
- package/dist/server/server/agent/providers/diagnostic-utils.js +355 -0
- package/dist/server/server/agent/providers/generic-acp-agent.d.ts +42 -0
- package/dist/server/server/agent/providers/generic-acp-agent.js +160 -0
- package/dist/server/server/agent/providers/kiro-acp-agent.d.ts +17 -0
- package/dist/server/server/agent/providers/kiro-acp-agent.js +78 -0
- package/dist/server/server/agent/providers/mock-load-test-agent.d.ts +85 -0
- package/dist/server/server/agent/providers/mock-load-test-agent.js +1010 -0
- package/dist/server/server/agent/providers/mock-slow-provider.d.ts +14 -0
- package/dist/server/server/agent/providers/mock-slow-provider.js +39 -0
- package/dist/server/server/agent/providers/openai-compat-agent.d.ts +422 -0
- package/dist/server/server/agent/providers/openai-compat-agent.js +2536 -0
- package/dist/server/server/agent/providers/openai-compat-feature-definitions.d.ts +40 -0
- package/dist/server/server/agent/providers/openai-compat-feature-definitions.js +82 -0
- package/dist/server/server/agent/providers/openai-compat-mcp.d.ts +87 -0
- package/dist/server/server/agent/providers/openai-compat-mcp.js +353 -0
- package/dist/server/server/agent/providers/openai-compat-otto-tool-permissions.d.ts +29 -0
- package/dist/server/server/agent/providers/openai-compat-otto-tool-permissions.js +96 -0
- package/dist/server/server/agent/providers/openai-compat-tools.d.ts +69 -0
- package/dist/server/server/agent/providers/openai-compat-tools.js +1224 -0
- package/dist/server/server/agent/providers/opencode/paths.d.ts +2 -0
- package/dist/server/server/agent/providers/opencode/paths.js +7 -0
- package/dist/server/server/agent/providers/opencode/rewind.d.ts +18 -0
- package/dist/server/server/agent/providers/opencode/rewind.js +14 -0
- package/dist/server/server/agent/providers/opencode/server-manager.d.ts +91 -0
- package/dist/server/server/agent/providers/opencode/server-manager.js +425 -0
- package/dist/server/server/agent/providers/opencode/test-server-manager.d.ts +25 -0
- package/dist/server/server/agent/providers/opencode/test-server-manager.js +39 -0
- package/dist/server/server/agent/providers/opencode/test-utils/test-opencode-harness.d.ts +92 -0
- package/dist/server/server/agent/providers/opencode/test-utils/test-opencode-harness.js +260 -0
- package/dist/server/server/agent/providers/opencode/tool-call-detail-parser.d.ts +3 -0
- package/dist/server/server/agent/providers/opencode/tool-call-detail-parser.js +256 -0
- package/dist/server/server/agent/providers/opencode/tool-call-mapper.d.ts +13 -0
- package/dist/server/server/agent/providers/opencode/tool-call-mapper.js +53 -0
- package/dist/server/server/agent/providers/opencode-agent.d.ts +286 -0
- package/dist/server/server/agent/providers/opencode-agent.js +2830 -0
- package/dist/server/server/agent/providers/pi/agent.d.ts +132 -0
- package/dist/server/server/agent/providers/pi/agent.js +1649 -0
- package/dist/server/server/agent/providers/pi/cli-runtime.d.ts +21 -0
- package/dist/server/server/agent/providers/pi/cli-runtime.js +261 -0
- package/dist/server/server/agent/providers/pi/history-mapper.d.ts +9 -0
- package/dist/server/server/agent/providers/pi/history-mapper.js +140 -0
- package/dist/server/server/agent/providers/pi/rewind.d.ts +8 -0
- package/dist/server/server/agent/providers/pi/rewind.js +8 -0
- package/dist/server/server/agent/providers/pi/rpc-types.d.ts +208 -0
- package/dist/server/server/agent/providers/pi/rpc-types.js +2 -0
- package/dist/server/server/agent/providers/pi/runtime.d.ts +57 -0
- package/dist/server/server/agent/providers/pi/runtime.js +56 -0
- package/dist/server/server/agent/providers/pi/session-descriptor.d.ts +16 -0
- package/dist/server/server/agent/providers/pi/session-descriptor.js +346 -0
- package/dist/server/server/agent/providers/pi/test-utils/fake-pi.d.ts +83 -0
- package/dist/server/server/agent/providers/pi/test-utils/fake-pi.js +184 -0
- package/dist/server/server/agent/providers/pi/tool-call-mapper.d.ts +112 -0
- package/dist/server/server/agent/providers/pi/tool-call-mapper.js +284 -0
- package/dist/server/server/agent/providers/provider-image-output.d.ts +25 -0
- package/dist/server/server/agent/providers/provider-image-output.js +111 -0
- package/dist/server/server/agent/providers/provider-runner.d.ts +27 -0
- package/dist/server/server/agent/providers/provider-runner.js +81 -0
- package/dist/server/server/agent/providers/test-utils/session-stream-adapter.d.ts +3 -0
- package/dist/server/server/agent/providers/test-utils/session-stream-adapter.js +60 -0
- package/dist/server/server/agent/providers/tool-call-detail-primitives.d.ts +884 -0
- package/dist/server/server/agent/providers/tool-call-detail-primitives.js +778 -0
- package/dist/server/server/agent/providers/tool-call-mapper-utils.d.ts +25 -0
- package/dist/server/server/agent/providers/tool-call-mapper-utils.js +208 -0
- package/dist/server/server/agent/providers/trae-acp-agent.d.ts +15 -0
- package/dist/server/server/agent/providers/trae-acp-agent.js +18 -0
- package/dist/server/server/agent/recordings-debug.d.ts +3 -0
- package/dist/server/server/agent/recordings-debug.js +19 -0
- package/dist/server/server/agent/rewind/rewind.d.ts +10 -0
- package/dist/server/server/agent/rewind/rewind.js +29 -0
- package/dist/server/server/agent/rewind/test-rewind-session.d.ts +48 -0
- package/dist/server/server/agent/rewind/test-rewind-session.js +88 -0
- package/dist/server/server/agent/runtime-mcp-config.d.ts +14 -0
- package/dist/server/server/agent/runtime-mcp-config.js +53 -0
- package/dist/server/server/agent/structured-generation-providers.d.ts +29 -0
- package/dist/server/server/agent/structured-generation-providers.js +236 -0
- package/dist/server/server/agent/stt-debug.d.ts +10 -0
- package/dist/server/server/agent/stt-debug.js +33 -0
- package/dist/server/server/agent/stt-manager.d.ts +38 -0
- package/dist/server/server/agent/stt-manager.js +246 -0
- package/dist/server/server/agent/system-prompt.d.ts +2 -0
- package/dist/server/server/agent/system-prompt.js +8 -0
- package/dist/server/server/agent/timeline-append.d.ts +10 -0
- package/dist/server/server/agent/timeline-append.js +27 -0
- package/dist/server/server/agent/timeline-projection.d.ts +71 -0
- package/dist/server/server/agent/timeline-projection.js +373 -0
- package/dist/server/server/agent/tools/otto-tools.d.ts +80 -0
- package/dist/server/server/agent/tools/otto-tools.js +2912 -0
- package/dist/server/server/agent/tools/types.d.ts +36 -0
- package/dist/server/server/agent/tools/types.js +2 -0
- package/dist/server/server/agent/tts-debug.d.ts +8 -0
- package/dist/server/server/agent/tts-debug.js +24 -0
- package/dist/server/server/agent/tts-manager.d.ts +41 -0
- package/dist/server/server/agent/tts-manager.js +375 -0
- package/dist/server/server/agent-attention-policy.d.ts +29 -0
- package/dist/server/server/agent-attention-policy.js +36 -0
- package/dist/server/server/artifact/artifact-prompt.d.ts +2 -0
- package/dist/server/server/artifact/artifact-prompt.js +15 -0
- package/dist/server/server/artifact/artifact-service.d.ts +91 -0
- package/dist/server/server/artifact/artifact-service.js +419 -0
- package/dist/server/server/artifact/artifact-store.d.ts +24 -0
- package/dist/server/server/artifact/artifact-store.js +168 -0
- package/dist/server/server/artifact/artifact-watcher.d.ts +34 -0
- package/dist/server/server/artifact/artifact-watcher.js +146 -0
- package/dist/server/server/artifact/html-validator.d.ts +26 -0
- package/dist/server/server/artifact/html-validator.js +92 -0
- package/dist/server/server/atomic-file.d.ts +5 -0
- package/dist/server/server/atomic-file.js +19 -0
- package/dist/server/server/auth.d.ts +38 -0
- package/dist/server/server/auth.js +143 -0
- package/dist/server/server/auto-archive-on-merge/archive-if-safe.d.ts +40 -0
- package/dist/server/server/auto-archive-on-merge/archive-if-safe.js +92 -0
- package/dist/server/server/auto-archive-on-merge/index.d.ts +8 -0
- package/dist/server/server/auto-archive-on-merge/index.js +15 -0
- package/dist/server/server/bootstrap.d.ts +127 -0
- package/dist/server/server/bootstrap.js +1331 -0
- package/dist/server/server/browser-tools/broker.d.ts +45 -0
- package/dist/server/server/browser-tools/broker.js +390 -0
- package/dist/server/server/browser-tools/errors.d.ts +22 -0
- package/dist/server/server/browser-tools/errors.js +27 -0
- package/dist/server/server/browser-tools/policy.d.ts +10 -0
- package/dist/server/server/browser-tools/policy.js +16 -0
- package/dist/server/server/browser-tools/tools.d.ts +24 -0
- package/dist/server/server/browser-tools/tools.js +967 -0
- package/dist/server/server/chat/chat-mentions.d.ts +47 -0
- package/dist/server/server/chat/chat-mentions.js +113 -0
- package/dist/server/server/chat/chat-service.d.ts +78 -0
- package/dist/server/server/chat/chat-service.js +337 -0
- package/dist/server/server/checkout/status-projection.d.ts +19 -0
- package/dist/server/server/checkout/status-projection.js +117 -0
- package/dist/server/server/checkout-diff-manager.d.ts +41 -0
- package/dist/server/server/checkout-diff-manager.js +189 -0
- package/dist/server/server/checkout-git-utils.d.ts +11 -0
- package/dist/server/server/checkout-git-utils.js +34 -0
- package/dist/server/server/client-message-id.d.ts +3 -0
- package/dist/server/server/client-message-id.js +12 -0
- package/dist/server/server/config.d.ts +22 -0
- package/dist/server/server/config.js +330 -0
- package/dist/server/server/connection-offer.d.ts +20 -0
- package/dist/server/server/connection-offer.js +59 -0
- package/dist/server/server/daemon-config-store.d.ts +44 -0
- package/dist/server/server/daemon-config-store.js +530 -0
- package/dist/server/server/daemon-keypair.d.ts +8 -0
- package/dist/server/server/daemon-keypair.js +42 -0
- package/dist/server/server/daemon-version.d.ts +5 -0
- package/dist/server/server/daemon-version.js +22 -0
- package/dist/server/server/daemon-worker.d.ts +2 -0
- package/dist/server/server/daemon-worker.js +251 -0
- package/dist/server/server/dictation/dictation-stream-manager.d.ts +87 -0
- package/dist/server/server/dictation/dictation-stream-manager.js +572 -0
- package/dist/server/server/exports.d.ts +24 -0
- package/dist/server/server/exports.js +24 -0
- package/dist/server/server/file-download/token-store.d.ts +24 -0
- package/dist/server/server/file-download/token-store.js +40 -0
- package/dist/server/server/file-explorer/code-index.d.ts +28 -0
- package/dist/server/server/file-explorer/code-index.js +127 -0
- package/dist/server/server/file-explorer/file-search.d.ts +72 -0
- package/dist/server/server/file-explorer/file-search.js +297 -0
- package/dist/server/server/file-explorer/file-watcher.d.ts +40 -0
- package/dist/server/server/file-explorer/file-watcher.js +0 -0
- package/dist/server/server/file-explorer/gitignore.d.ts +39 -0
- package/dist/server/server/file-explorer/gitignore.js +191 -0
- package/dist/server/server/file-explorer/service.d.ts +103 -0
- package/dist/server/server/file-explorer/service.js +420 -0
- package/dist/server/server/file-upload/index.d.ts +27 -0
- package/dist/server/server/file-upload/index.js +158 -0
- package/dist/server/server/hostnames.d.ts +13 -0
- package/dist/server/server/hostnames.js +94 -0
- package/dist/server/server/json-utils.d.ts +11 -0
- package/dist/server/server/json-utils.js +45 -0
- package/dist/server/server/lifecycle-reasons.d.ts +4 -0
- package/dist/server/server/lifecycle-reasons.js +6 -0
- package/dist/server/server/logger.d.ts +29 -0
- package/dist/server/server/logger.js +125 -0
- package/dist/server/server/loop-service.d.ts +234 -0
- package/dist/server/server/loop-service.js +804 -0
- package/dist/server/server/managed-processes/managed-processes.d.ts +76 -0
- package/dist/server/server/managed-processes/managed-processes.js +326 -0
- package/dist/server/server/messages.d.ts +9 -0
- package/dist/server/server/messages.js +29 -0
- package/dist/server/server/migrations/backfill-workspace-id.migration.d.ts +9 -0
- package/dist/server/server/migrations/backfill-workspace-id.migration.js +64 -0
- package/dist/server/server/otto-env.d.ts +13 -0
- package/dist/server/server/otto-env.js +53 -0
- package/dist/server/server/otto-home.d.ts +2 -0
- package/dist/server/server/otto-home.js +19 -0
- package/dist/server/server/otto-worktree-service.d.ts +52 -0
- package/dist/server/server/otto-worktree-service.js +294 -0
- package/dist/server/server/package-version.d.ts +19 -0
- package/dist/server/server/package-version.js +60 -0
- package/dist/server/server/pagination/cursor.d.ts +16 -0
- package/dist/server/server/pagination/cursor.js +62 -0
- package/dist/server/server/pagination/sortable-pager.d.ts +24 -0
- package/dist/server/server/pagination/sortable-pager.js +68 -0
- package/dist/server/server/pairing-offer.d.ts +18 -0
- package/dist/server/server/pairing-offer.js +47 -0
- package/dist/server/server/pairing-qr.d.ts +7 -0
- package/dist/server/server/pairing-qr.js +45 -0
- package/dist/server/server/path-utils.d.ts +5 -0
- package/dist/server/server/path-utils.js +34 -0
- package/dist/server/server/persisted-config.d.ts +417 -0
- package/dist/server/server/persisted-config.js +471 -0
- package/dist/server/server/persistence-hooks.d.ts +31 -0
- package/dist/server/server/persistence-hooks.js +93 -0
- package/dist/server/server/pid-lock.d.ts +32 -0
- package/dist/server/server/pid-lock.js +170 -0
- package/dist/server/server/preview/dev-server-manager.d.ts +108 -0
- package/dist/server/server/preview/dev-server-manager.js +426 -0
- package/dist/server/server/preview/launch-config.d.ts +37 -0
- package/dist/server/server/preview/launch-config.js +63 -0
- package/dist/server/server/preview/preview-tools.d.ts +30 -0
- package/dist/server/server/preview/preview-tools.js +249 -0
- package/dist/server/server/private-files.d.ts +6 -0
- package/dist/server/server/private-files.js +37 -0
- package/dist/server/server/process-diagnostics.d.ts +17 -0
- package/dist/server/server/process-diagnostics.js +22 -0
- package/dist/server/server/push/notifications.d.ts +9 -0
- package/dist/server/server/push/notifications.js +15 -0
- package/dist/server/server/push/push-service.d.ts +20 -0
- package/dist/server/server/push/push-service.js +66 -0
- package/dist/server/server/push/token-store.d.ts +18 -0
- package/dist/server/server/push/token-store.js +68 -0
- package/dist/server/server/relay-transport.d.ts +31 -0
- package/dist/server/server/relay-transport.js +514 -0
- package/dist/server/server/resolve-workspace-id-for-path.d.ts +3 -0
- package/dist/server/server/resolve-workspace-id-for-path.js +41 -0
- package/dist/server/server/resolve-worktree-creation-intent.d.ts +32 -0
- package/dist/server/server/resolve-worktree-creation-intent.js +121 -0
- package/dist/server/server/schedule/cron.d.ts +4 -0
- package/dist/server/server/schedule/cron.js +81 -0
- package/dist/server/server/schedule/service.d.ts +89 -0
- package/dist/server/server/schedule/service.js +882 -0
- package/dist/server/server/schedule/store.d.ts +27 -0
- package/dist/server/server/schedule/store.js +190 -0
- package/dist/server/server/script-health-monitor.d.ts +39 -0
- package/dist/server/server/script-health-monitor.js +159 -0
- package/dist/server/server/script-proxy.d.ts +3 -0
- package/dist/server/server/script-proxy.js +2 -0
- package/dist/server/server/script-route-branch-handler.d.ts +10 -0
- package/dist/server/server/script-route-branch-handler.js +11 -0
- package/dist/server/server/script-status-projection.d.ts +36 -0
- package/dist/server/server/script-status-projection.js +200 -0
- package/dist/server/server/server-id.d.ts +17 -0
- package/dist/server/server/server-id.js +68 -0
- package/dist/server/server/service-proxy.d.ts +237 -0
- package/dist/server/server/service-proxy.js +714 -0
- package/dist/server/server/session/agent-config/agent-config-session.d.ts +59 -0
- package/dist/server/server/session/agent-config/agent-config-session.js +110 -0
- package/dist/server/server/session/agent-updates/agent-updates-service.d.ts +65 -0
- package/dist/server/server/session/agent-updates/agent-updates-service.js +232 -0
- package/dist/server/server/session/artifact/artifact-session.d.ts +45 -0
- package/dist/server/server/session/artifact/artifact-session.js +293 -0
- package/dist/server/server/session/chat/chat-schedule-loop-session.d.ts +120 -0
- package/dist/server/server/session/chat/chat-schedule-loop-session.js +489 -0
- package/dist/server/server/session/checkout/checkout-session.d.ts +146 -0
- package/dist/server/server/session/checkout/checkout-session.js +1000 -0
- package/dist/server/server/session/checkout/git-metadata-generator.d.ts +53 -0
- package/dist/server/server/session/checkout/git-metadata-generator.js +159 -0
- package/dist/server/server/session/daemon/daemon-self-update-session-controller.d.ts +32 -0
- package/dist/server/server/session/daemon/daemon-self-update-session-controller.js +88 -0
- package/dist/server/server/session/daemon/daemon-self-updater.d.ts +32 -0
- package/dist/server/server/session/daemon/daemon-self-updater.js +56 -0
- package/dist/server/server/session/daemon/daemon-session.d.ts +76 -0
- package/dist/server/server/session/daemon/daemon-session.js +148 -0
- package/dist/server/server/session/daemon/diagnostics.d.ts +41 -0
- package/dist/server/server/session/daemon/diagnostics.js +431 -0
- package/dist/server/server/session/daemon/install-origin.d.ts +7 -0
- package/dist/server/server/session/daemon/install-origin.js +64 -0
- package/dist/server/server/session/daemon/npm-global-cli.d.ts +29 -0
- package/dist/server/server/session/daemon/npm-global-cli.js +98 -0
- package/dist/server/server/session/files/workspace-files-session.d.ts +60 -0
- package/dist/server/server/session/files/workspace-files-session.js +518 -0
- package/dist/server/server/session/git-mutation/git-mutation-service.d.ts +34 -0
- package/dist/server/server/session/git-mutation/git-mutation-service.js +71 -0
- package/dist/server/server/session/project-config/project-config-session.d.ts +34 -0
- package/dist/server/server/session/project-config/project-config-session.js +125 -0
- package/dist/server/server/session/provider/provider-catalog-session.d.ts +74 -0
- package/dist/server/server/session/provider/provider-catalog-session.js +343 -0
- package/dist/server/server/session/voice/voice-session.d.ts +167 -0
- package/dist/server/server/session/voice/voice-session.js +912 -0
- package/dist/server/server/session/voice/voice-turn-controller.d.ts +38 -0
- package/dist/server/server/session/voice/voice-turn-controller.js +393 -0
- package/dist/server/server/session/workspace-git-observer/workspace-git-observer-service.d.ts +36 -0
- package/dist/server/server/session/workspace-git-observer/workspace-git-observer-service.js +134 -0
- package/dist/server/server/session/workspace-provisioning/workspace-provisioning-service.d.ts +34 -0
- package/dist/server/server/session/workspace-provisioning/workspace-provisioning-service.js +190 -0
- package/dist/server/server/session/workspace-scripts/workspace-scripts-service.d.ts +41 -0
- package/dist/server/server/session/workspace-scripts/workspace-scripts-service.js +100 -0
- package/dist/server/server/session.d.ts +450 -0
- package/dist/server/server/session.js +4763 -0
- package/dist/server/server/speech/audio.d.ts +10 -0
- package/dist/server/server/speech/audio.js +101 -0
- package/dist/server/server/speech/provider-resolver.d.ts +3 -0
- package/dist/server/server/speech/provider-resolver.js +7 -0
- package/dist/server/server/speech/providers/local/config.d.ts +30 -0
- package/dist/server/server/speech/providers/local/config.js +133 -0
- package/dist/server/server/speech/providers/local/models.d.ts +13 -0
- package/dist/server/server/speech/providers/local/models.js +21 -0
- package/dist/server/server/speech/providers/local/runtime.d.ts +31 -0
- package/dist/server/server/speech/providers/local/runtime.js +135 -0
- package/dist/server/server/speech/providers/local/sherpa/assets/silero_vad.onnx +0 -0
- package/dist/server/server/speech/providers/local/sherpa/model-catalog.d.ts +109 -0
- package/dist/server/server/speech/providers/local/sherpa/model-catalog.js +129 -0
- package/dist/server/server/speech/providers/local/sherpa/model-downloader.d.ts +16 -0
- package/dist/server/server/speech/providers/local/sherpa/model-downloader.js +195 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-offline-recognizer.d.ts +49 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-offline-recognizer.js +73 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-onnx-node-loader.d.ts +9 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-onnx-node-loader.js +107 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-parakeet-realtime-session.d.ts +28 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-parakeet-realtime-session.js +137 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-parakeet-stt.d.ts +21 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-parakeet-stt.js +133 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-runtime-env.d.ts +18 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-runtime-env.js +84 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-tts.d.ts +24 -0
- package/dist/server/server/speech/providers/local/sherpa/sherpa-tts.js +145 -0
- package/dist/server/server/speech/providers/local/sherpa/silero-vad-provider.d.ts +19 -0
- package/dist/server/server/speech/providers/local/sherpa/silero-vad-provider.js +49 -0
- package/dist/server/server/speech/providers/local/sherpa/silero-vad-session.d.ts +38 -0
- package/dist/server/server/speech/providers/local/sherpa/silero-vad-session.js +176 -0
- package/dist/server/server/speech/providers/local/sherpa/tts-voices.d.ts +10 -0
- package/dist/server/server/speech/providers/local/sherpa/tts-voices.js +86 -0
- package/dist/server/server/speech/providers/local/worker-bytes.d.ts +4 -0
- package/dist/server/server/speech/providers/local/worker-bytes.js +9 -0
- package/dist/server/server/speech/providers/local/worker-client.d.ts +93 -0
- package/dist/server/server/speech/providers/local/worker-client.js +591 -0
- package/dist/server/server/speech/providers/local/worker-process.d.ts +2 -0
- package/dist/server/server/speech/providers/local/worker-process.js +270 -0
- package/dist/server/server/speech/providers/local/worker-protocol.d.ts +96 -0
- package/dist/server/server/speech/providers/local/worker-protocol.js +2 -0
- package/dist/server/server/speech/providers/openai/config.d.ts +19 -0
- package/dist/server/server/speech/providers/openai/config.js +160 -0
- package/dist/server/server/speech/providers/openai/runtime.d.ts +29 -0
- package/dist/server/server/speech/providers/openai/runtime.js +102 -0
- package/dist/server/server/speech/providers/openai/stt.d.ts +23 -0
- package/dist/server/server/speech/providers/openai/stt.js +209 -0
- package/dist/server/server/speech/providers/openai/tts.d.ts +20 -0
- package/dist/server/server/speech/providers/openai/tts.js +70 -0
- package/dist/server/server/speech/speech-config-resolver.d.ts +11 -0
- package/dist/server/server/speech/speech-config-resolver.js +132 -0
- package/dist/server/server/speech/speech-provider.d.ts +71 -0
- package/dist/server/server/speech/speech-provider.js +2 -0
- package/dist/server/server/speech/speech-runtime.d.ts +67 -0
- package/dist/server/server/speech/speech-runtime.js +615 -0
- package/dist/server/server/speech/speech-settings-options.d.ts +14 -0
- package/dist/server/server/speech/speech-settings-options.js +73 -0
- package/dist/server/server/speech/speech-types.d.ts +22 -0
- package/dist/server/server/speech/speech-types.js +8 -0
- package/dist/server/server/speech/turn-detection-provider.d.ts +23 -0
- package/dist/server/server/speech/turn-detection-provider.js +2 -0
- package/dist/server/server/utils/diff-highlighter.d.ts +57 -0
- package/dist/server/server/utils/diff-highlighter.js +279 -0
- package/dist/server/server/voice-config.d.ts +15 -0
- package/dist/server/server/voice-config.js +54 -0
- package/dist/server/server/voice-permission-policy.d.ts +4 -0
- package/dist/server/server/voice-permission-policy.js +13 -0
- package/dist/server/server/voice-types.d.ts +12 -0
- package/dist/server/server/voice-types.js +2 -0
- package/dist/server/server/web-ui.d.ts +10 -0
- package/dist/server/server/web-ui.js +205 -0
- package/dist/server/server/websocket/runtime-metrics.d.ts +94 -0
- package/dist/server/server/websocket/runtime-metrics.js +148 -0
- package/dist/server/server/websocket-server.d.ts +187 -0
- package/dist/server/server/websocket-server.js +1766 -0
- package/dist/server/server/workspace-archive-service.d.ts +65 -0
- package/dist/server/server/workspace-archive-service.js +229 -0
- package/dist/server/server/workspace-auto-name.d.ts +55 -0
- package/dist/server/server/workspace-auto-name.js +128 -0
- package/dist/server/server/workspace-bootstrap-dedupe.d.ts +34 -0
- package/dist/server/server/workspace-bootstrap-dedupe.js +23 -0
- package/dist/server/server/workspace-directory.d.ts +93 -0
- package/dist/server/server/workspace-directory.js +422 -0
- package/dist/server/server/workspace-git-metadata.d.ts +24 -0
- package/dist/server/server/workspace-git-metadata.js +55 -0
- package/dist/server/server/workspace-git-service.d.ts +270 -0
- package/dist/server/server/workspace-git-service.js +1423 -0
- package/dist/server/server/workspace-reconciliation-service.d.ts +57 -0
- package/dist/server/server/workspace-reconciliation-service.js +278 -0
- package/dist/server/server/workspace-registry-bootstrap.d.ts +13 -0
- package/dist/server/server/workspace-registry-bootstrap.js +121 -0
- package/dist/server/server/workspace-registry-model.d.ts +55 -0
- package/dist/server/server/workspace-registry-model.js +190 -0
- package/dist/server/server/workspace-registry.d.ts +117 -0
- package/dist/server/server/workspace-registry.js +194 -0
- package/dist/server/server/workspace-script-runtime-store.d.ts +28 -0
- package/dist/server/server/workspace-script-runtime-store.js +78 -0
- package/dist/server/server/workspace-service-env.d.ts +18 -0
- package/dist/server/server/workspace-service-env.js +85 -0
- package/dist/server/server/workspace-service-port-registry.d.ts +19 -0
- package/dist/server/server/workspace-service-port-registry.js +59 -0
- package/dist/server/server/worktree/commands.d.ts +55 -0
- package/dist/server/server/worktree/commands.js +107 -0
- package/dist/server/server/worktree-bootstrap.d.ts +76 -0
- package/dist/server/server/worktree-bootstrap.js +720 -0
- package/dist/server/server/worktree-branch-name-generator.d.ts +35 -0
- package/dist/server/server/worktree-branch-name-generator.js +91 -0
- package/dist/server/server/worktree-core.d.ts +31 -0
- package/dist/server/server/worktree-core.js +105 -0
- package/dist/server/server/worktree-errors.d.ts +12 -0
- package/dist/server/server/worktree-errors.js +28 -0
- package/dist/server/server/worktree-session.d.ts +152 -0
- package/dist/server/server/worktree-session.js +466 -0
- package/dist/server/services/git-hosting/bitbucket-cloud-service.d.ts +24 -0
- package/dist/server/services/git-hosting/bitbucket-cloud-service.js +754 -0
- package/dist/server/services/git-hosting/github-hosting-service.d.ts +4 -0
- package/dist/server/services/git-hosting/github-hosting-service.js +11 -0
- package/dist/server/services/git-hosting/hosting-http-client.d.ts +20 -0
- package/dist/server/services/git-hosting/hosting-http-client.js +131 -0
- package/dist/server/services/git-hosting/request-cache.d.ts +20 -0
- package/dist/server/services/git-hosting/request-cache.js +68 -0
- package/dist/server/services/git-hosting/resolver.d.ts +32 -0
- package/dist/server/services/git-hosting/resolver.js +152 -0
- package/dist/server/services/git-hosting/router.d.ts +4 -0
- package/dist/server/services/git-hosting/router.js +105 -0
- package/dist/server/services/git-hosting/status-poller.d.ts +39 -0
- package/dist/server/services/git-hosting/status-poller.js +149 -0
- package/dist/server/services/git-hosting/types.d.ts +53 -0
- package/dist/server/services/git-hosting/types.js +75 -0
- package/dist/server/services/github-service.d.ts +339 -0
- package/dist/server/services/github-service.js +2109 -0
- package/dist/server/services/quota-fetcher/manifest.d.ts +4 -0
- package/dist/server/services/quota-fetcher/manifest.js +52 -0
- package/dist/server/services/quota-fetcher/provider.d.ts +17 -0
- package/dist/server/services/quota-fetcher/provider.js +2 -0
- package/dist/server/services/quota-fetcher/providers/claude.d.ts +26 -0
- package/dist/server/services/quota-fetcher/providers/claude.js +217 -0
- package/dist/server/services/quota-fetcher/providers/codex.d.ts +23 -0
- package/dist/server/services/quota-fetcher/providers/codex.js +211 -0
- package/dist/server/services/quota-fetcher/providers/copilot.d.ts +17 -0
- package/dist/server/services/quota-fetcher/providers/copilot.js +75 -0
- package/dist/server/services/quota-fetcher/providers/cursor.d.ts +17 -0
- package/dist/server/services/quota-fetcher/providers/cursor.js +123 -0
- package/dist/server/services/quota-fetcher/providers/grok.d.ts +18 -0
- package/dist/server/services/quota-fetcher/providers/grok.js +89 -0
- package/dist/server/services/quota-fetcher/providers/kimi.d.ts +20 -0
- package/dist/server/services/quota-fetcher/providers/kimi.js +89 -0
- package/dist/server/services/quota-fetcher/providers/minimax.d.ts +29 -0
- package/dist/server/services/quota-fetcher/providers/minimax.js +227 -0
- package/dist/server/services/quota-fetcher/providers/zai.d.ts +17 -0
- package/dist/server/services/quota-fetcher/providers/zai.js +58 -0
- package/dist/server/services/quota-fetcher/service.d.ts +28 -0
- package/dist/server/services/quota-fetcher/service.js +58 -0
- package/dist/server/services/quota-fetcher/usage.d.ts +22 -0
- package/dist/server/services/quota-fetcher/usage.js +49 -0
- package/dist/server/terminal/activity/terminal-activity-tracker.d.ts +20 -0
- package/dist/server/terminal/activity/terminal-activity-tracker.js +59 -0
- package/dist/server/terminal/agent-hooks/agent-hook-installer.d.ts +62 -0
- package/dist/server/terminal/agent-hooks/agent-hook-installer.js +117 -0
- package/dist/server/terminal/agent-hooks/claude/claude-settings.d.ts +7 -0
- package/dist/server/terminal/agent-hooks/claude/claude-settings.js +88 -0
- package/dist/server/terminal/agent-hooks/claude/claude.d.ts +4 -0
- package/dist/server/terminal/agent-hooks/claude/claude.js +47 -0
- package/dist/server/terminal/agent-hooks/codex/codex-settings.d.ts +7 -0
- package/dist/server/terminal/agent-hooks/codex/codex-settings.js +99 -0
- package/dist/server/terminal/agent-hooks/codex/codex.d.ts +4 -0
- package/dist/server/terminal/agent-hooks/codex/codex.js +30 -0
- package/dist/server/terminal/agent-hooks/opencode/opencode-plugin.d.ts +4 -0
- package/dist/server/terminal/agent-hooks/opencode/opencode-plugin.js +46 -0
- package/dist/server/terminal/agent-hooks/opencode/opencode.d.ts +3 -0
- package/dist/server/terminal/agent-hooks/opencode/opencode.js +23 -0
- package/dist/server/terminal/agent-hooks/provider-registry.d.ts +24 -0
- package/dist/server/terminal/agent-hooks/provider-registry.js +36 -0
- package/dist/server/terminal/agent-hooks/terminal-agent-hook-setting.d.ts +10 -0
- package/dist/server/terminal/agent-hooks/terminal-agent-hook-setting.js +26 -0
- package/dist/server/terminal/shell-integration/zsh/.zshenv +17 -0
- package/dist/server/terminal/shell-integration/zsh/otto-integration.zsh +32 -0
- package/dist/server/terminal/terminal-capture.d.ts +12 -0
- package/dist/server/terminal/terminal-capture.js +43 -0
- package/dist/server/terminal/terminal-manager-factory.d.ts +6 -0
- package/dist/server/terminal/terminal-manager-factory.js +5 -0
- package/dist/server/terminal/terminal-manager.d.ts +78 -0
- package/dist/server/terminal/terminal-manager.js +319 -0
- package/dist/server/terminal/terminal-output-coalescer.d.ts +34 -0
- package/dist/server/terminal/terminal-output-coalescer.js +73 -0
- package/dist/server/terminal/terminal-restore.d.ts +18 -0
- package/dist/server/terminal/terminal-restore.js +52 -0
- package/dist/server/terminal/terminal-session-controller.d.ts +85 -0
- package/dist/server/terminal/terminal-session-controller.js +819 -0
- package/dist/server/terminal/terminal-ts-loader.mjs +20 -0
- package/dist/server/terminal/terminal-worker-process.d.ts +2 -0
- package/dist/server/terminal/terminal-worker-process.js +304 -0
- package/dist/server/terminal/terminal-worker-protocol.d.ts +119 -0
- package/dist/server/terminal/terminal-worker-protocol.js +2 -0
- package/dist/server/terminal/terminal.d.ts +151 -0
- package/dist/server/terminal/terminal.js +1155 -0
- package/dist/server/terminal/worker-terminal-manager.d.ts +20 -0
- package/dist/server/terminal/worker-terminal-manager.js +688 -0
- package/dist/server/utils/build-metadata-prompt.d.ts +19 -0
- package/dist/server/utils/build-metadata-prompt.js +29 -0
- package/dist/server/utils/checkout-git.d.ts +253 -0
- package/dist/server/utils/checkout-git.js +2241 -0
- package/dist/server/utils/directory-suggestions.d.ts +26 -0
- package/dist/server/utils/directory-suggestions.js +830 -0
- package/dist/server/utils/git-rev-parse-path.d.ts +3 -0
- package/dist/server/utils/git-rev-parse-path.js +21 -0
- package/dist/server/utils/github-remote.d.ts +9 -0
- package/dist/server/utils/github-remote.js +62 -0
- package/dist/server/utils/otto-config-file.d.ts +30 -0
- package/dist/server/utils/otto-config-file.js +90 -0
- package/dist/server/utils/path.d.ts +18 -0
- package/dist/server/utils/path.js +123 -0
- package/dist/server/utils/project-icon.d.ts +39 -0
- package/dist/server/utils/project-icon.js +364 -0
- package/dist/server/utils/promise-timeout.d.ts +9 -0
- package/dist/server/utils/promise-timeout.js +25 -0
- package/dist/server/utils/run-git-command.d.ts +37 -0
- package/dist/server/utils/run-git-command.js +232 -0
- package/dist/server/utils/spawn.d.ts +25 -0
- package/dist/server/utils/spawn.js +59 -0
- package/dist/server/utils/string-command-shell.d.ts +13 -0
- package/dist/server/utils/string-command-shell.js +37 -0
- package/dist/server/utils/tree-kill.d.ts +18 -0
- package/dist/server/utils/tree-kill.js +77 -0
- package/dist/server/utils/windows-command.d.ts +15 -0
- package/dist/server/utils/windows-command.js +41 -0
- package/dist/server/utils/worktree-metadata.d.ts +39 -0
- package/dist/server/utils/worktree-metadata.js +174 -0
- package/dist/server/utils/worktree.d.ts +205 -0
- package/dist/server/utils/worktree.js +1120 -0
- package/dist/server/web-ui/_expo/static/css/xterm-3bb1704bf6cb0876640973dc0244b4cb.css +1 -0
- package/dist/server/web-ui/_expo/static/css/xterm-3bb1704bf6cb0876640973dc0244b4cb.css.br +0 -0
- package/dist/server/web-ui/_expo/static/css/xterm-3bb1704bf6cb0876640973dc0244b4cb.css.gz +0 -0
- package/dist/server/web-ui/_expo/static/js/web/desktop-attachment-bridge-a25c6055b348629689f75618db2c83e1.js +1 -0
- package/dist/server/web-ui/_expo/static/js/web/desktop-attachment-bridge-a25c6055b348629689f75618db2c83e1.js.br +0 -0
- package/dist/server/web-ui/_expo/static/js/web/desktop-attachment-bridge-a25c6055b348629689f75618db2c83e1.js.gz +0 -0
- package/dist/server/web-ui/_expo/static/js/web/desktop-attachment-store-7dc26ea1611eb9d7c2971a6745e5bf5c.js +1 -0
- package/dist/server/web-ui/_expo/static/js/web/desktop-attachment-store-7dc26ea1611eb9d7c2971a6745e5bf5c.js.br +0 -0
- package/dist/server/web-ui/_expo/static/js/web/desktop-attachment-store-7dc26ea1611eb9d7c2971a6745e5bf5c.js.gz +0 -0
- package/dist/server/web-ui/_expo/static/js/web/index-ea91f496cee180fa5bf308c8cc177646.js +3199 -0
- package/dist/server/web-ui/_expo/static/js/web/index-ea91f496cee180fa5bf308c8cc177646.js.br +0 -0
- package/dist/server/web-ui/_expo/static/js/web/index-ea91f496cee180fa5bf308c8cc177646.js.gz +0 -0
- package/dist/server/web-ui/_expo/static/js/web/indexeddb-attachment-store-b6b853a967343babf305512fe8c5958c.js +1 -0
- package/dist/server/web-ui/_expo/static/js/web/indexeddb-attachment-store-b6b853a967343babf305512fe8c5958c.js.br +0 -0
- package/dist/server/web-ui/_expo/static/js/web/indexeddb-attachment-store-b6b853a967343babf305512fe8c5958c.js.gz +0 -0
- package/dist/server/web-ui/_expo/static/js/web/native-file-attachment-store-17223e158406802adc686d02d946573d.js +3 -0
- package/dist/server/web-ui/_expo/static/js/web/native-file-attachment-store-17223e158406802adc686d02d946573d.js.br +0 -0
- package/dist/server/web-ui/_expo/static/js/web/native-file-attachment-store-17223e158406802adc686d02d946573d.js.gz +0 -0
- package/dist/server/web-ui/apple-touch-icon.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/@expo-google-fonts/inter/400Regular/Inter_400Regular.51b6ad87261f18b6433ec52871ddfabc.ttf +0 -0
- package/dist/server/web-ui/assets/__node_modules/@expo-google-fonts/jetbrains-mono/400Regular/JetBrainsMono_400Regular.a0147b5ab9e4946e81879aef45313def.ttf +0 -0
- package/dist/server/web-ui/assets/__node_modules/@react-navigation/elements/lib/module/assets/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/@react-navigation/elements/lib/module/assets/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/@react-navigation/elements/lib/module/assets/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/@react-navigation/elements/lib/module/assets/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/@react-navigation/elements/lib/module/assets/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/@react-navigation/elements/lib/module/assets/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/@react-navigation/elements/lib/module/assets/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/@react-navigation/elements/lib/module/assets/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/@react-navigation/elements/lib/module/assets/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/@react-navigation/elements/lib/module/assets/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/@react-navigation/elements/lib/module/assets/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png +0 -0
- package/dist/server/web-ui/assets/__node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/antigravity.6e91a685c33435e0b466a56db86cf141.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/clion.baa1f4eb572e962a6117bdbee95749e4.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/cursor.c31d6bce4fe9aadc3fe59962f4c4fcf3.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/finder.7f68fc2c475621a672e1be09309d5567.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/goland.0796ab2b9be2637fd1cdcde891fad3ca.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/intellij-idea.33bc9ff9c0815d8ad43f618c8c244401.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/phpstorm.c60b33bc7a8309143d232e14b76554c5.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/pycharm.88f25ac484989c45c25323e0adccfa9f.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/rider.1a1091dc3a0ede0461f0aa38a54f080a.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/rubymine.0e5b66fd7d43f8cbac0f05bba97c9a21.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/rustrover.3590ef05482369f41d3484c90272570d.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/vscode.832bdb4c685d930f1c864c793703600b.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/webstorm.aa5dc2cd8c20cc0a155c4c5c5ab3c5f5.png +0 -0
- package/dist/server/web-ui/assets/assets/images/editor-apps/zed.f3a670b7f9aa226da4fe53fb86f1abbd.png +0 -0
- package/dist/server/web-ui/assets/assets/images/favicon-dark-attention.3b2c331d11122d8f743c73a5878593be.png +0 -0
- package/dist/server/web-ui/assets/assets/images/favicon-dark-running.6077c2ab71021b31c82a42e0b42ad837.png +0 -0
- package/dist/server/web-ui/assets/assets/images/favicon-dark.12984efe6d435a13794a74cd2f858dcd.png +0 -0
- package/dist/server/web-ui/assets/assets/images/favicon-light-attention.3b2c331d11122d8f743c73a5878593be.png +0 -0
- package/dist/server/web-ui/assets/assets/images/favicon-light-running.6077c2ab71021b31c82a42e0b42ad837.png +0 -0
- package/dist/server/web-ui/assets/assets/images/favicon-light.12984efe6d435a13794a74cd2f858dcd.png +0 -0
- package/dist/server/web-ui/assets/assets/images/notification-icon.2394c3b427c0f5ee2bb84864d8fb0f45.png +0 -0
- package/dist/server/web-ui/favicon.ico +0 -0
- package/dist/server/web-ui/index.html +147 -0
- package/dist/server/web-ui/index.html.br +0 -0
- package/dist/server/web-ui/index.html.gz +0 -0
- package/dist/server/web-ui/manifest.json +27 -0
- package/dist/server/web-ui/manifest.json.br +0 -0
- package/dist/server/web-ui/manifest.json.gz +0 -0
- package/dist/server/web-ui/metadata.json +1 -0
- package/dist/server/web-ui/metadata.json.br +1 -0
- package/dist/server/web-ui/metadata.json.gz +0 -0
- package/dist/server/web-ui/pwa-icon-192.png +0 -0
- package/dist/server/web-ui/pwa-icon-512.png +0 -0
- package/dist/server/web-ui/robots.txt +2 -0
- package/dist/src/executable-resolution/executable-resolution.js +118 -0
- package/dist/src/executable-resolution/windows.js +65 -0
- package/dist/src/server/agent/provider-launch-config.js +167 -0
- package/dist/src/server/otto-env.js +53 -0
- package/dist/src/server/otto-home.js +19 -0
- package/dist/src/server/persisted-config.js +471 -0
- package/dist/src/server/pid-lock.js +170 -0
- package/dist/src/server/private-files.js +37 -0
- package/dist/src/server/speech/providers/local/sherpa/sherpa-runtime-env.js +84 -0
- package/dist/src/terminal/shell-integration/zsh/.zshenv +17 -0
- package/dist/src/terminal/shell-integration/zsh/otto-integration.zsh +32 -0
- package/dist/src/utils/spawn.js +59 -0
- package/dist/src/utils/windows-command.js +41 -0
- package/package.json +118 -0
|
@@ -0,0 +1,4515 @@
|
|
|
1
|
+
import { getAgentStreamEventTurnId, } from "../agent-sdk-types.js";
|
|
2
|
+
import { importSessionFromPersistence } from "../provider-session-import.js";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import fs from "node:fs/promises";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { renderPromptAttachmentAsText } from "../prompt-attachments.js";
|
|
9
|
+
import { composeSystemPromptParts } from "../system-prompt.js";
|
|
10
|
+
import { curateAgentActivity } from "../activity-curator.js";
|
|
11
|
+
import { mapCodexToolCallEnvelope, mapCodexToolCallFromThreadItem, splitCodexMcpToolResultImages, } from "./codex/tool-call-mapper.js";
|
|
12
|
+
import { checkProviderLaunchAvailable, createProviderEnv, createProviderEnvSpec, resolveProviderLaunch, } from "../provider-launch-config.js";
|
|
13
|
+
import { findExecutable, probeExecutable, } from "../../../executable-resolution/executable-resolution.js";
|
|
14
|
+
import { createPathEquivalenceMatcher } from "../../../utils/path.js";
|
|
15
|
+
import { spawnProcess } from "../../../utils/spawn.js";
|
|
16
|
+
import { extractCodexTerminalSessionId, nonEmptyString } from "./tool-call-mapper-utils.js";
|
|
17
|
+
import { buildCodexFeatures, codexModelSupportsFastMode } from "./codex-feature-definitions.js";
|
|
18
|
+
import { CodexAppServerClient, parseCodexThreadForkResponse, parseCodexThreadRollbackResponse, } from "./codex/app-server-transport.js";
|
|
19
|
+
import { revertCodexConversation } from "./codex/rewind.js";
|
|
20
|
+
import { materializeProviderImage, renderProviderImageOutputAsAssistantMarkdown, } from "./provider-image-output.js";
|
|
21
|
+
import { normalizeProviderReplayTimestamp } from "../provider-history-timestamps.js";
|
|
22
|
+
import { formatProviderDiagnostic, formatProviderDiagnosticError, buildBinaryDiagnosticRows, buildCommandResolutionDiagnosticRows, resolveBinaryVersion, } from "./diagnostic-utils.js";
|
|
23
|
+
import { runProviderTurn } from "./provider-runner.js";
|
|
24
|
+
import { SETTING_APPLIES_NEXT_TURN_NOTICE } from "../provider-notices.js";
|
|
25
|
+
function assertChildWithPipes(child) {
|
|
26
|
+
if (!child.stdin || !child.stdout || !child.stderr) {
|
|
27
|
+
throw new Error("Child process did not expose stdio pipes");
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function isRecord(value) {
|
|
31
|
+
return value != null && typeof value === "object" && !Array.isArray(value);
|
|
32
|
+
}
|
|
33
|
+
function isCodexAlreadyUnarchivedError(error, threadId) {
|
|
34
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
35
|
+
return message.includes(`no archived rollout found for thread id ${threadId}`);
|
|
36
|
+
}
|
|
37
|
+
const TURN_START_TIMEOUT_MS = 90 * 1000;
|
|
38
|
+
const INTERRUPT_TIMEOUT_MS = 2000;
|
|
39
|
+
const CODEX_PROVIDER = "codex";
|
|
40
|
+
// Codex treats most app-server client names as the model-request originator.
|
|
41
|
+
// This reserved Codex name is non-originating, so requests keep Codex's default
|
|
42
|
+
// CLI identity instead of showing up as Otto in provider usage logs.
|
|
43
|
+
const CODEX_NON_ORIGINATING_APP_SERVER_CLIENT_INFO = {
|
|
44
|
+
name: "codex_app_server_daemon",
|
|
45
|
+
title: "Codex App Server Daemon",
|
|
46
|
+
version: "0.0.0",
|
|
47
|
+
};
|
|
48
|
+
const ASSISTANT_MESSAGE_BOUNDARY_MARKDOWN = "\n\n---\n\n";
|
|
49
|
+
const CODEX_TOOL_THREAD_ITEM_TYPES = new Set([
|
|
50
|
+
"commandExecution",
|
|
51
|
+
"fileChange",
|
|
52
|
+
"mcpToolCall",
|
|
53
|
+
"webSearch",
|
|
54
|
+
"collabAgentToolCall",
|
|
55
|
+
]);
|
|
56
|
+
const CODEX_CONTEXT_COMPACTION_TYPE = "contextCompaction";
|
|
57
|
+
const CODEX_PLAN_IMPLEMENTATION_PROMPT_PREFIX = "The user approved the plan. Implement it now. Do not restate or revise the plan unless blocked.";
|
|
58
|
+
// Codex's experimental `goals` feature ships in 0.128.0+. Older binaries reject
|
|
59
|
+
// `--enable goals` at launch, so we gate by version and silently skip the flag
|
|
60
|
+
// (and the /goal slash command) when the binary is too old.
|
|
61
|
+
const CODEX_GOALS_MIN_VERSION = [0, 128, 0];
|
|
62
|
+
const CODEX_AUTO_REVIEW_MIN_VERSION = [0, 115, 0];
|
|
63
|
+
function parseCodexVersion(versionOutput) {
|
|
64
|
+
const match = versionOutput.match(/(\d+)\.(\d+)\.(\d+)/);
|
|
65
|
+
if (!match)
|
|
66
|
+
return null;
|
|
67
|
+
return [Number(match[1]), Number(match[2]), Number(match[3])];
|
|
68
|
+
}
|
|
69
|
+
function codexVersionAtLeast(versionOutput, min) {
|
|
70
|
+
const parsed = parseCodexVersion(versionOutput);
|
|
71
|
+
if (!parsed)
|
|
72
|
+
return false;
|
|
73
|
+
for (let i = 0; i < 3; i += 1) {
|
|
74
|
+
if (parsed[i] > min[i])
|
|
75
|
+
return true;
|
|
76
|
+
if (parsed[i] < min[i])
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
function parseGoalSubcommand(args) {
|
|
82
|
+
const trimmed = (args ?? "").trim();
|
|
83
|
+
if (!trimmed)
|
|
84
|
+
return { kind: "usage" };
|
|
85
|
+
const lower = trimmed.toLowerCase();
|
|
86
|
+
if (lower === "pause")
|
|
87
|
+
return { kind: "pause" };
|
|
88
|
+
if (lower === "resume")
|
|
89
|
+
return { kind: "resume" };
|
|
90
|
+
if (lower === "clear")
|
|
91
|
+
return { kind: "clear" };
|
|
92
|
+
return { kind: "set", objective: trimmed };
|
|
93
|
+
}
|
|
94
|
+
function formatOutOfBandStatusMessage(text) {
|
|
95
|
+
return `${text.replace(/\n+$/u, "")}\n\n`;
|
|
96
|
+
}
|
|
97
|
+
const CODEX_APP_SERVER_CAPABILITIES = {
|
|
98
|
+
supportsStreaming: true,
|
|
99
|
+
supportsSessionPersistence: true,
|
|
100
|
+
supportsSessionListing: true,
|
|
101
|
+
supportsDynamicModes: false,
|
|
102
|
+
supportsMcpServers: true,
|
|
103
|
+
supportsReasoningStream: true,
|
|
104
|
+
supportsToolInvocations: true,
|
|
105
|
+
supportsRewindConversation: true,
|
|
106
|
+
supportsRewindFiles: false,
|
|
107
|
+
supportsRewindBoth: false,
|
|
108
|
+
};
|
|
109
|
+
const CODEX_MODES = [
|
|
110
|
+
{
|
|
111
|
+
id: "auto",
|
|
112
|
+
label: "Default Permissions",
|
|
113
|
+
description: "Edit files and run commands with Codex's default approval flow.",
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
id: "auto-review",
|
|
117
|
+
label: "Auto-review",
|
|
118
|
+
description: "Same workspace-write permissions as Default, but eligible `on-request` approvals are routed through the auto-reviewer subagent.",
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
id: "full-access",
|
|
122
|
+
label: "Full Access",
|
|
123
|
+
description: "Edit files, run commands, and access the network without additional prompts.",
|
|
124
|
+
isUnattended: true,
|
|
125
|
+
},
|
|
126
|
+
];
|
|
127
|
+
const DEFAULT_CODEX_MODE_ID = "auto";
|
|
128
|
+
const MODE_PRESETS = {
|
|
129
|
+
"read-only": {
|
|
130
|
+
approvalPolicy: "on-request",
|
|
131
|
+
sandbox: "read-only",
|
|
132
|
+
},
|
|
133
|
+
auto: {
|
|
134
|
+
approvalPolicy: "on-request",
|
|
135
|
+
sandbox: "workspace-write",
|
|
136
|
+
},
|
|
137
|
+
"auto-review": {
|
|
138
|
+
approvalPolicy: "on-request",
|
|
139
|
+
sandbox: "workspace-write",
|
|
140
|
+
approvalsReviewer: "auto_review",
|
|
141
|
+
},
|
|
142
|
+
"full-access": {
|
|
143
|
+
approvalPolicy: "never",
|
|
144
|
+
sandbox: "danger-full-access",
|
|
145
|
+
networkAccess: true,
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
function isAutoReviewReviewer(value) {
|
|
149
|
+
return value === "auto_review" || value === "guardian_subagent";
|
|
150
|
+
}
|
|
151
|
+
function applyApprovalsReviewerParam(params, preset) {
|
|
152
|
+
if (preset.approvalsReviewer) {
|
|
153
|
+
params.approvalsReviewer = preset.approvalsReviewer;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function shouldPromoteThreadResponseToAutoReview(params) {
|
|
157
|
+
return (isAutoReviewReviewer(params.approvalsReviewer) &&
|
|
158
|
+
params.approvalPolicy === "on-request" &&
|
|
159
|
+
params.sandbox === "workspace-write");
|
|
160
|
+
}
|
|
161
|
+
function validateCodexMode(modeId) {
|
|
162
|
+
if (!(modeId in MODE_PRESETS)) {
|
|
163
|
+
const validModes = Object.keys(MODE_PRESETS).join(", ");
|
|
164
|
+
throw new Error(`Invalid Codex mode "${modeId}". Valid modes are: ${validModes}`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function normalizeCodexThinkingOptionId(thinkingOptionId) {
|
|
168
|
+
if (typeof thinkingOptionId !== "string") {
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
const normalized = thinkingOptionId.trim();
|
|
172
|
+
if (!normalized || normalized === "default") {
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
return normalized;
|
|
176
|
+
}
|
|
177
|
+
function normalizeCodexModelId(modelId) {
|
|
178
|
+
if (typeof modelId !== "string") {
|
|
179
|
+
return undefined;
|
|
180
|
+
}
|
|
181
|
+
const normalized = modelId.trim();
|
|
182
|
+
if (!normalized) {
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
return normalized;
|
|
186
|
+
}
|
|
187
|
+
function normalizeCodexModelLabel(displayName) {
|
|
188
|
+
return displayName.replace(/\bgpt\b/gi, "GPT");
|
|
189
|
+
}
|
|
190
|
+
function isSchemaRecord(value) {
|
|
191
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
192
|
+
}
|
|
193
|
+
function isObjectSchemaNode(schema) {
|
|
194
|
+
const type = schema.type;
|
|
195
|
+
return (isSchemaRecord(schema.properties) ||
|
|
196
|
+
type === "object" ||
|
|
197
|
+
(Array.isArray(type) && type.includes("object")));
|
|
198
|
+
}
|
|
199
|
+
function normalizeCodexOutputSchemaNode(schema, schemaPath) {
|
|
200
|
+
if (Array.isArray(schema)) {
|
|
201
|
+
return schema.map((entry, index) => normalizeCodexOutputSchemaNode(entry, `${schemaPath}[${index}]`));
|
|
202
|
+
}
|
|
203
|
+
if (!isSchemaRecord(schema)) {
|
|
204
|
+
return schema;
|
|
205
|
+
}
|
|
206
|
+
const normalized = {};
|
|
207
|
+
for (const [key, value] of Object.entries(schema)) {
|
|
208
|
+
normalized[key] = normalizeCodexOutputSchemaNode(value, `${schemaPath}.${key}`);
|
|
209
|
+
}
|
|
210
|
+
if (!isObjectSchemaNode(normalized)) {
|
|
211
|
+
return normalized;
|
|
212
|
+
}
|
|
213
|
+
if (normalized.additionalProperties === undefined) {
|
|
214
|
+
normalized.additionalProperties = false;
|
|
215
|
+
}
|
|
216
|
+
else if (normalized.additionalProperties !== false) {
|
|
217
|
+
throw new Error(`Codex structured outputs require ${schemaPath} to set additionalProperties to false for object schemas.`);
|
|
218
|
+
}
|
|
219
|
+
const properties = isSchemaRecord(normalized.properties) ? normalized.properties : null;
|
|
220
|
+
if (!properties) {
|
|
221
|
+
return normalized;
|
|
222
|
+
}
|
|
223
|
+
const propertyKeys = Object.keys(properties);
|
|
224
|
+
const existingRequired = Array.isArray(normalized.required)
|
|
225
|
+
? normalized.required.filter((entry) => typeof entry === "string")
|
|
226
|
+
: [];
|
|
227
|
+
normalized.required = Array.from(new Set([...existingRequired, ...propertyKeys]));
|
|
228
|
+
return normalized;
|
|
229
|
+
}
|
|
230
|
+
export function normalizeCodexOutputSchema(schema) {
|
|
231
|
+
if (!isSchemaRecord(schema)) {
|
|
232
|
+
throw new Error("Codex structured outputs require a JSON object schema.");
|
|
233
|
+
}
|
|
234
|
+
const normalized = normalizeCodexOutputSchemaNode(schema, "$");
|
|
235
|
+
if (!isSchemaRecord(normalized) || !isObjectSchemaNode(normalized)) {
|
|
236
|
+
throw new Error("Codex structured outputs require a root object schema.");
|
|
237
|
+
}
|
|
238
|
+
return normalized;
|
|
239
|
+
}
|
|
240
|
+
function mergeCodexConfiguredDefaults(primary, fallback) {
|
|
241
|
+
return {
|
|
242
|
+
model: primary.model ?? fallback.model,
|
|
243
|
+
thinkingOptionId: primary.thinkingOptionId ?? fallback.thinkingOptionId,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
function codexMicrosoftStorePackageRoot() {
|
|
247
|
+
const localAppData = process.env.LOCALAPPDATA;
|
|
248
|
+
if (!localAppData) {
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
return path.join(localAppData, "Packages");
|
|
252
|
+
}
|
|
253
|
+
export async function findCodexMicrosoftStoreBinary() {
|
|
254
|
+
if (process.platform !== "win32") {
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
const packageRoot = codexMicrosoftStorePackageRoot();
|
|
258
|
+
if (!packageRoot) {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
let entries;
|
|
262
|
+
try {
|
|
263
|
+
entries = await fs.readdir(packageRoot, { withFileTypes: true });
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
const codexPackages = entries
|
|
269
|
+
.filter((entry) => entry.isDirectory() && entry.name.startsWith("OpenAI.Codex_"))
|
|
270
|
+
.map((entry) => entry.name)
|
|
271
|
+
.sort();
|
|
272
|
+
for (const packageName of codexPackages) {
|
|
273
|
+
const candidate = path.join(packageRoot, packageName, "LocalCache", "Local", "OpenAI", "Codex", "bin", "codex.exe");
|
|
274
|
+
if (await probeExecutable(candidate)) {
|
|
275
|
+
return candidate;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
export async function findDefaultCodexBinary() {
|
|
281
|
+
return (await findExecutable("codex")) ?? (await findCodexMicrosoftStoreBinary());
|
|
282
|
+
}
|
|
283
|
+
async function resolveCodexLaunchPrefix(runtimeSettings) {
|
|
284
|
+
const launch = await resolveCodexLaunch(runtimeSettings);
|
|
285
|
+
const availability = await checkCodexLaunchAvailable(launch);
|
|
286
|
+
if (!availability.available) {
|
|
287
|
+
throw new Error("Codex binary not found. Install the Codex CLI (https://github.com/openai/codex) and ensure it is available in your shell PATH.");
|
|
288
|
+
}
|
|
289
|
+
return {
|
|
290
|
+
command: launch.source === "override" ? launch.command : (availability.resolvedPath ?? launch.command),
|
|
291
|
+
args: launch.args,
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
async function resolveCodexLaunch(runtimeSettings) {
|
|
295
|
+
return resolveProviderLaunch({
|
|
296
|
+
commandConfig: runtimeSettings?.command,
|
|
297
|
+
defaultBinary: {
|
|
298
|
+
command: "codex",
|
|
299
|
+
resolvePath: findDefaultCodexBinary,
|
|
300
|
+
},
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
async function checkCodexLaunchAvailable(launch) {
|
|
304
|
+
return checkProviderLaunchAvailable(launch, {
|
|
305
|
+
command: "codex",
|
|
306
|
+
resolvePath: findDefaultCodexBinary,
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
function resolveCodexHomeDir() {
|
|
310
|
+
return process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex");
|
|
311
|
+
}
|
|
312
|
+
function decodeEscapedChar(next) {
|
|
313
|
+
if (next === "n")
|
|
314
|
+
return "\n";
|
|
315
|
+
if (next === "t")
|
|
316
|
+
return "\t";
|
|
317
|
+
return next;
|
|
318
|
+
}
|
|
319
|
+
function resolvePermissionDecision(response) {
|
|
320
|
+
if (response.behavior === "allow")
|
|
321
|
+
return "accept";
|
|
322
|
+
if (response.interrupt)
|
|
323
|
+
return "cancel";
|
|
324
|
+
return "decline";
|
|
325
|
+
}
|
|
326
|
+
function firstPositiveFiniteNumber(primary, secondary) {
|
|
327
|
+
if (typeof primary === "number" && Number.isFinite(primary) && primary > 0) {
|
|
328
|
+
return primary;
|
|
329
|
+
}
|
|
330
|
+
if (typeof secondary === "number" && Number.isFinite(secondary) && secondary > 0) {
|
|
331
|
+
return secondary;
|
|
332
|
+
}
|
|
333
|
+
return undefined;
|
|
334
|
+
}
|
|
335
|
+
function tokenizeCommandArgs(args) {
|
|
336
|
+
const tokens = [];
|
|
337
|
+
let current = "";
|
|
338
|
+
let quote = null;
|
|
339
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
340
|
+
const ch = args[i];
|
|
341
|
+
if (quote) {
|
|
342
|
+
if (ch === quote) {
|
|
343
|
+
quote = null;
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (ch === "\\" && i + 1 < args.length) {
|
|
347
|
+
const next = args[i + 1];
|
|
348
|
+
if (next === quote || next === "\\" || next === "n" || next === "t") {
|
|
349
|
+
i += 1;
|
|
350
|
+
current += decodeEscapedChar(next);
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
current += ch;
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
if (ch === "'" || ch === '"') {
|
|
358
|
+
quote = ch;
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
if (/\s/.test(ch)) {
|
|
362
|
+
if (current) {
|
|
363
|
+
tokens.push(current);
|
|
364
|
+
current = "";
|
|
365
|
+
}
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
current += ch;
|
|
369
|
+
}
|
|
370
|
+
if (current) {
|
|
371
|
+
tokens.push(current);
|
|
372
|
+
}
|
|
373
|
+
return tokens;
|
|
374
|
+
}
|
|
375
|
+
function parseFrontMatter(markdown) {
|
|
376
|
+
const lines = markdown.split("\n");
|
|
377
|
+
if (lines[0]?.trim() !== "---") {
|
|
378
|
+
return { frontMatter: {}, body: markdown };
|
|
379
|
+
}
|
|
380
|
+
let end = -1;
|
|
381
|
+
for (let i = 1; i < lines.length; i += 1) {
|
|
382
|
+
if (lines[i]?.trim() === "---") {
|
|
383
|
+
end = i;
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
if (end === -1) {
|
|
388
|
+
return { frontMatter: {}, body: markdown };
|
|
389
|
+
}
|
|
390
|
+
const metaLines = lines.slice(1, end);
|
|
391
|
+
const body = lines.slice(end + 1).join("\n");
|
|
392
|
+
const frontMatter = {};
|
|
393
|
+
for (const line of metaLines) {
|
|
394
|
+
const trimmed = line.trim();
|
|
395
|
+
if (!trimmed || trimmed.startsWith("#")) {
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
const idx = trimmed.indexOf(":");
|
|
399
|
+
if (idx <= 0) {
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
const key = trimmed.slice(0, idx).trim();
|
|
403
|
+
let value = trimmed.slice(idx + 1).trim();
|
|
404
|
+
value = value.replace(/^['"]/, "").replace(/['"]$/, "");
|
|
405
|
+
if (key && value) {
|
|
406
|
+
frontMatter[key] = value;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return { frontMatter, body };
|
|
410
|
+
}
|
|
411
|
+
async function listCodexCustomPrompts() {
|
|
412
|
+
const codexHome = resolveCodexHomeDir();
|
|
413
|
+
const promptsDir = path.join(codexHome, "prompts");
|
|
414
|
+
let entries;
|
|
415
|
+
try {
|
|
416
|
+
entries = await fs.readdir(promptsDir, { withFileTypes: true });
|
|
417
|
+
}
|
|
418
|
+
catch {
|
|
419
|
+
return [];
|
|
420
|
+
}
|
|
421
|
+
const mdEntries = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".md") && entry.name.slice(0, -".md".length));
|
|
422
|
+
const parsedCommands = await Promise.all(mdEntries.map(async (entry) => {
|
|
423
|
+
const name = entry.name.slice(0, -".md".length);
|
|
424
|
+
const fullPath = path.join(promptsDir, entry.name);
|
|
425
|
+
let content;
|
|
426
|
+
try {
|
|
427
|
+
content = await fs.readFile(fullPath, "utf8");
|
|
428
|
+
}
|
|
429
|
+
catch {
|
|
430
|
+
return null;
|
|
431
|
+
}
|
|
432
|
+
const parsed = parseFrontMatter(content);
|
|
433
|
+
const description = parsed.frontMatter["description"] ?? "Custom prompt";
|
|
434
|
+
const argumentHint = parsed.frontMatter["argument-hint"] ?? parsed.frontMatter["argument_hint"] ?? "";
|
|
435
|
+
return {
|
|
436
|
+
name: `prompts:${name}`,
|
|
437
|
+
description,
|
|
438
|
+
argumentHint,
|
|
439
|
+
kind: "command",
|
|
440
|
+
};
|
|
441
|
+
}));
|
|
442
|
+
const commands = parsedCommands.filter((cmd) => cmd !== null);
|
|
443
|
+
return commands.sort((a, b) => a.name.localeCompare(b.name));
|
|
444
|
+
}
|
|
445
|
+
export async function listCodexSkills(cwd, workspaceGitService) {
|
|
446
|
+
const candidates = [];
|
|
447
|
+
candidates.push(path.join(cwd, ".codex", "skills"));
|
|
448
|
+
const repoRoot = workspaceGitService
|
|
449
|
+
? await workspaceGitService.resolveRepoRoot(cwd).catch(() => null)
|
|
450
|
+
: null;
|
|
451
|
+
if (repoRoot) {
|
|
452
|
+
candidates.push(path.join(path.dirname(cwd), ".codex", "skills"));
|
|
453
|
+
candidates.push(path.join(repoRoot, ".codex", "skills"));
|
|
454
|
+
}
|
|
455
|
+
candidates.push(path.join(resolveCodexHomeDir(), "skills"));
|
|
456
|
+
const candidateReads = await Promise.all(candidates.map(async (dir) => {
|
|
457
|
+
let entries;
|
|
458
|
+
try {
|
|
459
|
+
entries = await fs.readdir(dir, { withFileTypes: true });
|
|
460
|
+
}
|
|
461
|
+
catch {
|
|
462
|
+
return [];
|
|
463
|
+
}
|
|
464
|
+
const dirEntries = entries.filter((entry) => entry.isDirectory() || entry.isSymbolicLink());
|
|
465
|
+
const skillContents = await Promise.all(dirEntries.map(async (entry) => {
|
|
466
|
+
const skillDir = path.join(dir, entry.name);
|
|
467
|
+
const skillPath = path.join(skillDir, "SKILL.md");
|
|
468
|
+
try {
|
|
469
|
+
return await fs.readFile(skillPath, "utf8");
|
|
470
|
+
}
|
|
471
|
+
catch {
|
|
472
|
+
return null;
|
|
473
|
+
}
|
|
474
|
+
}));
|
|
475
|
+
return skillContents.filter((content) => content !== null);
|
|
476
|
+
}));
|
|
477
|
+
const commandsByName = new Map();
|
|
478
|
+
for (const skillContents of candidateReads) {
|
|
479
|
+
for (const content of skillContents) {
|
|
480
|
+
const { frontMatter } = parseFrontMatter(content);
|
|
481
|
+
const name = frontMatter["name"];
|
|
482
|
+
const description = frontMatter["description"];
|
|
483
|
+
if (!name || !description) {
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
if (!commandsByName.has(name)) {
|
|
487
|
+
commandsByName.set(name, {
|
|
488
|
+
name,
|
|
489
|
+
description,
|
|
490
|
+
argumentHint: "",
|
|
491
|
+
kind: "skill",
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
return Array.from(commandsByName.values()).sort((a, b) => a.name.localeCompare(b.name));
|
|
497
|
+
}
|
|
498
|
+
function escapeRegExp(value) {
|
|
499
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
500
|
+
}
|
|
501
|
+
function expandCodexCustomPrompt(template, args) {
|
|
502
|
+
const trimmedArgs = args ? args.trim() : "";
|
|
503
|
+
const tokens = trimmedArgs ? tokenizeCommandArgs(trimmedArgs) : [];
|
|
504
|
+
const named = {};
|
|
505
|
+
const positional = [];
|
|
506
|
+
for (const token of tokens) {
|
|
507
|
+
const idx = token.indexOf("=");
|
|
508
|
+
if (idx > 0) {
|
|
509
|
+
const key = token.slice(0, idx);
|
|
510
|
+
const value = token.slice(idx + 1);
|
|
511
|
+
if (key) {
|
|
512
|
+
named[key] = value;
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
positional.push(token);
|
|
517
|
+
}
|
|
518
|
+
const dollarPlaceholder = "__CODEX_DOLLAR_PLACEHOLDER__";
|
|
519
|
+
let out = template.split("$$").join(dollarPlaceholder);
|
|
520
|
+
out = out.split("$ARGUMENTS").join(trimmedArgs);
|
|
521
|
+
for (let i = 1; i <= 9; i += 1) {
|
|
522
|
+
const value = positional[i - 1] ?? "";
|
|
523
|
+
out = out.split(`$${i}`).join(value);
|
|
524
|
+
}
|
|
525
|
+
const namedKeys = Object.keys(named).sort((a, b) => b.length - a.length);
|
|
526
|
+
for (const key of namedKeys) {
|
|
527
|
+
const value = named[key] ?? "";
|
|
528
|
+
const re = new RegExp(`\\$${escapeRegExp(key)}\\b`, "g");
|
|
529
|
+
out = out.replace(re, value);
|
|
530
|
+
}
|
|
531
|
+
out = out.split(dollarPlaceholder).join("$");
|
|
532
|
+
return out;
|
|
533
|
+
}
|
|
534
|
+
function toCodexMcpConfig(config) {
|
|
535
|
+
switch (config.type) {
|
|
536
|
+
case "stdio":
|
|
537
|
+
return {
|
|
538
|
+
command: config.command,
|
|
539
|
+
args: config.args,
|
|
540
|
+
env: config.env,
|
|
541
|
+
};
|
|
542
|
+
case "http":
|
|
543
|
+
return {
|
|
544
|
+
url: config.url,
|
|
545
|
+
http_headers: config.headers,
|
|
546
|
+
};
|
|
547
|
+
case "sse":
|
|
548
|
+
return {
|
|
549
|
+
url: config.url,
|
|
550
|
+
http_headers: config.headers,
|
|
551
|
+
};
|
|
552
|
+
default: {
|
|
553
|
+
const _exhaustive = config;
|
|
554
|
+
throw new Error(`Unsupported MCP config type: ${String(_exhaustive.type)}`);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
function toObjectRecord(value) {
|
|
559
|
+
return isRecord(value) ? value : undefined;
|
|
560
|
+
}
|
|
561
|
+
const CodexModelListResponseSchema = z.object({
|
|
562
|
+
data: z
|
|
563
|
+
.array(z.object({
|
|
564
|
+
id: z.string(),
|
|
565
|
+
displayName: z.string().optional(),
|
|
566
|
+
description: z.string().optional(),
|
|
567
|
+
isDefault: z.boolean().optional(),
|
|
568
|
+
model: z.string().optional(),
|
|
569
|
+
defaultReasoningEffort: z.string().optional(),
|
|
570
|
+
supportedReasoningEfforts: z
|
|
571
|
+
.array(z.object({
|
|
572
|
+
reasoningEffort: z.string().optional(),
|
|
573
|
+
description: z.string().optional(),
|
|
574
|
+
}))
|
|
575
|
+
.optional(),
|
|
576
|
+
}))
|
|
577
|
+
.optional(),
|
|
578
|
+
});
|
|
579
|
+
function filterCodexThreadsByCwd(threads, cwd) {
|
|
580
|
+
if (!cwd) {
|
|
581
|
+
return threads;
|
|
582
|
+
}
|
|
583
|
+
// thread/list rows carry an optional cwd. The descriptor builder later
|
|
584
|
+
// falls back to process.cwd() if the field is missing, so we only match
|
|
585
|
+
// here when the row genuinely carries a cwd string — otherwise threads
|
|
586
|
+
// with no cwd would falsely match the daemon's own cwd.
|
|
587
|
+
const matchesCwd = createPathEquivalenceMatcher(cwd);
|
|
588
|
+
return threads.filter((thread) => typeof thread.cwd === "string" && matchesCwd(thread.cwd));
|
|
589
|
+
}
|
|
590
|
+
export function toAgentUsage(tokenUsage) {
|
|
591
|
+
const usage = toObjectRecord(tokenUsage);
|
|
592
|
+
if (!usage)
|
|
593
|
+
return undefined;
|
|
594
|
+
const last = toObjectRecord(usage.last);
|
|
595
|
+
const contextWindowMaxTokens = firstPositiveFiniteNumber(usage.model_context_window, usage.modelContextWindow);
|
|
596
|
+
const contextWindowUsedTokens = firstPositiveFiniteNumber(last?.total_tokens, last?.totalTokens);
|
|
597
|
+
return {
|
|
598
|
+
inputTokens: typeof last?.inputTokens === "number" ? last.inputTokens : undefined,
|
|
599
|
+
cachedInputTokens: typeof last?.cachedInputTokens === "number" ? last.cachedInputTokens : undefined,
|
|
600
|
+
outputTokens: typeof last?.outputTokens === "number" ? last.outputTokens : undefined,
|
|
601
|
+
...(contextWindowMaxTokens !== undefined ? { contextWindowMaxTokens } : {}),
|
|
602
|
+
...(contextWindowUsedTokens !== undefined ? { contextWindowUsedTokens } : {}),
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
function extractUserText(content) {
|
|
606
|
+
if (!Array.isArray(content))
|
|
607
|
+
return null;
|
|
608
|
+
const parts = [];
|
|
609
|
+
for (const item of content) {
|
|
610
|
+
const record = toObjectRecord(item);
|
|
611
|
+
if (!record) {
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
if (record.type === "text" && typeof record.text === "string") {
|
|
615
|
+
parts.push(record.text);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
return parts.length > 0 ? parts.join("\n") : null;
|
|
619
|
+
}
|
|
620
|
+
function normalizePlanMarkdown(text) {
|
|
621
|
+
return text
|
|
622
|
+
.split("\n")
|
|
623
|
+
.map((line) => line.replace(/\s+$/, ""))
|
|
624
|
+
.join("\n")
|
|
625
|
+
.trim();
|
|
626
|
+
}
|
|
627
|
+
export function planStepsToMarkdown(steps) {
|
|
628
|
+
const lines = steps
|
|
629
|
+
.map((entry) => entry.step.trim())
|
|
630
|
+
.filter((step) => step.length > 0)
|
|
631
|
+
.map((step) => {
|
|
632
|
+
if (/^(#{1,6}\s|[-*+]\s|\d+\.\s)/.test(step)) {
|
|
633
|
+
return step;
|
|
634
|
+
}
|
|
635
|
+
return `- ${step}`;
|
|
636
|
+
});
|
|
637
|
+
return normalizePlanMarkdown(lines.join("\n"));
|
|
638
|
+
}
|
|
639
|
+
export function mapCodexPlanToToolCall(params) {
|
|
640
|
+
const text = normalizePlanMarkdown(params.text);
|
|
641
|
+
if (!text) {
|
|
642
|
+
return null;
|
|
643
|
+
}
|
|
644
|
+
return {
|
|
645
|
+
type: "tool_call",
|
|
646
|
+
callId: params.callId,
|
|
647
|
+
name: "plan",
|
|
648
|
+
status: "completed",
|
|
649
|
+
error: null,
|
|
650
|
+
detail: {
|
|
651
|
+
type: "plan",
|
|
652
|
+
text,
|
|
653
|
+
},
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
function buildPlanPermissionActions(options) {
|
|
657
|
+
const actions = [
|
|
658
|
+
{
|
|
659
|
+
id: "reject",
|
|
660
|
+
label: "Reject",
|
|
661
|
+
behavior: "deny",
|
|
662
|
+
variant: "danger",
|
|
663
|
+
intent: "dismiss",
|
|
664
|
+
},
|
|
665
|
+
{
|
|
666
|
+
id: "implement",
|
|
667
|
+
label: "Implement",
|
|
668
|
+
behavior: "allow",
|
|
669
|
+
variant: "primary",
|
|
670
|
+
intent: "implement",
|
|
671
|
+
},
|
|
672
|
+
];
|
|
673
|
+
if (options?.includeResumeAction && options.resumeLabel) {
|
|
674
|
+
actions.push({
|
|
675
|
+
id: "implement_resume",
|
|
676
|
+
label: options.resumeLabel,
|
|
677
|
+
behavior: "allow",
|
|
678
|
+
variant: "secondary",
|
|
679
|
+
intent: "implement_resume",
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
return actions;
|
|
683
|
+
}
|
|
684
|
+
function buildCodexPlanImplementationPrompt(planText) {
|
|
685
|
+
const normalizedPlan = normalizePlanMarkdown(planText);
|
|
686
|
+
if (!normalizedPlan) {
|
|
687
|
+
return `${CODEX_PLAN_IMPLEMENTATION_PROMPT_PREFIX} Make the required code changes and verify them.`;
|
|
688
|
+
}
|
|
689
|
+
return [
|
|
690
|
+
CODEX_PLAN_IMPLEMENTATION_PROMPT_PREFIX,
|
|
691
|
+
"Approved plan:",
|
|
692
|
+
normalizedPlan,
|
|
693
|
+
"Carry out the work, make the necessary code changes, and verify the result.",
|
|
694
|
+
].join("\n\n");
|
|
695
|
+
}
|
|
696
|
+
export function normalizeCodexQuestionPrompts(raw) {
|
|
697
|
+
if (!Array.isArray(raw)) {
|
|
698
|
+
return [];
|
|
699
|
+
}
|
|
700
|
+
const questions = [];
|
|
701
|
+
for (const item of raw) {
|
|
702
|
+
const record = toObjectRecord(item);
|
|
703
|
+
if (!record) {
|
|
704
|
+
continue;
|
|
705
|
+
}
|
|
706
|
+
const id = nonEmptyString(record.id);
|
|
707
|
+
const header = nonEmptyString(record.header);
|
|
708
|
+
const question = nonEmptyString(record.question);
|
|
709
|
+
if (!id || !header || !question) {
|
|
710
|
+
continue;
|
|
711
|
+
}
|
|
712
|
+
const options = Array.isArray(record.options)
|
|
713
|
+
? record.options.flatMap((option) => {
|
|
714
|
+
const optionRecord = toObjectRecord(option);
|
|
715
|
+
if (!optionRecord) {
|
|
716
|
+
return [];
|
|
717
|
+
}
|
|
718
|
+
const label = nonEmptyString(optionRecord.label);
|
|
719
|
+
if (!label) {
|
|
720
|
+
return [];
|
|
721
|
+
}
|
|
722
|
+
return [
|
|
723
|
+
{
|
|
724
|
+
label,
|
|
725
|
+
...(typeof optionRecord.description === "string" &&
|
|
726
|
+
optionRecord.description.trim().length > 0
|
|
727
|
+
? { description: optionRecord.description }
|
|
728
|
+
: {}),
|
|
729
|
+
},
|
|
730
|
+
];
|
|
731
|
+
})
|
|
732
|
+
: [];
|
|
733
|
+
questions.push({
|
|
734
|
+
id,
|
|
735
|
+
header,
|
|
736
|
+
question,
|
|
737
|
+
options,
|
|
738
|
+
...(record.multiSelect === true ? { multiSelect: true } : {}),
|
|
739
|
+
...(record.isOther === true ? { isOther: true } : {}),
|
|
740
|
+
...(record.isSecret === true ? { isSecret: true } : {}),
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
return questions;
|
|
744
|
+
}
|
|
745
|
+
export function formatCodexQuestionPrompts(questions) {
|
|
746
|
+
return questions
|
|
747
|
+
.map((question) => {
|
|
748
|
+
const lines = [`${question.header}: ${question.question}`];
|
|
749
|
+
if (question.options.length > 0) {
|
|
750
|
+
lines.push(`Options: ${question.options.map((option) => option.label).join(", ")}`);
|
|
751
|
+
}
|
|
752
|
+
return lines.join("\n");
|
|
753
|
+
})
|
|
754
|
+
.join("\n\n")
|
|
755
|
+
.trim();
|
|
756
|
+
}
|
|
757
|
+
export function mapCodexQuestionRequestToToolCall(params) {
|
|
758
|
+
const formattedQuestions = formatCodexQuestionPrompts(params.questions);
|
|
759
|
+
const formattedAnswers = params.answers && Object.keys(params.answers).length > 0
|
|
760
|
+
? Object.entries(params.answers)
|
|
761
|
+
.map(([id, values]) => `${id}: ${values.join(", ")}`)
|
|
762
|
+
.join("\n")
|
|
763
|
+
: null;
|
|
764
|
+
const detailText = params.status === "completed" && formattedAnswers
|
|
765
|
+
? [formattedQuestions, "Answers:", formattedAnswers].filter(Boolean).join("\n\n")
|
|
766
|
+
: formattedQuestions;
|
|
767
|
+
const base = {
|
|
768
|
+
type: "tool_call",
|
|
769
|
+
callId: params.callId,
|
|
770
|
+
name: "request_user_input",
|
|
771
|
+
detail: {
|
|
772
|
+
type: "plain_text",
|
|
773
|
+
text: detailText,
|
|
774
|
+
icon: "brain",
|
|
775
|
+
},
|
|
776
|
+
metadata: {
|
|
777
|
+
questions: params.questions,
|
|
778
|
+
...(params.answers ? { answers: params.answers } : {}),
|
|
779
|
+
},
|
|
780
|
+
};
|
|
781
|
+
if (params.status === "failed") {
|
|
782
|
+
return {
|
|
783
|
+
...base,
|
|
784
|
+
status: "failed",
|
|
785
|
+
error: params.error ?? { message: "Question dismissed" },
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
if (params.status === "canceled") {
|
|
789
|
+
return {
|
|
790
|
+
...base,
|
|
791
|
+
status: "canceled",
|
|
792
|
+
error: null,
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
if (params.status === "running") {
|
|
796
|
+
return {
|
|
797
|
+
...base,
|
|
798
|
+
status: "running",
|
|
799
|
+
error: null,
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
return {
|
|
803
|
+
...base,
|
|
804
|
+
status: "completed",
|
|
805
|
+
error: null,
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
function mapCodexQuestionResponseByHeader(params) {
|
|
809
|
+
if (params.response.behavior !== "allow") {
|
|
810
|
+
return null;
|
|
811
|
+
}
|
|
812
|
+
const updatedInputRecord = toObjectRecord(params.response.updatedInput);
|
|
813
|
+
const answersRecord = toObjectRecord(updatedInputRecord?.answers);
|
|
814
|
+
if (!answersRecord) {
|
|
815
|
+
return null;
|
|
816
|
+
}
|
|
817
|
+
const answers = {};
|
|
818
|
+
for (const question of params.questions) {
|
|
819
|
+
const rawAnswer = answersRecord[question.header];
|
|
820
|
+
if (typeof rawAnswer !== "string") {
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
const normalizedAnswer = rawAnswer.trim();
|
|
824
|
+
if (!normalizedAnswer) {
|
|
825
|
+
continue;
|
|
826
|
+
}
|
|
827
|
+
const values = question.multiSelect
|
|
828
|
+
? normalizedAnswer
|
|
829
|
+
.split(",")
|
|
830
|
+
.map((entry) => entry.trim())
|
|
831
|
+
.filter((entry) => entry.length > 0)
|
|
832
|
+
: [normalizedAnswer];
|
|
833
|
+
if (values.length > 0) {
|
|
834
|
+
answers[question.id] = { answers: values };
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
return Object.keys(answers).length > 0 ? answers : null;
|
|
838
|
+
}
|
|
839
|
+
function extractPatchLikeText(value) {
|
|
840
|
+
const record = toObjectRecord(value);
|
|
841
|
+
if (!record) {
|
|
842
|
+
return undefined;
|
|
843
|
+
}
|
|
844
|
+
const candidates = [
|
|
845
|
+
record.diff,
|
|
846
|
+
record.patch,
|
|
847
|
+
record.unified_diff,
|
|
848
|
+
record.unifiedDiff,
|
|
849
|
+
record.content,
|
|
850
|
+
record.newString,
|
|
851
|
+
];
|
|
852
|
+
for (const candidate of candidates) {
|
|
853
|
+
if (typeof candidate === "string" && candidate.length > 0) {
|
|
854
|
+
return candidate;
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
return undefined;
|
|
858
|
+
}
|
|
859
|
+
function normalizeCodexThreadItemType(rawType) {
|
|
860
|
+
if (!rawType) {
|
|
861
|
+
return rawType;
|
|
862
|
+
}
|
|
863
|
+
switch (rawType) {
|
|
864
|
+
case "UserMessage":
|
|
865
|
+
return "userMessage";
|
|
866
|
+
case "AgentMessage":
|
|
867
|
+
return "agentMessage";
|
|
868
|
+
case "Reasoning":
|
|
869
|
+
return "reasoning";
|
|
870
|
+
case "Plan":
|
|
871
|
+
return "plan";
|
|
872
|
+
case "CommandExecution":
|
|
873
|
+
return "commandExecution";
|
|
874
|
+
case "FileChange":
|
|
875
|
+
return "fileChange";
|
|
876
|
+
case "McpToolCall":
|
|
877
|
+
return "mcpToolCall";
|
|
878
|
+
case "WebSearch":
|
|
879
|
+
return "webSearch";
|
|
880
|
+
case "CollabAgentToolCall":
|
|
881
|
+
return "collabAgentToolCall";
|
|
882
|
+
case "ImageView":
|
|
883
|
+
return "imageView";
|
|
884
|
+
case "ImageGeneration":
|
|
885
|
+
return "imageGeneration";
|
|
886
|
+
default:
|
|
887
|
+
return rawType;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
function normalizeCodexCommandValue(value) {
|
|
891
|
+
if (typeof value === "string") {
|
|
892
|
+
const trimmed = value.trim();
|
|
893
|
+
if (!trimmed.length) {
|
|
894
|
+
return null;
|
|
895
|
+
}
|
|
896
|
+
const wrapperMatch = trimmed.match(/^(?:\/bin\/)?(?:zsh|bash|sh)\s+-(?:lc|c)\s+([\s\S]+)$/);
|
|
897
|
+
if (!wrapperMatch) {
|
|
898
|
+
return trimmed;
|
|
899
|
+
}
|
|
900
|
+
const candidate = wrapperMatch[1]?.trim() ?? "";
|
|
901
|
+
if (!candidate.length) {
|
|
902
|
+
return trimmed;
|
|
903
|
+
}
|
|
904
|
+
if ((candidate.startsWith('"') && candidate.endsWith('"')) ||
|
|
905
|
+
(candidate.startsWith("'") && candidate.endsWith("'"))) {
|
|
906
|
+
return candidate.slice(1, -1);
|
|
907
|
+
}
|
|
908
|
+
return candidate;
|
|
909
|
+
}
|
|
910
|
+
if (!Array.isArray(value)) {
|
|
911
|
+
return null;
|
|
912
|
+
}
|
|
913
|
+
const parts = value
|
|
914
|
+
.filter((entry) => typeof entry === "string")
|
|
915
|
+
.map((entry) => entry.trim())
|
|
916
|
+
.filter((entry) => entry.length > 0);
|
|
917
|
+
if (parts.length === 0) {
|
|
918
|
+
return null;
|
|
919
|
+
}
|
|
920
|
+
if (parts.length >= 3 && (parts[1] === "-lc" || parts[1] === "-c")) {
|
|
921
|
+
return parts[2] ?? parts;
|
|
922
|
+
}
|
|
923
|
+
return parts;
|
|
924
|
+
}
|
|
925
|
+
function parseCodexPatchChanges(changes) {
|
|
926
|
+
const resolvePathFromRecord = (record) => {
|
|
927
|
+
const directPath = (typeof record.path === "string" && record.path.trim().length > 0
|
|
928
|
+
? record.path.trim()
|
|
929
|
+
: "") ||
|
|
930
|
+
(typeof record.file_path === "string" && record.file_path.trim().length > 0
|
|
931
|
+
? record.file_path.trim()
|
|
932
|
+
: "") ||
|
|
933
|
+
(typeof record.filePath === "string" && record.filePath.trim().length > 0
|
|
934
|
+
? record.filePath.trim()
|
|
935
|
+
: "");
|
|
936
|
+
return directPath;
|
|
937
|
+
};
|
|
938
|
+
if (!changes || typeof changes !== "object") {
|
|
939
|
+
return [];
|
|
940
|
+
}
|
|
941
|
+
if (Array.isArray(changes)) {
|
|
942
|
+
return changes
|
|
943
|
+
.map((entry) => {
|
|
944
|
+
const record = toObjectRecord(entry);
|
|
945
|
+
if (!record) {
|
|
946
|
+
return null;
|
|
947
|
+
}
|
|
948
|
+
const pathValue = resolvePathFromRecord(record);
|
|
949
|
+
if (!pathValue) {
|
|
950
|
+
return null;
|
|
951
|
+
}
|
|
952
|
+
return {
|
|
953
|
+
path: pathValue,
|
|
954
|
+
kind: (typeof record.kind === "string" && record.kind) ||
|
|
955
|
+
(typeof record.type === "string" && record.type) ||
|
|
956
|
+
undefined,
|
|
957
|
+
content: extractPatchLikeText(record),
|
|
958
|
+
};
|
|
959
|
+
})
|
|
960
|
+
.filter((entry) => entry !== null);
|
|
961
|
+
}
|
|
962
|
+
const recordChanges = toObjectRecord(changes);
|
|
963
|
+
if (!recordChanges) {
|
|
964
|
+
return [];
|
|
965
|
+
}
|
|
966
|
+
const directPathValue = resolvePathFromRecord(recordChanges);
|
|
967
|
+
if (directPathValue) {
|
|
968
|
+
return [
|
|
969
|
+
{
|
|
970
|
+
path: directPathValue,
|
|
971
|
+
kind: (typeof recordChanges.kind === "string" && recordChanges.kind) ||
|
|
972
|
+
(typeof recordChanges.type === "string" && recordChanges.type) ||
|
|
973
|
+
undefined,
|
|
974
|
+
content: extractPatchLikeText(recordChanges),
|
|
975
|
+
},
|
|
976
|
+
];
|
|
977
|
+
}
|
|
978
|
+
return Object.entries(recordChanges)
|
|
979
|
+
.map(([entryPath, value]) => {
|
|
980
|
+
const normalizedPath = entryPath.trim();
|
|
981
|
+
if (!normalizedPath) {
|
|
982
|
+
return null;
|
|
983
|
+
}
|
|
984
|
+
return {
|
|
985
|
+
path: normalizedPath,
|
|
986
|
+
kind: value &&
|
|
987
|
+
typeof value === "object" &&
|
|
988
|
+
typeof value.type === "string"
|
|
989
|
+
? (value.type ?? undefined)
|
|
990
|
+
: undefined,
|
|
991
|
+
content: extractPatchLikeText(value),
|
|
992
|
+
};
|
|
993
|
+
})
|
|
994
|
+
.filter((entry) => entry !== null);
|
|
995
|
+
}
|
|
996
|
+
function codexPatchTextFields(text) {
|
|
997
|
+
if (typeof text !== "string") {
|
|
998
|
+
return {};
|
|
999
|
+
}
|
|
1000
|
+
const normalized = text.trimStart();
|
|
1001
|
+
const looksLikeUnifiedDiff = normalized.startsWith("diff --git") ||
|
|
1002
|
+
normalized.startsWith("@@") ||
|
|
1003
|
+
normalized.startsWith("--- ") ||
|
|
1004
|
+
normalized.startsWith("+++ ");
|
|
1005
|
+
return looksLikeUnifiedDiff ? { patch: text } : { content: text };
|
|
1006
|
+
}
|
|
1007
|
+
function toRunningToolCall(item) {
|
|
1008
|
+
return {
|
|
1009
|
+
...item,
|
|
1010
|
+
status: "running",
|
|
1011
|
+
error: null,
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
function isEditToolCallWithoutContent(item) {
|
|
1015
|
+
if (item.type !== "tool_call") {
|
|
1016
|
+
return false;
|
|
1017
|
+
}
|
|
1018
|
+
if (item.detail.type !== "edit") {
|
|
1019
|
+
return false;
|
|
1020
|
+
}
|
|
1021
|
+
const hasDiff = typeof item.detail.unifiedDiff === "string" && item.detail.unifiedDiff.trim().length > 0;
|
|
1022
|
+
const hasNewString = typeof item.detail.newString === "string" && item.detail.newString.trim().length > 0;
|
|
1023
|
+
return !hasDiff && !hasNewString;
|
|
1024
|
+
}
|
|
1025
|
+
function decodeCodexOutputDeltaChunk(chunk) {
|
|
1026
|
+
const trimmed = chunk.trim();
|
|
1027
|
+
if (trimmed.length === 0) {
|
|
1028
|
+
return chunk;
|
|
1029
|
+
}
|
|
1030
|
+
if (!/^[A-Za-z0-9+/=]+$/.test(trimmed) || trimmed.length % 4 !== 0) {
|
|
1031
|
+
return chunk;
|
|
1032
|
+
}
|
|
1033
|
+
try {
|
|
1034
|
+
const decoded = Buffer.from(trimmed, "base64").toString("utf8");
|
|
1035
|
+
if (decoded.length === 0) {
|
|
1036
|
+
return chunk;
|
|
1037
|
+
}
|
|
1038
|
+
const normalizedInput = trimmed.replace(/=+$/, "");
|
|
1039
|
+
const normalizedRoundTrip = Buffer.from(decoded, "utf8").toString("base64").replace(/=+$/, "");
|
|
1040
|
+
return normalizedRoundTrip === normalizedInput ? decoded : chunk;
|
|
1041
|
+
}
|
|
1042
|
+
catch {
|
|
1043
|
+
return chunk;
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
function mapCodexExecNotificationToToolCall(params) {
|
|
1047
|
+
const command = normalizeCodexCommandValue(params.command);
|
|
1048
|
+
if (!command) {
|
|
1049
|
+
return null;
|
|
1050
|
+
}
|
|
1051
|
+
const isFailure = params.running
|
|
1052
|
+
? false
|
|
1053
|
+
: params.success === false || (typeof params.exitCode === "number" && params.exitCode !== 0);
|
|
1054
|
+
const output = params.running
|
|
1055
|
+
? null
|
|
1056
|
+
: {
|
|
1057
|
+
command,
|
|
1058
|
+
...(params.output !== null && params.output !== undefined ? { output: params.output } : {}),
|
|
1059
|
+
...(params.exitCode !== null && params.exitCode !== undefined
|
|
1060
|
+
? { exitCode: params.exitCode }
|
|
1061
|
+
: {}),
|
|
1062
|
+
};
|
|
1063
|
+
const mapped = mapCodexToolCallEnvelope({
|
|
1064
|
+
callId: params.callId ?? null,
|
|
1065
|
+
name: "shell",
|
|
1066
|
+
input: {
|
|
1067
|
+
command,
|
|
1068
|
+
...(params.cwd ? { cwd: params.cwd } : {}),
|
|
1069
|
+
},
|
|
1070
|
+
output,
|
|
1071
|
+
error: isFailure ? { message: params.stderr?.trim() || "Command failed" } : null,
|
|
1072
|
+
cwd: params.cwd ?? null,
|
|
1073
|
+
});
|
|
1074
|
+
if (!mapped) {
|
|
1075
|
+
return null;
|
|
1076
|
+
}
|
|
1077
|
+
return params.running ? toRunningToolCall(mapped) : mapped;
|
|
1078
|
+
}
|
|
1079
|
+
export function mapCodexPatchNotificationToToolCall(params) {
|
|
1080
|
+
const files = parseCodexPatchChanges(params.changes);
|
|
1081
|
+
const firstPath = files[0]?.path;
|
|
1082
|
+
const firstPatchText = files
|
|
1083
|
+
.map((file) => file.content?.trim())
|
|
1084
|
+
.find((value) => typeof value === "string" && value.length > 0);
|
|
1085
|
+
const patchText = firstPatchText;
|
|
1086
|
+
const patchFields = codexPatchTextFields(patchText);
|
|
1087
|
+
const mapped = mapCodexToolCallEnvelope({
|
|
1088
|
+
callId: params.callId ?? null,
|
|
1089
|
+
name: "apply_patch",
|
|
1090
|
+
input: firstPath
|
|
1091
|
+
? {
|
|
1092
|
+
path: firstPath,
|
|
1093
|
+
...patchFields,
|
|
1094
|
+
files: files.map((file) => ({ path: file.path, kind: file.kind })),
|
|
1095
|
+
}
|
|
1096
|
+
: {
|
|
1097
|
+
changes: params.changes ?? null,
|
|
1098
|
+
...patchFields,
|
|
1099
|
+
},
|
|
1100
|
+
output: params.running
|
|
1101
|
+
? null
|
|
1102
|
+
: {
|
|
1103
|
+
...(files.length > 0
|
|
1104
|
+
? {
|
|
1105
|
+
files: files.map((file) => Object.assign({ path: file.path }, file.kind ? { kind: file.kind } : {}, codexPatchTextFields(file.content ?? patchText))),
|
|
1106
|
+
}
|
|
1107
|
+
: {}),
|
|
1108
|
+
...(params.stdout ? { stdout: params.stdout } : {}),
|
|
1109
|
+
...(params.stderr ? { stderr: params.stderr } : {}),
|
|
1110
|
+
...(params.success !== null && params.success !== undefined
|
|
1111
|
+
? { success: params.success }
|
|
1112
|
+
: {}),
|
|
1113
|
+
},
|
|
1114
|
+
error: params.running || params.success !== false
|
|
1115
|
+
? null
|
|
1116
|
+
: { message: params.stderr?.trim() || "Patch apply failed" },
|
|
1117
|
+
cwd: params.cwd ?? null,
|
|
1118
|
+
});
|
|
1119
|
+
if (!mapped) {
|
|
1120
|
+
return null;
|
|
1121
|
+
}
|
|
1122
|
+
return params.running ? toRunningToolCall(mapped) : mapped;
|
|
1123
|
+
}
|
|
1124
|
+
function mapCodexTerminalInteractionToToolCall(params) {
|
|
1125
|
+
const processId = nonEmptyString(params.processId ?? undefined);
|
|
1126
|
+
const callId = processId
|
|
1127
|
+
? `terminal-session-${processId}`
|
|
1128
|
+
: (nonEmptyString(params.fallbackCallId ?? undefined) ?? "terminal-interaction");
|
|
1129
|
+
const label = nonEmptyString(params.command ?? undefined);
|
|
1130
|
+
return {
|
|
1131
|
+
type: "tool_call",
|
|
1132
|
+
callId,
|
|
1133
|
+
name: "terminal",
|
|
1134
|
+
status: "completed",
|
|
1135
|
+
error: null,
|
|
1136
|
+
detail: {
|
|
1137
|
+
type: "plain_text",
|
|
1138
|
+
...(label ? { label } : {}),
|
|
1139
|
+
icon: "square_terminal",
|
|
1140
|
+
},
|
|
1141
|
+
...(processId ? { metadata: { processId } } : {}),
|
|
1142
|
+
};
|
|
1143
|
+
}
|
|
1144
|
+
function mapCodexThreadPlanItem(normalizedItem) {
|
|
1145
|
+
const callId = nonEmptyString(normalizedItem.id ?? normalizedItem.itemId ?? undefined) ??
|
|
1146
|
+
`plan:${normalizePlanMarkdown(typeof normalizedItem.text === "string" ? normalizedItem.text : "")}`;
|
|
1147
|
+
return mapCodexPlanToToolCall({
|
|
1148
|
+
callId,
|
|
1149
|
+
text: typeof normalizedItem.text === "string" ? normalizedItem.text : "",
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
function mapCodexThreadReasoningItem(normalizedItem) {
|
|
1153
|
+
const summary = Array.isArray(normalizedItem.summary) ? normalizedItem.summary.join("\n") : "";
|
|
1154
|
+
const content = Array.isArray(normalizedItem.content) ? normalizedItem.content.join("\n") : "";
|
|
1155
|
+
const text = summary || content;
|
|
1156
|
+
return text ? { type: "reasoning", text } : null;
|
|
1157
|
+
}
|
|
1158
|
+
function mapCodexThreadUserMessageItem(normalizedItem, includeUserMessage) {
|
|
1159
|
+
if (!includeUserMessage) {
|
|
1160
|
+
return null;
|
|
1161
|
+
}
|
|
1162
|
+
const text = extractUserText(normalizedItem.content) ?? "";
|
|
1163
|
+
const messageId = nonEmptyString(normalizedItem.id);
|
|
1164
|
+
return {
|
|
1165
|
+
type: "user_message",
|
|
1166
|
+
text,
|
|
1167
|
+
...(messageId ? { messageId } : {}),
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
function firstStringField(record, fields) {
|
|
1171
|
+
for (const field of fields) {
|
|
1172
|
+
const value = record[field];
|
|
1173
|
+
if (typeof value === "string") {
|
|
1174
|
+
return value;
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
return null;
|
|
1178
|
+
}
|
|
1179
|
+
function readCodexHistoryTimestamp(item) {
|
|
1180
|
+
const record = toObjectRecord(item);
|
|
1181
|
+
if (!record) {
|
|
1182
|
+
return null;
|
|
1183
|
+
}
|
|
1184
|
+
return (normalizeProviderReplayTimestamp(record.timestamp) ??
|
|
1185
|
+
normalizeProviderReplayTimestamp(record.createdAt) ??
|
|
1186
|
+
normalizeProviderReplayTimestamp(record.created_at));
|
|
1187
|
+
}
|
|
1188
|
+
function readCodexTurnHistoryTimestamp(turn, timelineItem) {
|
|
1189
|
+
const record = toObjectRecord(turn);
|
|
1190
|
+
if (!record) {
|
|
1191
|
+
return null;
|
|
1192
|
+
}
|
|
1193
|
+
const startedAt = normalizeProviderReplayTimestamp(record.startedAt) ??
|
|
1194
|
+
normalizeProviderReplayTimestamp(record.started_at);
|
|
1195
|
+
const completedAt = normalizeProviderReplayTimestamp(record.completedAt) ??
|
|
1196
|
+
normalizeProviderReplayTimestamp(record.completed_at);
|
|
1197
|
+
if (timelineItem.type === "user_message") {
|
|
1198
|
+
return startedAt ?? completedAt;
|
|
1199
|
+
}
|
|
1200
|
+
return completedAt ?? startedAt;
|
|
1201
|
+
}
|
|
1202
|
+
function codexImageOutputFromResult(result) {
|
|
1203
|
+
if (typeof result === "string") {
|
|
1204
|
+
const trimmed = result.trim();
|
|
1205
|
+
if (trimmed.toLowerCase().startsWith("data:image/") ||
|
|
1206
|
+
(/^[A-Za-z0-9+/]+={0,2}$/.test(trimmed) && trimmed.length > 64)) {
|
|
1207
|
+
return { data: trimmed };
|
|
1208
|
+
}
|
|
1209
|
+
return { url: trimmed };
|
|
1210
|
+
}
|
|
1211
|
+
const resultRecord = toObjectRecord(result);
|
|
1212
|
+
if (!resultRecord) {
|
|
1213
|
+
return null;
|
|
1214
|
+
}
|
|
1215
|
+
return {
|
|
1216
|
+
path: firstStringField(resultRecord, ["path", "savedPath", "saved_path"]),
|
|
1217
|
+
url: firstStringField(resultRecord, ["url"]),
|
|
1218
|
+
data: firstStringField(resultRecord, ["data"]),
|
|
1219
|
+
mimeType: firstStringField(resultRecord, ["mimeType", "mime_type"]),
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
function mapCodexThreadImageItem(normalizedType, normalizedItem) {
|
|
1223
|
+
if (normalizedType === "imageView") {
|
|
1224
|
+
return renderProviderImageOutputAsAssistantMarkdown({
|
|
1225
|
+
path: firstStringField(normalizedItem, ["path"]),
|
|
1226
|
+
});
|
|
1227
|
+
}
|
|
1228
|
+
const savedPath = firstStringField(normalizedItem, ["savedPath", "saved_path"]);
|
|
1229
|
+
const result = codexImageOutputFromResult(normalizedItem.result);
|
|
1230
|
+
return renderProviderImageOutputAsAssistantMarkdown({
|
|
1231
|
+
path: savedPath ?? result?.path ?? null,
|
|
1232
|
+
url: result?.url ?? null,
|
|
1233
|
+
data: result?.data ?? null,
|
|
1234
|
+
mimeType: result?.mimeType ?? null,
|
|
1235
|
+
}, { materialize: materializeProviderImage });
|
|
1236
|
+
}
|
|
1237
|
+
export function threadItemToTimeline(item, options) {
|
|
1238
|
+
const itemRecord = toObjectRecord(item);
|
|
1239
|
+
if (!itemRecord)
|
|
1240
|
+
return null;
|
|
1241
|
+
const includeUserMessage = options?.includeUserMessage ?? true;
|
|
1242
|
+
const cwd = options?.cwd ?? null;
|
|
1243
|
+
const normalizedType = normalizeCodexThreadItemType(typeof itemRecord.type === "string" ? itemRecord.type : undefined);
|
|
1244
|
+
const normalizedItem = normalizedType && normalizedType !== itemRecord.type
|
|
1245
|
+
? { ...itemRecord, type: normalizedType }
|
|
1246
|
+
: itemRecord;
|
|
1247
|
+
if (normalizedType === "imageView" || normalizedType === "imageGeneration") {
|
|
1248
|
+
return mapCodexThreadImageItem(normalizedType, normalizedItem);
|
|
1249
|
+
}
|
|
1250
|
+
if (normalizedType && CODEX_TOOL_THREAD_ITEM_TYPES.has(normalizedType)) {
|
|
1251
|
+
return mapCodexToolCallFromThreadItem(normalizedItem, { cwd });
|
|
1252
|
+
}
|
|
1253
|
+
switch (normalizedType) {
|
|
1254
|
+
case "userMessage":
|
|
1255
|
+
return mapCodexThreadUserMessageItem(normalizedItem, includeUserMessage);
|
|
1256
|
+
case "agentMessage": {
|
|
1257
|
+
const messageId = nonEmptyString(normalizedItem.id);
|
|
1258
|
+
return {
|
|
1259
|
+
type: "assistant_message",
|
|
1260
|
+
text: typeof normalizedItem.text === "string" ? normalizedItem.text : "",
|
|
1261
|
+
...(messageId ? { messageId } : {}),
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
case "plan":
|
|
1265
|
+
return mapCodexThreadPlanItem(normalizedItem);
|
|
1266
|
+
case "reasoning":
|
|
1267
|
+
return mapCodexThreadReasoningItem(normalizedItem);
|
|
1268
|
+
case CODEX_CONTEXT_COMPACTION_TYPE:
|
|
1269
|
+
return {
|
|
1270
|
+
type: "compaction",
|
|
1271
|
+
status: "completed",
|
|
1272
|
+
};
|
|
1273
|
+
default:
|
|
1274
|
+
return null;
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
function mcpToolResultImagesToTimeline(item) {
|
|
1278
|
+
const itemRecord = toObjectRecord(item);
|
|
1279
|
+
if (!itemRecord) {
|
|
1280
|
+
return [];
|
|
1281
|
+
}
|
|
1282
|
+
const normalizedType = normalizeCodexThreadItemType(typeof itemRecord.type === "string" ? itemRecord.type : undefined);
|
|
1283
|
+
if (normalizedType !== "mcpToolCall") {
|
|
1284
|
+
return [];
|
|
1285
|
+
}
|
|
1286
|
+
const { images } = splitCodexMcpToolResultImages(itemRecord.result);
|
|
1287
|
+
return images
|
|
1288
|
+
.map((image) => renderProviderImageOutputAsAssistantMarkdown(image, {
|
|
1289
|
+
materialize: materializeProviderImage,
|
|
1290
|
+
}))
|
|
1291
|
+
.filter((timelineItem) => timelineItem !== null);
|
|
1292
|
+
}
|
|
1293
|
+
function threadItemToTimelineEntries(item, options) {
|
|
1294
|
+
const timelineItem = threadItemToTimeline(item, options);
|
|
1295
|
+
if (!timelineItem) {
|
|
1296
|
+
return [];
|
|
1297
|
+
}
|
|
1298
|
+
return [timelineItem, ...mcpToolResultImagesToTimeline(item)];
|
|
1299
|
+
}
|
|
1300
|
+
const CodexThreadReadResponseSchema = z
|
|
1301
|
+
.object({
|
|
1302
|
+
thread: z
|
|
1303
|
+
.object({
|
|
1304
|
+
turns: z
|
|
1305
|
+
.array(z
|
|
1306
|
+
.object({
|
|
1307
|
+
items: z.array(z.unknown()).default([]),
|
|
1308
|
+
})
|
|
1309
|
+
.passthrough())
|
|
1310
|
+
.default([]),
|
|
1311
|
+
})
|
|
1312
|
+
.passthrough()
|
|
1313
|
+
.default({ turns: [] }),
|
|
1314
|
+
})
|
|
1315
|
+
.passthrough();
|
|
1316
|
+
async function requestCodexThreadHistory(requestThread, threadId) {
|
|
1317
|
+
const response = await requestThread(threadId);
|
|
1318
|
+
return CodexThreadReadResponseSchema.parse(response);
|
|
1319
|
+
}
|
|
1320
|
+
async function loadCodexThreadHistoryTimeline(params) {
|
|
1321
|
+
const response = await requestCodexThreadHistory(params.requestThread, params.threadId);
|
|
1322
|
+
const timeline = [];
|
|
1323
|
+
for (const turn of response.thread.turns) {
|
|
1324
|
+
for (const item of turn.items) {
|
|
1325
|
+
for (const timelineItem of threadItemToTimelineEntries(item, { cwd: params.cwd })) {
|
|
1326
|
+
const timestamp = readCodexHistoryTimestamp(item) ?? readCodexTurnHistoryTimestamp(turn, timelineItem);
|
|
1327
|
+
timeline.push({
|
|
1328
|
+
item: timelineItem,
|
|
1329
|
+
timestamp: timestamp ?? undefined,
|
|
1330
|
+
});
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
return timeline;
|
|
1335
|
+
}
|
|
1336
|
+
function readCodexThread(client, threadId) {
|
|
1337
|
+
return client.request("thread/read", {
|
|
1338
|
+
threadId,
|
|
1339
|
+
includeTurns: true,
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
export async function forkCodexThread(client, params) {
|
|
1343
|
+
if (client.forkThread) {
|
|
1344
|
+
return client.forkThread(params);
|
|
1345
|
+
}
|
|
1346
|
+
return parseCodexThreadForkResponse(await client.request("thread/fork", params));
|
|
1347
|
+
}
|
|
1348
|
+
export async function rollbackCodexThread(client, params) {
|
|
1349
|
+
if (client.rollbackThread) {
|
|
1350
|
+
return client.rollbackThread(params);
|
|
1351
|
+
}
|
|
1352
|
+
return parseCodexThreadRollbackResponse(await client.request("thread/rollback", params));
|
|
1353
|
+
}
|
|
1354
|
+
function toSandboxPolicy(type, networkAccess) {
|
|
1355
|
+
switch (type) {
|
|
1356
|
+
case "read-only":
|
|
1357
|
+
return { type: "readOnly" };
|
|
1358
|
+
case "workspace-write":
|
|
1359
|
+
return { type: "workspaceWrite", networkAccess: networkAccess ?? false };
|
|
1360
|
+
case "danger-full-access":
|
|
1361
|
+
return { type: "dangerFullAccess" };
|
|
1362
|
+
default:
|
|
1363
|
+
return { type: "workspaceWrite", networkAccess: networkAccess ?? false };
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
const ThreadStartedNotificationSchema = z
|
|
1367
|
+
.object({
|
|
1368
|
+
thread: z.object({ id: z.string() }).passthrough(),
|
|
1369
|
+
})
|
|
1370
|
+
.passthrough();
|
|
1371
|
+
const TurnStartedNotificationSchema = z
|
|
1372
|
+
.object({
|
|
1373
|
+
threadId: z.string().optional(),
|
|
1374
|
+
turn: z.object({ id: z.string() }).passthrough(),
|
|
1375
|
+
})
|
|
1376
|
+
.passthrough();
|
|
1377
|
+
const TurnCompletedNotificationSchema = z
|
|
1378
|
+
.object({
|
|
1379
|
+
threadId: z.string().optional(),
|
|
1380
|
+
turn: z
|
|
1381
|
+
.object({
|
|
1382
|
+
status: z.string(),
|
|
1383
|
+
error: z
|
|
1384
|
+
.object({
|
|
1385
|
+
message: z.string().optional(),
|
|
1386
|
+
})
|
|
1387
|
+
.passthrough()
|
|
1388
|
+
.nullable()
|
|
1389
|
+
.optional(),
|
|
1390
|
+
})
|
|
1391
|
+
.passthrough(),
|
|
1392
|
+
})
|
|
1393
|
+
.passthrough();
|
|
1394
|
+
const TurnPlanUpdatedNotificationSchema = z
|
|
1395
|
+
.object({
|
|
1396
|
+
plan: z.array(z
|
|
1397
|
+
.object({
|
|
1398
|
+
step: z.string().optional(),
|
|
1399
|
+
status: z.string().optional(),
|
|
1400
|
+
})
|
|
1401
|
+
.passthrough()),
|
|
1402
|
+
})
|
|
1403
|
+
.passthrough();
|
|
1404
|
+
const TurnDiffUpdatedNotificationSchema = z
|
|
1405
|
+
.object({
|
|
1406
|
+
diff: z.string(),
|
|
1407
|
+
})
|
|
1408
|
+
.passthrough();
|
|
1409
|
+
const ThreadTokenUsageUpdatedNotificationSchema = z
|
|
1410
|
+
.object({
|
|
1411
|
+
tokenUsage: z.unknown(),
|
|
1412
|
+
})
|
|
1413
|
+
.passthrough();
|
|
1414
|
+
const ItemTextDeltaNotificationSchema = z
|
|
1415
|
+
.object({
|
|
1416
|
+
threadId: z.string().optional(),
|
|
1417
|
+
itemId: z.string(),
|
|
1418
|
+
delta: z.string(),
|
|
1419
|
+
})
|
|
1420
|
+
.passthrough();
|
|
1421
|
+
const ItemLifecycleNotificationSchema = z
|
|
1422
|
+
.object({
|
|
1423
|
+
threadId: z.string().optional(),
|
|
1424
|
+
item: z
|
|
1425
|
+
.object({
|
|
1426
|
+
id: z.string().optional(),
|
|
1427
|
+
type: z.string().optional(),
|
|
1428
|
+
})
|
|
1429
|
+
.passthrough(),
|
|
1430
|
+
})
|
|
1431
|
+
.passthrough();
|
|
1432
|
+
const ContextCompactedNotificationSchema = z
|
|
1433
|
+
.object({
|
|
1434
|
+
threadId: z.string(),
|
|
1435
|
+
turnId: z.string().optional(),
|
|
1436
|
+
})
|
|
1437
|
+
.passthrough();
|
|
1438
|
+
const CodexEventTurnAbortedNotificationSchema = z
|
|
1439
|
+
.object({
|
|
1440
|
+
msg: z
|
|
1441
|
+
.object({
|
|
1442
|
+
type: z.literal("turn_aborted"),
|
|
1443
|
+
reason: z.string().optional(),
|
|
1444
|
+
})
|
|
1445
|
+
.passthrough(),
|
|
1446
|
+
})
|
|
1447
|
+
.passthrough();
|
|
1448
|
+
const CodexEventTaskCompleteNotificationSchema = z
|
|
1449
|
+
.object({
|
|
1450
|
+
msg: z
|
|
1451
|
+
.object({
|
|
1452
|
+
type: z.literal("task_complete"),
|
|
1453
|
+
})
|
|
1454
|
+
.passthrough(),
|
|
1455
|
+
})
|
|
1456
|
+
.passthrough();
|
|
1457
|
+
const CodexEventItemLifecycleNotificationSchema = z
|
|
1458
|
+
.object({
|
|
1459
|
+
threadId: z.string().optional(),
|
|
1460
|
+
msg: z
|
|
1461
|
+
.object({
|
|
1462
|
+
type: z.enum(["item_started", "item_completed"]),
|
|
1463
|
+
threadId: z.string().optional(),
|
|
1464
|
+
thread_id: z.string().optional(),
|
|
1465
|
+
item: z
|
|
1466
|
+
.object({
|
|
1467
|
+
id: z.string().optional(),
|
|
1468
|
+
type: z.string().optional(),
|
|
1469
|
+
})
|
|
1470
|
+
.passthrough(),
|
|
1471
|
+
})
|
|
1472
|
+
.passthrough(),
|
|
1473
|
+
})
|
|
1474
|
+
.passthrough();
|
|
1475
|
+
const CodexEventExecCommandBeginNotificationSchema = z
|
|
1476
|
+
.object({
|
|
1477
|
+
msg: z
|
|
1478
|
+
.object({
|
|
1479
|
+
type: z.literal("exec_command_begin"),
|
|
1480
|
+
call_id: z.string().optional(),
|
|
1481
|
+
command: z.unknown().optional(),
|
|
1482
|
+
cwd: z.string().optional(),
|
|
1483
|
+
})
|
|
1484
|
+
.passthrough(),
|
|
1485
|
+
})
|
|
1486
|
+
.passthrough();
|
|
1487
|
+
const CodexEventExecCommandEndNotificationSchema = z
|
|
1488
|
+
.object({
|
|
1489
|
+
msg: z
|
|
1490
|
+
.object({
|
|
1491
|
+
type: z.literal("exec_command_end"),
|
|
1492
|
+
call_id: z.string().optional(),
|
|
1493
|
+
command: z.unknown().optional(),
|
|
1494
|
+
cwd: z.string().optional(),
|
|
1495
|
+
stdout: z.string().optional(),
|
|
1496
|
+
stderr: z.string().optional(),
|
|
1497
|
+
aggregated_output: z.string().optional(),
|
|
1498
|
+
aggregatedOutput: z.string().optional(),
|
|
1499
|
+
formatted_output: z.string().optional(),
|
|
1500
|
+
exit_code: z.number().nullable().optional(),
|
|
1501
|
+
exitCode: z.number().nullable().optional(),
|
|
1502
|
+
success: z.boolean().optional(),
|
|
1503
|
+
})
|
|
1504
|
+
.passthrough(),
|
|
1505
|
+
})
|
|
1506
|
+
.passthrough();
|
|
1507
|
+
const CodexEventExecCommandOutputDeltaNotificationSchema = z
|
|
1508
|
+
.object({
|
|
1509
|
+
msg: z
|
|
1510
|
+
.object({
|
|
1511
|
+
type: z.literal("exec_command_output_delta"),
|
|
1512
|
+
call_id: z.string().optional(),
|
|
1513
|
+
stream: z.string().optional(),
|
|
1514
|
+
chunk: z.string().optional(),
|
|
1515
|
+
delta: z.string().optional(),
|
|
1516
|
+
})
|
|
1517
|
+
.passthrough(),
|
|
1518
|
+
})
|
|
1519
|
+
.passthrough();
|
|
1520
|
+
const CodexEventTerminalInteractionNotificationSchema = z
|
|
1521
|
+
.object({
|
|
1522
|
+
msg: z
|
|
1523
|
+
.object({
|
|
1524
|
+
type: z.literal("terminal_interaction"),
|
|
1525
|
+
call_id: z.string().optional(),
|
|
1526
|
+
process_id: z.union([z.string(), z.number()]).optional(),
|
|
1527
|
+
stdin: z.string().optional(),
|
|
1528
|
+
})
|
|
1529
|
+
.passthrough(),
|
|
1530
|
+
})
|
|
1531
|
+
.passthrough();
|
|
1532
|
+
const ItemCommandExecutionTerminalInteractionNotificationSchema = z
|
|
1533
|
+
.object({
|
|
1534
|
+
itemId: z.string().optional(),
|
|
1535
|
+
processId: z.union([z.string(), z.number()]).optional(),
|
|
1536
|
+
stdin: z.string().optional(),
|
|
1537
|
+
})
|
|
1538
|
+
.passthrough();
|
|
1539
|
+
const CodexEventPatchApplyBeginNotificationSchema = z
|
|
1540
|
+
.object({
|
|
1541
|
+
msg: z
|
|
1542
|
+
.object({
|
|
1543
|
+
type: z.literal("patch_apply_begin"),
|
|
1544
|
+
call_id: z.string().optional(),
|
|
1545
|
+
changes: z.unknown().optional(),
|
|
1546
|
+
})
|
|
1547
|
+
.passthrough(),
|
|
1548
|
+
})
|
|
1549
|
+
.passthrough();
|
|
1550
|
+
const CodexEventPatchApplyEndNotificationSchema = z
|
|
1551
|
+
.object({
|
|
1552
|
+
msg: z
|
|
1553
|
+
.object({
|
|
1554
|
+
type: z.literal("patch_apply_end"),
|
|
1555
|
+
call_id: z.string().optional(),
|
|
1556
|
+
changes: z.unknown().optional(),
|
|
1557
|
+
stdout: z.string().optional(),
|
|
1558
|
+
stderr: z.string().optional(),
|
|
1559
|
+
success: z.boolean().optional(),
|
|
1560
|
+
})
|
|
1561
|
+
.passthrough(),
|
|
1562
|
+
})
|
|
1563
|
+
.passthrough();
|
|
1564
|
+
const ItemFileChangeOutputDeltaNotificationSchema = z
|
|
1565
|
+
.object({
|
|
1566
|
+
itemId: z.string(),
|
|
1567
|
+
delta: z.string().optional(),
|
|
1568
|
+
chunk: z.string().optional(),
|
|
1569
|
+
})
|
|
1570
|
+
.passthrough();
|
|
1571
|
+
const CodexEventTurnDiffNotificationSchema = z
|
|
1572
|
+
.object({
|
|
1573
|
+
msg: z
|
|
1574
|
+
.object({
|
|
1575
|
+
type: z.literal("turn_diff"),
|
|
1576
|
+
unified_diff: z.string().optional(),
|
|
1577
|
+
diff: z.string().optional(),
|
|
1578
|
+
})
|
|
1579
|
+
.passthrough(),
|
|
1580
|
+
})
|
|
1581
|
+
.passthrough();
|
|
1582
|
+
const CodexEventThreadRolledBackNotificationSchema = z
|
|
1583
|
+
.object({
|
|
1584
|
+
msg: z
|
|
1585
|
+
.object({
|
|
1586
|
+
type: z.literal("thread_rolled_back"),
|
|
1587
|
+
num_turns: z.number().int().nonnegative().optional(),
|
|
1588
|
+
numTurns: z.number().int().nonnegative().optional(),
|
|
1589
|
+
})
|
|
1590
|
+
.passthrough(),
|
|
1591
|
+
})
|
|
1592
|
+
.passthrough();
|
|
1593
|
+
function isCodexDeltaNotification(parsed) {
|
|
1594
|
+
return (parsed.kind === "agent_message_delta" ||
|
|
1595
|
+
parsed.kind === "reasoning_delta" ||
|
|
1596
|
+
parsed.kind === "exec_command_output_delta" ||
|
|
1597
|
+
parsed.kind === "file_change_output_delta");
|
|
1598
|
+
}
|
|
1599
|
+
const CodexNotificationSchema = z.union([
|
|
1600
|
+
z
|
|
1601
|
+
.object({ method: z.literal("thread/started"), params: ThreadStartedNotificationSchema })
|
|
1602
|
+
.transform(({ params }) => ({
|
|
1603
|
+
kind: "thread_started",
|
|
1604
|
+
threadId: params.thread.id,
|
|
1605
|
+
})),
|
|
1606
|
+
z.object({ method: z.literal("thread/started"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1607
|
+
kind: "invalid_payload",
|
|
1608
|
+
method,
|
|
1609
|
+
params,
|
|
1610
|
+
})),
|
|
1611
|
+
z.object({ method: z.literal("turn/started"), params: TurnStartedNotificationSchema }).transform(({ params }) => ({
|
|
1612
|
+
kind: "turn_started",
|
|
1613
|
+
turnId: params.turn.id,
|
|
1614
|
+
threadId: params.threadId ?? null,
|
|
1615
|
+
})),
|
|
1616
|
+
z.object({ method: z.literal("turn/started"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1617
|
+
kind: "invalid_payload",
|
|
1618
|
+
method,
|
|
1619
|
+
params,
|
|
1620
|
+
})),
|
|
1621
|
+
z
|
|
1622
|
+
.object({ method: z.literal("turn/completed"), params: TurnCompletedNotificationSchema })
|
|
1623
|
+
.transform(({ params }) => ({
|
|
1624
|
+
kind: "turn_completed",
|
|
1625
|
+
status: params.turn.status,
|
|
1626
|
+
errorMessage: params.turn.error?.message ?? null,
|
|
1627
|
+
threadId: params.threadId ?? null,
|
|
1628
|
+
})),
|
|
1629
|
+
z.object({ method: z.literal("turn/completed"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1630
|
+
kind: "invalid_payload",
|
|
1631
|
+
method,
|
|
1632
|
+
params,
|
|
1633
|
+
})),
|
|
1634
|
+
z
|
|
1635
|
+
.object({ method: z.literal("turn/plan/updated"), params: TurnPlanUpdatedNotificationSchema })
|
|
1636
|
+
.transform(({ params }) => ({
|
|
1637
|
+
kind: "plan_updated",
|
|
1638
|
+
plan: params.plan.map((entry) => ({
|
|
1639
|
+
step: entry.step ?? null,
|
|
1640
|
+
status: entry.status ?? null,
|
|
1641
|
+
})),
|
|
1642
|
+
})),
|
|
1643
|
+
z.object({ method: z.literal("turn/plan/updated"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1644
|
+
kind: "invalid_payload",
|
|
1645
|
+
method,
|
|
1646
|
+
params,
|
|
1647
|
+
})),
|
|
1648
|
+
z
|
|
1649
|
+
.object({ method: z.literal("turn/diff/updated"), params: TurnDiffUpdatedNotificationSchema })
|
|
1650
|
+
.transform(({ params }) => ({ kind: "diff_updated", diff: params.diff })),
|
|
1651
|
+
z.object({ method: z.literal("turn/diff/updated"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1652
|
+
kind: "invalid_payload",
|
|
1653
|
+
method,
|
|
1654
|
+
params,
|
|
1655
|
+
})),
|
|
1656
|
+
z
|
|
1657
|
+
.object({
|
|
1658
|
+
method: z.literal("thread/tokenUsage/updated"),
|
|
1659
|
+
params: ThreadTokenUsageUpdatedNotificationSchema,
|
|
1660
|
+
})
|
|
1661
|
+
.transform(({ params }) => ({
|
|
1662
|
+
kind: "token_usage_updated",
|
|
1663
|
+
tokenUsage: params.tokenUsage,
|
|
1664
|
+
})),
|
|
1665
|
+
z.object({ method: z.literal("thread/tokenUsage/updated"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1666
|
+
kind: "invalid_payload",
|
|
1667
|
+
method,
|
|
1668
|
+
params,
|
|
1669
|
+
})),
|
|
1670
|
+
z
|
|
1671
|
+
.object({ method: z.literal("thread/compacted"), params: ContextCompactedNotificationSchema })
|
|
1672
|
+
.transform(({ params }) => ({
|
|
1673
|
+
kind: "context_compacted",
|
|
1674
|
+
threadId: params.threadId,
|
|
1675
|
+
turnId: params.turnId ?? null,
|
|
1676
|
+
})),
|
|
1677
|
+
z.object({ method: z.literal("thread/compacted"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1678
|
+
kind: "invalid_payload",
|
|
1679
|
+
method,
|
|
1680
|
+
params,
|
|
1681
|
+
})),
|
|
1682
|
+
z
|
|
1683
|
+
.object({
|
|
1684
|
+
method: z.literal("item/agentMessage/delta"),
|
|
1685
|
+
params: ItemTextDeltaNotificationSchema,
|
|
1686
|
+
})
|
|
1687
|
+
.transform(({ params }) => ({
|
|
1688
|
+
kind: "agent_message_delta",
|
|
1689
|
+
itemId: params.itemId,
|
|
1690
|
+
delta: params.delta,
|
|
1691
|
+
threadId: params.threadId ?? null,
|
|
1692
|
+
})),
|
|
1693
|
+
z.object({ method: z.literal("item/agentMessage/delta"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1694
|
+
kind: "invalid_payload",
|
|
1695
|
+
method,
|
|
1696
|
+
params,
|
|
1697
|
+
})),
|
|
1698
|
+
z
|
|
1699
|
+
.object({
|
|
1700
|
+
method: z.literal("item/reasoning/summaryTextDelta"),
|
|
1701
|
+
params: ItemTextDeltaNotificationSchema,
|
|
1702
|
+
})
|
|
1703
|
+
.transform(({ params }) => ({
|
|
1704
|
+
kind: "reasoning_delta",
|
|
1705
|
+
itemId: params.itemId,
|
|
1706
|
+
delta: params.delta,
|
|
1707
|
+
threadId: params.threadId ?? null,
|
|
1708
|
+
})),
|
|
1709
|
+
z.object({ method: z.literal("item/reasoning/summaryTextDelta"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1710
|
+
kind: "invalid_payload",
|
|
1711
|
+
method,
|
|
1712
|
+
params,
|
|
1713
|
+
})),
|
|
1714
|
+
z
|
|
1715
|
+
.object({ method: z.literal("item/completed"), params: ItemLifecycleNotificationSchema })
|
|
1716
|
+
.transform(({ params }) => ({
|
|
1717
|
+
kind: "item_completed",
|
|
1718
|
+
source: "item",
|
|
1719
|
+
threadId: params.threadId ?? null,
|
|
1720
|
+
item: params.item,
|
|
1721
|
+
})),
|
|
1722
|
+
z.object({ method: z.literal("item/completed"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1723
|
+
kind: "invalid_payload",
|
|
1724
|
+
method,
|
|
1725
|
+
params,
|
|
1726
|
+
})),
|
|
1727
|
+
z
|
|
1728
|
+
.object({ method: z.literal("item/started"), params: ItemLifecycleNotificationSchema })
|
|
1729
|
+
.transform(({ params }) => ({
|
|
1730
|
+
kind: "item_started",
|
|
1731
|
+
source: "item",
|
|
1732
|
+
threadId: params.threadId ?? null,
|
|
1733
|
+
item: params.item,
|
|
1734
|
+
})),
|
|
1735
|
+
z.object({ method: z.literal("item/started"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1736
|
+
kind: "invalid_payload",
|
|
1737
|
+
method,
|
|
1738
|
+
params,
|
|
1739
|
+
})),
|
|
1740
|
+
z
|
|
1741
|
+
.object({
|
|
1742
|
+
method: z.literal("codex/event/item_started"),
|
|
1743
|
+
params: CodexEventItemLifecycleNotificationSchema,
|
|
1744
|
+
})
|
|
1745
|
+
.transform(({ params }) => ({
|
|
1746
|
+
kind: "item_started",
|
|
1747
|
+
source: "codex_event",
|
|
1748
|
+
threadId: params.threadId ?? params.msg.threadId ?? params.msg.thread_id ?? null,
|
|
1749
|
+
item: params.msg.item,
|
|
1750
|
+
})),
|
|
1751
|
+
z.object({ method: z.literal("codex/event/item_started"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1752
|
+
kind: "invalid_payload",
|
|
1753
|
+
method,
|
|
1754
|
+
params,
|
|
1755
|
+
})),
|
|
1756
|
+
z
|
|
1757
|
+
.object({
|
|
1758
|
+
method: z.literal("codex/event/item_completed"),
|
|
1759
|
+
params: CodexEventItemLifecycleNotificationSchema,
|
|
1760
|
+
})
|
|
1761
|
+
.transform(({ params }) => ({
|
|
1762
|
+
kind: "item_completed",
|
|
1763
|
+
source: "codex_event",
|
|
1764
|
+
threadId: params.threadId ?? params.msg.threadId ?? params.msg.thread_id ?? null,
|
|
1765
|
+
item: params.msg.item,
|
|
1766
|
+
})),
|
|
1767
|
+
z.object({ method: z.literal("codex/event/item_completed"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1768
|
+
kind: "invalid_payload",
|
|
1769
|
+
method,
|
|
1770
|
+
params,
|
|
1771
|
+
})),
|
|
1772
|
+
z
|
|
1773
|
+
.object({
|
|
1774
|
+
method: z.literal("codex/event/exec_command_begin"),
|
|
1775
|
+
params: CodexEventExecCommandBeginNotificationSchema,
|
|
1776
|
+
})
|
|
1777
|
+
.transform(({ params }) => ({
|
|
1778
|
+
kind: "exec_command_started",
|
|
1779
|
+
callId: params.msg.call_id ?? null,
|
|
1780
|
+
command: params.msg.command ?? null,
|
|
1781
|
+
cwd: params.msg.cwd ?? null,
|
|
1782
|
+
})),
|
|
1783
|
+
z.object({ method: z.literal("codex/event/exec_command_begin"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1784
|
+
kind: "invalid_payload",
|
|
1785
|
+
method,
|
|
1786
|
+
params,
|
|
1787
|
+
})),
|
|
1788
|
+
z
|
|
1789
|
+
.object({
|
|
1790
|
+
method: z.literal("codex/event/exec_command_end"),
|
|
1791
|
+
params: CodexEventExecCommandEndNotificationSchema,
|
|
1792
|
+
})
|
|
1793
|
+
.transform(({ params }) => ({
|
|
1794
|
+
kind: "exec_command_completed",
|
|
1795
|
+
callId: params.msg.call_id ?? null,
|
|
1796
|
+
command: params.msg.command ?? null,
|
|
1797
|
+
cwd: params.msg.cwd ?? null,
|
|
1798
|
+
output: params.msg.aggregated_output ??
|
|
1799
|
+
params.msg.aggregatedOutput ??
|
|
1800
|
+
params.msg.formatted_output ??
|
|
1801
|
+
params.msg.stdout ??
|
|
1802
|
+
null,
|
|
1803
|
+
exitCode: params.msg.exit_code ?? params.msg.exitCode ?? null,
|
|
1804
|
+
success: params.msg.success ?? null,
|
|
1805
|
+
stderr: params.msg.stderr ?? null,
|
|
1806
|
+
})),
|
|
1807
|
+
z.object({ method: z.literal("codex/event/exec_command_end"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1808
|
+
kind: "invalid_payload",
|
|
1809
|
+
method,
|
|
1810
|
+
params,
|
|
1811
|
+
})),
|
|
1812
|
+
z
|
|
1813
|
+
.object({
|
|
1814
|
+
method: z.literal("codex/event/exec_command_output_delta"),
|
|
1815
|
+
params: CodexEventExecCommandOutputDeltaNotificationSchema,
|
|
1816
|
+
})
|
|
1817
|
+
.transform(({ params }) => ({
|
|
1818
|
+
kind: "exec_command_output_delta",
|
|
1819
|
+
callId: params.msg.call_id ?? null,
|
|
1820
|
+
stream: params.msg.stream ?? null,
|
|
1821
|
+
chunk: params.msg.chunk ?? params.msg.delta ?? null,
|
|
1822
|
+
})),
|
|
1823
|
+
z
|
|
1824
|
+
.object({
|
|
1825
|
+
method: z.literal("codex/event/exec_command_output_delta"),
|
|
1826
|
+
params: z.unknown(),
|
|
1827
|
+
})
|
|
1828
|
+
.transform(({ method, params }) => ({
|
|
1829
|
+
kind: "invalid_payload",
|
|
1830
|
+
method,
|
|
1831
|
+
params,
|
|
1832
|
+
})),
|
|
1833
|
+
z
|
|
1834
|
+
.object({
|
|
1835
|
+
method: z.literal("codex/event/terminal_interaction"),
|
|
1836
|
+
params: CodexEventTerminalInteractionNotificationSchema,
|
|
1837
|
+
})
|
|
1838
|
+
.transform(({ params }) => ({
|
|
1839
|
+
kind: "terminal_interaction",
|
|
1840
|
+
source: "codex_event",
|
|
1841
|
+
callId: params.msg.call_id ?? null,
|
|
1842
|
+
processId: typeof params.msg.process_id === "number"
|
|
1843
|
+
? String(params.msg.process_id)
|
|
1844
|
+
: (params.msg.process_id ?? null),
|
|
1845
|
+
stdin: params.msg.stdin ?? null,
|
|
1846
|
+
})),
|
|
1847
|
+
z
|
|
1848
|
+
.object({ method: z.literal("codex/event/terminal_interaction"), params: z.unknown() })
|
|
1849
|
+
.transform(({ method, params }) => ({
|
|
1850
|
+
kind: "invalid_payload",
|
|
1851
|
+
method,
|
|
1852
|
+
params,
|
|
1853
|
+
})),
|
|
1854
|
+
z
|
|
1855
|
+
.object({
|
|
1856
|
+
method: z.literal("item/commandExecution/terminalInteraction"),
|
|
1857
|
+
params: ItemCommandExecutionTerminalInteractionNotificationSchema,
|
|
1858
|
+
})
|
|
1859
|
+
.transform(({ params }) => ({
|
|
1860
|
+
kind: "terminal_interaction",
|
|
1861
|
+
source: "item",
|
|
1862
|
+
callId: params.itemId ?? null,
|
|
1863
|
+
processId: typeof params.processId === "number"
|
|
1864
|
+
? String(params.processId)
|
|
1865
|
+
: (params.processId ?? null),
|
|
1866
|
+
stdin: params.stdin ?? null,
|
|
1867
|
+
})),
|
|
1868
|
+
z
|
|
1869
|
+
.object({
|
|
1870
|
+
method: z.literal("item/commandExecution/terminalInteraction"),
|
|
1871
|
+
params: z.unknown(),
|
|
1872
|
+
})
|
|
1873
|
+
.transform(({ method, params }) => ({
|
|
1874
|
+
kind: "invalid_payload",
|
|
1875
|
+
method,
|
|
1876
|
+
params,
|
|
1877
|
+
})),
|
|
1878
|
+
z
|
|
1879
|
+
.object({
|
|
1880
|
+
method: z.literal("codex/event/patch_apply_begin"),
|
|
1881
|
+
params: CodexEventPatchApplyBeginNotificationSchema,
|
|
1882
|
+
})
|
|
1883
|
+
.transform(({ params }) => ({
|
|
1884
|
+
kind: "patch_apply_started",
|
|
1885
|
+
callId: params.msg.call_id ?? null,
|
|
1886
|
+
changes: params.msg.changes ?? null,
|
|
1887
|
+
})),
|
|
1888
|
+
z.object({ method: z.literal("codex/event/patch_apply_begin"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1889
|
+
kind: "invalid_payload",
|
|
1890
|
+
method,
|
|
1891
|
+
params,
|
|
1892
|
+
})),
|
|
1893
|
+
z
|
|
1894
|
+
.object({
|
|
1895
|
+
method: z.literal("codex/event/patch_apply_end"),
|
|
1896
|
+
params: CodexEventPatchApplyEndNotificationSchema,
|
|
1897
|
+
})
|
|
1898
|
+
.transform(({ params }) => ({
|
|
1899
|
+
kind: "patch_apply_completed",
|
|
1900
|
+
callId: params.msg.call_id ?? null,
|
|
1901
|
+
changes: params.msg.changes ?? null,
|
|
1902
|
+
stdout: params.msg.stdout ?? null,
|
|
1903
|
+
stderr: params.msg.stderr ?? null,
|
|
1904
|
+
success: params.msg.success ?? null,
|
|
1905
|
+
})),
|
|
1906
|
+
z.object({ method: z.literal("codex/event/patch_apply_end"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1907
|
+
kind: "invalid_payload",
|
|
1908
|
+
method,
|
|
1909
|
+
params,
|
|
1910
|
+
})),
|
|
1911
|
+
z
|
|
1912
|
+
.object({
|
|
1913
|
+
method: z.literal("item/fileChange/outputDelta"),
|
|
1914
|
+
params: ItemFileChangeOutputDeltaNotificationSchema,
|
|
1915
|
+
})
|
|
1916
|
+
.transform(({ params }) => ({
|
|
1917
|
+
kind: "file_change_output_delta",
|
|
1918
|
+
itemId: params.itemId,
|
|
1919
|
+
delta: params.delta ?? params.chunk ?? null,
|
|
1920
|
+
})),
|
|
1921
|
+
z.object({ method: z.literal("item/fileChange/outputDelta"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1922
|
+
kind: "invalid_payload",
|
|
1923
|
+
method,
|
|
1924
|
+
params,
|
|
1925
|
+
})),
|
|
1926
|
+
z
|
|
1927
|
+
.object({
|
|
1928
|
+
method: z.literal("codex/event/turn_diff"),
|
|
1929
|
+
params: CodexEventTurnDiffNotificationSchema,
|
|
1930
|
+
})
|
|
1931
|
+
.transform(({ params }) => ({
|
|
1932
|
+
kind: "diff_updated",
|
|
1933
|
+
diff: params.msg.unified_diff ?? params.msg.diff ?? "",
|
|
1934
|
+
})),
|
|
1935
|
+
z.object({ method: z.literal("codex/event/turn_diff"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1936
|
+
kind: "invalid_payload",
|
|
1937
|
+
method,
|
|
1938
|
+
params,
|
|
1939
|
+
})),
|
|
1940
|
+
z
|
|
1941
|
+
.object({
|
|
1942
|
+
method: z.literal("codex/event/turn_aborted"),
|
|
1943
|
+
params: CodexEventTurnAbortedNotificationSchema,
|
|
1944
|
+
})
|
|
1945
|
+
.transform(() => ({
|
|
1946
|
+
kind: "turn_completed",
|
|
1947
|
+
status: "interrupted",
|
|
1948
|
+
errorMessage: null,
|
|
1949
|
+
threadId: null,
|
|
1950
|
+
})),
|
|
1951
|
+
z.object({ method: z.literal("codex/event/turn_aborted"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1952
|
+
kind: "invalid_payload",
|
|
1953
|
+
method,
|
|
1954
|
+
params,
|
|
1955
|
+
})),
|
|
1956
|
+
z
|
|
1957
|
+
.object({
|
|
1958
|
+
method: z.literal("codex/event/task_complete"),
|
|
1959
|
+
params: CodexEventTaskCompleteNotificationSchema,
|
|
1960
|
+
})
|
|
1961
|
+
.transform(() => ({
|
|
1962
|
+
kind: "turn_completed",
|
|
1963
|
+
status: "completed",
|
|
1964
|
+
errorMessage: null,
|
|
1965
|
+
threadId: null,
|
|
1966
|
+
})),
|
|
1967
|
+
z.object({ method: z.literal("codex/event/task_complete"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1968
|
+
kind: "invalid_payload",
|
|
1969
|
+
method,
|
|
1970
|
+
params,
|
|
1971
|
+
})),
|
|
1972
|
+
z
|
|
1973
|
+
.object({
|
|
1974
|
+
method: z.literal("codex/event/thread_rolled_back"),
|
|
1975
|
+
params: CodexEventThreadRolledBackNotificationSchema,
|
|
1976
|
+
})
|
|
1977
|
+
.transform(({ params }) => ({
|
|
1978
|
+
kind: "thread_rolled_back",
|
|
1979
|
+
numTurns: params.msg.num_turns ?? params.msg.numTurns ?? 0,
|
|
1980
|
+
})),
|
|
1981
|
+
z.object({ method: z.literal("codex/event/thread_rolled_back"), params: z.unknown() }).transform(({ method, params }) => ({
|
|
1982
|
+
kind: "invalid_payload",
|
|
1983
|
+
method,
|
|
1984
|
+
params,
|
|
1985
|
+
})),
|
|
1986
|
+
z
|
|
1987
|
+
.object({ method: z.string(), params: z.unknown() })
|
|
1988
|
+
.transform(({ method, params }) => ({ kind: "unknown_method", method, params })),
|
|
1989
|
+
]);
|
|
1990
|
+
async function readCodexConfiguredDefaults(client, logger) {
|
|
1991
|
+
let savedConfigDefaults = {};
|
|
1992
|
+
try {
|
|
1993
|
+
const response = toObjectRecord(await client.request("getUserSavedConfig", {}));
|
|
1994
|
+
const config = toObjectRecord(response?.config);
|
|
1995
|
+
const modelValue = typeof config?.model === "string" ? config.model : undefined;
|
|
1996
|
+
const thinkingOptionValue = typeof config?.modelReasoningEffort === "string" ? config.modelReasoningEffort : null;
|
|
1997
|
+
savedConfigDefaults = {
|
|
1998
|
+
model: normalizeCodexModelId(modelValue),
|
|
1999
|
+
thinkingOptionId: normalizeCodexThinkingOptionId(thinkingOptionValue),
|
|
2000
|
+
};
|
|
2001
|
+
}
|
|
2002
|
+
catch (error) {
|
|
2003
|
+
logger.debug({ error }, "Failed to read Codex saved config defaults");
|
|
2004
|
+
}
|
|
2005
|
+
if (savedConfigDefaults.model && savedConfigDefaults.thinkingOptionId) {
|
|
2006
|
+
return savedConfigDefaults;
|
|
2007
|
+
}
|
|
2008
|
+
let configReadDefaults = {};
|
|
2009
|
+
try {
|
|
2010
|
+
const response = toObjectRecord(await client.request("config/read", {}));
|
|
2011
|
+
const config = toObjectRecord(response?.config);
|
|
2012
|
+
const modelValue = typeof config?.model === "string" ? config.model : undefined;
|
|
2013
|
+
const thinkingOptionValue = typeof config?.model_reasoning_effort === "string" ? config.model_reasoning_effort : null;
|
|
2014
|
+
configReadDefaults = {
|
|
2015
|
+
model: normalizeCodexModelId(modelValue),
|
|
2016
|
+
thinkingOptionId: normalizeCodexThinkingOptionId(thinkingOptionValue),
|
|
2017
|
+
};
|
|
2018
|
+
}
|
|
2019
|
+
catch (error) {
|
|
2020
|
+
logger.debug({ error }, "Failed to read Codex config defaults");
|
|
2021
|
+
}
|
|
2022
|
+
return mergeCodexConfiguredDefaults(savedConfigDefaults, configReadDefaults);
|
|
2023
|
+
}
|
|
2024
|
+
export async function codexAppServerTurnInputFromPrompt(prompt, logger) {
|
|
2025
|
+
if (typeof prompt === "string") {
|
|
2026
|
+
return [toCodexTextInput(prompt)];
|
|
2027
|
+
}
|
|
2028
|
+
const output = [];
|
|
2029
|
+
let previousTextBlock = false;
|
|
2030
|
+
for (const block of prompt) {
|
|
2031
|
+
if (block.type === "text") {
|
|
2032
|
+
output.push(toCodexTextInput(block.text));
|
|
2033
|
+
previousTextBlock = block.text.length > 0;
|
|
2034
|
+
continue;
|
|
2035
|
+
}
|
|
2036
|
+
if (block.type === "skill") {
|
|
2037
|
+
output.push(block);
|
|
2038
|
+
previousTextBlock = false;
|
|
2039
|
+
continue;
|
|
2040
|
+
}
|
|
2041
|
+
if (block.type === "image") {
|
|
2042
|
+
try {
|
|
2043
|
+
const filePath = materializeProviderImage({
|
|
2044
|
+
data: block.data,
|
|
2045
|
+
mimeType: block.mimeType,
|
|
2046
|
+
}).path;
|
|
2047
|
+
output.push({ type: "localImage", path: filePath });
|
|
2048
|
+
}
|
|
2049
|
+
catch (error) {
|
|
2050
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2051
|
+
logger.warn({ message }, "Failed to write Codex image attachment");
|
|
2052
|
+
output.push({
|
|
2053
|
+
...toCodexTextInput(`User attached image (failed to write temp file): ${message}`),
|
|
2054
|
+
});
|
|
2055
|
+
}
|
|
2056
|
+
previousTextBlock = false;
|
|
2057
|
+
continue;
|
|
2058
|
+
}
|
|
2059
|
+
const attachmentText = renderPromptAttachmentAsText(block);
|
|
2060
|
+
output.push(toCodexTextInput(previousTextBlock ? `\n\n${attachmentText}` : attachmentText));
|
|
2061
|
+
previousTextBlock = true;
|
|
2062
|
+
}
|
|
2063
|
+
return output;
|
|
2064
|
+
}
|
|
2065
|
+
function toCodexTextInput(text) {
|
|
2066
|
+
return {
|
|
2067
|
+
type: "text",
|
|
2068
|
+
text,
|
|
2069
|
+
text_elements: [],
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
2072
|
+
export function buildCodexAppServerEnv(runtimeSettings, launchEnv) {
|
|
2073
|
+
return createProviderEnv({
|
|
2074
|
+
runtimeSettings,
|
|
2075
|
+
overlays: [launchEnv],
|
|
2076
|
+
});
|
|
2077
|
+
}
|
|
2078
|
+
function buildCodexAppServerInitializeParams() {
|
|
2079
|
+
return {
|
|
2080
|
+
clientInfo: CODEX_NON_ORIGINATING_APP_SERVER_CLIENT_INFO,
|
|
2081
|
+
capabilities: {
|
|
2082
|
+
experimentalApi: true,
|
|
2083
|
+
},
|
|
2084
|
+
};
|
|
2085
|
+
}
|
|
2086
|
+
function normalizeOpenAICompatibleBaseUrl(value) {
|
|
2087
|
+
const trimmed = value.trim();
|
|
2088
|
+
if (!trimmed) {
|
|
2089
|
+
return null;
|
|
2090
|
+
}
|
|
2091
|
+
const withoutTrailingSlashes = trimmed.replace(/\/+$/u, "");
|
|
2092
|
+
if (withoutTrailingSlashes.endsWith("/v1")) {
|
|
2093
|
+
return withoutTrailingSlashes;
|
|
2094
|
+
}
|
|
2095
|
+
return `${withoutTrailingSlashes}/v1`;
|
|
2096
|
+
}
|
|
2097
|
+
function buildCodexCustomProviderConfig(runtimeSettings, customProvider) {
|
|
2098
|
+
if (customProvider?.extends !== CODEX_PROVIDER) {
|
|
2099
|
+
return null;
|
|
2100
|
+
}
|
|
2101
|
+
const baseUrl = runtimeSettings?.env?.OPENAI_BASE_URL;
|
|
2102
|
+
if (typeof baseUrl !== "string") {
|
|
2103
|
+
return null;
|
|
2104
|
+
}
|
|
2105
|
+
const normalizedBaseUrl = normalizeOpenAICompatibleBaseUrl(baseUrl);
|
|
2106
|
+
if (!normalizedBaseUrl) {
|
|
2107
|
+
return null;
|
|
2108
|
+
}
|
|
2109
|
+
const providerConfig = {
|
|
2110
|
+
name: customProvider.label,
|
|
2111
|
+
base_url: normalizedBaseUrl,
|
|
2112
|
+
wire_api: "responses",
|
|
2113
|
+
};
|
|
2114
|
+
if (runtimeSettings?.env?.OPENAI_API_KEY?.trim()) {
|
|
2115
|
+
providerConfig.env_key = "OPENAI_API_KEY";
|
|
2116
|
+
providerConfig.requires_openai_auth = false;
|
|
2117
|
+
}
|
|
2118
|
+
return {
|
|
2119
|
+
model_provider: customProvider.id,
|
|
2120
|
+
model_providers: {
|
|
2121
|
+
[customProvider.id]: providerConfig,
|
|
2122
|
+
},
|
|
2123
|
+
};
|
|
2124
|
+
}
|
|
2125
|
+
export class CodexAppServerAgentSession {
|
|
2126
|
+
constructor(config, resumeHandle, logger, spawnAppServer, deps = {}, ephemeral = false, goalsEnabled = false, autoReviewEnabled = false, agentId) {
|
|
2127
|
+
this.resumeHandle = resumeHandle;
|
|
2128
|
+
this.spawnAppServer = spawnAppServer;
|
|
2129
|
+
this.deps = deps;
|
|
2130
|
+
this.ephemeral = ephemeral;
|
|
2131
|
+
this.goalsEnabled = goalsEnabled;
|
|
2132
|
+
this.autoReviewEnabled = autoReviewEnabled;
|
|
2133
|
+
this.agentId = agentId;
|
|
2134
|
+
this.provider = CODEX_PROVIDER;
|
|
2135
|
+
this.capabilities = CODEX_APP_SERVER_CAPABILITIES;
|
|
2136
|
+
this.currentThreadId = null;
|
|
2137
|
+
this.currentTurnId = null;
|
|
2138
|
+
this.client = null;
|
|
2139
|
+
this.subscribers = new Set();
|
|
2140
|
+
this.nextTurnOrdinal = 0;
|
|
2141
|
+
this.activeForegroundTurnId = null;
|
|
2142
|
+
this.cachedRuntimeInfo = null;
|
|
2143
|
+
this.serviceTier = null;
|
|
2144
|
+
this.planModeEnabled = false;
|
|
2145
|
+
this.historyPending = false;
|
|
2146
|
+
this.persistedHistory = [];
|
|
2147
|
+
this.pendingPermissions = new Map();
|
|
2148
|
+
this.pendingPermissionHandlers = new Map();
|
|
2149
|
+
this.resolvedPermissionRequests = new Set();
|
|
2150
|
+
this.pendingAgentMessages = new Map();
|
|
2151
|
+
this.pendingReasoning = new Map();
|
|
2152
|
+
this.pendingCommandOutputDeltas = new Map();
|
|
2153
|
+
this.pendingFileChangeOutputDeltas = new Map();
|
|
2154
|
+
this.pendingAssistantMessageBoundary = false;
|
|
2155
|
+
this.terminalCommandByProcessId = new Map();
|
|
2156
|
+
this.pendingUnlabeledTerminalInteractions = new Set();
|
|
2157
|
+
this.emittedTerminalInteractionKeys = new Set();
|
|
2158
|
+
this.emittedExecCommandStartedCallIds = new Set();
|
|
2159
|
+
this.emittedExecCommandCompletedCallIds = new Set();
|
|
2160
|
+
this.emittedItemStartedIds = new Set();
|
|
2161
|
+
this.emittedItemCompletedIds = new Set();
|
|
2162
|
+
this.subAgentCallsByCallId = new Map();
|
|
2163
|
+
this.subAgentCallIdByChildThreadId = new Map();
|
|
2164
|
+
this.warnedUnknownNotificationMethods = new Set();
|
|
2165
|
+
this.warnedInvalidNotificationPayloads = new Set();
|
|
2166
|
+
this.warnedIncompleteEditToolCallIds = new Set();
|
|
2167
|
+
this.latestPlanResult = null;
|
|
2168
|
+
this.userMessageTurnIndexes = new Map();
|
|
2169
|
+
this.userMessageTurnIds = [];
|
|
2170
|
+
this.pendingManualCompactionStarts = 0;
|
|
2171
|
+
this.compactionTriggerByItemId = new Map();
|
|
2172
|
+
// Codex can report one completed compaction through both channels:
|
|
2173
|
+
// `thread/compacted` and a completed `contextCompaction` item.
|
|
2174
|
+
this.unpairedCompactionNotificationCompletions = 0;
|
|
2175
|
+
this.unpairedCompactionItemCompletions = 0;
|
|
2176
|
+
this.connected = false;
|
|
2177
|
+
this.collaborationModes = [];
|
|
2178
|
+
this.resolvedCollaborationMode = null;
|
|
2179
|
+
this.cachedSkills = [];
|
|
2180
|
+
this.logger = logger.child({
|
|
2181
|
+
module: "agent",
|
|
2182
|
+
provider: CODEX_PROVIDER,
|
|
2183
|
+
agentId: this.agentId,
|
|
2184
|
+
});
|
|
2185
|
+
if (config.modeId === undefined) {
|
|
2186
|
+
throw new Error("Codex agent requires modeId to be specified");
|
|
2187
|
+
}
|
|
2188
|
+
validateCodexMode(config.modeId);
|
|
2189
|
+
this.currentMode = config.modeId;
|
|
2190
|
+
this.config = config;
|
|
2191
|
+
this.config.thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId);
|
|
2192
|
+
if (this.config.featureValues?.fast_mode && codexModelSupportsFastMode(this.config.model)) {
|
|
2193
|
+
this.serviceTier = "fast";
|
|
2194
|
+
}
|
|
2195
|
+
if (this.config.featureValues?.plan_mode) {
|
|
2196
|
+
this.planModeEnabled = true;
|
|
2197
|
+
}
|
|
2198
|
+
if (this.resumeHandle?.sessionId) {
|
|
2199
|
+
this.currentThreadId = this.resumeHandle.sessionId;
|
|
2200
|
+
this.historyPending = true;
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
get id() {
|
|
2204
|
+
return this.currentThreadId;
|
|
2205
|
+
}
|
|
2206
|
+
get features() {
|
|
2207
|
+
return buildCodexFeatures({
|
|
2208
|
+
modelId: this.config.model,
|
|
2209
|
+
fastModeEnabled: this.serviceTier === "fast",
|
|
2210
|
+
planModeEnabled: this.planModeEnabled,
|
|
2211
|
+
planModeAvailable: this.hasPlanCollaborationMode(),
|
|
2212
|
+
});
|
|
2213
|
+
}
|
|
2214
|
+
async connect() {
|
|
2215
|
+
if (this.connected)
|
|
2216
|
+
return;
|
|
2217
|
+
const child = await this.spawnAppServer();
|
|
2218
|
+
this.client = new CodexAppServerClient(child, this.logger, () => this.traceContext());
|
|
2219
|
+
this.client.setNotificationHandler((method, params) => this.handleNotification(method, params));
|
|
2220
|
+
this.registerRequestHandlers();
|
|
2221
|
+
await this.client.request("initialize", buildCodexAppServerInitializeParams());
|
|
2222
|
+
this.client.notify("initialized", {});
|
|
2223
|
+
await this.loadCollaborationModes();
|
|
2224
|
+
await this.loadSkills();
|
|
2225
|
+
if (this.currentThreadId) {
|
|
2226
|
+
await this.ensureThreadLoaded();
|
|
2227
|
+
await this.loadPersistedHistory();
|
|
2228
|
+
}
|
|
2229
|
+
this.connected = true;
|
|
2230
|
+
}
|
|
2231
|
+
traceContext() {
|
|
2232
|
+
return {
|
|
2233
|
+
agentId: this.agentId,
|
|
2234
|
+
sessionId: this.currentThreadId ?? undefined,
|
|
2235
|
+
turnId: this.activeForegroundTurnId ?? undefined,
|
|
2236
|
+
};
|
|
2237
|
+
}
|
|
2238
|
+
async loadCollaborationModes() {
|
|
2239
|
+
if (!this.client)
|
|
2240
|
+
return;
|
|
2241
|
+
try {
|
|
2242
|
+
const response = toObjectRecord(await this.client.request("collaborationMode/list", {}));
|
|
2243
|
+
const data = Array.isArray(response?.data) ? response.data : [];
|
|
2244
|
+
this.collaborationModes = data.map((entry) => {
|
|
2245
|
+
const record = toObjectRecord(entry);
|
|
2246
|
+
return {
|
|
2247
|
+
name: typeof record?.name === "string" ? record.name : "",
|
|
2248
|
+
mode: typeof record?.mode === "string" ? record.mode : null,
|
|
2249
|
+
model: typeof record?.model === "string" ? record.model : null,
|
|
2250
|
+
reasoning_effort: typeof record?.reasoning_effort === "string" ? record.reasoning_effort : null,
|
|
2251
|
+
developer_instructions: typeof record?.developer_instructions === "string"
|
|
2252
|
+
? record.developer_instructions
|
|
2253
|
+
: null,
|
|
2254
|
+
};
|
|
2255
|
+
});
|
|
2256
|
+
}
|
|
2257
|
+
catch (error) {
|
|
2258
|
+
this.logger.trace({
|
|
2259
|
+
agentId: this.agentId,
|
|
2260
|
+
provider: CODEX_PROVIDER,
|
|
2261
|
+
sessionId: this.currentThreadId,
|
|
2262
|
+
turnId: this.activeForegroundTurnId ?? undefined,
|
|
2263
|
+
error,
|
|
2264
|
+
}, "provider.codex.metadata.collaboration_modes_failed");
|
|
2265
|
+
this.collaborationModes = [];
|
|
2266
|
+
}
|
|
2267
|
+
this.refreshResolvedCollaborationMode();
|
|
2268
|
+
}
|
|
2269
|
+
async loadSkills() {
|
|
2270
|
+
if (!this.client)
|
|
2271
|
+
return;
|
|
2272
|
+
try {
|
|
2273
|
+
const response = toObjectRecord(await this.client.request("skills/list", {
|
|
2274
|
+
cwd: [this.config.cwd],
|
|
2275
|
+
}));
|
|
2276
|
+
const entries = Array.isArray(response?.data) ? response.data : [];
|
|
2277
|
+
const skillsByName = new Map();
|
|
2278
|
+
for (const entry of entries) {
|
|
2279
|
+
const entryRecord = toObjectRecord(entry);
|
|
2280
|
+
const list = Array.isArray(entryRecord?.skills) ? entryRecord.skills : [];
|
|
2281
|
+
for (const skill of list) {
|
|
2282
|
+
const skillRecord = toObjectRecord(skill);
|
|
2283
|
+
if (typeof skillRecord?.name !== "string" || typeof skillRecord?.path !== "string")
|
|
2284
|
+
continue;
|
|
2285
|
+
if (!skillsByName.has(skillRecord.name)) {
|
|
2286
|
+
skillsByName.set(skillRecord.name, {
|
|
2287
|
+
name: skillRecord.name,
|
|
2288
|
+
description: resolveSkillDescription(skillRecord),
|
|
2289
|
+
path: skillRecord.path,
|
|
2290
|
+
});
|
|
2291
|
+
}
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
this.cachedSkills = Array.from(skillsByName.values());
|
|
2295
|
+
}
|
|
2296
|
+
catch (error) {
|
|
2297
|
+
this.logger.trace({
|
|
2298
|
+
agentId: this.agentId,
|
|
2299
|
+
provider: CODEX_PROVIDER,
|
|
2300
|
+
sessionId: this.currentThreadId,
|
|
2301
|
+
turnId: this.activeForegroundTurnId ?? undefined,
|
|
2302
|
+
error,
|
|
2303
|
+
}, "provider.codex.metadata.skills_failed");
|
|
2304
|
+
this.cachedSkills = [];
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
findCollaborationMode(target) {
|
|
2308
|
+
if (this.collaborationModes.length === 0)
|
|
2309
|
+
return null;
|
|
2310
|
+
const findByName = (predicate) => this.collaborationModes.find((entry) => predicate(entry.name.toLowerCase()));
|
|
2311
|
+
if (target === "plan") {
|
|
2312
|
+
return findByName((name) => name.includes("plan") || name.includes("read")) ?? null;
|
|
2313
|
+
}
|
|
2314
|
+
return (findByName((name) => name.includes("auto") || name.includes("code")) ??
|
|
2315
|
+
this.collaborationModes.find((entry) => {
|
|
2316
|
+
const name = entry.name.toLowerCase();
|
|
2317
|
+
return !name.includes("plan") && !name.includes("read");
|
|
2318
|
+
}) ??
|
|
2319
|
+
this.collaborationModes[0] ??
|
|
2320
|
+
null);
|
|
2321
|
+
}
|
|
2322
|
+
hasPlanCollaborationMode() {
|
|
2323
|
+
return this.findCollaborationMode("plan") !== null;
|
|
2324
|
+
}
|
|
2325
|
+
resolveCollaborationMode() {
|
|
2326
|
+
const match = this.findCollaborationMode(this.planModeEnabled ? "plan" : "code");
|
|
2327
|
+
if (!match)
|
|
2328
|
+
return null;
|
|
2329
|
+
const settings = {};
|
|
2330
|
+
if (match.model)
|
|
2331
|
+
settings.model = match.model;
|
|
2332
|
+
if (match.reasoning_effort)
|
|
2333
|
+
settings.reasoning_effort = match.reasoning_effort;
|
|
2334
|
+
const developerInstructions = composeSystemPromptParts(match.developer_instructions, this.config.systemPrompt, this.config.daemonAppendSystemPrompt);
|
|
2335
|
+
if (developerInstructions)
|
|
2336
|
+
settings.developer_instructions = developerInstructions;
|
|
2337
|
+
if (this.config.model)
|
|
2338
|
+
settings.model = this.config.model;
|
|
2339
|
+
const thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId);
|
|
2340
|
+
if (thinkingOptionId)
|
|
2341
|
+
settings.reasoning_effort = thinkingOptionId;
|
|
2342
|
+
return { mode: match.mode ?? "code", settings, name: match.name };
|
|
2343
|
+
}
|
|
2344
|
+
refreshResolvedCollaborationMode() {
|
|
2345
|
+
this.resolvedCollaborationMode = this.resolveCollaborationMode();
|
|
2346
|
+
}
|
|
2347
|
+
applyFeatureValue(featureId, value) {
|
|
2348
|
+
this.config.featureValues = {
|
|
2349
|
+
...this.config.featureValues,
|
|
2350
|
+
[featureId]: value,
|
|
2351
|
+
};
|
|
2352
|
+
if (featureId === "fast_mode") {
|
|
2353
|
+
this.serviceTier = value ? "fast" : null;
|
|
2354
|
+
this.cachedRuntimeInfo = null;
|
|
2355
|
+
return;
|
|
2356
|
+
}
|
|
2357
|
+
this.planModeEnabled = value;
|
|
2358
|
+
this.refreshResolvedCollaborationMode();
|
|
2359
|
+
this.cachedRuntimeInfo = null;
|
|
2360
|
+
}
|
|
2361
|
+
rememberPlanResult(item) {
|
|
2362
|
+
if (item.detail.type !== "plan") {
|
|
2363
|
+
return;
|
|
2364
|
+
}
|
|
2365
|
+
this.latestPlanResult = {
|
|
2366
|
+
callId: item.callId,
|
|
2367
|
+
text: item.detail.text,
|
|
2368
|
+
turnId: this.currentTurnId,
|
|
2369
|
+
};
|
|
2370
|
+
}
|
|
2371
|
+
emitSyntheticPlanApprovalRequest(planText) {
|
|
2372
|
+
const requestId = `permission-${randomUUID()}`;
|
|
2373
|
+
const request = {
|
|
2374
|
+
id: requestId,
|
|
2375
|
+
provider: CODEX_PROVIDER,
|
|
2376
|
+
name: "CodexPlanApproval",
|
|
2377
|
+
kind: "plan",
|
|
2378
|
+
title: "Plan",
|
|
2379
|
+
description: "Review the proposed plan before implementation starts.",
|
|
2380
|
+
input: { plan: planText },
|
|
2381
|
+
actions: buildPlanPermissionActions(),
|
|
2382
|
+
metadata: {
|
|
2383
|
+
planText,
|
|
2384
|
+
source: "codex_plan_approval",
|
|
2385
|
+
},
|
|
2386
|
+
};
|
|
2387
|
+
this.pendingPermissions.set(requestId, request);
|
|
2388
|
+
this.pendingPermissionHandlers.set(requestId, {
|
|
2389
|
+
resolve: () => undefined,
|
|
2390
|
+
kind: "plan",
|
|
2391
|
+
planText,
|
|
2392
|
+
});
|
|
2393
|
+
this.emitEvent({ type: "permission_requested", provider: CODEX_PROVIDER, request });
|
|
2394
|
+
}
|
|
2395
|
+
/**
|
|
2396
|
+
* Prepare the session for plan implementation by disabling plan mode
|
|
2397
|
+
* and returning the implementation prompt. The caller is responsible for
|
|
2398
|
+
* starting the turn through the normal streamAgent path.
|
|
2399
|
+
*/
|
|
2400
|
+
preparePlanImplementation(params) {
|
|
2401
|
+
const planText = typeof params.planText === "string" ? normalizePlanMarkdown(params.planText) : "";
|
|
2402
|
+
this.applyFeatureValue("plan_mode", false);
|
|
2403
|
+
return buildCodexPlanImplementationPrompt(planText);
|
|
2404
|
+
}
|
|
2405
|
+
registerRequestHandlers() {
|
|
2406
|
+
if (!this.client)
|
|
2407
|
+
return;
|
|
2408
|
+
this.client.setRequestHandler("item/commandExecution/requestApproval", (params) => this.handleCommandApprovalRequest(params));
|
|
2409
|
+
this.client.setRequestHandler("item/fileChange/requestApproval", (params) => this.handleFileChangeApprovalRequest(params));
|
|
2410
|
+
this.client.setRequestHandler("item/tool/requestUserInput", (params) => this.handleToolApprovalRequest(params));
|
|
2411
|
+
// Keep the legacy method name for older Codex builds.
|
|
2412
|
+
this.client.setRequestHandler("tool/requestUserInput", (params) => this.handleToolApprovalRequest(params));
|
|
2413
|
+
}
|
|
2414
|
+
async loadPersistedHistory() {
|
|
2415
|
+
if (!this.client || !this.currentThreadId)
|
|
2416
|
+
return;
|
|
2417
|
+
const client = this.client;
|
|
2418
|
+
const threadId = this.currentThreadId;
|
|
2419
|
+
const timeline = await loadCodexThreadHistoryTimeline({
|
|
2420
|
+
threadId,
|
|
2421
|
+
cwd: this.config.cwd ?? null,
|
|
2422
|
+
requestThread: (threadIdToRead) => {
|
|
2423
|
+
return readCodexThread(client, threadIdToRead);
|
|
2424
|
+
},
|
|
2425
|
+
});
|
|
2426
|
+
this.resetCodexUserMessageTurns();
|
|
2427
|
+
for (const entry of timeline) {
|
|
2428
|
+
if (entry.item.type === "user_message") {
|
|
2429
|
+
this.rememberCodexUserMessageTurn(entry.item.messageId);
|
|
2430
|
+
}
|
|
2431
|
+
}
|
|
2432
|
+
if (timeline.length > 0) {
|
|
2433
|
+
this.persistedHistory = timeline;
|
|
2434
|
+
this.historyPending = true;
|
|
2435
|
+
}
|
|
2436
|
+
}
|
|
2437
|
+
async ensureThreadLoaded() {
|
|
2438
|
+
if (!this.client || !this.currentThreadId)
|
|
2439
|
+
return;
|
|
2440
|
+
try {
|
|
2441
|
+
const loaded = toObjectRecord(await this.client.request("thread/loaded/list", {}));
|
|
2442
|
+
const ids = Array.isArray(loaded?.data) ? loaded.data : [];
|
|
2443
|
+
if (ids.includes(this.currentThreadId)) {
|
|
2444
|
+
return;
|
|
2445
|
+
}
|
|
2446
|
+
const params = { threadId: this.currentThreadId };
|
|
2447
|
+
const developerInstructions = composeSystemPromptParts(this.config.systemPrompt, this.config.daemonAppendSystemPrompt);
|
|
2448
|
+
if (developerInstructions) {
|
|
2449
|
+
params.developerInstructions = developerInstructions;
|
|
2450
|
+
}
|
|
2451
|
+
const codexConfig = this.buildCodexInnerConfig();
|
|
2452
|
+
if (codexConfig) {
|
|
2453
|
+
params.config = codexConfig;
|
|
2454
|
+
}
|
|
2455
|
+
await this.client.request("thread/resume", params);
|
|
2456
|
+
}
|
|
2457
|
+
catch (error) {
|
|
2458
|
+
const threadId = this.currentThreadId;
|
|
2459
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2460
|
+
this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread");
|
|
2461
|
+
throw new Error(`Failed to resume Codex thread ${threadId}: ${message}`, { cause: error });
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
parseSlashCommandInput(text) {
|
|
2465
|
+
const trimmed = text.trim();
|
|
2466
|
+
if (!trimmed.startsWith("/") || trimmed.length <= 1) {
|
|
2467
|
+
return null;
|
|
2468
|
+
}
|
|
2469
|
+
const withoutPrefix = trimmed.slice(1);
|
|
2470
|
+
const firstWhitespaceIdx = withoutPrefix.search(/\s/);
|
|
2471
|
+
const commandName = firstWhitespaceIdx === -1 ? withoutPrefix : withoutPrefix.slice(0, firstWhitespaceIdx);
|
|
2472
|
+
if (!commandName || commandName.includes("/")) {
|
|
2473
|
+
return null;
|
|
2474
|
+
}
|
|
2475
|
+
const rawArgs = firstWhitespaceIdx === -1 ? "" : withoutPrefix.slice(firstWhitespaceIdx + 1).trim();
|
|
2476
|
+
return rawArgs.length > 0 ? { commandName, args: rawArgs } : { commandName };
|
|
2477
|
+
}
|
|
2478
|
+
async resolveSlashCommandInvocation(prompt) {
|
|
2479
|
+
if (typeof prompt !== "string") {
|
|
2480
|
+
return null;
|
|
2481
|
+
}
|
|
2482
|
+
const parsed = this.parseSlashCommandInput(prompt);
|
|
2483
|
+
if (!parsed) {
|
|
2484
|
+
return null;
|
|
2485
|
+
}
|
|
2486
|
+
try {
|
|
2487
|
+
const commands = await this.listCommands();
|
|
2488
|
+
return commands.some((command) => command.name === parsed.commandName) ? parsed : null;
|
|
2489
|
+
}
|
|
2490
|
+
catch (error) {
|
|
2491
|
+
this.logger.warn({ err: error, commandName: parsed.commandName }, "Failed to resolve slash command; falling back to plain prompt input");
|
|
2492
|
+
return null;
|
|
2493
|
+
}
|
|
2494
|
+
}
|
|
2495
|
+
async buildCommandPromptInput(commandName, args) {
|
|
2496
|
+
if (commandName.startsWith("prompts:")) {
|
|
2497
|
+
const promptName = commandName.slice("prompts:".length);
|
|
2498
|
+
const codexHome = resolveCodexHomeDir();
|
|
2499
|
+
const promptPath = path.join(codexHome, "prompts", `${promptName}.md`);
|
|
2500
|
+
const raw = await fs.readFile(promptPath, "utf8");
|
|
2501
|
+
const parsed = parseFrontMatter(raw);
|
|
2502
|
+
return expandCodexCustomPrompt(parsed.body, args);
|
|
2503
|
+
}
|
|
2504
|
+
if (!this.connected) {
|
|
2505
|
+
await this.connect();
|
|
2506
|
+
}
|
|
2507
|
+
else {
|
|
2508
|
+
await this.loadSkills();
|
|
2509
|
+
}
|
|
2510
|
+
const skill = this.cachedSkills.find((entry) => entry.name === commandName);
|
|
2511
|
+
if (skill) {
|
|
2512
|
+
const trimmedArgs = args?.trim() ?? "";
|
|
2513
|
+
const text = trimmedArgs ? `$${skill.name} ${trimmedArgs}` : `$${skill.name}`;
|
|
2514
|
+
const input = [
|
|
2515
|
+
{ type: "skill", name: skill.name, path: skill.path },
|
|
2516
|
+
{ type: "text", text },
|
|
2517
|
+
];
|
|
2518
|
+
return input;
|
|
2519
|
+
}
|
|
2520
|
+
return args ? `$${commandName} ${args}` : `$${commandName}`;
|
|
2521
|
+
}
|
|
2522
|
+
async buildTurnStartParams(prompt, options) {
|
|
2523
|
+
const input = await this.buildUserInput(prompt);
|
|
2524
|
+
const preset = MODE_PRESETS[this.currentMode] ?? MODE_PRESETS[DEFAULT_CODEX_MODE_ID];
|
|
2525
|
+
const approvalPolicy = this.config.approvalPolicy ?? preset.approvalPolicy;
|
|
2526
|
+
const sandboxPolicyType = this.config.sandboxMode ?? preset.sandbox;
|
|
2527
|
+
const params = {
|
|
2528
|
+
threadId: this.currentThreadId,
|
|
2529
|
+
input,
|
|
2530
|
+
approvalPolicy,
|
|
2531
|
+
sandboxPolicy: toSandboxPolicy(sandboxPolicyType, typeof this.config.networkAccess === "boolean"
|
|
2532
|
+
? this.config.networkAccess
|
|
2533
|
+
: preset.networkAccess),
|
|
2534
|
+
};
|
|
2535
|
+
applyApprovalsReviewerParam(params, preset);
|
|
2536
|
+
if (this.config.model) {
|
|
2537
|
+
params.model = this.config.model;
|
|
2538
|
+
}
|
|
2539
|
+
const thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId);
|
|
2540
|
+
if (thinkingOptionId) {
|
|
2541
|
+
params.effort = thinkingOptionId;
|
|
2542
|
+
}
|
|
2543
|
+
if (this.serviceTier) {
|
|
2544
|
+
params.serviceTier = this.serviceTier;
|
|
2545
|
+
}
|
|
2546
|
+
if (this.resolvedCollaborationMode) {
|
|
2547
|
+
params.collaborationMode = {
|
|
2548
|
+
mode: this.resolvedCollaborationMode.mode,
|
|
2549
|
+
settings: this.resolvedCollaborationMode.settings,
|
|
2550
|
+
};
|
|
2551
|
+
}
|
|
2552
|
+
if (this.config.cwd) {
|
|
2553
|
+
params.cwd = this.config.cwd;
|
|
2554
|
+
}
|
|
2555
|
+
if (options?.outputSchema) {
|
|
2556
|
+
params.outputSchema = normalizeCodexOutputSchema(options.outputSchema);
|
|
2557
|
+
}
|
|
2558
|
+
const developerInstructions = composeSystemPromptParts(this.config.systemPrompt, this.config.daemonAppendSystemPrompt);
|
|
2559
|
+
if (developerInstructions) {
|
|
2560
|
+
params.developerInstructions = developerInstructions;
|
|
2561
|
+
}
|
|
2562
|
+
const codexConfig = this.buildCodexInnerConfig();
|
|
2563
|
+
if (codexConfig) {
|
|
2564
|
+
params.config = codexConfig;
|
|
2565
|
+
}
|
|
2566
|
+
return {
|
|
2567
|
+
params,
|
|
2568
|
+
thinkingOptionId,
|
|
2569
|
+
approvalPolicy,
|
|
2570
|
+
sandboxPolicyType,
|
|
2571
|
+
hasOutputSchema: Boolean(options?.outputSchema),
|
|
2572
|
+
hasDeveloperInstructions: Boolean(developerInstructions),
|
|
2573
|
+
hasCodexConfig: Boolean(codexConfig),
|
|
2574
|
+
};
|
|
2575
|
+
}
|
|
2576
|
+
logTurnStartSummary({ turnId, thinkingOptionId, approvalPolicy, sandboxPolicyType, hasOutputSchema, hasDeveloperInstructions, hasCodexConfig, }) {
|
|
2577
|
+
this.logger.info({
|
|
2578
|
+
turnId,
|
|
2579
|
+
threadId: this.currentThreadId,
|
|
2580
|
+
model: this.config.model ?? null,
|
|
2581
|
+
modeId: this.currentMode ?? null,
|
|
2582
|
+
effort: thinkingOptionId ?? null,
|
|
2583
|
+
serviceTier: this.serviceTier,
|
|
2584
|
+
cwd: this.config.cwd ?? null,
|
|
2585
|
+
approvalPolicy,
|
|
2586
|
+
sandboxPolicyType,
|
|
2587
|
+
hasCollaborationMode: Boolean(this.resolvedCollaborationMode),
|
|
2588
|
+
hasOutputSchema,
|
|
2589
|
+
hasDeveloperInstructions,
|
|
2590
|
+
hasCodexConfig,
|
|
2591
|
+
}, "Starting Codex app-server turn");
|
|
2592
|
+
}
|
|
2593
|
+
async run(prompt, options) {
|
|
2594
|
+
return runProviderTurn({
|
|
2595
|
+
prompt,
|
|
2596
|
+
runOptions: options,
|
|
2597
|
+
startTurn: (p, o) => this.startTurn(p, o),
|
|
2598
|
+
subscribe: (callback) => this.subscribe(callback),
|
|
2599
|
+
getSessionId: async () => (await this.getRuntimeInfo()).sessionId ?? "",
|
|
2600
|
+
reduceFinalText: ({ current, item }) => {
|
|
2601
|
+
if (item.type === "assistant_message") {
|
|
2602
|
+
return item.text;
|
|
2603
|
+
}
|
|
2604
|
+
if (item.type === "tool_call" && item.detail.type === "plan") {
|
|
2605
|
+
return item.detail.text;
|
|
2606
|
+
}
|
|
2607
|
+
return current;
|
|
2608
|
+
},
|
|
2609
|
+
});
|
|
2610
|
+
}
|
|
2611
|
+
async startTurn(prompt, options) {
|
|
2612
|
+
if (this.activeForegroundTurnId) {
|
|
2613
|
+
throw new Error("A foreground turn is already active");
|
|
2614
|
+
}
|
|
2615
|
+
await this.connect();
|
|
2616
|
+
if (!this.client) {
|
|
2617
|
+
throw new Error("Codex client not initialized");
|
|
2618
|
+
}
|
|
2619
|
+
const slashCommand = await this.resolveSlashCommandInvocation(prompt);
|
|
2620
|
+
const effectivePrompt = slashCommand
|
|
2621
|
+
? await this.buildCommandPromptInput(slashCommand.commandName, slashCommand.args)
|
|
2622
|
+
: prompt;
|
|
2623
|
+
if (this.currentThreadId) {
|
|
2624
|
+
await this.ensureThreadLoaded();
|
|
2625
|
+
}
|
|
2626
|
+
else {
|
|
2627
|
+
await this.ensureThread();
|
|
2628
|
+
}
|
|
2629
|
+
const turnStart = await this.buildTurnStartParams(effectivePrompt, options);
|
|
2630
|
+
const turnId = this.createTurnId();
|
|
2631
|
+
this.activeForegroundTurnId = turnId;
|
|
2632
|
+
try {
|
|
2633
|
+
this.logTurnStartSummary({
|
|
2634
|
+
turnId,
|
|
2635
|
+
thinkingOptionId: turnStart.thinkingOptionId,
|
|
2636
|
+
approvalPolicy: turnStart.approvalPolicy,
|
|
2637
|
+
sandboxPolicyType: turnStart.sandboxPolicyType,
|
|
2638
|
+
hasOutputSchema: turnStart.hasOutputSchema,
|
|
2639
|
+
hasDeveloperInstructions: turnStart.hasDeveloperInstructions,
|
|
2640
|
+
hasCodexConfig: turnStart.hasCodexConfig,
|
|
2641
|
+
});
|
|
2642
|
+
await this.client.request("turn/start", turnStart.params, TURN_START_TIMEOUT_MS);
|
|
2643
|
+
}
|
|
2644
|
+
catch (error) {
|
|
2645
|
+
this.activeForegroundTurnId = null;
|
|
2646
|
+
throw error;
|
|
2647
|
+
}
|
|
2648
|
+
return { turnId };
|
|
2649
|
+
}
|
|
2650
|
+
rememberCodexUserMessageTurn(messageId) {
|
|
2651
|
+
if (typeof messageId !== "string" || messageId.length === 0) {
|
|
2652
|
+
return false;
|
|
2653
|
+
}
|
|
2654
|
+
if (this.userMessageTurnIndexes.has(messageId)) {
|
|
2655
|
+
return false;
|
|
2656
|
+
}
|
|
2657
|
+
this.userMessageTurnIndexes.set(messageId, this.userMessageTurnIds.length);
|
|
2658
|
+
this.userMessageTurnIds.push(messageId);
|
|
2659
|
+
return true;
|
|
2660
|
+
}
|
|
2661
|
+
resetCodexUserMessageTurns() {
|
|
2662
|
+
this.userMessageTurnIndexes.clear();
|
|
2663
|
+
this.userMessageTurnIds.length = 0;
|
|
2664
|
+
}
|
|
2665
|
+
truncateCodexUserMessageTurns(numTurns) {
|
|
2666
|
+
if (numTurns <= 0) {
|
|
2667
|
+
return;
|
|
2668
|
+
}
|
|
2669
|
+
this.userMessageTurnIds.length = Math.max(0, this.userMessageTurnIds.length - numTurns);
|
|
2670
|
+
this.userMessageTurnIndexes.clear();
|
|
2671
|
+
this.userMessageTurnIds.forEach((messageId, index) => {
|
|
2672
|
+
this.userMessageTurnIndexes.set(messageId, index);
|
|
2673
|
+
});
|
|
2674
|
+
}
|
|
2675
|
+
codexUserMessageTurns() {
|
|
2676
|
+
return {
|
|
2677
|
+
resolve: (messageId) => this.userMessageTurnIndexes.get(messageId) ?? null,
|
|
2678
|
+
count: () => this.userMessageTurnIds.length,
|
|
2679
|
+
};
|
|
2680
|
+
}
|
|
2681
|
+
subscribe(callback) {
|
|
2682
|
+
this.subscribers.add(callback);
|
|
2683
|
+
return () => {
|
|
2684
|
+
this.subscribers.delete(callback);
|
|
2685
|
+
};
|
|
2686
|
+
}
|
|
2687
|
+
async *streamHistory() {
|
|
2688
|
+
if (!this.historyPending || this.persistedHistory.length === 0) {
|
|
2689
|
+
return;
|
|
2690
|
+
}
|
|
2691
|
+
const history = this.persistedHistory;
|
|
2692
|
+
this.persistedHistory = [];
|
|
2693
|
+
this.historyPending = false;
|
|
2694
|
+
for (const entry of history) {
|
|
2695
|
+
yield {
|
|
2696
|
+
type: "timeline",
|
|
2697
|
+
provider: CODEX_PROVIDER,
|
|
2698
|
+
item: entry.item,
|
|
2699
|
+
timestamp: entry.timestamp,
|
|
2700
|
+
};
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
async getRuntimeInfo() {
|
|
2704
|
+
if (this.cachedRuntimeInfo)
|
|
2705
|
+
return { ...this.cachedRuntimeInfo };
|
|
2706
|
+
if (!this.connected) {
|
|
2707
|
+
await this.connect();
|
|
2708
|
+
}
|
|
2709
|
+
if (!this.currentThreadId) {
|
|
2710
|
+
await this.ensureThread();
|
|
2711
|
+
}
|
|
2712
|
+
const info = {
|
|
2713
|
+
provider: CODEX_PROVIDER,
|
|
2714
|
+
sessionId: this.currentThreadId,
|
|
2715
|
+
model: this.config.model ?? null,
|
|
2716
|
+
thinkingOptionId: normalizeCodexThinkingOptionId(this.config.thinkingOptionId) ?? null,
|
|
2717
|
+
modeId: this.currentMode ?? null,
|
|
2718
|
+
extra: this.resolvedCollaborationMode
|
|
2719
|
+
? { collaborationMode: this.resolvedCollaborationMode.name }
|
|
2720
|
+
: undefined,
|
|
2721
|
+
};
|
|
2722
|
+
this.cachedRuntimeInfo = info;
|
|
2723
|
+
return { ...info };
|
|
2724
|
+
}
|
|
2725
|
+
async getAvailableModes() {
|
|
2726
|
+
if (this.autoReviewEnabled) {
|
|
2727
|
+
return CODEX_MODES;
|
|
2728
|
+
}
|
|
2729
|
+
return CODEX_MODES.filter((mode) => mode.id !== "auto-review");
|
|
2730
|
+
}
|
|
2731
|
+
async getCurrentMode() {
|
|
2732
|
+
return this.currentMode ?? null;
|
|
2733
|
+
}
|
|
2734
|
+
async setMode(modeId) {
|
|
2735
|
+
validateCodexMode(modeId);
|
|
2736
|
+
this.currentMode = modeId;
|
|
2737
|
+
this.cachedRuntimeInfo = null;
|
|
2738
|
+
if (this.activeForegroundTurnId) {
|
|
2739
|
+
return SETTING_APPLIES_NEXT_TURN_NOTICE;
|
|
2740
|
+
}
|
|
2741
|
+
}
|
|
2742
|
+
async setModel(modelId) {
|
|
2743
|
+
this.config.model = modelId ?? undefined;
|
|
2744
|
+
if (!codexModelSupportsFastMode(this.config.model)) {
|
|
2745
|
+
this.serviceTier = null;
|
|
2746
|
+
}
|
|
2747
|
+
this.refreshResolvedCollaborationMode();
|
|
2748
|
+
this.cachedRuntimeInfo = null;
|
|
2749
|
+
}
|
|
2750
|
+
async setThinkingOption(thinkingOptionId) {
|
|
2751
|
+
this.config.thinkingOptionId = normalizeCodexThinkingOptionId(thinkingOptionId);
|
|
2752
|
+
this.refreshResolvedCollaborationMode();
|
|
2753
|
+
this.cachedRuntimeInfo = null;
|
|
2754
|
+
if (this.activeForegroundTurnId) {
|
|
2755
|
+
return SETTING_APPLIES_NEXT_TURN_NOTICE;
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
async setFeature(featureId, value) {
|
|
2759
|
+
if (featureId === "fast_mode") {
|
|
2760
|
+
if (Boolean(value) && !codexModelSupportsFastMode(this.config.model)) {
|
|
2761
|
+
throw new Error(`Codex fast mode is not available for model '${this.config.model ?? "default"}'`);
|
|
2762
|
+
}
|
|
2763
|
+
this.applyFeatureValue("fast_mode", Boolean(value));
|
|
2764
|
+
return;
|
|
2765
|
+
}
|
|
2766
|
+
if (featureId === "plan_mode") {
|
|
2767
|
+
this.applyFeatureValue("plan_mode", Boolean(value));
|
|
2768
|
+
return;
|
|
2769
|
+
}
|
|
2770
|
+
throw new Error(`Unknown Codex feature: ${featureId}`);
|
|
2771
|
+
}
|
|
2772
|
+
getPendingPermissions() {
|
|
2773
|
+
return Array.from(this.pendingPermissions.values());
|
|
2774
|
+
}
|
|
2775
|
+
async respondToPermission(requestId, response) {
|
|
2776
|
+
const pending = this.pendingPermissionHandlers.get(requestId);
|
|
2777
|
+
if (!pending) {
|
|
2778
|
+
throw new Error(`No pending Codex app-server permission request with id '${requestId}'`);
|
|
2779
|
+
}
|
|
2780
|
+
const pendingRequest = this.pendingPermissions.get(requestId) ?? null;
|
|
2781
|
+
if (pending.kind === "plan") {
|
|
2782
|
+
return this.handlePlanPermissionResponse({ requestId, response, pending, pendingRequest });
|
|
2783
|
+
}
|
|
2784
|
+
this.pendingPermissionHandlers.delete(requestId);
|
|
2785
|
+
this.pendingPermissions.delete(requestId);
|
|
2786
|
+
this.resolvedPermissionRequests.add(requestId);
|
|
2787
|
+
if (response.behavior === "deny" && pendingRequest?.kind === "tool") {
|
|
2788
|
+
this.emitDeniedToolCallTimelineEvent({ requestId, response, pendingRequest });
|
|
2789
|
+
}
|
|
2790
|
+
this.emitEvent({
|
|
2791
|
+
type: "permission_resolved",
|
|
2792
|
+
provider: CODEX_PROVIDER,
|
|
2793
|
+
requestId,
|
|
2794
|
+
resolution: response,
|
|
2795
|
+
});
|
|
2796
|
+
if (pending.kind === "command") {
|
|
2797
|
+
pending.resolve({ decision: resolvePermissionDecision(response) });
|
|
2798
|
+
return;
|
|
2799
|
+
}
|
|
2800
|
+
if (pending.kind === "file") {
|
|
2801
|
+
pending.resolve({ decision: resolvePermissionDecision(response) });
|
|
2802
|
+
return;
|
|
2803
|
+
}
|
|
2804
|
+
const questions = pending.questions ?? [];
|
|
2805
|
+
const itemId = typeof pendingRequest?.metadata?.itemId === "string"
|
|
2806
|
+
? pendingRequest.metadata.itemId
|
|
2807
|
+
: requestId;
|
|
2808
|
+
if (response.behavior === "allow") {
|
|
2809
|
+
const mappedAnswers = mapCodexQuestionResponseByHeader({
|
|
2810
|
+
questions,
|
|
2811
|
+
response,
|
|
2812
|
+
});
|
|
2813
|
+
const answers = mappedAnswers ??
|
|
2814
|
+
Object.fromEntries(questions
|
|
2815
|
+
.map((question) => {
|
|
2816
|
+
const fallback = question.options[0]?.label?.trim();
|
|
2817
|
+
return fallback ? [question.id, { answers: [fallback] }] : null;
|
|
2818
|
+
})
|
|
2819
|
+
.filter((entry) => entry !== null));
|
|
2820
|
+
this.emitEvent({
|
|
2821
|
+
type: "timeline",
|
|
2822
|
+
provider: CODEX_PROVIDER,
|
|
2823
|
+
item: mapCodexQuestionRequestToToolCall({
|
|
2824
|
+
callId: itemId,
|
|
2825
|
+
questions,
|
|
2826
|
+
status: "completed",
|
|
2827
|
+
answers: Object.fromEntries(Object.entries(answers).map(([id, value]) => [id, value.answers])),
|
|
2828
|
+
}),
|
|
2829
|
+
});
|
|
2830
|
+
pending.resolve({ answers });
|
|
2831
|
+
return;
|
|
2832
|
+
}
|
|
2833
|
+
this.emitEvent({
|
|
2834
|
+
type: "timeline",
|
|
2835
|
+
provider: CODEX_PROVIDER,
|
|
2836
|
+
item: mapCodexQuestionRequestToToolCall({
|
|
2837
|
+
callId: itemId,
|
|
2838
|
+
questions,
|
|
2839
|
+
status: response.interrupt ? "canceled" : "failed",
|
|
2840
|
+
error: { message: response.message ?? "Question dismissed" },
|
|
2841
|
+
}),
|
|
2842
|
+
});
|
|
2843
|
+
pending.resolve({ answers: {} });
|
|
2844
|
+
}
|
|
2845
|
+
handlePlanPermissionResponse(params) {
|
|
2846
|
+
const { requestId, response, pending, pendingRequest } = params;
|
|
2847
|
+
let followUpPrompt;
|
|
2848
|
+
if (response.behavior === "allow") {
|
|
2849
|
+
followUpPrompt = this.preparePlanImplementation({
|
|
2850
|
+
planText: pending.planText ?? pendingRequest?.metadata?.planText,
|
|
2851
|
+
});
|
|
2852
|
+
}
|
|
2853
|
+
this.pendingPermissionHandlers.delete(requestId);
|
|
2854
|
+
this.pendingPermissions.delete(requestId);
|
|
2855
|
+
this.resolvedPermissionRequests.add(requestId);
|
|
2856
|
+
this.emitEvent({
|
|
2857
|
+
type: "permission_resolved",
|
|
2858
|
+
provider: CODEX_PROVIDER,
|
|
2859
|
+
requestId,
|
|
2860
|
+
resolution: response,
|
|
2861
|
+
});
|
|
2862
|
+
if (followUpPrompt) {
|
|
2863
|
+
return { followUpPrompt };
|
|
2864
|
+
}
|
|
2865
|
+
}
|
|
2866
|
+
emitDeniedToolCallTimelineEvent(params) {
|
|
2867
|
+
const { requestId, response, pendingRequest } = params;
|
|
2868
|
+
let fallbackName;
|
|
2869
|
+
if (pendingRequest.name === "CodexBash") {
|
|
2870
|
+
fallbackName = "shell";
|
|
2871
|
+
}
|
|
2872
|
+
else if (pendingRequest.name === "CodexFileChange") {
|
|
2873
|
+
fallbackName = "apply_patch";
|
|
2874
|
+
}
|
|
2875
|
+
else {
|
|
2876
|
+
fallbackName = pendingRequest.name;
|
|
2877
|
+
}
|
|
2878
|
+
this.emitEvent({
|
|
2879
|
+
type: "timeline",
|
|
2880
|
+
provider: CODEX_PROVIDER,
|
|
2881
|
+
item: {
|
|
2882
|
+
type: "tool_call",
|
|
2883
|
+
callId: requestId,
|
|
2884
|
+
name: fallbackName,
|
|
2885
|
+
status: "failed",
|
|
2886
|
+
error: { message: response.message ?? "Permission denied" },
|
|
2887
|
+
detail: pendingRequest.detail ?? {
|
|
2888
|
+
type: "unknown",
|
|
2889
|
+
input: pendingRequest.input ?? null,
|
|
2890
|
+
output: null,
|
|
2891
|
+
},
|
|
2892
|
+
metadata: {
|
|
2893
|
+
permissionRequestId: requestId,
|
|
2894
|
+
denied: true,
|
|
2895
|
+
},
|
|
2896
|
+
},
|
|
2897
|
+
});
|
|
2898
|
+
}
|
|
2899
|
+
describePersistence() {
|
|
2900
|
+
if (!this.currentThreadId)
|
|
2901
|
+
return null;
|
|
2902
|
+
const thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId) ?? null;
|
|
2903
|
+
return {
|
|
2904
|
+
provider: CODEX_PROVIDER,
|
|
2905
|
+
sessionId: this.currentThreadId,
|
|
2906
|
+
nativeHandle: this.currentThreadId,
|
|
2907
|
+
metadata: {
|
|
2908
|
+
provider: CODEX_PROVIDER,
|
|
2909
|
+
cwd: this.config.cwd,
|
|
2910
|
+
title: this.config.title ?? null,
|
|
2911
|
+
threadId: this.currentThreadId,
|
|
2912
|
+
modeId: this.currentMode,
|
|
2913
|
+
model: this.config.model ?? null,
|
|
2914
|
+
thinkingOptionId,
|
|
2915
|
+
extra: this.config.extra,
|
|
2916
|
+
systemPrompt: this.config.systemPrompt,
|
|
2917
|
+
mcpServers: this.config.mcpServers,
|
|
2918
|
+
},
|
|
2919
|
+
};
|
|
2920
|
+
}
|
|
2921
|
+
async revertConversation(input) {
|
|
2922
|
+
await this.connect();
|
|
2923
|
+
if (!this.client) {
|
|
2924
|
+
throw new Error("Codex client is not initialized");
|
|
2925
|
+
}
|
|
2926
|
+
if (this.currentThreadId) {
|
|
2927
|
+
await this.ensureThreadLoaded();
|
|
2928
|
+
}
|
|
2929
|
+
else {
|
|
2930
|
+
await this.ensureThread();
|
|
2931
|
+
}
|
|
2932
|
+
await revertCodexConversation({
|
|
2933
|
+
client: this.client,
|
|
2934
|
+
threadId: this.currentThreadId,
|
|
2935
|
+
messageId: input.messageId,
|
|
2936
|
+
cwd: this.config.cwd ?? null,
|
|
2937
|
+
model: this.config.model ?? null,
|
|
2938
|
+
serviceTier: this.serviceTier,
|
|
2939
|
+
userMessageTurns: this.codexUserMessageTurns(),
|
|
2940
|
+
setThreadId: async (threadId) => {
|
|
2941
|
+
this.currentThreadId = threadId;
|
|
2942
|
+
this.cachedRuntimeInfo = null;
|
|
2943
|
+
this.persistedHistory = [];
|
|
2944
|
+
this.historyPending = false;
|
|
2945
|
+
await this.loadPersistedHistory();
|
|
2946
|
+
},
|
|
2947
|
+
});
|
|
2948
|
+
}
|
|
2949
|
+
async interrupt() {
|
|
2950
|
+
if (!this.client || !this.currentThreadId || !this.currentTurnId)
|
|
2951
|
+
return;
|
|
2952
|
+
try {
|
|
2953
|
+
await this.client.request("turn/interrupt", {
|
|
2954
|
+
threadId: this.currentThreadId,
|
|
2955
|
+
turnId: this.currentTurnId,
|
|
2956
|
+
}, INTERRUPT_TIMEOUT_MS);
|
|
2957
|
+
}
|
|
2958
|
+
catch (error) {
|
|
2959
|
+
this.logger.warn({ error }, "Failed to interrupt Codex turn");
|
|
2960
|
+
}
|
|
2961
|
+
}
|
|
2962
|
+
async close() {
|
|
2963
|
+
for (const pending of this.pendingPermissionHandlers.values()) {
|
|
2964
|
+
pending.resolve({ decision: "cancel" });
|
|
2965
|
+
}
|
|
2966
|
+
this.pendingPermissionHandlers.clear();
|
|
2967
|
+
this.pendingPermissions.clear();
|
|
2968
|
+
this.resolvedPermissionRequests.clear();
|
|
2969
|
+
this.subscribers.clear();
|
|
2970
|
+
this.activeForegroundTurnId = null;
|
|
2971
|
+
if (this.client) {
|
|
2972
|
+
await this.client.dispose();
|
|
2973
|
+
}
|
|
2974
|
+
this.client = null;
|
|
2975
|
+
this.connected = false;
|
|
2976
|
+
this.currentThreadId = null;
|
|
2977
|
+
this.currentTurnId = null;
|
|
2978
|
+
}
|
|
2979
|
+
async listCommands() {
|
|
2980
|
+
const prompts = await listCodexCustomPrompts();
|
|
2981
|
+
if (!this.connected) {
|
|
2982
|
+
await this.connect();
|
|
2983
|
+
}
|
|
2984
|
+
else {
|
|
2985
|
+
await this.loadSkills();
|
|
2986
|
+
}
|
|
2987
|
+
const appServerSkills = this.cachedSkills.map((skill) => ({
|
|
2988
|
+
name: skill.name,
|
|
2989
|
+
description: skill.description,
|
|
2990
|
+
argumentHint: "",
|
|
2991
|
+
kind: "skill",
|
|
2992
|
+
}));
|
|
2993
|
+
const fallbackSkills = appServerSkills.length === 0
|
|
2994
|
+
? await listCodexSkills(this.config.cwd, this.deps.workspaceGitService)
|
|
2995
|
+
: [];
|
|
2996
|
+
const builtin = [
|
|
2997
|
+
{
|
|
2998
|
+
name: "compact",
|
|
2999
|
+
description: "Summarize conversation to prevent hitting the context limit",
|
|
3000
|
+
argumentHint: "",
|
|
3001
|
+
kind: "command",
|
|
3002
|
+
},
|
|
3003
|
+
];
|
|
3004
|
+
if (this.goalsEnabled) {
|
|
3005
|
+
builtin.push({
|
|
3006
|
+
name: "goal",
|
|
3007
|
+
description: "Set, pause, resume, or clear the agent's goal",
|
|
3008
|
+
argumentHint: "[<objective>|pause|resume|clear]",
|
|
3009
|
+
kind: "command",
|
|
3010
|
+
});
|
|
3011
|
+
}
|
|
3012
|
+
return [...builtin, ...appServerSkills, ...fallbackSkills, ...prompts].sort((a, b) => a.name.localeCompare(b.name));
|
|
3013
|
+
}
|
|
3014
|
+
tryHandleOutOfBand(prompt) {
|
|
3015
|
+
if (typeof prompt !== "string")
|
|
3016
|
+
return null;
|
|
3017
|
+
const parsed = this.parseSlashCommandInput(prompt);
|
|
3018
|
+
if (!parsed)
|
|
3019
|
+
return null;
|
|
3020
|
+
if (parsed.commandName === "compact") {
|
|
3021
|
+
return {
|
|
3022
|
+
run: async ({ emit }) => {
|
|
3023
|
+
const error = await this.executeCompactCommand();
|
|
3024
|
+
if (error) {
|
|
3025
|
+
emit({
|
|
3026
|
+
type: "timeline",
|
|
3027
|
+
provider: CODEX_PROVIDER,
|
|
3028
|
+
item: { type: "assistant_message", text: formatOutOfBandStatusMessage(error) },
|
|
3029
|
+
});
|
|
3030
|
+
}
|
|
3031
|
+
},
|
|
3032
|
+
};
|
|
3033
|
+
}
|
|
3034
|
+
if (!this.goalsEnabled || parsed.commandName !== "goal")
|
|
3035
|
+
return null;
|
|
3036
|
+
const subcommand = parseGoalSubcommand(parsed.args);
|
|
3037
|
+
return {
|
|
3038
|
+
run: async ({ emit }) => {
|
|
3039
|
+
const text = formatOutOfBandStatusMessage(await this.executeGoalSubcommand(subcommand));
|
|
3040
|
+
emit({
|
|
3041
|
+
type: "timeline",
|
|
3042
|
+
provider: CODEX_PROVIDER,
|
|
3043
|
+
item: { type: "assistant_message", text },
|
|
3044
|
+
});
|
|
3045
|
+
},
|
|
3046
|
+
};
|
|
3047
|
+
}
|
|
3048
|
+
async executeCompactCommand() {
|
|
3049
|
+
try {
|
|
3050
|
+
await this.connect();
|
|
3051
|
+
if (this.currentThreadId) {
|
|
3052
|
+
await this.ensureThreadLoaded();
|
|
3053
|
+
}
|
|
3054
|
+
else {
|
|
3055
|
+
await this.ensureThread();
|
|
3056
|
+
}
|
|
3057
|
+
if (!this.client || !this.currentThreadId) {
|
|
3058
|
+
throw new Error("Codex thread is not available");
|
|
3059
|
+
}
|
|
3060
|
+
this.pendingManualCompactionStarts += 1;
|
|
3061
|
+
try {
|
|
3062
|
+
await this.client.request("thread/compact/start", {
|
|
3063
|
+
threadId: this.currentThreadId,
|
|
3064
|
+
});
|
|
3065
|
+
}
|
|
3066
|
+
catch (error) {
|
|
3067
|
+
this.pendingManualCompactionStarts = Math.max(0, this.pendingManualCompactionStarts - 1);
|
|
3068
|
+
throw error;
|
|
3069
|
+
}
|
|
3070
|
+
return null;
|
|
3071
|
+
}
|
|
3072
|
+
catch (error) {
|
|
3073
|
+
const message = error instanceof Error ? error.message : "unknown error";
|
|
3074
|
+
return `Failed to compact context: ${message}`;
|
|
3075
|
+
}
|
|
3076
|
+
}
|
|
3077
|
+
async executeGoalSubcommand(subcommand) {
|
|
3078
|
+
if (subcommand.kind === "usage") {
|
|
3079
|
+
return "Usage: /goal <objective>|pause|resume|clear";
|
|
3080
|
+
}
|
|
3081
|
+
try {
|
|
3082
|
+
await this.connect();
|
|
3083
|
+
if (this.currentThreadId) {
|
|
3084
|
+
await this.ensureThreadLoaded();
|
|
3085
|
+
}
|
|
3086
|
+
else {
|
|
3087
|
+
await this.ensureThread();
|
|
3088
|
+
}
|
|
3089
|
+
if (!this.client || !this.currentThreadId) {
|
|
3090
|
+
throw new Error("Codex thread is not available");
|
|
3091
|
+
}
|
|
3092
|
+
switch (subcommand.kind) {
|
|
3093
|
+
case "set": {
|
|
3094
|
+
await this.client.request("thread/goal/set", {
|
|
3095
|
+
threadId: this.currentThreadId,
|
|
3096
|
+
objective: subcommand.objective,
|
|
3097
|
+
status: "active",
|
|
3098
|
+
});
|
|
3099
|
+
return `Goal set: ${subcommand.objective}`;
|
|
3100
|
+
}
|
|
3101
|
+
case "pause": {
|
|
3102
|
+
await this.client.request("thread/goal/set", {
|
|
3103
|
+
threadId: this.currentThreadId,
|
|
3104
|
+
status: "paused",
|
|
3105
|
+
});
|
|
3106
|
+
return "Goal paused.";
|
|
3107
|
+
}
|
|
3108
|
+
case "resume": {
|
|
3109
|
+
await this.client.request("thread/goal/set", {
|
|
3110
|
+
threadId: this.currentThreadId,
|
|
3111
|
+
status: "active",
|
|
3112
|
+
});
|
|
3113
|
+
return "Goal resumed.";
|
|
3114
|
+
}
|
|
3115
|
+
case "clear": {
|
|
3116
|
+
await this.client.request("thread/goal/clear", {
|
|
3117
|
+
threadId: this.currentThreadId,
|
|
3118
|
+
});
|
|
3119
|
+
return "Goal cleared.";
|
|
3120
|
+
}
|
|
3121
|
+
}
|
|
3122
|
+
}
|
|
3123
|
+
catch (error) {
|
|
3124
|
+
const message = error instanceof Error ? error.message : "unknown error";
|
|
3125
|
+
return `Failed to update goal: ${message}`;
|
|
3126
|
+
}
|
|
3127
|
+
}
|
|
3128
|
+
async resolveModelAndThinking() {
|
|
3129
|
+
if (!this.client) {
|
|
3130
|
+
throw new Error("Codex client is not initialized");
|
|
3131
|
+
}
|
|
3132
|
+
let configuredDefaults = {};
|
|
3133
|
+
let model = this.config.model;
|
|
3134
|
+
let thinkingOptionId = normalizeCodexThinkingOptionId(this.config.thinkingOptionId);
|
|
3135
|
+
if (!model || !thinkingOptionId) {
|
|
3136
|
+
configuredDefaults = await readCodexConfiguredDefaults(this.client, this.logger);
|
|
3137
|
+
}
|
|
3138
|
+
if (!model) {
|
|
3139
|
+
model = configuredDefaults.model;
|
|
3140
|
+
}
|
|
3141
|
+
if (!thinkingOptionId) {
|
|
3142
|
+
thinkingOptionId = configuredDefaults.thinkingOptionId;
|
|
3143
|
+
}
|
|
3144
|
+
if (!model || !thinkingOptionId) {
|
|
3145
|
+
const modelResponse = toObjectRecord(await this.client.request("model/list", {}));
|
|
3146
|
+
const modelData = Array.isArray(modelResponse?.data) ? modelResponse.data : [];
|
|
3147
|
+
const models = modelData
|
|
3148
|
+
.map((m) => {
|
|
3149
|
+
const record = toObjectRecord(m);
|
|
3150
|
+
return {
|
|
3151
|
+
id: typeof record?.id === "string" ? record.id : "",
|
|
3152
|
+
isDefault: !!record?.isDefault,
|
|
3153
|
+
defaultReasoningEffort: typeof record?.defaultReasoningEffort === "string"
|
|
3154
|
+
? record.defaultReasoningEffort
|
|
3155
|
+
: undefined,
|
|
3156
|
+
};
|
|
3157
|
+
})
|
|
3158
|
+
.filter((m) => m.id);
|
|
3159
|
+
const defaultModel = models.find((m) => m.isDefault) ?? models[0];
|
|
3160
|
+
if (!defaultModel) {
|
|
3161
|
+
throw new Error("No models available from Codex app-server");
|
|
3162
|
+
}
|
|
3163
|
+
const selectedModel = (model ? models.find((candidate) => candidate.id === model) : undefined) ?? defaultModel;
|
|
3164
|
+
if (!model) {
|
|
3165
|
+
model = selectedModel.id;
|
|
3166
|
+
}
|
|
3167
|
+
if (!thinkingOptionId) {
|
|
3168
|
+
thinkingOptionId = normalizeCodexThinkingOptionId(selectedModel.defaultReasoningEffort);
|
|
3169
|
+
}
|
|
3170
|
+
}
|
|
3171
|
+
if (!model) {
|
|
3172
|
+
throw new Error("Unable to resolve Codex model");
|
|
3173
|
+
}
|
|
3174
|
+
return { model, thinkingOptionId };
|
|
3175
|
+
}
|
|
3176
|
+
async ensureThread() {
|
|
3177
|
+
if (!this.client)
|
|
3178
|
+
return;
|
|
3179
|
+
if (this.currentThreadId)
|
|
3180
|
+
return;
|
|
3181
|
+
const { model, thinkingOptionId } = await this.resolveModelAndThinking();
|
|
3182
|
+
this.config.model = model;
|
|
3183
|
+
this.config.thinkingOptionId = thinkingOptionId;
|
|
3184
|
+
const preset = MODE_PRESETS[this.currentMode] ?? MODE_PRESETS[DEFAULT_CODEX_MODE_ID];
|
|
3185
|
+
const approvalPolicy = this.config.approvalPolicy ?? preset.approvalPolicy;
|
|
3186
|
+
const sandbox = this.config.sandboxMode ?? preset.sandbox;
|
|
3187
|
+
const innerConfig = this.buildCodexInnerConfig();
|
|
3188
|
+
const developerInstructions = composeSystemPromptParts(this.config.systemPrompt, this.config.daemonAppendSystemPrompt);
|
|
3189
|
+
const params = {
|
|
3190
|
+
model,
|
|
3191
|
+
cwd: this.config.cwd ?? null,
|
|
3192
|
+
approvalPolicy,
|
|
3193
|
+
sandbox,
|
|
3194
|
+
...(developerInstructions ? { developerInstructions } : {}),
|
|
3195
|
+
...(innerConfig ? { config: innerConfig } : {}),
|
|
3196
|
+
...(this.ephemeral ? { ephemeral: true } : {}),
|
|
3197
|
+
};
|
|
3198
|
+
applyApprovalsReviewerParam(params, preset);
|
|
3199
|
+
const rawResponse = await this.client.request("thread/start", params);
|
|
3200
|
+
const response = toObjectRecord(rawResponse);
|
|
3201
|
+
const threadRecord = toObjectRecord(response?.thread);
|
|
3202
|
+
const threadId = typeof threadRecord?.id === "string" ? threadRecord.id : undefined;
|
|
3203
|
+
if (!threadId) {
|
|
3204
|
+
throw new Error("Codex app-server did not return thread id");
|
|
3205
|
+
}
|
|
3206
|
+
const responseApprovalsReviewer = typeof response?.approvalsReviewer === "string" ? response.approvalsReviewer : undefined;
|
|
3207
|
+
if (shouldPromoteThreadResponseToAutoReview({
|
|
3208
|
+
approvalsReviewer: responseApprovalsReviewer,
|
|
3209
|
+
approvalPolicy,
|
|
3210
|
+
sandbox,
|
|
3211
|
+
})) {
|
|
3212
|
+
this.currentMode = "auto-review";
|
|
3213
|
+
this.cachedRuntimeInfo = null;
|
|
3214
|
+
}
|
|
3215
|
+
this.currentThreadId = threadId;
|
|
3216
|
+
}
|
|
3217
|
+
buildCodexInnerConfig() {
|
|
3218
|
+
const innerConfig = {};
|
|
3219
|
+
if (this.config.mcpServers) {
|
|
3220
|
+
const mcpServers = {};
|
|
3221
|
+
for (const [name, serverConfig] of Object.entries(this.config.mcpServers)) {
|
|
3222
|
+
mcpServers[name] = toCodexMcpConfig(serverConfig);
|
|
3223
|
+
}
|
|
3224
|
+
innerConfig.mcp_servers = mcpServers;
|
|
3225
|
+
}
|
|
3226
|
+
if (this.config.extra?.codex) {
|
|
3227
|
+
Object.assign(innerConfig, this.config.extra.codex);
|
|
3228
|
+
}
|
|
3229
|
+
if (this.deps.customCodexConfig) {
|
|
3230
|
+
Object.assign(innerConfig, this.deps.customCodexConfig);
|
|
3231
|
+
}
|
|
3232
|
+
return Object.keys(innerConfig).length > 0 ? innerConfig : null;
|
|
3233
|
+
}
|
|
3234
|
+
async buildUserInput(prompt) {
|
|
3235
|
+
if (typeof prompt === "string") {
|
|
3236
|
+
return [toCodexTextInput(prompt)];
|
|
3237
|
+
}
|
|
3238
|
+
return await codexAppServerTurnInputFromPrompt(prompt, this.logger);
|
|
3239
|
+
}
|
|
3240
|
+
emitEvent(event) {
|
|
3241
|
+
this.notifySubscribers(event);
|
|
3242
|
+
}
|
|
3243
|
+
notifySubscribers(event) {
|
|
3244
|
+
const turnId = this.activeForegroundTurnId;
|
|
3245
|
+
const tagged = turnId ? { ...event, turnId } : event;
|
|
3246
|
+
this.logger.trace({
|
|
3247
|
+
agentId: this.agentId,
|
|
3248
|
+
provider: CODEX_PROVIDER,
|
|
3249
|
+
sessionId: this.currentThreadId,
|
|
3250
|
+
turnId: getAgentStreamEventTurnId(tagged),
|
|
3251
|
+
event: tagged,
|
|
3252
|
+
}, "provider.codex.event_emit");
|
|
3253
|
+
for (const callback of this.subscribers) {
|
|
3254
|
+
try {
|
|
3255
|
+
callback(tagged);
|
|
3256
|
+
}
|
|
3257
|
+
catch (error) {
|
|
3258
|
+
this.logger.warn({ err: error }, "Subscriber callback threw");
|
|
3259
|
+
}
|
|
3260
|
+
}
|
|
3261
|
+
}
|
|
3262
|
+
createTurnId() {
|
|
3263
|
+
return `codex-turn-${this.nextTurnOrdinal++}`;
|
|
3264
|
+
}
|
|
3265
|
+
handleNotification(method, params) {
|
|
3266
|
+
const parsed = CodexNotificationSchema.parse({ method, params });
|
|
3267
|
+
this.traceParsedNotification(method, params, parsed);
|
|
3268
|
+
if (isCodexDeltaNotification(parsed)) {
|
|
3269
|
+
this.handleCodexDeltaNotification(parsed);
|
|
3270
|
+
return;
|
|
3271
|
+
}
|
|
3272
|
+
if (this.handleThreadStateNotification(parsed)) {
|
|
3273
|
+
return;
|
|
3274
|
+
}
|
|
3275
|
+
switch (parsed.kind) {
|
|
3276
|
+
case "thread_started":
|
|
3277
|
+
this.handleThreadStartedNotification(parsed);
|
|
3278
|
+
return;
|
|
3279
|
+
case "turn_started":
|
|
3280
|
+
this.handleTurnStartedNotification(parsed);
|
|
3281
|
+
return;
|
|
3282
|
+
case "turn_completed":
|
|
3283
|
+
this.handleTurnCompletedNotification(parsed);
|
|
3284
|
+
return;
|
|
3285
|
+
case "plan_updated":
|
|
3286
|
+
this.handlePlanUpdatedNotification(parsed);
|
|
3287
|
+
return;
|
|
3288
|
+
case "diff_updated":
|
|
3289
|
+
// NOTE: Codex app-server emits frequent `turn/diff/updated` notifications
|
|
3290
|
+
// containing a full accumulated unified diff for the *entire turn*.
|
|
3291
|
+
// This is not a concrete file-change tool call; it is progress telemetry.
|
|
3292
|
+
return;
|
|
3293
|
+
case "token_usage_updated":
|
|
3294
|
+
this.handleTokenUsageUpdatedNotification(parsed);
|
|
3295
|
+
return;
|
|
3296
|
+
case "exec_command_started":
|
|
3297
|
+
this.handleExecCommandStartedNotification(parsed);
|
|
3298
|
+
return;
|
|
3299
|
+
case "exec_command_completed":
|
|
3300
|
+
this.handleExecCommandCompletedNotification(parsed);
|
|
3301
|
+
return;
|
|
3302
|
+
case "terminal_interaction":
|
|
3303
|
+
this.handleTerminalInteractionNotification(parsed);
|
|
3304
|
+
return;
|
|
3305
|
+
case "patch_apply_started":
|
|
3306
|
+
this.handlePatchApplyStartedNotification(parsed);
|
|
3307
|
+
return;
|
|
3308
|
+
case "patch_apply_completed":
|
|
3309
|
+
this.handlePatchApplyCompletedNotification(parsed);
|
|
3310
|
+
return;
|
|
3311
|
+
case "item_completed":
|
|
3312
|
+
this.handleItemCompletedNotification(parsed);
|
|
3313
|
+
return;
|
|
3314
|
+
case "item_started":
|
|
3315
|
+
this.handleItemStartedNotification(parsed);
|
|
3316
|
+
return;
|
|
3317
|
+
case "invalid_payload":
|
|
3318
|
+
this.warnInvalidNotificationPayload(parsed.method, parsed.params);
|
|
3319
|
+
return;
|
|
3320
|
+
case "unknown_method":
|
|
3321
|
+
this.warnUnknownNotificationMethod(parsed.method, parsed.params);
|
|
3322
|
+
return;
|
|
3323
|
+
default:
|
|
3324
|
+
return;
|
|
3325
|
+
}
|
|
3326
|
+
}
|
|
3327
|
+
handleThreadStateNotification(parsed) {
|
|
3328
|
+
switch (parsed.kind) {
|
|
3329
|
+
case "context_compacted":
|
|
3330
|
+
this.handleContextCompactedNotification(parsed);
|
|
3331
|
+
return true;
|
|
3332
|
+
case "thread_rolled_back":
|
|
3333
|
+
this.handleThreadRolledBackNotification(parsed);
|
|
3334
|
+
return true;
|
|
3335
|
+
default:
|
|
3336
|
+
return false;
|
|
3337
|
+
}
|
|
3338
|
+
}
|
|
3339
|
+
traceParsedNotification(method, params, parsed) {
|
|
3340
|
+
this.logger.trace({
|
|
3341
|
+
agentId: this.agentId,
|
|
3342
|
+
provider: CODEX_PROVIDER,
|
|
3343
|
+
sessionId: this.currentThreadId,
|
|
3344
|
+
turnId: this.activeForegroundTurnId ?? undefined,
|
|
3345
|
+
method,
|
|
3346
|
+
params,
|
|
3347
|
+
parsed,
|
|
3348
|
+
}, "provider.codex.parsed_event");
|
|
3349
|
+
}
|
|
3350
|
+
getSubAgentCallIdForThread(threadId) {
|
|
3351
|
+
if (!threadId || threadId === this.currentThreadId) {
|
|
3352
|
+
return null;
|
|
3353
|
+
}
|
|
3354
|
+
return this.subAgentCallIdByChildThreadId.get(threadId) ?? null;
|
|
3355
|
+
}
|
|
3356
|
+
registerSubAgentToolCall(timelineItem, rawItem) {
|
|
3357
|
+
if (timelineItem.detail.type !== "sub_agent") {
|
|
3358
|
+
return;
|
|
3359
|
+
}
|
|
3360
|
+
const existing = this.subAgentCallsByCallId.get(timelineItem.callId);
|
|
3361
|
+
const state = existing ??
|
|
3362
|
+
{
|
|
3363
|
+
callId: timelineItem.callId,
|
|
3364
|
+
toolCall: timelineItem,
|
|
3365
|
+
childItemOrder: [],
|
|
3366
|
+
childItems: new Map(),
|
|
3367
|
+
};
|
|
3368
|
+
state.toolCall = {
|
|
3369
|
+
...timelineItem,
|
|
3370
|
+
detail: {
|
|
3371
|
+
...timelineItem.detail,
|
|
3372
|
+
log: timelineItem.detail.log ||
|
|
3373
|
+
(state.toolCall.detail.type === "sub_agent" ? state.toolCall.detail.log : ""),
|
|
3374
|
+
},
|
|
3375
|
+
};
|
|
3376
|
+
this.subAgentCallsByCallId.set(timelineItem.callId, state);
|
|
3377
|
+
const receiverThreadIds = Array.isArray(rawItem.receiverThreadIds)
|
|
3378
|
+
? rawItem.receiverThreadIds.filter((value) => typeof value === "string")
|
|
3379
|
+
: [];
|
|
3380
|
+
for (const receiverThreadId of receiverThreadIds) {
|
|
3381
|
+
this.subAgentCallIdByChildThreadId.set(receiverThreadId, timelineItem.callId);
|
|
3382
|
+
}
|
|
3383
|
+
}
|
|
3384
|
+
upsertSubAgentChildItem(callId, itemId, item) {
|
|
3385
|
+
const state = this.subAgentCallsByCallId.get(callId);
|
|
3386
|
+
if (!state) {
|
|
3387
|
+
return;
|
|
3388
|
+
}
|
|
3389
|
+
if (!state.childItems.has(itemId)) {
|
|
3390
|
+
state.childItemOrder.push(itemId);
|
|
3391
|
+
}
|
|
3392
|
+
state.childItems.set(itemId, item);
|
|
3393
|
+
}
|
|
3394
|
+
getSubAgentChildTimeline(state) {
|
|
3395
|
+
return state.childItemOrder
|
|
3396
|
+
.map((itemId) => state.childItems.get(itemId))
|
|
3397
|
+
.filter((item) => Boolean(item));
|
|
3398
|
+
}
|
|
3399
|
+
emitSubAgentActivityUpdate(callId, status) {
|
|
3400
|
+
const state = this.subAgentCallsByCallId.get(callId);
|
|
3401
|
+
if (!state || state.toolCall.detail.type !== "sub_agent") {
|
|
3402
|
+
return;
|
|
3403
|
+
}
|
|
3404
|
+
const childTimeline = this.getSubAgentChildTimeline(state);
|
|
3405
|
+
const log = childTimeline.length > 0
|
|
3406
|
+
? curateAgentActivity(childTimeline, { labelAssistantMessages: true })
|
|
3407
|
+
: "";
|
|
3408
|
+
const resolvedStatus = status ?? state.toolCall.status;
|
|
3409
|
+
const baseToolCall = {
|
|
3410
|
+
...state.toolCall,
|
|
3411
|
+
detail: {
|
|
3412
|
+
...state.toolCall.detail,
|
|
3413
|
+
log,
|
|
3414
|
+
},
|
|
3415
|
+
};
|
|
3416
|
+
const nextToolCall = resolvedStatus === "failed"
|
|
3417
|
+
? {
|
|
3418
|
+
...baseToolCall,
|
|
3419
|
+
status: "failed",
|
|
3420
|
+
error: state.toolCall.error ?? { message: "Sub-agent failed" },
|
|
3421
|
+
}
|
|
3422
|
+
: {
|
|
3423
|
+
...baseToolCall,
|
|
3424
|
+
status: resolvedStatus,
|
|
3425
|
+
error: null,
|
|
3426
|
+
};
|
|
3427
|
+
state.toolCall = nextToolCall;
|
|
3428
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: nextToolCall });
|
|
3429
|
+
}
|
|
3430
|
+
handleSubAgentChildItemCompleted(callId, itemId, timelineItem) {
|
|
3431
|
+
this.applyBufferedDeltaTextToTimelineItem(timelineItem, itemId);
|
|
3432
|
+
if (itemId) {
|
|
3433
|
+
this.upsertSubAgentChildItem(callId, itemId, timelineItem);
|
|
3434
|
+
this.pendingAgentMessages.delete(itemId);
|
|
3435
|
+
this.pendingReasoning.delete(itemId);
|
|
3436
|
+
this.pendingCommandOutputDeltas.delete(itemId);
|
|
3437
|
+
this.pendingFileChangeOutputDeltas.delete(itemId);
|
|
3438
|
+
}
|
|
3439
|
+
this.emitSubAgentActivityUpdate(callId, "running");
|
|
3440
|
+
}
|
|
3441
|
+
shouldSkipCompletedThreadItem(timelineItem, normalizedItemType, itemId) {
|
|
3442
|
+
// For commandExecution items, codex/event/exec_command_* is authoritative.
|
|
3443
|
+
if (timelineItem.type === "tool_call" && normalizedItemType === "commandExecution") {
|
|
3444
|
+
const callId = timelineItem.callId || itemId;
|
|
3445
|
+
return Boolean(callId && this.emittedExecCommandCompletedCallIds.has(callId));
|
|
3446
|
+
}
|
|
3447
|
+
return Boolean(itemId && this.emittedItemCompletedIds.has(itemId));
|
|
3448
|
+
}
|
|
3449
|
+
handleCodexDeltaNotification(parsed) {
|
|
3450
|
+
if (parsed.kind === "agent_message_delta") {
|
|
3451
|
+
const prev = this.pendingAgentMessages.get(parsed.itemId) ?? "";
|
|
3452
|
+
const text = prev + parsed.delta;
|
|
3453
|
+
this.pendingAgentMessages.set(parsed.itemId, text);
|
|
3454
|
+
const subAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId);
|
|
3455
|
+
if (subAgentCallId) {
|
|
3456
|
+
this.upsertSubAgentChildItem(subAgentCallId, parsed.itemId, {
|
|
3457
|
+
type: "assistant_message",
|
|
3458
|
+
messageId: parsed.itemId,
|
|
3459
|
+
text,
|
|
3460
|
+
});
|
|
3461
|
+
this.emitSubAgentActivityUpdate(subAgentCallId, "running");
|
|
3462
|
+
return;
|
|
3463
|
+
}
|
|
3464
|
+
const isFirstDeltaForItem = prev.length === 0;
|
|
3465
|
+
this.emitEvent({
|
|
3466
|
+
type: "timeline",
|
|
3467
|
+
provider: CODEX_PROVIDER,
|
|
3468
|
+
item: {
|
|
3469
|
+
type: "assistant_message",
|
|
3470
|
+
messageId: parsed.itemId,
|
|
3471
|
+
text: isFirstDeltaForItem && this.pendingAssistantMessageBoundary
|
|
3472
|
+
? `${ASSISTANT_MESSAGE_BOUNDARY_MARKDOWN}${parsed.delta}`
|
|
3473
|
+
: parsed.delta,
|
|
3474
|
+
},
|
|
3475
|
+
});
|
|
3476
|
+
if (isFirstDeltaForItem) {
|
|
3477
|
+
this.pendingAssistantMessageBoundary = false;
|
|
3478
|
+
}
|
|
3479
|
+
return;
|
|
3480
|
+
}
|
|
3481
|
+
if (parsed.kind === "reasoning_delta") {
|
|
3482
|
+
const prev = this.pendingReasoning.get(parsed.itemId) ?? [];
|
|
3483
|
+
prev.push(parsed.delta);
|
|
3484
|
+
this.pendingReasoning.set(parsed.itemId, prev);
|
|
3485
|
+
const subAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId);
|
|
3486
|
+
if (subAgentCallId) {
|
|
3487
|
+
this.upsertSubAgentChildItem(subAgentCallId, parsed.itemId, {
|
|
3488
|
+
type: "reasoning",
|
|
3489
|
+
text: prev.join(""),
|
|
3490
|
+
});
|
|
3491
|
+
this.emitSubAgentActivityUpdate(subAgentCallId, "running");
|
|
3492
|
+
return;
|
|
3493
|
+
}
|
|
3494
|
+
this.emitEvent({
|
|
3495
|
+
type: "timeline",
|
|
3496
|
+
provider: CODEX_PROVIDER,
|
|
3497
|
+
item: { type: "reasoning", text: parsed.delta },
|
|
3498
|
+
});
|
|
3499
|
+
return;
|
|
3500
|
+
}
|
|
3501
|
+
if (parsed.kind === "exec_command_output_delta") {
|
|
3502
|
+
this.appendOutputDeltaChunk(this.pendingCommandOutputDeltas, parsed.callId, parsed.chunk, {
|
|
3503
|
+
decodeBase64: true,
|
|
3504
|
+
});
|
|
3505
|
+
return;
|
|
3506
|
+
}
|
|
3507
|
+
this.appendOutputDeltaChunk(this.pendingFileChangeOutputDeltas, parsed.itemId, parsed.delta);
|
|
3508
|
+
}
|
|
3509
|
+
handleThreadStartedNotification(parsed) {
|
|
3510
|
+
this.currentThreadId = parsed.threadId;
|
|
3511
|
+
this.emitEvent({
|
|
3512
|
+
type: "thread_started",
|
|
3513
|
+
provider: CODEX_PROVIDER,
|
|
3514
|
+
sessionId: parsed.threadId,
|
|
3515
|
+
});
|
|
3516
|
+
}
|
|
3517
|
+
handleTurnStartedNotification(parsed) {
|
|
3518
|
+
const subAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId);
|
|
3519
|
+
if (subAgentCallId) {
|
|
3520
|
+
this.emitSubAgentActivityUpdate(subAgentCallId, "running");
|
|
3521
|
+
return;
|
|
3522
|
+
}
|
|
3523
|
+
this.currentTurnId = parsed.turnId;
|
|
3524
|
+
this.resetTurnTrackingState();
|
|
3525
|
+
this.emitEvent({ type: "turn_started", provider: CODEX_PROVIDER });
|
|
3526
|
+
}
|
|
3527
|
+
handleTurnCompletedNotification(parsed) {
|
|
3528
|
+
const subAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId);
|
|
3529
|
+
if (subAgentCallId) {
|
|
3530
|
+
let status = "completed";
|
|
3531
|
+
if (parsed.status === "failed") {
|
|
3532
|
+
status = "failed";
|
|
3533
|
+
}
|
|
3534
|
+
else if (parsed.status === "interrupted") {
|
|
3535
|
+
status = "canceled";
|
|
3536
|
+
}
|
|
3537
|
+
this.emitSubAgentActivityUpdate(subAgentCallId, status);
|
|
3538
|
+
return;
|
|
3539
|
+
}
|
|
3540
|
+
if (parsed.status === "failed") {
|
|
3541
|
+
this.emitEvent({
|
|
3542
|
+
type: "turn_failed",
|
|
3543
|
+
provider: CODEX_PROVIDER,
|
|
3544
|
+
error: parsed.errorMessage ?? "Codex turn failed",
|
|
3545
|
+
});
|
|
3546
|
+
}
|
|
3547
|
+
else if (parsed.status === "interrupted") {
|
|
3548
|
+
this.emitEvent({ type: "turn_canceled", provider: CODEX_PROVIDER, reason: "interrupted" });
|
|
3549
|
+
}
|
|
3550
|
+
else {
|
|
3551
|
+
if (this.planModeEnabled && this.latestPlanResult?.text) {
|
|
3552
|
+
this.emitSyntheticPlanApprovalRequest(this.latestPlanResult.text);
|
|
3553
|
+
}
|
|
3554
|
+
this.emitEvent({
|
|
3555
|
+
type: "turn_completed",
|
|
3556
|
+
provider: CODEX_PROVIDER,
|
|
3557
|
+
usage: this.latestUsage,
|
|
3558
|
+
});
|
|
3559
|
+
}
|
|
3560
|
+
this.activeForegroundTurnId = null;
|
|
3561
|
+
this.resetTurnTrackingState();
|
|
3562
|
+
}
|
|
3563
|
+
resetTurnTrackingState() {
|
|
3564
|
+
this.latestPlanResult = null;
|
|
3565
|
+
this.emittedItemStartedIds.clear();
|
|
3566
|
+
this.emittedItemCompletedIds.clear();
|
|
3567
|
+
this.emittedExecCommandStartedCallIds.clear();
|
|
3568
|
+
this.emittedExecCommandCompletedCallIds.clear();
|
|
3569
|
+
this.pendingAgentMessages.clear();
|
|
3570
|
+
this.pendingReasoning.clear();
|
|
3571
|
+
this.pendingCommandOutputDeltas.clear();
|
|
3572
|
+
this.pendingFileChangeOutputDeltas.clear();
|
|
3573
|
+
this.pendingAssistantMessageBoundary = false;
|
|
3574
|
+
this.warnedIncompleteEditToolCallIds.clear();
|
|
3575
|
+
this.unpairedCompactionNotificationCompletions = 0;
|
|
3576
|
+
this.unpairedCompactionItemCompletions = 0;
|
|
3577
|
+
}
|
|
3578
|
+
handlePlanUpdatedNotification(parsed) {
|
|
3579
|
+
const timelineItem = mapCodexPlanToToolCall({
|
|
3580
|
+
callId: `plan:${this.currentTurnId ?? this.currentThreadId ?? "current"}`,
|
|
3581
|
+
text: planStepsToMarkdown(parsed.plan.map((entry) => ({
|
|
3582
|
+
step: entry.step ?? "",
|
|
3583
|
+
status: entry.status ?? "pending",
|
|
3584
|
+
}))),
|
|
3585
|
+
});
|
|
3586
|
+
if (timelineItem) {
|
|
3587
|
+
this.rememberPlanResult(timelineItem);
|
|
3588
|
+
// In plan mode, the same plan is rendered through the synthetic approval
|
|
3589
|
+
// permission. Keep the remembered text for that card, but do not also
|
|
3590
|
+
// emit a static timeline plan panel.
|
|
3591
|
+
if (this.planModeEnabled) {
|
|
3592
|
+
return;
|
|
3593
|
+
}
|
|
3594
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem });
|
|
3595
|
+
}
|
|
3596
|
+
}
|
|
3597
|
+
handleTokenUsageUpdatedNotification(parsed) {
|
|
3598
|
+
this.latestUsage = toAgentUsage(parsed.tokenUsage);
|
|
3599
|
+
if (this.latestUsage) {
|
|
3600
|
+
this.notifySubscribers({
|
|
3601
|
+
type: "usage_updated",
|
|
3602
|
+
provider: CODEX_PROVIDER,
|
|
3603
|
+
usage: this.latestUsage,
|
|
3604
|
+
});
|
|
3605
|
+
}
|
|
3606
|
+
}
|
|
3607
|
+
resolveContextCompactionTrigger(itemId) {
|
|
3608
|
+
if (itemId) {
|
|
3609
|
+
const known = this.compactionTriggerByItemId.get(itemId);
|
|
3610
|
+
if (known) {
|
|
3611
|
+
return known;
|
|
3612
|
+
}
|
|
3613
|
+
}
|
|
3614
|
+
if (this.pendingManualCompactionStarts > 0) {
|
|
3615
|
+
this.pendingManualCompactionStarts -= 1;
|
|
3616
|
+
return "manual";
|
|
3617
|
+
}
|
|
3618
|
+
return undefined;
|
|
3619
|
+
}
|
|
3620
|
+
createContextCompactionTimelineItem(status, itemId) {
|
|
3621
|
+
const trigger = this.resolveContextCompactionTrigger(itemId);
|
|
3622
|
+
if (itemId && trigger) {
|
|
3623
|
+
if (status === "loading") {
|
|
3624
|
+
this.compactionTriggerByItemId.set(itemId, trigger);
|
|
3625
|
+
}
|
|
3626
|
+
else {
|
|
3627
|
+
this.compactionTriggerByItemId.delete(itemId);
|
|
3628
|
+
}
|
|
3629
|
+
}
|
|
3630
|
+
return {
|
|
3631
|
+
type: "compaction",
|
|
3632
|
+
status,
|
|
3633
|
+
...(trigger ? { trigger } : {}),
|
|
3634
|
+
};
|
|
3635
|
+
}
|
|
3636
|
+
isContextCompactionItem(item) {
|
|
3637
|
+
return (normalizeCodexThreadItemType(typeof item.type === "string" ? item.type : undefined) ===
|
|
3638
|
+
CODEX_CONTEXT_COMPACTION_TYPE);
|
|
3639
|
+
}
|
|
3640
|
+
isUserMessageItem(item) {
|
|
3641
|
+
return (normalizeCodexThreadItemType(typeof item.type === "string" ? item.type : undefined) ===
|
|
3642
|
+
"userMessage");
|
|
3643
|
+
}
|
|
3644
|
+
handleThreadRolledBackNotification(parsed) {
|
|
3645
|
+
this.truncateCodexUserMessageTurns(parsed.numTurns);
|
|
3646
|
+
}
|
|
3647
|
+
handleContextCompactedNotification(parsed) {
|
|
3648
|
+
if (parsed.threadId !== this.currentThreadId) {
|
|
3649
|
+
return;
|
|
3650
|
+
}
|
|
3651
|
+
if (this.unpairedCompactionItemCompletions > 0) {
|
|
3652
|
+
this.unpairedCompactionItemCompletions -= 1;
|
|
3653
|
+
return;
|
|
3654
|
+
}
|
|
3655
|
+
this.unpairedCompactionNotificationCompletions += 1;
|
|
3656
|
+
this.emitEvent({
|
|
3657
|
+
type: "timeline",
|
|
3658
|
+
provider: CODEX_PROVIDER,
|
|
3659
|
+
item: this.createContextCompactionTimelineItem("completed"),
|
|
3660
|
+
...(parsed.turnId ? { turnId: parsed.turnId } : {}),
|
|
3661
|
+
});
|
|
3662
|
+
}
|
|
3663
|
+
handleExecCommandStartedNotification(parsed) {
|
|
3664
|
+
if (parsed.callId) {
|
|
3665
|
+
this.emittedExecCommandStartedCallIds.add(parsed.callId);
|
|
3666
|
+
this.pendingCommandOutputDeltas.delete(parsed.callId);
|
|
3667
|
+
}
|
|
3668
|
+
const timelineItem = mapCodexExecNotificationToToolCall({
|
|
3669
|
+
callId: parsed.callId,
|
|
3670
|
+
command: parsed.command,
|
|
3671
|
+
cwd: parsed.cwd ?? this.config.cwd ?? null,
|
|
3672
|
+
running: true,
|
|
3673
|
+
});
|
|
3674
|
+
if (timelineItem) {
|
|
3675
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem });
|
|
3676
|
+
}
|
|
3677
|
+
}
|
|
3678
|
+
handleExecCommandCompletedNotification(parsed) {
|
|
3679
|
+
const bufferedOutput = this.consumeOutputDelta(this.pendingCommandOutputDeltas, parsed.callId);
|
|
3680
|
+
const resolvedOutput = parsed.output ?? bufferedOutput;
|
|
3681
|
+
this.rememberTerminalProcessForCommand(parsed.command, resolvedOutput);
|
|
3682
|
+
const timelineItem = mapCodexExecNotificationToToolCall({
|
|
3683
|
+
callId: parsed.callId,
|
|
3684
|
+
command: parsed.command,
|
|
3685
|
+
cwd: parsed.cwd ?? this.config.cwd ?? null,
|
|
3686
|
+
output: resolvedOutput,
|
|
3687
|
+
exitCode: parsed.exitCode,
|
|
3688
|
+
success: parsed.success,
|
|
3689
|
+
stderr: parsed.stderr,
|
|
3690
|
+
running: false,
|
|
3691
|
+
});
|
|
3692
|
+
if (timelineItem) {
|
|
3693
|
+
this.emittedExecCommandCompletedCallIds.add(timelineItem.callId);
|
|
3694
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem });
|
|
3695
|
+
}
|
|
3696
|
+
}
|
|
3697
|
+
handleTerminalInteractionNotification(parsed) {
|
|
3698
|
+
const interactionKey = [parsed.processId ?? "", parsed.stdin ?? ""].join("\u0000");
|
|
3699
|
+
if (!this.shouldEmitTerminalInteractionKey(interactionKey)) {
|
|
3700
|
+
return;
|
|
3701
|
+
}
|
|
3702
|
+
const command = (parsed.processId ? this.terminalCommandByProcessId.get(parsed.processId) : undefined) ??
|
|
3703
|
+
null;
|
|
3704
|
+
if (!command && parsed.processId) {
|
|
3705
|
+
this.pendingUnlabeledTerminalInteractions.add(parsed.processId);
|
|
3706
|
+
}
|
|
3707
|
+
const timelineItem = mapCodexTerminalInteractionToToolCall({
|
|
3708
|
+
processId: parsed.processId,
|
|
3709
|
+
fallbackCallId: parsed.callId,
|
|
3710
|
+
command,
|
|
3711
|
+
});
|
|
3712
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem });
|
|
3713
|
+
}
|
|
3714
|
+
handlePatchApplyStartedNotification(parsed) {
|
|
3715
|
+
if (parsed.callId) {
|
|
3716
|
+
this.pendingFileChangeOutputDeltas.delete(parsed.callId);
|
|
3717
|
+
}
|
|
3718
|
+
const timelineItem = mapCodexPatchNotificationToToolCall({
|
|
3719
|
+
callId: parsed.callId,
|
|
3720
|
+
changes: parsed.changes,
|
|
3721
|
+
cwd: this.config.cwd ?? null,
|
|
3722
|
+
running: true,
|
|
3723
|
+
});
|
|
3724
|
+
if (timelineItem) {
|
|
3725
|
+
this.warnOnIncompleteEditToolCall(timelineItem, "patch_apply_started", {
|
|
3726
|
+
callId: parsed.callId,
|
|
3727
|
+
changes: parsed.changes,
|
|
3728
|
+
});
|
|
3729
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem });
|
|
3730
|
+
}
|
|
3731
|
+
}
|
|
3732
|
+
handlePatchApplyCompletedNotification(parsed) {
|
|
3733
|
+
const bufferedOutput = this.consumeOutputDelta(this.pendingFileChangeOutputDeltas, parsed.callId);
|
|
3734
|
+
const timelineItem = mapCodexPatchNotificationToToolCall({
|
|
3735
|
+
callId: parsed.callId,
|
|
3736
|
+
changes: parsed.changes,
|
|
3737
|
+
cwd: this.config.cwd ?? null,
|
|
3738
|
+
stdout: parsed.stdout ?? bufferedOutput,
|
|
3739
|
+
stderr: parsed.stderr,
|
|
3740
|
+
success: parsed.success,
|
|
3741
|
+
running: false,
|
|
3742
|
+
});
|
|
3743
|
+
if (timelineItem) {
|
|
3744
|
+
this.warnOnIncompleteEditToolCall(timelineItem, "patch_apply_completed", {
|
|
3745
|
+
callId: parsed.callId,
|
|
3746
|
+
changes: parsed.changes,
|
|
3747
|
+
stdout: parsed.stdout,
|
|
3748
|
+
});
|
|
3749
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem });
|
|
3750
|
+
}
|
|
3751
|
+
}
|
|
3752
|
+
handleItemCompletedNotification(parsed) {
|
|
3753
|
+
// Codex emits mirrored lifecycle notifications via both `codex/event/item_*`
|
|
3754
|
+
// and canonical `item/*`. We render only the canonical channel to avoid
|
|
3755
|
+
// duplicated assistant/reasoning rows.
|
|
3756
|
+
if (parsed.source === "codex_event") {
|
|
3757
|
+
return;
|
|
3758
|
+
}
|
|
3759
|
+
if (this.isUserMessageItem(parsed.item)) {
|
|
3760
|
+
this.handleUserMessageItem(parsed);
|
|
3761
|
+
return;
|
|
3762
|
+
}
|
|
3763
|
+
if (this.isContextCompactionItem(parsed.item)) {
|
|
3764
|
+
if (this.unpairedCompactionNotificationCompletions > 0) {
|
|
3765
|
+
this.unpairedCompactionNotificationCompletions -= 1;
|
|
3766
|
+
return;
|
|
3767
|
+
}
|
|
3768
|
+
this.emitEvent({
|
|
3769
|
+
type: "timeline",
|
|
3770
|
+
provider: CODEX_PROVIDER,
|
|
3771
|
+
item: this.createContextCompactionTimelineItem("completed", parsed.item.id),
|
|
3772
|
+
});
|
|
3773
|
+
this.unpairedCompactionItemCompletions += 1;
|
|
3774
|
+
return;
|
|
3775
|
+
}
|
|
3776
|
+
const timelineItem = threadItemToTimeline(parsed.item, {
|
|
3777
|
+
includeUserMessage: false,
|
|
3778
|
+
cwd: this.config.cwd ?? null,
|
|
3779
|
+
});
|
|
3780
|
+
if (!timelineItem) {
|
|
3781
|
+
return;
|
|
3782
|
+
}
|
|
3783
|
+
const childSubAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId);
|
|
3784
|
+
if (childSubAgentCallId) {
|
|
3785
|
+
this.handleSubAgentChildItemCompleted(childSubAgentCallId, parsed.item.id, timelineItem);
|
|
3786
|
+
return;
|
|
3787
|
+
}
|
|
3788
|
+
const normalizedItemType = normalizeCodexThreadItemType(typeof parsed.item.type === "string" ? parsed.item.type : undefined);
|
|
3789
|
+
const itemId = parsed.item.id;
|
|
3790
|
+
if (this.shouldSkipCompletedThreadItem(timelineItem, normalizedItemType, itemId)) {
|
|
3791
|
+
return;
|
|
3792
|
+
}
|
|
3793
|
+
if (this.consumeStreamedTextCompletion(timelineItem, itemId)) {
|
|
3794
|
+
if (timelineItem.type === "assistant_message") {
|
|
3795
|
+
this.pendingAssistantMessageBoundary = true;
|
|
3796
|
+
}
|
|
3797
|
+
if (itemId) {
|
|
3798
|
+
this.emittedItemCompletedIds.add(itemId);
|
|
3799
|
+
this.emittedItemStartedIds.delete(itemId);
|
|
3800
|
+
}
|
|
3801
|
+
return;
|
|
3802
|
+
}
|
|
3803
|
+
this.applyBufferedDeltaTextToTimelineItem(timelineItem, itemId);
|
|
3804
|
+
if (timelineItem.type === "tool_call") {
|
|
3805
|
+
this.registerSubAgentToolCall(timelineItem, parsed.item);
|
|
3806
|
+
if (timelineItem.detail.type === "plan") {
|
|
3807
|
+
this.rememberPlanResult(timelineItem);
|
|
3808
|
+
// Codex can surface plans both as turn/plan updates and as completed
|
|
3809
|
+
// thread items. In plan mode, approval owns the visible plan card.
|
|
3810
|
+
if (this.planModeEnabled) {
|
|
3811
|
+
return;
|
|
3812
|
+
}
|
|
3813
|
+
}
|
|
3814
|
+
this.warnOnIncompleteEditToolCall(timelineItem, "item_completed", parsed.item);
|
|
3815
|
+
}
|
|
3816
|
+
const imageItems = mcpToolResultImagesToTimeline(parsed.item);
|
|
3817
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem });
|
|
3818
|
+
if (timelineItem.type === "assistant_message") {
|
|
3819
|
+
this.pendingAssistantMessageBoundary = true;
|
|
3820
|
+
}
|
|
3821
|
+
for (const imageItem of imageItems) {
|
|
3822
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: imageItem });
|
|
3823
|
+
this.pendingAssistantMessageBoundary = true;
|
|
3824
|
+
}
|
|
3825
|
+
if (itemId) {
|
|
3826
|
+
this.emittedItemCompletedIds.add(itemId);
|
|
3827
|
+
this.emittedItemStartedIds.delete(itemId);
|
|
3828
|
+
this.pendingCommandOutputDeltas.delete(itemId);
|
|
3829
|
+
this.pendingFileChangeOutputDeltas.delete(itemId);
|
|
3830
|
+
}
|
|
3831
|
+
}
|
|
3832
|
+
consumeStreamedTextCompletion(timelineItem, itemId) {
|
|
3833
|
+
if (!itemId) {
|
|
3834
|
+
return false;
|
|
3835
|
+
}
|
|
3836
|
+
if (timelineItem.type === "assistant_message" && this.pendingAgentMessages.has(itemId)) {
|
|
3837
|
+
const streamedText = this.pendingAgentMessages.get(itemId) ?? "";
|
|
3838
|
+
this.pendingAgentMessages.delete(itemId);
|
|
3839
|
+
this.emitMissingFinalTextSuffix(timelineItem, streamedText);
|
|
3840
|
+
return true;
|
|
3841
|
+
}
|
|
3842
|
+
if (timelineItem.type === "reasoning" && this.pendingReasoning.has(itemId)) {
|
|
3843
|
+
const streamedText = this.pendingReasoning.get(itemId)?.join("") ?? "";
|
|
3844
|
+
this.pendingReasoning.delete(itemId);
|
|
3845
|
+
this.emitMissingFinalTextSuffix(timelineItem, streamedText);
|
|
3846
|
+
return true;
|
|
3847
|
+
}
|
|
3848
|
+
return false;
|
|
3849
|
+
}
|
|
3850
|
+
emitMissingFinalTextSuffix(timelineItem, streamedText) {
|
|
3851
|
+
if (!timelineItem.text.startsWith(streamedText)) {
|
|
3852
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem });
|
|
3853
|
+
return;
|
|
3854
|
+
}
|
|
3855
|
+
const suffix = timelineItem.text.slice(streamedText.length);
|
|
3856
|
+
if (!suffix) {
|
|
3857
|
+
return;
|
|
3858
|
+
}
|
|
3859
|
+
this.emitEvent({
|
|
3860
|
+
type: "timeline",
|
|
3861
|
+
provider: CODEX_PROVIDER,
|
|
3862
|
+
item: timelineItem.type === "assistant_message"
|
|
3863
|
+
? {
|
|
3864
|
+
type: timelineItem.type,
|
|
3865
|
+
text: suffix,
|
|
3866
|
+
...(timelineItem.messageId ? { messageId: timelineItem.messageId } : {}),
|
|
3867
|
+
}
|
|
3868
|
+
: { type: timelineItem.type, text: suffix },
|
|
3869
|
+
});
|
|
3870
|
+
}
|
|
3871
|
+
applyBufferedDeltaTextToTimelineItem(timelineItem, itemId) {
|
|
3872
|
+
if (!itemId) {
|
|
3873
|
+
return;
|
|
3874
|
+
}
|
|
3875
|
+
if (timelineItem.type === "assistant_message") {
|
|
3876
|
+
const buffered = this.pendingAgentMessages.get(itemId);
|
|
3877
|
+
if (buffered && buffered.length > 0) {
|
|
3878
|
+
timelineItem.text = buffered;
|
|
3879
|
+
}
|
|
3880
|
+
return;
|
|
3881
|
+
}
|
|
3882
|
+
if (timelineItem.type === "reasoning") {
|
|
3883
|
+
const buffered = this.pendingReasoning.get(itemId);
|
|
3884
|
+
if (buffered && buffered.length > 0) {
|
|
3885
|
+
timelineItem.text = buffered.join("");
|
|
3886
|
+
}
|
|
3887
|
+
}
|
|
3888
|
+
}
|
|
3889
|
+
handleItemStartedNotification(parsed) {
|
|
3890
|
+
if (parsed.source === "codex_event") {
|
|
3891
|
+
return;
|
|
3892
|
+
}
|
|
3893
|
+
if (this.isUserMessageItem(parsed.item)) {
|
|
3894
|
+
this.handleUserMessageItem(parsed);
|
|
3895
|
+
return;
|
|
3896
|
+
}
|
|
3897
|
+
if (this.isContextCompactionItem(parsed.item)) {
|
|
3898
|
+
this.emitEvent({
|
|
3899
|
+
type: "timeline",
|
|
3900
|
+
provider: CODEX_PROVIDER,
|
|
3901
|
+
item: this.createContextCompactionTimelineItem("loading", parsed.item.id),
|
|
3902
|
+
});
|
|
3903
|
+
return;
|
|
3904
|
+
}
|
|
3905
|
+
const timelineItem = threadItemToTimeline(parsed.item, {
|
|
3906
|
+
includeUserMessage: false,
|
|
3907
|
+
cwd: this.config.cwd ?? null,
|
|
3908
|
+
});
|
|
3909
|
+
if (!timelineItem || timelineItem.type !== "tool_call") {
|
|
3910
|
+
return;
|
|
3911
|
+
}
|
|
3912
|
+
const childSubAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId);
|
|
3913
|
+
if (childSubAgentCallId) {
|
|
3914
|
+
if (parsed.item.id) {
|
|
3915
|
+
this.upsertSubAgentChildItem(childSubAgentCallId, parsed.item.id, timelineItem);
|
|
3916
|
+
}
|
|
3917
|
+
this.emitSubAgentActivityUpdate(childSubAgentCallId, "running");
|
|
3918
|
+
return;
|
|
3919
|
+
}
|
|
3920
|
+
const normalizedItemType = normalizeCodexThreadItemType(typeof parsed.item.type === "string" ? parsed.item.type : undefined);
|
|
3921
|
+
const itemId = parsed.item.id;
|
|
3922
|
+
if (normalizedItemType === "commandExecution") {
|
|
3923
|
+
const callId = timelineItem.callId || itemId;
|
|
3924
|
+
if (callId && this.emittedExecCommandStartedCallIds.has(callId)) {
|
|
3925
|
+
return;
|
|
3926
|
+
}
|
|
3927
|
+
}
|
|
3928
|
+
if (itemId && this.emittedItemStartedIds.has(itemId)) {
|
|
3929
|
+
return;
|
|
3930
|
+
}
|
|
3931
|
+
this.warnOnIncompleteEditToolCall(timelineItem, "item_started", parsed.item);
|
|
3932
|
+
this.registerSubAgentToolCall(timelineItem, parsed.item);
|
|
3933
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem });
|
|
3934
|
+
if (itemId) {
|
|
3935
|
+
this.emittedItemStartedIds.add(itemId);
|
|
3936
|
+
this.pendingCommandOutputDeltas.delete(itemId);
|
|
3937
|
+
this.pendingFileChangeOutputDeltas.delete(itemId);
|
|
3938
|
+
}
|
|
3939
|
+
}
|
|
3940
|
+
handleUserMessageItem(parsed) {
|
|
3941
|
+
const itemId = parsed.item.id;
|
|
3942
|
+
const timelineItem = threadItemToTimeline(parsed.item, {
|
|
3943
|
+
includeUserMessage: true,
|
|
3944
|
+
cwd: this.config.cwd ?? null,
|
|
3945
|
+
});
|
|
3946
|
+
if (!timelineItem || timelineItem.type !== "user_message") {
|
|
3947
|
+
return;
|
|
3948
|
+
}
|
|
3949
|
+
const childSubAgentCallId = this.getSubAgentCallIdForThread(parsed.threadId);
|
|
3950
|
+
if (childSubAgentCallId) {
|
|
3951
|
+
if (itemId) {
|
|
3952
|
+
this.upsertSubAgentChildItem(childSubAgentCallId, itemId, timelineItem);
|
|
3953
|
+
}
|
|
3954
|
+
this.emitSubAgentActivityUpdate(childSubAgentCallId, "running");
|
|
3955
|
+
return;
|
|
3956
|
+
}
|
|
3957
|
+
if (!this.rememberCodexUserMessageTurn(timelineItem.messageId)) {
|
|
3958
|
+
return;
|
|
3959
|
+
}
|
|
3960
|
+
this.emitEvent({ type: "timeline", provider: CODEX_PROVIDER, item: timelineItem });
|
|
3961
|
+
}
|
|
3962
|
+
warnUnknownNotificationMethod(method, params) {
|
|
3963
|
+
if (this.warnedUnknownNotificationMethods.has(method)) {
|
|
3964
|
+
return;
|
|
3965
|
+
}
|
|
3966
|
+
this.warnedUnknownNotificationMethods.add(method);
|
|
3967
|
+
this.logger.trace({
|
|
3968
|
+
agentId: this.agentId,
|
|
3969
|
+
provider: CODEX_PROVIDER,
|
|
3970
|
+
sessionId: this.currentThreadId,
|
|
3971
|
+
turnId: this.activeForegroundTurnId ?? undefined,
|
|
3972
|
+
method,
|
|
3973
|
+
params,
|
|
3974
|
+
}, "provider.codex.event_unhandled");
|
|
3975
|
+
}
|
|
3976
|
+
warnInvalidNotificationPayload(method, params) {
|
|
3977
|
+
const key = method;
|
|
3978
|
+
if (this.warnedInvalidNotificationPayloads.has(key)) {
|
|
3979
|
+
return;
|
|
3980
|
+
}
|
|
3981
|
+
this.warnedInvalidNotificationPayloads.add(key);
|
|
3982
|
+
this.logger.warn({ method, params }, "Invalid Codex app-server notification payload");
|
|
3983
|
+
}
|
|
3984
|
+
appendOutputDeltaChunk(store, id, chunk, options) {
|
|
3985
|
+
if (!id || !chunk) {
|
|
3986
|
+
return;
|
|
3987
|
+
}
|
|
3988
|
+
const normalized = options?.decodeBase64 ? decodeCodexOutputDeltaChunk(chunk) : chunk;
|
|
3989
|
+
if (!normalized.length) {
|
|
3990
|
+
return;
|
|
3991
|
+
}
|
|
3992
|
+
const prev = store.get(id) ?? [];
|
|
3993
|
+
prev.push(normalized);
|
|
3994
|
+
store.set(id, prev);
|
|
3995
|
+
}
|
|
3996
|
+
consumeOutputDelta(store, id) {
|
|
3997
|
+
if (!id) {
|
|
3998
|
+
return null;
|
|
3999
|
+
}
|
|
4000
|
+
const buffered = store.get(id);
|
|
4001
|
+
if (!buffered || buffered.length === 0) {
|
|
4002
|
+
return null;
|
|
4003
|
+
}
|
|
4004
|
+
store.delete(id);
|
|
4005
|
+
return buffered.join("");
|
|
4006
|
+
}
|
|
4007
|
+
rememberTerminalProcessForCommand(command, output) {
|
|
4008
|
+
const normalizedCommand = normalizeCodexCommandValue(command);
|
|
4009
|
+
if (!normalizedCommand) {
|
|
4010
|
+
return;
|
|
4011
|
+
}
|
|
4012
|
+
const displayCommand = typeof normalizedCommand === "string"
|
|
4013
|
+
? normalizedCommand
|
|
4014
|
+
: normalizedCommand.join(" ").trim();
|
|
4015
|
+
if (!displayCommand) {
|
|
4016
|
+
return;
|
|
4017
|
+
}
|
|
4018
|
+
const processId = extractCodexTerminalSessionId(output ?? undefined);
|
|
4019
|
+
if (!processId) {
|
|
4020
|
+
return;
|
|
4021
|
+
}
|
|
4022
|
+
this.terminalCommandByProcessId.set(processId, displayCommand);
|
|
4023
|
+
if (!this.pendingUnlabeledTerminalInteractions.has(processId)) {
|
|
4024
|
+
return;
|
|
4025
|
+
}
|
|
4026
|
+
this.pendingUnlabeledTerminalInteractions.delete(processId);
|
|
4027
|
+
this.emitEvent({
|
|
4028
|
+
type: "timeline",
|
|
4029
|
+
provider: CODEX_PROVIDER,
|
|
4030
|
+
item: mapCodexTerminalInteractionToToolCall({
|
|
4031
|
+
processId,
|
|
4032
|
+
command: displayCommand,
|
|
4033
|
+
}),
|
|
4034
|
+
});
|
|
4035
|
+
}
|
|
4036
|
+
shouldEmitTerminalInteractionKey(key) {
|
|
4037
|
+
if (this.emittedTerminalInteractionKeys.has(key)) {
|
|
4038
|
+
return false;
|
|
4039
|
+
}
|
|
4040
|
+
this.emittedTerminalInteractionKeys.add(key);
|
|
4041
|
+
return true;
|
|
4042
|
+
}
|
|
4043
|
+
warnOnIncompleteEditToolCall(item, source, payload) {
|
|
4044
|
+
if (!isEditToolCallWithoutContent(item)) {
|
|
4045
|
+
return;
|
|
4046
|
+
}
|
|
4047
|
+
const warnKey = `${source}:${item.callId}`;
|
|
4048
|
+
if (this.warnedIncompleteEditToolCallIds.has(warnKey)) {
|
|
4049
|
+
return;
|
|
4050
|
+
}
|
|
4051
|
+
this.warnedIncompleteEditToolCallIds.add(warnKey);
|
|
4052
|
+
this.logger.warn({
|
|
4053
|
+
source,
|
|
4054
|
+
callId: item.callId,
|
|
4055
|
+
status: item.status,
|
|
4056
|
+
name: item.name,
|
|
4057
|
+
detail: item.detail,
|
|
4058
|
+
payload,
|
|
4059
|
+
}, "Codex edit tool call is missing diff/content fields");
|
|
4060
|
+
}
|
|
4061
|
+
handleCommandApprovalRequest(params) {
|
|
4062
|
+
const parsed = z
|
|
4063
|
+
.object({
|
|
4064
|
+
itemId: z.string(),
|
|
4065
|
+
threadId: z.string(),
|
|
4066
|
+
turnId: z.string(),
|
|
4067
|
+
command: z.string().nullable().optional(),
|
|
4068
|
+
cwd: z.string().nullable().optional(),
|
|
4069
|
+
reason: z.string().nullable().optional(),
|
|
4070
|
+
})
|
|
4071
|
+
.parse(params);
|
|
4072
|
+
const commandPreview = mapCodexExecNotificationToToolCall({
|
|
4073
|
+
callId: parsed.itemId,
|
|
4074
|
+
command: parsed.command,
|
|
4075
|
+
cwd: parsed.cwd ?? this.config.cwd ?? null,
|
|
4076
|
+
running: true,
|
|
4077
|
+
});
|
|
4078
|
+
const requestId = `permission-${parsed.itemId}`;
|
|
4079
|
+
const title = parsed.command ? `Run command: ${parsed.command}` : "Run command";
|
|
4080
|
+
const request = {
|
|
4081
|
+
id: requestId,
|
|
4082
|
+
provider: CODEX_PROVIDER,
|
|
4083
|
+
name: "CodexBash",
|
|
4084
|
+
kind: "tool",
|
|
4085
|
+
title,
|
|
4086
|
+
description: parsed.reason ?? undefined,
|
|
4087
|
+
input: {
|
|
4088
|
+
command: parsed.command ?? undefined,
|
|
4089
|
+
cwd: parsed.cwd ?? undefined,
|
|
4090
|
+
},
|
|
4091
|
+
detail: commandPreview?.detail ?? {
|
|
4092
|
+
type: "unknown",
|
|
4093
|
+
input: {
|
|
4094
|
+
command: parsed.command ?? null,
|
|
4095
|
+
cwd: parsed.cwd ?? null,
|
|
4096
|
+
},
|
|
4097
|
+
output: null,
|
|
4098
|
+
},
|
|
4099
|
+
metadata: {
|
|
4100
|
+
itemId: parsed.itemId,
|
|
4101
|
+
threadId: parsed.threadId,
|
|
4102
|
+
turnId: parsed.turnId,
|
|
4103
|
+
},
|
|
4104
|
+
};
|
|
4105
|
+
this.pendingPermissions.set(requestId, request);
|
|
4106
|
+
this.emitEvent({ type: "permission_requested", provider: CODEX_PROVIDER, request });
|
|
4107
|
+
return new Promise((resolve) => {
|
|
4108
|
+
this.pendingPermissionHandlers.set(requestId, { resolve, kind: "command" });
|
|
4109
|
+
});
|
|
4110
|
+
}
|
|
4111
|
+
handleFileChangeApprovalRequest(params) {
|
|
4112
|
+
const parsed = z
|
|
4113
|
+
.object({
|
|
4114
|
+
itemId: z.string(),
|
|
4115
|
+
threadId: z.string(),
|
|
4116
|
+
turnId: z.string(),
|
|
4117
|
+
reason: z.string().nullable().optional(),
|
|
4118
|
+
})
|
|
4119
|
+
.parse(params);
|
|
4120
|
+
const requestId = `permission-${parsed.itemId}`;
|
|
4121
|
+
const request = {
|
|
4122
|
+
id: requestId,
|
|
4123
|
+
provider: CODEX_PROVIDER,
|
|
4124
|
+
name: "CodexFileChange",
|
|
4125
|
+
kind: "tool",
|
|
4126
|
+
title: "Apply file changes",
|
|
4127
|
+
description: parsed.reason ?? undefined,
|
|
4128
|
+
detail: {
|
|
4129
|
+
type: "unknown",
|
|
4130
|
+
input: {
|
|
4131
|
+
reason: parsed.reason ?? null,
|
|
4132
|
+
},
|
|
4133
|
+
output: null,
|
|
4134
|
+
},
|
|
4135
|
+
metadata: {
|
|
4136
|
+
itemId: parsed.itemId,
|
|
4137
|
+
threadId: parsed.threadId,
|
|
4138
|
+
turnId: parsed.turnId,
|
|
4139
|
+
},
|
|
4140
|
+
};
|
|
4141
|
+
this.pendingPermissions.set(requestId, request);
|
|
4142
|
+
this.emitEvent({ type: "permission_requested", provider: CODEX_PROVIDER, request });
|
|
4143
|
+
return new Promise((resolve) => {
|
|
4144
|
+
this.pendingPermissionHandlers.set(requestId, { resolve, kind: "file" });
|
|
4145
|
+
});
|
|
4146
|
+
}
|
|
4147
|
+
handleToolApprovalRequest(params) {
|
|
4148
|
+
const parsed = z
|
|
4149
|
+
.object({
|
|
4150
|
+
itemId: z.string(),
|
|
4151
|
+
threadId: z.string(),
|
|
4152
|
+
turnId: z.string(),
|
|
4153
|
+
questions: z.array(z.unknown()),
|
|
4154
|
+
})
|
|
4155
|
+
.parse(params);
|
|
4156
|
+
const requestId = `permission-${parsed.itemId}`;
|
|
4157
|
+
const questions = normalizeCodexQuestionPrompts(parsed.questions);
|
|
4158
|
+
const request = {
|
|
4159
|
+
id: requestId,
|
|
4160
|
+
provider: CODEX_PROVIDER,
|
|
4161
|
+
name: "request_user_input",
|
|
4162
|
+
kind: "question",
|
|
4163
|
+
title: "Question",
|
|
4164
|
+
description: undefined,
|
|
4165
|
+
detail: {
|
|
4166
|
+
type: "plain_text",
|
|
4167
|
+
text: formatCodexQuestionPrompts(questions),
|
|
4168
|
+
icon: "brain",
|
|
4169
|
+
},
|
|
4170
|
+
input: { questions },
|
|
4171
|
+
metadata: {
|
|
4172
|
+
itemId: parsed.itemId,
|
|
4173
|
+
threadId: parsed.threadId,
|
|
4174
|
+
turnId: parsed.turnId,
|
|
4175
|
+
questions,
|
|
4176
|
+
},
|
|
4177
|
+
};
|
|
4178
|
+
this.pendingPermissions.set(requestId, request);
|
|
4179
|
+
this.emitEvent({
|
|
4180
|
+
type: "timeline",
|
|
4181
|
+
provider: CODEX_PROVIDER,
|
|
4182
|
+
item: mapCodexQuestionRequestToToolCall({
|
|
4183
|
+
callId: parsed.itemId,
|
|
4184
|
+
questions,
|
|
4185
|
+
status: "running",
|
|
4186
|
+
}),
|
|
4187
|
+
});
|
|
4188
|
+
this.emitEvent({ type: "permission_requested", provider: CODEX_PROVIDER, request });
|
|
4189
|
+
return new Promise((resolve) => {
|
|
4190
|
+
this.pendingPermissionHandlers.set(requestId, {
|
|
4191
|
+
resolve,
|
|
4192
|
+
kind: "question",
|
|
4193
|
+
questions,
|
|
4194
|
+
});
|
|
4195
|
+
});
|
|
4196
|
+
}
|
|
4197
|
+
}
|
|
4198
|
+
export class CodexAppServerAgentClient {
|
|
4199
|
+
constructor(logger, runtimeSettings, deps = {}) {
|
|
4200
|
+
this.logger = logger;
|
|
4201
|
+
this.runtimeSettings = runtimeSettings;
|
|
4202
|
+
this.deps = deps;
|
|
4203
|
+
this.provider = CODEX_PROVIDER;
|
|
4204
|
+
this.capabilities = CODEX_APP_SERVER_CAPABILITIES;
|
|
4205
|
+
this.goalsEnabledPromise = null;
|
|
4206
|
+
this.autoReviewEnabledPromise = null;
|
|
4207
|
+
}
|
|
4208
|
+
sessionDeps() {
|
|
4209
|
+
return {
|
|
4210
|
+
...this.deps,
|
|
4211
|
+
customCodexConfig: buildCodexCustomProviderConfig(this.runtimeSettings, this.deps.customProvider),
|
|
4212
|
+
};
|
|
4213
|
+
}
|
|
4214
|
+
resolveGoalsEnabled() {
|
|
4215
|
+
if (!this.goalsEnabledPromise) {
|
|
4216
|
+
this.goalsEnabledPromise = (async () => {
|
|
4217
|
+
try {
|
|
4218
|
+
const launchPrefix = await resolveCodexLaunchPrefix(this.runtimeSettings);
|
|
4219
|
+
const versionOutput = await resolveBinaryVersion(launchPrefix.command);
|
|
4220
|
+
const enabled = codexVersionAtLeast(versionOutput, CODEX_GOALS_MIN_VERSION);
|
|
4221
|
+
this.logger.trace({
|
|
4222
|
+
provider: CODEX_PROVIDER,
|
|
4223
|
+
versionOutput,
|
|
4224
|
+
enabled,
|
|
4225
|
+
}, "provider.codex.config.goals_resolved");
|
|
4226
|
+
return enabled;
|
|
4227
|
+
}
|
|
4228
|
+
catch (error) {
|
|
4229
|
+
this.logger.warn({ err: error }, "Failed to probe codex version for goals gate");
|
|
4230
|
+
return false;
|
|
4231
|
+
}
|
|
4232
|
+
})();
|
|
4233
|
+
}
|
|
4234
|
+
return this.goalsEnabledPromise;
|
|
4235
|
+
}
|
|
4236
|
+
resolveAutoReviewEnabled() {
|
|
4237
|
+
if (!this.autoReviewEnabledPromise) {
|
|
4238
|
+
this.autoReviewEnabledPromise = (async () => {
|
|
4239
|
+
try {
|
|
4240
|
+
const launchPrefix = await resolveCodexLaunchPrefix(this.runtimeSettings);
|
|
4241
|
+
const versionOutput = await resolveBinaryVersion(launchPrefix.command);
|
|
4242
|
+
const enabled = codexVersionAtLeast(versionOutput, CODEX_AUTO_REVIEW_MIN_VERSION);
|
|
4243
|
+
this.logger.trace({
|
|
4244
|
+
provider: CODEX_PROVIDER,
|
|
4245
|
+
versionOutput,
|
|
4246
|
+
enabled,
|
|
4247
|
+
}, "provider.codex.config.auto_review_resolved");
|
|
4248
|
+
return enabled;
|
|
4249
|
+
}
|
|
4250
|
+
catch (error) {
|
|
4251
|
+
this.logger.warn({ err: error }, "Failed to probe codex version for auto-review gate");
|
|
4252
|
+
return false;
|
|
4253
|
+
}
|
|
4254
|
+
})();
|
|
4255
|
+
}
|
|
4256
|
+
return this.autoReviewEnabledPromise;
|
|
4257
|
+
}
|
|
4258
|
+
async spawnAppServer(launchEnv, options) {
|
|
4259
|
+
const launchPrefix = await resolveCodexLaunchPrefix(this.runtimeSettings);
|
|
4260
|
+
const args = [...launchPrefix.args, "app-server"];
|
|
4261
|
+
if (options?.goalsEnabled) {
|
|
4262
|
+
args.push("--enable", "goals");
|
|
4263
|
+
}
|
|
4264
|
+
this.logger.trace({
|
|
4265
|
+
agentId: options?.agentId,
|
|
4266
|
+
provider: CODEX_PROVIDER,
|
|
4267
|
+
launchPrefix,
|
|
4268
|
+
goalsEnabled: options?.goalsEnabled === true,
|
|
4269
|
+
}, "provider.codex.spawn");
|
|
4270
|
+
const child = spawnProcess(launchPrefix.command, args, {
|
|
4271
|
+
detached: process.platform !== "win32",
|
|
4272
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
4273
|
+
...createProviderEnvSpec({
|
|
4274
|
+
runtimeSettings: this.runtimeSettings,
|
|
4275
|
+
overlays: [launchEnv],
|
|
4276
|
+
}),
|
|
4277
|
+
});
|
|
4278
|
+
assertChildWithPipes(child);
|
|
4279
|
+
return child;
|
|
4280
|
+
}
|
|
4281
|
+
async createSession(config, launchContext, options) {
|
|
4282
|
+
if (options?.persistSession === false) {
|
|
4283
|
+
this.logger.debug("Codex app-server does not expose an ephemeral-session option; persistSession=false is currently a no-op");
|
|
4284
|
+
// TODO: Honor persistSession=false if app-server adds support, or route
|
|
4285
|
+
// utility generations through `codex exec --ephemeral` in a larger change.
|
|
4286
|
+
}
|
|
4287
|
+
const sessionConfig = { ...config, provider: CODEX_PROVIDER };
|
|
4288
|
+
const goalsEnabled = await this.resolveGoalsEnabled();
|
|
4289
|
+
const autoReviewEnabled = await this.resolveAutoReviewEnabled();
|
|
4290
|
+
const session = new CodexAppServerAgentSession(sessionConfig, null, this.logger, () => this.spawnAppServer(launchContext?.env, { goalsEnabled, agentId: launchContext?.agentId }), this.sessionDeps(), options?.persistSession === false, goalsEnabled, autoReviewEnabled, launchContext?.agentId);
|
|
4291
|
+
await session.connect();
|
|
4292
|
+
return session;
|
|
4293
|
+
}
|
|
4294
|
+
async resumeSession(handle, overrides, launchContext) {
|
|
4295
|
+
const storedConfig = (handle.metadata ?? {});
|
|
4296
|
+
const merged = {
|
|
4297
|
+
...storedConfig,
|
|
4298
|
+
...overrides,
|
|
4299
|
+
provider: CODEX_PROVIDER,
|
|
4300
|
+
cwd: overrides?.cwd ?? storedConfig.cwd ?? process.cwd(),
|
|
4301
|
+
};
|
|
4302
|
+
const goalsEnabled = await this.resolveGoalsEnabled();
|
|
4303
|
+
const autoReviewEnabled = await this.resolveAutoReviewEnabled();
|
|
4304
|
+
const session = new CodexAppServerAgentSession(merged, handle, this.logger, () => this.spawnAppServer(launchContext?.env, { goalsEnabled, agentId: launchContext?.agentId }), this.sessionDeps(), false, goalsEnabled, autoReviewEnabled, launchContext?.agentId);
|
|
4305
|
+
await session.connect();
|
|
4306
|
+
return session;
|
|
4307
|
+
}
|
|
4308
|
+
async listImportableSessions(options) {
|
|
4309
|
+
const child = await this.spawnAppServer();
|
|
4310
|
+
const client = this.deps._createCodexClient?.(child, this.logger, () => ({})) ??
|
|
4311
|
+
new CodexAppServerClient(child, this.logger);
|
|
4312
|
+
try {
|
|
4313
|
+
await client.request("initialize", buildCodexAppServerInitializeParams());
|
|
4314
|
+
client.notify("initialized", {});
|
|
4315
|
+
const limit = options?.limit ?? 20;
|
|
4316
|
+
// thread/list returns the cheap `cwd` field. Fetch a wider window when
|
|
4317
|
+
// filtering since most threads will be from other cwds, then keep the
|
|
4318
|
+
// local realpath-aware filter for symlink-equivalent workspace paths.
|
|
4319
|
+
const listLimit = options?.cwd ? Math.max(limit, 50) : limit;
|
|
4320
|
+
const response = toObjectRecord(await client.request("thread/list", {
|
|
4321
|
+
limit: listLimit,
|
|
4322
|
+
...(options?.cwd ? { cwd: options.cwd } : {}),
|
|
4323
|
+
}));
|
|
4324
|
+
const allThreads = Array.isArray(response?.data) ? response.data.filter(isRecord) : [];
|
|
4325
|
+
const threads = filterCodexThreadsByCwd(allThreads, options?.cwd);
|
|
4326
|
+
return threads.slice(0, limit).map((thread) => {
|
|
4327
|
+
const threadId = typeof thread.id === "string" ? thread.id : "";
|
|
4328
|
+
const cwd = typeof thread.cwd === "string" ? thread.cwd : process.cwd();
|
|
4329
|
+
const preview = typeof thread.preview === "string" ? thread.preview : null;
|
|
4330
|
+
const title = typeof thread.name === "string" && thread.name.trim() ? thread.name : preview;
|
|
4331
|
+
return {
|
|
4332
|
+
providerHandleId: threadId,
|
|
4333
|
+
cwd,
|
|
4334
|
+
title,
|
|
4335
|
+
firstPromptPreview: preview,
|
|
4336
|
+
lastPromptPreview: preview,
|
|
4337
|
+
lastActivityAt: new Date(((typeof thread.updatedAt === "number" ? thread.updatedAt : undefined) ??
|
|
4338
|
+
(typeof thread.createdAt === "number" ? thread.createdAt : undefined) ??
|
|
4339
|
+
0) * 1000),
|
|
4340
|
+
};
|
|
4341
|
+
});
|
|
4342
|
+
}
|
|
4343
|
+
finally {
|
|
4344
|
+
await client.dispose();
|
|
4345
|
+
}
|
|
4346
|
+
}
|
|
4347
|
+
async importSession(input, context) {
|
|
4348
|
+
return importSessionFromPersistence({
|
|
4349
|
+
provider: CODEX_PROVIDER,
|
|
4350
|
+
request: input,
|
|
4351
|
+
context,
|
|
4352
|
+
resumeSession: this.resumeSession.bind(this),
|
|
4353
|
+
});
|
|
4354
|
+
}
|
|
4355
|
+
async fetchCatalog(_options) {
|
|
4356
|
+
const models = await this.fetchModelsFromAppServer();
|
|
4357
|
+
return { models, modes: CODEX_MODES };
|
|
4358
|
+
}
|
|
4359
|
+
async fetchModelsFromAppServer() {
|
|
4360
|
+
// Codex model/list is global to the app server in this flow; cwd/force are intentionally ignored.
|
|
4361
|
+
const child = await this.spawnAppServer();
|
|
4362
|
+
const client = new CodexAppServerClient(child, this.logger);
|
|
4363
|
+
try {
|
|
4364
|
+
await client.request("initialize", buildCodexAppServerInitializeParams());
|
|
4365
|
+
client.notify("initialized", {});
|
|
4366
|
+
const rawResponse = await client.request("model/list", {});
|
|
4367
|
+
const parsedResponse = CodexModelListResponseSchema.safeParse(rawResponse);
|
|
4368
|
+
const models = parsedResponse.success ? (parsedResponse.data.data ?? []) : [];
|
|
4369
|
+
const configuredDefaults = await readCodexConfiguredDefaults(client, this.logger);
|
|
4370
|
+
const configuredDefaultModelId = configuredDefaults.model;
|
|
4371
|
+
const configuredDefaultThinkingOptionId = configuredDefaults.thinkingOptionId;
|
|
4372
|
+
const hasConfiguredDefaultModel = typeof configuredDefaultModelId === "string"
|
|
4373
|
+
? models.some((model) => model?.id === configuredDefaultModelId)
|
|
4374
|
+
: false;
|
|
4375
|
+
return models.map((model) => buildCodexModelDefinition(model, {
|
|
4376
|
+
configuredDefaultModelId,
|
|
4377
|
+
configuredDefaultThinkingOptionId,
|
|
4378
|
+
hasConfiguredDefaultModel,
|
|
4379
|
+
}));
|
|
4380
|
+
}
|
|
4381
|
+
finally {
|
|
4382
|
+
await client.dispose();
|
|
4383
|
+
}
|
|
4384
|
+
}
|
|
4385
|
+
async archiveNativeSession(handle) {
|
|
4386
|
+
const threadId = handle.nativeHandle ?? handle.sessionId;
|
|
4387
|
+
if (!threadId)
|
|
4388
|
+
return;
|
|
4389
|
+
const child = await this.spawnAppServer();
|
|
4390
|
+
const client = new CodexAppServerClient(child, this.logger);
|
|
4391
|
+
try {
|
|
4392
|
+
await client.request("initialize", buildCodexAppServerInitializeParams());
|
|
4393
|
+
client.notify("initialized", {});
|
|
4394
|
+
await client.request("thread/archive", { threadId });
|
|
4395
|
+
}
|
|
4396
|
+
finally {
|
|
4397
|
+
await client.dispose();
|
|
4398
|
+
}
|
|
4399
|
+
}
|
|
4400
|
+
async unarchiveNativeSession(handle) {
|
|
4401
|
+
const threadId = handle.nativeHandle ?? handle.sessionId;
|
|
4402
|
+
if (!threadId)
|
|
4403
|
+
return;
|
|
4404
|
+
const child = await this.spawnAppServer();
|
|
4405
|
+
const client = new CodexAppServerClient(child, this.logger);
|
|
4406
|
+
try {
|
|
4407
|
+
await client.request("initialize", buildCodexAppServerInitializeParams());
|
|
4408
|
+
client.notify("initialized", {});
|
|
4409
|
+
try {
|
|
4410
|
+
await client.request("thread/unarchive", { threadId });
|
|
4411
|
+
}
|
|
4412
|
+
catch (error) {
|
|
4413
|
+
if (!isCodexAlreadyUnarchivedError(error, threadId)) {
|
|
4414
|
+
throw error;
|
|
4415
|
+
}
|
|
4416
|
+
try {
|
|
4417
|
+
await client.request("thread/read", { threadId });
|
|
4418
|
+
}
|
|
4419
|
+
catch {
|
|
4420
|
+
throw error;
|
|
4421
|
+
}
|
|
4422
|
+
}
|
|
4423
|
+
}
|
|
4424
|
+
finally {
|
|
4425
|
+
await client.dispose();
|
|
4426
|
+
}
|
|
4427
|
+
}
|
|
4428
|
+
async isAvailable() {
|
|
4429
|
+
const launch = await resolveCodexLaunch(this.runtimeSettings);
|
|
4430
|
+
const availability = await checkCodexLaunchAvailable(launch);
|
|
4431
|
+
return availability.available;
|
|
4432
|
+
}
|
|
4433
|
+
async getDiagnostic() {
|
|
4434
|
+
try {
|
|
4435
|
+
const launch = await resolveCodexLaunch(this.runtimeSettings);
|
|
4436
|
+
const availability = await checkCodexLaunchAvailable(launch);
|
|
4437
|
+
const entries = [
|
|
4438
|
+
...(await buildCommandResolutionDiagnosticRows(launch, {
|
|
4439
|
+
knownBinaryNames: ["codex"],
|
|
4440
|
+
})),
|
|
4441
|
+
...(await buildBinaryDiagnosticRows(launch, availability)),
|
|
4442
|
+
];
|
|
4443
|
+
return {
|
|
4444
|
+
diagnostic: formatProviderDiagnostic("Codex", entries),
|
|
4445
|
+
};
|
|
4446
|
+
}
|
|
4447
|
+
catch (error) {
|
|
4448
|
+
return {
|
|
4449
|
+
diagnostic: formatProviderDiagnosticError("Codex", error),
|
|
4450
|
+
};
|
|
4451
|
+
}
|
|
4452
|
+
}
|
|
4453
|
+
}
|
|
4454
|
+
function buildCodexModelDefinition(model, ctx) {
|
|
4455
|
+
const defaultReasoningEffort = normalizeCodexThinkingOptionId(typeof model.defaultReasoningEffort === "string" ? model.defaultReasoningEffort : null);
|
|
4456
|
+
const resolvedDefaultReasoningEffort = ctx.configuredDefaultThinkingOptionId ?? defaultReasoningEffort;
|
|
4457
|
+
const thinkingById = buildCodexThinkingOptionMap(model.supportedReasoningEfforts, resolvedDefaultReasoningEffort, ctx.configuredDefaultThinkingOptionId);
|
|
4458
|
+
const thinkingOptions = Array.from(thinkingById.values()).map((option) => Object.assign({}, option, {
|
|
4459
|
+
isDefault: option.id === resolvedDefaultReasoningEffort,
|
|
4460
|
+
}));
|
|
4461
|
+
const defaultThinkingOptionId = resolvedDefaultReasoningEffort ??
|
|
4462
|
+
thinkingOptions.find((option) => option.isDefault)?.id ??
|
|
4463
|
+
thinkingOptions[0]?.id;
|
|
4464
|
+
const isDefaultModel = ctx.hasConfiguredDefaultModel
|
|
4465
|
+
? model.id === ctx.configuredDefaultModelId
|
|
4466
|
+
: model.isDefault;
|
|
4467
|
+
return {
|
|
4468
|
+
provider: CODEX_PROVIDER,
|
|
4469
|
+
id: model.id,
|
|
4470
|
+
label: normalizeCodexModelLabel(model.displayName ?? ""),
|
|
4471
|
+
description: model.description,
|
|
4472
|
+
isDefault: isDefaultModel,
|
|
4473
|
+
thinkingOptions: thinkingOptions.length > 0 ? thinkingOptions : undefined,
|
|
4474
|
+
defaultThinkingOptionId,
|
|
4475
|
+
metadata: {
|
|
4476
|
+
model: model.model,
|
|
4477
|
+
defaultReasoningEffort: model.defaultReasoningEffort,
|
|
4478
|
+
supportedReasoningEfforts: model.supportedReasoningEfforts,
|
|
4479
|
+
},
|
|
4480
|
+
};
|
|
4481
|
+
}
|
|
4482
|
+
function buildCodexThinkingOptionMap(supportedReasoningEfforts, resolvedDefaultReasoningEffort, configuredDefaultThinkingOptionId) {
|
|
4483
|
+
const thinkingById = new Map();
|
|
4484
|
+
if (Array.isArray(supportedReasoningEfforts)) {
|
|
4485
|
+
for (const entry of supportedReasoningEfforts) {
|
|
4486
|
+
const id = normalizeCodexThinkingOptionId(typeof entry?.reasoningEffort === "string" ? entry.reasoningEffort : null);
|
|
4487
|
+
if (!id)
|
|
4488
|
+
continue;
|
|
4489
|
+
const description = typeof entry?.description === "string" && entry.description.trim().length > 0
|
|
4490
|
+
? entry.description
|
|
4491
|
+
: undefined;
|
|
4492
|
+
thinkingById.set(id, { id, label: id, description });
|
|
4493
|
+
}
|
|
4494
|
+
}
|
|
4495
|
+
if (resolvedDefaultReasoningEffort && !thinkingById.has(resolvedDefaultReasoningEffort)) {
|
|
4496
|
+
thinkingById.set(resolvedDefaultReasoningEffort, {
|
|
4497
|
+
id: resolvedDefaultReasoningEffort,
|
|
4498
|
+
label: resolvedDefaultReasoningEffort,
|
|
4499
|
+
description: configuredDefaultThinkingOptionId === resolvedDefaultReasoningEffort
|
|
4500
|
+
? "Configured default reasoning effort"
|
|
4501
|
+
: "Model default reasoning effort",
|
|
4502
|
+
});
|
|
4503
|
+
}
|
|
4504
|
+
return thinkingById;
|
|
4505
|
+
}
|
|
4506
|
+
function resolveSkillDescription(skill) {
|
|
4507
|
+
if (typeof skill.description === "string") {
|
|
4508
|
+
return skill.description;
|
|
4509
|
+
}
|
|
4510
|
+
if (typeof skill.shortDescription === "string") {
|
|
4511
|
+
return skill.shortDescription;
|
|
4512
|
+
}
|
|
4513
|
+
return "Skill";
|
|
4514
|
+
}
|
|
4515
|
+
//# sourceMappingURL=codex-app-server-agent.js.map
|