carthagent 0.0.0-stage → 1.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +219 -2
- package/bin/ctg.mjs +736 -0
- package/docs/budgets.md +72 -0
- package/docs/compaction.md +34 -0
- package/docs/context-efficiency-plan.md +24 -0
- package/docs/context-efficiency-review.md +27 -0
- package/docs/context-efficiency.md +49 -0
- package/docs/deepseek-jev-benchmark-plan.md +70 -0
- package/docs/deepseek-jev-benchmark-repair-plan.md +20 -0
- package/docs/deepseek-jev-benchmark-restart.md +9 -0
- package/docs/deepseek-jev-benchmark-results.md +77 -0
- package/docs/deepseek-jev-benchmark-running.md +60 -0
- package/docs/deepseek-jev-benchmark-v3-results.md +41 -0
- package/docs/deepseek-jev-benchmark-v4-protocol.md +15 -0
- package/docs/deepseek-jev-benchmark-v4-results.md +119 -0
- package/docs/deepseek-jev-http400-diagnosis.md +45 -0
- package/docs/delivery-review-evidence.md +53 -0
- package/docs/delivery-timeout-repair-plan.md +51 -0
- package/docs/evaluation-readiness.md +31 -0
- package/docs/evaluation.md +70 -0
- package/docs/extending.md +354 -0
- package/docs/glm-pilot-execution.md +9 -0
- package/docs/glm-pilot-plan.md +15 -0
- package/docs/glm-pilot-results.md +71 -0
- package/docs/graph-context-optimization.md +15 -0
- package/docs/jev-repository-pilot-plan.md +25 -0
- package/docs/jev-repository-pilot-protocol.md +39 -0
- package/docs/jev-repository-pilot-restart.md +7 -0
- package/docs/jev-repository-pilot-results.md +79 -0
- package/docs/jev.md +32 -0
- package/docs/model-registry.md +25 -0
- package/docs/native-compatibility.md +117 -0
- package/docs/opencode-archive.md +9 -0
- package/docs/opencode-migration.md +115 -0
- package/docs/opencode-runtime.md +94 -0
- package/docs/opencode-workspace.md +31 -0
- package/docs/owned-runtime-workflow-registration.md +17 -0
- package/docs/plan-advisor-evaluation.md +38 -0
- package/docs/planning-startup-fix-plan.md +23 -0
- package/docs/planning-startup-fix-review.md +24 -0
- package/docs/planning.md +118 -0
- package/docs/production-merge-review.md +23 -0
- package/docs/quality.md +35 -0
- package/docs/repository-benchmark-design.md +111 -0
- package/docs/review-assurance.md +9 -0
- package/docs/review-experiment-results.md +59 -0
- package/docs/tested-planning-roadmap.md +58 -0
- package/docs/tested-planning.md +58 -0
- package/docs/tui-pickers.md +9 -0
- package/docs/webdriver.md +83 -0
- package/docs/workflow-modes.md +26 -0
- package/docs/workflow.d2 +17 -0
- package/docs/workflow.svg +149 -0
- package/docs/workspace-coordination.md +9 -0
- package/evaluate.mjs +249 -0
- package/extensions/codegraph.ts +36 -0
- package/extensions/delivery.ts +819 -0
- package/extensions/experiential.ts +21 -0
- package/extensions/subscriptions.ts +21 -0
- package/guidance/profiles/authenticated-web.json +24 -0
- package/guidance/profiles/data-visualization.json +25 -0
- package/guidance/profiles/database-change.json +24 -0
- package/guidance/profiles/external-api.json +24 -0
- package/guidance/profiles/transactional-data.json +25 -0
- package/guidance/profiles/web-application.json +26 -0
- package/lib/acceptance-review.mjs +4 -0
- package/lib/browser-bin.mjs +160 -0
- package/lib/browser-errors.mjs +54 -0
- package/lib/browser.mjs +219 -0
- package/lib/budget.mjs +37 -0
- package/lib/cdp.mjs +221 -0
- package/lib/cloud/client.mjs +275 -0
- package/lib/cloud/control-plane.mjs +350 -0
- package/lib/cloud/gateway.mjs +380 -0
- package/lib/cloud/http.mjs +135 -0
- package/lib/cloud/ledger.mjs +215 -0
- package/lib/codegraph-query.mjs +60 -0
- package/lib/codegraph.mjs +378 -0
- package/lib/context-archive.mjs +18 -0
- package/lib/delivery-context.mjs +132 -0
- package/lib/delivery-guidance.mjs +9 -0
- package/lib/delivery-review.mjs +94 -0
- package/lib/delivery.mjs +610 -0
- package/lib/engine.mjs +137 -0
- package/lib/guidance.mjs +71 -0
- package/lib/jev-advisor.mjs +47 -0
- package/lib/opencode/archive.mjs +122 -0
- package/lib/opencode/compatibility.mjs +19 -0
- package/lib/opencode/credentials.mjs +205 -0
- package/lib/opencode/evaluation-budget-plugin/index.ts +147 -0
- package/lib/opencode/evaluation.mjs +242 -0
- package/lib/opencode/file-lock.mjs +86 -0
- package/lib/opencode/headless.mjs +200 -0
- package/lib/opencode/review.mjs +213 -0
- package/lib/opencode/runtime.mjs +246 -0
- package/lib/opencode/service.mjs +249 -0
- package/lib/opencode/session-options.mjs +60 -0
- package/lib/opencode/workspace.mjs +133 -0
- package/lib/openrouter-jev.mjs +37 -0
- package/lib/outcome-contract.mjs +21 -0
- package/lib/plan-advisor.mjs +38 -0
- package/lib/planning-access.mjs +7 -0
- package/lib/planning-advice.mjs +28 -0
- package/lib/planning-discovery.mjs +14 -0
- package/lib/planning-guide.mjs +34 -0
- package/lib/planning-view.mjs +57 -0
- package/lib/planning.mjs +155 -0
- package/lib/probe-diagnostics.mjs +13 -0
- package/lib/providers/experiential.mjs +292 -0
- package/lib/providers/model-catalog.json +700 -0
- package/lib/providers/model-catalog.mjs +7 -0
- package/lib/providers/names.mjs +13 -0
- package/lib/providers/subscription-models.mjs +483 -0
- package/lib/reports.mjs +80 -0
- package/lib/review-state.mjs +49 -0
- package/lib/review.mjs +114 -0
- package/lib/scenarios.mjs +99 -0
- package/lib/ship-auth.mjs +44 -0
- package/lib/ship-jev.mjs +59 -0
- package/lib/ship-telemetry.mjs +183 -0
- package/lib/tui/ansi.mjs +255 -0
- package/lib/tui/app.mjs +2445 -0
- package/lib/tui/auth.mjs +249 -0
- package/lib/tui/carthage.mjs +109 -0
- package/lib/tui/clipboard.mjs +122 -0
- package/lib/tui/d2.mjs +431 -0
- package/lib/tui/feed.mjs +467 -0
- package/lib/tui/framing.mjs +80 -0
- package/lib/tui/glyphs.mjs +172 -0
- package/lib/tui/hash-worker.mjs +11 -0
- package/lib/tui/mock-engine.mjs +222 -0
- package/lib/tui/models.mjs +73 -0
- package/lib/tui/picker.mjs +18 -0
- package/lib/tui/theme.mjs +663 -0
- package/lib/tui/title.mjs +7 -0
- package/lib/update-channel.mjs +62 -0
- package/lib/update.mjs +230 -0
- package/lib/webdriver.mjs +82 -0
- package/lib/workflow.mjs +88 -0
- package/lib/workspace.mjs +39 -0
- package/metadata.json +8 -0
- package/package.json +94 -4
- package/plugins/carthagent/index.ts +3 -0
- package/plugins/carthagent/package.json +28 -0
- package/plugins/carthagent/src/archive-rpc.ts +46 -0
- package/plugins/carthagent/src/bootstrap.ts +38 -0
- package/plugins/carthagent/src/index.ts +62 -0
- package/plugins/carthagent/src/pull-request-rpc.ts +54 -0
- package/plugins/carthagent/src/rpc.ts +76 -0
- package/plugins/carthagent/src/server/archive-rpc.ts +327 -0
- package/plugins/carthagent/src/server/budgets.ts +21 -0
- package/plugins/carthagent/src/server/codegraph.ts +46 -0
- package/plugins/carthagent/src/server/delivery.ts +488 -0
- package/plugins/carthagent/src/server/device-auth.ts +91 -0
- package/plugins/carthagent/src/server/native-delivery.ts +26 -0
- package/plugins/carthagent/src/server/orchestration.ts +56 -0
- package/plugins/carthagent/src/server/policy.ts +24 -0
- package/plugins/carthagent/src/server/providers.ts +424 -0
- package/plugins/carthagent/src/server/pull-request-rpc.ts +387 -0
- package/plugins/carthagent/src/server/session-controls.ts +82 -0
- package/plugins/carthagent/src/server/telemetry.ts +92 -0
- package/plugins/carthagent/src/server/workspace-rpc.ts +349 -0
- package/plugins/carthagent/src/session-rpc.ts +31 -0
- package/plugins/carthagent/src/testing.ts +85 -0
- package/plugins/carthagent/src/workspace-rpc.ts +133 -0
- package/plugins/carthagent/test-plugin/index.ts +4 -0
- package/plugins/carthagent/test-plugin/package.json +1 -0
- package/plugins/carthagent/tsconfig.json +19 -0
- package/plugins/carthagent/tui.ts +1 -0
- package/prompts/delivery.md +7 -0
- package/public/index.html +983 -0
- package/scenarios/cli/grade_cli.py +69 -0
- package/scenarios/cli/scenario.json +21 -0
- package/scenarios/game/baseline/minecraft.py +193 -0
- package/scenarios/game/context.md +1 -0
- package/scenarios/game/grade_minecraft_clone.py +603 -0
- package/scenarios/game/requirements.txt +2 -0
- package/scenarios/game/scenario.json +33 -0
- package/server.mjs +341 -0
- package/skills/game-development/SKILL.md +36 -0
- package/skills/game-development/assets/ursina_starter.py +98 -0
- package/skills/game-development/scripts/verify_ursina.py +80 -0
- package/skills/software-delivery/SKILL.md +50 -0
- package/skills/typescript-delivery/SKILL.md +69 -0
- package/tests/acceptance-review.test.mjs +13 -0
- package/tests/auth.test.mjs +234 -0
- package/tests/bounded-summary.test.mjs +68 -0
- package/tests/browser-bin.test.mjs +91 -0
- package/tests/browser.test.mjs +96 -0
- package/tests/budget-engine.test.mjs +110 -0
- package/tests/budget.test.mjs +23 -0
- package/tests/cli.test.mjs +245 -0
- package/tests/clipboard.test.mjs +79 -0
- package/tests/cloud-client.test.mjs +129 -0
- package/tests/cloud-control-plane.test.mjs +144 -0
- package/tests/cloud-gateway.test.mjs +147 -0
- package/tests/cloud-http.test.mjs +102 -0
- package/tests/cloud-ledger.test.mjs +75 -0
- package/tests/codegraph-query.test.mjs +66 -0
- package/tests/codegraph.test.mjs +142 -0
- package/tests/delivery-context.test.mjs +66 -0
- package/tests/delivery-review.test.mjs +139 -0
- package/tests/delivery.test.mjs +343 -0
- package/tests/engine-api.mjs +24 -0
- package/tests/experiential-extension.test.mjs +37 -0
- package/tests/experiential.test.mjs +300 -0
- package/tests/extension.test.mjs +921 -0
- package/tests/fixtures/archive-plugin/index.ts +10 -0
- package/tests/guidance.test.mjs +78 -0
- package/tests/model-registry.test.mjs +68 -0
- package/tests/models.test.mjs +70 -0
- package/tests/openai-idempotency.test.mjs +99 -0
- package/tests/opencode-archive-rpc.test.mjs +82 -0
- package/tests/opencode-delivery.test.mjs +231 -0
- package/tests/opencode-providers.test.mjs +414 -0
- package/tests/opencode-runtime.test.mjs +455 -0
- package/tests/opencode-session-controls.test.mjs +115 -0
- package/tests/opencode-session-options.test.mjs +26 -0
- package/tests/opencode-workspace.test.mjs +339 -0
- package/tests/outcome-contract.test.mjs +17 -0
- package/tests/picker.test.mjs +34 -0
- package/tests/plan-advisor.test.mjs +88 -0
- package/tests/plan-review-loop.test.mjs +53 -0
- package/tests/planning-advice.test.mjs +27 -0
- package/tests/planning-contract.test.mjs +65 -0
- package/tests/planning-startup.test.mjs +38 -0
- package/tests/planning-view.test.mjs +33 -0
- package/tests/planning.test.mjs +223 -0
- package/tests/probe-diagnostics.test.mjs +21 -0
- package/tests/pull-request-rpc.test.mjs +366 -0
- package/tests/review-state.test.mjs +32 -0
- package/tests/review.test.mjs +127 -0
- package/tests/server.test.mjs +252 -0
- package/tests/ship-jev.test.mjs +77 -0
- package/tests/ship-telemetry.test.mjs +333 -0
- package/tests/standard-workflow.test.mjs +28 -0
- package/tests/subscription-models.test.mjs +416 -0
- package/tests/subscriptions-extension.test.mjs +27 -0
- package/tests/terminal-title.test.mjs +13 -0
- package/tests/test_grade_minecraft_clone.py +199 -0
- package/tests/test_starter.py +78 -0
- package/tests/theme.test.mjs +175 -0
- package/tests/tui-copy-paste.test.mjs +54 -0
- package/tests/tui.test.mjs +808 -0
- package/tests/update-channels.test.mjs +129 -0
- package/tests/update.test.mjs +175 -0
- package/tests/webdriver.test.mjs +31 -0
- package/tests/workflow.test.mjs +47 -0
- package/tests/workspace-rpc.test.mjs +236 -0
- package/tests/workspace.test.mjs +24 -0
- package/tools/benchmark/advisor.test.mjs +7 -0
- package/tools/benchmark/advisor.ts +27 -0
- package/tools/benchmark/campaign.mjs +45 -0
- package/tools/benchmark/diagnose-request.mjs +40 -0
- package/tools/benchmark/eval-common.mjs +32 -0
- package/tools/benchmark/eval-ledger.mjs +22 -0
- package/tools/benchmark/eval-shop.mjs +26 -0
- package/tools/benchmark/eval-voxel.mjs +20 -0
- package/tools/benchmark/evaluate.mjs +24 -0
- package/tools/benchmark/evaluators.test.mjs +13 -0
- package/tools/benchmark/fixtures/shop/server.mjs +18 -0
- package/tools/benchmark/fixtures/shop/ui.html +8 -0
- package/tools/benchmark/freeze.mjs +30 -0
- package/tools/benchmark/gateway.mjs +91 -0
- package/tools/benchmark/gateway.test.mjs +38 -0
- package/tools/benchmark/generator.mjs +11 -0
- package/tools/benchmark/generator.test.mjs +26 -0
- package/tools/benchmark/guard.test.mjs +133 -0
- package/tools/benchmark/guard.ts +136 -0
- package/tools/benchmark/native-plugin/index.ts +24 -0
- package/tools/benchmark/planning-startup.test.mjs +47 -0
- package/tools/benchmark/preflight-live.mjs +31 -0
- package/tools/benchmark/preflight.mjs +22 -0
- package/tools/benchmark/replay-diagnostic.mjs +23 -0
- package/tools/benchmark/runner.mjs +141 -0
- package/tools/benchmark/runner.test.mjs +93 -0
- package/tools/benchmark/runtime.mjs +23 -0
- package/tools/benchmark/selftest.mjs +47 -0
- package/tools/benchmark/smoke-jev.mjs +5 -0
- package/tools/benchmark/tasks.mjs +20 -0
- package/tools/benchmark/transport.mjs +65 -0
- package/tools/benchmark/transport.test.mjs +44 -0
- package/tools/benchmark/upstream-error.mjs +18 -0
- package/tools/benchmark/upstream-error.test.mjs +10 -0
- package/tools/browser-check.mjs +109 -0
- package/tools/check-syntax.mjs +27 -0
- package/tools/evaluate-plan-advisor.mjs +20 -0
- package/tools/native-fixture.mjs +194 -0
- package/tools/native-pty-smoke.py +108 -0
- package/tools/native-report-plugin/index.ts +50 -0
- package/tools/native-report-plugin/package.json +7 -0
- package/tools/patch-compaction.mjs +24 -0
- package/tools/patch-model-catalog.mjs +12 -0
- package/tools/patch-print-shutdown.mjs +39 -0
- package/tools/repo-pilot/evaluator.cjs +32 -0
- package/tools/repo-pilot/reference.mjs +43 -0
- package/tools/repo-pilot/runner.mjs +85 -0
- package/tools/repo-pilot/sandbox-entry.mjs +12 -0
- package/tools/repo-pilot/tasks.mjs +20 -0
- package/tools/repo-pilot/type-evaluator.cjs +6 -0
- package/tools/test-native-controls.mjs +84 -0
- package/tools/test-native-delivery-host.mjs +307 -0
- package/tools/test-native-evaluation.mjs +46 -0
- package/tools/test-native-host.mjs +385 -0
- package/tools/test-native-outcomes.mjs +73 -0
- package/tools/test-native-package.mjs +70 -0
- package/tools/test-native-pty.mjs +20 -0
- package/tools/test-native-report.mjs +88 -0
- package/tools/test-native-swe-host.mjs +132 -0
- package/tools/test-native-swe.mjs +122 -0
- package/tools/test-picker-pty.py +45 -0
- package/tools/test-python.mjs +29 -0
- package/tools/test-webdriver.mjs +54 -0
- package/tools/verify-release-version.mjs +37 -0
- package/tools/webdriver-check.mjs +52 -0
- package/vendor/agent/bounded-summary.mjs +88 -0
- package/vendor/agent/chunks/anthropic-messages-VWZZOSJQ.js +6 -0
- package/vendor/agent/chunks/anthropic.js +75 -0
- package/vendor/agent/chunks/azure-openai-responses-BJLAM6CD.js +2 -0
- package/vendor/agent/chunks/bedrock-converse-stream.js +74 -0
- package/vendor/agent/chunks/chord-context.js +96 -0
- package/vendor/agent/chunks/chunk-4L3WN2XY.js +2 -0
- package/vendor/agent/chunks/chunk-6CYCI3EJ.js +12 -0
- package/vendor/agent/chunks/chunk-6R7UI4IY.js +2 -0
- package/vendor/agent/chunks/chunk-7ZC4UXSL.js +2 -0
- package/vendor/agent/chunks/chunk-AXIIZGTV.js +2 -0
- package/vendor/agent/chunks/chunk-CLNPYIDP.js +42 -0
- package/vendor/agent/chunks/chunk-DRQDKNXA.js +2 -0
- package/vendor/agent/chunks/chunk-GMWCTUPB.js +2 -0
- package/vendor/agent/chunks/chunk-IDDQWTHI.js +2 -0
- package/vendor/agent/chunks/chunk-JVUZSMYM.js +1548 -0
- package/vendor/agent/chunks/chunk-L2ZPNLYD.js +2 -0
- package/vendor/agent/chunks/chunk-NUHFSC37.js +25 -0
- package/vendor/agent/chunks/chunk-OUXLLA64.js +11 -0
- package/vendor/agent/chunks/chunk-PGXDEOVV.js +2 -0
- package/vendor/agent/chunks/chunk-PJACZCIR.js +2 -0
- package/vendor/agent/chunks/chunk-PRRNXB7S.js +2 -0
- package/vendor/agent/chunks/chunk-TEPMHNKQ.js +2 -0
- package/vendor/agent/chunks/chunk-TRDNDS6A.js +4 -0
- package/vendor/agent/chunks/chunk-U6ZMQKGD.js +50 -0
- package/vendor/agent/chunks/chunk-UAQELI3K.js +2 -0
- package/vendor/agent/chunks/chunk-USJZMAIR.js +2 -0
- package/vendor/agent/chunks/chunk-XDUWOHPL.js +6 -0
- package/vendor/agent/chunks/chunk-XNGRGP62.js +2 -0
- package/vendor/agent/chunks/github-copilot.js +2 -0
- package/vendor/agent/chunks/google-generative-ai-Q2K7FBDI.js +2 -0
- package/vendor/agent/chunks/google-vertex-7UJBF4S7.js +2 -0
- package/vendor/agent/chunks/https-proxy-agent-2VXB7436.js +13 -0
- package/vendor/agent/chunks/image-resize-worker.js +2 -0
- package/vendor/agent/chunks/kimi-coding.js +2 -0
- package/vendor/agent/chunks/lib-HGQMNYVT.js +9 -0
- package/vendor/agent/chunks/mistral-conversations-4M6BZBX6.js +5 -0
- package/vendor/agent/chunks/multipart-parser-SQ6GDJL7.js +3 -0
- package/vendor/agent/chunks/node-KG362ECQ.js +16 -0
- package/vendor/agent/chunks/node-TWVVAGPO.js +2 -0
- package/vendor/agent/chunks/openai-codex-responses-R6VYZTVY.js +10 -0
- package/vendor/agent/chunks/openai-codex.js +75 -0
- package/vendor/agent/chunks/openai-completions-EKZT2IH2.js +7 -0
- package/vendor/agent/chunks/openai-responses-TFDINO6W.js +2 -0
- package/vendor/agent/chunks/openrouter-images-N4XVVFSD.js +2 -0
- package/vendor/agent/chunks/openrouter.js +75 -0
- package/vendor/agent/chunks/pi-messages-PML4SPVJ.js +8 -0
- package/vendor/agent/chunks/radius.js +75 -0
- package/vendor/agent/chunks/src-UK77SYZE.js +4 -0
- package/vendor/agent/chunks/xai.js +2 -0
- package/vendor/agent/cli.js +3 -0
- package/vendor/agent/dist/modes/interactive/theme/dark.json +91 -0
- package/vendor/agent/dist/modes/interactive/theme/light.json +90 -0
- package/vendor/agent/dist/modes/interactive/theme/theme-schema.json +356 -0
- package/vendor/agent/index.js +2 -0
- package/vendor/agent/modes/interactive/theme/dark.json +91 -0
- package/vendor/agent/modes/interactive/theme/light.json +90 -0
- package/vendor/agent/modes/interactive/theme/theme-schema.json +356 -0
- package/vendor/agent/package.json +14 -0
- package/vendor/agent/rpc-entry.js +3 -0
- package/vendor/agent/theme/dark.json +91 -0
- package/vendor/agent/theme/light.json +90 -0
- package/vendor/agent/theme/theme-schema.json +356 -0
package/lib/tui/app.mjs
ADDED
|
@@ -0,0 +1,2445 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* carthagent TUI — a split-terminal delivery console on top of the bundled engine's `--mode rpc`.
|
|
3
|
+
*
|
|
4
|
+
* ┌ header: 𐤀 · model · status · elapsed · tokens · cost ──────────┐
|
|
5
|
+
* │ RUN TERMINAL (live feed) │ PLAN (live d2 flowchart + │
|
|
6
|
+
* │ │ checks + fingerprint) │
|
|
7
|
+
* │ › input box / footer hints │
|
|
8
|
+
* └─────────────────────────────────────────────────────────────────┘
|
|
9
|
+
*/
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
import { Worker } from 'node:worker_threads';
|
|
12
|
+
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
|
13
|
+
import { join, dirname, resolve } from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
import os from 'node:os';
|
|
16
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
17
|
+
import { planD2, computePhase, freshChecks, coverageReport, verificationMode, evidenceFresh, runCommand } from '../delivery.mjs';
|
|
18
|
+
import { planningView, planningViewLines } from '../planning-view.mjs';
|
|
19
|
+
import { parseD2, renderD2 } from './d2.mjs';
|
|
20
|
+
import { resolveGlyphs, spinnerFrame } from './glyphs.mjs';
|
|
21
|
+
import { createFeed, resetFeed, applyEvent, echoUser, echoBash, notice, renderFeed, runline, hydrateFeed } from './feed.mjs';
|
|
22
|
+
import { getTheme, resolveThemeName, detectTermMode, THEME_NAMES } from './theme.mjs';
|
|
23
|
+
import { frameHint, framePrompt, shouldFrame } from './framing.mjs';
|
|
24
|
+
import { locateEngine, buildEngineArgs, listSessions, mostRecentSession } from '../engine.mjs';
|
|
25
|
+
import { normalizeReviewMode, resolveReviewMode, saveCarthagentConfig, carthagentConfigPath, reviewKickoff, shouldOfferReview } from '../review.mjs';
|
|
26
|
+
import { authTypeLabel, applyAuthEvent, createCloudBillingLink, filterLoginProviders, formatCloudAccount, formatCloudUsage, hasConfiguredProvider, loadAuthRuntime, loadCloudAccount, loadCloudAccountUsage, loginAndRefresh, loginProviderFocus, loginProviderList, newAuthState, revokeCloudSession } from './auth.mjs';
|
|
27
|
+
import { cloudManagedUsageRecovery } from '../cloud/client.mjs';
|
|
28
|
+
import { openBrowser } from '../cloud/client.mjs';
|
|
29
|
+
import { readClipboard, writeClipboard, sanitizePaste } from './clipboard.mjs';
|
|
30
|
+
import { createModelLoader, modelMatchesQuery, modelSupportsThinking, providersFromModels } from './models.mjs';
|
|
31
|
+
import { modelDisplayIdentity, providerDisplayName } from '../providers/names.mjs';
|
|
32
|
+
import { pickerKey, commitPicker } from './picker.mjs';
|
|
33
|
+
import { terminalTitleSequence } from './title.mjs';
|
|
34
|
+
import { compareVersions, latestReleaseCached, packageVersion, updateCheckEnabled } from '../update.mjs';
|
|
35
|
+
import { RESET, BOLD, ITALIC, fg, bg, width, strip, truncate, padEnd, bar, bgLine, colorDepth, sliceCols, inverseCols, wrap } from './ansi.mjs';
|
|
36
|
+
|
|
37
|
+
export { locateEngine, buildEngineArgs };
|
|
38
|
+
|
|
39
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
40
|
+
const ROOT = resolve(__dirname, '..', '..');
|
|
41
|
+
const CTG_BIN = join(ROOT, 'bin', 'ctg.mjs');
|
|
42
|
+
|
|
43
|
+
// ------------------------------------------------------------------ RPC client
|
|
44
|
+
|
|
45
|
+
class EngineRpc {
|
|
46
|
+
constructor() { this.listeners = []; this.pending = new Map(); this.reqId = 0; this.buf = ''; this.proc = null; this.stderrTail = ''; this.gen = 0; }
|
|
47
|
+
/** (Re)spawn the engine child. Calling again force-restarts a wedged process;
|
|
48
|
+
* events from the previous generation are ignored. */
|
|
49
|
+
start({ cmd, args, cwd, env }) {
|
|
50
|
+
const gen = ++this.gen;
|
|
51
|
+
try { this.proc?.kill('SIGKILL'); } catch { }
|
|
52
|
+
this.buf = ''; this.stderrTail = ''; this.exited = null;
|
|
53
|
+
for (const p of this.pending.values()) p.reject(new Error('agent process restarted'));
|
|
54
|
+
this.pending.clear();
|
|
55
|
+
this.proc = spawn(cmd, args, { cwd, env: env || process.env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
56
|
+
this.proc.stdout.on('data', d => {
|
|
57
|
+
if (gen !== this.gen) return;
|
|
58
|
+
this.buf += d.toString();
|
|
59
|
+
let i;
|
|
60
|
+
while ((i = this.buf.indexOf('\n')) !== -1) {
|
|
61
|
+
const line = this.buf.slice(0, i); this.buf = this.buf.slice(i + 1);
|
|
62
|
+
if (!line.trim()) continue;
|
|
63
|
+
let msg; try { msg = JSON.parse(line); } catch { continue; }
|
|
64
|
+
this.dispatch(msg);
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
this.proc.stderr.on('data', d => { if (gen !== this.gen) return; this.stderrTail = (this.stderrTail + d).slice(-4000); });
|
|
68
|
+
this.proc.on('exit', (code, sig) => {
|
|
69
|
+
if (gen !== this.gen) return;
|
|
70
|
+
this.exited = { code, sig };
|
|
71
|
+
for (const l of this.listeners) l({ type: '__exit__', code, sig });
|
|
72
|
+
for (const p of this.pending.values()) p.reject(new Error(`agent exited (${code})`));
|
|
73
|
+
this.pending.clear();
|
|
74
|
+
});
|
|
75
|
+
this.proc.on('error', e => { if (gen !== this.gen) return; for (const l of this.listeners) l({ type: '__error__', error: e }); });
|
|
76
|
+
}
|
|
77
|
+
dispatch(msg) {
|
|
78
|
+
if (msg.type === 'response' && msg.id && this.pending.has(msg.id)) {
|
|
79
|
+
const p = this.pending.get(msg.id); this.pending.delete(msg.id);
|
|
80
|
+
msg.success === false ? p.reject(new Error(msg.error || 'rpc error')) : p.resolve(msg.data);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
for (const l of this.listeners) l(msg);
|
|
84
|
+
}
|
|
85
|
+
onEvent(l) { this.listeners.push(l); }
|
|
86
|
+
send(cmd) {
|
|
87
|
+
const id = `r${++this.reqId}`;
|
|
88
|
+
return new Promise((res, rej) => {
|
|
89
|
+
if (this.exited || !this.proc?.stdin?.writable) return rej(new Error('agent process is not running'));
|
|
90
|
+
this.pending.set(id, { resolve: res, reject: rej });
|
|
91
|
+
try { this.proc.stdin.write(JSON.stringify({ ...cmd, id }) + '\n'); }
|
|
92
|
+
catch (e) { this.pending.delete(id); rej(e); }
|
|
93
|
+
setTimeout(() => { if (this.pending.has(id)) { this.pending.delete(id); rej(new Error(`timeout: ${cmd.type}`)); } }, 30000);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
replyExtensionUi(id, value) {
|
|
97
|
+
try { this.proc?.stdin?.write(JSON.stringify({ type: 'extension_ui_response', id, cancelled: true, ...value }) + '\n'); } catch { }
|
|
98
|
+
}
|
|
99
|
+
kill() { const proc = this.proc; try { proc?.kill('SIGTERM'); } catch { } setTimeout(() => { try { proc?.kill('SIGKILL'); } catch { } }, 800); }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ------------------------------------------------------------------ screen
|
|
103
|
+
|
|
104
|
+
class Screen {
|
|
105
|
+
constructor() { this.prev = []; this.w = 0; this.h = 0; this.onResize = null; this.bgHex = null; }
|
|
106
|
+
enter(cwd) {
|
|
107
|
+
const out = process.stdout;
|
|
108
|
+
this.w = out.columns || 80; this.h = out.rows || 24;
|
|
109
|
+
// Save the shell's title, then replace any stale engine branding.
|
|
110
|
+
out.write('\x1b[22;0t' + terminalTitleSequence(cwd));
|
|
111
|
+
out.write('\x1b[?1049h\x1b[?25l\x1b[?1000h\x1b[?1002h\x1b[?1006h\x1b[?2004h\x1b[2J');
|
|
112
|
+
process.stdin.setRawMode?.(true);
|
|
113
|
+
process.stdin.resume();
|
|
114
|
+
// 'resize' on stdout is emitted on all platforms (SIGWINCH doesn't exist on Windows)
|
|
115
|
+
this._winch = () => { this.w = out.columns; this.h = out.rows; this.prev = []; this.onResize?.(); };
|
|
116
|
+
out.on('resize', this._winch);
|
|
117
|
+
process.on('SIGWINCH', this._winch);
|
|
118
|
+
}
|
|
119
|
+
exit() {
|
|
120
|
+
const out = process.stdout;
|
|
121
|
+
out.off('resize', this._winch);
|
|
122
|
+
process.off('SIGWINCH', this._winch);
|
|
123
|
+
process.stdin.setRawMode?.(false);
|
|
124
|
+
out.write('\x1b[?2004l\x1b[?1006l\x1b[?1002l\x1b[?1000l\x1b[?25h\x1b[?2026l\x1b[?1049l');
|
|
125
|
+
out.write('\x1b[23;0t');
|
|
126
|
+
}
|
|
127
|
+
/** Diff-write a frame: lines[] of styled strings, then place cursor.
|
|
128
|
+
* Each line is full-bleed painted on this.bgHex (set per-frame by render):
|
|
129
|
+
* bg is re-applied after every RESET inside the line, and EL runs while bg
|
|
130
|
+
* is still active so erased cells keep the fill instead of flashing default. */
|
|
131
|
+
frame(lines, cursor) {
|
|
132
|
+
const out = process.stdout;
|
|
133
|
+
const B = this.bgHex ? bg(this.bgHex) : '';
|
|
134
|
+
let s = '\x1b[?2026h';
|
|
135
|
+
for (let y = 0; y < lines.length; y++) {
|
|
136
|
+
if (this.prev[y] === lines[y]) continue;
|
|
137
|
+
s += `\x1b[${y + 1};1H` + (B ? lines[y].split(RESET).join(RESET + B) + B + '\x1b[K' + RESET : lines[y] + '\x1b[K');
|
|
138
|
+
}
|
|
139
|
+
for (let y = lines.length; y < this.prev.length; y++) s += `\x1b[${y + 1};1H` + (B ? B + '\x1b[K' + RESET : '\x1b[K');
|
|
140
|
+
if (cursor) s += `\x1b[${cursor.y};${cursor.x}H\x1b[?25h`;
|
|
141
|
+
else s += '\x1b[?25l';
|
|
142
|
+
s += '\x1b[?2026l';
|
|
143
|
+
out.write(s);
|
|
144
|
+
this.prev = lines;
|
|
145
|
+
this.plain = lines.map(strip); // text-only copy for drag-select extraction
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// ------------------------------------------------------------------ keys
|
|
150
|
+
|
|
151
|
+
const KEY_SEQS = {
|
|
152
|
+
'\x1b[A': 'up', '\x1b[B': 'down', '\x1b[C': 'right', '\x1b[D': 'left',
|
|
153
|
+
'\x1b[H': 'home', '\x1b[F': 'end', '\x1b[1~': 'home', '\x1b[4~': 'end',
|
|
154
|
+
'\x1b[3~': 'delete', '\x1b[5~': 'pgup', '\x1b[6~': 'pgdn', '\x1b[Z': 'stab',
|
|
155
|
+
'\x1bOH': 'home', '\x1bOF': 'end', '\x1bOA': 'up', '\x1bOB': 'down', '\x1bOC': 'right', '\x1bOD': 'left',
|
|
156
|
+
// Modified delete / backspace sequences (Cmd, Ctrl, Alt)
|
|
157
|
+
'\x1b[3;5~': 'ctrl-delete', '\x1b[3;3~': 'alt-delete', '\x1b[3;2~': 'shift-delete',
|
|
158
|
+
'\x1b[3;9~': 'cmd-delete', '\x1b[3;10~': 'cmd-delete',
|
|
159
|
+
// xterm modifyOtherKeys backspace (127) and delete (8)
|
|
160
|
+
'\x1b[27;5;127~': 'ctrl-backspace', '\x1b[27;3;127~': 'alt-backspace', '\x1b[27;2;127~': 'backspace',
|
|
161
|
+
'\x1b[27;9;127~': 'cmd-delete', '\x1b[27;10;127~': 'cmd-delete',
|
|
162
|
+
'\x1b[27;5;8~': 'ctrl-backspace', '\x1b[27;9;8~': 'cmd-delete',
|
|
163
|
+
// Kitty keyboard protocol
|
|
164
|
+
'\x1b[127;5u': 'ctrl-backspace', '\x1b[127;3u': 'alt-backspace', '\x1b[127;2u': 'backspace',
|
|
165
|
+
'\x1b[127;8u': 'cmd-delete', '\x1b[127;9u': 'cmd-delete', '\x1b[127;10u': 'cmd-delete',
|
|
166
|
+
'\x1b[127;13u': 'cmd-delete', '\x1b[127;14u': 'cmd-delete',
|
|
167
|
+
'\x1b[8;5u': 'ctrl-backspace', '\x1b[8;3u': 'alt-backspace', '\x1b[8;9u': 'cmd-delete',
|
|
168
|
+
'\x1b\x7f': 'alt-backspace', '\x1b\x08': 'alt-backspace',
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
export function makeKeyParser(onKey) {
|
|
172
|
+
let buf = '', pasting = false, escTimer = null;
|
|
173
|
+
const decoder = new StringDecoder('utf8');
|
|
174
|
+
let paste = '';
|
|
175
|
+
const flushEsc = () => { if (buf === '\x1b') { buf = ''; onKey({ key: 'esc' }); } };
|
|
176
|
+
return chunk => {
|
|
177
|
+
clearTimeout(escTimer);
|
|
178
|
+
buf += Buffer.isBuffer(chunk) ? decoder.write(chunk) : chunk;
|
|
179
|
+
// Consume every token in order, including mixed text, mouse and paste
|
|
180
|
+
// reports in one read. Keep incomplete escape sequences across reads.
|
|
181
|
+
for (;;) {
|
|
182
|
+
if (!buf) return;
|
|
183
|
+
if (pasting) {
|
|
184
|
+
const end = buf.indexOf('\x1b[201~');
|
|
185
|
+
if (end === -1) {
|
|
186
|
+
let keep = Math.min(buf.length, 5);
|
|
187
|
+
while (keep && !'\x1b[201~'.startsWith(buf.slice(-keep))) keep--;
|
|
188
|
+
paste += buf.slice(0, buf.length - keep);
|
|
189
|
+
buf = keep ? buf.slice(-keep) : '';
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
paste += buf.slice(0, end);
|
|
193
|
+
if (paste) onKey({ key: 'paste', text: sanitizePaste(paste, { multiline: true }) });
|
|
194
|
+
paste = '';
|
|
195
|
+
buf = buf.slice(end + 6); pasting = false; continue;
|
|
196
|
+
}
|
|
197
|
+
if (buf.startsWith('\x1b[200~')) { pasting = true; buf = buf.slice(6); continue; }
|
|
198
|
+
// mouse SGR — carry 1-based cell coords so scroll can route by pane
|
|
199
|
+
const m = buf.match(/^\x1b\[<(\d+);(\d+);(\d+)([Mm])/);
|
|
200
|
+
if (m) {
|
|
201
|
+
buf = buf.slice(m[0].length);
|
|
202
|
+
const raw = +m[1];
|
|
203
|
+
const b = raw & ~28; // strip shift/alt/ctrl modifier bits; low bits carry the button
|
|
204
|
+
const at = { x: +m[2], y: +m[3], ctrl: !!(raw & 16), alt: !!(raw & 8), shift: !!(raw & 4) };
|
|
205
|
+
if (m[4] === 'm') onKey({ key: 'mouseup', button: b, ...at });
|
|
206
|
+
else if (b === 64) onKey({ key: 'wheelup', ...at });
|
|
207
|
+
else if (b === 65) onKey({ key: 'wheeldown', ...at });
|
|
208
|
+
else if (b & 32) onKey({ key: 'mousedrag', button: b & ~32, ...at });
|
|
209
|
+
else onKey({ key: 'mousedown', button: b, ...at });
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
// escape sequences
|
|
213
|
+
let done = false;
|
|
214
|
+
for (const seq of Object.keys(KEY_SEQS).sort((a, b) => b.length - a.length)) {
|
|
215
|
+
if (buf.startsWith(seq)) { onKey({ key: KEY_SEQS[seq] }); buf = buf.slice(seq.length); done = true; break; }
|
|
216
|
+
}
|
|
217
|
+
if (done) continue;
|
|
218
|
+
if (buf === '\x1b') { clearTimeout(escTimer); escTimer = setTimeout(flushEsc, 40); return; }
|
|
219
|
+
if (buf.startsWith('\x1b')) {
|
|
220
|
+
const rest = buf.slice(1);
|
|
221
|
+
if (['\x1b[200~', ...Object.keys(KEY_SEQS)].some(seq => seq.startsWith(buf))) return;
|
|
222
|
+
if (/^\[<[\d;]*$/.test(rest)) return; // incomplete SGR mouse report — wait for M/m terminator
|
|
223
|
+
if ('\x1b['.startsWith(buf.slice(0, 2)) && buf.length < 16 && /[\[\d;?<$u~]/.test(rest)) return; // incomplete seq
|
|
224
|
+
if (rest.length >= 1) { buf = rest; if (buf.startsWith('\x1b')) { buf = buf.slice(1); onKey({ key: 'esc' }); } continue; }
|
|
225
|
+
}
|
|
226
|
+
// plain input
|
|
227
|
+
let i = 0;
|
|
228
|
+
while (i < buf.length) {
|
|
229
|
+
const c = buf[i];
|
|
230
|
+
if (c === '\x1b') break;
|
|
231
|
+
const cp = buf.codePointAt(i);
|
|
232
|
+
const ch = String.fromCodePoint(cp);
|
|
233
|
+
i += ch.length;
|
|
234
|
+
const code = cp;
|
|
235
|
+
if (code === 13 || code === 10) onKey({ key: 'enter' });
|
|
236
|
+
else if (code === 127 || code === 8) onKey({ key: 'backspace' });
|
|
237
|
+
else if (code === 3) onKey({ key: 'ctrl-c' });
|
|
238
|
+
else if (code === 20) onKey({ key: 'ctrl-t' });
|
|
239
|
+
else if (code === 18) onKey({ key: 'ctrl-r' });
|
|
240
|
+
else if (code === 14) onKey({ key: 'ctrl-n' });
|
|
241
|
+
else if (code === 12) onKey({ key: 'ctrl-l' });
|
|
242
|
+
else if (code === 21) onKey({ key: 'ctrl-u' });
|
|
243
|
+
else if (code === 23) onKey({ key: 'ctrl-w' });
|
|
244
|
+
else if (code === 25) onKey({ key: 'ctrl-y' });
|
|
245
|
+
else if (code === 22) onKey({ key: 'ctrl-v' });
|
|
246
|
+
else if (code === 1) onKey({ key: 'home' });
|
|
247
|
+
else if (code === 5) onKey({ key: 'end' });
|
|
248
|
+
else if (code === 11) onKey({ key: 'ctrl-k' });
|
|
249
|
+
else if (code === 9) onKey({ key: 'tab' });
|
|
250
|
+
else if (code === 24) onKey({ key: 'x' });
|
|
251
|
+
else if (code >= 32) onKey({ key: 'char', ch });
|
|
252
|
+
}
|
|
253
|
+
buf = buf.slice(i);
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ------------------------------------------------------------------ slash commands
|
|
259
|
+
|
|
260
|
+
/** Single source of truth for slash-command discovery (autocomplete + /help).
|
|
261
|
+
* Keep in sync with the `slash()` executor switch below — names here must
|
|
262
|
+
* resolve to a real case there, or the popup will offer a no-op command. */
|
|
263
|
+
const SLASH_COMMANDS = [
|
|
264
|
+
{ name: '/help', desc: 'show keys and commands' },
|
|
265
|
+
{ name: '/resume', aliases: ['/sessions'], args: '[id|name]', desc: 'resume a session' },
|
|
266
|
+
{ name: '/new', desc: 'start a fresh session' },
|
|
267
|
+
{ name: '/restart', aliases: ['/kill'], desc: 'force-restart the agent (resumes session)' },
|
|
268
|
+
{ name: '/theme', args: '[name]', desc: 'pick or set the theme' },
|
|
269
|
+
{ name: '/model', args: '[name]', desc: 'pick or set the model' },
|
|
270
|
+
{ name: '/thinking', desc: 'set the thinking level' },
|
|
271
|
+
{ name: '/compact', args: '[notes]', desc: 'compact the context window' },
|
|
272
|
+
{ name: '/autocompact', args: '[on|off]', desc: 'toggle automatic context compaction' },
|
|
273
|
+
{ name: '/review', aliases: ['/review-mode'], args: '[ask|yes|no|status]', desc: 'self-review loop control' },
|
|
274
|
+
{ name: '/export', args: '[file]', desc: 'export the session to HTML' },
|
|
275
|
+
{ name: '/copy', desc: 'copy the full last assistant response' },
|
|
276
|
+
{ name: '/stats', desc: 'show session token/cost stats' },
|
|
277
|
+
{ name: '/clear', desc: 'clear the message feed' },
|
|
278
|
+
{ name: '/abort', desc: 'abort the current run' },
|
|
279
|
+
{ name: '/raw', args: '<prompt>', desc: 'send without delivery framing' },
|
|
280
|
+
{ name: '/guide', args: '[task]', desc: 'toggle or run phased delivery framing' },
|
|
281
|
+
{ name: '/login', aliases: ['/auth'], desc: 'connect an AI provider' },
|
|
282
|
+
{ name: '/account', aliases: ['/cloud'], desc: 'show Ship usage, credit, plan, and sessions' },
|
|
283
|
+
{ name: '/usage', desc: 'show recent Ship usage' },
|
|
284
|
+
{ name: '/billing', args: '[checkout [plan]|portal]', desc: 'open Ship billing' },
|
|
285
|
+
{ name: '/logout-cloud', args: '[session-id]', desc: 'revoke a Ship CLI session' },
|
|
286
|
+
{ name: '/update', args: '[check]', desc: 'update carthagent to the latest release' },
|
|
287
|
+
{ name: '/quit', aliases: ['/q', '/exit'], desc: 'quit carthagent' },
|
|
288
|
+
];
|
|
289
|
+
|
|
290
|
+
/** Pure filter for slash-command autocomplete. `q` is the buffer text starting
|
|
291
|
+
* with '/'. Returns matching command entries (name or alias startsWith q).
|
|
292
|
+
* Returns [] once a space appears (we're past the command token, into args). */
|
|
293
|
+
export function matchSlash(q, list = SLASH_COMMANDS) {
|
|
294
|
+
if (!q.startsWith('/') || q.includes(' ')) return [];
|
|
295
|
+
const ql = q.toLowerCase();
|
|
296
|
+
return list.filter(c => c.name.toLowerCase().startsWith(ql)
|
|
297
|
+
|| (c.aliases || []).some(a => a.toLowerCase().startsWith(ql)));
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export function cloudManagedUsageNotice(event, activeModel = '') {
|
|
301
|
+
const message = event?.message;
|
|
302
|
+
if (event?.type !== 'message_end' || message?.role !== 'assistant' || message.stopReason !== 'error') return null;
|
|
303
|
+
const provider = message.provider || String(activeModel).split('/')[0];
|
|
304
|
+
return provider === 'experiential-labs' ? cloudManagedUsageRecovery(message.errorMessage) : null;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export function isCloudCreditExhaustion(event, activeModel = '') {
|
|
308
|
+
return cloudManagedUsageNotice(event, activeModel) !== null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Compute geometry for the slash-command autocomplete card.
|
|
312
|
+
* The card is left-justified (aligned with prompt area: x0 = 2) and sized
|
|
313
|
+
* adequately to hold command details without border overflow. */
|
|
314
|
+
export function slashCardDimensions(W) {
|
|
315
|
+
const cardW = Math.max(16, Math.min(W - 4, 88));
|
|
316
|
+
const innerW = Math.max(2, cardW - 2);
|
|
317
|
+
const x0 = Math.min(2, Math.max(0, W - cardW));
|
|
318
|
+
return { cardW, innerW, x0 };
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Render slash autocomplete card lines for testing and TUI rendering. */
|
|
322
|
+
export function syncActiveModel(state, feed, model) {
|
|
323
|
+
if (!model?.provider || !model?.id) return;
|
|
324
|
+
state.model = `${model.provider}/${model.id}`;
|
|
325
|
+
let changed = false;
|
|
326
|
+
for (const block of feed.blocks) {
|
|
327
|
+
if (block.kind === 'welcome' && block.model !== modelDisplayIdentity(state.model)) {
|
|
328
|
+
block.model = modelDisplayIdentity(state.model);
|
|
329
|
+
changed = true;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
if (changed) feed.version++;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export function renderSlashCard(items, sel, W, t = {}, G = { active: '●' }) {
|
|
336
|
+
const { cardW, innerW, x0 } = slashCardDimensions(W);
|
|
337
|
+
const accent = t.primary || t.accent || '#888';
|
|
338
|
+
const faint = t.textMuted || t.faint || '#666', muted = t.muted || faint;
|
|
339
|
+
const bc = accent;
|
|
340
|
+
const row = core => fg(bc) + '│' + RESET + padEnd(truncate(core, innerW), innerW) + fg(bc) + '│' + RESET;
|
|
341
|
+
const card = [];
|
|
342
|
+
const title = ' commands ';
|
|
343
|
+
card.push(fg(bc) + '╭' + '─'.repeat(2) + RESET + fg(muted) + title + RESET + fg(bc) + '─'.repeat(Math.max(0, innerW - 2 - title.length)) + '╮' + RESET);
|
|
344
|
+
const maxRows = Math.min(items.length, 8);
|
|
345
|
+
const selIdx = Math.min(sel, Math.max(0, items.length - 1));
|
|
346
|
+
const start = Math.max(0, selIdx - maxRows + 1);
|
|
347
|
+
for (let i = start; i < start + maxRows; i++) {
|
|
348
|
+
const c = items[i];
|
|
349
|
+
if (!c) { card.push(row('')); continue; }
|
|
350
|
+
const isSel = i === selIdx;
|
|
351
|
+
const marker = isSel ? fg(accent) + G.active + RESET : ' ';
|
|
352
|
+
const aliases = c.aliases?.length ? fg(faint) + ' (' + c.aliases.join(', ') + ')' + RESET : '';
|
|
353
|
+
const args = c.args ? fg(faint) + ' ' + c.args + RESET : '';
|
|
354
|
+
const nameCol = (isSel ? fg(accent) + BOLD : fg(t.text || '#eee')) + c.name + RESET;
|
|
355
|
+
const descCol = fg(faint) + ' — ' + c.desc + RESET;
|
|
356
|
+
const core = ' ' + marker + ' ' + nameCol + aliases + args + descCol;
|
|
357
|
+
card.push(row(core));
|
|
358
|
+
}
|
|
359
|
+
const hints = ` ${items.length ? selIdx + 1 : 0}/${items.length} · ↑↓ browse · Tab complete · Enter activate · Esc dismiss `;
|
|
360
|
+
card.push(row(fg(faint) + hints + RESET));
|
|
361
|
+
card.push(fg(bc) + '╰' + '─'.repeat(innerW) + '╯' + RESET);
|
|
362
|
+
return { card, cardW, innerW, x0 };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// Manual plan-scroll sentinel: null/PLAN_FOLLOW = auto-follow frontier.
|
|
366
|
+
const PLAN_FOLLOW = -1;
|
|
367
|
+
|
|
368
|
+
/** Rail width tiers: wider terminals get a wider PLAN rail (still split). */
|
|
369
|
+
export function planSideWidth(W) {
|
|
370
|
+
if (W >= 200) return Math.min(84, Math.floor(W * 0.42));
|
|
371
|
+
if (W >= 160) return Math.min(72, Math.floor(W * 0.40));
|
|
372
|
+
if (W >= 120) return Math.min(64, Math.floor(W * 0.38));
|
|
373
|
+
return Math.max(34, Math.min(56, Math.floor(W * 0.36)));
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** Map a scrolling viewport onto a scrollbar track: the thumb {pos,len} in
|
|
377
|
+
* cells, or null when the content already fits (nothing to scroll). */
|
|
378
|
+
export function barRange(viewport, total, start) {
|
|
379
|
+
if (viewport <= 0 || total <= viewport) return null;
|
|
380
|
+
const len = Math.max(1, Math.round(viewport * viewport / total));
|
|
381
|
+
const maxStart = Math.max(1, total - viewport);
|
|
382
|
+
const clamped = Math.min(Math.max(0, start || 0), maxStart);
|
|
383
|
+
const pos = Math.min(viewport - len, Math.round((viewport - len) * clamped / maxStart));
|
|
384
|
+
return { pos, len };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** One scrollbar cell in the active theme: a faint track and a brighter thumb
|
|
388
|
+
* (accent while its pane is focused). Carries no background — the pane paints it. */
|
|
389
|
+
export function scrollCell(glyphs, kind, focused, t) {
|
|
390
|
+
if (kind !== 'thumb' && kind !== 'track') return ' ';
|
|
391
|
+
const track = t.borderSubtle || t.border || t.textMuted;
|
|
392
|
+
const thumb = focused ? (t.primary || t.accent) : (t.secondary || t.accent2 || t.textMuted || t.borderActive);
|
|
393
|
+
return fg(kind === 'thumb' ? thumb : track) + (kind === 'thumb' ? glyphs.scrollThumb : glyphs.scrollTrack) + RESET;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Clamp a drag-copy column range to the pane where the drag began, so feed
|
|
397
|
+
* text copies without the scrollbar, the pane separator or plan-rail
|
|
398
|
+
* fragments. `clip` is the render-time geometry {feedEnd, planStart, planEnd,
|
|
399
|
+
* rowTop, rowBottom} (0-based, end-exclusive); `anchorX` is the 1-based
|
|
400
|
+
* mousedown column, `row` the 1-based screen row of this line, and [c0,c1)
|
|
401
|
+
* the raw 0-based column range for it. */
|
|
402
|
+
export function paneClipCols(clip, anchorX, row, c0, c1) {
|
|
403
|
+
if (!clip || row - 1 < clip.rowTop || row - 1 > clip.rowBottom) return [c0, c1];
|
|
404
|
+
if (anchorX - 1 >= clip.planStart) return [Math.max(c0, clip.planStart), Math.min(c1, clip.planEnd)];
|
|
405
|
+
return [c0, Math.min(c1, clip.feedEnd)];
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// ------------------------------------------------------------------ editor
|
|
409
|
+
|
|
410
|
+
export function selectionBounds(sel) {
|
|
411
|
+
const a = { x: sel.ax, y: sel.ay }, b = { x: sel.bx, y: sel.by };
|
|
412
|
+
return (a.y < b.y || (a.y === b.y && a.x <= b.x)) ? [a, b] : [b, a];
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
export function selectionText(lines, sel, columns, clip = null) {
|
|
416
|
+
const [top, bot] = selectionBounds(sel);
|
|
417
|
+
const rows = [];
|
|
418
|
+
for (let y = Math.max(1, top.y); y <= Math.min(lines.length, bot.y); y++) {
|
|
419
|
+
const [c0, c1] = paneClipCols(clip, sel.ax, y, y === top.y ? top.x - 1 : 0, y === bot.y ? bot.x : columns);
|
|
420
|
+
rows.push(sliceCols(lines[y - 1] || '', Math.max(0, c0), Math.max(0, c1)).replace(/\s+$/, ''));
|
|
421
|
+
}
|
|
422
|
+
return rows.join('\n').replace(/^\n+|\n+$/g, '');
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
class Editor {
|
|
426
|
+
constructor() { this.buf = ''; this.cur = 0; this.history = []; this.hi = -1; this.saved = ''; }
|
|
427
|
+
insert(s) { this.buf = this.buf.slice(0, this.cur) + s + this.buf.slice(this.cur); this.cur += s.length; }
|
|
428
|
+
backspace() { if (this.cur > 0) { this.buf = this.buf.slice(0, this.cur - 1) + this.buf.slice(this.cur); this.cur--; } }
|
|
429
|
+
del() { this.buf = this.buf.slice(0, this.cur) + this.buf.slice(this.cur + 1); }
|
|
430
|
+
wordBack() { const m = this.buf.slice(0, this.cur).match(/\S+\s*$/); if (m) { this.buf = this.buf.slice(0, this.cur - m[0].length) + this.buf.slice(this.cur); this.cur -= m[0].length; } }
|
|
431
|
+
killEnd() { this.buf = this.buf.slice(0, this.cur); }
|
|
432
|
+
clear() { this.buf = ''; this.cur = 0; }
|
|
433
|
+
up() { if (!this.history.length) return; if (this.hi === -1) { this.saved = this.buf; this.hi = this.history.length - 1; } else if (this.hi > 0) this.hi--; this.buf = this.history[this.hi]; this.cur = this.buf.length; }
|
|
434
|
+
down() { if (this.hi === -1) return; if (this.hi < this.history.length - 1) { this.hi++; this.buf = this.history[this.hi]; } else { this.hi = -1; this.buf = this.saved; } this.cur = this.buf.length; }
|
|
435
|
+
take() { const v = this.buf; if (v.trim()) { this.history.push(v); if (this.history.length > 200) this.history.shift(); } this.hi = -1; this.clear(); return v; }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// ------------------------------------------------------------------ delivery → graph states
|
|
439
|
+
|
|
440
|
+
export function computeNodeStates(delivery, checksRunning, checkRunId, currentHash) {
|
|
441
|
+
const states = new Map();
|
|
442
|
+
const plan = delivery?.plan;
|
|
443
|
+
if (!plan) return { states, checkRows: [], status: null, allFresh: false, anyFail: false };
|
|
444
|
+
const ev = delivery.evidence || {};
|
|
445
|
+
const status = delivery.status || 'implementing';
|
|
446
|
+
const checks = plan.checks || [];
|
|
447
|
+
let firstQueued = false;
|
|
448
|
+
const checkRows = checks.map(c => {
|
|
449
|
+
const e = ev[c.id];
|
|
450
|
+
let st = 'pending';
|
|
451
|
+
if (e) st = e.passed ? 'done' : 'fail';
|
|
452
|
+
const stale = !!(e?.passed && currentHash && !evidenceFresh(c, e, currentHash, delivery));
|
|
453
|
+
if (stale) st = 'stale';
|
|
454
|
+
if (checksRunning && !e) {
|
|
455
|
+
// during an id="all" run the first pending row is the one executing
|
|
456
|
+
const isCurrent = checkRunId === 'all' ? !firstQueued : checkRunId === c.id;
|
|
457
|
+
st = isCurrent ? 'running' : 'queued';
|
|
458
|
+
if (isCurrent) firstQueued = true;
|
|
459
|
+
}
|
|
460
|
+
return { id: c.id, kind: c.kind, st, code: e?.code, ms: e?.durationMs, required: c.id.startsWith('required_') };
|
|
461
|
+
});
|
|
462
|
+
const allPass = checks.length > 0 && checkRows.every(r => r.st === 'done');
|
|
463
|
+
const allFresh = allPass && !checkRows.some(r => r.st === 'stale');
|
|
464
|
+
const anyFail = checkRows.some(r => r.st === 'fail');
|
|
465
|
+
states.set('goal', 'done');
|
|
466
|
+
const implActive = status === 'implementing' || status === 'planned';
|
|
467
|
+
const stepStatus = delivery.stepStatus || {};
|
|
468
|
+
const stepStates = (plan.steps || []).map((_, i) => stepStatus[`step${i}`]);
|
|
469
|
+
// Exactly one "current" step: the first explicit active, else the first
|
|
470
|
+
// step not already done/failed. Previously every unmarked step rendered as
|
|
471
|
+
// active while implementing, so the D2 rail lit a swirl on the whole plan
|
|
472
|
+
// and auto-follow pinned to step0 no matter where the agent actually was.
|
|
473
|
+
let current = stepStates.findIndex(s => s === 'active');
|
|
474
|
+
if (current < 0) current = stepStates.findIndex(s => s !== 'done' && s !== 'failed');
|
|
475
|
+
(plan.steps || []).forEach((_, i) => {
|
|
476
|
+
const st = stepStates[i];
|
|
477
|
+
if (typeof plan.steps[i] !== 'string') {
|
|
478
|
+
states.set(`step${i}`, st === 'done' ? 'done' : st === 'failed' ? 'fail' : st === 'active' ? 'active' : 'pending');
|
|
479
|
+
}
|
|
480
|
+
else if (st === 'done') states.set(`step${i}`, 'done');
|
|
481
|
+
else if (st === 'failed') states.set(`step${i}`, 'fail');
|
|
482
|
+
else if (!implActive) states.set(`step${i}`, 'done');
|
|
483
|
+
else if (i === current) states.set(`step${i}`, 'active');
|
|
484
|
+
else if (i < current) states.set(`step${i}`, 'done');
|
|
485
|
+
else states.set(`step${i}`, 'pending');
|
|
486
|
+
});
|
|
487
|
+
let verify = 'pending';
|
|
488
|
+
const informative = verificationMode(plan) !== 'required';
|
|
489
|
+
if (informative && checks.length === 0) verify = 'done';
|
|
490
|
+
else if (anyFail) verify = 'fail';
|
|
491
|
+
else if (checksRunning) verify = 'active';
|
|
492
|
+
else if (allFresh && status === 'verified') verify = 'done';
|
|
493
|
+
else if (allFresh) verify = 'done';
|
|
494
|
+
else if (status === 'verifying') verify = 'pending';
|
|
495
|
+
else if (allPass) verify = 'done';
|
|
496
|
+
if (status === 'blocked' && !checksRunning) verify = anyFail ? 'fail' : 'blocked';
|
|
497
|
+
states.set('verify', verify);
|
|
498
|
+
states.set('repair', anyFail && !informative ? 'fail' : 'pending');
|
|
499
|
+
states.set('review', status === 'verified' ? 'done' : (allFresh && !anyFail) || informative ? 'active' : 'pending');
|
|
500
|
+
states.set('deliver', status === 'verified' ? 'done' : status === 'blocked' ? 'blocked' : 'pending');
|
|
501
|
+
if (plan.workflow || plan.design) {
|
|
502
|
+
const view = planningView(delivery, currentHash, { runningCheck: checksRunning && checkRunId !== 'all' ? checkRunId : undefined });
|
|
503
|
+
for (const node of view.workflow?.nodes || []) states.set(node.id, node.status);
|
|
504
|
+
if (!plan.workflow && view.gate.locked) for (let i = 0; i < plan.steps.length; i++) if (!['done', 'fail'].includes(states.get(`step${i}`))) states.set(`step${i}`, 'blocked');
|
|
505
|
+
}
|
|
506
|
+
return { states, checkRows, status, allFresh, anyFail };
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// ------------------------------------------------------------------ app
|
|
510
|
+
|
|
511
|
+
export async function runTui(opts) {
|
|
512
|
+
const cwd = opts.cwd || process.cwd();
|
|
513
|
+
const termMode = detectTermMode(process.env);
|
|
514
|
+
const T = { theme: getTheme(resolveThemeName(opts.theme), termMode) };
|
|
515
|
+
const G = resolveGlyphs({ ascii: opts.ascii, mode: opts.glyphs });
|
|
516
|
+
const spin = frame => spinnerFrame(G, frame);
|
|
517
|
+
const feed = createFeed();
|
|
518
|
+
const screen = new Screen();
|
|
519
|
+
const editor = new Editor();
|
|
520
|
+
const rpc = new EngineRpc();
|
|
521
|
+
|
|
522
|
+
const state = {
|
|
523
|
+
view: 'split', // split | feed | plan
|
|
524
|
+
scroll: 0, // feed scroll offset from bottom
|
|
525
|
+
expand: false,
|
|
526
|
+
running: false,
|
|
527
|
+
awaitingRun: false, // prompt sent, agent_start not yet seen — keep the UI alive
|
|
528
|
+
sessionId: null,
|
|
529
|
+
model: opts.model || '',
|
|
530
|
+
thinking: opts.thinking || '',
|
|
531
|
+
isCompacting: false,
|
|
532
|
+
autoCompaction: true,
|
|
533
|
+
checkRunId: null,
|
|
534
|
+
runStarted: 0,
|
|
535
|
+
runEnded: 0,
|
|
536
|
+
delivery: null, // report.json contents
|
|
537
|
+
d2Source: '',
|
|
538
|
+
d2Graph: null,
|
|
539
|
+
currentHash: '',
|
|
540
|
+
checkToolRunning: false,
|
|
541
|
+
lastActivity: Date.now(),
|
|
542
|
+
toast: null, // {text, tone, until}
|
|
543
|
+
startedAt: Date.now(),
|
|
544
|
+
focusPane: 'feed', // split-view scroll focus: 'feed' | 'plan'
|
|
545
|
+
planningTab: 'workflow',
|
|
546
|
+
planScroll: null, // null = auto-follow frontier; number = manual graph start row
|
|
547
|
+
autoFraming: opts.autoFraming ?? true, // phased delivery framing for plain prompts
|
|
548
|
+
stats: null, // get_session_stats payload
|
|
549
|
+
overlay: null, // settings overlay: { row: 0=theme,1=provider,2=model, provider?, search?, modelSel? }
|
|
550
|
+
modelList: null, // cached get_available_models response [{provider,id,...}]
|
|
551
|
+
sessionFile: null, // current session .jsonl path (get_state.sessionFile)
|
|
552
|
+
sessionName: null,
|
|
553
|
+
abortAt: 0, // soft-abort requested at; esc/^c again force-restarts the engine
|
|
554
|
+
sessions: null, // resume picker: { items, sel, search }
|
|
555
|
+
slash: null, // slash-command autocomplete: { items, sel }
|
|
556
|
+
hydrated: false, // feed was rebuilt from a session file
|
|
557
|
+
sel: null, // active mouse selection {ax,ay,bx,by,dragged}
|
|
558
|
+
runWrites: 0, // write/edit tool calls in the current run
|
|
559
|
+
reviewOffer: null, // pending self-review offer {reason}
|
|
560
|
+
reviewLoop: false, // a self-review loop is running — suppress re-offers
|
|
561
|
+
reviewOfferedRuns: new Set(), // run keys already offered (dedupe)
|
|
562
|
+
reviewPendingVerified: false, // report.json flipped to verified this run
|
|
563
|
+
auth: null, // connect-provider popup: see lib/tui/auth.mjs
|
|
564
|
+
cloudRecoveryOfferedAt: 0,
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
// ---- spawn agent
|
|
568
|
+
let engineCmd;
|
|
569
|
+
if (opts.demo) engineCmd = { cmd: process.execPath, args: [join(__dirname, 'mock-engine.mjs')] };
|
|
570
|
+
else {
|
|
571
|
+
try { engineCmd = locateEngine(opts.engineCli); }
|
|
572
|
+
catch (e) { console.error(e.message); process.exit(1); }
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const baseArgs = () => opts.demo ? engineCmd.args : [...engineCmd.args, '--mode', 'rpc', ...buildEngineArgs({ isolate: true, ...opts, cwd })];
|
|
576
|
+
const spawnEngine = (extraArgs = []) => rpc.start({
|
|
577
|
+
cmd: engineCmd.cmd,
|
|
578
|
+
args: [...baseArgs(), ...extraArgs],
|
|
579
|
+
cwd,
|
|
580
|
+
env: {
|
|
581
|
+
...process.env,
|
|
582
|
+
CARTHAGENT_CODING_AGENT_DIR: process.env.CARTHAGENT_CODING_AGENT_DIR || join(os.homedir(), '.carthagent', 'agent'),
|
|
583
|
+
PI_CODING_AGENT_DIR: process.env.PI_CODING_AGENT_DIR || process.env.CARTHAGENT_CODING_AGENT_DIR || join(os.homedir(), '.carthagent', 'agent'),
|
|
584
|
+
CARTHAGENT_RUN_MODE: 'interactive'
|
|
585
|
+
}
|
|
586
|
+
});
|
|
587
|
+
spawnEngine();
|
|
588
|
+
|
|
589
|
+
// ---- passive update notice: once-a-day cached check; failures stay silent
|
|
590
|
+
if (!opts.demo && updateCheckEnabled()) {
|
|
591
|
+
const installed = packageVersion();
|
|
592
|
+
latestReleaseCached().then(({ release }) => {
|
|
593
|
+
if (installed && release && compareVersions(installed, release.version) < 0) {
|
|
594
|
+
state.updateAvailable = release;
|
|
595
|
+
notice(feed, `Carthagent ${release.version} is available (installed ${installed}) — run /update`, 'info');
|
|
596
|
+
feed.version++;
|
|
597
|
+
}
|
|
598
|
+
}).catch(() => { /* update check is best-effort */ });
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// ---- fingerprint worker
|
|
602
|
+
let hashWorker = null, hashBusy = false;
|
|
603
|
+
try {
|
|
604
|
+
hashWorker = new Worker(new URL('./hash-worker.mjs', import.meta.url));
|
|
605
|
+
hashWorker.on('message', m => { if (m.hash) { if (state.currentHash && state.currentHash !== m.hash) feed.version++; state.currentHash = m.hash; } hashBusy = false; });
|
|
606
|
+
hashWorker.on('error', () => { hashBusy = false; });
|
|
607
|
+
} catch { hashWorker = null; }
|
|
608
|
+
const hashTick = () => {
|
|
609
|
+
if (!hashWorker || hashBusy) return;
|
|
610
|
+
hashBusy = true;
|
|
611
|
+
hashWorker.postMessage({ cwd, roots: ['.'] });
|
|
612
|
+
};
|
|
613
|
+
|
|
614
|
+
// ---- harness watcher: newest report.json + plan.d2 under .harness/<sessionId>/
|
|
615
|
+
const readHarness = () => {
|
|
616
|
+
if (!state.sessionId) return;
|
|
617
|
+
try {
|
|
618
|
+
const base = join(cwd, '.harness', state.sessionId);
|
|
619
|
+
if (!existsSync(base)) return;
|
|
620
|
+
let best = null;
|
|
621
|
+
for (const run of readdirSync(base)) {
|
|
622
|
+
const rp = join(base, run, 'report.json');
|
|
623
|
+
try { const mt = statSync(rp).mtimeMs; if (!best || mt > best.mt) best = { mt, dir: join(base, run), rp }; } catch { }
|
|
624
|
+
}
|
|
625
|
+
if (!best) return;
|
|
626
|
+
const report = JSON.parse(readFileSync(best.rp, 'utf8'));
|
|
627
|
+
const d2p = join(best.dir, 'plan.d2');
|
|
628
|
+
const d2 = existsSync(d2p) ? readFileSync(d2p, 'utf8') : (report.plan ? planD2(report.plan) : '');
|
|
629
|
+
const prevStatus = state.delivery?.status;
|
|
630
|
+
state.delivery = report;
|
|
631
|
+
if (d2 && d2 !== state.d2Source) { state.d2Source = d2; state.d2Graph = parseD2(d2); state.planScroll = PLAN_FOLLOW; }
|
|
632
|
+
if (report.status !== prevStatus) state.lastActivity = Date.now();
|
|
633
|
+
if (report.status === 'verified' && prevStatus !== 'verified') state.reviewPendingVerified = true;
|
|
634
|
+
feed.version++;
|
|
635
|
+
} catch { /* transient parse while file being written */ }
|
|
636
|
+
};
|
|
637
|
+
|
|
638
|
+
// ---- instant plan preview from delivery_plan tool call args
|
|
639
|
+
const previewPlan = planArgs => {
|
|
640
|
+
try {
|
|
641
|
+
const d2 = planD2(planArgs);
|
|
642
|
+
if (d2 && d2 !== state.d2Source) { state.d2Source = d2; state.d2Graph = parseD2(d2); state.planScroll = PLAN_FOLLOW; }
|
|
643
|
+
if (!state.delivery || !state.delivery.plan) state.delivery = { status: 'implementing', plan: planArgs, evidence: {} };
|
|
644
|
+
state.lastActivity = Date.now();
|
|
645
|
+
} catch { }
|
|
646
|
+
};
|
|
647
|
+
|
|
648
|
+
// ---- RPC event handling
|
|
649
|
+
rpc.onEvent(ev => {
|
|
650
|
+
if (ev.type === '__exit__') {
|
|
651
|
+
notice(feed, `agent process exited (code ${ev.code}${ev.sig ? `, ${ev.sig}` : ''})${rpc.stderrTail ? ` — ${rpc.stderrTail.split('\n').filter(Boolean).pop()}` : ''} — /restart respawns`, 'error');
|
|
652
|
+
state.running = false;
|
|
653
|
+
state.awaitingRun = false;
|
|
654
|
+
state.abortAt = 0;
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
if (ev.type === '__error__') { notice(feed, `agent process error: ${ev.error.message}`, 'error'); return; }
|
|
658
|
+
applyEvent(feed, ev);
|
|
659
|
+
const cloudRecovery = cloudManagedUsageNotice(ev, state.model);
|
|
660
|
+
if (cloudRecovery && Date.now() - state.cloudRecoveryOfferedAt > 2_000) {
|
|
661
|
+
state.cloudRecoveryOfferedAt = Date.now();
|
|
662
|
+
notice(feed, cloudRecovery, 'warn');
|
|
663
|
+
}
|
|
664
|
+
if (ev.type === 'tool_execution_start') {
|
|
665
|
+
if (ev.toolName === 'delivery_plan') previewPlan(ev.args);
|
|
666
|
+
if (ev.toolName === 'delivery_check') { state.checkToolRunning = true; state.checkRunId = ev.args?.id; }
|
|
667
|
+
if (ev.toolName === 'write' || ev.toolName === 'edit') state.runWrites++;
|
|
668
|
+
}
|
|
669
|
+
if (ev.type === 'tool_execution_end') {
|
|
670
|
+
if (ev.toolName === 'delivery_check') { state.checkToolRunning = false; readHarness(); }
|
|
671
|
+
if (ev.toolName === 'delivery_finish' && !ev.isError) {
|
|
672
|
+
try {
|
|
673
|
+
const r = JSON.parse((ev.result?.content || []).find(c => c.type === 'text')?.text || '{}');
|
|
674
|
+
feed.blocks.push({ kind: 'banner', title: r.status === 'verified' ? 'verified' : 'blocked', tone: r.status === 'verified' ? 'ok' : 'warn', text: r.report || '', t: Date.now() });
|
|
675
|
+
feed.version++;
|
|
676
|
+
} catch { }
|
|
677
|
+
}
|
|
678
|
+
if (['delivery_plan', 'delivery_revise', 'delivery_design', 'delivery_progress', 'delivery_review'].includes(ev.toolName)) readHarness();
|
|
679
|
+
}
|
|
680
|
+
if (ev.type === 'agent_start') { state.running = true; state.abortAt = 0; if (!state.awaitingRun) state.runStarted = Date.now(); state.awaitingRun = false; state.runEnded = 0; state.runWrites = 0; state.reviewOffer = null; }
|
|
681
|
+
if (ev.type === 'agent_end' || ev.type === 'agent_settled') { state.running = false; state.awaitingRun = false; state.abortAt = 0; state.runEnded = Date.now(); refreshShipUsage(); }
|
|
682
|
+
if (ev.type === 'agent_settled') maybeOfferReview();
|
|
683
|
+
if (ev.type === 'extension_ui_request') {
|
|
684
|
+
if (['select', 'confirm', 'input', 'editor'].includes(ev.method)) {
|
|
685
|
+
rpc.replyExtensionUi(ev.id, {});
|
|
686
|
+
notice(feed, `extension dialog ${ev.method} auto-dismissed (TUI)`, 'warn');
|
|
687
|
+
}
|
|
688
|
+
if (ev.method === 'notify') state.toast = { text: ev.message, tone: ev.notifyType === 'warning' ? 'warn' : ev.notifyType || 'info', until: Date.now() + 4000 };
|
|
689
|
+
}
|
|
690
|
+
state.lastActivity = Date.now();
|
|
691
|
+
});
|
|
692
|
+
|
|
693
|
+
// ---- session state sync + restart/resume helpers
|
|
694
|
+
const refreshState = () => rpc.send({ type: 'get_state' }).then(s => {
|
|
695
|
+
state.sessionId = s.sessionId;
|
|
696
|
+
state.sessionFile = s.sessionFile || null;
|
|
697
|
+
state.sessionName = s.sessionName || null;
|
|
698
|
+
applyActiveModel(s.model);
|
|
699
|
+
if (s.thinkingLevel) state.thinking = s.thinkingLevel;
|
|
700
|
+
state.running = !!s.isStreaming;
|
|
701
|
+
if (s.isStreaming) state.awaitingRun = false;
|
|
702
|
+
if (!s.isStreaming) state.abortAt = 0;
|
|
703
|
+
return s;
|
|
704
|
+
});
|
|
705
|
+
|
|
706
|
+
/** Parse a session .jsonl into an entry list (tolerant of a partial tail line). */
|
|
707
|
+
const readSessionEntries = file => {
|
|
708
|
+
try {
|
|
709
|
+
return readFileSync(file, 'utf8').split('\n')
|
|
710
|
+
.map(l => { try { return JSON.parse(l); } catch { return null; } })
|
|
711
|
+
.filter(Boolean);
|
|
712
|
+
} catch { return []; }
|
|
713
|
+
};
|
|
714
|
+
|
|
715
|
+
/** Rebuild the feed from a session file (resume/switch/continue). */
|
|
716
|
+
const hydrateFrom = file => {
|
|
717
|
+
const entries = readSessionEntries(file);
|
|
718
|
+
if (entries.length) { hydrateFeed(feed, entries); state.hydrated = true; }
|
|
719
|
+
};
|
|
720
|
+
|
|
721
|
+
/** Kill the agent child and respawn it on the same session file — the escape
|
|
722
|
+
* hatch when the process ignores `abort` (wedged stream, deadlocked tool). */
|
|
723
|
+
const restartPi = async (why = 'restart') => {
|
|
724
|
+
const resumeFile = !opts.demo && (state.sessionFile || mostRecentSession(cwd));
|
|
725
|
+
notice(feed, `${why === 'force' ? 'agent unresponsive — force restarting' : 'restarting agent'}${resumeFile ? ' (resuming session)' : ''}…`, 'warn');
|
|
726
|
+
state.running = false; state.awaitingRun = false; state.abortAt = 0; state.checkToolRunning = false; state.isCompacting = false;
|
|
727
|
+
feed.currentAssistant = feed.currentThinking = null;
|
|
728
|
+
spawnEngine(resumeFile && existsSync(resumeFile) ? ['--session', resumeFile] : []);
|
|
729
|
+
try {
|
|
730
|
+
const s = await refreshState();
|
|
731
|
+
notice(feed, `agent restarted · session ${String(state.sessionId || 'new').slice(0, 8)} · ${s.messageCount ?? 0} messages`, 'info');
|
|
732
|
+
readHarness();
|
|
733
|
+
feed.version++;
|
|
734
|
+
} catch (e) {
|
|
735
|
+
notice(feed, `agent restart failed: ${e.message}`, 'error');
|
|
736
|
+
}
|
|
737
|
+
};
|
|
738
|
+
|
|
739
|
+
/** Soft abort: cancel the run and any queued steers/follow-ups (queued text
|
|
740
|
+
* returns to the editor). A second esc/^c while still running force-restarts. */
|
|
741
|
+
const abortRun = () => {
|
|
742
|
+
state.abortAt = Date.now();
|
|
743
|
+
rpc.send({ type: 'clear_queue' }).then(q => {
|
|
744
|
+
const queued = [...(q?.steering || []), ...(q?.followUp || [])].filter(Boolean);
|
|
745
|
+
if (queued.length && !editor.buf) { editor.buf = queued[0]; editor.cur = editor.buf.length; }
|
|
746
|
+
}).catch(() => { });
|
|
747
|
+
rpc.send({ type: 'abort_retry' }).catch(() => { });
|
|
748
|
+
rpc.send({ type: 'abort' }).catch(() => { });
|
|
749
|
+
notice(feed, 'aborting… esc/^c again force-restarts agent', 'warn');
|
|
750
|
+
};
|
|
751
|
+
|
|
752
|
+
// ---- connect-provider popup (in-console auth; see lib/tui/auth.mjs)
|
|
753
|
+
let authRuntime = null;
|
|
754
|
+
let authAbort = null;
|
|
755
|
+
let authPrompt = null; // { resolve, reject } for the pending engine prompt
|
|
756
|
+
|
|
757
|
+
const authVisible = () => state.auth ? filterLoginProviders(state.auth.providers, state.auth.filter) : [];
|
|
758
|
+
|
|
759
|
+
const authFinish = (error) => {
|
|
760
|
+
const a = state.auth;
|
|
761
|
+
authAbort = null; authPrompt = null;
|
|
762
|
+
if (!a) return; // popup already closed (e.g. user cancelled)
|
|
763
|
+
state.auth = null;
|
|
764
|
+
if (error) notice(feed, `login failed: ${error.message}`, 'error');
|
|
765
|
+
else if (opts.loginOnly) { screen.exit(); process.exit(0); }
|
|
766
|
+
else if (a.provider) {
|
|
767
|
+
notice(feed, `connected ${a.provider.name} — restarting agent`, 'info');
|
|
768
|
+
state.modelList = null; // new provider may add models
|
|
769
|
+
for (const block of feed.blocks) if (block.kind === 'welcome') { block.noProvider = false; block.model = modelDisplayIdentity(state.model) || block.model; }
|
|
770
|
+
feed.version++;
|
|
771
|
+
restartPi('auth').then(() => fetchModels()).catch(() => { });
|
|
772
|
+
}
|
|
773
|
+
feed.version++;
|
|
774
|
+
};
|
|
775
|
+
|
|
776
|
+
const authStart = (type) => {
|
|
777
|
+
const a = state.auth;
|
|
778
|
+
if (!a?.provider || !type) return;
|
|
779
|
+
a.type = type; a.phase = 'waiting'; a.prompt = null; a.input = ''; a.error = '';
|
|
780
|
+
a.message = type === 'oauth' ? 'Starting authorization…' : 'Enter your API key'; a.busy = true;
|
|
781
|
+
authAbort = new AbortController();
|
|
782
|
+
loginAndRefresh(authRuntime, a.provider.id, type, {
|
|
783
|
+
signal: authAbort.signal,
|
|
784
|
+
prompt: prompt => new Promise((resolve, reject) => {
|
|
785
|
+
a.prompt = prompt; a.phase = 'prompt'; a.promptSel = 0; a.input = ''; a.busy = false;
|
|
786
|
+
a.message = prompt.message || '';
|
|
787
|
+
authPrompt = { resolve, reject };
|
|
788
|
+
feed.version++;
|
|
789
|
+
}),
|
|
790
|
+
notify: event => { applyAuthEvent(a, event); feed.version++; },
|
|
791
|
+
}).then(() => authFinish()).catch(error => {
|
|
792
|
+
if (String(error?.message || '').includes('cancel')) authFinish(new Error('cancelled'));
|
|
793
|
+
else authFinish(error);
|
|
794
|
+
});
|
|
795
|
+
};
|
|
796
|
+
|
|
797
|
+
const authChooseProvider = row => {
|
|
798
|
+
const a = state.auth;
|
|
799
|
+
if (!row) return;
|
|
800
|
+
a.provider = row; a.error = '';
|
|
801
|
+
if (row.types.length > 1) { a.phase = 'type'; a.typeSel = 0; a.sel = 0; }
|
|
802
|
+
else authStart(row.types[0]);
|
|
803
|
+
feed.version++;
|
|
804
|
+
};
|
|
805
|
+
|
|
806
|
+
const authSubmitPrompt = value => {
|
|
807
|
+
const pending = authPrompt;
|
|
808
|
+
if (!pending) return;
|
|
809
|
+
authPrompt = null;
|
|
810
|
+
state.auth.prompt = null; state.auth.phase = 'waiting';
|
|
811
|
+
state.auth.message = 'Verifying…'; state.auth.busy = true; state.auth.input = '';
|
|
812
|
+
pending.resolve(value);
|
|
813
|
+
feed.version++;
|
|
814
|
+
};
|
|
815
|
+
|
|
816
|
+
/** Ctrl+V in a text/secret prompt: read the OS clipboard and append it. */
|
|
817
|
+
const authPasteClipboard = () => {
|
|
818
|
+
readClipboard().then(text => {
|
|
819
|
+
const a = state.auth;
|
|
820
|
+
if (!a || a.phase !== 'prompt' || a.prompt?.type === 'select') return;
|
|
821
|
+
a.input += sanitizePaste(text);
|
|
822
|
+
feed.version++;
|
|
823
|
+
});
|
|
824
|
+
};
|
|
825
|
+
|
|
826
|
+
const authCancel = () => {
|
|
827
|
+
const a = state.auth;
|
|
828
|
+
if (!a) return;
|
|
829
|
+
const pending = authPrompt;
|
|
830
|
+
authPrompt = null;
|
|
831
|
+
if (pending) pending.reject(new Error('Login cancelled'));
|
|
832
|
+
try { authAbort?.abort(); } catch { }
|
|
833
|
+
authAbort = null;
|
|
834
|
+
state.auth = null;
|
|
835
|
+
if (opts.loginOnly) { screen.exit(); process.exit(0); }
|
|
836
|
+
notice(feed, 'login cancelled', 'warn');
|
|
837
|
+
feed.version++;
|
|
838
|
+
};
|
|
839
|
+
|
|
840
|
+
const openAuth = async ({ focusProviderId } = {}) => {
|
|
841
|
+
if (opts.demo) { notice(feed, 'login is unavailable in demo mode', 'warn'); return; }
|
|
842
|
+
if (state.auth) {
|
|
843
|
+
if (!focusProviderId) { state.auth = null; feed.version++; return; }
|
|
844
|
+
const visible = filterLoginProviders(state.auth.providers || [], state.auth.filter || '');
|
|
845
|
+
const focused = visible.findIndex(provider => provider.id === focusProviderId);
|
|
846
|
+
if (focused >= 0) { state.auth.sel = focused; feed.version++; }
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
state.auth = newAuthState();
|
|
850
|
+
state.auth.message = 'Loading providers…';
|
|
851
|
+
state.auth.busy = true;
|
|
852
|
+
feed.version++;
|
|
853
|
+
try {
|
|
854
|
+
authRuntime = await loadAuthRuntime();
|
|
855
|
+
const a = state.auth;
|
|
856
|
+
if (!a) return; // closed while loading
|
|
857
|
+
const activeProviderId = String(state.model || '').split('/')[0] || undefined;
|
|
858
|
+
a.providers = loginProviderList(authRuntime, { activeProviderId });
|
|
859
|
+
// When no provider is configured, always focus on Carthagent Ship (the recommended row).
|
|
860
|
+
const noProviderConfigured = !hasConfiguredProvider();
|
|
861
|
+
a.sel = loginProviderFocus(a.providers, noProviderConfigured ? 'experiential-labs' : (focusProviderId || activeProviderId));
|
|
862
|
+
a.busy = false; a.message = '';
|
|
863
|
+
} catch (error) {
|
|
864
|
+
if (state.auth) { state.auth.error = error.message; state.auth.busy = false; state.auth.message = ''; }
|
|
865
|
+
}
|
|
866
|
+
feed.version++;
|
|
867
|
+
};
|
|
868
|
+
|
|
869
|
+
const ensureAuthRuntime = async () => {
|
|
870
|
+
authRuntime ||= await loadAuthRuntime();
|
|
871
|
+
return authRuntime;
|
|
872
|
+
};
|
|
873
|
+
|
|
874
|
+
const usingCloudModel = () => String(state.model || '').split('/')[0] === 'experiential-labs';
|
|
875
|
+
|
|
876
|
+
const shipUsageChip = account => {
|
|
877
|
+
const monthly = account?.managedUsage?.monthly;
|
|
878
|
+
const allowance = Number(monthly?.allowanceNanoUsd);
|
|
879
|
+
if (!Number.isFinite(allowance) || allowance <= 0) return null;
|
|
880
|
+
const available = Math.max(0, Number(monthly?.availableNanoUsd) || 0);
|
|
881
|
+
return { percent: Math.round(((allowance - available) / allowance) * 100) };
|
|
882
|
+
};
|
|
883
|
+
|
|
884
|
+
const refreshShipUsage = async () => {
|
|
885
|
+
if (opts.demo) return;
|
|
886
|
+
if (!usingCloudModel()) { state.shipUsage = null; return; }
|
|
887
|
+
try {
|
|
888
|
+
const account = await loadCloudAccount(await ensureAuthRuntime());
|
|
889
|
+
state.shipUsage = usingCloudModel() ? shipUsageChip(account) : null;
|
|
890
|
+
} catch { /* Ship usage chip is best-effort */ }
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
const applyActiveModel = model => {
|
|
894
|
+
const wasCloud = usingCloudModel();
|
|
895
|
+
syncActiveModel(state, feed, model);
|
|
896
|
+
if (usingCloudModel() !== wasCloud) refreshShipUsage();
|
|
897
|
+
};
|
|
898
|
+
|
|
899
|
+
// Ship allowance chip: refreshed on a minute timer while on a Ship model
|
|
900
|
+
// and whenever a run settles; failures stay silent.
|
|
901
|
+
const shipUsageTimer = setInterval(refreshShipUsage, 60_000);
|
|
902
|
+
shipUsageTimer.unref?.();
|
|
903
|
+
refreshShipUsage();
|
|
904
|
+
|
|
905
|
+
const showCloudAccount = async () => {
|
|
906
|
+
try {
|
|
907
|
+
const { account, usage } = await loadCloudAccountUsage(await ensureAuthRuntime());
|
|
908
|
+
state.shipUsage = shipUsageChip(account);
|
|
909
|
+
push2(formatCloudAccount(account, { usage }));
|
|
910
|
+
const active = (account.sessions || []).filter(session => !session.revoked_at);
|
|
911
|
+
if (active.length) push2(active.map(session => `${session.id} · ${session.client_name || 'Carthagent CLI'} · last used ${session.last_used_at || session.created_at}`).join('\n'));
|
|
912
|
+
} catch (error) {
|
|
913
|
+
if (error.message === 'cloud_login_required') { notice(feed, 'Carthagent Ship sign-in required — opening /login', 'warn'); openAuth({ focusProviderId: 'experiential-labs' }); }
|
|
914
|
+
else notice(feed, `Ship account: ${error.message}`, 'error');
|
|
915
|
+
}
|
|
916
|
+
};
|
|
917
|
+
|
|
918
|
+
const showCloudUsage = async () => {
|
|
919
|
+
try {
|
|
920
|
+
const { account, usage } = await loadCloudAccountUsage(await ensureAuthRuntime());
|
|
921
|
+
state.shipUsage = shipUsageChip(account);
|
|
922
|
+
push2(formatCloudUsage(usage, { account, byok: !usingCloudModel() }));
|
|
923
|
+
} catch (error) {
|
|
924
|
+
if (error.message === 'cloud_login_required') { notice(feed, 'Carthagent Ship sign-in required — opening /login', 'warn'); openAuth({ focusProviderId: 'experiential-labs' }); }
|
|
925
|
+
else notice(feed, `Ship usage: ${error.message}`, 'error');
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
|
|
929
|
+
const openCloudBilling = async (action, plan) => {
|
|
930
|
+
try {
|
|
931
|
+
const result = await createCloudBillingLink(await ensureAuthRuntime(), action, { plan });
|
|
932
|
+
const opened = await openBrowser(result.url).catch(() => false);
|
|
933
|
+
notice(feed, `${action === 'portal' ? 'billing portal' : `${plan || 'Ship'} checkout`}${opened ? ' opened' : ''}: ${result.url}`, 'info');
|
|
934
|
+
writeClipboard(result.url).then(() => { state.toast = { text: `billing URL ${opened ? 'opened and ' : ''}copied`, tone: 'info', until: Date.now() + 3000 }; }).catch(() => { });
|
|
935
|
+
} catch (error) {
|
|
936
|
+
if (error.message === 'cloud_login_required') { notice(feed, 'Carthagent Ship sign-in required — opening /login', 'warn'); openAuth({ focusProviderId: 'experiential-labs' }); }
|
|
937
|
+
else notice(feed, `Ship billing: ${error.message}`, 'error');
|
|
938
|
+
}
|
|
939
|
+
};
|
|
940
|
+
|
|
941
|
+
const revokeCloud = async sessionId => {
|
|
942
|
+
if (!sessionId) { notice(feed, 'usage: /logout-cloud <session-id> — use /account to list sessions', 'warn'); return; }
|
|
943
|
+
try {
|
|
944
|
+
await revokeCloudSession(await ensureAuthRuntime(), sessionId);
|
|
945
|
+
notice(feed, `revoked Ship session ${sessionId}`, 'info');
|
|
946
|
+
} catch (error) { notice(feed, `Ship session: ${error.message}`, 'error'); }
|
|
947
|
+
};
|
|
948
|
+
|
|
949
|
+
// ---- slash-command autocomplete
|
|
950
|
+
/** Recompute the popup from the editor buffer. Active only while the buffer
|
|
951
|
+
* is a single command token (starts with '/', no space yet). */
|
|
952
|
+
const updateSlash = () => {
|
|
953
|
+
const items = matchSlash(editor.buf);
|
|
954
|
+
if (!items.length) { state.slash = null; return; }
|
|
955
|
+
const prev = state.slash;
|
|
956
|
+
state.slash = { items, sel: prev ? Math.min(prev.sel, items.length - 1) : 0 };
|
|
957
|
+
};
|
|
958
|
+
|
|
959
|
+
/** Replace the editor's command token with the selected command + trailing
|
|
960
|
+
* space, then dismiss the popup. Returns true if it acted. */
|
|
961
|
+
const completeSlash = () => {
|
|
962
|
+
if (!state.slash) return false;
|
|
963
|
+
const item = state.slash.items[state.slash.sel];
|
|
964
|
+
if (!item) return false;
|
|
965
|
+
editor.buf = item.name + ' ';
|
|
966
|
+
editor.cur = editor.buf.length;
|
|
967
|
+
state.slash = null;
|
|
968
|
+
return true;
|
|
969
|
+
};
|
|
970
|
+
|
|
971
|
+
// ---- resume picker
|
|
972
|
+
const openSessionPicker = () => {
|
|
973
|
+
if (opts.demo) { notice(feed, 'no saved sessions in demo mode', 'warn'); return; }
|
|
974
|
+
const items = listSessions(cwd);
|
|
975
|
+
if (!items.length) { notice(feed, `no saved sessions for ${cwd}`, 'warn'); return; }
|
|
976
|
+
state.sessions = { items, sel: 0, search: '' };
|
|
977
|
+
};
|
|
978
|
+
|
|
979
|
+
const filteredSessions = () => {
|
|
980
|
+
const p = state.sessions;
|
|
981
|
+
if (!p) return [];
|
|
982
|
+
const q = p.search.trim().toLowerCase();
|
|
983
|
+
if (!q) return p.items;
|
|
984
|
+
return p.items.filter(s => `${s.name || ''} ${s.firstMessage} ${s.id}`.toLowerCase().includes(q));
|
|
985
|
+
};
|
|
986
|
+
|
|
987
|
+
const switchSession = async item => {
|
|
988
|
+
if (opts.demo) { notice(feed, 'no saved sessions in demo mode', 'warn'); return; }
|
|
989
|
+
if (state.running) { notice(feed, 'run in progress — esc aborts first, then /resume', 'warn'); return; }
|
|
990
|
+
try {
|
|
991
|
+
const r = await rpc.send({ type: 'switch_session', sessionPath: item.path });
|
|
992
|
+
if (r?.cancelled) { notice(feed, 'session switch cancelled by extension', 'warn'); return; }
|
|
993
|
+
hydrateFrom(item.path);
|
|
994
|
+
state.stats = null;
|
|
995
|
+
rpc.send({ type: 'get_session_stats' }).then(st => { state.stats = st; }).catch(() => { });
|
|
996
|
+
const s = await refreshState().catch(() => null);
|
|
997
|
+
state.delivery = null; state.d2Source = ''; state.d2Graph = null;
|
|
998
|
+
state.scroll = 0; state.planScroll = PLAN_FOLLOW;
|
|
999
|
+
readHarness();
|
|
1000
|
+
notice(feed, `resumed ${item.name || item.firstMessage?.slice(0, 60) || String(item.id || '').slice(0, 8)} · ${s?.messageCount ?? '?'} messages`, 'info');
|
|
1001
|
+
feed.version++;
|
|
1002
|
+
} catch (e) { notice(feed, `resume failed: ${e.message}`, 'error'); }
|
|
1003
|
+
};
|
|
1004
|
+
|
|
1005
|
+
// initial state + polls
|
|
1006
|
+
refreshState().then(s => {
|
|
1007
|
+
// `ctg -c/--session` loaded history before the console attached — rebuild
|
|
1008
|
+
// the feed from the session file so it shows where things stand.
|
|
1009
|
+
if ((opts.session || opts.continue) && s.sessionFile && !state.hydrated) {
|
|
1010
|
+
hydrateFrom(s.sessionFile);
|
|
1011
|
+
state.scroll = 0;
|
|
1012
|
+
if (state.hydrated) notice(feed, `resumed session ${String(s.sessionId || '').slice(0, 8)}`, 'info');
|
|
1013
|
+
}
|
|
1014
|
+
}).catch(() => { });
|
|
1015
|
+
|
|
1016
|
+
// Read the live engine registry on every use; discovery continues after launch.
|
|
1017
|
+
const fetchModels = createModelLoader(rpc, state);
|
|
1018
|
+
// Warm the model cache so the settings provider toggle / picker is instant.
|
|
1019
|
+
fetchModels();
|
|
1020
|
+
|
|
1021
|
+
const choiceItems = (p) => {
|
|
1022
|
+
let items;
|
|
1023
|
+
if (p.page === 'thinking') items = (p.levels || []).map(value => ({ value, label: value }));
|
|
1024
|
+
else if (p.row === 0) items = THEME_NAMES.map(value => ({ value, label: value }));
|
|
1025
|
+
else if (p.row === 1) items = [{ value: '', label: 'All providers' }, ...providersFromModels(state.modelList).map(value => ({ value, label: providerDisplayName(value) }))];
|
|
1026
|
+
else items = (state.modelList || []).filter(m => !p.provider || m.provider === p.provider).map(m => ({ ...m, value: m.full, label: `${providerDisplayName(m.provider)} · ${m.name || m.id}`, description: m.name && m.name !== m.id ? m.id : '' }));
|
|
1027
|
+
const q = p.search || '';
|
|
1028
|
+
return p.row === 2 && p.page !== 'thinking'
|
|
1029
|
+
? items.filter(item => modelMatchesQuery(item, q))
|
|
1030
|
+
: items.filter(it => `${it.label} ${it.value}`.toLowerCase().includes(q.toLowerCase()));
|
|
1031
|
+
};
|
|
1032
|
+
const activeModelInfo = () => (state.modelList || []).find(model => model.full === state.model);
|
|
1033
|
+
const modelHasThinking = () => modelSupportsThinking(activeModelInfo());
|
|
1034
|
+
const openOverlay = (row, direct = false, page = 'settings') => {
|
|
1035
|
+
const p = state.overlay = { row, page, provider: null, direct, search: direct || page === 'thinking' ? '' : undefined, sel: 0, loading: true };
|
|
1036
|
+
if (page === 'thinking') p.levels = [];
|
|
1037
|
+
if (row === 0 && direct) {
|
|
1038
|
+
p.originalTheme = currentThemeName();
|
|
1039
|
+
const current = choiceItems(p).findIndex(item => item.value === p.originalTheme);
|
|
1040
|
+
p.sel = current < 0 ? 0 : current;
|
|
1041
|
+
}
|
|
1042
|
+
fetchModels().then(() => { p.loading = false; feed.version++; });
|
|
1043
|
+
rpc.send({ type: 'get_available_thinking_levels' }).then(r => {
|
|
1044
|
+
p.levels = r.levels || [];
|
|
1045
|
+
if (p.page === 'thinking') {
|
|
1046
|
+
const current = choiceItems(p).findIndex(item => item.value === state.thinking);
|
|
1047
|
+
p.sel = current < 0 ? 0 : current;
|
|
1048
|
+
}
|
|
1049
|
+
}).catch(e => { p.error = e.message; });
|
|
1050
|
+
return p;
|
|
1051
|
+
};
|
|
1052
|
+
const applyModel = async (m) => {
|
|
1053
|
+
if (state.running) throw Error('Stop the active response before switching models.');
|
|
1054
|
+
if (state.model === m.full) return;
|
|
1055
|
+
const r = await rpc.send({ type: 'set_model', provider: m.provider, modelId: m.id });
|
|
1056
|
+
if (!r?.provider || !r?.id) throw Error('Model switch returned no model.');
|
|
1057
|
+
applyActiveModel(r);
|
|
1058
|
+
saveCarthagentConfig({ model: state.model });
|
|
1059
|
+
notice(feed, `model → ${modelDisplayIdentity(state.model)}`, 'info');
|
|
1060
|
+
};
|
|
1061
|
+
const previewThemeChoice = (p, items = choiceItems(p)) => {
|
|
1062
|
+
if (p.row !== 0 || p.search === undefined) return;
|
|
1063
|
+
const item = items[p.sel];
|
|
1064
|
+
if (!item) return;
|
|
1065
|
+
p.previewTheme = item.value;
|
|
1066
|
+
T.theme = getTheme(item.value, termMode);
|
|
1067
|
+
screen.prev = [];
|
|
1068
|
+
};
|
|
1069
|
+
const restoreThemePreview = p => {
|
|
1070
|
+
if (!p.originalTheme) return;
|
|
1071
|
+
T.theme = getTheme(p.originalTheme, termMode);
|
|
1072
|
+
screen.prev = [];
|
|
1073
|
+
p.previewTheme = null;
|
|
1074
|
+
};
|
|
1075
|
+
const commitChoice = (p, item) => commitPicker(p, async () => {
|
|
1076
|
+
if (p.page === 'thinking') {
|
|
1077
|
+
await rpc.send({ type: 'set_thinking_level', level: item.value });
|
|
1078
|
+
await refreshState();
|
|
1079
|
+
} else if (p.row === 0) {
|
|
1080
|
+
T.theme = getTheme(item.value, termMode); screen.prev = [];
|
|
1081
|
+
p.originalTheme = item.value;
|
|
1082
|
+
p.previewTheme = null;
|
|
1083
|
+
saveCarthagentConfig({ theme: item.value });
|
|
1084
|
+
} else if (p.row === 1) p.provider = item.value;
|
|
1085
|
+
else {
|
|
1086
|
+
await applyModel(item);
|
|
1087
|
+
if (modelSupportsThinking(item)) {
|
|
1088
|
+
const result = await rpc.send({ type: 'get_available_thinking_levels' });
|
|
1089
|
+
p.levels = result.levels || [];
|
|
1090
|
+
p.enterThinking = true;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
}, () => {
|
|
1094
|
+
if (state.overlay !== p) return;
|
|
1095
|
+
if (p.enterThinking) {
|
|
1096
|
+
p.enterThinking = false;
|
|
1097
|
+
p.page = 'thinking'; p.direct = true; p.search = ''; p.error = '';
|
|
1098
|
+
const current = choiceItems(p).findIndex(item => item.value === state.thinking);
|
|
1099
|
+
p.sel = current < 0 ? 0 : current;
|
|
1100
|
+
} else if (p.direct || p.page === 'thinking') state.overlay = null;
|
|
1101
|
+
else { p.search = undefined; p.sel = 0; }
|
|
1102
|
+
});
|
|
1103
|
+
|
|
1104
|
+
const statePoll = setInterval(() => {
|
|
1105
|
+
// Keep an already-open picker current when background discovery completes.
|
|
1106
|
+
if (state.overlay) fetchModels().then(() => { feed.version++; });
|
|
1107
|
+
rpc.send({ type: 'get_state' }).then(s => {
|
|
1108
|
+
state.sessionId = s.sessionId;
|
|
1109
|
+
state.sessionFile = s.sessionFile || state.sessionFile;
|
|
1110
|
+
state.sessionName = s.sessionName ?? state.sessionName;
|
|
1111
|
+
applyActiveModel(s.model);
|
|
1112
|
+
state.running = s.isStreaming;
|
|
1113
|
+
if (s.isStreaming) state.awaitingRun = false;
|
|
1114
|
+
if (!s.isStreaming && !state.awaitingRun && !state.runEnded) state.runEnded = Date.now();
|
|
1115
|
+
if (!s.isStreaming) state.abortAt = 0;
|
|
1116
|
+
state.isCompacting = s.isCompacting;
|
|
1117
|
+
if (s.autoCompactionEnabled !== undefined) state.autoCompaction = s.autoCompactionEnabled;
|
|
1118
|
+
}).catch(() => { });
|
|
1119
|
+
rpc.send({ type: 'get_session_stats' }).then(s => { state.stats = s; }).catch(() => { });
|
|
1120
|
+
}, 2500);
|
|
1121
|
+
const harnessPoll = setInterval(readHarness, 450);
|
|
1122
|
+
const hashPoll = setInterval(() => { if (state.running || state.delivery) hashTick(); }, 1600);
|
|
1123
|
+
hashTick();
|
|
1124
|
+
|
|
1125
|
+
// ---- self-review offer (ask mode) — the engine's extension dialogs can't
|
|
1126
|
+
// reach rpc clients, so the console renders the prompt itself. 'yes' mode is
|
|
1127
|
+
// kicked by the delivery extension; 'no' suppresses this entirely.
|
|
1128
|
+
const reviewMode = () => resolveReviewMode(opts.review);
|
|
1129
|
+
const maybeOfferReview = () => {
|
|
1130
|
+
const verified = state.reviewPendingVerified;
|
|
1131
|
+
const writes = state.runWrites;
|
|
1132
|
+
state.reviewPendingVerified = false;
|
|
1133
|
+
const runKey = `${state.sessionId}@${state.runStarted}`;
|
|
1134
|
+
if (!shouldOfferReview({ mode: opts.demo ? 'no' : reviewMode(), verified, writes, loopActive: state.reviewLoop, offeredRuns: state.reviewOfferedRuns, runKey })) return;
|
|
1135
|
+
if (state.reviewOfferedRuns.size > 200) state.reviewOfferedRuns.clear();
|
|
1136
|
+
state.reviewOfferedRuns.add(runKey);
|
|
1137
|
+
state.reviewOffer = { reason: verified ? 'delivery verified' : `${writes} file${writes === 1 ? '' : 's'} changed` };
|
|
1138
|
+
notice(feed, `${state.reviewOffer.reason} — self-review? ^y start PR ↔ review ↔ fixes loop · esc skip · /review <ask|yes|no> sets default`, 'info');
|
|
1139
|
+
feed.version++;
|
|
1140
|
+
};
|
|
1141
|
+
const startReview = () => {
|
|
1142
|
+
state.reviewOffer = null;
|
|
1143
|
+
state.reviewLoop = true;
|
|
1144
|
+
runline(feed);
|
|
1145
|
+
echoUser(feed, 'self-review loop', false);
|
|
1146
|
+
sendAgent('prompt', reviewKickoff(CTG_BIN));
|
|
1147
|
+
state.scroll = 0;
|
|
1148
|
+
};
|
|
1149
|
+
|
|
1150
|
+
// ---- submit helpers
|
|
1151
|
+
// A prompt takes a beat to reach agent_start (engine turn setup, upstream
|
|
1152
|
+
// dispatch, first token) — awaitingRun keeps the spinner/border alive so the
|
|
1153
|
+
// submit never looks hung. Cleared on agent_start/agent_end or send failure.
|
|
1154
|
+
const sendAgent = (type, message) => {
|
|
1155
|
+
const prevStarted = state.runStarted, prevEnded = state.runEnded;
|
|
1156
|
+
if (type === 'prompt') { state.awaitingRun = true; state.runStarted = Date.now(); state.runEnded = 0; }
|
|
1157
|
+
rpc.send({ type, message }).catch(e => {
|
|
1158
|
+
if (type === 'prompt') { state.awaitingRun = false; state.runStarted = prevStarted; state.runEnded = prevEnded; }
|
|
1159
|
+
notice(feed, e.message, 'error');
|
|
1160
|
+
});
|
|
1161
|
+
};
|
|
1162
|
+
const submit = text => {
|
|
1163
|
+
const v = text.trim();
|
|
1164
|
+
if (!v) return;
|
|
1165
|
+
state.reviewOffer = null;
|
|
1166
|
+
state.reviewLoop = false;
|
|
1167
|
+
if (v.startsWith('/')) return slash(v);
|
|
1168
|
+
if (v.startsWith('!')) {
|
|
1169
|
+
const cmd = v.slice(1).trim();
|
|
1170
|
+
if (!cmd) return;
|
|
1171
|
+
const b = echoBash(feed, cmd);
|
|
1172
|
+
rpc.send({ type: 'bash', command: cmd }).then(r => {
|
|
1173
|
+
b.status = 'done'; b.code = r?.exitCode; b.live = ''; b.tail = String(r?.output ?? '').split('\n');
|
|
1174
|
+
feed.version++;
|
|
1175
|
+
}).catch(e => { b.status = 'done'; b.code = 1; b.tail = [String(e.message)]; feed.version++; });
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
if (state.running || state.awaitingRun) { echoUser(feed, v, true); sendAgent('steer', v); }
|
|
1179
|
+
else {
|
|
1180
|
+
// Phased delivery framing (the carthagent default): the feed shows the
|
|
1181
|
+
// task as typed; the engine receives the expanded delivery prompt.
|
|
1182
|
+
const expanded = shouldFrame(v, { enabled: state.autoFraming, delivery: opts.delivery !== false || opts.demo })
|
|
1183
|
+
? framePrompt(v) : null;
|
|
1184
|
+
runline(feed);
|
|
1185
|
+
echoUser(feed, v, false, expanded || undefined);
|
|
1186
|
+
sendAgent('prompt', expanded || v);
|
|
1187
|
+
}
|
|
1188
|
+
state.scroll = 0;
|
|
1189
|
+
};
|
|
1190
|
+
|
|
1191
|
+
const slash = v => {
|
|
1192
|
+
const [cmd, ...rest] = v.split(/\s+/);
|
|
1193
|
+
const arg = rest.join(' ');
|
|
1194
|
+
const done = t => notice(feed, t, 'info');
|
|
1195
|
+
switch (cmd) {
|
|
1196
|
+
case '/workflow': case '/architecture': case '/evidence':
|
|
1197
|
+
state.planningTab = cmd.slice(1); state.planScroll = null; break;
|
|
1198
|
+
case '/login': case '/auth': openAuth(); break;
|
|
1199
|
+
case '/account': case '/cloud': showCloudAccount(); break;
|
|
1200
|
+
case '/usage': showCloudUsage(); break;
|
|
1201
|
+
case '/billing': {
|
|
1202
|
+
const [action = 'checkout', plan] = arg.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
1203
|
+
if (!['checkout', 'portal'].includes(action) || (plan && action !== 'checkout')) done('usage: /billing [checkout [plan]|portal]');
|
|
1204
|
+
else openCloudBilling(action, plan);
|
|
1205
|
+
break;
|
|
1206
|
+
}
|
|
1207
|
+
case '/logout-cloud': revokeCloud(arg.trim()); break;
|
|
1208
|
+
case '/q': case '/quit': case '/exit': cleanup(0); break;
|
|
1209
|
+
case '/help': push2(`${BOLD}keys${RESET} enter send/steer · esc abort (again = force-restart agent) · ^r resume session · tab focus · ${G.shift}tab view · pgup/pgdn/wheel scroll focused pane · drag-select copies · ^t settings · ^n new session · ^x expand · ^l clear · ^c quit
|
|
1210
|
+
${BOLD}input${RESET} type / for command autocomplete (↑↓ select · tab complete) · plain text runs phased delivery (${state.autoFraming ? 'on' : 'off'}) · /raw <text> bypasses · /guide [task] toggles or runs · ^v pastes · !<cmd> bash
|
|
1211
|
+
${BOLD}views${RESET} /workflow · /architecture · /evidence (observed receipts, not inferred success)
|
|
1212
|
+
${BOLD}cmds${RESET} /login · /account · /usage · /billing [checkout|portal] · /logout-cloud <session> · /update [check] · /resume [id|name] · /restart · /theme [${THEME_NAMES.join('|')}] · /model [name] · /thinking · /compact · /autocompact [on|off] · /new · /export [file] · /copy · /stats · /clear · /quit
|
|
1213
|
+
${BOLD}review${RESET} /review starts a PR ↔ fresh-review ↔ fixes loop · /review ask|yes|no sets the default · ^y accepts a pending offer`); break;
|
|
1214
|
+
case '/raw': {
|
|
1215
|
+
const v2 = arg.trim();
|
|
1216
|
+
if (!v2) { done('usage: /raw <prompt> — send without delivery framing'); break; }
|
|
1217
|
+
if (state.running || state.awaitingRun) { echoUser(feed, v2, true); sendAgent('steer', v2); }
|
|
1218
|
+
else { runline(feed); echoUser(feed, v2); sendAgent('prompt', v2); }
|
|
1219
|
+
state.scroll = 0;
|
|
1220
|
+
break;
|
|
1221
|
+
}
|
|
1222
|
+
case '/guide': {
|
|
1223
|
+
if (!arg) {
|
|
1224
|
+
state.autoFraming = !state.autoFraming;
|
|
1225
|
+
done(`phased delivery framing → ${state.autoFraming ? 'on' : 'off'}`); break;
|
|
1226
|
+
}
|
|
1227
|
+
const expanded = framePrompt(arg);
|
|
1228
|
+
runline(feed);
|
|
1229
|
+
echoUser(feed, arg, false, expanded !== arg ? expanded : undefined);
|
|
1230
|
+
sendAgent(state.running || state.awaitingRun ? 'steer' : 'prompt', expanded);
|
|
1231
|
+
state.scroll = 0;
|
|
1232
|
+
break;
|
|
1233
|
+
}
|
|
1234
|
+
case '/theme': {
|
|
1235
|
+
if (arg && THEME_NAMES.includes(arg.toLowerCase())) {
|
|
1236
|
+
const name = arg.toLowerCase();
|
|
1237
|
+
T.theme = getTheme(name, termMode); screen.prev = [];
|
|
1238
|
+
saveCarthagentConfig({ theme: name });
|
|
1239
|
+
done(`theme → ${name}`);
|
|
1240
|
+
}
|
|
1241
|
+
else openOverlay(0);
|
|
1242
|
+
break;
|
|
1243
|
+
}
|
|
1244
|
+
case '/model': {
|
|
1245
|
+
if (!arg) { openOverlay(2, true); break; }
|
|
1246
|
+
// /model <name> — resolve and set directly
|
|
1247
|
+
fetchModels().then(list => {
|
|
1248
|
+
const ql = arg.toLowerCase();
|
|
1249
|
+
const m = list.find(x => x.full.toLowerCase() === ql)
|
|
1250
|
+
|| list.find(x => x.id.toLowerCase() === ql)
|
|
1251
|
+
|| list.find(x => modelMatchesQuery(x, arg));
|
|
1252
|
+
if (m) applyModel(m).catch(e => notice(feed, e.message, 'error'));
|
|
1253
|
+
else notice(feed, `no model matching "${arg}"`, 'error');
|
|
1254
|
+
});
|
|
1255
|
+
break;
|
|
1256
|
+
}
|
|
1257
|
+
case '/thinking': {
|
|
1258
|
+
fetchModels().then(() => {
|
|
1259
|
+
if (!modelHasThinking()) {
|
|
1260
|
+
notice(feed, `${modelDisplayIdentity(state.model) || 'The current model'} does not support thinking effort. Choose a thinking model with /model.`, 'warn');
|
|
1261
|
+
return;
|
|
1262
|
+
}
|
|
1263
|
+
openOverlay(2, true, 'thinking');
|
|
1264
|
+
});
|
|
1265
|
+
break;
|
|
1266
|
+
}
|
|
1267
|
+
case '/compact': rpc.send({ type: 'compact', customInstructions: arg || undefined }).then(() => done('context compacted')).catch(e => notice(feed, e.message, 'error')); break;
|
|
1268
|
+
case '/autocompact': {
|
|
1269
|
+
const a = arg.trim().toLowerCase();
|
|
1270
|
+
if (a && !['on', 'off'].includes(a)) { done('usage: /autocompact [on|off]'); break; }
|
|
1271
|
+
const next = a ? a === 'on' : !state.autoCompaction;
|
|
1272
|
+
rpc.send({ type: 'set_auto_compaction', enabled: next })
|
|
1273
|
+
.then(() => { state.autoCompaction = next; done(`auto-compact → ${next ? 'on' : 'off'}`); })
|
|
1274
|
+
.catch(e => notice(feed, e.message, 'error'));
|
|
1275
|
+
break;
|
|
1276
|
+
}
|
|
1277
|
+
case '/new': rpc.send({ type: 'new_session' }).then(() => {
|
|
1278
|
+
resetFeed(feed);
|
|
1279
|
+
state.delivery = null;
|
|
1280
|
+
state.d2Source = '';
|
|
1281
|
+
state.d2Graph = null;
|
|
1282
|
+
state.sessionId = null;
|
|
1283
|
+
state.sessionFile = null;
|
|
1284
|
+
state.sessionName = null;
|
|
1285
|
+
state.stats = null;
|
|
1286
|
+
state.runStarted = 0;
|
|
1287
|
+
state.runEnded = 0;
|
|
1288
|
+
state.scroll = 0;
|
|
1289
|
+
state.planScroll = null;
|
|
1290
|
+
refreshState().catch(() => { });
|
|
1291
|
+
rpc.send({ type: 'get_session_stats' }).then(s => { state.stats = s; }).catch(() => { });
|
|
1292
|
+
done('new session');
|
|
1293
|
+
feed.version++;
|
|
1294
|
+
}).catch(e => notice(feed, e.message, 'error')); break;
|
|
1295
|
+
case '/resume': case '/sessions': {
|
|
1296
|
+
if (!arg) { openSessionPicker(); break; }
|
|
1297
|
+
const q = arg.toLowerCase();
|
|
1298
|
+
const it = listSessions(cwd).find(s => s.id === arg || s.id.startsWith(q) || (s.name || '').toLowerCase().includes(q));
|
|
1299
|
+
if (it) switchSession(it);
|
|
1300
|
+
else notice(feed, `no session matching "${arg}"`, 'error');
|
|
1301
|
+
break;
|
|
1302
|
+
}
|
|
1303
|
+
case '/restart': case '/kill': restartPi('restart'); break;
|
|
1304
|
+
case '/review': case '/review-mode': {
|
|
1305
|
+
const a = arg.trim().toLowerCase();
|
|
1306
|
+
if (!a) { startReview(); break; }
|
|
1307
|
+
if (a === 'status') { done(`self-review mode: ${reviewMode()}${opts.review ? ' (--review flag)' : ''}`); break; }
|
|
1308
|
+
if (normalizeReviewMode(a)) { saveCarthagentConfig({ review: a }); done(`self-review default → ${a} (saved to ${carthagentConfigPath()})`); break; }
|
|
1309
|
+
done('usage: /review [ask|yes|no|status] — bare /review starts a loop now');
|
|
1310
|
+
break;
|
|
1311
|
+
}
|
|
1312
|
+
case '/export': rpc.send({ type: 'export_html', outputPath: arg || undefined }).then(r => done(`exported → ${r?.path}`)).catch(e => notice(feed, e.message, 'error')); break;
|
|
1313
|
+
case '/copy':
|
|
1314
|
+
rpc.send({ type: 'get_last_assistant_text' }).then(r => {
|
|
1315
|
+
if (!r?.text) { done('no assistant response to copy yet'); return; }
|
|
1316
|
+
copyText(r.text);
|
|
1317
|
+
}).catch(e => notice(feed, e.message, 'error'));
|
|
1318
|
+
break;
|
|
1319
|
+
case '/stats': rpc.send({ type: 'get_session_stats' }).then(r => done(JSON.stringify(r))).catch(e => notice(feed, e.message, 'error')); break;
|
|
1320
|
+
case '/clear': feed.blocks = []; feed.version++; break;
|
|
1321
|
+
case '/update': case '/upgrade': {
|
|
1322
|
+
const a = arg.trim().toLowerCase().replace(/^--/, '');
|
|
1323
|
+
if (a && !['check', 'force'].includes(a)) { done('usage: /update [check|force]'); break; }
|
|
1324
|
+
if (state.updating) { notice(feed, 'an update is already running', 'warn'); break; }
|
|
1325
|
+
state.updating = true;
|
|
1326
|
+
notice(feed, a === 'check' ? 'checking for a Carthagent update…' : 'updating Carthagent…', 'info');
|
|
1327
|
+
const argv = [process.execPath, CTG_BIN, 'update'];
|
|
1328
|
+
if (a) argv.push(`--${a}`);
|
|
1329
|
+
runCommand(argv, { cwd, timeoutSeconds: 600 }).then(result => {
|
|
1330
|
+
state.updating = false;
|
|
1331
|
+
const out = strip(result.output || '').split('\n').map(l => l.trim()).filter(Boolean).slice(-2).join(' — ');
|
|
1332
|
+
if (result.code === 0) {
|
|
1333
|
+
if (a !== 'check') { state.updateAvailable = null; feed.version++; }
|
|
1334
|
+
notice(feed, out || 'Carthagent is up to date.', 'info');
|
|
1335
|
+
} else notice(feed, `update failed: ${out || (result.timedOut ? 'timed out' : 'see `ctg update` for details')}`, 'error');
|
|
1336
|
+
}).catch(e => { state.updating = false; notice(feed, `update failed: ${e.message}`, 'error'); });
|
|
1337
|
+
break;
|
|
1338
|
+
}
|
|
1339
|
+
case '/abort': abortRun(); break;
|
|
1340
|
+
default:
|
|
1341
|
+
// unknown slash → forward as prompt (the engine resolves extension commands, skills)
|
|
1342
|
+
if (state.running || state.awaitingRun) { echoUser(feed, v, true); sendAgent('steer', v); }
|
|
1343
|
+
else { echoUser(feed, v); sendAgent('prompt', v); }
|
|
1344
|
+
}
|
|
1345
|
+
};
|
|
1346
|
+
const push2 = text => { feed.blocks.push({ kind: 'notice', tone: 'info', text, t: Date.now() }); feed.version++; };
|
|
1347
|
+
|
|
1348
|
+
/** Extract the dragged screen region from the last rendered frame and write
|
|
1349
|
+
* it to the clipboard via native OS tool (e.g. pbcopy on macOS) and OSC 52
|
|
1350
|
+
* (for compatible / remote terminals, with tmux pass-through). */
|
|
1351
|
+
const copySelection = sel => {
|
|
1352
|
+
const clip = (state.overlay || state.sessions || state.slash || state.auth) ? null : copyClip;
|
|
1353
|
+
const text = sel.feed ? selectionText(sel.feed.lines, sel.logical, sel.feed.columns)
|
|
1354
|
+
: selectionText(screen.plain || [], sel, screen.w, clip);
|
|
1355
|
+
if (!text) return;
|
|
1356
|
+
copyText(text);
|
|
1357
|
+
};
|
|
1358
|
+
|
|
1359
|
+
const copyText = text => {
|
|
1360
|
+
const b64 = Buffer.from(text, 'utf8').toString('base64');
|
|
1361
|
+
const osc52 = `\x1b]52;c;${b64}\x07`;
|
|
1362
|
+
if (process.env.TMUX) {
|
|
1363
|
+
process.stdout.write(`\x1bPtmux;\x1b${osc52}\x1b\\`);
|
|
1364
|
+
} else {
|
|
1365
|
+
process.stdout.write(osc52);
|
|
1366
|
+
}
|
|
1367
|
+
writeClipboard(text).catch(() => {});
|
|
1368
|
+
state.toast = {
|
|
1369
|
+
text: `copy sent · ${Array.from(text).length} chars`,
|
|
1370
|
+
tone: 'info', until: Date.now() + 1500
|
|
1371
|
+
};
|
|
1372
|
+
};
|
|
1373
|
+
|
|
1374
|
+
function currentThemeName() {
|
|
1375
|
+
return THEME_NAMES.find(k => getTheme(k, termMode) === T.theme) || resolveThemeName();
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
/** Stamp a centered settings card over the rendered frame. */
|
|
1379
|
+
function stampOverlay(lines, W, H, frame) {
|
|
1380
|
+
const t = T_();
|
|
1381
|
+
const baseBg = t.background || '#0f0f0f';
|
|
1382
|
+
const elemBg = t.backgroundElement || baseBg;
|
|
1383
|
+
const paintCard = l => bgLine(l, W, elemBg);
|
|
1384
|
+
const thinkingPage = state.overlay.page === 'thinking';
|
|
1385
|
+
const searching = state.overlay.search !== undefined;
|
|
1386
|
+
const matches = searching ? choiceItems(state.overlay) : [];
|
|
1387
|
+
const maxListRows = Math.min(matches.length, Math.max(3, H - 12));
|
|
1388
|
+
const modelPage = searching && !thinkingPage && state.overlay.row === 2;
|
|
1389
|
+
const rows = searching ? [
|
|
1390
|
+
{ label: thinkingPage ? 'effort' : 'search', value: state.overlay.search + '\u2588' },
|
|
1391
|
+
{ label: thinkingPage ? 'model' : 'current', value: thinkingPage ? modelDisplayIdentity(state.model) : state.overlay.row === 2 ? modelDisplayIdentity(state.model) : state.overlay.row === 0 ? currentThemeName() : (providerDisplayName(state.overlay.provider) || 'All providers') },
|
|
1392
|
+
...(thinkingPage ? [{ label: 'current', value: state.thinking || '—' }] : modelPage && modelHasThinking() ? [{ label: 'thinking', value: state.thinking || '—' }] : []),
|
|
1393
|
+
] : [
|
|
1394
|
+
{ label: 'theme', value: currentThemeName() },
|
|
1395
|
+
{ label: 'provider', value: providerDisplayName(state.overlay.provider) || 'All providers' },
|
|
1396
|
+
{ label: 'model', value: modelDisplayIdentity(state.model) || '—' },
|
|
1397
|
+
];
|
|
1398
|
+
const cardW = Math.min(W - 4, 70);
|
|
1399
|
+
const innerW = cardW - 2;
|
|
1400
|
+
const x0 = Math.floor((W - cardW) / 2);
|
|
1401
|
+
const cardH = 3 + rows.length + 1 + (searching ? maxListRows + 1 : 0); // top + rows + hints + [list + sep] + bottom
|
|
1402
|
+
const y0 = Math.floor((H - cardH) / 2);
|
|
1403
|
+
const accent = t.primary || t.accent;
|
|
1404
|
+
const faint = t.textMuted || t.faint, muted = t.muted || faint;
|
|
1405
|
+
const bc = accent;
|
|
1406
|
+
const card = [];
|
|
1407
|
+
const title = thinkingPage ? ' Model thinking effort ' : searching ? ` Select ${['theme', 'provider filter', 'model'][state.overlay.row]} ` : ' settings ';
|
|
1408
|
+
const topFill = Math.max(0, innerW - 2 - title.length);
|
|
1409
|
+
card.push(fg(bc) + '╭' + '─'.repeat(2) + RESET + fg(muted) + title + RESET + fg(bc) + '─'.repeat(topFill) + '╮' + RESET);
|
|
1410
|
+
for (let i = 0; i < rows.length; i++) {
|
|
1411
|
+
const r = rows[i];
|
|
1412
|
+
const sel = i === state.overlay.row;
|
|
1413
|
+
const marker = sel ? fg(accent) + G.active + RESET : fg(faint) + ' ' + RESET;
|
|
1414
|
+
const label = (sel ? fg(accent) + BOLD : fg(muted)) + r.label.padEnd(9) + RESET;
|
|
1415
|
+
const val = fg(t.text) + (r.value || '—') + RESET;
|
|
1416
|
+
const core = truncate(' ' + marker + ' ' + label + ' ' + val, innerW);
|
|
1417
|
+
const padN = Math.max(0, innerW - width(core));
|
|
1418
|
+
card.push(fg(bc) + '│' + RESET + core + ' '.repeat(padN) + fg(bc) + '│' + RESET);
|
|
1419
|
+
}
|
|
1420
|
+
if (searching) {
|
|
1421
|
+
// Separator above the model list
|
|
1422
|
+
card.push(fg(bc) + '├' + '─'.repeat(innerW) + '┤' + RESET);
|
|
1423
|
+
const selIdx = state.overlay.sel ?? 0;
|
|
1424
|
+
const scrollOff = Math.max(0, selIdx - maxListRows + 1);
|
|
1425
|
+
for (let i = 0; i < maxListRows; i++) {
|
|
1426
|
+
const idx = scrollOff + i;
|
|
1427
|
+
const m = matches[idx];
|
|
1428
|
+
if (!m) { card.push(fg(bc) + '│' + RESET + ' '.repeat(innerW) + fg(bc) + '│' + RESET); continue; }
|
|
1429
|
+
const isSel = idx === selIdx;
|
|
1430
|
+
const prefix = isSel ? fg(accent) + G.active + RESET : fg(faint) + ' ' + RESET;
|
|
1431
|
+
const current = thinkingPage ? state.thinking : state.overlay.row === 2 ? state.model : state.overlay.row === 0 ? currentThemeName() : (state.overlay.provider || '');
|
|
1432
|
+
const suffix = m.description ? ` · ${m.description}` : '';
|
|
1433
|
+
const name = truncate((m.value === current ? '[current] ' : '') + m.label + suffix, innerW - 4);
|
|
1434
|
+
const nameCol = isSel ? fg(accent) + BOLD + name + RESET : fg(t.text) + name + RESET;
|
|
1435
|
+
const core = ' ' + prefix + ' ' + nameCol;
|
|
1436
|
+
const padN = Math.max(0, innerW - width(core));
|
|
1437
|
+
card.push(fg(bc) + '│' + RESET + core + ' '.repeat(padN) + fg(bc) + '│' + RESET);
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
const hints = state.overlay.pending ? ' Applying… please wait ' : state.overlay.error ? ` ${state.overlay.error} ` : searching && !matches.length ? (state.overlay.loading ? ' Loading… ' : ' No matches · type to filter · Esc cancel ') : searching ? ` ${(state.overlay.sel || 0) + 1}/${matches.length} · Enter ${thinkingPage ? 'set effort' : state.overlay.row === 2 ? 'switch' : 'apply'}${modelPage && modelHasThinking() ? ' · Tab effort' : ''} · Esc cancel ` : ' ↑↓ browse · Enter open · Esc close ';
|
|
1441
|
+
const hintText = truncate(hints, innerW);
|
|
1442
|
+
const hpad = Math.max(0, innerW - width(hintText));
|
|
1443
|
+
card.push(fg(bc) + '│' + RESET + fg(faint) + hintText + RESET + ' '.repeat(hpad) + fg(bc) + '│' + RESET);
|
|
1444
|
+
card.push(fg(bc) + '╰' + '─'.repeat(innerW) + '╯' + RESET);
|
|
1445
|
+
for (let i = 0; i < card.length; i++) {
|
|
1446
|
+
const y = y0 + i;
|
|
1447
|
+
if (y < 0 || y >= H) continue;
|
|
1448
|
+
lines[y] = paintCard(padEnd(truncate(' '.repeat(x0) + card[i], W), W));
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
const fmtAgo = ms => {
|
|
1453
|
+
const s = Math.max(0, (Date.now() - ms) / 1000);
|
|
1454
|
+
return s < 90 ? 'now' : s < 3600 ? `${Math.floor(s / 60)}m ago` : s < 86400 ? `${Math.floor(s / 3600)}h ago` : `${Math.floor(s / 86400)}d ago`;
|
|
1455
|
+
};
|
|
1456
|
+
|
|
1457
|
+
/** Session picker card: filterable list of this cwd's saved sessions. */
|
|
1458
|
+
function stampSessions(lines, W, H) {
|
|
1459
|
+
const t = T_();
|
|
1460
|
+
const baseBg = t.background || '#0f0f0f';
|
|
1461
|
+
const elemBg = t.backgroundElement || baseBg;
|
|
1462
|
+
const paintCard = l => bgLine(l, W, elemBg);
|
|
1463
|
+
const p = state.sessions;
|
|
1464
|
+
const items = filteredSessions();
|
|
1465
|
+
const cardW = Math.min(W - 4, 78);
|
|
1466
|
+
const innerW = cardW - 2;
|
|
1467
|
+
const maxRows = Math.min(Math.max(items.length, 1), Math.max(4, H - 10));
|
|
1468
|
+
const cardH = 1 + 1 + 1 + maxRows + 1 + 1; // top + search + sep + list + hints + bottom
|
|
1469
|
+
const x0 = Math.floor((W - cardW) / 2);
|
|
1470
|
+
const y0 = Math.floor((H - cardH) / 2);
|
|
1471
|
+
const accent = t.primary || t.accent;
|
|
1472
|
+
const faint = t.textMuted || t.faint, muted = t.muted || faint;
|
|
1473
|
+
const bc = accent;
|
|
1474
|
+
const row = core => fg(bc) + '│' + RESET + core + ' '.repeat(Math.max(0, innerW - width(core))) + fg(bc) + '│' + RESET;
|
|
1475
|
+
const card = [];
|
|
1476
|
+
const title = ' resume session ';
|
|
1477
|
+
card.push(fg(bc) + '╭' + '─'.repeat(2) + RESET + fg(muted) + title + RESET + fg(bc) + '─'.repeat(Math.max(0, innerW - 2 - title.length)) + '╮' + RESET);
|
|
1478
|
+
card.push(row(` ${fg(faint)}filter${RESET} ${fg(t.text)}${p.search}${fg(accent)}▌${RESET}`));
|
|
1479
|
+
card.push(fg(bc) + '├' + '─'.repeat(innerW) + '┤' + RESET);
|
|
1480
|
+
const selIdx = Math.min(p.sel, Math.max(0, items.length - 1));
|
|
1481
|
+
const scrollOff = Math.max(0, selIdx - maxRows + 1);
|
|
1482
|
+
for (let i = 0; i < maxRows; i++) {
|
|
1483
|
+
const s = items[scrollOff + i];
|
|
1484
|
+
if (!s) { card.push(row(items.length ? '' : ` ${fg(faint)}${ITALIC}no matches${RESET}`)); continue; }
|
|
1485
|
+
const isSel = scrollOff + i === selIdx;
|
|
1486
|
+
const meta = `${fmtAgo(s.modified)} · ${s.messageCount} msg · ${s.id.slice(0, 8)}`;
|
|
1487
|
+
const room = Math.max(8, innerW - 4 - strip(meta).length - 1);
|
|
1488
|
+
const name = s.name || s.firstMessage || '(empty session)';
|
|
1489
|
+
const marker = isSel ? fg(accent) + G.active + RESET : ' ';
|
|
1490
|
+
const label = (isSel ? fg(accent) + BOLD : fg(t.text)) + padEnd(truncate(name, room), room) + RESET;
|
|
1491
|
+
card.push(row(` ${marker} ${label} ${fg(faint)}${meta}${RESET}`));
|
|
1492
|
+
}
|
|
1493
|
+
const hints = ' type to filter · ↑↓ navigate · enter resume · esc close ';
|
|
1494
|
+
card.push(row(fg(faint) + hints + RESET));
|
|
1495
|
+
card.push(fg(bc) + '╰' + '─'.repeat(innerW) + '╯' + RESET);
|
|
1496
|
+
for (let i = 0; i < card.length; i++) {
|
|
1497
|
+
const y = y0 + i;
|
|
1498
|
+
if (y < 0 || y >= H) continue;
|
|
1499
|
+
lines[y] = paintCard(padEnd(truncate(' '.repeat(x0) + card[i], W), W));
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
/** Connect-provider popup: pick a provider (and auth method), then answer
|
|
1504
|
+
* the engine's login prompts inline — no terminal hand-off. */
|
|
1505
|
+
function stampAuth(lines, W, H) {
|
|
1506
|
+
const t = T_();
|
|
1507
|
+
const baseBg = t.background || '#0f0f0f';
|
|
1508
|
+
const elemBg = t.backgroundElement || baseBg;
|
|
1509
|
+
const paintCard = l => bgLine(l, W, elemBg);
|
|
1510
|
+
const a = state.auth;
|
|
1511
|
+
const cardW = Math.min(W - 4, 76);
|
|
1512
|
+
const innerW = cardW - 2;
|
|
1513
|
+
const accent = t.primary || t.accent;
|
|
1514
|
+
const accent2 = t.secondary || t.accent2 || accent;
|
|
1515
|
+
const faint = t.textMuted || t.faint, muted = t.muted || faint;
|
|
1516
|
+
const ok = t.success || t.ok;
|
|
1517
|
+
const bc = accent;
|
|
1518
|
+
const row = core => fg(bc) + '│' + RESET + core + ' '.repeat(Math.max(0, innerW - width(core))) + fg(bc) + '│' + RESET;
|
|
1519
|
+
const wrapText = (text, cols) => {
|
|
1520
|
+
const out = []; let line = '';
|
|
1521
|
+
for (const w of String(text).split(/\s+/)) {
|
|
1522
|
+
if (width(line) + w.length + 1 > cols && line) { out.push(line); line = w; }
|
|
1523
|
+
else line = line ? line + ' ' + w : w;
|
|
1524
|
+
}
|
|
1525
|
+
if (line) out.push(line);
|
|
1526
|
+
return out;
|
|
1527
|
+
};
|
|
1528
|
+
const card = [];
|
|
1529
|
+
const title = a.phase === 'type' ? ' auth method ' : a.phase === 'providers' ? ' connect a provider ' : ` ${a.provider?.name || 'provider'} `;
|
|
1530
|
+
card.push(fg(bc) + '╭' + '─'.repeat(2) + RESET + fg(muted) + title + RESET + fg(bc) + '─'.repeat(Math.max(0, innerW - 2 - title.length)) + '╮' + RESET);
|
|
1531
|
+
if (a.phase === 'providers') for (const l of wrapText("Carthagent's managed gateway is recommended; direct providers remain available.", innerW - 2)) card.push(row(` ${fg(accent2)}${l}${RESET}`));
|
|
1532
|
+
|
|
1533
|
+
if (a.phase === 'providers' || a.phase === 'type') {
|
|
1534
|
+
const items = a.phase === 'type'
|
|
1535
|
+
? (a.provider?.types || []).map(ty => ({ id: ty, name: authTypeLabel(ty, a.provider?.id) }))
|
|
1536
|
+
: authVisible();
|
|
1537
|
+
if (a.phase === 'providers') {
|
|
1538
|
+
card.push(row(` ${fg(faint)}filter${RESET} ${fg(t.text)}${a.filter}${fg(accent)}▌${RESET}`));
|
|
1539
|
+
card.push(fg(bc) + '├' + '─'.repeat(innerW) + '┤' + RESET);
|
|
1540
|
+
}
|
|
1541
|
+
const maxRows = Math.min(Math.max(items.length, 1), Math.max(4, H - 12));
|
|
1542
|
+
const selIdx = Math.min(a.sel, Math.max(0, items.length - 1));
|
|
1543
|
+
const scrollOff = Math.max(0, selIdx - maxRows + 1);
|
|
1544
|
+
for (let i = 0; i < maxRows; i++) {
|
|
1545
|
+
const it = items[scrollOff + i];
|
|
1546
|
+
if (!it) { card.push(row(items.length ? '' : ` ${fg(faint)}${a.busy ? 'loading…' : 'no matches'}${RESET}`)); continue; }
|
|
1547
|
+
const isSel = scrollOff + i === selIdx;
|
|
1548
|
+
const marker = isSel ? fg(accent) + G.active + RESET : ' ';
|
|
1549
|
+
if (a.phase === 'type') {
|
|
1550
|
+
card.push(row(` ${marker} ${(isSel ? fg(accent) + BOLD : fg(t.text)) + it.name + RESET}`));
|
|
1551
|
+
} else {
|
|
1552
|
+
const meta = it.types.map(type => authTypeLabel(type, it.id)).join(' · ');
|
|
1553
|
+
const configuredBadge = it.configured ? ` ${G.done} connected` : '';
|
|
1554
|
+
const recommendedBadge = it.recommended ? ' Recommended' : '';
|
|
1555
|
+
const badgeWidth = configuredBadge.length + recommendedBadge.length;
|
|
1556
|
+
const room = Math.max(8, innerW - 5 - meta.length - badgeWidth);
|
|
1557
|
+
const labelColor = it.recommended ? (t.error || t.err || accent2) : (isSel ? accent : t.text);
|
|
1558
|
+
const label = fg(labelColor) + (it.recommended || isSel ? BOLD : '') + padEnd(truncate(it.name, room), room) + RESET;
|
|
1559
|
+
card.push(row(` ${marker} ${label} ${it.recommended ? fg(t.error || t.err || accent2) + recommendedBadge + RESET : ''} ${fg(faint)}${meta}${RESET}${it.configured ? fg(ok) + configuredBadge + RESET : ''}`));
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
const hints = a.phase === 'type'
|
|
1563
|
+
? ' ↑↓ select · enter connect · esc back '
|
|
1564
|
+
: ' type to filter · ^v paste · ↑↓ select · enter connect · esc close ';
|
|
1565
|
+
card.push(row(fg(faint) + hints + RESET));
|
|
1566
|
+
} else {
|
|
1567
|
+
const wrap = (text, cols) => {
|
|
1568
|
+
const out = []; let line = '';
|
|
1569
|
+
for (const w of String(text).split(/\s+/)) {
|
|
1570
|
+
if (width(line) + w.length + 1 > cols && line) { out.push(line); line = w; }
|
|
1571
|
+
else line = line ? line + ' ' + w : w;
|
|
1572
|
+
}
|
|
1573
|
+
if (line) out.push(line);
|
|
1574
|
+
return out.length ? out : [''];
|
|
1575
|
+
};
|
|
1576
|
+
if (a.message) for (const l of wrap(a.message, innerW - 2)) card.push(row(' ' + fg(t.text) + l + RESET));
|
|
1577
|
+
if (a.deviceCode?.userCode) {
|
|
1578
|
+
card.push(row(' ' + fg(faint) + 'code' + RESET + ' ' + fg(accent) + BOLD + a.deviceCode.userCode + RESET));
|
|
1579
|
+
if (a.deviceCode.verificationUri) card.push(row(' ' + fg(faint) + 'url' + RESET + ' ' + fg(t.text) + truncate(a.deviceCode.verificationUri, innerW - 8) + RESET));
|
|
1580
|
+
} else if (a.url) {
|
|
1581
|
+
card.push(row(' ' + fg(t.text) + truncate(a.url, innerW - 2) + RESET));
|
|
1582
|
+
}
|
|
1583
|
+
if (a.instructions) for (const l of wrap(a.instructions, innerW - 2)) card.push(row(' ' + fg(faint) + l + RESET));
|
|
1584
|
+
if (Array.isArray(a.links)) for (const link of a.links) card.push(row(' ' + fg(faint) + truncate(link.url || '', innerW - 2) + RESET));
|
|
1585
|
+
if (a.phase === 'prompt') {
|
|
1586
|
+
card.push(fg(bc) + '├' + '─'.repeat(innerW) + '┤' + RESET);
|
|
1587
|
+
const p = a.prompt || {};
|
|
1588
|
+
if (p.type === 'select') {
|
|
1589
|
+
const opts = p.options || [];
|
|
1590
|
+
for (let i = 0; i < opts.length; i++) {
|
|
1591
|
+
const isSel = i === (a.promptSel || 0);
|
|
1592
|
+
const marker = isSel ? fg(accent) + G.active + RESET : ' ';
|
|
1593
|
+
card.push(row(` ${marker} ${(isSel ? fg(accent) + BOLD : fg(t.text)) + opts[i].label + RESET}`));
|
|
1594
|
+
}
|
|
1595
|
+
} else {
|
|
1596
|
+
const shown = p.type === 'secret' ? '•'.repeat(a.input.length) : a.input;
|
|
1597
|
+
const body = !shown && p.placeholder ? fg(faint) + p.placeholder + RESET : fg(t.text) + shown + RESET;
|
|
1598
|
+
card.push(row(` ${body}${fg(accent)}▌${RESET}`));
|
|
1599
|
+
}
|
|
1600
|
+
card.push(row(fg(faint) + (p.type === 'select' ? ' ↑↓ select · enter confirm · esc cancel ' : ' enter confirm · ^v paste · esc cancel ') + RESET));
|
|
1601
|
+
} else {
|
|
1602
|
+
card.push(row(fg(faint) + ' working… esc cancel ' + RESET));
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
card.push(fg(bc) + '╰' + '─'.repeat(innerW) + '╯' + RESET);
|
|
1606
|
+
|
|
1607
|
+
const x0 = Math.floor((W - cardW) / 2);
|
|
1608
|
+
const y0 = Math.floor((H - card.length) / 2);
|
|
1609
|
+
for (let i = 0; i < card.length; i++) {
|
|
1610
|
+
const y = y0 + i;
|
|
1611
|
+
if (y < 0 || y >= H) continue;
|
|
1612
|
+
lines[y] = paintCard(padEnd(truncate(' '.repeat(x0) + card[i], W), W));
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
/** Slash-command autocomplete card: bottom-anchored above the input box.
|
|
1617
|
+
* Left-justified (aligned with prompt area) with rows strictly bounded within box.
|
|
1618
|
+
* Shows filtered commands; ↑↓ select, tab/enter complete, esc close. */
|
|
1619
|
+
function stampSlash(lines, W, H) {
|
|
1620
|
+
const t = T_();
|
|
1621
|
+
const baseBg = t.background || '#0f0f0f';
|
|
1622
|
+
const elemBg = t.backgroundElement || baseBg;
|
|
1623
|
+
const paintCard = l => bgLine(l, W, elemBg);
|
|
1624
|
+
const p = state.slash;
|
|
1625
|
+
const { card, x0 } = renderSlashCard(p.items, p.sel, W, t, G);
|
|
1626
|
+
const y0 = H - 4 - card.length; // sit directly above the input box (3 rows + footer)
|
|
1627
|
+
for (let i = 0; i < card.length; i++) {
|
|
1628
|
+
const y = y0 + i;
|
|
1629
|
+
if (y < 0 || y >= H - 4) continue; // never overwrite the input box
|
|
1630
|
+
lines[y] = paintCard(padEnd(truncate(' '.repeat(x0) + card[i], W), W));
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
// ---- input
|
|
1635
|
+
const onKey = k => {
|
|
1636
|
+
state.lastActivity = Date.now();
|
|
1637
|
+
// Drag-select → copy, opencode-style: tracked here because mouse reporting
|
|
1638
|
+
// replaces the terminal's native selection. Works over any screen state.
|
|
1639
|
+
if (k.key === 'mousedown' || k.key === 'mousedrag' || k.key === 'mouseup') {
|
|
1640
|
+
// Control-click or right-click in/around the input box clears the prompt buffer
|
|
1641
|
+
if (k.key === 'mousedown' && (k.ctrl || k.button === 2) && k.y >= screen.h - 4 && k.y <= screen.h - 2) {
|
|
1642
|
+
if (editor.buf) { editor.clear(); updateSlash(); }
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
if (k.button === 0) {
|
|
1646
|
+
if (k.key === 'mousedown') {
|
|
1647
|
+
state.sel = { ax: k.x, ay: k.y, bx: k.x, by: k.y, dragged: false };
|
|
1648
|
+
if (!state.overlay && !state.sessions && !state.slash && !state.auth && feedViewport && k.y >= 4 && k.y <= screen.h - 4 && k.x <= feedViewport.columns) {
|
|
1649
|
+
state.sel.feed = { ...feedViewport, lines: cachedFeed.lines.map(strip) };
|
|
1650
|
+
const y = feedViewport.start + k.y - 3;
|
|
1651
|
+
state.sel.logical = { ax: k.x, ay: y, bx: k.x, by: y };
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
else if (k.key === 'mousedrag' && state.sel) {
|
|
1655
|
+
state.sel.bx = k.x; state.sel.by = k.y;
|
|
1656
|
+
if (k.x !== state.sel.ax || k.y !== state.sel.ay) state.sel.dragged = true;
|
|
1657
|
+
updateFeedSelection(state.sel);
|
|
1658
|
+
} else if (k.key === 'mouseup' && state.sel) {
|
|
1659
|
+
const sel = state.sel;
|
|
1660
|
+
sel.bx = k.x; sel.by = k.y;
|
|
1661
|
+
updateFeedSelection(sel);
|
|
1662
|
+
state.sel = null;
|
|
1663
|
+
if (sel.dragged) copySelection(sel);
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
return;
|
|
1667
|
+
}
|
|
1668
|
+
if (state.auth) {
|
|
1669
|
+
const a = state.auth;
|
|
1670
|
+
if (a.phase === 'prompt') {
|
|
1671
|
+
const p = a.prompt || {};
|
|
1672
|
+
if (p.type === 'select') {
|
|
1673
|
+
const opts = p.options || [];
|
|
1674
|
+
switch (k.key) {
|
|
1675
|
+
case 'up': a.promptSel = Math.max(0, (a.promptSel || 0) - 1); break;
|
|
1676
|
+
case 'down': a.promptSel = Math.min(opts.length - 1, (a.promptSel || 0) + 1); break;
|
|
1677
|
+
case 'enter': { const o = opts[a.promptSel || 0]; if (o) authSubmitPrompt(o.id); break; }
|
|
1678
|
+
case 'esc': authCancel(); break;
|
|
1679
|
+
case 'ctrl-c': cleanup(0); break;
|
|
1680
|
+
}
|
|
1681
|
+
} else {
|
|
1682
|
+
switch (k.key) {
|
|
1683
|
+
case 'enter': if (a.input.trim()) authSubmitPrompt(a.input.trim()); break;
|
|
1684
|
+
case 'esc': authCancel(); break;
|
|
1685
|
+
case 'ctrl-c': cleanup(0); break;
|
|
1686
|
+
case 'ctrl-v': authPasteClipboard(); break;
|
|
1687
|
+
case 'backspace': a.input = a.input.slice(0, -1); break;
|
|
1688
|
+
case 'char': a.input += k.ch; break;
|
|
1689
|
+
case 'paste': a.input += sanitizePaste(k.text); break;
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
feed.version++;
|
|
1693
|
+
return;
|
|
1694
|
+
}
|
|
1695
|
+
if (a.phase === 'waiting') {
|
|
1696
|
+
if (k.key === 'esc') authCancel();
|
|
1697
|
+
else if (k.key === 'ctrl-c') cleanup(0);
|
|
1698
|
+
return;
|
|
1699
|
+
}
|
|
1700
|
+
// provider / auth-method list
|
|
1701
|
+
const items = a.phase === 'type'
|
|
1702
|
+
? (a.provider?.types || []).map(ty => ({ id: ty, name: authTypeLabel(ty, a.provider?.id) }))
|
|
1703
|
+
: authVisible();
|
|
1704
|
+
a.sel = Math.max(0, Math.min(a.sel, Math.max(0, items.length - 1)));
|
|
1705
|
+
switch (k.key) {
|
|
1706
|
+
case 'esc':
|
|
1707
|
+
if (a.phase === 'type') { a.phase = 'providers'; a.sel = 0; a.type = null; }
|
|
1708
|
+
else state.auth = null;
|
|
1709
|
+
break;
|
|
1710
|
+
case 'ctrl-c': cleanup(0); break;
|
|
1711
|
+
case 'up': a.sel = Math.max(0, a.sel - 1); break;
|
|
1712
|
+
case 'down': a.sel = Math.min(items.length - 1, a.sel + 1); break;
|
|
1713
|
+
case 'pgup': a.sel = Math.max(0, a.sel - 8); break;
|
|
1714
|
+
case 'pgdn': a.sel = Math.min(items.length - 1, a.sel + 8); break;
|
|
1715
|
+
case 'backspace': if (a.phase === 'providers') { a.filter = a.filter.slice(0, -1); a.sel = 0; } break;
|
|
1716
|
+
case 'char': if (a.phase === 'providers' && k.ch) { a.filter += k.ch; a.sel = 0; } break;
|
|
1717
|
+
case 'paste': if (a.phase === 'providers') { a.filter += k.text; a.sel = 0; } break;
|
|
1718
|
+
case 'enter':
|
|
1719
|
+
if (a.phase === 'type') authStart(items[a.sel]?.id);
|
|
1720
|
+
else authChooseProvider(items[a.sel]);
|
|
1721
|
+
break;
|
|
1722
|
+
}
|
|
1723
|
+
feed.version++;
|
|
1724
|
+
return;
|
|
1725
|
+
}
|
|
1726
|
+
if (state.sessions) {
|
|
1727
|
+
const p = state.sessions;
|
|
1728
|
+
const items = filteredSessions();
|
|
1729
|
+
p.sel = Math.max(0, Math.min(p.sel, items.length - 1));
|
|
1730
|
+
switch (k.key) {
|
|
1731
|
+
case 'esc': case 'ctrl-r': case 'tab': state.sessions = null; break;
|
|
1732
|
+
case 'ctrl-c': cleanup(0); break;
|
|
1733
|
+
case 'up': p.sel = Math.max(0, p.sel - 1); break;
|
|
1734
|
+
case 'down': p.sel = Math.min(items.length - 1, p.sel + 1); break;
|
|
1735
|
+
case 'pgup': p.sel = Math.max(0, p.sel - 8); break;
|
|
1736
|
+
case 'pgdn': p.sel = Math.min(items.length - 1, p.sel + 8); break;
|
|
1737
|
+
case 'backspace': p.search = p.search.slice(0, -1); p.sel = 0; break;
|
|
1738
|
+
case 'enter': {
|
|
1739
|
+
const it = items[p.sel];
|
|
1740
|
+
state.sessions = null;
|
|
1741
|
+
if (it) switchSession(it);
|
|
1742
|
+
break;
|
|
1743
|
+
}
|
|
1744
|
+
case 'char': p.search += k.ch; p.sel = 0; break;
|
|
1745
|
+
case 'paste': p.search += k.text; p.sel = 0; break;
|
|
1746
|
+
}
|
|
1747
|
+
return;
|
|
1748
|
+
}
|
|
1749
|
+
if (state.overlay) {
|
|
1750
|
+
const p = state.overlay;
|
|
1751
|
+
if (k.key === 'ctrl-c') { cleanup(0); return; }
|
|
1752
|
+
if (p.pending) return;
|
|
1753
|
+
if (p.search !== undefined) {
|
|
1754
|
+
const items = choiceItems(p);
|
|
1755
|
+
if (k.key === 'tab' && p.row === 2) {
|
|
1756
|
+
if (p.page === 'thinking') { p.page = 'settings'; p.search = ''; p.sel = 0; p.error = ''; }
|
|
1757
|
+
else if (modelHasThinking()) {
|
|
1758
|
+
p.page = 'thinking'; p.search = ''; p.error = ''; p.loading = true; p.levels = [];
|
|
1759
|
+
rpc.send({ type: 'get_available_thinking_levels' }).then(result => {
|
|
1760
|
+
if (state.overlay !== p || p.page !== 'thinking') return;
|
|
1761
|
+
p.levels = result.levels || []; p.loading = false;
|
|
1762
|
+
const current = choiceItems(p).findIndex(item => item.value === state.thinking);
|
|
1763
|
+
p.sel = current < 0 ? 0 : current;
|
|
1764
|
+
}).catch(error => { if (state.overlay === p) { p.error = error.message; p.loading = false; } });
|
|
1765
|
+
} else p.error = 'Current model does not support thinking effort.';
|
|
1766
|
+
return;
|
|
1767
|
+
}
|
|
1768
|
+
const action = pickerKey(p, k.key, items.length);
|
|
1769
|
+
if (action === 'cancel') {
|
|
1770
|
+
restoreThemePreview(p);
|
|
1771
|
+
if (p.direct) state.overlay = null;
|
|
1772
|
+
else { p.search = undefined; p.error = ''; }
|
|
1773
|
+
} else if (action === 'commit') commitChoice(p, items[p.sel]);
|
|
1774
|
+
else if (k.key === 'char' || k.key === 'paste') {
|
|
1775
|
+
p.search += k.ch ?? k.text; p.sel = 0; p.error = '';
|
|
1776
|
+
previewThemeChoice(p);
|
|
1777
|
+
} else if (k.key === 'backspace') {
|
|
1778
|
+
p.search = p.search.slice(0, -1); p.sel = 0; p.error = '';
|
|
1779
|
+
previewThemeChoice(p);
|
|
1780
|
+
} else previewThemeChoice(p, items);
|
|
1781
|
+
} else {
|
|
1782
|
+
if (k.key === 'esc' || k.key === 'ctrl-t') state.overlay = null;
|
|
1783
|
+
else if (k.key === 'up') p.row = (p.row + 2) % 3;
|
|
1784
|
+
else if (k.key === 'down') p.row = (p.row + 1) % 3;
|
|
1785
|
+
else if (k.key === 'enter') {
|
|
1786
|
+
p.search = ''; p.sel = 0; p.error = '';
|
|
1787
|
+
if (p.row === 0) {
|
|
1788
|
+
p.originalTheme = currentThemeName();
|
|
1789
|
+
const themes = choiceItems(p);
|
|
1790
|
+
const current = themes.findIndex(item => item.value === p.originalTheme);
|
|
1791
|
+
p.sel = current < 0 ? 0 : current;
|
|
1792
|
+
previewThemeChoice(p, themes);
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
return;
|
|
1797
|
+
}
|
|
1798
|
+
// Which pane do scroll keys target? Single-pane views scroll what's
|
|
1799
|
+
// visible; in split, wheel routes by column when coords are present,
|
|
1800
|
+
// otherwise the focused pane (tab) wins.
|
|
1801
|
+
const scrollTarget = k => {
|
|
1802
|
+
if (state.view === 'plan') return 'plan';
|
|
1803
|
+
if (state.view === 'feed') return 'feed';
|
|
1804
|
+
if ((k.key === 'wheelup' || k.key === 'wheeldown') && typeof k.x === 'number') {
|
|
1805
|
+
const sideW = planSideWidth(screen.w);
|
|
1806
|
+
const feedW = screen.w - sideW - 1;
|
|
1807
|
+
if (k.x > feedW + 1) return 'plan';
|
|
1808
|
+
return 'feed';
|
|
1809
|
+
}
|
|
1810
|
+
return state.focusPane === 'plan' ? 'plan' : 'feed';
|
|
1811
|
+
};
|
|
1812
|
+
const scrollPlan = (d, abs) => {
|
|
1813
|
+
if (abs != null) { state.planScroll = abs; return; }
|
|
1814
|
+
state.planScroll = (state.planScroll ?? PLAN_FOLLOW) + d;
|
|
1815
|
+
};
|
|
1816
|
+
// ---- slash-command autocomplete popup: navigate/select while active.
|
|
1817
|
+
// Intercepts up/down/pgup/pgdn/tab/enter/esc before the main switch so the
|
|
1818
|
+
// popup owns those keys; all other keys fall through to edit the buffer
|
|
1819
|
+
// and then updateSlash() recomputes the matches.
|
|
1820
|
+
if (state.slash) {
|
|
1821
|
+
const p = state.slash;
|
|
1822
|
+
switch (k.key) {
|
|
1823
|
+
case 'up': p.sel = Math.max(0, p.sel - 1); return;
|
|
1824
|
+
case 'down': p.sel = Math.min(p.items.length - 1, p.sel + 1); return;
|
|
1825
|
+
case 'pgup': p.sel = Math.max(0, p.sel - 8); return;
|
|
1826
|
+
case 'pgdn': p.sel = Math.min(p.items.length - 1, p.sel + 8); return;
|
|
1827
|
+
case 'tab': case 'stab': if (completeSlash()) return; break; // fall through to pane-focus tab on no-op
|
|
1828
|
+
case 'enter': {
|
|
1829
|
+
const item = p.items[p.sel];
|
|
1830
|
+
if (item) { state.slash = null; editor.take(); submit(item.name); }
|
|
1831
|
+
return;
|
|
1832
|
+
}
|
|
1833
|
+
case 'esc': state.slash = null; return;
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
switch (k.key) {
|
|
1837
|
+
case 'char': editor.insert(k.ch); updateSlash(); break;
|
|
1838
|
+
case 'paste': editor.insert(k.text); updateSlash(); break;
|
|
1839
|
+
case 'ctrl-v': readClipboard().then(text => { if (state.auth) return; editor.insert(sanitizePaste(text, { multiline: true })); updateSlash(); }); break;
|
|
1840
|
+
case 'backspace': editor.backspace(); updateSlash(); break;
|
|
1841
|
+
case 'delete': editor.del(); updateSlash(); break;
|
|
1842
|
+
case 'left': editor.cur = Math.max(0, editor.cur - 1); break;
|
|
1843
|
+
case 'right': editor.cur = Math.min(editor.buf.length, editor.cur + 1); break;
|
|
1844
|
+
case 'home': editor.cur = 0; break;
|
|
1845
|
+
case 'end': editor.cur = editor.buf.length; break;
|
|
1846
|
+
case 'ctrl-u': case 'cmd-delete': editor.clear(); updateSlash(); break;
|
|
1847
|
+
case 'ctrl-w': case 'alt-backspace': case 'ctrl-backspace': editor.wordBack(); updateSlash(); break;
|
|
1848
|
+
case 'ctrl-k': case 'ctrl-delete': case 'alt-delete': editor.killEnd(); updateSlash(); break;
|
|
1849
|
+
case 'up': if (editor.buf === '' || editor.hi !== -1) editor.up(); else (scrollTarget(k) === 'plan' ? scrollPlan(-2) : state.scroll += 3); break;
|
|
1850
|
+
case 'down': if (editor.hi !== -1) editor.down(); else (scrollTarget(k) === 'plan' ? scrollPlan(2) : state.scroll = Math.max(0, state.scroll - 3)); break;
|
|
1851
|
+
case 'pgup': scrollTarget(k) === 'plan' ? scrollPlan(-8) : state.scroll += 12; break;
|
|
1852
|
+
case 'pgdn': scrollTarget(k) === 'plan' ? scrollPlan(8) : state.scroll = Math.max(0, state.scroll - 12); break;
|
|
1853
|
+
case 'wheelup': scrollTarget(k) === 'plan' ? scrollPlan(-3) : state.scroll += 3; break;
|
|
1854
|
+
case 'wheeldown': scrollTarget(k) === 'plan' ? scrollPlan(3) : state.scroll = Math.max(0, state.scroll - 3); break;
|
|
1855
|
+
case 'tab': {
|
|
1856
|
+
const narrow = screen.w < 96;
|
|
1857
|
+
if (narrow) {
|
|
1858
|
+
state.view = state.view === 'plan' ? 'feed' : 'plan';
|
|
1859
|
+
} else if (state.view === 'split') {
|
|
1860
|
+
// tab moves scroll focus between panes; shift+tab cycles views.
|
|
1861
|
+
state.focusPane = state.focusPane === 'plan' ? 'feed' : 'plan';
|
|
1862
|
+
} else {
|
|
1863
|
+
state.view = 'split';
|
|
1864
|
+
}
|
|
1865
|
+
screen.prev = [];
|
|
1866
|
+
break;
|
|
1867
|
+
}
|
|
1868
|
+
case 'stab': {
|
|
1869
|
+
const narrow = screen.w < 96;
|
|
1870
|
+
state.view = narrow ? (state.view === 'plan' ? 'feed' : 'plan') : (state.view === 'split' ? 'feed' : 'split');
|
|
1871
|
+
screen.prev = [];
|
|
1872
|
+
break;
|
|
1873
|
+
}
|
|
1874
|
+
case 'enter': submit(editor.take()); break;
|
|
1875
|
+
case 'ctrl-y':
|
|
1876
|
+
if (state.reviewOffer) startReview();
|
|
1877
|
+
else notice(feed, 'no pending self-review offer — /review starts a loop manually', 'info');
|
|
1878
|
+
break;
|
|
1879
|
+
case 'esc':
|
|
1880
|
+
if (state.running) { state.abortAt ? restartPi('force') : abortRun(); }
|
|
1881
|
+
else if (state.reviewOffer) state.reviewOffer = null;
|
|
1882
|
+
else if (editor.buf) editor.clear();
|
|
1883
|
+
else if (state.planScroll != null && state.planScroll !== PLAN_FOLLOW) state.planScroll = PLAN_FOLLOW;
|
|
1884
|
+
break;
|
|
1885
|
+
case 'ctrl-t': if (state.overlay) state.overlay = null; else openOverlay(0); break;
|
|
1886
|
+
case 'ctrl-r': openSessionPicker(); break;
|
|
1887
|
+
case 'ctrl-n': slash('/new'); break;
|
|
1888
|
+
case 'ctrl-l': feed.blocks = []; feed.version++; break;
|
|
1889
|
+
case 'x': state.expand = !state.expand; feed.version++; break;
|
|
1890
|
+
case 'ctrl-c':
|
|
1891
|
+
if (state.running) { state.abortAt ? restartPi('force') : abortRun(); editor.clear(); break; }
|
|
1892
|
+
if (editor.buf) { editor.clear(); break; }
|
|
1893
|
+
cleanup(0);
|
|
1894
|
+
break;
|
|
1895
|
+
}
|
|
1896
|
+
};
|
|
1897
|
+
const parseKeys = makeKeyParser(onKey);
|
|
1898
|
+
process.stdin.on('data', parseKeys);
|
|
1899
|
+
|
|
1900
|
+
// ---- cleanup
|
|
1901
|
+
let cleaned = false;
|
|
1902
|
+
const cleanup = code => {
|
|
1903
|
+
if (cleaned) return; cleaned = true;
|
|
1904
|
+
clearInterval(statePoll); clearInterval(harnessPoll); clearInterval(hashPoll);
|
|
1905
|
+
hashWorker?.terminate();
|
|
1906
|
+
rpc.kill();
|
|
1907
|
+
screen.exit();
|
|
1908
|
+
process.exit(code);
|
|
1909
|
+
};
|
|
1910
|
+
process.on('SIGINT', () => cleanup(130));
|
|
1911
|
+
process.on('SIGTERM', () => cleanup(143));
|
|
1912
|
+
screen.onResize = () => { state.sel = null; if (screen.w < 96 && state.view === 'split') state.view = 'feed'; };
|
|
1913
|
+
|
|
1914
|
+
// ---- render pieces
|
|
1915
|
+
const T_ = () => T.theme;
|
|
1916
|
+
const accent0 = () => { const t = T_(); return t.primary || t.accent; };
|
|
1917
|
+
const fmtDur = ms => { const s = Math.floor(ms / 1000); return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}`; };
|
|
1918
|
+
const fmtTok = n => n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(n);
|
|
1919
|
+
|
|
1920
|
+
function headerLines(W, frame) {
|
|
1921
|
+
const t = T_();
|
|
1922
|
+
const warn = t.warning || t.warn, err = t.error || t.err;
|
|
1923
|
+
const logo = fg(t.primary || t.accent) + BOLD + '𐤀 carthagent' + RESET;
|
|
1924
|
+
const spinChar = (state.running || state.awaitingRun) ? ` ${fg(t.primary || t.accent)}${spin(frame)}${RESET}` : '';
|
|
1925
|
+
const elapsed = state.runStarted ? fmtDur((state.running ? Date.now() : state.runEnded || Date.now()) - state.runStarted) : '';
|
|
1926
|
+
let model = modelDisplayIdentity(state.model);
|
|
1927
|
+
if (model && W < 130) model = model.split('/').at(-1);
|
|
1928
|
+
const ctxp = state.stats?.contextUsage?.percent;
|
|
1929
|
+
const ctxTxt = typeof ctxp === 'number' ? (ctxp < 10 ? ctxp.toFixed(1) : String(Math.round(ctxp))) : '';
|
|
1930
|
+
const ctxCol = typeof ctxp !== 'number' ? (t.textMuted || t.faint) : ctxp > 80 ? err : ctxp > 55 ? warn : (t.textMuted || t.faint);
|
|
1931
|
+
const ctxChip = typeof ctxp === 'number' ? `${fg(ctxCol)}ctx ${ctxTxt}%${RESET} ` : '';
|
|
1932
|
+
const shipChip = usingCloudModel() && state.shipUsage?.percent >= 80 ? `${fg(err)}⚓ ${state.shipUsage.percent}%${RESET} ` : '';
|
|
1933
|
+
const upChip = state.updateAvailable ? `${fg(warn)}↑ ${state.updateAvailable.version}${RESET} ` : '';
|
|
1934
|
+
const acChip = state.autoCompaction === false ? `${fg(warn)}ac off${RESET} ` : '';
|
|
1935
|
+
const truecolorOff = colorDepth !== 24;
|
|
1936
|
+
const tcChip = truecolorOff ? fg(warn) + `${G.stale} 256` + RESET + ' ' : '';
|
|
1937
|
+
const info = t.info || t.accent2 || t.secondary;
|
|
1938
|
+
const faint = t.textMuted || t.faint;
|
|
1939
|
+
const right = `${fg(faint)}${model}${state.thinking ? ':' + state.thinking : ''} ${shipChip}${upChip}${acChip}${ctxChip}${tcChip}${fg(faint)}${elapsed}${elapsed ? ' ' : ''}${feed.tokens ? fg(info) + fmtTok(feed.tokens) + ' tok' + RESET + ' ' : ''}${feed.cost ? fg(info) + '$' + feed.cost.toFixed(3) + RESET + ' ' : ''}${RESET}`;
|
|
1940
|
+
// Working directory is always in the header, right after the logo.
|
|
1941
|
+
const home = os.homedir();
|
|
1942
|
+
const shownCwd = cwd.startsWith(home) ? '~' + cwd.slice(home.length) : cwd;
|
|
1943
|
+
const head = `${logo}${spinChar} `;
|
|
1944
|
+
const cwdRoom = Math.max(8, W - width(head) - width(right) - 2);
|
|
1945
|
+
const left = head + truncate(fg(faint) + shownCwd + RESET, cwdRoom);
|
|
1946
|
+
const gap = Math.max(1, W - width(left) - width(right) - 1);
|
|
1947
|
+
return [truncate(left + ' '.repeat(gap) + right, W)];
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1950
|
+
function dividerLine(W, t) {
|
|
1951
|
+
return fg(t.borderSubtle || t.border) + '─'.repeat(W) + RESET;
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1954
|
+
/** Rail status: revision + fresh check count (the phase tracker was
|
|
1955
|
+
* removed from the panel header). */
|
|
1956
|
+
function phaseLines(W, t) {
|
|
1957
|
+
const faint = t.textMuted || t.faint;
|
|
1958
|
+
const ok = t.success || t.ok, warn = t.warning || t.warn, err = t.error || t.err;
|
|
1959
|
+
const { phase, index, revision } = computePhase(state.delivery, state.currentHash, state.checkToolRunning);
|
|
1960
|
+
const { fresh, total } = freshChecks(state.delivery, state.currentHash);
|
|
1961
|
+
const stale = total - fresh;
|
|
1962
|
+
const freshTxt = total
|
|
1963
|
+
? (stale > 0 ? fg(warn) + `${fresh}/${total} fresh` + RESET : fg(ok) + `${fresh}/${total} fresh` + RESET)
|
|
1964
|
+
: fg(faint) + 'no checks' + RESET;
|
|
1965
|
+
const revTxt = fg(faint) + `rev ${revision}` + RESET;
|
|
1966
|
+
const errMark = state.delivery && Object.values(state.delivery.evidence || {}).some(e => !e.passed)
|
|
1967
|
+
? ` ${fg(err)}${G.fail} failing${RESET}` : '';
|
|
1968
|
+
return { lines: [truncate(` ${revTxt} ${fg(faint)}·${RESET} ${freshTxt}${errMark}`, W)], phase, index };
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
function sideLines(W, H, frame) {
|
|
1972
|
+
const t = T_();
|
|
1973
|
+
const faint = t.textMuted || t.faint;
|
|
1974
|
+
const out = [];
|
|
1975
|
+
const pad = l => padEnd(truncate(l, W), W);
|
|
1976
|
+
const phases = phaseLines(W, t);
|
|
1977
|
+
out.push(...phases.lines.map(pad));
|
|
1978
|
+
const view = planningView(state.delivery, state.currentHash);
|
|
1979
|
+
out.push(pad(`${view.gate.phase} · ${state.planningTab}`));
|
|
1980
|
+
if (view.gate.locked) for (const l of wrap('LOCKED: validate / review / approve', Math.max(4, W - 1))) out.push(pad(l));
|
|
1981
|
+
if (state.planningTab !== 'workflow') {
|
|
1982
|
+
const rows = planningViewLines(view, state.planningTab).flatMap(line => wrap(line, Math.max(4, W - 1)));
|
|
1983
|
+
const start = typeof state.planScroll === 'number' && state.planScroll >= 0 ? state.planScroll : 0;
|
|
1984
|
+
out.push(...rows.slice(start, start + Math.max(0, H - out.length)).map(pad));
|
|
1985
|
+
while (out.length < H) out.push(pad(''));
|
|
1986
|
+
return out.slice(0, H);
|
|
1987
|
+
}
|
|
1988
|
+
out.push(pad(''));
|
|
1989
|
+
if (!state.d2Graph) {
|
|
1990
|
+
out.push(pad(`${fg(faint)}No active plan.${RESET}`));
|
|
1991
|
+
out.push(...statLines(W, t).map(pad));
|
|
1992
|
+
while (out.length < H) out.push(pad(''));
|
|
1993
|
+
return out;
|
|
1994
|
+
}
|
|
1995
|
+
const { states, checkRows, status, allFresh } = computeNodeStates(state.delivery, state.checkToolRunning, state.checkRunId, state.currentHash);
|
|
1996
|
+
const { phase: _phase, index: phaseIndex } = computePhase(state.delivery, state.currentHash, state.checkToolRunning);
|
|
1997
|
+
const stats = statLines(W, t, frame);
|
|
1998
|
+
const cov = coverageLine(W, t);
|
|
1999
|
+
const full = renderD2(state.d2Graph, { width: W - 1, theme: t, states, packet: null, flash: new Set(), frame, phaseIndex, glyphs: G });
|
|
2000
|
+
const graph = full;
|
|
2001
|
+
const { lines, hotRow, boxes = [] } = graph;
|
|
2002
|
+
|
|
2003
|
+
// Allocate height without starving the D2 graph
|
|
2004
|
+
const minGraphH = lines.length > 0 && H >= 12 ? Math.min(lines.length, 5) : 0;
|
|
2005
|
+
const availForChecks = Math.max(2, Math.min(checkRows.length, H - out.length - minGraphH - stats.length - cov.length - 4));
|
|
2006
|
+
const activeCheckRows = checkRows.slice(0, Math.min(checkRows.length, Math.max(2, availForChecks)));
|
|
2007
|
+
const chHeight = checkRowsHeight(activeCheckRows, state.delivery);
|
|
2008
|
+
|
|
2009
|
+
let graphH = Math.max(0, H - out.length - chHeight - stats.length - cov.length - 3);
|
|
2010
|
+
if (graphH < 3 && lines.length > 0 && H >= 12) {
|
|
2011
|
+
graphH = Math.min(lines.length, Math.max(3, H - out.length - chHeight - 2));
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
// Clamp manual scroll every frame; new graphs reset to follow.
|
|
2015
|
+
const maxStart = Math.max(0, lines.length - Math.max(0, graphH));
|
|
2016
|
+
if (state.planScroll != null && state.planScroll !== PLAN_FOLLOW) {
|
|
2017
|
+
state.planScroll = Math.min(Math.max(0, state.planScroll), maxStart);
|
|
2018
|
+
}
|
|
2019
|
+
const win = windowLines(lines, graphH, hotRow, state.planScroll ?? PLAN_FOLLOW, boxes);
|
|
2020
|
+
const startRow = win._start ?? 0;
|
|
2021
|
+
const graphTop = out.length;
|
|
2022
|
+
out.push(...win.map(pad));
|
|
2023
|
+
|
|
2024
|
+
// Show frontier detail only when frontier node is not already fully visible in the graph window
|
|
2025
|
+
const frontierBox = boxes.find(b => b.id === graph.frontierId);
|
|
2026
|
+
const frontierVisible = win.length > 0 && frontierBox && frontierBox.top >= startRow && frontierBox.bottom < startRow + win.length;
|
|
2027
|
+
let detail = frontierVisible ? [] : frontierDetail(W, t, states, graph.frontierId, graph.frontierLabel);
|
|
2028
|
+
|
|
2029
|
+
if (win.length > 0 && detail.length > 0) out.push(pad(''));
|
|
2030
|
+
out.push(...detail.map(pad));
|
|
2031
|
+
out.push(pad(''));
|
|
2032
|
+
out.push(...checkLines(activeCheckRows, W, t, frame).map(pad));
|
|
2033
|
+
out.push(...cov.map(pad));
|
|
2034
|
+
out.push(pad(''));
|
|
2035
|
+
out.push(...stats.map(pad));
|
|
2036
|
+
out.push(pad(''));
|
|
2037
|
+
const fp = state.currentHash ? state.currentHash.slice(0, 12) : '…';
|
|
2038
|
+
const ok = t.success || t.ok, warn = t.warning || t.warn;
|
|
2039
|
+
const fpColor = !state.delivery ? faint : allFresh ? ok : warn;
|
|
2040
|
+
// Drop whole trailing fields rather than truncating one mid-token.
|
|
2041
|
+
const fpBits = [status || ''];
|
|
2042
|
+
if (state.delivery?.revision) fpBits.push(`rev ${state.delivery.revision}`);
|
|
2043
|
+
if (state.delivery?.runId) fpBits.push(`run ${state.delivery.runId.slice(0, 6)}`);
|
|
2044
|
+
while (fpBits.length && width(`fp ${fp} ${fpBits.join(' · ')}`) > W) fpBits.pop();
|
|
2045
|
+
out.push(pad(`${fg(faint)}fp ${RESET}${fg(fpColor)}${fp}${RESET}${fpBits.length ? ` ${fg(faint)}${fpBits.join(' · ')}${RESET}` : ''}`));
|
|
2046
|
+
while (out.length < H) out.push(pad(''));
|
|
2047
|
+
const result = out.slice(0, H);
|
|
2048
|
+
// Scrollbar cells line up with the graph window only: the detail/check/stat
|
|
2049
|
+
// rows below it are pinned, not part of the scrolling region.
|
|
2050
|
+
const br = barRange(win.length, lines.length, startRow);
|
|
2051
|
+
if (br) {
|
|
2052
|
+
const bar = new Array(H).fill(null);
|
|
2053
|
+
for (let i = 0; i < win.length; i++) bar[graphTop + i] = (i >= br.pos && i < br.pos + br.len) ? 'thumb' : 'track';
|
|
2054
|
+
result._bar = bar;
|
|
2055
|
+
}
|
|
2056
|
+
return result;
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
/** 1–2 pinned lines under the graph: full frontier label (untruncated).
|
|
2060
|
+
* Active frontier gets a bold "CURRENT" tag so the live step is unambiguous
|
|
2061
|
+
* even before the swirl/pulse animations draw the eye. */
|
|
2062
|
+
function frontierDetail(W, t, states, frontierId, frontierLabel) {
|
|
2063
|
+
if (!frontierId || !frontierLabel) return [];
|
|
2064
|
+
const faint = t.textMuted || t.faint, muted = t.muted || faint;
|
|
2065
|
+
const st = states.get(frontierId) || 'pending';
|
|
2066
|
+
const accent = t.primary || t.accent;
|
|
2067
|
+
const ok = t.success || t.ok, warn = t.warning || t.warn, err = t.error || t.err;
|
|
2068
|
+
const dot = st === 'done' ? fg(ok) + G.done + RESET
|
|
2069
|
+
: st === 'fail' ? fg(err) + G.fail + RESET
|
|
2070
|
+
: st === 'stale' ? fg(warn) + G.stale + RESET
|
|
2071
|
+
: st === 'blocked' ? fg(warn) + G.blocked + RESET
|
|
2072
|
+
: st === 'active' ? fg(accent) + G.active + RESET
|
|
2073
|
+
: fg(faint) + G.pending + RESET;
|
|
2074
|
+
const tag = st === 'active' ? `${fg(accent)}${BOLD}CURRENT${RESET} ` : st === 'fail' ? `${fg(err)}${BOLD}STUCK${RESET} ` : st === 'blocked' ? `${fg(warn)}${BOLD}BLOCKED${RESET} ` : '';
|
|
2075
|
+
const head = `${tag}${dot} ${fg(muted)}${frontierId}${RESET} `;
|
|
2076
|
+
const avail = Math.max(8, W - width(head));
|
|
2077
|
+
const text = String(frontierLabel).replace(/\s+/g, ' ').trim();
|
|
2078
|
+
if (width(text) <= avail) return [truncate(head + fg(t.text) + text + RESET, W)];
|
|
2079
|
+
return wrapFrontier(head, text, avail, W, t);
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
function wrapFrontier(head, text, avail, W, t) {
|
|
2083
|
+
// Cheap word wrap on plain text (labels carry no ANSI).
|
|
2084
|
+
const words = text.split(/\s+/);
|
|
2085
|
+
const rows = [];
|
|
2086
|
+
let cur = '';
|
|
2087
|
+
for (const w of words) {
|
|
2088
|
+
const next = cur ? cur + ' ' + w : w;
|
|
2089
|
+
let ww = 0;
|
|
2090
|
+
ww += [...next].length;
|
|
2091
|
+
if (ww > avail && cur) { rows.push(cur); cur = w; if (rows.length === 2) break; }
|
|
2092
|
+
else cur = next;
|
|
2093
|
+
}
|
|
2094
|
+
if (cur && rows.length < 2) rows.push(cur);
|
|
2095
|
+
const stillOver = text.length > rows.join(' ').length + 1;
|
|
2096
|
+
const out = [truncate(head + fg(t.text) + (rows[0] || '') + RESET, W)];
|
|
2097
|
+
if (rows[1] != null) {
|
|
2098
|
+
let second = rows[1] + (stillOver ? '…' : '');
|
|
2099
|
+
while (second.length && second.length + 2 > avail) second = second.slice(0, -2) + (stillOver ? '…' : '');
|
|
2100
|
+
out.push(truncate(' ' + fg(t.text) + second + RESET, W));
|
|
2101
|
+
}
|
|
2102
|
+
return out;
|
|
2103
|
+
}
|
|
2104
|
+
|
|
2105
|
+
/** One line summarizing acceptance-criteria evidence coverage. Flags
|
|
2106
|
+
* criteria with no fresh passing check and those backed only by static
|
|
2107
|
+
* probes — the white-screen case the checks list alone never surfaced. */
|
|
2108
|
+
function coverageLine(W, t) {
|
|
2109
|
+
const delivery = state.delivery;
|
|
2110
|
+
if (!delivery?.plan?.acceptance?.length) return [];
|
|
2111
|
+
const faint = t.textMuted || t.faint;
|
|
2112
|
+
const ok = t.success || t.ok, warn = t.warning || t.warn;
|
|
2113
|
+
const report = coverageReport(delivery.plan, delivery.evidence, state.currentHash, delivery);
|
|
2114
|
+
const covered = report.filter(r => r.covered).length;
|
|
2115
|
+
const staticOnly = report.filter(r => r.staticOnly).length;
|
|
2116
|
+
const uncovered = report.length - covered;
|
|
2117
|
+
const parts = [`${covered}/${report.length} criteria`];
|
|
2118
|
+
if (uncovered) parts.push(`${uncovered} uncovered`);
|
|
2119
|
+
if (staticOnly) parts.push(`${staticOnly} static-only`);
|
|
2120
|
+
// Drop whole segments rather than letting truncate clip one mid-word.
|
|
2121
|
+
while (parts.length > 1 && width(` COVERAGE ${parts.join(' · ')}`) > W) parts.pop();
|
|
2122
|
+
const tone = uncovered || staticOnly ? warn : ok;
|
|
2123
|
+
return [truncate(`${fg(faint)} COVERAGE${RESET} ${fg(tone)}${parts.join(' · ')}${RESET}`, W)];
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
function statLines(W, t) {
|
|
2127
|
+
const faint = t.textMuted || t.faint, muted = t.muted || faint;
|
|
2128
|
+
if (!state.stats && !feed.tokens && !feed.cost) return [];
|
|
2129
|
+
const tokens = state.stats?.tokens?.total ?? feed.tokens;
|
|
2130
|
+
const context = state.stats?.contextUsage?.percent;
|
|
2131
|
+
const cost = state.stats?.cost ?? feed.cost;
|
|
2132
|
+
if (!tokens && !cost && (typeof context !== 'number' || context === 0)) return [];
|
|
2133
|
+
const parts = [];
|
|
2134
|
+
if (tokens) parts.push(`tokens ${fmtTok(tokens)}`);
|
|
2135
|
+
if (typeof context === 'number' && context > 0) parts.push(`context ${Math.round(context)}%`);
|
|
2136
|
+
if (cost) parts.push(`cost $${cost.toFixed(3)}`);
|
|
2137
|
+
if (!parts.length) return [];
|
|
2138
|
+
// Drop whole segments rather than letting truncate clip one mid-word.
|
|
2139
|
+
while (parts.length > 1 && width(` USAGE ${parts.join(' ')}`) > W) parts.pop();
|
|
2140
|
+
return [truncate(`${fg(faint)} USAGE${RESET} ${fg(muted)}${parts.join(' ')}${RESET}`, W)];
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2143
|
+
function checkRowsHeight(rows, delivery) {
|
|
2144
|
+
// header + up to 8 rows + the "… more" line when clipped + handoff
|
|
2145
|
+
return 1 + Math.min(rows.length, 8) + (rows.length > 8 ? 1 : 0) + (delivery?.handoff ? 1 : 0);
|
|
2146
|
+
}
|
|
2147
|
+
|
|
2148
|
+
function checkLines(rows, W, t, frame) {
|
|
2149
|
+
const faint = t.textMuted || t.faint, muted = t.muted || faint;
|
|
2150
|
+
const ok = t.success || t.ok, warn = t.warning || t.warn, err = t.error || t.err;
|
|
2151
|
+
const accent = t.primary || t.accent, hot = t.accent || t.hot;
|
|
2152
|
+
const doneN = rows.filter(r => r.st === 'done').length;
|
|
2153
|
+
const prog = rows.length
|
|
2154
|
+
? ` ${fg(doneN === rows.length ? ok : accent)}${bar(doneN / rows.length, Math.min(10, W - 12), { filled: '▓', empty: '░' })}${RESET} ${fg(muted)}${doneN}/${rows.length}${RESET}`
|
|
2155
|
+
: '';
|
|
2156
|
+
const out = [`${fg(faint)} CHECKS${RESET}${prog}`];
|
|
2157
|
+
for (const r of rows.slice(0, 8)) {
|
|
2158
|
+
const icon =
|
|
2159
|
+
r.st === 'done' ? fg(ok) + G.done + RESET :
|
|
2160
|
+
r.st === 'fail' ? fg(err) + G.fail + RESET :
|
|
2161
|
+
r.st === 'stale' ? fg(warn) + G.stale + RESET :
|
|
2162
|
+
r.st === 'running' ? fg(accent) + spin(frame) + RESET :
|
|
2163
|
+
r.st === 'queued' ? fg(faint) + G.queued + RESET :
|
|
2164
|
+
fg(faint) + G.pending + RESET;
|
|
2165
|
+
const meta = r.st === 'fail' ? `exit ${r.code}` : r.st === 'running' ? 'running' : r.ms != null ? `${(r.ms / 1000).toFixed(1)}s` : r.kind;
|
|
2166
|
+
const staleMark = r.st === 'stale' ? fg(warn) + ' stale' + RESET : '';
|
|
2167
|
+
out.push(` ${icon} ${fg(r.st === 'pending' ? faint : t.text)}${r.id}${RESET} ${fg(faint)}${meta}${staleMark}${r.required ? fg(hot) + ' req' + RESET : ''}${RESET}`);
|
|
2168
|
+
}
|
|
2169
|
+
if (rows.length > 8) out.push(` ${fg(faint)}… ${rows.length - 8} more${RESET}`);
|
|
2170
|
+
const h = state.delivery?.handoff;
|
|
2171
|
+
if (h) out.push(`${fg(faint)} handoff ${RESET}${fg(h.status === 'verified' ? ok : warn)}${h.status}${RESET}`);
|
|
2172
|
+
return out;
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
function windowLines(lines, h, hot, manual = PLAN_FOLLOW, boxes = []) {
|
|
2176
|
+
if (h < 3) return [];
|
|
2177
|
+
if (lines.length <= h) {
|
|
2178
|
+
const win = lines.slice();
|
|
2179
|
+
win._start = 0;
|
|
2180
|
+
return win;
|
|
2181
|
+
}
|
|
2182
|
+
let start;
|
|
2183
|
+
if (manual != null && manual !== PLAN_FOLLOW) {
|
|
2184
|
+
start = Math.min(Math.max(0, manual), lines.length - h);
|
|
2185
|
+
for (const b of boxes) {
|
|
2186
|
+
if (b.top < start && start <= b.bottom) {
|
|
2187
|
+
start = b.top;
|
|
2188
|
+
break;
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
} else {
|
|
2192
|
+
const target = boxes.find(b => b.top <= hot && b.bottom >= hot) || boxes.find(b => b.top === hot);
|
|
2193
|
+
if (target && h >= target.h) {
|
|
2194
|
+
start = target.top - Math.floor((h - target.h) / 2);
|
|
2195
|
+
} else {
|
|
2196
|
+
start = hot - Math.floor(h * 0.4);
|
|
2197
|
+
}
|
|
2198
|
+
start = Math.min(Math.max(0, start), lines.length - h);
|
|
2199
|
+
for (const b of boxes) {
|
|
2200
|
+
if (b.top < start && start <= b.bottom) {
|
|
2201
|
+
if (target && b.top + h >= target.bottom + 1) {
|
|
2202
|
+
start = b.top;
|
|
2203
|
+
} else {
|
|
2204
|
+
start = b.bottom + 1;
|
|
2205
|
+
}
|
|
2206
|
+
break;
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
start = Math.min(Math.max(0, start), lines.length - h);
|
|
2211
|
+
const win = lines.slice(start, start + h);
|
|
2212
|
+
win._start = start;
|
|
2213
|
+
return win;
|
|
2214
|
+
}
|
|
2215
|
+
|
|
2216
|
+
function inputBox(W, frame) {
|
|
2217
|
+
const t = T_();
|
|
2218
|
+
const faint = t.textMuted || t.faint;
|
|
2219
|
+
const hot = state.running || state.awaitingRun;
|
|
2220
|
+
const bc = hot ? (t.borderActive || t.primary || t.accent) : t.border;
|
|
2221
|
+
const framingOn = state.autoFraming && opts.delivery !== false;
|
|
2222
|
+
// Phased delivery is the carthagent default — the pill stays empty so the
|
|
2223
|
+
// product stays clean of mode badges. Steering keeps its label.
|
|
2224
|
+
const mode = hot ? 'steer' : '';
|
|
2225
|
+
const titleTxt = mode ? ` ${mode}${opts.demo ? ' · demo' : ''} `
|
|
2226
|
+
: state.reviewOffer ? ' self-review? ^y start · esc skip ' : '';
|
|
2227
|
+
const fill = Math.max(0, W - 2 - width(titleTxt));
|
|
2228
|
+
const top = titleTxt
|
|
2229
|
+
? fg(bc) + '╭' + RESET + fg(hot ? (t.primary || t.accent) : faint) + BOLD + titleTxt + RESET + fg(bc) + '─'.repeat(fill) + '╮' + RESET
|
|
2230
|
+
: fg(bc) + '╭' + '─'.repeat(Math.max(0, W - 2)) + '╮' + RESET;
|
|
2231
|
+
const prompt = hot ? fg(t.warning || t.warn) + G.active + RESET : fg(t.primary || t.accent) + '›' + RESET;
|
|
2232
|
+
const hint = state.awaitingRun
|
|
2233
|
+
? 'starting run…'
|
|
2234
|
+
: state.running
|
|
2235
|
+
? 'steer the run…'
|
|
2236
|
+
: framingOn ? frameHint(frame) : 'message carthagent…';
|
|
2237
|
+
const hintLine = fg(faint) + ITALIC + hint + ' /help' + RESET;
|
|
2238
|
+
// horizontal scroll: keep the cursor visible when the buffer overflows
|
|
2239
|
+
const avail = Math.max(4, W - 6);
|
|
2240
|
+
let off = 0;
|
|
2241
|
+
while (width(editor.buf.slice(0, editor.cur).slice(off)) >= avail) off++;
|
|
2242
|
+
const view = editor.buf.slice(off);
|
|
2243
|
+
const shown = editor.buf ? fg(t.text) + view + RESET : hintLine;
|
|
2244
|
+
const midCore = ` ${prompt} ${shown}`;
|
|
2245
|
+
const mid = fg(bc) + '│' + RESET + padEnd(truncate(midCore, W - 2), W - 2) + fg(bc) + '│' + RESET;
|
|
2246
|
+
const bot = fg(bc) + '╰' + '─'.repeat(Math.max(0, W - 2)) + '╯' + RESET;
|
|
2247
|
+
const cx = Math.min(W - 1, 5 + width(editor.buf.slice(0, editor.cur).slice(off)));
|
|
2248
|
+
return { rows: [top, mid, bot], cx };
|
|
2249
|
+
}
|
|
2250
|
+
|
|
2251
|
+
function footerLine(W, frame) {
|
|
2252
|
+
const t = T_();
|
|
2253
|
+
const faint = t.textMuted || t.faint;
|
|
2254
|
+
const escLabel = state.running ? (state.abortAt ? 'force restart' : 'abort') : 'clear';
|
|
2255
|
+
const sep = ` ${fg(t.border)}·${RESET} `;
|
|
2256
|
+
const hints = [
|
|
2257
|
+
`${fg(faint)}enter${RESET} ${(state.running || state.awaitingRun) ? 'steer' : 'send'}`,
|
|
2258
|
+
`${fg(faint)}esc${RESET} ${escLabel}`,
|
|
2259
|
+
`${fg(faint)}tab${RESET} focus`,
|
|
2260
|
+
`${fg(faint)}${G.shift}tab${RESET} view`,
|
|
2261
|
+
`${fg(faint)}^r${RESET} resume`,
|
|
2262
|
+
`${fg(faint)}^t${RESET} settings`,
|
|
2263
|
+
`${fg(faint)}^x${RESET} expand`,
|
|
2264
|
+
`${fg(faint)}^c${RESET} quit`,
|
|
2265
|
+
];
|
|
2266
|
+
// Drop trailing hints when the row can't fit them — truncating mid-hint
|
|
2267
|
+
// leaves a dangling separator or half a key, which reads as broken.
|
|
2268
|
+
while (hints.length > 2 && width(' ' + hints.join(sep)) > W) hints.pop();
|
|
2269
|
+
const keys = ' ' + hints.join(sep);
|
|
2270
|
+
const toast = state.toast && Date.now() < state.toast.until ? state.toast : null;
|
|
2271
|
+
if (toast) {
|
|
2272
|
+
const tone = toast.tone === 'error' ? (t.error || t.err) : toast.tone === 'warning' ? (t.warning || t.warn) : (t.info || t.accent2 || t.secondary);
|
|
2273
|
+
const chip = fg(tone) + toast.text + RESET;
|
|
2274
|
+
return truncate(chip + ' '.repeat(Math.max(1, W - width(chip) - width(strip(keys)) - 1)), W);
|
|
2275
|
+
}
|
|
2276
|
+
return truncate(keys, W);
|
|
2277
|
+
}
|
|
2278
|
+
|
|
2279
|
+
// ---- main render
|
|
2280
|
+
let cachedFeed = { v: -1, w: -1, expand: null, lines: [], blockRows: [] };
|
|
2281
|
+
let feedViewport = null;
|
|
2282
|
+
const updateFeedSelection = sel => {
|
|
2283
|
+
if (!sel.feed || !feedViewport) return;
|
|
2284
|
+
sel.logical.bx = Math.max(1, Math.min(sel.feed.columns, sel.bx));
|
|
2285
|
+
sel.logical.by = Math.max(1, Math.min(sel.feed.lines.length, feedViewport.start + Math.max(4, Math.min(screen.h - 4, sel.by)) - 3));
|
|
2286
|
+
};
|
|
2287
|
+
// Pane column geometry of the last frame, for drag-copy clipping.
|
|
2288
|
+
let copyClip = null;
|
|
2289
|
+
function render(frame) {
|
|
2290
|
+
const W = screen.w, H = screen.h, t = T_();
|
|
2291
|
+
const faint = t.textMuted || t.faint;
|
|
2292
|
+
const baseBg = t.background || '#0f0f0f';
|
|
2293
|
+
const panelBg = t.backgroundPanel || baseBg;
|
|
2294
|
+
const paintBase = l => bgLine(l, W, baseBg);
|
|
2295
|
+
screen.bgHex = baseBg;
|
|
2296
|
+
if (W < 30 || H < 8) {
|
|
2297
|
+
screen.frame([paintBase(fg(t.warning || t.warn) + 'terminal too small — resize' + RESET)], null);
|
|
2298
|
+
return;
|
|
2299
|
+
}
|
|
2300
|
+
const lines = new Array(H).fill('');
|
|
2301
|
+
lines[0] = headerLines(W, frame)[0];
|
|
2302
|
+
lines[1] = dividerLine(W, t);
|
|
2303
|
+
|
|
2304
|
+
const contentH = H - 6; // header2 + input box3 + footer1
|
|
2305
|
+
const narrow = W < 96;
|
|
2306
|
+
const planOnly = state.view === 'plan';
|
|
2307
|
+
const showSide = planOnly || (state.view === 'split' && !narrow);
|
|
2308
|
+
// Wider terminals get a wider PLAN rail (d2 text breathes); planOnly is
|
|
2309
|
+
// already full-width. Guard the feed so it never collapses below 36 cols.
|
|
2310
|
+
let sideW = planOnly ? W : showSide ? planSideWidth(W) : 0;
|
|
2311
|
+
if (showSide && !planOnly && W - sideW - 1 < 36) sideW = Math.max(0, W - 37);
|
|
2312
|
+
const feedW = planOnly ? 0 : W - sideW - (showSide ? 1 : 0);
|
|
2313
|
+
// Each pane reserves its rightmost column for a scrollbar; the PLAN rail
|
|
2314
|
+
// reclaims the spare column between it and the feed separator.
|
|
2315
|
+
const feedContentW = planOnly ? 0 : feedW - 1;
|
|
2316
|
+
const planContentW = planOnly ? W - 1 : sideW - 1;
|
|
2317
|
+
const planAreaW = planOnly ? W : sideW;
|
|
2318
|
+
// 0-based, end-exclusive content columns for each split pane. Copying
|
|
2319
|
+
// clips to the drag anchor's pane so a feed selection never drags in the
|
|
2320
|
+
// scrollbar, the │ separator or plan-rail fragments. Rows 0-1 (header)
|
|
2321
|
+
// are full-width; rows from index 2 through the body keep the composition.
|
|
2322
|
+
copyClip = showSide && !planOnly
|
|
2323
|
+
? { feedEnd: feedContentW, planStart: feedW + 1, planEnd: feedW + 1 + planContentW, rowTop: 2, rowBottom: H - 5 }
|
|
2324
|
+
: null;
|
|
2325
|
+
|
|
2326
|
+
// pane titles — MESSAGES only now; the PLAN rail no longer carries a
|
|
2327
|
+
// title or phase tracker. In split, the focused feed pane gets ●.
|
|
2328
|
+
const feedDot = state.view === 'split' ? (state.focusPane === 'feed' ? fg(accent0()) + G.phaseDone + RESET + ' ' : fg(faint) + G.phasePending + RESET + ' ') : '';
|
|
2329
|
+
const feedTitle = `${feedDot}${fg(faint)}MESSAGES${RESET}`;
|
|
2330
|
+
lines[2] = planOnly ? '' : truncate(feedTitle, feedW);
|
|
2331
|
+
// feed body (base surface)
|
|
2332
|
+
const bodyTop = 3, bodyH = contentH - 1;
|
|
2333
|
+
if (state.view !== 'plan') {
|
|
2334
|
+
if (!state.sel?.feed && (cachedFeed.v !== feed.version || cachedFeed.w !== feedContentW || cachedFeed.expand !== state.expand || frame % 4 === 0)) {
|
|
2335
|
+
cachedFeed = { v: feed.version, w: feedContentW, expand: state.expand, ...renderFeed(feed, feedContentW, t, { expandResults: state.expand, frame, glyphs: G }) };
|
|
2336
|
+
}
|
|
2337
|
+
const fl = cachedFeed.lines;
|
|
2338
|
+
const maxScroll = Math.max(0, fl.length - bodyH);
|
|
2339
|
+
if (state.sel?.feed && state.sel.dragged && frame % 2 === 0) {
|
|
2340
|
+
if (state.sel.by <= 4) state.scroll++;
|
|
2341
|
+
else if (state.sel.by >= H - 4) state.scroll--;
|
|
2342
|
+
}
|
|
2343
|
+
state.scroll = Math.max(0, Math.min(state.scroll, maxScroll));
|
|
2344
|
+
const start = Math.max(0, fl.length - bodyH - state.scroll);
|
|
2345
|
+
feedViewport = { start, columns: feedContentW };
|
|
2346
|
+
if (state.sel?.feed) updateFeedSelection(state.sel);
|
|
2347
|
+
const fr = barRange(bodyH, fl.length, start);
|
|
2348
|
+
const feedFocused = state.focusPane === 'feed';
|
|
2349
|
+
for (let i = 0; i < bodyH; i++) {
|
|
2350
|
+
const bar = !fr ? null : (i >= fr.pos && i < fr.pos + fr.len) ? 'thumb' : 'track';
|
|
2351
|
+
lines[bodyTop + i] = paintBase(padEnd(truncate(fl[start + i] || '', feedContentW), feedContentW) + scrollCell(G, bar, feedFocused, t));
|
|
2352
|
+
}
|
|
2353
|
+
if (state.scroll > 0) lines[2] = paintBase(truncate(feedTitle + fg(faint) + ` ↑ ${state.scroll} above` + RESET, feedW));
|
|
2354
|
+
else lines[2] = planOnly ? lines[2] : paintBase(truncate(feedTitle, feedW));
|
|
2355
|
+
} else {
|
|
2356
|
+
feedViewport = null;
|
|
2357
|
+
lines[2] = paintBase(lines[2]);
|
|
2358
|
+
}
|
|
2359
|
+
lines[0] = paintBase(lines[0]);
|
|
2360
|
+
lines[1] = paintBase(lines[1]);
|
|
2361
|
+
|
|
2362
|
+
// side panel — always visible in split view; the d2 phase graph is core.
|
|
2363
|
+
// Painted on backgroundPanel so the rail reads as a distinct surface.
|
|
2364
|
+
// The whole composed row keeps the base fill; the panel cell content
|
|
2365
|
+
// carries its own panel fill via bgLine inside sideLines-less paintPanel.
|
|
2366
|
+
const panelFill = bg(panelBg);
|
|
2367
|
+
const paintPanel = l => bgLine(l, planAreaW > 0 ? planAreaW : W, panelBg);
|
|
2368
|
+
if (showSide) {
|
|
2369
|
+
const planOnly = state.view === 'plan';
|
|
2370
|
+
const sl = sideLines(planContentW, bodyH, frame);
|
|
2371
|
+
const planBar = sl._bar || [];
|
|
2372
|
+
const planFocused = state.focusPane === 'plan';
|
|
2373
|
+
const borderColor = state.focusPane === 'plan' ? (t.borderActive || t.borderHot || t.border) : t.border;
|
|
2374
|
+
const sep = planOnly ? '' : fg(borderColor) + panelFill + '│' + RESET;
|
|
2375
|
+
if (!planOnly) lines[2] = paintBase(padEnd(truncate(lines[2] || '', feedW), feedW) + sep + paintPanel(''));
|
|
2376
|
+
for (let i = 0; i < sl.length && bodyTop + i < H - 4; i++) {
|
|
2377
|
+
const row = bodyTop + i;
|
|
2378
|
+
const body = padEnd(truncate(sl[i] || '', planContentW), planContentW) + scrollCell(G, planBar[i], planFocused, t);
|
|
2379
|
+
lines[row] = planOnly
|
|
2380
|
+
? paintBase(body)
|
|
2381
|
+
: paintBase(padEnd(truncate((lines[row] || ''), feedW), feedW) + sep + paintPanel(body));
|
|
2382
|
+
}
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
// boxed input
|
|
2386
|
+
const box = inputBox(W, frame);
|
|
2387
|
+
lines[H - 4] = paintBase(box.rows[0]);
|
|
2388
|
+
lines[H - 3] = paintBase(box.rows[1]);
|
|
2389
|
+
lines[H - 2] = paintBase(box.rows[2]);
|
|
2390
|
+
lines[H - 1] = paintBase(footerLine(W, frame));
|
|
2391
|
+
// fill untouched body rows so no default-bg gaps remain
|
|
2392
|
+
for (let i = 0; i < H; i++) if (!lines[i]) lines[i] = paintBase('');
|
|
2393
|
+
|
|
2394
|
+
if (state.overlay) stampOverlay(lines, W, H, frame);
|
|
2395
|
+
if (state.sessions) stampSessions(lines, W, H);
|
|
2396
|
+
if (state.slash) stampSlash(lines, W, H);
|
|
2397
|
+
if (state.auth) stampAuth(lines, W, H);
|
|
2398
|
+
// inverse-video the dragged region so selection is visible while held;
|
|
2399
|
+
// clip the highlight to the anchor pane exactly as copySelection does
|
|
2400
|
+
if (state.sel?.feed) {
|
|
2401
|
+
const [top, bot] = selectionBounds(state.sel.logical);
|
|
2402
|
+
for (let i = 0; i < bodyH; i++) {
|
|
2403
|
+
const y = feedViewport.start + i + 1;
|
|
2404
|
+
if (y < top.y || y > bot.y) continue;
|
|
2405
|
+
lines[bodyTop + i] = inverseCols(lines[bodyTop + i], y === top.y ? top.x - 1 : 0, y === bot.y ? bot.x : feedContentW);
|
|
2406
|
+
}
|
|
2407
|
+
} else if (state.sel) {
|
|
2408
|
+
const { ax, ay, bx, by } = state.sel;
|
|
2409
|
+
const top = (ay < by || (ay === by && ax <= bx)) ? { x: ax, y: ay } : { x: bx, y: by };
|
|
2410
|
+
const bot = (top.x === ax && top.y === ay) ? { x: bx, y: by } : { x: ax, y: ay };
|
|
2411
|
+
const selClip = (state.overlay || state.sessions || state.slash || state.auth) ? null : copyClip;
|
|
2412
|
+
for (let y = Math.max(1, top.y); y <= Math.min(bot.y, lines.length); y++) {
|
|
2413
|
+
const raw0 = y === top.y ? top.x - 1 : 0;
|
|
2414
|
+
const raw1 = y === bot.y ? bot.x : W;
|
|
2415
|
+
const [c0, c1] = paneClipCols(selClip, ax, y, raw0, raw1);
|
|
2416
|
+
lines[y - 1] = inverseCols(lines[y - 1] || '', Math.max(0, c0), Math.max(0, c1));
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
screen.frame(lines, (state.overlay || state.sessions || state.slash || state.auth) ? null : { y: H - 2, x: box.cx });
|
|
2420
|
+
}
|
|
2421
|
+
|
|
2422
|
+
screen.enter(cwd);
|
|
2423
|
+
let frame = 0;
|
|
2424
|
+
let renderWarned = false;
|
|
2425
|
+
setInterval(() => {
|
|
2426
|
+
try { render(frame++); } catch (e) {
|
|
2427
|
+
if (process.env.CARTHAGENT_DEBUG && !renderWarned) { renderWarned = true; try { notice(feed, `render: ${e.stack?.split('\n')[0] || e.message}`, 'error'); } catch { } }
|
|
2428
|
+
}
|
|
2429
|
+
}, 66);
|
|
2430
|
+
// Welcome card doubles as the feed's empty state.
|
|
2431
|
+
const noProvider = !opts.demo && !hasConfiguredProvider();
|
|
2432
|
+
const welcome = { kind: 'welcome', model: modelDisplayIdentity(state.model || opts.model || ''), cwd, mode: opts.demo ? 'demo' : 'extension', noProvider, t: Date.now() };
|
|
2433
|
+
feed.blocks.push(welcome); feed.version++;
|
|
2434
|
+
rpc.send({ type: 'get_state' }).then(s => { applyActiveModel(s.model); }).catch(() => { });
|
|
2435
|
+
if (opts.prompt) submit(opts.prompt);
|
|
2436
|
+
if (opts.resume) openSessionPicker();
|
|
2437
|
+
if (opts.openAuth) {
|
|
2438
|
+
await refreshState().catch(() => null);
|
|
2439
|
+
await openAuth();
|
|
2440
|
+
} else if (noProvider) {
|
|
2441
|
+
// First run with no credentials: auto-open the provider picker focused on Carthagent Ship.
|
|
2442
|
+
await refreshState().catch(() => null);
|
|
2443
|
+
await openAuth({ focusProviderId: 'experiential-labs' });
|
|
2444
|
+
}
|
|
2445
|
+
}
|