From 48d2cee88465bbe9e69eb2c98dd7906072ff8be1 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 21:51:39 +0800 Subject: [PATCH 01/23] refactor(runtime): fold Agent creation and restore into options `Agent::create_session(config, options)` takes the id, the prepare step and the Session extension; `restore_session(id, options)` takes the protocol projection gate. The four creation methods and the two restore methods are deleted, and every caller moves to the options. Tests adapt their call sites only; assertions, expectations and timeouts are unchanged. Refs #2020 --- crates/dim-agent-aimux/tests/model_flow.rs | 52 +- .../tests/model_flow/native.rs | 148 ++++-- .../tests/agent_options_flow.rs | 128 +++++ .../tests/branch_flow.rs | 467 ++++++++++-------- .../tests/capabilities_flow.rs | 1 + .../tests/context_flow.rs | 65 +-- .../context_flow/checkpoint_projection.rs | 2 +- .../tests/context_flow/compacted_bindings.rs | 19 +- .../tests/context_flow/compaction_events.rs | 10 +- .../tests/context_flow/context_reads.rs | 168 ++++--- .../tests/context_flow/digest.rs | 23 +- .../tests/context_flow/manual_compaction.rs | 35 +- .../tests/context_flow/pinning.rs | 47 +- .../tests/context_flow/product_summary.rs | 5 +- .../tests/context_flow/replan.rs | 2 +- .../tests/context_flow/retention.rs | 18 +- .../tests/dispatch_flow.rs | 6 +- .../tests/faces_flow.rs | 13 +- crates/dim-agent-capabilities/tests/flows.rs | 21 +- .../tests/hooks_flow.rs | 56 ++- .../tests/host_flows.rs | 167 ++++--- .../tests/input_flow.rs | 10 +- .../tests/interrupt_flow.rs | 41 +- .../tests/legacy_session_faces.rs | 8 +- .../tests/model_stream_recovery_flow.rs | 36 +- .../tests/permission_flow.rs | 244 ++++++--- .../tests/permission_flow/worktrees.rs | 27 +- .../tests/recall_flow.rs | 13 +- .../tests/review_flows.rs | 112 +++-- .../tests/session_extension.rs | 14 +- .../tests/workspace_files.rs | 17 +- .../tests/questions_flow.rs | 15 +- crates/dim-agent-runtime/src/agent.rs | 128 ++--- crates/dim-agent-runtime/src/assembly.rs | 3 +- .../tests/lifecycle_review.rs | 13 +- .../dim-app-server/examples/restore_cost.rs | 12 +- .../examples/session_typescript_spike.rs | 8 +- .../examples/timeline_acceptance.rs | 17 +- crates/dim-app-server/src/agents.rs | 33 +- .../src/agents/sessions/tests.rs | 6 +- .../dim-app-server/tests/attachments_flow.rs | 2 +- .../dim-app-server/tests/mcp_session_flow.rs | 40 +- .../dim-app-server/tests/read_image_flow.rs | 36 +- .../tests/session_files_flow.rs | 17 +- crates/dim-app-server/tests/settings_flow.rs | 2 +- crates/dim-app-server/tests/storage_flow.rs | 102 ++-- .../tests/storage_flow/prompt_migration.rs | 10 +- .../tests/storage_flow/prompt_recovery.rs | 8 +- .../tests/storage_flow/queue_recovery.rs | 26 +- .../tests/storage_flow/recall.rs | 11 +- .../tests/storage_session_flow.rs | 12 +- .../tests/transport_flow/branch_typescript.rs | 7 +- .../transport_flow/session_typescript.rs | 17 +- .../tests/transport_flow/tree.rs | 5 +- .../tests/transport_flow/worktrees.rs | 2 +- crates/dim-codemode/tests/flow.rs | 15 +- crates/dim-goal/tests/support/parts.rs | 19 +- .../tests/image_flow.rs | 17 +- crates/dim-migration/tests/migration_flow.rs | 9 +- crates/dimcode/tests/cli_flow/hooks.rs | 11 +- .../tests/cli_flow/prompt_migration.rs | 4 +- docs/design/appserver/restore-shared-read.md | 2 +- .../appserver/session-deletion-and-fork.md | 2 +- docs/design/thin-instances.md | 5 +- .../design/appserver/restore-shared-read.md | 2 +- .../appserver/session-deletion-and-fork.md | 2 +- tests/integration/tests/context_input.rs | 4 +- tests/integration/tests/extensions.rs | 83 ++-- tests/integration/tests/interrupt.rs | 6 +- tests/integration/tests/local_execution.rs | 59 ++- tests/integration/tests/local_product.rs | 31 +- tests/integration/tests/local_support/mod.rs | 15 +- tests/integration/tests/minimal_execution.rs | 9 +- tests/integration/tests/named_parts.rs | 19 +- tests/integration/tests/part_registry.rs | 45 +- tests/integration/tests/prompt_boundaries.rs | 10 +- tests/integration/tests/prompt_guide.rs | 107 ++-- tests/integration/tests/prompt_lifecycle.rs | 70 +-- tests/integration/tests/prompt_sources.rs | 12 +- tests/integration/tests/session_lifecycle.rs | 3 +- tests/integration/tests/skills.rs | 13 +- tests/integration/tests/timeline_tail.rs | 4 +- tests/integration/tests/tool_binding.rs | 128 +++-- tests/integration/tests/wait_protocol.rs | 10 +- xtask/src/catalog.rs | 26 +- xtask/src/main.rs | 24 +- xtask/src/plugins.rs | 13 +- xtask/src/scenario_eval.rs | 15 +- 88 files changed, 2141 insertions(+), 1160 deletions(-) create mode 100644 crates/dim-agent-capabilities/tests/agent_options_flow.rs diff --git a/crates/dim-agent-aimux/tests/model_flow.rs b/crates/dim-agent-aimux/tests/model_flow.rs index e10675ca3a..fd52b7b7e2 100644 --- a/crates/dim-agent-aimux/tests/model_flow.rs +++ b/crates/dim-agent-aimux/tests/model_flow.rs @@ -448,7 +448,7 @@ async fn native_http_text_usage_tools_and_continuation_follow_agent_events() { tokio::time::timeout(Duration::from_secs(15), async { let server = TestServer::start().await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent.create_session(session_config(), Default::default()).await.unwrap(); session.submit("text".into(), InputMode::Queue, "main").await.unwrap(); session.idle("main").await.unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -512,7 +512,7 @@ async fn native_http_text_usage_tools_and_continuation_follow_agent_events() { "sessionId": "stale-session", "turnId": "stale-turn", "requestId": "stale-request", "runId": "caller-run", "traceId": "caller-trace", "experiment": "selected" })).unwrap()); - let selected = agent.create_session(explicit).await.unwrap(); + let selected = agent.create_session(explicit, Default::default()).await.unwrap(); selected.submit("text".into(), InputMode::Queue, "main").await.unwrap(); selected.idle("main").await.unwrap(); let events = chain_events(&selected, "main", ..).await.unwrap(); @@ -545,7 +545,10 @@ async fn chat_usage_without_details_records_cache_read_as_unknown() { tokio::time::timeout(Duration::from_secs(15), async { let server = TestServer::start().await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent + .create_session(session_config(), Default::default()) + .await + .unwrap(); session .submit("usage-nodetails".into(), InputMode::Queue, "main") .await @@ -577,7 +580,10 @@ async fn chat_reasoning_tokens_reach_the_recorded_usage() { tokio::time::timeout(Duration::from_secs(15), async { let server = TestServer::start().await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent + .create_session(session_config(), Default::default()) + .await + .unwrap(); session .submit("usage-reasoning".into(), InputMode::Queue, "main") .await @@ -623,7 +629,10 @@ async fn protocol_session( }; let models = Arc::new(AimuxModels::from_config(configuration_of(&base, kind)).unwrap()); let agent = model_agent(models, None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent + .create_session(session_config(), Default::default()) + .await + .unwrap(); (agent, session) } @@ -645,7 +654,10 @@ async fn chat_without_details_records_no_reasoning_count() { tokio::time::timeout(Duration::from_secs(15), async { let server = TestServer::start().await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent + .create_session(session_config(), Default::default()) + .await + .unwrap(); session .submit("usage-nodetails".into(), InputMode::Queue, "main") .await @@ -667,7 +679,10 @@ async fn chat_with_a_zero_reasoning_count_records_zero() { tokio::time::timeout(Duration::from_secs(15), async { let server = TestServer::start().await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent + .create_session(session_config(), Default::default()) + .await + .unwrap(); session .submit("usage-zero".into(), InputMode::Queue, "main") .await @@ -735,7 +750,7 @@ async fn interrupt_releases_native_request_and_keeps_other_branches_usable() { tokio::time::timeout(Duration::from_secs(15), async { let server = TestServer::start().await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent.create_session(session_config(), Default::default()).await.unwrap(); session.submit("wait".into(), InputMode::Queue, "main").await.unwrap(); // Streaming text is progress until its block ends (agent-029). while !session.get::("main").unwrap().is_some_and(|progress| !progress.text.is_empty()) { @@ -758,7 +773,7 @@ async fn failed_native_outputs_do_not_execute_tools_or_invent_usage() { let server = TestServer::start().await; let agent = model_agent(server.models(), None).await; for prompt in ["unauthorized", "truncated", "length"] { - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent.create_session(session_config(), Default::default()).await.unwrap(); session.submit(prompt.into(), InputMode::Queue, "main").await.unwrap(); session.idle("main").await.unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -777,7 +792,12 @@ async fn model_configuration_rejects_unknown_models_before_session_start() { let agent = model_agent(server.models(), None).await; let mut config = session_config(); config.model.model_id = "not-registered".into(); - assert!(agent.create_session(config).await.is_err()); + assert!( + agent + .create_session(config, Default::default()) + .await + .is_err() + ); assert!(agent.sessions().is_empty()); assert!(server.endpoint.requests.lock().unwrap().is_empty()); agent.close().await.unwrap(); @@ -1030,7 +1050,7 @@ async fn before_committed_request_controls_model_settings_and_tool_admission() { let mut builder = builder(models.clone(), Arc::new(MockTools)); builder.require_feature(Feature::new("test.final-model-request").branch("test.final-model-request", move |names| Ok(Box::new(OverrideRequest { remove_tools, timeline: names.key()? })))); let agent = model_agent(models.clone(), Some(builder)).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent.create_session(session_config(), Default::default()).await.unwrap(); session.submit("tool".into(), InputMode::Queue, "main").await.unwrap(); session.idle("main").await.unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -1234,7 +1254,10 @@ async fn recorded_requests_write_their_wire_exchange() { let recording = Recording::start().await; let server = TestServer::start().await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent + .create_session(session_config(), Default::default()) + .await + .unwrap(); session .submit("text".into(), InputMode::Queue, "main") .await @@ -1604,7 +1627,10 @@ async fn a_same_origin_307_or_308_redirect_completes_the_turn_at_its_target() { ] { let server = RedirectServer::start(status, "/v1b/chat/completions").await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent + .create_session(session_config(), Default::default()) + .await + .unwrap(); session .submit("text".into(), InputMode::Queue, "main") .await diff --git a/crates/dim-agent-aimux/tests/model_flow/native.rs b/crates/dim-agent-aimux/tests/model_flow/native.rs index a3b21d10b2..d4f8ff6f42 100644 --- a/crates/dim-agent-aimux/tests/model_flow/native.rs +++ b/crates/dim-agent-aimux/tests/model_flow/native.rs @@ -2051,7 +2051,10 @@ async fn a_stream_event_failure_with_an_unknown_code_is_not_retried() { async fn a_stream_event_status_code_mid_thinking_is_retried_in_place() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit("stream-code-thinking".into(), InputMode::Queue, "main") .await @@ -2091,7 +2094,10 @@ async fn a_stream_event_auth_code_is_rejected_once() { for code in ["401", "403"] { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit(format!("stream-code-{code}"), InputMode::Queue, "main") .await @@ -2127,7 +2133,10 @@ async fn a_stream_event_auth_code_is_rejected_once() { async fn a_stream_event_numeric_type_is_not_a_status_and_is_not_retried() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit("stream-type-502".into(), InputMode::Queue, "main") .await @@ -2167,7 +2176,10 @@ async fn a_stream_event_numeric_type_is_not_a_status_and_is_not_retried() { async fn a_stream_event_status_string_mid_thinking_is_retried_in_place() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit( "stream-code-string-thinking".into(), @@ -2211,7 +2223,10 @@ async fn a_stream_event_status_string_mid_thinking_is_retried_in_place() { async fn a_stream_event_status_code_after_visible_output_is_not_retried() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit("stream-code-visible-502".into(), InputMode::Queue, "main") .await @@ -2254,7 +2269,7 @@ async fn a_4xx_with_a_server_class_label_is_rejected_once() { let responses = NativeServer::start("openai-responses").await; let agent = model_agent(responses.models(), None).await; let session = agent - .create_session(responses.session_config()) + .create_session(responses.session_config(), Default::default()) .await .unwrap(); session @@ -2299,7 +2314,10 @@ async fn a_4xx_with_a_server_class_label_is_rejected_once() { async fn an_empty_reply_is_retried_once_and_the_answer_finishes_the_turn() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit("empty-reply".into(), InputMode::Queue, "main") .await @@ -2338,7 +2356,10 @@ async fn an_empty_reply_is_retried_once_and_the_answer_finishes_the_turn() { async fn an_empty_reply_twice_fails_the_turn_without_a_third_attempt() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit("empty-reply-twice".into(), InputMode::Queue, "main") .await @@ -2380,7 +2401,10 @@ async fn an_empty_reply_twice_fails_the_turn_without_a_third_attempt() { async fn a_thinking_only_reply_fails_after_one_attempt() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit("empty-reply-thinking".into(), InputMode::Queue, "main") .await @@ -2468,7 +2492,10 @@ fn failed_model_outputs(events: &[Arc]) -> Vec<(String, ModelFailure async fn a_content_filter_finish_reason_ends_the_turn_without_a_continuation() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit("finish-filter".into(), InputMode::Queue, "main") .await @@ -2513,7 +2540,10 @@ async fn a_content_filter_finish_reason_ends_the_turn_without_a_continuation() { async fn an_unrecognized_finish_reason_continues_the_turn_once() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit("finish-unrecognized".into(), InputMode::Queue, "main") .await @@ -2554,7 +2584,10 @@ async fn an_unrecognized_finish_reason_continues_the_turn_once() { async fn an_unrecognized_finish_reason_without_announced_calls_does_not_continue() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit("finish-unrecognized-quiet".into(), InputMode::Queue, "main") .await @@ -2594,7 +2627,10 @@ async fn an_unrecognized_finish_reason_without_announced_calls_does_not_continue async fn a_generation_error_finish_reason_continues_the_turn_once() { let server = NativeServer::start("gemini").await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session .submit("finish-error".into(), InputMode::Queue, "main") .await @@ -2636,7 +2672,10 @@ async fn a_generation_error_finish_reason_continues_the_turn_once() { async fn cut_tool_arguments_content_filter_keeps_its_kind() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit( "cut-tool-arguments-content-filter".into(), @@ -2708,7 +2747,10 @@ async fn cut_tool_arguments_content_filter_keeps_its_kind() { async fn cut_tool_arguments_without_a_filter_stay_malformed() { let chat = NativeServer::start("openai-chat").await; let agent = model_agent(chat.models(), None).await; - let session = agent.create_session(chat.session_config()).await.unwrap(); + let session = agent + .create_session(chat.session_config(), Default::default()) + .await + .unwrap(); session .submit( "cut-tool-arguments-without-filter".into(), @@ -3230,7 +3272,10 @@ async fn four_native_apis_preserve_signed_blocks_and_tool_continuation() { for kind in ["openai-chat","openai-responses","anthropic","gemini"] { let server = NativeServer::start(kind).await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session.input(InputMessageData { user: Some(UserInput { content: vec![ ContentBlock::Text { text: "tool".into() }, @@ -3448,7 +3493,10 @@ async fn anthropic_requests_mark_the_system_and_the_conversation_tail_for_cache( tokio::time::timeout(Duration::from_secs(30), async { let server = NativeServer::start("anthropic").await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session .submit("tool".into(), InputMode::Queue, "main") .await @@ -3533,7 +3581,10 @@ async fn explicit_system_breakpoints_stay_within_the_four_breakpoint_limit() { }, )); let agent = model_agent(models, Some(builder)).await; - let session = agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session .submit("tool".into(), InputMode::Queue, "main") .await @@ -3657,7 +3708,10 @@ async fn native_unsigned_thinking_completes_and_is_not_replayed() { for kind in ["anthropic", "openai-responses"] { let server = NativeServer::start(kind).await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session .submit("missing-continuation".into(), InputMode::Queue, "main") .await @@ -3905,7 +3959,10 @@ async fn native_content_keeps_unsigned_thinking_and_respects_committed_tools() { let mut custom=builder(models.clone(),Arc::new(MockTools)); custom.require_feature(Feature::new("test.rewrite-native").branch("test.rewrite-native", move|names|Ok(Box::new(RewriteNative{complete,timeline:names.key()?})))); let agent=model_agent(models.clone(),Some(custom)).await; - let session=agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session.submit("tool".into(),InputMode::Queue,"main").await.unwrap();session.idle("main").await.unwrap(); let events=chain_events(&session, "main", ..).await.unwrap(); assert!(events.iter().any(|e|matches!(&e.kind,EventKind::ModelOutputEnd(data) if matches!(data.outcome,ModelOutputOutcome::Failed{..})))); @@ -3915,7 +3972,10 @@ async fn native_content_keeps_unsigned_thinking_and_respects_committed_tools() { } let custom=builder(models.clone(),Arc::new(ErrorEcho)); let agent = model_agent(models, Some(custom)).await; - let session = agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session.submit("tool".into(),InputMode::Queue,"main").await.unwrap();session.idle("main").await.unwrap(); let requests=server.endpoint.requests.lock().unwrap().clone(); let last=&requests.last().unwrap().2; @@ -3925,7 +3985,10 @@ async fn native_content_keeps_unsigned_thinking_and_respects_committed_tools() { for kind in ["anthropic", "openai-responses"] { let server = NativeServer::start(kind).await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session.submit("missing-continuation".into(),InputMode::Queue,"main").await.unwrap(); session.idle("main").await.unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -3971,7 +4034,10 @@ async fn native_content_keeps_unsigned_thinking_and_respects_committed_tools() { ] { let server = NativeServer::start(kind).await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session.submit(prompt.into(), InputMode::Queue, "main").await.unwrap(); session.idle("main").await.unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -4005,7 +4071,10 @@ async fn native_content_keeps_unsigned_thinking_and_respects_committed_tools() { for prompt in ["native-refusal", "native-refusal-done", "native-refusal-empty"] { let server = NativeServer::start("openai-responses").await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session.submit(prompt.into(), InputMode::Queue, "main").await.unwrap(); session.idle("main").await.unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -4044,7 +4113,10 @@ async fn native_content_keeps_unsigned_thinking_and_respects_committed_tools() { for prompt in ["native-text-tool", "native-thought-tool"] { let server = NativeServer::start("gemini").await; let agent = model_agent(server.models(), None).await; - let session = agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session.submit(prompt.into(), InputMode::Queue, "main").await.unwrap(); session.idle("main").await.unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -4066,7 +4138,7 @@ async fn native_content_keeps_unsigned_thinking_and_respects_committed_tools() { } let server = NativeServer::start("gemini").await; let agent = model_agent(server.models(),None).await; - agent.create_session(server.session_config()).await.unwrap(); + agent.create_session(server.session_config(), Default::default()).await.unwrap(); let host = agent.root().get::().unwrap(); for (config, expected_budget) in [ (json!({"reasoning":{"enabled":true,"budgetTokens":0}}),None), @@ -4137,7 +4209,7 @@ async fn native_model_switch_keeps_stored_thinking_for_its_protocol() { ); let agent = model_agent(models, None).await; let session = agent - .create_session(claude.session_config()) + .create_session(claude.session_config(), Default::default()) .await .unwrap(); session @@ -4456,7 +4528,10 @@ async fn tool_result_images_take_the_form_its_protocol_defines() { let models = server.models(); let agent = model_agent(models.clone(), Some(builder(models, Arc::new(ImageEcho)))).await; - let session = agent.create_session(server.session_config()).await.unwrap(); + let session = agent + .create_session(server.session_config(), Default::default()) + .await + .unwrap(); session.submit("call the tool".into(), InputMode::Queue, "main").await.unwrap(); session.idle("main").await.unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -4587,7 +4662,7 @@ async fn a_model_without_image_input_gets_references_and_unreferenceable_image_p reasoning: None, service_tier: None, }); - let session = agent.create_session(config).await.unwrap(); + let session = agent.create_session(config, Default::default()).await.unwrap(); session.submit("call the tool".into(), InputMode::Queue, "main").await.unwrap(); session.idle("main").await.unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -5418,7 +5493,10 @@ async fn gemini_signature_after_unsigned_text_signs_that_text_and_replays() { .unwrap(), ); let agent = model_agent(models, None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent + .create_session(session_config(), Default::default()) + .await + .unwrap(); session .submit("first".into(), InputMode::Queue, "main") .await @@ -6381,7 +6459,10 @@ async fn gemini_a_signed_part_closes_its_text_block_and_replays_the_split() { .unwrap(), ); let agent = model_agent(models, None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent + .create_session(session_config(), Default::default()) + .await + .unwrap(); session .submit("first".into(), InputMode::Queue, "main") .await @@ -6507,7 +6588,10 @@ async fn gemini_two_signed_blocks_keep_their_own_text_and_signature() { .unwrap(), ); let agent = model_agent(models, None).await; - let session = agent.create_session(session_config()).await.unwrap(); + let session = agent + .create_session(session_config(), Default::default()) + .await + .unwrap(); session .submit("first".into(), InputMode::Queue, "main") .await diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs new file mode 100644 index 0000000000..fcdd18d2ff --- /dev/null +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -0,0 +1,128 @@ +use dim_agent_capabilities::defaults; +use dim_agent_runtime::testing::MinimalHost; +use dim_agent_runtime::{ + AgentBuilder, AgentConfig, CreateSessionOptions, MemoryTimelineStore, RestoreSessionOptions, + SessionConfig, TimelineStore, TimelineStoreBinding, +}; +use rutis::host::DynPlugin; +use rutis::{Ctx, Plugin}; +use std::sync::{ + Arc, + atomic::{AtomicU32, Ordering}, +}; + +const GROUP: &str = "options-probe"; + +struct Probe { + value: u32, + seen: Arc, +} +impl Plugin for Probe { + type Deps = (); + fn name(&self) -> &str { + "options-probe" + } + async fn apply(&self, _ctx: &Ctx, (): Self::Deps) -> rutis::Result { + self.seen.store(self.value, Ordering::SeqCst); + Ok(()) + } +} + +fn builder(store: &Arc, seen: Arc) -> AgentBuilder { + let mut builder = AgentBuilder::new(AgentConfig::default()); + defaults::mock_hosts(&mut builder); + defaults::install(&mut builder); + builder + .timeline_store(TimelineStoreBinding::new(store.clone())) + .session_extension_part::(GROUP, "options-probe", move |_, value: &u32| { + Ok(Box::new(Probe { + value: *value, + seen: seen.clone(), + }) as Box) + }); + builder +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn create_and_restore_options_apply_their_fields() { + let seen = Arc::new(AtomicU32::new(0)); + let store = Arc::new(MemoryTimelineStore::default()); + let agent = MinimalHost::start(&builder(&store, seen.clone())) + .await + .unwrap(); + + let prepared_id = "prepared-session"; + let config = SessionConfig::default(); + let prepare = { + let store = store.clone(); + let id = prepared_id.to_owned(); + let config = config.clone(); + Box::pin(async move { + store.create_session(&id, &config).await?; + Ok(()) + }) + }; + let session = agent + .create_session( + config, + CreateSessionOptions::default() + .prepare(prepared_id, prepare) + .extension(GROUP, 7_u32), + ) + .await + .unwrap(); + assert_eq!( + session.id(), + prepared_id, + "a prepared creation is named by the id its prepare step commits" + ); + assert_eq!( + seen.load(Ordering::SeqCst), + 7, + "the Session loaded the extension's value" + ); + session.close().await.unwrap(); + + let session = agent + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().id("explicit-session"), + ) + .await + .unwrap(); + assert_eq!( + session.id(), + "explicit-session", + "the options name a plain creation" + ); + session.close().await.unwrap(); + + store + .create_session("stored", &SessionConfig::default()) + .await + .unwrap(); + let session = agent + .restore_session("stored".into(), RestoreSessionOptions::default()) + .await + .unwrap(); + assert!( + session.config().excluded_tools.is_empty(), + "without a protocol version the stored configuration is restored as written" + ); + session.close().await.unwrap(); + + let session = agent + .restore_session( + "stored".into(), + RestoreSessionOptions::default().protocol_version(1), + ) + .await + .unwrap(); + assert_eq!( + session.config().excluded_tools, + vec!["codemode".to_owned()], + "a protocol version below 4 keeps the codemode tool out" + ); + session.close().await.unwrap(); + agent.close().await.unwrap(); +} diff --git a/crates/dim-agent-capabilities/tests/branch_flow.rs b/crates/dim-agent-capabilities/tests/branch_flow.rs index aac15e54cd..d2fb47b13a 100644 --- a/crates/dim-agent-capabilities/tests/branch_flow.rs +++ b/crates/dim-agent-capabilities/tests/branch_flow.rs @@ -904,7 +904,9 @@ async fn restore_settles_interrupted_creates_and_keeps_failed_directories_inacti let batch = vec![Ok(vec![1]), Ok(vec![1]), Ok(vec![1, 2]), Ok(vec![2])]; for _ in 0..2 { let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.restore_session("saved".into())).await.unwrap(); + let session = soon(agent.restore_session("saved".into(), Default::default())) + .await + .unwrap(); soon(session.idle("main")).await.unwrap(); let opening = probe.opening_reads.lock().unwrap().pop().unwrap(); let main = probe.main_timeline.lock().unwrap().clone().unwrap(); @@ -1066,7 +1068,9 @@ async fn a_restart_completes_an_end_without_its_result() { let mut builder = builder(&probe); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.restore_session("saved".into())).await.unwrap(); + let session = soon(agent.restore_session("saved".into(), Default::default())) + .await + .unwrap(); soon(session.idle("main")).await.unwrap(); assert_eq!( session @@ -1249,7 +1253,9 @@ async fn a_restart_completes_an_interrupted_descendants_end_first() { let mut builder = builder(&Arc::new(Probe::default())); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.restore_session("saved".into())).await.unwrap(); + let session = soon(agent.restore_session("saved".into(), Default::default())) + .await + .unwrap(); soon(session.idle("main")).await.unwrap(); assert_eq!( session @@ -1746,7 +1752,9 @@ async fn a_restore_reads_a_line_end_in_one_page_and_no_range() { let counting = Arc::new(TestStore::refusing_ranges(store)); let builder = builder_with_store(&Arc::new(Probe::default()), counting.clone()); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.restore_session("saved".into())).await.unwrap(); + let session = soon(agent.restore_session("saved".into(), Default::default())) + .await + .unwrap(); soon(session.idle("main")).await.unwrap(); assert_eq!(counting.range_reads(), 0, "a restore reads no stored range"); @@ -1925,7 +1933,9 @@ async fn an_end_at_load_finds_the_restored_line_published() { }, )); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.restore_session("saved".into())).await.unwrap(); + let session = soon(agent.restore_session("saved".into(), Default::default())) + .await + .unwrap(); soon(session.idle("main")).await.unwrap(); soon(async { while ends.lock().unwrap().is_empty() { @@ -1969,7 +1979,7 @@ async fn an_end_refuses_a_line_that_is_still_opening() { let probe = Arc::new(Probe::default()); probe.delay_child.store(true, Ordering::SeqCst); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.idle("main")).await.unwrap(); @@ -2034,7 +2044,7 @@ async fn a_line_that_is_ending_opens_no_more_lines() { let mut builder = builder(&probe); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "hold the dispatcher").await; @@ -2117,7 +2127,7 @@ async fn wait_create(session: &Session, after: u64) -> Arc { async fn ending_a_line_ends_its_children_first_and_records_one_result_each() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.submit("ancestor".into(), InputMode::Queue, "main")) @@ -2242,7 +2252,7 @@ async fn ending_a_line_ends_its_children_first_and_records_one_result_each() { async fn a_branch_this_session_never_had_is_unknown() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); assert!(matches!( @@ -2260,7 +2270,7 @@ async fn a_branch_this_session_never_had_is_unknown() { async fn an_ancestors_end_closes_a_descendants_pending_tool_end() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let ancestor = soon(session.branch("main".into(), 0, options("ancestor"))) @@ -2363,7 +2373,7 @@ async fn an_ancestors_end_closes_a_descendants_pending_tool_end() { async fn an_ancestors_end_names_itself_on_every_descendant() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let ancestor = soon(session.branch("main".into(), 0, options("ancestor"))) @@ -2419,7 +2429,7 @@ async fn an_ancestors_end_names_itself_on_every_descendant() { async fn a_line_that_ended_itself_names_itself_on_its_descendants() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.idle("main")).await.unwrap(); @@ -2502,7 +2512,7 @@ async fn a_line_that_ended_itself_names_itself_on_its_descendants() { async fn a_line_cannot_open_under_an_ending_ancestor() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.idle("main")).await.unwrap(); @@ -2584,7 +2594,7 @@ async fn a_line_cannot_open_under_an_ending_ancestor() { async fn ending_a_line_waits_for_a_child_still_building() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.idle("main")).await.unwrap(); @@ -2659,7 +2669,7 @@ async fn a_failed_child_of_an_ended_parent_stays_unknown_after_a_restart() { let mut build = builder(&probe); build.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&build).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.idle("main")).await.unwrap(); @@ -2721,7 +2731,9 @@ async fn a_failed_child_of_an_ended_parent_stays_unknown_after_a_restart() { let mut build = builder(&probe); build.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&build).await.unwrap(); - let session = soon(agent.restore_session(id)).await.unwrap(); + let session = soon(agent.restore_session(id, Default::default())) + .await + .unwrap(); assert_eq!(session.ended_head(&child), None); let commands = probe.commands.lock().unwrap().clone().unwrap(); assert!(commands.info(child.clone()).is_err()); @@ -2732,7 +2744,7 @@ async fn a_failed_child_of_an_ended_parent_stays_unknown_after_a_restart() { async fn a_host_line_opens_with_its_identity_block_and_the_creator_prompt() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = soon(session.branch("main".into(), 0, options("what this line is for"))) @@ -2817,7 +2829,7 @@ async fn a_line_reports_the_source_its_create_recorded_open_or_restored() { }), ); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.submit("ancestor".into(), InputMode::Queue, "main")) @@ -2864,7 +2876,9 @@ async fn a_line_reports_the_source_its_create_recorded_open_or_restored() { }), ); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.restore_session(id)).await.unwrap(); + let session = soon(agent.restore_session(id, Default::default())) + .await + .unwrap(); assert_eq!(source(session.branches(), &child), Some(host)); assert_eq!(source(session.branches(), "main"), None); assert_eq!( @@ -2886,7 +2900,7 @@ async fn a_line_reports_the_source_its_create_recorded_open_or_restored() { async fn data_creation_releases_its_cancellation_wait_when_the_caller_leaves() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); pause(&session, &probe).await; @@ -2947,7 +2961,7 @@ async fn data_creation_releases_its_cancellation_wait_when_the_caller_leaves() { async fn final_prompt_position_and_fixed_ancestor_prefix_drive_creation() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -3084,7 +3098,7 @@ async fn final_prompt_position_and_fixed_ancestor_prefix_drive_creation() { async fn delayed_create_uses_its_anchor_and_survives_an_abandoned_waiter() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); pause(&session, &probe).await; @@ -3139,7 +3153,7 @@ async fn delayed_create_uses_its_anchor_and_survives_an_abandoned_waiter() { async fn close_releases_an_unconsumed_create_without_waiting_for_dispatch() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); pause(&session, &probe).await; @@ -3178,7 +3192,7 @@ async fn close_releases_an_unconsumed_create_without_waiting_for_dispatch() { async fn parent_close_waits_for_dispatch_before_releasing_branch_reservations() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); pause(&session, &probe).await; @@ -3239,7 +3253,7 @@ async fn parent_close_waits_for_dispatch_before_releasing_branch_reservations() async fn failed_build_rolls_back_and_releases_capacity_even_without_its_waiter() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); probe.fail_child.store(true, Ordering::SeqCst); @@ -3312,7 +3326,7 @@ async fn failed_build_rolls_back_and_releases_capacity_even_without_its_waiter() async fn candidates_remain_private_until_the_initial_input_is_accepted() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); *probe.session.lock().unwrap() = Some(session.clone()); @@ -3367,7 +3381,7 @@ async fn candidates_remain_private_until_the_initial_input_is_accepted() { async fn invalid_batch_cut_settles_creation_without_faulting_the_session() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let timeline = probe.main_timeline.lock().unwrap().clone().unwrap(); @@ -3415,7 +3429,7 @@ async fn invalid_batch_cut_settles_creation_without_faulting_the_session() { async fn model_output_cannot_be_inherited_as_an_asymmetric_prefix() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -3462,7 +3476,7 @@ async fn a_tool_call_on_main_opens_a_line_before_its_own_request() { let probe = Arc::new(Probe::default()); let agent = MinimalHost::start(&builder(&probe)).await.unwrap(); let root = agent.root().clone(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let broadcast = Broadcast::listen(&root, session.id()); @@ -3771,7 +3785,7 @@ async fn settle_line(session: &Session, branch: &str) -> (u64, String, u64) { async fn a_refused_branch_call_writes_nothing() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let host = soon(session.branch("main".into(), 0, options("host line"))) @@ -3971,7 +3985,7 @@ async fn a_refused_branch_call_writes_nothing() { async fn a_line_messages_and_reads_its_parent_and_the_lines_it_opened() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let tool_line = open_line(&session, "opened with the tool").await; @@ -4197,7 +4211,7 @@ async fn a_line_messages_and_reads_its_parent_and_the_lines_it_opened() { async fn a_host_line_sends_the_line_it_was_cut_from_no_message() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let host = soon(session.branch("main".into(), 0, options("a plugin line"))) @@ -4280,7 +4294,7 @@ async fn messages_written(session: &Session, lines: &[&String]) -> Vec { async fn a_sibling_or_grandparent_is_refused_with_nothing_written() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let sibling = |prompt: &'static str| { @@ -4388,7 +4402,7 @@ async fn a_sibling_or_grandparent_is_refused_with_nothing_written() { async fn session_close_cancels_an_active_build_and_waits_for_rollback() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); probe.delay_child.store(true, Ordering::SeqCst); @@ -4486,7 +4500,7 @@ async fn quiet(session: &Session, line: &str) { async fn the_root_lists_its_open_tool_lines_under_the_roster_key() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let first = open_line(&session, "first purpose").await; @@ -4552,7 +4566,7 @@ async fn a_configured_roster_closing_reaches_the_roster() { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -4592,7 +4606,7 @@ async fn a_configured_note_block_reaches_the_note() { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "the configured line").await; @@ -4649,7 +4663,7 @@ async fn the_default_configuration_writes_no_guidance_block() { let agent = MinimalHost::start(&builder_with_branch_config(&probe, config)) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, purpose).await; @@ -4709,7 +4723,7 @@ async fn a_user_lines_default_note_reaches_the_model_request() { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let cut = idle_cut(&session, "main").await; @@ -4798,7 +4812,7 @@ async fn a_former_default_tool_lines_note_reaches_the_model_request() { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "the parser race").await; @@ -4888,7 +4902,7 @@ async fn an_appended_note_does_not_wake_the_idle_former_default() { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "the parser race").await; @@ -4973,7 +4987,7 @@ async fn a_configured_description_reaches_the_request_declaration() { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.submit("hello".into(), InputMode::Queue, "main")) @@ -5040,7 +5054,7 @@ async fn last_system(session: &Session, branch: &str) -> String { async fn each_line_carries_the_entry_of_the_marker_its_part_writes() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -5108,7 +5122,7 @@ async fn system_at(session: &Session, branch: &str, sequence: u64) -> String { async fn a_childs_first_system_is_its_parents_at_the_cut() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -5135,7 +5149,7 @@ async fn a_childs_first_system_is_its_parents_at_the_cut() { async fn a_line_names_the_stale_file_failure_the_way_the_tool_reports_it() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -5212,7 +5226,7 @@ async fn file_call( async fn the_branch_tool_declares_its_actions_and_modes() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.submit("hello".into(), InputMode::Queue, "main")) @@ -5283,7 +5297,7 @@ async fn the_branch_tool_declares_its_actions_and_modes() { async fn the_branch_tool_reports_invalid_arguments() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); for (arguments, text) in [ @@ -5314,7 +5328,7 @@ async fn the_branch_tool_reports_invalid_arguments() { async fn a_title_is_refused_with_what_names_a_line() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let refused = tool_call( @@ -5412,7 +5426,7 @@ async fn a_title_is_refused_with_what_names_a_line() { async fn a_message_reaches_its_receiver_in_the_mode_it_asked_for() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -5582,7 +5596,7 @@ async fn a_message_reaches_its_receiver_in_the_mode_it_asked_for() { async fn a_first_parent_read_starts_after_the_cut() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.submit("BEFORE-THE-CUT".into(), InputMode::Queue, "main")) @@ -5681,15 +5695,18 @@ async fn a_parent_read_carries_the_effects_its_tool_results_declared() { let mut builder = builder_with_tools(&probe, Arc::new(EffectTools)); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig { - tools: Some(vec![ - "echo".into(), - "wait".into(), - "branch".into(), - "touch".into(), - ]), - ..SessionConfig::default() - })) + let session = soon(agent.create_session( + SessionConfig { + tools: Some(vec![ + "echo".into(), + "wait".into(), + "branch".into(), + "touch".into(), + ]), + ..SessionConfig::default() + }, + Default::default(), + )) .await .unwrap(); soon(session.submit("BEFORE-THE-CUT".into(), InputMode::Queue, "main")) @@ -5753,7 +5770,7 @@ async fn a_parent_read_carries_the_effects_its_tool_results_declared() { async fn an_after_below_the_cut_is_raised_to_it() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.submit("BEFORE-THE-CUT".into(), InputMode::Queue, "main")) @@ -5793,7 +5810,7 @@ async fn an_after_below_the_cut_is_raised_to_it() { async fn an_after_past_the_targets_head_is_refused_and_the_cursor_stays() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); // A host line writes no idle notice, so main has no turn in flight and @@ -5836,7 +5853,7 @@ async fn an_after_past_the_targets_head_is_refused_and_the_cursor_stays() { async fn a_read_without_after_continues_from_the_last_page_in_both_directions() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "check the parser").await; @@ -5901,7 +5918,7 @@ async fn a_read_without_after_continues_from_the_last_page_in_both_directions() async fn main_re_reads_a_line_from_zero_and_the_cursor_follows_that_read() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "check the parser").await; @@ -5982,7 +5999,7 @@ async fn a_read_cursor_survives_a_restore() { let agent = MinimalHost::start(&builder_with_store(&probe, store.clone())) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let id = session.id().to_string(); @@ -6000,7 +6017,9 @@ async fn a_read_cursor_survives_a_restore() { let agent = MinimalHost::start(&builder_with_store(&probe, store)) .await .unwrap(); - let session = soon(agent.restore_session(id)).await.unwrap(); + let session = soon(agent.restore_session(id, Default::default())) + .await + .unwrap(); until_branch(&session, &child).await; soon(session.idle(&child)).await.unwrap(); let page = page_of(&tool_call(&session, &child, r#"{"action":"read","branch":"main"}"#).await); @@ -6017,7 +6036,7 @@ async fn a_read_cursor_survives_a_restore() { async fn an_idle_line_is_told_its_parent_moved_without_being_woken() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -6111,7 +6130,7 @@ async fn a_running_line_gets_the_block_with_its_next_request_once() { let agent = MinimalHost::start(&builder_with_gates(&probe, &gates)) .await .unwrap(); - let session = patient(agent.create_session(SessionConfig::default())) + let session = patient(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -6220,7 +6239,7 @@ async fn two_parent_turns_while_the_line_is_idle_write_one_block() { let agent = MinimalHost::start(&builder_with_gates(&probe, &gates)) .await .unwrap(); - let session = patient(agent.create_session(SessionConfig::default())) + let session = patient(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -6292,7 +6311,7 @@ async fn a_move_while_a_block_is_held_is_written_after_the_block_is_consumed() { let agent = MinimalHost::start(&builder_with_gates(&probe, &gates)) .await .unwrap(); - let session = patient(agent.create_session(SessionConfig::default())) + let session = patient(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); // A host line writes no idle notice, so main's turn stays where the test @@ -6337,7 +6356,7 @@ async fn a_move_while_a_block_is_held_is_written_after_the_block_is_consumed() { async fn a_move_while_a_block_is_held_is_written_after_the_block_is_deleted() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_host_line(&session, "main", "watch the tests").await; @@ -6383,7 +6402,7 @@ async fn a_move_while_a_block_is_held_is_written_after_the_block_is_interrupted( let agent = MinimalHost::start(&builder_with_gates(&probe, &gates)) .await .unwrap(); - let session = patient(agent.create_session(SessionConfig::default())) + let session = patient(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_host_line(&session, "main", "watch the tests").await; @@ -6472,7 +6491,7 @@ async fn a_nested_line_is_told_its_own_parent_at_open() { ); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let outer = open_host_line(&session, "main", "outer line").await; @@ -6640,7 +6659,7 @@ async fn a_nested_line_whose_opening_read_fails_is_a_failed_create() { ); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let outer = open_host_line(&session, "main", "outer line").await; @@ -6766,7 +6785,9 @@ async fn a_restore_writes_a_due_parent_block_once_and_none_without_movement() { let agent = MinimalHost::start(&builder_with_store(&probe, store.clone())) .await .unwrap(); - let session = soon(agent.restore_session("saved".into())).await.unwrap(); + let session = soon(agent.restore_session("saved".into(), Default::default())) + .await + .unwrap(); let events = until_events(&session, "line", |events| { !parent_block_events(events).is_empty() }) @@ -6876,7 +6897,9 @@ async fn a_restore_writes_a_due_parent_block_once_and_none_without_movement() { let agent = MinimalHost::start(&builder_with_store(&probe, store)) .await .unwrap(); - let session = soon(agent.restore_session("saved".into())).await.unwrap(); + let session = soon(agent.restore_session("saved".into(), Default::default())) + .await + .unwrap(); until_branch(&session, "line").await; soon(session.idle("line")).await.unwrap(); tokio::time::sleep(Duration::from_millis(100)).await; @@ -6965,7 +6988,9 @@ async fn an_ending_line_and_main_get_no_parent_block() { let agent = MinimalHost::start(&builder_with_store(&probe, store)) .await .unwrap(); - let session = soon(agent.restore_session("saved".into())).await.unwrap(); + let session = soon(agent.restore_session("saved".into(), Default::default())) + .await + .unwrap(); until_branch(&session, "main").await; soon(session.idle("main")).await.unwrap(); until_branch(&session, "line").await; @@ -7000,7 +7025,7 @@ async fn the_parent_block_replays_after_a_compaction() { ); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "compact my line").await; @@ -7035,7 +7060,7 @@ async fn the_parent_block_replays_after_a_compaction() { async fn the_creating_turn_alone_does_not_tell_the_line() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -7065,7 +7090,7 @@ async fn a_second_tool_call_in_the_creating_turn_tells_the_line() { let agent = MinimalHost::start(&builder_with_model(&probe, Arc::new(ActingModel))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -7101,7 +7126,7 @@ async fn a_second_tool_call_in_the_creating_turn_tells_the_line() { async fn a_line_message_answered_with_text_tells_the_line_nothing() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -7132,7 +7157,7 @@ async fn a_host_line_is_told_when_its_parent_makes_a_tool_call() { let agent = MinimalHost::start(&builder_with_model(&probe, Arc::new(ActingModel))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "watch the tests").await; @@ -7196,7 +7221,7 @@ async fn a_purpose_tool_call_is_the_lines_first_step() { let agent = MinimalHost::start(&builder_with_model(&probe, Arc::new(PurposeModel))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "tool:echo {\"text\":\"purpose\"}").await; @@ -7224,7 +7249,7 @@ async fn a_host_line_opened_after_main_moved( older_cut: bool, ) -> (MinimalHost, Session, String, String, u64) { let agent = setup(probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let at = if older_cut { @@ -7365,7 +7390,7 @@ async fn a_host_line_cut_before_it_was_opened_is_not_told_about_the_gap() { async fn the_creating_call_is_written_before_the_line_was_opened() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -7395,7 +7420,7 @@ async fn the_creating_call_is_written_before_the_line_was_opened() { async fn an_idle_line_tells_main_once_when_its_turn_ends_without_a_word() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -7461,7 +7486,7 @@ async fn a_tool_line_without_idle_notices_stays_quiet_after_restore() { let agent = MinimalHost::start(&builder_with_store(&probe, store.clone())) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let id = session.id().to_owned(); @@ -7495,7 +7520,9 @@ async fn a_tool_line_without_idle_notices_stays_quiet_after_restore() { let agent = MinimalHost::start(&builder_with_store(&probe, store)) .await .unwrap(); - let session = soon(agent.restore_session(id)).await.unwrap(); + let session = soon(agent.restore_session(id, Default::default())) + .await + .unwrap(); soon(session.idle(&child)).await.unwrap(); let before = local_events(&session, &child) .await @@ -7540,7 +7567,7 @@ async fn a_tool_line_without_idle_notices_stays_quiet_after_restore() { async fn a_turn_that_steered_main_writes_no_idle_notice() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -7575,7 +7602,7 @@ async fn a_turn_that_steered_main_writes_no_idle_notice() { async fn a_stop_with_a_held_steer_still_tells_main_the_line_stopped() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -7638,7 +7665,7 @@ async fn a_stop_with_a_held_steer_still_tells_main_the_line_stopped() { async fn a_tool_line_ends_itself_and_main_learns_it_from_the_roster() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -7745,7 +7772,7 @@ async fn a_tool_line_ends_itself_and_main_learns_it_from_the_roster() { async fn a_second_end_in_the_same_turn_writes_no_second_final_message() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -7811,7 +7838,7 @@ async fn a_second_end_in_the_same_turn_writes_no_second_final_message() { async fn a_host_lines_end_says_nothing_to_main() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let host = soon(session.branch("main".into(), 0, options("host line"))) @@ -7943,7 +7970,7 @@ async fn a_host_lines_end_says_nothing_to_main() { async fn a_tree_page_refuses_a_through_inside_a_batch() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "read the batch").await; @@ -7982,7 +8009,7 @@ async fn a_tree_page_refuses_a_through_inside_a_batch() { async fn an_end_from_outside_a_tool_line_wakes_main_with_a_notice() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -8133,7 +8160,7 @@ async fn an_idle_line_wakes_the_wait_of_the_main_that_opened_it() { let agent = MinimalHost::start(&builder_with_wait(&probe, gates.clone())) .await .unwrap(); - let session = patient(agent.create_session(SessionConfig::default())) + let session = patient(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -8163,7 +8190,7 @@ async fn an_ended_line_wakes_the_wait_of_the_main_that_opened_it() { let agent = MinimalHost::start(&builder_with_wait(&probe, Arc::new(FlowModel))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -8194,7 +8221,7 @@ async fn a_steer_message_from_a_line_wakes_the_wait_of_the_main_that_opened_it() let agent = MinimalHost::start(&builder_with_wait(&probe, Arc::new(FlowModel))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let child = open_line(&session, "watch the tests").await; @@ -8324,7 +8351,7 @@ async fn a_roster_and_an_identity_replay_separately_after_a_compaction() { ); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let first = open_line(&session, "compact my line").await; @@ -8437,16 +8464,19 @@ async fn a_manual_compaction_replays_a_lines_identity() { let agent = MinimalHost::start(&builder).await.unwrap(); // The Session's own model: a manual compaction at idle has no request to // adopt one from. - let session = soon(agent.create_session(SessionConfig { - model: ModelSelection { - provider_id: "test".into(), - model_id: "flow".into(), - capability_snapshot: None, - config: None, - metadata: None, + let session = soon(agent.create_session( + SessionConfig { + model: ModelSelection { + provider_id: "test".into(), + model_id: "flow".into(), + capability_snapshot: None, + config: None, + metadata: None, + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - })) + Default::default(), + )) .await .unwrap(); let line = open_line(&session, "compact my line").await; @@ -8572,7 +8602,7 @@ async fn compact_line(session: &Session, line: &str) { async fn a_child_cut_after_a_roster_retires_it_and_one_cut_before_gets_nothing() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let before = open_line(&session, "cut before the roster").await; @@ -8691,7 +8721,7 @@ async fn closing_after_dispatch_before_the_build_first_poll_is_a_normal_cancella }), ); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let (tree, dispatcher, root) = ports.lock().unwrap().take().unwrap(); @@ -8729,7 +8759,7 @@ fn interrupt() -> EventKind { async fn a_stop_settles_the_branch_tool_while_the_tree_still_builds_the_child() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); probe.delay_child.store(true, Ordering::SeqCst); @@ -8846,7 +8876,7 @@ async fn an_ancestors_end_closes_a_pending_end_whose_delivery_was_held() { let probe = Arc::new(Probe::default()); let gate = Arc::new(Gate::default()); let agent = MinimalHost::start(&gated(&probe, &gate)).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let ancestor = soon(session.branch("main".into(), 0, options("ancestor"))) @@ -9000,7 +9030,7 @@ async fn a_turn_spanning_a_restart_after_a_steer_writes_no_idle_notice() { let mut builder1 = builder(&probe); builder1.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(first.clone())); let agent = MinimalHost::start(&builder1).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let id = session.id().to_owned(); @@ -9038,7 +9068,9 @@ async fn a_turn_spanning_a_restart_after_a_steer_writes_no_idle_notice() { let mut builder2 = builder(&probe); builder2.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(second)); let agent = MinimalHost::start(&builder2).await.unwrap(); - let session = soon(agent.restore_session(id)).await.unwrap(); + let session = soon(agent.restore_session(id, Default::default())) + .await + .unwrap(); soon(session.idle(&child)).await.unwrap(); soon(session.idle("main")).await.unwrap(); tokio::time::sleep(Duration::from_millis(300)).await; @@ -9119,7 +9151,7 @@ async fn tree_chain_queries_preserve_inherited_cuts_after_ending_and_restore() { let config = builder_with_store(&probe, store); let agent = MinimalHost::start(&config).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -9185,7 +9217,10 @@ async fn tree_chain_queries_preserve_inherited_cuts_after_ending_and_restore() { let session_id = session.id().to_owned(); soon(agent.close()).await.unwrap(); let agent = MinimalHost::start(&config).await.unwrap(); - let restored = agent.restore_session(session_id).await.unwrap(); + let restored = agent + .restore_session(session_id, Default::default()) + .await + .unwrap(); let tree = restored.session_service::().unwrap(); assert_eq!(texts(&tree, &leaf).await, expected); assert_eq!(texts(&tree, &zero).await, ["visible-root"]); @@ -9198,7 +9233,7 @@ async fn tree_chain_queries_preserve_inherited_cuts_after_ending_and_restore() { async fn a_chain_read_continues_past_a_page_that_ended_in_an_ancestor() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -9265,7 +9300,7 @@ async fn a_chain_read_continues_past_a_page_that_ended_in_an_ancestor() { async fn the_directory_lists_open_and_cascade_ended_lines_with_their_end_events() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.submit("ancestor".into(), InputMode::Queue, "main")) @@ -9354,7 +9389,7 @@ async fn the_directory_lists_open_and_cascade_ended_lines_with_their_end_events( async fn the_directory_reports_a_line_whose_end_is_pending_as_ending() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let ancestor = soon(session.branch("main".into(), 0, options("ancestor"))) @@ -9478,7 +9513,7 @@ async fn the_directory_reports_a_host_end_as_ending_before_its_ended_row() { let probe = Arc::new(Probe::default()); let gate = Arc::new(Gate::default()); let agent = MinimalHost::start(&gated(&probe, &gate)).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = soon(session.branch("main".into(), 0, options("host line"))) @@ -9559,7 +9594,7 @@ async fn the_directory_reports_a_cascaded_end_as_ending_before_its_ended_row() { let probe = Arc::new(Probe::default()); let gate = Arc::new(Gate::default()); let agent = MinimalHost::start(&gated(&probe, &gate)).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let ancestor = soon(session.branch("main".into(), 0, options("ancestor"))) @@ -9690,7 +9725,9 @@ async fn timeline_store_binding_preserves_memory_batch_publication_and_wire_read }, )); let host = MinimalHost::start(&builder).await.unwrap(); - host.create_session(SessionConfig::default()).await.unwrap(); + host.create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); let (native, wire) = binding.get().unwrap(); native .create_session("parity", &SessionConfig::default()) @@ -9853,7 +9890,7 @@ fn refusal(error: &Result<()>) -> (&'static str, String) { async fn the_default_branch_starts_at_the_root_and_survives_a_restart() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); assert_eq!(session.default_branch().unwrap(), "main"); @@ -9886,7 +9923,9 @@ async fn the_default_branch_starts_at_the_root_and_survives_a_restart() { assert_eq!(fact.from, None); let id = session.id(); soon(session.close()).await.unwrap(); - let session = soon(agent.restore_session(id.into())).await.unwrap(); + let session = soon(agent.restore_session(id.into(), Default::default())) + .await + .unwrap(); soon(session.idle("main")).await.unwrap(); assert_eq!( session.default_branch().unwrap(), @@ -9900,7 +9939,7 @@ async fn the_default_branch_starts_at_the_root_and_survives_a_restart() { async fn a_restore_reads_one_fact_for_a_multi_line_session_and_none_for_a_single_line() { let single = Arc::new(TestStore::default()); let agent = setup_with(&single).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let id = session.id(); @@ -9912,7 +9951,9 @@ async fn a_restore_reads_one_fact_for_a_multi_line_session_and_none_for_a_single )) .await .unwrap(); - let session = soon(restored.restore_session(id.into())).await.unwrap(); + let session = soon(restored.restore_session(id.into(), Default::default())) + .await + .unwrap(); assert_eq!(session.default_branch().unwrap(), "main"); assert_eq!( single.pages("main", &["branch/default", "session/forked"]), @@ -9923,7 +9964,7 @@ async fn a_restore_reads_one_fact_for_a_multi_line_session_and_none_for_a_single let multi = Arc::new(TestStore::default()); let agent = setup_with(&multi).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "one more line").await; @@ -9944,7 +9985,9 @@ async fn a_restore_reads_one_fact_for_a_multi_line_session_and_none_for_a_single )) .await .unwrap(); - let session = soon(restored.restore_session(id.into())).await.unwrap(); + let session = soon(restored.restore_session(id.into(), Default::default())) + .await + .unwrap(); soon(session.idle("main")).await.unwrap(); assert_eq!( multi.pages("main", &["branch/default", "session/forked"]), @@ -10026,7 +10069,9 @@ async fn a_restore_of_a_fork_that_opened_a_line_keeps_the_root_default() { )) .await .unwrap(); - let session = soon(agent.restore_session("forked".into())).await.unwrap(); + let session = soon(agent.restore_session("forked".into(), Default::default())) + .await + .unwrap(); assert_eq!( session.default_branch().unwrap(), "main", @@ -10043,7 +10088,7 @@ async fn a_restore_of_a_fork_that_opened_a_line_keeps_the_root_default() { async fn an_end_whose_final_message_fails_is_delivered_by_the_next_restore() { let store = Arc::new(TestStore::default()); let agent = setup_with(&store).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let session_id = session.id().to_owned(); @@ -10099,7 +10144,7 @@ async fn an_end_whose_final_message_fails_is_delivered_by_the_next_restore() { )) .await .unwrap(); - let session = soon(restored.restore_session(session_id.clone())) + let session = soon(restored.restore_session(session_id.clone(), Default::default())) .await .unwrap(); let events = local_events(&session, "main").await; @@ -10127,7 +10172,9 @@ async fn an_end_whose_final_message_fails_is_delivered_by_the_next_restore() { )) .await .unwrap(); - let session = soon(again.restore_session(session_id)).await.unwrap(); + let session = soon(again.restore_session(session_id, Default::default())) + .await + .unwrap(); assert_eq!( deliveries(&local_events(&session, "main").await, &submission), 1, @@ -10146,7 +10193,7 @@ async fn an_end_whose_final_message_fails_is_delivered_by_the_next_restore() { async fn a_second_end_retries_an_undelivered_final_message() { let store = Arc::new(TestStore::default()); let agent = setup_with(&store).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "deliver me").await; @@ -10222,7 +10269,7 @@ async fn a_second_end_retries_an_undelivered_final_message() { async fn ending_the_parent_of_a_line_with_an_undelivered_message_answers() { let store = Arc::new(TestStore::default()); let agent = setup_with(&store).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let parent = open_line(&session, "outer").await; @@ -10283,7 +10330,7 @@ async fn ending_the_parent_of_a_line_with_an_undelivered_message_answers() { async fn ending_the_root_the_default_branch_or_an_ancestor_is_refused() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "outer").await; @@ -10344,7 +10391,7 @@ async fn ending_the_root_the_default_branch_or_an_ancestor_is_refused() { async fn a_user_opened_line_records_its_own_source() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = soon(session.branch( @@ -10390,7 +10437,7 @@ async fn a_user_opened_line_records_its_own_source() { async fn a_user_opened_line_states_the_end_rule_that_never_changes() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = soon(session.branch( @@ -10436,7 +10483,7 @@ async fn a_user_opened_line_states_the_end_rule_that_never_changes() { async fn a_default_branch_that_was_a_tool_line_stops_sending_its_idle_notice() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "work alone").await; @@ -10528,7 +10575,7 @@ async fn a_switched_line_keeps_its_identity_after_a_compaction() { ); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); @@ -10678,7 +10725,7 @@ async fn a_multi_paragraph_purpose_survives_a_move_and_a_compaction() { ); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line( @@ -10748,7 +10795,7 @@ fn identity_block_applied(events: &[Arc]) -> bool { async fn a_move_leaves_the_new_default_branchs_prefix_unchanged() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "keep this prefix").await; @@ -10817,7 +10864,7 @@ async fn default_notes(session: &Session, lines: &[&str]) -> Vec<(String, usize) async fn a_move_writes_one_note_per_participant_that_is_not_the_root() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let b = open_line(&session, "b").await; @@ -10896,7 +10943,7 @@ async fn a_move_writes_one_note_per_participant_that_is_not_the_root() { async fn moves_that_overtake_their_writer_each_reach_their_participants() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let b = open_line(&session, "b").await; @@ -10983,7 +11030,7 @@ async fn moves_that_overtake_their_writer_each_reach_their_participants() { async fn a_move_answers_only_after_its_fact_is_durable() { let store = Arc::new(TestStore::default()); let agent = setup_with(&store).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "continue on").await; @@ -11038,7 +11085,7 @@ async fn a_move_answers_only_after_its_fact_is_durable() { async fn a_move_whose_write_fails_changes_nothing() { let store = Arc::new(TestStore::default()); let agent = setup_with(&store).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let session_id = session.id().to_owned(); @@ -11081,7 +11128,9 @@ async fn a_move_whose_write_fails_changes_nothing() { )) .await .unwrap(); - let session = soon(restored.restore_session(session_id)).await.unwrap(); + let session = soon(restored.restore_session(session_id, Default::default())) + .await + .unwrap(); assert_eq!( session.default_branch().unwrap(), "main", @@ -11109,7 +11158,7 @@ async fn a_restore_falls_back_to_the_root_for_a_target_it_cannot_select() { let agent = MinimalHost::start(&builder_with_store(&probe, store.clone())) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = soon(session.branch( @@ -11141,7 +11190,9 @@ async fn a_restore_falls_back_to_the_root_for_a_target_it_cannot_select() { let restored = MinimalHost::start(&builder_with_store(&Arc::new(Probe::default()), store)) .await .unwrap(); - let session = soon(restored.restore_session(id.into())).await.unwrap(); + let session = soon(restored.restore_session(id.into(), Default::default())) + .await + .unwrap(); assert_eq!( session.default_branch().unwrap(), "main", @@ -11260,7 +11311,9 @@ async fn a_restore_falls_back_to_the_root_for_a_target_that_has_ended() { let agent = MinimalHost::start(&builder_with_store(&probe, store.clone())) .await .unwrap(); - let session = soon(agent.restore_session("saved".into())).await.unwrap(); + let session = soon(agent.restore_session("saved".into(), Default::default())) + .await + .unwrap(); assert_eq!( session.default_branch().unwrap(), "main", @@ -11276,7 +11329,7 @@ async fn a_restore_falls_back_to_the_root_for_a_target_that_has_ended() { async fn every_refusal_of_a_move_writes_nothing() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let tree = session.session_service::().unwrap(); @@ -11361,7 +11414,7 @@ async fn every_refusal_of_a_move_writes_nothing() { async fn a_former_default_branch_keeps_no_stale_instruction_and_ends_after_a_move_back() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let a = open_line(&session, "a").await; @@ -11469,7 +11522,7 @@ async fn a_former_default_branch_keeps_no_stale_instruction_and_ends_after_a_mov async fn a_former_default_branch_resumes_its_idle_notice_and_may_end_itself() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "a line").await; @@ -11534,7 +11587,7 @@ async fn a_switch_and_an_end_admit_in_one_order_and_the_refusal_writes_nothing() for end_first in [true, false] { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let a = open_line(&session, "a").await; @@ -11615,7 +11668,7 @@ async fn a_switch_and_an_end_admit_in_one_order_and_the_refusal_writes_nothing() async fn a_pre_upgrade_host_line_is_refused_and_a_user_line_is_accepted() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let legacy = soon(session.branch("main".into(), 0, options("opened before the upgrade"))) @@ -11685,7 +11738,7 @@ async fn a_switch_and_a_tool_lines_end_admit_in_one_order_without_a_refused_ones for end_first in [true, false] { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "the line that ends").await; @@ -11843,7 +11896,9 @@ async fn a_restart_delivers_a_tool_ends_final_message_exactly_once() { )) .await .unwrap(); - let session = soon(agent.restore_session("saved".into())).await.unwrap(); + let session = soon(agent.restore_session("saved".into(), Default::default())) + .await + .unwrap(); let events = until_events(&session, "main", |events| !finals(events).is_empty()).await; let delivered = finals(&events); assert_eq!(delivered.len(), 1, "{delivered:?}"); @@ -11884,7 +11939,9 @@ async fn a_restart_delivers_a_tool_ends_final_message_exactly_once() { let again = MinimalHost::start(&builder_with_store(&Arc::new(Probe::default()), store)) .await .unwrap(); - let session = soon(again.restore_session(id.into())).await.unwrap(); + let session = soon(again.restore_session(id.into(), Default::default())) + .await + .unwrap(); soon(session.idle("main")).await.unwrap(); let events = local_events(&session, "main").await; assert_eq!( @@ -11915,7 +11972,7 @@ async fn a_clean_restart_writes_no_status_note() { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let b = open_line(&session, "the purpose of B").await; @@ -11958,7 +12015,9 @@ async fn a_clean_restart_writes_no_status_note() { let again = MinimalHost::start(&builder_with_store(&Arc::new(Probe::default()), store)) .await .unwrap(); - let session = soon(again.restore_session(id.clone())).await.unwrap(); + let session = soon(again.restore_session(id.clone(), Default::default())) + .await + .unwrap(); assert_eq!(session.default_branch().unwrap(), d, "the fact stands"); for line in [&b, &c, &d] { soon(session.submit("next request".into(), InputMode::Queue, line)) @@ -12027,7 +12086,7 @@ async fn a_stale_note_is_replaced_once(old: &str, user: bool) { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let b = if user { @@ -12092,7 +12151,9 @@ async fn a_stale_note_is_replaced_once(old: &str, user: bool) { )) .await .unwrap(); - let session = soon(agent.restore_session(id.clone())).await.unwrap(); + let session = soon(agent.restore_session(id.clone(), Default::default())) + .await + .unwrap(); assert_eq!(session.default_branch().unwrap(), b, "the fact stands"); let stopped = tokio::time::timeout(Duration::from_secs(5), async { loop { @@ -12158,7 +12219,9 @@ async fn a_stale_note_is_replaced_once(old: &str, user: bool) { let third = MinimalHost::start(&builder_with_store(&Arc::new(Probe::default()), second)) .await .unwrap(); - let session = soon(third.restore_session(id)).await.unwrap(); + let session = soon(third.restore_session(id, Default::default())) + .await + .unwrap(); soon(session.idle(&b)).await.unwrap(); assert_eq!( status_notes(&local_events(&session, &b).await).len(), @@ -12213,7 +12276,7 @@ async fn the_roots_roster_from_before_the_key_split_is_retired_at_load() { let agent = MinimalHost::start(&compacting_builder(first.clone())) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "the purpose of the line").await; @@ -12260,7 +12323,9 @@ async fn the_roots_roster_from_before_the_key_split_is_retired_at_load() { let again = MinimalHost::start(&compacting_builder(second.clone())) .await .unwrap(); - let session = soon(again.restore_session(id.clone())).await.unwrap(); + let session = soon(again.restore_session(id.clone(), Default::default())) + .await + .unwrap(); let mut events = local_events(&session, "main").await; for _ in 0..500 { if roster_block(&events).is_some() { @@ -12311,7 +12376,9 @@ async fn the_roots_roster_from_before_the_key_split_is_retired_at_load() { let third = MinimalHost::start(&compacting_builder(second)) .await .unwrap(); - let session = soon(third.restore_session(id.clone())).await.unwrap(); + let session = soon(third.restore_session(id.clone(), Default::default())) + .await + .unwrap(); tokio::time::sleep(Duration::from_millis(500)).await; let local = local_events(&session, "main").await; assert_eq!( @@ -12341,7 +12408,7 @@ async fn a_move_that_stopped_between_its_fact_and_its_notes_is_completed_at_load )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let b = open_line(&session, "the purpose of B").await; @@ -12409,7 +12476,9 @@ async fn a_move_that_stopped_between_its_fact_and_its_notes_is_completed_at_load )) .await .unwrap(); - let session = soon(agent.restore_session(id.clone())).await.unwrap(); + let session = soon(agent.restore_session(id.clone(), Default::default())) + .await + .unwrap(); assert_eq!(session.default_branch().unwrap(), c, "the fact stands"); let mut arrived = std::collections::BTreeSet::new(); let stopped = tokio::time::timeout(Duration::from_secs(5), async { @@ -12473,7 +12542,9 @@ async fn a_move_that_stopped_between_its_fact_and_its_notes_is_completed_at_load let again = MinimalHost::start(&builder_with_store(&Arc::new(Probe::default()), store)) .await .unwrap(); - let session = soon(again.restore_session(id.clone())).await.unwrap(); + let session = soon(again.restore_session(id.clone(), Default::default())) + .await + .unwrap(); soon(session.idle("main")).await.unwrap(); assert_eq!( default_notes(&session, &["main", &b, &c]).await, @@ -12500,7 +12571,7 @@ async fn a_restore_writes_the_owed_note_before_the_line_answers() { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let b = open_line(&session, "the purpose of B").await; @@ -12545,7 +12616,9 @@ async fn a_restore_writes_the_owed_note_before_the_line_answers() { )) .await .unwrap(); - let session = soon(agent.restore_session(id.clone())).await.unwrap(); + let session = soon(agent.restore_session(id.clone(), Default::default())) + .await + .unwrap(); assert_eq!(session.default_branch().unwrap(), b, "the fact stands"); let stopped = tokio::time::timeout(Duration::from_secs(5), async { loop { @@ -12664,7 +12737,7 @@ async fn records_end(session: &Session, line: &str) { async fn a_move_committed_before_its_writer_starts_still_owes_its_note() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let mut held = dim_agent_capabilities::timeline_tree::testing::hold_writers(session.id()); @@ -12764,7 +12837,7 @@ async fn a_move_committed_before_its_writer_starts_still_owes_its_note() { async fn a_move_cancelled_after_admission_settles_under_the_tree() { let store = Arc::new(TestStore::default()); let agent = setup_with(&store).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "switched while cancelled").await; @@ -12811,7 +12884,7 @@ async fn a_move_cancelled_after_admission_settles_under_the_tree() { async fn a_cancelled_move_whose_publication_fails_keeps_the_tree_until_it_settles() { let store = Arc::new(TestStore::default()); let agent = setup_with(&store).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let first = open_line(&session, "first switch").await; @@ -12871,7 +12944,7 @@ async fn a_cancelled_move_whose_publication_fails_keeps_the_tree_until_it_settle async fn an_end_retry_cancelled_after_admission_settles_under_the_tree() { let store = Arc::new(TestStore::default()); let agent = setup_with(&store).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let line = open_line(&session, "deliver me").await; @@ -12942,7 +13015,7 @@ async fn an_end_retry_cancelled_after_admission_settles_under_the_tree() { async fn a_close_waits_for_an_admitted_move_and_a_restore_reads_its_fact() { let store = Arc::new(TestStore::default()); let agent = setup_with(&store).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let id = session.id().to_owned(); @@ -12966,7 +13039,7 @@ async fn a_close_waits_for_an_admitted_move_and_a_restore_reads_its_fact() { let failed = Arc::new(TestStore::default()); let agent = setup_with(&failed).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let id = session.id().to_owned(); @@ -13023,7 +13096,9 @@ async fn restore_default(store: &Arc, id: &str) -> String { )) .await .unwrap(); - let session = soon(restored.restore_session(id.into())).await.unwrap(); + let session = soon(restored.restore_session(id.into(), Default::default())) + .await + .unwrap(); let default = session.default_branch().unwrap(); soon(session.close()).await.unwrap(); soon(restored.close()).await.unwrap(); @@ -13128,7 +13203,7 @@ fn creates(events: &[Arc]) -> usize { async fn the_root_opens_a_line_while_another_line_is_default() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); // C inherits the root's history through a completed turn: the cut ends a @@ -13230,7 +13305,7 @@ async fn the_root_opens_a_line_while_another_line_is_default() { async fn the_default_branch_opens_a_line() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let b = open_line(&session, "b").await; @@ -13288,7 +13363,7 @@ async fn the_default_branch_opens_a_line() { async fn a_former_default_branch_keeps_its_lines_and_opens_none() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let a = open_line(&session, "a").await; @@ -13366,7 +13441,7 @@ async fn a_former_default_branch_keeps_its_lines_and_opens_none() { async fn a_plugin_line_never_opens_a_line() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let host = open_host_line(&session, "main", "a plugin line").await; @@ -13392,7 +13467,7 @@ async fn a_plugin_line_never_opens_a_line() { async fn a_tool_line_still_cannot_open_a_line() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let a = open_line(&session, "a").await; @@ -13420,7 +13495,7 @@ async fn the_cap_does_not_count_the_default_branch_or_its_ancestors() { let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let b = open_line(&session, "b").await; @@ -13456,7 +13531,7 @@ async fn a_switch_over_the_cap_closes_nothing() { let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let a = open_line(&session, "a").await; @@ -13487,7 +13562,7 @@ async fn a_switch_that_frees_a_slot_admits_the_next_open() { let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let a = open_line(&session, "a").await; @@ -13516,7 +13591,7 @@ async fn the_cap_is_refused_under_the_tree_lock() { let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let a = open_line(&session, "a").await; @@ -13540,7 +13615,7 @@ async fn the_cap_is_refused_under_the_tree_lock() { let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let a = open_line(&session, "a").await; @@ -13618,7 +13693,7 @@ async fn an_open_after_a_move_waits_and_counts_the_moves_result() { let agent = MinimalHost::start(&builder_with_store_config(&probe, store.clone(), capped(1))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let cut = idle_cut(&session, "main").await; @@ -13679,7 +13754,7 @@ async fn an_open_from_the_moving_line_is_refused_once_the_move_settles() { let agent = MinimalHost::start(&builder_with_store(&probe, store.clone())) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let b = open_line(&session, "b").await; @@ -13739,7 +13814,7 @@ async fn a_paused_build_does_not_hold_the_tree_lock() { let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let cut = idle_cut(&session, "main").await; @@ -13786,7 +13861,7 @@ async fn an_open_admitted_before_a_move_still_stands() { let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(1))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let a = open_line(&session, "a").await; @@ -13815,7 +13890,7 @@ async fn an_opener_that_is_not_the_root_keeps_its_identity_and_its_roster() { let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let b = open_line(&session, "b").await; @@ -13868,7 +13943,7 @@ async fn an_opener_that_is_not_the_root_keeps_its_identity_and_its_roster() { async fn a_user_opened_default_branch_coordinates_the_line_it_opens() { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let cut = session.sequence("main").unwrap(); @@ -13931,7 +14006,7 @@ async fn a_status_note_and_a_live_roster_do_not_retire_each_other() { let agent = MinimalHost::start(&builder_with_branch_config(&probe, capped(2))) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let b = open_line(&session, "b").await; @@ -14010,7 +14085,7 @@ async fn measure_e3_cold_restore_with_two_openers() { for _ in 0..5 { let probe = Arc::new(Probe::default()); let agent = setup(&probe).await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let opener = tool_line(&session, "main", "the default branch").await; @@ -14024,7 +14099,9 @@ async fn measure_e3_cold_restore_with_two_openers() { let id = session.id(); soon(session.close()).await.unwrap(); let started = std::time::Instant::now(); - let restored = soon(agent.restore_session(id.into())).await.unwrap(); + let restored = soon(agent.restore_session(id.into(), Default::default())) + .await + .unwrap(); soon(restored.idle("main")).await.unwrap(); elapsed.push(started.elapsed()); soon(agent.close()).await.unwrap(); diff --git a/crates/dim-agent-capabilities/tests/capabilities_flow.rs b/crates/dim-agent-capabilities/tests/capabilities_flow.rs index 01fd065891..9c62c91b02 100644 --- a/crates/dim-agent-capabilities/tests/capabilities_flow.rs +++ b/crates/dim-agent-capabilities/tests/capabilities_flow.rs @@ -1,5 +1,6 @@ mod support; +mod agent_options_flow; mod branch_flow; #[path = "context_flow.rs"] mod context_flow; diff --git a/crates/dim-agent-capabilities/tests/context_flow.rs b/crates/dim-agent-capabilities/tests/context_flow.rs index 49fe3c0e9b..87395924e4 100644 --- a/crates/dim-agent-capabilities/tests/context_flow.rs +++ b/crates/dim-agent-capabilities/tests/context_flow.rs @@ -384,7 +384,7 @@ async fn a_steer_before_any_model_output_ends_the_request_and_continues_the_turn let model = Arc::new(SilentFirstCall::default()); let agent = MinimalHost::start(&builder(model.clone())).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -481,7 +481,7 @@ async fn provider_budget_recovery_uses_one_fixed_source_and_retries_only_once() .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); // The turn's input is larger than the summary wrapper plus the @@ -557,7 +557,7 @@ async fn foreign_compaction_cursor_fails_recovery_without_another_model_call() { Context { foreign_cursor: true, ..Context::default() }, )).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -635,7 +635,7 @@ async fn compressor_cursor_cannot_split_an_assistant_tool_use_from_its_result() .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -739,7 +739,7 @@ async fn compaction_restores_counts_and_uses_the_committed_context_baseline() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session.input(context_input(), "main").await.unwrap(); @@ -814,7 +814,7 @@ async fn compaction_restores_counts_and_uses_the_committed_context_baseline() { ); let forged_agent = MinimalHost::start(&forged_builder).await.unwrap(); let forged_session = forged_agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); forged_session.input(context_input(), "main").await.unwrap(); @@ -956,7 +956,7 @@ async fn before_modified_request_is_budget_checked_before_native_model_invocatio })); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1044,7 +1044,7 @@ async fn a_final_request_transform_does_not_calibrate_the_canonical_context() { })); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1099,7 +1099,7 @@ async fn provider_usage_baseline_counts_new_history_and_ignores_unusable_measure }).into()).unwrap(); dim_agent_runtime::core::close_timeline(&timeline).await.unwrap(); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session("usage-baseline".into()).await.unwrap(); + let session = agent.restore_session("usage-baseline".into(), Default::default()).await.unwrap(); session .submit("first".into(), InputMode::Queue, "main") .await @@ -1231,7 +1231,7 @@ async fn provider_usage_baseline_counts_new_history_and_ignores_unusable_measure ); changed.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&changed).await.unwrap(); - let session = agent.restore_session(id).await.unwrap(); + let session = agent.restore_session(id, Default::default()).await.unwrap(); let usage = session .service::("main") .unwrap() @@ -1365,7 +1365,10 @@ async fn restore_preserves_each_parent_tools_own_confirmed_child_effects() { ); profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session("effects".into()).await.unwrap(); + let session = agent + .restore_session("effects".into(), Default::default()) + .await + .unwrap(); tokio::time::timeout(Duration::from_secs(3), session.idle("main")) .await .unwrap() @@ -1614,7 +1617,10 @@ async fn restoring_each_preparation_handoff_settles_without_replaying_work() { ); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session("restore".into()).await.unwrap(); + let session = agent + .restore_session("restore".into(), Default::default()) + .await + .unwrap(); tokio::time::timeout(Duration::from_secs(3), session.idle("main")) .await .unwrap_or_else(|_| panic!("recovery stuck at {boundary}")) @@ -1781,7 +1787,7 @@ async fn restoring_idle_unpaused_queue_input_applies_it_without_a_new_submission builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .restore_session("queued-restore".into()) + .restore_session("queued-restore".into(), Default::default()) .await .unwrap(); tokio::time::timeout(Duration::from_secs(3), session.idle("main")) @@ -1878,7 +1884,7 @@ async fn restoring_pending_inputs_runs_each_queued_input_in_its_own_turn() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .restore_session("applied-restore".into()) + .restore_session("applied-restore".into(), Default::default()) .await .unwrap(); tokio::time::timeout(Duration::from_secs(3), session.idle("main")) @@ -1999,7 +2005,7 @@ async fn a_restored_queue_writes_one_owed_deletion_for_a_handover_input() { }; let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .restore_session("handover-restore".into()) + .restore_session("handover-restore".into(), Default::default()) .await .unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -2010,7 +2016,7 @@ async fn a_restored_queue_writes_one_owed_deletion_for_a_handover_input() { let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .restore_session("handover-restore".into()) + .restore_session("handover-restore".into(), Default::default()) .await .unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -2103,7 +2109,7 @@ async fn a_compaction_completed_after_a_stop_is_committed_not_discarded() { defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); for text in ["x".repeat(500), "y".repeat(500)] { @@ -2188,14 +2194,17 @@ async fn a_single_long_turn_compacts_inside_itself_instead_of_skipping() { .await .unwrap(); let session = agent - .create_session(SessionConfig { - tools: Some(vec!["echo".into()]), - permission_policy: dim_agent_runtime::PermissionPolicy { - preset: dim_agent_runtime::PermissionPreset::FullAccess, + .create_session( + SessionConfig { + tools: Some(vec!["echo".into()]), + permission_policy: dim_agent_runtime::PermissionPolicy { + preset: dim_agent_runtime::PermissionPreset::FullAccess, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); let command = format!("tool:echo {{\"text\":\"{}\"}}", "y".repeat(600)); @@ -2248,7 +2257,7 @@ async fn a_changed_prefix_message_fails_the_preparation() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -2295,7 +2304,7 @@ async fn a_short_request_fails_the_preparation() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -2331,7 +2340,7 @@ async fn a_message_appended_after_the_prefix_reaches_the_model() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -2381,7 +2390,7 @@ async fn a_completed_compaction_keeps_its_replacement_in_the_prefix_check() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -2436,7 +2445,7 @@ async fn a_completed_compaction_keeps_its_replacement_in_the_prefix_check() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session diff --git a/crates/dim-agent-capabilities/tests/context_flow/checkpoint_projection.rs b/crates/dim-agent-capabilities/tests/context_flow/checkpoint_projection.rs index 38c11de1a8..533d6dd8e1 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/checkpoint_projection.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/checkpoint_projection.rs @@ -54,7 +54,7 @@ async fn keyed_blocks_replay_verbatim_after_repeated_compaction_until_retired() .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let inputs = [ diff --git a/crates/dim-agent-capabilities/tests/context_flow/compacted_bindings.rs b/crates/dim-agent-capabilities/tests/context_flow/compacted_bindings.rs index b2c86c0575..d331fa6bdd 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/compacted_bindings.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/compacted_bindings.rs @@ -226,15 +226,18 @@ impl Files { } async fn session(&self) -> Session { self.agent - .create_session(SessionConfig { - cwd: self.dir.to_string_lossy().into_owned(), - tools: Some(vec!["read".into(), "write".into(), "edit".into()]), - permission_policy: PermissionPolicy { - preset: PermissionPreset::FullAccess, - ..Default::default() + .create_session( + SessionConfig { + cwd: self.dir.to_string_lossy().into_owned(), + tools: Some(vec!["read".into(), "write".into(), "edit".into()]), + permission_policy: PermissionPolicy { + preset: PermissionPreset::FullAccess, + ..Default::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - }) + Default::default(), + ) .await .unwrap() } diff --git a/crates/dim-agent-capabilities/tests/context_flow/compaction_events.rs b/crates/dim-agent-capabilities/tests/context_flow/compaction_events.rs index 8a3eb68cab..07ead264bd 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/compaction_events.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/compaction_events.rs @@ -38,7 +38,7 @@ async fn snapshot_codecs_preserve_completed_compaction_even_when_saving_fails() builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let original = "x".repeat(1_500); @@ -310,7 +310,7 @@ async fn committed_summary_drives_current_and_following_model_requests() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let original = "x".repeat(1_500); @@ -383,7 +383,7 @@ async fn committed_cursor_preserves_the_history_after_its_cutoff() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -472,7 +472,7 @@ async fn final_outcome_controls_normal_preparation_and_budget_recovery() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let original = "x".repeat(500); @@ -555,7 +555,7 @@ async fn a_damaged_compaction_fails_replay_without_silently_regenerating_history )); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session diff --git a/crates/dim-agent-capabilities/tests/context_flow/context_reads.rs b/crates/dim-agent-capabilities/tests/context_flow/context_reads.rs index c4bb38ac42..a9c37a3203 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/context_reads.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/context_reads.rs @@ -523,7 +523,7 @@ async fn prepared_requests_use_saved_boundaries_and_growth_after_compaction_and_ profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -630,7 +630,7 @@ async fn prepared_requests_use_saved_boundaries_and_growth_after_compaction_and_ drop(session); store.context_pages.lock().unwrap().clear(); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session(id).await.unwrap(); + let session = agent.restore_session(id, Default::default()).await.unwrap(); session .service::("main") .unwrap() @@ -738,7 +738,10 @@ async fn growth_checks_seek_numeric_boundaries_across_larger_restored_histories( }, )); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session("growth".into()).await.unwrap(); + let session = agent + .restore_session("growth".into(), Default::default()) + .await + .unwrap(); session .submit( "initialize on a real request".into(), @@ -794,7 +797,10 @@ async fn growth_checks_seek_numeric_boundaries_across_larger_restored_histories( agent.close().await.unwrap(); drop(session); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session("growth".into()).await.unwrap(); + let session = agent + .restore_session("growth".into(), Default::default()) + .await + .unwrap(); session .service::("main") .unwrap() @@ -870,7 +876,7 @@ async fn persisted_usage_reads_and_restores_without_projecting_history() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let session_id = session.id().to_owned(); @@ -952,7 +958,10 @@ async fn persisted_usage_reads_and_restores_without_projecting_history() { ); resumed_builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&resumed_builder).await.unwrap(); - let restored = agent.restore_session(session_id.clone()).await.unwrap(); + let restored = agent + .restore_session(session_id.clone(), Default::default()) + .await + .unwrap(); let usage = restored .service::("main") .unwrap() @@ -1005,7 +1014,10 @@ async fn persisted_usage_reads_and_restores_without_projecting_history() { store.context_pages.lock().unwrap().clear(); store.property_queries.lock().unwrap().clear(); let agent = MinimalHost::start(&resumed_builder).await.unwrap(); - let restored = agent.restore_session(session_id).await.unwrap(); + let restored = agent + .restore_session(session_id, Default::default()) + .await + .unwrap(); let usage = restored .service::("main") .unwrap() @@ -1072,7 +1084,7 @@ async fn closing_during_usage_result_publication_is_not_a_statistics_fault() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1163,7 +1175,7 @@ async fn unavailable_usage_counter_does_not_fault_resume_and_can_recover() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -1198,7 +1210,10 @@ async fn unavailable_usage_counter_does_not_fault_resume_and_can_recover() { resolver.0.store(false, Ordering::SeqCst); store.context_pages.lock().unwrap().clear(); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session(id.clone()).await.unwrap(); + let session = agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); let unavailable = session .service::("main") .unwrap() @@ -1216,7 +1231,7 @@ async fn unavailable_usage_counter_does_not_fault_resume_and_can_recover() { resolver.0.store(true, Ordering::SeqCst); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session(id).await.unwrap(); + let session = agent.restore_session(id, Default::default()).await.unwrap(); let restored = session .service::("main") .unwrap() @@ -1248,7 +1263,7 @@ async fn unsupported_usage_counter_does_not_fall_back_to_history_projection() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1390,7 +1405,10 @@ async fn unconfigured_usage_does_not_project_legacy_messages() { ); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session("unconfigured".into()).await.unwrap(); + let session = agent + .restore_session("unconfigured".into(), Default::default()) + .await + .unwrap(); let preparation = session .service::("main") .unwrap(); @@ -1450,7 +1468,7 @@ async fn usage_reads_the_published_head_while_a_fact_is_in_flight() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1598,7 +1616,7 @@ async fn model_reload_recovers_the_old_terminal_before_its_publication() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); @@ -1727,7 +1745,10 @@ async fn stop_waits_for_an_unpublished_turn_end_seen_by_a_reloaded_loop() { reload.install(&mut builder, model.clone()); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.create_session(SessionConfig::default()).await.unwrap(); + let session = agent + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); let old_loop = session.service::("main").unwrap(); let generation = || session.branch_diagnostics("main").unwrap().plugins .into_iter().find(|plugin| plugin.name == "Loop").unwrap(); @@ -1779,7 +1800,7 @@ async fn either_context_read_failure_ends_the_turn_and_allows_the_next_input() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); store.fail_at.store( @@ -1854,7 +1875,7 @@ async fn each_model_step_reads_full_context_for_policy_and_streams_otherwise() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); for input in ["x".repeat(1_500), "next".into(), "third".into()] { @@ -2002,7 +2023,7 @@ async fn a_second_compaction_saves_a_snapshot_that_decodes() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); for input in [ @@ -2122,7 +2143,7 @@ async fn stop_is_dispatched_while_either_context_read_is_waiting() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); store.pause_at.store( @@ -2213,7 +2234,7 @@ async fn configuration_reference_read_failure_aborts_resume_and_allows_retry() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let update = ConfigureUpdate { @@ -2245,7 +2266,7 @@ async fn configuration_reference_read_failure_aborts_resume_and_allows_retry() { agent.close().await.unwrap(); let agent = MinimalHost::start(&builder).await.unwrap(); - let failed = match agent.restore_session(id.clone()).await { + let failed = match agent.restore_session(id.clone(), Default::default()).await { Ok(_) => panic!("a missing configuration read must prevent publication"), Err(error) => error, }; @@ -2259,7 +2280,7 @@ async fn configuration_reference_read_failure_aborts_resume_and_allows_retry() { agent.close().await.unwrap(); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session(id).await.unwrap(); + let session = agent.restore_session(id, Default::default()).await.unwrap(); session .submit("after recovery retry".into(), InputMode::Queue, "main") .await @@ -2313,7 +2334,7 @@ async fn concurrent_system_adoptions_include_previous_unpublished_updates() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -2480,7 +2501,7 @@ async fn a_request_written_after_an_interrupt_loop_has_not_handled_does_not_run( let mut setup = None; for _ in 0..50 { let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); store.pause_preparation.store(true, Ordering::SeqCst); @@ -2633,7 +2654,7 @@ async fn progress_keeps_committed_output_until_it_is_published() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let mut progress = session.on::("main").unwrap().unwrap(); @@ -2689,7 +2710,7 @@ async fn a_steer_during_the_context_read_ends_the_request_before_it_is_handed_ov builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); store.pause_preparation.store(true, Ordering::SeqCst); @@ -2773,7 +2794,7 @@ async fn a_below_threshold_preparation_reads_no_growing_turn_order() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let mut per_turn: Vec>> = Vec::new(); @@ -3414,10 +3435,13 @@ async fn usage_reuses_counted_messages_and_current_registry_tools_without_extra_ )); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .create_session(SessionConfig { - tools: Some(vec!["echo".into()]), - ..Default::default() - }) + .create_session( + SessionConfig { + tools: Some(vec!["echo".into()]), + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); let timeline = cell.get().unwrap(); @@ -3533,7 +3557,7 @@ async fn usage_reuses_counted_messages_and_current_registry_tools_without_extra_ agent.close().await.unwrap(); let messages = counter.messages.load(Ordering::SeqCst); let agent = MinimalHost::start(&profile).await.unwrap(); - let restored = agent.restore_session(id).await.unwrap(); + let restored = agent.restore_session(id, Default::default()).await.unwrap(); let reading = restored .service::("main") .unwrap() @@ -3572,7 +3596,7 @@ async fn resuming_a_replacement_only_context_defers_missing_usage_until_a_reques profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(source.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -3641,7 +3665,7 @@ async fn resuming_a_replacement_only_context_defers_missing_usage_until_a_reques let mut profile = builder_with_usage_resolver(counter.clone()); profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session(id).await.unwrap(); + let session = agent.restore_session(id, Default::default()).await.unwrap(); assert!(matches!( session .service::("main") @@ -3690,7 +3714,7 @@ async fn usage_upgrades_saved_numbers_or_initializes_once_without_historical_res profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(source.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -3881,7 +3905,10 @@ async fn usage_upgrades_saved_numbers_or_initializes_once_without_historical_res let mut profile = builder_with_usage_resolver(counter.clone()); profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session(id.clone()).await.unwrap(); + let session = agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); let value = session .service::("main") .unwrap() @@ -3943,7 +3970,10 @@ async fn usage_upgrades_saved_numbers_or_initializes_once_without_historical_res counter.messages.store(0, Ordering::SeqCst); store.context_pages.lock().unwrap().clear(); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session(id.clone()).await.unwrap(); + let session = agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); let reloaded = session .service::("main") .unwrap() @@ -3983,7 +4013,10 @@ async fn usage_upgrades_saved_numbers_or_initializes_once_without_historical_res counter.messages.store(0, Ordering::SeqCst); store.context_pages.lock().unwrap().clear(); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session(id.clone()).await.unwrap(); + let session = agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); let value = session .service::("main") .unwrap() @@ -4017,7 +4050,10 @@ async fn usage_upgrades_saved_numbers_or_initializes_once_without_historical_res assert!(value.estimated_input_tokens > expected.estimated_input_tokens); agent.close().await.unwrap(); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session(id.clone()).await.unwrap(); + let session = agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); let reloaded = session .service::("main") .unwrap() @@ -4062,7 +4098,10 @@ async fn usage_upgrades_saved_numbers_or_initializes_once_without_historical_res .await .unwrap(); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session(id.clone()).await.unwrap(); + let session = agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); assert!(matches!( session .service::("main") @@ -4124,7 +4163,7 @@ async fn child_tool_results_do_not_change_usage_live_after_reload_or_compaction( )); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -4191,7 +4230,10 @@ async fn child_tool_results_do_not_change_usage_live_after_reload_or_compaction( let id = session.id().to_owned(); agent.close().await.unwrap(); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session(id.clone()).await.unwrap(); + let session = agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); assert_eq!( session .service::("main") @@ -4258,7 +4300,7 @@ async fn child_tool_results_do_not_change_usage_live_after_reload_or_compaction( .await .unwrap(); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session(id).await.unwrap(); + let session = agent.restore_session(id, Default::default()).await.unwrap(); assert!(matches!( session .service::("main") @@ -4376,7 +4418,10 @@ async fn legacy_prompt_references_migrate_explicitly_and_preserve_domain_task_st ); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let error = match agent.restore_session(key.session_id.clone()).await { + let error = match agent + .restore_session(key.session_id.clone(), Default::default()) + .await + { Ok(_) => panic!("legacy prompt adoption must require migration"), Err(error) => error, }; @@ -4417,7 +4462,10 @@ async fn legacy_prompt_references_migrate_explicitly_and_preserve_domain_task_st .await .unwrap(); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session(key.session_id).await.unwrap(); + let session = agent + .restore_session(key.session_id, Default::default()) + .await + .unwrap(); let state = session .get::("main") .unwrap() @@ -4472,7 +4520,7 @@ async fn a_restore_asks_for_consumptions_only_for_the_inputs_it_adopts() { profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -4547,7 +4595,10 @@ async fn a_restore_asks_for_consumptions_only_for_the_inputs_it_adopts() { profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); store.property_queries.lock().unwrap().clear(); - let session = agent.restore_session(id.clone()).await.unwrap(); + let session = agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); // The checkpoint rows the walk read: one per query whose kind is the // recovery key. Read them before anything else queries the store. let rows = store @@ -4676,7 +4727,7 @@ async fn a_change_naming_two_inputs_waits_for_both() { profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -4784,7 +4835,10 @@ async fn a_change_naming_two_inputs_waits_for_both() { if let Some(at) = hidden { *store.hidden_consumptions.lock().unwrap() = vec![change.inputs[at].clone()]; } - let session = agent.restore_session(id.clone()).await.unwrap(); + let session = agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); let state = session .get::(&child) .unwrap() @@ -4824,7 +4878,7 @@ async fn a_restore_reads_a_v1_checkpoints_boundary_from_source_through() { profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -4912,7 +4966,7 @@ async fn a_restore_reads_a_v1_checkpoints_boundary_from_source_through() { profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .restore_session(id) + .restore_session(id, Default::default()) .await .expect("a v1 checkpoint restores"); let state = session @@ -4947,7 +5001,7 @@ async fn a_line_starts_before_an_undelivered_removal_under_a_later_system_change profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -5151,7 +5205,7 @@ async fn a_line_starts_before_an_undelivered_removal_under_a_later_system_change ); profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); - let session = agent.restore_session(id).await.unwrap(); + let session = agent.restore_session(id, Default::default()).await.unwrap(); let child = session .branch( "main".into(), @@ -5239,7 +5293,7 @@ async fn a_long_inherited_suffix_keeps_each_consumption_query_bounded() { profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -5374,7 +5428,7 @@ async fn a_long_inherited_suffix_keeps_each_consumption_query_bounded() { profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .restore_session(id) + .restore_session(id, Default::default()) .await .expect("the restore succeeds"); let child = session @@ -5513,7 +5567,7 @@ async fn model_only_reload_hands_off_a_running_preparation_at_its_recovery_cut() builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let parts = session.branch_diagnostics("main").unwrap().plugins; diff --git a/crates/dim-agent-capabilities/tests/context_flow/digest.rs b/crates/dim-agent-capabilities/tests/context_flow/digest.rs index f0edc7793b..b489c69c8c 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/digest.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/digest.rs @@ -150,18 +150,21 @@ async fn effects_session( ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig { - tools: Some(vec![ - "declare".into(), - "declare_error".into(), - "plain".into(), - ]), - permission_policy: PermissionPolicy { - preset: PermissionPreset::FullAccess, + .create_session( + SessionConfig { + tools: Some(vec![ + "declare".into(), + "declare_error".into(), + "plain".into(), + ]), + permission_policy: PermissionPolicy { + preset: PermissionPreset::FullAccess, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); (agent, session) diff --git a/crates/dim-agent-capabilities/tests/context_flow/manual_compaction.rs b/crates/dim-agent-capabilities/tests/context_flow/manual_compaction.rs index 4f2b1ee49e..a1ba153e1b 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/manual_compaction.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/manual_compaction.rs @@ -337,7 +337,7 @@ async fn steers_wait_for_compaction_and_explicit_interrupts_still_cancel() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); turns(&session, &[first().as_str(), "second", "third"]).await; @@ -583,7 +583,7 @@ async fn a_manual_compaction_with_no_turn_writes_only_its_facts() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); turns(&session, &[first().as_str(), "second", "third"]).await; @@ -683,7 +683,7 @@ async fn a_checkpointed_step_renders_its_context_once() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); turns(&session, &[first().as_str(), "second", "third"]).await; @@ -797,7 +797,7 @@ async fn a_manual_compaction_keeps_at_most_the_latest_turn() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); turns(&session, &[first().as_str(), latest.as_str()]).await; @@ -847,7 +847,7 @@ async fn a_manual_compaction_inside_a_turn_runs_at_the_next_step_boundary() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); turns(&session, &[first().as_str(), "second"]).await; @@ -1079,7 +1079,7 @@ async fn a_replaced_strategy_is_replayed_by_the_same_rule_and_checked_by_the_pol builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); turns(&session, &[first().as_str(), "second", "third"]).await; @@ -1170,7 +1170,7 @@ async fn a_replaced_strategy_is_replayed_by_the_same_rule_and_checked_by_the_pol let agent = MinimalHost::start(&builder).await.unwrap(); let main_head = head("main").await; *store.fail_range.lock().unwrap() = Some(("main".into(), 1..=main_head, 1)); - let failed = agent.restore_session(id.clone()).await; + let failed = agent.restore_session(id.clone(), Default::default()).await; assert!( matches!(&failed, Err(error) if error.to_string().contains("injected history read failure")), "{:?}", @@ -1184,10 +1184,13 @@ async fn a_replaced_strategy_is_replayed_by_the_same_rule_and_checked_by_the_pol // the part's own read of this range is the second one. *store.hold_range.lock().unwrap() = Some(("main".into(), 1..=main_head, 2)); armed.store(true, Ordering::SeqCst); - let session = tokio::time::timeout(Duration::from_secs(5), agent.restore_session(id)) - .await - .expect("a read of a part does not wait for the held read") - .unwrap(); + let session = tokio::time::timeout( + Duration::from_secs(5), + agent.restore_session(id, Default::default()), + ) + .await + .expect("a read of a part does not wait for the held read") + .unwrap(); store.ranges.lock().unwrap().clear(); let queries = std::mem::take(&mut *store.queries.lock().unwrap()); // The opening part reads `main` from its start and the child from its own. @@ -1296,7 +1299,7 @@ async fn an_interrupt_cancels_a_running_step_and_a_pending_command() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); turns(&session, &[first().as_str(), "second", "third"]).await; @@ -1357,7 +1360,7 @@ async fn a_reload_during_a_step_settles_it_without_another_strategy_call() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); turns(&session, &[first().as_str(), "second", "third"]).await; @@ -1416,7 +1419,7 @@ async fn a_failed_manual_compaction_lets_the_turn_continue_and_recovery_compacts .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let first = "f".repeat(1_000); @@ -1541,7 +1544,7 @@ async fn repeated_and_concurrent_requests_join_the_outstanding_command() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); turns(&session, &[first().as_str(), "second", "third"]).await; @@ -1611,7 +1614,7 @@ async fn a_second_command_consumed_while_one_is_outstanding_is_skipped() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); turns(&session, &[first().as_str(), "second", "third"]).await; diff --git a/crates/dim-agent-capabilities/tests/context_flow/pinning.rs b/crates/dim-agent-capabilities/tests/context_flow/pinning.rs index c5fae7197e..6793c033fe 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/pinning.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/pinning.rs @@ -98,14 +98,17 @@ async fn tool_session( .await .unwrap(); let session = agent - .create_session(SessionConfig { - tools: Some(vec!["wait".into()]), - permission_policy: dim_agent_runtime::PermissionPolicy { - preset: dim_agent_runtime::PermissionPreset::FullAccess, + .create_session( + SessionConfig { + tools: Some(vec!["wait".into()]), + permission_policy: dim_agent_runtime::PermissionPolicy { + preset: dim_agent_runtime::PermissionPreset::FullAccess, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); (agent, session) @@ -337,14 +340,17 @@ async fn a_queued_input_consumed_at_the_next_turns_start_is_pinned() { .await .unwrap(); let session = agent - .create_session(SessionConfig { - tools: Some(vec!["wait".into()]), - permission_policy: dim_agent_runtime::PermissionPolicy { - preset: dim_agent_runtime::PermissionPreset::FullAccess, + .create_session( + SessionConfig { + tools: Some(vec!["wait".into()]), + permission_policy: dim_agent_runtime::PermissionPolicy { + preset: dim_agent_runtime::PermissionPreset::FullAccess, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); session @@ -477,7 +483,7 @@ async fn a_compaction_with_no_running_turn_pins_nothing() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); for text in ["x".repeat(1_500), "second".into()] { @@ -588,14 +594,17 @@ async fn cycles_session( .await .unwrap(); let session = agent - .create_session(SessionConfig { - tools: Some(vec!["wait".into()]), - permission_policy: dim_agent_runtime::PermissionPolicy { - preset: dim_agent_runtime::PermissionPreset::FullAccess, + .create_session( + SessionConfig { + tools: Some(vec!["wait".into()]), + permission_policy: dim_agent_runtime::PermissionPolicy { + preset: dim_agent_runtime::PermissionPreset::FullAccess, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); (agent, session) diff --git a/crates/dim-agent-capabilities/tests/context_flow/product_summary.rs b/crates/dim-agent-capabilities/tests/context_flow/product_summary.rs index 73d5bd4cbc..f5e066f0e9 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/product_summary.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/product_summary.rs @@ -452,7 +452,10 @@ async fn product_session_on( }) .await .unwrap(); - let session = agent.create_session(config_session).await.unwrap(); + let session = agent + .create_session(config_session, Default::default()) + .await + .unwrap(); (agent, session) } diff --git a/crates/dim-agent-capabilities/tests/context_flow/replan.rs b/crates/dim-agent-capabilities/tests/context_flow/replan.rs index e6394e842a..caa5c4726c 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/replan.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/replan.rs @@ -139,7 +139,7 @@ async fn replanned_session_with( ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); (agent, session) diff --git a/crates/dim-agent-capabilities/tests/context_flow/retention.rs b/crates/dim-agent-capabilities/tests/context_flow/retention.rs index 08e7d43b08..57761d317c 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/retention.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/retention.rs @@ -25,7 +25,7 @@ async fn compact_after_small_turns( .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -84,7 +84,7 @@ async fn a_cut_on_the_retention_window_boundary_stays_a_legal_cut() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -212,7 +212,7 @@ async fn a_tail_that_cannot_fit_the_bound_is_replaced_entirely() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -388,7 +388,7 @@ async fn recovery_compares_the_provider_baseline_estimate_with_the_input_budget( profile.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&profile).await.unwrap(); let session = agent - .restore_session("provider-recovery".into()) + .restore_session("provider-recovery".into(), Default::default()) .await .unwrap(); for text in ["x".repeat(1_500), "second".into()] { @@ -487,7 +487,7 @@ async fn automatic_compaction_waits_for_a_quarter_of_the_budget_of_new_history() .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let starts = |events: &[Arc]| { @@ -558,7 +558,7 @@ async fn compact_marked( .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -641,7 +641,7 @@ async fn a_summary_that_overshoots_the_budget_fails_the_recovery_request() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -728,7 +728,7 @@ async fn a_child_branch_regrows_from_its_own_history() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); for text in ["p".repeat(1_500), "q".repeat(1_500)] { @@ -860,7 +860,7 @@ async fn a_budget_retry_reuses_a_cut_before_the_latest_turn_start() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session diff --git a/crates/dim-agent-capabilities/tests/dispatch_flow.rs b/crates/dim-agent-capabilities/tests/dispatch_flow.rs index 3d279a0026..8d3b85bf15 100644 --- a/crates/dim-agent-capabilities/tests/dispatch_flow.rs +++ b/crates/dim-agent-capabilities/tests/dispatch_flow.rs @@ -90,7 +90,7 @@ async fn handler_panic_is_attributed_and_freezes_the_dispatch_cursor() { }, )); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let input = soon(session.submit("hello".into(), InputMode::Queue, "main")) @@ -170,7 +170,7 @@ async fn domain_wildcard_subscribes_to_every_key_in_that_domain() { }), ); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.submit("hello".into(), InputMode::Queue, "main")) @@ -231,7 +231,7 @@ async fn loop_publishes_running_only_once_turn_start_is_dispatched() { }, )); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.submit("hello".into(), InputMode::Queue, "main")) diff --git a/crates/dim-agent-capabilities/tests/faces_flow.rs b/crates/dim-agent-capabilities/tests/faces_flow.rs index eaa8ef5ee8..68ee8701bf 100644 --- a/crates/dim-agent-capabilities/tests/faces_flow.rs +++ b/crates/dim-agent-capabilities/tests/faces_flow.rs @@ -107,13 +107,16 @@ async fn fixture(tools: Arc) -> Fixture { })); let host = MinimalHost::start(&builder).await.unwrap(); let session = host - .create_session(SessionConfig { - permission_policy: PermissionPolicy { - preset: PermissionPreset::WorkspaceWrite, + .create_session( + SessionConfig { + permission_policy: PermissionPolicy { + preset: PermissionPreset::WorkspaceWrite, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); let session_instance = group_instance(&session.diagnostics().unwrap(), "SessionScope"); diff --git a/crates/dim-agent-capabilities/tests/flows.rs b/crates/dim-agent-capabilities/tests/flows.rs index 3cc9e85abb..576379766e 100644 --- a/crates/dim-agent-capabilities/tests/flows.rs +++ b/crates/dim-agent-capabilities/tests/flows.rs @@ -18,7 +18,10 @@ async fn agent() -> MinimalHost { async fn echo_tools_and_observable_state_follow_the_public_flow() { tokio::time::timeout(Duration::from_secs(10), async { let agent = agent().await; - let session = agent.create_session(SessionConfig::default()).await.unwrap(); + let session = agent + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); session.submit("hello".into(), InputMode::Queue, "main").await.unwrap(); session.idle("main").await.unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -55,7 +58,7 @@ async fn stop_ends_the_turn_and_a_waiting_queue_input_runs_next() { let agent = agent().await; let root = agent.root().clone(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let mut events = Events::follow(&root, &session, "main", 0).await; @@ -114,7 +117,7 @@ async fn branch_tool_reuses_capabilities_without_replaying_ancestor_inputs() { tokio::time::timeout(Duration::from_secs(10), async { let agent = agent().await; let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -184,7 +187,7 @@ async fn closed_default_memory_sessions_release_history_but_shared_stores_retain } let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -195,7 +198,7 @@ async fn closed_default_memory_sessions_release_history_but_shared_stores_retain let id = session.id().to_owned(); session.close().await.unwrap(); drop(session); - let restored = agent.restore_session(id).await; + let restored = agent.restore_session(id, Default::default()).await; if shared { let session = restored.unwrap(); assert!(chain_events(&session, "main", ..).await.unwrap().iter().any(|event| @@ -217,7 +220,7 @@ async fn the_prompt_projection_covers_the_facts_a_restored_branch_published() { )); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let model = |model_id: &str| ConfigureUpdate { @@ -247,7 +250,7 @@ async fn the_prompt_projection_covers_the_facts_a_restored_branch_published() { ); let id = session.id().to_owned(); session.close().await.unwrap(); - let restored = agent.restore_session(id).await.unwrap(); + let restored = agent.restore_session(id, Default::default()).await.unwrap(); assert_eq!( projection(&restored), loaded, @@ -278,7 +281,7 @@ async fn repeated_idle_release_checks_never_reject_a_running_turn() { let agent = MinimalHost::start(&builder).await.unwrap(); let root = agent.root().clone(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let mut events = Events::follow(&root, &session, "main", 0).await; @@ -356,7 +359,7 @@ async fn a_refused_idle_release_reopens_the_branch_for_the_running_turn() { let agent = MinimalHost::start(&builder).await.unwrap(); let root = agent.root().clone(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let mut events = Events::follow(&root, &session, "main", 0).await; diff --git a/crates/dim-agent-capabilities/tests/hooks_flow.rs b/crates/dim-agent-capabilities/tests/hooks_flow.rs index 77e88cfdf4..11859ff337 100644 --- a/crates/dim-agent-capabilities/tests/hooks_flow.rs +++ b/crates/dim-agent-capabilities/tests/hooks_flow.rs @@ -718,13 +718,16 @@ impl Env { async fn session_with(&self, preset: PermissionPreset) -> Session { self.agent - .create_session(SessionConfig { - permission_policy: PermissionPolicy { - preset, - ..Default::default() + .create_session( + SessionConfig { + permission_policy: PermissionPolicy { + preset, + ..Default::default() + }, + ..self.session_config() }, - ..self.session_config() - }) + Default::default(), + ) .await .unwrap() } @@ -2138,16 +2141,19 @@ async fn member_session_payloads_carry_collaboration_role() { }))); let member = env .agent - .create_session(SessionConfig { - cwd: env.dir.join("work").to_string_lossy().into_owned(), - tools: Some(env.mounted.clone()), - permission_policy: PermissionPolicy { - preset: PermissionPreset::FullAccess, + .create_session( + SessionConfig { + cwd: env.dir.join("work").to_string_lossy().into_owned(), + tools: Some(env.mounted.clone()), + permission_policy: PermissionPolicy { + preset: PermissionPreset::FullAccess, + ..Default::default() + }, + collaboration_role: CollaborationRole::Member, ..Default::default() }, - collaboration_role: CollaborationRole::Member, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); let leader = env.session().await; @@ -2441,7 +2447,11 @@ async fn a_second_session_start_does_not_run_the_hooks_again() { wait_blocks(&session, "session-start", 1).await; let id = session.id().to_owned(); session.close().await.unwrap(); - let restored = env.agent.restore_session(id).await.unwrap(); + let restored = env + .agent + .restore_session(id, Default::default()) + .await + .unwrap(); tokio::time::sleep(Duration::from_millis(300)).await; assert_eq!(std::fs::read_to_string(&runs).unwrap(), "start\n"); assert_eq!(hook_blocks(&restored, "session-start").await.len(), 1); @@ -4106,7 +4116,11 @@ async fn matchers_keep_selecting_tools_with_an_adopted_tool_part() { assert_eq!(last_result(&session).await.is_error, None); let id = session.id().to_owned(); session.close().await.unwrap(); - let restored = env.agent.restore_session(id).await.unwrap(); + let restored = env + .agent + .restore_session(id, Default::default()) + .await + .unwrap(); std::fs::remove_file(&bash).unwrap(); std::fs::remove_file(&mcp).unwrap(); turn(&restored, "tool:exec {\"command\":\"true\"}").await; @@ -4581,7 +4595,11 @@ async fn a_queued_follow_up_keeps_its_round_after_session_restore() { "Stop": [command(serde_json::json!({"type":"command", "command":format!("{{ cat; echo; }} >> {}; echo again >&2; exit 2",payloads.display())}))] }))); stored_session(&env, "follow-up", vec![queued_follow_up(Some(2))]).await; - let session = env.agent.restore_session("follow-up".into()).await.unwrap(); + let session = env + .agent + .restore_session("follow-up".into(), Default::default()) + .await + .unwrap(); wait_blocks(&session, "follow-up", 2).await; wait_event(&session, |kind| match kind { EventKind::InputMessage(data) @@ -4639,7 +4657,7 @@ async fn a_legacy_queued_follow_up_finishes_without_starting_another_hook() { stored_session(&env, "legacy-follow-up", vec![queued_follow_up(None)]).await; let session = env .agent - .restore_session("legacy-follow-up".into()) + .restore_session("legacy-follow-up".into(), Default::default()) .await .unwrap(); wait_event(&session, |kind| { @@ -4702,7 +4720,7 @@ async fn recovery_settlements_start_no_hook_but_new_tool_failures_do() { stored_session(&env, "unfinished-tool", prefix).await; let session = env .agent - .restore_session("unfinished-tool".into()) + .restore_session("unfinished-tool".into(), Default::default()) .await .unwrap(); wait_event(&session, |kind| matches!(kind, EventKind::ToolResult(data) if data.call_event_id.as_deref() == Some(batch.id.as_str())).then_some(())).await; diff --git a/crates/dim-agent-capabilities/tests/host_flows.rs b/crates/dim-agent-capabilities/tests/host_flows.rs index 5937c23da6..cd14c9a56a 100644 --- a/crates/dim-agent-capabilities/tests/host_flows.rs +++ b/crates/dim-agent-capabilities/tests/host_flows.rs @@ -264,7 +264,7 @@ async fn run_cuts(cut: Cut, cuts: usize) -> (Vec>, Mi .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -320,7 +320,7 @@ async fn a_steer_applied_before_a_failed_step_takes_over_instead_of_continuing() .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let waiting = arrived.notified(); @@ -398,7 +398,7 @@ async fn the_continuation_reads_the_closure_result_of_the_announced_call() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -627,7 +627,7 @@ async fn run_announcing_failure( builder.plugin(move |_| Ok(Box::new(AnnouncingHosts(hosts.clone())))); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -837,7 +837,7 @@ async fn a_continuation_spends_the_rest_of_the_failed_request_chain() { builder.plugin(move |_| Ok(Box::new(QuietThenAnnouncedHosts(hosts.clone())))); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -905,7 +905,7 @@ async fn a_compaction_step_before_the_continuation_keeps_its_chain() { builder.plugin(move |_| Ok(Box::new(QuietThenAnnouncedHosts(hosts.clone())))); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1045,7 +1045,10 @@ async fn a_max_tokens_turn_keeps_the_session_usable_with_a_larger_output_limit() ..Default::default() }); let mut model = config.model.clone(); - let session = agent.create_session(config).await.unwrap(); + let session = agent + .create_session(config, Default::default()) + .await + .unwrap(); session .submit("first".into(), InputMode::Queue, "main") .await @@ -1126,7 +1129,7 @@ async fn a_failure_without_facts_keeps_its_message_and_bounds_the_reason() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1222,7 +1225,7 @@ async fn steer_and_append_enter_the_current_turn_at_tool_result_while_queue_wait )) .await .unwrap(); - let session = agent.create_session(SessionConfig { tools: Some(vec!["boundary".into()]), permission_policy: dim_agent_runtime::PermissionPolicy { preset: dim_agent_runtime::PermissionPreset::FullAccess, ..Default::default() }, ..Default::default() }).await.unwrap(); + let session = agent.create_session(SessionConfig { tools: Some(vec!["boundary".into()]), permission_policy: dim_agent_runtime::PermissionPolicy { preset: dim_agent_runtime::PermissionPreset::FullAccess, ..Default::default() }, ..Default::default() }, Default::default()).await.unwrap(); session.submit("tool:boundary {}".into(), InputMode::Queue, "main").await.unwrap(); entered.notified().await; let queued = session.submit("next turn".into(), InputMode::Queue, "main").await.unwrap(); @@ -1290,7 +1293,7 @@ async fn model_receives_the_committed_before_result_and_fixed_history() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1369,7 +1372,7 @@ async fn stop_waits_for_native_cleanup_and_keeps_a_real_success() { let agent = MinimalHost::start(&builder(Arc::new(EchoModel), Arc::new(tools))) .await .unwrap(); - let session = agent.create_session(SessionConfig { tools: Some(vec!["delayed".into()]), permission_policy: dim_agent_runtime::PermissionPolicy { preset: dim_agent_runtime::PermissionPreset::FullAccess, ..Default::default() }, ..SessionConfig::default() }).await.unwrap(); + let session = agent.create_session(SessionConfig { tools: Some(vec!["delayed".into()]), permission_policy: dim_agent_runtime::PermissionPolicy { preset: dim_agent_runtime::PermissionPreset::FullAccess, ..Default::default() }, ..SessionConfig::default() }, Default::default()).await.unwrap(); session.submit("tool:delayed {}".into(), InputMode::Queue, "main").await.unwrap(); started.notified().await; session.stop("main", "stop".into()).await.unwrap(); @@ -1440,7 +1443,7 @@ async fn invalid_model_stream_is_cancelled_and_drained_before_settlement() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1958,7 +1961,7 @@ async fn recovery_agent_with( } let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); (agent, session, probe) @@ -2218,7 +2221,7 @@ async fn process_model_recovery_respects_output_cleanup_and_cancellation() { builder.plugin(move |_| Ok(Box::new(RecoveryHosts(hosts.clone())))); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -2322,7 +2325,7 @@ async fn transient_retries_are_bounded_and_stop_after_irreversible_output() { builder.plugin(move |_| Ok(Box::new(RecoveryHosts(hosts.clone())))); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -2445,7 +2448,7 @@ async fn waiting_to_retry_obeys_stop_steer_and_provider_reload() { builder.plugin(move |_| Ok(Box::new(RecoveryHosts(hosts.clone())))); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -2599,7 +2602,7 @@ async fn stop_during_native_drain_keeps_an_already_completed_model_result() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -2912,7 +2915,10 @@ async fn an_idle_append_starts_no_turn_and_joins_the_next_one() { )) .await .unwrap(); - let session = agent.create_session(SessionConfig::default()).await.unwrap(); + let session = agent + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); let appended = session.submit("idle context".into(), InputMode::Append, "main").await.unwrap(); session.idle("main").await.unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -2997,7 +3003,10 @@ async fn a_steer_during_output_continues_the_turn_instead_of_ending_it() { Arc::new(HeldOutput { requests: requests.clone(), release: release.clone() }), Arc::new(MockTools), )).await.unwrap(); - let session = agent.create_session(SessionConfig::default()).await.unwrap(); + let session = agent + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); session.submit("first".into(), InputMode::Queue, "main").await.unwrap(); let mut dispatch = session.dispatch_watch("main").unwrap(); loop { @@ -3080,7 +3089,7 @@ async fn model_output_is_committed_per_block_and_shown_as_progress_until_then() .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -3260,7 +3269,7 @@ async fn a_thinking_block_keeps_its_start_in_progress_and_history() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -3420,7 +3429,7 @@ async fn end_markers_do_not_split_adjacent_blocks() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -3542,7 +3551,7 @@ async fn buffered_text_is_committed_once_a_second_old() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -3616,14 +3625,17 @@ async fn a_held_input_is_withdrawn_once_and_an_applied_one_is_not() { .await .unwrap(); let session = agent - .create_session(SessionConfig { - tools: Some(vec!["boundary".into()]), - permission_policy: dim_agent_runtime::PermissionPolicy { - preset: dim_agent_runtime::PermissionPreset::FullAccess, + .create_session( + SessionConfig { + tools: Some(vec!["boundary".into()]), + permission_policy: dim_agent_runtime::PermissionPolicy { + preset: dim_agent_runtime::PermissionPreset::FullAccess, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); session @@ -3828,14 +3840,17 @@ async fn deleted(session: &dim_agent_runtime::Session, id: &str) -> Vec dim_agent_runtime::Session { agent - .create_session(SessionConfig { - tools: Some(vec!["boundary".into()]), - permission_policy: dim_agent_runtime::PermissionPolicy { - preset: dim_agent_runtime::PermissionPreset::FullAccess, + .create_session( + SessionConfig { + tools: Some(vec!["boundary".into()]), + permission_policy: dim_agent_runtime::PermissionPolicy { + preset: dim_agent_runtime::PermissionPreset::FullAccess, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap() } @@ -4179,7 +4194,7 @@ async fn a_handover_input_written_while_idle_starts_no_turn() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let handover = session @@ -4400,7 +4415,10 @@ async fn vision_and_text_models_route_images_without_changing_history() { )) .await .unwrap(); - let session = agent.create_session(SessionConfig::default()).await.unwrap(); + let session = agent + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); session .configure(ConfigureUpdate { model: Some(model_with_vision("seeing", true)), ..Default::default() }, "main") .await @@ -4561,11 +4579,14 @@ async fn stored_attachment_and_tool_images_route_by_vision_capability() { builder.process_value(Arc::new(SessionFiles(files.clone()))); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig { - model: model_with_vision("vision", true), - tools: Some(vec!["shot".into()]), - ..Default::default() - }) + .create_session( + SessionConfig { + model: model_with_vision("vision", true), + tools: Some(vec!["shot".into()]), + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); let bytes = base64::engine::general_purpose::STANDARD @@ -4784,10 +4805,13 @@ async fn a_gemini_request_does_not_charge_a_gif_against_the_encoded_image_budget .await .unwrap(); let session = agent - .create_session(SessionConfig { - model: model_with_vision("gemini", true), - ..Default::default() - }) + .create_session( + SessionConfig { + model: model_with_vision("gemini", true), + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); let bytes = base64::engine::general_purpose::STANDARD @@ -4921,10 +4945,13 @@ async fn a_native_xai_request_turns_an_unsupported_image_into_its_reference() { .await .unwrap(); let session = agent - .create_session(SessionConfig { - model: model_with_vision("native-xai", true), - ..Default::default() - }) + .create_session( + SessionConfig { + model: model_with_vision("native-xai", true), + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); let bytes = base64::engine::general_purpose::STANDARD @@ -5062,10 +5089,13 @@ async fn a_compatible_xai_request_turns_an_unsupported_image_into_its_reference( .await .unwrap(); let session = agent - .create_session(SessionConfig { - model: model_with_vision("compatible-xai", true), - ..Default::default() - }) + .create_session( + SessionConfig { + model: model_with_vision("compatible-xai", true), + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); let bytes = base64::engine::general_purpose::STANDARD @@ -5155,10 +5185,13 @@ async fn a_vision_model_receives_stored_attachment_and_tool_images_as_pixels() { builder.process_value(Arc::new(SessionFiles(files.clone()))); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig { - tools: Some(vec!["shot".into()]), - ..Default::default() - }) + .create_session( + SessionConfig { + tools: Some(vec!["shot".into()]), + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); let bytes = base64::engine::general_purpose::STANDARD @@ -5489,11 +5522,14 @@ async fn replacing_a_tool_image_preserves_other_messages_and_the_stored_result() .await .unwrap(); let session = agent - .create_session(SessionConfig { - model: model_with_vision("conversational", vision), - tools: Some(vec!["shot".into()]), - ..Default::default() - }) + .create_session( + SessionConfig { + model: model_with_vision("conversational", vision), + tools: Some(vec!["shot".into()]), + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); session @@ -5682,7 +5718,10 @@ async fn tool_result_estimates(with_image: bool) -> Vec { reasoning: None, service_tier: None, }); - let session = agent.create_session(config).await.unwrap(); + let session = agent + .create_session(config, Default::default()) + .await + .unwrap(); session .submit("tool:shot {}".into(), InputMode::Queue, "main") .await diff --git a/crates/dim-agent-capabilities/tests/input_flow.rs b/crates/dim-agent-capabilities/tests/input_flow.rs index b1ad2c2709..87f0e17e57 100644 --- a/crates/dim-agent-capabilities/tests/input_flow.rs +++ b/crates/dim-agent-capabilities/tests/input_flow.rs @@ -62,7 +62,10 @@ async fn start(store: Arc) -> Fixture { defaults::mock_hosts(&mut builder); defaults::install(&mut builder); let host = MinimalHost::start(&builder).await.unwrap(); - let session = host.create_session(SessionConfig::default()).await.unwrap(); + let session = host + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); Fixture { host, session } } @@ -130,7 +133,10 @@ async fn quiet() -> Fixture { ); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(memory())); let host = MinimalHost::start(&builder).await.unwrap(); - let session = host.create_session(SessionConfig::default()).await.unwrap(); + let session = host + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); Fixture { host, session } } diff --git a/crates/dim-agent-capabilities/tests/interrupt_flow.rs b/crates/dim-agent-capabilities/tests/interrupt_flow.rs index d32b6f5058..b01785e58e 100644 --- a/crates/dim-agent-capabilities/tests/interrupt_flow.rs +++ b/crates/dim-agent-capabilities/tests/interrupt_flow.rs @@ -262,7 +262,7 @@ async fn interrupt_reaches_every_capability_before_native_cleanup_and_stop_waits }), ); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); let diagnostics = session.branch_diagnostics("main").unwrap(); @@ -442,7 +442,7 @@ async fn input_written_before_an_interrupt_waits_for_the_next_driving_input() { }), ); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -533,7 +533,7 @@ fn echoed(events: &[Arc], text: &str) -> bool { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_steer_input_after_a_stop_starts_a_turn() { let (agent, _gate) = gated().await; - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); soon(session.stop("main", "operator stop".into())) @@ -634,7 +634,7 @@ async fn a_tool_call_already_committed_when_the_interrupt_arrives_is_not_execute ); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -708,7 +708,7 @@ async fn stop_waits_for_an_interrupted_turn_whose_start_is_not_yet_dispatched() }), ); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -896,7 +896,7 @@ async fn a_stop_during_output_keeps_its_text_and_closes_every_started_call() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -1061,7 +1061,7 @@ async fn a_replaced_request_commits_no_output_its_host_still_streams() { let mut builder = channel_builder(model.clone()); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -1205,7 +1205,7 @@ async fn a_steer_during_preparation_ends_the_request_before_the_model_call() { defaults::tool_host(&mut builder, Arc::new(MockTools)); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -1315,7 +1315,7 @@ async fn a_steer_consumed_after_the_first_output_waits_for_the_output_end() { ); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -1527,7 +1527,7 @@ async fn a_steer_is_not_consumed_between_a_failed_call_and_its_terminal() { let (gate, hold) = hold_terminal(&mut builder); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -1590,7 +1590,7 @@ async fn a_steer_is_not_consumed_between_a_failed_preparation_and_its_terminal() let (gate, hold) = hold_terminal(&mut builder); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -1614,7 +1614,7 @@ async fn stop_turn_stops_only_the_open_turn_it_names() { let mut builder = channel_builder(model.clone()); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); session @@ -1841,14 +1841,17 @@ async fn an_interrupt_while_a_later_segment_waits_cancels_those_calls() { dim_agent_capabilities::register_names(&mut builder); defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig { - tools: Some(vec!["x0".into(), "x1".into(), "c2".into()]), - permission_policy: PermissionPolicy { - preset: PermissionPreset::FullAccess, - ..Default::default() + let session = soon(agent.create_session( + SessionConfig { + tools: Some(vec!["x0".into(), "x1".into(), "c2".into()]), + permission_policy: PermissionPolicy { + preset: PermissionPreset::FullAccess, + ..Default::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - })) + Default::default(), + )) .await .unwrap(); session diff --git a/crates/dim-agent-capabilities/tests/legacy_session_faces.rs b/crates/dim-agent-capabilities/tests/legacy_session_faces.rs index 0531696744..37fcffb257 100644 --- a/crates/dim-agent-capabilities/tests/legacy_session_faces.rs +++ b/crates/dim-agent-capabilities/tests/legacy_session_faces.rs @@ -196,8 +196,12 @@ async fn the_agent_config_face_resolves_inside_each_session_instance() { }, )); let host = MinimalHost::start(&builder).await.unwrap(); - host.create_session(SessionConfig::default()).await.unwrap(); - host.create_session(SessionConfig::default()).await.unwrap(); + host.create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); + host.create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); assert_eq!(reads.load(Ordering::SeqCst), 2); host.close().await.unwrap(); } diff --git a/crates/dim-agent-capabilities/tests/model_stream_recovery_flow.rs b/crates/dim-agent-capabilities/tests/model_stream_recovery_flow.rs index c5581b8481..b87c331a3e 100644 --- a/crates/dim-agent-capabilities/tests/model_stream_recovery_flow.rs +++ b/crates/dim-agent-capabilities/tests/model_stream_recovery_flow.rs @@ -265,7 +265,7 @@ async fn a_stream_cut_before_any_committed_event_retries_in_place() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -369,7 +369,7 @@ async fn a_stream_cut_after_a_committed_event_ends_the_turn_without_retrying() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -424,7 +424,7 @@ async fn a_usage_fact_before_a_cut_stops_the_retry() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -515,7 +515,7 @@ async fn an_idle_timeout_before_any_committed_event_retries_in_place() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -583,7 +583,7 @@ async fn an_idle_timeout_after_a_committed_event_ends_the_turn_without_retrying( .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -632,7 +632,7 @@ async fn thinking_progress_is_shown_once_per_interval() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -733,7 +733,7 @@ async fn a_text_delta_shows_buffered_thinking_at_once() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -797,7 +797,7 @@ async fn a_tool_start_shows_buffered_thinking_at_once() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -858,7 +858,7 @@ async fn buffered_thinking_is_shown_within_one_interval_without_another_delta() .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -924,7 +924,7 @@ async fn a_thinking_block_end_shows_the_buffer_at_once() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -996,7 +996,7 @@ async fn a_pending_thinking_buffer_is_not_shown_after_a_retry() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1175,7 +1175,7 @@ async fn a_steer_during_the_retry_backoff_replaces_the_attempt() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1262,7 +1262,7 @@ async fn a_steer_during_a_terminal_failure(kind: ModelFailureKind, retry_after: .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1495,7 +1495,7 @@ async fn a_credential_refresh_clears_the_attempt_only_once_it_succeeds() { }); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1623,7 +1623,7 @@ async fn thinking_progress_volume_is_throttled() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1691,7 +1691,7 @@ async fn a_retry_that_emits_no_output_names_its_boundary_on_the_terminal() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1768,7 +1768,7 @@ async fn a_retry_that_shows_its_own_thought_names_that_block_on_the_terminal() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -1853,7 +1853,7 @@ async fn a_failure_without_a_retry_omits_the_retry_boundary() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session diff --git a/crates/dim-agent-capabilities/tests/permission_flow.rs b/crates/dim-agent-capabilities/tests/permission_flow.rs index 735f102822..07aae6e3c5 100644 --- a/crates/dim-agent-capabilities/tests/permission_flow.rs +++ b/crates/dim-agent-capabilities/tests/permission_flow.rs @@ -275,7 +275,7 @@ async fn restore_cancels_only_unsettled_approvals_across_pages_without_running_t defaults::tool_host(&mut builder, tools.clone()); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .restore_session("approval-recovery".into()) + .restore_session("approval-recovery".into(), Default::default()) .await .unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -536,7 +536,10 @@ async fn a_composition_without_facts_builds_and_asks() { let work = temporary_directory("no-grants"); let agent = agent(Arc::new(RiskTools::default())).await; let session = agent - .create_session(config_in(&work, preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config_in(&work, preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -596,7 +599,7 @@ async fn file_write_facts_decide_each_path_by_preset() { ), ] { let session = agent - .create_session(config_in(&work, preset(policy))) + .create_session(config_in(&work, preset(policy)), Default::default()) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -617,7 +620,10 @@ async fn file_write_facts_decide_each_path_by_preset() { // A relative target is resolved against the Session cwd with the // tools' resolver before the facts. let session = agent - .create_session(config_in(&work, preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config_in(&work, preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -636,14 +642,17 @@ async fn file_write_facts_decide_each_path_by_preset() { // An explicit tool allow does not bypass a path fact. let session = agent - .create_session(config_in( - &work, - PermissionPolicy { - preset: PermissionPreset::WorkspaceWrite, - allowed_tools: vec!["write".into()], - ..Default::default() - }, - )) + .create_session( + config_in( + &work, + PermissionPolicy { + preset: PermissionPreset::WorkspaceWrite, + allowed_tools: vec!["write".into()], + ..Default::default() + }, + ), + Default::default(), + ) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -655,7 +664,10 @@ async fn file_write_facts_decide_each_path_by_preset() { // An unreadable ownership or grants source denies instead of asking. files.fail(true); let session = agent - .create_session(config_in(&work, preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config_in(&work, preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -717,7 +729,7 @@ async fn file_read_facts_decide_each_path_by_preset() { (PermissionPreset::FullAccess, ["allow"; 6]), ] { let session = agent - .create_session(config_in(&work, preset(policy))) + .create_session(config_in(&work, preset(policy)), Default::default()) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -765,7 +777,10 @@ async fn file_read_facts_decide_each_path_by_preset() { // resolver before the facts. `grep` and `glob` without a path search // the cwd, which is the workspace. let session = agent - .create_session(config_in(&work, preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config_in(&work, preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -803,7 +818,10 @@ async fn file_read_facts_decide_each_path_by_preset() { std::os::unix::fs::symlink(&root, &escape).unwrap(); std::os::unix::fs::symlink(&work, into_workspace.join("work")).unwrap(); let session = agent - .create_session(config_in(&work, preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config_in(&work, preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -819,14 +837,17 @@ async fn file_read_facts_decide_each_path_by_preset() { // An explicit tool allow does not bypass a path fact. let session = agent - .create_session(config_in( - &work, - PermissionPolicy { - preset: PermissionPreset::ReadOnly, - allowed_tools: vec!["read".into()], - ..Default::default() - }, - )) + .create_session( + config_in( + &work, + PermissionPolicy { + preset: PermissionPreset::ReadOnly, + allowed_tools: vec!["read".into()], + ..Default::default() + }, + ), + Default::default(), + ) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -837,7 +858,10 @@ async fn file_read_facts_decide_each_path_by_preset() { // An unreadable ownership or grants source denies instead of asking. files.fail(true); let session = agent - .create_session(config_in(&work, preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config_in(&work, preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -848,7 +872,10 @@ async fn file_read_facts_decide_each_path_by_preset() { grants.set(None); files.fail(false); let session = agent - .create_session(config_in(&work, preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config_in(&work, preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -875,7 +902,10 @@ async fn a_session_grant_matches_only_the_canonical_target_and_mode() { let tools = Arc::new(RiskTools::default()); let agent = granted_agent(tools.clone(), grants.clone(), files).await; let session = agent - .create_session(config_in(&work, preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config_in(&work, preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -992,7 +1022,10 @@ async fn presets_decide_by_risk_and_denied_calls_do_not_run() { (PermissionPreset::FullAccess, ["allow"; 6]), ]; for (policy, verdicts) in expected { - let session = agent.create_session(config(preset(policy))).await.unwrap(); + let session = agent + .create_session(config(preset(policy)), Default::default()) + .await + .unwrap(); let permission = session.service::("main").unwrap(); for ((name, risk), expected) in TOOLS.iter().zip(verdicts) { assert_eq!( @@ -1004,7 +1037,7 @@ async fn presets_decide_by_risk_and_denied_calls_do_not_run() { session.close().await.unwrap(); } let session = agent - .create_session(config(PermissionPolicy::default())) + .create_session(config(PermissionPolicy::default()), Default::default()) .await .unwrap(); assert!(call(&session, "write").await); @@ -1068,7 +1101,10 @@ async fn tool_lists_override_presets_and_disallowed_wins() { .unwrap() .clone(); let risk = TOOLS.iter().find(|(tool, _)| *tool == name).unwrap().1; - let session = agent.create_session(config(policy)).await.unwrap(); + let session = agent + .create_session(config(policy), Default::default()) + .await + .unwrap(); let permission = session.service::("main").unwrap(); assert_eq!(verdict(&permission, &name, risk).await, expected); session.close().await.unwrap(); @@ -1082,7 +1118,7 @@ async fn updates_are_versioned_per_branch_take_effect_when_dispatched_and_surviv let tools = Arc::new(RiskTools::default()); let agent = agent(tools.clone()).await; let session = agent - .create_session(config(serde_json::from_value(serde_json::json!({"preset":"full-access","fileAccess":"read-only","toolApproval":"ask","allowedTools":[],"disallowedTools":[]})).unwrap())) + .create_session(config(serde_json::from_value(serde_json::json!({"preset":"full-access","fileAccess":"read-only","toolApproval":"ask","allowedTools":[],"disallowedTools":[]})).unwrap()), Default::default()) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -1175,7 +1211,7 @@ async fn updates_are_versioned_per_branch_take_effect_when_dispatched_and_surviv let id = session.id().to_owned(); session.close().await.unwrap(); drop(session); - let restored = agent.restore_session(id).await.unwrap(); + let restored = agent.restore_session(id, Default::default()).await.unwrap(); assert_eq!( restored.get::("main").unwrap().unwrap(), current @@ -1194,7 +1230,10 @@ async fn full_access_releases_all_waiting_calls_without_user_responses() { let rules = TestRules::new(vec![]); let agent = ruled_agent(tools.clone(), rules.clone()).await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let child = session @@ -1313,7 +1352,10 @@ async fn a_policy_denial_settles_a_waiting_call_without_a_user_response() { let tools = Arc::new(RiskTools::default()); let agent = agent(tools.clone()).await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); session @@ -1437,7 +1479,10 @@ async fn a_response_that_finds_its_batch_stopped_ends_as_an_interrupt() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); session @@ -1492,7 +1537,10 @@ async fn allow_rules_answer_approval_only_for_simple_commands_within_the_preset( let rules = TestRules::new(vec![rule("cargo test", Prefix, Allow)]); let agent = ruled_agent(tools.clone(), rules).await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); assert_eq!(text(&exec(&session, "cargo test -p x").await), "exec ran"); @@ -1508,7 +1556,10 @@ async fn allow_rules_answer_approval_only_for_simple_commands_within_the_preset( session.close().await.unwrap(); let session = agent - .create_session(config(preset(PermissionPreset::ReadOnly))) + .create_session( + config(preset(PermissionPreset::ReadOnly)), + Default::default(), + ) .await .unwrap(); assert_eq!( @@ -1519,10 +1570,13 @@ async fn allow_rules_answer_approval_only_for_simple_commands_within_the_preset( session.close().await.unwrap(); { let session = agent - .create_session(config(PermissionPolicy { - preset: PermissionPreset::WorkspaceWrite, - ..Default::default() - })) + .create_session( + config(PermissionPolicy { + preset: PermissionPreset::WorkspaceWrite, + ..Default::default() + }), + Default::default(), + ) .await .unwrap(); assert_eq!(text(&exec(&session, "cargo test -p x").await), "exec ran"); @@ -1553,7 +1607,10 @@ async fn deny_rules_match_any_segment_under_every_preset_and_are_read_at_use_tim let rules = TestRules::new(vec![]); let agent = ruled_agent(tools.clone(), rules.clone()).await; let session = agent - .create_session(config(preset(PermissionPreset::FullAccess))) + .create_session( + config(preset(PermissionPreset::FullAccess)), + Default::default(), + ) .await .unwrap(); assert_eq!(text(&exec(&session, "git push origin").await), "exec ran"); @@ -1574,11 +1631,14 @@ async fn deny_rules_match_any_segment_under_every_preset_and_are_read_at_use_tim session.close().await.unwrap(); { let session = agent - .create_session(config(PermissionPolicy { - preset: PermissionPreset::FullAccess, - allowed_tools: vec!["exec".into()], - ..Default::default() - })) + .create_session( + config(PermissionPolicy { + preset: PermissionPreset::FullAccess, + allowed_tools: vec!["exec".into()], + ..Default::default() + }), + Default::default(), + ) .await .unwrap(); assert_eq!( @@ -1602,7 +1662,10 @@ async fn a_deny_rule_written_while_approval_is_pending_cancels_the_allowed_call( let rules = TestRules::new(vec![]); let agent = ruled_agent(tools.clone(), rules.clone()).await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); submit_exec(&session, "git push").await; @@ -1647,7 +1710,10 @@ async fn unreadable_rules_deny_command_calls_only() { rules.set(None); let agent = ruled_agent(tools.clone(), rules).await; let session = agent - .create_session(config(preset(PermissionPreset::FullAccess))) + .create_session( + config(preset(PermissionPreset::FullAccess)), + Default::default(), + ) .await .unwrap(); assert_eq!( @@ -1690,7 +1756,10 @@ async fn a_policy_tightened_during_the_rules_read_decides_the_call() { let agent = ruled_agent(tools.clone(), rules.clone()).await; let session = agent - .create_session(config(preset(PermissionPreset::FullAccess))) + .create_session( + config(preset(PermissionPreset::FullAccess)), + Default::default(), + ) .await .unwrap(); rules.hold.store(true, Ordering::SeqCst); @@ -1712,7 +1781,10 @@ async fn a_policy_tightened_during_the_rules_read_decides_the_call() { for manual in [true, false] { rules.hold.store(false, Ordering::SeqCst); let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); submit_exec(&session, "ls").await; @@ -2049,7 +2121,10 @@ async fn advisors_are_asked_in_name_order_and_an_ask_refines_an_allow() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::FullAccess))) + .create_session( + config(preset(PermissionPreset::FullAccess)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); @@ -2119,7 +2194,10 @@ async fn full_access_keeps_advisor_questions_without_repeating_advice() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); @@ -2168,7 +2246,10 @@ async fn a_policy_change_during_advice_does_not_leave_a_stale_question() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); @@ -2217,7 +2298,10 @@ async fn an_allow_advice_admits_a_call_the_preset_would_ask_about() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); @@ -2258,7 +2342,10 @@ async fn a_deny_advice_wins_over_an_allow_and_an_ask() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::FullAccess))) + .create_session( + config(preset(PermissionPreset::FullAccess)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); @@ -2289,7 +2376,10 @@ async fn a_second_registration_of_the_same_name_fails() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::FullAccess))) + .create_session( + config(preset(PermissionPreset::FullAccess)), + Default::default(), + ) .await .unwrap(); let _ = session.service::("main").unwrap(); @@ -2311,7 +2401,10 @@ async fn a_registration_is_withdrawn_when_its_part_unloads() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); @@ -2378,7 +2471,10 @@ async fn advisors_are_not_asked_when_the_policy_denies() { "Tool `exec` is not allowed by the read-only preset (starting processes)", ), ] { - let session = agent.create_session(config(policy.clone())).await.unwrap(); + let session = agent + .create_session(config(policy.clone()), Default::default()) + .await + .unwrap(); let approval = session.service::("main").unwrap(); let error = approval .admit( @@ -2427,7 +2523,10 @@ async fn advisors_are_not_asked_when_a_command_rule_denies() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); @@ -2464,7 +2563,10 @@ async fn advisors_are_not_asked_on_the_recheck_after_an_answer() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); @@ -2509,7 +2611,10 @@ async fn an_advisor_error_counts_as_none() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); @@ -2539,7 +2644,10 @@ async fn cancelling_the_batch_fails_the_admission_and_the_advisor_sees_it() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::FullAccess))) + .create_session( + config(preset(PermissionPreset::FullAccess)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); @@ -2592,7 +2700,10 @@ async fn cancelling_the_batch_drops_an_advice_that_never_answers() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::FullAccess))) + .create_session( + config(preset(PermissionPreset::FullAccess)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); @@ -2635,7 +2746,10 @@ async fn an_advisor_withdrawn_while_its_advice_is_pending_counts_as_none() { ) .await; let session = agent - .create_session(config(preset(PermissionPreset::WorkspaceWrite))) + .create_session( + config(preset(PermissionPreset::WorkspaceWrite)), + Default::default(), + ) .await .unwrap(); let approval = session.service::("main").unwrap(); diff --git a/crates/dim-agent-capabilities/tests/permission_flow/worktrees.rs b/crates/dim-agent-capabilities/tests/permission_flow/worktrees.rs index deda653779..beaebb1ab5 100644 --- a/crates/dim-agent-capabilities/tests/permission_flow/worktrees.rs +++ b/crates/dim-agent-capabilities/tests/permission_flow/worktrees.rs @@ -157,13 +157,16 @@ async fn concurrent_discovery_is_shared_caller_cancellation_is_local_and_cache_i ) .await; let session = agent - .create_session(config_in( - &probes.repo, - PermissionPolicy { - disallowed_tools: vec!["write".into()], - ..writable() - }, - )) + .create_session( + config_in( + &probes.repo, + PermissionPolicy { + disallowed_tools: vec!["write".into()], + ..writable() + }, + ), + Default::default(), + ) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -254,7 +257,7 @@ async fn concurrent_discovery_is_shared_caller_cancellation_is_local_and_cache_i )); assert_eq!(probes.count(), 6); let other = agent - .create_session(config_in(&probes.repo, writable())) + .create_session(config_in(&probes.repo, writable()), Default::default()) .await .unwrap(); assert_eq!( @@ -290,7 +293,7 @@ async fn a_policy_tightened_during_git_discovery_decides_the_waiting_call() { ) .await; let session = agent - .create_session(config_in(&probes.repo, writable())) + .create_session(config_in(&probes.repo, writable()), Default::default()) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -336,7 +339,7 @@ async fn git_unavailability_timeout_reload_and_session_close_do_not_publish_perm ) .await; let session = agent - .create_session(config_in(&probes.repo, writable())) + .create_session(config_in(&probes.repo, writable()), Default::default()) .await .unwrap(); let permission = session.service::("main").unwrap(); @@ -385,7 +388,7 @@ async fn git_unavailability_timeout_reload_and_session_close_do_not_publish_perm )); assert_eq!(associations.0.load(Ordering::SeqCst), 0); let restored = agent - .restore_session(session.id().to_owned()) + .restore_session(session.id().to_owned(), Default::default()) .await .unwrap(); let permission = restored.service::("main").unwrap(); @@ -455,7 +458,7 @@ async fn a_source_that_becomes_a_git_worktree_is_rechecked_after_a_negative_prob ) .await; let session = agent - .create_session(config_in(&probes.repo, writable())) + .create_session(config_in(&probes.repo, writable()), Default::default()) .await .unwrap(); let permission = session.service::("main").unwrap(); diff --git a/crates/dim-agent-capabilities/tests/recall_flow.rs b/crates/dim-agent-capabilities/tests/recall_flow.rs index 5de9e3eed3..4d71c2ef4b 100644 --- a/crates/dim-agent-capabilities/tests/recall_flow.rs +++ b/crates/dim-agent-capabilities/tests/recall_flow.rs @@ -93,10 +93,13 @@ fn said(message: &Message) -> String { async fn open(agent: &Agent) -> Session { agent - .create_session(SessionConfig { - tools: None, - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + tools: None, + ..SessionConfig::default() + }, + Default::default(), + ) .await .unwrap() } @@ -936,7 +939,7 @@ async fn the_read_only_preset_runs_recall_without_an_approval_request() { }, tools: None, ..SessionConfig::default() - }) + }, Default::default()) .await .unwrap(); session diff --git a/crates/dim-agent-capabilities/tests/review_flows.rs b/crates/dim-agent-capabilities/tests/review_flows.rs index b12f2940dc..a8334d612e 100644 --- a/crates/dim-agent-capabilities/tests/review_flows.rs +++ b/crates/dim-agent-capabilities/tests/review_flows.rs @@ -127,14 +127,17 @@ async fn one_tool_panic_does_not_abandon_other_native_cleanup_or_reorder_actual_ )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig { - tools: Some(vec!["panic".into(), "slow".into()]), - permission_policy: PermissionPolicy { - preset: PermissionPreset::FullAccess, - ..Default::default() + let session = soon(agent.create_session( + SessionConfig { + tools: Some(vec!["panic".into(), "slow".into()]), + permission_policy: PermissionPolicy { + preset: PermissionPreset::FullAccess, + ..Default::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - })) + Default::default(), + )) .await .unwrap(); session @@ -238,7 +241,7 @@ async fn a_branch_failing_after_its_root_is_built_rolls_it_back_before_releasing }), ); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig::default())) + let session = soon(agent.create_session(SessionConfig::default(), Default::default())) .await .unwrap(); assert_eq!(live.load(Ordering::SeqCst), 1); @@ -394,14 +397,17 @@ async fn a_read_of_a_batch_does_not_start_before_the_exclusive_call_before_it_re let agent = MinimalHost::start(&builder(Arc::new(BatchModel(&["x0", "c1"])), tools.clone())) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig { - tools: Some(vec!["x0".into(), "c1".into()]), - permission_policy: PermissionPolicy { - preset: PermissionPreset::FullAccess, - ..Default::default() + let session = soon(agent.create_session( + SessionConfig { + tools: Some(vec!["x0".into(), "c1".into()]), + permission_policy: PermissionPolicy { + preset: PermissionPreset::FullAccess, + ..Default::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - })) + Default::default(), + )) .await .unwrap(); session @@ -434,14 +440,17 @@ async fn a_read_starts_after_the_step_before_it_and_before_the_step_after() { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig { - tools: Some(vec!["c0".into(), "x1".into(), "c2".into()]), - permission_policy: PermissionPolicy { - preset: PermissionPreset::FullAccess, - ..Default::default() + let session = soon(agent.create_session( + SessionConfig { + tools: Some(vec!["c0".into(), "x1".into(), "c2".into()]), + permission_policy: PermissionPolicy { + preset: PermissionPreset::FullAccess, + ..Default::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - })) + Default::default(), + )) .await .unwrap(); session @@ -468,15 +477,18 @@ async fn both_calls_of_one_batch_ask_before_either_is_answered() { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig { - tools: Some(vec!["ask0".into(), "ask1".into()]), - // Under workspace-write, an unclassified risk asks. - permission_policy: PermissionPolicy { - preset: PermissionPreset::WorkspaceWrite, - ..Default::default() + let session = soon(agent.create_session( + SessionConfig { + tools: Some(vec!["ask0".into(), "ask1".into()]), + // Under workspace-write, an unclassified risk asks. + permission_policy: PermissionPolicy { + preset: PermissionPreset::WorkspaceWrite, + ..Default::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - })) + Default::default(), + )) .await .unwrap(); session @@ -521,14 +533,17 @@ async fn an_approved_concurrent_call_runs_while_its_sibling_still_waits() { )) .await .unwrap(); - let session = soon(agent.create_session(SessionConfig { - tools: Some(vec!["ask0".into(), "ask1".into()]), - permission_policy: PermissionPolicy { - preset: PermissionPreset::WorkspaceWrite, - ..Default::default() + let session = soon(agent.create_session( + SessionConfig { + tools: Some(vec!["ask0".into(), "ask1".into()]), + permission_policy: PermissionPolicy { + preset: PermissionPreset::WorkspaceWrite, + ..Default::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - })) + Default::default(), + )) .await .unwrap(); session @@ -672,17 +687,20 @@ async fn a_denied_step_settles_first_without_starting_the_steps_after_it() { tools.clone(), ); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = soon(agent.create_session(SessionConfig { - tools: Some(vec!["x0".into(), "x1".into(), "x2".into(), "x3".into()]), - permission_policy: PermissionPolicy { - // `x2` is unclassified, so it asks; the test denies it at - // admission, which settles its own step while `x0` runs. - preset: PermissionPreset::WorkspaceWrite, - allowed_tools: vec!["x0".into(), "x1".into(), "x3".into()], - ..Default::default() + let session = soon(agent.create_session( + SessionConfig { + tools: Some(vec!["x0".into(), "x1".into(), "x2".into(), "x3".into()]), + permission_policy: PermissionPolicy { + // `x2` is unclassified, so it asks; the test denies it at + // admission, which settles its own step while `x0` runs. + preset: PermissionPreset::WorkspaceWrite, + allowed_tools: vec!["x0".into(), "x1".into(), "x3".into()], + ..Default::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - })) + Default::default(), + )) .await .unwrap(); session diff --git a/crates/dim-agent-capabilities/tests/session_extension.rs b/crates/dim-agent-capabilities/tests/session_extension.rs index 292bdc8a54..f4f06da057 100644 --- a/crates/dim-agent-capabilities/tests/session_extension.rs +++ b/crates/dim-agent-capabilities/tests/session_extension.rs @@ -3,7 +3,9 @@ //! that fails fails creation with its own error (#602). use dim_agent_capabilities::defaults; use dim_agent_runtime::testing::MinimalHost; -use dim_agent_runtime::{AgentBuilder, AgentConfig, SessionConfig, SessionLifecycle, SessionPhase}; +use dim_agent_runtime::{ + AgentBuilder, AgentConfig, CreateSessionOptions, SessionConfig, SessionLifecycle, SessionPhase, +}; use rutis::Ctx; use rutis::Plugin; use rutis::host::{CtxHost, DynPlugin, ErrorKind, Key}; @@ -73,7 +75,10 @@ async fn a_requested_extension_mounts_before_publication_and_leaves_with_its_ses }); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session_with_extension(SessionConfig::default(), GROUP, 7_u32) + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().extension(GROUP, 7_u32), + ) .await .unwrap(); assert_eq!( @@ -109,7 +114,10 @@ async fn a_failing_extension_fails_creation_with_its_error() { }); let agent = MinimalHost::start(&builder).await.unwrap(); let error = agent - .create_session_with_extension(SessionConfig::default(), GROUP, 7_u32) + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().extension(GROUP, 7_u32), + ) .await .err() .expect("a failing extension rejects its Session"); diff --git a/crates/dim-agent-capabilities/tests/workspace_files.rs b/crates/dim-agent-capabilities/tests/workspace_files.rs index cb6eb54ef9..81e105bc91 100644 --- a/crates/dim-agent-capabilities/tests/workspace_files.rs +++ b/crates/dim-agent-capabilities/tests/workspace_files.rs @@ -3725,15 +3725,18 @@ mod toolhost { .await .unwrap(); let session = agent - .create_session(SessionConfig { - cwd: workspace.to_string_lossy().into_owned(), - tools: Some(vec!["write".into()]), - permission_policy: PermissionPolicy { - preset: PermissionPreset::FullAccess, + .create_session( + SessionConfig { + cwd: workspace.to_string_lossy().into_owned(), + tools: Some(vec!["write".into()]), + permission_policy: PermissionPolicy { + preset: PermissionPreset::FullAccess, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); session diff --git a/crates/dim-agent-questions/tests/questions_flow.rs b/crates/dim-agent-questions/tests/questions_flow.rs index 79d0905302..0fc11073f1 100644 --- a/crates/dim-agent-questions/tests/questions_flow.rs +++ b/crates/dim-agent-questions/tests/questions_flow.rs @@ -309,11 +309,14 @@ impl Fixture { } async fn session(&self, interactive: bool) -> Session { self.agent - .create_session(SessionConfig { - tools: Some(vec!["ask_user".into(), "wait".into()]), - interactive, - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + tools: Some(vec!["ask_user".into(), "wait".into()]), + interactive, + ..SessionConfig::default() + }, + Default::default(), + ) .await .unwrap() } @@ -981,7 +984,7 @@ async fn interrupt_reload_and_close_settle_a_waiting_call() { .unwrap(); let restored = fixture .agent - .restore_session(session.id().to_owned()) + .restore_session(session.id().to_owned(), Default::default()) .await .unwrap(); let events = turn(&restored, "main").await; diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 12eb3af853..c2d78aca9e 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -39,6 +39,60 @@ enum SessionStart { Prepared(BoxFuture<'static, Result<()>>), Restore, } +/// How [`Agent::create_session`] creates its Session: the id to create under, +/// the host-owned directory to prepare before publication, and the Session +/// extension to load. +#[derive(Default)] +pub struct CreateSessionOptions { + id: Option, + prepare: Option<(String, BoxFuture<'static, Result<()>>)>, + extension: Option, +} +impl CreateSessionOptions { + /// Creates the Session under `id` instead of a generated one. A creation + /// that [`prepare`](Self::prepare)s a Session takes its id from there. + pub fn id(mut self, id: impl Into) -> Self { + self.id = Some(id.into()); + self + } + /// Reserves runtime capacity before committing the host-owned directory: + /// `prepare` commits the rows of `id`, and creation loads them once it + /// completes. A prepared creation is created under `id`. + pub fn prepare( + mut self, + id: impl Into, + prepare: BoxFuture<'static, Result<()>>, + ) -> Self { + self.prepare = Some((id.into(), prepare)); + self + } + /// Loads the Session extension `group` ([`AgentBuilder::session_extension`]) + /// for this Session only, with `value`, before main initialization. + /// Admission and rollback remain owned by this Agent. + pub fn extension( + mut self, + group: impl Into, + value: V, + ) -> Self { + self.extension = Some(extension(group, value)); + self + } +} +/// How [`Agent::restore_session`] restores its Session: the owner +/// connection's projection gate, when it has one. +#[derive(Default)] +pub struct RestoreSessionOptions { + protocol_version: Option, +} +impl RestoreSessionOptions { + /// Applies the owner connection's projection gate at `protocol_version` + /// ([`SessionConfig::exclude_codemode_below`]). Without it, the stored + /// configuration is restored as written. + pub fn protocol_version(mut self, protocol_version: u32) -> Self { + self.protocol_version = Some(protocol_version); + self + } +} impl Agent { pub(crate) fn new(builder: AgentBuilder, assembly: Assembly, placement: Placement) -> Self { Self(Arc::new(AgentInner { @@ -61,68 +115,26 @@ impl Agent { pub fn faces(&self) -> &crate::Faces { self.0.builder.faces() } - pub async fn create_session(&self, config: SessionConfig) -> Result { - self.create( - Uuid::new_v4().to_string(), - config, - SessionStart::Create, - None, - ) - .await - } - /// Loads the Session extension `group` ([`AgentBuilder::session_extension`]) - /// for this Session only, with `value`, before main initialization. - /// Admission and rollback remain owned by this Agent. - pub async fn create_session_with_extension( + pub async fn create_session( &self, config: SessionConfig, - group: impl Into, - value: V, + options: CreateSessionOptions, ) -> Result { - self.create( - Uuid::new_v4().to_string(), - config, - SessionStart::Create, - Some(extension(group, value)), - ) - .await - } - /// Reserves runtime capacity before committing the host-owned directory. - pub async fn create_prepared_session( - &self, - id: String, - config: SessionConfig, - prepare: BoxFuture<'static, Result<()>>, - ) -> Result { - self.create(id, config, SessionStart::Prepared(prepare), None) - .await + let (id, start) = match options.prepare { + Some((id, prepare)) => (id, SessionStart::Prepared(prepare)), + None => ( + options.id.unwrap_or_else(|| Uuid::new_v4().to_string()), + SessionStart::Create, + ), + }; + self.create(id, config, start, options.extension).await } - /// Loads a Session extension after admission and directory preparation. - pub async fn create_prepared_session_with_extension( + /// Restores the original Session identity and its stored configuration, + /// applying the projection gate [`RestoreSessionOptions`] names. + pub async fn restore_session( &self, id: String, - config: SessionConfig, - prepare: BoxFuture<'static, Result<()>>, - group: impl Into, - value: V, - ) -> Result { - self.create( - id, - config, - SessionStart::Prepared(prepare), - Some(extension(group, value)), - ) - .await - } - /// Restores the original Session identity and its stored configuration. - pub async fn restore_session(&self, id: String) -> Result { - self.restore_session_for_version(id, u32::MAX).await - } - /// Restores a Session and applies the owner connection's projection gate. - pub async fn restore_session_for_version( - &self, - id: String, - protocol_version: u32, + options: RestoreSessionOptions, ) -> Result { let mut config = self .0 @@ -131,7 +143,9 @@ impl Agent { .session_config(&id) .await? .ok_or_else(|| AgentError::Storage(format!("unknown session {id}")))?; - config.exclude_codemode_below(protocol_version); + if let Some(protocol_version) = options.protocol_version { + config.exclude_codemode_below(protocol_version); + } let session = self.create(id, config, SessionStart::Restore, None).await?; crate::memory::trim_if_large(); Ok(session) diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index 10a4b80194..b0df3a0f7e 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -537,7 +537,8 @@ impl AgentBuilder { } /// A Rust part of the Session extension `group`: a nested instanced /// group created only for Sessions that ask for it, with a value of type - /// `V` (see [`Agent::create_session_with_extension`]). `make` builds a + /// `V` (see [`Agent::create_session`] and + /// [`CreateSessionOptions::extension`]). `make` builds a /// copy from the names its dependencies resolve to there and the /// extension's value. The extension loads alongside the Session's parts /// after its scope is ready, and every part must be Active before main diff --git a/crates/dim-agent-runtime/tests/lifecycle_review.rs b/crates/dim-agent-runtime/tests/lifecycle_review.rs index 81ff3aa266..e05aed2601 100644 --- a/crates/dim-agent-runtime/tests/lifecycle_review.rs +++ b/crates/dim-agent-runtime/tests/lifecycle_review.rs @@ -77,7 +77,11 @@ async fn agent_close_joins_cancelled_construction_and_retains_async_rollback_fai let host = MinimalHost::start(&builder).await.unwrap(); let agent = host.agent().clone(); let owner = agent.clone(); - let create = tokio::spawn(async move { owner.create_session(SessionConfig::default()).await }); + let create = tokio::spawn(async move { + owner + .create_session(SessionConfig::default(), Default::default()) + .await + }); tokio::time::timeout(Duration::from_secs(2), entered.notified()) .await .unwrap(); @@ -138,8 +142,11 @@ fn agent_close_freezes_build_ownership_before_the_close_task_can_be_polled() { .unwrap(); let agent = host.agent().clone(); let creator = agent.clone(); - let create = construction_runtime - .spawn(async move { creator.create_session(SessionConfig::default()).await }); + let create = construction_runtime.spawn(async move { + creator + .create_session(SessionConfig::default(), Default::default()) + .await + }); construction_runtime.block_on(async { tokio::time::timeout(Duration::from_secs(2), entered.notified()) .await diff --git a/crates/dim-app-server/examples/restore_cost.rs b/crates/dim-app-server/examples/restore_cost.rs index bc5e944b15..199323fa5a 100644 --- a/crates/dim-app-server/examples/restore_cost.rs +++ b/crates/dim-app-server/examples/restore_cost.rs @@ -324,7 +324,9 @@ async fn grow( ) -> std::result::Result, Error> { let mut sessions = vec![]; for &target in sizes { - let session = agent.create_session(SessionConfig::default()).await?; + let session = agent + .create_session(SessionConfig::default(), Default::default()) + .await?; session.idle("main").await?; let start = Instant::now(); let mut turns = 0; @@ -678,7 +680,9 @@ async fn main() -> std::result::Result<(), Error> { allocation::reset_peak(); probe.recording.store(true, Ordering::Relaxed); let start = Instant::now(); - let session = agent.restore_session(id.clone()).await?; + let session = agent + .restore_session(id.clone(), Default::default()) + .await?; let called = Instant::now(); session.idle("main").await?; let end = Instant::now(); @@ -737,7 +741,9 @@ async fn main() -> std::result::Result<(), Error> { tokio::time::sleep(std::time::Duration::from_millis(pause)).await; } let start = Instant::now(); - let session = agent.create_session(SessionConfig::default()).await?; + let session = agent + .create_session(SessionConfig::default(), Default::default()) + .await?; session.idle("main").await?; create.push(ms(start, Instant::now())); if std::env::var_os("RESTORE_COST_SPANS").is_some() { diff --git a/crates/dim-app-server/examples/session_typescript_spike.rs b/crates/dim-app-server/examples/session_typescript_spike.rs index bf1b9f7b69..e61758f032 100644 --- a/crates/dim-app-server/examples/session_typescript_spike.rs +++ b/crates/dim-app-server/examples/session_typescript_spike.rs @@ -376,10 +376,14 @@ async fn run(root: &Ctx) -> Result> { let anchor = anchors.recv().await.expect("Agent anchor"); let agent = builder.build(loader.clone(), &anchor); let started = Instant::now(); - let one = agent.create_session(SessionConfig::default()).await?; + let one = agent + .create_session(SessionConfig::default(), Default::default()) + .await?; let session_ms = started.elapsed().as_secs_f64() * 1_000.0; let first = loaded.recv().await.expect("first Session probe"); - let two = agent.create_session(SessionConfig::default()).await?; + let two = agent + .create_session(SessionConfig::default(), Default::default()) + .await?; let second = loaded.recv().await.expect("second Session probe"); assert_eq!(first.session_id, one.id()); assert_eq!(second.session_id, two.id()); diff --git a/crates/dim-app-server/examples/timeline_acceptance.rs b/crates/dim-app-server/examples/timeline_acceptance.rs index 7aec0fe4bc..c95753612b 100644 --- a/crates/dim-app-server/examples/timeline_acceptance.rs +++ b/crates/dim-app-server/examples/timeline_acceptance.rs @@ -277,11 +277,14 @@ async fn memory(steps: usize) -> std::result::Result<(), Error> { defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await?; let session = agent - .create_session(SessionConfig { - system_prompt: "s".repeat(800_000), - tools: Some(vec![]), - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + system_prompt: "s".repeat(800_000), + tools: Some(vec![]), + ..SessionConfig::default() + }, + Default::default(), + ) .await?; session.idle("main").await?; let tree = captured.lock().unwrap().clone().unwrap(); @@ -835,7 +838,9 @@ async fn reads() -> std::result::Result<(), Error> { }), ); let agent = MinimalHost::start(&builder).await?; - let session = agent.restore_session(name.into()).await?; + let session = agent + .restore_session(name.into(), Default::default()) + .await?; session.idle("main").await?; let active = captured.lock().unwrap().clone().unwrap().get("main")?; let mut dispatch = Vec::new(); diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index e5e3d00489..9bfd32c55d 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -7,10 +7,10 @@ use crate::{ }; use dim_agent_capabilities::{host::ModelSelectionHost, methods::RpcError}; use dim_agent_runtime::{ - AGENT_GROUP, Agent, AgentBuilder, AgentError, CollaborationRole, InUse, Modules, Names, - NoConfig, QueryFilter, QueryOperand, QueryOutput, QueryPage, QueryPick, QueryRow, QuerySelect, - QuerySpec, QueryValue, Session, SessionConfig, TimelineKey, TimelineQuery, TimelineQueryScope, - TimelineReadScope, TimelineReadSegment, + AGENT_GROUP, Agent, AgentBuilder, AgentError, CollaborationRole, CreateSessionOptions, InUse, + Modules, Names, NoConfig, QueryFilter, QueryOperand, QueryOutput, QueryPage, QueryPick, + QueryRow, QuerySelect, QuerySpec, QueryValue, RestoreSessionOptions, Session, SessionConfig, + TimelineKey, TimelineQuery, TimelineQueryScope, TimelineReadScope, TimelineReadSegment, }; pub use dim_agent_types::AgentProfile; use dim_agent_types::{ROOT_BRANCH_ID, TimelinePosition}; @@ -1015,7 +1015,10 @@ impl AgentIndex { tokio::spawn(async move { let session = host .agent - .restore_session_for_version(id.clone(), version) + .restore_session( + id.clone(), + RestoreSessionOptions::default().protocol_version(version), + ) .await?; if slot.closing.load(Ordering::Acquire) { // The close stopped this Session's restoration while @@ -1591,13 +1594,17 @@ impl AgentIndex { .await { Some((id, prepare)) => { - let creation = host - .agent - .create_prepared_session(id.clone(), config, prepare); + let creation = host.agent.create_session( + config, + CreateSessionOptions::default().prepare(id.clone(), prepare), + ); self.admit(&id, &host.agent_id, version, creation).await } None => { - let session = host.agent.create_session(config).await?; + let session = host + .agent + .create_session(config, Default::default()) + .await?; self.insert_version(session.id(), &host.agent_id, version); Ok(session) } @@ -2031,10 +2038,10 @@ impl AgentIndex { let (id, prepare) = self.prepared(config.cwd.clone(), move |fork| { Box::pin(async move { store.fork_session(&source, &fork, at, &record).await }) }); - let creation = usage - .host - .agent - .create_prepared_session(id.clone(), config, prepare); + let creation = usage.host.agent.create_session( + config, + CreateSessionOptions::default().prepare(id.clone(), prepare), + ); let fork = self .admit(&id, &usage.host.agent_id, version, creation) .await?; diff --git a/crates/dim-app-server/src/agents/sessions/tests.rs b/crates/dim-app-server/src/agents/sessions/tests.rs index 31a150b051..79a3f82350 100644 --- a/crates/dim-app-server/src/agents/sessions/tests.rs +++ b/crates/dim-app-server/src/agents/sessions/tests.rs @@ -26,7 +26,7 @@ async fn typed_input_retains_admitted_io_and_accepts_each_submission_once() { let session = server .agent() .unwrap() - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let index = server.root.get::().unwrap(); @@ -182,7 +182,7 @@ async fn exists_answers_loaded_unloaded_closed_and_deleted() { // Loaded, then unloaded with its rows kept: still exists. let unloaded = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let unloaded_id = unloaded.id().to_owned(); @@ -215,7 +215,7 @@ async fn exists_answers_loaded_unloaded_closed_and_deleted() { // Closed keeps its rows, so it exists; deleting it removes them. let closed = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let closed_id = closed.id().to_owned(); diff --git a/crates/dim-app-server/tests/attachments_flow.rs b/crates/dim-app-server/tests/attachments_flow.rs index 9f7a35e51c..f94836600b 100644 --- a/crates/dim-app-server/tests/attachments_flow.rs +++ b/crates/dim-app-server/tests/attachments_flow.rs @@ -424,7 +424,7 @@ impl Contract { async fn session(&self) -> (String, Arc) { let session = self .agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let methods = session diff --git a/crates/dim-app-server/tests/mcp_session_flow.rs b/crates/dim-app-server/tests/mcp_session_flow.rs index 31dc3f6138..9084adc2a4 100644 --- a/crates/dim-app-server/tests/mcp_session_flow.rs +++ b/crates/dim-app-server/tests/mcp_session_flow.rs @@ -679,19 +679,22 @@ impl Env { } async fn session(&self, project: bool, preset: PermissionPreset) -> Session { self.agent - .create_session(SessionConfig { - cwd: self - .home - .join(if project { "project" } else { "other" }) - .to_string_lossy() - .into(), - tools: Some(vec![]), - permission_policy: PermissionPolicy { - preset, + .create_session( + SessionConfig { + cwd: self + .home + .join(if project { "project" } else { "other" }) + .to_string_lossy() + .into(), + tools: Some(vec![]), + permission_policy: PermissionPolicy { + preset, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap() } @@ -2235,11 +2238,14 @@ async fn an_unpublished_session_never_starts_discovery() { .await; let created = env .agent - .create_session(SessionConfig { - cwd: env.home.join("other").to_string_lossy().into(), - tools: Some(vec![]), - ..Default::default() - }) + .create_session( + SessionConfig { + cwd: env.home.join("other").to_string_lossy().into(), + tools: Some(vec![]), + ..Default::default() + }, + Default::default(), + ) .await; let error = created.err().expect("assembly fails").to_string(); assert!( @@ -2622,7 +2628,7 @@ async fn mcp_image_tool_results_reach_the_model_and_the_session_keeps_working() ..Default::default() }, ..Default::default() - }) + }, Default::default()) .await .unwrap(); let store = agent diff --git a/crates/dim-app-server/tests/read_image_flow.rs b/crates/dim-app-server/tests/read_image_flow.rs index 978b2abf78..cbcb145cde 100644 --- a/crates/dim-app-server/tests/read_image_flow.rs +++ b/crates/dim-app-server/tests/read_image_flow.rs @@ -261,16 +261,19 @@ async fn accumulated_user_and_read_images_follow_model_routing() { .await .unwrap(); let session = agent - .create_session(SessionConfig { - cwd: work.to_str().unwrap().into(), - tools: Some(vec!["read".into()]), - model: vision, - permission_policy: PermissionPolicy { - preset: PermissionPreset::FullAccess, + .create_session( + SessionConfig { + cwd: work.to_str().unwrap().into(), + tools: Some(vec!["read".into()]), + model: vision, + permission_policy: PermissionPolicy { + preset: PermissionPreset::FullAccess, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); @@ -527,15 +530,18 @@ async fn an_offloaded_read_result_registers_its_output_path() { .unwrap(); let session = agent - .create_session(SessionConfig { - cwd: work.to_string_lossy().into_owned(), - tools: Some(vec!["read".into()]), - permission_policy: PermissionPolicy { - preset: PermissionPreset::FullAccess, + .create_session( + SessionConfig { + cwd: work.to_string_lossy().into_owned(), + tools: Some(vec!["read".into()]), + permission_policy: PermissionPolicy { + preset: PermissionPreset::FullAccess, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); session diff --git a/crates/dim-app-server/tests/session_files_flow.rs b/crates/dim-app-server/tests/session_files_flow.rs index bc06c65aad..3b305de3f9 100644 --- a/crates/dim-app-server/tests/session_files_flow.rs +++ b/crates/dim-app-server/tests/session_files_flow.rs @@ -403,15 +403,18 @@ async fn a_session_reads_its_own_file_without_an_approval_request() { for preset in [PermissionPreset::WorkspaceWrite, PermissionPreset::ReadOnly] { let session = agent - .create_session(SessionConfig { - cwd: work.to_string_lossy().into_owned(), - tools: Some(vec!["read".into()]), - permission_policy: PermissionPolicy { - preset, + .create_session( + SessionConfig { + cwd: work.to_string_lossy().into_owned(), + tools: Some(vec!["read".into()]), + permission_policy: PermissionPolicy { + preset, + ..Default::default() + }, ..Default::default() }, - ..Default::default() - }) + Default::default(), + ) .await .unwrap(); let stored = store diff --git a/crates/dim-app-server/tests/settings_flow.rs b/crates/dim-app-server/tests/settings_flow.rs index 897d1402e7..f6b9ad8f0f 100644 --- a/crates/dim-app-server/tests/settings_flow.rs +++ b/crates/dim-app-server/tests/settings_flow.rs @@ -199,7 +199,7 @@ async fn server_reload_preserves_project_root_identity_and_settings() { let _session = server .agent() .unwrap() - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let (settings, loader) = services.borrow().clone().unwrap(); diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index c9084f56ba..316a44de2d 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -1323,7 +1323,10 @@ async fn output_block_start_id_roundtrips_through_the_merged_row() { dim_agent_capabilities::defaults::install(&mut builder); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session("session".into()).await.unwrap(); + let session = agent + .restore_session("session".into(), Default::default()) + .await + .unwrap(); let restored = chain_events(&session, "main", ..=2).await.unwrap(); let text: Vec<_> = restored .iter() @@ -1940,7 +1943,10 @@ async fn extension_events_keep_their_own_rows_and_restore_unchanged() { dim_agent_capabilities::defaults::install(&mut builder); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session("session".into()).await.unwrap(); + let session = agent + .restore_session("session".into(), Default::default()) + .await + .unwrap(); let restored = chain_events(&session, "main", ..=3).await.unwrap(); let written: Vec<_> = written.iter().map(|entry| entry.event.clone()).collect(); assert_eq!( @@ -2076,7 +2082,10 @@ async fn conditional_steer_recovers_checked_candidates_once_and_preserves_old_in dim_agent_capabilities::defaults::install(&mut builder); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session("session".into()).await.unwrap(); + let session = agent + .restore_session("session".into(), Default::default()) + .await + .unwrap(); tokio::time::timeout(PUBLISHED, session.idle("main")) .await .unwrap() @@ -2290,7 +2299,10 @@ async fn branch_end_events_restore_unchanged_and_the_line_stays_ended() { dim_agent_capabilities::defaults::install(&mut builder); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session("session".into()).await.unwrap(); + let session = agent + .restore_session("session".into(), Default::default()) + .await + .unwrap(); let restored = chain_events(&session, "main", ..=5).await.unwrap(); assert!( restored @@ -2331,7 +2343,7 @@ async fn stored_two_line_session(database: &Database) -> (String, String) { let agent = MinimalHost::start(&builder).await.unwrap(); let session = settled( "the Session opens", - agent.create_session(SessionConfig::default()), + agent.create_session(SessionConfig::default(), Default::default()), ) .await .unwrap(); @@ -2395,7 +2407,12 @@ async fn a_silent_restore_times_out_naming_the_restore_phase() { let (id, _) = stored_two_line_session(&database).await; let _slow = slow_restore_steps(&id, Duration::from_millis(1500)); let (agent, store, db) = restoring_host(&database, Some(Duration::from_secs(1))).await; - let error = match settled("the silent restore times out", agent.restore_session(id)).await { + let error = match settled( + "the silent restore times out", + agent.restore_session(id, Default::default()), + ) + .await + { Ok(_) => panic!("a restore silent past the bound must fail the opening"), Err(error) => error, }; @@ -2422,9 +2439,12 @@ async fn a_slow_restore_reports_progress_and_keeps_the_opening_alive() { let _slow = slow_restore_steps(&id, Duration::from_millis(250)); let (agent, store, db) = restoring_host(&database, Some(bound)).await; let started = Instant::now(); - let session = settled("the slow restore completes", agent.restore_session(id)) - .await - .expect("reported progress renews the opening's inactivity bound"); + let session = settled( + "the slow restore completes", + agent.restore_session(id, Default::default()), + ) + .await + .expect("reported progress renews the opening's inactivity bound"); let elapsed = started.elapsed(); assert!( elapsed > bound, @@ -2452,9 +2472,12 @@ async fn a_restore_resolves_its_reporting_identity_once() { let (id, _) = stored_two_line_session(&database).await; let resolutions = count_identity_resolutions(&id); let (agent, store, db) = restoring_host(&database, None).await; - settled("the restore completes", agent.restore_session(id)) - .await - .expect("a restore within its opening bound completes"); + settled( + "the restore completes", + agent.restore_session(id, Default::default()), + ) + .await + .expect("a restore within its opening bound completes"); assert_eq!( resolutions.count(), 1, @@ -2477,16 +2500,19 @@ async fn each_tree_generation_resolves_its_own_reporting_identity() { let (agent, store, db) = restoring_host(&database, None).await; let session = settled( "the first restore completes", - agent.restore_session(id.clone()), + agent.restore_session(id.clone(), Default::default()), ) .await .expect("a restore within its opening bound completes"); settled("the first Session closes", session.close()) .await .unwrap(); - let second = settled("the second restore completes", agent.restore_session(id)) - .await - .expect("a restore within its opening bound completes"); + let second = settled( + "the second restore completes", + agent.restore_session(id, Default::default()), + ) + .await + .expect("a restore within its opening bound completes"); let ids = resolutions.ids(); assert_eq!( ids.len(), @@ -2579,7 +2605,7 @@ async fn a_row_reload_resolves_the_new_tree_reporting_identity() { let agent = MinimalHost::start(&builder).await.unwrap(); let session = settled( "the first restore completes", - agent.restore_session(id.clone()), + agent.restore_session(id.clone(), Default::default()), ) .await .expect("a restore within its opening bound completes"); @@ -3666,11 +3692,11 @@ async fn failed_output_commit_closes_only_its_session_and_recovery_settles_the_o builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let mut agent = MinimalHost::start(&builder).await.unwrap(); let bad = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let mut good = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let bad_id = bad.id().to_owned(); @@ -3729,7 +3755,7 @@ async fn failed_output_commit_closes_only_its_session_and_recovery_settles_the_o let head = store.head(&key(&bad_id, "main")).await.unwrap(); let failed_restore = settled( "a failed settlement rejects restore", - agent.restore_session(bad_id.clone()), + agent.restore_session(bad_id.clone(), Default::default()), ) .await .err() @@ -3758,11 +3784,17 @@ async fn failed_output_commit_closes_only_its_session_and_recovery_settles_the_o dim_agent_capabilities::defaults::install(&mut builder); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); agent = MinimalHost::start(&builder).await.unwrap(); - good = agent.restore_session(good_id).await.unwrap(); + good = agent + .restore_session(good_id, Default::default()) + .await + .unwrap(); } - let session = settled("the orphan restores", agent.restore_session(bad_id)) - .await - .unwrap(); + let session = settled( + "the orphan restores", + agent.restore_session(bad_id, Default::default()), + ) + .await + .unwrap(); assert!( bad.submit("old generation".into(), InputMode::Queue, "main") .await @@ -5236,7 +5268,10 @@ async fn a_v21_store_upgrades_in_place_once_and_restores_typeless_tool_schemas() dim_agent_capabilities::defaults::install(&mut builder); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session("schema".into()).await.unwrap(); + let session = agent + .restore_session("schema".into(), Default::default()) + .await + .unwrap(); let restored = chain_events(&session, "main", ..=2).await.unwrap(); assert_eq!(restored[0], configured.event); assert_eq!(restored[1], called.event); @@ -5344,7 +5379,10 @@ async fn a_type_array_tool_schema_round_trips_on_the_current_store_without_an_up dim_agent_capabilities::defaults::install(&mut builder); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.restore_session("schema".into()).await.unwrap(); + let session = agent + .restore_session("schema".into(), Default::default()) + .await + .unwrap(); let restored = chain_events(&session, "main", ..=2).await.unwrap(); assert_eq!(restored[0], configured.event); assert_eq!(restored[1], called.event); @@ -6442,7 +6480,10 @@ async fn recovery_ignores_disposable_snapshots_but_preserves_and_validates_facts dim_agent_capabilities::defaults::install(&mut builder); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - agent.restore_session("session".into()).await.unwrap(); + agent + .restore_session("session".into(), Default::default()) + .await + .unwrap(); agent.close().await.unwrap(); dim_agent_runtime::core::close_timeline(&timeline) .await @@ -6858,8 +6899,11 @@ async fn a_cold_read_failure_preserves_the_record_and_other_session_progress() { dim_agent_capabilities::defaults::install(&mut builder); builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); - let bad = agent.create_session(SessionConfig::default()).await.unwrap(); - let good = agent.create_session(SessionConfig::default()).await.unwrap(); + let bad = agent.create_session(SessionConfig::default(), Default::default()).await.unwrap(); + let good = agent + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); bad.submit("stored request".into(), InputMode::Queue, "main").await.unwrap(); bad.idle("main").await.unwrap(); let connection = Connection::open(&database.0).unwrap(); diff --git a/crates/dim-app-server/tests/storage_flow/prompt_migration.rs b/crates/dim-app-server/tests/storage_flow/prompt_migration.rs index 3527e17fb9..379554493a 100644 --- a/crates/dim-app-server/tests/storage_flow/prompt_migration.rs +++ b/crates/dim-app-server/tests/storage_flow/prompt_migration.rs @@ -24,7 +24,7 @@ async fn legacy_session(database: &Path) -> String { let store = SqliteTimelineStore::new(db.clone()); let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -86,7 +86,11 @@ async fn resume( let db = SqliteStorage::open(database.to_owned()).unwrap(); let store = SqliteTimelineStore::new(db.clone()); let agent = MinimalHost::start(&builder(&store)).await.unwrap(); - let result = settled("the branch settles", agent.restore_session(id.to_owned())).await; + let result = settled( + "the branch settles", + agent.restore_session(id.to_owned(), Default::default()), + ) + .await; let snapshot = match result { Ok(session) => session .get::("main") @@ -113,7 +117,7 @@ async fn a_legacy_branch_answers_its_migration_instruction_on_the_wire() { let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let failure = settled( "the guard refuses a branch with no saved references", - agent.restore_session(id), + agent.restore_session(id, Default::default()), ) .await .err() diff --git a/crates/dim-app-server/tests/storage_flow/prompt_recovery.rs b/crates/dim-app-server/tests/storage_flow/prompt_recovery.rs index 7ff7dfa6d2..00879a5b86 100644 --- a/crates/dim-app-server/tests/storage_flow/prompt_recovery.rs +++ b/crates/dim-app-server/tests/storage_flow/prompt_recovery.rs @@ -20,7 +20,7 @@ async fn prompt_resume_reads_effective_elements_and_recovers_a_committed_adoptio let store = SqliteTimelineStore::new(db.clone()); let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -113,7 +113,7 @@ async fn prompt_resume_reads_effective_elements_and_recovers_a_committed_adoptio store.record_query_statistics(); let session = settled( "effective prompts restore without reading inactive elements", - agent.restore_session(id.clone()), + agent.restore_session(id.clone(), Default::default()), ) .await .unwrap(); @@ -175,7 +175,7 @@ async fn prompt_resume_reads_effective_elements_and_recovers_a_committed_adoptio let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let session = settled( "the saved prefix consumes the unfinished adoption", - agent.restore_session(id.clone()), + agent.restore_session(id.clone(), Default::default()), ) .await .unwrap(); @@ -201,7 +201,7 @@ async fn prompt_resume_reads_effective_elements_and_recovers_a_committed_adoptio let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let failure = settled( "unknown prompt schema fails without replay", - agent.restore_session(id), + agent.restore_session(id, Default::default()), ) .await .err() diff --git a/crates/dim-app-server/tests/storage_flow/queue_recovery.rs b/crates/dim-app-server/tests/storage_flow/queue_recovery.rs index 15e04056b4..010d5268a3 100644 --- a/crates/dim-app-server/tests/storage_flow/queue_recovery.rs +++ b/crates/dim-app-server/tests/storage_flow/queue_recovery.rs @@ -17,7 +17,7 @@ async fn queue_resume_finishes_multiple_source_pages_without_republishing_an_old let store = SqliteTimelineStore::new(db.clone()); let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -46,7 +46,7 @@ async fn queue_resume_finishes_multiple_source_pages_without_republishing_an_old let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let session = settled( "all new source pages restore", - agent.restore_session(id.clone()), + agent.restore_session(id.clone(), Default::default()), ) .await .unwrap(); @@ -81,7 +81,7 @@ async fn current_inputs_restore_and_are_removed_when_a_turn_consumes_them() { let store = SqliteTimelineStore::new(db.clone()); let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -119,7 +119,7 @@ async fn current_inputs_restore_and_are_removed_when_a_turn_consumes_them() { let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let session = settled( "the current inputs restore", - agent.restore_session(id.clone()), + agent.restore_session(id.clone(), Default::default()), ) .await .unwrap(); @@ -169,7 +169,7 @@ async fn queue_resume_reuses_an_application_written_by_an_older_owner_after_a_sa let store = SqliteTimelineStore::new(db.clone()); let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -209,7 +209,7 @@ async fn queue_resume_reuses_an_application_written_by_an_older_owner_after_a_sa let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let session = settled( "saved state and older output restore", - agent.restore_session(id), + agent.restore_session(id, Default::default()), ) .await .unwrap(); @@ -232,7 +232,7 @@ async fn obsolete_queue_nodes_do_not_override_current_business_facts() { let store = SqliteTimelineStore::new(db.clone()); let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let input = session @@ -275,7 +275,7 @@ async fn obsolete_queue_nodes_do_not_override_current_business_facts() { let agent = MinimalHost::start(&builder(&store)).await.unwrap(); let restored = settled( "business facts restore independently of obsolete nodes", - agent.restore_session(id.clone()), + agent.restore_session(id.clone(), Default::default()), ) .await .unwrap(); @@ -309,7 +309,7 @@ async fn queue_decisions_commit_and_resume_once_after_a_failed_commit() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -338,7 +338,7 @@ async fn queue_decisions_commit_and_resume_once_after_a_failed_commit() { drop(connection); let restored = settled( "the queue restores its unprocessed source", - agent.restore_session(id.clone()), + agent.restore_session(id.clone(), Default::default()), ) .await .unwrap(); @@ -380,7 +380,7 @@ async fn queue_decisions_commit_and_resume_once_after_a_failed_commit() { let agent = MinimalHost::start(&builder).await.unwrap(); let restored = settled( "the queue restores its saved state", - agent.restore_session(id.clone()), + agent.restore_session(id.clone(), Default::default()), ) .await .unwrap(); @@ -420,7 +420,7 @@ async fn obsolete_queue_result_versions_do_not_control_recovery() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -451,7 +451,7 @@ async fn obsolete_queue_result_versions_do_not_control_recovery() { let agent = MinimalHost::start(&builder).await.unwrap(); let restored = settled( "obsolete result schemas are not state inputs", - agent.restore_session(id.clone()), + agent.restore_session(id.clone(), Default::default()), ) .await .unwrap(); diff --git a/crates/dim-app-server/tests/storage_flow/recall.rs b/crates/dim-app-server/tests/storage_flow/recall.rs index cb454972c3..ac346a347a 100644 --- a/crates/dim-app-server/tests/storage_flow/recall.rs +++ b/crates/dim-app-server/tests/storage_flow/recall.rs @@ -54,10 +54,13 @@ async fn sqlite_recall_verifies_indexed_candidates_and_fallbacks_against_the_sam builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig { - tools: None, - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + tools: None, + ..SessionConfig::default() + }, + Default::default(), + ) .await .unwrap(); for message in [ diff --git a/crates/dim-app-server/tests/storage_session_flow.rs b/crates/dim-app-server/tests/storage_session_flow.rs index e18d0a956d..c757c07787 100644 --- a/crates/dim-app-server/tests/storage_session_flow.rs +++ b/crates/dim-app-server/tests/storage_session_flow.rs @@ -151,7 +151,10 @@ async fn storage_failure_during_generic_cleanup_supersedes_the_session_fault() { move |names| Ok(Box::new(GenericCleanupFault::new(names, captured_tree.clone())?)), )); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.create_session(SessionConfig::default()).await.unwrap(); + let session = agent + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); let idle = session.branch("main".into(), 0, BranchOptions { prompt: "idle sibling".into(), source: BranchSource::Host { operation_id: "idle sibling".into() }, }).await.unwrap(); @@ -198,7 +201,10 @@ async fn sqlite_session_failure_rejects_writes_on_an_idle_sibling_timeline() { move |names| Ok(Box::new(CaptureTimeline::new(names, captured.clone())?)), )); let agent = MinimalHost::start(&builder).await.unwrap(); - let session = agent.create_session(SessionConfig::default()).await.unwrap(); + let session = agent + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); let mut siblings = Vec::new(); for name in ["failed sibling", "idle sibling"] { let branch = session.branch("main".into(), 0, BranchOptions { @@ -331,7 +337,7 @@ async fn session_close_and_idle_unload_persist_finalizers_and_release_branch_par )); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session diff --git a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs index 87e03c56cb..ef1bbc0ad4 100644 --- a/crates/dim-app-server/tests/transport_flow/branch_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/branch_typescript.rs @@ -577,7 +577,7 @@ async fn node_branch_opening_completion_can_refuse_session_creation() { ) .await; let error = agent - .create_session(Default::default()) + .create_session(Default::default(), Default::default()) .await .err() .expect("opening must fail"); @@ -612,7 +612,10 @@ async fn node_session_fault_is_observed_and_closes_the_native_session() { }, ) .await; - let error = match agent.create_session(Default::default()).await { + let error = match agent + .create_session(Default::default(), Default::default()) + .await + { Ok(session) => session.close().await.unwrap_err(), Err(error) => error, }; diff --git a/crates/dim-app-server/tests/transport_flow/session_typescript.rs b/crates/dim-app-server/tests/transport_flow/session_typescript.rs index f4100960c8..dc8ac8bc39 100644 --- a/crates/dim-app-server/tests/transport_flow/session_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/session_typescript.rs @@ -942,13 +942,16 @@ async fn node_session_typescript_creation_config_and_misplaced_rows() { let session = server .agent() .unwrap() - .create_session(dim_agent_runtime::SessionConfig { - cwd: std::env::temp_dir().to_str().unwrap().into(), - tools: Some(vec!["echo".into()]), - interactive, - collaboration_role: role, - ..Default::default() - }) + .create_session( + dim_agent_runtime::SessionConfig { + cwd: std::env::temp_dir().to_str().unwrap().into(), + tools: Some(vec!["echo".into()]), + interactive, + collaboration_role: role, + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); let methods = tokio::time::timeout(Duration::from_secs(5), async { diff --git a/crates/dim-app-server/tests/transport_flow/tree.rs b/crates/dim-app-server/tests/transport_flow/tree.rs index b8716ca6e6..b99a5f852e 100644 --- a/crates/dim-app-server/tests/transport_flow/tree.rs +++ b/crates/dim-app-server/tests/transport_flow/tree.rs @@ -158,7 +158,10 @@ async fn v2_tree_history_resume_and_protocol_isolation_work_on_both_transports() let mut legacy = Client::new(&server, !ws).await; let unbound = agent - .create_session(dim_agent_runtime::SessionConfig::default()) + .create_session( + dim_agent_runtime::SessionConfig::default(), + Default::default(), + ) .await .unwrap(); for client in [&mut tree, &mut legacy] { diff --git a/crates/dim-app-server/tests/transport_flow/worktrees.rs b/crates/dim-app-server/tests/transport_flow/worktrees.rs index 25265139a9..7703d2ce64 100644 --- a/crates/dim-app-server/tests/transport_flow/worktrees.rs +++ b/crates/dim-app-server/tests/transport_flow/worktrees.rs @@ -1751,7 +1751,7 @@ async fn committed_shell_completion_recovers_after_notice_failure_and_host_loss( let session = server .agent() .unwrap() - .restore_session(id.clone()) + .restore_session(id.clone(), Default::default()) .await .unwrap(); tokio::time::timeout(Duration::from_secs(30), session.idle("main")) diff --git a/crates/dim-codemode/tests/flow.rs b/crates/dim-codemode/tests/flow.rs index 3091bc1d32..a5b8f71814 100644 --- a/crates/dim-codemode/tests/flow.rs +++ b/crates/dim-codemode/tests/flow.rs @@ -187,12 +187,15 @@ impl Fixture { permission_policy: PermissionPolicy, ) -> Session { self.agent - .create_session(SessionConfig { - tools: Some(tools), - interactive, - permission_policy, - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + tools: Some(tools), + interactive, + permission_policy, + ..SessionConfig::default() + }, + Default::default(), + ) .await .unwrap() } diff --git a/crates/dim-goal/tests/support/parts.rs b/crates/dim-goal/tests/support/parts.rs index a89c846fad..f9d6f24292 100644 --- a/crates/dim-goal/tests/support/parts.rs +++ b/crates/dim-goal/tests/support/parts.rs @@ -1022,11 +1022,14 @@ impl Env { .expect("the part host assembles"); let session = host .agent() - .create_session(dim_agent_runtime::SessionConfig { - cwd: home.to_string_lossy().into_owned(), - tools: Some(vec!["goal_update".into(), "wait".into()]), - ..Default::default() - }) + .create_session( + dim_agent_runtime::SessionConfig { + cwd: home.to_string_lossy().into_owned(), + tools: Some(vec!["goal_update".into(), "wait".into()]), + ..Default::default() + }, + Default::default(), + ) .await .expect("the Session builds"); let env = Self { @@ -1163,7 +1166,7 @@ impl Env { session.close().await.expect("the Session closes"); let session = host .agent() - .restore_session(id) + .restore_session(id, Default::default()) .await .expect("the Session restores"); let env = Self { @@ -1186,7 +1189,7 @@ impl Env { pub async fn restore_failure(&self, id: &str) -> dim_agent_runtime::AgentError { self.host .agent() - .restore_session(id.to_owned()) + .restore_session(id.to_owned(), Default::default()) .await .err() .expect("invalid durable recovery state must fail the Session restore") @@ -1226,7 +1229,7 @@ impl Env { session.close().await.expect("the Session closes"); let session = host .agent() - .restore_session(id.to_owned()) + .restore_session(id.to_owned(), Default::default()) .await .expect("the seeded Session restores"); let env = Self { diff --git a/crates/dim-image-understanding/tests/image_flow.rs b/crates/dim-image-understanding/tests/image_flow.rs index 0c5bd2f9a4..c9ab878a79 100644 --- a/crates/dim-image-understanding/tests/image_flow.rs +++ b/crates/dim-image-understanding/tests/image_flow.rs @@ -506,11 +506,14 @@ impl Fixture { self.server .agent() .unwrap() - .create_session(SessionConfig { - cwd: self.home.to_string_lossy().into_owned(), - tools: Some(vec!["read".into(), "image_understand".into()]), - ..Default::default() - }) + .create_session( + SessionConfig { + cwd: self.home.to_string_lossy().into_owned(), + tools: Some(vec!["read".into(), "image_understand".into()]), + ..Default::default() + }, + Default::default(), + ) .await .unwrap() } @@ -824,7 +827,7 @@ async fn image_questions_follow_current_defaults_and_reuse_only_completed_own_an .server .agent() .unwrap() - .restore_session(session.id().into()) + .restore_session(session.id().into(), Default::default()) .await .unwrap(); assert_eq!( @@ -1546,7 +1549,7 @@ async fn a_compacted_image_resolves_from_history_after_the_index_is_rebuilt() { .server .agent() .unwrap() - .restore_session(session.id().into()) + .restore_session(session.id().into(), Default::default()) .await .unwrap(); assert_eq!( diff --git a/crates/dim-migration/tests/migration_flow.rs b/crates/dim-migration/tests/migration_flow.rs index ae83572c97..a1cd73c1f6 100644 --- a/crates/dim-migration/tests/migration_flow.rs +++ b/crates/dim-migration/tests/migration_flow.rs @@ -899,7 +899,12 @@ async fn migration_keeps_large_images_as_files_without_rejecting_session_history ) .await .unwrap(); - let session = server.agent().unwrap().restore_session(id).await.unwrap(); + let session = server + .agent() + .unwrap() + .restore_session(id, Default::default()) + .await + .unwrap(); let history = chain_events(&session, "main", ..).await.unwrap(); let replacement = history .iter() @@ -1113,7 +1118,7 @@ async fn offline_import_reopens_with_unchanged_native_consumers_and_preserves_co "listing must not restore imported Sessions" ); let session = agent - .restore_session(id.clone()) + .restore_session(id.clone(), Default::default()) .await .expect("Native restore must accept imported data"); assert_eq!( diff --git a/crates/dimcode/tests/cli_flow/hooks.rs b/crates/dimcode/tests/cli_flow/hooks.rs index 1e2dd37a27..494697fd7a 100644 --- a/crates/dimcode/tests/cli_flow/hooks.rs +++ b/crates/dimcode/tests/cli_flow/hooks.rs @@ -619,10 +619,13 @@ fn a_stop_hook_exports_its_session_from_dimcode_home() { let session = server .agent() .unwrap() - .create_session(SessionConfig { - cwd: project.to_string_lossy().into_owned(), - ..Default::default() - }) + .create_session( + SessionConfig { + cwd: project.to_string_lossy().into_owned(), + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); session diff --git a/crates/dimcode/tests/cli_flow/prompt_migration.rs b/crates/dimcode/tests/cli_flow/prompt_migration.rs index 1eaaaa5270..6c0f144feb 100644 --- a/crates/dimcode/tests/cli_flow/prompt_migration.rs +++ b/crates/dimcode/tests/cli_flow/prompt_migration.rs @@ -40,7 +40,7 @@ async fn legacy_session(database: &Path) -> String { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -102,7 +102,7 @@ async fn resume(database: &Path, id: &str) -> dim_agent_runtime::Result) ``` -Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`create_prepared_session`)。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 +Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`Agent::create_session` 带 `CreateSessionOptions::prepare`)。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 ## 3. 删除 diff --git a/tests/integration/tests/context_input.rs b/tests/integration/tests/context_input.rs index 2179fe3dbe..feb136ad6e 100644 --- a/tests/integration/tests/context_input.rs +++ b/tests/integration/tests/context_input.rs @@ -23,7 +23,7 @@ fn context_input(content: &str) -> InputMessageData { async fn context_only_input_waits_for_the_next_user_turn() { let agent = MinimalHost::start(&builder()).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -70,7 +70,7 @@ async fn context_only_input_waits_for_the_next_user_turn() { async fn context_only_input_after_a_stop_starts_no_turn() { let agent = MinimalHost::start(&builder()).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session.stop("main", "pause".into()).await.unwrap(); diff --git a/tests/integration/tests/extensions.rs b/tests/integration/tests/extensions.rs index c2543e290f..21e8c50d22 100644 --- a/tests/integration/tests/extensions.rs +++ b/tests/integration/tests/extensions.rs @@ -42,11 +42,11 @@ async fn external_cross_crate_capabilities_are_isolated_and_installed_in_every_b .require_feature(provider()); let agent = MinimalHost::start(&b).await.unwrap(); let one = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let two = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); one.submit("hello".into(), InputMode::Queue, "main") @@ -148,11 +148,11 @@ async fn before_runs_only_on_its_own_branch() { ); let agent = MinimalHost::start(&b).await.unwrap(); let one = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let two = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let branch = one @@ -200,7 +200,7 @@ async fn missing_dependency_and_undeclared_read_fail_before_session_publication( .require_feature(consumer(true)); let agent = MinimalHost::start(&missing).await.unwrap(); let error = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .err() .unwrap(); @@ -215,7 +215,7 @@ async fn missing_dependency_and_undeclared_read_fail_before_session_publication( .require_feature(consumer(false)); let agent = MinimalHost::start(&undeclared).await.unwrap(); let error = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .err() .unwrap(); @@ -260,7 +260,7 @@ async fn unawaited_children_are_reported() { )); let agent = MinimalHost::start(&b).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let findings = agent.check_assembly().unwrap(); @@ -410,7 +410,7 @@ async fn a_required_row_waits_for_the_child_it_mounts() { ); let agent = MinimalHost::start(&b).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let findings = agent.check_assembly().unwrap(); @@ -460,7 +460,7 @@ async fn a_child_that_never_loads_fails_creation_and_is_named() { ); let agent = MinimalHost::start(&b).await.unwrap(); let error = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .err() .expect("creation fails"); @@ -647,7 +647,7 @@ async fn a_reapplied_row_waits_for_a_child_whose_dependency_returns_late() { let agent = MinimalHost::start(&b).await.unwrap(); let root = agent.root().clone(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let owner = fiber(&agent, &root, "test.mounting-owner"); @@ -692,7 +692,7 @@ async fn a_row_cancelled_while_its_child_waits_ends_the_wait() { let agent = MinimalHost::start(&b).await.unwrap(); let root = agent.root().clone(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let owner = fiber(&agent, &root, "test.mounting-owner"); @@ -763,7 +763,7 @@ async fn findings_name_their_branch() { ); let agent = MinimalHost::start(&b).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let fork = session @@ -820,7 +820,7 @@ async fn optional_reads_are_allowed_and_undeclared_required_reads_are_reported() ); let agent = MinimalHost::start(&b).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let findings = agent.check_assembly().unwrap(); @@ -874,7 +874,7 @@ async fn reads_of_a_withdrawn_generation_are_reported() { )); let agent = MinimalHost::start(&b).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); armed.store(true, std::sync::atomic::Ordering::SeqCst); @@ -1046,7 +1046,7 @@ async fn abandoned_first_creation_is_owned_until_agent_close_finishes() { let agent = MinimalHost::start(&builder()).await.unwrap(); let root = agent.root().clone(); let host = root.diagnostics().plugins.len(); - let mut creating = Box::pin(agent.create_session(SessionConfig::default())); + let mut creating = Box::pin(agent.create_session(SessionConfig::default(), Default::default())); assert!(futures_util::poll!(creating.as_mut()).is_pending()); drop(creating); let (first, second) = tokio::join!(agent.agent().close(), agent.agent().close()); @@ -1064,7 +1064,7 @@ async fn abandoned_first_creation_is_owned_until_agent_close_finishes() { async fn close_continues_after_waiter_is_dropped_and_concurrent_closers_join() { let agent = MinimalHost::start(&builder()).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let first = session.close(); @@ -1085,14 +1085,14 @@ fn owning_agent_can_close_or_drop_outside_the_runtime_enter_guard() { .unwrap(); let agent = runtime.block_on(MinimalHost::start(&builder())).unwrap(); let session = runtime - .block_on(agent.create_session(SessionConfig::default())) + .block_on(agent.create_session(SessionConfig::default(), Default::default())) .unwrap(); let close = agent.close(); runtime.block_on(close).unwrap(); runtime.block_on(session.close()).unwrap(); let agent = runtime.block_on(MinimalHost::start(&builder())).unwrap(); let session = runtime - .block_on(agent.create_session(SessionConfig::default())) + .block_on(agent.create_session(SessionConfig::default(), Default::default())) .unwrap(); drop(agent); runtime.block_on(session.close()).unwrap(); @@ -1150,7 +1150,7 @@ async fn initialization_preserves_each_distinct_cleanup_failure_once() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let error = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .err() .expect("initialization failed"); @@ -1209,12 +1209,12 @@ async fn scoped_services_stay_inside_their_session_and_unkeyed_ones_are_reported )); let agent = MinimalHost::start(&scoped).await.unwrap(); let first = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); assert!(seen.load(std::sync::atomic::Ordering::SeqCst)); let second = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); assert!(!seen.load(std::sync::atomic::Ordering::SeqCst)); @@ -1234,7 +1234,7 @@ async fn scoped_services_stay_inside_their_session_and_unkeyed_ones_are_reported ); let agent = MinimalHost::start(&unkeyed).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let findings = agent.check_assembly().unwrap(); @@ -1258,7 +1258,7 @@ async fn closed_session_and_branch_subtrees_leave_no_plugins_or_bindings() { let mut baseline = None; for round in 0..20 { let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let branch = session @@ -1371,7 +1371,10 @@ async fn plugin_names_cannot_replace_other_capabilities_or_loader_groups() { }); let agent = MinimalHost::start(&b).await.unwrap(); agent - .create_session_with_extension(SessionConfig::default(), "trace", installed.clone()) + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().extension("trace", installed.clone()), + ) .await .unwrap(); assert_eq!(installed.load(Ordering::SeqCst), (1 << 10) - 1); @@ -1405,12 +1408,12 @@ async fn factory_and_extension_failures_reject_the_session_instead_of_omitting_c let agent = MinimalHost::start(&b).await.unwrap(); for _ in 0..panic_at { agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); } let error = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .err() .expect("a required factory failure rejects creation"); @@ -1429,11 +1432,17 @@ async fn factory_and_extension_failures_reject_the_session_instead_of_omitting_c }); let agent = MinimalHost::start(&b).await.unwrap(); let missing_value = agent - .create_session_with_extension(SessionConfig::default(), "extension", "wrong value type") + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().extension("extension", "wrong value type"), + ) .await; assert!(missing_value.is_err()); let wrong_name = agent - .create_session_with_extension(SessionConfig::default(), "extension", 1_u32) + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().extension("extension", 1_u32), + ) .await; assert!(wrong_name.is_err()); assert!(agent.sessions().is_empty()); @@ -1442,7 +1451,10 @@ async fn factory_and_extension_failures_reject_the_session_instead_of_omitting_c let agent = MinimalHost::start(&builder()).await.unwrap(); assert!( agent - .create_session_with_extension(SessionConfig::default(), "missing", ()) + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().extension("missing", ()), + ) .await .is_err() ); @@ -1461,7 +1473,10 @@ async fn factory_and_extension_failures_reject_the_session_instead_of_omitting_c let agent = MinimalHost::start(&b).await.unwrap(); assert!( agent - .create_session_with_extension(SessionConfig::default(), "pending", ()) + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().extension("pending", ()), + ) .await .is_err() ); @@ -1661,8 +1676,12 @@ async fn nested_instances_preserve_optional_rows_and_cleanup_across_create_resto let (agent, saved) = (agent.clone(), saved.clone()); tokio::spawn(async move { match saved { - None => agent.create_session(SessionConfig::default()).await, - Some(id) => agent.restore_session(id).await, + None => { + agent + .create_session(SessionConfig::default(), Default::default()) + .await + } + Some(id) => agent.restore_session(id, Default::default()).await, } }) }; diff --git a/tests/integration/tests/interrupt.rs b/tests/integration/tests/interrupt.rs index d8e9835ce0..729decd8ce 100644 --- a/tests/integration/tests/interrupt.rs +++ b/tests/integration/tests/interrupt.rs @@ -21,7 +21,7 @@ async fn interrupt_commits_before_later_input_without_waiting_for_dispatch() { dim_agent_capabilities::defaults::install(&mut builder); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let interrupt = session.interrupt("main", "reload".into()).unwrap(); @@ -176,7 +176,7 @@ async fn external_capability_receives_interrupt_and_owns_cleanup_outside_the_sto ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -283,7 +283,7 @@ async fn a_large_interrupt_and_later_input_need_no_byte_budget() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session.stop("main", "pause".into()).await.unwrap(); diff --git a/tests/integration/tests/local_execution.rs b/tests/integration/tests/local_execution.rs index 9cab6b9109..15c92ceb1e 100644 --- a/tests/integration/tests/local_execution.rs +++ b/tests/integration/tests/local_execution.rs @@ -443,7 +443,10 @@ impl Harness { } } async fn session(&self) -> Session { - self.agent.create_session(self.config()).await.unwrap() + self.agent + .create_session(self.config(), Default::default()) + .await + .unwrap() } /// Runs one user turn whose model issues `calls`, then replies `done`. async fn run(&self, session: &Session, calls: &[(&str, Value)]) { @@ -1882,7 +1885,11 @@ async fn idle_unload_waits_for_tasks_and_a_restart_wakes_for_every_unreported_en .pop() .unwrap(); - let restored = harness.agent.restore_session(id).await.unwrap(); + let restored = harness + .agent + .restore_session(id, Default::default()) + .await + .unwrap(); let events = until(&restored, "recovery", |events| { ended(events).len() == 3 && notifications(events).len() == 3 }) @@ -2213,7 +2220,11 @@ async fn an_end_after_the_branch_close_interrupt_does_not_wake() { ], ) .await; - let restored = harness.agent.restore_session(id).await.unwrap(); + let restored = harness + .agent + .restore_session(id, Default::default()) + .await + .unwrap(); restored.idle("main").await.unwrap(); assert!(notifications(&local_events(&restored).await).is_empty()); restored.close().await.unwrap(); @@ -2236,7 +2247,11 @@ async fn a_new_generation_can_start_its_first_background_task_after_an_old_close })], ) .await; - let restored = harness.agent.restore_session(id).await.unwrap(); + let restored = harness + .agent + .restore_session(id, Default::default()) + .await + .unwrap(); let pid_file = harness.cwd.join("new-generation.pid"); harness .run(&restored, &[("exec", sleeper(&pid_file))]) @@ -3067,7 +3082,11 @@ async fn background_exec_face_answers_as_the_typed_service() { let id = session.id().to_owned(); session.close().await.unwrap(); - let restored = harness.agent.restore_session(id).await.unwrap(); + let restored = harness + .agent + .restore_session(id, Default::default()) + .await + .unwrap(); restored.idle("main").await.unwrap(); let background = restored.service::("main").unwrap(); let ctx = harness.seen.ctx("main"); @@ -3182,7 +3201,11 @@ async fn a_batch_that_edits_then_reads_sees_the_edit() { "edit".into(), "exec".into(), ]); - let session = harness.agent.create_session(config).await.unwrap(); + let session = harness + .agent + .create_session(config, Default::default()) + .await + .unwrap(); let path = harness.cwd.join("batch-read.txt"); std::fs::write(&path, "before\n").unwrap(); let target = path.to_string_lossy().into_owned(); @@ -3224,7 +3247,11 @@ async fn a_batch_that_edits_then_runs_a_command_sees_the_edit() { let harness = Harness::new(platform(&[]).await, Hook::None).await; let mut config = harness.config(); config.tools = Some(vec!["read".into(), "edit".into(), "exec".into()]); - let session = harness.agent.create_session(config).await.unwrap(); + let session = harness + .agent + .create_session(config, Default::default()) + .await + .unwrap(); let path = harness.cwd.join("batch-exec.txt"); std::fs::write(&path, "before\n").unwrap(); let target = path.to_string_lossy().into_owned(); @@ -3298,7 +3325,11 @@ async fn a_failed_recovery_wake_faults_the_session_and_is_posted_once_on_retry() .store .fail_next_wake .store(failure, Ordering::SeqCst); - match harness.agent.restore_session(id.clone()).await { + match harness + .agent + .restore_session(id.clone(), Default::default()) + .await + { Err(error) => assert!( error.to_string().contains("injected exec wake failure"), "{error}" @@ -3339,7 +3370,11 @@ async fn a_failed_recovery_wake_faults_the_session_and_is_posted_once_on_retry() "failed wake was not committed" ); assert_eq!(ended(&persisted).len(), 1); - let recovered = harness.agent.restore_session(id.clone()).await.unwrap(); + let recovered = harness + .agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); recovered.idle("main").await.unwrap(); let events = local_events(&recovered).await; assert_eq!( @@ -3352,7 +3387,11 @@ async fn a_failed_recovery_wake_faults_the_session_and_is_posted_once_on_retry() "recovery must not rerun or re-end the process" ); unload_once_released(&recovered).await; - let repeated = harness.agent.restore_session(id).await.unwrap(); + let repeated = harness + .agent + .restore_session(id, Default::default()) + .await + .unwrap(); repeated.idle("main").await.unwrap(); assert_eq!( notifications(&local_events(&repeated).await), diff --git a/tests/integration/tests/local_product.rs b/tests/integration/tests/local_product.rs index ab1af07848..8c13ce061a 100644 --- a/tests/integration/tests/local_product.rs +++ b/tests/integration/tests/local_product.rs @@ -82,21 +82,24 @@ async fn product(dirs: &Dirs) -> Product { async fn session(product: &Product, cwd: &Path) -> Session { product .agent - .create_session(SessionConfig { - cwd: cwd.to_string_lossy().into_owned(), - tools: Some( - [ - "read", "write", "edit", "glob", "grep", "exec", "wait", "skill", - ] - .map(String::from) - .to_vec(), - ), - permission_policy: PermissionPolicy { - preset: PermissionPreset::WorkspaceWrite, - ..Default::default() + .create_session( + SessionConfig { + cwd: cwd.to_string_lossy().into_owned(), + tools: Some( + [ + "read", "write", "edit", "glob", "grep", "exec", "wait", "skill", + ] + .map(String::from) + .to_vec(), + ), + permission_policy: PermissionPolicy { + preset: PermissionPreset::WorkspaceWrite, + ..Default::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - }) + Default::default(), + ) .await .unwrap() } diff --git a/tests/integration/tests/local_support/mod.rs b/tests/integration/tests/local_support/mod.rs index 6afbb8f4b0..d4c6126094 100644 --- a/tests/integration/tests/local_support/mod.rs +++ b/tests/integration/tests/local_support/mod.rs @@ -367,12 +367,15 @@ impl Env { } pub async fn session(&self, cwd: &Path, system_prompt: &str) -> Result { self.agent - .create_session(SessionConfig { - cwd: cwd.to_string_lossy().into_owned(), - system_prompt: system_prompt.into(), - tools: Some(vec!["skill".into(), "gate".into()]), - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + cwd: cwd.to_string_lossy().into_owned(), + system_prompt: system_prompt.into(), + tools: Some(vec!["skill".into(), "gate".into()]), + ..SessionConfig::default() + }, + Default::default(), + ) .await } } diff --git a/tests/integration/tests/minimal_execution.rs b/tests/integration/tests/minimal_execution.rs index d73e193777..f1a0111438 100644 --- a/tests/integration/tests/minimal_execution.rs +++ b/tests/integration/tests/minimal_execution.rs @@ -286,7 +286,10 @@ impl Harness { config } async fn session(&self) -> Session { - self.agent.create_session(self.config()).await.unwrap() + self.agent + .create_session(self.config(), Default::default()) + .await + .unwrap() } async fn run(&self, session: &Session, calls: &[(&str, Value)]) { self.model.push(calls); @@ -1347,7 +1350,7 @@ async fn restoring_shell_exec_prefixes_settles_orphans_and_reposts_only_missing_ } let restored = harness .agent - .restore_session(session.id().to_owned()) + .restore_session(session.id().to_owned(), Default::default()) .await .unwrap(); let events = until( @@ -1425,7 +1428,7 @@ async fn restoring_shell_exec_prefixes_settles_orphans_and_reposts_only_missing_ assert!(restored.unload_if_idle().await.unwrap()); let again = harness .agent - .restore_session(session.id().to_owned()) + .restore_session(session.id().to_owned(), Default::default()) .await .unwrap(); again.idle("main").await.unwrap(); diff --git a/tests/integration/tests/named_parts.rs b/tests/integration/tests/named_parts.rs index 7ce812536a..95cca91546 100644 --- a/tests/integration/tests/named_parts.rs +++ b/tests/integration/tests/named_parts.rs @@ -302,7 +302,7 @@ async fn a_part_without_layer_types_mounts_in_every_group() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -386,7 +386,7 @@ async fn a_part_provides_by_name_and_each_instance_sees_its_own_copy() { let mut ids = Vec::new(); for _ in 0..2 { let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); ids.push(session.id().to_owned()); @@ -420,7 +420,7 @@ async fn a_rust_part_reads_a_crossing_name_at_its_catalog_key() { let mut ids = Vec::new(); for _ in 0..2 { let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); ids.push(session.id().to_owned()); @@ -451,7 +451,7 @@ async fn a_misplaced_part_fails_where_it_is_mounted_naming_the_group() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let error = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .err() .expect("a Session part reading branch names fails"); @@ -556,7 +556,7 @@ async fn a_session_and_its_main_branch_keep_opening_while_rows_become_active() { let agent = MinimalHost::start(&builder).await.unwrap(); let session = tokio::time::timeout( Duration::from_secs(20), - agent.create_session(SessionConfig::default()), + agent.create_session(SessionConfig::default(), Default::default()), ) .await .expect("a progressing opening finishes") @@ -602,7 +602,7 @@ async fn a_row_blocking_in_apply_fails_creation_after_no_progress() { let started = std::time::Instant::now(); let error = tokio::time::timeout( Duration::from_secs(20), - agent.create_session(SessionConfig::default()), + agent.create_session(SessionConfig::default(), Default::default()), ) .await .expect("creation returns after no progress") @@ -637,7 +637,7 @@ async fn activity_outside_an_opening_cannot_keep_a_stuck_session_alive() { } }; let error = tokio::select! { - result = agent.create_session(SessionConfig::default()) => result.err().expect("the stuck opening fails"), + result = agent.create_session(SessionConfig::default(), Default::default()) => result.err().expect("the stuck opening fails"), () = unrelated => panic!("unrelated Active rows kept the opening alive"), }; assert!(error.to_string().contains("test.stuck"), "{error}"); @@ -658,7 +658,7 @@ async fn restarting_an_optional_row_cannot_keep_a_stuck_opening_alive() { })); let agent = MinimalHost::start(&builder).await.unwrap(); let root = agent.root().clone(); - let mut opening = Box::pin(agent.create_session(SessionConfig::default())); + let mut opening = Box::pin(agent.create_session(SessionConfig::default(), Default::default())); let churn = async { let view = loop { if let Some(view) = root @@ -727,7 +727,8 @@ async fn optional_rows_extend_a_session_or_branch_opening_until_required_rows_ar } let agent = MinimalHost::start(&builder).await.unwrap(); let root = agent.root().clone(); - let mut opening = Box::pin(agent.create_session(SessionConfig::default())); + let mut opening = + Box::pin(agent.create_session(SessionConfig::default(), Default::default())); tokio::select! { result = &mut opening => panic!("gated opening finished before publication: {:?}", result.err()), _ = tokio::time::sleep(Duration::from_millis(200)) => {} diff --git a/tests/integration/tests/part_registry.rs b/tests/integration/tests/part_registry.rs index af53a934a9..9c30d428e4 100644 --- a/tests/integration/tests/part_registry.rs +++ b/tests/integration/tests/part_registry.rs @@ -239,7 +239,7 @@ async fn a_registered_part_reaches_open_and_later_sessions_and_leaves_with_its_p let (agent, registry) = placed(builder()).await; let root = agent.root().clone(); let before = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let log = Log::default(); @@ -254,7 +254,7 @@ async fn a_registered_part_reaches_open_and_later_sessions_and_leaves_with_its_p let first = format!("mounted {}", before.id()); eventually(|| log.lock().unwrap().contains(&first)).await; let after = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let second = format!("mounted {}", after.id()); @@ -271,7 +271,7 @@ async fn a_registered_part_reaches_open_and_later_sessions_and_leaves_with_its_p assert!(!mounted(session, "test.recorder")); } let later = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); tokio::time::sleep(Duration::from_millis(100)).await; @@ -305,14 +305,17 @@ async fn a_generator_may_mount_nothing_for_an_instance() { ) .await; let off = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let on = agent - .create_session(SessionConfig { - system_prompt: "recorded".into(), - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + system_prompt: "recorded".into(), + ..SessionConfig::default() + }, + Default::default(), + ) .await .unwrap(); let mounted_on = format!("mounted {}", on.id()); @@ -336,7 +339,11 @@ async fn a_required_part_gates_publication_and_its_failure_fails_the_session() { let root = agent.root().clone(); let creating = { let agent = agent.agent().clone(); - tokio::spawn(async move { agent.create_session(SessionConfig::default()).await }) + tokio::spawn(async move { + agent + .create_session(SessionConfig::default(), Default::default()) + .await + }) }; let registry = registries.recv().await.unwrap(); tokio::time::sleep(Duration::from_millis(200)).await; @@ -378,7 +385,7 @@ async fn a_required_part_gates_publication_and_its_failure_fails_the_session() { ) .await; let error = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .err() .expect("a failed required part fails its Session"); @@ -414,7 +421,11 @@ async fn an_optional_part_settles_before_publication_and_its_failure_stays_local .await; let creating = { let agent = agent.agent().clone(); - tokio::spawn(async move { agent.create_session(SessionConfig::default()).await }) + tokio::spawn(async move { + agent + .create_session(SessionConfig::default(), Default::default()) + .await + }) }; tokio::time::sleep(Duration::from_millis(200)).await; assert!( @@ -467,7 +478,7 @@ async fn a_branch_part_mounts_in_each_branch() { ) .await; let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let main = format!("branch {}/main", session.id()); @@ -497,8 +508,14 @@ async fn agents_of_one_builder_mount_only_their_own_plugins_parts() { let registry = registries.recv().await.unwrap(); let two = MinimalHost::start(&builder).await.unwrap(); let other = registries.recv().await.unwrap(); - let first = one.create_session(SessionConfig::default()).await.unwrap(); - let second = two.create_session(SessionConfig::default()).await.unwrap(); + let first = one + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); + let second = two + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); assert!(!Arc::ptr_eq(®istry, &other), "each host has its own"); assert!(!Arc::ptr_eq(®istry, &builder.parts())); let log = Log::default(); diff --git a/tests/integration/tests/prompt_boundaries.rs b/tests/integration/tests/prompt_boundaries.rs index b6292f2d31..bff8abc7ec 100644 --- a/tests/integration/tests/prompt_boundaries.rs +++ b/tests/integration/tests/prompt_boundaries.rs @@ -84,7 +84,7 @@ async fn rejected_prompt_load_does_not_publish_or_poison_the_pending_load() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); @@ -208,7 +208,7 @@ async fn rewritten_control_identity_is_registered_without_leaking_activity() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let result = tokio::time::timeout( @@ -346,7 +346,7 @@ async fn scope_ended_in_committed_tail_supersedes_loading_result() { ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let result = session @@ -462,7 +462,7 @@ async fn scope_retirement_rejects_inconsistent_before_batches_and_retries_after_ )); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let id = session.id().to_owned(); @@ -528,7 +528,7 @@ async fn scope_retirement_rejects_inconsistent_before_batches_and_retries_after_ let _ = agent.close().await; active.store(false, std::sync::atomic::Ordering::SeqCst); let agent = MinimalHost::start(&builder).await.unwrap(); - let restored = agent.restore_session(id).await.unwrap(); + let restored = agent.restore_session(id, Default::default()).await.unwrap(); restored.idle("main").await.unwrap(); assert!( !restored diff --git a/tests/integration/tests/prompt_guide.rs b/tests/integration/tests/prompt_guide.rs index 333b77d698..de092a0019 100644 --- a/tests/integration/tests/prompt_guide.rs +++ b/tests/integration/tests/prompt_guide.rs @@ -251,10 +251,13 @@ async fn both_paths_carry_one_composition() { workspace(&mut builder, &dirs); let agent = platform_host(&builder, &dirs).await; let session = agent - .create_session(SessionConfig { - system_prompt: "configured rules".into(), - ..work_config(&dirs) - }) + .create_session( + SessionConfig { + system_prompt: "configured rules".into(), + ..work_config(&dirs) + }, + Default::default(), + ) .await .unwrap(); session @@ -305,10 +308,13 @@ async fn both_paths_carry_one_composition() { defaults::install_with_prompt(&mut builder, Arc::new(EmptyPromptHost), None); let agent = platform_host(&builder, &dirs).await; let session = agent - .create_session(SessionConfig { - system_prompt: "host rules".into(), - ..work_config(&dirs) - }) + .create_session( + SessionConfig { + system_prompt: "host rules".into(), + ..work_config(&dirs) + }, + Default::default(), + ) .await .unwrap(); run(&session, "hello").await; @@ -394,10 +400,13 @@ async fn an_adopted_request_and_the_summarizers_request_carry_one_system() { workspace(&mut builder, &dirs); let agent = platform_host(&builder, &dirs).await; let session = agent - .create_session(SessionConfig { - system_prompt: "configured rules".into(), - ..work_config(&dirs) - }) + .create_session( + SessionConfig { + system_prompt: "configured rules".into(), + ..work_config(&dirs) + }, + Default::default(), + ) .await .unwrap(); session @@ -507,7 +516,7 @@ async fn an_entry_takes_effect_when_its_writer_loads_and_ends_when_it_unloads() )); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); assert_eq!( @@ -657,7 +666,10 @@ async fn a_branch_scoped_entry_publishes_only_on_its_branch() { }, )); let agent = platform_host(&builder, &dirs).await; - let session = agent.create_session(work_config(&dirs)).await.unwrap(); + let session = agent + .create_session(work_config(&dirs), Default::default()) + .await + .unwrap(); assert_eq!( session .configure( @@ -800,10 +812,13 @@ async fn an_entry_registered_while_its_branch_opens_is_adopted() { store.hold_next_configuration_on("main"); // The pinned creation lives past the host's close: it borrows a clone. let opener = agent.agent().clone(); - let creation = opener.create_session(SessionConfig { - system_prompt: "configured rules".into(), - ..work_config(&dirs) - }); + let creation = opener.create_session( + SessionConfig { + system_prompt: "configured rules".into(), + ..work_config(&dirs) + }, + Default::default(), + ); tokio::pin!(creation); let session = tokio::select! { _ = &mut creation => panic!("the Session opened before its publication was held"), @@ -873,7 +888,10 @@ async fn a_fork_composes_its_own_entries_at_its_open() { tables.clone(), ) .await; - let session = agent.create_session(work_config(&dirs)).await.unwrap(); + let session = agent + .create_session(work_config(&dirs), Default::default()) + .await + .unwrap(); assert_eq!( session .configure( @@ -981,7 +999,10 @@ async fn a_fork_carries_its_own_entry_in_its_first_request() { tables.clone(), ) .await; - let session = agent.create_session(work_config(&dirs)).await.unwrap(); + let session = agent + .create_session(work_config(&dirs), Default::default()) + .await + .unwrap(); assert_eq!( session .configure( @@ -1054,7 +1075,7 @@ async fn a_restored_branch_converges_on_the_entries_its_writers_register() { let views = Arc::new(Mutex::new(Vec::new())); let agent = restore_guide_agent(store.clone(), flag.clone(), views.clone()).await; let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); assert_eq!( @@ -1079,7 +1100,10 @@ async fn a_restored_branch_converges_on_the_entries_its_writers_register() { // entry at its open. flag.store(true, Ordering::SeqCst); let agent = restore_guide_agent(store.clone(), flag.clone(), views.clone()).await; - let session = agent.restore_session(id.clone()).await.unwrap(); + let session = agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); wait_for_configurations(&session, "main", 1).await; let adopted = last_configured(&session, "main").await; let system = system_text(adopted.system.as_ref().expect("the adopted System")); @@ -1091,7 +1115,7 @@ async fn a_restored_branch_converges_on_the_entries_its_writers_register() { // The writer leaves it: the next restore drops the entry the same way. flag.store(false, Ordering::SeqCst); let agent = restore_guide_agent(store.clone(), flag.clone(), views.clone()).await; - let session = agent.restore_session(id).await.unwrap(); + let session = agent.restore_session(id, Default::default()).await.unwrap(); wait_for_configurations(&session, "main", 2).await; let adopted = last_configured(&session, "main").await; let system = system_text(adopted.system.as_ref().expect("the adopted System")); @@ -1113,7 +1137,7 @@ async fn a_restored_branch_carries_its_entries_in_its_first_request() { let views = Arc::new(Mutex::new(Vec::new())); let agent = restore_guide_agent(store.clone(), flag.clone(), views.clone()).await; let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); assert_eq!( @@ -1139,7 +1163,7 @@ async fn a_restored_branch_carries_its_entries_in_its_first_request() { // between it and the open. flag.store(true, Ordering::SeqCst); let agent = restore_guide_agent(store.clone(), flag, views).await; - let session = agent.restore_session(id).await.unwrap(); + let session = agent.restore_session(id, Default::default()).await.unwrap(); session .submit("second".into(), InputMode::Queue, "main") .await @@ -1175,7 +1199,10 @@ async fn a_closing_branch_does_not_adopt_its_withdrawn_guide() { tables.clone(), ) .await; - let session = agent.create_session(work_config(&dirs)).await.unwrap(); + let session = agent + .create_session(work_config(&dirs), Default::default()) + .await + .unwrap(); assert_eq!( session .configure( @@ -1295,7 +1322,10 @@ async fn an_entry_withdrawing_as_the_session_unloads_is_not_recorded() { tables.clone(), ) .await; - let session = agent.create_session(work_config(&dirs)).await.unwrap(); + let session = agent + .create_session(work_config(&dirs), Default::default()) + .await + .unwrap(); assert_eq!( session .configure( @@ -1355,7 +1385,7 @@ async fn an_entry_withdrawing_as_the_session_unloads_is_not_recorded() { tables.clone(), ) .await; - let restored = agent.restore_session(id).await.unwrap(); + let restored = agent.restore_session(id, Default::default()).await.unwrap(); wait_for_configurations(&restored, "main", recorded).await; let adopted = last_configured(&restored, "main").await; let system = system_text(adopted.system.as_ref().expect("the adopted System")); @@ -1383,7 +1413,10 @@ async fn a_reloaded_writer_readopts_its_returned_entry() { tables.clone(), ) .await; - let session = agent.create_session(work_config(&dirs)).await.unwrap(); + let session = agent + .create_session(work_config(&dirs), Default::default()) + .await + .unwrap(); assert_eq!( session .configure( @@ -1491,7 +1524,7 @@ async fn a_composition_that_moved_and_returned_while_its_branch_opens_is_adopted store.hold_next_configuration_on("main"); // The pinned creation lives past the host's close: it borrows a clone. let opener = agent.agent().clone(); - let creation = opener.create_session(SessionConfig::default()); + let creation = opener.create_session(SessionConfig::default(), Default::default()); tokio::pin!(creation); let session = tokio::select! { _ = &mut creation => panic!("the Session opened before its publication was held"), @@ -1586,7 +1619,7 @@ async fn an_entry_that_returns_during_the_open_adoption_is_adopted() { store.hold_next_configuration_on("main"); // The pinned creation lives past the host's close: it borrows a clone. let opener = agent.agent().clone(); - let creation = opener.create_session(SessionConfig::default()); + let creation = opener.create_session(SessionConfig::default(), Default::default()); tokio::pin!(creation); let session = tokio::select! { _ = &mut creation => panic!("the Session opened before its publication was held"), @@ -1629,7 +1662,7 @@ async fn the_frame_states_the_compaction_handle() { defaults::install_with_prompt(&mut builder, Arc::new(EmptyPromptHost), None); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); run(&session, "hello").await; @@ -1953,7 +1986,10 @@ async fn each_branch_keeps_its_own_entries() { workspace(&mut builder, &dirs); defaults::install_with_prompt(&mut builder, Arc::new(EmptyPromptHost), None); let agent = platform_host(&builder, &dirs).await; - let session = agent.create_session(work_config(&dirs)).await.unwrap(); + let session = agent + .create_session(work_config(&dirs), Default::default()) + .await + .unwrap(); run(&session, "on main").await; let main = last_system(&session, "main").await; assert_eq!( @@ -2140,7 +2176,10 @@ async fn a_tools_only_adoption_carries_the_entry_its_writer_registers() { }, )); let agent = platform_host(&builder, &dirs).await; - let session = agent.create_session(work_config(&dirs)).await.unwrap(); + let session = agent + .create_session(work_config(&dirs), Default::default()) + .await + .unwrap(); assert_eq!( session .configure( diff --git a/tests/integration/tests/prompt_lifecycle.rs b/tests/integration/tests/prompt_lifecycle.rs index a5ecfc1bc0..3708f9bad5 100644 --- a/tests/integration/tests/prompt_lifecycle.rs +++ b/tests/integration/tests/prompt_lifecycle.rs @@ -150,10 +150,13 @@ async fn model_adoption_preserves_enabled_tools_on_initialization_and_refresh() .await .unwrap(); let session = agent - .create_session(SessionConfig { - tools: Some(vec!["echo".into()]), - ..Default::default() - }) + .create_session( + SessionConfig { + tools: Some(vec!["echo".into()]), + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); if !initial { @@ -228,10 +231,13 @@ async fn input_guide_survives_configuration_refresh_and_revocation_without_dupli let host = Arc::new(Prompts(Mutex::new(BTreeMap::new()))); let agent = MinimalHost::start(&builder(host.clone())).await.unwrap(); let session = agent - .create_session(SessionConfig { - system_prompt: "legacy rules".into(), - ..Default::default() - }) + .create_session( + SessionConfig { + system_prompt: "legacy rules".into(), + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); for (version, expected) in [ @@ -455,7 +461,7 @@ async fn configuration_publication_preserves_trusted_before_changes_atomically() ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); @@ -548,7 +554,7 @@ async fn prepared_model_call_keeps_its_configuration_while_later_turn_uses_refre .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let target = PromptSourceTarget { @@ -733,7 +739,7 @@ async fn a_line_records_the_system_it_sends_across_a_parent_block() { let host = Arc::new(Prompts(Mutex::new(BTreeMap::new()))); let agent = MinimalHost::start(&builder(host)).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -865,7 +871,7 @@ async fn configuration_is_atomic_failure_safe_and_inherited() { ])))); let agent = MinimalHost::start(&builder(host.clone())).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let frozen_sources = vec![( @@ -1091,7 +1097,7 @@ async fn overlapping_load_is_superseded_and_close_joins_cancellation() { )])))); let agent = MinimalHost::start(&builder(host.clone())).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let target = PromptSourceTarget { @@ -1239,7 +1245,7 @@ async fn initial_configuration_loads_before_start_and_failure_rolls_back() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let events = chain_events(&session, "main", ..).await.unwrap(); @@ -1271,7 +1277,7 @@ async fn initial_configuration_loads_before_start_and_failure_rolls_back() { let result = MinimalHost::start(&builder_with_initial(failing, initial)) .await .unwrap() - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await; let error = match result { Ok(_) => panic!("initial load failure unexpectedly created a session"), @@ -1498,7 +1504,7 @@ async fn a_restore_keeps_opening_while_dispatch_or_opening_receipts_advance() { let started = std::time::Instant::now(); let session = tokio::time::timeout( Duration::from_secs(20), - agent.restore_session("slow-restore".into()), + agent.restore_session("slow-restore".into(), Default::default()), ) .await .expect("progressing restore finishes") @@ -1552,7 +1558,7 @@ async fn opening_failure_is_not_hidden_by_an_earlier_pending_receipt() { let agent = MinimalHost::start(&builder).await.unwrap(); let result = tokio::time::timeout( Duration::from_secs(1), - agent.create_session(SessionConfig::default()), + agent.create_session(SessionConfig::default(), Default::default()), ) .await .expect("opening failure must be prompt"); @@ -1645,9 +1651,13 @@ async fn startup_opening_dispatch_is_free_and_close_or_deadline_joins_the_host() let creating = agent.clone(); let mut creation = tokio::spawn(async move { if restore { - creating.restore_session("startup".into()).await + creating + .restore_session("startup".into(), Default::default()) + .await } else { - creating.create_session(SessionConfig::default()).await + creating + .create_session(SessionConfig::default(), Default::default()) + .await } }); tokio::time::timeout(Duration::from_secs(1), started.notified()) @@ -1763,7 +1773,7 @@ async fn child_opening_deadline_or_close_joins_before_recording_failure() { }); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let started = Arc::new(Notify::new()); @@ -1954,7 +1964,7 @@ async fn restoring_a_session_keeps_its_adopted_system_and_model() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .restore_session("restored-prompt".into()) + .restore_session("restored-prompt".into(), Default::default()) .await .unwrap(); assert_eq!( @@ -2142,7 +2152,7 @@ async fn restoring_a_never_started_session_starts_it() { builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store)); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .restore_session("empty-prompt-restore".into()) + .restore_session("empty-prompt-restore".into(), Default::default()) .await .unwrap(); assert_eq!(calls.load(Ordering::SeqCst), 1); @@ -2176,7 +2186,7 @@ async fn an_undelivered_initial_context_prompt_is_adopted_again_in_a_child() { .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); assert_eq!(calls.load(Ordering::SeqCst), 1); @@ -2294,7 +2304,7 @@ async fn a_delivered_initial_context_prompt_is_inherited_and_unchanged_in_a_chil .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); // One turn consumes the initial delivery block. @@ -2359,7 +2369,7 @@ async fn same_body_new_version_reconfigures_but_identical_update_is_unchanged() )])))); let agent = MinimalHost::start(&builder(host.clone())).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let target = PromptSourceTarget { @@ -2416,7 +2426,7 @@ async fn duplicate_targets_are_rejected_before_loading() { let host = Arc::new(Prompts(Mutex::new(BTreeMap::new()))); let agent = MinimalHost::start(&builder(host)).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let target = PromptSourceTarget { @@ -2458,7 +2468,7 @@ async fn large_request_can_supersede_a_consumed_load_without_a_history_byte_budg )); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let first = tokio::spawn({ @@ -2515,7 +2525,7 @@ async fn loader_panic_is_reported_to_the_agent_supervisor() { )])))); let agent = MinimalHost::start(&builder(host)).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let error = session @@ -2609,7 +2619,7 @@ async fn before_retargeting_requires_matching_capabilities_without_remerging_par ); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); session @@ -2675,7 +2685,7 @@ async fn frozen_configuration_rejects_mismatched_identity_and_nonbranch_system_e .await .unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); let before = session.sequence("main").unwrap(); diff --git a/tests/integration/tests/prompt_sources.rs b/tests/integration/tests/prompt_sources.rs index 025f0ac32f..627e23b28b 100644 --- a/tests/integration/tests/prompt_sources.rs +++ b/tests/integration/tests/prompt_sources.rs @@ -286,7 +286,11 @@ async fn a_restored_session_receives_the_changed_environment_once() { }, ) .await; - let session = env.agent.restore_session(id.clone()).await.unwrap(); + let session = env + .agent + .restore_session(id.clone(), Default::default()) + .await + .unwrap(); run(&session, "after restart").await; let sent = delivered(&session, ENVIRONMENT).await; assert_eq!(sent.len(), environments); @@ -406,7 +410,11 @@ async fn a_loaded_branch_appends_a_date_reminder_when_the_day_changes() { ..Options::default() }; let env = local_support::env(&dirs, options).await; - let session = env.agent.restore_session(id).await.unwrap(); + let session = env + .agent + .restore_session(id, Default::default()) + .await + .unwrap(); run(&session, "after restart").await; assert_eq!(dates(&session).await, ["2026-09-30", "2026-10-01"]); env.agent.close().await.unwrap(); diff --git a/tests/integration/tests/session_lifecycle.rs b/tests/integration/tests/session_lifecycle.rs index 4ba81677ec..5dae87689e 100644 --- a/tests/integration/tests/session_lifecycle.rs +++ b/tests/integration/tests/session_lifecycle.rs @@ -31,7 +31,8 @@ async fn agent_close_during_assembly_never_activates_the_session() { tools: Some(vec!["skill".into(), "gate".into()]), ..SessionConfig::default() }; - let creating = tokio::spawn(async move { agent.create_session(config).await }); + let creating = + tokio::spawn(async move { agent.create_session(config, Default::default()).await }); tokio::time::timeout(std::time::Duration::from_secs(10), hold.entered.notified()) .await .expect("assembly reached the hold"); diff --git a/tests/integration/tests/skills.rs b/tests/integration/tests/skills.rs index b152744dd6..0e6b729699 100644 --- a/tests/integration/tests/skills.rs +++ b/tests/integration/tests/skills.rs @@ -1224,11 +1224,14 @@ async fn catalog_changes_during_assembly_wait_for_session_publication() { let cwd = layout.cwd.to_string_lossy().into_owned(); let creating = tokio::spawn(async move { agent - .create_session(SessionConfig { - cwd, - tools: Some(vec!["skill".into(), "gate".into()]), - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + cwd, + tools: Some(vec!["skill".into(), "gate".into()]), + ..SessionConfig::default() + }, + Default::default(), + ) .await }); tokio::time::timeout(std::time::Duration::from_secs(10), hold.entered.notified()) diff --git a/tests/integration/tests/timeline_tail.rs b/tests/integration/tests/timeline_tail.rs index 52bb5d1971..186294d96d 100644 --- a/tests/integration/tests/timeline_tail.rs +++ b/tests/integration/tests/timeline_tail.rs @@ -285,7 +285,7 @@ async fn handover(tail: bool) -> (u64, u64) { )); let agent = MinimalHost::start(&builder).await.unwrap(); let session = agent - .create_session(SessionConfig::default()) + .create_session(SessionConfig::default(), Default::default()) .await .unwrap(); tokio::time::timeout(std::time::Duration::from_secs(10), started_rx.recv()) @@ -742,7 +742,7 @@ async fn consume_branch() -> (MinimalHost, Session, Ctx, Arc, Arc Session { self.agent - .create_session(SessionConfig { - tools: Some(vec!["gate".into()]), - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + tools: Some(vec!["gate".into()]), + ..SessionConfig::default() + }, + Default::default(), + ) .await .unwrap() } @@ -550,7 +553,10 @@ async fn a_preparing_request_keeps_its_contributor_generation() { let agent = contributing(&builder).await; let root = agent.root().clone(); enable(&agent).await; - let session = agent.create_session(config).await.unwrap(); + let session = agent + .create_session(config, Default::default()) + .await + .unwrap(); session .submit("tool:optional {}".into(), InputMode::Queue, "main") .await @@ -661,15 +667,18 @@ async fn custom_preparation_keeps_none_empty_and_filtered_declarations() { let agent = contributing(&builder).await; enable(&agent).await; let session = agent - .create_session(SessionConfig { - cwd: dirs.root.to_string_lossy().into_owned(), - tools: Some(vec!["optional".into(), "echo".into()]), - permission_policy: PermissionPolicy { - allowed_tools: vec!["echo".into()], - ..PermissionPolicy::default() + .create_session( + SessionConfig { + cwd: dirs.root.to_string_lossy().into_owned(), + tools: Some(vec!["optional".into(), "echo".into()]), + permission_policy: PermissionPolicy { + allowed_tools: vec!["echo".into()], + ..PermissionPolicy::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - }) + Default::default(), + ) .await .unwrap(); let calls_echo = valid && selected.as_ref().is_some_and(|tools| !tools.is_empty()); @@ -726,14 +735,17 @@ async fn optional_contributors_do_not_gate_the_loop_and_follow_new_generations() let root = agent.root().clone(); enable(&agent).await; let session = agent - .create_session(SessionConfig { - tools: Some(vec!["optional".into(), "absent".into(), "echo".into()]), - permission_policy: PermissionPolicy { - allowed_tools: vec!["echo".into(), "optional".into()], - ..PermissionPolicy::default() + .create_session( + SessionConfig { + tools: Some(vec!["optional".into(), "absent".into(), "echo".into()]), + permission_policy: PermissionPolicy { + allowed_tools: vec!["echo".into(), "optional".into()], + ..PermissionPolicy::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - }) + Default::default(), + ) .await .unwrap(); session @@ -902,14 +914,17 @@ async fn contributors_are_current_for_the_first_request_without_initial_configur let agent = build().await; let root = agent.root().clone(); let session = agent - .create_session(SessionConfig { - tools: Some(vec!["optional".into(), "echo".into()]), - permission_policy: PermissionPolicy { - allowed_tools: vec!["echo".into(), "optional".into()], - ..PermissionPolicy::default() + .create_session( + SessionConfig { + tools: Some(vec!["optional".into(), "echo".into()]), + permission_policy: PermissionPolicy { + allowed_tools: vec!["echo".into(), "optional".into()], + ..PermissionPolicy::default() + }, + ..SessionConfig::default() }, - ..SessionConfig::default() - }) + Default::default(), + ) .await .unwrap(); let provider = root @@ -939,7 +954,7 @@ async fn contributors_are_current_for_the_first_request_without_initial_configur agent.close().await.unwrap(); let agent = build().await; - let restored = agent.restore_session(id).await.unwrap(); + let restored = agent.restore_session(id, Default::default()).await.unwrap(); restored .submit("tool:optional {}".into(), InputMode::Queue, "main") .await @@ -1156,10 +1171,13 @@ async fn a_session_without_a_mount_list_declares_every_registered_tool() { let env = env(source, None).await; let session = env .agent - .create_session(SessionConfig { - tools, - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + tools, + ..SessionConfig::default() + }, + Default::default(), + ) .await .unwrap(); adopted(&session, "main", &[("mcp:a", "v1")]).await; @@ -1210,7 +1228,11 @@ async fn a_restored_branch_adopts_the_new_versions_before_its_first_request() { let source = TestSource::new(); source.seed(vec![set("mcp:a", "v2", &["lookup"], &log, None)]); let env2 = env(source, Some(store)).await; - let restored = env2.agent.restore_session(id).await.unwrap(); + let restored = env2 + .agent + .restore_session(id, Default::default()) + .await + .unwrap(); adopted(&restored, "main", &[("mcp:a", "v2")]).await; env2.turn(&restored, "main", &["lookup"]).await; assert_eq!(last_result(&restored, "main").await, "v2 ran lookup"); @@ -1346,10 +1368,13 @@ async fn tool_updates_wait_for_branch_activation_and_do_not_run_after_failed_ass let agent = env.agent.agent().clone(); let creating = tokio::spawn(async move { agent - .create_session(SessionConfig { - tools: Some(vec!["gate".into()]), - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + tools: Some(vec!["gate".into()]), + ..SessionConfig::default() + }, + Default::default(), + ) .await }); let (timeline, registry, source) = @@ -1410,10 +1435,13 @@ async fn registered_sources_keep_their_names_apart_from_contributed_tools() { let invalid = env_named(TestSource::new(), None, "#contributed").await; let error = invalid .agent - .create_session(SessionConfig { - tools: Some(vec!["gate".into()]), - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + tools: Some(vec!["gate".into()]), + ..SessionConfig::default() + }, + Default::default(), + ) .await .err() .expect("an invalid source name fails the Session") @@ -1456,10 +1484,13 @@ async fn contributed_tools_follow_their_provider_until_the_session_closes() { let root = agent.root().clone(); enable(&agent).await; let session = agent - .create_session(SessionConfig { - tools: Some(vec!["optional".into(), "echo".into()]), - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + tools: Some(vec!["optional".into(), "echo".into()]), + ..SessionConfig::default() + }, + Default::default(), + ) .await .unwrap(); let provider = root @@ -1625,7 +1656,10 @@ async fn a_persisted_contributed_version_names_one_generation_across_restores() ..SessionConfig::default() }; let agent = build().await; - let session = agent.create_session(config).await.unwrap(); + let session = agent + .create_session(config, Default::default()) + .await + .unwrap(); session .submit("tool:optional {}".into(), InputMode::Queue, "main") .await @@ -1639,7 +1673,7 @@ async fn a_persisted_contributed_version_names_one_generation_across_restores() agent.close().await.unwrap(); let agent = build().await; - let restored = agent.restore_session(id).await.unwrap(); + let restored = agent.restore_session(id, Default::default()).await.unwrap(); restored .submit("tool:optional {}".into(), InputMode::Queue, "main") .await diff --git a/tests/integration/tests/wait_protocol.rs b/tests/integration/tests/wait_protocol.rs index 17a6995f5a..3b33ec1994 100644 --- a/tests/integration/tests/wait_protocol.rs +++ b/tests/integration/tests/wait_protocol.rs @@ -325,7 +325,10 @@ async fn wait_timeline_traces_match_the_notification_contract() { ]); let mut cover = Cover::default(); for trace in &traces { - let session = host.create_session(SessionConfig::default()).await.unwrap(); + let session = host + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); let (timeline, ctx) = seen.lock().unwrap().clone().unwrap(); let mut history = Vec::new(); let mut taken = Vec::new(); @@ -417,7 +420,10 @@ async fn wait_timeline_traces_match_the_notification_contract() { session.close().await.unwrap(); } for initially_open in [false, true] { - let session = host.create_session(SessionConfig::default()).await.unwrap(); + let session = host + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); let (timeline, ctx) = seen.lock().unwrap().clone().unwrap(); if initially_open { timeline diff --git a/xtask/src/catalog.rs b/xtask/src/catalog.rs index 41b94a311c..f0611531a3 100644 --- a/xtask/src/catalog.rs +++ b/xtask/src/catalog.rs @@ -66,11 +66,14 @@ pub(super) async fn collect() -> Result { .agent() .ok_or("the product profile has no default Agent")?; let session = agent - .create_session(SessionConfig { - cwd: dir.to_string_lossy().into_owned(), - tools: None, - ..Default::default() - }) + .create_session( + SessionConfig { + cwd: dir.to_string_lossy().into_owned(), + tools: None, + ..Default::default() + }, + Default::default(), + ) .await?; let layers = [ ("process", app_server::process_layer(server.diagnostics())), @@ -416,11 +419,14 @@ mod face_tests { .unwrap(); let agent = server.agent().unwrap(); let session = agent - .create_session(SessionConfig { - cwd: dir.to_string_lossy().into_owned(), - tools: None, - ..Default::default() - }) + .create_session( + SessionConfig { + cwd: dir.to_string_lossy().into_owned(), + tools: None, + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); let layers = [ diff --git a/xtask/src/main.rs b/xtask/src/main.rs index bb2c581785..74acd2b30f 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -283,7 +283,7 @@ fn mermaid(graphs: &BTreeMap<&str, Value>) -> String { } async fn graph() -> std::result::Result<(), Box> { let (agent, config, native) = configured_agent().await?; - let session = agent.create_session(config).await?; + let session = agent.create_session(config, Default::default()).await?; let session_diagnostics = session.diagnostics()?; let main_diagnostics = session.branch_diagnostics("main")?; let instance = |d: &RuntimeDiagnostics, name: &str| { @@ -368,7 +368,11 @@ async fn measure() -> std::result::Result<(), Box> { let start = Instant::now(); let mut sessions = vec![]; for _ in 0..count { - sessions.push(agent.create_session(config.clone()).await?); + sessions.push( + agent + .create_session(config.clone(), Default::default()) + .await?, + ); } let create_ms = start.elapsed().as_secs_f64() * 1000.; let bytes_active = allocation::live(); @@ -385,7 +389,9 @@ async fn measure() -> std::result::Result<(), Box> { } let mut concurrent = Vec::new(); for count in [1usize, 16, 64].into_iter().filter(|_| !native) { - let session = agent.create_session(config.clone()).await?; + let session = agent + .create_session(config.clone(), Default::default()) + .await?; let mut branches = vec!["main".to_owned()]; for index in 1..count { branches.push( @@ -465,7 +471,9 @@ async fn context_replay() -> std::result::Result<(), Box> let agent = agent_with_store(store).await?; let live_agent = allocation::live(); let rss_agent = rss_kb(); - let session = agent.create_session(SessionConfig::default()).await?; + let session = agent + .create_session(SessionConfig::default(), Default::default()) + .await?; let live_session = allocation::live(); let rss_session = rss_kb(); let mut steps = Vec::new(); @@ -560,7 +568,9 @@ async fn context_breakdown() -> std::result::Result<(), Box std::result::Result<(), Box> let live_agent = allocation::live(); let rss_agent = rss_kb(); let start = Instant::now(); - let session = agent.restore_session(session_id.clone()).await?; + let session = agent + .restore_session(session_id.clone(), Default::default()) + .await?; let restore_ms = start.elapsed().as_secs_f64() * 1000.; let live_restored = allocation::live(); let peak_restored = allocation::peak(); diff --git a/xtask/src/plugins.rs b/xtask/src/plugins.rs index e2a60ad5dd..d4d27a1a38 100644 --- a/xtask/src/plugins.rs +++ b/xtask/src/plugins.rs @@ -199,11 +199,14 @@ pub async fn local_graph() -> Result> { .await?; let process = agent.root().clone(); let session = agent - .create_session(SessionConfig { - cwd: work.canonicalize()?.to_string_lossy().into_owned(), - tools: Some(TOOLS.map(String::from).to_vec()), - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + cwd: work.canonicalize()?.to_string_lossy().into_owned(), + tools: Some(TOOLS.map(String::from).to_vec()), + ..SessionConfig::default() + }, + Default::default(), + ) .await?; let session_diagnostics = session.diagnostics()?; let main_diagnostics = session.branch_diagnostics("main")?; diff --git a/xtask/src/scenario_eval.rs b/xtask/src/scenario_eval.rs index 342316709c..0f095ebcf7 100644 --- a/xtask/src/scenario_eval.rs +++ b/xtask/src/scenario_eval.rs @@ -22210,12 +22210,15 @@ mod run_tools_tests { .agent() .expect("the served profile has a default Agent"); let session = agent - .create_session(SessionConfig { - cwd: cwd.to_string_lossy().into_owned(), - tools: None, - model, - ..Default::default() - }) + .create_session( + SessionConfig { + cwd: cwd.to_string_lossy().into_owned(), + tools: None, + model, + ..Default::default() + }, + Default::default(), + ) .await .unwrap(); let registry = probe From 674789c8288ce240a73b1a4afa11103a374b8388 Mon Sep 17 00:00:00 2001 From: huihui Date: Wed, 25 Nov 2026 22:58:03 +0800 Subject: [PATCH 02/23] refactor(runtime): name a prepared creation's Session once `CreateSessionOptions` no longer holds the Session id twice: `id` is the only name, and `prepare` receives it when creation runs, so a prepared step commits the rows of the Session being created and cannot disagree with it. The options flow test covers a prepare step with an explicit id and without one, alongside the explicit-id and extension creations, and the thin-instances example states a call that compiles. Refs #2020 --- .../tests/agent_options_flow.rs | 65 ++++++++++++++----- crates/dim-agent-runtime/src/agent.rs | 38 ++++++----- crates/dim-app-server/src/agents.rs | 62 ++++++++---------- docs/design/thin-instances.md | 2 +- 4 files changed, 98 insertions(+), 69 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index fcdd18d2ff..2b2920b312 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -7,7 +7,7 @@ use dim_agent_runtime::{ use rutis::host::DynPlugin; use rutis::{Ctx, Plugin}; use std::sync::{ - Arc, + Arc, Mutex, atomic::{AtomicU32, Ordering}, }; @@ -51,30 +51,37 @@ async fn create_and_restore_options_apply_their_fields() { .await .unwrap(); - let prepared_id = "prepared-session"; - let config = SessionConfig::default(); - let prepare = { - let store = store.clone(); - let id = prepared_id.to_owned(); - let config = config.clone(); - Box::pin(async move { - store.create_session(&id, &config).await?; - Ok(()) - }) - }; + let prepared = Arc::new(Mutex::new(None::)); let session = agent .create_session( - config, + SessionConfig::default(), CreateSessionOptions::default() - .prepare(prepared_id, prepare) + .id("named-session") + .prepare({ + let store = store.clone(); + let prepared = prepared.clone(); + move |id| { + *prepared.lock().unwrap() = Some(id.clone()); + let config = SessionConfig::default(); + Box::pin(async move { + store.create_session(&id, &config).await?; + Ok(()) + }) + } + }) .extension(GROUP, 7_u32), ) .await .unwrap(); assert_eq!( session.id(), - prepared_id, - "a prepared creation is named by the id its prepare step commits" + "named-session", + "a prepared creation is created under the id the options name" + ); + assert_eq!( + *prepared.lock().unwrap(), + Some("named-session".to_owned()), + "the prepare step commits the rows of the id its Session is created under" ); assert_eq!( seen.load(Ordering::SeqCst), @@ -83,6 +90,32 @@ async fn create_and_restore_options_apply_their_fields() { ); session.close().await.unwrap(); + let generated = Arc::new(Mutex::new(None::)); + let session = agent + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().prepare({ + let store = store.clone(); + let generated = generated.clone(); + move |id| { + *generated.lock().unwrap() = Some(id.clone()); + let config = SessionConfig::default(); + Box::pin(async move { + store.create_session(&id, &config).await?; + Ok(()) + }) + } + }), + ) + .await + .unwrap(); + assert_eq!( + generated.lock().unwrap().as_deref(), + Some(session.id()), + "a prepared creation without an id is created under a generated one, which the prepare step receives" + ); + session.close().await.unwrap(); + let session = agent .create_session( SessionConfig::default(), diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index c2d78aca9e..0656c89110 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -34,9 +34,12 @@ enum Entry { Building(watch::Receiver>>), Ready(Session), } +/// The host-owned step of a prepared creation: creation hands it the id the +/// Session is created under, and the step commits that id's rows. +type Preparation = Box BoxFuture<'static, Result<()>> + Send>; enum SessionStart { Create, - Prepared(BoxFuture<'static, Result<()>>), + Prepared(Preparation), Restore, } /// How [`Agent::create_session`] creates its Session: the id to create under, @@ -45,25 +48,26 @@ enum SessionStart { #[derive(Default)] pub struct CreateSessionOptions { id: Option, - prepare: Option<(String, BoxFuture<'static, Result<()>>)>, + prepare: Option, extension: Option, } impl CreateSessionOptions { /// Creates the Session under `id` instead of a generated one. A creation - /// that [`prepare`](Self::prepare)s a Session takes its id from there. + /// that also [`prepare`](Self::prepare)s a Session hands the same id to + /// that step. pub fn id(mut self, id: impl Into) -> Self { self.id = Some(id.into()); self } /// Reserves runtime capacity before committing the host-owned directory: - /// `prepare` commits the rows of `id`, and creation loads them once it - /// completes. A prepared creation is created under `id`. - pub fn prepare( - mut self, - id: impl Into, - prepare: BoxFuture<'static, Result<()>>, - ) -> Self { - self.prepare = Some((id.into(), prepare)); + /// `prepare` receives the id the Session is created under, commits that + /// id's rows, and creation loads them once it completes. The id is the + /// [`id`](Self::id) given, or a generated one. + pub fn prepare(mut self, prepare: F) -> Self + where + F: FnOnce(String) -> BoxFuture<'static, Result<()>> + Send + 'static, + { + self.prepare = Some(Box::new(prepare)); self } /// Loads the Session extension `group` ([`AgentBuilder::session_extension`]) @@ -120,12 +124,10 @@ impl Agent { config: SessionConfig, options: CreateSessionOptions, ) -> Result { - let (id, start) = match options.prepare { - Some((id, prepare)) => (id, SessionStart::Prepared(prepare)), - None => ( - options.id.unwrap_or_else(|| Uuid::new_v4().to_string()), - SessionStart::Create, - ), + let id = options.id.unwrap_or_else(|| Uuid::new_v4().to_string()); + let start = match options.prepare { + Some(prepare) => SessionStart::Prepared(prepare), + None => SessionStart::Create, }; self.create(id, config, start, options.extension).await } @@ -187,7 +189,7 @@ impl Agent { SessionInitialization::New } SessionStart::Prepared(prepare) => { - prepare.await?; + prepare(id.clone()).await?; created = true; SessionInitialization::Prepared(assembly.store.branches(&id).await?) } diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index 9bfd32c55d..4ebf32c611 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1471,7 +1471,7 @@ impl AgentIndex { leader: Option<&str>, origin: SessionOrigin, worktree: Option, - ) -> Option<(String, BoxFuture<'static, dim_agent_runtime::Result<()>>)> { + ) -> Option<(String, CreateSessionOptions)> { let store = self.session_store.clone()?; let stored = config.clone(); let agent_id = host.agent_id.clone(); @@ -1492,32 +1492,32 @@ impl AgentIndex { }) })) } - /// A new Session id and the prepare step of its prepared creation: the - /// project of `cwd` is authorized, then `step` writes the Session's rows. - /// Creation, `launch` and a fork share it (S5c §9). - fn prepared( - &self, - cwd: String, - step: impl FnOnce(String) -> BoxFuture<'static, dim_agent_runtime::Result<()>>, - ) -> (String, BoxFuture<'static, dim_agent_runtime::Result<()>>) { + /// A new Session id and the options of its prepared creation: the project + /// of `cwd` is authorized, then `step` writes the Session's rows. Creation, + /// `launch` and a fork share it (S5c §9). + fn prepared(&self, cwd: String, step: F) -> (String, CreateSessionOptions) + where + F: FnOnce(String) -> BoxFuture<'static, dim_agent_runtime::Result<()>> + Send + 'static, + { let id = uuid::Uuid::new_v4().to_string(); - let step = step(id.clone()); let settings = self.settings.clone(); let stopping = self.stopping.clone(); - ( - id, - Box::pin(async move { - if let Some(settings) = settings { - settings - .authorize_project(cwd.into(), &stopping) - .await - .map_err(|error| { - AgentError::fault("project authorization", error.to_string()) - })?; - } - step.await - }), - ) + let options = CreateSessionOptions::default() + .id(id.clone()) + .prepare(move |id: String| { + Box::pin(async move { + if let Some(settings) = settings { + settings + .authorize_project(cwd.into(), &stopping) + .await + .map_err(|error| { + AgentError::fault("project authorization", error.to_string()) + })?; + } + step(id).await + }) + }); + (id, options) } pub(crate) async fn create_with_worktree( @@ -1593,11 +1593,8 @@ impl AgentIndex { .prepare_session(host, &config, version, leader, origin, worktree) .await { - Some((id, prepare)) => { - let creation = host.agent.create_session( - config, - CreateSessionOptions::default().prepare(id.clone(), prepare), - ); + Some((id, options)) => { + let creation = host.agent.create_session(config, options); self.admit(&id, &host.agent_id, version, creation).await } None => { @@ -2035,13 +2032,10 @@ impl AgentIndex { .map_err(|error| AgentError::Storage(format!("the fork configuration: {error}")))?; } let source = source.to_owned(); - let (id, prepare) = self.prepared(config.cwd.clone(), move |fork| { + let (id, options) = self.prepared(config.cwd.clone(), move |fork| { Box::pin(async move { store.fork_session(&source, &fork, at, &record).await }) }); - let creation = usage.host.agent.create_session( - config, - CreateSessionOptions::default().prepare(id.clone(), prepare), - ); + let creation = usage.host.agent.create_session(config, options); let fork = self .admit(&id, &usage.host.agent_id, version, creation) .await?; diff --git a/docs/design/thin-instances.md b/docs/design/thin-instances.md index 0a1ba2d5fa..b0ec0d0e98 100644 --- a/docs/design/thin-instances.md +++ b/docs/design/thin-instances.md @@ -153,7 +153,7 @@ tree shows where their content sits. When `StartupProgress` gives up, or on cancellation, creation shuts the scope's view down. The task that disposed of a creation still running, `rows`, `scope_entries` and `scope_rows` go too. - **Requested extensions.** An extension requested through - `Agent::create_session(config, CreateSessionOptions::extension(group, value))` keeps its + `Agent::create_session(config, CreateSessionOptions::default().extension(group, value))` keeps its contract: the plugins registered for `group` (`AgentBuilder::session_extension_part`) are built from `value` with the Session's `Names` and must be Active before the Session publishes. The Session scope builds and mounts them as its children and hands them to creation as required (step 2). A From d284776948581a68fafe4acd7b1e21e74aa13cdc Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 00:33:12 +0800 Subject: [PATCH 03/23] fix(runtime): validate an explicit Session id before creating An explicit id is rejected unless it is one normal path component, the form Session command-output storage addresses, and the check runs before the prepare step, the first storage write and publication, so a rejected id leaves no Session and no rows. The check moves into the runtime so Session admission and the App Server boundaries share one definition instead of two. --- .../tests/agent_options_flow.rs | 189 +++++++++++++++++- crates/dim-agent-runtime/src/agent.rs | 17 ++ crates/dim-app-server/src/agents.rs | 4 +- crates/dim-app-server/src/protocol.rs | 11 - crates/dim-app-server/src/storage/timeline.rs | 8 +- 5 files changed, 206 insertions(+), 23 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index 2b2920b312..0ef9070e91 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -1,14 +1,19 @@ use dim_agent_capabilities::defaults; use dim_agent_runtime::testing::MinimalHost; use dim_agent_runtime::{ - AgentBuilder, AgentConfig, CreateSessionOptions, MemoryTimelineStore, RestoreSessionOptions, - SessionConfig, TimelineStore, TimelineStoreBinding, + AgentBuilder, AgentConfig, AgentError, BoxFuture, CreateSessionOptions, MemoryTimelineStore, + PublishCallback, QueryPage, QueryResult, QuerySpec, RestoreSessionOptions, Result, + SessionConfig, StoredBranch, StoredEvent, TimelineKey, TimelineReadScope, TimelineStore, + TimelineStoreBinding, TimelineTrace, }; use rutis::host::DynPlugin; use rutis::{Ctx, Plugin}; -use std::sync::{ - Arc, Mutex, - atomic::{AtomicU32, Ordering}, +use std::{ + ops::RangeInclusive, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicU32, Ordering}, + }, }; const GROUP: &str = "options-probe"; @@ -28,10 +33,15 @@ impl Plugin for Probe { } } -fn builder(store: &Arc, seen: Arc) -> AgentBuilder { +fn installed() -> AgentBuilder { let mut builder = AgentBuilder::new(AgentConfig::default()); defaults::mock_hosts(&mut builder); defaults::install(&mut builder); + builder +} + +fn builder(store: &Arc, seen: Arc) -> AgentBuilder { + let mut builder = installed(); builder .timeline_store(TimelineStoreBinding::new(store.clone())) .session_extension_part::(GROUP, "options-probe", move |_, value: &u32| { @@ -43,6 +53,105 @@ fn builder(store: &Arc, seen: Arc) -> AgentBuild builder } +/// A store that records the Sessions a creation commits, so a creation that +/// writes nothing is visible. +#[derive(Default)] +struct Shared { + memory: MemoryTimelineStore, + created: Mutex>, +} +impl TimelineStore for Shared { + fn query<'a>( + &'a self, + scope: &'a TimelineReadScope, + query: &'a QuerySpec, + page: Option<&'a QueryPage>, + ) -> BoxFuture<'a, Result> { + self.memory.query(scope, query, page) + } + fn create_session<'a>( + &'a self, + session_id: &'a str, + config: &'a SessionConfig, + ) -> BoxFuture<'a, Result<()>> { + self.created.lock().unwrap().push(session_id.to_owned()); + self.memory.create_session(session_id, config) + } + fn rollback_session<'a>(&'a self, session_id: &'a str) -> BoxFuture<'a, Result<()>> { + self.memory.rollback_session(session_id) + } + fn release_session<'a>(&'a self, session_id: &'a str) -> BoxFuture<'a, Result<()>> { + self.memory.release_session(session_id) + } + fn session_config<'a>( + &'a self, + session_id: &'a str, + ) -> BoxFuture<'a, Result>> { + self.memory.session_config(session_id) + } + fn branches<'a>(&'a self, session_id: &'a str) -> BoxFuture<'a, Result>> { + self.memory.branches(session_id) + } + fn head<'a>(&'a self, key: &'a TimelineKey) -> BoxFuture<'a, Result> { + self.memory.head(key) + } + fn batch_end<'a>(&'a self, key: &'a TimelineKey, sequence: u64) -> BoxFuture<'a, Result<()>> { + self.memory.batch_end(key, sequence) + } + fn append( + &self, + key: TimelineKey, + events: Vec, + publish: PublishCallback, + ) -> Result<()> { + self.memory.append(key, events, publish) + } + fn read_segments<'a>( + &'a self, + session_id: &'a str, + segments: Vec<(String, RangeInclusive)>, + ) -> BoxFuture<'a, Result>>> { + self.memory.read_segments(session_id, segments) + } + fn trace<'a>( + &'a self, + key: &'a TimelineKey, + sequence: u64, + ) -> BoxFuture<'a, Result>> { + self.memory.trace(key, sequence) + } +} + +/// A host on this store, without the extension probe. +async fn store_host(store: &Arc) -> MinimalHost { + let mut builder = installed(); + builder.timeline_store(TimelineStoreBinding::new(store.clone())); + MinimalHost::start(&builder).await.unwrap() +} + +/// The prepare step of a host that commits the Session's rows in the store, so +/// a creation that reaches it is visible there. +fn preparing( + store: &Arc, + entered: Arc, +) -> impl FnOnce(String) -> BoxFuture<'static, Result<()>> + Send + 'static { + let store = store.clone(); + move |id| { + entered.store(true, Ordering::SeqCst); + let store = store.clone(); + Box::pin(async move { store.create_session(&id, &SessionConfig::default()).await }) + } +} + +/// The error of a rejected creation; a `Session` is not `Debug`, so `unwrap_err` +/// does not apply. +fn rejected(created: Result) -> AgentError { + match created { + Ok(_) => panic!("the creation was accepted"), + Err(error) => error, + } +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn create_and_restore_options_apply_their_fields() { let seen = Arc::new(AtomicU32::new(0)); @@ -159,3 +268,71 @@ async fn create_and_restore_options_apply_their_fields() { session.close().await.unwrap(); agent.close().await.unwrap(); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_explicit_id_is_admitted_only_as_one_path_component() { + let store = Arc::new(Shared::default()); + let host = store_host(&store).await; + let agent = host.agent().clone(); + for id in ["", ".", "..", "../escape", "nested/id", "/absolute"] { + let entered = Arc::new(AtomicBool::new(false)); + let error = rejected( + agent + .create_session( + SessionConfig::default(), + CreateSessionOptions::default() + .id(id) + .prepare(preparing(&store, entered.clone())), + ) + .await, + ); + assert!( + matches!(&error, AgentError::InvalidInput(message) if message == &format!("invalid Session id {id}")), + "{id:?} is not one path component: {error}" + ); + assert!( + !entered.load(Ordering::SeqCst), + "{id:?}: a rejected id reaches no prepare step" + ); + assert!( + agent.get_session(id).is_none(), + "{id:?}: a rejected id publishes no Session" + ); + } + let error = rejected( + agent + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().id("nested/plain"), + ) + .await, + ); + assert!( + matches!(&error, AgentError::InvalidInput(_)), + "a rejected id without a prepare step: {error}" + ); + assert!( + store.created.lock().unwrap().is_empty(), + "a rejected id writes no rows: {:?}", + store.created.lock().unwrap() + ); + assert!( + agent.sessions().is_empty(), + "a rejected id publishes no Session" + ); + + let session = agent + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().id("explicit-session"), + ) + .await + .unwrap(); + assert_eq!( + session.id(), + "explicit-session", + "a legal explicit id is preserved" + ); + session.close().await.unwrap(); + host.close().await.unwrap(); +} diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 0656c89110..c99df47ffa 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -55,6 +55,11 @@ impl CreateSessionOptions { /// Creates the Session under `id` instead of a generated one. A creation /// that also [`prepare`](Self::prepare)s a Session hands the same id to /// that step. + /// + /// The id must be one normal path component, which is what Session + /// command-output storage addresses ([`check_session_id`]); + /// [`Agent::create_session`] rejects any other id before it prepares, + /// writes or publishes. pub fn id(mut self, id: impl Into) -> Self { self.id = Some(id.into()); self @@ -97,6 +102,17 @@ impl RestoreSessionOptions { self } } +/// Requires the single path component that Session command-output storage +/// addresses: an absolute path, a current or parent directory, and a path of +/// several components are rejected with [`AgentError::InvalidInput`]. +pub fn check_session_id(id: &str) -> Result<()> { + if !matches!(std::path::Path::new(id).components().collect::>()[..], + [std::path::Component::Normal(name)] if name == id) + { + return Err(AgentError::InvalidInput(format!("invalid Session id {id}"))); + } + Ok(()) +} impl Agent { pub(crate) fn new(builder: AgentBuilder, assembly: Assembly, placement: Placement) -> Self { Self(Arc::new(AgentInner { @@ -125,6 +141,7 @@ impl Agent { options: CreateSessionOptions, ) -> Result { let id = options.id.unwrap_or_else(|| Uuid::new_v4().to_string()); + check_session_id(&id)?; let start = match options.prepare { Some(prepare) => SessionStart::Prepared(prepare), None => SessionStart::Create, diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index 4ebf32c611..67250c2823 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1657,7 +1657,7 @@ impl AgentIndex { .activity .take_hold() .ok_or_else(|| AgentError::Reloading("process admission".into()))?; - crate::protocol::check_session_id(id)?; + dim_agent_runtime::check_session_id(id)?; let slot = self.slot(id); let gate = slot.gate.lock().await; let removed = self.remove_locked(id, &slot).await?; @@ -1679,7 +1679,7 @@ impl AgentIndex { &self, id: &str, ) -> dim_agent_runtime::Result { - crate::protocol::check_session_id(id)?; + dim_agent_runtime::check_session_id(id)?; let slot = self.slot(id); let gate = slot.gate.lock().await; // One match yields both the outcome and what there is to announce, so diff --git a/crates/dim-app-server/src/protocol.rs b/crates/dim-app-server/src/protocol.rs index 3c642759df..b37e7d5166 100644 --- a/crates/dim-app-server/src/protocol.rs +++ b/crates/dim-app-server/src/protocol.rs @@ -682,17 +682,6 @@ pub struct CatalogCancel { pub struct SessionId { pub session_id: String, } -/// Requires the single path component used by Session command-output storage. -pub(crate) fn check_session_id(id: &str) -> dim_agent_runtime::Result<()> { - if !matches!(std::path::Path::new(id).components().collect::>()[..], - [std::path::Component::Normal(name)] if name == id) - { - return Err(dim_agent_runtime::AgentError::InvalidInput(format!( - "invalid Session id {id}" - ))); - } - Ok(()) -} /// `session.delete`: with `requireInactive`, a Session in use refuses the /// delete with `session_active` instead of being closed and removed. diff --git a/crates/dim-app-server/src/storage/timeline.rs b/crates/dim-app-server/src/storage/timeline.rs index dee6c94f74..33028aea7a 100644 --- a/crates/dim-app-server/src/storage/timeline.rs +++ b/crates/dim-app-server/src/storage/timeline.rs @@ -1622,7 +1622,7 @@ impl SessionStore { /// Rejects an `id` that is not one path component (D3). Returns whether /// this database had rows of the id. pub async fn delete_session(&self, id: &str) -> Result { - crate::protocol::check_session_id(id)?; + dim_agent_runtime::check_session_id(id)?; let _ownership = self.ownership.lock().await; let stored = self.has_records(id).await?; if stored { @@ -1668,8 +1668,8 @@ impl SessionStore { at: u64, config: &str, ) -> Result<()> { - crate::protocol::check_session_id(source)?; - crate::protocol::check_session_id(fork)?; + dim_agent_runtime::check_session_id(source)?; + dim_agent_runtime::check_session_id(fork)?; let _ownership = self.ownership.lock().await; if let Some(cwd) = config_cwd(config) { self.reject_deletion(&cwd).await?; @@ -1695,7 +1695,7 @@ impl SessionStore { origin: SessionOrigin, worktree: Option, ) -> Result<()> { - crate::protocol::check_session_id(session_id)?; + dim_agent_runtime::check_session_id(session_id)?; let session = session_id.to_owned(); let config = config.clone(); let agent = agent_id.to_owned(); From 743ae6b20db73f9c5de0ee83434c1b505ed69e7f Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 00:34:14 +0800 Subject: [PATCH 04/23] fix(runtime): keep the existing Session's state when a duplicate is rejected A creation that fails now undoes only what it committed: a rejected duplicate no longer releases admission state or clears a recorded write failure that belongs to the Session another Agent already created under that id. Creation that fails before committing rows leaves the store untouched, and a restore, which loads an existing Session, releases the load it admitted. --- .../tests/agent_options_flow.rs | 74 ++++++++++++++++++- crates/dim-agent-runtime/src/agent.rs | 21 ++++-- 2 files changed, 85 insertions(+), 10 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index 0ef9070e91..1abab809c7 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -9,6 +9,7 @@ use dim_agent_runtime::{ use rutis::host::DynPlugin; use rutis::{Ctx, Plugin}; use std::{ + collections::BTreeMap, ops::RangeInclusive, sync::{ Arc, Mutex, @@ -53,12 +54,15 @@ fn builder(store: &Arc, seen: Arc) -> AgentBuild builder } -/// A store that records the Sessions a creation commits, so a creation that -/// writes nothing is visible. +/// A store two Agents can share. `release_session` drops the admission state +/// the product store keys by Session id, so a creation that releases a Session +/// it never admitted is visible as lost state. #[derive(Default)] struct Shared { memory: MemoryTimelineStore, created: Mutex>, + released: Mutex>, + failures: Mutex>, } impl TimelineStore for Shared { fn query<'a>( @@ -81,7 +85,11 @@ impl TimelineStore for Shared { self.memory.rollback_session(session_id) } fn release_session<'a>(&'a self, session_id: &'a str) -> BoxFuture<'a, Result<()>> { - self.memory.release_session(session_id) + Box::pin(async move { + self.released.lock().unwrap().push(session_id.to_owned()); + self.failures.lock().unwrap().remove(session_id); + self.memory.release_session(session_id).await + }) } fn session_config<'a>( &'a self, @@ -336,3 +344,63 @@ async fn an_explicit_id_is_admitted_only_as_one_path_component() { session.close().await.unwrap(); host.close().await.unwrap(); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_rejected_duplicate_keeps_the_existing_sessions_state() { + let store = Arc::new(Shared::default()); + let first = store_host(&store).await; + let second = store_host(&store).await; + let session = first + .agent() + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().id("shared"), + ) + .await + .unwrap(); + store + .failures + .lock() + .unwrap() + .insert("shared".into(), "disk full".into()); + + let error = rejected( + second + .agent() + .create_session( + SessionConfig::default(), + CreateSessionOptions::default().id("shared"), + ) + .await, + ); + assert!( + matches!(&error, AgentError::Storage(message) if message == "session shared already exists"), + "a duplicate id is a rejected creation: {error}" + ); + assert_eq!( + store + .failures + .lock() + .unwrap() + .get("shared") + .map(String::as_str), + Some("disk full"), + "the rejected duplicate keeps the existing Session's recorded write failure" + ); + assert!( + store.released.lock().unwrap().is_empty(), + "the rejected duplicate releases no Session it never admitted: {:?}", + store.released.lock().unwrap() + ); + assert!( + first + .agent() + .get_session("shared") + .is_some_and(|session| session.id() == "shared"), + "the first Agent's Session stays loaded" + ); + + session.close().await.unwrap(); + first.close().await.unwrap(); + second.close().await.unwrap(); +} diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index c99df47ffa..60cb564ec4 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -42,6 +42,12 @@ enum SessionStart { Prepared(Preparation), Restore, } +/// What a creation that fails undoes in the store. +enum Cleanup { + Nothing, + Rollback, + Release, +} /// How [`Agent::create_session`] creates its Session: the id to create under, /// the host-owned directory to prepare before publication, and the Session /// extension to load. @@ -196,21 +202,22 @@ impl Agent { } let owner = self.clone(); tokio::spawn(async move { - let mut created = false; + let mut cleanup = Cleanup::Nothing; let mut result = async { let placement = owner.0.placement.clone(); let initialization = match start { SessionStart::Create => { assembly.store.create_session(&id, &config).await?; - created = true; + cleanup = Cleanup::Rollback; SessionInitialization::New } SessionStart::Prepared(prepare) => { prepare(id.clone()).await?; - created = true; + cleanup = Cleanup::Rollback; SessionInitialization::Prepared(assembly.store.branches(&id).await?) } SessionStart::Restore => { + cleanup = Cleanup::Release; SessionInitialization::Restore(assembly.store.branches(&id).await?) } }; @@ -251,10 +258,10 @@ impl Agent { }; } if let Err(failure) = result { - let cleanup = if created { - owner.0.assembly.store.rollback_session(&id).await - } else { - owner.0.assembly.store.release_session(&id).await + let cleanup = match cleanup { + Cleanup::Nothing => Ok(()), + Cleanup::Rollback => owner.0.assembly.store.rollback_session(&id).await, + Cleanup::Release => owner.0.assembly.store.release_session(&id).await, }; result = Err(match cleanup { Ok(()) => failure, From 2bbc7cdc6d6f959f730288ca00fe802c0f5bd9e4 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 01:17:53 +0800 Subject: [PATCH 05/23] test(runtime): compare the existing stored rows across a rejected duplicate The duplicate-creation regression test now reads the existing Session's stored configuration and branch directory before the rejected creation, and asserts they are unchanged afterwards, so a rollback of those rows fails it. --- .../tests/agent_options_flow.rs | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index 1abab809c7..84a69a35bd 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -151,6 +151,23 @@ fn preparing( } } +/// The rows the store keeps for one Session: its configuration and its branch +/// directory. `None` once neither is stored. +async fn stored_rows(store: &Shared, id: &str) -> Option<(serde_json::Value, serde_json::Value)> { + let config = store + .session_config(id) + .await + .expect("the stored configuration is readable")?; + let branches = store + .branches(id) + .await + .expect("the stored branch directory is readable"); + Some(( + serde_json::to_value(config).expect("the stored configuration serializes"), + serde_json::to_value(branches).expect("the stored branch directory serializes"), + )) +} + /// The error of a rejected creation; a `Session` is not `Debug`, so `unwrap_err` /// does not apply. fn rejected(created: Result) -> AgentError { @@ -363,6 +380,7 @@ async fn a_rejected_duplicate_keeps_the_existing_sessions_state() { .lock() .unwrap() .insert("shared".into(), "disk full".into()); + let rows = stored_rows(&store, "shared").await; let error = rejected( second @@ -392,6 +410,11 @@ async fn a_rejected_duplicate_keeps_the_existing_sessions_state() { "the rejected duplicate releases no Session it never admitted: {:?}", store.released.lock().unwrap() ); + assert_eq!( + stored_rows(&store, "shared").await, + rows, + "the rejected duplicate leaves the existing Session's stored rows as they were" + ); assert!( first .agent() From 570cc8fa687e2375a94c1ed5f635a1799c5d2978 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 02:43:53 +0800 Subject: [PATCH 06/23] fix(runtime): book a Session id's output name before creating An explicit Session id is one path component, but nothing proved the filesystem could back it with a directory: a name over the component limit, one a case-insensitive or normalization-insensitive volume equates with another id, or one another Session already uses failed only when command output was first written, or silently shared that output. Agent::create_session now books the id below the host's command-output root at /.session-ids/ with an exclusive create_dir before its prepare step, storage write or publication, so an id this filesystem cannot back, or one already booked, is refused with InvalidInput and leaves no booking, row or published Session. A creation that fails releases its booking with its rows. SessionStore's delete removes the booking with the output directory, under the same rows-here rule, so a delete of an id this database does not store cannot free another database's name. WorkspaceToolsConfig::output_root is the root the Agent is given; the command-output directory itself stays lazy, as ADR 013 D4 expects. The design note and its Chinese copy record the booking, and two flow tests cover an id this filesystem cannot hold and two ids it cannot tell apart. --- .../src/workspace_tools/mod.rs | 3 + .../tests/agent_options_flow.rs | 149 +++++++++++++++++- crates/dim-agent-runtime/src/agent.rs | 75 ++++++++- crates/dim-agent-runtime/src/assembly.rs | 17 ++ crates/dim-app-server/src/storage/files.rs | 33 ++-- docs/adr/013-command-output-ownership.md | 7 + .../appserver/session-deletion-and-fork.md | 19 ++- .../appserver/session-deletion-and-fork.md | 13 +- 8 files changed, 284 insertions(+), 32 deletions(-) diff --git a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs index 8ae7975162..814aa8195c 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs @@ -53,6 +53,8 @@ const SEARCH_METHOD: &str = "session.files.search"; #[derive(Debug, Clone)] pub struct WorkspaceToolsConfig { /// Absolute root of command output files, `//`. + /// [`install`] also gives it to the Agent as the root below which a + /// Session id is booked before it prepares or writes. pub output_root: PathBuf, /// The root boundary of a session's file tools, when a host configures /// one. The product passes `None`: the tools keep their unbounded @@ -69,6 +71,7 @@ pub use files::FileToolBoundary; /// coordinator, one lock domain for every Session it serves, across their /// generations and its own, and hands it to each Session's part. pub fn install(builder: &mut AgentBuilder, config: WorkspaceToolsConfig) { + builder.session_output_root(config.output_root.clone()); let coordinator = Arc::::default(); builder.plugin(move |names| { Ok(Box::new(WorkspaceToolsOwner::new( diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index 84a69a35bd..c5a6561b5f 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -1,4 +1,8 @@ -use dim_agent_capabilities::defaults; +use dim_agent_capabilities::{ + defaults, + host_platform::{HostPlatform, ShellStatus}, + workspace_tools::{self, WorkspaceToolsConfig}, +}; use dim_agent_runtime::testing::MinimalHost; use dim_agent_runtime::{ AgentBuilder, AgentConfig, AgentError, BoxFuture, CreateSessionOptions, MemoryTimelineStore, @@ -11,6 +15,7 @@ use rutis::{Ctx, Plugin}; use std::{ collections::BTreeMap, ops::RangeInclusive, + path::Path, sync::{ Arc, Mutex, atomic::{AtomicBool, AtomicU32, Ordering}, @@ -427,3 +432,145 @@ async fn a_rejected_duplicate_keeps_the_existing_sessions_state() { first.close().await.unwrap(); second.close().await.unwrap(); } + +/// A host whose WorkspaceTools output root is `root`: the product's wiring of +/// the id admission. No tool runs, so the platform needs no exec shell. +async fn output_host(store: &Arc, root: &Path) -> MinimalHost { + let mut builder = AgentBuilder::new(AgentConfig::default()); + defaults::mock_model_hosts(&mut builder); + defaults::install(&mut builder); + builder.timeline_store(TimelineStoreBinding::new(store.clone())); + workspace_tools::install( + &mut builder, + WorkspaceToolsConfig { + boundary: None, + output_root: root.to_owned(), + }, + ); + let platform = HostPlatform::current(ShellStatus::Unavailable { + code: "test", + reason: "the id admission runs no shell".into(), + }) + .expect("the process platform"); + MinimalHost::start_with(&builder, move |root, _| { + root.provide_as::(Arc::new(platform))?; + Ok(()) + }) + .await + .expect("the output host starts") +} + +/// A Session that declares one tool the output host serves and runs none. +fn output_session() -> SessionConfig { + SessionConfig { + tools: Some(vec!["read".into()]), + ..Default::default() + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_id_without_a_usable_output_directory_is_rejected_before_preparation() { + let root = std::env::temp_dir().join(format!("dim-output-{}", uuid::Uuid::new_v4())); + let store = Arc::new(Shared::default()); + let host = output_host(&store, &root).await; + let agent = host.agent().clone(); + // One component this filesystem cannot hold as a directory name. + let id = "s".repeat(300); + let entered = Arc::new(AtomicBool::new(false)); + let error = rejected( + agent + .create_session( + output_session(), + CreateSessionOptions::default() + .id(id.clone()) + .prepare(preparing(&store, entered.clone())), + ) + .await, + ); + assert!( + matches!(&error, AgentError::InvalidInput(message) if message.starts_with(&format!("Session id {id} has no usable output directory"))), + "a name this filesystem cannot hold is rejected: {error}" + ); + assert!( + !entered.load(Ordering::SeqCst), + "a rejected id reaches no prepare step" + ); + assert!( + store.created.lock().unwrap().is_empty(), + "a rejected id writes no rows: {:?}", + store.created.lock().unwrap() + ); + assert!( + agent.get_session(&id).is_none(), + "a rejected id publishes no Session" + ); + host.close().await.unwrap(); + std::fs::remove_dir_all(&root).unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn ids_the_filesystem_cannot_tell_apart_do_not_share_an_output_directory() { + let root = std::env::temp_dir().join(format!("dim-output-{}", uuid::Uuid::new_v4())); + let store = Arc::new(Shared::default()); + let host = output_host(&store, &root).await; + let agent = host.agent().clone(); + let first = agent + .create_session( + output_session(), + CreateSessionOptions::default().id("Named-Session"), + ) + .await + .unwrap(); + assert_eq!( + first.id(), + "Named-Session", + "an accepted id keeps its value" + ); + let entered = Arc::new(AtomicBool::new(false)); + match agent + .create_session( + output_session(), + CreateSessionOptions::default() + .id("named-session") + .prepare(preparing(&store, entered.clone())), + ) + .await + { + Ok(second) => { + assert_ne!(second.id(), first.id()); + std::fs::create_dir_all(root.join(first.id())).unwrap(); + assert!( + !root.join(second.id()).exists(), + "ids this filesystem can tell apart keep distinct output directories" + ); + second.close().await.unwrap(); + } + Err(error) => { + assert!( + matches!(&error, AgentError::InvalidInput(message) if message == "session named-session is already in use"), + "an id this filesystem cannot tell apart from an accepted one is refused: {error}" + ); + assert!( + !entered.load(Ordering::SeqCst), + "a refused id reaches no prepare step" + ); + assert!( + !store + .created + .lock() + .unwrap() + .iter() + .any(|id| id == "named-session"), + "a refused id writes no rows: {:?}", + store.created.lock().unwrap() + ); + assert!( + agent.get_session("named-session").is_none(), + "a refused id publishes no Session" + ); + } + } + first.close().await.unwrap(); + host.close().await.unwrap(); + std::fs::remove_dir_all(&root).unwrap(); +} diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 60cb564ec4..83a6cb6fbf 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -11,6 +11,7 @@ use dim_agent_types::{AgentEvent, BranchSource, InputMessageData, InputMode}; use rutis::host::{CtxHost, FiberView}; use std::{ collections::BTreeMap, + path::Path, sync::{Arc, Mutex, Weak}, }; use tokio::sync::watch; @@ -42,9 +43,14 @@ enum SessionStart { Prepared(Preparation), Restore, } -/// What a creation that fails undoes in the store. +/// What a creation that fails undoes: its store rows and the output name it +/// booked. enum Cleanup { + /// Nothing was written: no rows and no booked name. Nothing, + /// The id's output name is booked and no rows were written. + Booked, + /// The id's rows were written; its output name is booked. Rollback, Release, } @@ -65,7 +71,8 @@ impl CreateSessionOptions { /// The id must be one normal path component, which is what Session /// command-output storage addresses ([`check_session_id`]); /// [`Agent::create_session`] rejects any other id before it prepares, - /// writes or publishes. + /// writes or publishes, as it rejects an id the host's output root cannot + /// back with a directory ([`AgentBuilder::session_output_root`]). pub fn id(mut self, id: impl Into) -> Self { self.id = Some(id.into()); self @@ -111,6 +118,10 @@ impl RestoreSessionOptions { /// Requires the single path component that Session command-output storage /// addresses: an absolute path, a current or parent directory, and a path of /// several components are rejected with [`AgentError::InvalidInput`]. +/// +/// A [`Agent::create_session`] checks this and also books that component below +/// the host's output root, so the id it accepts is one this filesystem can +/// back with a directory, and no other Session holds the same directory. pub fn check_session_id(id: &str) -> Result<()> { if !matches!(std::path::Path::new(id).components().collect::>()[..], [std::path::Component::Normal(name)] if name == id) @@ -119,13 +130,56 @@ pub fn check_session_id(id: &str) -> Result<()> { } Ok(()) } +/// The directory below a Session output root that books each id a creation +/// accepts: `/.session-ids/`. +pub const SESSION_ID_BOOKINGS: &str = ".session-ids"; +/// Books `id`'s name below the Session output `root`, when the host configured +/// one, at `/.session-ids/`. The entry sits in the root the Session's +/// command output addresses and is the id itself, so booking proves this +/// filesystem can back the id with a directory there, and that no other +/// Session holds a name it cannot tell apart from this one. The caller owns +/// the booking until it removes it ([`release_booking`]). +async fn book_session_id(root: Option<&Path>, id: &str) -> Result<()> { + let Some(root) = root else { + return Ok(()); + }; + let bookings = root.join(SESSION_ID_BOOKINGS); + if let Err(error) = tokio::fs::create_dir_all(&bookings).await { + return Err(AgentError::InvalidInput(format!( + "Session id {id} has no usable output directory: {error}" + ))); + } + match tokio::fs::create_dir(bookings.join(id)).await { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Err( + AgentError::InvalidInput(format!("session {id} is already in use")), + ), + Err(error) => Err(AgentError::InvalidInput(format!( + "Session id {id} has no usable output directory: {error}" + ))), + } +} +/// Removes a booking ([`book_session_id`]); an absent one counts as removed, +/// so a cleanup that follows a partial failure is safe. +async fn release_booking(root: Option<&Path>, id: &str) -> Result<()> { + let Some(root) = root else { + return Ok(()); + }; + match tokio::fs::remove_dir(root.join(SESSION_ID_BOOKINGS).join(id)).await { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(AgentError::Storage(format!( + "the output booking of session {id}: {error}" + ))), + } +} impl Agent { pub(crate) fn new(builder: AgentBuilder, assembly: Assembly, placement: Placement) -> Self { Self(Arc::new(AgentInner { builder, + assembly, placement, handle: std::sync::OnceLock::new(), - assembly, entries: Mutex::new(BTreeMap::new()), closing: CancellationToken::new(), close: CloseOnce::default(), @@ -205,13 +259,18 @@ impl Agent { let mut cleanup = Cleanup::Nothing; let mut result = async { let placement = owner.0.placement.clone(); + let output_root = owner.0.builder.output_root(); let initialization = match start { SessionStart::Create => { + book_session_id(output_root, &id).await?; + cleanup = Cleanup::Booked; assembly.store.create_session(&id, &config).await?; cleanup = Cleanup::Rollback; SessionInitialization::New } SessionStart::Prepared(prepare) => { + book_session_id(output_root, &id).await?; + cleanup = Cleanup::Booked; prepare(id.clone()).await?; cleanup = Cleanup::Rollback; SessionInitialization::Prepared(assembly.store.branches(&id).await?) @@ -258,9 +317,17 @@ impl Agent { }; } if let Err(failure) = result { + let output_root = owner.0.builder.output_root(); let cleanup = match cleanup { Cleanup::Nothing => Ok(()), - Cleanup::Rollback => owner.0.assembly.store.rollback_session(&id).await, + Cleanup::Booked => release_booking(output_root, &id).await, + Cleanup::Rollback => owner + .0 + .assembly + .store + .rollback_session(&id) + .await + .and(release_booking(output_root, &id).await), Cleanup::Release => owner.0.assembly.store.release_session(&id).await, }; result = Err(match cleanup { diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index b0df3a0f7e..c3c9bb6a59 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -273,6 +273,9 @@ pub(crate) struct Assembly { pub config: AgentConfig, /// Maximum inactivity interval while opening a Session or branch. pub startup_timeout: Duration, + /// The root of each Session's command-output directory, when the host + /// configures one (`/`). + session_output_root: Option, pub store: Arc, pub ephemeral_store: Option>, /// Shutdowns of instances whose creation was abandoned before the @@ -351,6 +354,7 @@ impl AgentBuilder { assembly: Assembly { config, startup_timeout: Duration::from_secs(10), + session_output_root: None, store: TimelineStoreBinding::new(Arc::new(MemoryTimelineStore::default())), ephemeral_store: None, abandoned: tokio_util::task::TaskTracker::new(), @@ -381,6 +385,19 @@ impl AgentBuilder { self.assembly.startup_timeout = timeout; self } + /// The root of each Session's command-output directory, `/`: + /// [`Agent::create_session`] books the id's name there before it prepares, + /// writes or publishes, so an id this filesystem cannot back with a + /// directory, or one another Session already holds, is rejected before any + /// of those steps ([`check_session_id`]). + pub fn session_output_root(&mut self, root: impl Into) -> &mut Self { + self.assembly.session_output_root = Some(root.into()); + self + } + /// The configured command-output root, if the host configured one. + pub(crate) fn output_root(&self) -> Option<&std::path::Path> { + self.assembly.session_output_root.as_deref() + } /// The assembly's service names: hosts register theirs before adding /// parts that depend on them, and their loader uses this catalog. pub fn catalog(&self) -> &rutis_loader::ServiceCatalog { diff --git a/crates/dim-app-server/src/storage/files.rs b/crates/dim-app-server/src/storage/files.rs index 748655492f..ba5662882c 100644 --- a/crates/dim-app-server/src/storage/files.rs +++ b/crates/dim-app-server/src/storage/files.rs @@ -300,32 +300,35 @@ impl SessionFiles { } /// S5c's delete step: removes every output directory the Session needs - /// (ADR 013 D4): its own `/command-output/` - /// and the directory of every path it has a row for, except one another - /// Session of this database still names a path under. An absent directory - /// counts as removed. Each removal is durable before the caller commits - /// the row deletion. Fails without the node's FileStorage, without - /// HostPlatform for a shell directory, or with `Locked` or - /// `DirectoryNotEmpty` while a writer outside the closed Session holds - /// an entry; the delete is then retried. + /// (ADR 013 D4): its own `/command-output/`, + /// the booking a creation made for its id + /// (`/command-output/.session-ids/`), and the + /// directory of every path it has a row for, except one another Session of + /// this database still names a path under. An absent directory counts as + /// removed. Each removal is durable before the caller commits the row + /// deletion. Fails without the node's FileStorage, without HostPlatform for + /// a shell directory, or with `Locked` or `DirectoryNotEmpty` while a writer + /// outside the closed Session holds an entry; the delete is then retried. pub(super) async fn remove_output(&self, session_id: &str) -> dim_agent_runtime::Result<()> { let session = session_id.to_owned(); - let own = self + let output = self .0 .db .path .parent() - .map(|directory| { - directory - .join(super::COMMAND_OUTPUT_DIRECTORY) - .join(session_id) - }) .ok_or_else(|| error("the native store path has no directory"))?; + let own = output + .join(super::COMMAND_OUTPUT_DIRECTORY) + .join(session_id); + let booking = output + .join(super::COMMAND_OUTPUT_DIRECTORY) + .join(dim_agent_runtime::SESSION_ID_BOOKINGS) + .join(session_id); let candidates = self .0 .db .run_read(move |connection| { - let mut candidates = BTreeSet::from([own]); + let mut candidates = BTreeSet::from([own, booking]); let mut query = connection .prepare("SELECT DISTINCT path FROM session_output_owners WHERE session_id = ?1") .map_err(error)?; diff --git a/docs/adr/013-command-output-ownership.md b/docs/adr/013-command-output-ownership.md index 672929b585..ba162c85de 100644 --- a/docs/adr/013-command-output-ownership.md +++ b/docs/adr/013-command-output-ownership.md @@ -70,6 +70,13 @@ directory; when F is deleted, F's copied rows name S's directory, so F's delete directory shared with another database is that database's responsibility; this guard is scoped to this database and the cross-database case is accepted. +A creation books its id's name before it prepares or writes, at +`/.session-ids/`: one directory named by the id itself, created exclusively, so a +name this filesystem cannot back with a directory and a name that resolves to another Session's +directory are both refused before anything is written. A booking holds no output and has no row; +the deleting session's booking is a candidate under the same rows-here rule as its own output +directory, and a failed creation's own cleanup removes it. + The session-files owner supplies the paths and the last-owner answer; HostPlatform removes the `.dim/exec` directory it owns and makes the removal durable (the parent is synced) before the row commit. HostPlatform does not read ownership rows. Keeping the removal before the row commit diff --git a/docs/design/appserver/session-deletion-and-fork.md b/docs/design/appserver/session-deletion-and-fork.md index 87c4f73a13..35430e97ea 100644 --- a/docs/design/appserver/session-deletion-and-fork.md +++ b/docs/design/appserver/session-deletion-and-fork.md @@ -64,7 +64,10 @@ or the Session facade. Rpc checks the params and the Session's protocol version and calls Agents. Agents owns the Session lifecycle: the admission gate `acquire` already holds while it restores a Session, `Session::close`, and prepared creation -(`Agent::create_session` with `CreateSessionOptions::prepare`). SessionStore owns the rows and the files under the database directory. Its new steps +(`Agent::create_session` with `CreateSessionOptions::prepare`). A creation books its new id's output name first — +`/.session-ids/`, one directory named by the id in the root its command output addresses — before its +prepare step writes the rows: an id this filesystem cannot back with a directory, or one another Session already +books, is refused before anything prepares, writes or publishes. SessionStore owns the rows and the files under the database directory. Its new steps are Rust methods over the native store, not services: only Agents calls them. ## 3. Deletion @@ -127,7 +130,8 @@ are Rust methods over the native store, not services: only Agents calls them. write are removed with the rest. From the close on, S's slot is closed: S does not load again in this process, whether or not its rows go (step 6). 3. **Command output.** SessionStore removes the Session's output directories before any row changes - (ADR 013 D4): its own `/command-output//`, and the directory of every + (ADR 013 D4): its own `/command-output//`, the booking a creation made for + the id (`/command-output/.session-ids//`), and the directory of every path it has a row for, so inherited `command-output//` and `.dim/exec///` directories a fork copied are covered. A directory is removed only if no row of another Session in this database names a path under it. SessionStore @@ -174,6 +178,7 @@ are Rust methods over the native store, not services: only Agents calls them. | Output ownership | Native store, `session_output_owners` rows (v29, [ADR 013](../../adr/013-command-output-ownership.md) D1) | Step 4, same transaction | | Worktree usage associations | Native store, `session_worktrees` rows ([worktree access §4](../worktree-access.md#4-持久使用关联与清理边界)) | Step 4, same transaction; directory records and worktree files remain | | Exec output, offloaded `read` results and persistent shell logs | `/command-output//` and every directory named by S's output rows | Step 3. A directory another Session in this database still names is kept | +| A creation's booking of the id | `/command-output/.session-ids//` | Step 3. It holds no output and has no row; a creation that fails removes its own before this step | | Loaded instance, leases, subscriptions, in-flight uses | Process memory | Step 2 | | Protocol version, admission slot, unavailable-Session entry | Agents, in memory | Step 6 | | Collaboration relations that name S, the member Sessions S leads and the Agents S owns | Durable: `agent_sessions.leader_session_id` and `agents.owner_session_id` ([Collaboration §6](../plugins/Collaboration.md#6-delegation-ownership-and-lifetime)); Collaboration's relations are rebuilt from them | Agents deletes a leader with its Team: each member's own delete, in which SessionStore removes that Session's rows, then the Agent records Agents owns, then S. Collaboration drops a relation when it observes a member's close ([collaboration.rs](../../../crates/dim-app-server/src/collaboration.rs) `session_ended`) or the delete of an unloaded member, and rebuilds the rest when it loads ([idle unload §7](idle-unload.md#7-races-and-interactions)) | @@ -238,7 +243,8 @@ gone. | During the sweep | S5a's states | — | [Session files §6](session-files.md#6-deletion-crash-recovery-and-serialization) | **Why the directory goes before the commit.** The Session's own `command-output//` directory has no row of its -own (only the files in it may). Once the rows are gone, an orphaned directory could only be found by listing +own (only the files in it may), and neither has its booking under `.session-ids/`. Once the rows are gone, an orphaned +directory could only be found by listing `command-output/`, and that directory is shared by every database in the database directory (two `--database` files in one directory), so a listing cannot tell a deleted Session's directory from another store's. Removing it first means no committed delete ever leaves one behind. A directory another Session in this database still names is kept @@ -249,9 +255,10 @@ commit, made with `synchronous=FULL`, stays. `remove` now syncs the parent befor gap; HostPlatform syncs the parent of a removed `.dim/exec` directory the same way. **Only an id with rows here.** For the same reason a delete removes the directory only while its own database has -rows of the id. Two daemons on `a.sqlite` and `b.sqlite` in one directory share `command-output/`; a +rows of the id, and with them the id's booking. Two daemons on `a.sqlite` and `b.sqlite` in one directory share `command-output/`; a `session.delete {S_b}` sent to the first, for example by a CLI given the wrong `--database`, replies `{deleted: false}` and must not -remove the output of S_b, which is alive in the second. The check costs no convergence: the directory goes before the +remove the output of S_b, which is alive in the second, nor its booking, which keeps a second creation of the same +name from taking the same directory. The check costs no convergence: the directory goes before the rows, so a database with no rows of S has no directory of S left to remove, and Agents' admission gate keeps two deletes of one id from interleaving. A retry after a commit therefore removes nothing, as it needs nothing removed. @@ -555,7 +562,7 @@ delete against loading. | The delete's close during the fork's cut check | The check fails `session_closed` | | Put against delete or fork | Session files §6 | | Two deletes | The second waits for the gate, then finds no rows: `{deleted: false}` | -| Delete of a Session still building: a `session.create`, a member's creation or a fork whose rows are committed and listed | The creation holds the new id's gate from before its rows commit until the Session is published and its protocol version recorded (D6). The delete waits, then closes the published Session and removes its rows. A creation that fails rolls its rows back, and the delete finds nothing | +| Delete of a Session still building: a `session.create`, a member's creation or a fork whose rows are committed and listed | The creation books the new id's output name before its prepare step and holds the id's gate from before its rows commit until the Session is published and its protocol version recorded (D6). The delete waits, then closes the published Session and removes its rows and its booking. A creation that fails rolls its rows back and releases its booking, and the delete finds nothing | | Delete against attach, submit or a Session method | They wait for the gate, then fail `session_closed`; requests that already hold a use end with the close | | Delete against the Session's own appends | The close settles them; the row transaction follows every queued append on the Timeline writer | | Fork against appends to the source | Rows through `at` never change, and the fork copies no row after them: child directories come without events | diff --git a/docs/zh/design/appserver/session-deletion-and-fork.md b/docs/zh/design/appserver/session-deletion-and-fork.md index d6c657e7c3..a2482acd07 100644 --- a/docs/zh/design/appserver/session-deletion-and-fork.md +++ b/docs/zh/design/appserver/session-deletion-and-fork.md @@ -12,7 +12,7 @@ 客户端用 `session.delete` 删除 Session,用 `session.fork` 分叉 Session。两者都是协议 v3 的 Rpc 内建方法,调用 Agents;Agents 负责加载、关闭和创建 Session,SessionStore 执行行与文件的步骤。 -- **删除。** Agents 不再加载该 Session;若它已加载,就关闭它,让各能力结算在途工作并释放所持资源。随后 SessionStore 移除该 Session 的输出目录:它自己的 `command-output//`,以及它每一行路径所在的目录;另一个 Session 仍在该目录下有行时保留(ADR 013 D4)。然后在一个事务内删除使 Session 可见的行(Session 文件和输出所有权行、授权、标题、目录、owner、Session 与分支),再按有界事务删除它的 Timeline 行。失去最后一个所有者的文件由 S5a 的清扫移除。删除不存在的 Session 也成功。 +- **删除。** Agents 不再加载该 Session;若它已加载,就关闭它,让各能力结算在途工作并释放所持资源。随后 SessionStore 移除该 Session 的输出目录:它自己的 `command-output//`、创建时为该 id 占下的 `command-output/.session-ids//`,以及它每一行路径所在的目录;另一个 Session 仍在该目录下有行时保留(ADR 013 D4)。然后在一个事务内删除使 Session 可见的行(Session 文件和输出所有权行、授权、标题、目录、owner、Session 与分支),再按有界事务删除它的 Timeline 行。失去最后一个所有者的文件由 S5a 的清扫移除。删除不存在的 Session 也成功。 - **清理。** 一次删除移除该 Session 拥有的一切(§3.3)。按时间或保留数量清理并预览,由 CLI 组合 `session.summaries` 与 `session.delete` 完成,没有对应的服务端方法。 - **崩溃安全。** 目录的移除在第一个行事务提交之前落盘,Session 文件按 S5a 的行处理。第一个事务移除使 Session 可见的行;其余 Timeline 行按有界事务删除。中断只会留下不可见的 Session 和至多该 id 的不可达行,重试会删除它们;下一次清扫完成文件(§4)。 - **分叉。** 分叉按有界事务把源 Session 的 `main` 截至某个切点的部分按存储的字节复制到一个新 Session,并共享源的 Session 文件。切点必须是 `main` 的静止点,`main` 到那时创建的分支只复制目录、不带事件,因此客户端给分叉发送输入之前,分叉不会自己开始任何工作(§6.5)。分叉的 `main` 以 `branch/resume` 打开:分叉就是源的对话在切点处、以新 id 恢复。分叉紧接在复制的事实之后写下自己的一个事实 `session/forked`,让折叠分支自身历史的所有者知道复制到哪里为止(§6.5);v3 连接会投递它,v2 保持自己的事件列表。`SessionConfig` 整体复制,`interactive` 和权限预设随之带过去,不放宽任何权限。 @@ -43,7 +43,7 @@ 资源节点(P1/P2 即控制节点) FileStorage: remove(command-output/) ``` -Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`Agent::create_session` 带 `CreateSessionOptions::prepare`)。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 +Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`Agent::create_session` 带 `CreateSessionOptions::prepare`)。创建先把新 id 的输出名字占下——`<输出根>/.session-ids/`,在它命令输出所在的根下、以该 id 本身命名的一个目录——再进入准备步骤写行:文件系统无法承载成目录的 id,或已被另一个 Session 占下的 id,在任何准备、写入、发布之前就被拒绝。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 ## 3. 删除 @@ -84,7 +84,7 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 设了 `requireInactive` 时,删除在移除任何东西之前检查:S 和它会一并移除的每个 Session(它领导的成员,递归)都没有被使用。检查在 S 的准入门下进行,并对每个 Session 分别读取。一个 Session 处于使用中,指持有 `SessionUse`(每个被接受的请求和每个订阅都持有,所以附着的客户端算),或存在 `SessionHold`(被接受的分离工作取得),或它已加载且任一条线有回合在运行、或其已接受的工作尚未被派发(`Session::in_use`,逐条线)。失败或正在关闭的线不让 Session 处于使用中:线上没有工作,删除自身的关闭会结算它持有的东西。卸载的 Session 没有线和 hold,只有使用数能让它处于使用中。拒绝为 `session_active`(§3.5),什么都不移除;消息说明是什么在用它。只有所有者能回答这件事:只有它看得到此刻的使用、hold 和线,而客户端读摘要只能读到删除之前的状态。准入门一直持有到 S 被忘记,所以检查之后不会再有对 S 的新使用被接纳。成员是在它自己的准入门之外读取的,因此客户端在检查与该成员删除之间附着到成员的情况不在保证之内。不持 `SessionUse` 就启动回合的调用方,要么在启动期间持有该 Session(后台任务的唤醒取得 `SessionHold`,Scheduler 经 `sessions` 服务的运行取得租约),要么在关闭之后追加,而分支会拒绝。 2. **关闭。** 若 S 已加载,Agents 像 `session.close` 那样关闭它:业务关闭,不是卸载。各能力结算已接受的工作,写出终态事实,释放进程、FileStorage 租约和成员请求。关闭报告清理错误时记日志并继续删除:未能写出的事实会随其余部分一起删除。从关闭起 S 的槽位即关闭:无论行最终是否删除,S 在本进程内都不再加载(第 6 步)。 -3. **命令输出。** SessionStore 在改动任何行之前移除该 Session 的输出目录(ADR 013 D4):它自己的 `<数据库目录>/command-output//`,以及它每一行路径所在的目录,因此分叉复制来的 `command-output//` 和 `.dim/exec///` 目录也覆盖在内。另一个 Session 仍在该目录下有行时,目录保留。SessionStore 的所有权锁把这次移除与第 4 步的删行跨 Session 串行化:否则两个并发删除可能都看到对方的行,都保留共享目录,提交后目录没有所有者。分叉步骤在复制时持有同一把锁并复制当前的全部输出行;一致由锁保证,而不是靠检查文件是否存在,因此运行中的命令在写出文件之前登记的行也会被复制,该命令创建的文件归分叉所有。`command-output` 目录通过 S 的资源节点上的 FileStorage(与 S5a 一样每次调用时查找)移除;`.dim/exec` 目录由 HostPlatform 移除,HostPlatform 不读取所有权行。目录不存在视为已移除。每次移除必须在第 4 步之前落盘(§4),因此 FileStorage 的 `remove` 要同步被移除条目的父目录(§14)。失败时删除在改动任何行之前结束(§3.5)。只有本数据库有 S 的行时,SessionStore 才移除自己的 `command-output//`:`command-output/` 由同一目录下的所有数据库共用,本库没有行的 id,其目录可能属于另一个数据库的 Session(§4)。 +3. **命令输出。** SessionStore 在改动任何行之前移除该 Session 的输出目录(ADR 013 D4):它自己的 `<数据库目录>/command-output//`、创建时为该 id 占下的 `<数据库目录>/command-output/.session-ids//`,以及它每一行路径所在的目录,因此分叉复制来的 `command-output//` 和 `.dim/exec///` 目录也覆盖在内。另一个 Session 仍在该目录下有行时,目录保留。SessionStore 的所有权锁把这次移除与第 4 步的删行跨 Session 串行化:否则两个并发删除可能都看到对方的行,都保留共享目录,提交后目录没有所有者。分叉步骤在复制时持有同一把锁并复制当前的全部输出行;一致由锁保证,而不是靠检查文件是否存在,因此运行中的命令在写出文件之前登记的行也会被复制,该命令创建的文件归分叉所有。`command-output` 目录通过 S 的资源节点上的 FileStorage(与 S5a 一样每次调用时查找)移除;`.dim/exec` 目录由 HostPlatform 移除,HostPlatform 不读取所有权行。目录不存在视为已移除。每次移除必须在第 4 步之前落盘(§4),因此 FileStorage 的 `remove` 要同步被移除条目的父目录(§14)。失败时删除在改动任何行之前结束(§3.5)。只有本数据库有 S 的行时,SessionStore 才移除自己的 `command-output//` 和该 id 的占位:`command-output/` 由同一目录下的所有数据库共用,本库没有行的 id,其目录可能属于另一个数据库的 Session(§4)。 4. **行。** 一个 `IMMEDIATE` 事务删除使 S 可见的行:`session_file_owners`(S5a 释放其文件)、`session_output_owners`、`session_grants`、`session_worktrees`、S5b 的标题元数据(§14)、`session_catalog`([#556 的目录投影](../../../design/appserver/native-storage-format.md#556-v23-格式决定))、`session_owners`、`timeline_branches` 和 `agent_sessions`。`timeline_snapshots`、`timeline_events` 和 `timeline_content` 随后在复制连接上按有界事务删除,每个事务至多删除 256 行,其他 Session 的提交与发布因此能在其间进行(#599)。复制连接关闭外键,第一个事务才能先删掉其余删除所引用的行。该操作在 Timeline 写线程排空已为 S 排队的所有追加之后执行,并清除 S 记下的写入失败;删除与创建回滚共用它。见[存储格式 §SQLite 运行参数与空间回收](../../../design/appserver/native-storage-format.md#sqlite-运行参数与空间回收)。 5. **清扫。** SessionStore 安排 S5a 的清扫([Session 文件 §5.4](session-files.md#54-清扫))。最后一个所有者是 S 的文件在清扫中移除;仍有分叉拥有的文件保留。 6. **忘记。** Agents 删除 S 的协议版本和不可用 Session 条目,把 S 的槽位标为已关闭、已删除,并在没有其他东西持有它时移除它([空闲卸载 §6.4](idle-unload.md#64-准入槽))。仍在准入门处等待的调用方会看到槽位已关闭,之后的调用方会发现 S 既没有所有者也没有行:两种情况下 `acquire` 都回答 `session_closed`。在第 4 步之前失败的删除则释放准入门。被它关闭的 Session 保持 `session.close` 之后的状态:行还在,`session.summaries` 不列出它,本进程内不再加载,重试即可删除;重启后它照常加载。删除没有关闭的 Session 在下次使用时照常加载(§16 D5)。 @@ -99,6 +99,7 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | 标题元数据 | 原生存储,S5b 的 `session_metadata` 行([标题元数据](session-title-metadata.md#9-生命周期)) | 第 4 步,同一事务 | | Worktree 使用关联 | 原生存储,`session_worktrees` 行([worktree access §4](../../../design/worktree-access.md#4-持久使用关联与清理边界)) | 第 4 步,同一事务;保留目录记录与 worktree 文件 | | exec 输出、转存的 `read` 结果和持久 shell 日志 | `<数据库目录>/command-output//` 及 S 的输出行命名的每个目录 | 第 3 步。本数据库另一个 Session 仍命名的目录保留 | +| 创建时为该 id 占下的名字 | `<数据库目录>/command-output/.session-ids//` | 第 3 步。它不存输出,也没有自己的行;创建失败时由创建自己的清理移除 | | 已加载实例、租约、订阅、在途使用 | 进程内存 | 第 2 步 | | 协议版本、准入槽位、不可用 Session 条目 | Agents 内存 | 第 6 步 | | 指向 S 的 Collaboration 关系、S 领导的成员 Session 与 S 拥有的 Agent | 持久:`agent_sessions.leader_session_id` 与 `agents.owner_session_id`([Collaboration §6](../plugins/Collaboration.md#6-委派的所有权与寿命));Collaboration 的关系由它们重建 | Agents 随 leader 一起删除 Team:每个成员自己的删除(其行由 SessionStore 删除)、Agents 拥有的 Agent 记录,最后是 S。Collaboration 在观察到成员关闭([collaboration.rs](../../../../crates/dim-app-server/src/collaboration.rs) 的 `session_ended`)或删除已卸载成员时移除关系,装载时重建其余([空闲卸载 §7](idle-unload.md#7-竞争与交互)) | @@ -153,9 +154,9 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | 提交之后、回复之前 | 无行 | 目录已无;S 的文件无所有者 | 客户端重试时本库已无行,不移除目录,得到 `{deleted: false}` 并再次安排清扫;否则由 S5a 的下一次触发(另一次删除,或之后某一代的第一次写入)移除文件 | | 清扫期间 | S5a 的状态 | — | [Session 文件 §6](session-files.md) 的崩溃恢复表 | -**为什么目录在提交之前移除。** S 自己的 `command-output//` 目录没有自己的行(只有其中的文件可能有)。行删除之后,孤立的目录只能靠列出 `command-output/` 找到,而这个目录由同一数据库目录下的所有数据库共用(一个目录下两个 `--database` 文件),列目录无法区分已删除 Session 的目录和另一个存储的目录。先移除目录,任何已提交的删除都不会留下它。本数据库另一个 Session 仍命名的目录保留(ADR 013 D4):它仍能通过那个 Session 的行找到,下一次删除再移除它。S5a 的文件采用相反的顺序,因为有行记录它们,清扫能找到。FileStorage 的移除原本不同步([S6](https://github.com/arcships/dim/pull/87)):断电后,被移除的目录可能重新出现,而之后以 `synchronous=FULL` 提交的事务仍然有效。现在 `remove` 在返回前同步父目录(§14),消除了这个窗口;HostPlatform 对移除的 `.dim/exec` 目录也同步父目录。 +**为什么目录在提交之前移除。** S 自己的 `command-output//` 目录没有自己的行(只有其中的文件可能有),它在 `.session-ids/` 下的占位也没有。行删除之后,孤立的目录只能靠列出 `command-output/` 找到,而这个目录由同一数据库目录下的所有数据库共用(一个目录下两个 `--database` 文件),列目录无法区分已删除 Session 的目录和另一个存储的目录。先移除目录,任何已提交的删除都不会留下它。本数据库另一个 Session 仍命名的目录保留(ADR 013 D4):它仍能通过那个 Session 的行找到,下一次删除再移除它。S5a 的文件采用相反的顺序,因为有行记录它们,清扫能找到。FileStorage 的移除原本不同步([S6](https://github.com/arcships/dim/pull/87)):断电后,被移除的目录可能重新出现,而之后以 `synchronous=FULL` 提交的事务仍然有效。现在 `remove` 在返回前同步父目录(§14),消除了这个窗口;HostPlatform 对移除的 `.dim/exec` 目录也同步父目录。 -**只移除本库有行的 id。** 出于同样的原因,只有本数据库有该 id 的行时,删除才移除它的目录。同一目录下 `a.sqlite` 和 `b.sqlite` 两个守护进程共用 `command-output/`;把 `session.delete {S_b}` 发给前者(例如 CLI 用错了 `--database`)时,它回复 `{deleted: false}`,不能移除仍在后者中运行的 S_b 的输出。这个检查不影响收敛:目录在行之前移除,所以本库没有 S 的行时,也已没有 S 的目录可移除;Agents 的准入门保证同一 id 的两次删除不会交错。因此提交之后的重试什么都不移除,也不需要移除。 +**只移除本库有行的 id。** 出于同样的原因,只有本数据库有该 id 的行时,删除才移除它的目录和该 id 的占位。同一目录下 `a.sqlite` 和 `b.sqlite` 两个守护进程共用 `command-output/`;把 `session.delete {S_b}` 发给前者(例如 CLI 用错了 `--database`)时,它回复 `{deleted: false}`,不能移除仍在后者中运行的 S_b 的输出,也不能移除它的占位(那会让同名的新创建用上同一个目录)。这个检查不影响收敛:目录在行之前移除,所以本库没有 S 的行时,也已没有 S 的目录可移除;Agents 的准入门保证同一 id 的两次删除不会交错。因此提交之后的重试什么都不移除,也不需要移除。 被否决的方案: @@ -354,7 +355,7 @@ S5c 中被否决:在 S 的分叉都删除之前保留 S 的命令输出。ADR | 删除的关闭发生在分叉检查切点期间 | 检查失败于 `session_closed` | | 写入与删除或分叉 | Session 文件 §6 | | 两次删除 | 第二次等准入门,然后发现没有行:`{deleted: false}` | -| 删除仍在构建的 Session:行已提交并已列出的 `session.create`、成员创建或分叉 | 创建从其行提交之前起持有新 id 的准入门,直到 Session 发布、协议版本记下为止(D6)。删除等待,然后关闭已发布的 Session 并删除其行。创建失败时回滚它的行,删除什么也找不到 | +| 删除仍在构建的 Session:行已提交并已列出的 `session.create`、成员创建或分叉 | 创建在准备步骤之前就占下新 id 的输出名字,并从其行提交之前起持有新 id 的准入门,直到 Session 发布、协议版本记下为止(D6)。删除等待,然后关闭已发布的 Session 并删除其行和占位。创建失败时回滚它的行并释放占位,删除什么也找不到 | | 删除与 attach、submit 或 Session 方法 | 它们等准入门,然后失败于 `session_closed`;已持有使用权的请求随关闭结束 | | 删除与该 Session 自己的追加 | 关闭结算它们;行事务在 Timeline 写线程上排在所有已排队的追加之后 | | 分叉与对源的追加 | `at` 及之前的行不变,分叉也不复制其后的任何行:子分支目录不带事件 | From d81f37d4e5e79e100f6284aebf51a62e35ad728c Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 03:11:28 +0800 Subject: [PATCH 07/23] test(runtime): release a failed creation's booked name A creation that fails before its prepare step and one that fails after its rows are committed both release the id's booking, with the rows in the second case, so the same id can be created again. The test drives both exits through the output root the product configures. --- .../tests/agent_options_flow.rs | 86 ++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index c5a6561b5f..667cde8067 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -10,7 +10,7 @@ use dim_agent_runtime::{ SessionConfig, StoredBranch, StoredEvent, TimelineKey, TimelineReadScope, TimelineStore, TimelineStoreBinding, TimelineTrace, }; -use rutis::host::DynPlugin; +use rutis::host::{DynPlugin, ErrorKind}; use rutis::{Ctx, Plugin}; use std::{ collections::BTreeMap, @@ -436,9 +436,19 @@ async fn a_rejected_duplicate_keeps_the_existing_sessions_state() { /// A host whose WorkspaceTools output root is `root`: the product's wiring of /// the id admission. No tool runs, so the platform needs no exec shell. async fn output_host(store: &Arc, root: &Path) -> MinimalHost { + output_host_with(store, root, |_| {}).await +} + +/// [`output_host`] with `install` run on the builder, for a fixture part. +async fn output_host_with( + store: &Arc, + root: &Path, + install: impl FnOnce(&mut AgentBuilder), +) -> MinimalHost { let mut builder = AgentBuilder::new(AgentConfig::default()); defaults::mock_model_hosts(&mut builder); defaults::install(&mut builder); + install(&mut builder); builder.timeline_store(TimelineStoreBinding::new(store.clone())); workspace_tools::install( &mut builder, @@ -574,3 +584,77 @@ async fn ids_the_filesystem_cannot_tell_apart_do_not_share_an_output_directory() host.close().await.unwrap(); std::fs::remove_dir_all(&root).unwrap(); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_failed_creation_releases_its_booked_name() { + let root = std::env::temp_dir().join(format!("dim-output-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&root).unwrap(); + let store = Arc::new(Shared::default()); + let host = output_host_with(&store, &root, |builder| { + builder.session_extension_part::(GROUP, "options-probe", |_, _: &u32| { + Err(rutis::Error::from(ErrorKind::PluginFailed( + "extension fixture refused".into(), + ))) + }); + }) + .await; + let agent = host.agent().clone(); + let error = rejected( + agent + .create_session( + output_session(), + CreateSessionOptions::default().id("retried").prepare(|_| { + Box::pin(async { Err(AgentError::InvalidInput("prepare refused".into())) }) + }), + ) + .await, + ); + assert!( + matches!(&error, AgentError::InvalidInput(message) if message == "prepare refused"), + "a failed prepare is the creation's error: {error}" + ); + assert!( + store.created.lock().unwrap().is_empty(), + "a failed prepare writes no rows: {:?}", + store.created.lock().unwrap() + ); + let entered = Arc::new(AtomicBool::new(false)); + let error = rejected( + agent + .create_session( + output_session(), + CreateSessionOptions::default() + .id("retried") + .prepare(preparing(&store, entered.clone())) + .extension(GROUP, 7_u32), + ) + .await, + ); + assert!( + entered.load(Ordering::SeqCst), + "the creation committed its rows before the build failed" + ); + assert!( + error.to_string().contains("extension fixture refused"), + "a build that fails after its rows keeps its own error: {error}" + ); + assert!( + store.session_config("retried").await.unwrap().is_none(), + "a failed build rolls its rows back" + ); + let session = agent + .create_session( + output_session(), + CreateSessionOptions::default().id("retried"), + ) + .await + .expect("a failed creation releases its booked name"); + assert_eq!( + session.id(), + "retried", + "the id is the one it was booked under" + ); + session.close().await.unwrap(); + host.close().await.unwrap(); + std::fs::remove_dir_all(&root).unwrap(); +} From bdc21bc4b4fb4c8c51450900a0f600af1001cadc Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 03:49:34 +0800 Subject: [PATCH 08/23] fix(runtime): reserve the id bookings' name as a Session id A Session named `.session-ids` would own the booking root below the output root, so its command output would be every other Session's booking and deleting it would remove all of them. `check_session_id` now rejects that name, and every spelling a case-insensitive filesystem folds to it, before any booking, prepare step, storage write or publication. The rejection is shared: the App Server's delete, fork and owned-creation steps call the same check. --- .../tests/agent_options_flow.rs | 21 +++++++++++++++++++ crates/dim-agent-runtime/src/agent.rs | 10 +++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index 667cde8067..31a26d1b8e 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -329,6 +329,27 @@ async fn an_explicit_id_is_admitted_only_as_one_path_component() { "{id:?}: a rejected id publishes no Session" ); } + for id in [".session-ids", ".SESSION-IDS"] { + let entered = Arc::new(AtomicBool::new(false)); + let error = rejected( + agent + .create_session( + SessionConfig::default(), + CreateSessionOptions::default() + .id(id) + .prepare(preparing(&store, entered.clone())), + ) + .await, + ); + assert!( + matches!(&error, AgentError::InvalidInput(message) if message == &format!("invalid Session id {id}")), + "{id:?} names the id bookings rather than a Session: {error}" + ); + assert!( + !entered.load(Ordering::SeqCst), + "{id:?}: a rejected id reaches no prepare step" + ); + } let error = rejected( agent .create_session( diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 83a6cb6fbf..8f91174bd0 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -119,11 +119,16 @@ impl RestoreSessionOptions { /// addresses: an absolute path, a current or parent directory, and a path of /// several components are rejected with [`AgentError::InvalidInput`]. /// +/// [`SESSION_ID_BOOKINGS`] is reserved in every spelling a case-insensitive +/// filesystem may fold to it: that entry below an output root holds the +/// bookings, so a Session named by it would own every other Session's name. +/// /// A [`Agent::create_session`] checks this and also books that component below /// the host's output root, so the id it accepts is one this filesystem can /// back with a directory, and no other Session holds the same directory. pub fn check_session_id(id: &str) -> Result<()> { - if !matches!(std::path::Path::new(id).components().collect::>()[..], + if id.eq_ignore_ascii_case(SESSION_ID_BOOKINGS) + || !matches!(std::path::Path::new(id).components().collect::>()[..], [std::path::Component::Normal(name)] if name == id) { return Err(AgentError::InvalidInput(format!("invalid Session id {id}"))); @@ -131,7 +136,8 @@ pub fn check_session_id(id: &str) -> Result<()> { Ok(()) } /// The directory below a Session output root that books each id a creation -/// accepts: `/.session-ids/`. +/// accepts: `/.session-ids/`. No Session may be named by this +/// entry ([`check_session_id`]). pub const SESSION_ID_BOOKINGS: &str = ".session-ids"; /// Books `id`'s name below the Session output `root`, when the host configured /// one, at `/.session-ids/`. The entry sits in the root the Session's From cc6a1c105312757e48f03e29b1e0af60a55e66e5 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 03:49:37 +0800 Subject: [PATCH 09/23] test(app-server): cover the booking a delete removes The delete's output removal already took the creation's booking of the id with the Session's own directory, and nothing exercised it. The new case books a name, deletes the Session, and then books the same name again, which only succeeds because the delete removed the first booking. --- .../dim-app-server/src/storage/files/tests.rs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/dim-app-server/src/storage/files/tests.rs b/crates/dim-app-server/src/storage/files/tests.rs index a8f44ceb36..2a6594280f 100644 --- a/crates/dim-app-server/src/storage/files/tests.rs +++ b/crates/dim-app-server/src/storage/files/tests.rs @@ -365,6 +365,32 @@ async fn an_interrupted_delete_converges_on_retry_and_the_next_sweep() { fixture.close().await; } +/// ADR 013 D4: a delete removes the booking a creation made for the id, so +/// the name it held is free for a later creation. +#[tokio::test] +async fn a_delete_returns_the_booked_name_to_a_later_creation() { + let fixture = Fixture::new().await; + let store = SessionStore::new(fixture.db.clone(), fixture.root.clone(), 0); + let output = fixture.home.join("command-output"); + let booking = output + .join(dim_agent_runtime::SESSION_ID_BOOKINGS) + .join("reused"); + fixture.session("reused").await; + std::fs::create_dir_all(&booking).unwrap(); + std::fs::write(booking.join("owner"), b"store").unwrap(); + std::fs::create_dir_all(output.join("reused")).unwrap(); + std::fs::write(output.join("reused/exec.log"), b"output").unwrap(); + + assert!(store.delete_session("reused").await.unwrap()); + assert!(!booking.exists(), "the delete removes the booked name"); + assert!(!output.join("reused").exists()); + + fixture.session("reused").await; + std::fs::create_dir(&booking).expect("a deleted Session's name is free again"); + drop(store); + fixture.close().await; +} + /// A fork persists the configuration its caller read: a source update that /// lands after that read changes neither the live fork nor its record. #[tokio::test] From eb4ca48d3982ac261f0c74369df0e4c2e70ef449 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 03:49:37 +0800 Subject: [PATCH 10/23] docs(runtime): state what the Session id booking covers The booking refuses a name another creation booked; it says nothing about a Session stored before it, one written through the store's own creation and fork steps, or the persistent shell's directory on another volume. The paragraph now states those limits, the cross-database refusal, and the reserved booking name, in both languages. --- docs/adr/013-command-output-ownership.md | 12 ++++++++---- docs/design/appserver/session-deletion-and-fork.md | 9 +++++++-- .../zh/design/appserver/session-deletion-and-fork.md | 2 +- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/adr/013-command-output-ownership.md b/docs/adr/013-command-output-ownership.md index ba162c85de..99f878d4d5 100644 --- a/docs/adr/013-command-output-ownership.md +++ b/docs/adr/013-command-output-ownership.md @@ -72,10 +72,14 @@ to this database and the cross-database case is accepted. A creation books its id's name before it prepares or writes, at `/.session-ids/`: one directory named by the id itself, created exclusively, so a -name this filesystem cannot back with a directory and a name that resolves to another Session's -directory are both refused before anything is written. A booking holds no output and has no row; -the deleting session's booking is a candidate under the same rows-here rule as its own output -directory, and a failed creation's own cleanup removes it. +name this filesystem cannot back with a directory, and a name it folds to one another creation +booked, are both refused before anything is written. A booking protects a booked name only: a +Session stored before this step holds none, and the proof is the output root's volume rather than +the host home's `exec` tree. Two databases sharing an output root refuse each other's booked +names, and `.session-ids` is not a Session id in any spelling a case-insensitive filesystem folds +to it. A booking holds no output and has no row; the deleting session's booking is a candidate +under the same rows-here rule as its own output directory, and a failed creation's own cleanup +removes it. The session-files owner supplies the paths and the last-owner answer; HostPlatform removes the `.dim/exec` directory it owns and makes the removal durable (the parent is synced) before the row diff --git a/docs/design/appserver/session-deletion-and-fork.md b/docs/design/appserver/session-deletion-and-fork.md index 35430e97ea..0e42b82722 100644 --- a/docs/design/appserver/session-deletion-and-fork.md +++ b/docs/design/appserver/session-deletion-and-fork.md @@ -66,8 +66,13 @@ Rpc checks the params and the Session's protocol version and calls Agents. Agent admission gate `acquire` already holds while it restores a Session, `Session::close`, and prepared creation (`Agent::create_session` with `CreateSessionOptions::prepare`). A creation books its new id's output name first — `/.session-ids/`, one directory named by the id in the root its command output addresses — before its -prepare step writes the rows: an id this filesystem cannot back with a directory, or one another Session already -books, is refused before anything prepares, writes or publishes. SessionStore owns the rows and the files under the database directory. Its new steps +prepare step writes the rows: an id this filesystem cannot back with a directory, and an id it folds to a name another +creation booked, are refused before anything prepares, writes or publishes. What the booking protects is a booked name: +a Session stored before this step, or written by another face of the store, holds none, so an id this filesystem folds to +its name is accepted and both address one directory. The booking proves the name in the output root's volume; the +persistent shell's directory lies below the host home, which may be another volume. Two databases that share one output +root refuse each other's booked names, because one name addresses one directory, and `.session-ids` is no Session id in +any spelling a case-insensitive filesystem folds to it. SessionStore owns the rows and the files under the database directory. Its new steps are Rust methods over the native store, not services: only Agents calls them. ## 3. Deletion diff --git a/docs/zh/design/appserver/session-deletion-and-fork.md b/docs/zh/design/appserver/session-deletion-and-fork.md index a2482acd07..8b24d5fe3a 100644 --- a/docs/zh/design/appserver/session-deletion-and-fork.md +++ b/docs/zh/design/appserver/session-deletion-and-fork.md @@ -43,7 +43,7 @@ 资源节点(P1/P2 即控制节点) FileStorage: remove(command-output/) ``` -Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`Agent::create_session` 带 `CreateSessionOptions::prepare`)。创建先把新 id 的输出名字占下——`<输出根>/.session-ids/`,在它命令输出所在的根下、以该 id 本身命名的一个目录——再进入准备步骤写行:文件系统无法承载成目录的 id,或已被另一个 Session 占下的 id,在任何准备、写入、发布之前就被拒绝。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 +Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`Agent::create_session` 带 `CreateSessionOptions::prepare`)。创建先把新 id 的输出名字占下——`<输出根>/.session-ids/`,在它命令输出所在的根下、以该 id 本身命名的一个目录——再进入准备步骤写行:文件系统无法承载成目录的 id,以及文件系统会折叠到另一个创建已占下的名字的 id,都在任何准备、写入、发布之前被拒绝。占位保护的是已经占下来的名字:本次改动之前存下的 Session、以及由 store 其它面写入的 Session 都没有占位,所以一个会被文件系统折叠到它的名字的 id 仍会被接受,两者因而共用一个目录。占位证明的是输出根所在卷上的名字;持久 shell 的目录在宿主 home 下,可能在另一个卷上。共用一个输出根的两个数据库会拒绝对方已占下的名字,因为一个名字只对应一个目录;`.session-ids` 在任何会被大小写不敏感文件系统折叠到它的写法下都不是合法的 Session id。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 ## 3. 删除 From 361480a7595ebfd027a63b6eff3fed27cb953ba0 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 03:52:34 +0800 Subject: [PATCH 11/23] fix(runtime): reserve the id bookings' name as Windows folds it Windows strips a directory name's trailing dots and spaces, so `.session-ids.` and `.session-ids ` would name the bookings entry itself, and the reservation let them through. `check_session_id` now folds the id the way such a volume does before comparing it, and the admission test covers both spellings besides the case variants. --- .../tests/agent_options_flow.rs | 2 +- crates/dim-agent-runtime/src/agent.rs | 11 +++++++---- docs/adr/013-command-output-ownership.md | 3 +-- docs/design/appserver/session-deletion-and-fork.md | 2 +- docs/zh/design/appserver/session-deletion-and-fork.md | 2 +- 5 files changed, 11 insertions(+), 9 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index 31a26d1b8e..4f0b35322d 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -329,7 +329,7 @@ async fn an_explicit_id_is_admitted_only_as_one_path_component() { "{id:?}: a rejected id publishes no Session" ); } - for id in [".session-ids", ".SESSION-IDS"] { + for id in [".session-ids", ".SESSION-IDS", ".session-ids.", ".session-ids "] { let entered = Arc::new(AtomicBool::new(false)); let error = rejected( agent diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 8f91174bd0..cd9ac71b36 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -119,15 +119,18 @@ impl RestoreSessionOptions { /// addresses: an absolute path, a current or parent directory, and a path of /// several components are rejected with [`AgentError::InvalidInput`]. /// -/// [`SESSION_ID_BOOKINGS`] is reserved in every spelling a case-insensitive -/// filesystem may fold to it: that entry below an output root holds the -/// bookings, so a Session named by it would own every other Session's name. +/// [`SESSION_ID_BOOKINGS`] is reserved in every spelling a filesystem may fold +/// to it — its case, and on Windows its trailing dots and spaces: that entry +/// below an output root holds the bookings, so a Session named by it would own +/// every other Session's name. /// /// A [`Agent::create_session`] checks this and also books that component below /// the host's output root, so the id it accepts is one this filesystem can /// back with a directory, and no other Session holds the same directory. pub fn check_session_id(id: &str) -> Result<()> { - if id.eq_ignore_ascii_case(SESSION_ID_BOOKINGS) + if id + .trim_end_matches(|c| c == '.' || c == ' ') + .eq_ignore_ascii_case(SESSION_ID_BOOKINGS) || !matches!(std::path::Path::new(id).components().collect::>()[..], [std::path::Component::Normal(name)] if name == id) { diff --git a/docs/adr/013-command-output-ownership.md b/docs/adr/013-command-output-ownership.md index 99f878d4d5..485c4cfd70 100644 --- a/docs/adr/013-command-output-ownership.md +++ b/docs/adr/013-command-output-ownership.md @@ -76,8 +76,7 @@ name this filesystem cannot back with a directory, and a name it folds to one an booked, are both refused before anything is written. A booking protects a booked name only: a Session stored before this step holds none, and the proof is the output root's volume rather than the host home's `exec` tree. Two databases sharing an output root refuse each other's booked -names, and `.session-ids` is not a Session id in any spelling a case-insensitive filesystem folds -to it. A booking holds no output and has no row; the deleting session's booking is a candidate +names, and `.session-ids` is not a Session id in any spelling a filesystem may fold to it. A booking holds no output and has no row; the deleting session's booking is a candidate under the same rows-here rule as its own output directory, and a failed creation's own cleanup removes it. diff --git a/docs/design/appserver/session-deletion-and-fork.md b/docs/design/appserver/session-deletion-and-fork.md index 0e42b82722..01b6a0612d 100644 --- a/docs/design/appserver/session-deletion-and-fork.md +++ b/docs/design/appserver/session-deletion-and-fork.md @@ -72,7 +72,7 @@ a Session stored before this step, or written by another face of the store, hold its name is accepted and both address one directory. The booking proves the name in the output root's volume; the persistent shell's directory lies below the host home, which may be another volume. Two databases that share one output root refuse each other's booked names, because one name addresses one directory, and `.session-ids` is no Session id in -any spelling a case-insensitive filesystem folds to it. SessionStore owns the rows and the files under the database directory. Its new steps +any spelling this filesystem may fold to it, its case and on Windows its trailing dots and spaces. SessionStore owns the rows and the files under the database directory. Its new steps are Rust methods over the native store, not services: only Agents calls them. ## 3. Deletion diff --git a/docs/zh/design/appserver/session-deletion-and-fork.md b/docs/zh/design/appserver/session-deletion-and-fork.md index 8b24d5fe3a..f73e1ddf85 100644 --- a/docs/zh/design/appserver/session-deletion-and-fork.md +++ b/docs/zh/design/appserver/session-deletion-and-fork.md @@ -43,7 +43,7 @@ 资源节点(P1/P2 即控制节点) FileStorage: remove(command-output/) ``` -Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`Agent::create_session` 带 `CreateSessionOptions::prepare`)。创建先把新 id 的输出名字占下——`<输出根>/.session-ids/`,在它命令输出所在的根下、以该 id 本身命名的一个目录——再进入准备步骤写行:文件系统无法承载成目录的 id,以及文件系统会折叠到另一个创建已占下的名字的 id,都在任何准备、写入、发布之前被拒绝。占位保护的是已经占下来的名字:本次改动之前存下的 Session、以及由 store 其它面写入的 Session 都没有占位,所以一个会被文件系统折叠到它的名字的 id 仍会被接受,两者因而共用一个目录。占位证明的是输出根所在卷上的名字;持久 shell 的目录在宿主 home 下,可能在另一个卷上。共用一个输出根的两个数据库会拒绝对方已占下的名字,因为一个名字只对应一个目录;`.session-ids` 在任何会被大小写不敏感文件系统折叠到它的写法下都不是合法的 Session id。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 +Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`Agent::create_session` 带 `CreateSessionOptions::prepare`)。创建先把新 id 的输出名字占下——`<输出根>/.session-ids/`,在它命令输出所在的根下、以该 id 本身命名的一个目录——再进入准备步骤写行:文件系统无法承载成目录的 id,以及文件系统会折叠到另一个创建已占下的名字的 id,都在任何准备、写入、发布之前被拒绝。占位保护的是已经占下来的名字:本次改动之前存下的 Session、以及由 store 其它面写入的 Session 都没有占位,所以一个会被文件系统折叠到它的名字的 id 仍会被接受,两者因而共用一个目录。占位证明的是输出根所在卷上的名字;持久 shell 的目录在宿主 home 下,可能在另一个卷上。共用一个输出根的两个数据库会拒绝对方已占下的名字,因为一个名字只对应一个目录;`.session-ids` 在任何会被文件系统折叠到它的写法下(大小写,以及 Windows 上的尾部点和空格)都不是合法的 Session id。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 ## 3. 删除 From 88b81d6e6e3ed8d7e116a0bb8766bd13960804e1 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 03:53:17 +0800 Subject: [PATCH 12/23] style(runtime): wrap the reserved id spellings The four spellings do not fit one rustfmt line. --- crates/dim-agent-capabilities/tests/agent_options_flow.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index 4f0b35322d..415c1465eb 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -329,7 +329,12 @@ async fn an_explicit_id_is_admitted_only_as_one_path_component() { "{id:?}: a rejected id publishes no Session" ); } - for id in [".session-ids", ".SESSION-IDS", ".session-ids.", ".session-ids "] { + for id in [ + ".session-ids", + ".SESSION-IDS", + ".session-ids.", + ".session-ids ", + ] { let entered = Arc::new(AtomicBool::new(false)); let error = rejected( agent From d35c92315516d33f34eacb75b0210bfdfde59895 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 04:09:29 +0800 Subject: [PATCH 13/23] style(runtime): trim the reserved name with a pattern Clippy asks for the character list rather than a closure. --- crates/dim-agent-runtime/src/agent.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index cd9ac71b36..b665ad10bd 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -129,7 +129,7 @@ impl RestoreSessionOptions { /// back with a directory, and no other Session holds the same directory. pub fn check_session_id(id: &str) -> Result<()> { if id - .trim_end_matches(|c| c == '.' || c == ' ') + .trim_end_matches(['.', ' ']) .eq_ignore_ascii_case(SESSION_ID_BOOKINGS) || !matches!(std::path::Path::new(id).components().collect::>()[..], [std::path::Component::Normal(name)] if name == id) From 69c11336f06cc7c71e17f4117407acdde645b5ca Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 04:19:11 +0800 Subject: [PATCH 14/23] docs(runtime): wrap the booking paragraph The new sentences ran past the width the surrounding paragraphs keep. --- docs/adr/013-command-output-ownership.md | 6 +++--- docs/design/appserver/session-deletion-and-fork.md | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/adr/013-command-output-ownership.md b/docs/adr/013-command-output-ownership.md index 485c4cfd70..754565ecda 100644 --- a/docs/adr/013-command-output-ownership.md +++ b/docs/adr/013-command-output-ownership.md @@ -76,9 +76,9 @@ name this filesystem cannot back with a directory, and a name it folds to one an booked, are both refused before anything is written. A booking protects a booked name only: a Session stored before this step holds none, and the proof is the output root's volume rather than the host home's `exec` tree. Two databases sharing an output root refuse each other's booked -names, and `.session-ids` is not a Session id in any spelling a filesystem may fold to it. A booking holds no output and has no row; the deleting session's booking is a candidate -under the same rows-here rule as its own output directory, and a failed creation's own cleanup -removes it. +names, and `.session-ids` is not a Session id in any spelling a filesystem may fold to it. A +booking holds no output and has no row; the deleting session's booking is a candidate under the +same rows-here rule as its own output directory, and a failed creation's own cleanup removes it. The session-files owner supplies the paths and the last-owner answer; HostPlatform removes the `.dim/exec` directory it owns and makes the removal durable (the parent is synced) before the row diff --git a/docs/design/appserver/session-deletion-and-fork.md b/docs/design/appserver/session-deletion-and-fork.md index 01b6a0612d..80a6cf4e3d 100644 --- a/docs/design/appserver/session-deletion-and-fork.md +++ b/docs/design/appserver/session-deletion-and-fork.md @@ -72,8 +72,9 @@ a Session stored before this step, or written by another face of the store, hold its name is accepted and both address one directory. The booking proves the name in the output root's volume; the persistent shell's directory lies below the host home, which may be another volume. Two databases that share one output root refuse each other's booked names, because one name addresses one directory, and `.session-ids` is no Session id in -any spelling this filesystem may fold to it, its case and on Windows its trailing dots and spaces. SessionStore owns the rows and the files under the database directory. Its new steps -are Rust methods over the native store, not services: only Agents calls them. +any spelling this filesystem may fold to it: its case, and on Windows its trailing dots and spaces. SessionStore owns the +rows and the files under the database directory. Its new steps are Rust methods over the native store, not services: +only Agents calls them. ## 3. Deletion From d41af6a55c52ef8d5de644716e556cf572f04a9a Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 04:47:29 +0800 Subject: [PATCH 15/23] docs(runtime): narrow what a Session id booking protects A booking protects a booked name, not every Session: an id stored before the booking, or written by another face of the store, holds none. Say so in the two rustdoc comments that claimed otherwise. --- crates/dim-agent-runtime/src/agent.rs | 9 +++++---- crates/dim-agent-runtime/src/assembly.rs | 4 ++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index b665ad10bd..a586e32e37 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -125,8 +125,9 @@ impl RestoreSessionOptions { /// every other Session's name. /// /// A [`Agent::create_session`] checks this and also books that component below -/// the host's output root, so the id it accepts is one this filesystem can -/// back with a directory, and no other Session holds the same directory. +/// the host's output root, so the id it accepts is one this filesystem can back +/// with a directory, and a name it folds to one another creation booked is +/// refused. pub fn check_session_id(id: &str) -> Result<()> { if id .trim_end_matches(['.', ' ']) @@ -146,8 +147,8 @@ pub const SESSION_ID_BOOKINGS: &str = ".session-ids"; /// one, at `/.session-ids/`. The entry sits in the root the Session's /// command output addresses and is the id itself, so booking proves this /// filesystem can back the id with a directory there, and that no other -/// Session holds a name it cannot tell apart from this one. The caller owns -/// the booking until it removes it ([`release_booking`]). +/// creation has booked a name it cannot tell apart from this one. The caller +/// owns the booking until it removes it ([`release_booking`]). async fn book_session_id(root: Option<&Path>, id: &str) -> Result<()> { let Some(root) = root else { return Ok(()); diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index c3c9bb6a59..dea9488de0 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -388,8 +388,8 @@ impl AgentBuilder { /// The root of each Session's command-output directory, `/`: /// [`Agent::create_session`] books the id's name there before it prepares, /// writes or publishes, so an id this filesystem cannot back with a - /// directory, or one another Session already holds, is rejected before any - /// of those steps ([`check_session_id`]). + /// directory, or one it folds to a name another creation booked, is + /// rejected before any of those steps ([`check_session_id`]). pub fn session_output_root(&mut self, root: impl Into) -> &mut Self { self.assembly.session_output_root = Some(root.into()); self From 775a873ceecfa504751d0644e3fe8e1488f13eb2 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 04:47:29 +0800 Subject: [PATCH 16/23] test(app-server): book a deleted name with an empty directory The booking is an empty directory a creation holds; the owner file was left over from a design that was not adopted. --- crates/dim-app-server/src/storage/files/tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/dim-app-server/src/storage/files/tests.rs b/crates/dim-app-server/src/storage/files/tests.rs index 2a6594280f..075b2e3f9b 100644 --- a/crates/dim-app-server/src/storage/files/tests.rs +++ b/crates/dim-app-server/src/storage/files/tests.rs @@ -377,7 +377,6 @@ async fn a_delete_returns_the_booked_name_to_a_later_creation() { .join("reused"); fixture.session("reused").await; std::fs::create_dir_all(&booking).unwrap(); - std::fs::write(booking.join("owner"), b"store").unwrap(); std::fs::create_dir_all(output.join("reused")).unwrap(); std::fs::write(output.join("reused/exec.log"), b"output").unwrap(); From bef532a55f8ed0dfb7789012966bce7b6486eead Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 05:34:07 +0800 Subject: [PATCH 17/23] fix(runtime): reserve the booking name under Unicode case folding An id whose Unicode case folding is the booking name is refused, so the long s and sharp s spellings fail with the ASCII ones; trailing dots and spaces are trimmed first. --- crates/dim-agent-runtime/src/agent.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index a586e32e37..70461373e6 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -119,8 +119,8 @@ impl RestoreSessionOptions { /// addresses: an absolute path, a current or parent directory, and a path of /// several components are rejected with [`AgentError::InvalidInput`]. /// -/// [`SESSION_ID_BOOKINGS`] is reserved in every spelling a filesystem may fold -/// to it — its case, and on Windows its trailing dots and spaces: that entry +/// [`SESSION_ID_BOOKINGS`] is reserved: an id whose Unicode case folding, with +/// its trailing dots and spaces trimmed, is that name is refused. That entry /// below an output root holds the bookings, so a Session named by it would own /// every other Session's name. /// @@ -131,7 +131,10 @@ impl RestoreSessionOptions { pub fn check_session_id(id: &str) -> Result<()> { if id .trim_end_matches(['.', ' ']) - .eq_ignore_ascii_case(SESSION_ID_BOOKINGS) + .chars() + .flat_map(char::to_lowercase) + .flat_map(char::to_uppercase) + .eq(".SESSION-IDS".chars()) || !matches!(std::path::Path::new(id).components().collect::>()[..], [std::path::Component::Normal(name)] if name == id) { From 5a7a60c764cd82d1b56e576ddd13f508a7178c45 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 05:34:07 +0800 Subject: [PATCH 18/23] test(runtime): refuse the folding spellings of the booking name The rejected-id flow test adds the long s and sharp s spellings of the booking name, which the check accepts before this fix. --- crates/dim-agent-capabilities/tests/agent_options_flow.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index 415c1465eb..8109b098c1 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -334,6 +334,8 @@ async fn an_explicit_id_is_admitted_only_as_one_path_component() { ".SESSION-IDS", ".session-ids.", ".session-ids ", + ".\u{017f}ession-ids", + ".se\u{00df}ion-ids", ] { let entered = Arc::new(AtomicBool::new(false)); let error = rejected( From d43ba131927cb30495ebea90e59d287a399482db Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 05:34:07 +0800 Subject: [PATCH 19/23] docs(runtime): narrow the reserved name to its folding The runtime rustdoc, the ADR's booking paragraph and the design in both languages now say which spellings the reserved name covers, instead of every spelling a filesystem may fold. --- docs/adr/013-command-output-ownership.md | 7 ++++--- docs/design/appserver/session-deletion-and-fork.md | 7 +++---- docs/zh/design/appserver/session-deletion-and-fork.md | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/adr/013-command-output-ownership.md b/docs/adr/013-command-output-ownership.md index 754565ecda..077bb08eb0 100644 --- a/docs/adr/013-command-output-ownership.md +++ b/docs/adr/013-command-output-ownership.md @@ -76,9 +76,10 @@ name this filesystem cannot back with a directory, and a name it folds to one an booked, are both refused before anything is written. A booking protects a booked name only: a Session stored before this step holds none, and the proof is the output root's volume rather than the host home's `exec` tree. Two databases sharing an output root refuse each other's booked -names, and `.session-ids` is not a Session id in any spelling a filesystem may fold to it. A -booking holds no output and has no row; the deleting session's booking is a candidate under the -same rows-here rule as its own output directory, and a failed creation's own cleanup removes it. +names, and `.session-ids` is not a Session id under Unicode case folding, nor with trailing dots +and spaces. A booking holds no output and has no row; the deleting session's booking is a +candidate under the same rows-here rule as its own output directory, and a failed creation's own +cleanup removes it. The session-files owner supplies the paths and the last-owner answer; HostPlatform removes the `.dim/exec` directory it owns and makes the removal durable (the parent is synced) before the row diff --git a/docs/design/appserver/session-deletion-and-fork.md b/docs/design/appserver/session-deletion-and-fork.md index 80a6cf4e3d..5c95a53a87 100644 --- a/docs/design/appserver/session-deletion-and-fork.md +++ b/docs/design/appserver/session-deletion-and-fork.md @@ -71,10 +71,9 @@ creation booked, are refused before anything prepares, writes or publishes. What a Session stored before this step, or written by another face of the store, holds none, so an id this filesystem folds to its name is accepted and both address one directory. The booking proves the name in the output root's volume; the persistent shell's directory lies below the host home, which may be another volume. Two databases that share one output -root refuse each other's booked names, because one name addresses one directory, and `.session-ids` is no Session id in -any spelling this filesystem may fold to it: its case, and on Windows its trailing dots and spaces. SessionStore owns the -rows and the files under the database directory. Its new steps are Rust methods over the native store, not services: -only Agents calls them. +root refuse each other's booked names, because one name addresses one directory, and `.session-ids` is not a Session id under +Unicode case folding, nor with trailing dots and spaces. SessionStore owns the rows and the files under the database +directory. Its new steps are Rust methods over the native store, not services: only Agents calls them. ## 3. Deletion diff --git a/docs/zh/design/appserver/session-deletion-and-fork.md b/docs/zh/design/appserver/session-deletion-and-fork.md index f73e1ddf85..ba28c2069d 100644 --- a/docs/zh/design/appserver/session-deletion-and-fork.md +++ b/docs/zh/design/appserver/session-deletion-and-fork.md @@ -43,7 +43,7 @@ 资源节点(P1/P2 即控制节点) FileStorage: remove(command-output/) ``` -Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`Agent::create_session` 带 `CreateSessionOptions::prepare`)。创建先把新 id 的输出名字占下——`<输出根>/.session-ids/`,在它命令输出所在的根下、以该 id 本身命名的一个目录——再进入准备步骤写行:文件系统无法承载成目录的 id,以及文件系统会折叠到另一个创建已占下的名字的 id,都在任何准备、写入、发布之前被拒绝。占位保护的是已经占下来的名字:本次改动之前存下的 Session、以及由 store 其它面写入的 Session 都没有占位,所以一个会被文件系统折叠到它的名字的 id 仍会被接受,两者因而共用一个目录。占位证明的是输出根所在卷上的名字;持久 shell 的目录在宿主 home 下,可能在另一个卷上。共用一个输出根的两个数据库会拒绝对方已占下的名字,因为一个名字只对应一个目录;`.session-ids` 在任何会被文件系统折叠到它的写法下(大小写,以及 Windows 上的尾部点和空格)都不是合法的 Session id。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 +Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`Agent::create_session` 带 `CreateSessionOptions::prepare`)。创建先把新 id 的输出名字占下——`<输出根>/.session-ids/`,在它命令输出所在的根下、以该 id 本身命名的一个目录——再进入准备步骤写行:文件系统无法承载成目录的 id,以及文件系统会折叠到另一个创建已占下的名字的 id,都在任何准备、写入、发布之前被拒绝。占位保护的是已经占下来的名字:本次改动之前存下的 Session、以及由 store 其它面写入的 Session 都没有占位,所以一个会被文件系统折叠到它的名字的 id 仍会被接受,两者因而共用一个目录。占位证明的是输出根所在卷上的名字;持久 shell 的目录在宿主 home 下,可能在另一个卷上。共用一个输出根的两个数据库会拒绝对方已占下的名字,因为一个名字只对应一个目录;`.session-ids` 在 Unicode 大小写折叠下、以及带尾部点或空格的写法下,都不是合法的 Session id。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 ## 3. 删除 From 6867cb6454521383a225b9f81998f2f12b99a625 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 07:52:35 +0800 Subject: [PATCH 20/23] revert(runtime): withdraw the Session id booking The booking has no owner for its whole life. A delete derives the booking from the deleting row's id, so it can release a booking that another Session holds, and a rollback or delete that fails releases a name while a stored Session still addresses it. Crash recovery and Sessions stored before the booking hold no booking at all. The design moves to #2204 as one piece: every enabled output root, including the persistent shell's, release only once the final owner is gone, release in the configured output root, legacy ids that stay deletable and usable as a fork source, and a booking namespace no accepted Session id can occupy. This commit restores the tree to the state before the booking, so the creation and restore options, the duplicate-create fix and the id admission fix ship without it. --- .../src/workspace_tools/mod.rs | 3 - .../tests/agent_options_flow.rs | 263 +----------------- crates/dim-agent-runtime/src/agent.rs | 90 +----- crates/dim-agent-runtime/src/assembly.rs | 17 -- crates/dim-app-server/src/storage/files.rs | 33 +-- .../dim-app-server/src/storage/files/tests.rs | 25 -- docs/adr/013-command-output-ownership.md | 11 - .../appserver/session-deletion-and-fork.md | 26 +- .../appserver/session-deletion-and-fork.md | 13 +- 9 files changed, 35 insertions(+), 446 deletions(-) diff --git a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs index 814aa8195c..8ae7975162 100644 --- a/crates/dim-agent-capabilities/src/workspace_tools/mod.rs +++ b/crates/dim-agent-capabilities/src/workspace_tools/mod.rs @@ -53,8 +53,6 @@ const SEARCH_METHOD: &str = "session.files.search"; #[derive(Debug, Clone)] pub struct WorkspaceToolsConfig { /// Absolute root of command output files, `//`. - /// [`install`] also gives it to the Agent as the root below which a - /// Session id is booked before it prepares or writes. pub output_root: PathBuf, /// The root boundary of a session's file tools, when a host configures /// one. The product passes `None`: the tools keep their unbounded @@ -71,7 +69,6 @@ pub use files::FileToolBoundary; /// coordinator, one lock domain for every Session it serves, across their /// generations and its own, and hands it to each Session's part. pub fn install(builder: &mut AgentBuilder, config: WorkspaceToolsConfig) { - builder.session_output_root(config.output_root.clone()); let coordinator = Arc::::default(); builder.plugin(move |names| { Ok(Box::new(WorkspaceToolsOwner::new( diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index 8109b098c1..84a69a35bd 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -1,8 +1,4 @@ -use dim_agent_capabilities::{ - defaults, - host_platform::{HostPlatform, ShellStatus}, - workspace_tools::{self, WorkspaceToolsConfig}, -}; +use dim_agent_capabilities::defaults; use dim_agent_runtime::testing::MinimalHost; use dim_agent_runtime::{ AgentBuilder, AgentConfig, AgentError, BoxFuture, CreateSessionOptions, MemoryTimelineStore, @@ -10,12 +6,11 @@ use dim_agent_runtime::{ SessionConfig, StoredBranch, StoredEvent, TimelineKey, TimelineReadScope, TimelineStore, TimelineStoreBinding, TimelineTrace, }; -use rutis::host::{DynPlugin, ErrorKind}; +use rutis::host::DynPlugin; use rutis::{Ctx, Plugin}; use std::{ collections::BTreeMap, ops::RangeInclusive, - path::Path, sync::{ Arc, Mutex, atomic::{AtomicBool, AtomicU32, Ordering}, @@ -329,34 +324,6 @@ async fn an_explicit_id_is_admitted_only_as_one_path_component() { "{id:?}: a rejected id publishes no Session" ); } - for id in [ - ".session-ids", - ".SESSION-IDS", - ".session-ids.", - ".session-ids ", - ".\u{017f}ession-ids", - ".se\u{00df}ion-ids", - ] { - let entered = Arc::new(AtomicBool::new(false)); - let error = rejected( - agent - .create_session( - SessionConfig::default(), - CreateSessionOptions::default() - .id(id) - .prepare(preparing(&store, entered.clone())), - ) - .await, - ); - assert!( - matches!(&error, AgentError::InvalidInput(message) if message == &format!("invalid Session id {id}")), - "{id:?} names the id bookings rather than a Session: {error}" - ); - assert!( - !entered.load(Ordering::SeqCst), - "{id:?}: a rejected id reaches no prepare step" - ); - } let error = rejected( agent .create_session( @@ -460,229 +427,3 @@ async fn a_rejected_duplicate_keeps_the_existing_sessions_state() { first.close().await.unwrap(); second.close().await.unwrap(); } - -/// A host whose WorkspaceTools output root is `root`: the product's wiring of -/// the id admission. No tool runs, so the platform needs no exec shell. -async fn output_host(store: &Arc, root: &Path) -> MinimalHost { - output_host_with(store, root, |_| {}).await -} - -/// [`output_host`] with `install` run on the builder, for a fixture part. -async fn output_host_with( - store: &Arc, - root: &Path, - install: impl FnOnce(&mut AgentBuilder), -) -> MinimalHost { - let mut builder = AgentBuilder::new(AgentConfig::default()); - defaults::mock_model_hosts(&mut builder); - defaults::install(&mut builder); - install(&mut builder); - builder.timeline_store(TimelineStoreBinding::new(store.clone())); - workspace_tools::install( - &mut builder, - WorkspaceToolsConfig { - boundary: None, - output_root: root.to_owned(), - }, - ); - let platform = HostPlatform::current(ShellStatus::Unavailable { - code: "test", - reason: "the id admission runs no shell".into(), - }) - .expect("the process platform"); - MinimalHost::start_with(&builder, move |root, _| { - root.provide_as::(Arc::new(platform))?; - Ok(()) - }) - .await - .expect("the output host starts") -} - -/// A Session that declares one tool the output host serves and runs none. -fn output_session() -> SessionConfig { - SessionConfig { - tools: Some(vec!["read".into()]), - ..Default::default() - } -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn an_id_without_a_usable_output_directory_is_rejected_before_preparation() { - let root = std::env::temp_dir().join(format!("dim-output-{}", uuid::Uuid::new_v4())); - let store = Arc::new(Shared::default()); - let host = output_host(&store, &root).await; - let agent = host.agent().clone(); - // One component this filesystem cannot hold as a directory name. - let id = "s".repeat(300); - let entered = Arc::new(AtomicBool::new(false)); - let error = rejected( - agent - .create_session( - output_session(), - CreateSessionOptions::default() - .id(id.clone()) - .prepare(preparing(&store, entered.clone())), - ) - .await, - ); - assert!( - matches!(&error, AgentError::InvalidInput(message) if message.starts_with(&format!("Session id {id} has no usable output directory"))), - "a name this filesystem cannot hold is rejected: {error}" - ); - assert!( - !entered.load(Ordering::SeqCst), - "a rejected id reaches no prepare step" - ); - assert!( - store.created.lock().unwrap().is_empty(), - "a rejected id writes no rows: {:?}", - store.created.lock().unwrap() - ); - assert!( - agent.get_session(&id).is_none(), - "a rejected id publishes no Session" - ); - host.close().await.unwrap(); - std::fs::remove_dir_all(&root).unwrap(); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn ids_the_filesystem_cannot_tell_apart_do_not_share_an_output_directory() { - let root = std::env::temp_dir().join(format!("dim-output-{}", uuid::Uuid::new_v4())); - let store = Arc::new(Shared::default()); - let host = output_host(&store, &root).await; - let agent = host.agent().clone(); - let first = agent - .create_session( - output_session(), - CreateSessionOptions::default().id("Named-Session"), - ) - .await - .unwrap(); - assert_eq!( - first.id(), - "Named-Session", - "an accepted id keeps its value" - ); - let entered = Arc::new(AtomicBool::new(false)); - match agent - .create_session( - output_session(), - CreateSessionOptions::default() - .id("named-session") - .prepare(preparing(&store, entered.clone())), - ) - .await - { - Ok(second) => { - assert_ne!(second.id(), first.id()); - std::fs::create_dir_all(root.join(first.id())).unwrap(); - assert!( - !root.join(second.id()).exists(), - "ids this filesystem can tell apart keep distinct output directories" - ); - second.close().await.unwrap(); - } - Err(error) => { - assert!( - matches!(&error, AgentError::InvalidInput(message) if message == "session named-session is already in use"), - "an id this filesystem cannot tell apart from an accepted one is refused: {error}" - ); - assert!( - !entered.load(Ordering::SeqCst), - "a refused id reaches no prepare step" - ); - assert!( - !store - .created - .lock() - .unwrap() - .iter() - .any(|id| id == "named-session"), - "a refused id writes no rows: {:?}", - store.created.lock().unwrap() - ); - assert!( - agent.get_session("named-session").is_none(), - "a refused id publishes no Session" - ); - } - } - first.close().await.unwrap(); - host.close().await.unwrap(); - std::fs::remove_dir_all(&root).unwrap(); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_failed_creation_releases_its_booked_name() { - let root = std::env::temp_dir().join(format!("dim-output-{}", uuid::Uuid::new_v4())); - std::fs::create_dir_all(&root).unwrap(); - let store = Arc::new(Shared::default()); - let host = output_host_with(&store, &root, |builder| { - builder.session_extension_part::(GROUP, "options-probe", |_, _: &u32| { - Err(rutis::Error::from(ErrorKind::PluginFailed( - "extension fixture refused".into(), - ))) - }); - }) - .await; - let agent = host.agent().clone(); - let error = rejected( - agent - .create_session( - output_session(), - CreateSessionOptions::default().id("retried").prepare(|_| { - Box::pin(async { Err(AgentError::InvalidInput("prepare refused".into())) }) - }), - ) - .await, - ); - assert!( - matches!(&error, AgentError::InvalidInput(message) if message == "prepare refused"), - "a failed prepare is the creation's error: {error}" - ); - assert!( - store.created.lock().unwrap().is_empty(), - "a failed prepare writes no rows: {:?}", - store.created.lock().unwrap() - ); - let entered = Arc::new(AtomicBool::new(false)); - let error = rejected( - agent - .create_session( - output_session(), - CreateSessionOptions::default() - .id("retried") - .prepare(preparing(&store, entered.clone())) - .extension(GROUP, 7_u32), - ) - .await, - ); - assert!( - entered.load(Ordering::SeqCst), - "the creation committed its rows before the build failed" - ); - assert!( - error.to_string().contains("extension fixture refused"), - "a build that fails after its rows keeps its own error: {error}" - ); - assert!( - store.session_config("retried").await.unwrap().is_none(), - "a failed build rolls its rows back" - ); - let session = agent - .create_session( - output_session(), - CreateSessionOptions::default().id("retried"), - ) - .await - .expect("a failed creation releases its booked name"); - assert_eq!( - session.id(), - "retried", - "the id is the one it was booked under" - ); - session.close().await.unwrap(); - host.close().await.unwrap(); - std::fs::remove_dir_all(&root).unwrap(); -} diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 70461373e6..60cb564ec4 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -11,7 +11,6 @@ use dim_agent_types::{AgentEvent, BranchSource, InputMessageData, InputMode}; use rutis::host::{CtxHost, FiberView}; use std::{ collections::BTreeMap, - path::Path, sync::{Arc, Mutex, Weak}, }; use tokio::sync::watch; @@ -43,14 +42,9 @@ enum SessionStart { Prepared(Preparation), Restore, } -/// What a creation that fails undoes: its store rows and the output name it -/// booked. +/// What a creation that fails undoes in the store. enum Cleanup { - /// Nothing was written: no rows and no booked name. Nothing, - /// The id's output name is booked and no rows were written. - Booked, - /// The id's rows were written; its output name is booked. Rollback, Release, } @@ -71,8 +65,7 @@ impl CreateSessionOptions { /// The id must be one normal path component, which is what Session /// command-output storage addresses ([`check_session_id`]); /// [`Agent::create_session`] rejects any other id before it prepares, - /// writes or publishes, as it rejects an id the host's output root cannot - /// back with a directory ([`AgentBuilder::session_output_root`]). + /// writes or publishes. pub fn id(mut self, id: impl Into) -> Self { self.id = Some(id.into()); self @@ -118,81 +111,21 @@ impl RestoreSessionOptions { /// Requires the single path component that Session command-output storage /// addresses: an absolute path, a current or parent directory, and a path of /// several components are rejected with [`AgentError::InvalidInput`]. -/// -/// [`SESSION_ID_BOOKINGS`] is reserved: an id whose Unicode case folding, with -/// its trailing dots and spaces trimmed, is that name is refused. That entry -/// below an output root holds the bookings, so a Session named by it would own -/// every other Session's name. -/// -/// A [`Agent::create_session`] checks this and also books that component below -/// the host's output root, so the id it accepts is one this filesystem can back -/// with a directory, and a name it folds to one another creation booked is -/// refused. pub fn check_session_id(id: &str) -> Result<()> { - if id - .trim_end_matches(['.', ' ']) - .chars() - .flat_map(char::to_lowercase) - .flat_map(char::to_uppercase) - .eq(".SESSION-IDS".chars()) - || !matches!(std::path::Path::new(id).components().collect::>()[..], + if !matches!(std::path::Path::new(id).components().collect::>()[..], [std::path::Component::Normal(name)] if name == id) { return Err(AgentError::InvalidInput(format!("invalid Session id {id}"))); } Ok(()) } -/// The directory below a Session output root that books each id a creation -/// accepts: `/.session-ids/`. No Session may be named by this -/// entry ([`check_session_id`]). -pub const SESSION_ID_BOOKINGS: &str = ".session-ids"; -/// Books `id`'s name below the Session output `root`, when the host configured -/// one, at `/.session-ids/`. The entry sits in the root the Session's -/// command output addresses and is the id itself, so booking proves this -/// filesystem can back the id with a directory there, and that no other -/// creation has booked a name it cannot tell apart from this one. The caller -/// owns the booking until it removes it ([`release_booking`]). -async fn book_session_id(root: Option<&Path>, id: &str) -> Result<()> { - let Some(root) = root else { - return Ok(()); - }; - let bookings = root.join(SESSION_ID_BOOKINGS); - if let Err(error) = tokio::fs::create_dir_all(&bookings).await { - return Err(AgentError::InvalidInput(format!( - "Session id {id} has no usable output directory: {error}" - ))); - } - match tokio::fs::create_dir(bookings.join(id)).await { - Ok(()) => Ok(()), - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Err( - AgentError::InvalidInput(format!("session {id} is already in use")), - ), - Err(error) => Err(AgentError::InvalidInput(format!( - "Session id {id} has no usable output directory: {error}" - ))), - } -} -/// Removes a booking ([`book_session_id`]); an absent one counts as removed, -/// so a cleanup that follows a partial failure is safe. -async fn release_booking(root: Option<&Path>, id: &str) -> Result<()> { - let Some(root) = root else { - return Ok(()); - }; - match tokio::fs::remove_dir(root.join(SESSION_ID_BOOKINGS).join(id)).await { - Ok(()) => Ok(()), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(error) => Err(AgentError::Storage(format!( - "the output booking of session {id}: {error}" - ))), - } -} impl Agent { pub(crate) fn new(builder: AgentBuilder, assembly: Assembly, placement: Placement) -> Self { Self(Arc::new(AgentInner { builder, - assembly, placement, handle: std::sync::OnceLock::new(), + assembly, entries: Mutex::new(BTreeMap::new()), closing: CancellationToken::new(), close: CloseOnce::default(), @@ -272,18 +205,13 @@ impl Agent { let mut cleanup = Cleanup::Nothing; let mut result = async { let placement = owner.0.placement.clone(); - let output_root = owner.0.builder.output_root(); let initialization = match start { SessionStart::Create => { - book_session_id(output_root, &id).await?; - cleanup = Cleanup::Booked; assembly.store.create_session(&id, &config).await?; cleanup = Cleanup::Rollback; SessionInitialization::New } SessionStart::Prepared(prepare) => { - book_session_id(output_root, &id).await?; - cleanup = Cleanup::Booked; prepare(id.clone()).await?; cleanup = Cleanup::Rollback; SessionInitialization::Prepared(assembly.store.branches(&id).await?) @@ -330,17 +258,9 @@ impl Agent { }; } if let Err(failure) = result { - let output_root = owner.0.builder.output_root(); let cleanup = match cleanup { Cleanup::Nothing => Ok(()), - Cleanup::Booked => release_booking(output_root, &id).await, - Cleanup::Rollback => owner - .0 - .assembly - .store - .rollback_session(&id) - .await - .and(release_booking(output_root, &id).await), + Cleanup::Rollback => owner.0.assembly.store.rollback_session(&id).await, Cleanup::Release => owner.0.assembly.store.release_session(&id).await, }; result = Err(match cleanup { diff --git a/crates/dim-agent-runtime/src/assembly.rs b/crates/dim-agent-runtime/src/assembly.rs index dea9488de0..b0df3a0f7e 100644 --- a/crates/dim-agent-runtime/src/assembly.rs +++ b/crates/dim-agent-runtime/src/assembly.rs @@ -273,9 +273,6 @@ pub(crate) struct Assembly { pub config: AgentConfig, /// Maximum inactivity interval while opening a Session or branch. pub startup_timeout: Duration, - /// The root of each Session's command-output directory, when the host - /// configures one (`/`). - session_output_root: Option, pub store: Arc, pub ephemeral_store: Option>, /// Shutdowns of instances whose creation was abandoned before the @@ -354,7 +351,6 @@ impl AgentBuilder { assembly: Assembly { config, startup_timeout: Duration::from_secs(10), - session_output_root: None, store: TimelineStoreBinding::new(Arc::new(MemoryTimelineStore::default())), ephemeral_store: None, abandoned: tokio_util::task::TaskTracker::new(), @@ -385,19 +381,6 @@ impl AgentBuilder { self.assembly.startup_timeout = timeout; self } - /// The root of each Session's command-output directory, `/`: - /// [`Agent::create_session`] books the id's name there before it prepares, - /// writes or publishes, so an id this filesystem cannot back with a - /// directory, or one it folds to a name another creation booked, is - /// rejected before any of those steps ([`check_session_id`]). - pub fn session_output_root(&mut self, root: impl Into) -> &mut Self { - self.assembly.session_output_root = Some(root.into()); - self - } - /// The configured command-output root, if the host configured one. - pub(crate) fn output_root(&self) -> Option<&std::path::Path> { - self.assembly.session_output_root.as_deref() - } /// The assembly's service names: hosts register theirs before adding /// parts that depend on them, and their loader uses this catalog. pub fn catalog(&self) -> &rutis_loader::ServiceCatalog { diff --git a/crates/dim-app-server/src/storage/files.rs b/crates/dim-app-server/src/storage/files.rs index ba5662882c..748655492f 100644 --- a/crates/dim-app-server/src/storage/files.rs +++ b/crates/dim-app-server/src/storage/files.rs @@ -300,35 +300,32 @@ impl SessionFiles { } /// S5c's delete step: removes every output directory the Session needs - /// (ADR 013 D4): its own `/command-output/`, - /// the booking a creation made for its id - /// (`/command-output/.session-ids/`), and the - /// directory of every path it has a row for, except one another Session of - /// this database still names a path under. An absent directory counts as - /// removed. Each removal is durable before the caller commits the row - /// deletion. Fails without the node's FileStorage, without HostPlatform for - /// a shell directory, or with `Locked` or `DirectoryNotEmpty` while a writer - /// outside the closed Session holds an entry; the delete is then retried. + /// (ADR 013 D4): its own `/command-output/` + /// and the directory of every path it has a row for, except one another + /// Session of this database still names a path under. An absent directory + /// counts as removed. Each removal is durable before the caller commits + /// the row deletion. Fails without the node's FileStorage, without + /// HostPlatform for a shell directory, or with `Locked` or + /// `DirectoryNotEmpty` while a writer outside the closed Session holds + /// an entry; the delete is then retried. pub(super) async fn remove_output(&self, session_id: &str) -> dim_agent_runtime::Result<()> { let session = session_id.to_owned(); - let output = self + let own = self .0 .db .path .parent() + .map(|directory| { + directory + .join(super::COMMAND_OUTPUT_DIRECTORY) + .join(session_id) + }) .ok_or_else(|| error("the native store path has no directory"))?; - let own = output - .join(super::COMMAND_OUTPUT_DIRECTORY) - .join(session_id); - let booking = output - .join(super::COMMAND_OUTPUT_DIRECTORY) - .join(dim_agent_runtime::SESSION_ID_BOOKINGS) - .join(session_id); let candidates = self .0 .db .run_read(move |connection| { - let mut candidates = BTreeSet::from([own, booking]); + let mut candidates = BTreeSet::from([own]); let mut query = connection .prepare("SELECT DISTINCT path FROM session_output_owners WHERE session_id = ?1") .map_err(error)?; diff --git a/crates/dim-app-server/src/storage/files/tests.rs b/crates/dim-app-server/src/storage/files/tests.rs index 075b2e3f9b..a8f44ceb36 100644 --- a/crates/dim-app-server/src/storage/files/tests.rs +++ b/crates/dim-app-server/src/storage/files/tests.rs @@ -365,31 +365,6 @@ async fn an_interrupted_delete_converges_on_retry_and_the_next_sweep() { fixture.close().await; } -/// ADR 013 D4: a delete removes the booking a creation made for the id, so -/// the name it held is free for a later creation. -#[tokio::test] -async fn a_delete_returns_the_booked_name_to_a_later_creation() { - let fixture = Fixture::new().await; - let store = SessionStore::new(fixture.db.clone(), fixture.root.clone(), 0); - let output = fixture.home.join("command-output"); - let booking = output - .join(dim_agent_runtime::SESSION_ID_BOOKINGS) - .join("reused"); - fixture.session("reused").await; - std::fs::create_dir_all(&booking).unwrap(); - std::fs::create_dir_all(output.join("reused")).unwrap(); - std::fs::write(output.join("reused/exec.log"), b"output").unwrap(); - - assert!(store.delete_session("reused").await.unwrap()); - assert!(!booking.exists(), "the delete removes the booked name"); - assert!(!output.join("reused").exists()); - - fixture.session("reused").await; - std::fs::create_dir(&booking).expect("a deleted Session's name is free again"); - drop(store); - fixture.close().await; -} - /// A fork persists the configuration its caller read: a source update that /// lands after that read changes neither the live fork nor its record. #[tokio::test] diff --git a/docs/adr/013-command-output-ownership.md b/docs/adr/013-command-output-ownership.md index 077bb08eb0..672929b585 100644 --- a/docs/adr/013-command-output-ownership.md +++ b/docs/adr/013-command-output-ownership.md @@ -70,17 +70,6 @@ directory; when F is deleted, F's copied rows name S's directory, so F's delete directory shared with another database is that database's responsibility; this guard is scoped to this database and the cross-database case is accepted. -A creation books its id's name before it prepares or writes, at -`/.session-ids/`: one directory named by the id itself, created exclusively, so a -name this filesystem cannot back with a directory, and a name it folds to one another creation -booked, are both refused before anything is written. A booking protects a booked name only: a -Session stored before this step holds none, and the proof is the output root's volume rather than -the host home's `exec` tree. Two databases sharing an output root refuse each other's booked -names, and `.session-ids` is not a Session id under Unicode case folding, nor with trailing dots -and spaces. A booking holds no output and has no row; the deleting session's booking is a -candidate under the same rows-here rule as its own output directory, and a failed creation's own -cleanup removes it. - The session-files owner supplies the paths and the last-owner answer; HostPlatform removes the `.dim/exec` directory it owns and makes the removal durable (the parent is synced) before the row commit. HostPlatform does not read ownership rows. Keeping the removal before the row commit diff --git a/docs/design/appserver/session-deletion-and-fork.md b/docs/design/appserver/session-deletion-and-fork.md index 5c95a53a87..87c4f73a13 100644 --- a/docs/design/appserver/session-deletion-and-fork.md +++ b/docs/design/appserver/session-deletion-and-fork.md @@ -64,16 +64,8 @@ or the Session facade. Rpc checks the params and the Session's protocol version and calls Agents. Agents owns the Session lifecycle: the admission gate `acquire` already holds while it restores a Session, `Session::close`, and prepared creation -(`Agent::create_session` with `CreateSessionOptions::prepare`). A creation books its new id's output name first — -`/.session-ids/`, one directory named by the id in the root its command output addresses — before its -prepare step writes the rows: an id this filesystem cannot back with a directory, and an id it folds to a name another -creation booked, are refused before anything prepares, writes or publishes. What the booking protects is a booked name: -a Session stored before this step, or written by another face of the store, holds none, so an id this filesystem folds to -its name is accepted and both address one directory. The booking proves the name in the output root's volume; the -persistent shell's directory lies below the host home, which may be another volume. Two databases that share one output -root refuse each other's booked names, because one name addresses one directory, and `.session-ids` is not a Session id under -Unicode case folding, nor with trailing dots and spaces. SessionStore owns the rows and the files under the database -directory. Its new steps are Rust methods over the native store, not services: only Agents calls them. +(`Agent::create_session` with `CreateSessionOptions::prepare`). SessionStore owns the rows and the files under the database directory. Its new steps +are Rust methods over the native store, not services: only Agents calls them. ## 3. Deletion @@ -135,8 +127,7 @@ directory. Its new steps are Rust methods over the native store, not services: o write are removed with the rest. From the close on, S's slot is closed: S does not load again in this process, whether or not its rows go (step 6). 3. **Command output.** SessionStore removes the Session's output directories before any row changes - (ADR 013 D4): its own `/command-output//`, the booking a creation made for - the id (`/command-output/.session-ids//`), and the directory of every + (ADR 013 D4): its own `/command-output//`, and the directory of every path it has a row for, so inherited `command-output//` and `.dim/exec///` directories a fork copied are covered. A directory is removed only if no row of another Session in this database names a path under it. SessionStore @@ -183,7 +174,6 @@ directory. Its new steps are Rust methods over the native store, not services: o | Output ownership | Native store, `session_output_owners` rows (v29, [ADR 013](../../adr/013-command-output-ownership.md) D1) | Step 4, same transaction | | Worktree usage associations | Native store, `session_worktrees` rows ([worktree access §4](../worktree-access.md#4-持久使用关联与清理边界)) | Step 4, same transaction; directory records and worktree files remain | | Exec output, offloaded `read` results and persistent shell logs | `/command-output//` and every directory named by S's output rows | Step 3. A directory another Session in this database still names is kept | -| A creation's booking of the id | `/command-output/.session-ids//` | Step 3. It holds no output and has no row; a creation that fails removes its own before this step | | Loaded instance, leases, subscriptions, in-flight uses | Process memory | Step 2 | | Protocol version, admission slot, unavailable-Session entry | Agents, in memory | Step 6 | | Collaboration relations that name S, the member Sessions S leads and the Agents S owns | Durable: `agent_sessions.leader_session_id` and `agents.owner_session_id` ([Collaboration §6](../plugins/Collaboration.md#6-delegation-ownership-and-lifetime)); Collaboration's relations are rebuilt from them | Agents deletes a leader with its Team: each member's own delete, in which SessionStore removes that Session's rows, then the Agent records Agents owns, then S. Collaboration drops a relation when it observes a member's close ([collaboration.rs](../../../crates/dim-app-server/src/collaboration.rs) `session_ended`) or the delete of an unloaded member, and rebuilds the rest when it loads ([idle unload §7](idle-unload.md#7-races-and-interactions)) | @@ -248,8 +238,7 @@ gone. | During the sweep | S5a's states | — | [Session files §6](session-files.md#6-deletion-crash-recovery-and-serialization) | **Why the directory goes before the commit.** The Session's own `command-output//` directory has no row of its -own (only the files in it may), and neither has its booking under `.session-ids/`. Once the rows are gone, an orphaned -directory could only be found by listing +own (only the files in it may). Once the rows are gone, an orphaned directory could only be found by listing `command-output/`, and that directory is shared by every database in the database directory (two `--database` files in one directory), so a listing cannot tell a deleted Session's directory from another store's. Removing it first means no committed delete ever leaves one behind. A directory another Session in this database still names is kept @@ -260,10 +249,9 @@ commit, made with `synchronous=FULL`, stays. `remove` now syncs the parent befor gap; HostPlatform syncs the parent of a removed `.dim/exec` directory the same way. **Only an id with rows here.** For the same reason a delete removes the directory only while its own database has -rows of the id, and with them the id's booking. Two daemons on `a.sqlite` and `b.sqlite` in one directory share `command-output/`; a +rows of the id. Two daemons on `a.sqlite` and `b.sqlite` in one directory share `command-output/`; a `session.delete {S_b}` sent to the first, for example by a CLI given the wrong `--database`, replies `{deleted: false}` and must not -remove the output of S_b, which is alive in the second, nor its booking, which keeps a second creation of the same -name from taking the same directory. The check costs no convergence: the directory goes before the +remove the output of S_b, which is alive in the second. The check costs no convergence: the directory goes before the rows, so a database with no rows of S has no directory of S left to remove, and Agents' admission gate keeps two deletes of one id from interleaving. A retry after a commit therefore removes nothing, as it needs nothing removed. @@ -567,7 +555,7 @@ delete against loading. | The delete's close during the fork's cut check | The check fails `session_closed` | | Put against delete or fork | Session files §6 | | Two deletes | The second waits for the gate, then finds no rows: `{deleted: false}` | -| Delete of a Session still building: a `session.create`, a member's creation or a fork whose rows are committed and listed | The creation books the new id's output name before its prepare step and holds the id's gate from before its rows commit until the Session is published and its protocol version recorded (D6). The delete waits, then closes the published Session and removes its rows and its booking. A creation that fails rolls its rows back and releases its booking, and the delete finds nothing | +| Delete of a Session still building: a `session.create`, a member's creation or a fork whose rows are committed and listed | The creation holds the new id's gate from before its rows commit until the Session is published and its protocol version recorded (D6). The delete waits, then closes the published Session and removes its rows. A creation that fails rolls its rows back, and the delete finds nothing | | Delete against attach, submit or a Session method | They wait for the gate, then fail `session_closed`; requests that already hold a use end with the close | | Delete against the Session's own appends | The close settles them; the row transaction follows every queued append on the Timeline writer | | Fork against appends to the source | Rows through `at` never change, and the fork copies no row after them: child directories come without events | diff --git a/docs/zh/design/appserver/session-deletion-and-fork.md b/docs/zh/design/appserver/session-deletion-and-fork.md index ba28c2069d..d6c657e7c3 100644 --- a/docs/zh/design/appserver/session-deletion-and-fork.md +++ b/docs/zh/design/appserver/session-deletion-and-fork.md @@ -12,7 +12,7 @@ 客户端用 `session.delete` 删除 Session,用 `session.fork` 分叉 Session。两者都是协议 v3 的 Rpc 内建方法,调用 Agents;Agents 负责加载、关闭和创建 Session,SessionStore 执行行与文件的步骤。 -- **删除。** Agents 不再加载该 Session;若它已加载,就关闭它,让各能力结算在途工作并释放所持资源。随后 SessionStore 移除该 Session 的输出目录:它自己的 `command-output//`、创建时为该 id 占下的 `command-output/.session-ids//`,以及它每一行路径所在的目录;另一个 Session 仍在该目录下有行时保留(ADR 013 D4)。然后在一个事务内删除使 Session 可见的行(Session 文件和输出所有权行、授权、标题、目录、owner、Session 与分支),再按有界事务删除它的 Timeline 行。失去最后一个所有者的文件由 S5a 的清扫移除。删除不存在的 Session 也成功。 +- **删除。** Agents 不再加载该 Session;若它已加载,就关闭它,让各能力结算在途工作并释放所持资源。随后 SessionStore 移除该 Session 的输出目录:它自己的 `command-output//`,以及它每一行路径所在的目录;另一个 Session 仍在该目录下有行时保留(ADR 013 D4)。然后在一个事务内删除使 Session 可见的行(Session 文件和输出所有权行、授权、标题、目录、owner、Session 与分支),再按有界事务删除它的 Timeline 行。失去最后一个所有者的文件由 S5a 的清扫移除。删除不存在的 Session 也成功。 - **清理。** 一次删除移除该 Session 拥有的一切(§3.3)。按时间或保留数量清理并预览,由 CLI 组合 `session.summaries` 与 `session.delete` 完成,没有对应的服务端方法。 - **崩溃安全。** 目录的移除在第一个行事务提交之前落盘,Session 文件按 S5a 的行处理。第一个事务移除使 Session 可见的行;其余 Timeline 行按有界事务删除。中断只会留下不可见的 Session 和至多该 id 的不可达行,重试会删除它们;下一次清扫完成文件(§4)。 - **分叉。** 分叉按有界事务把源 Session 的 `main` 截至某个切点的部分按存储的字节复制到一个新 Session,并共享源的 Session 文件。切点必须是 `main` 的静止点,`main` 到那时创建的分支只复制目录、不带事件,因此客户端给分叉发送输入之前,分叉不会自己开始任何工作(§6.5)。分叉的 `main` 以 `branch/resume` 打开:分叉就是源的对话在切点处、以新 id 恢复。分叉紧接在复制的事实之后写下自己的一个事实 `session/forked`,让折叠分支自身历史的所有者知道复制到哪里为止(§6.5);v3 连接会投递它,v2 保持自己的事件列表。`SessionConfig` 整体复制,`interactive` 和权限预设随之带过去,不放宽任何权限。 @@ -43,7 +43,7 @@ 资源节点(P1/P2 即控制节点) FileStorage: remove(command-output/) ``` -Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`Agent::create_session` 带 `CreateSessionOptions::prepare`)。创建先把新 id 的输出名字占下——`<输出根>/.session-ids/`,在它命令输出所在的根下、以该 id 本身命名的一个目录——再进入准备步骤写行:文件系统无法承载成目录的 id,以及文件系统会折叠到另一个创建已占下的名字的 id,都在任何准备、写入、发布之前被拒绝。占位保护的是已经占下来的名字:本次改动之前存下的 Session、以及由 store 其它面写入的 Session 都没有占位,所以一个会被文件系统折叠到它的名字的 id 仍会被接受,两者因而共用一个目录。占位证明的是输出根所在卷上的名字;持久 shell 的目录在宿主 home 下,可能在另一个卷上。共用一个输出根的两个数据库会拒绝对方已占下的名字,因为一个名字只对应一个目录;`.session-ids` 在 Unicode 大小写折叠下、以及带尾部点或空格的写法下,都不是合法的 Session id。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 +Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负责 Session 的生命周期:`acquire` 恢复 Session 时已经持有的准入门、`Session::close` 和预备创建(`Agent::create_session` 带 `CreateSessionOptions::prepare`)。SessionStore 负责数据库目录下的行和文件。它新增的步骤是作用于原生存储的 Rust 方法,不是服务:只有 Agents 调用。 ## 3. 删除 @@ -84,7 +84,7 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 设了 `requireInactive` 时,删除在移除任何东西之前检查:S 和它会一并移除的每个 Session(它领导的成员,递归)都没有被使用。检查在 S 的准入门下进行,并对每个 Session 分别读取。一个 Session 处于使用中,指持有 `SessionUse`(每个被接受的请求和每个订阅都持有,所以附着的客户端算),或存在 `SessionHold`(被接受的分离工作取得),或它已加载且任一条线有回合在运行、或其已接受的工作尚未被派发(`Session::in_use`,逐条线)。失败或正在关闭的线不让 Session 处于使用中:线上没有工作,删除自身的关闭会结算它持有的东西。卸载的 Session 没有线和 hold,只有使用数能让它处于使用中。拒绝为 `session_active`(§3.5),什么都不移除;消息说明是什么在用它。只有所有者能回答这件事:只有它看得到此刻的使用、hold 和线,而客户端读摘要只能读到删除之前的状态。准入门一直持有到 S 被忘记,所以检查之后不会再有对 S 的新使用被接纳。成员是在它自己的准入门之外读取的,因此客户端在检查与该成员删除之间附着到成员的情况不在保证之内。不持 `SessionUse` 就启动回合的调用方,要么在启动期间持有该 Session(后台任务的唤醒取得 `SessionHold`,Scheduler 经 `sessions` 服务的运行取得租约),要么在关闭之后追加,而分支会拒绝。 2. **关闭。** 若 S 已加载,Agents 像 `session.close` 那样关闭它:业务关闭,不是卸载。各能力结算已接受的工作,写出终态事实,释放进程、FileStorage 租约和成员请求。关闭报告清理错误时记日志并继续删除:未能写出的事实会随其余部分一起删除。从关闭起 S 的槽位即关闭:无论行最终是否删除,S 在本进程内都不再加载(第 6 步)。 -3. **命令输出。** SessionStore 在改动任何行之前移除该 Session 的输出目录(ADR 013 D4):它自己的 `<数据库目录>/command-output//`、创建时为该 id 占下的 `<数据库目录>/command-output/.session-ids//`,以及它每一行路径所在的目录,因此分叉复制来的 `command-output//` 和 `.dim/exec///` 目录也覆盖在内。另一个 Session 仍在该目录下有行时,目录保留。SessionStore 的所有权锁把这次移除与第 4 步的删行跨 Session 串行化:否则两个并发删除可能都看到对方的行,都保留共享目录,提交后目录没有所有者。分叉步骤在复制时持有同一把锁并复制当前的全部输出行;一致由锁保证,而不是靠检查文件是否存在,因此运行中的命令在写出文件之前登记的行也会被复制,该命令创建的文件归分叉所有。`command-output` 目录通过 S 的资源节点上的 FileStorage(与 S5a 一样每次调用时查找)移除;`.dim/exec` 目录由 HostPlatform 移除,HostPlatform 不读取所有权行。目录不存在视为已移除。每次移除必须在第 4 步之前落盘(§4),因此 FileStorage 的 `remove` 要同步被移除条目的父目录(§14)。失败时删除在改动任何行之前结束(§3.5)。只有本数据库有 S 的行时,SessionStore 才移除自己的 `command-output//` 和该 id 的占位:`command-output/` 由同一目录下的所有数据库共用,本库没有行的 id,其目录可能属于另一个数据库的 Session(§4)。 +3. **命令输出。** SessionStore 在改动任何行之前移除该 Session 的输出目录(ADR 013 D4):它自己的 `<数据库目录>/command-output//`,以及它每一行路径所在的目录,因此分叉复制来的 `command-output//` 和 `.dim/exec///` 目录也覆盖在内。另一个 Session 仍在该目录下有行时,目录保留。SessionStore 的所有权锁把这次移除与第 4 步的删行跨 Session 串行化:否则两个并发删除可能都看到对方的行,都保留共享目录,提交后目录没有所有者。分叉步骤在复制时持有同一把锁并复制当前的全部输出行;一致由锁保证,而不是靠检查文件是否存在,因此运行中的命令在写出文件之前登记的行也会被复制,该命令创建的文件归分叉所有。`command-output` 目录通过 S 的资源节点上的 FileStorage(与 S5a 一样每次调用时查找)移除;`.dim/exec` 目录由 HostPlatform 移除,HostPlatform 不读取所有权行。目录不存在视为已移除。每次移除必须在第 4 步之前落盘(§4),因此 FileStorage 的 `remove` 要同步被移除条目的父目录(§14)。失败时删除在改动任何行之前结束(§3.5)。只有本数据库有 S 的行时,SessionStore 才移除自己的 `command-output//`:`command-output/` 由同一目录下的所有数据库共用,本库没有行的 id,其目录可能属于另一个数据库的 Session(§4)。 4. **行。** 一个 `IMMEDIATE` 事务删除使 S 可见的行:`session_file_owners`(S5a 释放其文件)、`session_output_owners`、`session_grants`、`session_worktrees`、S5b 的标题元数据(§14)、`session_catalog`([#556 的目录投影](../../../design/appserver/native-storage-format.md#556-v23-格式决定))、`session_owners`、`timeline_branches` 和 `agent_sessions`。`timeline_snapshots`、`timeline_events` 和 `timeline_content` 随后在复制连接上按有界事务删除,每个事务至多删除 256 行,其他 Session 的提交与发布因此能在其间进行(#599)。复制连接关闭外键,第一个事务才能先删掉其余删除所引用的行。该操作在 Timeline 写线程排空已为 S 排队的所有追加之后执行,并清除 S 记下的写入失败;删除与创建回滚共用它。见[存储格式 §SQLite 运行参数与空间回收](../../../design/appserver/native-storage-format.md#sqlite-运行参数与空间回收)。 5. **清扫。** SessionStore 安排 S5a 的清扫([Session 文件 §5.4](session-files.md#54-清扫))。最后一个所有者是 S 的文件在清扫中移除;仍有分叉拥有的文件保留。 6. **忘记。** Agents 删除 S 的协议版本和不可用 Session 条目,把 S 的槽位标为已关闭、已删除,并在没有其他东西持有它时移除它([空闲卸载 §6.4](idle-unload.md#64-准入槽))。仍在准入门处等待的调用方会看到槽位已关闭,之后的调用方会发现 S 既没有所有者也没有行:两种情况下 `acquire` 都回答 `session_closed`。在第 4 步之前失败的删除则释放准入门。被它关闭的 Session 保持 `session.close` 之后的状态:行还在,`session.summaries` 不列出它,本进程内不再加载,重试即可删除;重启后它照常加载。删除没有关闭的 Session 在下次使用时照常加载(§16 D5)。 @@ -99,7 +99,6 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | 标题元数据 | 原生存储,S5b 的 `session_metadata` 行([标题元数据](session-title-metadata.md#9-生命周期)) | 第 4 步,同一事务 | | Worktree 使用关联 | 原生存储,`session_worktrees` 行([worktree access §4](../../../design/worktree-access.md#4-持久使用关联与清理边界)) | 第 4 步,同一事务;保留目录记录与 worktree 文件 | | exec 输出、转存的 `read` 结果和持久 shell 日志 | `<数据库目录>/command-output//` 及 S 的输出行命名的每个目录 | 第 3 步。本数据库另一个 Session 仍命名的目录保留 | -| 创建时为该 id 占下的名字 | `<数据库目录>/command-output/.session-ids//` | 第 3 步。它不存输出,也没有自己的行;创建失败时由创建自己的清理移除 | | 已加载实例、租约、订阅、在途使用 | 进程内存 | 第 2 步 | | 协议版本、准入槽位、不可用 Session 条目 | Agents 内存 | 第 6 步 | | 指向 S 的 Collaboration 关系、S 领导的成员 Session 与 S 拥有的 Agent | 持久:`agent_sessions.leader_session_id` 与 `agents.owner_session_id`([Collaboration §6](../plugins/Collaboration.md#6-委派的所有权与寿命));Collaboration 的关系由它们重建 | Agents 随 leader 一起删除 Team:每个成员自己的删除(其行由 SessionStore 删除)、Agents 拥有的 Agent 记录,最后是 S。Collaboration 在观察到成员关闭([collaboration.rs](../../../../crates/dim-app-server/src/collaboration.rs) 的 `session_ended`)或删除已卸载成员时移除关系,装载时重建其余([空闲卸载 §7](idle-unload.md#7-竞争与交互)) | @@ -154,9 +153,9 @@ Rpc 检查参数和 Session 的协议版本,然后调用 Agents。Agents 负 | 提交之后、回复之前 | 无行 | 目录已无;S 的文件无所有者 | 客户端重试时本库已无行,不移除目录,得到 `{deleted: false}` 并再次安排清扫;否则由 S5a 的下一次触发(另一次删除,或之后某一代的第一次写入)移除文件 | | 清扫期间 | S5a 的状态 | — | [Session 文件 §6](session-files.md) 的崩溃恢复表 | -**为什么目录在提交之前移除。** S 自己的 `command-output//` 目录没有自己的行(只有其中的文件可能有),它在 `.session-ids/` 下的占位也没有。行删除之后,孤立的目录只能靠列出 `command-output/` 找到,而这个目录由同一数据库目录下的所有数据库共用(一个目录下两个 `--database` 文件),列目录无法区分已删除 Session 的目录和另一个存储的目录。先移除目录,任何已提交的删除都不会留下它。本数据库另一个 Session 仍命名的目录保留(ADR 013 D4):它仍能通过那个 Session 的行找到,下一次删除再移除它。S5a 的文件采用相反的顺序,因为有行记录它们,清扫能找到。FileStorage 的移除原本不同步([S6](https://github.com/arcships/dim/pull/87)):断电后,被移除的目录可能重新出现,而之后以 `synchronous=FULL` 提交的事务仍然有效。现在 `remove` 在返回前同步父目录(§14),消除了这个窗口;HostPlatform 对移除的 `.dim/exec` 目录也同步父目录。 +**为什么目录在提交之前移除。** S 自己的 `command-output//` 目录没有自己的行(只有其中的文件可能有)。行删除之后,孤立的目录只能靠列出 `command-output/` 找到,而这个目录由同一数据库目录下的所有数据库共用(一个目录下两个 `--database` 文件),列目录无法区分已删除 Session 的目录和另一个存储的目录。先移除目录,任何已提交的删除都不会留下它。本数据库另一个 Session 仍命名的目录保留(ADR 013 D4):它仍能通过那个 Session 的行找到,下一次删除再移除它。S5a 的文件采用相反的顺序,因为有行记录它们,清扫能找到。FileStorage 的移除原本不同步([S6](https://github.com/arcships/dim/pull/87)):断电后,被移除的目录可能重新出现,而之后以 `synchronous=FULL` 提交的事务仍然有效。现在 `remove` 在返回前同步父目录(§14),消除了这个窗口;HostPlatform 对移除的 `.dim/exec` 目录也同步父目录。 -**只移除本库有行的 id。** 出于同样的原因,只有本数据库有该 id 的行时,删除才移除它的目录和该 id 的占位。同一目录下 `a.sqlite` 和 `b.sqlite` 两个守护进程共用 `command-output/`;把 `session.delete {S_b}` 发给前者(例如 CLI 用错了 `--database`)时,它回复 `{deleted: false}`,不能移除仍在后者中运行的 S_b 的输出,也不能移除它的占位(那会让同名的新创建用上同一个目录)。这个检查不影响收敛:目录在行之前移除,所以本库没有 S 的行时,也已没有 S 的目录可移除;Agents 的准入门保证同一 id 的两次删除不会交错。因此提交之后的重试什么都不移除,也不需要移除。 +**只移除本库有行的 id。** 出于同样的原因,只有本数据库有该 id 的行时,删除才移除它的目录。同一目录下 `a.sqlite` 和 `b.sqlite` 两个守护进程共用 `command-output/`;把 `session.delete {S_b}` 发给前者(例如 CLI 用错了 `--database`)时,它回复 `{deleted: false}`,不能移除仍在后者中运行的 S_b 的输出。这个检查不影响收敛:目录在行之前移除,所以本库没有 S 的行时,也已没有 S 的目录可移除;Agents 的准入门保证同一 id 的两次删除不会交错。因此提交之后的重试什么都不移除,也不需要移除。 被否决的方案: @@ -355,7 +354,7 @@ S5c 中被否决:在 S 的分叉都删除之前保留 S 的命令输出。ADR | 删除的关闭发生在分叉检查切点期间 | 检查失败于 `session_closed` | | 写入与删除或分叉 | Session 文件 §6 | | 两次删除 | 第二次等准入门,然后发现没有行:`{deleted: false}` | -| 删除仍在构建的 Session:行已提交并已列出的 `session.create`、成员创建或分叉 | 创建在准备步骤之前就占下新 id 的输出名字,并从其行提交之前起持有新 id 的准入门,直到 Session 发布、协议版本记下为止(D6)。删除等待,然后关闭已发布的 Session 并删除其行和占位。创建失败时回滚它的行并释放占位,删除什么也找不到 | +| 删除仍在构建的 Session:行已提交并已列出的 `session.create`、成员创建或分叉 | 创建从其行提交之前起持有新 id 的准入门,直到 Session 发布、协议版本记下为止(D6)。删除等待,然后关闭已发布的 Session 并删除其行。创建失败时回滚它的行,删除什么也找不到 | | 删除与 attach、submit 或 Session 方法 | 它们等准入门,然后失败于 `session_closed`;已持有使用权的请求随关闭结束 | | 删除与该 Session 自己的追加 | 关闭结算它们;行事务在 Timeline 写线程上排在所有已排队的追加之后 | | 分叉与对源的追加 | `at` 及之前的行不变,分叉也不复制其后的任何行:子分支目录不带事件 | From fe40ba4700548f08a2b32ea76910944a7b458db6 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 10:05:20 +0800 Subject: [PATCH 21/23] refactor(runtime): generate the plain creation's Session id `CreateSessionOptions` no longer takes a standalone id: a plain creation is always created under a generated UUIDv4, and the only caller-named id is `prepare(id, step)`, whose step receives that same id. The App Server's prepared creation passes the id it generated with the step, and the flow test moves its explicit-id cases to `prepare` and asserts that two plain creations get distinct valid UUIDv4 ids. --- .../tests/agent_options_flow.rs | 96 ++++++++----------- crates/dim-agent-runtime/src/agent.rs | 44 ++++----- crates/dim-app-server/src/agents.rs | 28 +++--- 3 files changed, 74 insertions(+), 94 deletions(-) diff --git a/crates/dim-agent-capabilities/tests/agent_options_flow.rs b/crates/dim-agent-capabilities/tests/agent_options_flow.rs index 84a69a35bd..5b0cdf1983 100644 --- a/crates/dim-agent-capabilities/tests/agent_options_flow.rs +++ b/crates/dim-agent-capabilities/tests/agent_options_flow.rs @@ -190,8 +190,7 @@ async fn create_and_restore_options_apply_their_fields() { .create_session( SessionConfig::default(), CreateSessionOptions::default() - .id("named-session") - .prepare({ + .prepare("named-session", { let store = store.clone(); let prepared = prepared.clone(); move |id| { @@ -210,7 +209,7 @@ async fn create_and_restore_options_apply_their_fields() { assert_eq!( session.id(), "named-session", - "a prepared creation is created under the id the options name" + "a prepared creation is created under the id its options name" ); assert_eq!( *prepared.lock().unwrap(), @@ -224,45 +223,37 @@ async fn create_and_restore_options_apply_their_fields() { ); session.close().await.unwrap(); - let generated = Arc::new(Mutex::new(None::)); - let session = agent - .create_session( - SessionConfig::default(), - CreateSessionOptions::default().prepare({ - let store = store.clone(); - let generated = generated.clone(); - move |id| { - *generated.lock().unwrap() = Some(id.clone()); - let config = SessionConfig::default(); - Box::pin(async move { - store.create_session(&id, &config).await?; - Ok(()) - }) - } - }), - ) + let first = agent + .create_session(SessionConfig::default(), CreateSessionOptions::default()) .await .unwrap(); - assert_eq!( - generated.lock().unwrap().as_deref(), - Some(session.id()), - "a prepared creation without an id is created under a generated one, which the prepare step receives" - ); - session.close().await.unwrap(); - - let session = agent - .create_session( - SessionConfig::default(), - CreateSessionOptions::default().id("explicit-session"), - ) + let second = agent + .create_session(SessionConfig::default(), CreateSessionOptions::default()) .await .unwrap(); - assert_eq!( - session.id(), - "explicit-session", - "the options name a plain creation" + for session in [&first, &second] { + let id = uuid::Uuid::parse_str(session.id()) + .unwrap_or_else(|error| panic!("a plain creation is created under a UUID: {error}")); + assert_eq!( + id.get_version_num(), + 4, + "a plain creation is created under a UUIDv4: {}", + session.id() + ); + assert_eq!( + id.get_variant(), + uuid::Variant::RFC4122, + "a plain creation's id is an RFC 4122 UUID: {}", + session.id() + ); + } + assert_ne!( + first.id(), + second.id(), + "two plain creations are created under different ids" ); - session.close().await.unwrap(); + first.close().await.unwrap(); + second.close().await.unwrap(); store .create_session("stored", &SessionConfig::default()) @@ -305,9 +296,7 @@ async fn an_explicit_id_is_admitted_only_as_one_path_component() { agent .create_session( SessionConfig::default(), - CreateSessionOptions::default() - .id(id) - .prepare(preparing(&store, entered.clone())), + CreateSessionOptions::default().prepare(id, preparing(&store, entered.clone())), ) .await, ); @@ -324,18 +313,6 @@ async fn an_explicit_id_is_admitted_only_as_one_path_component() { "{id:?}: a rejected id publishes no Session" ); } - let error = rejected( - agent - .create_session( - SessionConfig::default(), - CreateSessionOptions::default().id("nested/plain"), - ) - .await, - ); - assert!( - matches!(&error, AgentError::InvalidInput(_)), - "a rejected id without a prepare step: {error}" - ); assert!( store.created.lock().unwrap().is_empty(), "a rejected id writes no rows: {:?}", @@ -349,7 +326,10 @@ async fn an_explicit_id_is_admitted_only_as_one_path_component() { let session = agent .create_session( SessionConfig::default(), - CreateSessionOptions::default().id("explicit-session"), + CreateSessionOptions::default().prepare( + "explicit-session", + preparing(&store, Arc::new(AtomicBool::new(false))), + ), ) .await .unwrap(); @@ -371,7 +351,10 @@ async fn a_rejected_duplicate_keeps_the_existing_sessions_state() { .agent() .create_session( SessionConfig::default(), - CreateSessionOptions::default().id("shared"), + CreateSessionOptions::default().prepare( + "shared", + preparing(&store, Arc::new(AtomicBool::new(false))), + ), ) .await .unwrap(); @@ -387,7 +370,10 @@ async fn a_rejected_duplicate_keeps_the_existing_sessions_state() { .agent() .create_session( SessionConfig::default(), - CreateSessionOptions::default().id("shared"), + CreateSessionOptions::default().prepare( + "shared", + preparing(&store, Arc::new(AtomicBool::new(false))), + ), ) .await, ); diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 60cb564ec4..aec0b77886 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -48,37 +48,28 @@ enum Cleanup { Rollback, Release, } -/// How [`Agent::create_session`] creates its Session: the id to create under, -/// the host-owned directory to prepare before publication, and the Session -/// extension to load. +/// How [`Agent::create_session`] creates its Session: the host-owned prepared +/// creation, which names the id it creates under, and the Session extension to +/// load. #[derive(Default)] pub struct CreateSessionOptions { - id: Option, - prepare: Option, + prepare: Option<(String, Preparation)>, extension: Option, } impl CreateSessionOptions { - /// Creates the Session under `id` instead of a generated one. A creation - /// that also [`prepare`](Self::prepare)s a Session hands the same id to - /// that step. + /// Creates the Session under `id` instead of the generated one: `prepare` + /// receives `id`, commits that id's rows, and creation loads them once it + /// completes. Without it, the Session is created under a generated UUIDv4. /// /// The id must be one normal path component, which is what Session /// command-output storage addresses ([`check_session_id`]); /// [`Agent::create_session`] rejects any other id before it prepares, /// writes or publishes. - pub fn id(mut self, id: impl Into) -> Self { - self.id = Some(id.into()); - self - } - /// Reserves runtime capacity before committing the host-owned directory: - /// `prepare` receives the id the Session is created under, commits that - /// id's rows, and creation loads them once it completes. The id is the - /// [`id`](Self::id) given, or a generated one. - pub fn prepare(mut self, prepare: F) -> Self + pub fn prepare(mut self, id: impl Into, prepare: F) -> Self where F: FnOnce(String) -> BoxFuture<'static, Result<()>> + Send + 'static, { - self.prepare = Some(Box::new(prepare)); + self.prepare = Some((id.into(), Box::new(prepare))); self } /// Loads the Session extension `group` ([`AgentBuilder::session_extension`]) @@ -141,18 +132,23 @@ impl Agent { pub fn faces(&self) -> &crate::Faces { self.0.builder.faces() } + /// Creates a Session. A prepared creation is created under the id its + /// [`CreateSessionOptions::prepare`] names; a plain creation is created + /// under a generated UUIDv4. pub async fn create_session( &self, config: SessionConfig, options: CreateSessionOptions, ) -> Result { - let id = options.id.unwrap_or_else(|| Uuid::new_v4().to_string()); - check_session_id(&id)?; - let start = match options.prepare { - Some(prepare) => SessionStart::Prepared(prepare), - None => SessionStart::Create, + let CreateSessionOptions { prepare, extension } = options; + let (id, start) = match prepare { + Some((id, prepare)) => { + check_session_id(&id)?; + (id, SessionStart::Prepared(prepare)) + } + None => (Uuid::new_v4().to_string(), SessionStart::Create), }; - self.create(id, config, start, options.extension).await + self.create(id, config, start, extension).await } /// Restores the original Session identity and its stored configuration, /// applying the projection gate [`RestoreSessionOptions`] names. diff --git a/crates/dim-app-server/src/agents.rs b/crates/dim-app-server/src/agents.rs index 67250c2823..ded1b0849b 100644 --- a/crates/dim-app-server/src/agents.rs +++ b/crates/dim-app-server/src/agents.rs @@ -1502,21 +1502,19 @@ impl AgentIndex { let id = uuid::Uuid::new_v4().to_string(); let settings = self.settings.clone(); let stopping = self.stopping.clone(); - let options = CreateSessionOptions::default() - .id(id.clone()) - .prepare(move |id: String| { - Box::pin(async move { - if let Some(settings) = settings { - settings - .authorize_project(cwd.into(), &stopping) - .await - .map_err(|error| { - AgentError::fault("project authorization", error.to_string()) - })?; - } - step(id).await - }) - }); + let options = CreateSessionOptions::default().prepare(id.clone(), move |id: String| { + Box::pin(async move { + if let Some(settings) = settings { + settings + .authorize_project(cwd.into(), &stopping) + .await + .map_err(|error| { + AgentError::fault("project authorization", error.to_string()) + })?; + } + step(id).await + }) + }); (id, options) } From 418f6ed770c3e30a30d4ffa8abde1c51a354a65e Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 11:03:06 +0800 Subject: [PATCH 22/23] test(integration): pass the Session options in the environment flows The integration flows added on main call the creation and restore entries with the previous arity, so they gain the options argument the rest of the workspace passes. --- .../integration/tests/environment_clients.rs | 22 ++++++++++++------- .../integration/tests/environment_settings.rs | 2 +- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/tests/integration/tests/environment_clients.rs b/tests/integration/tests/environment_clients.rs index e780a142c0..56935d6ecb 100644 --- a/tests/integration/tests/environment_clients.rs +++ b/tests/integration/tests/environment_clients.rs @@ -588,10 +588,13 @@ async fn a_line_opens_with_both_snapshots_while_a_later_batch_is_unpublished() { ) .await; let opener = host.agent().clone(); - let creation = opener.create_session(SessionConfig { - cwd: cwd.to_string_lossy().into_owned(), - ..SessionConfig::default() - }); + let creation = opener.create_session( + SessionConfig { + cwd: cwd.to_string_lossy().into_owned(), + ..SessionConfig::default() + }, + Default::default(), + ); tokio::pin!(creation); let mut held = None; let session = tokio::select! { @@ -806,10 +809,13 @@ async fn a_held_opening_fact_read_does_not_hold_a_line_open() { let session = host .agent() .clone() - .create_session(SessionConfig { - cwd: cwd.to_string_lossy().into_owned(), - ..SessionConfig::default() - }) + .create_session( + SessionConfig { + cwd: cwd.to_string_lossy().into_owned(), + ..SessionConfig::default() + }, + Default::default(), + ) .await .expect("the Session opens inside its shorter opening budget"); for (source, label) in [ diff --git a/tests/integration/tests/environment_settings.rs b/tests/integration/tests/environment_settings.rs index 79bb2c92c4..a5df224633 100644 --- a/tests/integration/tests/environment_settings.rs +++ b/tests/integration/tests/environment_settings.rs @@ -250,7 +250,7 @@ async fn a_held_settings_read_never_holds_a_branch_open() { let second = env(&dirs, options()).await; let session = second .agent - .restore_session(id) + .restore_session(id, Default::default()) .await .expect("the session restores while the settings read is held"); assert_eq!( From 08b73bfa8180a53e1a8a58de48a14150d3c1a440 Mon Sep 17 00:00:00 2001 From: huihui Date: Thu, 26 Nov 2026 11:23:48 +0800 Subject: [PATCH 23/23] docs(capabilities): pass creation options in the README example The README creation example passed only the configuration, so copying it no longer compiled and failed with E0061. It now passes CreateSessionOptions::default() and imports the type in the same example. --- crates/dim-agent-capabilities/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/dim-agent-capabilities/README.md b/crates/dim-agent-capabilities/README.md index 87ec43c4fc..8aff2643e5 100644 --- a/crates/dim-agent-capabilities/README.md +++ b/crates/dim-agent-capabilities/README.md @@ -4,7 +4,7 @@ ```rust,no_run use dim_agent_capabilities::defaults; -use dim_agent_runtime::{AgentBuilder, AgentConfig, SessionConfig}; +use dim_agent_runtime::{AgentBuilder, AgentConfig, CreateSessionOptions, SessionConfig}; use dim_agent_types::InputMode; # async fn example() -> dim_agent_runtime::Result<()> { @@ -12,7 +12,7 @@ let mut builder = AgentBuilder::new(AgentConfig::default()); defaults::mock_hosts(&mut builder); defaults::install(&mut builder); let agent = builder.build(); -let session = agent.create_session(SessionConfig::default()).await?; +let session = agent.create_session(SessionConfig::default(), CreateSessionOptions::default()).await?; session.submit("hello".into(), InputMode::Queue, "main").await?; session.idle("main").await?; agent.close().await?;