@hncode/hncode 0.8.6 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -0
- package/README_CN.md +27 -0
- package/package.json +1 -1
- package/src/agent.js +172 -43
- package/src/bootstrap.js +63 -56
- package/src/ci.js +247 -247
- package/src/colors.js +5 -1
- package/src/commands.js +121 -0
- package/src/composer.js +31 -1
- package/src/config.js +177 -45
- package/src/context.js +29 -0
- package/src/files.js +32 -0
- package/src/fx.js +19 -2
- package/src/i18n.js +180 -131
- package/src/index.js +558 -77
- package/src/permission-gate.js +103 -0
- package/src/plugin.js +221 -2
- package/src/prompt-presets.js +36 -0
- package/src/protocol.js +184 -0
- package/src/registry-browser.js +14 -3
- package/src/remote.js +117 -5
- package/src/schedule.js +148 -11
- package/src/serve.js +613 -0
- package/src/session-client.js +148 -0
- package/src/session-host.js +52 -0
- package/src/session.js +26 -3
- package/src/settings-schema.js +2 -2
- package/src/status-line.js +48 -0
- package/src/toml.js +18 -4
- package/src/tool-status.js +45 -0
- package/src/tools/bash.js +43 -24
- package/src/tools/edit.js +10 -5
- package/src/tools/web-search.js +8 -5
- package/src/tools/write.js +28 -3
- package/src/tui.js +448 -1380
- package/src/ws.js +248 -0
- package/src/session-hub.js +0 -445
- package/src/web-auth.js +0 -98
- package/src/web-daemon-cli.js +0 -63
- package/src/web-daemon-client.js +0 -203
- package/src/web-daemon.js +0 -894
- package/src/web-live.js +0 -250
- package/src/web-public/app.css +0 -1524
- package/src/web-public/app.js +0 -2969
- package/src/web-public/complete.js +0 -154
- package/src/web-public/fonts/JetBrainsMono-Bold.woff2 +0 -0
- package/src/web-public/fonts/JetBrainsMono-Regular.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-100-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-101-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-102-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-103-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-104-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-105-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-106-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-107-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-108-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-109-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-110-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-111-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-112-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-113-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-114-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-115-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-116-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-117-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-118-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-119-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-21-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-22-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-23-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-24-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-25-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-26-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-27-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-28-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-29-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-30-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-31-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-32-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-33-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-34-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-35-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-36-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-37-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-38-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-39-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-4-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-40-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-41-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-42-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-43-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-44-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-45-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-46-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-47-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-48-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-49-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-5-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-50-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-51-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-52-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-53-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-54-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-55-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-56-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-57-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-58-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-59-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-6-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-60-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-61-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-62-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-63-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-64-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-65-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-66-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-67-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-68-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-69-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-70-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-71-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-72-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-73-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-74-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-75-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-76-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-77-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-78-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-79-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-80-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-81-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-82-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-83-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-84-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-85-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-86-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-87-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-88-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-89-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-90-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-91-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-97-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-98-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc-99-400-normal.woff2 +0 -0
- package/src/web-public/fonts/noto-sans-sc.css +0 -775
- package/src/web-public/fonts.css +0 -31
- package/src/web-public/home.css +0 -222
- package/src/web-public/home.html +0 -33
- package/src/web-public/home.js +0 -160
- package/src/web-public/i18n.js +0 -983
- package/src/web-public/index.html +0 -196
- package/src/web-public/login.css +0 -123
- package/src/web-public/login.html +0 -25
- package/src/web-public/login.js +0 -46
- package/src/web-public/settings.js +0 -290
- package/src/web-ws.js +0 -226
- package/src/web.js +0 -430
package/src/tui.js
CHANGED
|
@@ -23,6 +23,8 @@ import {
|
|
|
23
23
|
import { copyText, readText, warmClipboard, readClipboardContentAsync, readClipboardTextOnly, imageUrlFromClipboardText, cleanupPastedImages, stopClipboardHelper } from './clipboard.js';
|
|
24
24
|
import { Dictation } from './voice.js';
|
|
25
25
|
import { visualWidth, estimateTokens, estimateTokensFloat, estimateMessagesTokens, estimateMessageTokens, messageTokens, expandTabs } from './term.js';
|
|
26
|
+
import { contextBreakdown } from './context.js';
|
|
27
|
+
import { collectWorkspaceFiles } from './files.js';
|
|
26
28
|
// The extracted modules are pulled in as NAMESPACES and unpacked into local bindings. That way adding a helper to
|
|
27
29
|
// one of them is a one-line change there, rather than an edit to a long named-import list that silently leaves a
|
|
28
30
|
// name out and fails at runtime with "X is not defined".
|
|
@@ -92,6 +94,7 @@ export {
|
|
|
92
94
|
} from './markdown.js';
|
|
93
95
|
|
|
94
96
|
import * as toolLine from './tool-line.js';
|
|
97
|
+
import { isFailureResult, failureReason } from './tool-status.js';
|
|
95
98
|
|
|
96
99
|
const { msgColorFor, keyArgument, formatToolLine } = toolLine;
|
|
97
100
|
|
|
@@ -163,12 +166,12 @@ import { buildTree, visibleRows, allDirs, renderTree, moveSel } from './file-tre
|
|
|
163
166
|
import { walkFiles } from './tools/ignore.js';
|
|
164
167
|
|
|
165
168
|
|
|
166
|
-
import { Agent, SYSTEM_PROMPT, THINKING_TAGS_INSTRUCTION, needsThinkingTags, addUsage } from './agent.js';
|
|
169
|
+
import { Agent, SYSTEM_PROMPT, THINKING_TAGS_INSTRUCTION, needsThinkingTags, addUsage, PLAN_MODE_INSTRUCTION } from './agent.js';
|
|
167
170
|
import { LLM } from './llm.js';
|
|
168
171
|
import * as sess from './session.js';
|
|
169
172
|
import { convRowFor } from './session.js';
|
|
170
173
|
import { resolveProvider, resolveModelArg, addProvider, removeProvider, addModel, upsertModel, replaceProviderModels, fetchModels, fetchCatalog, modelKey, modelLabel, bareModelId, effortOptions, effortWire, effortsFromReasoning, rememberModel, hncodeConfigFile, resolveConfig, setConfigString, setConfigBool, readPersonalPrompt, readPersonalPromptRaw, writePersonalPrompt, personalPromptFile, readAgentsMd, agentsFilesFor, readMemory, readMemoryRaw, writeMemoryRaw, memoryFile, ensureWebToken, effectiveSnapshot, costFromCatalog, modelCost, usageCost } from './config.js';
|
|
171
|
-
import { pluginCommands, renderWidgets, runHooks, runPatch, runPatchSync, runKeybindsSync, pluginKeybinds, setPluginLoggerTui } from './plugin.js';
|
|
174
|
+
import { pluginCommands, renderWidgets, runHooks, runPatch, runPatchSync, runKeybindsSync, pluginKeybinds, setPluginLoggerTui, unloadPlugins, loadPlugins, takePluginNotices, setPluginHost, setPluginSurface } from './plugin.js';
|
|
172
175
|
import { OTHER_LABEL, SUPPLEMENT_LABEL } from './tools/ask-user-question.js';
|
|
173
176
|
import { render as renderTodos } from './tools/todo.js';
|
|
174
177
|
// `latex.js` is NOT imported here. `renderLatex` had no call site in this file — the same dead import mermaid had, and
|
|
@@ -197,10 +200,12 @@ import { diffScreens, placementKey, placementRows, setImageRegenerator } from '.
|
|
|
197
200
|
// module evaluation, the single largest item on the path to the first frame.
|
|
198
201
|
import { getTool, toolNames } from './tools/index.js';
|
|
199
202
|
import { installGoalStore, getGoal } from './tools/goal.js';
|
|
200
|
-
import {
|
|
203
|
+
import { describeRules, selfTestRules, describeSelfTest } from './permissions.js';
|
|
201
204
|
import { isDestructiveCommand as shellIsDestructiveCommand, isReadOnlyCommand as shellIsReadOnlyCommand } from './shell-safety.js';
|
|
202
|
-
import { usdRate, syncRate, convert, normalizeCurrency, SUPPORTED_CURRENCIES } from './fx.js';
|
|
203
|
-
import { approvalKey, sessionApprovalLabel,
|
|
205
|
+
import { usdRate, syncRate, convert, normalizeCurrency, SUPPORTED_CURRENCIES, costCurrency } from './fx.js';
|
|
206
|
+
import { approvalKey, sessionApprovalLabel, rememberApproval, describeSessionApprovals } from './session-approvals.js';
|
|
207
|
+
import { decideApproval } from './permission-gate.js';
|
|
208
|
+
import { statusTallyText, setStatusLang } from './status-line.js';
|
|
204
209
|
import { listStyles, findStyle, styleReminder, writeStyleTemplate, styleDirs, nameFromFile } from './output-styles.js';
|
|
205
210
|
import { EXPERIMENTS, experimentState, enabledExperiments, mergeExperiments, pruneUnknown, describeExperiments, isExperiment } from './experiments.js';
|
|
206
211
|
import { forkMessages, SideThread, recapMessages, digestStats, SIDE_RO_TOOLS, SIDE_TOOL_REFUSAL, sideToolAllowed } from './side-thread.js';
|
|
@@ -208,9 +213,6 @@ import { listSchedules, dueSchedules, markRun, describeSchedules, validateEntry,
|
|
|
208
213
|
import { packSession, serializeTeleport, parseTeleport, unpackInto, teleportFileName, describeTeleport } from './teleport.js';
|
|
209
214
|
import { buildSteps, renderStep, replaySummary, stateAtStep } from './rollout.js';
|
|
210
215
|
import { renderBtwPanel, btwPanelHeight } from './btw-panel.js';
|
|
211
|
-
import { SessionHub } from './session-hub.js';
|
|
212
|
-
// `web.js` is NOT imported here. It is the `/web` HTTP and SSE server — 70ms of module evaluation, and the only thing
|
|
213
|
-
// that reaches it is `/web` itself. Every session paid that before its first frame for a feature most never start.
|
|
214
216
|
import { FAMILIES, TASKS, buildPreset, presetLabel } from './prompt-presets.js';
|
|
215
217
|
import { tuiView } from './session-view.js';
|
|
216
218
|
import { SessionCore } from './session-core.js';
|
|
@@ -316,7 +318,7 @@ function costEntry(cost) {
|
|
|
316
318
|
let uiLang = 'en';
|
|
317
319
|
|
|
318
320
|
/** Point the UI at a language id. Called once, from startTUI. */
|
|
319
|
-
export function setUiLang(lang) { uiLang = lang === 'zh' ? 'zh' : 'en'; i18nSetUiLang(uiLang); }
|
|
321
|
+
export function setUiLang(lang) { uiLang = lang === 'zh' ? 'zh' : 'en'; i18nSetUiLang(uiLang); setStatusLang(uiLang); }
|
|
320
322
|
/** The language the UI is currently speaking. */
|
|
321
323
|
export function getUiLang() { return i18nGetUiLang(); }
|
|
322
324
|
|
|
@@ -352,110 +354,16 @@ export function trTitle(title) {
|
|
|
352
354
|
// Monotonic counter for /search: each query bumps it so a slow ripgrep result
|
|
353
355
|
// from an earlier keystroke is discarded instead of overwriting newer hits.
|
|
354
356
|
let searchSeq = 0;
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
{ name: 'ask', aliases: ['manual'], desc: 'Ask mode: read-only runs automatically; every other action asks first.', priority: 99 },
|
|
366
|
-
{ name: 'model', desc: 'Switch LLM model', priority: 100 },
|
|
367
|
-
// The argument hint is a PLACEHOLDER, not the level list: the real levels come
|
|
368
|
-
// from the current model (models.dev), so they are completed live by
|
|
369
|
-
// setArgCompletionProvider rather than hardcoded here.
|
|
370
|
-
{ name: 'effort', aliases: ['thinking'], desc: 'Switch thinking effort', priority: 95, argumentHint: '[level]' },
|
|
371
|
-
{ name: 'provider', aliases: ['providers'], desc: 'Manage AI providers (add / delete)', priority: 95 },
|
|
372
|
-
{ name: 'help', aliases: ['h', '?'], desc: 'Show available commands and shortcuts', priority: 80 },
|
|
373
|
-
{ name: 'new', aliases: ['clear'], desc: 'Start a fresh session in the current workspace', priority: 80 },
|
|
374
|
-
{ name: 'sessions', aliases: ['resume'], desc: 'Browse and resume sessions', priority: 80 },
|
|
375
|
-
{ name: 'all-sessions', desc: 'Browse sessions from EVERY workspace', priority: 79 },
|
|
376
|
-
{ name: 'tasks', aliases: ['task'], desc: 'Browse background tasks (full-screen panel)', priority: 80 },
|
|
377
|
-
{ name: 'swarm', desc: 'Toggle swarm mode: decompose work across parallel subagents', priority: 80, argumentHint: '[on|off]' },
|
|
378
|
-
{ name: 'subagent-model', aliases: ['swarm-sub-agent'], desc: 'Which model subagents run on, for both Agent and AgentSwarm (default = this session\u2019s model)', priority: 60, argumentHint: '[<model> | default]' },
|
|
379
|
-
{ name: 'compact', desc: 'Compact the conversation context (AI summary + keep last 20%)', priority: 80, argumentHint: '[ratio]' },
|
|
380
|
-
{ name: 'goal', aliases: ['objective'], desc: 'Start or manage an autonomous goal', priority: 80, argumentHint: '[status|pause|resume|cancel|replace <text>] | <objective>' },
|
|
381
|
-
{ name: 'init', desc: 'Generate or update AGENTS.md from the codebase', priority: 70, argumentHint: '[instructions]' },
|
|
382
|
-
{ name: 'fork', desc: 'Fork the current session into a copy without switching to it', priority: 80 },
|
|
383
|
-
// `/rewind` is the name this is usually looked for by; the behaviour is the same picker either way.
|
|
384
|
-
{ name: 'undo', aliases: ['rewind'], desc: 'Rewind to an earlier prompt: the transcript truncates and the files those turns changed are restored', priority: 80, argumentHint: '[count]' },
|
|
385
|
-
{ name: 'trim', desc: 'Trim old tool results now, down to the keep ratio (manual)', priority: 40, argumentHint: '[keep-ratio]' },
|
|
386
|
-
{ name: 'auto-trim', aliases: ['autotrim'], desc: 'Auto tool-result trimming: the threshold is a share of the WINDOW, `keep` a share of the tool-result TEXT', priority: 40, argumentHint: '[on|off | threshold <n> | keep <n>]' },
|
|
387
|
-
{ name: 'title', aliases: ['rename'], desc: 'Set or show session title (also sets window title)', priority: 60, argumentHint: '<title>' },
|
|
388
|
-
{ name: 'auto-title', desc: 'Let the model name the session from its first message (persisted)', priority: 60, argumentHint: '[on|off]' },
|
|
389
|
-
{ name: 'ptc', desc: 'PTC mode: every tool call goes through the programmatic sandbox, no direct tools', priority: 55, argumentHint: '[on|off]' },
|
|
390
|
-
{ name: 'status', desc: 'Show current session and runtime status', priority: 60 },
|
|
391
|
-
{ name: 'doctor', desc: 'Diagnose the environment: config, store, MCP, hooks, disk, git, terminal', priority: 60, argumentHint: '[--all] [--probe]' },
|
|
392
|
-
{ name: 'memory-profile', aliases: ['memprof'], desc: 'Where this session’s memory goes: text vs tool results vs tool arguments', priority: 60, argumentHint: '[--verbose]' },
|
|
393
|
-
{ name: 'usage', desc: 'Show real token totals (provider-reported) + context window', priority: 60 },
|
|
394
|
-
{ name: 'stats', aliases: ['summary'], desc: 'What this session has done: turns, tools, files touched, time and tokens', priority: 59 },
|
|
395
|
-
{ name: 'cost', desc: 'Show what this session has spent, in USD or CNY', priority: 60, argumentHint: '[usd|cny]' },
|
|
396
|
-
{ name: 'context', aliases: ['ctx'], desc: 'Break down what fills the context window', priority: 60 },
|
|
397
|
-
{ name: 'raw', desc: 'Show assistant replies verbatim: no Markdown, no wrapping', priority:50, argumentHint: '[on|off]' },
|
|
398
|
-
{ name: 'reduced-motion', desc: 'Replace all animation with a slow-breathing indicator', priority: 50, argumentHint: '[on|off]' },
|
|
399
|
-
{ name: 'shimmer-edge', desc: 'Sweep edge: cosine (soft both sides) or linear (hard leading edge)', priority: 40, argumentHint: '[cosine|linear]' },
|
|
400
|
-
{ name: 'output-style', aliases: ['style'], desc: 'Apply an output style loaded from ~/.hncode/output-styles/*.md', priority: 50, argumentHint: '[name | off | new <name> | edit]' },
|
|
401
|
-
{ name: 'experiments', desc: 'List or toggle unfinished features', priority: 50, argumentHint: '[name on|off]' },
|
|
402
|
-
{ name: 'btw', aliases: ['aside'], desc: 'Ask a question in a side thread that does not enter the conversation', priority: 55, argumentHint: '[question]' },
|
|
403
|
-
{ name: 'recap', desc: 'Say where this session got to, without changing it', priority: 55 },
|
|
404
|
-
{ name: 'secondary-model', aliases: ['small-model'], desc: 'Pick the model used for side questions and recaps', priority: 45, argumentHint: '[model | off]' },
|
|
405
|
-
{ name: 'replay', aliases: ['rollout'], desc: 'Step back through this session: what the model saw at each step', priority: 45, argumentHint: '[step | next | prev | last]' },
|
|
406
|
-
{ name: 'schedule', desc: 'Recurring prompts queued on a running session', priority: 45, argumentHint: '[list | run <id>]' },
|
|
407
|
-
{ name: 'teleport', desc: 'Export or import this session for another machine or checkout', priority: 45, argumentHint: '[export [path] | import <file>]' },
|
|
408
|
-
{ name: 'search', aliases: ['grep'], desc: 'Search the project and insert the hit into the composer', priority: 60, argumentHint: '[query]' },
|
|
409
|
-
{ name: 'mcp', desc: 'Show MCP server status', priority: 60, argumentHint: '[tools]' },
|
|
410
|
-
{ name: 'mcp-config', desc: 'Manage MCP servers (interactive, or list / add / remove)', priority: 60, argumentHint: '[list] | add <name> <command|url> [args…] | remove <name>' },
|
|
411
|
-
{ name: 'statusline', desc: 'Configure which items appear in the status line', priority: 60 },
|
|
412
|
-
{ name: 'theme', desc: 'Switch the colour theme', priority: 60, argumentHint: `[${THEME_NAMES.join('|')}]` },
|
|
413
|
-
{ name: 'keybindings', aliases: ['keys'], desc: 'Remap a key to another key or to a slash command', priority: 55, argumentHint: '[list | add <key> <key|/command> | remove <key> | edit]' },
|
|
414
|
-
{ name: 'agents', aliases: ['subagents'], desc: 'List running subagents, and message, interrupt or close them', priority: 55, argumentHint: '[list | message <id> <text> | interrupt [id|all] | close <id>]' },
|
|
415
|
-
{ name: 'team', desc: 'Lead a team: watch and message the members, add them, and open a team from an earlier session', priority: 100, argumentHint: '[panel | create <name> | add <name> [model] | msg <name> <text> | list | delete]' },
|
|
416
|
-
{ name: 'files', aliases: ['tree'], desc: 'Browse the workspace as a tree; Enter inserts the path', priority: 60, argumentHint: '[path-filter]' },
|
|
417
|
-
{ name: 'checkpoints', aliases: ['cp'], desc: 'List per-file checkpoints and restore one file on its own', priority: 55, argumentHint: '[list | restore <n> | diff <n>]' },
|
|
418
|
-
{ name: 'save-history', desc: 'Keep the display-only transcript (notices, warnings, compaction, plan cards, reasoning) in the saved session', priority: 60, argumentHint: '[on|off|thinking|nothinking]' },
|
|
419
|
-
{ name: 'export-md', aliases: ['export'], desc: 'Export current session as a Markdown file', priority: 40, argumentHint: '[output-path]' },
|
|
420
|
-
{ name: 'import-session', aliases: ['import'], desc: 'Attach a Markdown file to the prompt so the AI reads it without a tool call', priority: 40, argumentHint: '<file.md>' },
|
|
421
|
-
{ name: 'copy', desc: 'Copy the last assistant message to the clipboard', priority: 40 },
|
|
422
|
-
{ name: 'set-system-prompt', aliases: ['system-prompt'], desc: 'Edit the system prompt, or load one of the model-family presets', priority: 60 },
|
|
423
|
-
{ name: 'personal', aliases: ['preferences'], desc: 'Edit personal preferences injected into every prompt (global or per-project)', priority: 60, argumentHint: '[global|project]' },
|
|
424
|
-
{ name: 'permissions', aliases: ['rules'], desc: 'Show or edit standing allow/ask/deny rules for tools', priority: 60, argumentHint: '[edit]' },
|
|
425
|
-
{ name: 'external', aliases: ['allow-external'], desc: 'Toggle access to paths outside the workspace (persisted)', priority: 60, argumentHint: '[on|off]' },
|
|
426
|
-
{ name: 'web', desc: 'Serve this session to a browser (token-protected; loopback by default)', priority: 60, argumentHint: '[bindIp] [port] | off' },
|
|
427
|
-
{ name: 'calm-mode', desc: 'Terse replies: stop the model narrating what it will do and why unless asked', priority: 60, argumentHint: '[on|off]' },
|
|
428
|
-
{ name: 'add-dir', desc: 'Add or list an additional workspace directory', priority: 60, argumentHint: '[list] | <path>' },
|
|
429
|
-
{ name: 'move', aliases: ['cd'], desc: 'Move current session to another directory (must exist)', priority: 60, argumentHint: '<path>' },
|
|
430
|
-
{ name: 'vim', aliases: ['nvim'], desc: 'Edit the composer in $EDITOR (vim by default); on save it comes back into the composer', priority: 60 },
|
|
431
|
-
{ name: 'reload', desc: 'Reload config and plugins without restart', priority: 60 },
|
|
432
|
-
{ name: 'reload-config', desc: 'Reload config.toml settings only', priority: 60 },
|
|
433
|
-
{ name: 'plugins', desc: 'Open the plugin manager (installed + available in the repo)', priority: 60, argumentHint: '[install <name> | remove <name> | reload]' },
|
|
434
|
-
{ name: 'skills', desc: 'Open the skill manager (installed + available in the repo)', priority: 60, argumentHint: '[install <name> | remove <name>]' },
|
|
435
|
-
{ name: 'import-skill', desc: 'Add a skill from a Markdown file, or install every skill in a GitHub repository (owner/repo)', cooldown: false },
|
|
436
|
-
{ name: 'hooks', desc: 'Show configured shell hooks, or test one', priority: 60, argumentHint: '[list | test <event>]' },
|
|
437
|
-
{ name: 'git', desc: 'Show repository status (branch, changes, remote)', priority: 62 },
|
|
438
|
-
{ name: 'commit', desc: 'Stage and commit with a message (or let the agent draft one)', priority: 62, argumentHint: '[message]' },
|
|
439
|
-
{ name: 'branch', desc: 'List, create, or switch git branches', priority: 62, argumentHint: '[list | <name> | -c <name>]' },
|
|
440
|
-
{ name: 'worktree', desc: 'List, create, or remove git worktrees for parallel work', priority: 60, argumentHint: '[list | new [name] [--branch] | add <dir> [branch] | remove <dir>]' },
|
|
441
|
-
{ name: 'pr', desc: 'Show the URL to open a pull request for the current branch', priority: 60, argumentHint: '[base]' },
|
|
442
|
-
{ name: 'add', aliases: ['stage'], desc: 'Stage changes (all by default, or given paths)', priority: 62, argumentHint: '[<path> ...]' },
|
|
443
|
-
{ name: 'diff', desc: 'Show uncommitted changes', priority: 62, argumentHint: '[--staged|--cached] [<path>]' },
|
|
444
|
-
{ name: 'review', desc: 'Have the agent review the uncommitted changes and report real problems', priority: 62, argumentHint: '[--staged|--cached] [<path>]' },
|
|
445
|
-
{ name: 'log', desc: 'Show recent commits', priority: 62, argumentHint: '[count] [<path>]' },
|
|
446
|
-
{ name: 'push', desc: 'Push the current branch (asks first)', priority: 62, argumentHint: '[branch] [-f]' },
|
|
447
|
-
{ name: 'stash', desc: 'Stash changes: list / push / pop', priority: 60, argumentHint: '[list | push [msg] | pop]' },
|
|
448
|
-
{ name: 'rebase', desc: 'Rebase the current branch onto another (asks first)', priority: 60, argumentHint: '<branch>' },
|
|
449
|
-
{ name: 'cache', desc: 'Toggle prompt caching for long stable prefixes (saves input tokens)', priority: 58, argumentHint: '[on|off]' },
|
|
450
|
-
{ name: 'logout', aliases: ['disconnect'], desc: 'Log out of a configured provider', priority: 40 },
|
|
451
|
-
{ name: 'feedback', aliases: ['bug'], desc: 'Open a prefilled GitHub issue (title + body)', priority: 60, argumentHint: '<title> | <body>' },
|
|
452
|
-
{ name: 'update', desc: 'Check for and install a newer version', priority: 40, argumentHint: '[-y]' },
|
|
453
|
-
{ name: 'auto-update', desc: 'Toggle automatic background updates (check at startup + every 30 min)', priority: 40, argumentHint: '[on|off]' },
|
|
454
|
-
{ name: 'auto-compact', aliases: ['autocompact'], desc: 'Auto context compaction: toggle, or set the trigger/keep ratios', priority: 40, argumentHint: '[on|off | threshold <n> | keep <n>]' },
|
|
455
|
-
{ name: 'lang', desc: 'Switch the interface language (zh / en)', priority: 60, argumentHint: '[zh|en]' },
|
|
456
|
-
{ name: 'version', desc: 'Show version information', priority: 20 },
|
|
457
|
-
{ name: 'exit', aliases: ['quit', 'q'], desc: 'Exit the application', priority: 20 },
|
|
458
|
-
].sort((a, b) => (b.priority || 0) - (a.priority || 0) || a.name.localeCompare(b.name));
|
|
357
|
+
// ---- which front end a command belongs to ----
|
|
358
|
+
//
|
|
359
|
+
// surface: 'tui' a terminal-only affordance (an editor, a keybinding file, the
|
|
360
|
+
// shimmer sweep). Pointless — and confusing — in a window.
|
|
361
|
+
// surface: 'gui' a window-only affordance.
|
|
362
|
+
// absent both, which is the overwhelming majority.
|
|
363
|
+
//
|
|
364
|
+
// A GUI reads this to decide what to list; the TUI ignores it and keeps offering everything.
|
|
365
|
+
export { COMMANDS, TUI_ONLY_COMMANDS, commandsForSurface } from './commands.js';
|
|
366
|
+
import { COMMANDS, commandsForSurface } from './commands.js';
|
|
459
367
|
|
|
460
368
|
/**
|
|
461
369
|
* The command list as the user sees it: names as typed, descriptions translated.
|
|
@@ -557,29 +465,6 @@ export const SWARM_MODE_INSTRUCTION =
|
|
|
557
465
|
+ ' subagents unprompted still applies everywhere else.\n'
|
|
558
466
|
+ '- If after exploring you conclude no subagent is needed, say why and stop.';
|
|
559
467
|
|
|
560
|
-
export const PLAN_MODE_INSTRUCTION =
|
|
561
|
-
'PLAN MODE is ON. You are in a read-only planning phase.\n'
|
|
562
|
-
+ '- The write tools (Write, Edit, Bash, ...) are NOT available. Investigate with\n'
|
|
563
|
-
+ ' the read-only tools you do have, then produce a PLAN.\n'
|
|
564
|
-
+ '- Do NOT try to make the changes. Your job this turn is the plan, not the code.\n'
|
|
565
|
-
+ '- End your reply with the plan wrapped in <|plan|> and </|plan|> tags, on their\n'
|
|
566
|
-
+ ' own lines. Everything between them is shown to the user verbatim and is what\n'
|
|
567
|
-
+ ' they approve. Only the LAST such block is used.\n'
|
|
568
|
-
+ '- Inside the block, use short Markdown: a heading per step, and bullets for the\n'
|
|
569
|
-
+ ' files to touch and why. Be concrete enough that the plan can be executed as\n'
|
|
570
|
-
+ ' written — name files, functions and commands.\n'
|
|
571
|
-
+ '- Keep any text OUTSIDE the tags to a one-line summary of what you found.\n'
|
|
572
|
-
+ '- Once the plan is approved the mode turns off and you get the write tools, so\n'
|
|
573
|
-
+ ' the plan must stand on its own.\n'
|
|
574
|
-
+ '\n'
|
|
575
|
-
+ 'Example shape:\n'
|
|
576
|
-
+ '<|plan|>\n'
|
|
577
|
-
+ '## Add the /personal command\n'
|
|
578
|
-
+ '- `src/config.js`: add readPersonalPrompt() merging global + project files.\n'
|
|
579
|
-
+ '- `src/tui.js`: register /personal, inject the text each turn.\n'
|
|
580
|
-
+ '## Verify\n'
|
|
581
|
-
+ '- Write a temp workspace, check both scopes merge in order.\n'
|
|
582
|
-
+ '</|plan|>';
|
|
583
468
|
|
|
584
469
|
// Sent back to the model once the user approves a plan. Plan mode is off by then,
|
|
585
470
|
// so it has the write tools; this frames the approved text as an instruction
|
|
@@ -657,7 +542,6 @@ export const TIPS = [
|
|
|
657
542
|
'/personal edits your standing preferences',
|
|
658
543
|
'/permissions shows allow/ask/deny rules for tools',
|
|
659
544
|
'/external toggles access outside the workspace',
|
|
660
|
-
'/web serves this session to a browser',
|
|
661
545
|
'/add-dir grants access to another directory',
|
|
662
546
|
'/reload re-reads config.toml without restarting',
|
|
663
547
|
'/skills install <name> pulls one from the repo',
|
|
@@ -1339,48 +1223,10 @@ export function composerTextIndexAt(layout, rowIdx, colInside) {
|
|
|
1339
1223
|
return Math.min(m.end, m.start + idx);
|
|
1340
1224
|
}
|
|
1341
1225
|
|
|
1342
|
-
// A Bash result is a FAILURE when the command exited non-zero or the spawn
|
|
1343
|
-
//
|
|
1344
|
-
//
|
|
1345
|
-
//
|
|
1346
|
-
// src/tools/*.js). Any result starting with one of these is a FAILED call:
|
|
1347
|
-
// "Error: old_string not found in …" (Edit)
|
|
1348
|
-
// "Error reading/writing <path>: …" (Read/Write/Edit)
|
|
1349
|
-
// "Cannot read: <path> appears to be …" (Read)
|
|
1350
|
-
// "Edit rejected: …" (Edit staleness / read guards)
|
|
1351
|
-
// "Command cannot be empty." (Bash)
|
|
1352
|
-
// resolvePath throws are surfaced verbatim as `e.message`, e.g.
|
|
1353
|
-
// "Path outside workspace: …" / "ENOENT: no such file or directory …".
|
|
1354
|
-
const FAIL_PREFIX = /^(Error\b|\[error:|Cannot read:|Edit rejected:|Command cannot be empty\b|Path outside workspace\b|ENOENT\b|EACCES\b|EPERM\b|EISDIR\b|ENOTDIR\b)/i;
|
|
1355
|
-
|
|
1356
|
-
export function isFailureResult(text, toolName) {
|
|
1357
|
-
const s = String(text == null ? '' : text);
|
|
1358
|
-
const trimmed = s.trim();
|
|
1359
|
-
if (FAIL_PREFIX.test(trimmed)) return true;
|
|
1360
|
-
// A non-zero Bash exit code marks the call as failed (red status bullet). The
|
|
1361
|
-
// `[exit code: N]` LINE itself is never shown to the user — it is bookkeeping
|
|
1362
|
-
// for the model only (see messageLines).
|
|
1363
|
-
const m = /\[exit code:\s*([^\]]+)\]/.exec(s);
|
|
1364
|
-
if (!m) return false;
|
|
1365
|
-
const v = m[1].trim();
|
|
1366
|
-
return v !== '0';
|
|
1367
|
-
}
|
|
1368
|
-
|
|
1369
|
-
// Extract the human-readable failure reason from a tool result, or '' when the
|
|
1370
|
-
// result should not render an extra "why it failed" line. The reason is shown
|
|
1371
|
-
// in red under the tool call for non-Bash tools (Edit / Read / Write / …); Bash
|
|
1372
|
-
// failures are already obvious from the command's own output, so they return ''.
|
|
1373
|
-
export function failureReason(text, toolName) {
|
|
1374
|
-
const name = String(toolName || '').toLowerCase();
|
|
1375
|
-
if (name === 'bash') return '';
|
|
1376
|
-
const s = String(text == null ? '' : text);
|
|
1377
|
-
const trimmed = s.trim();
|
|
1378
|
-
if (!FAIL_PREFIX.test(trimmed)) return '';
|
|
1379
|
-
// Collapse to a single line and drop the `[error: …]` wrapper.
|
|
1380
|
-
let line = trimmed.split('\n')[0].trim();
|
|
1381
|
-
line = line.replace(/^\[error:\s*/i, '').replace(/\]$/, '').trim();
|
|
1382
|
-
return line;
|
|
1383
|
-
}
|
|
1226
|
+
// A Bash result is a FAILURE when the command exited non-zero or the spawn itself errored.
|
|
1227
|
+
// The predicate lives in src/tool-status.js because the CLI puts the same answer on the event
|
|
1228
|
+
// stream for the desktop, and two copies of this list is how the window ended up showing a
|
|
1229
|
+
// refused edit with a green dot.
|
|
1384
1230
|
|
|
1385
1231
|
// (The tool line and the per-role colour live in src/tool-line.js.)
|
|
1386
1232
|
|
|
@@ -2432,7 +2278,6 @@ export function renderChatLines(state, w, viewport) {
|
|
|
2432
2278
|
}
|
|
2433
2279
|
const total = cursor;
|
|
2434
2280
|
state._chatTotal = total;
|
|
2435
|
-
state._chatTotal = total;
|
|
2436
2281
|
// Memo for the count-only caller (scrollChat). These metrics do NOT depend on
|
|
2437
2282
|
// `scroll`, only on the transcript and the layout, so they stay valid until one
|
|
2438
2283
|
// of those changes. scrollChat used to call the FULL renderer — with no viewport
|
|
@@ -2921,12 +2766,8 @@ export function refreshCost(state, cfg) {
|
|
|
2921
2766
|
// The currency the cost readouts use, from config.toml (`cost_currency`), the
|
|
2922
2767
|
// environment, or USD. Persisted by `/cost usd|cny`, so the switch survives a
|
|
2923
2768
|
// restart and the status row follows it.
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
if (fromEnv) return fromEnv;
|
|
2927
|
-
const raw = cfg && ((cfg.raw && cfg.raw.cost_currency) ?? cfg.costCurrency);
|
|
2928
|
-
return normalizeCurrency(raw) || 'USD';
|
|
2929
|
-
}
|
|
2769
|
+
// ONE IMPLEMENTATION, in fx.js: the window and the cost endpoint ask the same question.
|
|
2770
|
+
export { costCurrency };
|
|
2930
2771
|
|
|
2931
2772
|
// (Number, money and time formatting live in src/format.js.)
|
|
2932
2773
|
|
|
@@ -3623,7 +3464,6 @@ export function resolveHoverHit(state, hitboxes) {
|
|
|
3623
3464
|
export function refreshGitInfo(state, opts = {}) {
|
|
3624
3465
|
const cwd = state.cwd || state.workspace || '';
|
|
3625
3466
|
if (!cwd) return;
|
|
3626
|
-
if (!cwd) return;
|
|
3627
3467
|
const now = Date.now();
|
|
3628
3468
|
const force = opts.force === true;
|
|
3629
3469
|
// Mid-turn the agent is about to write more files, so a POLL would only produce a value that is
|
|
@@ -3654,34 +3494,6 @@ export function refreshGitInfo(state, opts = {}) {
|
|
|
3654
3494
|
if (typeof state._requestRender === 'function') state._requestRender();
|
|
3655
3495
|
});
|
|
3656
3496
|
}
|
|
3657
|
-
/**
|
|
3658
|
-
* Tokens per content type, and how many messages of each kind there are.
|
|
3659
|
-
*
|
|
3660
|
-
* Shared by `/context` (which prints the table) and by the status bar's bar (which draws
|
|
3661
|
-
* it), so the two can never disagree about what is being counted.
|
|
3662
|
-
*/
|
|
3663
|
-
export function contextBreakdown(session, cfg) {
|
|
3664
|
-
// `cfg` is optional because the render path reaches this through `state.cfg`, and a state
|
|
3665
|
-
// built directly (several tests do) has no `cfg` at all. An absent config must not take
|
|
3666
|
-
// the frame down; it only means the tool-definition count falls back to the full list.
|
|
3667
|
-
const conf = cfg || {};
|
|
3668
|
-
const byRole = { system: 0, user: 0, assistant: 0, tool: 0, other: 0 };
|
|
3669
|
-
const countByRole = { system: 0, user: 0, assistant: 0, tool: 0, other: 0 };
|
|
3670
|
-
for (const m of ((session && session.messages) || [])) {
|
|
3671
|
-
// Per-message estimator, memoised: `estimateMessagesTokens([m])` re-ran the whole message
|
|
3672
|
-
// loop for a single-element array, which on a long transcript made /context O(n²). The
|
|
3673
|
-
// memo means re-opening /context — or opening it after the bar already priced these
|
|
3674
|
-
// messages — is a WeakMap hit per message instead of a fresh walk of every tool body.
|
|
3675
|
-
const t = messageTokens(m, conf);
|
|
3676
|
-
const r = (m.role === 'system' || m.role === 'user' || m.role === 'assistant' || m.role === 'tool') ? m.role : 'other';
|
|
3677
|
-
byRole[r] += t;
|
|
3678
|
-
countByRole[r] += 1;
|
|
3679
|
-
}
|
|
3680
|
-
// Tool definitions ride every request (name + schema), priced here the same way
|
|
3681
|
-
// usedTokens() prices them.
|
|
3682
|
-
const toolCount = Array.isArray(conf.toolFilter) ? conf.toolFilter.length : (toolNames().length);
|
|
3683
|
-
return { byRole, countByRole, toolDefTokens: toolCount * 8, toolCount };
|
|
3684
|
-
}
|
|
3685
3497
|
|
|
3686
3498
|
/**
|
|
3687
3499
|
* The same breakdown in the shape the bar draws it, CACHED.
|
|
@@ -4466,7 +4278,6 @@ const queueH = takeover ? 0 : queuePanelHeight(state);
|
|
|
4466
4278
|
//
|
|
4467
4279
|
// It used to pass the transcript index here while the loop still walked the whole transcript, so the
|
|
4468
4280
|
// rail was drawn from the geometry of the FIRST `bodyH` rows of the conversation and every row actually
|
|
4469
|
-
// rail was drawn from the geometry of the FIRST `bodyH` rows of the conversation and every row actually
|
|
4470
4281
|
// on screen fell outside that range — the bar came out blank as soon as the transcript was scrolled off
|
|
4471
4282
|
// the top, i.e. in the normal case, and only appeared when the window happened to start at row 0.
|
|
4472
4283
|
if (sb && screenRow >= 0 && screenRow < bodyH) {
|
|
@@ -5643,19 +5454,15 @@ const queueH = takeover ? 0 : queuePanelHeight(state);
|
|
|
5643
5454
|
// AND the model must have prices (its own entry or the models.dev catalog). Either one
|
|
5644
5455
|
// missing would mean inventing the number, so it is omitted rather than shown as `0$`,
|
|
5645
5456
|
// which reads as "this was free".
|
|
5646
|
-
|
|
5647
|
-
//
|
|
5648
|
-
// can sit the number where the language wants it, and the plural only exists in English.
|
|
5457
|
+
// THE TALLIES COME FROM ONE FUNCTION, so the text a window shows and the text this row draws
|
|
5458
|
+
// cannot drift apart. It is the same sentence with the colour around it.
|
|
5649
5459
|
const countsRight = col(
|
|
5650
|
-
|
|
5651
|
-
|
|
5652
|
-
|
|
5653
|
-
:
|
|
5654
|
-
|
|
5655
|
-
|
|
5656
|
-
? tr('status.stepsOne', '{n} step', { n: state.steps })
|
|
5657
|
-
: tr('status.steps', '{n} steps', { n: state.steps }))
|
|
5658
|
-
+ ` | ${Math.round(state.tokRate)} tok/s`,
|
|
5460
|
+
statusTallyText({
|
|
5461
|
+
rounds: state.rounds || 0,
|
|
5462
|
+
steps: state.steps || 0,
|
|
5463
|
+
tokRate: state.tokRate || 0,
|
|
5464
|
+
cost: state._costText || '',
|
|
5465
|
+
}),
|
|
5659
5466
|
C.white,
|
|
5660
5467
|
);
|
|
5661
5468
|
const statusRight = countsRight;
|
|
@@ -6406,7 +6213,6 @@ export function makeState({ cfg, session, opts }) {
|
|
|
6406
6213
|
// only `(state, cols, rows)` and has no closure over startTUI's locals.
|
|
6407
6214
|
session: session || null,
|
|
6408
6215
|
provider: cfg.provider || '',
|
|
6409
|
-
provider: cfg.provider || '',
|
|
6410
6216
|
model: cfg.model || '',
|
|
6411
6217
|
// REDUCED MOTION and the sweep-edge shape are copied onto the STATE, not read
|
|
6412
6218
|
// from `cfg` at render time: `composeFrame(state, …)` only receives the state,
|
|
@@ -6532,8 +6338,13 @@ export function makeState({ cfg, session, opts }) {
|
|
|
6532
6338
|
mentionList: [],
|
|
6533
6339
|
mentionSel: 0,
|
|
6534
6340
|
mentionOffset: 0,
|
|
6535
|
-
|
|
6536
|
-
|
|
6341
|
+
// THE GOAL IS SESSION STATE, like `plan` and `focus` right below it. It used to start empty on
|
|
6342
|
+
// every launch, so a resumed session reported "No goal set" for an objective set minutes
|
|
6343
|
+
// earlier — and the turn loop stopped restarting against it. Read here, written by
|
|
6344
|
+
// persistState() at the end of a turn.
|
|
6345
|
+
objective: (session && session.objective) || '',
|
|
6346
|
+
goalPaused: !!(session && session.goalPaused),
|
|
6347
|
+
goalOwner: (session && session.goalOwner) || 'agent',
|
|
6537
6348
|
plan: !!(session && session.plan),
|
|
6538
6349
|
planPath: (session && session.planPath) || null,
|
|
6539
6350
|
focus: !!(session && session.focus),
|
|
@@ -6594,6 +6405,9 @@ export function makeState({ cfg, session, opts }) {
|
|
|
6594
6405
|
_costText: null, // the amount as printed, in the display currency
|
|
6595
6406
|
_costCurrency: 'USD',
|
|
6596
6407
|
_costRate: null, // the rate used, or null when the figure is USD
|
|
6408
|
+
// The last rate MEASURED, kept so it survives the end of the turn that produced it. The
|
|
6409
|
+
// live window is a second wide; see the timer that reads it.
|
|
6410
|
+
_lastTokRate: 0,
|
|
6597
6411
|
};
|
|
6598
6412
|
}
|
|
6599
6413
|
|
|
@@ -7145,7 +6959,9 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
7145
6959
|
if (key === 'calm_mode') cfg.calmMode = v;
|
|
7146
6960
|
if (key === 'title_display') cfg.titleDisplay = v;
|
|
7147
6961
|
if (key === 'auto_title') cfg.autoTitle = v;
|
|
7148
|
-
|
|
6962
|
+
// `swarm_mode` is deliberately absent: swarm is a per-session switch toggled with /swarm,
|
|
6963
|
+
// not a saved preference. A stale value in an old config.toml is ignored rather than
|
|
6964
|
+
// silently turning every future session into one that decomposes its work.
|
|
7149
6965
|
if (key === 'tool_allow_external_paths') cfg.allowExternal = v;
|
|
7150
6966
|
if (key === 'sampling' && !v) {
|
|
7151
6967
|
// Off means NONE of them is sent — not their defaults, which is what a provider rejecting them
|
|
@@ -8049,6 +7865,9 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
8049
7865
|
state.ctxMax = cfg.maxContextTokens || state.ctxMax;
|
|
8050
7866
|
state.tokRate = 0;
|
|
8051
7867
|
state._tokTimes = [];
|
|
7868
|
+
// The last measured rate belongs to the conversation that just ended, for the same
|
|
7869
|
+
// reason the spend does: a new session starts from zero.
|
|
7870
|
+
state._lastTokRate = 0;
|
|
8052
7871
|
// The spend belongs to the session that is ending, so a new session starts
|
|
8053
7872
|
// from zero. The session object is reused, so `usage` must be CLEARED here
|
|
8054
7873
|
// rather than just left out.
|
|
@@ -8141,6 +7960,14 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
8141
7960
|
state.rounds = session.rounds || 0;
|
|
8142
7961
|
state.steps = session.steps || 0;
|
|
8143
7962
|
state.lastTurnMs = session.lastTurnMs || 0;
|
|
7963
|
+
// THE GOAL COMES BACK WITH THE SESSION, like rounds and steps above. `/goal status`
|
|
7964
|
+
// reads `state.objective`, so a resume that left it empty answered "No goal set" for
|
|
7965
|
+
// an objective that was still the thing being worked towards.
|
|
7966
|
+
state.objective = String(session.objective || '');
|
|
7967
|
+
state.goalPaused = !!session.goalPaused;
|
|
7968
|
+
state.goalOwner = String(session.goalOwner || 'agent');
|
|
7969
|
+
// The todo list is session state too, and the panel is drawn from `state.todos`.
|
|
7970
|
+
state.todos = Array.isArray(session.todos) ? session.todos.slice() : [];
|
|
8144
7971
|
// The resumed session may live in another directory, and EVERY tool path
|
|
8145
7972
|
// resolves against it (`resolvePath` uses `ctx.cwd || ctx.workspace`,
|
|
8146
7973
|
// and the agent copies `cfg` into `ctx` each turn). Updating only
|
|
@@ -8197,21 +8024,18 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
8197
8024
|
}
|
|
8198
8025
|
case 'swarm': {
|
|
8199
8026
|
// Swarm mode: tell the model to decompose work across parallel subagents.
|
|
8027
|
+
//
|
|
8028
|
+
// A SESSION SETTING, NOT A SAVED PREFERENCE. It used to be written to config.toml, which
|
|
8029
|
+
// made "turn swarm on for this one task" a permanent default — the next session, started
|
|
8030
|
+
// for something else entirely, still ran in swarm mode. Plan and Focus have always been
|
|
8031
|
+
// session-scoped; this belongs with them.
|
|
8200
8032
|
const a = raw.toLowerCase();
|
|
8201
8033
|
let want;
|
|
8202
8034
|
if (a === 'on') want = true;
|
|
8203
8035
|
else if (a === 'off') want = false;
|
|
8204
8036
|
else want = !state.swarm;
|
|
8205
8037
|
state.swarm = want;
|
|
8206
|
-
// Plan / Focus / Swarm are one mutually exclusive group: turning one on
|
|
8207
|
-
// turns the other two off.
|
|
8208
8038
|
if (want) { state.plan = false; state.focus = false; }
|
|
8209
|
-
// A write that fails SILENTLY still shows the success message below, so the user believes the setting
|
|
8210
|
-
// stuck and it comes back wrong after a restart.
|
|
8211
|
-
try { setConfigString('swarm_mode', want ? 'true' : 'false'); } catch (e) {
|
|
8212
|
-
appErr(`Could not save this setting: ${e.message}. It applies to this session only.`);
|
|
8213
|
-
}
|
|
8214
|
-
cfg.raw.swarm_mode = want;
|
|
8215
8039
|
app(want
|
|
8216
8040
|
? uiText('Swarm mode ON - the model will decompose work across parallel subagents (AgentSwarm)')
|
|
8217
8041
|
: 'Swarm mode OFF');
|
|
@@ -8579,7 +8403,7 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
8579
8403
|
saveSession(session);
|
|
8580
8404
|
// Same formula as everywhere else: messages PLUS the tool schemas.
|
|
8581
8405
|
state.tokens = estimateMessagesTokens(session.messages, cfg) + (cfg.toolDefTokens || 0);
|
|
8582
|
-
|
|
8406
|
+
sessHost.noteCtxAfterShrink(state.tokens);
|
|
8583
8407
|
// Same rule as everywhere else: the percentage comes from the number the row prints, not from the
|
|
8584
8408
|
// estimate. Using `state.tokens` here made a compacted session show `696k/1M` beside 57%.
|
|
8585
8409
|
state.ctxPercent = usagePercent(state.ctxTokens, state.ctxMax || maxCtx);
|
|
@@ -8920,77 +8744,6 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
8920
8744
|
return;
|
|
8921
8745
|
}
|
|
8922
8746
|
|
|
8923
|
-
case 'web': {
|
|
8924
|
-
// Publish this session to the browser through the MACHINE-WIDE web UI.
|
|
8925
|
-
//
|
|
8926
|
-
// There is one daemon per machine, on the fixed port from config.toml, and
|
|
8927
|
-
// it is what the user opens: it lists every workspace and every session —
|
|
8928
|
-
// the running ones live, the finished ones read from disk. This command
|
|
8929
|
-
// brings up this session's own server and registers it there; if the daemon
|
|
8930
|
-
// is already up it is REUSED rather than restarted, which is the whole point
|
|
8931
|
-
// of a stable address and a stable token.
|
|
8932
|
-
const a = raw.trim();
|
|
8933
|
-
if (a.toLowerCase() === 'off' || a.toLowerCase() === 'stop') {
|
|
8934
|
-
app(h.stopWeb() ? uiText('Web UI stopped (this session is no longer listed).') : uiText('Web UI is not running.'));
|
|
8935
|
-
return;
|
|
8936
|
-
}
|
|
8937
|
-
if (!h.startWebGlobal) { appErr(uiText('Web UI is unavailable in this build.')); return; }
|
|
8938
|
-
// Optional "[bindIp] [port]" — the same shapes `--web` accepts. The old
|
|
8939
|
-
// code threw these away and always bound loopback, so `/web 0.0.0.0` looked
|
|
8940
|
-
// like it worked while nothing was reachable from the network.
|
|
8941
|
-
let bindArg, portArg;
|
|
8942
|
-
if (a) {
|
|
8943
|
-
const parts = a.split(/\s+/);
|
|
8944
|
-
if (/^\d+$/.test(parts[0])) portArg = Number(parts[0]);
|
|
8945
|
-
else bindArg = parts[0];
|
|
8946
|
-
if (parts[1] && /^\d+$/.test(parts[1])) portArg = Number(parts[1]);
|
|
8947
|
-
}
|
|
8948
|
-
say('Starting the web UI…');
|
|
8949
|
-
h.startWebGlobal(bindArg, portArg).then(({ srv, daemon, token }) => {
|
|
8950
|
-
if (!daemon) {
|
|
8951
|
-
// The daemon could not be reached or started. The session's own server
|
|
8952
|
-
// is still up, so report THAT rather than pretending /web failed.
|
|
8953
|
-
sayPanel([
|
|
8954
|
-
`Web UI (this session only): ${srv.url}`,
|
|
8955
|
-
'',
|
|
8956
|
-
uiText('The machine-wide daemon is unavailable, so this session is served'),
|
|
8957
|
-
'directly. Open the address above; the token is below.',
|
|
8958
|
-
'',
|
|
8959
|
-
` ${srv.token}`,
|
|
8960
|
-
].join('\n'));
|
|
8961
|
-
notice(`Web UI on ${srv.url} (daemon unavailable)`, 'error');
|
|
8962
|
-
return;
|
|
8963
|
-
}
|
|
8964
|
-
const lan = daemon.host && daemon.host !== '127.0.0.1' && daemon.host !== 'localhost';
|
|
8965
|
-
sayPanel([
|
|
8966
|
-
`Web UI: ${daemon.rootUrl}`,
|
|
8967
|
-
`Session: ${daemon.url}`,
|
|
8968
|
-
`Bind: ${daemon.host}:${daemon.port}${lan ? ' (reachable from the network)' : ' (this machine only)'}`,
|
|
8969
|
-
daemon.spawned ? 'Daemon: started (was not running)' : 'Daemon: reused (already running)',
|
|
8970
|
-
'',
|
|
8971
|
-
uiText('The root page lists every workspace and session — running ones live,'),
|
|
8972
|
-
'finished ones from disk. The token below is stored in config.toml, so',
|
|
8973
|
-
'it stays the same across restarts.',
|
|
8974
|
-
'',
|
|
8975
|
-
uiText('Access token (paste it into the login page):'),
|
|
8976
|
-
'',
|
|
8977
|
-
` ${token || srv.token}`,
|
|
8978
|
-
'',
|
|
8979
|
-
uiText('Anyone with this token can run commands as you. Stop this session with'),
|
|
8980
|
-
'/web off.',
|
|
8981
|
-
].join('\n'));
|
|
8982
|
-
notice(`Web UI at ${daemon.rootUrl}`);
|
|
8983
|
-
}).catch((e) => {
|
|
8984
|
-
appErr(`Could not start the web UI: ${e.message}`);
|
|
8985
|
-
});
|
|
8986
|
-
return;
|
|
8987
|
-
}
|
|
8988
|
-
|
|
8989
|
-
|
|
8990
|
-
|
|
8991
|
-
|
|
8992
|
-
|
|
8993
|
-
|
|
8994
8747
|
case 'calm-mode': {
|
|
8995
8748
|
// Terse-output mode: while ON, an instruction is injected with each request
|
|
8996
8749
|
// telling the model not to narrate what it is about to do or why, unless
|
|
@@ -9064,7 +8817,9 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
9064
8817
|
sendPrompt('Resume the active goal.');
|
|
9065
8818
|
return;
|
|
9066
8819
|
}
|
|
9067
|
-
|
|
8820
|
+
// BOTH SPELLINGS. `/goal cancel` is the command word; uiText('cancel') is what it reads as
|
|
8821
|
+
// in a translated interface. Comparing only against the translation meant an English `cancel` fell through to the catch-all below and SET THE GOAL to the literal word 'cancel'.
|
|
8822
|
+
if (a === 'cancel' || a === 'clear' || a === uiText('cancel')) { applyGoal('', false); app(uiText('Goal cancelled.')); return; }
|
|
9068
8823
|
if (a.startsWith('replace ')) { applyGoal(raw.slice(8).trim(), false); app(uiText('Goal replaced.')); return; }
|
|
9069
8824
|
applyGoal(raw, false);
|
|
9070
8825
|
app(`Goal set: ${raw}`);
|
|
@@ -9098,9 +8853,10 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
9098
8853
|
[tr('tui.help.groupEveryday', 'Everyday'), ['settings', 'set', 'model', 'provider', 'permission', 'yolo', 'lang']],
|
|
9099
8854
|
[tr('tui.help.groupSession', 'Session'), ['new', 'sessions', 'all-sessions', 'resume', 'save', 'export', 'compact', 'goal', 'init', 'jump']],
|
|
9100
8855
|
[tr('tui.help.groupContext', 'Context'), ['context', 'tokens', 'usage', 'cost', 'memory', 'personal', 'output-style']],
|
|
9101
|
-
[tr('tui.help.groupWork', 'Work'), ['plan', 'focus', 'swarm', 'team', 'btw', 'tasks']],
|
|
8856
|
+
[tr('tui.help.groupWork', 'Work'), ['plan', 'focus', 'swarm', 'goal', 'team', 'btw', 'tasks']],
|
|
9102
8857
|
[tr('tui.help.groupExtend', 'Extend'), ['skills', 'plugins', 'import-skill', 'plugin-manager']],
|
|
9103
8858
|
[tr('tui.help.groupDiagnostics', 'Diagnostics'), ['doctor', 'status', 'version', 'raw', 'reduced-motion', 'help']],
|
|
8859
|
+
[tr('tui.help.groupKeys', 'Keys'), ['keybindings']],
|
|
9104
8860
|
];
|
|
9105
8861
|
const byName = new Map(localizedCommands().map((c) => [c.name, c]));
|
|
9106
8862
|
const shown = new Set();
|
|
@@ -10188,7 +9944,7 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
10188
9944
|
//
|
|
10189
9945
|
// Plus the tool schemas, like every other writer: `/trim` counts messages, and the request also
|
|
10190
9946
|
// carries the tools, so leaving them out dropped the gauge by that much more than was freed.
|
|
10191
|
-
|
|
9947
|
+
sessHost.noteCtxAfterShrink(after + (cfg.toolDefTokens || 0));
|
|
10192
9948
|
state.ctxPercent = usagePercent(state.ctxTokens, state.ctxMax || cfg.maxContextTokens || 1);
|
|
10193
9949
|
if (session) {
|
|
10194
9950
|
try {
|
|
@@ -10479,8 +10235,6 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
10479
10235
|
return;
|
|
10480
10236
|
}
|
|
10481
10237
|
|
|
10482
|
-
case 'keybindings': {
|
|
10483
|
-
}
|
|
10484
10238
|
case 'keybindings': {
|
|
10485
10239
|
// Bindings live in ~/.hncode/keybindings.json; this is the editing entry point.
|
|
10486
10240
|
// A binding names a target the key dispatcher ALREADY understands (another key) or
|
|
@@ -11142,6 +10896,9 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
11142
10896
|
state.modelLabel = modelLabel(cfg) || cfg.model || '';
|
|
11143
10897
|
state.reasoning = !!cfg.reasoning;
|
|
11144
10898
|
cfg.effort = state.reasoning ? state.effort : '';
|
|
10899
|
+
// The level restored from config belongs to the model restored with it: if that
|
|
10900
|
+
// model does not offer it, drop it rather than sending it on the first request.
|
|
10901
|
+
dropUnsupportedEffort(state, cfg);
|
|
11145
10902
|
if (cfg.raw && cfg.raw.theme) { state.theme = cfg.raw.theme; setTheme(state.theme); }
|
|
11146
10903
|
const beforeMax = state.ctxMax;
|
|
11147
10904
|
state.ctxMax = cfg.maxContextTokens || state.ctxMax;
|
|
@@ -11170,6 +10927,8 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
11170
10927
|
state.modelLabel = modelLabel(cfg) || cfg.model || '';
|
|
11171
10928
|
state.reasoning = !!cfg.reasoning;
|
|
11172
10929
|
cfg.effort = state.reasoning ? state.effort : '';
|
|
10930
|
+
// A reload can change the model, so the level needs the same check a switch gets.
|
|
10931
|
+
dropUnsupportedEffort(state, cfg);
|
|
11173
10932
|
if (cfg.raw && cfg.raw.theme) { state.theme = cfg.raw.theme; setTheme(state.theme); }
|
|
11174
10933
|
const beforeMax = state.ctxMax;
|
|
11175
10934
|
state.ctxMax = cfg.maxContextTokens || state.ctxMax;
|
|
@@ -11579,6 +11338,23 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
|
|
|
11579
11338
|
: uiText('Prompt caching disabled — every request sends the full prompt as fresh input.'));
|
|
11580
11339
|
return;
|
|
11581
11340
|
}
|
|
11341
|
+
case 'time': {
|
|
11342
|
+
// THE CLOCK IN THE PROMPT.
|
|
11343
|
+
//
|
|
11344
|
+
// A model has no clock of its own, so the current local time rides along with the turn:
|
|
11345
|
+
// "yesterday", "this morning" and "run it at nine" are unanswerable without it. It also
|
|
11346
|
+
// carries the machine's zone, which is a fingerprint — a request from +08:00 says where its
|
|
11347
|
+
// owner is — so it can be turned off here and stays off.
|
|
11348
|
+
const a = String(raw || '').toLowerCase();
|
|
11349
|
+
const want = a === 'on' ? true : a === 'off' ? false : !(cfg.injectTime !== false);
|
|
11350
|
+
cfg.injectTime = want;
|
|
11351
|
+
try { setConfigString('inject_time', want ? 'true' : 'false'); } catch { /* best-effort persist */ }
|
|
11352
|
+
app(`${uiText('Time in prompt')}: ${want ? uiText('ON') : uiText('OFF')}`);
|
|
11353
|
+
sayPanel(want
|
|
11354
|
+
? 'Each turn carries the machine\'s local time and zone, so the model can answer "what time is it" and "run it tomorrow".'
|
|
11355
|
+
: 'No clock is sent. The model cannot tell the date or the hour, and nothing in the request names a time zone.');
|
|
11356
|
+
return;
|
|
11357
|
+
}
|
|
11582
11358
|
case 'worktree': {
|
|
11583
11359
|
const cwd = state.cwd || cfg.workspace || process.cwd();
|
|
11584
11360
|
if (!gitmod.isRepo(cwd)) { appErr(`Not a git repository: ${cwd}`); return; }
|
|
@@ -12057,6 +11833,27 @@ function commandPathsAreInside(state, cmd, cwd) {
|
|
|
12057
11833
|
}
|
|
12058
11834
|
return true;
|
|
12059
11835
|
}
|
|
11836
|
+
/**
|
|
11837
|
+
* Drop an effort level the CURRENT model does not offer.
|
|
11838
|
+
*
|
|
11839
|
+
* A level belongs to its model. After any path that changes the model — a switch, a config
|
|
11840
|
+
* reload — the level that was set may no longer exist, and sending it means a request the
|
|
11841
|
+
* endpoint rejects or silently ignores while the picker still shows the grade. Three copies of
|
|
11842
|
+
* this check would drift; one is called from each.
|
|
11843
|
+
*/
|
|
11844
|
+
function dropUnsupportedEffort(state, cfg) {
|
|
11845
|
+
const keep = String(state.effort || '');
|
|
11846
|
+
if (!keep || keep === 'off') return;
|
|
11847
|
+
let levels = null;
|
|
11848
|
+
try { levels = effortOptions(cfg, cfg.model); } catch { return; }
|
|
11849
|
+
// No declared levels means the model has no opinion, so the level stands.
|
|
11850
|
+
if (!Array.isArray(levels) || !levels.length) return;
|
|
11851
|
+
if (levels.includes(keep)) return;
|
|
11852
|
+
state.effort = 'off';
|
|
11853
|
+
state.reasoning = false;
|
|
11854
|
+
cfg.effort = '';
|
|
11855
|
+
}
|
|
11856
|
+
|
|
12060
11857
|
function applyModel(state, cfg, next) {
|
|
12061
11858
|
cfg.model = next.model; cfg.innerModel = next.innerModel; cfg.provider = next.provider;
|
|
12062
11859
|
cfg.baseUrl = next.baseUrl; cfg.endpoint = next.endpoint; cfg.apiKey = next.apiKey; cfg.protocol = next.protocol;
|
|
@@ -12077,6 +11874,9 @@ function applyModel(state, cfg, next) {
|
|
|
12077
11874
|
// Accumulating dollars per event instead would price every earlier request at
|
|
12078
11875
|
// whatever model happened to be active at the time — which is not what the
|
|
12079
11876
|
// session total means.
|
|
11877
|
+
// The level belongs to its model, so a switch can invalidate it (see dropUnsupportedEffort).
|
|
11878
|
+
dropUnsupportedEffort(state, cfg);
|
|
11879
|
+
|
|
12080
11880
|
refreshCost(state, cfg);
|
|
12081
11881
|
try { if (cfg.model) rememberModel(cfg.model); } catch {}
|
|
12082
11882
|
}
|
|
@@ -12608,10 +12408,21 @@ export function csiName(params, fin) {
|
|
|
12608
12408
|
//
|
|
12609
12409
|
// `viewArg` overrides `deps.view` for one call, which is how a caller holding both a terminal and
|
|
12610
12410
|
// a browser reaches the right one per turn.
|
|
12611
|
-
async function runTurn(deps, text, opts = {}, viewArg) {
|
|
12411
|
+
export async function runTurn(deps, text, opts = {}, viewArg) {
|
|
12612
12412
|
const { state, cfg, session, host, spawn } = deps;
|
|
12613
12413
|
const sessHost = host;
|
|
12414
|
+
// `dispatch` needs the terminal-side surface (notice, openPanel, …); the headless caller
|
|
12415
|
+
// passes its own, the TUI passes cmdHost. Falling back to `host` keeps a test that only
|
|
12416
|
+
// stubs SessionHost working.
|
|
12417
|
+
const cmdHost = deps.cmdHost || host;
|
|
12614
12418
|
const viewCur = viewArg || deps.view;
|
|
12419
|
+
// THE SESSION'S FOLDER, not the process's. `Agent` resolves every tool path against
|
|
12420
|
+
// `cfg.workspace`, and a server runs many conversations from one config object — so without
|
|
12421
|
+
// this the turn read and wrote in the directory the server was started from.
|
|
12422
|
+
if (session && session.workspace) {
|
|
12423
|
+
cfg.workspace = session.workspace;
|
|
12424
|
+
if (state) state.workspace = session.workspace;
|
|
12425
|
+
}
|
|
12615
12426
|
// Drop any compaction row left dangling by an interrupted turn so the next
|
|
12616
12427
|
// auto-compaction starts clean (no ghost 'running' row that blinks with nothing
|
|
12617
12428
|
// behind it). The live reference is dropped too.
|
|
@@ -12646,6 +12457,18 @@ async function runTurn(deps, text, opts = {}, viewArg) {
|
|
|
12646
12457
|
const needsTitle = !!session && cfg.autoTitle !== false
|
|
12647
12458
|
&& !session.title && state.titleAttempts < TITLE_ATTEMPT_LIMIT;
|
|
12648
12459
|
state.titleAttempts++;
|
|
12460
|
+
// AUTOMATIC NAMING IS OFF, so nothing else will ever name this session. The user still
|
|
12461
|
+
// needs to recognise it in a list, and the first thing they typed is the only description
|
|
12462
|
+
// that exists — truncated, one line, at the same 20 characters the desktop uses so the two
|
|
12463
|
+
// front ends show the same name for the same session.
|
|
12464
|
+
if (session && cfg.autoTitle === false && !session.title) {
|
|
12465
|
+
const fallback = sess.titleFromPrompt(text);
|
|
12466
|
+
if (fallback) {
|
|
12467
|
+
session.title = fallback;
|
|
12468
|
+
try { sess.saveSession(session); } catch { /* cosmetic */ }
|
|
12469
|
+
writeWindowTitle(session, process.stdout);
|
|
12470
|
+
}
|
|
12471
|
+
}
|
|
12649
12472
|
state.running = true;
|
|
12650
12473
|
// Pick the Working… wording ONCE for this turn, so it does not change while
|
|
12651
12474
|
// the gradient loops. The next turn picks a new one.
|
|
@@ -12838,6 +12661,38 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
12838
12661
|
else if (isSkill && !argsText) { /* body-only activation: nothing for the user turn */ }
|
|
12839
12662
|
else messages.push({ role: 'user', content: opts.modelText != null ? opts.modelText : (argsText || text) });
|
|
12840
12663
|
|
|
12664
|
+
// THE CLOCK, AS PART OF THE REQUEST AND NOT OF THE CONVERSATION.
|
|
12665
|
+
//
|
|
12666
|
+
// A model has no clock of its own: "yesterday", "this morning" and "run it at nine" are all
|
|
12667
|
+
// unanswerable without one, so the current local time rides along with the turn. It is a
|
|
12668
|
+
// SYSTEM message here, which is the difference between a note about the turn and something
|
|
12669
|
+
// the person said — as a user message it was drawn in the transcript as the person's words and
|
|
12670
|
+
// the model quoted it back.
|
|
12671
|
+
//
|
|
12672
|
+
// It is added AFTER the history loop, which drops system messages: the clock describes THIS
|
|
12673
|
+
// request, not the conversation so far. And it can be turned off — the stamp carries the
|
|
12674
|
+
// machine's zone, which is a fingerprint as well as a convenience.
|
|
12675
|
+
if (cfg.injectTime !== false) {
|
|
12676
|
+
const { timeStamp } = await import('./agent.js');
|
|
12677
|
+
// APPENDED TO THE USER'S OWN MESSAGE, in the tagged form harnesses use for environment
|
|
12678
|
+
// facts. A system message landing between the user's line and the request is an unusual
|
|
12679
|
+
// shape — providers put system content at the head — so the model read it as a fresh
|
|
12680
|
+
// instruction and answered it. It is also where the clock belongs: it describes the
|
|
12681
|
+
// moment that line was sent.
|
|
12682
|
+
//
|
|
12683
|
+
// It is NOT marked `_timestamp`, because it is no longer a message of its own: the text
|
|
12684
|
+
// is part of what the person sent, and stripping it would change their own line.
|
|
12685
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
12686
|
+
if (messages[i] && messages[i].role === 'user') {
|
|
12687
|
+
messages[i] = {
|
|
12688
|
+
...messages[i],
|
|
12689
|
+
content: `${messages[i].content}\n\n<env>Current time: ${timeStamp()}</env>`,
|
|
12690
|
+
};
|
|
12691
|
+
break;
|
|
12692
|
+
}
|
|
12693
|
+
}
|
|
12694
|
+
}
|
|
12695
|
+
|
|
12841
12696
|
// What the TEAM has said to the lead since the last turn.
|
|
12842
12697
|
//
|
|
12843
12698
|
// The lead is this session, and its inbox is the only channel an agent has for reaching
|
|
@@ -12886,6 +12741,28 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
12886
12741
|
session.steps = state.steps || session.steps;
|
|
12887
12742
|
session.todos = state.todos || session.todos;
|
|
12888
12743
|
session.mode = state.mode || session.mode;
|
|
12744
|
+
// THE GOAL IS TURN-SPANNING STATE, saved at the same cadence: the agent (or the user) can
|
|
12745
|
+
// set or change it mid-turn, and a crash between turns must not lose the objective the
|
|
12746
|
+
// work was organised around.
|
|
12747
|
+
session.objective = String(state.objective || '');
|
|
12748
|
+
session.goalPaused = !!state.goalPaused;
|
|
12749
|
+
session.goalOwner = String(state.goalOwner || 'agent');
|
|
12750
|
+
// WHERE THE CONTEXT WENT TRAVELS WITH THE SESSION. `/context` computed the breakdown on
|
|
12751
|
+
// demand for the terminal and never wrote it down, so a conversation reopened later — in the
|
|
12752
|
+
// window, or by another /context after a restart — had the total and nothing behind it. It
|
|
12753
|
+
// is the same bucketing the command prints, from the same function.
|
|
12754
|
+
try {
|
|
12755
|
+
// THE SAME PRICING THE STATUS BAR USES, including the assembled system prompt: it is
|
|
12756
|
+
// not a session message (see contextSegments), so a breakdown built from
|
|
12757
|
+
// `session.messages` alone reported the bucket that costs the most as zero.
|
|
12758
|
+
const sys = typeof state.turnSystemPrompt === 'string' ? state.turnSystemPrompt : '';
|
|
12759
|
+
const priced = sys ? [{ role: 'system', content: sys }, ...session.messages] : session.messages;
|
|
12760
|
+
const b = contextBreakdown({ messages: priced }, cfg);
|
|
12761
|
+
session.ctxBreakdown = {
|
|
12762
|
+
byRole: b.byRole, countByRole: b.countByRole,
|
|
12763
|
+
toolDefTokens: b.toolDefTokens, toolCount: b.toolCount,
|
|
12764
|
+
};
|
|
12765
|
+
} catch { /* a breakdown is a nicety; the save must land */ }
|
|
12889
12766
|
// `saveSessionSoon`: this runs at every STEP boundary, which makes it the hottest save in the program. The
|
|
12890
12767
|
// synchronous version spent 38ms of `JSON.stringify` plus a 1.3 MB write on a session that size — a stall the user
|
|
12891
12768
|
// sees as the interface freezing between a tool finishing and the next thing appearing, and it is paid again at
|
|
@@ -12931,6 +12808,10 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
12931
12808
|
|
|
12932
12809
|
// Approval callback: called before every tool execution
|
|
12933
12810
|
const onApproval = async (toolName, args) => {
|
|
12811
|
+
// A CALLER WITH ITS OWN FRONT END ANSWERS FIRST. `deps.onApproval` is how a resident server
|
|
12812
|
+
// puts the question to its window; without it the promise below waits on a keypress that
|
|
12813
|
+
// will never come and the whole turn stops there.
|
|
12814
|
+
if (typeof deps.onApproval === 'function') return await deps.onApproval(toolName, args);
|
|
12934
12815
|
// Read the mode LIVE: /permission, /yolo and /auto can change while the
|
|
12935
12816
|
// turn runs, and the decision must follow the CURRENT setting.
|
|
12936
12817
|
const cur = state.mode || 'ask';
|
|
@@ -12949,106 +12830,16 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
12949
12830
|
|
|
12950
12831
|
|
|
12951
12832
|
|
|
12952
|
-
// Standing rules
|
|
12953
|
-
//
|
|
12954
|
-
|
|
12955
|
-
|
|
12956
|
-
|
|
12957
|
-
if (
|
|
12833
|
+
// Standing rules, session grants, the safe-tool list and the three modes are ONE decision, in
|
|
12834
|
+
// permission-gate.js: the headless run asks the same question and must get the same answer.
|
|
12835
|
+
const verdict = decideApproval({
|
|
12836
|
+
mode: cur, toolName, args, rules: cfg.permissions, sessionApprovals: session.sessionApprovals,
|
|
12837
|
+
});
|
|
12838
|
+
if (verdict === 'deny') {
|
|
12958
12839
|
viewCur.err(`${toolName} is blocked by a permission rule (deny).`);
|
|
12959
12840
|
return false;
|
|
12960
12841
|
}
|
|
12961
|
-
|
|
12962
|
-
// rule — a rule is written for the command the user had in mind, and a line
|
|
12963
|
-
// can carry a second command the rule never described. `ruleMatches` splits
|
|
12964
|
-
// segments for the same reason; this is the second half of that guard, for
|
|
12965
|
-
// commands where no rule matched at all.
|
|
12966
|
-
const destructive = toolName === 'Bash'
|
|
12967
|
-
&& isDestructiveCommand(String((args && (args.command || args.cmd)) || ''));
|
|
12968
|
-
if (rule === 'allow' && !destructive) return true;
|
|
12969
|
-
// `ask` falls through to the prompt below, skipping the mode shortcuts.
|
|
12970
|
-
|
|
12971
|
-
// AUTO MODE ANSWERS HERE, and it answers everything.
|
|
12972
|
-
//
|
|
12973
|
-
// The mode means "nothing asks": the user has already said they do not want to be interrupted
|
|
12974
|
-
// for this session. So nothing below may send them a prompt — not a destructive-looking
|
|
12975
|
-
// command, not a heuristic that misfired. Getting this wrong is worse than the risk it guards
|
|
12976
|
-
// against, because a mode that claims to ask nothing and then asks anyway teaches the user to
|
|
12977
|
-
// hold down Enter, which destroys the value of every prompt that follows.
|
|
12978
|
-
//
|
|
12979
|
-
// `deny` above is checked BEFORE this and still wins, which is the one answer that is meant to
|
|
12980
|
-
// hold regardless of mode — the user wrote that rule down deliberately.
|
|
12981
|
-
//
|
|
12982
|
-
// An explicit `ask` rule is checked just above and skips this, because a rule naming a command
|
|
12983
|
-
// to ask about is also deliberate, and it outranks a mode chosen in a menu.
|
|
12984
|
-
if (rule !== 'ask' && cur === 'auto') return true;
|
|
12985
|
-
// Session approvals (Ctrl+A on a prompt) come AFTER the configured rules and BEFORE the mode
|
|
12986
|
-
// shortcuts:
|
|
12987
|
-
// * after, so a `deny` or an explicit `ask` rule still wins — a transient grant must not
|
|
12988
|
-
// override a decision the user wrote down;
|
|
12989
|
-
// * before, so an approval covers the modes that would otherwise ask again.
|
|
12990
|
-
//
|
|
12991
|
-
// `destructive` is passed in because the approval is keyed on it: approving one `rm -rf build`
|
|
12992
|
-
// must not silently cover every later command that looks similar.
|
|
12993
|
-
if (rule !== 'ask' && isApprovedForSession(session.sessionApprovals, toolName, args, destructive)) {
|
|
12994
|
-
return true;
|
|
12995
|
-
}
|
|
12996
|
-
// Read-only tools never need permission in any mode. AskUserQuestion is on
|
|
12997
|
-
// this list because ASKING the user is not a side effect — gating it behind
|
|
12998
|
-
// an approval prompt would mean answering two prompts to ask one question.
|
|
12999
|
-
// (In auto mode the TOOL refuses itself before any UI; see ctx.permissionMode.)
|
|
13000
|
-
// Tools that act ONLY inside the session: the roster, the mailbox, the task list, the memories.
|
|
13001
|
-
// `isInsideWorkspace` answers `false` for any tool it does not know, so without this they all asked for
|
|
13002
|
-
// approval in yolo — the one mode whose point is not asking.
|
|
13003
|
-
// A PLUGIN'S TOOL ANSWERS FOR ITSELF.
|
|
13004
|
-
//
|
|
13005
|
-
// The list below covers the tools this program ships. A plugin's tools cannot be added to it from outside,
|
|
13006
|
-
// and `isInsideWorkspace` does not know them — so every one of them asked for approval whatever it did. A
|
|
13007
|
-
// spec declaring `autoApprove: true` now says so itself, which is the only place that knows whether the
|
|
13008
|
-
// tool touches anything.
|
|
13009
|
-
if (rule !== 'ask') {
|
|
13010
|
-
const own = getTool(toolName);
|
|
13011
|
-
if (own && own.autoApprove === true) return true;
|
|
13012
|
-
}
|
|
13013
|
-
const safeTools = ['Read', 'Grep', 'Glob', 'FetchURL', 'WebSearch', 'TaskOutput', 'TaskList', 'TaskStop', 'TaskWait', 'TodoList', 'Goal', 'ActivateSkill', 'PTC', 'FileLines', 'AgentList', 'AgentMessage', 'AgentInterrupt', 'AgentClose', 'TaskInput', 'SendMessage', 'TeamTaskCreate', 'TeamTaskUpdate', 'TeamTaskList', 'ListTeammates', 'Memory', 'AskUserQuestion'];
|
|
13014
|
-
if (rule !== 'ask' && safeTools.includes(toolName)) return true;
|
|
13015
|
-
// A read-only SHELL COMMAND (ls/git status/rg/cat …) is as safe as a
|
|
13016
|
-
// read-only TOOL, so it runs without a prompt in Ask mode too — the user
|
|
13017
|
-
// has no decision to make about `git log`. Only in `ask`; an explicit
|
|
13018
|
-
// `ask` rule above still wins, and YOLO/AUTO never reach here anyway.
|
|
13019
|
-
if (cur === 'ask' && rule !== 'ask' && toolName === 'Bash') {
|
|
13020
|
-
const c = String((args && (args.command || args.cmd)) || '');
|
|
13021
|
-
if (isReadOnlyCommand(c) && !isDestructiveCommand(c)) return true;
|
|
13022
|
-
}
|
|
13023
|
-
|
|
13024
|
-
|
|
13025
|
-
// ASK: an ordinary action runs, anything with a consequence asks.
|
|
13026
|
-
//
|
|
13027
|
-
// This is the only mode that gates FILE work, which is the point of it — the other two exist for people who
|
|
13028
|
-
// have decided not to be asked.
|
|
13029
|
-
if (cur === 'ask' && rule !== 'ask') {
|
|
13030
|
-
// A read-only shell command is as safe as a read-only tool: there is no decision to make about `git log`.
|
|
13031
|
-
if (toolName === 'Bash') {
|
|
13032
|
-
const c = String((args && (args.command || args.cmd)) || '');
|
|
13033
|
-
if (isReadOnlyCommand(c) && !isDestructiveCommand(c)) return true;
|
|
13034
|
-
}
|
|
13035
|
-
}
|
|
13036
|
-
|
|
13037
|
-
// YOLO: routine work runs. FILES ARE NOT A REASON TO ASK.
|
|
13038
|
-
//
|
|
13039
|
-
// A user in yolo has said they do not want to confirm edits, and a path outside the workspace is still just a
|
|
13040
|
-
// path. What still asks is DESTRUCTION — a command that deletes, rewrites history or kills a process — because
|
|
13041
|
-
// that is the one class of action nobody means to authorise wholesale.
|
|
13042
|
-
if (cur === 'yolo' && rule !== 'ask') {
|
|
13043
|
-
if (toolName === 'Bash') {
|
|
13044
|
-
const cmd = String((args && (args.command || args.cmd)) || '');
|
|
13045
|
-
if (!isDestructiveCommand(cmd)) return true;
|
|
13046
|
-
} else {
|
|
13047
|
-
// Every non-shell tool: no path test. `isInsideWorkspace` was the thing asking about `/goal` and about a
|
|
13048
|
-
// Read elsewhere, neither of which is a decision.
|
|
13049
|
-
return true;
|
|
13050
|
-
}
|
|
13051
|
-
}
|
|
12842
|
+
if (verdict === 'allow') return true;
|
|
13052
12843
|
return new Promise((resolve) => {
|
|
13053
12844
|
let desc = '';
|
|
13054
12845
|
if (args && typeof args === 'object') {
|
|
@@ -13080,7 +12871,11 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
13080
12871
|
// AskUserQuestion bridge: the tool calls ctx.askQuestion(questions, ctx) and
|
|
13081
12872
|
// awaits the answers. Same promise-handshake the approval prompt uses, so the
|
|
13082
12873
|
// agent simply blocks while the user reads and chooses.
|
|
13083
|
-
cfg.askQuestion = (questions, ctx) =>
|
|
12874
|
+
cfg.askQuestion = (questions, ctx) => {
|
|
12875
|
+
// A CALLER WITH ITS OWN FRONT END ANSWERS. Without this a question blocks on a keypress
|
|
12876
|
+
// that a headless caller can never deliver, and the turn waits out its timeout.
|
|
12877
|
+
if (typeof deps.askQuestion === 'function') return deps.askQuestion(questions, ctx);
|
|
12878
|
+
return new Promise((resolve) => {
|
|
13084
12879
|
state.question = {
|
|
13085
12880
|
items: questions,
|
|
13086
12881
|
index: 0,
|
|
@@ -13122,7 +12917,8 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
13122
12917
|
sig.addEventListener('abort', onAbort, { once: true });
|
|
13123
12918
|
}
|
|
13124
12919
|
viewCur.render();
|
|
13125
|
-
|
|
12920
|
+
});
|
|
12921
|
+
};
|
|
13126
12922
|
// Open a file-history turn BEFORE the agent can write anything (file-history.js):
|
|
13127
12923
|
// the first write to a file in this turn snapshots its pre-turn content, which
|
|
13128
12924
|
// is exactly what /undo restores. Recorded even when nothing is written, so the
|
|
@@ -13155,6 +12951,11 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
13155
12951
|
// change) takes effect on the next message without restarting.
|
|
13156
12952
|
hookConfig: loadHooks(cfg.workspace).hooks,
|
|
13157
12953
|
onEvent: (e) => {
|
|
12954
|
+
// TELL THE HOST FIRST. `sessHost.onEvent` is the seam a non-terminal front end
|
|
12955
|
+
// subscribes through, and nothing called it: this loop drove the view and stopped
|
|
12956
|
+
// there, so a resident server received no events at all — a turn that ran to
|
|
12957
|
+
// completion reported only `done`, and the window showed an unanswered request.
|
|
12958
|
+
try { sessHost.onEvent(e); } catch { /* a subscriber must not break the turn */ }
|
|
13158
12959
|
// Everything the MODEL streams counts toward the tok/s meter: reasoning
|
|
13159
12960
|
// chunks carry `text` just like answer chunks do.
|
|
13160
12961
|
//
|
|
@@ -13231,8 +13032,13 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
13231
13032
|
return;
|
|
13232
13033
|
}
|
|
13233
13034
|
if (e.type === 'compacted') {
|
|
13234
|
-
|
|
13235
|
-
|
|
13035
|
+
// THE FIGURE AFTER COMPACTION IS THE TRUTH, whoever computed it. This used to skip it
|
|
13036
|
+
// whenever a provider report had ever landed — so the gauge kept showing the size the
|
|
13037
|
+
// history HAD before it was summarised, and on a session that compacts repeatedly it
|
|
13038
|
+
// sat on one stale number for as long as the conversation continued. The agent has
|
|
13039
|
+
// already dropped its own reported figure at this point (it describes the request that
|
|
13040
|
+
// was just replaced), so both sides restart from the same measurement.
|
|
13041
|
+
sessHost.noteCtxAfterShrink(e.after);
|
|
13236
13042
|
// Compaction is over, so the Working row goes back to a rotating phrase.
|
|
13237
13043
|
//
|
|
13238
13044
|
// RE-ROLLED, not restored: an automatic compaction happens MID-TURN — the agent hit
|
|
@@ -13506,9 +13312,7 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
13506
13312
|
const entry = [...state.chat].reverse().find((m) => m.role === 'tool' && m.pending && m.id === e.id)
|
|
13507
13313
|
|| [...state.chat].reverse().find((m) => m.role === 'tool' && m.pending);
|
|
13508
13314
|
if (entry) {
|
|
13509
|
-
// Bounded to a TAIL. This string is mirrored into the hub row and
|
|
13510
13315
|
// shipped over SSE on every patch, so leaving it unbounded grew the
|
|
13511
|
-
// TUI's row, the hub's row and the browser's copy together, once per
|
|
13512
13316
|
// chunk. Only the tail is ever displayed.
|
|
13513
13317
|
entry.liveOutput = tailChars(
|
|
13514
13318
|
(entry.liveOutput || '') + e.chunk,
|
|
@@ -13724,6 +13528,11 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
13724
13528
|
// without a row the transcript quietly looks like output went missing, and
|
|
13725
13529
|
// the user has no way to know the text is still readable.
|
|
13726
13530
|
viewCur.addChat({ role: 'system', text: `Trimmed ${e.elided} old tool result(s) to free context (${fmtTokens(e.before)} → ${fmtTokens(e.after)}); the removed text is saved on disk. You can modify or disable this feature by using "/auto-trim"` });
|
|
13531
|
+
// THE GAUGE FOLLOWS THE TRIM. This event carries the size AFTER the pass, and the
|
|
13532
|
+
// history it describes no longer exists in its old form — the same reason compaction
|
|
13533
|
+
// resets. Without this the row kept the pre-trim number until the next reply, so a
|
|
13534
|
+
// trim that freed 200k looked like it freed nothing.
|
|
13535
|
+
sessHost.noteCtxAfterShrink(e.after);
|
|
13727
13536
|
}
|
|
13728
13537
|
else if (e.type === 'todos') {
|
|
13729
13538
|
// A FINISHED list is dropped outright, not stored and hidden.
|
|
@@ -13937,7 +13746,19 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
13937
13746
|
// `session.messages` now holds the full request, system prompt included, so the bar
|
|
13938
13747
|
// reads the real text from here on and the turn-scoped copy must not be counted too.
|
|
13939
13748
|
state.turnSystemPrompt = null;
|
|
13940
|
-
|
|
13749
|
+
// THE CLOCK IS NOT PART OF THE CONVERSATION. It is appended to the user's message on the
|
|
13750
|
+
// way out; saving the array as it stood kept it, so every later turn replayed a time that
|
|
13751
|
+
// had already passed and the transcript showed a clock nobody typed.
|
|
13752
|
+
{
|
|
13753
|
+
const { stripEnvBlock } = await import('./agent.js');
|
|
13754
|
+
session.messages = messages
|
|
13755
|
+
// THE PROMPT IS REBUILT EVERY TURN, so storing it would keep a stale copy of the
|
|
13756
|
+
// instructions — and a tool definition — in the middle of the transcript.
|
|
13757
|
+
.filter((m) => m && m.role !== 'system' && !m._timestamp)
|
|
13758
|
+
.map((m) => (m && m.role === 'user' && typeof m.content === 'string'
|
|
13759
|
+
? { ...m, content: stripEnvBlock(m.content) }
|
|
13760
|
+
: m));
|
|
13761
|
+
}
|
|
13941
13762
|
session.rounds = state.rounds;
|
|
13942
13763
|
session.steps = state.steps;
|
|
13943
13764
|
// THE GAUGE TRAVELS WITH THE MESSAGES.
|
|
@@ -13956,6 +13777,15 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
|
|
|
13956
13777
|
// The todo list is part of the session's visible state: persist it here
|
|
13957
13778
|
// too, so resuming (or `hncode -c`) brings the panel back.
|
|
13958
13779
|
session.todos = state.todos || [];
|
|
13780
|
+
// THE GOAL TRAVELS WITH THE SESSION TOO.
|
|
13781
|
+
//
|
|
13782
|
+
// It lives only in `state.objective`, which dies with the process: a resumed session reported
|
|
13783
|
+
// "No goal set" for an objective the user (or the agent) had set minutes earlier, and the
|
|
13784
|
+
// turn loop stopped restarting against it. Written here, next to the rest of the visible
|
|
13785
|
+
// state, and read back on resume.
|
|
13786
|
+
session.objective = String(state.objective || '');
|
|
13787
|
+
session.goalPaused = !!state.goalPaused;
|
|
13788
|
+
session.goalOwner = String(state.goalOwner || 'agent');
|
|
13959
13789
|
// Focus is one turn: the turn it was set for has now ended, so it goes off. Done
|
|
13960
13790
|
// HERE, before the save below, so `session.focus` is written false and resuming
|
|
13961
13791
|
// the session does not bring the narrowed toolset back. `focusAtTurnStart` (not
|
|
@@ -14207,8 +14037,22 @@ export async function startTUI(opts) {
|
|
|
14207
14037
|
if (h.length > 240) h.splice(0, h.length - 240);
|
|
14208
14038
|
}
|
|
14209
14039
|
}
|
|
14040
|
+
/**
|
|
14041
|
+
* The history just got SHORTER, so any provider report describes a request that no longer
|
|
14042
|
+
* exists.
|
|
14043
|
+
*
|
|
14044
|
+
* `setCtxTokens` deliberately lets a report outrank every estimate — right for a growing
|
|
14045
|
+
* request, wrong here: after a compaction or a trim the old figure was kept and the gauge sat
|
|
14046
|
+
* on the pre-compaction size for the rest of the session. That is the "stuck number" people
|
|
14047
|
+
* report: it looks frozen because the one value it is allowed to show belongs to the past.
|
|
14048
|
+
*/
|
|
14049
|
+
function noteCtxAfterShrink(tokens) {
|
|
14050
|
+
state.ctxReportedOnce = false;
|
|
14051
|
+
state.ctxSource = 'estimate';
|
|
14052
|
+
if (session) session.ctxReportedOnce = false;
|
|
14053
|
+
setCtxTokens(Number(tokens) || 0, null, { fromEstimate: true });
|
|
14054
|
+
}
|
|
14210
14055
|
|
|
14211
|
-
|
|
14212
14056
|
// Set when the config has no model, so the interface can say so without blocking startup.
|
|
14213
14057
|
let modelMissing = false;
|
|
14214
14058
|
|
|
@@ -14243,6 +14087,8 @@ export async function startTUI(opts) {
|
|
|
14243
14087
|
state._ensureVoice = ensureVoice;
|
|
14244
14088
|
|
|
14245
14089
|
cfg.effort = state.reasoning ? state.effort : '';
|
|
14090
|
+
// A reload can change the model, so the level needs the same check a switch gets.
|
|
14091
|
+
dropUnsupportedEffort(state, cfg);
|
|
14246
14092
|
// Price the session's restored tokens against the model it is about to use, so
|
|
14247
14093
|
// /cost and the status badge are right before the first new request.
|
|
14248
14094
|
refreshCost(state, cfg);
|
|
@@ -14324,151 +14170,6 @@ export async function startTUI(opts) {
|
|
|
14324
14170
|
const stdin = process.stdin;
|
|
14325
14171
|
const stdout = process.stdout;
|
|
14326
14172
|
|
|
14327
|
-
// ---- web UI bridge (/web) --------------------------------------------------
|
|
14328
|
-
// `web` is null until the user runs /web. `hub` is created then too, so a
|
|
14329
|
-
// session that never opens the UI pays for none of this. The hub is the shared
|
|
14330
|
-
// state; syncWeb pushes the transcript into it and pushes the session status,
|
|
14331
|
-
// and `webActions` wires the browser's requests to the SAME functions the
|
|
14332
|
-
// keyboard calls — that is what makes the two front-ends behave identically.
|
|
14333
|
-
let web = null;
|
|
14334
|
-
let hub = null;
|
|
14335
|
-
let webSyncQueued = false;
|
|
14336
|
-
// The machine-wide daemon attachment (see attachGlobalWeb). Null until /web,
|
|
14337
|
-
// and its presence is what "this session is published" means.
|
|
14338
|
-
let webDaemon = null;
|
|
14339
|
-
|
|
14340
|
-
function syncWeb() {
|
|
14341
|
-
if (!web || !hub) return;
|
|
14342
|
-
// Coalesce: `emit` for each changed row already marks the subscribers dirty,
|
|
14343
|
-
// and syncChat is cheap, but a burst of frames would still run it repeatedly
|
|
14344
|
-
// for the same state.
|
|
14345
|
-
if (webSyncQueued) return;
|
|
14346
|
-
webSyncQueued = true;
|
|
14347
|
-
setImmediate(() => {
|
|
14348
|
-
webSyncQueued = false;
|
|
14349
|
-
if (!web || !hub) return;
|
|
14350
|
-
try { hub.syncChat(state.chat); } catch { /* the UI must never break the TUI */ }
|
|
14351
|
-
try { hub.setStatus(webStatus()); } catch { /* best-effort */ }
|
|
14352
|
-
});
|
|
14353
|
-
}
|
|
14354
|
-
|
|
14355
|
-
|
|
14356
|
-
// Everything the browser's status panel and side panes show. Built fresh on each
|
|
14357
|
-
// sync: it is a handful of field reads, and deriving it from live state is what
|
|
14358
|
-
// keeps the two front-ends from disagreeing after a mode change.
|
|
14359
|
-
function webStatus() {
|
|
14360
|
-
// Files this conversation touched, counted from the transcript. The TUI has no
|
|
14361
|
-
// separate index, and reading it here means a Write the model made is listed
|
|
14362
|
-
// without any tool having to announce itself.
|
|
14363
|
-
const files = new Map();
|
|
14364
|
-
const bump = (p, op) => {
|
|
14365
|
-
if (typeof p !== 'string' || !p) return;
|
|
14366
|
-
let rel = p;
|
|
14367
|
-
try { rel = path.relative(state.cwd || cfg.workspace || '', p) || p; } catch { /* keep as-is */ }
|
|
14368
|
-
if (rel.startsWith('..')) rel = p; // outside the workspace: show it whole
|
|
14369
|
-
const e = files.get(rel) || { path: rel, ops: new Set(), count: 0 };
|
|
14370
|
-
e.ops.add(op);
|
|
14371
|
-
e.count++;
|
|
14372
|
-
files.set(rel, e);
|
|
14373
|
-
};
|
|
14374
|
-
for (const m of state.chat || []) {
|
|
14375
|
-
if (m.role !== 'tool' || !m.toolArgs) continue;
|
|
14376
|
-
const a = m.toolArgs;
|
|
14377
|
-
const p = a.path || a.file_path;
|
|
14378
|
-
bump(p, m.toolName || 'tool');
|
|
14379
|
-
}
|
|
14380
|
-
const fileList = [...files.values()]
|
|
14381
|
-
.map((e) => ({ path: e.path, ops: [...e.ops].join(' '), count: e.count }))
|
|
14382
|
-
.sort((x, y) => y.count - x.count || x.path.localeCompare(y.path))
|
|
14383
|
-
.slice(0, 200);
|
|
14384
|
-
|
|
14385
|
-
const tasks = Object.values(state.tasks || {}).map((t) => ({
|
|
14386
|
-
id: t.id || t.taskId || '',
|
|
14387
|
-
kind: t.kind || 'bash',
|
|
14388
|
-
status: t.status || 'running',
|
|
14389
|
-
summary: t.summary || t.description || t.prompt || '',
|
|
14390
|
-
// Passed through when the task carries them, so the web task card can show
|
|
14391
|
-
// a start time / agent id instead of silently rendering nothing.
|
|
14392
|
-
startedAt: t.startedAt || t.startAt || 0,
|
|
14393
|
-
agentId: t.agentId || '',
|
|
14394
|
-
}));
|
|
14395
|
-
|
|
14396
|
-
const next = {
|
|
14397
|
-
session: session && session.id,
|
|
14398
|
-
title: session && session.title,
|
|
14399
|
-
model: state.modelLabel || cfg.model || '',
|
|
14400
|
-
provider: cfg.provider || '',
|
|
14401
|
-
mode: PERMISSION_LABEL[state.mode] || state.mode || '',
|
|
14402
|
-
cwd: state.cwd || '',
|
|
14403
|
-
plan: !!state.plan,
|
|
14404
|
-
focus: !!state.focus,
|
|
14405
|
-
swarm: !!state.swarm,
|
|
14406
|
-
// Live git status mirror, so the web statusline can show branch + diff
|
|
14407
|
-
// counts exactly like the TUI footer. Null when git is unavailable.
|
|
14408
|
-
git: state._gitInfo || null,
|
|
14409
|
-
// Thinking state, mirroring the terminal footer's model suffix. The
|
|
14410
|
-
// statusline appends "thinking[: effort]" from these two fields.
|
|
14411
|
-
reasoning: !!state.reasoning,
|
|
14412
|
-
effort: state.effort || '',
|
|
14413
|
-
busy: !!state.running,
|
|
14414
|
-
// The Working row's phrase and animation tick. Sent so the BROWSER shows
|
|
14415
|
-
// the same word, mid-sweep, as the terminal — the browser used to pick its
|
|
14416
|
-
// own random word and run its own clock, so the two screens disagreed about
|
|
14417
|
-
// both the text and the colour phase.
|
|
14418
|
-
workMsg: state.workMsg || '',
|
|
14419
|
-
spin: state.spin || 0,
|
|
14420
|
-
// The tick the current pulse BEGAN. The browser animates the tool-name
|
|
14421
|
-
// sweep and the Working row off `spin`, and both must start their cycle at
|
|
14422
|
-
// the tick the pulse started — using the raw spinner tick would drop them
|
|
14423
|
-
// into a mid-cycle colour the instant the animation hands over, which is a
|
|
14424
|
-
// different colour on screen from the terminal's.
|
|
14425
|
-
pulseStart: state.pulseStart == null ? 0 : state.pulseStart,
|
|
14426
|
-
ctxTokens: state.ctxTokens || 0,
|
|
14427
|
-
ctxMax: state.ctxMax || 0,
|
|
14428
|
-
ctxPercent: state.ctxPercent || 0,
|
|
14429
|
-
rounds: state.rounds || 0,
|
|
14430
|
-
steps: state.steps || 0,
|
|
14431
|
-
tokRate: state.tokRate || 0,
|
|
14432
|
-
todos: [...(state.todos || [])],
|
|
14433
|
-
queued: [...(state.queued || [])],
|
|
14434
|
-
tasks,
|
|
14435
|
-
files: fileList,
|
|
14436
|
-
tools: toolsForWeb(),
|
|
14437
|
-
commands: commandsForWeb(),
|
|
14438
|
-
// The workspace tree, for `@` completion in the composer. Cached (below)
|
|
14439
|
-
// because walking a real project is synchronous I/O on the render path.
|
|
14440
|
-
workspaceFiles: workspaceFilesForWeb(),
|
|
14441
|
-
quick: QUICK_COMMANDS,
|
|
14442
|
-
// The enumerable settings the browser can CHANGE, with the current value.
|
|
14443
|
-
//
|
|
14444
|
-
// The terminal exposes these as pickers, which the browser cannot render —
|
|
14445
|
-
// that is why /model and friends did nothing there. Sending the options
|
|
14446
|
-
// with the status lets the browser draw its own control and post the choice
|
|
14447
|
-
// back through `dispatch` ("/model <alias>"), which is the same path the
|
|
14448
|
-
// keyboard takes.
|
|
14449
|
-
options: optionsForWeb(),
|
|
14450
|
-
// A blocking prompt, if one is on screen — the browser renders it as a modal
|
|
14451
|
-
// and answers through the `approve` / `answerQuestion` actions.
|
|
14452
|
-
pending: pendingForWeb(),
|
|
14453
|
-
};
|
|
14454
|
-
|
|
14455
|
-
// Reuse the previous identity for any field whose CONTENT is unchanged.
|
|
14456
|
-
//
|
|
14457
|
-
// `setStatus` skips the broadcast when nothing changed, and it decides that by
|
|
14458
|
-
// identity. Most fields above are rebuilt on every call (todos, queued, tasks
|
|
14459
|
-
// and the file list all come from fresh arrays), so without this every frame
|
|
14460
|
-
// would look like a change and the full status would be pushed over SSE twelve
|
|
14461
|
-
// times a second for nothing. Comparing here — once, shallowly — is what makes
|
|
14462
|
-
// the "did anything actually change" test meaningful.
|
|
14463
|
-
const prev = (hub && hub.status) || null;
|
|
14464
|
-
if (prev) {
|
|
14465
|
-
for (const k of Object.keys(next)) {
|
|
14466
|
-
if (next[k] === prev[k]) continue;
|
|
14467
|
-
if (shallowEqualArray(next[k], prev[k])) next[k] = prev[k];
|
|
14468
|
-
}
|
|
14469
|
-
}
|
|
14470
|
-
return next;
|
|
14471
|
-
}
|
|
14472
14173
|
|
|
14473
14174
|
/** True when two arrays hold the same content (compared one level deep). */
|
|
14474
14175
|
function shallowEqualArray(a, b) {
|
|
@@ -14580,7 +14281,7 @@ export async function startTUI(opts) {
|
|
|
14580
14281
|
}
|
|
14581
14282
|
// Built ONCE per session and reused by reference.
|
|
14582
14283
|
//
|
|
14583
|
-
//
|
|
14284
|
+
// Building these lists on every frame cost a map over ~20 tools and ~60 commands at the
|
|
14584
14285
|
// these lists each time cost a map over ~20 tools and ~60 commands at the
|
|
14585
14286
|
// spinner's 80 ms cadence — and it defeated `setStatus`'s change detection,
|
|
14586
14287
|
// which compares by identity. The registries do not change while a session runs,
|
|
@@ -14850,8 +14551,6 @@ export async function startTUI(opts) {
|
|
|
14850
14551
|
// every change reaches the screen through this one function, so it catches the
|
|
14851
14552
|
// rows that bypass addChat (streamed prose, tool rows, the plan bubble, an
|
|
14852
14553
|
// abort) without instrumenting each of those call sites. `syncChat` is a no-op
|
|
14853
|
-
// until `/web` runs, and it is incremental, so an idle frame costs nothing.
|
|
14854
|
-
if (web) void syncWeb();
|
|
14855
14554
|
// Re-set AFTER the write: `_frameTickAt` names the LAST frame, so it has to be
|
|
14856
14555
|
// captured once that frame is on the terminal, not before it.
|
|
14857
14556
|
state._frameTickAt = getTerminalFlushTick();
|
|
@@ -14975,6 +14674,11 @@ export async function startTUI(opts) {
|
|
|
14975
14674
|
if (wait === 0) { setImmediate(paintNow); return; }
|
|
14976
14675
|
setTimeout(paintNow, wait);
|
|
14977
14676
|
}
|
|
14677
|
+
|
|
14678
|
+
/** Kept as a named hook because the streaming path calls it in several places. */
|
|
14679
|
+
function anchorScroll() {
|
|
14680
|
+
renderSoon();
|
|
14681
|
+
}
|
|
14978
14682
|
// THE MERMAID REPAINT HOOK.
|
|
14979
14683
|
//
|
|
14980
14684
|
// The mermaid renderer is loaded on first use, so the first frame of a diagram draws
|
|
@@ -15038,39 +14742,6 @@ export async function startTUI(opts) {
|
|
|
15038
14742
|
|
|
15039
14743
|
// ---- @ file completion ----------------------------------------------------
|
|
15040
14744
|
|
|
15041
|
-
// ---- @ file completion ----------------------------------------------------
|
|
15042
|
-
// Typing `@` shows an INLINE candidate list above the composer — the same widget
|
|
15043
|
-
// `/` uses (state.mention*) — rather than taking over the screen. It used to be a
|
|
15044
|
-
// silent rewrite of the input to the FIRST match of a single-directory listing:
|
|
15045
|
-
// you could not see the candidates, could not descend into a subdirectory
|
|
15046
|
-
// (`@src/` matched nothing), and hidden files were dropped.
|
|
15047
|
-
//
|
|
15048
|
-
// `walk` is bounded (depth + entry count) because it runs on a keystroke.
|
|
15049
|
-
function collectWorkspaceFiles(root, { limit = 4000, maxDepth = 8 } = {}) {
|
|
15050
|
-
const out = [];
|
|
15051
|
-
const skip = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'target', '__pycache__']);
|
|
15052
|
-
const walk = (dir, rel, depth) => {
|
|
15053
|
-
if (out.length >= limit || depth > maxDepth) return;
|
|
15054
|
-
let entries;
|
|
15055
|
-
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
15056
|
-
// Deterministic order: directories first, then files, each alphabetical, so
|
|
15057
|
-
// the list does not jump around between keystrokes.
|
|
15058
|
-
entries.sort((a, b) => (b.isDirectory() - a.isDirectory()) || a.name.localeCompare(b.name));
|
|
15059
|
-
for (const e of entries) {
|
|
15060
|
-
if (out.length >= limit) return;
|
|
15061
|
-
if (skip.has(e.name)) continue;
|
|
15062
|
-
const relPath = rel ? rel + '/' + e.name : e.name;
|
|
15063
|
-
if (e.isDirectory()) {
|
|
15064
|
-
out.push({ label: relPath + '/', isDir: true, rel: relPath + '/' });
|
|
15065
|
-
walk(path.join(dir, e.name), relPath, depth + 1);
|
|
15066
|
-
} else {
|
|
15067
|
-
out.push({ label: relPath, isDir: false, rel: relPath });
|
|
15068
|
-
}
|
|
15069
|
-
}
|
|
15070
|
-
};
|
|
15071
|
-
walk(root, '', 0);
|
|
15072
|
-
return out;
|
|
15073
|
-
}
|
|
15074
14745
|
|
|
15075
14746
|
// Everything after the last `@` that has no whitespace in it is the query.
|
|
15076
14747
|
function atQueryAt(input) {
|
|
@@ -15449,15 +15120,11 @@ export async function startTUI(opts) {
|
|
|
15449
15120
|
// instead of reaching for `state` and `renderFrame` directly, which is what lets the same
|
|
15450
15121
|
// code run in the web daemon where there is no terminal to draw on.
|
|
15451
15122
|
const view = tuiView({
|
|
15452
|
-
//
|
|
15453
|
-
// here — a captured copy would be the null we have now, and every web push would no-op.
|
|
15454
|
-
get hub() { return hub; },
|
|
15455
|
-
get hub() { return hub; },
|
|
15123
|
+
// The view object the turn loop draws through.
|
|
15456
15124
|
renderFrame,
|
|
15457
15125
|
renderSoon,
|
|
15458
15126
|
addChat,
|
|
15459
15127
|
notice,
|
|
15460
|
-
syncWeb: (...a) => syncWeb(...a),
|
|
15461
15128
|
openEditor,
|
|
15462
15129
|
openPicker,
|
|
15463
15130
|
openForm,
|
|
@@ -15568,6 +15235,57 @@ export async function startTUI(opts) {
|
|
|
15568
15235
|
}
|
|
15569
15236
|
|
|
15570
15237
|
const sessHost = new SessionHost({ state, cfg, session, view, onEvent: (e) => core.emit(e) });
|
|
15238
|
+
// WHAT `dispatch` RECEIVES.
|
|
15239
|
+
//
|
|
15240
|
+
// `dispatch` is module-level and calls `h.notice`, `h.openPanel`, `h.openPicker`,
|
|
15241
|
+
// `h.refreshKeybindings` and the rest of the terminal-side surface. None of those live on
|
|
15242
|
+
// SessionHost — they are closures in this function — so passing `sessHost` alone made every
|
|
15243
|
+
// slash command throw a TypeError that the submit path reported as a single line, i.e. the
|
|
15244
|
+
// command looked like it did nothing. One object that carries both halves is what the
|
|
15245
|
+
// dispatch signature has always expected.
|
|
15246
|
+
const cmdHost = Object.assign(Object.create(sessHost), {
|
|
15247
|
+
// The dispatch surface. Every name here is one `dispatch` destructures or reads off `h`;
|
|
15248
|
+
// a name missing from this list is an undefined call the moment that command runs, which is
|
|
15249
|
+
// how `/goal status` died with "addChat is not a function".
|
|
15250
|
+
addChat,
|
|
15251
|
+
notice,
|
|
15252
|
+
renderFrame,
|
|
15253
|
+
openPanel,
|
|
15254
|
+
openTasksPanel,
|
|
15255
|
+
openPicker,
|
|
15256
|
+
openEditor,
|
|
15257
|
+
openForm,
|
|
15258
|
+
refreshKeybindings,
|
|
15259
|
+
spawnTeammates,
|
|
15260
|
+
editComposerExternal,
|
|
15261
|
+
openRegistryBrowser,
|
|
15262
|
+
quit,
|
|
15263
|
+
// `saveSession` and `sendPrompt` are names dispatch uses that startTUI never defined: the
|
|
15264
|
+
// persistence lives on the session module, and starting a turn is `submit`. Aliased here so
|
|
15265
|
+
// a command that saves or sends gets the real thing instead of undefined.
|
|
15266
|
+
saveSession: (s) => sess.saveSession(s || session),
|
|
15267
|
+
sendPrompt: (text) => submit(typeof text === 'string' ? text : undefined),
|
|
15268
|
+
// The three reload paths. Each is guarded by `if (h.xxx)` in dispatch, so a missing one made
|
|
15269
|
+
// `/reload` and `/move` report "not available in this host" — true, but only because nothing
|
|
15270
|
+
// had wired them. They call the same functions the CLI itself uses at startup.
|
|
15271
|
+
reloadConfig: () => resolveConfig(),
|
|
15272
|
+
reloadPlugins: async () => {
|
|
15273
|
+
try {
|
|
15274
|
+
await unloadPlugins();
|
|
15275
|
+
await loadPlugins();
|
|
15276
|
+
return takePluginNotices();
|
|
15277
|
+
} catch (e) { return [{ level: 'error', text: (e && e.message) || String(e) }]; }
|
|
15278
|
+
},
|
|
15279
|
+
replaceSession: (next) => {
|
|
15280
|
+
// `/move` hands back a NEW session object. Rebinding here is what makes every later save
|
|
15281
|
+
// write that one instead of the session it was moved away from.
|
|
15282
|
+
session = next;
|
|
15283
|
+
state.session = next;
|
|
15284
|
+
sessHost.session = next;
|
|
15285
|
+
try { sessHost.persistState(); } catch { /* the move itself already succeeded */ }
|
|
15286
|
+
},
|
|
15287
|
+
persistState: () => sessHost.persistState(),
|
|
15288
|
+
});
|
|
15571
15289
|
// The session-naming implementation, reached by `runTurn` THROUGH the host.
|
|
15572
15290
|
//
|
|
15573
15291
|
// `runTurn` is a module-level function and this is a nested one inside `startTUI`, so a
|
|
@@ -15583,6 +15301,97 @@ export async function startTUI(opts) {
|
|
|
15583
15301
|
// `runTurn` receives the SessionHost instance), so the call threw `setCtxTokens is not defined` — the same
|
|
15584
15302
|
// mistake the `makeTitle` note above describes, made again.
|
|
15585
15303
|
sessHost.setCtxTokens = setCtxTokens;
|
|
15304
|
+
// AND THE SHRINK NOTICE, for the same reason: `dispatch` and `runTurn` are module-level and
|
|
15305
|
+
// call it after a compaction or a trim, while it needs this scope's `state`, `session` and
|
|
15306
|
+
// `setCtxTokens`. Reached directly it threw `noteCtxAfterShrink is not defined` — the exact
|
|
15307
|
+
// mistake the note above describes, made once more.
|
|
15308
|
+
sessHost.noteCtxAfterShrink = noteCtxAfterShrink;
|
|
15309
|
+
|
|
15310
|
+
// ---- capabilities a plugin can drive ----
|
|
15311
|
+
//
|
|
15312
|
+
// THIS IS THE OTHER END OF `api`. Without it every method on the plugin API answers "not
|
|
15313
|
+
// supported by this host" while looking correctly implemented: `plugin.js` forwards each one to
|
|
15314
|
+
// `_host`, and nothing had ever set `_host`. A plugin that opened a file tree or read a bound key
|
|
15315
|
+
// got a refusal from a feature that was finished.
|
|
15316
|
+
//
|
|
15317
|
+
// The surface is 'tui': a plugin reads `api.surface` to choose between a status-bar widget and a
|
|
15318
|
+
// rail row, and this is the process with a terminal.
|
|
15319
|
+
setPluginSurface('tui');
|
|
15320
|
+
const host = {
|
|
15321
|
+
openFileTree(filter) {
|
|
15322
|
+
// The same guard `/files` uses: a workspace with nothing in it says so rather than opening an
|
|
15323
|
+
// empty panel the user has to dismiss.
|
|
15324
|
+
try {
|
|
15325
|
+
const cwd = state.cwd || cfg.workspace || process.cwd();
|
|
15326
|
+
const files = walkFiles(cwd, { includeIgnored: false });
|
|
15327
|
+
const root = buildTree(files, cwd);
|
|
15328
|
+
if (!root.children.length) return false;
|
|
15329
|
+
// ONE OVERLAY AT A TIME. Opening the tree on top of a picker leaves two things owning the
|
|
15330
|
+
// keys, and the one underneath never gets a chance to close.
|
|
15331
|
+
const expanded = new Set();
|
|
15332
|
+
for (const c of root.children) if (c.dir) expanded.add(c.rel);
|
|
15333
|
+
state.fileTree = { root, expanded, sel: 0, scroll: 0, filter: String(filter || ''), cwd };
|
|
15334
|
+
state.picker = null; state.form = null; state.panel = null; state.menuOpen = false;
|
|
15335
|
+
renderFrame();
|
|
15336
|
+
return true;
|
|
15337
|
+
} catch { return false; }
|
|
15338
|
+
},
|
|
15339
|
+
closeFileTree() {
|
|
15340
|
+
if (!state.fileTree) return;
|
|
15341
|
+
state.fileTree = null;
|
|
15342
|
+
renderFrame();
|
|
15343
|
+
},
|
|
15344
|
+
openPanel: (content) => openPanel(content),
|
|
15345
|
+
openEditor: (opts) => openEditor(opts),
|
|
15346
|
+
openPicker: (opts) => openPicker(opts),
|
|
15347
|
+
openForm: (opts) => openForm(opts),
|
|
15348
|
+
openTasksPanel: () => openTasksPanel(),
|
|
15349
|
+
openRegistryBrowser: (kind) => openRegistryBrowser(kind),
|
|
15350
|
+
notice: (text, kind) => notice(text, kind),
|
|
15351
|
+
addChat: (role, text) => addChat({ role, text }),
|
|
15352
|
+
getMessages: () => state.chat || [],
|
|
15353
|
+
sendPrompt: (text) => submit(typeof text === 'string' ? text : undefined),
|
|
15354
|
+
saveSession: (s) => sess.saveSession(s || session),
|
|
15355
|
+
quit: () => quit(0),
|
|
15356
|
+
getTheme() { return currentTheme(); },
|
|
15357
|
+
setTheme(name) {
|
|
15358
|
+
if (!hasTheme(name)) return false;
|
|
15359
|
+
setTheme(name);
|
|
15360
|
+
state.theme = name;
|
|
15361
|
+
// THE DIFFERENTIAL PAINTER COMPARES AGAINST THE FRAME IT BELIEVES IT PAINTED. `setTheme`
|
|
15362
|
+
// alone leaves every cached cell carrying the old escapes, so the new theme appears only on
|
|
15363
|
+
// the rows that happen to change next.
|
|
15364
|
+
lastFrame = null;
|
|
15365
|
+
renderFrame();
|
|
15366
|
+
return true;
|
|
15367
|
+
},
|
|
15368
|
+
// A PLUGIN GETS A READING, NOT THE LIVE HANDLE. The steer and interrupt functions belong to the
|
|
15369
|
+
// TUI's task registry and would let a plugin drive an agent around the runtime's back.
|
|
15370
|
+
subagents() {
|
|
15371
|
+
return listRuns().map((r) => ({ id: r.agentId, name: r.name, type: r.type, status: r.status }));
|
|
15372
|
+
},
|
|
15373
|
+
messageSubagent(ref, text) { return sendToRun(ref, text); },
|
|
15374
|
+
interruptSubagent(ref) { return interruptRun(ref); },
|
|
15375
|
+
closeSubagent(ref) { return closeRun(ref); },
|
|
15376
|
+
// THREE SOURCES, ALL CHECKED. "Is this key already taken?" needs the built-ins and the user's
|
|
15377
|
+
// own file as well as what other plugins claimed; checking only the plugin list let a plugin
|
|
15378
|
+
// silently steal Ctrl+B.
|
|
15379
|
+
//
|
|
15380
|
+
// `keybindings` is declared LATER in this function than this object, so it is read at CALL time
|
|
15381
|
+
// rather than captured here — a direct reference would hit the temporal dead zone the first time
|
|
15382
|
+
// a plugin asked, which is a crash inside a screen nobody is looking at.
|
|
15383
|
+
isKeyBound(key) {
|
|
15384
|
+
const k = normalizeKey(key);
|
|
15385
|
+
if (keybindings.bindings.has(k)) return true;
|
|
15386
|
+
if (pluginKeybinds().includes(k)) return true;
|
|
15387
|
+
return BUILTIN_KEYS.has(k);
|
|
15388
|
+
},
|
|
15389
|
+
boundKeys() {
|
|
15390
|
+
return [...new Set([...keybindings.bindings.keys(), ...pluginKeybinds(), ...BUILTIN_KEYS])];
|
|
15391
|
+
},
|
|
15392
|
+
};
|
|
15393
|
+
setPluginHost(host);
|
|
15394
|
+
|
|
15586
15395
|
// The Goal tool writes the SAME objective field /goal does, so the status panel and the turn loop cannot
|
|
15587
15396
|
// disagree about what the agent is working towards. `runTurn` reaches both through `sessHost`, which is why
|
|
15588
15397
|
// the store is installed here rather than inside the tool.
|
|
@@ -15729,7 +15538,9 @@ export async function startTUI(opts) {
|
|
|
15729
15538
|
try {
|
|
15730
15539
|
const listed = kind === 'skills'
|
|
15731
15540
|
? await remote.listRemoteSkillsDetailed()
|
|
15732
|
-
|
|
15541
|
+
// THE PLUGIN LIST CARRIES DESCRIPTIONS TOO. A remote catalogue of bare directory names told the
|
|
15542
|
+
// reader nothing about what any of them did.
|
|
15543
|
+
: await remote.listRemotePluginsDetailed();
|
|
15733
15544
|
b.data.remote = listed.ok ? listed.items : [];
|
|
15734
15545
|
b.data.remoteError = listed.ok ? '' : listed.error;
|
|
15735
15546
|
} catch (e) {
|
|
@@ -16457,7 +16268,10 @@ export async function startTUI(opts) {
|
|
|
16457
16268
|
const tokTimer = setInterval(() => {
|
|
16458
16269
|
const times = state._tokTimes;
|
|
16459
16270
|
if (!times || !times.length) {
|
|
16460
|
-
|
|
16271
|
+
// THE LAST MEASUREMENT SURVIVES THE TURN. The window is a second wide, so a turn that
|
|
16272
|
+
// ended emptied it — and the row dropped to `0 tok/s`, which reads as "nothing happened"
|
|
16273
|
+
// rather than "that was how fast it went". The next turn replaces it.
|
|
16274
|
+
if (state._lastTokRate) { state.tokRate = state._lastTokRate; renderSoon(); }
|
|
16461
16275
|
return;
|
|
16462
16276
|
}
|
|
16463
16277
|
const cutoff = Date.now() - TOK_WINDOW_MS;
|
|
@@ -16465,6 +16279,7 @@ export async function startTUI(opts) {
|
|
|
16465
16279
|
while (drop < times.length && times[drop] < cutoff) drop++;
|
|
16466
16280
|
if (drop) times.splice(0, drop);
|
|
16467
16281
|
const rate = times.length;
|
|
16282
|
+
if (rate > 0) state._lastTokRate = rate;
|
|
16468
16283
|
if (rate !== state.tokRate) { state.tokRate = rate; renderSoon(); }
|
|
16469
16284
|
}, 50);
|
|
16470
16285
|
|
|
@@ -16705,8 +16520,8 @@ export async function startTUI(opts) {
|
|
|
16705
16520
|
function dispatchFromStatusBar(cmd) {
|
|
16706
16521
|
const savedInput = state.input || '';
|
|
16707
16522
|
const savedCaret = state.caret || 0;
|
|
16708
|
-
Promise.resolve(dispatch(cmd, '', state, cfg, session,
|
|
16709
|
-
.catch(() => {})
|
|
16523
|
+
Promise.resolve(dispatch(cmd, '', state, cfg, session, cmdHost, submit, stdout))
|
|
16524
|
+
.catch((err) => { appErr('status dispatch failed: ' + ((err && err.message) || err)); })
|
|
16710
16525
|
.then(() => {
|
|
16711
16526
|
// Only restore when the picker is the thing now open and it did not itself
|
|
16712
16527
|
// seed the composer (a command may legitimately write to state.input).
|
|
@@ -16750,7 +16565,7 @@ export async function startTUI(opts) {
|
|
|
16750
16565
|
}
|
|
16751
16566
|
state.menuOpen = false; state.menuList = []; state.menuSel = 0; state.menuOffset = 0;
|
|
16752
16567
|
state.input = ''; state.caret = 0;
|
|
16753
|
-
dispatch(cmd.name, '', state, cfg, session,
|
|
16568
|
+
dispatch(cmd.name, '', state, cfg, session, cmdHost, submit, stdout);
|
|
16754
16569
|
if (state._quit) { quit(); return true; }
|
|
16755
16570
|
renderFrame();
|
|
16756
16571
|
}
|
|
@@ -17611,7 +17426,6 @@ export async function startTUI(opts) {
|
|
|
17611
17426
|
// the editor for a steered draft).
|
|
17612
17427
|
if (draft) { state.input = ''; state.caret = 0; state.pastes.clear(); state.pasteCounter = 0; }
|
|
17613
17428
|
state.queued = [];
|
|
17614
|
-
if (web && hub) { try { hub.pubStatusField('queued', []); } catch { /* best-effort */ } }
|
|
17615
17429
|
renderFrame();
|
|
17616
17430
|
}
|
|
17617
17431
|
|
|
@@ -17621,7 +17435,6 @@ export async function startTUI(opts) {
|
|
|
17621
17435
|
if (!state.queued || !state.queued.length) return false;
|
|
17622
17436
|
const text = state.queued[state.queued.length - 1];
|
|
17623
17437
|
state.queued = state.queued.slice(0, -1);
|
|
17624
|
-
if (web && hub) { try { hub.pubStatusField('queued', [...state.queued]); } catch { /* best-effort */ } }
|
|
17625
17438
|
state.input = text;
|
|
17626
17439
|
state.caret = text.length;
|
|
17627
17440
|
// Drop the matching transcript entry: the item is back in the composer.
|
|
@@ -17833,9 +17646,9 @@ export async function startTUI(opts) {
|
|
|
17833
17646
|
const sp = text.indexOf(' ');
|
|
17834
17647
|
const c = sp === -1 ? text : text.slice(0, sp);
|
|
17835
17648
|
const arg = sp === -1 ? '' : text.slice(sp + 1).trim();
|
|
17836
|
-
Promise.resolve(dispatch(c, arg, state, cfg, session,
|
|
17649
|
+
Promise.resolve(dispatch(c, arg, state, cfg, session, cmdHost, submit, stdout))
|
|
17837
17650
|
.catch((err) => {
|
|
17838
|
-
try {
|
|
17651
|
+
try { cmdHost.notice(`keybinding ${t.key} → ${text} failed: ${(err && err.message) || err}`, 'error'); }
|
|
17839
17652
|
catch { /* the UI itself is broken */ }
|
|
17840
17653
|
});
|
|
17841
17654
|
renderFrame();
|
|
@@ -19326,7 +19139,7 @@ export async function startTUI(opts) {
|
|
|
19326
19139
|
// An entry from the SECOND level (arguments) is not a command name: it must
|
|
19327
19140
|
// never be turned into `submit('/' + name)`. That is what produced
|
|
19328
19141
|
// "Unknown command: /" — typing an argument that matches no completion
|
|
19329
|
-
// (`/trim 0`, `/
|
|
19142
|
+
// (`/trim 0`, `/set model x`) left a hint-only row selected, and Enter sent
|
|
19330
19143
|
// the literal "/". `_cmdName` marks a row as belonging to the argument level.
|
|
19331
19144
|
const argLevel = !!(selItem && selItem._cmdName);
|
|
19332
19145
|
if (argLevel && selItem._argWord && selItem.name) {
|
|
@@ -19630,47 +19443,11 @@ function wheelStep(state, family) {
|
|
|
19630
19443
|
// The draft belongs to the history walk that just ended; the next ↑ starts fresh.
|
|
19631
19444
|
state.draftInput = '';
|
|
19632
19445
|
if (!text) { renderFrame(); return; }
|
|
19633
|
-
//
|
|
19634
|
-
//
|
|
19635
|
-
//
|
|
19636
|
-
//
|
|
19637
|
-
|
|
19638
|
-
// it is the only way to steer a member while the lead is mid-turn.
|
|
19639
|
-
if (text.startsWith('@')) {
|
|
19640
|
-
const m = /^@([\w-]+)\s+([\s\S]+)$/.exec(text);
|
|
19641
|
-
if (!m) {
|
|
19642
|
-
notice(uiText('Use `@name message` to send straight to a member.'), 'error');
|
|
19643
|
-
renderFrame();
|
|
19644
|
-
return;
|
|
19645
|
-
}
|
|
19646
|
-
const [, who, body] = m;
|
|
19647
|
-
const teamName = leadTeam();
|
|
19648
|
-
if (!teamName) {
|
|
19649
|
-
notice(uiText('No team. Create one: /team create <name>'), 'error');
|
|
19650
|
-
renderFrame();
|
|
19651
|
-
return;
|
|
19652
|
-
}
|
|
19653
|
-
const roster = teamMod.readRoster(teamName);
|
|
19654
|
-
const names = String(roster || '').split('\n').map((l) => l.trim().split(/\s+/)[0]).filter(Boolean);
|
|
19655
|
-
// The user is not on the roster, so `@team-lead` would look unknown — it is accepted because a
|
|
19656
|
-
// member's own sends use that alias and it is the box the person reads.
|
|
19657
|
-
if (!names.includes(who) && who !== TEAM_LEAD_NAME) {
|
|
19658
|
-
notice(`No member "${who}". On this team: ${names.join(', ') || '(nobody)'}`, 'error');
|
|
19659
|
-
renderFrame();
|
|
19660
|
-
return;
|
|
19661
|
-
}
|
|
19662
|
-
try {
|
|
19663
|
-
mailMod.writeToMailbox(teamName, who, { from: TEAM_LEAD_NAME, text: body.trim() });
|
|
19664
|
-
// Shown in the transcript so the instruction is part of the record: a message that only exists in
|
|
19665
|
-
// someone's inbox is one the person cannot see themselves having sent.
|
|
19666
|
-
addChat({ role: 'system', text: `[you → ${who}] ${body.trim()}` });
|
|
19667
|
-
notice(`sent to ${who}`);
|
|
19668
|
-
} catch (e) {
|
|
19669
|
-
notice(`could not send: ${(e && e.message) || e}`, 'error');
|
|
19670
|
-
}
|
|
19671
|
-
renderFrame();
|
|
19672
|
-
return;
|
|
19673
|
-
}
|
|
19446
|
+
// `@` belongs to FILE REFERENCES here, so it must not also route to a teammate. The two collided:
|
|
19447
|
+
// typing `@src/tui.js` was read as `@member` and refused with "Use `@name message`", so the
|
|
19448
|
+
// composer could not mention a file at all. Sending to a member has a command of its own,
|
|
19449
|
+
// `/team msg <name> <text>`, which is what the prompt and the roster point at.
|
|
19450
|
+
|
|
19674
19451
|
|
|
19675
19452
|
if (!state.running) {
|
|
19676
19453
|
state.turnStart = Date.now();
|
|
@@ -19732,9 +19509,9 @@ function wheelStep(state, family) {
|
|
|
19732
19509
|
// registry browser hitting a bad field) surfaced as an unhandledRejection,
|
|
19733
19510
|
// which the process handler turns into process.exit(1) — the whole session
|
|
19734
19511
|
// died with no in-UI explanation. Catch here, report, and keep running.
|
|
19735
|
-
Promise.resolve(dispatch(c, arg, state, cfg, session,
|
|
19512
|
+
Promise.resolve(dispatch(c, arg, state, cfg, session, cmdHost, submit, stdout))
|
|
19736
19513
|
.catch((err) => {
|
|
19737
|
-
try {
|
|
19514
|
+
try { notice(`/${String(c).replace(/^\//, '')} failed: ${(err && err.message) || err}`, 'error'); }
|
|
19738
19515
|
catch { /* the UI itself is broken; the process handler will log it */ }
|
|
19739
19516
|
try { renderFrame(); } catch { /* ignore */ }
|
|
19740
19517
|
});
|
|
@@ -19754,8 +19531,6 @@ function wheelStep(state, family) {
|
|
|
19754
19531
|
// turn happened to trigger next. Push an independent `queued` event so the
|
|
19755
19532
|
// browser updates the queue pane immediately (claude-code-style granular
|
|
19756
19533
|
// event instead of a full-status snapshot).
|
|
19757
|
-
if (web) void syncWeb();
|
|
19758
|
-
if (web && hub) { try { hub.pubStatusField('queued', [...state.queued]); } catch { /* best-effort */ } }
|
|
19759
19534
|
return;
|
|
19760
19535
|
}
|
|
19761
19536
|
|
|
@@ -19857,7 +19632,7 @@ function wheelStep(state, family) {
|
|
|
19857
19632
|
// The TUI's binding of the turn loop. `runTurn` is module-level so a headless session can
|
|
19858
19633
|
// call the same code with its own five objects; this only supplies the terminal's.
|
|
19859
19634
|
async function runAgent(text, opts, viewArg) {
|
|
19860
|
-
return runTurn({ state, cfg, session, host: sessHost, view, spawn: spawnTeammates }, text, opts, viewArg);
|
|
19635
|
+
return runTurn({ state, cfg, session, host: sessHost, cmdHost, view, spawn: spawnTeammates }, text, opts, viewArg);
|
|
19861
19636
|
}
|
|
19862
19637
|
|
|
19863
19638
|
// Remember the session's working mode (permission / plan / focus / effort)
|
|
@@ -19865,685 +19640,6 @@ function wheelStep(state, family) {
|
|
|
19865
19640
|
// these are settings, not conversation, and must survive an abrupt exit.
|
|
19866
19641
|
function persistState() { return sessHost.persistState(); }
|
|
19867
19642
|
|
|
19868
|
-
// ---- /web: serve this session to a browser ---------------------------------
|
|
19869
|
-
// Started on demand. The browser talks to the SAME session: prompts it sends go
|
|
19870
|
-
// through `submit` (identical to typing), slash commands through `dispatch`, and
|
|
19871
|
-
// its transcript is the TUI's own `state.chat` mirrored by syncChat() on every
|
|
19872
|
-
// paint. Nothing here reimplements agent behaviour — it only relays.
|
|
19873
|
-
async function startWeb(bindIp, port) {
|
|
19874
|
-
if (web) { notice(`Web UI already running at ${web.url}`); return web; }
|
|
19875
|
-
hub = new SessionHub();
|
|
19876
|
-
// Actions the browser can take. Each one calls the SAME function the keyboard
|
|
19877
|
-
// calls, which is what keeps the two front-ends behaviourally identical.
|
|
19878
|
-
// Straight through to the core. It validates and throws in the same shape as before, so
|
|
19879
|
-
// the HTTP layer (which maps a throw to 409) is unaffected.
|
|
19880
|
-
// `opts.new` starts a FRESH session before the prompt runs.
|
|
19881
|
-
//
|
|
19882
|
-
// The caller does not know the new session's id in advance, so asking them to create one first
|
|
19883
|
-
// means two requests and a round trip to learn an id that this side invents anyway. Passing
|
|
19884
|
-
// `new: true` lets the daemon accept a prompt against any session URL and have it run in a new
|
|
19885
|
-
// session instead — the same thing `/new` does, minus the slash command.
|
|
19886
|
-
hub.actions.submit = async (text, opts) => {
|
|
19887
|
-
if (opts && opts.new) {
|
|
19888
|
-
// Flush the outgoing session first: its todos and transcript belong to the id being replaced,
|
|
19889
|
-
// and `dispatch` does exactly what `/new` does, so the two cannot drift apart.
|
|
19890
|
-
await core.dispatch('new', '');
|
|
19891
|
-
// The hub's rows and event ring belong to the session that just ended. Clearing them keeps a
|
|
19892
|
-
// viewer from showing the previous conversation under the new id.
|
|
19893
|
-
hub.rows = [];
|
|
19894
|
-
hub.events = [];
|
|
19895
|
-
}
|
|
19896
|
-
// `core.submit` AWAITS THE WHOLE TURN, so its result is the finished turn — no polling needed.
|
|
19897
|
-
const out = await core.submit(text);
|
|
19898
|
-
// `opts.return` asks for the transcript of what just ran:
|
|
19899
|
-
//
|
|
19900
|
-
// "turn" the rows of this turn, tool results included
|
|
19901
|
-
// "full" every row the session holds
|
|
19902
|
-
// "none" (default) whatever `core.submit` returned, unchanged
|
|
19903
|
-
//
|
|
19904
|
-
// Without this a caller had to submit, wait an unknown time, then issue a second request for
|
|
19905
|
-
// `/api/state` — two round trips and a guess at how long the turn would take.
|
|
19906
|
-
const want = opts && opts.return;
|
|
19907
|
-
if (!want || want === 'none') return out;
|
|
19908
|
-
// FORCE ONE SYNC: `syncChat` does nothing while no browser is subscribed, so `hub.rows` would be
|
|
19909
|
-
// empty here and the caller would get an empty transcript from a turn that plainly ran.
|
|
19910
|
-
try { hub.syncChat(state.chat || []); } catch { /* the reply still carries `result` */ }
|
|
19911
|
-
// The turn begins at the last user row; everything after it is what the prompt produced.
|
|
19912
|
-
const rows = Array.isArray(hub.rows) ? hub.rows : [];
|
|
19913
|
-
let from = 0;
|
|
19914
|
-
for (let k = rows.length - 1; k >= 0; k--) { if (rows[k] && rows[k].role === 'user') { from = k; break; } }
|
|
19915
|
-
const slice = want === 'full' ? rows : rows.slice(from);
|
|
19916
|
-
const detail = (opts && opts.detail) || 'full';
|
|
19917
|
-
const shaped = detail === 'minimal' ? slice.filter((r) => r.role !== 'tool')
|
|
19918
|
-
: detail === 'summary' ? slice.map((r) => (r.role === 'tool' ? { ...r, text: '', liveOutput: '', diff: undefined } : r))
|
|
19919
|
-
: slice;
|
|
19920
|
-
return { result: out, rows: shaped, detail, sessionId: session && session.id };
|
|
19921
|
-
};
|
|
19922
|
-
hub.actions.dispatch = async (cmd, arg) => {
|
|
19923
|
-
const out = await core.dispatch(cmd, arg);
|
|
19924
|
-
// The core runs the command; the repaint is this front end's business, so it stays
|
|
19925
|
-
// here rather than in the core. A headless run has nothing to repaint and passes a
|
|
19926
|
-
// no-op view.
|
|
19927
|
-
v.render();
|
|
19928
|
-
return out;
|
|
19929
|
-
};
|
|
19930
|
-
hub.actions.interrupt = () => core.interrupt();
|
|
19931
|
-
hub.actions.stopTask = async (id) => {
|
|
19932
|
-
const ctxLike = state.agent && state.agent.ctx ? state.agent.ctx : { tasks: state.tasks };
|
|
19933
|
-
stopTask(ctxLike, String(id || ''));
|
|
19934
|
-
};
|
|
19935
|
-
hub.actions.setMode = async (mode) => {
|
|
19936
|
-
const m = String(mode || '');
|
|
19937
|
-
if (!['ask', 'yolo', 'auto'].includes(m)) throw new Error('unknown mode: ' + m);
|
|
19938
|
-
setPermission(state, m);
|
|
19939
|
-
persistState();
|
|
19940
|
-
renderFrame();
|
|
19941
|
-
};
|
|
19942
|
-
hub.actions.shell = async (cmd) => {
|
|
19943
|
-
const c = String(cmd || '').trim();
|
|
19944
|
-
if (!c) throw new Error('empty command');
|
|
19945
|
-
await runShellCommand(c);
|
|
19946
|
-
};
|
|
19947
|
-
// ANSWER A RUNNING COMMAND FROM THE BROWSER.
|
|
19948
|
-
//
|
|
19949
|
-
// The terminal has Ctrl+G for this; the web UI had no equivalent, so a command that prompted was simply stuck
|
|
19950
|
-
// for anyone watching in a browser. Both go through the SAME foreground hook, so the two front ends cannot
|
|
19951
|
-
// disagree about which process a line is going to.
|
|
19952
|
-
hub.actions.stdinLine = async (line) => {
|
|
19953
|
-
const fg = state.agent && state.agent.ctx && state.agent.ctx._foreground;
|
|
19954
|
-
if (!fg || typeof fg.write !== 'function') throw new Error('no command is running in the foreground');
|
|
19955
|
-
if (!fg.write(String(line == null ? '' : line) + '\n')) throw new Error('the command has finished');
|
|
19956
|
-
};
|
|
19957
|
-
// Move the running command to the background. Ctrl+B's equivalent.
|
|
19958
|
-
hub.actions.detach = async () => {
|
|
19959
|
-
const fg = state.agent && state.agent.ctx && state.agent.ctx._foreground;
|
|
19960
|
-
if (!fg || typeof fg.detach !== 'function') throw new Error('nothing to background');
|
|
19961
|
-
const id = fg.detach();
|
|
19962
|
-
if (!id) throw new Error('the command has finished');
|
|
19963
|
-
try { state.agent.ctx._foreground = null; } catch { /* the agent may already be gone */ }
|
|
19964
|
-
notice(`Moved to background: ${id}`, 'info');
|
|
19965
|
-
renderFrame();
|
|
19966
|
-
return id;
|
|
19967
|
-
};
|
|
19968
|
-
// The two handshakes the agent blocks on. Resolving these from the browser is
|
|
19969
|
-
// what lets a phone answer an approval the terminal is showing.
|
|
19970
|
-
hub.actions.approve = async (id, ok) => {
|
|
19971
|
-
const ap = state.approvalPending;
|
|
19972
|
-
if (!ap) throw new Error('no approval is pending');
|
|
19973
|
-
state.approvalPending = null;
|
|
19974
|
-
ap.resolve(!!ok);
|
|
19975
|
-
renderFrame();
|
|
19976
|
-
};
|
|
19977
|
-
// The plan under review in Plan mode. Same idea as `approve`: the turn is blocked on a
|
|
19978
|
-
// promise, and a browser has to be able to settle it. Without this, a plan raised in
|
|
19979
|
-
// Plan mode left the web UI stuck on a spinning turn with no way forward except finding
|
|
19980
|
-
// the terminal that raised it.
|
|
19981
|
-
hub.actions.answerPlan = async (id, outcome) => {
|
|
19982
|
-
const pp = state.planPending;
|
|
19983
|
-
if (!pp) throw new Error('no plan is pending');
|
|
19984
|
-
const want = String(outcome || '').toLowerCase();
|
|
19985
|
-
// The terminal produces exactly these three (handleKey: enter -> approve, e -> edit,
|
|
19986
|
-
// esc -> keep). An unknown one is refused rather than coerced, so a stale browser tab
|
|
19987
|
-
// cannot settle a review with a meaning nobody chose.
|
|
19988
|
-
if (!['approve', 'edit', 'keep'].includes(want)) {
|
|
19989
|
-
throw new Error(`unknown plan outcome: ${outcome} (expected approve, edit or keep)`);
|
|
19990
|
-
}
|
|
19991
|
-
state.planPending = null;
|
|
19992
|
-
pp.resolve(want);
|
|
19993
|
-
renderFrame();
|
|
19994
|
-
};
|
|
19995
|
-
// The full-screen editor's Save and Cancel, so the six commands that open one
|
|
19996
|
-
// (/memory, /personal, /permissions, /output-style, /keybindings, /set-system-prompt)
|
|
19997
|
-
// are usable from a browser. They call the SAME `onSave` the terminal's Ctrl+S calls,
|
|
19998
|
-
// so a value written from the web takes the identical path — including the validation
|
|
19999
|
-
// the command puts in its own onSave.
|
|
20000
|
-
hub.actions.saveEditor = async (id, text) => {
|
|
20001
|
-
const ed = state.editor;
|
|
20002
|
-
if (!ed) throw new Error('no editor is open');
|
|
20003
|
-
if (typeof ed.onSave !== 'function') {
|
|
20004
|
-
throw new Error('this editor is read-only: no onSave handler');
|
|
20005
|
-
}
|
|
20006
|
-
const value = String(text == null ? '' : text);
|
|
20007
|
-
// Close first, then save: onSave may itself open a picker or write a notice, and it
|
|
20008
|
-
// must not be overwritten by a stale editor still being on screen.
|
|
20009
|
-
state.editor = null;
|
|
20010
|
-
renderFrame();
|
|
20011
|
-
ed.onSave(value);
|
|
20012
|
-
};
|
|
20013
|
-
hub.actions.cancelEditor = async (id) => {
|
|
20014
|
-
if (!state.editor) throw new Error('no editor is open');
|
|
20015
|
-
state.editor = null;
|
|
20016
|
-
renderFrame();
|
|
20017
|
-
};
|
|
20018
|
-
hub.actions.answerQuestion = async (id, answers, extra, note, advance) => {
|
|
20019
|
-
const q = state.question;
|
|
20020
|
-
if (!q) throw new Error('no question is pending');
|
|
20021
|
-
const list = Array.isArray(answers) ? answers : [];
|
|
20022
|
-
const cur = (q.items && q.items[q.index]) || {};
|
|
20023
|
-
const key = cur.question || 'answer';
|
|
20024
|
-
// The per-question answer: the picked option label(s), unless a free-text
|
|
20025
|
-
// "Other" was provided (then that wins, matching the terminal).
|
|
20026
|
-
const other = extra == null ? '' : String(extra).trim();
|
|
20027
|
-
if (other) q.answers[key] = other;
|
|
20028
|
-
else if (list.length) q.answers[key] = list.join(', ');
|
|
20029
|
-
// The whole-request note is only meaningful on the last question; store it
|
|
20030
|
-
// for the final resolve rather than as this question's answer.
|
|
20031
|
-
if (note != null) q.supplement = String(note);
|
|
20032
|
-
|
|
20033
|
-
const total = (q.items || []).length;
|
|
20034
|
-
const isLast = q.index >= total - 1;
|
|
20035
|
-
const more = advance !== false && !isLast;
|
|
20036
|
-
if (more) {
|
|
20037
|
-
// Advance to the next question and let the status broadcast re-open the
|
|
20038
|
-
// modal with it. Do NOT resolve yet — the agent is still blocked.
|
|
20039
|
-
q.index += 1;
|
|
20040
|
-
q.sel = 0;
|
|
20041
|
-
q.picked = new Set();
|
|
20042
|
-
try { syncWebNow(); } catch { /* best-effort */ }
|
|
20043
|
-
renderFrame();
|
|
20044
|
-
return { ok: true, index: q.index, total };
|
|
20045
|
-
}
|
|
20046
|
-
const answersOut = { ...q.answers };
|
|
20047
|
-
state.question = null;
|
|
20048
|
-
q.resolve({ answers: answersOut, additional: q.supplement || '' });
|
|
20049
|
-
try { syncWebNow(); } catch { /* best-effort */ }
|
|
20050
|
-
renderFrame();
|
|
20051
|
-
return { ok: true, done: true };
|
|
20052
|
-
};
|
|
20053
|
-
|
|
20054
|
-
// ---- session settings the browser can change ------------------------------
|
|
20055
|
-
//
|
|
20056
|
-
// Every one of these runs the SAME code the terminal's slash command does, and
|
|
20057
|
-
// persists, so a change made in the browser survives a restart and shows up in
|
|
20058
|
-
// the terminal immediately. Nothing is reimplemented here — the point is that
|
|
20059
|
-
// the two front-ends are views of one session.
|
|
20060
|
-
|
|
20061
|
-
/** Push the transcript and status to the hub right now, not on the next paint. */
|
|
20062
|
-
function syncWebNow() {
|
|
20063
|
-
if (!web || !hub) return;
|
|
20064
|
-
try { hub.syncChat(state.chat); } catch { /* the UI must never break the TUI */ }
|
|
20065
|
-
try { hub.setStatus(webStatus()); } catch { /* best-effort */ }
|
|
20066
|
-
renderFrame();
|
|
20067
|
-
}
|
|
20068
|
-
|
|
20069
|
-
hub.actions.setTitle = async (title) => {
|
|
20070
|
-
const t = String(title || '').trim();
|
|
20071
|
-
if (!t) throw new Error('title required');
|
|
20072
|
-
session.title = t.slice(0, 200);
|
|
20073
|
-
try { sess.saveSession(session); } catch { /* the title is cosmetic */ }
|
|
20074
|
-
writeWindowTitle(session, stdout);
|
|
20075
|
-
syncWebNow();
|
|
20076
|
-
};
|
|
20077
|
-
|
|
20078
|
-
|
|
20079
|
-
// Steer: inject text into the RUNNING turn instead of queueing a new one.
|
|
20080
|
-
// `agent.steer()` buffers it for the next model call — nothing can be inserted
|
|
20081
|
-
// into a request already in flight.
|
|
20082
|
-
hub.actions.steer = async (text) => {
|
|
20083
|
-
const t = String(text || '').trim();
|
|
20084
|
-
if (!t) throw new Error('text required');
|
|
20085
|
-
if (!state.running || !state.agent) throw new Error('nothing is running');
|
|
20086
|
-
state.agent.steer(t);
|
|
20087
|
-
addChat({ role: 'steer', text: t });
|
|
20088
|
-
};
|
|
20089
|
-
|
|
20090
|
-
// Edit a QUEUED message: pull it back out of the queue so the browser can put
|
|
20091
|
-
// it in the composer, exactly like the terminal's ↑-to-recall (see
|
|
20092
|
-
// recallQueued). Matched by TEXT, not index — the browser's list is rebuilt on
|
|
20093
|
-
// every status frame, so an index captured at click time can point at a
|
|
20094
|
-
// different item by the time it arrives.
|
|
20095
|
-
//
|
|
20096
|
-
// Returns the removed text so the caller can seed its composer with it.
|
|
20097
|
-
hub.actions.editQueued = async (text) => {
|
|
20098
|
-
const t = String(text == null ? '' : text);
|
|
20099
|
-
const i = state.queued.findIndex((q) => String(q) === t);
|
|
20100
|
-
if (i < 0) throw new Error('that message is no longer queued');
|
|
20101
|
-
state.queued.splice(i, 1);
|
|
20102
|
-
// Drop the matching transcript entry too: the message is now being edited,
|
|
20103
|
-
// not waiting, so leaving a `queued` row would double it.
|
|
20104
|
-
for (let k = state.chat.length - 1; k >= 0; k--) {
|
|
20105
|
-
if (state.chat[k].role === 'queued' && state.chat[k].text === t) { state.chat.splice(k, 1); break; }
|
|
20106
|
-
}
|
|
20107
|
-
if (web && hub) { try { hub.pubStatusField('queued', [...state.queued]); } catch { /* best-effort */ } }
|
|
20108
|
-
syncWebNow();
|
|
20109
|
-
return { ok: true, text: t };
|
|
20110
|
-
};
|
|
20111
|
-
|
|
20112
|
-
// Remove a queued message outright (the browser's ✕), without editing it.
|
|
20113
|
-
hub.actions.dropQueued = async (text) => {
|
|
20114
|
-
const t = String(text == null ? '' : text);
|
|
20115
|
-
const i = state.queued.findIndex((q) => String(q) === t);
|
|
20116
|
-
if (i < 0) throw new Error('that message is no longer queued');
|
|
20117
|
-
state.queued.splice(i, 1);
|
|
20118
|
-
for (let k = state.chat.length - 1; k >= 0; k--) {
|
|
20119
|
-
if (state.chat[k].role === 'queued' && state.chat[k].text === t) { state.chat.splice(k, 1); break; }
|
|
20120
|
-
}
|
|
20121
|
-
if (web && hub) { try { hub.pubStatusField('queued', [...state.queued]); } catch { /* best-effort */ } }
|
|
20122
|
-
syncWebNow();
|
|
20123
|
-
return { ok: true };
|
|
20124
|
-
};
|
|
20125
|
-
|
|
20126
|
-
// The effective config, with secrets REPLACED by a set/unset flag. The browser
|
|
20127
|
-
// needs to show what is in force without ever receiving a key.
|
|
20128
|
-
hub.actions.getConfig = async () => effectiveSnapshot(cfg);
|
|
20129
|
-
|
|
20130
|
-
/**
|
|
20131
|
-
* Set one root-level key in config.toml.
|
|
20132
|
-
*
|
|
20133
|
-
* `key` is whitelisted: this surface can be reached over the network, and
|
|
20134
|
-
* "write any key" would let a caller rewrite the whole file, including the
|
|
20135
|
-
* provider table and the access token.
|
|
20136
|
-
*/
|
|
20137
|
-
hub.actions.setConfig = async (key, value) => {
|
|
20138
|
-
const ALLOWED = new Set([
|
|
20139
|
-
'calm_mode', 'auto_update', 'auto_compact', 'prompt_cache',
|
|
20140
|
-
'temperature', 'top_p', 'presence_penalty', 'sampling',
|
|
20141
|
-
'tool_allow_external_paths', 'subagent_model', 'swarm_mode', 'theme',
|
|
20142
|
-
]);
|
|
20143
|
-
const k = String(key || '');
|
|
20144
|
-
if (!ALLOWED.has(k)) throw new Error(`not a settable key: ${k}`);
|
|
20145
|
-
const raw = String(value);
|
|
20146
|
-
if (/^(true|false)$/i.test(raw)) setConfigBool(k, /^true$/i.test(raw));
|
|
20147
|
-
else setConfigString(k, raw);
|
|
20148
|
-
// Re-read so the change is live without a restart.
|
|
20149
|
-
Object.assign(cfg, resolveConfig());
|
|
20150
|
-
state.reasoning = !!cfg.reasoning;
|
|
20151
|
-
syncWebNow();
|
|
20152
|
-
return effectiveSnapshot(cfg);
|
|
20153
|
-
};
|
|
20154
|
-
|
|
20155
|
-
// ---- providers and models -------------------------------------------------
|
|
20156
|
-
//
|
|
20157
|
-
// These edit config.toml through the same helpers /provider uses, then
|
|
20158
|
-
// re-resolve so the change is live. The option caches are invalidated because
|
|
20159
|
-
// `webStatus` reuses arrays by identity — without that the browser would keep
|
|
20160
|
-
// showing a provider that has just been deleted.
|
|
20161
|
-
|
|
20162
|
-
function invalidateOptionCaches() {
|
|
20163
|
-
toolsCache = null;
|
|
20164
|
-
commandsCache = null;
|
|
20165
|
-
wsFilesCache = { root: '', at: 0, files: null };
|
|
20166
|
-
}
|
|
20167
|
-
|
|
20168
|
-
/** Every provider with its base URL and model count, for the settings UI. */
|
|
20169
|
-
hub.actions.listProviders = async () => {
|
|
20170
|
-
const pr = (cfg.raw && cfg.raw.providers) || {};
|
|
20171
|
-
const models = (cfg.raw && cfg.raw.models) || {};
|
|
20172
|
-
return Object.keys(pr).map((name) => ({
|
|
20173
|
-
name,
|
|
20174
|
-
baseUrl: String(pr[name].base_url || pr[name].baseUrl || ''),
|
|
20175
|
-
protocol: String(pr[name].protocol || 'openai'),
|
|
20176
|
-
keySet: !!(pr[name].api_key || pr[name].apiKey),
|
|
20177
|
-
current: name === cfg.provider,
|
|
20178
|
-
models: Object.keys(models).filter((k) => (models[k].provider || '') === name),
|
|
20179
|
-
}));
|
|
20180
|
-
};
|
|
20181
|
-
|
|
20182
|
-
hub.actions.addProvider = async (name, baseUrl, apiKey, protocol) => {
|
|
20183
|
-
const n = String(name || '').trim();
|
|
20184
|
-
if (!n) throw new Error('provider name required');
|
|
20185
|
-
if (!/^[A-Za-z0-9_-]+$/.test(n)) throw new Error('name may contain letters, digits, - and _ only');
|
|
20186
|
-
// Accept the protocol value OR a Type label ("OpenAI Responses").
|
|
20187
|
-
const proto = typeToProtocol(protocol);
|
|
20188
|
-
addProvider(n, { base_url: String(baseUrl || ''), api_key: String(apiKey || ''), protocol: proto });
|
|
20189
|
-
cfg.raw.providers = cfg.raw.providers || {};
|
|
20190
|
-
cfg.raw.providers[n] = { base_url: String(baseUrl || ''), api_key: String(apiKey || ''), protocol: proto };
|
|
20191
|
-
invalidateOptionCaches();
|
|
20192
|
-
syncWebNow();
|
|
20193
|
-
return hub.actions.listProviders();
|
|
20194
|
-
};
|
|
20195
|
-
|
|
20196
|
-
hub.actions.removeProvider = async (name) => {
|
|
20197
|
-
const n = String(name || '');
|
|
20198
|
-
if (!n) throw new Error('provider name required');
|
|
20199
|
-
const pr = (cfg.raw && cfg.raw.providers) || {};
|
|
20200
|
-
if (!pr[n]) throw new Error(`no such provider: ${n}`);
|
|
20201
|
-
removeProvider(n);
|
|
20202
|
-
delete pr[n];
|
|
20203
|
-
// Its models go too: a model keyed to a provider that no longer exists is
|
|
20204
|
-
// unselectable and only clutters the picker.
|
|
20205
|
-
for (const key of Object.keys(cfg.raw.models || {})) {
|
|
20206
|
-
if (key.split('/')[0] === n) delete cfg.raw.models[key];
|
|
20207
|
-
}
|
|
20208
|
-
if (cfg.provider === n) { cfg.provider = ''; state.provider = ''; }
|
|
20209
|
-
invalidateOptionCaches();
|
|
20210
|
-
syncWebNow();
|
|
20211
|
-
return hub.actions.listProviders();
|
|
20212
|
-
};
|
|
20213
|
-
|
|
20214
|
-
// Read the provider's model list from its /models endpoint and register every
|
|
20215
|
-
// model, so the picker fills in without the user typing ids. Best-effort: an
|
|
20216
|
-
// unreachable endpoint leaves the provider added.
|
|
20217
|
-
hub.actions.discoverModels = async (name) => {
|
|
20218
|
-
const n = String(name || '');
|
|
20219
|
-
const pr = (cfg.raw && cfg.raw.providers) || {};
|
|
20220
|
-
const p = pr[n];
|
|
20221
|
-
if (!p) throw new Error(`no such provider: ${n}`);
|
|
20222
|
-
const baseUrl = p.base_url || p.baseUrl || '';
|
|
20223
|
-
if (!baseUrl) throw new Error('provider has no base_url');
|
|
20224
|
-
// `throwOnError`: the caller asked for this explicitly, so an unreachable
|
|
20225
|
-
// endpoint or a rejected key must surface as an error rather than as
|
|
20226
|
-
// "found 0 models", which is indistinguishable from an empty catalogue.
|
|
20227
|
-
const found = await fetchModels({
|
|
20228
|
-
baseUrl,
|
|
20229
|
-
apiKey: p.api_key || p.apiKey || '',
|
|
20230
|
-
protocol: p.protocol || 'openai',
|
|
20231
|
-
throwOnError: true,
|
|
20232
|
-
});
|
|
20233
|
-
cfg.raw.models = cfg.raw.models || {};
|
|
20234
|
-
let added = 0;
|
|
20235
|
-
for (const m of found) {
|
|
20236
|
-
const key = modelKey(n, m.id);
|
|
20237
|
-
if (!cfg.raw.models[key]) added++;
|
|
20238
|
-
addModel(n, m.id, { display_name: m.display, contextLength: m.contextLength, maxTokens: m.maxTokens });
|
|
20239
|
-
cfg.raw.models[key] = {
|
|
20240
|
-
provider: n, model: m.id,
|
|
20241
|
-
display_name: m.display || undefined,
|
|
20242
|
-
maxTokens: m.maxTokens || undefined,
|
|
20243
|
-
contextLength: m.contextLength || undefined,
|
|
20244
|
-
reasoning: m.reasoning || undefined,
|
|
20245
|
-
efforts: m.efforts || undefined,
|
|
20246
|
-
};
|
|
20247
|
-
}
|
|
20248
|
-
invalidateOptionCaches();
|
|
20249
|
-
syncWebNow();
|
|
20250
|
-
return { found: found.length, added };
|
|
20251
|
-
};
|
|
20252
|
-
|
|
20253
|
-
// The models.dev catalogue, for "import a known provider".
|
|
20254
|
-
hub.actions.listKnownProviders = async () => {
|
|
20255
|
-
const catalog = await fetchCatalog();
|
|
20256
|
-
if (!catalog) throw new Error('could not reach models.dev');
|
|
20257
|
-
return Object.values(catalog)
|
|
20258
|
-
.filter((p) => p && p.id && p.api)
|
|
20259
|
-
.map((p) => ({ id: p.id, name: p.name || p.id, api: p.api }))
|
|
20260
|
-
.sort((a, b) => String(a.name).localeCompare(String(b.name)));
|
|
20261
|
-
};
|
|
20262
|
-
|
|
20263
|
-
/**
|
|
20264
|
-
* Import a models.dev entry as a provider, then discover its models.
|
|
20265
|
-
*
|
|
20266
|
-
* The key is required from the caller: models.dev publishes endpoints, not
|
|
20267
|
-
* credentials, so this cannot complete without the user supplying one.
|
|
20268
|
-
*/
|
|
20269
|
-
hub.actions.importKnownProvider = async (catalogId, name, apiKey) => {
|
|
20270
|
-
const catalog = await fetchCatalog();
|
|
20271
|
-
if (!catalog) throw new Error('could not reach models.dev');
|
|
20272
|
-
const entry = catalog[String(catalogId || '')];
|
|
20273
|
-
if (!entry || !entry.api) throw new Error(`unknown provider: ${catalogId}`);
|
|
20274
|
-
const n = String(name || entry.id || '').trim();
|
|
20275
|
-
if (!n) throw new Error('provider name required');
|
|
20276
|
-
const proto = /anthropic/i.test(String(entry.api)) ? 'anthropic' : 'openai';
|
|
20277
|
-
addProvider(n, { base_url: entry.api, api_key: String(apiKey || ''), protocol: proto });
|
|
20278
|
-
cfg.raw.providers = cfg.raw.providers || {};
|
|
20279
|
-
cfg.raw.providers[n] = { base_url: entry.api, api_key: String(apiKey || ''), protocol: proto };
|
|
20280
|
-
invalidateOptionCaches();
|
|
20281
|
-
syncWebNow();
|
|
20282
|
-
// Models are a bonus — a bad key must not undo the provider.
|
|
20283
|
-
let discovered = { found: 0, added: 0 };
|
|
20284
|
-
try { discovered = await hub.actions.discoverModels(n); } catch { /* best-effort */ }
|
|
20285
|
-
return { name: n, baseUrl: entry.api, protocol: proto, ...discovered };
|
|
20286
|
-
};
|
|
20287
|
-
|
|
20288
|
-
|
|
20289
|
-
|
|
20290
|
-
// Brought in on first use: see the note at the top of this file.
|
|
20291
|
-
const { startWebServer } = await import('./web.js');
|
|
20292
|
-
const srv = await startWebServer({
|
|
20293
|
-
hub,
|
|
20294
|
-
bindIp: bindIp || '127.0.0.1',
|
|
20295
|
-
port: port == null ? 0 : port,
|
|
20296
|
-
onNotice: (m, k) => notice(m, k),
|
|
20297
|
-
});
|
|
20298
|
-
web = srv;
|
|
20299
|
-
// Seed the browser with what already exists, so opening the page mid-session
|
|
20300
|
-
// shows the conversation rather than an empty pane.
|
|
20301
|
-
try { hub.syncChat(state.chat); hub.setStatus(webStatus()); } catch { /* best-effort */ }
|
|
20302
|
-
return srv;
|
|
20303
|
-
}
|
|
20304
|
-
|
|
20305
|
-
function stopWeb() {
|
|
20306
|
-
if (!web) { notice(uiText('Web UI is not running'), 'error'); return false; }
|
|
20307
|
-
// Tell the daemon first, so its directory stops listing this session instead
|
|
20308
|
-
// of showing a link to a port that is about to disappear.
|
|
20309
|
-
if (webDaemon) {
|
|
20310
|
-
try { webDaemon.detach(); } catch { /* best-effort */ }
|
|
20311
|
-
webDaemon = null;
|
|
20312
|
-
}
|
|
20313
|
-
try { web.close(); } catch { /* already gone */ }
|
|
20314
|
-
web = null;
|
|
20315
|
-
hub = null;
|
|
20316
|
-
return true;
|
|
20317
|
-
}
|
|
20318
|
-
|
|
20319
|
-
/**
|
|
20320
|
-
* Bring up the GLOBAL web UI for this session.
|
|
20321
|
-
*
|
|
20322
|
-
* Two servers are involved and the distinction matters:
|
|
20323
|
-
* * `startWeb()` here — this session's OWN server, holding the transcript,
|
|
20324
|
-
* the actions and the SSE stream. It binds a random loopback port.
|
|
20325
|
-
* * the daemon — one per machine, on the FIXED port from config.toml. It
|
|
20326
|
-
* serves the directory and proxies /s/<id>/* to the session above.
|
|
20327
|
-
*
|
|
20328
|
-
* The user asked for a fixed address that survives restarts and lists every
|
|
20329
|
-
* session, so the daemon is what they open. If one is already running this
|
|
20330
|
-
* session just registers with it — that is the "reuse, do not start another"
|
|
20331
|
-
* behaviour, and it is also the only option, since a second daemon could not
|
|
20332
|
-
* bind the fixed port anyway.
|
|
20333
|
-
*/
|
|
20334
|
-
async function attachGlobalWeb(bindIp, port) {
|
|
20335
|
-
// The bind address: an explicit /web argument wins, else the config value,
|
|
20336
|
-
// else loopback. It decides BOTH bindings — the session's own server and the
|
|
20337
|
-
// daemon the browser actually opens — so `/web 0.0.0.0` is really reachable
|
|
20338
|
-
// from another machine instead of silently listening on 127.0.0.1.
|
|
20339
|
-
const host = String(bindIp || cfg.webHost || '127.0.0.1');
|
|
20340
|
-
// The session's own server first: the daemon needs a port to proxy to.
|
|
20341
|
-
const srv = await startWeb(host, port == null ? 0 : port);
|
|
20342
|
-
try {
|
|
20343
|
-
// IMPORTED HERE, NOT AT THE TOP. This chain pulls in web-daemon.js and measures ~76ms
|
|
20344
|
-
// to evaluate, and only /web ever reaches it — every other session paid that on
|
|
20345
|
-
// startup for a command it never runs.
|
|
20346
|
-
const { attachToDaemon } = await import('./web-daemon-client.js');
|
|
20347
|
-
webDaemon = await attachToDaemon({
|
|
20348
|
-
id: (session && session.id) || 'session',
|
|
20349
|
-
port: srv.port,
|
|
20350
|
-
token: srv.token,
|
|
20351
|
-
title: (session && session.title) || '',
|
|
20352
|
-
workspace: state.cwd || cfg.workspace || '',
|
|
20353
|
-
host,
|
|
20354
|
-
});
|
|
20355
|
-
} catch (e) {
|
|
20356
|
-
// The daemon is a convenience layer; the session's own server still works,
|
|
20357
|
-
// so fall back to reporting that rather than failing /web outright.
|
|
20358
|
-
notice(`Global web UI unavailable (${e.message}); this session is still served directly`, 'error');
|
|
20359
|
-
webDaemon = null;
|
|
20360
|
-
}
|
|
20361
|
-
// The daemon's token is the one the user pastes into the login page. It comes
|
|
20362
|
-
// from config.toml, so it is the same value every session reports — which is
|
|
20363
|
-
// the point: a saved browser login keeps working.
|
|
20364
|
-
return { srv, daemon: webDaemon, token: ensureWebToken() };
|
|
20365
|
-
}
|
|
20366
|
-
|
|
20367
|
-
|
|
20368
|
-
|
|
20369
|
-
const host = {
|
|
20370
|
-
// The one spawner, so the model's TeamCreate tool and the /team command start the same
|
|
20371
|
-
// kind of teammate.
|
|
20372
|
-
spawnTeammates,
|
|
20373
|
-
addChat, openPicker, openForm, notice, openPanel, openEditor, editComposerExternal, openTasksPanel, openRegistryBrowser,
|
|
20374
|
-
// While the side-thread box is open, a typed message goes to the SIDE THREAD, not
|
|
20375
|
-
// to the agent — this is the half of kimi's design that makes the box usable:
|
|
20376
|
-
// its `sendUserInput` feeds the panel from the ordinary composer, so a follow-up
|
|
20377
|
-
// needs no command. `opts.toMain` is the escape hatch for the paths that must
|
|
20378
|
-
// reach the agent regardless (a schedule, a command's own prompt).
|
|
20379
|
-
sendPrompt: (text, opts) => {
|
|
20380
|
-
const o = opts || {};
|
|
20381
|
-
if (state.btwPanel && !o.toMain && !o.fromSchedule) {
|
|
20382
|
-
void askSideQuestion(state, cfg, text, renderSoon);
|
|
20383
|
-
return;
|
|
20384
|
-
}
|
|
20385
|
-
void runAgent(text, o);
|
|
20386
|
-
},
|
|
20387
|
-
quit: () => { state._quit = true; },
|
|
20388
|
-
saveSession: (s) => { (async () => { try { const { runHooks } = await import('./plugin.js'); await runHooks('onSessionSave', s || session); } catch {} })(); sess.saveSession(s); },
|
|
20389
|
-
// Rebinds the closure's session AND the mirror on `state`. /move replaces it, and without
|
|
20390
|
-
// this the caller and the command disagreed about which session was current — every later
|
|
20391
|
-
// save wrote the old object, still stamped with the directory it was moved away from.
|
|
20392
|
-
replaceSession: (s) => { if (!s) return; session = s; state.session = s; if (s.workspace) state.workspace = s.workspace; writeWindowTitle(session, stdout); },
|
|
20393
|
-
getMessages: () => (session && session.messages ? session.messages : []),
|
|
20394
|
-
clearSession: () => { if (session) session.messages = []; if (state) { state.ctxTokens = 0; state.ctxPercent = 0; } renderFrame(); },
|
|
20395
|
-
getConfig: (key) => (cfg && key != null ? cfg[key] : undefined),
|
|
20396
|
-
setConfig: (key, val) => { if (cfg && key != null) cfg[key] = val; },
|
|
20397
|
-
// Persist a TOML root-level key to config.toml and keep the live cfg in sync.
|
|
20398
|
-
persistConfig: (key, val) => {
|
|
20399
|
-
try {
|
|
20400
|
-
setConfigString(String(key), typeof val === 'string' ? val : JSON.stringify(val));
|
|
20401
|
-
if (cfg && key != null) cfg[key] = val;
|
|
20402
|
-
return true;
|
|
20403
|
-
} catch (e) { return false; }
|
|
20404
|
-
},
|
|
20405
|
-
reloadConfig: () => resolveConfig(),
|
|
20406
|
-
// Full reload: unload the current plugins, then re-run discovery/load and return
|
|
20407
|
-
// any notices (so a freshly added/edited plugin shows up without restarting).
|
|
20408
|
-
// `fresh: true` re-imports each file with a cache-busting query — without it the
|
|
20409
|
-
// ESM cache hands back the module instance from the previous load and an EDIT to
|
|
20410
|
-
// a plugin file would change nothing.
|
|
20411
|
-
reloadPlugins: async () => {
|
|
20412
|
-
const { loadPlugins, takePluginNotices } = await import('./plugin.js');
|
|
20413
|
-
await loadPlugins(cfg.pluginDir || undefined, { fresh: true });
|
|
20414
|
-
return takePluginNotices();
|
|
20415
|
-
},
|
|
20416
|
-
persistState,
|
|
20417
|
-
// `dispatch` is module-level and reloads the keybinding file after /keybindings edits it.
|
|
20418
|
-
// It cannot call this by name — the function is nested inside `startTUI` — so the same
|
|
20419
|
-
// indirection `renderFrame` below exists for. Without it, `/keybindings` threw
|
|
20420
|
-
// `refreshKeybindings is not defined` and killed the process, exactly as `submit` did.
|
|
20421
|
-
refreshKeybindings,
|
|
20422
|
-
startWeb,
|
|
20423
|
-
startWebGlobal: attachGlobalWeb,
|
|
20424
|
-
startWebGlobal: attachGlobalWeb,
|
|
20425
|
-
stopWeb,
|
|
20426
|
-
webInfo: () => web,
|
|
20427
|
-
// `dispatch` is module-level and was declared with a `renderFrame` parameter
|
|
20428
|
-
// that NONE of its four callers ever passed. That was harmless until /compact
|
|
20429
|
-
// started calling it, which threw "renderFrame is not a function". Reaching it
|
|
20430
|
-
// through `host` means a future caller cannot forget it again.
|
|
20431
|
-
renderFrame,
|
|
20432
|
-
|
|
20433
|
-
// ---- capabilities a plugin can drive -------------------------------------
|
|
20434
|
-
//
|
|
20435
|
-
// These forward to the SAME code the slash commands use, so a plugin cannot reach a
|
|
20436
|
-
// state the command could not: opening the tree runs the identical builder, and
|
|
20437
|
-
// switching the theme drops `lastFrame` the same way /theme does (without which the
|
|
20438
|
-
// differential painter would emit nothing and the screen would keep the old colours).
|
|
20439
|
-
|
|
20440
|
-
openFileTree(filter) {
|
|
20441
|
-
const cwd = state.cwd || cfg.workspace || process.cwd();
|
|
20442
|
-
let files = [];
|
|
20443
|
-
try { files = walkFiles(cwd, { includeIgnored: false }); } catch { return false; }
|
|
20444
|
-
const root = buildTree(files, cwd);
|
|
20445
|
-
if (!root.children.length) return false;
|
|
20446
|
-
const expanded = new Set();
|
|
20447
|
-
for (const c of root.children) if (c.dir) expanded.add(c.rel);
|
|
20448
|
-
state.fileTree = { root, expanded, sel: 0, scroll: 0, filter: String(filter || '').trim(), cwd };
|
|
20449
|
-
state.picker = null; state.form = null; state.panel = null; state.menuOpen = false;
|
|
20450
|
-
renderFrame();
|
|
20451
|
-
return true;
|
|
20452
|
-
},
|
|
20453
|
-
closeFileTree() {
|
|
20454
|
-
if (!state.fileTree) return;
|
|
20455
|
-
state.fileTree = null;
|
|
20456
|
-
state.hoverHit = null;
|
|
20457
|
-
renderFrame();
|
|
20458
|
-
},
|
|
20459
|
-
getTheme() { return state.theme || null; },
|
|
20460
|
-
setTheme(name) {
|
|
20461
|
-
if (!hasTheme(name)) return false;
|
|
20462
|
-
state.theme = name;
|
|
20463
|
-
setTheme(name);
|
|
20464
|
-
try { setConfigString('theme', name); } catch { /* the session still uses it */ }
|
|
20465
|
-
// The full repaint: see the same note in the /theme command.
|
|
20466
|
-
lastFrame = null;
|
|
20467
|
-
renderFrame();
|
|
20468
|
-
return true;
|
|
20469
|
-
},
|
|
20470
|
-
subagents() { return listRuns().map((r) => ({ id: r.agentId, runId: r.runId, taskId: r.taskId, type: r.type, description: r.description, startedAt: r.startedAt })); },
|
|
20471
|
-
messageSubagent(ref, text) { return sendToRun(ref, text); },
|
|
20472
|
-
interruptSubagent(ref) { return ref ? interruptRun(ref) : interruptAll(); },
|
|
20473
|
-
closeSubagent(ref) { return closeRun(ref); },
|
|
20474
|
-
isKeyBound(key) {
|
|
20475
|
-
const k = normalizeKey(key);
|
|
20476
|
-
if (!k) return false;
|
|
20477
|
-
// Three sources, and all three have to be checked or a plugin gets a wrong answer:
|
|
20478
|
-
// * the user's own keybindings file (a data structure);
|
|
20479
|
-
// * a plugin's claim from registerKeybind (also data);
|
|
20480
|
-
// * the BUILT-IN keys the TUI dispatches in its switch — not data, so the list
|
|
20481
|
-
// below is the subset a plugin would realistically take and silently break.
|
|
20482
|
-
if (keybindings.bindings.has(k)) return true;
|
|
20483
|
-
if (pluginKeybinds().some((kb) => kb.key === k)) return true;
|
|
20484
|
-
return BUILTIN_KEYS.has(k);
|
|
20485
|
-
},
|
|
20486
|
-
boundKeys() {
|
|
20487
|
-
const out = new Set([...keybindings.bindings.keys()]);
|
|
20488
|
-
for (const k of BUILTIN_KEYS) out.add(k);
|
|
20489
|
-
for (const kb of pluginKeybinds()) out.add(kb.key);
|
|
20490
|
-
return [...out];
|
|
20491
|
-
},
|
|
20492
|
-
};
|
|
20493
|
-
// The core's `dispatch` needs this object, and it is declared here rather than at the core
|
|
20494
|
-
// because a command's callbacks (`openPicker`, `openPanel`, …) are defined in this same
|
|
20495
|
-
// literal. Until this line runs, a command dispatched THROUGH THE CORE has no UI callbacks;
|
|
20496
|
-
// nothing dispatches before the TUI is fully built, so that window is not reachable.
|
|
20497
|
-
commandHost = host;
|
|
20498
|
-
|
|
20499
|
-
// Hand the full host surface to the plugin system so api.* can forward (sendPrompt,
|
|
20500
|
-
// openPanel, notice, getMessages, setConfig, ...). Done once, here, after `host` exists.
|
|
20501
|
-
(async () => { try { const { setPluginHost } = await import('./plugin.js'); setPluginHost(host); } catch {} })();
|
|
20502
|
-
|
|
20503
|
-
// Surface what the plugins did. `loadPlugins()` already ran (index.js, before the TUI
|
|
20504
|
-
// existed) and collected its notices, including any load failure — which previously went
|
|
20505
|
-
// only to stderr, invisible while the TUI owns the screen. A plugin that failed to load
|
|
20506
|
-
// simply did not appear, with nothing explaining why.
|
|
20507
|
-
void (async () => {
|
|
20508
|
-
try {
|
|
20509
|
-
const { takePluginNotices, runHooks } = await import('./plugin.js');
|
|
20510
|
-
// onStartup: plugins that want to greet / schedule / open a panel on launch.
|
|
20511
|
-
try { await runHooks('onStartup'); } catch (e) { console.error('[hncode-plugin] onStartup error:', e.message); }
|
|
20512
|
-
const notes = takePluginNotices();
|
|
20513
|
-
if (!notes.length) return;
|
|
20514
|
-
// ONE collapsible block instead of a wall of lines: a plugin set can emit
|
|
20515
|
-
// dozens of notices, which pushed the actual conversation off screen at
|
|
20516
|
-
// startup. Collapsed it is a single summary line; Ctrl+L expands it in place
|
|
20517
|
-
// (see the `c-l` handler next to the other Ctrl shortcuts).
|
|
20518
|
-
const icon = { error: '✗', warn: '!', info: '•' };
|
|
20519
|
-
const detail = notes.map((n) => `${icon[n.level] || '•'} plugin: ${n.text}`);
|
|
20520
|
-
const errs = notes.filter((n) => n.level === 'error').length;
|
|
20521
|
-
const first = notes[0];
|
|
20522
|
-
const summary = `plugin: ${first.text}`;
|
|
20523
|
-
const suffix = notes.length > 1
|
|
20524
|
-
? ` (+${notes.length - 1} more${errs ? `, ${errs} error${errs === 1 ? '' : 's'}` : ''} · ctrl+l)`
|
|
20525
|
-
: '';
|
|
20526
|
-
const msg = {
|
|
20527
|
-
role: notes.some((n) => n.level === 'error') ? 'aborted' : 'system',
|
|
20528
|
-
text: summary + suffix,
|
|
20529
|
-
// Collapsed by default; Ctrl+L flips `expanded` and the renderer prints
|
|
20530
|
-
// `allLines` instead of the single summary.
|
|
20531
|
-
pluginLog: true,
|
|
20532
|
-
expanded: false,
|
|
20533
|
-
allLines: detail,
|
|
20534
|
-
};
|
|
20535
|
-
state.chat.push(msg);
|
|
20536
|
-
renderFrame();
|
|
20537
|
-
} catch { /* notices are best-effort; never break startup */ }
|
|
20538
|
-
})();
|
|
20539
|
-
|
|
20540
|
-
// Appending streamed text can also add rows (the message wraps as it grows).
|
|
20541
|
-
// No arithmetic is needed here: renderChatLines() anchors the scrolled-up window
|
|
20542
|
-
// by row against the exact row count, so this only has to schedule a repaint.
|
|
20543
|
-
// Kept as a named hook because the streaming path calls it in several places.
|
|
20544
|
-
function anchorScroll() {
|
|
20545
|
-
renderSoon();
|
|
20546
|
-
}
|
|
20547
19643
|
// ---- paced streaming ------------------------------------------------------
|
|
20548
19644
|
// Answer and reasoning deltas are NOT painted as they arrive: they go into a
|
|
20549
19645
|
// StreamBuffer that drips them out at a smooth, time-paced rate. A provider that
|
|
@@ -20689,6 +19785,13 @@ function wheelStep(state, family) {
|
|
|
20689
19785
|
// * it ran exactly once. `needsTitle` only held on the very first turn, so a
|
|
20690
19786
|
// failure (offline, aborted, empty reply) left the session nameless forever.
|
|
20691
19787
|
// state.titleAttempts now allows a few retries on later turns.
|
|
19788
|
+
/** The shared naming rule lives in session.js — see `titleFromPrompt` there. */
|
|
19789
|
+
function titleFromPrompt(text) {
|
|
19790
|
+
// One implementation, in session.js: the headless CLI names its sessions by the same rule,
|
|
19791
|
+
// so a row in the terminal and a row in the window read the same for the same conversation.
|
|
19792
|
+
return sess.titleFromPrompt(text);
|
|
19793
|
+
}
|
|
19794
|
+
|
|
20692
19795
|
async function generateTitle(userText) {
|
|
20693
19796
|
const asked = String(userText || '').replace(/\s+/g, ' ').trim().slice(0, 400);
|
|
20694
19797
|
if (!asked) return;
|
|
@@ -20800,13 +19903,6 @@ function wheelStep(state, family) {
|
|
|
20800
19903
|
// The /tasks panel owns a flash timer; leaving it armed keeps the process
|
|
20801
19904
|
// alive until it fires after exit.
|
|
20802
19905
|
if (state.tasksPanel && state.tasksPanel.flashTimer) clearTimeout(state.tasksPanel.flashTimer);
|
|
20803
|
-
// Leaving the daemon registered would keep this session listed as "live" in
|
|
20804
|
-
// the browser until its heartbeat went stale. Deregistering now flips the page
|
|
20805
|
-
// to the read-only view straight away.
|
|
20806
|
-
if (webDaemon) {
|
|
20807
|
-
try { webDaemon.detach(); } catch { /* best-effort */ }
|
|
20808
|
-
webDaemon = null;
|
|
20809
|
-
}
|
|
20810
19906
|
try { sess.saveSession(session); } catch {}
|
|
20811
19907
|
stdout.write('\x1b[<u\x1b[?2004l\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l');
|
|
20812
19908
|
stdout.write(alternateScreen(false));
|
|
@@ -21008,35 +20104,6 @@ function quit() {
|
|
|
21008
20104
|
|
|
21009
20105
|
|
|
21010
20106
|
|
|
21011
|
-
// WEB UI (--web): same opt-in shape as --control. It starts AFTER the first
|
|
21012
|
-
// paint (the UI is already up by this point), and a failure is reported in the
|
|
21013
|
-
// transcript rather than killing the session — a port already in use must not
|
|
21014
|
-
// stop the user from working.
|
|
21015
|
-
if (opts.web && typeof opts.web === 'object') {
|
|
21016
|
-
try {
|
|
21017
|
-
const srv = await startWeb(opts.web.bindIp, opts.web.port);
|
|
21018
|
-
const lan = !srv.loopback;
|
|
21019
|
-
addChat({
|
|
21020
|
-
role: 'system',
|
|
21021
|
-
text: [
|
|
21022
|
-
`Web UI: ${srv.url}`,
|
|
21023
|
-
`Bind: ${srv.host}:${srv.port}${lan ? ' (reachable from the network)' : ' (this machine only)'}`,
|
|
21024
|
-
'',
|
|
21025
|
-
uiText('Access token (paste it into the login page):'),
|
|
21026
|
-
'',
|
|
21027
|
-
` ${srv.token}`,
|
|
21028
|
-
'',
|
|
21029
|
-
'Anyone with this token can run commands as you in this workspace.',
|
|
21030
|
-
'Stop the server with /web off.',
|
|
21031
|
-
].join('\n'),
|
|
21032
|
-
});
|
|
21033
|
-
renderFrame();
|
|
21034
|
-
} catch (e) {
|
|
21035
|
-
addChat({ role: 'warn', text: `Could not start the web UI: ${e.message}` });
|
|
21036
|
-
renderFrame();
|
|
21037
|
-
}
|
|
21038
|
-
}
|
|
21039
|
-
process.on('exit', () => { try { if (web) web.close(); } catch { /* already gone */ } });
|
|
21040
20107
|
|
|
21041
20108
|
|
|
21042
20109
|
// Keep the process alive for the whole session. startTUI is async and returns
|
|
@@ -21044,3 +20111,4 @@ function quit() {
|
|
|
21044
20111
|
// resolves immediately and Node exits (the "flash of UI then quit" bug).
|
|
21045
20112
|
return new Promise(() => {});
|
|
21046
20113
|
}
|
|
20114
|
+
//(注:内容由AI生成)
|