strands-darwin 0.0.34 → 0.0.36

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 (273) hide show
  1. package/README.md +22 -3
  2. package/README.zh-CN.md +22 -3
  3. package/dist/patches/@strands-agents+sdk+1.16.0.patch +29 -15
  4. package/dist/patches/ink+7.1.1.patch +58 -0
  5. package/dist/src/agent/background-delegation.d.ts +3 -3
  6. package/dist/src/agent/background-delegation.js +2 -2
  7. package/dist/src/agent/background-delegation.js.map +1 -1
  8. package/dist/src/agent/context-breakdown.d.ts +2 -1
  9. package/dist/src/agent/context-breakdown.js +2 -1
  10. package/dist/src/agent/context-breakdown.js.map +1 -1
  11. package/dist/src/agent/instructions.d.ts +22 -3
  12. package/dist/src/agent/instructions.js +67 -34
  13. package/dist/src/agent/instructions.js.map +1 -1
  14. package/dist/src/agent/prompt-cache.js +15 -2
  15. package/dist/src/agent/prompt-cache.js.map +1 -1
  16. package/dist/src/agent/refusal.d.ts +44 -7
  17. package/dist/src/agent/refusal.js +54 -8
  18. package/dist/src/agent/refusal.js.map +1 -1
  19. package/dist/src/agent/rewind.d.ts +2 -0
  20. package/dist/src/agent/rewind.js +4 -1
  21. package/dist/src/agent/rewind.js.map +1 -1
  22. package/dist/src/agent/runtime.d.ts +86 -13
  23. package/dist/src/agent/runtime.js +250 -43
  24. package/dist/src/agent/runtime.js.map +1 -1
  25. package/dist/src/agent/session.d.ts +96 -4
  26. package/dist/src/agent/session.js +249 -9
  27. package/dist/src/agent/session.js.map +1 -1
  28. package/dist/src/agent/stream-idle.d.ts +16 -0
  29. package/dist/src/agent/stream-idle.js +127 -0
  30. package/dist/src/agent/stream-idle.js.map +1 -0
  31. package/dist/src/agent/stream-resumption.d.ts +5 -2
  32. package/dist/src/agent/stream-resumption.js +5 -2
  33. package/dist/src/agent/stream-resumption.js.map +1 -1
  34. package/dist/src/agent/system-prompt.d.ts +1 -1
  35. package/dist/src/agent/system-prompt.js +4 -1
  36. package/dist/src/agent/system-prompt.js.map +1 -1
  37. package/dist/src/agent/thinking.js +4 -2
  38. package/dist/src/agent/thinking.js.map +1 -1
  39. package/dist/src/agent/working-context.d.ts +21 -1
  40. package/dist/src/agent/working-context.js +28 -1
  41. package/dist/src/agent/working-context.js.map +1 -1
  42. package/dist/src/agent/workspace-trust.d.ts +112 -0
  43. package/dist/src/agent/workspace-trust.js +207 -0
  44. package/dist/src/agent/workspace-trust.js.map +1 -0
  45. package/dist/src/agentcore/auto-policy.d.ts +7 -0
  46. package/dist/src/agentcore/auto-policy.js +50 -0
  47. package/dist/src/agentcore/auto-policy.js.map +1 -0
  48. package/dist/src/agentcore/auto-state.d.ts +43 -0
  49. package/dist/src/agentcore/auto-state.js +73 -0
  50. package/dist/src/agentcore/auto-state.js.map +1 -0
  51. package/dist/src/agentcore/cli.d.ts +2 -0
  52. package/dist/src/agentcore/cli.js +38 -0
  53. package/dist/src/agentcore/cli.js.map +1 -0
  54. package/dist/src/agentcore/config.d.ts +48 -0
  55. package/dist/src/agentcore/config.js +44 -0
  56. package/dist/src/agentcore/config.js.map +1 -0
  57. package/dist/src/agentcore/controller.d.ts +105 -0
  58. package/dist/src/agentcore/controller.js +979 -0
  59. package/dist/src/agentcore/controller.js.map +1 -0
  60. package/dist/src/agentcore/projection.d.ts +2 -0
  61. package/dist/src/agentcore/projection.js +8 -0
  62. package/dist/src/agentcore/projection.js.map +1 -0
  63. package/dist/src/agentcore/records.d.ts +41 -0
  64. package/dist/src/agentcore/records.js +149 -0
  65. package/dist/src/agentcore/records.js.map +1 -0
  66. package/dist/src/agentcore/state.d.ts +16 -0
  67. package/dist/src/agentcore/state.js +149 -0
  68. package/dist/src/agentcore/state.js.map +1 -0
  69. package/dist/src/agentcore/tools.d.ts +3 -0
  70. package/dist/src/agentcore/tools.js +11 -0
  71. package/dist/src/agentcore/tools.js.map +1 -0
  72. package/dist/src/agentcore/transport.d.ts +37 -0
  73. package/dist/src/agentcore/transport.js +242 -0
  74. package/dist/src/agentcore/transport.js.map +1 -0
  75. package/dist/src/agentcore/upload-projection.d.ts +208 -0
  76. package/dist/src/agentcore/upload-projection.js +823 -0
  77. package/dist/src/agentcore/upload-projection.js.map +1 -0
  78. package/dist/src/agents/child-recipe.js +4 -1
  79. package/dist/src/agents/child-recipe.js.map +1 -1
  80. package/dist/src/agents/loader.d.ts +12 -0
  81. package/dist/src/agents/loader.js +15 -1
  82. package/dist/src/agents/loader.js.map +1 -1
  83. package/dist/src/agents/subagent-tool.js +6 -7
  84. package/dist/src/agents/subagent-tool.js.map +1 -1
  85. package/dist/src/agents/workflow-tool.js +4 -6
  86. package/dist/src/agents/workflow-tool.js.map +1 -1
  87. package/dist/src/cli-doctor.js +14 -5
  88. package/dist/src/cli-doctor.js.map +1 -1
  89. package/dist/src/cli-import.d.ts +1 -0
  90. package/dist/src/cli-import.js +26 -0
  91. package/dist/src/cli-import.js.map +1 -0
  92. package/dist/src/cli-main.js +60 -10
  93. package/dist/src/cli-main.js.map +1 -1
  94. package/dist/src/cli-permissions.d.ts +2 -0
  95. package/dist/src/cli-permissions.js +20 -0
  96. package/dist/src/cli-permissions.js.map +1 -0
  97. package/dist/src/cli-sessions.js +6 -2
  98. package/dist/src/cli-sessions.js.map +1 -1
  99. package/dist/src/cli-usage.d.ts +9 -1
  100. package/dist/src/cli-usage.js +13 -0
  101. package/dist/src/cli-usage.js.map +1 -1
  102. package/dist/src/cli.js +19 -2
  103. package/dist/src/cli.js.map +1 -1
  104. package/dist/src/commands/custom-commands.d.ts +1 -1
  105. package/dist/src/commands/custom-commands.js +20 -6
  106. package/dist/src/commands/custom-commands.js.map +1 -1
  107. package/dist/src/commands/init-command.d.ts +47 -0
  108. package/dist/src/commands/init-command.js +110 -0
  109. package/dist/src/commands/init-command.js.map +1 -0
  110. package/dist/src/commands/review-command.d.ts +10 -0
  111. package/dist/src/commands/review-command.js +28 -0
  112. package/dist/src/commands/review-command.js.map +1 -0
  113. package/dist/src/config-file.d.ts +9 -0
  114. package/dist/src/config-file.js +82 -0
  115. package/dist/src/config-file.js.map +1 -0
  116. package/dist/src/config.d.ts +100 -7
  117. package/dist/src/config.js +253 -46
  118. package/dist/src/config.js.map +1 -1
  119. package/dist/src/dev-repl.js +33 -2
  120. package/dist/src/dev-repl.js.map +1 -1
  121. package/dist/src/headless-protocol.d.ts +24 -1
  122. package/dist/src/headless-protocol.js +24 -5
  123. package/dist/src/headless-protocol.js.map +1 -1
  124. package/dist/src/headless-runner.d.ts +8 -0
  125. package/dist/src/headless-runner.js +42 -2
  126. package/dist/src/headless-runner.js.map +1 -1
  127. package/dist/src/headless.d.ts +11 -0
  128. package/dist/src/headless.js +33 -7
  129. package/dist/src/headless.js.map +1 -1
  130. package/dist/src/hooks/hook-process.js +7 -2
  131. package/dist/src/hooks/hook-process.js.map +1 -1
  132. package/dist/src/hooks/lifecycle-hooks.js +3 -1
  133. package/dist/src/hooks/lifecycle-hooks.js.map +1 -1
  134. package/dist/src/hooks/tool-hooks.js +3 -1
  135. package/dist/src/hooks/tool-hooks.js.map +1 -1
  136. package/dist/src/import-claude-files.d.ts +28 -0
  137. package/dist/src/import-claude-files.js +227 -0
  138. package/dist/src/import-claude-files.js.map +1 -0
  139. package/dist/src/import-claude-snippets.d.ts +2 -0
  140. package/dist/src/import-claude-snippets.js +105 -0
  141. package/dist/src/import-claude-snippets.js.map +1 -0
  142. package/dist/src/import-claude.d.ts +13 -0
  143. package/dist/src/import-claude.js +287 -0
  144. package/dist/src/import-claude.js.map +1 -0
  145. package/dist/src/mcp/registry.d.ts +57 -1
  146. package/dist/src/mcp/registry.js +78 -6
  147. package/dist/src/mcp/registry.js.map +1 -1
  148. package/dist/src/memory/command.d.ts +1 -1
  149. package/dist/src/memory/command.js +89 -4
  150. package/dist/src/memory/command.js.map +1 -1
  151. package/dist/src/memory/controller.d.ts +32 -0
  152. package/dist/src/memory/controller.js +39 -3
  153. package/dist/src/memory/controller.js.map +1 -1
  154. package/dist/src/memory/state.d.ts +6 -0
  155. package/dist/src/memory/state.js +6 -1
  156. package/dist/src/memory/state.js.map +1 -1
  157. package/dist/src/memory/store.d.ts +13 -0
  158. package/dist/src/memory/store.js +38 -2
  159. package/dist/src/memory/store.js.map +1 -1
  160. package/dist/src/memory/tools.d.ts +7 -0
  161. package/dist/src/memory/tools.js +12 -1
  162. package/dist/src/memory/tools.js.map +1 -1
  163. package/dist/src/paths.js +3 -0
  164. package/dist/src/paths.js.map +1 -1
  165. package/dist/src/permissions-test.d.ts +18 -0
  166. package/dist/src/permissions-test.js +207 -0
  167. package/dist/src/permissions-test.js.map +1 -0
  168. package/dist/src/pricing/model-prices.d.ts +11 -6
  169. package/dist/src/pricing/model-prices.js +37 -16
  170. package/dist/src/pricing/model-prices.js.map +1 -1
  171. package/dist/src/project-identity.d.ts +3 -0
  172. package/dist/src/project-identity.js +8 -0
  173. package/dist/src/project-identity.js.map +1 -0
  174. package/dist/src/project-overrides.d.ts +57 -0
  175. package/dist/src/project-overrides.js +79 -0
  176. package/dist/src/project-overrides.js.map +1 -0
  177. package/dist/src/skills/builtin/setup-agentcore-memory/SKILL.md +158 -0
  178. package/dist/src/skills/loader.d.ts +1 -1
  179. package/dist/src/skills/loader.js +4 -1
  180. package/dist/src/skills/loader.js.map +1 -1
  181. package/dist/src/tools/background-bash.d.ts +21 -3
  182. package/dist/src/tools/background-bash.js +44 -8
  183. package/dist/src/tools/background-bash.js.map +1 -1
  184. package/dist/src/tools/file-editor-serial.d.ts +14 -0
  185. package/dist/src/tools/file-editor-serial.js +15 -0
  186. package/dist/src/tools/file-editor-serial.js.map +1 -1
  187. package/dist/src/tools/shell-env.d.ts +101 -0
  188. package/dist/src/tools/shell-env.js +173 -0
  189. package/dist/src/tools/shell-env.js.map +1 -0
  190. package/dist/src/trajectory/reader.d.ts +1 -1
  191. package/dist/src/trajectory/reader.js +23 -3
  192. package/dist/src/trajectory/reader.js.map +1 -1
  193. package/dist/src/trajectory/replay.js +23 -0
  194. package/dist/src/trajectory/replay.js.map +1 -1
  195. package/dist/src/trajectory/resume-recap.d.ts +11 -1
  196. package/dist/src/trajectory/resume-recap.js +10 -1
  197. package/dist/src/trajectory/resume-recap.js.map +1 -1
  198. package/dist/src/trajectory/rewind-history.d.ts +8 -0
  199. package/dist/src/trajectory/rewind-history.js +81 -0
  200. package/dist/src/trajectory/rewind-history.js.map +1 -0
  201. package/dist/src/trajectory/writer.d.ts +44 -3
  202. package/dist/src/trajectory/writer.js +80 -14
  203. package/dist/src/trajectory/writer.js.map +1 -1
  204. package/dist/src/tui/App.d.ts +8 -1
  205. package/dist/src/tui/App.js +453 -75
  206. package/dist/src/tui/App.js.map +1 -1
  207. package/dist/src/tui/InputBox.d.ts +1 -1
  208. package/dist/src/tui/InputBox.js +1 -1
  209. package/dist/src/tui/MessageList.js +1 -1
  210. package/dist/src/tui/MessageList.js.map +1 -1
  211. package/dist/src/tui/PermissionPrompt.js +5 -3
  212. package/dist/src/tui/PermissionPrompt.js.map +1 -1
  213. package/dist/src/tui/QueuedMessages.js +14 -8
  214. package/dist/src/tui/QueuedMessages.js.map +1 -1
  215. package/dist/src/tui/ToolCallPanel.js +2 -2
  216. package/dist/src/tui/ToolCallPanel.js.map +1 -1
  217. package/dist/src/tui/WorkspaceTrustPrompt.d.ts +8 -0
  218. package/dist/src/tui/WorkspaceTrustPrompt.js +37 -0
  219. package/dist/src/tui/WorkspaceTrustPrompt.js.map +1 -0
  220. package/dist/src/tui/draft-stash.d.ts +25 -0
  221. package/dist/src/tui/draft-stash.js +49 -0
  222. package/dist/src/tui/draft-stash.js.map +1 -0
  223. package/dist/src/tui/frame-budget.d.ts +2 -2
  224. package/dist/src/tui/frame-budget.js +3 -3
  225. package/dist/src/tui/frame-budget.js.map +1 -1
  226. package/dist/src/tui/help-format.d.ts +2 -2
  227. package/dist/src/tui/help-format.js +3 -3
  228. package/dist/src/tui/help-format.js.map +1 -1
  229. package/dist/src/tui/instructions-format.d.ts +14 -0
  230. package/dist/src/tui/instructions-format.js +24 -0
  231. package/dist/src/tui/instructions-format.js.map +1 -0
  232. package/dist/src/tui/mcp-format.d.ts +9 -0
  233. package/dist/src/tui/mcp-format.js +5 -3
  234. package/dist/src/tui/mcp-format.js.map +1 -1
  235. package/dist/src/tui/permission-rule-preview.d.ts +23 -0
  236. package/dist/src/tui/permission-rule-preview.js +38 -0
  237. package/dist/src/tui/permission-rule-preview.js.map +1 -0
  238. package/dist/src/tui/prompt-editor.d.ts +12 -0
  239. package/dist/src/tui/prompt-editor.js +38 -28
  240. package/dist/src/tui/prompt-editor.js.map +1 -1
  241. package/dist/src/tui/prompt-history-search.js +3 -2
  242. package/dist/src/tui/prompt-history-search.js.map +1 -1
  243. package/dist/src/tui/prompt-queue.d.ts +4 -2
  244. package/dist/src/tui/prompt-queue.js +22 -5
  245. package/dist/src/tui/prompt-queue.js.map +1 -1
  246. package/dist/src/tui/rewind-search.js +4 -3
  247. package/dist/src/tui/rewind-search.js.map +1 -1
  248. package/dist/src/tui/search-preview.d.ts +2 -0
  249. package/dist/src/tui/search-preview.js +9 -0
  250. package/dist/src/tui/search-preview.js.map +1 -0
  251. package/dist/src/tui/shell-command.js +4 -1
  252. package/dist/src/tui/shell-command.js.map +1 -1
  253. package/dist/src/tui/spinner.d.ts +1 -0
  254. package/dist/src/tui/spinner.js +6 -0
  255. package/dist/src/tui/spinner.js.map +1 -0
  256. package/dist/src/tui/status-format.d.ts +24 -0
  257. package/dist/src/tui/status-format.js +62 -2
  258. package/dist/src/tui/status-format.js.map +1 -1
  259. package/dist/src/tui/subagent-format.js +6 -0
  260. package/dist/src/tui/subagent-format.js.map +1 -1
  261. package/dist/src/tui/tangent.d.ts +122 -0
  262. package/dist/src/tui/tangent.js +153 -0
  263. package/dist/src/tui/tangent.js.map +1 -0
  264. package/dist/src/tui/task-format.d.ts +5 -0
  265. package/dist/src/tui/task-format.js +15 -0
  266. package/dist/src/tui/task-format.js.map +1 -1
  267. package/dist/src/tui/trust-format.d.ts +31 -0
  268. package/dist/src/tui/trust-format.js +102 -0
  269. package/dist/src/tui/trust-format.js.map +1 -0
  270. package/dist/src/tui/turn-state.d.ts +13 -1
  271. package/dist/src/tui/turn-state.js +13 -0
  272. package/dist/src/tui/turn-state.js.map +1 -1
  273. package/package.json +4 -3
@@ -16,16 +16,17 @@ import os from 'node:os';
16
16
  import path from 'node:path';
17
17
  import { Box, Text, useApp, useBoxMetrics, useInput, usePaste, useStdout, useWindowSize } from 'ink';
18
18
  import React, { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from 'react';
19
- import { AGENTS_FILENAME, MAX_INSTRUCTIONS_BYTES } from '../agent/instructions.js';
19
+ import { AGENTS_FILENAME } from '../agent/instructions.js';
20
20
  import { APPROVAL_MODES, describeApprovalMode, isApprovalMode, } from '../agent/permission.js';
21
21
  import { compactAndRecord, compactFocusRefusal, normalizeCompactFocus } from '../agent/compact.js';
22
+ import { permissionTestReport } from '../permissions-test.js';
22
23
  import { formatUsageValue, sumUsage, usageBuckets, usageRows, cacheEffectivenessRows } from '../agent/usage.js';
23
24
  import { describeModelCosts } from '../agent/cost.js';
24
25
  import { averageRequestInputTokens } from '../agent/call-stats.js';
25
26
  import { describeCacheMissCause, warmCacheSwitchNotice } from '../agent/cache-miss.js';
26
27
  import { runWithStreamResumption, STREAM_CONTINUATION_NOTICE } from '../agent/stream-resumption.js';
27
28
  import { retryFailureNotice } from '../agent/model-retry.js';
28
- import { isRefusalStop, REFUSAL_NOTICE } from '../agent/refusal.js';
29
+ import { isRefusalStop, refusalNoticeWithRewind } from '../agent/refusal.js';
29
30
  import { contextOverflowErrorMessage } from '../context-overflow-error.js';
30
31
  import { routeSdkLogs } from '../agent/sdk-logging.js';
31
32
  import { SYSTEM_PROMPT_FILENAME } from '../agent/system-prompt.js';
@@ -36,28 +37,34 @@ import { WORKFLOW_COMMAND_USAGE, parseWorkflowCommand } from '../commands/workfl
36
37
  import { MCP_CONFIG_FILENAME, mcpConfigCandidates } from '../mcp/registry.js';
37
38
  import { DARWIN_DIRNAME } from '../paths.js';
38
39
  import { readBackgroundTail, readBackgroundTails } from '../tools/background-tail.js';
40
+ import { formatShellEnvNotice } from '../tools/shell-env.js';
39
41
  import { exportTranscript } from '../trajectory/export.js';
42
+ import { loadRewindHistory } from '../trajectory/rewind-history.js';
40
43
  import { readPromptHistory, } from '../trajectory/prompt-history.js';
41
44
  import { InputBox, MAX_COMPLETIONS, completionSelection, moveCompletionSelection, } from './InputBox.js';
42
45
  import { busySuffix } from './busy-suffix.js';
46
+ import { formatInstructionsLoadedRow, formatInstructionsProblemRow } from './instructions-format.js';
43
47
  import { LIVE_BLOCK_CHROME_ROWS, wrapToRows } from './live-text.js';
44
48
  import { fenceOpenAfter } from './markdown.js';
45
49
  import { PERMISSION_BOX_FIXED_ROWS, frameBudget, promptBoxWanted, queueListWanted, toolDetailsVisible, toolInputRows, toolPanelWanted, } from './frame-budget.js';
46
50
  import { MessageList } from './MessageList.js';
47
51
  import { PermissionPrompt, permissionBoxClaim } from './PermissionPrompt.js';
52
+ import { PermissionRulePreview, ruleReviewClaim, ruleReviewLayout } from './permission-rule-preview.js';
48
53
  import { welcomeLayout } from './WelcomeHeader.js';
49
54
  import { ActiveToolCalls } from './ToolCallPanel.js';
50
55
  import { QueuedMessages } from './QueuedMessages.js';
51
- import { backspaceAtCursor, deleteAtCursor, deleteWordAfter, deleteWordBefore, insertAtCursor, killToRowEdge, layoutEditor, moveHorizontal, moveToRowEdge, moveVertical, moveWordHorizontal, popUndo, pushUndo, } from './prompt-editor.js';
56
+ import { backspaceAtCursor, deleteAtCursor, deleteWordAfter, deleteWordBefore, insertAtCursor, killToRowEdge, layoutEditor, moveHorizontal, moveToRowEdge, moveVertical, moveWordHorizontal, popUndo, pushUndo, updateLastCut, LAST_CUT_OVERFLOW_NOTICE, } from './prompt-editor.js';
52
57
  import { NO_WORKSPACE_PATHS, applyPathCompletion, scanWorkspacePaths, workspacePathsNote, } from './path-completion.js';
53
58
  import { promptCompletionState, visiblePromptCompletions, } from './prompt-completion.js';
54
59
  import { openPromptRecall, promptRecallIndicator, stepPromptRecall, } from './prompt-recall.js';
55
60
  import { acceptPromptHistorySearch, appendPromptHistorySearchQuery, backspacePromptHistorySearchQuery, cancelPromptHistorySearch, clearPromptHistorySearchQuery, movePromptHistorySearchSelection, openPromptHistorySearch, promptHistorySearchView, resolvePromptHistorySearch, } from './prompt-history-search.js';
56
61
  import { ESCAPE_REWIND_CHORD_MS, acceptRewindSearch, appendRewindSearchQuery, backspaceRewindSearchQuery, cancelRewindSearch, clearRewindSearchQuery, moveRewindSearchSelection, openRewindSearch, rewindSearchView, } from './rewind-search.js';
62
+ import { TANGENT_COMMAND_USAGE, armTangent, captureReturnPoint, discardedPromptCount, parseTangentCommand, rewindDraftAfterBranch, tangentCommandOutcome, tangentEndedByNotice, tangentHeaderSuffix, tangentReturnNotice, tangentStatusFact, } from './tangent.js';
57
63
  import { clipboardImageFact, readClipboardImage } from './clipboard-image.js';
64
+ import { DRAFT_STASH_DROP_NOTICE, stashHint, toggleDraftStash } from './draft-stash.js';
58
65
  import { delegationWakeEntries, hasQueuedImage, isTaskWake, partitionQueue, queuedCountHint, refusesToQueue, takeBackDraft, } from './prompt-queue.js';
59
66
  import { composeShellReport, parseShellCommand, projectShellOutput, runShellCommand, } from './shell-command.js';
60
- import { formatTaskCompletion, formatTasksReport } from './task-format.js';
67
+ import { formatTaskCompletion, formatTasksReport, runningTasksHeader } from './task-format.js';
61
68
  import { TASK_WAKE_TAIL_LINES, formatTaskNotification, formatTaskWakeUndelivered, taskNotificationFields, } from './task-wake.js';
62
69
  import { formatDispatchCancellation, formatDispatchCompletion, formatDispatchesReport, } from './subagent-format.js';
63
70
  import { liveBackgroundDelegationRefusal } from '../agent/background-delegation.js';
@@ -70,6 +77,7 @@ import { PlanChecklist } from './PlanChecklist.js';
70
77
  import { ringTerminalBell } from './terminal-bell.js';
71
78
  import { notifyTerminal } from './terminal-notify.js';
72
79
  import { createTerminalTitleWriter, deriveTerminalTitleState } from './terminal-title.js';
80
+ import { formatTrustNotice } from './trust-format.js';
73
81
  import { initialTurnState, turnReducer } from './turn-state.js';
74
82
  import { visualColor, visualMarker } from './visual-language.js';
75
83
  /** Window in which a second Ctrl+C means "exit", not "cancel again". */
@@ -108,7 +116,7 @@ function normalizeDraftText(value) {
108
116
  return value.replace(/\r+\n/g, '\n').replace(/\r/g, '\n').replace(NON_TEXT_CONTROLS, '');
109
117
  }
110
118
  export function App({ runtime: initialRuntime, permissions, initialHistory = [], startNewSession, startRewind, }) {
111
- const { exit, waitUntilRenderFlush } = useApp();
119
+ const { exit: inkExit, waitUntilRenderFlush } = useApp();
112
120
  const { columns, rows } = useWindowSize();
113
121
  const { write: writeToTerminal } = useStdout();
114
122
  // The live session. A prop at startup, state afterwards: `/clear` replaces the
@@ -136,11 +144,11 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
136
144
  const statusRef = useRef(status);
137
145
  statusRef.current = status;
138
146
  const [workspacePaths, setWorkspacePaths] = useState(NO_WORKSPACE_PATHS);
139
- const commandNames = useMemo(() => [
140
- ...BUILTIN_COMMAND_NAMES,
141
- ...runtime.info.commandNames,
142
- ...runtime.info.skillNames,
143
- ], [runtime]);
147
+ const commandNames = useMemo(() => [...new Set([
148
+ ...BUILTIN_COMMAND_NAMES,
149
+ ...runtime.info.commandNames,
150
+ ...runtime.info.skillNames,
151
+ ])], [runtime]);
144
152
  // Escape suppresses one computed query generation, not the draft. Mirrors are
145
153
  // required for the same reason as the editor/selection mirrors: a second batched
146
154
  // key must see the first Escape before React commits its render.
@@ -179,6 +187,23 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
179
187
  attachedImageRef.current = next;
180
188
  setAttachedImageState(next);
181
189
  }, []);
190
+ // SER-085: one unsent composer snapshot, never passed to submit/runtime/records.
191
+ const [draftStash, setDraftStashState] = useState(undefined);
192
+ const draftStashRef = useRef(draftStash);
193
+ const setDraftStash = useCallback((next) => {
194
+ draftStashRef.current = next;
195
+ setDraftStashState(next);
196
+ }, []);
197
+ const exit = useCallback(() => {
198
+ if (draftStashRef.current === undefined) {
199
+ inkExit();
200
+ return;
201
+ }
202
+ setDraftStash(undefined);
203
+ dispatch({ type: 'notice', text: DRAFT_STASH_DROP_NOTICE });
204
+ // Let the bounded notice reach Static before Ink unmounts the composer.
205
+ void waitUntilRenderFlush().finally(() => inkExit());
206
+ }, [dispatch, inkExit, setDraftStash, waitUntilRenderFlush]);
182
207
  const layout = layoutEditor(draft, columns, editor.cursor);
183
208
  const preferredColumn = useRef(undefined);
184
209
  // Composer undo (SER-044): the drafts destroyed by kill/word-delete chords,
@@ -186,6 +211,9 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
186
211
  // editor's ownership (submit, queue take-back, recall walk, search accept),
187
212
  // so Ctrl+_ can never resurrect a prompt that was already sent or recorded.
188
213
  const undoStack = useRef([]);
214
+ // SER-084: one last cut, cleared at the same ownership seams as undo. Never
215
+ // clipboard/record/model state; typing, movement and undo leave it intact.
216
+ const lastCut = useRef('');
189
217
  /**
190
218
  * Applies one destructive editing chord: snapshots the exact draft it
191
219
  * destroys (only when it destroys anything — a no-op kill at an edge must
@@ -197,8 +225,12 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
197
225
  const next = edit(current);
198
226
  if (next.text !== current.text)
199
227
  undoStack.current = pushUndo(undoStack.current, current);
228
+ const cut = updateLastCut(lastCut.current, current, next);
229
+ lastCut.current = cut.text;
230
+ if (cut.overflow)
231
+ dispatch({ type: 'notice', text: LAST_CUT_OVERFLOW_NOTICE, severity: 'warn' });
200
232
  setEditor(next);
201
- }, [setEditor]);
233
+ }, [dispatch, setEditor]);
202
234
  // The frame's fixed furniture. Only the header is *measured*: its height depends
203
235
  // on nothing below it, so measuring it cannot oscillate. Everything else states
204
236
  // what it wants and `frameBudget` hands out the rows — see `frame-budget.ts` for
@@ -231,6 +263,10 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
231
263
  const diagnosticsWarned = useRef(false);
232
264
  /** One bounded project-memory degradation notice per runtime. */
233
265
  const memoryWarned = useRef(false);
266
+ useEffect(() => {
267
+ if (runtime.config.agentCoreMemory !== undefined)
268
+ dispatch({ type: 'notice', text: runtime.cloudMemoryStatus });
269
+ }, [runtime, dispatch]);
234
270
  /** True while `/clear` is assembling the successor runtime; see the handler. */
235
271
  const clearing = useRef(false);
236
272
  /** Kill handle of the running `!` command; undefined whenever none is running. */
@@ -309,6 +345,15 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
309
345
  });
310
346
  }, [dispatch]);
311
347
  const pendingPermission = useSyncExternalStore((onChange) => permissions.subscribe(onChange), permissions.getSnapshot, permissions.getSnapshot);
348
+ const [ruleReview, setRuleReview] = useState();
349
+ const renderedRuleReview = useRef(undefined);
350
+ const reviewing = ruleReview?.request === pendingPermission && pendingPermission !== undefined
351
+ ? ruleReview : undefined;
352
+ // Background activity is independent of the foreground turn.
353
+ // The manager publishes starts and terminal transitions, never output or ticks.
354
+ const subscribeTaskActivity = useCallback((onChange) => runtime.subscribeToBackgroundTaskActivity(onChange), [runtime]);
355
+ const readRunningTaskCount = useCallback(() => runtime.runningBackgroundTaskCount, [runtime]);
356
+ const runningTaskCount = useSyncExternalStore(subscribeTaskActivity, readRunningTaskCount, readRunningTaskCount);
312
357
  // A pending confirmation outranks streaming: the loop is blocked on it.
313
358
  const effectiveStatus = pendingPermission !== undefined ? 'awaiting-permission' : status;
314
359
  // Built-ins stay first, then project commands, then skills. Collision filtering
@@ -384,6 +429,16 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
384
429
  rewindSearchRef.current = next;
385
430
  setRewindSearchState(next);
386
431
  }, []);
432
+ // `/tangent` (SER-083): live TUI session state like the permission mode — never
433
+ // persisted or recorded, dropped by `/clear`, absent in a resumed session. In
434
+ // state for the header/status projections and mirrored in a ref for the
435
+ // callbacks that read it after an await.
436
+ const [tangent, setTangentState] = useState(undefined);
437
+ const tangentRef = useRef(tangent);
438
+ const setTangent = useCallback((next) => {
439
+ tangentRef.current = next;
440
+ setTangentState(next);
441
+ }, []);
387
442
  const updateRewindSearch = useCallback((update) => {
388
443
  const current = rewindSearchRef.current;
389
444
  if (current !== undefined)
@@ -436,6 +491,43 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
436
491
  setRewindSearch(openRewindSearch(opening, runtime.info.sessionId, catalogue.checkpoints));
437
492
  return true;
438
493
  }, [dispatch, runtime, setEditor, setHistorySearch, setRecall, setRewindSearch, startRewind]);
494
+ // The one way a rewind successor takes over the screen — `/rewind` acceptance and
495
+ // a `/tangent` return (SER-083) both land here, so the terminal clear, the editor
496
+ // hand-back rule, the per-session latches and the omission notice cannot drift.
497
+ // The only difference between the two is the draft: `rewindDraftAfterBranch`.
498
+ const adoptBranchSuccessor = useCallback(async (next, kind, checkpoint, sourceSessionId) => {
499
+ // The predecessor is retired, so its closing trajectory append has settled.
500
+ // Display-only replay cannot alter the SDK-restored conversation.
501
+ const history = await loadRewindHistory(next.info.projectRoot, sourceSessionId, checkpoint);
502
+ writeToTerminal(CLEAR_TERMINAL);
503
+ recordAction({ type: 'clear', history });
504
+ setRuntime(next);
505
+ clipboardReadGeneration.current += 1;
506
+ if (draftStashRef.current !== undefined) {
507
+ setDraftStash(undefined);
508
+ withNoticeDiagnostics(recordAction, next.diagnostics)({ type: 'notice', text: DRAFT_STASH_DROP_NOTICE });
509
+ }
510
+ setRewindSearch(undefined);
511
+ // The restored session replaces the whole editor state; the selected prompt
512
+ // returns unsent (a tangent return hands back nothing — the user asked to
513
+ // return, not to resend), and undo must not reach across the session boundary.
514
+ undoStack.current = [];
515
+ lastCut.current = '';
516
+ const draft = rewindDraftAfterBranch(kind, checkpoint.prompt);
517
+ setEditor({ text: draft, cursor: { offset: draft.length, affinity: 'upstream' } });
518
+ setSelectedCompletion(0);
519
+ contextWarnLatch.current = createContextWarnLatch();
520
+ trajectoryWarned.current = false;
521
+ diagnosticsWarned.current = false;
522
+ pendingShellReports.current = [];
523
+ setQueued([]);
524
+ withNoticeDiagnostics(recordAction, next.diagnostics)({
525
+ type: 'notice',
526
+ severity: 'warn',
527
+ text: `rewound conversation into new session ${next.info.sessionId}; source ${sourceSessionId} remains saved and resumable. ` +
528
+ 'Workspace unchanged: workspace files, shell and ! effects, hooks, MCP writes, subagents, background jobs, and learned-memory files were not rewound.',
529
+ });
530
+ }, [recordAction, setDraftStash, setEditor, setQueued, setRewindSearch, setSelectedCompletion, writeToTerminal]);
439
531
  // When the first no-op Escape landed on an empty idle composer; a second one
440
532
  // within ESCAPE_REWIND_CHORD_MS opens the chooser. Cleared by any other key or
441
533
  // owner, so the chord can never straddle a draft, a turn or a menu.
@@ -502,7 +594,8 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
502
594
  : undefined;
503
595
  const busyRetryWait = busyElapsedMs === undefined ? undefined : liveRetryWait(runtime);
504
596
  const queuedCounts = partitionQueue(queued);
505
- const streamingHint = hintForStatus(effectiveStatus, busyElapsedMs === undefined ? undefined : busySuffix(busyElapsedMs, liveSpend(runtime), busyRetryWait), queuedCounts.user.length, queuedCounts.wakes.length);
597
+ const statusHint = hintForStatus(effectiveStatus, busyElapsedMs === undefined ? undefined : busySuffix(busyElapsedMs, liveSpend(runtime), busyRetryWait), queuedCounts.user.length, queuedCounts.wakes.length);
598
+ const streamingHint = statusHint === undefined ? undefined : stashHint(statusHint, draftStash !== undefined, columns);
506
599
  const activeToolClaims = state.activeTools.map((tool) => ({
507
600
  detailRows: toolDetailsVisible(tool.name, state.toolDetailsExpanded)
508
601
  ? toolInputRows(tool.input, columns, tool.name).length
@@ -534,7 +627,9 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
534
627
  floor: 1,
535
628
  }
536
629
  : {
537
- wanted: permissionBoxClaim(pendingPermission, permissions.waiting, columns),
630
+ wanted: reviewing === undefined
631
+ ? permissionBoxClaim(pendingPermission, permissions.waiting, columns)
632
+ : ruleReviewClaim(reviewing.rule, columns),
538
633
  // The box keeps its heading, summary and decision row while it can:
539
634
  // a question that scrolled off the frame blocks the agent loop.
540
635
  floor: PERMISSION_BOX_FIXED_ROWS,
@@ -551,24 +646,46 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
551
646
  // One row still names the checklist and states its full item count.
552
647
  floor: state.livePlan.length === 0 ? 0 : 1,
553
648
  },
554
- // The queued listing (SER-027): one row per entry, cut entries stated by the
555
- // queue's own notice row. Floor 0 — the busy hint's count keeps a fully cut
556
- // listing from going invisible.
557
- queued: { wanted: queueListWanted(queued.length), floor: 0 },
649
+ // Typed entries keep their rows; settled-task notifications share one summary.
650
+ // Floor 0 — the busy hint counts both when the listing is fully cut.
651
+ queued: { wanted: queueListWanted(queued.length, queued.filter(isTaskWake).length), floor: 0 },
558
652
  // The answer yields first: it is the one participant whose content is already
559
653
  // guaranteed to reach `<Static>` history in full.
560
654
  live: { wanted: liveTextRows === 0 ? 0 : liveTextRows + LIVE_BLOCK_CHROME_ROWS, floor: 0 },
561
655
  });
562
- // Spinner tick, while a model is actually streaming or a `!` command is running —
563
- // the running command's panel row carries the same spinner and elapsed suffix.
564
- // `/compact` waits on its own model calls too, but has no per-call tool panel to
565
- // animate.
656
+ // A changed viewport starts review over. An Enter may acknowledge only a page
657
+ // flushed by Ink, never a newly selected rule or an unrendered next page.
658
+ const activeRuleReview = useMemo(() => reviewing === undefined ? undefined : {
659
+ ...reviewing,
660
+ offset: reviewing.columns === columns && reviewing.maxRows === grants.prompt ? reviewing.offset : 0,
661
+ columns,
662
+ maxRows: grants.prompt,
663
+ }, [reviewing, columns, grants.prompt]);
664
+ useLayoutEffect(() => {
665
+ renderedRuleReview.current = undefined;
666
+ let current = true;
667
+ if (reviewing !== undefined && activeRuleReview !== undefined &&
668
+ (reviewing.columns !== columns || reviewing.maxRows !== grants.prompt))
669
+ setRuleReview(activeRuleReview);
670
+ else if (ruleReview !== undefined && reviewing === undefined)
671
+ setRuleReview(undefined);
672
+ else if (activeRuleReview !== undefined)
673
+ void waitUntilRenderFlush().then(() => {
674
+ if (current)
675
+ renderedRuleReview.current = activeRuleReview;
676
+ }, () => { });
677
+ return () => { current = false; };
678
+ }, [activeRuleReview, reviewing, ruleReview, columns, grants.prompt, waitUntilRenderFlush]);
679
+ // One clock for live tools and the background-task marker, including while the
680
+ // foreground is idle or awaiting permission. No tick when all activity stops.
681
+ // `/compact` alone has no per-call tool panel to animate.
682
+ const animateActivity = effectiveStatus === 'streaming' || effectiveStatus === 'shell' || runningTaskCount > 0;
566
683
  useEffect(() => {
567
- if (effectiveStatus !== 'streaming' && effectiveStatus !== 'shell')
684
+ if (!animateActivity)
568
685
  return;
569
686
  const timer = setInterval(() => setFrame((f) => f + 1), SPINNER_INTERVAL_MS);
570
687
  return () => clearInterval(timer);
571
- }, [effectiveStatus]);
688
+ }, [animateActivity]);
572
689
  // A `!` command must not outlive the TUI that ran it: on unmount (Ctrl+D, /exit,
573
690
  // a second Ctrl+C) the group gets the same TERM→KILL reaping a cancel gives it.
574
691
  useEffect(() => () => shellRun.current?.kill(), []);
@@ -608,6 +725,26 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
608
725
  return;
609
726
  dispatch({ type: 'notice', text: `diagnostics: recording SDK debug/info to ${file}` });
610
727
  }, [dispatch, runtime]);
728
+ // SER-082: what model-spawned shells did not inherit, said once in the transcript
729
+ // on the same terms as the diagnostics line above — a frame row is not an option,
730
+ // and a clean environment adds no line. Names only, a few of them; `/status` has
731
+ // the bounded full list. Per runtime, so a `/clear` successor states it again.
732
+ useEffect(() => {
733
+ const notice = formatShellEnvNotice(runtime.info.shellEnv.withheld);
734
+ if (notice === undefined)
735
+ return;
736
+ dispatch({ type: 'notice', text: `shell env: ${notice} — see /status` });
737
+ }, [dispatch, runtime]);
738
+ // SER-090: what the checkout declared and this session held back, said once in the
739
+ // transcript on the same terms — a trusted project or an empty inventory adds no
740
+ // line. Per runtime, so a `/clear` successor (which inherits the decision) states
741
+ // it again; `/status` and `/mcp` carry the same held items on their existing rows.
742
+ useEffect(() => {
743
+ const notice = formatTrustNotice(runtime.info.workspaceTrust, runtime.info.projectRoot);
744
+ if (notice === undefined)
745
+ return;
746
+ dispatch({ type: 'notice', text: notice, severity: 'warn' });
747
+ }, [dispatch, runtime]);
611
748
  // Terminal task events are transcript-only observers: they never alter turn
612
749
  // status, active tools, permissions, or the agent loop. React dispatch also
613
750
  // causes an immediate idle render; cleanup prevents shutdown notices after exit.
@@ -711,6 +848,7 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
711
848
  // The queue's entries replace the draft wholesale; the drafts destroyed by
712
849
  // earlier chords are no longer what Ctrl+_ should bring back.
713
850
  undoStack.current = [];
851
+ lastCut.current = '';
714
852
  setEditor({ text, cursor: { offset: text.length, affinity: 'upstream' } });
715
853
  preferredColumn.current = undefined;
716
854
  setSelectedCompletion(0);
@@ -757,9 +895,12 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
757
895
  answerTailLive = false;
758
896
  }
759
897
  // The SDK ends a refused turn normally, so the transcript would show an
760
- // empty (or cut-short) answer with no reason. Name it once, as a notice.
898
+ // empty (or cut-short) answer with no reason. Name it once, as a notice,
899
+ // with the stop reason actually received (SRF-029) and the remedy only
900
+ // this driver has: the runtime catalogued the prompt, so `/rewind` to it
901
+ // removes the declined exchange (SRF-030).
761
902
  if (event.type === 'agentResultEvent' && isRefusalStop(event.result.stopReason)) {
762
- dispatch({ type: 'notice', text: REFUSAL_NOTICE, severity: 'warn' });
903
+ dispatch({ type: 'notice', text: refusalNoticeWithRewind(event.result.stopReason), severity: 'warn' });
763
904
  }
764
905
  }
765
906
  }, (error) => {
@@ -822,6 +963,24 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
822
963
  turnAborted.current = false;
823
964
  returnQueuedToEditor(true);
824
965
  }
966
+ // An armed `/tangent` (SER-083) resolves on the first prompt after it: the
967
+ // checkpoint `send()` captured before this prompt is the return point, read
968
+ // back from the catalogue the runtime already keeps — no snapshot of our own,
969
+ // no second listing shape. No growth means the tangent ends here, saying why.
970
+ const armed = tangentRef.current;
971
+ if (armed?.phase === 'armed') {
972
+ const facts = { image: image !== undefined, sessionOriginated: origin !== undefined, completed: !failed };
973
+ let catalogue;
974
+ try {
975
+ catalogue = await runtime.listRewindCheckpoints();
976
+ }
977
+ catch (error) {
978
+ catalogue = { checkpoints: [], capped: false, problem: error instanceof Error ? error.message : String(error) };
979
+ }
980
+ const outcome = captureReturnPoint(armed, catalogue, facts);
981
+ setTangent(outcome.kind === 'started' ? outcome.state : undefined);
982
+ dispatch({ type: 'notice', text: outcome.notice, ...(outcome.kind === 'ended' && { severity: 'warn' }) });
983
+ }
825
984
  // Post-turn context-pressure check: reuse the configurable warning latch
826
985
  // and existing Static transcript notice — no second threshold or live row.
827
986
  // Compaction remains an explicit user command. A failed estimate is silently
@@ -857,6 +1016,8 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
857
1016
  diagnosticsWarned.current = true;
858
1017
  dispatch({ type: 'notice', text: `diagnostics: ${diagnosticsProblem}`, severity: 'warn' });
859
1018
  }
1019
+ if (runtime.config.agentCoreMemory !== undefined)
1020
+ dispatch({ type: 'notice', text: runtime.cloudMemoryStatus });
860
1021
  const memoryProblem = runtime.memoryStatus?.problem;
861
1022
  if (memoryProblem !== undefined && !memoryWarned.current) {
862
1023
  memoryWarned.current = true;
@@ -866,9 +1027,13 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
866
1027
  dispatch({ type: 'notice', text: `hook: ${problem}`, severity: 'warn' });
867
1028
  }
868
1029
  return !failed;
869
- }, [prepareAnswerClose, returnQueuedToEditor, runtime, waitUntilRenderFlush]);
1030
+ }, [prepareAnswerClose, returnQueuedToEditor, runtime, setTangent, waitUntilRenderFlush]);
870
1031
  const submit = useCallback(async (raw, queuedEntry) => {
871
1032
  const text = raw.trim();
1033
+ if (clearing.current) {
1034
+ dispatch({ type: 'notice', text: 'Session management in progress; submit again when it finishes' });
1035
+ return;
1036
+ }
872
1037
  // A drained entry owns its optional image, including explicit absence. It
873
1038
  // must never borrow a newer attachment still sitting beside the editor.
874
1039
  const image = queuedEntry === undefined ? attachedImageRef.current : queuedEntry.image;
@@ -879,6 +1044,7 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
879
1044
  // that retain the draft: clearing there only loses undo history — the
880
1045
  // failure mode this guards against is resurrecting a sent prompt.
881
1046
  undoStack.current = [];
1047
+ lastCut.current = '';
882
1048
  // A drained background-task wake (SER-069): one ordinary turn through the
883
1049
  // same `runTurn` a prompt uses — hooks, permission gate, trajectory barrier
884
1050
  // and `TurnComplete` all fire — but nothing above the model applies: no
@@ -978,7 +1144,7 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
978
1144
  // like /mode: this never reaches the agent, and there is no tool that can
979
1145
  // invoke it. Additions have no path through here; they stay exclusively
980
1146
  // with the permission-prompt grant flow.
981
- if (text === '/permissions' || text.startsWith('/permissions ')) {
1147
+ if (/^\/permissions(?:\s|$)/.test(text)) {
982
1148
  setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
983
1149
  setSelectedCompletion(0);
984
1150
  dispatch({ type: 'userInput', text });
@@ -989,6 +1155,25 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
989
1155
  // narrows future context synchronously; remember is an explicit typed command,
990
1156
  // never a model tool. Keep it idle-only so a running request cannot race a
991
1157
  // system-prompt replacement.
1158
+ if (/^\/cloud-memory(?:\s|$)/.test(text)) {
1159
+ if (status !== 'idle' || clearing.current) {
1160
+ dispatch({ type: 'notice', text: '/cloud-memory does not queue — run it after current work finishes' });
1161
+ return;
1162
+ }
1163
+ clearing.current = true;
1164
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1165
+ setSelectedCompletion(0);
1166
+ try {
1167
+ dispatch({ type: 'notice', text: await runtime.manageCloudMemory(text.slice('/cloud-memory'.length).trim()) });
1168
+ }
1169
+ catch (error) {
1170
+ dispatch({ type: 'notice', text: error instanceof Error ? error.message : 'Cloud memory context refresh failed' });
1171
+ }
1172
+ finally {
1173
+ clearing.current = false;
1174
+ }
1175
+ return;
1176
+ }
992
1177
  if (/^\/memory(?:\s|$)/.test(text)) {
993
1178
  if (status !== 'idle') {
994
1179
  dispatch({ type: 'notice', text: '/memory does not queue — run it after current work finishes' });
@@ -1152,6 +1337,7 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1152
1337
  overriddenServerNames: runtime.info.mcpOverriddenServerNames,
1153
1338
  ignoredConfigPath: runtime.info.mcpIgnoredConfigPath,
1154
1339
  candidatePaths: [candidates.global, candidates.preferred, candidates.fallback],
1340
+ heldServers: runtime.info.workspaceTrust.heldMcpServers,
1155
1341
  }),
1156
1342
  });
1157
1343
  return;
@@ -1169,6 +1355,7 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1169
1355
  dispatch({ type: 'notice', text: '/status takes no arguments' });
1170
1356
  return;
1171
1357
  }
1358
+ await runtime.refreshCloudPolicy(); // Local-only peer policy discovery; never cloud retrieval.
1172
1359
  // The /context machinery, degraded rather than fatal: a failed estimate
1173
1360
  // costs one line of the report, never the report.
1174
1361
  let context;
@@ -1190,10 +1377,14 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1190
1377
  mode: runtime.permissionMode,
1191
1378
  allowRuleCount: runtime.allowRuleCount,
1192
1379
  denyRuleCount: runtime.denyRuleCount,
1380
+ tangent: tangentStatusFact(tangentRef.current),
1381
+ cloudMemory: runtime.cloudMemoryStatus,
1193
1382
  mcpServers: runtime.listMcpServers(),
1194
1383
  skillNames: runtime.info.skillNames,
1195
1384
  hookSources: runtime.info.hookSources,
1196
1385
  hookShadowNotices: runtime.info.hookShadowNotices,
1386
+ shellEnv: runtime.info.shellEnv,
1387
+ workspaceTrust: runtime.info.workspaceTrust,
1197
1388
  projectRoot: runtime.info.projectRoot,
1198
1389
  homeDir: os.homedir(),
1199
1390
  trajectory: runtime.trajectoryStatus,
@@ -1340,6 +1531,86 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1340
1531
  }
1341
1532
  return;
1342
1533
  }
1534
+ // `/tangent` (SER-083): a bookmark over the rewind path. Below the busy check
1535
+ // like `/rewind` (it refuses to queue: arming is a statement about "the next
1536
+ // prompt", and the return replaces the runtime). Arming only reads the
1537
+ // catalogue; the return is `startRewind` on the captured row, adopted through
1538
+ // the same successor path as `/rewind` — minus the draft hand-back.
1539
+ const tangentCommand = parseTangentCommand(text);
1540
+ if (tangentCommand !== undefined) {
1541
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1542
+ setSelectedCompletion(0);
1543
+ dispatch({ type: 'userInput', text });
1544
+ if (tangentCommand === 'usage') {
1545
+ dispatch({ type: 'notice', text: TANGENT_COMMAND_USAGE });
1546
+ return;
1547
+ }
1548
+ if (startRewind === undefined) {
1549
+ dispatch({ type: 'notice', text: '/tangent is not available in this driver', severity: 'warn' });
1550
+ return;
1551
+ }
1552
+ const outcome = tangentCommandOutcome(tangentRef.current, tangentCommand);
1553
+ if (outcome.action === 'notice' || outcome.action === 'disarm') {
1554
+ if (outcome.action === 'disarm')
1555
+ setTangent(undefined);
1556
+ dispatch({ type: 'notice', text: outcome.notice });
1557
+ return;
1558
+ }
1559
+ if (outcome.action === 'arm') {
1560
+ const armed = armTangent(await runtime.listRewindCheckpoints());
1561
+ if (armed.kind === 'refused') {
1562
+ dispatch({ type: 'notice', text: armed.notice, severity: 'warn' });
1563
+ return;
1564
+ }
1565
+ setTangent(armed.state);
1566
+ dispatch({ type: 'notice', text: armed.notice });
1567
+ return;
1568
+ }
1569
+ // Return: the same refusals `/rewind` acceptance has, in the same order.
1570
+ const liveDelegations = runtime.listBackgroundDelegations();
1571
+ if (liveDelegations.length > 0) {
1572
+ dispatch({ type: 'notice', text: liveBackgroundDelegationRefusal('/tangent', liveDelegations), severity: 'warn' });
1573
+ return;
1574
+ }
1575
+ if (clearing.current) {
1576
+ dispatch({ type: 'notice', text: 'still starting the new session — press enter again once it appears' });
1577
+ return;
1578
+ }
1579
+ const sourceSessionId = runtime.info.sessionId;
1580
+ clearing.current = true;
1581
+ let next;
1582
+ let discarded;
1583
+ try {
1584
+ // Counted before the branch, from the source's own catalogue; a listing
1585
+ // failure costs precision, never the return.
1586
+ let catalogue;
1587
+ try {
1588
+ catalogue = await runtime.listRewindCheckpoints();
1589
+ }
1590
+ catch {
1591
+ catalogue = undefined;
1592
+ }
1593
+ discarded = discardedPromptCount(outcome.state, catalogue);
1594
+ next = await startRewind(outcome.state.returnPoint);
1595
+ await adoptBranchSuccessor(next, 'tangent', outcome.state.returnPoint, sourceSessionId);
1596
+ }
1597
+ catch (error) {
1598
+ // Stale or unmapped row: the rewind path's own error, and the tangent stays
1599
+ // armed — nothing was released, the user can still /rewind by hand.
1600
+ dispatch({
1601
+ type: 'notice',
1602
+ text: `could not rewind; still in ${sourceSessionId}: ${error instanceof Error ? error.message : String(error)}`,
1603
+ severity: 'error',
1604
+ });
1605
+ return;
1606
+ }
1607
+ finally {
1608
+ clearing.current = false;
1609
+ }
1610
+ setTangent(undefined);
1611
+ withNoticeDiagnostics(recordAction, next.diagnostics)({ type: 'notice', text: tangentReturnNotice(discarded) });
1612
+ return;
1613
+ }
1343
1614
  // the local reports above it: this replaces the conversation the running turn is
1344
1615
  // streaming into, and the SDK's session snapshot is written when that turn ends —
1345
1616
  // so a mid-turn switch would hand the old session's manager a conversation it no
@@ -1398,6 +1669,10 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1398
1669
  writeToTerminal(CLEAR_TERMINAL);
1399
1670
  dispatch({ type: 'clear' });
1400
1671
  setRuntime(next);
1672
+ if (draftStashRef.current !== undefined) {
1673
+ setDraftStash(undefined);
1674
+ withNoticeDiagnostics(recordAction, next.diagnostics)({ type: 'notice', text: DRAFT_STASH_DROP_NOTICE });
1675
+ }
1401
1676
  // Per-session latches, reset with the session they were latched for.
1402
1677
  contextWarnLatch.current = createContextWarnLatch();
1403
1678
  trajectoryWarned.current = false;
@@ -1419,6 +1694,12 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1419
1694
  text: `cleared — new session ${next.info.sessionId}. Previous session ${previousSessionId} is saved and ` +
1420
1695
  `resumable (darwin --session ${previousSessionId}); background jobs and MCP servers keep running.`,
1421
1696
  });
1697
+ // The tangent bookmarked a conversation this session no longer holds
1698
+ // (SER-083): it ends with one notice, and no rewind is performed for it.
1699
+ if (tangentRef.current !== undefined) {
1700
+ setTangent(undefined);
1701
+ withNoticeDiagnostics(recordAction, next.diagnostics)({ type: 'notice', text: tangentEndedByNotice('/clear') });
1702
+ }
1422
1703
  return;
1423
1704
  }
1424
1705
  if (text === '/compact' || text.startsWith('/compact ')) {
@@ -1474,7 +1755,17 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1474
1755
  dispatch({ type: 'notice', text: WORKFLOW_COMMAND_USAGE });
1475
1756
  return;
1476
1757
  }
1477
- setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1758
+ // A drained entry must not erase a newer draft. Reserve its image across
1759
+ // asynchronous activation too, so a dequeued image cannot lose ownership.
1760
+ if (queuedEntry === undefined) {
1761
+ setEditor({ text: '', cursor: { offset: 0, affinity: 'downstream' } });
1762
+ }
1763
+ if (image !== undefined) {
1764
+ imageTurnInFlight.current = true;
1765
+ clipboardReadGeneration.current += 1;
1766
+ if (queuedEntry === undefined)
1767
+ setAttachedImage(undefined);
1768
+ }
1478
1769
  setSelectedCompletion(0);
1479
1770
  dispatch({ type: 'userInput', text });
1480
1771
  // Skills and project commands send their expanded prompt instead of the
@@ -1489,7 +1780,11 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1489
1780
  ? `loaded skill "${expanded.skill.name}"`
1490
1781
  : expanded.kind === 'workflow'
1491
1782
  ? 'delegating via the workflow tool'
1492
- : `loaded command "/${expanded.command.name}"`,
1783
+ : expanded.kind === 'init'
1784
+ ? 'writing project instructions with /init'
1785
+ : expanded.kind === 'review'
1786
+ ? 'reviewing current changes with /review'
1787
+ : `loaded command "/${expanded.command.name}"`,
1493
1788
  });
1494
1789
  toSend = expanded.message;
1495
1790
  }
@@ -1497,9 +1792,17 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1497
1792
  catch (error) {
1498
1793
  dispatch({
1499
1794
  type: 'notice',
1500
- text: `could not expand ${text}: ${error instanceof Error ? error.message : String(error)}`,
1795
+ text: `could not expand ${text}: ${error instanceof Error ? error.message : String(error)}; prompt not sent — restored to the editor`,
1501
1796
  severity: 'error',
1502
1797
  });
1798
+ if (image !== undefined)
1799
+ imageTurnInFlight.current = false;
1800
+ // The drain already shifted this entry. Return it plus later user entries
1801
+ // ahead of any draft typed during activation; wakes retain their ordinary
1802
+ // queue disposition. No user command remains to auto-drain after failure.
1803
+ setQueued([{ text: raw, ...(image === undefined ? {} : { image }) }, ...queuedRef.current]);
1804
+ returnQueuedToEditor(true);
1805
+ return;
1503
1806
  }
1504
1807
  // Reports from `!` commands run since the last turn ride ahead of this
1505
1808
  // prompt (PRD D5): one string through the ordinary send path, so the
@@ -1512,12 +1815,6 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1512
1815
  // The invocation owns its image while streaming. Success consumes it; a
1513
1816
  // provider/model rejection restores the exact image + literal prompt so the
1514
1817
  // user can retry or remove without rereading the clipboard.
1515
- if (image !== undefined)
1516
- imageTurnInFlight.current = true;
1517
- if (image !== undefined && queuedEntry === undefined) {
1518
- clipboardReadGeneration.current += 1;
1519
- setAttachedImage(undefined);
1520
- }
1521
1818
  const completed = await runTurn(toSend, text, image);
1522
1819
  if (image !== undefined)
1523
1820
  imageTurnInFlight.current = false;
@@ -1531,7 +1828,7 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1531
1828
  severity: 'warn',
1532
1829
  });
1533
1830
  }
1534
- }, [dispatch, exit, openRewindChooser, recordAction, returnQueuedToEditor, runtime, runTurn, setAttachedImage, setEditor, setQueued, startNewSession, status, writeToTerminal]);
1831
+ }, [adoptBranchSuccessor, dispatch, exit, openRewindChooser, recordAction, returnQueuedToEditor, runtime, runTurn, setAttachedImage, setDraftStash, setEditor, setQueued, setTangent, startNewSession, startRewind, status, writeToTerminal]);
1535
1832
  // The drain (SER-027): when the session is idle and nothing owns the keyboard,
1536
1833
  // the oldest queued entry goes back through the ordinary submit path — its own
1537
1834
  // turn for a prompt, its own run for a `!`, its own `userInput` recorded at
@@ -1581,6 +1878,12 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1581
1878
  * tool call they just approved.
1582
1879
  */
1583
1880
  const answerPermission = useCallback((decision) => {
1881
+ // The queue may have withdrawn/replaced the rendered question before React
1882
+ // handles this key. Neither answer nor persistence may target its successor.
1883
+ if (pendingPermission === undefined || permissions.current !== pendingPermission || pendingPermission.withdrawn.aborted)
1884
+ return;
1885
+ renderedRuleReview.current = undefined;
1886
+ setRuleReview(undefined);
1584
1887
  permissions.answer(decision);
1585
1888
  const rule = decision.rule;
1586
1889
  if (rule === undefined)
@@ -1599,7 +1902,7 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1599
1902
  severity: 'warn',
1600
1903
  });
1601
1904
  });
1602
- }, [permissions, runtime]);
1905
+ }, [pendingPermission, permissions, runtime]);
1603
1906
  /** Any edit ends the walk: the draft is the user's again, not an entry from the record. */
1604
1907
  const endRecall = useCallback(() => {
1605
1908
  if (recallRef.current !== undefined)
@@ -1652,6 +1955,7 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1652
1955
  // A recalled record entry replaces the draft: the recall walk keeps its own
1653
1956
  // snapshot behavior, and undo must not cross into a different prompt's text.
1654
1957
  undoStack.current = [];
1958
+ lastCut.current = '';
1655
1959
  setEditor({ text, cursor: { offset: text.length, affinity: 'upstream' } });
1656
1960
  preferredColumn.current = undefined;
1657
1961
  // A recalled `/…` prompt reopens the command menu, so the selection has to start
@@ -1693,7 +1997,7 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1693
1997
  const value = editorRef.current;
1694
1998
  if (current === undefined) {
1695
1999
  // Only from an empty draft: typed text is never replaced by a recalled prompt,
1696
- // which is why no stashed draft has to exist for this to be safe.
2000
+ // independently of the explicit Ctrl+S stash.
1697
2001
  if (direction !== 'older' || value.text !== '')
1698
2002
  return false;
1699
2003
  // A reading that a finished turn has marked stale — or one still arriving — opens a
@@ -1765,6 +2069,7 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1765
2069
  // Escape-restore snapshot stays untouched, but undo must not reach
1766
2070
  // back into the pre-search draft from a different text.
1767
2071
  undoStack.current = [];
2072
+ lastCut.current = '';
1768
2073
  setEditor(accepted);
1769
2074
  setSelectedCompletion(0);
1770
2075
  preferredColumn.current = undefined;
@@ -1807,6 +2112,7 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1807
2112
  let next;
1808
2113
  try {
1809
2114
  next = await startRewind(selected);
2115
+ await adoptBranchSuccessor(next, 'rewind', selected, search.sourceSessionId);
1810
2116
  }
1811
2117
  catch (error) {
1812
2118
  dispatch({
@@ -1819,27 +2125,13 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1819
2125
  finally {
1820
2126
  clearing.current = false;
1821
2127
  }
1822
- writeToTerminal(CLEAR_TERMINAL);
1823
- recordAction({ type: 'clear' });
1824
- setRuntime(next);
1825
- setRewindSearch(undefined);
1826
- // The restored session replaces the whole editor state; the selected prompt
1827
- // returns unsent, and undo must not reach across the session boundary.
1828
- undoStack.current = [];
1829
- setEditor({ text: selected.prompt, cursor: { offset: selected.prompt.length, affinity: 'upstream' } });
1830
- setSelectedCompletion(0);
1831
- contextWarnLatch.current = createContextWarnLatch();
1832
- trajectoryWarned.current = false;
1833
- diagnosticsWarned.current = false;
1834
- pendingShellReports.current = [];
1835
- setQueued([]);
1836
- withNoticeDiagnostics(recordAction, next.diagnostics)({
1837
- type: 'notice',
1838
- severity: 'warn',
1839
- text: `rewound conversation into new session ${next.info.sessionId}; source ${search.sourceSessionId} remains saved and resumable. ` +
1840
- 'Workspace unchanged: workspace files, shell and ! effects, hooks, MCP writes, subagents, background jobs, and learned-memory files were not rewound.',
1841
- });
1842
- }, [dispatch, recordAction, runtime, setEditor, setQueued, setRewindSearch, startRewind, writeToTerminal]);
2128
+ // A tangent bookmarked the conversation just left behind (SER-083): it ends
2129
+ // with one notice, and the rewind the user chose is the only rewind performed.
2130
+ if (tangentRef.current !== undefined) {
2131
+ setTangent(undefined);
2132
+ withNoticeDiagnostics(recordAction, next.diagnostics)({ type: 'notice', text: tangentEndedByNotice('/rewind') });
2133
+ }
2134
+ }, [adoptBranchSuccessor, dispatch, recordAction, runtime, setRewindSearch, setTangent, startRewind]);
1843
2135
  const handleRewindSearchKey = useCallback((typed, key) => {
1844
2136
  const current = rewindSearchRef.current;
1845
2137
  if (current === undefined)
@@ -1934,17 +2226,40 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1934
2226
  }
1935
2227
  // Confirmations take the keyboard while one is pending.
1936
2228
  if (pendingPermission !== undefined) {
1937
- if (typed === 'y' || typed === 'Y')
2229
+ if (permissions.current !== pendingPermission || pendingPermission.withdrawn.aborted)
2230
+ return;
2231
+ // Ctrl+Y is a composer chord, never plain approval. y stays once-only even
2232
+ // during review; Esc still denies (b is the non-denying way back).
2233
+ if ((typed === 'y' || typed === 'Y') && !key.ctrl && !key.meta)
1938
2234
  answerPermission({ allowed: true });
1939
2235
  else if (typed === 'n' || typed === 'N' || key.escape)
1940
2236
  answerPermission({ allowed: false });
1941
- // Lowercase takes the narrow offer, uppercase the whole tool — the more
1942
- // sweeping choice costs the more deliberate keystroke.
1943
- else if (typed === 'a' || typed === 'A') {
2237
+ else if (!key.ctrl && !key.meta && typed === 'b' && reviewing !== undefined) {
2238
+ renderedRuleReview.current = undefined;
2239
+ setRuleReview(undefined);
2240
+ }
2241
+ else if (!key.ctrl && !key.meta && key.return && reviewing !== undefined) {
2242
+ const shown = renderedRuleReview.current;
2243
+ if (shown === undefined || shown !== activeRuleReview)
2244
+ return;
2245
+ const page = ruleReviewLayout(shown.rule, columns, grants.prompt, shown.offset);
2246
+ if (!page.ready)
2247
+ return;
2248
+ renderedRuleReview.current = undefined;
2249
+ if (page.end < page.total)
2250
+ setRuleReview({ ...shown, offset: page.end });
2251
+ else
2252
+ answerPermission({ allowed: true, rule: shown.rule });
2253
+ }
2254
+ // Lowercase reviews the narrow offer; uppercase reviews the whole tool.
2255
+ // Selection alone never resolves the call or writes a rule.
2256
+ else if (!key.ctrl && !key.meta && (typed === 'a' || typed === 'A')) {
1944
2257
  const suggestions = pendingPermission.suggestions;
1945
2258
  const chosen = typed === 'a' ? suggestions[0] : suggestions[suggestions.length - 1];
1946
- if (chosen !== undefined)
1947
- answerPermission({ allowed: true, rule: chosen.rule });
2259
+ if (chosen !== undefined) {
2260
+ renderedRuleReview.current = undefined;
2261
+ setRuleReview({ request: pendingPermission, rule: chosen.rule, offset: 0, columns, maxRows: grants.prompt });
2262
+ }
1948
2263
  }
1949
2264
  return;
1950
2265
  }
@@ -1972,6 +2287,29 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1972
2287
  openHistorySearch();
1973
2288
  return;
1974
2289
  }
2290
+ // Explicit stash owns no automatic send/queue path. Raw-mode Ctrl+S arrives
2291
+ // here like the other composer chords, after every modal key owner.
2292
+ if (key.ctrl && typed === 's') {
2293
+ const result = toggleDraftStash({ editor: editorRef.current, image: attachedImageRef.current }, draftStashRef.current, imageTurnInFlight.current || hasQueuedImage(queuedRef.current));
2294
+ if (result.action === 'inert')
2295
+ return;
2296
+ if (result.action === 'refused') {
2297
+ dispatch({ type: 'notice', text: result.notice, severity: 'warn' });
2298
+ return;
2299
+ }
2300
+ clipboardReadGeneration.current += 1;
2301
+ undoStack.current = [];
2302
+ lastCut.current = '';
2303
+ preferredColumn.current = undefined;
2304
+ setRecall(undefined);
2305
+ setDismissedCompletion(undefined);
2306
+ setSelectedCompletion(0);
2307
+ setDraftStash(result.slot);
2308
+ setAttachedImage(result.composer.image);
2309
+ setEditor(result.composer.editor);
2310
+ dispatch({ type: 'notice', text: `draft ${result.action === 'stored' ? 'stashed' : 'restored'} — not sent` });
2311
+ return;
2312
+ }
1975
2313
  // Clipboard image attachment is editor ownership, below permission,
1976
2314
  // compaction and search modes. Ctrl+O toggles without editing draft text.
1977
2315
  if (key.ctrl && typed === 'o') {
@@ -1980,6 +2318,9 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
1980
2318
  setAttachedImage(undefined);
1981
2319
  dispatch({ type: 'notice', text: 'clipboard image removed from the next prompt' });
1982
2320
  }
2321
+ else if (draftStashRef.current?.image !== undefined) {
2322
+ dispatch({ type: 'notice', text: 'one clipboard image is stashed — restore it before attaching another' });
2323
+ }
1983
2324
  else if (imageTurnInFlight.current || hasQueuedImage(queuedRef.current)) {
1984
2325
  dispatch({ type: 'notice', text: 'one clipboard image is already queued or sending — take it back or let it finish first' });
1985
2326
  }
@@ -2042,6 +2383,17 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
2042
2383
  preferredColumn.current = undefined;
2043
2384
  return;
2044
2385
  }
2386
+ // Yank is insertion, not snapshot restoration: keep intervening edits and
2387
+ // the cut for repeated use, without changing SER-044's destructive-only undo.
2388
+ if (key.ctrl && typed === 'y') {
2389
+ if (lastCut.current !== '') {
2390
+ setEditor((current) => insertAtCursor(current, lastCut.current));
2391
+ preferredColumn.current = undefined;
2392
+ setSelectedCompletion(0);
2393
+ endRecall();
2394
+ }
2395
+ return;
2396
+ }
2045
2397
  // Composer undo (SER-044). Most terminals send both Ctrl+_ and Ctrl+- as
2046
2398
  // byte 0x1f, which Ink's legacy parser reports as the bare unit separator
2047
2399
  // with no modifier flags; the kitty protocol reports a real ctrl chord.
@@ -2261,12 +2613,22 @@ export function App({ runtime: initialRuntime, permissions, initialHistory = [],
2261
2613
  const text = normalizeDraftText(pasted);
2262
2614
  if (text === '')
2263
2615
  return;
2616
+ // Ink delivers paste separately from keys. Use immediate owners/updates so
2617
+ // batched paste and key events filter the same query, never the held draft.
2618
+ if (rewindSearchRef.current !== undefined) {
2619
+ updateRewindSearch((current) => appendRewindSearchQuery(current, text));
2620
+ return;
2621
+ }
2622
+ if (historySearchRef.current !== undefined) {
2623
+ updateHistorySearch((current) => appendPromptHistorySearchQuery(current, text));
2624
+ return;
2625
+ }
2264
2626
  setEditor((current) => insertAtCursor(current, text));
2265
2627
  preferredColumn.current = undefined;
2266
2628
  setSelectedCompletion(0);
2267
2629
  endRecall();
2268
2630
  });
2269
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { ref: headerRef, flexDirection: "column", children: _jsx(Header, { runtime: runtime, status: effectiveStatus, frame: frame }) }), _jsx(MessageList, { history: state.history, ...(state.staticEpoch === 0 ? { welcome: initialWelcome } : {}), liveText: state.liveText, liveCodeOpen: fenceOpenAfter(state.committedAnswer), columns: columns, maxLiveRows: grants.live, staticEpoch: state.staticEpoch }), _jsxs(Box, { ref: chromeRef, flexDirection: "column", children: [state.thinking && effectiveStatus === 'streaming' && (_jsx(Text, { dimColor: true, wrap: "truncate-end", children: `thinking…${busyElapsedMs === undefined ? '' : busySuffix(busyElapsedMs, undefined, busyRetryWait)}` })), _jsx(ActiveToolCalls, { tools: state.activeTools, frame: frame, toolDetailsExpanded: state.toolDetailsExpanded, columns: columns, maxRows: grants.tools }), _jsx(PlanChecklist, { plan: state.livePlan, maxRows: grants.plan }), _jsx(QueuedMessages, { entries: queued, maxRows: grants.queued }), pendingPermission !== undefined ? (_jsx(PermissionPrompt, { request: pendingPermission, waiting: permissions.waiting, columns: columns, maxRows: grants.prompt })) : (_jsx(InputBox, { layout: layout, completions: completions, completionKind: completionKind, completionNote: completionNote, selectedCompletion: selectedCompletion, editable: effectiveStatus !== 'compacting', offset: { top: chrome.top, left: chrome.left }, maxRows: grants.prompt, hint: streamingHint, attachment: attachedImage === undefined ? undefined : clipboardImageFact(attachedImage), recallIndicator: recallIndicator, historySearch: historySearchProjection, rewindSearch: rewindSearchProjection }))] })] }));
2631
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { ref: headerRef, flexDirection: "column", children: _jsx(Header, { runtime: runtime, status: effectiveStatus, frame: frame, tangent: tangent, runningTaskCount: runningTaskCount, draftStashed: statusHint === undefined && draftStash !== undefined }) }), _jsx(MessageList, { history: state.history, ...(state.staticEpoch === 0 ? { welcome: initialWelcome } : {}), liveText: state.liveText, liveCodeOpen: fenceOpenAfter(state.committedAnswer), columns: columns, maxLiveRows: grants.live, staticEpoch: state.staticEpoch }), _jsxs(Box, { ref: chromeRef, flexDirection: "column", children: [state.thinking && effectiveStatus === 'streaming' && (_jsx(Text, { dimColor: true, wrap: "truncate-end", children: `thinking…${busyElapsedMs === undefined ? '' : busySuffix(busyElapsedMs, undefined, busyRetryWait)}` })), _jsx(ActiveToolCalls, { tools: state.activeTools, frame: frame, toolDetailsExpanded: state.toolDetailsExpanded, columns: columns, maxRows: grants.tools }), _jsx(PlanChecklist, { plan: state.livePlan, maxRows: grants.plan }), _jsx(QueuedMessages, { entries: queued, maxRows: grants.queued }), activeRuleReview !== undefined ? _jsx(PermissionRulePreview, { review: activeRuleReview }) : pendingPermission !== undefined ? (_jsx(PermissionPrompt, { request: pendingPermission, waiting: permissions.waiting, columns: columns, maxRows: grants.prompt })) : (_jsx(InputBox, { layout: layout, completions: completions, completionKind: completionKind, completionNote: completionNote, selectedCompletion: selectedCompletion, editable: effectiveStatus !== 'compacting', offset: { top: chrome.top, left: chrome.left }, maxRows: grants.prompt, hint: streamingHint, attachment: attachedImage === undefined ? undefined : clipboardImageFact(attachedImage), recallIndicator: recallIndicator, historySearch: historySearchProjection, rewindSearch: rewindSearchProjection }))] })] }));
2270
2632
  }
2271
2633
  /** The hint row under the draft, or nothing when the session is idle. */
2272
2634
  function hintForStatus(status, busyReadout, queuedCount = 0, queuedWakeCount = 0) {
@@ -2315,15 +2677,19 @@ function lastRetryOutcome(runtime) {
2315
2677
  return undefined;
2316
2678
  }
2317
2679
  }
2318
- export function Header({ runtime, status = 'idle', frame = 0, }) {
2680
+ export function Header({ runtime, status = 'idle', frame = 0, tangent, runningTaskCount = 0, draftStashed = false, }) {
2681
+ const { columns } = useWindowSize();
2319
2682
  const info = runtime.info;
2320
2683
  const instructions = info.projectInstructions;
2321
2684
  // Live, not info.permissionMode: /mode moves it mid-session, and a header still
2322
2685
  // naming the startup policy would be worse than no header — this row is the only
2323
2686
  // place the effective mode is stated, and it must not gain a second one.
2324
2687
  const mode = runtime.permissionMode;
2325
- return (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsxs(Text, { children: [_jsxs(Text, { color: visualColor.identity, bold: true, children: [visualMarker.identity, " DARWIN"] }), _jsxs(Text, { dimColor: true, children: [' · ', status === 'streaming' ? _jsx(WorkingStatus, { frame: frame }) : headerStatus(status)] })] }), _jsxs(Text, { dimColor: true, children: [runtime.config.provider, "/", runtime.config.model, " \u00B7 session ", info.sessionId, info.resumed ? ' (resumed)' : '', formatPromptCache(runtime.promptCache), formatThinking(runtime.thinking)] }), mode === 'yolo' ? (_jsxs(Text, { color: visualColor.warning, children: ["mode: ", describeMode(mode, runtime.allowRuleCount, runtime.denyRuleCount)] })) : mode === 'plan' ? (_jsxs(Text, { color: visualColor.warning, children: ["mode: ", describeMode(mode, runtime.allowRuleCount, runtime.denyRuleCount)] })) : (_jsxs(Text, { dimColor: true, children: ["mode: ", describeMode(mode, runtime.allowRuleCount, runtime.denyRuleCount)] })), instructions !== undefined &&
2326
- (instructions.truncated ? (_jsxs(Text, { color: visualColor.warning, children: [AGENTS_FILENAME, ": loaded (", formatBytes(instructions.bytes), ", truncated to", ' ', MAX_INSTRUCTIONS_BYTES / 1024, " KB)"] })) : (_jsxs(Text, { dimColor: true, children: [AGENTS_FILENAME, ": loaded (", formatBytes(instructions.bytes), ")"] }))), info.projectInstructionsProblem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: [AGENTS_FILENAME, ": skipped \u2014 ", info.projectInstructionsProblem] })), info.systemPromptSource === 'config' && (_jsxs(Text, { dimColor: true, children: ["system prompt: overridden by ", DARWIN_DIRNAME, "/", CONFIG_FILENAME] })), info.systemPromptSource === 'file' && (_jsxs(Text, { dimColor: true, children: ["system prompt: ", DARWIN_DIRNAME, "/", SYSTEM_PROMPT_FILENAME] })), info.systemPromptProblem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["system prompt: using the default \u2014 ", info.systemPromptProblem] })), info.workingContextProblem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["working context: no directory listing \u2014 ", info.workingContextProblem] })), info.promptCache.problem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["prompt cache: off \u2014 ", info.promptCache.problem] })), runtime.thinking.problem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["thinking: ", runtime.thinking.problem] })), hasCapabilities(info) && (_jsxs(Text, { dimColor: true, children: ["loaded: ", formatCapabilities(info), " \u00B7 type / for commands"] })), info.mcpIgnoredConfigPath !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["mcp: using ", DARWIN_DIRNAME, "/", MCP_CONFIG_FILENAME, " \u2014 ", info.mcpIgnoredConfigPath, " ignored"] })), info.hookShadowNotices.map((notice) => (_jsxs(Text, { color: visualColor.warning, wrap: "truncate-end", children: ["hooks: ", notice.layer, " ", notice.directory, " shadows ", notice.shadowed.join(', ')] }, notice.directory))), info.skillProblems.map((problem) => (_jsxs(Text, { color: visualColor.warning, children: ["skill skipped: ", problem.directory, " \u2014 ", problem.reason] }, problem.directory))), info.commandProblems.map((problem) => (_jsxs(Text, { color: visualColor.warning, children: ["command skipped: ", problem.file, " \u2014 ", problem.reason] }, problem.file))), info.agentProblems.map((problem) => (_jsxs(Text, { color: visualColor.warning, children: ["agent skipped: ", problem.file, " \u2014 ", problem.reason] }, problem.file))), _jsx(Text, { dimColor: true, children: "/ for actions \u00B7 @ for paths \u00B7 ctrl+c cancels \u00B7 /exit quits" })] }));
2688
+ const stateLabel = status === 'streaming' ? 'working' : headerStatus(status);
2689
+ const tangentSuffix = tangentHeaderSuffix(tangent);
2690
+ const activity = runningTasksHeader(runningTaskCount, columns - `◆ DARWIN · ${stateLabel}${tangentSuffix}`.length, frame);
2691
+ return (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsxs(Text, { wrap: "truncate-end", children: [_jsxs(Text, { color: visualColor.identity, bold: true, children: [visualMarker.identity, " DARWIN"] }), _jsxs(Text, { dimColor: true, children: [' · ', status === 'streaming' ? _jsx(WorkingStatus, { frame: frame }) : headerStatus(status), tangentSuffix] }), _jsx(Text, { color: visualColor.active, children: activity.label }), _jsx(Text, { dimColor: true, children: activity.hint })] }), _jsxs(Text, { dimColor: true, children: [runtime.config.provider, "/", runtime.config.model, " \u00B7 session ", info.sessionId, info.resumed ? ' (resumed)' : '', formatPromptCache(runtime.promptCache), formatThinking(runtime.thinking)] }), mode === 'yolo' ? (_jsxs(Text, { color: visualColor.warning, children: ["mode: ", describeMode(mode, runtime.allowRuleCount, runtime.denyRuleCount)] })) : mode === 'plan' ? (_jsxs(Text, { color: visualColor.warning, children: ["mode: ", describeMode(mode, runtime.allowRuleCount, runtime.denyRuleCount)] })) : (_jsxs(Text, { dimColor: true, children: ["mode: ", describeMode(mode, runtime.allowRuleCount, runtime.denyRuleCount)] })), instructions !== undefined &&
2692
+ (instructions.truncated ? (_jsx(Text, { color: visualColor.warning, children: formatInstructionsLoadedRow(instructions) })) : (_jsx(Text, { dimColor: true, children: formatInstructionsLoadedRow(instructions) }))), info.projectInstructionsProblem !== undefined && (_jsx(Text, { color: visualColor.warning, children: formatInstructionsProblemRow(info.projectInstructionsProblemFile ?? AGENTS_FILENAME, info.projectInstructionsProblem) })), info.systemPromptSource === 'config' && (_jsxs(Text, { dimColor: true, children: ["system prompt: overridden by ", DARWIN_DIRNAME, "/", CONFIG_FILENAME] })), info.systemPromptSource === 'file' && (_jsxs(Text, { dimColor: true, children: ["system prompt: ", DARWIN_DIRNAME, "/", SYSTEM_PROMPT_FILENAME] })), info.systemPromptProblem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["system prompt: using the default \u2014 ", info.systemPromptProblem] })), info.workingContextProblem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["working context: no directory listing \u2014 ", info.workingContextProblem] })), info.promptCache.problem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["prompt cache: off \u2014 ", info.promptCache.problem] })), runtime.thinking.problem !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["thinking: ", runtime.thinking.problem] })), hasCapabilities(info) && (_jsxs(Text, { dimColor: true, children: ["loaded: ", formatCapabilities(info), " \u00B7 type / for commands"] })), info.mcpIgnoredConfigPath !== undefined && (_jsxs(Text, { color: visualColor.warning, children: ["mcp: using ", DARWIN_DIRNAME, "/", MCP_CONFIG_FILENAME, " \u2014 ", info.mcpIgnoredConfigPath, " ignored"] })), info.hookShadowNotices.map((notice) => (_jsxs(Text, { color: visualColor.warning, wrap: "truncate-end", children: ["hooks: ", notice.layer, " ", notice.directory, " shadows ", notice.shadowed.join(', ')] }, notice.directory))), info.skillProblems.map((problem) => (_jsxs(Text, { color: visualColor.warning, children: ["skill skipped: ", problem.directory, " \u2014 ", problem.reason] }, problem.directory))), info.commandProblems.map((problem) => (_jsxs(Text, { color: visualColor.warning, children: ["command skipped: ", problem.file, " \u2014 ", problem.reason] }, problem.file))), info.agentProblems.map((problem) => (_jsxs(Text, { color: visualColor.warning, children: ["agent skipped: ", problem.file, " \u2014 ", problem.reason] }, problem.file))), _jsx(Text, { dimColor: true, children: stashHint('/ for actions · @ for paths · ctrl+c cancels · /exit quits', draftStashed, columns) })] }));
2327
2693
  }
2328
2694
  const WORKING_LABEL = 'working';
2329
2695
  /** Highlights one letter in place, preserving the header's exact width and row count. */
@@ -2361,10 +2727,6 @@ function formatCapabilities(info) {
2361
2727
  function capabilityCount(count, label) {
2362
2728
  return count > 0 ? `${count} ${label}${count === 1 ? '' : 's'}` : undefined;
2363
2729
  }
2364
- /** Sizes are shown so an accidentally huge AGENTS.md is visible at a glance. */
2365
- function formatBytes(bytes) {
2366
- return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
2367
- }
2368
2730
  /**
2369
2731
  * Provider-aware token counters as a labelled block.
2370
2732
  *
@@ -2706,7 +3068,23 @@ export function formatPermissionRulesReport(entries, rulesFile, denyRules) {
2706
3068
  */
2707
3069
  export function applyPermissionsCommand(runtime, text, dispatch) {
2708
3070
  const argument = text.slice('/permissions'.length).trim();
2709
- const usage = 'usage: /permissions — list allow- and deny-rules · /permissions revoke <n|rule|all> (allow-rules only)';
3071
+ const usage = 'usage: /permissions — list allow- and deny-rules · /permissions revoke <n|rule|all> (allow-rules only) · /permissions test <rule>';
3072
+ // Consume the remaining string intact; splitting/joining would change bash patterns.
3073
+ if (/^test(?:\s|$)/i.test(argument)) {
3074
+ const rule = argument.slice(4).trim();
3075
+ if (rule === '') {
3076
+ dispatch({ type: 'notice', text: `test needs a rule\n ${usage}` });
3077
+ return;
3078
+ }
3079
+ const status = runtime.trajectoryStatus;
3080
+ void permissionTestReport(rule, {
3081
+ projectRoot: runtime.info.projectRoot,
3082
+ sessionId: runtime.info.sessionId,
3083
+ denyRules: [...runtime.listDenyRules()],
3084
+ recording: status === undefined ? 'disabled' : status.active ? 'active' : 'stopped',
3085
+ }).then(text => dispatch({ type: 'notice', text }), () => dispatch({ type: 'notice', text: 'permissions test: evidence unavailable; no rules changed' }));
3086
+ return;
3087
+ }
2710
3088
  if (argument === '') {
2711
3089
  dispatch({
2712
3090
  type: 'notice',