@hncode/hncode 0.8.5 → 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.
Files changed (159) hide show
  1. package/README.md +30 -0
  2. package/README_CN.md +27 -0
  3. package/package.json +1 -1
  4. package/src/agent.js +172 -43
  5. package/src/bootstrap.js +63 -56
  6. package/src/ci.js +247 -247
  7. package/src/colors.js +5 -1
  8. package/src/commands.js +121 -0
  9. package/src/composer.js +31 -1
  10. package/src/config.js +177 -45
  11. package/src/context.js +29 -0
  12. package/src/files.js +32 -0
  13. package/src/fx.js +19 -2
  14. package/src/i18n.js +180 -131
  15. package/src/index.js +558 -77
  16. package/src/permission-gate.js +103 -0
  17. package/src/plugin.js +221 -2
  18. package/src/prompt-presets.js +36 -0
  19. package/src/protocol.js +184 -0
  20. package/src/registry-browser.js +14 -3
  21. package/src/remote.js +117 -5
  22. package/src/schedule.js +148 -11
  23. package/src/serve.js +613 -0
  24. package/src/session-client.js +148 -0
  25. package/src/session-host.js +52 -0
  26. package/src/session.js +26 -3
  27. package/src/settings-schema.js +2 -2
  28. package/src/status-line.js +48 -0
  29. package/src/term.js +20 -1
  30. package/src/toml.js +18 -4
  31. package/src/tool-line.js +13 -6
  32. package/src/tool-status.js +45 -0
  33. package/src/tools/bash.js +43 -24
  34. package/src/tools/edit.js +10 -5
  35. package/src/tools/web-search.js +8 -5
  36. package/src/tools/write.js +28 -3
  37. package/src/tui.js +498 -1397
  38. package/src/ws.js +248 -0
  39. package/src/session-hub.js +0 -445
  40. package/src/web-auth.js +0 -98
  41. package/src/web-daemon-cli.js +0 -63
  42. package/src/web-daemon-client.js +0 -203
  43. package/src/web-daemon.js +0 -894
  44. package/src/web-live.js +0 -250
  45. package/src/web-public/app.css +0 -1524
  46. package/src/web-public/app.js +0 -2969
  47. package/src/web-public/complete.js +0 -154
  48. package/src/web-public/fonts/JetBrainsMono-Bold.woff2 +0 -0
  49. package/src/web-public/fonts/JetBrainsMono-Regular.woff2 +0 -0
  50. package/src/web-public/fonts/noto-sans-sc-100-400-normal.woff2 +0 -0
  51. package/src/web-public/fonts/noto-sans-sc-101-400-normal.woff2 +0 -0
  52. package/src/web-public/fonts/noto-sans-sc-102-400-normal.woff2 +0 -0
  53. package/src/web-public/fonts/noto-sans-sc-103-400-normal.woff2 +0 -0
  54. package/src/web-public/fonts/noto-sans-sc-104-400-normal.woff2 +0 -0
  55. package/src/web-public/fonts/noto-sans-sc-105-400-normal.woff2 +0 -0
  56. package/src/web-public/fonts/noto-sans-sc-106-400-normal.woff2 +0 -0
  57. package/src/web-public/fonts/noto-sans-sc-107-400-normal.woff2 +0 -0
  58. package/src/web-public/fonts/noto-sans-sc-108-400-normal.woff2 +0 -0
  59. package/src/web-public/fonts/noto-sans-sc-109-400-normal.woff2 +0 -0
  60. package/src/web-public/fonts/noto-sans-sc-110-400-normal.woff2 +0 -0
  61. package/src/web-public/fonts/noto-sans-sc-111-400-normal.woff2 +0 -0
  62. package/src/web-public/fonts/noto-sans-sc-112-400-normal.woff2 +0 -0
  63. package/src/web-public/fonts/noto-sans-sc-113-400-normal.woff2 +0 -0
  64. package/src/web-public/fonts/noto-sans-sc-114-400-normal.woff2 +0 -0
  65. package/src/web-public/fonts/noto-sans-sc-115-400-normal.woff2 +0 -0
  66. package/src/web-public/fonts/noto-sans-sc-116-400-normal.woff2 +0 -0
  67. package/src/web-public/fonts/noto-sans-sc-117-400-normal.woff2 +0 -0
  68. package/src/web-public/fonts/noto-sans-sc-118-400-normal.woff2 +0 -0
  69. package/src/web-public/fonts/noto-sans-sc-119-400-normal.woff2 +0 -0
  70. package/src/web-public/fonts/noto-sans-sc-21-400-normal.woff2 +0 -0
  71. package/src/web-public/fonts/noto-sans-sc-22-400-normal.woff2 +0 -0
  72. package/src/web-public/fonts/noto-sans-sc-23-400-normal.woff2 +0 -0
  73. package/src/web-public/fonts/noto-sans-sc-24-400-normal.woff2 +0 -0
  74. package/src/web-public/fonts/noto-sans-sc-25-400-normal.woff2 +0 -0
  75. package/src/web-public/fonts/noto-sans-sc-26-400-normal.woff2 +0 -0
  76. package/src/web-public/fonts/noto-sans-sc-27-400-normal.woff2 +0 -0
  77. package/src/web-public/fonts/noto-sans-sc-28-400-normal.woff2 +0 -0
  78. package/src/web-public/fonts/noto-sans-sc-29-400-normal.woff2 +0 -0
  79. package/src/web-public/fonts/noto-sans-sc-30-400-normal.woff2 +0 -0
  80. package/src/web-public/fonts/noto-sans-sc-31-400-normal.woff2 +0 -0
  81. package/src/web-public/fonts/noto-sans-sc-32-400-normal.woff2 +0 -0
  82. package/src/web-public/fonts/noto-sans-sc-33-400-normal.woff2 +0 -0
  83. package/src/web-public/fonts/noto-sans-sc-34-400-normal.woff2 +0 -0
  84. package/src/web-public/fonts/noto-sans-sc-35-400-normal.woff2 +0 -0
  85. package/src/web-public/fonts/noto-sans-sc-36-400-normal.woff2 +0 -0
  86. package/src/web-public/fonts/noto-sans-sc-37-400-normal.woff2 +0 -0
  87. package/src/web-public/fonts/noto-sans-sc-38-400-normal.woff2 +0 -0
  88. package/src/web-public/fonts/noto-sans-sc-39-400-normal.woff2 +0 -0
  89. package/src/web-public/fonts/noto-sans-sc-4-400-normal.woff2 +0 -0
  90. package/src/web-public/fonts/noto-sans-sc-40-400-normal.woff2 +0 -0
  91. package/src/web-public/fonts/noto-sans-sc-41-400-normal.woff2 +0 -0
  92. package/src/web-public/fonts/noto-sans-sc-42-400-normal.woff2 +0 -0
  93. package/src/web-public/fonts/noto-sans-sc-43-400-normal.woff2 +0 -0
  94. package/src/web-public/fonts/noto-sans-sc-44-400-normal.woff2 +0 -0
  95. package/src/web-public/fonts/noto-sans-sc-45-400-normal.woff2 +0 -0
  96. package/src/web-public/fonts/noto-sans-sc-46-400-normal.woff2 +0 -0
  97. package/src/web-public/fonts/noto-sans-sc-47-400-normal.woff2 +0 -0
  98. package/src/web-public/fonts/noto-sans-sc-48-400-normal.woff2 +0 -0
  99. package/src/web-public/fonts/noto-sans-sc-49-400-normal.woff2 +0 -0
  100. package/src/web-public/fonts/noto-sans-sc-5-400-normal.woff2 +0 -0
  101. package/src/web-public/fonts/noto-sans-sc-50-400-normal.woff2 +0 -0
  102. package/src/web-public/fonts/noto-sans-sc-51-400-normal.woff2 +0 -0
  103. package/src/web-public/fonts/noto-sans-sc-52-400-normal.woff2 +0 -0
  104. package/src/web-public/fonts/noto-sans-sc-53-400-normal.woff2 +0 -0
  105. package/src/web-public/fonts/noto-sans-sc-54-400-normal.woff2 +0 -0
  106. package/src/web-public/fonts/noto-sans-sc-55-400-normal.woff2 +0 -0
  107. package/src/web-public/fonts/noto-sans-sc-56-400-normal.woff2 +0 -0
  108. package/src/web-public/fonts/noto-sans-sc-57-400-normal.woff2 +0 -0
  109. package/src/web-public/fonts/noto-sans-sc-58-400-normal.woff2 +0 -0
  110. package/src/web-public/fonts/noto-sans-sc-59-400-normal.woff2 +0 -0
  111. package/src/web-public/fonts/noto-sans-sc-6-400-normal.woff2 +0 -0
  112. package/src/web-public/fonts/noto-sans-sc-60-400-normal.woff2 +0 -0
  113. package/src/web-public/fonts/noto-sans-sc-61-400-normal.woff2 +0 -0
  114. package/src/web-public/fonts/noto-sans-sc-62-400-normal.woff2 +0 -0
  115. package/src/web-public/fonts/noto-sans-sc-63-400-normal.woff2 +0 -0
  116. package/src/web-public/fonts/noto-sans-sc-64-400-normal.woff2 +0 -0
  117. package/src/web-public/fonts/noto-sans-sc-65-400-normal.woff2 +0 -0
  118. package/src/web-public/fonts/noto-sans-sc-66-400-normal.woff2 +0 -0
  119. package/src/web-public/fonts/noto-sans-sc-67-400-normal.woff2 +0 -0
  120. package/src/web-public/fonts/noto-sans-sc-68-400-normal.woff2 +0 -0
  121. package/src/web-public/fonts/noto-sans-sc-69-400-normal.woff2 +0 -0
  122. package/src/web-public/fonts/noto-sans-sc-70-400-normal.woff2 +0 -0
  123. package/src/web-public/fonts/noto-sans-sc-71-400-normal.woff2 +0 -0
  124. package/src/web-public/fonts/noto-sans-sc-72-400-normal.woff2 +0 -0
  125. package/src/web-public/fonts/noto-sans-sc-73-400-normal.woff2 +0 -0
  126. package/src/web-public/fonts/noto-sans-sc-74-400-normal.woff2 +0 -0
  127. package/src/web-public/fonts/noto-sans-sc-75-400-normal.woff2 +0 -0
  128. package/src/web-public/fonts/noto-sans-sc-76-400-normal.woff2 +0 -0
  129. package/src/web-public/fonts/noto-sans-sc-77-400-normal.woff2 +0 -0
  130. package/src/web-public/fonts/noto-sans-sc-78-400-normal.woff2 +0 -0
  131. package/src/web-public/fonts/noto-sans-sc-79-400-normal.woff2 +0 -0
  132. package/src/web-public/fonts/noto-sans-sc-80-400-normal.woff2 +0 -0
  133. package/src/web-public/fonts/noto-sans-sc-81-400-normal.woff2 +0 -0
  134. package/src/web-public/fonts/noto-sans-sc-82-400-normal.woff2 +0 -0
  135. package/src/web-public/fonts/noto-sans-sc-83-400-normal.woff2 +0 -0
  136. package/src/web-public/fonts/noto-sans-sc-84-400-normal.woff2 +0 -0
  137. package/src/web-public/fonts/noto-sans-sc-85-400-normal.woff2 +0 -0
  138. package/src/web-public/fonts/noto-sans-sc-86-400-normal.woff2 +0 -0
  139. package/src/web-public/fonts/noto-sans-sc-87-400-normal.woff2 +0 -0
  140. package/src/web-public/fonts/noto-sans-sc-88-400-normal.woff2 +0 -0
  141. package/src/web-public/fonts/noto-sans-sc-89-400-normal.woff2 +0 -0
  142. package/src/web-public/fonts/noto-sans-sc-90-400-normal.woff2 +0 -0
  143. package/src/web-public/fonts/noto-sans-sc-91-400-normal.woff2 +0 -0
  144. package/src/web-public/fonts/noto-sans-sc-97-400-normal.woff2 +0 -0
  145. package/src/web-public/fonts/noto-sans-sc-98-400-normal.woff2 +0 -0
  146. package/src/web-public/fonts/noto-sans-sc-99-400-normal.woff2 +0 -0
  147. package/src/web-public/fonts/noto-sans-sc.css +0 -775
  148. package/src/web-public/fonts.css +0 -31
  149. package/src/web-public/home.css +0 -222
  150. package/src/web-public/home.html +0 -33
  151. package/src/web-public/home.js +0 -160
  152. package/src/web-public/i18n.js +0 -983
  153. package/src/web-public/index.html +0 -196
  154. package/src/web-public/login.css +0 -123
  155. package/src/web-public/login.html +0 -25
  156. package/src/web-public/login.js +0 -46
  157. package/src/web-public/settings.js +0 -290
  158. package/src/web-ws.js +0 -226
  159. 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 { decideFromRules, describeRules, selfTestRules, describeSelfTest } from './permissions.js';
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, isApprovedForSession, rememberApproval, describeSessionApprovals } from './session-approvals.js';
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
- export const COMMANDS = [
356
- { name: 'yolo', aliases: ['yes'], desc: 'Yolo mode: anything inside the workspace (edits, writes, commands) runs automatically; paths outside it, destructive commands, questions and plans still ask.', priority: 101 },
357
- { name: 'permission', desc: 'Select permission mode', priority: 100 },
358
- { name: 'settings', aliases: ['config'], desc: 'Browse and change every setting, grouped by area', priority: 100, argumentHint: '[tab|filter]' },
359
- { name: 'set', desc: 'Set one config value by key, or list what differs from the default', priority: 100, argumentHint: '[<key> [value]]' },
360
- { name: 'sampling', desc: 'Show or set temperature, top_p and presence_penalty', priority: 100, argumentHint: '[on|off|temperature <n>|top_p <n>|presence_penalty <n>]' },
361
- { name: 'plan', desc: 'Toggle plan mode', priority: 100, argumentHint: '[on|off|clear]' },
362
- { name: 'websearch-api', desc: 'Edit the WebSearch API keys (one per line, tried in order)', priority: 96 },
363
- { name: 'focus', desc: 'Toggle Focus mode (minimal tools first, full tools after)', priority: 98, argumentHint: '[on|off]' },
364
- { name: 'auto', desc: 'Auto mode: never interrupts you; everything runs and is decided automatically.', priority: 99 },
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
- // itself errored. Detected from the tool-result text (the only place the code
1344
- // survives for the UI, since the exit-code line is hidden from display).
1345
- // Failure prefixes that the built-in tools actually return (verified against
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
 
@@ -1469,9 +1315,23 @@ function messageLines(msg, width, workspace, expanded, spin, pulseStart, rawMode
1469
1315
  // is not a continuation and gets no mark — the break is already unmistakable.
1470
1316
  const wrapped = [];
1471
1317
  for (const segment of segments) {
1472
- const parts = wrapAnsiWords(segment, bodyW);
1318
+ // THE CONTINUATION MARK NEEDS A COLUMN OF ITS OWN, AND ONLY ONCE.
1319
+ //
1320
+ // `parts[i]` fills the row exactly, so appending `…` made the row ONE COLUMN WIDER than
1321
+ // the terminal. The terminal then wraps it itself, taking two display rows where this
1322
+ // function counted one — and every row below shifts by one, which is why the offset
1323
+ // moved around instead of being a constant.
1324
+ //
1325
+ // And only when the segment does not already end in one: `keyArgument` truncates the
1326
+ // argument it was handed, so a wrapped command could come out `… …` — two marks and a
1327
+ // space between them, on a row that was already at its limit.
1328
+ const willBreak = visualCol(segment) > bodyW;
1329
+ const room = willBreak ? Math.max(1, bodyW - 1) : bodyW;
1330
+ const parts = wrapAnsiWords(segment, room);
1473
1331
  for (let i = 0; i < parts.length; i++) {
1474
- wrapped.push(i < parts.length - 1 ? parts[i] + col('…', C.gray) : parts[i]);
1332
+ const last = i === parts.length - 1;
1333
+ const alreadyMarked = /…\s*$/.test(stripAnsi(parts[i]));
1334
+ wrapped.push(last || alreadyMarked ? parts[i] : parts[i] + col('…', C.gray));
1475
1335
  }
1476
1336
  }
1477
1337
  const out = wrapped.map((t, i) => ({
@@ -2418,7 +2278,6 @@ export function renderChatLines(state, w, viewport) {
2418
2278
  }
2419
2279
  const total = cursor;
2420
2280
  state._chatTotal = total;
2421
- state._chatTotal = total;
2422
2281
  // Memo for the count-only caller (scrollChat). These metrics do NOT depend on
2423
2282
  // `scroll`, only on the transcript and the layout, so they stay valid until one
2424
2283
  // of those changes. scrollChat used to call the FULL renderer — with no viewport
@@ -2907,12 +2766,8 @@ export function refreshCost(state, cfg) {
2907
2766
  // The currency the cost readouts use, from config.toml (`cost_currency`), the
2908
2767
  // environment, or USD. Persisted by `/cost usd|cny`, so the switch survives a
2909
2768
  // restart and the status row follows it.
2910
- export function costCurrency(cfg) {
2911
- const fromEnv = normalizeCurrency(process.env.HNCODE_COST_CURRENCY);
2912
- if (fromEnv) return fromEnv;
2913
- const raw = cfg && ((cfg.raw && cfg.raw.cost_currency) ?? cfg.costCurrency);
2914
- return normalizeCurrency(raw) || 'USD';
2915
- }
2769
+ // ONE IMPLEMENTATION, in fx.js: the window and the cost endpoint ask the same question.
2770
+ export { costCurrency };
2916
2771
 
2917
2772
  // (Number, money and time formatting live in src/format.js.)
2918
2773
 
@@ -3609,7 +3464,6 @@ export function resolveHoverHit(state, hitboxes) {
3609
3464
  export function refreshGitInfo(state, opts = {}) {
3610
3465
  const cwd = state.cwd || state.workspace || '';
3611
3466
  if (!cwd) return;
3612
- if (!cwd) return;
3613
3467
  const now = Date.now();
3614
3468
  const force = opts.force === true;
3615
3469
  // Mid-turn the agent is about to write more files, so a POLL would only produce a value that is
@@ -3640,34 +3494,6 @@ export function refreshGitInfo(state, opts = {}) {
3640
3494
  if (typeof state._requestRender === 'function') state._requestRender();
3641
3495
  });
3642
3496
  }
3643
- /**
3644
- * Tokens per content type, and how many messages of each kind there are.
3645
- *
3646
- * Shared by `/context` (which prints the table) and by the status bar's bar (which draws
3647
- * it), so the two can never disagree about what is being counted.
3648
- */
3649
- export function contextBreakdown(session, cfg) {
3650
- // `cfg` is optional because the render path reaches this through `state.cfg`, and a state
3651
- // built directly (several tests do) has no `cfg` at all. An absent config must not take
3652
- // the frame down; it only means the tool-definition count falls back to the full list.
3653
- const conf = cfg || {};
3654
- const byRole = { system: 0, user: 0, assistant: 0, tool: 0, other: 0 };
3655
- const countByRole = { system: 0, user: 0, assistant: 0, tool: 0, other: 0 };
3656
- for (const m of ((session && session.messages) || [])) {
3657
- // Per-message estimator, memoised: `estimateMessagesTokens([m])` re-ran the whole message
3658
- // loop for a single-element array, which on a long transcript made /context O(n²). The
3659
- // memo means re-opening /context — or opening it after the bar already priced these
3660
- // messages — is a WeakMap hit per message instead of a fresh walk of every tool body.
3661
- const t = messageTokens(m, conf);
3662
- const r = (m.role === 'system' || m.role === 'user' || m.role === 'assistant' || m.role === 'tool') ? m.role : 'other';
3663
- byRole[r] += t;
3664
- countByRole[r] += 1;
3665
- }
3666
- // Tool definitions ride every request (name + schema), priced here the same way
3667
- // usedTokens() prices them.
3668
- const toolCount = Array.isArray(conf.toolFilter) ? conf.toolFilter.length : (toolNames().length);
3669
- return { byRole, countByRole, toolDefTokens: toolCount * 8, toolCount };
3670
- }
3671
3497
 
3672
3498
  /**
3673
3499
  * The same breakdown in the shape the bar draws it, CACHED.
@@ -4452,7 +4278,6 @@ const queueH = takeover ? 0 : queuePanelHeight(state);
4452
4278
  //
4453
4279
  // It used to pass the transcript index here while the loop still walked the whole transcript, so the
4454
4280
  // rail was drawn from the geometry of the FIRST `bodyH` rows of the conversation and every row actually
4455
- // rail was drawn from the geometry of the FIRST `bodyH` rows of the conversation and every row actually
4456
4281
  // on screen fell outside that range — the bar came out blank as soon as the transcript was scrolled off
4457
4282
  // the top, i.e. in the normal case, and only appeared when the window happened to start at row 0.
4458
4283
  if (sb && screenRow >= 0 && screenRow < bodyH) {
@@ -5629,19 +5454,15 @@ const queueH = takeover ? 0 : queuePanelHeight(state);
5629
5454
  // AND the model must have prices (its own entry or the models.dev catalog). Either one
5630
5455
  // missing would mean inventing the number, so it is omitted rather than shown as `0$`,
5631
5456
  // which reads as "this was free".
5632
- const costSeg = state._costText ? `${state._costText} ${uiText('cost')} | ` : '';
5633
- // THE TALLIES ARE COUNTED NOUNS, so they go through `tr` rather than `uiText`: a template
5634
- // 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.
5635
5459
  const countsRight = col(
5636
- `${costSeg}`
5637
- + (state.rounds === 1
5638
- ? tr('status.turnsOne', '{n} turn', { n: state.rounds })
5639
- : tr('status.turns', '{n} turns', { n: state.rounds }))
5640
- + ' | '
5641
- + (state.steps === 1
5642
- ? tr('status.stepsOne', '{n} step', { n: state.steps })
5643
- : tr('status.steps', '{n} steps', { n: state.steps }))
5644
- + ` | ${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
+ }),
5645
5466
  C.white,
5646
5467
  );
5647
5468
  const statusRight = countsRight;
@@ -6392,7 +6213,6 @@ export function makeState({ cfg, session, opts }) {
6392
6213
  // only `(state, cols, rows)` and has no closure over startTUI's locals.
6393
6214
  session: session || null,
6394
6215
  provider: cfg.provider || '',
6395
- provider: cfg.provider || '',
6396
6216
  model: cfg.model || '',
6397
6217
  // REDUCED MOTION and the sweep-edge shape are copied onto the STATE, not read
6398
6218
  // from `cfg` at render time: `composeFrame(state, …)` only receives the state,
@@ -6518,8 +6338,13 @@ export function makeState({ cfg, session, opts }) {
6518
6338
  mentionList: [],
6519
6339
  mentionSel: 0,
6520
6340
  mentionOffset: 0,
6521
- objective: '',
6522
- goalPaused: false,
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',
6523
6348
  plan: !!(session && session.plan),
6524
6349
  planPath: (session && session.planPath) || null,
6525
6350
  focus: !!(session && session.focus),
@@ -6580,6 +6405,9 @@ export function makeState({ cfg, session, opts }) {
6580
6405
  _costText: null, // the amount as printed, in the display currency
6581
6406
  _costCurrency: 'USD',
6582
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,
6583
6411
  };
6584
6412
  }
6585
6413
 
@@ -7131,7 +6959,9 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
7131
6959
  if (key === 'calm_mode') cfg.calmMode = v;
7132
6960
  if (key === 'title_display') cfg.titleDisplay = v;
7133
6961
  if (key === 'auto_title') cfg.autoTitle = v;
7134
- if (key === 'swarm_mode') cfg.swarm = v;
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.
7135
6965
  if (key === 'tool_allow_external_paths') cfg.allowExternal = v;
7136
6966
  if (key === 'sampling' && !v) {
7137
6967
  // Off means NONE of them is sent — not their defaults, which is what a provider rejecting them
@@ -8035,6 +7865,9 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
8035
7865
  state.ctxMax = cfg.maxContextTokens || state.ctxMax;
8036
7866
  state.tokRate = 0;
8037
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;
8038
7871
  // The spend belongs to the session that is ending, so a new session starts
8039
7872
  // from zero. The session object is reused, so `usage` must be CLEARED here
8040
7873
  // rather than just left out.
@@ -8127,6 +7960,14 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
8127
7960
  state.rounds = session.rounds || 0;
8128
7961
  state.steps = session.steps || 0;
8129
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() : [];
8130
7971
  // The resumed session may live in another directory, and EVERY tool path
8131
7972
  // resolves against it (`resolvePath` uses `ctx.cwd || ctx.workspace`,
8132
7973
  // and the agent copies `cfg` into `ctx` each turn). Updating only
@@ -8183,21 +8024,18 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
8183
8024
  }
8184
8025
  case 'swarm': {
8185
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.
8186
8032
  const a = raw.toLowerCase();
8187
8033
  let want;
8188
8034
  if (a === 'on') want = true;
8189
8035
  else if (a === 'off') want = false;
8190
8036
  else want = !state.swarm;
8191
8037
  state.swarm = want;
8192
- // Plan / Focus / Swarm are one mutually exclusive group: turning one on
8193
- // turns the other two off.
8194
8038
  if (want) { state.plan = false; state.focus = false; }
8195
- // A write that fails SILENTLY still shows the success message below, so the user believes the setting
8196
- // stuck and it comes back wrong after a restart.
8197
- try { setConfigString('swarm_mode', want ? 'true' : 'false'); } catch (e) {
8198
- appErr(`Could not save this setting: ${e.message}. It applies to this session only.`);
8199
- }
8200
- cfg.raw.swarm_mode = want;
8201
8039
  app(want
8202
8040
  ? uiText('Swarm mode ON - the model will decompose work across parallel subagents (AgentSwarm)')
8203
8041
  : 'Swarm mode OFF');
@@ -8565,7 +8403,7 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
8565
8403
  saveSession(session);
8566
8404
  // Same formula as everywhere else: messages PLUS the tool schemas.
8567
8405
  state.tokens = estimateMessagesTokens(session.messages, cfg) + (cfg.toolDefTokens || 0);
8568
- if (!state.ctxReportedOnce) state.ctxTokens = state.tokens;
8406
+ sessHost.noteCtxAfterShrink(state.tokens);
8569
8407
  // Same rule as everywhere else: the percentage comes from the number the row prints, not from the
8570
8408
  // estimate. Using `state.tokens` here made a compacted session show `696k/1M` beside 57%.
8571
8409
  state.ctxPercent = usagePercent(state.ctxTokens, state.ctxMax || maxCtx);
@@ -8906,77 +8744,6 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
8906
8744
  return;
8907
8745
  }
8908
8746
 
8909
- case 'web': {
8910
- // Publish this session to the browser through the MACHINE-WIDE web UI.
8911
- //
8912
- // There is one daemon per machine, on the fixed port from config.toml, and
8913
- // it is what the user opens: it lists every workspace and every session —
8914
- // the running ones live, the finished ones read from disk. This command
8915
- // brings up this session's own server and registers it there; if the daemon
8916
- // is already up it is REUSED rather than restarted, which is the whole point
8917
- // of a stable address and a stable token.
8918
- const a = raw.trim();
8919
- if (a.toLowerCase() === 'off' || a.toLowerCase() === 'stop') {
8920
- app(h.stopWeb() ? uiText('Web UI stopped (this session is no longer listed).') : uiText('Web UI is not running.'));
8921
- return;
8922
- }
8923
- if (!h.startWebGlobal) { appErr(uiText('Web UI is unavailable in this build.')); return; }
8924
- // Optional "[bindIp] [port]" — the same shapes `--web` accepts. The old
8925
- // code threw these away and always bound loopback, so `/web 0.0.0.0` looked
8926
- // like it worked while nothing was reachable from the network.
8927
- let bindArg, portArg;
8928
- if (a) {
8929
- const parts = a.split(/\s+/);
8930
- if (/^\d+$/.test(parts[0])) portArg = Number(parts[0]);
8931
- else bindArg = parts[0];
8932
- if (parts[1] && /^\d+$/.test(parts[1])) portArg = Number(parts[1]);
8933
- }
8934
- say('Starting the web UI…');
8935
- h.startWebGlobal(bindArg, portArg).then(({ srv, daemon, token }) => {
8936
- if (!daemon) {
8937
- // The daemon could not be reached or started. The session's own server
8938
- // is still up, so report THAT rather than pretending /web failed.
8939
- sayPanel([
8940
- `Web UI (this session only): ${srv.url}`,
8941
- '',
8942
- uiText('The machine-wide daemon is unavailable, so this session is served'),
8943
- 'directly. Open the address above; the token is below.',
8944
- '',
8945
- ` ${srv.token}`,
8946
- ].join('\n'));
8947
- notice(`Web UI on ${srv.url} (daemon unavailable)`, 'error');
8948
- return;
8949
- }
8950
- const lan = daemon.host && daemon.host !== '127.0.0.1' && daemon.host !== 'localhost';
8951
- sayPanel([
8952
- `Web UI: ${daemon.rootUrl}`,
8953
- `Session: ${daemon.url}`,
8954
- `Bind: ${daemon.host}:${daemon.port}${lan ? ' (reachable from the network)' : ' (this machine only)'}`,
8955
- daemon.spawned ? 'Daemon: started (was not running)' : 'Daemon: reused (already running)',
8956
- '',
8957
- uiText('The root page lists every workspace and session — running ones live,'),
8958
- 'finished ones from disk. The token below is stored in config.toml, so',
8959
- 'it stays the same across restarts.',
8960
- '',
8961
- uiText('Access token (paste it into the login page):'),
8962
- '',
8963
- ` ${token || srv.token}`,
8964
- '',
8965
- uiText('Anyone with this token can run commands as you. Stop this session with'),
8966
- '/web off.',
8967
- ].join('\n'));
8968
- notice(`Web UI at ${daemon.rootUrl}`);
8969
- }).catch((e) => {
8970
- appErr(`Could not start the web UI: ${e.message}`);
8971
- });
8972
- return;
8973
- }
8974
-
8975
-
8976
-
8977
-
8978
-
8979
-
8980
8747
  case 'calm-mode': {
8981
8748
  // Terse-output mode: while ON, an instruction is injected with each request
8982
8749
  // telling the model not to narrate what it is about to do or why, unless
@@ -9050,7 +8817,9 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
9050
8817
  sendPrompt('Resume the active goal.');
9051
8818
  return;
9052
8819
  }
9053
- if (a === uiText('cancel')) { applyGoal('', false); app(uiText('Goal cancelled.')); return; }
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; }
9054
8823
  if (a.startsWith('replace ')) { applyGoal(raw.slice(8).trim(), false); app(uiText('Goal replaced.')); return; }
9055
8824
  applyGoal(raw, false);
9056
8825
  app(`Goal set: ${raw}`);
@@ -9084,9 +8853,10 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
9084
8853
  [tr('tui.help.groupEveryday', 'Everyday'), ['settings', 'set', 'model', 'provider', 'permission', 'yolo', 'lang']],
9085
8854
  [tr('tui.help.groupSession', 'Session'), ['new', 'sessions', 'all-sessions', 'resume', 'save', 'export', 'compact', 'goal', 'init', 'jump']],
9086
8855
  [tr('tui.help.groupContext', 'Context'), ['context', 'tokens', 'usage', 'cost', 'memory', 'personal', 'output-style']],
9087
- [tr('tui.help.groupWork', 'Work'), ['plan', 'focus', 'swarm', 'team', 'btw', 'tasks']],
8856
+ [tr('tui.help.groupWork', 'Work'), ['plan', 'focus', 'swarm', 'goal', 'team', 'btw', 'tasks']],
9088
8857
  [tr('tui.help.groupExtend', 'Extend'), ['skills', 'plugins', 'import-skill', 'plugin-manager']],
9089
8858
  [tr('tui.help.groupDiagnostics', 'Diagnostics'), ['doctor', 'status', 'version', 'raw', 'reduced-motion', 'help']],
8859
+ [tr('tui.help.groupKeys', 'Keys'), ['keybindings']],
9090
8860
  ];
9091
8861
  const byName = new Map(localizedCommands().map((c) => [c.name, c]));
9092
8862
  const shown = new Set();
@@ -10174,7 +9944,7 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
10174
9944
  //
10175
9945
  // Plus the tool schemas, like every other writer: `/trim` counts messages, and the request also
10176
9946
  // carries the tools, so leaving them out dropped the gauge by that much more than was freed.
10177
- if (!state.ctxReportedOnce) state.ctxTokens = after + (cfg.toolDefTokens || 0);
9947
+ sessHost.noteCtxAfterShrink(after + (cfg.toolDefTokens || 0));
10178
9948
  state.ctxPercent = usagePercent(state.ctxTokens, state.ctxMax || cfg.maxContextTokens || 1);
10179
9949
  if (session) {
10180
9950
  try {
@@ -10465,8 +10235,6 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
10465
10235
  return;
10466
10236
  }
10467
10237
 
10468
- case 'keybindings': {
10469
- }
10470
10238
  case 'keybindings': {
10471
10239
  // Bindings live in ~/.hncode/keybindings.json; this is the editing entry point.
10472
10240
  // A binding names a target the key dispatcher ALREADY understands (another key) or
@@ -11128,6 +10896,9 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
11128
10896
  state.modelLabel = modelLabel(cfg) || cfg.model || '';
11129
10897
  state.reasoning = !!cfg.reasoning;
11130
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);
11131
10902
  if (cfg.raw && cfg.raw.theme) { state.theme = cfg.raw.theme; setTheme(state.theme); }
11132
10903
  const beforeMax = state.ctxMax;
11133
10904
  state.ctxMax = cfg.maxContextTokens || state.ctxMax;
@@ -11156,6 +10927,8 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
11156
10927
  state.modelLabel = modelLabel(cfg) || cfg.model || '';
11157
10928
  state.reasoning = !!cfg.reasoning;
11158
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);
11159
10932
  if (cfg.raw && cfg.raw.theme) { state.theme = cfg.raw.theme; setTheme(state.theme); }
11160
10933
  const beforeMax = state.ctxMax;
11161
10934
  state.ctxMax = cfg.maxContextTokens || state.ctxMax;
@@ -11565,6 +11338,23 @@ export async function dispatch(cmdRaw, arg, state, cfg, session, h, submit, stdo
11565
11338
  : uiText('Prompt caching disabled — every request sends the full prompt as fresh input.'));
11566
11339
  return;
11567
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
+ }
11568
11358
  case 'worktree': {
11569
11359
  const cwd = state.cwd || cfg.workspace || process.cwd();
11570
11360
  if (!gitmod.isRepo(cwd)) { appErr(`Not a git repository: ${cwd}`); return; }
@@ -12043,6 +11833,27 @@ function commandPathsAreInside(state, cmd, cwd) {
12043
11833
  }
12044
11834
  return true;
12045
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
+
12046
11857
  function applyModel(state, cfg, next) {
12047
11858
  cfg.model = next.model; cfg.innerModel = next.innerModel; cfg.provider = next.provider;
12048
11859
  cfg.baseUrl = next.baseUrl; cfg.endpoint = next.endpoint; cfg.apiKey = next.apiKey; cfg.protocol = next.protocol;
@@ -12063,6 +11874,9 @@ function applyModel(state, cfg, next) {
12063
11874
  // Accumulating dollars per event instead would price every earlier request at
12064
11875
  // whatever model happened to be active at the time — which is not what the
12065
11876
  // session total means.
11877
+ // The level belongs to its model, so a switch can invalidate it (see dropUnsupportedEffort).
11878
+ dropUnsupportedEffort(state, cfg);
11879
+
12066
11880
  refreshCost(state, cfg);
12067
11881
  try { if (cfg.model) rememberModel(cfg.model); } catch {}
12068
11882
  }
@@ -12594,10 +12408,21 @@ export function csiName(params, fin) {
12594
12408
  //
12595
12409
  // `viewArg` overrides `deps.view` for one call, which is how a caller holding both a terminal and
12596
12410
  // a browser reaches the right one per turn.
12597
- async function runTurn(deps, text, opts = {}, viewArg) {
12411
+ export async function runTurn(deps, text, opts = {}, viewArg) {
12598
12412
  const { state, cfg, session, host, spawn } = deps;
12599
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;
12600
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
+ }
12601
12426
  // Drop any compaction row left dangling by an interrupted turn so the next
12602
12427
  // auto-compaction starts clean (no ghost 'running' row that blinks with nothing
12603
12428
  // behind it). The live reference is dropped too.
@@ -12632,6 +12457,18 @@ async function runTurn(deps, text, opts = {}, viewArg) {
12632
12457
  const needsTitle = !!session && cfg.autoTitle !== false
12633
12458
  && !session.title && state.titleAttempts < TITLE_ATTEMPT_LIMIT;
12634
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
+ }
12635
12472
  state.running = true;
12636
12473
  // Pick the Working… wording ONCE for this turn, so it does not change while
12637
12474
  // the gradient loops. The next turn picks a new one.
@@ -12824,6 +12661,38 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
12824
12661
  else if (isSkill && !argsText) { /* body-only activation: nothing for the user turn */ }
12825
12662
  else messages.push({ role: 'user', content: opts.modelText != null ? opts.modelText : (argsText || text) });
12826
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
+
12827
12696
  // What the TEAM has said to the lead since the last turn.
12828
12697
  //
12829
12698
  // The lead is this session, and its inbox is the only channel an agent has for reaching
@@ -12872,6 +12741,28 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
12872
12741
  session.steps = state.steps || session.steps;
12873
12742
  session.todos = state.todos || session.todos;
12874
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 */ }
12875
12766
  // `saveSessionSoon`: this runs at every STEP boundary, which makes it the hottest save in the program. The
12876
12767
  // synchronous version spent 38ms of `JSON.stringify` plus a 1.3 MB write on a session that size — a stall the user
12877
12768
  // sees as the interface freezing between a tool finishing and the next thing appearing, and it is paid again at
@@ -12917,6 +12808,10 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
12917
12808
 
12918
12809
  // Approval callback: called before every tool execution
12919
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);
12920
12815
  // Read the mode LIVE: /permission, /yolo and /auto can change while the
12921
12816
  // turn runs, and the decision must follow the CURRENT setting.
12922
12817
  const cur = state.mode || 'ask';
@@ -12935,106 +12830,16 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
12935
12830
 
12936
12831
 
12937
12832
 
12938
- // Standing rules come FIRST, before every mode rule, so:
12939
- // * a `deny` cannot be escaped by switching to Auto / Yolo;
12940
- // * an explicit `ask` still prompts even in a mode that auto-approves;
12941
- // * an `allow` spares the user the same prompt on every turn.
12942
- const rule = decideFromRules(cfg.permissions, toolName, args);
12943
- if (rule === 'deny') {
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') {
12944
12839
  viewCur.err(`${toolName} is blocked by a permission rule (deny).`);
12945
12840
  return false;
12946
12841
  }
12947
- // A destructive Bash command is never auto-approved, not even by an `allow`
12948
- // rule — a rule is written for the command the user had in mind, and a line
12949
- // can carry a second command the rule never described. `ruleMatches` splits
12950
- // segments for the same reason; this is the second half of that guard, for
12951
- // commands where no rule matched at all.
12952
- const destructive = toolName === 'Bash'
12953
- && isDestructiveCommand(String((args && (args.command || args.cmd)) || ''));
12954
- if (rule === 'allow' && !destructive) return true;
12955
- // `ask` falls through to the prompt below, skipping the mode shortcuts.
12956
-
12957
- // AUTO MODE ANSWERS HERE, and it answers everything.
12958
- //
12959
- // The mode means "nothing asks": the user has already said they do not want to be interrupted
12960
- // for this session. So nothing below may send them a prompt — not a destructive-looking
12961
- // command, not a heuristic that misfired. Getting this wrong is worse than the risk it guards
12962
- // against, because a mode that claims to ask nothing and then asks anyway teaches the user to
12963
- // hold down Enter, which destroys the value of every prompt that follows.
12964
- //
12965
- // `deny` above is checked BEFORE this and still wins, which is the one answer that is meant to
12966
- // hold regardless of mode — the user wrote that rule down deliberately.
12967
- //
12968
- // An explicit `ask` rule is checked just above and skips this, because a rule naming a command
12969
- // to ask about is also deliberate, and it outranks a mode chosen in a menu.
12970
- if (rule !== 'ask' && cur === 'auto') return true;
12971
- // Session approvals (Ctrl+A on a prompt) come AFTER the configured rules and BEFORE the mode
12972
- // shortcuts:
12973
- // * after, so a `deny` or an explicit `ask` rule still wins — a transient grant must not
12974
- // override a decision the user wrote down;
12975
- // * before, so an approval covers the modes that would otherwise ask again.
12976
- //
12977
- // `destructive` is passed in because the approval is keyed on it: approving one `rm -rf build`
12978
- // must not silently cover every later command that looks similar.
12979
- if (rule !== 'ask' && isApprovedForSession(session.sessionApprovals, toolName, args, destructive)) {
12980
- return true;
12981
- }
12982
- // Read-only tools never need permission in any mode. AskUserQuestion is on
12983
- // this list because ASKING the user is not a side effect — gating it behind
12984
- // an approval prompt would mean answering two prompts to ask one question.
12985
- // (In auto mode the TOOL refuses itself before any UI; see ctx.permissionMode.)
12986
- // Tools that act ONLY inside the session: the roster, the mailbox, the task list, the memories.
12987
- // `isInsideWorkspace` answers `false` for any tool it does not know, so without this they all asked for
12988
- // approval in yolo — the one mode whose point is not asking.
12989
- // A PLUGIN'S TOOL ANSWERS FOR ITSELF.
12990
- //
12991
- // The list below covers the tools this program ships. A plugin's tools cannot be added to it from outside,
12992
- // and `isInsideWorkspace` does not know them — so every one of them asked for approval whatever it did. A
12993
- // spec declaring `autoApprove: true` now says so itself, which is the only place that knows whether the
12994
- // tool touches anything.
12995
- if (rule !== 'ask') {
12996
- const own = getTool(toolName);
12997
- if (own && own.autoApprove === true) return true;
12998
- }
12999
- 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'];
13000
- if (rule !== 'ask' && safeTools.includes(toolName)) return true;
13001
- // A read-only SHELL COMMAND (ls/git status/rg/cat …) is as safe as a
13002
- // read-only TOOL, so it runs without a prompt in Ask mode too — the user
13003
- // has no decision to make about `git log`. Only in `ask`; an explicit
13004
- // `ask` rule above still wins, and YOLO/AUTO never reach here anyway.
13005
- if (cur === 'ask' && rule !== 'ask' && toolName === 'Bash') {
13006
- const c = String((args && (args.command || args.cmd)) || '');
13007
- if (isReadOnlyCommand(c) && !isDestructiveCommand(c)) return true;
13008
- }
13009
-
13010
-
13011
- // ASK: an ordinary action runs, anything with a consequence asks.
13012
- //
13013
- // This is the only mode that gates FILE work, which is the point of it — the other two exist for people who
13014
- // have decided not to be asked.
13015
- if (cur === 'ask' && rule !== 'ask') {
13016
- // A read-only shell command is as safe as a read-only tool: there is no decision to make about `git log`.
13017
- if (toolName === 'Bash') {
13018
- const c = String((args && (args.command || args.cmd)) || '');
13019
- if (isReadOnlyCommand(c) && !isDestructiveCommand(c)) return true;
13020
- }
13021
- }
13022
-
13023
- // YOLO: routine work runs. FILES ARE NOT A REASON TO ASK.
13024
- //
13025
- // A user in yolo has said they do not want to confirm edits, and a path outside the workspace is still just a
13026
- // path. What still asks is DESTRUCTION — a command that deletes, rewrites history or kills a process — because
13027
- // that is the one class of action nobody means to authorise wholesale.
13028
- if (cur === 'yolo' && rule !== 'ask') {
13029
- if (toolName === 'Bash') {
13030
- const cmd = String((args && (args.command || args.cmd)) || '');
13031
- if (!isDestructiveCommand(cmd)) return true;
13032
- } else {
13033
- // Every non-shell tool: no path test. `isInsideWorkspace` was the thing asking about `/goal` and about a
13034
- // Read elsewhere, neither of which is a decision.
13035
- return true;
13036
- }
13037
- }
12842
+ if (verdict === 'allow') return true;
13038
12843
  return new Promise((resolve) => {
13039
12844
  let desc = '';
13040
12845
  if (args && typeof args === 'object') {
@@ -13066,7 +12871,11 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
13066
12871
  // AskUserQuestion bridge: the tool calls ctx.askQuestion(questions, ctx) and
13067
12872
  // awaits the answers. Same promise-handshake the approval prompt uses, so the
13068
12873
  // agent simply blocks while the user reads and chooses.
13069
- cfg.askQuestion = (questions, ctx) => new Promise((resolve) => {
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) => {
13070
12879
  state.question = {
13071
12880
  items: questions,
13072
12881
  index: 0,
@@ -13108,7 +12917,8 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
13108
12917
  sig.addEventListener('abort', onAbort, { once: true });
13109
12918
  }
13110
12919
  viewCur.render();
13111
- });
12920
+ });
12921
+ };
13112
12922
  // Open a file-history turn BEFORE the agent can write anything (file-history.js):
13113
12923
  // the first write to a file in this turn snapshots its pre-turn content, which
13114
12924
  // is exactly what /undo restores. Recorded even when nothing is written, so the
@@ -13141,6 +12951,11 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
13141
12951
  // change) takes effect on the next message without restarting.
13142
12952
  hookConfig: loadHooks(cfg.workspace).hooks,
13143
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 */ }
13144
12959
  // Everything the MODEL streams counts toward the tok/s meter: reasoning
13145
12960
  // chunks carry `text` just like answer chunks do.
13146
12961
  //
@@ -13217,8 +13032,13 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
13217
13032
  return;
13218
13033
  }
13219
13034
  if (e.type === 'compacted') {
13220
- if (!state.ctxReportedOnce) state.ctxTokens = e.after || state.ctxTokens;
13221
- state.ctxPercent = usagePercent(state.ctxTokens, state.ctxMax || 1);
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);
13222
13042
  // Compaction is over, so the Working row goes back to a rotating phrase.
13223
13043
  //
13224
13044
  // RE-ROLLED, not restored: an automatic compaction happens MID-TURN — the agent hit
@@ -13492,9 +13312,7 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
13492
13312
  const entry = [...state.chat].reverse().find((m) => m.role === 'tool' && m.pending && m.id === e.id)
13493
13313
  || [...state.chat].reverse().find((m) => m.role === 'tool' && m.pending);
13494
13314
  if (entry) {
13495
- // Bounded to a TAIL. This string is mirrored into the hub row and
13496
13315
  // shipped over SSE on every patch, so leaving it unbounded grew the
13497
- // TUI's row, the hub's row and the browser's copy together, once per
13498
13316
  // chunk. Only the tail is ever displayed.
13499
13317
  entry.liveOutput = tailChars(
13500
13318
  (entry.liveOutput || '') + e.chunk,
@@ -13710,6 +13528,11 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
13710
13528
  // without a row the transcript quietly looks like output went missing, and
13711
13529
  // the user has no way to know the text is still readable.
13712
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);
13713
13536
  }
13714
13537
  else if (e.type === 'todos') {
13715
13538
  // A FINISHED list is dropped outright, not stored and hidden.
@@ -13923,7 +13746,19 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
13923
13746
  // `session.messages` now holds the full request, system prompt included, so the bar
13924
13747
  // reads the real text from here on and the turn-scoped copy must not be counted too.
13925
13748
  state.turnSystemPrompt = null;
13926
- session.messages = messages;
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
+ }
13927
13762
  session.rounds = state.rounds;
13928
13763
  session.steps = state.steps;
13929
13764
  // THE GAUGE TRAVELS WITH THE MESSAGES.
@@ -13942,6 +13777,15 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
13942
13777
  // The todo list is part of the session's visible state: persist it here
13943
13778
  // too, so resuming (or `hncode -c`) brings the panel back.
13944
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');
13945
13789
  // Focus is one turn: the turn it was set for has now ended, so it goes off. Done
13946
13790
  // HERE, before the save below, so `session.focus` is written false and resuming
13947
13791
  // the session does not bring the narrowed toolset back. `focusAtTurnStart` (not
@@ -14193,8 +14037,22 @@ export async function startTUI(opts) {
14193
14037
  if (h.length > 240) h.splice(0, h.length - 240);
14194
14038
  }
14195
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
+ }
14196
14055
 
14197
-
14198
14056
  // Set when the config has no model, so the interface can say so without blocking startup.
14199
14057
  let modelMissing = false;
14200
14058
 
@@ -14229,6 +14087,8 @@ export async function startTUI(opts) {
14229
14087
  state._ensureVoice = ensureVoice;
14230
14088
 
14231
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);
14232
14092
  // Price the session's restored tokens against the model it is about to use, so
14233
14093
  // /cost and the status badge are right before the first new request.
14234
14094
  refreshCost(state, cfg);
@@ -14310,151 +14170,6 @@ export async function startTUI(opts) {
14310
14170
  const stdin = process.stdin;
14311
14171
  const stdout = process.stdout;
14312
14172
 
14313
- // ---- web UI bridge (/web) --------------------------------------------------
14314
- // `web` is null until the user runs /web. `hub` is created then too, so a
14315
- // session that never opens the UI pays for none of this. The hub is the shared
14316
- // state; syncWeb pushes the transcript into it and pushes the session status,
14317
- // and `webActions` wires the browser's requests to the SAME functions the
14318
- // keyboard calls — that is what makes the two front-ends behave identically.
14319
- let web = null;
14320
- let hub = null;
14321
- let webSyncQueued = false;
14322
- // The machine-wide daemon attachment (see attachGlobalWeb). Null until /web,
14323
- // and its presence is what "this session is published" means.
14324
- let webDaemon = null;
14325
-
14326
- function syncWeb() {
14327
- if (!web || !hub) return;
14328
- // Coalesce: `emit` for each changed row already marks the subscribers dirty,
14329
- // and syncChat is cheap, but a burst of frames would still run it repeatedly
14330
- // for the same state.
14331
- if (webSyncQueued) return;
14332
- webSyncQueued = true;
14333
- setImmediate(() => {
14334
- webSyncQueued = false;
14335
- if (!web || !hub) return;
14336
- try { hub.syncChat(state.chat); } catch { /* the UI must never break the TUI */ }
14337
- try { hub.setStatus(webStatus()); } catch { /* best-effort */ }
14338
- });
14339
- }
14340
-
14341
-
14342
- // Everything the browser's status panel and side panes show. Built fresh on each
14343
- // sync: it is a handful of field reads, and deriving it from live state is what
14344
- // keeps the two front-ends from disagreeing after a mode change.
14345
- function webStatus() {
14346
- // Files this conversation touched, counted from the transcript. The TUI has no
14347
- // separate index, and reading it here means a Write the model made is listed
14348
- // without any tool having to announce itself.
14349
- const files = new Map();
14350
- const bump = (p, op) => {
14351
- if (typeof p !== 'string' || !p) return;
14352
- let rel = p;
14353
- try { rel = path.relative(state.cwd || cfg.workspace || '', p) || p; } catch { /* keep as-is */ }
14354
- if (rel.startsWith('..')) rel = p; // outside the workspace: show it whole
14355
- const e = files.get(rel) || { path: rel, ops: new Set(), count: 0 };
14356
- e.ops.add(op);
14357
- e.count++;
14358
- files.set(rel, e);
14359
- };
14360
- for (const m of state.chat || []) {
14361
- if (m.role !== 'tool' || !m.toolArgs) continue;
14362
- const a = m.toolArgs;
14363
- const p = a.path || a.file_path;
14364
- bump(p, m.toolName || 'tool');
14365
- }
14366
- const fileList = [...files.values()]
14367
- .map((e) => ({ path: e.path, ops: [...e.ops].join(' '), count: e.count }))
14368
- .sort((x, y) => y.count - x.count || x.path.localeCompare(y.path))
14369
- .slice(0, 200);
14370
-
14371
- const tasks = Object.values(state.tasks || {}).map((t) => ({
14372
- id: t.id || t.taskId || '',
14373
- kind: t.kind || 'bash',
14374
- status: t.status || 'running',
14375
- summary: t.summary || t.description || t.prompt || '',
14376
- // Passed through when the task carries them, so the web task card can show
14377
- // a start time / agent id instead of silently rendering nothing.
14378
- startedAt: t.startedAt || t.startAt || 0,
14379
- agentId: t.agentId || '',
14380
- }));
14381
-
14382
- const next = {
14383
- session: session && session.id,
14384
- title: session && session.title,
14385
- model: state.modelLabel || cfg.model || '',
14386
- provider: cfg.provider || '',
14387
- mode: PERMISSION_LABEL[state.mode] || state.mode || '',
14388
- cwd: state.cwd || '',
14389
- plan: !!state.plan,
14390
- focus: !!state.focus,
14391
- swarm: !!state.swarm,
14392
- // Live git status mirror, so the web statusline can show branch + diff
14393
- // counts exactly like the TUI footer. Null when git is unavailable.
14394
- git: state._gitInfo || null,
14395
- // Thinking state, mirroring the terminal footer's model suffix. The
14396
- // statusline appends "thinking[: effort]" from these two fields.
14397
- reasoning: !!state.reasoning,
14398
- effort: state.effort || '',
14399
- busy: !!state.running,
14400
- // The Working row's phrase and animation tick. Sent so the BROWSER shows
14401
- // the same word, mid-sweep, as the terminal — the browser used to pick its
14402
- // own random word and run its own clock, so the two screens disagreed about
14403
- // both the text and the colour phase.
14404
- workMsg: state.workMsg || '',
14405
- spin: state.spin || 0,
14406
- // The tick the current pulse BEGAN. The browser animates the tool-name
14407
- // sweep and the Working row off `spin`, and both must start their cycle at
14408
- // the tick the pulse started — using the raw spinner tick would drop them
14409
- // into a mid-cycle colour the instant the animation hands over, which is a
14410
- // different colour on screen from the terminal's.
14411
- pulseStart: state.pulseStart == null ? 0 : state.pulseStart,
14412
- ctxTokens: state.ctxTokens || 0,
14413
- ctxMax: state.ctxMax || 0,
14414
- ctxPercent: state.ctxPercent || 0,
14415
- rounds: state.rounds || 0,
14416
- steps: state.steps || 0,
14417
- tokRate: state.tokRate || 0,
14418
- todos: [...(state.todos || [])],
14419
- queued: [...(state.queued || [])],
14420
- tasks,
14421
- files: fileList,
14422
- tools: toolsForWeb(),
14423
- commands: commandsForWeb(),
14424
- // The workspace tree, for `@` completion in the composer. Cached (below)
14425
- // because walking a real project is synchronous I/O on the render path.
14426
- workspaceFiles: workspaceFilesForWeb(),
14427
- quick: QUICK_COMMANDS,
14428
- // The enumerable settings the browser can CHANGE, with the current value.
14429
- //
14430
- // The terminal exposes these as pickers, which the browser cannot render —
14431
- // that is why /model and friends did nothing there. Sending the options
14432
- // with the status lets the browser draw its own control and post the choice
14433
- // back through `dispatch` ("/model <alias>"), which is the same path the
14434
- // keyboard takes.
14435
- options: optionsForWeb(),
14436
- // A blocking prompt, if one is on screen — the browser renders it as a modal
14437
- // and answers through the `approve` / `answerQuestion` actions.
14438
- pending: pendingForWeb(),
14439
- };
14440
-
14441
- // Reuse the previous identity for any field whose CONTENT is unchanged.
14442
- //
14443
- // `setStatus` skips the broadcast when nothing changed, and it decides that by
14444
- // identity. Most fields above are rebuilt on every call (todos, queued, tasks
14445
- // and the file list all come from fresh arrays), so without this every frame
14446
- // would look like a change and the full status would be pushed over SSE twelve
14447
- // times a second for nothing. Comparing here — once, shallowly — is what makes
14448
- // the "did anything actually change" test meaningful.
14449
- const prev = (hub && hub.status) || null;
14450
- if (prev) {
14451
- for (const k of Object.keys(next)) {
14452
- if (next[k] === prev[k]) continue;
14453
- if (shallowEqualArray(next[k], prev[k])) next[k] = prev[k];
14454
- }
14455
- }
14456
- return next;
14457
- }
14458
14173
 
14459
14174
  /** True when two arrays hold the same content (compared one level deep). */
14460
14175
  function shallowEqualArray(a, b) {
@@ -14566,7 +14281,7 @@ export async function startTUI(opts) {
14566
14281
  }
14567
14282
  // Built ONCE per session and reused by reference.
14568
14283
  //
14569
- // `webStatus` runs on every frame (syncWeb is called from paintNow), so building
14284
+ // Building these lists on every frame cost a map over ~20 tools and ~60 commands at the
14570
14285
  // these lists each time cost a map over ~20 tools and ~60 commands at the
14571
14286
  // spinner's 80 ms cadence — and it defeated `setStatus`'s change detection,
14572
14287
  // which compares by identity. The registries do not change while a session runs,
@@ -14836,8 +14551,6 @@ export async function startTUI(opts) {
14836
14551
  // every change reaches the screen through this one function, so it catches the
14837
14552
  // rows that bypass addChat (streamed prose, tool rows, the plan bubble, an
14838
14553
  // abort) without instrumenting each of those call sites. `syncChat` is a no-op
14839
- // until `/web` runs, and it is incremental, so an idle frame costs nothing.
14840
- if (web) void syncWeb();
14841
14554
  // Re-set AFTER the write: `_frameTickAt` names the LAST frame, so it has to be
14842
14555
  // captured once that frame is on the terminal, not before it.
14843
14556
  state._frameTickAt = getTerminalFlushTick();
@@ -14961,6 +14674,11 @@ export async function startTUI(opts) {
14961
14674
  if (wait === 0) { setImmediate(paintNow); return; }
14962
14675
  setTimeout(paintNow, wait);
14963
14676
  }
14677
+
14678
+ /** Kept as a named hook because the streaming path calls it in several places. */
14679
+ function anchorScroll() {
14680
+ renderSoon();
14681
+ }
14964
14682
  // THE MERMAID REPAINT HOOK.
14965
14683
  //
14966
14684
  // The mermaid renderer is loaded on first use, so the first frame of a diagram draws
@@ -15024,39 +14742,6 @@ export async function startTUI(opts) {
15024
14742
 
15025
14743
  // ---- @ file completion ----------------------------------------------------
15026
14744
 
15027
- // ---- @ file completion ----------------------------------------------------
15028
- // Typing `@` shows an INLINE candidate list above the composer — the same widget
15029
- // `/` uses (state.mention*) — rather than taking over the screen. It used to be a
15030
- // silent rewrite of the input to the FIRST match of a single-directory listing:
15031
- // you could not see the candidates, could not descend into a subdirectory
15032
- // (`@src/` matched nothing), and hidden files were dropped.
15033
- //
15034
- // `walk` is bounded (depth + entry count) because it runs on a keystroke.
15035
- function collectWorkspaceFiles(root, { limit = 4000, maxDepth = 8 } = {}) {
15036
- const out = [];
15037
- const skip = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'target', '__pycache__']);
15038
- const walk = (dir, rel, depth) => {
15039
- if (out.length >= limit || depth > maxDepth) return;
15040
- let entries;
15041
- try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
15042
- // Deterministic order: directories first, then files, each alphabetical, so
15043
- // the list does not jump around between keystrokes.
15044
- entries.sort((a, b) => (b.isDirectory() - a.isDirectory()) || a.name.localeCompare(b.name));
15045
- for (const e of entries) {
15046
- if (out.length >= limit) return;
15047
- if (skip.has(e.name)) continue;
15048
- const relPath = rel ? rel + '/' + e.name : e.name;
15049
- if (e.isDirectory()) {
15050
- out.push({ label: relPath + '/', isDir: true, rel: relPath + '/' });
15051
- walk(path.join(dir, e.name), relPath, depth + 1);
15052
- } else {
15053
- out.push({ label: relPath, isDir: false, rel: relPath });
15054
- }
15055
- }
15056
- };
15057
- walk(root, '', 0);
15058
- return out;
15059
- }
15060
14745
 
15061
14746
  // Everything after the last `@` that has no whitespace in it is the query.
15062
14747
  function atQueryAt(input) {
@@ -15435,15 +15120,11 @@ export async function startTUI(opts) {
15435
15120
  // instead of reaching for `state` and `renderFrame` directly, which is what lets the same
15436
15121
  // code run in the web daemon where there is no terminal to draw on.
15437
15122
  const view = tuiView({
15438
- // `hub` is assigned later (startWeb), so it is read through a getter rather than captured
15439
- // here — a captured copy would be the null we have now, and every web push would no-op.
15440
- get hub() { return hub; },
15441
- get hub() { return hub; },
15123
+ // The view object the turn loop draws through.
15442
15124
  renderFrame,
15443
15125
  renderSoon,
15444
15126
  addChat,
15445
15127
  notice,
15446
- syncWeb: (...a) => syncWeb(...a),
15447
15128
  openEditor,
15448
15129
  openPicker,
15449
15130
  openForm,
@@ -15554,6 +15235,57 @@ export async function startTUI(opts) {
15554
15235
  }
15555
15236
 
15556
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
+ });
15557
15289
  // The session-naming implementation, reached by `runTurn` THROUGH the host.
15558
15290
  //
15559
15291
  // `runTurn` is a module-level function and this is a nested one inside `startTUI`, so a
@@ -15569,6 +15301,97 @@ export async function startTUI(opts) {
15569
15301
  // `runTurn` receives the SessionHost instance), so the call threw `setCtxTokens is not defined` — the same
15570
15302
  // mistake the `makeTitle` note above describes, made again.
15571
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
+
15572
15395
  // The Goal tool writes the SAME objective field /goal does, so the status panel and the turn loop cannot
15573
15396
  // disagree about what the agent is working towards. `runTurn` reaches both through `sessHost`, which is why
15574
15397
  // the store is installed here rather than inside the tool.
@@ -15715,7 +15538,9 @@ export async function startTUI(opts) {
15715
15538
  try {
15716
15539
  const listed = kind === 'skills'
15717
15540
  ? await remote.listRemoteSkillsDetailed()
15718
- : await remote.listRemotePlugins();
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();
15719
15544
  b.data.remote = listed.ok ? listed.items : [];
15720
15545
  b.data.remoteError = listed.ok ? '' : listed.error;
15721
15546
  } catch (e) {
@@ -16443,7 +16268,10 @@ export async function startTUI(opts) {
16443
16268
  const tokTimer = setInterval(() => {
16444
16269
  const times = state._tokTimes;
16445
16270
  if (!times || !times.length) {
16446
- if (state.tokRate !== 0) { state.tokRate = 0; renderSoon(); }
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(); }
16447
16275
  return;
16448
16276
  }
16449
16277
  const cutoff = Date.now() - TOK_WINDOW_MS;
@@ -16451,6 +16279,7 @@ export async function startTUI(opts) {
16451
16279
  while (drop < times.length && times[drop] < cutoff) drop++;
16452
16280
  if (drop) times.splice(0, drop);
16453
16281
  const rate = times.length;
16282
+ if (rate > 0) state._lastTokRate = rate;
16454
16283
  if (rate !== state.tokRate) { state.tokRate = rate; renderSoon(); }
16455
16284
  }, 50);
16456
16285
 
@@ -16691,8 +16520,8 @@ export async function startTUI(opts) {
16691
16520
  function dispatchFromStatusBar(cmd) {
16692
16521
  const savedInput = state.input || '';
16693
16522
  const savedCaret = state.caret || 0;
16694
- Promise.resolve(dispatch(cmd, '', state, cfg, session, host, submit, stdout))
16695
- .catch(() => {})
16523
+ Promise.resolve(dispatch(cmd, '', state, cfg, session, cmdHost, submit, stdout))
16524
+ .catch((err) => { appErr('status dispatch failed: ' + ((err && err.message) || err)); })
16696
16525
  .then(() => {
16697
16526
  // Only restore when the picker is the thing now open and it did not itself
16698
16527
  // seed the composer (a command may legitimately write to state.input).
@@ -16736,7 +16565,7 @@ export async function startTUI(opts) {
16736
16565
  }
16737
16566
  state.menuOpen = false; state.menuList = []; state.menuSel = 0; state.menuOffset = 0;
16738
16567
  state.input = ''; state.caret = 0;
16739
- dispatch(cmd.name, '', state, cfg, session, host, submit, stdout);
16568
+ dispatch(cmd.name, '', state, cfg, session, cmdHost, submit, stdout);
16740
16569
  if (state._quit) { quit(); return true; }
16741
16570
  renderFrame();
16742
16571
  }
@@ -17309,13 +17138,25 @@ export async function startTUI(opts) {
17309
17138
  // frame and only the body branch sets it).
17310
17139
  if (!allowHidden && state._bodyScreenTop == null) return '';
17311
17140
  const { cols } = dims();
17312
- // The FULL transcript, and that is correct here: `selection.row` is an ABSOLUTE
17313
- // transcript row, not a screen row. mouseToCell() already converted it
17314
- // (`_bodyTop + rowInBody`), and composeFrame's highlight indexes the windowed
17315
- // array with the same absolute number — the windowed array keeps the transcript's
17316
- // absolute length and fills off-screen slots with '', so index N is the same row
17317
- // in both. Verified by printing drawn-vs-full side by side at several scrolls.
17318
- const rawChat = renderChatLines(state, cols);
17141
+ // THE SAME RENDER THE SCREEN USED.
17142
+ //
17143
+ // `selection.row` is an index into the ROW ARRAY, and that array is built by
17144
+ // renderChatLines. Two calls with the same state can still disagree about how many rows
17145
+ // the transcript has: windowed, a message far from the viewport is counted from its cached
17146
+ // `_count`; rendered whole, every message is laid out for real, and a message whose rows
17147
+ // come out empty — a `tool_result` with no tool name, of which a long session has dozens —
17148
+ // counts differently.
17149
+ //
17150
+ // Measured on a real 2677-message session: windowed 10576 rows, whole 10604. The frame's
17151
+ // `_bodyTop` comes from the windowed count, so indexing the whole one put every copy 28
17152
+ // rows off — further down the transcript, further off, which is exactly "it depends where
17153
+ // I click".
17154
+ //
17155
+ // So the copy asks for the SAME array the frame asked for, with the same viewport.
17156
+ const bodyH = state._bodyH || 0;
17157
+ const rawChat = state._forceFullRender || !bodyH
17158
+ ? renderChatLines(state, cols)
17159
+ : renderChatLines(state, cols, { bodyH, scroll: state.scroll || 0 });
17319
17160
  const a = sel.anchor, h = sel.head;
17320
17161
  const start = (h.row < a.row || (h.row === a.row && h.col < a.col)) ? h : a;
17321
17162
  const end = start === a ? h : a;
@@ -17358,10 +17199,17 @@ export async function startTUI(opts) {
17358
17199
  return out.join('\n');
17359
17200
  }
17360
17201
  function slicePlainByCol(text, c0, c1) {
17361
- // A full-row slice keeps its content but loses the RIGHT PADDING. The row is padded to the terminal
17362
- // width, and `c1 === Infinity` means "to the end of the row" — copying that padding would put
17363
- // invisible spaces on the clipboard that were never selected.
17364
- if (c0 === 0 && c1 === Infinity) return text.replace(/\s+$/, '');
17202
+ // A slice that runs TO THE END OF THE ROW loses the right padding. The row is padded to
17203
+ // the terminal width, and that padding is not content — the highlight stops at the last
17204
+ // character, so the copy has to as well, or the clipboard comes back with a line of
17205
+ // invisible spaces that were never selected.
17206
+ //
17207
+ // `c0 === 0` USED TO BE PART OF THIS TEST, and that was the bug: a selection whose first
17208
+ // row starts at column 1 — which is every row, since column 0 is the margin the copy
17209
+ // skips — took the other path and kept its padding. Dragging across two or more rows and
17210
+ // pasting gave the first line followed by thirty-odd spaces.
17211
+ const toEnd = c1 === Infinity;
17212
+ if (c0 === 0 && toEnd) return text.replace(/\s+$/, '');
17365
17213
  let out = '';
17366
17214
  let col = 0;
17367
17215
  const s = String(text || '');
@@ -17369,12 +17217,12 @@ export async function startTUI(opts) {
17369
17217
  const cp = s.codePointAt(i);
17370
17218
  const ch = String.fromCodePoint(cp);
17371
17219
  const cw = visualWidth(ch);
17372
- if (col >= c0 && (c1 === Infinity || col < c1)) out += ch;
17220
+ if (col >= c0 && (toEnd || col < c1)) out += ch;
17373
17221
  col += cw;
17374
17222
  i += cp > 0xffff ? 2 : 1;
17375
- if (c1 !== Infinity && col >= c1) break;
17223
+ if (!toEnd && col >= c1) break;
17376
17224
  }
17377
- return out;
17225
+ return toEnd ? out.replace(/\s+$/, '') : out;
17378
17226
  }
17379
17227
  function copyToClipboard(text) {
17380
17228
  // Empty text is NOT a success. `copyText` returns false without touching the
@@ -17578,7 +17426,6 @@ export async function startTUI(opts) {
17578
17426
  // the editor for a steered draft).
17579
17427
  if (draft) { state.input = ''; state.caret = 0; state.pastes.clear(); state.pasteCounter = 0; }
17580
17428
  state.queued = [];
17581
- if (web && hub) { try { hub.pubStatusField('queued', []); } catch { /* best-effort */ } }
17582
17429
  renderFrame();
17583
17430
  }
17584
17431
 
@@ -17588,7 +17435,6 @@ export async function startTUI(opts) {
17588
17435
  if (!state.queued || !state.queued.length) return false;
17589
17436
  const text = state.queued[state.queued.length - 1];
17590
17437
  state.queued = state.queued.slice(0, -1);
17591
- if (web && hub) { try { hub.pubStatusField('queued', [...state.queued]); } catch { /* best-effort */ } }
17592
17438
  state.input = text;
17593
17439
  state.caret = text.length;
17594
17440
  // Drop the matching transcript entry: the item is back in the composer.
@@ -17800,9 +17646,9 @@ export async function startTUI(opts) {
17800
17646
  const sp = text.indexOf(' ');
17801
17647
  const c = sp === -1 ? text : text.slice(0, sp);
17802
17648
  const arg = sp === -1 ? '' : text.slice(sp + 1).trim();
17803
- Promise.resolve(dispatch(c, arg, state, cfg, session, host, submit, stdout))
17649
+ Promise.resolve(dispatch(c, arg, state, cfg, session, cmdHost, submit, stdout))
17804
17650
  .catch((err) => {
17805
- try { host.notice(`keybinding ${t.key} → ${text} failed: ${(err && err.message) || err}`, 'error'); }
17651
+ try { cmdHost.notice(`keybinding ${t.key} → ${text} failed: ${(err && err.message) || err}`, 'error'); }
17806
17652
  catch { /* the UI itself is broken */ }
17807
17653
  });
17808
17654
  renderFrame();
@@ -18352,7 +18198,7 @@ export async function startTUI(opts) {
18352
18198
  return;
18353
18199
  }
18354
18200
 
18355
- if (t.key === 'c-s-m' && t.held) return; // the terminal's auto-repeat, not a new press
18201
+ if (t.key === 'c-s-m' && t.held) return; // the terminal's auto-repeat, not a new press
18356
18202
  if (t.key === 'c-s-m') {
18357
18203
  // Ctrl+Shift+M, HELD: the key going down opens the microphone and letting it up
18358
18204
  // closes it. A hold rather than a tap because the user knows when they have
@@ -19293,7 +19139,7 @@ export async function startTUI(opts) {
19293
19139
  // An entry from the SECOND level (arguments) is not a command name: it must
19294
19140
  // never be turned into `submit('/' + name)`. That is what produced
19295
19141
  // "Unknown command: /" — typing an argument that matches no completion
19296
- // (`/trim 0`, `/web 0.0.0.0`) left a hint-only row selected, and Enter sent
19142
+ // (`/trim 0`, `/set model x`) left a hint-only row selected, and Enter sent
19297
19143
  // the literal "/". `_cmdName` marks a row as belonging to the argument level.
19298
19144
  const argLevel = !!(selItem && selItem._cmdName);
19299
19145
  if (argLevel && selItem._argWord && selItem.name) {
@@ -19597,47 +19443,11 @@ function wheelStep(state, family) {
19597
19443
  // The draft belongs to the history walk that just ended; the next ↑ starts fresh.
19598
19444
  state.draftInput = '';
19599
19445
  if (!text) { renderFrame(); return; }
19600
- // `@name message` sends STRAIGHT to a teammate, without the model.
19601
- //
19602
- // This is Claude Code's `parseDirectMemberMessage`, and the reason it exists: routing a one-line
19603
- // instruction through the conversation costs a full model turn for the lead, and the lead may reword
19604
- // it. When you already know who should do it and what to say, the mailbox is the shorter path — and
19605
- // it is the only way to steer a member while the lead is mid-turn.
19606
- if (text.startsWith('@')) {
19607
- const m = /^@([\w-]+)\s+([\s\S]+)$/.exec(text);
19608
- if (!m) {
19609
- notice(uiText('Use `@name message` to send straight to a member.'), 'error');
19610
- renderFrame();
19611
- return;
19612
- }
19613
- const [, who, body] = m;
19614
- const teamName = leadTeam();
19615
- if (!teamName) {
19616
- notice(uiText('No team. Create one: /team create <name>'), 'error');
19617
- renderFrame();
19618
- return;
19619
- }
19620
- const roster = teamMod.readRoster(teamName);
19621
- const names = String(roster || '').split('\n').map((l) => l.trim().split(/\s+/)[0]).filter(Boolean);
19622
- // The user is not on the roster, so `@team-lead` would look unknown — it is accepted because a
19623
- // member's own sends use that alias and it is the box the person reads.
19624
- if (!names.includes(who) && who !== TEAM_LEAD_NAME) {
19625
- notice(`No member "${who}". On this team: ${names.join(', ') || '(nobody)'}`, 'error');
19626
- renderFrame();
19627
- return;
19628
- }
19629
- try {
19630
- mailMod.writeToMailbox(teamName, who, { from: TEAM_LEAD_NAME, text: body.trim() });
19631
- // Shown in the transcript so the instruction is part of the record: a message that only exists in
19632
- // someone's inbox is one the person cannot see themselves having sent.
19633
- addChat({ role: 'system', text: `[you → ${who}] ${body.trim()}` });
19634
- notice(`sent to ${who}`);
19635
- } catch (e) {
19636
- notice(`could not send: ${(e && e.message) || e}`, 'error');
19637
- }
19638
- renderFrame();
19639
- return;
19640
- }
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
+
19641
19451
 
19642
19452
  if (!state.running) {
19643
19453
  state.turnStart = Date.now();
@@ -19699,9 +19509,9 @@ function wheelStep(state, family) {
19699
19509
  // registry browser hitting a bad field) surfaced as an unhandledRejection,
19700
19510
  // which the process handler turns into process.exit(1) — the whole session
19701
19511
  // died with no in-UI explanation. Catch here, report, and keep running.
19702
- Promise.resolve(dispatch(c, arg, state, cfg, session, host, submit, stdout))
19512
+ Promise.resolve(dispatch(c, arg, state, cfg, session, cmdHost, submit, stdout))
19703
19513
  .catch((err) => {
19704
- try { host.notice(`/${String(c).replace(/^\//, '')} failed: ${(err && err.message) || err}`, 'error'); }
19514
+ try { notice(`/${String(c).replace(/^\//, '')} failed: ${(err && err.message) || err}`, 'error'); }
19705
19515
  catch { /* the UI itself is broken; the process handler will log it */ }
19706
19516
  try { renderFrame(); } catch { /* ignore */ }
19707
19517
  });
@@ -19721,8 +19531,6 @@ function wheelStep(state, family) {
19721
19531
  // turn happened to trigger next. Push an independent `queued` event so the
19722
19532
  // browser updates the queue pane immediately (claude-code-style granular
19723
19533
  // event instead of a full-status snapshot).
19724
- if (web) void syncWeb();
19725
- if (web && hub) { try { hub.pubStatusField('queued', [...state.queued]); } catch { /* best-effort */ } }
19726
19534
  return;
19727
19535
  }
19728
19536
 
@@ -19824,7 +19632,7 @@ function wheelStep(state, family) {
19824
19632
  // The TUI's binding of the turn loop. `runTurn` is module-level so a headless session can
19825
19633
  // call the same code with its own five objects; this only supplies the terminal's.
19826
19634
  async function runAgent(text, opts, viewArg) {
19827
- 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);
19828
19636
  }
19829
19637
 
19830
19638
  // Remember the session's working mode (permission / plan / focus / effort)
@@ -19832,685 +19640,6 @@ function wheelStep(state, family) {
19832
19640
  // these are settings, not conversation, and must survive an abrupt exit.
19833
19641
  function persistState() { return sessHost.persistState(); }
19834
19642
 
19835
- // ---- /web: serve this session to a browser ---------------------------------
19836
- // Started on demand. The browser talks to the SAME session: prompts it sends go
19837
- // through `submit` (identical to typing), slash commands through `dispatch`, and
19838
- // its transcript is the TUI's own `state.chat` mirrored by syncChat() on every
19839
- // paint. Nothing here reimplements agent behaviour — it only relays.
19840
- async function startWeb(bindIp, port) {
19841
- if (web) { notice(`Web UI already running at ${web.url}`); return web; }
19842
- hub = new SessionHub();
19843
- // Actions the browser can take. Each one calls the SAME function the keyboard
19844
- // calls, which is what keeps the two front-ends behaviourally identical.
19845
- // Straight through to the core. It validates and throws in the same shape as before, so
19846
- // the HTTP layer (which maps a throw to 409) is unaffected.
19847
- // `opts.new` starts a FRESH session before the prompt runs.
19848
- //
19849
- // The caller does not know the new session's id in advance, so asking them to create one first
19850
- // means two requests and a round trip to learn an id that this side invents anyway. Passing
19851
- // `new: true` lets the daemon accept a prompt against any session URL and have it run in a new
19852
- // session instead — the same thing `/new` does, minus the slash command.
19853
- hub.actions.submit = async (text, opts) => {
19854
- if (opts && opts.new) {
19855
- // Flush the outgoing session first: its todos and transcript belong to the id being replaced,
19856
- // and `dispatch` does exactly what `/new` does, so the two cannot drift apart.
19857
- await core.dispatch('new', '');
19858
- // The hub's rows and event ring belong to the session that just ended. Clearing them keeps a
19859
- // viewer from showing the previous conversation under the new id.
19860
- hub.rows = [];
19861
- hub.events = [];
19862
- }
19863
- // `core.submit` AWAITS THE WHOLE TURN, so its result is the finished turn — no polling needed.
19864
- const out = await core.submit(text);
19865
- // `opts.return` asks for the transcript of what just ran:
19866
- //
19867
- // "turn" the rows of this turn, tool results included
19868
- // "full" every row the session holds
19869
- // "none" (default) whatever `core.submit` returned, unchanged
19870
- //
19871
- // Without this a caller had to submit, wait an unknown time, then issue a second request for
19872
- // `/api/state` — two round trips and a guess at how long the turn would take.
19873
- const want = opts && opts.return;
19874
- if (!want || want === 'none') return out;
19875
- // FORCE ONE SYNC: `syncChat` does nothing while no browser is subscribed, so `hub.rows` would be
19876
- // empty here and the caller would get an empty transcript from a turn that plainly ran.
19877
- try { hub.syncChat(state.chat || []); } catch { /* the reply still carries `result` */ }
19878
- // The turn begins at the last user row; everything after it is what the prompt produced.
19879
- const rows = Array.isArray(hub.rows) ? hub.rows : [];
19880
- let from = 0;
19881
- for (let k = rows.length - 1; k >= 0; k--) { if (rows[k] && rows[k].role === 'user') { from = k; break; } }
19882
- const slice = want === 'full' ? rows : rows.slice(from);
19883
- const detail = (opts && opts.detail) || 'full';
19884
- const shaped = detail === 'minimal' ? slice.filter((r) => r.role !== 'tool')
19885
- : detail === 'summary' ? slice.map((r) => (r.role === 'tool' ? { ...r, text: '', liveOutput: '', diff: undefined } : r))
19886
- : slice;
19887
- return { result: out, rows: shaped, detail, sessionId: session && session.id };
19888
- };
19889
- hub.actions.dispatch = async (cmd, arg) => {
19890
- const out = await core.dispatch(cmd, arg);
19891
- // The core runs the command; the repaint is this front end's business, so it stays
19892
- // here rather than in the core. A headless run has nothing to repaint and passes a
19893
- // no-op view.
19894
- v.render();
19895
- return out;
19896
- };
19897
- hub.actions.interrupt = () => core.interrupt();
19898
- hub.actions.stopTask = async (id) => {
19899
- const ctxLike = state.agent && state.agent.ctx ? state.agent.ctx : { tasks: state.tasks };
19900
- stopTask(ctxLike, String(id || ''));
19901
- };
19902
- hub.actions.setMode = async (mode) => {
19903
- const m = String(mode || '');
19904
- if (!['ask', 'yolo', 'auto'].includes(m)) throw new Error('unknown mode: ' + m);
19905
- setPermission(state, m);
19906
- persistState();
19907
- renderFrame();
19908
- };
19909
- hub.actions.shell = async (cmd) => {
19910
- const c = String(cmd || '').trim();
19911
- if (!c) throw new Error('empty command');
19912
- await runShellCommand(c);
19913
- };
19914
- // ANSWER A RUNNING COMMAND FROM THE BROWSER.
19915
- //
19916
- // The terminal has Ctrl+G for this; the web UI had no equivalent, so a command that prompted was simply stuck
19917
- // for anyone watching in a browser. Both go through the SAME foreground hook, so the two front ends cannot
19918
- // disagree about which process a line is going to.
19919
- hub.actions.stdinLine = async (line) => {
19920
- const fg = state.agent && state.agent.ctx && state.agent.ctx._foreground;
19921
- if (!fg || typeof fg.write !== 'function') throw new Error('no command is running in the foreground');
19922
- if (!fg.write(String(line == null ? '' : line) + '\n')) throw new Error('the command has finished');
19923
- };
19924
- // Move the running command to the background. Ctrl+B's equivalent.
19925
- hub.actions.detach = async () => {
19926
- const fg = state.agent && state.agent.ctx && state.agent.ctx._foreground;
19927
- if (!fg || typeof fg.detach !== 'function') throw new Error('nothing to background');
19928
- const id = fg.detach();
19929
- if (!id) throw new Error('the command has finished');
19930
- try { state.agent.ctx._foreground = null; } catch { /* the agent may already be gone */ }
19931
- notice(`Moved to background: ${id}`, 'info');
19932
- renderFrame();
19933
- return id;
19934
- };
19935
- // The two handshakes the agent blocks on. Resolving these from the browser is
19936
- // what lets a phone answer an approval the terminal is showing.
19937
- hub.actions.approve = async (id, ok) => {
19938
- const ap = state.approvalPending;
19939
- if (!ap) throw new Error('no approval is pending');
19940
- state.approvalPending = null;
19941
- ap.resolve(!!ok);
19942
- renderFrame();
19943
- };
19944
- // The plan under review in Plan mode. Same idea as `approve`: the turn is blocked on a
19945
- // promise, and a browser has to be able to settle it. Without this, a plan raised in
19946
- // Plan mode left the web UI stuck on a spinning turn with no way forward except finding
19947
- // the terminal that raised it.
19948
- hub.actions.answerPlan = async (id, outcome) => {
19949
- const pp = state.planPending;
19950
- if (!pp) throw new Error('no plan is pending');
19951
- const want = String(outcome || '').toLowerCase();
19952
- // The terminal produces exactly these three (handleKey: enter -> approve, e -> edit,
19953
- // esc -> keep). An unknown one is refused rather than coerced, so a stale browser tab
19954
- // cannot settle a review with a meaning nobody chose.
19955
- if (!['approve', 'edit', 'keep'].includes(want)) {
19956
- throw new Error(`unknown plan outcome: ${outcome} (expected approve, edit or keep)`);
19957
- }
19958
- state.planPending = null;
19959
- pp.resolve(want);
19960
- renderFrame();
19961
- };
19962
- // The full-screen editor's Save and Cancel, so the six commands that open one
19963
- // (/memory, /personal, /permissions, /output-style, /keybindings, /set-system-prompt)
19964
- // are usable from a browser. They call the SAME `onSave` the terminal's Ctrl+S calls,
19965
- // so a value written from the web takes the identical path — including the validation
19966
- // the command puts in its own onSave.
19967
- hub.actions.saveEditor = async (id, text) => {
19968
- const ed = state.editor;
19969
- if (!ed) throw new Error('no editor is open');
19970
- if (typeof ed.onSave !== 'function') {
19971
- throw new Error('this editor is read-only: no onSave handler');
19972
- }
19973
- const value = String(text == null ? '' : text);
19974
- // Close first, then save: onSave may itself open a picker or write a notice, and it
19975
- // must not be overwritten by a stale editor still being on screen.
19976
- state.editor = null;
19977
- renderFrame();
19978
- ed.onSave(value);
19979
- };
19980
- hub.actions.cancelEditor = async (id) => {
19981
- if (!state.editor) throw new Error('no editor is open');
19982
- state.editor = null;
19983
- renderFrame();
19984
- };
19985
- hub.actions.answerQuestion = async (id, answers, extra, note, advance) => {
19986
- const q = state.question;
19987
- if (!q) throw new Error('no question is pending');
19988
- const list = Array.isArray(answers) ? answers : [];
19989
- const cur = (q.items && q.items[q.index]) || {};
19990
- const key = cur.question || 'answer';
19991
- // The per-question answer: the picked option label(s), unless a free-text
19992
- // "Other" was provided (then that wins, matching the terminal).
19993
- const other = extra == null ? '' : String(extra).trim();
19994
- if (other) q.answers[key] = other;
19995
- else if (list.length) q.answers[key] = list.join(', ');
19996
- // The whole-request note is only meaningful on the last question; store it
19997
- // for the final resolve rather than as this question's answer.
19998
- if (note != null) q.supplement = String(note);
19999
-
20000
- const total = (q.items || []).length;
20001
- const isLast = q.index >= total - 1;
20002
- const more = advance !== false && !isLast;
20003
- if (more) {
20004
- // Advance to the next question and let the status broadcast re-open the
20005
- // modal with it. Do NOT resolve yet — the agent is still blocked.
20006
- q.index += 1;
20007
- q.sel = 0;
20008
- q.picked = new Set();
20009
- try { syncWebNow(); } catch { /* best-effort */ }
20010
- renderFrame();
20011
- return { ok: true, index: q.index, total };
20012
- }
20013
- const answersOut = { ...q.answers };
20014
- state.question = null;
20015
- q.resolve({ answers: answersOut, additional: q.supplement || '' });
20016
- try { syncWebNow(); } catch { /* best-effort */ }
20017
- renderFrame();
20018
- return { ok: true, done: true };
20019
- };
20020
-
20021
- // ---- session settings the browser can change ------------------------------
20022
- //
20023
- // Every one of these runs the SAME code the terminal's slash command does, and
20024
- // persists, so a change made in the browser survives a restart and shows up in
20025
- // the terminal immediately. Nothing is reimplemented here — the point is that
20026
- // the two front-ends are views of one session.
20027
-
20028
- /** Push the transcript and status to the hub right now, not on the next paint. */
20029
- function syncWebNow() {
20030
- if (!web || !hub) return;
20031
- try { hub.syncChat(state.chat); } catch { /* the UI must never break the TUI */ }
20032
- try { hub.setStatus(webStatus()); } catch { /* best-effort */ }
20033
- renderFrame();
20034
- }
20035
-
20036
- hub.actions.setTitle = async (title) => {
20037
- const t = String(title || '').trim();
20038
- if (!t) throw new Error('title required');
20039
- session.title = t.slice(0, 200);
20040
- try { sess.saveSession(session); } catch { /* the title is cosmetic */ }
20041
- writeWindowTitle(session, stdout);
20042
- syncWebNow();
20043
- };
20044
-
20045
-
20046
- // Steer: inject text into the RUNNING turn instead of queueing a new one.
20047
- // `agent.steer()` buffers it for the next model call — nothing can be inserted
20048
- // into a request already in flight.
20049
- hub.actions.steer = async (text) => {
20050
- const t = String(text || '').trim();
20051
- if (!t) throw new Error('text required');
20052
- if (!state.running || !state.agent) throw new Error('nothing is running');
20053
- state.agent.steer(t);
20054
- addChat({ role: 'steer', text: t });
20055
- };
20056
-
20057
- // Edit a QUEUED message: pull it back out of the queue so the browser can put
20058
- // it in the composer, exactly like the terminal's ↑-to-recall (see
20059
- // recallQueued). Matched by TEXT, not index — the browser's list is rebuilt on
20060
- // every status frame, so an index captured at click time can point at a
20061
- // different item by the time it arrives.
20062
- //
20063
- // Returns the removed text so the caller can seed its composer with it.
20064
- hub.actions.editQueued = async (text) => {
20065
- const t = String(text == null ? '' : text);
20066
- const i = state.queued.findIndex((q) => String(q) === t);
20067
- if (i < 0) throw new Error('that message is no longer queued');
20068
- state.queued.splice(i, 1);
20069
- // Drop the matching transcript entry too: the message is now being edited,
20070
- // not waiting, so leaving a `queued` row would double it.
20071
- for (let k = state.chat.length - 1; k >= 0; k--) {
20072
- if (state.chat[k].role === 'queued' && state.chat[k].text === t) { state.chat.splice(k, 1); break; }
20073
- }
20074
- if (web && hub) { try { hub.pubStatusField('queued', [...state.queued]); } catch { /* best-effort */ } }
20075
- syncWebNow();
20076
- return { ok: true, text: t };
20077
- };
20078
-
20079
- // Remove a queued message outright (the browser's ✕), without editing it.
20080
- hub.actions.dropQueued = async (text) => {
20081
- const t = String(text == null ? '' : text);
20082
- const i = state.queued.findIndex((q) => String(q) === t);
20083
- if (i < 0) throw new Error('that message is no longer queued');
20084
- state.queued.splice(i, 1);
20085
- for (let k = state.chat.length - 1; k >= 0; k--) {
20086
- if (state.chat[k].role === 'queued' && state.chat[k].text === t) { state.chat.splice(k, 1); break; }
20087
- }
20088
- if (web && hub) { try { hub.pubStatusField('queued', [...state.queued]); } catch { /* best-effort */ } }
20089
- syncWebNow();
20090
- return { ok: true };
20091
- };
20092
-
20093
- // The effective config, with secrets REPLACED by a set/unset flag. The browser
20094
- // needs to show what is in force without ever receiving a key.
20095
- hub.actions.getConfig = async () => effectiveSnapshot(cfg);
20096
-
20097
- /**
20098
- * Set one root-level key in config.toml.
20099
- *
20100
- * `key` is whitelisted: this surface can be reached over the network, and
20101
- * "write any key" would let a caller rewrite the whole file, including the
20102
- * provider table and the access token.
20103
- */
20104
- hub.actions.setConfig = async (key, value) => {
20105
- const ALLOWED = new Set([
20106
- 'calm_mode', 'auto_update', 'auto_compact', 'prompt_cache',
20107
- 'temperature', 'top_p', 'presence_penalty', 'sampling',
20108
- 'tool_allow_external_paths', 'subagent_model', 'swarm_mode', 'theme',
20109
- ]);
20110
- const k = String(key || '');
20111
- if (!ALLOWED.has(k)) throw new Error(`not a settable key: ${k}`);
20112
- const raw = String(value);
20113
- if (/^(true|false)$/i.test(raw)) setConfigBool(k, /^true$/i.test(raw));
20114
- else setConfigString(k, raw);
20115
- // Re-read so the change is live without a restart.
20116
- Object.assign(cfg, resolveConfig());
20117
- state.reasoning = !!cfg.reasoning;
20118
- syncWebNow();
20119
- return effectiveSnapshot(cfg);
20120
- };
20121
-
20122
- // ---- providers and models -------------------------------------------------
20123
- //
20124
- // These edit config.toml through the same helpers /provider uses, then
20125
- // re-resolve so the change is live. The option caches are invalidated because
20126
- // `webStatus` reuses arrays by identity — without that the browser would keep
20127
- // showing a provider that has just been deleted.
20128
-
20129
- function invalidateOptionCaches() {
20130
- toolsCache = null;
20131
- commandsCache = null;
20132
- wsFilesCache = { root: '', at: 0, files: null };
20133
- }
20134
-
20135
- /** Every provider with its base URL and model count, for the settings UI. */
20136
- hub.actions.listProviders = async () => {
20137
- const pr = (cfg.raw && cfg.raw.providers) || {};
20138
- const models = (cfg.raw && cfg.raw.models) || {};
20139
- return Object.keys(pr).map((name) => ({
20140
- name,
20141
- baseUrl: String(pr[name].base_url || pr[name].baseUrl || ''),
20142
- protocol: String(pr[name].protocol || 'openai'),
20143
- keySet: !!(pr[name].api_key || pr[name].apiKey),
20144
- current: name === cfg.provider,
20145
- models: Object.keys(models).filter((k) => (models[k].provider || '') === name),
20146
- }));
20147
- };
20148
-
20149
- hub.actions.addProvider = async (name, baseUrl, apiKey, protocol) => {
20150
- const n = String(name || '').trim();
20151
- if (!n) throw new Error('provider name required');
20152
- if (!/^[A-Za-z0-9_-]+$/.test(n)) throw new Error('name may contain letters, digits, - and _ only');
20153
- // Accept the protocol value OR a Type label ("OpenAI Responses").
20154
- const proto = typeToProtocol(protocol);
20155
- addProvider(n, { base_url: String(baseUrl || ''), api_key: String(apiKey || ''), protocol: proto });
20156
- cfg.raw.providers = cfg.raw.providers || {};
20157
- cfg.raw.providers[n] = { base_url: String(baseUrl || ''), api_key: String(apiKey || ''), protocol: proto };
20158
- invalidateOptionCaches();
20159
- syncWebNow();
20160
- return hub.actions.listProviders();
20161
- };
20162
-
20163
- hub.actions.removeProvider = async (name) => {
20164
- const n = String(name || '');
20165
- if (!n) throw new Error('provider name required');
20166
- const pr = (cfg.raw && cfg.raw.providers) || {};
20167
- if (!pr[n]) throw new Error(`no such provider: ${n}`);
20168
- removeProvider(n);
20169
- delete pr[n];
20170
- // Its models go too: a model keyed to a provider that no longer exists is
20171
- // unselectable and only clutters the picker.
20172
- for (const key of Object.keys(cfg.raw.models || {})) {
20173
- if (key.split('/')[0] === n) delete cfg.raw.models[key];
20174
- }
20175
- if (cfg.provider === n) { cfg.provider = ''; state.provider = ''; }
20176
- invalidateOptionCaches();
20177
- syncWebNow();
20178
- return hub.actions.listProviders();
20179
- };
20180
-
20181
- // Read the provider's model list from its /models endpoint and register every
20182
- // model, so the picker fills in without the user typing ids. Best-effort: an
20183
- // unreachable endpoint leaves the provider added.
20184
- hub.actions.discoverModels = async (name) => {
20185
- const n = String(name || '');
20186
- const pr = (cfg.raw && cfg.raw.providers) || {};
20187
- const p = pr[n];
20188
- if (!p) throw new Error(`no such provider: ${n}`);
20189
- const baseUrl = p.base_url || p.baseUrl || '';
20190
- if (!baseUrl) throw new Error('provider has no base_url');
20191
- // `throwOnError`: the caller asked for this explicitly, so an unreachable
20192
- // endpoint or a rejected key must surface as an error rather than as
20193
- // "found 0 models", which is indistinguishable from an empty catalogue.
20194
- const found = await fetchModels({
20195
- baseUrl,
20196
- apiKey: p.api_key || p.apiKey || '',
20197
- protocol: p.protocol || 'openai',
20198
- throwOnError: true,
20199
- });
20200
- cfg.raw.models = cfg.raw.models || {};
20201
- let added = 0;
20202
- for (const m of found) {
20203
- const key = modelKey(n, m.id);
20204
- if (!cfg.raw.models[key]) added++;
20205
- addModel(n, m.id, { display_name: m.display, contextLength: m.contextLength, maxTokens: m.maxTokens });
20206
- cfg.raw.models[key] = {
20207
- provider: n, model: m.id,
20208
- display_name: m.display || undefined,
20209
- maxTokens: m.maxTokens || undefined,
20210
- contextLength: m.contextLength || undefined,
20211
- reasoning: m.reasoning || undefined,
20212
- efforts: m.efforts || undefined,
20213
- };
20214
- }
20215
- invalidateOptionCaches();
20216
- syncWebNow();
20217
- return { found: found.length, added };
20218
- };
20219
-
20220
- // The models.dev catalogue, for "import a known provider".
20221
- hub.actions.listKnownProviders = async () => {
20222
- const catalog = await fetchCatalog();
20223
- if (!catalog) throw new Error('could not reach models.dev');
20224
- return Object.values(catalog)
20225
- .filter((p) => p && p.id && p.api)
20226
- .map((p) => ({ id: p.id, name: p.name || p.id, api: p.api }))
20227
- .sort((a, b) => String(a.name).localeCompare(String(b.name)));
20228
- };
20229
-
20230
- /**
20231
- * Import a models.dev entry as a provider, then discover its models.
20232
- *
20233
- * The key is required from the caller: models.dev publishes endpoints, not
20234
- * credentials, so this cannot complete without the user supplying one.
20235
- */
20236
- hub.actions.importKnownProvider = async (catalogId, name, apiKey) => {
20237
- const catalog = await fetchCatalog();
20238
- if (!catalog) throw new Error('could not reach models.dev');
20239
- const entry = catalog[String(catalogId || '')];
20240
- if (!entry || !entry.api) throw new Error(`unknown provider: ${catalogId}`);
20241
- const n = String(name || entry.id || '').trim();
20242
- if (!n) throw new Error('provider name required');
20243
- const proto = /anthropic/i.test(String(entry.api)) ? 'anthropic' : 'openai';
20244
- addProvider(n, { base_url: entry.api, api_key: String(apiKey || ''), protocol: proto });
20245
- cfg.raw.providers = cfg.raw.providers || {};
20246
- cfg.raw.providers[n] = { base_url: entry.api, api_key: String(apiKey || ''), protocol: proto };
20247
- invalidateOptionCaches();
20248
- syncWebNow();
20249
- // Models are a bonus — a bad key must not undo the provider.
20250
- let discovered = { found: 0, added: 0 };
20251
- try { discovered = await hub.actions.discoverModels(n); } catch { /* best-effort */ }
20252
- return { name: n, baseUrl: entry.api, protocol: proto, ...discovered };
20253
- };
20254
-
20255
-
20256
-
20257
- // Brought in on first use: see the note at the top of this file.
20258
- const { startWebServer } = await import('./web.js');
20259
- const srv = await startWebServer({
20260
- hub,
20261
- bindIp: bindIp || '127.0.0.1',
20262
- port: port == null ? 0 : port,
20263
- onNotice: (m, k) => notice(m, k),
20264
- });
20265
- web = srv;
20266
- // Seed the browser with what already exists, so opening the page mid-session
20267
- // shows the conversation rather than an empty pane.
20268
- try { hub.syncChat(state.chat); hub.setStatus(webStatus()); } catch { /* best-effort */ }
20269
- return srv;
20270
- }
20271
-
20272
- function stopWeb() {
20273
- if (!web) { notice(uiText('Web UI is not running'), 'error'); return false; }
20274
- // Tell the daemon first, so its directory stops listing this session instead
20275
- // of showing a link to a port that is about to disappear.
20276
- if (webDaemon) {
20277
- try { webDaemon.detach(); } catch { /* best-effort */ }
20278
- webDaemon = null;
20279
- }
20280
- try { web.close(); } catch { /* already gone */ }
20281
- web = null;
20282
- hub = null;
20283
- return true;
20284
- }
20285
-
20286
- /**
20287
- * Bring up the GLOBAL web UI for this session.
20288
- *
20289
- * Two servers are involved and the distinction matters:
20290
- * * `startWeb()` here — this session's OWN server, holding the transcript,
20291
- * the actions and the SSE stream. It binds a random loopback port.
20292
- * * the daemon — one per machine, on the FIXED port from config.toml. It
20293
- * serves the directory and proxies /s/<id>/* to the session above.
20294
- *
20295
- * The user asked for a fixed address that survives restarts and lists every
20296
- * session, so the daemon is what they open. If one is already running this
20297
- * session just registers with it — that is the "reuse, do not start another"
20298
- * behaviour, and it is also the only option, since a second daemon could not
20299
- * bind the fixed port anyway.
20300
- */
20301
- async function attachGlobalWeb(bindIp, port) {
20302
- // The bind address: an explicit /web argument wins, else the config value,
20303
- // else loopback. It decides BOTH bindings — the session's own server and the
20304
- // daemon the browser actually opens — so `/web 0.0.0.0` is really reachable
20305
- // from another machine instead of silently listening on 127.0.0.1.
20306
- const host = String(bindIp || cfg.webHost || '127.0.0.1');
20307
- // The session's own server first: the daemon needs a port to proxy to.
20308
- const srv = await startWeb(host, port == null ? 0 : port);
20309
- try {
20310
- // IMPORTED HERE, NOT AT THE TOP. This chain pulls in web-daemon.js and measures ~76ms
20311
- // to evaluate, and only /web ever reaches it — every other session paid that on
20312
- // startup for a command it never runs.
20313
- const { attachToDaemon } = await import('./web-daemon-client.js');
20314
- webDaemon = await attachToDaemon({
20315
- id: (session && session.id) || 'session',
20316
- port: srv.port,
20317
- token: srv.token,
20318
- title: (session && session.title) || '',
20319
- workspace: state.cwd || cfg.workspace || '',
20320
- host,
20321
- });
20322
- } catch (e) {
20323
- // The daemon is a convenience layer; the session's own server still works,
20324
- // so fall back to reporting that rather than failing /web outright.
20325
- notice(`Global web UI unavailable (${e.message}); this session is still served directly`, 'error');
20326
- webDaemon = null;
20327
- }
20328
- // The daemon's token is the one the user pastes into the login page. It comes
20329
- // from config.toml, so it is the same value every session reports — which is
20330
- // the point: a saved browser login keeps working.
20331
- return { srv, daemon: webDaemon, token: ensureWebToken() };
20332
- }
20333
-
20334
-
20335
-
20336
- const host = {
20337
- // The one spawner, so the model's TeamCreate tool and the /team command start the same
20338
- // kind of teammate.
20339
- spawnTeammates,
20340
- addChat, openPicker, openForm, notice, openPanel, openEditor, editComposerExternal, openTasksPanel, openRegistryBrowser,
20341
- // While the side-thread box is open, a typed message goes to the SIDE THREAD, not
20342
- // to the agent — this is the half of kimi's design that makes the box usable:
20343
- // its `sendUserInput` feeds the panel from the ordinary composer, so a follow-up
20344
- // needs no command. `opts.toMain` is the escape hatch for the paths that must
20345
- // reach the agent regardless (a schedule, a command's own prompt).
20346
- sendPrompt: (text, opts) => {
20347
- const o = opts || {};
20348
- if (state.btwPanel && !o.toMain && !o.fromSchedule) {
20349
- void askSideQuestion(state, cfg, text, renderSoon);
20350
- return;
20351
- }
20352
- void runAgent(text, o);
20353
- },
20354
- quit: () => { state._quit = true; },
20355
- saveSession: (s) => { (async () => { try { const { runHooks } = await import('./plugin.js'); await runHooks('onSessionSave', s || session); } catch {} })(); sess.saveSession(s); },
20356
- // Rebinds the closure's session AND the mirror on `state`. /move replaces it, and without
20357
- // this the caller and the command disagreed about which session was current — every later
20358
- // save wrote the old object, still stamped with the directory it was moved away from.
20359
- replaceSession: (s) => { if (!s) return; session = s; state.session = s; if (s.workspace) state.workspace = s.workspace; writeWindowTitle(session, stdout); },
20360
- getMessages: () => (session && session.messages ? session.messages : []),
20361
- clearSession: () => { if (session) session.messages = []; if (state) { state.ctxTokens = 0; state.ctxPercent = 0; } renderFrame(); },
20362
- getConfig: (key) => (cfg && key != null ? cfg[key] : undefined),
20363
- setConfig: (key, val) => { if (cfg && key != null) cfg[key] = val; },
20364
- // Persist a TOML root-level key to config.toml and keep the live cfg in sync.
20365
- persistConfig: (key, val) => {
20366
- try {
20367
- setConfigString(String(key), typeof val === 'string' ? val : JSON.stringify(val));
20368
- if (cfg && key != null) cfg[key] = val;
20369
- return true;
20370
- } catch (e) { return false; }
20371
- },
20372
- reloadConfig: () => resolveConfig(),
20373
- // Full reload: unload the current plugins, then re-run discovery/load and return
20374
- // any notices (so a freshly added/edited plugin shows up without restarting).
20375
- // `fresh: true` re-imports each file with a cache-busting query — without it the
20376
- // ESM cache hands back the module instance from the previous load and an EDIT to
20377
- // a plugin file would change nothing.
20378
- reloadPlugins: async () => {
20379
- const { loadPlugins, takePluginNotices } = await import('./plugin.js');
20380
- await loadPlugins(cfg.pluginDir || undefined, { fresh: true });
20381
- return takePluginNotices();
20382
- },
20383
- persistState,
20384
- // `dispatch` is module-level and reloads the keybinding file after /keybindings edits it.
20385
- // It cannot call this by name — the function is nested inside `startTUI` — so the same
20386
- // indirection `renderFrame` below exists for. Without it, `/keybindings` threw
20387
- // `refreshKeybindings is not defined` and killed the process, exactly as `submit` did.
20388
- refreshKeybindings,
20389
- startWeb,
20390
- startWebGlobal: attachGlobalWeb,
20391
- startWebGlobal: attachGlobalWeb,
20392
- stopWeb,
20393
- webInfo: () => web,
20394
- // `dispatch` is module-level and was declared with a `renderFrame` parameter
20395
- // that NONE of its four callers ever passed. That was harmless until /compact
20396
- // started calling it, which threw "renderFrame is not a function". Reaching it
20397
- // through `host` means a future caller cannot forget it again.
20398
- renderFrame,
20399
-
20400
- // ---- capabilities a plugin can drive -------------------------------------
20401
- //
20402
- // These forward to the SAME code the slash commands use, so a plugin cannot reach a
20403
- // state the command could not: opening the tree runs the identical builder, and
20404
- // switching the theme drops `lastFrame` the same way /theme does (without which the
20405
- // differential painter would emit nothing and the screen would keep the old colours).
20406
-
20407
- openFileTree(filter) {
20408
- const cwd = state.cwd || cfg.workspace || process.cwd();
20409
- let files = [];
20410
- try { files = walkFiles(cwd, { includeIgnored: false }); } catch { return false; }
20411
- const root = buildTree(files, cwd);
20412
- if (!root.children.length) return false;
20413
- const expanded = new Set();
20414
- for (const c of root.children) if (c.dir) expanded.add(c.rel);
20415
- state.fileTree = { root, expanded, sel: 0, scroll: 0, filter: String(filter || '').trim(), cwd };
20416
- state.picker = null; state.form = null; state.panel = null; state.menuOpen = false;
20417
- renderFrame();
20418
- return true;
20419
- },
20420
- closeFileTree() {
20421
- if (!state.fileTree) return;
20422
- state.fileTree = null;
20423
- state.hoverHit = null;
20424
- renderFrame();
20425
- },
20426
- getTheme() { return state.theme || null; },
20427
- setTheme(name) {
20428
- if (!hasTheme(name)) return false;
20429
- state.theme = name;
20430
- setTheme(name);
20431
- try { setConfigString('theme', name); } catch { /* the session still uses it */ }
20432
- // The full repaint: see the same note in the /theme command.
20433
- lastFrame = null;
20434
- renderFrame();
20435
- return true;
20436
- },
20437
- subagents() { return listRuns().map((r) => ({ id: r.agentId, runId: r.runId, taskId: r.taskId, type: r.type, description: r.description, startedAt: r.startedAt })); },
20438
- messageSubagent(ref, text) { return sendToRun(ref, text); },
20439
- interruptSubagent(ref) { return ref ? interruptRun(ref) : interruptAll(); },
20440
- closeSubagent(ref) { return closeRun(ref); },
20441
- isKeyBound(key) {
20442
- const k = normalizeKey(key);
20443
- if (!k) return false;
20444
- // Three sources, and all three have to be checked or a plugin gets a wrong answer:
20445
- // * the user's own keybindings file (a data structure);
20446
- // * a plugin's claim from registerKeybind (also data);
20447
- // * the BUILT-IN keys the TUI dispatches in its switch — not data, so the list
20448
- // below is the subset a plugin would realistically take and silently break.
20449
- if (keybindings.bindings.has(k)) return true;
20450
- if (pluginKeybinds().some((kb) => kb.key === k)) return true;
20451
- return BUILTIN_KEYS.has(k);
20452
- },
20453
- boundKeys() {
20454
- const out = new Set([...keybindings.bindings.keys()]);
20455
- for (const k of BUILTIN_KEYS) out.add(k);
20456
- for (const kb of pluginKeybinds()) out.add(kb.key);
20457
- return [...out];
20458
- },
20459
- };
20460
- // The core's `dispatch` needs this object, and it is declared here rather than at the core
20461
- // because a command's callbacks (`openPicker`, `openPanel`, …) are defined in this same
20462
- // literal. Until this line runs, a command dispatched THROUGH THE CORE has no UI callbacks;
20463
- // nothing dispatches before the TUI is fully built, so that window is not reachable.
20464
- commandHost = host;
20465
-
20466
- // Hand the full host surface to the plugin system so api.* can forward (sendPrompt,
20467
- // openPanel, notice, getMessages, setConfig, ...). Done once, here, after `host` exists.
20468
- (async () => { try { const { setPluginHost } = await import('./plugin.js'); setPluginHost(host); } catch {} })();
20469
-
20470
- // Surface what the plugins did. `loadPlugins()` already ran (index.js, before the TUI
20471
- // existed) and collected its notices, including any load failure — which previously went
20472
- // only to stderr, invisible while the TUI owns the screen. A plugin that failed to load
20473
- // simply did not appear, with nothing explaining why.
20474
- void (async () => {
20475
- try {
20476
- const { takePluginNotices, runHooks } = await import('./plugin.js');
20477
- // onStartup: plugins that want to greet / schedule / open a panel on launch.
20478
- try { await runHooks('onStartup'); } catch (e) { console.error('[hncode-plugin] onStartup error:', e.message); }
20479
- const notes = takePluginNotices();
20480
- if (!notes.length) return;
20481
- // ONE collapsible block instead of a wall of lines: a plugin set can emit
20482
- // dozens of notices, which pushed the actual conversation off screen at
20483
- // startup. Collapsed it is a single summary line; Ctrl+L expands it in place
20484
- // (see the `c-l` handler next to the other Ctrl shortcuts).
20485
- const icon = { error: '✗', warn: '!', info: '•' };
20486
- const detail = notes.map((n) => `${icon[n.level] || '•'} plugin: ${n.text}`);
20487
- const errs = notes.filter((n) => n.level === 'error').length;
20488
- const first = notes[0];
20489
- const summary = `plugin: ${first.text}`;
20490
- const suffix = notes.length > 1
20491
- ? ` (+${notes.length - 1} more${errs ? `, ${errs} error${errs === 1 ? '' : 's'}` : ''} · ctrl+l)`
20492
- : '';
20493
- const msg = {
20494
- role: notes.some((n) => n.level === 'error') ? 'aborted' : 'system',
20495
- text: summary + suffix,
20496
- // Collapsed by default; Ctrl+L flips `expanded` and the renderer prints
20497
- // `allLines` instead of the single summary.
20498
- pluginLog: true,
20499
- expanded: false,
20500
- allLines: detail,
20501
- };
20502
- state.chat.push(msg);
20503
- renderFrame();
20504
- } catch { /* notices are best-effort; never break startup */ }
20505
- })();
20506
-
20507
- // Appending streamed text can also add rows (the message wraps as it grows).
20508
- // No arithmetic is needed here: renderChatLines() anchors the scrolled-up window
20509
- // by row against the exact row count, so this only has to schedule a repaint.
20510
- // Kept as a named hook because the streaming path calls it in several places.
20511
- function anchorScroll() {
20512
- renderSoon();
20513
- }
20514
19643
  // ---- paced streaming ------------------------------------------------------
20515
19644
  // Answer and reasoning deltas are NOT painted as they arrive: they go into a
20516
19645
  // StreamBuffer that drips them out at a smooth, time-paced rate. A provider that
@@ -20656,6 +19785,13 @@ function wheelStep(state, family) {
20656
19785
  // * it ran exactly once. `needsTitle` only held on the very first turn, so a
20657
19786
  // failure (offline, aborted, empty reply) left the session nameless forever.
20658
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
+
20659
19795
  async function generateTitle(userText) {
20660
19796
  const asked = String(userText || '').replace(/\s+/g, ' ').trim().slice(0, 400);
20661
19797
  if (!asked) return;
@@ -20767,13 +19903,6 @@ function wheelStep(state, family) {
20767
19903
  // The /tasks panel owns a flash timer; leaving it armed keeps the process
20768
19904
  // alive until it fires after exit.
20769
19905
  if (state.tasksPanel && state.tasksPanel.flashTimer) clearTimeout(state.tasksPanel.flashTimer);
20770
- // Leaving the daemon registered would keep this session listed as "live" in
20771
- // the browser until its heartbeat went stale. Deregistering now flips the page
20772
- // to the read-only view straight away.
20773
- if (webDaemon) {
20774
- try { webDaemon.detach(); } catch { /* best-effort */ }
20775
- webDaemon = null;
20776
- }
20777
19906
  try { sess.saveSession(session); } catch {}
20778
19907
  stdout.write('\x1b[<u\x1b[?2004l\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l');
20779
19908
  stdout.write(alternateScreen(false));
@@ -20975,35 +20104,6 @@ function quit() {
20975
20104
 
20976
20105
 
20977
20106
 
20978
- // WEB UI (--web): same opt-in shape as --control. It starts AFTER the first
20979
- // paint (the UI is already up by this point), and a failure is reported in the
20980
- // transcript rather than killing the session — a port already in use must not
20981
- // stop the user from working.
20982
- if (opts.web && typeof opts.web === 'object') {
20983
- try {
20984
- const srv = await startWeb(opts.web.bindIp, opts.web.port);
20985
- const lan = !srv.loopback;
20986
- addChat({
20987
- role: 'system',
20988
- text: [
20989
- `Web UI: ${srv.url}`,
20990
- `Bind: ${srv.host}:${srv.port}${lan ? ' (reachable from the network)' : ' (this machine only)'}`,
20991
- '',
20992
- uiText('Access token (paste it into the login page):'),
20993
- '',
20994
- ` ${srv.token}`,
20995
- '',
20996
- 'Anyone with this token can run commands as you in this workspace.',
20997
- 'Stop the server with /web off.',
20998
- ].join('\n'),
20999
- });
21000
- renderFrame();
21001
- } catch (e) {
21002
- addChat({ role: 'warn', text: `Could not start the web UI: ${e.message}` });
21003
- renderFrame();
21004
- }
21005
- }
21006
- process.on('exit', () => { try { if (web) web.close(); } catch { /* already gone */ } });
21007
20107
 
21008
20108
 
21009
20109
  // Keep the process alive for the whole session. startTUI is async and returns
@@ -21011,3 +20111,4 @@ function quit() {
21011
20111
  // resolves immediately and Node exits (the "flash of UI then quit" bug).
21012
20112
  return new Promise(() => {});
21013
20113
  }
20114
+ //(注:内容由AI生成)