deepstrike 0.3.0__tar.gz → 0.3.1__tar.gz

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 (57) hide show
  1. {deepstrike-0.3.0 → deepstrike-0.3.1}/Cargo.lock +9 -8
  2. {deepstrike-0.3.0 → deepstrike-0.3.1}/Cargo.toml +2 -1
  3. {deepstrike-0.3.0 → deepstrike-0.3.1}/PKG-INFO +33 -2
  4. {deepstrike-0.3.0 → deepstrike-0.3.1}/README.md +32 -1
  5. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-bindings-py/Cargo.toml +3 -3
  6. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-bindings-py/src/lib.rs +131 -35
  7. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-kernel/Cargo.toml +1 -1
  8. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-kernel/src/abi.rs +84 -1
  9. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-kernel/src/context.rs +162 -17
  10. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-kernel/src/governance.rs +11 -3
  11. deepstrike-0.3.1/crates/ds-kernel/src/lib.rs +24 -0
  12. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-kernel/src/state_machine.rs +90 -34
  13. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-kernel/src/voice.rs +32 -9
  14. deepstrike-0.3.1/crates/ds-kernel/tests/history_attachments.rs +403 -0
  15. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-kernel/tests/kernel_invariants.rs +91 -27
  16. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-runtime/Cargo.toml +1 -1
  17. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-runtime/src/blob.rs +6 -4
  18. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-runtime/src/cron.rs +8 -5
  19. deepstrike-0.3.1/crates/ds-runtime/src/host_plan.rs +1332 -0
  20. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-runtime/src/lib.rs +4 -2
  21. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-runtime/src/markdown.rs +50 -24
  22. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-runtime/src/outbox.rs +78 -3
  23. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-runtime/src/store/mod.rs +32 -5
  24. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-runtime/src/types.rs +68 -0
  25. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-store-sqlite/Cargo.toml +2 -2
  26. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-store-sqlite/src/schema.rs +1 -0
  27. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-store-sqlite/src/sqlite.rs +703 -347
  28. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-store-sqlite/src/sqlite_ffi.rs +3 -1
  29. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-store-sqlite/tests/runtime_invariants.rs +1190 -21
  30. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-tokenizer/src/lib.rs +6 -6
  31. {deepstrike-0.3.0 → deepstrike-0.3.1}/deepstrike/__init__.py +42 -2
  32. deepstrike-0.3.1/deepstrike/attachments.py +176 -0
  33. {deepstrike-0.3.0 → deepstrike-0.3.1}/deepstrike/driver.py +246 -28
  34. {deepstrike-0.3.0 → deepstrike-0.3.1}/deepstrike/events.py +91 -23
  35. {deepstrike-0.3.0 → deepstrike-0.3.1}/deepstrike/facade.py +422 -98
  36. {deepstrike-0.3.0 → deepstrike-0.3.1}/deepstrike/native.py +27 -7
  37. deepstrike-0.3.1/deepstrike/provider_error.py +334 -0
  38. deepstrike-0.3.1/deepstrike/providers.py +1157 -0
  39. {deepstrike-0.3.0 → deepstrike-0.3.1}/deepstrike/security.py +1 -1
  40. deepstrike-0.3.1/deepstrike/subagents.py +856 -0
  41. {deepstrike-0.3.0 → deepstrike-0.3.1}/deepstrike/tools.py +128 -0
  42. deepstrike-0.3.1/deepstrike/worker.py +797 -0
  43. {deepstrike-0.3.0 → deepstrike-0.3.1}/pyproject.toml +1 -1
  44. deepstrike-0.3.0/crates/ds-kernel/src/lib.rs +0 -23
  45. deepstrike-0.3.0/crates/ds-runtime/src/host_plan.rs +0 -555
  46. deepstrike-0.3.0/deepstrike/providers.py +0 -259
  47. deepstrike-0.3.0/deepstrike/worker.py +0 -523
  48. {deepstrike-0.3.0 → deepstrike-0.3.1}/LICENSE +0 -0
  49. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-bindings-py/LICENSE +0 -0
  50. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-bindings-py/build.rs +0 -0
  51. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-kernel/LICENSE +0 -0
  52. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-runtime/LICENSE +0 -0
  53. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-runtime/src/codec.rs +0 -0
  54. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-store-sqlite/LICENSE +0 -0
  55. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-store-sqlite/src/lib.rs +0 -0
  56. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-tokenizer/Cargo.toml +0 -0
  57. {deepstrike-0.3.0 → deepstrike-0.3.1}/crates/ds-tokenizer/LICENSE +0 -0
@@ -211,7 +211,7 @@ dependencies = [
211
211
 
212
212
  [[package]]
213
213
  name = "deepstrike-kernel"
214
- version = "0.3.0"
214
+ version = "0.3.1"
215
215
  dependencies = [
216
216
  "compact_str",
217
217
  "deepstrike-tokenizer",
@@ -224,7 +224,7 @@ dependencies = [
224
224
 
225
225
  [[package]]
226
226
  name = "deepstrike-runtime"
227
- version = "0.3.0"
227
+ version = "0.3.1"
228
228
  dependencies = [
229
229
  "deepstrike-kernel",
230
230
  "pretty_assertions",
@@ -238,9 +238,10 @@ dependencies = [
238
238
 
239
239
  [[package]]
240
240
  name = "deepstrike-sdk"
241
- version = "0.3.0"
241
+ version = "0.3.1"
242
242
  dependencies = [
243
243
  "async-trait",
244
+ "base64 0.22.1",
244
245
  "deepstrike-kernel",
245
246
  "deepstrike-runtime",
246
247
  "deepstrike-store-sqlite",
@@ -255,7 +256,7 @@ dependencies = [
255
256
 
256
257
  [[package]]
257
258
  name = "deepstrike-store-sqlite"
258
- version = "0.3.0"
259
+ version = "0.3.1"
259
260
  dependencies = [
260
261
  "deepstrike-kernel",
261
262
  "deepstrike-runtime",
@@ -270,7 +271,7 @@ dependencies = [
270
271
 
271
272
  [[package]]
272
273
  name = "deepstrike-tokenizer"
273
- version = "0.3.0"
274
+ version = "0.3.1"
274
275
  dependencies = [
275
276
  "pretty_assertions",
276
277
  "tiktoken-rs",
@@ -311,7 +312,7 @@ dependencies = [
311
312
 
312
313
  [[package]]
313
314
  name = "ds-bindings-node"
314
- version = "0.3.0"
315
+ version = "0.3.1"
315
316
  dependencies = [
316
317
  "deepstrike-kernel",
317
318
  "deepstrike-runtime",
@@ -324,7 +325,7 @@ dependencies = [
324
325
 
325
326
  [[package]]
326
327
  name = "ds-bindings-py"
327
- version = "0.3.0"
328
+ version = "0.3.1"
328
329
  dependencies = [
329
330
  "deepstrike-kernel",
330
331
  "deepstrike-runtime",
@@ -335,7 +336,7 @@ dependencies = [
335
336
 
336
337
  [[package]]
337
338
  name = "ds-bindings-wasm"
338
- version = "0.3.0"
339
+ version = "0.3.1"
339
340
  dependencies = [
340
341
  "deepstrike-kernel",
341
342
  "serde_json",
@@ -3,7 +3,7 @@ resolver = "2"
3
3
  members = ["crates/ds-tokenizer", "crates/ds-kernel", "crates/ds-runtime", "crates/ds-store-sqlite", "crates/ds-bindings-py"]
4
4
 
5
5
  [workspace.package]
6
- version = "0.3.0"
6
+ version = "0.3.1"
7
7
  edition = "2024"
8
8
  repository = "https://github.com/kongusen/deepstrike"
9
9
  license-file = "LICENSE"
@@ -18,6 +18,7 @@ tokio = { version = "1", features = ["full"] }
18
18
  reqwest = { version = "0.12", features = ["json", "stream"] }
19
19
  async-trait = "0.1"
20
20
  sha2 = "0.10"
21
+ base64 = "0.22"
21
22
  time = { version = "0.3", features = ["parsing", "formatting"] }
22
23
 
23
24
  [profile.release]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: deepstrike
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  License-File: LICENSE
5
5
  Summary: DeepStrike v0.3 ultra-thin Python SDK over ds-kernel and ds-runtime
6
6
  Requires-Python: >=3.10
@@ -55,9 +55,40 @@ async def main() -> None:
55
55
  asyncio.run(main())
56
56
  ```
57
57
 
58
+ ## Conversations, Images and Streaming (since 0.3.1)
59
+
60
+ ```python
61
+ from deepstrike import attachment, run_agent, stream_agent, tool, tool_result
62
+
63
+ # Continue an earlier conversation, and send an image with the goal.
64
+ outcome = await run_agent(
65
+ editor,
66
+ "Does this screenshot match the release note?",
67
+ history=[
68
+ {"role": "user", "content": "What shipped in R17?"},
69
+ {"role": "assistant", "content": "Offline search, on May 8."},
70
+ ],
71
+ attachments=[attachment("image/png", open("screen.png", "rb").read())],
72
+ )
73
+
74
+
75
+ # A tool can return images (or PDFs) next to its text.
76
+ @tool("screenshot", "Capture the current page.")
77
+ async def screenshot(args: dict):
78
+ return tool_result("Captured.", [attachment("image/png", await capture())])
79
+
80
+
81
+ # With an event listener, the provider streams: `provider_delta` carries text as it arrives.
82
+ async for ev in stream_agent(editor, "Write the brief."):
83
+ if ev["type"] == "provider_delta" and ev["delta"]["type"] == "text":
84
+ print(ev["delta"]["text"], end="", flush=True)
85
+ ```
86
+
87
+ With a blob store, attachment bytes go to the blob store and runs keep only references. The built-in providers are `OpenAIProvider` (Chat Completions and compatible endpoints), `OpenAIResponsesProvider`, `AnthropicProvider` and `GeminiProvider`. All accept `max_tokens`, `extra_body`, `headers` and `retry`. `OpenAIProvider` sends `max_tokens` as `max_completion_tokens` to api.openai.com (`max_tokens_param` overrides it). It also sends a thinking model's `reasoning_content` (DeepSeek, Kimi, GLM, Qwen) back with the turn that produced it. `AnthropicProvider` caches the system prompt and the conversation so far (`prompt_cache=False` turns it off).
88
+
58
89
  ## Capabilities
59
90
 
60
- - **Host `AgentRuntime` & Pluggable Storage**: `storage = open_local_storage("./.deepstrike")` + `runtime = create_runtime(store=storage.store, blob_store=storage.blob_store)` + `mounted = runtime.mount(editor)` cleanly decouples stateless `AgentSpec` definitions from `SqliteAgentStore` / `LocalFsBlobStore` lifecycle, plus `durable_flow(...)`.
91
+ - **Host `AgentRuntime` & Pluggable Storage**: `storage = open_local_storage("./.deepstrike")` + `runtime = create_runtime(store=storage.store, blob_store=storage.blob_store)` + `mounted = runtime.mount(editor)` cleanly decouples stateless `AgentSpec` definitions from `SqliteAgentStore` / `LocalFsBlobStore` lifecycle, plus `durable_flow(...)`. Outbox `deliver(msg)` callbacks are **at-least-once** and must be idempotent (key external sends on `msg["id"]` or `msg["dedupe_key"]`).
61
92
  - **Execution Security Plane**: `build_isolated_env()`, `McpStdioClient`, `create_sandboxed_exec_tool()`, `EgressPolicyEngine`, `InMemoryCredentialVault`, and fail-closed `create_composite_risk_classifier()`.
62
93
  - **Offline Test Suite**:
63
94
 
@@ -46,9 +46,40 @@ async def main() -> None:
46
46
  asyncio.run(main())
47
47
  ```
48
48
 
49
+ ## Conversations, Images and Streaming (since 0.3.1)
50
+
51
+ ```python
52
+ from deepstrike import attachment, run_agent, stream_agent, tool, tool_result
53
+
54
+ # Continue an earlier conversation, and send an image with the goal.
55
+ outcome = await run_agent(
56
+ editor,
57
+ "Does this screenshot match the release note?",
58
+ history=[
59
+ {"role": "user", "content": "What shipped in R17?"},
60
+ {"role": "assistant", "content": "Offline search, on May 8."},
61
+ ],
62
+ attachments=[attachment("image/png", open("screen.png", "rb").read())],
63
+ )
64
+
65
+
66
+ # A tool can return images (or PDFs) next to its text.
67
+ @tool("screenshot", "Capture the current page.")
68
+ async def screenshot(args: dict):
69
+ return tool_result("Captured.", [attachment("image/png", await capture())])
70
+
71
+
72
+ # With an event listener, the provider streams: `provider_delta` carries text as it arrives.
73
+ async for ev in stream_agent(editor, "Write the brief."):
74
+ if ev["type"] == "provider_delta" and ev["delta"]["type"] == "text":
75
+ print(ev["delta"]["text"], end="", flush=True)
76
+ ```
77
+
78
+ With a blob store, attachment bytes go to the blob store and runs keep only references. The built-in providers are `OpenAIProvider` (Chat Completions and compatible endpoints), `OpenAIResponsesProvider`, `AnthropicProvider` and `GeminiProvider`. All accept `max_tokens`, `extra_body`, `headers` and `retry`. `OpenAIProvider` sends `max_tokens` as `max_completion_tokens` to api.openai.com (`max_tokens_param` overrides it). It also sends a thinking model's `reasoning_content` (DeepSeek, Kimi, GLM, Qwen) back with the turn that produced it. `AnthropicProvider` caches the system prompt and the conversation so far (`prompt_cache=False` turns it off).
79
+
49
80
  ## Capabilities
50
81
 
51
- - **Host `AgentRuntime` & Pluggable Storage**: `storage = open_local_storage("./.deepstrike")` + `runtime = create_runtime(store=storage.store, blob_store=storage.blob_store)` + `mounted = runtime.mount(editor)` cleanly decouples stateless `AgentSpec` definitions from `SqliteAgentStore` / `LocalFsBlobStore` lifecycle, plus `durable_flow(...)`.
82
+ - **Host `AgentRuntime` & Pluggable Storage**: `storage = open_local_storage("./.deepstrike")` + `runtime = create_runtime(store=storage.store, blob_store=storage.blob_store)` + `mounted = runtime.mount(editor)` cleanly decouples stateless `AgentSpec` definitions from `SqliteAgentStore` / `LocalFsBlobStore` lifecycle, plus `durable_flow(...)`. Outbox `deliver(msg)` callbacks are **at-least-once** and must be idempotent (key external sends on `msg["id"]` or `msg["dedupe_key"]`).
52
83
  - **Execution Security Plane**: `build_isolated_env()`, `McpStdioClient`, `create_sandboxed_exec_tool()`, `EgressPolicyEngine`, `InMemoryCredentialVault`, and fail-closed `create_composite_risk_classifier()`.
53
84
  - **Offline Test Suite**:
54
85
 
@@ -17,7 +17,7 @@ sqlite = ["dep:ds-store-sqlite"]
17
17
 
18
18
  [dependencies]
19
19
  pyo3 = { version = "0.23", features = ["extension-module", "abi3-py310", "generate-import-lib"] }
20
- ds-kernel = { package = "deepstrike-kernel", path = "../ds-kernel", version = "0.3.0" }
21
- ds-runtime = { package = "deepstrike-runtime", path = "../ds-runtime", version = "0.3.0" }
22
- ds-store-sqlite = { package = "deepstrike-store-sqlite", path = "../ds-store-sqlite", version = "0.3.0", optional = true }
20
+ ds-kernel = { package = "deepstrike-kernel", path = "../ds-kernel", version = "0.3.1" }
21
+ ds-runtime = { package = "deepstrike-runtime", path = "../ds-runtime", version = "0.3.1" }
22
+ ds-store-sqlite = { package = "deepstrike-store-sqlite", path = "../ds-store-sqlite", version = "0.3.1", optional = true }
23
23
  serde_json.workspace = true
@@ -4,8 +4,9 @@ use std::path::Path;
4
4
  use ds_kernel::{KernelInput, KernelSnapshot, RunConfig, RunKernel, RunPhase, StepOutput};
5
5
  use ds_runtime::blob::{BlobStore, LocalFsBlobStore};
6
6
  use ds_runtime::host_plan::{
7
- compute_step_digest, derive_wakeup_run_id, merge_outbox_policy, plan_approval_resolution,
8
- plan_wakeup, PartialOutboxPolicy, PlanApprovalInput, PlanWakeupInput, StepDigestInput,
7
+ PartialOutboxPolicy, PlanApprovalInput, PlanWakeupInput, StepDigestInput, compute_step_digest,
8
+ derive_wakeup_run_id, merge_outbox_policy, plan_approval_resolution, plan_wakeup,
9
+ resolve_inbox_trigger_trust,
9
10
  };
10
11
  #[cfg(feature = "sqlite")]
11
12
  use ds_runtime::markdown::{load_skills_from_dir, sync_memory_dir_to_store};
@@ -15,9 +16,9 @@ use ds_runtime::store::AgentStore;
15
16
  use ds_runtime::{
16
17
  AckWakeupCmd, AcquireGroupSlotCmd, AuditEventInput, BeginToolEffectCmd, ClaimOutboxCmd,
17
18
  ClaimReadyWakeupCmd, ClaimWakeupCmd, CommitSuspensionCmd, CompleteRunCmd, CreateRunCmd,
18
- CreateRunGroupCmd, EnqueueOutboxCmd, FinishToolEffectCmd, MarkOutboxDeliveredCmd,
19
- MarkOutboxFailedCmd, MemorySlot, NackWakeupCmd, PushInboxCmd, RenewLeaseCmd,
20
- SaveRunCheckpointCmd, UpsertMemoryCmd, UpsertSkillCmd, UpsertTimerCmd,
19
+ CreateRunGroupCmd, EnqueueOutboxCmd, FinishToolEffectCmd, ListToolEffectsCmd,
20
+ MarkOutboxDeliveredCmd, MarkOutboxFailedCmd, MemorySlot, NackWakeupCmd, PushInboxCmd,
21
+ RenewLeaseCmd, SaveRunCheckpointCmd, UpsertMemoryCmd, UpsertSkillCmd, UpsertTimerCmd,
21
22
  };
22
23
  #[cfg(feature = "sqlite")]
23
24
  use ds_store_sqlite::SqliteAgentStore;
@@ -37,10 +38,9 @@ fn phase_str(p: RunPhase) -> &'static str {
37
38
  }
38
39
  }
39
40
 
40
- #[pyclass(unsendable)]
41
+ #[pyclass]
41
42
  pub struct NativeRunKernel {
42
- inner: RunKernel,
43
- initial_step: Option<StepOutput>,
43
+ inner: std::sync::Mutex<(RunKernel, Option<StepOutput>)>,
44
44
  }
45
45
 
46
46
  #[pymethods]
@@ -50,8 +50,7 @@ impl NativeRunKernel {
50
50
  let cfg: RunConfig = serde_json::from_str(config_json).map_err(to_py_err)?;
51
51
  let (kernel, out) = RunKernel::start(cfg, now_ms).map_err(to_py_err)?;
52
52
  Ok(Self {
53
- inner: kernel,
54
- initial_step: Some(out),
53
+ inner: std::sync::Mutex::new((kernel, Some(out))),
55
54
  })
56
55
  }
57
56
 
@@ -60,43 +59,71 @@ impl NativeRunKernel {
60
59
  let snap: KernelSnapshot = serde_json::from_str(snapshot_json).map_err(to_py_err)?;
61
60
  let kernel = RunKernel::restore(snap).map_err(to_py_err)?;
62
61
  Ok(Self {
63
- inner: kernel,
64
- initial_step: None,
62
+ inner: std::sync::Mutex::new((kernel, None)),
65
63
  })
66
64
  }
67
65
 
68
- fn take_initial_step_json(&mut self) -> PyResult<Option<String>> {
69
- match self.initial_step.take() {
66
+ fn take_initial_step_json(&self) -> PyResult<Option<String>> {
67
+ let mut guard = self
68
+ .inner
69
+ .lock()
70
+ .map_err(|_| PyRuntimeError::new_err("kernel mutex poisoned"))?;
71
+ match guard.1.take() {
70
72
  Some(step) => Ok(Some(serde_json::to_string(&step).map_err(to_py_err)?)),
71
73
  None => Ok(None),
72
74
  }
73
75
  }
74
76
 
75
- fn step(&mut self, input_json: &str, now_ms: u64) -> PyResult<String> {
77
+ fn step(&self, input_json: &str, now_ms: u64) -> PyResult<String> {
76
78
  let input: KernelInput = serde_json::from_str(input_json).map_err(to_py_err)?;
77
- let out = self.inner.step(input, now_ms).map_err(to_py_err)?;
79
+ let mut guard = self
80
+ .inner
81
+ .lock()
82
+ .map_err(|_| PyRuntimeError::new_err("kernel mutex poisoned"))?;
83
+ let out = guard.0.step(input, now_ms).map_err(to_py_err)?;
78
84
  serde_json::to_string(&out).map_err(to_py_err)
79
85
  }
80
86
 
81
87
  fn snapshot_json(&self) -> PyResult<String> {
82
- serde_json::to_string(&self.inner.snapshot()).map_err(to_py_err)
88
+ let guard = self
89
+ .inner
90
+ .lock()
91
+ .map_err(|_| PyRuntimeError::new_err("kernel mutex poisoned"))?;
92
+ serde_json::to_string(&guard.0.snapshot()).map_err(to_py_err)
83
93
  }
84
94
 
85
95
  /// Re-issues the effects a restored checkpoint is still waiting on (same call ids).
86
- fn outstanding_effects_json(&mut self) -> PyResult<String> {
87
- let out = self.inner.outstanding_effects().map_err(to_py_err)?;
96
+ fn outstanding_effects_json(&self) -> PyResult<String> {
97
+ let mut guard = self
98
+ .inner
99
+ .lock()
100
+ .map_err(|_| PyRuntimeError::new_err("kernel mutex poisoned"))?;
101
+ let out = guard.0.outstanding_effects().map_err(to_py_err)?;
88
102
  serde_json::to_string(&out).map_err(to_py_err)
89
103
  }
90
104
 
91
- fn phase(&self) -> &'static str {
92
- phase_str(self.inner.phase())
105
+ fn phase(&self) -> PyResult<&'static str> {
106
+ let guard = self
107
+ .inner
108
+ .lock()
109
+ .map_err(|_| PyRuntimeError::new_err("kernel mutex poisoned"))?;
110
+ Ok(phase_str(guard.0.phase()))
93
111
  }
94
112
 
95
- fn turn(&self) -> u32 {
96
- self.inner.turn()
113
+ fn turn(&self) -> PyResult<u32> {
114
+ let guard = self
115
+ .inner
116
+ .lock()
117
+ .map_err(|_| PyRuntimeError::new_err("kernel mutex poisoned"))?;
118
+ Ok(guard.0.turn())
97
119
  }
98
120
  }
99
121
 
122
+ #[pyfunction]
123
+ fn count_tokens(text: &str) -> u32 {
124
+ ds_kernel::count_tokens(text)
125
+ }
126
+
100
127
  #[pyfunction]
101
128
  fn host_derive_wakeup_run_id(batch_json: &str) -> PyResult<String> {
102
129
  let batch = serde_json::from_str(batch_json).map_err(to_py_err)?;
@@ -134,6 +161,14 @@ fn host_compute_step_digest(input_json: &str) -> PyResult<String> {
134
161
  Ok(compute_step_digest(input))
135
162
  }
136
163
 
164
+ #[pyfunction]
165
+ #[pyo3(signature = (source, explicit=None))]
166
+ fn host_resolve_inbox_trigger_trust(source: &str, explicit: Option<&str>) -> PyResult<String> {
167
+ resolve_inbox_trigger_trust(source, explicit)
168
+ .map(str::to_string)
169
+ .map_err(to_py_err)
170
+ }
171
+
137
172
  #[cfg(feature = "sqlite")]
138
173
  #[pyclass]
139
174
  pub struct NativeRuntimeStore {
@@ -236,9 +271,18 @@ impl NativeRuntimeStore {
236
271
  serde_json::to_string(&res).map_err(to_py_err)
237
272
  }
238
273
 
239
- fn poll_due_timers(&self, py: Python<'_>, now_ms: u64) -> PyResult<String> {
274
+ #[pyo3(signature = (now_ms, tenant_id=None))]
275
+ fn poll_due_timers(
276
+ &self,
277
+ py: Python<'_>,
278
+ now_ms: u64,
279
+ tenant_id: Option<&str>,
280
+ ) -> PyResult<String> {
240
281
  let res = py
241
- .allow_threads(|| self.inner.poll_due_timers(now_ms))
282
+ .allow_threads(|| match tenant_id {
283
+ Some(tid) => self.inner.poll_due_timers_for_tenant(tid, now_ms),
284
+ None => self.inner.poll_due_timers(now_ms),
285
+ })
242
286
  .map_err(to_py_err)?;
243
287
  serde_json::to_string(&res).map_err(to_py_err)
244
288
  }
@@ -251,7 +295,12 @@ impl NativeRuntimeStore {
251
295
  serde_json::to_string(&res).map_err(to_py_err)
252
296
  }
253
297
 
254
- fn get_run_group(&self, py: Python<'_>, tenant_id: &str, group_id: &str) -> PyResult<Option<String>> {
298
+ fn get_run_group(
299
+ &self,
300
+ py: Python<'_>,
301
+ tenant_id: &str,
302
+ group_id: &str,
303
+ ) -> PyResult<Option<String>> {
255
304
  match py
256
305
  .allow_threads(|| self.inner.get_run_group(tenant_id, group_id))
257
306
  .map_err(to_py_err)?
@@ -277,8 +326,11 @@ impl NativeRuntimeStore {
277
326
  reason: &str,
278
327
  now_ms: u64,
279
328
  ) -> PyResult<usize> {
280
- py.allow_threads(|| self.inner.cancel_run_group(tenant_id, group_id, reason, now_ms))
281
- .map_err(to_py_err)
329
+ py.allow_threads(|| {
330
+ self.inner
331
+ .cancel_run_group(tenant_id, group_id, reason, now_ms)
332
+ })
333
+ .map_err(to_py_err)
282
334
  }
283
335
 
284
336
  fn create_run(&self, py: Python<'_>, cmd_json: &str) -> PyResult<()> {
@@ -329,9 +381,18 @@ impl NativeRuntimeStore {
329
381
  }
330
382
  }
331
383
 
332
- fn poll_expired_suspensions(&self, py: Python<'_>, now_ms: u64) -> PyResult<String> {
384
+ #[pyo3(signature = (now_ms, tenant_id=None))]
385
+ fn poll_expired_suspensions(
386
+ &self,
387
+ py: Python<'_>,
388
+ now_ms: u64,
389
+ tenant_id: Option<&str>,
390
+ ) -> PyResult<String> {
333
391
  let res = py
334
- .allow_threads(|| self.inner.poll_expired_suspensions(now_ms))
392
+ .allow_threads(|| match tenant_id {
393
+ Some(tid) => self.inner.poll_expired_suspensions_for_tenant(tid, now_ms),
394
+ None => self.inner.poll_expired_suspensions(now_ms),
395
+ })
335
396
  .map_err(to_py_err)?;
336
397
  serde_json::to_string(&res).map_err(to_py_err)
337
398
  }
@@ -356,6 +417,14 @@ impl NativeRuntimeStore {
356
417
  .map_err(to_py_err)
357
418
  }
358
419
 
420
+ fn list_tool_effects(&self, py: Python<'_>, cmd_json: &str) -> PyResult<String> {
421
+ let cmd: ListToolEffectsCmd = serde_json::from_str(cmd_json).map_err(to_py_err)?;
422
+ let res = py
423
+ .allow_threads(|| self.inner.list_tool_effects(cmd))
424
+ .map_err(to_py_err)?;
425
+ serde_json::to_string(&res).map_err(to_py_err)
426
+ }
427
+
359
428
  fn enqueue_outbox(&self, py: Python<'_>, cmd_json: &str) -> PyResult<String> {
360
429
  let cmd: EnqueueOutboxCmd = serde_json::from_str(cmd_json).map_err(to_py_err)?;
361
430
  let res = py
@@ -415,7 +484,12 @@ impl NativeRuntimeStore {
415
484
  }
416
485
  }
417
486
 
418
- fn list_memory_index(&self, py: Python<'_>, tenant_id: &str, agent_id: &str) -> PyResult<String> {
487
+ fn list_memory_index(
488
+ &self,
489
+ py: Python<'_>,
490
+ tenant_id: &str,
491
+ agent_id: &str,
492
+ ) -> PyResult<String> {
419
493
  let res = py
420
494
  .allow_threads(|| self.inner.list_memory_index(tenant_id, agent_id))
421
495
  .map_err(to_py_err)?;
@@ -449,7 +523,10 @@ impl NativeRuntimeStore {
449
523
  None => None,
450
524
  };
451
525
  let res = py
452
- .allow_threads(|| self.inner.list_memory_documents(tenant_id, agent_id, parsed))
526
+ .allow_threads(|| {
527
+ self.inner
528
+ .list_memory_documents(tenant_id, agent_id, parsed)
529
+ })
453
530
  .map_err(to_py_err)?;
454
531
  serde_json::to_string(&res).map_err(to_py_err)
455
532
  }
@@ -462,7 +539,12 @@ impl NativeRuntimeStore {
462
539
  serde_json::to_string(&res).map_err(to_py_err)
463
540
  }
464
541
 
465
- fn list_skill_catalog(&self, py: Python<'_>, tenant_id: &str, agent_id: &str) -> PyResult<String> {
542
+ fn list_skill_catalog(
543
+ &self,
544
+ py: Python<'_>,
545
+ tenant_id: &str,
546
+ agent_id: &str,
547
+ ) -> PyResult<String> {
466
548
  let res = py
467
549
  .allow_threads(|| self.inner.list_skill_catalog(tenant_id, agent_id))
468
550
  .map_err(to_py_err)?;
@@ -514,7 +596,13 @@ impl NativeRuntimeStore {
514
596
  now_ms: u64,
515
597
  ) -> PyResult<usize> {
516
598
  py.allow_threads(|| {
517
- sync_memory_dir_to_store(&self.inner, tenant_id, agent_id, Path::new(dir_path), now_ms)
599
+ sync_memory_dir_to_store(
600
+ &self.inner,
601
+ tenant_id,
602
+ agent_id,
603
+ Path::new(dir_path),
604
+ now_ms,
605
+ )
518
606
  })
519
607
  .map_err(to_py_err)
520
608
  }
@@ -528,7 +616,13 @@ impl NativeRuntimeStore {
528
616
  now_ms: u64,
529
617
  ) -> PyResult<usize> {
530
618
  py.allow_threads(|| {
531
- load_skills_from_dir(&self.inner, tenant_id, scope_id, Path::new(dir_path), now_ms)
619
+ load_skills_from_dir(
620
+ &self.inner,
621
+ tenant_id,
622
+ scope_id,
623
+ Path::new(dir_path),
624
+ now_ms,
625
+ )
532
626
  })
533
627
  .map_err(to_py_err)
534
628
  }
@@ -586,5 +680,7 @@ fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> {
586
680
  m.add_function(wrap_pyfunction!(host_plan_approval, m)?)?;
587
681
  m.add_function(wrap_pyfunction!(host_merge_outbox_policy, m)?)?;
588
682
  m.add_function(wrap_pyfunction!(host_compute_step_digest, m)?)?;
683
+ m.add_function(wrap_pyfunction!(host_resolve_inbox_trigger_trust, m)?)?;
684
+ m.add_function(wrap_pyfunction!(count_tokens, m)?)?;
589
685
  Ok(())
590
686
  }
@@ -14,7 +14,7 @@ default = ["cl100k"]
14
14
  cl100k = ["ds-tokenizer/cl100k"]
15
15
 
16
16
  [dependencies]
17
- ds-tokenizer = { package = "deepstrike-tokenizer", path = "../ds-tokenizer", version = "0.3.0", default-features = false }
17
+ ds-tokenizer = { package = "deepstrike-tokenizer", path = "../ds-tokenizer", version = "0.3.1", default-features = false }
18
18
  serde.workspace = true
19
19
  serde_json.workspace = true
20
20
  compact_str.workspace = true
@@ -61,6 +61,58 @@ pub struct AuthorizedToolCall {
61
61
  pub requires_risk_check: bool,
62
62
  }
63
63
 
64
+ /// Token estimate for an attachment that does not carry its own `token_estimate`. Roughly what
65
+ /// providers charge for a 1,000 × 1,000 pixel image.
66
+ pub const DEFAULT_ATTACHMENT_TOKENS: u32 = 1_600;
67
+
68
+ /// Binary content (an image) that travels with a message's text.
69
+ ///
70
+ /// Exactly one of `data` (base64) and `blob_ref` (a `BlobStore` reference) is set. The kernel never
71
+ /// reads the bytes: it carries the attachment, counts `estimated_tokens` toward the context budget,
72
+ /// and drops attachments of old tool results under context pressure. The host resolves `blob_ref`
73
+ /// into `data` before it hands a request to the provider.
74
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75
+ pub struct Attachment {
76
+ /// MIME type, for example `image/png`.
77
+ pub media_type: String,
78
+ #[serde(default, skip_serializing_if = "Option::is_none")]
79
+ pub data: Option<String>,
80
+ #[serde(default, skip_serializing_if = "Option::is_none")]
81
+ pub blob_ref: Option<String>,
82
+ #[serde(default, skip_serializing_if = "Option::is_none")]
83
+ pub sha256: Option<String>,
84
+ #[serde(default, skip_serializing_if = "Option::is_none")]
85
+ pub byte_len: Option<u64>,
86
+ #[serde(default, skip_serializing_if = "Option::is_none")]
87
+ pub name: Option<String>,
88
+ /// Tokens this attachment costs the provider, when the host knows better than the default.
89
+ #[serde(default, skip_serializing_if = "Option::is_none")]
90
+ pub token_estimate: Option<u32>,
91
+ }
92
+
93
+ impl Attachment {
94
+ pub fn estimated_tokens(&self) -> u32 {
95
+ self.token_estimate.unwrap_or(DEFAULT_ATTACHMENT_TOKENS)
96
+ }
97
+
98
+ /// Why the attachment is malformed, if it is.
99
+ pub fn validate(&self) -> Result<(), String> {
100
+ if self.media_type.trim().is_empty() {
101
+ return Err("attachment media_type must not be empty".into());
102
+ }
103
+ match (&self.data, &self.blob_ref) {
104
+ (Some(_), None) | (None, Some(_)) => Ok(()),
105
+ _ => Err("attachment must set exactly one of data and blob_ref".into()),
106
+ }
107
+ }
108
+ }
109
+
110
+ pub(crate) fn attachments_tokens(attachments: &[Attachment]) -> u32 {
111
+ attachments
112
+ .iter()
113
+ .fold(0u32, |acc, a| acc.saturating_add(a.estimated_tokens()))
114
+ }
115
+
64
116
  /// Content-addressed descriptor for an oversized tool output stored outside the kernel.
65
117
  #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66
118
  pub struct ExternalHandle {
@@ -95,12 +147,16 @@ pub enum ToolResultEnvelope {
95
147
  is_error: bool,
96
148
  #[serde(default)]
97
149
  error_kind: Option<ToolErrorKind>,
150
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
151
+ attachments: Vec<Attachment>,
98
152
  },
99
153
  External {
100
154
  call_id: String,
101
155
  handle: ExternalHandle,
102
156
  #[serde(default)]
103
157
  is_error: bool,
158
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
159
+ attachments: Vec<Attachment>,
104
160
  },
105
161
  AsyncPending {
106
162
  call_id: String,
@@ -117,6 +173,8 @@ pub enum ToolResultEnvelope {
117
173
  call_id: String,
118
174
  child_run_ids: Vec<String>,
119
175
  wait_mode: WaitMode,
176
+ #[serde(default, skip_serializing_if = "Option::is_none")]
177
+ metadata: Option<serde_json::Value>,
120
178
  },
121
179
  }
122
180
 
@@ -163,6 +221,9 @@ pub struct PreparedRequest {
163
221
  pub system_knowledge: String,
164
222
  pub turns: Vec<TurnMessage>,
165
223
  pub state_turn: String,
224
+ /// Attachments of the run's goal; providers send them with `state_turn`.
225
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
226
+ pub state_attachments: Vec<Attachment>,
166
227
  pub tools: Vec<ToolSchema>,
167
228
  pub fingerprint: PrefixFingerprint,
168
229
  pub estimated_tokens: u32,
@@ -176,6 +237,8 @@ pub struct PreparedRequest {
176
237
  pub enum TurnMessage {
177
238
  User {
178
239
  content: String,
240
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
241
+ attachments: Vec<Attachment>,
179
242
  },
180
243
  Assistant {
181
244
  content: String,
@@ -189,6 +252,8 @@ pub enum TurnMessage {
189
252
  tool_name: String,
190
253
  content: String,
191
254
  is_error: bool,
255
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
256
+ attachments: Vec<Attachment>,
192
257
  },
193
258
  }
194
259
 
@@ -318,6 +383,8 @@ pub enum SuspensionKind {
318
383
  call_id: String,
319
384
  child_run_ids: Vec<String>,
320
385
  wait_mode: WaitMode,
386
+ #[serde(default, skip_serializing_if = "Option::is_none")]
387
+ metadata: Option<serde_json::Value>,
321
388
  },
322
389
  }
323
390
 
@@ -798,6 +865,15 @@ impl Default for ContextConfig {
798
865
  pub struct RunConfig {
799
866
  pub run_id: String,
800
867
  pub goal: String,
868
+ /// Attachments of the goal (for example, images the user sent with the request).
869
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
870
+ pub goal_attachments: Vec<Attachment>,
871
+ /// Earlier conversation the run continues from, oldest first. The kernel seeds it into context
872
+ /// as ordinary turns (compacted and archived like the run's own) and then clears this field, so
873
+ /// a snapshot does not carry it twice. A `tool` message must answer a tool call of the
874
+ /// assistant message before it, and every such tool call must be answered.
875
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
876
+ pub history: Vec<TurnMessage>,
801
877
  #[serde(default)]
802
878
  pub system_prompt: String,
803
879
  #[serde(default)]
@@ -826,6 +902,9 @@ pub struct RunConfig {
826
902
  pub context: ContextConfig,
827
903
  #[serde(default)]
828
904
  pub prompt_budget: PromptBudgetConfig,
905
+ /// Opaque host metadata preserved across checkpoints/suspensions (e.g., Role Team reply targets).
906
+ #[serde(default, skip_serializing_if = "Option::is_none")]
907
+ pub host_metadata: Option<serde_json::Value>,
829
908
  }
830
909
 
831
910
  /// Portable logical snapshot of an active or suspended Run.
@@ -864,6 +943,8 @@ pub struct StoredToolResult {
864
943
  pub is_error: bool,
865
944
  #[serde(default)]
866
945
  pub external_handle: Option<ExternalHandle>,
946
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
947
+ pub attachments: Vec<Attachment>,
867
948
  }
868
949
 
869
950
  #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -876,7 +957,9 @@ pub enum PendingEffectKind {
876
957
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
877
958
  risk_check_call_ids: Vec<String>,
878
959
  },
879
- ResourceOp { call_id: String },
960
+ ResourceOp {
961
+ call_id: String,
962
+ },
880
963
  }
881
964
 
882
965
  #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]