nova-personal-agent-server 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +30 -2
- package/bin/novapersonal-server.mjs +4 -0
- package/package.json +61 -4
- package/resources/endpointing/volcengine-v1/LICENSE.silero-vad.txt +21 -0
- package/resources/endpointing/volcengine-v1/MANIFEST.json +31 -0
- package/resources/endpointing/volcengine-v1/silence-16k-s16le.pcm +0 -0
- package/resources/endpointing/volcengine-v1/speech-16k-s16le.pcm +0 -0
- package/resources/native/codex-sandbox-probe +0 -0
- package/resources/native/project-native/nova_project_native.node +0 -0
- package/resources/native-resources-v1.json +1 -0
- package/runtime/dist/eval/demos.js +156 -0
- package/runtime/dist/eval/fixture-host.js +385 -0
- package/runtime/dist/eval/fixtures.js +319 -0
- package/runtime/dist/eval/realtime/session-fixtures.js +474 -0
- package/runtime/dist/eval/scorecard.js +285 -0
- package/runtime/dist/eval/sim.js +43 -0
- package/runtime/dist/src/cascaded-text-provider.js +31 -0
- package/runtime/dist/src/cli.js +96 -0
- package/runtime/dist/src/composition/assembly.js +352 -0
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +455 -0
- package/runtime/dist/src/composition/production-composition.js +389 -0
- package/runtime/dist/src/composition/realtime-assembly.js +1330 -0
- package/runtime/dist/src/config/capability-registry.js +315 -0
- package/runtime/dist/src/config/cascaded-realtime-config.js +146 -0
- package/runtime/dist/src/config/coding-backends.js +8 -0
- package/runtime/dist/src/config/coding-profiles.js +98 -0
- package/runtime/dist/src/config/config.js +857 -0
- package/runtime/dist/src/config/diagnostics.js +139 -0
- package/runtime/dist/src/config/environment-contract.js +202 -0
- package/runtime/dist/src/config/self-hosted.js +23 -0
- package/runtime/dist/src/connectors/composio/client.js +195 -0
- package/runtime/dist/src/connectors/composio/google.js +208 -0
- package/runtime/dist/src/connectors/composio/index.js +334 -0
- package/runtime/dist/src/connectors/feishu/cli.js +220 -0
- package/runtime/dist/src/connectors/feishu/index.js +980 -0
- package/runtime/dist/src/connectors/macos/calendar.js +35 -0
- package/runtime/dist/src/connectors/macos/mail.js +32 -0
- package/runtime/dist/src/connectors/macos/reader.js +62 -0
- package/runtime/dist/src/conversation-voice-provider.js +41 -0
- package/runtime/dist/src/core/approval-port.js +9 -0
- package/runtime/dist/src/core/approval.js +1328 -0
- package/runtime/dist/src/core/calls.js +35 -0
- package/runtime/dist/src/core/camera-session.js +32 -0
- package/runtime/dist/src/core/causal-runtime.js +650 -0
- package/runtime/dist/src/core/clock.js +139 -0
- package/runtime/dist/src/core/context-view.js +156 -0
- package/runtime/dist/src/core/effects.js +62 -0
- package/runtime/dist/src/core/events.js +217 -0
- package/runtime/dist/src/core/executor-diagnostic.js +9 -0
- package/runtime/dist/src/core/ids.js +32 -0
- package/runtime/dist/src/core/media-store.js +104 -0
- package/runtime/dist/src/core/memory.js +296 -0
- package/runtime/dist/src/core/pending-decision.js +64 -0
- package/runtime/dist/src/core/ports.js +125 -0
- package/runtime/dist/src/core/runtime.js +1459 -0
- package/runtime/dist/src/core/schedule-tools.js +15 -0
- package/runtime/dist/src/core/sims.js +186 -0
- package/runtime/dist/src/core/slots.js +97 -0
- package/runtime/dist/src/core/source-processing-instructions.js +3 -0
- package/runtime/dist/src/core/source-processing-tools.js +12 -0
- package/runtime/dist/src/core/suggestions.js +143 -0
- package/runtime/dist/src/core/task-tools.js +22 -0
- package/runtime/dist/src/core/tool-schema.js +212 -0
- package/runtime/dist/src/core/trace.js +34 -0
- package/runtime/dist/src/core/work-tools.js +94 -0
- package/runtime/dist/src/desktop/desktop-camera-source.js +31 -0
- package/runtime/dist/src/desktop/desktop-camera.js +281 -0
- package/runtime/dist/src/desktop/desktop-control.js +140 -0
- package/runtime/dist/src/desktop/desktop-progress.js +162 -0
- package/runtime/dist/src/desktop/desktop-session.js +2106 -0
- package/runtime/dist/src/desktop/desktop-tasks.js +80 -0
- package/runtime/dist/src/desktop/desktop-wire.js +605 -0
- package/runtime/dist/src/desktop/phone-desktop-entry.js +17 -0
- package/runtime/dist/src/desktop/startup-error.js +18 -0
- package/runtime/dist/src/desktop/workbench-acceptance.js +262 -0
- package/runtime/dist/src/desktop-entry.js +106 -0
- package/runtime/dist/src/desktop.js +1092 -0
- package/runtime/dist/src/executors/acp/backends.js +105 -0
- package/runtime/dist/src/executors/acp/mcp.js +81 -0
- package/runtime/dist/src/executors/acp/preflight.js +14 -0
- package/runtime/dist/src/executors/acp/process-owner.js +112 -0
- package/runtime/dist/src/executors/acp/transport.js +760 -0
- package/runtime/dist/src/executors/acp/windows-launch.js +68 -0
- package/runtime/dist/src/executors/agent-controller.js +244 -0
- package/runtime/dist/src/executors/autoglm.js +376 -0
- package/runtime/dist/src/executors/browser-device.js +102 -0
- package/runtime/dist/src/executors/browser.js +61 -0
- package/runtime/dist/src/executors/camera.js +101 -0
- package/runtime/dist/src/executors/chromium-frame-source.js +173 -0
- package/runtime/dist/src/executors/codex/adapter-live.js +292 -0
- package/runtime/dist/src/executors/codex/adapter-project.js +1306 -0
- package/runtime/dist/src/executors/codex/app-server-schema.js +712 -0
- package/runtime/dist/src/executors/codex/app-server-transport.js +1798 -0
- package/runtime/dist/src/executors/codex/approval-protocol.js +439 -0
- package/runtime/dist/src/executors/codex/common.js +655 -0
- package/runtime/dist/src/executors/codex/contract.js +581 -0
- package/runtime/dist/src/executors/codex/controller.js +141 -0
- package/runtime/dist/src/executors/codex/credential-snapshot.js +195 -0
- package/runtime/dist/src/executors/codex/factory.js +463 -0
- package/runtime/dist/src/executors/codex/host-config.js +238 -0
- package/runtime/dist/src/executors/codex/host.js +17 -0
- package/runtime/dist/src/executors/codex/index.js +19 -0
- package/runtime/dist/src/executors/codex/launch-profile.js +37 -0
- package/runtime/dist/src/executors/codex/local-sessions.js +119 -0
- package/runtime/dist/src/executors/codex/managed-mcp.js +196 -0
- package/runtime/dist/src/executors/codex/process-owner.js +398 -0
- package/runtime/dist/src/executors/codex/production-host.js +887 -0
- package/runtime/dist/src/executors/codex/progress-instructions.js +10 -0
- package/runtime/dist/src/executors/codex/protocol.js +581 -0
- package/runtime/dist/src/executors/codex/safe-json.js +87 -0
- package/runtime/dist/src/executors/codex/session-title.js +61 -0
- package/runtime/dist/src/executors/codex/shared-home.js +29 -0
- package/runtime/dist/src/executors/codex/spawn-env.js +162 -0
- package/runtime/dist/src/executors/codex/turn-projection.js +435 -0
- package/runtime/dist/src/executors/codex/version.js +38 -0
- package/runtime/dist/src/executors/codex/windows-guardian.js +716 -0
- package/runtime/dist/src/executors/coding/intake-model.js +103 -0
- package/runtime/dist/src/executors/coding/intake.js +824 -0
- package/runtime/dist/src/executors/coding/json-completion.js +14 -0
- package/runtime/dist/src/executors/coding/target-resolution.js +61 -0
- package/runtime/dist/src/executors/coding/work-order.js +50 -0
- package/runtime/dist/src/executors/coding-executor.js +23 -0
- package/runtime/dist/src/executors/computer-backend.js +188 -0
- package/runtime/dist/src/executors/computer-device.js +187 -0
- package/runtime/dist/src/executors/computer-worker.js +125 -0
- package/runtime/dist/src/executors/computer.js +100 -0
- package/runtime/dist/src/executors/device-lock.js +127 -0
- package/runtime/dist/src/executors/frame-source.js +29 -0
- package/runtime/dist/src/executors/gui-evidence.js +30 -0
- package/runtime/dist/src/executors/gui-execution.js +237 -0
- package/runtime/dist/src/executors/gui-runner.js +88 -0
- package/runtime/dist/src/executors/host-executor-capability.js +12 -0
- package/runtime/dist/src/executors/index.js +13 -0
- package/runtime/dist/src/executors/mcp-client.js +198 -0
- package/runtime/dist/src/executors/mcp.js +210 -0
- package/runtime/dist/src/executors/mobile-android.js +180 -0
- package/runtime/dist/src/executors/mobile-ios.js +303 -0
- package/runtime/dist/src/executors/mobile.js +78 -0
- package/runtime/dist/src/executors/search-mcp.js +146 -0
- package/runtime/dist/src/executors/search.js +524 -0
- package/runtime/dist/src/executors/task-resources.js +38 -0
- package/runtime/dist/src/executors/vision/assess.js +296 -0
- package/runtime/dist/src/executors/vision/controller-core.js +373 -0
- package/runtime/dist/src/executors/vision/controller.js +164 -0
- package/runtime/dist/src/executors/vision/lifecycle.js +69 -0
- package/runtime/dist/src/executors/vision.js +5 -0
- package/runtime/dist/src/executors/watcher.js +718 -0
- package/runtime/dist/src/http/bounded-response.js +37 -0
- package/runtime/dist/src/index.js +56 -0
- package/runtime/dist/src/knowledge/assembly.js +60 -0
- package/runtime/dist/src/knowledge/documents.js +520 -0
- package/runtime/dist/src/knowledge/embeddings.js +201 -0
- package/runtime/dist/src/knowledge/mcp.js +218 -0
- package/runtime/dist/src/knowledge/parse-worker.js +122 -0
- package/runtime/dist/src/knowledge/references.js +51 -0
- package/runtime/dist/src/knowledge/service.js +526 -0
- package/runtime/dist/src/knowledge/store-client.js +185 -0
- package/runtime/dist/src/knowledge/store-worker.js +843 -0
- package/runtime/dist/src/knowledge/types.js +2 -0
- package/runtime/dist/src/mcp/http-server.js +177 -0
- package/runtime/dist/src/mem0/resource.js +35 -0
- package/runtime/dist/src/mem0/store-worker.js +330 -0
- package/runtime/dist/src/memory/blackboard-session.js +205 -0
- package/runtime/dist/src/memory/blackboard-store.js +194 -0
- package/runtime/dist/src/memory/blackboard-worker.js +369 -0
- package/runtime/dist/src/memory/entry.js +39 -0
- package/runtime/dist/src/memory/factory.js +20 -0
- package/runtime/dist/src/memory/personal-memory-inspection.js +18 -0
- package/runtime/dist/src/memory/personal-memory.js +10 -0
- package/runtime/dist/src/memory/prerecall.js +20 -0
- package/runtime/dist/src/memory/provenance.js +17 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +194 -0
- package/runtime/dist/src/memory/retrieval.js +235 -0
- package/runtime/dist/src/memory/sensitivity.js +261 -0
- package/runtime/dist/src/memory-ledger/models.js +98 -0
- package/runtime/dist/src/memory-ledger/store-client.js +210 -0
- package/runtime/dist/src/memory-ledger/store-worker.js +130 -0
- package/runtime/dist/src/memory-ledger/store.js +597 -0
- package/runtime/dist/src/memory-substrate/candidates.js +16 -0
- package/runtime/dist/src/memory-substrate/consolidation.js +124 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +111 -0
- package/runtime/dist/src/memory-substrate/life-operations.js +280 -0
- package/runtime/dist/src/memory-substrate/markdown-repository.js +610 -0
- package/runtime/dist/src/memory-substrate/migration.js +87 -0
- package/runtime/dist/src/memory-substrate/profile-source-input.js +9 -0
- package/runtime/dist/src/memory-substrate/purge.js +398 -0
- package/runtime/dist/src/memory-substrate/resolution.js +32 -0
- package/runtime/dist/src/memory-substrate/resource.js +867 -0
- package/runtime/dist/src/memory-substrate/retrieval.js +85 -0
- package/runtime/dist/src/memory-substrate/source-operations.js +306 -0
- package/runtime/dist/src/memory-substrate/source-processing.js +326 -0
- package/runtime/dist/src/memory-substrate/source-state.js +93 -0
- package/runtime/dist/src/memory-substrate/store.js +534 -0
- package/runtime/dist/src/memory-substrate/workspace-projections.js +106 -0
- package/runtime/dist/src/memory-substrate/workspace.js +21 -0
- package/runtime/dist/src/model/jev-client.js +25 -0
- package/runtime/dist/src/model/model-adapters.js +64 -0
- package/runtime/dist/src/model/model-gateway.js +399 -0
- package/runtime/dist/src/model/model-lane.js +34 -0
- package/runtime/dist/src/model/model-purpose.js +5 -0
- package/runtime/dist/src/model/personal-writer.js +361 -0
- package/runtime/dist/src/model/proactivity.js +72 -0
- package/runtime/dist/src/model/prompting.js +279 -0
- package/runtime/dist/src/model/task-verifier.js +217 -0
- package/runtime/dist/src/model/vision-capability.js +10 -0
- package/runtime/dist/src/news/feeds.js +114 -0
- package/runtime/dist/src/news/jev-ranking.js +25 -0
- package/runtime/dist/src/news/ranking.js +26 -0
- package/runtime/dist/src/news/service.js +262 -0
- package/runtime/dist/src/notifications/adapters/feishu.js +10 -0
- package/runtime/dist/src/notifications/adapters/nova.js +15 -0
- package/runtime/dist/src/notifications/content.js +15 -0
- package/runtime/dist/src/notifications/contracts.js +9 -0
- package/runtime/dist/src/notifications/feed.js +8 -0
- package/runtime/dist/src/notifications/service.js +412 -0
- package/runtime/dist/src/notifications/store.js +4 -0
- package/runtime/dist/src/personal-agent/app-context.js +113 -0
- package/runtime/dist/src/personal-agent/approval-scope.js +8 -0
- package/runtime/dist/src/personal-agent/coding-targets.js +82 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +94 -0
- package/runtime/dist/src/personal-agent/contracts.js +32 -0
- package/runtime/dist/src/personal-agent/conversation-runtime.js +536 -0
- package/runtime/dist/src/personal-agent/conversations.js +187 -0
- package/runtime/dist/src/personal-agent/daily-brief.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2403 -0
- package/runtime/dist/src/personal-agent/intake-task.js +37 -0
- package/runtime/dist/src/personal-agent/life.js +260 -0
- package/runtime/dist/src/personal-agent/memory-overview.js +19 -0
- package/runtime/dist/src/personal-agent/profile-sources.js +34 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +244 -0
- package/runtime/dist/src/personal-agent/project-digests.js +242 -0
- package/runtime/dist/src/personal-agent/sampling.js +20 -0
- package/runtime/dist/src/personal-agent/schedule-agent.js +60 -0
- package/runtime/dist/src/personal-agent/schedule-api.js +61 -0
- package/runtime/dist/src/personal-agent/schedule-presets.js +13 -0
- package/runtime/dist/src/personal-agent/schedule-reference.js +3 -0
- package/runtime/dist/src/personal-agent/scheduled-response-scope.js +38 -0
- package/runtime/dist/src/personal-agent/scheduled-run-authority.js +44 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +280 -0
- package/runtime/dist/src/personal-agent/scheduled-time.js +99 -0
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +109 -0
- package/runtime/dist/src/personal-agent/source-priority.js +142 -0
- package/runtime/dist/src/personal-agent/source-processing-agent.js +158 -0
- package/runtime/dist/src/personal-agent/source-walk.js +25 -0
- package/runtime/dist/src/personal-agent/sources.js +1484 -0
- package/runtime/dist/src/personal-agent/store-lock-worker.js +17 -0
- package/runtime/dist/src/personal-agent/store.js +146 -0
- package/runtime/dist/src/personal-agent/task-loop.js +163 -0
- package/runtime/dist/src/personal-agent/tasks.js +920 -0
- package/runtime/dist/src/personal-agent/turn-deadline.js +55 -0
- package/runtime/dist/src/personal-agent/understanding.js +160 -0
- package/runtime/dist/src/personal-agent/workbench-context.js +239 -0
- package/runtime/dist/src/projects/confirmed-project-capability.js +60 -0
- package/runtime/dist/src/projects/host-paths.js +133 -0
- package/runtime/dist/src/projects/managed-workspace-maintenance.js +351 -0
- package/runtime/dist/src/projects/project-confirmation.js +486 -0
- package/runtime/dist/src/projects/project-native-resource.js +284 -0
- package/runtime/dist/src/projects/project-node-files.js +169 -0
- package/runtime/dist/src/projects/project-root-file.js +16 -0
- package/runtime/dist/src/projects/project-state.js +504 -0
- package/runtime/dist/src/projects/project-store-files.js +1271 -0
- package/runtime/dist/src/projects/project-store.js +1345 -0
- package/runtime/dist/src/realtime/aoq.js +141 -0
- package/runtime/dist/src/realtime/bridge.js +652 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +1669 -0
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +219 -0
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +478 -0
- package/runtime/dist/src/realtime/cascaded/gemini-speech.js +232 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +37 -0
- package/runtime/dist/src/realtime/cascaded/ports.js +2 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +216 -0
- package/runtime/dist/src/realtime/cascaded/qwen-llm.js +7 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-asr.js +110 -0
- package/runtime/dist/src/realtime/cascaded/self-hosted-tts.js +137 -0
- package/runtime/dist/src/realtime/cascaded/transcribe.js +42 -0
- package/runtime/dist/src/realtime/coding-progress-narration.js +28 -0
- package/runtime/dist/src/realtime/confirmation-turn-isolation.js +586 -0
- package/runtime/dist/src/realtime/dictation.js +28 -0
- package/runtime/dist/src/realtime/evidence.js +276 -0
- package/runtime/dist/src/realtime/floor.js +43 -0
- package/runtime/dist/src/realtime/frontend-instructions.js +195 -0
- package/runtime/dist/src/realtime/gemini.js +517 -0
- package/runtime/dist/src/realtime/history.js +122 -0
- package/runtime/dist/src/realtime/host-delivery.js +1711 -0
- package/runtime/dist/src/realtime/integrated-wire-profile.js +128 -0
- package/runtime/dist/src/realtime/memory-board.js +105 -0
- package/runtime/dist/src/realtime/openai-wire-profile.js +46 -0
- package/runtime/dist/src/realtime/playback.js +242 -0
- package/runtime/dist/src/realtime/project-confirmation-flow.js +1428 -0
- package/runtime/dist/src/realtime/prompt-language.js +17 -0
- package/runtime/dist/src/realtime/protocol.js +428 -0
- package/runtime/dist/src/realtime/provider-projection.js +526 -0
- package/runtime/dist/src/realtime/provider-session.js +491 -0
- package/runtime/dist/src/realtime/qwen-transport.js +144 -0
- package/runtime/dist/src/realtime/qwen.js +1377 -0
- package/runtime/dist/src/realtime/recall.js +341 -0
- package/runtime/dist/src/realtime/service-ports.js +8 -0
- package/runtime/dist/src/realtime/service-state.js +259 -0
- package/runtime/dist/src/realtime/service.js +1726 -0
- package/runtime/dist/src/realtime/session-state.js +684 -0
- package/runtime/dist/src/realtime/session.js +1976 -0
- package/runtime/dist/src/realtime/speech-prep.js +63 -0
- package/runtime/dist/src/realtime/streaming-speech.js +120 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +136 -0
- package/runtime/dist/src/realtime/telemetry.js +144 -0
- package/runtime/dist/src/realtime/tool-continuations.js +1510 -0
- package/runtime/dist/src/realtime/transport.js +8 -0
- package/runtime/dist/src/realtime/usage.js +55 -0
- package/runtime/dist/src/realtime/user-origin-binding.js +173 -0
- package/runtime/dist/src/realtime/volcengine/ark.js +428 -0
- package/runtime/dist/src/realtime/volcengine/asr.js +573 -0
- package/runtime/dist/src/realtime/volcengine/audio.js +39 -0
- package/runtime/dist/src/realtime/volcengine/endpointing-capability.js +834 -0
- package/runtime/dist/src/realtime/volcengine/livekit-endpointing.js +714 -0
- package/runtime/dist/src/realtime/volcengine/local-eot-executor.js +33 -0
- package/runtime/dist/src/realtime/volcengine/protocol.js +247 -0
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +237 -0
- package/runtime/dist/src/realtime/volcengine/tts.js +444 -0
- package/runtime/dist/src/realtime/volcengine/websocket.js +293 -0
- package/runtime/dist/src/server/aoq-chat-server.js +497 -0
- package/runtime/dist/src/server/client-pairing.js +192 -0
- package/runtime/dist/src/server/client-protocol.js +87 -0
- package/runtime/dist/src/server/client-server.js +312 -0
- package/runtime/dist/src/server/server-config.js +72 -0
- package/runtime/dist/src/server-entry.js +135 -0
- package/runtime/dist/src/storage/bounded-json.js +63 -0
- package/runtime/dist/src/storage/native-file-lock.js +8 -0
- package/runtime/dist/src/storage/native-resource-snapshot.js +41 -0
- package/runtime/dist/src/storage/private-database.js +120 -0
- package/runtime/dist/src/text/canonical-json.js +60 -0
- package/runtime/dist/src/text/python-number.js +18 -0
- package/runtime/dist/src/text/python-text.js +92 -0
- package/runtime/dist/src/text/unicode-casefold.js +29 -0
- package/runtime/dist/src/text/unicode-normalize.js +138 -0
- package/runtime/dist/src/text/unicode-tables.js +210 -0
- package/runtime/dist/src/understanding/candidates.js +77 -0
- package/runtime/dist/src/understanding/fixture.js +7 -0
- package/runtime/dist/src/understanding/jev.js +20 -0
- package/runtime/dist/src/understanding/pipeline.js +38 -0
- package/runtime/dist/src/voicemem/store-client.js +476 -0
- package/runtime/dist/src/voicemem/store-worker.js +380 -0
- package/runtime/dist/src/voicemem/versioned-memory.js +170 -0
- package/runtime/scripts/pair-device.mjs +109 -0
- package/src/command.mjs +48 -0
|
@@ -0,0 +1,1306 @@
|
|
|
1
|
+
import { taskGrantService } from '../../personal-agent/tasks.js';
|
|
2
|
+
import { acquireTaskResources, taskResourcesBusy, quarantineTaskResources, taskResourcesUncertain } from '../task-resources.js';
|
|
3
|
+
import { managedMcpResources } from './managed-mcp.js';
|
|
4
|
+
import { basename } from 'node:path';
|
|
5
|
+
import { compareCodePoints } from '../../text/canonical-json.js';
|
|
6
|
+
import { stripLikePython } from '../../text/python-text.js';
|
|
7
|
+
import { realpath } from 'node:fs/promises';
|
|
8
|
+
import { readLocalCodexSessions, readLocalCodexProjects, localRolloutAvailable } from './local-sessions.js';
|
|
9
|
+
import { hostPersistentHomeFromConfig, hostWorkspaceFromConfig } from '../../projects/host-paths.js';
|
|
10
|
+
import { hostWorkspacePath } from '../../projects/host-paths.js';
|
|
11
|
+
import { MAX_PROJECT_SESSION_TITLE, normalizeProjectSessionTitle } from '../../projects/project-state.js';
|
|
12
|
+
import { CodexTransportError } from './app-server-transport.js';
|
|
13
|
+
import { CODEX_PROJECT_APPROVAL_MANIFEST, CODEX_PROJECT_MANIFEST, validateCodexRequest, } from './contract.js';
|
|
14
|
+
import { ProjectStateError, } from '../../projects/project-store.js';
|
|
15
|
+
import { consumeHostExecutorCapability } from '../host-executor-capability.js';
|
|
16
|
+
import { USER_PRIORITY } from '../../core/memory.js';
|
|
17
|
+
import { ProjectResolutionError, } from '../coding-executor.js';
|
|
18
|
+
import { MAX_CONCURRENT_WORK, deriveSessionTitle } from '../../core/work-tools.js';
|
|
19
|
+
import { CodexLiveAdapter } from './adapter-live.js';
|
|
20
|
+
import { createCodexAdapterSharedState, failureHandoff, failureStage, } from './common.js';
|
|
21
|
+
/** Recent-project budget for display, local discovery and rich session history. */
|
|
22
|
+
const MAX_ROSTER = 10;
|
|
23
|
+
/** Whether a stored title is what importing `catalogTitle` produces: normalized, or normalized plus a ` (n)` uniqueness suffix. */
|
|
24
|
+
function sameSessionTitle(stored, catalogTitle) {
|
|
25
|
+
try {
|
|
26
|
+
const expected = normalizeProjectSessionTitle([...catalogTitle].slice(0, MAX_PROJECT_SESSION_TITLE).join('')).display;
|
|
27
|
+
if (stored === expected)
|
|
28
|
+
return true;
|
|
29
|
+
const suffixed = /^(.+) \((\d+)\)$/u.exec(stored);
|
|
30
|
+
if (suffixed === null)
|
|
31
|
+
return false;
|
|
32
|
+
const room = Math.max(1, MAX_PROJECT_SESSION_TITLE - [...` (${suffixed[2]})`].length);
|
|
33
|
+
return suffixed[1] === stripLikePython([...expected].slice(0, room).join(''));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const LEGACY_CODEX_BACKEND = Object.freeze({ backend_id: 'codex', backend_profile_id: 'codex:legacy' });
|
|
40
|
+
export class ProjectCodexAdapter {
|
|
41
|
+
manifest;
|
|
42
|
+
#localCodexHome;
|
|
43
|
+
#defaultBackend;
|
|
44
|
+
#localSessionIds = new Set();
|
|
45
|
+
#localProjects = null;
|
|
46
|
+
#sessionProjectPaths = new Map();
|
|
47
|
+
#catalogHealthy = false;
|
|
48
|
+
#catalogTimer = null;
|
|
49
|
+
#catalogRefresh = null;
|
|
50
|
+
#store;
|
|
51
|
+
#confirmation;
|
|
52
|
+
#transportFactory;
|
|
53
|
+
#projectViewObservers = new Set();
|
|
54
|
+
#projectContextObservers = new Set();
|
|
55
|
+
// ponytail: one status snapshot shared by every run's live adapter, so `status` reports the last
|
|
56
|
+
// run that touched it; per-slot status is the upgrade path once the host asks for it.
|
|
57
|
+
#liveState = createCodexAdapterSharedState();
|
|
58
|
+
#status = new CodexLiveAdapter(NULL_TRANSPORT, undefined, { sharedState: this.#liveState });
|
|
59
|
+
#confirmedBindings = new WeakMap();
|
|
60
|
+
#retainedTransportCleanups = new Set();
|
|
61
|
+
#resourceKeys;
|
|
62
|
+
#slotWaiters = new Set();
|
|
63
|
+
taskResource() { return this.#resourceKeys?.length === 1 ? this.#resourceKeys[0] : null; }
|
|
64
|
+
#slots = new Map();
|
|
65
|
+
#taskWorkspaces = new Map();
|
|
66
|
+
taskPort = {
|
|
67
|
+
quarantineResources: () => { quarantineTaskResources(this.#resourceKeys ?? []); },
|
|
68
|
+
inspectSession: async (sessionId) => {
|
|
69
|
+
const snapshot = await this.#store.snapshot(), session = snapshot.sessions.find(item => item.session_id === sessionId);
|
|
70
|
+
if (!session)
|
|
71
|
+
return 'task_session_not_found';
|
|
72
|
+
if (session.state !== 'ready')
|
|
73
|
+
return 'task_session_' + session.state;
|
|
74
|
+
try {
|
|
75
|
+
await this.#store.revalidateWorkspace(session.workspace_id);
|
|
76
|
+
if (!await this.#rolloutAvailable(session))
|
|
77
|
+
return 'task_session_resume_unavailable';
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return 'task_session_resume_unavailable';
|
|
81
|
+
}
|
|
82
|
+
if (this.#slots.has(session.workspace_id))
|
|
83
|
+
return 'task_session_running';
|
|
84
|
+
return null;
|
|
85
|
+
},
|
|
86
|
+
resolveSession: async (sessionId) => {
|
|
87
|
+
const snapshot = await this.#store.snapshot(), session = snapshot.sessions.find(item => item.session_id === sessionId);
|
|
88
|
+
const workspace = snapshot.workspaces.find(item => item.workspace_id === session?.workspace_id);
|
|
89
|
+
if (!session || !workspace)
|
|
90
|
+
throw Error('session_not_found');
|
|
91
|
+
const activeSlot = this.#slots.get(workspace.workspace_id);
|
|
92
|
+
const activeBinding = activeSlot === undefined ? undefined : this.#taskWorkspaces.get(activeSlot.work.work_id);
|
|
93
|
+
const liveStartingSession = session.state === 'starting' && activeSlot !== undefined && activeSlot.live !== null
|
|
94
|
+
&& activeBinding?.workspace_id === workspace.workspace_id && activeBinding.session_id === sessionId;
|
|
95
|
+
if (session.state !== 'ready' && !liveStartingSession)
|
|
96
|
+
throw Error('session_not_found');
|
|
97
|
+
await this.#store.revalidateWorkspace(workspace.workspace_id);
|
|
98
|
+
if (activeSlot && this.#taskWorkspaces.get(activeSlot.work.work_id)?.session_id !== sessionId)
|
|
99
|
+
throw Error('session_active');
|
|
100
|
+
return { project: workspace.display_name, session_id: sessionId, active: !!activeSlot, ...(activeSlot ? { work_id: activeSlot.work.work_id } : {}) };
|
|
101
|
+
},
|
|
102
|
+
cancelTask: (workId) => this.#cancelWork(workId) ? 'cancelling' : 'not_running',
|
|
103
|
+
taskDirectory: async (workId) => {
|
|
104
|
+
const workspaceId = this.#taskWorkspaces.get(workId)?.workspace_id;
|
|
105
|
+
return workspaceId === undefined ? null : hostWorkspacePath(await this.#store.revalidateWorkspace(workspaceId));
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
#snapshot = null;
|
|
109
|
+
#publicView = Object.freeze({
|
|
110
|
+
workspace_display_name: null,
|
|
111
|
+
session_title: null,
|
|
112
|
+
roster: [],
|
|
113
|
+
pending_confirmation: false,
|
|
114
|
+
pending_confirmation_busy: false,
|
|
115
|
+
});
|
|
116
|
+
#publicWorkspaceId = null;
|
|
117
|
+
#refreshSequence = 0;
|
|
118
|
+
#initializePromise = null;
|
|
119
|
+
#projectCommitActive = false;
|
|
120
|
+
#closed = false;
|
|
121
|
+
#closePromise = null;
|
|
122
|
+
constructor(options) {
|
|
123
|
+
this.manifest = options.codexApproval === undefined
|
|
124
|
+
? CODEX_PROJECT_MANIFEST
|
|
125
|
+
: CODEX_PROJECT_APPROVAL_MANIFEST;
|
|
126
|
+
this.#resourceKeys = managedMcpResources(options.managedMcp);
|
|
127
|
+
this.#defaultBackend = options.defaultBackend ?? (() => LEGACY_CODEX_BACKEND);
|
|
128
|
+
this.#localCodexHome = options.localCodexHome;
|
|
129
|
+
this.#store = options.store;
|
|
130
|
+
this.#confirmation = options.confirmation;
|
|
131
|
+
this.#transportFactory = options.transportFactory;
|
|
132
|
+
if (options.onProjectView !== undefined)
|
|
133
|
+
this.#projectViewObservers.add(options.onProjectView);
|
|
134
|
+
}
|
|
135
|
+
/** Exact controller owned by this adapter; host assembly uses it for spoken confirmation. */
|
|
136
|
+
get confirmationController() {
|
|
137
|
+
return this.#confirmation;
|
|
138
|
+
}
|
|
139
|
+
initialize() {
|
|
140
|
+
if (this.#initializePromise !== null)
|
|
141
|
+
return this.#initializePromise;
|
|
142
|
+
const work = this.#refreshLocalSessions().then(async () => {
|
|
143
|
+
await this.#refreshProjectViewTolerant();
|
|
144
|
+
if (this.#localCodexHome && !this.#closed) {
|
|
145
|
+
this.#catalogTimer = setInterval(() => { void this.#refreshLocalSessions().then(() => this.#refreshProjectViewTolerant()).catch(() => undefined); }, 30_000);
|
|
146
|
+
this.#catalogTimer.unref();
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
this.#initializePromise = work;
|
|
150
|
+
return work;
|
|
151
|
+
}
|
|
152
|
+
#refreshLocalSessions() {
|
|
153
|
+
if (!this.#localCodexHome || this.#closed)
|
|
154
|
+
return Promise.resolve();
|
|
155
|
+
if (this.#catalogRefresh)
|
|
156
|
+
return this.#catalogRefresh;
|
|
157
|
+
const refresh = (async () => {
|
|
158
|
+
const ids = new Set();
|
|
159
|
+
try {
|
|
160
|
+
const home = await realpath(this.#localCodexHome);
|
|
161
|
+
this.#localProjects = await readLocalCodexProjects(home);
|
|
162
|
+
const projectPaths = new Map();
|
|
163
|
+
const registeredPaths = new Set((await this.#store.snapshot()).workspaces.map(workspace => workspace.canonical_path));
|
|
164
|
+
for (const project of this.#localProjects ?? []) {
|
|
165
|
+
if (registeredPaths.has(project.path))
|
|
166
|
+
continue;
|
|
167
|
+
try {
|
|
168
|
+
await this.#store.ensureImported(project.name, hostWorkspaceFromConfig(project.path, [project.path]));
|
|
169
|
+
}
|
|
170
|
+
catch { /* One unavailable project must not hide the remaining roots. */ }
|
|
171
|
+
}
|
|
172
|
+
const catalog = await readLocalCodexSessions(home);
|
|
173
|
+
const projectFor = (item) => this.#localProjects?.find(project => project.path === item.cwd && project.threadIds.includes(item.threadId))
|
|
174
|
+
?? this.#localProjects?.find(project => project.threadIds.includes(item.threadId))
|
|
175
|
+
?? this.#localProjects?.find(project => project.path === item.cwd);
|
|
176
|
+
const paths = new Set();
|
|
177
|
+
for (const item of catalog) {
|
|
178
|
+
if (this.#localProjects !== null ? projectFor(item) !== undefined : paths.size < MAX_ROSTER)
|
|
179
|
+
paths.add(item.cwd);
|
|
180
|
+
}
|
|
181
|
+
// Each import is a locked read-parse-validate-write transaction (~50 ms on a real store), so only
|
|
182
|
+
// entries the store does not already hold identically go through one.
|
|
183
|
+
let workspacesByPath = new Map();
|
|
184
|
+
let sessionsByThread = new Map();
|
|
185
|
+
let stale = true;
|
|
186
|
+
for (const item of [...catalog].reverse()) {
|
|
187
|
+
if (this.#closed)
|
|
188
|
+
return;
|
|
189
|
+
if (!paths.has(item.cwd))
|
|
190
|
+
continue;
|
|
191
|
+
// An import can evict other sessions at capacity, so re-read the store after one before trusting a skip.
|
|
192
|
+
if (stale) {
|
|
193
|
+
const held = await this.#store.snapshot();
|
|
194
|
+
workspacesByPath = new Map(held.workspaces.map(workspace => [workspace.canonical_path, workspace]));
|
|
195
|
+
sessionsByThread = new Map(held.sessions.flatMap(session => session.codex_thread_id === null ? [] : [[`${session.executor_home ?? ''}\0${session.codex_thread_id}`, session]]));
|
|
196
|
+
stale = false;
|
|
197
|
+
}
|
|
198
|
+
const workspace = workspacesByPath.get(item.cwd);
|
|
199
|
+
const existing = workspace === undefined ? undefined : sessionsByThread.get(`${home}\0${item.threadId}`);
|
|
200
|
+
if (workspace !== undefined && existing?.workspace_id === workspace.workspace_id && existing.state === 'ready'
|
|
201
|
+
&& (existing.origin === 'nova' || (existing.last_used_at >= item.updatedAt && workspace.last_used_at >= item.updatedAt
|
|
202
|
+
&& sameSessionTitle(existing.display_title, item.title)))) {
|
|
203
|
+
ids.add(existing.session_id);
|
|
204
|
+
const project = projectFor(item);
|
|
205
|
+
if (project)
|
|
206
|
+
projectPaths.set(existing.session_id, project.path);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
stale = true;
|
|
210
|
+
try {
|
|
211
|
+
const workspace = await this.#store.ensureImported([...basename(item.cwd)].slice(0, 80).join('') || 'workspace', hostWorkspaceFromConfig(item.cwd, [item.cwd]));
|
|
212
|
+
const session = await this.#store.importSession(workspace.workspace_id, {
|
|
213
|
+
threadId: item.threadId, title: item.title, home: home, updatedAt: item.updatedAt,
|
|
214
|
+
});
|
|
215
|
+
ids.add(session.session_id);
|
|
216
|
+
const project = projectFor(item);
|
|
217
|
+
if (project)
|
|
218
|
+
projectPaths.set(session.session_id, project.path);
|
|
219
|
+
}
|
|
220
|
+
catch { /* An unavailable directory or full store must not hide other sessions. */ }
|
|
221
|
+
}
|
|
222
|
+
this.#localSessionIds = ids;
|
|
223
|
+
this.#sessionProjectPaths = projectPaths;
|
|
224
|
+
this.#catalogHealthy = true;
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
this.#catalogHealthy = false;
|
|
228
|
+
}
|
|
229
|
+
})();
|
|
230
|
+
this.#catalogRefresh = refresh.finally(() => { this.#catalogRefresh = null; });
|
|
231
|
+
return this.#catalogRefresh;
|
|
232
|
+
}
|
|
233
|
+
targetPort = {
|
|
234
|
+
list: () => this.#listCodingTargets(),
|
|
235
|
+
forWork: async (workId) => {
|
|
236
|
+
const binding = this.#taskWorkspaces.get(workId);
|
|
237
|
+
if (binding?.session_id === undefined)
|
|
238
|
+
return null;
|
|
239
|
+
try {
|
|
240
|
+
return await this.#validateCodingTarget({ workspace_id: binding.workspace_id, session_id: binding.session_id });
|
|
241
|
+
}
|
|
242
|
+
catch (error) {
|
|
243
|
+
if (error instanceof ProjectResolutionError)
|
|
244
|
+
return null;
|
|
245
|
+
throw error;
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
validate: selection => this.#validateCodingTarget(selection),
|
|
249
|
+
resolve: (decision, selection, taskContext) => this.resolveIntakeTarget(decision, selection, taskContext),
|
|
250
|
+
};
|
|
251
|
+
async #listCodingTargets() {
|
|
252
|
+
await this.#refreshLocalSessions();
|
|
253
|
+
const snapshot = await this.#store.snapshot();
|
|
254
|
+
const targets = [];
|
|
255
|
+
const savedRoots = this.#localProjects === null ? null : new Map(this.#localProjects.map(project => [project.path, project]));
|
|
256
|
+
const workspaces = [...snapshot.workspaces].sort((a, b) => b.last_used_at - a.last_used_at);
|
|
257
|
+
for (const workspace of savedRoots === null ? workspaces.slice(0, MAX_ROSTER) : workspaces) {
|
|
258
|
+
if (savedRoots !== null && !savedRoots.has(workspace.canonical_path)
|
|
259
|
+
&& !snapshot.sessions.some(session => session.workspace_id === workspace.workspace_id && this.#sessionProjectPaths.has(session.session_id)))
|
|
260
|
+
continue;
|
|
261
|
+
try {
|
|
262
|
+
await this.#store.revalidateWorkspace(workspace.workspace_id);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
// Exclusive workspace concurrency: a running work blocks every session of its workspace.
|
|
268
|
+
const holder = this.#slots.get(workspace.workspace_id)?.work.title;
|
|
269
|
+
const base = { workspace_id: workspace.workspace_id, project: workspace.display_name, executor: 'codex', directory: workspace.canonical_path, ...(holder === undefined ? {} : { running: holder }) };
|
|
270
|
+
const saved = savedRoots?.get(workspace.canonical_path);
|
|
271
|
+
if (savedRoots === null || saved)
|
|
272
|
+
targets.push({ ...base, session_id: null, title: workspace.display_name,
|
|
273
|
+
...(saved ? { group_project: saved.name } : {}) });
|
|
274
|
+
for (const session of snapshot.sessions.filter(item => item.workspace_id === workspace.workspace_id
|
|
275
|
+
&& item.state === 'ready' && item.backend_session_id !== null
|
|
276
|
+
&& (!item.executor_home || item.origin === 'nova' || (this.#catalogHealthy && this.#localSessionIds.has(item.session_id))))
|
|
277
|
+
.sort((a, b) => b.last_used_at - a.last_used_at).slice(0, 20)) {
|
|
278
|
+
const projectPath = this.#sessionProjectPaths.get(session.session_id) ?? workspace.canonical_path;
|
|
279
|
+
if (savedRoots !== null && !savedRoots.has(projectPath))
|
|
280
|
+
continue;
|
|
281
|
+
const group = snapshot.workspaces.find(item => item.canonical_path === projectPath);
|
|
282
|
+
if (savedRoots !== null && !group)
|
|
283
|
+
continue;
|
|
284
|
+
if (await this.#rolloutAvailable(session))
|
|
285
|
+
targets.push({ ...base, session_id: session.session_id, title: session.display_title, last_active: session.last_used_at,
|
|
286
|
+
...(group && savedRoots ? { group_workspace_id: group.workspace_id, group_project: savedRoots.get(projectPath).name, group_directory: group.canonical_path } : {}) });
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return targets;
|
|
290
|
+
}
|
|
291
|
+
async #validateCodingTarget(selection) {
|
|
292
|
+
const snapshot = await this.#store.snapshot();
|
|
293
|
+
const workspace = snapshot.workspaces.find(item => item.workspace_id === selection.workspace_id);
|
|
294
|
+
if (!workspace)
|
|
295
|
+
throw new ProjectResolutionError('unknown_project', { reason: 'target_unavailable' });
|
|
296
|
+
try {
|
|
297
|
+
await this.#store.revalidateWorkspace(workspace.workspace_id);
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
if (error instanceof ProjectStateError && ['workspace_invalid', 'workspace_not_found', 'workspace_boundary_changed'].includes(error.code)) {
|
|
301
|
+
throw new ProjectResolutionError('unknown_project', { reason: 'target_unavailable' });
|
|
302
|
+
}
|
|
303
|
+
throw error;
|
|
304
|
+
}
|
|
305
|
+
const base = { workspace_id: workspace.workspace_id, project: workspace.display_name, executor: 'codex' };
|
|
306
|
+
if (selection.session_id === null)
|
|
307
|
+
return { ...base, session_id: null, title: workspace.display_name };
|
|
308
|
+
const session = snapshot.sessions.find(item => item.workspace_id === workspace.workspace_id && item.session_id === selection.session_id);
|
|
309
|
+
if (session?.state !== 'ready' || session.backend_session_id === null
|
|
310
|
+
|| !await this.#externalSessionAvailable(workspace, session) || !await this.#rolloutAvailable(session)) {
|
|
311
|
+
throw new ProjectResolutionError('unknown_session', { reason: 'target_unavailable' });
|
|
312
|
+
}
|
|
313
|
+
return { ...base, session_id: session.session_id, title: session.display_title };
|
|
314
|
+
}
|
|
315
|
+
async codingBackendFor(sessionId) {
|
|
316
|
+
if (sessionId === null)
|
|
317
|
+
return this.#defaultBackend().backend_id;
|
|
318
|
+
const session = (await this.#store.snapshot()).sessions.find(item => item.session_id === sessionId);
|
|
319
|
+
return session?.backend_id ?? this.#defaultBackend().backend_id;
|
|
320
|
+
}
|
|
321
|
+
async activeCommittedWorkspace() {
|
|
322
|
+
const snapshot = await this.#store.snapshot();
|
|
323
|
+
if (snapshot.active_workspace_id === null)
|
|
324
|
+
return null;
|
|
325
|
+
return snapshot.workspaces.find(workspace => workspace.workspace_id === snapshot.active_workspace_id) ?? null;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Deterministic coordinator sink (spec 08): exact roster-name match, `work` refuses busy/capacity.
|
|
329
|
+
* Resolve only — no directory, session, proposal, dispatch, or active-project change; a `switch`
|
|
330
|
+
* resolves to `select` and, like every other change of the active project, is committed only by
|
|
331
|
+
* `commitConfirmed` after the user confirmed it.
|
|
332
|
+
*/
|
|
333
|
+
async resolveIntakeTarget(decision, selection, taskContext) {
|
|
334
|
+
if (taskContext)
|
|
335
|
+
taskGrantService(taskContext);
|
|
336
|
+
if (decision.kind === 'create') {
|
|
337
|
+
const name = await this.#store.validateManagedCreate(decision.project ?? '');
|
|
338
|
+
return {
|
|
339
|
+
workspace: name, action: 'create', workspace_display_name: name, workspace_id: null,
|
|
340
|
+
session_title: null, session_id: null,
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
const selected = selection === undefined ? undefined : await this.#validateCodingTarget(selection);
|
|
344
|
+
const workspace = await this.#resolveProject(selected?.project ?? decision.project);
|
|
345
|
+
if (selected && (workspace.workspace_id !== selected.workspace_id
|
|
346
|
+
|| (decision.project !== null && workspace.display_name.toLowerCase() !== decision.project.toLowerCase()))) {
|
|
347
|
+
throw new ProjectResolutionError('unknown_project', { reason: 'target_mismatch' });
|
|
348
|
+
}
|
|
349
|
+
if (decision.kind === 'work' && !taskContext) {
|
|
350
|
+
const slot = this.#slots.get(workspace.workspace_id);
|
|
351
|
+
if (slot !== undefined) {
|
|
352
|
+
throw new ProjectResolutionError('busy_project', {
|
|
353
|
+
project: workspace.display_name, work_id: slot.work.work_id, title: slot.work.title,
|
|
354
|
+
// Steering is offered only where the bound backend supports it (Codex app-server).
|
|
355
|
+
options: slot.work.backend_id === undefined || slot.work.backend_id === 'codex' ? ['steer', 'cancel'] : ['cancel'],
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
if (this.#slots.size >= MAX_CONCURRENT_WORK) {
|
|
359
|
+
throw new ProjectResolutionError('capacity', { running: this.running().map(work => ({ ...work })) });
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
await this.#store.revalidateWorkspace(workspace.workspace_id);
|
|
363
|
+
let session = null;
|
|
364
|
+
if (decision.kind === 'work' && decision.session === 'latest') {
|
|
365
|
+
try {
|
|
366
|
+
session = decision.session_title ? await this.#store.resolveSession(workspace.workspace_id, decision.session_title)
|
|
367
|
+
: selected === undefined ? await this.#latestReadySession(workspace)
|
|
368
|
+
: selected.session_id === null ? null
|
|
369
|
+
: (await this.#store.listSessions(workspace)).find(item => item.session_id === selected.session_id && item.state === 'ready') ?? null;
|
|
370
|
+
if (selected?.session_id && !decision.session_title && session === null)
|
|
371
|
+
throw new Error('session_unavailable');
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
throw new ProjectResolutionError('unknown_session', { project: workspace.display_name, title: decision.session_title ?? '' });
|
|
375
|
+
}
|
|
376
|
+
if (session !== null && !(await this.#rolloutAvailable(session)))
|
|
377
|
+
throw new ProjectResolutionError('unknown_session', { project: workspace.display_name, title: session.display_title });
|
|
378
|
+
if (session !== null && !await this.#externalSessionAvailable(workspace, session))
|
|
379
|
+
throw new ProjectResolutionError('unknown_session', { project: workspace.display_name, title: session.display_title });
|
|
380
|
+
}
|
|
381
|
+
return {
|
|
382
|
+
workspace: workspace.canonical_path,
|
|
383
|
+
action: decision.kind === 'switch' ? 'select' : session === null ? 'reuse' : 'resume',
|
|
384
|
+
workspace_display_name: workspace.display_name, workspace_id: workspace.workspace_id,
|
|
385
|
+
session_title: session?.display_title ?? null, session_id: session?.session_id ?? null,
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
roster() {
|
|
389
|
+
const snapshot = this.#snapshot;
|
|
390
|
+
// Display limits must not hide valid project evidence in the bounded registry.
|
|
391
|
+
return [...(snapshot?.workspaces ?? [])].sort((left, right) => right.last_used_at - left.last_used_at || right.created_at - left.created_at
|
|
392
|
+
|| compareCodePoints(right.workspace_id, left.workspace_id)).map((workspace, index) => {
|
|
393
|
+
const session = index < MAX_ROSTER ? snapshot?.sessions.find(record => record.session_id === workspace.active_session_id) : undefined;
|
|
394
|
+
return {
|
|
395
|
+
name: workspace.display_name,
|
|
396
|
+
last_used_at: workspace.last_used_at,
|
|
397
|
+
last_session_title: session?.display_title ?? null,
|
|
398
|
+
...(this.#localCodexHome && index < MAX_ROSTER ? { sessions: (snapshot?.sessions ?? [])
|
|
399
|
+
.filter(item => item.workspace_id === workspace.workspace_id && item.state === 'ready' && (!item.executor_home || item.origin === 'nova' || this.#localSessionIds.has(item.session_id)))
|
|
400
|
+
.sort((a, b) => b.last_used_at - a.last_used_at).slice(0, 20).map(item => item.display_title) } : {}),
|
|
401
|
+
running: this.#runningIn(workspace.display_name),
|
|
402
|
+
};
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
running() {
|
|
406
|
+
return [...this.#slots.values()].map(slot => slot.work);
|
|
407
|
+
}
|
|
408
|
+
/** Exact target id cancels only that work; otherwise 0 → not_running, 1 → cancel, >1 → model target. */
|
|
409
|
+
async cancel(instruction, context) {
|
|
410
|
+
const running = this.running().filter(work => context.workIds === undefined || context.workIds.has(work.work_id));
|
|
411
|
+
if (running.length === 0)
|
|
412
|
+
return { code: 'not_running' };
|
|
413
|
+
let target = context.targetWorkId === undefined
|
|
414
|
+
? running.length === 1 ? running[0] : undefined
|
|
415
|
+
: running.find(work => work.work_id === context.targetWorkId);
|
|
416
|
+
if (context.targetWorkId !== undefined && context.stillWanted?.() === false)
|
|
417
|
+
return { code: 'ambiguous_work', running };
|
|
418
|
+
if (target === undefined && context.targetWorkId === undefined && instruction !== undefined && instruction !== ''
|
|
419
|
+
&& context.resolveCancelTarget !== undefined) {
|
|
420
|
+
const id = await context.resolveCancelTarget(instruction, running);
|
|
421
|
+
// The user may have corrected themselves during the model call: a stale cancel stops nothing.
|
|
422
|
+
if (context.stillWanted?.() === false)
|
|
423
|
+
return { code: 'ambiguous_work', running };
|
|
424
|
+
target = running.find(work => work.work_id === id);
|
|
425
|
+
}
|
|
426
|
+
if (target === undefined || !this.#cancelWork(target.work_id))
|
|
427
|
+
return { code: 'ambiguous_work', running };
|
|
428
|
+
return { code: 'cancelled', work: target };
|
|
429
|
+
}
|
|
430
|
+
#cancelWork(workId) {
|
|
431
|
+
for (const slot of this.#slots.values()) {
|
|
432
|
+
if (slot.work.work_id !== workId)
|
|
433
|
+
continue;
|
|
434
|
+
slot.cancelled = true;
|
|
435
|
+
slot.controller.abort();
|
|
436
|
+
return true;
|
|
437
|
+
}
|
|
438
|
+
return false;
|
|
439
|
+
}
|
|
440
|
+
#runningIn(project) {
|
|
441
|
+
return [...this.#slots.values()]
|
|
442
|
+
.filter(slot => slot.work.project === project)
|
|
443
|
+
.map(slot => ({ work_id: slot.work.work_id, title: slot.work.title,
|
|
444
|
+
...(slot.work.backend_id === undefined ? {} : { backend_id: slot.work.backend_id }) }));
|
|
445
|
+
}
|
|
446
|
+
async #resolveProject(project) {
|
|
447
|
+
try {
|
|
448
|
+
return await this.#store.resolveWorkspace(project);
|
|
449
|
+
}
|
|
450
|
+
catch (error) {
|
|
451
|
+
if (!(error instanceof ProjectStateError)
|
|
452
|
+
|| (error.code !== 'workspace_not_found' && error.code !== 'workspace_name_invalid'))
|
|
453
|
+
throw error;
|
|
454
|
+
const names = this.#publicView.roster.map(entry => entry.name);
|
|
455
|
+
const needle = (project ?? '').toLowerCase();
|
|
456
|
+
const related = needle === ''
|
|
457
|
+
? []
|
|
458
|
+
: names.filter(name => name.toLowerCase().includes(needle) || needle.includes(name.toLowerCase()));
|
|
459
|
+
throw new ProjectResolutionError('unknown_project', {
|
|
460
|
+
project, suggestions: (related.length > 0 ? related : names).slice(0, 3), hint: 'create',
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
/** The workspace's active session when it can be resumed (ready with a thread), else `null`. */
|
|
465
|
+
async #latestReadySession(workspace) {
|
|
466
|
+
if (workspace.active_session_id === null)
|
|
467
|
+
return this.#localCodexHome
|
|
468
|
+
? (await this.#store.listSessions(workspace)).filter(item => item.state === 'ready' && this.#localSessionIds.has(item.session_id))
|
|
469
|
+
.sort((a, b) => b.last_used_at - a.last_used_at)[0] ?? null : null;
|
|
470
|
+
let session;
|
|
471
|
+
try {
|
|
472
|
+
session = await this.#store.resolveSession(workspace.workspace_id, null);
|
|
473
|
+
}
|
|
474
|
+
catch (error) {
|
|
475
|
+
if (error instanceof ProjectStateError && error.code === 'session_not_found')
|
|
476
|
+
return null;
|
|
477
|
+
throw error;
|
|
478
|
+
}
|
|
479
|
+
return session.state === 'ready' && session.backend_session_id !== null && await this.#rolloutAvailable(session) ? session : null;
|
|
480
|
+
}
|
|
481
|
+
/** Exact resume authority cannot depend on the discovery catalog's UI page limit. */
|
|
482
|
+
async #externalSessionAvailable(workspace, session) {
|
|
483
|
+
if (!session.executor_home || session.origin === 'nova')
|
|
484
|
+
return true;
|
|
485
|
+
if (!this.#localCodexHome || !session.codex_thread_id)
|
|
486
|
+
return false;
|
|
487
|
+
try {
|
|
488
|
+
const home = await realpath(this.#localCodexHome);
|
|
489
|
+
if (home !== session.executor_home)
|
|
490
|
+
return false;
|
|
491
|
+
return (await readLocalCodexSessions(home, session.codex_thread_id)).some(item => item.cwd === workspace.canonical_path);
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
return false;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
async #rolloutAvailable(session) {
|
|
498
|
+
if (session.executor_home && session.codex_thread_id
|
|
499
|
+
&& await localRolloutAvailable(session.executor_home, session.codex_thread_id) === false) {
|
|
500
|
+
await this.#store.markSessionUnavailable(session.session_id, { wait: true });
|
|
501
|
+
return false;
|
|
502
|
+
}
|
|
503
|
+
return true;
|
|
504
|
+
}
|
|
505
|
+
observeProjectView(observer) {
|
|
506
|
+
this.#projectViewObservers.add(observer);
|
|
507
|
+
return () => { this.#projectViewObservers.delete(observer); };
|
|
508
|
+
}
|
|
509
|
+
observeProjectContext(observer) {
|
|
510
|
+
this.#projectContextObservers.add(observer);
|
|
511
|
+
return () => { this.#projectContextObservers.delete(observer); };
|
|
512
|
+
}
|
|
513
|
+
async dispatch(op, request, context) {
|
|
514
|
+
const privateValue = consumeHostExecutorCapability(context);
|
|
515
|
+
if (privateValue !== undefined) {
|
|
516
|
+
if (op !== 'run'
|
|
517
|
+
|| Object.keys(request).length !== 1
|
|
518
|
+
|| typeof request.work_order !== 'string')
|
|
519
|
+
return failureHandoff('invalid_operation', op);
|
|
520
|
+
const binding = this.#confirmedBindings.get(privateValue);
|
|
521
|
+
if (binding?.operation !== privateValue
|
|
522
|
+
|| binding.delegateId !== context.delegate.delegate_id
|
|
523
|
+
|| binding.originRef !== context.delegate.origin_ref)
|
|
524
|
+
return failureHandoff('confirmation_binding_mismatch', op);
|
|
525
|
+
this.#confirmedBindings.delete(privateValue);
|
|
526
|
+
if (this.#closed)
|
|
527
|
+
return failureHandoff('closed', 'run');
|
|
528
|
+
try {
|
|
529
|
+
return await this.#runConfirmed(binding.operation, binding.workOrder, context);
|
|
530
|
+
}
|
|
531
|
+
catch (error) {
|
|
532
|
+
if (error instanceof ProjectStateError)
|
|
533
|
+
return projectProblemHandoff(error.code);
|
|
534
|
+
throw error;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
const admitted = validateCodexRequest('project', op, request);
|
|
538
|
+
if (!admitted.ok)
|
|
539
|
+
return failureHandoff(admitted.error, admitted.op);
|
|
540
|
+
if (op === 'status')
|
|
541
|
+
return await this.#status.dispatch(op, request, context);
|
|
542
|
+
if (op === 'cancel') {
|
|
543
|
+
const workId = String(admitted.value.work_id);
|
|
544
|
+
return {
|
|
545
|
+
outcome: 'ok', trust: 'trusted_system',
|
|
546
|
+
content: { op: 'cancel', code: this.#cancelWork(workId) ? 'cancelled' : 'not_running', work_id: workId },
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
if (op !== 'run' && op !== 'steer')
|
|
550
|
+
return failureHandoff('invalid_operation', op);
|
|
551
|
+
if (this.#closed)
|
|
552
|
+
return failureHandoff('closed', op);
|
|
553
|
+
let workspace;
|
|
554
|
+
try {
|
|
555
|
+
workspace = await this.#store.resolveWorkspace(admitted.value.project);
|
|
556
|
+
}
|
|
557
|
+
catch (error) {
|
|
558
|
+
return projectProblemHandoff(projectErrorCode(error), op);
|
|
559
|
+
}
|
|
560
|
+
if (op === 'steer') {
|
|
561
|
+
const slot = this.#slots.get(workspace.workspace_id), live = slot?.live;
|
|
562
|
+
if (!slot || !live)
|
|
563
|
+
return projectNoActiveTurn();
|
|
564
|
+
const wanted = () => this.#slots.get(workspace.workspace_id) === slot && slot.live === live
|
|
565
|
+
&& (admitted.value.work_id === undefined || admitted.value.work_id === slot.work.work_id)
|
|
566
|
+
&& (admitted.value.session_id === undefined || admitted.value.session_id === this.#taskWorkspaces.get(slot.work.work_id)?.session_id);
|
|
567
|
+
if (!wanted())
|
|
568
|
+
return failureHandoff('superseded', op);
|
|
569
|
+
return await live.dispatch(op, { instruction: String(admitted.value.instruction) }, { ...context, beforeWrite: () => { context.beforeWrite?.(); if (!wanted())
|
|
570
|
+
throw Error('superseded'); } });
|
|
571
|
+
}
|
|
572
|
+
return await this.#dispatchRun(workspace, admitted.value, context);
|
|
573
|
+
}
|
|
574
|
+
/** Public `run` (spec 08): `latest` resumes the active ready session, otherwise a new titled thread. */
|
|
575
|
+
async #dispatchRun(workspace, input, context) {
|
|
576
|
+
let resumed = null;
|
|
577
|
+
try {
|
|
578
|
+
if (input.session_id) {
|
|
579
|
+
resumed = (await this.#store.listSessions(workspace)).find(item => item.session_id === input.session_id && item.state === 'ready') ?? null;
|
|
580
|
+
if (resumed === null)
|
|
581
|
+
return failureHandoff('resume_unavailable', 'run');
|
|
582
|
+
}
|
|
583
|
+
else if (input.session === 'latest')
|
|
584
|
+
resumed = await this.#latestReadySession(workspace);
|
|
585
|
+
}
|
|
586
|
+
catch (error) {
|
|
587
|
+
return projectProblemHandoff(projectErrorCode(error));
|
|
588
|
+
}
|
|
589
|
+
const title = resumed?.display_title ?? input.title ?? deriveSessionTitle(input.work_order);
|
|
590
|
+
return await this.#runInSlot(workspace, title, context, (slot, runContext) => this.#runBound(slot, workspace, resumed, title, input.work_order, runContext));
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Own one run slot for the workspace: a second run on a live slot is `busy_project`, the global cap
|
|
594
|
+
* is `capacity`. The slot's controller is the one `cancel` aborts; the runtime signal chains into it.
|
|
595
|
+
*/
|
|
596
|
+
async #runInSlot(workspace, title, context, run) {
|
|
597
|
+
if (this.#closed)
|
|
598
|
+
return failureHandoff('closed', 'run');
|
|
599
|
+
if (this.#resourceKeys === null)
|
|
600
|
+
return failureHandoff('computer_resource_unavailable', 'run');
|
|
601
|
+
const busy = () => this.#slots.has(workspace.workspace_id) ? 'busy_project' : this.#slots.size >= MAX_CONCURRENT_WORK ? 'capacity' : null;
|
|
602
|
+
if (!context.resourceWaiting && busy()) {
|
|
603
|
+
const existing = this.#slots.get(workspace.workspace_id);
|
|
604
|
+
return existing ? refusedRunHandoff('busy_project', { project: workspace.display_name, work_id: existing.work.work_id, title: existing.work.title }) : refusedRunHandoff('capacity', { running: this.running().map(work => ({ ...work })) });
|
|
605
|
+
}
|
|
606
|
+
let release;
|
|
607
|
+
if (this.#resourceKeys.length) {
|
|
608
|
+
if (taskResourcesBusy(this.#resourceKeys))
|
|
609
|
+
await context.resourceWaiting?.(taskResourcesUncertain(this.#resourceKeys) ? 'computer_resource_uncertain' : 'computer_resource_busy');
|
|
610
|
+
release = await acquireTaskResources(this.#resourceKeys, context.signal);
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
while (busy()) {
|
|
614
|
+
if (!context.resourceWaiting) {
|
|
615
|
+
release?.();
|
|
616
|
+
return refusedRunHandoff(busy(), { running: this.running().map(work => ({ ...work })) });
|
|
617
|
+
}
|
|
618
|
+
await context.resourceWaiting(busy());
|
|
619
|
+
await new Promise((resolve, reject) => {
|
|
620
|
+
const changed = () => { if (!busy() || this.#closed) {
|
|
621
|
+
cleanup();
|
|
622
|
+
resolve();
|
|
623
|
+
} }, abort = () => { cleanup(); reject(context.signal.reason instanceof Error ? context.signal.reason : new Error('aborted')); }, cleanup = () => { this.#slotWaiters.delete(changed); context.signal.removeEventListener('abort', abort); };
|
|
624
|
+
this.#slotWaiters.add(changed);
|
|
625
|
+
context.signal.addEventListener('abort', abort, { once: true });
|
|
626
|
+
if (context.signal.aborted)
|
|
627
|
+
abort();
|
|
628
|
+
else
|
|
629
|
+
changed();
|
|
630
|
+
});
|
|
631
|
+
if (this.#closed)
|
|
632
|
+
throw Error('closed');
|
|
633
|
+
}
|
|
634
|
+
context.signal.throwIfAborted();
|
|
635
|
+
context.beforeWrite?.();
|
|
636
|
+
}
|
|
637
|
+
catch (error) {
|
|
638
|
+
release?.();
|
|
639
|
+
throw error;
|
|
640
|
+
}
|
|
641
|
+
const controller = new AbortController();
|
|
642
|
+
const onAbort = () => { controller.abort(); };
|
|
643
|
+
if (context.signal.aborted)
|
|
644
|
+
controller.abort();
|
|
645
|
+
else
|
|
646
|
+
context.signal.addEventListener('abort', onAbort, { once: true });
|
|
647
|
+
const slot = {
|
|
648
|
+
work: { work_id: context.delegate.delegate_id, project: workspace.display_name, title },
|
|
649
|
+
controller,
|
|
650
|
+
live: null,
|
|
651
|
+
task: null,
|
|
652
|
+
cancelled: false,
|
|
653
|
+
};
|
|
654
|
+
this.#slots.set(workspace.workspace_id, slot);
|
|
655
|
+
if (this.#taskWorkspaces.size >= 64) {
|
|
656
|
+
const oldest = [...this.#taskWorkspaces.keys()].find(id => !this.running().some(work => work.work_id === id));
|
|
657
|
+
if (oldest !== undefined)
|
|
658
|
+
this.#taskWorkspaces.delete(oldest);
|
|
659
|
+
}
|
|
660
|
+
this.#taskWorkspaces.set(slot.work.work_id, { workspace_id: workspace.workspace_id });
|
|
661
|
+
const task = Promise.resolve().then(async () => { await context.resourceWaiting?.(null); controller.signal.throwIfAborted(); context.beforeWrite?.(); return run(slot, { ...context, signal: controller.signal }); });
|
|
662
|
+
slot.task = task;
|
|
663
|
+
try {
|
|
664
|
+
const result = await task;
|
|
665
|
+
if (result.outcome === 'unknown' || this.#retainedTransportCleanups.size) {
|
|
666
|
+
quarantineTaskResources(this.#resourceKeys);
|
|
667
|
+
release = undefined;
|
|
668
|
+
}
|
|
669
|
+
return result;
|
|
670
|
+
}
|
|
671
|
+
catch (error) {
|
|
672
|
+
if (error instanceof ProjectStateError)
|
|
673
|
+
return projectProblemHandoff(error.code);
|
|
674
|
+
quarantineTaskResources(this.#resourceKeys);
|
|
675
|
+
release = undefined;
|
|
676
|
+
throw error;
|
|
677
|
+
}
|
|
678
|
+
finally {
|
|
679
|
+
context.signal.removeEventListener('abort', onAbort);
|
|
680
|
+
if (this.#slots.get(workspace.workspace_id) === slot)
|
|
681
|
+
this.#slots.delete(workspace.workspace_id);
|
|
682
|
+
release?.();
|
|
683
|
+
for (const changed of this.#slotWaiters)
|
|
684
|
+
changed();
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
async commitConfirmed(operation, runtimeDispatch, confirmation = this.#confirmation) {
|
|
688
|
+
if (!confirmation.ownsConfirmed(operation)) {
|
|
689
|
+
return commitResult(false, 'confirmation_invalid');
|
|
690
|
+
}
|
|
691
|
+
if (this.#projectCommitActive)
|
|
692
|
+
return commitResult(false, 'confirmation_in_progress');
|
|
693
|
+
this.#projectCommitActive = true;
|
|
694
|
+
try {
|
|
695
|
+
const workOrder = operation.work_order;
|
|
696
|
+
if (workOrder === null) {
|
|
697
|
+
// Workspace-only changes have no runtime delegate admission. Claim immediately; every
|
|
698
|
+
// validation or store failure after this boundary is terminal rather than retryable.
|
|
699
|
+
if (!confirmation.claimConfirmed(operation)) {
|
|
700
|
+
return commitResult(false, 'confirmation_invalid');
|
|
701
|
+
}
|
|
702
|
+
let committedWorkspace;
|
|
703
|
+
let previousWorkspace = null;
|
|
704
|
+
try {
|
|
705
|
+
previousWorkspace = await this.activeCommittedWorkspace();
|
|
706
|
+
if (operation.action === 'create') {
|
|
707
|
+
await this.#store.validateManagedCreate(operation.workspace_display_name);
|
|
708
|
+
committedWorkspace = await this.#store.createManaged(operation.workspace_display_name);
|
|
709
|
+
}
|
|
710
|
+
else if (operation.action === 'select' && operation.workspace_id !== null) {
|
|
711
|
+
committedWorkspace = await this.#store.selectWorkspaceExact(operation.workspace_display_name, operation.workspace_id);
|
|
712
|
+
}
|
|
713
|
+
else {
|
|
714
|
+
return commitResult(false, 'invalid_operation');
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
catch (error) {
|
|
718
|
+
return commitResult(false, projectErrorCode(error));
|
|
719
|
+
}
|
|
720
|
+
try {
|
|
721
|
+
await this.#refreshProjectContextBarrier();
|
|
722
|
+
}
|
|
723
|
+
catch (error) {
|
|
724
|
+
if (operation.action === 'create') {
|
|
725
|
+
await this.#store.rollbackManagedCreate(committedWorkspace.workspace_id, { wait: true, previousWorkspaceId: previousWorkspace?.workspace_id ?? null }).catch(() => false);
|
|
726
|
+
}
|
|
727
|
+
else if (previousWorkspace !== null) {
|
|
728
|
+
await this.#store.selectWorkspaceExact(previousWorkspace.display_name, previousWorkspace.workspace_id).catch(() => undefined);
|
|
729
|
+
}
|
|
730
|
+
try {
|
|
731
|
+
await this.#refreshProjectContextBarrier();
|
|
732
|
+
}
|
|
733
|
+
catch (recoveryError) {
|
|
734
|
+
return commitResult(false, projectErrorCode(recoveryError));
|
|
735
|
+
}
|
|
736
|
+
return commitResult(false, projectErrorCode(error));
|
|
737
|
+
}
|
|
738
|
+
return commitResult(true, 'committed');
|
|
739
|
+
}
|
|
740
|
+
const normalized = validateCodexRequest('project', 'run', { work_order: workOrder });
|
|
741
|
+
const busy = this.#slots.size >= MAX_CONCURRENT_WORK
|
|
742
|
+
|| (operation.workspace_id !== null && this.#slots.has(operation.workspace_id));
|
|
743
|
+
if (!normalized.ok || normalized.value.work_order !== workOrder || busy) {
|
|
744
|
+
if (busy)
|
|
745
|
+
confirmation.rollbackConfirmed(operation);
|
|
746
|
+
else
|
|
747
|
+
confirmation.rejectConfirmed(operation);
|
|
748
|
+
return commitResult(false, busy ? 'busy' : 'invalid_operation');
|
|
749
|
+
}
|
|
750
|
+
try {
|
|
751
|
+
await this.#revalidateProposal(operation);
|
|
752
|
+
}
|
|
753
|
+
catch (error) {
|
|
754
|
+
confirmation.rejectConfirmed(operation);
|
|
755
|
+
return commitResult(false, projectErrorCode(error));
|
|
756
|
+
}
|
|
757
|
+
let launchAuthorized = false;
|
|
758
|
+
const admission = await runtimeDispatch({
|
|
759
|
+
executor: 'codex',
|
|
760
|
+
op: 'run',
|
|
761
|
+
request: { work_order: workOrder },
|
|
762
|
+
origin_ref: operation.origin_ref,
|
|
763
|
+
}, {
|
|
764
|
+
kind: 'realtime_tool',
|
|
765
|
+
priority: USER_PRIORITY,
|
|
766
|
+
routing_class: 'user_awaited',
|
|
767
|
+
origin: null,
|
|
768
|
+
selected_suggestion: null,
|
|
769
|
+
}, operation, () => launchAuthorized);
|
|
770
|
+
if (!admission.accepted || admission.delegate_id === null) {
|
|
771
|
+
confirmation.rollbackConfirmed(operation);
|
|
772
|
+
return commitResult(false, 'runtime_rejected');
|
|
773
|
+
}
|
|
774
|
+
if (!confirmation.recordRuntimeAdmission(operation)) {
|
|
775
|
+
return commitResult(false, 'confirmation_invalid');
|
|
776
|
+
}
|
|
777
|
+
if (!confirmation.claimConfirmed(operation)) {
|
|
778
|
+
return commitResult(false, 'confirmation_invalid');
|
|
779
|
+
}
|
|
780
|
+
this.#confirmedBindings.set(operation, Object.freeze({
|
|
781
|
+
operation,
|
|
782
|
+
delegateId: admission.delegate_id,
|
|
783
|
+
originRef: operation.origin_ref,
|
|
784
|
+
workOrder,
|
|
785
|
+
}));
|
|
786
|
+
launchAuthorized = true;
|
|
787
|
+
return commitResult(true, 'accepted', admission.delegate_id);
|
|
788
|
+
}
|
|
789
|
+
finally {
|
|
790
|
+
this.#projectCommitActive = false;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
publicProjectView(pendingConfirmation) {
|
|
794
|
+
const available = this.#localCodexHome ? this.roster().filter(entry => entry.sessions?.length).map(entry => ({ project: entry.name, titles: entry.sessions })) : [];
|
|
795
|
+
const base = {
|
|
796
|
+
...this.#publicView,
|
|
797
|
+
...(available.length ? { available_sessions: available } : {}),
|
|
798
|
+
roster: this.#publicView.roster.slice(0, MAX_ROSTER).map(entry => ({ ...entry, running: this.#runningIn(entry.name) })),
|
|
799
|
+
};
|
|
800
|
+
if (!pendingConfirmation) {
|
|
801
|
+
return Object.freeze({
|
|
802
|
+
...base,
|
|
803
|
+
pending_confirmation: false,
|
|
804
|
+
pending_confirmation_busy: false,
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
const confirmation = pendingConfirmation ? this.#confirmation.view : null;
|
|
808
|
+
return Object.freeze({
|
|
809
|
+
...base,
|
|
810
|
+
pending_confirmation: true,
|
|
811
|
+
pending_confirmation_busy: confirmation?.pending_confirmation_busy ?? false,
|
|
812
|
+
...(confirmation?.pending_confirmation_id === undefined
|
|
813
|
+
? {}
|
|
814
|
+
: { pending_confirmation_id: confirmation.pending_confirmation_id }),
|
|
815
|
+
pending_action: confirmation?.pending_action ?? null,
|
|
816
|
+
pending_workspace_display_name: confirmation?.pending_workspace_display_name ?? null,
|
|
817
|
+
pending_session_title: confirmation?.pending_session_title ?? null,
|
|
818
|
+
pending_expires_in_seconds: confirmation?.pending_expires_in_seconds ?? null,
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
publicProjectContext(pendingConfirmation) {
|
|
822
|
+
return Object.freeze({
|
|
823
|
+
workspace_id: this.#publicWorkspaceId,
|
|
824
|
+
view: this.publicProjectView(pendingConfirmation),
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
close() {
|
|
828
|
+
if (this.#catalogTimer) {
|
|
829
|
+
clearInterval(this.#catalogTimer);
|
|
830
|
+
this.#catalogTimer = null;
|
|
831
|
+
}
|
|
832
|
+
if (this.#closePromise !== null)
|
|
833
|
+
return this.#closePromise;
|
|
834
|
+
this.#closed = true;
|
|
835
|
+
const work = this.#close();
|
|
836
|
+
const exposed = work.catch(error => {
|
|
837
|
+
if (this.#closePromise === exposed && this.#retainedTransportCleanups.size > 0) {
|
|
838
|
+
this.#closePromise = null;
|
|
839
|
+
}
|
|
840
|
+
throw error;
|
|
841
|
+
});
|
|
842
|
+
this.#closePromise = exposed;
|
|
843
|
+
return exposed;
|
|
844
|
+
}
|
|
845
|
+
async #close() {
|
|
846
|
+
for (const changed of this.#slotWaiters)
|
|
847
|
+
changed();
|
|
848
|
+
await this.#catalogRefresh;
|
|
849
|
+
const slots = [...this.#slots.values()];
|
|
850
|
+
for (const slot of slots)
|
|
851
|
+
slot.controller.abort();
|
|
852
|
+
let closeFailure = null;
|
|
853
|
+
try {
|
|
854
|
+
await this.#status.close();
|
|
855
|
+
}
|
|
856
|
+
catch (error) {
|
|
857
|
+
closeFailure = projectCloseError(error);
|
|
858
|
+
}
|
|
859
|
+
for (const slot of slots) {
|
|
860
|
+
await slot.task?.catch(() => undefined);
|
|
861
|
+
try {
|
|
862
|
+
await slot.live?.close();
|
|
863
|
+
}
|
|
864
|
+
catch (error) {
|
|
865
|
+
closeFailure ??= projectCloseError(error);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
try {
|
|
869
|
+
await this.#drainRetainedTransportCleanups();
|
|
870
|
+
}
|
|
871
|
+
catch (error) {
|
|
872
|
+
closeFailure ??= projectCloseError(error);
|
|
873
|
+
}
|
|
874
|
+
if (closeFailure !== null && this.#retainedTransportCleanups.size > 0)
|
|
875
|
+
throw closeFailure;
|
|
876
|
+
await this.#store.close();
|
|
877
|
+
if (closeFailure !== null)
|
|
878
|
+
throw closeFailure;
|
|
879
|
+
}
|
|
880
|
+
async #revalidateProposal(operation) {
|
|
881
|
+
if (operation.action === 'create') {
|
|
882
|
+
if (operation.workspace_id !== null || operation.session_id !== null) {
|
|
883
|
+
throw new ProjectStateError('workspace_boundary_changed');
|
|
884
|
+
}
|
|
885
|
+
await this.#store.validateManagedCreate(operation.workspace_display_name);
|
|
886
|
+
return;
|
|
887
|
+
}
|
|
888
|
+
if (operation.action === 'reuse') {
|
|
889
|
+
if (operation.workspace_id === null || operation.session_id !== null) {
|
|
890
|
+
throw new ProjectStateError('workspace_boundary_changed');
|
|
891
|
+
}
|
|
892
|
+
const workspace = await this.#store.resolveWorkspace(operation.workspace_display_name);
|
|
893
|
+
if (workspace.workspace_id !== operation.workspace_id) {
|
|
894
|
+
throw new ProjectStateError('workspace_boundary_changed');
|
|
895
|
+
}
|
|
896
|
+
await this.#store.revalidateWorkspace(workspace.workspace_id);
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
if (operation.action !== 'resume' || operation.workspace_id === null || operation.session_id === null) {
|
|
900
|
+
throw new ProjectStateError('session_workspace_mismatch');
|
|
901
|
+
}
|
|
902
|
+
const workspace = await this.#store.resolveWorkspace(operation.workspace_display_name);
|
|
903
|
+
if (workspace.workspace_id !== operation.workspace_id) {
|
|
904
|
+
throw new ProjectStateError('workspace_boundary_changed');
|
|
905
|
+
}
|
|
906
|
+
const session = (await this.#store.listSessions(workspace)).find(item => item.session_id === operation.session_id);
|
|
907
|
+
if (session?.session_id !== operation.session_id
|
|
908
|
+
|| session.state !== 'ready'
|
|
909
|
+
|| session.backend_session_id === null)
|
|
910
|
+
throw new ProjectStateError('session_unavailable');
|
|
911
|
+
await this.#store.revalidateWorkspace(workspace.workspace_id);
|
|
912
|
+
}
|
|
913
|
+
async #runConfirmed(operation, workOrder, context) {
|
|
914
|
+
const title = operation.session_title ?? deriveSessionTitle(workOrder);
|
|
915
|
+
if (operation.action === 'create') {
|
|
916
|
+
const previousWorkspace = await this.activeCommittedWorkspace();
|
|
917
|
+
const workspace = await this.#store.createManaged(operation.workspace_display_name);
|
|
918
|
+
let result;
|
|
919
|
+
try {
|
|
920
|
+
result = await this.#runInSlot(workspace, title, context, (slot, runContext) => this.#runBound(slot, workspace, null, title, workOrder, runContext));
|
|
921
|
+
}
|
|
922
|
+
catch (error) {
|
|
923
|
+
const rolledBack = await this.#store.rollbackManagedCreate(workspace.workspace_id, { wait: true, previousWorkspaceId: previousWorkspace?.workspace_id ?? null }).catch(() => false);
|
|
924
|
+
if (rolledBack)
|
|
925
|
+
await this.#refreshProjectContextBarrier();
|
|
926
|
+
throw error;
|
|
927
|
+
}
|
|
928
|
+
if (result.outcome !== 'ok') {
|
|
929
|
+
const rolledBack = await this.#store.rollbackManagedCreate(workspace.workspace_id, { wait: true, previousWorkspaceId: previousWorkspace?.workspace_id ?? null }).catch(() => false);
|
|
930
|
+
if (rolledBack)
|
|
931
|
+
await this.#refreshProjectContextBarrier();
|
|
932
|
+
}
|
|
933
|
+
return result;
|
|
934
|
+
}
|
|
935
|
+
if (operation.action === 'reuse') {
|
|
936
|
+
if (operation.workspace_id === null || operation.session_id !== null) {
|
|
937
|
+
return failureHandoff('confirmation_binding_mismatch', 'run');
|
|
938
|
+
}
|
|
939
|
+
const workspace = await this.#store.resolveWorkspace(operation.workspace_display_name);
|
|
940
|
+
if (workspace.workspace_id !== operation.workspace_id) {
|
|
941
|
+
return failureHandoff('workspace_boundary_changed', 'run');
|
|
942
|
+
}
|
|
943
|
+
return await this.#runInSlot(workspace, title, context, (slot, runContext) => this.#runBound(slot, workspace, null, title, workOrder, runContext));
|
|
944
|
+
}
|
|
945
|
+
if (operation.action !== 'resume' || operation.workspace_id === null || operation.session_id === null) {
|
|
946
|
+
return failureHandoff('confirmation_binding_mismatch', 'run');
|
|
947
|
+
}
|
|
948
|
+
const workspace = await this.#store.resolveWorkspace(operation.workspace_display_name);
|
|
949
|
+
if (workspace.workspace_id !== operation.workspace_id) {
|
|
950
|
+
return failureHandoff('workspace_boundary_changed', 'run');
|
|
951
|
+
}
|
|
952
|
+
const session = (await this.#store.listSessions(workspace)).find(item => item.session_id === operation.session_id);
|
|
953
|
+
if (session?.session_id !== operation.session_id || session.state !== 'ready') {
|
|
954
|
+
return projectProblemHandoff('session_unavailable');
|
|
955
|
+
}
|
|
956
|
+
return await this.#runInSlot(workspace, session.display_title, context, (slot, runContext) => this.#runBound(slot, workspace, session, session.display_title, workOrder, runContext));
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* Run one work order against a workspace inside its slot. `title` names the new thread (and the
|
|
960
|
+
* provisional session) when `resumed` is null; a user cancel surfaces as a `cancelled` handoff.
|
|
961
|
+
*/
|
|
962
|
+
async #runBound(slot, workspace, resumed, title, workOrder, context) {
|
|
963
|
+
try {
|
|
964
|
+
await this.#drainRetainedTransportCleanups();
|
|
965
|
+
}
|
|
966
|
+
catch {
|
|
967
|
+
return failureHandoff('transport_failure', 'run');
|
|
968
|
+
}
|
|
969
|
+
let session = resumed;
|
|
970
|
+
let startRollback = null;
|
|
971
|
+
let titleUpdates = Promise.resolve();
|
|
972
|
+
let reportedThreadId = null;
|
|
973
|
+
let bindingMismatch = false;
|
|
974
|
+
let result = null;
|
|
975
|
+
let resumeRollback = null;
|
|
976
|
+
const disposition = { value: null };
|
|
977
|
+
await this.#store.revalidateWorkspace(workspace.workspace_id);
|
|
978
|
+
if (resumed !== null && !(await this.#rolloutAvailable(resumed)))
|
|
979
|
+
return failureHandoff('resume_unavailable', 'run', 'thread_start');
|
|
980
|
+
if (resumed?.executor_home && resumed.origin !== 'nova') {
|
|
981
|
+
await this.#refreshLocalSessions();
|
|
982
|
+
if (!await this.#externalSessionAvailable(workspace, resumed))
|
|
983
|
+
return failureHandoff('resume_unavailable', 'run');
|
|
984
|
+
}
|
|
985
|
+
// A resumed session keeps its persisted binding; only a new session reads the current default.
|
|
986
|
+
const backend = resumed === null
|
|
987
|
+
? Object.freeze({ ...this.#defaultBackend() })
|
|
988
|
+
: { backend_id: resumed.backend_id, backend_profile_id: resumed.backend_profile_id };
|
|
989
|
+
const codex = backend.backend_id === 'codex';
|
|
990
|
+
let codexHome = null;
|
|
991
|
+
let canonicalHome;
|
|
992
|
+
try {
|
|
993
|
+
const executorHome = !codex ? undefined : resumed === null ? this.#localCodexHome : resumed.executor_home;
|
|
994
|
+
canonicalHome = executorHome === undefined ? undefined : await realpath(executorHome);
|
|
995
|
+
if (resumed?.executor_home && canonicalHome !== resumed.executor_home)
|
|
996
|
+
return failureHandoff('resume_unavailable', 'run');
|
|
997
|
+
if (codex)
|
|
998
|
+
codexHome = canonicalHome === undefined
|
|
999
|
+
? await this.#store.persistentHome(workspace.workspace_id, { create: resumed === null })
|
|
1000
|
+
: hostPersistentHomeFromConfig(canonicalHome, [canonicalHome]);
|
|
1001
|
+
}
|
|
1002
|
+
catch (error) {
|
|
1003
|
+
if (resumed !== null)
|
|
1004
|
+
return failureHandoff('resume_unavailable', 'run');
|
|
1005
|
+
throw error;
|
|
1006
|
+
}
|
|
1007
|
+
let inner;
|
|
1008
|
+
try {
|
|
1009
|
+
if (session === null) {
|
|
1010
|
+
const begun = await this.#store.beginSessionForRun(workspace.workspace_id, title, canonicalHome, backend);
|
|
1011
|
+
session = begun.session;
|
|
1012
|
+
startRollback = begun.rollback;
|
|
1013
|
+
}
|
|
1014
|
+
// Persistent-home setup and session persistence both cross await boundaries. Revalidate the
|
|
1015
|
+
// exact approved workspace again immediately before host process construction.
|
|
1016
|
+
let approvedWorkspace;
|
|
1017
|
+
if (resumed === null) {
|
|
1018
|
+
approvedWorkspace = await this.#store.revalidateWorkspace(workspace.workspace_id);
|
|
1019
|
+
}
|
|
1020
|
+
else {
|
|
1021
|
+
const prepared = await this.#store.prepareSessionResumeForRun(workspace.workspace_id, resumed.session_id, resumed.backend_session_id ?? '');
|
|
1022
|
+
approvedWorkspace = prepared.workspace;
|
|
1023
|
+
resumeRollback = prepared.rollback;
|
|
1024
|
+
}
|
|
1025
|
+
// The provider-facing active view must observe the exact session binding before any
|
|
1026
|
+
// transport can run against it. This also keeps a resumed session from inheriting the
|
|
1027
|
+
// prior display title during the process-construction window.
|
|
1028
|
+
if (backend.backend_id !== 'codex')
|
|
1029
|
+
slot.work = { ...slot.work, backend_id: backend.backend_id };
|
|
1030
|
+
await this.#refreshProjectContextBarrier();
|
|
1031
|
+
inner = this.#transportFactory.create(Object.freeze({
|
|
1032
|
+
workspace: approvedWorkspace,
|
|
1033
|
+
codexHome,
|
|
1034
|
+
...backend,
|
|
1035
|
+
preserveHome: true,
|
|
1036
|
+
resumeThreadId: resumed?.backend_session_id ?? null,
|
|
1037
|
+
work: slot.work,
|
|
1038
|
+
}));
|
|
1039
|
+
}
|
|
1040
|
+
catch (error) {
|
|
1041
|
+
if (startRollback !== null) {
|
|
1042
|
+
await this.#store.rollbackSessionStartForRun(startRollback, { wait: true }).catch(() => false);
|
|
1043
|
+
await this.#refreshProjectContextBarrier();
|
|
1044
|
+
}
|
|
1045
|
+
else if (resumeRollback !== null) {
|
|
1046
|
+
await this.#store.rollbackSessionResume(resumeRollback, { wait: true }).catch(() => false);
|
|
1047
|
+
await this.#refreshProjectContextBarrier();
|
|
1048
|
+
}
|
|
1049
|
+
if (error instanceof CodexTransportError) {
|
|
1050
|
+
const terminal = failureHandoff(error.code, 'run', failureStage(error.code, 'thread_start'));
|
|
1051
|
+
return terminal;
|
|
1052
|
+
}
|
|
1053
|
+
throw error;
|
|
1054
|
+
}
|
|
1055
|
+
const sessionId = session.session_id;
|
|
1056
|
+
this.#taskWorkspaces.set(slot.work.work_id, { workspace_id: workspace.workspace_id, session_id: sessionId });
|
|
1057
|
+
const transport = new ThreadObservingTransport(inner, {
|
|
1058
|
+
threadName: resumed === null ? title : null,
|
|
1059
|
+
onThreadReady: threadId => {
|
|
1060
|
+
if (reportedThreadId !== null && reportedThreadId !== threadId)
|
|
1061
|
+
bindingMismatch = true;
|
|
1062
|
+
reportedThreadId ??= threadId;
|
|
1063
|
+
if (resumed?.backend_session_id !== undefined && resumed.backend_session_id !== null) {
|
|
1064
|
+
if (threadId !== resumed.backend_session_id)
|
|
1065
|
+
bindingMismatch = true;
|
|
1066
|
+
}
|
|
1067
|
+
},
|
|
1068
|
+
// Codex may rename the thread; mirror it into the running work and the session title
|
|
1069
|
+
// (advisory: the store may still disambiguate against a sibling session).
|
|
1070
|
+
onThreadNamed: (threadId, name) => {
|
|
1071
|
+
if (threadId !== reportedThreadId || bindingMismatch)
|
|
1072
|
+
return;
|
|
1073
|
+
titleUpdates = titleUpdates.then(async () => {
|
|
1074
|
+
if (!await this.#store.setSessionTitle(sessionId, name))
|
|
1075
|
+
return;
|
|
1076
|
+
const saved = (await this.#store.snapshot()).sessions.find(item => item.session_id === sessionId);
|
|
1077
|
+
if (saved)
|
|
1078
|
+
slot.work = { ...slot.work, title: saved.display_title };
|
|
1079
|
+
await this.#refreshProjectContextBarrier();
|
|
1080
|
+
}).catch(() => undefined);
|
|
1081
|
+
},
|
|
1082
|
+
});
|
|
1083
|
+
const active = new CodexLiveAdapter(transport, undefined, {
|
|
1084
|
+
sharedState: this.#liveState,
|
|
1085
|
+
onValidatedOutcome: value => { disposition.value = value; },
|
|
1086
|
+
});
|
|
1087
|
+
slot.live = active;
|
|
1088
|
+
let sessionBound = false;
|
|
1089
|
+
try {
|
|
1090
|
+
await context.bindSession?.(sessionId);
|
|
1091
|
+
sessionBound = true;
|
|
1092
|
+
result = await active.dispatch('run', { work_order: workOrder }, context);
|
|
1093
|
+
await titleUpdates;
|
|
1094
|
+
}
|
|
1095
|
+
catch (error) {
|
|
1096
|
+
if (!slot.cancelled || !(error instanceof Error && error.name === 'AbortError'))
|
|
1097
|
+
throw error;
|
|
1098
|
+
result = {
|
|
1099
|
+
outcome: 'cancelled', trust: 'trusted_system',
|
|
1100
|
+
content: { reason: 'user_cancelled', work_id: slot.work.work_id },
|
|
1101
|
+
};
|
|
1102
|
+
}
|
|
1103
|
+
finally {
|
|
1104
|
+
slot.live = null;
|
|
1105
|
+
try {
|
|
1106
|
+
await active.close();
|
|
1107
|
+
}
|
|
1108
|
+
catch {
|
|
1109
|
+
// Completion evidence is already terminal. Retain cleanup ownership and fence the next
|
|
1110
|
+
// process until the transport's retryable close path succeeds.
|
|
1111
|
+
this.#retainedTransportCleanups.add(transport);
|
|
1112
|
+
}
|
|
1113
|
+
if (resumed === null) {
|
|
1114
|
+
if (reportedThreadId !== null && !bindingMismatch) {
|
|
1115
|
+
try {
|
|
1116
|
+
await this.#store.markSessionReady(session.session_id, reportedThreadId, { wait: true });
|
|
1117
|
+
}
|
|
1118
|
+
catch (error) {
|
|
1119
|
+
if (startRollback === null)
|
|
1120
|
+
throw new ProjectStateError('state_corrupt');
|
|
1121
|
+
await this.#store.rollbackSessionStartForRun(startRollback, { wait: true }).catch(() => false);
|
|
1122
|
+
if (!(error instanceof ProjectStateError && error.code === 'state_busy')) {
|
|
1123
|
+
reportedThreadId = null;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
else {
|
|
1128
|
+
if (startRollback === null)
|
|
1129
|
+
throw new ProjectStateError('state_corrupt');
|
|
1130
|
+
await this.#store.rollbackSessionStartForRun(startRollback, { wait: true }).catch(() => false);
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
else if (!sessionBound && resumeRollback !== null) {
|
|
1134
|
+
await this.#store.rollbackSessionResume(resumeRollback, { wait: true }).catch(() => false);
|
|
1135
|
+
}
|
|
1136
|
+
else if (bindingMismatch
|
|
1137
|
+
// A missing app-server thread is final. An ACP refusal (e.g. -32002) may follow a backend
|
|
1138
|
+
// upgrade, login or config change, so the session stays ready for an explicit retry.
|
|
1139
|
+
|| (disposition.value?.code === 'resume_unavailable' && session.backend_id === 'codex')) {
|
|
1140
|
+
await this.#store.markSessionUnavailable(session.session_id, { wait: true }).catch(() => undefined);
|
|
1141
|
+
}
|
|
1142
|
+
await this.#refreshProjectViewTolerant();
|
|
1143
|
+
}
|
|
1144
|
+
const transportResult = result ?? failureHandoff('transport_failure', 'run', 'thread_start');
|
|
1145
|
+
const terminal = bindingMismatch
|
|
1146
|
+
? failureHandoff('session_thread_mismatch', 'run', 'thread_start')
|
|
1147
|
+
: resumed === null && reportedThreadId === null && transportResult.outcome === 'ok'
|
|
1148
|
+
? failureHandoff('thread_id_invalid', 'run', 'thread_start')
|
|
1149
|
+
: transportResult;
|
|
1150
|
+
return terminal;
|
|
1151
|
+
}
|
|
1152
|
+
async #loadProjectContext() {
|
|
1153
|
+
this.#refreshSequence += 1;
|
|
1154
|
+
const sequence = this.#refreshSequence;
|
|
1155
|
+
const [stored, snapshot] = await Promise.all([this.#store.publicContext(false), this.#store.snapshot()]);
|
|
1156
|
+
if (sequence !== this.#refreshSequence)
|
|
1157
|
+
return null;
|
|
1158
|
+
this.#publicWorkspaceId = stored.workspace_id;
|
|
1159
|
+
this.#publicView = stored.view;
|
|
1160
|
+
this.#snapshot = snapshot;
|
|
1161
|
+
return Object.freeze({
|
|
1162
|
+
workspace_id: stored.workspace_id,
|
|
1163
|
+
view: this.publicProjectView(this.#confirmation.pending),
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
async #publishAdvisoryProjectView(context) {
|
|
1167
|
+
for (const observer of this.#projectViewObservers) {
|
|
1168
|
+
try {
|
|
1169
|
+
await observer(context.view);
|
|
1170
|
+
}
|
|
1171
|
+
catch { /* public rendering is advisory */ }
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
async #refreshProjectView() {
|
|
1175
|
+
const context = await this.#loadProjectContext();
|
|
1176
|
+
if (context !== null)
|
|
1177
|
+
await this.#publishAdvisoryProjectView(context);
|
|
1178
|
+
}
|
|
1179
|
+
async #refreshProjectContextBarrier() {
|
|
1180
|
+
const context = await this.#loadProjectContext();
|
|
1181
|
+
if (context === null)
|
|
1182
|
+
throw new ProjectStateError('context_delivery_failed');
|
|
1183
|
+
await this.#publishAdvisoryProjectView(context);
|
|
1184
|
+
for (const observer of this.#projectContextObservers) {
|
|
1185
|
+
try {
|
|
1186
|
+
await observer(context);
|
|
1187
|
+
}
|
|
1188
|
+
catch {
|
|
1189
|
+
throw new ProjectStateError('context_delivery_failed');
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
async #refreshProjectViewTolerant() {
|
|
1194
|
+
try {
|
|
1195
|
+
await this.#refreshProjectView();
|
|
1196
|
+
}
|
|
1197
|
+
catch (error) {
|
|
1198
|
+
if (!(error instanceof ProjectStateError) || error.code !== 'state_busy')
|
|
1199
|
+
throw error;
|
|
1200
|
+
await this.#publishAdvisoryProjectView(Object.freeze({
|
|
1201
|
+
workspace_id: this.#publicWorkspaceId,
|
|
1202
|
+
view: this.publicProjectView(this.#confirmation.pending),
|
|
1203
|
+
}));
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
async #drainRetainedTransportCleanups() {
|
|
1207
|
+
let firstFailure = null;
|
|
1208
|
+
for (const transport of [...this.#retainedTransportCleanups]) {
|
|
1209
|
+
try {
|
|
1210
|
+
await transport.close('shutdown');
|
|
1211
|
+
this.#retainedTransportCleanups.delete(transport);
|
|
1212
|
+
}
|
|
1213
|
+
catch (error) {
|
|
1214
|
+
firstFailure ??= projectCloseError(error);
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
if (firstFailure !== null)
|
|
1218
|
+
throw firstFailure;
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
class ThreadObservingTransport {
|
|
1222
|
+
inner;
|
|
1223
|
+
observation;
|
|
1224
|
+
constructor(inner, observation) {
|
|
1225
|
+
this.inner = inner;
|
|
1226
|
+
this.observation = observation;
|
|
1227
|
+
}
|
|
1228
|
+
preflight(deadline) {
|
|
1229
|
+
return this.inner.preflight(deadline);
|
|
1230
|
+
}
|
|
1231
|
+
prewarm(deadline) {
|
|
1232
|
+
return this.inner.prewarm(deadline);
|
|
1233
|
+
}
|
|
1234
|
+
run(input, observer, deadline, completionDeadline) {
|
|
1235
|
+
const { threadName, onThreadReady, onThreadNamed } = this.observation;
|
|
1236
|
+
return this.inner.run(threadName === null ? input : { ...input, threadName }, {
|
|
1237
|
+
...observer,
|
|
1238
|
+
onThreadReady: threadId => {
|
|
1239
|
+
onThreadReady(threadId);
|
|
1240
|
+
observer.onThreadReady?.(threadId);
|
|
1241
|
+
},
|
|
1242
|
+
onThreadNamed: (threadId, name) => {
|
|
1243
|
+
if (name !== null)
|
|
1244
|
+
onThreadNamed(threadId, name);
|
|
1245
|
+
observer.onThreadNamed?.(threadId, name);
|
|
1246
|
+
},
|
|
1247
|
+
}, deadline, completionDeadline);
|
|
1248
|
+
}
|
|
1249
|
+
steer(input, deadline) {
|
|
1250
|
+
return this.inner.steer(input, deadline);
|
|
1251
|
+
}
|
|
1252
|
+
close(reason) {
|
|
1253
|
+
return this.inner.close(reason);
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
const NULL_TRANSPORT = Object.freeze({
|
|
1257
|
+
preflight: () => Promise.reject(new Error('project transport absent')),
|
|
1258
|
+
prewarm: () => Promise.resolve(null),
|
|
1259
|
+
run: () => Promise.reject(new Error('project transport absent')),
|
|
1260
|
+
steer: () => Promise.resolve({ code: 'no_active_turn', written: false }),
|
|
1261
|
+
close: () => Promise.resolve(),
|
|
1262
|
+
});
|
|
1263
|
+
/** Spec 08 run refusals (`busy_project`, `capacity`): recoverable, the host re-plans. */
|
|
1264
|
+
function refusedRunHandoff(code, content) {
|
|
1265
|
+
return {
|
|
1266
|
+
outcome: 'refused',
|
|
1267
|
+
trust: 'trusted_system',
|
|
1268
|
+
content: { op: 'run', code, ...content, recoverable: true },
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
const PROJECT_REFUSAL_CODES = new Set([
|
|
1272
|
+
'workspace_name_conflict',
|
|
1273
|
+
'workspace_not_found',
|
|
1274
|
+
'session_not_found',
|
|
1275
|
+
'session_unavailable',
|
|
1276
|
+
'workspace_name_invalid',
|
|
1277
|
+
'workspace_limit',
|
|
1278
|
+
'session_limit',
|
|
1279
|
+
]);
|
|
1280
|
+
function projectProblemHandoff(code, op = 'run') {
|
|
1281
|
+
if (PROJECT_REFUSAL_CODES.has(code)) {
|
|
1282
|
+
return {
|
|
1283
|
+
outcome: 'refused',
|
|
1284
|
+
trust: 'trusted_system',
|
|
1285
|
+
content: { op, code, recoverable: true },
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
1288
|
+
return failureHandoff(code, op);
|
|
1289
|
+
}
|
|
1290
|
+
function projectNoActiveTurn() {
|
|
1291
|
+
return {
|
|
1292
|
+
outcome: 'failed',
|
|
1293
|
+
trust: 'trusted_system',
|
|
1294
|
+
content: { op: 'steer', worker: 'codex', code: 'no_active_turn' },
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
function projectErrorCode(error) {
|
|
1298
|
+
return error instanceof ProjectStateError ? error.code : 'state_corrupt';
|
|
1299
|
+
}
|
|
1300
|
+
function projectCloseError(error) {
|
|
1301
|
+
return error instanceof Error ? error : new Error('project close failed');
|
|
1302
|
+
}
|
|
1303
|
+
function commitResult(accepted, code, delegateId) {
|
|
1304
|
+
return Object.freeze({ accepted, code, ...(delegateId === undefined ? {} : { delegate_id: delegateId }) });
|
|
1305
|
+
}
|
|
1306
|
+
//# sourceMappingURL=adapter-project.js.map
|