@strands-agents/cli 0.1.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 (275) hide show
  1. package/LICENSE +175 -0
  2. package/NOTICE +1 -0
  3. package/README.md +576 -0
  4. package/bin/strands.js +256 -0
  5. package/dist/src/cli/arguments.js +198 -0
  6. package/dist/src/cli/arguments.js.map +1 -0
  7. package/dist/src/cli/invocation.js +124 -0
  8. package/dist/src/cli/invocation.js.map +1 -0
  9. package/dist/src/cli/run.js +252 -0
  10. package/dist/src/cli/run.js.map +1 -0
  11. package/dist/src/console.js +235 -0
  12. package/dist/src/console.js.map +1 -0
  13. package/dist/src/logging.js +103 -0
  14. package/dist/src/logging.js.map +1 -0
  15. package/dist/src/main.js +7 -0
  16. package/dist/src/main.js.map +1 -0
  17. package/dist/src/tui/acp/projection.js +276 -0
  18. package/dist/src/tui/acp/projection.js.map +1 -0
  19. package/dist/src/tui/acp/server.js +263 -0
  20. package/dist/src/tui/acp/server.js.map +1 -0
  21. package/dist/src/tui/agent-configuration.js +335 -0
  22. package/dist/src/tui/agent-configuration.js.map +1 -0
  23. package/dist/src/tui/agent-setup.js +80 -0
  24. package/dist/src/tui/agent-setup.js.map +1 -0
  25. package/dist/src/tui/background/activity.js +273 -0
  26. package/dist/src/tui/background/activity.js.map +1 -0
  27. package/dist/src/tui/background/inbox.js +120 -0
  28. package/dist/src/tui/background/inbox.js.map +1 -0
  29. package/dist/src/tui/background/tasks.js +98 -0
  30. package/dist/src/tui/background/tasks.js.map +1 -0
  31. package/dist/src/tui/builtin-tools.js +65 -0
  32. package/dist/src/tui/builtin-tools.js.map +1 -0
  33. package/dist/src/tui/chat/commands.js +98 -0
  34. package/dist/src/tui/chat/commands.js.map +1 -0
  35. package/dist/src/tui/chat/controller-helpers.js +62 -0
  36. package/dist/src/tui/chat/controller-helpers.js.map +1 -0
  37. package/dist/src/tui/chat/controller.js +1913 -0
  38. package/dist/src/tui/chat/controller.js.map +1 -0
  39. package/dist/src/tui/chat/help.js +94 -0
  40. package/dist/src/tui/chat/help.js.map +1 -0
  41. package/dist/src/tui/chat/panels.js +418 -0
  42. package/dist/src/tui/chat/panels.js.map +1 -0
  43. package/dist/src/tui/chat/projector.js +443 -0
  44. package/dist/src/tui/chat/projector.js.map +1 -0
  45. package/dist/src/tui/chat/sdk-projector.js +194 -0
  46. package/dist/src/tui/chat/sdk-projector.js.map +1 -0
  47. package/dist/src/tui/chat/shell.js +263 -0
  48. package/dist/src/tui/chat/shell.js.map +1 -0
  49. package/dist/src/tui/chat/types.js +2 -0
  50. package/dist/src/tui/chat/types.js.map +1 -0
  51. package/dist/src/tui/config.js +497 -0
  52. package/dist/src/tui/config.js.map +1 -0
  53. package/dist/src/tui/configuration-instructions.js +14 -0
  54. package/dist/src/tui/configuration-instructions.js.map +1 -0
  55. package/dist/src/tui/mcp/config.js +370 -0
  56. package/dist/src/tui/mcp/config.js.map +1 -0
  57. package/dist/src/tui/mcp.js +98 -0
  58. package/dist/src/tui/mcp.js.map +1 -0
  59. package/dist/src/tui/memory-options.js +10 -0
  60. package/dist/src/tui/memory-options.js.map +1 -0
  61. package/dist/src/tui/messaging.js +193 -0
  62. package/dist/src/tui/messaging.js.map +1 -0
  63. package/dist/src/tui/model/context.js +13 -0
  64. package/dist/src/tui/model/context.js.map +1 -0
  65. package/dist/src/tui/model/display.js +59 -0
  66. package/dist/src/tui/model/display.js.map +1 -0
  67. package/dist/src/tui/model/runtime.js +365 -0
  68. package/dist/src/tui/model/runtime.js.map +1 -0
  69. package/dist/src/tui/model/selection.js +160 -0
  70. package/dist/src/tui/model/selection.js.map +1 -0
  71. package/dist/src/tui/package-version.js +47 -0
  72. package/dist/src/tui/package-version.js.map +1 -0
  73. package/dist/src/tui/permissions/file-change-preview.js +182 -0
  74. package/dist/src/tui/permissions/file-change-preview.js.map +1 -0
  75. package/dist/src/tui/permissions/policy.js +223 -0
  76. package/dist/src/tui/permissions/policy.js.map +1 -0
  77. package/dist/src/tui/permissions/settings.js +21 -0
  78. package/dist/src/tui/permissions/settings.js.map +1 -0
  79. package/dist/src/tui/project/acp.js +93 -0
  80. package/dist/src/tui/project/acp.js.map +1 -0
  81. package/dist/src/tui/project/archive.js +239 -0
  82. package/dist/src/tui/project/archive.js.map +1 -0
  83. package/dist/src/tui/project/configuration-secrets.js +107 -0
  84. package/dist/src/tui/project/configuration-secrets.js.map +1 -0
  85. package/dist/src/tui/project/configuration.js +201 -0
  86. package/dist/src/tui/project/configuration.js.map +1 -0
  87. package/dist/src/tui/project/export.js +560 -0
  88. package/dist/src/tui/project/export.js.map +1 -0
  89. package/dist/src/tui/project/import.js +75 -0
  90. package/dist/src/tui/project/import.js.map +1 -0
  91. package/dist/src/tui/project/module-loader.js +157 -0
  92. package/dist/src/tui/project/module-loader.js.map +1 -0
  93. package/dist/src/tui/project/packaging.js +53 -0
  94. package/dist/src/tui/project/packaging.js.map +1 -0
  95. package/dist/src/tui/project/portable-dependencies.js +34 -0
  96. package/dist/src/tui/project/portable-dependencies.js.map +1 -0
  97. package/dist/src/tui/project/portable-mcp.js +118 -0
  98. package/dist/src/tui/project/portable-mcp.js.map +1 -0
  99. package/dist/src/tui/project/python.js +414 -0
  100. package/dist/src/tui/project/python.js.map +1 -0
  101. package/dist/src/tui/project/run.js +118 -0
  102. package/dist/src/tui/project/run.js.map +1 -0
  103. package/dist/src/tui/project/source.js +307 -0
  104. package/dist/src/tui/project/source.js.map +1 -0
  105. package/dist/src/tui/project/typescript.js +135 -0
  106. package/dist/src/tui/project/typescript.js.map +1 -0
  107. package/dist/src/tui/project/worker.py +731 -0
  108. package/dist/src/tui/provider/aws-client.js +67 -0
  109. package/dist/src/tui/provider/aws-client.js.map +1 -0
  110. package/dist/src/tui/provider/aws-config.js +66 -0
  111. package/dist/src/tui/provider/aws-config.js.map +1 -0
  112. package/dist/src/tui/provider/bedrock-catalog.js +87 -0
  113. package/dist/src/tui/provider/bedrock-catalog.js.map +1 -0
  114. package/dist/src/tui/provider/discovery.js +323 -0
  115. package/dist/src/tui/provider/discovery.js.map +1 -0
  116. package/dist/src/tui/provider/environment.js +138 -0
  117. package/dist/src/tui/provider/environment.js.map +1 -0
  118. package/dist/src/tui/provider/packages.js +42 -0
  119. package/dist/src/tui/provider/packages.js.map +1 -0
  120. package/dist/src/tui/run.js +257 -0
  121. package/dist/src/tui/run.js.map +1 -0
  122. package/dist/src/tui/runtime.js +520 -0
  123. package/dist/src/tui/runtime.js.map +1 -0
  124. package/dist/src/tui/session/agent-definition.js +100 -0
  125. package/dist/src/tui/session/agent-definition.js.map +1 -0
  126. package/dist/src/tui/session/catalog.js +159 -0
  127. package/dist/src/tui/session/catalog.js.map +1 -0
  128. package/dist/src/tui/session/context.js +118 -0
  129. package/dist/src/tui/session/context.js.map +1 -0
  130. package/dist/src/tui/session/conversation-helpers.js +46 -0
  131. package/dist/src/tui/session/conversation-helpers.js.map +1 -0
  132. package/dist/src/tui/session/conversations.js +456 -0
  133. package/dist/src/tui/session/conversations.js.map +1 -0
  134. package/dist/src/tui/session/desktop-profile.js +80 -0
  135. package/dist/src/tui/session/desktop-profile.js.map +1 -0
  136. package/dist/src/tui/session/options.js +44 -0
  137. package/dist/src/tui/session/options.js.map +1 -0
  138. package/dist/src/tui/session/sessions.js +251 -0
  139. package/dist/src/tui/session/sessions.js.map +1 -0
  140. package/dist/src/tui/session/voice.js +353 -0
  141. package/dist/src/tui/session/voice.js.map +1 -0
  142. package/dist/src/tui/settings.js +362 -0
  143. package/dist/src/tui/settings.js.map +1 -0
  144. package/dist/src/tui/setup/questions.js +277 -0
  145. package/dist/src/tui/setup/questions.js.map +1 -0
  146. package/dist/src/tui/skills.js +135 -0
  147. package/dist/src/tui/skills.js.map +1 -0
  148. package/dist/src/tui/steering.js +67 -0
  149. package/dist/src/tui/steering.js.map +1 -0
  150. package/dist/src/tui/strands-backend.js +368 -0
  151. package/dist/src/tui/strands-backend.js.map +1 -0
  152. package/dist/src/tui/stream-presentation.js +138 -0
  153. package/dist/src/tui/stream-presentation.js.map +1 -0
  154. package/dist/src/tui/telemetry.js +46 -0
  155. package/dist/src/tui/telemetry.js.map +1 -0
  156. package/dist/src/tui/terminal/composer.js +237 -0
  157. package/dist/src/tui/terminal/composer.js.map +1 -0
  158. package/dist/src/tui/terminal/directory-picker.js +76 -0
  159. package/dist/src/tui/terminal/directory-picker.js.map +1 -0
  160. package/dist/src/tui/terminal/ink.js +94 -0
  161. package/dist/src/tui/terminal/ink.js.map +1 -0
  162. package/dist/src/tui/terminal/mouse-input.js +83 -0
  163. package/dist/src/tui/terminal/mouse-input.js.map +1 -0
  164. package/dist/src/tui/terminal/open-url.js +21 -0
  165. package/dist/src/tui/terminal/open-url.js.map +1 -0
  166. package/dist/src/tui/terminal/process-tree.js +132 -0
  167. package/dist/src/tui/terminal/process-tree.js.map +1 -0
  168. package/dist/src/tui/terminal/sanitize.js +71 -0
  169. package/dist/src/tui/terminal/sanitize.js.map +1 -0
  170. package/dist/src/tui/terminal/shell-output.js +43 -0
  171. package/dist/src/tui/terminal/shell-output.js.map +1 -0
  172. package/dist/src/tui/terminal/terminal.js +39 -0
  173. package/dist/src/tui/terminal/terminal.js.map +1 -0
  174. package/dist/src/tui/view/agents-panel.js +21 -0
  175. package/dist/src/tui/view/agents-panel.js.map +1 -0
  176. package/dist/src/tui/view/app.js +1068 -0
  177. package/dist/src/tui/view/app.js.map +1 -0
  178. package/dist/src/tui/view/chat-root.js +88 -0
  179. package/dist/src/tui/view/chat-root.js.map +1 -0
  180. package/dist/src/tui/view/chat-view.js +185 -0
  181. package/dist/src/tui/view/chat-view.js.map +1 -0
  182. package/dist/src/tui/view/command-palette.js +18 -0
  183. package/dist/src/tui/view/command-palette.js.map +1 -0
  184. package/dist/src/tui/view/custom-theme-editor.js +301 -0
  185. package/dist/src/tui/view/custom-theme-editor.js.map +1 -0
  186. package/dist/src/tui/view/export-panel.js +14 -0
  187. package/dist/src/tui/view/export-panel.js.map +1 -0
  188. package/dist/src/tui/view/fade-in.js +106 -0
  189. package/dist/src/tui/view/fade-in.js.map +1 -0
  190. package/dist/src/tui/view/frog-canvas.js +375 -0
  191. package/dist/src/tui/view/frog-canvas.js.map +1 -0
  192. package/dist/src/tui/view/frog-drawing.js +415 -0
  193. package/dist/src/tui/view/frog-drawing.js.map +1 -0
  194. package/dist/src/tui/view/frog-easter-egg.js +53 -0
  195. package/dist/src/tui/view/frog-easter-egg.js.map +1 -0
  196. package/dist/src/tui/view/frog-intro-renderer.js +634 -0
  197. package/dist/src/tui/view/frog-intro-renderer.js.map +1 -0
  198. package/dist/src/tui/view/help-footer.js +36 -0
  199. package/dist/src/tui/view/help-footer.js.map +1 -0
  200. package/dist/src/tui/view/interaction.js +349 -0
  201. package/dist/src/tui/view/interaction.js.map +1 -0
  202. package/dist/src/tui/view/intro.js +35 -0
  203. package/dist/src/tui/view/intro.js.map +1 -0
  204. package/dist/src/tui/view/markdown.js +99 -0
  205. package/dist/src/tui/view/markdown.js.map +1 -0
  206. package/dist/src/tui/view/media.js +70 -0
  207. package/dist/src/tui/view/media.js.map +1 -0
  208. package/dist/src/tui/view/model-panel.js +65 -0
  209. package/dist/src/tui/view/model-panel.js.map +1 -0
  210. package/dist/src/tui/view/panel-components.js +17 -0
  211. package/dist/src/tui/view/panel-components.js.map +1 -0
  212. package/dist/src/tui/view/panels.js +129 -0
  213. package/dist/src/tui/view/panels.js.map +1 -0
  214. package/dist/src/tui/view/presentation.js +382 -0
  215. package/dist/src/tui/view/presentation.js.map +1 -0
  216. package/dist/src/tui/view/prompt-editor.js +74 -0
  217. package/dist/src/tui/view/prompt-editor.js.map +1 -0
  218. package/dist/src/tui/view/provider-list.js +14 -0
  219. package/dist/src/tui/view/provider-list.js.map +1 -0
  220. package/dist/src/tui/view/sessions-panel.js +15 -0
  221. package/dist/src/tui/view/sessions-panel.js.map +1 -0
  222. package/dist/src/tui/view/settings-panel.js +146 -0
  223. package/dist/src/tui/view/settings-panel.js.map +1 -0
  224. package/dist/src/tui/view/setup-question.js +90 -0
  225. package/dist/src/tui/view/setup-question.js.map +1 -0
  226. package/dist/src/tui/view/setup-wizard/brand.js +18 -0
  227. package/dist/src/tui/view/setup-wizard/brand.js.map +1 -0
  228. package/dist/src/tui/view/setup-wizard/index.js +1557 -0
  229. package/dist/src/tui/view/setup-wizard/index.js.map +1 -0
  230. package/dist/src/tui/view/setup-wizard/opening-menu.js +88 -0
  231. package/dist/src/tui/view/setup-wizard/opening-menu.js.map +1 -0
  232. package/dist/src/tui/view/setup-wizard/path-completion.js +53 -0
  233. package/dist/src/tui/view/setup-wizard/path-completion.js.map +1 -0
  234. package/dist/src/tui/view/setup-wizard/profile-fields.js +29 -0
  235. package/dist/src/tui/view/setup-wizard/profile-fields.js.map +1 -0
  236. package/dist/src/tui/view/setup-wizard/progress.js +42 -0
  237. package/dist/src/tui/view/setup-wizard/progress.js.map +1 -0
  238. package/dist/src/tui/view/setup-wizard/providers.js +344 -0
  239. package/dist/src/tui/view/setup-wizard/providers.js.map +1 -0
  240. package/dist/src/tui/view/setup-wizard/settings-panel.js +74 -0
  241. package/dist/src/tui/view/setup-wizard/settings-panel.js.map +1 -0
  242. package/dist/src/tui/view/setup-wizard/steps.js +544 -0
  243. package/dist/src/tui/view/setup-wizard/steps.js.map +1 -0
  244. package/dist/src/tui/view/setup-wizard/types.js +2 -0
  245. package/dist/src/tui/view/setup-wizard/types.js.map +1 -0
  246. package/dist/src/tui/view/setup-wizard/use-provider-discovery.js +145 -0
  247. package/dist/src/tui/view/setup-wizard/use-provider-discovery.js.map +1 -0
  248. package/dist/src/tui/view/startup-view.js +42 -0
  249. package/dist/src/tui/view/startup-view.js.map +1 -0
  250. package/dist/src/tui/view/text-input.js +33 -0
  251. package/dist/src/tui/view/text-input.js.map +1 -0
  252. package/dist/src/tui/view/theme-detection.js +45 -0
  253. package/dist/src/tui/view/theme-detection.js.map +1 -0
  254. package/dist/src/tui/view/theme.js +127 -0
  255. package/dist/src/tui/view/theme.js.map +1 -0
  256. package/dist/src/tui/view/transcript-layout.js +60 -0
  257. package/dist/src/tui/view/transcript-layout.js.map +1 -0
  258. package/dist/src/tui/view/transcript-turn.js +135 -0
  259. package/dist/src/tui/view/transcript-turn.js.map +1 -0
  260. package/dist/src/tui/view/transcript.js +138 -0
  261. package/dist/src/tui/view/transcript.js.map +1 -0
  262. package/dist/src/tui/view/use-party-frame.js +15 -0
  263. package/dist/src/tui/view/use-party-frame.js.map +1 -0
  264. package/dist/src/tui/view/use-spinner.js +14 -0
  265. package/dist/src/tui/view/use-spinner.js.map +1 -0
  266. package/dist/src/tui/voice/session.js +515 -0
  267. package/dist/src/tui/voice/session.js.map +1 -0
  268. package/dist/src/tui/workspace/sandbox.js +156 -0
  269. package/dist/src/tui/workspace/sandbox.js.map +1 -0
  270. package/dist/src/tui/workspace/trust.js +147 -0
  271. package/dist/src/tui/workspace/trust.js.map +1 -0
  272. package/dist/src/usage.js +187 -0
  273. package/dist/src/usage.js.map +1 -0
  274. package/package.json +97 -0
  275. package/src/tui/voice/sidecar.py +606 -0
@@ -0,0 +1,1913 @@
1
+ import { homedir } from 'node:os';
2
+ import { resolve } from 'node:path';
3
+ import { clonePanel, effortSlider, permissionRequestRows, formatPermissionPanelBody, formatTaskActivity, modelFilters, taskDetailRows, taskDetailTitle, settingsCategoryFilters, settingsRows, taskRows, sanitizeRows, makePanel, modelRows, sessionRows, setupQuestionRows, skillRows, skillDetailRows, permissionSettingsRows, mcpRows, mcpOptions, BACKGROUND_TASK_WAIT_TOGGLE, } from './panels.js';
4
+ import { LOCAL_COMMAND_NAMES, parseCommandInvocation } from './commands.js';
5
+ import { helpRows } from './help.js';
6
+ import { DEFAULT_CHAT_SETTINGS, DEFAULT_SETTINGS_CATEGORY, SETTINGS_CATEGORIES, parseSettingUpdate, } from '../settings.js';
7
+ import { agentLaunchCommand } from '../project/import.js';
8
+ import {} from '../session/sessions.js';
9
+ import { unquote } from '../session/conversation-helpers.js';
10
+ import {} from '../messaging.js';
11
+ import { modelDisplayName } from '../model/display.js';
12
+ import { modelControlErrorMessage } from '../model/selection.js';
13
+ import { presentChatStream } from '../stream-presentation.js';
14
+ import { errorMessage, sanitizeTerminalText } from '../terminal/sanitize.js';
15
+ import { canChooseDirectory } from '../terminal/directory-picker.js';
16
+ import { copyTerminalText } from '../terminal/terminal.js';
17
+ import { cloneRuntime, cloneTask, isUnresolvedBackgroundTask, readTaskValue, readyBackgroundGeneration, } from './controller-helpers.js';
18
+ import { TurnProjector, projectMessages } from './projector.js';
19
+ import {} from './types.js';
20
+ export * from './types.js';
21
+ const EXIT_WORDS = new Set(['exit', 'quit']);
22
+ const MAX_PENDING_PEER_MESSAGES = 32;
23
+ const TOOL_OUTPUT_EMIT_INTERVAL_MS = 32;
24
+ const EXPORT_PYTHON = 'export:python';
25
+ const EXPORT_TYPESCRIPT = 'export:typescript';
26
+ export class ChatController {
27
+ peerEndpointId;
28
+ _listeners = new Set();
29
+ _completedTurns = [];
30
+ _panelStack = [];
31
+ _skillDetails = new Map();
32
+ _sessions;
33
+ _sessionCache;
34
+ _sessionRefresh;
35
+ _sessionGeneration = 0;
36
+ _skills;
37
+ _skillNames = new Set();
38
+ _mcp;
39
+ _settings;
40
+ _streamPresentation;
41
+ _pinnedModels;
42
+ _setModelPinned;
43
+ _setSettings;
44
+ _requestSetup;
45
+ _exportAgentProject;
46
+ _project;
47
+ _copyText;
48
+ _setupQuestions;
49
+ _exportedPath;
50
+ _backend;
51
+ _activeProjector;
52
+ _drainingProjector;
53
+ _presentationAbort;
54
+ _pendingSubmissions = [];
55
+ _pendingSubmissionRun;
56
+ _stopWatchingTasks;
57
+ _stopWatchingPermissions;
58
+ _stopWatchingSetupQuestions;
59
+ _stopWatchingTaskActivity;
60
+ _usageSubscriptions = new Set();
61
+ _usageGeneration = 0;
62
+ _taskDetailRefreshTimer;
63
+ _tasks = [];
64
+ _taskBaselineReady = false;
65
+ _backgroundContinuationPending = false;
66
+ _backgroundContinuationRun;
67
+ _deliveredBackgroundTaskIds = new Set();
68
+ _openTaskDetailId;
69
+ _notices = [];
70
+ _context;
71
+ _attemptedBackgroundGeneration;
72
+ _panel;
73
+ _deferredModelRestart;
74
+ _deferredModelNoticeId;
75
+ _resourceChanging = false;
76
+ _composerStatus;
77
+ _setupGuideAnswer;
78
+ _closed = false;
79
+ _exitCode;
80
+ _hardExitCode;
81
+ _nextTurn;
82
+ _nextNotice = 1;
83
+ _nextPanel = 1;
84
+ _nextSubmission = 1;
85
+ _runtime;
86
+ _snapshot;
87
+ constructor(backend, options = {}) {
88
+ this.peerEndpointId = options.peerEndpointId;
89
+ this._backend = backend;
90
+ this._sessions = options.sessions;
91
+ this._skills = options.skills;
92
+ for (const name of options.skillNames ?? []) {
93
+ this._skillNames.add(name.toLowerCase());
94
+ }
95
+ this._mcp = options.mcp;
96
+ this._settings = globalThis.structuredClone({ ...DEFAULT_CHAT_SETTINGS, ...options.settings });
97
+ this._streamPresentation = options.streamPresentation;
98
+ this._pinnedModels = new Set(options.pinnedModels ?? []);
99
+ this._setModelPinned = options.setModelPinned;
100
+ this._setSettings = options.setSettings;
101
+ this._requestSetup = options.requestSetup;
102
+ this._exportAgentProject = options.exportAgentProject;
103
+ this._project = options.project;
104
+ this._copyText = options.copyText ?? copyTerminalText;
105
+ this._setupQuestions = options.setupQuestions;
106
+ const info = backend.info?.();
107
+ this._runtime = {
108
+ agent: backend.name,
109
+ version: 'development',
110
+ backendId: backend.id,
111
+ protocol: backend.protocol,
112
+ model: info?.model ?? 'unknown',
113
+ ...(info?.effort !== undefined ? { effort: info.effort } : {}),
114
+ session: 'in-memory',
115
+ cwd: process.cwd(),
116
+ tools: info?.tools ?? [],
117
+ ...options.runtime,
118
+ };
119
+ if (options.initialTurns) {
120
+ this._completedTurns = [...options.initialTurns];
121
+ }
122
+ else if (options.initialMessages) {
123
+ this._completedTurns.push(...projectMessages(options.initialMessages, backend.name));
124
+ }
125
+ this._nextTurn = this._completedTurns.length + 1;
126
+ this._context = { ...(backend.contextUsage?.() ?? {}) };
127
+ this._snapshot = this._createSnapshot();
128
+ this._stopWatchingTasks = this._backend.watchTasks?.((tasks) => {
129
+ if (this._closed) {
130
+ return;
131
+ }
132
+ this._setTasks(tasks);
133
+ this._emit();
134
+ });
135
+ if (!this._stopWatchingTasks) {
136
+ this._taskBaselineReady = true;
137
+ }
138
+ this._stopWatchingPermissions = this._backend.watchPermissions?.((request) => {
139
+ if (this._closed || this._backend.protocol !== 'strands') {
140
+ return;
141
+ }
142
+ if (request) {
143
+ this._openPermissionPanel(request);
144
+ }
145
+ else {
146
+ this._closePermissionPanel();
147
+ }
148
+ });
149
+ this._stopWatchingSetupQuestions = this._setupQuestions?.subscribe((request) => {
150
+ if (request) {
151
+ this._openSetupQuestion(request);
152
+ }
153
+ else {
154
+ this._closeSetupQuestion();
155
+ }
156
+ });
157
+ }
158
+ subscribe = (listener) => {
159
+ this._listeners.add(listener);
160
+ return () => {
161
+ this._listeners.delete(listener);
162
+ };
163
+ };
164
+ getSnapshot = () => this._snapshot;
165
+ async captureConversation() {
166
+ if (!this._backend.captureConversation) {
167
+ throw new Error('This agent cannot transfer its conversation.');
168
+ }
169
+ if (this.busy || this._hasUnresolvedBackgroundTasks()) {
170
+ throw new Error('Finish or cancel running work before applying setup changes.');
171
+ }
172
+ const session = this._backend.sessionIdentity;
173
+ const sourceSelection = this._backend.sourceSelection?.();
174
+ return {
175
+ snapshot: await this._backend.captureConversation(),
176
+ completedTurns: [...this._completedTurns],
177
+ model: this._runtime.model,
178
+ ...(session ? { session } : {}),
179
+ ...(sourceSelection ? { sourceSelection } : {}),
180
+ };
181
+ }
182
+ showError(title, message) {
183
+ this._openError(title, '', message);
184
+ }
185
+ get backend() {
186
+ return this._backend;
187
+ }
188
+ get busy() {
189
+ return (this._activeProjector !== undefined ||
190
+ this._drainingProjector !== undefined ||
191
+ this._pendingSubmissions.length > 0 ||
192
+ this._pendingSubmissionRun !== undefined ||
193
+ this._resourceChanging);
194
+ }
195
+ get hardExitCode() {
196
+ return this._hardExitCode;
197
+ }
198
+ actionableCommandToken(input) {
199
+ if (input.startsWith('!')) {
200
+ return '!';
201
+ }
202
+ const invocation = parseCommandInvocation(input);
203
+ if (!invocation) {
204
+ return undefined;
205
+ }
206
+ if (invocation.prefix === '/' && LOCAL_COMMAND_NAMES.has(invocation.name.toLowerCase())) {
207
+ return invocation.token;
208
+ }
209
+ return this._backend.protocol === 'strands' && this._skillNames.has(invocation.name.toLowerCase())
210
+ ? invocation.token
211
+ : undefined;
212
+ }
213
+ async start(firstRequest, options) {
214
+ if (firstRequest) {
215
+ const prompt = firstRequest.trim();
216
+ if (prompt.startsWith('!')) {
217
+ await this._executeSubmission(prompt);
218
+ }
219
+ else {
220
+ await this._runPrompt(prompt, options?.hidePrompt ? '' : prompt);
221
+ }
222
+ }
223
+ }
224
+ async submit(input) {
225
+ const prompt = input.trim();
226
+ if (!prompt || this._closed) {
227
+ return undefined;
228
+ }
229
+ if (EXIT_WORDS.has(prompt.toLowerCase())) {
230
+ this.close();
231
+ return undefined;
232
+ }
233
+ if (this._panel?.kind === 'question' && this._respondSetupQuestionText(prompt)) {
234
+ return undefined;
235
+ }
236
+ if (/^\/help(?:\s|$)/iu.test(prompt) && !this._resourceChanging && this._panel?.kind !== 'permission') {
237
+ return this._executeSubmission(prompt);
238
+ }
239
+ if (this._activeProjector ||
240
+ this._drainingProjector ||
241
+ this._pendingSubmissionRun ||
242
+ this._pendingSubmissions.length > 0) {
243
+ return this._enqueueSubmission(prompt);
244
+ }
245
+ if (this._resourceChanging) {
246
+ return undefined;
247
+ }
248
+ return this._executeSubmission(prompt);
249
+ }
250
+ enqueuePeerMessage(message) {
251
+ if (this._closed ||
252
+ this._resourceChanging ||
253
+ !this._backend.streamPeer ||
254
+ this._pendingSubmissions.filter((pending) => pending.kind === 'peer').length >= MAX_PENDING_PEER_MESSAGES) {
255
+ return false;
256
+ }
257
+ this._pendingSubmissions.push({
258
+ kind: 'peer',
259
+ id: `queued-${this._nextSubmission++}`,
260
+ message,
261
+ });
262
+ this._emit();
263
+ this._startPendingSubmissions();
264
+ return true;
265
+ }
266
+ async steer(input) {
267
+ const prompt = input.trim();
268
+ if (!prompt || this._closed) {
269
+ return undefined;
270
+ }
271
+ if (EXIT_WORDS.has(prompt.toLowerCase())) {
272
+ this.close();
273
+ return undefined;
274
+ }
275
+ if (prompt.startsWith('!')) {
276
+ return this.busy ? this._enqueueSubmission(prompt) : this._executeSubmission(prompt);
277
+ }
278
+ if (this._resourceChanging &&
279
+ !this._activeProjector &&
280
+ !this._drainingProjector &&
281
+ !this._pendingSubmissionRun &&
282
+ this._pendingSubmissions.length === 0) {
283
+ return undefined;
284
+ }
285
+ if (!this.busy) {
286
+ return this._executeSubmission(prompt);
287
+ }
288
+ if (this._activeProjector && this._backend.queueSteering) {
289
+ if (this._backend.queueSteering(prompt)) {
290
+ return undefined;
291
+ }
292
+ }
293
+ const pending = this._enqueueSubmission(prompt, true);
294
+ this.cancel();
295
+ return pending;
296
+ }
297
+ steerQueued(id = this._pendingSubmissions.find((pending) => pending.kind === 'user')?.id) {
298
+ if (!id || this._closed) {
299
+ return false;
300
+ }
301
+ const index = this._pendingSubmissions.findIndex((pending) => pending.id === id);
302
+ if (index < 0) {
303
+ return false;
304
+ }
305
+ const pending = this._pendingSubmissions[index];
306
+ if (pending.kind !== 'user') {
307
+ return false;
308
+ }
309
+ if (!pending.prompt.startsWith('!') && this._activeProjector && this._backend.queueSteering) {
310
+ if (this._backend.queueSteering(pending.prompt)) {
311
+ this._pendingSubmissions.splice(index, 1);
312
+ pending.resolve(undefined);
313
+ this._emit();
314
+ return true;
315
+ }
316
+ }
317
+ if (index > 0) {
318
+ this._pendingSubmissions.splice(index, 1);
319
+ this._pendingSubmissions.unshift(pending);
320
+ }
321
+ this.cancel();
322
+ this._emit();
323
+ return true;
324
+ }
325
+ updateQueuedPrompt(id, prompt) {
326
+ const normalized = prompt.trim();
327
+ const pending = this._pendingSubmissions.find((candidate) => candidate.kind === 'user' && candidate.id === id);
328
+ if (!pending || !normalized) {
329
+ return false;
330
+ }
331
+ pending.prompt = normalized;
332
+ this._emit();
333
+ return true;
334
+ }
335
+ moveQueuedPrompt(id, direction) {
336
+ const userIndexes = this._pendingSubmissions.flatMap((pending, index) => (pending.kind === 'user' ? [index] : []));
337
+ const position = userIndexes.findIndex((index) => this._pendingSubmissions[index]?.id === id);
338
+ const currentIndex = userIndexes[position];
339
+ const targetIndex = userIndexes[position + direction];
340
+ if (currentIndex === undefined || targetIndex === undefined) {
341
+ return false;
342
+ }
343
+ const current = this._pendingSubmissions[currentIndex];
344
+ this._pendingSubmissions[currentIndex] = this._pendingSubmissions[targetIndex];
345
+ this._pendingSubmissions[targetIndex] = current;
346
+ this._emit();
347
+ return true;
348
+ }
349
+ async _executeSubmission(prompt) {
350
+ if (prompt.startsWith('!')) {
351
+ return this._runShellCommand(prompt);
352
+ }
353
+ const directSkill = prompt.startsWith('$') ? parseCommandInvocation(prompt) : undefined;
354
+ if (directSkill) {
355
+ const turn = await this._activateSkillAndRun(directSkill.name, directSkill.argument);
356
+ if (turn === null) {
357
+ this._openError('unknown skill', `$${directSkill.name}`, 'Use /skills to list available skills.');
358
+ return undefined;
359
+ }
360
+ return turn;
361
+ }
362
+ if (prompt.startsWith('/')) {
363
+ await this._handleCommand(prompt);
364
+ return undefined;
365
+ }
366
+ return this._runPrompt(prompt);
367
+ }
368
+ async _runShellCommand(prompt) {
369
+ const command = prompt.slice(1).trim();
370
+ if (!command) {
371
+ this._openError('shell command required', '!', 'Use !<command> to run a command in the active sandbox.');
372
+ return undefined;
373
+ }
374
+ if (!this._backend.streamShell) {
375
+ this._openError('shell unavailable', `!${command}`, 'The active backend does not expose a sandbox. Switch to the built-in Strands connection.');
376
+ return undefined;
377
+ }
378
+ this._panel = undefined;
379
+ this._panelStack.length = 0;
380
+ return this._runStream(prompt, this._backend.streamShell(command));
381
+ }
382
+ async _runPrompt(prompt, displayPrompt = prompt) {
383
+ if (this._closed || this._activeProjector || this._drainingProjector || this._resourceChanging) {
384
+ return undefined;
385
+ }
386
+ if (this._setupQuestions && displayPrompt) {
387
+ this._setupGuideAnswer = displayPrompt;
388
+ }
389
+ this._panel = undefined;
390
+ this._panelStack.length = 0;
391
+ return this._runStream(displayPrompt, this._backend.stream(prompt));
392
+ }
393
+ async _runPeerMessage(message) {
394
+ if (this._closed ||
395
+ this._activeProjector ||
396
+ this._drainingProjector ||
397
+ this._resourceChanging ||
398
+ !this._backend.streamPeer) {
399
+ return undefined;
400
+ }
401
+ this._panel = undefined;
402
+ this._panelStack.length = 0;
403
+ return this._runStream(message.body, this._backend.streamPeer(message), 'peer', message.from);
404
+ }
405
+ async _runBackgroundContinuation() {
406
+ if (this._closed ||
407
+ this._activeProjector !== undefined ||
408
+ this._drainingProjector !== undefined ||
409
+ this._pendingSubmissionRun !== undefined ||
410
+ this._resourceChanging ||
411
+ this._pendingSubmissions.some((pending) => pending.kind === 'user') ||
412
+ !this._backend.streamBackgroundResults ||
413
+ !this._backend.hasReadyBackgroundResults?.()) {
414
+ return;
415
+ }
416
+ await this._runStream('', this._backend.streamBackgroundResults(), 'background');
417
+ }
418
+ async _runStream(prompt, source, turnSource, peer) {
419
+ const turnId = `turn-${this._nextTurn++}`;
420
+ const projector = new TurnProjector(turnId, prompt, this._backend.name, turnSource, peer);
421
+ const usageGeneration = this._usageGeneration;
422
+ const presentationAbort = new AbortController();
423
+ let toolOutputEmitTimer;
424
+ const emitStreamEvent = (event) => {
425
+ if (event.type !== 'toolOutputDelta') {
426
+ clearTimeout(toolOutputEmitTimer);
427
+ toolOutputEmitTimer = undefined;
428
+ this._emit();
429
+ return;
430
+ }
431
+ toolOutputEmitTimer ??= setTimeout(() => {
432
+ toolOutputEmitTimer = undefined;
433
+ this._emit();
434
+ }, TOOL_OUTPUT_EMIT_INTERVAL_MS);
435
+ };
436
+ this._activeProjector = projector;
437
+ this._presentationAbort = presentationAbort;
438
+ this._emit();
439
+ const contextBeforeTurn = { ...this._context };
440
+ try {
441
+ const turnContext = {};
442
+ const stream = this._streamPresentation
443
+ ? presentChatStream(source, this._streamPresentation, presentationAbort.signal)
444
+ : source;
445
+ let next = await stream.next();
446
+ while (!next.done) {
447
+ this._handleEvent(projector, next.value, turnContext);
448
+ emitStreamEvent(next.value);
449
+ next = await stream.next();
450
+ }
451
+ projector.finish(next.value);
452
+ if (next.value.context || Object.keys(turnContext).length > 0) {
453
+ this._context = { ...turnContext, ...next.value.context };
454
+ }
455
+ if (next.value.watchUsage && !this._closed && usageGeneration === this._usageGeneration) {
456
+ this._watchTurnUsage(turnId, projector, next.value.watchUsage);
457
+ }
458
+ }
459
+ catch (error) {
460
+ this._context = contextBeforeTurn;
461
+ projector.fail(error);
462
+ }
463
+ finally {
464
+ clearTimeout(toolOutputEmitTimer);
465
+ const wasDetachedByCancellation = this._drainingProjector === projector;
466
+ if (!wasDetachedByCancellation) {
467
+ this._completedTurns.push(projector.snapshot());
468
+ }
469
+ if (this._activeProjector === projector) {
470
+ this._activeProjector = undefined;
471
+ }
472
+ if (wasDetachedByCancellation) {
473
+ this._drainingProjector = undefined;
474
+ }
475
+ this._clearDeliveredBackgroundTaskNotices();
476
+ if (this._presentationAbort === presentationAbort) {
477
+ this._presentationAbort = undefined;
478
+ }
479
+ this._emit();
480
+ if (!this._closed) {
481
+ await this._applyDeferredModelRestart();
482
+ this._startBackgroundContinuation();
483
+ this._startPendingSubmissions();
484
+ }
485
+ }
486
+ return projector.snapshot();
487
+ }
488
+ _watchTurnUsage(turnId, projector, watch) {
489
+ let active = true;
490
+ let unsubscribe = () => { };
491
+ const stop = () => {
492
+ active = false;
493
+ unsubscribe();
494
+ this._usageSubscriptions.delete(stop);
495
+ };
496
+ unsubscribe = watch((usage) => {
497
+ if (!active) {
498
+ return;
499
+ }
500
+ stop();
501
+ if (this._closed || !usage) {
502
+ return;
503
+ }
504
+ projector.setUsage(usage);
505
+ const index = this._completedTurns.findIndex((turn) => turn.id === turnId);
506
+ if (index >= 0) {
507
+ this._completedTurns[index] = { ...this._completedTurns[index], usage: { ...usage } };
508
+ }
509
+ if (this._activeProjector === projector ||
510
+ (!this._activeProjector && this._completedTurns.at(-1)?.id === turnId)) {
511
+ const { currentTokens, projectedTokens, contextWindow } = this._context;
512
+ this._context = {
513
+ ...(currentTokens !== undefined ? { currentTokens } : {}),
514
+ ...(projectedTokens !== undefined ? { projectedTokens } : {}),
515
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
516
+ ...usage,
517
+ };
518
+ }
519
+ this._emit();
520
+ });
521
+ if (active) {
522
+ this._usageSubscriptions.add(stop);
523
+ }
524
+ else {
525
+ unsubscribe();
526
+ }
527
+ }
528
+ _stopWatchingUsage() {
529
+ this._usageGeneration++;
530
+ for (const stop of this._usageSubscriptions) {
531
+ stop();
532
+ }
533
+ }
534
+ cancel() {
535
+ if (this._activeProjector) {
536
+ const projector = this._activeProjector;
537
+ projector.markCancelled();
538
+ this._completedTurns.push(projector.snapshot());
539
+ this._activeProjector = undefined;
540
+ this._drainingProjector = projector;
541
+ this._presentationAbort?.abort();
542
+ this._backend.cancel();
543
+ this._emit();
544
+ return true;
545
+ }
546
+ if (this._drainingProjector) {
547
+ this._presentationAbort?.abort();
548
+ this._backend.cancel();
549
+ return true;
550
+ }
551
+ return false;
552
+ }
553
+ close(exitCode = 0) {
554
+ if (this._closed) {
555
+ return;
556
+ }
557
+ this._closed = true;
558
+ this._stopWatchingUsage();
559
+ this._backgroundContinuationPending = false;
560
+ const interrupted = this._activeProjector !== undefined || this._drainingProjector !== undefined;
561
+ this._exitCode = interrupted && exitCode === 0 ? 130 : exitCode;
562
+ if (interrupted) {
563
+ this._hardExitCode = this._exitCode;
564
+ this._activeProjector?.markCancelled();
565
+ this._presentationAbort?.abort();
566
+ this._backend.cancel();
567
+ }
568
+ this._resolvePendingSubmissions();
569
+ this._emit();
570
+ }
571
+ async dispose() {
572
+ this._stopWatchingUsage();
573
+ if (this._activeProjector || this._drainingProjector) {
574
+ this._presentationAbort?.abort();
575
+ this._backend.cancel();
576
+ }
577
+ this._resolvePendingSubmissions();
578
+ this._stopWatchingTasks?.();
579
+ this._stopWatchingTasks = undefined;
580
+ this._stopWatchingPermissions?.();
581
+ this._stopWatchingPermissions = undefined;
582
+ this._stopWatchingSetupQuestions?.();
583
+ this._stopWatchingSetupQuestions = undefined;
584
+ this._stopTaskActivity();
585
+ this._listeners.clear();
586
+ await Promise.allSettled([Promise.resolve().then(() => this._backend.dispose?.()), this._mcp?.dispose()]);
587
+ }
588
+ _enqueueSubmission(prompt, priority = false) {
589
+ return new Promise((resolve) => {
590
+ const pending = {
591
+ kind: 'user',
592
+ id: `queued-${this._nextSubmission++}`,
593
+ prompt,
594
+ resolve,
595
+ };
596
+ if (priority) {
597
+ this._pendingSubmissions.unshift(pending);
598
+ }
599
+ else {
600
+ this._pendingSubmissions.push(pending);
601
+ }
602
+ this._emit();
603
+ this._startPendingSubmissions();
604
+ });
605
+ }
606
+ _startPendingSubmissions() {
607
+ if (this._pendingSubmissionRun ||
608
+ this._pendingSubmissions.length === 0 ||
609
+ this._closed ||
610
+ this._activeProjector ||
611
+ this._drainingProjector ||
612
+ this._resourceChanging) {
613
+ return;
614
+ }
615
+ const run = this._drainPendingSubmissions();
616
+ this._pendingSubmissionRun = run;
617
+ void run.finally(() => {
618
+ if (this._pendingSubmissionRun === run) {
619
+ this._pendingSubmissionRun = undefined;
620
+ }
621
+ this._startBackgroundContinuation();
622
+ this._startPendingSubmissions();
623
+ this._emit();
624
+ });
625
+ }
626
+ async _drainPendingSubmissions() {
627
+ while (!this._closed && !this._activeProjector && !this._drainingProjector && !this._resourceChanging) {
628
+ if (!this._pendingSubmissions.some((pending) => pending.kind === 'user') &&
629
+ this._backgroundContinuationPending &&
630
+ this._backend.hasReadyBackgroundResults?.()) {
631
+ return;
632
+ }
633
+ const pending = this._pendingSubmissions.shift();
634
+ if (!pending) {
635
+ return;
636
+ }
637
+ this._panel = undefined;
638
+ this._panelStack.length = 0;
639
+ if (pending.kind === 'peer') {
640
+ await this._runPeerMessage(pending.message);
641
+ }
642
+ else {
643
+ const turn = await this._executeSubmission(pending.prompt);
644
+ pending.resolve(turn);
645
+ }
646
+ }
647
+ }
648
+ _resolvePendingSubmissions() {
649
+ for (const pending of this._pendingSubmissions.splice(0)) {
650
+ if (pending.kind === 'user') {
651
+ pending.resolve(undefined);
652
+ }
653
+ }
654
+ }
655
+ dismissPanel() {
656
+ if (!this._panel ||
657
+ this._resourceChanging ||
658
+ this._panel.kind === 'permission' ||
659
+ this._panel.kind === 'question') {
660
+ return false;
661
+ }
662
+ this._stopTaskActivity();
663
+ this._panel = this._panelStack.pop();
664
+ this._emit();
665
+ return true;
666
+ }
667
+ async activatePanelRow(row) {
668
+ if (!this._panel || !row.value || this._resourceChanging) {
669
+ return false;
670
+ }
671
+ switch (this._panel.kind) {
672
+ case 'help': {
673
+ const selected = this._panel.rows.find((candidate) => candidate.value === row.value);
674
+ if (!selected) {
675
+ return false;
676
+ }
677
+ if (row.value.startsWith('help:command:')) {
678
+ await this.submit(`/${row.value.slice('help:command:'.length)}`);
679
+ }
680
+ else {
681
+ this._pushPanel('detail', selected.label, [], { body: selected.description });
682
+ }
683
+ return true;
684
+ }
685
+ case 'models':
686
+ return row.value.startsWith('effort:')
687
+ ? this._selectEffort(row.value.slice('effort:'.length))
688
+ : this._selectModel(row.value);
689
+ case 'skills':
690
+ return this._openSkillDetail(row.value);
691
+ case 'tasks':
692
+ return row.value === BACKGROUND_TASK_WAIT_TOGGLE
693
+ ? this._toggleBackgroundTaskWaitMode()
694
+ : this._openTaskDetail(row.value);
695
+ case 'permissions':
696
+ return this._updatePermissions(row.value);
697
+ case 'settings':
698
+ return row.value.startsWith('settings:')
699
+ ? this._openSettingsCategory(row.value)
700
+ : this._updateSetting(row.value);
701
+ case 'export':
702
+ if (row.value === 'export:copy-path' || row.value === 'export:copy-command') {
703
+ return this._copyExport(row.value);
704
+ }
705
+ return row.value === EXPORT_TYPESCRIPT
706
+ ? this._exportAgent('typescript')
707
+ : row.value === EXPORT_PYTHON
708
+ ? this._exportAgent('python')
709
+ : false;
710
+ case 'permission':
711
+ return this._respondPermission(row.value);
712
+ case 'question':
713
+ return this._respondSetupQuestion(row.value);
714
+ default:
715
+ return false;
716
+ }
717
+ }
718
+ openContextPanel() {
719
+ this._openPanel('context', 'Context usage', []);
720
+ }
721
+ async toggleModelPin(modelId) {
722
+ const normalized = sanitizeTerminalText(modelId).trim();
723
+ if (!normalized) {
724
+ return false;
725
+ }
726
+ const pinned = !this._pinnedModels.has(normalized);
727
+ try {
728
+ await this._setModelPinned?.(normalized, pinned);
729
+ if (pinned) {
730
+ this._pinnedModels.add(normalized);
731
+ }
732
+ else {
733
+ this._pinnedModels.delete(normalized);
734
+ }
735
+ if (this._panel?.kind === 'models') {
736
+ const rows = this._panel.rows
737
+ .map((row) => {
738
+ if (row.value !== normalized) {
739
+ return row;
740
+ }
741
+ const { pinned: _pinned, ...rest } = row;
742
+ return pinned ? { ...rest, pinned: true } : rest;
743
+ })
744
+ .sort((left, right) => {
745
+ const leftCurrent = left.badge?.text === 'current';
746
+ const rightCurrent = right.badge?.text === 'current';
747
+ if (leftCurrent !== rightCurrent) {
748
+ return leftCurrent ? -1 : 1;
749
+ }
750
+ if (Boolean(left.pinned) !== Boolean(right.pinned)) {
751
+ return left.pinned ? -1 : 1;
752
+ }
753
+ return left.label.localeCompare(right.label) || left.description.localeCompare(right.description);
754
+ });
755
+ this._panel = { ...this._panel, rows: sanitizeRows(rows) };
756
+ this._emit();
757
+ }
758
+ return true;
759
+ }
760
+ catch (error) {
761
+ this._openError('model pin failed', normalized, errorMessage(error));
762
+ return false;
763
+ }
764
+ }
765
+ sessionTarget(reference) {
766
+ return this._sessions && this._backend.protocol === 'strands'
767
+ ? this._sessions.resolve(reference)
768
+ : Promise.resolve(undefined);
769
+ }
770
+ sessionResumeBlockReason() {
771
+ if (this.busy) {
772
+ return 'Wait for the current turn and queued work to finish before opening another saved session.';
773
+ }
774
+ if (this._hasUnresolvedBackgroundTasks()) {
775
+ return 'Background work is still running or waiting to be delivered. Finish or cancel it before opening another saved session.';
776
+ }
777
+ return undefined;
778
+ }
779
+ async _rebuildModel(modelId) {
780
+ if (!this._backend.restartModel) {
781
+ this._openError('model change unavailable', modelId, 'This backend cannot change to this model.');
782
+ return false;
783
+ }
784
+ if (this._activeProjector || this._drainingProjector) {
785
+ const supersededModelId = this._deferredModelRestart;
786
+ const supersededNotice = this._notices.find((candidate) => candidate.id === this._deferredModelNoticeId);
787
+ if (supersededModelId && supersededNotice) {
788
+ supersededNotice.status = 'delivered';
789
+ supersededNotice.text =
790
+ `Model change to ${modelDisplayName(supersededModelId)} superseded by ` + modelDisplayName(modelId);
791
+ }
792
+ this._deferredModelRestart = modelId;
793
+ const notice = this._addNotice('running', `Model change queued for after the current turn: ${modelDisplayName(modelId)}`);
794
+ this._deferredModelNoticeId = notice.id;
795
+ this._emit();
796
+ return true;
797
+ }
798
+ this._resourceChanging = true;
799
+ try {
800
+ const selected = await this._backend.restartModel(modelId);
801
+ this._context = {};
802
+ this._refreshRuntime(typeof selected === 'string' ? selected : modelId);
803
+ this._updateOpenModelPanel(modelId);
804
+ this._emit();
805
+ return true;
806
+ }
807
+ catch (error) {
808
+ this._openError('model change failed', modelId, modelControlErrorMessage(error, 'model'));
809
+ return false;
810
+ }
811
+ finally {
812
+ this._resourceChanging = false;
813
+ }
814
+ }
815
+ _handleEvent(projector, event, turnContext) {
816
+ if (event.type === 'tasks') {
817
+ this._setTasks(event.tasks);
818
+ return;
819
+ }
820
+ if (event.type === 'context') {
821
+ const firstUpdate = Object.keys(turnContext).length === 0;
822
+ Object.assign(turnContext, event.usage);
823
+ this._context = firstUpdate ? { ...event.usage } : { ...this._context, ...event.usage };
824
+ return;
825
+ }
826
+ if (event.type === 'permission') {
827
+ this._openPermissionPanel(event.request);
828
+ return;
829
+ }
830
+ projector.handle(event);
831
+ }
832
+ _createSnapshot() {
833
+ const activeTurn = this._activeProjector?.snapshot();
834
+ return {
835
+ completedTurns: [...this._completedTurns],
836
+ ...(activeTurn ? { activeTurn } : {}),
837
+ queuedPrompts: this._pendingSubmissions.map((pending) => ({
838
+ id: pending.id,
839
+ prompt: sanitizeTerminalText(pending.kind === 'peer' ? pending.message.body : pending.prompt),
840
+ ...(pending.kind === 'peer'
841
+ ? {
842
+ source: 'peer',
843
+ from: sanitizeTerminalText(pending.message.from.name),
844
+ }
845
+ : {}),
846
+ })),
847
+ notices: this._notices.map((notice) => ({ ...notice })),
848
+ tasks: this._tasks.map(cloneTask),
849
+ context: { ...this._context },
850
+ status: this._closed ? 'closed' : activeTurn ? 'running' : this._drainingProjector ? 'interrupting' : 'idle',
851
+ ...(this._composerStatus ? { composerStatus: this._composerStatus } : {}),
852
+ ...(this._panel ? { panel: clonePanel(this._panel) } : {}),
853
+ runtime: cloneRuntime(this._runtime),
854
+ settings: globalThis.structuredClone(this._settings),
855
+ ...(this._setupQuestions ? { setupGuide: true } : {}),
856
+ ...(this._setupGuideAnswer ? { setupGuideAnswer: this._setupGuideAnswer } : {}),
857
+ ...(this._exitCode !== undefined ? { exitCode: this._exitCode } : {}),
858
+ };
859
+ }
860
+ _emit() {
861
+ this._snapshot = this._createSnapshot();
862
+ for (const listener of this._listeners) {
863
+ listener();
864
+ }
865
+ }
866
+ async _handleCommand(prompt) {
867
+ const [command = '', ...rest] = prompt.slice(1).trim().split(/\s+/);
868
+ const argument = rest.join(' ');
869
+ switch (command.toLowerCase()) {
870
+ case 'help':
871
+ this._openPanel('help', 'Help', helpRows(this._backend, {
872
+ sessions: this._sessions !== undefined,
873
+ skills: this._skills !== undefined,
874
+ mcp: this._mcp !== undefined,
875
+ setup: this._requestSetup !== undefined,
876
+ export: this._exportAgentProject !== undefined,
877
+ }), {
878
+ searchable: true,
879
+ filters: [
880
+ { id: 'controls', label: 'Shortcuts' },
881
+ { id: 'commands', label: 'Commands' },
882
+ { id: 'tools', label: 'Tools' },
883
+ { id: 'all', label: 'All' },
884
+ ],
885
+ });
886
+ break;
887
+ case 'context':
888
+ this.openContextPanel();
889
+ break;
890
+ case 'compact':
891
+ await this._compactConversation();
892
+ break;
893
+ case 'clear':
894
+ await this._clearConversation();
895
+ break;
896
+ case 'tasks':
897
+ this._openTasksPanel();
898
+ break;
899
+ case 'model':
900
+ await (argument ? this._selectModel(argument) : this.openModelPanel());
901
+ break;
902
+ case 'effort':
903
+ await (argument ? this._selectEffort(argument.toLowerCase()) : this.openModelPanel({ focusEffort: true }));
904
+ break;
905
+ case 'sessions':
906
+ await (argument ? this._handleSessionsCommand(argument) : this._openSessionsPanel());
907
+ break;
908
+ case 'skills':
909
+ await this._openSkillsPanel();
910
+ break;
911
+ case 'mcp':
912
+ await this._openMcpPanel();
913
+ break;
914
+ case 'permissions':
915
+ await this._handlePermissionsCommand(argument);
916
+ break;
917
+ case 'settings':
918
+ this._openSettingsCategory(`settings:${DEFAULT_SETTINGS_CATEGORY}`, true);
919
+ break;
920
+ case 'setup':
921
+ this._requestSetup?.();
922
+ break;
923
+ case 'export':
924
+ await this._handleExportCommand(parseCommandInvocation(prompt)?.argument ?? '');
925
+ break;
926
+ case 'exit':
927
+ this.close();
928
+ break;
929
+ default: {
930
+ const turn = await this._activateSkillAndRun(command, argument);
931
+ if (turn === null) {
932
+ this._openError('unknown command', `/${command}`, 'Type / to browse commands or use /skills to list skills.');
933
+ }
934
+ break;
935
+ }
936
+ }
937
+ }
938
+ _openTasksPanel() {
939
+ this._openPanel('tasks', `tasks (${this._tasks.length})`, taskRows(this._tasks, this._backend.backgroundTasksWaitForCompletion?.()));
940
+ }
941
+ async _toggleBackgroundTaskWaitMode() {
942
+ const current = this._backend.backgroundTasksWaitForCompletion?.();
943
+ if (current === undefined || !this._backend.setBackgroundTasksWaitForCompletion) {
944
+ return false;
945
+ }
946
+ if (this._hasUnresolvedBackgroundTasks()) {
947
+ this._openError('task mode change blocked', 'Wait for completion', 'Background work is still running or waiting to be delivered. Finish or cancel it before rebuilding the agent.');
948
+ return false;
949
+ }
950
+ const next = !current;
951
+ this._resourceChanging = true;
952
+ this._openPanel('tasks', 'updating background behavior', [
953
+ {
954
+ label: 'Wait for completion',
955
+ description: `Rebuilding the agent with wait for completion ${next ? 'on' : 'off'}.`,
956
+ },
957
+ ]);
958
+ try {
959
+ await this._backend.setBackgroundTasksWaitForCompletion(next);
960
+ this._context = {};
961
+ this._refreshRuntime();
962
+ this._openTasksPanel();
963
+ return true;
964
+ }
965
+ catch (error) {
966
+ this._openError('task mode change failed', 'Wait for completion', errorMessage(error));
967
+ return false;
968
+ }
969
+ finally {
970
+ this._resourceChanging = false;
971
+ }
972
+ }
973
+ async openModelPanel({ focusEffort = false } = {}) {
974
+ if (!this._backend.listModels) {
975
+ this._openError('models unavailable', this._runtime.model, 'This backend does not expose model selection.');
976
+ return;
977
+ }
978
+ const loading = this._openPanel('models', 'models', [{ label: 'loading', description: 'Discovering models.' }]);
979
+ try {
980
+ const models = await this._backend.listModels();
981
+ if (this._panel?.id !== loading.id) {
982
+ return;
983
+ }
984
+ const efforts = this._backend.listEfforts?.() ?? [];
985
+ const slider = effortSlider(efforts);
986
+ this._openPanel('models', `models (${models.length})`, modelRows(models, this._pinnedModels, this._runtime.model), {
987
+ searchable: true,
988
+ filters: modelFilters(models.map((model) => model.catalog).filter((catalog) => !!catalog), this._backend.protocol),
989
+ ...(slider ? { slider: { ...slider, ...(focusEffort && !slider.disabled ? { focused: true } : {}) } } : {}),
990
+ body: `${modelDisplayName(this._runtime.model)}\n${this._runtime.model}`,
991
+ });
992
+ }
993
+ catch (error) {
994
+ if (this._panel?.id === loading.id) {
995
+ this._openError('model discovery failed', this._runtime.model, errorMessage(error));
996
+ }
997
+ }
998
+ }
999
+ async _selectModel(modelId) {
1000
+ if (!this._backend.switchModel && !this._backend.restartModel) {
1001
+ this._openError('model switch unavailable', modelId, 'This backend does not expose model selection.');
1002
+ return false;
1003
+ }
1004
+ let mode;
1005
+ try {
1006
+ mode = this._backend.modelChangeMode?.(modelId) ?? (this._backend.switchModel ? 'live' : 'restart');
1007
+ }
1008
+ catch (error) {
1009
+ this._openError('model change failed', modelId, modelControlErrorMessage(error, 'model'));
1010
+ return false;
1011
+ }
1012
+ if (mode === 'restart') {
1013
+ if (this._hasUnresolvedBackgroundTasks()) {
1014
+ this._openError('model change blocked', modelId, 'Background work is still running or waiting to be delivered. Finish or cancel it before changing models.');
1015
+ return false;
1016
+ }
1017
+ return this._rebuildModel(modelId);
1018
+ }
1019
+ this._resourceChanging = true;
1020
+ try {
1021
+ const selected = await this._backend.switchModel(modelId);
1022
+ this._context = {};
1023
+ this._refreshRuntime(selected ?? modelId);
1024
+ if (this._activeProjector || this._drainingProjector) {
1025
+ this._addNotice('delivered', `Model updated for the next model call: ${modelDisplayName(modelId)}`);
1026
+ }
1027
+ this._updateOpenModelPanel(modelId);
1028
+ this._emit();
1029
+ return true;
1030
+ }
1031
+ catch (error) {
1032
+ this._openError('model switch failed', modelId, modelControlErrorMessage(error, 'model'));
1033
+ return false;
1034
+ }
1035
+ finally {
1036
+ this._resourceChanging = false;
1037
+ }
1038
+ }
1039
+ async _selectEffort(effort) {
1040
+ if (!this._backend.setEffort) {
1041
+ this._openError('effort unavailable', effort, 'This backend does not expose reasoning effort.');
1042
+ return false;
1043
+ }
1044
+ if (this._hasUnresolvedBackgroundTasks()) {
1045
+ this._openError('effort change blocked', effort, 'Background work is still running or waiting to be delivered. Finish or cancel it before rebuilding the agent.');
1046
+ return false;
1047
+ }
1048
+ this._resourceChanging = true;
1049
+ try {
1050
+ const selected = await this._backend.setEffort(effort);
1051
+ this._context = {};
1052
+ this._refreshRuntime();
1053
+ if (this._panel?.kind === 'models' && this._panel.slider) {
1054
+ this._panel = {
1055
+ ...this._panel,
1056
+ slider: {
1057
+ ...this._panel.slider,
1058
+ options: this._panel.slider.options.map(({ active: _active, ...option }) => ({
1059
+ ...option,
1060
+ ...(option.id === effort ? { active: true } : {}),
1061
+ })),
1062
+ },
1063
+ };
1064
+ }
1065
+ this._emit();
1066
+ return selected !== undefined;
1067
+ }
1068
+ catch (error) {
1069
+ this._openError('effort change failed', effort, modelControlErrorMessage(error, 'effort'));
1070
+ return false;
1071
+ }
1072
+ finally {
1073
+ this._resourceChanging = false;
1074
+ }
1075
+ }
1076
+ async _openSessionsPanel() {
1077
+ const sessionsRuntime = this._sessions;
1078
+ if (!sessionsRuntime || this._backend.protocol !== 'strands') {
1079
+ this._openError('sessions unavailable', 'sessions', 'Saved sessions are not available for this backend.');
1080
+ return;
1081
+ }
1082
+ if (this._sessionCache) {
1083
+ const panel = this._showSessionsPanel(sessionsRuntime, this._sessionCache);
1084
+ void this._refreshSessionsPanel(sessionsRuntime, panel.id);
1085
+ return;
1086
+ }
1087
+ const loading = this._openPanel('sessions', 'sessions', [
1088
+ { label: 'loading', description: `Reading ${sessionsRuntime.directory}` },
1089
+ ]);
1090
+ await this._refreshSessionsPanel(sessionsRuntime, loading.id);
1091
+ }
1092
+ async _refreshSessionsPanel(sessionsRuntime, panelId) {
1093
+ const generation = this._sessionGeneration;
1094
+ try {
1095
+ const sessions = await this._listSessions(sessionsRuntime);
1096
+ if (generation !== this._sessionGeneration || this._panel?.id !== panelId) {
1097
+ return;
1098
+ }
1099
+ this._showSessionsPanel(sessionsRuntime, sessions, panelId);
1100
+ }
1101
+ catch (error) {
1102
+ if (generation === this._sessionGeneration && this._panel?.id === panelId && !this._sessionCache) {
1103
+ this._openError('session discovery failed', sessionsRuntime.directory, errorMessage(error));
1104
+ }
1105
+ }
1106
+ }
1107
+ _listSessions(sessionsRuntime) {
1108
+ if (this._sessionRefresh) {
1109
+ return this._sessionRefresh;
1110
+ }
1111
+ const generation = this._sessionGeneration;
1112
+ const refresh = sessionsRuntime.list().then((sessions) => {
1113
+ if (generation === this._sessionGeneration) {
1114
+ this._sessionCache = sessions;
1115
+ }
1116
+ return sessions;
1117
+ });
1118
+ this._sessionRefresh = refresh;
1119
+ const clearRefresh = () => {
1120
+ if (this._sessionRefresh === refresh) {
1121
+ this._sessionRefresh = undefined;
1122
+ }
1123
+ };
1124
+ void refresh.then(clearRefresh, clearRefresh);
1125
+ return refresh;
1126
+ }
1127
+ _showSessionsPanel(sessionsRuntime, sessions, panelId) {
1128
+ const rows = sessionRows(sessions, sessionsRuntime.directory);
1129
+ if (!panelId) {
1130
+ return this._openPanel('sessions', `sessions (${sessions.length})`, rows, { searchable: true });
1131
+ }
1132
+ const panel = this._makePanel('sessions', `sessions (${sessions.length})`, rows, { searchable: true });
1133
+ this._panel = { ...panel, id: panelId };
1134
+ this._emit();
1135
+ return this._panel;
1136
+ }
1137
+ _invalidateSessions() {
1138
+ this._sessionGeneration++;
1139
+ this._sessionRefresh = undefined;
1140
+ }
1141
+ async _handleSessionsCommand(argument) {
1142
+ const rename = /^rename(?:\s+([\s\S]+))?$/i.exec(argument);
1143
+ if (!rename) {
1144
+ this._openError('sessions command failed', `/sessions ${argument}`, 'Use /sessions or /sessions rename <name>.');
1145
+ return;
1146
+ }
1147
+ const name = rename[1] ?? '';
1148
+ if (!name) {
1149
+ this._openError('session rename failed', '/sessions rename', 'Use /sessions rename <name>.');
1150
+ return;
1151
+ }
1152
+ if (!this._sessions?.renameCurrent || this._backend.protocol !== 'strands') {
1153
+ this._openError('session rename unavailable', name, 'The current backend does not expose a file-backed session.');
1154
+ return;
1155
+ }
1156
+ this._resourceChanging = true;
1157
+ try {
1158
+ const renamed = await this._sessions.renameCurrent(name);
1159
+ this._runtime.session = renamed.name;
1160
+ this._invalidateSessions();
1161
+ this._sessionCache = this._sessionCache?.map((session) => session.active ? { ...session, name: renamed.name } : session);
1162
+ await this._openSessionsPanel();
1163
+ }
1164
+ catch (error) {
1165
+ this._openError('session rename failed', name, errorMessage(error));
1166
+ }
1167
+ finally {
1168
+ this._resourceChanging = false;
1169
+ }
1170
+ }
1171
+ async _openSkillsPanel() {
1172
+ if (!this._skills || this._backend.protocol !== 'strands') {
1173
+ this._openError('skills unavailable', 'skills', 'No skills runtime is configured for this backend.');
1174
+ return;
1175
+ }
1176
+ const loading = this._openPanel('skills', 'skills', [
1177
+ { label: 'loading', description: 'Parsing configured skills with the Strands SDK.' },
1178
+ ]);
1179
+ try {
1180
+ const skills = await this._skills.list();
1181
+ if (this._panel?.id !== loading.id) {
1182
+ return;
1183
+ }
1184
+ this._skillDetails.clear();
1185
+ for (const skill of skills) {
1186
+ this._skillDetails.set(skill.name, skill);
1187
+ this._skillNames.add(skill.name.toLowerCase());
1188
+ }
1189
+ this._openPanel('skills', `skills (${skills.length})`, skillRows(skills), {
1190
+ searchable: true,
1191
+ ...(this._skills.paths?.length ? { body: `Checked: ${this._skills.paths.join(', ')}` } : {}),
1192
+ });
1193
+ }
1194
+ catch (error) {
1195
+ if (this._panel?.id === loading.id) {
1196
+ this._openError('skill discovery failed', 'skills', errorMessage(error));
1197
+ }
1198
+ }
1199
+ }
1200
+ async _activateSkillAndRun(name, argument) {
1201
+ if (!this._skills || this._backend.protocol !== 'strands') {
1202
+ return null;
1203
+ }
1204
+ this._resourceChanging = true;
1205
+ let skill;
1206
+ try {
1207
+ skill = await this._skills.activate(name);
1208
+ }
1209
+ catch (error) {
1210
+ this._openError('skill activation failed', name, errorMessage(error));
1211
+ return undefined;
1212
+ }
1213
+ finally {
1214
+ this._resourceChanging = false;
1215
+ }
1216
+ if (!skill) {
1217
+ return null;
1218
+ }
1219
+ this._skillNames.add(skill.name.toLowerCase());
1220
+ this._skillDetails.set(skill.name, skill);
1221
+ return this._runPrompt(argument || `Use the ${skill.name} skill.`);
1222
+ }
1223
+ async _compactConversation() {
1224
+ if (!this._backend.compact) {
1225
+ this._openError('compaction unavailable', 'compact', 'This backend cannot compact its conversation.');
1226
+ return;
1227
+ }
1228
+ if (this._hasUnresolvedBackgroundTasks()) {
1229
+ this._openError('compaction blocked', 'compact', 'Background work is still running or waiting to be delivered. Finish or cancel it before compacting.');
1230
+ return;
1231
+ }
1232
+ this._resourceChanging = true;
1233
+ this._composerStatus = 'Compacting context...';
1234
+ this._panel = undefined;
1235
+ this._panelStack.length = 0;
1236
+ this._emit();
1237
+ try {
1238
+ if (await this._backend.compact()) {
1239
+ this._context = {};
1240
+ }
1241
+ }
1242
+ catch (error) {
1243
+ this._openError('compaction failed', 'compact', errorMessage(error));
1244
+ }
1245
+ finally {
1246
+ this._resourceChanging = false;
1247
+ this._composerStatus = undefined;
1248
+ this._emit();
1249
+ }
1250
+ }
1251
+ async _clearConversation() {
1252
+ if (!this._backend.clear) {
1253
+ this._openError('clear unavailable', 'clear', 'This backend cannot start a fresh conversation.');
1254
+ return;
1255
+ }
1256
+ if (this._hasUnresolvedBackgroundTasks()) {
1257
+ this._openError('clear blocked', 'clear', 'Background work is still running or waiting to be delivered. Finish or cancel it before clearing.');
1258
+ return;
1259
+ }
1260
+ this._resourceChanging = true;
1261
+ this._openPanel('progress', 'starting fresh conversation', [
1262
+ { label: this._backend.name, description: 'Rebuilding through createHarness() without restoring context.' },
1263
+ ]);
1264
+ try {
1265
+ await this._backend.clear();
1266
+ this._stopWatchingUsage();
1267
+ this._completedTurns = [];
1268
+ this._notices = [];
1269
+ this._tasks = [];
1270
+ this._context = {};
1271
+ this._nextTurn = 1;
1272
+ this._nextNotice = 1;
1273
+ this._taskBaselineReady = false;
1274
+ this._backgroundContinuationPending = false;
1275
+ this._attemptedBackgroundGeneration = undefined;
1276
+ this._stopTaskActivity();
1277
+ this._skillDetails.clear();
1278
+ this._runtime.session = this._backend.info?.().sessionId ?? 'in-memory';
1279
+ this._invalidateSessions();
1280
+ this._sessionCache = undefined;
1281
+ this._refreshRuntime();
1282
+ this._panel = undefined;
1283
+ this._panelStack.length = 0;
1284
+ this._emit();
1285
+ }
1286
+ catch (error) {
1287
+ this._openError('clear failed', 'clear', errorMessage(error));
1288
+ }
1289
+ finally {
1290
+ this._resourceChanging = false;
1291
+ }
1292
+ }
1293
+ _openSkillDetail(name) {
1294
+ const skill = this._skillDetails.get(name);
1295
+ if (!skill) {
1296
+ return false;
1297
+ }
1298
+ this._pushPanel('detail', `skill: ${skill.name}`, skillDetailRows(skill), {
1299
+ body: skill.instructions || '(No instructions.)',
1300
+ });
1301
+ return true;
1302
+ }
1303
+ async _openMcpPanel() {
1304
+ if (!this._mcp) {
1305
+ this._openError('MCP unavailable', 'mcp', 'No MCP runtime is configured.');
1306
+ return;
1307
+ }
1308
+ const loading = this._openPanel('mcp', 'MCP servers', [
1309
+ { label: 'loading', description: 'Checking server connections and tools.' },
1310
+ ]);
1311
+ try {
1312
+ const servers = await this._mcp.list(true);
1313
+ if (this._panel?.id !== loading.id) {
1314
+ return;
1315
+ }
1316
+ this._openPanel('mcp', `MCP servers (${servers.length})`, mcpRows(servers), mcpOptions(servers, this._mcp.paths, this._mcp.warnings));
1317
+ }
1318
+ catch (error) {
1319
+ if (this._panel?.id === loading.id) {
1320
+ this._openError('MCP connection failed', 'mcp', errorMessage(error));
1321
+ }
1322
+ }
1323
+ }
1324
+ async _handlePermissionsCommand(argument) {
1325
+ if (!argument) {
1326
+ this._openPermissionsPanel();
1327
+ return;
1328
+ }
1329
+ const normalized = argument.toLowerCase();
1330
+ if (normalized === 'default' || normalized === 'bypass' || normalized === 'bypasspermissions') {
1331
+ await this._setPermissionMode(normalized === 'default' ? 'default' : 'bypassPermissions');
1332
+ return;
1333
+ }
1334
+ this._openError('unknown permission mode', argument, 'Use /permissions, /permissions default, or /permissions bypass.');
1335
+ }
1336
+ _openPermissionsPanel() {
1337
+ const status = this._backend.permissionStatus?.();
1338
+ if (!status ||
1339
+ !this._backend.setPermissionMode ||
1340
+ !this._backend.allowPermission ||
1341
+ !this._backend.removeAllowedPermission) {
1342
+ this._openError('permissions unavailable', this._backend.name, 'Permission configuration is available only for the built-in Strands backend.');
1343
+ return;
1344
+ }
1345
+ this._openPanel('permissions', 'permissions', permissionSettingsRows(status, this._runtime.tools), {
1346
+ ...(status.mode === 'bypassPermissions'
1347
+ ? { body: 'WARNING: Permission checks are bypassed. Configured interventions and sandboxing still apply.' }
1348
+ : {}),
1349
+ });
1350
+ }
1351
+ async _updatePermissions(value) {
1352
+ const [prefix, action, encodedValue] = value.split(':');
1353
+ if (prefix !== 'permissions' || !action || !encodedValue) {
1354
+ return false;
1355
+ }
1356
+ if (action === 'mode' && (encodedValue === 'default' || encodedValue === 'bypassPermissions')) {
1357
+ return this._setPermissionMode(encodedValue);
1358
+ }
1359
+ if (action !== 'tool' ||
1360
+ !this._backend.allowPermission ||
1361
+ !this._backend.removeAllowedPermission ||
1362
+ !this._backend.permissionStatus) {
1363
+ return false;
1364
+ }
1365
+ const toolName = decodeURIComponent(encodedValue);
1366
+ try {
1367
+ const allowed = this._backend.permissionStatus()?.allowedTools.includes(toolName) ?? false;
1368
+ if (allowed) {
1369
+ await this._backend.removeAllowedPermission(toolName);
1370
+ }
1371
+ else {
1372
+ await this._backend.allowPermission(toolName);
1373
+ }
1374
+ this._openPermissionsPanel();
1375
+ return true;
1376
+ }
1377
+ catch (error) {
1378
+ this._openError('permission update failed', toolName, errorMessage(error));
1379
+ return false;
1380
+ }
1381
+ }
1382
+ async _setPermissionMode(mode) {
1383
+ if (!this._backend.setPermissionMode) {
1384
+ this._openError('permissions unavailable', this._backend.name, 'Permission configuration is available only for the built-in Strands backend.');
1385
+ return false;
1386
+ }
1387
+ try {
1388
+ await this._backend.setPermissionMode(mode);
1389
+ this._openPermissionsPanel();
1390
+ return true;
1391
+ }
1392
+ catch (error) {
1393
+ this._openError('permission update failed', mode, errorMessage(error));
1394
+ return false;
1395
+ }
1396
+ }
1397
+ async _handleExportCommand(argument) {
1398
+ if (!argument) {
1399
+ this._openExportPanel();
1400
+ return;
1401
+ }
1402
+ const match = /^(\S+)\s+([\s\S]+)$/u.exec(argument);
1403
+ const language = match?.[1]?.toLowerCase();
1404
+ const destination = unquote(match?.[2]?.trim() ?? '');
1405
+ if ((language !== 'typescript' && language !== 'python') || !destination.trim()) {
1406
+ this._openError('Export arguments required', '/export', 'Usage: /export <typescript|python> <path.zip>');
1407
+ return;
1408
+ }
1409
+ const path = destination.startsWith('~/') ? resolve(homedir(), destination.slice(2)) : destination;
1410
+ await this._exportAgent(language, resolve(this._runtime.cwd, path));
1411
+ }
1412
+ _openExportPanel() {
1413
+ if (!this._exportAgentProject) {
1414
+ this._openError('export unavailable', '/export', 'This connection cannot export an agent project.');
1415
+ return;
1416
+ }
1417
+ this._exportedPath = undefined;
1418
+ this._openPanel('export', `Export · ${this._backend.name}`, [
1419
+ {
1420
+ label: 'TypeScript',
1421
+ description: 'Runnable @strands-agents/harness project',
1422
+ value: EXPORT_TYPESCRIPT,
1423
+ },
1424
+ {
1425
+ label: 'Python',
1426
+ description: 'Runnable strands-harness project',
1427
+ value: EXPORT_PYTHON,
1428
+ },
1429
+ ].filter((row) => !this._project || row.value === `export:${this._project.language}`), {
1430
+ body: [
1431
+ `Agent: ${this._backend.name}`,
1432
+ `Source: ${this._project?.entrypoint ?? 'Current agent configuration'}`,
1433
+ `Location: ${this._project?.root ?? this._runtime.cwd}`,
1434
+ this._project
1435
+ ? `Language: ${this._project.language === 'typescript' ? 'TypeScript' : 'Python'} · preserves authored source`
1436
+ : 'Choose a language, then choose where to save the ZIP.',
1437
+ ...(!canChooseDirectory()
1438
+ ? [`Save with /export ${this._project?.language ?? '<typescript|python>'} <path.zip>.`]
1439
+ : []),
1440
+ ].join('\n'),
1441
+ });
1442
+ }
1443
+ async _exportAgent(language, destination) {
1444
+ if (!this._exportAgentProject) {
1445
+ return false;
1446
+ }
1447
+ if (this._project && language !== this._project.language) {
1448
+ this._openError('export failed', language, `This agent is authored in ${this._project.language}; export it in the same language to preserve its code.`);
1449
+ return false;
1450
+ }
1451
+ this._resourceChanging = true;
1452
+ try {
1453
+ const path = await this._exportAgentProject(language, destination);
1454
+ if (path) {
1455
+ this._exportedPath = path;
1456
+ this._openPanel('export', 'Export complete', [
1457
+ { label: 'Copy path', description: path, value: 'export:copy-path' },
1458
+ { label: 'Copy launch command', description: agentLaunchCommand(path), value: 'export:copy-command' },
1459
+ ], {
1460
+ body: [
1461
+ `Agent: ${this._backend.name}`,
1462
+ `Source: ${this._project?.entrypoint ?? 'Current agent configuration'}`,
1463
+ `Language: ${language === 'typescript' ? 'TypeScript' : 'Python'}`,
1464
+ `Saved to: ${path}`,
1465
+ ].join('\n'),
1466
+ });
1467
+ }
1468
+ else if (destination === undefined && !canChooseDirectory()) {
1469
+ this._openError('Export path required', '/export', `Use /export ${language} <path.zip> to save this agent.`);
1470
+ }
1471
+ return path !== undefined;
1472
+ }
1473
+ catch (error) {
1474
+ this._openError('export failed', language, errorMessage(error));
1475
+ return false;
1476
+ }
1477
+ finally {
1478
+ this._resourceChanging = false;
1479
+ }
1480
+ }
1481
+ async _copyExport(action) {
1482
+ if (!this._exportedPath || this._panel?.kind !== 'export') {
1483
+ return false;
1484
+ }
1485
+ const panel = this._panel;
1486
+ const text = action === 'export:copy-path' ? this._exportedPath : agentLaunchCommand(this._exportedPath);
1487
+ let copied = false;
1488
+ try {
1489
+ copied = await this._copyText(text);
1490
+ }
1491
+ catch {
1492
+ // Clipboard failures are reflected on the selected row.
1493
+ }
1494
+ if (this._panel === panel) {
1495
+ this._panel = {
1496
+ ...panel,
1497
+ rows: panel.rows.map((row) => row.value === action
1498
+ ? {
1499
+ ...row,
1500
+ description: `${copied ? 'Copied' : 'Copy failed'} · ${sanitizeTerminalText(text)}`,
1501
+ badge: { text: copied ? 'Copied' : 'Copy failed', tone: copied ? 'success' : 'danger' },
1502
+ }
1503
+ : row),
1504
+ };
1505
+ this._emit();
1506
+ }
1507
+ return copied;
1508
+ }
1509
+ async _updateSetting(setting) {
1510
+ if (this._panel?.kind !== 'settings') {
1511
+ return false;
1512
+ }
1513
+ if (setting === 'setup') {
1514
+ if (!this._requestSetup)
1515
+ return false;
1516
+ this._requestSetup();
1517
+ return true;
1518
+ }
1519
+ const update = parseSettingUpdate(setting, this._settings);
1520
+ if (!update) {
1521
+ return false;
1522
+ }
1523
+ this._resourceChanging = true;
1524
+ try {
1525
+ await this._setSettings?.(update);
1526
+ }
1527
+ catch (error) {
1528
+ this._openError('setting update failed', setting.split('=')[0], errorMessage(error));
1529
+ return false;
1530
+ }
1531
+ finally {
1532
+ this._resourceChanging = false;
1533
+ }
1534
+ this._settings = globalThis.structuredClone({ ...this._settings, ...update });
1535
+ this._panel = {
1536
+ ...this._panel,
1537
+ rows: sanitizeRows(settingsRows(this._settings, this._requestSetup !== undefined, this._panel.settingsCategory ?? DEFAULT_SETTINGS_CATEGORY)),
1538
+ };
1539
+ this._emit();
1540
+ return true;
1541
+ }
1542
+ _openSettingsCategory(value, replace = false) {
1543
+ const category = SETTINGS_CATEGORIES.find(({ id }) => value === `settings:${id}`);
1544
+ if (!category) {
1545
+ return false;
1546
+ }
1547
+ const rows = settingsRows(this._settings, this._requestSetup !== undefined, category.id);
1548
+ const options = {
1549
+ filters: settingsCategoryFilters(),
1550
+ settingsCategory: category.id,
1551
+ settingsCategories: SETTINGS_CATEGORIES,
1552
+ };
1553
+ if (replace) {
1554
+ this._openPanel('settings', category.label, rows, options);
1555
+ }
1556
+ else if (this._panel?.kind === 'settings') {
1557
+ this._panel = this._makePanel('settings', category.label, rows, options);
1558
+ this._emit();
1559
+ }
1560
+ else {
1561
+ this._pushPanel('settings', category.label, rows, options);
1562
+ }
1563
+ return true;
1564
+ }
1565
+ _respondPermission(value) {
1566
+ const [prefix, encodedRequestId, encodedOptionId] = value.split(':');
1567
+ if (prefix !== 'permission' || !encodedRequestId || !encodedOptionId) {
1568
+ return false;
1569
+ }
1570
+ const requestId = decodeURIComponent(encodedRequestId);
1571
+ const optionId = decodeURIComponent(encodedOptionId);
1572
+ if (!this._backend.respondPermission?.(requestId, optionId)) {
1573
+ return false;
1574
+ }
1575
+ this._closePermissionPanel();
1576
+ return true;
1577
+ }
1578
+ _respondSetupQuestion(value) {
1579
+ const [prefix, encodedRequestId, encodedChoiceId] = value.split(':');
1580
+ if (prefix !== 'question' || !encodedRequestId || !encodedChoiceId) {
1581
+ return false;
1582
+ }
1583
+ const previousAnswer = this._setupGuideAnswer;
1584
+ this._setupGuideAnswer = this._panel?.rows.find((row) => row.value === value)?.label;
1585
+ const responded = this._setupQuestions?.respond(decodeURIComponent(encodedRequestId), decodeURIComponent(encodedChoiceId)) ?? false;
1586
+ if (!responded) {
1587
+ this._setupGuideAnswer = previousAnswer;
1588
+ }
1589
+ return responded;
1590
+ }
1591
+ _respondSetupQuestionText(answer) {
1592
+ const value = this._panel?.rows.find((row) => row.value?.startsWith('question:'))?.value;
1593
+ const [, encodedRequestId] = value?.split(':') ?? [];
1594
+ if (!encodedRequestId) {
1595
+ return false;
1596
+ }
1597
+ const previousAnswer = this._setupGuideAnswer;
1598
+ const normalizedAnswer = sanitizeTerminalText(answer).trim();
1599
+ this._setupGuideAnswer = normalizedAnswer;
1600
+ try {
1601
+ const responded = this._setupQuestions?.respondText(decodeURIComponent(encodedRequestId), normalizedAnswer) ?? false;
1602
+ if (!responded) {
1603
+ this._setupGuideAnswer = previousAnswer;
1604
+ }
1605
+ return responded;
1606
+ }
1607
+ catch (error) {
1608
+ this._setupGuideAnswer = previousAnswer;
1609
+ throw error;
1610
+ }
1611
+ }
1612
+ _openPermissionPanel(request) {
1613
+ this._pushPanel('permission', `Allow ${request.toolName}?`, permissionRequestRows(request), {
1614
+ body: formatPermissionPanelBody(request),
1615
+ ...(request.diff ? { diff: request.diff } : {}),
1616
+ });
1617
+ }
1618
+ _openSetupQuestion(request) {
1619
+ this._setupGuideAnswer = undefined;
1620
+ this._pushPanel('question', 'Dr. Harness', setupQuestionRows(request), { body: request.question });
1621
+ }
1622
+ _refreshRuntime(model) {
1623
+ const info = this._backend.info?.();
1624
+ const session = info?.sessionId && this._sessions?.current === info.sessionId && this._runtime.session !== info.sessionId
1625
+ ? this._runtime.session
1626
+ : (info?.sessionId ?? (this._backend.protocol === 'strands' ? this._runtime.session : 'not saved'));
1627
+ const runtime = {
1628
+ ...this._runtime,
1629
+ agent: this._backend.name,
1630
+ backendId: this._backend.id,
1631
+ protocol: this._backend.protocol,
1632
+ model: model ?? info?.model ?? this._runtime.model,
1633
+ tools: info?.tools ?? [],
1634
+ session,
1635
+ };
1636
+ if (info?.effort !== undefined) {
1637
+ runtime.effort = info.effort;
1638
+ }
1639
+ else {
1640
+ delete runtime.effort;
1641
+ }
1642
+ this._runtime = runtime;
1643
+ }
1644
+ _closePermissionPanel() {
1645
+ if (this._panel?.kind !== 'permission') {
1646
+ return;
1647
+ }
1648
+ this._panel = this._panelStack.pop();
1649
+ this._emit();
1650
+ }
1651
+ _closeSetupQuestion() {
1652
+ if (this._panel?.kind !== 'question') {
1653
+ return;
1654
+ }
1655
+ this._panel = this._panelStack.pop();
1656
+ this._emit();
1657
+ }
1658
+ _setTasks(tasks) {
1659
+ const previous = new Map(this._tasks.map((task) => [task.id, task]));
1660
+ this._tasks = tasks.map(cloneTask);
1661
+ if (this._taskBaselineReady) {
1662
+ this._recordTaskTransitions(previous, this._tasks);
1663
+ }
1664
+ else {
1665
+ this._taskBaselineReady = true;
1666
+ }
1667
+ if (this._panel?.kind === 'tasks') {
1668
+ this._panel = {
1669
+ ...this._panel,
1670
+ title: `tasks (${this._tasks.length})`,
1671
+ rows: sanitizeRows(taskRows(this._tasks, this._backend.backgroundTasksWaitForCompletion?.())),
1672
+ };
1673
+ }
1674
+ if (this._openTaskDetailId) {
1675
+ this._refreshTaskDetail();
1676
+ }
1677
+ const generation = readyBackgroundGeneration(this._tasks);
1678
+ if (generation && this._attemptedBackgroundGeneration !== generation && this._backend.streamBackgroundResults) {
1679
+ this._backgroundContinuationPending = true;
1680
+ this._startBackgroundContinuation();
1681
+ }
1682
+ else if (!generation) {
1683
+ this._backgroundContinuationPending = false;
1684
+ }
1685
+ }
1686
+ _startBackgroundContinuation() {
1687
+ if (!this._backgroundContinuationPending ||
1688
+ this._backgroundContinuationRun ||
1689
+ this._closed ||
1690
+ this._activeProjector !== undefined ||
1691
+ this._drainingProjector !== undefined ||
1692
+ this._pendingSubmissionRun !== undefined ||
1693
+ this._resourceChanging ||
1694
+ this._pendingSubmissions.some((pending) => pending.kind === 'user') ||
1695
+ !this._backend.streamBackgroundResults) {
1696
+ return;
1697
+ }
1698
+ if (!this._backend.hasReadyBackgroundResults?.()) {
1699
+ this._backgroundContinuationPending = false;
1700
+ return;
1701
+ }
1702
+ const generation = readyBackgroundGeneration(this._tasks);
1703
+ if (!generation || this._attemptedBackgroundGeneration === generation) {
1704
+ this._backgroundContinuationPending = false;
1705
+ return;
1706
+ }
1707
+ this._attemptedBackgroundGeneration = generation;
1708
+ this._backgroundContinuationPending = false;
1709
+ const run = this._runBackgroundContinuation();
1710
+ this._backgroundContinuationRun = run;
1711
+ void run.finally(() => {
1712
+ if (this._backgroundContinuationRun === run) {
1713
+ this._backgroundContinuationRun = undefined;
1714
+ }
1715
+ this._startBackgroundContinuation();
1716
+ this._startPendingSubmissions();
1717
+ });
1718
+ }
1719
+ _hasUnresolvedBackgroundTasks() {
1720
+ return this._tasks.some(isUnresolvedBackgroundTask);
1721
+ }
1722
+ _openTaskDetail(value) {
1723
+ const taskId = readTaskValue(value);
1724
+ const task = taskId ? this._tasks.find((candidate) => candidate.id === taskId) : undefined;
1725
+ if (!task) {
1726
+ return false;
1727
+ }
1728
+ this._stopTaskActivity();
1729
+ this._openTaskDetailId = task.id;
1730
+ const activity = this._backend.getTaskActivity?.(task.id);
1731
+ this._pushPanel('detail', taskDetailTitle(task, activity), taskDetailRows(task, activity), {
1732
+ body: activity ? '' : formatTaskActivity(task),
1733
+ followTail: true,
1734
+ ...(activity ? { activity } : {}),
1735
+ });
1736
+ this._stopWatchingTaskActivity = this._backend.watchTaskActivity?.(task.id, () => {
1737
+ if (this._openTaskDetailId !== task.id || this._taskDetailRefreshTimer) {
1738
+ return;
1739
+ }
1740
+ this._taskDetailRefreshTimer = setTimeout(() => {
1741
+ this._taskDetailRefreshTimer = undefined;
1742
+ this._refreshTaskDetail();
1743
+ this._emit();
1744
+ }, 33);
1745
+ });
1746
+ return true;
1747
+ }
1748
+ _refreshTaskDetail() {
1749
+ const taskId = this._openTaskDetailId;
1750
+ const task = taskId ? this._tasks.find((candidate) => candidate.id === taskId) : undefined;
1751
+ if (!task || this._panel?.kind !== 'detail') {
1752
+ return;
1753
+ }
1754
+ const activity = this._backend.getTaskActivity?.(task.id);
1755
+ const { activity: _previousActivity, ...panel } = this._panel;
1756
+ this._panel = {
1757
+ ...panel,
1758
+ title: taskDetailTitle(task, activity),
1759
+ rows: sanitizeRows(taskDetailRows(task, activity)),
1760
+ body: sanitizeTerminalText(activity ? '' : formatTaskActivity(task)),
1761
+ ...(activity ? { activity } : {}),
1762
+ };
1763
+ }
1764
+ _stopTaskActivity() {
1765
+ clearTimeout(this._taskDetailRefreshTimer);
1766
+ this._taskDetailRefreshTimer = undefined;
1767
+ this._stopWatchingTaskActivity?.();
1768
+ this._stopWatchingTaskActivity = undefined;
1769
+ this._openTaskDetailId = undefined;
1770
+ }
1771
+ _recordTaskTransitions(previous, current) {
1772
+ const currentIds = new Set(current.map((task) => task.id));
1773
+ for (const task of current) {
1774
+ if (task.source !== 'background') {
1775
+ continue;
1776
+ }
1777
+ const prior = previous.get(task.id);
1778
+ if (prior?.status !== task.status &&
1779
+ (task.status === 'completed' || task.status === 'failed' || task.status === 'cancelled')) {
1780
+ const status = task.status === 'completed' ? 'success' : 'error';
1781
+ this._addNotice(status, `Background task ${task.status} (${task.label})`, task.id);
1782
+ }
1783
+ if (prior?.deliveryState !== 'delivered' && task.deliveryState === 'delivered') {
1784
+ this._markBackgroundTaskDelivered(task.id);
1785
+ }
1786
+ }
1787
+ for (const task of previous.values()) {
1788
+ if (task.source === 'background' && task.deliveryState === 'ready' && !currentIds.has(task.id)) {
1789
+ this._markBackgroundTaskDelivered(task.id);
1790
+ }
1791
+ }
1792
+ }
1793
+ _markBackgroundTaskDelivered(taskId) {
1794
+ this._deliveredBackgroundTaskIds.add(taskId);
1795
+ if (!this._activeProjector && !this._drainingProjector) {
1796
+ this._clearDeliveredBackgroundTaskNotices();
1797
+ }
1798
+ }
1799
+ _clearDeliveredBackgroundTaskNotices() {
1800
+ if (this._deliveredBackgroundTaskIds.size === 0) {
1801
+ return;
1802
+ }
1803
+ this._notices = this._notices.filter((notice) => notice.status !== 'success' || !notice.taskId || !this._deliveredBackgroundTaskIds.has(notice.taskId));
1804
+ this._deliveredBackgroundTaskIds.clear();
1805
+ }
1806
+ _addNotice(status, text, taskId) {
1807
+ const afterTurnId = this._activeProjector?.snapshot().id ?? this._completedTurns.at(-1)?.id;
1808
+ const notice = {
1809
+ id: `notice-${this._nextNotice++}`,
1810
+ ...(afterTurnId ? { afterTurnId } : {}),
1811
+ ...(taskId !== undefined ? { taskId } : {}),
1812
+ text: sanitizeTerminalText(text),
1813
+ status,
1814
+ };
1815
+ this._notices.push(notice);
1816
+ return notice;
1817
+ }
1818
+ async _applyDeferredModelRestart() {
1819
+ const modelId = this._deferredModelRestart;
1820
+ if (!modelId || this._closed || this._activeProjector || this._drainingProjector || !this._backend.restartModel) {
1821
+ return;
1822
+ }
1823
+ this._deferredModelRestart = undefined;
1824
+ const notice = this._notices.find((candidate) => candidate.id === this._deferredModelNoticeId);
1825
+ this._deferredModelNoticeId = undefined;
1826
+ if (this._hasUnresolvedBackgroundTasks()) {
1827
+ if (notice) {
1828
+ notice.status = 'error';
1829
+ notice.text = 'Model change could not run because background work is still active';
1830
+ }
1831
+ this._emit();
1832
+ return;
1833
+ }
1834
+ this._resourceChanging = true;
1835
+ if (notice) {
1836
+ notice.text = `Applying model change: ${modelDisplayName(modelId)}`;
1837
+ }
1838
+ this._emit();
1839
+ try {
1840
+ const selected = await this._backend.restartModel(modelId);
1841
+ this._context = {};
1842
+ this._refreshRuntime(typeof selected === 'string' ? selected : modelId);
1843
+ this._updateOpenModelPanel(modelId);
1844
+ if (notice) {
1845
+ notice.status = 'delivered';
1846
+ notice.text = `Model changed to ${modelDisplayName(modelId)}`;
1847
+ }
1848
+ }
1849
+ catch (error) {
1850
+ if (notice) {
1851
+ notice.status = 'error';
1852
+ notice.text = modelControlErrorMessage(error, 'model');
1853
+ }
1854
+ }
1855
+ finally {
1856
+ this._resourceChanging = false;
1857
+ this._emit();
1858
+ }
1859
+ }
1860
+ _updateOpenModelPanel(modelId) {
1861
+ const panel = this._panel;
1862
+ if (panel?.kind !== 'models') {
1863
+ return;
1864
+ }
1865
+ const rows = panel.rows.map((row) => {
1866
+ const next = { ...row };
1867
+ if (next.badge?.text === 'current') {
1868
+ delete next.badge;
1869
+ if (next.section === 'Current model') {
1870
+ delete next.section;
1871
+ }
1872
+ }
1873
+ return row.value === modelId
1874
+ ? {
1875
+ ...next,
1876
+ section: 'Current model',
1877
+ badge: { text: 'current', tone: 'success' },
1878
+ }
1879
+ : next;
1880
+ });
1881
+ const slider = effortSlider(this._backend.listEfforts?.() ?? []);
1882
+ const updated = this._makePanel('models', panel.title, rows, {
1883
+ ...(panel.searchable !== undefined ? { searchable: panel.searchable } : {}),
1884
+ ...(panel.filters ? { filters: panel.filters } : {}),
1885
+ ...(slider ? { slider } : {}),
1886
+ body: `${modelDisplayName(this._runtime.model)}\n${this._runtime.model}`,
1887
+ });
1888
+ this._panel = { ...updated, id: panel.id };
1889
+ }
1890
+ _openPanel(kind, title, rows, options = {}) {
1891
+ this._panelStack.length = 0;
1892
+ const panel = this._makePanel(kind, title, rows, options);
1893
+ this._panel = panel;
1894
+ this._emit();
1895
+ return panel;
1896
+ }
1897
+ _pushPanel(kind, title, rows, options) {
1898
+ if (this._panel) {
1899
+ this._panelStack.push(this._panel);
1900
+ }
1901
+ const panel = this._makePanel(kind, title, rows, options);
1902
+ this._panel = panel;
1903
+ this._emit();
1904
+ return panel;
1905
+ }
1906
+ _makePanel(kind, title, rows, options) {
1907
+ return makePanel(`panel-${this._nextPanel++}`, kind, title, rows, options);
1908
+ }
1909
+ _openError(title, label, description) {
1910
+ this._openPanel('error', title, [{ label, description, tone: 'danger' }]);
1911
+ }
1912
+ }
1913
+ //# sourceMappingURL=controller.js.map