@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,731 @@
1
+ """Execute an authored Python agent; only terminal commands cross the process boundary."""
2
+
3
+ import ast
4
+ import asyncio
5
+ import base64
6
+ import contextlib
7
+ import importlib
8
+ import importlib.abc
9
+ import importlib.machinery
10
+ import importlib.util
11
+ import inspect
12
+ import json
13
+ import os
14
+ import re
15
+ import sys
16
+ import threading
17
+ import tokenize
18
+ from pathlib import Path
19
+ from typing import Literal
20
+ from uuid import uuid4
21
+
22
+ import strands_harness
23
+ from strands import Agent, tool
24
+ from strands.hooks import HookOrder
25
+ from strands.hooks.events import BeforeToolCallEvent
26
+ from strands.session import SnapshotSessionManager
27
+ from strands.storage import LocalFileStorage
28
+ from strands.tools.mcp import MCPClient
29
+ from strands.types.tools import ToolContext
30
+ from strands.vended_plugins.skills import AgentSkills
31
+ from strands_harness import define_harness_agent_config, harness_agent_kwargs_from_config
32
+ from strands_harness.defaults import DEFAULT_MODEL
33
+
34
+ channel = os.fdopen(3, "w", buffering=1)
35
+ pending_permissions = {}
36
+
37
+
38
+ def encode(value):
39
+ if isinstance(value, bytes):
40
+ return {"$bytes": base64.b64encode(value).decode("ascii")}
41
+ raise TypeError(f"Cannot send {type(value).__name__} to the terminal")
42
+
43
+
44
+ def decode(value):
45
+ if set(value) == {"$bytes"}:
46
+ return base64.b64decode(value["$bytes"])
47
+ return value
48
+
49
+
50
+ def send(message):
51
+ channel.write(json.dumps(message, default=encode) + "\n")
52
+
53
+
54
+ def emit(event):
55
+ send({"type": "event", "event": event})
56
+
57
+
58
+ async def authorize_tool(event):
59
+ tool_use = event.tool_use
60
+ if tool_use["name"] == "strands_config":
61
+ return
62
+ request = {
63
+ "type": "authorize",
64
+ "name": tool_use["name"],
65
+ "input": tool_use.get("input", {}),
66
+ "pathInWorkspace": False,
67
+ }
68
+ path = tool_use.get("input", {}).get("path")
69
+ if isinstance(path, str):
70
+ try:
71
+ resolved = Path(path).resolve()
72
+ request["pathInWorkspace"] = resolved.is_relative_to(Path.cwd().resolve())
73
+ if tool_use["name"] in ("write", "edit"):
74
+ request["before"] = await event.agent.sandbox.read_text(path)
75
+ except FileNotFoundError:
76
+ if tool_use["name"] == "write":
77
+ request["before"] = ""
78
+ except Exception:
79
+ pass
80
+ approved = await permission(request)
81
+ if not approved:
82
+ event.cancel_tool = "DENIED: Tool call denied by the user"
83
+
84
+
85
+ async def permission(request):
86
+ request_id = request.get("id", str(uuid4()))
87
+ future = asyncio.get_running_loop().create_future()
88
+ pending_permissions[request_id] = future
89
+ try:
90
+ send({**request, "id": request_id})
91
+ return await future
92
+ finally:
93
+ pending_permissions.pop(request_id, None)
94
+
95
+
96
+ def overrides_from_config(partial):
97
+ if not partial:
98
+ return {}
99
+ config = define_harness_agent_config(partial)
100
+ options = harness_agent_kwargs_from_config(config)
101
+ # These values are normally omitted by the config loader when equal to defaults.
102
+ for key in ("builtinTools", "builtinPlugins", "caching", "description", "instructions", "sessionId"):
103
+ if key in partial:
104
+ options[re.sub(r"[A-Z]", lambda match: "_" + match[0].lower(), key)] = config[key]
105
+ aliases = {
106
+ "subagents": "tools",
107
+ "modelModule": "model",
108
+ "webFetchModelModule": "web_fetch_model",
109
+ "memoryStores": "memory_store",
110
+ "interventionModules": "interventions",
111
+ }
112
+ keys = {aliases.get(key, re.sub(r"[A-Z]", lambda match: "_" + match[0].lower(), key)) for key in partial}
113
+ keys.update(partial.get("agentConfig", {}))
114
+ keys.update(partial.get("agentConfigModules", {}))
115
+ return {
116
+ key: options[key]
117
+ for key in keys
118
+ if key in options and key not in ("agent_config", "agent_config_modules", "dependencies")
119
+ }
120
+
121
+
122
+ def display_content(block):
123
+ if "text" in block:
124
+ return {"type": "text", "text": block["text"]}
125
+ if "json" in block:
126
+ return {"type": "json", "value": block["json"]}
127
+ for kind in ("image", "document"):
128
+ if kind in block:
129
+ media = block[kind]
130
+ source = media["source"]
131
+ source_type = next(iter(source))
132
+ return {
133
+ "type": kind,
134
+ **{key: value for key, value in media.items() if key != "source"},
135
+ "source": {"type": source_type, source_type: source[source_type]},
136
+ }
137
+ return {"type": "text", "text": str(block)}
138
+
139
+
140
+ def display_messages(agent):
141
+ messages = []
142
+ for message in agent.messages:
143
+ blocks = []
144
+ for block in message["content"]:
145
+ if "text" in block or "toolUse" in block:
146
+ blocks.append(block)
147
+ elif "toolResult" in block:
148
+ result = block["toolResult"]
149
+ blocks.append(
150
+ {
151
+ "toolResult": {
152
+ **result,
153
+ "content": [
154
+ value if "text" in value or "json" in value else {"text": "[media]"}
155
+ for value in result.get("content", [])
156
+ ],
157
+ }
158
+ }
159
+ )
160
+ if blocks:
161
+ messages.append({"role": message["role"], "content": blocks})
162
+ return messages
163
+
164
+
165
+ def local_session_directory(storage):
166
+ parts = []
167
+ while hasattr(storage, "_storage") and hasattr(storage, "_prefix"):
168
+ parts.append(storage._prefix)
169
+ storage = storage._storage
170
+ if not isinstance(storage, LocalFileStorage):
171
+ return None
172
+ return str(Path(storage._base_dir, *parts).resolve())
173
+
174
+
175
+ class Runtime:
176
+ def __init__(self, module, command):
177
+ self.module = module
178
+ partial = command.get("overrides", {})
179
+ for assignment in command.get("assignments", []):
180
+ path, raw = assignment.split("=", 1)
181
+ keys = path.split(".")
182
+ try:
183
+ value = json.loads(raw)
184
+ except ValueError:
185
+ value = raw
186
+ if len(keys) == 1:
187
+ partial[keys[0]] = value
188
+ else:
189
+ target = partial.setdefault(keys[0], {})
190
+ if not isinstance(target, dict):
191
+ target = {}
192
+ partial[keys[0]] = target
193
+ for key in keys[1:-1]:
194
+ if not isinstance(target.get(key), dict):
195
+ target[key] = {}
196
+ target = target[key]
197
+ target[keys[-1]] = value
198
+ self.options = overrides_from_config(partial)
199
+ for source, target in (("sessionId", "session_id"), ("sessionDir", "session_dir")):
200
+ if source in command:
201
+ self.options[target] = command[source]
202
+ self.explicit_option_keys = set(self.options)
203
+ model = self.options.get("model")
204
+ self.source_configuration = (
205
+ {"model": model, "thinking": self.options.get("effort", "auto")} if isinstance(model, str) else None
206
+ )
207
+ selection = command.get("sourceSelection")
208
+ if (
209
+ self.source_configuration
210
+ and selection
211
+ and selection["source"] == module.__file__
212
+ and selection["configured"] == self.source_configuration
213
+ ):
214
+ self.options.update(
215
+ model=selection["selected"]["model"],
216
+ effort=selection["selected"]["thinking"],
217
+ )
218
+ self.session_configuration = {
219
+ "sessionId": self.options.get("session_id"),
220
+ "sessionDir": str(self.options.get("session_dir", ".agent/sessions")),
221
+ }
222
+ session_directory = command.get("sessionStorageDirectory")
223
+ self.options["session_dir"] = str(Path(self.options.get("session_dir", ".agent/sessions")).resolve())
224
+ self.session_directory = (
225
+ str(Path(session_directory).resolve())
226
+ if session_directory is not None
227
+ else str(Path(self.options["session_dir"]) / "session")
228
+ )
229
+ self.agent: Agent
230
+ self.initial_agent = module.agent
231
+ self.factory = getattr(module, "create_agent", None)
232
+ self.interactive = command.get("interactive", False)
233
+ self.mcp_servers = command.get("mcpServers", {})
234
+ self.skill_paths = command.get("skillPaths", [])
235
+ self.cancel_signal = threading.Event()
236
+ self.reload_requested = False
237
+
238
+ async def build(self, options, snapshot=None):
239
+ previous = getattr(self, "agent", self.initial_agent)
240
+ factory_options = {key: options[key] for key in self.explicit_option_keys if key in options}
241
+ if self.initial_agent is not None and not factory_options:
242
+ candidate = self.initial_agent
243
+ self.initial_agent = None
244
+ else:
245
+ self.initial_agent = None
246
+ if not callable(self.factory):
247
+ raise ValueError(
248
+ "This source exports an agent instance but not create_agent(**overrides), "
249
+ "and is not a direct agent = create_harness(...) definition; recreation controls are unavailable."
250
+ )
251
+ candidate = self.factory(**factory_options)
252
+ if inspect.isawaitable(candidate):
253
+ candidate = await candidate
254
+ if not isinstance(candidate, Agent):
255
+ raise TypeError("create_harness() must return a Strands Agent")
256
+ try:
257
+ await self.augment(candidate)
258
+ if snapshot:
259
+ candidate.load_snapshot(snapshot)
260
+ await self.save(candidate)
261
+ except Exception:
262
+ await self.cleanup(candidate)
263
+ raise
264
+ self.agent = candidate
265
+ self.options = options
266
+ if previous is not None and previous is not candidate:
267
+ await self.cleanup(previous)
268
+
269
+ async def augment(self, agent):
270
+ if self.interactive:
271
+ agent.hooks.add_callback(BeforeToolCallEvent, authorize_tool, order=HookOrder.INTERVENTION_INPUT)
272
+ if not any(spec["name"] == "strands_config" for spec in agent.tool_registry.get_all_tool_specs()):
273
+ agent.tool_registry.process_tools([self.configuration_tool()])
274
+ if self.mcp_servers:
275
+ existing = {getattr(provider, "client_name", None) for provider in agent.tool_registry._tool_providers}
276
+ servers = {name: value for name, value in self.mcp_servers.items() if name not in existing}
277
+ if servers:
278
+ agent.tool_registry.process_tools(
279
+ MCPClient.load_servers(
280
+ servers,
281
+ continue_on_error=True,
282
+ prefix_with_server_name=True,
283
+ )
284
+ )
285
+ if self.skill_paths:
286
+ skills = next(
287
+ (plugin for plugin in agent._plugin_registry._plugins.values() if isinstance(plugin, AgentSkills)),
288
+ None,
289
+ )
290
+ if skills:
291
+ skills.set_available_skills([*skills.get_available_skills(agent), *self.skill_paths])
292
+ await skills.init_agent(agent)
293
+ else:
294
+ agent._plugin_registry.add_and_init(AgentSkills(skills=self.skill_paths))
295
+
296
+ def configuration_tool(self):
297
+ runtime = self
298
+
299
+ @tool(name="strands_config")
300
+ def strands_config(action: Literal["inspect", "apply"], revision: int | None = None) -> str:
301
+ """Inspect this source-backed agent or apply source edits by reloading it after the current turn.
302
+
303
+ Args:
304
+ action: Inspect the active source or apply edits made to it.
305
+ revision: The revision returned by inspect; required when applying.
306
+ """
307
+ if action == "inspect":
308
+ return json.dumps(
309
+ {
310
+ "revision": 0,
311
+ "target": {"source": runtime.module.__file__},
312
+ "runtime": {
313
+ "name": runtime.agent.name,
314
+ "model": runtime.agent.model.get_config().get("model_id"),
315
+ "tools": [spec["name"] for spec in runtime.agent.tool_registry.get_all_tool_specs()],
316
+ },
317
+ }
318
+ )
319
+ if revision != 0:
320
+ raise ValueError("Inspect the source before applying it, then pass revision 0.")
321
+ runtime.reload_requested = True
322
+ return "Source reload validated. It will be applied after this turn, preserving the conversation."
323
+
324
+ return strands_config
325
+
326
+ async def cleanup(self, agent):
327
+ manager = getattr(agent, "memory_manager", None)
328
+ if manager:
329
+ with contextlib.suppress(Exception):
330
+ await manager.flush()
331
+ with contextlib.suppress(Exception):
332
+ agent.cleanup()
333
+
334
+ async def save(self, agent=None):
335
+ agent = self.agent if agent is None else agent
336
+ manager = agent._session_manager
337
+ if isinstance(manager, SnapshotSessionManager):
338
+ await manager.save_snapshot(agent, is_latest=True)
339
+
340
+ def skills(self):
341
+ return next(
342
+ (plugin for plugin in self.agent._plugin_registry._plugins.values() if isinstance(plugin, AgentSkills)),
343
+ None,
344
+ )
345
+
346
+ def state(self):
347
+ model = self.options.get("model")
348
+ if not isinstance(model, str):
349
+ model = str(self.agent.model.get_config().get("model_id", type(self.agent.model).__name__))
350
+ manager = self.agent._session_manager
351
+ session_id = (
352
+ manager.session_id if isinstance(manager, SnapshotSessionManager) else self.options.get("session_id")
353
+ )
354
+ storage = manager._storage if isinstance(manager, SnapshotSessionManager) else None
355
+ session_directory = local_session_directory(storage)
356
+ managed_session = session_directory is not None
357
+ skills = self.skills()
358
+ active = skills.get_activated_skills(self.agent) if skills else []
359
+ return {
360
+ "name": self.agent.name or "Agent",
361
+ "reconstructable": callable(self.factory),
362
+ "description": self.agent.description or "",
363
+ "model": model,
364
+ **({"modelSpecifier": self.options["model"]} if isinstance(self.options.get("model"), str) else {}),
365
+ "thinking": self.options.get("effort", "auto"),
366
+ **(
367
+ {
368
+ "sourceSelection": {
369
+ "source": self.module.__file__,
370
+ "configured": self.source_configuration,
371
+ "selected": {
372
+ "model": self.options.get("model") or DEFAULT_MODEL,
373
+ "thinking": self.options.get("effort", "auto"),
374
+ },
375
+ }
376
+ }
377
+ if self.source_configuration
378
+ else {}
379
+ ),
380
+ **({"sessionId": session_id} if session_id else {}),
381
+ "sessionDirectory": session_directory or self.options["session_dir"],
382
+ **(
383
+ {
384
+ "session": {
385
+ "sessionId": session_id,
386
+ "sessionDirectory": session_directory,
387
+ "workspace": str(Path.cwd()),
388
+ "configured": self.session_configuration,
389
+ }
390
+ }
391
+ if managed_session
392
+ else {}
393
+ ),
394
+ "messages": display_messages(self.agent),
395
+ "privatePaths": [
396
+ *([session_directory] if session_directory else []),
397
+ str(Path(self.options.get("memory_dir", ".agent/memory")).resolve()),
398
+ ],
399
+ "tools": [
400
+ {"name": spec["name"], "description": spec.get("description", "")}
401
+ for spec in self.agent.tool_registry.get_all_tool_specs()
402
+ ],
403
+ "skills": [
404
+ {
405
+ "name": skill.name,
406
+ "description": skill.description,
407
+ "instructions": skill.instructions,
408
+ "active": skill.name in active,
409
+ }
410
+ for skill in skills.get_available_skills(self.agent)
411
+ ]
412
+ if skills
413
+ else [],
414
+ }
415
+
416
+ def result(self, result, *, reload=False):
417
+ send({"type": "result", "result": result, "state": self.state(), "reload": reload})
418
+
419
+ async def turn(self, prompt):
420
+ self.cancel_signal.clear()
421
+ self.reload_requested = False
422
+ snapshot = self.agent.take_snapshot(preset="session")
423
+ emitted_tool_results = set()
424
+ try:
425
+ while True:
426
+ result = None
427
+ async for event in self.agent.stream_async(prompt, cancel_signal=self.cancel_signal):
428
+ if isinstance(event.get("data"), str):
429
+ emit({"type": "textDelta", "text": event["data"]})
430
+ if event.get("reasoningText"):
431
+ emit({"type": "reasoningDelta", "text": event["reasoningText"]})
432
+ tool_results = [event["tool_result"]] if event.get("tool_result") else []
433
+ for block in event.get("message", {}).get("content", []):
434
+ if "toolUse" in block:
435
+ emit({"type": "toolStart", **block["toolUse"]})
436
+ elif "toolResult" in block:
437
+ tool_results.append(block["toolResult"])
438
+ elif "image" in block or "document" in block:
439
+ emit({"type": "media", "content": display_content(block)})
440
+ for tool_result in tool_results:
441
+ if tool_result["toolUseId"] in emitted_tool_results:
442
+ continue
443
+ emitted_tool_results.add(tool_result["toolUseId"])
444
+ emit(
445
+ {
446
+ "type": "toolResult",
447
+ "toolUseId": tool_result["toolUseId"],
448
+ "status": tool_result["status"],
449
+ "content": [display_content(block) for block in tool_result.get("content", [])],
450
+ }
451
+ )
452
+ if "result" in event:
453
+ result = event["result"]
454
+ if result is None:
455
+ raise RuntimeError("The Python agent finished without a result")
456
+ if result.stop_reason != "interrupt" or not result.interrupts:
457
+ self.result(
458
+ {
459
+ "stopReason": result.stop_reason,
460
+ "finalText": str(result),
461
+ "usage": {
462
+ "cacheReadInputTokens": 0,
463
+ "cacheWriteInputTokens": 0,
464
+ **result.metrics.accumulated_usage,
465
+ },
466
+ },
467
+ reload=self.reload_requested and not self.cancel_signal.is_set(),
468
+ )
469
+ return
470
+ prompt = []
471
+ for interrupt in result.interrupts:
472
+ future = asyncio.get_running_loop().create_future()
473
+ pending_permissions[interrupt.id] = future
474
+ try:
475
+ emit(
476
+ {
477
+ "type": "permission",
478
+ "request": {
479
+ "id": interrupt.id,
480
+ "toolName": interrupt.name,
481
+ "input": interrupt.reason,
482
+ "options": [
483
+ {"id": "allow", "label": "Allow", "kind": "allow_once"},
484
+ {"id": "deny", "label": "Deny", "kind": "reject_once"},
485
+ ],
486
+ },
487
+ }
488
+ )
489
+ approved = await future
490
+ prompt.append({"interruptResponse": {"interruptId": interrupt.id, "response": approved}})
491
+ finally:
492
+ pending_permissions.pop(interrupt.id, None)
493
+ except asyncio.CancelledError:
494
+ self.result({"stopReason": "cancelled"})
495
+ except Exception as error:
496
+ try:
497
+ self.agent.load_snapshot(snapshot)
498
+ await self.save()
499
+ except Exception as rollback_error:
500
+ send({"type": "error", "message": f"{error}; could not restore session: {rollback_error}"})
501
+ return
502
+ send({"type": "error", "message": str(error)})
503
+ finally:
504
+ self.reload_requested = False
505
+
506
+ async def command(self, command):
507
+ kind = command["type"]
508
+ if kind == "conversation":
509
+ from strands.types._snapshot import Snapshot
510
+
511
+ snapshot = command.get("snapshot")
512
+ if snapshot:
513
+ data = snapshot["data"]
514
+ if not command.get("preserveReasoning"):
515
+ for message in data["messages"]:
516
+ message["content"] = [block for block in message["content"] if "reasoningContent" not in block]
517
+ data["messages"] = [message for message in data["messages"] if message["content"]]
518
+ self.agent.load_snapshot(
519
+ Snapshot(scope="agent", schema_version=snapshot["schemaVersion"], data=data, app_data={})
520
+ )
521
+ await self.save()
522
+ self.result({"stopReason": "restored"})
523
+ else:
524
+ snapshot = self.agent.take_snapshot(include=["messages", "state", "conversation_manager_state"])
525
+ self.result(
526
+ {
527
+ "stopReason": "snapshot",
528
+ "finalText": json.dumps(
529
+ {
530
+ "scope": snapshot.scope,
531
+ "schemaVersion": snapshot.schema_version,
532
+ "createdAt": snapshot.created_at,
533
+ "data": snapshot.data,
534
+ "appData": {},
535
+ },
536
+ default=encode,
537
+ ),
538
+ }
539
+ )
540
+ elif kind == "reload-failed":
541
+ self.agent.messages.append(
542
+ {
543
+ "role": "user",
544
+ "content": [
545
+ {
546
+ "text": (
547
+ "The harness setup result: source reload failed. "
548
+ "The previous agent remains active.\n"
549
+ f"Reason: {command['message']}\n"
550
+ "Correct the source and use strands_config apply to retry."
551
+ )
552
+ }
553
+ ],
554
+ }
555
+ )
556
+ await self.save()
557
+ self.result({"stopReason": "recorded"})
558
+ elif kind == "snapshot":
559
+ snapshot = self.agent.take_snapshot(preset="session").to_dict()
560
+ self.result({"stopReason": "snapshot", "finalText": json.dumps(snapshot, default=encode)})
561
+ elif kind == "seed":
562
+ from strands.types._snapshot import Snapshot
563
+
564
+ self.agent.load_snapshot(Snapshot.from_dict(json.loads(command["snapshot"], object_hook=decode)))
565
+ await self.save()
566
+ self.result({"stopReason": "seeded"})
567
+ elif kind == "reset":
568
+ options = dict(self.options)
569
+ if "model" in command:
570
+ options["model"] = command["model"]
571
+ self.explicit_option_keys.add("model")
572
+ if "thinking" in command:
573
+ options["effort"] = command["thinking"]
574
+ self.explicit_option_keys.add("effort")
575
+ if "sessionId" in command and options.get("session", True):
576
+ options["session_id"] = command["sessionId"]
577
+ self.explicit_option_keys.add("session_id")
578
+ snapshot = None if command.get("clear") else self.agent.take_snapshot(preset="session")
579
+ await self.build(options, snapshot)
580
+ self.result({"stopReason": "reset"})
581
+ elif kind == "compact":
582
+ from strands.agent.conversation_manager import SummarizingConversationManager
583
+
584
+ manager = SummarizingConversationManager(summary_ratio=0.8, preserve_recent_messages=2)
585
+ before = len(self.agent.messages)
586
+ await asyncio.to_thread(manager.reduce_context, self.agent)
587
+ await self.save()
588
+ self.result({"stopReason": "compacted" if len(self.agent.messages) < before else "unchanged"})
589
+ elif kind == "skill":
590
+ skills = self.skills()
591
+ if not skills:
592
+ raise ValueError("This agent has no skills")
593
+ await skills.skills(
594
+ skill_name=command["name"],
595
+ tool_context=ToolContext(
596
+ tool_use={"toolUseId": str(uuid4()), "name": "skills", "input": {}},
597
+ agent=self.agent,
598
+ invocation_state={},
599
+ ),
600
+ )
601
+ await self.save()
602
+ self.result({"stopReason": "activated"})
603
+ else:
604
+ raise ValueError(f"Unknown terminal command: {kind}")
605
+
606
+
607
+ class ProjectSourceLoader(importlib.machinery.SourceFileLoader):
608
+ def get_code(self, fullname):
609
+ # Same-size edits within one second can leave timestamp-based bytecode valid.
610
+ return self.source_to_code(self.get_data(self.path), self.path)
611
+
612
+
613
+ class ProjectImports(importlib.abc.MetaPathFinder):
614
+ def __init__(self, root):
615
+ self.root = root
616
+
617
+ def find_spec(self, fullname, path=None, target=None):
618
+ spec = importlib.machinery.PathFinder.find_spec(fullname, path)
619
+ if spec is not None and isinstance(spec.loader, importlib.machinery.SourceFileLoader):
620
+ source = Path(spec.loader.path).resolve()
621
+ if source.is_relative_to(self.root) and ".venv" not in source.relative_to(self.root).parts:
622
+ spec.loader = ProjectSourceLoader(fullname, str(source))
623
+ return spec
624
+
625
+
626
+ def direct_harness_assignment(entrypoint):
627
+ with tokenize.open(entrypoint) as source:
628
+ tree = ast.parse(source.read(), filename=str(entrypoint))
629
+ return any(
630
+ isinstance(node, (ast.Assign, ast.AnnAssign))
631
+ and (
632
+ any(isinstance(target, ast.Name) and target.id == "agent" for target in node.targets)
633
+ if isinstance(node, ast.Assign)
634
+ else isinstance(node.target, ast.Name) and node.target.id == "agent"
635
+ )
636
+ and isinstance(node.value, ast.Call)
637
+ and isinstance(node.value.func, ast.Name)
638
+ and node.value.func.id == "create_harness"
639
+ for node in tree.body
640
+ )
641
+
642
+
643
+ def load_project(entrypoint, root):
644
+ sys.meta_path.insert(0, ProjectImports(root))
645
+ sys.path[:0] = [str(root), str(entrypoint.parent)]
646
+ relative = entrypoint.relative_to(root)
647
+ module_parts = list(relative.with_suffix("").parts)
648
+ if module_parts[-1] == "__init__":
649
+ module_parts.pop()
650
+ packaged = bool(module_parts) and all(
651
+ (root.joinpath(*module_parts[:index], "__init__.py")).is_file() for index in range(1, len(module_parts))
652
+ )
653
+ captured = []
654
+ original_create_harness = strands_harness.create_harness
655
+
656
+ def capture_create_harness(*args, **options):
657
+ agent = original_create_harness(*args, **options)
658
+ captured.append((agent, args, options))
659
+ return agent
660
+
661
+ strands_harness.create_harness = capture_create_harness
662
+ try:
663
+ if packaged:
664
+ module = importlib.import_module(".".join(module_parts))
665
+ else:
666
+ spec = importlib.util.spec_from_file_location(f"harness_project_agent_{uuid4().hex}", entrypoint)
667
+ if spec is None or spec.loader is None:
668
+ raise RuntimeError(f"Cannot load Python agent from {entrypoint}")
669
+ module = importlib.util.module_from_spec(spec)
670
+ sys.modules[spec.name] = module
671
+ spec.loader.exec_module(module)
672
+ finally:
673
+ strands_harness.create_harness = original_create_harness
674
+ agent = getattr(module, "agent", None)
675
+ if not isinstance(agent, Agent):
676
+ raise TypeError('Export a Strands Agent as "agent".')
677
+ if not callable(getattr(module, "create_agent", None)) and direct_harness_assignment(entrypoint):
678
+ construction = next(((args, options) for candidate, args, options in captured if candidate is agent), None)
679
+ if construction is not None:
680
+ args, options = construction
681
+
682
+ def create_agent(**overrides):
683
+ return original_create_harness(*args, **{**options, **overrides})
684
+
685
+ module.create_agent = create_agent
686
+ return module
687
+
688
+
689
+ async def main():
690
+ module = load_project(Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve())
691
+ command = json.loads(await asyncio.to_thread(sys.stdin.readline))
692
+ runtime = Runtime(module, command)
693
+ await runtime.build(runtime.options)
694
+ send({"type": "ready", "state": runtime.state()})
695
+ running = None
696
+ try:
697
+ while line := await asyncio.to_thread(sys.stdin.readline):
698
+ command = json.loads(line, object_hook=decode)
699
+ kind = command["type"]
700
+ if kind == "permission":
701
+ future = pending_permissions.get(command["requestId"])
702
+ if future and not future.done():
703
+ future.set_result(command["approved"])
704
+ elif kind in ("cancel", "close"):
705
+ runtime.cancel_signal.set()
706
+ if running:
707
+ running.cancel()
708
+ if kind == "close":
709
+ break
710
+ elif running and not running.done():
711
+ send({"type": "error", "message": "The Python agent is busy"})
712
+ elif kind == "prompt":
713
+ running = asyncio.create_task(runtime.turn(command["prompt"]))
714
+ else:
715
+ try:
716
+ await runtime.command(command)
717
+ except Exception as error:
718
+ send({"type": "error", "message": str(error)})
719
+ finally:
720
+ if running and not running.done():
721
+ running.cancel()
722
+ with contextlib.suppress(asyncio.CancelledError):
723
+ await running
724
+ await runtime.cleanup(runtime.agent)
725
+
726
+
727
+ try:
728
+ asyncio.run(main())
729
+ except Exception as error:
730
+ send({"type": "error", "message": str(error)})
731
+ sys.exit(1)