agentengine-sdk-python 0.8.6__py3-none-any.whl → 0.8.8__py3-none-any.whl

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 (764) hide show
  1. {agentengine_sdk_python-0.8.6.dist-info → agentengine_sdk_python-0.8.8.dist-info}/METADATA +41 -18
  2. {agentengine_sdk_python-0.8.6.dist-info → agentengine_sdk_python-0.8.8.dist-info}/RECORD +710 -526
  3. {agentengine_sdk_python-0.8.6.dist-info → agentengine_sdk_python-0.8.8.dist-info}/WHEEL +1 -1
  4. ksadk/__init__.py +2 -1
  5. ksadk/_build_provenance.json +1 -1
  6. ksadk/_mcp_compat.py +305 -0
  7. ksadk/a2a/_invocation_state.py +1 -1
  8. ksadk/a2a/adk_invocation_context.py +2 -1
  9. ksadk/a2a/adk_tools.py +19 -9
  10. ksadk/a2a/bootstrap.py +7 -6
  11. ksadk/a2a/codex.py +2 -1
  12. ksadk/a2a/control_plane.py +119 -2
  13. ksadk/a2a/executor.py +24 -7
  14. ksadk/a2a/invocation_service.py +198 -7
  15. ksadk/a2a/kernel_task_adapter.py +60 -9
  16. ksadk/a2a/langgraph_invocation_context.py +3 -2
  17. ksadk/a2a/langgraph_managed.py +17 -1
  18. ksadk/a2a/langgraph_recovery.py +43 -5
  19. ksadk/a2a/langgraph_tool_runtime.py +8 -6
  20. ksadk/a2a/langgraph_tools.py +13 -1
  21. ksadk/a2a/platform.py +8 -2
  22. ksadk/a2a/runtime_approval.py +6 -21
  23. ksadk/a2a/runtime_input.py +3 -2
  24. ksadk/a2a/timeouts.py +37 -0
  25. ksadk/a2a/tool_outcomes.py +73 -0
  26. ksadk/a2a/workload_tokens.py +21 -134
  27. ksadk/a2ui/__init__.py +4 -0
  28. ksadk/a2ui/assets/basic-v0_9_1.json +1383 -0
  29. ksadk/a2ui/assets/common-types-v0_9.json +305 -0
  30. ksadk/a2ui/assets/legacy-seven-components.json +230 -0
  31. ksadk/a2ui/assets/manifest.json +86 -0
  32. ksadk/a2ui/budget.py +54 -0
  33. ksadk/a2ui/catalog.py +64 -0
  34. ksadk/a2ui/generation.py +71 -0
  35. ksadk/a2ui/legacy.py +88 -0
  36. ksadk/a2ui/linking.py +115 -0
  37. ksadk/a2ui/payload.py +46 -0
  38. ksadk/a2ui/presentation.py +79 -0
  39. ksadk/a2ui/registry.py +166 -0
  40. ksadk/a2ui/wire.py +110 -0
  41. ksadk/agent.py +29 -0
  42. ksadk/agui/_agent_helpers.py +16 -1
  43. ksadk/agui/_agent_kernel.py +515 -0
  44. ksadk/agui/_agent_projection.py +379 -0
  45. ksadk/agui/_agent_resume.py +279 -0
  46. ksadk/agui/_agent_types.py +67 -0
  47. ksadk/agui/a2ui_projection.py +3 -1
  48. ksadk/agui/agent.py +184 -571
  49. ksadk/agui/config.py +19 -5
  50. ksadk/agui/hosted.py +343 -0
  51. ksadk/agui/request_identity.py +11 -0
  52. ksadk/agui/routes.py +79 -2
  53. ksadk/api/client.py +158 -7
  54. ksadk/builders/code_builder.py +174 -52
  55. ksadk/builders/container_builder.py +28 -7
  56. ksadk/builders/framework_requirements.py +5 -4
  57. ksadk/builders/mcp_builder.py +145 -1
  58. ksadk/builders/project_imports.py +66 -0
  59. ksadk/cli/cmd_deploy.py +5 -0
  60. ksadk/cli/cmd_invoke.py +57 -2
  61. ksadk/cli/cmd_mcp.py +1 -1
  62. ksadk/cli/cmd_run.py +2 -4
  63. ksadk/cli/cmd_studio.py +19 -3
  64. ksadk/cli/cmd_web.py +28 -56
  65. ksadk/cli/hosted_command_events.py +148 -0
  66. ksadk/cli/hosted_invoke.py +66 -14
  67. ksadk/cli/runtime_bootstrap.py +5 -1
  68. ksadk/codex/async_client.py +354 -12
  69. ksadk/codex/runtime.py +17 -2
  70. ksadk/common/cloud_headers.py +33 -6
  71. ksadk/common/diagnostics.py +15 -0
  72. ksadk/compat/adk_compat.py +2 -0
  73. ksadk/compat/adk_stream.py +35 -0
  74. ksadk/compat/copilotkit_a2ui.py +85 -21
  75. ksadk/configs/env_registry.py +102 -19
  76. ksadk/configs/env_registry_a2a.py +42 -0
  77. ksadk/conversations/a2ui_projection.py +50 -0
  78. ksadk/conversations/context.py +12 -0
  79. ksadk/conversations/message_projection.py +106 -60
  80. ksadk/conversations/message_projection_blocks.py +75 -3
  81. ksadk/conversations/message_projection_outcomes.py +81 -0
  82. ksadk/conversations/projector.py +35 -0
  83. ksadk/conversations/runtime_invocation.py +3 -0
  84. ksadk/conversations/runtime_observability.py +1 -0
  85. ksadk/conversations/runtime_projection.py +23 -1
  86. ksadk/conversations/runtime_stream_events.py +11 -7
  87. ksadk/conversations/runtime_streaming.py +21 -17
  88. ksadk/deployment/mcp.py +93 -0
  89. ksadk/deployment/providers/serverless.py +130 -4
  90. ksadk/detection/mcp_detector.py +80 -22
  91. ksadk/events/_v1_compat/projection.py +2 -0
  92. ksadk/events/adapters/_langgraph_custom.py +195 -0
  93. ksadk/events/adapters/_langgraph_model_tasks.py +59 -0
  94. ksadk/events/adapters/_langgraph_support.py +80 -29
  95. ksadk/events/adapters/_langgraph_tool_outcomes.py +71 -0
  96. ksadk/events/adapters/_langgraph_usage_origin.py +86 -0
  97. ksadk/events/adapters/adk.py +11 -0
  98. ksadk/events/adapters/langgraph.py +188 -20
  99. ksadk/events/canonical.py +23 -1
  100. ksadk/events/canonical_store.py +133 -4
  101. ksadk/events/cold_recovery.py +2 -1
  102. ksadk/events/native_checkpoint.py +10 -0
  103. ksadk/events/reducer.py +9 -9
  104. ksadk/events/run_authority.py +15 -0
  105. ksadk/events/session_event.py +61 -0
  106. ksadk/events/sse_heartbeat.py +50 -0
  107. ksadk/events/usage.py +50 -0
  108. ksadk/harness/__init__.py +3 -0
  109. ksadk/harness/app.py +1 -1
  110. ksadk/harness/artifact_adapters/native_catalog.py +92 -0
  111. ksadk/harness/artifact_adapters/native_tool.py +16 -0
  112. ksadk/harness/browser_adapters/native_playwright.py +3 -1
  113. ksadk/harness/browser_adapters/native_vision.py +2 -1
  114. ksadk/harness/engine/postgres_checkpointer.py +170 -29
  115. ksadk/harness/model_adapters/native_openai.py +3 -1
  116. ksadk/harness/native/artifact_catalog_contract.py +26 -0
  117. ksadk/harness/native/artifact_partial_read_capacity.py +6 -3
  118. ksadk/harness/native/artifact_read_capacity.py +15 -87
  119. ksadk/harness/native/artifact_runtime.py +44 -1
  120. ksadk/harness/native/artifact_search_capacity.py +20 -119
  121. ksadk/harness/native/artifact_single_read_capacity.py +7 -6
  122. ksadk/harness/native/background_command_contract.py +40 -0
  123. ksadk/harness/native/background_commands.py +101 -0
  124. ksadk/harness/native/call_budget.py +24 -0
  125. ksadk/harness/native/child_budget.py +6 -6
  126. ksadk/harness/native/child_interruption.py +3 -2
  127. ksadk/harness/native/child_media.py +105 -0
  128. ksadk/harness/native/context.py +44 -0
  129. ksadk/harness/native/context_compaction_projection.py +38 -2
  130. ksadk/harness/native/context_continuation.py +54 -0
  131. ksadk/harness/native/context_contributions.py +2 -1
  132. ksadk/harness/native/context_directory_progress.py +117 -0
  133. ksadk/harness/native/context_driver.py +136 -11
  134. ksadk/harness/native/context_partial_summary.py +2 -0
  135. ksadk/harness/native/context_partition.py +37 -1
  136. ksadk/harness/native/context_replay.py +2 -1
  137. ksadk/harness/native/context_request_projection.py +59 -6
  138. ksadk/harness/native/context_runtime.py +211 -16
  139. ksadk/harness/native/context_runtime_contracts.py +123 -1
  140. ksadk/harness/native/context_session_history.py +96 -0
  141. ksadk/harness/native/context_source_progress.py +164 -5
  142. ksadk/harness/native/context_summary_planning.py +63 -15
  143. ksadk/harness/native/context_summary_prompt.py +72 -0
  144. ksadk/harness/native/context_summary_recovery.py +3 -1
  145. ksadk/harness/native/delivery_artifacts.py +58 -0
  146. ksadk/harness/native/delivery_context.py +64 -0
  147. ksadk/harness/native/delivery_feedback.py +95 -0
  148. ksadk/harness/native/delivery_review.py +10 -10
  149. ksadk/harness/native/effect_control.py +45 -1
  150. ksadk/harness/native/effect_receipts.py +50 -3
  151. ksadk/harness/native/effect_runtime.py +10 -1
  152. ksadk/harness/native/engine.py +601 -16
  153. ksadk/harness/native/execution_budget.py +88 -0
  154. ksadk/harness/native/history.py +1 -0
  155. ksadk/harness/native/machine.py +44 -7
  156. ksadk/harness/native/model.py +17 -3
  157. ksadk/harness/native/model_runtime.py +192 -12
  158. ksadk/harness/native/model_takeover.py +4 -2
  159. ksadk/harness/native/notification_admission.py +183 -0
  160. ksadk/harness/native/ports.py +54 -6
  161. ksadk/harness/native/run_clock.py +13 -6
  162. ksadk/harness/native/state.py +100 -1
  163. ksadk/harness/native/stream_display_buffer.py +198 -0
  164. ksadk/harness/native/subagents.py +21 -0
  165. ksadk/harness/native/task_policy.py +8 -3
  166. ksadk/harness/native/tool_batch_capacity.py +152 -0
  167. ksadk/harness/native/tool_budget.py +38 -9
  168. ksadk/harness/native/tool_error_recovery.py +241 -0
  169. ksadk/harness/native/tool_error_streak.py +10 -1
  170. ksadk/harness/native/tool_progress.py +1 -0
  171. ksadk/harness/native/tool_scheduling.py +9 -10
  172. ksadk/harness/native/turn_control.py +21 -2
  173. ksadk/harness/native/verification_runtime.py +2 -1
  174. ksadk/harness/native_facade.py +180 -9
  175. ksadk/harness/native_projection.py +18 -8
  176. ksadk/harness/native_runtime.py +208 -3
  177. ksadk/harness/provider_thinking.py +63 -0
  178. ksadk/harness/public_activity.py +3 -0
  179. ksadk/harness/service_presentation.py +44 -0
  180. ksadk/harness/service_runtime.py +1038 -0
  181. ksadk/harness/skill_adapters/native_disclosure.py +13 -1
  182. ksadk/harness/skill_adapters/native_metadata.py +40 -0
  183. ksadk/harness/spec.py +6 -0
  184. ksadk/harness/stores/native_commit_history.py +373 -0
  185. ksadk/harness/stores/native_contract.py +205 -1
  186. ksadk/harness/stores/native_memory.py +363 -1
  187. ksadk/harness/stores/native_sqlite.py +572 -14
  188. ksadk/harness/stores/native_sqlite_migration.py +34 -7
  189. ksadk/harness/subagent.py +6 -1
  190. ksadk/harness/subagent_adapters/native_background_child.py +8 -7
  191. ksadk/harness/subagent_adapters/native_child.py +87 -8
  192. ksadk/harness/tool_display.py +113 -2
  193. ksadk/harness/tool_display_contract.py +34 -1
  194. ksadk/interaction/contracts.py +19 -4
  195. ksadk/interaction/display_values.py +140 -0
  196. ksadk/interaction/form_values.py +130 -0
  197. ksadk/interaction/langgraph.py +53 -0
  198. ksadk/interaction/langgraph_approval.py +59 -0
  199. ksadk/interaction/langgraph_interrupt.py +129 -0
  200. ksadk/interaction/langgraph_observer.py +125 -0
  201. ksadk/interaction/ledger.py +32 -5
  202. ksadk/interaction/native_events.py +29 -0
  203. ksadk/interaction/providers/harness.py +9 -4
  204. ksadk/interaction/providers/langgraph.py +19 -8
  205. ksadk/interaction/resolution.py +43 -0
  206. ksadk/interaction/schema.py +168 -0
  207. ksadk/interaction/submission.py +184 -0
  208. ksadk/kernel/admission_cursor.py +19 -0
  209. ksadk/kernel/bootstrap.py +344 -228
  210. ksadk/kernel/contract_fingerprints.py +5 -0
  211. ksadk/kernel/contracts.py +1 -0
  212. ksadk/kernel/control.py +67 -0
  213. ksadk/kernel/conversation_input.py +39 -0
  214. ksadk/kernel/execution_host_ingress.py +6 -3
  215. ksadk/kernel/history_projection.py +85 -4
  216. ksadk/kernel/ingress.py +89 -27
  217. ksadk/kernel/interactions_memory.py +447 -0
  218. ksadk/kernel/interactions_postgres.py +500 -0
  219. ksadk/kernel/interactions_sqlite.py +684 -0
  220. ksadk/kernel/legacy_postgres_repair.py +113 -0
  221. ksadk/kernel/local_interactions.py +172 -0
  222. ksadk/kernel/memory_store.py +137 -366
  223. ksadk/kernel/native_confirmation.py +109 -0
  224. ksadk/kernel/postgres_locks.py +23 -0
  225. ksadk/kernel/postgres_store.py +573 -511
  226. ksadk/kernel/postgres_time.py +12 -0
  227. ksadk/kernel/recovery.py +26 -1
  228. ksadk/kernel/runtime_config.py +72 -0
  229. ksadk/kernel/runtime_environment.py +301 -0
  230. ksadk/kernel/session_storage.py +144 -0
  231. ksadk/kernel/sql/002_session_retirement.sql +86 -0
  232. ksadk/kernel/sql/003_legacy_repair_queue.sql +49 -0
  233. ksadk/kernel/sql/backfill_session_namespaces.sql +59 -0
  234. ksadk/kernel/sqlite_session_cleanup.py +84 -0
  235. ksadk/kernel/sqlite_store.py +232 -622
  236. ksadk/kernel/store.py +6 -0
  237. ksadk/kernel/submission_postgres.py +99 -0
  238. ksadk/kernel/submission_sqlite.py +107 -0
  239. ksadk/kernel/teams_effects.py +3 -4
  240. ksadk/kernel/teams_execution_context.py +3 -4
  241. ksadk/kernel/worker.py +91 -202
  242. ksadk/kernel/worker_controls.py +112 -27
  243. ksadk/kernel/worker_identity.py +15 -8
  244. ksadk/kernel/worker_interactions.py +343 -47
  245. ksadk/knowledge_base/__init__.py +1 -1
  246. ksadk/knowledge_base/client.py +138 -17
  247. ksadk/knowledge_base/openclaw_bridge.py +58 -0
  248. ksadk/knowledge_base/service.py +2 -0
  249. ksadk/mcp_runtime/__init__.py +34 -15
  250. ksadk/mcp_runtime/_adk.py +14 -0
  251. ksadk/mcp_runtime/oauth/__init__.py +6 -0
  252. ksadk/mcp_runtime/oauth/_agent.py +215 -0
  253. ksadk/mcp_runtime/oauth/_durable_tools.py +208 -0
  254. ksadk/mcp_runtime/oauth/bootstrap.py +69 -0
  255. ksadk/mcp_runtime/oauth/client.py +200 -0
  256. ksadk/mcp_runtime/oauth/code_config.py +90 -0
  257. ksadk/mcp_runtime/oauth/contract.json +32 -0
  258. ksadk/mcp_runtime/oauth/contract.py +6 -0
  259. ksadk/mcp_runtime/oauth/declarations.py +106 -0
  260. ksadk/mcp_runtime/oauth/http.py +63 -0
  261. ksadk/mcp_runtime/oauth/kernel.py +717 -0
  262. ksadk/mcp_runtime/oauth/langgraph.py +434 -0
  263. ksadk/mcp_runtime/oauth/local/__init__.py +1 -0
  264. ksadk/mcp_runtime/oauth/local/broker.py +491 -0
  265. ksadk/mcp_runtime/oauth/local/checkpoint.py +17 -0
  266. ksadk/mcp_runtime/oauth/local/persistence.py +227 -0
  267. ksadk/mcp_runtime/oauth/local/protocol.py +390 -0
  268. ksadk/mcp_runtime/oauth/local/runtime.py +413 -0
  269. ksadk/mcp_runtime/oauth/local/transport.py +79 -0
  270. ksadk/mcp_runtime/oauth/runtime_io.py +43 -0
  271. ksadk/mcp_runtime/oauth/security.py +73 -0
  272. ksadk/mcp_runtime/oauth/tools.py +434 -0
  273. ksadk/mcp_runtime/oauth/transport.py +109 -0
  274. ksadk/memory/adk/backends/sdk_ltm_backend.py +21 -12
  275. ksadk/memory/adk/long_term_memory.py +1 -2
  276. ksadk/memory/openclaw_bridge.py +115 -0
  277. ksadk/memory/providers/local_postgres.py +247 -55
  278. ksadk/memory/scope_ids.py +49 -0
  279. ksadk/memory/service.py +29 -3
  280. ksadk/model_gateway/client.py +1 -1
  281. ksadk/model_proxy/compat.py +22 -0
  282. ksadk/model_proxy/transform.py +3 -4
  283. ksadk/plugins/providers/codex.py +37 -2
  284. ksadk/plugins/providers/harness.py +65 -28
  285. ksadk/plugins/providers/harness_service.py +198 -0
  286. ksadk/plugins/providers/harness_service_context.py +175 -0
  287. ksadk/plugins/providers/harness_service_hooks.py +168 -0
  288. ksadk/plugins/providers/harness_service_memory.py +479 -0
  289. ksadk/plugins/providers/harness_tools.py +39 -2
  290. ksadk/plugins/providers/platform_resources.py +2 -2
  291. ksadk/resource_runtime/contracts.py +8 -3
  292. ksadk/resource_runtime/knowledge.py +1 -1
  293. ksadk/resource_runtime/langgraph.py +7 -3
  294. ksadk/resource_runtime/managed_projection.py +24 -9
  295. ksadk/resource_runtime/mcp_server.py +3 -3
  296. ksadk/resource_runtime/worker.py +24 -5
  297. ksadk/runners/_adk_a2a_stream.py +10 -0
  298. ksadk/runners/_adk_canonical_stream.py +38 -10
  299. ksadk/runners/_adk_tunnel_history.py +96 -0
  300. ksadk/runners/_langgraph_answer_contract.py +47 -0
  301. ksadk/runners/_langgraph_canonical_stream.py +657 -0
  302. ksadk/runners/_langgraph_checkpoint_binding.py +89 -0
  303. ksadk/runners/_langgraph_factory.py +79 -0
  304. ksadk/runners/_langgraph_final_answer.py +91 -0
  305. ksadk/runners/_langgraph_fresh_turn.py +67 -0
  306. ksadk/runners/_langgraph_interactions.py +199 -0
  307. ksadk/runners/_langgraph_output.py +69 -0
  308. ksadk/runners/_langgraph_runner_streams.py +38 -75
  309. ksadk/runners/_langgraph_state_reader.py +5 -0
  310. ksadk/runners/_langgraph_wait_cancellation.py +49 -0
  311. ksadk/runners/_session_identity.py +30 -4
  312. ksadk/runners/adk_runner.py +108 -22
  313. ksadk/runners/base_runner.py +21 -0
  314. ksadk/runners/langgraph_runner.py +122 -108
  315. ksadk/runners/patch_langchain.py +4 -2
  316. ksadk/runtime/_langgraph_interaction_adapter.py +333 -0
  317. ksadk/runtime/_runner_adapter/a2ui_surface.py +194 -22
  318. ksadk/runtime/_runner_adapter/chunk_mapping.py +688 -0
  319. ksadk/runtime/_runner_adapter/resume_context.py +64 -0
  320. ksadk/runtime/_runner_adapter/stream_mapping.py +29 -597
  321. ksadk/runtime/conversation_execution.py +61 -32
  322. ksadk/runtime/executor.py +34 -1
  323. ksadk/runtime/factory.py +17 -5
  324. ksadk/runtime/framework_adapters.py +37 -2
  325. ksadk/runtime/langgraph_checkpoint_view.py +168 -0
  326. ksadk/runtime/launch.py +2 -0
  327. ksadk/runtime/preprocessing.py +9 -1
  328. ksadk/runtime/runner_adapter.py +77 -37
  329. ksadk/runtime/session_storage.py +71 -0
  330. ksadk/sandbox/backends/e2b.py +95 -13
  331. ksadk/sandbox/backends/local_process.py +68 -4
  332. ksadk/sandbox/base.py +1 -1
  333. ksadk/sandbox/diagnostics.py +31 -0
  334. ksadk/sandbox/e2b_background.py +1768 -0
  335. ksadk/sandbox/e2b_errors.py +26 -0
  336. ksadk/sandbox/local_background.py +406 -0
  337. ksadk/sandbox/local_controls.py +8 -1
  338. ksadk/server/database_access.py +369 -0
  339. ksadk/server/database_access_contract.py +222 -0
  340. ksadk/server/factory.py +180 -3
  341. ksadk/server/history_deadline.py +20 -4
  342. ksadk/server/history_page_cache.py +8 -2
  343. ksadk/server/routes/common.py +13 -1
  344. ksadk/server/routes/control.py +2 -1
  345. ksadk/server/routes/database_access.py +17 -0
  346. ksadk/server/routes/dependencies.py +28 -0
  347. ksadk/server/routes/harness_service_view.py +38 -0
  348. ksadk/server/routes/interactions.py +106 -0
  349. ksadk/server/routes/kernel_ingress.py +19 -1
  350. ksadk/server/routes/local_kernel_control.py +80 -0
  351. ksadk/server/routes/openai_compat.py +6 -0
  352. ksadk/server/routes/projection.py +159 -2
  353. ksadk/server/routes/routers.py +6 -0
  354. ksadk/server/routes/run.py +30 -1
  355. ksadk/server/routes/session_identity.py +130 -0
  356. ksadk/server/routes/sessions.py +326 -312
  357. ksadk/server/routes/streaming.py +3 -2
  358. ksadk/server/routes/ui_bootstrap.py +265 -0
  359. ksadk/server/routes/workspace.py +7 -0
  360. ksadk/server/static/a2ui/basic-v0_9_1.json +1383 -0
  361. ksadk/server/static/a2ui/common-types-v0_9.json +305 -0
  362. ksadk/server/static/a2ui/legacy-seven-components.json +230 -0
  363. ksadk/server/static/a2ui/manifest.json +86 -0
  364. ksadk/server/static/a2ui/material-icons-OFL-1.1.txt +93 -0
  365. ksadk/server/static/assets/{ArtifactsPanel-CILaW-fC.js → ArtifactsPanel-Cdr5C_vM.js} +1 -1
  366. ksadk/server/static/assets/{CodeBlock-BVrNVtJC.js → CodeBlock-BWRafud9.js} +6 -6
  367. ksadk/server/static/assets/{MathMessageMarkdown-Dp7c4wWD.js → MathMessageMarkdown-CFKeJIvy.js} +7 -7
  368. ksadk/server/static/assets/{MermaidBlock-Dxop8Rd7.js → MermaidBlock-BneAGUOd.js} +9 -9
  369. ksadk/server/static/assets/NativeTerminalPanel-BHI85zDO.js +1 -0
  370. ksadk/server/static/assets/OfficialA2uiRenderer-BOmT36lJ.js +16 -0
  371. ksadk/server/static/assets/{abnfDiagram-VCTEODGH-ckWDmOzw.js → abnfDiagram-VCTEODGH-DQvlOsBI.js} +1 -1
  372. ksadk/server/static/assets/{arc-DqxJede-.js → arc-CGx0e4pN.js} +1 -1
  373. ksadk/server/static/assets/architecture-7GRP2DOG-CFWjFkDL.js +1 -0
  374. ksadk/server/static/assets/{architectureDiagram-5GKGNRK7-SEQA4bVi.js → architectureDiagram-5GKGNRK7-WyybcNKX.js} +1 -1
  375. ksadk/server/static/assets/{blockDiagram-NRAW4CY4-pM0B-6NJ.js → blockDiagram-NRAW4CY4-C9Cx_GVs.js} +1 -1
  376. ksadk/server/static/assets/{c4Diagram-UCG6FXSJ-m2tuCNVq.js → c4Diagram-UCG6FXSJ-Bh7X3bGr.js} +1 -1
  377. ksadk/server/static/assets/channel-D6Dp_l74.js +1 -0
  378. ksadk/server/static/assets/chunk-2Q5K7J3B-CwmjhFYK.js +1 -0
  379. ksadk/server/static/assets/{chunk-5VM5RSS4-GJHDr9Ww.js → chunk-5VM5RSS4-cP9XupZj.js} +1 -1
  380. ksadk/server/static/assets/{chunk-F27PBJKO-CbAN45AV.js → chunk-F27PBJKO-Bm77fvR9.js} +1 -1
  381. ksadk/server/static/assets/{chunk-G27WJ6UU-D5ngbbzF.js → chunk-G27WJ6UU-DDKNPesQ.js} +1 -1
  382. ksadk/server/static/assets/{chunk-JWPE2WC7-Cc5IwuYC.js → chunk-JWPE2WC7-BqiUDB7s.js} +1 -1
  383. ksadk/server/static/assets/{chunk-LCL6LL3I-CprgDDdJ.js → chunk-LCL6LL3I-C528mMZy.js} +1 -1
  384. ksadk/server/static/assets/{chunk-POPQ4Y6H-CDZhSy82.js → chunk-POPQ4Y6H-CzZ9g_Uf.js} +1 -1
  385. ksadk/server/static/assets/{chunk-RHFEMEQ7-CZchUNro.js → chunk-RHFEMEQ7-CXj4tUZ-.js} +1 -1
  386. ksadk/server/static/assets/{chunk-SVP7TREG-BVruqk6T.js → chunk-SVP7TREG-BHyd85pS.js} +1 -1
  387. ksadk/server/static/assets/{chunk-XXDRQBXY-4ld9SxPN.js → chunk-XXDRQBXY-Qe29PHGe.js} +1 -1
  388. ksadk/server/static/assets/classDiagram-DTDB5LWJ-DsbvkCAV.js +1 -0
  389. ksadk/server/static/assets/classDiagram-v2-JRS7N3AN-DsbvkCAV.js +1 -0
  390. ksadk/server/static/assets/{cose-bilkent-JH36ORCC-Dmyyk_Vp.js → cose-bilkent-JH36ORCC-maRKgeec.js} +1 -1
  391. ksadk/server/static/assets/cynefin-OW5HDTMX-CBZRVuc4.js +1 -0
  392. ksadk/server/static/assets/{cynefinDiagram-5FMLGOSQ-BIyq3EJb.js → cynefinDiagram-5FMLGOSQ-CoD0bEvn.js} +1 -1
  393. ksadk/server/static/assets/{dagre-3AP2YEHR-eBw08Qdk.js → dagre-3AP2YEHR-BkpgQqyW.js} +1 -1
  394. ksadk/server/static/assets/{dagre-DfvnEf45.js → dagre-BUaTFrYa.js} +1 -1
  395. ksadk/server/static/assets/{diagram-S7CK7UJ4-CUSrE3Mg.js → diagram-S7CK7UJ4-25HdTbjE.js} +1 -1
  396. ksadk/server/static/assets/{diagram-UQ7AKVKN-Dq5Zw2gy.js → diagram-UQ7AKVKN-KO-WqOIg.js} +1 -1
  397. ksadk/server/static/assets/{diagram-VSXAHHWV-DyUHfNwT.js → diagram-VSXAHHWV-B360BkDQ.js} +1 -1
  398. ksadk/server/static/assets/{diagram-VX7I27RA-CREmM89O.js → diagram-VX7I27RA-COr1Oqsg.js} +1 -1
  399. ksadk/server/static/assets/{diagram-Z3DM3KII-Dw9zhHUK.js → diagram-Z3DM3KII-CgaKrIwB.js} +1 -1
  400. ksadk/server/static/assets/{dist-AEv-vXf-.js → dist--HftQyp9.js} +1 -1
  401. ksadk/server/static/assets/{dist-pq-nD33R.js → dist-B3Jp5r1e.js} +1 -1
  402. ksadk/server/static/assets/{dist-cxTGfdqx.js → dist-BEbS8Bag.js} +1 -1
  403. ksadk/server/static/assets/{dist-BX_-FENW.js → dist-BQ116UdZ.js} +1 -1
  404. ksadk/server/static/assets/{dist-DDSyLEOX.js → dist-BoRn8a_t.js} +1 -1
  405. ksadk/server/static/assets/{dist-BBsYarrI.js → dist-Brbrdmff.js} +1 -1
  406. ksadk/server/static/assets/{dist-B8Myiet9.js → dist-Bsuusoi0.js} +1 -1
  407. ksadk/server/static/assets/{dist-DUxO0R99.js → dist-Bxcu8Ca0.js} +1 -1
  408. ksadk/server/static/assets/{dist-CVPau3tn.js → dist-By-MVndb.js} +1 -1
  409. ksadk/server/static/assets/{dist-lOy23y43.js → dist-C9BTMVwS.js} +1 -1
  410. ksadk/server/static/assets/{dist-C_qdxcSH.js → dist-CBo9AHUv.js} +1 -1
  411. ksadk/server/static/assets/{dist-bupkyEBZ.js → dist-CR61WJFC.js} +1 -1
  412. ksadk/server/static/assets/{dist-CHpW1BHj.js → dist-CwnkOyDn.js} +1 -1
  413. ksadk/server/static/assets/{dist-0uJ4tdx6.js → dist-CxIl4t92.js} +1 -1
  414. ksadk/server/static/assets/{dist-Cp2PaOMY.js → dist-DKG0OYnk.js} +1 -1
  415. ksadk/server/static/assets/{dist-BQMrUwdI.js → dist-DSw5Ju6-.js} +1 -1
  416. ksadk/server/static/assets/{dist-hL5p1til.js → dist-DXOlCAay.js} +1 -1
  417. ksadk/server/static/assets/{dist-CD4L6ymH.js → dist-DgJ57sRe.js} +1 -1
  418. ksadk/server/static/assets/{dist-CuR5Bgme.js → dist-DmWw0IXB.js} +1 -1
  419. ksadk/server/static/assets/{dist-Co68Apq4.js → dist-DzdXSBJb.js} +1 -1
  420. ksadk/server/static/assets/{dist-B49GzZDb.js → dist-HHvdjADB.js} +1 -1
  421. ksadk/server/static/assets/{dist-QzbGrED_.js → dist-_0Xgu_07.js} +1 -1
  422. ksadk/server/static/assets/{ebnfDiagram-PWID7BFC-BS5LdNoR.js → ebnfDiagram-PWID7BFC-DogDP2db.js} +1 -1
  423. ksadk/server/static/assets/{erDiagram-SSCWMZ5O-Bv1QtiY-.js → erDiagram-SSCWMZ5O-CeBDnUjR.js} +1 -1
  424. ksadk/server/static/assets/eventmodeling-NTZA5JFV-vXZWMkpn.js +1 -0
  425. ksadk/server/static/assets/flowDiagram-A5DVABFB-5LRgzKLv.js +1 -0
  426. ksadk/server/static/assets/{ganttDiagram-EL5Y4UJY-musi-e0G.js → ganttDiagram-EL5Y4UJY-oIQL3MCp.js} +1 -1
  427. ksadk/server/static/assets/gitGraph-4MIJSDKK-BUWSkncI.js +1 -0
  428. ksadk/server/static/assets/{gitGraphDiagram-WWUBYQGX-DH37EGkG.js → gitGraphDiagram-WWUBYQGX-B7qz0cmZ.js} +1 -1
  429. ksadk/server/static/assets/index-4g1ndaxW.js +1132 -0
  430. ksadk/server/static/assets/index-DEVfafsU.css +2 -0
  431. ksadk/server/static/assets/info-A6RAGUB7-CzJ_YrOs.js +1 -0
  432. ksadk/server/static/assets/{infoDiagram-RXCK75RN-C1kEtv2y.js → infoDiagram-RXCK75RN-yQRC41Ya.js} +1 -1
  433. ksadk/server/static/assets/{ishikawaDiagram-5VMMS53U-BCNPyMka.js → ishikawaDiagram-5VMMS53U-BCu4HiwL.js} +1 -1
  434. ksadk/server/static/assets/{journeyDiagram-EYS64GPL--cDbKnjP.js → journeyDiagram-EYS64GPL-JaqmO73K.js} +1 -1
  435. ksadk/server/static/assets/{kanban-definition-3QL26DDD-R1rAVw2f.js → kanban-definition-3QL26DDD-DQo4X8NO.js} +1 -1
  436. ksadk/server/static/assets/{katex-BT-X-V7U.js → katex-t_DWylQw.js} +1 -1
  437. ksadk/server/static/assets/{linear-DTR631iG.js → linear-DWdnI35B.js} +1 -1
  438. ksadk/server/static/assets/material-icons-latin-400-normal-kAwBdRge.woff2 +0 -0
  439. ksadk/server/static/assets/{mermaid-parser.core-DfFzJhX8.js → mermaid-parser.core-BHrT2Pfe.js} +2 -2
  440. ksadk/server/static/assets/{mindmap-definition-FBJOCRG2-D4by_rmk.js → mindmap-definition-FBJOCRG2-PBVAhZYV.js} +1 -1
  441. ksadk/server/static/assets/packet-AYTQ26CC-CXoos6fx.js +1 -0
  442. ksadk/server/static/assets/{pegDiagram-XKGWAZYB-xWXPEh0c.js → pegDiagram-XKGWAZYB-CU_cLfow.js} +1 -1
  443. ksadk/server/static/assets/pie-WAS4IAKB-CjF9NoIt.js +1 -0
  444. ksadk/server/static/assets/{pieDiagram-E7YTZNPT-BudBDlCI.js → pieDiagram-E7YTZNPT-B1h0-_pW.js} +1 -1
  445. ksadk/server/static/assets/{quadrantDiagram-AXDQQJYC-DXZ0PCJF.js → quadrantDiagram-AXDQQJYC-DEMoGo5a.js} +1 -1
  446. ksadk/server/static/assets/radar-RG4KPBEZ-BQGWs9nw.js +1 -0
  447. ksadk/server/static/assets/railroad-74A4TZTK-B6znvLUK.js +1 -0
  448. ksadk/server/static/assets/railroad-abnf-HS5TGJTU-Bzquz0As.js +1 -0
  449. ksadk/server/static/assets/railroad-ebnf-LZEXJU2U-1IikGkb5.js +1 -0
  450. ksadk/server/static/assets/railroad-peg-WCYAUIDC-BKKgHzdc.js +1 -0
  451. ksadk/server/static/assets/{railroadDiagram-O6MQD6OU-BdAYRYB8.js → railroadDiagram-O6MQD6OU-BTAob2wg.js} +1 -1
  452. ksadk/server/static/assets/{requirementDiagram-EFPCY7ZU-CBBmaL70.js → requirementDiagram-EFPCY7ZU-Dl0Q2SuO.js} +1 -1
  453. ksadk/server/static/assets/{sankeyDiagram-P5KCCOFB-Doc3rdwp.js → sankeyDiagram-P5KCCOFB-DeaTWkur.js} +1 -1
  454. ksadk/server/static/assets/{sequenceDiagram-WJ2MYXX4-0J8R8hWW.js → sequenceDiagram-WJ2MYXX4-gFQYrsOd.js} +1 -1
  455. ksadk/server/static/assets/{sizeCapture-X5ZJPWSS-CfFLlWsK.js → sizeCapture-X5ZJPWSS-pGQzddMB.js} +1 -1
  456. ksadk/server/static/assets/{stateDiagram-HBIQ2CUA-jBwkjtTy.js → stateDiagram-HBIQ2CUA-DmpYOZt1.js} +1 -1
  457. ksadk/server/static/assets/stateDiagram-v2-4QOOHH4V-Dolxgkw3.js +1 -0
  458. ksadk/server/static/assets/{swimlanes-XN3QIQJK-B0WxTQf8.js → swimlanes-XN3QIQJK-BfuSAsrr.js} +1 -1
  459. ksadk/server/static/assets/swimlanesDiagram-VK2B7HYN-BuI1erYj.js +8 -0
  460. ksadk/server/static/assets/{timeline-definition-24CTP7MA-BfCT_75A.js → timeline-definition-24CTP7MA-CgJwrrxf.js} +1 -1
  461. ksadk/server/static/assets/treeView-Q6P3EWNA-DtMdDH8N.js +1 -0
  462. ksadk/server/static/assets/treemap-WGGIJYW6-VoU8QtLZ.js +1 -0
  463. ksadk/server/static/assets/{vennDiagram-4TSXK5OY-9gX1VMDC.js → vennDiagram-4TSXK5OY-CBSAgXDd.js} +1 -1
  464. ksadk/server/static/assets/wardley-WFR3VGLG-YWSRB0Zm.js +1 -0
  465. ksadk/server/static/assets/{wardleyDiagram-VM6X3IG4-sEs_BP6O.js → wardleyDiagram-VM6X3IG4-013TZ2JZ.js} +1 -1
  466. ksadk/server/static/assets/{xychartDiagram-S5SC5T6Z-Ll4jvUN9.js → xychartDiagram-S5SC5T6Z-u6Frp8xp.js} +1 -1
  467. ksadk/server/static/index.html +2 -2
  468. ksadk/server/static/ui-source.json +11 -0
  469. ksadk/sessions/_local_service_sync.py +146 -5
  470. ksadk/sessions/_postgres_schema.py +17 -0
  471. ksadk/sessions/base.py +3 -0
  472. ksadk/sessions/continuity.py +7 -1
  473. ksadk/sessions/db_budget.py +14 -12
  474. ksadk/sessions/history_budget.py +7 -0
  475. ksadk/sessions/in_memory.py +113 -4
  476. ksadk/sessions/persistence.py +73 -7
  477. ksadk/sessions/postgres_service.py +948 -8
  478. ksadk/sessions/resilience.py +16 -0
  479. ksadk/sessions/resilient.py +601 -5
  480. ksadk/sessions/topology.py +9 -2
  481. ksadk/skills/mcp_server/register.py +471 -415
  482. ksadk/skills/mcp_server/server.py +239 -217
  483. ksadk/skills/request_connection.py +188 -0
  484. ksadk/skills/runtime/backends/e2b.py +52 -12
  485. ksadk/skills/service_client.py +104 -45
  486. ksadk/studio/api.py +413 -11
  487. ksadk/studio/api_contracts.py +7 -3
  488. ksadk/studio/api_plugin_routes.py +13 -6
  489. ksadk/studio/authoring_coordinator.py +6 -1
  490. ksadk/studio/background_output.py +72 -0
  491. ksadk/studio/build_resolution.py +28 -4
  492. ksadk/studio/cloud.py +516 -7
  493. ksadk/studio/cloud_history.py +149 -0
  494. ksadk/studio/cloud_shared_web.py +32 -3
  495. ksadk/studio/compiler.py +93 -4
  496. ksadk/studio/contracts.py +376 -9
  497. ksadk/studio/dsh_application.py +17 -4
  498. ksadk/studio/execution_host.py +10 -5
  499. ksadk/studio/interaction_submission.py +7 -2
  500. ksadk/studio/mcp_runtime.py +23 -8
  501. ksadk/studio/model_chat_tools.py +22 -10
  502. ksadk/studio/model_client.py +41 -11
  503. ksadk/studio/model_wire_identity.py +24 -0
  504. ksadk/studio/native_background_command_port.py +97 -0
  505. ksadk/studio/native_background_connection.py +230 -0
  506. ksadk/studio/native_background_locator.py +272 -0
  507. ksadk/studio/native_background_ownership.py +255 -0
  508. ksadk/studio/native_background_wakeup.py +686 -0
  509. ksadk/studio/native_browser_port.py +9 -3
  510. ksadk/studio/native_child_skills.py +4 -0
  511. ksadk/studio/native_coding_template.py +287 -0
  512. ksadk/studio/native_command_policy.py +23 -0
  513. ksadk/studio/native_context_evidence.py +81 -0
  514. ksadk/studio/native_context_port.py +13 -2
  515. ksadk/studio/native_directory_observation.py +177 -0
  516. ksadk/studio/native_final_shape.py +148 -19
  517. ksadk/studio/native_mcp_disclosure.py +8 -6
  518. ksadk/studio/native_mcp_tool_port.py +3 -1
  519. ksadk/studio/native_memory_context.py +10 -8
  520. ksadk/studio/native_model_port.py +201 -43
  521. ksadk/studio/native_planning.py +43 -2
  522. ksadk/studio/native_product.py +237 -12
  523. ksadk/studio/native_project_instructions.py +267 -0
  524. ksadk/studio/native_read_budget.py +21 -3
  525. ksadk/studio/native_subagent_port.py +125 -2
  526. ksadk/studio/native_tool_port.py +255 -14
  527. ksadk/studio/native_verification_presentation.py +13 -3
  528. ksadk/studio/plugin_composition.py +8 -1
  529. ksadk/studio/plugin_kernel_adapter.py +13 -0
  530. ksadk/studio/plugin_native_activation.py +6 -4
  531. ksadk/studio/plugin_runtime.py +9 -0
  532. ksadk/studio/presentation.py +12 -0
  533. ksadk/studio/project_instruction_trust.py +54 -0
  534. ksadk/studio/repository.py +1 -1
  535. ksadk/studio/resource_catalog.py +4 -1
  536. ksadk/studio/run_activity.py +8 -0
  537. ksadk/studio/run_service.py +496 -40
  538. ksadk/studio/scheduler_assistant.py +3 -1
  539. ksadk/studio/service.py +101 -2
  540. ksadk/studio/shared_web.py +38 -12
  541. ksadk/studio/shared_web_response_events.py +32 -5
  542. ksadk/studio/static/assets/ChannelsPage-Do_mRmVu.js +8 -0
  543. ksadk/studio/static/assets/{CodeBlock-DMIf4h33-CkufcPYo.js → CodeBlock-DMIf4h33-CsO7rJKv.js} +3 -3
  544. ksadk/studio/static/assets/{ExecutionTree-v3HexvPo-Bk8wzGSy.js → ExecutionTree-v3HexvPo-BeWoMqA-.js} +1 -1
  545. ksadk/studio/static/assets/{MathMessageMarkdown-BesSeCYl-DYG1Wzbx.js → MathMessageMarkdown-BesSeCYl-CiB60plG.js} +1 -1
  546. ksadk/studio/static/assets/{MermaidBlock-H_0qzQDf-BdXtxug_.js → MermaidBlock-H_0qzQDf-oRTZUNRr.js} +3 -3
  547. ksadk/studio/static/assets/{MessageMarkdown-CwMTvgFj-BeyLyQHu.js → MessageMarkdown-CwMTvgFj-BzEmQkHH.js} +5 -5
  548. ksadk/studio/static/assets/OfficialA2uiRenderer-DI49Kpxu-BBxfdj3P.js +16 -0
  549. ksadk/studio/static/assets/{PrismRenderer-5pK6tUdb.js → PrismRenderer-CcrOV6Lf.js} +1 -1
  550. ksadk/studio/static/assets/TeamsPage-qNVYpcox.js +4 -0
  551. ksadk/studio/static/assets/{abnfDiagram-VCTEODGH-Bnb1O3tA.js → abnfDiagram-VCTEODGH-BdEjkX5G.js} +1 -1
  552. ksadk/studio/static/assets/{arc-Pry-7G1_.js → arc-4LNeT6Qr.js} +1 -1
  553. ksadk/studio/static/assets/architecture-7GRP2DOG-C6BmiLXs.js +1 -0
  554. ksadk/studio/static/assets/{architectureDiagram-5GKGNRK7-5Zn1gqJv.js → architectureDiagram-5GKGNRK7-nKXkceF2.js} +3 -3
  555. ksadk/studio/static/assets/{blockDiagram-I7D4REHJ-CLB4L11u.js → blockDiagram-I7D4REHJ-pSawBX0F.js} +1 -1
  556. ksadk/studio/static/assets/{c4Diagram-7LVT6UL2-BOma_Z_F.js → c4Diagram-7LVT6UL2-D3DGtCIa.js} +1 -1
  557. ksadk/studio/static/assets/channel-CwBcaXYb.js +1 -0
  558. ksadk/studio/static/assets/{chunk-2E4U76K2-BFf_huql.js → chunk-2E4U76K2-CfUBZPB8.js} +2 -2
  559. ksadk/studio/static/assets/chunk-2Q5K7J3B-B9fZb2AW.js +1 -0
  560. ksadk/studio/static/assets/{chunk-2ZTRR5NV-C2qZJila.js → chunk-2ZTRR5NV-63jTqPgP.js} +1 -1
  561. ksadk/studio/static/assets/{chunk-3Z5EZCMW-DMniOlPd.js → chunk-3Z5EZCMW-CLzTC-ds.js} +1 -1
  562. ksadk/studio/static/assets/{chunk-4HAMMTFA-DVtDP4rm.js → chunk-4HAMMTFA--k1euiK8.js} +3 -3
  563. ksadk/studio/static/assets/{chunk-5V3GS4D5-i-ZDOEnP.js → chunk-5V3GS4D5--NT8dMSC.js} +1 -1
  564. ksadk/studio/static/assets/{chunk-5VM5RSS4-ZNzvKenW.js → chunk-5VM5RSS4-B4EX-xPG.js} +2 -2
  565. ksadk/studio/static/assets/{chunk-6AZGARVD-BB6FqMl-.js → chunk-6AZGARVD-BxyCuIKr.js} +1 -1
  566. ksadk/studio/static/assets/{chunk-6EIED4P4-DdUJkP0f.js → chunk-6EIED4P4-BqAnqs6L.js} +1 -1
  567. ksadk/studio/static/assets/{chunk-6K3QC6MW-CqVsVn-y.js → chunk-6K3QC6MW-DqKCc1_c.js} +1 -1
  568. ksadk/studio/static/assets/{chunk-6TQVIW2G-DKlLbNIP.js → chunk-6TQVIW2G-NQp6TssR.js} +1 -1
  569. ksadk/studio/static/assets/{chunk-747NJXEK-BFkZPlab.js → chunk-747NJXEK-CFf3ol0D.js} +1 -1
  570. ksadk/studio/static/assets/{chunk-75Z2AOVW-BZNhM4vB.js → chunk-75Z2AOVW-DpzsVI3p.js} +1 -1
  571. ksadk/studio/static/assets/chunk-CLGD4ZFX-BiEFihjn.js +1 -0
  572. ksadk/studio/static/assets/{chunk-DU6HZSFF-CpEZCUgg.js → chunk-DU6HZSFF-HbWKkMwX.js} +3 -3
  573. ksadk/studio/static/assets/{chunk-F27PBJKO-D7pvKf0C.js → chunk-F27PBJKO-BY9pwz0W.js} +1 -1
  574. ksadk/studio/static/assets/{chunk-FOHPRMQF-DHwB1DNv.js → chunk-FOHPRMQF-BAABtQ6R.js} +5 -5
  575. ksadk/studio/static/assets/{chunk-GMAD6QVW-DE_8H717.js → chunk-GMAD6QVW-C-Lw1ag9.js} +1 -1
  576. ksadk/studio/static/assets/{chunk-GVQU2GXP-BfEB0lNv.js → chunk-GVQU2GXP-CCUMaVF8.js} +1 -1
  577. ksadk/studio/static/assets/{chunk-I5DQTOEV-Hm2LfiYI.js → chunk-I5DQTOEV-DpUJ7zEH.js} +1 -1
  578. ksadk/studio/static/assets/{chunk-ICYGCRZG-749o-pGJ.js → chunk-ICYGCRZG-CknVx2uG.js} +1 -1
  579. ksadk/studio/static/assets/{chunk-IH6LHLGP-CC6I9F3i.js → chunk-IH6LHLGP-BJ6nT6RF.js} +1 -1
  580. ksadk/studio/static/assets/{chunk-IMKFNOWR-D38axYOR.js → chunk-IMKFNOWR-CTelL5KO.js} +1 -1
  581. ksadk/studio/static/assets/{chunk-JWPE2WC7-DVXcaiue.js → chunk-JWPE2WC7-CMg2kMrr.js} +1 -1
  582. ksadk/studio/static/assets/{chunk-KI3K4JFJ-Rma-0k_M.js → chunk-KI3K4JFJ-B1SKa0PC.js} +1 -1
  583. ksadk/studio/static/assets/{chunk-L3NEJ4N5-Dq5xn7aL.js → chunk-L3NEJ4N5-C8A22muD.js} +1 -1
  584. ksadk/studio/static/assets/{chunk-LNGE3PJU-DWpGwHrW.js → chunk-LNGE3PJU-D_NJe87O.js} +1 -1
  585. ksadk/studio/static/assets/{chunk-OSK3NFVY-DiCQjx9b.js → chunk-OSK3NFVY-DFHvKoNt.js} +1 -1
  586. ksadk/studio/static/assets/{chunk-OUJLGHUK-D0j2JRSg.js → chunk-OUJLGHUK-DkHSrVKj.js} +1 -1
  587. ksadk/studio/static/assets/{chunk-P2QGCYS3-VdhKmfYq.js → chunk-P2QGCYS3-C3nH7MEr.js} +1 -1
  588. ksadk/studio/static/assets/{chunk-POPQ4Y6H-C1_rzO5M.js → chunk-POPQ4Y6H-CLm6A2JW.js} +1 -1
  589. ksadk/studio/static/assets/{chunk-PWAF6VOD-B45HvflI.js → chunk-PWAF6VOD-BmVQq92D.js} +1 -1
  590. ksadk/studio/static/assets/{chunk-SHT3W25Y-DsCFnRVE.js → chunk-SHT3W25Y-cETj_Yg7.js} +1 -1
  591. ksadk/studio/static/assets/{chunk-SVP7TREG-DljApgRX.js → chunk-SVP7TREG-hm4Ur8KN.js} +1 -1
  592. ksadk/studio/static/assets/{chunk-TICWLB2K-DWqRtyqa.js → chunk-TICWLB2K-BuVjFGjc.js} +1 -1
  593. ksadk/studio/static/assets/{chunk-TLUHSLCS-DUeGgnD5.js → chunk-TLUHSLCS-7mZ4xr0q.js} +2 -2
  594. ksadk/studio/static/assets/{chunk-UY3FDG6J-CnmaAkG5.js → chunk-UY3FDG6J-2nV2i5mW.js} +1 -1
  595. ksadk/studio/static/assets/{chunk-XHIXRSVI-BFQ6B8BE.js → chunk-XHIXRSVI-BIR36bKX.js} +1 -1
  596. ksadk/studio/static/assets/chunk-XXDRQBXY-rafYnJzG.js +1 -0
  597. ksadk/studio/static/assets/classDiagram-ZZMXUADV-DdyoXyMk.js +1 -0
  598. ksadk/studio/static/assets/classDiagram-v2-VYDZK3BY-DdyoXyMk.js +1 -0
  599. ksadk/studio/static/assets/{cose-bilkent-JH36ORCC-om8AY0Mc.js → cose-bilkent-JH36ORCC-B9Ubz7rk.js} +1 -1
  600. ksadk/studio/static/assets/{createLucideIcon-DR0LGTP5.js → createLucideIcon-CTD6_IjT.js} +1 -1
  601. ksadk/studio/static/assets/cynefin-OW5HDTMX-BVS4hy6V.js +1 -0
  602. ksadk/studio/static/assets/{cynefinDiagram-5FMLGOSQ-6BrmK52S.js → cynefinDiagram-5FMLGOSQ-CKrgw1wI.js} +1 -1
  603. ksadk/studio/static/assets/{cytoscape.esm-CGd-uY3x.js → cytoscape.esm-Jip0ihto.js} +16 -16
  604. ksadk/studio/static/assets/{dagre-GXQ25YYZ-buZBRlwz.js → dagre-GXQ25YYZ-NjDjs3Kl.js} +1 -1
  605. ksadk/studio/static/assets/{dagre-PrKaheQc.js → dagre-YnTFOVV4.js} +1 -1
  606. ksadk/studio/static/assets/{diagram-S7CK7UJ4-C6aH78c4.js → diagram-S7CK7UJ4-C6X87QRZ.js} +1 -1
  607. ksadk/studio/static/assets/{diagram-UQ7AKVKN-DY_tQ6C_.js → diagram-UQ7AKVKN-Xf2JVuyK.js} +1 -1
  608. ksadk/studio/static/assets/{diagram-VSXAHHWV-DX9p5cQT.js → diagram-VSXAHHWV-CUZlU7Dr.js} +1 -1
  609. ksadk/studio/static/assets/{diagram-VX7I27RA-DB2WSH8X.js → diagram-VX7I27RA-BOcfFxfe.js} +1 -1
  610. ksadk/studio/static/assets/{diagram-Z3DM3KII-Ce1BJwHE.js → diagram-Z3DM3KII-1zrr7ezR.js} +1 -1
  611. ksadk/studio/static/assets/{dist-v5Q1xZ2K.js → dist-Brlz61T5.js} +1 -1
  612. ksadk/studio/static/assets/{ebnfDiagram-PWID7BFC-Daukxwqf.js → ebnfDiagram-PWID7BFC-C1LymnKg.js} +1 -1
  613. ksadk/studio/static/assets/{erDiagram-RLTQ6QDP-CGthTMmJ.js → erDiagram-RLTQ6QDP-Dm0YWPea.js} +1 -1
  614. ksadk/studio/static/assets/eventmodeling-NTZA5JFV-D9gMNzTL.js +1 -0
  615. ksadk/studio/static/assets/flowDiagram-HODETNUW-NYJgBJQu.js +1 -0
  616. ksadk/studio/static/assets/{ganttDiagram-EL5Y4UJY-BfoAZW9X.js → ganttDiagram-EL5Y4UJY-uJ27IKEw.js} +1 -1
  617. ksadk/studio/static/assets/gitGraph-4MIJSDKK-DQVCMicu.js +1 -0
  618. ksadk/studio/static/assets/{gitGraphDiagram-WWUBYQGX-S985OIJF.js → gitGraphDiagram-WWUBYQGX-mtpvi7ne.js} +3 -3
  619. ksadk/studio/static/assets/index-Cp9Unfkn.css +2 -0
  620. ksadk/studio/static/assets/index-HepnaEeR.js +1152 -0
  621. ksadk/studio/static/assets/{index.dom-BQenBtFm.js → index.dom-DSf_jcX2.js} +1 -1
  622. ksadk/studio/static/assets/info-A6RAGUB7-CMrsF9SP.js +1 -0
  623. ksadk/studio/static/assets/{infoDiagram-27XIBGKW-CO3W8tFn.js → infoDiagram-27XIBGKW-Hqrd2vbU.js} +1 -1
  624. ksadk/studio/static/assets/{ishikawaDiagram-5VMMS53U-BUGEl8cO.js → ishikawaDiagram-5VMMS53U-BB7nm3Dk.js} +1 -1
  625. ksadk/studio/static/assets/{journeyDiagram-3NMN7TZE-Ch2ZYxvr.js → journeyDiagram-3NMN7TZE-BXbRt7Ps.js} +1 -1
  626. ksadk/studio/static/assets/{kanban-definition-UXKFOSKX-Da-Fp4vC.js → kanban-definition-UXKFOSKX-2EtAxRbw.js} +1 -1
  627. ksadk/studio/static/assets/{katex-DhON-x74.js → katex-K_8DQ5UN.js} +1 -1
  628. ksadk/studio/static/assets/{line-BDaeq300.js → line-C4h80pWP.js} +1 -1
  629. ksadk/studio/static/assets/{linear-DmucvK78.js → linear-DCteYK3U.js} +1 -1
  630. ksadk/studio/static/assets/{mermaid-parser.core-Cj5mYdBi.js → mermaid-parser.core-TWhr-wg2.js} +2 -2
  631. ksadk/studio/static/assets/{mindmap-definition-YA3MSWOX-CvlsVQ38.js → mindmap-definition-YA3MSWOX-BC7jpEOt.js} +1 -1
  632. ksadk/studio/static/assets/{ordinal-BDEzSJ7C.js → ordinal-BXUrfsNY.js} +1 -1
  633. ksadk/studio/static/assets/packet-AYTQ26CC-BdMfjW7Z.js +1 -0
  634. ksadk/studio/static/assets/{pegDiagram-XKGWAZYB-BuHuNgT5.js → pegDiagram-XKGWAZYB-C-ZzWopk.js} +1 -1
  635. ksadk/studio/static/assets/pie-WAS4IAKB-B06bKgAM.js +1 -0
  636. ksadk/studio/static/assets/{pieDiagram-E7YTZNPT-DlrWiSOv.js → pieDiagram-E7YTZNPT-DGDL1XJp.js} +1 -1
  637. ksadk/studio/static/assets/{quadrantDiagram-AXDQQJYC-BA3hpUZM.js → quadrantDiagram-AXDQQJYC-DAPa64vy.js} +1 -1
  638. ksadk/studio/static/assets/radar-RG4KPBEZ-4lhecdYg.js +1 -0
  639. ksadk/studio/static/assets/railroad-74A4TZTK-CBTdV2Xq.js +1 -0
  640. ksadk/studio/static/assets/railroad-abnf-HS5TGJTU-D4HzgxJY.js +1 -0
  641. ksadk/studio/static/assets/railroad-ebnf-LZEXJU2U-D-qRzoh8.js +1 -0
  642. ksadk/studio/static/assets/railroad-peg-WCYAUIDC-DYA99dLv.js +1 -0
  643. ksadk/studio/static/assets/{railroadDiagram-O6MQD6OU-BxpAazym.js → railroadDiagram-O6MQD6OU-CkH0b7UT.js} +1 -1
  644. ksadk/studio/static/assets/{react-vendor-BNmTiJ-I.js → react-vendor-CTyAWUMQ.js} +1 -1
  645. ksadk/studio/static/assets/{requirementDiagram-BXWQKSXE-E-Ge0FcV.js → requirementDiagram-BXWQKSXE-BgZ0H8ni.js} +2 -2
  646. ksadk/studio/static/assets/rolldown-runtime-cO0ylGnt.js +1 -0
  647. ksadk/studio/static/assets/{sankeyDiagram-P5KCCOFB-CA6YKhQ3.js → sankeyDiagram-P5KCCOFB-BgqqGK6v.js} +1 -1
  648. ksadk/studio/static/assets/{sequenceDiagram-WJ2MYXX4-CcElXGg4.js → sequenceDiagram-WJ2MYXX4-CbQE1ava.js} +1 -1
  649. ksadk/studio/static/assets/{sizeCapture-INFHLROL-B0uUizjq.js → sizeCapture-INFHLROL-BtEJ4_JN.js} +1 -1
  650. ksadk/studio/static/assets/{src-B6xuSHsQ.js → src-DSHesKRm.js} +1 -1
  651. ksadk/studio/static/assets/{stateDiagram-D77RDMKH-DdXZOFqY.js → stateDiagram-D77RDMKH-D9uG2y8U.js} +1 -1
  652. ksadk/studio/static/assets/stateDiagram-v2-MP3YSRHH-2pITMnQn.js +1 -0
  653. ksadk/studio/static/assets/{swimlanes-42K2YHIH-NtgEEHLY.js → swimlanes-42K2YHIH-B0QgwqLd.js} +1 -1
  654. ksadk/studio/static/assets/swimlanesDiagram-VR7AAH4N-TXD08-JZ.js +8 -0
  655. ksadk/studio/static/assets/{timeline-definition-24CTP7MA-CIuYhNy3.js → timeline-definition-24CTP7MA-tbRyDWb4.js} +1 -1
  656. ksadk/studio/static/assets/treeView-Q6P3EWNA-NawrivXx.js +1 -0
  657. ksadk/studio/static/assets/treemap-WGGIJYW6-DabVcIU4.js +1 -0
  658. ksadk/studio/static/assets/{vennDiagram-4TSXK5OY-7HbApbrv.js → vennDiagram-4TSXK5OY-Xjhys4e4.js} +1 -1
  659. ksadk/studio/static/assets/wardley-WFR3VGLG-BrU5uhdd.js +1 -0
  660. ksadk/studio/static/assets/{wardleyDiagram-VM6X3IG4-CMJiaedy.js → wardleyDiagram-VM6X3IG4--sd605zd.js} +1 -1
  661. ksadk/studio/static/assets/{xychartDiagram-S5SC5T6Z-BdgtMvW2.js → xychartDiagram-S5SC5T6Z-B3XzcsnZ.js} +1 -1
  662. ksadk/studio/static/index.html +9 -9
  663. ksadk/studio/static/ui-source.json +11 -0
  664. ksadk/studio/teams_installation.py +1 -1
  665. ksadk/studio/templates.py +33 -3
  666. ksadk/toolsets/__init__.py +14 -1
  667. ksadk/toolsets/sandbox.py +303 -7
  668. ksadk/toolsets/workspace.py +17 -10
  669. ksadk/toolsets/workspace_editing.py +40 -0
  670. ksadk/toolsets/workspace_model_observation.py +6 -1
  671. ksadk/tracing/__init__.py +10 -1
  672. ksadk/tracing/routed.py +416 -0
  673. ksadk/tracing/setup.py +111 -6
  674. ksadk/tunnel/__init__.py +37 -0
  675. ksadk/tunnel/connector.py +384 -0
  676. ksadk/tunnel/discovery.py +107 -0
  677. ksadk/tunnel/failure.py +168 -0
  678. ksadk/tunnel/http_tools.py +100 -0
  679. ksadk/tunnel/langgraph.py +125 -0
  680. ksadk/tunnel/middleware.py +28 -0
  681. ksadk/tunnel/peers.py +872 -0
  682. ksadk/tunnel/protocol.py +97 -0
  683. ksadk/tunnel/registry.py +306 -0
  684. ksadk/tunnel/runtime.py +147 -0
  685. ksadk/tunnel/server.py +201 -0
  686. ksadk/tunnel/services.py +366 -0
  687. ksadk/tunnel/toolset.py +78 -0
  688. ksadk/version.py +1 -1
  689. ksadk_runtime_common/memory_backend/manifest.py +1 -1
  690. ksadk_runtime_common/memory_backend/providers/ksmem.py +60 -0
  691. ksadk_runtime_common/memory_backend/providers/lancedb.py +1 -2
  692. ksadk_runtime_common/memory_backend/providers/mem0.py +21 -0
  693. ksadk_runtime_common/memory_backend/registry.py +2 -0
  694. ksadk_runtime_common/memory_backend/render.py +1 -1
  695. ksadk_runtime_common/schemas/memory_backend_manifest.schema.json +37 -12
  696. ksadk_runtime_common/schemas/runtime_event_v2.json +2 -1
  697. ksadk/server/static/assets/NativeTerminalPanel-Cjjz8B30.js +0 -1
  698. ksadk/server/static/assets/architecture-7GRP2DOG-pn_DuLy6.js +0 -1
  699. ksadk/server/static/assets/channel-fySsnkft.js +0 -1
  700. ksadk/server/static/assets/chunk-2Q5K7J3B-BheGxKRQ.js +0 -1
  701. ksadk/server/static/assets/classDiagram-DTDB5LWJ-DSfLtNYm.js +0 -1
  702. ksadk/server/static/assets/classDiagram-v2-JRS7N3AN-DSfLtNYm.js +0 -1
  703. ksadk/server/static/assets/cynefin-OW5HDTMX-PFWIGtvA.js +0 -1
  704. ksadk/server/static/assets/eventmodeling-NTZA5JFV-DsM4upQX.js +0 -1
  705. ksadk/server/static/assets/flowDiagram-A5DVABFB-D5NA16k9.js +0 -1
  706. ksadk/server/static/assets/gitGraph-4MIJSDKK-DUCVz-ih.js +0 -1
  707. ksadk/server/static/assets/index-CZdkAvsv.js +0 -244
  708. ksadk/server/static/assets/index-CvXdHgF3.css +0 -2
  709. ksadk/server/static/assets/info-A6RAGUB7-rw0ZNHZp.js +0 -1
  710. ksadk/server/static/assets/packet-AYTQ26CC-Ca4Hvki9.js +0 -1
  711. ksadk/server/static/assets/pie-WAS4IAKB-hwiz6fbw.js +0 -1
  712. ksadk/server/static/assets/radar-RG4KPBEZ-BR1oZXLM.js +0 -1
  713. ksadk/server/static/assets/railroad-74A4TZTK-DfgEISfX.js +0 -1
  714. ksadk/server/static/assets/railroad-abnf-HS5TGJTU-CWOC3rdk.js +0 -1
  715. ksadk/server/static/assets/railroad-ebnf-LZEXJU2U-CiRvHCLY.js +0 -1
  716. ksadk/server/static/assets/railroad-peg-WCYAUIDC-DSDDyJ2f.js +0 -1
  717. ksadk/server/static/assets/stateDiagram-v2-4QOOHH4V-Cw1fPb5w.js +0 -1
  718. ksadk/server/static/assets/swimlanesDiagram-VK2B7HYN-Cc3JMBAF.js +0 -8
  719. ksadk/server/static/assets/treeView-Q6P3EWNA-C05SJHxo.js +0 -1
  720. ksadk/server/static/assets/treemap-WGGIJYW6-BqNLAhc3.js +0 -1
  721. ksadk/server/static/assets/wardley-WFR3VGLG-DokNktqB.js +0 -1
  722. ksadk/studio/static/assets/ChannelsPage-xX5HlMId.js +0 -8
  723. ksadk/studio/static/assets/TeamsPage-CCaaGaVp.js +0 -3
  724. ksadk/studio/static/assets/architecture-7GRP2DOG-BMOPAkUC.js +0 -1
  725. ksadk/studio/static/assets/channel-r8itPEik.js +0 -1
  726. ksadk/studio/static/assets/chunk-2Q5K7J3B-C1jixKkw.js +0 -1
  727. ksadk/studio/static/assets/chunk-CLGD4ZFX-D-GTtyKs.js +0 -1
  728. ksadk/studio/static/assets/chunk-XXDRQBXY-DqAYeljN.js +0 -1
  729. ksadk/studio/static/assets/classDiagram-ZZMXUADV-DjeMNJmu.js +0 -1
  730. ksadk/studio/static/assets/classDiagram-v2-VYDZK3BY-DjeMNJmu.js +0 -1
  731. ksadk/studio/static/assets/cynefin-OW5HDTMX-7tP7QfM3.js +0 -1
  732. ksadk/studio/static/assets/eventmodeling-NTZA5JFV-BR2FzK4R.js +0 -1
  733. ksadk/studio/static/assets/flowDiagram-HODETNUW-CZ1tEenp.js +0 -1
  734. ksadk/studio/static/assets/gitGraph-4MIJSDKK-DYlXv_yJ.js +0 -1
  735. ksadk/studio/static/assets/index-C7DNDik2.css +0 -2
  736. ksadk/studio/static/assets/index-Cy68gTlH.js +0 -265
  737. ksadk/studio/static/assets/info-A6RAGUB7-BlU-8_xu.js +0 -1
  738. ksadk/studio/static/assets/packet-AYTQ26CC-BSJEH9Lb.js +0 -1
  739. ksadk/studio/static/assets/pie-WAS4IAKB-qxv01Y8W.js +0 -1
  740. ksadk/studio/static/assets/radar-RG4KPBEZ-B6h6pWOs.js +0 -1
  741. ksadk/studio/static/assets/railroad-74A4TZTK-CGtTWdGc.js +0 -1
  742. ksadk/studio/static/assets/railroad-abnf-HS5TGJTU-Cq7y22IA.js +0 -1
  743. ksadk/studio/static/assets/railroad-ebnf-LZEXJU2U-V0aQVv9m.js +0 -1
  744. ksadk/studio/static/assets/railroad-peg-WCYAUIDC-BQiIsX_p.js +0 -1
  745. ksadk/studio/static/assets/rolldown-runtime-hePW80VL.js +0 -1
  746. ksadk/studio/static/assets/stateDiagram-v2-MP3YSRHH-CJbOM-QK.js +0 -1
  747. ksadk/studio/static/assets/swimlanesDiagram-VR7AAH4N-D-AVlW8B.js +0 -8
  748. ksadk/studio/static/assets/treeView-Q6P3EWNA-BTTYcvrF.js +0 -1
  749. ksadk/studio/static/assets/treemap-WGGIJYW6-Cg7tyfH8.js +0 -1
  750. ksadk/studio/static/assets/wardley-WFR3VGLG-C6N1rULY.js +0 -1
  751. {agentengine_sdk_python-0.8.6.dist-info → agentengine_sdk_python-0.8.8.dist-info}/entry_points.txt +0 -0
  752. {agentengine_sdk_python-0.8.6.dist-info → agentengine_sdk_python-0.8.8.dist-info}/licenses/LICENSE +0 -0
  753. {agentengine_sdk_python-0.8.6.dist-info → agentengine_sdk_python-0.8.8.dist-info}/top_level.txt +0 -0
  754. /ksadk/studio/static/assets/{array-BifhSqXX.js → array-mTkv7xdZ.js} +0 -0
  755. /ksadk/studio/static/assets/{chunk-Y2CYZVJY-DsF7k-Jl.js → chunk-Y2CYZVJY-C72YQVBQ.js} +0 -0
  756. /ksadk/studio/static/assets/{clsx-DB0hHKMi.js → clsx-BE-4uLAX.js} +0 -0
  757. /ksadk/studio/static/assets/{defaultLocale-BFoDCU3G.js → defaultLocale-YBltSZ3l.js} +0 -0
  758. /ksadk/studio/static/assets/{graphlib-DS17s2tU.js → graphlib-CYZB3_li.js} +0 -0
  759. /ksadk/studio/static/assets/{init-C-OQMol4.js → init-Ccnd9r3c.js} +0 -0
  760. /ksadk/studio/static/assets/{path-fybaL0A-.js → path-BfzAkHoX.js} +0 -0
  761. /ksadk/studio/static/assets/{preload-helper-CO68xz6u.js → preload-helper-2TpOpXko.js} +0 -0
  762. /ksadk/studio/static/assets/{presentation-yYw7xK60-BmcZriri.js → presentation-yYw7xK60-B7PYgYAE.js} +0 -0
  763. /ksadk/studio/static/assets/{rolldown-runtime-Dy4uBu1J-DK3Fl9T5.js → rolldown-runtime-Dy4uBu1J-CmRlGT1x.js} +0 -0
  764. /ksadk/studio/static/assets/{rough.esm-Dy-Kn_BL.js → rough.esm-BF6Sy8cM.js} +0 -0
@@ -0,0 +1,1768 @@
1
+ """Host-owned durable background commands for the E2B sandbox backend.
2
+
3
+ This mirrors ``ksadk.sandbox.local_background``: a host-owned, file-backed
4
+ command store keyed by session owner, idempotent startup, UTF-8 output cursors,
5
+ cooperative cancellation and truthful unknown-outcome handling.
6
+
7
+ Durability is cross-process. Each command is owned by a **detached supervisor
8
+ subprocess** (``start_new_session=True``) that holds the remote E2B command's
9
+ event stream and appends output to host files. The supervisor survives the
10
+ tool/host process being killed; a new host process reads the same files and
11
+ checks the supervisor's cross-process lock for liveness. The persistent E2B
12
+ sandbox is owned by the supervisor and is **never** registered with the
13
+ disposable ``SandboxRegistry`` and **never** killed on atexit — killing it on
14
+ a normal exit would destroy commands awaiting recovery. Cleanup is an
15
+ explicit host action (``E2BCommandStore.close``); a host that dies without
16
+ cleaning up leaves the sandbox to the remote TTL (documented limitation).
17
+
18
+ The remote E2B command outlives any single client. The current implementation
19
+ and test stream (local_subprocess reconnect returns an empty stream) do not
20
+ prove that a disconnect gap is recoverable; the outcome is conservatively
21
+ reported as ``unknown`` when evidence is incomplete. The real deployed
22
+ service's replay semantics for commands.connect(pid) are not verified (e2b
23
+ 2.21.1 only confirms ConnectRequest has no explicit output cursor; the envd
24
+ DataEvent.Fork replay behavior was not traced). Output already captured to
25
+ host files is preserved across reconnect; the gap, if any, is acknowledged
26
+ via ``evidence_incomplete`` and ``observed_exit_code`` rather than claimed
27
+ complete.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import codecs
33
+ import fcntl
34
+ import hashlib
35
+ import json
36
+ import logging
37
+ import os
38
+ import select
39
+ import signal
40
+ import subprocess
41
+ import sys
42
+ import threading
43
+ import time
44
+ from collections.abc import Callable
45
+ from dataclasses import dataclass
46
+ from pathlib import Path
47
+ from typing import TYPE_CHECKING, Any, Iterator, Protocol
48
+ from uuid import uuid4
49
+
50
+ from ksadk.sandbox.base import SandboxCommandResult, SandboxError
51
+
52
+ if TYPE_CHECKING:
53
+ from ksadk.studio.native_background_connection import BackgroundHostDeclaration
54
+
55
+ logger = logging.getLogger(__name__)
56
+
57
+ _TERMINAL = {"completed", "failed", "cancelled", "timed_out", "output_limit", "unknown"}
58
+ _COMMAND_ID = __import__("re").compile(r"[a-f0-9]{64}\Z")
59
+ # A recovery reservation is durable but not permanent: if the claiming host
60
+ # crashes before its supervisor takes over (or the spawn fails), a new host may
61
+ # reclaim after this TTL so an orphaned claim cannot block recovery forever.
62
+ _RECOVERY_CLAIM_TTL_SECONDS = 30.0
63
+
64
+ # ---------------------------------------------------------------------------
65
+ # File helpers (shared shape with local_background; duplicated to keep this
66
+ # module self-contained for the detached supervisor subprocess).
67
+ # ---------------------------------------------------------------------------
68
+
69
+
70
+ def _private_directory(path: Path) -> None:
71
+ for part in (path, *path.parents):
72
+ if part.is_symlink():
73
+ raise SandboxError("Background command state cannot follow symbolic links")
74
+ path.mkdir(mode=0o700, parents=True, exist_ok=True)
75
+ os.chmod(path, 0o700)
76
+
77
+
78
+ def _open_private(path: Path, flags: int) -> int:
79
+ return os.open(path, flags | os.O_NOFOLLOW, 0o600)
80
+
81
+
82
+ def _atomic_json(path: Path, value: dict[str, Any]) -> None:
83
+ temporary = path.with_name(f".{path.name}.{uuid4().hex}")
84
+ try:
85
+ with os.fdopen(_open_private(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL), "w") as out:
86
+ json.dump(value, out, sort_keys=True)
87
+ out.flush()
88
+ os.fsync(out.fileno())
89
+ os.replace(temporary, path)
90
+ directory = os.open(path.parent, os.O_RDONLY)
91
+ try:
92
+ os.fsync(directory)
93
+ finally:
94
+ os.close(directory)
95
+ finally:
96
+ temporary.unlink(missing_ok=True)
97
+
98
+
99
+ def _json(path: Path) -> dict[str, Any]:
100
+ with os.fdopen(_open_private(path, os.O_RDONLY), "r") as source:
101
+ result = json.load(source)
102
+ if not isinstance(result, dict):
103
+ raise SandboxError("Invalid background command record")
104
+ return result
105
+
106
+
107
+ def _read_window(path: Path, cursor: int, max_bytes: int) -> tuple[str, int]:
108
+ if type(cursor) is not int or cursor < 0:
109
+ raise SandboxError("Command output cursor must be a non-negative byte offset")
110
+ with os.fdopen(_open_private(path, os.O_RDONLY), "rb") as source:
111
+ size = os.fstat(source.fileno()).st_size
112
+ if cursor > size:
113
+ raise SandboxError("Command output cursor exceeds retained output")
114
+ source.seek(cursor)
115
+ data = source.read(max_bytes)
116
+ decoder = codecs.getincrementaldecoder("utf-8")("strict")
117
+ try:
118
+ text = decoder.decode(data, final=False)
119
+ except UnicodeDecodeError as exc:
120
+ raise SandboxError("Command output cursor is not a UTF-8 boundary") from exc
121
+ pending, _ = decoder.getstate()
122
+ return text, cursor + len(data) - len(pending)
123
+
124
+
125
+ def _read_window_all(path: Path) -> tuple[str, int]:
126
+ with os.fdopen(_open_private(path, os.O_RDONLY), "rb") as source:
127
+ data = source.read()
128
+ return data.decode("utf-8"), len(data)
129
+
130
+
131
+ # ---------------------------------------------------------------------------
132
+ # Command handle (read path) — cross-process liveness via supervisor.lock flock.
133
+ # ---------------------------------------------------------------------------
134
+
135
+
136
+ @dataclass(frozen=True)
137
+ class CommandOutput:
138
+ status: str
139
+ stdout: str
140
+ stderr: str
141
+ stdout_cursor: int
142
+ stderr_cursor: int
143
+ exit_code: int | None
144
+ cancel_requested: bool = False
145
+ # Exposed so the observer/HTTP can report that a reconnect gap left the
146
+ # outcome with incomplete evidence, and what exit code was observed but
147
+ # could not be trusted as complete.
148
+ evidence_incomplete: bool = False
149
+ observed_exit_code: int | None = None
150
+ outcome_reason: str = ""
151
+
152
+
153
+ class BackgroundStream(Protocol):
154
+ """Supervisor transport: iteration, observed terminal result and disconnect."""
155
+
156
+ @property
157
+ def result(self) -> Any: ...
158
+
159
+ def __iter__(self) -> Iterator[tuple[str, str, str]]: ...
160
+
161
+ def disconnect(self) -> None: ...
162
+
163
+
164
+ class _StreamAdapter:
165
+ """Confine the E2B SDK's private result slot to one transport adapter."""
166
+
167
+ def __init__(self, stream: Any) -> None:
168
+ self._stream = stream
169
+
170
+ @property
171
+ def result(self) -> Any:
172
+ return getattr(self._stream, "_result", None)
173
+
174
+ def __iter__(self):
175
+ return iter(self._stream)
176
+
177
+ @property
178
+ def stop_check(self):
179
+ return getattr(self._stream, "stop_check", None)
180
+
181
+ @stop_check.setter
182
+ def stop_check(self, callback):
183
+ if hasattr(self._stream, "stop_check"):
184
+ self._stream.stop_check = callback
185
+
186
+ def disconnect(self) -> None:
187
+ callback = getattr(self._stream, "disconnect", None)
188
+ if callable(callback):
189
+ callback()
190
+
191
+
192
+ class E2BBackgroundCommand:
193
+ """A host-owned handle to one remote E2B background command.
194
+
195
+ The locator (``command_id``) is the only identity exposed to the model and
196
+ the native layer; the remote pid stays internal. Output is read from host
197
+ files via UTF-8 cursors. Liveness is cross-process: the detached supervisor
198
+ holds ``supervisor.lock`` with an exclusive flock while it runs.
199
+ """
200
+
201
+ def __init__(self, store: "E2BCommandStore", directory: Path, *, command_id: str):
202
+ self._store = store
203
+ self._directory = directory
204
+ self.command_id = command_id
205
+ self._record() # Refuse a handle from another session/root.
206
+
207
+ def _record(self) -> dict[str, Any]:
208
+ record = _json(self._directory / "record.json")
209
+ if record.get("owner") != self._store.owner or record.get("command_id") != self.command_id:
210
+ raise SandboxError("Background command does not belong to this session")
211
+ return record
212
+
213
+ @property
214
+ def timeout_seconds(self) -> int:
215
+ return self._record()["process_timeout_seconds"]
216
+
217
+ @property
218
+ def process_id(self) -> int:
219
+ # The supervisor's own pid, used only as a liveness/compatibility
220
+ # locator. No action sends signals to it; cancellation writes a marker
221
+ # that the supervisor observes and translates into a remote kill.
222
+ process_id = self._record().get("supervisor_pid")
223
+ if type(process_id) is not int or process_id < 1:
224
+ raise SandboxError("Background command supervisor identity is unavailable")
225
+ return process_id
226
+
227
+ def read_output(
228
+ self, *, stdout_cursor: int = 0, stderr_cursor: int = 0, max_bytes: int = 65536
229
+ ) -> CommandOutput:
230
+ if type(max_bytes) is not int or not 4 <= max_bytes <= 65536:
231
+ raise SandboxError("Command output window must be between 4 and 65536 bytes")
232
+ # Cross-process liveness: if the advisory lock is free, no live
233
+ # supervisor owns the command. A non-terminal status without a live
234
+ # supervisor cannot be confirmed and must not be retried.
235
+ with os.fdopen(
236
+ _open_private(self._directory / "supervisor.lock", os.O_RDWR | os.O_CREAT), "r+"
237
+ ) as lock:
238
+ try:
239
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
240
+ except BlockingIOError:
241
+ supervisor_alive = True
242
+ else:
243
+ supervisor_alive = False
244
+ record = self._record()
245
+ status = str(record.get("status", "unknown"))
246
+ if status not in _TERMINAL and not supervisor_alive:
247
+ if status != "starting" or time.time() - record["created_at"] > 5:
248
+ status = "unknown"
249
+ stdout, stdout_end = _read_window(self._directory / "stdout", stdout_cursor, max_bytes)
250
+ stderr, stderr_end = _read_window(self._directory / "stderr", stderr_cursor, max_bytes)
251
+ return CommandOutput(
252
+ status=status,
253
+ stdout=stdout,
254
+ stderr=stderr,
255
+ stdout_cursor=stdout_end,
256
+ stderr_cursor=stderr_end,
257
+ exit_code=record.get("exit_code") if status in _TERMINAL else None,
258
+ cancel_requested=(self._directory / "cancel").exists(),
259
+ evidence_incomplete=bool(record.get("evidence_incomplete")),
260
+ observed_exit_code=record.get("observed_exit_code"),
261
+ outcome_reason=str(record.get("outcome_reason") or record.get("observed_reason") or ""),
262
+ )
263
+
264
+ def request_cancel(self) -> CommandOutput:
265
+ output = self.read_output()
266
+ if output.status == "unknown":
267
+ record = self._record()
268
+ if (record.get("pid") and record.get("sandbox_id")
269
+ and self._store._authority_proven()):
270
+ source = _make_stream_source(self._store._source_config,
271
+ record["sandbox_id"], self._store._sandbox_root)
272
+ confirmed = _safe_kill(source, int(record["pid"]), "cancel")
273
+ record["remote_cancel_confirmed"] = confirmed
274
+ _atomic_json(self._directory / "record.json", record)
275
+ with os.fdopen(_open_private(
276
+ self._directory / "cancel", os.O_WRONLY | os.O_CREAT
277
+ ), "w"):
278
+ pass
279
+ return self.read_output()
280
+ if output.status not in _TERMINAL:
281
+ with os.fdopen(
282
+ _open_private(self._directory / "cancel", os.O_WRONLY | os.O_CREAT), "w"
283
+ ):
284
+ pass
285
+ return self.read_output()
286
+
287
+ def wait(self, timeout: float | None = None) -> SandboxCommandResult:
288
+ started = time.monotonic()
289
+ while (output := self.read_output()).status not in _TERMINAL:
290
+ if timeout is not None and time.monotonic() - started >= timeout:
291
+ raise TimeoutError("Background command is still running")
292
+ time.sleep(0.05)
293
+ if output.status == "unknown":
294
+ raise SandboxError("Background command outcome is unknown; do not repeat the action")
295
+ stdout, _ = _read_window_all(self._directory / "stdout")
296
+ stderr, _ = _read_window_all(self._directory / "stderr")
297
+ return SandboxCommandResult(stdout=stdout, stderr=stderr, exit_code=output.exit_code)
298
+
299
+ def kill(self) -> bool:
300
+ self.request_cancel()
301
+ try:
302
+ self.wait(timeout=3)
303
+ except (TimeoutError, SandboxError):
304
+ return False
305
+ return self.read_output().status == "cancelled"
306
+
307
+
308
+ # ---------------------------------------------------------------------------
309
+ # Command store (launch + recover + connect) — spawns detached supervisors.
310
+ # ---------------------------------------------------------------------------
311
+
312
+
313
+ class E2BCommandStore:
314
+ """Host-owned command records for one session, backed by detached supervisors."""
315
+
316
+ def __init__(
317
+ self,
318
+ *,
319
+ state_root: Path,
320
+ workspace_root: Path,
321
+ session_id: str,
322
+ source_config: dict[str, Any],
323
+ kill_sandbox: Callable[[str], None] | None = None,
324
+ declaration: BackgroundHostDeclaration | None = None,
325
+ ) -> None:
326
+ if os.name != "posix":
327
+ raise SandboxError("E2B background commands require POSIX process controls")
328
+ root = state_root.expanduser().absolute()
329
+ workspace = workspace_root.resolve()
330
+ if root.resolve() == workspace or workspace in root.resolve().parents:
331
+ raise SandboxError("Background command state must be outside the editable workspace")
332
+ self.owner = hashlib.sha256(
333
+ json.dumps([str(workspace), "e2b", session_id], separators=(",", ":")).encode()
334
+ ).hexdigest()
335
+ self.directory = root / "commands" / self.owner
336
+ _private_directory(self.directory)
337
+ self._sandbox_root = root / "sandboxes" / self.owner
338
+ _private_directory(self._sandbox_root)
339
+ self._source_config = source_config
340
+ self._kill_sandbox = kill_sandbox
341
+ # The host-declared typed connection target + credential resolver.
342
+ # Authority for read/stop/recover/terminate is the full typed identity
343
+ # (connection_ref/tenant_ref/principal_ref/endpoint/auth_mode) frozen in
344
+ # sandbox.json at launch, matched against this declaration. None means
345
+ # the E2B background capability is not declared; any frozen typed target
346
+ # then has no provable authority (unknown, zero backend calls).
347
+ self._declaration = declaration
348
+
349
+ def _has_sandbox_state(self) -> bool:
350
+ """True iff a sandbox.json file exists for this owner (regardless of
351
+ whether it carries a typed connection). Distinguishes a genuine first
352
+ launch (no sandbox.json at all) from an existing sandbox state that
353
+ merely lacks a provable typed identity (legacy/damaged)."""
354
+ sandbox_file = self._sandbox_root / "sandbox.json"
355
+ return sandbox_file.is_file() and not sandbox_file.is_symlink()
356
+
357
+ def _frozen_target(self) -> Any:
358
+ """Return the typed BackgroundConnectionTarget frozen in sandbox.json.
359
+
360
+ None when sandbox.json is absent, corrupt, or carries no typed identity
361
+ (a legacy api_url/domain/traffic_source record). Callers treat None as
362
+ ``unknown`` — never as an absent authority. Use :meth:`_has_sandbox_state`
363
+ to tell a genuine first launch (no file) from a legacy/damaged existing
364
+ state (file present, no typed identity).
365
+ """
366
+ if not self._has_sandbox_state():
367
+ return None
368
+ try:
369
+ data = _json(self._sandbox_root / "sandbox.json")
370
+ except Exception:
371
+ return None
372
+ from ksadk.studio.native_background_connection import BackgroundConnectionTarget
373
+
374
+ return BackgroundConnectionTarget.from_dict(data.get("connection"))
375
+
376
+ def _authority_proven(self) -> bool:
377
+ """True iff the host declaration proves authority over the existing
378
+ sandbox frozen in sandbox.json — the full typed identity matches the
379
+ declaration. This is the gate for operations that TOUCH an existing
380
+ sandbox (recover reconnect, close kill, terminate kill).
381
+
382
+ False (caller refuses with 0 side effects) when:
383
+ - a typed target is frozen but the declaration is missing/mismatched;
384
+ - no typed target is frozen and the source is production E2B (an
385
+ existing sandbox we cannot prove authority over — legacy/damaged).
386
+
387
+ The ``local_subprocess`` test seam has no typed connection by design
388
+ (it is the explicit test harness, not a real E2B sandbox with an
389
+ account), so a missing typed target there is always allowed. That
390
+ bypass is scoped to the test seam only and must not let production E2B
391
+ through an unprovable state.
392
+ """
393
+ frozen = self._frozen_target()
394
+ if frozen is not None:
395
+ if self._declaration is None:
396
+ return False
397
+ return self._declaration.target.authority_matches(frozen)
398
+ # No typed target: production E2B cannot prove authority over an existing
399
+ # sandbox; the local_subprocess test seam (source_kind or stream) has no
400
+ # real account to protect.
401
+ cfg = self._source_config
402
+ return (cfg.get("source_kind") == "local_subprocess"
403
+ or cfg.get("stream") == "local_subprocess")
404
+
405
+ def _assert_authority(self) -> None:
406
+ """Fail closed before touching an existing sandbox unless the host is
407
+ the authority, and allow a genuine first launch.
408
+
409
+ - A typed target frozen in sandbox.json requires the host declaration to
410
+ match it in full (same connection_ref/tenant_ref/principal_ref/
411
+ endpoint/auth_mode + E2B transport). A different tenant/principal at
412
+ the same endpoint, or no declaration, is refused.
413
+ - No typed target on production E2B: a genuine first launch (no
414
+ sandbox.json at all) has no existing sandbox to protect and is
415
+ allowed; an existing sandbox.json without a typed identity
416
+ (legacy/damaged) is an unprovable existing state → refused (unknown,
417
+ zero backend calls).
418
+ - The ``local_subprocess`` test seam has no typed connection by design
419
+ and is allowed through; that bypass is scoped to the test seam and
420
+ must not let production E2B through an unprovable state.
421
+ """
422
+ frozen = self._frozen_target()
423
+ if frozen is not None:
424
+ if self._declaration is None:
425
+ raise SandboxError("E2B background requires a host-declared connection target")
426
+ if not self._declaration.target.authority_matches(frozen):
427
+ raise SandboxError("E2B background connection authority mismatch")
428
+ return
429
+ # No typed target. The test seam (local_subprocess stream) has no real
430
+ # account; a missing typed target is its normal state, not a damaged sandbox.
431
+ cfg = self._source_config
432
+ if cfg.get("source_kind") == "local_subprocess" or cfg.get("stream") == "local_subprocess":
433
+ return
434
+ # Production E2B: a genuine first launch (no sandbox.json) is allowed;
435
+ # an existing sandbox.json with no typed identity is unprovable → refuse.
436
+ if self._has_sandbox_state():
437
+ raise SandboxError("E2B background sandbox has no provable typed connection")
438
+ return # first launch
439
+
440
+ def record_sandbox_id_for_task(self, task_id: str) -> str | None:
441
+ """Return the sandbox_id a command record launched under, by task_id.
442
+
443
+ Pure read used by the canonical Native ownership verifier to link a
444
+ sealed ``BackgroundCommandRef.task_id`` to the ``sandbox_id`` frozen in
445
+ ``sandbox.json``. Returns None when the task is not owned by this
446
+ session, has no record, or the record carries no sandbox_id. Never
447
+ raises — a missing/inconsistent link is None (the verifier treats None
448
+ as "not proven", fail closed).
449
+ """
450
+ if not isinstance(task_id, str) or not _COMMAND_ID.fullmatch(task_id):
451
+ return None
452
+ directory = self.directory / task_id
453
+ if directory.is_symlink() or not (directory / "record.json").is_file():
454
+ return None
455
+ try:
456
+ rec = _json(directory / "record.json")
457
+ except Exception:
458
+ return None
459
+ if rec.get("owner") != self.owner or rec.get("command_id") != task_id:
460
+ return None
461
+ sandbox_id = rec.get("sandbox_id")
462
+ return sandbox_id if isinstance(sandbox_id, str) and sandbox_id else None
463
+
464
+ def connect(self, command_id: str) -> E2BBackgroundCommand:
465
+ if not isinstance(command_id, str) or not _COMMAND_ID.fullmatch(command_id):
466
+ raise SandboxError("Invalid background command identity")
467
+ directory = self.directory / command_id
468
+ if directory.is_symlink() or not (directory / "record.json").is_file():
469
+ raise SandboxError("Background command is not owned by this session")
470
+ return E2BBackgroundCommand(self, directory, command_id=command_id)
471
+
472
+ def connect_or_recover(self, command_id: str) -> E2BBackgroundCommand:
473
+ """Connect to a command, reattaching a supervisor if the prior one died.
474
+
475
+ This is the product-path entry: ordinary reads and the recovery reattach
476
+ share one owned path. An unknown outcome is never re-executed; recovery
477
+ only reconnects to the existing remote command. The host declaration's
478
+ typed identity must match the frozen launch target before any backend
479
+ reconnect is attempted — a different authority cannot read another
480
+ authority's command.
481
+ """
482
+ self._assert_authority()
483
+ handle = self.connect(command_id)
484
+ record = handle._record()
485
+ status = str(record.get("status", "unknown"))
486
+ # A non-terminal status with no live supervisor and a known remote
487
+ # identity is recoverable; otherwise return the handle as-is.
488
+ if status in _TERMINAL:
489
+ return handle
490
+ if not record.get("pid") or not record.get("sandbox_id"):
491
+ return handle
492
+ if _supervisor_lock_held(handle._directory):
493
+ return handle # supervisor alive
494
+ return self.recover(command_id)
495
+
496
+ def start(
497
+ self,
498
+ *,
499
+ command: str,
500
+ cwd: str | None,
501
+ env: dict[str, str] | None,
502
+ timeout: int,
503
+ operation_key: str | None = None,
504
+ ) -> E2BBackgroundCommand:
505
+ command_id = hashlib.sha256(
506
+ (self.owner + ":" + (operation_key or uuid4().hex)).encode()
507
+ ).hexdigest()
508
+ digest = hashlib.sha256(
509
+ json.dumps([command, cwd, env, timeout], sort_keys=True).encode()
510
+ ).hexdigest()
511
+ with os.fdopen(
512
+ _open_private(self.directory / "launch.lock", os.O_RDWR | os.O_CREAT), "r+"
513
+ ) as lock:
514
+ fcntl.flock(lock, fcntl.LOCK_EX)
515
+ # A re-launch by a different authority (different typed identity) must
516
+ # not reuse or re-drive another authority's command. The first launch
517
+ # has no frozen target and is allowed through.
518
+ self._assert_authority()
519
+ directory = self.directory / command_id
520
+ if directory.exists():
521
+ handle = self.connect(command_id)
522
+ if handle._record().get("request_digest") != digest:
523
+ raise SandboxError(
524
+ "Background command operation identity has different arguments"
525
+ )
526
+ return handle # Even an unknown launch is never executed a second time.
527
+ _private_directory(directory)
528
+ for name in ("stdout", "stderr", "supervisor.lock"):
529
+ os.close(_open_private(directory / name, os.O_RDWR | os.O_CREAT | os.O_EXCL))
530
+ _atomic_json(
531
+ directory / "record.json",
532
+ {
533
+ "version": 1,
534
+ "owner": self.owner,
535
+ "command_id": command_id,
536
+ "request_digest": digest,
537
+ "process_timeout_seconds": timeout,
538
+ "status": "starting",
539
+ "created_at": time.time(),
540
+ "backend": self._source_config.get("source_kind") or "e2b",
541
+ },
542
+ )
543
+ handle = self.connect(command_id)
544
+ self._spawn_supervisor(handle, mode="start", generation=0,
545
+ request={"command": command, "cwd": cwd, "env": env})
546
+ deadline = time.monotonic() + 5
547
+ while handle._record()["status"] == "starting" and time.monotonic() < deadline:
548
+ time.sleep(0.02)
549
+ return handle
550
+
551
+ def recover(self, command_id: str) -> E2BBackgroundCommand:
552
+ """Reattach after the previous supervisor died mid-command.
553
+
554
+ Reconnects to the remote command via ``sandbox_id`` + ``pid``. Output
555
+ produced during the disconnect gap is not replayed by E2B; the
556
+ supervisor captures only post-reconnect output. The outcome stays
557
+ ``unknown`` with ``evidence_incomplete`` even if a terminal exit code is
558
+ observed, because the gap output is missing. Never relaunches the
559
+ command.
560
+
561
+ ``recover.lock`` serializes the spawn decision across concurrent hosts.
562
+ The parent holds it while spawning the child and waits for the child to
563
+ take ``supervisor.lock`` before releasing ``recover.lock``, so a second
564
+ host arriving in the gap sees the lock held and does not spawn again.
565
+ A generation counter fences stale supervisors.
566
+ """
567
+ handle = self.connect(command_id)
568
+ record = handle._record()
569
+ if str(record.get("status", "unknown")) in _TERMINAL:
570
+ return handle
571
+ if not record.get("pid") or not record.get("sandbox_id"):
572
+ return handle # Cannot reconnect without a remote identity.
573
+ # Reconnecting touches an existing sandbox. Require proven authority
574
+ # (full typed identity of the frozen sandbox.json matched to the host
575
+ # declaration). An unprovable authority — a missing/legacy typed target
576
+ # on production E2B, or a mismatched/missing declaration — settles to a
577
+ # truthful ``unknown`` with zero backend side effects (no spawn, no
578
+ # kill) rather than reconnecting to a sandbox this host cannot prove it
579
+ # owns. This governs recover() as a public entry uniformly with
580
+ # connect_or_recover/close/terminate.
581
+ if not self._authority_proven():
582
+ self._settle_unknown(handle, "recovery authority unprovable")
583
+ return handle
584
+ with os.fdopen(
585
+ _open_private(handle._directory / "recover.lock", os.O_RDWR | os.O_CREAT), "r+"
586
+ ) as rlock:
587
+ fcntl.flock(rlock, fcntl.LOCK_EX)
588
+ # Re-check inside the recover lock: a concurrent host may have
589
+ # already persisted a reservation or a live supervisor may exist.
590
+ record = handle._record()
591
+ if str(record.get("status", "unknown")) in _TERMINAL:
592
+ return handle
593
+ if _supervisor_lock_held(handle._directory):
594
+ return handle # A live supervisor owns it; nothing to recover.
595
+ claimed_gen = record.get("recovery_claim_generation")
596
+ if claimed_gen is not None:
597
+ # A reservation exists. If it is stale (the claiming host crashed
598
+ # before its supervisor took over, or the spawn failed), a new
599
+ # host may reclaim it after the reservation TTL. This prevents a
600
+ # durable-but-orphaned claim from blocking recovery forever.
601
+ claim_age = time.time() - float(record.get("recovery_claim_at") or 0)
602
+ if claim_age < _RECOVERY_CLAIM_TTL_SECONDS:
603
+ # The durable claim already prevents a second spawn. If a
604
+ # supervisor is already live, return immediately; if not, the
605
+ # claim's supervisor will take over (or expire after TTL for
606
+ # reclaim). Do not block other hosts in a wait window — the
607
+ # claim is the serialization mechanism, not the wait.
608
+ return handle
609
+ # Stale claim: clear it and fall through to spawn a fresh
610
+ # reservation. The new generation must advance past the stale
611
+ # claim's generation (not just record.generation, which the
612
+ # stale claim may not have confirmed), so a delayed child from
613
+ # the stale claim cannot collide with the new reservation's
614
+ # token.
615
+ stale_claim_gen = int(claimed_gen or 0)
616
+ record.pop("recovery_claim_generation", None)
617
+ record.pop("recovery_claim_at", None)
618
+ record["_stale_claim_floor"] = stale_claim_gen
619
+ # Persist a durable reservation before spawning. This survives the
620
+ # recover.lock being released (e.g. after the wait window), so a
621
+ # second host arriving later sees the claim and does not spawn again.
622
+ # Generation is monotonically increasing across all reservations:
623
+ # max of the confirmed generation, any prior claim, and any stale
624
+ # claim floor, plus one. This guarantees a delayed child from an
625
+ # older reservation always has a strictly smaller token than any
626
+ # later reservation.
627
+ prior_gen = int(record.get("generation") or 0)
628
+ prior_claim = int(record.get("recovery_claim_generation") or 0)
629
+ stale_floor = int(record.get("_stale_claim_floor") or 0)
630
+ generation = max(prior_gen, prior_claim, stale_floor) + 1
631
+ record["recovery_claim_generation"] = generation
632
+ record["recovery_claim_at"] = time.time()
633
+ record.pop("_stale_claim_floor", None)
634
+ _atomic_json(handle._directory / "record.json", record)
635
+ self._spawn_supervisor(handle, mode="reconnect", generation=generation)
636
+ # The durable claim already prevents a second spawn. Do not wait for
637
+ # the child to take supervisor.lock before returning — the claim is
638
+ # the serialization mechanism. The child will take over (or the claim
639
+ # expires after TTL for reclaim). Blocking here would add an unbounded
640
+ # wait for the child's import/startup time.
641
+ return handle
642
+
643
+ def close(self) -> bool:
644
+ """Kill the persistent sandbox. Returns True if killed, False otherwise.
645
+
646
+ Governed like recover/terminate: the host declaration must prove
647
+ authority over the existing sandbox (full typed identity match) and the
648
+ frozen sandbox.json must belong to this owner, before any kill RPC. An
649
+ unprovable authority or a foreign-owned sandbox returns False with zero
650
+ side effects — an undeclared host must not kill another authority's
651
+ sandbox.
652
+ """
653
+ if self._kill_sandbox is None:
654
+ return False
655
+ if not self._authority_proven():
656
+ return False # 0 side effects: cannot prove authority over this sandbox
657
+ sandbox_file = self._sandbox_root / "sandbox.json"
658
+ if not sandbox_file.is_file() or sandbox_file.is_symlink():
659
+ return False
660
+ try:
661
+ sandbox_data = _json(sandbox_file)
662
+ except Exception:
663
+ return False
664
+ # Ownership: the frozen sandbox.json must belong to this session's owner
665
+ # key. A foreign-owned sandbox.json is not this session's sandbox.
666
+ if sandbox_data.get("owner") != self.owner:
667
+ return False
668
+ sandbox_id = sandbox_data.get("sandbox_id", "")
669
+ if not sandbox_id:
670
+ return False
671
+ self._kill_sandbox(sandbox_id)
672
+ return True
673
+
674
+ def terminate(self) -> str:
675
+ """Terminate the owner's persistent sandbox with full status semantics.
676
+
677
+ Returns one of: "terminated", "confirmed_absent", "not_e2b",
678
+ "no_owner", "unknown", "failed", "timeout".
679
+
680
+ Owner proof (what this proves, and its boundary):
681
+
682
+ * **Account authority** — the typed connection target frozen in
683
+ sandbox.json matches the host declaration in full (same
684
+ connection_ref/tenant_ref/principal_ref/endpoint/auth_mode).
685
+ * **Session ownership** — the owner key
686
+ ``sha256([workspace, "e2b", session_id])`` ties the durable state
687
+ (command records + sandbox.json) to the canonical ``session_id``
688
+ supplied by the host (from ``session_service``).
689
+ * **Sandbox↔command linkage** — when command records carry a
690
+ ``sandbox_id`` (the production case: the supervisor writes it before
691
+ sandbox.json), the sandbox.json ``sandbox_id`` must match one of
692
+ them, proving the sandbox was launched by a command this session
693
+ owns. A mismatch is inconsistent/tampered → unknown.
694
+
695
+ This is host durable state, NOT the canonical launch receipt. Proving
696
+ the ``sandbox_id`` corresponds to a canonical Native *run* requires the
697
+ launch receipt (RunHandle/scope/receipt), which the read/stop
698
+ ``BackgroundCommandLocator`` traverses; ``terminate`` operates at the
699
+ session-durable-state level and does not re-traverse the receipt. The
700
+ command record ``backend`` is metadata only (it distinguishes a
701
+ deterministic ``not_e2b`` from a damaged ``unknown``); the first record
702
+ never authorizes the kill. A frozen typed target with no matching host
703
+ declaration, or a different typed identity, is ``unknown`` with zero
704
+ backend calls — never a blind kill under a different authority.
705
+
706
+ Ownership consistency (the owner key
707
+ ``sha256([workspace, "e2b", session_id])`` ties the durable state to the
708
+ canonical session id): every command record must be a VALID launch
709
+ evidence record — well-formed JSON, owned by this owner
710
+ (``rec.owner == self.owner``), ``command_id`` matching its directory,
711
+ ``backend == "e2b"``, and a ``sandbox_id`` matching ``sandbox.json``'s.
712
+ A corrupted record, a record missing ``sandbox_id`` or ``backend``, a
713
+ foreign/tampered record, or a sandbox.json with no command records at
714
+ all is missing/inconsistent launch evidence → ``unknown`` with zero
715
+ backend calls. ``unknown`` retains metadata and never becomes
716
+ ``confirmed_absent``. A shared typed account does NOT prove the sandbox
717
+ was launched by this session. Valid-owner cleanup is preserved.
718
+ """
719
+ sandbox_file = self._sandbox_root / "sandbox.json"
720
+ has_sandbox = sandbox_file.is_file() and not sandbox_file.is_symlink()
721
+ # Scan all command records. Each must be a complete, valid launch
722
+ # evidence record owned by this session. A record is a valid launch
723
+ # evidence record iff: well-formed JSON; rec.owner == self.owner;
724
+ # rec.command_id == its directory name; rec.backend == "e2b";
725
+ # rec.sandbox_id present. Any deviation (corrupt JSON, foreign/tampered
726
+ # owner or command_id, missing backend, missing sandbox_id) means that
727
+ # record does not prove a launch this session owns → fail closed.
728
+ commands_dir = self.directory
729
+ has_commands = False
730
+ inconsistent = False
731
+ record_backends: set = set()
732
+ matching_launch_evidence = False # a record whose sandbox_id == sandbox.json's
733
+ if commands_dir.is_dir():
734
+ for child in sorted(commands_dir.iterdir()):
735
+ rec_path = child / "record.json"
736
+ if rec_path.is_file() and not rec_path.is_symlink():
737
+ has_commands = True
738
+ try:
739
+ rec = _json(rec_path)
740
+ except Exception:
741
+ # Corrupt record: cannot prove a launch → inconsistent.
742
+ inconsistent = True
743
+ continue
744
+ # Ownership + identity consistency.
745
+ if rec.get("owner") != self.owner or rec.get("command_id") != child.name:
746
+ inconsistent = True
747
+ continue
748
+ backend = rec.get("backend")
749
+ if backend is not None:
750
+ record_backends.add(backend)
751
+ # A launch evidence record for an e2b sandbox requires a
752
+ # backend of "e2b" and a sandbox_id. local_process is a
753
+ # legitimate non-e2b record (a different backend), not an
754
+ # inconsistent one — it is handled by the deterministic
755
+ # not_e2b judgement. Any other backend (unknown/foreign) or
756
+ # a missing sandbox_id on an e2b record means this record
757
+ # does not prove an e2b launch this session owns →
758
+ # inconsistent.
759
+ if backend == "e2b":
760
+ if not rec.get("sandbox_id"):
761
+ inconsistent = True
762
+ continue
763
+ elif backend != "local_process":
764
+ inconsistent = True
765
+ continue
766
+ # No owner: no commands AND no sandbox.json.
767
+ if not has_commands and not has_sandbox:
768
+ return "no_owner"
769
+ if not has_sandbox:
770
+ # No frozen typed connection to prove authority. Records that all
771
+ # prove a non-e2b backend are a deterministic not_e2b (allow delete);
772
+ # anything else (e2b records without the frozen target, mixed
773
+ # backends, no record backend, or a damaged record) → unknown. A
774
+ # tampered/corrupt record makes the state inconsistent → unknown.
775
+ if not inconsistent and record_backends == {"local_process"}:
776
+ return "not_e2b"
777
+ return "unknown"
778
+ try:
779
+ sandbox_data = _json(sandbox_file)
780
+ except Exception:
781
+ return "unknown"
782
+ sandbox_id = sandbox_data.get("sandbox_id", "")
783
+ if not sandbox_id:
784
+ return "unknown"
785
+ # Sandbox ownership: sandbox.json.owner must match this session's owner
786
+ # key. A sandbox.json planted with a foreign owner is not this session's
787
+ # sandbox → unknown, zero backend calls.
788
+ if sandbox_data.get("owner") != self.owner:
789
+ return "unknown"
790
+ # Launch evidence: a sandbox.json with no command records means no command
791
+ # this session owns recorded launching it → unknown. (Production always
792
+ # writes the command record before sandbox.json.)
793
+ if not has_commands:
794
+ return "unknown"
795
+ # Deterministic not_e2b: a sandbox.json with no typed identity (legacy/
796
+ # damaged) whose command records are ALL local_process (no corrupt/
797
+ # foreign/e2b record mixed in) is not an E2B sandbox at all — the
798
+ # metadata can be deleted without a kill RPC. Judged before the
799
+ # inconsistent check so a clean local_process-only session is
800
+ # deterministically cleaned. A mixed state (local_process + a corrupt or
801
+ # e2b record) is NOT deterministically not_e2b → falls through to unknown.
802
+ frozen_target = self._frozen_target()
803
+ if (frozen_target is None and not inconsistent
804
+ and record_backends == {"local_process"}):
805
+ return "not_e2b"
806
+ # Any corrupt/foreign/tampered/incomplete record is inconsistent state
807
+ # that cannot prove a clean launch → unknown.
808
+ if inconsistent:
809
+ return "unknown"
810
+ # Sandbox↔command linkage: at least one valid launch evidence record must
811
+ # carry a sandbox_id matching sandbox.json's. A sandbox.json pointing at
812
+ # a sandbox no session command proves it launched → unknown, no kill.
813
+ for child in sorted(commands_dir.iterdir()):
814
+ rec_path = child / "record.json"
815
+ if rec_path.is_file() and not rec_path.is_symlink():
816
+ try:
817
+ rec = _json(rec_path)
818
+ if (rec.get("owner") == self.owner
819
+ and rec.get("command_id") == child.name
820
+ and rec.get("backend") == "e2b"
821
+ and rec.get("sandbox_id") == sandbox_id):
822
+ matching_launch_evidence = True
823
+ break
824
+ except Exception:
825
+ pass
826
+ if not matching_launch_evidence:
827
+ return "unknown"
828
+ # Reaching here means a valid e2b launch evidence record matched the
829
+ # sandbox.json sandbox_id. A typed target was already required above
830
+ # (frozen_target is not None here, or it would have returned at the
831
+ # not_e2b/unknown judgement). Authority: the host declaration must
832
+ # match the frozen typed identity in full. No declaration, or a
833
+ # different tenant/principal at the same endpoint, is a different
834
+ # authority → unknown, zero backend calls.
835
+ if not self._authority_proven():
836
+ return "unknown"
837
+ if self._kill_sandbox is None:
838
+ return "unknown"
839
+ # Kill RPC in a bounded helper thread. SDK returns True=killed,
840
+ # False=confirmed not found. Exception or timeout → unknown/failed.
841
+ result_box: list = []
842
+ def _do_kill():
843
+ try:
844
+ result_box.append(self._kill_sandbox(sandbox_id))
845
+ except Exception:
846
+ result_box.append(None)
847
+ t = threading.Thread(target=_do_kill, daemon=True)
848
+ t.start()
849
+ t.join(timeout=_kill_rpc_timeout())
850
+ if not result_box:
851
+ return "timeout"
852
+ if result_box[0] is True:
853
+ return "terminated"
854
+ if result_box[0] is False:
855
+ return "confirmed_absent"
856
+ return "failed"
857
+
858
+ def _spawn_supervisor(
859
+ self, handle: E2BBackgroundCommand, *, mode: str, generation: int = 0,
860
+ request: dict[str, Any] | None = None,
861
+ ) -> None:
862
+ source_root = str(Path(__file__).resolve().parents[2])
863
+ script = (
864
+ "import sys; sys.path.insert(0, sys.argv[1]); "
865
+ "from ksadk.sandbox.e2b_background import _run_supervisor; _run_supervisor()"
866
+ )
867
+ config = {
868
+ "mode": mode,
869
+ "directory": str(handle._directory),
870
+ "sandbox_root": str(self._sandbox_root),
871
+ "owner": self.owner,
872
+ "source_config": self._source_config,
873
+ # Launch arguments travel only over the private stdin pipe. Recovery
874
+ # reconnects by pid and never needs to persist command text or env.
875
+ "command": (request or {}).get("command", ""),
876
+ "cwd": (request or {}).get("cwd"),
877
+ "env": (request or {}).get("env"),
878
+ "timeout": handle._record().get("process_timeout_seconds", 0),
879
+ "generation": generation,
880
+ }
881
+ try:
882
+ process = subprocess.Popen(
883
+ [sys.executable, "-B", "-I", "-c", script, source_root, str(handle._directory)],
884
+ stdin=subprocess.PIPE,
885
+ stdout=subprocess.DEVNULL,
886
+ stderr=subprocess.DEVNULL,
887
+ start_new_session=True,
888
+ close_fds=True,
889
+ # The supervisor imports trusted code; credentials arrive over
890
+ # the stdin pipe, never via env or argv.
891
+ env={"PATH": os.defpath, "LANG": "C.UTF-8"},
892
+ )
893
+ except OSError:
894
+ self._settle_unknown(handle, "supervisor spawn failed")
895
+ return
896
+ threading.Thread(target=process.wait, daemon=True).start()
897
+ assert process.stdin is not None
898
+ try:
899
+ process.stdin.write(json.dumps(config).encode())
900
+ process.stdin.close()
901
+ except OSError:
902
+ # Return the stable locator even when acknowledgement is uncertain.
903
+ try:
904
+ process.stdin.close()
905
+ except OSError:
906
+ pass
907
+
908
+ @staticmethod
909
+ def _settle_unknown(handle: E2BBackgroundCommand, reason: str) -> None:
910
+ record = handle._record()
911
+ record.update(status="unknown", exit_code=None, completed_at=time.time(),
912
+ failure_reason=reason)
913
+ _atomic_json(handle._directory / "record.json", record)
914
+
915
+
916
+ def _supervisor_lock_held(directory: Path) -> bool:
917
+ """Cross-process liveness probe: True if a live supervisor holds the lock."""
918
+ try:
919
+ with os.fdopen(
920
+ _open_private(directory / "supervisor.lock", os.O_RDWR | os.O_CREAT), "r+"
921
+ ) as lock:
922
+ try:
923
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
924
+ except BlockingIOError:
925
+ return True
926
+ except OSError:
927
+ return False
928
+ return False
929
+
930
+
931
+ # Bounded timeout for the kill RPC helper thread. This is our own implementation
932
+ # policy: a single SIGKILL RPC should return within seconds; if it hangs
933
+ # (network failure) the supervisor must not block indefinitely. Configurable
934
+ # via KSADK_E2B_KILL_TIMEOUT_SECONDS for hosts that need a different bound.
935
+ def _kill_rpc_timeout() -> float:
936
+ raw = os.environ.get("KSADK_E2B_KILL_TIMEOUT_SECONDS", "10")
937
+ try:
938
+ return max(0.1, float(raw))
939
+ except (TypeError, ValueError):
940
+ return 10.0
941
+
942
+
943
+ def _safe_kill(source: Any, pid: int, kind: str) -> bool:
944
+ """Issue a remote kill and return whether it was confirmed.
945
+
946
+ A kill that raises, returns False, or cannot be confirmed within a bounded
947
+ time is not a successful cancellation. The kill RPC runs in a helper thread
948
+ with a bounded join so a non-returning RPC (network hang) does not block
949
+ the watcher indefinitely.
950
+ """
951
+ result_box: list[bool] = []
952
+
953
+ def _do_kill():
954
+ try:
955
+ result_box.append(bool(source.kill(pid)))
956
+ except Exception:
957
+ result_box.append(False)
958
+
959
+ t = threading.Thread(target=_do_kill, daemon=True)
960
+ t.start()
961
+ t.join(timeout=_kill_rpc_timeout())
962
+ return result_box[0] if result_box else False
963
+
964
+
965
+ def _disconnect_stream(stream: Any) -> None:
966
+ """Close a command event stream without killing the command.
967
+
968
+ The real E2B SDK CommandHandle (command_handle.py:88-95) provides disconnect()
969
+ which closes the event generator without sending a signal. This lets the
970
+ supervisor settle after a timeout even when the kill failed and the stream
971
+ would otherwise block forever on ``for event in self._events``. For the
972
+ local test harness (_PipeStream) disconnect is a no-op; stop_check handles
973
+ the bounded exit there.
974
+ """
975
+ disconnect = getattr(stream, "disconnect", None)
976
+ if callable(disconnect):
977
+ try:
978
+ disconnect()
979
+ except Exception:
980
+ logger.warning("E2B background stream disconnect failed")
981
+
982
+
983
+ # ---------------------------------------------------------------------------
984
+ # Detached supervisor entry (runs in its own process).
985
+ # ---------------------------------------------------------------------------
986
+
987
+
988
+ def _run_supervisor() -> None:
989
+ directory = Path(sys.argv[2])
990
+ try:
991
+ config = json.load(sys.stdin)
992
+ except Exception:
993
+ return
994
+ try:
995
+ source = _make_stream_source(
996
+ config["source_config"], config.get("sandbox_id"), Path(config["sandbox_root"])
997
+ )
998
+ _supervise(directory, Path(config["sandbox_root"]), config, source)
999
+ except Exception:
1000
+ logger.exception("E2B background supervisor crashed")
1001
+ try:
1002
+ _settle_unknown_safe(directory, "supervisor crashed")
1003
+ except Exception:
1004
+ pass
1005
+
1006
+
1007
+ def _settle_unknown_safe(directory: Path, reason: str) -> None:
1008
+ record = _json(directory / "record.json")
1009
+ record.update(status="unknown", exit_code=None, completed_at=time.time(),
1010
+ failure_reason=reason, outcome_reason=reason)
1011
+ _atomic_json(directory / "record.json", record)
1012
+
1013
+
1014
+ def _supervise(
1015
+ directory: Path, sandbox_root: Path, config: dict[str, Any], source: Any
1016
+ ) -> None:
1017
+ with os.fdopen(_open_private(directory / "supervisor.lock", os.O_RDWR), "r+") as lock:
1018
+ fcntl.flock(lock, fcntl.LOCK_EX)
1019
+ record = _json(directory / "record.json")
1020
+ mode = config["mode"]
1021
+ generation = int(config.get("generation") or 0)
1022
+ # All entry points first check the terminal state: a command that has
1023
+ # already settled must not be taken over again by any supervisor
1024
+ # (including a late start or a late reconnect child).
1025
+ if str(record.get("status", "unknown")) in _TERMINAL:
1026
+ logger.warning(
1027
+ "E2B background supervisor %s refused: record already terminal (%s)",
1028
+ directory.name, record.get("status"),
1029
+ )
1030
+ return
1031
+ record_generation = int(record.get("generation") or 0)
1032
+ # Generation fence (complete contract):
1033
+ # - reconnect: the parent persisted recovery_claim_generation before
1034
+ # spawning this supervisor. If a different/newer claim exists, or the
1035
+ # claim was already cleared but the record's generation advanced past
1036
+ # this supervisor (a newer reclaim won), this supervisor is stale and
1037
+ # must refuse to take over. It must never overwrite a newer record.
1038
+ # - start: a fresh command (generation 0) must not overwrite a record
1039
+ # that already advanced to a higher generation via recovery.
1040
+ record_generation = int(record.get("generation") or 0)
1041
+ if mode == "reconnect":
1042
+ claimed = record.get("recovery_claim_generation")
1043
+ if claimed is not None:
1044
+ if int(claimed) != generation:
1045
+ logger.warning(
1046
+ "E2B background supervisor %s (gen=%d) superseded by claim gen=%s",
1047
+ directory.name, generation, claimed,
1048
+ )
1049
+ return
1050
+ elif record_generation > generation:
1051
+ # Claim was cleared by a newer reclaim; this stale supervisor
1052
+ # must not overwrite the newer generation's record.
1053
+ logger.warning(
1054
+ "E2B background supervisor %s (gen=%d) stale vs record gen=%d",
1055
+ directory.name, generation, record_generation,
1056
+ )
1057
+ return
1058
+ # Confirm takeover: clear the claim and persist this generation.
1059
+ record["generation"] = generation
1060
+ record.pop("recovery_claim_generation", None)
1061
+ record.pop("recovery_claim_at", None)
1062
+ else: # start
1063
+ if record_generation > generation:
1064
+ logger.warning(
1065
+ "E2B background start supervisor %s refused: record gen=%d > %d",
1066
+ directory.name, record_generation, generation,
1067
+ )
1068
+ return
1069
+ record["generation"] = generation
1070
+ cancel_path = directory / "cancel"
1071
+ record["supervisor_pid"] = os.getpid()
1072
+ # reconnect mode must not overwrite output already delivered to host
1073
+ # files; only append post-reconnect bytes. start mode is the first
1074
+ # supervisor and owns the canonical output.
1075
+ append_only = mode == "reconnect"
1076
+ try:
1077
+ if mode == "start":
1078
+ pid, stream, sandbox_id = source.start(
1079
+ config["command"], cwd=config.get("cwd"),
1080
+ envs=config.get("env"), timeout=config.get("timeout") or 0,
1081
+ )
1082
+ record.update(status="running", pid=pid, sandbox_id=sandbox_id,
1083
+ started_at=time.time())
1084
+ _atomic_json(directory / "record.json", record)
1085
+ sandbox_json = {
1086
+ "sandbox_id": sandbox_id, "owner": config["owner"],
1087
+ "created_at": time.time(),
1088
+ }
1089
+ source_config = config.get("source_config") or {}
1090
+ # Freeze the typed host-declared connection target (non-sensitive
1091
+ # identity only; no key) as the canonical authority for later
1092
+ # read/stop/recover/terminate. A declaration that provided
1093
+ # connection_target wins; a legacy/test source that only carried
1094
+ # the transport triple falls back to that projection.
1095
+ typed = source_config.get("connection_target")
1096
+ if isinstance(typed, dict):
1097
+ sandbox_json["connection"] = dict(typed)
1098
+ else:
1099
+ conn = source_config.get("connection")
1100
+ if isinstance(conn, dict):
1101
+ sandbox_json["connection"] = {
1102
+ "api_url": conn.get("api_url", ""),
1103
+ "domain": conn.get("domain", ""),
1104
+ "traffic_source": conn.get("traffic_source", ""),
1105
+ }
1106
+ _atomic_json(sandbox_root / "sandbox.json", sandbox_json)
1107
+ else: # reconnect
1108
+ pid = int(record.get("pid") or 0)
1109
+ stream = source.reconnect(pid, timeout=config.get("timeout") or 0)
1110
+ record["recovered_at"] = time.time()
1111
+ # The disconnect gap is acknowledged: prior captured output stays
1112
+ # in the host files; only post-reconnect output is appended. The
1113
+ # outcome stays unknown until a new terminal event is observed,
1114
+ # because E2B does not replay output produced during the gap.
1115
+ record["reconnect_gap"] = True
1116
+ _atomic_json(directory / "record.json", record)
1117
+
1118
+ # Compute the remaining process deadline. A reconnect must not
1119
+ # reset the timeout: it preserves the original remaining window
1120
+ # measured from the command's original start, so a command that
1121
+ # already exhausted most of its deadline is not granted a fresh one.
1122
+ # None means no deadline (unlimited); 0 means the deadline is
1123
+ # already exhausted (must time out immediately), distinct from
1124
+ # unlimited so an expired command cannot run forever after reconnect.
1125
+ process_timeout = config.get("timeout") or 0
1126
+ if not process_timeout:
1127
+ remaining_seconds: float | None = None
1128
+ elif mode == "start":
1129
+ remaining_seconds = float(process_timeout)
1130
+ else:
1131
+ started_at = float(record.get("started_at") or 0)
1132
+ elapsed = max(0.0, time.time() - started_at) if started_at else 0.0
1133
+ remaining_seconds = max(0.0, float(process_timeout) - elapsed)
1134
+
1135
+ # Cancellation and timeout are controlled by a watcher thread that
1136
+ # is independent of the stream's output events. The real E2B SDK
1137
+ # (command_handle.py:54-86) only yields on non-empty stdout/stderr/
1138
+ # pty and sets _result on end without yielding; a long silent command
1139
+ # blocks ``for event in self._events`` indefinitely, so a cancel
1140
+ # check placed after each yield would never run. The watcher polls
1141
+ # the cancel marker and the process deadline and issues the remote
1142
+ # kill directly.
1143
+ #
1144
+ # A kill request is separate from a confirmed terminal outcome. The
1145
+ # watcher records whether the kill RPC succeeded (returned True); the
1146
+ # final status is decided from the actually-observed result, not from
1147
+ # the request. A kill that was refused, failed, or whose effect is
1148
+ # unknown must not be reported as a successful cancellation.
1149
+ stream: BackgroundStream = _StreamAdapter(stream)
1150
+ cancel_requested = {"value": False}
1151
+ timeout_requested = {"value": False}
1152
+ kill_succeeded = {"value": False}
1153
+ watcher_done = threading.Event()
1154
+ consumed = threading.Event()
1155
+
1156
+ def _watch() -> None:
1157
+ """Single arbiter for cancel/timeout and kill. The watcher is the
1158
+ only component that decides the deadline has expired or a cancel
1159
+ was requested, and the only one that issues kill. It also detects
1160
+ when the stream has received a terminal event (the SDK sets
1161
+ _result without yielding) so the supervisor can settle even if the
1162
+ RPC generator blocks after end. This avoids the race where
1163
+ consumer.join(timeout) and the watcher's own deadline check
1164
+ compete. After kill (success or failure), disconnect the stream
1165
+ so the consumer can settle, then return."""
1166
+ deadline = remaining_seconds
1167
+ start = time.monotonic()
1168
+ while True:
1169
+ if not cancel_requested["value"] and cancel_path.exists():
1170
+ cancel_requested["value"] = True
1171
+ kill_succeeded["value"] = _safe_kill(source, pid, "cancel")
1172
+ _disconnect_stream(stream)
1173
+ return
1174
+ if (deadline is not None and not timeout_requested["value"]
1175
+ and time.monotonic() - start >= deadline):
1176
+ timeout_requested["value"] = True
1177
+ kill_succeeded["value"] = _safe_kill(source, pid, "timeout")
1178
+ _disconnect_stream(stream)
1179
+ return
1180
+ # The SDK sets _result when an end event arrives but does not
1181
+ # yield it, so the consumer's for-loop blocks on the next
1182
+ # generator step. Detect _result here and signal the consumer
1183
+ # to stop — the outcome is confirmed without blocking.
1184
+ if stream.result is not None:
1185
+ consumed.set()
1186
+ watcher_done.set()
1187
+ return
1188
+ if watcher_done.wait(timeout=0.05):
1189
+ return
1190
+
1191
+ watcher = threading.Thread(target=_watch, name="e2b-bg-watch", daemon=True)
1192
+ watcher.start()
1193
+
1194
+ def _should_stop_stream() -> bool:
1195
+ return (
1196
+ cancel_requested["value"]
1197
+ or timeout_requested["value"]
1198
+ or stream.result is not None
1199
+ )
1200
+
1201
+ if hasattr(stream, "stop_check"):
1202
+ stream.stop_check = _should_stop_stream
1203
+
1204
+ result: Any = None
1205
+ stream_error = False
1206
+ settled = {"value": False}
1207
+
1208
+ def _guarded_append(path: Path, text: str) -> None:
1209
+ # After the supervisor has committed a terminal status, late
1210
+ # output from a still-blocking consumer must not mutate the
1211
+ # host files or advance cursors.
1212
+ if settled["value"]:
1213
+ return
1214
+ _append_output(path, text)
1215
+
1216
+ def _consume():
1217
+ nonlocal result, stream_error
1218
+ try:
1219
+ for out, err, _pty in stream:
1220
+ if cancel_requested["value"] or timeout_requested["value"]:
1221
+ break
1222
+ if out:
1223
+ _guarded_append(directory / "stdout", out)
1224
+ if err:
1225
+ _guarded_append(directory / "stderr", err)
1226
+ if stream.result is not None:
1227
+ break
1228
+ except Exception:
1229
+ stream_error = True
1230
+ finally:
1231
+ consumed.set()
1232
+ watcher_done.set()
1233
+
1234
+ consumer = threading.Thread(target=_consume, name="e2b-bg-stream", daemon=True)
1235
+ consumer.start()
1236
+ # Wait for the watcher (the single arbiter for cancel/timeout/kill).
1237
+ # The watcher returns when: (a) cancel is requested, (b) the deadline
1238
+ # expires, or (c) the consumer finished naturally (via watcher_done).
1239
+ # This means a natural completion exits immediately even with a
1240
+ # deadline — the process is not killed after it already finished.
1241
+ # Bounded by the process deadline if set; without a deadline, the
1242
+ # watcher exits on cancel or natural completion (both set watcher_done).
1243
+ if remaining_seconds is not None:
1244
+ watcher.join(timeout=max(remaining_seconds, 0.1) + 1)
1245
+ else:
1246
+ watcher.join()
1247
+ watcher_done.set()
1248
+ watcher.join(timeout=1)
1249
+ # After the arbiter has settled, give the consumer a bounded grace to
1250
+ # deliver any final result from the killed/disconnected stream.
1251
+ consumer.join(timeout=2)
1252
+
1253
+ if not consumed.is_set():
1254
+ # The consumer is still blocking (kill failed, stream blocks on
1255
+ # RPC, disconnect did not help). The outcome is unknown.
1256
+ settled["value"] = True
1257
+ _settle_unknown_safe(directory, "stream blocked past deadline")
1258
+ return
1259
+ result = stream.result
1260
+ exit_code = getattr(result, "exit_code", None) if result is not None else None
1261
+ if stream_error and result is None:
1262
+ settled["value"] = True
1263
+ _settle_unknown_safe(directory, "stream ended without result")
1264
+ return
1265
+ # Decide status from the observed result, keeping the real exit code.
1266
+ # A cancel/timeout request that the kill could not confirm does not
1267
+ # invent a terminal outcome.
1268
+ if exit_code is not None:
1269
+ # A terminal event was observed: report the real exit code. If a
1270
+ # cancel/timeout was requested, classify the reason but keep the
1271
+ # observed code rather than overwriting it. A cancel whose kill
1272
+ # was refused does not turn a successful natural exit into failed;
1273
+ # the command finished on its own.
1274
+ if cancel_requested["value"] and kill_succeeded["value"]:
1275
+ status, reason = "cancelled", "cancelled"
1276
+ elif cancel_requested["value"] and not kill_succeeded["value"]:
1277
+ # Cancel was requested but the kill was refused; the command
1278
+ # finished naturally. Report its real outcome, not a fake
1279
+ # cancellation or a blanket failed.
1280
+ if exit_code == 0:
1281
+ status, reason = "completed", "exit_after_cancel_request"
1282
+ else:
1283
+ status, reason = "failed", "exit_after_cancel_request"
1284
+ elif timeout_requested["value"] and kill_succeeded["value"]:
1285
+ status, reason = "timed_out", "timed_out"
1286
+ elif timeout_requested["value"] and not kill_succeeded["value"]:
1287
+ if exit_code == 0:
1288
+ status, reason = "completed", "exit_after_timeout_request"
1289
+ else:
1290
+ status, reason = "failed", "exit_after_timeout_request"
1291
+ elif exit_code == 0:
1292
+ status, reason = "completed", ""
1293
+ else:
1294
+ status, reason = "failed", ""
1295
+ elif cancel_requested["value"] and kill_succeeded["value"]:
1296
+ # No terminal event, but the kill succeeded: the process was
1297
+ # cancelled. Exit code is unknown (killed).
1298
+ status, exit_code, reason = "cancelled", None, "killed_by_cancel"
1299
+ elif timeout_requested["value"] and kill_succeeded["value"]:
1300
+ # Kill succeeded but no terminal event was observed (stream was
1301
+ # disconnected). The exit code is unknown (killed), not forged as
1302
+ # 124. The status is timed_out with a classified reason.
1303
+ status, exit_code, reason = "timed_out", None, "killed_by_timeout"
1304
+ elif cancel_requested["value"] or timeout_requested["value"]:
1305
+ # A kill was requested but could not be confirmed: the remote
1306
+ # outcome is unknown, not a successful cancel/timeout.
1307
+ status, exit_code, reason = "unknown", None, "kill_unconfirmed"
1308
+ else:
1309
+ status, exit_code, reason = "unknown", None, "no_terminal_event"
1310
+ # In reconnect mode the host files already hold the pre-gap output;
1311
+ # do not replace them. In start mode the append log is the complete
1312
+ # output, so finalize it (replace) for cursor stability.
1313
+ if not append_only:
1314
+ for channel in ("stdout", "stderr"):
1315
+ _finalize_output_from_log(directory / channel)
1316
+ record = _json(directory / "record.json")
1317
+ # Terminal-state generation fence: if a newer recovery advanced the
1318
+ # record's generation past this supervisor while it held the lock is
1319
+ # impossible (flock is exclusive), but defend anyway — a stale
1320
+ # supervisor that reacquired the lock after a newer reclaim must not
1321
+ # overwrite the newer generation's terminal result.
1322
+ if int(record.get("generation") or 0) > generation:
1323
+ logger.warning(
1324
+ "E2B background supervisor %s refused terminal write: record gen=%d > %d",
1325
+ directory.name, int(record.get("generation") or 0), generation,
1326
+ )
1327
+ settled["value"] = True
1328
+ return
1329
+ # A reconnect that observed a terminal event still cannot claim a
1330
+ # complete outcome: output from the disconnect gap is missing, so
1331
+ # the evidence is incomplete even if the exit code is known. Keep
1332
+ # the exit code for inspection but mark the outcome unknown.
1333
+ if append_only and record.get("reconnect_gap"):
1334
+ record["evidence_incomplete"] = True
1335
+ record["observed_exit_code"] = exit_code
1336
+ record["observed_reason"] = reason
1337
+ status = "unknown"
1338
+ exit_code = None
1339
+ else:
1340
+ record["outcome_reason"] = reason
1341
+ # Mark settled before writing the terminal record so any late output
1342
+ # from the still-blocking consumer is rejected by _guarded_append.
1343
+ settled["value"] = True
1344
+ record.update(status=status, exit_code=exit_code, completed_at=time.time())
1345
+ _atomic_json(directory / "record.json", record)
1346
+ except Exception:
1347
+ _settle_unknown_safe(directory, "supervisor body failed")
1348
+ raise
1349
+
1350
+
1351
+ def _append_output(path: Path, text: str) -> None:
1352
+ with os.fdopen(_open_private(path, os.O_WRONLY | os.O_APPEND), "ab") as out:
1353
+ out.write(text.encode("utf-8"))
1354
+
1355
+
1356
+ def _finalize_output_from_log(path: Path) -> None:
1357
+ """Atomically replace the append log with itself, making the retained
1358
+ output the canonical record for cursor stability. The content is unchanged;
1359
+ only the in-place append log is committed as the durable full output."""
1360
+ with os.fdopen(_open_private(path, os.O_RDONLY), "rb") as source:
1361
+ data = source.read()
1362
+ temporary = path.with_name(f".{path.name}.{uuid4().hex}")
1363
+ with os.fdopen(_open_private(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL), "wb") as out:
1364
+ out.write(data)
1365
+ out.flush()
1366
+ os.fsync(out.fileno())
1367
+ os.replace(temporary, path)
1368
+
1369
+
1370
+ # ---------------------------------------------------------------------------
1371
+ # Stream sources — pluggable so the lifecycle can be exercised without a real
1372
+ # remote sandbox. Production uses ``e2b``; the ``local_subprocess`` source runs
1373
+ # the command as a local process and is a deterministic lifecycle harness.
1374
+ # ---------------------------------------------------------------------------
1375
+
1376
+
1377
+ def _make_stream_source(
1378
+ source_config: dict[str, Any], sandbox_id: str | None, sandbox_root: Path
1379
+ ) -> Any:
1380
+ # The stream transport is selected by ``stream`` (test-seam-only mock
1381
+ # transport) falling back to ``source_kind`` (the backend label). Production
1382
+ # never sets ``stream``; the test seam sets it to ``local_subprocess`` to run
1383
+ # the command as a local process while ``source_kind`` stays ``e2b`` so the
1384
+ # command record is truthfully labeled ``e2b`` (matching the sealed receipt
1385
+ # backend). This is a bounded mock-transport seam, not a production identity
1386
+ # override: the record backend, the receipt backend, and the verifier all
1387
+ # agree on ``e2b``; only the wire transport is mocked.
1388
+ kind = source_config.get("source_kind")
1389
+ stream = source_config.get("stream") or kind
1390
+ if stream == "local_subprocess":
1391
+ return _LocalSubprocessStreamSource(sandbox_id, source_config)
1392
+ if kind == "e2b" or stream == "e2b":
1393
+ return _E2BStreamSource(source_config, sandbox_id, sandbox_root)
1394
+ raise SandboxError(f"Unknown E2B background stream source kind: {kind!r}")
1395
+
1396
+
1397
+ class _E2BStreamSource:
1398
+ """Real E2B stream source, constructed inside the supervisor process."""
1399
+
1400
+ def __init__(
1401
+ self, source_config: dict[str, Any], sandbox_id: str | None, sandbox_root: Path
1402
+ ) -> None:
1403
+ from ksadk.sandbox.backends.e2b import E2BSandboxBackend
1404
+ from ksadk.sandbox.base import SandboxSpec, SandboxType
1405
+ from ksadk.sandbox.e2b_connection import ExplicitE2BConnection
1406
+
1407
+ spec = source_config["spec"]
1408
+ spec_obj = SandboxSpec(
1409
+ template_id=spec["template_id"],
1410
+ sandbox_type=SandboxType(spec["sandbox_type"]),
1411
+ timeout=spec["timeout"],
1412
+ allow_internet_access=spec["allow_internet_access"],
1413
+ metadata=dict(spec.get("metadata") or {}),
1414
+ env=dict(spec.get("env") or {}),
1415
+ )
1416
+ conn = source_config.get("connection")
1417
+ conn_obj = None
1418
+ if conn is not None:
1419
+ conn_obj = ExplicitE2BConnection(
1420
+ api_url=conn["api_url"], domain=conn["domain"],
1421
+ api_key=conn["api_key"], traffic_source=conn["traffic_source"],
1422
+ )
1423
+ self._source_config = source_config
1424
+ self._backend = E2BSandboxBackend(spec=spec_obj, connection=conn_obj)
1425
+ self._sandbox_id = sandbox_id
1426
+ self._sandbox_root = sandbox_root
1427
+ self._session: Any = None
1428
+
1429
+ def _session_get(self) -> Any:
1430
+ if self._session is not None:
1431
+ return self._session
1432
+ # Serialize sandbox get-or-create across concurrent supervisors.
1433
+ with os.fdopen(
1434
+ _open_private(self._sandbox_root / "sandbox.lock", os.O_RDWR | os.O_CREAT), "r+"
1435
+ ) as lock:
1436
+ fcntl.flock(lock, fcntl.LOCK_EX)
1437
+ sandbox_file = self._sandbox_root / "sandbox.json"
1438
+ if (
1439
+ self._sandbox_id is None
1440
+ and sandbox_file.is_file()
1441
+ and not sandbox_file.is_symlink()
1442
+ ):
1443
+ self._sandbox_id = _json(sandbox_file).get("sandbox_id") or None
1444
+ if self._sandbox_id:
1445
+ self._session = self._backend.reconnect_session(session_locator=self._sandbox_id)
1446
+ else:
1447
+ self._session = self._backend.create_session(
1448
+ session_id=self._sandbox_root.name, input_files=[]
1449
+ )
1450
+ self._sandbox_id = getattr(self._session, "sandbox_id", "") or ""
1451
+ if not self._sandbox_id:
1452
+ raise SandboxError("E2B background sandbox did not expose a sandbox id")
1453
+ identity = {"sandbox_id": self._sandbox_id, "owner": self._sandbox_root.name,
1454
+ "created_at": time.time()}
1455
+ connection = (self._source_config.get("connection_target")
1456
+ or self._source_config.get("connection"))
1457
+ if isinstance(connection, dict):
1458
+ identity["connection"] = {key: value for key, value in connection.items()
1459
+ if key != "api_key"}
1460
+ # Publish identity before releasing the get-or-create lock; a
1461
+ # second supervisor must reconnect even before start() returns.
1462
+ _atomic_json(sandbox_file, identity)
1463
+ return self._session
1464
+
1465
+ def start(self, command, *, cwd, envs, timeout):
1466
+ session = self._session_get()
1467
+ handle = session.start_background_stream(
1468
+ command, envs=envs, cwd=cwd, timeout=max(timeout, 0) or None,
1469
+ )
1470
+ pid = int(getattr(handle, "pid", 0) or 0)
1471
+ if pid <= 0:
1472
+ raise SandboxError("E2B background command did not expose a process id")
1473
+ return pid, handle, self._sandbox_id
1474
+
1475
+ def reconnect(self, pid, *, timeout):
1476
+ session = self._session_get()
1477
+ return session.connect_background_stream(pid, timeout=timeout or None)
1478
+
1479
+ def kill(self, pid):
1480
+ return bool(self._session_get().kill_command(pid))
1481
+
1482
+
1483
+ class _LocalSubprocessStreamSource:
1484
+ """Deterministic lifecycle harness: the "remote command" is a local process.
1485
+
1486
+ Used to exercise the detached-supervisor lifecycle (cross-process survival,
1487
+ idempotency, cancellation, unknown outcome) without a real E2B sandbox.
1488
+ The command runs as a child of the supervisor, so it survives the tool/host
1489
+ process being killed while the supervisor lives. Like E2B's event stream,
1490
+ the pipe does not replay output: once the supervisor dies the buffered
1491
+ output is lost, so the outcome is ``unknown`` (no replay), faithfully.
1492
+ """
1493
+
1494
+ def __init__(self, sandbox_id: str | None, source_config: dict[str, Any] | None = None) -> None:
1495
+ self._sandbox_id = sandbox_id or "fake-local-subprocess"
1496
+ # Test knob: "fail" makes kill return False (refused); "raise" makes it
1497
+ # throw (unknown). Defaults to True (kill succeeds). Production e2b
1498
+ # never uses local_subprocess, so this never affects real backends.
1499
+ self._kill_mode = (source_config or {}).get("kill_succeeds", True)
1500
+
1501
+ def start(self, command, *, cwd, envs, timeout, sandbox_root=None):
1502
+ proc = subprocess.Popen(
1503
+ ["/bin/sh", "-c", command],
1504
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1505
+ start_new_session=True, cwd=cwd or None, env=envs or None,
1506
+ )
1507
+ return proc.pid, _PipeStream(proc), self._sandbox_id
1508
+
1509
+ def reconnect(self, pid, *, timeout):
1510
+ # Cannot reattach to the original pipe; E2B does not replay output.
1511
+ return _PipeStream(None)
1512
+
1513
+ def kill(self, pid):
1514
+ if self._kill_mode == "raise":
1515
+ raise OSError("injected kill failure")
1516
+ if self._kill_mode == "fail":
1517
+ return False
1518
+ try:
1519
+ os.kill(pid, signal.SIGKILL)
1520
+ return True
1521
+ except OSError:
1522
+ return False
1523
+
1524
+
1525
+ class _PipeStream:
1526
+ """Iterable over a local subprocess stdout/stderr, mirroring the SDK handle."""
1527
+
1528
+ def __init__(self, proc: subprocess.Popen | None):
1529
+ self._proc = proc
1530
+ self._result: Any = None
1531
+ # Optional callback: () -> bool. When set, the stream polls it on each
1532
+ # select timeout and stops (without yielding) when it returns True. This
1533
+ # lets the supervisor exit when a kill could not be confirmed rather than
1534
+ # blocking forever on a still-running process. Mirrors the SDK shape:
1535
+ # no idle tick is yielded; the stream simply stops.
1536
+ self.stop_check: Callable[[], bool] | None = None
1537
+
1538
+ @property
1539
+ def pid(self) -> int:
1540
+ return self._proc.pid if self._proc is not None else 0
1541
+
1542
+ def __iter__(self):
1543
+ if self._proc is None:
1544
+ return
1545
+ stdout = self._proc.stdout
1546
+ stderr = self._proc.stderr
1547
+ fds: list[int] = []
1548
+ fd_channel: dict[int, str] = {}
1549
+ if stdout is not None:
1550
+ fds.append(stdout.fileno())
1551
+ fd_channel[stdout.fileno()] = "stdout"
1552
+ if stderr is not None:
1553
+ fds.append(stderr.fileno())
1554
+ fd_channel[stderr.fileno()] = "stderr"
1555
+ # Mirror the real E2B SDK (command_handle.py:54-86): yield only on
1556
+ # non-empty stdout/stderr and set _result on process end without
1557
+ # yielding. A silent long command blocks here; cancellation is handled
1558
+ # by the independent watcher thread, not by polling after a yield. The
1559
+ # select timeout only lets the supervisor notice a stop_check (e.g. an
1560
+ # unconfirmed kill) — it never yields an idle tick.
1561
+ stopped = False
1562
+ while fds:
1563
+ try:
1564
+ ready, _, _ = select.select(fds, [], [], 0.2)
1565
+ except (OSError, ValueError):
1566
+ break
1567
+ if not ready:
1568
+ if self.stop_check is not None and self.stop_check():
1569
+ stopped = True
1570
+ break
1571
+ continue
1572
+ for fd in ready:
1573
+ data = os.read(fd, 65536)
1574
+ if not data:
1575
+ fds = [f for f in fds if f != fd]
1576
+ continue
1577
+ text = data.decode("utf-8", "replace")
1578
+ if fd_channel.get(fd) == "stdout":
1579
+ yield text, None, None
1580
+ else:
1581
+ yield None, text, None
1582
+ if stopped:
1583
+ # The supervisor asked us to stop (timeout deadline reached). If the
1584
+ # kill succeeded the process is dead and wait() returns immediately
1585
+ # with a real exit code. If the kill failed the process is still
1586
+ # alive; wait() times out (0.5s, bounded by the select poll interval)
1587
+ # and _result stays unset so the supervisor reports unknown with
1588
+ # kill_unconfirmed. This is not an arbitrary grace — it is the time
1589
+ # for a SIGKILL to take effect, which is near-instant.
1590
+ try:
1591
+ self._proc.wait(timeout=0.5)
1592
+ self._result = _Result(self._proc.returncode)
1593
+ except subprocess.TimeoutExpired:
1594
+ pass
1595
+ return
1596
+ self._proc.wait()
1597
+ self._result = _Result(self._proc.returncode)
1598
+
1599
+
1600
+ class _Result:
1601
+ def __init__(self, exit_code: int | None) -> None:
1602
+ self.exit_code = exit_code
1603
+
1604
+
1605
+ # ---------------------------------------------------------------------------
1606
+ # Session wrapper (product-path surface).
1607
+ # ---------------------------------------------------------------------------
1608
+
1609
+
1610
+ def e2b_source_config(
1611
+ backend: Any, declaration: BackgroundHostDeclaration | None = None,
1612
+ ) -> dict[str, Any]:
1613
+ """Build the serializable supervisor config from an ``E2BSandboxBackend``.
1614
+
1615
+ When a host declaration is present, its non-sensitive typed
1616
+ ``connection_target`` is carried alongside the credential-bearing
1617
+ ``connection`` so the supervisor freezes the canonical authority into
1618
+ sandbox.json at launch. The key stays in ``connection`` (private, over the
1619
+ stdin pipe only) and is never written to sandbox.json.
1620
+ """
1621
+ from ksadk.sandbox.base import SandboxType # noqa: F401
1622
+
1623
+ spec = backend.spec
1624
+ connection = backend.connection
1625
+ config: dict[str, Any] = {
1626
+ "source_kind": "e2b",
1627
+ "spec": {
1628
+ "template_id": spec.template_id,
1629
+ "sandbox_type": spec.sandbox_type.value,
1630
+ "timeout": spec.timeout,
1631
+ "allow_internet_access": spec.allow_internet_access,
1632
+ "metadata": dict(spec.metadata),
1633
+ "env": dict(spec.env),
1634
+ },
1635
+ "connection": (
1636
+ {
1637
+ "api_url": connection.api_url,
1638
+ "domain": connection.domain,
1639
+ "api_key": connection.api_key.get_secret_value(),
1640
+ "traffic_source": connection.traffic_source,
1641
+ }
1642
+ if connection is not None
1643
+ else None
1644
+ ),
1645
+ }
1646
+ if declaration is not None:
1647
+ config["connection_target"] = declaration.target.to_dict()
1648
+ return config
1649
+
1650
+
1651
+ def _e2b_kill_sandbox(backend: Any) -> Callable[[str], bool]:
1652
+ def kill(sandbox_id: str) -> bool:
1653
+ session = backend.reconnect_session(session_locator=sandbox_id)
1654
+ return bool(session.kill())
1655
+
1656
+ return kill
1657
+
1658
+
1659
+ class E2BBackgroundSession:
1660
+ """Session wrapper exposing the background command lifecycle for E2B.
1661
+
1662
+ Mirrors the subset of ``LocalProcessSandboxSession`` used by the product
1663
+ path: ``start_command`` / ``connect_background_command`` / ``sandbox_id``.
1664
+ """
1665
+
1666
+ def __init__(
1667
+ self,
1668
+ *,
1669
+ store: E2BCommandStore,
1670
+ session_id: str,
1671
+ ):
1672
+ self._store = store
1673
+ self._session_id = session_id
1674
+
1675
+ @classmethod
1676
+ def for_e2b(
1677
+ cls,
1678
+ *,
1679
+ state_root: Path,
1680
+ workspace_root: Path,
1681
+ session_id: str,
1682
+ sandbox_backend: Any,
1683
+ declaration: BackgroundHostDeclaration | None = None,
1684
+ ) -> "E2BBackgroundSession":
1685
+ store = E2BCommandStore(
1686
+ state_root=state_root,
1687
+ workspace_root=workspace_root,
1688
+ session_id=session_id,
1689
+ source_config=e2b_source_config(sandbox_backend, declaration),
1690
+ kill_sandbox=_e2b_kill_sandbox(sandbox_backend),
1691
+ declaration=declaration,
1692
+ )
1693
+ return cls(store=store, session_id=session_id)
1694
+
1695
+ @classmethod
1696
+ def open(
1697
+ cls,
1698
+ *,
1699
+ state_root: Path,
1700
+ workspace_root: Path,
1701
+ session_id: str,
1702
+ source_config: dict[str, Any],
1703
+ kill_sandbox: Callable[[str], None] | None = None,
1704
+ declaration: BackgroundHostDeclaration | None = None,
1705
+ ) -> "E2BBackgroundSession":
1706
+ store = E2BCommandStore(
1707
+ state_root=state_root,
1708
+ workspace_root=workspace_root,
1709
+ session_id=session_id,
1710
+ source_config=source_config,
1711
+ kill_sandbox=kill_sandbox,
1712
+ declaration=declaration,
1713
+ )
1714
+ return cls(store=store, session_id=session_id)
1715
+
1716
+ @property
1717
+ def store(self) -> E2BCommandStore:
1718
+ return self._store
1719
+
1720
+ @property
1721
+ def sandbox_id(self) -> str:
1722
+ path = self._store._sandbox_root / "sandbox.json"
1723
+ return str(_json(path).get("sandbox_id") or "") if path.is_file() else ""
1724
+
1725
+ def start_command(
1726
+ self,
1727
+ command: str,
1728
+ *,
1729
+ timeout: int | None = None,
1730
+ env: dict[str, str] | None = None,
1731
+ cwd: str | None = None,
1732
+ operation_key: str | None = None,
1733
+ ) -> E2BBackgroundCommand:
1734
+ if not str(command or "").strip():
1735
+ raise SandboxError("command is required")
1736
+ if timeout is not None and (type(timeout) is not int or timeout < 1):
1737
+ raise SandboxError("Background process timeout must be a positive integer")
1738
+ return self._store.start(
1739
+ command=command, cwd=cwd, env=env, timeout=timeout or 0, operation_key=operation_key,
1740
+ )
1741
+
1742
+ def connect_background_command(self, command_id: str) -> E2BBackgroundCommand:
1743
+ # The product query path is also the recovery entry: if the prior
1744
+ # supervisor died mid-command, connecting attempts to reattach a
1745
+ # reconnect supervisor (never relaunching the command). This keeps
1746
+ # recovery on the same owned path as ordinary observation rather than
1747
+ # leaving it as an unused standalone helper.
1748
+ return self._store.connect_or_recover(command_id)
1749
+
1750
+ def kill(self) -> bool:
1751
+ # A session-level kill must not destroy the persistent sandbox that may
1752
+ # still host running background commands for this owner.
1753
+ return False
1754
+
1755
+ def terminate_owner(self) -> str:
1756
+ """Explicitly terminate the owner's persistent sandbox.
1757
+
1758
+ Returns:
1759
+ "terminated" — sandbox killed (SDK True).
1760
+ "confirmed_absent" — SDK confirmed not found (SDK False).
1761
+ "not_e2b" — record backend is not e2b.
1762
+ "no_owner" — no command records and no sandbox.json.
1763
+ "unknown" — damaged/empty/legacy/mismatch.
1764
+ "failed" — kill RPC raised an exception.
1765
+ "timeout" — kill RPC did not return in time.
1766
+ Never called on ordinary aclose; only on explicit owner termination.
1767
+ """
1768
+ return self._store.terminate()