somora 2026.930.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +364 -0
- package/bin/node-version.d.mts +3 -0
- package/bin/node-version.mjs +45 -0
- package/bin/somora.mjs +77 -0
- package/config.example.yaml +896 -0
- package/docs/agents.md +677 -0
- package/docs/api.md +3194 -0
- package/docs/browser.md +317 -0
- package/docs/builder.md +331 -0
- package/docs/cache-strategy.md +373 -0
- package/docs/compaction.md +253 -0
- package/docs/display.md +154 -0
- package/docs/dream-phases.md +891 -0
- package/docs/files.md +387 -0
- package/docs/imagegen.md +366 -0
- package/docs/images/somora-hero.png +0 -0
- package/docs/images/somora-mobile-2026-05-23.png +0 -0
- package/docs/images/somora-tui-2026-05-23.png +0 -0
- package/docs/images/somora-web-2026-05-23.png +0 -0
- package/docs/index.md +178 -0
- package/docs/lsp.md +93 -0
- package/docs/mcp.md +332 -0
- package/docs/memory.md +407 -0
- package/docs/mobile.md +310 -0
- package/docs/models.md +379 -0
- package/docs/projects.md +425 -0
- package/docs/realtime-voice.md +293 -0
- package/docs/resources.md +230 -0
- package/docs/sampling.md +128 -0
- package/docs/security.md +189 -0
- package/docs/sentinel.md +295 -0
- package/docs/setup.md +1217 -0
- package/docs/skills.md +501 -0
- package/docs/team.md +189 -0
- package/docs/thinking.md +463 -0
- package/docs/tmux.md +399 -0
- package/docs/tools.md +117 -0
- package/docs/videogen.md +191 -0
- package/docs/voice.md +288 -0
- package/docs/web.md +893 -0
- package/docs/wiki.md +583 -0
- package/npm-shrinkwrap.json +5670 -0
- package/package.json +116 -0
- package/src/attachments/store.ts +196 -0
- package/src/browser/change-stream.ts +31 -0
- package/src/browser/display.ts +108 -0
- package/src/browser/policy.ts +121 -0
- package/src/browser/screencast.ts +374 -0
- package/src/browser/service.ts +1337 -0
- package/src/browser/session.ts +15 -0
- package/src/browser/snapshot.ts +40 -0
- package/src/cli/auth.ts +117 -0
- package/src/cli/codex.ts +41 -0
- package/src/cli/lsp.ts +71 -0
- package/src/cli/resolvers/clawhub.ts +400 -0
- package/src/cli/setup.ts +835 -0
- package/src/cli/skill.ts +619 -0
- package/src/cli/somora.ts +548 -0
- package/src/cli/systemd-unit.ts +72 -0
- package/src/cli/team.ts +148 -0
- package/src/cli/tui/activity-stream.ts +121 -0
- package/src/cli/tui/api.ts +479 -0
- package/src/cli/tui/app.tsx +1169 -0
- package/src/cli/tui/autocomplete.tsx +55 -0
- package/src/cli/tui/commands.ts +913 -0
- package/src/cli/tui/dream-glyphs.ts +22 -0
- package/src/cli/tui/footer.tsx +15 -0
- package/src/cli/tui/format.ts +28 -0
- package/src/cli/tui/header.tsx +279 -0
- package/src/cli/tui/index.tsx +120 -0
- package/src/cli/tui/markdown.tsx +63 -0
- package/src/cli/tui/sampling.ts +162 -0
- package/src/cli/tui/separator.tsx +13 -0
- package/src/cli/tui/state.ts +42 -0
- package/src/cli/tui/stream.ts +330 -0
- package/src/cli/tui/thinking-text.ts +54 -0
- package/src/cli/tui/turn-views.tsx +499 -0
- package/src/cli/tui/types.ts +410 -0
- package/src/cli/tui/work-queue.ts +161 -0
- package/src/cli/update-args.ts +55 -0
- package/src/cli/wiki.ts +406 -0
- package/src/compaction/index.ts +28 -0
- package/src/compaction/midturn.ts +210 -0
- package/src/compaction/policy.ts +154 -0
- package/src/compaction/summarize.ts +691 -0
- package/src/compaction/template.ts +90 -0
- package/src/compaction/types.ts +148 -0
- package/src/config/loader.ts +276 -0
- package/src/config/reload.ts +43 -0
- package/src/config/types.ts +2292 -0
- package/src/dream/deep-actions.ts +324 -0
- package/src/dream/deep-dispatcher.ts +237 -0
- package/src/dream/deep-llm.ts +388 -0
- package/src/dream/deep-prompts.ts +106 -0
- package/src/dream/deep-runner.ts +757 -0
- package/src/dream/deep-skip-cache.ts +199 -0
- package/src/dream/deep-worker.ts +229 -0
- package/src/dream/json-salvage.ts +34 -0
- package/src/dream/judge.ts +188 -0
- package/src/dream/loop-state.ts +286 -0
- package/src/dream/lucid-actions.ts +303 -0
- package/src/dream/lucid-batches.ts +94 -0
- package/src/dream/lucid-prompt.ts +82 -0
- package/src/dream/lucid-runner.ts +744 -0
- package/src/dream/lucid-storage.ts +277 -0
- package/src/dream/lucid-structure.ts +102 -0
- package/src/dream/lucid-types.ts +137 -0
- package/src/dream/lucid-worker.ts +224 -0
- package/src/dream/rem-dedup.ts +502 -0
- package/src/dream/rem-extract.ts +782 -0
- package/src/dream/rem-reset-run.ts +67 -0
- package/src/dream/rem-runner.ts +696 -0
- package/src/dream/rem-worker.ts +527 -0
- package/src/dream/review-window.ts +71 -0
- package/src/dream/scheduler-state.ts +129 -0
- package/src/dream/storage.ts +497 -0
- package/src/dream/types.ts +133 -0
- package/src/dream/wiki-context.ts +133 -0
- package/src/engine/a2a.ts +33 -0
- package/src/engine/availability.ts +63 -0
- package/src/engine/claude-cli.ts +969 -0
- package/src/engine/codex-app-server-client.ts +294 -0
- package/src/engine/codex-bin.ts +49 -0
- package/src/engine/codex-cli.ts +1014 -0
- package/src/engine/codex-dynamic-tools.ts +239 -0
- package/src/engine/codex-home.ts +63 -0
- package/src/engine/codex-thread-config.ts +74 -0
- package/src/engine/context-budget.ts +257 -0
- package/src/engine/engine-meta-labels.ts +211 -0
- package/src/engine/grok-cli.ts +941 -0
- package/src/engine/inline-think.ts +59 -0
- package/src/engine/model-availability.ts +105 -0
- package/src/engine/openai-compatible.ts +2464 -0
- package/src/engine/reasoning-retry.ts +83 -0
- package/src/engine/registry.ts +13 -0
- package/src/engine/replay.ts +195 -0
- package/src/engine/sampling.ts +90 -0
- package/src/engine/thinking-params.ts +264 -0
- package/src/engine/types.ts +269 -0
- package/src/engine/user-tag.ts +24 -0
- package/src/imagegen/aspect.ts +128 -0
- package/src/imagegen/generate.ts +642 -0
- package/src/imagegen/references.ts +75 -0
- package/src/imagegen/types.ts +154 -0
- package/src/lsp/client.ts +183 -0
- package/src/lsp/fake-server.helper.mjs +42 -0
- package/src/lsp/format.ts +29 -0
- package/src/lsp/index.ts +21 -0
- package/src/lsp/manager.ts +238 -0
- package/src/lsp/registry.ts +151 -0
- package/src/mcp/config.ts +117 -0
- package/src/mcp/hub/audit.ts +55 -0
- package/src/mcp/hub/bridge.ts +115 -0
- package/src/mcp/hub/catalog.ts +69 -0
- package/src/mcp/hub/credentials.ts +406 -0
- package/src/mcp/hub/env-expand.ts +14 -0
- package/src/mcp/hub/manager.ts +770 -0
- package/src/mcp/hub/normalize.ts +213 -0
- package/src/mcp/server.ts +368 -0
- package/src/mcp/tool-schema.ts +20 -0
- package/src/media/capabilities.ts +392 -0
- package/src/media/records.ts +175 -0
- package/src/media/store.ts +217 -0
- package/src/media/types.ts +69 -0
- package/src/memory/chunking.ts +168 -0
- package/src/memory/embeddings.ts +262 -0
- package/src/memory/index.ts +15 -0
- package/src/memory/inject.ts +197 -0
- package/src/memory/manager.ts +996 -0
- package/src/memory/registry.ts +176 -0
- package/src/memory/rescan.ts +101 -0
- package/src/memory/retrieval.ts +586 -0
- package/src/memory/shared-index.ts +372 -0
- package/src/memory/slug.ts +39 -0
- package/src/memory/storage.ts +385 -0
- package/src/memory/watcher.ts +134 -0
- package/src/multimodal/blocks.ts +101 -0
- package/src/multimodal/dimensions.ts +214 -0
- package/src/multimodal/load.ts +86 -0
- package/src/multimodal/mime.ts +135 -0
- package/src/multimodal/pdf-render.ts +80 -0
- package/src/multimodal/user-content.ts +266 -0
- package/src/persona/files.ts +144 -0
- package/src/persona/loader.ts +598 -0
- package/src/persona/skill-gating-store.ts +59 -0
- package/src/persona/tool-gating-store.ts +113 -0
- package/src/projects/focus.ts +186 -0
- package/src/projects/prompt-block.ts +106 -0
- package/src/projects/scheme.ts +107 -0
- package/src/projects/store.ts +144 -0
- package/src/projects/types.ts +73 -0
- package/src/sentinel/dispatcher.ts +97 -0
- package/src/sentinel/schedule.ts +271 -0
- package/src/sentinel/scheduler.ts +840 -0
- package/src/sentinel/store.ts +259 -0
- package/src/sentinel/types.ts +221 -0
- package/src/server/activity-stream.ts +160 -0
- package/src/server/ask-calls.ts +137 -0
- package/src/server/ask-wait-graph.ts +171 -0
- package/src/server/async-tasks.ts +199 -0
- package/src/server/builder-busy.ts +86 -0
- package/src/server/builder-prompt.ts +204 -0
- package/src/server/builder-questions.ts +117 -0
- package/src/server/builder-session.ts +249 -0
- package/src/server/chat-aborts.ts +83 -0
- package/src/server/claude-config-dir.ts +71 -0
- package/src/server/claude-credential-sync.ts +454 -0
- package/src/server/env-file.ts +100 -0
- package/src/server/env.ts +115 -0
- package/src/server/heal-session.ts +151 -0
- package/src/server/history-page.ts +46 -0
- package/src/server/index.ts +7244 -0
- package/src/server/lockfile.ts +89 -0
- package/src/server/logger.ts +67 -0
- package/src/server/logs.ts +187 -0
- package/src/server/loopback-fetch.ts +130 -0
- package/src/server/openai-client.ts +89 -0
- package/src/server/prompt-assembly.ts +334 -0
- package/src/server/restart-reconcile.ts +139 -0
- package/src/server/run-turn-fallback.ts +275 -0
- package/src/server/run-turn-types.ts +91 -0
- package/src/server/run-turn.ts +1474 -0
- package/src/server/sanitize-assistant-text.ts +112 -0
- package/src/server/session-export.ts +220 -0
- package/src/server/session-queue.ts +376 -0
- package/src/server/session-workdir.ts +49 -0
- package/src/server/sse-h2-safe.ts +61 -0
- package/src/server/sse-liveness.ts +162 -0
- package/src/server/sse-serializer.ts +161 -0
- package/src/server/start-turn.ts +249 -0
- package/src/server/steer-inbox.ts +107 -0
- package/src/server/tls-keeper.ts +153 -0
- package/src/server/tool-format.ts +167 -0
- package/src/server/turn-framing.ts +52 -0
- package/src/server/turn-origin-kind.ts +74 -0
- package/src/server/turn-origin.ts +40 -0
- package/src/server/work-ledger.ts +975 -0
- package/src/server/workspace.ts +114 -0
- package/src/setup/config-edit.ts +201 -0
- package/src/setup/presets.ts +71 -0
- package/src/setup/prompt.ts +163 -0
- package/src/setup/tailscale.ts +44 -0
- package/src/skills/bin-checks.ts +227 -0
- package/src/skills/bootstrap.ts +347 -0
- package/src/skills/env-scope.ts +175 -0
- package/src/skills/gating.ts +71 -0
- package/src/skills/lint.ts +202 -0
- package/src/skills/load.ts +368 -0
- package/src/skills/path-helpers.ts +102 -0
- package/src/skills/registry.ts +178 -0
- package/src/ssh/exec.ts +142 -0
- package/src/ssh/index.ts +12 -0
- package/src/ssh/known-hosts.ts +109 -0
- package/src/ssh/pool.ts +307 -0
- package/src/storage/sessions.ts +602 -0
- package/src/team/render.ts +149 -0
- package/src/team/resolve.ts +122 -0
- package/src/team/store.ts +124 -0
- package/src/team/types.ts +111 -0
- package/src/team/write.ts +95 -0
- package/src/testing/isolated-home.mts +46 -0
- package/src/tmux/attention-watcher.ts +272 -0
- package/src/tmux/attention.ts +336 -0
- package/src/tmux/list.ts +91 -0
- package/src/tmux/origin-store.ts +102 -0
- package/src/tmux/tui-markers.ts +267 -0
- package/src/tools/agents/ask-cancel.ts +94 -0
- package/src/tools/agents/ask-result.ts +235 -0
- package/src/tools/agents/ask.ts +704 -0
- package/src/tools/agents/builder-dispatch.ts +217 -0
- package/src/tools/agents/images.ts +104 -0
- package/src/tools/agents/index.ts +42 -0
- package/src/tools/agents/long-task-timeouts.ts +39 -0
- package/src/tools/agents/session-list.ts +136 -0
- package/src/tools/agents/session-model.ts +106 -0
- package/src/tools/agents/spawn.ts +845 -0
- package/src/tools/agents/status.ts +589 -0
- package/src/tools/browser/index.ts +6 -0
- package/src/tools/browser/ops.ts +145 -0
- package/src/tools/browser/tools.ts +184 -0
- package/src/tools/builder/short-descriptions.ts +80 -0
- package/src/tools/builder/tools.ts +222 -0
- package/src/tools/docs/index.ts +1 -0
- package/src/tools/docs/tools.ts +228 -0
- package/src/tools/dream/index.ts +11 -0
- package/src/tools/dream/tools.ts +1002 -0
- package/src/tools/exec/allowlist.ts +233 -0
- package/src/tools/exec/background-detach.helper.mts +27 -0
- package/src/tools/exec/blacklist.ts +336 -0
- package/src/tools/exec/concurrency.ts +150 -0
- package/src/tools/exec/fit-output.ts +82 -0
- package/src/tools/exec/index.ts +7 -0
- package/src/tools/exec/internal-env.ts +89 -0
- package/src/tools/exec/job-store.ts +403 -0
- package/src/tools/exec/local.ts +649 -0
- package/src/tools/exec/remote.ts +399 -0
- package/src/tools/exec/tools.ts +934 -0
- package/src/tools/file/analyze.ts +378 -0
- package/src/tools/file/index.ts +2 -0
- package/src/tools/file/local.ts +707 -0
- package/src/tools/file/lsp-hook.ts +72 -0
- package/src/tools/file/persona-guard.ts +61 -0
- package/src/tools/file/policy.ts +292 -0
- package/src/tools/file/read-format.ts +129 -0
- package/src/tools/file/remote.ts +680 -0
- package/src/tools/file/replace.ts +507 -0
- package/src/tools/file/search-window.ts +224 -0
- package/src/tools/file/tools.ts +658 -0
- package/src/tools/file/write-scope.ts +182 -0
- package/src/tools/gating.ts +106 -0
- package/src/tools/image/budget.ts +82 -0
- package/src/tools/image/index.ts +7 -0
- package/src/tools/image/tools.ts +601 -0
- package/src/tools/index.ts +99 -0
- package/src/tools/memory/index.ts +12 -0
- package/src/tools/memory/tools.ts +399 -0
- package/src/tools/projects/index.ts +1 -0
- package/src/tools/projects/tools.ts +643 -0
- package/src/tools/registry.ts +427 -0
- package/src/tools/resources/index.ts +8 -0
- package/src/tools/resources/tools.ts +176 -0
- package/src/tools/resources/visibility.ts +60 -0
- package/src/tools/sentinel/index.ts +1 -0
- package/src/tools/sentinel/tools.ts +592 -0
- package/src/tools/skill/index.ts +4 -0
- package/src/tools/skill/tools.ts +285 -0
- package/src/tools/time/index.ts +5 -0
- package/src/tools/time/tools.ts +123 -0
- package/src/tools/tmux/index.ts +1 -0
- package/src/tools/tmux/local.ts +277 -0
- package/src/tools/tmux/remote.ts +168 -0
- package/src/tools/tmux/tools.ts +1064 -0
- package/src/tools/tool-output.ts +97 -0
- package/src/tools/types.ts +227 -0
- package/src/tools/video/index.ts +1 -0
- package/src/tools/video/tools.ts +425 -0
- package/src/tools/web/fetch.ts +337 -0
- package/src/tools/web/index.ts +4 -0
- package/src/tools/web/tools.ts +186 -0
- package/src/tools/wiki/index.ts +1 -0
- package/src/tools/wiki/tools.ts +445 -0
- package/src/tts/cache-gc.ts +128 -0
- package/src/tts/prepare-for-tts.ts +114 -0
- package/src/tts/service.ts +332 -0
- package/src/types/events.ts +695 -0
- package/src/types/turn-origin.ts +53 -0
- package/src/version.ts +21 -0
- package/src/videogen/dialects.ts +222 -0
- package/src/videogen/generate.ts +484 -0
- package/src/videogen/jobs.ts +178 -0
- package/src/videogen/runner.ts +125 -0
- package/src/videogen/wake.ts +119 -0
- package/src/voice/realtime/call.ts +948 -0
- package/src/voice/realtime/consult.ts +293 -0
- package/src/voice/realtime/fake-provider.ts +134 -0
- package/src/voice/realtime/manager.ts +384 -0
- package/src/voice/realtime/openai-provider.ts +471 -0
- package/src/voice/realtime/persona.ts +227 -0
- package/src/voice/realtime/session-match.ts +116 -0
- package/src/voice/realtime/types.ts +182 -0
- package/src/wiki/conflict.ts +113 -0
- package/src/wiki/explorer.ts +578 -0
- package/src/wiki/index-builder.ts +172 -0
- package/src/wiki/language.ts +134 -0
- package/src/wiki/log-builder.ts +150 -0
- package/src/wiki/map.ts +258 -0
- package/src/wiki/migration/analyze.ts +304 -0
- package/src/wiki/migration/execute.ts +689 -0
- package/src/wiki/migration/refine.ts +402 -0
- package/src/wiki/migration/store.ts +100 -0
- package/src/wiki/move-page.ts +57 -0
- package/src/wiki/structure-file.ts +192 -0
- package/src/wiki/taxonomy.ts +140 -0
- package/src/wiki/templates.ts +163 -0
- package/src/wiki/types.ts +133 -0
- package/templates/skills/README.md +24 -0
- package/templates/skills/_templates/api-wrapper/SKILL.md +26 -0
- package/templates/skills/_templates/cli-wrapper/BOOTSTRAP.md +32 -0
- package/templates/skills/_templates/cli-wrapper/SKILL.md +24 -0
- package/templates/skills/_templates/default/SKILL.md +25 -0
- package/templates/skills/builder-handover/SKILL.md +96 -0
- package/templates/skills/builder-handover/assets/ORDER.md +12 -0
- package/templates/skills/skill-author/SKILL.md +110 -0
- package/tsconfig.json +22 -0
- package/web/dist/assets/index-BaVv6pB2.js +631 -0
- package/web/dist/assets/index-BaVv6pB2.js.map +1 -0
- package/web/dist/assets/index-V3FV3Z25.css +32 -0
- package/web/dist/favicon.svg +8 -0
- package/web/dist/index.html +20 -0
- package/web/package.json +36 -0
- package/web/tsconfig.json +25 -0
- package/web-mobile/dist/apple-touch-icon.png +0 -0
- package/web-mobile/dist/assets/index-BqKt7IMx.css +1 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js +88 -0
- package/web-mobile/dist/assets/index-X_vRr6cd.js.map +1 -0
- package/web-mobile/dist/favicon.svg +8 -0
- package/web-mobile/dist/icon-192.png +0 -0
- package/web-mobile/dist/icon-512.png +0 -0
- package/web-mobile/dist/index.html +27 -0
- package/web-mobile/dist/manifest.webmanifest +32 -0
- package/web-mobile/dist/service-worker.js +90 -0
- package/web-mobile/package.json +28 -0
- package/web-mobile/tsconfig.json +25 -0
|
@@ -0,0 +1,1014 @@
|
|
|
1
|
+
// codex-cli engine — Codex app-server + dynamic tools.
|
|
2
|
+
//
|
|
3
|
+
// Design: private/codex-app-server-design.md (2026-09-05). Replaces the
|
|
4
|
+
// `codex exec --json` + MCP adapter in one step: Codex 0.153 runs the
|
|
5
|
+
// GPT-5.6 family and GPT-6 as code-mode-only and always defers MCP tools,
|
|
6
|
+
// which left the model guessing somora's tool names. Dynamic tools are
|
|
7
|
+
// first-class for Codex (per-tool deferral, namespaces, direct-only
|
|
8
|
+
// namespaces) — the path OpenClaw takes.
|
|
9
|
+
//
|
|
10
|
+
// Per turn:
|
|
11
|
+
// 1. sync auth into somora's CODEX_HOME, spawn `codex app-server`
|
|
12
|
+
// 2. thread/start (fresh) or thread/resume (stored thread id) with the
|
|
13
|
+
// thread config overlay, developer instructions and the dynamic tool
|
|
14
|
+
// catalog built from this turn's ToolInvoker
|
|
15
|
+
// 3. turn/start with the user text (+ localImage attachments), effort
|
|
16
|
+
// 4. notifications → somora events; item/tool/call → registry invoke
|
|
17
|
+
// 5. turn/completed → assistant_message + turn_end, meta write, SIGTERM
|
|
18
|
+
//
|
|
19
|
+
// Engine name stays 'codex-cli' so provider configs keep working.
|
|
20
|
+
|
|
21
|
+
import { mkdirSync } from 'node:fs';
|
|
22
|
+
import { createHash } from 'node:crypto';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { logger } from '../server/logger.ts';
|
|
25
|
+
import type { NormalizedEvent } from '../types/events.ts';
|
|
26
|
+
import type { ToolDefinition } from '../tools/types.ts';
|
|
27
|
+
import {
|
|
28
|
+
computeReplayDelta,
|
|
29
|
+
getLastSeenTs,
|
|
30
|
+
renderReplayPrefix,
|
|
31
|
+
withLastSeenTs,
|
|
32
|
+
type EngineLastSeen,
|
|
33
|
+
capReplayDelta,
|
|
34
|
+
} from './replay.ts';
|
|
35
|
+
import type { AgentEngine, TurnInput } from './types.ts';
|
|
36
|
+
import { buildCodexAttachments } from '../multimodal/user-content.ts';
|
|
37
|
+
import {
|
|
38
|
+
codexReasoningEffort,
|
|
39
|
+
isReasoningEffortError,
|
|
40
|
+
parseSupportedEfforts,
|
|
41
|
+
pickFallbackEffort,
|
|
42
|
+
} from './thinking-params.ts';
|
|
43
|
+
import { CodexAppServerClient, CodexRpcError } from './codex-app-server-client.ts';
|
|
44
|
+
import { codexAppServerArgv, resolveCodexLaunch } from './codex-bin.ts';
|
|
45
|
+
import { codexChildEnv, somoraCodexHome, syncCodexAuth } from './codex-home.ts';
|
|
46
|
+
import {
|
|
47
|
+
buildCodexToolCatalog,
|
|
48
|
+
codexToolGuidance,
|
|
49
|
+
DEFAULT_CODEX_DIRECT_TOOLS,
|
|
50
|
+
toolResultToCodexResponse,
|
|
51
|
+
type CodexToolCatalog,
|
|
52
|
+
} from './codex-dynamic-tools.ts';
|
|
53
|
+
import { buildCodexThreadConfig } from './codex-thread-config.ts';
|
|
54
|
+
import type { Compaction } from '../compaction/index.ts';
|
|
55
|
+
|
|
56
|
+
const ENGINE = 'codex-cli';
|
|
57
|
+
|
|
58
|
+
/** Tool name shape on somora events — matches the claude-cli MCP shape so
|
|
59
|
+
* the TUI/web formatters (which strip `mcp__somora__`) render both
|
|
60
|
+
* engines identically. */
|
|
61
|
+
const EVENT_TOOL_PREFIX = 'mcp__somora__';
|
|
62
|
+
|
|
63
|
+
interface CodexCliMeta {
|
|
64
|
+
engine?: string;
|
|
65
|
+
/** Codex thread id of this session. */
|
|
66
|
+
codexSessionId?: string;
|
|
67
|
+
/** Model the thread last ran under. A switch is passed to
|
|
68
|
+
* thread/resume as `model` (no rethread needed with the app-server)
|
|
69
|
+
* and surfaced as an engine_meta marker. */
|
|
70
|
+
codexRecordedModel?: string;
|
|
71
|
+
/** Fingerprint of the dynamic tool catalog the thread was started
|
|
72
|
+
* with. Codex keeps a thread's tools for its lifetime — `thread/resume`
|
|
73
|
+
* and `thread/fork` both ignore a new `dynamicTools` list (verified
|
|
74
|
+
* 2026-09-05) — so a changed catalog (Abilities toggle in /web, a new
|
|
75
|
+
* hub server, a dream_review loop, a somora update that changed a
|
|
76
|
+
* schema) means a fresh thread with the session history replayed.
|
|
77
|
+
* Same trigger OpenClaw uses ("dynamic-tools-mismatch"). */
|
|
78
|
+
codexToolsFingerprint?: string;
|
|
79
|
+
/** Obsolete (MCP-era rename tracking); tolerated on old sessions. */
|
|
80
|
+
mcpServerName?: string;
|
|
81
|
+
engineLastSeen?: EngineLastSeen;
|
|
82
|
+
compactions?: Compaction[];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** thread/resume errors that mean "this thread is gone" → fresh thread. */
|
|
86
|
+
const CODEX_STALE_THREAD_RE = /no rollout found|not found|does not exist|failed to load|no such thread/i;
|
|
87
|
+
|
|
88
|
+
interface UsageAcc {
|
|
89
|
+
tokens_in: number;
|
|
90
|
+
tokens_in_cached: number;
|
|
91
|
+
context_tokens: number;
|
|
92
|
+
/** The window codex reports for this thread (`modelContextWindow`). */
|
|
93
|
+
context_window: number;
|
|
94
|
+
tokens_out: number;
|
|
95
|
+
tokens_out_reasoning: number;
|
|
96
|
+
seen: boolean;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Names, deferral and input schemas — what decides whether a call can
|
|
100
|
+
* be made. Descriptions are left out so wording edits do not rethread. */
|
|
101
|
+
function catalogFingerprint(catalog: CodexToolCatalog): string {
|
|
102
|
+
const h = createHash('sha1');
|
|
103
|
+
for (const spec of catalog.specs) {
|
|
104
|
+
const tools = spec.type === 'namespace' ? spec.tools : [spec];
|
|
105
|
+
for (const t of tools) {
|
|
106
|
+
h.update(`${spec.name}.${t.name}|${t.deferLoading ? 'd' : 'i'}|${JSON.stringify(t.inputSchema)}\n`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return h.digest('hex').slice(0, 16);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Config bridged through process.env by applyCodexCliEnv (config.yaml
|
|
113
|
+
* codexCli.*), so the engine stays free of the Config type. */
|
|
114
|
+
function codexDirectTools(): readonly string[] {
|
|
115
|
+
const raw = process.env.SOMORA_CODEX_DIRECT_TOOLS;
|
|
116
|
+
if (!raw) return DEFAULT_CODEX_DIRECT_TOOLS;
|
|
117
|
+
try {
|
|
118
|
+
const parsed = JSON.parse(raw) as unknown;
|
|
119
|
+
if (Array.isArray(parsed) && parsed.every((x) => typeof x === 'string')) return parsed as string[];
|
|
120
|
+
} catch {
|
|
121
|
+
/* fall through */
|
|
122
|
+
}
|
|
123
|
+
return DEFAULT_CODEX_DIRECT_TOOLS;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function codexToolTimeoutMs(): number {
|
|
127
|
+
const raw = Number(process.env.SOMORA_CODEX_TOOL_TIMEOUT_SEC);
|
|
128
|
+
return Number.isFinite(raw) && raw > 0 ? raw * 1000 : 1800_000;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Ordered text segments keyed by Codex item id (agentMessage /
|
|
132
|
+
* reasoning items stream deltas, then complete with the full text). */
|
|
133
|
+
class SegmentBuffer {
|
|
134
|
+
private readonly order: string[] = [];
|
|
135
|
+
private readonly text = new Map<string, string>();
|
|
136
|
+
|
|
137
|
+
append(itemId: string, delta: string): void {
|
|
138
|
+
if (!this.text.has(itemId)) {
|
|
139
|
+
this.order.push(itemId);
|
|
140
|
+
this.text.set(itemId, '');
|
|
141
|
+
}
|
|
142
|
+
this.text.set(itemId, `${this.text.get(itemId) ?? ''}${delta}`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
set(itemId: string, full: string): void {
|
|
146
|
+
if (!this.text.has(itemId)) this.order.push(itemId);
|
|
147
|
+
this.text.set(itemId, full);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
has(itemId: string): boolean {
|
|
151
|
+
return this.text.has(itemId);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
get cumulative(): string {
|
|
155
|
+
return this.order
|
|
156
|
+
.map((id) => (this.text.get(id) ?? '').trim())
|
|
157
|
+
.filter((t) => t.length > 0)
|
|
158
|
+
.join('\n\n');
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Push-based event queue consumed by the async generator. */
|
|
163
|
+
class EventQueue {
|
|
164
|
+
private readonly items: NormalizedEvent[] = [];
|
|
165
|
+
private wake: (() => void) | null = null;
|
|
166
|
+
private done = false;
|
|
167
|
+
|
|
168
|
+
push(ev: NormalizedEvent): void {
|
|
169
|
+
this.items.push(ev);
|
|
170
|
+
this.wake?.();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
finish(): void {
|
|
174
|
+
this.done = true;
|
|
175
|
+
this.wake?.();
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async *drain(): AsyncGenerator<NormalizedEvent> {
|
|
179
|
+
while (true) {
|
|
180
|
+
if (this.items.length > 0) {
|
|
181
|
+
yield this.items.shift()!;
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (this.done) return;
|
|
185
|
+
await new Promise<void>((resolve) => {
|
|
186
|
+
this.wake = () => {
|
|
187
|
+
this.wake = null;
|
|
188
|
+
resolve();
|
|
189
|
+
};
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* A codex `error` notification. The text sits in `error.message`, not
|
|
197
|
+
* in a top-level `message` — reading the latter stringified the whole
|
|
198
|
+
* object into the chat row and into the reasoning-effort check.
|
|
199
|
+
* Shape seen live (2026-09): `{ error: { message, codexErrorInfo,
|
|
200
|
+
* additionalDetails }, willRetry, threadId, turnId }`.
|
|
201
|
+
* Exported for tests.
|
|
202
|
+
*/
|
|
203
|
+
export function readCodexError(p: Record<string, unknown>): { message: string; willRetry: boolean } {
|
|
204
|
+
const err = p.error as { message?: unknown; additionalDetails?: unknown } | undefined;
|
|
205
|
+
const base =
|
|
206
|
+
typeof err?.message === 'string'
|
|
207
|
+
? err.message
|
|
208
|
+
: typeof p.message === 'string'
|
|
209
|
+
? p.message
|
|
210
|
+
: JSON.stringify(p).slice(0, 500);
|
|
211
|
+
const details = typeof err?.additionalDetails === 'string' && err.additionalDetails ? ` — ${err.additionalDetails}` : '';
|
|
212
|
+
return { message: `${base}${details}`.slice(0, 500), willRetry: p.willRetry === true };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export const codexCliEngine: AgentEngine = {
|
|
216
|
+
name: ENGINE,
|
|
217
|
+
|
|
218
|
+
async *runTurn(input: TurnInput): AsyncIterable<NormalizedEvent> {
|
|
219
|
+
const {
|
|
220
|
+
agent,
|
|
221
|
+
session,
|
|
222
|
+
systemPrompt,
|
|
223
|
+
ephemeralContext,
|
|
224
|
+
projectContext,
|
|
225
|
+
userMessage,
|
|
226
|
+
history,
|
|
227
|
+
metaStore,
|
|
228
|
+
resolvedModel,
|
|
229
|
+
thinking,
|
|
230
|
+
fromAgent,
|
|
231
|
+
fromSession,
|
|
232
|
+
signal,
|
|
233
|
+
} = input;
|
|
234
|
+
if (resolvedModel.provider.engine !== ENGINE) {
|
|
235
|
+
throw new Error(
|
|
236
|
+
`codex-cli engine called with non-matching provider engine: ${resolvedModel.provider.engine}`,
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
const logCtx = { engine: ENGINE, agent, session };
|
|
240
|
+
const ts = () => Date.now();
|
|
241
|
+
const turnId = `t-${Date.now()}`;
|
|
242
|
+
const meta = (await metaStore.get(agent, session)) as CodexCliMeta;
|
|
243
|
+
|
|
244
|
+
let resumeId = meta.codexSessionId;
|
|
245
|
+
const modelSwitched =
|
|
246
|
+
resumeId && meta.codexRecordedModel && meta.codexRecordedModel !== resolvedModel.modelId
|
|
247
|
+
? { from: meta.codexRecordedModel, to: resolvedModel.modelId }
|
|
248
|
+
: undefined;
|
|
249
|
+
|
|
250
|
+
yield { kind: 'turn_start', ts: ts(), engine: ENGINE, turnId };
|
|
251
|
+
if (modelSwitched) {
|
|
252
|
+
logger.info({ msg: 'engine.model_switch', ...logCtx, ...modelSwitched, threadId: resumeId });
|
|
253
|
+
yield {
|
|
254
|
+
kind: 'engine_meta',
|
|
255
|
+
ts: ts(),
|
|
256
|
+
engine: ENGINE,
|
|
257
|
+
itemType: 'model_switch',
|
|
258
|
+
payload: {
|
|
259
|
+
from: modelSwitched.from,
|
|
260
|
+
to: modelSwitched.to,
|
|
261
|
+
text: `Codex thread continues under ${modelSwitched.to} (was ${modelSwitched.from}).`,
|
|
262
|
+
},
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// ---- tool catalog + developer instructions -------------------------
|
|
267
|
+
const toolDefs: readonly ToolDefinition[] = input.tools?.list() ?? [];
|
|
268
|
+
const catalog: CodexToolCatalog = buildCodexToolCatalog(toolDefs, codexDirectTools());
|
|
269
|
+
if (catalog.skipped.length > 0) {
|
|
270
|
+
logger.warn({ msg: 'engine.codex_tools_skipped', ...logCtx, skipped: catalog.skipped });
|
|
271
|
+
}
|
|
272
|
+
const developerInstructions = `${systemPrompt}\n\n---\n\n${codexToolGuidance(catalog)}`;
|
|
273
|
+
const toolsFingerprint = catalogFingerprint(catalog);
|
|
274
|
+
if (resumeId && meta.codexToolsFingerprint !== toolsFingerprint) {
|
|
275
|
+
logger.info({
|
|
276
|
+
msg: 'engine.tools_changed_rethread',
|
|
277
|
+
...logCtx,
|
|
278
|
+
droppedThreadId: resumeId,
|
|
279
|
+
previous: meta.codexToolsFingerprint ?? null,
|
|
280
|
+
next: toolsFingerprint,
|
|
281
|
+
directTools: catalog.directNames.length,
|
|
282
|
+
deferredTools: catalog.deferredNames.length,
|
|
283
|
+
});
|
|
284
|
+
yield {
|
|
285
|
+
kind: 'engine_meta',
|
|
286
|
+
ts: ts(),
|
|
287
|
+
engine: ENGINE,
|
|
288
|
+
itemType: 'tools_changed',
|
|
289
|
+
payload: {
|
|
290
|
+
from: resumeId,
|
|
291
|
+
text: 'The tool set available to this agent changed — Codex thread restarted with the session history carried over.',
|
|
292
|
+
},
|
|
293
|
+
};
|
|
294
|
+
resumeId = undefined;
|
|
295
|
+
}
|
|
296
|
+
const threadConfig = buildCodexThreadConfig({
|
|
297
|
+
shellEnvironmentPolicy: process.env.SOMORA_CODEX_SHELL_ENV_POLICY,
|
|
298
|
+
directOnlyNamespaces: catalog.directOnlyNamespaces,
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
// ---- turn input -----------------------------------------------------
|
|
302
|
+
const { imagePaths, promptPrefix: attachmentPrefix } = await buildCodexAttachments(
|
|
303
|
+
input.attachments ?? [],
|
|
304
|
+
);
|
|
305
|
+
// The A2A header travels in ephemeralContext (src/server/turn-framing.ts).
|
|
306
|
+
const taggedUserMessage = userMessage;
|
|
307
|
+
const ephemeralBlock = ephemeralContext ? `${ephemeralContext}\n\n---\n\n` : '';
|
|
308
|
+
const buildText = (resumed: boolean, replayPrefix: string): string => {
|
|
309
|
+
const projectBlock = resumed && projectContext ? `${projectContext}\n\n---\n\n` : '';
|
|
310
|
+
return `${attachmentPrefix}${ephemeralBlock}${projectBlock}${replayPrefix}${taggedUserMessage}`;
|
|
311
|
+
};
|
|
312
|
+
let effort = codexReasoningEffort(thinking, resolvedModel.model);
|
|
313
|
+
const summary = input.captureThinking === false ? 'none' : 'auto';
|
|
314
|
+
// One retry when the backend rejects the effort word (GPT-6 Astra
|
|
315
|
+
// has no `minimal`, which is what somora's `off` maps to — 2026-09-06
|
|
316
|
+
// report). The rejection arrives as an `error` notification followed
|
|
317
|
+
// by `turn/completed` with status failed; the retry re-issues
|
|
318
|
+
// turn/start on the same thread with the nearest value the backend
|
|
319
|
+
// itself listed. Mirrors withReasoningRetry() on the openai path.
|
|
320
|
+
let effortRetryPending: string | null = null;
|
|
321
|
+
let effortRetried = false;
|
|
322
|
+
let startTurn: ((eff: string | null) => Promise<void>) | undefined;
|
|
323
|
+
|
|
324
|
+
// ---- process ----------------------------------------------------------
|
|
325
|
+
const auth = syncCodexAuth();
|
|
326
|
+
if (!auth.somoraExists) {
|
|
327
|
+
logger.warn({
|
|
328
|
+
msg: 'engine.codex_auth_missing',
|
|
329
|
+
...logCtx,
|
|
330
|
+
userAuthPath: auth.userAuthPath,
|
|
331
|
+
hint: 'run `somora codex login` (or `codex login`) — the turn will fail on authentication',
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
const workspace = join(somoraCodexHome(), 'workspace');
|
|
335
|
+
mkdirSync(workspace, { recursive: true });
|
|
336
|
+
const launch = resolveCodexLaunch();
|
|
337
|
+
|
|
338
|
+
const queue = new EventQueue();
|
|
339
|
+
const assistant = new SegmentBuffer();
|
|
340
|
+
const reasoning = new SegmentBuffer();
|
|
341
|
+
const usage: UsageAcc = {
|
|
342
|
+
tokens_in: 0,
|
|
343
|
+
tokens_in_cached: 0,
|
|
344
|
+
context_tokens: 0,
|
|
345
|
+
context_window: 0,
|
|
346
|
+
tokens_out: 0,
|
|
347
|
+
tokens_out_reasoning: 0,
|
|
348
|
+
seen: false,
|
|
349
|
+
};
|
|
350
|
+
const streamErrors: string[] = [];
|
|
351
|
+
let reconnectNoted = false;
|
|
352
|
+
let threadId: string | undefined = resumeId;
|
|
353
|
+
let activeTurnId: string | undefined;
|
|
354
|
+
let turnOutcome: { status: string; error?: string } | undefined;
|
|
355
|
+
let pendingToolCalls = 0;
|
|
356
|
+
let abortFired = false;
|
|
357
|
+
let watchdogFired = false;
|
|
358
|
+
let finished = false;
|
|
359
|
+
let client: CodexAppServerClient | undefined;
|
|
360
|
+
|
|
361
|
+
const IDLE_TIMEOUT_MS = input.idleTimeoutMs ?? 300_000;
|
|
362
|
+
const TOOL_IDLE_TIMEOUT_MS = Math.max(input.toolIdleTimeoutMs ?? 0, IDLE_TIMEOUT_MS);
|
|
363
|
+
let idleTimer: ReturnType<typeof setTimeout> | undefined;
|
|
364
|
+
let steerPoll: ReturnType<typeof setInterval> | undefined;
|
|
365
|
+
const finish = (): void => {
|
|
366
|
+
if (finished) return;
|
|
367
|
+
finished = true;
|
|
368
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
369
|
+
if (steerPoll) clearInterval(steerPoll);
|
|
370
|
+
queue.finish();
|
|
371
|
+
};
|
|
372
|
+
// Steering: the app-server takes input for a running turn through
|
|
373
|
+
// `turn/steer` (expectedTurnId guards against a turn that already
|
|
374
|
+
// ended). What arrives in the session's letterbox is forwarded as
|
|
375
|
+
// text input; the record for the session file is queued once the
|
|
376
|
+
// request was accepted, and put back into the letterbox when it was
|
|
377
|
+
// refused so nothing is lost.
|
|
378
|
+
if (input.steer) {
|
|
379
|
+
const steer = input.steer;
|
|
380
|
+
steerPoll = setInterval(() => {
|
|
381
|
+
if (finished || !client || !threadId || !activeTurnId) return;
|
|
382
|
+
const msgs = steer.drain();
|
|
383
|
+
if (msgs.length === 0) return;
|
|
384
|
+
const c = client;
|
|
385
|
+
const params = {
|
|
386
|
+
threadId,
|
|
387
|
+
expectedTurnId: activeTurnId,
|
|
388
|
+
input: msgs.map((m) => ({ type: 'text' as const, text: steer.frame(m) })),
|
|
389
|
+
};
|
|
390
|
+
c.request('turn/steer', params, { timeoutMs: 5_000 })
|
|
391
|
+
.then(() => {
|
|
392
|
+
queue.push({ kind: 'steer_applied', ts: ts(), engine: ENGINE, messages: msgs });
|
|
393
|
+
})
|
|
394
|
+
.catch((err: unknown) => {
|
|
395
|
+
logger.warn({ msg: 'engine.steer_refused', ...logCtx, err: String((err as Error)?.message ?? err) });
|
|
396
|
+
steer.requeue(msgs);
|
|
397
|
+
});
|
|
398
|
+
}, 300);
|
|
399
|
+
steerPoll.unref?.();
|
|
400
|
+
}
|
|
401
|
+
const armIdleTimer = (): void => {
|
|
402
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
403
|
+
const threshold = pendingToolCalls > 0 ? TOOL_IDLE_TIMEOUT_MS : IDLE_TIMEOUT_MS;
|
|
404
|
+
idleTimer = setTimeout(() => {
|
|
405
|
+
if (finished) return;
|
|
406
|
+
watchdogFired = true;
|
|
407
|
+
logger.error({
|
|
408
|
+
msg: 'engine.watchdog_idle_timeout',
|
|
409
|
+
...logCtx,
|
|
410
|
+
idleMs: threshold,
|
|
411
|
+
pendingToolCalls,
|
|
412
|
+
hint: 'no app-server notification received — process wedged; SIGTERM',
|
|
413
|
+
});
|
|
414
|
+
client?.close();
|
|
415
|
+
finish();
|
|
416
|
+
}, threshold);
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
const onAbort = (): void => {
|
|
420
|
+
if (abortFired) return;
|
|
421
|
+
abortFired = true;
|
|
422
|
+
logger.info({ msg: 'engine.abort_requested', ...logCtx, threadId, turnId: activeTurnId });
|
|
423
|
+
if (client && threadId && activeTurnId) {
|
|
424
|
+
client
|
|
425
|
+
.request('turn/interrupt', { threadId, turnId: activeTurnId }, { timeoutMs: 2_000 })
|
|
426
|
+
.catch(() => {});
|
|
427
|
+
setTimeout(() => {
|
|
428
|
+
if (!finished) {
|
|
429
|
+
client?.close();
|
|
430
|
+
finish();
|
|
431
|
+
}
|
|
432
|
+
}, 2_500).unref();
|
|
433
|
+
} else {
|
|
434
|
+
client?.close();
|
|
435
|
+
finish();
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
if (signal) {
|
|
439
|
+
if (signal.aborted) onAbort();
|
|
440
|
+
else signal.addEventListener('abort', onAbort, { once: true });
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// ---- notifications ----------------------------------------------------
|
|
444
|
+
const onNotification = (method: string, rawParams: unknown): void => {
|
|
445
|
+
if (finished) return;
|
|
446
|
+
armIdleTimer();
|
|
447
|
+
const p = (rawParams ?? {}) as Record<string, unknown>;
|
|
448
|
+
switch (method) {
|
|
449
|
+
case 'thread/started': {
|
|
450
|
+
const t = p.thread as { id?: unknown } | undefined;
|
|
451
|
+
if (typeof t?.id === 'string') threadId = t.id;
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
case 'turn/started': {
|
|
455
|
+
const t = p.turn as { id?: unknown } | undefined;
|
|
456
|
+
if (typeof t?.id === 'string') activeTurnId = t.id;
|
|
457
|
+
break;
|
|
458
|
+
}
|
|
459
|
+
case 'item/agentMessage/delta': {
|
|
460
|
+
if (typeof p.itemId === 'string' && typeof p.delta === 'string') {
|
|
461
|
+
assistant.append(p.itemId, p.delta);
|
|
462
|
+
queue.push({ kind: 'assistant_delta', ts: ts(), engine: ENGINE, text: assistant.cumulative });
|
|
463
|
+
}
|
|
464
|
+
break;
|
|
465
|
+
}
|
|
466
|
+
case 'item/reasoning/summaryPartAdded': {
|
|
467
|
+
if (typeof p.itemId === 'string' && reasoning.has(p.itemId)) reasoning.append(p.itemId, '\n\n');
|
|
468
|
+
break;
|
|
469
|
+
}
|
|
470
|
+
case 'item/reasoning/summaryTextDelta': {
|
|
471
|
+
if (typeof p.itemId === 'string' && typeof p.delta === 'string') {
|
|
472
|
+
reasoning.append(p.itemId, p.delta);
|
|
473
|
+
queue.push({ kind: 'thinking_delta', ts: ts(), engine: ENGINE, text: reasoning.cumulative });
|
|
474
|
+
}
|
|
475
|
+
break;
|
|
476
|
+
}
|
|
477
|
+
case 'item/started':
|
|
478
|
+
case 'item/completed': {
|
|
479
|
+
const item = p.item as Record<string, unknown> | undefined;
|
|
480
|
+
if (!item || typeof item !== 'object') break;
|
|
481
|
+
const type = typeof item.type === 'string' ? item.type : 'unknown';
|
|
482
|
+
const itemId = typeof item.id === 'string' ? item.id : `item-${Date.now()}`;
|
|
483
|
+
if (method === 'item/started') {
|
|
484
|
+
if (type === 'agentMessage') assistant.set(itemId, '');
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
if (type === 'agentMessage') {
|
|
488
|
+
if (typeof item.text === 'string') assistant.set(itemId, item.text);
|
|
489
|
+
} else if (type === 'reasoning') {
|
|
490
|
+
const parts = Array.isArray(item.summary)
|
|
491
|
+
? item.summary.filter((s): s is string => typeof s === 'string')
|
|
492
|
+
: [];
|
|
493
|
+
if (parts.length > 0) reasoning.set(itemId, parts.join('\n\n'));
|
|
494
|
+
} else if (type === 'userMessage' || type === 'dynamicToolCall') {
|
|
495
|
+
// dynamicToolCall is surfaced from the item/tool/call request.
|
|
496
|
+
} else {
|
|
497
|
+
// mcpToolCall / commandExecution / fileChange / collab… should not
|
|
498
|
+
// happen with the lock-down; persist as breadcrumb.
|
|
499
|
+
logger.info({ msg: 'engine.meta_item', ...logCtx, itemType: type });
|
|
500
|
+
queue.push({ kind: 'engine_meta', ts: ts(), engine: ENGINE, itemType: type, payload: item });
|
|
501
|
+
}
|
|
502
|
+
break;
|
|
503
|
+
}
|
|
504
|
+
case 'thread/tokenUsage/updated': {
|
|
505
|
+
const tu = p.tokenUsage as
|
|
506
|
+
| { last?: Record<string, unknown>; modelContextWindow?: unknown }
|
|
507
|
+
| undefined;
|
|
508
|
+
const last = tu?.last;
|
|
509
|
+
if (last) {
|
|
510
|
+
const n = (k: string) => (typeof last[k] === 'number' ? (last[k] as number) : 0);
|
|
511
|
+
usage.tokens_in += n('inputTokens');
|
|
512
|
+
usage.tokens_in_cached += n('cachedInputTokens');
|
|
513
|
+
// Occupancy: this request's prompt, replaced not summed.
|
|
514
|
+
// `tokens_in` above is what the turn cost across all of its
|
|
515
|
+
// requests and is a multiple of the window on a long turn.
|
|
516
|
+
//
|
|
517
|
+
// `cachedInputTokens` is a SUBSET of `inputTokens`, not a
|
|
518
|
+
// second helping — measured against the app-server on
|
|
519
|
+
// 2026-09-11: inputTokens 16,235, cachedInputTokens 12,160,
|
|
520
|
+
// totalTokens 16,240 with 5 output tokens. Adding them
|
|
521
|
+
// counted the cached part twice, which is why a long codex
|
|
522
|
+
// chat climbed past 100 % and stayed red however often the
|
|
523
|
+
// CLI compacted: 425,581 shown against a 272,000 window on a
|
|
524
|
+
// conversation that never exceeded its real 258,400.
|
|
525
|
+
// (Anthropic counts the other way round — there input_tokens
|
|
526
|
+
// EXCLUDES the cached part, which is why claude-cli sums.)
|
|
527
|
+
usage.context_tokens = n('inputTokens');
|
|
528
|
+
usage.tokens_out += n('outputTokens');
|
|
529
|
+
usage.tokens_out_reasoning += n('reasoningOutputTokens');
|
|
530
|
+
usage.seen = true;
|
|
531
|
+
}
|
|
532
|
+
// The window codex itself enforces for this thread. It is
|
|
533
|
+
// server-delivered per model and account, so it beats the
|
|
534
|
+
// hand-configured session cap in config.yaml.
|
|
535
|
+
if (typeof tu?.modelContextWindow === 'number' && tu.modelContextWindow > 0) {
|
|
536
|
+
usage.context_window = tu.modelContextWindow;
|
|
537
|
+
}
|
|
538
|
+
break;
|
|
539
|
+
}
|
|
540
|
+
case 'error': {
|
|
541
|
+
const { message, willRetry } = readCodexError(p);
|
|
542
|
+
// `willRetry: true` is codex telling us it is handling it —
|
|
543
|
+
// a dropped stream it reconnects (up to 5 tries, then its own
|
|
544
|
+
// fallback to HTTPS). The turn goes on. Each of these used to
|
|
545
|
+
// land in the chat as a red "codex error" row and in
|
|
546
|
+
// streamErrors: four rows per turn on image-heavy threads,
|
|
547
|
+
// for turns that then completed (report 2026-09-14). One
|
|
548
|
+
// neutral row per turn instead; the tries stay in the log.
|
|
549
|
+
if (willRetry) {
|
|
550
|
+
logger.info({ msg: 'engine.codex_retrying', ...logCtx, message: message.slice(0, 300) });
|
|
551
|
+
if (!reconnectNoted) {
|
|
552
|
+
reconnectNoted = true;
|
|
553
|
+
queue.push({
|
|
554
|
+
kind: 'engine_meta',
|
|
555
|
+
ts: ts(),
|
|
556
|
+
engine: ENGINE,
|
|
557
|
+
itemType: 'reconnecting',
|
|
558
|
+
payload: {
|
|
559
|
+
text: 'connection to the model dropped — codex is reconnecting by itself; the turn continues',
|
|
560
|
+
detail: message,
|
|
561
|
+
},
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
break;
|
|
565
|
+
}
|
|
566
|
+
if (!effortRetried && effort && isReasoningEffortError(message)) {
|
|
567
|
+
const supported = parseSupportedEfforts(message);
|
|
568
|
+
const fallback = supported ? pickFallbackEffort(effort, supported) : null;
|
|
569
|
+
if (fallback && fallback !== effort) {
|
|
570
|
+
effortRetried = true;
|
|
571
|
+
effortRetryPending = fallback;
|
|
572
|
+
logger.warn({
|
|
573
|
+
msg: 'engine.reasoning_effort_rejected',
|
|
574
|
+
...logCtx,
|
|
575
|
+
model: resolvedModel.modelId,
|
|
576
|
+
requested: effort,
|
|
577
|
+
supported,
|
|
578
|
+
fallback,
|
|
579
|
+
backend: message.slice(0, 300),
|
|
580
|
+
});
|
|
581
|
+
queue.push({
|
|
582
|
+
kind: 'engine_meta',
|
|
583
|
+
ts: ts(),
|
|
584
|
+
engine: ENGINE,
|
|
585
|
+
itemType: 'reasoning_effort_adjusted',
|
|
586
|
+
payload: {
|
|
587
|
+
text:
|
|
588
|
+
`${resolvedModel.modelId} rejected reasoning effort '${effort}' — ` +
|
|
589
|
+
`retrying with '${fallback}'. Map the level in the model's ` +
|
|
590
|
+
'`reasoning.levels` config to make this permanent.',
|
|
591
|
+
requested: effort,
|
|
592
|
+
sent: fallback,
|
|
593
|
+
backend: message.slice(0, 300),
|
|
594
|
+
},
|
|
595
|
+
});
|
|
596
|
+
break;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
streamErrors.push(message);
|
|
600
|
+
logger.warn({ msg: 'engine.codex_error_item', ...logCtx, message: message.slice(0, 500) });
|
|
601
|
+
queue.push({
|
|
602
|
+
kind: 'engine_meta',
|
|
603
|
+
ts: ts(),
|
|
604
|
+
engine: ENGINE,
|
|
605
|
+
itemType: 'error',
|
|
606
|
+
payload: { message },
|
|
607
|
+
});
|
|
608
|
+
break;
|
|
609
|
+
}
|
|
610
|
+
case 'warning':
|
|
611
|
+
case 'configWarning':
|
|
612
|
+
case 'deprecationNotice': {
|
|
613
|
+
const text = String(p.message ?? p.summary ?? '');
|
|
614
|
+
// The end of the reconnect story above: codex gave up on the
|
|
615
|
+
// WebSocket and carries on over HTTPS. Until now only the log
|
|
616
|
+
// knew — the chat showed errors and then, unexplained, an
|
|
617
|
+
// answer.
|
|
618
|
+
if (/falling back from websockets? to https/i.test(text)) {
|
|
619
|
+
logger.warn({ msg: 'engine.codex_transport_fallback', ...logCtx, message: text.slice(0, 400) });
|
|
620
|
+
queue.push({
|
|
621
|
+
kind: 'engine_meta',
|
|
622
|
+
ts: ts(),
|
|
623
|
+
engine: ENGINE,
|
|
624
|
+
itemType: 'transport_fallback',
|
|
625
|
+
payload: {
|
|
626
|
+
text: 'codex switched from WebSocket to HTTPS for this turn — slower, nothing lost',
|
|
627
|
+
detail: text.slice(0, 400),
|
|
628
|
+
},
|
|
629
|
+
});
|
|
630
|
+
break;
|
|
631
|
+
}
|
|
632
|
+
// Sandbox prerequisites are irrelevant: threads run with
|
|
633
|
+
// danger-full-access (somora is the sandbox). Keep the log clean.
|
|
634
|
+
if (/bubblewrap|sandbox prerequisites/i.test(text)) {
|
|
635
|
+
logger.debug({ msg: 'engine.codex_warning', ...logCtx, method, message: text.slice(0, 200) });
|
|
636
|
+
break;
|
|
637
|
+
}
|
|
638
|
+
logger.warn({
|
|
639
|
+
msg: 'engine.codex_warning',
|
|
640
|
+
...logCtx,
|
|
641
|
+
method,
|
|
642
|
+
message: String(p.message ?? p.summary ?? '').slice(0, 400),
|
|
643
|
+
});
|
|
644
|
+
break;
|
|
645
|
+
}
|
|
646
|
+
case 'thread/compacted': {
|
|
647
|
+
// codex compacts its own thread and says so. Until now the
|
|
648
|
+
// only sign was the occupancy number dropping on the next
|
|
649
|
+
// turn, which is exactly the "what just happened?" the
|
|
650
|
+
// 2026-09-11 report was about. Same row the openai-compatible
|
|
651
|
+
// engine writes when somora compacts, so both read alike.
|
|
652
|
+
queue.push({
|
|
653
|
+
kind: 'engine_meta',
|
|
654
|
+
ts: ts(),
|
|
655
|
+
engine: ENGINE,
|
|
656
|
+
itemType: 'context_compacted',
|
|
657
|
+
payload: {
|
|
658
|
+
text: 'codex compacted this thread itself — the context percentage drops accordingly',
|
|
659
|
+
reason: 'engine_side',
|
|
660
|
+
},
|
|
661
|
+
});
|
|
662
|
+
logger.info({ msg: 'engine.codex_compacted', ...logCtx });
|
|
663
|
+
break;
|
|
664
|
+
}
|
|
665
|
+
case 'turn/completed': {
|
|
666
|
+
if (effortRetryPending && startTurn) {
|
|
667
|
+
// The failed turn produced nothing; start over on the same
|
|
668
|
+
// thread with the adjusted effort. A failure of the retry
|
|
669
|
+
// itself ends the stream through the normal error path.
|
|
670
|
+
const next = effortRetryPending;
|
|
671
|
+
effortRetryPending = null;
|
|
672
|
+
effort = next;
|
|
673
|
+
logger.info({ msg: 'engine.reasoning_effort_retry', ...logCtx, effort: next });
|
|
674
|
+
void startTurn(next).catch((err: unknown) => {
|
|
675
|
+
if (finished) return;
|
|
676
|
+
streamErrors.push((err as Error).message);
|
|
677
|
+
logger.error({ msg: 'engine.fail', ...logCtx, err: (err as Error).message });
|
|
678
|
+
finish();
|
|
679
|
+
});
|
|
680
|
+
break;
|
|
681
|
+
}
|
|
682
|
+
const turn = p.turn as { status?: unknown; error?: { message?: unknown } | null } | undefined;
|
|
683
|
+
turnOutcome = {
|
|
684
|
+
status: typeof turn?.status === 'string' ? turn.status : 'unknown',
|
|
685
|
+
...(turn?.error && typeof turn.error.message === 'string' ? { error: turn.error.message } : {}),
|
|
686
|
+
};
|
|
687
|
+
finish();
|
|
688
|
+
break;
|
|
689
|
+
}
|
|
690
|
+
default:
|
|
691
|
+
logger.debug({ msg: 'engine.codex_notification', ...logCtx, method });
|
|
692
|
+
}
|
|
693
|
+
};
|
|
694
|
+
|
|
695
|
+
// ---- server → client requests (tools, approvals) ----------------------
|
|
696
|
+
const toolTimeoutMs = codexToolTimeoutMs();
|
|
697
|
+
const onServerRequest = async (req: { method: string; params: unknown }): Promise<unknown> => {
|
|
698
|
+
if (req.method === 'item/tool/call') {
|
|
699
|
+
const params = (req.params ?? {}) as {
|
|
700
|
+
callId?: unknown;
|
|
701
|
+
namespace?: unknown;
|
|
702
|
+
tool?: unknown;
|
|
703
|
+
arguments?: unknown;
|
|
704
|
+
};
|
|
705
|
+
const callId = typeof params.callId === 'string' ? params.callId : `call-${Date.now()}`;
|
|
706
|
+
const nsRaw = typeof params.namespace === 'string' ? params.namespace : null;
|
|
707
|
+
const toolRaw = typeof params.tool === 'string' ? params.tool : '';
|
|
708
|
+
const registryName = catalog.resolve(nsRaw, toolRaw);
|
|
709
|
+
const args = params.arguments ?? {};
|
|
710
|
+
queue.push({
|
|
711
|
+
kind: 'tool_call',
|
|
712
|
+
ts: ts(),
|
|
713
|
+
engine: ENGINE,
|
|
714
|
+
callId,
|
|
715
|
+
tool: `${EVENT_TOOL_PREFIX}${registryName ?? toolRaw}`,
|
|
716
|
+
input: args,
|
|
717
|
+
});
|
|
718
|
+
if (!registryName || !input.tools) {
|
|
719
|
+
const error = `unknown tool '${nsRaw ? `${nsRaw}.` : ''}${toolRaw}'`;
|
|
720
|
+
queue.push({ kind: 'tool_result', ts: ts(), engine: ENGINE, callId, output: null, error });
|
|
721
|
+
return toolResultToCodexResponse({ ok: false, error });
|
|
722
|
+
}
|
|
723
|
+
pendingToolCalls++;
|
|
724
|
+
armIdleTimer();
|
|
725
|
+
const started = Date.now();
|
|
726
|
+
let result;
|
|
727
|
+
try {
|
|
728
|
+
result = await Promise.race([
|
|
729
|
+
input.tools.invoke(registryName, args),
|
|
730
|
+
new Promise<never>((_, reject) =>
|
|
731
|
+
setTimeout(
|
|
732
|
+
() => reject(new Error(`tool '${registryName}' timed out after ${toolTimeoutMs / 1000}s`)),
|
|
733
|
+
toolTimeoutMs,
|
|
734
|
+
).unref(),
|
|
735
|
+
),
|
|
736
|
+
]);
|
|
737
|
+
} catch (err) {
|
|
738
|
+
result = { ok: false, error: (err as Error).message };
|
|
739
|
+
} finally {
|
|
740
|
+
if (pendingToolCalls > 0) pendingToolCalls--;
|
|
741
|
+
armIdleTimer();
|
|
742
|
+
}
|
|
743
|
+
logger.info({
|
|
744
|
+
msg: 'engine.tool_call',
|
|
745
|
+
...logCtx,
|
|
746
|
+
tool: registryName,
|
|
747
|
+
ok: result.ok,
|
|
748
|
+
ms: Date.now() - started,
|
|
749
|
+
});
|
|
750
|
+
queue.push({
|
|
751
|
+
kind: 'tool_result',
|
|
752
|
+
ts: ts(),
|
|
753
|
+
engine: ENGINE,
|
|
754
|
+
callId,
|
|
755
|
+
output: result.ok ? (result.data ?? null) : null,
|
|
756
|
+
...(result.ok ? {} : { error: result.error ?? 'tool failed' }),
|
|
757
|
+
});
|
|
758
|
+
return toolResultToCodexResponse(result);
|
|
759
|
+
}
|
|
760
|
+
if (req.method === 'item/tool/requestUserInput') return { answers: {} };
|
|
761
|
+
if (req.method === 'item/permissions/requestApproval') return { permissions: {}, scope: 'turn' };
|
|
762
|
+
if (req.method.endsWith('/requestApproval') || req.method === 'execCommandApproval' || req.method === 'applyPatchApproval') {
|
|
763
|
+
logger.warn({ msg: 'engine.codex_unexpected_approval', ...logCtx, method: req.method });
|
|
764
|
+
return { decision: 'decline' };
|
|
765
|
+
}
|
|
766
|
+
logger.warn({ msg: 'engine.codex_unhandled_request', ...logCtx, method: req.method });
|
|
767
|
+
return {};
|
|
768
|
+
};
|
|
769
|
+
|
|
770
|
+
// ---- drive the turn (runs concurrently with draining the queue) ------
|
|
771
|
+
const drive = async (): Promise<void> => {
|
|
772
|
+
try {
|
|
773
|
+
client = await CodexAppServerClient.start({
|
|
774
|
+
command: launch.command,
|
|
775
|
+
args: codexAppServerArgv(launch),
|
|
776
|
+
env: codexChildEnv(),
|
|
777
|
+
cwd: workspace,
|
|
778
|
+
onNotification,
|
|
779
|
+
onServerRequest,
|
|
780
|
+
logCtx,
|
|
781
|
+
});
|
|
782
|
+
void client.exited().then(({ code, signal: sig }) => {
|
|
783
|
+
if (!finished) {
|
|
784
|
+
logger.error({
|
|
785
|
+
msg: 'engine.codex_app_server_exited_early',
|
|
786
|
+
...logCtx,
|
|
787
|
+
code,
|
|
788
|
+
signal: sig,
|
|
789
|
+
stderr: client?.stderrTail.slice(-600),
|
|
790
|
+
});
|
|
791
|
+
streamErrors.push(
|
|
792
|
+
`codex app-server exited (code ${code}, signal ${sig ?? 'none'})${client?.stderrTail.trim() ? `: ${client.stderrTail.trim().slice(-400)}` : ''}`,
|
|
793
|
+
);
|
|
794
|
+
finish();
|
|
795
|
+
}
|
|
796
|
+
});
|
|
797
|
+
armIdleTimer();
|
|
798
|
+
if (abortFired) return;
|
|
799
|
+
|
|
800
|
+
const baseThreadParams = {
|
|
801
|
+
model: resolvedModel.modelId,
|
|
802
|
+
cwd: workspace,
|
|
803
|
+
approvalPolicy: 'never',
|
|
804
|
+
sandbox: 'danger-full-access',
|
|
805
|
+
config: threadConfig,
|
|
806
|
+
developerInstructions,
|
|
807
|
+
personality: 'none',
|
|
808
|
+
dynamicTools: catalog.specs,
|
|
809
|
+
};
|
|
810
|
+
let resumed = false;
|
|
811
|
+
if (resumeId) {
|
|
812
|
+
try {
|
|
813
|
+
const r = (await client.request(
|
|
814
|
+
'thread/resume',
|
|
815
|
+
{ threadId: resumeId, excludeTurns: true, ...baseThreadParams },
|
|
816
|
+
{ timeoutMs: 60_000 },
|
|
817
|
+
)) as { thread?: { id?: string } };
|
|
818
|
+
threadId = r.thread?.id ?? resumeId;
|
|
819
|
+
resumed = true;
|
|
820
|
+
} catch (err) {
|
|
821
|
+
const message = (err as Error).message;
|
|
822
|
+
if (err instanceof CodexRpcError && CODEX_STALE_THREAD_RE.test(message)) {
|
|
823
|
+
logger.warn({
|
|
824
|
+
msg: 'engine.session_resume_cleared',
|
|
825
|
+
...logCtx,
|
|
826
|
+
stale_id: resumeId,
|
|
827
|
+
err: message.slice(0, 300),
|
|
828
|
+
hint: 'thread gone — starting a fresh thread with the session history replayed',
|
|
829
|
+
});
|
|
830
|
+
queue.push({
|
|
831
|
+
kind: 'engine_meta',
|
|
832
|
+
ts: ts(),
|
|
833
|
+
engine: ENGINE,
|
|
834
|
+
itemType: 'thread_recreated',
|
|
835
|
+
payload: {
|
|
836
|
+
from: resumeId,
|
|
837
|
+
text: 'The Codex thread for this session no longer existed — a fresh thread was started with the session history carried over.',
|
|
838
|
+
},
|
|
839
|
+
});
|
|
840
|
+
resumeId = undefined;
|
|
841
|
+
threadId = undefined;
|
|
842
|
+
} else {
|
|
843
|
+
throw err;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
if (!resumed) {
|
|
848
|
+
const r = (await client.request(
|
|
849
|
+
'thread/start',
|
|
850
|
+
{ ...baseThreadParams, serviceName: 'somora' },
|
|
851
|
+
{ timeoutMs: 60_000 },
|
|
852
|
+
)) as { thread?: { id?: string } };
|
|
853
|
+
threadId = r.thread?.id;
|
|
854
|
+
}
|
|
855
|
+
if (abortFired) return;
|
|
856
|
+
|
|
857
|
+
const lastSeenTs = resumed ? getLastSeenTs(meta, ENGINE) : 0;
|
|
858
|
+
const rawDelta = computeReplayDelta(history, lastSeenTs, meta.compactions);
|
|
859
|
+
const replayDelta = resumed ? rawDelta : capReplayDelta(rawDelta);
|
|
860
|
+
const replayPrefix = renderReplayPrefix(replayDelta);
|
|
861
|
+
logger.info({
|
|
862
|
+
msg: 'engine.init',
|
|
863
|
+
...logCtx,
|
|
864
|
+
provider: resolvedModel.providerName,
|
|
865
|
+
model: resolvedModel.modelId,
|
|
866
|
+
bin: launch.source === 'bundled' ? `bundled ${launch.version ?? '?'}` : launch.command,
|
|
867
|
+
resumed,
|
|
868
|
+
threadId,
|
|
869
|
+
lastSeenTs,
|
|
870
|
+
replayPairs: replayDelta.pairs.length,
|
|
871
|
+
replaySummary: Boolean(replayDelta.summary),
|
|
872
|
+
directTools: catalog.directNames.length,
|
|
873
|
+
deferredTools: catalog.deferredNames.length,
|
|
874
|
+
images: imagePaths.length,
|
|
875
|
+
effort: effort ?? null,
|
|
876
|
+
});
|
|
877
|
+
|
|
878
|
+
const inputItems: Array<Record<string, unknown>> = [
|
|
879
|
+
{ type: 'text', text: buildText(resumed, replayPrefix), text_elements: [] },
|
|
880
|
+
...imagePaths.map((path) => ({ type: 'localImage', path })),
|
|
881
|
+
];
|
|
882
|
+
const rpc = client;
|
|
883
|
+
startTurn = async (eff: string | null): Promise<void> => {
|
|
884
|
+
const t = (await rpc.request(
|
|
885
|
+
'turn/start',
|
|
886
|
+
{
|
|
887
|
+
threadId,
|
|
888
|
+
input: inputItems,
|
|
889
|
+
...(eff ? { effort: eff } : {}),
|
|
890
|
+
summary,
|
|
891
|
+
},
|
|
892
|
+
{ timeoutMs: 60_000 },
|
|
893
|
+
)) as { turn?: { id?: string } };
|
|
894
|
+
if (typeof t.turn?.id === 'string') activeTurnId = t.turn.id;
|
|
895
|
+
};
|
|
896
|
+
await startTurn(effort);
|
|
897
|
+
} catch (err) {
|
|
898
|
+
if (!finished) {
|
|
899
|
+
streamErrors.push((err as Error).message);
|
|
900
|
+
logger.error({ msg: 'engine.fail', ...logCtx, err: (err as Error).message });
|
|
901
|
+
finish();
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
};
|
|
905
|
+
void drive();
|
|
906
|
+
|
|
907
|
+
// ---- emit -------------------------------------------------------------
|
|
908
|
+
try {
|
|
909
|
+
for await (const ev of queue.drain()) yield ev;
|
|
910
|
+
} finally {
|
|
911
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
912
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
913
|
+
}
|
|
914
|
+
client?.close();
|
|
915
|
+
|
|
916
|
+
const finalText = assistant.cumulative;
|
|
917
|
+
const thinkingText = reasoning.cumulative;
|
|
918
|
+
const usageOut = usage.seen
|
|
919
|
+
? {
|
|
920
|
+
usage: {
|
|
921
|
+
tokens_in: usage.tokens_in,
|
|
922
|
+
tokens_out: usage.tokens_out,
|
|
923
|
+
tokens_in_cached: usage.tokens_in_cached,
|
|
924
|
+
tokens_out_reasoning: usage.tokens_out_reasoning,
|
|
925
|
+
...(usage.context_tokens > 0 ? { context_tokens: usage.context_tokens } : {}),
|
|
926
|
+
...(usage.context_window > 0 ? { context_window: usage.context_window } : {}),
|
|
927
|
+
},
|
|
928
|
+
}
|
|
929
|
+
: {};
|
|
930
|
+
|
|
931
|
+
const emitFinal = function* (): Generator<NormalizedEvent> {
|
|
932
|
+
if (thinkingText) yield { kind: 'thinking_message', ts: ts(), engine: ENGINE, text: thinkingText };
|
|
933
|
+
};
|
|
934
|
+
|
|
935
|
+
if (watchdogFired) {
|
|
936
|
+
const message = `codex app-server timed out (${IDLE_TIMEOUT_MS / 1000}s idle)${streamErrors.length ? `: ${streamErrors.join('; ').slice(0, 400)}` : ''}`;
|
|
937
|
+
yield { kind: 'error', ts: ts(), engine: ENGINE, message, providerError: true };
|
|
938
|
+
yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId, ...usageOut };
|
|
939
|
+
await persistMeta();
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
if (abortFired) {
|
|
943
|
+
logger.info({ msg: 'engine.aborted', ...logCtx });
|
|
944
|
+
const partial = finalText ? `${finalText}\n\n[somora] aborted by user` : '[somora] aborted by user';
|
|
945
|
+
yield* emitFinal();
|
|
946
|
+
yield { kind: 'assistant_message', ts: ts(), engine: ENGINE, text: partial };
|
|
947
|
+
yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId, ...usageOut };
|
|
948
|
+
await persistMeta();
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
951
|
+
if (!turnOutcome || turnOutcome.status !== 'completed') {
|
|
952
|
+
const reason =
|
|
953
|
+
turnOutcome?.error ??
|
|
954
|
+
(streamErrors.length > 0 ? streamErrors.join('; ') : `turn ended with status ${turnOutcome?.status ?? 'unknown'}`);
|
|
955
|
+
logger.error({
|
|
956
|
+
msg: 'engine.fail',
|
|
957
|
+
...logCtx,
|
|
958
|
+
model: resolvedModel.modelId,
|
|
959
|
+
status: turnOutcome?.status,
|
|
960
|
+
err: reason.slice(0, 1000),
|
|
961
|
+
streamErrors,
|
|
962
|
+
});
|
|
963
|
+
if (finalText) {
|
|
964
|
+
yield* emitFinal();
|
|
965
|
+
yield { kind: 'assistant_message', ts: ts(), engine: ENGINE, text: finalText };
|
|
966
|
+
}
|
|
967
|
+
yield { kind: 'error', ts: ts(), engine: ENGINE, message: `codex turn failed: ${reason}`, providerError: true };
|
|
968
|
+
yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId, ...usageOut };
|
|
969
|
+
await persistMeta();
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
if (finalText) {
|
|
974
|
+
yield* emitFinal();
|
|
975
|
+
yield { kind: 'assistant_message', ts: ts(), engine: ENGINE, text: finalText };
|
|
976
|
+
}
|
|
977
|
+
logger.info({
|
|
978
|
+
msg: 'engine.turn',
|
|
979
|
+
...logCtx,
|
|
980
|
+
provider: resolvedModel.providerName,
|
|
981
|
+
model: resolvedModel.modelId,
|
|
982
|
+
tokens_in: usage.tokens_in,
|
|
983
|
+
tokens_in_cached: usage.tokens_in_cached,
|
|
984
|
+
context_tokens: usage.context_tokens,
|
|
985
|
+
context_window: usage.context_window || null,
|
|
986
|
+
tokens_out: usage.tokens_out,
|
|
987
|
+
tokens_out_reasoning: usage.tokens_out_reasoning,
|
|
988
|
+
threadId,
|
|
989
|
+
finalTextLen: finalText.length,
|
|
990
|
+
});
|
|
991
|
+
yield { kind: 'turn_end', ts: ts(), engine: ENGINE, turnId, ...usageOut };
|
|
992
|
+
await persistMeta();
|
|
993
|
+
|
|
994
|
+
async function persistMeta(): Promise<void> {
|
|
995
|
+
if (!threadId) return;
|
|
996
|
+
const id = threadId;
|
|
997
|
+
try {
|
|
998
|
+
await metaStore.update(agent, session, (freshMeta) => {
|
|
999
|
+
const { mcpServerName: _drop, ...rest } = freshMeta as CodexCliMeta;
|
|
1000
|
+
return {
|
|
1001
|
+
...rest,
|
|
1002
|
+
engine: ENGINE,
|
|
1003
|
+
codexSessionId: id,
|
|
1004
|
+
codexRecordedModel: resolvedModel.modelId,
|
|
1005
|
+
codexToolsFingerprint: toolsFingerprint,
|
|
1006
|
+
engineLastSeen: withLastSeenTs(freshMeta, ENGINE, ts()),
|
|
1007
|
+
};
|
|
1008
|
+
});
|
|
1009
|
+
} catch (err) {
|
|
1010
|
+
logger.warn({ msg: 'engine.meta_write_failed', ...logCtx, err: String(err) });
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
},
|
|
1014
|
+
};
|