@quantiya/codevibe-codex-plugin 2.0.6 → 2.0.8
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/README.md +20 -23
- package/dist/server.js +21 -21
- package/hooks/common.sh +506 -19
- package/{bin/codevibe-codex → libexec/companion-launcher} +37 -76
- package/node_modules/@quantiya/codevibe-core/README.md +7 -5
- package/node_modules/@quantiya/codevibe-core/dist/agy-cli-contract.d.ts +14 -0
- package/node_modules/@quantiya/codevibe-core/dist/appsync/appsync-client.d.ts +229 -61
- package/node_modules/@quantiya/codevibe-core/dist/appsync/event-throttle.d.ts +33 -0
- package/node_modules/@quantiya/codevibe-core/dist/appsync/index.d.ts +3 -2
- package/node_modules/@quantiya/codevibe-core/dist/appsync/queries.d.ts +6 -2
- package/node_modules/@quantiya/codevibe-core/dist/auth/auth-telemetry.d.ts +26 -0
- package/node_modules/@quantiya/codevibe-core/dist/auth/keychain-cli.d.ts +6 -0
- package/node_modules/@quantiya/codevibe-core/dist/auth/vendor-key-cli.d.ts +49 -0
- package/node_modules/@quantiya/codevibe-core/dist/companion-mode/index.d.ts +50 -22
- package/node_modules/@quantiya/codevibe-core/dist/companion-mode/persist-preference.d.ts +1 -5
- package/node_modules/@quantiya/codevibe-core/dist/companion-mode/resolve-agent.d.ts +5 -4
- package/node_modules/@quantiya/codevibe-core/dist/config/config.d.ts +0 -5
- package/node_modules/@quantiya/codevibe-core/dist/credential-broker/__tests__/oauth-refresh.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/credential-broker/__tests__/upstream-result-helpers.d.ts +21 -0
- package/node_modules/@quantiya/codevibe-core/dist/credential-broker/broker.d.ts +196 -12
- package/node_modules/@quantiya/codevibe-core/dist/credential-broker/chatgpt-config.d.ts +40 -0
- package/node_modules/@quantiya/codevibe-core/dist/credential-broker/index.d.ts +4 -1
- package/node_modules/@quantiya/codevibe-core/dist/credential-broker/oauth-account-lock.d.ts +150 -0
- package/node_modules/@quantiya/codevibe-core/dist/credential-broker/oauth-refresh.d.ts +72 -0
- package/node_modules/@quantiya/codevibe-core/dist/credential-broker/types.d.ts +165 -17
- package/node_modules/@quantiya/codevibe-core/dist/credential-broker/upstream-client.d.ts +3 -2
- package/node_modules/@quantiya/codevibe-core/dist/credential-broker/vendor-key-store.d.ts +32 -1
- package/node_modules/@quantiya/codevibe-core/dist/crypto/__tests__/encrypt-for-emit.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/crypto/__tests__/open-prompt-id.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/crypto/encrypt-for-emit.d.ts +39 -0
- package/node_modules/@quantiya/codevibe-core/dist/crypto/index.d.ts +3 -0
- package/node_modules/@quantiya/codevibe-core/dist/crypto/open-prompt-id.d.ts +36 -0
- package/node_modules/@quantiya/codevibe-core/dist/daemon/__tests__/process-guards.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/daemon/index.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/dist/daemon/process-guards.d.ts +38 -0
- package/node_modules/@quantiya/codevibe-core/dist/e1/__tests__/prompt-raise.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/e1/index.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/dist/e1/prompt-raise.d.ts +65 -0
- package/node_modules/@quantiya/codevibe-core/dist/index.d.ts +20 -2
- package/node_modules/@quantiya/codevibe-core/dist/index.js +4543 -288
- package/node_modules/@quantiya/codevibe-core/dist/keychain/__tests__/keychain-manager.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/keychain/__tests__/keychain-migrate.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/keychain/keychain-backend.d.ts +105 -0
- package/node_modules/@quantiya/codevibe-core/dist/keychain/keychain-manager.d.ts +40 -5
- package/node_modules/@quantiya/codevibe-core/dist/keychain/keychain-migrate.d.ts +46 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/anchored-fs.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/bounded-directory.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/bounded-output.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/durable-directory.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/hosted-class-a-sink.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/process-identity.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/process-tree.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/publication-authority-capability.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/reviewer-rationale-flag.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/snapshot-merge.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/workspace-authority-fixture.d.ts +3 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/workspace-authority.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/__tests__/workspace-materializer.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/agentic-disposable-repo.d.ts +23 -6
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/agentic-resolve.d.ts +16 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/anchored-fs.d.ts +243 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/bounded-directory.d.ts +64 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/bounded-helper.d.ts +22 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/bounded-output.d.ts +11 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/class-a-emit.d.ts +13 -1
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/class-a-sign.d.ts +15 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/durable-directory.d.ts +25 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/durable-store.d.ts +217 -25
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/group-decision-outcome.d.ts +11 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/hosted-class-a-sink.d.ts +27 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/implementor-argv.d.ts +89 -7
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/index.d.ts +3 -2
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/local-executor-impl.d.ts +177 -76
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/merge-conflict-resolve.d.ts +19 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/process-identity.d.ts +16 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/process-tree.d.ts +123 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/revert-reconcile.d.ts +16 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/revert-runner.d.ts +14 -1
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/reviewer-rationale-flag.d.ts +10 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/snapshot-merge.d.ts +124 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/task-group-types.d.ts +7 -6
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/team-execution-flag.d.ts +2 -2
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/track-registry.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/types.d.ts +34 -2
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/verification-gates/build.d.ts +5 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/verification-gates/deploy-preflight.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/verification-gates/diff-sanity.d.ts +12 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/verification-gates/hostile-grep.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/verification-gates/lint.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/verification-gates/shell-runner.d.ts +5 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/verification-gates/source-traceability.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/verification-gates/tests.d.ts +3 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/verification-gates/typecheck.d.ts +3 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/verification-runner.d.ts +6 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/workspace-authority.d.ts +45 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/workspace-materializer.d.ts +27 -0
- package/node_modules/@quantiya/codevibe-core/dist/local-executor/workspace-shadow.d.ts +378 -85
- package/node_modules/@quantiya/codevibe-core/dist/local-model/manager.d.ts +1 -1
- package/node_modules/@quantiya/codevibe-core/dist/local-model/ollama.d.ts +40 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/__tests__/detect-agents.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/detect-agents.d.ts +10 -30
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/index.d.ts +1 -2
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/a1a-planner-offers.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/a6-cli-surface.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/advisory-attachment-journal.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/advisory-attachments-dir-race.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/advisory-multi-mention-panel.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/advisory-panel-attachments.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/advisory-quota-stdout-result.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/agent-turn-context-batch.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/bounded-shutdown.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/brainstorm-quorum-wiring.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/brainstorm-quorum.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/cli-team-session-key.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/command-intent.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/context-compaction.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/context-items-hosted-sync.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/context-items-wiring.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/context-items.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/cp8-full-team-events.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/cp8-team-decomposed-zk.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/explicit-tty-exit.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/mention-suggest.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/planner-offer-e1.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/route-browse-summarize-recovery.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/__tests__/workspace-shutdown.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/advisory-attachment-journal.d.ts +165 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/attachments.d.ts +53 -8
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/bounded-shutdown.d.ts +22 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/brainstorm-quorum.d.ts +118 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/cli.d.ts +97 -70
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/cli.js +51847 -33465
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/command-intent.d.ts +56 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/components/InputBar.d.ts +6 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/components/OrchestrationApp.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/context-compaction.d.ts +264 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/context-items-hosted-sync.d.ts +19 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/context-items.d.ts +408 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/context-store.d.ts +162 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/declared-test-runner.d.ts +21 -2
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/emit-shell-event.d.ts +41 -13
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/explicit-tty-exit.d.ts +17 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/gate-decision-submit.d.ts +11 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/gate-prompts.d.ts +78 -3
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/index.d.ts +309 -37
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/mention-suggest.d.ts +11 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/mode-selection.d.ts +4 -22
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/planner-offer-e1.d.ts +97 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/quorum-loop.d.ts +603 -77
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/reducer.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/task-progress.d.ts +17 -4
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/team-decompose.d.ts +47 -29
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/types.d.ts +103 -6
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/workspace-shutdown.d.ts +27 -0
- package/node_modules/@quantiya/codevibe-core/dist/planner/index.d.ts +1 -1
- package/node_modules/@quantiya/codevibe-core/dist/planner/local-advisory.d.ts +12 -0
- package/node_modules/@quantiya/codevibe-core/dist/planner/local-gemma.d.ts +27 -0
- package/node_modules/@quantiya/codevibe-core/dist/planner/types.d.ts +7 -0
- package/node_modules/@quantiya/codevibe-core/dist/reviewer/index.d.ts +0 -2
- package/node_modules/@quantiya/codevibe-core/dist/reviewer/output-parser.d.ts +19 -0
- package/node_modules/@quantiya/codevibe-core/dist/reviewer/provider.d.ts +9 -6
- package/node_modules/@quantiya/codevibe-core/dist/reviewer/providers/antigravity.d.ts +2 -3
- package/node_modules/@quantiya/codevibe-core/dist/reviewer/registry.d.ts +9 -4
- package/node_modules/@quantiya/codevibe-core/dist/reviewer/token-usage.d.ts +10 -0
- package/node_modules/@quantiya/codevibe-core/dist/reviewer/types.d.ts +3 -0
- package/node_modules/@quantiya/codevibe-core/dist/reviewer/verdict-classifier.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/session/__tests__/device-registration-lease.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/session/__tests__/pending-session-create.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/session/__tests__/session-rekey-fingerprint.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/session/__tests__/session-resume-key-reconciliation.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/session/__tests__/session-resume-pending-first.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/session/device-key-watcher.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/session/index.d.ts +4 -2
- package/node_modules/@quantiya/codevibe-core/dist/session/pending-session-create.d.ts +61 -0
- package/node_modules/@quantiya/codevibe-core/dist/session/register-device-key.d.ts +11 -1
- package/node_modules/@quantiya/codevibe-core/dist/session/session-rekey.d.ts +8 -8
- package/node_modules/@quantiya/codevibe-core/dist/session/session-resume.d.ts +21 -1
- package/node_modules/@quantiya/codevibe-core/dist/substrate/command-runner.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/dist/substrate/docker.d.ts +14 -32
- package/node_modules/@quantiya/codevibe-core/dist/substrate/index.d.ts +0 -1
- package/node_modules/@quantiya/codevibe-core/dist/substrate/sandbox-exec.d.ts +17 -16
- package/node_modules/@quantiya/codevibe-core/dist/substrate/types.d.ts +39 -5
- package/node_modules/@quantiya/codevibe-core/dist/substrate-launch/__tests__/reviewer-credential-preflight.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/substrate-launch/apikey-bootstrap.d.ts +24 -1
- package/node_modules/@quantiya/codevibe-core/dist/substrate-launch/engage-substrate.d.ts +20 -0
- package/node_modules/@quantiya/codevibe-core/dist/substrate-launch/index.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/dist/substrate-launch/reviewer-credential-preflight.d.ts +50 -0
- package/node_modules/@quantiya/codevibe-core/dist/substrate-launch/sanitized-env.d.ts +5 -5
- package/node_modules/@quantiya/codevibe-core/dist/test-publication-authority-setup.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/__tests__/consolidator.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/__tests__/digest.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/__tests__/flock-rollout-lock.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/__tests__/ledger.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/__tests__/outbox.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/__tests__/replay-cursor.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/__tests__/session-map.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/__tests__/socket-rollout-lock.test.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/atomic-file.d.ts +27 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/consolidator.d.ts +253 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/digest.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/flock-rollout-lock.d.ts +68 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/index.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/ledger.d.ts +274 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/outbox.d.ts +60 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/replay-cursor.d.ts +190 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/session-map.d.ts +133 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/socket-rollout-lock.d.ts +57 -0
- package/node_modules/@quantiya/codevibe-core/dist/tool-activity/types.d.ts +368 -0
- package/node_modules/@quantiya/codevibe-core/dist/types/encryption.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/dist/types/events.d.ts +29 -4
- package/node_modules/@quantiya/codevibe-core/dist/types/session.d.ts +32 -2
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/README.md +207 -163
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/index.d.ts +15 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/index.js +31 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/max.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/max.js +3 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/md5.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/md5.js +13 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/native.d.ts +6 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/native.js +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/nil.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/nil.js +3 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/package.json +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/parse.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/parse.js +11 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/regex.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/regex.js +3 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/rng.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/rng.js +13 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/sha1.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/sha1.js +13 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/stringify.d.ts +3 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/stringify.js +39 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/types.d.ts +21 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/types.js +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/uuid-bin.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/uuid-bin.js +72 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v1.d.ts +11 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v1.js +87 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v1ToV6.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v1ToV6.js +13 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v3.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v3.js +14 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v35.d.ts +7 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v35.js +44 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v4.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v4.js +29 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v5.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v5.js +14 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v6.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v6.js +22 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v6ToV1.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v6ToV1.js +13 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v7.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/v7.js +69 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/validate.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/validate.js +7 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/version.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs/version.js +10 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/index.d.ts +15 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/index.js +31 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/max.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/max.js +3 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/md5.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/md5.js +137 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/native.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/native.js +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/nil.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/nil.js +3 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/package.json +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/parse.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/parse.js +11 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/regex.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/regex.js +3 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/rng.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/rng.js +14 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/sha1.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/sha1.js +72 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/stringify.d.ts +3 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/stringify.js +39 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/types.d.ts +21 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/types.js +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/uuid-bin.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/uuid-bin.js +72 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v1.d.ts +11 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v1.js +87 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v1ToV6.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v1ToV6.js +13 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v3.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v3.js +14 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v35.d.ts +7 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v35.js +44 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v4.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v4.js +29 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v5.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v5.js +14 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v6.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v6.js +22 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v6ToV1.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v6ToV1.js +13 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v7.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/v7.js +69 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/validate.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/validate.js +7 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/version.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/cjs-browser/version.js +10 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/bin/uuid +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/index.d.ts +15 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/{esm-node → esm}/index.js +9 -4
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/max.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/max.js +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/md5.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/md5.js +11 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/native.d.ts +6 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/native.js +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/nil.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/nil.js +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/parse.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/parse.js +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/regex.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/regex.js +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/rng.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/rng.js +10 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/sha1.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/sha1.js +11 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/stringify.d.ts +3 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/stringify.js +35 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/types.d.ts +21 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/types.js +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/uuid-bin.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/uuid-bin.js +70 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v1.d.ts +11 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v1.js +83 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v1ToV6.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v1ToV6.js +10 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v3.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v3.js +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v35.d.ts +7 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v35.js +39 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v4.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v4.js +27 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v5.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v5.js +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v6.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v6.js +20 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v6ToV1.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v6ToV1.js +10 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v7.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/v7.js +65 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/validate.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/validate.js +5 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/version.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm/version.js +8 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/index.d.ts +15 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/index.js +9 -4
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/max.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/max.js +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/md5.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/md5.js +113 -193
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/native.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/native.js +1 -3
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/nil.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/nil.js +1 -1
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/parse.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/parse.js +6 -32
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/regex.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/regex.js +1 -1
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/rng.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/rng.js +6 -13
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/sha1.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/sha1.js +62 -88
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/stringify.d.ts +3 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/stringify.js +27 -25
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/types.d.ts +21 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/types.js +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/uuid-bin.d.ts +1 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/uuid-bin.js +70 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v1.d.ts +11 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v1.js +78 -90
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v1ToV6.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v1ToV6.js +10 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v3.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v3.js +8 -3
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v35.d.ts +7 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v35.js +30 -57
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v4.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v4.js +21 -23
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v5.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v5.js +8 -3
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v6.d.ts +4 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v6.js +20 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v6ToV1.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v6ToV1.js +10 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v7.d.ts +9 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/v7.js +65 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/validate.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/validate.js +2 -4
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/version.d.ts +2 -0
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-browser/version.js +5 -8
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/package.json +73 -76
- package/node_modules/@quantiya/codevibe-core/package.json +7 -6
- package/node_modules/fs-ext/.eslintrc +53 -0
- package/node_modules/fs-ext/.github/workflows/node.js.yml +31 -0
- package/node_modules/fs-ext/.travis.yml +25 -0
- package/node_modules/fs-ext/LICENSE.txt +18 -0
- package/node_modules/fs-ext/README.md +130 -0
- package/node_modules/fs-ext/appveyor.yml +20 -0
- package/node_modules/fs-ext/binding.gyp +11 -0
- package/node_modules/fs-ext/build/Makefile +347 -0
- package/node_modules/fs-ext/build/Release/.deps/Release/fs_ext.node.d +1 -0
- package/node_modules/fs-ext/build/Release/.deps/Release/obj.target/fs_ext/fs-ext.o.d +165 -0
- package/node_modules/fs-ext/build/Release/fs_ext.node +0 -0
- package/node_modules/fs-ext/build/Release/obj.target/fs_ext/fs-ext.o +0 -0
- package/node_modules/fs-ext/build/binding.Makefile +6 -0
- package/node_modules/fs-ext/build/config.gypi +504 -0
- package/node_modules/fs-ext/build/fs_ext.target.mk +183 -0
- package/node_modules/fs-ext/build/gyp-mac-tool +768 -0
- package/node_modules/fs-ext/example.js +57 -0
- package/node_modules/fs-ext/fs-ext.cc +622 -0
- package/node_modules/fs-ext/fs-ext.js +131 -0
- package/node_modules/fs-ext/package.json +42 -0
- package/node_modules/fs-ext/run_tests.js +17 -0
- package/node_modules/fs-ext/tests/test-fs-fcntl.js +350 -0
- package/node_modules/fs-ext/tests/test-fs-flock.js +452 -0
- package/node_modules/fs-ext/tests/test-fs-flock_stress.js +239 -0
- package/node_modules/fs-ext/tests/test-fs-seek.js +607 -0
- package/node_modules/fs-ext/tests/test-fs-seek_stress.js +313 -0
- package/node_modules/fs-ext/tests/test-fs-statvfs.js +15 -0
- package/node_modules/fs-ext/tests/worker-test.js +56 -0
- package/node_modules/fs-ext/wscript +15 -0
- package/node_modules/nan/.github/workflows/ci.yml +46 -0
- package/node_modules/nan/.pre-commit-config.yaml +8 -0
- package/node_modules/nan/CHANGELOG.md +605 -0
- package/node_modules/nan/CMakeLists.txt +138 -0
- package/node_modules/nan/LICENSE.md +9 -0
- package/node_modules/nan/README.md +457 -0
- package/node_modules/nan/doc/asyncworker.md +146 -0
- package/node_modules/nan/doc/buffers.md +54 -0
- package/node_modules/nan/doc/callback.md +76 -0
- package/node_modules/nan/doc/converters.md +41 -0
- package/node_modules/nan/doc/errors.md +226 -0
- package/node_modules/nan/doc/json.md +62 -0
- package/node_modules/nan/doc/maybe_types.md +583 -0
- package/node_modules/nan/doc/methods.md +689 -0
- package/node_modules/nan/doc/new.md +147 -0
- package/node_modules/nan/doc/node_misc.md +123 -0
- package/node_modules/nan/doc/object_wrappers.md +263 -0
- package/node_modules/nan/doc/persistent.md +296 -0
- package/node_modules/nan/doc/scopes.md +73 -0
- package/node_modules/nan/doc/script.md +58 -0
- package/node_modules/nan/doc/string_bytes.md +81 -0
- package/node_modules/nan/doc/v8_internals.md +211 -0
- package/node_modules/nan/doc/v8_misc.md +85 -0
- package/node_modules/nan/include_dirs.js +1 -0
- package/node_modules/nan/nan.h +3202 -0
- package/node_modules/nan/nan_callbacks.h +141 -0
- package/node_modules/nan/nan_callbacks_12_inl.h +730 -0
- package/node_modules/nan/nan_callbacks_pre_12_inl.h +528 -0
- package/node_modules/nan/nan_converters.h +72 -0
- package/node_modules/nan/nan_converters_43_inl.h +68 -0
- package/node_modules/nan/nan_converters_pre_43_inl.h +42 -0
- package/node_modules/nan/nan_define_own_property_helper.h +29 -0
- package/node_modules/nan/nan_implementation_12_inl.h +446 -0
- package/node_modules/nan/nan_implementation_pre_12_inl.h +263 -0
- package/node_modules/nan/nan_json.h +166 -0
- package/node_modules/nan/nan_maybe_43_inl.h +360 -0
- package/node_modules/nan/nan_maybe_pre_43_inl.h +268 -0
- package/node_modules/nan/nan_new.h +340 -0
- package/node_modules/nan/nan_object_wrap.h +156 -0
- package/node_modules/nan/nan_persistent_12_inl.h +132 -0
- package/node_modules/nan/nan_persistent_pre_12_inl.h +242 -0
- package/node_modules/nan/nan_private.h +73 -0
- package/node_modules/nan/nan_scriptorigin.h +97 -0
- package/node_modules/nan/nan_string_bytes.h +305 -0
- package/node_modules/nan/nan_typedarray_contents.h +96 -0
- package/node_modules/nan/nan_weak.h +453 -0
- package/node_modules/nan/package.json +38 -0
- package/node_modules/nan/tools/1to2.js +412 -0
- package/node_modules/nan/tools/README.md +14 -0
- package/node_modules/nan/tools/package.json +19 -0
- package/package.json +5 -5
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/orchestration-cli.d.ts +0 -12
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/setup-bootstrap.d.ts +0 -146
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/setup-failure-recourse.d.ts +0 -23
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/setup-save.d.ts +0 -47
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/setup-seat-picker.d.ts +0 -72
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/setup-telemetry.d.ts +0 -54
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/setup-test-agents.d.ts +0 -108
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/setup-types.d.ts +0 -146
- package/node_modules/@quantiya/codevibe-core/dist/orchestration/setup-wizard.d.ts +0 -57
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/cohort-flag.d.ts +0 -16
- package/node_modules/@quantiya/codevibe-core/dist/reviewer/providers/gemini.d.ts +0 -109
- package/node_modules/@quantiya/codevibe-core/dist/substrate/git-proxy.d.ts +0 -35
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/CHANGELOG.md +0 -274
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/CONTRIBUTING.md +0 -18
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/bin/uuid +0 -2
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/index.js +0 -79
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/md5.js +0 -223
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/native.js +0 -11
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/nil.js +0 -8
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/parse.js +0 -45
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/regex.js +0 -8
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/rng.js +0 -25
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/sha1.js +0 -104
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/stringify.js +0 -44
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/v1.js +0 -107
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/v3.js +0 -16
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/v35.js +0 -80
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/v4.js +0 -43
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/v5.js +0 -16
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/validate.js +0 -17
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/commonjs-browser/version.js +0 -21
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/md5.js +0 -13
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/native.js +0 -4
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/nil.js +0 -1
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/parse.js +0 -35
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/regex.js +0 -1
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/rng.js +0 -12
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/sha1.js +0 -13
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/stringify.js +0 -33
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/v1.js +0 -95
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/v3.js +0 -4
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/v35.js +0 -66
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/v4.js +0 -29
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/v5.js +0 -4
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/validate.js +0 -7
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/esm-node/version.js +0 -11
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/index.js +0 -79
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/md5-browser.js +0 -223
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/md5.js +0 -23
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/native-browser.js +0 -11
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/native.js +0 -15
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/nil.js +0 -8
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/parse.js +0 -45
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/regex.js +0 -8
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/rng-browser.js +0 -25
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/rng.js +0 -24
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/sha1-browser.js +0 -104
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/sha1.js +0 -23
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/stringify.js +0 -44
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/uuid-bin.js +0 -85
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/v1.js +0 -107
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/v3.js +0 -16
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/v35.js +0 -80
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/v4.js +0 -43
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/v5.js +0 -16
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/validate.js +0 -17
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/dist/version.js +0 -21
- package/node_modules/@quantiya/codevibe-core/node_modules/uuid/wrapper.mjs +0 -10
- /package/node_modules/@quantiya/codevibe-core/dist/{companion-mode/__tests__/detect-parallel.test.d.ts → appsync/__tests__/appsync-client-context-items.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{orchestration-shell/__tests__/cli-stub-session-adapter.test.d.ts → appsync/__tests__/heartbeat-active.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{orchestration/__tests__/setup-bootstrap.test.d.ts → appsync/__tests__/orphan-sweep-null-heartbeat.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{orchestration/__tests__/setup-failure-recourse.test.d.ts → appsync/__tests__/refresh-open-prompt-ttl-chunk.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{orchestration/__tests__/setup-save.test.d.ts → auth/__tests__/keychain-cli.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{orchestration/__tests__/setup-seat-picker.test.d.ts → auth/__tests__/vendor-key-cli.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{orchestration/__tests__/setup-telemetry.test.d.ts → companion-mode/__tests__/mode-selected-emit.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{orchestration/__tests__/setup-test-agents.test.d.ts → companion-mode/__tests__/private-launcher-detection.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{orchestration/__tests__/setup-types.test.d.ts → companion-mode/__tests__/private-launcher-path.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{orchestration/__tests__/setup-wizard.test.d.ts → credential-broker/__tests__/broker-c4.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{reviewer/providers/__tests__/gemini-live-smoke.test.d.ts → credential-broker/__tests__/broker-streaming.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{reviewer/providers/__tests__/gemini.test.d.ts → credential-broker/__tests__/chatgpt-config.test.d.ts} +0 -0
- /package/node_modules/@quantiya/codevibe-core/dist/{substrate/__tests__/git-proxy.test.d.ts → credential-broker/__tests__/oauth-account-lock.test.d.ts} +0 -0
package/dist/server.js
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`),
|
|
3
|
-
`);for(;u!==-1;){if(i!==this.readGeneration){o.destroy();return}let
|
|
4
|
-
`)}}}catch(
|
|
5
|
-
${
|
|
6
|
-
`))if(!(i.test(s)||s.startsWith("***")||s.startsWith("---")||s.startsWith("+++"))){if(s.startsWith("-"))e.push(s.slice(1));else if(s.startsWith("+"))t.push(s.slice(1));else if(s.startsWith(" ")){let
|
|
1
|
+
"use strict";var Be=Object.create;var M=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var qe=(c,e)=>{for(var t in e)M(c,t,{get:e[t],enumerable:!0})},re=(c,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ue(e))!ze.call(c,s)&&s!==t&&M(c,s,{get:()=>e[s],enumerable:!(i=Ke(e,s))||i.enumerable});return c};var P=(c,e,t)=>(t=c!=null?Be($e(c)):{},re(e||!c||!c.__esModule?M(t,"default",{value:c,enumerable:!0}):t,c)),He=c=>re(M({},"__esModule",{value:!0}),c);var It={};qe(It,{CodexCompanionServer:()=>V,extractShellCommandFromPromptText:()=>Me,extractShellCommandPartsFromPromptText:()=>ie});module.exports=He(It);var Fe=require("uuid"),ee=P(require("crypto")),A=P(require("fs")),N=P(require("path")),De=P(require("os")),te=require("util"),G=require("child_process"),d=require("@quantiya/codevibe-core");var ne=P(require("os")),oe=P(require("path")),ae=require("@quantiya/codevibe-core"),n=(0,ae.createLogger)({name:"codevibe-codex",logFile:oe.default.join(ne.default.tmpdir(),"codevibe-codex-mcp.log"),level:"debug"});var le=require("events"),S=P(require("fs")),_=P(require("path")),pe=require("string_decoder"),ce=require("chokidar"),de=require("@quantiya/codevibe-core");var We=256*1024,L=class extends le.EventEmitter{constructor(){super();this.watcher=null;this.filePositions=new Map;this.activeLogFile=null;this.sessionId=null;this.isWatching=!1;this.startTime=0;this.sessionsDir=null;this.activeReads=new Map;this.pendingReads=new Set;this.readGeneration=0;this.bindSource=null;this.authoritativeSessionId=null;this.pendingTranscriptBind=null;this.startBaselineSizes=new Map}start(){if(this.isWatching){n.warn("Session log watcher already running");return}let t=(0,de.getConfig)().codex.sessionsDir;this.sessionsDir=t,n.info("Starting Codex session log watcher",{sessionsDir:t}),S.existsSync(t)||(n.info("Codex sessions directory does not exist yet, creating...",{sessionsDir:t}),S.mkdirSync(t,{recursive:!0})),this.startTime=Date.now(),this.readGeneration++,this.bindSource=null,this.authoritativeSessionId=null,this.snapshotStartBaselines(t),this.drainPendingTranscriptBind(),this.watcher=(0,ce.watch)(t,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},depth:4,ignored:i=>{let s=_.basename(i);return S.existsSync(i)&&S.statSync(i).isDirectory()?!1:!s.startsWith("rollout-")||!s.endsWith(".jsonl")}}),this.watcher.on("add",i=>{i.endsWith(".jsonl")&&this.onFileAdded(i)}),this.watcher.on("change",i=>{i.endsWith(".jsonl")&&this.onFileChanged(i)}),this.watcher.on("error",i=>{n.error("Watcher error:",i),this.emit("error",i)}),this.watcher.on("ready",()=>{n.info("Session log watcher ready"),this.bindRecentSessionFile()}),this.isWatching=!0,n.info("Session log watcher started")}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.isWatching=!1,this.readGeneration++,this.filePositions.clear(),this.activeReads.clear(),this.pendingReads.clear(),this.activeLogFile=null,this.sessionId=null,this.sessionsDir=null,this.bindSource=null,this.authoritativeSessionId=null,this.pendingTranscriptBind=null,this.startBaselineSizes.clear(),n.info("Session log watcher stopped")}getSessionId(){return this.sessionId}getActiveLogFile(){return this.activeLogFile}getBindSource(){return this.bindSource}getAuthoritativeSessionId(){return this.authoritativeSessionId}tryRealpath(t){try{return S.realpathSync(t)}catch{return null}}isInteractiveRollout(t){return!(!t||t.originator==="codex_exec"||t.threadSource==="subagent"||t.sourceSubagent)}computeSeedOffset(t){let i;try{i=S.statSync(t)}catch{return 0}if(this.getSessionAgeMs(t,i)>=this.startTime)return 0;let r=this.startBaselineSizes.get(t);return r!==void 0?r:i.size}applyBind(t,i){this.readGeneration++,this.activeReads.delete(t),this.pendingReads.delete(t),this.activeLogFile=t,this.bindSource=i,i==="heuristic"&&(this.authoritativeSessionId=null),this.filePositions.has(t)||this.filePositions.set(t,this.computeSeedOffset(t)),this.scheduleReadNewLines(t)}bindToFile(t){let i=this.tryRealpath(t);if(!i){n.warn("bindToFile: could not canonicalize path; skipping",{filePath:t});return}if(i===this.activeLogFile){this.bindSource="authoritative";return}n.info("bindToFile: authoritative bind to session rollout",{filePath:i}),this.applyBind(i,"authoritative")}async bindToSessionTranscript(t,i){if(typeof t!="string"||t.length===0)return!1;if(!this.sessionsDir)return this.pendingTranscriptBind={transcriptPath:t,expectedSessionId:i},n.debug("bindToSessionTranscript: watcher not started yet; queued pending authoritative bind",{transcriptPath:t,expectedSessionId:i}),!1;let s=this.tryRealpath(t),r=this.tryRealpath(this.sessionsDir);if(!s||!r)return!1;let o=_.relative(r,s);if(o===".."||o.startsWith(".."+_.sep)||_.isAbsolute(o))return n.warn("bindToSessionTranscript: path not under sessionsDir; rejecting",{transcriptPath:s}),!1;let l=_.basename(s);if(!l.startsWith("rollout-")||!l.endsWith(".jsonl"))return!1;let a=null;for(let p=0;p<3&&(a=this.readSessionMeta(s),!a);p++)await new Promise(u=>setTimeout(u,20));return!a||a.id!==i?(n.debug("bindToSessionTranscript: meta missing or id mismatch; not binding",{transcriptPath:s,metaId:a?.id,expectedSessionId:i}),!1):this.isInteractiveRollout(a)?(this.bindToFile(s),this.authoritativeSessionId=i,!0):(n.debug("bindToSessionTranscript: non-interactive rollout (codex_exec/subagent); not binding",{transcriptPath:s,originator:a.originator,threadSource:a.threadSource}),!1)}async drainPendingTranscriptBind(){let t=this.pendingTranscriptBind;t&&(this.pendingTranscriptBind=null,await this.bindToSessionTranscript(t.transcriptPath,t.expectedSessionId))}onFileAdded(t){let i=this.tryRealpath(t);if(!i)return;try{let r=S.statSync(i);if((r.birthtimeMs||r.ctimeMs)<this.startTime-5e3)return}catch{}if(this.activeLogFile)return;let s=this.readSessionMeta(i);if(!this.isInteractiveRollout(s)){n.debug("Ignoring non-interactive rollout (add)",{filePath:i,originator:s?.originator,threadSource:s?.threadSource});return}n.info("New Codex session log detected (heuristic bind)",{filePath:i}),this.applyBind(i,"heuristic")}onFileChanged(t){let i=this.tryRealpath(t);if(i&&!(this.activeLogFile&&i!==this.activeLogFile)){if(!this.activeLogFile){let s=!1;try{let o=S.statSync(i);s=this.getSessionAgeMs(i,o)>=this.startTime-5e3||o.mtimeMs>=this.startTime-5e3}catch{}if(!s)return;let r=this.readSessionMeta(i);if(!this.isInteractiveRollout(r)){n.debug("Ignoring non-interactive rollout (change)",{filePath:i,originator:r?.originator});return}n.info("Binding session log on change (heuristic)",{filePath:i}),this.applyBind(i,"heuristic");return}this.scheduleReadNewLines(i)}}readSessionMeta(t){let i=null;try{i=S.openSync(t,"r");let s=new pe.StringDecoder("utf8"),r=Buffer.alloc(64*1024),o="",l=0,a=-1;for(;l<We;){let m=S.readSync(i,r,0,r.length,l);if(m<=0||(l+=m,o+=s.write(r.subarray(0,m)),a=o.indexOf(`
|
|
2
|
+
`),a!==-1))break}o+=s.end();let p=a===-1?o:o.slice(0,a);if(!p.trim())return null;let u=JSON.parse(p),h=u.payload||{};return{id:typeof h.id=="string"?h.id:void 0,timestamp:typeof u.timestamp=="string"?u.timestamp:void 0,originator:typeof h.originator=="string"?h.originator:void 0,cwd:typeof h.cwd=="string"?h.cwd:void 0,threadSource:typeof h.thread_source=="string"?h.thread_source:void 0,sourceSubagent:!!(h.source&&typeof h.source=="object"&&h.source.subagent)}}catch{return null}finally{if(i!==null)try{S.closeSync(i)}catch{}}}snapshotStartBaselines(t){this.startBaselineSizes.clear();try{for(let{filePath:i,size:s}of this.collectRecentSessionFiles(t,!0)){let r=this.tryRealpath(i);r&&this.startBaselineSizes.set(r,s)}}catch{}}getSessionAgeMs(t,i){let s=this.readSessionMeta(t);if(s?.timestamp){let r=Date.parse(s.timestamp);if(!Number.isNaN(r))return r}return i.birthtimeMs||i.ctimeMs}bindRecentSessionFile(){if(!(this.activeLogFile||!this.sessionsDir))try{let t=this.collectRecentSessionFiles(this.sessionsDir).sort((i,s)=>s.modifiedAt-i.modifiedAt);for(let i of t){let s=this.tryRealpath(i.filePath);if(!s)continue;let r=this.readSessionMeta(s);if(this.isInteractiveRollout(r)){n.info("Binding recent interactive session file missed during initial scan",{filePath:s,watcherStartTime:new Date(this.startTime).toISOString()}),this.applyBind(s,"heuristic");return}}}catch(t){n.warn("Failed to backfill recent session file",{error:t})}}collectRecentSessionFiles(t,i=!1){let s=[],r=[t];for(;r.length>0;){let o=r.pop();if(!o)continue;let l;try{l=S.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let a of l){let p=_.join(o,a.name);if(a.isDirectory()){r.push(p);continue}if(!(!a.isFile()||!a.name.startsWith("rollout-")||!a.name.endsWith(".jsonl")))try{let u=S.statSync(p),h=u.birthtimeMs||u.ctimeMs,m=u.mtimeMs;(i||h>=this.startTime||m>=this.startTime-5e3)&&s.push({filePath:p,createdAt:h,modifiedAt:m,size:u.size})}catch{}}}return s}scheduleReadNewLines(t){let i=this.activeReads.get(t);if(i)return this.pendingReads.add(t),i;let s=this.readGeneration,r=this.drainReadQueue(t,s);return this.activeReads.set(t,r),r.finally(()=>{this.activeReads.get(t)===r&&(this.activeReads.delete(t),this.pendingReads.delete(t))}),r}async drainReadQueue(t,i){do this.pendingReads.delete(t),await this.readNewLines(t,i);while(i===this.readGeneration&&this.pendingReads.has(t))}async readNewLines(t,i){if(i!==this.readGeneration)return;let s=this.filePositions.get(t)||0;try{let r=S.statSync(t);if(r.size<s&&(n.info("Session log truncated/rotated; resetting cursor to 0",{filePath:t,oldPosition:s,size:r.size}),s=0,this.filePositions.set(t,0)),r.size<=s)return;let o=S.createReadStream(t,{start:s,encoding:"utf-8"}),l=s,a="";for await(let p of o){if(i!==this.readGeneration){o.destroy();return}a+=p;let u=a.indexOf(`
|
|
3
|
+
`);for(;u!==-1;){if(i!==this.readGeneration){o.destroy();return}let h=a.slice(0,u),m=a.slice(0,u+1);a=a.slice(u+1),l+=Buffer.byteLength(m,"utf-8");let g=h.endsWith("\r")?h.slice(0,-1):h;if(g.trim())try{let f=JSON.parse(g);this.processLogEntry(f)}catch(f){n.warn("Failed to parse log line",{filePath:t,line:g.substring(0,100),error:f})}if(i===this.readGeneration&&this.filePositions.set(t,l),i!==this.readGeneration){o.destroy();return}u=a.indexOf(`
|
|
4
|
+
`)}}}catch(r){n.error("Error reading log file",{filePath:t,error:r}),this.emit("error",r)}}processLogEntry(t){if(n.debug("Processing log entry",{type:t.type}),t.type==="session_meta"){let i=t.payload;this.sessionId=i.id,n.info("Codex session started",{sessionId:i.id,cwd:i.cwd,cliVersion:i.cli_version}),this.emit("session-started",i);return}this.emit("log-entry",t),t.type==="event_msg"&&t.payload?.type?this.emit(`event:${t.payload.type}`,t):t.type==="response_item"&&t.payload?.type&&this.emit(`response:${t.payload.type}`,t)}};var j=require("uuid"),E=require("@quantiya/codevibe-core");var R=new Map;function ue(c,e){let t={sessionId:e,source:E.EventSource.DESKTOP};if(c.type==="event_msg"&&c.payload){let i=c.payload.type;switch(i){case"user_message":return{...t,type:E.EventType.USER_PROMPT,content:c.payload.message||"",metadata:{images:c.payload.images||[]}};case"agent_message":return{...t,type:E.EventType.ASSISTANT_RESPONSE,content:c.payload.message||"",metadata:{phase:c.payload.phase}};case"agent_reasoning":return{...t,type:E.EventType.REASONING,content:c.payload.text||""};case"token_count":return n.debug("Skipping token_count entry"),null;default:return n.debug("Unknown event_msg type",{type:i}),null}}if(c.type==="response_item"&&c.payload){let i=c.payload.type;if(i==="function_call"){let{name:s,arguments:r,call_id:o}=c.payload,l={};try{l=JSON.parse(r||"{}")}catch{l={raw:r}}let a=(0,j.v4)();R.set(o,{name:s,input:r,eventId:a});let p=X(s),u=Ve(s,l);return{...t,type:E.EventType.TOOL_USE,content:u,metadata:{toolName:p,toolInput:l,callId:o,status:"running"}}}if(i==="function_call_output"){let{call_id:s,output:r}=c.payload,o=R.get(s);R.delete(s);let l=o?.name?X(o.name):"Tool",a=Xe(r,500);return{...t,type:E.EventType.TOOL_USE,content:`${l} completed:
|
|
5
|
+
${a}`,metadata:{toolName:l,toolOutput:r,callId:s,status:"completed"}}}if(i==="custom_tool_call"){let{name:s,call_id:r,input:o,status:l}=c.payload;R.set(r,{name:s,input:o,eventId:(0,j.v4)()});let a=je(o),{oldString:p,newString:u}=Ge(o),h=a?`Editing: ${a.filePath}`:"Applying patch";return{...t,type:E.EventType.TOOL_USE,content:h,metadata:{tool_name:"Edit",tool_input:{file_path:a?.filePath||"",old_string:p,new_string:u},callId:r,status:l||"running"}}}if(i==="custom_tool_call_output"){let{call_id:s,output:r}=c.payload,o=R.get(s);R.delete(s);let l={};try{l=JSON.parse(r||"{}")}catch{l={raw:r}}let a=l.output?.includes("Success")||!l.error;return{...t,type:E.EventType.TOOL_USE,content:a?"File edit applied successfully":`Edit failed: ${l.error||"Unknown error"}`,metadata:{toolName:"Edit",toolOutput:l,callId:s,status:"completed",success:a}}}return n.debug("Unknown response_item type",{type:i}),null}return c.type==="turn_context"?(n.debug("Skipping turn_context entry"),null):(n.debug("Unhandled log entry type",{type:c.type}),null)}function X(c){return{shell_command:"Bash",shell:"Bash",apply_patch:"Edit",write_file:"Write",read_file:"Read",list_files:"Glob",search_files:"Grep",web_search:"WebSearch",web_fetch:"WebFetch"}[c]||c}function Ve(c,e){switch(c){case"shell_command":case"shell":return`Running: ${e.command||"command"}`;case"read_file":return`Reading: ${e.file_path||e.path||"file"}`;case"write_file":return`Writing: ${e.file_path||e.path||"file"}`;case"list_files":return`Listing: ${e.path||"."}`;case"search_files":return`Searching for: ${e.pattern||e.query||"pattern"}`;case"web_search":return`Searching web: ${e.query||"query"}`;default:return`Running ${X(c)}`}}function Ge(c){let e=[],t=[],i=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;for(let s of c.split(`
|
|
6
|
+
`))if(!(i.test(s)||s.startsWith("***")||s.startsWith("---")||s.startsWith("+++"))){if(s.startsWith("-"))e.push(s.slice(1));else if(s.startsWith("+"))t.push(s.slice(1));else if(s.startsWith(" ")){let r=s.slice(1);e.push(r),t.push(r)}}return{oldString:e.join(`
|
|
7
7
|
`),newString:t.join(`
|
|
8
|
-
`)}}function qe(l){if(!l)return null;let e=l.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);return e?{filePath:e[1].trim()}:null}function ze(l,e){return l?l.length<=e?l:l.substring(0,e)+"...":""}function ae(){w.clear()}var pe=require("events"),le=require("@quantiya/codevibe-core");var k=class extends pe.EventEmitter{constructor(){super();this.pendingCalls=new Map;this.timers=new Map;this.timeoutMs=(0,le.getConfig)().codex.approvalTimeoutMs,r.info("Approval detector initialized",{timeoutMs:this.timeoutMs})}onToolCallStart(t,i,s){r.debug("Tool call started",{callId:t,name:i});let n=this.parseInput(s),o=this.extractFilePath(i,s,n),a=this.extractDiff(i,s,n),p={callId:t,name:i,input:s,filePath:o,diff:a,parsedInput:n,timestamp:Date.now(),notificationSent:!1};if(this.pendingCalls.set(t,p),!this.shouldScheduleApprovalTimeout(i,n)){r.debug("Skipping approval timeout for non-escalated tool call",{callId:t,name:i});return}let d=setTimeout(()=>{this.checkPendingCall(t)},this.timeoutMs);this.timers.set(t,d)}onToolCallComplete(t){r.debug("Tool call completed",{callId:t}),this.pendingCalls.delete(t);let i=this.timers.get(t);i&&(clearTimeout(i),this.timers.delete(t))}checkPendingCall(t){let i=this.pendingCalls.get(t);if(!i||i.notificationSent)return;let s=Date.now()-i.timestamp;r.info("Tool call still pending after timeout",{callId:t,name:i.name,elapsedMs:s}),i.notificationSent=!0,this.pendingCalls.set(t,i),this.emit("approval-pending",{callId:t,toolName:i.name,hint:this.extractHint(i.name,i.input,i.filePath),filePath:i.filePath,diff:i.diff,toolInput:i.parsedInput,rawInput:i.input,elapsedMs:s})}extractHint(t,i,s){if(s)return`File: ${s}`;if(t==="apply_patch"&&i){let n=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(n)return`File: ${n[1].trim()}`}if(t==="exec_command"||t==="shell_command"||t==="shell")try{let n=JSON.parse(i),o=typeof n.command=="string"?n.command:typeof n.cmd=="string"?n.cmd:void 0;if(o)return`Command: ${o.substring(0,50)}${o.length>50?"...":""}`}catch{}return`Tool: ${this.mapToolName(t)}`}mapToolName(t){return{exec_command:"Bash",shell_command:"Bash",shell:"Bash",apply_patch:"File Edit",write_file:"Write File",read_file:"Read File"}[t]||t}parseInput(t){if(t)try{return JSON.parse(t)}catch{return}}shouldScheduleApprovalTimeout(t,i){return t!=="exec_command"&&t!=="shell_command"&&t!=="shell"?!1:i?.sandbox_permissions==="require_escalated"}extractFilePath(t,i,s){if(t==="apply_patch"&&i){let o=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(o)return o[1].trim()}let n=s?.file_path||s?.path||s?.filePath;if(n&&typeof n=="string")return n}extractDiff(t,i,s){if(t==="apply_patch"&&i)return i;if(s?.diff&&typeof s.diff=="string")return s.diff}getPendingCalls(){return Array.from(this.pendingCalls.values())}hasPendingCalls(){return this.pendingCalls.size>0}clear(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear(),this.pendingCalls.clear(),r.debug("Approval detector cleared")}shutdown(){this.clear(),this.removeAllListeners(),r.info("Approval detector shutdown")}};var ce=require("child_process"),de=require("util");var j=(0,de.promisify)(ce.exec),C="__CODEVIBE_CODEX_KEY_ESCAPE__",M=class{async sendInput(e,t){r.info("Attempting to send input to Codex",{sessionId:e,input:t});try{let i=process.env.CODEVIBE_CODEX_TMUX_SESSION;return i?(r.info("Using tmux send-keys",{tmuxSession:i}),t===C?await this.sendKeyViaTmux(i,"Escape"):await this.sendViaTmux(i,t),r.info("Successfully sent input to Codex",{sessionId:e,input:t}),!0):(r.error("No tmux session found - codevibe-codex wrapper is required",{sessionId:e,hint:"Start Codex CLI using the codevibe-codex wrapper script"}),!1)}catch(i){return r.error("Failed to send input to Codex",{sessionId:e,error:i instanceof Error?i.message:String(i)}),!1}}async sendViaTmux(e,t){let i=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");r.info("Sending via tmux",{sessionName:e,inputLength:t.length});try{let s=`tmux send-keys -t "${e}" -l "${i}"`;await j(s),await this.delay(500);let n=`tmux send-keys -t "${e}" Enter`;await j(n),r.info("tmux send-keys completed")}catch(s){throw r.error("tmux send-keys failed",{sessionName:e,error:s}),s}}async sendKeyViaTmux(e,t){r.info("Sending special key via tmux",{sessionName:e,key:t});try{let i=`tmux send-keys -t "${e}" ${t}`;await j(i),r.info("tmux special-key send completed")}catch(i){throw r.error("tmux special-key send failed",{sessionName:e,key:t,error:i}),i}}delay(e){return new Promise(t=>setTimeout(t,e))}isApprovalResponse(e){let t=e.trim().toLowerCase();return["y","n","a","q","e","yes","no"].includes(t)||/^[0-9]+$/.test(t)}};var y=v(require("fs")),ue=v(require("os")),L=v(require("path")),me=require("crypto"),he=require("child_process"),fe=require("events"),ge=require("util");var V=(0,ge.promisify)(he.exec),N=class extends fe.EventEmitter{constructor(){super(...arguments);this.sessionName=null;this.started=!1;this.pipeFilePath=null;this.filePosition=0;this.watcher=null;this.processing=!1;this.pendingRead=!1;this.lastPromptHash=null}async start(t){if(this.started&&this.sessionName===t){r.debug("Tmux pane observer already started",{sessionName:t});return}this.started&&await this.stop(),this.sessionName=t,this.started=!0,this.filePosition=0,this.lastPromptHash=null,this.pipeFilePath=L.join(ue.tmpdir(),`codevibe-codex-pane-${process.pid}.log`),y.mkdirSync(L.dirname(this.pipeFilePath),{recursive:!0}),y.writeFileSync(this.pipeFilePath,""),await this.enablePipePane(),this.startFileWatcher(),r.info("Tmux pane observer started",{sessionName:t})}async stop(){if(this.started){try{await this.disablePipePane()}catch(t){r.debug("Failed to disable tmux pipe-pane cleanly",{error:t})}if(this.watcher&&(this.watcher.close(),this.watcher=null),this.pipeFilePath)try{y.unlinkSync(this.pipeFilePath)}catch{}r.info("Tmux pane observer stopped",{sessionName:this.sessionName}),this.started=!1,this.sessionName=null,this.pipeFilePath=null,this.filePosition=0,this.processing=!1,this.pendingRead=!1,this.lastPromptHash=null,this.removeAllListeners("prompt-candidate"),this.removeAllListeners("observer-error")}}async captureSnapshot(t=120){if(!this.sessionName)throw new Error("Tmux pane observer is not started");let i=Math.max(1,Math.floor(t)),s=this.escapeShellArg(this.sessionName),n=`tmux capture-pane -p -e -J -S -${i} -t '${s}'`;try{let{stdout:o}=await V(n);return o}catch(o){throw r.error("Failed to capture tmux pane snapshot",{sessionName:this.sessionName,error:o}),this.emit("observer-error",o),o}}escapeShellArg(t){return t.replace(/'/g,"'\\''")}async enablePipePane(){if(!this.sessionName||!this.pipeFilePath)throw new Error("Tmux pane observer is not initialized");let t=this.escapeShellArg(this.sessionName),i=this.escapeShellArg(this.pipeFilePath),s=`tmux pipe-pane -O -t '${t}' "cat >> '${i}'"`;await V(s),r.debug("Enabled tmux pipe-pane mirroring",{sessionName:this.sessionName,pipeFilePath:this.pipeFilePath})}async disablePipePane(){if(!this.sessionName)return;let i=`tmux pipe-pane -t '${this.escapeShellArg(this.sessionName)}'`;await V(i)}startFileWatcher(){this.pipeFilePath&&(this.watcher=y.watch(this.pipeFilePath,t=>{t==="change"&&this.processFileChanges()}))}async processFileChanges(){if(this.pipeFilePath){if(this.processing){this.pendingRead=!0;return}this.processing=!0;try{do{this.pendingRead=!1;let t=this.readAppendedChunk();if(!t||!this.looksLikePromptDelta(t))continue;let i=await this.captureSnapshot();if(!i||!this.looksLikePromptSnapshot(i))continue;let s=this.hashPromptSnapshot(i);s!==this.lastPromptHash&&(this.lastPromptHash=s,this.emit("prompt-candidate",{rawDelta:t,snapshot:i,detectedAt:Date.now()}))}while(this.pendingRead)}catch(t){r.error("Failed to process tmux pane changes",{error:t}),this.emit("observer-error",t)}finally{this.processing=!1}}}readAppendedChunk(){if(!this.pipeFilePath)return"";let t=y.statSync(this.pipeFilePath);if(t.size<=this.filePosition)return"";let i=y.openSync(this.pipeFilePath,"r");try{let s=t.size-this.filePosition,n=Buffer.alloc(s);return y.readSync(i,n,0,s,this.filePosition),this.filePosition=t.size,n.toString("utf-8")}finally{y.closeSync(i)}}looksLikePromptDelta(t){return/\[(?:y\/n|Y\/n|y\/N)\]|\b(?:apply|approve|allow|reject|deny|continue)\b/i.test(t)}looksLikePromptSnapshot(t){let i=t.split(`
|
|
8
|
+
`)}}function je(c){if(!c)return null;let e=c.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);return e?{filePath:e[1].trim()}:null}function Xe(c,e){return c?c.length<=e?c:c.substring(0,e)+"...":""}function he(){R.clear()}var b=require("@quantiya/codevibe-core"),me=3e3,Ye=8,Je=10,Qe=100;function fe(c){let e=Buffer.byteLength(c.carryover);return{status:"partial",progressKey:`${c.fileIdentity.dev}:${c.fileIdentity.ino}:${c.size}:${c.endOfComplete}:${e}`,size:c.size,carryoverBytes:e,endOfComplete:c.endOfComplete}}var Ze="tool_activity",k=class{constructor(e){this.consolidator=null;this.ledger=null;this.sessionMap=null;this.ownership=null;this.cursor=null;this.backendSessionId=null;this.rolloutId=null;this.transcriptPath=null;this.backstopTimer=null;this.backstopInFlight=null;this.cursorReady=Promise.resolve();this.cursorRepaired=!1;this.deps=e}static mintBackendSessionId(){return b.ToolActivitySessionMap.mintCodexBackendSessionId()}async recordedBackendSessionId(e){return new b.ToolActivitySessionMap({agent:"codex",logger:this.deps.logger,lock:new b.InProcessRolloutLock,root:this.deps.root}).ownerBackendSessionId(e)}get sessionId(){return this.backendSessionId}get rollout(){return this.rolloutId}isActive(){return this.consolidator!==null}async start(e,t,i){this.backendSessionId=e,this.rolloutId=t;let s=(0,b.createRolloutLock)({agent:"codex",logger:this.deps.logger,socketDir:this.deps.socketDir,root:this.deps.root});this.sessionMap=new b.ToolActivitySessionMap({agent:"codex",logger:this.deps.logger,lock:s,root:this.deps.root}),this.ownership=await this.sessionMap.claimOwnership(t,e);let r=new b.ToolActivityOutbox({agent:"codex",logger:this.deps.logger,root:this.deps.root});this.ledger=new b.ToolActivityLedger({agent:"codex",sessionId:e,logger:this.deps.logger,root:this.deps.root}),this.consolidator=new b.ToolActivityConsolidator({agent:"codex",sessionId:e,logger:this.deps.logger,outbox:r,ledger:this.ledger,transport:this.buildTransport()}),await this.consolidator.init(),i&&this.bindTranscript(i),this.deps.logger.info("[tool-activity] codex consolidator started",{sessionId:e,rollout:t,hasTranscript:!!i})}bindTranscript(e){if(!this.consolidator||!e||this.transcriptPath===e)return;this.transcriptPath=e;let t=new b.ToolReplayCursor({agent:"codex",sessionId:this.backendSessionId,canonicalPath:e,logger:this.deps.logger,root:this.deps.root,readBytes:this.deps.replayReadBytes,maxFrameBytes:this.deps.replayMaxFrameBytes});this.cursor=t,this.cursorRepaired=!1,this.cursorReady=t.load().catch(s=>this.deps.logger.warn("[tool-activity] codex cursor load failed (rescanning fresh)",{sessionId:this.backendSessionId,err:String(s)}));let i=this.deps.backstopIntervalMs??3e3;i>0&&!this.backstopTimer&&(this.backstopTimer=setInterval(()=>{this.runTranscriptBackstop().catch(s=>this.deps.logger.warn("[tool-activity] codex transcript backstop failed",{sessionId:this.backendSessionId,err:String(s)}))},i),this.backstopTimer.unref?.())}async observeCall(e,t){if(!this.consolidator||!this.sessionMap||!this.ownership||!e.callId||!e.toolName)return;let i=this.consolidator;await this.sessionMap.bindCall(this.ownership,e.callId);let s={id:e.callId,tool:e.toolName,normalizedTarget:st(e.toolName,e.toolInput),ts:e.ts??new Date().toISOString(),byteOffset:e.byteOffset??0,...e.toolInput!==void 0?{digest:(0,b.digestOf)(e.toolInput)}:{}},r=await i.observe(s,t);return r==="closed"?await i.captureTerminal(s,this.deps.shutdownDrainMs??me)?"sealed-terminal":"closed":r}async runTranscriptBackstop(e=!1){await this.runTranscriptBackstopTurn(e)}runTranscriptBackstopTurn(e=!1){if(this.backstopInFlight)return this.backstopInFlight;let t=this.cursor,i=this.cursorReady,s=this.consolidator;if(!s||!t)return Promise.resolve("caught-up");let o=(async()=>{if(await i,this.cursor!==t)return"more";if(!this.cursorRepaired){if(await s.repairLostWindows(t),this.cursor!==t)return"more";this.cursorRepaired=!0}return this.doTranscriptBackstop(t,e)})().finally(()=>{this.backstopInFlight===o&&(this.backstopInFlight=null)});return this.backstopInFlight=o,o}async doTranscriptBackstop(e,t=!1){let i=this.consolidator;if(!i)return"caught-up";this.ledger&&await this.ledger.reloadLegacyOwned();for(let s=0;s<Ye;s+=1){if(this.cursor!==e)return"caught-up";let r=await e.readFrames();if(r.missing)return"caught-up";if(r.frames.length===0)return r.carryover.length>0?fe(r):"caught-up";let o=Number.POSITIVE_INFINITY,l=t?{includeInFlight:!0}:void 0;for(let a of r.frames)for(let p of et(a.line,a.startOffset))await this.observeCall(p,l)==="deferred-in-flight"&&(o=Math.min(o,a.startOffset));if(await i.flush(),o<r.endOfComplete)return await e.checkpoint(o,{fileIdentity:r.fileIdentity,size:r.size,carryover:""}),"more";if(await e.checkpoint(r.endOfComplete,{fileIdentity:r.fileIdentity,size:r.size,carryover:r.carryover}),!r.hasMore)return r.carryover.length>0?fe(r):"caught-up"}return"more"}async flush(){await this.consolidator?.flush()}async stop(){this.backstopTimer&&(clearInterval(this.backstopTimer),this.backstopTimer=null),await this.runTranscriptBackstop().catch(()=>{});let e=Math.max(1,Math.trunc(this.deps.shutdownPartialNoProgressTurns??Qe)),t=null,i=0;for(;;){let s=await this.runTranscriptBackstopTurn(!0);if(s==="caught-up")break;if(typeof s!="string"){if(s.progressKey===t?i+=1:(t=s.progressKey,i=1),i>=e){this.deps.logger.warn("[tool-activity] deferring unchanged incomplete rollout suffix during shutdown; the next owner will re-read it from the durable complete-line boundary",{size:s.size,carryoverBytes:s.carryoverBytes,endOfComplete:s.endOfComplete,unchangedTurns:i});break}await new Promise(r=>setTimeout(r,Je))}else t=null,i=0,await new Promise(r=>setImmediate(r))}await this.consolidator?.drainSends(this.deps.shutdownDrainMs??me).catch(()=>{});try{await this.consolidator?.shutdown()}finally{await this.ownership?.release().catch(()=>{}),this.ownership=null,this.consolidator=null,this.ledger=null,this.sessionMap=null,this.cursor=null}}buildTransport(){let e=async(t,i,s)=>{let r=s?s.sessionKey:this.deps.getSessionKey();if(!r)throw new Error("[tool-activity] no session key at send (retryable)");let o=s?s.sessionKeyGen:this.deps.getSessionKeyGen();await this.deps.createEvent({sessionId:t,type:b.EventType.TOOL_ACTIVITY,source:b.EventSource.DESKTOP,content:this.deps.encryptContent(Ze,r),metadata:{encrypted:this.deps.encryptMetadata({manifest:i.manifest},r)},timestamp:i.windowStart,isEncrypted:!0,clientEventId:i.clientEventId,...o?{expectedSessionKeyGen:o}:{}})};return{send:async(t,i)=>{try{await e(t,i)}catch(s){if((0,b.isSessionKeyStaleError)(s)&&this.deps.refreshSessionKey){let r=await this.deps.refreshSessionKey(t);if(!r)throw s;await e(t,i,r);return}throw s}}}}};function et(c,e){let t;try{t=JSON.parse(c)}catch{return[]}if(t?.type!=="response_item"||!t.payload)return[];let i=t.payload,s=typeof t.timestamp=="string"?t.timestamp:new Date(0).toISOString();if(i.type==="function_call"&&typeof i.call_id=="string"&&typeof i.name=="string"){let r;try{r=JSON.parse(i.arguments||"{}")}catch{r={raw:i.arguments}}return[{callId:i.call_id,toolName:tt(i.name),toolInput:r,ts:s,byteOffset:e}]}if(i.type==="custom_tool_call"&&typeof i.call_id=="string"){let r=it(typeof i.input=="string"?i.input:""),o=r?{file_path:r,patch:i.input}:{patch:i.input};return[{callId:i.call_id,toolName:"Edit",toolInput:o,ts:s,byteOffset:e}]}return[]}function tt(c){return c==="shell"||c==="shell_command"||c==="local_shell"?"Bash":c==="apply_patch"?"Edit":c}function it(c){let e=c.match(/^\*\*\* (?:Update|Add|Delete) File: (.+)$/m);return e?e[1].trim():void 0}function st(c,e){if(!e||typeof e!="object")return;let t=e,i=r=>typeof r=="string"&&r.length>0?r:void 0,s=Array.isArray(t.command)?t.command.filter(r=>typeof r=="string").join(" ").trim().split(/\s+/)[0]:typeof t.command=="string"?t.command.trim().split(/\s+/)[0]:void 0;return i(t.file_path)??i(t.path)??i(t.pattern)??i(t.url)??(s&&s.length>0?s:void 0)}var ge=require("events"),ye=require("@quantiya/codevibe-core");var B=class extends ge.EventEmitter{constructor(){super();this.pendingCalls=new Map;this.timers=new Map;this.timeoutMs=(0,ye.getConfig)().codex.approvalTimeoutMs,n.info("Approval detector initialized",{timeoutMs:this.timeoutMs})}onToolCallStart(t,i,s){n.debug("Tool call started",{callId:t,name:i});let r=this.parseInput(s),o=this.extractFilePath(i,s,r),l=this.extractDiff(i,s,r),a={callId:t,name:i,input:s,filePath:o,diff:l,parsedInput:r,timestamp:Date.now(),notificationSent:!1};if(this.pendingCalls.set(t,a),!this.shouldScheduleApprovalTimeout(i,r)){n.debug("Skipping approval timeout for non-escalated tool call",{callId:t,name:i});return}let p=setTimeout(()=>{this.checkPendingCall(t)},this.timeoutMs);this.timers.set(t,p)}onToolCallComplete(t){n.debug("Tool call completed",{callId:t}),this.pendingCalls.delete(t);let i=this.timers.get(t);i&&(clearTimeout(i),this.timers.delete(t))}checkPendingCall(t){let i=this.pendingCalls.get(t);if(!i||i.notificationSent)return;let s=Date.now()-i.timestamp;n.info("Tool call still pending after timeout",{callId:t,name:i.name,elapsedMs:s}),i.notificationSent=!0,this.pendingCalls.set(t,i),this.emit("approval-pending",{callId:t,toolName:i.name,hint:this.extractHint(i.name,i.input,i.filePath),filePath:i.filePath,diff:i.diff,toolInput:i.parsedInput,rawInput:i.input,elapsedMs:s})}extractHint(t,i,s){if(s)return`File: ${s}`;if(t==="apply_patch"&&i){let r=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(r)return`File: ${r[1].trim()}`}if(t==="exec_command"||t==="shell_command"||t==="shell")try{let r=JSON.parse(i),o=typeof r.command=="string"?r.command:typeof r.cmd=="string"?r.cmd:void 0;if(o)return`Command: ${o.substring(0,50)}${o.length>50?"...":""}`}catch{}return`Tool: ${this.mapToolName(t)}`}mapToolName(t){return{exec_command:"Bash",shell_command:"Bash",shell:"Bash",apply_patch:"File Edit",write_file:"Write File",read_file:"Read File"}[t]||t}parseInput(t){if(t)try{return JSON.parse(t)}catch{return}}shouldScheduleApprovalTimeout(t,i){return t!=="exec_command"&&t!=="shell_command"&&t!=="shell"?!1:i?.sandbox_permissions==="require_escalated"}extractFilePath(t,i,s){if(t==="apply_patch"&&i){let o=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(o)return o[1].trim()}let r=s?.file_path||s?.path||s?.filePath;if(r&&typeof r=="string")return r}extractDiff(t,i,s){if(t==="apply_patch"&&i)return i;if(s?.diff&&typeof s.diff=="string")return s.diff}getPendingCalls(){return Array.from(this.pendingCalls.values())}hasPendingCalls(){return this.pendingCalls.size>0}clear(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear(),this.pendingCalls.clear(),n.debug("Approval detector cleared")}shutdown(){this.clear(),this.removeAllListeners(),n.info("Approval detector shutdown")}};var ve=require("child_process"),Se=require("util");var Y=(0,Se.promisify)(ve.exec),F="__CODEVIBE_CODEX_KEY_ESCAPE__",K=class{async sendInput(e,t){n.info("Attempting to send input to Codex",{sessionId:e,input:t});try{let i=process.env.CODEVIBE_CODEX_TMUX_SESSION;return i?(n.info("Using tmux send-keys",{tmuxSession:i}),t===F?await this.sendKeyViaTmux(i,"Escape"):await this.sendViaTmux(i,t),n.info("Successfully sent input to Codex",{sessionId:e,input:t}),!0):(n.error("No tmux session found - CodeVibe Companion launch is required",{sessionId:e,hint:"Start Codex CLI using `codevibe --agent codex`"}),!1)}catch(i){return n.error("Failed to send input to Codex",{sessionId:e,error:i instanceof Error?i.message:String(i)}),!1}}async sendViaTmux(e,t){let i=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");n.info("Sending via tmux",{sessionName:e,inputLength:t.length});try{let s=`tmux send-keys -t "${e}" -l "${i}"`;await Y(s),await this.delay(500);let r=`tmux send-keys -t "${e}" Enter`;await Y(r),n.info("tmux send-keys completed")}catch(s){throw n.error("tmux send-keys failed",{sessionName:e,error:s}),s}}async sendKeyViaTmux(e,t){n.info("Sending special key via tmux",{sessionName:e,key:t});try{let i=`tmux send-keys -t "${e}" ${t}`;await Y(i),n.info("tmux special-key send completed")}catch(i){throw n.error("tmux special-key send failed",{sessionName:e,key:t,error:i}),i}}delay(e){return new Promise(t=>setTimeout(t,e))}isApprovalResponse(e){let t=e.trim().toLowerCase();return["y","n","a","q","e","yes","no"].includes(t)||/^[0-9]+$/.test(t)}};var I=P(require("fs")),be=P(require("os")),$=P(require("path")),Pe=require("crypto"),Ie=require("child_process"),we=require("events"),_e=require("util");var J=(0,_e.promisify)(Ie.exec),U=class extends we.EventEmitter{constructor(){super(...arguments);this.sessionName=null;this.started=!1;this.pipeFilePath=null;this.filePosition=0;this.watcher=null;this.processing=!1;this.pendingRead=!1;this.lastPromptHash=null}async start(t){if(this.started&&this.sessionName===t){n.debug("Tmux pane observer already started",{sessionName:t});return}this.started&&await this.stop(),this.sessionName=t,this.started=!0,this.filePosition=0,this.lastPromptHash=null,this.pipeFilePath=$.join(be.tmpdir(),`codevibe-codex-pane-${process.pid}.log`),I.mkdirSync($.dirname(this.pipeFilePath),{recursive:!0}),I.writeFileSync(this.pipeFilePath,""),await this.enablePipePane(),this.startFileWatcher(),n.info("Tmux pane observer started",{sessionName:t})}async stop(){if(this.started){try{await this.disablePipePane()}catch(t){n.debug("Failed to disable tmux pipe-pane cleanly",{error:t})}if(this.watcher&&(this.watcher.close(),this.watcher=null),this.pipeFilePath)try{I.unlinkSync(this.pipeFilePath)}catch{}n.info("Tmux pane observer stopped",{sessionName:this.sessionName}),this.started=!1,this.sessionName=null,this.pipeFilePath=null,this.filePosition=0,this.processing=!1,this.pendingRead=!1,this.lastPromptHash=null,this.removeAllListeners("prompt-candidate"),this.removeAllListeners("observer-error")}}resetLastPromptHash(){this.lastPromptHash=null}async captureSnapshot(t=120){if(!this.sessionName)throw new Error("Tmux pane observer is not started");let i=Math.max(1,Math.floor(t)),s=this.escapeShellArg(this.sessionName),r=`tmux capture-pane -p -e -J -S -${i} -t '${s}'`;try{let{stdout:o}=await J(r);return o}catch(o){throw n.error("Failed to capture tmux pane snapshot",{sessionName:this.sessionName,error:o}),this.emit("observer-error",o),o}}escapeShellArg(t){return t.replace(/'/g,"'\\''")}async enablePipePane(){if(!this.sessionName||!this.pipeFilePath)throw new Error("Tmux pane observer is not initialized");let t=this.escapeShellArg(this.sessionName),i=this.escapeShellArg(this.pipeFilePath),s=`tmux pipe-pane -O -t '${t}' "cat >> '${i}'"`;await J(s),n.debug("Enabled tmux pipe-pane mirroring",{sessionName:this.sessionName,pipeFilePath:this.pipeFilePath})}async disablePipePane(){if(!this.sessionName)return;let i=`tmux pipe-pane -t '${this.escapeShellArg(this.sessionName)}'`;await J(i)}startFileWatcher(){this.pipeFilePath&&(this.watcher=I.watch(this.pipeFilePath,t=>{t==="change"&&this.processFileChanges()}))}async processFileChanges(){if(this.pipeFilePath){if(this.processing){this.pendingRead=!0;return}this.processing=!0;try{do{this.pendingRead=!1;let t=this.readAppendedChunk();if(!t||!this.looksLikePromptDelta(t))continue;let i=await this.captureSnapshot();if(!i||!this.looksLikePromptSnapshot(i))continue;let s=this.hashPromptSnapshot(i);s!==this.lastPromptHash&&(this.lastPromptHash=s,this.emit("prompt-candidate",{rawDelta:t,snapshot:i,detectedAt:Date.now()}))}while(this.pendingRead)}catch(t){n.error("Failed to process tmux pane changes",{error:t}),this.emit("observer-error",t)}finally{this.processing=!1}}}readAppendedChunk(){if(!this.pipeFilePath)return"";let t=I.statSync(this.pipeFilePath);if(t.size<=this.filePosition)return"";let i=I.openSync(this.pipeFilePath,"r");try{let s=t.size-this.filePosition,r=Buffer.alloc(s);return I.readSync(i,r,0,s,this.filePosition),this.filePosition=t.size,r.toString("utf-8")}finally{I.closeSync(i)}}looksLikePromptDelta(t){return/\[(?:y\/n|Y\/n|y\/N)\]|\b(?:apply|approve|allow|reject|deny|continue)\b/i.test(t)}looksLikePromptSnapshot(t){let i=t.split(`
|
|
9
9
|
`).slice(-20).join(`
|
|
10
10
|
`);return/\[(?:y\/n|Y\/n|y\/N)\]|^\s*\d+\.\s+/im.test(i)}hashPromptSnapshot(t){let i=t.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").replace(/\r/g,`
|
|
11
11
|
`).replace(/[ \t]+\n/g,`
|
|
12
|
-
`).trim();return(0,
|
|
13
|
-
`),t=o=>/^[\s>]*\d+\.\s/.test(o),i=-1;for(let o=e.length-1;o>=0;o-=1)if(/^\s*\$\s+/.test(e[o])){i=o;break}if(i===-1)return;let s=e[i].trim().match(/^\$\s+(.+)$/);if(!s?.[1]?.trim())return;let n=[s[1].trim()];for(let o=i+1;o<e.length;o+=1){let a=e[o];if(t(a)||/^\s*$/.test(a)||/^\s*\$\s+/.test(a))break;n.push(a.trim())}return n.length>0?n:void 0}function Oe(l){let e=Q(l);if(!e)return;let t=e.join(" ").trim();return t.length>0?t:void 0}var z=class{constructor(){this.sessionState=null;this.unsubscribe=null;this.sessionKey=null;this.pendingInteractivePrompt=null;this.queuedInteractivePrompts=[];this.isInitializingSession=!1;this.bufferedLogEntries=[];this.hooksActive=!1;this.hooksCompatibilityNoticeSent=!1;this.resolvedApprovalDedupeKeys=new Map;this.subscribedSessionId=null;this.mobilePromptDeduper=new K({expiryMs:1e4});this.launchSessionInitPromise=null;this.sessionStartedInitPromise=null;this.v1Bridge=new B;this.orchestrationClient=null;this.userDecisionUnsubscribe=null;this.httpApi=new U,this.sessionWatcher=new D,this.approvalDetector=new k,this.promptResponder=new M,this.tmuxPaneObserver=new N}async start(){r.info("Starting CodeVibe Codex companion server",{environment:(0,c.getEnvironment)()}),this.appSyncClient=new c.AppSyncClient,await this.appSyncClient.authenticateWithStoredTokens()||(r.error('Authentication failed. Run "codevibe-codex login" first.'),console.error('Not authenticated. Run "codevibe-codex login" to sign in.'),process.exit(1)),r.info("Authenticated successfully",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()}),await(0,c.registerDeviceEncryptionKey)(this.appSyncClient,r),(0,c.startDeviceKeyWatcher)(this.appSyncClient,r),(0,c.pushDetectedAgents)(this.appSyncClient,r).catch(i=>{r.warn("Failed to update available agents (non-fatal)",{error:i?.message})});try{let i=await this.appSyncClient.sweepOrphanSessions({agentType:"CODEX"});i>0&&r.info("Orphan sweep: marked stale Codex sessions INACTIVE",{swept:i})}catch(i){r.warn("Orphan sweep failed, continuing startup",{error:i instanceof Error?i.message:String(i)})}this.httpApi.onEvent(this.handleEventFromHook.bind(this));let t=await this.httpApi.start();r.info("HTTP API started for hooks",{port:t}),await this.createLaunchSession(),this.setupEventHandlers(),this.sessionWatcher.start(),r.info("CodeVibe Codex companion server started")}async createLaunchSession(){let e=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!e){r.warn("No CODEVIBE_CODEX_TMUX_SESSION \u2014 skipping launch session");return}let t;this.launchSessionInitPromise=new Promise(i=>{t=i});try{let i=process.env.CODEX_WORKING_DIRECTORY||process.cwd(),s=this.generateSessionId(e),n=this.appSyncClient.getCurrentUserId();r.info("Creating launch session",{sessionId:s,projectPath:i});let o=!1;try{let a=await(0,c.resumeOrCreateSession)({sessionId:s,userId:n,agentType:c.AgentType.CODEX,projectPath:i,metadata:{launchSession:!0}},this.appSyncClient,r);this.sessionKey=a.sessionKey,o=!0,this.sessionState={sessionId:s,userId:n,projectPath:i,cwd:i,createdAt:new Date,subscriptionActive:!1,metadata:{launchSession:!0},codexSessionId:e,codexLogFile:void 0},await g("daemon_init_step_completed",{step:"session_resume_or_create",path:"launch_session"})}catch(a){await g("daemon_init_step_failed",{step:"session_resume_or_create",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),r.error("Failed to create/resume launch session (non-fatal)",{error:a})}if(!o)return;await g("daemon_init_step_completed",{step:"session_state_set",path:"launch_session"}),await(0,c.applyPerSessionOrchestrationOverride)(this.appSyncClient,s,r);try{this.subscribeToMobileEvents(s)?await g("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"launch_session"}):await g("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(a){await g("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),r.error("Failed to subscribe to mobile events for launch session",{error:a})}try{this.appSyncClient.startHeartbeat(s),await g("daemon_init_step_completed",{step:"heartbeat_start",path:"launch_session"})}catch(a){await g("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),r.error("Failed to start heartbeat for launch session",{error:a})}try{await this.subscribeToOnApplyUserDecision(s)}catch(a){r.error("Failed to subscribe to onApplyUserDecision for launch session (non-fatal)",{error:a})}this.startMobileEndWatcher(s),r.info("Launch session created",{sessionId:s})}finally{t()}}async handleEventFromHook(e){let{session_id:t,hook_event_name:i,type:s,content:n,metadata:o}=e;if(this.hooksActive=!0,r.info("[Hooks] Received event",{sessionId:t,hookEvent:i,type:s,contentLength:n?.length}),i==="SessionStart"){if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,await this.sessionWatcher.bindToSessionTranscript(o?.transcript_path,t),this.sessionState)r.info("[Hooks] SessionStart \u2014 launch session already exists, updating codexSessionId",{existingSessionId:this.sessionState.sessionId,codexSessionId:t}),this.sessionState.codexSessionId=t,this.sessionState.metadata={...this.sessionState.metadata,codexSessionId:t,cliVersion:o?.model||"unknown",modelProvider:o?.model||"unknown",launchSession:void 0},this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,metadata:this.sessionState.metadata}).catch(p=>r.warn("Failed to update session metadata",{error:p})),await this.startTmuxObserverWithBeacon("session_start_existing");else{let p={id:t,timestamp:new Date().toISOString(),cwd:o?.cwd||process.cwd(),originator:"hook",cli_version:o?.model||"unknown",instructions:null,source:o?.source||"startup",model_provider:o?.model||"unknown"};await this.ensureSessionStarted(p)}return}if(!this.sessionState){r.warn("[Hooks] Session not initialized, buffering event",{hook_event_name:i});return}let a=this.sessionState.sessionId;if(s==="USER_PROMPT"&&n){let p=this.consumeRecentMobilePrompt(a,n);if(p){r.info("[Hooks] Skipping duplicate USER_PROMPT from mobile",{sessionId:a,matchType:p.matchType,originalLength:p.originalLength,echoLength:p.echoLength});return}}if(i==="PreToolUse"){r.debug("[Hooks] PreToolUse observed; AppSync emission suppressed",{toolName:o?.tool_name||"unknown",sessionId:a});return}if(i==="PermissionRequest"){await this.handlePermissionRequestHook(e);return}if(i==="PostToolUse"){let p=n,d=o,u=!1;this.sessionKey&&(p=c.cryptoService.encryptContent(n,this.sessionKey),o&&(d={encrypted:c.cryptoService.encryptMetadata(o,this.sessionKey)}),u=!0),await this.appSyncClient.createEvent({sessionId:a,type:c.EventType.TOOL_USE,source:c.EventSource.DESKTOP,content:p,metadata:d,isEncrypted:u,timestamp:(0,c.prepareEventTimestamp)({orderingKey:a})});return}if(s==="ASSISTANT_RESPONSE"||s==="USER_PROMPT"){if(s==="ASSISTANT_RESPONSE"&&this.sessionWatcher.getBindSource()==="authoritative"&&this.sessionWatcher.getAuthoritativeSessionId()===t){r.debug("[Hooks] Suppressing Stop final \u2014 JSONL watcher authoritatively bound to this session (Bug #2)");return}s==="ASSISTANT_RESPONSE"&&r.info("[Hooks] Emitting Stop final as backstop \u2014 watcher not authoritatively bound",{bindSource:this.sessionWatcher.getBindSource()});let p=n,d=!1;this.sessionKey&&n&&(p=c.cryptoService.encryptContent(n,this.sessionKey),d=!0),await this.appSyncClient.createEvent({sessionId:a,type:s==="ASSISTANT_RESPONSE"?c.EventType.ASSISTANT_RESPONSE:c.EventType.USER_PROMPT,source:c.EventSource.DESKTOP,content:p,isEncrypted:d,timestamp:(0,c.prepareEventTimestamp)({orderingKey:a})});return}}mapToolName(e){return{shell_command:"Bash",shell:"Bash",apply_patch:"Edit",create_file:"Write",read_file:"Read"}[e]||e}trackMobilePrompt(e,t){this.mobilePromptDeduper.track(e,t),r.debug("Tracking mobile prompt for USER_PROMPT echo deduplication",{sessionId:e,promptLength:t.trim().length})}forgetMobilePrompt(e,t){this.mobilePromptDeduper.forget(e,t)}consumeRecentMobilePrompt(e,t){return this.mobilePromptDeduper.consumeIfDuplicate(e,t)}setupEventHandlers(){this.sessionWatcher.on("session-started",async e=>{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState){r.info("[JSONL] Session already active, skipping",{currentSessionId:this.sessionState.sessionId,codexSessionId:e.id});return}await this.ensureSessionStarted(e)}),this.sessionWatcher.on("log-entry",async e=>{await this.handleLogEntry(e)}),this.approvalDetector.on("approval-pending",async e=>{await this.handleApprovalPending(e)}),this.tmuxPaneObserver.on("prompt-candidate",async e=>{await this.handleTmuxPromptCandidate(e.snapshot)}),this.tmuxPaneObserver.on("observer-error",e=>{r.debug("Tmux pane observer error",{error:e})}),this.sessionWatcher.on("error",e=>{r.error("Session watcher error:",e)})}async ensureSessionStarted(e){if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState)return;if(this.sessionStartedInitPromise){try{await this.sessionStartedInitPromise}catch{}return}let t=this.handleSessionStarted(e);this.sessionStartedInitPromise=t.catch(()=>{});try{await t}finally{this.sessionStartedInitPromise=null}}async handleSessionStarted(e){r.info("Handling new Codex session",{codexSessionId:e.id}),this.isInitializingSession=!0,this.bufferedLogEntries=[],this.sessionState&&await this.endActiveSession("new-codex-session-started");let t=process.env.CODEX_WORKING_DIRECTORY||e.cwd||process.cwd(),i=this.generateSessionId(e.id),s=this.appSyncClient.getCurrentUserId(),n={codexSessionId:e.id,cliVersion:e.cli_version,modelProvider:e.model_provider};try{let o=await(0,c.resumeOrCreateSession)({sessionId:i,userId:s,agentType:c.AgentType.CODEX,projectPath:t,metadata:n},this.appSyncClient,r);this.sessionKey=o.sessionKey,await g("daemon_init_step_completed",{step:"session_resume_or_create",path:"session_started"})}catch(o){throw this.isInitializingSession=!1,await g("daemon_init_step_failed",{step:"session_resume_or_create",path:"session_started",error_class:o?.name||"Error",error_message:o?.message||String(o)}),r.error("Failed to create/resume session:",o),o}try{this.sessionState={sessionId:i,userId:s,projectPath:t,cwd:e.cwd,createdAt:new Date,subscriptionActive:!1,metadata:n,codexSessionId:e.id,codexLogFile:this.sessionWatcher.getActiveLogFile()||void 0},await(0,c.applyPerSessionOrchestrationOverride)(this.appSyncClient,i,r),await g("daemon_init_step_completed",{step:"session_state_set",path:"session_started"})}catch(o){await g("daemon_init_step_failed",{step:"session_state_set",path:"session_started",error_class:o?.name||"Error",error_message:o?.message||String(o)}),r.error("Failed to set session state:",o)}try{this.subscribeToMobileEvents(i)?await g("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"session_started"}):await g("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(o){await g("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:o?.name||"Error",error_message:o?.message||String(o)}),r.error("Failed to subscribe to mobile events:",o)}try{this.appSyncClient.startHeartbeat(i),await g("daemon_init_step_completed",{step:"heartbeat_start",path:"session_started"})}catch(o){await g("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:o?.name||"Error",error_message:o?.message||String(o)}),r.error("Failed to start heartbeat:",o)}try{await this.subscribeToOnApplyUserDecision(i)}catch(o){r.error("Failed to subscribe to onApplyUserDecision (non-fatal)",{error:o})}this.startMobileEndWatcher(i);try{await this.flushBufferedLogEntries(),await g("daemon_init_step_completed",{step:"flush_buffered_entries",path:"session_started"})}catch(o){await g("daemon_init_step_failed",{step:"flush_buffered_entries",path:"session_started",error_class:o?.name||"Error",error_message:o?.message||String(o)}),r.error("Failed to flush buffered log entries:",o),this.bufferedLogEntries=[]}await this.startTmuxObserverWithBeacon("session_started"),this.isInitializingSession=!1}async flushBufferedLogEntries(){if(this.bufferedLogEntries.length===0)return;let e=this.bufferedLogEntries;this.bufferedLogEntries=[],r.info("Flushing buffered log entries after session initialization",{count:e.length,sessionId:this.sessionState?.sessionId});for(let t of e)await this.handleLogEntry(t)}async handleLogEntry(e){if(!this.sessionState){if(this.isInitializingSession){this.bufferedLogEntries.push(e),r.debug("Buffering log entry until session initialization completes",{type:e.type,bufferedCount:this.bufferedLogEntries.length});return}r.warn("Received log entry but no active session");return}let t=this.sessionState.sessionId,i=this.sessionKey;if(e.type==="response_item"&&e.payload){let p=e.payload.type;if(p==="function_call"||p==="custom_tool_call")this.approvalDetector.onToolCallStart(e.payload.call_id,e.payload.name,e.payload.arguments||e.payload.input||"");else if(p==="function_call_output"||p==="custom_tool_call_output"){let d=this.approvalDetector.getPendingCalls().find(m=>m.callId===e.payload.call_id),u=d?this.buildApprovalDedupeKey(this.buildApprovalPromptContextFromPendingCall(d)):void 0;this.approvalDetector.onToolCallComplete(e.payload.call_id),await this.clearResolvedInteractivePrompt(e.payload.call_id,u)}}let s=oe(e,t);if(!s)return;s.timestamp=(0,c.prepareEventTimestamp)({orderingKey:t,agentClock:e.timestamp});let n=e.payload?.type,o=n==="function_call"||n==="function_call_output",a=s.type===c.EventType.USER_PROMPT||s.type===c.EventType.ASSISTANT_RESPONSE||o&&(s.type===c.EventType.TOOL_USE||s.type===c.EventType.INTERACTIVE_PROMPT);if(!this.hooksActive&&a&&await this.emitHooksCompatibilityModeNotice(),this.hooksActive){if(s.type===c.EventType.USER_PROMPT){r.debug("[JSONL] Skipping USER_PROMPT \u2014 hooks deliver it",{type:s.type});return}if(o&&(s.type===c.EventType.TOOL_USE||s.type===c.EventType.INTERACTIVE_PROMPT)){r.debug("[JSONL] Skipping function_call \u2014 hooks deliver this",{type:s.type,tool:e.payload?.name});return}}if(s.type===c.EventType.USER_PROMPT&&s.source===c.EventSource.DESKTOP){let p=this.consumeRecentMobilePrompt(t,s.content);if(p){r.info("[JSONL] Skipping duplicate USER_PROMPT from mobile",{sessionId:t,matchType:p.matchType,originalLength:p.originalLength,echoLength:p.echoLength});return}}try{if(i){if(s.content=c.cryptoService.encryptContent(s.content,i),s.metadata){let p=c.cryptoService.encryptMetadata(s.metadata,i);s.metadata={encrypted:p}}s.isEncrypted=!0,r.debug("Event encrypted",{type:s.type})}await this.appSyncClient.createEvent(s),r.debug("Event synced to backend",{type:s.type,encrypted:!!i})}catch(p){r.error("Failed to sync event:",p)}}async handlePermissionRequestHook(e){if(!this.sessionState)return;let t=e.metadata||{},i=typeof t.tool_name=="string"?t.tool_name:"Tool",s=t.tool_input,n=this.stringifyToolInput(s),o={toolName:i,toolInput:s,rawInput:n,filePath:this.extractFilePathFromToolInput(i,s,n),diff:i==="apply_patch"?n:void 0,hint:this.buildPermissionRequestHint(i,s,n)},a=this.buildToolDetailsForInteractivePrompt(o),p=a.tool_name||this.mapToolNameForApproval(i),d=a.tool_input||this.buildFallbackToolInput(o),u=!!(p&&d),h=(await this.tryParsePermissionRequestPromptFromTmux(Ae=>this.parsedPromptMatchesApprovalContext(Ae,o)))?.parsedPrompt??null;if(!h){r.warn("[Hooks] Suppressing PermissionRequest mobile prompt because exact Codex options are unavailable",{sessionId:this.sessionState.sessionId,toolName:i,hint:o.hint});return}let S=this.buildApprovalDedupeKey({toolName:i,toolInput:s,filePath:o.filePath,rawInput:n,hint:o.hint});if(S&&this.hasRecentlyResolvedApprovalDedupeKey(S)){r.info("[Hooks] Skipping PermissionRequest prompt; same approval was already answered recently",{sessionId:this.sessionState.sessionId,toolName:i,dedupeKey:S});return}let P=this.buildCodexPromptPresentation(h);if(!P){r.warn("[Hooks] Suppressing PermissionRequest mobile prompt because Codex option hotkeys are unavailable",{sessionId:this.sessionState.sessionId,toolName:i,hint:o.hint});return}let O=this.buildPermissionPromptId(t,i,s,n),A=this.buildApprovalPromptContent(P.content,{toolName:p,toolInput:d,hint:o.hint,filePath:o.filePath}),T={promptId:O,kind:P.kind,options:P.options,submitMap:P.submitMap,promptText:A,createdAt:Date.now(),source:"permission_hook",dedupeKey:S,requiresFollowUpText:P.requiresFollowUpText},J={isApprovalHint:!0,toolName:i,toolInput:s,hint:o.hint,filePath:o.filePath,diff:o.diff,rawInput:n,tool_name:p,tool_input:d,has_details:u,options:P.options,instructions:P.instructions,prompt_source:h?"permission_hook_tmux":"permission_hook",permission_mode:t.permission_mode,turn_id:t.turn_id,dedupe_key:S};r.info("[Hooks] Sending PermissionRequest interactive prompt",{sessionId:this.sessionState.sessionId,toolName:i,promptId:O,promptSource:J.prompt_source,dedupeKey:S}),await this.enqueueOrEmitInteractivePrompt({prompt:T,content:A,metadata:J})}async emitHooksCompatibilityModeNotice(){if(this.hooksCompatibilityNoticeSent||!this.sessionState)return;this.hooksCompatibilityNoticeSent=!0;let e="Codex hooks are not active. CodeVibe is using compatibility mode: mobile approvals still mirror the desktop prompt, but timeline events may be delayed or incomplete. Open Codex /hooks and trust/enable CodeVibe hooks for full fidelity.",t=e,i={compatibility_mode:!0,reason:"codex_hooks_inactive",action:"trust_enable_codevibe_hooks"},s=!1;this.sessionKey&&(t=c.cryptoService.encryptContent(e,this.sessionKey),i={encrypted:c.cryptoService.encryptMetadata(i,this.sessionKey)},s=!0),r.warn("Codex hooks inactive; running in compatibility mode",{sessionId:this.sessionState.sessionId});try{await this.appSyncClient.createEvent({sessionId:this.sessionState.sessionId,type:c.EventType.NOTIFICATION,source:c.EventSource.DESKTOP,content:t,metadata:i,timestamp:(0,c.prepareEventTimestamp)({orderingKey:this.sessionState.sessionId}),...s?{isEncrypted:!0}:{}})}catch(n){r.warn("Failed to emit hooks compatibility mode notification",{error:n})}}async handleApprovalPending(e){if(!this.sessionState)return;let t=this.buildApprovalDedupeKey(e);if(t&&this.hasRecentlyResolvedApprovalDedupeKey(t)){r.info("Skipping heuristic approval prompt; same approval was already answered recently",{callId:e.callId,toolName:e.toolName,dedupeKey:t});return}if(t&&this.hasActiveOrQueuedPermissionHookPrompt(t)){this.mergeCallIdIntoPromptByDedupeKey(t,e.callId),r.info("Skipping heuristic approval prompt; PermissionRequest hook already emitted it",{callId:e.callId,toolName:e.toolName,dedupeKey:t});return}r.info("Sending approval pending interactive prompt",e);try{let i=await this.tryParseInteractivePromptFromTmux(),s=i?.parsedPrompt??null,n=this.buildToolDetailsForInteractivePrompt(e,i?.snapshot),o=n.tool_name||this.mapToolNameForApproval(e.toolName),a=n.tool_input||this.buildFallbackToolInput(e),p=!!(o&&a);if(!s){r.warn("Suppressing heuristic approval prompt because exact Codex options are unavailable",{callId:e.callId,toolName:e.toolName,hint:e.hint});return}if(!this.parsedPromptMatchesApprovalContext(s,e)){r.warn("Suppressing heuristic approval prompt because parsed tmux prompt does not match the active tool",{callId:e.callId,toolName:e.toolName,hint:e.hint,parsedPromptText:s.promptText});return}let d=this.buildCodexPromptPresentation(s);if(!d){r.warn("Suppressing heuristic approval prompt because Codex option hotkeys are unavailable",{callId:e.callId,toolName:e.toolName,hint:e.hint});return}let u=d.options,m=this.buildApprovalPromptContent(d.content,{toolName:o,toolInput:a,hint:e.hint,filePath:e.filePath}),h={promptId:e.callId,callId:e.callId,kind:d.kind,options:u,submitMap:d.submitMap,promptText:d.promptText,createdAt:Date.now(),source:s?"tmux":"heuristic",dedupeKey:t,requiresFollowUpText:d.requiresFollowUpText},S={isApprovalHint:!0,toolName:e.toolName,toolInput:e.toolInput,hint:e.hint,callId:e.callId,filePath:e.filePath,diff:e.diff,rawInput:e.rawInput,tool_name:o,tool_input:a,has_details:p,options:u,instructions:d.instructions,prompt_source:s?"tmux":"heuristic",dedupe_key:t};r.debug("Interactive prompt (pre-encryption)",{sessionId:this.sessionState.sessionId,callId:e.callId,contentPreview:m.substring(0,200),toolDetails:n,metadata:S}),await this.enqueueOrEmitInteractivePrompt({prompt:h,content:m,metadata:S})}catch(i){r.error("Failed to send approval interactive prompt:",i)}}async handleTmuxPromptCandidate(e){if(!this.sessionState)return;let t=(0,E.parseInteractivePrompt)(e);if(!t)return;let i=this.buildCodexPromptPresentation(t);if(!i){r.warn("Skipping tmux-detected prompt because Codex option hotkeys are unavailable",{parsedPromptText:t.promptText});return}let s=this.getMostRecentPendingToolCall();s||(await new Promise(T=>setTimeout(T,500)),s=this.getMostRecentPendingToolCall());let n=s?this.buildApprovalPromptContextFromPendingCall(s):null;if(n&&!this.parsedPromptMatchesApprovalContext(t,n)){r.warn("Skipping tmux-detected prompt because parsed prompt does not match pending tool call",{callId:s?.callId,toolName:s?.name,parsedPromptText:t.promptText});return}let o=n?null:this.buildApprovalPromptContextFromParsedPrompt(t),a=n||o;if(!a){r.warn("Skipping tmux-detected prompt because no tool context could be derived from the parsed prompt",{parsedPromptText:t.promptText});return}let p=a?this.buildApprovalDedupeKey(a):void 0;if(p&&this.hasRecentlyResolvedApprovalDedupeKey(p)){r.info("Skipping tmux-detected prompt; same approval was already answered recently",{promptText:t.promptText,dedupeKey:p});return}if(p&&this.hasActiveOrQueuedPermissionHookPrompt(p)){s?.callId&&this.mergeCallIdIntoPromptByDedupeKey(p,s.callId),r.info("Skipping tmux-detected prompt; PermissionRequest hook already emitted it",{promptText:t.promptText,dedupeKey:p});return}let d=a?this.buildToolDetailsForInteractivePrompt(a,e):{},u=d.tool_name||this.mapToolNameForApproval(s?.name),m=d.tool_input||(a?this.buildFallbackToolInput(a):void 0),h=!!(u&&m),P={promptId:s?.callId||(0,Ee.v4)(),callId:s?.callId,kind:i.kind,options:i.options,submitMap:i.submitMap,promptText:i.promptText,createdAt:Date.now(),source:"tmux",dedupeKey:p,requiresFollowUpText:i.requiresFollowUpText},O={options:i.options,instructions:i.instructions,prompt_source:"tmux_live",tool_name:u,tool_input:m,has_details:h,dedupe_key:p},A=this.buildApprovalPromptContent(i.content,{toolName:u,toolInput:m,hint:a?.hint,filePath:a?.filePath});try{await this.enqueueOrEmitInteractivePrompt({prompt:P,content:A,metadata:O})&&r.info("Sent tmux-detected interactive prompt",{sessionId:this.sessionState.sessionId,promptText:t.promptText,kind:t.kind})}catch(T){r.error("Failed to send tmux-detected interactive prompt",{error:T})}}async enqueueOrEmitInteractivePrompt(e){if(e.prompt.dedupeKey&&this.hasRecentlyResolvedApprovalDedupeKey(e.prompt.dedupeKey))return r.debug("Skipping interactive prompt emission; same approval was already answered recently",{source:e.prompt.source,callId:e.prompt.callId,dedupeKey:e.prompt.dedupeKey}),!1;let t=this.pendingInteractivePrompt;if(!t){this.pendingInteractivePrompt=e.prompt;try{return await this.emitInteractivePromptEvent(e),!0}catch(i){throw this.pendingInteractivePrompt?.promptId===e.prompt.promptId&&(this.pendingInteractivePrompt=null),i}}return this.isSameInteractivePrompt(t,e.prompt)?(!t.callId&&e.prompt.callId&&(t.callId=e.prompt.callId,r.debug("Merged callId into existing interactive prompt",{source:t.source,callId:e.prompt.callId,promptText:t.promptText})),r.debug("Skipping duplicate interactive prompt emission",{existingSource:t.source,candidateSource:e.prompt.source,existingCallId:t.callId,candidateCallId:e.prompt.callId,promptText:e.prompt.promptText}),!1):this.queuedInteractivePrompts.some(i=>this.isSameInteractivePrompt(i.prompt,e.prompt))?(r.debug("Skipping duplicate queued interactive prompt",{candidateSource:e.prompt.source,candidateCallId:e.prompt.callId,promptText:e.prompt.promptText}),!1):(this.queuedInteractivePrompts.push(e),r.info("Queued interactive prompt behind active prompt",{activeCallId:t.callId,queuedCallId:e.prompt.callId,queueLength:this.queuedInteractivePrompts.length}),!1)}async emitInteractivePromptEvent(e){if(!this.sessionState)return;let t=e.content,i=e.metadata,s=!1;this.sessionKey&&(t=c.cryptoService.encryptContent(t,this.sessionKey),i={encrypted:c.cryptoService.encryptMetadata(i,this.sessionKey)},s=!0),await this.appSyncClient.createEvent({sessionId:this.sessionState.sessionId,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:t,metadata:i,promptId:e.prompt.promptId,timestamp:(0,c.prepareEventTimestamp)({orderingKey:this.sessionState.sessionId}),...s?{isEncrypted:!0}:{}})}async emitNextQueuedInteractivePrompt(){if(this.pendingInteractivePrompt||this.queuedInteractivePrompts.length===0)return;let e=this.queuedInteractivePrompts.shift();if(e){this.pendingInteractivePrompt=e.prompt;try{await this.emitInteractivePromptEvent(e),r.info("Emitted next queued interactive prompt",{callId:e.prompt.callId,queueLength:this.queuedInteractivePrompts.length})}catch(t){this.pendingInteractivePrompt=null,r.error("Failed to emit queued interactive prompt",{error:t}),await this.emitNextQueuedInteractivePrompt()}}}removeQueuedInteractivePromptByCallId(e){let t=this.queuedInteractivePrompts.length,i=this.queuedInteractivePrompts.filter(s=>s.prompt.callId===e);for(let s of i)this.rememberResolvedApprovalDedupeKey(s.prompt.dedupeKey);this.queuedInteractivePrompts=this.queuedInteractivePrompts.filter(s=>s.prompt.callId!==e),this.queuedInteractivePrompts.length!==t&&r.debug("Removed resolved tool call from interactive prompt queue",{callId:e,removed:t-this.queuedInteractivePrompts.length})}async clearResolvedInteractivePrompt(e,t){let i=this.pendingInteractivePrompt;if(i&&(i.callId===e||t!==void 0&&i.dedupeKey===t)){this.rememberResolvedApprovalDedupeKey(i.dedupeKey),this.pendingInteractivePrompt=null,await this.emitNextQueuedInteractivePrompt();return}this.removeQueuedInteractivePromptByCallId(e),t!==void 0&&this.removeQueuedInteractivePromptByDedupeKey(t)}removeQueuedInteractivePromptByDedupeKey(e){let t=this.queuedInteractivePrompts.length,i=this.queuedInteractivePrompts.filter(s=>s.prompt.dedupeKey===e);for(let s of i)this.rememberResolvedApprovalDedupeKey(s.prompt.dedupeKey);this.queuedInteractivePrompts=this.queuedInteractivePrompts.filter(s=>s.prompt.dedupeKey!==e),this.queuedInteractivePrompts.length!==t&&r.debug("Removed resolved deduped tool call from interactive prompt queue",{dedupeKey:e,removed:t-this.queuedInteractivePrompts.length})}mergeCallIdIntoPromptByDedupeKey(e,t){let i=this.pendingInteractivePrompt;if(i?.dedupeKey===e&&!i.callId){i.callId=t,r.debug("Merged callId into active deduped interactive prompt",{source:i.source,callId:t,dedupeKey:e});return}let s=this.queuedInteractivePrompts.find(n=>n.prompt.dedupeKey===e&&!n.prompt.callId);s&&(s.prompt.callId=t,r.debug("Merged callId into queued deduped interactive prompt",{source:s.prompt.source,callId:t,dedupeKey:e}))}isSameInteractivePrompt(e,t){return Date.now()-e.createdAt>it?!1:e.callId&&t.callId?e.callId===t.callId:e.dedupeKey&&t.dedupeKey?e.dedupeKey===t.dedupeKey:e.kind===t.kind&&this.normalizePromptDedupeText(e.promptText)===this.normalizePromptDedupeText(t.promptText)}normalizePromptDedupeText(e){return e.replace(/\s+/g," ").trim().toLowerCase()}async startTmuxObserver(){let e=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!e)return r.debug("Skipping tmux pane observer start - no tmux session in environment"),!0;try{return await this.tmuxPaneObserver.start(e),!0}catch(t){return r.warn("Failed to start tmux pane observer",{tmuxSession:e,error:t}),!1}}async startTmuxObserverWithBeacon(e){try{await this.startTmuxObserver()?await g("daemon_init_step_completed",{step:"tmux_observer_start",path:e}):await g("daemon_init_step_failed",{step:"tmux_observer_start",path:e,error_class:"TmuxObserverStartFailed",error_message:"tmuxPaneObserver.start threw (see plugin log)"})}catch(t){await g("daemon_init_step_failed",{step:"tmux_observer_start",path:e,error_class:t?.name||"Error",error_message:t?.message||String(t)}),r.error("Failed to start tmux observer:",t)}}async tryParseInteractivePromptFromTmux(){try{let e=await this.tmuxPaneObserver.captureSnapshot(),t=(0,E.parseInteractivePrompt)(e);return r.debug("tmux prompt parse result",{parsed:!!t,kind:t?.kind,promptText:t?.promptText,snapshotPreview:this.summarizePromptSnapshot(e)}),{parsedPrompt:t,snapshot:e}}catch(e){return r.debug("tmux prompt parsing unavailable",{error:e}),null}}async tryParsePermissionRequestPromptFromTmux(e){let t=await this.tryParseInteractivePromptFromTmux();if(t?.parsedPrompt&&(!e||e(t.parsedPrompt,t.snapshot)))return t;t?.parsedPrompt&&r.warn("Ignoring parsed PermissionRequest prompt because it does not match the active tool",{promptText:t.parsedPrompt.promptText}),await new Promise(s=>setTimeout(s,250));let i=await this.tryParseInteractivePromptFromTmux();return i?.parsedPrompt&&(!e||e(i.parsedPrompt,i.snapshot))?i:(i?.parsedPrompt&&r.warn("Ignoring retried PermissionRequest prompt because it does not match the active tool",{promptText:i.parsedPrompt.promptText}),i?.snapshot||t?.snapshot?{parsedPrompt:null,snapshot:i?.snapshot||t?.snapshot||""}:null)}buildPromptPresentation(e){return e?{content:e.promptText,promptText:e.promptText,kind:e.kind,options:e.options,submitMap:e.submitMap,instructions:this.buildPromptInstructions(e),requiresFollowUpText:e.requiresFollowUpText}:{content:"Codex is waiting for approval.",promptText:"Codex is waiting for approval.",kind:"yes_no",options:[{number:"1",text:'Yes (sends "y")'},{number:"2",text:'No, tell Codex what to change (sends "n <instructions>")'}],submitMap:{1:"y",2:"n"},instructions:"Reply with 1 to approve, or 2 followed by what to change",requiresFollowUpText:!0}}buildCodexPromptPresentation(e){let t=this.buildPromptPresentation(e),i=this.buildSubmitMapFromCodexOptionHotkeys(t.options);return i?{...t,submitMap:i,instructions:this.buildCodexPermissionInstructions(t.options),requiresFollowUpText:this.optionsRequireFollowUpText(t.options)}:null}buildSubmitMapFromCodexOptionHotkeys(e){let t={};for(let i of e){let s=i.text.match(/\(([^)]+)\)\s*$/)?.[1]?.trim().toLowerCase();if(!s||!rt.test(s))return null;s==="esc"||s==="escape"?t[i.number]=C:t[i.number]=s}return t}buildCodexPermissionInstructions(e){let t=e.find(o=>/\((?:y|yes)\)\s*$/i.test(o.text)),i=e.find(o=>/\(p\)\s*$/i.test(o.text)),s=e.find(o=>/\((?:esc|escape)\)\s*$/i.test(o.text)),n=[];return t&&n.push(`${t.number} to approve`),i&&n.push(`${i.number} to persist the desktop allow rule`),s&&n.push(`${s.number} followed by what to change`),n.length>0?`Reply with ${n.join(", ")}`:"Reply with the number of the option you want"}optionsRequireFollowUpText(e){return e.some(t=>/what to (?:do differently|change)|instructions/i.test(t.text))}getMostRecentPendingToolCall(){let e=this.approvalDetector.getPendingCalls();return e.length===0?null:e.reduce((t,i)=>i.timestamp>t.timestamp?i:t)}hasActiveOrQueuedPermissionHookPrompt(e){let t=this.pendingInteractivePrompt;return t?.source==="permission_hook"&&t.dedupeKey===e?!0:this.queuedInteractivePrompts.some(i=>i.prompt.source==="permission_hook"&&i.prompt.dedupeKey===e)}hasRecentlyResolvedApprovalDedupeKey(e){return this.pruneResolvedApprovalDedupeKeys(),this.resolvedApprovalDedupeKeys.has(e)}rememberResolvedApprovalDedupeKey(e){e&&(this.pruneResolvedApprovalDedupeKeys(),this.resolvedApprovalDedupeKeys.set(e,Date.now()))}pruneResolvedApprovalDedupeKeys(){let e=Date.now()-st;for(let[t,i]of this.resolvedApprovalDedupeKeys.entries())i<e&&this.resolvedApprovalDedupeKeys.delete(t)}buildApprovalDedupeKey(e){let t=e.toolName||"Tool",i=this.firstString(e.toolInput?.command,e.toolInput?.cmd,e.rawInput);if(i)return`command:${this.hashDedupeValue(`${this.mapToolNameForApproval(t)||t}:${i.trim()}`)}`;let s=this.firstString(e.filePath,e.toolInput?.file_path,e.toolInput?.path,e.toolInput?.filePath);if(s)return`file:${this.hashDedupeValue(`${t}:${s}`)}`;let n=this.firstString(e.hint);if(n)return`hint:${this.hashDedupeValue(`${t}:${n}`)}`}hashDedupeValue(e){return X.createHash("sha256").update(e.replace(/\s+/g," ").trim().toLowerCase()).digest("hex").slice(0,16)}buildPermissionPromptId(e,t,i,s){let n=typeof e.turn_id=="string"&&e.turn_id.trim().length>0?e.turn_id.trim():void 0,o=X.createHash("sha256").update(`${t}:${s||this.stringifyToolInput(i)}`).digest("hex").slice(0,12);return`permission-${n||"turn"}-${o}`}buildPermissionRequestHint(e,t,i){let s=this.firstString(t?.command,t?.cmd);if(s)return`Command: ${this.truncateApprovalDetail(s,80)}`;let n=this.extractFilePathFromToolInput(e,t,i);return n?`File: ${n}`:`Tool: ${this.mapToolNameForApproval(e)||e}`}extractFilePathFromToolInput(e,t,i){let s=this.firstString(t?.file_path,t?.path,t?.filePath);if(s)return s;if(e==="apply_patch"&&i){let n=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(n)return n[1].trim()}}stringifyToolInput(e){if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}}buildApprovalPromptContextFromPendingCall(e){return{toolName:e.name,filePath:e.filePath,diff:e.diff,toolInput:e.parsedInput,rawInput:e.input,hint:e.filePath?`File: ${e.filePath}`:`Tool: ${this.mapToolNameForApproval(e.name)||e.name}`}}buildApprovalPromptContextFromParsedPrompt(e){let t=this.extractShellCommandFromPromptText(e.promptText);return t?{toolName:"Bash",toolInput:{command:t},rawInput:t,hint:`Command: ${this.truncateApprovalDetail(t,80)}`}:null}parsedPromptMatchesApprovalContext(e,t){let i=this.firstString(t.toolInput?.command,t.toolInput?.cmd);if(i){let n=Q(e.promptText);if(!n||n.length===0)return!1;let o=this.normalizeApprovalCommand(i);return this.normalizeApprovalCommand(n.join(" "))===o||n.length>1&&this.normalizeApprovalCommand(n.join(""))===o}let s=this.firstString(t.filePath,t.toolInput?.file_path,t.toolInput?.path,t.toolInput?.filePath);return s?e.promptText.includes(s):!1}normalizeApprovalCommand(e){return e.replace(/\s+/g," ").trim()}extractShellCommandFromPromptText(e){return Oe(e)}buildPromptInstructions(e){return e.kind==="yes_no"&&e.requiresFollowUpText?"Reply with 1 to approve, or 2 followed by what to change":e.kind==="yes_no"?"Reply with 1 for yes or 2 for no":e.kind==="numbered"?"Reply with the number of the option you want":"Reply with your response"}buildApprovalPromptContent(e,t){let i=e.trim(),s=i==="Codex is waiting for approval.",n=/^\$\s+/.test(i),o=t.toolName?`${t.toolName} requires approval.`:"Codex is waiting for approval.",a=[s||n||!i?o:i],p=typeof t.toolInput?.command=="string"?t.toolInput.command.trim():void 0;if(p&&!a.join(`
|
|
14
|
-
`).includes(
|
|
15
|
-
`);let
|
|
16
|
-
`).includes(
|
|
17
|
-
`)):(t.hint&&!
|
|
18
|
-
`).includes(t.hint)&&
|
|
12
|
+
`).trim();return(0,Pe.createHash)("sha256").update(i).digest("hex")}};var C=require("@quantiya/codevibe-core");var Q=P(require("express")),x=P(require("fs")),Ee=P(require("path")),Te=P(require("os"));var rt=1800*1e3,nt=60*1e3,ot=1440*60*1e3;var z=class{constructor(){this.assignedPort=0;this.portRefreshTimer=null;this.app=(0,Q.default)(),this.setupMiddleware(),this.setupRoutes(),this.tmuxSession=process.env.CODEVIBE_CODEX_TMUX_SESSION}getPort(){return this.assignedPort}setupMiddleware(){this.app.use(Q.default.json({limit:"1mb"})),this.app.use((e,t,i)=>{n.debug(`${e.method} ${e.path}`,{body:e.body}),i()})}setupRoutes(){this.app.get("/health",(e,t)=>{t.json({success:!0,service:"codevibe-codex",pid:process.pid,data:{status:"healthy",uptime:process.uptime()}})}),this.app.post("/event",this.handleEvent.bind(this))}async handleEvent(e,t){try{let i=e.body;if(!i.session_id||!i.hook_event_name){t.status(400).json({success:!1,error:"Missing session_id or hook_event_name"});return}let s=this.transformHookToEvent(i);n.info("Received hook event",{sessionId:i.session_id,hookEvent:i.hook_event_name,type:s.type}),this.eventHandler&&await this.eventHandler(s),t.json({success:!0})}catch(i){n.error("Error handling event:",i),t.status(500).json({success:!1,error:i instanceof Error?i.message:"Unknown error"})}}transformHookToEvent(e){let t={cwd:e.cwd,hook_event_name:e.hook_event_name,...e.metadata||{}},i,s;switch(e.hook_event_name){case"SessionStart":i="NOTIFICATION",s="Session started",t.source=e.source,t.transcript_path=e.transcript_path,t.model=e.model;break;case"UserPromptSubmit":i="USER_PROMPT",s=e.prompt||"";break;case"PreToolUse":i="NOTIFICATION",s="PreToolUse observed",t.tool_name=e.tool_name,t.tool_input=e.tool_input,t.tool_use_id=e.tool_use_id,t.approval_status="observed_pre_tool",t.requires_user_action=!1;break;case"PermissionRequest":i="NOTIFICATION",s="PermissionRequest observed",t.tool_name=e.tool_name,t.tool_input=e.tool_input,t.permission_mode=e.permission_mode,t.turn_id=e.turn_id,t.requires_user_action=!0;break;case"PostToolUse":i="TOOL_USE",s=JSON.stringify({tool_name:e.tool_name,tool_input:e.tool_input,tool_response:e.tool_response}),t.tool_name=e.tool_name,t.tool_input=e.tool_input,t.tool_use_id=e.tool_use_id;break;case"Stop":i="ASSISTANT_RESPONSE",s=e.last_assistant_message||"";break;default:i="NOTIFICATION",s=`Hook: ${e.hook_event_name}`}return{session_id:e.session_id,hook_event_name:e.hook_event_name,type:i,source:"DESKTOP",content:s,metadata:t}}onEvent(e){this.eventHandler=e}async start(){return new Promise((e,t)=>{try{this.server=this.app.listen(0,"localhost",()=>{let i=this.server.address();this.assignedPort=i.port,n.info(`HTTP API listening on http://localhost:${this.assignedPort}`),this.writePortFile(this.assignedPort),this.startPortFileKeepalive(),e(this.assignedPort)}),this.server.on("error",i=>{n.error("HTTP server error:",i),t(i)})}catch(i){t(i)}})}portFilePath(){return this.tmuxSession?Ee.join(Te.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`):null}writePortFile(e){let t=this.portFilePath();if(!t){n.warn("No CODEVIBE_CODEX_TMUX_SESSION set, skipping port file");return}try{x.writeFileSync(t,e.toString()),n.info(`Port file written: ${t} -> ${e}`)}catch(i){n.error(`Failed to write port file: ${t}`,i)}}removePortFile(){let e=this.portFilePath();if(e)try{x.existsSync(e)&&(x.unlinkSync(e),n.info(`Port file removed: ${e}`))}catch(t){n.warn(`Failed to remove port file: ${e}`,t)}}startPortFileKeepalive(){this.portRefreshTimer&&(clearInterval(this.portRefreshTimer),this.portRefreshTimer=null);let e=Number(process.env.CODEVIBE_PORTFILE_REFRESH_MS),t=Number.isFinite(e)&&e>0?Math.min(ot,Math.max(nt,e)):rt;this.portRefreshTimer=setInterval(()=>this.refreshPortFile(),t)}refreshPortFile(){let e=this.portFilePath();if(e)try{let t=new Date;x.utimesSync(e,t,t)}catch(t){t?.code==="ENOENT"?this.writePortFile(this.assignedPort):n.warn(`Port-file refresh failed: ${e}`,t)}}async stop(){return this.portRefreshTimer&&(clearInterval(this.portRefreshTimer),this.portRefreshTimer=null),this.removePortFile(),new Promise(e=>{this.server?this.server.close(()=>{n.info("HTTP API stopped"),e()}):e()})}};var q=class{constructor(e={}){this.pendingBySession=new Map;this.expiryMs=e.expiryMs??1e4,this.minFuzzyEchoLength=e.minFuzzyEchoLength??16,this.minFuzzyEchoRatio=e.minFuzzyEchoRatio??.35,this.now=e.now??Date.now}track(e,t){let i=this.normalize(t);if(!i)return;let s=this.validEntries(e);s.push({normalized:i,timestamp:this.now()}),this.pendingBySession.set(e,s)}forget(e,t){let i=this.normalize(t);if(!i)return;let s=!1,r=this.validEntries(e).filter(o=>!s&&o.normalized===i?(s=!0,!1):!0);this.replaceEntries(e,r)}consumeIfDuplicate(e,t){let i=this.normalize(t);if(!i)return null;let s=null,r=this.validEntries(e).filter(o=>{if(!s){let l=this.matchType(o.normalized,i);if(l)return s={matchType:l,originalLength:o.normalized.length,echoLength:i.length},!1}return!0});return this.replaceEntries(e,r),s}validEntries(e){let t=this.now()-this.expiryMs;return(this.pendingBySession.get(e)||[]).filter(i=>i.timestamp>=t)}replaceEntries(e,t){t.length>0?this.pendingBySession.set(e,t):this.pendingBySession.delete(e)}matchType(e,t){if(e===t)return"exact";let i=t.length>=this.minFuzzyEchoLength,s=t.length/e.length>=this.minFuzzyEchoRatio;return i&&s&&e.endsWith(t)?"suffix":null}normalize(e){return e.replace(/\s+/g," ").trim()}};var Re=P(require("crypto")),Ce=P(require("fs")),Oe=P(require("https")),H=P(require("os")),Ae=P(require("path")),at="G-GS74YEQTB8",lt="lAfOF6OxRzSQ-NsLBRjhAg",pt="www.google-analytics.com",ct=`/mp/collect?measurement_id=${at}&api_secret=${lt}`,xe=800;function dt(){try{let c=Ae.resolve(__dirname,"..","package.json"),e=Ce.readFileSync(c,"utf-8"),t=JSON.parse(e);if(typeof t.version=="string"&&t.version.length>0&&t.version.length<30)return t.version}catch{}return"unknown"}var ut=dt();function ht(){let c=typeof process.getuid=="function"?process.getuid():0;return Re.createHash("sha256").update(`${H.hostname()}-${c}`).digest("hex").substring(0,36)}function mt(c){if(!c)return"";let e=H.homedir(),t=c.replace(/[\n\r\t]/g," ");if(e&&e.length>0){let i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replace(new RegExp(i,"g"),"~")}return t=t.replace(/\/Users\/[^/\s"'`]+/g,"/Users/<user>").replace(/\/home\/[^/\s"'`]+/g,"/home/<user>").replace(/[^\x20-\x7E]/g,""),t.trim().substring(0,100)}function v(c,e){return new Promise(t=>{let i,s=!1,r=()=>{s||(s=!0,clearTimeout(o),t())},o=setTimeout(()=>{try{i?.destroy()}catch{}r()},xe);typeof o.unref=="function"&&o.unref();try{let l={...e};typeof l.error_message=="string"&&(l.error_message=mt(l.error_message));let a=JSON.stringify({client_id:ht(),events:[{name:c,params:{agent:"codex",plugin_version:ut,platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production",...l}}]});i=Oe.request({hostname:pt,path:ct,method:"POST",headers:{"Content-Type":"application/json"},timeout:xe},p=>{p.resume(),p.on("end",r),p.on("close",r),p.on("error",r)}),i.on("error",r),i.on("timeout",()=>{try{i?.destroy()}catch{}r()}),i.on("close",r),i.write(a),i.end()}catch{r()}})}var W=class{constructor(){this.originated=new Set;this.externallyResolved=new Set}markOriginated(e){this.originated.add(e)}clearOriginated(e){this.originated.delete(e)}getOriginated(){return new Set(this.originated)}getExternallyResolved(){return new Set(this.externallyResolved)}isExternallyResolved(e){return this.externallyResolved.has(e)}dispatch(e){let{gateId:t}=e;return this.originated.has(t)?(this.originated.delete(t),this.externallyResolved.add(t),"self_echo"):(this.externallyResolved.add(t),"foreign")}clear(){this.originated.clear(),this.externallyResolved.clear()}};function ke(c){return`[CodeVibe] Decision recorded on another device: ${c} \u2014 type any number to dismiss the open AskUserQuestion`}var Ne=(0,te.promisify)(G.exec),ft=(0,te.promisify)(G.execFile),gt="/quit",D="CODEVIBE_CODEX_TMUX_SESSION",Z="CODEVIBE_CODEX_DAEMON_RECOVERY",yt=1e3,vt=600*1e3,St=30*1e3,bt=/^(?:[a-z0-9]|esc|escape)$/;async function Pt(c,e){let t=async(i,s)=>{try{await Ne(i)}catch(r){n.warn("tmux send-keys failed during self-terminate",{sessionName:c,label:s,error:String(r)})}};await t(`tmux send-keys -t "${c}" C-c`,"ctrl-c"),await new Promise(i=>setTimeout(i,200)),await t(`tmux send-keys -t "${c}" -l "${e}"`,"quit-text"),await new Promise(i=>setTimeout(i,500)),await t(`tmux send-keys -t "${c}" Enter`,"enter")}function ie(c){let e=c.split(`
|
|
13
|
+
`),t=o=>/^[\s>]*\d+\.\s/.test(o),i=-1;for(let o=e.length-1;o>=0;o-=1)if(/^\s*\$\s+/.test(e[o])){i=o;break}if(i===-1)return;let s=e[i].trim().match(/^\$\s+(.+)$/);if(!s?.[1]?.trim())return;let r=[s[1].trim()];for(let o=i+1;o<e.length;o+=1){let l=e[o];if(t(l)||/^\s*$/.test(l)||/^\s*\$\s+/.test(l))break;r.push(l.trim())}return r.length>0?r:void 0}function Me(c){let e=ie(c);if(!e)return;let t=e.join(" ").trim();return t.length>0?t:void 0}var V=class c{constructor(){this.sessionState=null;this.unsubscribe=null;this.sessionKey=null;this.sessionIsEncrypted=!1;this.sessionKeyGen=null;this.e1PromptRaises=new Map;this.e1NeedsReRaise=new Set;this.e1RetirementOrphans=new Map;this.e1ContentKeyIndex=new Map;this.e1TtlRefreshTimer=null;this.toolActivity=null;this.toolActivityStartPromise=null;this.toolActivityLegacyRecorders=new Map;this.pendingInteractivePrompt=null;this.queuedInteractivePrompts=[];this.isInitializingSession=!1;this.bufferedLogEntries=[];this.logEntryChain=Promise.resolve();this.hooksActive=!1;this.hooksCompatibilityNoticeSent=!1;this.resolvedApprovalDedupeKeys=new Map;this.subscribedSessionId=null;this.subscribedSessionState=null;this.terminalInputChain=Promise.resolve();this.terminalInputBlockedStates=new WeakSet;this.mobilePromptDeduper=new q({expiryMs:1e4});this.launchSessionInitPromise=null;this.sessionStartedInitPromise=null;this.bootstrapSessionId=null;this.recoveryBootstrapOwnerBound=!1;this.resumeBackendSession=d.resumeOrCreateSession;this.sessionBootstrapFailureCount=0;this.sessionBootstrapRetryAt=0;this.retiredSessionRecoveryPromise=null;this.lifecycleGeneration=0;this.isStopping=!1;this.tmuxLifecycleTimer=null;this.tmuxLifecycleCheckInFlight=!1;this.tmuxLifecycleObservedAlive=!1;this.v1Bridge=new W;this.orchestrationClient=null;this.userDecisionUnsubscribe=null;this.httpApi=new z,this.sessionWatcher=new L,this.approvalDetector=new B,this.promptResponder=new K,this.tmuxPaneObserver=new U}static{this.E1_TTL_REFRESH_MS=300*1e3}async start(){n.info("Starting CodeVibe Codex companion server",{environment:(0,d.getEnvironment)()}),this.appSyncClient=new d.AppSyncClient,await this.appSyncClient.authenticateWithStoredTokens()||(n.error('Authentication failed. Run "codevibe login" first.'),console.error('Not authenticated. Run "codevibe login" to sign in.'),process.exit(1)),n.info("Authenticated successfully",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()}),await(0,d.registerDeviceEncryptionKey)(this.appSyncClient,n),(0,d.startDeviceKeyWatcher)(this.appSyncClient,n),(0,d.pushDetectedAgents)(this.appSyncClient,n).catch(i=>{n.warn("Failed to update available agents (non-fatal)",{error:i?.message})});try{let i=await this.appSyncClient.sweepOrphanSessions({agentType:"CODEX"});i>0&&n.info("Orphan sweep: marked stale Codex sessions INACTIVE",{swept:i})}catch(i){n.warn("Orphan sweep failed, continuing startup",{error:i instanceof Error?i.message:String(i)})}this.httpApi.onEvent(this.handleEventFromHook.bind(this));let t=await this.httpApi.start();n.info("HTTP API started for hooks",{port:t}),this.startTmuxLifecycleMonitor(),await this.createLaunchSession(),this.setupEventHandlers(),this.sessionWatcher.start(),n.info("CodeVibe Codex companion server started")}async createLaunchSession(){if(this.isStopping)return;if(process.env[Z]==="1"){n.info("Recovery daemon deferring backend bootstrap until the native rollout is known");return}let e=this.lifecycleGeneration,t=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!t){n.warn("No CODEVIBE_CODEX_TMUX_SESSION \u2014 skipping launch session");return}let i;this.launchSessionInitPromise=new Promise(s=>{i=s});try{let s=process.env.CODEX_WORKING_DIRECTORY||process.cwd(),r=this.getOrCreateBootstrapSessionId(),o=this.appSyncClient.getCurrentUserId();n.info("Creating launch session",{sessionId:r,projectPath:s});let l=!1;try{let a=await(0,d.resumeOrCreateSession)({sessionId:r,userId:o,agentType:d.AgentType.CODEX,projectPath:s,metadata:{launchSession:!0}},this.appSyncClient,n);if(r=a.sessionId,!this.isLifecycleCurrent(e)){await this.retireCancelledBootstrap(r,"launch_session");return}this.sessionKey=a.sessionKey,this.sessionKeyGen=a.sessionKeyGen,this.sessionIsEncrypted=!!a.sessionKey,l=!0,this.sessionState={sessionId:r,userId:o,projectPath:s,cwd:s,createdAt:new Date,subscriptionActive:!1,metadata:{launchSession:!0},encryptionSnapshot:{sessionKey:a.sessionKey,sessionIsEncrypted:!!a.sessionKey},codexSessionId:t,codexLogFile:void 0},this.clearSessionBootstrapFailure(),this.bootstrapSessionId=null,await v("daemon_init_step_completed",{step:"session_resume_or_create",path:"launch_session"})}catch(a){if(!this.isLifecycleCurrent(e)){let p=this.authoritativeSessionIdFromError(a)??r;await this.retireCancelledBootstrap(p,"launch_session_error");return}await v("daemon_init_step_failed",{step:"session_resume_or_create",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),a?.code==="ENCRYPTED_SESSION_NO_KEY"&&(this.sessionIsEncrypted=!0,this.sessionKey=null),this.bindBootstrapIdentityFromError(a),this.recordSessionBootstrapFailure(a,"launch_session"),n.error("Failed to create/resume launch session (non-fatal)",{error:a})}if(!l)return;await v("daemon_init_step_completed",{step:"session_state_set",path:"launch_session"});try{this.subscribeToMobileEvents(r)?await v("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"launch_session"}):await v("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(a){await v("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),n.error("Failed to subscribe to mobile events for launch session",{error:a})}try{await this.appSyncClient.startHeartbeat(r)?await v("daemon_init_step_completed",{step:"heartbeat_start",path:"launch_session"}):(await v("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:"InitialHeartbeatNotPersisted",error_message:"Backend did not confirm the initial heartbeat mutation"}),n.error("Initial launch-session heartbeat was not persisted",{sessionId:r}))}catch(a){await v("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),n.error("Failed to start heartbeat for launch session",{error:a})}try{await this.subscribeToOnApplyUserDecision(r)}catch(a){n.error("Failed to subscribe to onApplyUserDecision for launch session (non-fatal)",{error:a})}this.startMobileEndWatcher(r),n.info("Launch session created",{sessionId:r})}finally{i()}}encryptForEmit(e,t,i,s){let r=this.sessionState;if(!r||r.sessionId!==s||!r.encryptionSnapshot)return n.warn("Dropping event from stale or unresolved session generation (#638)",{type:i,sessionId:s,currentSessionId:r?.sessionId}),null;let{sessionKey:o,sessionIsEncrypted:l}=r.encryptionSnapshot,a=(0,d.encryptForEmit)(o,l,e,t);return a===null&&n.error("No session key for ENCRYPTED session \u2014 dropping event (fail-closed, #638)",{type:i,sessionId:s}),a}newE1Raise(e,t,i){let{record:s}=(0,d.newPromptRaise)({sessionId:e,producerKind:"PLUGIN_APPROVAL",mobileActionable:t,agentType:"CODEX",...i!==void 0&&{title:i}});return this.e1PromptRaises.set(s.promptId,{record:s}),this.e1TtlRefreshTimer||this.startE1TtlRefresh(),s}stashE1RaiseContent(e,t,i){let s=this.e1PromptRaises.get(e);s&&(s.contentPlain=t,s.metadataPlain=i)}async emitSuppressedPromptCarrier(e,t){let i="\u26A0\uFE0F A prompt is waiting in your desktop terminal, but its options could not be shown here. Please answer it on your desktop.",s=this.encryptForEmit(i,{e1SuppressedPrompt:!0},d.EventType.NOTIFICATION,e);return s?(await this.appSyncClient.createEvent({sessionId:e,type:d.EventType.NOTIFICATION,source:d.EventSource.DESKTOP,content:s.content,metadata:s.metadata,...(0,d.raiseFieldsFromRecord)(t),notificationText:i,timestamp:(0,d.prepareEventTimestamp)({orderingKey:e}),isEncrypted:s.isEncrypted?!0:void 0}),n.info("E1: emitted suppressed-prompt badge carrier (mobileActionable=false)",{sessionId:e,promptId:t.promptId}),!0):!1}raiseSuppressedBadge(e,t){if(t){let s=`${e}::${t}`,r=this.e1ContentKeyIndex.get(s);if(r&&this.e1PromptRaises.has(r))return;r&&this.e1ContentKeyIndex.delete(s)}let i=this.newE1Raise(e,!1);t&&this.e1ContentKeyIndex.set(`${e}::${t}`,i.promptId),this.emitSuppressedPromptCarrier(e,i).catch(s=>{n.error("E1: failed to emit suppressed-prompt badge carrier",{sessionId:e,promptId:i.promptId,error:s instanceof Error?s.message:String(s)})})}snapshotOpenE1(e){return[...this.e1PromptRaises.values()].filter(t=>t.record.sessionId===e).map(t=>({record:{...t.record},...t.contentPlain!==void 0&&{contentPlain:t.contentPlain},...t.metadataPlain!==void 0&&{metadataPlain:t.metadataPlain}}))}parkRetirementOrphans(e){for(let t of this.snapshotOpenE1(e))this.e1RetirementOrphans.set(t.record.promptId,t)}async drainRetirementOrphans(e){if(this.e1RetirementOrphans.size!==0){n.info("E1 (\xA76a-4): re-homing parked retirement-orphan prompts onto replacement session",{replacementSessionId:e,count:this.e1RetirementOrphans.size});for(let[t,i]of[...this.e1RetirementOrphans]){let r=this.e1PromptRaises.get(t)??{record:{...i.record},...i.contentPlain!==void 0&&{contentPlain:i.contentPlain},...i.metadataPlain!==void 0&&{metadataPlain:i.metadataPlain}};if(r.record.sessionId=e,this.e1PromptRaises.set(t,r),!await this.reRaiseOneE1(e,r,{untilAck:!0}))break;this.e1RetirementOrphans.delete(t)}this.e1TtlRefreshTimer||this.startE1TtlRefresh()}}isReRaiseTargetCurrent(e){return!this.isStopping&&this.sessionState!==null&&this.sessionState.sessionId===e}async reRaiseOneE1(e,t,i){let s=t.record,r=s.mobileActionable&&t.contentPlain!==void 0,o=i?.untilAck??!1,l=4,a=4e3;for(let p=1;o||p<=l;p++){if(o&&!this.isReRaiseTargetCurrent(e))return this.e1NeedsReRaise.add(s.promptId),n.warn("E1: retirement re-raise aborted (stopping/superseded) \u2014 parked",{sessionId:e,promptId:s.promptId}),!1;try{if(r){let u=this.encryptForEmit(t.contentPlain,t.metadataPlain??{},d.EventType.INTERACTIVE_PROMPT,e);if(!u)return!1;await this.appSyncClient.createEvent({sessionId:e,type:d.EventType.INTERACTIVE_PROMPT,source:d.EventSource.DESKTOP,content:u.content,metadata:u.metadata,...(0,d.raiseFieldsFromRecord)(s),timestamp:(0,d.prepareEventTimestamp)({orderingKey:e}),...u.isEncrypted?{isEncrypted:!0}:{}})}else if(s.mobileActionable=!1,!await this.emitSuppressedPromptCarrier(e,s))return!1;return this.e1NeedsReRaise.delete(s.promptId),n.info("E1: re-raised prompt onto replacement session",{sessionId:e,promptId:s.promptId,actionable:r}),!0}catch(u){if(!o&&p===l)return this.e1NeedsReRaise.add(s.promptId),n.error("E1: re-raise unacked after backoff \u2014 parked for retry-until-ack",{sessionId:e,promptId:s.promptId,error:u instanceof Error?u.message:String(u)}),!1;if(o){let h=Date.now()+Math.min(250*2**(p-1),a);for(;Date.now()<h&&this.isReRaiseTargetCurrent(e);)await new Promise(m=>setTimeout(m,Math.min(50,h-Date.now())))}else await new Promise(h=>setTimeout(h,250*p))}}return!1}async drainPendingE1ReRaises(){if(this.e1NeedsReRaise.size!==0)for(let e of[...this.e1NeedsReRaise]){let t=this.e1PromptRaises.get(e);if(!t){this.e1NeedsReRaise.delete(e);continue}!this.sessionState||t.record.sessionId!==this.sessionState.sessionId||await this.reRaiseOneE1(t.record.sessionId,t)}}async refreshE1Ttls(){await this.drainPendingE1ReRaises();let e=this.sessionState?.sessionId;if(!e)return;let t=[...this.e1PromptRaises.values()].filter(i=>i.record.sessionId===e).map(i=>i.record.promptId);if(t.length!==0)try{let i=await this.appSyncClient.refreshOpenPromptTtl(t);for(let s of i){let r=this.e1PromptRaises.get(s);r&&r.record.sessionId===e&&await this.reRaiseOneE1(e,r)}}catch(i){n.warn("E1: TTL-refresh tick failed (non-fatal, retries next tick)",{error:i instanceof Error?i.message:String(i)})}}startE1TtlRefresh(){this.e1TtlRefreshTimer&&clearInterval(this.e1TtlRefreshTimer),this.e1TtlRefreshTimer=setInterval(()=>{this.refreshE1Ttls()},c.E1_TTL_REFRESH_MS)}stopE1TtlRefresh(){this.e1TtlRefreshTimer&&(clearInterval(this.e1TtlRefreshTimer),this.e1TtlRefreshTimer=null)}isExpectedSessionStateCurrent(e){return!this.isStopping&&this.sessionState===e&&!this.terminalInputBlockedStates.has(e)}sendSessionPinnedInput(e,t){if(!this.isExpectedSessionStateCurrent(e)||this.terminalInputBlockedStates.has(e))return Promise.resolve(!1);let i=this.terminalInputChain.then(async()=>!this.isExpectedSessionStateCurrent(e)||this.terminalInputBlockedStates.has(e)?!1:this.promptResponder.sendInput(e.sessionId,t));return this.terminalInputChain=i.then(()=>{},()=>{}),i}async handleEventFromHook(e){let{session_id:t,hook_event_name:i,type:s,content:r,metadata:o}=e;if(this.hooksActive=!0,n.info("[Hooks] Received event",{sessionId:t,hookEvent:i,type:s,contentLength:r?.length}),i==="SessionStart"){if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,await this.sessionWatcher.bindToSessionTranscript(o?.transcript_path,t),this.sessionState)n.info("[Hooks] SessionStart \u2014 launch session already exists, updating codexSessionId",{existingSessionId:this.sessionState.sessionId,codexSessionId:t}),this.sessionState.codexSessionId=t,this.sessionState.metadata={...this.sessionState.metadata,codexSessionId:t,cliVersion:o?.model||"unknown",modelProvider:o?.model||"unknown",launchSession:void 0},this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,metadata:this.sessionState.metadata}).catch(p=>n.warn("Failed to update session metadata",{error:p})),await this.startTmuxObserverWithBeacon("session_start_existing"),await this.ensureToolActivityStarted(t);else{let p={id:t,timestamp:new Date().toISOString(),cwd:o?.cwd||process.cwd(),originator:"hook",cli_version:o?.model||"unknown",instructions:null,source:o?.source||"startup",model_provider:o?.model||"unknown"};await this.ensureSessionStarted(p)}return}if(!this.sessionState){n.warn("[Hooks] Hook event for un-bootstrapped session \u2014 self-healing via session bootstrap (#638)",{hookEvent:i,sessionId:t});let p={id:t,timestamp:new Date().toISOString(),cwd:o?.cwd||process.cwd(),originator:"hook",cli_version:o?.model||"unknown",instructions:null,source:o?.source||"startup",model_provider:o?.model||"unknown"};if(await this.ensureSessionStarted(p),!this.sessionState){n.warn("[Hooks] Session still not initialized after self-heal, dropping event",{hook_event_name:i});return}}let l=this.sessionState,a=l.sessionId;if(s==="USER_PROMPT"&&r){let p=this.consumeRecentMobilePrompt(a,r);if(p){n.info("[Hooks] Skipping duplicate USER_PROMPT from mobile",{sessionId:a,matchType:p.matchType,originalLength:p.originalLength,echoLength:p.echoLength});return}}if(i==="PreToolUse"){n.debug("[Hooks] PreToolUse observed; AppSync emission suppressed",{toolName:o?.tool_name||"unknown",sessionId:a});return}if(i==="PermissionRequest"){await this.handlePermissionRequestHook(e,l);return}if(i==="PostToolUse"){if(this.toolActivity?.isActive()&&await this.toolActivity.observeCall({callId:o?.tool_use_id??o?.call_id??o?.callId,toolName:o?.tool_name,toolInput:o?.tool_input})!=="closed")return;let p=this.encryptForEmit(r,o,d.EventType.TOOL_USE,a);if(!p)return;let u=p.content,h=p.metadata,m=p.isEncrypted,g=o?.tool_use_id??o?.call_id??o?.callId,f=typeof g=="string"&&g.length>0&&!!this.sessionKey,y=f?this.getToolActivityLegacyRecorder(a):void 0;y&&f&&y.markLegacyInFlight(g);try{let w=await this.appSyncClient.createEvent({sessionId:a,type:d.EventType.TOOL_USE,source:d.EventSource.DESKTOP,content:u,metadata:h,isEncrypted:m,timestamp:(0,d.prepareEventTimestamp)({orderingKey:a})});y&&f&&((0,d.isPersistedEventResult)(w)?await y.finalizeLegacyOwned([g]):y.clearLegacyInFlight(g))}catch(w){throw y&&f&&y.clearLegacyInFlight(g),w}return}if(s==="ASSISTANT_RESPONSE"||s==="USER_PROMPT"){if(s==="ASSISTANT_RESPONSE"&&this.sessionWatcher.getBindSource()==="authoritative"&&this.sessionWatcher.getAuthoritativeSessionId()===t){n.debug("[Hooks] Suppressing Stop final \u2014 JSONL watcher authoritatively bound to this session (Bug #2)");return}s==="ASSISTANT_RESPONSE"&&n.info("[Hooks] Emitting Stop final as backstop \u2014 watcher not authoritatively bound",{bindSource:this.sessionWatcher.getBindSource()});let p=s==="ASSISTANT_RESPONSE"?d.EventType.ASSISTANT_RESPONSE:d.EventType.USER_PROMPT,u=this.encryptForEmit(r,void 0,p,a);if(!u)return;await this.appSyncClient.createEvent({sessionId:a,type:p,source:d.EventSource.DESKTOP,content:u.content,isEncrypted:u.isEncrypted,timestamp:(0,d.prepareEventTimestamp)({orderingKey:a})});return}}mapToolName(e){return{shell_command:"Bash",shell:"Bash",apply_patch:"Edit",create_file:"Write",read_file:"Read"}[e]||e}trackMobilePrompt(e,t){this.mobilePromptDeduper.track(e,t),n.debug("Tracking mobile prompt for USER_PROMPT echo deduplication",{sessionId:e,promptLength:t.trim().length})}forgetMobilePrompt(e,t){this.mobilePromptDeduper.forget(e,t)}consumeRecentMobilePrompt(e,t){return this.mobilePromptDeduper.consumeIfDuplicate(e,t)}setupEventHandlers(){this.sessionWatcher.on("session-started",async e=>{try{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState){n.info("[JSONL] Session already active, skipping",{currentSessionId:this.sessionState.sessionId,codexSessionId:e.id}),await this.ensureToolActivityStarted(e.id);return}await this.ensureSessionStarted(e)}catch(t){n.error("[JSONL] session-started handler failed (non-fatal) \u2014 next event retries",{codexSessionId:e?.id,error:String(t)})}}),this.sessionWatcher.on("log-entry",e=>{this.enqueueLogEntry(e)}),this.approvalDetector.on("approval-pending",async e=>{try{await this.handleApprovalPending(e)}catch(t){n.error("approval-pending handler failed (non-fatal)",{error:String(t)})}}),this.tmuxPaneObserver.on("prompt-candidate",async e=>{try{await this.handleTmuxPromptCandidate(e.snapshot)}catch(t){n.error("prompt-candidate handler failed (non-fatal)",{error:String(t)})}}),this.tmuxPaneObserver.on("observer-error",e=>{n.debug("Tmux pane observer error",{error:e})}),this.sessionWatcher.on("error",e=>{n.error("Session watcher error:",e)})}async ensureSessionStarted(e,t){if(this.isStopping||(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.isStopping)||this.sessionState)return;process.env[Z]==="1"&&await this.bindRecoveryBootstrapIdentity(e.id);let i=this.sessionBootstrapRetryAt-Date.now();if(i>0){n.warn("Session bootstrap is in retry backoff; hook will be retried later",{codexSessionId:e.id,retryDelayMs:i,failureCount:this.sessionBootstrapFailureCount});return}if(this.sessionStartedInitPromise){try{await this.sessionStartedInitPromise}catch{}return}let s=this.handleSessionStarted(e,t);this.sessionStartedInitPromise=s.catch(()=>{});try{await s}finally{this.sessionStartedInitPromise=null}}async handleSessionStarted(e,t){if(this.isStopping)return;let i=this.lifecycleGeneration;n.info("Handling new Codex session",{codexSessionId:e.id}),this.isInitializingSession=!0,this.bufferedLogEntries=[],this.sessionState&&await this.endActiveSession("new-codex-session-started");let s=process.env.CODEX_WORKING_DIRECTORY||e.cwd||process.cwd(),r=this.getOrCreateBootstrapSessionId(),o=this.appSyncClient.getCurrentUserId(),l={codexSessionId:e.id,cliVersion:e.cli_version,modelProvider:e.model_provider},a={sessionKey:null,sessionIsEncrypted:!0};try{let p={sessionId:r,userId:o,agentType:d.AgentType.CODEX,projectPath:s,metadata:l},u=await this.resumeOrCreateBootstrapSession(p);if(r=u.sessionId,!this.isLifecycleCurrent(i)){this.isInitializingSession=!1,await this.retireCancelledBootstrap(r,"session_started");return}this.sessionKey=u.sessionKey,this.sessionKeyGen=u.sessionKeyGen,this.sessionIsEncrypted=!!u.sessionKey,a={sessionKey:u.sessionKey,sessionIsEncrypted:!!u.sessionKey},await v("daemon_init_step_completed",{step:"session_resume_or_create",path:"session_started"})}catch(p){if(this.isInitializingSession=!1,!this.isLifecycleCurrent(i)){let u=this.authoritativeSessionIdFromError(p)??r;await this.retireCancelledBootstrap(u,"session_started_error");return}throw await v("daemon_init_step_failed",{step:"session_resume_or_create",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),p?.code==="ENCRYPTED_SESSION_NO_KEY"&&(this.sessionIsEncrypted=!0,this.sessionKey=null),this.bindBootstrapIdentityFromError(p),this.recordSessionBootstrapFailure(p,"session_started"),n.error("Failed to create/resume session:",p),p}try{this.sessionState={sessionId:r,userId:o,projectPath:s,cwd:e.cwd,createdAt:new Date,subscriptionActive:!1,metadata:l,encryptionSnapshot:a,codexSessionId:e.id,codexLogFile:this.sessionWatcher.getActiveLogFile()||void 0},this.clearSessionBootstrapFailure(),this.bootstrapSessionId=null,this.recoveryBootstrapOwnerBound=!1,await v("daemon_init_step_completed",{step:"session_state_set",path:"session_started"})}catch(p){await v("daemon_init_step_failed",{step:"session_state_set",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),n.error("Failed to set session state:",p)}await this.ensureToolActivityStarted(e.id);try{this.subscribeToMobileEvents(r)?await v("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"session_started"}):await v("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(p){await v("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),n.error("Failed to subscribe to mobile events:",p)}if(t)try{await t()}catch(p){n.error("E1: pre-heartbeat re-raise hook failed (non-fatal)",{sessionId:r,error:p instanceof Error?p.message:String(p)})}try{await this.drainRetirementOrphans(r)}catch(p){n.error("E1: retirement-orphan drain failed (non-fatal)",{sessionId:r,error:p instanceof Error?p.message:String(p)})}try{await this.appSyncClient.startHeartbeat(r)?await v("daemon_init_step_completed",{step:"heartbeat_start",path:"session_started"}):(await v("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:"InitialHeartbeatNotPersisted",error_message:"Backend did not confirm the initial heartbeat mutation"}),n.error("Initial session heartbeat was not persisted",{sessionId:r}))}catch(p){await v("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),n.error("Failed to start heartbeat:",p)}try{await this.subscribeToOnApplyUserDecision(r)}catch(p){n.error("Failed to subscribe to onApplyUserDecision (non-fatal)",{error:p})}this.startMobileEndWatcher(r);try{await this.flushBufferedLogEntries(),await v("daemon_init_step_completed",{step:"flush_buffered_entries",path:"session_started"})}catch(p){await v("daemon_init_step_failed",{step:"flush_buffered_entries",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),n.error("Failed to flush buffered log entries:",p),this.bufferedLogEntries=[]}await this.startTmuxObserverWithBeacon("session_started"),this.isInitializingSession=!1}getOrCreateBootstrapSessionId(){return this.bootstrapSessionId||(this.bootstrapSessionId=k.mintBackendSessionId()),this.bootstrapSessionId}async bindRecoveryBootstrapIdentity(e){if(!(process.env[Z]!=="1"||this.bootstrapSessionId||this.sessionState||!e))try{let t=await this.buildToolActivityIntegration().recordedBackendSessionId(e);if(!t){n.warn("Recovery daemon found no durable backend owner; a new session will be created",{rolloutId:e});return}if(!/^codex-[A-Za-z0-9_-]{1,180}$/.test(t)){n.warn("Recovery daemon ignored invalid durable backend owner",{rolloutId:e});return}this.bootstrapSessionId=t,this.recoveryBootstrapOwnerBound=!0,n.info("Recovery daemon reclaiming existing backend session",{rolloutId:e,sessionId:t})}catch(t){n.warn("Recovery daemon could not read the durable rollout owner; a new session will be created",{rolloutId:e,error:t instanceof Error?t.message:String(t)})}}isSessionIdReservedRejection(e){return(e instanceof Error?e.message:String(e)).includes("SESSION_ID_RESERVED")}async resumeOrCreateBootstrapSession(e){try{return await this.resumeBackendSession(e,this.appSyncClient,n)}catch(t){if(!this.recoveryBootstrapOwnerBound||!this.isSessionIdReservedRejection(t))throw t;return n.warn("Recovery discarded a permanently reserved pending create; retrying the durable rollout owner",{sessionId:e.sessionId}),this.resumeBackendSession(e,this.appSyncClient,n)}}startTmuxLifecycleMonitor(){if(this.tmuxLifecycleTimer)return;let e=process.env[D];e&&(this.tmuxLifecycleTimer=setInterval(()=>{this.checkTmuxLifecycle(e)},yt),this.tmuxLifecycleTimer.unref?.(),this.checkTmuxLifecycle(e))}async tmuxSessionExists(e){try{return await ft("tmux",["has-session","-t",e]),!0}catch{return!1}}async checkTmuxLifecycle(e){if(!(this.isStopping||this.tmuxLifecycleCheckInFlight)){this.tmuxLifecycleCheckInFlight=!0;try{if(await this.tmuxSessionExists(e)){this.tmuxLifecycleObservedAlive=!0;return}if(!this.tmuxLifecycleObservedAlive||this.isStopping)return;this.stopTmuxLifecycleMonitor(),n.info("Native Codex tmux session ended; stopping companion daemon",{tmuxSession:e}),this.stop().then(()=>process.exit(0),t=>{n.error("Failed to stop companion daemon after native session end",{error:t instanceof Error?t.message:String(t)}),process.exit(1)})}finally{this.tmuxLifecycleCheckInFlight=!1}}}stopTmuxLifecycleMonitor(){this.tmuxLifecycleTimer&&(clearInterval(this.tmuxLifecycleTimer),this.tmuxLifecycleTimer=null)}isLifecycleCurrent(e){return!this.isStopping&&this.lifecycleGeneration===e}authoritativeSessionIdFromError(e){let t=e?.authoritativeSessionId;return typeof t=="string"&&t.length>0?t:null}async retireCancelledBootstrap(e,t){this.appSyncClient.stopHeartbeat(e),this.appSyncClient.cleanupSubscription(e);try{await this.appSyncClient.updateSession({sessionId:e,status:d.SessionStatus.INACTIVE}),n.info("Cancelled bootstrap row marked INACTIVE",{sessionId:e,path:t})}catch(i){n.warn("Cancelled bootstrap row could not be marked INACTIVE",{sessionId:e,path:t,error:i instanceof Error?i.message:String(i)})}}bindBootstrapIdentityFromError(e){let t=e?.authoritativeSessionId;typeof t!="string"||t.length===0||(this.bootstrapSessionId=t,n.info("Retained authoritative backend identity from failed bootstrap",{sessionId:t}))}recoverRetiredBackendSession(e){if(this.retiredSessionRecoveryPromise)return this.retiredSessionRecoveryPromise;if(this.isStopping)return Promise.resolve();let t=(async()=>{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionStartedInitPromise&&await this.sessionStartedInitPromise,this.isStopping)return;let i=this.sessionState;if(!i||i.sessionId!==e)return;let s={id:i.codexSessionId||e,timestamp:new Date().toISOString(),cwd:i.cwd||i.projectPath,originator:"codevibe-retired-session-recovery",cli_version:String(i.metadata?.cliVersion??"unknown"),instructions:null,source:"codevibe",model_provider:String(i.metadata?.modelProvider??"unknown")};n.warn("Backend retired live Codex session; creating replacement row",{sessionId:e,codexSessionId:s.id}),this.parkRetirementOrphans(e),await this.endActiveSession("backend-generation-retired"),this.bootstrapSessionId=null,this.clearSessionBootstrapFailure(),await this.ensureSessionStarted(s)})();return this.retiredSessionRecoveryPromise=t.finally(()=>{this.retiredSessionRecoveryPromise=null}),this.retiredSessionRecoveryPromise}recordSessionBootstrapFailure(e,t){this.sessionBootstrapFailureCount+=1;let i=e instanceof Error?e.message:String(e),r=i.includes("SESSION_LIMIT_EXCEEDED")?6e4:Math.min(5e3*2**(this.sessionBootstrapFailureCount-1),6e4);this.sessionBootstrapRetryAt=Date.now()+r,n.warn("Session bootstrap retry scheduled",{path:t,requestedSessionId:this.bootstrapSessionId,failureCount:this.sessionBootstrapFailureCount,delayMs:r,error:i})}clearSessionBootstrapFailure(){this.sessionBootstrapFailureCount=0,this.sessionBootstrapRetryAt=0}async flushBufferedLogEntries(){if(this.bufferedLogEntries.length===0)return;let e=this.bufferedLogEntries;this.bufferedLogEntries=[],n.info("Flushing buffered log entries after session initialization",{count:e.length,sessionId:this.sessionState?.sessionId});let t=Promise.resolve();for(let i of e)t=this.enqueueLogEntry(i);await t.catch(()=>{})}enqueueLogEntry(e){let t=this.logEntryChain.then(()=>this.handleLogEntry(e));return this.logEntryChain=t.catch(i=>{n.error("[JSONL] log entry handler failed",{type:e.type,err:String(i)})}),t}async handleLogEntry(e){if(!this.sessionState){if(this.isInitializingSession){this.bufferedLogEntries.push(e),n.debug("Buffering log entry until session initialization completes",{type:e.type,bufferedCount:this.bufferedLogEntries.length});return}n.warn("Received log entry but no active session");return}let t=this.sessionState,i=t.sessionId,{sessionKey:s,sessionIsEncrypted:r}=t.encryptionSnapshot;if(e.type==="response_item"&&e.payload){let f=e.payload.type;if(f==="function_call"||f==="custom_tool_call")this.approvalDetector.onToolCallStart(e.payload.call_id,e.payload.name,e.payload.arguments||e.payload.input||"");else if(f==="function_call_output"||f==="custom_tool_call_output"){let y=this.approvalDetector.getPendingCalls().find(T=>T.callId===e.payload.call_id),w=y?this.buildApprovalDedupeKey(this.buildApprovalPromptContextFromPendingCall(y)):void 0;if(this.approvalDetector.onToolCallComplete(e.payload.call_id),await this.clearResolvedInteractivePrompt(e.payload.call_id,w),!this.isExpectedSessionStateCurrent(t))return}}let o=ue(e,i);if(!o)return;o.timestamp=(0,d.prepareEventTimestamp)({orderingKey:i,agentClock:e.timestamp});let l=e.payload?.type,a=!1;if(this.toolActivity?.isActive()&&o.type===d.EventType.TOOL_USE){let f=l==="function_call"||l==="custom_tool_call",y=l==="function_call_output"||l==="custom_tool_call_output";if(f&&typeof e.payload?.call_id=="string"){let w=this.sessionWatcher.getActiveLogFile();w&&this.toolActivity.bindTranscript(w);let T=await this.toolActivity.observeCall({callId:e.payload.call_id,toolName:o.metadata?.toolName??o.metadata?.tool_name,toolInput:o.metadata?.toolInput??o.metadata?.tool_input,ts:e.timestamp});if(!this.isExpectedSessionStateCurrent(t)||T!=="closed")return;a=!0}if(y)return}if(this.toolActivity?.isActive()&&(l==="user_message"||l==="agent_message")&&(await this.toolActivity.flush().catch(f=>n.warn("[tool-activity] codex boundary flush failed",{sessionId:i,err:String(f)})),!this.isExpectedSessionStateCurrent(t)))return;let p=l==="function_call"||l==="function_call_output",u=o.type===d.EventType.USER_PROMPT||o.type===d.EventType.ASSISTANT_RESPONSE||p&&(o.type===d.EventType.TOOL_USE||o.type===d.EventType.INTERACTIVE_PROMPT);if(!this.hooksActive&&u&&(await this.emitHooksCompatibilityModeNotice(t),!this.isExpectedSessionStateCurrent(t)))return;if(this.hooksActive){if(o.type===d.EventType.USER_PROMPT){n.debug("[JSONL] Skipping USER_PROMPT \u2014 hooks deliver it",{type:o.type});return}if(p&&(o.type===d.EventType.TOOL_USE||o.type===d.EventType.INTERACTIVE_PROMPT)&&!a){n.debug("[JSONL] Skipping function_call \u2014 hooks deliver this",{type:o.type,tool:e.payload?.name});return}}if(o.type===d.EventType.USER_PROMPT&&o.source===d.EventSource.DESKTOP){let f=this.consumeRecentMobilePrompt(i,o.content);if(f){n.info("[JSONL] Skipping duplicate USER_PROMPT from mobile",{sessionId:i,matchType:f.matchType,originalLength:f.originalLength,echoLength:f.echoLength});return}}if(this.sessionState!==t){n.warn("[JSONL] Dropping event from stale session generation (#638)",{sessionId:i,currentSessionId:this.sessionState?.sessionId});return}let h=e.payload?.call_id,m=o.type===d.EventType.TOOL_USE&&typeof h=="string"&&h.length>0&&!!s,g=m?this.getToolActivityLegacyRecorder(i):void 0;g&&m&&g.markLegacyInFlight(h);try{let f=(0,d.encryptForEmit)(s,r,o.content,o.metadata);if(!f){n.error("No session key for ENCRYPTED session \u2014 dropping JSONL event (fail-closed, #638)",{type:o.type,sessionId:i});return}o.content=f.content,o.metadata=f.metadata,f.isEncrypted&&(o.isEncrypted=!0,n.debug("Event encrypted",{type:o.type}));let y=await this.appSyncClient.createEvent(o);n.debug("Event synced to backend",{type:o.type,encrypted:f.isEncrypted}),g&&m&&((0,d.isPersistedEventResult)(y)?await g.finalizeLegacyOwned([h]):g.clearLegacyInFlight(h))}catch(f){g&&m&&g.clearLegacyInFlight(h),n.error("Failed to sync event:",f)}}async handlePermissionRequestHook(e,t){if(!this.isExpectedSessionStateCurrent(t))return;let i=e.metadata||{},s=typeof i.tool_name=="string"?i.tool_name:"Tool",r=i.tool_input,o=this.stringifyToolInput(r),l={toolName:s,toolInput:r,rawInput:o,filePath:this.extractFilePathFromToolInput(s,r,o),diff:s==="apply_patch"?o:void 0,hint:this.buildPermissionRequestHint(s,r,o)},a=this.buildToolDetailsForInteractivePrompt(l),p=a.tool_name||this.mapToolNameForApproval(s),u=a.tool_input||this.buildFallbackToolInput(l),h=!!(p&&u),m=await this.tryParsePermissionRequestPromptFromTmux(Le=>this.parsedPromptMatchesApprovalContext(Le,l));if(!this.isExpectedSessionStateCurrent(t)){n.warn("[Hooks] Dropping stale PermissionRequest after session generation changed",{sessionId:t.sessionId,currentSessionId:this.sessionState?.sessionId});return}let g=m?.parsedPrompt??null;if(!g){n.warn("[Hooks] Suppressing PermissionRequest mobile prompt because exact Codex options are unavailable",{sessionId:t.sessionId,toolName:s,hint:l.hint}),this.raiseSuppressedBadge(t.sessionId,this.buildApprovalDedupeKey({toolName:s,toolInput:r,filePath:l.filePath,rawInput:o,hint:l.hint}));return}let f=this.buildApprovalDedupeKey({toolName:s,toolInput:r,filePath:l.filePath,rawInput:o,hint:l.hint});if(f&&this.hasRecentlyResolvedApprovalDedupeKey(t.sessionId,f)){n.info("[Hooks] Skipping PermissionRequest prompt; same approval was already answered recently",{sessionId:t.sessionId,toolName:s,dedupeKey:f});return}let y=this.buildCodexPromptPresentation(g);if(!y){n.warn("[Hooks] Suppressing PermissionRequest mobile prompt because Codex option hotkeys are unavailable",{sessionId:t.sessionId,toolName:s,hint:l.hint}),this.raiseSuppressedBadge(t.sessionId,f);return}let w=this.buildPermissionPromptId(i,s,r,o),T=this.buildApprovalPromptContent(y.content,{toolName:p,toolInput:u,hint:l.hint,filePath:l.filePath}),O={promptId:w,kind:y.kind,options:y.options,submitMap:y.submitMap,promptText:T,createdAt:Date.now(),source:"permission_hook",dedupeKey:f,requiresFollowUpText:y.requiresFollowUpText},se={isApprovalHint:!0,toolName:s,toolInput:r,hint:l.hint,filePath:l.filePath,diff:l.diff,rawInput:o,tool_name:p,tool_input:u,has_details:h,options:y.options,instructions:y.instructions,prompt_source:g?"permission_hook_tmux":"permission_hook",permission_mode:i.permission_mode,turn_id:i.turn_id,dedupe_key:f};n.info("[Hooks] Sending PermissionRequest interactive prompt",{sessionId:t.sessionId,toolName:s,promptId:w,promptSource:se.prompt_source,dedupeKey:f}),await this.enqueueOrEmitInteractivePrompt({prompt:O,content:T,metadata:se,ownerState:t})}async emitHooksCompatibilityModeNotice(e){if(this.hooksCompatibilityNoticeSent||!this.isExpectedSessionStateCurrent(e))return;this.hooksCompatibilityNoticeSent=!0;let t="Codex hooks are not active. CodeVibe is using compatibility mode: mobile approvals still mirror the desktop prompt, but timeline events may be delayed or incomplete. Open Codex /hooks and trust/enable CodeVibe hooks for full fidelity.",i={compatibility_mode:!0,reason:"codex_hooks_inactive",action:"trust_enable_codevibe_hooks"};n.warn("Codex hooks inactive; running in compatibility mode",{sessionId:e.sessionId});let s=this.encryptForEmit(t,i,d.EventType.NOTIFICATION,e.sessionId);if(s)try{await this.appSyncClient.createEvent({sessionId:e.sessionId,type:d.EventType.NOTIFICATION,source:d.EventSource.DESKTOP,content:s.content,metadata:s.metadata,timestamp:(0,d.prepareEventTimestamp)({orderingKey:e.sessionId}),...s.isEncrypted?{isEncrypted:!0}:{}})}catch(r){n.warn("Failed to emit hooks compatibility mode notification",{error:r})}}async handleApprovalPending(e){let t=this.sessionState;if(!t)return;let i=this.buildApprovalDedupeKey(e);if(i&&this.hasRecentlyResolvedApprovalDedupeKey(t.sessionId,i)){n.info("Skipping heuristic approval prompt; same approval was already answered recently",{callId:e.callId,toolName:e.toolName,dedupeKey:i});return}if(i&&this.hasActiveOrQueuedPermissionHookPrompt(i)){this.mergeCallIdIntoPromptByDedupeKey(i,e.callId),n.info("Skipping heuristic approval prompt; PermissionRequest hook already emitted it",{callId:e.callId,toolName:e.toolName,dedupeKey:i});return}n.info("Sending approval pending interactive prompt",e);try{let s=await this.tryParseInteractivePromptFromTmux(),r=s?.parsedPrompt??null,o=this.buildToolDetailsForInteractivePrompt(e,s?.snapshot),l=o.tool_name||this.mapToolNameForApproval(e.toolName),a=o.tool_input||this.buildFallbackToolInput(e),p=!!(l&&a);if(!r){n.warn("Suppressing heuristic approval prompt because exact Codex options are unavailable",{callId:e.callId,toolName:e.toolName,hint:e.hint}),this.raiseSuppressedBadge(t.sessionId,i);return}if(!this.parsedPromptMatchesApprovalContext(r,e)){n.warn("Suppressing heuristic approval prompt because parsed tmux prompt does not match the active tool",{callId:e.callId,toolName:e.toolName,hint:e.hint,parsedPromptText:r.promptText}),this.raiseSuppressedBadge(t.sessionId,i);return}let u=this.buildCodexPromptPresentation(r);if(!u){n.warn("Suppressing heuristic approval prompt because Codex option hotkeys are unavailable",{callId:e.callId,toolName:e.toolName,hint:e.hint}),this.raiseSuppressedBadge(t.sessionId,i);return}let h=u.options,m=this.buildApprovalPromptContent(u.content,{toolName:l,toolInput:a,hint:e.hint,filePath:e.filePath}),g={promptId:e.callId,callId:e.callId,kind:u.kind,options:h,submitMap:u.submitMap,promptText:u.promptText,createdAt:Date.now(),source:r?"tmux":"heuristic",dedupeKey:i,requiresFollowUpText:u.requiresFollowUpText},f={isApprovalHint:!0,toolName:e.toolName,toolInput:e.toolInput,hint:e.hint,callId:e.callId,filePath:e.filePath,diff:e.diff,rawInput:e.rawInput,tool_name:l,tool_input:a,has_details:p,options:h,instructions:u.instructions,prompt_source:r?"tmux":"heuristic",dedupe_key:i};n.debug("Interactive prompt (pre-encryption)",{sessionId:t.sessionId,callId:e.callId,contentPreview:m.substring(0,200),toolDetails:o,metadata:f}),await this.enqueueOrEmitInteractivePrompt({prompt:g,content:m,metadata:f,ownerState:t})}catch(s){n.error("Failed to send approval interactive prompt:",s)}}async handleTmuxPromptCandidate(e){let t=this.sessionState;if(!t){this.tmuxPaneObserver.resetLastPromptHash();return}let i=(0,C.parseInteractivePrompt)(e);if(!i){this.raiseSuppressedBadge(t.sessionId,null);return}let s=this.buildCodexPromptPresentation(i);if(!s){n.warn("Skipping tmux-detected prompt because Codex option hotkeys are unavailable",{parsedPromptText:i.promptText}),this.raiseSuppressedBadge(t.sessionId,null);return}let r=this.getMostRecentPendingToolCall();if(!r){if(await new Promise(O=>setTimeout(O,500)),!this.isExpectedSessionStateCurrent(t)){n.warn("Dropping tmux prompt candidate after session generation changed",{sessionId:t.sessionId,currentSessionId:this.sessionState?.sessionId});return}r=this.getMostRecentPendingToolCall()}let o=r?this.buildApprovalPromptContextFromPendingCall(r):null;if(o&&!this.parsedPromptMatchesApprovalContext(i,o)){n.warn("Skipping tmux-detected prompt because parsed prompt does not match pending tool call",{callId:r?.callId,toolName:r?.name,parsedPromptText:i.promptText}),this.raiseSuppressedBadge(t.sessionId,null);return}let l=o?null:this.buildApprovalPromptContextFromParsedPrompt(i),a=o||l;if(!a){n.warn("Skipping tmux-detected prompt because no tool context could be derived from the parsed prompt",{parsedPromptText:i.promptText}),this.raiseSuppressedBadge(t.sessionId,null);return}let p=a?this.buildApprovalDedupeKey(a):void 0;if(p&&this.hasRecentlyResolvedApprovalDedupeKey(t.sessionId,p)){n.info("Skipping tmux-detected prompt; same approval was already answered recently",{promptText:i.promptText,dedupeKey:p});return}if(p&&this.hasActiveOrQueuedPermissionHookPrompt(p)){r?.callId&&this.mergeCallIdIntoPromptByDedupeKey(p,r.callId),n.info("Skipping tmux-detected prompt; PermissionRequest hook already emitted it",{promptText:i.promptText,dedupeKey:p});return}let u=a?this.buildToolDetailsForInteractivePrompt(a,e):{},h=u.tool_name||this.mapToolNameForApproval(r?.name),m=u.tool_input||(a?this.buildFallbackToolInput(a):void 0),g=!!(h&&m),y={promptId:r?.callId||(0,Fe.v4)(),callId:r?.callId,kind:s.kind,options:s.options,submitMap:s.submitMap,promptText:s.promptText,createdAt:Date.now(),source:"tmux",dedupeKey:p,requiresFollowUpText:s.requiresFollowUpText},w={options:s.options,instructions:s.instructions,prompt_source:"tmux_live",tool_name:h,tool_input:m,has_details:g,dedupe_key:p},T=this.buildApprovalPromptContent(s.content,{toolName:h,toolInput:m,hint:a?.hint,filePath:a?.filePath});try{await this.enqueueOrEmitInteractivePrompt({prompt:y,content:T,metadata:w,ownerState:t})&&n.info("Sent tmux-detected interactive prompt",{sessionId:t.sessionId,promptText:i.promptText,kind:i.kind})}catch(O){n.error("Failed to send tmux-detected interactive prompt",{error:O})}}async enqueueOrEmitInteractivePrompt(e){if(!this.isExpectedSessionStateCurrent(e.ownerState))return n.warn("Dropping interactive prompt from stale session generation",{sessionId:e.ownerState.sessionId,currentSessionId:this.sessionState?.sessionId,source:e.prompt.source}),!1;if(e.prompt.dedupeKey&&this.hasRecentlyResolvedApprovalDedupeKey(e.ownerState.sessionId,e.prompt.dedupeKey))return n.debug("Skipping interactive prompt emission; same approval was already answered recently",{source:e.prompt.source,callId:e.prompt.callId,dedupeKey:e.prompt.dedupeKey}),!1;let t=this.pendingInteractivePrompt;if(!t){this.pendingInteractivePrompt=e.prompt;try{return await this.emitInteractivePromptEvent(e),!0}catch(i){throw this.pendingInteractivePrompt?.promptId===e.prompt.promptId&&(this.pendingInteractivePrompt=null),i}}return this.isSameInteractivePrompt(t,e.prompt)?(!t.callId&&e.prompt.callId&&(t.callId=e.prompt.callId,n.debug("Merged callId into existing interactive prompt",{source:t.source,callId:e.prompt.callId,promptText:t.promptText})),n.debug("Skipping duplicate interactive prompt emission",{existingSource:t.source,candidateSource:e.prompt.source,existingCallId:t.callId,candidateCallId:e.prompt.callId,promptText:e.prompt.promptText}),!1):this.queuedInteractivePrompts.some(i=>this.isSameInteractivePrompt(i.prompt,e.prompt))?(n.debug("Skipping duplicate queued interactive prompt",{candidateSource:e.prompt.source,candidateCallId:e.prompt.callId,promptText:e.prompt.promptText}),!1):(this.queuedInteractivePrompts.push(e),n.info("Queued interactive prompt behind active prompt",{activeCallId:t.callId,queuedCallId:e.prompt.callId,queueLength:this.queuedInteractivePrompts.length}),!1)}async emitInteractivePromptEvent(e){if(!this.isExpectedSessionStateCurrent(e.ownerState))return;let t=e.ownerState.sessionId,i=this.e1PromptRaises.get(e.prompt.promptId),s=i?i.record:this.newE1Raise(t,!0);e.prompt.promptId=s.promptId,e.prompt.dedupeKey&&this.e1ContentKeyIndex.set(`${t}::${e.prompt.dedupeKey}`,s.promptId),this.stashE1RaiseContent(s.promptId,e.content,e.metadata??{});let r=this.encryptForEmit(e.content,e.metadata,d.EventType.INTERACTIVE_PROMPT,t);r&&await this.appSyncClient.createEvent({sessionId:t,type:d.EventType.INTERACTIVE_PROMPT,source:d.EventSource.DESKTOP,content:r.content,metadata:r.metadata,...(0,d.raiseFieldsFromRecord)(s),timestamp:(0,d.prepareEventTimestamp)({orderingKey:t}),...r.isEncrypted?{isEncrypted:!0}:{}})}async emitNextQueuedInteractivePrompt(){if(this.pendingInteractivePrompt||this.queuedInteractivePrompts.length===0)return;let e=this.queuedInteractivePrompts.shift();if(e){if(!this.isExpectedSessionStateCurrent(e.ownerState)){n.warn("Discarding queued prompt from stale session generation",{sessionId:e.ownerState.sessionId,currentSessionId:this.sessionState?.sessionId}),await this.emitNextQueuedInteractivePrompt();return}this.pendingInteractivePrompt=e.prompt;try{await this.emitInteractivePromptEvent(e),n.info("Emitted next queued interactive prompt",{callId:e.prompt.callId,queueLength:this.queuedInteractivePrompts.length})}catch(t){this.pendingInteractivePrompt=null,n.error("Failed to emit queued interactive prompt",{error:t}),await this.emitNextQueuedInteractivePrompt()}}}removeQueuedInteractivePromptByCallId(e){let t=this.queuedInteractivePrompts.length,i=this.queuedInteractivePrompts.filter(s=>s.prompt.callId===e);for(let s of i)this.rememberResolvedApprovalDedupeKey(s.ownerState.sessionId,s.prompt.dedupeKey);this.queuedInteractivePrompts=this.queuedInteractivePrompts.filter(s=>s.prompt.callId!==e),this.queuedInteractivePrompts.length!==t&&n.debug("Removed resolved tool call from interactive prompt queue",{callId:e,removed:t-this.queuedInteractivePrompts.length})}async clearResolvedInteractivePrompt(e,t){let i=this.pendingInteractivePrompt;if(i&&(i.callId===e||t!==void 0&&i.dedupeKey===t)){this.rememberResolvedApprovalDedupeKey(this.sessionState?.sessionId,i.dedupeKey),this.pendingInteractivePrompt=null,await this.emitNextQueuedInteractivePrompt();return}this.removeQueuedInteractivePromptByCallId(e),t!==void 0&&this.removeQueuedInteractivePromptByDedupeKey(t)}removeQueuedInteractivePromptByDedupeKey(e){let t=this.queuedInteractivePrompts.length,i=this.queuedInteractivePrompts.filter(s=>s.prompt.dedupeKey===e);for(let s of i)this.rememberResolvedApprovalDedupeKey(s.ownerState.sessionId,s.prompt.dedupeKey);this.queuedInteractivePrompts=this.queuedInteractivePrompts.filter(s=>s.prompt.dedupeKey!==e),this.queuedInteractivePrompts.length!==t&&n.debug("Removed resolved deduped tool call from interactive prompt queue",{dedupeKey:e,removed:t-this.queuedInteractivePrompts.length})}mergeCallIdIntoPromptByDedupeKey(e,t){let i=this.pendingInteractivePrompt;if(i?.dedupeKey===e&&!i.callId){i.callId=t,n.debug("Merged callId into active deduped interactive prompt",{source:i.source,callId:t,dedupeKey:e});return}let s=this.queuedInteractivePrompts.find(r=>r.prompt.dedupeKey===e&&!r.prompt.callId);s&&(s.prompt.callId=t,n.debug("Merged callId into queued deduped interactive prompt",{source:s.prompt.source,callId:t,dedupeKey:e}))}isSameInteractivePrompt(e,t){return Date.now()-e.createdAt>vt?!1:e.callId&&t.callId?e.callId===t.callId:e.dedupeKey&&t.dedupeKey?e.dedupeKey===t.dedupeKey:e.kind===t.kind&&this.normalizePromptDedupeText(e.promptText)===this.normalizePromptDedupeText(t.promptText)}normalizePromptDedupeText(e){return e.replace(/\s+/g," ").trim().toLowerCase()}async startTmuxObserver(){let e=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!e)return n.debug("Skipping tmux pane observer start - no tmux session in environment"),!0;try{return await this.tmuxPaneObserver.start(e),!0}catch(t){return n.warn("Failed to start tmux pane observer",{tmuxSession:e,error:t}),!1}}async startTmuxObserverWithBeacon(e){try{await this.startTmuxObserver()?await v("daemon_init_step_completed",{step:"tmux_observer_start",path:e}):await v("daemon_init_step_failed",{step:"tmux_observer_start",path:e,error_class:"TmuxObserverStartFailed",error_message:"tmuxPaneObserver.start threw (see plugin log)"})}catch(t){await v("daemon_init_step_failed",{step:"tmux_observer_start",path:e,error_class:t?.name||"Error",error_message:t?.message||String(t)}),n.error("Failed to start tmux observer:",t)}}async tryParseInteractivePromptFromTmux(){try{let e=await this.tmuxPaneObserver.captureSnapshot(),t=(0,C.parseInteractivePrompt)(e);return n.debug("tmux prompt parse result",{parsed:!!t,kind:t?.kind,promptText:t?.promptText,snapshotPreview:this.summarizePromptSnapshot(e)}),{parsedPrompt:t,snapshot:e}}catch(e){return n.debug("tmux prompt parsing unavailable",{error:e}),null}}async tryParsePermissionRequestPromptFromTmux(e){let t=await this.tryParseInteractivePromptFromTmux();if(t?.parsedPrompt&&(!e||e(t.parsedPrompt,t.snapshot)))return t;t?.parsedPrompt&&n.warn("Ignoring parsed PermissionRequest prompt because it does not match the active tool",{promptText:t.parsedPrompt.promptText}),await new Promise(s=>setTimeout(s,250));let i=await this.tryParseInteractivePromptFromTmux();return i?.parsedPrompt&&(!e||e(i.parsedPrompt,i.snapshot))?i:(i?.parsedPrompt&&n.warn("Ignoring retried PermissionRequest prompt because it does not match the active tool",{promptText:i.parsedPrompt.promptText}),i?.snapshot||t?.snapshot?{parsedPrompt:null,snapshot:i?.snapshot||t?.snapshot||""}:null)}buildPromptPresentation(e){return e?{content:e.promptText,promptText:e.promptText,kind:e.kind,options:e.options,submitMap:e.submitMap,instructions:this.buildPromptInstructions(e),requiresFollowUpText:e.requiresFollowUpText}:{content:"Codex is waiting for approval.",promptText:"Codex is waiting for approval.",kind:"yes_no",options:[{number:"1",text:'Yes (sends "y")'},{number:"2",text:'No, tell Codex what to change (sends "n <instructions>")'}],submitMap:{1:"y",2:"n"},instructions:"Reply with 1 to approve, or 2 followed by what to change",requiresFollowUpText:!0}}buildCodexPromptPresentation(e){let t=this.buildPromptPresentation(e),i=this.buildSubmitMapFromCodexOptionHotkeys(t.options);return i?{...t,submitMap:i,instructions:this.buildCodexPermissionInstructions(t.options),requiresFollowUpText:this.optionsRequireFollowUpText(t.options)}:null}buildSubmitMapFromCodexOptionHotkeys(e){let t={};for(let i of e){let s=i.text.match(/\(([^)]+)\)\s*$/)?.[1]?.trim().toLowerCase();if(!s||!bt.test(s))return null;s==="esc"||s==="escape"?t[i.number]=F:t[i.number]=s}return t}buildCodexPermissionInstructions(e){let t=e.find(o=>/\((?:y|yes)\)\s*$/i.test(o.text)),i=e.find(o=>/\(p\)\s*$/i.test(o.text)),s=e.find(o=>/\((?:esc|escape)\)\s*$/i.test(o.text)),r=[];return t&&r.push(`${t.number} to approve`),i&&r.push(`${i.number} to persist the desktop allow rule`),s&&r.push(`${s.number} followed by what to change`),r.length>0?`Reply with ${r.join(", ")}`:"Reply with the number of the option you want"}optionsRequireFollowUpText(e){return e.some(t=>/what to (?:do differently|change)|instructions/i.test(t.text))}getMostRecentPendingToolCall(){let e=this.approvalDetector.getPendingCalls();return e.length===0?null:e.reduce((t,i)=>i.timestamp>t.timestamp?i:t)}hasActiveOrQueuedPermissionHookPrompt(e){let t=this.pendingInteractivePrompt;return t?.source==="permission_hook"&&t.dedupeKey===e?!0:this.queuedInteractivePrompts.some(i=>i.prompt.source==="permission_hook"&&i.prompt.dedupeKey===e)}hasRecentlyResolvedApprovalDedupeKey(e,t){return e?(this.pruneResolvedApprovalDedupeKeys(),this.resolvedApprovalDedupeKeys.has(`${e}::${t}`)):!1}rememberResolvedApprovalDedupeKey(e,t){!e||!t||(this.pruneResolvedApprovalDedupeKeys(),this.resolvedApprovalDedupeKeys.set(`${e}::${t}`,Date.now()))}pruneResolvedApprovalDedupeKeys(){let e=Date.now()-St;for(let[t,i]of this.resolvedApprovalDedupeKeys.entries())i<e&&this.resolvedApprovalDedupeKeys.delete(t)}buildApprovalDedupeKey(e){let t=e.toolName||"Tool",i=this.firstString(e.toolInput?.command,e.toolInput?.cmd,e.rawInput);if(i)return`command:${this.hashDedupeValue(`${this.mapToolNameForApproval(t)||t}:${i.trim()}`)}`;let s=this.firstString(e.filePath,e.toolInput?.file_path,e.toolInput?.path,e.toolInput?.filePath);if(s)return`file:${this.hashDedupeValue(`${t}:${s}`)}`;let r=this.firstString(e.hint);if(r)return`hint:${this.hashDedupeValue(`${t}:${r}`)}`}hashDedupeValue(e){return ee.createHash("sha256").update(e.replace(/\s+/g," ").trim().toLowerCase()).digest("hex").slice(0,16)}buildPermissionPromptId(e,t,i,s){let r=typeof e.turn_id=="string"&&e.turn_id.trim().length>0?e.turn_id.trim():void 0,o=ee.createHash("sha256").update(`${t}:${s||this.stringifyToolInput(i)}`).digest("hex").slice(0,12);return`permission-${r||"turn"}-${o}`}buildPermissionRequestHint(e,t,i){let s=this.firstString(t?.command,t?.cmd);if(s)return`Command: ${this.truncateApprovalDetail(s,80)}`;let r=this.extractFilePathFromToolInput(e,t,i);return r?`File: ${r}`:`Tool: ${this.mapToolNameForApproval(e)||e}`}extractFilePathFromToolInput(e,t,i){let s=this.firstString(t?.file_path,t?.path,t?.filePath);if(s)return s;if(e==="apply_patch"&&i){let r=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(r)return r[1].trim()}}stringifyToolInput(e){if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}}buildApprovalPromptContextFromPendingCall(e){return{toolName:e.name,filePath:e.filePath,diff:e.diff,toolInput:e.parsedInput,rawInput:e.input,hint:e.filePath?`File: ${e.filePath}`:`Tool: ${this.mapToolNameForApproval(e.name)||e.name}`}}buildApprovalPromptContextFromParsedPrompt(e){let t=this.extractShellCommandFromPromptText(e.promptText);return t?{toolName:"Bash",toolInput:{command:t},rawInput:t,hint:`Command: ${this.truncateApprovalDetail(t,80)}`}:null}parsedPromptMatchesApprovalContext(e,t){let i=this.firstString(t.toolInput?.command,t.toolInput?.cmd);if(i){let r=ie(e.promptText);if(!r||r.length===0)return!1;let o=this.normalizeApprovalCommand(i);return this.normalizeApprovalCommand(r.join(" "))===o||r.length>1&&this.normalizeApprovalCommand(r.join(""))===o}let s=this.firstString(t.filePath,t.toolInput?.file_path,t.toolInput?.path,t.toolInput?.filePath);return s?e.promptText.includes(s):!1}normalizeApprovalCommand(e){return e.replace(/\s+/g," ").trim()}extractShellCommandFromPromptText(e){return Me(e)}buildPromptInstructions(e){return e.kind==="yes_no"&&e.requiresFollowUpText?"Reply with 1 to approve, or 2 followed by what to change":e.kind==="yes_no"?"Reply with 1 for yes or 2 for no":e.kind==="numbered"?"Reply with the number of the option you want":"Reply with your response"}buildApprovalPromptContent(e,t){let i=e.trim(),s=i==="Codex is waiting for approval.",r=/^\$\s+/.test(i),o=t.toolName?`${t.toolName} requires approval.`:"Codex is waiting for approval.",l=[s||r||!i?o:i],a=typeof t.toolInput?.command=="string"?t.toolInput.command.trim():void 0;if(a&&!l.join(`
|
|
14
|
+
`).includes(a))return l.push("Command:",this.truncateApprovalDetail(a,240)),l.join(`
|
|
15
|
+
`);let p=t.filePath||t.toolInput?.file_path;return typeof p=="string"&&p.length>0&&!l.join(`
|
|
16
|
+
`).includes(p)?(l.push(`File: ${p}`),l.join(`
|
|
17
|
+
`)):(t.hint&&!l.join(`
|
|
18
|
+
`).includes(t.hint)&&l.push(t.hint),l.join(`
|
|
19
19
|
`))}truncateApprovalDetail(e,t){return e.length>t?`${e.slice(0,t-3)}...`:e}summarizePromptSnapshot(e){return e.split(`
|
|
20
20
|
`).map(t=>t.trimEnd()).filter(t=>t.length>0).slice(-12).map(t=>t.slice(0,160)).join(`
|
|
21
|
-
`)}translatePromptResponse(e){let t=this.pendingInteractivePrompt;if(!t)return{primaryInput:e};let s=e.trim().match(/^(\d+)(?:[,.:;\-\s]+([\s\S]+))?$/);if(!s)return{primaryInput:e};let
|
|
22
|
-
`)){let
|
|
21
|
+
`)}translatePromptResponse(e){let t=this.pendingInteractivePrompt;if(!t)return{primaryInput:e};let s=e.trim().match(/^(\d+)(?:[,.:;\-\s]+([\s\S]+))?$/);if(!s)return{primaryInput:e};let r=s[1],o=s[2]?.trim(),l=t.submitMap[r];return l?t.requiresFollowUpText&&o?{primaryInput:l,followUpInput:o}:{primaryInput:l}:{primaryInput:e}}getEventPromptId(e){let t=e.promptId;return typeof t=="string"&&t.trim().length>0?t.trim():null}isApprovalResponseLike(e){let t=e.trim().toLowerCase();return/^(?:\d+|y|yes|n|no)(?:[\s,.:;-].*)?$/.test(t)}async emitRejectedPromptResponseNotification(e,t,i){if(!this.isExpectedSessionStateCurrent(i))return;let s=i.sessionId,r="Response ignored because it was not tied to the current prompt. Please reply to the latest prompt again.",o={prompt_response_rejected:!0,reason:e,eventId:t.eventId,eventPromptId:this.getEventPromptId(t),activePromptId:this.pendingInteractivePrompt?.promptId},l=this.encryptForEmit(r,o,d.EventType.NOTIFICATION,s);if(l)try{await this.appSyncClient.createEvent({sessionId:s,type:d.EventType.NOTIFICATION,source:d.EventSource.DESKTOP,content:l.content,metadata:l.metadata,timestamp:(0,d.prepareEventTimestamp)({orderingKey:s}),...l.isEncrypted?{isEncrypted:!0}:{}})}catch(a){n.warn("Failed to emit rejected prompt response notification",{reason:e,error:a})}}buildToolDetailsForInteractivePrompt(e,t){let i=e.toolName,s=e.toolInput&&typeof e.toolInput=="object"?e.toolInput:void 0;if(i==="apply_patch"){let o=e.diff||e.rawInput;if(o){let{oldString:l,newString:a,oldStartLine:p,newStartLine:u}=this.extractOldNewFromPatch(o),h=t?this.extractDiffLineAnchorsFromSnapshot(t):{};return{tool_name:"Edit",tool_input:{file_path:e.filePath,content:o,diff:e.diff,raw_patch:e.rawInput,old_string:l,new_string:a,old_start_line:p??h.oldStartLine,new_start_line:u??h.newStartLine}}}}if(i==="exec_command"||i==="shell_command"||i==="shell"||i==="Bash"){let o=this.firstString(s?.command,s?.cmd,e.rawInput,e.hint);if(o)return{tool_name:"Bash",tool_input:{command:o,output:s?.output}}}let r={};return e.filePath&&(r.file_path=e.filePath),e.diff&&(r.diff=e.diff),e.rawInput&&(r.raw_input=e.rawInput),Object.keys(r).length>0?{tool_name:i||"Tool",tool_input:r}:{}}firstString(...e){for(let t of e)if(typeof t=="string"&&t.trim().length>0)return t}buildFallbackToolInput(e){let t={};return e.filePath&&(t.file_path=e.filePath),e.diff&&(t.diff=e.diff),e.rawInput&&(t.raw_input=e.rawInput),e.toolInput&&typeof e.toolInput=="object"&&(t.parsed_input=e.toolInput),Object.keys(t).length>0?t:void 0}mapToolNameForApproval(e){return e?{exec_command:"Bash",Bash:"Bash",apply_patch:"Edit",shell_command:"Bash",shell:"Bash",Edit:"Edit",Write:"Write"}[e]||e:void 0}extractOldNewFromPatch(e){let t=[],i=[],s=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/,r=0,o=0,l=0,a,p;for(let u of e.split(`
|
|
22
|
+
`)){let h=u.match(s);if(h){r+=1,o=Number.parseInt(h[1],10),l=Number.parseInt(h[2],10);continue}if(!(u.startsWith("***")||u.startsWith("---")||u.startsWith("+++")||u.startsWith("*** End Patch"))){if(u.startsWith("-"))a===void 0&&(a=o),t.push(u.slice(1)),o+=1;else if(u.startsWith("+"))p===void 0&&(p=l),i.push(u.slice(1)),l+=1;else if(u.startsWith(" ")){let m=u.slice(1);t.push(m),i.push(m),o+=1,l+=1}}}return{oldString:t.join(`
|
|
23
23
|
`),newString:i.join(`
|
|
24
|
-
`),oldStartLine:
|
|
25
|
-
`)){let o=
|
|
26
|
-
`);
|
|
24
|
+
`),oldStartLine:r===1?a:void 0,newStartLine:r===1?p:void 0}}extractDiffLineAnchorsFromSnapshot(e){let t=(0,C.normalizeSnapshot)(e),i,s;for(let r of t.split(`
|
|
25
|
+
`)){let o=r.match(/^\s*(\d+)\s+(.*)$/);if(!o)continue;let l=Number.parseInt(o[1],10),a=o[2];if(Number.isFinite(l)){if(a.startsWith("-")){i??=l;continue}if(a.startsWith("+")){s??=l;continue}i??=l,s??=l}}return n.debug("Recovered diff line anchors from tmux snapshot",{oldStartLine:i,newStartLine:s,snapshotPreview:this.summarizePromptSnapshot(e)}),{oldStartLine:i,newStartLine:s}}subscribeToMobileEvents(e){let t=this.sessionState;if(!t||t.sessionId!==e)return n.warn("Refusing mobile subscription without matching session generation",{sessionId:e,currentSessionId:t?.sessionId}),!1;if(this.subscribedSessionId===e&&this.subscribedSessionState===t)return n.info("Already subscribed to mobile events, skipping",{sessionId:e}),!0;if(n.info("Subscribing to mobile events",{sessionId:e}),this.unsubscribe){try{this.unsubscribe()}catch(i){n.warn("Error cleaning up previous subscription (non-fatal)",{error:i})}this.subscribedSessionId=null,this.subscribedSessionState=null}try{this.unsubscribe=this.appSyncClient.subscribeToEvents(e,async i=>{await this.handleMobileEvent(i,t)},i=>{n.error("Subscription error:",i)},{onSessionRetired:()=>this.recoverRetiredBackendSession(e)}),this.subscribedSessionId=e,this.subscribedSessionState=t}catch(i){return n.error("Failed to subscribe to mobile events (non-fatal)",{sessionId:e,error:i}),!1}return this.isExpectedSessionStateCurrent(t)&&(t.subscriptionActive=!0),n.info("Subscribed to mobile events"),!0}async ensureOrchestrationClient(e){let{OrchestrationClient:t}=await import("@quantiya/quorum-core"),i=await d.keychainManager.getTokens((0,d.getEnvironment)());if(!i?.idToken)throw new Error("No Cognito ID token available \u2014 plugin must be logged in");let s=(0,d.getConfig)(),r=this.sessionKey??Buffer.alloc(32).toString("base64"),o=require("ws");return await t.connect({appsyncUrl:s.aws.appsyncUrl,cognitoIdToken:i.idToken,tokenProvider:async()=>(await d.keychainManager.getTokens((0,d.getEnvironment)()))?.idToken??i.idToken,sessionId:e,sessionKeyB64:r,webSocketFactory:((a,p)=>new o(a,p))})}async subscribeToOnApplyUserDecision(e){if(this.userDecisionUnsubscribe){try{this.userDecisionUnsubscribe()}catch(t){n.warn("Error invoking previous onApplyUserDecision unsubscribe (non-fatal)",{error:t})}this.userDecisionUnsubscribe=null}if(this.orchestrationClient){try{await this.orchestrationClient.destroy()}catch(t){n.warn("Error destroying previous OrchestrationClient (non-fatal)",{error:t})}this.orchestrationClient=null}try{let t=await this.ensureOrchestrationClient(e);this.orchestrationClient=t;let i=await t.onApplyUserDecision(s=>{this.handleApplyUserDecisionEvent(s)});return this.userDecisionUnsubscribe=i,n.info("[v1-bridge] Subscribed to onApplyUserDecision via OrchestrationClient",{sessionId:e}),!0}catch(t){if(n.error("Failed to subscribe to onApplyUserDecision (non-fatal)",{sessionId:e,error:t}),this.orchestrationClient){try{await this.orchestrationClient.destroy()}catch{}this.orchestrationClient=null}return!1}}handleApplyUserDecisionEvent(e){let{gateId:t,decision:i,sessionId:s,taskId:r}=e;if(this.v1Bridge.dispatch(e)==="self_echo"){n.debug("[v1-bridge] Self-origin decision echo absorbed",{gateId:t,decision:i,sessionId:s,taskId:r});return}n.info("[v1-bridge] cross-device decision recorded",{gateId:t,decision:i,sessionId:s,taskId:r});let l=String(i).toUpperCase();this.emitOrchestrationBanner(l)}async emitOrchestrationBanner(e){let t=process.env[D];if(!t){n.warn("[v1-bridge] No tmux session set; cannot emit cross-device banner",{expectedEnv:D});return}let s=ke(e).replace(/"/g,'\\"'),r=`tmux display-message -d 8000 -t "${t}" "${s}"`;try{await Ne(r),n.info("[v1-bridge] Cross-device decision banner emitted",{decision:e})}catch(o){n.warn("[v1-bridge] tmux display-message failed (non-fatal)",{error:o instanceof Error?o.message:String(o)})}}async originateUserDecision(e){this.v1Bridge.markOriginated(e.gateId);let t=this.sessionState?.sessionId;if(!t)throw this.v1Bridge.clearOriginated(e.gateId),new Error("No active session \u2014 cannot originate user decision");let i=this.orchestrationClient,s=!1;i||(i=await this.ensureOrchestrationClient(t),s=!0);try{await i.applyUserDecision(e),n.info("[v1-bridge] originated user decision",{gateId:e.gateId,decision:e.decision,sessionId:t})}catch(r){throw this.v1Bridge.clearOriginated(e.gateId),n.error("[v1-bridge] applyUserDecision failed (rolled back originator marker)",{gateId:e.gateId,decision:e.decision,error:r instanceof Error?r.message:String(r)}),r}finally{if(s&&i)try{await i.destroy()}catch{}}}_v1BridgeStateForTest(){return this.v1Bridge}_v1BridgeHandleEventForTest(e){this.handleApplyUserDecisionEvent(e)}async downloadAttachment(e,t,i,s){try{let r=e.isEncrypted??s??!1;n.info("Downloading attachment",{id:e.id,type:e.type,filename:e.filename,s3Key:e.s3Key,attachmentIsEncrypted:e.isEncrypted,eventIsEncrypted:s,shouldDecrypt:r});let{downloadUrl:o}=await this.appSyncClient.getAttachmentDownloadUrl(e.s3Key),l=await fetch(o);if(!l.ok)throw new Error(`Failed to download attachment: ${l.status} ${l.statusText}`);let a=Buffer.from(await l.arrayBuffer());if(r&&i)try{n.info("Decrypting attachment",{id:e.id}),a=d.cryptoService.decryptData(a,i),n.info("Attachment decrypted successfully",{id:e.id,decryptedSize:a.length})}catch(g){throw n.error("Failed to decrypt attachment:",{id:e.id,error:g}),new Error("Failed to decrypt attachment")}else if(r&&!i)return n.warn("Cannot decrypt attachment - no session key available",{id:e.id}),null;let p=N.join(De.tmpdir(),"codevibe-codex",t);A.existsSync(p)||A.mkdirSync(p,{recursive:!0});let u="";if(e.filename){let g=N.extname(e.filename);g&&(u=g)}u||(u={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}[e.type]||".bin");let h=`attachment-${e.id}${u}`,m=N.join(p,h);return A.writeFileSync(m,a),n.info("Attachment saved to temp file",{id:e.id,filePath:m,size:a.length}),m}catch(r){return n.error("Failed to download attachment:",{id:e.id,error:r}),null}}async handleMobileEvent(e,t=this.sessionState){if(e.attachments&&e.attachments.length>0&&n.info("DEBUG: Raw attachment data from subscription",{attachments:JSON.stringify(e.attachments),eventIsEncrypted:e.isEncrypted}),n.info("Received mobile event",{eventId:e.eventId,type:e.type,content:e.content?.substring(0,50),attachmentCount:e.attachments?.length||0,isEncrypted:e.isEncrypted}),!t||!this.isExpectedSessionStateCurrent(t)||e.sessionId!==t.sessionId){n.warn("Dropping mobile event for stale or mismatched session generation",{eventSessionId:e.sessionId,expectedSessionId:t?.sessionId,currentSessionId:this.sessionState?.sessionId});return}let i=t.sessionId,{sessionKey:s}=t.encryptionSnapshot,r=e.content||"";if(e.isEncrypted){if(!s){n.error("Dropping encrypted mobile event without its session-pinned key",{eventId:e.eventId,sessionId:i});return}try{r=d.cryptoService.decryptContent(e.content,s),n.debug("Event decrypted successfully",{eventId:e.eventId})}catch(o){n.error("Failed to decrypt event:",{eventId:e.eventId,error:o});return}}try{await this.appSyncClient.updateEventStatus({eventId:e.eventId,sessionId:e.sessionId,timestamp:e.timestamp,deliveryStatus:d.DeliveryStatus.DELIVERED})}catch(o){n.error("Failed to update delivery status:",o)}if(this.isExpectedSessionStateCurrent(t)&&(e.type===d.EventType.USER_PROMPT||e.type===d.EventType.PROMPT_RESPONSE)){let o=r,l=e.attachments||[],a=e.type===d.EventType.PROMPT_RESPONSE;if(e.type===d.EventType.PROMPT_RESPONSE){let m=this.getEventPromptId(e),g=this.pendingInteractivePrompt?.promptId;if(!m||!g||m!==g){n.warn("Rejecting stale or unbound PROMPT_RESPONSE",{eventId:e.eventId,eventPromptId:m,activePromptId:g}),await this.emitRejectedPromptResponseNotification("prompt_id_mismatch",e,t);return}}else this.pendingInteractivePrompt&&this.isApprovalResponseLike(o)&&(a=!0,n.info("Treating approval-shaped USER_PROMPT as active prompt response",{eventId:e.eventId,activePromptId:this.pendingInteractivePrompt.promptId,promptPreview:o.slice(0,20)}));let p=[];if(l.length>0){n.info("Downloading attachments for prompt",{count:l.length});for(let m of l){let g=await this.downloadAttachment(m,i,s,e.isEncrypted);if(!this.isExpectedSessionStateCurrent(t))return;g&&p.push(g)}if(p.length>0){let m=p.map(g=>`[Attached file: ${g}]`).join(`
|
|
26
|
+
`);o?o=`${m}
|
|
27
27
|
|
|
28
|
-
${
|
|
28
|
+
${o}`:o=`${m}
|
|
29
29
|
|
|
30
|
-
Please analyze the attached file(s).`,
|
|
30
|
+
Please analyze the attached file(s).`,n.info("Prompt updated with attachment paths",{attachmentCount:p.length,newPromptLength:o.length})}}let u=this.translatePromptResponse(o);if(!this.isExpectedSessionStateCurrent(t)||(u.primaryInput!==F&&this.trackMobilePrompt(i,u.primaryInput),!this.isExpectedSessionStateCurrent(t)))return;let h=await this.sendSessionPinnedInput(t,u.primaryInput);if(!this.isExpectedSessionStateCurrent(t))return;if(!h&&u.primaryInput!==F&&this.forgetMobilePrompt(i,u.primaryInput),h&&u.followUpInput){if(this.trackMobilePrompt(i,u.followUpInput),!this.isExpectedSessionStateCurrent(t))return;let m=await this.sendSessionPinnedInput(t,u.followUpInput);if(!this.isExpectedSessionStateCurrent(t))return;m||this.forgetMobilePrompt(i,u.followUpInput)}if(h&&this.pendingInteractivePrompt&&a){let m=this.pendingInteractivePrompt;if(this.rememberResolvedApprovalDedupeKey(t.sessionId,m.dedupeKey),this.pendingInteractivePrompt=null,await this.emitNextQueuedInteractivePrompt(),!this.isExpectedSessionStateCurrent(t))return}if(h){if(!this.isExpectedSessionStateCurrent(t))return;try{await this.appSyncClient.updateEventStatus({eventId:e.eventId,sessionId:e.sessionId,timestamp:e.timestamp,deliveryStatus:d.DeliveryStatus.EXECUTED})}catch(m){n.error("Failed to update executed status:",m)}}}}buildToolActivityIntegration(){return new k({logger:n,createEvent:e=>this.appSyncClient.createEvent(e),encryptContent:(e,t)=>d.cryptoService.encryptContent(e,t),encryptMetadata:(e,t)=>d.cryptoService.encryptMetadata(e,t),getSessionKey:()=>this.sessionKey,getSessionKeyGen:()=>this.sessionKeyGen,refreshSessionKey:e=>this.refreshToolActivitySessionKey(e)})}async refreshToolActivitySessionKey(e){try{let t=await this.appSyncClient.getSession(e);if(!t||!t.isEncrypted)return null;let i=t.sessionKeyGen??null,s=t.encryptedKeys??[];if(s.length===0)return null;let r=await d.keychainManager.getSessionKey(e,s,i);return r?(n.info("[tool-activity] refreshed session key for SessionKeyStale retry (live key untouched)",{sessionId:e,sessionKeyGen:i}),{sessionKey:r,sessionKeyGen:i}):null}catch(t){return n.warn("[tool-activity] session key refresh failed after SessionKeyStale (staying retryable)",{sessionId:e,error:String(t)}),null}}getToolActivityLegacyRecorder(e){let t=this.toolActivityLegacyRecorders.get(e);return t||(t=new d.ToolActivityLedger({agent:"codex",sessionId:e,logger:n}),this.toolActivityLegacyRecorders.set(e,t)),t}async ensureToolActivityStarted(e){if(!this.sessionState||!e)return;let t=this.sessionWatcher.getActiveLogFile()||this.sessionState.codexLogFile||void 0,i=this.toolActivity;if(i){t&&i.bindTranscript(t);return}if(this.toolActivityStartPromise){await this.toolActivityStartPromise,t&&this.toolActivity?.bindTranscript(t);return}if(!this.sessionKey)return;let s=this.sessionState.sessionId;this.toolActivityStartPromise=(async()=>{let r=this.buildToolActivityIntegration();try{await r.start(s,e,t),this.toolActivity=r}catch(o){throw await r.stop().catch(()=>{}),this.toolActivityStartPromise=null,o}})().catch(r=>{n.warn("[tool-activity] failed to start codex consolidator (non-fatal)",{backendSessionId:s,rolloutId:e,error:String(r)})}),await this.toolActivityStartPromise}startMobileEndWatcher(e){!this.sessionState||this.sessionState.sessionId!==e||(this.sessionState.mobileEndWatcher=this.appSyncClient.watchForMobileEnd(e,async()=>{n.info("Mobile ended session \u2014 sending desktop quit",{sessionId:e}),this.appSyncClient.stopHeartbeat(e),this.appSyncClient.cleanupSubscription(e);try{await this.appSyncClient.updateSession({sessionId:e,status:d.SessionStatus.INACTIVE}),n.info("Marked session INACTIVE on mobile-end (before tmux terminate)",{sessionId:e})}catch(i){n.warn("Failed to mark session INACTIVE on mobile-end",{sessionId:e,error:i})}let t=process.env[D];if(!t){n.warn("No tmux session set; skipping desktop self-terminate",{sessionId:e,expectedEnv:D});return}await Pt(t,gt)}))}async endActiveSession(e){if(!this.sessionState)return;let t=this.sessionState;if(this.terminalInputBlockedStates.add(t),await this.terminalInputChain.catch(()=>{}),this.sessionState!==t){n.warn("Session changed while waiting for terminal-input teardown barrier",{endingSessionId:t.sessionId,currentSessionId:this.sessionState?.sessionId,reason:e});return}if(n.info("Ending active session",{sessionId:t.sessionId,codexSessionId:t.codexSessionId,reason:e}),this.sessionState.mobileEndWatcher&&(this.sessionState.mobileEndWatcher.stop(),this.sessionState.mobileEndWatcher=void 0),this.userDecisionUnsubscribe){try{this.userDecisionUnsubscribe()}catch(i){n.warn("Error invoking onApplyUserDecision unsubscribe (non-fatal)",{error:i})}this.userDecisionUnsubscribe=null}if(this.orchestrationClient){try{await this.orchestrationClient.destroy()}catch(i){n.warn("Error destroying OrchestrationClient (non-fatal)",{error:i})}this.orchestrationClient=null}this.v1Bridge.clear(),this.appSyncClient.stopHeartbeat(this.sessionState.sessionId),this.stopE1TtlRefresh(),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null,this.subscribedSessionId=null,this.subscribedSessionState=null),await this.tmuxPaneObserver.stop(),this.pendingInteractivePrompt=null,this.queuedInteractivePrompts=[],this.isInitializingSession=!1,this.bufferedLogEntries=[],e==="shutdown"&&this.sessionWatcher.stop(),this.toolActivityStartPromise&&(await this.toolActivityStartPromise.catch(()=>{}),this.toolActivityStartPromise=null),await this.logEntryChain.catch(()=>{}),this.toolActivity&&(await this.toolActivity.stop(),this.toolActivity=null);for(let i of this.toolActivityLegacyRecorders.values())i.disposeLegacyCoordination();this.toolActivityLegacyRecorders.clear(),this.sessionKey&&(d.keychainManager.clearSessionKey(this.sessionState.sessionId),this.sessionKey=null,this.sessionKeyGen=null);try{await this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,status:d.SessionStatus.INACTIVE})}catch(i){n.error("Failed to update session status:",i)}this.sessionState=null}async stop(){n.info("Stopping CodeVibe Codex companion server"),this.stopTmuxLifecycleMonitor(),this.isStopping=!0,this.lifecycleGeneration+=1;let e=this.launchSessionInitPromise,t=this.sessionStartedInitPromise,i=this.retiredSessionRecoveryPromise;await Promise.all([e?.catch(()=>{}),t?.catch(()=>{}),i?.catch(()=>{})]);try{await this.endActiveSession("shutdown"),this.sessionWatcher.stop(),this.approvalDetector.shutdown(),he()}finally{await this.httpApi.stop(),this.appSyncClient.cleanupSubscriptions()}n.info("CodeVibe Codex companion server stopped")}};if(require.main===module){let c=new V;process.on("SIGINT",async()=>{n.info("Received SIGINT, shutting down..."),await c.stop(),process.exit(0)}),process.on("SIGTERM",async()=>{n.info("Received SIGTERM, shutting down..."),await c.stop(),process.exit(0)}),(0,d.installDaemonProcessGuards)(n,{onFatal:()=>{c.stop().finally(()=>process.exit(1))}}),c.start().catch(e=>{n.error("Failed to start server:",e),process.exit(1)})}0&&(module.exports={CodexCompanionServer,extractShellCommandFromPromptText,extractShellCommandPartsFromPromptText});
|