@wrongstack/cli 0.297.0 → 0.298.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{acp-A5OSIU2P.js → acp-S4LZQB66.js} +91 -23
- package/dist/{auth-CJWQJVRH.js → auth-NLLGEYQR.js} +3 -3
- package/dist/boot/governance-evidence-candidate.d.ts +3 -0
- package/dist/boot/governance-shadow-bridge.d.ts +19 -0
- package/dist/boot/governance-trace-context.d.ts +64 -0
- package/dist/boot/tui-session-resume.d.ts +10 -1
- package/dist/chimera-reviewer-policy.d.ts +89 -1
- package/dist/chimera-subagent-ladder.d.ts +72 -0
- package/dist/{chunk-AZESNNIC.js → chunk-4HH3YGG4.js} +3 -3
- package/dist/{chunk-QUNHS6O3.js → chunk-4U3DMA2Y.js} +2 -2
- package/dist/{chunk-IHBYBYGA.js → chunk-A6Q5KGLV.js} +51 -18
- package/dist/{chunk-ABXK4VVY.js → chunk-ARWGQUB3.js} +2 -1
- package/dist/{chunk-7JABKXET.js → chunk-C5GH4YBL.js} +1018 -175
- package/dist/{chunk-TADVX644.js → chunk-GO3TJICK.js} +11 -2
- package/dist/{chunk-JBTFWWKV.js → chunk-I2BM6FK6.js} +9 -4
- package/dist/{chunk-AXVZMEWG.js → chunk-I5MEUFDI.js} +2 -2
- package/dist/{chunk-XWEGWYDU.js → chunk-PEKUKUCH.js} +4 -71
- package/dist/chunk-U3SS4NRH.js +10 -0
- package/dist/{chunk-QZKWRNIP.js → chunk-V3XH6XBJ.js} +12 -9
- package/dist/{cli-main-GOY5YGVL.js → cli-main-7QLL2PY6.js} +957 -271
- package/dist/cli-main-helpers.d.ts +42 -2
- package/dist/{execution-A4PGK4XV.js → execution-HJ643JGZ.js} +834 -676
- package/dist/execution-chimera-cascade.d.ts +7 -1
- package/dist/execution-chimera-review.d.ts +35 -0
- package/dist/fleet/host-types.d.ts +6 -1
- package/dist/fleet-statusline.d.ts +1 -0
- package/dist/governance-V2Z42RBE.js +65 -0
- package/dist/governance-hq-telemetry.d.ts +17 -0
- package/dist/{hq-GBPGXIR5.js → hq-WO6CLUSI.js} +2 -2
- package/dist/hq-server/auth.d.ts +33 -2
- package/dist/hq-server/login-attempt-store.d.ts +73 -0
- package/dist/hq-server/routes/auth-handlers.d.ts +73 -5
- package/dist/hq-server/routes.d.ts +5 -5
- package/dist/hq-server/types.d.ts +36 -2
- package/dist/hq-server/utils.d.ts +51 -6
- package/dist/{hq-server-YQUUMTPU.js → hq-server-6TSAORAC.js} +2 -2
- package/dist/hq-server.d.ts +10 -0
- package/dist/index.js +52 -24
- package/dist/live-settings-input.d.ts +4 -3
- package/dist/plugin-management.d.ts +3 -8
- package/dist/{plugin-usage-OU6X6LM3.js → plugin-usage-VTL7ZTVC.js} +2 -2
- package/dist/{plugins-4LJ5IUBI.js → plugins-ETY6W3DC.js} +3 -3
- package/dist/settings-menu.d.ts +1 -1
- package/dist/slash-commands/fallback.d.ts +2 -0
- package/dist/slash-commands/goal-refiner.d.ts +1 -1
- package/dist/subcommands/handlers/acp-connection-gate.d.ts +20 -0
- package/dist/subcommands/handlers/governance.d.ts +8 -0
- package/dist/{update-YC4TYW2Y.js → update-MV6TUACD.js} +3 -3
- package/dist/utils/win32-cmd.d.ts +9 -6
- package/dist/{version-help-DROHZRW6.js → version-help-ASKQYXDJ.js} +2 -2
- package/dist/{webui-server-XKFUOKMJ.js → webui-server-PCLSXX6L.js} +10 -3
- package/dist/wiring/brain-and-orchestration.d.ts +2 -0
- package/dist/wiring/provider-runtime-setup.d.ts +2 -2
- package/package.json +24 -23
- package/dist/acp-A5OSIU2P.js.map +0 -7
- package/dist/acp-registry-cache.d.ts.map +0 -1
- package/dist/acp-server-agent.d.ts.map +0 -1
- package/dist/arg-parser.d.ts.map +0 -1
- package/dist/audit-2ZSFGNIF.js.map +0 -7
- package/dist/auth-CJWQJVRH.js.map +0 -7
- package/dist/auth-menu/add-provider.d.ts.map +0 -1
- package/dist/auth-menu/anthropic-oauth.d.ts.map +0 -1
- package/dist/auth-menu/auth-menu-audit.d.ts.map +0 -1
- package/dist/auth-menu/direct.d.ts.map +0 -1
- package/dist/auth-menu/github-copilot-oauth.d.ts.map +0 -1
- package/dist/auth-menu/helpers.d.ts.map +0 -1
- package/dist/auth-menu/index.d.ts.map +0 -1
- package/dist/auth-menu/local-presets.d.ts.map +0 -1
- package/dist/auth-menu/local.d.ts.map +0 -1
- package/dist/auth-menu/loopback-server.d.ts.map +0 -1
- package/dist/auth-menu/oauth-menu.d.ts.map +0 -1
- package/dist/auth-menu/openai-codex-oauth.d.ts.map +0 -1
- package/dist/auth-menu/panel-service.d.ts.map +0 -1
- package/dist/auth-menu/provider-menu.d.ts.map +0 -1
- package/dist/auth-menu/shared.d.ts.map +0 -1
- package/dist/auth-menu/top-menu.d.ts.map +0 -1
- package/dist/auth-menu/types.d.ts.map +0 -1
- package/dist/auth-menu.d.ts.map +0 -1
- package/dist/bench-7ZDWSNEF.js.map +0 -7
- package/dist/boot/auto-discover-providers.d.ts.map +0 -1
- package/dist/boot/brain-decision-log.d.ts.map +0 -1
- package/dist/boot/config-backup-recovery.d.ts.map +0 -1
- package/dist/boot/container-wiring.d.ts.map +0 -1
- package/dist/boot/dispatch-singleshot.d.ts.map +0 -1
- package/dist/boot/dispatch-tui.d.ts.map +0 -1
- package/dist/boot/dispatch-webui.d.ts.map +0 -1
- package/dist/boot/event-wiring.d.ts.map +0 -1
- package/dist/boot/execution-mode.d.ts.map +0 -1
- package/dist/boot/launch-banner.d.ts.map +0 -1
- package/dist/boot/launch-menu.d.ts.map +0 -1
- package/dist/boot/short-circuit-desktop.d.ts.map +0 -1
- package/dist/boot/short-circuit-flags.d.ts.map +0 -1
- package/dist/boot/short-circuit-hq.d.ts.map +0 -1
- package/dist/boot/simpleui-full-auto.d.ts.map +0 -1
- package/dist/boot/system-prompt-builder.d.ts.map +0 -1
- package/dist/boot/system-prompt.d.ts.map +0 -1
- package/dist/boot/tool-registry.d.ts.map +0 -1
- package/dist/boot/tui-coordinator-callbacks.d.ts.map +0 -1
- package/dist/boot/tui-coordinator-setup.d.ts.map +0 -1
- package/dist/boot/tui-debug-stream.d.ts.map +0 -1
- package/dist/boot/tui-goal-wiring.d.ts.map +0 -1
- package/dist/boot/tui-live-sessions.d.ts.map +0 -1
- package/dist/boot/tui-project-picker-callback.d.ts.map +0 -1
- package/dist/boot/tui-project-spawn.d.ts.map +0 -1
- package/dist/boot/tui-project-switch.d.ts.map +0 -1
- package/dist/boot/tui-runtime-state.d.ts.map +0 -1
- package/dist/boot/tui-sdd-callback.d.ts.map +0 -1
- package/dist/boot/tui-session-resume.d.ts.map +0 -1
- package/dist/boot/tui-settings-adapter.d.ts.map +0 -1
- package/dist/boot-config.d.ts.map +0 -1
- package/dist/boot.d.ts.map +0 -1
- package/dist/brain-menu/panel-service.d.ts.map +0 -1
- package/dist/chimera-review-task.d.ts.map +0 -1
- package/dist/chimera-reviewer-policy.d.ts.map +0 -1
- package/dist/chronicle-QQEQFSSE.js.map +0 -7
- package/dist/chunk-5N34EWJR.js.map +0 -7
- package/dist/chunk-66T43Q4Y.js.map +0 -7
- package/dist/chunk-7JABKXET.js.map +0 -7
- package/dist/chunk-7OCVIDC7.js.map +0 -7
- package/dist/chunk-ABXK4VVY.js.map +0 -7
- package/dist/chunk-AXVZMEWG.js.map +0 -7
- package/dist/chunk-AZESNNIC.js.map +0 -7
- package/dist/chunk-BGFM3PD7.js.map +0 -7
- package/dist/chunk-DPJZQCVP.js.map +0 -7
- package/dist/chunk-F4PEGAJZ.js.map +0 -7
- package/dist/chunk-IHBYBYGA.js.map +0 -7
- package/dist/chunk-JBSQ7ONN.js.map +0 -7
- package/dist/chunk-JBTFWWKV.js.map +0 -7
- package/dist/chunk-JUHRI6OV.js.map +0 -7
- package/dist/chunk-JW75HY4F.js.map +0 -7
- package/dist/chunk-OP47B3IX.js.map +0 -7
- package/dist/chunk-PJHET45A.js.map +0 -7
- package/dist/chunk-Q5GTM25S.js.map +0 -7
- package/dist/chunk-QD544J2B.js.map +0 -7
- package/dist/chunk-QUNHS6O3.js.map +0 -7
- package/dist/chunk-QZKWRNIP.js.map +0 -7
- package/dist/chunk-TADVX644.js.map +0 -7
- package/dist/chunk-TGDHN4LM.js.map +0 -7
- package/dist/chunk-TYO2OVAD.js.map +0 -7
- package/dist/chunk-VCYZ3WZV.js.map +0 -7
- package/dist/chunk-VJUEZZYB.js +0 -29
- package/dist/chunk-VJUEZZYB.js.map +0 -7
- package/dist/chunk-WHOIR577.js.map +0 -7
- package/dist/chunk-XJXDOF63.js.map +0 -7
- package/dist/chunk-XTIXVJXP.js.map +0 -7
- package/dist/chunk-XWEGWYDU.js.map +0 -7
- package/dist/chunk-YWUPHRGB.js.map +0 -7
- package/dist/cli-bundled-prompts.d.ts.map +0 -1
- package/dist/cli-bundled-skills.d.ts.map +0 -1
- package/dist/cli-context.d.ts.map +0 -1
- package/dist/cli-entry-main.d.ts.map +0 -1
- package/dist/cli-entry-point.d.ts.map +0 -1
- package/dist/cli-eternal-flag.d.ts.map +0 -1
- package/dist/cli-main-GOY5YGVL.js.map +0 -7
- package/dist/cli-main-helpers.d.ts.map +0 -1
- package/dist/cli-main.d.ts.map +0 -1
- package/dist/cli-update-notice.d.ts.map +0 -1
- package/dist/config-doctor.d.ts.map +0 -1
- package/dist/config-history.d.ts.map +0 -1
- package/dist/context-limit.d.ts.map +0 -1
- package/dist/context-overflow-diagnostic.d.ts.map +0 -1
- package/dist/diag-doctor-OQ3AA63O.js.map +0 -7
- package/dist/diff-renderer.d.ts.map +0 -1
- package/dist/execute-deps.d.ts.map +0 -1
- package/dist/execution-A4PGK4XV.js.map +0 -7
- package/dist/execution-chimera-ask.d.ts +0 -10
- package/dist/execution-chimera-ask.d.ts.map +0 -1
- package/dist/execution-chimera-cascade.d.ts.map +0 -1
- package/dist/execution-cleanup.d.ts.map +0 -1
- package/dist/execution-kanban-dispatch.d.ts.map +0 -1
- package/dist/execution-repl-fleet-callbacks.d.ts.map +0 -1
- package/dist/execution-storage-observability.d.ts.map +0 -1
- package/dist/execution-tui-next-step-callbacks.d.ts.map +0 -1
- package/dist/execution.d.ts.map +0 -1
- package/dist/export-TPORYVRZ.js.map +0 -7
- package/dist/fleet/host-acp-runner-cache.d.ts.map +0 -1
- package/dist/fleet/host-acp.d.ts.map +0 -1
- package/dist/fleet/host-concurrency.d.ts.map +0 -1
- package/dist/fleet/host-context.d.ts.map +0 -1
- package/dist/fleet/host-director-builder.d.ts.map +0 -1
- package/dist/fleet/host-director-event-bridges.d.ts.map +0 -1
- package/dist/fleet/host-director-services.d.ts.map +0 -1
- package/dist/fleet/host-event-bridge.d.ts.map +0 -1
- package/dist/fleet/host-helpers.d.ts.map +0 -1
- package/dist/fleet/host-learning-tracker.d.ts.map +0 -1
- package/dist/fleet/host-learning.d.ts.map +0 -1
- package/dist/fleet/host-lifecycle-events.d.ts.map +0 -1
- package/dist/fleet/host-paths.d.ts.map +0 -1
- package/dist/fleet/host-provider.d.ts.map +0 -1
- package/dist/fleet/host-session-writer.d.ts.map +0 -1
- package/dist/fleet/host-shadow-pass.d.ts.map +0 -1
- package/dist/fleet/host-spawn-types.d.ts.map +0 -1
- package/dist/fleet/host-status.d.ts.map +0 -1
- package/dist/fleet/host-subagent-factory.d.ts.map +0 -1
- package/dist/fleet/host-supervisor.d.ts.map +0 -1
- package/dist/fleet/host-task-result-report.d.ts.map +0 -1
- package/dist/fleet/host-types.d.ts.map +0 -1
- package/dist/fleet/host.d.ts.map +0 -1
- package/dist/fleet/routing.d.ts.map +0 -1
- package/dist/fleet/status-broadcast.d.ts.map +0 -1
- package/dist/fleet/supervisor-registry.d.ts.map +0 -1
- package/dist/fleet-statusline.d.ts.map +0 -1
- package/dist/goal-host.d.ts.map +0 -1
- package/dist/hooks-wiring.d.ts.map +0 -1
- package/dist/hq-GBPGXIR5.js.map +0 -7
- package/dist/hq-command-controller.d.ts.map +0 -1
- package/dist/hq-publisher.d.ts.map +0 -1
- package/dist/hq-recovery-html.d.ts.map +0 -1
- package/dist/hq-server/audit-actor.d.ts.map +0 -1
- package/dist/hq-server/auth-state.d.ts.map +0 -1
- package/dist/hq-server/auth.d.ts.map +0 -1
- package/dist/hq-server/preflight.d.ts.map +0 -1
- package/dist/hq-server/project-root.d.ts.map +0 -1
- package/dist/hq-server/routes/auth-handlers.d.ts.map +0 -1
- package/dist/hq-server/routes/session-handlers.d.ts.map +0 -1
- package/dist/hq-server/routes/system-handlers.d.ts.map +0 -1
- package/dist/hq-server/routes.d.ts.map +0 -1
- package/dist/hq-server/snapshot.d.ts.map +0 -1
- package/dist/hq-server/startup.d.ts.map +0 -1
- package/dist/hq-server/trust-boundary.d.ts.map +0 -1
- package/dist/hq-server/types.d.ts.map +0 -1
- package/dist/hq-server/utils.d.ts.map +0 -1
- package/dist/hq-server/ws.d.ts.map +0 -1
- package/dist/hq-server-YQUUMTPU.js.map +0 -7
- package/dist/hq-server.d.ts.map +0 -1
- package/dist/hq-static-serve.d.ts.map +0 -1
- package/dist/hq-ttl-U2FAYFAT.js.map +0 -7
- package/dist/hq-tunnel-RFKGC4HI.js.map +0 -7
- package/dist/hq-tunnel.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -7
- package/dist/init-E2NDDOHI.js.map +0 -7
- package/dist/input-reader.d.ts.map +0 -1
- package/dist/kanban-dispatch-route.d.ts.map +0 -1
- package/dist/kanban-hq-sync.d.ts.map +0 -1
- package/dist/kanban-run-mirror-EKVNGXWW.js.map +0 -7
- package/dist/launch-hints.d.ts.map +0 -1
- package/dist/live-settings-input.d.ts.map +0 -1
- package/dist/mailbox-bridge-bootstrap.d.ts.map +0 -1
- package/dist/mailbox-serve-DBOOOOWZ.js.map +0 -7
- package/dist/mcp-CYLPUEHC.js.map +0 -7
- package/dist/mcp-serve.d.ts.map +0 -1
- package/dist/modeldiag-HENYJ4N7.js.map +0 -7
- package/dist/multi-agent.d.ts.map +0 -1
- package/dist/next-task-predictor.d.ts.map +0 -1
- package/dist/permission-prompt.d.ts.map +0 -1
- package/dist/permissions-FNYLZIL4.js.map +0 -7
- package/dist/picker-key-state.d.ts.map +0 -1
- package/dist/picker-model-picker.d.ts.map +0 -1
- package/dist/picker-ui.d.ts.map +0 -1
- package/dist/picker.d.ts.map +0 -1
- package/dist/plugin-api-factory.d.ts.map +0 -1
- package/dist/plugin-management.d.ts.map +0 -1
- package/dist/plugin-usage-OU6X6LM3.js.map +0 -7
- package/dist/plugins-4LJ5IUBI.js.map +0 -7
- package/dist/pre-launch/launch-prompts.d.ts.map +0 -1
- package/dist/pre-launch/project-check.d.ts.map +0 -1
- package/dist/pre-launch.d.ts.map +0 -1
- package/dist/preflight.d.ts.map +0 -1
- package/dist/profile-config-path.d.ts.map +0 -1
- package/dist/project-BLQ3ALVL.js.map +0 -7
- package/dist/project-manifest-GE25PW4S.js.map +0 -7
- package/dist/project-picker-BOCWHBXP.js.map +0 -7
- package/dist/project-picker.d.ts.map +0 -1
- package/dist/projects-XE76NFNZ.js.map +0 -7
- package/dist/provider-config-utils.d.ts.map +0 -1
- package/dist/provider-helpers.d.ts.map +0 -1
- package/dist/provider-id.d.ts.map +0 -1
- package/dist/providers-models-GDELBHZK.js.map +0 -7
- package/dist/quick-VIO2BEHS.js.map +0 -7
- package/dist/renderer.d.ts.map +0 -1
- package/dist/repl-auto-proceed.d.ts.map +0 -1
- package/dist/repl-client-registration.d.ts.map +0 -1
- package/dist/repl-input.d.ts.map +0 -1
- package/dist/repl-options.d.ts.map +0 -1
- package/dist/repl-rendering.d.ts.map +0 -1
- package/dist/repl-suggestions.d.ts.map +0 -1
- package/dist/repl.d.ts.map +0 -1
- package/dist/replay-KCTXNMZQ.js.map +0 -7
- package/dist/rewind-EJMVFVLS.js.map +0 -7
- package/dist/sdd-runtime-AIJCJGWC.js.map +0 -7
- package/dist/services/autonomy-mode.d.ts.map +0 -1
- package/dist/services/commit-message.d.ts.map +0 -1
- package/dist/services/dispatch-classifier.d.ts.map +0 -1
- package/dist/services/mcp-management.d.ts.map +0 -1
- package/dist/services/project-facts.d.ts.map +0 -1
- package/dist/services/project-manifest.d.ts.map +0 -1
- package/dist/services/sdd/project-context.d.ts.map +0 -1
- package/dist/services/sdd/spec-detection.d.ts.map +0 -1
- package/dist/services/sdd/state.d.ts.map +0 -1
- package/dist/services/sdd/task-manager.d.ts.map +0 -1
- package/dist/services/sdd-runtime.d.ts.map +0 -1
- package/dist/services/statusline-config.d.ts.map +0 -1
- package/dist/services/suggestion-store.d.ts.map +0 -1
- package/dist/session-event-wiring.d.ts.map +0 -1
- package/dist/session-stats.d.ts.map +0 -1
- package/dist/sessions-config-NLCMK3BY.js.map +0 -7
- package/dist/settings-menu.d.ts.map +0 -1
- package/dist/shutdown-cleanup.d.ts.map +0 -1
- package/dist/simpleui-dist-JIFGUJO7.js.map +0 -7
- package/dist/simpleui-dist.d.ts.map +0 -1
- package/dist/slash-commands/acp.d.ts.map +0 -1
- package/dist/slash-commands/agent-improve.d.ts.map +0 -1
- package/dist/slash-commands/agents.d.ts.map +0 -1
- package/dist/slash-commands/audit.d.ts.map +0 -1
- package/dist/slash-commands/auth.d.ts.map +0 -1
- package/dist/slash-commands/autonomy.d.ts.map +0 -1
- package/dist/slash-commands/brain.d.ts.map +0 -1
- package/dist/slash-commands/btw.d.ts.map +0 -1
- package/dist/slash-commands/clear.d.ts.map +0 -1
- package/dist/slash-commands/codebase-reindex.d.ts.map +0 -1
- package/dist/slash-commands/collab.d.ts.map +0 -1
- package/dist/slash-commands/command-context.d.ts.map +0 -1
- package/dist/slash-commands/commit-llm.d.ts.map +0 -1
- package/dist/slash-commands/compact.d.ts.map +0 -1
- package/dist/slash-commands/context.d.ts.map +0 -1
- package/dist/slash-commands/coordinator.d.ts.map +0 -1
- package/dist/slash-commands/delegate.d.ts.map +0 -1
- package/dist/slash-commands/design.d.ts.map +0 -1
- package/dist/slash-commands/dev.d.ts.map +0 -1
- package/dist/slash-commands/diag-stats.d.ts.map +0 -1
- package/dist/slash-commands/dispatch-llm.d.ts.map +0 -1
- package/dist/slash-commands/doctor.d.ts.map +0 -1
- package/dist/slash-commands/enhance.d.ts.map +0 -1
- package/dist/slash-commands/ensemble.d.ts.map +0 -1
- package/dist/slash-commands/f-keys.d.ts.map +0 -1
- package/dist/slash-commands/fallback.d.ts.map +0 -1
- package/dist/slash-commands/fix-classifier.d.ts.map +0 -1
- package/dist/slash-commands/fix.d.ts.map +0 -1
- package/dist/slash-commands/fleet.d.ts.map +0 -1
- package/dist/slash-commands/git.d.ts.map +0 -1
- package/dist/slash-commands/gitid.d.ts.map +0 -1
- package/dist/slash-commands/goal-refiner.d.ts.map +0 -1
- package/dist/slash-commands/goal.d.ts.map +0 -1
- package/dist/slash-commands/health.d.ts.map +0 -1
- package/dist/slash-commands/help.d.ts.map +0 -1
- package/dist/slash-commands/helpers.d.ts.map +0 -1
- package/dist/slash-commands/hq.d.ts.map +0 -1
- package/dist/slash-commands/index.d.ts.map +0 -1
- package/dist/slash-commands/init.d.ts.map +0 -1
- package/dist/slash-commands/interrupt.d.ts.map +0 -1
- package/dist/slash-commands/kanban-agent-helpers.d.ts.map +0 -1
- package/dist/slash-commands/kanban-format.d.ts.map +0 -1
- package/dist/slash-commands/kanban-help.d.ts.map +0 -1
- package/dist/slash-commands/kanban.d.ts.map +0 -1
- package/dist/slash-commands/mailbox-demo.d.ts.map +0 -1
- package/dist/slash-commands/mailbox-serve.d.ts.map +0 -1
- package/dist/slash-commands/mailbox.d.ts.map +0 -1
- package/dist/slash-commands/mcp-utils.d.ts.map +0 -1
- package/dist/slash-commands/mcp.d.ts.map +0 -1
- package/dist/slash-commands/memory-compact.d.ts.map +0 -1
- package/dist/slash-commands/memory-flags.d.ts.map +0 -1
- package/dist/slash-commands/memory-formatters.d.ts.map +0 -1
- package/dist/slash-commands/memory.d.ts.map +0 -1
- package/dist/slash-commands/metrics.d.ts.map +0 -1
- package/dist/slash-commands/mode.d.ts.map +0 -1
- package/dist/slash-commands/modelcaps.d.ts.map +0 -1
- package/dist/slash-commands/models.d.ts.map +0 -1
- package/dist/slash-commands/mouse.d.ts.map +0 -1
- package/dist/slash-commands/next.d.ts.map +0 -1
- package/dist/slash-commands/plan.d.ts.map +0 -1
- package/dist/slash-commands/plugin.d.ts.map +0 -1
- package/dist/slash-commands/profile.d.ts.map +0 -1
- package/dist/slash-commands/project-utils.d.ts.map +0 -1
- package/dist/slash-commands/project.d.ts.map +0 -1
- package/dist/slash-commands/provider-status.d.ts.map +0 -1
- package/dist/slash-commands/prune.d.ts.map +0 -1
- package/dist/slash-commands/refiner.d.ts.map +0 -1
- package/dist/slash-commands/review.d.ts.map +0 -1
- package/dist/slash-commands/sdd/rendering.d.ts.map +0 -1
- package/dist/slash-commands/sdd-command-helpers.d.ts.map +0 -1
- package/dist/slash-commands/sdd-format.d.ts.map +0 -1
- package/dist/slash-commands/sdd.d.ts.map +0 -1
- package/dist/slash-commands/security.d.ts.map +0 -1
- package/dist/slash-commands/session.d.ts.map +0 -1
- package/dist/slash-commands/setmodel.d.ts.map +0 -1
- package/dist/slash-commands/settings.d.ts.map +0 -1
- package/dist/slash-commands/shadow.d.ts.map +0 -1
- package/dist/slash-commands/slash-deep-help.d.ts.map +0 -1
- package/dist/slash-commands/spawn-agents.d.ts.map +0 -1
- package/dist/slash-commands/statusline.d.ts.map +0 -1
- package/dist/slash-commands/suggest.d.ts.map +0 -1
- package/dist/slash-commands/suggestion-store.d.ts.map +0 -1
- package/dist/slash-commands/supervisor.d.ts.map +0 -1
- package/dist/slash-commands/surfaces.d.ts.map +0 -1
- package/dist/slash-commands/tasks.d.ts.map +0 -1
- package/dist/slash-commands/techstack.d.ts.map +0 -1
- package/dist/slash-commands/telegram-pairing.d.ts.map +0 -1
- package/dist/slash-commands/telegram-settings.d.ts.map +0 -1
- package/dist/slash-commands/telegram-setup.d.ts.map +0 -1
- package/dist/slash-commands/todos.d.ts.map +0 -1
- package/dist/slash-commands/tool.d.ts.map +0 -1
- package/dist/slash-commands/tools.d.ts.map +0 -1
- package/dist/slash-commands/tuneup.d.ts.map +0 -1
- package/dist/slash-commands/working-dir.d.ts.map +0 -1
- package/dist/slash-commands/worktree.d.ts.map +0 -1
- package/dist/slash-commands/yolo.d.ts.map +0 -1
- package/dist/spinner.d.ts.map +0 -1
- package/dist/subcommands/contracts.d.ts.map +0 -1
- package/dist/subcommands/handlers/acp.d.ts.map +0 -1
- package/dist/subcommands/handlers/audit.d.ts.map +0 -1
- package/dist/subcommands/handlers/auth-local-help.d.ts.map +0 -1
- package/dist/subcommands/handlers/auth.d.ts.map +0 -1
- package/dist/subcommands/handlers/bench-run-help.d.ts.map +0 -1
- package/dist/subcommands/handlers/bench.d.ts.map +0 -1
- package/dist/subcommands/handlers/chronicle.d.ts.map +0 -1
- package/dist/subcommands/handlers/config-history.d.ts.map +0 -1
- package/dist/subcommands/handlers/diag-doctor.d.ts.map +0 -1
- package/dist/subcommands/handlers/export.d.ts.map +0 -1
- package/dist/subcommands/handlers/helpers.d.ts.map +0 -1
- package/dist/subcommands/handlers/hq.d.ts.map +0 -1
- package/dist/subcommands/handlers/init.d.ts.map +0 -1
- package/dist/subcommands/handlers/mailbox-serve.d.ts.map +0 -1
- package/dist/subcommands/handlers/mcp.d.ts.map +0 -1
- package/dist/subcommands/handlers/model-smoke-test.d.ts.map +0 -1
- package/dist/subcommands/handlers/modeldiag-profiles.d.ts.map +0 -1
- package/dist/subcommands/handlers/modeldiag.d.ts.map +0 -1
- package/dist/subcommands/handlers/models-add-help.d.ts.map +0 -1
- package/dist/subcommands/handlers/per-subcommand-deep-help-table.d.ts.map +0 -1
- package/dist/subcommands/handlers/per-subcommand-help-data.d.ts.map +0 -1
- package/dist/subcommands/handlers/per-subcommand-help-table.d.ts.map +0 -1
- package/dist/subcommands/handlers/per-subcommand-help-types.d.ts.map +0 -1
- package/dist/subcommands/handlers/per-subcommand-help.d.ts.map +0 -1
- package/dist/subcommands/handlers/permissions.d.ts.map +0 -1
- package/dist/subcommands/handlers/plugin-usage.d.ts.map +0 -1
- package/dist/subcommands/handlers/project.d.ts.map +0 -1
- package/dist/subcommands/handlers/projects.d.ts.map +0 -1
- package/dist/subcommands/handlers/providers-models.d.ts.map +0 -1
- package/dist/subcommands/handlers/quick.d.ts.map +0 -1
- package/dist/subcommands/handlers/replay.d.ts.map +0 -1
- package/dist/subcommands/handlers/rewind.d.ts.map +0 -1
- package/dist/subcommands/handlers/sessions-config.d.ts.map +0 -1
- package/dist/subcommands/handlers/sessions-fleet.d.ts.map +0 -1
- package/dist/subcommands/handlers/tools-skills.d.ts.map +0 -1
- package/dist/subcommands/handlers/update.d.ts.map +0 -1
- package/dist/subcommands/handlers/version-help.d.ts.map +0 -1
- package/dist/subcommands/index.d.ts.map +0 -1
- package/dist/theme.d.ts.map +0 -1
- package/dist/tools-skills-UNKLOB7M.js.map +0 -7
- package/dist/tui-thinking-word.d.ts.map +0 -1
- package/dist/tuneup.d.ts.map +0 -1
- package/dist/update-YC4TYW2Y.js.map +0 -7
- package/dist/update-check-UMYTOH7Z.js.map +0 -7
- package/dist/update-check.d.ts.map +0 -1
- package/dist/utils/delay-format.d.ts.map +0 -1
- package/dist/utils/hq-ttl.d.ts.map +0 -1
- package/dist/utils/win32-cmd.d.ts.map +0 -1
- package/dist/utils.d.ts.map +0 -1
- package/dist/version-help-DROHZRW6.js.map +0 -7
- package/dist/version.d.ts.map +0 -1
- package/dist/webui-server/client-registration.d.ts.map +0 -1
- package/dist/webui-server/connection-handler.d.ts.map +0 -1
- package/dist/webui-server/context-breakdown.d.ts.map +0 -1
- package/dist/webui-server/contracts.d.ts.map +0 -1
- package/dist/webui-server/cost-helpers.d.ts.map +0 -1
- package/dist/webui-server/kanban-host-adapter.d.ts.map +0 -1
- package/dist/webui-server/kanban-run-mirror.d.ts.map +0 -1
- package/dist/webui-server/kanban-supervisor.d.ts.map +0 -1
- package/dist/webui-server/lifecycle.d.ts.map +0 -1
- package/dist/webui-server/listen-helpers.d.ts.map +0 -1
- package/dist/webui-server/logger-shim.d.ts.map +0 -1
- package/dist/webui-server/node-pty-loader.d.ts.map +0 -1
- package/dist/webui-server/prefs-seeding.d.ts.map +0 -1
- package/dist/webui-server/privileged-actions.d.ts.map +0 -1
- package/dist/webui-server/provider-config.d.ts.map +0 -1
- package/dist/webui-server/session-start-payload.d.ts.map +0 -1
- package/dist/webui-server/setup-events.d.ts.map +0 -1
- package/dist/webui-server/static-serve.d.ts.map +0 -1
- package/dist/webui-server/stream-coalescer.d.ts.map +0 -1
- package/dist/webui-server/terminal-log-view.d.ts.map +0 -1
- package/dist/webui-server-XKFUOKMJ.js.map +0 -7
- package/dist/webui-server-options.d.ts.map +0 -1
- package/dist/webui-server.d.ts.map +0 -1
- package/dist/wiring/brain-and-orchestration.d.ts.map +0 -1
- package/dist/wiring/codebase-index.d.ts.map +0 -1
- package/dist/wiring/command-host-adapters.d.ts.map +0 -1
- package/dist/wiring/command-host-state.d.ts.map +0 -1
- package/dist/wiring/controllers.d.ts.map +0 -1
- package/dist/wiring/dep-watcher-bridge.d.ts.map +0 -1
- package/dist/wiring/dep-watcher.d.ts.map +0 -1
- package/dist/wiring/design-studio.d.ts.map +0 -1
- package/dist/wiring/director-setup.d.ts.map +0 -1
- package/dist/wiring/eternal-command-handlers.d.ts.map +0 -1
- package/dist/wiring/fleet-command-handlers.d.ts.map +0 -1
- package/dist/wiring/hq-telemetry.d.ts.map +0 -1
- package/dist/wiring/lifecycle-plugins.d.ts.map +0 -1
- package/dist/wiring/mailbox-bridge-bootstrap.d.ts.map +0 -1
- package/dist/wiring/management-tools.d.ts.map +0 -1
- package/dist/wiring/metrics.d.ts.map +0 -1
- package/dist/wiring/pipeline.d.ts.map +0 -1
- package/dist/wiring/plugins.d.ts.map +0 -1
- package/dist/wiring/provider-runtime-setup.d.ts.map +0 -1
- package/dist/wiring/provider-runtime.d.ts.map +0 -1
- package/dist/wiring/provider-status.d.ts.map +0 -1
- package/dist/wiring/provider-utility-tools.d.ts.map +0 -1
- package/dist/wiring/provider.d.ts.map +0 -1
- package/dist/wiring/replay.d.ts.map +0 -1
- package/dist/wiring/runtime-controller-deps.d.ts.map +0 -1
- package/dist/wiring/runtime-dispatch-state.d.ts.map +0 -1
- package/dist/wiring/runtime-lifecycle-deps.d.ts.map +0 -1
- package/dist/wiring/runtime-picker-deps.d.ts.map +0 -1
- package/dist/wiring/sage.d.ts.map +0 -1
- package/dist/wiring/sdd-handlers.d.ts.map +0 -1
- package/dist/wiring/security-command.d.ts.map +0 -1
- package/dist/wiring/session-command-handlers.d.ts.map +0 -1
- package/dist/wiring/session-registry.d.ts.map +0 -1
- package/dist/wiring/session.d.ts.map +0 -1
- package/dist/wiring/slash-commands.d.ts.map +0 -1
- package/dist/wiring/to-execute-deps.d.ts.map +0 -1
- package/dist/wiring/tools.d.ts.map +0 -1
package/dist/index.js.map
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/cli-entry-point.ts", "../src/boot.ts", "../src/boot/config-backup-recovery.ts", "../src/boot-config.ts", "../src/input-reader.ts", "../src/launch-hints.ts", "../src/pre-launch/project-check.ts", "../src/pre-launch/launch-prompts.ts", "../src/renderer.ts", "../src/subcommands/index.ts", "../src/boot/short-circuit-flags.ts", "../src/boot/short-circuit-desktop.ts", "../src/boot/short-circuit-hq.ts", "../src/boot/launch-menu.ts", "../src/boot/launch-banner.ts", "../src/preflight.ts", "../src/cli-update-notice.ts", "../src/boot/container-wiring.ts", "../src/cli-bundled-skills.ts", "../src/cli-bundled-prompts.ts", "../src/wiring/replay.ts", "../src/cli-context.ts", "../src/cli-entry-main.ts", "../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Detect whether this module was loaded as the CLI's main entry point\n * (vs imported as a library) and, if so, run the supplied `main` function\n * with the current process argv.\n *\n * Why a helper:\n * 1. **isMain detection in one place** \u2014 the `import.meta.url` /\n * `process.argv[1]` comparison has both POSIX (`/`) and Windows (`\\`)\n * path forms; centralising it stops the pattern from drifting.\n * 2. **Bounded exit on both success and failure** \u2014 Node will normally\n * drain async handles (undici TLS, log flushes) on its own, but a\n * leaking plugin or MCP server can hang the process indefinitely.\n * A 500ms `setTimeout(exit)` with `.unref()` lets the natural drain\n * finish first, then forces exit if anything is still pending. The\n * `.unref()` is critical: it prevents the timer itself from keeping\n * the event loop alive.\n * 3. **Stack-trace on rejection** \u2014 a top-level `main().catch(...)` that\n * logs `err.stack` (not just the message) makes crash dumps from\n * end-user bug reports actually debuggable.\n */\n\n// \u2500\u2500 Permanent SQLite ExperimentalWarning suppressor \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// Node 22.5+'s built-in node:sqlite emits a one-line ExperimentalWarning the\n// first time the module is loaded, via process.emitWarning(message, type).\n// Three lazy loaders (sage, techstack, codebase-index) already suppress it\n// locally, but any code path that loads node:sqlite BEFORE those suppressors\n// are instantiated fires the warning to stderr.\n//\n// By replacing process.emitWarning at this module's evaluation time (before\n// any downstream dynamic import or lazy require), this catches the FIRST\n// node:sqlite access regardless of which module triggers it. Static imports\n// in transitive dependencies are NOT covered (ESM hoists them before this\n// runs), but every node:sqlite access in this project is through dynamic\n// lazy loaders, so this intercepts all production paths. Later suppressors\n// capture the already-filtered function as their \"original\", which is\n// harmless \u2014 double-filtering is a no-op.\n//\n// \u26A0\uFE0F process.emitWarning(warning: string, type?: string, ...): when warning\n// is a plain string (two-arg form used by Node's internal emitExperimentalWarning),\n// the type is in rest[0] \u2014 NOT warning.name (which is undefined for strings).\nconst SQLITE_WARNING_RE = /sqlite is an experimental feature/i;\n\nfunction installSqliteWarningFilter(): void {\n const originalEmit = process.emitWarning.bind(process);\n process.emitWarning = ((warning: unknown, ...rest: unknown[]): void => {\n const msg = typeof warning === 'string' ? warning : ((warning as Error)?.message ?? '');\n // Node's emitWarning overloads:\n // (warning: string, type?: string, code?: string)\n // (warning: Error, options?: { type?: string; code?: string })\n // When warning is a string the type lives in rest[0]; when it's an Error\n // the type is warning.name.\n const type =\n typeof warning === 'string' ? String(rest[0] ?? '') : ((warning as Error).name ?? '');\n if (type === 'ExperimentalWarning' && SQLITE_WARNING_RE.test(msg)) {\n return; // suppressed \u2014 node:sqlite has been stable since Node 22.5\n }\n (originalEmit as (w: unknown, ...args: unknown[]) => void)(warning, ...rest);\n }) as typeof process.emitWarning;\n}\n\ninstallSqliteWarningFilter();\n\nimport { writeErr } from '@wrongstack/core/utils';\n\nconst isMain =\n import.meta.url === `file://${process.argv[1]?.replace(/\\\\/g, '/')}` ||\n process.argv[1]?.endsWith('/cli/dist/index.js') ||\n process.argv[1]?.endsWith('\\\\cli\\\\dist\\\\index.js');\n\ninterface ErrorEventStream {\n on(event: 'error', listener: (error: unknown) => void): unknown;\n off(event: 'error', listener: (error: unknown) => void): unknown;\n}\n\ninterface BrokenPipeHandlerOptions {\n streams?: readonly ErrorEventStream[] | undefined;\n exit?: ((code: number) => void) | undefined;\n}\n\nfunction isBrokenOutputConsumer(error: unknown): boolean {\n if (typeof error !== 'object' || error === null || !('code' in error)) return false;\n return error.code === 'EPIPE' || error.code === 'ECONNRESET' || error.code === 'ECONNABORTED';\n}\n\n/**\n * Treat a closed stdout/stderr consumer as a normal CLI shutdown.\n *\n * A failed `write()` is reported asynchronously through the destination\n * stream's `error` event, so wrapping individual writes in `try/catch` cannot\n * prevent Node's unhandled-event crash. Windows can report the same closed\n * consumer as ECONNRESET rather than EPIPE, so handle both at the process entry\n * boundary and rethrow other stream failures so genuine faults remain visible.\n */\nexport function installBrokenPipeHandlers(options: BrokenPipeHandlerOptions = {}): () => void {\n const streams = options.streams ?? [process.stdout, process.stderr];\n const exit = options.exit ?? ((code: number) => process.exit(code));\n let handled = false;\n\n const onError = (error: unknown): void => {\n if (!isBrokenOutputConsumer(error)) throw error;\n if (handled) return;\n handled = true;\n exit(0);\n };\n\n for (const stream of streams) stream.on('error', onError);\n return () => {\n for (const stream of streams) stream.off('error', onError);\n };\n}\n\nexport function runAsMain(mainFn: (argv: string[]) => Promise<number>): void {\n if (!isMain) return;\n installBrokenPipeHandlers();\n mainFn(process.argv.slice(2)).then(\n (c) => {\n // Set exitCode and let Node drain async handles (undici TLS, log file\n // flushes) naturally. Force-exit after a brief grace period so we don't\n // hang if a plugin or MCP server leaks. Avoids libuv UV_HANDLE_CLOSING\n // assertions seen on Windows when process.exit() races with handle teardown.\n process.exitCode = c;\n // 500ms grace: let undici TLS, log flushes, and plugin teardown complete.\n // The unref() prevents this timer from keeping the event loop alive\n // if everything else finishes first.\n setTimeout(() => process.exit(c), 500).unref();\n },\n (err) => {\n writeErr((err instanceof Error ? err.stack : String(err)) + '\\n');\n process.exitCode = 1;\n setTimeout(() => process.exit(1), 500).unref();\n },\n );\n}\n", "import * as fs from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { toErrorMessage } from '@wrongstack/core/utils';\n\n/**\n * Boot phase \u2014 everything before the DI container wiring.\n * Extracted from index.ts so main() focuses on wire \u2192 execute.\n */\n\n/**\n * Curated model-catalog overlay served from our GitHub repo. Deep-merged on\n * top of models.dev so we can add/fix providers/models without an upstream\n * fix or a release. See `packages/cli/data/README.md`.\n */\nconst GITHUB_PROVIDERS_OVERLAY_URL =\n 'https://raw.githubusercontent.com/WrongStack/WrongStack/main/packages/cli/data/providers.json';\n\n/**\n * Resolve the bundled overlay `providers.json`. It ships at `<pkg>/data/` \u2014\n * a sibling of both `src/` (dev) and `dist/` (published) \u2014 so `../data/\u2026`\n * relative to this module resolves in both. Returns undefined if anything\n * about the resolution looks off (the overlay is optional).\n */\nfunction resolveBundledOverlayFile(): string | undefined {\n try {\n return fileURLToPath(new URL('../data/providers.json', import.meta.url));\n } catch {\n return undefined;\n }\n}\n\nimport type { Config, ModelsRegistry, SecretVault } from '@wrongstack/core/types';\nimport { color, isStdinTTY, type WstackPaths, writeErr } from '@wrongstack/core/utils';\nimport { normalizeTokenSavingTier } from '@wrongstack/core/types';\nimport { DefaultLogger } from '@wrongstack/core/infrastructure';\nimport { DefaultModelsRegistry } from '@wrongstack/core/models';\nimport { TOKENS } from '@wrongstack/core/kernel';\nimport { ToolRegistry } from '@wrongstack/core/registry';\nimport { createDefaultContainer } from '@wrongstack/runtime';\nimport { registerBuiltinToolTier } from '@wrongstack/tools/tool-tier';\nimport { parseArgs } from './arg-parser.js';\nimport { discoverAndMergeProviders } from './boot/auto-discover-providers.js';\nimport { maybeRestoreDefaultProfileFromBackup } from './boot/config-backup-recovery.js';\nimport { applySimpleUiFullAutoProfile, isSimpleUiFullAuto } from './boot/simpleui-full-auto.js';\nimport { bootConfig } from './boot-config.js';\nimport { ReadlineInputReader } from './input-reader.js';\nimport { printLaunchHints } from './launch-hints.js';\nimport { type PickerResult, runPicker, saveToGlobalConfig } from './picker.js';\nimport {\n LaunchAbortedError,\n persistLaunchChoices,\n runLaunchPrompts,\n runProjectCheck,\n} from './pre-launch.js';\nimport { activeProfileConfigPath } from './profile-config-path.js';\nimport { resolveActiveApiKey } from './provider-config-utils.js';\nimport { isKeylessLocalProvider, visibleModelIds } from './provider-helpers.js';\nimport { TerminalRenderer } from './renderer.js';\nimport { runUpdateCommand } from './subcommands/handlers/update.js';\nimport { subcommands } from './subcommands/index.js';\nimport type { UpdateInfo } from './update-check.js';\nimport { patchConfig } from './utils.js';\n\ninterface SavedDefaultStatus {\n ok: boolean;\n reason?: string;\n}\n\nasync function validateSavedProviderModel(\n config: Config,\n modelsRegistry: ModelsRegistry,\n): Promise<SavedDefaultStatus> {\n const providerId = config.provider;\n const modelId = config.model;\n if (!providerId || !modelId) return { ok: false, reason: 'missing provider/model' };\n\n const saved = config.providers?.[providerId];\n const lookupId = saved?.type && saved.type !== providerId ? saved.type : providerId;\n const catalogProvider = await modelsRegistry.getProvider(lookupId).catch(() => undefined);\n if (!catalogProvider && !saved?.family)\n return { ok: false, reason: `provider \"${providerId}\" is no longer available` };\n\n const hasCredential =\n (catalogProvider?.envVars ?? saved?.envVars ?? []).some((envVar) =>\n Boolean(process.env[envVar]),\n ) ||\n (saved !== undefined && resolveActiveApiKey(saved) !== undefined) ||\n isKeylessLocalProvider({\n apiBase: saved?.baseUrl ?? catalogProvider?.apiBase,\n envVars: saved?.envVars ?? catalogProvider?.envVars,\n });\n if (!hasCredential) return { ok: false, reason: `provider \"${providerId}\" has no usable key` };\n\n const visible = visibleModelIds(\n providerId,\n config,\n (catalogProvider?.models ?? []).map((m) => m.id),\n saved,\n );\n if (visible.length > 0 && !visible.includes(modelId)) {\n return {\n ok: false,\n reason: `model \"${modelId}\" is no longer available for provider \"${providerId}\"`,\n };\n }\n return { ok: true };\n}\n\n/**\n * Resolve a usable `{ provider, model }` from saved config when the active\n * pointers are unset \u2014 the non-interactive (WebUI / --no-interactive) analogue\n * of the TUI's interactive picker. Mirrors the standalone WebUI's auto-select\n * (packages/webui-server start-webui.ts) so a config whose only entry is a\n * custom provider still boots instead of erroring out. Prefers an already-set\n * `config.provider`, otherwise the first saved provider; the model comes from\n * the provider's saved `models` allowlist, falling back to the catalog's first\n * model. Returns undefined when no provider yields a concrete model.\n */\nexport async function autoSelectSavedProvider(\n config: Config,\n modelsRegistry: ModelsRegistry,\n): Promise<{ provider: string; model: string } | undefined> {\n const providers = config.providers ?? {};\n const entries =\n config.provider && providers[config.provider]\n ? ([[config.provider, providers[config.provider]]] as const)\n : Object.entries(providers);\n for (const [id, cfg] of entries) {\n if (!cfg) continue;\n let model = cfg.models?.[0];\n if (!model) {\n const catalogId = cfg.type && cfg.type !== id ? cfg.type : id;\n const catalog = await modelsRegistry.getProvider(catalogId).catch(() => undefined);\n model = catalog?.models?.[0]?.id;\n }\n if (model) return { provider: id, model };\n }\n return undefined;\n}\n\nexport interface BootContext {\n config: Config;\n vault: SecretVault;\n wpaths: WstackPaths;\n cwd: string;\n projectRoot: string;\n userHome: string;\n flags: Record<string, string | boolean>;\n positional: string[];\n modelsRegistry: ModelsRegistry;\n renderer: TerminalRenderer;\n reader: ReadlineInputReader;\n logger: DefaultLogger;\n /** Set by background update check \u2014 if outdated, index.ts shows notification */\n updateInfo?: UpdateInfo | undefined;\n /** True when running in --webui/--no-interactive mode but provider/model not configured */\n needsSetup?: boolean | undefined;\n}\n\nfunction resolveBundledSkillsDir(): string | undefined {\n try {\n const req = createRequire(import.meta.url);\n const corePkg = req.resolve('@wrongstack/core/package.json');\n return path.join(path.dirname(corePkg), 'skills');\n } catch {\n return undefined;\n }\n}\n\nfunction resolveBundledPromptsDir(): string | undefined {\n try {\n const req = createRequire(import.meta.url);\n const corePkg = req.resolve('@wrongstack/core/package.json');\n return path.join(path.dirname(corePkg), 'data', 'prompts');\n } catch {\n return undefined;\n }\n}\n\n/**\n * Determine whether a directory is the user's home directory. Used by the\n * startup guard to refuse launching wstack in `~` \u2014 where it would risk\n * creating a `.git` repo at the top of the user's filesystem.\n *\n * Resolves both paths so trailing slashes and relative segments are\n * normalized before the comparison. Case is compared as-is (matches\n * `os.homedir()` and `process.cwd()` output on every platform). Symlinks\n * are NOT followed: the common case (`cwd === os.homedir()` literally) is\n * what this guard targets.\n *\n * Exported for testing \u2014 the call site in {@link boot} performs the actual\n * warning + exit.\n */\nexport function isHomeDirectory(cwd: string, userHome: string): boolean {\n if (!cwd || !userHome) return false;\n return path.resolve(cwd) === path.resolve(userHome);\n}\n\n/**\n * Determine whether the first-run YOLO disclosure notice should be printed\n * to stderr. Exported for testing.\n *\n * @param lastChoices Saved launch preferences from config (undefined = first run)\n * @param yoloPinned Explicit --yolo/--no-yolo flag (undefined = not provided)\n * @param yolo Resolved YOLO state\n */\nexport function shouldPrintYoloNotice(\n lastChoices: unknown,\n yoloPinned: boolean | undefined,\n yolo: boolean,\n): boolean {\n return !lastChoices && yoloPinned === undefined && yolo;\n}\n\n/**\n * Boot the CLI: parse args, load config, handle subcommand dispatch\n * (early exit), run interactive prompts (project check, provider picker,\n * mode/yolo). Returns a BootContext for the wiring phase, or an exit\n * code when the run should stop here.\n */\nexport async function boot(argv: string[]): Promise<BootContext | number> {\n const { flags, positional } = parseArgs(argv);\n\n // Self-update is a recovery path: do not require valid user config, provider\n // metadata, or the DI container just to replace the installed CLI package.\n if (positional[0] === 'update') {\n const renderer = new TerminalRenderer();\n return runUpdateCommand(positional.slice(1), {\n cwd: process.cwd(),\n userHome: os.homedir(),\n renderer,\n flags,\n });\n }\n\n // `wstack resume <id>` is sugar for `wstack --resume <id>`.\n if (positional[0] === 'resume' && positional[1] && !subcommands['__noop_resume_marker']) {\n flags['resume'] = positional[1];\n positional.splice(0, 2);\n }\n\n let bootResult;\n try {\n bootResult = await bootConfig(flags);\n } catch (err) {\n writeErr(`Config error: ${toErrorMessage(err)}\\n`);\n return 2;\n }\n let { paths, config, vault } = bootResult;\n const first = positional[0];\n\n // Only an ordinary interactive CLI launch may offer backup recovery. Keep\n // subcommands, single-shot prompts, WebUI, and explicit skip modes silent.\n const mayOfferConfigRecovery =\n isStdinTTY() &&\n (positional.length === 0 || first === 'quick') &&\n (!config.activeProfile || config.activeProfile === 'default') &&\n typeof flags['prompt'] !== 'string' &&\n !flags['webui'] &&\n !flags['no-interactive'] &&\n !flags['skip'];\n const renderer = new TerminalRenderer();\n const reader = new ReadlineInputReader({ historyFile: paths.wpaths.historyFile });\n if (mayOfferConfigRecovery) {\n const restored = await maybeRestoreDefaultProfileFromBackup({\n globalRoot: paths.wpaths.globalRoot,\n profilePath: paths.wpaths.profileConfig('default'),\n renderer,\n reader,\n });\n if (restored) {\n try {\n bootResult = await bootConfig(flags);\n ({ paths, config, vault } = bootResult);\n } catch (err) {\n writeErr(`Config error after backup restore: ${toErrorMessage(err)}\\n`);\n await reader.close();\n return 2;\n }\n }\n }\n\n config = applySimpleUiFullAutoProfile(config, flags);\n const simpleUiFullAuto = isSimpleUiFullAuto(flags);\n const { cwd, projectRoot, userHome, wpaths, pathResolver } = paths;\n const profileConfigPath = activeProfileConfigPath(wpaths, config);\n void pathResolver; // used by callers via container binding\n\n // `wrongstack quick` \u2014 accept all defaults, list plugins, open TUI with F3 panel.\n // Handled here (before subcommand dispatch) so `wstack quick something` doesn't\n // accidentally fall through to single-shot mode.\n if (first === 'quick') {\n flags['quick'] = true;\n flags['tui'] = true;\n positional.splice(0, 1); // consume 'quick'\n const plugins = config?.plugins ?? [];\n if (plugins.length === 0) {\n console.debug('[wrongstack:quick] No plugins configured');\n } else {\n for (const p of plugins) {\n const name = typeof p === 'string' ? p : p.name;\n const enabled = typeof p === 'object' && p.enabled === false ? ' (disabled)' : '';\n console.debug(`[wrongstack:quick] plugin: ${name}${enabled}`);\n }\n }\n }\n\n const logger = new DefaultLogger({\n level: config.log.level,\n file: wpaths.logFile,\n // Suppress stderr output in TUI mode: plugin/library log messages\n // (e.g. Telegram \"getUpdates failed\") write directly to stderr and\n // bypass Ink, which breaks the Static/live boundary.\n // Logs still go to the disk file for post-hoc debugging.\n stderr: !flags.tui,\n });\n const modelsRegistry = new DefaultModelsRegistry({\n cacheFile: wpaths.modelsCache,\n // Force a refresh attempt once per CLI process. Model metadata changes faster\n // than releases (new model ids, corrected context windows), and stale cache\n // here directly affects runtime behavior like context bars and compaction.\n // If the network is unavailable, DefaultModelsRegistry still falls back to\n // stale cache or the bundled overlay instead of failing startup.\n ttlSeconds: 0,\n // Curated overlay merged on top of models.dev: fetched from GitHub raw for\n // freshness, with the bundled file as the offline floor.\n overlayUrl: GITHUB_PROVIDERS_OVERLAY_URL,\n overlayFile: resolveBundledOverlayFile(),\n overlayCacheFile: wpaths.modelsOverlayCache,\n });\n\n // Quick path: subcommand dispatch \u2014 run BEFORE network I/O so\n // Lightweight subcommands such as `wstack help` and `wstack version` do not\n // wait for models.dev. The deprecated `wstack init` compatibility handler is\n // dispatched here too, but current setup flows use `wstack auth`.\n if (first && subcommands[first]) {\n // Create container to get the SAME skillLoader instance that the main\n // interactive CLI uses. This ensures cache invalidation after\n // /skill-install propagates correctly to /skill and other commands.\n const container = createDefaultContainer({\n config,\n wpaths,\n logger,\n modelsRegistry,\n bundledSkillsDir: config.features.skills ? resolveBundledSkillsDir() : undefined,\n bundledPromptsDir: config.features.prompts === false ? undefined : resolveBundledPromptsDir(),\n });\n const sessionStore = container.resolve(TOKENS.SessionStore);\n const skillLoader = container.resolve(TOKENS.SkillLoader);\n const toolRegistryForSubcmd = new ToolRegistry();\n registerBuiltinToolTier({\n registry: toolRegistryForSubcmd,\n tier: normalizeTokenSavingTier(config.features.tokenSavingMode),\n });\n const code = await subcommands[first]?.(positional.slice(1), {\n config,\n renderer,\n reader,\n sessionStore,\n skillLoader,\n toolRegistry: toolRegistryForSubcmd,\n modelsRegistry,\n paths: wpaths,\n vault,\n cwd,\n projectRoot,\n userHome,\n flags,\n });\n await reader.close();\n return code;\n }\n\n // Safety guard: refuse to start when the current working directory is the\n // user's home directory. Running wstack in ~ risks creating a .git repo at\n // the top of the user's filesystem and treating every file under it as\n // project state. Utility subcommands (auth, version, etc.) were already\n // dispatched above and are not affected; this guard covers only session\n // launches (interactive, --webui, --no-interactive, quick, single-shot).\n if (isHomeDirectory(cwd, userHome)) {\n writeErr(\n `\\n ${color.red(color.bold('\u26A0 This is not a working directory.'))}\\n` +\n ` ${color.red('Please open wstack in a project folder.')}\\n\\n`,\n );\n await reader.close();\n return 1;\n }\n\n // Background update check is handled in preflight.ts \u2192 applyPrintUpdateNotice(),\n // which has a 2-second timeout and prints the \"Update available\" notice.\n // No fire-and-forget here \u2014 the preflight phase owns update notifications.\n\n // Blocking models.dev refresh \u2014 fetches fresh catalog before app starts.\n // --no-models-refresh skips this. On timeout (15s default) or network failure,\n // falls back to cache and logs a warning; the app still boots normally.\n if (!flags['no-models-refresh']) {\n try {\n await modelsRegistry.refresh();\n logger.info('models.dev catalog refreshed');\n } catch (err) {\n const msg = toErrorMessage(err);\n logger.warn(`models.dev refresh failed (${msg}); using cached catalog`);\n }\n }\n\n // Auto-discover model lists for openai-compatible gateways (omniroute, \u2026)\n // from their `/v1/models` endpoint and merge them into the catalog. Best-\n // effort: a down server or missing key is a logged no-op (cache fallback).\n try {\n await discoverAndMergeProviders({\n config,\n registry: modelsRegistry,\n cacheDir: path.dirname(wpaths.modelsCache),\n logger,\n });\n } catch (err) {\n logger.debug(`provider auto-discovery skipped: ${toErrorMessage(err)}`);\n }\n\n const isSingleShot = positional.length > 0 || typeof flags['prompt'] === 'string';\n // Skip interactive TTY prompts when: single-shot, --webui, or --no-interactive\n // --skip bypasses every interactive startup prompt (provider picker, launch\n // mode, indexing question) and uses saved preferences or sensible defaults.\n const isInteractiveTTY =\n isStdinTTY() && !isSingleShot && !flags['webui'] && !flags['no-interactive'] && !flags['skip'];\n\n if (isInteractiveTTY) {\n // If the current working directory has no .git repository, prompt the\n // user before proceeding \u2014 this lets them initialize one here instead\n // of the path resolver discovering a .git in a parent directory.\n await checkGitInCwd({ cwd, renderer, reader });\n\n const cont = await runProjectCheck({ projectRoot, cwd, renderer, reader });\n if (!cont) {\n await reader.close();\n return 0;\n }\n }\n\n // Early TUI TTY guard. The Ink TUI (run-tui.ts) requires a TTY on both stdin\n // and stdout and bails with exit 2 if either is piped. That guard runs late\n // (from execution.ts), so on an unconfigured machine the \"No provider or model\n // configured\" check below would fire first \u2014 both return 2, but a piped\n // `--tui` would then emit the wrong message. Hoist the TTY check here so a\n // non-interactive `--tui` always reports the interactive-terminal guidance\n // regardless of provider/model config state (see tui-smoke CI job).\n const wantsTui = flags['tui'] === true && flags['no-tui'] !== true;\n if (wantsTui && (!process.stdout.isTTY || !process.stdin.isTTY)) {\n writeErr(\n 'wstack: --tui requires an interactive terminal on both stdin and stdout.\\n' +\n ' Drop the flag (use the plain REPL) or run wstack directly without piping.\\n',\n );\n await reader.close();\n return 2;\n }\n\n // Provider + model selection\n const providerFlag = typeof flags['provider'] === 'string' ? flags['provider'] : undefined;\n const modelFlag = typeof flags['model'] === 'string' ? flags['model'] : undefined;\n // When --webui or --no-interactive is active, skip interactive picker and require config values\n const noInteractiveMode = flags['webui'] || flags['no-interactive'];\n // Non-interactive surfaces can't run the picker, so adopt a saved provider\n // (e.g. a custom one added via /auth) when the active pointers are unset \u2014\n // otherwise a custom-provider-only config fails the presence check below and\n // shows \"No provider or model configured\". The TUI reaches the picker instead.\n if (noInteractiveMode && (!config.provider || !config.model)) {\n const picked = await autoSelectSavedProvider(config, modelsRegistry);\n if (picked) config = patchConfig(config, picked);\n }\n if (!(!!providerFlag && !!modelFlag)) {\n if (isStdinTTY() && !noInteractiveMode) {\n let picked: PickerResult | undefined;\n let skipPicker = false;\n\n // --- Summary gate: saved provider/model from last session ---\n const savedProvider = config.provider;\n const savedModel = config.model;\n if (savedProvider && savedModel) {\n const savedStatus = await validateSavedProviderModel(config, modelsRegistry);\n renderer.write(\n `\\n ${color.dim('Last settings:')} ${color.bold(savedProvider)} / ${color.bold(savedModel)}\\n`,\n );\n if (!savedStatus.ok) {\n renderer.writeWarning(\n `Saved provider/model is no longer usable (${savedStatus.reason ?? 'unknown reason'}); choose a provider.\\n`,\n );\n } else {\n const answer = (\n await reader.readLine(\n ` ${color.amber('?')} Continue with these? ${color.dim('[Y/n/q]')} ${color.dim('(auto Y in 5s)')} `,\n { timeoutMs: 5000, defaultAnswer: 'y' },\n )\n )\n .trim()\n .toLowerCase();\n if (answer === 'q') {\n renderer.write(color.dim(' Goodbye!\\n'));\n await reader.close();\n return 0;\n }\n if (answer !== 'n' && answer !== 'no') {\n // Accepted \u2014 use saved values, skip the picker entirely\n skipPicker = true;\n renderer.write(\n `\\n ${color.green('\u25B6')} ${color.bold(savedProvider)} / ${color.bold(savedModel)}\\n\\n`,\n );\n }\n }\n }\n\n if (!skipPicker) {\n picked = await runPicker({\n modelsRegistry,\n renderer,\n reader,\n config,\n defaultProvider: providerFlag ?? config.provider,\n defaultModel: modelFlag ?? config.model,\n });\n }\n\n if (!picked && !skipPicker) {\n if (!config.provider || !config.model) {\n await reader.close();\n return 2;\n }\n }\n\n if (picked) {\n const prevProvider = config.provider;\n const prevModel = config.model;\n config = patchConfig(config, { provider: picked.provider, model: picked.model });\n if (picked.provider !== prevProvider || picked.model !== prevModel) {\n const saved = await saveToGlobalConfig(profileConfigPath, picked.provider, picked.model);\n if (saved) {\n renderer.writeInfo(`Saved ${picked.provider}/${picked.model} as default.\\n`);\n } else {\n renderer.writeWarning(\n `Could not save ${picked.provider}/${picked.model} to config. Check permissions or disk space.\\n`,\n );\n }\n }\n }\n } else if (!config.provider || !config.model) {\n writeErr(\n 'No provider or model configured. Run `wstack auth`, or pass --provider <id> --model <id>.\\n',\n );\n await reader.close();\n return 2;\n } else {\n const savedStatus = await validateSavedProviderModel(config, modelsRegistry);\n if (!savedStatus.ok) {\n writeErr(\n `Saved provider/model is no longer usable (${savedStatus.reason ?? 'unknown reason'}). Run \\`wstack auth\\` or pass --provider <id> --model <id>.\\n`,\n );\n await reader.close();\n return 2;\n }\n }\n }\n\n // --webui serves the browser UI alongside the terminal REPL and is mutually\n // exclusive with the Ink TUI (both own stdout). Pin the surface to REPL so the\n // launch picker below doesn't ask TUI/REPL and let a TUI choice shadow the\n // --webui branch in execution.ts (which is checked AFTER the TUI branch).\n if (flags['webui']) {\n flags['tui'] = false;\n flags['no-tui'] = true;\n }\n\n // Project registration is handled by core/boot.ts \u2192 registerProjectInManifest\n // during bootConfig. No duplicate needed here.\n\n // Mode + YOLO + Director + Autonomy prompts\n if (isInteractiveTTY) {\n let modePinned: 'tui' | 'repl' | undefined;\n if (flags['no-tui']) modePinned = 'repl';\n else if (flags['tui']) modePinned = 'tui';\n const yoloPinned: boolean | undefined =\n flags['no-yolo'] === true ? false : flags['yolo'] === true ? true : undefined;\n let autonomyPinned: 'off' | 'auto' | undefined;\n if (flags['no-autonomy'] === true) autonomyPinned = 'off';\n else if (flags['eternal'] === true)\n autonomyPinned = 'off'; // --eternal starts engine directly, skips launch-prompt autonomy\n else if (typeof flags['autonomy'] === 'string') {\n const v = (flags['autonomy'] as string).toLowerCase();\n autonomyPinned = v === 'off' || v === 'no' || v === 'false' ? 'off' : 'auto';\n } else if (flags['autonomy'] === true) {\n autonomyPinned = 'auto';\n }\n\n // Build saved preferences from config so the prompt can offer a one-line\n // \"Continue with these?\" summary instead of re-asking every question.\n const lastChoices = config.launch\n ? {\n mode: config.launch.mode ?? 'tui',\n yolo: config.yolo ?? true,\n autonomy: config.launch.autonomy ?? 'auto',\n }\n : undefined;\n\n let choices: Awaited<ReturnType<typeof runLaunchPrompts>>;\n try {\n choices = await runLaunchPrompts({\n renderer,\n reader,\n modePinned,\n yoloPinned,\n autonomyPinned,\n lastChoices,\n });\n } catch (err) {\n if (err instanceof LaunchAbortedError) {\n await reader.close();\n return 0;\n }\n throw err;\n }\n if (choices.mode === 'tui') {\n flags['tui'] = true;\n flags['no-tui'] = false;\n } else {\n flags['tui'] = false;\n flags['no-tui'] = true;\n }\n if (choices.yolo !== config.yolo) config = patchConfig(config, { yolo: choices.yolo });\n flags['autonomy'] = choices.autonomy;\n\n // First-run YOLO disclosure: when YOLO auto-enabled on the very first\n // interactive launch and was not explicitly pinned via --yolo or\n // --no-yolo, print a one-time notice to stderr so the user is aware\n // that non-denied tool calls (shell, file writes, etc.) run without\n // confirmation.\n if (shouldPrintYoloNotice(lastChoices, yoloPinned, choices.yolo)) {\n writeErr(\n `\\n ${color.yellow('YOLO is on')}: non-denied tool calls, including shell and file writes, run without confirmation.\\n` +\n ` ${color.dim('Explicit deny rules still apply. Use')} --no-yolo ${color.dim('or')} /yolo off ${color.dim('to require prompts.')}\\n\\n`,\n );\n }\n\n // --skip-index / --skip suppresses startup codebase indexing.\n if ((flags['skip-index'] || flags['skip']) && config.indexing) {\n config = patchConfig(config, {\n indexing: { ...config.indexing, onSessionStart: false },\n });\n }\n\n // Persist launch preferences so the next boot remembers them.\n // When --webui is active the mode is pinned to REPL (TUI owns stdout),\n // but we must NOT persist that choice \u2014 the user's last non-webui mode\n // (likely TUI) should survive so the next plain `wstack` session returns\n // to their preferred surface instead of silently landing in REPL.\n if (!simpleUiFullAuto) {\n try {\n const toPersist = flags['webui']\n ? { ...choices, mode: lastChoices?.mode ?? config.launch?.mode ?? 'tui' }\n : choices;\n await persistLaunchChoices(profileConfigPath, toPersist);\n } catch {\n // Best-effort \u2014 never blocks launch.\n }\n }\n\n await printLaunchHints(renderer, flags, {\n cursorFile: path.join(wpaths.cacheDir, 'hint-cursor'),\n });\n } else {\n // When skipping interactive prompts (--webui or --no-interactive), use saved\n // preferences or sensible defaults. Director stays OFF in non-interactive mode.\n // Autonomy defaults to the configured defaultMode (now 'auto') so non-interactive\n // sessions self-drive too \u2014 unless the user explicitly opts out with --no-autonomy\n // (or sets autonomy.defaultMode: 'off' in config).\n // Launch autonomy only supports 'off' | 'auto' (no 'suggest' surface here).\n // Respect an explicit opt-out (--no-autonomy or defaultMode 'off'); otherwise\n // default to 'auto' so non-interactive sessions self-drive too.\n const nonInteractiveAutonomy: 'off' | 'auto' =\n !simpleUiFullAuto && (flags['no-autonomy'] === true || config.autonomy?.defaultMode === 'off')\n ? 'off'\n : 'auto';\n const effectiveChoices = config.launch\n ? {\n mode: flags['no-tui'] ? 'repl' : (config.launch.mode ?? 'tui'),\n yolo: config.yolo ?? true,\n autonomy: nonInteractiveAutonomy,\n }\n : {\n mode: 'repl',\n yolo: true,\n autonomy: nonInteractiveAutonomy,\n };\n\n if (effectiveChoices.mode === 'repl') {\n flags['tui'] = false;\n flags['no-tui'] = true;\n }\n flags['autonomy'] = effectiveChoices.autonomy;\n }\n\n // Director Mode is permanently on.\n flags['director'] = true;\n\n return {\n config,\n vault,\n wpaths,\n cwd,\n projectRoot,\n userHome,\n flags,\n positional,\n modelsRegistry,\n renderer,\n reader,\n logger,\n needsSetup: !noInteractiveMode ? false : !config.provider || !config.model,\n };\n}\n\n/**\n * Check whether the current working directory has a `.git` repository.\n * If not, prompt the user before the path resolver walks up to a parent.\n * When the parent directory contains a `.git`, also inform the user so\n * they know why the project root was resolved to a different directory.\n */\nasync function checkGitInCwd(opts: {\n cwd: string;\n renderer: TerminalRenderer;\n reader: ReadlineInputReader;\n}): Promise<void> {\n const { cwd, renderer, reader } = opts;\n const cwdGit = path.join(cwd, '.git');\n\n let hasCwdGit = false;\n try {\n await fs.access(cwdGit);\n hasCwdGit = true;\n } catch {\n // no .git in cwd\n }\n\n if (!hasCwdGit) {\n renderer.write(\n `\\n ${color.amber('\u25CB')} This folder has no ${color.bold('.git')} repository.\\n`,\n );\n const answer = (\n await reader.readLine(` ${color.amber('?')} Initialize one here? ${color.dim('[y/N]')} `)\n )\n .trim()\n .toLowerCase();\n if (answer === 'y' || answer === 'yes') {\n try {\n const { spawn } = await import('node:child_process');\n await new Promise<void>((resolve, reject) => {\n const child = spawn('git', ['init'], {\n cwd,\n signal: AbortSignal.timeout(10_000),\n windowsHide: true,\n });\n child.on('error', reject);\n child.on('close', (code) =>\n code === 0 ? resolve() : reject(new Error(`git init failed with ${code}`)),\n );\n });\n renderer.write(` ${color.green('\u2713')} Git repository initialized\\n`);\n hasCwdGit = true;\n } catch (err) {\n renderer.writeError(`git init failed: ${toErrorMessage(err)}\\n`);\n }\n }\n }\n\n // Check only the immediate parent \u2014 inform the user if .git exists there.\n const parentDir = path.dirname(cwd);\n if (parentDir !== cwd) {\n try {\n await fs.access(path.join(parentDir, '.git'));\n renderer.write(\n ` ${color.dim('\u2139')} A ${color.bold('.git')} repo exists in the parent directory: ${color.dim(parentDir)}\\n`,\n );\n } catch {\n // parent has no .git \u2014 nothing to report\n }\n }\n}\n", "import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { color, toErrorMessage } from '@wrongstack/core/utils';\nimport { atomicWrite, backupConfigFile } from '@wrongstack/core/utils';\nimport type { ReadlineInputReader } from '../input-reader.js';\nimport type { TerminalRenderer } from '../renderer.js';\n\nexport interface ProviderConfigBackup {\n filePath: string;\n fileName: string;\n raw: string;\n providerIds: string[];\n modifiedAtMs: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction providerIds(value: unknown): string[] {\n if (!isRecord(value)) return [];\n const providers = value['providers'];\n return isRecord(providers) ? Object.keys(providers) : [];\n}\n\n/**\n * Recovery is intentionally based on the profile file itself, not the merged\n * runtime config. Project-local overrides must not hide an empty default\n * profile and prevent the user from recovering their global settings.\n */\nexport async function defaultProfileProvidersAreEmpty(profilePath: string): Promise<boolean> {\n try {\n const parsed: unknown = JSON.parse(await fs.readFile(profilePath, 'utf8'));\n return providerIds(parsed).length === 0;\n } catch {\n return false;\n }\n}\n\nfunction profileSnapshotTimestamp(fileName: string, fallback: number): number {\n const match =\n /^profiles-default-config-(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2})-(\\d{2})-(\\d{2})-(\\d{3})\\.json$/i.exec(\n fileName,\n );\n if (!match) return fallback;\n const [, year, month, day, hour, minute, second, millisecond] = match;\n return Date.UTC(\n Number(year),\n Number(month) - 1,\n Number(day),\n Number(hour),\n Number(minute),\n Number(second),\n Number(millisecond),\n );\n}\n\n/**\n * Find the newest valid default-profile snapshot that actually contains\n * providers. Profile config history uses names such as\n * `profiles-default-config-2026-07-19T12-34-56-789.json`.\n */\nexport async function findLatestProviderBackup(\n globalRoot: string,\n): Promise<ProviderConfigBackup | undefined> {\n const directory = path.join(globalRoot, 'config-history');\n const candidates: Array<{ filePath: string; fileName: string; modifiedAtMs: number }> = [];\n\n let entries;\n try {\n entries = await fs.readdir(directory, { withFileTypes: true });\n } catch {\n return undefined;\n }\n for (const entry of entries) {\n if (\n !entry.isFile() ||\n !/^profiles-default-config-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-\\d{3}\\.json$/i.test(entry.name)\n ) {\n continue;\n }\n const filePath = path.join(directory, entry.name);\n try {\n const stat = await fs.stat(filePath);\n candidates.push({\n filePath,\n fileName: entry.name,\n modifiedAtMs: profileSnapshotTimestamp(entry.name, stat.mtimeMs),\n });\n } catch {\n // File disappeared between readdir and stat; skip it.\n }\n }\n\n candidates.sort((a, b) => b.modifiedAtMs - a.modifiedAtMs);\n for (const candidate of candidates) {\n try {\n const raw = await fs.readFile(candidate.filePath, 'utf8');\n const parsed: unknown = JSON.parse(raw);\n const ids = providerIds(parsed);\n if (ids.length === 0) continue;\n return { ...candidate, raw, providerIds: ids };\n } catch {\n // A broken/newer backup must not prevent using the next valid snapshot.\n }\n }\n return undefined;\n}\n\nexport async function restoreDefaultProfileBackup(opts: {\n backup: ProviderConfigBackup;\n globalRoot: string;\n profilePath: string;\n}): Promise<void> {\n await backupConfigFile(opts.profilePath, { globalRoot: opts.globalRoot });\n await fs.mkdir(path.dirname(opts.profilePath), { recursive: true });\n await atomicWrite(opts.profilePath, opts.backup.raw, { mode: 0o600 });\n}\n\n/** Prompt once during an ordinary interactive boot. Enter accepts recovery. */\nexport async function maybeRestoreDefaultProfileFromBackup(opts: {\n globalRoot: string;\n profilePath: string;\n renderer: TerminalRenderer;\n reader: ReadlineInputReader;\n}): Promise<boolean> {\n if (!(await defaultProfileProvidersAreEmpty(opts.profilePath))) return false;\n\n const backup = await findLatestProviderBackup(opts.globalRoot);\n if (!backup) return false;\n\n const shownProviders = backup.providerIds.slice(0, 5).join(', ');\n const remainder = backup.providerIds.length - 5;\n const providerSummary = remainder > 0 ? `${shownProviders} +${remainder}` : shownProviders;\n opts.renderer.write(\n `\\n ${color.amber('\u25CB')} ${color.bold('default')} profile has no saved providers.\\n` +\n ` ${color.dim('Latest usable backup:')} ${color.bold(backup.fileName)} ` +\n `${color.dim(`(${backup.providerIds.length} provider: ${providerSummary})`)}\\n`,\n );\n\n const answer = (\n await opts.reader.readLine(\n ` ${color.amber('?')} Restore all settings from this backup? ${color.dim('[Y/n]')} `,\n )\n )\n .trim()\n .toLowerCase();\n if (answer === 'n' || answer === 'no') return false;\n\n try {\n await restoreDefaultProfileBackup({\n backup,\n globalRoot: opts.globalRoot,\n profilePath: opts.profilePath,\n });\n opts.renderer.write(\n ` ${color.green('\u2713')} Restored all settings from ${color.dim(backup.fileName)}\\n`,\n );\n return true;\n } catch (err) {\n opts.renderer.writeWarning(`Could not restore config backup: ${toErrorMessage(err)}\\n`);\n return false;\n }\n}\n", "import type { BootConfigOptions } from '@wrongstack/core/infrastructure';\nimport type { Config } from '@wrongstack/core/types';\nimport { bootConfig as coreBootConfig } from '@wrongstack/core/infrastructure';\nimport type { WstackPaths } from '@wrongstack/core/utils';\nimport type { DefaultPathResolver } from '@wrongstack/core/infrastructure';\n\nexport interface BootPaths {\n cwd: string;\n projectRoot: string;\n userHome: string;\n wpaths: WstackPaths;\n pathResolver: DefaultPathResolver;\n}\n\nexport interface BootConfigResult {\n paths: BootPaths;\n config: Config;\n vault: BootConfigVault;\n}\n\n/** The concrete vault type returned by the core boot routine. */\ntype BootConfigVault = Awaited<ReturnType<typeof coreBootConfig>>['vault'];\n\n/**\n * Thin CLI wrapper over the canonical `bootConfig` in `@wrongstack/core`.\n * Re-shapes the core result into the CLI's historical `{ paths, config, vault }`\n * return type. All real boot behavior (path resolution, vault, secret\n * migration, config + sync loading) lives in core so the CLI and the WebUI\n * server can't drift.\n */\nexport async function bootConfig(\n flags: Record<string, string | boolean>,\n): Promise<BootConfigResult> {\n const isWebui = !!flags['webui'];\n const opts: BootConfigOptions = {\n flags,\n appLabel: 'wstack',\n ...(isWebui ? { skipIdentityValidation: true } : {}),\n };\n const { cwd, projectRoot, userHome, wpaths, pathResolver, config, vault } =\n await coreBootConfig(opts);\n return {\n paths: { cwd, projectRoot, userHome, wpaths, pathResolver },\n config,\n vault,\n };\n}\n", "import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as readline from 'node:readline';\nimport type { InputReader, PromptOption } from '@wrongstack/core/types';\nimport { resolveWstackPaths, setOutputLineGuard, setRawMode, writeOut } from '@wrongstack/core/utils';\n\nexport interface ReadlineInputReaderOptions {\n historyFile?: string | undefined;\n prompt?: string | undefined;\n}\n\nexport class ReadlineInputReader implements InputReader {\n private rl?: readline.Interface | undefined;\n private readonly historyFile: string;\n private history: string[] = [];\n private pending = false;\n private suppressNextHistory = false;\n\n constructor(opts: ReadlineInputReaderOptions = {}) {\n this.historyFile =\n opts.historyFile ?? resolveWstackPaths({ projectRoot: process.cwd() }).historyFile;\n }\n\n private async loadHistory(): Promise<void> {\n try {\n const raw = await fs.readFile(this.historyFile, 'utf8');\n this.history = raw.split('\\n').filter(Boolean).slice(-1000);\n } catch {\n this.history = [];\n }\n }\n\n private async saveHistory(): Promise<void> {\n try {\n await fs.mkdir(path.dirname(this.historyFile), { recursive: true });\n await fs.writeFile(this.historyFile, this.history.slice(-1000).join('\\n'));\n } catch {\n // ignore\n }\n }\n\n private shouldPersistHistory(line: string): boolean {\n return !/^\\s*\\/(?:telegram-setup|tg-setup)\\s+\\d+:[A-Za-z0-9_-]+(?:\\s|$)/i.test(line);\n }\n\n private ensure(): readline.Interface {\n if (!this.rl) {\n this.rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n history: this.history,\n terminal: process.stdin.isTTY,\n });\n }\n return this.rl;\n }\n\n async readLine(\n prompt?: string,\n timeoutOpts?: { timeoutMs: number; defaultAnswer: string } | undefined,\n ): Promise<string> {\n if (this.history.length === 0) await this.loadHistory();\n while (this.pending) {\n // Wait for the current read to settle before accepting another.\n await new Promise<void>((resolve) => setTimeout(resolve, 50));\n }\n this.pending = true;\n try {\n // Tear down any stale interface *and await its full close event*\n // before creating a replacement. On Windows, readline listeners\n // linger past .close() \u2014 if the new interface attaches while the\n // old one is still draining, both fire for every keystroke and the\n // user sees every typed character doubled (5\u219255, 2\u219222).\n if (this.rl) {\n const old = this.rl;\n this.rl = undefined;\n await new Promise<void>((resolve) => {\n // If the interface is already closed/closing the 'close' event\n // may fire synchronously or on the next tick \u2014 the promise\n // handles both.\n if ((old as never as { closed?: boolean | undefined }).closed) {\n resolve();\n } else {\n old.once('close', resolve);\n old.close();\n }\n });\n }\n const fresh = this.ensure();\n // While this prompt is on screen, bracket every out-of-band write\n // (logger WARN/INFO, async Telegram activity) so it can't strand the\n // half-typed draft in scrollback. Cleared the moment the read settles.\n this.installPromptGuard(fresh);\n return new Promise<string>((resolve) => {\n let settled = false;\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined;\n\n const settle = (line: string): void => {\n if (settled) return;\n settled = true;\n if (timeoutHandle) clearTimeout(timeoutHandle);\n setOutputLineGuard(null);\n resolve(line);\n };\n\n // When a timeout is configured, auto-feed the default answer\n // after `timeoutMs` milliseconds. `fresh.write()` programmatically\n // feeds the readline parser as if the user typed it \u2014 the question\n // callback fires naturally and the default text appears on screen\n // so the user sees what happened.\n if (timeoutOpts) {\n timeoutHandle = setTimeout(() => {\n if (!settled) {\n fresh.write(`${timeoutOpts.defaultAnswer}\\n`);\n }\n }, timeoutOpts.timeoutMs);\n }\n\n fresh.question(prompt ?? '> ', (line) => {\n const persistHistory = !this.suppressNextHistory && this.shouldPersistHistory(line);\n this.suppressNextHistory = false;\n if (line.trim() && persistHistory) {\n this.history.push(line);\n // Fire-and-forget: saveHistory logs its own errors; we intentionally\n // don't await or .catch() here \u2014 failing to write history must not\n // block the user input path. Using the two-arg .then() form (not\n // .catch()) so TypeScript flags if the Promise type ever changes.\n this.saveHistory().then(undefined, () => {\n /* intentionally empty */\n });\n }\n settle(line);\n });\n // Ctrl+C closes the readline interface \u2014 resolve with empty\n // string so callers treat it as cancel instead of crashing with\n // an unhandled EOF error.\n fresh.once('close', () => settle(''));\n // Handle any unexpected throw inside the executor by settling to\n // empty string so callers treat it as cancel rather than crashing.\n fresh.on?.('error', (_e: unknown) => settle(''));\n }).then((result) => {\n // Close the interface so the next readLine call tears it down\n // first (see the guard above). On Windows / Node \u2265 24 the\n // interface can enter an internally-closed state after\n // question() resolves; reusing it throws ERR_USE_AFTER_CLOSE.\n // Drop our reference before closing as well. Keeping a closed\n // interface reachable made the next terminal owner inherit stale\n // readline state during the boot-prompt -> Ink handoff.\n if (this.rl === fresh) this.rl = undefined;\n fresh.close();\n return result;\n });\n } finally {\n this.pending = false;\n }\n }\n\n /**\n * Install the out-of-band write guard for the active prompt. When a log\n * line or other async output lands while the user is mid-type, the guard\n * clears the draft row, lets the message print, then repaints the prompt\n * and the in-progress draft (cursor preserved) via readline's own\n * refresh. Without it, each async write leaves the half-typed line\n * stranded as a fresh scrollback row.\n *\n * No-op on non-TTY output (piped/redirected) \u2014 there's no draft to\n * protect and the ANSI clear/repaint would be noise in a file.\n */\n private installPromptGuard(rl: readline.Interface): void {\n const out = process.stdout;\n if (!out.isTTY) {\n setOutputLineGuard(null);\n return;\n }\n setOutputLineGuard({\n suspend(): void {\n // Carriage-return to column 0 and erase the whole row so the\n // out-of-band line prints onto clean terminal space.\n readline.cursorTo(out, 0);\n readline.clearLine(out, 0);\n },\n resume(): void {\n // `prompt(true)` re-emits the prompt + current line buffer and\n // restores the cursor column, so editing-in-place survives the\n // interruption. Guarded: the interface may have closed between the\n // write being issued and this callback firing.\n try {\n rl.prompt(true);\n } catch {\n // readline closed mid-write \u2014 nothing left to repaint.\n }\n },\n });\n }\n\n async readKey(prompt: string, options: PromptOption[]): Promise<string> {\n // This flow drives stdin directly; no readline prompt to protect.\n setOutputLineGuard(null);\n writeOut(prompt);\n return new Promise<string>((resolve) => {\n const stdin = process.stdin;\n const wasRaw = stdin.isRaw;\n const wasPaused = stdin.isPaused();\n setRawMode(stdin, true);\n stdin.resume();\n const onData = (buf: Buffer) => {\n const key = buf.toString();\n // Ctrl+C \u2014 treat as cancel (resolve with empty string).\n if (key === '\\x03') {\n cleanup();\n writeOut('\\n');\n resolve('');\n return;\n }\n const opt = options.find(\n (o) => o.key.toLowerCase() === key.toLowerCase() || o.value === key,\n );\n if (opt) {\n cleanup();\n writeOut(`${opt.key}\\n`);\n resolve(opt.value);\n }\n };\n const onClose = () => {\n cleanup();\n resolve('');\n };\n const cleanup = () => {\n stdin.off('data', onData);\n stdin.off('close', onClose);\n setRawMode(stdin, wasRaw);\n if (wasPaused) stdin.pause();\n };\n stdin.on('data', onData);\n stdin.on('close', onClose);\n });\n }\n\n /**\n * Read a line of input while masking each character with a bullet so the\n * user gets visual confirmation that bytes are arriving (especially on\n * paste, which previously felt like nothing happened). Pasted chunks\n * are echoed as a run of bullets, Backspace/DEL erases one bullet, and\n * Ctrl+U / Ctrl+T are honored. Non-TTY input is read normally \u2014 there's\n * nothing to hide when piped, and echoing bullets to a file is noise.\n *\n * Returns the raw entered string (no trim \u2014 caller decides).\n */\n async readSecret(prompt: string): Promise<string> {\n const stdin = process.stdin;\n if (!stdin.isTTY) {\n this.suppressNextHistory = true;\n return this.readLine(prompt);\n }\n // Tear down the active readline so we can take over stdin.\n setOutputLineGuard(null);\n this.rl?.close();\n this.rl = undefined;\n writeOut(prompt);\n return new Promise<string>((resolve) => {\n let buf = '';\n const wasRaw = stdin.isRaw;\n const cleanup = () => {\n stdin.off('data', onData);\n setRawMode(stdin, wasRaw);\n stdin.pause();\n };\n\n // setRawMode/resume must be inside try-catch so cleanup always\n // runs on setup failure \u2014 otherwise stdin stays in raw mode and\n // the terminal becomes unusable.\n try {\n setRawMode(stdin, true);\n stdin.resume();\n stdin.setEncoding('utf8');\n } catch (setupErr) {\n // Restore state before propagating\n setRawMode(stdin, wasRaw);\n stdin.pause();\n throw setupErr;\n }\n\n const eraseChar = () => {\n // Move cursor back, overwrite with space, move back again.\n writeOut('\\b \\b');\n };\n const eraseAll = () => {\n for (let i = 0; i < buf.length; i++) eraseChar();\n };\n\n const onData = (chunk: string) => {\n // Process the whole chunk at once \u2014 paste arrives as one event.\n // We walk char-by-char so embedded control bytes (e.g. a stray\n // CR inside a paste) terminate input cleanly.\n for (const ch of chunk) {\n if (ch === '\\r' || ch === '\\n') {\n cleanup();\n writeOut(` ${dim(`[${buf.length} chars]`)}\\n`);\n resolve(buf);\n return;\n }\n if (ch === '\u0003') {\n // Ctrl+C \u2014 resolve with empty string like readLine/readKey\n // instead of process.exit(130), so the event bus cleanup,\n // session save, and log flush handlers have a chance to run.\n cleanup();\n writeOut('\\n');\n resolve('');\n return;\n }\n if (ch === '\u0015') {\n // Ctrl+U \u2014 clear line\n eraseAll();\n buf = '';\n continue;\n }\n if (ch === '\u0017') {\n // Ctrl+T \u2014 erase last whitespace-delimited token\n const m = buf.match(/(\\S+\\s*)$/);\n const drop = m ? m[0].length : buf.length;\n for (let i = 0; i < drop; i++) eraseChar();\n buf = buf.slice(0, buf.length - drop);\n continue;\n }\n if (ch === '\u007F' || ch === '\\b') {\n if (buf.length > 0) {\n buf = buf.slice(0, -1);\n eraseChar();\n }\n continue;\n }\n // Skip other control bytes silently (escape sequences, etc.).\n if (ch < ' ') continue;\n buf += ch;\n writeOut('\u2022');\n }\n };\n stdin.on('data', onData);\n });\n }\n\n async close(): Promise<void> {\n setOutputLineGuard(null);\n await this.saveHistory();\n this.rl?.close();\n this.rl = undefined;\n }\n}\n\n// Local ANSI dim \u2014 kept inline so this module has no @wrongstack/core\n// dependency for its single visual flourish.\nfunction dim(s: string): string {\n if (!process.stdout.isTTY) return s;\n return `\u001B[2m${s}\u001B[22m`;\n}\n", "/**\n * Launch-time feature hints. Shown once per CLI launch \u2014 after the\n * provider/model/mode/YOLO prompts have resolved and right before the\n * REPL or TUI starts \u2014 to remind users what slash commands, flags, and\n * runtime controls this build ships with. Suppress with `--no-hints` or\n * `WRONGSTACK_NO_HINTS=1`.\n *\n * Rather than dumping every category at once, each launch shows ONE\n * category and rotates to the next on the following launch (round-robin\n * via a tiny persisted cursor). So you see Autonomy one boot, agent tools\n * the next, workspace integrations after that \u2014 bite-sized, and the whole\n * set still comes around quickly. `/help` lists everything on demand.\n *\n * The list is intentionally hand-curated rather than auto-derived from\n * the slash-command registry: a one-line blurb tuned for each entry\n * lands better than `command.description` boilerplate.\n */\n\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { color } from '@wrongstack/core/utils';\nimport type { TerminalRenderer } from './renderer.js';\n\ninterface Hint {\n readonly key: string;\n readonly blurb: string;\n}\n\ninterface HintGroup {\n readonly title: string;\n readonly items: readonly Hint[];\n}\n\nconst GROUPS: readonly HintGroup[] = [\n {\n title: 'Autonomy',\n items: [\n { key: '/goal <text>', blurb: 'lock in a verifiable mission \u2014 only Esc / Ctrl+C interrupt' },\n {\n key: '/autonomy eternal',\n blurb: 'sense \u2192 decide \u2192 execute \u2192 reflect loop until you stop it',\n },\n {\n key: '--eternal \"<mission>\"',\n blurb: 'boot directly into the eternal-autonomy engine with a mission',\n },\n {\n key: '/autonomy on|suggest',\n blurb: 'self-driving: auto-pick next step or just suggest it',\n },\n ],\n },\n {\n title: 'Agents & fleet',\n items: [\n {\n key: '/delegate [--role=<role>] <task>',\n blurb: 'route work to a specialist; omit --role for automatic selection',\n },\n {\n key: '/spawn [-p <provider>] [-m <model>] [-n <name>] <task>',\n blurb: 'launch one isolated subagent with optional runtime overrides',\n },\n {\n key: '/agents [list|show <id>|stream on|off]',\n blurb: 'open the TUI monitor, inspect a subagent, or control its activity stream',\n },\n {\n key: '/fleet status|usage|kill|log|manifest',\n blurb: 'inspect and control the active subagent fleet',\n },\n ],\n },\n {\n title: 'Steering',\n items: [\n {\n key: 'Esc (while busy)',\n blurb: 'soft interrupt \u2014 next message carries a STEERING preamble',\n },\n { key: '/steer <text>', blurb: 'mid-flight redirect, works when Esc is eaten by tmux' },\n { key: '/btw <note>', blurb: 'non-aborting nudge \u2014 agent folds it in at its next step' },\n {\n key: 'Ctrl+C \u00D7 1 / \u00D7 2 / \u00D7 3',\n blurb: 'cancel iteration \u00B7 force-exit Ink \u00B7 hard exit(130)',\n },\n ],\n },\n {\n title: 'Modes & context',\n items: [\n {\n key: '/mode',\n blurb: 'switch persona: code-reviewer, debugger, architect, tester, devops, \u2026',\n },\n { key: '/model', blurb: 'two-step provider \u2192 model picker, hot-swap at runtime' },\n { key: '/yolo on|off|toggle', blurb: 'auto-approve tool calls without restart' },\n {\n key: '/context mode frugal|balanced|deep|archival',\n blurb: 'pick how aggressively history is trimmed',\n },\n { key: '/compact', blurb: 'manually compact the in-flight context window' },\n {\n key: '/plan show|add|start|done',\n blurb: 'strategic roadmap, survives /resume across sessions',\n },\n ],\n },\n {\n title: 'Workspace tools',\n items: [\n {\n key: '@<query>',\n blurb: 'search project files and insert a path into the prompt',\n },\n {\n key: 'Alt+V \u00B7 /image',\n blurb: 'attach a clipboard image in the TUI',\n },\n {\n key: '/mcp \u00B7 wstack mcp add <name>',\n blurb: 'inspect or connect MCP servers',\n },\n {\n key: '/plugin install|enable|disable <name>',\n blurb: 'manage optional integrations such as Telegram or LSP',\n },\n {\n key: '/skill \u00B7 /init \u00B7 /commit',\n blurb: 'browse skills \u00B7 scaffold project guidance \u00B7 draft a commit',\n },\n {\n key: '/diag \u00B7 wstack usage \u00B7 wstack resume <id>',\n blurb: 'inspect diagnostics, review costs, or continue an earlier session',\n },\n ],\n },\n] as const;\n\n/**\n * Total number of hints across all groups. Exported so callers can\n * assert \"\u2265 20\" in tests without re-counting.\n */\nexport const HINT_COUNT: number = GROUPS.reduce((n, g) => n + g.items.length, 0);\n\n/** Number of rotating categories. */\nexport const HINT_GROUP_COUNT: number = GROUPS.length;\n\n/** Category titles, in rotation order. Exported for tests. */\nexport const HINT_GROUP_TITLES: readonly string[] = GROUPS.map((g) => g.title);\n\nfunction shouldSuppress(flags: Record<string, string | boolean>): boolean {\n if (flags['no-hints'] === true) return true;\n if (flags['hints'] === false) return true;\n const env = process.env.WRONGSTACK_NO_HINTS;\n if (env && env !== '0' && env.toLowerCase() !== 'false') return true;\n return false;\n}\n\nexport interface LaunchHintOptions {\n /**\n * File holding the rotation cursor. When set, each call advances it so\n * consecutive launches show different categories (round-robin). Missing\n * or unreadable file starts the rotation at the first category.\n */\n readonly cursorFile?: string | undefined;\n /**\n * Force a specific category index (wraps around). Overrides the cursor.\n * Mainly for tests and `--hints`-style explicit selection.\n */\n readonly groupIndex?: number | undefined;\n /** Terminal width used to wrap long hint rows. Defaults to stdout width. */\n readonly termWidth?: number | undefined;\n}\n\nconst DEFAULT_TERM_WIDTH = 80;\nconst MIN_TERM_WIDTH = 20;\nconst HINT_INDENT = ' ';\nconst HINT_CONTINUATION_INDENT = ' ';\n\nconst wrap = (n: number): number => ((n % GROUPS.length) + GROUPS.length) % GROUPS.length;\n\nfunction displayWidth(value: string): number {\n return [...value].length;\n}\n\nfunction wrapWords(value: string, firstWidth: number, continuationWidth = firstWidth): string[] {\n const words = value.trim().split(/\\s+/).filter(Boolean);\n const lines: string[] = [];\n let line = '';\n let width = Math.max(1, firstWidth);\n\n for (const sourceWord of words) {\n let word = sourceWord;\n while (word) {\n if (line) {\n if (displayWidth(line) + 1 + displayWidth(word) <= width) {\n line += ` ${word}`;\n word = '';\n } else {\n lines.push(line);\n line = '';\n width = Math.max(1, continuationWidth);\n }\n continue;\n }\n\n if (displayWidth(word) <= width) {\n line = word;\n word = '';\n } else {\n const characters = [...word];\n lines.push(characters.slice(0, width).join(''));\n word = characters.slice(width).join('');\n width = Math.max(1, continuationWidth);\n }\n }\n }\n\n if (line) lines.push(line);\n return lines;\n}\n\nfunction renderHintLines(item: Hint, termWidth: number): string[] {\n const inline = `${HINT_INDENT}${item.key} \u2014 ${item.blurb}`;\n if (displayWidth(inline) <= termWidth) {\n return [\n `${HINT_INDENT}${color.bold(item.key)} ${color.dim('\u2014')} ${color.dim(item.blurb)}`,\n ];\n }\n\n const lines: string[] = [];\n const keyLines = wrapWords(\n item.key,\n termWidth - displayWidth(HINT_INDENT),\n termWidth - displayWidth(HINT_CONTINUATION_INDENT),\n );\n keyLines.forEach((line, index) => {\n const indent = index === 0 ? HINT_INDENT : HINT_CONTINUATION_INDENT;\n lines.push(`${indent}${color.bold(line)}`);\n });\n\n const blurbLines = wrapWords(\n `\u2014 ${item.blurb}`,\n termWidth - displayWidth(HINT_CONTINUATION_INDENT),\n );\n for (const line of blurbLines) lines.push(`${HINT_CONTINUATION_INDENT}${color.dim(line)}`);\n return lines;\n}\n\nfunction renderHeaderLines(group: HintGroup, groupIndex: number, termWidth: number): string[] {\n const progress = `${groupIndex + 1}/${GROUPS.length}`;\n const plain = ` ${group.title} ${progress}`;\n if (displayWidth(plain) <= termWidth) {\n return [\n ` ${color.cyan('\u25C7')} ${color.bold(group.title)} ${color.dim(progress)}`,\n ` ${color.dim('\u2500'.repeat(Math.min(termWidth - 2, 48)))}`,\n ];\n }\n\n return [\n ` ${color.cyan('\u25C7')} ${color.bold(group.title)}`,\n ` ${color.dim('\u2500'.repeat(Math.min(termWidth - 2, 48)))}`,\n ];\n}\n\nfunction renderFooterLines(termWidth: number): string[] {\n const footer = '/help lists everything \u00B7 hide with --no-hints';\n if (displayWidth(` ${footer}`) <= termWidth) {\n return [\n ` ${color.dim('\u2500'.repeat(Math.min(termWidth - 2, 48)))}`,\n ` ${color.dim(`${color.bold('/help')} lists everything \u00B7 hide with ${color.bold('--no-hints')}`)}`,\n ];\n }\n\n return [\n ...wrapWords(footer, termWidth - 2).map((line) => ` ${color.dim(line)}`),\n ];\n}\n\n/**\n * Pick the category to show. Priority: explicit `groupIndex` \u2192 persisted\n * round-robin cursor \u2192 random. Advancing the cursor is best-effort; any\n * filesystem error falls back to a random category so a boot is never\n * blocked on hint bookkeeping.\n */\nasync function pickGroupIndex(opts: LaunchHintOptions): Promise<number> {\n if (typeof opts.groupIndex === 'number') return wrap(opts.groupIndex);\n if (opts.cursorFile) {\n try {\n let current = 0;\n try {\n const raw = await fs.readFile(opts.cursorFile, 'utf8');\n const parsed = Number.parseInt(raw.trim(), 10);\n if (Number.isFinite(parsed)) current = wrap(parsed);\n } catch {\n // No cursor yet \u2014 start at the first category.\n }\n await fs.mkdir(path.dirname(opts.cursorFile), { recursive: true });\n await fs.writeFile(opts.cursorFile, String(wrap(current + 1)));\n return current;\n } catch {\n // Fall through to random on any FS error.\n }\n }\n return Math.floor(Math.random() * GROUPS.length);\n}\n\n/**\n * Print one rotating category of launch hints to `renderer`. No-op when\n * suppressed via `--no-hints` or `WRONGSTACK_NO_HINTS=1`.\n */\nexport async function printLaunchHints(\n renderer: Pick<TerminalRenderer, 'write'>,\n flags: Record<string, string | boolean>,\n opts: LaunchHintOptions = {},\n): Promise<void> {\n if (shouldSuppress(flags)) return;\n\n const idx = await pickGroupIndex(opts);\n const group = GROUPS[idx];\n if (!group) return;\n const termWidth = Math.max(\n MIN_TERM_WIDTH,\n Math.floor(opts.termWidth ?? process.stdout.columns ?? DEFAULT_TERM_WIDTH),\n );\n\n const lines: string[] = [];\n lines.push('');\n lines.push(...renderHeaderLines(group, idx, termWidth));\n for (const item of group.items) lines.push(...renderHintLines(item, termWidth));\n lines.push('');\n lines.push(...renderFooterLines(termWidth));\n lines.push('');\n\n renderer.write(`${lines.join('\\n')}\\n`);\n}\n", "// Project detection \u2014 scans the working directory for AGENTS.md or a recognized\n// manifest, scaffolds AGENTS.md on request, and decides whether to bail out.\n\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { color, toErrorMessage } from '@wrongstack/core/utils';\nimport type { ReadlineInputReader } from '../input-reader.js';\nimport type { TerminalRenderer } from '../renderer.js';\nimport { detectProjectFacts, renderAgentsTemplate } from '../services/project-facts.js';\n\nexport type ProjectKind =\n /** `.wrongstack/AGENTS.md` exists \u2014 fully set up. */\n | 'initialized'\n /** Has a recognizable manifest (package.json, pyproject.toml, etc.) but no AGENTS.md yet. */\n | 'project'\n /** No manifest, no AGENTS.md \u2014 probably an empty/scratch directory. */\n | 'empty';\n\nconst MANIFESTS = [\n 'package.json',\n 'pyproject.toml',\n 'Cargo.toml',\n 'go.mod',\n 'Makefile',\n 'pom.xml',\n 'build.gradle',\n 'build.gradle.kts',\n 'composer.json',\n 'Gemfile',\n];\n\nexport async function detectProjectKind(projectRoot: string): Promise<ProjectKind> {\n try {\n await fs.access(path.join(projectRoot, '.wrongstack', 'AGENTS.md'));\n return 'initialized';\n } catch {\n // not initialized\n }\n for (const m of MANIFESTS) {\n try {\n await fs.access(path.join(projectRoot, m));\n return 'project';\n } catch {\n // try next\n }\n }\n return 'empty';\n}\n\nasync function scaffoldAgentsMd(projectRoot: string): Promise<string> {\n const dir = path.join(projectRoot, '.wrongstack');\n const file = path.join(dir, 'AGENTS.md');\n const facts = await detectProjectFacts(projectRoot);\n const body = renderAgentsTemplate(facts);\n await fs.mkdir(dir, { recursive: true });\n await fs.writeFile(file, body, 'utf8');\n return file;\n}\n\n/**\n * Print a one-line project status banner and, when relevant, prompt the\n * user about scaffolding `AGENTS.md` or continuing in a directory that\n * doesn't look like a project. Returns `false` if the user bailed out.\n */\nexport async function runProjectCheck(opts: {\n projectRoot: string;\n /** The actual working directory \u2014 where the user is standing. Git init\n * always happens here, never in a parent projectRoot that the walk-up\n * detected. */\n cwd: string;\n renderer: TerminalRenderer;\n reader: ReadlineInputReader;\n}): Promise<boolean> {\n const { projectRoot, cwd, renderer, reader } = opts;\n const kind = await detectProjectKind(projectRoot);\n\n if (kind === 'initialized') {\n renderer.write(\n `\\n ${color.green('\u2713')} Project initialized ${color.dim(`(${path.join(projectRoot, '.wrongstack', 'AGENTS.md')})`)}\\n`,\n );\n return true;\n }\n\n if (kind === 'project') {\n renderer.write(\n `\\n ${color.amber('\u25CF')} Project detected ${color.dim(`(${projectRoot})`)} but ${color.bold('.wrongstack/AGENTS.md')} is missing.\\n`,\n );\n const answer = (\n await reader.readLine(\n ` ${color.amber('?')} Scaffold ${color.bold('AGENTS.md')} now? ${color.dim('[y/N/q]')} `,\n )\n )\n .trim()\n .toLowerCase();\n if (answer === 'q') {\n renderer.write(color.dim(' Cancelled.\\n'));\n return false;\n }\n if (answer === 'y' || answer === 'yes') {\n try {\n const file = await scaffoldAgentsMd(projectRoot);\n renderer.write(` ${color.green('\u2713')} Wrote ${color.dim(file)}\\n`);\n } catch (err) {\n renderer.writeError(\n `Failed to scaffold AGENTS.md: ${toErrorMessage(err)}`,\n );\n }\n }\n return true;\n }\n\n // 'empty' \u2014 no manifest, no AGENTS.md, possibly no git\n const gitDir = path.join(projectRoot, '.git');\n let hasGit = false;\n try {\n await fs.access(gitDir);\n hasGit = true;\n } catch {\n // no git\n }\n\n if (!hasGit) {\n renderer.write(\n `\\n ${color.dim('\u25CB')} ${color.dim(`No project manifest in ${projectRoot} \u2014 running in a scratch directory.`)}\\n`,\n );\n const answer = (\n await reader.readLine(\n ` ${color.amber('?')} No git repo found. ${color.bold('Initialize git?')} ${color.dim('[y/N/q]')} `,\n )\n )\n .trim()\n .toLowerCase();\n if (answer === 'q') {\n renderer.write(color.dim(' Cancelled.\\n'));\n return false;\n }\n if (answer === 'y' || answer === 'yes') {\n try {\n const { spawn } = await import('node:child_process');\n await new Promise<void>((resolve, reject) => {\n const child = spawn('git', ['init'], {\n cwd,\n signal: AbortSignal.timeout(10_000),\n windowsHide: true,\n });\n child.on('error', reject);\n child.on('close', (code) =>\n code === 0 ? resolve() : reject(new Error(`git init failed with ${code}`)),\n );\n });\n renderer.write(` ${color.green('\u2713')} Git repository initialized\\n`);\n } catch (err) {\n renderer.writeError(\n `git init failed: ${toErrorMessage(err)}\\n`,\n );\n }\n }\n } else {\n renderer.write(\n `\\n ${color.dim('\u25CB')} ${color.dim(`No project manifest in ${projectRoot} \u2014 running in a scratch directory.`)}\\n`,\n );\n }\n\n const answer = (\n await reader.readLine(` ${color.amber('?')} Continue anyway? ${color.dim('[Y/n/q]')} `)\n )\n .trim()\n .toLowerCase();\n if (answer === 'q' || answer === 'n' || answer === 'no') {\n renderer.write(color.dim(' Cancelled.\\n'));\n return false;\n }\n return true;\n}\n", "// Launch prompts \u2014 interactive mode (TUI/REPL), YOLO, Director, and Autonomy,\n// plus the summary gate that offers to repeat saved preferences and the\n// atomic write of the resolved choices back to the global config.\n\nimport * as fs from 'node:fs/promises';\nimport { atomicWrite, color } from '@wrongstack/core/utils';\nimport type { ReadlineInputReader } from '../input-reader.js';\nimport type { TerminalRenderer } from '../renderer.js';\n\nexport interface LaunchModeChoices {\n /** TUI or plain REPL. */\n mode: 'tui' | 'repl';\n /** Auto-approve tool calls except explicit deny rules. */\n yolo: boolean;\n /** Initial autonomy mode. 'off' = stops after each turn; 'auto' = self-driving. */\n autonomy: 'off' | 'auto';\n}\n\n/**\n * Thrown by runLaunchPrompts when the user presses q to cancel.\n * Caught by boot.ts so it can exit cleanly without process.exit().\n */\nexport class LaunchAbortedError extends Error {\n readonly exitCode = 0;\n constructor() {\n super('Launch cancelled by user');\n this.name = 'LaunchAbortedError';\n }\n}\n\n/**\n * Ask for interactive mode (TUI vs REPL), YOLO, Director, and Autonomy.\n * Each prompt is skipped when the corresponding option is pinned via CLI\n * flag. Returns the resolved set.\n *\n * When `lastChoices` is provided (from saved config), the function shows a\n * one-line summary and asks **one** question: \"Continue with these?\" instead\n * of re-asking every prompt individually.\n *\n * @throws LaunchAbortedError when the user presses q to cancel.\n */\nexport async function runLaunchPrompts(opts: {\n renderer: TerminalRenderer;\n reader: ReadlineInputReader;\n modePinned?: 'tui' | 'repl' | undefined;\n yoloPinned?: boolean | undefined;\n autonomyPinned?: 'off' | 'auto' | undefined;\n /** Saved launch preferences from a previous session (persisted to config). */\n lastChoices?: LaunchModeChoices | undefined;\n}): Promise<LaunchModeChoices> {\n const { renderer, reader, modePinned, yoloPinned, autonomyPinned, lastChoices } =\n opts;\n\n // If EVERY field is pinned by CLI flags, skip all prompts entirely.\n if (\n modePinned !== undefined &&\n yoloPinned !== undefined &&\n autonomyPinned !== undefined\n ) {\n return {\n mode: modePinned,\n yolo: yoloPinned,\n autonomy: autonomyPinned,\n };\n }\n\n // --- First run (no saved preferences): use the built-in defaults silently ---\n // The user explicitly asked for \"yolo on\" and \"autonomy auto\"\n // by default at first install. No prompts on the first launch \u2014 the new\n // defaults are applied without asking. The summary gate kicks in on the\n // SECOND launch (after persistLaunchChoices has written the first run's\n // values to the global config).\n if (!lastChoices) {\n return {\n mode: modePinned ?? 'tui',\n yolo: yoloPinned ?? true,\n autonomy: autonomyPinned ?? 'auto',\n };\n }\n\n // --- Override detection: at least one CLI flag diverges from saved ---\n // If the user has saved preferences but explicitly passes a different value\n // for any of the 3 fields via CLI flags, skip the summary gate and go\n // straight to individual prompts. The user is \"explicitly changing\n // settings from the start\", which is what the request described.\n const hasOverride =\n (modePinned !== undefined && modePinned !== lastChoices.mode) ||\n (yoloPinned !== undefined && yoloPinned !== lastChoices.yolo) ||\n (autonomyPinned !== undefined && autonomyPinned !== lastChoices.autonomy);\n\n // --- Summary gate: when saved preferences exist, show them + one question ---\n if (lastChoices && !hasOverride) {\n // Merge: pinned values override saved preferences.\n const effective = {\n mode: modePinned ?? lastChoices.mode,\n yolo: yoloPinned ?? lastChoices.yolo,\n autonomy: autonomyPinned ?? lastChoices.autonomy,\n };\n\n const onOff = (v: boolean) => (v ? color.green('on') : color.dim('off'));\n const modeLabel = effective.mode.toUpperCase();\n\n renderer.write(\n `\\n ${color.dim('Last settings:')} ${color.bold(modeLabel)} \u00B7 YOLO ${onOff(effective.yolo)} \u00B7 Autonomy ${effective.autonomy === 'auto' ? color.green('auto') : color.dim('off')}\\n`,\n );\n\n const answer = (\n await reader.readLine(\n ` ${color.amber('?')} Continue with these? ${color.dim('[Y/n/q]')} ${color.dim('(auto Y in 5s)')} `,\n { timeoutMs: 5000, defaultAnswer: 'y' },\n )\n )\n .trim()\n .toLowerCase();\n\n if (answer === 'q') {\n renderer.write(color.dim(' Goodbye!\\n'));\n throw new LaunchAbortedError();\n }\n\n if (answer !== 'n' && answer !== 'no') {\n // User accepted \u2014 proceed with effective values.\n const badges = buildBadges(effective);\n const badgeStr = badges.length > 0 ? ` (${badges.join(' \u00B7 ')})` : '';\n renderer.write(\n `\\n ${color.green('\u25B6')} Launching in ${color.bold(modeLabel)} mode${badgeStr}\\n\\n`,\n );\n return effective;\n }\n\n // User said no \u2014 fall through to individual prompts.\n }\n\n // --- Individual prompts (existing behavior, one at a time) ---\n let mode: 'tui' | 'repl';\n if (modePinned) {\n mode = modePinned;\n } else {\n const answer = (\n await reader.readLine(\n `\\n ${color.amber('?')} Interactive mode: ${color.bold('T')}UI / ${color.bold('R')}EPL ${color.dim('[T/r/q]')} `,\n )\n )\n .trim()\n .toLowerCase();\n if (answer === 'q') {\n renderer.write(color.dim(' Goodbye!\\n'));\n throw new LaunchAbortedError();\n }\n mode = answer === 'r' || answer === 'repl' ? 'repl' : 'tui';\n }\n\n let yolo: boolean;\n if (yoloPinned !== undefined && yoloPinned === lastChoices?.yolo) {\n yolo = yoloPinned;\n } else {\n const answer = (\n await reader.readLine(\n ` ${color.amber('?')} YOLO mode ${color.dim('(auto-approve tool calls)')} ${color.dim('[Y/n/q]')} `,\n )\n )\n .trim()\n .toLowerCase();\n if (answer === 'q') {\n renderer.write(color.dim(' Goodbye!\\n'));\n throw new LaunchAbortedError();\n }\n yolo = answer !== 'n' && answer !== 'no';\n }\n\n // (Director Mode is permanently on \u2014 no prompt needed)\n\n let autonomy: 'off' | 'auto';\n if (autonomyPinned !== undefined && autonomyPinned === lastChoices?.autonomy) {\n autonomy = autonomyPinned;\n } else {\n const answer = (\n await reader.readLine(\n ` ${color.amber('?')} Autonomy mode ${color.dim('(auto-continue \u2014 agent picks next step)')} ${color.dim('[Y/n/q]')} `,\n )\n )\n .trim()\n .toLowerCase();\n if (answer === 'q') {\n renderer.write(color.dim(' Goodbye!\\n'));\n throw new LaunchAbortedError();\n }\n autonomy = answer !== 'n' && answer !== 'no' ? 'auto' : 'off';\n }\n\n const badges = buildBadges({ mode, yolo, autonomy });\n const badgeStr = badges.length > 0 ? ` (${badges.join(' \u00B7 ')})` : '';\n renderer.write(\n `\\n ${color.green('\u25B6')} Launching in ${color.bold(mode.toUpperCase())} mode${badgeStr}\\n\\n`,\n );\n\n return { mode, yolo, autonomy };\n}\n\n/** Build the mode-badge labels shown in the launch line. */\nfunction buildBadges(chosen: LaunchModeChoices): string[] {\n const badges: string[] = [];\n if (chosen.yolo) badges.push(color.yellow('YOLO'));\n if (chosen.autonomy !== 'off')\n badges.push(color.magenta(`AUTONOMY:${chosen.autonomy.toUpperCase()}`));\n return badges;\n}\n\n/**\n * Persist the user's launch-mode choices (mode, yolo, autonomy)\n * back to the global config file so the next boot can offer a one-line\n * \"Continue with these?\" summary instead of re-asking every question.\n *\n * Reads the existing config, updates only the `yolo` and `launch` keys,\n * and writes back atomically. Other fields (including encrypted secrets)\n * pass through round-trip unchanged.\n */\nexport async function persistLaunchChoices(\n configPath: string,\n choices: LaunchModeChoices,\n): Promise<void> {\n let fileExists = false;\n try {\n await fs.access(configPath);\n fileExists = true;\n } catch {}\n\n let existing: Record<string, unknown> = {};\n try {\n const raw = await fs.readFile(configPath, 'utf8');\n existing = JSON.parse(raw) as Record<string, unknown>;\n } catch (err) {\n if (fileExists) {\n throw new Error(\n `Refusing to overwrite corrupt config at ${configPath} ` +\n `(${(err as Error).message}). Fix or move the file aside before retrying.`,\n { cause: err },\n );\n }\n // No existing file \u2014 start fresh, that's fine.\n existing = {};\n }\n\n existing.yolo = choices.yolo;\n existing.launch = {\n mode: choices.mode,\n autonomy: choices.autonomy,\n };\n\n await atomicWrite(configPath, JSON.stringify(existing, null, 2), { mode: 0o600 });\n}\n", "import type { ContentBlock, Renderer, TextBlock, ToolResultRenderMode } from '@wrongstack/core/types';\nimport { color } from '@wrongstack/core/utils';\nimport { renderDiff } from './diff-renderer.js';\nimport { theme } from './theme.js';\n\nexport interface TerminalRendererOptions {\n out?: NodeJS.WriteStream | undefined;\n err?: NodeJS.WriteStream | undefined;\n}\n\nexport class TerminalRenderer implements Renderer {\n private readonly out: NodeJS.WriteStream;\n private readonly err: NodeJS.WriteStream;\n private lineStart = true;\n /** When true, stdout-bound rendering is disabled (for non-terminal UI surfaces). */\n private silent = false;\n /**\n * When true, Ink exclusively owns the terminal. Both stdout and stderr\n * rendering must be disabled: either stream can interleave with Ink's\n * cursor updates and make the TUI flicker or leave stray debug notes.\n */\n private tuiActive = false;\n /**\n * Per-tool on-screen result render mode. Defaults to `'extend'` so\n * existing callers without `setResultRenderMode` see full content.\n * `setResultRenderMode(name, mode)` overrides the entry for `name`; the\n * override is one-shot for that name (the default reasserts after the\n * next write) so callers can set the mode right before each tool call\n * without leaking state across unrelated tool calls.\n */\n private renderModes = new Map<string, ToolResultRenderMode>();\n /** Mode applied when no entry is set for a given tool name. */\n private static readonly DEFAULT_RENDER_MODE: ToolResultRenderMode = 'extend';\n /** Maximum number of one-shot hints retained when callers abandon a result. */\n private static readonly MAX_RENDER_MODES = 256;\n /** Lines kept per tool family in `extend` mode. */\n private static readonly EXTEND_PREVIEW_LINES = 10;\n\n constructor(opts: TerminalRendererOptions = {}) {\n this.out = opts.out ?? process.stdout;\n this.err = opts.err ?? process.stderr;\n }\n\n /**\n * Toggle stdout suppression for non-terminal UI surfaces such as WebUI.\n * Diagnostics continue to flow to stderr. Idempotent.\n */\n setSilent(silent: boolean): void {\n this.silent = silent;\n }\n\n isSilent(): boolean {\n return this.silent;\n }\n\n /**\n * Toggle exclusive TUI ownership of both terminal streams. Unlike\n * {@link setSilent}, TUI mode suppresses stderr as well as stdout and clears\n * any CLI-only result mode staged before Ink took ownership. While active,\n * new result-mode hints are ignored. The two flags compose with OR semantics\n * for stdout suppression only; TUI ownership adds the other behaviors.\n * Enable immediately before starting Ink and disable in the paired\n * `finally`, only after the TUI has fully exited.\n */\n setTuiActive(active: boolean): void {\n // Drop any CLI-only hint staged before Ink took ownership. While active,\n // setResultRenderMode is suppressed and matching result writes consume\n // defensively, so no one-shot mode can survive the TUI boundary.\n if (active) this.renderModes.clear();\n this.tuiActive = active;\n }\n\n isTuiActive(): boolean {\n return this.tuiActive;\n }\n\n private suppressStdout(): boolean {\n return this.silent || this.tuiActive;\n }\n\n setResultRenderMode(name: string, mode: ToolResultRenderMode): void {\n if (this.suppressStdout()) return;\n // Refreshing an existing hint must not evict an unrelated one.\n if (this.renderModes.delete(name)) {\n this.renderModes.set(name, mode);\n return;\n }\n if (this.renderModes.size >= TerminalRenderer.MAX_RENDER_MODES) {\n const oldestName = this.renderModes.keys().next().value;\n if (oldestName !== undefined) this.renderModes.delete(oldestName);\n }\n this.renderModes.set(name, mode);\n }\n\n private getRenderMode(name: string): ToolResultRenderMode {\n return this.renderModes.get(name) ?? TerminalRenderer.DEFAULT_RENDER_MODE;\n }\n\n private clearRenderMode(name: string): void {\n this.renderModes.delete(name);\n }\n\n write(input: string | TextBlock): void {\n if (this.suppressStdout()) return;\n const text = typeof input === 'string' ? input : input.text;\n if (!text) return;\n const rendered = renderMarkdown(text);\n this.out.write(rendered);\n this.lineStart = rendered.endsWith('\\n');\n }\n\n writeLine(text = ''): void {\n if (this.suppressStdout()) return;\n if (!this.lineStart) this.out.write('\\n');\n if (text) this.out.write(`${text}\\n`);\n else this.out.write('\\n');\n this.lineStart = true;\n }\n\n writeBlock(block: ContentBlock): void {\n if (block.type === 'tool_result') {\n const text =\n typeof block.content === 'string' ? block.content : JSON.stringify(block.content);\n this.writeToolResult(block.name ?? 'result', text, !!block.is_error);\n return;\n }\n if (this.suppressStdout()) return;\n if (block.type === 'text') {\n this.write(block);\n } else if (block.type === 'tool_use') {\n this.writeToolCall(block.name, block.input);\n }\n }\n\n writeToolCall(name: string, input: unknown): void {\n if (this.suppressStdout()) return;\n if (!this.lineStart) this.out.write('\\n');\n const arrow = theme.primary('\u2192');\n const display = formatInputSummary(input);\n this.out.write(`${arrow} ${theme.bold(name)}${display ? color.dim(` ${display}`) : ''}\\n`);\n this.lineStart = true;\n }\n\n writeToolResult(name: string, content: unknown, isError: boolean): void {\n if (this.suppressStdout()) {\n // TUI/WebUI rendering happens elsewhere, but this call still represents\n // the one result that consumes a staged per-tool mode. Dropping the write\n // without clearing would leak the override into the next CLI result.\n this.clearRenderMode(name);\n return;\n }\n const txt = typeof content === 'string' ? content : safeStringify(content);\n const prefix = isError ? theme.error('\u2718') : theme.success('\u2713');\n const renderMode = this.getRenderMode(name);\n // One-shot mode: consume the override so an unset call doesn't carry\n // the previous tool's mode into the next one.\n this.clearRenderMode(name);\n\n // Tools that embed user-visible text in a `text` field (read, etc.)\n // arrive here as a JSON-string like `{\"path\":\"\u2026\",\"text\":\"line-1\\nline-2\"}`.\n // For the extend-mode preview we want to slice the *body* lines, not the\n // serialised JSON. `summarize` already parses the structured value;\n // pull `text` out here when present so the preview head/tail match\n // what the user actually saw.\n const bodyText = extractBodyText(content, name);\n\n if (isError) {\n const firstLine = txt.split('\\n')[0] ?? '';\n const truncated = firstLine.length > 200 ? `${firstLine.slice(0, 197)}\u2026` : firstLine;\n this.out.write(` ${prefix} ${color.dim(truncated)}\\n`);\n this.lineStart = true;\n return;\n }\n\n // Edit-like tools: pull the embedded diff if present.\n const isEditLike = name === 'edit' || name === 'write';\n const diff = extractDiff(content);\n if (isEditLike && diff) {\n this.out.write(` ${prefix} ${color.dim(summarize(content, name))}\\n`);\n const rendered = renderDiff(diff)\n .split('\\n')\n .map((l) => ` ${l}`)\n .join('\\n');\n this.out.write(`${rendered}\\n`);\n this.lineStart = true;\n return;\n }\n\n const summary = summarize(content, name);\n const isReadLike = name === 'read' || name === 'grep' || name === 'glob' || name === 'bash';\n\n // SIMPLE mode: meta only \u2014 no content lines. For tools whose result\n // already carries structured metadata (read/grep/glob/bash), the\n // summary line is the entire on-screen rendering. For unknown tools,\n // show the first line as a tiny preview to avoid hiding failure modes\n // that aren't summarised.\n if (renderMode === 'simple') {\n this.out.write(` ${prefix} ${color.dim(summary || compactSingleLine(bodyText))}\\n`);\n this.lineStart = true;\n return;\n }\n\n // EXTEND mode: full preview, up to 10 lines for read-like tools.\n const previewLines = isEditLike\n ? 0\n : isReadLike\n ? TerminalRenderer.EXTEND_PREVIEW_LINES\n : 2;\n\n const lines = bodyText.split('\\n');\n const head = lines.slice(0, previewLines).map((l: string) => l.replace(/\\s+$/, ''));\n const moreCount = Math.max(0, lines.length - head.length);\n this.out.write(` ${prefix} ${color.dim(summary)}\\n`);\n for (const l of head) {\n const capped = l.length > 200 ? `${l.slice(0, 197)}\u2026` : l;\n this.out.write(` ${color.dim(capped)}\\n`);\n }\n if (moreCount > 0) {\n this.out.write(\n ` ${color.dim(`+${moreCount} more line${moreCount === 1 ? '' : 's'}`)}\\n`,\n );\n }\n this.lineStart = true;\n }\n\n writeDiff(diff: string): void {\n if (this.suppressStdout()) return;\n if (!this.lineStart) this.out.write('\\n');\n this.out.write(`${renderDiff(diff)}\\n`);\n this.lineStart = true;\n }\n\n writeWarning(text: string): void {\n if (this.tuiActive) return;\n this.err.write(`${theme.warn('\u26A0')} ${text}\\n`);\n }\n writeError(text: string): void {\n if (this.tuiActive) return;\n this.err.write(`${theme.error('\u2718')} ${text}\\n`);\n }\n writeInfo(text: string): void {\n if (this.tuiActive) return;\n this.err.write(`${theme.info('\u2139')} ${text}\\n`);\n }\n\n clear(): void {\n if (this.suppressStdout()) return;\n this.out.write('\\x1b[2J\\x1b[H');\n this.lineStart = true;\n }\n\n /**\n * Write a flashy agent completion banner for delegate tool results.\n * Renders a box like:\n * \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n * \u2502 \u2713 [role] done in 4m 32s \u2502\n * \u2502 127 iterations \u00B7 341 tools \u2502\n * \u2502 Found 14 bugs across 6 files... \u2502\n * \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n */\n writeAgentSummary(summary: string, ok: boolean): void {\n if (this.suppressStdout()) return;\n if (!this.lineStart) this.out.write('\\n');\n\n const lines = summary.split('\\n');\n const icon = ok ? theme.success('\u2713') : theme.error('\u2718');\n const firstLine = `${icon} ${lines[0] ?? summary}`;\n const body = lines.slice(1);\n\n // Compute width: min 44, max terminal width (fallback 80).\n const maxWidth = Math.min(process.stdout.columns ?? 80, 120);\n const contentWidth = Math.max(\n firstLine.length,\n body.reduce((a, l) => Math.max(a, l.length), 0),\n );\n const boxWidth = Math.min(Math.max(contentWidth + 4, 44), maxWidth);\n\n const thick = '\u2501'.repeat(boxWidth - 2);\n const thin = '\u2500'.repeat(boxWidth - 2);\n\n this.out.write(`\\n ${theme.primary('\u250C')}${thick}${theme.primary('\u2510')}\\n`);\n\n const centre = (s: string) => {\n const inner = ` ${s} `;\n const padLen = Math.max(0, boxWidth - 2 - s.length);\n const left = Math.floor(padLen / 2);\n const right = padLen - left;\n return `${' '.repeat(left)}${inner}${' '.repeat(right)}`;\n };\n\n this.out.write(` ${theme.primary('\u2502')}${centre(firstLine)}${theme.primary('\u2502')}\\n`);\n\n for (const l of body) {\n this.out.write(\n ` ${theme.primary('\u2502')} ${l}${' '.repeat(Math.max(0, boxWidth - 3 - l.length))}${theme.primary('\u2502')}\\n`,\n );\n }\n\n this.out.write(` ${theme.primary('\u2514')}${thin}${theme.primary('\u2518')}\\n`);\n this.lineStart = true;\n }\n\n /**\n * Render subagent completion banners from a RunResult.\n * Uses `delegateSummaries` when available (populated by delegate tool),\n * otherwise falls back to scanning message history.\n */\n writeDelegateSummaries(result: {\n delegateSummaries?: Array<{ summary: string | undefined; ok: boolean }>;\n messages?: Array<unknown> | undefined;\n }): void {\n if (this.suppressStdout()) return;\n // Prefer the structured field from delegate tool.\n if (result.delegateSummaries) {\n for (const { summary, ok } of result.delegateSummaries) {\n if (!summary) continue;\n this.writeAgentSummary(summary, ok);\n }\n return;\n }\n // Fallback: scan message history for delegate tool_result blocks.\n if (!result.messages) return;\n for (const msg of result.messages) {\n const m = msg as { content?: Array<unknown> | undefined };\n if (!Array.isArray(m.content)) continue;\n for (const block of m.content) {\n const b = block as {\n type?: string | undefined;\n name?: string | undefined;\n content?: unknown | undefined;\n };\n if (b.type !== 'tool_result' || b.name !== 'delegate') continue;\n let obj: unknown;\n try {\n obj = typeof b.content === 'string' ? JSON.parse(b.content) : b.content;\n } catch {\n continue;\n }\n const o = obj as { summary?: string | undefined; ok?: boolean | undefined };\n if (o.summary) {\n this.writeAgentSummary(o.summary, o.ok ?? true);\n }\n }\n }\n }\n}\n\nfunction renderMarkdown(s: string): string {\n let out = s;\n // Headings\n out = out.replace(/^(#{1,6}) (.+)$/gm, (_m, hashes, text) => {\n return theme.primary(theme.bold(`${hashes} ${text}`));\n });\n // Fenced code\n out = out.replace(/```([a-zA-Z0-9_+-]*)\\n([\\s\\S]*?)```/g, (_m, _lang, code) => {\n return color.gray(`\\n\u250C\u2500\\n${code.replace(/^/gm, '\u2502 ')}\u2514\u2500`);\n });\n // Inline code\n out = out.replace(/`([^`\\n]+)`/g, (_m, code) => theme.accent(code));\n // Bold\n out = out.replace(/\\*\\*([^*]+)\\*\\*/g, (_m, text) => theme.bold(text));\n // Italic \u2014 single-asterisk\n out = out.replace(\n /(^|[^*])\\*([^*\\n]+)\\*([^*]|$)/g,\n (_m, l, t, r) => `${l}${color.italic(t)}${r}`,\n );\n return out;\n}\n\nfunction formatInputSummary(input: unknown): string {\n if (!input || typeof input !== 'object') return '';\n const obj = input as Record<string, unknown>;\n if (typeof obj['path'] === 'string') return obj['path'] as string;\n if (typeof obj['url'] === 'string') return obj['url'] as string;\n if (typeof obj['command'] === 'string') {\n const cmd = obj['command'] as string;\n return cmd.length > 60 ? cmd.slice(0, 57) + '...' : cmd;\n }\n if (typeof obj['pattern'] === 'string') return obj['pattern'] as string;\n return '';\n}\n\nfunction safeStringify(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Pull the user-visible body text out of a structured tool result so the\n * extend-mode preview slices real lines, not serialised JSON.\n *\n * - `read` returns `{text, total_lines, ...}` \u2014 the body is `text`.\n * - Bash/text-output tools that serialise `{stdout, stderr, ...}` get a\n * joined stdout/stderr string so multi-line output is previewable.\n * - Plain strings and structured payloads without a body field fall back\n * to the serialised form (existing behaviour).\n */\nfunction extractBodyText(value: unknown, name: string): string {\n let v: unknown = value;\n if (typeof value === 'string') {\n const trimmed = value.trimStart();\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n try {\n v = JSON.parse(value);\n } catch {\n return value;\n }\n } else {\n return value;\n }\n }\n if (typeof v !== 'object' || v === null) {\n return safeStringify(value);\n }\n const o = v as Record<string, unknown>;\n if (name === 'read' && typeof o['text'] === 'string') return o['text'] as string;\n if (name === 'bash') {\n const stdout = typeof o['stdout'] === 'string' ? (o['stdout'] as string) : '';\n const stderr = typeof o['stderr'] === 'string' ? (o['stderr'] as string) : '';\n if (stdout && stderr) return `${stdout}\\n${stderr}`;\n return stdout || stderr || '';\n }\n // No body field recognised \u2014 return the serialised form so the preview\n // still shows something rather than going blank.\n return safeStringify(value);\n}\n\n/**\n * If the tool result is an object with a `diff` field (e.g. from the edit\n * tool), return that. If it's a string containing a unified diff header,\n * return it as-is. Otherwise return null and the caller falls back to a\n * generic preview.\n */\nfunction extractDiff(value: unknown): string | null {\n if (typeof value === 'object' && value !== null) {\n const d = (value as { diff?: unknown | undefined }).diff;\n if (typeof d === 'string' && d.length > 0) return d;\n }\n if (typeof value === 'string') {\n // The agent serialises tool results to JSON before handing them to the\n // renderer, so a string `{\"diff\": \"...\"}` is the common case. Try parsing.\n const trimmed = value.trimStart();\n if (trimmed.startsWith('{')) {\n try {\n const parsed = JSON.parse(value) as { diff?: unknown | undefined };\n if (typeof parsed.diff === 'string' && parsed.diff.length > 0) {\n return parsed.diff;\n }\n } catch {\n // fall through\n }\n }\n if (/^---[^\\n]*\\n\\+\\+\\+/m.test(value)) return value;\n }\n return null;\n}\n\n/**\n * Short summary shown next to the \u2713: file path + count for edit, line count\n * for read/grep, etc. Falls back to nothing if the shape isn't recognised.\n *\n * For `read`, returns `path N lines (truncated|cached)`. For `bash`,\n * returns `exit=N X lines / Y bytes`. For tools without structured meta,\n * returns an empty string and the renderer falls back to a single-line\n * preview so unknown shapes still get some on-screen signal.\n */\nfunction summarize(value: unknown, name: string): string {\n // Tool results arrive at the renderer already serialised to a JSON string.\n // Re-parse so we can pull out structured fields. Falls back to the raw value\n // for tools that return plain strings.\n let v: unknown = value;\n if (typeof value === 'string') {\n const trimmed = value.trimStart();\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n try {\n v = JSON.parse(value);\n } catch {\n // not JSON \u2014 leave as string\n }\n }\n }\n if (typeof v === 'object' && v !== null) {\n const o = v as Record<string, unknown>;\n if (name === 'edit') {\n const path = typeof o['path'] === 'string' ? (o['path'] as string) : '';\n const reps = typeof o['replacements'] === 'number' ? (o['replacements'] as number) : 0;\n return `${path} ${reps} replacement${reps === 1 ? '' : 's'}`.trim();\n }\n if (name === 'write') {\n const path = typeof o['path'] === 'string' ? (o['path'] as string) : '';\n const bytes = typeof o['bytes'] === 'number' ? (o['bytes'] as number) : undefined;\n return bytes !== undefined ? `${path} ${bytes}B` : path;\n }\n if (name === 'read') {\n return summarizeRead(o);\n }\n if (name === 'bash') {\n return summarizeBash(o);\n }\n if (typeof o['count'] === 'number') {\n return `${o['count']} match${o['count'] === 1 ? '' : 'es'}`;\n }\n }\n return '';\n}\n\nfunction summarizeRead(o: Record<string, unknown>): string {\n const path = typeof o['path'] === 'string' ? (o['path'] as string) : '';\n const total = typeof o['total_lines'] === 'number' ? (o['total_lines'] as number) : undefined;\n const truncated = o['truncated'] === true;\n const cached = o['cached'] === true;\n const note = typeof o['note'] === 'string' ? (o['note'] as string) : undefined;\n const parts: string[] = [];\n if (path) parts.push(path);\n if (total !== undefined) parts.push(`${total} line${total === 1 ? '' : 's'}`);\n const flags: string[] = [];\n if (truncated) flags.push('truncated');\n if (cached) flags.push('cached');\n if (flags.length > 0) parts.push(`(${flags.join(', ')})`);\n let summary = parts.join(' ').trim();\n if (note) summary = summary ? `${summary} \u2014 ${note}` : note;\n return summary;\n}\n\nfunction summarizeBash(o: Record<string, unknown>): string {\n const exit = typeof o['exitCode'] === 'number'\n ? (o['exitCode'] as number)\n : typeof o['exit_code'] === 'number'\n ? (o['exit_code'] as number)\n : undefined;\n const stdout = typeof o['stdout'] === 'string' ? (o['stdout'] as string) : '';\n const stderr = typeof o['stderr'] === 'string' ? (o['stderr'] as string) : '';\n const outLines = stdout ? stdout.split('\\n').length : 0;\n const errLines = stderr ? stderr.split('\\n').length : 0;\n const totalBytes = stdout.length + stderr.length;\n const parts: string[] = [];\n if (exit !== undefined) parts.push(`exit=${exit}`);\n if (outLines > 0) parts.push(`${outLines} stdout line${outLines === 1 ? '' : 's'}`);\n if (errLines > 0) parts.push(`${errLines} stderr line${errLines === 1 ? '' : 's'}`);\n if (totalBytes > 0) parts.push(`${totalBytes}B`);\n return parts.join(' ');\n}\n\n/**\n * Last-resort single-line preview used when `summarize` returns nothing\n * (e.g. unknown tool result shape). Trims whitespace, takes the first\n * line, and caps at 200 chars to match the per-line cap in extend mode.\n */\nfunction compactSingleLine(text: string): string {\n const first = text.split('\\n')[0]?.trim() ?? '';\n if (!first) return '(no output)';\n return first.length > 200 ? `${first.slice(0, 197)}\u2026` : first;\n}\n", "import type { SubcommandHandler } from './contracts.js';\nexport type { SubcommandDeps, SubcommandHandler } from './contracts.js';\n\n/**\n * Subcommand handlers are loaded on invocation, not at boot.\n *\n * This module is reached from `boot.ts` on EVERY `wstack` invocation, so 27\n * static imports meant `wstack version` and `wstack mailbox serve` evaluated\n * the union of every handler \u2014 including `bench`, `hq`, `modeldiag`, `replay`\n * and `chronicle` \u2014 plus everything those handlers pull in. `@wrongstack/bench`\n * for example is imported by exactly one handler and nothing else in the CLI.\n *\n * The dispatch in `boot.ts` was already short-circuited correctly; the problem\n * was purely that the module graph had been resolved and evaluated before it\n * ever ran.\n *\n * Bundling note: the build runs with `splitting: false`, so esbuild inlines\n * these in-repo modules into one file. That still defers *evaluation* (esbuild\n * wraps each in a lazy `__esm` initializer), which is where the heap goes. But\n * a WORKSPACE package a handler imports statically is hoisted to a top-level\n * import of the bundle and stays eager \u2014 such a handler has to import it\n * dynamically itself. See `tools/src/codebase-index/ts-parser.ts` for that\n * pattern and why it is the only boundary that survives bundling.\n */\ntype SubcommandLoader = () => Promise<SubcommandHandler>;\n\nconst loaders: Record<string, SubcommandLoader> = {\n acp: async () => (await import('./handlers/acp.js')).acpCmd,\n init: async () => (await import('./handlers/init.js')).initCmd,\n auth: async () => (await import('./handlers/auth.js')).authCmd,\n update: async () => (await import('./handlers/update.js')).updateCmd,\n sessions: async () => (await import('./handlers/sessions-config.js')).sessionsCmd,\n config: async () => (await import('./handlers/sessions-config.js')).configCmd,\n rewind: async () => (await import('./handlers/rewind.js')).rewindCmd,\n replay: async () => (await import('./handlers/replay.js')).replayCmd,\n audit: async () => (await import('./handlers/audit.js')).auditCmd,\n tools: async () => (await import('./handlers/tools-skills.js')).toolsCmd,\n skills: async () => (await import('./handlers/tools-skills.js')).skillsCmd,\n providers: async () => (await import('./handlers/providers-models.js')).providersCmd,\n models: async () => (await import('./handlers/providers-models.js')).modelsCmd,\n mcp: async () => (await import('./handlers/mcp.js')).mcpCmd,\n plugin: async () => (await import('./handlers/plugin-usage.js')).pluginCmd,\n plugins: async () => (await import('./handlers/plugin-usage.js')).pluginCmd,\n diag: async () => (await import('./handlers/diag-doctor.js')).diagCmd,\n doctor: async () => (await import('./handlers/diag-doctor.js')).doctorCmd,\n export: async () => (await import('./handlers/export.js')).exportCmd,\n usage: async () => (await import('./handlers/plugin-usage.js')).usageCmd,\n version: async () => (await import('./handlers/version-help.js')).versionCmd,\n help: async () => (await import('./handlers/version-help.js')).helpCmd,\n projects: async () => (await import('./handlers/projects.js')).projectsCmd,\n modeldiag: async () => (await import('./handlers/modeldiag.js')).modeldiagCmd,\n quick: async () => (await import('./handlers/quick.js')).quickCmd,\n bench: async () => (await import('./handlers/bench.js')).benchCmd,\n chronicle: async () => (await import('./handlers/chronicle.js')).chronicleCmd,\n hq: async () => (await import('./handlers/hq.js')).hqCmd,\n mailbox: async () => (await import('./handlers/mailbox-serve.js')).mailboxServeCmd,\n permissions: async () => (await import('./handlers/permissions.js')).permissionsCmd,\n project: async () => (await import('./handlers/project.js')).projectCmd,\n};\n\n/**\n * Name -> handler map. Each entry keeps the plain `SubcommandHandler` shape, so\n * existence checks (`subcommands[name]`) and direct invocation both behave\n * exactly as before; the handler module is imported on first call.\n */\nexport const subcommands: Record<string, SubcommandHandler> = Object.fromEntries(\n Object.entries(loaders).map(([name, load]): [string, SubcommandHandler] => [\n name,\n async (args, deps) => (await load())(args, deps),\n ]),\n);\n\n/** Every registered subcommand name, resolvable without loading a handler. */\nexport const subcommandNames: readonly string[] = Object.keys(loaders);\n", "/**\n * --help / --version short-circuit \u2014 extracted from cli-main.ts.\n *\n * The baseline boot-shape test (PR 0 of Issue #29) showed that\n * `wstack --help` previously returned exit 2 because boot() ran\n * config I/O before reaching the help handler. This short-circuit\n * bypasses boot() entirely for informational flags.\n *\n * Returns the exit code (0) when a short-circuit fired, or null when\n * neither flag was present (caller should proceed to boot()).\n */\nimport { parseArgs } from '../arg-parser.js';\nimport { helpCmd, versionCmd } from '../subcommands/handlers/version-help.js';\n\n/**\n * Check argv for --help / --version and dispatch directly.\n *\n * Returns 0 when a flag fired, or null when neither was present.\n * The renderer is a stub that writes to stdout \u2014 help text is plain\n * `write` calls, no TTY needed.\n */\nexport async function handleHelpVersionShortCircuit(\n argv: string[],\n): Promise<number | null> {\n const earlyFlags = parseArgs(argv).flags;\n if (earlyFlags['help'] !== true && earlyFlags['version'] !== true) {\n return null;\n }\n\n const stubRenderer = {\n write: (line: string) => { process.stdout.write(line); },\n } as never as Parameters<typeof helpCmd>[1]['renderer'];\n const handler = earlyFlags['help'] === true ? helpCmd : versionCmd;\n return await handler([], { renderer: stubRenderer } as Parameters<typeof helpCmd>[1]);\n}\n", "/**\n * --desktop short-circuit.\n *\n * Starts the Electron desktop shell before the normal project boot path. This\n * keeps `wstack --desktop` and `wstack desktop` project-independent, matching\n * `--hq`.\n */\nimport { spawn } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\nimport { color } from '@wrongstack/core/utils';\n\nexport function stripDesktopLauncherArgs(argv: string[]): string[] {\n const out: string[] = [];\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (!arg) continue;\n if (arg === '--desktop' || arg.startsWith('--desktop=')) continue;\n if (i === 0 && arg === 'desktop') continue;\n out.push(arg);\n }\n return out;\n}\n\nexport async function handleDesktopShortCircuit(\n flags: Record<string, string | boolean>,\n argv: string[],\n): Promise<number | null> {\n if (flags['desktop'] !== true) return null;\n return launchDesktop(stripDesktopLauncherArgs(argv));\n}\n\nasync function launchDesktop(args: string[]): Promise<number> {\n const req = createRequire(import.meta.url);\n let launcherPath: string;\n try {\n const desktopPkgPath = req.resolve('@wrongstack/desktop/package.json');\n launcherPath = path.join(path.dirname(desktopPkgPath), 'bin', 'wrongstack-desktop.js');\n } catch {\n process.stderr.write(\n [\n color.red('\u2717 WrongStack Desktop is not installed.'),\n '',\n 'Install the desktop package:',\n ' npm install -g @wrongstack/desktop',\n '',\n 'The umbrella package also supports desktop when installed with optional dependencies:',\n ' npm install -g wrongstack',\n '',\n ].join('\\n'),\n );\n return 1;\n }\n\n return await new Promise<number>((resolve) => {\n const child = spawn(process.execPath, [launcherPath, ...args], {\n stdio: 'inherit',\n env: process.env,\n windowsHide: false,\n });\n child.once('error', (err) => {\n process.stderr.write(`${color.red('\u2717 Failed to start WrongStack Desktop:')} ${err.message}\\n`);\n resolve(1);\n });\n child.once('exit', (code, signal) => {\n if (typeof code === 'number') resolve(code);\n else resolve(signal ? 1 : 0);\n });\n });\n}\n", "/**\n * --hq short-circuit \u2014 extracted from cli-main.ts.\n *\n * Starts the HQ command center server before boot() \u2014 HQ is\n * project-independent. Blocks until SIGINT/SIGTERM.\n *\n * Returns 0 when the HQ flag was present and the server ran, or null\n * when the flag was absent (caller should proceed to boot()).\n */\n\nimport * as fs from 'node:fs/promises';\nimport * as net from 'node:net';\nimport * as path from 'node:path';\nimport { color, isPidAlive } from '@wrongstack/core/utils';\nimport { HQ_CLI_DEFAULT_HOST, isLoopbackHost, resolveHqDataDir } from '@wrongstack/core/hq';\nimport { DEFAULT_PORT } from '../hq-server.js';\nimport type { HqQuickTunnelHandle } from '../hq-tunnel.js';\n\ninterface HqRuntimeMarker {\n url?: string;\n pid?: number;\n updatedAt?: string;\n}\n\n/**\n * Returns true if there is an HQ server already running for this data dir\n * (runtime.json exists and its PID is still alive).\n */\nasync function isHqAlreadyRunning(dataDir: string): Promise<HqRuntimeMarker | null> {\n const markerPath = path.join(dataDir, 'runtime.json');\n let fd;\n try {\n fd = await fs.open(markerPath, 'r');\n const content = await fd.read().then(({ buffer }) => buffer.toString('utf8'));\n const marker = JSON.parse(content) as HqRuntimeMarker;\n // A live pid means an HQ is already up and we should attach to it. The\n // inline `process.kill` this replaced treated EPERM as dead, so an HQ\n // owned by another user would be missed and a second one started on top.\n if (marker.pid && isPidAlive(marker.pid)) return marker;\n return null;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n return null;\n } finally {\n if (fd) await fd.close();\n }\n}\n\n/**\n * Returns true if the port is already in use on the given host.\n */\nasync function isPortInUse(host: string, port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server = net.createServer();\n server.once('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n resolve(true);\n } else {\n resolve(false);\n }\n });\n server.once('listening', () => {\n server.close(() => resolve(false));\n });\n server.listen(port, host);\n });\n}\n\n/**\n * Check for --hq flag and start the HQ server if present.\n *\n * Returns 0 when the server started, or null when --hq was not set.\n */\nexport async function handleHqShortCircuit(\n flags: Record<string, string | boolean>,\n): Promise<number | null> {\n if (flags['hq'] !== true) return null;\n\n const { startHqServer } = await import('../hq-server.js');\n const tunnelRequested = flags['tunnel'] === true;\n // The CLI opts into the wide bind explicitly; the library default stays loopback.\n // Quick Tunnel is outbound-only, so keep its origin private by default.\n const host =\n typeof flags['host'] === 'string'\n ? flags['host']\n : tunnelRequested\n ? '127.0.0.1'\n : HQ_CLI_DEFAULT_HOST;\n if (tunnelRequested && !isLoopbackHost(host)) {\n process.stderr.write(\n `${color.red('\u2717')} --tunnel requires a loopback origin. Remove --host or use --host 127.0.0.1.\\n`,\n );\n return 1;\n }\n\n // Port: use --port flag if explicitly given; otherwise use the documented\n // default without prompting so `wstack --hq` and `wstack hq` are direct\n // launch commands.\n let port: number;\n if (typeof flags['port'] === 'string' && flags['port'].trim() !== '') {\n const parsed = Number.parseInt(flags['port'], 10);\n if (Number.isFinite(parsed) && parsed > 0 && parsed < 65536) {\n port = parsed;\n } else {\n process.stderr.write(`${color.red('\u2717')} Invalid --port value: ${flags['port']}\\n`);\n return 1;\n }\n } else port = DEFAULT_PORT;\n\n const dataDir = typeof flags['data-dir'] === 'string' ? flags['data-dir'] : undefined;\n const password =\n typeof flags['password'] === 'string' ? flags['password'] : process.env.WRONGSTACK_HQ_PASSWORD;\n if (password !== undefined && password.length < 8) {\n process.stderr.write(`${color.red('\u2717')} HQ password must be at least 8 characters.\\n`);\n return 1;\n }\n // User explicitly chose a port if they either passed --port OR accepted\n // a non-default value from the interactive prompt.\n const userProvidedPort =\n (typeof flags['port'] === 'string' && flags['port'].trim() !== '') || port !== DEFAULT_PORT;\n\n // Resolve data dir the same way startHqServer does so we can check for a\n // running HQ instance before attempting to start a new one.\n const resolvedDataDir = dataDir ?? resolveHqDataDir();\n const existing = await isHqAlreadyRunning(resolvedDataDir);\n if (existing) {\n process.stderr.write(\n `${color.red('\u2717')} HQ is already running at ${existing.url} ` +\n `(PID ${existing.pid}). Stop it first or use a different --data-dir.\\n`,\n );\n return 1;\n }\n\n // Probe the port before binding \u2014 fail fast with a clear message.\n if (await isPortInUse(host, port)) {\n process.stderr.write(\n `${color.red('\u2717')} Port ${port} is already in use. ` +\n `Choose a different port or stop the process using it.\\n`,\n );\n return 1;\n }\n\n // --hq-token-ttl: optional TTL stamped on first-run tokens (e.g. \"1h\", \"7d\", \"86400000\").\n let tokenTtlMs: number | undefined;\n const rawTtl =\n typeof flags['hq-token-ttl'] === 'string'\n ? flags['hq-token-ttl']\n : (process.env.WRONGSTACK_HQ_TOKEN_TTL as string | undefined);\n if (rawTtl !== undefined && rawTtl.length > 0) {\n const { parseTokenTtlValue } = await import('../utils/hq-ttl.js');\n const parsed = parseTokenTtlValue(rawTtl);\n if (parsed.error) {\n process.stderr.write(`${color.red('\u2717')} Invalid --hq-token-ttl: ${parsed.error}\\n`);\n return 1;\n }\n tokenTtlMs = parsed.value;\n }\n\n let handle;\n try {\n handle = await startHqServer({\n host,\n port,\n strictPort: flags['strict-port'] === true,\n exactPort: userProvidedPort,\n allowInsecureOpen: flags['insecure-open'] === true,\n secureCookies: tunnelRequested,\n requireBrowserAuth: tunnelRequested,\n ...(dataDir !== undefined ? { dataDir } : {}),\n ...(password !== undefined ? { password } : {}),\n ...(tokenTtlMs !== undefined ? { tokenTtlMs } : {}),\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (err instanceof Error && 'code' in err && err.code === 'EADDRINUSE') {\n process.stderr.write(\n `${color.red('\u2717')} Port ${port} is already in use. Please choose a different port.\\n`,\n );\n } else {\n process.stderr.write(`${color.red('\u2717')} Failed to start HQ server: ${msg}\\n`);\n }\n return 1;\n }\n\n let tunnel: HqQuickTunnelHandle | undefined;\n let browserUrl = handle.firstRunSetup?.browserUrl ?? `http://${handle.host}:${handle.port}`;\n if (tunnelRequested) {\n if (\n handle.firstRunSetup !== undefined &&\n !handle.firstRunSetup.browserTokenMode &&\n !handle.firstRunSetup.passwordMode\n ) {\n await handle.close();\n process.stderr.write(\n `${color.red('\u2717')} Refusing to publish HQ in open mode. Set --password or create a browser token first.\\n`,\n );\n return 1;\n }\n try {\n const { buildPublicHqUrl, startHqQuickTunnel } = await import('../hq-tunnel.js');\n const originHost = handle.host === '::1' ? '[::1]' : handle.host;\n tunnel = await startHqQuickTunnel(`http://${originHost}:${handle.port}`, {\n onUnexpectedExit: (message) => process.stderr.write(`${color.yellow('!')} ${message}\\n`),\n });\n // cloudflared discovered this URL from its own process output, so it is a\n // server-established origin rather than a client-selected Host header.\n handle.trustPublicOrigin(new URL(tunnel.url).origin);\n browserUrl = buildPublicHqUrl(\n tunnel.url,\n handle.firstRunSetup?.browserUrl,\n handle.firstRunSetup?.passwordMode !== true,\n );\n process.stdout.write(`\\n${color.green('Cloudflare Quick Tunnel ready:')} ${browserUrl}\\n`);\n process.stdout.write(\n `${color.dim('Temporary development URL; DNS may need a few seconds, it changes on restart and ends when HQ stops.')}\\n`,\n );\n } catch (err) {\n await handle.close();\n process.stderr.write(\n `${color.red('\u2717')} Failed to start Cloudflare Quick Tunnel: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return 1;\n }\n }\n\n if (flags['open'] === true) {\n try {\n const { openBrowser } = await import('@wrongstack/webui-server');\n openBrowser(browserUrl);\n } catch {\n // best-effort\n }\n }\n // Keep the process alive until SIGINT/SIGTERM\n await new Promise<void>((resolve) => {\n const shutdown = async () => {\n const results = await Promise.allSettled([\n ...(tunnel ? [tunnel.close()] : []),\n handle.close(),\n ]);\n const failure = results.find(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n );\n if (failure) {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'hq.server_close_failed',\n message: String(failure.reason),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n resolve();\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n });\n return 0;\n}\n", "/**\n * Interactive launch menu \u2014 surfaced when `wstack` is invoked with no\n * mode flag (no `--webui`, `--simpleui`, `--hq`, or `--desktop`) and no\n * positional subcommand, on an interactive TTY.\n *\n * The menu asks the user **once** which top-level surface to launch:\n * 1) TUI / REPL \u2014 interactive terminal (the historical default)\n * 2) WebUI \u2014 browser-based project UI (port 3456 by default)\n * 3) SimpleUI \u2014 lightweight browser UI (port 3466 by default)\n * 4) HQ \u2014 project-independent HQ dashboard (port 3499)\n *\n * It returns either:\n * - `null` \u2014 caller should fall through to the historical\n * boot() flow unchanged (menu skipped).\n * - `LaunchChoice` \u2014 caller should honor the selection:\n * * `tui-repl` \u2192 proceed to boot() with no flag\n * changes (the inner pre-launch prompts still\n * ask TUI vs REPL + YOLO + autonomy).\n * * `webui` / `simpleui` \u2192 caller injects the\n * surface flag + chosen port into argv.\n * * `hq` \u2192 caller dispatches to the HQ\n * short-circuit with the chosen port/host.\n *\n * Why this lives in `boot/`: it sits next to the other entry-point\n * short-circuits (`short-circuit-{flags,desktop,hq}.ts`) and is\n * consumed by `cli-context.ts` between those short-circuits and\n * `boot()`. It deliberately does NOT take any DI container, agent,\n * or session \u2014 those are owned by the post-boot phase.\n */\n\nimport { atomicWrite, color, isStdinTTY, setRawMode } from '@wrongstack/core/utils';\nimport { HQ_CLI_DEFAULT_HOST } from '@wrongstack/core/hq';\nimport type { LaunchMenuChoice } from '@wrongstack/core/types';\nimport * as fs from 'node:fs/promises';\nimport { DEFAULT_PORT as HQ_DEFAULT_PORT } from '../hq-server.js';\nimport { launchBannerLines } from './launch-banner.js';\nimport type { ReadlineInputReader } from '../input-reader.js';\nimport type { TerminalRenderer } from '../renderer.js';\nimport { CLI_VERSION } from '../version.js';\n\n/** Top-level surfaces the user can launch from the menu. */\nexport type LaunchMenuMode = LaunchMenuChoice['mode'];\n\n/** Resolved menu result \u2014 the caller must act on this, not re-derive. */\nexport interface LaunchMenuResult extends LaunchMenuChoice {\n /**\n * True when the user typed `q` (or pressed Ctrl+C) at any prompt.\n * Caller should exit gracefully with code 0.\n */\n cancelled: boolean;\n}\n\n// Default ports \u2014 keep in sync with the rest of the codebase.\n// WebUI / SimpleUI: packages/webui-server/src/server/port-utils.ts\n// HQ: packages/cli/src/hq-server.ts (DEFAULT_PORT)\nconst DEFAULT_PORTS: Record<Exclude<LaunchMenuMode, 'tui-repl'>, number> = {\n webui: 3456,\n simpleui: 3466,\n hq: HQ_DEFAULT_PORT,\n};\n\nconst DEFAULT_HOST = '127.0.0.1';\n/** Shared with the other HQ entry points so the two cannot drift apart. */\nconst HQ_DEFAULT_HOST = HQ_CLI_DEFAULT_HOST;\n\nfunction defaultHostFor(mode: Exclude<LaunchMenuMode, 'tui-repl'>): string {\n return mode === 'hq' ? HQ_DEFAULT_HOST : DEFAULT_HOST;\n}\n\n/** Numbered choices shown to the user. Order MUST match the menu printout. */\nconst MODE_OPTIONS: ReadonlyArray<{ key: number; mode: LaunchMenuMode; label: string; hint: string; icon: string }> = [\n { key: 1, mode: 'tui-repl', label: 'TUI / REPL', hint: 'interactive terminal (default)', icon: '\u2328' },\n { key: 2, mode: 'webui', label: 'WebUI', hint: `browser-based project UI (port ${DEFAULT_PORTS.webui})`, icon: '\uD83C\uDF10' },\n { key: 3, mode: 'simpleui', label: 'SimpleUI', hint: `lightweight browser UI (port ${DEFAULT_PORTS.simpleui})`, icon: '\uD83D\uDCC4' },\n { key: 4, mode: 'hq', label: 'HQ', hint: `project-independent dashboard (port ${HQ_DEFAULT_PORT})`, icon: '\uD83D\uDCCA' },\n];\n\nconst MENU_TIMEOUT_MS = 8_000;\nconst SUMMARY_TIMEOUT_MS = 5_000;\nconst PORT_TIMEOUT_MS = 8_000;\n\n/**\n * Pure predicate \u2014 extracted so unit tests can lock the skip\n * conditions down without booting a renderer or reader.\n *\n * Menu is skipped when ANY of these are true:\n * - `--no-menu` flag is set\n * - `--webui`, `--simpleui`, `--hq`, or `--desktop` flag is set\n * (the user already chose a surface)\n * - stdin is not a TTY (CI, pipes, redirects)\n * - the first positional looks like a known subcommand (auth,\n * init, mcp, plugin, doctor, version, help, \u2026)\n * - `--no-interactive` or `--skip` (existing \"skip all prompts\"\n * contract from boot.ts)\n * - a one-shot prompt (`--prompt <x>`) is supplied\n * - any positional argument is present (treats it like the user\n * is forwarding a one-shot query, not launching a surface)\n */\nexport function shouldSkipMenu(\n argv: string[],\n flags: Record<string, string | boolean>,\n positional: string[],\n): boolean {\n if (flags['no-menu'] === true) return true;\n if (flags['webui'] === true) return true;\n if (flags['simpleui'] === true) return true;\n if (flags['hq'] === true) return true;\n if (flags['desktop'] === true) return true;\n if (flags['no-interactive'] === true) return true;\n if (flags['skip'] === true) return true;\n if (typeof flags['prompt'] === 'string') return true;\n if (!isStdinTTY()) return true;\n if (positional.length > 0) {\n // A leading positional that matches a known subcommand means the\n // user invoked a subcommand (auth, mcp, plugin, \u2026). Don't ambush\n // them with a menu. Unknown positional args are still treated as\n // a one-shot query (handled above by the positional.length check).\n const first = positional[0];\n if (first && KNOWN_SUBCOMMANDS.has(first)) return true;\n }\n // Silence unused-arg lint without dropping the parameter \u2014 argv is\n // reserved for future deep argv parsing (e.g. recognizing\n // `wstack mcp add \u2026` after subcommand-stripping).\n void argv;\n return false;\n}\n\n/**\n * Subcommands that `shouldSkipMenu` treats as explicit user intent\n * (the user invoked a command, not a launchable surface). Kept in\n * sync with `packages/cli/src/subcommands/index.ts` \u2014 when a new\n * subcommand is added there, add it here too. The CLI dispatcher's\n * own short-circuit handles unknown positionals as one-shot prompts,\n * which the menu already excludes via the positional.length check.\n */\nconst KNOWN_SUBCOMMANDS = new Set<string>([\n 'auth',\n 'init',\n 'mcp',\n 'plugin',\n 'doctor',\n 'version',\n 'help',\n 'provider',\n 'project',\n 'session',\n 'sessions',\n 'replay',\n 'export',\n 'rewind',\n 'config-history',\n 'modeldiag',\n 'models-add',\n 'tools',\n 'skill',\n 'skills',\n 'update',\n 'quick',\n 'audit',\n 'bench',\n 'mailbox-serve',\n 'resume',\n]);\n\ninterface RunLaunchMenuDeps {\n argv: string[];\n flags: Record<string, string | boolean>;\n positional: string[];\n renderer: TerminalRenderer;\n reader: ReadlineInputReader;\n /**\n * Last saved menu choice, if any. When provided the menu shows a\n * one-line summary + \"Continue? [Y/n/q]\" gate before re-asking,\n * matching the `runLaunchPrompts` pattern.\n */\n lastChoice?: LaunchMenuChoice | undefined;\n /**\n * Override the default ports (used by tests). Production callers\n * should leave this unset.\n */\n defaultPorts?: Partial<typeof DEFAULT_PORTS> | undefined;\n}\n\n/**\n * Run the interactive launch menu.\n *\n * Returns `null` when the menu should be skipped (see\n * {@link shouldSkipMenu}). Otherwise returns a {@link LaunchMenuResult}\n * the caller must act on.\n */\nexport async function runLaunchMenu(deps: RunLaunchMenuDeps): Promise<LaunchMenuResult | null> {\n if (shouldSkipMenu(deps.argv, deps.flags, deps.positional)) {\n return null;\n }\n\n const { renderer, reader, lastChoice } = deps;\n const ports = { ...DEFAULT_PORTS, ...(deps.defaultPorts ?? {}) };\n\n writeBanner(renderer);\n\n // Summary gate \u2014 same pattern as runLaunchPrompts.\n if (lastChoice) {\n const accept = await promptSummaryGate(deps);\n if (accept === 'use-last') {\n return finalize(lastChoice, ports);\n }\n if (accept === 'cancel') {\n return { ...lastChoice, cancelled: true };\n }\n // accept === 're-prompt' \u2192 fall through to the numbered menu.\n }\n\n renderer.write(`\\n ${color.amber('?')} Choose how to run WrongStack:\\n\\n`);\n\n // Preferred path: raw-mode arrow-key selector. Falls back to the\n // numbered readline prompt when raw mode is unavailable (piped stdin,\n // tests, exotic terminals) \u2014 the two paths MUST stay behaviorally\n // equivalent: same options, same timeout default, same cancel keys.\n const arrowPick = await promptModeArrow(deps);\n\n let choice: LaunchMenuChoice;\n if (arrowPick) {\n if (arrowPick.cancelled) {\n return { mode: 'tui-repl', cancelled: true };\n }\n choice = { mode: arrowPick.mode };\n } else {\n for (const opt of MODE_OPTIONS) {\n renderer.write(\n ` ${color.bold(String(opt.key))}) ${opt.icon} ${color.bold(opt.label)} ${color.dim(opt.hint)}\\n`,\n );\n }\n renderer.write(`\\n ${color.dim('\u2500'.repeat(48))}\\n`);\n const answer = (\n await reader.readLine(\n ` ${color.amber('?')} Mode ${color.dim('[1-4, q to quit]')} ${color.dim(`(auto 1 in ${MENU_TIMEOUT_MS / 1000}s)`)} `,\n { timeoutMs: MENU_TIMEOUT_MS, defaultAnswer: '1' },\n )\n )\n .trim()\n .toLowerCase();\n\n if (answer === 'q' || answer === 'quit') {\n renderer.write(color.dim(' Goodbye!\\n'));\n return { mode: 'tui-repl', cancelled: true };\n }\n\n const picked = MODE_OPTIONS.find((o) => String(o.key) === answer || o.mode === answer);\n // Anything unrecognized falls back to the first option (TUI/REPL),\n // matching the timeout default \u2014 the menu is best-effort.\n choice = picked ? { mode: picked.mode } : { mode: 'tui-repl' };\n }\n\n // For modes that bind a port/host, ask once and persist the answer.\n if (choice.mode !== 'tui-repl') {\n const port = await promptPort(deps, ports[choice.mode]);\n choice.port = port;\n const defaultHost = defaultHostFor(choice.mode);\n const host = await promptHost(deps, defaultHost);\n if (host !== defaultHost) choice.host = host;\n }\n\n return finalize(choice, ports);\n}\n\n/**\n * Print the WRONGSTACK banner (same artwork the TUI shows) above the\n * menu. Pure decoration \u2014 kept out of the non-interactive paths by the\n * `shouldSkipMenu` gate that runs before this.\n */\nfunction writeBanner(renderer: TerminalRenderer): void {\n const columns = process.stdout.columns ?? 80;\n renderer.write('\\n');\n for (const line of launchBannerLines(columns, CLI_VERSION)) {\n renderer.write(` ${line}\\n`);\n }\n}\n\n/**\n * True when we can take stdin into raw mode for the arrow-key selector.\n * Piped stdin/stdout, test runners, and terminals without setRawMode all\n * fall back to the numbered readline prompt.\n */\nfunction canUseArrowMenu(): boolean {\n if (process.env.VITEST || process.env.NODE_ENV === 'test') return false;\n const stdin = process.stdin as NodeJS.ReadStream & { setRawMode?: unknown };\n return (\n isStdinTTY() &&\n process.stdout.isTTY === true &&\n typeof stdin.setRawMode === 'function'\n );\n}\n\ninterface ArrowPickResult {\n cancelled: boolean;\n mode: LaunchMenuMode;\n}\n\n/**\n * Raw-mode arrow-key selector over {@link MODE_OPTIONS}.\n *\n * Keys: \u2191/\u2193 (or k/j) move, Enter launches, 1\u20134 jump-launch, q/Esc/Ctrl+C\n * cancel. A live countdown auto-launches the highlighted option after\n * {@link MENU_TIMEOUT_MS}; any keypress stops the countdown. On settle the\n * whole block collapses to a single confirmation line so scrollback stays\n * tidy.\n *\n * Returns `null` when raw mode is unavailable or fails to engage \u2014\n * the caller then runs the numbered readline prompt instead.\n */\nasync function promptModeArrow(deps: RunLaunchMenuDeps): Promise<ArrowPickResult | null> {\n if (!canUseArrowMenu()) return null;\n const { renderer } = deps;\n const stdin = process.stdin;\n const out = (s: string): void => renderer.write(s);\n\n return await new Promise<ArrowPickResult | null>((resolve) => {\n let index = 0;\n let drawn = 0;\n let remaining = Math.round(MENU_TIMEOUT_MS / 1000);\n let countdown = true;\n let settled = false;\n let interval: ReturnType<typeof setInterval> | undefined;\n const wasRaw = stdin.isRaw === true;\n const wasPaused = stdin.isPaused();\n\n const rows = (): string[] => {\n const lines: string[] = [];\n for (let i = 0; i < MODE_OPTIONS.length; i++) {\n const opt = MODE_OPTIONS[i]!;\n const selected = i === index;\n const pointer = selected ? color.pink('\u276F') : ' ';\n const label = selected ? color.amber(color.bold(opt.label)) : color.bold(opt.label);\n lines.push(\n ` ${pointer} ${color.dim(String(opt.key))} ${opt.icon} ${label} ${color.dim(opt.hint)}`,\n );\n }\n lines.push('');\n const auto = countdown\n ? color.dim(` \u00B7 auto-launches ${MODE_OPTIONS[index]!.label} in ${remaining}s`)\n : '';\n lines.push(` ${color.dim('\u2191\u2193 move \u00B7 Enter launch \u00B7 1-4 jump \u00B7 q quit')}${auto}`);\n return lines;\n };\n\n const paint = (): void => {\n const lines = rows();\n let frame = drawn > 0 ? `\\x1b[${drawn}A` : '';\n frame += `${lines.map((line) => `\\x1b[2K${line}`).join('\\n')}\\n`;\n out(frame);\n drawn = lines.length;\n };\n\n const stopInput = (): void => {\n if (interval) {\n clearInterval(interval);\n interval = undefined;\n }\n stdin.off('data', onData);\n stdin.off('close', onClose);\n try {\n setRawMode(stdin, wasRaw);\n } catch {\n // Terminal vanished mid-menu \u2014 nothing to restore.\n }\n if (wasPaused) stdin.pause();\n };\n\n const settle = (result: ArrowPickResult, finalLine: string): void => {\n if (settled) return;\n settled = true;\n stopInput();\n // Collapse the menu block to a single line: jump to the block's\n // first row, wipe to end of screen, print the confirmation.\n if (drawn > 0) out(`\\x1b[${drawn}A`);\n out('\\x1b[0J');\n out(finalLine);\n out('\\x1b[?25h');\n resolve(result);\n };\n\n const pick = (): void => {\n const opt = MODE_OPTIONS[index]!;\n settle(\n { cancelled: false, mode: opt.mode },\n ` ${color.green('\u2714')} ${opt.icon} ${color.bold(opt.label)} ${color.dim(opt.hint)}\\n`,\n );\n };\n\n const cancel = (): void => {\n settle({ cancelled: true, mode: 'tui-repl' }, color.dim(' Goodbye!\\n'));\n };\n\n const stopCountdown = (): void => {\n if (!countdown) return;\n countdown = false;\n if (interval) {\n clearInterval(interval);\n interval = undefined;\n }\n };\n\n const onData = (buf: Buffer): void => {\n const key = buf.toString('utf8');\n stopCountdown();\n if (key === '\\x03' || key === 'q' || key === 'Q' || key === '\\x1b') {\n cancel();\n return;\n }\n if (key === '\\r' || key === '\\n') {\n pick();\n return;\n }\n if (key === '\\x1b[A' || key === '\\x1bOA' || key === 'k') {\n index = (index + MODE_OPTIONS.length - 1) % MODE_OPTIONS.length;\n paint();\n return;\n }\n if (key === '\\x1b[B' || key === '\\x1bOB' || key === 'j') {\n index = (index + 1) % MODE_OPTIONS.length;\n paint();\n return;\n }\n if (/^[0-9]$/.test(key)) {\n const digit = Number.parseInt(key, 10);\n if (digit >= 1 && digit <= MODE_OPTIONS.length) {\n index = digit - 1;\n pick();\n return;\n }\n }\n // Unrecognized key \u2014 repaint to drop the countdown suffix.\n paint();\n };\n\n const onClose = (): void => {\n settle({ cancelled: true, mode: 'tui-repl' }, '');\n };\n\n try {\n setRawMode(stdin, true);\n stdin.resume();\n } catch {\n // Raw mode refused (unusual TTY) \u2014 signal fallback.\n resolve(null);\n return;\n }\n\n out('\\x1b[?25l');\n paint();\n stdin.on('data', onData);\n stdin.once('close', onClose);\n interval = setInterval(() => {\n remaining -= 1;\n if (remaining <= 0) {\n pick();\n return;\n }\n paint();\n }, 1000);\n });\n}\n\n/**\n * One-line \"continue with last settings?\" gate.\n *\n * Returns:\n * - 'use-last' \u2192 caller should reuse `lastChoice` as-is.\n * - 'cancel' \u2192 user typed `q`; caller exits gracefully.\n * - 're-prompt' \u2192 user typed `n` (or anything else); fall through\n * to the numbered menu below.\n */\nasync function promptSummaryGate(\n deps: RunLaunchMenuDeps,\n): Promise<'use-last' | 'cancel' | 're-prompt'> {\n const { renderer, reader, lastChoice } = deps;\n if (!lastChoice) return 're-prompt';\n\n const modeLabel = describeMode(lastChoice.mode);\n const portStr =\n typeof lastChoice.port === 'number'\n ? ` \u00B7 port ${color.bold(String(lastChoice.port))}`\n : '';\n const hostStr =\n typeof lastChoice.host === 'string' ? ` \u00B7 host ${color.dim(lastChoice.host)}` : '';\n renderer.write(`\\n ${color.dim('\u2500'.repeat(48))}\\n`);\n renderer.write(\n ` ${color.cyan('\u23CE')} ${color.dim('Last settings:')} ${color.bold(modeLabel)}${portStr}${hostStr}\\n`,\n );\n renderer.write(` ${color.dim('\u2500'.repeat(48))}\\n`);\n\n const answer = (\n await reader.readLine(\n ` ${color.amber('?')} Continue with these? ${color.dim('[Y/n/q]')} ${color.dim('(auto Y in 5s)')} `,\n { timeoutMs: SUMMARY_TIMEOUT_MS, defaultAnswer: 'y' },\n )\n )\n .trim()\n .toLowerCase();\n\n if (answer === 'q' || answer === 'quit') {\n renderer.write(color.dim(' Goodbye!\\n'));\n return 'cancel';\n }\n if (answer === 'n' || answer === 'no') return 're-prompt';\n return 'use-last';\n}\n\n/**\n * Ask for an optional port. Returns the chosen port, or `defaultPort`\n * if the user pressed Enter / timed out. Validates the range; on\n * invalid input, re-prompts until the user quits or supplies a valid\n * integer (capped at a small bounded retry to keep the menu snappy).\n */\nasync function promptPort(deps: RunLaunchMenuDeps, defaultPort: number): Promise<number> {\n const { renderer, reader } = deps;\n const maxRetries = 3;\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n const answer = (\n await reader.readLine(\n ` ${color.amber('?')} Port ${color.dim(`[${defaultPort}]`)} ${color.dim('(Enter = default, q = cancel)')} `,\n { timeoutMs: PORT_TIMEOUT_MS, defaultAnswer: '' },\n )\n ).trim();\n\n if (answer === '' || answer === '\\n') return defaultPort;\n if (answer === 'q' || answer === 'quit') return defaultPort;\n\n const parsed = Number.parseInt(answer, 10);\n if (Number.isFinite(parsed) && parsed > 0 && parsed < 65536) {\n return parsed;\n }\n renderer.writeWarning(` Invalid port \"${answer}\". Use 1\u201365535.\\n`);\n }\n return defaultPort;\n}\n\n/**\n * Ask for an optional host. HQ defaults to all interfaces (`0.0.0.0`);\n * project-scoped browser surfaces remain loopback-first (`127.0.0.1`).\n * Enter or timeout accepts that default. We deliberately don't validate beyond a non-empty string\n * \u2014 node's `net.createServer().listen(port, host)` will surface any\n * DNS failure at bind time.\n */\nasync function promptHost(deps: RunLaunchMenuDeps, defaultHost: string): Promise<string> {\n const { renderer, reader } = deps;\n renderer.write(\n ` ${color.dim('\u2139')} Press Enter to bind to ${color.bold(defaultHost)}${defaultHost === HQ_DEFAULT_HOST ? ' (all interfaces)' : ' (loopback)'}.\\n`,\n );\n const answer = (\n await reader.readLine(\n ` ${color.amber('?')} Host ${color.dim(`[${defaultHost}]`)} ${color.dim('(Enter = default, q = cancel)')} `,\n { timeoutMs: PORT_TIMEOUT_MS, defaultAnswer: '' },\n )\n ).trim();\n\n if (answer === '' || answer === 'q' || answer === 'quit') return defaultHost;\n return answer;\n}\n\n/**\n * Apply default-port fallback for any mode that binds a port. Keeps\n * the saved `lastChoice` minimal \u2014 we never persist the literal\n * default port (it would just shadow the source-of-truth in\n * port-utils.ts).\n */\nfunction finalize(\n choice: LaunchMenuChoice,\n ports: typeof DEFAULT_PORTS,\n): LaunchMenuResult {\n if (choice.mode === 'tui-repl') return { ...choice, cancelled: false };\n const fallback = ports[choice.mode];\n return {\n ...choice,\n port: typeof choice.port === 'number' ? choice.port : fallback,\n host:\n choice.host ??\n defaultHostFor(choice.mode),\n cancelled: false,\n };\n}\n\nfunction describeMode(mode: LaunchMenuMode): string {\n switch (mode) {\n case 'tui-repl':\n return 'TUI / REPL';\n case 'webui':\n return 'WebUI';\n case 'simpleui':\n return 'SimpleUI';\n case 'hq':\n return 'HQ';\n default: {\n // Exhaustiveness guard \u2014 `mode` is a finite union, so this is\n // unreachable. The runtime check keeps TS's `noUnusedParameters`\n // happy and documents the fallback.\n const exhaustive: never = mode;\n return String(exhaustive);\n }\n }\n}\n\n/**\n * Pure function \u2014 translate a `LaunchMenuResult` into the argv a\n * downstream `boot()` call should consume.\n *\n * Behaviour:\n * - `tui-repl` \u2192 unchanged argv; pre-launch prompts ask TUI vs REPL.\n * - `webui` \u2192 appends `--webui --port=<n> [--host=<h>]`.\n * - `simpleui` \u2192 appends `--simpleui --port=<n> [--host=<h>]`.\n * - `hq` \u2192 appends `--hq --port=<n> [--host=<h>]` (the\n * short-circuit in cli-context.ts will pick this up\n * and dispatch to startHqServer).\n *\n * The function is intentionally argv-only \u2014 no side effects, no I/O \u2014\n * so unit tests can pin the transformation down without mocking\n * readers or renderers.\n */\nexport function applyLaunchMenuToArgv(\n argv: string[],\n result: LaunchMenuResult,\n): string[] {\n if (result.cancelled) return argv;\n const out = [...argv];\n switch (result.mode) {\n case 'tui-repl':\n return out;\n case 'webui':\n if (typeof result.port === 'number') out.push(`--port=${result.port}`);\n if (typeof result.host === 'string') out.push(`--host=${result.host}`);\n out.push('--webui');\n return out;\n case 'simpleui':\n if (typeof result.port === 'number') out.push(`--port=${result.port}`);\n if (typeof result.host === 'string') out.push(`--host=${result.host}`);\n out.push('--simpleui');\n return out;\n case 'hq':\n if (typeof result.port === 'number') out.push(`--port=${result.port}`);\n if (typeof result.host === 'string') out.push(`--host=${result.host}`);\n out.push('--hq');\n return out;\n default: {\n const exhaustive: never = result.mode;\n void exhaustive;\n return out;\n }\n }\n}\n\n/**\n * Convert a {@link LaunchMenuResult} into the shape we persist to\n * `config.launch.menuChoice`. Returns `undefined` for cancellations\n * (we don't want to overwrite a saved choice with nothing) and for\n * `tui-repl` (the inner pre-launch prompts already persist\n * `config.launch.mode` for the TUI/REPL decision).\n *\n * Port validation mirrors `promptPort`'s 1\u201365535 range \u2014 if a\n * caller hands us a result with an out-of-range port we coerce it\n * to `undefined` so the next boot uses the surface default rather\n * than a value that would crash the server.\n */\nexport function toPersistedMenuChoice(\n result: LaunchMenuResult,\n): LaunchMenuChoice | undefined {\n if (result.cancelled) return undefined;\n if (result.mode === 'tui-repl') return undefined;\n const port =\n typeof result.port === 'number' && Number.isFinite(result.port) &&\n result.port > 0 && result.port < 65536\n ? result.port\n : undefined;\n return {\n mode: result.mode,\n ...(port !== undefined ? { port } : {}),\n ...(typeof result.host === 'string' && result.host.length > 0\n ? { host: result.host }\n : {}),\n };\n}\n\n/**\n * Persist a resolved menu choice to the global config so the next\n * boot can offer a one-line \"Continue with last settings?\" gate.\n *\n * Mirrors `persistLaunchChoices` from `pre-launch/launch-prompts.ts`:\n * reads the existing JSON, mutates only `launch.menuChoice`, writes\n * back atomically with mode 0600. Best-effort \u2014 never throws to\n * the caller, so a corrupt config file can't block the actual launch.\n */\nexport async function persistMenuChoice(\n globalConfigPath: string,\n choice: LaunchMenuChoice,\n): Promise<void> {\n let fileExists = false;\n try {\n await fs.access(globalConfigPath);\n fileExists = true;\n } catch {}\n\n let existing: Record<string, unknown> = {};\n try {\n const raw = await fs.readFile(globalConfigPath, 'utf8');\n existing = JSON.parse(raw) as Record<string, unknown>;\n } catch (err) {\n if (fileExists) {\n // Same policy as persistLaunchChoices: refuse to overwrite a\n // corrupt file silently.\n throw new Error(\n `Refusing to overwrite corrupt config at ${globalConfigPath} ` +\n `(${(err as Error).message}). Fix or move the file aside before retrying.`,\n { cause: err },\n );\n }\n existing = {};\n }\n\n const launch = (existing.launch ?? {}) as Record<string, unknown>;\n existing.launch = { ...launch, menuChoice: choice };\n\n await atomicWrite(globalConfigPath, JSON.stringify(existing, null, 2), {\n mode: 0o600,\n });\n}\n", "/**\n * Pre-boot launch banner \u2014 the WRONGSTACK brand mark + wordmark rendered\n * as raw ANSI strings for the plain-terminal launch menu.\n *\n * This is a deliberate plain-string twin of the TUI banner\n * (packages/tui/src/components/history/banner.tsx). Importing the TUI\n * component here would drag ink+react into the pre-boot path \u2014 which may\n * end up launching WebUI/HQ and never need them. When the TUI glyph\n * tables or palette change, update these in the same commit.\n */\n\n// Canonical palette from website/public/wrongstack.svg.\nconst STACK_ORANGE = { r: 0xfd, g: 0x9f, b: 0x02 };\nconst SIGNAL_PINK = { r: 0xfe, g: 0x2e, b: 0x5f };\n\ntype Rgb = { r: number; g: number; b: number };\n\nfunction mixRgb(a: Rgb, b: Rgb, t: number): Rgb {\n const clamped = Math.min(1, Math.max(0, t));\n return {\n r: Math.round(a.r + (b.r - a.r) * clamped),\n g: Math.round(a.g + (b.g - a.g) * clamped),\n b: Math.round(a.b + (b.b - a.b) * clamped),\n };\n}\n\nfunction fg(c: Rgb): string {\n return `\\x1b[38;2;${c.r};${c.g};${c.b}m`;\n}\n\n/**\n * Per-call (not module-load) so tests can toggle NO_COLOR/FORCE_COLOR.\n * Mirrors the semantics of core/utils/color.ts.\n */\nfunction colorsEnabled(): boolean {\n const flag = (value: string | undefined): boolean =>\n value !== undefined && value.trim() !== '' && !/^(0|false|no|off)$/i.test(value.trim());\n if (flag(process.env.NO_COLOR)) return false;\n if (flag(process.env.FORCE_COLOR)) return true;\n return process.stdout.isTTY === true;\n}\n\n// \u2500\u2500 Packed 5\u00D77 wordmark (see tui banner.tsx for the derivation) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nconst WORDMARK_GLYPH_BITS: Readonly<Record<string, ReadonlyArray<string>>> = Object.freeze({\n W: Object.freeze(['10001', '10001', '10001', '10101', '10101', '10101', '01010']),\n R: Object.freeze(['11110', '10001', '10001', '11110', '10100', '10010', '10001']),\n O: Object.freeze(['01110', '10001', '10001', '10001', '10001', '10001', '01110']),\n N: Object.freeze(['10001', '11001', '11001', '10101', '10011', '10011', '10001']),\n G: Object.freeze(['01110', '10001', '10000', '10111', '10001', '10001', '01110']),\n S: Object.freeze(['01111', '10000', '10000', '01110', '00001', '00001', '11110']),\n T: Object.freeze(['11111', '00100', '00100', '00100', '00100', '00100', '00100']),\n A: Object.freeze(['01110', '10001', '10001', '11111', '10001', '10001', '10001']),\n C: Object.freeze(['01111', '10000', '10000', '10000', '10000', '10000', '01111']),\n K: Object.freeze(['10001', '10010', '10100', '11000', '10100', '10010', '10001']),\n});\n\nconst WORDMARK = 'WRONGSTACK';\nconst WORDMARK_PIXEL_ROWS = 7;\nconst WORDMARK_ROWS = Math.ceil(WORDMARK_PIXEL_ROWS / 2);\nconst GLYPH_WIDTH = 5;\n/** Exported so the menu can decide full vs compact by terminal width. */\nexport const WORDMARK_WIDTH = WORDMARK.length * GLYPH_WIDTH + WORDMARK.length - 1;\n\nfunction packedCell(top: string | undefined, bottom: string | undefined): string {\n if (top === '1' && bottom === '1') return '\u2588';\n if (top === '1') return '\u2580';\n if (bottom === '1') return '\u2584';\n return ' ';\n}\n\nfunction packedGlyphRow(glyph: ReadonlyArray<string>, row: number): string {\n const top = glyph[row * 2] ?? '';\n const bottom = glyph[row * 2 + 1] ?? '';\n return Array.from({ length: GLYPH_WIDTH }, (_, column) =>\n packedCell(top[column], bottom[column]),\n ).join('');\n}\n\nconst WORDMARK_LINES: ReadonlyArray<string> = Object.freeze(\n Array.from({ length: WORDMARK_ROWS }, (_, row) =>\n [...WORDMARK]\n .map((letter) => {\n const glyph = WORDMARK_GLYPH_BITS[letter];\n return glyph ? packedGlyphRow(glyph, row) : ' '.repeat(GLYPH_WIDTH);\n })\n .join(' '),\n ),\n);\n\n/** Left-to-right orange\u2192pink gradient across the visible glyphs of a line. */\nfunction gradientLine(text: string, colorOn: boolean): string {\n if (!colorOn) return text;\n const length = text.length;\n let out = '\\x1b[1m';\n for (let i = 0; i < length; i++) {\n const ch = text[i]!;\n if (ch === ' ') {\n out += ch;\n continue;\n }\n const t = length > 1 ? i / (length - 1) : 0.5;\n out += `${fg(mixRgb(STACK_ORANGE, SIGNAL_PINK, t))}${ch}`;\n }\n return `${out}\\x1b[0m`;\n}\n\nfunction dimLine(text: string, colorOn: boolean): string {\n return colorOn ? `\\x1b[2m${text}\\x1b[22m` : text;\n}\n\n// \u2500\u2500 Brand mark: five blocks, pink one dropped half a step (resting frame) \u2500\nconst MARK_COLS = 5;\nconst PINK_HOME = 1;\nconst MARK_WIDTH = MARK_COLS * 2 + (MARK_COLS - 1);\n\nfunction buildMarkLines(colorOn: boolean): string[] {\n const orange = colorOn ? fg(STACK_ORANGE) : '';\n const pink = colorOn ? fg(SIGNAL_PINK) : '';\n const reset = colorOn ? '\\x1b[0m' : '';\n // pinkRow = 1: pink tile occupies rows 1\u20132 of column 1; orange tiles\n // fill rows 0\u20131 everywhere else \u2014 same as the TUI's resting frame.\n return Array.from({ length: 3 }, (_, row) => {\n const cells = Array.from({ length: MARK_COLS }, (_, column) => {\n if (column === PINK_HOME && (row === 1 || row === 2)) return `${pink}\u2588\u2588${reset}`;\n if (row < 2 && column !== PINK_HOME) return `${orange}\u2588\u2588${reset}`;\n return ' ';\n });\n return cells.join(' ').trimEnd();\n });\n}\n\n/**\n * Build the launch-screen banner as an array of pre-colored lines\n * (no trailing newlines, no indent \u2014 the caller owns placement).\n *\n * Full art (mark + wordmark + tagline) when the terminal is wide enough;\n * a one-line gradient fallback otherwise. Honors NO_COLOR / non-TTY by\n * emitting plain text.\n */\nexport function launchBannerLines(columns: number, version?: string): string[] {\n const colorOn = colorsEnabled();\n const tagline = version\n ? `v${version} \u00B7 the wrong stack for all the right reasons`\n : 'the wrong stack for all the right reasons';\n\n if (columns < WORDMARK_WIDTH + 4) {\n const compact = '\u2590\u2588\u258C W R O N G S T A C K';\n return [gradientLine(compact, colorOn), dimLine(tagline, colorOn)];\n }\n\n const markPad = ' '.repeat(Math.max(0, Math.floor((WORDMARK_WIDTH - MARK_WIDTH) / 2)));\n const tagPad = ' '.repeat(Math.max(0, Math.floor((WORDMARK_WIDTH - tagline.length) / 2)));\n return [\n ...buildMarkLines(colorOn).map((line) => markPad + line),\n '',\n ...WORDMARK_LINES.map((line) => gradientLine(line, colorOn)),\n tagPad + dimLine(tagline, colorOn),\n ];\n}\n", "// Side-effect orchestration that runs *after* `boot()` and *before*\n// any heavy subsystem (mailbox, autonomy, brain, eternal engine,\n// webui) is constructed. PR 2 of Issue #29 extracts these from\n// the 2,300-line `main()` body so the post-help-short-circuit\n// flow reads as:\n//\n// if (--help) return help();\n// const ctx = await boot(argv);\n// if (typeof ctx === 'number') return ctx;\n// const pre = await preflight(ctx.config, ctx.updateInfo); // <-- this module\n// ctx.updateInfo = pre.updateInfo;\n// // ... rest of main() with the side effects already applied\n//\n// The four operations live here, in order:\n//\n// 1. `applyNodeEnvDefault()` \\u2014 default to React/Ink PRODUCTION\n// builds when NODE_ENV is unset. Must run before the lazy\n// `--tui` import evaluates ink/react. Explicit user/test\n// overrides win (vitest sets NODE_ENV=test). The marker\n// flag lets `buildChildEnv()` strip the injected value from\n// child processes \\u2014 a leaked NODE_ENV=production would\n// make `pnpm install` skip devDependencies and flip\n// test-runner behavior.\n//\n// 2. `applyPrintUpdateNotice(info)` \\u2014 best-effort update\n// notification. Never blocks boot (2-second timeout). The\n// result supersedes the initial `updateInfo` so the\n// version-aware UI (slash bar, release-notice on the TUI\n// status line) can use it without re-fetching.\n//\n// 3. `applyDebugStreamSeed(config)` \\u2014 seed the stream-debug\n// singleton from persisted config so `WireAdapter` picks\n// it up on construction. Runtime toggles update this\n// singleton directly; the config file is the source of\n// truth for restarts. The default debug-stream callback\n// is intentionally left unset \\u2014 the TUI installs its\n// own reducer-bound callback, and in REPL/headless mode\n// stderr output from the default callback would\n// interfere with the readline prompt and flood the\n// terminal. Data is still collected (and accessible via\n// /diag-stats) but not dumped to the console.\n//\n// The `runPreflight()` orchestrator wraps all three so the\n// caller doesn't have to remember the order, and so the order\n// is documented in one place (here) instead of at the top of\n// every test that needs to set up a fake `BootContext`.\n\nimport type { Config } from '@wrongstack/core/types';\nimport { ensureSessionShell } from '@wrongstack/tools';\nimport type { UpdateInfo } from './update-check.js';\nimport { printUpdateNotice } from './cli-update-notice.js';\n\nexport interface PreflightResult {\n /** The (possibly refreshed) update info, after the 2-second\n * quick-check. Undefined if the check was aborted. */\n updateInfo: UpdateInfo | undefined;\n /** Whether `setDebugStreamEnabled(true)` was called. Callers\n * don't need this today, but exporting it makes the\n * orchestrator's effect explicit. */\n debugStreamEnabled: boolean;\n}\n\n/**\n * Default `NODE_ENV=production` when unset, so the React/Ink\n * `react-reconciler.development.js` path (which ticks\n * `performance.measure()` per render and leaks ~200 user-timing\n * entries/sec into Node's global timeline) is never picked.\n *\n * Must run before the lazy `--tui` import evaluates ink/react.\n * The marker flag lets `buildChildEnv()` strip the injected\n * value from child processes \\u2014 a leaked `NODE_ENV=production`\n * would make `pnpm install` skip devDependencies and flip\n * test-runner behavior.\n */\nexport function applyNodeEnvDefault(): void {\n if (process.env['NODE_ENV'] === undefined) {\n process.env['NODE_ENV'] = 'production';\n process.env['WRONGSTACK_NODE_ENV_DEFAULTED'] = '1';\n }\n}\n\n/**\n * Pin one stable shell for the session on Windows via `WRONGSTACK_SHELL`, so\n * the bash tool's shell routing and the system-prompt Environment block agree\n * on a single target the model can write syntax for. No-op on POSIX and when\n * the user already set a valid `WRONGSTACK_SHELL`. Defaults Windows to\n * PowerShell (pwsh 7+ when present); `WRONGSTACK_SHELL=cmd` opts back to cmd.exe.\n *\n * Like `applyNodeEnvDefault()`, this is idempotent \u2014 once the env var is set the\n * second call (inside `runPreflight()`) is a no-op.\n */\nexport function applySessionShellDefault(): void {\n ensureSessionShell();\n}\n\n/**\n * Best-effort `printUpdateNotice()` wrapper. The 2-second\n * quick-check is a network call that must not block boot;\n * callers get back the (possibly refreshed) `UpdateInfo`\n * so version-aware UI can render without re-fetching.\n */\nexport async function applyPrintUpdateNotice(\n initialUpdateInfo: UpdateInfo | undefined,\n): Promise<UpdateInfo | undefined> {\n return await printUpdateNotice(initialUpdateInfo);\n}\n\n/**\n * Seed the stream-debug singleton from persisted config so\n * `WireAdapter` picks it up on construction. Runtime toggles\n * (e.g. `/diag-stats stream-debug on`) update this singleton\n * directly; the config file is the source of truth for\n * restarts. The default debug-stream callback is intentionally\n * left unset \\u2014 see the module-level docstring for why.\n */\nexport async function applyDebugStreamSeed(config: Config): Promise<void> {\n const { setDebugStreamEnabled } = await import('@wrongstack/providers');\n if (config.debugStream) {\n setDebugStreamEnabled(true);\n }\n}\n\n/**\n * Apply every pre-boot side effect, in dependency order. Returns\n * the (possibly refreshed) update info so the caller can write\n * it back into the `BootContext` for downstream consumers.\n */\nexport async function runPreflight(\n config: Config,\n initialUpdateInfo: UpdateInfo | undefined,\n): Promise<PreflightResult> {\n applyNodeEnvDefault();\n applySessionShellDefault();\n const updateInfo = await applyPrintUpdateNotice(initialUpdateInfo);\n await applyDebugStreamSeed(config);\n return {\n updateInfo,\n debugStreamEnabled: Boolean(config.debugStream),\n };\n}\n", "/**\n * Print the \"Update available: vX \u2192 vY\" notice on stderr.\n *\n * If `initialUpdateInfo` is missing (boot's background check missed the\n * cache), this function fires a fresh quick check with a 2s timeout and\n * returns whichever `UpdateInfo` it ended up with. The caller can chain\n * off the return value to short-circuit later in the boot pipeline.\n *\n * Best-effort: any failure to fetch the update info is swallowed (the\n * notice is decorative, not load-bearing). Returns the resolved\n * `UpdateInfo` so callers that want to log it elsewhere don't have to\n * re-run the check.\n */\nimport { writeErr } from '@wrongstack/core/utils';\nimport type { UpdateInfo } from './update-check.js';\n\nconst NOTICE_FMT = `\\n \\x1b[33m\u2191 Update available: v%s \u2192 v%s\\x1b[0m Run \\`wrongstack update\\` to upgrade.\\n\\n`;\n\nexport async function printUpdateNotice(\n initialUpdateInfo?: UpdateInfo | undefined,\n): Promise<UpdateInfo | undefined> {\n let info = initialUpdateInfo;\n if (!info?.outdated) {\n const ac = new AbortController();\n const timer = setTimeout(() => ac.abort(), 2000);\n try {\n const { checkForUpdate } = await import('./update-check.js');\n info = await checkForUpdate(ac.signal);\n } catch {\n // best-effort\n } finally {\n clearTimeout(timer);\n }\n }\n if (info?.outdated) {\n writeErr(NOTICE_FMT.replace('%s', info.current).replace('%s', info.latest));\n }\n return info;\n}\n", "// PR 3 of Issue #29: extract the PathResolver + EventBus + container\n// setup block (the 49 lines that ran between `runPreflight()` and\n// the modeId/modelCapabilities resolution) into a separate file.\n//\n// Why this split:\n//\n// - The wiring is order-sensitive: PathResolver and EventBus are\n// stand-alone, but `createDefaultContainer({...})` consumes them\n// and must come *after* both. Pulling the wiring into a single\n// `wireContainer()` call makes the order explicit and reviewable\n// in one place, instead of being scattered across the middle of\n// the 2,300-line main() body.\n//\n// - The wiring is also pretty much the *only* place that uses\n// `@wrongstack/runtime`'s `createDefaultContainer` factory.\n// Collapsing it into a 25-line helper means future readers\n// don't have to know the runtime API surface to follow the\n// boot sequence; they just see `wireContainer(...)`.\n//\n// - The `container.bind(TOKENS.X, ...)` calls (ConfigStore,\n// PathResolver, Renderer, InputReader) are bootstrap-level\n// \"overrides\" on top of `createDefaultContainer`'s defaults.\n// Inlining them into the helper means a future change to the\n// bootstrap bindings (e.g. swapping the Renderer for a stub in\n// tests) only needs to touch one file.\n//\n// What is *not* in this helper:\n//\n// - The replay wiring. That block is a `flags['replay']` /\n// `flags['record']` check, not a container-binding step, and\n// moving it in here would force the helper to know about CLI\n// flags. It's slated for a separate PR (boot/replay.ts or\n// similar) that the cli-main refactor issue #29 will track.\n//\n// - The modeId/modelCapabilities resolution. That comes *after*\n// the container is wired, and depends on the resolved\n// container's services. It will land in a follow-up PR\n// (system-prompt.ts or similar).\n\nimport type { Config, Logger, Renderer, ModelsRegistry } from '@wrongstack/core/types';\nimport type { WstackPaths } from '@wrongstack/core/utils';\nimport type { EventBus } from '@wrongstack/core/kernel';\nimport { EventBus as CoreEventBus, TOKENS } from '@wrongstack/core/kernel';\nimport { DefaultPathResolver } from '@wrongstack/core/infrastructure';\nimport { createDefaultContainer } from '@wrongstack/runtime';\nimport { makePromptDelegate } from '../permission-prompt.js';\nimport { resolveBundledSkillsDir } from '../cli-bundled-skills.js';\nimport { resolveBundledPromptsDir } from '../cli-bundled-prompts.js';\n\ninterface WireContainerDeps {\n config: Config;\n wpaths: WstackPaths;\n cwd: string;\n logger: Logger;\n reader: Parameters<typeof makePromptDelegate>[0];\n renderer: Renderer;\n modelsRegistry: ModelsRegistry;\n}\n\n/**\n * Build the PathResolver, create the EventBus, call\n * `createDefaultContainer(...)`, then bind the bootstrap-level\n * services (PathResolver, Renderer, InputReader) on top.\n * Returns the new `events` bus alongside the container so main()\n * can keep publishing to it without re-creating one.\n *\n * The function is intentionally synchronous: every input is a\n * plain value or an already-constructed object, so the boot\n * sequence doesn't fork on async here. Async work (e.g. loading\n * the bundled skills dir) happens inside `createDefaultContainer`\n * and is awaited by the caller.\n */\nexport function wireContainer(deps: WireContainerDeps): {\n pathResolver: InstanceType<typeof DefaultPathResolver>;\n events: EventBus;\n container: ReturnType<typeof createDefaultContainer>;\n} {\n const pathResolver = new DefaultPathResolver(deps.cwd);\n const events = new CoreEventBus();\n events.setLogger(deps.logger);\n\n const container = createDefaultContainer({\n config: deps.config,\n wpaths: deps.wpaths,\n logger: deps.logger,\n modelsRegistry: deps.modelsRegistry,\n events,\n permission: {\n yolo: deps.config.yolo,\n promptDelegate: makePromptDelegate(deps.reader) as NonNullable<NonNullable<Parameters<typeof createDefaultContainer>[0]['permission']>['promptDelegate']>,\n },\n compactor: {\n preserveK: deps.config.context.preserveK,\n eliseThreshold: deps.config.context.eliseThreshold,\n },\n bundledSkillsDir: deps.config.features.skills ? resolveBundledSkillsDir() : undefined,\n bundledPromptsDir:\n deps.config.features.prompts === false ? undefined : resolveBundledPromptsDir(),\n });\n\n // Bootstrap-level overrides on top of `createDefaultContainer`'s\n // defaults. These are the services main() needs to inject *after*\n // the factory runs (the factory doesn't know about the CLI's\n // PathResolver, Renderer, or InputReader \u2014 those are constructed\n // by main() and passed in via `wireContainer`'s deps).\n container.bind(TOKENS.PathResolver, () => pathResolver);\n container.bind(TOKENS.Renderer, () => deps.renderer);\n container.bind(TOKENS.InputReader, () => deps.reader);\n\n return { pathResolver, events, container };\n}\n", "/**\n * Resolves the bundled `<pkg>/skills/` directory shipped with the installed\n * `@wrongstack/core` package. Used by the CLI to discover the curated skill\n * set without making the user point at a path manually.\n *\n * The directory lives at a sibling of `dist/` (in development: `src/`) so\n * the resolution walks one level up from the core package's `package.json`\n * and joins with `skills`. Returns `undefined` if the lookup fails for any\n * reason \u2014 the caller should treat that as \"no bundled skills this run\"\n * and continue without error.\n */\n\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\n\nexport function resolveBundledSkillsDir(): string | undefined {\n try {\n const req = createRequire(import.meta.url);\n const corePkg = req.resolve('@wrongstack/core/package.json');\n return path.join(path.dirname(corePkg), 'skills');\n } catch {\n return undefined;\n }\n}\n", "/**\n * Resolves the bundled `<pkg>/data/prompts/` dataset shipped with the installed\n * `@wrongstack/core` package. Used by the CLI/WebUI to discover the curated\n * builtin prompt library without the user pointing at a path manually.\n *\n * The directory lives at a sibling of `dist/` (in development: `src/`) so the\n * resolution walks one level up from the core package's `package.json` and\n * joins with `data/prompts`. Returns `undefined` if the lookup fails \u2014 the\n * caller treats that as \"no bundled prompts this run\" and continues.\n */\n\nimport { createRequire } from 'node:module';\nimport * as path from 'node:path';\n\nexport function resolveBundledPromptsDir(): string | undefined {\n try {\n const req = createRequire(import.meta.url);\n const corePkg = req.resolve('@wrongstack/core/package.json');\n return path.join(path.dirname(corePkg), 'data', 'prompts');\n } catch {\n return undefined;\n }\n}\n", "import { type Container, TOKENS } from '@wrongstack/core/kernel';\nimport type { Logger, ProviderRunner } from '@wrongstack/core/types';\nimport { type ReplayMode, ReplayProviderRunner } from '@wrongstack/core/replay';\nimport { ReplayLogStore } from '@wrongstack/core/storage';\nimport { runProviderWithRetry } from '@wrongstack/core/agent';\nimport type { WstackPaths } from '@wrongstack/core/utils';\n\n/**\n * Bind a `ReplayProviderRunner` into the container under\n * `TOKENS.ProviderRunner`. The agent picks this up at construction\n * time and uses the wrapped runner for every LLM call.\n *\n * Three modes are exposed via the `mode` parameter:\n *\n * - 'record' \u2014 every real API call is persisted. Used in\n * production-like runs to build a replay log that can later\n * be re-exercised in dev / CI.\n * - 'replay' \u2014 only the log is consulted. The inner runner is\n * never called. Useful for deterministic regression tests\n * and offline debugging.\n * - 'auto' \u2014 record on miss, serve on hit. This is the\n * \"warm start\" mode for dev iterations: the first time a\n * particular request is seen, it is recorded; subsequent\n * identical requests are served from the log.\n *\n * The log lives next to the session JSONL via\n * `sessionScopedPath(projectSessions, sessionId, '.replay.jsonl')`,\n * colocated with annotations and audit sidecars.\n */\nexport interface BindReplayOptions {\n container: Container;\n wpaths: WstackPaths;\n sessionId: string;\n mode: ReplayMode;\n logger?: Logger | undefined;\n}\n\nexport function bindReplayToContainer(opts: BindReplayOptions): void {\n const { container, wpaths, sessionId, mode, logger } = opts;\n if (!opts.container.has(TOKENS.ProviderRunner)) {\n // No prior binding \u2014 install the default `runProviderWithRetry`\n // first so the replay wrapper has a real inner to delegate to.\n container.bind(\n TOKENS.ProviderRunner,\n () =>\n ({\n run: (o) => runProviderWithRetry(o),\n }) satisfies ProviderRunner,\n );\n }\n const inner = container.resolve(TOKENS.ProviderRunner);\n const log = new ReplayLogStore({ dir: wpaths.projectSessions });\n const wrapped = new ReplayProviderRunner(inner, {\n log,\n sessionId,\n mode,\n logger: logger\n ? {\n debug: (m) => logger.debug?.(m),\n warn: (m) => logger.warn?.(m),\n }\n : undefined,\n });\n // Re-bind to override the just-installed default with the wrapped\n // version. Container's `bind` is replace-by-default; if a project's\n // container disallows rebinding, callers should use a decorator\n // pattern via `AgentExtension.wrapProviderRunner` instead.\n container.bind(TOKENS.ProviderRunner, () => wrapped);\n}\n", "/**\n * cli-context \u2014 Boot context initialization for the CLI main entry point.\n *\n * Consolidates the first ~150 lines of the monolithic main() function:\n * - Pre-boot side effects (NODE_ENV, shell default)\n * - Short-circuits (--help, --version, --desktop, --hq)\n * - Interactive launch menu (TUI/REPL \u00B7 WebUI \u00B7 SimpleUI \u00B7 HQ)\n * - Boot() call + preflight\n * - OAuth token persistence\n * - Container wiring (EventBus, DI container)\n * - Replay/record mode wiring\n *\n * Returns a `CliContext` object with all the dependencies the rest of\n * main() needs, or a numeric exit code when a short-circuit fires.\n */\n\nimport { boot } from './boot.js';\nimport { parseArgs } from './arg-parser.js';\nimport { handleHelpVersionShortCircuit } from './boot/short-circuit-flags.js';\nimport { handleDesktopShortCircuit } from './boot/short-circuit-desktop.js';\nimport { handleHqShortCircuit } from './boot/short-circuit-hq.js';\nimport {\n applyLaunchMenuToArgv,\n runLaunchMenu,\n persistMenuChoice,\n toPersistedMenuChoice,\n} from './boot/launch-menu.js';\nimport { ReadlineInputReader } from './input-reader.js';\nimport { TerminalRenderer } from './renderer.js';\nimport { runPreflight } from './preflight.js';\nimport { applyNodeEnvDefault, applySessionShellDefault } from './preflight.js';\nimport { wireContainer } from './boot/container-wiring.js';\nimport { bindReplayToContainer } from './wiring/replay.js';\nimport { setOAuthTokenPersister } from '@wrongstack/providers';\nimport { mutateConfigProviders, normalizeKeys, writeKeysBack } from './provider-config-utils.js';\nimport { activeProfileConfigPath } from './profile-config-path.js';\nimport { TOKENS } from '@wrongstack/core/kernel';\n\nimport type { EventBus } from '@wrongstack/core/kernel';\nimport type { ConfigStore } from '@wrongstack/core/types';\nimport type { BootContext } from './boot.js';\n\n// \u2500\u2500 Context type \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** All boot-phase dependencies the rest of main() needs. */\nexport interface CliContext extends BootContext {\n events: EventBus;\n container: ReturnType<typeof wireContainer>['container'];\n configStore: ConfigStore;\n}\n\n// \u2500\u2500 Initializer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Run all pre-boot and boot-phase setup. Returns a `CliContext` on success,\n * or a numeric exit code when a short-circuit flag (--help, --desktop, --hq)\n * fires. When the return is a number the caller must return it immediately.\n */\nexport async function initializeCli(argv: string[]): Promise<CliContext | number> {\n // Pre-boot side effects (must fire before --help short-circuit).\n applyNodeEnvDefault();\n applySessionShellDefault();\n\n // --help / --version short-circuit.\n const earlyFlags = parseArgs(argv).flags;\n const earlyExit = await handleHelpVersionShortCircuit(argv);\n if (earlyExit !== null) return earlyExit;\n\n // --desktop short-circuit.\n const desktopExit = await handleDesktopShortCircuit(earlyFlags, argv);\n if (desktopExit !== null) return desktopExit;\n\n // Interactive launch menu \u2014 asks the user to pick TUI/REPL \u00B7 WebUI \u00B7\n // SimpleUI \u00B7 HQ when no surface flag was given and stdin is a TTY.\n // No-op when:\n // - any surface flag is present (--webui/--simpleui/--hq/--desktop)\n // - --no-menu is set, or --no-interactive/--skip already opt out\n // - stdin isn't a TTY (CI, pipes, redirects)\n // - first positional is a known subcommand (auth, mcp, \u2026)\n // - any positional arg is present (one-shot query)\n // See `runLaunchMenu` / `shouldSkipMenu` for the full predicate.\n //\n // We mint our own renderer + reader here so the menu doesn't depend\n // on the heavy BootContext. When the menu selects a non-TUI surface\n // we re-run the relevant short-circuit with the augmented argv so\n // existing flag parsing paths keep their single source of truth.\n const { flags: _earlyForMenu, positional: _positionalForMenu } = parseArgs(argv);\n const launchMenuReader = new ReadlineInputReader();\n let menuResult: Awaited<ReturnType<typeof runLaunchMenu>>;\n try {\n menuResult = await runLaunchMenu({\n argv,\n flags: _earlyForMenu,\n positional: _positionalForMenu,\n renderer: new TerminalRenderer(),\n reader: launchMenuReader,\n // Last-saved menu choice wiring is intentionally minimal here:\n // we only honor it when the user has *also* chosen no other\n // surface flag. The persisted record is updated lazily inside\n // boot() via a follow-up patch in the wiring layer, but the\n // menu itself stays stateless so unit tests don't need to mock\n // a ConfigStore. Users who want the saved-port shortcut without\n // the menu can pass `--no-menu --webui --port=<saved>`.\n lastChoice: undefined,\n });\n } finally {\n // The launch menu owns a short-lived readline instance. Fully release it\n // before boot creates its own reader (and before Ink later takes stdin),\n // so no listener or closed-interface state leaks across owners.\n await launchMenuReader.close();\n }\n let effectiveArgv = argv;\n if (menuResult !== null) {\n if (menuResult.cancelled) {\n // User typed `q` \u2014 exit gracefully, no error.\n return 0;\n }\n effectiveArgv = applyLaunchMenuToArgv(argv, menuResult);\n // Re-parse so the downstream short-circuits see the augmented\n // surface flags and any user-typed --port / --host.\n const augmentedFlags = parseArgs(effectiveArgv).flags;\n // Re-run the HQ short-circuit when the menu selected HQ, so we\n // get the same single-source-of-truth behaviour as `wstack --hq`.\n if (menuResult.mode === 'hq') {\n const hqAfterMenu = await handleHqShortCircuit(augmentedFlags);\n if (hqAfterMenu !== null) return hqAfterMenu;\n // Fall through to boot() if HQ short-circuit decided not to\n // fire (e.g. HQ was already running and reported an error\n // that returned a numeric exit). In that case honour what\n // boot() decides with the augmented argv.\n }\n // For webui/simpleui the boot() path already honours the\n // flags (--webui / --simpleui) and --port / --host via its\n // existing surface-detection in cli-context + boot.ts. Nothing\n // else to wire here.\n }\n\n // --hq short-circuit (only reached when the menu did NOT select HQ;\n // when it did, the short-circuit above already returned).\n const hqExit = await handleHqShortCircuit(parseArgs(effectiveArgv).flags);\n if (hqExit !== null) return hqExit;\n\n // Full boot.\n const ctx = await boot(effectiveArgv);\n if (typeof ctx === 'number') return ctx;\n\n // Persist the user's last menu choice so the next boot can show\n // a one-line \"Continue with these?\" summary gate. Best-effort \u2014\n // we swallow errors so a corrupt config file can't break the\n // actual launch. Only webui/simpleui/hq choices are persisted;\n // tui-repl is owned by the inner pre-launch prompts already.\n if (menuResult !== null) {\n const persisted = toPersistedMenuChoice(menuResult);\n if (persisted) {\n try {\n await persistMenuChoice(activeProfileConfigPath(ctx.wpaths, ctx.config), persisted);\n } catch (err) {\n ctx.logger.debug(\n `launch-menu: failed to persist menu choice (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n }\n }\n\n const {\n config,\n vault,\n wpaths,\n cwd,\n modelsRegistry,\n renderer,\n reader,\n logger,\n } = ctx;\n\n // Preflight (update-notice, debug-stream).\n const { updateInfo: refreshedUpdateInfo } = await runPreflight(config, ctx.updateInfo);\n\n // OAuth token persistence.\n const profileConfigPath = activeProfileConfigPath(wpaths, config);\n setOAuthTokenPersister((providerId, creds) => {\n void mutateConfigProviders(profileConfigPath, vault, (all) => {\n const p = all[providerId];\n if (!p) return;\n const keys = normalizeKeys(p);\n const active = p.activeKey ? keys.find((k: { label: string }) => k.label === p.activeKey) : keys[0];\n if (!active) return;\n active.apiKey = creds.accessToken;\n active.refreshToken = creds.refreshToken;\n active.expiresAt = new Date(creds.expiresAt).toISOString();\n if (creds.accountId) active.accountId = creds.accountId;\n writeKeysBack(p, keys);\n }).catch(() => {\n // Best-effort: failed persist leaves the in-memory token valid.\n });\n });\n\n // Container wiring (EventBus, DI container).\n const { events, container } = wireContainer({\n config,\n wpaths,\n cwd,\n logger,\n reader,\n renderer,\n modelsRegistry,\n });\n\n // Replay / record mode.\n const replayFlag = (ctx.flags as Record<string, boolean | string | undefined>)['replay'];\n const recordFlag = (ctx.flags as Record<string, boolean | string | undefined>)['record'];\n if (typeof replayFlag === 'string' || recordFlag === true) {\n const sessionId = typeof replayFlag === 'string' ? replayFlag : `record-${Date.now()}`;\n const mode = recordFlag === true ? 'record' : 'replay';\n bindReplayToContainer({\n container,\n wpaths,\n sessionId,\n mode,\n logger,\n });\n logger.info(`replay: ProviderRunner bound in '${mode}' mode for session ${sessionId}`);\n }\n\n const configStore = container.resolve(TOKENS.ConfigStore);\n\n return {\n ...ctx,\n updateInfo: refreshedUpdateInfo,\n events,\n container,\n configStore,\n } as CliContext;\n}\n", "/**\n * The CLI's outermost entry.\n *\n * This module exists to keep the interactive graph out of the boot graph.\n * `initializeCli()` handles everything that can short-circuit \u2014 `--help`,\n * `--desktop`, `--hq`, and every `wstack <subcommand>` \u2014 and returns a plain\n * exit code in those cases. Only when it returns a live `CliContext` does the\n * session actually need the interactive machinery.\n *\n * That machinery is large: `cli-main.ts` statically imports ~30 wiring modules,\n * which transitively reach `@wrongstack/sdd`, `/acp`, `/sage`, `/mcp` and\n * `/security-scanner` \u2014 measured at 21, 21, 20, 11 and 7.5MB RSS respectively.\n * Measured with the static edge in place, the CLI's always-loaded graph was 270\n * modules; `cli-context.ts` and `boot.ts` on their own reach 64 and 31 modules\n * and NONE of those five packages. So `wstack version` and\n * `wstack mailbox serve` were paying for the whole interactive stack.\n *\n * IMPORTANT: this boundary only works because `@wrongstack/cli` is built with\n * `splitting: true` (scripts/build-package.mjs). With splitting off, esbuild\n * inlines the dynamically imported module into the same output file and hoists\n * its external imports to the top \u2014 the `await import()` below would then defer\n * nothing at all. `packages/cli/tests/architecture/boot-graph-boundary.test.ts`\n * pins both halves of that contract.\n */\nimport { initializeCli } from './cli-context.js';\n\nexport async function main(argv: string[]): Promise<number> {\n const cliCtx = await initializeCli(argv);\n // A number means a short-circuit flag or a subcommand already ran to\n // completion; the interactive stack is never touched.\n if (typeof cliCtx === 'number') return cliCtx;\n\n const { runInteractive } = await import('./cli-main.js');\n return runInteractive(cliCtx);\n}\n", "export { installBrokenPipeHandlers } from './cli-entry-point.js';\nexport { main } from './cli-entry-main.js';\nexport { CLI_VERSION } from './version.js';\n\nimport { runAsMain } from './cli-entry-point.js';\nimport { main } from './cli-entry-main.js';\n\nrunAsMain(main);\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,SAAS,gBAAgB;AAtBzB,IAAM,oBAAoB;AAE1B,SAAS,6BAAmC;A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;AACF;;;AC/MA,eAAsB,KAAK,MAAiC;AAC1D,QAAM,SAAS,MAAM,cAAc,IAAI;AAGvC,MAAI,OAAO,WAAW,SAAU,QAAO;AAEvC,QAAM,EAAE,eAAe,IAAI,MAAM,OAAO,wBAAe;AACvD,SAAO,eAAe,MAAM;AAC9B;;;AC3BA,UAAU,IAAI;",
|
|
6
|
-
"names": ["fs", "path", "toErrorMessage", "color", "writeErr", "stat", "fs", "path", "resolve", "fs", "path", "color", "fs", "path", "color", "toErrorMessage", "color", "answer", "toErrorMessage", "spawn", "resolve", "fs", "atomicWrite", "color", "badges", "badgeStr", "color", "color", "path", "renderer", "writeErr", "toErrorMessage", "color", "spawn", "resolve", "createRequire", "path", "color", "resolve", "fs", "path", "color", "resolve", "color", "atomicWrite", "color", "isStdinTTY", "setRawMode", "HQ_CLI_DEFAULT_HOST", "fs", "_", "HQ_CLI_DEFAULT_HOST", "isStdinTTY", "color", "resolve", "setRawMode", "atomicWrite", "writeErr", "TOKENS", "createDefaultContainer", "createRequire", "path", "resolveBundledSkillsDir", "createRequire", "path", "resolveBundledPromptsDir", "createDefaultContainer", "resolveBundledSkillsDir", "resolveBundledPromptsDir", "TOKENS", "TOKENS", "TOKENS"]
|
|
7
|
-
}
|