evolcore 0.0.50 → 0.0.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -2
- package/bin/ec-build.mjs +60 -0
- package/bin/ecmsg.js +65 -63
- package/dist/ability/caller/command.js +24 -15
- package/dist/ability/caller/contract.js +24 -9
- package/dist/ability/caller/credential-files.js +132 -0
- package/dist/ability/caller/daemon.js +32 -7
- package/dist/ability/caller/schema-view.js +157 -0
- package/dist/ability/caller/service.js +202 -63
- package/dist/ability/interop-v1.js +156 -113
- package/dist/agent-template/jobs.js +14 -110
- package/dist/agent-template/runtime.js +331 -193
- package/dist/agent-template/service.js +1029 -1104
- package/dist/agent-template/share.js +103 -0
- package/dist/agent-template/tool-runner.js +25 -0
- package/dist/agent-template/types.js +10 -3
- package/dist/agents/claude/availability.js +94 -0
- package/dist/agents/claude/capability-provider.js +154 -0
- package/dist/agents/claude/index.js +145 -0
- package/dist/agents/{claude-runner.js → claude/runner.js} +74 -158
- package/dist/agents/claude/session-file-adapter.js +246 -0
- package/dist/agents/codex/app-server-client.js +90 -10
- package/dist/agents/codex/availability.js +164 -0
- package/dist/agents/codex/capability-provider.js +138 -0
- package/dist/agents/codex/cli.js +38 -0
- package/dist/agents/codex/index.js +345 -0
- package/dist/agents/codex/mcp-elicitation.js +135 -0
- package/dist/agents/{codex-runner.js → codex/runner.js} +648 -382
- package/dist/agents/codex/session-file-adapter.js +834 -0
- package/dist/agents/dsh/availability.js +28 -0
- package/dist/agents/dsh/capability-provider.js +56 -0
- package/dist/agents/dsh/desktop-locations.ps1 +66 -0
- package/dist/agents/dsh/desktop-probe.cjs +37 -0
- package/dist/agents/dsh/index.js +98 -0
- package/dist/agents/dsh/installation.js +400 -0
- package/dist/agents/dsh/resources.js +755 -0
- package/dist/agents/dsh/runner.js +1183 -0
- package/dist/agents/dsh/runtime/README.md +243 -0
- package/dist/agents/dsh/runtime/authorization.js +23 -0
- package/dist/agents/dsh/runtime/bridge.js +837 -0
- package/dist/agents/dsh/runtime/config.js +271 -0
- package/dist/agents/dsh/runtime/entry.js +229 -0
- package/dist/agents/dsh/runtime/session-inspector.js +340 -0
- package/dist/agents/dsh/runtime/tool-policy.js +49 -0
- package/dist/agents/dsh/session-file-adapter.js +145 -0
- package/dist/agents/ecagent/index.js +215 -0
- package/dist/agents/{ecagent-runner.js → ecagent/runner.js} +592 -106
- package/dist/agents/ecagent/session-file-adapter.js +134 -0
- package/dist/agents/gemini/index.js +55 -10
- package/dist/agents/gemini/{gemini-runner.js → runner.js} +4 -9
- package/dist/aun/ability-device-routing.js +11 -17
- package/dist/aun/aid/agentmd.js +27 -1
- package/dist/aun/aid/managed-operation.js +6 -4
- package/dist/aun/group/invite-service.js +1 -1
- package/dist/aun/menu/client.js +1 -1
- package/dist/aun/msg/history.js +1 -1
- package/dist/aun/msg/managed-operation.js +93 -21
- package/dist/aun/msg/p2p.js +6 -6
- package/dist/aun/service-proxy.js +1 -1
- package/dist/aun/storage/index.js +242 -0
- package/dist/build-identity.json +1 -1
- package/dist/channels/aun.js +180 -43
- package/dist/channels/daemon.js +3 -2
- package/dist/channels/dingtalk.js +1 -1
- package/dist/channels/feishu.js +9 -9
- package/dist/channels/qqbot.js +1 -1
- package/dist/channels/wechat.js +2 -2
- package/dist/channels/wecom.js +1 -1
- package/dist/{agents/claude-gateway → claude-gateway}/agent-registration.js +13 -13
- package/dist/{agents/claude-gateway → claude-gateway}/binding.js +3 -3
- package/dist/{agents/claude-gateway → claude-gateway}/inbox.js +1 -1
- package/dist/{agents/claude-gateway → claude-gateway}/index.js +2 -2
- package/dist/{agents/claude-gateway → claude-gateway}/listing.js +3 -3
- package/dist/{agents/claude-gateway → claude-gateway}/router.js +4 -4
- package/dist/{agents/claude-gateway → claude-gateway}/sessions.js +2 -2
- package/dist/{agents/claude-gateway → claude-gateway}/terminal.js +1 -1
- package/dist/{agents/claude-gateway → claude-gateway}/transcript.js +1 -1
- package/dist/cli/ability-command.js +8 -5
- package/dist/cli/ability-output.js +182 -0
- package/dist/cli/agent-command.js +1 -1
- package/dist/cli/agent-create.js +123 -42
- package/dist/cli/agent-template.js +400 -29
- package/dist/cli/agent.js +14 -11
- package/dist/cli/aun-commands.js +167 -111
- package/dist/cli/daemon-commands.js +38 -8
- package/dist/cli/data-command.js +1 -1
- package/dist/cli/debug-mode.js +9 -0
- package/dist/cli/directory.js +1 -2
- package/dist/cli/ecmsg-gateway.js +55 -19
- package/dist/cli/fs-command.js +67 -39
- package/dist/cli/index.js +25 -11
- package/dist/cli/init.js +124 -29
- package/dist/cli/managed-command-guard.js +2 -0
- package/dist/cli/model.js +1 -1
- package/dist/cli/restart-monitor.js +2 -2
- package/dist/cli/services-command.js +24 -1
- package/dist/cli/skill-command.js +4 -4
- package/dist/cli/task-context.js +24 -14
- package/dist/cli/team-workspace-command.js +50 -52
- package/dist/cli/thread-command.js +3 -2
- package/dist/cli/trigger-command.js +47 -12
- package/dist/cli/watch-logs.js +2 -1
- package/dist/config/boot-log.js +3 -0
- package/dist/config/builtin-role-templates.js +1 -1
- package/dist/config/config-field-policy.js +10 -6
- package/dist/config/config-manager.js +33 -12
- package/dist/config/gateway-config.js +21 -37
- package/dist/config/invoke-ipc-service.js +1 -1
- package/dist/config/owner-config.js +5 -3
- package/dist/config/peer-book-store.js +2 -3
- package/dist/config/peer-book.js +2 -2
- package/dist/config/peer-role-resolver.js +2 -2
- package/dist/config/provider-identity-migration.js +24 -105
- package/dist/config/provider-ipc-service.js +13 -3
- package/dist/config/provider-local-sync.js +4 -1
- package/dist/config/provider-menu-request.js +21 -3
- package/dist/config/provider-templates.js +1 -1
- package/dist/config/providers-config.js +39 -15
- package/dist/config/providers-import.js +3 -3
- package/dist/config/providers-management.js +74 -99
- package/dist/config/schema-migration.js +177 -11
- package/dist/config/schema-registry.js +1 -1
- package/dist/config-store.js +38 -50
- package/dist/core/{agent-application-service.js → agent/agent-application-service.js} +9 -9
- package/dist/core/{agent-create-status.js → agent/agent-create-status.js} +112 -4
- package/dist/core/{agent-creation-claim.js → agent/agent-creation-claim.js} +3 -3
- package/dist/core/{agent-ipc-registration.js → agent/agent-ipc-registration.js} +102 -25
- package/dist/core/{agent-reload-coordinator.js → agent/agent-reload-coordinator.js} +61 -1
- package/dist/core/{agent-runtime.js → agent/agent-runtime.js} +53 -27
- package/dist/core/{evolagent-registry.js → agent/evolagent-registry.js} +12 -12
- package/dist/core/{evolagent.js → agent/evolagent.js} +11 -11
- package/dist/core/auth/agent-delegation.js +1 -8
- package/dist/core/auth/delegation-authorization.js +28 -0
- package/dist/core/auth/operation-authorizer.js +7 -4
- package/dist/core/auth/operation-catalog.js +34 -5
- package/dist/core/baseagent/baseagent-availability.js +197 -0
- package/dist/core/baseagent/baseagent-capability-adapter.js +288 -0
- package/dist/core/baseagent/baseagent-config-shared.js +56 -0
- package/dist/core/baseagent/baseagent-identity.js +68 -0
- package/dist/core/{baseagent-loader.js → baseagent/baseagent-loader.js} +62 -6
- package/dist/core/baseagent/baseagent-model-defaults.js +26 -0
- package/dist/{agents → core/baseagent}/baseagent-plugin-descriptor.js +107 -24
- package/dist/core/baseagent/baseagent-plugin-loader.js +367 -0
- package/dist/core/baseagent/baseagent.js +157 -0
- package/dist/{agents → core/baseagent}/runner-types.js +36 -4
- package/dist/core/capability/capability-manager.js +79 -30
- package/dist/core/capability/providers/claude-capability-provider.js +2 -154
- package/dist/core/capability/providers/codex-capability-provider.js +2 -136
- package/dist/core/{channel-loader.js → channel/channel-loader.js} +226 -38
- package/dist/core/{channel-runtime.js → channel/channel-runtime.js} +18 -18
- package/dist/core/command/agent-control.js +60 -15
- package/dist/core/command/agent-template-menu.js +21 -9
- package/dist/core/command/agentmd-menu-request.js +19 -8
- package/dist/core/command/agentmd-menu.js +14 -5
- package/dist/core/command/command-handler.js +127 -57
- package/dist/core/command/context-policy-menu.js +122 -0
- package/dist/core/command/data-root-resolver.js +157 -20
- package/dist/core/command/memory-slash.js +6 -6
- package/dist/core/command/menu-catalog.js +80 -20
- package/dist/core/command/menu-handler.js +305 -25
- package/dist/core/command/menu-protocol.js +42 -8
- package/dist/core/command/menu-query-batch.js +9 -5
- package/dist/core/command/provider-menu.js +7 -11
- package/dist/core/command/role-menu.js +1 -1
- package/dist/core/command/skill-slash.js +17 -5
- package/dist/core/command/slash-gate.js +2 -4
- package/dist/core/command/slash-handler.js +127 -96
- package/dist/core/command/team-workspace-team.js +3 -3
- package/dist/core/command/topic-slash.js +10 -10
- package/dist/core/{daemon-bootstrap.js → daemon/daemon-bootstrap.js} +14 -14
- package/dist/core/{daemon-control.js → daemon/daemon-control.js} +46 -20
- package/dist/core/{daemon-lifecycle.js → daemon/daemon-lifecycle.js} +15 -15
- package/dist/core/{host-snapshot.js → daemon/host-snapshot.js} +3 -3
- package/dist/core/{ipc-registration.js → daemon/ipc-registration.js} +98 -38
- package/dist/core/{lifecycle-notice.js → daemon/lifecycle-notice.js} +4 -5
- package/dist/core/file-integrity/store.js +1 -1
- package/dist/core/handoff/ipc-registration.js +3 -3
- package/dist/core/handoff/runtime.js +1 -1
- package/dist/{agents → core/inference}/request-identity.js +2 -2
- package/dist/core/inference/text-inference.js +4 -4
- package/dist/core/{bootstrap-messages.js → initialization/bootstrap-messages.js} +10 -10
- package/dist/core/{bootstrap-service.js → initialization/bootstrap-service.js} +24 -23
- package/dist/core/initialization/service.js +54 -9
- package/dist/core/invoke/executors/media.js +1 -1
- package/dist/core/invoke/executors/text.js +1 -1
- package/dist/core/memory/consolidation-context.js +1 -1
- package/dist/core/memory/consolidation-trigger.js +9 -3
- package/dist/core/memory/consolidation.js +4 -4
- package/dist/core/memory/memory-admin.js +6 -6
- package/dist/core/memory/memory-writer.js +1 -1
- package/dist/core/memory/relation-idle-monitor.js +1 -1
- package/dist/core/message/aun-ipc-sender.js +114 -75
- package/dist/core/message/aun-request-registry.js +13 -5
- package/dist/core/message/auto-mention-gate.js +1 -1
- package/dist/core/message/contact-admission.js +1 -1
- package/dist/core/message/im-renderer.js +19 -0
- package/dist/core/{interaction-router.js → message/interaction-router.js} +4 -4
- package/dist/core/message/items-formatter.js +5 -5
- package/dist/core/message/message-admission.js +1 -1
- package/dist/core/message/message-bridge.js +135 -54
- package/dist/core/message/message-queue.js +83 -4
- package/dist/core/message/message-utils.js +1 -1
- package/dist/core/message/peer-mode.js +1 -1
- package/dist/core/message/response-engine.js +347 -163
- package/dist/core/message/send-options.js +9 -6
- package/dist/core/message/send-routing.js +45 -109
- package/dist/core/message/stream-idle-monitor.js +1 -1
- package/dist/core/{data-migration.js → migration/data-migration.js} +29 -1
- package/dist/core/model/catalog-service.js +29 -8
- package/dist/core/model/model-capabilities.js +88 -0
- package/dist/core/model/model-catalog.js +14 -3
- package/dist/core/model/model-diagnostics.js +4 -4
- package/dist/core/ownership/owner-resolver.js +95 -15
- package/dist/core/{pack-auth.js → pack/pack-auth.js} +30 -3
- package/dist/core/{pack-install.js → pack/pack-install.js} +95 -17
- package/dist/core/permission/approval-gateway.js +9 -18
- package/dist/core/permission/ec-command-parser.js +70 -34
- package/dist/core/permission/managed-file.js +234 -0
- package/dist/core/permission/protected-paths.js +56 -0
- package/dist/core/permission/sandbox-runtime.js +267 -3
- package/dist/core/permission/session-path-grants.js +1 -1
- package/dist/core/permission/shell-environment.js +15 -1
- package/dist/core/plugin/plugin-lifecycle.js +442 -0
- package/dist/core/session/adapters/claude-session-file-adapter.js +2 -246
- package/dist/core/session/adapters/codex-session-file-adapter.js +2 -566
- package/dist/core/session/adapters/ecagent-session-file-adapter.js +2 -134
- package/dist/core/{background-session → session/background}/session-cleanup.js +2 -2
- package/dist/core/{background-session → session/background}/types.js +1 -1
- package/dist/core/session/session-file-health.js +2 -272
- package/dist/core/session/session-idle-monitor.js +1 -1
- package/dist/core/session/session-manager.js +29 -2
- package/dist/core/session/session-terminal.js +185 -0
- package/dist/core/session/session-title.js +8 -11
- package/dist/core/{system-session → session/system}/memory.js +43 -9
- package/dist/core/{system-session → session/system}/registry.js +1 -1
- package/dist/core/{system-session → session/system}/types.js +1 -1
- package/dist/core/skill/index-generator.js +1 -0
- package/dist/core/task/task-activity-store.js +112 -0
- package/dist/core/task/task-recovery-service.js +2 -2
- package/dist/core/thread/ipc-operation.js +2 -2
- package/dist/core/thread/thread-operation.js +2 -1
- package/dist/core/thread/thread-route.js +5 -3
- package/dist/core/thread/thread-service.js +14 -4
- package/dist/directory/{owner-directory-admission.js → admission.js} +3 -3
- package/dist/directory/{owner-directory-cache.js → cache.js} +90 -8
- package/dist/directory/{owner-directory-markdown.js → markdown.js} +2 -2
- package/dist/directory/{owner-directory-query-operation.js → query-operation.js} +83 -9
- package/dist/directory/{owner-directory-search.js → search.js} +50 -2
- package/dist/directory/{owner-directory-store.js → store.js} +2 -2
- package/dist/eck/kit-renderer.js +1 -1
- package/dist/eck/manifest-engine.js +64 -2
- package/dist/eck/message-renderer.js +35 -0
- package/dist/ecweb/basic-settings-service.js +9 -3
- package/dist/{contracts → ecweb/contracts}/ecweb-service-protocol.js +2 -1
- package/dist/ecweb/dsh-native-service.js +413 -0
- package/dist/ecweb/providers-service.js +1 -1
- package/dist/ecweb/runtime/lifecycle.js +1 -1
- package/dist/ecweb/runtime/supervisor.js +1 -1
- package/dist/event-center/center-config.js +2 -2
- package/dist/event-center/dispatcher.js +1 -1
- package/dist/event-center/ipc-operation.js +12 -3
- package/dist/event-center/pack-loader.js +2 -2
- package/dist/event-center/registry.js +6 -6
- package/dist/event-center/runtime.js +2 -2
- package/dist/index.js +71 -42
- package/dist/ipc.js +103 -10
- package/dist/outputs/authorization.js +27 -0
- package/dist/outputs/events.js +10 -1
- package/dist/outputs/panel-cards.js +960 -0
- package/dist/paths.js +12 -0
- package/dist/pay/command.js +1 -1
- package/dist/pay/runtime.js +18 -10
- package/dist/response-system/engines/v1/proactive-flow.js +1 -1
- package/dist/services/dispatcher.js +2 -2
- package/dist/services/host/main.js +10 -1
- package/dist/services/host/protocol.js +9 -2
- package/dist/services/host/resident.js +37 -0
- package/dist/services/host-client.js +12 -0
- package/dist/services/host-recycle.js +8 -3
- package/dist/services/host-runtime.js +54 -15
- package/dist/services/index.js +83 -19
- package/dist/services/ipc-operation.js +303 -38
- package/dist/services/pack-manager.js +2 -2
- package/dist/services/router.js +43 -3
- package/dist/services/script-runner.js +34 -25
- package/dist/services/service-payload.js +28 -1
- package/dist/services/validation.js +28 -2
- package/dist/stats/context-usage.js +110 -0
- package/dist/stats/model-resolver.js +103 -17
- package/dist/stats/query.js +5 -0
- package/dist/trigger/application-service.js +3 -2
- package/dist/trigger/authorization.js +36 -33
- package/dist/trigger/ipc-service.js +4 -4
- package/dist/trigger/local-files.js +8 -176
- package/dist/trigger/manager.js +2 -2
- package/dist/trigger/parser.js +48 -0
- package/dist/trigger/scheduler.js +14 -2
- package/dist/trigger/script-executor.js +21 -0
- package/dist/trigger/script-sandbox.js +57 -243
- package/dist/trigger/system-definitions.js +25 -0
- package/dist/trigger/validation.js +1 -1
- package/dist/utils/atomic-write.js +88 -1
- package/dist/utils/cross-platform.js +4 -42
- package/dist/utils/error-dict.json +22 -1
- package/dist/utils/error-utils.js +193 -6
- package/dist/utils/evolcore-version.js +2 -2
- package/dist/utils/host-info.js +1 -1
- package/dist/utils/logger.js +3 -1
- package/dist/utils/media-cache.js +99 -4
- package/dist/utils/startup-trace.js +20 -4
- package/dist/utils/welcome.js +64 -20
- package/ecagent/README.md +35 -0
- package/ecagent/dist/agent-loop.js +80 -30
- package/ecagent/dist/harness/env/nodejs.d.ts +16 -0
- package/ecagent/dist/harness/env/nodejs.js +49 -20
- package/ecagent/dist/harness/messages.js +3 -2
- package/ecagent/dist/harness/types.d.ts +1 -0
- package/ecagent/dist/runtime/types.d.ts +2 -0
- package/ecagent/dist/runtime/utils/validation.d.ts +7 -1
- package/ecagent/dist/runtime/utils/validation.js +42 -0
- package/ecagent/dist/types.d.ts +2 -0
- package/kits/docs/INDEX.md +1 -1
- package/kits/docs/channels/feishu.md +1 -1
- package/kits/docs/evolcore/INDEX.md +10 -7
- package/kits/docs/evolcore/agent-create.md +2 -0
- package/kits/docs/evolcore/agent.md +100 -13
- package/kits/docs/evolcore/aid.md +19 -3
- package/kits/docs/evolcore/config.md +94 -0
- package/kits/docs/evolcore/ctl.md +2 -1
- package/kits/docs/evolcore/ec-capabilities.md +7 -10
- package/kits/docs/evolcore/ecweb-lifecycle.md +5 -1
- package/kits/docs/evolcore/event.md +1 -1
- package/kits/docs/evolcore/fs.md +49 -3
- package/kits/docs/evolcore/group.md +3 -3
- package/kits/docs/evolcore/memory-consolidation.md +1 -1
- package/kits/docs/evolcore/menu-protocol.md +24 -2
- package/kits/docs/evolcore/model.md +9 -1
- package/kits/docs/evolcore/msg.md +30 -28
- package/kits/docs/evolcore/pay.md +8 -20
- package/kits/docs/evolcore/plugin.md +74 -0
- package/kits/docs/evolcore/provider.md +8 -2
- package/kits/docs/evolcore/rpc.md +2 -2
- package/kits/docs/evolcore/skill.md +17 -1
- package/kits/docs/evolcore/stats.md +5 -0
- package/kits/docs/evolcore/storage.md +22 -0
- package/kits/docs/evolcore/thread-chain.md +19 -10
- package/kits/docs/evolcore/tool-authorization.md +4 -0
- package/kits/docs/evolcore/trigger.md +89 -13
- package/kits/docs/identity/AID_PROFILE_SPEC.md +1 -1
- package/kits/docs/venues/feishu-group.md +3 -2
- package/kits/docs/venues/feishu-private.md +3 -2
- package/kits/rules/02-navigation.md +20 -13
- package/kits/rules/06-channel.md +18 -2
- package/kits/schemas/_meta.json +8 -4
- package/kits/schemas/agent-config.schema.23.json +19 -3
- package/kits/schemas/agent-config.schema.24.json +986 -0
- package/kits/schemas/agent-config.schema.25.json +986 -0
- package/kits/schemas/daemon.schema.11.json +487 -0
- package/kits/schemas/daemon.schema.12.json +505 -0
- package/kits/schemas/defaults.schema.8.json +484 -0
- package/kits/schemas/providers.schema.1.json +1 -1
- package/kits/schemas/providers.schema.2.json +1 -1
- package/kits/schemas/providers.schema.3.json +8 -2
- package/kits/skills/.switches.json +4 -0
- package/kits/skills/ability/SKILL.md +194 -27
- package/kits/skills/ability/STRUCTURE.md +5 -0
- package/kits/skills/agent-output-cards/SKILL.md +90 -54
- package/kits/skills/agent-output-cards/examples/html-surface.json +11 -0
- package/kits/skills/agent-output-cards/examples/meeting-followups.json +16 -0
- package/kits/skills/agent-output-cards/examples/meeting-latest.json +24 -0
- package/kits/skills/agent-output-cards/examples/project-metrics.json +16 -0
- package/kits/skills/agent-output-cards/examples/quick-links.json +18 -0
- package/kits/skills/agent-output-cards/examples/surface.html +8 -0
- package/kits/skills/agent-template-project/SKILL.md +51 -0
- package/kits/skills/agent-template-project/references/01-collect-and-pack.md +174 -0
- package/kits/skills/agent-template-project/references/02-upload-and-share.md +109 -0
- package/kits/skills/agent-template-project/references/03-download-and-install.md +189 -0
- package/kits/skills/agent-template-project/references/04-upgrade-and-recovery.md +74 -0
- package/kits/skills/agent-template-project/references/05-publish-to-platform.md +62 -0
- package/kits/skills/ec-group/SKILL.md +3 -3
- package/kits/skills/ec-group-collaboration/SKILL.md +4 -4
- package/kits/skills/ec-identity/SKILL.md +9 -6
- package/kits/skills/ec-pay/SKILL.md +163 -41
- package/kits/skills/ec-provider/SKILL.md +5 -5
- package/kits/skills/ec-service-call/SKILL.md +3 -0
- package/kits/skills/ec-skill/SKILL.md +25 -9
- package/kits/skills/ec-skill/scripts/cli.mjs +7 -7
- package/kits/skills/ec-skill/scripts/skill.mjs +55 -41
- package/kits/skills/ec-skill/scripts/template/SKILL.md.tmpl +9 -0
- package/kits/skills/ec-trigger/SKILL.md +2 -2
- package/kits/skills/personal-assistant/SKILL.md +22 -22
- package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +1 -1
- package/kits/skills/scrapling-article-fetch/SKILL.md +5 -5
- package/kits/skills/thread-ops/SKILL.md +19 -9
- package/kits/skills/wechat-article-media-download/SKILL.md +2 -2
- package/kits/skills/wechat-article-reader/SKILL.md +2 -2
- package/kits/templates/system-fragments/commands.md +1 -1
- package/kits/templates/system-fragments/personal-assistant.md +2 -2
- package/kits/templates/system-fragments/reply.md +14 -9
- package/kits/templates/system-fragments/session.md +1 -1
- package/kits/templates/system-fragments/thread.md +10 -5
- package/package.json +6 -5
- package/scripts/agent-template/index.mjs +7 -1
- package/scripts/agent-template/inspect.mjs +81 -35
- package/scripts/agent-template/overlay.mjs +110 -4
- package/scripts/agent-template/shared/common.mjs +36 -4
- package/scripts/agent-template/shared/plan.mjs +4 -2
- package/scripts/agent-template/shared/service-packs.mjs +104 -0
- package/scripts/agent-template/shared/team-schema.json +467 -54
- package/scripts/agent-template/shared/template-contract.mjs +70 -68
- package/scripts/agent-template/shared/template-package.mjs +153 -36
- package/scripts/agent-template/shared/template-runtime.mjs +76 -64
- package/scripts/agent-template/shared/template.mjs +11 -46
- package/scripts/agent-template/team-pack.mjs +451 -35
- package/scripts/agent-template/team-preview.mjs +75 -226
- package/scripts/aid-batch/identity-batch.mjs +1 -1
- package/dist/agents/baseagent-availability.js +0 -176
- package/dist/agents/baseagent-capability-adapter.js +0 -102
- package/dist/agents/baseagent-plugin-loader.js +0 -145
- package/dist/agents/baseagent.js +0 -816
- package/dist/agents/codex/catalog.js +0 -80
- package/dist/agents/ecagent-plugin-lazy.js +0 -41
- package/dist/agents/tool-time-context.js +0 -55
- package/dist/core/legacy-rename.js +0 -41
- package/dist/core/plugin-lifecycle.js +0 -137
- package/dist/core/rate-window.js +0 -53
- package/dist/core/runner-reload-transaction.js +0 -60
- package/dist/core/runtime-lock.js +0 -90
- package/dist/core/soul.js +0 -66
- package/dist/core/system-session/grants.js +0 -40
- package/dist/directory/owner-directory-agentmd-sync.js +0 -89
- package/dist/directory/owner-directory-request-operation.js +0 -79
- package/dist/directory/owner-directory-text.js +0 -60
- package/kits/skills/ec-pay/references/pay-cli.md +0 -110
- /package/dist/agents/gemini/{gemini-capability-provider.js → capability-provider.js} +0 -0
- /package/dist/agents/gemini/{gemini-session-file-adapter.js → session-file-adapter.js} +0 -0
- /package/dist/{agents/claude-gateway → claude-gateway}/types.js +0 -0
- /package/dist/core/{system-channels.js → channel/system-channels.js} +0 -0
- /package/dist/core/{daemon-file-cache.js → daemon/daemon-file-cache.js} +0 -0
- /package/dist/core/{event-bus.js → event/event-bus.js} +0 -0
- /package/dist/core/{event-catalog.js → event/event-catalog.js} +0 -0
- /package/dist/core/{pack-ledger.js → pack/pack-ledger.js} +0 -0
- /package/dist/directory/{owner-directory-identity.js → identity.js} +0 -0
- /package/dist/directory/{owner-directory-policy.js → policy.js} +0 -0
- /package/dist/directory/{owner-directory-remarks.js → remarks.js} +0 -0
- /package/dist/directory/{owner-directory-scope.js → scope.js} +0 -0
- /package/dist/{contracts → ecweb/contracts}/ecweb-instance.js +0 -0
- /package/kits/templates/{bootstrap-welcome.md → bootstrap-intro.md} +0 -0
|
@@ -1,50 +1,54 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getCodexAppServerAvailabilityAsync } from './availability.js';
|
|
2
|
+
export { MIN_CODEX_CLI_VERSION, parseCodexCliVersion, isCodexCliVersionSupported, getCodexCliVersion, getCodexAppServerAvailability, isCodexAppServerAvailable, invalidateCodexAppServerAvailabilityCache, getCodexAppServerAvailabilityAsync } from './availability.js';
|
|
3
|
+
import { assertRunnerModelAllowed, getRunnerCatalog, catalogEfforts, assertCatalogSelectable } from '../../core/model/model-catalog.js';
|
|
2
4
|
// Codex/OpenAI API 不认识 Claude Code SDK 的窗口后缀,必须传入基础模型 ID。
|
|
3
|
-
import { parseModelId, stripContextWindowSuffix } from '
|
|
4
|
-
import {
|
|
5
|
-
import { formatAsyncQuestionAnswer, hasTrustedFullAccessContext, parseAsyncUserQuestions, unsettledInterruptError, withInterruptDeadline } from '
|
|
6
|
-
import { requestDangerousCommandPermissionResult } from '
|
|
7
|
-
import { permissionFailureResult } from '
|
|
8
|
-
import { checkReadonly, checkDangerousCommand, evaluateToolPreflight } from '
|
|
9
|
-
import { isShellToolName, normalizeFileMutation } from '
|
|
10
|
-
import { normalizeExecutionPermissionMode, normalizePermissionMode, resolvePhaseOneExecutionSandbox } from '
|
|
11
|
-
import { assertWindowsCodexFilesystemRuleBudget, buildCodexProtectedFilesystemRules, compactCodexLinuxFilesystemRules, getExistingRelationAttachmentDirs, isSameOrDescendant, resolveProtectedCandidate, } from '
|
|
12
|
-
import { CODEX_THREAD_ACTIVE_WRITER, CodexAppServerClient, } from './
|
|
13
|
-
import { getSandboxInitializationFailureCounters, isNestedSandboxInitializationFailure, recordSandboxInitializationFailure, SANDBOX_INITIALIZATION_FAILED, } from '
|
|
14
|
-
import { resolveOpenaiConfig
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import { agentCodexTokenPath, getPackageRoot, resolvePaths, resolveRoot } from '
|
|
31
|
-
import { CODEX_HOOK_TOKEN_ENV, MAIN_CLI_BIN } from '
|
|
32
|
-
import { ensureSessionRuntimeDir, ensureSessionRuntimeDirAsync, getManagedTaskTempDir } from '
|
|
33
|
-
import { buildTranscriptTurns } from '
|
|
34
|
-
import { CodexSessionFileAdapter } from '
|
|
35
|
-
import { readSessionHistoryBackward } from '
|
|
36
|
-
import {
|
|
5
|
+
import { parseModelId, stripContextWindowSuffix } from '../../core/model/context-window-suffix.js';
|
|
6
|
+
import { CODEX_FALLBACK_CONTEXT_TOKENS, readAgentCompactThreshold, resolveAgentContextPolicy } from '../../core/model/model-capabilities.js';
|
|
7
|
+
import { formatAsyncQuestionAnswer, hasTrustedFullAccessContext, parseAsyncUserQuestions, unsettledInterruptError, withInterruptDeadline } from '../../core/baseagent/runner-types.js';
|
|
8
|
+
import { requestDangerousCommandPermissionResult } from '../../core/permission/approval-gateway.js';
|
|
9
|
+
import { permissionFailureResult } from '../../core/permission/permission-result.js';
|
|
10
|
+
import { checkReadonly, checkDangerousCommand, evaluateToolPreflight } from '../../core/permission/tool-policy.js';
|
|
11
|
+
import { isShellToolName, normalizeFileMutation } from '../../core/permission/tool-canonical.js';
|
|
12
|
+
import { normalizeExecutionPermissionMode, normalizePermissionMode, resolvePhaseOneExecutionSandbox } from '../../core/permission/mode.js';
|
|
13
|
+
import { assertWindowsCodexFilesystemRuleBudget, buildCodexProtectedFilesystemRules, compactCodexLinuxFilesystemRules, getExistingCodexProjectSkillRoots, getExistingRelationAttachmentDirs, getExistingSelfAttachmentDirs, isSameOrDescendant, resolveProtectedCandidate, } from '../../core/permission/protected-paths.js';
|
|
14
|
+
import { CODEX_THREAD_ACTIVE_WRITER, CodexAppServerClient, } from './app-server-client.js';
|
|
15
|
+
import { getSandboxInitializationFailureCounters, isNestedSandboxInitializationFailure, recordSandboxInitializationFailure, SANDBOX_INITIALIZATION_FAILED, } from '../../core/permission/sandbox-runtime.js';
|
|
16
|
+
import { resolveOpenaiConfig } from './index.js';
|
|
17
|
+
import { resolveRuntimeBaseagentModelSelection } from '../../core/baseagent/baseagent.js';
|
|
18
|
+
import { logger } from '../../utils/logger.js';
|
|
19
|
+
import { resolveProviderService } from '../../config/providers.js';
|
|
20
|
+
import { catalogHash } from '../../core/model/catalog-service.js';
|
|
21
|
+
import { summarizeToolInputForAudit } from '../../utils/tool-summary.js';
|
|
22
|
+
import { auditCodexApprovalDecision, auditPermissionLifecycle, auditToolInfrastructureFailure, auditToolPreflightDenial } from '../../core/auth/authorization-audit.js';
|
|
23
|
+
import { classifyError, ErrorType, getToolResultErrorText, isOutputTokenLimitError, isRetryableError } from '../../utils/error-utils.js';
|
|
24
|
+
import { findModelSpec, getGatewayPricing as getSharedGatewayPricing } from '../../stats/model-resolver.js';
|
|
25
|
+
import { renderActionAsText } from '../../core/message/interaction-router.js';
|
|
26
|
+
import { buildEnvelope, isInteractionSendAccepted, sendInteractionPayload } from '../../core/message/message-utils.js';
|
|
27
|
+
import { isBaseagentSkillsEnabled, resolveCodexCapabilityThreadConfigForProject } from '../../core/capability/capability-manager.js';
|
|
28
|
+
import { resolveEffective } from '../../config/config-manager.js';
|
|
29
|
+
import { AGENT_DELEGATION_TOKEN_ENV, CODEX_SESSION_TOKEN_ENV, hashDelegatedCommandArgv, hashDelegatedCommandSpec, parseDelegatedExecutionSpec, } from '../../core/auth/agent-delegation.js';
|
|
30
|
+
import { sanitizeShellExecutionEnvironment } from '../../core/permission/shell-environment.js';
|
|
31
|
+
import { classifyEvolcoreShellCommand, canonicalizeEvolcoreCommandArgv, literalShellParseRemedy, containsLiteralManagedTmpDirOutsideSendContent, containsUnresolvedManagedTmpDirReference, hasCodexCmdCarrierEcIntent, hasPowerShellCredentialAssignment, normalizeEvolcoreCommandArgv, parseLiteralShellArgv, resolveCodexShellCarrierArgv, resolveCanonicalEvolcoreToolInput, serializeCanonicalEvolcoreExecutionSpec, } from '../../core/permission/ec-command-parser.js';
|
|
32
|
+
import { agentCodexTokenPath, getPackageRoot, resolvePaths, resolveRoot } from '../../paths.js';
|
|
33
|
+
import { CODEX_HOOK_TOKEN_ENV, MAIN_CLI_BIN } from '../../product.js';
|
|
34
|
+
import { ensureSessionRuntimeDir, ensureSessionRuntimeDirAsync, getManagedTaskTempDir } from '../../cli/task-context.js';
|
|
35
|
+
import { buildTranscriptTurns } from '../../core/session/session-transcript.js';
|
|
36
|
+
import { CodexSessionFileAdapter, repairCodexSessionProvider } from './session-file-adapter.js';
|
|
37
|
+
import { readSessionHistoryBackward } from '../../core/session/session-fs-store.js';
|
|
38
|
+
import { resolveRunInference } from '../../core/baseagent/runner-types.js';
|
|
37
39
|
import { execFileSync } from 'child_process';
|
|
38
|
-
import { probeCli, probeCliSync, CODEX_CLI_PROBE_TIMEOUT_MS, CODEX_CLI_PROBE_RETRY_TIMEOUT_MS } from '../utils/cross-platform.js';
|
|
39
40
|
import { createHash, randomBytes } from 'crypto';
|
|
40
|
-
import { buildModelRequestHeaders } from '
|
|
41
|
-
import { extractStructuredToolErrorMarker, normalizeToolErrorClassification, normalizeToolErrorCode, normalizeToolErrorDetailCode, } from '
|
|
41
|
+
import { buildModelRequestHeaders } from '../../core/inference/request-identity.js';
|
|
42
|
+
import { extractStructuredToolErrorMarker, normalizeToolErrorClassification, normalizeToolErrorCode, normalizeToolErrorDetailCode, } from '../../core/permission/tool-error-code.js';
|
|
42
43
|
import fs from 'fs';
|
|
43
|
-
import { assertOwnershipAuthorization } from '
|
|
44
|
+
import { assertOwnershipAuthorization } from '../../core/ownership/owner-resolver.js';
|
|
44
45
|
import path from 'path';
|
|
45
46
|
import os from 'os';
|
|
47
|
+
import { cancelledMcpElicitation, collectMcpConfirmation, parseMcpConfirmation } from './mcp-elicitation.js';
|
|
46
48
|
const APPROVAL_LOG_SUMMARY_MAX_LENGTH = 256;
|
|
47
49
|
const CODEX_INTERRUPT_TIMEOUT_MS = 5_000;
|
|
50
|
+
const CODEX_STARTUP_SETTLE_TIMEOUT_MS = 10_000;
|
|
51
|
+
const CODEX_THREAD_OPEN_TIMEOUT_MS = 60_000;
|
|
48
52
|
function toAgentErrorType(message) {
|
|
49
53
|
// Forgetting the provider thread is the only remedy for a missing model.
|
|
50
54
|
// classifyError must keep returning MODEL_UNAVAILABLE for it, but the runner
|
|
@@ -201,6 +205,19 @@ function waitForCodexOperation(operation, signal) {
|
|
|
201
205
|
onAbort();
|
|
202
206
|
});
|
|
203
207
|
}
|
|
208
|
+
async function waitForCodexDelay(ms, signal) {
|
|
209
|
+
let timer;
|
|
210
|
+
try {
|
|
211
|
+
await waitForCodexOperation(new Promise(resolve => {
|
|
212
|
+
timer = setTimeout(resolve, ms);
|
|
213
|
+
timer.unref?.();
|
|
214
|
+
}), signal);
|
|
215
|
+
}
|
|
216
|
+
finally {
|
|
217
|
+
if (timer)
|
|
218
|
+
clearTimeout(timer);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
204
221
|
function isCodexReasoningNotification(method) {
|
|
205
222
|
return method === 'item/reasoning/textDelta'
|
|
206
223
|
|| method === 'item/reasoning/summaryTextDelta'
|
|
@@ -213,7 +230,7 @@ const CODEX_THREAD_HANDOFF_TIMEOUT_MS = 2_000;
|
|
|
213
230
|
* "already has an active writer"; retrying the resume — never the input — is safe
|
|
214
231
|
* because the failed turn consumed nothing.
|
|
215
232
|
*/
|
|
216
|
-
const
|
|
233
|
+
const CODEX_THREAD_WRITER_RETRY_DELAYS_MS = [500, 1_000, 3_000];
|
|
217
234
|
function stableSecurityValue(value) {
|
|
218
235
|
if (value === undefined)
|
|
219
236
|
return 'undefined';
|
|
@@ -296,166 +313,6 @@ function isCodexActiveWriterError(error) {
|
|
|
296
313
|
return error?.code === CODEX_THREAD_ACTIVE_WRITER
|
|
297
314
|
|| CODEX_ACTIVE_WRITER_RE.test(error instanceof Error ? error.message : String(error));
|
|
298
315
|
}
|
|
299
|
-
// The permission bridge is version-locked to the audited approval schema and
|
|
300
|
-
// managed PreToolUse hook behavior used by proactive first-tool enforcement.
|
|
301
|
-
export const MIN_CODEX_CLI_VERSION = '0.144.1';
|
|
302
|
-
export function parseCodexCliVersion(output) {
|
|
303
|
-
const match = output.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/);
|
|
304
|
-
return match?.[1] ?? null;
|
|
305
|
-
}
|
|
306
|
-
export function isCodexCliVersionSupported(version) {
|
|
307
|
-
return compareVersions(version, MIN_CODEX_CLI_VERSION) >= 0;
|
|
308
|
-
}
|
|
309
|
-
function compactCodexProbeText(value, maxLength = 600) {
|
|
310
|
-
if (Buffer.isBuffer(value))
|
|
311
|
-
value = value.toString('utf-8');
|
|
312
|
-
if (typeof value !== 'string')
|
|
313
|
-
return undefined;
|
|
314
|
-
const text = value.replace(/\s+/gu, ' ').trim();
|
|
315
|
-
return text.length <= maxLength ? text : `${text.slice(0, maxLength - 3).trimEnd()}...`;
|
|
316
|
-
}
|
|
317
|
-
function logCodexProbeFailure(args, startedAt, error, timeoutMs, launch) {
|
|
318
|
-
const detail = error;
|
|
319
|
-
logger.warn(`[CodexProbe] CLI probe failed: ${JSON.stringify({
|
|
320
|
-
command: ['codex', ...args],
|
|
321
|
-
resolvedPath: launch?.resolvedPath ?? null,
|
|
322
|
-
launcherKind: launch?.launcherKind ?? null,
|
|
323
|
-
launcherPath: launch?.launcherPath ?? null,
|
|
324
|
-
path: detail?.path ?? null,
|
|
325
|
-
spawnargs: detail?.spawnargs ?? null,
|
|
326
|
-
elapsedMs: Date.now() - startedAt,
|
|
327
|
-
timeoutMs,
|
|
328
|
-
code: detail?.code ?? null,
|
|
329
|
-
status: detail?.status ?? null,
|
|
330
|
-
signal: detail?.signal ?? null,
|
|
331
|
-
timedOut: detail?.code === 'ETIMEDOUT',
|
|
332
|
-
message: compactCodexProbeText(detail?.message ?? String(error)),
|
|
333
|
-
stdout: compactCodexProbeText(detail?.stdout),
|
|
334
|
-
stderr: compactCodexProbeText(detail?.stderr),
|
|
335
|
-
})}`);
|
|
336
|
-
}
|
|
337
|
-
function probeCodexCli(args, executable) {
|
|
338
|
-
return probeCliSync('codex', args, {
|
|
339
|
-
executable, onFailure: logCodexProbeFailure,
|
|
340
|
-
validateOutput: args[0] === '--version' ? output => parseCodexCliVersion(output) !== null : undefined,
|
|
341
|
-
});
|
|
342
|
-
}
|
|
343
|
-
export function getCodexCliVersion(executable) {
|
|
344
|
-
try {
|
|
345
|
-
return parseCodexCliVersion(probeCodexCli(['--version'], executable));
|
|
346
|
-
}
|
|
347
|
-
catch {
|
|
348
|
-
return null;
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
export function getCodexAppServerAvailability() {
|
|
352
|
-
const cliPath = resolveCodexCliPath();
|
|
353
|
-
if (!cliPath) {
|
|
354
|
-
const powershellShim = resolveCodexPowerShellShimPath();
|
|
355
|
-
return {
|
|
356
|
-
available: false,
|
|
357
|
-
reason: powershellShim
|
|
358
|
-
? '检测到 codex.ps1,但当前 Windows 启动路径要求 codex.exe/codex.cmd/codex.bat;请重新安装 @openai/codex 以恢复 npm shim。'
|
|
359
|
-
: '未检测到 Codex CLI。',
|
|
360
|
-
};
|
|
361
|
-
}
|
|
362
|
-
const version = getCodexCliVersion(cliPath);
|
|
363
|
-
if (!version) {
|
|
364
|
-
return { available: false, reason: '无法读取 Codex CLI 版本。' };
|
|
365
|
-
}
|
|
366
|
-
if (!isCodexCliVersionSupported(version)) {
|
|
367
|
-
return {
|
|
368
|
-
available: false,
|
|
369
|
-
version,
|
|
370
|
-
reason: `Codex CLI ${version} 低于最低要求 ${MIN_CODEX_CLI_VERSION}。请升级 Codex CLI:npm install -g @openai/codex@latest`,
|
|
371
|
-
requiresUpgrade: true,
|
|
372
|
-
};
|
|
373
|
-
}
|
|
374
|
-
try {
|
|
375
|
-
probeCodexCli(['app-server', '--help'], cliPath);
|
|
376
|
-
return { available: true, version };
|
|
377
|
-
}
|
|
378
|
-
catch (error) {
|
|
379
|
-
if (error?.code === 'ETIMEDOUT') {
|
|
380
|
-
return { available: false, version, reason: `Codex CLI ${version} 的 app-server 探测超时,请稍后重试。` };
|
|
381
|
-
}
|
|
382
|
-
return { available: false, version, reason: `Codex CLI ${version} 的 app-server 探测失败,请检查 CLI 启动日志。` };
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
export function isCodexAppServerAvailable() {
|
|
386
|
-
return getCodexAppServerAvailability().available;
|
|
387
|
-
}
|
|
388
|
-
/**
|
|
389
|
-
* 启动期可用性探测结果缓存。
|
|
390
|
-
*
|
|
391
|
-
* 每次探测是一次完整的 Codex CLI 启动(Windows 上 0.3-0.45s)。启动时每个 codex
|
|
392
|
-
* agent 都会调一次(21 个 agent 就是 21 次进程启动),并行创建 runner 后会同时抢
|
|
393
|
-
* CPU,反而更慢。这里缓存整个探测的 Promise:并发调用共享同一轮探测,失败结果也
|
|
394
|
-
* 缓存,避免热加载反复重试。
|
|
395
|
-
*
|
|
396
|
-
* 用 TTL 而不是永久缓存:用户可能在 daemon 运行期间升级 Codex CLI,过期的失败结论
|
|
397
|
-
* 不应永久黏住。
|
|
398
|
-
*/
|
|
399
|
-
const CODEX_AVAILABILITY_CACHE_TTL_MS = 60_000;
|
|
400
|
-
let codexAvailabilityCache = null;
|
|
401
|
-
/** 让测试与显式刷新(例如安装 Codex 后)能清掉缓存。 */
|
|
402
|
-
export function invalidateCodexAppServerAvailabilityCache() {
|
|
403
|
-
codexAvailabilityCache = null;
|
|
404
|
-
}
|
|
405
|
-
/** Daemon startup/hot reload use asynchronous probes; sync CLI callers share the cache. */
|
|
406
|
-
export async function getCodexAppServerAvailabilityAsync() {
|
|
407
|
-
const now = Date.now();
|
|
408
|
-
if (codexAvailabilityCache && now - codexAvailabilityCache.at < CODEX_AVAILABILITY_CACHE_TTL_MS) {
|
|
409
|
-
return codexAvailabilityCache.promise;
|
|
410
|
-
}
|
|
411
|
-
const promise = probeCodexAppServerAvailabilityAsync();
|
|
412
|
-
codexAvailabilityCache = { at: now, promise };
|
|
413
|
-
// 失败的 Promise 同样要能被后续调用复用,但不能产生未处理拒绝。
|
|
414
|
-
promise.catch(() => { });
|
|
415
|
-
return promise;
|
|
416
|
-
}
|
|
417
|
-
async function probeCodexAppServerAvailabilityAsync() {
|
|
418
|
-
const cliPath = resolveCodexCliPath();
|
|
419
|
-
const options = {
|
|
420
|
-
timeouts: [CODEX_CLI_PROBE_TIMEOUT_MS, CODEX_CLI_PROBE_RETRY_TIMEOUT_MS],
|
|
421
|
-
executable: cliPath ?? undefined,
|
|
422
|
-
onFailure: logCodexProbeFailure,
|
|
423
|
-
};
|
|
424
|
-
if (!cliPath) {
|
|
425
|
-
const powershellShim = resolveCodexPowerShellShimPath();
|
|
426
|
-
return {
|
|
427
|
-
available: false,
|
|
428
|
-
reason: powershellShim
|
|
429
|
-
? '检测到 codex.ps1,但当前 Windows 启动路径要求 codex.exe/codex.cmd/codex.bat;请重新安装 @openai/codex 以恢复 npm shim。'
|
|
430
|
-
: '未检测到 Codex CLI。',
|
|
431
|
-
};
|
|
432
|
-
}
|
|
433
|
-
let version;
|
|
434
|
-
try {
|
|
435
|
-
// Each probe is a full Codex CLI launch (~0.3-0.45s on Windows). Run the
|
|
436
|
-
// app-server probe concurrently; its result is only consulted after the
|
|
437
|
-
// version gate passes, so the decision order is unchanged.
|
|
438
|
-
const appServerProbe = probeCli('codex', ['app-server', '--help'], options);
|
|
439
|
-
appServerProbe.catch(() => { });
|
|
440
|
-
version = parseCodexCliVersion(await probeCli('codex', ['--version'], {
|
|
441
|
-
...options, validateOutput: output => parseCodexCliVersion(output) !== null,
|
|
442
|
-
})) ?? undefined;
|
|
443
|
-
if (!version)
|
|
444
|
-
return { available: false, reason: '无法读取 Codex CLI 版本。' };
|
|
445
|
-
if (!isCodexCliVersionSupported(version)) {
|
|
446
|
-
return { available: false, version, requiresUpgrade: true,
|
|
447
|
-
reason: `Codex CLI ${version} 低于最低要求 ${MIN_CODEX_CLI_VERSION}。请升级 Codex CLI:npm install -g @openai/codex@latest` };
|
|
448
|
-
}
|
|
449
|
-
await appServerProbe;
|
|
450
|
-
return { available: true, version };
|
|
451
|
-
}
|
|
452
|
-
catch (error) {
|
|
453
|
-
const detail = error;
|
|
454
|
-
return { available: false, version, reason: detail.code === 'ETIMEDOUT' || detail.killed
|
|
455
|
-
? 'Codex CLI 探测超时,请稍后重试。'
|
|
456
|
-
: `Codex CLI 探测失败:${error instanceof Error ? error.message : String(error)}` };
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
316
|
export class CodexRunner {
|
|
460
317
|
name = 'codex';
|
|
461
318
|
// turn/start persists a new user turn before runQuery resolves. App-server
|
|
@@ -481,6 +338,7 @@ export class CodexRunner {
|
|
|
481
338
|
threadExternalToolFingerprints = new Map();
|
|
482
339
|
threadExternalToolBoundaries = new Map();
|
|
483
340
|
trackedApprovalItems = new Map();
|
|
341
|
+
pendingMcpElicitations = new Map();
|
|
484
342
|
pendingToolDenials = new Map();
|
|
485
343
|
registeredSafeOutputCalls = new Map();
|
|
486
344
|
pendingInterrupts = new Map();
|
|
@@ -496,6 +354,9 @@ export class CodexRunner {
|
|
|
496
354
|
appServerClient = null;
|
|
497
355
|
/** Trusted fullaccess calls use a separate unmasked app-server process. */
|
|
498
356
|
fullAccessAppServerClient = null;
|
|
357
|
+
/** Executing sessions never share a process; metadata queries use the clients above. */
|
|
358
|
+
sessionAppServerClients = new Map();
|
|
359
|
+
appServerSessionOwners = new WeakMap();
|
|
499
360
|
retiredProviderClients = new Set();
|
|
500
361
|
providerClientRevisions = new WeakMap();
|
|
501
362
|
onSessionIdUpdate;
|
|
@@ -536,7 +397,6 @@ export class CodexRunner {
|
|
|
536
397
|
});
|
|
537
398
|
this.capabilities = {
|
|
538
399
|
taskRecovery: true,
|
|
539
|
-
clear: false,
|
|
540
400
|
compact: true,
|
|
541
401
|
fork: true,
|
|
542
402
|
forkAtTurn: true,
|
|
@@ -555,15 +415,17 @@ export class CodexRunner {
|
|
|
555
415
|
this.onSessionIdUpdate = callbacks.onSessionIdUpdate;
|
|
556
416
|
this.codexVersion = runtime?.codexVersion;
|
|
557
417
|
}
|
|
558
|
-
getAppServerClient(fullAccess = false, providerOverride) {
|
|
559
|
-
const
|
|
418
|
+
getAppServerClient(fullAccess = false, providerOverride, sessionId) {
|
|
419
|
+
const sessionClientKey = sessionId ? JSON.stringify([sessionId, fullAccess]) : undefined;
|
|
420
|
+
const existing = sessionClientKey ? this.sessionAppServerClients.get(sessionClientKey)
|
|
421
|
+
: fullAccess ? this.fullAccessAppServerClient : this.appServerClient;
|
|
560
422
|
const connection = this.currentProviderConfig(providerOverride);
|
|
561
423
|
const revision = connection.providerId ? catalogHash({
|
|
562
424
|
providerId: connection.providerId,
|
|
563
425
|
baseUrl: connection.baseUrl, apiKey: connection.apiKey,
|
|
564
426
|
headers: connection.headers, queryParams: connection.queryParams,
|
|
565
427
|
}) : undefined;
|
|
566
|
-
if (existing && (!revision || this.providerClientRevisions.get(existing) === revision))
|
|
428
|
+
if (existing && !existing.isClosed() && (!revision || this.providerClientRevisions.get(existing) === revision))
|
|
567
429
|
return existing;
|
|
568
430
|
if (existing)
|
|
569
431
|
this.retiredProviderClients.add(existing);
|
|
@@ -605,7 +467,11 @@ export class CodexRunner {
|
|
|
605
467
|
this.threadSubscriptions.set(threadId, { client, state: 'unsubscribed' });
|
|
606
468
|
}
|
|
607
469
|
});
|
|
608
|
-
if (
|
|
470
|
+
if (sessionClientKey) {
|
|
471
|
+
this.sessionAppServerClients.set(sessionClientKey, client);
|
|
472
|
+
this.appServerSessionOwners.set(client, sessionId);
|
|
473
|
+
}
|
|
474
|
+
else if (fullAccess) {
|
|
609
475
|
this.fullAccessAppServerClient = client;
|
|
610
476
|
}
|
|
611
477
|
else {
|
|
@@ -633,7 +499,32 @@ export class CodexRunner {
|
|
|
633
499
|
if (subscribed)
|
|
634
500
|
return subscribed.client;
|
|
635
501
|
const sessionId = this.findSessionKeyByThread(threadId);
|
|
636
|
-
return this.getAppServerClient(sessionId ? this.chatModes.get(sessionId) === 'fullaccess' : false);
|
|
502
|
+
return this.getAppServerClient(sessionId ? this.chatModes.get(sessionId) === 'fullaccess' : false, undefined, sessionId);
|
|
503
|
+
}
|
|
504
|
+
async reclaimSessionClient(sessionId, client) {
|
|
505
|
+
if (this.appServerSessionOwners.get(client) !== sessionId)
|
|
506
|
+
throw unsettledInterruptError('Codex 运行态回收');
|
|
507
|
+
logger.warn(`[CodexRunner] Reclaiming session runtime: ${JSON.stringify({ sessionId, ...client.getDiagnosticContext() })}`);
|
|
508
|
+
const clients = new Set([client, ...this.sessionAppServerClients.values(), ...this.retiredProviderClients]
|
|
509
|
+
.filter(candidate => this.appServerSessionOwners.get(candidate) === sessionId));
|
|
510
|
+
await Promise.all([...clients].map(candidate => candidate.close()));
|
|
511
|
+
for (const [key, cached] of this.sessionAppServerClients) {
|
|
512
|
+
if (clients.has(cached))
|
|
513
|
+
this.sessionAppServerClients.delete(key);
|
|
514
|
+
}
|
|
515
|
+
for (const retired of clients)
|
|
516
|
+
this.retiredProviderClients.delete(retired);
|
|
517
|
+
for (const [threadId, subscription] of this.threadSubscriptions) {
|
|
518
|
+
if (!clients.has(subscription.client))
|
|
519
|
+
continue;
|
|
520
|
+
this.threadSubscriptions.delete(threadId);
|
|
521
|
+
this.unbindExternalToolBoundary(threadId);
|
|
522
|
+
}
|
|
523
|
+
for (const record of [...this.unconfirmedInterrupts.values()]) {
|
|
524
|
+
if (clients.has(record.client))
|
|
525
|
+
record.confirm('app-server:process-exited');
|
|
526
|
+
}
|
|
527
|
+
logger.info(`[CodexRunner] Session runtime reclaimed; persisted backend retained: session=${sessionId}`);
|
|
637
528
|
}
|
|
638
529
|
markThreadSubscribed(client, threadId) {
|
|
639
530
|
const existing = this.threadSubscriptions.get(threadId);
|
|
@@ -662,12 +553,21 @@ export class CodexRunner {
|
|
|
662
553
|
let releasePromise;
|
|
663
554
|
releasePromise = Promise.resolve().then(async () => {
|
|
664
555
|
let released = false;
|
|
556
|
+
const startedAt = Date.now();
|
|
665
557
|
try {
|
|
558
|
+
const interrupts = [...this.unconfirmedInterrupts.values()]
|
|
559
|
+
.filter(record => record.threadId === threadId && record.client === client);
|
|
560
|
+
if (interrupts.length) {
|
|
561
|
+
logger.info(`[CodexRunner] Waiting for turn termination before unsubscribe: thread=${threadId} reason=${reason}`);
|
|
562
|
+
await withInterruptDeadline(Promise.all(interrupts.map(record => record.settled)), 'Codex termination before unsubscribe', CODEX_INTERRUPT_TIMEOUT_MS);
|
|
563
|
+
}
|
|
666
564
|
const unsubscribe = client.threadUnsubscribe;
|
|
565
|
+
let status;
|
|
667
566
|
if (typeof unsubscribe === 'function') {
|
|
668
567
|
if (options.waitForClose && typeof client.threadUnsubscribeAndWait === 'function') {
|
|
669
568
|
try {
|
|
670
|
-
await client.threadUnsubscribeAndWait.call(client, threadId, options.timeoutMs ?? CODEX_THREAD_HANDOFF_TIMEOUT_MS);
|
|
569
|
+
const response = await client.threadUnsubscribeAndWait.call(client, threadId, options.timeoutMs ?? CODEX_THREAD_HANDOFF_TIMEOUT_MS);
|
|
570
|
+
status = response?.status;
|
|
671
571
|
}
|
|
672
572
|
catch (error) {
|
|
673
573
|
// The unsubscribe RPC has already succeeded when this is a
|
|
@@ -675,15 +575,15 @@ export class CodexRunner {
|
|
|
675
575
|
// target resume decide whether the archive fallback is needed.
|
|
676
576
|
if (error?.code !== 'CODEX_THREAD_CLOSE_TIMEOUT')
|
|
677
577
|
throw error;
|
|
678
|
-
logger.
|
|
578
|
+
logger.info(`[CodexRunner] thread/closed not observed before handoff timeout: `
|
|
679
579
|
+ `thread=${threadId} reason=${reason}`);
|
|
680
580
|
}
|
|
681
581
|
}
|
|
682
582
|
else {
|
|
683
|
-
await unsubscribe.call(client, threadId);
|
|
583
|
+
status = (await unsubscribe.call(client, threadId))?.status;
|
|
684
584
|
}
|
|
685
585
|
}
|
|
686
|
-
logger.
|
|
586
|
+
logger.info(`[CodexRunner] Thread unsubscribe acknowledged: thread=${threadId} reason=${reason} status=${String(status ?? 'unknown')} waitForClose=${!!options.waitForClose} durationMs=${Date.now() - startedAt}`);
|
|
687
587
|
released = true;
|
|
688
588
|
return true;
|
|
689
589
|
}
|
|
@@ -711,61 +611,81 @@ export class CodexRunner {
|
|
|
711
611
|
});
|
|
712
612
|
return await releasePromise;
|
|
713
613
|
}
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
* cross-client handoff, this only covers the same connection: the owner is
|
|
717
|
-
* unsubscribed (and awaited) once before the bounded retries, and any other
|
|
718
|
-
* active-writer rejection is released to the caller unchanged.
|
|
719
|
-
*/
|
|
720
|
-
async resumeThreadAllowingWriterRelease(appServer, threadId, projectPath, threadOptions, previousAppServer) {
|
|
721
|
-
try {
|
|
722
|
-
return await appServer.threadResume(threadId, projectPath, threadOptions);
|
|
723
|
-
}
|
|
724
|
-
catch (error) {
|
|
725
|
-
if (!isCodexActiveWriterError(error) || (previousAppServer && previousAppServer !== appServer))
|
|
726
|
-
throw error;
|
|
727
|
-
}
|
|
728
|
-
const subscription = this.threadSubscriptions.get(threadId);
|
|
729
|
-
if (subscription?.client === appServer && subscription.state === 'subscribed') {
|
|
730
|
-
await this.releaseThreadSubscription(appServer, threadId, 'writer-release-wait', {
|
|
731
|
-
waitForClose: true,
|
|
732
|
-
timeoutMs: CODEX_THREAD_HANDOFF_TIMEOUT_MS,
|
|
733
|
-
});
|
|
734
|
-
}
|
|
735
|
-
for (const delayMs of CODEX_RESUME_WRITER_RETRY_DELAYS_MS) {
|
|
736
|
-
await new Promise(resolve => {
|
|
737
|
-
const timer = setTimeout(resolve, delayMs);
|
|
738
|
-
timer.unref?.();
|
|
739
|
-
});
|
|
614
|
+
async retryThreadWriterOperation(threadId, operation, attempt, shouldRetry = isCodexActiveWriterError) {
|
|
615
|
+
for (let attemptIndex = 0;; attemptIndex++) {
|
|
740
616
|
try {
|
|
741
|
-
return await
|
|
617
|
+
return await attempt();
|
|
742
618
|
}
|
|
743
619
|
catch (error) {
|
|
744
|
-
|
|
620
|
+
const delayMs = CODEX_THREAD_WRITER_RETRY_DELAYS_MS[attemptIndex];
|
|
621
|
+
if (delayMs === undefined || !shouldRetry(error))
|
|
745
622
|
throw error;
|
|
746
|
-
logger.warn(`[CodexRunner] Thread writer
|
|
623
|
+
logger.warn(`[CodexRunner] Thread writer ${operation} retry in ${delayMs}ms: thread=${threadId} `
|
|
624
|
+
+ `error=${error instanceof Error ? error.message : String(error)}`);
|
|
625
|
+
await new Promise(resolve => {
|
|
626
|
+
const timer = setTimeout(resolve, delayMs);
|
|
627
|
+
timer.unref?.();
|
|
628
|
+
});
|
|
747
629
|
}
|
|
748
630
|
}
|
|
749
|
-
return await appServer.threadResume(threadId, projectPath, threadOptions);
|
|
750
631
|
}
|
|
751
|
-
|
|
632
|
+
/** With a known owner, active-writer rejection goes to the verified handoff. */
|
|
633
|
+
async resumeThreadAllowingWriterRelease(appServer, threadId, projectPath, threadOptions, previousAppServer, signal) {
|
|
634
|
+
let releaseAttempted = false;
|
|
635
|
+
const shouldRetry = (error) => isCodexActiveWriterError(error) && !previousAppServer;
|
|
636
|
+
return await this.retryThreadWriterOperation(threadId, 'resume', async () => {
|
|
637
|
+
signal?.throwIfAborted();
|
|
638
|
+
try {
|
|
639
|
+
return await appServer.threadResume(threadId, projectPath, threadOptions);
|
|
640
|
+
}
|
|
641
|
+
catch (error) {
|
|
642
|
+
signal?.throwIfAborted();
|
|
643
|
+
if (!releaseAttempted && shouldRetry(error)) {
|
|
644
|
+
releaseAttempted = true;
|
|
645
|
+
const subscription = this.threadSubscriptions.get(threadId);
|
|
646
|
+
if (subscription?.client === appServer && subscription.state === 'subscribed') {
|
|
647
|
+
await this.releaseThreadSubscription(appServer, threadId, 'writer-release-wait', {
|
|
648
|
+
waitForClose: true,
|
|
649
|
+
timeoutMs: CODEX_THREAD_HANDOFF_TIMEOUT_MS,
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
throw error;
|
|
654
|
+
}
|
|
655
|
+
}, shouldRetry);
|
|
656
|
+
}
|
|
657
|
+
async prepareThreadSubscription(client, threadId, signal) {
|
|
658
|
+
signal?.throwIfAborted();
|
|
752
659
|
const existing = this.threadSubscriptions.get(threadId);
|
|
753
660
|
if (!existing)
|
|
754
661
|
return undefined;
|
|
755
|
-
if (existing.client ===
|
|
756
|
-
|
|
757
|
-
await existing.release.catch(() => undefined);
|
|
662
|
+
if (existing.client.isRunning?.() === false) {
|
|
663
|
+
this.threadSubscriptions.delete(threadId);
|
|
758
664
|
return undefined;
|
|
759
665
|
}
|
|
760
|
-
if (existing.
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
666
|
+
if (existing.release)
|
|
667
|
+
await existing.release;
|
|
668
|
+
signal?.throwIfAborted();
|
|
669
|
+
if (this.threadSubscriptions.get(threadId)?.state === 'subscribed') {
|
|
670
|
+
await this.retryThreadWriterOperation(threadId, 'release', async () => {
|
|
671
|
+
signal?.throwIfAborted();
|
|
672
|
+
const released = await this.releaseThreadSubscription(existing.client, threadId, 'resume-handoff', {
|
|
673
|
+
waitForClose: true,
|
|
674
|
+
timeoutMs: CODEX_THREAD_HANDOFF_TIMEOUT_MS,
|
|
675
|
+
});
|
|
676
|
+
if (!released) {
|
|
677
|
+
const error = new Error(`Codex thread ${threadId} is still owned by another app-server connection`);
|
|
678
|
+
error.code = CODEX_THREAD_ACTIVE_WRITER;
|
|
679
|
+
throw error;
|
|
680
|
+
}
|
|
764
681
|
});
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
682
|
+
}
|
|
683
|
+
if (typeof existing.client.threadLoadedList === 'function') {
|
|
684
|
+
const loaded = await existing.client.threadLoadedList();
|
|
685
|
+
signal?.throwIfAborted();
|
|
686
|
+
logger.info(`[CodexRunner] Writer handoff inspection: thread=${threadId} sameClient=${existing.client === client} loaded=${loaded.data.includes(threadId)}`);
|
|
687
|
+
if (loaded.data.includes(threadId)) {
|
|
688
|
+
await this.archiveThreadForHandoff(existing.client, client, threadId, signal);
|
|
769
689
|
}
|
|
770
690
|
}
|
|
771
691
|
return existing.client;
|
|
@@ -809,7 +729,7 @@ export class CodexRunner {
|
|
|
809
729
|
if ((await owner.threadLoadedList()).data.includes(threadId)) {
|
|
810
730
|
// Codex can keep an unsubscribed writer alive. Its per-thread archive
|
|
811
731
|
// tears down that runtime synchronously; unarchive preserves the UUID.
|
|
812
|
-
await this.archiveThreadForHandoff(owner, owner, threadId);
|
|
732
|
+
await this.archiveThreadForHandoff(owner, owner, threadId, signal);
|
|
813
733
|
}
|
|
814
734
|
if ((await owner.threadLoadedList()).data.includes(threadId)) {
|
|
815
735
|
throw new Error('Codex Provider repair could not release the thread writer');
|
|
@@ -829,7 +749,11 @@ export class CodexRunner {
|
|
|
829
749
|
throw new Error('Codex resume did not preserve the bound thread and current Provider');
|
|
830
750
|
}
|
|
831
751
|
}
|
|
832
|
-
async archiveThreadForHandoff(sourceClient, targetClient, threadId) {
|
|
752
|
+
async archiveThreadForHandoff(sourceClient, targetClient, threadId, signal) {
|
|
753
|
+
await this.retryThreadWriterOperation(threadId, 'archive-handoff', () => this.archiveThreadForHandoffOnce(sourceClient, targetClient, threadId, signal));
|
|
754
|
+
}
|
|
755
|
+
async archiveThreadForHandoffOnce(sourceClient, targetClient, threadId, signal) {
|
|
756
|
+
signal?.throwIfAborted();
|
|
833
757
|
const existing = this.threadSubscriptions.get(threadId);
|
|
834
758
|
if (existing && existing.client !== sourceClient) {
|
|
835
759
|
const error = new Error(`Codex thread ${threadId} ownership changed during handoff`);
|
|
@@ -842,6 +766,13 @@ export class CodexRunner {
|
|
|
842
766
|
error.code = CODEX_THREAD_ACTIVE_WRITER;
|
|
843
767
|
throw error;
|
|
844
768
|
}
|
|
769
|
+
await this.assertInterruptSettled(sessionId, threadId);
|
|
770
|
+
const status = (await sourceClient.threadRead(threadId, false, 2_000)).thread?.status?.type;
|
|
771
|
+
signal?.throwIfAborted();
|
|
772
|
+
logger.info(`[CodexRunner] Writer handoff readiness: thread=${threadId} sameClient=${sourceClient === targetClient} status=${status ?? 'unknown'}`);
|
|
773
|
+
if (status !== 'idle' && status !== 'notLoaded' && status !== 'systemError') {
|
|
774
|
+
throw unsettledInterruptError('Codex 会话交接');
|
|
775
|
+
}
|
|
845
776
|
// Old app-server versions can acknowledge unsubscribe while retaining the
|
|
846
777
|
// writer. Archive is the only per-thread operation that synchronously
|
|
847
778
|
// tears down that runtime; the target client restores it before resume.
|
|
@@ -854,16 +785,18 @@ export class CodexRunner {
|
|
|
854
785
|
}
|
|
855
786
|
let archived = false;
|
|
856
787
|
try {
|
|
788
|
+
logger.info(`[CodexRunner] Writer handoff archive begin: thread=${threadId} sameClient=${sourceClient === targetClient}`);
|
|
857
789
|
await archive.call(sourceClient, threadId);
|
|
858
790
|
archived = true;
|
|
859
791
|
await unarchive.call(targetClient, threadId);
|
|
792
|
+
logger.info(`[CodexRunner] Writer handoff restored: thread=${threadId} sameClient=${sourceClient === targetClient}`);
|
|
860
793
|
}
|
|
861
794
|
catch (error) {
|
|
862
795
|
if (archived) {
|
|
863
796
|
// Do not strand the user's rollout under archived_sessions when the
|
|
864
797
|
// target client fails midway through the compatibility handoff.
|
|
865
798
|
try {
|
|
866
|
-
await
|
|
799
|
+
await sourceClient.threadUnarchive(threadId);
|
|
867
800
|
this.threadSubscriptions.set(threadId, { client: sourceClient, state: 'subscribed' });
|
|
868
801
|
}
|
|
869
802
|
catch (restoreError) {
|
|
@@ -878,6 +811,7 @@ export class CodexRunner {
|
|
|
878
811
|
throw handoffError;
|
|
879
812
|
}
|
|
880
813
|
this.threadSubscriptions.set(threadId, { client: targetClient, state: 'subscribed' });
|
|
814
|
+
signal?.throwIfAborted();
|
|
881
815
|
}
|
|
882
816
|
resolveCanonicalEcApproval(toolInput, managedTempDir, expectedCredentialToken) {
|
|
883
817
|
const rawCommand = typeof toolInput.command === 'string' ? toolInput.command : '';
|
|
@@ -1134,11 +1068,12 @@ export class CodexRunner {
|
|
|
1134
1068
|
this.pruneThreadOperationLocks();
|
|
1135
1069
|
}
|
|
1136
1070
|
resetAppServerClient() {
|
|
1137
|
-
const clients = [...this.retiredProviderClients, this.appServerClient, this.fullAccessAppServerClient]
|
|
1071
|
+
const clients = [...this.retiredProviderClients, ...this.sessionAppServerClients.values(), this.appServerClient, this.fullAccessAppServerClient]
|
|
1138
1072
|
.filter((client) => !!client);
|
|
1139
1073
|
this.retiredProviderClients.clear();
|
|
1140
1074
|
this.appServerClient = null;
|
|
1141
1075
|
this.fullAccessAppServerClient = null;
|
|
1076
|
+
this.sessionAppServerClients.clear();
|
|
1142
1077
|
this.threadSubscriptions.clear();
|
|
1143
1078
|
this.threadExternalToolFingerprints.clear();
|
|
1144
1079
|
this.threadExternalToolBoundaries.clear();
|
|
@@ -1158,16 +1093,23 @@ export class CodexRunner {
|
|
|
1158
1093
|
}
|
|
1159
1094
|
}
|
|
1160
1095
|
/**
|
|
1161
|
-
* Codex
|
|
1162
|
-
* 窗口本身超过 550k 的模型才覆盖,其余保持 Codex 自带的默认策略。
|
|
1096
|
+
* Codex 的模型窗口与自动压缩阈值分开下发;未配置时阈值为 258400。
|
|
1163
1097
|
*/
|
|
1164
1098
|
buildAutoCompactThreadConfig(model) {
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1099
|
+
return model ? { model_auto_compact_token_limit: CODEX_FALLBACK_CONTEXT_TOKENS } : null;
|
|
1100
|
+
}
|
|
1101
|
+
async configuredContextPolicy(model, provider) {
|
|
1102
|
+
const threshold = readAgentCompactThreshold(this.resolvedConfig.agentAid, 'codex');
|
|
1103
|
+
let catalog;
|
|
1104
|
+
try {
|
|
1105
|
+
catalog = await getRunnerCatalog('codex', provider ? undefined : this.resolvedConfig.agentAid, this.currentProviderConfig(provider));
|
|
1106
|
+
}
|
|
1107
|
+
catch (error) {
|
|
1108
|
+
logger.debug('[CodexRunner] Context catalog unavailable; using 258400 fallback', error);
|
|
1109
|
+
}
|
|
1110
|
+
const policy = resolveAgentContextPolicy('codex', model, catalog, threshold);
|
|
1111
|
+
logger.info(`[CodexRunner] Context policy: ${JSON.stringify(policy)}`);
|
|
1112
|
+
return policy;
|
|
1171
1113
|
}
|
|
1172
1114
|
mergeThreadConfig(...configs) {
|
|
1173
1115
|
const merged = {};
|
|
@@ -1191,15 +1133,7 @@ export class CodexRunner {
|
|
|
1191
1133
|
}
|
|
1192
1134
|
return Object.keys(merged).length > 0 ? merged : null;
|
|
1193
1135
|
}
|
|
1194
|
-
async resolveCapabilityThreadConfig(projectPath) {
|
|
1195
|
-
// 每次调用按当前 effective 配置解析;构造期快照会让 capability/baseagentSkills 改动要等 runner 重建才生效。
|
|
1196
|
-
let agentConfig = this.resolvedConfig.agentConfig;
|
|
1197
|
-
if (this.resolvedConfig.agentAid) {
|
|
1198
|
-
try {
|
|
1199
|
-
agentConfig = resolveEffective({ self: this.resolvedConfig.agentAid }, { cache: true });
|
|
1200
|
-
}
|
|
1201
|
-
catch { }
|
|
1202
|
-
}
|
|
1136
|
+
async resolveCapabilityThreadConfig(projectPath, agentConfig = this.currentEffectiveAgentConfig(), denyProjectSkills = false) {
|
|
1203
1137
|
// 拿不到配置时按 baseagentSkills 缺省值(关闭)处理。
|
|
1204
1138
|
const fallbackConfig = {
|
|
1205
1139
|
skills: { include_instructions: false, bundled: { enabled: false }, config: [{ name: 'eclink', enabled: false }] },
|
|
@@ -1207,7 +1141,7 @@ export class CodexRunner {
|
|
|
1207
1141
|
if (!agentConfig)
|
|
1208
1142
|
return fallbackConfig;
|
|
1209
1143
|
try {
|
|
1210
|
-
const resolved = await resolveCodexCapabilityThreadConfigForProject(agentConfig, projectPath, 'codex');
|
|
1144
|
+
const resolved = await resolveCodexCapabilityThreadConfigForProject(agentConfig, projectPath, 'codex', denyProjectSkills ? { includeProjectSkills: false } : undefined);
|
|
1211
1145
|
const skills = this.configRecord(resolved.skills);
|
|
1212
1146
|
const configured = Array.isArray(skills?.config)
|
|
1213
1147
|
? skills.config.filter(entry => {
|
|
@@ -1228,6 +1162,17 @@ export class CodexRunner {
|
|
|
1228
1162
|
return fallbackConfig;
|
|
1229
1163
|
}
|
|
1230
1164
|
}
|
|
1165
|
+
currentEffectiveAgentConfig() {
|
|
1166
|
+
// 每次调用按当前 effective 配置解析;构造期快照会让 capability/baseagentSkills 改动要等 runner 重建才生效。
|
|
1167
|
+
let agentConfig = this.resolvedConfig.agentConfig;
|
|
1168
|
+
if (this.resolvedConfig.agentAid) {
|
|
1169
|
+
try {
|
|
1170
|
+
agentConfig = resolveEffective({ self: this.resolvedConfig.agentAid }, { cache: true });
|
|
1171
|
+
}
|
|
1172
|
+
catch { }
|
|
1173
|
+
}
|
|
1174
|
+
return agentConfig;
|
|
1175
|
+
}
|
|
1231
1176
|
configRecord(value) {
|
|
1232
1177
|
return value && typeof value === 'object' && !Array.isArray(value)
|
|
1233
1178
|
? value
|
|
@@ -1449,7 +1394,7 @@ export class CodexRunner {
|
|
|
1449
1394
|
// ── Permission ──
|
|
1450
1395
|
currentMode = 'readonly';
|
|
1451
1396
|
// per-call/per-session 权限模式:runQuery 按本次解析结果写入,审批回调(异步、按 sessionKey 路由)据此判定。
|
|
1452
|
-
// 避免多会话共享 this.currentMode 时的并发污染(与
|
|
1397
|
+
// 避免多会话共享 this.currentMode 时的并发污染(与 Claude runner 的 per-call permissionMode 同构)。
|
|
1453
1398
|
chatModes = new Map();
|
|
1454
1399
|
/** 将权限模式映射为 Codex app-server 的 approvalPolicy(纯函数,无副作用,供 per-call 派生用)。 */
|
|
1455
1400
|
toApprovalPolicy(mode) {
|
|
@@ -1534,7 +1479,7 @@ export class CodexRunner {
|
|
|
1534
1479
|
}
|
|
1535
1480
|
return Object.fromEntries([...paths].map(candidate => [candidate, 'write']));
|
|
1536
1481
|
}
|
|
1537
|
-
buildPermissionProfileConfig(sessionId, mode, projectPath, bootstrapAgentMdPath, personalSoulDir) {
|
|
1482
|
+
buildPermissionProfileConfig(sessionId, mode, projectPath, bootstrapAgentMdPath, personalSoulDir, disableProjectSkillDiscovery = false) {
|
|
1538
1483
|
const profileName = this.permissionProfileName(sessionId);
|
|
1539
1484
|
const managedTempDir = ensureSessionRuntimeDir(sessionId);
|
|
1540
1485
|
const network = {
|
|
@@ -1547,6 +1492,15 @@ export class CodexRunner {
|
|
|
1547
1492
|
onlyOtherAgents: true,
|
|
1548
1493
|
}))
|
|
1549
1494
|
relationAttachmentDenies[directory] = 'deny';
|
|
1495
|
+
const projectSkillDenies = {};
|
|
1496
|
+
// Windows runs each native skill probe behind a sandbox helper. Denying
|
|
1497
|
+
// disabled project skill roots avoids repeated walks and ACL refreshes.
|
|
1498
|
+
if (disableProjectSkillDiscovery) {
|
|
1499
|
+
for (const directory of getExistingCodexProjectSkillRoots(projectPath)) {
|
|
1500
|
+
projectSkillDenies[directory] = 'deny';
|
|
1501
|
+
projectSkillDenies[`${directory}/**`] = 'deny';
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1550
1504
|
const filesystem = compactCodexLinuxFilesystemRules({
|
|
1551
1505
|
...buildCodexProtectedFilesystemRules(resolveRoot(), {
|
|
1552
1506
|
selfAid: this.resolvedConfig.agentAid,
|
|
@@ -1566,8 +1520,9 @@ export class CodexRunner {
|
|
|
1566
1520
|
} : {}),
|
|
1567
1521
|
...(personalSoulDir ? {
|
|
1568
1522
|
[path.resolve(personalSoulDir)]: mode === 'readonly' ? 'read' : 'write',
|
|
1569
|
-
[path.
|
|
1523
|
+
[`${path.resolve(personalSoulDir)}/**`]: mode === 'readonly' ? 'read' : 'write',
|
|
1570
1524
|
} : {}),
|
|
1525
|
+
...projectSkillDenies,
|
|
1571
1526
|
...relationAttachmentDenies,
|
|
1572
1527
|
...(mode !== 'readonly' && managedTempDir ? {
|
|
1573
1528
|
[managedTempDir]: 'write',
|
|
@@ -1592,7 +1547,7 @@ export class CodexRunner {
|
|
|
1592
1547
|
},
|
|
1593
1548
|
};
|
|
1594
1549
|
}
|
|
1595
|
-
buildExecutionSandboxOptions(sessionId, mode, projectPath, bootstrapAgentMdPath, personalSoulDir, permissionContext = this.permissionContexts.get(sessionId) ?? {}) {
|
|
1550
|
+
buildExecutionSandboxOptions(sessionId, mode, projectPath, bootstrapAgentMdPath, personalSoulDir, permissionContext = this.permissionContexts.get(sessionId) ?? {}, disableProjectSkillDiscovery = false) {
|
|
1596
1551
|
const decision = resolvePhaseOneExecutionSandbox(mode, permissionContext.role);
|
|
1597
1552
|
// 系统会话明确声明不要沙箱:Codex 的 permission profile 以项目目录为中心,
|
|
1598
1553
|
// 而系统会话的读写边界($EVOLCORE_HOME 下的批次目录与记忆目录)与 cwd 无关,
|
|
@@ -1603,7 +1558,7 @@ export class CodexRunner {
|
|
|
1603
1558
|
decision,
|
|
1604
1559
|
permissionProfileConfig: sandboxOff
|
|
1605
1560
|
? undefined
|
|
1606
|
-
: this.buildPermissionProfileConfig(sessionId, decision.permissionMode, projectPath, bootstrapAgentMdPath, personalSoulDir),
|
|
1561
|
+
: this.buildPermissionProfileConfig(sessionId, decision.permissionMode, projectPath, bootstrapAgentMdPath, personalSoulDir, disableProjectSkillDiscovery),
|
|
1607
1562
|
sandbox: sandboxOff ? 'danger-full-access' : undefined,
|
|
1608
1563
|
sessionSandboxOff,
|
|
1609
1564
|
};
|
|
@@ -2016,6 +1971,12 @@ export class CodexRunner {
|
|
|
2016
1971
|
&& !matchesCodexTask(operationTarget, target);
|
|
2017
1972
|
}))
|
|
2018
1973
|
return;
|
|
1974
|
+
// A cancelled turn/start may still return a live turn. Its startup path
|
|
1975
|
+
// owns the subscription until that turn has been interrupted and drained.
|
|
1976
|
+
if ([...(operations ?? [])].some(operation => operation.startupPending
|
|
1977
|
+
&& operation.lockAcquired
|
|
1978
|
+
&& (!target || matchesCodexTask(this.targetForOperation(operation), target))))
|
|
1979
|
+
return;
|
|
2019
1980
|
const capturedController = this.activeAbortControllers.get(key);
|
|
2020
1981
|
const capturedStream = this.activeStreams.get(key);
|
|
2021
1982
|
const hadController = capturedController !== undefined;
|
|
@@ -2175,6 +2136,8 @@ export class CodexRunner {
|
|
|
2175
2136
|
}
|
|
2176
2137
|
async acquireThreadOperation(key, operation, signal) {
|
|
2177
2138
|
signal?.throwIfAborted();
|
|
2139
|
+
if (key.startsWith('thread:'))
|
|
2140
|
+
this.assertStartupSettled(undefined, key.slice('thread:'.length));
|
|
2178
2141
|
const lock = this.getThreadOperationLock(key);
|
|
2179
2142
|
const previous = lock.tail;
|
|
2180
2143
|
let releaseCurrent;
|
|
@@ -2222,12 +2185,34 @@ export class CodexRunner {
|
|
|
2222
2185
|
}
|
|
2223
2186
|
}
|
|
2224
2187
|
// ── Core: runQuery ──
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2188
|
+
assertStartupSettled(sessionId, threadId) {
|
|
2189
|
+
for (const [ownerSessionId, operations] of this.queryOperations) {
|
|
2190
|
+
if (ownerSessionId !== sessionId && !threadId)
|
|
2191
|
+
continue;
|
|
2192
|
+
if ([...operations].some(operation => operation.lockAcquired
|
|
2193
|
+
&& operation.startupPending && operation.controller.signal.aborted
|
|
2194
|
+
&& (ownerSessionId === sessionId || operation.threadId === threadId))) {
|
|
2195
|
+
throw unsettledInterruptError('Codex 会话初始化');
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
async openThreadWithDeadline(open, diagnostics, controller) {
|
|
2200
|
+
controller?.signal.throwIfAborted();
|
|
2201
|
+
const timer = controller ? setTimeout(() => {
|
|
2202
|
+
logger.warn(`[CodexRunner] Thread open timed out: ${JSON.stringify({ ...diagnostics(), timeoutMs: CODEX_THREAD_OPEN_TIMEOUT_MS })}`);
|
|
2203
|
+
controller.abort(Object.assign(new Error('Codex 会话初始化超时;旧初始化结束前已暂停该会话的后续执行(CODEX_THREAD_OPEN_TIMEOUT)'), { code: 'CODEX_THREAD_OPEN_TIMEOUT' }));
|
|
2204
|
+
}, CODEX_THREAD_OPEN_TIMEOUT_MS) : undefined;
|
|
2205
|
+
timer?.unref?.();
|
|
2206
|
+
try {
|
|
2207
|
+
return await open();
|
|
2208
|
+
}
|
|
2209
|
+
finally {
|
|
2210
|
+
if (timer)
|
|
2211
|
+
clearTimeout(timer);
|
|
2212
|
+
}
|
|
2229
2213
|
}
|
|
2230
|
-
async runQuery(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, sessionManager, modelOverride, runtimeEnv) {
|
|
2214
|
+
async runQuery(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, sessionManager, modelOverride, runtimeEnv, startupRecoveryAttempt = 0) {
|
|
2215
|
+
resolveRunInference('codex', modelOverride?.inference);
|
|
2231
2216
|
const topicBinding = modelOverride?.backend?.kind === 'topic';
|
|
2232
2217
|
if (topicBinding && (!modelOverride?.turn || modelOverride.turn.sessionId !== sessionId || !this.onSessionIdUpdate)) {
|
|
2233
2218
|
const error = new Error('topic backend run requires an active TurnLease and binding callback');
|
|
@@ -2243,27 +2228,35 @@ export class CodexRunner {
|
|
|
2243
2228
|
}
|
|
2244
2229
|
const topicAgentSessionId = topicBinding ? modelOverride?.backend?.agentSessionId ?? null : undefined;
|
|
2245
2230
|
const knownThreadId = topicBinding
|
|
2246
|
-
?
|
|
2231
|
+
? topicAgentSessionId || undefined
|
|
2247
2232
|
: initialAgentSessionId || this.activeSessions.get(sessionId);
|
|
2233
|
+
this.assertStartupSettled(sessionId, modelOverride?.recovery?.agentSessionId || knownThreadId);
|
|
2248
2234
|
const operationKey = this.threadOperationKey(modelOverride?.recovery?.agentSessionId || knownThreadId, sessionId);
|
|
2249
2235
|
this.dropExpiredPendingInterrupt(sessionId, modelOverride?.turn);
|
|
2236
|
+
let resolveSettled;
|
|
2250
2237
|
const operation = {
|
|
2251
2238
|
controller: new AbortController(),
|
|
2252
2239
|
taskId: modelOverride?.turn?.taskId ?? this.permissionContexts.get(sessionId)?.taskId,
|
|
2253
2240
|
generation: modelOverride?.turn?.generation ?? this.permissionContexts.get(sessionId)?.turn?.generation,
|
|
2241
|
+
threadId: modelOverride?.recovery?.agentSessionId || knownThreadId,
|
|
2254
2242
|
lockAcquired: false,
|
|
2243
|
+
startupPending: true,
|
|
2244
|
+
settled: new Promise(resolve => { resolveSettled = resolve; }),
|
|
2255
2245
|
};
|
|
2256
2246
|
const operationTarget = this.targetForOperation(operation);
|
|
2257
2247
|
const operations = this.queryOperations.get(sessionId) ?? new Set();
|
|
2258
2248
|
operations.add(operation);
|
|
2259
2249
|
this.queryOperations.set(sessionId, operations);
|
|
2260
2250
|
let releaseLock;
|
|
2251
|
+
let startup;
|
|
2261
2252
|
const release = () => {
|
|
2253
|
+
operation.startupPending = false;
|
|
2262
2254
|
operations.delete(operation);
|
|
2263
2255
|
if (this.queryOperations.get(sessionId) === operations && operations.size === 0) {
|
|
2264
2256
|
this.queryOperations.delete(sessionId);
|
|
2265
2257
|
}
|
|
2266
2258
|
releaseLock?.();
|
|
2259
|
+
resolveSettled();
|
|
2267
2260
|
};
|
|
2268
2261
|
try {
|
|
2269
2262
|
if (operationTarget && this.consumePendingInterrupt(sessionId, operationTarget)) {
|
|
@@ -2272,14 +2265,50 @@ export class CodexRunner {
|
|
|
2272
2265
|
await waitForCodexOperation(this.assertInterruptSettled(sessionId, modelOverride?.recovery?.agentSessionId || knownThreadId), operation.controller.signal);
|
|
2273
2266
|
releaseLock = await this.acquireThreadOperation(operationKey, 'thread/resume+turn/start', operation.controller.signal);
|
|
2274
2267
|
operation.lockAcquired = true;
|
|
2268
|
+
this.assertStartupSettled(sessionId, operation.threadId);
|
|
2275
2269
|
await waitForCodexOperation(this.assertInterruptSettled(sessionId, modelOverride?.recovery?.agentSessionId || knownThreadId), operation.controller.signal);
|
|
2276
|
-
|
|
2270
|
+
startup = this.runQueryLocked(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, sessionManager, modelOverride, runtimeEnv, operation.controller);
|
|
2271
|
+
const stream = await waitForCodexOperation(startup, operation.controller.signal);
|
|
2272
|
+
operation.controller.signal.throwIfAborted();
|
|
2273
|
+
operation.startupPending = false;
|
|
2277
2274
|
this.activeOperationReleases.set(sessionId, release);
|
|
2278
2275
|
this.activeOperationReleaseTargets.set(sessionId, operationTarget);
|
|
2279
2276
|
return this.holdThreadOperation(stream, sessionId, release);
|
|
2280
2277
|
}
|
|
2281
2278
|
catch (error) {
|
|
2282
|
-
|
|
2279
|
+
if (startup && operation.controller.signal.aborted && !operation.inputSubmitted && operation.client
|
|
2280
|
+
&& this.appServerSessionOwners.get(operation.client) === sessionId) {
|
|
2281
|
+
try {
|
|
2282
|
+
await this.reclaimSessionClient(sessionId, operation.client);
|
|
2283
|
+
}
|
|
2284
|
+
catch (reclaimError) {
|
|
2285
|
+
logger.error(`[CodexRunner] Session runtime reclamation unconfirmed: session=${sessionId} error=${String(reclaimError)}`);
|
|
2286
|
+
throw unsettledInterruptError('Codex 运行态回收', reclaimError);
|
|
2287
|
+
}
|
|
2288
|
+
await startup.then(async (stream) => {
|
|
2289
|
+
for await (const _event of stream) { /* Discard cancelled events after confirmed exit. */ }
|
|
2290
|
+
}).catch(() => undefined);
|
|
2291
|
+
release();
|
|
2292
|
+
if (error?.code === 'CODEX_THREAD_OPEN_TIMEOUT') {
|
|
2293
|
+
if (!operation.interrupted && startupRecoveryAttempt === 0) {
|
|
2294
|
+
logger.warn(`[CodexRunner] Retrying thread open on a fresh session runtime: session=${sessionId} thread=${operation.threadId ?? '<new>'}`);
|
|
2295
|
+
return this.runQuery(sessionId, prompt, projectPath, initialAgentSessionId, images, systemPromptAppend, sessionManager, modelOverride, runtimeEnv, 1);
|
|
2296
|
+
}
|
|
2297
|
+
throw Object.assign(new Error('Codex 会话初始化再次超时;已回收卡住的运行态,原话题和历史保留,可稍后在原话题重试(CODEX_THREAD_OPEN_TIMEOUT)'), { code: 'CODEX_THREAD_OPEN_TIMEOUT' });
|
|
2298
|
+
}
|
|
2299
|
+
throw error;
|
|
2300
|
+
}
|
|
2301
|
+
if (startup && operation.controller.signal.aborted) {
|
|
2302
|
+
logger.warn(`[CodexRunner] Cancelled startup awaiting backend settlement: session=${sessionId} thread=${operation.threadId ?? '<new>'}`);
|
|
2303
|
+
void startup.then(async (stream) => {
|
|
2304
|
+
for await (const _event of stream) { /* Discard the cancelled run. */ }
|
|
2305
|
+
}).catch(cleanupError => {
|
|
2306
|
+
logger.debug(`[CodexRunner] Cancelled startup settled: session=${sessionId} error=${String(cleanupError)}`);
|
|
2307
|
+
}).finally(release);
|
|
2308
|
+
}
|
|
2309
|
+
else {
|
|
2310
|
+
release();
|
|
2311
|
+
}
|
|
2283
2312
|
throw error;
|
|
2284
2313
|
}
|
|
2285
2314
|
}
|
|
@@ -2311,6 +2340,8 @@ export class CodexRunner {
|
|
|
2311
2340
|
throw new Error('Async question reply requires its original Codex backend');
|
|
2312
2341
|
}
|
|
2313
2342
|
await this.assertInterruptSettled(sessionId, agentSessionId);
|
|
2343
|
+
this.assertStartupSettled(sessionId, agentSessionId);
|
|
2344
|
+
operationController?.signal.throwIfAborted();
|
|
2314
2345
|
let resumingThread = !!agentSessionId;
|
|
2315
2346
|
const modelContextId = modelOverride?.model || this.modelContextId;
|
|
2316
2347
|
await assertRunnerModelAllowed('codex', modelContextId, this.currentProviderConfig(modelOverride?.provider));
|
|
@@ -2328,11 +2359,21 @@ export class CodexRunner {
|
|
|
2328
2359
|
}
|
|
2329
2360
|
this.chatModes.set(sessionId, callMode);
|
|
2330
2361
|
const callApprovalPolicy = this.toApprovalPolicy(callMode);
|
|
2331
|
-
const
|
|
2332
|
-
const
|
|
2362
|
+
const effectiveAgentConfig = this.currentEffectiveAgentConfig();
|
|
2363
|
+
const disableProjectSkillDiscovery = process.platform === 'win32'
|
|
2364
|
+
&& !isBaseagentSkillsEnabled(effectiveAgentConfig);
|
|
2365
|
+
const executionSandbox = this.buildExecutionSandboxOptions(sessionId, callMode, projectPath, modelOverride?.bootstrapAgentMdPath, modelOverride?.personalSoulDir, undefined, disableProjectSkillDiscovery);
|
|
2366
|
+
const capabilityConfig = await this.resolveCapabilityThreadConfig(projectPath, effectiveAgentConfig, disableProjectSkillDiscovery && !!executionSandbox.permissionProfileConfig);
|
|
2367
|
+
operationController?.signal.throwIfAborted();
|
|
2368
|
+
const appServer = this.getAppServerClient(callMode === 'fullaccess', modelOverride?.provider, sessionId);
|
|
2369
|
+
const openingOperation = [...(this.queryOperations.get(sessionId) ?? [])]
|
|
2370
|
+
.find(operation => operation.controller === operationController);
|
|
2371
|
+
if (openingOperation) {
|
|
2372
|
+
openingOperation.threadId = agentSessionId;
|
|
2373
|
+
openingOperation.client = appServer;
|
|
2374
|
+
}
|
|
2333
2375
|
this.dropExpiredPendingInterrupt(sessionId, modelOverride?.turn);
|
|
2334
2376
|
const effectiveApprovalPolicy = callApprovalPolicy;
|
|
2335
|
-
const capabilityConfig = await this.resolveCapabilityThreadConfig(projectPath);
|
|
2336
2377
|
const userInputConfig = { features: {
|
|
2337
2378
|
default_mode_request_user_input: modelOverride?.enableRequestUserInput
|
|
2338
2379
|
?? this.resolvedConfig.enableRequestUserInput ?? true,
|
|
@@ -2343,6 +2384,7 @@ export class CodexRunner {
|
|
|
2343
2384
|
if (callMode !== 'fullaccess')
|
|
2344
2385
|
await this.assertProactiveHookAvailability(sessionId, appServer);
|
|
2345
2386
|
const managedTempInstruction = this.managedTempInstruction(sessionId);
|
|
2387
|
+
const contextPolicy = await this.configuredContextPolicy(modelContextId, modelOverride?.provider);
|
|
2346
2388
|
const developerInstructions = [systemPromptAppend, managedTempInstruction].filter(Boolean).join('\n\n') || undefined;
|
|
2347
2389
|
let threadSessionToken = agentSessionId
|
|
2348
2390
|
? this.ensureThreadCredential(agentSessionId)
|
|
@@ -2363,7 +2405,7 @@ export class CodexRunner {
|
|
|
2363
2405
|
...(fallback
|
|
2364
2406
|
? { sandbox: 'danger-full-access' }
|
|
2365
2407
|
: executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
|
|
2366
|
-
config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(fallback ? undefined : executionSandbox.permissionProfileConfig, persistentRuntimeEnv ? { shell_environment_policy: { set: persistentRuntimeEnv } } : undefined, capabilityConfig, userInputConfig, this.buildAutoCompactThreadConfig(callModel), externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(sessionId, threadSessionToken, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined), this.buildLifecycleLockdownConfig(callMode)), callMode, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined),
|
|
2408
|
+
config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(fallback ? undefined : executionSandbox.permissionProfileConfig, persistentRuntimeEnv ? { shell_environment_policy: { set: persistentRuntimeEnv } } : undefined, capabilityConfig, userInputConfig, contextPolicy?.codexThreadConfig ?? this.buildAutoCompactThreadConfig(callModel), externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(sessionId, threadSessionToken, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined), this.buildLifecycleLockdownConfig(callMode)), callMode, callMode === 'fullaccess' ? runtimeEnv?.[AGENT_DELEGATION_TOKEN_ENV] : undefined),
|
|
2367
2409
|
...(developerInstructions ? { developerInstructions } : {}),
|
|
2368
2410
|
});
|
|
2369
2411
|
let threadOptions = buildThreadOptions();
|
|
@@ -2371,21 +2413,48 @@ export class CodexRunner {
|
|
|
2371
2413
|
`role=${executionSandbox.decision.role ?? 'none'} sandbox=${executionSandbox.decision.state}`);
|
|
2372
2414
|
let threadResponse;
|
|
2373
2415
|
let previousAppServer;
|
|
2416
|
+
let openPhase = 'preparing';
|
|
2417
|
+
const openDiagnostics = () => ({
|
|
2418
|
+
...appServer.getStartupDiagnostics(),
|
|
2419
|
+
sessionId,
|
|
2420
|
+
threadId: agentSessionId ?? null,
|
|
2421
|
+
taskId: openingOperation?.taskId ?? null,
|
|
2422
|
+
generation: openingOperation?.generation ?? null,
|
|
2423
|
+
mode: callMode,
|
|
2424
|
+
sandbox: executionSandbox.decision.state,
|
|
2425
|
+
innerSandboxFallback,
|
|
2426
|
+
phase: openPhase,
|
|
2427
|
+
});
|
|
2374
2428
|
const openThread = async () => {
|
|
2429
|
+
operationController?.signal.throwIfAborted();
|
|
2430
|
+
logger.info(`[CodexRunner] Opening thread: ${JSON.stringify({
|
|
2431
|
+
sessionId, threadId: agentSessionId ?? null, mode: callMode,
|
|
2432
|
+
taskId: openingOperation?.taskId ?? null, generation: openingOperation?.generation ?? null,
|
|
2433
|
+
...appServer.getDiagnosticContext(),
|
|
2434
|
+
})}`);
|
|
2375
2435
|
if (agentSessionId) {
|
|
2436
|
+
openPhase = 'provider-preparation';
|
|
2376
2437
|
await this.prepareSessionProvider(appServer, agentSessionId, operationController?.signal);
|
|
2438
|
+
operationController?.signal.throwIfAborted();
|
|
2377
2439
|
// A thread may have been loaded by the other permission-mode client.
|
|
2378
2440
|
// Release that one thread before asking this client to resume it.
|
|
2379
|
-
|
|
2441
|
+
openPhase = 'subscription-handoff';
|
|
2442
|
+
previousAppServer = await this.prepareThreadSubscription(appServer, agentSessionId, operationController?.signal);
|
|
2443
|
+
operationController?.signal.throwIfAborted();
|
|
2380
2444
|
try {
|
|
2381
|
-
|
|
2445
|
+
openPhase = 'thread/resume';
|
|
2446
|
+
return await this.resumeThreadAllowingWriterRelease(appServer, agentSessionId, projectPath, threadOptions, previousAppServer, operationController?.signal);
|
|
2382
2447
|
}
|
|
2383
2448
|
catch (error) {
|
|
2384
|
-
|
|
2449
|
+
operationController?.signal.throwIfAborted();
|
|
2450
|
+
if (isCodexActiveWriterError(error) && previousAppServer) {
|
|
2385
2451
|
// Some Codex builds acknowledge unsubscribe before unloading the
|
|
2386
2452
|
// runtime. Archive/unarchive is a synchronous per-thread teardown
|
|
2387
2453
|
// and preserves the same persisted thread id for the retry.
|
|
2388
|
-
|
|
2454
|
+
openPhase = 'writer-handoff';
|
|
2455
|
+
await this.archiveThreadForHandoff(previousAppServer, appServer, agentSessionId, operationController?.signal);
|
|
2456
|
+
operationController?.signal.throwIfAborted();
|
|
2457
|
+
openPhase = 'thread/resume';
|
|
2389
2458
|
return appServer.threadResume(agentSessionId, projectPath, threadOptions);
|
|
2390
2459
|
}
|
|
2391
2460
|
// A legacy main session can retain a provider ID after its rollout was
|
|
@@ -2394,6 +2463,7 @@ export class CodexRunner {
|
|
|
2394
2463
|
if (topicBinding || recoverySessionId || modelOverride?.asyncQuestionAnswer || !isCodexNoRolloutError(error))
|
|
2395
2464
|
throw error;
|
|
2396
2465
|
const missingThreadId = agentSessionId;
|
|
2466
|
+
openPhase = 'missing-history-recovery';
|
|
2397
2467
|
if (modelOverride?.capsule) {
|
|
2398
2468
|
const recovered = await modelOverride.capsule.recover(missingThreadId, prompt, systemPromptAppend);
|
|
2399
2469
|
prompt = recovered.prompt;
|
|
@@ -2421,13 +2491,16 @@ export class CodexRunner {
|
|
|
2421
2491
|
threadSessionToken = this.createThreadCredential();
|
|
2422
2492
|
threadOptions = buildThreadOptions(innerSandboxFallback);
|
|
2423
2493
|
logger.warn(`[CodexRunner] recovered missing rollout before input submission: session=${sessionId} thread=${missingThreadId}`);
|
|
2494
|
+
operationController?.signal.throwIfAborted();
|
|
2495
|
+
openPhase = 'thread/start';
|
|
2424
2496
|
return appServer.threadStart(projectPath, threadOptions);
|
|
2425
2497
|
}
|
|
2426
2498
|
}
|
|
2499
|
+
openPhase = 'thread/start';
|
|
2427
2500
|
return appServer.threadStart(projectPath, threadOptions);
|
|
2428
2501
|
};
|
|
2429
2502
|
try {
|
|
2430
|
-
threadResponse = await openThread
|
|
2503
|
+
threadResponse = await this.openThreadWithDeadline(openThread, openDiagnostics, operationController);
|
|
2431
2504
|
}
|
|
2432
2505
|
catch (error) {
|
|
2433
2506
|
if (!canFallbackFromInnerSandbox || !isNestedSandboxInitializationFailure(error))
|
|
@@ -2476,13 +2549,20 @@ export class CodexRunner {
|
|
|
2476
2549
|
logger.warn(`[CodexSandbox] inner sandbox initialization failed; retrying with outer H-class guard ` +
|
|
2477
2550
|
`session=${sessionId} occurrences=${circuit.occurrences}: ${detail}`);
|
|
2478
2551
|
threadOptions = buildThreadOptions(true);
|
|
2479
|
-
threadResponse = await openThread
|
|
2552
|
+
threadResponse = await this.openThreadWithDeadline(openThread, openDiagnostics, operationController);
|
|
2480
2553
|
}
|
|
2481
|
-
if (agentSessionId)
|
|
2482
|
-
this.assertResumedProvider(appServer, threadResponse, agentSessionId);
|
|
2483
2554
|
let threadId = threadResponse.thread?.id || agentSessionId;
|
|
2484
2555
|
if (!threadId)
|
|
2485
2556
|
throw new Error('Codex app-server did not return a thread id');
|
|
2557
|
+
if (openingOperation)
|
|
2558
|
+
openingOperation.threadId = threadId;
|
|
2559
|
+
if (operationController?.signal.aborted) {
|
|
2560
|
+
this.markThreadSubscribed(appServer, threadId);
|
|
2561
|
+
await this.releaseThreadSubscription(appServer, threadId, 'cancelled-thread-open');
|
|
2562
|
+
operationController.signal.throwIfAborted();
|
|
2563
|
+
}
|
|
2564
|
+
if (agentSessionId)
|
|
2565
|
+
this.assertResumedProvider(appServer, threadResponse, agentSessionId);
|
|
2486
2566
|
if (recoverySessionId && threadId !== recoverySessionId) {
|
|
2487
2567
|
throw new Error('Task recovery cannot replace the original Codex thread');
|
|
2488
2568
|
}
|
|
@@ -2546,6 +2626,10 @@ export class CodexRunner {
|
|
|
2546
2626
|
projectPath,
|
|
2547
2627
|
model: callModel,
|
|
2548
2628
|
modelContextId,
|
|
2629
|
+
...(contextPolicy ? {
|
|
2630
|
+
modelContextWindowTokens: contextPolicy.executionContextWindowTokens,
|
|
2631
|
+
autoCompactTokens: contextPolicy.effectiveAutoCompactThresholdTokens,
|
|
2632
|
+
} : {}),
|
|
2549
2633
|
committed: resumingThread,
|
|
2550
2634
|
persistenceFinalized: resumingThread,
|
|
2551
2635
|
streamedAgentMessageIds: new Set(),
|
|
@@ -2666,6 +2750,9 @@ export class CodexRunner {
|
|
|
2666
2750
|
}
|
|
2667
2751
|
try {
|
|
2668
2752
|
operationController?.signal.throwIfAborted();
|
|
2753
|
+
modelOverride?.onInputSubmitted?.();
|
|
2754
|
+
if (openingOperation)
|
|
2755
|
+
openingOperation.inputSubmitted = true;
|
|
2669
2756
|
const turnResponse = await appServer.turnStart(threadId, input, {
|
|
2670
2757
|
cwd: projectPath,
|
|
2671
2758
|
model: callModel,
|
|
@@ -2762,9 +2849,6 @@ export class CodexRunner {
|
|
|
2762
2849
|
async interrupt(sessionKey, target) {
|
|
2763
2850
|
const operations = this.queryOperations.get(sessionKey);
|
|
2764
2851
|
const matchingOperations = [...(operations ?? [])].filter(operation => target ? matchesCodexTask(this.targetForOperation(operation), target) : operation.lockAcquired);
|
|
2765
|
-
for (const operation of matchingOperations) {
|
|
2766
|
-
operation.controller.abort(Object.assign(new Error('Codex operation interrupted'), { name: 'AbortError' }));
|
|
2767
|
-
}
|
|
2768
2852
|
const controller = this.activeAbortControllers.get(sessionKey);
|
|
2769
2853
|
const activeTurn = this.activeTurns.get(sessionKey);
|
|
2770
2854
|
const matchingController = controller && (!target || matchesCodexTask(this.activeAbortTargets.get(sessionKey), target))
|
|
@@ -2787,6 +2871,10 @@ export class CodexRunner {
|
|
|
2787
2871
|
? this.interruptAppServerTurn(matchingTurn.threadId, matchingTurn.turnId)
|
|
2788
2872
|
: Promise.resolve();
|
|
2789
2873
|
const interruptSubagents = this.interruptSubagentTurns(sessionKey, matchingTurn?.threadId, target);
|
|
2874
|
+
for (const operation of matchingOperations) {
|
|
2875
|
+
operation.interrupted = true;
|
|
2876
|
+
operation.controller.abort(Object.assign(new Error('Codex operation interrupted'), { name: 'AbortError' }));
|
|
2877
|
+
}
|
|
2790
2878
|
// Only a task-scoped request may be retained for a runner that has not
|
|
2791
2879
|
// reached its first turn yet. A session-only interrupt must never poison
|
|
2792
2880
|
// a later task during this startup gap.
|
|
@@ -2810,7 +2898,13 @@ export class CodexRunner {
|
|
|
2810
2898
|
}
|
|
2811
2899
|
logger.info(`[CodexRunner] Interrupted ${target ? `task=${target.taskId} generation=${target.generation}` : 'session'}: ${sessionKey}`);
|
|
2812
2900
|
}
|
|
2813
|
-
|
|
2901
|
+
const startupOperations = matchingOperations.filter(operation => operation.lockAcquired && operation.startupPending);
|
|
2902
|
+
const startupSettlement = startupOperations.length
|
|
2903
|
+
? withInterruptDeadline(Promise.all(startupOperations.map(operation => operation.settled)), 'Codex cancelled startup settlement', CODEX_STARTUP_SETTLE_TIMEOUT_MS).catch(error => {
|
|
2904
|
+
logger.warn(`[CodexRunner] Cancelled startup still unsettled: session=${sessionKey} error=${String(error)}`);
|
|
2905
|
+
})
|
|
2906
|
+
: Promise.resolve();
|
|
2907
|
+
await Promise.all([interruptTurn, interruptSubagents, startupSettlement]);
|
|
2814
2908
|
}
|
|
2815
2909
|
async interruptSubagentTurns(sessionId, parentThreadId, target) {
|
|
2816
2910
|
const entries = [...this.activeSubagentTurns.entries()]
|
|
@@ -2858,20 +2952,37 @@ export class CodexRunner {
|
|
|
2858
2952
|
const subscribed = this.threadSubscriptions.get(threadId);
|
|
2859
2953
|
const client = subscribed
|
|
2860
2954
|
? subscribed.client
|
|
2861
|
-
: this.getAppServerClient(sessionId ? this.chatModes.get(sessionId) === 'fullaccess' : false);
|
|
2955
|
+
: this.getAppServerClient(sessionId ? this.chatModes.get(sessionId) === 'fullaccess' : false, undefined, sessionId);
|
|
2862
2956
|
const key = JSON.stringify([threadId, turnId]);
|
|
2863
2957
|
const previous = this.unconfirmedInterrupts.get(key);
|
|
2864
|
-
previous
|
|
2865
|
-
|
|
2866
|
-
|
|
2958
|
+
if (previous) {
|
|
2959
|
+
try {
|
|
2960
|
+
await withInterruptDeadline(previous.settled, 'Codex existing turn/interrupt', CODEX_INTERRUPT_TIMEOUT_MS);
|
|
2961
|
+
}
|
|
2962
|
+
catch (error) {
|
|
2963
|
+
logger.warn(`[CodexRunner] Existing interrupt still unconfirmed: thread=${threadId} turn=${turnId} error=${String(error)}`);
|
|
2964
|
+
}
|
|
2965
|
+
return;
|
|
2966
|
+
}
|
|
2967
|
+
const startedAt = Date.now();
|
|
2867
2968
|
let confirm;
|
|
2969
|
+
let settled = false;
|
|
2868
2970
|
const confirmed = new Promise(resolve => { confirm = resolve; });
|
|
2869
|
-
const
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
2971
|
+
const record = {
|
|
2972
|
+
sessionId, threadId, turnId, client, settled: confirmed,
|
|
2973
|
+
confirm: evidence => {
|
|
2974
|
+
if (settled)
|
|
2975
|
+
return;
|
|
2976
|
+
settled = true;
|
|
2977
|
+
if (this.unconfirmedInterrupts.get(key) === record)
|
|
2978
|
+
this.unconfirmedInterrupts.delete(key);
|
|
2979
|
+
record.unsubscribe?.();
|
|
2980
|
+
logger.info(`[CodexRunner] Interrupt confirmed: session=${sessionId} thread=${threadId} turn=${turnId} evidence=${evidence} durationMs=${Date.now() - startedAt}`);
|
|
2981
|
+
confirm();
|
|
2982
|
+
},
|
|
2874
2983
|
};
|
|
2984
|
+
this.unconfirmedInterrupts.set(key, record);
|
|
2985
|
+
logger.info(`[CodexRunner] Interrupt requested: session=${sessionId} thread=${threadId} turn=${turnId}`);
|
|
2875
2986
|
record.unsubscribe = client.onNotification?.(notification => {
|
|
2876
2987
|
const params = notification.params ?? {};
|
|
2877
2988
|
if ((params.threadId ?? params.thread_id) !== threadId)
|
|
@@ -2879,47 +2990,62 @@ export class CodexRunner {
|
|
|
2879
2990
|
if (notification.method === 'thread/closed'
|
|
2880
2991
|
|| (notification.method === 'turn/completed'
|
|
2881
2992
|
&& (params.turn?.id ?? params.turnId ?? params.turn_id) === turnId))
|
|
2882
|
-
|
|
2993
|
+
record.confirm(notification.method);
|
|
2883
2994
|
});
|
|
2995
|
+
const polling = new AbortController();
|
|
2884
2996
|
try {
|
|
2997
|
+
const acknowledged = client.turnInterrupt(threadId, turnId).then(accepted => {
|
|
2998
|
+
if (!accepted)
|
|
2999
|
+
throw new Error('Codex interrupt was not accepted');
|
|
3000
|
+
logger.info(`[CodexRunner] Interrupt acknowledged: session=${sessionId} thread=${threadId} turn=${turnId} durationMs=${Date.now() - startedAt}`);
|
|
3001
|
+
});
|
|
2885
3002
|
await withInterruptDeadline(Promise.race([
|
|
2886
|
-
|
|
2887
|
-
if (!accepted)
|
|
2888
|
-
throw new Error('Codex interrupt was not accepted');
|
|
2889
|
-
}),
|
|
3003
|
+
acknowledged.then(() => confirmed),
|
|
2890
3004
|
confirmed,
|
|
3005
|
+
(async () => {
|
|
3006
|
+
while (!polling.signal.aborted) {
|
|
3007
|
+
await waitForCodexDelay(250, polling.signal);
|
|
3008
|
+
await this.verifyInterruptRecord(key, record);
|
|
3009
|
+
if (settled)
|
|
3010
|
+
return;
|
|
3011
|
+
}
|
|
3012
|
+
})(),
|
|
2891
3013
|
]), 'Codex turn/interrupt', CODEX_INTERRUPT_TIMEOUT_MS);
|
|
2892
3014
|
}
|
|
2893
3015
|
catch (error) {
|
|
2894
3016
|
logger.warn(`[CodexRunner] Unconfirmed interrupt: thread=${threadId} turn=${turnId} error=${String(error)}`);
|
|
2895
3017
|
}
|
|
3018
|
+
finally {
|
|
3019
|
+
polling.abort();
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
async verifyInterruptRecord(key, record) {
|
|
3023
|
+
if (this.unconfirmedInterrupts.get(key) !== record)
|
|
3024
|
+
return;
|
|
3025
|
+
try {
|
|
3026
|
+
const response = await withInterruptDeadline(record.client.threadRead(record.threadId, false, 2_000), 'Codex interrupt verification', 2_000);
|
|
3027
|
+
const threadStatus = response.thread?.status?.type;
|
|
3028
|
+
logger.debug(`[CodexRunner] Interrupt verification: session=${record.sessionId} thread=${record.threadId} turn=${record.turnId} status=${threadStatus ?? 'unknown'}`);
|
|
3029
|
+
if (threadStatus === 'idle' || threadStatus === 'notLoaded') {
|
|
3030
|
+
if (this.unconfirmedInterrupts.get(key) === record)
|
|
3031
|
+
record.confirm(`thread/read:${threadStatus}`);
|
|
3032
|
+
return;
|
|
3033
|
+
}
|
|
3034
|
+
if (threadStatus !== undefined)
|
|
3035
|
+
return;
|
|
3036
|
+
const history = await withInterruptDeadline(record.client.threadRead(record.threadId, true, 2_000), 'Codex interrupt history verification', 2_000);
|
|
3037
|
+
const turn = history.thread?.turns?.find(turn => turn.id === record.turnId);
|
|
3038
|
+
if (turn && ['completed', 'failed', 'interrupted'].includes(String(turn.status))
|
|
3039
|
+
&& !history.thread?.turns?.some(turn => turn.status === 'inProgress')
|
|
3040
|
+
&& this.unconfirmedInterrupts.get(key) === record) {
|
|
3041
|
+
record.confirm('thread/read:terminal-history');
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
catch { /* Ambiguous execution remains fenced; report it below. */ }
|
|
2896
3045
|
}
|
|
2897
3046
|
async assertInterruptSettled(sessionId, threadId) {
|
|
2898
3047
|
const pending = [...this.unconfirmedInterrupts.entries()].filter(([, record]) => record.sessionId === sessionId || (threadId && record.threadId === threadId));
|
|
2899
|
-
await Promise.all(pending.map(
|
|
2900
|
-
try {
|
|
2901
|
-
const response = await withInterruptDeadline(record.client.threadRead(record.threadId, false, 2_000), 'Codex interrupt verification', 2_000);
|
|
2902
|
-
const threadStatus = response.thread?.status?.type;
|
|
2903
|
-
if (threadStatus === 'idle' || threadStatus === 'notLoaded') {
|
|
2904
|
-
if (this.unconfirmedInterrupts.get(key) === record) {
|
|
2905
|
-
this.unconfirmedInterrupts.delete(key);
|
|
2906
|
-
record.unsubscribe?.();
|
|
2907
|
-
}
|
|
2908
|
-
return;
|
|
2909
|
-
}
|
|
2910
|
-
if (threadStatus !== undefined)
|
|
2911
|
-
return;
|
|
2912
|
-
const history = await withInterruptDeadline(record.client.threadRead(record.threadId, true, 2_000), 'Codex interrupt history verification', 2_000);
|
|
2913
|
-
const turn = history.thread?.turns?.find(turn => turn.id === record.turnId);
|
|
2914
|
-
if (turn && ['completed', 'failed', 'interrupted'].includes(String(turn.status))
|
|
2915
|
-
&& !history.thread?.turns?.some(turn => turn.status === 'inProgress')
|
|
2916
|
-
&& this.unconfirmedInterrupts.get(key) === record) {
|
|
2917
|
-
this.unconfirmedInterrupts.delete(key);
|
|
2918
|
-
record.unsubscribe?.();
|
|
2919
|
-
}
|
|
2920
|
-
}
|
|
2921
|
-
catch { /* Ambiguous execution remains fenced; report it below. */ }
|
|
2922
|
-
}));
|
|
3048
|
+
await Promise.all(pending.map(([key, record]) => this.verifyInterruptRecord(key, record)));
|
|
2923
3049
|
if ([...this.unconfirmedInterrupts.values()].some(record => record.sessionId === sessionId || (threadId && record.threadId === threadId))) {
|
|
2924
3050
|
throw unsettledInterruptError('Codex');
|
|
2925
3051
|
}
|
|
@@ -3028,6 +3154,12 @@ export class CodexRunner {
|
|
|
3028
3154
|
this.cleanupChildThreadsForSession(sessionId);
|
|
3029
3155
|
this.activeOperationReleaseTargets.delete(sessionId);
|
|
3030
3156
|
this.pruneThreadOperationLocks();
|
|
3157
|
+
if (!this.queryOperations.get(sessionId)?.size) {
|
|
3158
|
+
const client = [...this.sessionAppServerClients.values()]
|
|
3159
|
+
.find(candidate => this.appServerSessionOwners.get(candidate) === sessionId);
|
|
3160
|
+
if (client)
|
|
3161
|
+
await this.reclaimSessionClient(sessionId, client);
|
|
3162
|
+
}
|
|
3031
3163
|
}
|
|
3032
3164
|
}
|
|
3033
3165
|
resolveSessionFile(agentSessionId, _projectPath) {
|
|
@@ -3051,29 +3183,8 @@ export class CodexRunner {
|
|
|
3051
3183
|
};
|
|
3052
3184
|
return search(sessionsDir);
|
|
3053
3185
|
}
|
|
3054
|
-
async clearSession(sessionId, _agentSessionId, _projectPath) {
|
|
3055
|
-
// Codex: 清空会话 = 下次 runQuery 不传 resumeId,自动创建新 thread
|
|
3056
|
-
const threadId = this.activeSessions.get(sessionId) ?? _agentSessionId;
|
|
3057
|
-
const subscription = this.threadSubscriptions.get(threadId);
|
|
3058
|
-
if (subscription) {
|
|
3059
|
-
await this.releaseThreadSubscription(subscription.client, threadId, 'session-cleared');
|
|
3060
|
-
}
|
|
3061
|
-
this.activeSessions.delete(sessionId);
|
|
3062
|
-
this.activeTurns.delete(sessionId);
|
|
3063
|
-
this.activeAbortTargets.delete(sessionId);
|
|
3064
|
-
this.activeStreamTargets.delete(sessionId);
|
|
3065
|
-
this.activeOperationReleaseTargets.delete(sessionId);
|
|
3066
|
-
this.activeOperationReleases.delete(sessionId);
|
|
3067
|
-
this.steeringTails.delete(sessionId);
|
|
3068
|
-
this.chatModes.delete(sessionId);
|
|
3069
|
-
this.threadProjectPaths.delete(threadId);
|
|
3070
|
-
this.unbindExternalToolBoundary(threadId);
|
|
3071
|
-
this.clearTrackedApprovalItemsForThread(threadId);
|
|
3072
|
-
this.pruneThreadOperationLocks();
|
|
3073
|
-
await this.onSessionIdUpdate?.(sessionId, '');
|
|
3074
|
-
return true;
|
|
3075
|
-
}
|
|
3076
3186
|
async compactSession(_sessionId, agentSessionId, _projectPath, modelOverride) {
|
|
3187
|
+
resolveRunInference('codex', modelOverride?.inference);
|
|
3077
3188
|
const startedAt = Date.now();
|
|
3078
3189
|
const finish = (result) => {
|
|
3079
3190
|
logger.info(`[CodexRunner] Compact result: thread=${agentSessionId} ok=${result.ok} code=${result.ok ? 'ok' : result.code} durationMs=${result.durationMs}`);
|
|
@@ -3084,27 +3195,35 @@ export class CodexRunner {
|
|
|
3084
3195
|
try {
|
|
3085
3196
|
await assertRunnerModelAllowed('codex', modelOverride?.model || this.modelContextId, this.currentProviderConfig(modelOverride?.provider));
|
|
3086
3197
|
const compactMode = normalizeExecutionPermissionMode(modelOverride?.permissionMode ?? this.chatModes.get(_sessionId) ?? this.currentMode);
|
|
3087
|
-
const appServer = this.getAppServerClient(compactMode === 'fullaccess', modelOverride?.provider);
|
|
3198
|
+
const appServer = this.getAppServerClient(compactMode === 'fullaccess', modelOverride?.provider, _sessionId);
|
|
3088
3199
|
compactAppServer = appServer;
|
|
3089
3200
|
await this.prepareSessionProvider(appServer, agentSessionId);
|
|
3090
3201
|
await this.prepareThreadSubscription(appServer, agentSessionId);
|
|
3091
3202
|
this.onCompactStart?.(_sessionId);
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3203
|
+
const contextPolicy = await this.configuredContextPolicy(modelOverride?.model || this.modelContextId, modelOverride?.provider);
|
|
3204
|
+
if (!contextPolicy) {
|
|
3205
|
+
try {
|
|
3206
|
+
await this.startAndWaitForCompact(appServer, agentSessionId);
|
|
3207
|
+
return finish({ ok: true, durationMs: Date.now() - startedAt });
|
|
3208
|
+
}
|
|
3209
|
+
catch (error) {
|
|
3210
|
+
if (!this.isThreadNotFoundError(error))
|
|
3211
|
+
throw error;
|
|
3212
|
+
}
|
|
3095
3213
|
}
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
throw error;
|
|
3099
|
-
logger.info(`[CodexRunner] Compact thread not loaded, resuming before compact: ${agentSessionId}`);
|
|
3214
|
+
{
|
|
3215
|
+
logger.info(`[CodexRunner] Resuming before compact to load thread/config: ${agentSessionId}`);
|
|
3100
3216
|
await ensureSessionRuntimeDirAsync(_sessionId);
|
|
3101
3217
|
const compactModel = stripContextWindowSuffix(modelOverride?.model || this.model);
|
|
3102
3218
|
const compactEffort = modelOverride?.effortMode === 'model_default'
|
|
3103
3219
|
? undefined
|
|
3104
3220
|
: modelOverride?.effort ?? this.effort;
|
|
3105
3221
|
const compactPolicy = this.toApprovalPolicy(compactMode);
|
|
3106
|
-
const
|
|
3107
|
-
const
|
|
3222
|
+
const effectiveAgentConfig = this.currentEffectiveAgentConfig();
|
|
3223
|
+
const disableProjectSkillDiscovery = process.platform === 'win32'
|
|
3224
|
+
&& !isBaseagentSkillsEnabled(effectiveAgentConfig);
|
|
3225
|
+
const executionSandbox = this.buildExecutionSandboxOptions(_sessionId, compactMode, _projectPath, undefined, undefined, undefined, disableProjectSkillDiscovery);
|
|
3226
|
+
const capabilityConfig = await this.resolveCapabilityThreadConfig(_projectPath, effectiveAgentConfig, disableProjectSkillDiscovery && !!executionSandbox.permissionProfileConfig);
|
|
3108
3227
|
const externalToolConfig = compactMode === 'fullaccess'
|
|
3109
3228
|
? {}
|
|
3110
3229
|
: await this.resolveExternalToolApprovalConfig(appServer, _projectPath, capabilityConfig, compactMode);
|
|
@@ -3119,7 +3238,7 @@ export class CodexRunner {
|
|
|
3119
3238
|
approvalPolicy: compactPolicy,
|
|
3120
3239
|
approvalsReviewer: 'user',
|
|
3121
3240
|
...(executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
|
|
3122
|
-
config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(executionSandbox.permissionProfileConfig, capabilityConfig, externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(_sessionId, compactSessionToken), this.buildLifecycleLockdownConfig(compactMode)), compactMode),
|
|
3241
|
+
config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(executionSandbox.permissionProfileConfig, capabilityConfig, externalToolConfig, contextPolicy?.codexThreadConfig, this.buildEvolcoreShellEnvironmentConfig(_sessionId, compactSessionToken), this.buildLifecycleLockdownConfig(compactMode)), compactMode),
|
|
3123
3242
|
});
|
|
3124
3243
|
this.assertResumedProvider(appServer, resumed, agentSessionId);
|
|
3125
3244
|
this.markThreadSubscribed(appServer, agentSessionId);
|
|
@@ -3424,8 +3543,11 @@ export class CodexRunner {
|
|
|
3424
3543
|
const sessionKey = context?.sessionId ?? this.findSessionKeyByThread(agentSessionId);
|
|
3425
3544
|
await ensureSessionRuntimeDirAsync(sessionKey);
|
|
3426
3545
|
const mode = normalizePermissionMode(context?.permissionMode).mode;
|
|
3427
|
-
const
|
|
3428
|
-
const
|
|
3546
|
+
const effectiveAgentConfig = this.currentEffectiveAgentConfig();
|
|
3547
|
+
const disableProjectSkillDiscovery = process.platform === 'win32'
|
|
3548
|
+
&& !isBaseagentSkillsEnabled(effectiveAgentConfig);
|
|
3549
|
+
const executionSandbox = this.buildExecutionSandboxOptions(sessionKey, mode, projectPath, undefined, undefined, context ?? {}, disableProjectSkillDiscovery);
|
|
3550
|
+
const capabilityConfig = await this.resolveCapabilityThreadConfig(projectPath, effectiveAgentConfig, disableProjectSkillDiscovery && !!executionSandbox.permissionProfileConfig);
|
|
3429
3551
|
// Fork against the connection that owns the source thread. Codex keeps
|
|
3430
3552
|
// normal and full-access threads on separate app-server clients; using the
|
|
3431
3553
|
// default client here makes full-access forks time out or lose the thread.
|
|
@@ -3434,13 +3556,14 @@ export class CodexRunner {
|
|
|
3434
3556
|
if (sessionKey)
|
|
3435
3557
|
await this.assertProactiveHookAvailability(sessionKey, appServer);
|
|
3436
3558
|
const forkSessionToken = this.createThreadCredential();
|
|
3559
|
+
const contextPolicy = await this.configuredContextPolicy(this.modelContextId);
|
|
3437
3560
|
const response = await appServer.threadFork(agentSessionId, projectPath, title, {
|
|
3438
3561
|
model: this.model,
|
|
3439
3562
|
effort: this.effort,
|
|
3440
3563
|
approvalPolicy: this.toApprovalPolicy(mode),
|
|
3441
3564
|
approvalsReviewer: 'user',
|
|
3442
3565
|
...(executionSandbox.sandbox ? { sandbox: executionSandbox.sandbox } : {}),
|
|
3443
|
-
config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(executionSandbox.permissionProfileConfig, capabilityConfig, externalToolConfig, this.buildEvolcoreShellEnvironmentConfig(sessionKey, forkSessionToken), this.buildLifecycleLockdownConfig(mode)), mode),
|
|
3566
|
+
config: this.sanitizeThreadEnvironmentConfig(this.mergeThreadConfig(executionSandbox.permissionProfileConfig, capabilityConfig, externalToolConfig, contextPolicy?.codexThreadConfig, this.buildEvolcoreShellEnvironmentConfig(sessionKey, forkSessionToken), this.buildLifecycleLockdownConfig(mode)), mode),
|
|
3444
3567
|
...(lastTurnId ? { lastTurnId } : {}),
|
|
3445
3568
|
});
|
|
3446
3569
|
const forkedThreadId = response.thread?.id;
|
|
@@ -3565,6 +3688,18 @@ export class CodexRunner {
|
|
|
3565
3688
|
const threadId = this.requestThreadId(params);
|
|
3566
3689
|
const turnId = params.turnId ?? params.turn_id;
|
|
3567
3690
|
const key = this.approvalItemKey(threadId, turnId, itemId);
|
|
3691
|
+
if (threadId && ['item/completed', 'turn/completed', 'thread/closed'].includes(notification.method)) {
|
|
3692
|
+
const completedTurnId = turnId ?? params.turn?.id;
|
|
3693
|
+
for (const pending of this.pendingMcpElicitations?.values() ?? []) {
|
|
3694
|
+
if (pending.threadId !== threadId)
|
|
3695
|
+
continue;
|
|
3696
|
+
if (notification.method === 'item/completed' && pending.itemId !== itemId)
|
|
3697
|
+
continue;
|
|
3698
|
+
if (notification.method !== 'thread/closed' && completedTurnId && pending.turnId !== completedTurnId)
|
|
3699
|
+
continue;
|
|
3700
|
+
pending.abort.abort();
|
|
3701
|
+
}
|
|
3702
|
+
}
|
|
3568
3703
|
if (notification.method === 'item/completed' && threadId && typeof itemId === 'string') {
|
|
3569
3704
|
this.registeredSafeOutputCalls.delete(JSON.stringify([threadId, itemId]));
|
|
3570
3705
|
}
|
|
@@ -3652,6 +3787,10 @@ export class CodexRunner {
|
|
|
3652
3787
|
clearTrackedApprovalItemsForThread(threadId) {
|
|
3653
3788
|
if (!threadId)
|
|
3654
3789
|
return;
|
|
3790
|
+
for (const pending of this.pendingMcpElicitations?.values() ?? []) {
|
|
3791
|
+
if (pending.threadId === threadId)
|
|
3792
|
+
pending.abort.abort();
|
|
3793
|
+
}
|
|
3655
3794
|
for (const [key, tracked] of this.trackedApprovalItems) {
|
|
3656
3795
|
if (tracked.threadId === threadId)
|
|
3657
3796
|
this.trackedApprovalItems.delete(key);
|
|
@@ -3727,8 +3866,7 @@ export class CodexRunner {
|
|
|
3727
3866
|
async handleAppServerRequest(request) {
|
|
3728
3867
|
const params = (request.params || {});
|
|
3729
3868
|
if (request.method === 'mcpServer/elicitation/request') {
|
|
3730
|
-
|
|
3731
|
-
return { action: 'cancel', content: null, _meta: null };
|
|
3869
|
+
return this.handleMcpElicitation(request, params);
|
|
3732
3870
|
}
|
|
3733
3871
|
if (request.method === 'item/tool/requestUserInput') {
|
|
3734
3872
|
const trackedItem = this.findTrackedApprovalItem(params);
|
|
@@ -4304,6 +4442,125 @@ export class CodexRunner {
|
|
|
4304
4442
|
logger.info(`[CodexRunner] unattended MCP approval denied: session=${sessionKey} tool=${toolName}`);
|
|
4305
4443
|
return this.denyUntrackedExternalToolApproval(params, 'permission_mode_denied', toolName);
|
|
4306
4444
|
}
|
|
4445
|
+
async handleMcpElicitation(request, params) {
|
|
4446
|
+
const threadId = this.requestThreadId(params);
|
|
4447
|
+
const sessionKey = this.findSessionKeyByThread(threadId);
|
|
4448
|
+
const context = this.permissionContexts.get(sessionKey);
|
|
4449
|
+
const server = typeof params.serverName === 'string' ? params.serverName : '';
|
|
4450
|
+
const confirmation = parseMcpConfirmation(params);
|
|
4451
|
+
const requestId = `codex-elicitation-${crypto.randomUUID()}`;
|
|
4452
|
+
const mode = this.chatModes.get(sessionKey) ?? this.currentMode;
|
|
4453
|
+
const toolName = `MCP:${server || 'unknown'}/elicitation`;
|
|
4454
|
+
const audit = (phase, response, reason) => {
|
|
4455
|
+
auditPermissionLifecycle({
|
|
4456
|
+
phase, requestId, sessionId: sessionKey,
|
|
4457
|
+
agentAid: context?.selfAid, agentName: context?.agentName, taskId: context?.taskId,
|
|
4458
|
+
permissionMode: normalizeExecutionPermissionMode(mode), role: context?.role,
|
|
4459
|
+
toolName, approvalMethod: request.method,
|
|
4460
|
+
decision: !response ? 'pending' : response.action === 'accept' ? 'allow' : 'deny',
|
|
4461
|
+
decisionSource: response?.action === 'cancel' ? 'infrastructure' : 'approval',
|
|
4462
|
+
reason, summary: JSON.stringify({ server, mode: params.mode ?? 'form' }),
|
|
4463
|
+
...(response?.action !== 'cancel' && response ? {
|
|
4464
|
+
approverOperatorId: context?.userId,
|
|
4465
|
+
approverChannelKey: context?.adapter?.channelKey ?? context?.channel,
|
|
4466
|
+
approverPrincipalId: context?.actor?.principalId,
|
|
4467
|
+
} : {}),
|
|
4468
|
+
});
|
|
4469
|
+
};
|
|
4470
|
+
audit('request');
|
|
4471
|
+
const cancel = (reason) => {
|
|
4472
|
+
logger.warn(`[CodexRunner] MCP elicitation cancelled: thread=${threadId ?? '<missing>'} server=${server || '<missing>'} reason=${reason}`);
|
|
4473
|
+
const response = cancelledMcpElicitation();
|
|
4474
|
+
audit('response', response, reason);
|
|
4475
|
+
audit('final', response, reason);
|
|
4476
|
+
return response;
|
|
4477
|
+
};
|
|
4478
|
+
if (!confirmation || !threadId || !server)
|
|
4479
|
+
return cancel('unsupported_elicitation');
|
|
4480
|
+
if (!context || !this.isThreadOwnedBySession(sessionKey, threadId))
|
|
4481
|
+
return cancel('elicitation_session_unbound');
|
|
4482
|
+
if (context.approvalInteractionPolicy === 'deny'
|
|
4483
|
+
|| !['request', 'bypass', 'fullaccess'].includes(mode))
|
|
4484
|
+
return cancel('permission_mode_denied');
|
|
4485
|
+
if (mode === 'fullaccess' && !this.isTrustedFullAccessSession(sessionKey))
|
|
4486
|
+
return cancel('fullaccess_context_untrusted');
|
|
4487
|
+
// MCP elicitation has no itemId in the app-server protocol. Bind only to a
|
|
4488
|
+
// unique live call on the same server and turn; honor tool_call_id when supplied.
|
|
4489
|
+
const currentTurnId = () => this.findActiveTurnId(threadId) ?? this.activeSubagentTurns.get(threadId)?.turnId;
|
|
4490
|
+
const activeTurnId = currentTurnId();
|
|
4491
|
+
const turnId = typeof params.turnId === 'string' ? params.turnId : activeTurnId;
|
|
4492
|
+
if (!turnId || turnId !== activeTurnId)
|
|
4493
|
+
return cancel('elicitation_turn_unbound');
|
|
4494
|
+
const callId = params._meta?.tool_call_id;
|
|
4495
|
+
const candidates = [...this.trackedApprovalItems.values()].filter(tracked => tracked.threadId === threadId && tracked.turnId === turnId
|
|
4496
|
+
&& tracked.item.type === 'mcpToolCall' && tracked.item.server === server
|
|
4497
|
+
&& typeof tracked.item.tool === 'string' && tracked.item.tool.length > 0
|
|
4498
|
+
&& Object.prototype.hasOwnProperty.call(tracked.item, 'arguments')
|
|
4499
|
+
&& (callId == null || tracked.itemId === callId));
|
|
4500
|
+
if (candidates.length !== 1)
|
|
4501
|
+
return cancel('elicitation_call_unbound');
|
|
4502
|
+
const tracked = candidates[0];
|
|
4503
|
+
const boundary = this.threadExternalToolBoundaries.get(threadId);
|
|
4504
|
+
const isAppCall = typeof tracked.item.mcpAppResourceUri === 'string'
|
|
4505
|
+
|| (tracked.item.appContext && typeof tracked.item.appContext === 'object');
|
|
4506
|
+
const toolInput = { server, tool: tracked.item.tool, arguments: tracked.item.arguments };
|
|
4507
|
+
const isAllowed = () => {
|
|
4508
|
+
if (this.permissionContexts.get(sessionKey) !== context
|
|
4509
|
+
|| (this.chatModes.get(sessionKey) ?? this.currentMode) !== mode
|
|
4510
|
+
|| context.approvalInteractionPolicy === 'deny'
|
|
4511
|
+
|| currentTurnId() !== turnId
|
|
4512
|
+
|| !this.isThreadOwnedBySession(sessionKey, threadId)
|
|
4513
|
+
|| ![...this.trackedApprovalItems.values()].includes(tracked))
|
|
4514
|
+
return false;
|
|
4515
|
+
if (mode === 'fullaccess')
|
|
4516
|
+
return this.isTrustedFullAccessSession(sessionKey);
|
|
4517
|
+
if (!this.threadExternalToolFingerprints.get(threadId)
|
|
4518
|
+
|| this.threadExternalToolBoundaries.get(threadId) !== boundary
|
|
4519
|
+
|| !boundary || (isAppCall ? boundary.deniedApps.has(server) : boundary.deniedMcpServers.has(server))
|
|
4520
|
+
|| (isAppCall && !boundary.allowAnyApp && !boundary.allowedApps.has(server))
|
|
4521
|
+
|| !this.resolvePermissionWorkspacePath({ threadId }))
|
|
4522
|
+
return false;
|
|
4523
|
+
if (context.policyHook?.(`MCP:${server}/${tracked.item.tool}`, toolInput)?.block)
|
|
4524
|
+
return false;
|
|
4525
|
+
const systemDecision = context.systemSessionCheck?.(`MCP:${server}/${tracked.item.tool}`, toolInput);
|
|
4526
|
+
return !systemDecision || systemDecision.allow;
|
|
4527
|
+
};
|
|
4528
|
+
if (!isAllowed())
|
|
4529
|
+
return cancel('elicitation_capability_denied');
|
|
4530
|
+
// Capture the authenticated recipient as well as the task context reference.
|
|
4531
|
+
const userId = context.userId;
|
|
4532
|
+
const channelKey = context.adapter?.channelKey ?? context.channel;
|
|
4533
|
+
const channelId = context.channelId;
|
|
4534
|
+
const taskId = context.taskId;
|
|
4535
|
+
const abort = new AbortController();
|
|
4536
|
+
const signals = [context.abortSignal, this.activeAbortControllers.get(sessionKey)?.signal].filter((signal) => !!signal);
|
|
4537
|
+
const onAbort = () => abort.abort();
|
|
4538
|
+
for (const signal of signals) {
|
|
4539
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
4540
|
+
if (signal.aborted)
|
|
4541
|
+
abort.abort();
|
|
4542
|
+
}
|
|
4543
|
+
this.pendingMcpElicitations.set(requestId, { threadId, turnId, itemId: tracked.itemId, abort });
|
|
4544
|
+
try {
|
|
4545
|
+
const response = await collectMcpConfirmation({
|
|
4546
|
+
sessionKey, server, message: confirmation.message, context, signal: abort.signal,
|
|
4547
|
+
isCurrent: () => isAllowed() && context.userId === userId && context.taskId === taskId
|
|
4548
|
+
&& context.channelId === channelId
|
|
4549
|
+
&& (context.adapter?.channelKey ?? context.channel) === channelKey,
|
|
4550
|
+
});
|
|
4551
|
+
audit('response', response, `elicitation_${response.action}`);
|
|
4552
|
+
audit('final', response, `elicitation_${response.action}`);
|
|
4553
|
+
return response;
|
|
4554
|
+
}
|
|
4555
|
+
catch (error) {
|
|
4556
|
+
return cancel(error instanceof Error ? error.message : 'elicitation_failed');
|
|
4557
|
+
}
|
|
4558
|
+
finally {
|
|
4559
|
+
this.pendingMcpElicitations.delete(requestId);
|
|
4560
|
+
for (const signal of signals)
|
|
4561
|
+
signal.removeEventListener('abort', onAbort);
|
|
4562
|
+
}
|
|
4563
|
+
}
|
|
4307
4564
|
async handleMcpToolApproval(params, trackedItem) {
|
|
4308
4565
|
const questions = Array.isArray(params.questions) ? params.questions : [];
|
|
4309
4566
|
if (questions.length === 0)
|
|
@@ -4688,7 +4945,12 @@ export class CodexRunner {
|
|
|
4688
4945
|
// readonly decision. The map entry alone is stale if the directory was
|
|
4689
4946
|
// replaced between preflight and the approval callback.
|
|
4690
4947
|
managedTempDir: permCtx?.managedTempDir ?? this.getManagedTempDir(sessionKey),
|
|
4691
|
-
grantedReadRoots:
|
|
4948
|
+
grantedReadRoots: [
|
|
4949
|
+
...(permCtx?.grantedReadRoots ?? []),
|
|
4950
|
+
...(!permCtx?.systemSessionCheck ? getExistingSelfAttachmentDirs(resolveRoot(), {
|
|
4951
|
+
selfAid: this.resolvedConfig.agentAid,
|
|
4952
|
+
}) : []),
|
|
4953
|
+
],
|
|
4692
4954
|
allowReadonlySourceDiagnostics: permCtx?.allowReadonlySourceDiagnostics === true,
|
|
4693
4955
|
} : undefined;
|
|
4694
4956
|
if (toolName === 'Bash')
|
|
@@ -5059,7 +5321,7 @@ export class CodexRunner {
|
|
|
5059
5321
|
resumeResponse = await appServer.threadResume(agentSessionId, projectPath);
|
|
5060
5322
|
}
|
|
5061
5323
|
catch (error) {
|
|
5062
|
-
if (isCodexActiveWriterError(error) && previousAppServer
|
|
5324
|
+
if (isCodexActiveWriterError(error) && previousAppServer) {
|
|
5063
5325
|
await this.archiveThreadForHandoff(previousAppServer, appServer, agentSessionId);
|
|
5064
5326
|
resumeResponse = await appServer.threadResume(agentSessionId, projectPath);
|
|
5065
5327
|
}
|
|
@@ -6360,7 +6622,9 @@ export class CodexRunner {
|
|
|
6360
6622
|
...state.tokenUsage,
|
|
6361
6623
|
...(terminalTokenUsage && typeof terminalTokenUsage === 'object' ? terminalTokenUsage : {}),
|
|
6362
6624
|
...(turn.contextUsage ?? state.tokenUsage?.contextUsage ?? state.tokenUsage?.context),
|
|
6363
|
-
}, state.modelContextId ?? state.model, this.pickNumber(state.tokenUsage?.modelContextWindow, state.tokenUsage?.model_context_window, terminalTokenUsage?.modelContextWindow, terminalTokenUsage?.model_context_window));
|
|
6625
|
+
}, state.modelContextId ?? state.model, state.modelContextWindowTokens ?? this.pickNumber(state.tokenUsage?.modelContextWindow, state.tokenUsage?.model_context_window, terminalTokenUsage?.modelContextWindow, terminalTokenUsage?.model_context_window));
|
|
6626
|
+
if (contextUsage && state.autoCompactTokens !== undefined)
|
|
6627
|
+
contextUsage.autoCompactTokens = state.autoCompactTokens;
|
|
6364
6628
|
const modelCalls = [
|
|
6365
6629
|
...(parentTokenUsage ? [{
|
|
6366
6630
|
call_index: 0,
|
|
@@ -6531,10 +6795,12 @@ export class CodexRunner {
|
|
|
6531
6795
|
this.activeOperationReleaseTargets.clear();
|
|
6532
6796
|
await Promise.all([
|
|
6533
6797
|
...[...this.retiredProviderClients].map(client => client.close()),
|
|
6798
|
+
...[...this.sessionAppServerClients.values()].map(client => client.close()),
|
|
6534
6799
|
this.appServerClient?.close(),
|
|
6535
6800
|
this.fullAccessAppServerClient?.close(),
|
|
6536
6801
|
]);
|
|
6537
6802
|
this.retiredProviderClients.clear();
|
|
6803
|
+
this.sessionAppServerClients.clear();
|
|
6538
6804
|
this.codexSessionFileAdapter.close();
|
|
6539
6805
|
this.appServerClient = null;
|
|
6540
6806
|
this.fullAccessAppServerClient = null;
|