diff --git a/crates/mind-body/src/self_run.rs b/crates/mind-body/src/self_run.rs index 62ee9fb..6d8e6d4 100644 --- a/crates/mind-body/src/self_run.rs +++ b/crates/mind-body/src/self_run.rs @@ -279,10 +279,10 @@ pub enum Usage { TurnBegan, /// The CLI's level of background tasks (`background_tasks_changed`): `live` the `task_id` of every entry, `main` those of entries with no /// parent task that nobody awaits. - BackgroundTasks { live: Vec, main: Vec }, + BackgroundTasks { live: Vec, main: Vec, shell: Vec }, /// A task of the main session went to the background, by `task_id`: a `task_started` with `is_backgrounded` true and no parent task or /// awaiter, or a `task_updated` whose patch backgrounds it. - TaskBackgrounded { id: String }, + TaskBackgrounded { id: String, shell: bool }, /// A task notification, by `task_id`; `stopped`: its status is `stopped`. TaskNotified { id: String, stopped: bool }, /// The CLI replayed a task notification as a user line, taking it into a turn; the `` is the task's. @@ -320,6 +320,8 @@ pub fn read_usage(line: &str) -> Usage { let task_id = |object: &serde_json::Map| object.get("task_id").and_then(Value::as_str).map(String::from); // A task of the main session that nobody awaits: no parent task, `awaited` not true. let main = |object: &serde_json::Map| object.get("parent_task_id").is_none_or(Value::is_null) && object.get("awaited").and_then(Value::as_bool) != Some(true); + // The kind the CLI gives a task, `task_type`: only `local_bash` (a Bash task or a Monitor) is captured to get no turn when we stop it. + let shell = |object: &serde_json::Map| object.get("task_type").and_then(Value::as_str) == Some("local_bash"); match event.get("subtype").and_then(Value::as_str) { Some("init") => Usage::TurnBegan, Some("background_tasks_changed") => { @@ -327,10 +329,11 @@ pub fn read_usage(line: &str) -> Usage { Usage::BackgroundTasks { live: entries.iter().copied().filter_map(task_id).collect(), main: entries.iter().copied().filter(|entry| main(entry)).filter_map(task_id).collect(), + shell: entries.iter().copied().filter(|entry| shell(entry)).filter_map(task_id).collect(), } } - Some("task_started") if event.get("is_backgrounded").and_then(Value::as_bool) == Some(true) && main(&event) => task_id(&event).map_or(Usage::Other, |id| Usage::TaskBackgrounded { id }), - Some("task_updated") if event.get("patch").and_then(|patch| patch.get("is_backgrounded")).and_then(Value::as_bool) == Some(true) => task_id(&event).map_or(Usage::Other, |id| Usage::TaskBackgrounded { id }), + Some("task_started") if event.get("is_backgrounded").and_then(Value::as_bool) == Some(true) && main(&event) => task_id(&event).map_or(Usage::Other, |id| Usage::TaskBackgrounded { id, shell: shell(&event) }), + Some("task_updated") if event.get("patch").and_then(|patch| patch.get("is_backgrounded")).and_then(Value::as_bool) == Some(true) => task_id(&event).map_or(Usage::Other, |id| Usage::TaskBackgrounded { id, shell: false }), Some("task_notification") => task_id(&event).map_or(Usage::Other, |id| Usage::TaskNotified { id, stopped: event.get("status").and_then(Value::as_str) == Some("stopped") }), _ => Usage::Other, } diff --git a/crates/mind-body/src/self_run/claude-2.1.312-live-session-bg-agentstop.jsonl b/crates/mind-body/src/self_run/claude-2.1.312-live-session-bg-agentstop.jsonl new file mode 100644 index 0000000..9192be3 --- /dev/null +++ b/crates/mind-body/src/self_run/claude-2.1.312-live-session-bg-agentstop.jsonl @@ -0,0 +1,19 @@ +{"t": 0.0, "sent": "PLAN turn A."} +{"t": 0.34, "line": "{\"type\":\"system\",\"subtype\":\"init\",\"cwd\":\"/probe/work\",\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"tools\":[\"Task\",\"Bash\",\"CronCreate\",\"CronDelete\",\"CronList\",\"Edit\",\"EnterWorktree\",\"ExitWorktree\",\"ListAgents\",\"Monitor\",\"NotebookEdit\",\"Read\",\"ReportFindings\",\"ScheduleWakeup\",\"SendMessage\",\"Skill\",\"TaskStop\",\"ToolSearch\",\"WebFetch\",\"WebSearch\",\"Workflow\",\"Write\"],\"mcp_servers\":[],\"model\":\"claude-opus-5-5\",\"permissionMode\":\"bypassPermissions\",\"slash_commands\":[\"deep-research\",\"dataviz\",\"update-config\",\"verify\",\"debug\",\"code-review\",\"simplify\",\"batch\",\"fewer-permission-prompts\",\"doctor\",\"loop\",\"claude-api\",\"workflow-authoring\",\"run\",\"run-skill-generator\",\"plugin-authoring\",\"agents\",\"auto-mode-setup\",\"autocompact\",\"clear\",\"color\",\"config\",\"output-style\",\"context\",\"effort\",\"fast\",\"focus\",\"heapdump\",\"init\",\"mcp\",\"model\",\"__remote-workflow\",\"workflow-launch-exec\",\"reload-plugins\",\"reload-skills\",\"rename\",\"security-review\",\"usage\",\"insights\",\"recap\",\"goal\",\"list-agents\",\"team-onboarding\"],\"terminal_slash_commands\":[\"doctor\",\"color\",\"focus\",\"reload-plugins\"],\"apiKeySource\":\"ANTHROPIC_API_KEY\",\"claude_code_version\":\"2.1.312\",\"output_style\":\"default\",\"agents\":[\"claude\",\"Explore\",\"general-purpose\",\"Plan\",\"statusline-setup\"],\"skills\":[\"deep-research\",\"dataviz\",\"update-config\",\"verify\",\"debug\",\"code-review\",\"simplify\",\"batch\",\"fewer-permission-prompts\",\"doctor\",\"loop\",\"claude-api\",\"workflow-authoring\",\"run\",\"run-skill-generator\",\"plugin-authoring\"],\"plugins\":[{\"name\":\"cc-plugin-sec-default\",\"path\":\"builtin\",\"source\":\"cc-plugin-sec-default@builtin\"},{\"name\":\"cc-plugin-agents-md\",\"path\":\"builtin\",\"source\":\"cc-plugin-agents-md@builtin\"},{\"name\":\"cc-plugin-plugin-authoring\",\"path\":\"builtin\",\"source\":\"cc-plugin-plugin-authoring@builtin\"}],\"capabilities\":[\"interrupt_receipt_v1\",\"interrupt_cancel_queued_v1\",\"interrupt_send_now_v1\",\"interrupt_requeue_taken_v1\",\"msg_lifecycle_v1\",\"request_marker_lists_v1\",\"ask_user_question_unanswered_v1\",\"lifecycle_wakeup_source_v1\",\"sdk_mcp_tools_list_changed\",\"sdk_mcp_manifests\",\"mcp_read_resource_v1\",\"mcp_tool_ui_meta_v1\",\"ui_surface_v1\",\"mcp_call_result_not_for_model_v1\"],\"analytics_disabled\":true,\"product_feedback_disabled\":true,\"uuid\":\"525351a3-0d08-42f8-9edf-c814092c99ea\",\"memory_paths\":{\"auto\":\"/probe/cfg/projects/-probe-work/memory/\"},\"original_cwd\":\"/probe/work\",\"additional_directories\":[],\"messaging_socket_path\":\"/tmp/cc-socks/190923.sock\",\"fast_mode_state\":\"off\",\"fast_mode_disabled_reason\":\"sdk_opt_in_required\",\"per_turn_effort_active\":true,\"view_mode\":\"default\"}"} +{"t": 0.39, "line": "{\"type\":\"user\",\"message\":{\"role\":\"user\",\"content\":\"PLAN turn A.\"},\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"parent_tool_use_id\":null,\"uuid\":\"eff09b24-757e-462c-b6a6-064e395ffbd7\",\"timestamp\":\"2026-11-07T06:21:43.424Z\",\"isReplay\":true}"} +{"t": 0.4, "line": "{\"type\":\"assistant\",\"message\":{\"id\":\"msg_0001\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-opus-5-5\",\"content\":[{\"type\":\"tool_use\",\"id\":\"toolu_0001\",\"name\":\"Agent\",\"input\":{\"description\":\"probe agent\",\"prompt\":\"SUBTASK say done\",\"subagent_type\":\"general-purpose\",\"run_in_background\":true}}],\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":5,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0},\"context_management\":null},\"parent_tool_use_id\":null,\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"uuid\":\"65c9df5a-2126-49a9-a278-b32b553d0ac5\",\"timestamp\":\"2026-11-07T06:21:43.494Z\"}"} +{"t": 0.41, "line": "{\"type\":\"system\",\"subtype\":\"background_tasks_changed\",\"tasks\":[{\"task_id\":\"a916cb59a82a1fdcb\",\"run_id\":\"0mw60mr4l-c795f6ce\",\"task_type\":\"local_agent\",\"subagent_type\":\"general-purpose\",\"description\":\"probe agent\"}],\"uuid\":\"36fcb061-17f6-44e3-8093-0cff5e94e85e\",\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\"}"} +{"t": 0.41, "line": "{\"type\":\"system\",\"subtype\":\"task_started\",\"task_id\":\"a916cb59a82a1fdcb\",\"run_id\":\"0mw60mr4l-c795f6ce\",\"tool_use_id\":\"toolu_0001\",\"description\":\"probe agent\",\"subagent_type\":\"general-purpose\",\"is_backgrounded\":true,\"spawn_depth\":1,\"task_type\":\"local_agent\",\"prompt\":\"SUBTASK say done\",\"uuid\":\"bf5681bb-7464-4f95-9c0e-5b1793e746aa\",\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\"}"} +{"t": 0.43, "line": "{\"type\":\"user\",\"message\":{\"role\":\"user\",\"content\":[{\"tool_use_id\":\"toolu_0001\",\"type\":\"tool_result\",\"content\":[{\"type\":\"text\",\"text\":\"Async agent launched successfully. (This tool result is internal metadata \u2014 never quote or paste any part of it, including the agentId below, into a user-facing reply.)\\nagentId: a916cb59a82a1fdcb (internal ID - do not mention to user. Use SendMessage with to: 'a916cb59a82a1fdcb', summary: '<5-10 word recap>' to continue this agent.)\\nThe agent is working in the background. You will be notified automatically when it completes. You know nothing about its results until that notification arrives \u2014 do not report, assume, or predict them; continue other work or respond to the user in the meantime.\\nDo not duplicate this agent's work \u2014 avoid working with the same files or topics it is using.\\noutput_file: /tmp/claude-1000/-probe-work/07eda665-19c1-44b5-acb9-5e3359fe45e8/tasks/a916cb59a82a1fdcb.output\\nDo NOT Read or tail this file via the shell tool \u2014 it is the full subagent JSONL transcript and reading it will overflow your context. If the user asks for progress, say the agent is still running; you'll get a completion notification.\"}]}]},\"parent_tool_use_id\":null,\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"uuid\":\"a632d4c2-9565-449d-b348-362da20ca46d\",\"timestamp\":\"2026-11-07T06:21:43.522Z\",\"tool_use_result\":{\"isAsync\":true,\"status\":\"async_launched\",\"agentId\":\"a916cb59a82a1fdcb\",\"description\":\"probe agent\",\"resolvedModel\":\"claude-opus-5-5\",\"prompt\":\"SUBTASK say done\",\"outputFile\":\"/tmp/claude-1000/-probe-work/07eda665-19c1-44b5-acb9-5e3359fe45e8/tasks/a916cb59a82a1fdcb.output\",\"canReadOutputFile\":true,\"canContinueAgent\":true},\"tool_result_meta\":[{\"id\":\"toolu_0001\",\"permission_decision\":{\"decision\":\"accept\",\"source\":\"config\",\"reason_type\":\"mode\"}}]}"} +{"t": 0.49, "line": "{\"type\":\"assistant\",\"message\":{\"id\":\"msg_0003\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-opus-5-5\",\"content\":[{\"type\":\"tool_use\",\"id\":\"toolu_0003\",\"name\":\"TaskStop\",\"input\":{\"task_id\":\"a916cb59a82a1fdcb\"}}],\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":5,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0},\"context_management\":null},\"parent_tool_use_id\":null,\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"uuid\":\"3736fcc5-5360-4afc-a5ee-a19de37fc65c\",\"timestamp\":\"2026-11-07T06:21:43.589Z\"}"} +{"t": 0.49, "line": "{\"type\":\"system\",\"subtype\":\"task_updated\",\"task_id\":\"a916cb59a82a1fdcb\",\"run_id\":\"0mw60mr4l-c795f6ce\",\"patch\":{\"status\":\"killed\",\"end_time\":1794032503594},\"uuid\":\"49a01831-d82a-4963-b7ec-0f8209d1b06a\",\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\"}"} +{"t": 0.49, "line": "{\"type\":\"system\",\"subtype\":\"task_notification\",\"task_id\":\"a916cb59a82a1fdcb\",\"run_id\":\"0mw60mr4l-c795f6ce\",\"tool_use_id\":\"toolu_0001\",\"status\":\"stopped\",\"output_file\":\"/tmp/claude-1000/-probe-work/07eda665-19c1-44b5-acb9-5e3359fe45e8/tasks/a916cb59a82a1fdcb.output\",\"summary\":\"probe agent\",\"uuid\":\"3aeca1cb-a83b-4c76-bd85-7f2b9c5f5e79\",\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\"}"} +{"t": 0.49, "line": "{\"type\":\"system\",\"subtype\":\"background_tasks_changed\",\"tasks\":[],\"uuid\":\"6c419115-d457-4098-858a-790e415b58b4\",\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\"}"} +{"t": 0.5, "line": "{\"type\":\"user\",\"message\":{\"role\":\"user\",\"content\":[{\"tool_use_id\":\"toolu_0003\",\"type\":\"tool_result\",\"content\":\"{\\\"message\\\":\\\"Successfully stopped task: a916cb59a82a1fdcb (probe agent)\\\",\\\"task_id\\\":\\\"a916cb59a82a1fdcb\\\",\\\"task_type\\\":\\\"local_agent\\\",\\\"command\\\":\\\"probe agent\\\"}\"}]},\"parent_tool_use_id\":null,\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"uuid\":\"1afff4fa-799d-4356-b8b6-630f97165045\",\"timestamp\":\"2026-11-07T06:21:43.596Z\",\"tool_use_result\":{\"message\":\"Successfully stopped task: a916cb59a82a1fdcb (probe agent)\",\"task_id\":\"a916cb59a82a1fdcb\",\"task_type\":\"local_agent\",\"command\":\"probe agent\"},\"tool_result_meta\":[{\"id\":\"toolu_0003\",\"permission_decision\":{\"decision\":\"accept\",\"source\":\"config\",\"reason_type\":\"mode\"}}]}"} +{"t": 0.51, "line": "{\"type\":\"user\",\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"text\",\"text\":\"[Request interrupted by user]\"}]},\"parent_tool_use_id\":\"toolu_0001\",\"agent_id\":\"a916cb59a82a1fdcb\",\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"uuid\":\"198f58f3-772b-4e5c-a420-f06c323890ac\",\"timestamp\":\"2026-11-07T06:21:43.609Z\",\"subagent_type\":\"general-purpose\",\"task_description\":\"probe agent\"}"} +{"t": 0.52, "line": "{\"type\":\"assistant\",\"message\":{\"id\":\"msg_0004\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-opus-5-5\",\"content\":[{\"type\":\"text\",\"text\":\"ANSWER to request 4\"}],\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":5,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0},\"context_management\":null},\"parent_tool_use_id\":null,\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"uuid\":\"2757583d-d4cc-4154-a18c-97060c37cade\",\"timestamp\":\"2026-11-07T06:21:43.618Z\"}"} +{"t": 0.52, "line": "{\"duration_api_ms\":79,\"stop_reason\":\"end_turn\",\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"total_cost_usd\":0.00042,\"usage\":{\"input_tokens\":30,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0,\"output_tokens\":15,\"output_tokens_details\":{\"thinking_tokens\":0},\"server_tool_use\":{\"web_search_requests\":0,\"web_fetch_requests\":0},\"service_tier\":\"standard\",\"cache_creation\":{\"ephemeral_1h_input_tokens\":0,\"ephemeral_5m_input_tokens\":0},\"inference_geo\":\"\",\"iterations\":[],\"speed\":\"standard\",\"fallback_credit\":null},\"modelUsage\":{\"claude-opus-5-5\":{\"inputTokens\":30,\"outputTokens\":15,\"cacheReadInputTokens\":0,\"cacheCreationInputTokens\":0,\"webSearchRequests\":0,\"costUSD\":0.00042,\"contextWindow\":1000000,\"maxOutputTokens\":128000,\"thinkingTokens\":0,\"cacheCreationEphemeral5mInputTokens\":0,\"cacheCreationEphemeral1hInputTokens\":0,\"canonicalModel\":\"claude-opus-5-5\",\"provider\":\"firstParty\",\"costBasis\":\"list\"}},\"permission_denials\":[],\"terminal_reason\":\"completed\",\"fast_mode_state\":\"off\",\"fast_mode_disabled_reason\":\"sdk_opt_in_required\",\"subagent_stats\":{\"spawned\":1,\"requested\":{\"background\":1,\"foreground\":0,\"unset\":0},\"started_in_background\":1,\"max_depth\":1,\"spawned_by_subagents\":0,\"completed\":0,\"failed\":0,\"killed\":{\"parent\":1,\"user\":0,\"system\":0},\"refused\":{\"depth_limit\":0,\"concurrency_limit\":0,\"budget\":0},\"by_type\":{\"general-purpose\":1}},\"safety_stops\":0,\"is_error\":false,\"num_turns\":3,\"subtype\":\"success\",\"api_error_status\":null,\"result\":\"ANSWER to request 4\",\"ttft_ms\":97,\"type\":\"result\",\"duration_ms\":227,\"uuid\":\"08980920-e457-49ef-8a8e-7d97f02a4ba9\",\"ttft_stream_ms\":96,\"time_to_request_ms\":89,\"first_content_frame_ms\":96,\"queued_turn_count\":0,\"result_index\":0,\"model_usage_since_last_result\":{\"claude-opus-5-5\":{\"inputTokens\":30,\"outputTokens\":15,\"cacheReadInputTokens\":0,\"cacheCreationInputTokens\":0,\"webSearchRequests\":0,\"costUSD\":0.00042,\"contextWindow\":1000000,\"maxOutputTokens\":128000,\"thinkingTokens\":0,\"cacheCreationEphemeral5mInputTokens\":0,\"cacheCreationEphemeral1hInputTokens\":0,\"canonicalModel\":\"claude-opus-5-5\",\"provider\":\"firstParty\",\"costBasis\":\"list\"}}}"} +{"t": 0.54, "line": "{\"type\":\"system\",\"subtype\":\"init\",\"cwd\":\"/probe/work\",\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"tools\":[\"Task\",\"Bash\",\"CronCreate\",\"CronDelete\",\"CronList\",\"Edit\",\"EnterWorktree\",\"ExitWorktree\",\"ListAgents\",\"Monitor\",\"NotebookEdit\",\"Read\",\"ReportFindings\",\"ScheduleWakeup\",\"SendMessage\",\"Skill\",\"TaskStop\",\"ToolSearch\",\"WebFetch\",\"WebSearch\",\"Workflow\",\"Write\"],\"mcp_servers\":[],\"model\":\"claude-opus-5-5\",\"permissionMode\":\"bypassPermissions\",\"slash_commands\":[\"deep-research\",\"dataviz\",\"update-config\",\"verify\",\"debug\",\"code-review\",\"simplify\",\"batch\",\"fewer-permission-prompts\",\"doctor\",\"loop\",\"claude-api\",\"workflow-authoring\",\"run\",\"run-skill-generator\",\"plugin-authoring\",\"agents\",\"auto-mode-setup\",\"autocompact\",\"clear\",\"color\",\"config\",\"output-style\",\"context\",\"effort\",\"fast\",\"focus\",\"heapdump\",\"init\",\"mcp\",\"model\",\"__remote-workflow\",\"workflow-launch-exec\",\"reload-plugins\",\"reload-skills\",\"rename\",\"security-review\",\"usage\",\"insights\",\"recap\",\"goal\",\"list-agents\",\"team-onboarding\"],\"terminal_slash_commands\":[\"doctor\",\"color\",\"focus\",\"reload-plugins\"],\"apiKeySource\":\"ANTHROPIC_API_KEY\",\"claude_code_version\":\"2.1.312\",\"output_style\":\"default\",\"agents\":[\"claude\",\"Explore\",\"general-purpose\",\"Plan\",\"statusline-setup\"],\"skills\":[\"deep-research\",\"dataviz\",\"update-config\",\"verify\",\"debug\",\"code-review\",\"simplify\",\"batch\",\"fewer-permission-prompts\",\"doctor\",\"loop\",\"claude-api\",\"workflow-authoring\",\"run\",\"run-skill-generator\",\"plugin-authoring\"],\"plugins\":[{\"name\":\"cc-plugin-sec-default\",\"path\":\"builtin\",\"source\":\"cc-plugin-sec-default@builtin\"},{\"name\":\"cc-plugin-agents-md\",\"path\":\"builtin\",\"source\":\"cc-plugin-agents-md@builtin\"},{\"name\":\"cc-plugin-plugin-authoring\",\"path\":\"builtin\",\"source\":\"cc-plugin-plugin-authoring@builtin\"}],\"capabilities\":[\"interrupt_receipt_v1\",\"interrupt_cancel_queued_v1\",\"interrupt_send_now_v1\",\"interrupt_requeue_taken_v1\",\"msg_lifecycle_v1\",\"request_marker_lists_v1\",\"ask_user_question_unanswered_v1\",\"lifecycle_wakeup_source_v1\",\"sdk_mcp_tools_list_changed\",\"sdk_mcp_manifests\",\"mcp_read_resource_v1\",\"mcp_tool_ui_meta_v1\",\"ui_surface_v1\",\"mcp_call_result_not_for_model_v1\"],\"analytics_disabled\":true,\"product_feedback_disabled\":true,\"uuid\":\"6ce205fa-01fe-4360-8b2a-41d615da2f9d\",\"memory_paths\":{\"auto\":\"/probe/cfg/projects/-probe-work/memory/\"},\"original_cwd\":\"/probe/work\",\"additional_directories\":[],\"messaging_socket_path\":\"/tmp/cc-socks/190923.sock\",\"fast_mode_state\":\"off\",\"fast_mode_disabled_reason\":\"sdk_opt_in_required\",\"per_turn_effort_active\":true,\"view_mode\":\"default\"}"} +{"t": 0.55, "line": "{\"type\":\"assistant\",\"message\":{\"id\":\"msg_0005\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-opus-5-5\",\"content\":[{\"type\":\"text\",\"text\":\"ANSWER to request 5\"}],\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":10,\"output_tokens\":5,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0},\"context_management\":null},\"parent_tool_use_id\":null,\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"uuid\":\"b97630f6-934d-466e-9880-573bc10f9897\",\"timestamp\":\"2026-11-07T06:21:43.649Z\"}"} +{"t": 0.55, "line": "{\"duration_api_ms\":87,\"stop_reason\":\"end_turn\",\"session_id\":\"07eda665-19c1-44b5-acb9-5e3359fe45e8\",\"total_cost_usd\":0.0005600000000000001,\"usage\":{\"input_tokens\":10,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0,\"output_tokens\":5,\"output_tokens_details\":{\"thinking_tokens\":0},\"server_tool_use\":{\"web_search_requests\":0,\"web_fetch_requests\":0},\"service_tier\":\"standard\",\"cache_creation\":{\"ephemeral_1h_input_tokens\":0,\"ephemeral_5m_input_tokens\":0},\"inference_geo\":\"\",\"iterations\":[],\"speed\":\"standard\",\"fallback_credit\":null},\"modelUsage\":{\"claude-opus-5-5\":{\"inputTokens\":40,\"outputTokens\":20,\"cacheReadInputTokens\":0,\"cacheCreationInputTokens\":0,\"webSearchRequests\":0,\"costUSD\":0.0005600000000000001,\"contextWindow\":1000000,\"maxOutputTokens\":128000,\"thinkingTokens\":0,\"cacheCreationEphemeral5mInputTokens\":0,\"cacheCreationEphemeral1hInputTokens\":0,\"canonicalModel\":\"claude-opus-5-5\",\"provider\":\"firstParty\",\"costBasis\":\"list\"}},\"permission_denials\":[],\"terminal_reason\":\"completed\",\"fast_mode_state\":\"off\",\"fast_mode_disabled_reason\":\"sdk_opt_in_required\",\"origin\":{\"kind\":\"task-notification\",\"producer\":\"session-task\",\"runId\":\"0mw60mr4l-c795f6ce\"},\"subagent_stats\":{\"spawned\":1,\"requested\":{\"background\":1,\"foreground\":0,\"unset\":0},\"started_in_background\":1,\"max_depth\":1,\"spawned_by_subagents\":0,\"completed\":0,\"failed\":0,\"killed\":{\"parent\":1,\"user\":0,\"system\":0},\"refused\":{\"depth_limit\":0,\"concurrency_limit\":0,\"budget\":0},\"by_type\":{\"general-purpose\":1}},\"safety_stops\":0,\"is_error\":false,\"num_turns\":1,\"subtype\":\"success\",\"api_error_status\":null,\"result\":\"ANSWER to request 5\",\"ttft_ms\":21,\"type\":\"result\",\"duration_ms\":25,\"uuid\":\"c79fd15e-f5b1-42b4-8178-1e1d57d9bf00\",\"ttft_stream_ms\":21,\"time_to_request_ms\":19,\"first_content_frame_ms\":21,\"queued_turn_count\":0,\"result_index\":1,\"model_usage_since_last_result\":{\"claude-opus-5-5\":{\"inputTokens\":10,\"outputTokens\":5,\"cacheReadInputTokens\":0,\"cacheCreationInputTokens\":0,\"webSearchRequests\":0,\"costUSD\":0.00014000000000000001,\"contextWindow\":1000000,\"maxOutputTokens\":128000,\"thinkingTokens\":0,\"cacheCreationEphemeral5mInputTokens\":0,\"cacheCreationEphemeral1hInputTokens\":0,\"canonicalModel\":\"claude-opus-5-5\",\"provider\":\"firstParty\",\"costBasis\":\"list\"}}}"} +{"t": 25.03, "exit": 0} diff --git a/crates/mind-body/src/self_run/decide.rs b/crates/mind-body/src/self_run/decide.rs index fad5dba..372efc8 100644 --- a/crates/mind-body/src/self_run/decide.rs +++ b/crates/mind-body/src/self_run/decide.rs @@ -78,9 +78,9 @@ pub(super) enum Event { /// The CLI began a turn (its `system` init line). TurnBegan, /// The CLI's level of background tasks (`background_tasks_changed`): `live` every task in it, `main` those of the main session that nobody awaits. - BackgroundTasks { live: Vec, main: Vec }, + BackgroundTasks { live: Vec, main: Vec, shell: Vec }, /// A task of the main session went to the background (`task_started` backgrounded, or a `task_updated` that backgrounded it), by `task_id`. - TaskBackgrounded { id: String }, + TaskBackgrounded { id: String, shell: bool }, /// A task notification came (`task_notification`), by `task_id`; `stopped`: its status says it was stopped. TaskNotified { id: String, stopped: bool }, /// The CLI replayed a task notification as a user line: it took that notification into a turn, by `task_id`. Never one of our echoes. @@ -155,6 +155,8 @@ pub(super) struct State { running: BTreeSet, /// Tasks the main session ever backgrounded (the CLI's own SDK consumer's rule), by `task_id`: a monotone cache of the stream. backgrounded: BTreeSet, + /// Tasks the CLI's `task_type` calls `local_bash` (a Bash task or a Monitor), by `task_id`: the only kinds captured to get no turn when we stop them. + shell: BTreeSet, /// Tasks a `TaskStop` call of ours named: the CLI's stop tells the model nothing, so such a notification owes no turn. stopped_by_us: BTreeSet, /// Notifications of backgrounded tasks that have not yet been given their turn, by `task_id`. @@ -327,17 +329,21 @@ pub(super) fn decide(mut state: State, event: Event, now: DateTime) -> (Sta let mut action = Action::None; match event { Event::TurnBegan => state.open_turn(None), - Event::BackgroundTasks { live, main } => { + Event::BackgroundTasks { live, main, shell } => { state.running = live.into_iter().collect(); state.backgrounded.extend(main); + state.shell.extend(shell); } - Event::TaskBackgrounded { id } => { + Event::TaskBackgrounded { id, shell } => { + if shell { + state.shell.insert(id.clone()); + } state.backgrounded.insert(id); } - // The CLI's rule: a backgrounded task's notification is given a turn, except that of a stop the model asked for itself. A foreground, + // The CLI's rule: a backgrounded task's notification is given a turn, except that of a stop the model asked for itself of a shell task (any other kind, or an unread one, gets its turn when stopped as when ended). A foreground, // subagent-owned, awaited or unknown task owes nothing; a stop the CLI made on its own (a deadline, memory pressure) owes its turn. Event::TaskNotified { id, stopped } => { - if state.backgrounded.contains(&id) && !(stopped && state.stopped_by_us.contains(&id)) { + if state.backgrounded.contains(&id) && !(stopped && state.stopped_by_us.contains(&id) && state.shell.contains(&id)) { let since = state.turns; state.owed.insert(id, Owed { since, taken: false }); } diff --git a/crates/mind-body/src/self_run/decide/tests.rs b/crates/mind-body/src/self_run/decide/tests.rs index 5199f0d..9179823 100644 --- a/crates/mind-body/src/self_run/decide/tests.rs +++ b/crates/mind-body/src/self_run/decide/tests.rs @@ -517,11 +517,17 @@ fn a_flush_already_written_ends_the_session_by_itself_and_a_yield_does_not_cut_i /// The CLI's level after a background task of the main session came in: it is in the level and the session backgrounded it. fn level(ids: &[&str]) -> Event { let live: Vec = ids.iter().map(|id| id.to_string()).collect(); - Event::BackgroundTasks { main: live.clone(), live } + Event::BackgroundTasks { main: live.clone(), shell: live.clone(), live } } +/// A shell task (the CLI's `task_type` `local_bash`) of the main session went to the background. fn backgrounded(id: &str) -> Event { - Event::TaskBackgrounded { id: id.to_string() } + Event::TaskBackgrounded { id: id.to_string(), shell: true } +} + +/// A task of any other kind (an agent, a workflow, a remote one, or one whose kind the stream did not give). +fn backgrounded_other(id: &str) -> Event { + Event::TaskBackgrounded { id: id.to_string(), shell: false } } fn notified(id: &str) -> Event { @@ -620,7 +626,7 @@ fn the_level_is_replaced_whole_and_an_edge_line_never_edits_it() { assert!(running(vec![(backgrounded("t"), 1), (notified("t"), 2), (stopped("t"), 3)]).is_empty(), "nothing enters the level by an edge"); assert_eq!(running(vec![(level(&["t"]), 1), (backgrounded("u"), 2), (notified("t"), 3), (stopped("u"), 3)]), ["t"], "nothing leaves it by an edge"); // A subagent's or an awaited task is in the level (it holds idleness) but is not the main session's: it is never backgrounded. - let (state, _) = run(vec![(Event::BackgroundTasks { live: vec!["t".into(), "s".into()], main: vec!["t".into()] }, 1)]); + let (state, _) = run(vec![(Event::BackgroundTasks { live: vec!["t".into(), "s".into()], main: vec!["t".into()], shell: vec![] }, 1)]); assert_eq!(state.running.len(), 2); assert_eq!(state.backgrounded.into_iter().collect::>(), ["t"]); } @@ -631,12 +637,14 @@ fn a_notification_owes_a_turn_when_the_task_was_backgrounded_unless_the_session_ assert!(owes(vec![(backgrounded("t"), 3), (notified("t"), 4)]), "a backgrounded task's notification owes its turn"); assert!(owes(vec![(level(&["t"]), 3), (notified("t"), 4)]), "the level's main entry is backgrounded"); assert!(!owes(vec![(notified("t"), 4)]), "a task never backgrounded (foreground, or unknown) owes nothing"); - assert!(!owes(vec![(Event::BackgroundTasks { live: vec!["s".into()], main: vec![] }, 3), (notified("s"), 4)]), "a subagent's or an awaited task owes nothing"); + assert!(!owes(vec![(Event::BackgroundTasks { live: vec!["s".into()], main: vec![], shell: vec![] }, 3), (notified("s"), 4)]), "a subagent's or an awaited task owes nothing"); // A stop of ours: the model was told nothing but the call's result, so no turn follows. assert!(!owes(vec![(backgrounded("t"), 3), (stops_of("b", &["t"]), 3), (stopped("t"), 4)]), "a stop the session asked for owes nothing"); // A stop the CLI made on its own, a stop of another task, and a task that finished before our stop took hold, owe their turns. assert!(owes(vec![(backgrounded("t"), 3), (stopped("t"), 4)]), "a stop the session did not ask for owes its turn"); assert!(owes(vec![(backgrounded("t"), 3), (stops_of("b", &["other"]), 3), (stopped("t"), 4)])); + assert!(owes(vec![(backgrounded_other("t"), 3), (stops_of("b", &["t"]), 3), (stopped("t"), 4)]), "a stop of ours owes nothing only for a shell task: any other kind gets its turn"); + assert!(owes(vec![(Event::BackgroundTasks { live: vec!["t".into()], main: vec!["t".into()], shell: vec![] }, 3), (stops_of("b", &["t"]), 3), (stopped("t"), 4)]), "a level entry of another or unread kind gets its turn"); assert!(owes(vec![(backgrounded("t"), 3), (stops_of("b", &["t"]), 3), (notified("t"), 4)]), "a task that completed is told in its own turn: only a status of stopped is ours"); // The stop is read from any line of the turn, including a request line already seen. let (state, _) = run(vec![(req("a", 10), 1), (stops_of("a", &["t"]), 1)]); diff --git a/crates/mind-body/src/self_run/session.rs b/crates/mind-body/src/self_run/session.rs index 56c7171..d7179a8 100644 --- a/crates/mind-body/src/self_run/session.rs +++ b/crates/mind-body/src/self_run/session.rs @@ -80,8 +80,8 @@ pub(crate) fn drive(clock: &dyn Clock, mut child: Box, inbox: &mut dy Event::Echo } Usage::TurnBegan => Event::TurnBegan, - Usage::BackgroundTasks { live, main } => Event::BackgroundTasks { live, main }, - Usage::TaskBackgrounded { id } => Event::TaskBackgrounded { id }, + Usage::BackgroundTasks { live, main, shell } => Event::BackgroundTasks { live, main, shell }, + Usage::TaskBackgrounded { id, shell } => Event::TaskBackgrounded { id, shell }, Usage::TaskNotified { id, stopped } => Event::TaskNotified { id, stopped }, Usage::NotificationTaken { id } => Event::NotificationTaken { id }, Usage::Result { ok, blocked } => { diff --git a/crates/mind-body/src/self_run/tests.rs b/crates/mind-body/src/self_run/tests.rs index b83ebef..c4ea7cd 100644 --- a/crates/mind-body/src/self_run/tests.rs +++ b/crates/mind-body/src/self_run/tests.rs @@ -1575,8 +1575,8 @@ mod live_session { Usage::Request { id, prefix, stops } => (format!("request:{prefix}"), Fact::Request { id, prefix, stops }), Usage::Echo => ("echo".to_string(), Fact::Echo), Usage::TurnBegan => ("turn".to_string(), Fact::TurnBegan), - Usage::BackgroundTasks { live, main } => ("level".to_string(), Fact::BackgroundTasks { live, main }), - Usage::TaskBackgrounded { id } => ("backgrounded".to_string(), Fact::TaskBackgrounded { id }), + Usage::BackgroundTasks { live, main, shell } => ("level".to_string(), Fact::BackgroundTasks { live, main, shell }), + Usage::TaskBackgrounded { id, shell } => ("backgrounded".to_string(), Fact::TaskBackgrounded { id, shell }), Usage::TaskNotified { id, stopped } => ("notified".to_string(), Fact::TaskNotified { id, stopped }), Usage::NotificationTaken { id } => ("taken".to_string(), Fact::NotificationTaken { id }), Usage::Result { ok, blocked } => (format!("result:{}", if blocked { "blocked" } else if ok { "ok" } else { "error" }), Fact::Result { ok, blocked, ttl_1h }), @@ -1738,14 +1738,14 @@ mod live_session { // A persistent monitor: notice turns the CLI begins while its task stays in the level, then the notification and the level's end. assert_eq!(significant(&replay(BG_MONITOR)).iter().filter(|kind| **kind == "level").count(), 2); let task = |usage: &Usage| match usage { - Usage::TaskBackgrounded { id } | Usage::TaskNotified { id, .. } | Usage::NotificationTaken { id } => Some(id.clone()), + Usage::TaskBackgrounded { id, .. } | Usage::TaskNotified { id, .. } | Usage::NotificationTaken { id } => Some(id.clone()), _ => None, }; let fold = usages(BG_FOLD); let ids: Vec = fold.iter().filter_map(task).collect(); assert_eq!(ids.len(), 3, "backgrounded, notified, taken"); assert!(ids.iter().all(|id| *id == ids[0]) && !ids[0].starts_with("toolu_"), "one task_id names the task at its three lines: {ids:?}"); - assert!(fold.contains(&Usage::BackgroundTasks { live: vec![ids[0].clone()], main: vec![ids[0].clone()] }) && fold.contains(&Usage::BackgroundTasks { live: vec![], main: vec![] })); + assert!(fold.contains(&Usage::BackgroundTasks { live: vec![ids[0].clone()], main: vec![ids[0].clone()], shell: vec![ids[0].clone()] }) && fold.contains(&Usage::BackgroundTasks { live: vec![], main: vec![], shell: vec![] })); // A task that went to the background at its timeout was announced foreground and is backgrounded by the update that moved it: the start is no reading. let fgto = usages(BG_FGTO); let moved: Vec<&Usage> = fgto.iter().filter(|usage| matches!(usage, Usage::TaskBackgrounded { .. })).collect(); @@ -1753,19 +1753,21 @@ mod live_session { assert!(fgto.iter().any(|usage| matches!(usage, Usage::TaskNotified { stopped: false, .. }))); // A stop is a notification whose status is stopped, and the TaskStop call on the request line names the task. let kill = usages(BG_KILL); - let Some(Usage::TaskBackgrounded { id: killed }) = kill.iter().find(|usage| matches!(usage, Usage::TaskBackgrounded { .. })) else { panic!("{kill:?}") }; + let Some(Usage::TaskBackgrounded { id: killed, shell: true }) = kill.iter().find(|usage| matches!(usage, Usage::TaskBackgrounded { .. })) else { panic!("{kill:?}") }; assert!(kill.contains(&Usage::TaskNotified { id: killed.clone(), stopped: true })); assert!(kill.iter().any(|usage| matches!(usage, Usage::Request { stops, .. } if stops == std::slice::from_ref(killed))), "{kill:?}"); assert_eq!(kill.iter().filter(|usage| matches!(usage, Usage::Request { stops, .. } if !stops.is_empty())).count(), 1); // The level's `main` leaves out a subagent's and an awaited task; a start under a parent task, or awaited, or in the foreground, is no reading. - let changed = json!({"type": "system", "subtype": "background_tasks_changed", "tasks": [{"task_id": "m"}, {"task_id": "s", "parent_task_id": "p"}, {"task_id": "w", "awaited": true}, {"task_id": "n", "parent_task_id": null, "awaited": false}]}).to_string(); - assert_eq!(read_usage(&changed), Usage::BackgroundTasks { live: vec!["m".into(), "s".into(), "w".into(), "n".into()], main: vec!["m".into(), "n".into()] }); + let changed = json!({"type": "system", "subtype": "background_tasks_changed", "tasks": [{"task_id": "m", "task_type": "local_bash"}, {"task_id": "s", "parent_task_id": "p", "task_type": "local_agent"}, {"task_id": "w", "awaited": true}, {"task_id": "n", "parent_task_id": null, "awaited": false}]}).to_string(); + assert_eq!(read_usage(&changed), Usage::BackgroundTasks { live: vec!["m".into(), "s".into(), "w".into(), "n".into()], main: vec!["m".into(), "n".into()], shell: vec!["m".into()] }); let started = |extra: Value| { let mut line = json!({"type": "system", "subtype": "task_started", "task_id": "t", "is_backgrounded": true}); line.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); read_usage(&line.to_string()) }; - assert_eq!(started(json!({})), Usage::TaskBackgrounded { id: "t".into() }); + assert_eq!(started(json!({})), Usage::TaskBackgrounded { id: "t".into(), shell: false }, "no task_type is no shell"); + assert_eq!(started(json!({"task_type": "local_bash"})), Usage::TaskBackgrounded { id: "t".into(), shell: true }); + assert_eq!(started(json!({"task_type": "local_agent"})), Usage::TaskBackgrounded { id: "t".into(), shell: false }); assert_eq!(started(json!({"is_backgrounded": false})), Usage::Other, "a foreground task is no reading"); assert_eq!(started(json!({"parent_task_id": "p"})), Usage::Other); assert_eq!(started(json!({"awaited": true})), Usage::Other); @@ -1792,7 +1794,7 @@ mod live_session { let usages = usages(BG_AGENT); // One task_id names the task at its start and at its notification. let ids: Vec<&Usage> = usages.iter().filter(|usage| matches!(usage, Usage::TaskBackgrounded { .. } | Usage::TaskNotified { .. })).collect(); - assert!(matches!(ids[..], [Usage::TaskBackgrounded { id: started }, Usage::TaskNotified { id: ended, stopped: false }] if started == ended), "{ids:?}"); + assert!(matches!(ids[..], [Usage::TaskBackgrounded { id: started, .. }, Usage::TaskNotified { id: ended, stopped: false }] if started == ended), "{ids:?}"); assert!(usages.iter().position(|usage| matches!(usage, Usage::TaskBackgrounded { .. })) < usages.iter().position(|usage| matches!(usage, Usage::TaskNotified { .. }))); let idle = idleness(BG_AGENT); let labels: Vec<&str> = idle.iter().map(|(label, _)| label.as_str()).collect(); diff --git a/crates/mind-body/src/self_run/tests/conversation.rs b/crates/mind-body/src/self_run/tests/conversation.rs index ed9ed01..4d45060 100644 --- a/crates/mind-body/src/self_run/tests/conversation.rs +++ b/crates/mind-body/src/self_run/tests/conversation.rs @@ -13,6 +13,7 @@ const BG_RACE: &str = include_str!("../claude-2.1.312-live-session-bg-race.jsonl const BG_LATE: &str = include_str!("../claude-2.1.312-live-session-bg-late.jsonl"); const BG_FGTO: &str = include_str!("../claude-2.1.312-live-session-bg-fgto.jsonl"); const BG_KILL: &str = include_str!("../claude-2.1.312-live-session-bg-kill.jsonl"); +const BG_AGENTSTOP: &str = include_str!("../claude-2.1.312-live-session-bg-agentstop.jsonl"); const BG_MONITOR: &str = include_str!("../claude-2.1.312-live-session-bg-monitor.jsonl"); fn saying(text: &str) -> String { @@ -429,6 +430,28 @@ fn a_stop_the_session_did_not_ask_for_owes_its_turn() { assert_eq!((answered(&mind, 1), answered(&mind, 2), answered(&mind, 3)), (vec![id_of("a1")], vec![id_of("a1")], vec![id_of("l1")]), "the CLI's turn answers Aqua's brief, never Libby's"); } +/// A background Agent the session stops with TaskStop is notified inside the turn that stops it, and the CLI still begins a turn for that notice: +/// Libby's brief waits for it, and the turn answers Aqua's. +#[test] +fn an_agent_the_session_stops_with_taskstop_owes_its_turn() { + let lines = stream(BG_AGENTSTOP); + let (request1, result1, init2) = (after(&lines, "request", 1), after(&lines, "result", 1), after(&lines, "init", 2)); + let splices = |mind: &Rc| vec![(request1, vec![briefed(mind, 31, vec![libby("l1")])]), (result1, vec![Idle(31)])]; + let mind = serving_aqua(); + let ran = mind_run(&mind, script(&lines[..init2], splices(&mind))); + assert!(ran.outcome.is_ok()); + assert!(!written_with(&ran, "@libby:chat") && !written_with(&ran, &id_of("l1")), "the CLI's turn for the stopped agent is queued: {:?}", ran.written()); + let mind = serving_aqua(); + let ran = mind_run(&mind, [script(&lines, splices(&mind)), vec![Idle(31), Out(echo()), Out(saying("libby done"))]].concat()); + assert!(ran.outcome.is_ok()); + assert_eq!(tells(&ran).len(), 1, "{:?}", ran.written()); + let results = lines.iter().filter(|line| label_of(line) == "result").count(); + for n in 1..=results { + assert_eq!(answered(&mind, u32::try_from(n).unwrap()), vec![id_of("a1")], "reply {n}: the CLI's turn for Aqua's agent is Aqua's"); + } + assert_eq!(answered(&mind, u32::try_from(results + 1).unwrap()), vec![id_of("l1")]); +} + /// A persistent Monitor stays in the level through several notice turns the CLI begins; Libby's brief waits through all of them and the final turn /// of the notification. #[test]